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