agentscape3d 1.0.0-beta.1 → 1.0.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (386) hide show
  1. package/README.md +23 -48
  2. package/dist/core.d.ts +68 -0
  3. package/dist/core.js +209 -0
  4. package/dist/core.js.map +1 -0
  5. package/dist/index.d.ts +10 -229
  6. package/dist/index.js +192 -15462
  7. package/dist/index.js.map +1 -1
  8. package/package.json +11 -40
  9. package/cli.mjs +0 -27
  10. package/dist/AssetCompiler-CDFiElji.js +0 -2451
  11. package/dist/AssetCompiler-CDFiElji.js.map +0 -1
  12. package/dist/AssetInputContracts-Dy8iU4eT.js +0 -228
  13. package/dist/AssetInputContracts-Dy8iU4eT.js.map +0 -1
  14. package/dist/AssetRecipe-DmFpzxr-.js +0 -55
  15. package/dist/AssetRecipe-DmFpzxr-.js.map +0 -1
  16. package/dist/BrowserCodeWorker.js +0 -53615
  17. package/dist/KinematicHypothesisScreen-D-z6qgMB.js +0 -242
  18. package/dist/KinematicHypothesisScreen-D-z6qgMB.js.map +0 -1
  19. package/dist/SceneSerializer-DPVOyeRk.js +0 -353
  20. package/dist/SceneSerializer-DPVOyeRk.js.map +0 -1
  21. package/dist/StylePack-DNrdLeGI.js +0 -6314
  22. package/dist/StylePack-DNrdLeGI.js.map +0 -1
  23. package/dist/WorldArchive-pSBIGxLa.js +0 -420
  24. package/dist/WorldArchive-pSBIGxLa.js.map +0 -1
  25. package/dist/WorldIO-wsDfZGM4.js +0 -150
  26. package/dist/WorldIO-wsDfZGM4.js.map +0 -1
  27. package/dist/blankWorld-CBWbwJGj.js +0 -76
  28. package/dist/blankWorld-CBWbwJGj.js.map +0 -1
  29. package/dist/disposeObject3D-BQ9TyVC_.js +0 -54
  30. package/dist/disposeObject3D-BQ9TyVC_.js.map +0 -1
  31. package/dist/environments-DgH66NqV.js +0 -4220
  32. package/dist/environments-DgH66NqV.js.map +0 -1
  33. package/dist/gltfIO-B87nJaat.js +0 -10
  34. package/dist/gltfIO-B87nJaat.js.map +0 -1
  35. package/dist/grandUrbanBlock-Ob9pN-CB.js +0 -516
  36. package/dist/grandUrbanBlock-Ob9pN-CB.js.map +0 -1
  37. package/dist/magicCabin-D64fD1E2.js +0 -11024
  38. package/dist/magicCabin-D64fD1E2.js.map +0 -1
  39. package/dist/mcp.d.ts +0 -2
  40. package/dist/mcp.js +0 -1
  41. package/dist/monumentHall-BKbs0UOQ.js +0 -404
  42. package/dist/monumentHall-BKbs0UOQ.js.map +0 -1
  43. package/dist/node.d.ts +0 -16
  44. package/dist/node.js +0 -25
  45. package/dist/ruinedCourtyard-BoZxHldu.js +0 -697
  46. package/dist/ruinedCourtyard-BoZxHldu.js.map +0 -1
  47. package/dist/runtime/application/AgentTools.js +0 -25
  48. package/dist/runtime/application/README.md +0 -14
  49. package/dist/runtime/application/buildTaskObservation.js +0 -117
  50. package/dist/runtime/application/code-execution/AuthoringSandboxEntry.js +0 -46
  51. package/dist/runtime/application/code-execution/BrowserCodeExecutor.js +0 -35
  52. package/dist/runtime/application/code-execution/BrowserCodeWorker.js +0 -17
  53. package/dist/runtime/application/code-execution/RemoteAuthoringDocument.js +0 -72
  54. package/dist/runtime/application/createSession.js +0 -66
  55. package/dist/runtime/application/createWorldAuthoringContext.js +0 -400
  56. package/dist/runtime/application/generation/GenerationOrchestrator.js +0 -629
  57. package/dist/runtime/application/generation/GenerationRuntime.js +0 -214
  58. package/dist/runtime/application/generation/PromptHybridWorldOrchestrator.js +0 -285
  59. package/dist/runtime/application/native-scene/CodeProject.js +0 -119
  60. package/dist/runtime/application/native-scene/CodeProjectModules.js +0 -128
  61. package/dist/runtime/application/native-scene/NativeEnvironmentGeometry.js +0 -62
  62. package/dist/runtime/application/native-scene/NativeOverlayCheckpoint.js +0 -127
  63. package/dist/runtime/application/native-scene/NativeRenderDiscovery.js +0 -51
  64. package/dist/runtime/application/native-scene/NativeSceneHost.js +0 -164
  65. package/dist/runtime/application/native-scene/NativeSceneOverlay.js +0 -116
  66. package/dist/runtime/application/native-scene/NativeThreeModule.js +0 -16
  67. package/dist/runtime/application/object-forge/SceneObjectForge.js +0 -232
  68. package/dist/runtime/application/programmatic-assets/ProgrammaticAssetBuilder.js +0 -54
  69. package/dist/runtime/application/programmatic-assets/ProgrammaticAssetContract.js +0 -22
  70. package/dist/runtime/application/programmatic-assets/ThreeCodeAsset.js +0 -40
  71. package/dist/runtime/application/scene/CapabilityResolver.js +0 -79
  72. package/dist/runtime/application/scene/RequestWindow.js +0 -54
  73. package/dist/runtime/application/scene/SceneAgentTools.js +0 -21
  74. package/dist/runtime/application/scene/SceneContracts.js +0 -45
  75. package/dist/runtime/application/scene/SceneEditService.js +0 -144
  76. package/dist/runtime/application/scene/SceneFacade.js +0 -267
  77. package/dist/runtime/application/scene/SceneInteractionAdapters.js +0 -40
  78. package/dist/runtime/application/scene/SceneJobController.js +0 -229
  79. package/dist/runtime/application/scene/ScenePackage.js +0 -162
  80. package/dist/runtime/application/scene/ScenePersistence.js +0 -50
  81. package/dist/runtime/application/scene/SceneProject.js +0 -95
  82. package/dist/runtime/application/scene/SceneSkillNames.js +0 -5
  83. package/dist/runtime/application/scene/StarterScene.js +0 -56
  84. package/dist/runtime/application/scene/WorldArchive.js +0 -87
  85. package/dist/runtime/application/scene/WorldDirectory.js +0 -20
  86. package/dist/runtime/application/scene/WorldDocument.js +0 -74
  87. package/dist/runtime/application/scene/WorldIO.js +0 -103
  88. package/dist/runtime/application/scene/WorldStorage.js +0 -137
  89. package/dist/runtime/application/skills/SkillRegistry.js +0 -163
  90. package/dist/runtime/application/skills/packs/acceptanceSkills.js +0 -32
  91. package/dist/runtime/application/skills/packs/affordanceSkills.js +0 -36
  92. package/dist/runtime/application/skills/packs/assetSkills.js +0 -46
  93. package/dist/runtime/application/skills/packs/authoringSkills.js +0 -16
  94. package/dist/runtime/application/skills/packs/batchSkills.js +0 -22
  95. package/dist/runtime/application/skills/packs/codeSkills.js +0 -106
  96. package/dist/runtime/application/skills/packs/generationSkills.js +0 -45
  97. package/dist/runtime/application/skills/packs/interactionSkills.js +0 -46
  98. package/dist/runtime/application/skills/packs/recoverySkills.js +0 -80
  99. package/dist/runtime/application/skills/packs/sceneSkills.js +0 -24
  100. package/dist/runtime/application/skills/packs/spatialSkills.js +0 -35
  101. package/dist/runtime/application/skills/packs/verificationSkills.js +0 -14
  102. package/dist/runtime/application/skills/packs/worldSkills.js +0 -45
  103. package/dist/runtime/application/skills/registerCoreSkills.js +0 -31
  104. package/dist/runtime/application/skills/skillPrimitives.js +0 -4
  105. package/dist/runtime/application/tasks/CabinetCupTask.js +0 -76
  106. package/dist/runtime/application/tasks.jsonl +0 -67
  107. package/dist/runtime/application/world-authoring/AuthoringAssetProducer.js +0 -42
  108. package/dist/runtime/application/world-authoring/AuthoringDiff.js +0 -149
  109. package/dist/runtime/application/world-authoring/AuthoringDocument.js +0 -825
  110. package/dist/runtime/application/world-authoring/AuthoringExecutionHost.js +0 -109
  111. package/dist/runtime/application/world-authoring/AuthoringIdentity.js +0 -17
  112. package/dist/runtime/application/world-authoring/AuthoringModelResolver.js +0 -29
  113. package/dist/runtime/application/world-authoring/AuthoringPatch.js +0 -118
  114. package/dist/runtime/application/world-authoring/AuthoringPromotionController.js +0 -334
  115. package/dist/runtime/application/world-authoring/AuthoringPromotionSource.js +0 -126
  116. package/dist/runtime/application/world-authoring/AuthoringRevisionHistory.js +0 -144
  117. package/dist/runtime/application/world-authoring/HeadlessImageExport.js +0 -174
  118. package/dist/runtime/application/world-authoring/ModelRef.js +0 -62
  119. package/dist/runtime/apps/mcp-server/AUTHORING.md +0 -71
  120. package/dist/runtime/apps/mcp-server/AuthoringSandboxEntry.js +0 -1
  121. package/dist/runtime/apps/mcp-server/AuthoringSandboxWorker.mjs +0 -30
  122. package/dist/runtime/apps/mcp-server/BuildEnvironment.js +0 -17
  123. package/dist/runtime/apps/mcp-server/CodeExecutor.js +0 -71
  124. package/dist/runtime/apps/mcp-server/DEPLOYMENT-PC2.md +0 -42
  125. package/dist/runtime/apps/mcp-server/DockerBuildRunner.js +0 -66
  126. package/dist/runtime/apps/mcp-server/FileAssetRepository.js +0 -159
  127. package/dist/runtime/apps/mcp-server/HeadlessAssetIO.js +0 -8
  128. package/dist/runtime/apps/mcp-server/HeadlessGLTFLoader.js +0 -47
  129. package/dist/runtime/apps/mcp-server/HeadlessWorldHost.js +0 -132
  130. package/dist/runtime/apps/mcp-server/IsolatedAuthoringExecutor.js +0 -6
  131. package/dist/runtime/apps/mcp-server/PROGRAMMATIC-ASSETS.md +0 -116
  132. package/dist/runtime/apps/mcp-server/ProgrammaticAssets.js +0 -60
  133. package/dist/runtime/apps/mcp-server/README.md +0 -150
  134. package/dist/runtime/apps/mcp-server/RemoteAuthoringDocument.js +0 -1
  135. package/dist/runtime/apps/mcp-server/SandboxBundle.js +0 -13
  136. package/dist/runtime/apps/mcp-server/SessionManager.js +0 -80
  137. package/dist/runtime/apps/mcp-server/StudioBridgeHttp.js +0 -58
  138. package/dist/runtime/apps/mcp-server/StudioLiveBridge.js +0 -190
  139. package/dist/runtime/apps/mcp-server/TrustedAuthoringWorker.mjs +0 -16
  140. package/dist/runtime/apps/mcp-server/VALIDATION.md +0 -45
  141. package/dist/runtime/apps/mcp-server/acceptance-evidence.json +0 -332
  142. package/dist/runtime/apps/mcp-server/errorDiagnostics.js +0 -32
  143. package/dist/runtime/apps/mcp-server/examples/code-house.js +0 -24
  144. package/dist/runtime/apps/mcp-server/examples/procedural-assets.js +0 -37
  145. package/dist/runtime/apps/mcp-server/main.mjs +0 -56
  146. package/dist/runtime/apps/mcp-server/registerTools.js +0 -215
  147. package/dist/runtime/apps/mcp-server/sandbox/run.mjs +0 -23
  148. package/dist/runtime/apps/mcp-server/security.js +0 -21
  149. package/dist/runtime/apps/mcp-server/tasks.jsonl +0 -9
  150. package/dist/runtime/apps/server/CapabilityAdapterRegistry.js +0 -157
  151. package/dist/runtime/apps/server/README.md +0 -7
  152. package/dist/runtime/apps/server/WorldDiskStorage.js +0 -51
  153. package/dist/runtime/apps/server/openai-compatible-agent-gateway.mjs +0 -278
  154. package/dist/runtime/apps/server/tasks.jsonl +0 -10
  155. package/dist/runtime/foundation/EventBus.js +0 -18
  156. package/dist/runtime/foundation/JsonGateway.js +0 -47
  157. package/dist/runtime/foundation/PolicyEngine.js +0 -21
  158. package/dist/runtime/foundation/README.md +0 -7
  159. package/dist/runtime/foundation/TraceRecorder.js +0 -76
  160. package/dist/runtime/foundation/errors.js +0 -8
  161. package/dist/runtime/foundation/simulation/SimulationProfile.js +0 -143
  162. package/dist/runtime/foundation/version.js +0 -2
  163. package/dist/runtime/modules/agent/README.md +0 -11
  164. package/dist/runtime/modules/agent/ToolCallingAgent.js +0 -19
  165. package/dist/runtime/modules/agent/bootstrapWorld.js +0 -10
  166. package/dist/runtime/modules/agent/buildRecoveryProposals.js +0 -533
  167. package/dist/runtime/modules/agent/execution/AgentExecutionRules.js +0 -127
  168. package/dist/runtime/modules/agent/execution/AgentRunResults.js +0 -55
  169. package/dist/runtime/modules/agent/execution/AgentRunSession.js +0 -390
  170. package/dist/runtime/modules/agent/execution/AgentToolInvoker.js +0 -39
  171. package/dist/runtime/modules/agent/gateway/HttpLLMGateway.js +0 -19
  172. package/dist/runtime/modules/agent/prompt/index.js +0 -46
  173. package/dist/runtime/modules/agent/tasks.jsonl +0 -94
  174. package/dist/runtime/modules/artifact/ArtifactContentGate.js +0 -144
  175. package/dist/runtime/modules/artifact/ArtifactDescriptor.js +0 -280
  176. package/dist/runtime/modules/artifact/ArtifactImporter.js +0 -185
  177. package/dist/runtime/modules/artifact/ArtifactModule.js +0 -111
  178. package/dist/runtime/modules/artifact/ArtifactRegistry.js +0 -197
  179. package/dist/runtime/modules/artifact/IncrementalSha256.js +0 -129
  180. package/dist/runtime/modules/artifact/MemoryArtifactByteStore.js +0 -115
  181. package/dist/runtime/modules/artifact/README.md +0 -7
  182. package/dist/runtime/modules/artifact/storage/IndexedDbArtifactStore.js +0 -67
  183. package/dist/runtime/modules/artifact/tasks.jsonl +0 -31
  184. package/dist/runtime/modules/asset/AssetModule.js +0 -399
  185. package/dist/runtime/modules/asset/README.md +0 -54
  186. package/dist/runtime/modules/asset/loading/AssetLoader.js +0 -157
  187. package/dist/runtime/modules/asset/loading/GltfAssetLoader.js +0 -61
  188. package/dist/runtime/modules/asset/loading/builtins/BuiltinAssets.js +0 -95
  189. package/dist/runtime/modules/asset/loading/builtins/HouseDoor.js +0 -33
  190. package/dist/runtime/modules/asset/loading/builtins/IndustrialCabinet.js +0 -103
  191. package/dist/runtime/modules/asset/model/AssetInputContracts.js +0 -95
  192. package/dist/runtime/modules/asset/model/AssetRef.js +0 -12
  193. package/dist/runtime/modules/asset/model/MechanicalAssetDraft.js +0 -172
  194. package/dist/runtime/modules/asset/model/admission.js +0 -117
  195. package/dist/runtime/modules/asset/model/errors.js +0 -6
  196. package/dist/runtime/modules/asset/model/parts.js +0 -27
  197. package/dist/runtime/modules/asset/model/resourceBudget.js +0 -10
  198. package/dist/runtime/modules/asset/model/schema.js +0 -150
  199. package/dist/runtime/modules/asset/persistence/AssetManifestStore.js +0 -78
  200. package/dist/runtime/modules/asset/persistence/CompiledAssetStore.js +0 -84
  201. package/dist/runtime/modules/asset/persistence/LocalAssetLibrary.js +0 -86
  202. package/dist/runtime/modules/asset/persistence/LocalAssetLibraryStore.js +0 -81
  203. package/dist/runtime/modules/asset/production/AssetProductionPipeline.js +0 -272
  204. package/dist/runtime/modules/asset/production/AssetRecipe.js +0 -32
  205. package/dist/runtime/modules/asset/production/adapters/EmbodiedGenAdapter.js +0 -45
  206. package/dist/runtime/modules/asset/production/adapters/EmbodiedGenBundleAdapter.js +0 -590
  207. package/dist/runtime/modules/asset/production/compiler/AssetCompiler.js +0 -173
  208. package/dist/runtime/modules/asset/production/compiler/evidence/AnimationMotionEvidence.js +0 -124
  209. package/dist/runtime/modules/asset/production/compiler/evidence/StaticPanelEvidence.js +0 -56
  210. package/dist/runtime/modules/asset/production/compiler/gltfIO.js +0 -6
  211. package/dist/runtime/modules/asset/production/compiler/partGeometry.js +0 -74
  212. package/dist/runtime/modules/asset/production/compiler/passes/ArticulatedCollisionPass.js +0 -63
  213. package/dist/runtime/modules/asset/production/compiler/passes/ArticulationCandidatePass.js +0 -48
  214. package/dist/runtime/modules/asset/production/compiler/passes/AuthoringIntentPass.js +0 -16
  215. package/dist/runtime/modules/asset/production/compiler/passes/ColliderFallbackPass.js +0 -30
  216. package/dist/runtime/modules/asset/production/compiler/passes/CompileQualityPass.js +0 -75
  217. package/dist/runtime/modules/asset/production/compiler/passes/ExplicitDefinitionPass.js +0 -20
  218. package/dist/runtime/modules/asset/production/compiler/passes/GLTFInspectPass.js +0 -34
  219. package/dist/runtime/modules/asset/production/compiler/passes/GeometryPass.js +0 -32
  220. package/dist/runtime/modules/asset/production/compiler/passes/JointFramePass.js +0 -116
  221. package/dist/runtime/modules/asset/production/compiler/passes/KinematicEvidencePass.js +0 -84
  222. package/dist/runtime/modules/asset/production/compiler/passes/ManifestPass.js +0 -63
  223. package/dist/runtime/modules/asset/production/compiler/passes/NormalizeTransformPass.js +0 -16
  224. package/dist/runtime/modules/asset/production/compiler/passes/OptimizeGLBPass.js +0 -23
  225. package/dist/runtime/modules/asset/production/compiler/passes/PartColliderPass.js +0 -50
  226. package/dist/runtime/modules/asset/production/compiler/passes/PartGeometryEnrichmentPass.js +0 -60
  227. package/dist/runtime/modules/asset/production/compiler/passes/PartProposalPass.js +0 -93
  228. package/dist/runtime/modules/asset/production/compiler/passes/RemoteEnrichmentPass.js +0 -32
  229. package/dist/runtime/modules/asset/production/compiler/passes/ResourceBudgetPass.js +0 -55
  230. package/dist/runtime/modules/asset/production/compiler/passes/SegmentMaterializePass.js +0 -203
  231. package/dist/runtime/modules/asset/production/compiler/passes/SegmentationEvidencePass.js +0 -43
  232. package/dist/runtime/modules/asset/production/compiler/passes/SemanticHeuristicPass.js +0 -33
  233. package/dist/runtime/modules/asset/production/compiler/passes/StructurePass.js +0 -60
  234. package/dist/runtime/modules/asset/production/compiler/providers/HttpCompilerProvider.js +0 -23
  235. package/dist/runtime/modules/asset/production/verification/KinematicHypothesisScreen.js +0 -198
  236. package/dist/runtime/modules/asset/registry/AssetCatalog.js +0 -72
  237. package/dist/runtime/modules/asset/registry/AssetRegistry.js +0 -51
  238. package/dist/runtime/modules/asset/registry/manifests/index.js +0 -173
  239. package/dist/runtime/modules/asset/tasks.jsonl +0 -87
  240. package/dist/runtime/modules/generation/README.md +0 -9
  241. package/dist/runtime/modules/generation/connector/ConnectorArtifactClient.js +0 -45
  242. package/dist/runtime/modules/generation/connector/ConnectorCapabilityAdapter.js +0 -169
  243. package/dist/runtime/modules/generation/connector/ConnectorClient.js +0 -192
  244. package/dist/runtime/modules/generation/connector/ConnectorJobClient.js +0 -167
  245. package/dist/runtime/modules/generation/connector/ConnectorJobEventClient.js +0 -179
  246. package/dist/runtime/modules/generation/connector/ConnectorSession.js +0 -202
  247. package/dist/runtime/modules/generation/jobs/GenerationJobProjection.js +0 -239
  248. package/dist/runtime/modules/generation/jobs/GenerationJobReconciler.js +0 -99
  249. package/dist/runtime/modules/generation/jobs/GenerationJobStore.js +0 -91
  250. package/dist/runtime/modules/generation/jobs/GenerationJobTransportOverlay.js +0 -50
  251. package/dist/runtime/modules/generation/providers/ProviderRegistry.js +0 -304
  252. package/dist/runtime/modules/generation/tasks.jsonl +0 -35
  253. package/dist/runtime/modules/navigation/NavigationBackend.js +0 -17
  254. package/dist/runtime/modules/navigation/RecastNavigationBackend.js +0 -245
  255. package/dist/runtime/modules/physics/JoltPhysicsBackend.js +0 -850
  256. package/dist/runtime/modules/physics/PhysicsApiSurface.js +0 -651
  257. package/dist/runtime/modules/physics/PhysicsBackend.js +0 -88
  258. package/dist/runtime/modules/physics/RapierPhysicsBackend.js +0 -410
  259. package/dist/runtime/modules/rendering/README.md +0 -7
  260. package/dist/runtime/modules/rendering/RendererProbe.js +0 -153
  261. package/dist/runtime/modules/rendering/WebGpuPostFxPipeline.js +0 -140
  262. package/dist/runtime/modules/rendering/createRenderer.js +0 -76
  263. package/dist/runtime/modules/rendering/disposeObject3D.js +0 -34
  264. package/dist/runtime/modules/rendering/loadGaussianSplatVisual.js +0 -74
  265. package/dist/runtime/modules/rendering/style/StylePack.js +0 -34
  266. package/dist/runtime/modules/rendering/style/StyleSystem.js +0 -173
  267. package/dist/runtime/modules/rendering/tasks.jsonl +0 -7
  268. package/dist/runtime/modules/world/README.md +0 -13
  269. package/dist/runtime/modules/world/build/WorldBuilder.js +0 -170
  270. package/dist/runtime/modules/world/compiler/PipelineEngine.js +0 -32
  271. package/dist/runtime/modules/world/compiler/WorldAdmission.js +0 -43
  272. package/dist/runtime/modules/world/compiler/WorldBehaviorCompiler.js +0 -68
  273. package/dist/runtime/modules/world/compiler/WorldCompilation.js +0 -157
  274. package/dist/runtime/modules/world/compiler/WorldComposer.js +0 -201
  275. package/dist/runtime/modules/world/compiler/WorldPhysicsAdmission.js +0 -76
  276. package/dist/runtime/modules/world/compiler/WorldRecompiler.js +0 -356
  277. package/dist/runtime/modules/world/compiler/WorldRetry.js +0 -75
  278. package/dist/runtime/modules/world/compiler/createWorldPipeline.js +0 -379
  279. package/dist/runtime/modules/world/content/blankWorld.js +0 -35
  280. package/dist/runtime/modules/world/content/environments.js +0 -84
  281. package/dist/runtime/modules/world/content/grandUrbanBlock.js +0 -189
  282. package/dist/runtime/modules/world/content/magic-cabin/README.md +0 -28
  283. package/dist/runtime/modules/world/content/magic-cabin/affordances.js +0 -64
  284. package/dist/runtime/modules/world/content/magic-cabin/cabinContents.js +0 -7078
  285. package/dist/runtime/modules/world/content/magic-cabin/lighting.js +0 -26
  286. package/dist/runtime/modules/world/content/magic-cabin/materials.js +0 -20
  287. package/dist/runtime/modules/world/content/magicCabin.js +0 -190
  288. package/dist/runtime/modules/world/content/monumentHall.js +0 -154
  289. package/dist/runtime/modules/world/content/ruinedCourtyard.js +0 -196
  290. package/dist/runtime/modules/world/content/suzhouGarden/README.md +0 -141
  291. package/dist/runtime/modules/world/content/suzhouGarden/index.js +0 -137
  292. package/dist/runtime/modules/world/content/suzhouGarden/src/arch.js +0 -491
  293. package/dist/runtime/modules/world/content/suzhouGarden/src/buildings.js +0 -670
  294. package/dist/runtime/modules/world/content/suzhouGarden/src/core.js +0 -578
  295. package/dist/runtime/modules/world/content/suzhouGarden/src/lod.js +0 -127
  296. package/dist/runtime/modules/world/content/suzhouGarden/src/main.js +0 -642
  297. package/dist/runtime/modules/world/content/suzhouGarden/src/nature.js +0 -650
  298. package/dist/runtime/modules/world/content/suzhouGarden/src/rockery.js +0 -280
  299. package/dist/runtime/modules/world/content/suzhouGarden/src/sky.js +0 -242
  300. package/dist/runtime/modules/world/content/suzhouGarden/src/water.js +0 -215
  301. package/dist/runtime/modules/world/content/woodlandWorkshop.js +0 -192
  302. package/dist/runtime/modules/world/content/yuanmingyuan/README.md +0 -36
  303. package/dist/runtime/modules/world/content/yuanmingyuan/arch.js +0 -351
  304. package/dist/runtime/modules/world/content/yuanmingyuan/buildings.js +0 -490
  305. package/dist/runtime/modules/world/content/yuanmingyuan/core.js +0 -505
  306. package/dist/runtime/modules/world/content/yuanmingyuan/index.js +0 -101
  307. package/dist/runtime/modules/world/content/yuanmingyuan/nature.js +0 -435
  308. package/dist/runtime/modules/world/content/yuanmingyuan/sky.js +0 -169
  309. package/dist/runtime/modules/world/content/yuanmingyuan/water.js +0 -245
  310. package/dist/runtime/modules/world/errors.js +0 -9
  311. package/dist/runtime/modules/world/generated/GeneratedWorldCoordinates.js +0 -50
  312. package/dist/runtime/modules/world/generated/GeneratedWorldLoader.js +0 -297
  313. package/dist/runtime/modules/world/runtime/CommandHistory.js +0 -80
  314. package/dist/runtime/modules/world/runtime/ObjectStore.js +0 -31
  315. package/dist/runtime/modules/world/runtime/ObjectTransform.js +0 -62
  316. package/dist/runtime/modules/world/runtime/ObservedEntity.js +0 -37
  317. package/dist/runtime/modules/world/runtime/ProjectCapabilities.js +0 -207
  318. package/dist/runtime/modules/world/runtime/SceneSerializer.js +0 -246
  319. package/dist/runtime/modules/world/runtime/WorldAuthority.js +0 -41
  320. package/dist/runtime/modules/world/runtime/WorldCollisionSignature.js +0 -14
  321. package/dist/runtime/modules/world/runtime/WorldCommands.js +0 -502
  322. package/dist/runtime/modules/world/runtime/WorldObservation.js +0 -71
  323. package/dist/runtime/modules/world/runtime/WorldQueries.js +0 -340
  324. package/dist/runtime/modules/world/runtime/WorldRecovery.js +0 -78
  325. package/dist/runtime/modules/world/runtime/WorldRuntime.js +0 -649
  326. package/dist/runtime/modules/world/runtime/affordance/ObjectAffordances.js +0 -107
  327. package/dist/runtime/modules/world/runtime/affordance/WorldAffordances.js +0 -130
  328. package/dist/runtime/modules/world/runtime/behavior/BehaviorCompiler.js +0 -79
  329. package/dist/runtime/modules/world/runtime/behavior/ProjectStateMachine.js +0 -195
  330. package/dist/runtime/modules/world/runtime/behavior/RuleGraph.js +0 -70
  331. package/dist/runtime/modules/world/runtime/behavior/RuleRuntime.js +0 -115
  332. package/dist/runtime/modules/world/runtime/graph/SceneGraph.js +0 -216
  333. package/dist/runtime/modules/world/runtime/interaction/ArticulationRuntime.js +0 -214
  334. package/dist/runtime/modules/world/runtime/interaction/CarryCapability.js +0 -65
  335. package/dist/runtime/modules/world/runtime/interaction/CarryRuntime.js +0 -222
  336. package/dist/runtime/modules/world/runtime/interaction/InteractionApproach.js +0 -130
  337. package/dist/runtime/modules/world/runtime/interaction/InteractionContract.js +0 -57
  338. package/dist/runtime/modules/world/runtime/interaction/RecoveryRuntime.js +0 -123
  339. package/dist/runtime/modules/world/runtime/interaction/SettleRuntime.js +0 -120
  340. package/dist/runtime/modules/world/runtime/semantic/SemanticWorldView.js +0 -102
  341. package/dist/runtime/modules/world/runtime/simulation/SimulationClock.js +0 -89
  342. package/dist/runtime/modules/world/runtime/simulation/SimulationSession.js +0 -99
  343. package/dist/runtime/modules/world/runtime/simulation/ThermalSystem.js +0 -269
  344. package/dist/runtime/modules/world/runtime/spatial/SpatialSnapshot.js +0 -56
  345. package/dist/runtime/modules/world/runtime/spatial/ThreeBvhRuntime.js +0 -36
  346. package/dist/runtime/modules/world/runtime/systems/InteractionSystem.js +0 -728
  347. package/dist/runtime/modules/world/runtime/systems/LocomotionSystem.js +0 -269
  348. package/dist/runtime/modules/world/runtime/systems/NavigationSystem.js +0 -469
  349. package/dist/runtime/modules/world/runtime/systems/PhysicsSystem.js +0 -1657
  350. package/dist/runtime/modules/world/runtime/systems/RenderingSystem.js +0 -457
  351. package/dist/runtime/modules/world/runtime/systems/SpatialSystem.js +0 -284
  352. package/dist/runtime/modules/world/spec/WorldIR.js +0 -165
  353. package/dist/runtime/modules/world/spec/WorldIRToolSchema.js +0 -86
  354. package/dist/runtime/modules/world/spec/WorldPlannerProposal.js +0 -51
  355. package/dist/runtime/modules/world/spec/WorldRevision.js +0 -231
  356. package/dist/runtime/modules/world/spec/WorldSpec.js +0 -86
  357. package/dist/runtime/modules/world/tasks.jsonl +0 -530
  358. package/dist/runtime/modules/world/verification/ArticulationVerifier.js +0 -254
  359. package/dist/runtime/modules/world/verification/Finding.js +0 -105
  360. package/dist/runtime/modules/world/verification/InteractionEvidence.js +0 -69
  361. package/dist/runtime/modules/world/verification/RepairEngine.js +0 -49
  362. package/dist/runtime/modules/world/verification/WorldAcceptance.js +0 -158
  363. package/dist/runtime/modules/world/verification/WorldValidator.js +0 -65
  364. package/dist/runtime/package-lock.json +0 -6245
  365. package/dist/runtime/package.json +0 -91
  366. package/dist/runtime/public/assets/cabinet.glb +0 -0
  367. package/dist/runtime/public/assets/grand-urban-block/clean_asphalt_diff_1k.jpg +0 -0
  368. package/dist/runtime/public/assets/grand-urban-block/clean_asphalt_nor_gl_1k.jpg +0 -0
  369. package/dist/runtime/public/assets/grand-urban-block/concrete_pavement_diff_1k.jpg +0 -0
  370. package/dist/runtime/public/assets/grand-urban-block/urban_street_01_1k.hdr +0 -0
  371. package/dist/runtime/public/assets/monument-hall/marble_diff_1k.jpg +0 -0
  372. package/dist/runtime/public/assets/monument-hall/marble_nor_gl_1k.jpg +0 -0
  373. package/dist/runtime/public/assets/monument-hall/marble_rough_1k.jpg +0 -0
  374. package/dist/runtime/public/assets/monument-hall/solitude_interior_1k.hdr +0 -0
  375. package/dist/runtime/public/assets/ruined-courtyard/courtyard_1k.hdr +0 -0
  376. package/dist/runtime/public/assets/ruined-courtyard/mossy_cobblestone_diff_1k.jpg +0 -0
  377. package/dist/runtime/public/assets/ruined-courtyard/mossy_cobblestone_nor_gl_1k.jpg +0 -0
  378. package/dist/runtime/public/assets/ruined-courtyard/mossy_sandstone_diff_1k.jpg +0 -0
  379. package/dist/schema-Dudvovhu.js +0 -364
  380. package/dist/schema-Dudvovhu.js.map +0 -1
  381. package/dist/suzhouGarden-BCx_JeV5.js +0 -6159
  382. package/dist/suzhouGarden-BCx_JeV5.js.map +0 -1
  383. package/dist/woodlandWorkshop-BGNWPNdK.js +0 -484
  384. package/dist/woodlandWorkshop-BGNWPNdK.js.map +0 -1
  385. package/dist/yuanmingyuan-DAIb1msO.js +0 -4962
  386. package/dist/yuanmingyuan-DAIb1msO.js.map +0 -1
@@ -1,1657 +0,0 @@
1
- import * as THREE from 'three';
2
- import { orderParts, ROOT_PART } from '../../../asset/model/parts.js';
3
-
4
- const array3 = (v) => [v.x, v.y, v.z];
5
- const upright = (q) => {
6
- const upX = 2 * (q.x * q.y - q.z * q.w);
7
- const upY = 1 - 2 * (q.x * q.x + q.z * q.z);
8
- const upZ = 2 * (q.y * q.z + q.x * q.w);
9
- return upY > 0.999 && Math.abs(upX) < 0.02 && Math.abs(upZ) < 0.02;
10
- };
11
- const yaw = (q) => Math.atan2(2 * (q.w * q.y + q.x * q.z), 1 - 2 * (q.y * q.y + q.z * q.z));
12
- const boxAabbHalfExtents = (half, q) => {
13
- const xx = 1 - 2 * (q.y * q.y + q.z * q.z), xy = 2 * (q.x * q.y - q.z * q.w), xz = 2 * (q.x * q.z + q.y * q.w);
14
- const yx = 2 * (q.x * q.y + q.z * q.w), yy = 1 - 2 * (q.x * q.x + q.z * q.z), yz = 2 * (q.y * q.z - q.x * q.w);
15
- const zx = 2 * (q.x * q.z - q.y * q.w), zy = 2 * (q.y * q.z + q.x * q.w), zz = 1 - 2 * (q.x * q.x + q.y * q.y);
16
- return [
17
- Math.abs(xx) * half.x + Math.abs(xy) * half.y + Math.abs(xz) * half.z,
18
- Math.abs(yx) * half.x + Math.abs(yy) * half.y + Math.abs(yz) * half.z,
19
- Math.abs(zx) * half.x + Math.abs(zy) * half.y + Math.abs(zz) * half.z
20
- ];
21
- };
22
- const cylinderAabbHalfExtents = (radius, halfHeight, q) => {
23
- const axis = [2 * (q.x * q.y - q.z * q.w), 1 - 2 * (q.x * q.x + q.z * q.z), 2 * (q.y * q.z + q.x * q.w)];
24
- return axis.map((component) => radius * Math.sqrt(Math.max(0, 1 - component * component)) + halfHeight * Math.abs(component));
25
- };
26
- const capsuleAabbHalfExtents = (radius, halfHeight, q) => {
27
- const axis = [2 * (q.x * q.y - q.z * q.w), 1 - 2 * (q.x * q.x + q.z * q.z), 2 * (q.y * q.z + q.x * q.w)];
28
- return axis.map((component) => radius + halfHeight * Math.abs(component));
29
- };
30
- const convexAabb = (vertices, position, rotation) => {
31
- const q = new THREE.Quaternion(rotation.x, rotation.y, rotation.z, rotation.w);
32
- const v = new THREE.Vector3();
33
- const min = new THREE.Vector3(Infinity, Infinity, Infinity);
34
- const max = new THREE.Vector3(-Infinity, -Infinity, -Infinity);
35
- for (let i = 0; i < vertices.length; i += 3) {
36
- v.set(vertices[i], vertices[i + 1], vertices[i + 2]).applyQuaternion(q).add(position);
37
- min.min(v); max.max(v);
38
- }
39
- return { position:min.clone().add(max).multiplyScalar(0.5).toArray(), halfExtents:max.clone().sub(min).multiplyScalar(0.5).toArray() };
40
- };
41
-
42
- export class PhysicsSystem {
43
- constructor({ backend } = {}) {
44
- if (!backend) throw new TypeError('PhysicsSystem requires a physics backend');
45
- this.backend = backend;
46
- this.solverEnabled = backend.hasCapability?.('rigid-body') === true;
47
- this.world = null;
48
- this.entries = new Map();
49
- this.colliderProvenance = new Map();
50
- this.colliderHandles = new Map();
51
- this.colliderRuntime = new Map();
52
- this.collisionPairs = new Map();
53
- this.collisionEvents = [];
54
- this.collisionGroupBits = new Map();
55
- this.rootRotation = new THREE.Quaternion();
56
- this.inverseRootRotation = new THREE.Quaternion();
57
- this.partWorldRotation = new THREE.Quaternion();
58
- this.partLocalRotation = new THREE.Quaternion();
59
- this.rootWorldPosition = new THREE.Vector3();
60
- this.partWorldPosition = new THREE.Vector3();
61
- this.partLocalPosition = new THREE.Vector3();
62
- this.characterController = null;
63
- this.parentWorldPosition = new THREE.Vector3();
64
- this.parentWorldRotation = new THREE.Quaternion();
65
- this.inverseParentWorldRotation = new THREE.Quaternion();
66
- }
67
-
68
- async init(characterControllerOptions = null) {
69
- await this.backend.init();
70
- this.world = this.backend.createWorld();
71
- this.characterControllerOptions = characterControllerOptions || this.characterControllerOptions || null;
72
- if (!this.solverEnabled || !this.backend.hasCapability('character-controller')) return this;
73
- this.characterController=this.backend.createCharacterController(this.world, this.characterControllerOptions || undefined);
74
- return this;
75
- }
76
-
77
- setCharacterControllerOptions(options = null) {
78
- this.characterControllerOptions = options && typeof options === 'object' ? options : null;
79
- if (!this.world || !this.solverEnabled || !this.backend.hasCapability?.('character-controller')) return this;
80
- if (this.characterController && this.backend.removeCharacterController) {
81
- try { this.backend.removeCharacterController(this.world, this.characterController); } catch {}
82
- }
83
- this.characterController = this.backend.createCharacterController(this.world, this.characterControllerOptions || undefined);
84
- return this;
85
- }
86
-
87
- resetWorld() {
88
- const previousWorld=this.world;
89
- const previousController=this.characterController;
90
- this.entries.clear();
91
- this.colliderProvenance.clear();
92
- this.colliderHandles.clear();
93
- this.colliderRuntime.clear();
94
- this.collisionPairs.clear();
95
- this.collisionEvents.length=0;
96
- this.collisionGroupBits.clear();
97
- this.characterController=null;
98
- if(previousWorld && previousController) this.backend.removeCharacterController(previousWorld,previousController);
99
- if(previousWorld) this.backend.dispose(previousWorld);
100
- this.world=this.backend.createWorld();
101
- if(this.solverEnabled && this.backend.hasCapability('character-controller')) {
102
- // Preserve environment KCC options (e.g. cabin autostep); otherwise restore/reset
103
- // silently reverts to backend defaults and stairs become unwalkable.
104
- this.characterController=this.backend.createCharacterController(this.world, this.characterControllerOptions || undefined);
105
- }
106
- return this;
107
- }
108
-
109
- runtimeCapabilities() {
110
- const capabilities=['transform-state','articulation-pose'];
111
- if (this.backend.hasCapability('collision') && this.backend.hasCapability('scene-query')) capabilities.push('counterfactual-query','collision-events');
112
- return capabilities;
113
- }
114
-
115
- hasCapability(capability) {
116
- return this.backend.hasCapability(capability) || this.runtimeCapabilities().includes(capability);
117
- }
118
- runtimeExecutionModes() { return ['render-only']; }
119
- supportsExecutionMode(mode) {
120
- return this.backend.supportsExecutionMode(mode) || this.runtimeExecutionModes().includes(mode);
121
- }
122
- profile() {
123
- const backendCapabilities=[...this.backend.capabilities];
124
- const runtimeCapabilities=this.runtimeCapabilities();
125
- const backendExecutionModes=[...this.backend.executionModes];
126
- const runtimeExecutionModes=this.runtimeExecutionModes();
127
- return {
128
- identity:this.backend.identity,
129
- backendCapabilities,
130
- runtimeCapabilities,
131
- capabilities:[...new Set([...backendCapabilities,...runtimeCapabilities])],
132
- backendExecutionModes,
133
- runtimeExecutionModes,
134
- executionModes:[...new Set([...backendExecutionModes,...runtimeExecutionModes])],
135
- qualities:{...this.backend.qualities},
136
- solverEnabled:this.solverEnabled
137
- };
138
- }
139
-
140
- debugSnapshot({ nativeGeometry=true, contacts=true } = {}) {
141
- const bodies=[];
142
- const colliders=[];
143
- const joints=[];
144
- const contactPairs=[];
145
- const colliderRefs=[];
146
- const pushBody=(objectId,partName,body)=>{
147
- if(!body) return;
148
- const pose=this.backend.bodyPose(body);
149
- const motion=this.backend.bodyMotion(body);
150
- bodies.push({
151
- objectId,partName,
152
- bodyType:this.backend.bodyType(body),
153
- position:pose?.position ? [...pose.position] : null,
154
- rotation:pose?.rotation ? [...pose.rotation] : null,
155
- sleeping:motion?.sleeping ?? null,
156
- linearVelocity:motion?.linearVelocity ? [...motion.linearVelocity] : null,
157
- angularVelocity:motion?.angularVelocity ? [...motion.angularVelocity] : null,
158
- linearSpeed:Number.isFinite(motion?.linearSpeed) ? motion.linearSpeed : null,
159
- angularSpeed:Number.isFinite(motion?.angularSpeed) ? motion.angularSpeed : null
160
- });
161
- for(const [colliderIndex,collider] of this.backend.colliders(body).entries()) {
162
- const snapshot=this.backend.colliderSnapshot(collider);
163
- if(!snapshot) continue;
164
- const record={
165
- objectId,partName,colliderIndex,
166
- position:[snapshot.position.x,snapshot.position.y,snapshot.position.z],
167
- rotation:[snapshot.rotation.x,snapshot.rotation.y,snapshot.rotation.z,snapshot.rotation.w],
168
- shape:structuredClone(snapshot.shape),
169
- provenance:this.provenanceOfCollider(collider)
170
- };
171
- colliders.push(record);
172
- colliderRefs.push({key:this.backend.colliderKey(collider),collider,record});
173
- }
174
- };
175
- for(const [objectId,entry] of this.entries) {
176
- pushBody(objectId,ROOT_PART,entry.body);
177
- for(const [partName,part] of entry.parts) {
178
- pushBody(objectId,partName,part.body);
179
- if(part.joint) {
180
- const articulation=this.getArticulationState(objectId,partName);
181
- const pose=this.backend.bodyPose(part.body);
182
- const localAxis=part.spec?.joint?.axis ? [...part.spec.joint.axis] : null;
183
- const localAnchor=part.spec?.joint?.childAnchor ? [...part.spec.joint.childAnchor] : [0,0,0];
184
- let worldAxis=null,worldAnchor=null;
185
- if(pose?.position && pose?.rotation) {
186
- const rotation=new THREE.Quaternion(...pose.rotation);
187
- worldAnchor=new THREE.Vector3(...localAnchor).applyQuaternion(rotation).add(new THREE.Vector3(...pose.position)).toArray();
188
- if(localAxis) worldAxis=new THREE.Vector3(...localAxis).applyQuaternion(rotation).normalize().toArray();
189
- }
190
- joints.push({
191
- objectId,partName,
192
- jointType:part.spec?.joint?.type || articulation?.jointType || null,
193
- axis:localAxis,
194
- limits:part.spec?.joint?.limits ? [...part.spec.joint.limits] : null,
195
- parentAnchor:part.spec?.joint?.parentAnchor ? [...part.spec.joint.parentAnchor] : null,
196
- childAnchor:localAnchor,
197
- worldAxis,worldAnchor,
198
- coordinate:Number.isFinite(articulation?.coordinate) ? articulation.coordinate : null
199
- });
200
- }
201
- }
202
- }
203
- if(contacts && this.world && this.backend.hasCapability("collision")) {
204
- const seen=new Set();
205
- for(const source of colliderRefs) {
206
- for(const pair of this.backend.contactPairs(this.world,source.collider)) {
207
- const targetKey=this.backend.colliderKey(pair.other);
208
- const key=[String(source.key),String(targetKey)].sort().join(":");
209
- if(seen.has(key)) continue;
210
- seen.add(key);
211
- const targetSnapshot=this.backend.colliderSnapshot(pair.other);
212
- if(!targetSnapshot) continue;
213
- const targetPosition=[targetSnapshot.position.x,targetSnapshot.position.y,targetSnapshot.position.z];
214
- const anchor=source.record.position.map((value,index)=>(value+targetPosition[index])/2);
215
- contactPairs.push({
216
- source:source.record.provenance || {kind:"object",objectId:source.record.objectId,partName:source.record.partName,colliderIndex:source.record.colliderIndex},
217
- target:this.provenanceOfCollider(pair.other) || {kind:"unknown",colliderIndex:null},
218
- sourcePosition:[...source.record.position],
219
- targetPosition,
220
- anchor,
221
- anchorKind:"collider-midpoint",
222
- normal:Array.isArray(pair.normal) ? [...pair.normal] : null,
223
- minDistance:Number.isFinite(pair.minDistance) ? pair.minDistance : null,
224
- totalImpulse:Number.isFinite(pair.totalImpulse) ? pair.totalImpulse : null,
225
- evidenceKind:pair.evidenceKind || "contact",
226
- impulseAvailable:pair.impulseAvailable===true
227
- });
228
- }
229
- }
230
- }
231
- const backend=this.backend.debugSnapshot(this.world,{nativeGeometry}) || {};
232
- return {
233
- schemaVersion:1,
234
- source:"physics",
235
- backend:this.backend.identity,
236
- bodies,colliders,joints,contacts:contactPairs,
237
- nativeGeometry:backend.nativeGeometry || null,
238
- nativeGeometryAvailable:backend.nativeGeometryAvailable ?? Boolean(backend.nativeGeometry),
239
- metrics:{...(backend.metrics || {}),bodyCount:bodies.length,colliderCount:colliders.length,jointCount:joints.length,contactPairCount:contactPairs.length}
240
- };
241
- }
242
-
243
- // Narrow-phase contact for each distinct physical part pair, not just objects.
244
- // Keeps articulated body provenance; does not allocate a full debug snapshot.
245
- contactPartPairs(objectIds) {
246
- if(!this.world||!this.backend.hasCapability('collision'))return [];
247
- const allowed=new Set(objectIds);
248
- const seen=new Set(),result=[];
249
- for(const id of allowed) {
250
- const entry=this.entries.get(id);
251
- if(!entry)continue;
252
- for(const body of [entry.body,...[...entry.parts.values()].map(part=>part.body)]) {
253
- if(!body)continue;
254
- for(const collider of this.backend.colliders(body)) {
255
- const source=this.provenanceOfCollider(collider);
256
- if(source?.kind!=='object')continue;
257
- for(const pair of this.backend.contactPairs(this.world,collider)) {
258
- const target=this.provenanceOfCollider(pair.other);
259
- if(target?.kind!=='object'||source.objectId===target.objectId
260
- ||!allowed.has(target.objectId))continue;
261
- const [left,right]=[source,target].sort((a,b)=>
262
- a.objectId.localeCompare(b.objectId)||a.partName.localeCompare(b.partName));
263
- const key=[left.objectId,left.partName,right.objectId,right.partName].join('|');
264
- if(seen.has(key))continue;
265
- seen.add(key);
266
- result.push({
267
- sourceId:left.objectId,sourcePartName:left.partName,
268
- targetId:right.objectId,targetPartName:right.partName,
269
- evidenceKind:'physics-contact'
270
- });
271
- }
272
- }
273
- }
274
- }
275
- return result;
276
- }
277
-
278
- contactObjectPairs(objectIds) {
279
- const seen=new Set(),result=[];
280
- for(const pair of this.contactPartPairs(objectIds)){
281
- const key=pair.sourceId+'|'+pair.targetId;
282
- if(seen.has(key))continue;
283
- seen.add(key);
284
- result.push({sourceId:pair.sourceId,targetId:pair.targetId,evidenceKind:'physics-contact'});
285
- }
286
- return result;
287
- }
288
-
289
- addEnvironment(colliders = [], { id = '$environment', collision = null, sensor = false, collisionEvents = false } = {}) {
290
- if (!this.solverEnabled) return null;
291
- const body=this.backend.createBody(this.world,{type:'fixed'});
292
- this.addColliders(body,colliders,{collision,sensor,collisionEvents,provenance:{kind:'environment',environmentId:id}});
293
- return body;
294
- }
295
-
296
- addFloor() {
297
- return this.addEnvironment([{ shape:'box', halfExtents:[5, 0.1, 4], translation:[0, -0.1, 0] }]);
298
- }
299
-
300
- setEnvironmentPose(body, pose) {
301
- if (!this.solverEnabled || !body) return false;
302
- this.backend.setBodyPose(body, pose);
303
- return true;
304
- }
305
-
306
- _collisionBit(name) {
307
- if(this.collisionGroupBits.has(name)) return this.collisionGroupBits.get(name);
308
- if(this.collisionGroupBits.size>=16) throw new Error('Physics collision groups exceed Rapier-compatible limit of 16');
309
- const bit=1 << this.collisionGroupBits.size;
310
- this.collisionGroupBits.set(name,bit);
311
- return bit;
312
- }
313
-
314
- _compileCollisionFilter(collision) {
315
- if(!collision) return null;
316
- let membership=0,filter=0;
317
- for(const name of collision.groups || []) membership|=this._collisionBit(name);
318
- for(const name of collision.collidesWith || []) filter|=this._collisionBit(name);
319
- return {membership:membership & 0xffff,filter:filter & 0xffff};
320
- }
321
-
322
- _collisionPairAllowed(leftRuntime,rightRuntime) {
323
- const left=leftRuntime?.collisionFilter || {membership:0xffff,filter:0xffff};
324
- const right=rightRuntime?.collisionFilter || {membership:0xffff,filter:0xffff};
325
- return (left.membership & right.filter)!==0 && (right.membership & left.filter)!==0;
326
- }
327
-
328
- addColliders(body,colliders=[],{mass,friction,restitution,sensor=false,collisionEvents=false,collision=null,provenance=null}={}) {
329
- if (!this.solverEnabled || !body || !this.backend.hasCapability('collision')) return [];
330
- const collisionFilter=this._compileCollisionFilter(collision);
331
- const created=this.backend.createColliders(this.world,body,colliders,{mass,friction,restitution});
332
- this.backend.setBodyCollisionFilter(body,collisionFilter);
333
- created.forEach((collider,colliderIndex)=>{
334
- const key=this.backend.colliderKey(collider);
335
- this.colliderHandles.set(key,collider);
336
- if(provenance) this.colliderProvenance.set(key,{...provenance,colliderIndex});
337
- this.colliderRuntime.set(key,{sensor:Boolean(sensor),collisionEvents:Boolean(collisionEvents),collisionFilter});
338
- });
339
- if(sensor) this.backend.setBodySensor(body,true);
340
- return created;
341
- }
342
-
343
- unregisterBodyColliders(body) {
344
- if (!body) return;
345
- for(const collider of this.backend.colliders(body)) {
346
- const key=this.backend.colliderKey(collider);
347
- this.colliderProvenance.delete(key);
348
- this.colliderHandles.delete(key);
349
- this.colliderRuntime.delete(key);
350
- }
351
- }
352
-
353
- provenanceOfCollider(collider) {
354
- if (!collider) return null;
355
- const owner=this.colliderProvenance.get(this.backend.colliderKey(collider));
356
- return owner ? structuredClone(owner) : null;
357
- }
358
-
359
- addObject(id, manifest, object) {
360
- if (!this.solverEnabled) return this.addTransformState(id, manifest, object);
361
- const createdBodies = [];
362
- try {
363
- const worldPos = new THREE.Vector3();
364
- const worldRot = new THREE.Quaternion();
365
- object.getWorldPosition(worldPos);
366
- object.getWorldQuaternion(worldRot);
367
- const body=this.backend.createBody(this.world,{
368
- type:manifest.physics?.body || 'fixed', position:worldPos, rotation:worldRot,
369
- canSleep:manifest.physics?.canSleep ?? true, lockTranslation:manifest.physics?.lockTranslation, lockRotation:manifest.physics?.lockRotation
370
- });
371
- createdBodies.push(body);
372
- this.addColliders(body,manifest.physics?.colliders,{...manifest.physics,provenance:{kind:'object',objectId:id,partName:ROOT_PART}});
373
- this.backend.setBodyDynamics(body,manifest.physics || {});
374
- if(manifest.physics?.ccd != null) this.backend.setBodyCcd(body,manifest.physics.ccd);
375
-
376
- const entry = { body, root: object, rootSpec:manifest.physics || {}, parts: new Map(), lastPosition: worldPos.clone(), lastRotation: worldRot.clone() };
377
- const bodies = new Map([[ROOT_PART, body]]);
378
- for (const [partName, part] of orderParts(manifest.parts || {})) {
379
- if (!part.physics || !part.joint) continue;
380
- const node = object.getObjectByName(part.node);
381
- if (!node) continue;
382
- const parentName = part.parent || ROOT_PART;
383
- const parentBody = bodies.get(parentName);
384
- if (!parentBody) throw new Error(`Part parent body not available: ${partName} -> ${parentName}`);
385
-
386
- const partWorld = new THREE.Vector3();
387
- const partRotation = new THREE.Quaternion();
388
- node.getWorldPosition(partWorld);
389
- node.getWorldQuaternion(partRotation);
390
- const child=this.backend.createBody(this.world,{
391
- type:part.physics.body || 'dynamic', position:partWorld, rotation:partRotation,
392
- canSleep:part.physics?.canSleep ?? true, lockTranslation:part.physics?.lockTranslation, lockRotation:part.physics?.lockRotation
393
- });
394
- createdBodies.push(child);
395
- this.addColliders(child,part.physics.colliders,{...part.physics,provenance:{kind:'object',objectId:id,partName}});
396
- this.backend.setBodyDynamics(child,part.physics);
397
- if(part.physics?.ccd != null) this.backend.setBodyCcd(child,part.physics.ccd);
398
-
399
- const joint=this.backend.createJoint(this.world,part,parentBody,child);
400
- bodies.set(partName, child);
401
- entry.parts.set(partName, { body: child, joint, node, spec: part, parentName, restLocalRotation:node.quaternion.clone(), restLocalPosition:node.position.clone(), lastLocalRotation: node.quaternion.clone(), lastLocalPosition: node.position.clone() });
402
- }
403
-
404
- this.entries.set(id, entry);
405
- return entry;
406
- } catch (error) {
407
- for (const body of createdBodies.reverse()) {
408
- try { this.unregisterBodyColliders(body); this.backend.removeBody(this.world,body); } catch {}
409
- }
410
- throw error;
411
- }
412
- }
413
-
414
- addTransformState(id, manifest, object) {
415
- object.updateMatrixWorld(true);
416
- const worldPos = new THREE.Vector3();
417
- const worldRot = new THREE.Quaternion();
418
- object.getWorldPosition(worldPos);
419
- object.getWorldQuaternion(worldRot);
420
- const entry = {
421
- body:null,
422
- root:object,
423
- rootSpec:manifest.physics || {},
424
- parts:new Map(),
425
- lastPosition:worldPos.clone(),
426
- lastRotation:worldRot.clone(),
427
- held:false,
428
- transformOnly:true
429
- };
430
- for (const [partName, part] of orderParts(manifest.parts || {})) {
431
- if (!part.joint) continue;
432
- const node = object.getObjectByName(part.node);
433
- if (!node) continue;
434
- entry.parts.set(partName, {
435
- body:null,
436
- joint:null,
437
- node,
438
- spec:part,
439
- parentName:part.parent || ROOT_PART,
440
- restLocalRotation:node.quaternion.clone(),
441
- restLocalPosition:node.position.clone(),
442
- lastLocalRotation:node.quaternion.clone(),
443
- lastLocalPosition:node.position.clone()
444
- });
445
- }
446
- this.entries.set(id, entry);
447
- return entry;
448
- }
449
-
450
- setPosition(id, position) {
451
- const entry = this.entries.get(id);
452
- if (!entry) return;
453
- const next = new THREE.Vector3(...position);
454
- if (!entry.body) {
455
- if (entry.root.parent) {
456
- entry.root.parent.updateWorldMatrix(true, false);
457
- entry.root.position.copy(entry.root.parent.worldToLocal(next.clone()));
458
- } else entry.root.position.copy(next);
459
- entry.root.updateMatrixWorld(true);
460
- entry.lastPosition.copy(next);
461
- return true;
462
- }
463
- const delta = next.clone().sub(entry.lastPosition);
464
- this.backend.setBodyPose(entry.body,{position});
465
- this.backend.clearBodyMotion(entry.body,{linear:true,angular:false,wake:true});
466
- for (const { body } of entry.parts.values()) {
467
- this.backend.translateBody(body,delta.toArray(),{clearLinearVelocity:true,wake:true});
468
- }
469
- entry.lastPosition.copy(next);
470
- }
471
-
472
- beginTransform(id) {
473
- const entry = this.entries.get(id);
474
- if (!entry) return;
475
- if (!entry.body) { entry.transforming = true; return true; }
476
- entry.originalType=this.backend.bodyType(entry.body);
477
- this.backend.setBodyType(entry.body,'kinematic');
478
- for (const part of entry.parts.values()) {
479
- part.originalType=this.backend.bodyType(part.body);
480
- this.backend.setBodyType(part.body,'kinematic');
481
- }
482
- }
483
-
484
- syncTransform(id, object) {
485
- const entry = this.entries.get(id);
486
- if (!entry) return;
487
- object.updateMatrixWorld(true);
488
- const p = new THREE.Vector3();
489
- const q = new THREE.Quaternion();
490
- object.getWorldPosition(p);
491
- object.getWorldQuaternion(q);
492
- if (!entry.body) {
493
- entry.lastPosition.copy(p);
494
- entry.lastRotation.copy(q);
495
- for (const part of entry.parts.values()) {
496
- part.lastLocalPosition.copy(part.node.position);
497
- part.lastLocalRotation.copy(part.node.quaternion);
498
- }
499
- return true;
500
- }
501
- this.backend.setBodyPose(entry.body,{position:p,rotation:q});
502
- entry.lastPosition.copy(p);
503
- entry.lastRotation.copy(q);
504
- for (const part of entry.parts.values()) {
505
- const pp = new THREE.Vector3();
506
- const pq = new THREE.Quaternion();
507
- part.node.getWorldPosition(pp);
508
- part.node.getWorldQuaternion(pq);
509
- this.backend.setBodyPose(part.body,{position:pp,rotation:pq});
510
- }
511
- }
512
-
513
- endTransform(id) {
514
- const entry = this.entries.get(id);
515
- if (!entry) return;
516
- if (!entry.body) { delete entry.transforming; return true; }
517
- if (entry.originalType != null) this.backend.setBodyType(entry.body,entry.originalType);
518
- delete entry.originalType;
519
- for (const part of entry.parts.values()) {
520
- if (part.originalType != null) this.backend.setBodyType(part.body,part.originalType);
521
- delete part.originalType;
522
- this.backend.wakeBody(part.body);
523
- }
524
- }
525
-
526
- removeObject(id) {
527
- const entry = this.entries.get(id);
528
- if (!entry) return false;
529
- if (!entry.body) { this.entries.delete(id); return true; }
530
- for (const part of entry.parts.values()) {
531
- this.unregisterBodyColliders(part.body);
532
- this.backend.removeBody(this.world,part.body);
533
- }
534
- this.unregisterBodyColliders(entry.body);
535
- this.backend.removeBody(this.world,entry.body);
536
- this.entries.delete(id);
537
- return true;
538
- }
539
-
540
- setHeld(id, held) {
541
- const entry = this.entries.get(id);
542
- if (!entry) return false;
543
- if (!entry.body) { entry.held = Boolean(held); return true; }
544
- if (held) {
545
- if (entry.heldOriginalType == null) entry.heldOriginalType=this.backend.bodyType(entry.body);
546
- entry.held=true;
547
- this.backend.setBodyType(entry.body,'kinematic');
548
- this.backend.clearBodyMotion(entry.body,{wake:true});
549
- } else {
550
- entry.held=false;
551
- this.backend.setBodyType(entry.body,entry.heldOriginalType ?? 'dynamic');
552
- this.backend.clearBodyMotion(entry.body,{wake:true});
553
- delete entry.heldOriginalType;
554
- }
555
- return true;
556
- }
557
-
558
- setHeldTarget(id, target, rotation = null) {
559
- const entry = this.entries.get(id);
560
- const body = entry?.body;
561
- if (!entry) return false;
562
- if (!body) return this.setHeldPose(id, target, rotation);
563
- this.backend.setBodyPose(body,{position:target,rotation,next:true});
564
- return true;
565
- }
566
-
567
- setHeldPose(id, position, rotation = null) {
568
- const entry = this.entries.get(id);
569
- if (!entry) return false;
570
- if (entry.body) {
571
- this.backend.setBodyPose(entry.body,{position,rotation});
572
- }
573
- if (entry.root.parent) {
574
- entry.root.parent.updateWorldMatrix(true, false);
575
- entry.root.position.copy(entry.root.parent.worldToLocal(new THREE.Vector3(...position)));
576
- } else entry.root.position.fromArray(position);
577
- entry.lastPosition.fromArray(position);
578
- if (rotation) {
579
- entry.root.quaternion.fromArray(rotation);
580
- entry.lastRotation.fromArray(rotation);
581
- }
582
- entry.root.updateMatrixWorld(true);
583
- return true;
584
- }
585
-
586
- anchorPose(id, anchor, { next = false } = {}) {
587
- const entry = this.entries.get(id);
588
- const body = entry?.body;
589
- if (!entry || !anchor?.translation) return null;
590
- let position;
591
- let rotation;
592
- if (body) {
593
- const pose=this.backend.bodyPose(body,{next});
594
- position=new THREE.Vector3(...pose.position);
595
- rotation=new THREE.Quaternion(...pose.rotation);
596
- } else {
597
- entry.root.updateWorldMatrix(true, false);
598
- position = new THREE.Vector3();
599
- rotation = new THREE.Quaternion();
600
- entry.root.getWorldPosition(position);
601
- entry.root.getWorldQuaternion(rotation);
602
- }
603
- const local = new THREE.Vector3(...anchor.translation).applyQuaternion(rotation);
604
- const anchorPosition = position.clone().add(local);
605
- const localRotation = new THREE.Quaternion(...(anchor.rotation || [0,0,0,1]));
606
- const worldRotation = rotation.clone().multiply(localRotation).normalize();
607
- return { position:anchorPosition.toArray(), rotation:worldRotation.toArray() };
608
- }
609
-
610
- checkManifestPose(manifest, targetPosition, { excludeIds = [], quaternion = [0,0,0,1] } = {}) {
611
- if (!this.backend.hasCapability('collision')) return {checked:false,clear:false,reason:'PHYSICS_CAPABILITY_UNAVAILABLE',capability:'collision'};
612
- const colliders=manifest?.physics?.colliders || [];
613
- if (!colliders.length) return {checked:false,clear:false,reason:'ROOT_COLLIDER_UNAVAILABLE'};
614
- const excluded=new Set(excludeIds);
615
- const blockedBy=new Set();
616
- const shapeFor=(spec)=>{
617
- return this.backend.createQueryShape(spec);
618
- };
619
- this.backend.syncSceneQueries(this.world);
620
- for(let i=0;i<colliders.length;i++) {
621
- const spec=colliders[i],shape=shapeFor(spec);
622
- if (!shape) return {checked:false,clear:false,reason:'ROOT_COLLIDER_UNSUPPORTED',collider:i,shape:spec.shape || null};
623
- const local=spec.translation || [0,0,0];
624
- const rootRotation=new THREE.Quaternion(...quaternion).normalize();
625
- const position=new THREE.Vector3(...local).applyQuaternion(rootRotation).add(new THREE.Vector3(...targetPosition));
626
- const rotation=rootRotation.clone().multiply(new THREE.Quaternion(...(spec.rotation || [0,0,0,1]))).normalize();
627
- try {
628
- this.backend.intersectionsWithShape(this.world,position,rotation,shape,(other)=>{
629
- const provenance=this.provenanceOfCollider(other);
630
- if (provenance?.kind==='object' && excluded.has(provenance.objectId)) return true;
631
- blockedBy.add(provenance?.kind==='environment' ? `environment:${provenance.environmentId || '$environment'}`
632
- : provenance?.kind==='object' ? `object:${provenance.objectId}:${provenance.partName || ROOT_PART}` : '$unknown');
633
- return false;
634
- });
635
- } finally {
636
- this.backend.disposeQueryShape(shape);
637
- }
638
- if (blockedBy.size) return {checked:true,clear:false,blockedBy:[...blockedBy].sort(),coverage:Object.keys(manifest.parts || {}).length?'root-only':'full-root'};
639
- }
640
- return {checked:true,clear:true,blockedBy:[],coverage:Object.keys(manifest.parts || {}).length?'root-only':'full-root'};
641
- }
642
-
643
- checkBodyPose(id, targetPosition, targetRotation = null, { excludeIds = [] } = {}) {
644
- if (!this.backend.hasCapability('collision')) return {clear:false,code:'PHYSICS_CAPABILITY_UNAVAILABLE',capability:'collision'};
645
- const entry = this.entries.get(id);
646
- if (!entry || entry.parts.size) return { clear:false, code:'CARRY_BODY_UNSUPPORTED' };
647
- const bodyPose=this.backend.bodyPose(entry.body);
648
- const bodyRotation=new THREE.Quaternion(...bodyPose.rotation);
649
- const nextRotation = targetRotation ? new THREE.Quaternion(...targetRotation) : bodyRotation.clone();
650
- const targetBody = new THREE.Vector3(...targetPosition);
651
- const excluded = new Set([id, ...excludeIds]);
652
- const filter=(collider)=>{
653
- const parent=this.backend.colliderParent(collider);
654
- const owner=parent ? this.ownerOfBody(parent) : null;
655
- return !owner || !excluded.has(owner.id);
656
- };
657
-
658
- this.backend.syncSceneQueries(this.world);
659
- const bodyColliders=this.backend.colliders(entry.body);
660
- for (let i=0;i<bodyColliders.length;i++) {
661
- const collider=bodyColliders[i];
662
- const snapshot=this.backend.colliderSnapshot(collider);
663
- const spec = entry.rootSpec.colliders?.[i] || {};
664
- if (!['box','cylinder','capsule'].includes(spec.shape)) return { clear:false, code:'CARRY_COLLIDER_UNSUPPORTED', collider:i, shape:spec.shape || null };
665
- const local = new THREE.Vector3(...(spec.translation || [0,0,0]));
666
- const targetCenter = local.applyQuaternion(nextRotation).add(targetBody);
667
- let overlap = null;
668
- const colliderRotation=nextRotation.clone().multiply(new THREE.Quaternion(...(spec.rotation || [0,0,0,1])));
669
- this.backend.intersectionsWithShape(this.world,targetCenter,colliderRotation,snapshot.shapeRef,(other)=>{
670
- const parent=this.backend.colliderParent(other);
671
- const owner=parent ? this.ownerOfBody(parent) : null;
672
- if (owner && excluded.has(owner.id)) return true;
673
- overlap = owner?.id || '$environment';
674
- return false;
675
- },{excludeCollider:collider,excludeBody:entry.body,predicate:filter});
676
- if (overlap) return { clear:false, code:'CARRY_TARGET_BLOCKED', collider:i, blockedBy:[overlap] };
677
- }
678
- return { clear:true };
679
- }
680
-
681
- checkBodyMotion(id, targetPosition, targetRotation = null, { excludeIds = [] } = {}) {
682
- if (!this.backend.hasCapability('collision')) return {clear:false,code:'PHYSICS_CAPABILITY_UNAVAILABLE',capability:'collision'};
683
- const entry = this.entries.get(id);
684
- if (!entry || entry.parts.size) return { clear:false, code:'CARRY_BODY_UNSUPPORTED' };
685
- const bodyPose=this.backend.bodyPose(entry.body);
686
- const bodyRotation=new THREE.Quaternion(...bodyPose.rotation);
687
- const nextRotation = targetRotation ? new THREE.Quaternion(...targetRotation) : bodyRotation.clone();
688
- const targetBody = new THREE.Vector3(...targetPosition);
689
- const blockedBy = new Set();
690
- const excluded = new Set([id, ...excludeIds]);
691
- const filter=(collider)=>{
692
- const parent=this.backend.colliderParent(collider);
693
- const owner=parent ? this.ownerOfBody(parent) : null;
694
- return !owner || !excluded.has(owner.id);
695
- };
696
-
697
- this.backend.syncSceneQueries(this.world);
698
- const bodyColliders=this.backend.colliders(entry.body);
699
- for (let i=0;i<bodyColliders.length;i++) {
700
- const collider=bodyColliders[i];
701
- const snapshot=this.backend.colliderSnapshot(collider);
702
- const spec = entry.rootSpec.colliders?.[i] || {};
703
- if (!['box','cylinder','capsule'].includes(spec.shape)) return { clear:false, code:'CARRY_COLLIDER_UNSUPPORTED', collider:i, shape:spec.shape || null };
704
- const local = new THREE.Vector3(...(spec.translation || [0,0,0]));
705
- const targetCenter = local.applyQuaternion(nextRotation).add(targetBody);
706
- const delta=targetCenter.clone().sub(new THREE.Vector3(snapshot.position.x,snapshot.position.y,snapshot.position.z));
707
- if (delta.lengthSq() > 1e-12) {
708
- const hit=this.backend.castCollider(this.world,collider,delta.toArray(),{
709
- excludeCollider:collider,excludeBody:entry.body,predicate:filter,
710
- targetDistance:0,maxToi:1,stopAtPenetration:false
711
- });
712
- if(hit) {
713
- const parent=this.backend.colliderParent(hit.collider);
714
- const owner=parent ? this.ownerOfBody(parent) : null;
715
- blockedBy.add(owner?.id || '$environment');
716
- return {clear:false,code:'CARRY_SWEEP_BLOCKED',collider:i,blockedBy:[...blockedBy],toi:hit.timeOfImpact};
717
- }
718
- }
719
- }
720
- return this.checkBodyPose(id,targetPosition,targetRotation,{excludeIds});
721
- }
722
-
723
- cancelCharacterMovement(id) {
724
- if (!this.backend.hasCapability('character-controller')) return false;
725
- const body = this.entries.get(id)?.body;
726
- if (!body) return false;
727
- return this.backend.cancelCharacterMovement(body);
728
- }
729
-
730
- getPosition(id) {
731
- const entry = this.entries.get(id);
732
- const pose=entry?.body ? this.backend.bodyPose(entry.body) : null;
733
- if (pose) return [...pose.position];
734
- if (!entry?.root) return null;
735
- entry.root.updateWorldMatrix(true, false);
736
- const world = new THREE.Vector3();
737
- entry.root.getWorldPosition(world);
738
- return world.toArray();
739
- }
740
-
741
- getRotation(id) {
742
- const entry = this.entries.get(id);
743
- const pose=entry?.body ? this.backend.bodyPose(entry.body) : null;
744
- if (pose) return [...pose.rotation];
745
- if (!entry?.root) return null;
746
- entry.root.updateWorldMatrix(true, false);
747
- const world = new THREE.Quaternion();
748
- entry.root.getWorldQuaternion(world);
749
- return world.toArray();
750
- }
751
-
752
- // Portable body checkpoint, not an exact snapshot of the solver/contact caches.
753
- captureState() {
754
- const capture = (body, node) => ({
755
- position:node.position.toArray(), rotation:node.quaternion.toArray(),
756
- ...(body ? {
757
- type:this.backend.bodyType(body),
758
- pose:this.backend.bodyPose(body),
759
- motion:this.backend.bodyMotion(body),
760
- ...(this.backend.bodyType(body) === 'kinematic' ? { nextPose:this.backend.bodyPose(body, { next:true }) } : {})
761
- } : {})
762
- });
763
- return [...this.entries].map(([id, entry]) => ({
764
- id,
765
- root:capture(entry.body, entry.root),
766
- held:entry.held === true,
767
- heldOriginalType:entry.heldOriginalType ?? null,
768
- parts:[...entry.parts].map(([name, part]) => ({
769
- name, ...capture(part.body, part.node), motorTarget:part.motorTarget ?? null
770
- }))
771
- }));
772
- }
773
-
774
- captureArticulationPose(id) {
775
- const entry = this.entries.get(id);
776
- return entry ? [...entry.parts].map(([partName,part]) => ({ partName,
777
- position:part.node.position.toArray(), quaternion:part.node.quaternion.toArray(), motorTarget:part.motorTarget ?? null })) : [];
778
- }
779
-
780
- // Save/history restoration only. Live manipulation never calls this method.
781
- restoreArticulationPose(id, poses) {
782
- const entry = this.entries.get(id);
783
- if (!entry) throw new Error('ARTICULATION_PHYSICS_UNAVAILABLE');
784
- const checkpoint = this.captureState().find(item => item.id === id);
785
- for (const pose of poses) {
786
- const part = entry.parts.get(pose.partName);
787
- if (!part) throw new Error('ARTICULATION_PART_NOT_FOUND');
788
- const limits = part.spec.joint.limits;
789
- if (pose.motorTarget != null && limits && (pose.motorTarget < limits[0] || pose.motorTarget > limits[1])) throw new Error('JOINT_LIMIT_EXCEEDED');
790
- part.node.position.fromArray(pose.position); part.node.quaternion.fromArray(pose.quaternion);
791
- }
792
- entry.root.updateMatrixWorld(true);
793
- for (const pose of poses) {
794
- const part = entry.parts.get(pose.partName), value = checkpoint.parts.find(item => item.name === pose.partName);
795
- value.position = pose.position; value.rotation = pose.quaternion; value.motorTarget = pose.motorTarget;
796
- if (value.pose) value.pose = { position:part.node.getWorldPosition(new THREE.Vector3()).toArray(), rotation:part.node.getWorldQuaternion(new THREE.Quaternion()).toArray() };
797
- }
798
- this.restoreState([checkpoint]);
799
- }
800
-
801
- restoreState(state) {
802
- const restore = (body, node, value) => {
803
- node.position.fromArray(value.position);
804
- node.quaternion.fromArray(value.rotation);
805
- node.updateMatrixWorld(true);
806
- if (!body) return;
807
- if (this.backend.bodyType(body) !== value.type) this.backend.setBodyType(body, value.type);
808
- this.backend.setBodyPose(body, { ...value.pose, wake:false });
809
- if (value.nextPose) this.backend.setBodyPose(body, { ...value.nextPose, next:true, wake:false });
810
- if (value.motion && value.type === 'dynamic') {
811
- this.backend.setBodyMotion(body, { ...value.motion, wake:false });
812
- if (value.motion.sleeping) this.backend.sleepBody(body);
813
- else this.backend.wakeBody(body);
814
- }
815
- };
816
- for (const item of state) {
817
- const entry = this.entries.get(item.id);
818
- if (!entry) throw new Error(`Physics checkpoint object missing: ${item.id}`);
819
- entry.held = item.held;
820
- if (item.heldOriginalType == null) delete entry.heldOriginalType;
821
- else entry.heldOriginalType = item.heldOriginalType;
822
- restore(entry.body, entry.root, item.root);
823
- entry.root.getWorldPosition(entry.lastPosition);
824
- entry.root.getWorldQuaternion(entry.lastRotation);
825
- for (const value of item.parts) {
826
- const part = entry.parts.get(value.name);
827
- if (!part) throw new Error(`Physics checkpoint part missing: ${item.id}:${value.name}`);
828
- if (part.joint && part.spec.joint.type !== 'fixed') {
829
- this.backend.setJointTarget(part.joint, value.motorTarget, part.spec.joint.motor || {});
830
- }
831
- part.motorTarget = value.motorTarget;
832
- restore(part.body, part.node, value);
833
- part.lastLocalPosition.copy(part.node.position);
834
- part.lastLocalRotation.copy(part.node.quaternion);
835
- }
836
- }
837
- }
838
-
839
- getMotion(id, { partName = ROOT_PART } = {}) {
840
- const entry = this.entries.get(id);
841
- const body = partName===ROOT_PART ? entry?.body : entry?.parts.get(partName)?.body;
842
- if (!entry) return null;
843
- if (!body) return {
844
- sleeping:true,
845
- linearVelocity:[0,0,0],
846
- angularVelocity:[0,0,0],
847
- linearSpeed:0,
848
- angularSpeed:0,
849
- source:'transform-state'
850
- };
851
- return this.backend.bodyMotion(body);
852
- }
853
-
854
- manipulationBody(id, partName = ROOT_PART, { contacts = false } = {}) {
855
- const entry = this.entries.get(id);
856
- const part = partName === ROOT_PART ? null : entry?.parts.get(partName);
857
- const body = part ? part.body : partName === ROOT_PART ? entry?.body : null;
858
- const spec = part ? part.spec.physics : entry?.rootSpec;
859
- const colliders = body ? this.backend.colliders(body) : [];
860
- const contactCandidates = (contacts ? colliders : []).map(collider => {
861
- const snapshot = this.backend.colliderSnapshot(collider), shape = snapshot.shape;
862
- let vertexRadius = 0;
863
- if (shape.vertices) for (let i=0;i<shape.vertices.length;i+=3) vertexRadius = Math.max(vertexRadius,Math.hypot(shape.vertices[i],shape.vertices[i+1],shape.vertices[i+2]));
864
- const radius = shape.kind === 'box' ? Math.hypot(...array3(shape.halfExtents))
865
- : shape.kind === 'cylinder' ? Math.hypot(shape.radius,shape.halfHeight)
866
- : shape.kind === 'capsule' ? shape.radius+shape.halfHeight
867
- : shape.vertices ? vertexRadius : null;
868
- return { center:array3(snapshot.position), radius };
869
- }).filter(candidate => Number.isFinite(candidate.radius) && candidate.radius > 0);
870
- return { registered: Boolean(body), body: body ? this.backend.bodyType(body) : null,
871
- joint: Boolean(part?.joint), mass: spec?.mass ?? null,
872
- colliderCount:colliders.length, contactCandidates,
873
- lockTranslation:spec?.lockTranslation || [false,false,false], lockRotation:spec?.lockRotation || [false,false,false] };
874
- }
875
-
876
- setMotion(id,motion={}, { partName = ROOT_PART } = {}) {
877
- const entry=this.entries.get(id);
878
- const body=partName===ROOT_PART ? entry?.body : entry?.parts.get(partName)?.body;
879
- return body ? this.backend.setBodyMotion(body,motion) : false;
880
- }
881
-
882
- applyImpulse(id,impulse,{ partName = ROOT_PART, point = null, wake = true } = {}) {
883
- const entry=this.entries.get(id);
884
- const body=partName===ROOT_PART ? entry?.body : entry?.parts.get(partName)?.body;
885
- return body ? this.backend.applyImpulse(body,impulse,{point,wake}) : false;
886
- }
887
-
888
- applyForce(id,force,{ partName = ROOT_PART, point = null, wake = true } = {}) {
889
- const entry=this.entries.get(id);
890
- const body=partName===ROOT_PART ? entry?.body : entry?.parts.get(partName)?.body;
891
- return body ? this.backend.applyForce(body,force,{point,wake}) : false;
892
- }
893
-
894
- applyTorque(id,torque,{ partName = ROOT_PART, wake = true } = {}) {
895
- const entry=this.entries.get(id);
896
- const body=partName===ROOT_PART ? entry?.body : entry?.parts.get(partName)?.body;
897
- return body ? this.backend.applyTorque(body,torque,{wake}) : false;
898
- }
899
-
900
- setMaterial(id,material={}, { partName = ROOT_PART } = {}) {
901
- const entry=this.entries.get(id);
902
- const body=partName===ROOT_PART ? entry?.body : entry?.parts.get(partName)?.body;
903
- return body ? this.backend.setBodyMaterial(body,material) : false;
904
- }
905
-
906
- setDynamics(id,dynamics={}, { partName = ROOT_PART } = {}) {
907
- const entry=this.entries.get(id);
908
- const body=partName===ROOT_PART ? entry?.body : entry?.parts.get(partName)?.body;
909
- return body ? this.backend.setBodyDynamics(body,dynamics) : false;
910
- }
911
-
912
- setCcd(id,enabled,{ partName = ROOT_PART } = {}) {
913
- const entry=this.entries.get(id);
914
- const body=partName===ROOT_PART ? entry?.body : entry?.parts.get(partName)?.body;
915
- return body ? this.backend.setBodyCcd(body,Boolean(enabled)) : false;
916
- }
917
-
918
- sleep(id,{ partName = ROOT_PART } = {}) {
919
- const entry=this.entries.get(id);
920
- const body=partName===ROOT_PART ? entry?.body : entry?.parts.get(partName)?.body;
921
- return body ? this.backend.sleepBody(body) : false;
922
- }
923
-
924
- wake(id,{ partName = ROOT_PART } = {}) {
925
- const entry=this.entries.get(id);
926
- const body=partName===ROOT_PART ? entry?.body : entry?.parts.get(partName)?.body;
927
- return body ? this.backend.wakeBody(body) : false;
928
- }
929
-
930
- setSensor(id,enabled,{ partName = ROOT_PART } = {}) {
931
- const entry=this.entries.get(id);
932
- const body=partName===ROOT_PART ? entry?.body : entry?.parts.get(partName)?.body;
933
- if(!body) return false;
934
- const ok=this.backend.setBodySensor(body,Boolean(enabled));
935
- if(ok) for(const collider of this.backend.colliders(body)) {
936
- const key=this.backend.colliderKey(collider);
937
- const runtime=this.colliderRuntime.get(key) || {sensor:false,collisionEvents:false,collisionFilter:null};
938
- this.colliderRuntime.set(key,{...runtime,sensor:Boolean(enabled)});
939
- }
940
- return ok;
941
- }
942
-
943
- setCollisionFilter(id,collision,{ partName = ROOT_PART } = {}) {
944
- const entry=this.entries.get(id);
945
- const body=partName===ROOT_PART ? entry?.body : entry?.parts.get(partName)?.body;
946
- if(!body) return false;
947
- const collisionFilter=this._compileCollisionFilter(collision);
948
- const ok=this.backend.setBodyCollisionFilter(body,collisionFilter);
949
- if(ok) for(const collider of this.backend.colliders(body)) {
950
- const key=this.backend.colliderKey(collider);
951
- const runtime=this.colliderRuntime.get(key) || {sensor:false,collisionEvents:false,collisionFilter:null};
952
- this.colliderRuntime.set(key,{...runtime,collisionFilter});
953
- }
954
- return ok;
955
- }
956
-
957
- getPartRestPose(id, partName) {
958
- const part = this.entries.get(id)?.parts.get(partName);
959
- if (!part) return null;
960
- return { position:part.restLocalPosition.toArray(), rotation:part.restLocalRotation.toArray() };
961
- }
962
-
963
- getArticulationState(id, partName, { target = null } = {}) {
964
- const entry = this.entries.get(id);
965
- const part = entry?.parts.get(partName);
966
- if (!entry || !part?.node?.parent || part.spec?.joint?.type === 'fixed') return null;
967
- const parentFrame = part.parentName === ROOT_PART ? entry.root : entry.parts.get(part.parentName)?.node;
968
- if (!parentFrame) return null;
969
- entry.root.updateWorldMatrix(true, true);
970
- const parentWorldRotation = new THREE.Quaternion();
971
- const nodeParentWorldRotation = new THREE.Quaternion();
972
- parentFrame.getWorldQuaternion(parentWorldRotation);
973
- part.node.parent.getWorldQuaternion(nodeParentWorldRotation);
974
- const axis = new THREE.Vector3(...(part.spec.joint.axis || [1,0,0])).normalize()
975
- .applyQuaternion(parentWorldRotation)
976
- .applyQuaternion(nodeParentWorldRotation.invert())
977
- .normalize();
978
- if (!Number.isFinite(axis.lengthSq()) || axis.lengthSq() < .99) return null;
979
-
980
- let coordinate;
981
- if (part.spec.joint.type === 'prismatic') {
982
- coordinate = part.node.position.clone().sub(part.restLocalPosition).dot(axis);
983
- } else {
984
- const delta = part.node.quaternion.clone().multiply(part.restLocalRotation.clone().invert()).normalize();
985
- const angle = 2 * Math.atan2(delta.x*axis.x + delta.y*axis.y + delta.z*axis.z, delta.w);
986
- coordinate = Math.atan2(Math.sin(angle), Math.cos(angle));
987
- }
988
- if (!Number.isFinite(coordinate)) return null;
989
- const wrap = (value) => part.spec.joint.type === 'revolute' ? Math.atan2(Math.sin(value),Math.cos(value)) : value;
990
- const error = Number.isFinite(target) ? Math.abs(wrap(coordinate-target)) : null;
991
- return {
992
- id,partName,jointType:part.spec.joint.type,
993
- coordinate,target:Number.isFinite(target) ? target : null,error,
994
- tolerance:part.spec.joint.type === 'prismatic' ? .03 : .08,
995
- limits:part.spec.joint.limits ? [...part.spec.joint.limits] : null,
996
- localAxis:axis.toArray(),
997
- coordinateReference:'rest-zero-pose'
998
- };
999
- }
1000
-
1001
- articulationColliderPoses(id, partName, coordinate) {
1002
- if (!this.backend.hasCapability('collision')) return {checked:false,reason:'PHYSICS_CAPABILITY_UNAVAILABLE',capability:'collision',id,partName,coordinate};
1003
- const entry=this.entries.get(id);
1004
- const part=entry?.parts.get(partName);
1005
- if (!entry || !part?.node?.parent || !Number.isFinite(coordinate)) return {checked:false,reason:'PART_POSE_UNAVAILABLE',id,partName,coordinate};
1006
- const state=this.getArticulationState(id,partName);
1007
- if (!state) return {checked:false,reason:'JOINT_COORDINATE_UNAVAILABLE',id,partName,coordinate};
1008
- const childAnchor=new THREE.Vector3(...(part.spec.joint.childAnchor || [0,0,0]));
1009
- const parentRotation=new THREE.Quaternion();
1010
- part.node.parent.updateWorldMatrix(true,false);
1011
- part.node.parent.getWorldQuaternion(parentRotation);
1012
- const worldAxis=new THREE.Vector3(...state.localAxis).applyQuaternion(parentRotation).normalize();
1013
- if (!Number.isFinite(worldAxis.lengthSq()) || worldAxis.lengthSq()<.99) return {checked:false,reason:'JOINT_AXIS_UNAVAILABLE',id,partName,coordinate};
1014
-
1015
- const bodyPose=this.backend.bodyPose(part.body);
1016
- const currentBodyPosition=new THREE.Vector3(...bodyPose.position);
1017
- const currentBodyRotation=new THREE.Quaternion(...bodyPose.rotation).normalize();
1018
- const delta=coordinate-state.coordinate;
1019
- const bodyPosition=currentBodyPosition.clone();
1020
- const bodyRotation=currentBodyRotation.clone();
1021
- if (part.spec.joint.type==='prismatic') {
1022
- bodyPosition.addScaledVector(worldAxis,delta);
1023
- } else {
1024
- const pivotWorld=childAnchor.clone().applyQuaternion(currentBodyRotation).add(currentBodyPosition);
1025
- bodyRotation.premultiply(new THREE.Quaternion().setFromAxisAngle(worldAxis,delta)).normalize();
1026
- bodyPosition.copy(pivotWorld).sub(childAnchor.clone().applyQuaternion(bodyRotation));
1027
- }
1028
-
1029
- const inverseCurrent=currentBodyRotation.clone().invert();
1030
- const colliders=[];
1031
- for(const [i,collider] of this.backend.colliders(part.body).entries()) {
1032
- const snapshot=this.backend.colliderSnapshot(collider);
1033
- const currentColliderPosition=new THREE.Vector3(snapshot.position.x,snapshot.position.y,snapshot.position.z);
1034
- const currentColliderRotation=new THREE.Quaternion(snapshot.rotation.x,snapshot.rotation.y,snapshot.rotation.z,snapshot.rotation.w).normalize();
1035
- const localPosition=currentColliderPosition.clone().sub(currentBodyPosition).applyQuaternion(inverseCurrent);
1036
- const localRotation=inverseCurrent.clone().multiply(currentColliderRotation).normalize();
1037
- const position=localPosition.clone().applyQuaternion(bodyRotation).add(bodyPosition);
1038
- const rotation=bodyRotation.clone().multiply(localRotation).normalize();
1039
- colliders.push({index:i,shape:snapshot.shape,shapeRef:snapshot.shapeRef,position,rotation});
1040
- }
1041
- return {checked:true,id,partName,jointType:state.jointType,currentCoordinate:state.coordinate,coordinate,parentName:part.parentName,frameAssumption:'parent-pose-at-query',colliders};
1042
- }
1043
-
1044
- shapeBoundingRadius(shape) {
1045
- if (!shape) return null;
1046
- if (shape.halfExtents) {
1047
- const h=shape.halfExtents;
1048
- const border=Number(shape.borderRadius) || 0;
1049
- return Math.hypot(h.x+border,h.y+border,h.z+border);
1050
- }
1051
- if (Number.isFinite(shape.halfHeight) && Number.isFinite(shape.radius)) {
1052
- const border=Number(shape.borderRadius) || 0;
1053
- return Math.hypot(shape.radius+border,shape.halfHeight+shape.radius+border);
1054
- }
1055
- if (Number.isFinite(shape.radius)) return shape.radius;
1056
- if (shape.vertices?.length) {
1057
- let radius=0;
1058
- for(let i=0;i+2<shape.vertices.length;i+=3) radius=Math.max(radius,Math.hypot(shape.vertices[i],shape.vertices[i+1],shape.vertices[i+2]));
1059
- return radius || null;
1060
- }
1061
- if (shape.a && shape.b) return Math.max(Math.hypot(shape.a.x,shape.a.y,shape.a.z),Math.hypot(shape.b.x,shape.b.y,shape.b.z));
1062
- return null;
1063
- }
1064
-
1065
- articulationCounterfactualSampleCount(id, partName, current, target, { minSamples = 5, maxSamples = 33 } = {}) {
1066
- const entry=this.entries.get(id);
1067
- const part=entry?.parts.get(partName);
1068
- if (!part || !Number.isFinite(current) || !Number.isFinite(target)) return {checked:false,reason:'PART_SAMPLE_GEOMETRY_UNAVAILABLE'};
1069
- const delta=Math.abs(target-current);
1070
- if (delta<1e-9) return {checked:true,count:minSamples,delta,maxTravel:0,resolution:.08};
1071
- const bodyPose=this.backend.bodyPose(part.body);
1072
- const bodyPosition=new THREE.Vector3(...bodyPose.position);
1073
- const bodyRotation=new THREE.Quaternion(...bodyPose.rotation).normalize();
1074
- const inverseBody=bodyRotation.clone().invert();
1075
- const childAnchor=new THREE.Vector3(...(part.spec.joint.childAnchor || [0,0,0]));
1076
- let minRadius=Infinity,maxLever=0,covered=0;
1077
- for(const collider of this.backend.colliders(part.body)) {
1078
- const snapshot=this.backend.colliderSnapshot(collider);
1079
- const radius=this.shapeBoundingRadius(snapshot.shape);
1080
- if (!Number.isFinite(radius) || radius<=0) continue;
1081
- const localCenter=new THREE.Vector3(snapshot.position.x,snapshot.position.y,snapshot.position.z).sub(bodyPosition).applyQuaternion(inverseBody);
1082
- minRadius=Math.min(minRadius,radius);
1083
- maxLever=Math.max(maxLever,localCenter.distanceTo(childAnchor)+radius);
1084
- covered+=1;
1085
- }
1086
- if (!covered || !Number.isFinite(minRadius)) return {checked:false,reason:'COLLIDER_EXTENT_UNAVAILABLE'};
1087
- const maxTravel=part.spec.joint.type==='revolute' ? delta*maxLever : delta;
1088
- const resolution=THREE.MathUtils.clamp(minRadius*.35,.02,.08);
1089
- const count=THREE.MathUtils.clamp(Math.ceil(maxTravel/resolution)+1,minSamples,maxSamples);
1090
- return {checked:true,count,delta,maxTravel,resolution,colliders:covered,minRadius,maxLever:part.spec.joint.type==='revolute'?maxLever:null};
1091
- }
1092
-
1093
- articulationPairCounterfactual(originalId, originalPartName, originalTarget, blockerId, blockerPartName, blockerTarget, { samples = null } = {}) {
1094
- const originalState=this.getArticulationState(originalId,originalPartName,{target:originalTarget});
1095
- const blockerState=this.getArticulationState(blockerId,blockerPartName,{target:blockerTarget});
1096
- if (!originalState || !blockerState) return {checked:false,reason:'JOINT_COORDINATE_UNAVAILABLE'};
1097
- if (!Number.isFinite(originalTarget) || !Number.isFinite(blockerTarget)) return {checked:false,reason:'TARGET_UNAVAILABLE'};
1098
- const fixedSamples=Number.isFinite(samples) ? Math.max(2,Math.min(33,Math.trunc(samples))) : null;
1099
- const pairedSamples=samples && typeof samples==='object' ? {
1100
- original:Math.max(2,Math.min(33,Math.trunc(samples.original) || 2)),
1101
- blocker:Math.max(2,Math.min(33,Math.trunc(samples.blocker) || 2))
1102
- } : null;
1103
- const originalSampling=fixedSamples ? {checked:true,count:fixedSamples,mode:'fixed'}
1104
- : pairedSamples ? {checked:true,count:pairedSamples.original,mode:'fixed-pair'}
1105
- : this.articulationCounterfactualSampleCount(originalId,originalPartName,originalState.coordinate,originalTarget);
1106
- const blockerSampling=fixedSamples ? {checked:true,count:fixedSamples,mode:'fixed'}
1107
- : pairedSamples ? {checked:true,count:pairedSamples.blocker,mode:'fixed-pair'}
1108
- : this.articulationCounterfactualSampleCount(blockerId,blockerPartName,blockerState.coordinate,blockerTarget);
1109
- if (!originalSampling.checked) return {checked:false,reason:originalSampling.reason,source:'original-sampling'};
1110
- if (!blockerSampling.checked) return {checked:false,reason:blockerSampling.reason,source:'blocker-sampling'};
1111
-
1112
- const trajectory=(id,partName,current,target,count)=>{
1113
- const poses=[];
1114
- for(let i=0;i<count;i++) {
1115
- const alpha=i/(count-1);
1116
- const coordinate=current+(target-current)*alpha;
1117
- const pose=this.articulationColliderPoses(id,partName,coordinate);
1118
- if (!pose.checked) return pose;
1119
- poses.push(pose);
1120
- }
1121
- return {checked:true,poses};
1122
- };
1123
- const original=trajectory(originalId,originalPartName,originalState.coordinate,originalTarget,originalSampling.count);
1124
- if (!original.checked) return {checked:false,reason:original.reason,source:'original'};
1125
- const blocker=trajectory(blockerId,blockerPartName,blockerState.coordinate,blockerTarget,blockerSampling.count);
1126
- if (!blocker.checked) return {checked:false,reason:blocker.reason,source:'blocker'};
1127
-
1128
- const pairAt=(a,b)=>{
1129
- let intersections=0;
1130
- for(const left of a.colliders) for(const right of b.colliders) {
1131
- if(this.backend.shapesIntersect(
1132
- left.shapeRef,left.position.toArray(),left.rotation,
1133
- right.shapeRef,right.position.toArray(),right.rotation
1134
- )) intersections+=1;
1135
- }
1136
- return intersections;
1137
- };
1138
- const againstPose=(originalPoses,blockerPose)=>{
1139
- let conflictSamples=0,pairIntersections=0;
1140
- for(const originalPose of originalPoses) {
1141
- const pairs=pairAt(originalPose,blockerPose);
1142
- if (pairs) conflictSamples+=1;
1143
- pairIntersections+=pairs;
1144
- }
1145
- return {conflictSamples,pairIntersections};
1146
- };
1147
- const trajectoryConflict=(originalPoses,blockerPoses)=>{
1148
- let conflictSamplePairs=0,pairIntersections=0;
1149
- for(const originalPose of originalPoses) for(const blockerPose of blockerPoses) {
1150
- const pairs=pairAt(originalPose,blockerPose);
1151
- if (pairs) conflictSamplePairs+=1;
1152
- pairIntersections+=pairs;
1153
- }
1154
- return {conflictSamplePairs,pairIntersections};
1155
- };
1156
- const current=againstPose(original.poses,blocker.poses[0]);
1157
- const target=againstPose(original.poses,blocker.poses.at(-1));
1158
- const action=trajectoryConflict(original.poses,blocker.poses);
1159
- return {
1160
- checked:true,geometry:this.backend.evidenceGeometry('shape-pairs'),causal:false,frameAssumption:'parent-poses-static-during-hypothesis',
1161
- samples:{original:originalSampling.count,blocker:blockerSampling.count,mode:fixedSamples?'fixed':pairedSamples?'fixed-pair':'adaptive'},
1162
- sampling:{original:originalSampling,blocker:blockerSampling},
1163
- original:{id:originalId,partName:originalPartName,currentCoordinate:originalState.coordinate,target:originalTarget},
1164
- blocker:{id:blockerId,partName:blockerPartName,currentCoordinate:blockerState.coordinate,target:blockerTarget},
1165
- current,target,action,
1166
- targetSweepClear:target.conflictSamples===0,
1167
- conflictReduction:Math.max(0,current.conflictSamples-target.conflictSamples)
1168
- };
1169
- }
1170
-
1171
- articulationWorldCounterfactual(id, partName, target, { excludeObjectIds = [], excludeParts = [], samples = null } = {}) {
1172
- const state=this.getArticulationState(id,partName,{target});
1173
- if (!state || !Number.isFinite(target)) return {checked:false,reason:'JOINT_COORDINATE_UNAVAILABLE',id,partName};
1174
- const fixedSamples=Number.isFinite(samples) ? Math.max(2,Math.min(33,Math.trunc(samples))) : null;
1175
- const sampling=fixedSamples ? {checked:true,count:fixedSamples,mode:'fixed'} : this.articulationCounterfactualSampleCount(id,partName,state.coordinate,target);
1176
- if (!sampling.checked) return {checked:false,reason:sampling.reason,source:'sampling',id,partName};
1177
- const excluded=new Set([id,...excludeObjectIds]);
1178
- const excludedParts=new Set(excludeParts.map((item)=>`${item.objectId}:${item.partName || ROOT_PART}`));
1179
- const keyOf=(provenance,collider)=>{
1180
- const colliderKey=this.backend.colliderKey(collider);
1181
- if (provenance?.kind==='environment') return `environment:${provenance.environmentId || '$environment'}:${provenance.colliderIndex ?? colliderKey}`;
1182
- if (provenance?.kind==='object') return `object:${provenance.objectId}:${provenance.partName || ROOT_PART}:${provenance.colliderIndex ?? colliderKey}`;
1183
- return `unknown:${colliderKey}`;
1184
- };
1185
- const describe=(provenance,collider,key)=>provenance?.kind==='environment'
1186
- ? {key,kind:'environment',environmentId:provenance.environmentId || '$environment',colliderIndex:provenance.colliderIndex ?? null}
1187
- : provenance?.kind==='object'
1188
- ? {key,kind:'object',objectId:provenance.objectId,partName:provenance.partName || ROOT_PART,colliderIndex:provenance.colliderIndex ?? null}
1189
- : {key,kind:'unknown',colliderHandle:this.backend.colliderKey(collider)};
1190
- const poseHits=(pose)=>{
1191
- const hits=new Map();
1192
- for(const source of pose.colliders) {
1193
- this.backend.intersectionsWithShape(this.world,source.position.toArray(),source.rotation,source.shapeRef,(other)=>{
1194
- const provenance=this.provenanceOfCollider(other);
1195
- if (provenance?.kind==='object' && (excluded.has(provenance.objectId) || excludedParts.has(`${provenance.objectId}:${provenance.partName || ROOT_PART}`))) return true;
1196
- const key=keyOf(provenance,other);
1197
- if (!hits.has(key)) hits.set(key,describe(provenance,other,key));
1198
- return true;
1199
- });
1200
- }
1201
- return hits;
1202
- };
1203
- this.backend.syncSceneQueries(this.world);
1204
- const poses=[];
1205
- for(let i=0;i<sampling.count;i++) {
1206
- const alpha=i/(sampling.count-1);
1207
- const coordinate=state.coordinate+(target-state.coordinate)*alpha;
1208
- const pose=this.articulationColliderPoses(id,partName,coordinate);
1209
- if (!pose.checked) return {checked:false,reason:pose.reason,source:'trajectory',id,partName};
1210
- poses.push(pose);
1211
- }
1212
- const currentHits=poseHits(poses[0]);
1213
- const targetHits=poseHits(poses.at(-1));
1214
- const actionHits=new Map();
1215
- const sampleConflicts=[];
1216
- for(let sampleIndex=0;sampleIndex<poses.length;sampleIndex++) {
1217
- const hits=poseHits(poses[sampleIndex]);
1218
- if (hits.size) sampleConflicts.push({sampleIndex,coordinate:poses[sampleIndex].coordinate,blockers:[...hits.keys()]});
1219
- for(const [key,value] of hits) if (!actionHits.has(key)) actionHits.set(key,value);
1220
- }
1221
- const introduced=(hits)=>[...hits.entries()].filter(([key])=>!currentHits.has(key)).map(([,value])=>value);
1222
- const current=[...currentHits.values()];
1223
- const targetAll=[...targetHits.values()];
1224
- const actionAll=[...actionHits.values()];
1225
- const introducedTarget=introduced(targetHits);
1226
- const introducedAction=introduced(actionHits);
1227
- return {
1228
- checked:true,geometry:this.backend.evidenceGeometry('world-shape-query'),causal:false,
1229
- frameAssumption:'other-world-colliders-static-during-hypothesis',
1230
- id,partName,currentCoordinate:state.coordinate,target,
1231
- excludedObjectIds:[...excluded].sort(),excludedParts:[...excludedParts].sort(),
1232
- samples:{count:sampling.count,mode:fixedSamples?'fixed':'adaptive'},sampling,
1233
- current:{blockers:current},targetPose:{blockers:targetAll,introducedBlockers:introducedTarget},
1234
- actionEnvelope:{blockers:actionAll,introducedBlockers:introducedAction,sampleConflicts},
1235
- targetIntroducesNoCollision:introducedTarget.length===0,
1236
- actionIntroducesNoCollision:introducedAction.length===0
1237
- };
1238
- }
1239
-
1240
- articulationPairCounterfactualConvergence(originalId, originalPartName, originalTarget, blockerId, blockerPartName, blockerTarget, { multiplier = 2 } = {}) {
1241
- const base=this.articulationPairCounterfactual(originalId,originalPartName,originalTarget,blockerId,blockerPartName,blockerTarget);
1242
- if (!base.checked) return {checked:false,reason:base.reason || 'BASE_COUNTERFACTUAL_UNAVAILABLE',base};
1243
- const denserCount=(count)=>Math.min(33,Math.max(count+2,Math.ceil(count*Math.max(1.25,multiplier))));
1244
- const denseSamples={original:denserCount(base.samples.original),blocker:denserCount(base.samples.blocker)};
1245
- const dense=this.articulationPairCounterfactual(originalId,originalPartName,originalTarget,blockerId,blockerPartName,blockerTarget,{samples:denseSamples});
1246
- if (!dense.checked) return {checked:false,reason:dense.reason || 'DENSE_COUNTERFACTUAL_UNAVAILABLE',base,dense};
1247
- const ratio=(value,total)=>total>0?value/total:0;
1248
- const baseRatios={
1249
- current:ratio(base.current.conflictSamples,base.samples.original),
1250
- target:ratio(base.target.conflictSamples,base.samples.original),
1251
- action:ratio(base.action.conflictSamplePairs,base.samples.original*base.samples.blocker)
1252
- };
1253
- const denseRatios={
1254
- current:ratio(dense.current.conflictSamples,dense.samples.original),
1255
- target:ratio(dense.target.conflictSamples,dense.samples.original),
1256
- action:ratio(dense.action.conflictSamplePairs,dense.samples.original*dense.samples.blocker)
1257
- };
1258
- const drift={
1259
- current:Math.abs(baseRatios.current-denseRatios.current),
1260
- target:Math.abs(baseRatios.target-denseRatios.target),
1261
- action:Math.abs(baseRatios.action-denseRatios.action)
1262
- };
1263
- const qualitative={
1264
- targetSweepClear:base.targetSweepClear===dense.targetSweepClear,
1265
- clearanceGain:(base.conflictReduction>0)===(dense.conflictReduction>0)
1266
- };
1267
- return {
1268
- checked:true,causal:false,status:qualitative.targetSweepClear&&qualitative.clearanceGain?'stable':'unstable',
1269
- base,dense,
1270
- qualitative,
1271
- ratios:{base:baseRatios,dense:denseRatios,drift},
1272
- maxRatioDrift:Math.max(drift.current,drift.target,drift.action)
1273
- };
1274
- }
1275
-
1276
- ownerOfBody(body) {
1277
- const key=this.backend.bodyKey(body);
1278
- for (const [id,entry] of this.entries) {
1279
- if (this.backend.bodyKey(entry.body)===key) return {id,part:'$root'};
1280
- for (const [part,value] of entry.parts) if (this.backend.bodyKey(value.body)===key) return {id,part};
1281
- }
1282
- return null;
1283
- }
1284
-
1285
- raycast(origin, target, { excludeId = null, excludeIds = [] } = {}) {
1286
- if (!this.backend.hasCapability('scene-query')) return null;
1287
- const direction = [target[0] - origin[0], target[1] - origin[1], target[2] - origin[2]];
1288
- const distance = Math.hypot(...direction);
1289
- if (!Number.isFinite(distance) || distance < 1e-8 || !this.world) return null;
1290
- const normalized = direction.map((value) => value / distance);
1291
- const excluded = new Set([...(excludeId ? [excludeId] : []), ...excludeIds]);
1292
- const filter=excluded.size ? (collider)=>{
1293
- const parent=this.backend.colliderParent(collider);
1294
- const owner=parent ? this.ownerOfBody(parent) : null;
1295
- return !owner || !excluded.has(owner.id);
1296
- } : undefined;
1297
- const hit=this.backend.raycast(this.world,origin,normalized,distance,{solid:true,predicate:filter});
1298
- if(!hit) return null;
1299
- const body=this.backend.colliderParent(hit.collider);
1300
- const owner=body ? this.ownerOfBody(body) : null;
1301
- return {
1302
- id:owner?.id || null,
1303
- part:owner?.part || null,
1304
- environment:!owner,
1305
- provenance:this.provenanceOfCollider(hit.collider),
1306
- distance:hit.timeOfImpact,
1307
- point:[
1308
- origin[0] + normalized[0] * hit.timeOfImpact,
1309
- origin[1] + normalized[1] * hit.timeOfImpact,
1310
- origin[2] + normalized[2] * hit.timeOfImpact
1311
- ]
1312
- };
1313
- }
1314
-
1315
- faceCharacter(id, direction) {
1316
- const entry = this.entries.get(id);
1317
- if (!entry) return false;
1318
- const length = Math.hypot(direction[0], direction[2]);
1319
- if (length < 1e-8) return false;
1320
- const yaw = Math.atan2(-direction[0], -direction[2]);
1321
- if (!entry.body) return this.setCharacterYaw(id, yaw);
1322
- if (this.backend.bodyType(entry.body)!=='kinematic') return false;
1323
- this.backend.setBodyPose(entry.body,{rotation:[0,Math.sin(yaw/2),0,Math.cos(yaw/2)],next:true});
1324
- return true;
1325
- }
1326
-
1327
- setCharacterYaw(id, yaw) {
1328
- const entry = this.entries.get(id);
1329
- if (!entry || !Number.isFinite(yaw)) return false;
1330
- const rotation = new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0,1,0),yaw);
1331
- if (entry.body) {
1332
- if (this.backend.bodyType(entry.body)!=='kinematic') return false;
1333
- this.backend.setBodyPose(entry.body,{rotation});
1334
- this.backend.setBodyPose(entry.body,{rotation,next:true});
1335
- }
1336
- entry.root.quaternion.copy(rotation);
1337
- entry.lastRotation.copy(rotation);
1338
- entry.root.updateMatrixWorld(true);
1339
- return true;
1340
- }
1341
-
1342
- moveCharacter(id, desiredTranslation, { ignoreIds = [] } = {}) {
1343
- if (!this.backend.hasCapability('character-controller')) {
1344
- return { success:false, code:'PHYSICS_CAPABILITY_UNAVAILABLE', capability:'character-controller', movement:[0,0,0], grounded:false, collisions:[] };
1345
- }
1346
- const entry=this.entries.get(id);
1347
- if(!entry?.body || !this.characterController) {
1348
- return {success:false,code:'CHARACTER_BODY_UNAVAILABLE',movement:[0,0,0],grounded:false,collisions:[]};
1349
- }
1350
- const ignored=new Set(ignoreIds);
1351
- const result=this.backend.moveCharacter(this.characterController,entry.body,desiredTranslation,{
1352
- predicate:(other)=>{
1353
- const parent=this.backend.colliderParent(other);
1354
- const owner=parent ? this.ownerOfBody(parent) : null;
1355
- return !owner || !ignored.has(owner.id);
1356
- }
1357
- });
1358
- if(!result.success) return result;
1359
- return {
1360
- ...result,
1361
- collisions:result.collisions.map(({colliderKey,toi,normal})=>({colliderHandle:colliderKey,toi,normal}))
1362
- };
1363
- }
1364
-
1365
- setArticulationTarget(id, partName, target) {
1366
- const part = this.entries.get(id)?.parts.get(partName);
1367
- if (!part || !Number.isFinite(target)) return false;
1368
- if (!part.joint || !part.body) {
1369
- if (!this.hasCapability('articulation-pose')) return false;
1370
- const limits = part.spec.joint.limits || [];
1371
- if (limits.length === 2 && (target < limits[0] || target > limits[1])) return false;
1372
- const state = this.getArticulationState(id, partName);
1373
- if (!state) return false;
1374
- const axis = new THREE.Vector3(...state.localAxis).normalize();
1375
- if (part.spec.joint.type === 'prismatic') {
1376
- part.node.position.copy(part.restLocalPosition).addScaledVector(axis, target);
1377
- } else if (part.spec.joint.type === 'revolute') {
1378
- const rotation = new THREE.Quaternion().setFromAxisAngle(axis, target);
1379
- part.node.quaternion.copy(part.restLocalRotation).premultiply(rotation).normalize();
1380
- } else return false;
1381
- part.node.updateMatrixWorld(true);
1382
- part.lastLocalPosition.copy(part.node.position);
1383
- part.lastLocalRotation.copy(part.node.quaternion);
1384
- return true;
1385
- }
1386
- const motor=part.spec.joint.motor || {};
1387
- const applied=this.backend.setJointTarget(part.joint,target,motor);
1388
- if(!applied) return false;
1389
- part.motorTarget=target;
1390
- this.backend.wakeBody(part.body);
1391
- return true;
1392
- }
1393
-
1394
- holdArticulationCurrent(id, partName) {
1395
- const part = this.entries.get(id)?.parts.get(partName);
1396
- const state = this.getArticulationState(id,partName);
1397
- if (!part || !state) return false;
1398
- if (!part.joint || !part.body) return this.hasCapability('articulation-pose');
1399
- const motor=part.spec.joint.motor || {};
1400
- const applied=this.backend.setJointTarget(part.joint,state.coordinate,motor);
1401
- if(!applied) return false;
1402
- part.motorTarget=state.coordinate;
1403
- this.backend.wakeBody(part.body);
1404
- return true;
1405
- }
1406
-
1407
- getNavigationObstacles() {
1408
- if (!this.backend.hasCapability('collision')) return {items:[],skipped:[{reason:'physics-capability-unavailable',capability:'collision'}]};
1409
- this.backend.syncSceneQueries(this.world);
1410
- const items = [];
1411
- const skipped = [];
1412
- const addBody=(objectId,partName,body,bodyType,navigationObstacle=true)=>{
1413
- if(bodyType==='fixed' || navigationObstacle===false) return;
1414
- for(const [i,collider] of this.backend.colliders(body).entries()) {
1415
- const snapshot=this.backend.colliderSnapshot(collider);
1416
- const {shape,position,rotation}=snapshot;
1417
- const id=`${objectId}:${partName}:${i}`;
1418
- if(shape.kind==='box') {
1419
- const exact=upright(rotation);
1420
- items.push({
1421
- id,objectId,part:partName,collider:i,shape:'box',sourceShape:'box',quality:exact?'exact-yaw':'conservative-aabb',
1422
- position:array3(position),
1423
- halfExtents:exact?array3(shape.halfExtents):boxAabbHalfExtents(shape.halfExtents,rotation),
1424
- angle:exact?yaw(rotation):0
1425
- });
1426
- } else if(shape.kind==='cylinder') {
1427
- if(upright(rotation)) {
1428
- items.push({id,objectId,part:partName,collider:i,shape:'cylinder',sourceShape:'cylinder',quality:'exact-upright',position:[position.x,position.y-shape.halfHeight,position.z],radius:shape.radius,height:shape.halfHeight*2});
1429
- } else {
1430
- items.push({id,objectId,part:partName,collider:i,shape:'box',sourceShape:'cylinder',quality:'conservative-aabb',position:array3(position),halfExtents:cylinderAabbHalfExtents(shape.radius,shape.halfHeight,rotation),angle:0});
1431
- }
1432
- } else if(shape.kind==='capsule') {
1433
- const extentY=shape.halfHeight+shape.radius;
1434
- if(upright(rotation)) {
1435
- items.push({id,objectId,part:partName,collider:i,shape:'cylinder',sourceShape:'capsule',quality:'conservative-upright',position:[position.x,position.y-extentY,position.z],radius:shape.radius,height:extentY*2});
1436
- } else {
1437
- items.push({id,objectId,part:partName,collider:i,shape:'box',sourceShape:'capsule',quality:'conservative-aabb',position:array3(position),halfExtents:capsuleAabbHalfExtents(shape.radius,shape.halfHeight,rotation),angle:0});
1438
- }
1439
- } else if(shape.kind==='convexHull' && shape.vertices?.length) {
1440
- const box=convexAabb(shape.vertices,new THREE.Vector3(position.x,position.y,position.z),rotation);
1441
- items.push({id,objectId,part:partName,collider:i,shape:'box',sourceShape:'convexHull',quality:'conservative-aabb',...box,angle:0});
1442
- } else {
1443
- skipped.push({id,objectId,part:partName,collider:i,reason:'unsupported-shape',shapeType:shape.kind});
1444
- }
1445
- }
1446
- };
1447
-
1448
- for (const [id, entry] of this.entries) {
1449
- if (!entry.held) addBody(id, '$root', entry.body, entry.rootSpec.body || 'fixed', entry.rootSpec.navigationObstacle);
1450
- for (const [partName, part] of entry.parts) addBody(id, partName, part.body, part.spec.physics?.body || 'dynamic');
1451
- }
1452
- return { items, skipped };
1453
- }
1454
-
1455
- articulationContacts(id, partName) {
1456
- if (!this.backend.hasCapability('collision')) return [];
1457
- const entry=this.entries.get(id);
1458
- const part=entry?.parts.get(partName);
1459
- const body = partName === ROOT_PART ? entry?.body : part?.body;
1460
- if (!entry || !body || !this.world) return [];
1461
- const contacts=[];
1462
- for(const [sourceIndex,source] of this.backend.colliders(body).entries()) {
1463
- const sourceOwner=this.provenanceOfCollider(source) || {kind:'object',objectId:id,partName,colliderIndex:sourceIndex};
1464
- for(const pair of this.backend.contactPairs(this.world,source)) {
1465
- const target=this.provenanceOfCollider(pair.other);
1466
- const external=!target || target.kind==='environment' || target.objectId!==id;
1467
- contacts.push({
1468
- source:sourceOwner,
1469
- target:target || {kind:'unknown',colliderIndex:null},
1470
- external,
1471
- manifoldCount:pair.manifoldCount,
1472
- contactCount:pair.contactCount,
1473
- activeContactCount:pair.activeContactCount,
1474
- minDistance:pair.minDistance,
1475
- totalImpulse:Number.isFinite(pair.totalImpulse)?pair.totalImpulse:null,
1476
- evidenceKind:pair.evidenceKind || 'contact',
1477
- impulseAvailable:pair.impulseAvailable===true,
1478
- normal:pair.normal
1479
- });
1480
- }
1481
- }
1482
- contacts.sort((a,b)=>{
1483
- const ak=`${a.target.kind}:${a.target.objectId || a.target.environmentId || ''}:${a.target.partName || ''}:${a.target.colliderIndex ?? -1}:${a.source.colliderIndex}`;
1484
- const bk=`${b.target.kind}:${b.target.objectId || b.target.environmentId || ''}:${b.target.partName || ''}:${b.target.colliderIndex ?? -1}:${b.source.colliderIndex}`;
1485
- return ak.localeCompare(bk);
1486
- });
1487
- return contacts;
1488
- }
1489
-
1490
- articulationPenetrations(id, partName, { refresh = false } = {}) {
1491
- if (!this.backend.hasCapability('collision')) return [];
1492
- if(refresh) this.backend.syncSceneQueries(this.world);
1493
- const entry=this.entries.get(id);
1494
- const part=entry?.parts.get(partName);
1495
- if(!entry || !part) return [];
1496
- const owners=new Map([[this.backend.bodyKey(entry.body),'$root']]);
1497
- for(const [name,value] of entry.parts) owners.set(this.backend.bodyKey(value.body),name);
1498
- const hits=new Map();
1499
-
1500
- for(const [i,source] of this.backend.colliders(part.body).entries()) {
1501
- for(const penetration of this.backend.penetrations(this.world,source)) {
1502
- const otherBody=this.backend.colliderParent(penetration.other);
1503
- if(!otherBody || this.backend.bodyKey(otherBody)===this.backend.bodyKey(part.body)) continue;
1504
- const targetPart=owners.get(this.backend.bodyKey(otherBody)) || '$external';
1505
- const targetColliders=this.backend.colliders(otherBody);
1506
- const otherKey=this.backend.colliderKey(penetration.other);
1507
- const targetIndex=targetColliders.findIndex((collider)=>this.backend.colliderKey(collider)===otherKey);
1508
- const key=`${partName}[${i}]->${targetPart}[${targetIndex}]`;
1509
- const depth=-penetration.distance;
1510
- const previous=hits.get(key);
1511
- if(!previous || depth>previous.depth) hits.set(key,{key,depth,sourcePart:partName,sourceCollider:i,targetPart,targetCollider:targetIndex});
1512
- }
1513
- }
1514
- return [...hits.values()];
1515
- }
1516
-
1517
- dispose() {
1518
- this.entries.clear();
1519
- this.colliderProvenance.clear();
1520
- this.colliderHandles.clear();
1521
- this.colliderRuntime.clear();
1522
- this.collisionPairs.clear();
1523
- this.collisionEvents.length=0;
1524
- this.collisionGroupBits.clear();
1525
- if(this.world && this.characterController) this.backend.removeCharacterController(this.world,this.characterController);
1526
- this.characterController = null;
1527
- this.backend.dispose(this.world);
1528
- this.world = null;
1529
- }
1530
-
1531
- step(dt, store) {
1532
- this.backend.step(this.world, dt);
1533
- this.updateCollisionEvents();
1534
- return this.writeback(store);
1535
- }
1536
-
1537
- getCollisionEvents({ clear = true } = {}) {
1538
- const events=this.collisionEvents.map((event)=>structuredClone(event));
1539
- if(clear) this.collisionEvents.length=0;
1540
- return events;
1541
- }
1542
-
1543
- updateCollisionEvents() {
1544
- if(!this.world || !this.backend.hasCapability('collision')) return;
1545
- const watched=[...this.colliderRuntime.entries()].filter(([,runtime])=>runtime.sensor || runtime.collisionEvents);
1546
- if(!watched.length) { this.collisionPairs.clear(); return; }
1547
- this.backend.syncSceneQueries(this.world);
1548
- const current=new Map();
1549
- const descriptor=(key)=>{
1550
- const p=this.colliderProvenance.get(key);
1551
- if(!p) return {kind:'unknown',colliderKey:key};
1552
- if(p.kind==='environment') return {kind:'environment',environmentId:p.environmentId || '$environment',colliderIndex:p.colliderIndex ?? null};
1553
- return {kind:'object',objectId:p.objectId,partName:p.partName || ROOT_PART,colliderIndex:p.colliderIndex ?? null};
1554
- };
1555
- const addPair=(leftKey,rightKey)=>{
1556
- if(leftKey==null || rightKey==null || leftKey===rightKey) return;
1557
- const a=leftKey<rightKey?leftKey:rightKey,b=leftKey<rightKey?rightKey:leftKey,key=String(a)+':'+String(b);
1558
- if(current.has(key)) return;
1559
- const ar=this.colliderRuntime.get(a),br=this.colliderRuntime.get(b);
1560
- if(!this._collisionPairAllowed(ar,br)) return;
1561
- current.set(key,{key,sensor:Boolean(ar?.sensor || br?.sensor),a:descriptor(a),b:descriptor(b)});
1562
- };
1563
- for(const [sourceKey,sourceRuntime] of watched) {
1564
- const source=this.colliderHandles.get(sourceKey);
1565
- if(!source) continue;
1566
- if(sourceRuntime.sensor) {
1567
- const snapshot=this.backend.colliderSnapshot(source);
1568
- if(!snapshot) continue;
1569
- this.backend.intersectionsWithShape(this.world,snapshot.position,snapshot.rotation,snapshot.shapeRef,(other)=>{
1570
- const otherKey=this.backend.colliderKey(other);
1571
- const otherBody=this.backend.colliderParent(other),sourceBody=this.backend.colliderParent(source);
1572
- if(otherKey!==sourceKey && this.backend.bodyKey(otherBody)!==this.backend.bodyKey(sourceBody)) addPair(sourceKey,otherKey);
1573
- return true;
1574
- },{excludeCollider:source});
1575
- } else {
1576
- for(const pair of this.backend.contactPairs(this.world,source)) addPair(sourceKey,this.backend.colliderKey(pair.other));
1577
- }
1578
- }
1579
- for(const [key,pair] of current) if(!this.collisionPairs.has(key)) this.collisionEvents.push({type:pair.sensor?'sensor-entered':'collision-started',a:pair.a,b:pair.b});
1580
- for(const [key,pair] of this.collisionPairs) if(!current.has(key)) this.collisionEvents.push({type:pair.sensor?'sensor-exited':'collision-ended',a:pair.a,b:pair.b});
1581
- this.collisionPairs=current;
1582
- }
1583
-
1584
- writeback(store) {
1585
- let changed = false;
1586
- if (!this.solverEnabled) {
1587
- for (const [id, entry] of this.entries) {
1588
- const record = store.has(id) ? store.get(id) : null;
1589
- if (!record) continue;
1590
- record.object.updateMatrixWorld(true);
1591
- const p = new THREE.Vector3();
1592
- const q = new THREE.Quaternion();
1593
- record.object.getWorldPosition(p);
1594
- record.object.getWorldQuaternion(q);
1595
- if (p.distanceToSquared(entry.lastPosition) > 1e-10 || 1 - Math.abs(q.dot(entry.lastRotation)) > 1e-10) changed = true;
1596
- entry.lastPosition.copy(p);
1597
- entry.lastRotation.copy(q);
1598
- for (const part of entry.parts.values()) {
1599
- if (part.node.position.distanceToSquared(part.lastLocalPosition) > 1e-10 || 1 - Math.abs(part.node.quaternion.dot(part.lastLocalRotation)) > 1e-10) changed = true;
1600
- part.lastLocalPosition.copy(part.node.position);
1601
- part.lastLocalRotation.copy(part.node.quaternion);
1602
- }
1603
- }
1604
- return changed;
1605
- }
1606
-
1607
- for (const [id, entry] of this.entries) {
1608
- const record = store.has(id) ? store.get(id) : null;
1609
- if (!record) continue;
1610
-
1611
- if (this.backend.bodyType(entry.body)!=='fixed') {
1612
- const pose=this.backend.bodyPose(entry.body);
1613
- const p={x:pose.position[0],y:pose.position[1],z:pose.position[2]};
1614
- const q={x:pose.rotation[0],y:pose.rotation[1],z:pose.rotation[2],w:pose.rotation[3]};
1615
- const dx=p.x-entry.lastPosition.x;
1616
- const dy=p.y-entry.lastPosition.y;
1617
- const dz=p.z-entry.lastPosition.z;
1618
- const rotationDot=Math.abs(
1619
- entry.lastRotation.x*q.x+entry.lastRotation.y*q.y+
1620
- entry.lastRotation.z*q.z+entry.lastRotation.w*q.w
1621
- );
1622
- if(dx*dx+dy*dy+dz*dz>1e-10 || 1-rotationDot>1e-10) changed=true;
1623
- record.object.position.set(p.x,p.y,p.z);
1624
- record.object.quaternion.set(q.x,q.y,q.z,q.w);
1625
- entry.lastPosition.set(p.x,p.y,p.z);
1626
- entry.lastRotation.set(q.x,q.y,q.z,q.w);
1627
- }
1628
-
1629
- for (const part of entry.parts.values()) {
1630
- const pose=this.backend.bodyPose(part.body);
1631
- const p={x:pose.position[0],y:pose.position[1],z:pose.position[2]};
1632
- const q={x:pose.rotation[0],y:pose.rotation[1],z:pose.rotation[2],w:pose.rotation[3]};
1633
- this.partWorldRotation.set(q.x,q.y,q.z,q.w);
1634
- this.partWorldPosition.set(p.x,p.y,p.z);
1635
- const parentNode = part.node.parent;
1636
- if (parentNode) {
1637
- parentNode.updateWorldMatrix(true, false);
1638
- parentNode.getWorldPosition(this.parentWorldPosition);
1639
- parentNode.getWorldQuaternion(this.parentWorldRotation);
1640
- this.inverseParentWorldRotation.copy(this.parentWorldRotation).invert();
1641
- this.partLocalRotation.copy(this.inverseParentWorldRotation).multiply(this.partWorldRotation);
1642
- this.partLocalPosition.copy(this.partWorldPosition).sub(this.parentWorldPosition).applyQuaternion(this.inverseParentWorldRotation);
1643
- } else {
1644
- this.partLocalRotation.copy(this.partWorldRotation);
1645
- this.partLocalPosition.copy(this.partWorldPosition);
1646
- }
1647
- if (1 - Math.abs(part.lastLocalRotation.dot(this.partLocalRotation)) > 1e-10 || part.lastLocalPosition.distanceToSquared(this.partLocalPosition) > 1e-10) changed = true;
1648
- part.node.quaternion.copy(this.partLocalRotation);
1649
- part.node.position.copy(this.partLocalPosition);
1650
- part.node.updateMatrixWorld(false);
1651
- part.lastLocalRotation.copy(this.partLocalRotation);
1652
- part.lastLocalPosition.copy(this.partLocalPosition);
1653
- }
1654
- }
1655
- return changed;
1656
- }
1657
- }