threedog 0.2.1 → 0.7.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 (725) hide show
  1. package/CHANGELOG.md +371 -1
  2. package/README.md +21 -12
  3. package/core/Animator.js +15 -12
  4. package/core/Assets.js +92 -26
  5. package/core/Audio.js +45 -38
  6. package/core/Baked.js +30 -15
  7. package/core/Batching.js +102 -15
  8. package/core/Budget.js +40 -19
  9. package/core/Clock.js +40 -80
  10. package/core/DebugOverrides.js +75 -25
  11. package/core/Describe.js +105 -45
  12. package/core/Engine.js +203 -75
  13. package/core/Events.js +4 -1
  14. package/core/I18n.js +25 -13
  15. package/core/Input.js +175 -80
  16. package/core/Inspect.js +8 -5
  17. package/core/InspectMaterials.js +84 -0
  18. package/core/InspectPerf.js +68 -0
  19. package/core/InspectScene.js +13 -2
  20. package/core/Loading.js +2 -1
  21. package/core/MaterialInfo.js +7 -5
  22. package/core/Ops.js +50 -9
  23. package/core/Random.js +9 -2
  24. package/core/Rays.js +12 -7
  25. package/core/SaveStore.js +41 -9
  26. package/core/Saves.js +71 -15
  27. package/core/Stream.js +13 -10
  28. package/core/Threads.js +26 -7
  29. package/core/UrlState.js +69 -13
  30. package/core/Views.js +10 -6
  31. package/core/actor.js +1 -1
  32. package/core/adaptive.js +93 -0
  33. package/core/assetEntry.js +27 -7
  34. package/core/assetHot.js +176 -0
  35. package/core/assetLoad.js +44 -19
  36. package/core/assetManifest.js +53 -11
  37. package/core/assetReport.js +5 -5
  38. package/core/audioRules.js +13 -11
  39. package/core/audioVoice.js +69 -42
  40. package/core/batchGroups.js +9 -1
  41. package/core/canvasBox.js +1 -2
  42. package/core/catalog.js +21 -5
  43. package/core/cells.js +62 -0
  44. package/core/checks.js +10 -8
  45. package/core/chunkStream.js +87 -0
  46. package/core/control.js +149 -0
  47. package/core/copies.js +32 -0
  48. package/core/dayTime.js +12 -6
  49. package/core/debugView.js +85 -18
  50. package/core/describeRender.js +117 -21
  51. package/core/describeText.js +41 -21
  52. package/core/engineCamera.js +32 -0
  53. package/core/errorCodes.js +478 -32
  54. package/core/errorHints.js +41 -142
  55. package/core/errors.js +31 -8
  56. package/core/events.generated.js +13 -7
  57. package/core/gameLights.js +69 -0
  58. package/core/grayMap.js +20 -0
  59. package/core/grid.js +14 -13
  60. package/core/gridLoad.js +2 -1
  61. package/core/ground.js +6 -4
  62. package/core/headlessLoad.js +55 -0
  63. package/core/holds.js +78 -50
  64. package/core/inputContext.js +11 -7
  65. package/core/inputDefaults.js +24 -21
  66. package/core/inputPad.js +1 -1
  67. package/core/inputPointer.js +1 -1
  68. package/core/inputTouch.js +2 -2
  69. package/core/lifecycle.js +46 -12
  70. package/core/lightWatch.js +9 -5
  71. package/core/loop.js +109 -43
  72. package/core/math.js +18 -3
  73. package/core/moduleSlots.js +100 -0
  74. package/core/moduleTypes.js +86 -0
  75. package/core/modules.js +147 -29
  76. package/core/movement.js +2 -2
  77. package/core/namedModel.js +74 -0
  78. package/core/opsCheck.js +3 -3
  79. package/core/opsFail.js +15 -6
  80. package/core/opsGuard.js +4 -4
  81. package/core/opsRun.js +4 -3
  82. package/core/owned.js +171 -0
  83. package/core/page.js +44 -10
  84. package/core/params.js +30 -8
  85. package/core/pictureSlots.js +33 -0
  86. package/core/pictureWriters.js +343 -0
  87. package/core/plugins.js +245 -0
  88. package/core/saveApply.js +99 -17
  89. package/core/saveFiles.js +8 -6
  90. package/core/saveValues.js +46 -0
  91. package/core/saveVersions.js +20 -3
  92. package/core/scatter.js +48 -19
  93. package/core/sceneDelta.js +211 -0
  94. package/core/sceneMethods.js +31 -33
  95. package/core/screenToGround.js +1 -1
  96. package/core/services.js +27 -11
  97. package/core/session.js +28 -25
  98. package/core/shaderCost.js +78 -0
  99. package/core/shadowTypes.js +3 -2
  100. package/core/shadows.js +405 -0
  101. package/core/sharedPoint.js +303 -0
  102. package/core/skip.js +36 -28
  103. package/core/stackFrames.js +45 -0
  104. package/core/stacks.js +166 -0
  105. package/core/startup.js +153 -13
  106. package/core/streamSources.js +0 -11
  107. package/core/targeting.js +1 -1
  108. package/core/textureBytes.js +20 -0
  109. package/core/thingExplain.js +3 -3
  110. package/core/thingOps.js +29 -6
  111. package/core/things.js +22 -12
  112. package/core/threadPure.js +7 -3
  113. package/core/threePatches.js +47 -0
  114. package/core/tier.js +21 -10
  115. package/core/time.js +236 -0
  116. package/core/uiClock.js +25 -0
  117. package/core/util.js +8 -2
  118. package/core/validate.js +66 -87
  119. package/core/view.js +43 -0
  120. package/core/wrap.js +106 -0
  121. package/docs/AI.md +95 -104
  122. package/docs/API.md +35 -31
  123. package/docs/CODEMAP.md +231 -176
  124. package/docs/COMMANDS.md +63 -39
  125. package/docs/CONVENTIONS.md +99 -31
  126. package/docs/MIGRATING-0.3.md +248 -0
  127. package/docs/MIGRATING-0.4.md +320 -0
  128. package/docs/MIGRATING-0.5.md +68 -0
  129. package/docs/MIGRATING-0.6.md +126 -0
  130. package/docs/MIGRATING-0.7.md +39 -0
  131. package/docs/PERF.md +35 -7
  132. package/docs/THREE.md +82 -28
  133. package/docs/api/ambience.md +0 -1
  134. package/docs/api/assets.md +15 -11
  135. package/docs/api/audio.md +10 -14
  136. package/docs/api/budget.md +4 -0
  137. package/docs/api/calendar.md +41 -0
  138. package/docs/api/cameraRig.md +16 -5
  139. package/docs/api/characters.md +41 -24
  140. package/docs/api/clock.md +6 -5
  141. package/docs/api/collision.md +10 -7
  142. package/docs/api/content.md +6 -4
  143. package/docs/api/dialogue.md +9 -9
  144. package/docs/api/engine.md +95 -65
  145. package/docs/api/events.md +20 -14
  146. package/docs/api/grids.md +10 -3
  147. package/docs/api/ground.md +1 -1
  148. package/docs/api/hud.md +5 -2
  149. package/docs/api/i18n.md +1 -1
  150. package/docs/api/input.md +13 -7
  151. package/docs/api/interactions.md +10 -6
  152. package/docs/api/inventory.md +17 -17
  153. package/docs/api/level.md +0 -2
  154. package/docs/api/lightPool.md +3 -1
  155. package/docs/api/music.md +1 -1
  156. package/docs/api/nav.md +3 -0
  157. package/docs/api/occlusion.md +5 -0
  158. package/docs/api/openWorld.md +2 -1
  159. package/docs/api/particles.md +6 -3
  160. package/docs/api/photo.md +0 -2
  161. package/docs/api/pickups.md +21 -0
  162. package/docs/api/post.md +8 -5
  163. package/docs/api/quests.md +2 -3
  164. package/docs/api/rigid.md +16 -14
  165. package/docs/api/saves.md +6 -4
  166. package/docs/api/settings.md +2 -3
  167. package/docs/api/sky.md +18 -49
  168. package/docs/api/stream.md +1 -1
  169. package/docs/api/terrain.md +16 -7
  170. package/docs/api/terrainDraw.md +12 -0
  171. package/docs/api/timeline.md +3 -4
  172. package/docs/api/tools.md +32 -15
  173. package/docs/api/triggers.md +7 -10
  174. package/docs/api/vegetation.md +17 -9
  175. package/docs/api/vegetationDraw.md +10 -0
  176. package/docs/api/water.md +9 -21
  177. package/docs/api/weather.md +10 -15
  178. package/docs/api/weatherDraw.md +10 -0
  179. package/docs/api/world.md +3 -2
  180. package/docs/recipes/01-new-game.md +52 -42
  181. package/docs/recipes/02-npc.md +24 -7
  182. package/docs/recipes/03-items-pickups.md +57 -22
  183. package/docs/recipes/04-quests.md +12 -5
  184. package/docs/recipes/05-props-bake.md +174 -22
  185. package/docs/recipes/06-clock-events.md +100 -52
  186. package/docs/recipes/07-flow-scenes-pause.md +50 -10
  187. package/docs/recipes/08-weather-sky.md +134 -37
  188. package/docs/recipes/09-materials-lights-models.md +185 -0
  189. package/docs/recipes/10-blender-level.md +16 -4
  190. package/docs/recipes/11-vehicles.md +67 -10
  191. package/docs/recipes/13-animation.md +23 -9
  192. package/docs/recipes/14-custom-module.md +63 -29
  193. package/docs/recipes/15-perf.md +31 -10
  194. package/docs/recipes/16-dev-bridge.md +74 -40
  195. package/docs/recipes/18-world.md +26 -14
  196. package/docs/recipes/19-shooting-picking.md +12 -10
  197. package/docs/recipes/20-content-actions-save.md +60 -18
  198. package/docs/recipes/21-camera.md +55 -17
  199. package/docs/recipes/22-shop-gold.md +3 -3
  200. package/docs/recipes/23-ops.md +17 -11
  201. package/docs/recipes/26-ui-parts.md +86 -13
  202. package/docs/recipes/27-net.md +11 -5
  203. package/docs/recipes/28-terrain.md +36 -3
  204. package/docs/recipes/29-grid.md +46 -19
  205. package/docs/recipes/30-templates.md +72 -15
  206. package/docs/recipes/31-audio.md +20 -12
  207. package/docs/recipes/32-action-game.md +51 -4
  208. package/docs/recipes/34-environment-lighting.md +108 -21
  209. package/docs/recipes/35-picture-from-reference.md +147 -0
  210. package/docs/recipes/36-sky-ground-plants.md +158 -0
  211. package/docs/recipes/{37-terrain-look-hooks.md → 37-terrain-hooks.md} +9 -12
  212. package/docs/recipes/38-environment-hooks.md +67 -0
  213. package/docs/recipes/40-scene.md +114 -32
  214. package/docs/recipes/42-terrain-shape.md +2 -2
  215. package/docs/recipes/43-shader-patches-surfaces.md +206 -0
  216. package/docs/recipes/44-water-weather-hooks.md +191 -0
  217. package/docs/recipes/45-cascaded-shadows.md +130 -23
  218. package/docs/recipes/46-blender-art-route.md +17 -20
  219. package/docs/recipes/47-island-snow-backdrop.md +13 -15
  220. package/docs/recipes/49-game-module-contract.md +30 -17
  221. package/docs/recipes/50-own-renderer.md +4 -4
  222. package/docs/recipes/51-capability-catalog.md +3 -3
  223. package/docs/recipes/52-around-the-picture.md +181 -0
  224. package/docs/recipes/53-ground-up-close.md +12 -12
  225. package/docs/recipes/54-three-idioms.md +88 -0
  226. package/docs/recipes/55-mods-time-wrap.md +124 -0
  227. package/docs/recipes/56-webgpu-tsl.md +303 -0
  228. package/docs/recipes/57-control.md +104 -0
  229. package/docs/recipes/58-input.md +60 -0
  230. package/docs/recipes/59-depth-post-effects.md +83 -0
  231. package/docs/recipes/60-judge-the-picture.md +70 -0
  232. package/docs/recipes/61-deploy.md +27 -0
  233. package/docs/recipes/62-picture-code.md +244 -0
  234. package/docs/recipes/63-third-person-start.md +77 -0
  235. package/docs/recipes/64-particles.md +35 -0
  236. package/examples/action/.threedog/content-index.json +1 -0
  237. package/examples/action/GAMEMAP.md +20 -14
  238. package/examples/action/assets.js +8 -0
  239. package/examples/action/content/actions.js +1 -1
  240. package/examples/action/content/audio.js +5 -5
  241. package/examples/action/main.js +12 -15
  242. package/examples/action/models.js +23 -24
  243. package/examples/action/picture/index.js +13 -0
  244. package/examples/action/picture/lights.js +35 -0
  245. package/examples/action/picture/materials.js +8 -0
  246. package/examples/action/picture/palette.js +33 -0
  247. package/examples/plain-picture/.threedog/content-index.json +1 -0
  248. package/examples/plain-picture/FINDINGS.md +53 -0
  249. package/examples/plain-picture/GAMEMAP.md +90 -0
  250. package/examples/plain-picture/main.js +48 -0
  251. package/examples/plain-picture/picture/index.js +21 -0
  252. package/examples/plain-picture/picture/lights.js +54 -0
  253. package/examples/plain-picture/picture/materials.js +24 -0
  254. package/examples/plain-picture/picture/palette.js +16 -0
  255. package/examples/plain-picture/picture/sky.js +37 -0
  256. package/examples/pullable.json +133 -0
  257. package/examples/rc2d/.threedog/content-index.json +1 -0
  258. package/examples/rc2d/GAMEMAP.md +88 -0
  259. package/examples/rc2d/README.md +57 -0
  260. package/examples/rc2d/main.js +55 -0
  261. package/examples/rc2d/picture/index.js +18 -0
  262. package/examples/rc2d/picture/lights.js +11 -0
  263. package/examples/rc2d/picture/materials.js +18 -0
  264. package/examples/rc2d/picture/palette.js +15 -0
  265. package/examples/rc2d/picture/post.js +11 -0
  266. package/examples/rc2d/rc2d.js +187 -0
  267. package/examples/rc2d/shaders.js +144 -0
  268. package/examples/sheepisland/.threedog/content-index.json +1 -0
  269. package/examples/sheepisland/GAMEMAP.md +22 -17
  270. package/examples/sheepisland/assets.js +5 -0
  271. package/examples/sheepisland/content/templates.js +1 -1
  272. package/examples/sheepisland/content/vegetation.js +3 -1
  273. package/examples/sheepisland/main.js +29 -18
  274. package/examples/sheepisland/{style/models.js → models.js} +13 -24
  275. package/examples/sheepisland/picture/index.js +20 -0
  276. package/examples/sheepisland/picture/lights.js +34 -0
  277. package/examples/sheepisland/picture/materials.js +61 -0
  278. package/examples/sheepisland/picture/palette.js +60 -0
  279. package/examples/sheepisland/picture/sky.js +20 -0
  280. package/examples/sheepisland/views.js +1 -1
  281. package/examples/styletest/.threedog/content-index.json +1 -0
  282. package/examples/styletest/GAMEMAP.md +25 -22
  283. package/examples/styletest/assets.js +6 -0
  284. package/examples/styletest/content/templates.js +1 -1
  285. package/examples/styletest/content/vegetation.js +1 -1
  286. package/examples/styletest/main.js +25 -34
  287. package/examples/styletest/models.js +30 -30
  288. package/examples/styletest/params.js +2 -5
  289. package/examples/styletest/picture/env.js +38 -0
  290. package/examples/styletest/picture/index.js +16 -0
  291. package/examples/styletest/picture/lights.js +9 -0
  292. package/examples/styletest/picture/materials.js +28 -0
  293. package/examples/styletest/picture/palette.js +22 -0
  294. package/examples/techniques/contact-shadows/README.md +91 -0
  295. package/examples/techniques/contact-shadows/contactShadows.js +67 -0
  296. package/examples/techniques/contact-shadows/main.js +55 -0
  297. package/examples/techniques/contact-shadows/picture/index.js +14 -0
  298. package/examples/techniques/contact-shadows/picture/lights.js +34 -0
  299. package/examples/techniques/contact-shadows/picture/materials.js +12 -0
  300. package/examples/techniques/contact-shadows/picture/palette.js +17 -0
  301. package/examples/techniques/day-night-grade/README.md +83 -0
  302. package/examples/techniques/day-night-grade/main.js +41 -0
  303. package/examples/techniques/day-night-grade/picture/index.js +20 -0
  304. package/examples/techniques/day-night-grade/picture/lights.js +45 -0
  305. package/examples/techniques/day-night-grade/picture/materials.js +15 -0
  306. package/examples/techniques/day-night-grade/picture/palette.js +59 -0
  307. package/examples/techniques/day-night-grade/picture/post.js +25 -0
  308. package/examples/techniques/day-night-grade/picture/sky.js +33 -0
  309. package/examples/techniques/interior-light/README.md +106 -0
  310. package/examples/techniques/interior-light/interiorLight.js +47 -0
  311. package/examples/techniques/interior-light/main.js +87 -0
  312. package/examples/techniques/interior-light/picture/index.js +24 -0
  313. package/examples/techniques/interior-light/picture/lights.js +52 -0
  314. package/examples/techniques/interior-light/picture/materials.js +13 -0
  315. package/examples/techniques/interior-light/picture/palette.js +32 -0
  316. package/examples/techniques/interior-light/picture/sky.js +40 -0
  317. package/examples/techniques/modular-building/README.md +126 -0
  318. package/examples/techniques/modular-building/kit.js +426 -0
  319. package/examples/techniques/modular-building/main.js +39 -0
  320. package/examples/techniques/modular-building/picture/index.js +17 -0
  321. package/examples/techniques/modular-building/picture/lights.js +26 -0
  322. package/examples/techniques/modular-building/picture/materials.js +13 -0
  323. package/examples/techniques/modular-building/picture/palette.js +23 -0
  324. package/examples/techniques/night-lights/README.md +95 -0
  325. package/examples/techniques/night-lights/main.js +47 -0
  326. package/examples/techniques/night-lights/nightLights.js +95 -0
  327. package/examples/techniques/night-lights/picture/index.js +18 -0
  328. package/examples/techniques/night-lights/picture/lights.js +44 -0
  329. package/examples/techniques/night-lights/picture/materials.js +15 -0
  330. package/examples/techniques/night-lights/picture/palette.js +34 -0
  331. package/examples/techniques/night-lights/picture/post.js +9 -0
  332. package/examples/techniques/night-lights/picture/sky.js +36 -0
  333. package/examples/techniques/outlines-and-rim/README.md +59 -0
  334. package/examples/techniques/outlines-and-rim/main.js +61 -0
  335. package/examples/techniques/outlines-and-rim/outlines.js +64 -0
  336. package/examples/techniques/outlines-and-rim/picture/index.js +16 -0
  337. package/examples/techniques/outlines-and-rim/picture/lights.js +18 -0
  338. package/examples/techniques/outlines-and-rim/picture/materials.js +11 -0
  339. package/examples/techniques/outlines-and-rim/picture/palette.js +16 -0
  340. package/examples/techniques/outlines-and-rim/picture/post.js +10 -0
  341. package/examples/techniques/procedural-animation/README.md +79 -0
  342. package/examples/techniques/procedural-animation/creature.js +44 -0
  343. package/examples/techniques/procedural-animation/main.js +47 -0
  344. package/examples/techniques/procedural-animation/picture/index.js +15 -0
  345. package/examples/techniques/procedural-animation/picture/lights.js +35 -0
  346. package/examples/techniques/procedural-animation/picture/materials.js +10 -0
  347. package/examples/techniques/procedural-animation/picture/palette.js +16 -0
  348. package/examples/techniques/procedural-animation/picture/sky.js +31 -0
  349. package/examples/techniques/procedural-animation/proceduralAnim.js +118 -0
  350. package/examples/techniques/procedural-surface/README.md +69 -0
  351. package/examples/techniques/procedural-surface/main.js +65 -0
  352. package/examples/techniques/procedural-surface/picture/index.js +14 -0
  353. package/examples/techniques/procedural-surface/picture/lights.js +18 -0
  354. package/examples/techniques/procedural-surface/picture/materials.js +34 -0
  355. package/examples/techniques/procedural-surface/picture/palette.js +15 -0
  356. package/examples/techniques/procedural-surface/surface.js +120 -0
  357. package/examples/techniques/stylized-shading/README.md +74 -0
  358. package/examples/techniques/stylized-shading/main.js +62 -0
  359. package/examples/techniques/stylized-shading/picture/index.js +14 -0
  360. package/examples/techniques/stylized-shading/picture/lights.js +23 -0
  361. package/examples/techniques/stylized-shading/picture/materials.js +18 -0
  362. package/examples/techniques/stylized-shading/picture/palette.js +19 -0
  363. package/examples/techniques/stylized-shading/shading.js +131 -0
  364. package/examples/techniques/sun-and-key-light/README.md +133 -0
  365. package/examples/techniques/sun-and-key-light/keyLight.js +71 -0
  366. package/examples/techniques/sun-and-key-light/main.js +51 -0
  367. package/examples/techniques/sun-and-key-light/picture/index.js +13 -0
  368. package/examples/techniques/sun-and-key-light/picture/lights.js +33 -0
  369. package/examples/techniques/sun-and-key-light/picture/materials.js +9 -0
  370. package/examples/techniques/sun-and-key-light/picture/palette.js +29 -0
  371. package/examples/techniques/sun-and-key-light/picture/sky.js +16 -0
  372. package/examples/techniques/three-looks/README.md +21 -0
  373. package/examples/techniques/three-looks/main.js +58 -0
  374. package/examples/techniques/three-looks/picture/cartoon.js +23 -0
  375. package/examples/techniques/three-looks/picture/cinematic.js +27 -0
  376. package/examples/techniques/three-looks/picture/comic.js +27 -0
  377. package/examples/techniques/three-looks/picture/index.js +14 -0
  378. package/examples/techniques/three-looks/picture/sun.js +23 -0
  379. package/examples/techniques/wet-road/README.md +102 -0
  380. package/examples/techniques/wet-road/main.js +48 -0
  381. package/examples/techniques/wet-road/picture/index.js +17 -0
  382. package/examples/techniques/wet-road/picture/lights.js +57 -0
  383. package/examples/techniques/wet-road/picture/materials.js +16 -0
  384. package/examples/techniques/wet-road/picture/palette.js +24 -0
  385. package/examples/techniques/wet-road/picture/sky.js +46 -0
  386. package/examples/techniques/wet-road/wetRoad.js +209 -0
  387. package/examples/webgpu-tsl/.threedog/content-index.json +1 -0
  388. package/examples/webgpu-tsl/GAMEMAP.md +89 -0
  389. package/examples/webgpu-tsl/README.md +45 -0
  390. package/examples/webgpu-tsl/main.js +44 -0
  391. package/examples/webgpu-tsl/picture/index.js +18 -0
  392. package/examples/webgpu-tsl/picture/lights.js +25 -0
  393. package/examples/webgpu-tsl/picture/materials.js +36 -0
  394. package/examples/webgpu-tsl/picture/palette.js +23 -0
  395. package/examples/webgpu-tsl/picture/post.js +16 -0
  396. package/examples/webgpu-tsl/picture/sky.js +30 -0
  397. package/examples/world/.threedog/content-index.json +1 -0
  398. package/examples/world/GAMEMAP.md +31 -21
  399. package/examples/world/art/humanoid.js +38 -0
  400. package/examples/world/art/index.js +11 -0
  401. package/examples/world/art/models.js +57 -0
  402. package/examples/world/art/shapes.js +9 -0
  403. package/examples/world/assets.js +6 -0
  404. package/examples/world/content/audio.js +5 -5
  405. package/examples/world/content/items.js +1 -1
  406. package/examples/world/content/npcs.js +1 -1
  407. package/examples/world/content/props.js +1 -1
  408. package/examples/world/content/rules.js +1 -1
  409. package/examples/world/content/templates.js +1 -1
  410. package/examples/world/content/vegetation.js +1 -1
  411. package/examples/world/main.js +22 -18
  412. package/examples/world/models.js +17 -7
  413. package/examples/world/picture/index.js +20 -0
  414. package/examples/world/picture/lights.js +41 -0
  415. package/examples/world/picture/materials.js +34 -0
  416. package/examples/world/picture/palette.js +74 -0
  417. package/examples/world/picture/post.js +9 -0
  418. package/examples/world/picture/sky.js +39 -0
  419. package/index.d.ts +44 -54
  420. package/index.js +29 -25
  421. package/llms.txt +24 -15
  422. package/modules/ambience/Ambience.js +34 -23
  423. package/modules/calendar/Calendar.js +163 -0
  424. package/modules/calendar/contract.js +21 -0
  425. package/modules/calendar/index.js +82 -0
  426. package/modules/{sky → calendar}/schedule.js +17 -16
  427. package/modules/calendar/seasons.js +55 -0
  428. package/modules/camera/FirstPersonCamera.js +6 -15
  429. package/modules/camera/FixedCamera.js +33 -15
  430. package/modules/camera/FollowCamera.js +90 -16
  431. package/modules/camera/RtsCamera.js +18 -17
  432. package/modules/camera/common.js +73 -20
  433. package/modules/camera/contract.js +17 -0
  434. package/modules/camera/projection.js +11 -24
  435. package/modules/characters/Character.js +188 -48
  436. package/modules/characters/NPC.js +92 -41
  437. package/modules/characters/assetModel.js +8 -16
  438. package/modules/characters/behaviors.js +2 -1
  439. package/modules/characters/contract.js +13 -0
  440. package/modules/characters/footsteps.js +1 -1
  441. package/modules/characters/index.js +112 -49
  442. package/modules/characters/moveHelpers.js +4 -5
  443. package/modules/characters/movers/common.js +102 -19
  444. package/modules/characters/movers/manual.js +23 -0
  445. package/modules/characters/movers/rapier.js +19 -16
  446. package/modules/characters/movers/simple.js +14 -11
  447. package/modules/characters/movers/support.js +186 -0
  448. package/modules/characters/npcAvoid.js +47 -42
  449. package/modules/characters/npcSim.js +17 -9
  450. package/modules/characters/npcView.js +44 -16
  451. package/modules/characters/pathAsync.js +7 -3
  452. package/modules/characters/playerStrings.js +4 -3
  453. package/modules/characters/proceduralRig.js +19 -4
  454. package/modules/characters/useModel.js +2 -2
  455. package/modules/characters/vehicle.contract.js +21 -0
  456. package/modules/characters/walkTo.js +21 -7
  457. package/modules/collision/Collision.js +69 -27
  458. package/modules/collision/grid.js +8 -6
  459. package/modules/content/explain.js +2 -2
  460. package/modules/content/fields.js +102 -0
  461. package/modules/content/ids.js +8 -6
  462. package/modules/content/index.js +104 -27
  463. package/modules/content/loader.js +45 -33
  464. package/modules/content/models.js +58 -42
  465. package/modules/content/packs.js +6 -5
  466. package/modules/content/parts.js +41 -0
  467. package/modules/content/props.js +20 -11
  468. package/modules/content/rules.js +66 -0
  469. package/modules/content/stages.js +80 -0
  470. package/modules/content/templates.js +123 -30
  471. package/modules/debug/DebugPanel.js +24 -17
  472. package/modules/flow/contract.js +16 -0
  473. package/modules/flow/index.js +21 -15
  474. package/modules/gameplay/Container.js +41 -32
  475. package/modules/gameplay/Containers.js +30 -15
  476. package/modules/gameplay/Dialogue.js +113 -55
  477. package/modules/gameplay/Interactions.js +273 -72
  478. package/modules/gameplay/Inventory.js +72 -76
  479. package/modules/gameplay/Quests.js +75 -39
  480. package/modules/gameplay/boxOps.js +3 -3
  481. package/modules/gameplay/dialogue.contract.js +21 -0
  482. package/modules/gameplay/dialogueBox.js +4 -2
  483. package/modules/gameplay/dialogueBubbles.js +116 -0
  484. package/modules/gameplay/interactionPrompt.js +4 -1
  485. package/modules/gameplay/interactions.contract.js +16 -0
  486. package/modules/gameplay/inventory.contract.js +23 -0
  487. package/modules/gameplay/inventoryOps.js +19 -17
  488. package/modules/gameplay/pickups.js +306 -85
  489. package/modules/gameplay/questLog.js +6 -6
  490. package/modules/gameplay/quests.contract.js +17 -0
  491. package/modules/grid/Grid.js +92 -50
  492. package/modules/grid/Layer.js +27 -13
  493. package/modules/grid/index.js +96 -43
  494. package/modules/grid/ops.js +20 -18
  495. package/modules/grid/preview.js +37 -29
  496. package/modules/grid/strings.js +12 -0
  497. package/modules/grid/tiles.js +19 -22
  498. package/modules/hlod/index.js +52 -19
  499. package/modules/hud/index.js +48 -20
  500. package/modules/hud/parts.js +28 -13
  501. package/modules/level/heightfield.js +3 -1
  502. package/modules/level/index.js +49 -23
  503. package/modules/level/nodes.js +4 -3
  504. package/modules/lights/index.js +47 -19
  505. package/modules/music/Music.js +38 -21
  506. package/modules/music/rules.js +1 -1
  507. package/modules/nav/index.js +48 -42
  508. package/modules/net/Client.js +13 -6
  509. package/modules/net/Host.js +19 -5
  510. package/modules/net/Net.js +2 -1
  511. package/modules/net/index.js +13 -8
  512. package/modules/net/sync.js +9 -8
  513. package/modules/net/transports.js +77 -27
  514. package/modules/particles/Particles.js +58 -28
  515. package/modules/particles/contract.js +17 -0
  516. package/modules/particles/effect.js +54 -11
  517. package/modules/photo/Photo.js +56 -38
  518. package/modules/rigid/RigidBodies.js +194 -32
  519. package/modules/rigid/Vehicles.js +18 -15
  520. package/modules/rigid/sync.js +62 -17
  521. package/modules/settings/Settings.js +60 -55
  522. package/modules/settings/apply.js +38 -3
  523. package/modules/settings/sections.js +5 -3
  524. package/modules/settings/strings.js +3 -2
  525. package/modules/settings/view.js +5 -3
  526. package/modules/sky/Sky.js +132 -205
  527. package/modules/sky/clouds.js +37 -23
  528. package/modules/sky/dome.js +100 -0
  529. package/modules/sky/domeLayers.js +30 -15
  530. package/modules/sky/environment.js +45 -99
  531. package/modules/sky/fog.js +9 -139
  532. package/modules/sky/frame.js +60 -56
  533. package/modules/sky/season.js +21 -0
  534. package/modules/sky/shader.js +63 -35
  535. package/modules/sky/skyModule.js +52 -37
  536. package/modules/sky/tint.js +59 -0
  537. package/modules/terrain/ChunkManager.js +194 -110
  538. package/modules/terrain/chunkJob.js +1 -1
  539. package/modules/terrain/chunkQueries.js +6 -4
  540. package/modules/terrain/draw.js +154 -0
  541. package/modules/terrain/index.js +87 -54
  542. package/modules/terrain/terrainDefaults.js +2 -2
  543. package/modules/terrain/terrainEdit.js +18 -20
  544. package/modules/terrain/terrainGen.js +6 -4
  545. package/modules/terrain/terrainIsland.js +5 -4
  546. package/modules/terrain/terrainShape.js +12 -12
  547. package/modules/terrain/terrainShapeMain.js +8 -7
  548. package/modules/terrain/terrainTexture.js +21 -19
  549. package/modules/timeline/Timeline.js +95 -43
  550. package/modules/timeline/Tween.js +18 -10
  551. package/modules/timeline/letterbox.js +2 -2
  552. package/modules/timeline/shots.js +5 -1
  553. package/modules/triggers/index.js +111 -76
  554. package/modules/vegetation/Vegetation.js +229 -112
  555. package/modules/vegetation/densityMap.js +62 -0
  556. package/modules/vegetation/draw.js +191 -0
  557. package/modules/vegetation/groundChunks.js +52 -58
  558. package/modules/vegetation/index.js +32 -11
  559. package/modules/vegetation/modelGeometry.js +3 -2
  560. package/modules/vegetation/nearFade.js +8 -2
  561. package/modules/water/Water.js +157 -72
  562. package/modules/water/surface.js +86 -47
  563. package/modules/weather/Weather.js +96 -103
  564. package/modules/weather/particles.js +37 -14
  565. package/modules/weather/shaders.js +1 -1
  566. package/modules/weather/strings.js +2 -2
  567. package/modules/weather/weatherDraw.js +141 -0
  568. package/modules/world/World.js +26 -9
  569. package/modules/world/explain.js +1 -1
  570. package/modules/world/index.js +18 -4
  571. package/modules/world/persist.js +62 -2
  572. package/modules/world/pos.js +3 -2
  573. package/modules/world/records.js +8 -6
  574. package/modules/world/sim.js +60 -20
  575. package/modules/world/simFar.js +4 -3
  576. package/modules/world/state.js +3 -2
  577. package/modules/world/thingSource.js +1 -1
  578. package/modules/world/views.js +8 -6
  579. package/package.json +8 -3
  580. package/presets.js +43 -29
  581. package/render/PostFX.js +318 -135
  582. package/render/backend.js +486 -0
  583. package/render/cascades.js +195 -0
  584. package/render/cascades.tsl.js +96 -0
  585. package/render/daylight.js +39 -0
  586. package/render/detail.js +122 -41
  587. package/render/effects.js +155 -48
  588. package/render/engineUniforms.js +10 -1
  589. package/render/fuse.js +5 -4
  590. package/render/fx/cel.tsl.js +42 -0
  591. package/render/fx/cloudShadow.tsl.js +16 -0
  592. package/render/fx/detail.tsl.js +66 -0
  593. package/render/fx/index.js +28 -0
  594. package/render/fx/lighting.tsl.js +28 -0
  595. package/render/fx/nodeErrors.tsl.js +68 -0
  596. package/render/fx/noise.tsl.js +12 -0
  597. package/render/fx/objectOrigin.tsl.js +42 -0
  598. package/render/fx/particles.tsl.js +139 -0
  599. package/render/fx/patchNodes.tsl.js +403 -0
  600. package/render/fx/postWebGPU.tsl.js +181 -0
  601. package/render/fx/season.tsl.js +13 -0
  602. package/render/fx/sky.tsl.js +187 -0
  603. package/render/fx/uniforms.tsl.js +67 -0
  604. package/render/fx/water.tsl.js +53 -0
  605. package/render/fx/wind.tsl.js +22 -0
  606. package/render/fxNumbers.js +36 -0
  607. package/render/hotGlsl.js +24 -0
  608. package/render/layers.js +14 -0
  609. package/render/lighting.js +71 -18
  610. package/render/lightmap.js +142 -0
  611. package/render/lights.js +47 -6
  612. package/render/materials.js +55 -152
  613. package/render/modeling.js +73 -0
  614. package/render/neutral.js +23 -0
  615. package/render/occlusion.js +184 -0
  616. package/render/ownFrame.js +76 -0
  617. package/render/patches.js +317 -35
  618. package/render/postWebGL.js +205 -0
  619. package/render/probes.js +288 -0
  620. package/render/shaderErrors.js +154 -0
  621. package/render/slots.js +165 -0
  622. package/render/terms.js +163 -0
  623. package/render/uniformDecl.js +4 -3
  624. package/types/common.d.ts +2 -2
  625. package/types/core.d.ts +757 -346
  626. package/types/gameplay.d.ts +539 -330
  627. package/types/generated/core/Audio.d.ts +26 -42
  628. package/types/generated/core/Batching.d.ts +6 -2
  629. package/types/generated/core/Budget.d.ts +2 -8
  630. package/types/generated/core/DebugOverrides.d.ts +58 -9
  631. package/types/generated/core/I18n.d.ts +2 -2
  632. package/types/generated/core/Input.d.ts +110 -32
  633. package/types/generated/core/Ops.d.ts +31 -0
  634. package/types/generated/core/Random.d.ts +2 -2
  635. package/types/generated/core/Saves.d.ts +10 -2
  636. package/types/generated/core/Stream.d.ts +1 -1
  637. package/types/generated/core/Threads.d.ts +4 -1
  638. package/types/generated/core/Views.d.ts +0 -1
  639. package/types/generated/core/audioVoice.d.ts +17 -9
  640. package/types/generated/core/control.d.ts +55 -0
  641. package/types/generated/core/page.d.ts +9 -2
  642. package/types/generated/core/session.d.ts +2 -1
  643. package/types/generated/modules/ambience/Ambience.d.ts +0 -9
  644. package/types/generated/modules/calendar/Calendar.d.ts +84 -0
  645. package/types/generated/modules/calendar/index.d.ts +10 -0
  646. package/types/generated/modules/debug/DebugPanel.d.ts +2 -2
  647. package/types/generated/modules/grid/Grid.d.ts +61 -25
  648. package/types/generated/modules/grid/Layer.d.ts +13 -5
  649. package/types/generated/modules/grid/index.d.ts +56 -20
  650. package/types/generated/modules/music/Music.d.ts +5 -3
  651. package/types/generated/modules/net/index.d.ts +3 -3
  652. package/types/generated/modules/net/transports.d.ts +12 -3
  653. package/types/generated/modules/particles/Particles.d.ts +13 -6
  654. package/types/generated/modules/sky/Sky.d.ts +85 -110
  655. package/types/generated/modules/sky/skyModule.d.ts +1 -1
  656. package/types/generated/modules/timeline/Timeline.d.ts +8 -6
  657. package/types/generated/modules/water/Water.d.ts +50 -3
  658. package/types/generated/modules/weather/Weather.d.ts +44 -15
  659. package/types/generated/modules/weather/weatherDraw.d.ts +11 -0
  660. package/types/generated/modules/world/World.d.ts +20 -5
  661. package/types/generated/render/PostFX.d.ts +109 -29
  662. package/types/generated/render/lighting.d.ts +29 -0
  663. package/types/generated/render/materials.d.ts +31 -50
  664. package/types/generated/render/modeling.d.ts +30 -0
  665. package/types/generated/render/occlusion.d.ts +13 -0
  666. package/types/generated/render/patches.d.ts +16 -2
  667. package/types/generated/ui/UI.d.ts +6 -3
  668. package/types/nav.d.ts +6 -0
  669. package/types/physics.d.ts +140 -45
  670. package/types/tsl.d.ts +94 -0
  671. package/types/world.d.ts +489 -122
  672. package/ui/Focus.js +35 -14
  673. package/ui/LoadingScreen.js +3 -3
  674. package/ui/Parts.js +35 -15
  675. package/ui/UI.js +27 -17
  676. package/ui/cursor.js +115 -0
  677. package/ui/defaults.js +15 -11
  678. package/ui/theme.js +36 -27
  679. package/ui/touchPart.js +2 -2
  680. package/core/claims.js +0 -51
  681. package/core/look/coreParts.js +0 -112
  682. package/core/look/layers.js +0 -136
  683. package/core/look/part.js +0 -173
  684. package/core/look/report.js +0 -79
  685. package/core/look/write.js +0 -86
  686. package/core/renamed.js +0 -22
  687. package/core/styleParts.js +0 -98
  688. package/docs/api/entities.md +0 -61
  689. package/docs/api/style.md +0 -134
  690. package/docs/recipes/09-style-pack.md +0 -169
  691. package/docs/recipes/35-style-from-reference.md +0 -84
  692. package/docs/recipes/36-sky-ground-plant-looks.md +0 -118
  693. package/docs/recipes/38-environment-look-hooks.md +0 -88
  694. package/docs/recipes/41-thing-registry.md +0 -93
  695. package/docs/recipes/43-shader-patches-surface-looks.md +0 -135
  696. package/docs/recipes/44-water-weather-look-hooks.md +0 -135
  697. package/docs/recipes/48-make-material.md +0 -70
  698. package/docs/recipes/52-look.md +0 -146
  699. package/examples/action/look.js +0 -5
  700. package/examples/sheepisland/style/index.js +0 -79
  701. package/examples/styletest/look.js +0 -11
  702. package/examples/styletest/overrides.js +0 -33
  703. package/examples/styletest/panel.js +0 -135
  704. package/modules/entities/Entities.js +0 -243
  705. package/modules/entities/build.js +0 -25
  706. package/modules/entities/index.js +0 -4
  707. package/modules/sky/calendar.js +0 -80
  708. package/modules/sky/cascades.js +0 -125
  709. package/modules/sky/layers.js +0 -69
  710. package/modules/sky/look.js +0 -51
  711. package/modules/sky/lookFog.js +0 -80
  712. package/modules/sky/lookShadow.js +0 -50
  713. package/modules/sky/lookSky.js +0 -108
  714. package/modules/sky/shadow.js +0 -74
  715. package/modules/terrain/chunkLevels.js +0 -40
  716. package/modules/terrain/lookGround.js +0 -61
  717. package/modules/terrain/mountTerrain.js +0 -32
  718. package/modules/vegetation/lookWind.js +0 -37
  719. package/modules/water/look.js +0 -80
  720. package/modules/weather/look.js +0 -75
  721. package/modules/world/cells.js +0 -42
  722. package/render/lookSurface.js +0 -161
  723. package/render/postLook.js +0 -86
  724. package/render/surface.js +0 -69
  725. package/types/style.d.ts +0 -643
@@ -7,11 +7,13 @@
7
7
  // Data must be plain values (putting a three.js object or a function in it throws in dev); position is a plain { x, y, z }. Don't hold on to rec: loading a
8
8
  // save swaps in new objects, so keep the id and use world.get(id).
9
9
  import { DEV, fmt } from '../../core/validate.js';
10
+ import { checkTypeRule } from '../../core/moduleTypes.js';
10
11
  import { addRecord, setRecord, removeRecord, queryRecords } from './records.js';
11
12
  import { Views } from './views.js';
12
13
  import { Sim } from './sim.js';
13
14
  import { initState, mixInternals } from './state.js';
14
15
  import { putPos, centerOf } from './pos.js';
16
+ import { codedError } from '../../core/errorHints.js';
15
17
 
16
18
  const STRINGS = {
17
19
  anchor: 'world.anchor must be null, an Object3D, a Vector3 / { x, z } or [x, y, z]; got {got}',
@@ -58,7 +60,7 @@ export class World {
58
60
  get anchor() { return this._anchor; }
59
61
  set anchor(a) {
60
62
  const ok = a == null || a.isObject3D || (Array.isArray(a) ? a.length === 3 && a.every(Number.isFinite) : Number.isFinite(a.x) && Number.isFinite(a.z));
61
- if (!ok) throw new Error(fmt(STRINGS.anchor, { got: JSON.stringify(a) }));
63
+ if (!ok) throw codedError('world-option', fmt(STRINGS.anchor, { got: JSON.stringify(a) }));
62
64
  this._anchor = a ?? null;
63
65
  }
64
66
 
@@ -81,7 +83,7 @@ export class World {
81
83
  * @param {{ initial?: boolean, save?: boolean }} [opts]
82
84
  * @returns {WorldRecord | null}
83
85
  */
84
- add(def, opts) { return addRecord(this, def, opts); }
86
+ add(def, opts) { checkTypeRule(this.engine, 'world.write', `added a world record (${def?.kind ?? '?'})`); return addRecord(this, def, opts); }
85
87
  /**
86
88
  * Where a record comes from (filled in dev and test builds; null in release): { definedAt: 'content/props.js:14' } for a content entry,
87
89
  * { level, node } for a level-model node, { template } when it is a template instance, { spawned: { op, tick } } for a record created during play.
@@ -116,7 +118,7 @@ export class World {
116
118
  * @param {Record<string, any>} patch
117
119
  * @returns {WorldRecord}
118
120
  */
119
- set(id, patch) { return setRecord(this, id, patch); }
121
+ set(id, patch) { checkTypeRule(this.engine, 'world.write', `set world record ${id}`); return setRecord(this, id, patch); }
120
122
  /**
121
123
  * Move a record (no event; use it in simulate for things that move every step); still saved (saves diff against content).
122
124
  * The model of a positionFrom 'record' (default) record follows this frame; to do something else with the position in presentation, compare in update
@@ -137,7 +139,7 @@ export class World {
137
139
  * @param {string} id
138
140
  * @returns {void}
139
141
  */
140
- remove(id) { removeRecord(this, id); }
142
+ remove(id) { checkTypeRule(this.engine, 'world.write', `removed world record ${id}`); removeRecord(this, id); }
141
143
  /**
142
144
  * Query records; returns an array. With near only nearby cells are scanned and results are sorted nearest first (radius defaults to 30 m); where filters
143
145
  * further. For neighbor queries every step use forEachNear
@@ -163,14 +165,14 @@ export class World {
163
165
  * focus, teleport destination) and torn down when far from all of them (radius × 1.25); tearing down never touches the record. Callbacks:
164
166
  * build(rec) → three.js object (may be async). world adds it to the scene and places it at rec.position; if it throws / fails / returns a non-object:
165
167
  * reported once, does not block ready, retried when you leave and come back.
166
- * update(rec, obj, dt): called every frame for records that have a model (change the look from the data, e.g. an opened chest swaps texture).
168
+ * update(rec, obj, dt): called every frame for records that have a model (change the picture from the data, e.g. an opened chest swaps texture).
167
169
  * dispose(rec, obj): called on teardown (record first, model second); if omitted, engine.remove(obj).
168
170
  * show(rec) → false: this record has no model right now (picked up, waiting to respawn); re-evaluated when world.set changes records of this kind.
169
171
  * radius: meters, or a function (for distances that change, like terrain view distance); defaults to world.radius. Registering the same kind again: old
170
172
  * models are torn down with the old dispose and rebuilt with the new one.
171
173
  * positionFrom: 'record' (default, the model follows the record every frame) or 'view' (the model moves itself, e.g. driven by a character mover; model
172
174
  * position is copied back to the record at the end of each fixed step).
173
- * @example engine.world.present('chest', { build: rec => new THREE.Mesh(boxGeo, makeMaterial('prop')), dispose: (rec, obj) => engine.remove(obj), show: rec
175
+ * @example engine.world.present('chest', { build: rec => new THREE.Mesh(boxGeo, new THREE.MeshStandardMaterial()), dispose: (rec, obj) => engine.remove(obj), show: rec
174
176
  * => !rec.looted })
175
177
  * @param {string} kind
176
178
  * @param {{ build: (rec: WorldRecord) => any, update?: (rec: WorldRecord, obj: any, dt: number) => void, dispose?: (rec: WorldRecord, obj: any) => void,
@@ -184,6 +186,11 @@ export class World {
184
186
  * @returns {any}
185
187
  */
186
188
  view(id) { return this._v.map.get(id)?.obj ?? null; }
189
+ /**
190
+ * @internal Tear down this record's model now and build it again on the next refresh (a content template stage that names another model).
191
+ * The record is untouched; safe to call from a present update (the views loop tolerates the entry going away).
192
+ */
193
+ rebuild(id) { this._v.unview(id); this._v.dirty = true; }
187
194
  /**
188
195
  * All models that should exist near the stream sources are built (async ones too; failed builds do not count as pending). The loading screen waits for it; to
189
196
  * wait yourself, await world.whenReady @type {boolean}
@@ -205,20 +212,30 @@ export class World {
205
212
  * far(rec, dt): farther away, once every farEvery seconds; dt is the seconds accumulated since the last simulation (can catch up a long time at once); on the
206
213
  * far → near step, far runs first to pay back the owed time.
207
214
  * With only far (crops), near also advances via far; with only near, far records are not simulated and owed time is not made up.
208
- * Both dt are accumulated fixed-step seconds (not multiplied by clock.timeScale). For things measured in game clock (grows over days) store engine.clock.now
209
- * and compare.
215
+ * Both dt are accumulated real (fixed-step) seconds (not multiplied by clock.rate). For things measured in game clock (grows over days) store engine.clock.now
216
+ * and compare. channel: a time channel name (or rec => name) the kind lives on; then both dt are multiplied by that channel's speed (and the record's
217
+ * engine.time.local stack), so bullet time on 'enemies' slows near and far records alike (NPCs use it with their own channel).
210
218
  * radius defaults to the present radius ('view' widened by 1.25), or world.radius without present; may also be a function.
219
+ * fullRadius + nearEvery (tiers, for crowds): records within fullRadius m (number or function) run near every step; the rest of the near zone runs near
220
+ * once every nearEvery seconds, dt being the seconds since its last turn (deterministic: turns go by hashed id and step count, saved).
211
221
  * worker: true (experimental) runs far in engine.threads workers (batched per step, written back 4 steps later, bit-identical with threads off). far must
212
222
  * then be self-contained:
213
223
  * it is recompiled from source and sees only (rec, dt) and globals like Math; an outside variable throws naming it (threads on or off alike).
214
224
  * @example engine.world.simulate('zombie', { near: (rec, dt) => chase(rec, dt), far: (rec, dt) => wander(rec, dt), farEvery: 2 })
225
+ * @example engine.world.simulate('slime', { near: chase, far: wander, channel: 'enemies' }) // engine.mod('time.enemies', { mul: 0.35, for: 2 }) slows them
215
226
  * @example engine.world.simulate('crop', { far: (rec, dt) => { rec.growth = Math.min(1, rec.growth + dt / 600); }, worker: true })
216
227
  * @param {string} kind
217
228
  * @param {{ near?: (rec: WorldRecord, dt: number, obj: any) => void, far?: (rec: WorldRecord, dt: number) => void, farEvery?: number, radius?: number | (()
218
- * => number), worker?: boolean }} opts
229
+ * => number), fullRadius?: number | (() => number), nearEvery?: number, worker?: boolean, channel?: string | ((rec: WorldRecord) => string) }} opts
219
230
  * @returns {{ remove(): void }}
220
231
  */
221
232
  simulate(kind, opts) { return this._s.simulate(kind, opts); }
233
+ /**
234
+ * Stop running simulate() handlers on this machine until remove(): a multiplayer client lets the host simulate and only receives the records.
235
+ * Public so net() needs no world internals.
236
+ * @returns {{ remove(): void }}
237
+ */
238
+ pauseSimulation() { const s = this._s; s.fixed = () => {}; return { remove: () => { delete s.fixed; } }; }
222
239
  /** Number of fixed steps simulated */ get steps() { return this._s.n; }
223
240
 
224
241
 
@@ -8,4 +8,4 @@ export function worldExplain(e, t, out) {
8
8
  out.state = { ...t.fields, position: t.position };
9
9
  Object.assign(out.rules, { blocksMovement: rec.collide ?? false, pickable: rec.static !== false, interact: null, note: RULES_NOTE });
10
10
  }
11
- export const RULES_NOTE = 'blocksMovement = the collision shape (box / circle) walkers stop at; blocking sight is not modelled by the engine';
11
+ const RULES_NOTE = 'blocksMovement = the collision shape (box / circle) walkers stop at; blocking sight is not modelled by the engine';
@@ -9,6 +9,20 @@ import { worldExplain } from './explain.js';
9
9
  import { closest, warnOnce, DEV } from '../../core/validate.js';
10
10
  import { readParams, keysSchema } from '../../core/params.js';
11
11
 
12
+ const PLACED = '[session] {n} world record(s) were created or removed by code before the game started ({ids}): a new game should equal the content. '
13
+ + 'Move them to content (content/props.js with an id and a template from content/templates.js), or create them during play inside an op';
14
+
15
+ /**
16
+ * Dev check on the new-game state (saves.register checkNewGame, run once start() finished): authored things come from content, so a new game has
17
+ * no runtime records but the player and removes nothing. Changed fields are not checked: simulation may already move authored records (an NPC
18
+ * walking its schedule) while loading runs in real time. Lives here, not in core/session.js: only the world knows its own save format.
19
+ * @param {any} d the world part of the new-game state
20
+ */
21
+ function codePlaced(d) {
22
+ const ids = [...Object.entries(d?.records || {}).filter(([, r]) => r.kind !== 'player').map(([id]) => id), ...(d?.removed || [])];
23
+ if (ids.length) warnOnce(PLACED.replace('{n}', String(ids.length)).replace('{ids}', ids.slice(0, 8).join(', ') + (ids.length > 8 ? ', …' : '')));
24
+ }
25
+
12
26
  const ORPHAN = '[world] the save has changes for {n} id(s) that the content no longer defines: {list}. They are kept in the save (restoring the entry brings them back); '
13
27
  + "if an entry was renamed, add the pair to content/renames.js (export default { 'oldId': 'newId' }) and the saved state follows it; 'oldId': null drops it";
14
28
  const RENAME_TARGET = '[world] content/renames.js moves saved state to {list}, which no content entry defines: fix the new id (did you mean {near}?)';
@@ -25,12 +39,12 @@ export function world(opts = {}) {
25
39
  readParams('world', WORLD_PARAMS, opts);
26
40
  let w = null;
27
41
  return {
28
- name: 'world', label: 'World data', params: WORLD_PARAMS, options: opts, stage: 'world',
29
- install(e) {
42
+ name: 'world', type: 'world', provides: ['world'], label: 'World data', params: WORLD_PARAMS, options: opts, stage: 'ground',
43
+ install(e, ctx) { e.i18n.add({ 'zh-CN': { 'module.world': '世界数据' }, en: { 'module.world': 'world data' } });
30
44
  w = new World(e, opts);
31
45
  e.stream.player.at(() => w.center); // the default stream source sits where gameplay is simulated (world.anchor, else the player)
32
46
  e.stream.readyCheck('world', s => s.detail !== 'full' || w.ready);
33
- e.saves.register('world', { atomic: true, version: 3, migrate: WORLD_MIGRATE, save: () => w.toJSON(), load: d => w.fromJSON(d) });
47
+ e.saves.register('world', { atomic: true, version: 5, migrate: WORLD_MIGRATE, save: () => w.toJSON(), load: d => w.fromJSON(d), checkNewGame: codePlaced });
34
48
  e._things.addSource(recordSource(w)); // engine.thing / thing.set / the shared id space reach the records through this
35
49
  e.explainWith(worldExplain);
36
50
  e.budget.metric('worldRecords', () => w.records.size);
@@ -48,7 +62,7 @@ export function world(opts = {}) {
48
62
  const bad = [...w._renames].filter(([, b]) => b != null && !w._base.has(b) && due(b));
49
63
  if (bad.length) warnOnce(RENAME_TARGET.replace('{list}', bad.map(([a, b]) => `${b} (from ${a})`).join(', ')).replace('{near}', closest(bad[0][1], [...w._base.keys()]) ?? '-'));
50
64
  };
51
- for (const ev of ['engine:ready', 'save:loaded', 'level:loaded']) e.events.on(ev, () => { if (e.ready) warn(); });
65
+ for (const ev of ['engine:ready', 'save:loaded', 'level:loaded']) ctx.track(e.events.on(ev, () => { if (e.ready) warn(); }));
52
66
  }
53
67
  return w;
54
68
  },
@@ -7,17 +7,23 @@
7
7
  // Loading before content is loaded works too: changes and removals are remembered and applied / skipped when content is added. Things newly added to content after a game update still show up with an old save.
8
8
  // Temporary things (data for effects, one-off spawns): add(def, { save: false }) — not saved, cleared on load.
9
9
  // Changes are found by comparing JSON against the original content, not by events: fields changed directly inside simulate are saved too.
10
- // Save format (part 'world', version 3): every record is keyed by its stable id, and only what play changed is stored:
10
+ // Save format (part 'world', version 4): every record is keyed by its stable id, and only what play changed is stored:
11
11
  // { seq, step, time, records: { id: whole runtime record without id }, changed: { id: { set?: changed fields, del?: [removed fields] } },
12
12
  // removed: [ids of removed initial records], owed: { id: simulation seconds owed, only for kinds simulated with far } }
13
13
  // Version 1 kept records as an array: migrate step 1 (WORLD_MIGRATE) turns it into the id-keyed object.
14
14
  // Version 2 numbered runtime records `<kind>-<n>`; version 3 uses `<kind>#<n>`, so a runtime id can never equal an authored one (authored ids may not
15
15
  // contain `#`, content/ids.js). Step 2 renames them (legacyRuntimeIds says which), and the containers part follows with the same map (a template
16
16
  // instance's container is keyed by the record id).
17
+ // Version 4: a character's motion (Character.saveMotion: on the player record itself, in rec.motion for NPCs) keeps its jump state as
18
+ // jump: { coyote, used } instead of the flat coyote field (the jump API: air jumps count used jumps). Step 3 moves it.
19
+ // Version 5: an NPC's talk / talkLabel / talkRadius became interact { label, op: 'npc.talk', args: { script }, radius } (talking is one interact op
20
+ // among many). Step 4 moves them, on whole records and on changed fields.
17
21
  // Removed fields are recorded separately (not saved as null): after loading it is "no such field", same as in a live run; a field that was null stays null.
18
22
  // step / time are the simulation step count and accumulated seconds: far simulation takes turns by step-count buckets, so one save advances the same way every time (see sim.js).
19
23
 
20
24
  import { legacyRuntimeIds, renameIdKeys, renameIdValues } from '../../core/saveIds.js';
25
+ import { codedError } from '../../core/errorHints.js';
26
+ import { isPlainObject } from '../../core/util.js';
21
27
 
22
28
  const PLAIN_STRINGS = {
23
29
  msg: 'world data must be plain values (number, string, boolean, array, plain object): {path} is {what}. Put models in world.present() and logic in world.simulate()',
@@ -25,7 +31,7 @@ const PLAIN_STRINGS = {
25
31
  };
26
32
  /** Dev-time check: data must not contain three.js objects, functions or DOM elements (saves can only store plain values) @internal */
27
33
  export function checkPlain(v, path, depth = 0) {
28
- const fail = what => { throw new Error(PLAIN_STRINGS.msg.replace('{path}', path).replace('{what}', what)); };
34
+ const fail = what => { throw codedError('world-plain', PLAIN_STRINGS.msg.replace('{path}', path).replace('{what}', what)); };
29
35
  if (v == null || typeof v !== 'object') { if (typeof v === 'function') fail(PLAIN_STRINGS.fn); return; }
30
36
  const what = v.isObject3D ? PLAIN_STRINGS.obj : v.isMaterial || v.isBufferGeometry || v.isTexture ? PLAIN_STRINGS.asset : typeof Element !== 'undefined' && v instanceof Element ? PLAIN_STRINGS.dom : null;
31
37
  if (what) fail(what);
@@ -52,6 +58,27 @@ export const WORLD_MIGRATE = {
52
58
  if (!map.size) return d;
53
59
  return { ...d, records: renameIdValues(renameIdKeys(d.records, map), map), changed: renameIdValues(d.changed, map), owed: renameIdKeys(d.owed, map) };
54
60
  },
61
+ 3: d => { // motion coyote -> jump: { coyote, used: 0 } (whole runtime records and changed fields; the player keeps it on the record, NPCs in motion)
62
+ const fix = m => { if (!m || typeof m !== 'object' || !('coyote' in m)) return m; const { coyote, ...rest } = m; return { ...rest, jump: { coyote: coyote ?? 0, used: 0 } }; };
63
+ const rec = r => { const o = fix(r); return o && typeof o === 'object' && o.motion ? { ...o, motion: fix(o.motion) } : o; };
64
+ const map = (o, f) => o && typeof o === 'object' ? Object.fromEntries(Object.entries(o).map(([k, v]) => [k, f(v)])) : o;
65
+ return { ...d, records: map(d.records, rec), changed: map(d.changed, c => c?.set ? { ...c, set: rec(c.set) } : c) };
66
+ },
67
+ 4: d => { // NPC talk / talkLabel / talkRadius -> interact (records of any kind that carry talk: only NPCs had it)
68
+ const fix = r => {
69
+ if (!r || typeof r !== 'object' || !('talk' in r)) return r;
70
+ const { talk, talkLabel, talkRadius, ...rest } = r;
71
+ return { ...rest, interact: talk ? { label: talkLabel ?? null, op: 'npc.talk', args: { script: talk }, radius: talkRadius ?? 3.2 } : null };
72
+ };
73
+ const map = (o, f) => o && typeof o === 'object' ? Object.fromEntries(Object.entries(o).map(([k, v]) => [k, f(v)])) : o;
74
+ // a changed entry of an initial NPC: a removed talk means it no longer talks (interact removed). A label / radius alone (set or removed) has no
75
+ // script to build an interact from, so it is dropped and the content's interact stays; a stray key would sit on the record unread
76
+ const OLD = ['talkLabel', 'talkRadius'];
77
+ const strip = s => s && typeof s === 'object' && !('talk' in s) && OLD.some(k => k in s) ? Object.fromEntries(Object.entries(s).filter(([k]) => !OLD.includes(k))) : s;
78
+ const del = l => Array.isArray(l) ? [...new Set(l.filter(k => !OLD.includes(k)).map(k => k === 'talk' ? 'interact' : k))] : l;
79
+ const change = c => c && typeof c === 'object' ? { ...c, ...(c.set && { set: strip(fix(c.set)) }), ...(c.del && { del: del(c.del) }) } : c;
80
+ return { ...d, records: map(d.records, fix), changed: map(d.changed, change) };
81
+ },
55
82
  };
56
83
 
57
84
 
@@ -70,8 +97,41 @@ export function saveWorld(w) {
70
97
  return { seq: w._seq, ...w._s.toJSON(), records, changed, removed: [...w._removed] };
71
98
  }
72
99
 
100
+ // Shape check of a world save before anything is replaced. Why here and not in add(): putPos only checks in dev, and a save bypasses add() entirely,
101
+ // so a hand-edited or damaged record ({ x: 1e12, y: null, z: 'abc' }) went straight into the records and threw later in a listener / a mover,
102
+ // with the game half-loaded. Refusing throws: saves.apply rolls the whole load back and reports this message (save-bad-record).
103
+ const SHAPE_STRINGS = {
104
+ bad: "world save: {path} {why} (got {got}); the save was refused and the game was rolled back. The save was edited by hand or damaged: fix that field, or load another save",
105
+ obj: 'must be a plain object', kind: 'must have kind (a string)', pos: 'must be { x, y, z } with finite numbers within ±{max}',
106
+ arr: 'must be an array of record ids', count: 'must be a finite number >= 0',
107
+ };
108
+ /** Positions beyond this are damage, not a big world: float32 models are already centimetres off at 1e5 and useless far before 1e7 */
109
+ const POS_MAX = 1e7;
110
+ /** Throw save-bad-record for the first malformed core field of a world save (fields of the game's own are not checked) @internal */
111
+ function checkWorldSave(d) {
112
+ const bad = (path, why, got) => { throw codedError('save-bad-record', SHAPE_STRINGS.bad.replace('{path}', path).replace('{why}', why.replace('{max}', String(POS_MAX))).replace('{got}', String(JSON.stringify(got)).slice(0, 120))); };
113
+ const pos = (path, p) => { if (!isPlainObject(p) || !['x', 'y', 'z'].every(k => Number.isFinite(p[k]) && Math.abs(p[k]) <= POS_MAX)) bad(path, SHAPE_STRINGS.pos, p); };
114
+ const num = (path, v) => { if (v !== undefined && !(Number.isFinite(v) && v >= 0)) bad(path, SHAPE_STRINGS.count, v); };
115
+ if (!isPlainObject(d)) bad('the world part', SHAPE_STRINGS.obj, d);
116
+ num('seq', d.seq); num('step', d.step); num('time', d.time);
117
+ for (const f of ['records', 'changed', 'owed']) if (d[f] !== undefined && !isPlainObject(d[f])) bad(f, SHAPE_STRINGS.obj, d[f]);
118
+ if (d.removed !== undefined && !(Array.isArray(d.removed) && d.removed.every(id => typeof id === 'string'))) bad('removed', SHAPE_STRINGS.arr, d.removed);
119
+ for (const [id, r] of Object.entries(d.records ?? {})) {
120
+ if (!isPlainObject(r)) bad(`records.${id}`, SHAPE_STRINGS.obj, r);
121
+ if (typeof r.kind !== 'string') bad(`records.${id}`, SHAPE_STRINGS.kind, r.kind);
122
+ if ('position' in r) pos(`records.${id}.position`, r.position);
123
+ }
124
+ for (const [id, c] of Object.entries(d.changed ?? {})) {
125
+ if (!isPlainObject(c) || (c.set !== undefined && !isPlainObject(c.set)) || (c.del !== undefined && !Array.isArray(c.del))) bad(`changed.${id}`, SHAPE_STRINGS.obj, c);
126
+ if (c.set && 'position' in c.set) pos(`changed.${id}.set.position`, c.set.position);
127
+ if (c.set && 'kind' in c.set && typeof c.set.kind !== 'string') bad(`changed.${id}.set`, SHAPE_STRINGS.kind, c.set.kind);
128
+ }
129
+ for (const [id, v] of Object.entries(d.owed ?? {})) num(`owed.${id}`, v);
130
+ }
131
+
73
132
  /** Load: replace runtime records wholesale; loaded initial records go back to the original then get the save's changes; unloaded content waits for its add. Independent of the order of content.load @internal */
74
133
  export function loadWorld(w, d) {
134
+ checkWorldSave(d); // before anything is cleared: a refused save leaves the world as it was (the rollback then has nothing to undo here)
75
135
  w._v.clear();
76
136
  w.records.clear(); w._cells.clear(); w._unsaved.clear();
77
137
  for (const id of [...w._origin.keys()]) if (!w._base.has(id)) w._origin.delete(id); // runtime records come from the save now (no op to name)
@@ -1,6 +1,7 @@
1
1
  // Position read / write for world: shared by add / move / query. A wrong position (a Vector3 used as an array, [x, z] with only two numbers) silently becomes NaN and null in the save,
2
2
  // so dev builds throw on the spot and say how to fix it.
3
3
  import { DEV } from '../../core/validate.js';
4
+ import { codedError } from '../../core/errorHints.js';
4
5
 
5
6
  const STRINGS = {
6
7
  arr: '{fn}: an array position must be [x, y, z] (three numbers); for a horizontal position only, write { x, z }',
@@ -10,10 +11,10 @@ const STRINGS = {
10
11
  /** Write position v (Vector3 / object / [x, y, z] / { x, z }) into p; y stays unchanged if omitted @internal */
11
12
  export function putPos(fn, v, p) {
12
13
  const arr = Array.isArray(v), o = v.isObject3D ? v.position : v;
13
- if (DEV && arr && v.length !== 3) throw new Error(STRINGS.arr.replace('{fn}', fn));
14
+ if (DEV && arr && v.length !== 3) throw codedError('bad-position', STRINGS.arr.replace('{fn}', fn));
14
15
  const x = arr ? v[0] : o.x, y = arr ? v[1] : o.y ?? p.y, z = arr ? v[2] : o.z;
15
16
  // check before writing: a bad position leaves no half-written NaN in the data
16
- if (DEV && !(Number.isFinite(x) && Number.isFinite(y) && Number.isFinite(z))) throw new Error(STRINGS.nan.replace('{fn}', fn).replace('{got}', JSON.stringify(v)));
17
+ if (DEV && !(Number.isFinite(x) && Number.isFinite(y) && Number.isFinite(z))) throw codedError('bad-position', STRINGS.nan.replace('{fn}', fn).replace('{got}', JSON.stringify(v)));
17
18
  p.x = x; p.y = y; p.z = z;
18
19
  }
19
20
  /** Query center: objects use position, arrays are [x, y, z], others (Vector3 / { x, z }) are used as is, no allocation @internal */
@@ -1,9 +1,11 @@
1
1
  // World record mutations (add / rest / orphans / set / remove): the bodies behind the World methods of the same names. World.js keeps the public
2
2
  // JSDoc and signatures; these functions take the world as `w` and reach its internals the same way sim.js / views.js / persist.js do.
3
- import { DEV, checkOptionsArg, fmt } from '../../core/validate.js';
3
+ import { DEV, fmt } from '../../core/validate.js';
4
+ import { readParams, keysSchema } from '../../core/params.js';
4
5
  import { checkPlain } from './persist.js';
5
6
  import { putPos, centerOf } from './pos.js';
6
7
  import { claimId } from '../../core/things.js';
8
+ import { codedError } from '../../core/errorHints.js';
7
9
 
8
10
  export const STRINGS = {
9
11
  noKind: 'world.add() needs a kind (what sort of thing this is), e.g. world.add({ kind: "crate", position: [0, 0, 0] })',
@@ -15,10 +17,10 @@ export const STRINGS = {
15
17
 
16
18
  export function addRecord(w, def, opts) {
17
19
  DEV && w.engine.ops.guard('world.add');
18
- if (!def?.kind) throw new Error(STRINGS.noKind);
19
- if (DEV) { checkOptionsArg('world.add(def, opts)', opts, ['initial', 'save']); checkPlain({ ...def, position: undefined }, def.kind); }
20
+ if (!def?.kind) throw codedError('world-add', STRINGS.noKind);
21
+ if (DEV) { readParams('world.add(def, opts)', keysSchema(['initial', 'save']), opts); checkPlain({ ...def, position: undefined }, def.kind); }
20
22
  const { id: given, kind, position, ...rest } = def, initial = !!opts?.initial;
21
- if (initial && given == null) throw new Error(fmt(STRINGS.initialId, { kind }));
23
+ if (initial && given == null) throw codedError('world-add', fmt(STRINGS.initialId, { kind }));
22
24
  const id = given ?? `${kind}#${++w._seq}`, have = w.records.get(id), p = { x: 0, y: 0, z: 0 };
23
25
  if (position) putPos('world.add()', position, p);
24
26
  const rec = { id, kind, position: p, ...rest };
@@ -29,7 +31,7 @@ export function addRecord(w, def, opts) {
29
31
  if (w._removed.has(id)) return null;
30
32
  return w._insert(w._fromBase(id, w._base.get(id)), true);
31
33
  }
32
- if (have) throw new Error(fmt(STRINGS.dupId, { id }));
34
+ if (have) throw codedError('world-id', fmt(STRINGS.dupId, { id }));
33
35
  claimId(w.engine, id);
34
36
  if (opts?.save === false) w._unsaved.add(id);
35
37
  if (DEV) w._origin.set(id, { spawned: { op: w.engine.ops.running, tick: w.engine.tick } }); // who made it (inspect / pick)
@@ -55,7 +57,7 @@ export function orphanIds(w) {
55
57
  export function setRecord(w, id, patch) {
56
58
  DEV && w.engine.ops.guard('world.set');
57
59
  const rec = w._need(id, 'set');
58
- if (DEV) { if ('id' in patch || 'kind' in patch) throw new Error(fmt(STRINGS.setKey, { id })); checkPlain({ ...patch, position: undefined }, id); }
60
+ if (DEV) { if ('id' in patch || 'kind' in patch) throw codedError('world-add', fmt(STRINGS.setKey, { id })); checkPlain({ ...patch, position: undefined }, id); }
59
61
  const { position, ...rest } = patch;
60
62
  Object.assign(rec, rest);
61
63
  if (position) w.move(id, position);
@@ -1,6 +1,9 @@
1
1
  // Simulation layer of world: near records every fixed step, far records in id buckets taking turns under a per-step cap. The public API is in World.js
2
2
  // (simulate / anchor); this is the implementation.
3
- // Time: the dt of both near and far is "accumulated fixed-step seconds" (same ruler as every engine hook's dt, not multiplied by clock.timeScale).
3
+ // Time: the dt of both near and far is "accumulated fixed-step seconds" (real seconds, the same ruler as a plain onFixed dt; not multiplied by clock.rate).
4
+ // simulate(kind, { channel }) puts the kind on a time channel (engine.time): every dt handed to near / far (the owed payback and engine.skip's catch-up too)
5
+ // is multiplied by that channel's speed now, times the record's own engine.time.local stack, so bullet time on 'enemies' slows near and far alike.
6
+ // channel may be a function of the record (NPCs: each record names its own). The bookkeeping below stays in real seconds; only the handed dt is scaled.
4
7
  // For one record going near, far, near again, the dts add up to the elapsed time:
5
8
  // far dt = seconds accumulated since the last simulation; on the far → near step, far first pays back the owed time, then near runs.
6
9
  // A kind with only far (crops) does not split near / far and always advances at far's pace; a kind with only near is not simulated while far and its owed time
@@ -14,9 +17,15 @@
14
17
  // changes after loading;
15
18
  // when near records affect each other (avoiding each other, fighting over the same thing), sorting by id keeps "kept running" and "saved then loaded"
16
19
  // bit-identical.
20
+ // Near tiers (simulate({ fullRadius, nearEvery })): records inside fullRadius run every step; the rest of the near zone runs in id-hash buckets once every
21
+ // nearEvery seconds with the accumulated dt (the far idea, inside the near zone). Why: a crowd that is visible but not close (hundreds of NPCs) paid the full
22
+ // mover cost every step. Buckets follow the hashed id and the step count (both saved), not distances measured on frame boundaries, so a loaded save runs the
23
+ // same records on the same steps as a live run.
17
24
 
18
- import { DEV, checkOptionsArg } from '../../core/validate.js';
25
+ import { DEV } from '../../core/validate.js';
26
+ import { readParams, keysSchema } from '../../core/params.js';
19
27
  import { FarFlights } from './simFar.js';
28
+ import { codedError } from '../../core/errorHints.js';
20
29
 
21
30
  /** Near simulation order: by id (independent of insertion order and loading) */
22
31
  const byId = (a, b) => a.rec.id < b.rec.id ? -1 : 1;
@@ -37,19 +46,31 @@ export class Sim {
37
46
  this.n = 0; // simulation step count (saved: buckets follow it, so after loading the same batch is up as in a live run)
38
47
  this.at = { x: 0, z: 0 }; // this step's simulation center (taken from world.anchor at the start of each step)
39
48
  this.dt = 0;
40
- this.list = []; // records to simulate near this step (reused, not allocated each step)
49
+ this.list = []; // records inside a near radius this step (reused, not allocated each step)
50
+ this.order = []; // last step's near list sorted by id: reused when the membership did not change (most steps), so no sort per step
41
51
  this.flights = new FarFlights(this); // far with worker: true (simFar.js)
42
52
  // created once, no closure per step
43
- this._pick = (rec, d2) => { const s = this.sims.get(rec.kind); if (s && d2 <= s.r2 && this.w._inZone(rec)) this.list.push(this.ents.get(rec.id)); };
53
+ this._pick = (rec, d2) => {
54
+ const s = this.sims.get(rec.kind);
55
+ if (s && d2 <= s.r2 && this.w._inZone(rec)) { const e = this.ents.get(rec.id); e.d2 = d2; this.list.push(e); }
56
+ };
44
57
  }
45
58
 
46
59
  simulate(kind, opts) {
47
- if (DEV) checkOptionsArg(`world.simulate('${kind}', opts)`, opts, ['near', 'far', 'farEvery', 'radius', 'worker']);
60
+ if (DEV) readParams(`world.simulate('${kind}', opts)`, keysSchema(['near', 'far', 'farEvery', 'radius', 'fullRadius', 'nearEvery', 'worker', 'channel']), opts);
48
61
  const s = { ...opts };
62
+ if (s.channel != null && typeof s.channel !== 'string' && typeof s.channel !== 'function') {
63
+ throw codedError('world-option', `world.simulate('${kind}', { channel }): a time channel name ('world', 'player' or one from engine.time.channel(name)) or rec => name; got ${JSON.stringify(s.channel)}`);
64
+ }
49
65
  if (s.worker && s.far) this.flights.register(kind, s);
50
66
  this.sims.set(kind, s);
51
67
  return { remove: () => { if (this.sims.get(kind) === s) this.sims.delete(kind); } };
52
68
  }
69
+ /** dt as the kind's near / far gets it: on its time channel when simulate set one (real seconds otherwise) */
70
+ scaled(s, rec, dt) {
71
+ const ch = s.channel;
72
+ return ch == null ? dt : dt * this.w.engine.time.scale(typeof ch === 'function' ? ch(rec) : ch, rec.id);
73
+ }
53
74
  /** A new record starts counting time from the moment it is added (owed time from a save carries on) */
54
75
  added(rec) {
55
76
  const id = rec.id, o = this.owed.get(id);
@@ -82,13 +103,25 @@ export class Sim {
82
103
  if (!this.sims.size) return;
83
104
  let maxR2 = -1;
84
105
  // radius may be a function: asked once per kind per step
85
- for (const [kind, s] of this.sims) { s.r2 = s.near ? this.radius(kind, s) ** 2 : -1; if (s.r2 > maxR2) maxR2 = s.r2; }
106
+ for (const [kind, s] of this.sims) {
107
+ s.r2 = s.near ? this.radius(kind, s) ** 2 : -1; if (s.r2 > maxR2) maxR2 = s.r2;
108
+ // tiers: f2 = full-rate radius squared (Infinity = no tiers), P = steps between turns of the outer part
109
+ const f = s.fullRadius == null ? Infinity : typeof s.fullRadius === 'function' ? s.fullRadius() : s.fullRadius;
110
+ s.f2 = f * f; s.P = s.nearEvery ? Math.max(1, Math.round(s.nearEvery / dt)) : 1;
111
+ }
86
112
  if (maxR2 >= 0) {
87
113
  const L = this.list; L.length = 0;
88
114
  W._cells.forEach(this.at, Math.sqrt(maxR2), this._pick);
89
- L.sort(byId);
90
- for (const e of L) e.near = n; // mark first: isNear in simulate and skipping far both follow what was picked at the start of this step
91
- for (const e of L) if (!e.dead) this.nearOne(e);
115
+ // same members as last step (every one was near on step n - 1 and the count matches): last step's sorted order is still the id order
116
+ let same = L.length === this.order.length;
117
+ if (same) for (const e of L) if (e.near !== n - 1) { same = false; break; }
118
+ const O = same ? this.order : (this.order = L.slice().sort(byId));
119
+ for (const e of O) e.near = n; // mark first: isNear in simulate and skipping far both follow what was picked at the start of this step
120
+ for (const e of O) {
121
+ if (e.dead) continue;
122
+ const s = this.sims.get(e.rec.kind);
123
+ if (s && (s.P === 1 || e.d2 <= s.f2 || (n + e.h) % s.P === 0)) this.nearOne(e, s);
124
+ }
92
125
  }
93
126
  // far: first the ones queued by the previous step, then this step's bucket; at most farMaxPerTick per step, the rest queue (dt accumulates, no time lost)
94
127
  const max = W.farMaxPerTick, q = this.backlog;
@@ -111,24 +144,28 @@ export class Sim {
111
144
  }
112
145
  this.flights.flush();
113
146
  }
114
- nearOne(e) {
115
- const rec = e.rec, s = this.sims.get(rec.kind), now = this.time, dt = this.dt;
116
- if (!s?.near) return; // earlier simulation in this step replaced the registration of this kind
147
+ nearOne(e, s) {
148
+ const rec = e.rec, now = this.time, dt = this.dt;
149
+ if (!s.near) return; // earlier simulation in this step replaced the registration of this kind
117
150
  // For records whose model drives the position (positionFrom 'view'): near simulation needs the model, so build it right now instead of next frame —
118
151
  // otherwise the steps before the model is built and the first step after loading would differ from a live run (the result would depend on frame boundaries)
119
152
  const V = this.w._v, p = V.presenters.get(rec.kind);
120
153
  if (p?.positionFrom === 'view' && !V.map.has(rec.id) && (!p.show || p.show(rec))) V.build(rec, p);
121
154
  if (e.flight) this.flights.land(e);
122
- const owed = now - dt - e.last; // just came in from far: first make up the stretch far has not simulated
155
+ // near takes one step, or for a tiered kind everything since its last turn up to one tier period (the outer part waits P steps between turns; a record
156
+ // moving inward catches up its gap the same way); what is older came from far: far pays that stretch back first
157
+ const step = s.P > 1 ? Math.max(dt, Math.min(now - e.last, s.P * dt)) : dt;
158
+ const owed = now - step - e.last;
123
159
  e.last = now;
124
- if (owed > 1e-9 && s.far) s.far(rec, owed);
125
- s.near(rec, dt, this.w.view(rec.id));
160
+ if (owed > 1e-9 && s.far) s.far(rec, this.scaled(s, rec, owed));
161
+ s.near(rec, this.scaled(s, rec, step), this.w.view(rec.id));
126
162
  }
127
163
  farOne(e, s, now) {
128
164
  const dt = now - e.last;
129
165
  e.last = now;
130
166
  if (dt <= 0) return 0; // added during this step
131
- if (s.pure) this.flights.add(e, s, dt); else s.far(e.rec, dt);
167
+ const d = this.scaled(s, e.rec, dt);
168
+ if (s.pure) this.flights.add(e, s, dt, d); else s.far(e.rec, d);
132
169
  return 1;
133
170
  }
134
171
  /** engine.skip: move simulation time without stepping; on the last segment (done) every record with far catches up what it owes in one far(rec, dt), in id order.
@@ -143,7 +180,8 @@ export class Sim {
143
180
  const owed = now - e.last;
144
181
  e.last = now;
145
182
  if (owed <= 0) continue;
146
- if (s.pure) this.flights.now(e, s, owed); else s.far(e.rec, owed);
183
+ const d = this.scaled(s, e.rec, owed);
184
+ if (s.pure) this.flights.now(e, s, d); else s.far(e.rec, d);
147
185
  }
148
186
  }
149
187
  rebucket(K, P) {
@@ -156,9 +194,11 @@ export class Sim {
156
194
  toJSON() {
157
195
  const owed = {}, W = this.w, t = this.time;
158
196
  // in flight (worker far not landed): the record does not have that stretch yet, so it is still owed
159
- // only kinds simulated with far owe time: a prop, pickup or near-only kind never makes it up, so it writes nothing (saves stay small)
197
+ // only kinds simulated with far owe time: a prop, pickup or near-only kind never makes it up, so it writes nothing (saves stay small);
198
+ // a tiered near record waiting for its turn does owe its gap (near pays it on the turn), so a loaded save hands it the same dt as a live run
160
199
  for (const [id, e] of this.ents) {
161
- if (!this.sims.get(e.rec.kind)?.far) continue;
200
+ const s = this.sims.get(e.rec.kind);
201
+ if (!s?.far && !(s?.P > 1 && e.near === this.n)) continue;
162
202
  const last = e.flight ? e.flight.from : e.last;
163
203
  if (t - last > 1e-6 && !W._unsaved.has(id)) owed[id] = t - last;
164
204
  }
@@ -168,7 +208,7 @@ export class Sim {
168
208
  /** Load: work back the last simulation time from "seconds owed"; records are re-added later by loadWorld */
169
209
  fromJSON(d) {
170
210
  for (const e of this.ents.values()) e.dead = true; // results still in flight belong to the old records: dropped
171
- this.ents.clear(); this.kinds.clear(); this.backlog.length = 0;
211
+ this.ents.clear(); this.kinds.clear(); this.backlog.length = 0; this.order.length = 0;
172
212
  this.n = d?.step ?? 0; this.time = d?.time ?? 0;
173
213
  this.owed = new Map(Object.entries(d?.owed || {}).map(([id, s]) => [id, this.time - s]));
174
214
  }
@@ -37,9 +37,10 @@ export class FarFlights {
37
37
  s.key = kind + '#' + ++this.defs;
38
38
  if (T.size) T.pureLane().broadcast({ def: s.key, src: s.pure.src, label }, 'def:' + s.key);
39
39
  }
40
- add(e, s, dt) {
40
+ /** dt: real seconds this turn covers (bookkeeping); d: the dt far gets (dt on the kind's time channel, sim.scaled) */
41
+ add(e, s, dt, d = dt) {
41
42
  let b = this.open.get(s); if (!b) this.open.set(s, b = []);
42
- b.push([e, dt]);
43
+ b.push([e, dt, d]);
43
44
  }
44
45
  /** End of the far pass: send each kind's batch */
45
46
  flush() {
@@ -49,7 +50,7 @@ export class FarFlights {
49
50
  send(s, items) {
50
51
  const engine = this.sim.w.engine, T = engine.threads;
51
52
  // copies taken now: what far sees is the record as of this step, whatever happens to it during the flight
52
- const f = { s, items, snaps: items.map(([e, dt]) => [structuredClone(e.rec), dt]), results: null };
53
+ const f = { s, items, snaps: items.map(([e, , d]) => [structuredClone(e.rec), d]), results: null };
53
54
  for (const [e, dt] of items) e.flight = { f, from: e.last - dt };
54
55
  const t = engine.commits.request({ lag: FAR_LAG, apply: r => this.apply(f, r), fallback: () => f.snaps.map((_, i) => this.compute(f, i)) });
55
56
  // a failed worker run is ignored: the fallback runs the same code here at the due step and throws the same (clear) error
@@ -3,8 +3,9 @@
3
3
  import { DEV, fmt } from '../../core/validate.js';
4
4
  import { STRINGS as RECORD_STRINGS, restRecord, orphanIds } from './records.js';
5
5
  import { saveWorld, loadWorld, renamePending } from './persist.js';
6
- import { Cells } from './cells.js';
6
+ import { Cells } from '../../core/cells.js';
7
7
  import { centerOf } from './pos.js';
8
+ import { codedError } from '../../core/errorHints.js';
8
9
 
9
10
  export function initState(w, cellSize) {
10
11
  /** @internal */ w._anchor = null;
@@ -88,7 +89,7 @@ class Internals {
88
89
  /** @internal */
89
90
  _inZone(rec) { return this.zone == null || rec.zone == null || rec.zone === this.zone; }
90
91
  /** @internal */
91
- _need(id, fn) { const r = this.records.get(id); if (!r) throw new Error(fmt(RECORD_STRINGS.noId, { fn, id })); return r; }
92
+ _need(id, fn) { const r = this.records.get(id); if (!r) throw codedError('world-record', fmt(RECORD_STRINGS.noId, { fn, id })); return r; }
92
93
  /** Copy the original initial record and apply the changes from the save @internal */
93
94
  _fromBase(id, base) {
94
95
  const rec = structuredClone(base), d = this._pending.get(id);
@@ -2,7 +2,7 @@
2
2
  // explain, plus idOf / view / ids / restore for the model link and undo), never the World class, so engine.thing, thing.set and the shared id space
3
3
  // work the same whether or not this module is installed.
4
4
  const SAY = {
5
- defined: 'defined in {at}: edit it there to change the level for good (ops change only this session), or: npx threedog content set {id} <field> <json>',
5
+ defined: 'defined in {at}: edit it there to change the level for good (ops change only this session), or: threedog content set {id} <field> <json>',
6
6
  node: 'level {level} node {node}: change it in the level model',
7
7
  spawned: 'made during play{op}: not in content, saved whole',
8
8
  };
@@ -4,7 +4,9 @@
4
4
  // It only decides "which records have a model" and never affects gameplay: simulation follows the gameplay anchor (sim.js), and how fast models are built, or
5
5
  // whether they are built, does not change simulation results.
6
6
  import { reportError } from '../../core/errors.js';
7
- import { DEV, checkOptionsArg, warnOnce } from '../../core/validate.js';
7
+ import { DEV, warnOnce } from '../../core/validate.js';
8
+ import { readParams, keysSchema } from '../../core/params.js';
9
+ import { codedError } from '../../core/errorHints.js';
8
10
 
9
11
  const STRINGS = {
10
12
  noBuild: 'world.present(\'{kind}\', { build }) needs build: rec => three.js object',
@@ -15,7 +17,7 @@ const STRINGS = {
15
17
  positionFrom: 'positionFrom of world.present(\'{kind}\') must be \'record\' (the model follows the record, default) or \'view\' (the model moves itself, the record follows the model)',
16
18
  };
17
19
  /** Dev: code wrote the position of a model world places every frame (positionFrom 'record'): the write is lost next frame */
18
- const moved = (e, id) => e.thingConflict(`world model of '${id}' was moved by code outside its present update; world puts it back on the record every frame (positionFrom 'record'). Move the record instead: ops.run('thing.set', { id: '${id}', position }) or world.move, or present it with positionFrom: 'view'`);
20
+ const moved = (e, id) => e.thingConflict(`world model of '${id}' was moved by code outside its present update; world puts it back on the record every frame (positionFrom 'record'). Move the record instead: ops.run('thing.set', { id: '${id}', position }) or world.move, or present it with positionFrom: 'view'. Picture-only motion (a leg swing, a stagger) goes in the present's update(rec, obj, dt), which runs right after the placing`);
19
21
  const say = (s, kind, id = '', got = '') => s.replace(/\{kind\}/g, kind).replace('{id}', id).replace('{got}', got);
20
22
  const OPTS = ['build', 'update', 'dispose', 'show', 'radius', 'positionFrom'];
21
23
  const FULL = { detail: 'full' };
@@ -37,10 +39,10 @@ export class Views {
37
39
  }
38
40
 
39
41
  present(kind, opts) {
40
- if (typeof opts?.build !== 'function') throw new Error(say(STRINGS.noBuild, kind));
42
+ if (typeof opts?.build !== 'function') throw codedError('world-present', say(STRINGS.noBuild, kind));
41
43
  if (DEV) {
42
- checkOptionsArg(`world.present('${kind}', opts)`, opts, OPTS);
43
- if (opts.positionFrom != null && opts.positionFrom !== 'record' && opts.positionFrom !== 'view') throw new Error(say(STRINGS.positionFrom, kind));
44
+ readParams(`world.present('${kind}', opts)`, keysSchema(OPTS), opts);
45
+ if (opts.positionFrom != null && opts.positionFrom !== 'record' && opts.positionFrom !== 'view') throw codedError('world-present', say(STRINGS.positionFrom, kind));
44
46
  if (opts.dispose?.length === 1) warnOnce(say(STRINGS.disposeArgs, kind));
45
47
  }
46
48
  const old = this.presenters.get(kind);
@@ -152,7 +154,7 @@ export class Views {
152
154
  this.map.set(rec.id, v);
153
155
  const fail = err => { if (this.map.get(rec.id) === v) v.pending = false; reportError(e, err, say(STRINGS.failed, rec.kind), { soft: true }); };
154
156
  const done = obj => {
155
- if (!obj?.isObject3D) throw new Error(say(STRINGS.nullBuild, rec.kind, rec.id, String(obj)));
157
+ if (!obj?.isObject3D) throw codedError('world-present', say(STRINGS.nullBuild, rec.kind, rec.id, String(obj)));
156
158
  if (this.map.get(rec.id) !== v) { this.drop(rec, p, obj); return; } // no longer wanted by the time it was built
157
159
  v.obj = obj; v.pending = false; this.byObj.set(obj, rec.id);
158
160
  if (p.positionFrom === 'view') this.moving.add(rec.id);