threedog 0.7.0 → 0.8.0

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 (544) hide show
  1. package/CHANGELOG.md +196 -1
  2. package/README.md +6 -9
  3. package/core/{Animator.js → assets/Animator.js} +28 -18
  4. package/core/{Assets.js → assets/Assets.js} +98 -54
  5. package/core/{Baked.js → assets/Baked.js} +4 -4
  6. package/core/assets/assetEntry.js +237 -0
  7. package/core/{assetHot.js → assets/assetHot.js} +7 -6
  8. package/core/{assetLoad.js → assets/assetLoad.js} +55 -16
  9. package/core/assets/assetLod.js +113 -0
  10. package/core/{assetManifest.js → assets/assetManifest.js} +19 -11
  11. package/core/{assetReport.js → assets/assetReport.js} +6 -12
  12. package/core/{namedModel.js → assets/namedModel.js} +17 -13
  13. package/core/{Audio.js → audio/Audio.js} +26 -23
  14. package/core/{audioRules.js → audio/audioRules.js} +8 -5
  15. package/core/{audioVoice.js → audio/audioVoice.js} +17 -30
  16. package/core/{Events.js → base/Events.js} +3 -3
  17. package/core/{I18n.js → base/I18n.js} +10 -10
  18. package/core/{Random.js → base/Random.js} +5 -4
  19. package/core/{easing.js → base/easing.js} +1 -1
  20. package/core/{errorCodes.js → base/errorCodes.js} +98 -110
  21. package/core/{errorHints.js → base/errorHints.js} +5 -9
  22. package/core/{errors.js → base/errors.js} +6 -6
  23. package/core/{events.generated.js → base/events.generated.js} +1 -0
  24. package/core/{math.js → base/math.js} +15 -4
  25. package/core/{params.js → base/params.js} +3 -4
  26. package/core/base/util.js +32 -0
  27. package/core/{validate.js → base/validate.js} +28 -7
  28. package/core/{Engine.js → engine/Engine.js} +80 -77
  29. package/core/{Loading.js → engine/Loading.js} +4 -2
  30. package/core/{copies.js → engine/copies.js} +4 -4
  31. package/core/{headlessLoad.js → engine/headlessLoad.js} +4 -4
  32. package/core/{lifecycle.js → engine/lifecycle.js} +14 -12
  33. package/core/{loop.js → engine/loop.js} +68 -47
  34. package/core/{moduleSlots.js → engine/moduleSlots.js} +6 -6
  35. package/core/{moduleTypes.js → engine/moduleTypes.js} +13 -14
  36. package/core/{modules.js → engine/modules.js} +14 -11
  37. package/core/{page.js → engine/page.js} +36 -23
  38. package/core/{plugins.js → engine/plugins.js} +6 -9
  39. package/core/{services.js → engine/services.js} +47 -40
  40. package/core/{startup.js → engine/startup.js} +26 -24
  41. package/core/{Input.js → input/Input.js} +30 -22
  42. package/core/{inputContext.js → input/inputContext.js} +14 -5
  43. package/core/{inputPad.js → input/inputPad.js} +1 -1
  44. package/core/{inputPointer.js → input/inputPointer.js} +8 -2
  45. package/core/{inputTouch.js → input/inputTouch.js} +1 -1
  46. package/core/{Budget.js → inspect/Budget.js} +21 -20
  47. package/core/{DebugOverrides.js → inspect/DebugOverrides.js} +30 -16
  48. package/core/{Describe.js → inspect/Describe.js} +26 -22
  49. package/core/{Inspect.js → inspect/Inspect.js} +9 -7
  50. package/core/{InspectMaterials.js → inspect/InspectMaterials.js} +7 -8
  51. package/core/{InspectPerf.js → inspect/InspectPerf.js} +19 -13
  52. package/core/{InspectScene.js → inspect/InspectScene.js} +8 -5
  53. package/core/{MaterialInfo.js → inspect/MaterialInfo.js} +3 -2
  54. package/core/{UrlState.js → inspect/UrlState.js} +52 -20
  55. package/core/{catalog.js → inspect/catalog.js} +3 -3
  56. package/core/{checks.js → inspect/checks.js} +7 -5
  57. package/core/{debugView.js → inspect/debugView.js} +4 -4
  58. package/core/{describeRender.js → inspect/describeRender.js} +21 -20
  59. package/core/{describeText.js → inspect/describeText.js} +11 -6
  60. package/core/inspect/geometryWatch.js +38 -0
  61. package/core/{lightWatch.js → inspect/lightWatch.js} +8 -8
  62. package/core/{pictureWriters.js → inspect/pictureWriters.js} +15 -16
  63. package/core/{shaderCost.js → inspect/shaderCost.js} +1 -1
  64. package/core/{Ops.js → ops/Ops.js} +16 -11
  65. package/core/{control.js → ops/control.js} +13 -12
  66. package/core/ops/holds.js +139 -0
  67. package/core/{opsAtomic.js → ops/opsAtomic.js} +2 -1
  68. package/core/{opsCheck.js → ops/opsCheck.js} +4 -5
  69. package/core/{opsGuard.js → ops/opsGuard.js} +3 -3
  70. package/core/{opsRun.js → ops/opsRun.js} +7 -4
  71. package/core/{owned.js → ops/owned.js} +14 -17
  72. package/core/{sharedPoint.js → ops/sharedPoint.js} +8 -8
  73. package/core/{stackFrames.js → ops/stackFrames.js} +2 -2
  74. package/core/{stacks.js → ops/stacks.js} +12 -14
  75. package/core/{wrap.js → ops/wrap.js} +8 -6
  76. package/core/{SaveStore.js → saves/SaveStore.js} +1 -1
  77. package/core/{Saves.js → saves/Saves.js} +58 -36
  78. package/core/{saveApply.js → saves/saveApply.js} +13 -9
  79. package/core/{saveFiles.js → saves/saveFiles.js} +17 -15
  80. package/core/{saveValues.js → saves/saveValues.js} +20 -3
  81. package/core/{saveVersions.js → saves/saveVersions.js} +4 -17
  82. package/core/{session.js → saves/session.js} +31 -17
  83. package/core/{Rays.js → scene/Rays.js} +23 -25
  84. package/core/{Views.js → scene/Views.js} +14 -6
  85. package/core/{adaptive.js → scene/adaptive.js} +15 -8
  86. package/core/{canvasBox.js → scene/canvasBox.js} +2 -3
  87. package/core/{engineCamera.js → scene/engineCamera.js} +1 -1
  88. package/core/{gameLights.js → scene/gameLights.js} +17 -7
  89. package/core/{grayMap.js → scene/grayMap.js} +8 -2
  90. package/core/{grid.js → scene/grid.js} +4 -4
  91. package/core/{gridLoad.js → scene/gridLoad.js} +1 -1
  92. package/core/{ground.js → scene/ground.js} +9 -9
  93. package/core/{movement.js → scene/movement.js} +3 -3
  94. package/core/{pictureSlots.js → scene/pictureSlots.js} +2 -2
  95. package/core/{sceneDelta.js → scene/sceneDelta.js} +2 -2
  96. package/core/{sceneMethods.js → scene/sceneMethods.js} +36 -13
  97. package/core/scene/stepPoses.js +55 -0
  98. package/core/{targeting.js → scene/targeting.js} +4 -5
  99. package/core/{thingExplain.js → scene/thingExplain.js} +6 -5
  100. package/core/{thingOps.js → scene/thingOps.js} +4 -3
  101. package/core/{things.js → scene/things.js} +18 -5
  102. package/core/{threePatches.js → scene/threePatches.js} +1 -1
  103. package/core/{view.js → scene/view.js} +17 -16
  104. package/core/{Batching.js → stream/Batching.js} +85 -27
  105. package/core/{Stream.js → stream/Stream.js} +60 -30
  106. package/core/{batchGroups.js → stream/batchGroups.js} +10 -9
  107. package/core/{chunkStream.js → stream/chunkStream.js} +40 -0
  108. package/core/{scatter.js → stream/scatter.js} +2 -2
  109. package/core/{streamSources.js → stream/streamSources.js} +12 -7
  110. package/core/{Commits.js → threads/Commits.js} +6 -5
  111. package/core/{Jobs.js → threads/Jobs.js} +12 -10
  112. package/core/{Threads.js → threads/Threads.js} +16 -16
  113. package/core/{threadPure.js → threads/threadPure.js} +7 -5
  114. package/core/{threadServe.js → threads/threadServe.js} +3 -3
  115. package/core/{Clock.js → time/Clock.js} +17 -10
  116. package/core/{dayTime.js → time/dayTime.js} +5 -1
  117. package/core/{skip.js → time/skip.js} +18 -17
  118. package/core/{time.js → time/time.js} +18 -12
  119. package/core/{uiClock.js → time/uiClock.js} +4 -4
  120. package/docs/AI.md +22 -19
  121. package/docs/API.md +24 -23
  122. package/docs/CODEMAP.md +76 -183
  123. package/docs/COMMANDS.md +66 -58
  124. package/docs/CONVENTIONS.md +54 -14
  125. package/docs/MIGRATING-0.8.md +169 -0
  126. package/docs/THREE.md +78 -29
  127. package/docs/api/assets.md +12 -13
  128. package/docs/api/audio.md +6 -5
  129. package/docs/api/budget.md +4 -4
  130. package/docs/api/calendar.md +10 -11
  131. package/docs/api/cameraRig.md +29 -29
  132. package/docs/api/characters.md +23 -18
  133. package/docs/api/clock.md +1 -1
  134. package/docs/api/collision.md +12 -9
  135. package/docs/api/content.md +6 -6
  136. package/docs/api/dialogue.md +3 -3
  137. package/docs/api/engine.md +45 -43
  138. package/docs/api/events.md +3 -2
  139. package/docs/api/flow.md +1 -1
  140. package/docs/api/grids.md +1 -1
  141. package/docs/api/ground.md +4 -5
  142. package/docs/api/hud.md +2 -2
  143. package/docs/api/i18n.md +6 -6
  144. package/docs/api/input.md +7 -7
  145. package/docs/api/interactions.md +4 -4
  146. package/docs/api/inventory.md +9 -9
  147. package/docs/api/jobs.md +5 -5
  148. package/docs/api/level.md +7 -7
  149. package/docs/api/lightPool.md +1 -6
  150. package/docs/api/music.md +3 -3
  151. package/docs/api/nav.md +10 -10
  152. package/docs/api/openWorld.md +1 -1
  153. package/docs/api/particles.md +2 -2
  154. package/docs/api/photo.md +4 -2
  155. package/docs/api/pickups.md +2 -2
  156. package/docs/api/post.md +20 -3
  157. package/docs/api/quests.md +3 -3
  158. package/docs/api/rays.md +5 -7
  159. package/docs/api/rigid.md +27 -18
  160. package/docs/api/saves.md +8 -7
  161. package/docs/api/settings.md +9 -8
  162. package/docs/api/sky.md +8 -7
  163. package/docs/api/stream.md +7 -7
  164. package/docs/api/swarm.md +34 -0
  165. package/docs/api/terrain.md +7 -8
  166. package/docs/api/terrainDraw.md +1 -1
  167. package/docs/api/timeline.md +2 -2
  168. package/docs/api/tools.md +25 -22
  169. package/docs/api/vars.md +1 -1
  170. package/docs/api/vegetation.md +4 -3
  171. package/docs/api/vegetationDraw.md +1 -1
  172. package/docs/api/water.md +1 -1
  173. package/docs/api/weather.md +9 -9
  174. package/docs/api/weatherDraw.md +3 -3
  175. package/docs/api/world.md +5 -5
  176. package/docs/recipes/01-new-game.md +25 -40
  177. package/docs/recipes/02-npc.md +19 -20
  178. package/docs/recipes/03-items-pickups.md +27 -43
  179. package/docs/recipes/04-quests.md +3 -4
  180. package/docs/recipes/05-props-bake.md +29 -39
  181. package/docs/recipes/06-clock-events.md +27 -18
  182. package/docs/recipes/07-flow-scenes-pause.md +12 -17
  183. package/docs/recipes/08-weather-sky.md +88 -34
  184. package/docs/recipes/09-materials-lights-models.md +22 -36
  185. package/docs/recipes/10-blender-level.md +6 -7
  186. package/docs/recipes/11-vehicles.md +30 -22
  187. package/docs/recipes/12-navmesh.md +9 -8
  188. package/docs/recipes/13-animation.md +39 -17
  189. package/docs/recipes/14-custom-module.md +14 -13
  190. package/docs/recipes/15-perf.md +49 -26
  191. package/docs/recipes/16-dev-bridge.md +32 -52
  192. package/docs/recipes/18-world.md +36 -23
  193. package/docs/recipes/19-shooting-picking.md +4 -2
  194. package/docs/recipes/20-content-actions-save.md +30 -35
  195. package/docs/recipes/21-camera.md +33 -5
  196. package/docs/recipes/22-shop-gold.md +0 -4
  197. package/docs/recipes/23-ops.md +10 -10
  198. package/docs/recipes/26-ui-parts.md +22 -12
  199. package/docs/recipes/27-net.md +0 -2
  200. package/docs/recipes/28-terrain.md +117 -21
  201. package/docs/recipes/29-grid.md +2 -2
  202. package/docs/recipes/30-templates.md +55 -19
  203. package/docs/recipes/31-audio.md +5 -5
  204. package/docs/recipes/32-action-game.md +15 -6
  205. package/docs/recipes/33-stream-sources.md +2 -2
  206. package/docs/recipes/34-environment-lighting.md +67 -19
  207. package/docs/recipes/35-picture-from-reference.md +10 -17
  208. package/docs/recipes/36-ground-plants.md +105 -0
  209. package/docs/recipes/40-scene.md +7 -11
  210. package/docs/recipes/43-shader-patches-surfaces.md +20 -41
  211. package/docs/recipes/44-water-weather-hooks.md +48 -43
  212. package/docs/recipes/45-cascaded-shadows.md +39 -17
  213. package/docs/recipes/46-blender-art-route.md +7 -8
  214. package/docs/recipes/49-game-module-contract.md +5 -5
  215. package/docs/recipes/50-own-renderer.md +2 -2
  216. package/docs/recipes/52-around-the-picture.md +54 -98
  217. package/docs/recipes/53-ground-up-close.md +61 -24
  218. package/docs/recipes/55-mods-time-wrap.md +12 -16
  219. package/docs/recipes/56-webgpu-tsl.md +16 -14
  220. package/docs/recipes/57-control.md +9 -2
  221. package/docs/recipes/58-input.md +2 -2
  222. package/docs/recipes/59-depth-post-effects.md +1 -1
  223. package/docs/recipes/60-judge-the-picture.md +29 -24
  224. package/docs/recipes/62-picture-code.md +49 -17
  225. package/docs/recipes/63-third-person-start.md +17 -4
  226. package/docs/recipes/64-particles.md +1 -1
  227. package/docs/recipes/65-swarm.md +140 -0
  228. package/examples/action/.threedog/content-index.json +1 -1
  229. package/examples/action/GAMEMAP.md +2 -2
  230. package/examples/{sheepisland → perf-island}/.threedog/content-index.json +1 -1
  231. package/examples/{sheepisland → perf-island}/GAMEMAP.md +12 -11
  232. package/examples/{sheepisland → perf-island}/assets.js +1 -1
  233. package/examples/{sheepisland → perf-island}/main.js +8 -8
  234. package/examples/{sheepisland → perf-island}/models.js +1 -1
  235. package/examples/{sheepisland → perf-island}/params.js +1 -1
  236. package/examples/{sheepisland → perf-island}/picture/index.js +1 -1
  237. package/examples/{sheepisland → perf-island}/picture/palette.js +2 -2
  238. package/examples/{sheepisland → perf-island}/views.js +1 -1
  239. package/examples/plain-picture/GAMEMAP.md +1 -0
  240. package/examples/rc2d/GAMEMAP.md +3 -2
  241. package/examples/rc2d/main.js +1 -3
  242. package/examples/styletest/.threedog/content-index.json +1 -1
  243. package/examples/styletest/GAMEMAP.md +3 -2
  244. package/examples/techniques/contact-shadows/contactShadows.js +1 -1
  245. package/examples/techniques/contact-shadows/main.js +1 -1
  246. package/examples/techniques/interior-light/main.js +1 -1
  247. package/examples/techniques/modular-building/README.md +7 -6
  248. package/examples/techniques/outlines-and-rim/picture/post.js +1 -1
  249. package/examples/techniques/procedural-animation/README.md +1 -1
  250. package/examples/webgpu-tsl/GAMEMAP.md +1 -0
  251. package/examples/world/.threedog/content-index.json +1 -1
  252. package/examples/world/GAMEMAP.md +4 -3
  253. package/examples/world/picture/sky.js +1 -1
  254. package/index.d.ts +8 -7
  255. package/index.js +31 -31
  256. package/llms.txt +9 -13
  257. package/modules/ambience/Ambience.js +11 -8
  258. package/modules/calendar/Calendar.js +19 -19
  259. package/modules/calendar/index.js +13 -13
  260. package/modules/calendar/schedule.js +11 -6
  261. package/modules/calendar/seasons.js +7 -7
  262. package/modules/camera/FirstPersonCamera.js +2 -2
  263. package/modules/camera/FixedCamera.js +14 -15
  264. package/modules/camera/FollowCamera.js +4 -4
  265. package/modules/camera/RtsCamera.js +11 -11
  266. package/modules/camera/common.js +48 -24
  267. package/modules/camera/contract.js +1 -0
  268. package/modules/camera/projection.js +2 -2
  269. package/modules/characters/Character.js +33 -30
  270. package/modules/characters/NPC.js +27 -19
  271. package/modules/characters/assetModel.js +14 -10
  272. package/modules/characters/astar.js +7 -5
  273. package/modules/characters/behaviors.js +4 -5
  274. package/modules/characters/contract.js +2 -2
  275. package/modules/characters/index.js +168 -214
  276. package/modules/characters/moveHelpers.js +14 -3
  277. package/modules/characters/movers/common.js +16 -14
  278. package/modules/characters/movers/manual.js +1 -1
  279. package/modules/characters/movers/rapier.js +7 -6
  280. package/modules/characters/movers/simple.js +3 -3
  281. package/modules/characters/movers/support.js +8 -8
  282. package/modules/characters/npcAvoid.js +4 -4
  283. package/modules/characters/npcSim.js +23 -17
  284. package/modules/characters/npcView.js +6 -5
  285. package/modules/characters/pathAsync.js +12 -10
  286. package/modules/characters/pathWorker.js +1 -1
  287. package/modules/characters/player.js +108 -0
  288. package/modules/characters/playerStrings.js +2 -2
  289. package/modules/characters/proceduralRig.js +2 -2
  290. package/modules/characters/useModel.js +3 -3
  291. package/modules/characters/walkTo.js +11 -17
  292. package/modules/collision/Collision.js +26 -20
  293. package/modules/collision/contract.js +15 -0
  294. package/modules/content/explain.js +1 -2
  295. package/modules/content/fields.js +24 -3
  296. package/modules/content/ids.js +2 -2
  297. package/modules/content/index.js +61 -99
  298. package/modules/content/loader.js +14 -17
  299. package/modules/content/markers.js +25 -0
  300. package/modules/content/models.js +10 -7
  301. package/modules/content/packs.js +3 -3
  302. package/modules/content/parts.js +2 -2
  303. package/modules/content/places.js +35 -0
  304. package/modules/content/props.js +17 -14
  305. package/modules/content/rules.js +25 -21
  306. package/modules/content/stages.js +7 -7
  307. package/modules/content/templates.js +20 -20
  308. package/modules/content/words.js +34 -0
  309. package/modules/debug/DebugPanel.js +10 -43
  310. package/modules/flow/contract.js +1 -1
  311. package/modules/flow/index.js +11 -7
  312. package/modules/gameplay/Container.js +12 -11
  313. package/modules/gameplay/Containers.js +14 -5
  314. package/modules/gameplay/Dialogue.js +13 -11
  315. package/modules/gameplay/Interactions.js +37 -24
  316. package/modules/gameplay/Inventory.js +8 -9
  317. package/modules/gameplay/Quests.js +16 -9
  318. package/modules/gameplay/boxOps.js +1 -1
  319. package/modules/gameplay/dialogueBubbles.js +3 -4
  320. package/modules/gameplay/inventoryOps.js +0 -1
  321. package/modules/gameplay/pickups.js +22 -23
  322. package/modules/gameplay/questSave.js +3 -3
  323. package/modules/grid/Grid.js +1 -1
  324. package/modules/grid/Layer.js +4 -4
  325. package/modules/grid/index.js +7 -8
  326. package/modules/grid/preview.js +7 -7
  327. package/modules/grid/tiles.js +6 -6
  328. package/modules/hlod/index.js +37 -55
  329. package/modules/hud/index.js +17 -11
  330. package/modules/hud/parts.js +4 -4
  331. package/modules/level/contract.js +16 -0
  332. package/modules/level/heightfield.js +12 -10
  333. package/modules/level/index.js +47 -152
  334. package/modules/level/load.js +79 -0
  335. package/modules/level/meshes.js +65 -0
  336. package/modules/level/nodes.js +6 -7
  337. package/modules/lights/index.js +28 -181
  338. package/modules/lights/slots.js +93 -0
  339. package/modules/lights/sources.js +88 -0
  340. package/modules/music/Music.js +30 -26
  341. package/modules/music/rules.js +1 -1
  342. package/modules/nav/contract.js +14 -0
  343. package/modules/nav/index.js +11 -10
  344. package/modules/net/Client.js +7 -7
  345. package/modules/net/Host.js +7 -7
  346. package/modules/net/Net.js +1 -1
  347. package/modules/net/index.js +5 -4
  348. package/modules/net/sync.js +2 -2
  349. package/modules/net/transports.js +2 -2
  350. package/modules/particles/Particles.js +11 -8
  351. package/modules/particles/effect.js +7 -5
  352. package/modules/particles/shaders.js +2 -1
  353. package/modules/photo/Photo.js +15 -17
  354. package/modules/rigid/RigidBodies.js +66 -43
  355. package/modules/rigid/Vehicles.js +2 -3
  356. package/modules/rigid/ragdoll.js +287 -0
  357. package/modules/rigid/ragdollBones.js +159 -0
  358. package/modules/rigid/sync.js +6 -6
  359. package/modules/settings/Settings.js +108 -39
  360. package/modules/settings/apply.js +6 -6
  361. package/modules/settings/sections.js +16 -14
  362. package/modules/settings/view.js +3 -3
  363. package/modules/sky/Sky.js +29 -22
  364. package/modules/sky/clouds.js +7 -7
  365. package/modules/sky/dome.js +33 -20
  366. package/modules/sky/domeLayers.js +9 -9
  367. package/modules/sky/environment.js +6 -6
  368. package/modules/sky/frame.js +19 -10
  369. package/modules/sky/season.js +7 -1
  370. package/modules/sky/shader.js +24 -25
  371. package/modules/sky/skyModule.js +14 -27
  372. package/modules/sky/tint.js +1 -1
  373. package/modules/swarm/Swarm.js +346 -0
  374. package/modules/swarm/draw.js +68 -0
  375. package/modules/swarm/grid.js +63 -0
  376. package/modules/terrain/ChunkManager.js +70 -52
  377. package/modules/terrain/chunkQueries.js +7 -24
  378. package/modules/terrain/chunkWorker.js +1 -1
  379. package/modules/terrain/draw.js +14 -11
  380. package/modules/terrain/index.js +28 -34
  381. package/modules/terrain/terrainColorMap.js +6 -3
  382. package/modules/terrain/terrainDefaults.js +2 -1
  383. package/modules/terrain/terrainEdit.js +32 -27
  384. package/modules/terrain/terrainGen.js +17 -12
  385. package/modules/terrain/terrainIsland.js +2 -2
  386. package/modules/terrain/terrainMesh.js +7 -6
  387. package/modules/terrain/terrainShape.js +8 -10
  388. package/modules/terrain/terrainShapeMain.js +3 -3
  389. package/modules/timeline/Timeline.js +27 -19
  390. package/modules/timeline/Tween.js +6 -6
  391. package/modules/timeline/shots.js +5 -7
  392. package/modules/triggers/index.js +9 -9
  393. package/modules/vegetation/Vegetation.js +30 -23
  394. package/modules/vegetation/densityMap.js +4 -7
  395. package/modules/vegetation/draw.js +23 -18
  396. package/modules/vegetation/groundChunks.js +11 -31
  397. package/modules/vegetation/index.js +8 -6
  398. package/modules/vegetation/modelGeometry.js +3 -6
  399. package/modules/vegetation/nearFade.js +1 -1
  400. package/modules/water/Water.js +16 -16
  401. package/modules/water/surface.js +3 -3
  402. package/modules/weather/Weather.js +41 -30
  403. package/modules/weather/particles.js +8 -8
  404. package/modules/weather/weatherDraw.js +22 -18
  405. package/modules/world/World.js +8 -8
  406. package/modules/world/explain.js +1 -1
  407. package/modules/world/index.js +18 -12
  408. package/modules/world/persist.js +73 -25
  409. package/modules/world/pos.js +4 -4
  410. package/modules/world/records.js +28 -8
  411. package/modules/world/sim.js +4 -4
  412. package/modules/world/state.js +12 -5
  413. package/modules/world/thingSource.js +4 -2
  414. package/modules/world/views.js +11 -9
  415. package/package.json +42 -7
  416. package/presets.js +1 -3
  417. package/render/PostFX.js +39 -27
  418. package/render/backend.js +26 -32
  419. package/render/cascades.js +17 -12
  420. package/render/cascades.tsl.js +5 -8
  421. package/render/daylight.js +20 -3
  422. package/render/detail.js +8 -7
  423. package/render/effects.js +28 -25
  424. package/render/fuse.js +3 -3
  425. package/render/fx/cloudShadow.tsl.js +3 -3
  426. package/render/fx/detail.tsl.js +1 -1
  427. package/render/fx/index.js +5 -10
  428. package/render/fx/library.tsl.js +11 -0
  429. package/render/fx/lighting.tsl.js +2 -1
  430. package/render/fx/nodeErrors.tsl.js +2 -2
  431. package/render/fx/objectOrigin.tsl.js +1 -2
  432. package/render/fx/patchNodes.tsl.js +5 -15
  433. package/render/fx/postWebGPU.tsl.js +27 -23
  434. package/render/fx/sky.tsl.js +15 -17
  435. package/render/fx/uniforms.tsl.js +4 -4
  436. package/render/fx/wind.tsl.js +1 -1
  437. package/render/fxNumbers.js +3 -0
  438. package/render/layers.js +1 -1
  439. package/render/lighting.js +5 -3
  440. package/render/lightmap.js +20 -20
  441. package/render/lights.js +6 -6
  442. package/render/lit.js +24 -0
  443. package/render/materials.js +8 -7
  444. package/render/mergeCommon.js +22 -0
  445. package/render/modeling.js +2 -2
  446. package/render/occlusion.js +20 -4
  447. package/render/ownFrame.js +4 -4
  448. package/render/patches.js +13 -13
  449. package/render/postWebGL.js +12 -10
  450. package/render/probes.js +16 -19
  451. package/render/recordSweep.js +117 -0
  452. package/render/shaderErrors.js +10 -9
  453. package/render/shadowCache.tsl.js +107 -0
  454. package/render/shadowTypes.js +9 -0
  455. package/{core → render}/shadows.js +57 -11
  456. package/render/slots.js +7 -7
  457. package/render/terms.js +22 -24
  458. package/render/uniformDecl.js +1 -1
  459. package/types/core.d.ts +200 -153
  460. package/types/gameplay.d.ts +163 -91
  461. package/types/generated/core/{Audio.d.ts → audio/Audio.d.ts} +22 -7
  462. package/types/generated/core/{audioVoice.d.ts → audio/audioVoice.d.ts} +2 -2
  463. package/types/generated/core/{Events.d.ts → base/Events.d.ts} +4 -4
  464. package/types/generated/core/{I18n.d.ts → base/I18n.d.ts} +7 -15
  465. package/types/generated/core/{Random.d.ts → base/Random.d.ts} +4 -3
  466. package/types/generated/core/{page.d.ts → engine/page.d.ts} +8 -9
  467. package/types/generated/core/{Input.d.ts → input/Input.d.ts} +12 -8
  468. package/types/generated/core/{Budget.d.ts → inspect/Budget.d.ts} +36 -26
  469. package/types/generated/core/{DebugOverrides.d.ts → inspect/DebugOverrides.d.ts} +2 -2
  470. package/types/generated/core/{Ops.d.ts → ops/Ops.d.ts} +4 -3
  471. package/types/generated/core/{control.d.ts → ops/control.d.ts} +4 -10
  472. package/types/generated/core/{Saves.d.ts → saves/Saves.d.ts} +37 -13
  473. package/types/generated/core/{session.d.ts → saves/session.d.ts} +2 -1
  474. package/types/generated/core/{Rays.d.ts → scene/Rays.d.ts} +8 -27
  475. package/types/generated/core/{Views.d.ts → scene/Views.d.ts} +1 -1
  476. package/types/generated/core/{Batching.d.ts → stream/Batching.d.ts} +7 -7
  477. package/types/generated/core/{Stream.d.ts → stream/Stream.d.ts} +18 -16
  478. package/types/generated/core/{Commits.d.ts → threads/Commits.d.ts} +1 -1
  479. package/types/generated/core/{Jobs.d.ts → threads/Jobs.d.ts} +6 -6
  480. package/types/generated/core/{Threads.d.ts → threads/Threads.d.ts} +4 -4
  481. package/types/generated/modules/calendar/Calendar.d.ts +10 -11
  482. package/types/generated/modules/debug/DebugPanel.d.ts +1 -9
  483. package/types/generated/modules/grid/Layer.d.ts +1 -1
  484. package/types/generated/modules/grid/index.d.ts +3 -3
  485. package/types/generated/modules/music/Music.d.ts +7 -5
  486. package/types/generated/modules/particles/Particles.d.ts +1 -1
  487. package/types/generated/modules/sky/Sky.d.ts +21 -10
  488. package/types/generated/modules/swarm/Swarm.d.ts +80 -0
  489. package/types/generated/modules/timeline/Timeline.d.ts +2 -1
  490. package/types/generated/modules/water/Water.d.ts +1 -0
  491. package/types/generated/modules/weather/Weather.d.ts +16 -12
  492. package/types/generated/modules/weather/weatherDraw.d.ts +3 -3
  493. package/types/generated/modules/world/World.d.ts +5 -3
  494. package/types/generated/render/PostFX.d.ts +17 -11
  495. package/types/generated/render/materials.d.ts +1 -0
  496. package/types/generated/render/occlusion.d.ts +9 -0
  497. package/types/generated/render/patches.d.ts +1 -0
  498. package/types/generated/ui/Focus.d.ts +1 -0
  499. package/types/generated/ui/UI.d.ts +1 -0
  500. package/types/nav.d.ts +11 -11
  501. package/types/physics.d.ts +99 -70
  502. package/types/tsl.d.ts +37 -4
  503. package/types/world.d.ts +38 -71
  504. package/ui/Focus.js +10 -9
  505. package/ui/Parts.js +4 -3
  506. package/ui/UI.js +7 -7
  507. package/ui/defaults.js +3 -2
  508. package/ui/theme.js +5 -3
  509. package/core/assetEntry.js +0 -109
  510. package/core/holds.js +0 -134
  511. package/core/shadowTypes.js +0 -16
  512. package/core/util.js +0 -17
  513. package/docs/MIGRATING-0.3.md +0 -248
  514. package/docs/MIGRATING-0.4.md +0 -320
  515. package/docs/MIGRATING-0.5.md +0 -68
  516. package/docs/MIGRATING-0.6.md +0 -126
  517. package/docs/PERF.md +0 -245
  518. package/docs/recipes/36-sky-ground-plants.md +0 -158
  519. package/docs/recipes/37-terrain-hooks.md +0 -115
  520. package/docs/recipes/38-environment-hooks.md +0 -67
  521. package/docs/recipes/42-terrain-shape.md +0 -64
  522. package/docs/recipes/47-island-snow-backdrop.md +0 -43
  523. package/docs/recipes/54-three-idioms.md +0 -88
  524. package/examples/plain-picture/FINDINGS.md +0 -53
  525. /package/core/{Vars.js → base/Vars.js} +0 -0
  526. /package/core/{mulberry32.js → base/mulberry32.js} +0 -0
  527. /package/core/{inputDefaults.js → input/inputDefaults.js} +0 -0
  528. /package/core/{textureBytes.js → inspect/textureBytes.js} +0 -0
  529. /package/core/{actor.js → ops/actor.js} +0 -0
  530. /package/core/{opsFail.js → ops/opsFail.js} +0 -0
  531. /package/core/{opsHistory.js → ops/opsHistory.js} +0 -0
  532. /package/core/{saveIds.js → saves/saveIds.js} +0 -0
  533. /package/core/{screenToGround.js → scene/screenToGround.js} +0 -0
  534. /package/core/{tier.js → scene/tier.js} +0 -0
  535. /package/core/{cells.js → stream/cells.js} +0 -0
  536. /package/core/{streamCells.js → stream/streamCells.js} +0 -0
  537. /package/core/{pureWorker.js → threads/pureWorker.js} +0 -0
  538. /package/examples/{sheepisland → perf-island}/content/index.js +0 -0
  539. /package/examples/{sheepisland → perf-island}/content/props.js +0 -0
  540. /package/examples/{sheepisland → perf-island}/content/templates.js +0 -0
  541. /package/examples/{sheepisland → perf-island}/content/vegetation.js +0 -0
  542. /package/examples/{sheepisland → perf-island}/picture/lights.js +0 -0
  543. /package/examples/{sheepisland → perf-island}/picture/materials.js +0 -0
  544. /package/examples/{sheepisland → perf-island}/picture/sky.js +0 -0
@@ -15,14 +15,16 @@
15
15
  //
16
16
  // Rapier is downloaded on demand at start() (about 1.5MB); games without physics never load it.
17
17
  import * as THREE from 'three';
18
- import { vec3, xzOf } from '../../core/math.js';
18
+ import { vec3, xzOf } from '../../core/base/math.js';
19
19
 
20
- import { readParams, keysSchema } from '../../core/params.js';
21
- import { cellsChanged } from '../../core/streamCells.js';
20
+ import { readParams, keysSchema } from '../../core/base/params.js';
21
+ import { cellsChanged } from '../../core/stream/streamCells.js';
22
22
  import { createVehicle, VEHICLE_KEYS, STRINGS } from './Vehicles.js';
23
23
  import { syncTerrain, syncTrees, treesChanged, syncGroundTrees, syncStatics, syncLevel, recordLocks, carryBody, carryCollider } from './sync.js';
24
- import { codedError, coded } from '../../core/errorHints.js';
25
- import { warnOnce, DEV } from '../../core/validate.js';
24
+ import { Ragdolls } from './ragdoll.js';
25
+ import { codedError, coded } from '../../core/base/errorHints.js';
26
+ import { refuseSave, saveNumberOk, SAVE_MAX } from '../../core/saves/saveValues.js';
27
+ import { warnOnce, DEV } from '../../core/base/validate.js';
26
28
  // Params of addBox / addBall / addHull
27
29
  const PHYSICS = { physics: true }; // stream source filter (shared, not rebuilt every step)
28
30
  const BODY_KEYS = ['id', 'mass', 'friction', 'restitution', 'damping', 'angularDamping', 'fixed'];
@@ -58,10 +60,10 @@ function warmRapier(R) {
58
60
  }
59
61
 
60
62
  export class RigidBodies {
61
- /** gravity gravity = gravity; terrainRing = chunk rings around each physics stream source that get terrain collision; buoyancy = buoyancy toggle; buoyancyForce = buoyancy strength (1 = exactly floats); waterDrag = drag in water;
62
- * floatLine / floatDepth: floatLine / floatDepth: buoyancy starts when the body center is below floatLine meters above the surface and peaks floatDepth
63
- * meters deeper; treeColliderHeight = trunk collision cylinder height; treeRadius = trunks get cylinders only in chunks within this many meters of the player or a non-fixed body;
64
- * playerCapsule { halfHeight, radius } playerCapsule { halfHeight, radius } = player capsule size (default derived from engine.movement radius / height) */
63
+ /** terrainRing = chunk rings around each physics stream source that get terrain collision; buoyancyForce = buoyancy strength (1 = exactly floats); waterDrag = drag in water;
64
+ * floatLine / floatDepth: buoyancy starts when the body center is below floatLine meters above the surface and peaks floatDepth meters deeper;
65
+ * treeColliderHeight = trunk collision cylinder height; treeRadius = trunks get cylinders only in chunks within this many meters of the player or a non-fixed body;
66
+ * playerCapsule { halfHeight, radius } = player capsule size (default derived from engine.movement radius / height) */
65
67
  constructor(engine, { gravity = -9.81, terrainRing = 1, buoyancy = true, buoyancyForce = 1.6, waterDrag = 2.5, floatLine = 0.3, floatDepth = 0.8,
66
68
  treeColliderHeight = 6, treeRadius = 16, playerCapsule } = {}) {
67
69
  const mv = engine.movement; // default capsule uses the shared character radius / height: total height = 2 * halfHeight + 2 * radius
@@ -71,8 +73,8 @@ export class RigidBodies {
71
73
  this.terrainRing = terrainRing;
72
74
  this.buoyancy = buoyancy; this.buoyancyForce = buoyancyForce; this.waterDrag = waterDrag; this.playerCapsule = playerCapsule;
73
75
  this.floatLine = floatLine; this.floatDepth = floatDepth; this.treeColliderHeight = treeColliderHeight; this.treeRadius = treeRadius;
74
- this.R = null; this.world = null;
75
- this.bodies = []; // { body, mesh, offset, enabled }
76
+ this.rapier = null; this.world = null;
77
+ this.bodies = []; // { body, mesh, enabled }
76
78
  /** @internal body handle -> entry for rays, rebuilt only after bodies changed (null): a ray cast every frame (aim, a camera probe) built a new Map each time */ this._byHandle = null;
77
79
  /** @internal a session:end asked for a rebuild that world:load / afterLoad has not run yet (one rebuild per new game or load) */ this._freshDue = false;
78
80
  this.terrain = new Map(); // chunk key -> { colliders: [] }
@@ -95,17 +97,16 @@ export class RigidBodies {
95
97
  /** @internal module hook */
96
98
  async init() {
97
99
  if (this.ready) return;
98
- this.R = await this._wasm();
100
+ this.rapier = await this._wasm();
99
101
  this._newWorld();
100
102
  this.ready = true;
101
103
  }
102
104
  /** @internal A fresh Rapier world with the player capsule (and the flat plane without chunked ground): what init builds, and what _fresh rebuilds */
103
105
  _newWorld() {
104
- const R = this.R;
106
+ const R = this.rapier;
105
107
  /** @internal bumps with every world: a character mover holding a controller of an older world builds a new one (movers/rapier.js) */
106
108
  this.gen = (this.gen ?? 0) + 1;
107
109
  this.world = new R.World({ x: 0, y: this.gravity, z: 0 });
108
- this.world.timestep = 1 / 60;
109
110
  // Player capsule (kinematic: the character controller decides position; physics only pushes other things away)
110
111
  this.playerBody = this.world.createRigidBody(R.RigidBodyDesc.kinematicPositionBased());
111
112
  const pc = this.playerCapsule;
@@ -134,7 +135,7 @@ export class RigidBodies {
134
135
  for (const b of this.bodies) { const y = b.body; y.setLinvel({ x: 0, y: 0, z: 0 }, false); y.setAngvel({ x: 0, y: 0, z: 0 }, false); y.resetForces(false); y.resetTorques(false); if (y.isDynamic()) y.sleep(); }
135
136
  return;
136
137
  }
137
- const old = this.world, R = this.R, hadJoints = old.impulseJoints.len();
138
+ const old = this.world, R = this.rapier, hadJoints = old.impulseJoints.len();
138
139
  this._newWorld();
139
140
  this.terrain.clear(); this.trees.clear(); this.groundTrees.clear(); this._statics?.clear();
140
141
  this._levelVersion = undefined; this._levelColliders = [];
@@ -173,7 +174,7 @@ export class RigidBodies {
173
174
  _add(mesh, desc, { id, mass = 1, friction = 0.7, restitution = 0.1, damping = 0.05, angularDamping = 0.1, fixed = false } = {}) {
174
175
  // id names the body in the save part 'rigid': two live bodies with one id would load into each other
175
176
  if (id != null && this.bodies.some(b => b.id === id)) throw codedError('rigid-misuse', `rigid: id '${id}' is already used by another body or vehicle; ids name the body in saves, pick a unique one (e.g. the world record id)`);
176
- const R = this.R, p = mesh.position, q = mesh.quaternion;
177
+ const R = this.rapier, p = mesh.position, q = mesh.quaternion;
177
178
  const bd = (fixed ? R.RigidBodyDesc.fixed() : R.RigidBodyDesc.dynamic())
178
179
  .setTranslation(p.x, p.y, p.z).setRotation({ x: q.x, y: q.y, z: q.z, w: q.w })
179
180
  .setLinearDamping(damping).setAngularDamping(angularDamping).setCanSleep(true);
@@ -185,6 +186,7 @@ export class RigidBodies {
185
186
  entry.remove = () => this._remove(entry);
186
187
  recordLocks(entry, body);
187
188
  this.bodies.push(entry); this._byHandle = null;
189
+ this.engine._poses.add(mesh);
188
190
  // a loaded save holds this body's state (it is built after the load, e.g. by a world presenter): it continues from there, not from the record's pose
189
191
  const s = id != null && this._saved.get(id);
190
192
  if (s) { this._saved.delete(id); putState(entry, s); }
@@ -195,18 +197,14 @@ export class RigidBodies {
195
197
  readParams('rigid.addBox()', keysSchema([...BODY_KEYS, 'size']), o);
196
198
  if (!this._ready('addBox')) return null;
197
199
  const s = o.size || new THREE.Box3().setFromObject(mesh).getSize(new THREE.Vector3()).toArray();
198
- const e = this._add(mesh, this.R.ColliderDesc.cuboid(s[0] / 2, s[1] / 2, s[2] / 2), o);
199
- if (e) e.volume = s[0] * s[1] * s[2];
200
- return e;
200
+ return this._add(mesh, this.rapier.ColliderDesc.cuboid(s[0] / 2, s[1] / 2, s[2] / 2), o);
201
201
  }
202
202
  /** Ball */
203
203
  addBall(mesh, o = {}) {
204
204
  readParams('rigid.addBall()', keysSchema([...BODY_KEYS, 'radius']), o);
205
205
  if (!this._ready('addBall')) return null;
206
206
  const r = o.radius ?? new THREE.Box3().setFromObject(mesh).getSize(new THREE.Vector3()).x / 2;
207
- const e = this._add(mesh, this.R.ColliderDesc.ball(r), o);
208
- if (e) e.volume = 4.19 * r * r * r;
209
- return e;
207
+ return this._add(mesh, this.rapier.ColliderDesc.ball(r), o);
210
208
  }
211
209
  /** Convex hull: auto-wrapped around the model shape (irregular objects such as rocks, barrels) */
212
210
  addHull(mesh, o = {}) {
@@ -217,9 +215,7 @@ export class RigidBodies {
217
215
  for (let i = 0; i < g.attributes.position.count; i++) {
218
216
  v.fromBufferAttribute(g.attributes.position, i).multiply(mesh.scale); pts.set([v.x, v.y, v.z], i * 3);
219
217
  }
220
- const e = this._add(mesh, this.R.ColliderDesc.convexHull(pts), o);
221
- if (e) { g.computeBoundingBox(); const s = g.boundingBox.getSize(v).multiply(mesh.scale); e.volume = s.x * s.y * s.z * 0.5; }
222
- return e;
218
+ return this._add(mesh, this.rapier.ColliderDesc.convexHull(pts), o);
223
219
  }
224
220
  /**
225
221
  * Wheeled vehicle (Rapier ray-cast vehicle controller): id (stable, for saves; default vehicle1, vehicle2... in creation order), wheels, mass,
@@ -246,16 +242,34 @@ export class RigidBodies {
246
242
  this.world.removeVehicleController(v.controller);
247
243
  this._remove(v);
248
244
  }
249
- /** Whether the physics ground under a position is built (used by mover: 'rapier'; always true without chunked terrain) */
250
- groundReady(position) {
245
+ /**
246
+ * Turn a skinned character limp, one call; rd.remove() returns it to animation. Its mover, animation, capsule and camera yield until then. @experimental
247
+ * @param {any} who a Character, an NPC handle, a character id or a skinned Object3D
248
+ * @param {{ impulse?: any, position?: any, bones?: Record<string, any>, limits?: Record<string, any>, mass?: number }} [o] impulse: a push (kg*m/s) on the part nearest position, else on hips; bones: part -> bone name or bone, over the auto-detection; limits: part or kind ('lowerLeg') -> { bend, side, twist } as [min, max] radians from the bind pose; mass: whole body, default 70 kg
249
+ * @example const rd = engine.rigid.ragdoll(player, { impulse: [0, 200, -300], position: hit.point }); engine.clock.after(4, () => rd.remove());
250
+ */
251
+ ragdoll(who, o) {
252
+ if (!this._ready('ragdoll')) return null;
253
+ return (this._ragdolls ??= new Ragdolls(this)).start(who, o);
254
+ }
255
+ /** @internal Whether the physics ground under a position is built (used by mover: 'rapier'; always true without chunked terrain) */
256
+ readyAt(position) {
251
257
  if (!this.engine.ground.chunkCollision) return true;
252
- const [x, z] = xzOf(position), CH = this.engine.ground.chunkSize ?? 64;
253
- return !!this.terrain.get(Math.floor(x / CH) + ',' + Math.floor(z / CH))?.ready;
258
+ const [x, z] = xzOf(position);
259
+ return this._chunkReady(x, z);
260
+ }
261
+ /** @internal */
262
+ _chunkReady(x, z) { const CH = this.engine.ground.chunkSize ?? 64; return !!this.terrain.get(Math.floor(x / CH) + ',' + Math.floor(z / CH))?.ready; }
263
+ /** @internal A moving body left the terrain colliders. Told once in dev; not told: a body at rest left behind (normal), a chunk still waiting for its collider (it has a terrain entry, or chunks are pending) */
264
+ _tellFrozen(b, t, CH) {
265
+ if (this._srcPending || !b.body.isDynamic() || b.body.isSleeping() || this.terrain.has(Math.floor(t.x / CH) + ',' + Math.floor(t.z / CH))) return;
266
+ warnOnce(coded('rigid-misuse', `rigid: body '${b.id ?? (b.mesh.name || 'unnamed')}' froze at x ${t.x.toFixed(0)}, z ${t.z.toFixed(0)} (entry.enabled is false): it left rigid({ terrainRing: ${this.terrainRing} }), the ${CH} m chunks around the player that have terrain colliders, and would fall through the ground. It stays frozen until the player comes near. A body that must keep moving out there needs a larger terrainRing (recipe 11 section 3)`), 'rigid-frozen');
254
267
  }
255
268
  /** Delete the body (called by entry.remove()); the model stays */
256
269
  _remove(entry) {
257
270
  const i = this.bodies.indexOf(entry); if (i < 0) return;
258
271
  this.world.removeRigidBody(entry.body); this.bodies.splice(i, 1); this._byHandle = null;
272
+ this.engine._poses.remove(entry.mesh);
259
273
  }
260
274
  /** Push: impulse vector v (Vector3 / [x, y, z] / { x, y, z }) */
261
275
  impulse(entry, v) { const { x, y, z } = vec3(v); entry.body.wakeUp(); entry.body.applyImpulse({ x, y, z }, true); }
@@ -273,7 +287,7 @@ export class RigidBodies {
273
287
  if (!byHandle) { byHandle = this._byHandle = new Map(); for (const b of this.bodies) byHandle.set(b.body.handle, b); }
274
288
  const max = Number.isFinite(far) ? far : 1e6;
275
289
  const only = c => byHandle.has(c.parent()?.handle);
276
- const hit = this.world.castRayAndGetNormal(new this.R.Ray(origin, dir), max, true, undefined, undefined, undefined, this.playerBody, only);
290
+ const hit = this.world.castRayAndGetNormal(new this.rapier.Ray(origin, dir), max, true, undefined, undefined, undefined, this.playerBody, only);
277
291
  if (!hit) return null;
278
292
  const entry = byHandle.get(hit.collider.parent()?.handle);
279
293
  if (!entry) return null;
@@ -294,7 +308,12 @@ export class RigidBodies {
294
308
  return out;
295
309
  }
296
310
  /** @internal Load: bodies here now take their state in afterLoad (after _fresh rebuilt them); the rest when they are added */
297
- _loadState(d) { this._saved = new Map(Object.entries(d ?? {})); }
311
+ _loadState(d) {
312
+ // a body past float precision (x = -1e308) sends the ground loops around it spinning and the page never comes back: damage, refused like a damaged world record (world/persist.js)
313
+ for (const [id, s] of Object.entries(d ?? {}))
314
+ if (!Array.isArray(s) || s.length !== 14 || !s.every(v => typeof v === 'boolean' || saveNumberOk(v))) refuseSave('rigid', `body '${id}'`, `must be a list of 14 numbers within ±${SAVE_MAX}`, s);
315
+ this._saved = new Map(Object.entries(d ?? {})); this._ragdolls?.load();
316
+ }
298
317
  /** @internal afterLoad: hand the loaded state to the bodies that exist (vehicles, bodies the game keeps across a load) */
299
318
  _claimSaved() {
300
319
  for (const b of this.bodies) { const s = b.id != null && this._saved.get(b.id); if (s) { this._saved.delete(b.id); putState(b, s); } }
@@ -305,6 +324,8 @@ export class RigidBodies {
305
324
  step(dt) {
306
325
  if (!this.ready) return;
307
326
  const e = this.engine, G = e.ground, CH = G.chunkSize ?? 64, chunked = !!G.chunkCollision;
327
+ // the simulation runs on the world channel, like characters, walks and swarms: slow motion slows bodies and a hit-stop holds them. Collider upkeep below stays on real time
328
+ const worldDt = e.time.dt('world');
308
329
  const focus = e.player ? e.player.position : e.focus; // player-body: the player's own kinematic body follows the character, not engine.actor
309
330
  // terrain collision around physics stream sources: sync at once when their chunks change, otherwise check every 0.5 s (tree felling etc.)
310
331
  // compared in place against last step's cells (no array, no string key while nothing crosses a chunk border); the list is built only when syncing
@@ -328,16 +349,17 @@ export class RigidBodies {
328
349
  // player capsule follows the player (the rapier mover computes collision and writes the position itself); turned off while driving to avoid colliding with
329
350
  // the car
330
351
  if (e.player) this.playerBody.setNextKinematicTranslation({ x: focus.x, y: focus.y, z: focus.z });
331
- const onFoot = !e.player?.vehicle;
352
+ // no player, no capsule: with no player nothing moves it, and it would sit as an invisible solid body at the origin
353
+ const onFoot = !!e.player && !e.player.vehicle && !this._ragdolls?.holds(e.player);
332
354
  if (this.playerCollider.isEnabled() !== onFoot) this.playerCollider.setEnabled(onFoot);
333
- for (const v of this.vehicles) if (v.enabled) v._update(dt);
355
+ if (worldDt > 0) for (const v of this.vehicles) if (v.enabled) v._update(worldDt);
334
356
 
335
357
  // freeze bodies without terrain collision under them (unfrozen they would fall through)
336
358
  for (const b of this.bodies) {
337
359
  const t = b.body.translation();
338
360
  b._x = t.x; b._z = t.z;
339
- const ok = !chunked || !!this.terrain.get(Math.floor(t.x / CH) + ',' + Math.floor(t.z / CH))?.ready;
340
- if (ok !== b.enabled) { b.body.setEnabled(ok); b.enabled = ok; }
361
+ const ok = !chunked || this._chunkReady(t.x, t.z);
362
+ if (ok !== b.enabled) { if (DEV && !ok) this._tellFrozen(b, t, CH); b.body.setEnabled(ok); b.enabled = ok; }
341
363
  // buoyancy: the submerged part gets an upward force, and water adds drag
342
364
  const water = this.buoyancy ? e.waterAt(t.x, t.z) : -Infinity;
343
365
  if (ok && this.buoyancy && t.y < water + this.floatLine && b.body.isDynamic()) {
@@ -352,10 +374,10 @@ export class RigidBodies {
352
374
  }
353
375
  }
354
376
 
355
- this.world.step();
377
+ if (worldDt > 0) { this.world.timestep = worldDt; this.world.step(); }
356
378
 
357
379
  for (const b of this.bodies) {
358
- if (!b.enabled || b.body.isSleeping()) continue;
380
+ if (!b.enabled || b.body.isSleeping() || b.ragdoll) continue; // ragdoll parts are drawn by ragdoll.js, through the bones
359
381
  const t = b.body.translation(), r = b.body.rotation();
360
382
  b.mesh.position.set(t.x, t.y, t.z);
361
383
  b.mesh.quaternion.set(r.x, r.y, r.z, r.w);
@@ -366,6 +388,7 @@ export class RigidBodies {
366
388
  b._void = under;
367
389
  }
368
390
  for (const v of this.vehicles) v._sync();
391
+ this._ragdolls?.sync();
369
392
  }
370
393
 
371
394
  get stats() {
@@ -395,12 +418,12 @@ export function rigid(opts = {}) {
395
418
  readParams('rigid', RIGID_PARAMS, opts);
396
419
  let r = null;
397
420
  return {
398
- name: 'rigid', type: 'world', provides: ['rigid'], params: RIGID_PARAMS, options: opts, label: 'Physics', noSkip: 'bodies rest while time jumps (stepping seconds of physics would only scatter them)', optional: ['interactions'], requires: ['collision'],
421
+ name: 'rigid', type: 'world', provides: ['rigid'], params: RIGID_PARAMS, options: opts, label: 'Physics', noSkip: 'bodies rest while time jumps (stepping seconds of physics would only scatter them)', optional: ['interactions', 'cameraRig'], requires: ['collision'],
399
422
  install(e, ctx) {
400
423
  e.i18n.add(STRINGS); e.i18n.add({ 'zh-CN': { 'module.rigid': '物理引擎' }, en: { 'module.rigid': 'physics' } }); r = new RigidBodies(e, opts);
401
424
  r._wasm().catch(() => {}); // start loading now (see _wasm); a failure surfaces in init, which awaits the same promise
402
425
  e.budget.metric('rigidBodies', () => r.bodies.length);
403
- e.stream.readyCheck('rigid', s => !s.physics || r.ready && r.groundReady(s)); // a physics stream source waits for the collider under it
426
+ e.stream.addReadyCheck('rigid', s => !s.physics || r.ready && r.readyAt(s)); // a physics stream source waits for the collider under it
404
427
  e.rays.addProvider((o, d, far) => r._raycast(o, d, far)); // engine.raycast(..., { targets: 'all' }) includes rigid bodies
405
428
  // a new playthrough / a load is a fresh page for physics too (_fresh), rebuilt once per load: session:end only marks it due. With the world
406
429
  // module the rebuild runs on world:load, after the load removed the records' bodies, so the rebuilt world gets them back in view order; without
@@ -413,15 +436,15 @@ export function rigid(opts = {}) {
413
436
  return r;
414
437
  },
415
438
  afterLoad() { if (r._freshDue) r._fresh(); r._claimSaved(); }, // after every part loaded and _fresh rebuilt the world (world:load is emitted inside the world part's load)
416
- async init(e, ctx) { await r.init(); ctx.whileCompiling(() => warmRapier(r.R)); },
439
+ async init(e, ctx) { await r.init(); ctx.whileCompiling(() => warmRapier(r.rapier)); },
417
440
  counts() { return r.bodies.length; }, // engine.counts().rigid
418
441
  // bodies by type and what they are doing: sleeping = at rest (normal), frozen = disabled because no terrain collider is under them yet (they wait, not fall)
419
442
  describe() {
420
443
  const B = r.bodies, n = f => B.filter(f).length;
421
444
  return { ready: r.ready, bodies: B.length, dynamic: n(b => !b.fixed), fixed: n(b => b.fixed), sleeping: n(b => b.enabled && b.body.isSleeping()),
422
- frozen: n(b => !b.enabled), vehicles: r.vehicles.length, colliders: r.world ? r.world.colliders.len() : 0 };
445
+ frozen: n(b => !b.enabled), vehicles: r.vehicles.length, colliders: r.world ? r.world.colliders.len() : 0, ...(r._ragdolls?.live.size && { ragdolls: r._ragdolls.live.size }) };
423
446
  },
424
- fixed(dt) { if (r.ready) r.step(dt); },
425
- dispose() { r.world?.free(); r.world = null; },
447
+ fixed(dt) { r.step(dt); },
448
+ dispose() { r._ragdolls?.dispose(); r.world?.free(); r.world = null; },
426
449
  };
427
450
  }
@@ -8,7 +8,7 @@
8
8
  // engine.player.enter(car); car.drive(throttle, steer, brake)
9
9
  // Native objects: car.body (rigid body), car.controller (vehicle controller).
10
10
  import * as THREE from 'three';
11
- import { vec3 } from '../../core/math.js';
11
+ import { vec3 } from '../../core/base/math.js';
12
12
 
13
13
  export const VEHICLE_KEYS = ['id', 'wheels', 'mass', 'engineForce', 'brakeForce', 'maxSteer', 'suspension', 'seats', 'hideDriver', 'camera', 'size', 'friction', 'exitOffset'];
14
14
  export const STRINGS = { 'zh-CN': { 'vehicle.enter': '上车', 'vehicle.exit': '下车' }, en: { 'vehicle.enter': 'Get in', 'vehicle.exit': 'Get out' } };
@@ -29,11 +29,10 @@ function bodyBox(mesh, wheelObjs) {
29
29
 
30
30
  /** Create a vehicle (called by RigidBodies.addWheeled) */
31
31
  export function createVehicle(rigid, mesh, { wheels, mass = 800, engineForce = 800, brakeForce = 20, maxSteer = 0.5, suspension = {}, seats, hideDriver = true, camera, size, friction = 1.5, exitOffset = 0.8 }, id) {
32
- const e = rigid.engine, R = rigid.R, w = rigid.world;
32
+ const e = rigid.engine, R = rigid.rapier, w = rigid.world;
33
33
  const box = bodyBox(mesh, new Set(wheels.map(x => x.object).filter(Boolean)));
34
34
  const s = size ? new THREE.Vector3().fromArray(size) : box.getSize(new THREE.Vector3()), c = size ? new THREE.Vector3() : box.getCenter(new THREE.Vector3());
35
35
  const entry = rigid._add(mesh, R.ColliderDesc.cuboid(s.x / 2, s.y / 2, s.z / 2).setTranslation(c.x, c.y, c.z), { id, mass, friction: 0.5, damping: 0.1, angularDamping: 0.5 });
36
- entry.volume = s.x * s.y * s.z;
37
36
  const ctl = w.createVehicleController(entry.body);
38
37
  ctl.indexUpAxis = 1; ctl.setIndexForwardAxis = 2; // up = Y, forward = Z
39
38
  const { rest = 0.3, stiffness = 30, damping = 4 } = suspension;
@@ -0,0 +1,287 @@
1
+ // Ragdoll: one dynamic rigid body per part of a skinned character, joined by joints; every fixed step the result is written back to the plain three.js bones.
2
+ // const rd = engine.rigid.ragdoll(player, { impulse: [0, 2, -8], position: hitPoint });
3
+ // rd.remove(); // back to animation
4
+ //
5
+ // Why it is done this way:
6
+ // - Bodies do not use the bone's orientation but "one shared frame for the whole body in bind pose": bodyQ = boneWorldQ * inv(restQ). That way the frames on both sides of every joint coincide in bind pose,
7
+ // so the limit zero is the bind pose, whatever pose the animation was in at the start. Using bone orientation directly gives every joint an error the moment it is created and it blows apart on the first step.
8
+ // - Only hips writes a position, other bones write rotation only: child bones keep their local offsets, so bone length cannot change and the mesh cannot stretch (the forum post this was modelled on fails right here).
9
+ // - Parts go through rigid's _add: buoyancy, freezing while terrain is not ready, engine.raycast and world rebuild all come for free; no second copy.
10
+ // - Not saved: as soon as rigid's save part is read in (new game, load and saves.load all go through it) every ragdoll ends and a normal character comes back; a refused load never gets here, so the ragdoll keeps lying there.
11
+ // On a world rebuild without a load, rigid carries the bodies over and this rebuilds the joints on rigid:rebuilt.
12
+ // - Self-collision is off: capsules of neighbouring parts overlap at the start and would push each other away; the limits keep the pose.
13
+ // shortcut: one collision group, so ragdolls do not collide with each other either; to pile bodies up, give each ragdoll its own group bit.
14
+ import * as THREE from 'three';
15
+ import { vec3 } from '../../core/base/math.js';
16
+ import { readParams, keysSchema } from '../../core/base/params.js';
17
+ import { codedError } from '../../core/base/errorHints.js';
18
+ import { readBones, shapeParts } from './ragdollBones.js';
19
+
20
+ const KEYS = keysSchema(['impulse', 'position', 'bones', 'limits', 'mass']);
21
+ const GROUP = (0x8000 << 16 | 0x7fff) >>> 0; // the high 16 bits are its own group, the low 16 bits say what it can touch: everything except its own group
22
+ const D = Math.PI / 180;
23
+ // Default range of motion (radians, relative to bind pose). bend is positive forward (backward for knees), side is sideways, twist is around the bone. This is physical plausibility, not looks
24
+ const LIMITS = {
25
+ chest: { bend: [-30 * D, 40 * D], side: [-25 * D, 25 * D], twist: [-30 * D, 30 * D] },
26
+ head: { bend: [-40 * D, 50 * D], side: [-35 * D, 35 * D], twist: [-60 * D, 60 * D] },
27
+ upperArm: { bend: [-60 * D, 120 * D], side: [-100 * D, 100 * D], twist: [-70 * D, 70 * D] },
28
+ lowerArm: { bend: [0, 145 * D], side: [-3 * D, 3 * D], twist: [-60 * D, 60 * D] },
29
+ upperLeg: { bend: [-25 * D, 110 * D], side: [-45 * D, 45 * D], twist: [-35 * D, 35 * D] },
30
+ lowerLeg: { bend: [0, 140 * D], side: [-3 * D, 3 * D], twist: [-5 * D, 5 * D] },
31
+ };
32
+ const SHARE = { hips: 0.16, chest: 0.3, head: 0.08, upperArm: 0.03, lowerArm: 0.025, upperLeg: 0.11, lowerLeg: 0.07 }; // how the total mass is split
33
+ const FRICTION = 2; // damping in the joints (1/s): limbs with no muscle still do not whip around like ropes forever
34
+ const CALM_SPEED = 0.09, CALM_SPIN = 4, CALM_STEPS = 45; // speed squared (m²/s²), angular speed squared (rad²/s²), how many steps in a row
35
+ const HIT_SPEED = 6; // the speed (m/s) the hit part alone can take, see _push
36
+
37
+ const q1 = new THREE.Quaternion(), q2 = new THREE.Quaternion(), p1 = new THREE.Vector3(), p2 = new THREE.Vector3(), s1 = new THREE.Vector3();
38
+ const toQ = (r, out = q1) => out.set(r.x, r.y, r.z, r.w);
39
+ const worldOf = (o, p, q) => { o.matrixWorld.decompose(p, q, s1); };
40
+ const shapes = new WeakMap(); // skeleton -> { key, parts }: the same character falling again and again is not re-measured
41
+
42
+ export class Ragdolls {
43
+ /** @param {import('./RigidBodies.js').RigidBodies} r */
44
+ constructor(r) {
45
+ this.r = r; this.e = r.engine;
46
+ /** @type {Set<any>} */ this.live = new Set();
47
+ // Listeners are attached on first use: a game that never uses ragdolls pays nothing
48
+ this._sub = this.e.events.on('rigid:rebuilt', () => { for (const rd of this.live) this._joints(rd); });
49
+ }
50
+
51
+ /** The body of engine.rigid.ragdoll */
52
+ start(who, o = {}) {
53
+ readParams('rigid.ragdoll()', KEYS, o);
54
+ const { ch, root } = this._find(who);
55
+ const old = [...this.live].find(rd => rd.root === root);
56
+ if (old) { this._push(old, o); return old; } // already down and hit again: do not rebuild, just push once more
57
+ if (ch?.vehicle) throw codedError('rigid-misuse', `rigid.ragdoll(): character '${ch.id}' sits in a vehicle. Fix: character.exit() first`);
58
+ const mesh = skinOf(root);
59
+ if (!mesh) throw codedError('rigid-misuse', `rigid.ragdoll(): no SkinnedMesh under ${ch ? `character '${ch.id}'` : `'${root.name || root.type}'`}, so there are no bones to drive. A capsule or a procedural rig cannot go limp; a model given by name loads later: await character.whenReady first`);
60
+ const shape = this._shape(mesh, o.bones);
61
+ // Take control first: a remote character throws here, when nothing has been built yet
62
+ const hold = ch ? this.e.control.take(ch, { owner: 'ragdoll', layer: 'physics', step: () => false }) : null;
63
+ const rd = this._build(ch, root, mesh, shape, hold, o);
64
+ this.live.add(rd);
65
+ this._yield(rd);
66
+ this._push(rd, o);
67
+ return rd;
68
+ }
69
+
70
+ /** Accepts a Character, an NPC handle, a character id, or a model that belongs to no character */
71
+ _find(who) {
72
+ if (who?.isObject3D) return { ch: null, root: who };
73
+ const ch = who?.root && who?.move ? who : typeof who === 'string' ? this.e.control.characterOf(who) : who?.character;
74
+ if (!ch) throw codedError('rigid-misuse', `rigid.ragdoll(character): pass a Character, an NPC handle (its model must be built), a character id or a skinned Object3D, got ${String(who?.id ?? who)}`);
75
+ return { ch, root: ch.root };
76
+ }
77
+
78
+ _shape(mesh, bones = {}) {
79
+ const key = JSON.stringify(bones, (k, v) => (v?.isObject3D ? v.uuid : v));
80
+ const c = shapes.get(mesh.skeleton);
81
+ if (c?.key === key) return c.parts;
82
+ const parts = shapeParts(mesh, readBones(mesh.skeleton, bones));
83
+ shapes.set(mesh.skeleton, { key, parts });
84
+ return parts;
85
+ }
86
+
87
+ _build(ch, root, mesh, shape, hold, o) {
88
+ const { r } = this, R = r.rapier, mass = o.mass ?? 70;
89
+ root.updateWorldMatrix(true, true);
90
+ const holder = new THREE.Group(); // parent of the placeholder objects: _add does not add to the scene when there is a parent
91
+ const parts = {}, list = [];
92
+ // bind space to world scale: when the model is scaled (0.01 is common for Mixamo) colliders must use the real length as it is now
93
+ const a = shape.find(s => s.name === 'upperLegL'), b = shape.find(s => s.name === 'lowerLegL');
94
+ const k = a.bone.getWorldPosition(p1).distanceTo(b.bone.getWorldPosition(p2)) / a.p.distanceTo(b.p);
95
+ for (const s of shape) {
96
+ const proxy = new THREE.Object3D(), bq = new THREE.Quaternion();
97
+ holder.add(proxy);
98
+ worldOf(s.bone, proxy.position, bq);
99
+ proxy.quaternion.copy(bq).multiply(q2.copy(s.q).invert());
100
+ const seg = p1.subVectors(s.end, s.p).multiplyScalar(k), len = seg.length(), rad = s.radius * k;
101
+ const mid = seg.clone().multiplyScalar(0.5), up = q1.setFromUnitVectors(new THREE.Vector3(0, 1, 0), seg.clone().normalize());
102
+ const desc = R.ColliderDesc.capsule(Math.max(len / 2 - rad, len * 0.02), rad).setTranslation(mid.x, mid.y, mid.z)
103
+ .setRotation({ x: up.x, y: up.y, z: up.z, w: up.w }).setCollisionGroups(GROUP);
104
+ const entry = r._add(proxy, desc, { mass: mass * SHARE[s.kind], friction: 0.8, restitution: 0, damping: 0.1, angularDamping: 0.8 });
105
+ entry.ragdoll = true; entry.object = s.bone; // a ray hit returns the bone: the game needs to know what was hit
106
+ entry.body.enableCcd(true); // limbs are thin and fast when knocked away; without it they pass through thin ground
107
+ const part = { name: s.name, shape: s, entry, mass: mass * SHARE[s.kind], seg: seg.clone(), rad, bone: s.bone, pos0: s.bone.position.clone(), q0: s.bone.quaternion.clone() };
108
+ list.push(parts[s.name] = part);
109
+ }
110
+ const self = this;
111
+ const rd = {
112
+ ch, root, mesh, list, parts: Object.fromEntries(list.map(p => [p.name, p.entry])), hold, joints: [], limits: o.limits ?? {}, anchor: null, rig: null, anim: null, drawn: false, void: false, calm: 0,
113
+ get active() { return self.live.has(rd); },
114
+ get settled() { return rd.active && list.every(p => !p.entry.enabled || p.entry.body.isSleeping()); },
115
+ remove() { self._end(rd); },
116
+ };
117
+ // Joint anchors are computed from the current pose (not the bind pose): in-between bones that are not in the part table (Spine1, clavicle) may not be at their bind position at the start, and this way the error on the first step is zero
118
+ for (const p of list) {
119
+ if (!p.shape.parent) continue;
120
+ p.parent = parts[p.shape.parent];
121
+ const t0 = p.parent.entry.body.translation(), t1 = p.entry.body.translation();
122
+ p.anchor = p1.set(t1.x - t0.x, t1.y - t0.y, t1.z - t0.z).applyQuaternion(toQ(p.parent.entry.body.rotation()).invert()).clone();
123
+ p.range = this._range(p, rd.limits);
124
+ }
125
+ this._joints(rd);
126
+ // falling while running keeps the original velocity
127
+ if (ch) for (const p of list) p.entry.body.setLinvel({ x: ch.velocity.x, y: ch.vy, z: ch.velocity.y }, true);
128
+ return rd;
129
+ }
130
+
131
+ /** The three-axis range of this joint. If the starting pose is already past the limit, widen the range to the starting angle: otherwise the solver yanks it back on the first step and it looks like a twitch */
132
+ _range(p, limits) {
133
+ const given = limits[p.name] ?? limits[p.shape.kind], base = LIMITS[p.shape.kind];
134
+ const lim = { twist: given?.twist ?? base.twist, side: given?.side ?? base.side, bend: given?.bend ?? base.bend };
135
+ const F = p.shape.frame;
136
+ // The child's rotation relative to the parent, read in the joint frame: the imaginary x / y / z are the three values Rapier's limits use
137
+ toQ(p.parent.entry.body.rotation(), q1).invert().multiply(toQ(p.entry.body.rotation(), q2));
138
+ const f = q1.premultiply(q2.copy(F).invert()).multiply(F);
139
+ const sign = f.w < 0 ? -1 : 1, ang = c => 2 * Math.asin(THREE.MathUtils.clamp(sign * c, -1, 1));
140
+ return [[lim.twist, f.x], [lim.side, f.y], [lim.bend, f.z]].map(([[lo, hi], c]) => { const x = ang(c); return [Math.min(lo, x - 0.02), Math.max(hi, x + 0.02)]; });
141
+ }
142
+
143
+ /** Build the joints; runs again after a world rebuild. Rapier's JS layer only exposes setLimits for single-axis joints; the three-axis limits and damping of a spherical joint (actually type Generic) go through the rawSet below it (the ragdoll test fails first when the version is upgraded) */
144
+ _joints(rd) {
145
+ const { r } = this, R = r.rapier, w = r.world, zero = { x: 0, y: 0, z: 0 };
146
+ rd.joints = [];
147
+ for (const p of rd.list) {
148
+ if (!p.parent) continue;
149
+ const j = w.createImpulseJoint(R.JointData.spherical(p.anchor, zero), p.parent.entry.body, p.entry.body, true);
150
+ const F = p.shape.frame, f = { x: F.x, y: F.y, z: F.z, w: F.w };
151
+ j.setLocalFrame1(p.anchor, f); j.setLocalFrame2(zero, f);
152
+ [R.JointAxis.AngX, R.JointAxis.AngY, R.JointAxis.AngZ].forEach((axis, i) => {
153
+ j.rawSet.jointSetLimits(j.handle, axis, p.range[i][0], p.range[i][1]);
154
+ j.rawSet.jointConfigureMotorVelocity(j.handle, axis, 0, FRICTION);
155
+ });
156
+ rd.joints.push(j);
157
+ }
158
+ }
159
+
160
+ /**
161
+ * The impulse hits the part nearest to position (hips when no position is given). That part only takes HIT_SPEED worth, the rest is shared over the whole body by mass:
162
+ * in a real body force travels along the skeleton, but the solver cannot pass that much in one step, and the whole hit on a 5 kg head would send it flying and tear the joints apart. Total momentum is unchanged.
163
+ */
164
+ _push(rd, { impulse, position }) {
165
+ if (!impulse) return;
166
+ const i = vec3(impulse), at = position && vec3(position);
167
+ let hit = rd.list[0], dist = Infinity;
168
+ if (at) for (const p of rd.list) {
169
+ const c = p.entry.collider.translation(), d = at.distanceToSquared(p1.set(c.x, c.y, c.z));
170
+ if (d < dist) { dist = d; hit = p; }
171
+ }
172
+ const size = i.length(), own = size ? Math.min(1, hit.mass * HIT_SPEED / size) : 1, mass = rd.list.reduce((n, p) => n + p.mass, 0);
173
+ const v = { x: i.x * own, y: i.y * own, z: i.z * own };
174
+ if (at) hit.entry.body.applyImpulseAtPoint(v, { x: at.x, y: at.y, z: at.z }, true); else hit.entry.body.applyImpulse(v, true);
175
+ if (own < 1) for (const p of rd.list) {
176
+ const k = (1 - own) * p.mass / mass;
177
+ p.entry.body.applyImpulse({ x: i.x * k, y: i.y * k, z: i.z * k }, true);
178
+ }
179
+ }
180
+
181
+ /** Make the character's animation, movement, capsule and camera yield. Control was already taken in start */
182
+ _yield(rd) {
183
+ const { ch, root } = rd, e = this.e;
184
+ rd.anim = ch ? ch.anim : e.assets.animatorOf(root);
185
+ if (rd.anim) rd.anim._held = true;
186
+ if (ch) {
187
+ ch._limp = rd;
188
+ ch.velocity.set(0, 0); ch.vy = 0; ch.moveAmount = 0; ch.state = ch._stateMark = 'ragdoll';
189
+ // the player capsule is turned off by rigid.step according to _limp; an NPC's capsule belongs to its mover
190
+ if (ch !== e.player && ch.mover.collider && ch.mover.gen === this.r.gen) ch.mover.collider.setEnabled(false);
191
+ }
192
+ const rig = e.cameraRig;
193
+ if (rig?.target === root) {
194
+ // follow the waist, not the feet: the camera looks at the body, not at the air a person's height above it
195
+ rd.rig = rig; rd.anchor = new THREE.Object3D();
196
+ this._anchor(rd);
197
+ rig.follow(rd.anchor, { height: 0 });
198
+ }
199
+ }
200
+
201
+ _anchor(rd) { const t = rd.parts.hips.body.translation(); rd.anchor.position.set(t.x, t.y, t.z); }
202
+
203
+ /** Every fixed step, after the world has stepped (called by RigidBodies.step) */
204
+ sync() {
205
+ for (const rd of this.live) {
206
+ const { ch, root } = rd;
207
+ if (ch?._disposed || !root.parent) { this._end(rd, true); continue; } // the character or model was deleted: only clean up the physics
208
+ if (rd.settled) { if (rd.drawn) continue; rd.drawn = true; } else { rd.drawn = false; this._calm(rd); } // once asleep, stop writing: saves cost and a bone the game wrote stays
209
+ this._pose(rd);
210
+ ch?.syncRecord();
211
+ }
212
+ }
213
+
214
+ /** Once slow enough, put the whole body to sleep together: joints resting on their limits jitter slightly, Rapier's own sleep threshold is often never reached, and the body would be simulated forever. It only counts fixed steps, so it stays deterministic */
215
+ _calm(rd) {
216
+ for (const p of rd.list) {
217
+ const v = p.entry.body.linvel(), w = p.entry.body.angvel();
218
+ if (v.x * v.x + v.y * v.y + v.z * v.z > CALM_SPEED || w.x * w.x + w.y * w.y + w.z * w.z > CALM_SPIN) { rd.calm = 0; return; }
219
+ }
220
+ if (++rd.calm >= CALM_STEPS) for (const p of rd.list) p.entry.body.sleep();
221
+ }
222
+
223
+ /** Write the physics result back to the bones. root follows the body (triggers, streaming and saves read it), so the bones are computed after root has moved */
224
+ _pose(rd) {
225
+ const { root, list } = rd, hips = list[0].entry.body.translation();
226
+ let low = Infinity;
227
+ for (const p of list) { // lowest point of the body: the soles when standing, the ground when lying, no need to ask the terrain
228
+ const t = p.entry.body.translation(), q = toQ(p.entry.body.rotation());
229
+ low = Math.min(low, t.y - p.rad, t.y + p1.copy(p.seg).applyQuaternion(q).y - p.rad);
230
+ }
231
+ p1.set(hips.x, low, hips.z);
232
+ if (root.parent) root.parent.worldToLocal(p1);
233
+ root.position.copy(p1);
234
+ root.updateWorldMatrix(true, false);
235
+ for (const p of list) {
236
+ const b = p.entry.body, parent = p.bone.parent;
237
+ parent.updateWorldMatrix(true, false);
238
+ worldOf(parent, p1, q2);
239
+ p.bone.quaternion.copy(q2.invert().multiply(toQ(b.rotation()).multiply(p.shape.q)));
240
+ if (p === list[0]) {
241
+ const t = b.translation();
242
+ p.bone.position.copy(parent.worldToLocal(p1.set(t.x, t.y, t.z)));
243
+ }
244
+ p.bone.updateMatrixWorld();
245
+ }
246
+ if (rd.anchor) this._anchor(rd);
247
+ const under = hips.y < this.e.ground.voidY();
248
+ if (under && !rd.void) this.e.events.emit('terrain:void', { who: rd.parts.hips, position: { x: hips.x, y: hips.y, z: hips.z } });
249
+ rd.void = under;
250
+ }
251
+
252
+ /** Is this character lying down (rigid.step turns the player capsule off by this) */
253
+ holds(ch) { return !!ch._limp; }
254
+
255
+ /** Load: position belongs to the save, so the character is not put back where the body lies */
256
+ load() { for (const rd of [...this.live]) this._end(rd, false, false); }
257
+
258
+ /** End: tear down the physics and give every slot back to its owner. gone: the character no longer exists, nothing to give back; place: put the character where the body lies */
259
+ _end(rd, gone = false, place = true) {
260
+ if (!this.live.delete(rd)) return;
261
+ const { ch, list, anim, rig, anchor, hold } = rd;
262
+ for (const j of rd.joints) if (j.isValid()) this.r.world.removeImpulseJoint(j, true);
263
+ rd.joints = [];
264
+ for (const p of list) p.entry.remove();
265
+ hold?.remove(); // gone too: a slot is kept by id, so an NPC whose model was torn down while limp would come back paused for good
266
+ if (gone) return;
267
+ for (const p of list) { p.bone.position.copy(p.pos0); p.bone.quaternion.copy(p.q0); } // bones no animation clip writes also go back to how they were before falling
268
+ if (anim) anim._held = false;
269
+ if (ch) {
270
+ ch._limp = null;
271
+ if (ch !== this.e.player && ch.mover.collider && ch.mover.gen === this.r.gen) ch.mover.collider.setEnabled(true);
272
+ if (ch.state === 'ragdoll') ch.state = ch._stateMark = 'idle';
273
+ if (place) ch.placeAt(ch.root.position);
274
+ }
275
+ // if the game switched the camera away meanwhile, do not take it back
276
+ if (rig?.target === anchor) rig.follow(rd.root);
277
+ }
278
+
279
+ dispose() { this._sub.remove(); this.live.clear(); }
280
+ }
281
+
282
+ /** The SkinnedMesh with the most bones: clothes and accessories are often small meshes on the same skeleton */
283
+ function skinOf(root) {
284
+ let best = null;
285
+ root.traverse(o => { if (o.isSkinnedMesh && o.skeleton && (!best || o.skeleton.bones.length > best.skeleton.bones.length)) best = o; });
286
+ return best;
287
+ }