threedog 0.7.0 → 1.0.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 (593) hide show
  1. package/CHANGELOG.md +411 -1
  2. package/README.md +8 -11
  3. package/core/{Animator.js → assets/Animator.js} +30 -18
  4. package/core/{Assets.js → assets/Assets.js} +131 -56
  5. package/core/{Baked.js → assets/Baked.js} +4 -4
  6. package/core/assets/assetEntry.js +302 -0
  7. package/core/{assetHot.js → assets/assetHot.js} +9 -7
  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} +7 -14
  12. package/core/{namedModel.js → assets/namedModel.js} +17 -13
  13. package/core/{Audio.js → audio/Audio.js} +47 -25
  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} +15 -12
  18. package/core/{Random.js → base/Random.js} +7 -4
  19. package/core/{Vars.js → base/Vars.js} +14 -4
  20. package/core/{easing.js → base/easing.js} +1 -1
  21. package/core/{errorCodes.js → base/errorCodes.js} +151 -125
  22. package/core/{errorHints.js → base/errorHints.js} +17 -10
  23. package/core/{errors.js → base/errors.js} +12 -10
  24. package/core/{events.generated.js → base/events.generated.js} +11 -0
  25. package/core/base/follows.js +26 -0
  26. package/core/base/math.js +66 -0
  27. package/core/{params.js → base/params.js} +5 -6
  28. package/core/base/saveValues.js +81 -0
  29. package/core/base/sections.js +97 -0
  30. package/core/base/spelling.js +32 -0
  31. package/core/base/util.js +32 -0
  32. package/core/{validate.js → base/validate.js} +34 -34
  33. package/core/{Engine.js → engine/Engine.js} +137 -91
  34. package/core/{Loading.js → engine/Loading.js} +34 -5
  35. package/core/{copies.js → engine/copies.js} +4 -4
  36. package/core/{headlessLoad.js → engine/headlessLoad.js} +32 -15
  37. package/core/{lifecycle.js → engine/lifecycle.js} +41 -34
  38. package/core/{loop.js → engine/loop.js} +88 -49
  39. package/core/engine/moduleSlots.js +176 -0
  40. package/core/{moduleTypes.js → engine/moduleTypes.js} +26 -14
  41. package/core/engine/modules.js +503 -0
  42. package/core/{page.js → engine/page.js} +59 -29
  43. package/core/{plugins.js → engine/plugins.js} +21 -12
  44. package/core/{services.js → engine/services.js} +50 -40
  45. package/core/{startup.js → engine/startup.js} +66 -54
  46. package/core/{Input.js → input/Input.js} +67 -39
  47. package/core/{inputContext.js → input/inputContext.js} +14 -5
  48. package/core/input/inputKeyboard.js +39 -0
  49. package/core/{inputPad.js → input/inputPad.js} +24 -3
  50. package/core/{inputPointer.js → input/inputPointer.js} +11 -3
  51. package/core/input/inputSeat.js +66 -0
  52. package/core/{inputTouch.js → input/inputTouch.js} +24 -7
  53. package/core/{Budget.js → inspect/Budget.js} +21 -20
  54. package/core/{DebugOverrides.js → inspect/DebugOverrides.js} +43 -18
  55. package/core/{Describe.js → inspect/Describe.js} +34 -26
  56. package/core/{Inspect.js → inspect/Inspect.js} +39 -10
  57. package/core/{InspectMaterials.js → inspect/InspectMaterials.js} +7 -8
  58. package/core/{InspectPerf.js → inspect/InspectPerf.js} +19 -13
  59. package/core/{InspectScene.js → inspect/InspectScene.js} +8 -5
  60. package/core/{MaterialInfo.js → inspect/MaterialInfo.js} +3 -2
  61. package/core/{UrlState.js → inspect/UrlState.js} +60 -24
  62. package/core/{catalog.js → inspect/catalog.js} +15 -8
  63. package/core/{checks.js → inspect/checks.js} +7 -5
  64. package/core/{debugView.js → inspect/debugView.js} +4 -4
  65. package/core/{describeRender.js → inspect/describeRender.js} +24 -22
  66. package/core/{describeText.js → inspect/describeText.js} +17 -8
  67. package/core/inspect/geometryWatch.js +38 -0
  68. package/core/{lightWatch.js → inspect/lightWatch.js} +8 -8
  69. package/core/inspect/metadata.generated.js +4140 -0
  70. package/core/{pictureWriters.js → inspect/pictureWriters.js} +130 -47
  71. package/core/{shaderCost.js → inspect/shaderCost.js} +1 -1
  72. package/core/inspect/toolDoor.js +21 -0
  73. package/core/inspect/valueHistory.js +35 -0
  74. package/core/{Ops.js → ops/Ops.js} +44 -14
  75. package/core/{control.js → ops/control.js} +57 -31
  76. package/core/ops/holds.js +140 -0
  77. package/core/{opsAtomic.js → ops/opsAtomic.js} +18 -5
  78. package/core/{opsCheck.js → ops/opsCheck.js} +11 -10
  79. package/core/{opsFail.js → ops/opsFail.js} +5 -7
  80. package/core/{opsGuard.js → ops/opsGuard.js} +3 -3
  81. package/core/{opsRun.js → ops/opsRun.js} +9 -6
  82. package/core/{owned.js → ops/owned.js} +33 -19
  83. package/core/{sharedPoint.js → ops/sharedPoint.js} +13 -16
  84. package/core/{stackFrames.js → ops/stackFrames.js} +2 -2
  85. package/core/{stacks.js → ops/stacks.js} +34 -15
  86. package/core/{wrap.js → ops/wrap.js} +8 -6
  87. package/core/{SaveStore.js → saves/SaveStore.js} +53 -27
  88. package/core/{Saves.js → saves/Saves.js} +171 -54
  89. package/core/saves/saveApply.js +312 -0
  90. package/core/{saveFiles.js → saves/saveFiles.js} +45 -38
  91. package/core/{saveVersions.js → saves/saveVersions.js} +24 -23
  92. package/core/saves/session.js +231 -0
  93. package/core/saves/stateReplace.js +184 -0
  94. package/core/{Rays.js → scene/Rays.js} +44 -30
  95. package/core/{Views.js → scene/Views.js} +16 -8
  96. package/core/{adaptive.js → scene/adaptive.js} +19 -9
  97. package/core/{canvasBox.js → scene/canvasBox.js} +4 -3
  98. package/core/scene/compositeGround.js +72 -0
  99. package/core/scene/floor.js +17 -0
  100. package/core/{gameLights.js → scene/gameLights.js} +17 -7
  101. package/core/{grayMap.js → scene/grayMap.js} +8 -2
  102. package/core/{grid.js → scene/grid.js} +6 -4
  103. package/core/{gridLoad.js → scene/gridLoad.js} +1 -1
  104. package/core/scene/ground.contract.js +14 -0
  105. package/core/scene/ground.js +139 -0
  106. package/core/{movement.js → scene/movement.js} +3 -3
  107. package/core/{pictureSlots.js → scene/pictureSlots.js} +2 -2
  108. package/core/scene/pixel.js +154 -0
  109. package/core/scene/pixelRatio.js +167 -0
  110. package/core/{sceneDelta.js → scene/sceneDelta.js} +5 -5
  111. package/core/{sceneMethods.js → scene/sceneMethods.js} +43 -15
  112. package/core/scene/stepPoses.js +60 -0
  113. package/core/{targeting.js → scene/targeting.js} +4 -5
  114. package/core/{thingExplain.js → scene/thingExplain.js} +7 -6
  115. package/core/{thingOps.js → scene/thingOps.js} +25 -16
  116. package/core/{things.js → scene/things.js} +18 -5
  117. package/core/{threePatches.js → scene/threePatches.js} +1 -1
  118. package/core/{tier.js → scene/tier.js} +10 -0
  119. package/core/scene/view.js +161 -0
  120. package/core/{Batching.js → stream/Batching.js} +85 -28
  121. package/core/{Stream.js → stream/Stream.js} +80 -38
  122. package/core/{batchGroups.js → stream/batchGroups.js} +11 -9
  123. package/core/{chunkStream.js → stream/chunkStream.js} +40 -0
  124. package/core/{scatter.js → stream/scatter.js} +7 -4
  125. package/core/{streamSources.js → stream/streamSources.js} +14 -8
  126. package/core/{Commits.js → threads/Commits.js} +17 -11
  127. package/core/{Jobs.js → threads/Jobs.js} +25 -13
  128. package/core/{Threads.js → threads/Threads.js} +21 -18
  129. package/core/{threadPure.js → threads/threadPure.js} +7 -5
  130. package/core/{threadServe.js → threads/threadServe.js} +3 -3
  131. package/core/{Clock.js → time/Clock.js} +20 -11
  132. package/core/{dayTime.js → time/dayTime.js} +5 -1
  133. package/core/{skip.js → time/skip.js} +28 -21
  134. package/core/{time.js → time/time.js} +32 -20
  135. package/core/{uiClock.js → time/uiClock.js} +4 -4
  136. package/docs/AI.md +92 -72
  137. package/docs/API.md +33 -28
  138. package/docs/CODEMAP.md +121 -200
  139. package/docs/COMMANDS.md +77 -70
  140. package/docs/CONVENTIONS.md +167 -24
  141. package/docs/MIGRATING-0.8.md +171 -0
  142. package/docs/MIGRATING-1.0.md +101 -0
  143. package/docs/THREE.md +140 -38
  144. package/docs/api/assets.md +12 -13
  145. package/docs/api/audio.md +6 -5
  146. package/docs/api/budget.md +4 -4
  147. package/docs/api/calendar.md +10 -11
  148. package/docs/api/cameraRig.md +32 -29
  149. package/docs/api/characters.md +35 -24
  150. package/docs/api/clock.md +1 -1
  151. package/docs/api/collider3d.md +9 -0
  152. package/docs/api/collision.md +12 -9
  153. package/docs/api/content.md +18 -17
  154. package/docs/api/dialogue.md +5 -4
  155. package/docs/api/engine.md +58 -54
  156. package/docs/api/events.md +17 -6
  157. package/docs/api/flow.md +1 -1
  158. package/docs/api/grids.md +1 -1
  159. package/docs/api/ground.md +6 -7
  160. package/docs/api/hud.md +2 -2
  161. package/docs/api/i18n.md +6 -6
  162. package/docs/api/input.md +9 -8
  163. package/docs/api/interactions.md +5 -5
  164. package/docs/api/inventory.md +10 -10
  165. package/docs/api/jobs.md +5 -5
  166. package/docs/api/level.md +10 -9
  167. package/docs/api/lightPool.md +1 -6
  168. package/docs/api/music.md +3 -3
  169. package/docs/api/nav.md +14 -12
  170. package/docs/api/openWorld.md +1 -1
  171. package/docs/api/particles.md +10 -7
  172. package/docs/api/photo.md +4 -2
  173. package/docs/api/pickups.md +3 -3
  174. package/docs/api/post.md +21 -5
  175. package/docs/api/quests.md +7 -5
  176. package/docs/api/rays.md +7 -7
  177. package/docs/api/rigid.md +29 -19
  178. package/docs/api/saves.md +13 -11
  179. package/docs/api/settings.md +9 -8
  180. package/docs/api/sky.md +8 -7
  181. package/docs/api/stream.md +8 -9
  182. package/docs/api/swarm.md +34 -0
  183. package/docs/api/terrain.md +6 -8
  184. package/docs/api/terrainDraw.md +2 -2
  185. package/docs/api/timeline.md +4 -4
  186. package/docs/api/tools.md +27 -22
  187. package/docs/api/triggers.md +2 -0
  188. package/docs/api/vars.md +1 -1
  189. package/docs/api/vegetation.md +4 -3
  190. package/docs/api/vegetationDraw.md +2 -2
  191. package/docs/api/water.md +7 -3
  192. package/docs/api/weather.md +27 -12
  193. package/docs/api/weatherDraw.md +4 -4
  194. package/docs/api/world.md +6 -6
  195. package/docs/recipes/01-new-game.md +28 -43
  196. package/docs/recipes/02-npc.md +21 -23
  197. package/docs/recipes/03-items-pickups.md +37 -53
  198. package/docs/recipes/04-quests.md +5 -4
  199. package/docs/recipes/05-props-bake.md +34 -44
  200. package/docs/recipes/06-clock-events.md +31 -22
  201. package/docs/recipes/07-flow-scenes-pause.md +30 -32
  202. package/docs/recipes/08-weather-sky.md +91 -37
  203. package/docs/recipes/09-materials-lights-models.md +25 -39
  204. package/docs/recipes/10-blender-level.md +22 -11
  205. package/docs/recipes/11-vehicles.md +44 -24
  206. package/docs/recipes/12-navmesh.md +60 -15
  207. package/docs/recipes/13-animation.md +70 -22
  208. package/docs/recipes/14-custom-module.md +33 -20
  209. package/docs/recipes/15-perf.md +51 -28
  210. package/docs/recipes/16-dev-bridge.md +39 -58
  211. package/docs/recipes/18-world.md +49 -28
  212. package/docs/recipes/19-shooting-picking.md +7 -4
  213. package/docs/recipes/20-content-actions-save.md +55 -40
  214. package/docs/recipes/21-camera.md +47 -25
  215. package/docs/recipes/22-shop-gold.md +21 -16
  216. package/docs/recipes/23-ops.md +28 -24
  217. package/docs/recipes/26-ui-parts.md +25 -14
  218. package/docs/recipes/27-net.md +3 -5
  219. package/docs/recipes/28-terrain.md +119 -23
  220. package/docs/recipes/29-grid.md +3 -3
  221. package/docs/recipes/30-templates.md +63 -30
  222. package/docs/recipes/31-audio.md +7 -7
  223. package/docs/recipes/32-action-game.md +21 -11
  224. package/docs/recipes/33-stream-sources.md +6 -3
  225. package/docs/recipes/34-environment-lighting.md +72 -25
  226. package/docs/recipes/35-picture-from-reference.md +20 -23
  227. package/docs/recipes/36-ground-plants.md +106 -0
  228. package/docs/recipes/40-scene.md +18 -21
  229. package/docs/recipes/43-shader-patches-surfaces.md +27 -48
  230. package/docs/recipes/44-water-weather-hooks.md +56 -50
  231. package/docs/recipes/45-cascaded-shadows.md +41 -20
  232. package/docs/recipes/46-blender-art-route.md +9 -10
  233. package/docs/recipes/49-game-module-contract.md +7 -6
  234. package/docs/recipes/50-own-renderer.md +3 -2
  235. package/docs/recipes/51-capability-catalog.md +14 -8
  236. package/docs/recipes/52-around-the-picture.md +56 -100
  237. package/docs/recipes/53-ground-up-close.md +61 -24
  238. package/docs/recipes/55-mods-time-wrap.md +17 -20
  239. package/docs/recipes/56-webgpu-tsl.md +28 -15
  240. package/docs/recipes/57-control.md +39 -12
  241. package/docs/recipes/58-input.md +15 -2
  242. package/docs/recipes/59-depth-post-effects.md +1 -1
  243. package/docs/recipes/60-judge-the-picture.md +30 -25
  244. package/docs/recipes/62-picture-code.md +129 -39
  245. package/docs/recipes/63-third-person-start.md +19 -5
  246. package/docs/recipes/64-particles.md +54 -5
  247. package/docs/recipes/65-swarm.md +140 -0
  248. package/docs/recipes/66-common-tasks.md +313 -0
  249. package/examples/action/.threedog/content-index.json +1 -1
  250. package/examples/action/GAMEMAP.md +5 -5
  251. package/examples/perf-island/.threedog/content-index.json +1 -0
  252. package/examples/{sheepisland → perf-island}/GAMEMAP.md +15 -14
  253. package/examples/{sheepisland → perf-island}/assets.js +1 -1
  254. package/examples/{sheepisland → perf-island}/main.js +8 -8
  255. package/examples/{sheepisland → perf-island}/models.js +1 -1
  256. package/examples/{sheepisland → perf-island}/params.js +1 -1
  257. package/examples/{sheepisland → perf-island}/picture/index.js +1 -1
  258. package/examples/{sheepisland → perf-island}/picture/palette.js +2 -2
  259. package/examples/{sheepisland → perf-island}/views.js +1 -1
  260. package/examples/plain-picture/GAMEMAP.md +4 -1
  261. package/examples/rc2d/GAMEMAP.md +4 -3
  262. package/examples/rc2d/main.js +1 -3
  263. package/examples/rc2d/rc2d.js +1 -1
  264. package/examples/styletest/.threedog/content-index.json +1 -1
  265. package/examples/styletest/GAMEMAP.md +6 -5
  266. package/examples/techniques/contact-shadows/contactShadows.js +1 -1
  267. package/examples/techniques/contact-shadows/main.js +1 -1
  268. package/examples/techniques/interior-light/main.js +1 -1
  269. package/examples/techniques/modular-building/README.md +7 -6
  270. package/examples/techniques/outlines-and-rim/picture/post.js +1 -1
  271. package/examples/techniques/procedural-animation/README.md +1 -1
  272. package/examples/webgpu-tsl/GAMEMAP.md +2 -1
  273. package/examples/world/.threedog/content-index.json +1 -1
  274. package/examples/world/GAMEMAP.md +9 -7
  275. package/examples/world/main.js +3 -3
  276. package/examples/world/picture/sky.js +1 -1
  277. package/index.d.ts +16 -12
  278. package/index.js +53 -32
  279. package/llms.txt +11 -14
  280. package/modules/ambience/Ambience.js +16 -11
  281. package/modules/calendar/Calendar.js +19 -19
  282. package/modules/calendar/index.js +18 -16
  283. package/modules/calendar/schedule.js +11 -6
  284. package/modules/calendar/seasons.js +7 -7
  285. package/modules/camera/FirstPersonCamera.js +5 -5
  286. package/modules/camera/FixedCamera.js +43 -30
  287. package/modules/camera/FollowCamera.js +24 -15
  288. package/modules/camera/RtsCamera.js +12 -11
  289. package/modules/camera/common.js +72 -37
  290. package/modules/camera/contract.js +1 -0
  291. package/modules/camera/pixelSnap.js +62 -0
  292. package/modules/characters/Character.js +166 -70
  293. package/modules/characters/NPC.js +84 -44
  294. package/modules/characters/assetModel.js +16 -12
  295. package/modules/characters/astar.js +48 -27
  296. package/modules/characters/behaviors.js +4 -5
  297. package/modules/characters/character.contract.js +21 -0
  298. package/modules/characters/contract.js +17 -3
  299. package/modules/characters/index.js +240 -226
  300. package/modules/characters/moveHelpers.js +88 -12
  301. package/modules/characters/mover.contract.js +14 -0
  302. package/modules/characters/movers/common.js +22 -18
  303. package/modules/characters/movers/manual.js +1 -1
  304. package/modules/characters/movers/rapier.js +18 -10
  305. package/modules/characters/movers/simple.js +26 -13
  306. package/modules/characters/movers/support.js +24 -13
  307. package/modules/characters/npcAvoid.js +19 -16
  308. package/modules/characters/npcSim.js +88 -32
  309. package/modules/characters/npcView.js +19 -11
  310. package/modules/characters/pathAsync.js +81 -29
  311. package/modules/characters/pathJob.js +38 -21
  312. package/modules/characters/pathWorker.js +1 -1
  313. package/modules/characters/player.js +120 -0
  314. package/modules/characters/playerStrings.js +2 -2
  315. package/modules/characters/proceduralRig.js +2 -2
  316. package/modules/characters/seat.js +56 -0
  317. package/modules/characters/useModel.js +3 -3
  318. package/modules/characters/vehicle.contract.js +8 -5
  319. package/modules/characters/walkTo.js +40 -33
  320. package/modules/collision/Collision.js +69 -45
  321. package/modules/collision/contract.js +15 -0
  322. package/modules/collision/grid.js +6 -1
  323. package/modules/content/explain.js +2 -3
  324. package/modules/content/fields.js +24 -3
  325. package/modules/content/ids.js +5 -3
  326. package/modules/content/index.js +132 -114
  327. package/modules/content/loader.js +117 -140
  328. package/modules/content/markers.js +25 -0
  329. package/modules/content/models.js +54 -17
  330. package/modules/content/packs.js +5 -4
  331. package/modules/content/parts.js +2 -2
  332. package/modules/content/places.js +36 -0
  333. package/modules/content/props.js +22 -17
  334. package/modules/content/rules.js +47 -61
  335. package/modules/content/stages.js +7 -7
  336. package/modules/content/templates.js +80 -49
  337. package/modules/content/words.js +47 -0
  338. package/modules/debug/DebugPanel.js +14 -45
  339. package/modules/flow/contract.js +2 -1
  340. package/modules/flow/index.js +30 -16
  341. package/modules/gameplay/Container.js +17 -13
  342. package/modules/gameplay/Containers.js +23 -6
  343. package/modules/gameplay/Dialogue.js +93 -34
  344. package/modules/gameplay/Interactions.js +93 -51
  345. package/modules/gameplay/Inventory.js +64 -22
  346. package/modules/gameplay/Quests.js +146 -30
  347. package/modules/gameplay/boxOps.js +8 -1
  348. package/modules/gameplay/dialogueBubbles.js +16 -12
  349. package/modules/gameplay/inventoryOps.js +11 -8
  350. package/modules/gameplay/pickups.js +63 -37
  351. package/modules/gameplay/questLog.js +4 -2
  352. package/modules/gameplay/questSave.js +9 -4
  353. package/modules/gameplay/quests.contract.js +1 -1
  354. package/modules/grid/Grid.js +2 -2
  355. package/modules/grid/Layer.js +12 -8
  356. package/modules/grid/index.js +28 -23
  357. package/modules/grid/ops.js +43 -46
  358. package/modules/grid/preview.js +7 -7
  359. package/modules/grid/tiles.js +6 -6
  360. package/modules/hlod/index.js +42 -57
  361. package/modules/hud/index.js +22 -14
  362. package/modules/hud/parts.js +8 -8
  363. package/modules/level/contract.js +16 -0
  364. package/modules/level/heightfield.js +29 -31
  365. package/modules/level/index.js +113 -161
  366. package/modules/level/load.js +196 -0
  367. package/modules/level/meshes.js +65 -0
  368. package/modules/level/nodes.js +40 -23
  369. package/modules/lights/index.js +33 -183
  370. package/modules/lights/slots.js +93 -0
  371. package/modules/lights/sources.js +90 -0
  372. package/modules/music/Music.js +34 -28
  373. package/modules/music/rules.js +1 -1
  374. package/modules/nav/contract.js +16 -0
  375. package/modules/nav/index.js +180 -49
  376. package/modules/nav/navPath.js +45 -10
  377. package/modules/net/Client.js +7 -7
  378. package/modules/net/Host.js +7 -7
  379. package/modules/net/Net.js +1 -1
  380. package/modules/net/index.js +6 -5
  381. package/modules/net/sync.js +2 -2
  382. package/modules/net/transports.js +2 -2
  383. package/modules/particles/Particles.js +95 -29
  384. package/modules/particles/effect.js +86 -32
  385. package/modules/particles/shaders.js +19 -1
  386. package/modules/photo/Photo.js +23 -23
  387. package/modules/rigid/RigidBodies.js +255 -89
  388. package/modules/rigid/Vehicles.js +17 -8
  389. package/modules/rigid/collider3d.contract.js +26 -0
  390. package/modules/rigid/ragdoll.js +298 -0
  391. package/modules/rigid/ragdollBones.js +209 -0
  392. package/modules/rigid/refresh.js +10 -0
  393. package/modules/rigid/sync.js +51 -20
  394. package/modules/settings/Settings.js +177 -61
  395. package/modules/settings/apply.js +20 -13
  396. package/modules/settings/sections.js +19 -14
  397. package/modules/settings/strings.js +2 -2
  398. package/modules/settings/view.js +3 -3
  399. package/modules/sky/Sky.js +29 -22
  400. package/modules/sky/clouds.js +7 -7
  401. package/modules/sky/dome.js +33 -20
  402. package/modules/sky/domeLayers.js +9 -9
  403. package/modules/sky/environment.js +6 -6
  404. package/modules/sky/frame.js +19 -10
  405. package/modules/sky/season.js +7 -1
  406. package/modules/sky/shader.js +24 -25
  407. package/modules/sky/skyModule.js +17 -28
  408. package/modules/sky/tint.js +1 -1
  409. package/modules/swarm/Swarm.js +356 -0
  410. package/modules/swarm/draw.js +68 -0
  411. package/modules/swarm/grid.js +63 -0
  412. package/modules/terrain/ChunkManager.js +71 -59
  413. package/modules/terrain/chunkQueries.js +7 -24
  414. package/modules/terrain/chunkWorker.js +1 -1
  415. package/modules/terrain/draw.js +14 -11
  416. package/modules/terrain/index.js +42 -42
  417. package/modules/terrain/terrainColorMap.js +6 -3
  418. package/modules/terrain/terrainDefaults.js +2 -1
  419. package/modules/terrain/terrainEdit.js +45 -29
  420. package/modules/terrain/terrainGen.js +19 -12
  421. package/modules/terrain/terrainIsland.js +2 -2
  422. package/modules/terrain/terrainMesh.js +7 -6
  423. package/modules/terrain/terrainShape.js +8 -10
  424. package/modules/terrain/terrainShapeMain.js +3 -3
  425. package/modules/timeline/Timeline.js +83 -43
  426. package/modules/timeline/Tween.js +25 -19
  427. package/modules/timeline/shots.js +24 -17
  428. package/modules/triggers/index.js +95 -28
  429. package/modules/vegetation/Vegetation.js +34 -26
  430. package/modules/vegetation/densityMap.js +4 -7
  431. package/modules/vegetation/draw.js +39 -18
  432. package/modules/vegetation/groundChunks.js +21 -38
  433. package/modules/vegetation/index.js +37 -12
  434. package/modules/vegetation/modelGeometry.js +3 -6
  435. package/modules/vegetation/nearFade.js +1 -1
  436. package/modules/water/Water.js +20 -16
  437. package/modules/water/surface.js +3 -3
  438. package/modules/weather/Weather.js +52 -40
  439. package/modules/weather/particles.js +8 -8
  440. package/modules/weather/weatherDraw.js +28 -23
  441. package/modules/world/World.js +28 -15
  442. package/modules/world/explain.js +1 -1
  443. package/modules/world/index.js +30 -17
  444. package/modules/world/persist.js +90 -27
  445. package/modules/world/pos.js +5 -5
  446. package/modules/world/records.js +37 -11
  447. package/modules/world/sim.js +78 -27
  448. package/modules/world/simFar.js +2 -2
  449. package/modules/world/state.js +43 -11
  450. package/modules/world/thingSource.js +20 -5
  451. package/modules/world/views.js +27 -14
  452. package/package.json +48 -7
  453. package/presets.js +1 -3
  454. package/render/PostFX.js +83 -53
  455. package/render/backend.js +31 -33
  456. package/render/cascades.js +17 -12
  457. package/render/cascades.tsl.js +5 -8
  458. package/render/daylight.js +20 -3
  459. package/render/detail.js +8 -7
  460. package/render/effects.js +28 -25
  461. package/render/fuse.js +3 -3
  462. package/render/fx/cloudShadow.tsl.js +3 -3
  463. package/render/fx/detail.tsl.js +1 -1
  464. package/render/fx/index.js +5 -10
  465. package/render/fx/library.tsl.js +11 -0
  466. package/render/fx/lighting.tsl.js +2 -1
  467. package/render/fx/nodeErrors.tsl.js +2 -2
  468. package/render/fx/objectOrigin.tsl.js +1 -2
  469. package/render/fx/particles.tsl.js +8 -6
  470. package/render/fx/patchNodes.tsl.js +5 -15
  471. package/render/fx/postWebGPU.tsl.js +30 -26
  472. package/render/fx/sky.tsl.js +15 -17
  473. package/render/fx/uniforms.tsl.js +4 -4
  474. package/render/fx/wind.tsl.js +1 -1
  475. package/render/fxNumbers.js +3 -0
  476. package/render/layers.js +2 -2
  477. package/render/lighting.js +5 -3
  478. package/render/lightmap.js +41 -21
  479. package/render/lights.js +6 -6
  480. package/render/lit.js +24 -0
  481. package/render/materials.js +8 -7
  482. package/render/mergeCommon.js +22 -0
  483. package/render/modeling.js +2 -2
  484. package/render/occlusion.js +62 -15
  485. package/render/ownFrame.js +4 -4
  486. package/render/patches.js +15 -15
  487. package/render/postWebGL.js +15 -12
  488. package/render/probes.js +41 -19
  489. package/render/recordSweep.js +117 -0
  490. package/render/shaderErrors.js +10 -9
  491. package/render/shadowCache.tsl.js +107 -0
  492. package/render/shadowTypes.js +9 -0
  493. package/{core → render}/shadows.js +59 -13
  494. package/render/slots.js +7 -7
  495. package/render/terms.js +22 -24
  496. package/render/uniformDecl.js +1 -1
  497. package/types/core.d.ts +336 -202
  498. package/types/gameplay.d.ts +254 -130
  499. package/types/generated/core/{Audio.d.ts → audio/Audio.d.ts} +22 -7
  500. package/types/generated/core/{audioVoice.d.ts → audio/audioVoice.d.ts} +2 -2
  501. package/types/generated/core/{Events.d.ts → base/Events.d.ts} +4 -4
  502. package/types/generated/core/{I18n.d.ts → base/I18n.d.ts} +8 -16
  503. package/types/generated/core/{Random.d.ts → base/Random.d.ts} +4 -3
  504. package/types/generated/core/{page.d.ts → engine/page.d.ts} +8 -9
  505. package/types/generated/core/{Input.d.ts → input/Input.d.ts} +28 -10
  506. package/types/generated/core/input/inputSeat.d.ts +26 -0
  507. package/types/generated/core/{Budget.d.ts → inspect/Budget.d.ts} +36 -26
  508. package/types/generated/core/{DebugOverrides.d.ts → inspect/DebugOverrides.d.ts} +17 -3
  509. package/types/generated/core/{Ops.d.ts → ops/Ops.d.ts} +6 -4
  510. package/types/generated/core/{control.d.ts → ops/control.d.ts} +14 -10
  511. package/types/generated/core/{Saves.d.ts → saves/Saves.d.ts} +62 -18
  512. package/types/generated/core/{session.d.ts → saves/session.d.ts} +3 -2
  513. package/types/generated/core/{Rays.d.ts → scene/Rays.d.ts} +8 -27
  514. package/types/generated/core/{Views.d.ts → scene/Views.d.ts} +2 -2
  515. package/types/generated/core/{Batching.d.ts → stream/Batching.d.ts} +7 -7
  516. package/types/generated/core/{Stream.d.ts → stream/Stream.d.ts} +22 -18
  517. package/types/generated/core/{Commits.d.ts → threads/Commits.d.ts} +1 -1
  518. package/types/generated/core/{Jobs.d.ts → threads/Jobs.d.ts} +6 -6
  519. package/types/generated/core/{Threads.d.ts → threads/Threads.d.ts} +4 -4
  520. package/types/generated/modules/calendar/Calendar.d.ts +10 -11
  521. package/types/generated/modules/debug/DebugPanel.d.ts +1 -9
  522. package/types/generated/modules/grid/Grid.d.ts +1 -0
  523. package/types/generated/modules/grid/Layer.d.ts +1 -1
  524. package/types/generated/modules/grid/index.d.ts +3 -3
  525. package/types/generated/modules/music/Music.d.ts +7 -5
  526. package/types/generated/modules/particles/Particles.d.ts +5 -4
  527. package/types/generated/modules/sky/Sky.d.ts +21 -10
  528. package/types/generated/modules/swarm/Swarm.d.ts +80 -0
  529. package/types/generated/modules/timeline/Timeline.d.ts +7 -5
  530. package/types/generated/modules/water/Water.d.ts +1 -0
  531. package/types/generated/modules/weather/Weather.d.ts +14 -16
  532. package/types/generated/modules/weather/weatherDraw.d.ts +3 -3
  533. package/types/generated/modules/world/World.d.ts +11 -7
  534. package/types/generated/render/PostFX.d.ts +21 -23
  535. package/types/generated/render/materials.d.ts +1 -0
  536. package/types/generated/render/occlusion.d.ts +9 -0
  537. package/types/generated/render/patches.d.ts +1 -0
  538. package/types/generated/ui/Focus.d.ts +1 -0
  539. package/types/generated/ui/UI.d.ts +1 -0
  540. package/types/nav.d.ts +47 -15
  541. package/types/physics.d.ts +150 -73
  542. package/types/pixel.d.ts +75 -0
  543. package/types/tsl.d.ts +37 -4
  544. package/types/world.d.ts +48 -75
  545. package/ui/Focus.js +10 -9
  546. package/ui/Parts.js +13 -5
  547. package/ui/UI.js +7 -7
  548. package/ui/defaults.js +3 -2
  549. package/ui/theme.js +7 -5
  550. package/core/assetEntry.js +0 -109
  551. package/core/engineCamera.js +0 -32
  552. package/core/ground.js +0 -104
  553. package/core/holds.js +0 -134
  554. package/core/math.js +0 -48
  555. package/core/moduleSlots.js +0 -100
  556. package/core/modules.js +0 -314
  557. package/core/saveApply.js +0 -210
  558. package/core/saveValues.js +0 -46
  559. package/core/session.js +0 -174
  560. package/core/shadowTypes.js +0 -16
  561. package/core/util.js +0 -17
  562. package/core/view.js +0 -43
  563. package/docs/MIGRATING-0.3.md +0 -248
  564. package/docs/MIGRATING-0.4.md +0 -320
  565. package/docs/MIGRATING-0.5.md +0 -68
  566. package/docs/MIGRATING-0.6.md +0 -126
  567. package/docs/PERF.md +0 -245
  568. package/docs/recipes/36-sky-ground-plants.md +0 -158
  569. package/docs/recipes/37-terrain-hooks.md +0 -115
  570. package/docs/recipes/38-environment-hooks.md +0 -67
  571. package/docs/recipes/42-terrain-shape.md +0 -64
  572. package/docs/recipes/47-island-snow-backdrop.md +0 -43
  573. package/docs/recipes/54-three-idioms.md +0 -88
  574. package/examples/plain-picture/FINDINGS.md +0 -53
  575. package/examples/sheepisland/.threedog/content-index.json +0 -1
  576. package/modules/camera/projection.js +0 -21
  577. /package/core/{mulberry32.js → base/mulberry32.js} +0 -0
  578. /package/core/{inputDefaults.js → input/inputDefaults.js} +0 -0
  579. /package/core/{textureBytes.js → inspect/textureBytes.js} +0 -0
  580. /package/core/{actor.js → ops/actor.js} +0 -0
  581. /package/core/{opsHistory.js → ops/opsHistory.js} +0 -0
  582. /package/core/{saveIds.js → saves/saveIds.js} +0 -0
  583. /package/core/{screenToGround.js → scene/screenToGround.js} +0 -0
  584. /package/core/{cells.js → stream/cells.js} +0 -0
  585. /package/core/{streamCells.js → stream/streamCells.js} +0 -0
  586. /package/core/{pureWorker.js → threads/pureWorker.js} +0 -0
  587. /package/examples/{sheepisland → perf-island}/content/index.js +0 -0
  588. /package/examples/{sheepisland → perf-island}/content/props.js +0 -0
  589. /package/examples/{sheepisland → perf-island}/content/templates.js +0 -0
  590. /package/examples/{sheepisland → perf-island}/content/vegetation.js +0 -0
  591. /package/examples/{sheepisland → perf-island}/picture/lights.js +0 -0
  592. /package/examples/{sheepisland → perf-island}/picture/materials.js +0 -0
  593. /package/examples/{sheepisland → perf-island}/picture/sky.js +0 -0
@@ -6,7 +6,7 @@
6
6
 
7
7
  **Props** are a small number of hand-placed objects (a tree next to a cabin, rocks, street lamps). Write them as data; each entry becomes an ordinary
8
8
  `kind: 'prop'` record in `engine.world` (needs `world()`, which `openWorld()` already includes). The model is created only when the player gets close
9
- (within terrain view distance), and **the collision body and ray registration are built with the model and removed when the player leaves** (only
9
+ (within `world.radius`, or the stream's active radius when that is larger), and **the collision body and ray registration are built with the model and removed when the player leaves** (only
10
10
  things near the player need to block the way).
11
11
  Large repeated areas (forests, grass) don't use this; use `content/vegetation.js` (instanced vegetation), or section 2e for plants on your own geometry.
12
12
 
@@ -47,7 +47,7 @@ during development and say how to fix it).
47
47
  Inserting a new entry in the middle shifts the later indexes, so moves / deletions in old saves no longer match. **Give an `id` to any prop whose
48
48
  content may still change.**
49
49
  Get them in code, move or delete them (all saved with the game):
50
- ```js
50
+ ```js fragment
51
51
  engine.world.query({ kind: 'prop' }); // all prop data { id, position, model, rot, scale, collide ... }
52
52
  engine.world.move('prop:rock:3', { x: 12, z: -4 }); // move: model, collision and ray registration follow; height is recomputed from the ground
53
53
  engine.world.set('prop:rock:3', { rot: 1.2, scale: 1.5 }); // change rotation / size
@@ -70,11 +70,11 @@ If a model fails to generate, world reports it once in the console, does not blo
70
70
  ## 2. Large code-generated models and baking
71
71
  Big things assembled in code, such as a city block or a whole house, are written as a function, registered in the manifest and fetched by name. During
72
72
  development they are cached automatically (.threedog/cache) and recomputed when the code changes:
73
- ```js
73
+ ```js fragment
74
74
  import { buildBlock } from './block.js';
75
75
  engine.assets.manifest({ models: { 'city-block': buildBlock } }); // the function returns an Object3D or a geometry
76
76
  const block = await engine.assets.model('city-block');
77
- engine.use(level({ url: 'city-block' })); // a level reads it by name (the city example does this): baked file and cache both apply, and loading a save can switch back to this map
77
+ engine.use(level({ url: 'city-block' })); // a level reads it by name: baked file and cache both apply, and loading a save can switch back to this map
78
78
  ```
79
79
  To package a release or edit it in Blender, create `bake.js` in the game folder (`npm run bake -- -w <game>` reads the `bake` export of `bake.js`
80
80
  in that game's folder). A game's picture lives in its own `picture/` folder; a model built there is baked the same way, by importing its
@@ -99,13 +99,14 @@ it by name, and use the name everywhere. Later a `.glb` registered under the sam
99
99
  (a Mesh or a Group, with any number of meshes and materials, used as it is). It may be `async`.
100
100
  - Arguments: `model: ['name', ...args]` in content passes them as written (each argument list is its own cached model). Or declare a schema,
101
101
  `{ build, params: { height: { type: 'number', min: 1, max: 8, default: 3 }, leaf: { type: 'color', default: 0x4a7a3a } } }` (the
102
- `core/params.js` format, plus `'color'`): the generator then gets one object, defaults < dev panel values < a call's own `['pine', { height: 5 }]`,
102
+ `core/base/params.js` format, plus `'color'`): the generator then gets one object, defaults < dev panel values < a call's own `['pine', { height: 5 }]`,
103
103
  and a typo or wrong type throws naming the field.
104
104
  - Written as `function` (not an arrow), `this` is `{ palette, engine }`: `this.palette` = `engine.assets.palette`, `this.engine` = the engine.
105
105
  - Shadows: `{ build, castShadow: false }` in the manifest turns them off for every mesh. Without it, a generator that set `castShadow` or
106
106
  `receiveShadow` on any of its meshes keeps its own flags (a rug that receives but does not cast); one that set none casts and receives
107
107
  everywhere. The same rule holds for `assets.model(name)` and content props.
108
108
  - It runs once per name + params; every placement is a clone sharing geometry and materials (`engine.assets.model(name)` and content props alike).
109
+ - Who frees what: a copy from `assets.model` holds its original until `engine.remove`. `release` and `trim` skip what a copy still holds, and `describe().assets` counts `leases` and `waiting`. A generated model stays cached for good, and a content prop's prototype keeps one copy.
109
110
  - Cache key = name + the generator's source (its file and imports) + params + `engine.assets.palette`. Values it reads from outer variables must go in
110
111
  `params`, or a change keeps the stale model. In dev a build slower than `assets.cacheMinMs` (20 ms) is stored as GLB in `.threedog/cache` and
111
112
  read back next time; `npm run bake` writes the same GLB to `public/models/baked/` (section 2). Neither is needed: unbaked generators run in the
@@ -118,27 +119,17 @@ it by name, and use the name everywhere. Later a `.glb` registered under the sam
118
119
 
119
120
  ```js
120
121
  import * as THREE from 'three';
121
- import { RoundedBoxGeometry } from 'three/addons/geometries/RoundedBoxGeometry.js';
122
-
123
- function lampPost() {
124
- const pole = new THREE.MeshStandardMaterial({ color: this.palette.metal ?? 0x3a3d42, roughness: 0.5, metalness: 0.8 });
125
- const glass = new THREE.MeshStandardMaterial({ color: 0xfff2c0, emissive: 0xffd27a, emissiveIntensity: 1.5 });
122
+ function lampPost() { // a function, not an arrow, so this.palette is there
126
123
  const root = new THREE.Group();
127
- const base = new THREE.Mesh(new RoundedBoxGeometry(0.5, 0.3, 0.5, 2, 0.05), pole); base.position.y = 0.15;
128
- const post = new THREE.Mesh(new THREE.CylinderGeometry(0.05, 0.07, 3, 12), pole); post.position.y = 1.8;
129
- const head = new THREE.Mesh(new THREE.LatheGeometry([[0, 0], [0.2, 0.05], [0.14, 0.4], [0, 0.45]].map(([r, y]) => new THREE.Vector2(r, y)), 16), glass);
130
- head.position.y = 3.3;
131
- for (const m of [base, post, head]) { m.castShadow = m.receiveShadow = true; root.add(m); }
124
+ root.add(new THREE.Mesh(new THREE.CylinderGeometry(0.05, 0.07, 3, 12), new THREE.MeshStandardMaterial({ color: this.palette.metal ?? 0x3a3d42 })));
132
125
  return root;
133
126
  }
134
127
  engine.assets.manifest({ name: 'props', models: { lampPost } });
135
128
  // content/props.js: { model: 'lampPost', x: 4, z: 2, collide: 'circle' } code: engine.add(await engine.assets.model('lampPost'), { id: 'lamp-1' })
136
129
  ```
137
130
 
138
- **Where the colors come from**
139
- - **The model's own three.js materials** (`new THREE.MeshStandardMaterial({ map: canvasTexture })`, a `ShaderMaterial`), any type a game's picture calls for.
140
- - **Colors shared between models** live in the palette: read `this.palette.metal` in the generator, as the lamp post does.
141
- - Vertex colors for a merged model: `mergeColored([[geometry, this.palette.wood], ...])` returns one geometry.
131
+ **Where the colors come from.** The model's own three.js materials, of any type the game's picture calls for; colors shared between models from the palette (`this.palette.metal`
132
+ above); vertex colors for a merged model from `mergeColored([[geometry, this.palette.wood], ...])`, which returns one geometry.
142
133
 
143
134
  **The palette.** `engine.assets.palette` is a plain object of named colors: `engine.assets.palette = { wood: 0x8a5a36, leaf: 0xd98a3a }`, or write one key.
144
135
  Generators and code-made textures read it as `this.palette`. Set it before the models load; after a write, whatever is asked for next is built from the
@@ -149,7 +140,7 @@ Very detailed models (faces, sculpted shapes, hand-painted textures) are faster
149
140
 
150
141
  ## 2b. Many copies of one model: automatic batching
151
142
  Nothing to write for what the engine places: `engine.batching` (core) covers world record views (props, templates, grid items, `world.present`),
152
- `stream` builds and level files. When the same geometry + material (+ shadow flags) appears at least 8 times in one 64 m cell, those meshes are
143
+ `stream` builds and level files. When the same geometry + material (+ shadow flags) appears at least 8 times in one cell (256 m by default), those meshes are
153
144
  drawn by one real `THREE.InstancedMesh` per cell; fewer stay plain meshes. Each placed object stays in the scene with its own userData, record,
154
145
  collision and interactions; only its meshes are moved to layer 31 (not drawn), so `engine.raycast` / `pick` / photo return the original object,
155
146
  not an instance index.
@@ -158,7 +149,7 @@ Objects your code makes and adds (`engine.scene.add(mesh)`, `engine.add(mesh)`,
158
149
  `THREE.Raycaster`, scene walks and material swaps see exactly the meshes you made. Many static copies of your own mesh (fence posts, tiles, coins)
159
150
  opt in with one flag on the root you add, set before adding it (or call `engine.batching.refresh(obj)` after). In dev, `engine.inspect.perf()` and
160
151
  `describe().perf.batching.hint` say so when many identical meshes of yours draw one by one.
161
- ```js
152
+ ```js fragment
162
153
  for (const p of postSpots) { const m = new THREE.Mesh(postGeo, woodMat); m.position.copy(p); m.userData.batch = true; engine.scene.add(m); }
163
154
  ```
164
155
  ```js
@@ -167,9 +158,8 @@ if (crate) {
167
158
  engine.batching.tint(crate, 0xff8080); // recolor one copy (instance color; null restores)
168
159
  engine.batching.of(crate); // [{ mesh: InstancedMesh, index }], [] when drawn on its own
169
160
  }
170
- engine.batching.batches; // [{ mesh, cell, count, items }] for inspection
171
- engine.batching.stats; // { batches, instances, saved, note?, hint? } (also describe().perf.batching)
172
- engine.batching.enabled = false; // global switch; createEngine({ batching: false }) never starts it, { minCount, cell } tunes it
161
+ engine.batching.stats; // { batches, instances, saved, note?, hint? } (also describe().perf.batching); engine.batching.batches lists them
162
+ engine.batching.enabled = false; // global switch; createEngine({ batching: false }) never starts it, { minCount, cell } tunes it (wider cells draw fewer objects, narrower cull finer)
173
163
  ```
174
164
  - Move / hide / remove a copy as usual (`world.move`, `obj.visible = false`, `engine.remove`): its instance follows next frame; unloading a cell frees
175
165
  its batch.
@@ -179,11 +169,17 @@ engine.batching.enabled = false; // global switch; createEngine({
179
169
  - Never batched: skinned, morphing or animated models, multi-material or transparent meshes, `ShaderMaterial`, meshes with children, and level
180
170
  geometry `hlod` registered (hlod owns far, batching owns near).
181
171
 
172
+ ### Render bundles: three's BundleGroup, for static meshes that cannot batch
173
+ A WebGPU option with no engine API: `BundleGroup` (`three/webgpu`) is plain three.js, and the engine stays out of its way. Batch first: batching removes objects, a bundle only
174
+ removes the command recording of objects that stay, and three still refreshes each of them every pass. It may gain nothing in your scene, so compare before you keep it.
175
+ - **It replays what it recorded.** A child's `visible`, an added or removed child and `castShadow` show only after `bundle.needsUpdate = true`, and recording costs a frame hitch on a big bundle, so several small bundles beat one huge one if parts change. `bundle.visible` works at once.
176
+ - **Nothing inside is culled**, in the shadow pass too: size groups so `visible` can drop a whole one.
177
+ - **One owner per mesh.** A mesh under a `BundleGroup` is the bundle's: `engine.batching` leaves it alone (`userData.batch = true` on the group warns once) and `hlod.add` skips it with a warning, since neither could hide it. Occlusion culling does not reach it either. `engine.stream` works as usual, a build may return a `BundleGroup`.
178
+ - On a WebGL backend it is a plain group: correct, no gain. `describe().render.bundles` gives `{ groups, meshes, replayed }`; `engine.inspect.scene()` adds the reason `in-bundle`.
179
+
182
180
  ## 2c. Art iteration loop: edit -> hot swap -> gallery -> compare
183
- Works for any model made in code (a hut, a weapon, a coral, a character body), in any art style; the tools only build and show, they add no picture.
184
- For the models that matter (characters, main buildings, props repeated across the level), think through the parts and their proportions before
185
- writing code, and afterwards look at the model on its own, not only inside the level: `threedog gallery --shots` draws each one from a single
186
- three-quarter view under three lights. When something seems off, turn it on the live turntable (`threedog gallery`) to see it from another side.
181
+ Works for any model made in code, in any art style; the tools only build and show, they add no picture. For the models that matter (characters, main buildings,
182
+ props repeated across the level), think through the parts and their proportions first, and look at the model on its own afterwards, not only inside the level.
187
183
  - **Edit, see it in place**: keep generators in modules imported by the game's `assets.js` (for example an `art/` folder). Saving one (dev server) rebuilds
188
184
  its models and swaps every live copy in place: content props, template parts, pickups, vegetation instances, `assets.model` copies. Camera,
189
185
  player, time and world state stay; `describe().assetSwaps` and a toast say what changed. A collision box keeps its placed size until the next
@@ -191,15 +187,9 @@ three-quarter view under three lights. When something seems off, turn it on the
191
187
  - **Tune numbers live**: declare `params` (section 2a); the dev panel's models folder (`?panel=1`) shows them and every drag rebuilds the
192
188
  copies (`engine.assets.setParams(name, values)`). "write back", then `threedog tune write` (dry run; `--apply`) puts the values into the
193
189
  schema's `default` where the model is registered.
194
- - **Review all at once**: `?gallery=1` on the dev page, or `threedog gallery`, puts every registered model and texture on a turntable under
195
- three neutral light setups (midday, low sun, overcast). `threedog gallery --shots` writes `.threedog/gallery/<name>-<light>.png` and an
196
- `index.html` of all of them, so one picture covers the whole set.
197
- - **Outline and light/dark on their own**: `--shots --mode silhouette,value` adds `<name>-silhouette.png` (the model pure black on white) and
198
- `<name>-value.png` (the midday shot in grayscale) per asset, with facts printed and stored in `index.json`: `fill` (share of the frame),
199
- `boxFill` (share of its own bounding box), `aspect`, and luminance `p5` / `p50` / `p95` inside the outline. They are measurements, not
200
- grades. Principle for reading them: a shape the player must recognize at play distance usually still reads as a silhouette, and a
201
- narrow p5-p95 spread means hue carries the form; whether that is right depends on the game's picture and camera, so compare assets that must
202
- be told apart with each other rather than with a fixed number.
190
+ - **Review all at once**: `?gallery=1` on the dev page, or `threedog gallery`, puts every registered model and texture on a turntable;
191
+ `--shots` writes one page of pictures, `--mode silhouette,value` adds outline and grayscale shots with measurements (`../COMMANDS.md`). They are measurements, not grades: a shape the player must recognize at play distance usually still reads as a silhouette, and a
192
+ narrow p5-p95 spread means hue carries the form; compare assets that must be told apart with each other rather than with a fixed number.
203
193
  - **Compare with the reference**: `threedog picture compare <reference.png> .threedog/gallery/<name>-midday.png --out diff.png` gives numbers
204
194
  for one asset against its reference crop, the same way as for a whole screenshot (`recipes/35-picture-from-reference.md`).
205
195
 
@@ -211,13 +201,13 @@ the DESIGN.md "Asset sources" row, and every source ends up the same way, as a n
211
201
  |---|---|---|
212
202
  | Code (sections 2 and 2a: three.js geometry, `mergeColored`, three.js materials) | blockout, props, variations, anything tuned by `params` | a generator function in the manifest |
213
203
  | Blender -> glTF | sculpted or painted finish, rigs and clips | a `.glb` path; export settings, scale (1 unit = 1 m, Y-up, applied transforms), naming and which materials survive are in `recipes/46-blender-art-route.md` |
214
- | Free libraries (for example Kenney and Quaternius models, Poly Haven textures and HDRIs) | a lot of consistent content fast | the files in `public/` or an asset pack (section 3b), then `threedog assets` |
204
+ | Free libraries (for example Kenney and Quaternius models, Poly Haven textures and HDRIs) | a lot of consistent content fast | the files in `public/` or an asset pack (section 3b), then `threedog assets optimize` |
215
205
  | Your own earlier games | an effect, material, model or texture you already made and liked | `threedog lib list` / `lib pull` (below), or `threedog art copy ../earlier-game name` |
216
206
  | AI-generated 3D / textures | one-off props, texture variations | export glTF / PNG, then the same checks as any file: `threedog assets check`, scale, origin, triangle count, UVs |
217
207
 
218
- **Does it fit?** Every entry has one card, measured at `lib add`: what it needs, what it provides, which shared three.js values it writes, its size (1 unit = 1 meter, up axis, origin, texture color space), its style and a short usage; `threedog lib list <word> --card` prints it. Tag a style with `--style` in your own words (a pixel-art dungeon and a watercolor village both work): only tags can say that, and two entries with no tag in common are reported. After pulling several pieces, `threedog lib check` says what is missing and what clashes, and `threedog lib status` says which copies this game changed. Nothing is forced: fix a clash in your copy, or leave a note you meant.
208
+ **Does it fit?** Every library entry has one card, measured at `lib add` (needs, provides, shared three.js values it writes, size, style, usage); `threedog lib list <word> --card` prints it. Tag a style with `--style` in your own words: only tags can say that, and two entries with no tag in common are reported. After pulling several pieces, `threedog lib check` says what is missing and what clashes. Nothing is forced: fix a clash in your copy, or leave a note you meant.
219
209
 
220
- **Your own library.** `threedog lib add <file|folder|exportName> -w earlier-game` keeps a piece of a finished game in `~/.threedog/library` (outside the engine; `THREEDOG_LIBRARY` or `--lib` moves it) with a summary, the use line and the backends it works on; `threedog lib list [words]` searches it, `threedog lib pull <name>` copies it into this game and prints the use line (a code entry: its files go to `plugins/<name>/` and pull writes `plugins/<name>.js`, the one wiring line that calls its factory, from the entry's plug line: `lib add --plug "makeWater({ size: 4 })"` sets it, otherwise it calls the exported function; change the arguments in that file), `threedog lib page` writes a page with all previews. Look here before writing an effect from scratch. A pulled entry is a copy with no link back and no update: change it to fit this game rather than keeping it as it was, or every game ends up looking alike.
210
+ **Your own library.** `threedog lib add <file|folder|exportName> -w earlier-game` keeps a piece of a finished game in `~/.threedog/library`, `threedog lib list [words]` searches it, `threedog lib pull <name>` copies it into this game; flags and where each kind lands in `../COMMANDS.md`. Look here before writing an effect from scratch. A pulled entry is a copy with no link back and no update: change it to fit this game rather than keeping it as it was, or every game ends up looking alike.
221
211
 
222
212
  **Rules (correctness and licensing):**
223
213
  - Read the license of every asset you did not make, on the page you downloaded it from, before it goes into the game; a library can mix
@@ -256,7 +246,7 @@ Every asset load is a task in `engine.loading` (so are module init / `isReady`,
256
246
  phase (`queued` → `download` → `decode` → `upload` / `build` → `done` | `failed`), progress, the error (file, HTTP status, a texture or `.bin` the
257
247
  model references but could not load) and its source (which manifest, which path, file version, animation names).
258
248
  Decide per entry what a failure means:
259
- ```js
249
+ ```js fragment
260
250
  engine.assets.manifest({
261
251
  name: 'forest', // the source label in engine.loading (default 'manifest#1')
262
252
  models: {
@@ -299,13 +289,13 @@ engine.assets.manifest({ name: 'ui-fonts', base: '/fonts/', fonts: { pixel: 'pix
299
289
 
300
290
  ## 4. Verify
301
291
  - `npm run check`: prop model names and place names are validated. After `npm run map`, GAMEMAP.md has a props table.
302
- - Loading: `engine.loading.list({ phase: 'failed' })` should be empty; related test `npm test -- 加载可观察`.
292
+ - Loading: `engine.loading.list({ phase: 'failed' })` should be empty; related test `threedog test 加载可观察`.
303
293
  - `describe().content.props` is the number of prop entries; when the player is near, named objects appear in `nearby`
304
294
  (`npm run shot -- / --pos x,z --describe-only`).
305
295
  - Collision: `engine.collision.walkable({ x, z })` should be false at a prop's position.
306
- - Baking: `npm run bake` prints each item's size; related test `npm test -- 烘焙`. To look at the picture: `npm run shot -- / --pos x,z`.
296
+ - Baking: `npm run bake` prints each item's size; related test `threedog test 烘焙`. To look at the picture: `npm run shot -- / --pos x,z`.
307
297
 
308
298
  ## 5. Deleting objects
309
- `engine.remove(obj)` deletes an object and frees its GPU memory; `engine.detach(obj)` only takes it off for a while (add it back with `engine.add`).
299
+ `engine.remove(obj)` deletes an object and frees its GPU memory; `obj.removeFromParent()` only takes it off for a while (add it back with `engine.add`).
310
300
  Don't call `obj.removeFromParent()` or `scene.remove()` on meshes you built: their geometry and materials would leak.
311
301
  (`thing.remove` (`40-scene.md`) deletes a registered object so that an undo can bring it back; `engine.remove` is final.)
@@ -1,6 +1,6 @@
1
1
  # Scheduling events on the game clock
2
2
 
3
- **In this recipe**: Changing how fast time runs · The time table · 1. Where to write it · 2. Skipping time · 3. Verify
3
+ **In this recipe**: Changing how fast time runs · The time table · 1. Where to write it · 1b. Smooth movement between fixed steps · 2. Skipping time · 3. Verify
4
4
 
5
5
  ## Changing how fast time runs: `engine.mod`
6
6
  ```js
@@ -29,10 +29,10 @@ Details, only when you need them:
29
29
  - Order inside a fixed step: `onFixed(fn)` runs before the modules (player not moved yet), `onFixed(fn, { phase: 'late' })` after them. Stacks, `input.gate` and `engine.wrap` together: recipe 55.
30
30
 
31
31
  ## The time table (the single source; other docs link here)
32
- **One time source.** `engine.time` counts one thing, `engine.time.tick` (fixed steps run; `engine.tick` is the same number). Every other time is a
32
+ **One time source.** `engine.time` counts one thing, `engine.time.tick` (fixed steps run). Every other time is a
33
33
  read-only view of it, moved only by the engine, and always together: a fixed step, `engine.skip` and a new playthrough move or reset all of them.
34
34
  Read any view with `engine.time.now(name)`: `'real'`, `'ambient'`, `'calendar'` or a channel (`'world'`, `'player'`, your own).
35
- `'ambient'` (= `engine.uniforms.uTime`: wind, water, clouds) is the one view that keeps moving while gameplay is frozen.
35
+ `'ambient'` (= `engine.uniforms.uTime`: wind, water, clouds) is the one view that keeps moving while gameplay is frozen, unless the freeze is a full still (`{ ambient: true }`, which also stops skeletal animation and particles; `engine.still` says so, for your own frame code).
36
36
 
37
37
  Three rulers, always named: **real seconds** (`engine.time.now('real')` = tick / 60; the `dt` of a plain `onFixed` / module `fixed` / `world.simulate`, the N of
38
38
  `engine.step(N)`; never scaled), **channel seconds** (`engine.time.now(ch)`, the `dt` of
@@ -42,10 +42,11 @@ from calendar seconds: one day = `calendar.dayLength` calendar seconds. **Frame
42
42
 
43
43
  | Use it for | Time to use | Paused / frozen | `clock.rate` 2 (one real second at 60 Hz) |
44
44
  |---|---|---|---|
45
- | Movement, camera follow, physics (Rapier), AI steering | real seconds, or channel seconds for things bullet time should slow (`onFixed(fn, { channel })`) | stops | unchanged: speed in m/s stays the same |
45
+ | Movement, camera follow, AI steering | real seconds, or channel seconds for things bullet time should slow (`onFixed(fn, { channel })`) | stops | unchanged: speed in m/s stays the same |
46
+ | Physics (Rapier) | the `world` channel, so `engine.mod('time.world', ...)` slows bodies and speed 0 holds them; a mod on another channel leaves them alone | stops | unchanged |
46
47
  | Action judgement and action timelines (hit windows, invulnerability, "finish the swing"), cooldowns, hit-stop | a `mod` with `for` (hit-stop: `engine.mod('time.world', { owner: 'hitstop', set: 0, layer: 'system', for: 0.06 })`), or accumulate `dt` in `onFixed` | stops | unchanged: a 0.6 s swing is still 0.6 s |
47
48
  | `world.simulate` near / far, dialogue typing, cutscenes, `engine.step(N)` | real seconds | stops | unchanged |
48
- | Poison ticks, status effects, projectiles that bullet time should slow | channel seconds (`clock.after(s, 'ev', data, { channel })`, `for` + `clock: '<channel>'`) | stops | unchanged |
49
+ | Poison ticks, status effects, projectiles that bullet time should slow | channel seconds (`clock.after(s, 'ev', { data, channel })`, `for` + `clock: '<channel>'`) | stops | unchanged |
49
50
  | Crop / template stage growth, vegetation and pickup respawn, "ripe after 10 minutes" | calendar seconds (`clock.now`, `clock.after / every`; saved) | stops | twice as fast: growth that needs 600 calendar seconds is ripe after 300 real seconds |
50
51
  | Calendar, day, season, clock hours, lamps and shop doors (`calendar.at / between / daily / onSeason`) | time of day (`engine.calendar`, derived from calendar seconds) | stops | twice as fast: with `dayLength = 360` one hour (15 calendar seconds) passes in 7.5 real seconds |
51
52
  | UI animation and effects that follow the game (bobbing, sway) | `engine.time.now('real')` | stops | unchanged |
@@ -83,18 +84,19 @@ call `after` in code.
83
84
 
84
85
  ```js
85
86
  import { parseClock, formatClock } from 'threedog';
87
+ const lamp = new THREE.PointLight();
86
88
 
87
89
  // Time-window switch: lamps on from 18:00 to 06:00 (crosses midnight). On registration, at start, after loading a save, applyState, or turning the time back, it aligns to the current time immediately (returns a handle; lampHours.remove() cancels)
88
90
  const lampHours = engine.calendar.between('18:00', '06:00', { on: () => lamp.visible = true, off: () => lamp.visible = false });
89
91
 
90
92
  // An event when a clock time is crossed (an "action" once per day): open the market at 12:00
91
- engine.calendar.at('12:00', day => market.open(), { days: [1, 3, 5] }); // only on days 1, 3, 5; a function also works: day => day % 7 === 6
93
+ engine.calendar.at('12:00', day => engine.vars.bump('marketDays'), { days: [1, 3, 5] }); // only on days 1, 3, 5; a function also works: day => day % 7 === 6
92
94
 
93
95
  // After how long: pass an event name to make it saveable (still fires after loading a save); a function cannot be saved
94
- engine.clock.after(120, 'bread:ready', { oven: 1 });
95
- engine.events.on('bread:ready', ({ oven }) => engine.inventory?.add('bread', 1));
96
+ engine.clock.after(120, 'bread:ready', { data: { oven: 1 } });
97
+ engine.events.on('bread:ready', ({ oven }) => engine.vars.bump('bread'));
96
98
 
97
- engine.clock.every(30, () => spawnBird()); // every 30 calendar seconds (not 30 clock seconds)
99
+ engine.clock.every(30, () => engine.vars.bump('birds')); // every 30 calendar seconds (not 30 clock seconds)
98
100
  engine.calendar.daily(day => console.log('day', day)); // every day at 00:00
99
101
  engine.calendar.onSeason('winter', () => engine.weather?.set('snow', { seconds: 20 })); // needs seasons (presets.calendar.fourSeasons) and a 'snow' weather (presets.weather.temperate)
100
102
 
@@ -117,6 +119,15 @@ Length of a day: `openWorld({ camera: 'follow', dayLength: 600 })` / `calendar({
117
119
  `presets.calendar.cycle` is 360); `engine.mod('clock.rate', { owner: 'game', set: 10 })` speeds things up temporarily (`remove()` on its handle undoes it; see the table above).
118
120
  For "which time" or "has this been done" in a story, use `engine.vars.bump / setFlag`; don't keep your own variables (vars are saved automatically).
119
121
 
122
+ ## 1b. Smooth movement between fixed steps: `engine.stepBlend`
123
+ The game runs in fixed steps and the screen draws at its own rate, so most frames fall between two steps. Something you move in `onFixed` and draw at its latest position jumps from step to step and stutters, the more so on a fast screen. Keep where it was before the step and where it is now, and draw between them. `engine.stepBlend` says how far this frame is from the last step to the next, from 0 to 1:
124
+ ```js fragment
125
+ const body = { x: 0, lastX: 0 };
126
+ engine.onFixed(dt => { body.lastX = body.x; body.x += speed * dt; }); // the rules read body.x
127
+ engine.onFrame(() => { mesh.position.x = body.lastX + (body.x - body.lastX) * engine.stepBlend; }); // the picture only
128
+ ```
129
+ The picture runs at most one step behind the rules, too little to see. Rules read the fixed-step value, never the drawn one. After a teleport set `lastX` to `x` too, or the object slides across. While the game is frozen `stepBlend` holds still, so nothing jitters. `engine.swarm` does this by itself (recipe 65).
130
+
120
131
  ## 2. Skipping time (sleep until morning, wait an hour)
121
132
  `engine.skip` moves calendar seconds and the calendar clock forward without running every fixed step, so even a game with a real-length day can sleep through
122
133
  the night instantly.
@@ -136,16 +147,16 @@ What catches up, and how:
136
147
  - Not run while skipping: `onFixed`, module `fixed` hooks, physics, near simulation. Every time view moves exactly as if stepped (tick, real,
137
148
  ambient, each channel by the skipped real seconds x its speed, the calendar), so timers on any channel fire and `mod`s with `for` end in order (`mod:end` as often as when stepping). So anything that must advance during a sleep is measured in calendar seconds (`clock.now`) or lives in a world record with `far`.
138
149
  - Input is locked and gameplay frozen for the whole skip (keys pressed during the fade do nothing). With `fade: 0` (default) the time has moved when
139
- `skip` returns; with a fade the Promise resolves after the fade in, which needs frames (in a paused test keep calling `engine.step`).
150
+ `skip` returns; with a fade the Promise resolves after the fade in, which needs frames (in a halted test keep calling `engine.step`).
140
151
  - A stopped calendar (`clock.rate` 0) skips as if at 1x. The jump itself is the op `time.skip { seconds }` (logged and replayable; it refuses `seconds <= 0`).
141
- - A module that keeps its own time implements the hook `skip(dt, e, done)` (called once per segment; `done` on the last one).
152
+ - A module that keeps its own time implements the hook `skip` (recipe 49, item 3).
142
153
 
143
154
  ### Order inside one frame
144
- Each rendered frame runs: input poll -> the fixed steps due (`commits` applied first, then `onFixed`, module `fixed` hooks, clock timers) -> `onFrame`
145
- callbacks **in the order they were registered** -> module `frame` hooks -> stream / jobs / batching -> render -> `afterRender` hooks. The animation of a model
146
- from `engine.assets.animate` (and a Character's model) is itself an `onFrame` callback registered when the animator was created, so your `onFrame` runs
147
- before it if you registered first (you see last frame's pose) and after it if you registered later. To read or override a pose after animation, register
148
- the callback after the model is created, or use an `afterRender` hook.
155
+ Each rendered frame runs: input poll -> the fixed steps due (`commits` applied first, then `onFixed`, module `fixed` hooks, `onFixed` `{ phase: 'late' }`, clock timers) -> `onFrame`
156
+ callbacks **in the order they were registered** -> animators (every `engine.assets.animate` model and a Character's clips) -> module `frame` hooks -> stream / jobs / batching -> render -> `afterRender` hooks.
157
+ Animators run after the whole `onFrame` list, whoever registered first: an `anim.sync / go / set` from `onFrame` shows this frame, and `onFrame` reads last frame's pose.
158
+ To read or override a pose after animation, use `character.onPose` (recipe 13) or a module `frame` hook.
159
+ When a game has several systems, a default that keeps this order in one place: one `engine.onFixed(dt => { weapons.step(dt); enemies.step(dt); })` in `main.js` instead of one registration per system (`{ phase: 'late' }` for code that reads this step's results; a game module with `before` / `after`: recipe 14).
149
160
 
150
161
  ## 3. Verify
151
162
  - Without waiting real time: in a test or the console, `engine.calendar.timeOfDay = parseClock('17:59'); engine.step(5)`, then look at the result (`step`
@@ -156,10 +167,8 @@ the callback after the model is created, or use an `afterRender` hook.
156
167
  is not 1, divide by `engine.clock.speed` as well.
157
168
  - Reproduce a scenario: `npm run shot -- / --time 17:58 --wait 10 --describe-only`, then look at the time (18:0x) and your effect (lamps, NPCs, items).
158
169
  - After `npm run map`, the "timed events" section of GAMEMAP.md lists every `calendar.at/between/daily/onSeason` and `clock.after/every`.
159
- - Is skip the same as living through it? `const r = await engine.checkSkip(600)` skips 600 calendar seconds, rewinds, steps the same span and compares the
160
- saved state: `{ ok, diffs: [{ path, a, b }] }` (refuses with `{ ok: false, code: 'frozen' | 'rate0', facts, diffs }` while gameplay is frozen or the clock stopped; pending background results are applied first) (a = skip, b = step; `{ ignore: ['parts.world', 'parts.rigid', 'parts.random'] }` drops paths). Skip does not run near simulation (the weather module has a skip hook, so its timers do advance), so a moving player/NPC
161
- or a physics body that is still settling always differs: ignore those parts and read the rest. It leaves the world at the stepped state, so run
162
- it on a scratch playthrough or in a test. A diff usually means a module with its own time lacks a `skip` hook. `await engine.checkSave()` does the same
163
- for save -> load (a diff names a save part whose `load` does not restore what `save` wrote).
170
+ - Is skip the same as living through it? `const r = await engine.checkSkip(600)` skips 600 calendar seconds, rewinds, steps the same span and compares the saved state: `{ ok, diffs: [{ path, a, b }] }`
171
+ (a = skip, b = step; `{ ignore: ['parts.world', 'parts.rigid', 'parts.random'] }` drops paths; it refuses while frozen or with the clock stopped). Skip runs no near simulation, so a moving player/NPC
172
+ or a settling physics body always differs: ignore those parts and read the rest. It leaves the world at the stepped state, so run it on a scratch playthrough or in a test. A diff usually means a
173
+ module with its own time lacks a `skip` hook. `await engine.checkSave()` does the same for save -> load (a diff names a save part whose `load` does not restore what `save` wrote).
164
174
  - Why did it fire (or not)? `engine.events.traceSize = 200` records each event with the event or op that caused it: `events.trace('item:add').at(-1).chain`. Failed ops, sight queries and NPC state changes are entries too (with `code`); `events.note(name, { obj, code, data })` adds your own and `events.traceFocus(id)` makes one object verbose (the ring is bounded; size 0 costs nothing). Details: recipe 23 section 12.
165
- - Related tests: `npm test -- 游戏时钟 SKIP`.
@@ -4,7 +4,7 @@
4
4
 
5
5
  Needs the module `flow()` (not in openWorld; add it yourself: `engine.use(openWorld({ camera: 'follow', ...}), flow())`).
6
6
  - **Flow states**: title, playing (built-in `playing`), paused (built-in `paused`: freezes gameplay + locks input), ending, ... Only one is active at a time.
7
- - **Scene transition** `transition(fn)`: lock input -> fade to black -> fade music out -> (with `{ autosave: 'auto' }` save slot 'auto'; off by
7
+ - **Scene transition** `transition(fn)`: lock input -> fade to black -> fade music out -> (with `{ autosave: 'auto' }` save slot 'auto'; off by If the world does not settle within `engine.loading.timeoutMs`, it rejects with `module-not-ready` and gives the screen and input back. Autosave waits for the end of a transition.
8
8
  default) -> run fn -> wait until every module is ready -> fade in -> unlock. Repeated calls queue up automatically.
9
9
 
10
10
  ## 1. Pause / title / ending (in main.js)
@@ -21,22 +21,27 @@ engine.flow.define('title', {
21
21
  engine.flow.define('ending', { freeze: true, lockInput: true, enter: () => toast(engine, 'The end') });
22
22
  startBtn.onclick = () => engine.flow.go('playing');
23
23
 
24
- engine.input.action('pause', { label: 'Pause', keys: ['KeyO'] }); // read by action name; Esc is the back key (see below); presets.bindings.* hold ready key maps (P, I, J, E; see the key table in GAMEMAP)
24
+ engine.input.action('pause', { label: 'Pause', keys: ['KeyO'] }); // read by action name; Esc is the back key (see below)
25
25
  engine.onFrame(() => {
26
26
  if (engine.input.pressedRaw('pause')) engine.flow.go(engine.flow.state === 'paused' ? 'playing' : 'paused'); // paused pushes an opaque input context, so use pressedRaw
27
27
  });
28
28
  engine.events.on('flow:change', ({ from, to }) => console.log(from, '->', to));
29
29
  ```
30
30
  **Pausing has a single entry point: flow's `'paused'`** (internally `engine.freeze('flow')`: the picture keeps rendering and the UI keeps working).
31
- **Don't use `engine.pause()`** (it stops even rendering and is for tests).
31
+ `engine.haltLoop()` stops even rendering and is for tests; a game never needs it.
32
32
  The settings menu also pauses while open: `settings({ freezeWorld: true })`. With flow installed it switches to `'paused'` and returns to the previous
33
33
  state when the menu closes; without flow it calls `engine.freeze('settings')` directly.
34
34
  Stopped while frozen: the fixed step (movement, physics), module `fixed`, the game clock `clock`, quest checks (they run in the fixed step), timeline
35
35
  `wait` / tweens / camera / paths. Still running: rendering, UI, `onFrame`, the fade-to-black `fadeScreen`.
36
36
 
37
- Restarting a run from a UI button (retry, "play again"): do not reset positions, health and spawns inside the click handler or an `onFrame` callback; that is
38
- mid-frame and can leave half the world on the old tick. Apply it on a fixed tick: `engine.nextFixed(resetRun)`
39
- (runs at the start of the next fixed step, in a stable order), or set a flag in the handler and reset in `onFixed`.
37
+ Restarting a run from a UI button (retry, "play again"): a whole new run is `engine.session.newGame()`; it works from a frozen screen too, and flow goes to `'playing'` by itself.
38
+ To reset only part of the run, do not write positions, health and spawns inside the click handler or an `onFrame` callback; that is mid-frame and can leave half the world on the old tick.
39
+ Apply it on a fixed tick with `engine.nextFixed(fn)` or a flag read in `onFixed`. No fixed step runs while frozen, so on an end screen with `freeze: true` leave the freeze first:
40
+ ```js
41
+ engine.flow.define('gameOver', { freeze: true, lockInput: true });
42
+ const resetRun = () => engine.vars.bump('tries', 1); // the game's own reset: positions, health, spawns
43
+ const retry = async () => { engine.flow.go('playing'); await engine.nextFixed(resetRun); }; // this order: frozen, nextFixed never fires
44
+ ```
40
45
 
41
46
  ### Back key (Esc): the UI focus stack
42
47
  Windows (inventory, quests, settings), dialogue and cutscenes are pushed onto the stack in the order they open (`uiFocus(engine)` in `ui/Focus.js`),
@@ -44,6 +49,7 @@ and Esc goes **only to the top one**:
44
49
  cutscene -> skip; window -> close; dialogue -> swallow (do nothing); empty stack -> open the settings menu. So one Esc never both skips a cutscene and
45
50
  opens the menu, and no patch like "ignore keys for 0.15 s after opening" is needed.
46
51
  A game's own windows made with `makeWindow` are pushed automatically (`onCancel` changes what Esc does); UI you draw yourself must be pushed:
52
+ `uiFocus` is experimental; `engine.input.push` is the stable route to take the keys for a screen of your own.
47
53
  ```js
48
54
  import { uiFocus } from 'threedog';
49
55
  const h = uiFocus(engine).push('myMap', { cancel: () => closeMap() }); // call h.remove() when closing; h.fresh = opened this very frame
@@ -57,7 +63,7 @@ already showing. The title's buttons go through `engine.session` (section 4): a
57
63
  To open straight into play, pick the start state up front instead of leaving the title afterwards; time and weather come from the engine's
58
64
  own URL keys (`?time=22:20&weather=storm`, applied after `engine:ready`, weather at once, then `wait` seconds are advanced), so only the game's
59
65
  own state needs a key of its own.
60
- ```js
66
+ ```js fragment
61
67
  const q = new URLSearchParams(location.search), moment = q.get('moment'); // the game's own key: which lamps are lit, the score ...
62
68
  engine.use(openWorld({ camera: 'follow' }), flow({ start: moment ? 'playing' : 'title' }));
63
69
  engine.flow.define('title', { freeze: true, lockInput: true,
@@ -77,13 +83,12 @@ game's camera there at once. An unknown name stops with the list of places. A ca
77
83
  To get past the title without a key of your own, use the engine's `?play` URL key (`npm run shot -- --play`, `applyState({ play: true })`): after
78
84
  `engine:ready` it does what the title's Start does (`engine.session.newGame()`, then the title part closes), so `flow({ start: 'title' })` moves to
79
85
  `'playing'` and the game's `session:start` setup runs; with no title up it does nothing. `?fresh` (`applyState({ fresh: true })`) first deletes this
80
- page's saves, so the title offers no Continue; on a running page it also ends the run. Two things that make a moment
81
- drawing half-done in a picture: a headless page advances only on `engine.step` (the shot steps one frame after the game's code, so a
82
- `weather.set(name, { seconds: 0.1 })` made after `start()` shows a third of the change: use `seconds: 0`), and an `onFrame` copy of a sky
86
+ page's saves, so the title offers no Continue; on a running page it also ends the run. Two things that leave a moment half-drawn in a picture: a headless page
87
+ advances only on `engine.step`, so a `weather.set(name, { seconds: 0.1 })` made after `start()` is still changing (use `seconds: 0`), and an `onFrame` copy of a sky
83
88
  color is one frame old (share `engine.uniforms.uSkyHorizon` instead, recipe 08).
84
89
 
85
90
  ## 2. Changing scene / teleporting
86
- ```js
91
+ ```js fragment
87
92
  // A level-based game: switch to another map
88
93
  await engine.flow.transition(async () => {
89
94
  await engine.level.load('/models/town2.glb'); // or a name from the assets manifest
@@ -91,25 +96,20 @@ await engine.flow.transition(async () => {
91
96
  engine.cameraRig.follow(engine.player.root); // the camera jumps straight there instead of flying from far away
92
97
  }, { fade: 0.6, autosave: 'auto' }); // also save slot 'auto' before switching
93
98
 
94
- // Teleport within the same map (the city test page's teleport pad): no save, music keeps playing
99
+ // Teleport within the same map: no save, music keeps playing
95
100
  engine.flow.transition(() => engine.player.placeAt([40, 0, -20]), { music: 'keep' });
96
101
  ```
97
- When the level changes, the old level's things are cleared automatically: trigger zones built by `triggers.fromMarkers`, and pickups / trigger zones /
98
- props in content whose position uses a level marker.
99
- An NPC like that is not deleted: its data (in `engine.world`, with zone = level name) stays and only the model is removed; it is rebuilt automatically
102
+ When the level changes, trigger zones built by `triggers.fromMarkers` are cleared automatically. NPCs, pickups and props in content whose position uses a level
103
+ marker are not deleted: their data (in `engine.world`, with zone = level name) stays and only the model is removed; it is rebuilt automatically
100
104
  when you return to this map, with its state intact.
101
105
  Things the game builds itself that belong to this map are registered with `engine.level.track(handle)` (`{ remove() }`) and deleted together when the
102
106
  map changes.
103
107
  Loading a save across levels: the save records the level name, so `await engine.saves.load('slot1')` first switches back to that map, waits for it to
104
- finish loading, and then puts the player and everything else back (the level must be loaded by name, `level({ url })`; a code-built `level({ scene })`
105
- can't be recorded).
106
-
107
- Saves live in the browser's IndexedDB (no 5 MB limit; when it is unavailable it falls back to localStorage and tells you once; old localStorage saves
108
- are moved over on first launch). `save()` / `remove()` / `load()` return a Promise (awaiting is optional; a failed write shows a notice), while
109
- `list()` / `export()` are synchronous (saves are read into memory at startup). Photos are stored separately as Blobs and are not part of the world save.
110
- Backup: `engine.saves.exportFile('slot1')` downloads a .json (including all binary attachments such as photos; `{ files: false }` gives only the world
111
- save), and `await engine.saves.importFile(file)` restores it into a save slot (without a file, a file picker opens); the "Saves" page of the settings
112
- menu has matching buttons.
108
+ finish loading, and then puts the player and everything else back. The level must be loaded by name, `level({ url })`. For an area built in code that name
109
+ is a builder in the assets manifest (recipe 66, "Two areas built in code"); a `level({ scene })` object has no name to record.
110
+
111
+ Saves live in the browser's IndexedDB (falling back to localStorage, with one notice). `save()` / `remove()` / `load()` return a Promise (a failed write shows a notice), while
112
+ `list()` / `export()` are synchronous (saves are read into memory at startup). Attachments, file backup and `storageKey`: `../api/saves.md`.
113
113
  For just a fade-to-black, without locking input or saving: `await fadeScreen(engine, 1, { seconds: 0.5 }); ...; await fadeScreen(engine, 0, { seconds: 0.5 });` (import from `threedog`).
114
114
  Fades inside a cutscene use the timeline steps `{ fade: 0.5 }`, `{ fade: 0.5, to: 0 }`.
115
115
 
@@ -140,33 +140,31 @@ engine.input.action('menuConfirm', { label: 'OK', keys: ['Space'], context: 'men
140
140
  whether input is locked.
141
141
  - In tests: after `engine.flow.go('paused'); engine.step(1)` the player position, `engine.clock.now`, quest progress and timelines are unchanged;
142
142
  after `await engine.flow.transition(fn)` returns, `transitioning` is false (if fn throws, the error goes to the caller and the screen still fades back in).
143
- - Related tests: `npm test -- 游戏流程` (city: transition fade and input lock, paused freeze), `npm test -- 接缝` (Esc focus stack, quests/timelines frozen
144
- while frozen, screen fades back in when transition fails).
145
143
 
146
144
  ## 4. New game / continue / back to title / retry (engine.session)
147
145
  Every playthrough starts from a clean slate, so a second new game is exactly like the first:
148
- ```js
146
+ ```js fragment
149
147
  await engine.session.newGame(); // the state right after start(): world, containers, vars, quests, clock, sky, weather, random
150
148
  await engine.session.load('slot1'); // continue (title "Continue", settings "Load"); retry: engine.session.load('checkpoint')
151
149
  await engine.session.quit(); // back to the title (settings "Back to title"); the title's Start calls newGame
152
150
  engine.session.track(engine.events.once('npc:talk', onTalk)); // anything the game adds during play: removed when the playthrough ends
153
151
  ```
154
- Ending a playthrough skips a running cutscene, removes tracked handles, drops clock timers added after start(), drops background results not yet
152
+ Ending a playthrough drops a running cutscene, removes tracked handles, drops clock timers added after start(), drops background results not yet
155
153
  applied (commits), stops the music, applies the start state and snaps the camera to the player. flow goes back to its start state, then to
156
154
  `'playing'`. Events: `session:end`, `session:start { kind: 'new' | 'load', slot? }` (play an intro per new game there, not on `engine:ready`).
157
155
  - When a save part's `load()` throws, newGame / `session.load` resolve `false` and the old playthrough goes on: its data is rolled back, its
158
- tracked handles and timers stay, flow returns to the state it left, and `session:failed { kind, slot? }` fires instead of `session:start`.
156
+ tracked handles and timers stay, flow returns to the state it left, and `session:failed { kind, slot? }` fires instead of `session:start` (also from a rolled-back `saves.load` or `saves.apply`, with `kind: 'quick'`) (for a quit: instead of the title, kind 'quit').
159
157
  - `saves.load(slot)` is a quick load onto the running playthrough (keeps what the game added); `session.load(slot)` ends the playthrough first and
160
158
  refuses an unreadable save without touching the game. Deleting a save is `saves.remove(slot)`.
161
159
  - Listeners and hooks registered at boot stay (they are the game); register play-time ones with `session.track`.
162
160
 
163
161
  ## 5. Window and device (engine.page)
164
162
  One place listens to window focus, tab visibility, mouse lock and the WebGL context; modules never add their own listeners.
165
- - Window in the background / tab hidden: gameplay waits (no fixed steps; rendering and UI go on). `createEngine({ pauseOnBlur: false })` or
163
+ - Window in the background / tab hidden: gameplay is frozen by owner `'page'`, a full still (`freeze('page', { ambient: true })`; cutscenes stop too, rendering and UI go on; `engine.frozen` and `runState.owners` show it). `createEngine({ pauseOnBlur: false })` or
166
164
  `engine.page.pauseOnBlur = false` keeps playing. Coming back resumes with no catch-up burst; a long frame turns into at most 0.1 s of fixed steps,
167
165
  and fewer when the steps are heavy (at most about 33 ms of catch-up work per frame; the rest is dropped as a brief slow-down). `engine.step()` never drops time.
168
166
  - `engine.events.on('page:blur', () => engine.flow?.go('paused'))` also opens the pause menu. Other events: `page:focus`,
169
- `page:pointerlock { locked, byEngine }` (cameras lock again on the next click; a lock the player ended counts as Esc, because the browser keeps that key), `page:contextlost` / `page:contextrestored` (gameplay waits and the player
167
+ `page:pointerlock { locked, byEngine }` (cameras lock again on the next click; a lock the player ended counts as Esc, because the browser keeps that key), `page:contextlost` / `page:contextrestored` (the same freeze, and the player
170
168
  sees a message; three.js restores the context).
171
169
  - `engine.step()` still advances while away (tests, dev bridge). Held keys are released by Input.
172
- - Tests: `npm test -- "Session:" "Window:"`.
170
+ - Tests: `threedog test "Session:" "Window:"`.