threedog 0.8.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 (372) hide show
  1. package/CHANGELOG.md +219 -4
  2. package/README.md +6 -6
  3. package/core/assets/Animator.js +2 -0
  4. package/core/assets/Assets.js +44 -13
  5. package/core/assets/assetEntry.js +87 -22
  6. package/core/assets/assetHot.js +2 -1
  7. package/core/assets/assetReport.js +1 -2
  8. package/core/audio/Audio.js +24 -5
  9. package/core/base/I18n.js +6 -3
  10. package/core/base/Random.js +3 -1
  11. package/core/base/Vars.js +14 -4
  12. package/core/base/errorCodes.js +54 -16
  13. package/core/base/errorHints.js +12 -1
  14. package/core/base/errors.js +6 -4
  15. package/core/base/events.generated.js +10 -0
  16. package/core/base/follows.js +26 -0
  17. package/core/base/math.js +15 -8
  18. package/core/base/params.js +2 -2
  19. package/core/{saves → base}/saveValues.js +24 -6
  20. package/core/base/sections.js +97 -0
  21. package/core/base/spelling.js +32 -0
  22. package/core/base/validate.js +8 -29
  23. package/core/engine/Engine.js +61 -18
  24. package/core/engine/Loading.js +30 -3
  25. package/core/engine/copies.js +1 -1
  26. package/core/engine/headlessLoad.js +30 -13
  27. package/core/engine/lifecycle.js +30 -25
  28. package/core/engine/loop.js +22 -4
  29. package/core/engine/moduleSlots.js +91 -15
  30. package/core/engine/moduleTypes.js +13 -0
  31. package/core/engine/modules.js +248 -62
  32. package/core/engine/page.js +25 -8
  33. package/core/engine/plugins.js +15 -3
  34. package/core/engine/services.js +3 -0
  35. package/core/engine/startup.js +46 -36
  36. package/core/input/Input.js +39 -19
  37. package/core/input/inputKeyboard.js +39 -0
  38. package/core/input/inputPad.js +23 -2
  39. package/core/input/inputPointer.js +3 -1
  40. package/core/input/inputSeat.js +66 -0
  41. package/core/input/inputTouch.js +23 -6
  42. package/core/inspect/DebugOverrides.js +13 -2
  43. package/core/inspect/Describe.js +10 -6
  44. package/core/inspect/Inspect.js +31 -4
  45. package/core/inspect/UrlState.js +14 -10
  46. package/core/inspect/catalog.js +12 -5
  47. package/core/inspect/describeRender.js +3 -2
  48. package/core/inspect/describeText.js +6 -2
  49. package/core/inspect/metadata.generated.js +4140 -0
  50. package/core/inspect/pictureWriters.js +117 -33
  51. package/core/inspect/toolDoor.js +21 -0
  52. package/core/inspect/valueHistory.js +35 -0
  53. package/core/ops/Ops.js +32 -7
  54. package/core/ops/control.js +48 -23
  55. package/core/ops/holds.js +4 -3
  56. package/core/ops/opsAtomic.js +18 -6
  57. package/core/ops/opsCheck.js +7 -5
  58. package/core/ops/opsFail.js +5 -7
  59. package/core/ops/opsRun.js +2 -2
  60. package/core/ops/owned.js +20 -3
  61. package/core/ops/sharedPoint.js +7 -10
  62. package/core/ops/stacks.js +22 -1
  63. package/core/saves/SaveStore.js +52 -26
  64. package/core/saves/Saves.js +122 -27
  65. package/core/saves/saveApply.js +159 -61
  66. package/core/saves/saveFiles.js +30 -25
  67. package/core/saves/saveVersions.js +20 -6
  68. package/core/saves/session.js +76 -33
  69. package/core/saves/stateReplace.js +184 -0
  70. package/core/scene/Rays.js +21 -5
  71. package/core/scene/Views.js +6 -6
  72. package/core/scene/adaptive.js +13 -10
  73. package/core/scene/canvasBox.js +2 -0
  74. package/core/scene/compositeGround.js +72 -0
  75. package/core/scene/floor.js +17 -0
  76. package/core/scene/grid.js +2 -0
  77. package/core/scene/ground.contract.js +14 -0
  78. package/core/scene/ground.js +52 -17
  79. package/core/scene/pixel.js +154 -0
  80. package/core/scene/pixelRatio.js +167 -0
  81. package/core/scene/sceneDelta.js +3 -3
  82. package/core/scene/sceneMethods.js +11 -6
  83. package/core/scene/stepPoses.js +6 -1
  84. package/core/scene/thingExplain.js +1 -1
  85. package/core/scene/thingOps.js +22 -14
  86. package/core/scene/things.js +1 -1
  87. package/core/scene/tier.js +10 -0
  88. package/core/scene/view.js +126 -9
  89. package/core/stream/Batching.js +0 -1
  90. package/core/stream/Stream.js +24 -12
  91. package/core/stream/batchGroups.js +1 -0
  92. package/core/stream/scatter.js +5 -2
  93. package/core/stream/streamSources.js +2 -1
  94. package/core/threads/Commits.js +12 -7
  95. package/core/threads/Jobs.js +15 -5
  96. package/core/threads/Threads.js +5 -2
  97. package/core/time/Clock.js +3 -1
  98. package/core/time/skip.js +10 -4
  99. package/core/time/time.js +16 -10
  100. package/docs/AI.md +89 -72
  101. package/docs/API.md +18 -14
  102. package/docs/CODEMAP.md +68 -40
  103. package/docs/COMMANDS.md +22 -23
  104. package/docs/CONVENTIONS.md +120 -17
  105. package/docs/MIGRATING-0.8.md +2 -0
  106. package/docs/MIGRATING-1.0.md +101 -0
  107. package/docs/THREE.md +65 -12
  108. package/docs/api/cameraRig.md +3 -0
  109. package/docs/api/characters.md +13 -7
  110. package/docs/api/collider3d.md +9 -0
  111. package/docs/api/content.md +16 -15
  112. package/docs/api/dialogue.md +2 -1
  113. package/docs/api/engine.md +18 -16
  114. package/docs/api/events.md +14 -4
  115. package/docs/api/ground.md +2 -2
  116. package/docs/api/i18n.md +1 -1
  117. package/docs/api/input.md +2 -1
  118. package/docs/api/interactions.md +1 -1
  119. package/docs/api/inventory.md +1 -1
  120. package/docs/api/level.md +3 -2
  121. package/docs/api/nav.md +4 -2
  122. package/docs/api/particles.md +8 -5
  123. package/docs/api/pickups.md +1 -1
  124. package/docs/api/post.md +3 -4
  125. package/docs/api/quests.md +4 -2
  126. package/docs/api/rays.md +2 -0
  127. package/docs/api/rigid.md +3 -2
  128. package/docs/api/saves.md +8 -7
  129. package/docs/api/stream.md +4 -5
  130. package/docs/api/terrain.md +3 -4
  131. package/docs/api/terrainDraw.md +1 -1
  132. package/docs/api/timeline.md +2 -2
  133. package/docs/api/tools.md +3 -1
  134. package/docs/api/triggers.md +2 -0
  135. package/docs/api/vegetationDraw.md +1 -1
  136. package/docs/api/water.md +6 -2
  137. package/docs/api/weather.md +19 -4
  138. package/docs/api/weatherDraw.md +1 -1
  139. package/docs/api/world.md +1 -1
  140. package/docs/recipes/01-new-game.md +3 -3
  141. package/docs/recipes/02-npc.md +3 -4
  142. package/docs/recipes/03-items-pickups.md +11 -11
  143. package/docs/recipes/04-quests.md +2 -0
  144. package/docs/recipes/05-props-bake.md +9 -9
  145. package/docs/recipes/06-clock-events.md +6 -6
  146. package/docs/recipes/07-flow-scenes-pause.md +18 -15
  147. package/docs/recipes/08-weather-sky.md +5 -5
  148. package/docs/recipes/09-materials-lights-models.md +3 -3
  149. package/docs/recipes/10-blender-level.md +16 -4
  150. package/docs/recipes/11-vehicles.md +18 -6
  151. package/docs/recipes/12-navmesh.md +52 -8
  152. package/docs/recipes/13-animation.md +34 -8
  153. package/docs/recipes/14-custom-module.md +20 -8
  154. package/docs/recipes/15-perf.md +4 -4
  155. package/docs/recipes/16-dev-bridge.md +9 -8
  156. package/docs/recipes/18-world.md +13 -5
  157. package/docs/recipes/19-shooting-picking.md +3 -2
  158. package/docs/recipes/20-content-actions-save.md +26 -6
  159. package/docs/recipes/21-camera.md +17 -23
  160. package/docs/recipes/22-shop-gold.md +21 -12
  161. package/docs/recipes/23-ops.md +19 -15
  162. package/docs/recipes/26-ui-parts.md +3 -2
  163. package/docs/recipes/27-net.md +3 -3
  164. package/docs/recipes/28-terrain.md +3 -3
  165. package/docs/recipes/29-grid.md +1 -1
  166. package/docs/recipes/30-templates.md +10 -13
  167. package/docs/recipes/31-audio.md +2 -2
  168. package/docs/recipes/32-action-game.md +6 -5
  169. package/docs/recipes/33-stream-sources.md +4 -1
  170. package/docs/recipes/34-environment-lighting.md +7 -8
  171. package/docs/recipes/35-picture-from-reference.md +13 -9
  172. package/docs/recipes/36-ground-plants.md +3 -2
  173. package/docs/recipes/40-scene.md +11 -10
  174. package/docs/recipes/43-shader-patches-surfaces.md +7 -7
  175. package/docs/recipes/44-water-weather-hooks.md +9 -8
  176. package/docs/recipes/45-cascaded-shadows.md +3 -4
  177. package/docs/recipes/46-blender-art-route.md +3 -3
  178. package/docs/recipes/49-game-module-contract.md +2 -1
  179. package/docs/recipes/50-own-renderer.md +1 -0
  180. package/docs/recipes/51-capability-catalog.md +14 -8
  181. package/docs/recipes/52-around-the-picture.md +4 -4
  182. package/docs/recipes/55-mods-time-wrap.md +5 -4
  183. package/docs/recipes/56-webgpu-tsl.md +12 -1
  184. package/docs/recipes/57-control.md +30 -10
  185. package/docs/recipes/58-input.md +13 -0
  186. package/docs/recipes/60-judge-the-picture.md +1 -1
  187. package/docs/recipes/62-picture-code.md +106 -48
  188. package/docs/recipes/63-third-person-start.md +2 -1
  189. package/docs/recipes/64-particles.md +53 -4
  190. package/docs/recipes/65-swarm.md +2 -2
  191. package/docs/recipes/66-common-tasks.md +313 -0
  192. package/examples/action/.threedog/content-index.json +1 -1
  193. package/examples/action/GAMEMAP.md +3 -3
  194. package/examples/perf-island/.threedog/content-index.json +1 -1
  195. package/examples/perf-island/GAMEMAP.md +3 -3
  196. package/examples/perf-island/main.js +2 -2
  197. package/examples/plain-picture/GAMEMAP.md +3 -1
  198. package/examples/rc2d/GAMEMAP.md +1 -1
  199. package/examples/rc2d/rc2d.js +1 -1
  200. package/examples/styletest/.threedog/content-index.json +1 -1
  201. package/examples/styletest/GAMEMAP.md +3 -3
  202. package/examples/webgpu-tsl/GAMEMAP.md +1 -1
  203. package/examples/world/.threedog/content-index.json +1 -1
  204. package/examples/world/GAMEMAP.md +5 -4
  205. package/examples/world/main.js +3 -3
  206. package/index.d.ts +8 -5
  207. package/index.js +22 -1
  208. package/llms.txt +2 -1
  209. package/modules/ambience/Ambience.js +5 -3
  210. package/modules/calendar/index.js +7 -5
  211. package/modules/camera/FirstPersonCamera.js +3 -3
  212. package/modules/camera/FixedCamera.js +34 -20
  213. package/modules/camera/FollowCamera.js +20 -11
  214. package/modules/camera/RtsCamera.js +1 -0
  215. package/modules/camera/common.js +33 -22
  216. package/modules/camera/pixelSnap.js +62 -0
  217. package/modules/characters/Character.js +136 -43
  218. package/modules/characters/NPC.js +60 -28
  219. package/modules/characters/assetModel.js +2 -2
  220. package/modules/characters/astar.js +47 -28
  221. package/modules/characters/character.contract.js +21 -0
  222. package/modules/characters/contract.js +17 -3
  223. package/modules/characters/index.js +94 -34
  224. package/modules/characters/moveHelpers.js +80 -15
  225. package/modules/characters/mover.contract.js +14 -0
  226. package/modules/characters/movers/common.js +6 -4
  227. package/modules/characters/movers/rapier.js +12 -5
  228. package/modules/characters/movers/simple.js +25 -12
  229. package/modules/characters/movers/support.js +18 -7
  230. package/modules/characters/npcAvoid.js +15 -12
  231. package/modules/characters/npcSim.js +75 -25
  232. package/modules/characters/npcView.js +13 -6
  233. package/modules/characters/pathAsync.js +74 -24
  234. package/modules/characters/pathJob.js +38 -21
  235. package/modules/characters/player.js +59 -47
  236. package/modules/characters/seat.js +56 -0
  237. package/modules/characters/vehicle.contract.js +8 -5
  238. package/modules/characters/walkTo.js +31 -18
  239. package/modules/collision/Collision.js +44 -26
  240. package/modules/collision/contract.js +2 -2
  241. package/modules/collision/grid.js +6 -1
  242. package/modules/content/explain.js +1 -1
  243. package/modules/content/fields.js +3 -3
  244. package/modules/content/ids.js +3 -1
  245. package/modules/content/index.js +83 -27
  246. package/modules/content/loader.js +110 -130
  247. package/modules/content/markers.js +1 -1
  248. package/modules/content/models.js +48 -14
  249. package/modules/content/packs.js +2 -1
  250. package/modules/content/places.js +5 -4
  251. package/modules/content/props.js +8 -6
  252. package/modules/content/rules.js +29 -47
  253. package/modules/content/templates.js +66 -35
  254. package/modules/content/words.js +19 -6
  255. package/modules/debug/DebugPanel.js +4 -2
  256. package/modules/flow/contract.js +1 -0
  257. package/modules/flow/index.js +24 -14
  258. package/modules/gameplay/Container.js +5 -2
  259. package/modules/gameplay/Containers.js +9 -1
  260. package/modules/gameplay/Dialogue.js +82 -25
  261. package/modules/gameplay/Interactions.js +61 -32
  262. package/modules/gameplay/Inventory.js +56 -13
  263. package/modules/gameplay/Quests.js +133 -24
  264. package/modules/gameplay/boxOps.js +7 -0
  265. package/modules/gameplay/dialogueBubbles.js +14 -9
  266. package/modules/gameplay/inventoryOps.js +11 -7
  267. package/modules/gameplay/pickups.js +43 -16
  268. package/modules/gameplay/questLog.js +4 -2
  269. package/modules/gameplay/questSave.js +6 -1
  270. package/modules/gameplay/quests.contract.js +1 -1
  271. package/modules/grid/Grid.js +1 -1
  272. package/modules/grid/Layer.js +8 -4
  273. package/modules/grid/index.js +21 -15
  274. package/modules/grid/ops.js +43 -46
  275. package/modules/grid/tiles.js +1 -1
  276. package/modules/hlod/index.js +6 -3
  277. package/modules/hud/index.js +6 -4
  278. package/modules/hud/parts.js +4 -4
  279. package/modules/level/contract.js +2 -2
  280. package/modules/level/heightfield.js +17 -21
  281. package/modules/level/index.js +83 -26
  282. package/modules/level/load.js +165 -48
  283. package/modules/level/nodes.js +34 -16
  284. package/modules/lights/index.js +6 -3
  285. package/modules/lights/sources.js +3 -1
  286. package/modules/music/Music.js +4 -2
  287. package/modules/nav/contract.js +7 -5
  288. package/modules/nav/index.js +174 -44
  289. package/modules/nav/navPath.js +45 -10
  290. package/modules/net/index.js +1 -1
  291. package/modules/particles/Particles.js +85 -22
  292. package/modules/particles/effect.js +80 -28
  293. package/modules/particles/shaders.js +17 -0
  294. package/modules/photo/Photo.js +12 -10
  295. package/modules/rigid/RigidBodies.js +200 -57
  296. package/modules/rigid/Vehicles.js +15 -5
  297. package/modules/rigid/collider3d.contract.js +26 -0
  298. package/modules/rigid/ragdoll.js +55 -44
  299. package/modules/rigid/ragdollBones.js +83 -33
  300. package/modules/rigid/refresh.js +10 -0
  301. package/modules/rigid/sync.js +46 -15
  302. package/modules/settings/Settings.js +84 -37
  303. package/modules/settings/apply.js +15 -8
  304. package/modules/settings/sections.js +7 -4
  305. package/modules/settings/strings.js +2 -2
  306. package/modules/sky/skyModule.js +3 -1
  307. package/modules/swarm/Swarm.js +16 -6
  308. package/modules/terrain/ChunkManager.js +10 -16
  309. package/modules/terrain/index.js +17 -11
  310. package/modules/terrain/terrainEdit.js +13 -2
  311. package/modules/terrain/terrainGen.js +5 -3
  312. package/modules/terrain/terrainShape.js +1 -1
  313. package/modules/timeline/Timeline.js +58 -26
  314. package/modules/timeline/Tween.js +19 -13
  315. package/modules/timeline/shots.js +19 -10
  316. package/modules/triggers/index.js +87 -20
  317. package/modules/vegetation/Vegetation.js +4 -3
  318. package/modules/vegetation/draw.js +16 -0
  319. package/modules/vegetation/groundChunks.js +10 -7
  320. package/modules/vegetation/index.js +30 -7
  321. package/modules/water/Water.js +6 -2
  322. package/modules/weather/Weather.js +16 -15
  323. package/modules/weather/weatherDraw.js +7 -6
  324. package/modules/world/World.js +20 -7
  325. package/modules/world/explain.js +1 -1
  326. package/modules/world/index.js +13 -6
  327. package/modules/world/persist.js +23 -8
  328. package/modules/world/pos.js +4 -4
  329. package/modules/world/records.js +13 -7
  330. package/modules/world/sim.js +74 -23
  331. package/modules/world/simFar.js +2 -2
  332. package/modules/world/state.js +31 -6
  333. package/modules/world/thingSource.js +16 -3
  334. package/modules/world/views.js +19 -8
  335. package/package.json +7 -1
  336. package/render/PostFX.js +47 -29
  337. package/render/backend.js +5 -1
  338. package/render/fx/particles.tsl.js +8 -6
  339. package/render/fx/postWebGPU.tsl.js +3 -3
  340. package/render/layers.js +1 -1
  341. package/render/lightmap.js +23 -3
  342. package/render/occlusion.js +43 -12
  343. package/render/patches.js +2 -2
  344. package/render/postWebGL.js +4 -3
  345. package/render/probes.js +25 -0
  346. package/render/shadows.js +2 -2
  347. package/types/core.d.ts +142 -55
  348. package/types/gameplay.d.ts +92 -40
  349. package/types/generated/core/base/I18n.d.ts +2 -2
  350. package/types/generated/core/input/Input.d.ts +16 -2
  351. package/types/generated/core/input/inputSeat.d.ts +26 -0
  352. package/types/generated/core/inspect/DebugOverrides.d.ts +15 -1
  353. package/types/generated/core/ops/Ops.d.ts +2 -1
  354. package/types/generated/core/ops/control.d.ts +12 -2
  355. package/types/generated/core/saves/Saves.d.ts +26 -6
  356. package/types/generated/core/saves/session.d.ts +1 -1
  357. package/types/generated/core/scene/Views.d.ts +1 -1
  358. package/types/generated/core/stream/Stream.d.ts +6 -4
  359. package/types/generated/modules/grid/Grid.d.ts +1 -0
  360. package/types/generated/modules/particles/Particles.d.ts +4 -3
  361. package/types/generated/modules/timeline/Timeline.d.ts +5 -4
  362. package/types/generated/modules/weather/Weather.d.ts +1 -7
  363. package/types/generated/modules/world/World.d.ts +6 -4
  364. package/types/generated/render/PostFX.d.ts +6 -14
  365. package/types/nav.d.ts +36 -4
  366. package/types/physics.d.ts +55 -7
  367. package/types/pixel.d.ts +75 -0
  368. package/types/world.d.ts +14 -8
  369. package/ui/Parts.js +9 -2
  370. package/ui/theme.js +2 -2
  371. package/core/scene/engineCamera.js +0 -32
  372. package/modules/camera/projection.js +0 -21
@@ -4,6 +4,10 @@
4
4
  // sounds: freeing one needs no count. A playing voice holds its own buffer, so it plays on and the memory goes when it ends; the next play loads the file again
5
5
  // Plain functions that take the Assets instance, so they stay out of the class's public surface.
6
6
  //
7
+ // Who decides what a failed file means: the caller. An entry only says what it can fall back to, because it cannot know who asks: a prop on a gray box is a game that goes on, a level on a gray box
8
+ // is not a level. A caller that cannot use a stand-in waits with { whole: true } (Assets.wholeModel); e.fellBack is the failure the stand-in hides, and such a caller gets that instead, and tries the file
9
+ // again on its next ask. Internal on purpose: a game names `critical` for start(), and asks for a stand-in or not by what it does with the result.
10
+ //
7
11
  // Who owns what. An entry is a name; a load is one attempt at its data, and the load is what owns that data:
8
12
  // { owner, type, gameOwned, task, stop, value, users, settled, pinned }, reached as e.load.
9
13
  // - One rule for freed, replaced and disposed: whoever ends a load aborts `stop`; a result arriving for an aborted load is freed and never written
@@ -11,12 +15,16 @@
11
15
  // name moves on, and only the load knows which copies still hold its data.
12
16
  // - Each copy counts on the load its data came from, so a name that fell back to another (e.load is then the other entry's load, e.value stays null)
13
17
  // keeps that entry's data alive, and freeing the data sends every name reading it back to a fresh load.
14
- // - e.users is the count Assets._users reads: copies asked for by this name plus copies that borrow its data. load.users frees an old build.
18
+ // - e.users is the count Assets._users reads: leases (takeLease) asked for by this name plus leases that borrow its data; a model copy is one lease. load.users frees an old build.
15
19
  //
16
20
  // A caller already awaiting a load that was ended:
17
21
  // - release, trim, a palette write, a name registered again: the game is alive and asked for this asset, so the wait carries on with a fresh load
18
22
  // (release says "reloaded on next use", and a wait is a use). It gets a live value, or the failure of that fresh load. Why not reject: every
19
23
  // model() in the game would need a catch for a normal level change, and a rejected promise stays cached in the prototype tables.
24
+ // - the limit: a load that shows no sign of life for engine.loading.timeoutMs fails, by the path any failure takes (fallback, or asset-load). The limit sits on the load and not on each
25
+ // waiter, so every wait above it, a level, a pack, a preload, a save's part, ends by inheritance and none needs a timer of its own. Silence and not total time: a big file on a slow
26
+ // network that still arrives is not stuck.
27
+ // - leaving: a waiter with a signal (waitLoad) may stop waiting. When every waiter on a load has left, nobody wants it and it is aborted; a load shared with a waiter that stays goes on.
20
28
  // - assets.dispose: the promise stays pending for good. Why not reject or resolve null: `model(x).then(add)` with no catch would be an unhandled
21
29
  // rejection in teardown, and null would be a TypeError in the same place; the code after the await belongs to a disposed engine.
22
30
  import { warnOnce, fmt } from '../base/validate.js';
@@ -68,11 +76,11 @@ export function shadowDefaults(root, { castShadow, receiveShadow } = {}) {
68
76
  export function fetchEntry(a, e) {
69
77
  if (a._disposed) return NEVER;
70
78
  if (a._stale(e)) retireEntry(a, e);
71
- if (e.promise) return e.promise;
79
+ if (e.promise) { if (e.load) e.load.waits++; return e.promise; }
72
80
  e.palette = a._paletteKey;
73
81
  const L = a.engine.loading, name = e.variantOf ?? e.name ?? e.url;
74
82
  const t = L._begin(name, e.type, { critical: e.opts.critical === true, url: e.opts.build || e.opts.texture ? null : e.url, manifest: e.manifest ?? null });
75
- const load = e.load = { owner: e, type: e.type, gameOwned: !!e.opts.texture, task: t, stop: new AbortController(), value: null, users: 0, settled: false, pinned: false };
83
+ const load = e.load = { owner: e, type: e.type, gameOwned: !!e.opts.texture, task: t, stop: new AbortController(), value: null, users: 0, settled: false, pinned: false, waits: 1, left: false, stuck: false, whole: false };
76
84
  t.signal = load.stop.signal; // the loaders read it between phases, and a download passes it to fetch
77
85
  let work;
78
86
  if (e.type === 'model') {
@@ -83,9 +91,9 @@ export function fetchEntry(a, e) {
83
91
  else if (e.type === 'sound' && e.opts.build) work = Promise.resolve(e.opts.build); // a synth function: nothing to download
84
92
  else if (e.type === 'sound') work = loadAudio(a, e, t);
85
93
  // a._disposed too: an entry a hot swap dropped from the table is not reached by dispose, so its load was never aborted
86
- const ended = () => load.stop.signal.aborted || a._disposed;
87
- e.promise = work.then(v => {
88
- if (ended()) { freeValue(load, v); return fetchEntry(a, e); }
94
+ const ended = () => cancelled(load) || a._disposed;
95
+ e.promise = limited(a, load, work).then(v => {
96
+ if (ended()) { freeValue(load, v); return again(a, e, load); }
89
97
  L._done(t);
90
98
  const what = `${e.type} "${name}" <- ${e.url}`;
91
99
  if (t.missing.length) warnOnce(coded('asset-missing-ref', fmt(STRINGS.missingRefs, { what, list: t.missing.join(', ') })));
@@ -93,10 +101,52 @@ export function fetchEntry(a, e) {
93
101
  load.value = e.value = v;
94
102
  if (e.type === 'sound') capSounds(a, e);
95
103
  return v;
96
- }, err => (ended() ? fetchEntry(a, e) : failedEntry(a, e, load, err))); // a failure nobody wants any more is not reported
104
+ }, err => (ended() ? again(a, e, load) : failedEntry(a, e, load, err))); // a failure nobody wants any more is not reported
97
105
  return e.promise;
98
106
  }
99
107
 
108
+ /** A load ended under its waiters: they carry on with a fresh one (top of the file). Not when every waiter left: that is why it ended, and nobody is here to answer */
109
+ const again = (a, e, load) => load.left ? NEVER : fetchEntry(a, e);
110
+
111
+ /** Someone ended this load on purpose. A load stopped by its limit is aborted too, and that one failed: it takes the failure path */
112
+ const cancelled = load => load.stop.signal.aborted && !load.stuck;
113
+
114
+ /** The one limit on a load (top of the file). A build that ignores the abort may still answer: what it gives then is freed */
115
+ function limited(a, load, work) {
116
+ const t = load.task, L = a.engine.loading;
117
+ work.then(v => { if (load.stuck) freeValue(load, v); }, () => {});
118
+ return L._limit(work, () => cancelled(load) ? null : t.at, () => {
119
+ load.stuck = true;
120
+ queueMicrotask(() => load.stop.abort()); // after the failure below won the race, so a download that rejects on abort is not what the waiters hear
121
+ return new Error(`no answer for ${Math.round(L.timeoutMs / 1000)} s (engine.loading.timeoutMs)`);
122
+ });
123
+ }
124
+
125
+ /**
126
+ * The one wait on an entry that can say more than "give me what you have" (top of the file).
127
+ * @param {any} a the Assets instance
128
+ * @param {any} e
129
+ * @param {{ whole?: boolean, signal?: AbortSignal | null }} [o] whole: a stand-in is no answer; signal: this waiter may leave, rejecting with its reason
130
+ * @returns {Promise<any>}
131
+ * @internal
132
+ */
133
+ export function waitLoad(a, e, { whole = false, signal = null } = {}) {
134
+ if (whole && e.fellBack) retireEntry(a, e); // the last answer was a stand-in: this caller wants the file
135
+ const got = fetchEntry(a, e), load = e.load;
136
+ if (whole && load) load.whole = true;
137
+ if (!signal) return got;
138
+ return new Promise((res, rej) => {
139
+ const leave = () => {
140
+ rej(signal.reason);
141
+ if (load && --load.waits === 0 && !load.settled) { load.left = true; letGoAll(a, load); cancelLoad(a, load); }
142
+ };
143
+ if (signal.aborted) return leave();
144
+ signal.addEventListener('abort', leave, { once: true });
145
+ const stay = fn => v => { signal.removeEventListener('abort', leave); fn(v); };
146
+ got.then(stay(res), stay(rej));
147
+ });
148
+ }
149
+
100
150
  /** The fallback chain from e if it comes back to a name already on it (e -> ... -> e or into a ring), as names; null if it ends */
101
151
  function fallbackCycle(a, e) {
102
152
  const chain = [e.name ?? e.url];
@@ -115,13 +165,14 @@ function failedEntry(a, e, load, err) {
115
165
  e.promise = null;
116
166
  const degrade = e.named && !e.opts.build && !e.opts.critical;
117
167
  const fb = degrade ? (e.opts.fallback ?? (e.type === 'sound' ? 'silence' : e.type === 'font' ? 'the system font' : 'gray placeholder')) : null;
118
- a.engine.loading._fail(t, err, fb);
168
+ a.engine.loading._fail(t, err, load.whole ? null : fb); // whole: its caller says what the failure means, no stand-in is promised to the reader
119
169
  const msg = fmt(STRINGS.failed, { what: failureText(t) });
120
170
  const loop = degrade && e.opts.fallback ? fallbackCycle(a, e) : null;
121
171
  // A -> B -> A: each would wait for the other's fallback forever, so fail once and name the chain (the fix is in the manifest)
122
172
  if (loop) { e.load = null; throw codedError('asset-fallback-cycle', msg + fmt(STRINGS.cycle, { chain: loop.join(' -> ') })); }
123
173
  if (!degrade) { e.load = null; throw codedError('asset-load', msg); }
124
- warnOnce(coded('asset-load', msg + fmt(STRINGS.fellBack, { fallback: e.opts.fallback ? `"${fb}"` : fb })));
174
+ e.fellBack = codedError('asset-load', msg);
175
+ if (!load.whole) warnOnce(coded('asset-load', msg + fmt(STRINGS.fellBack, { fallback: e.opts.fallback ? `"${fb}"` : fb })));
125
176
  if (e.opts.fallback) return (e.promise = borrow(a, e, load, a._resolve(e.opts.fallback, e.type)));
126
177
  load.settled = true;
127
178
  load.value = e.value = e.type === 'model' ? shareModel(a, placeholder('model')) : placeholder(e.type);
@@ -130,21 +181,21 @@ function failedEntry(a, e, load, err) {
130
181
 
131
182
  /** e falls back to `from`: until `from` answers, e's own failed load stays the token a release ends; then e reads from's load, which owns the data */
132
183
  function borrow(a, e, load, from) {
133
- const ended = () => load.stop.signal.aborted;
184
+ const ended = () => cancelled(load);
134
185
  return fetchEntry(a, from).then(v => {
135
- if (ended()) return fetchEntry(a, e);
186
+ if (ended()) return again(a, e, load);
136
187
  if (from.load?.value !== v) { letGo(e); return fetchEntry(a, e); } // released between its load finishing and this line
137
188
  e.load = from.load;
138
189
  return v;
139
190
  }, err => {
140
- if (ended()) return fetchEntry(a, e);
191
+ if (ended()) return again(a, e, load);
141
192
  letGo(e); // not kept as a rejected promise: the next use tries again
142
193
  throw err;
143
194
  });
144
195
  }
145
196
 
146
197
  /** This name reads nothing now; its next use loads again */
147
- function letGo(e) { e.load = e.value = e.promise = null; }
198
+ function letGo(e) { e.load = e.value = e.promise = e.fellBack = null; }
148
199
  /** Every name reading this load, the owner and any that fell back to it, lets go of it */
149
200
  function letGoAll(a, load) { for (const x of a.entries.values()) if (x.load === load) letGo(x); }
150
201
 
@@ -182,7 +233,7 @@ export function freeEntry(a, e) {
182
233
 
183
234
  /**
184
235
  * The name moves on from its current load (a palette write, a new registration, tuned params): an unfinished load ends, and finished data goes as soon as
185
- * nothing holds it. Only models can be judged: copies are counted and geometry() pins. A texture is handed out uncounted, so a material may still show it: it
236
+ * nothing holds it. Only what is counted can be judged: copies and leases count and geometry() pins. A texture is handed out uncounted, so without a lease a material may still show it: it
186
237
  * is left to the game. Loads kept here wait in a._retired for their last copy, and for dispose
187
238
  */
188
239
  export function retireEntry(a, e) {
@@ -191,16 +242,30 @@ export function retireEntry(a, e) {
191
242
  if (load.owner !== e) { letGo(e); return; }
192
243
  letGoAll(a, load);
193
244
  if (!load.settled) cancelLoad(a, load);
194
- else if (load.type === 'model') { if (load.users > 0 || load.pinned) a._retired.add(load); else freeValue(load, load.value); }
245
+ else if (load.users > 0 || load.pinned) a._retired.add(load);
246
+ else if (load.type === 'model') freeValue(load, load.value);
195
247
  }
196
248
 
197
- /** One model copy went away (engine.remove): the argument is what Assets._copy recorded */
198
- export function dropCopy(a, { e, load }) {
199
- const owner = load.owner;
200
- load.users--; e.users--;
201
- if (owner !== e) owner.users--;
202
- if (load.users <= 0 && !load.pinned && a._retired.delete(load)) freeValue(load, load.value);
203
- if (owner.users <= 0 && owner.releasePending) freeEntry(a, owner);
249
+ /**
250
+ * The one count of who holds an entry's data: a model copy holds a lease (Assets._copy, ended by engine.remove), and assets.lease hands one to a module (content models). Why one count and not
251
+ * a lease table beside the copies: release, trim and a retired build would then have two answers to "is anybody using this". The handle is idempotent, so a module may
252
+ * end it itself and still have it tracked.
253
+ * @returns {{ name: string, remove(): void }}
254
+ */
255
+ export function takeLease(a, e, name = e.name) {
256
+ const load = e.load, owner = load.owner;
257
+ load.users++; e.users = (e.users || 0) + 1;
258
+ if (owner !== e) owner.users = (owner.users || 0) + 1;
259
+ e.releasePending = owner.releasePending = false;
260
+ let held = true;
261
+ return { name, remove() {
262
+ if (!held) return;
263
+ held = false;
264
+ load.users--; e.users--;
265
+ if (owner !== e) owner.users--;
266
+ if (load.users <= 0 && !load.pinned && a._retired.delete(load)) freeValue(load, load.value);
267
+ if (owner.users <= 0 && owner.releasePending) freeEntry(a, owner);
268
+ } };
204
269
  }
205
270
 
206
271
  /** e just loaded: while long sounds are over the budget, the one asked for longest ago goes (never e itself) */
@@ -11,6 +11,7 @@
11
11
  // the game built itself from a geometry is not found (only engine paths are).
12
12
  import { registerManifest, paramValues } from './assetManifest.js';
13
13
  import { protoCaches, protoOf, cachedModel } from './namedModel.js';
14
+ import { clone as skeletonClone } from 'three/addons/utils/SkeletonUtils.js';
14
15
  import { list } from '../base/util.js';
15
16
  import { reportError } from '../base/errors.js';
16
17
  import { codedError } from '../base/errorHints.js';
@@ -99,7 +100,7 @@ async function swapModels(e, changed, why = 'edit') {
99
100
  const neu = [...protoNew.values()].find(p => p.obj.userData.modelKey === ud.modelKey);
100
101
  if (neu) {
101
102
  for (const c of [...o.children]) if (meshesOf(c).some(m => oldGeo.has(m.geometry))) o.remove(c);
102
- for (const c of [...neu.obj.clone().children]) { o.add(c); count(list(JSON.parse(ud.modelKey))[0]); } // a copy: add() takes c out of the live list
103
+ for (const c of [...skeletonClone(neu.obj).children]) { o.add(c); count(list(JSON.parse(ud.modelKey))[0]); } // a copy: add() takes c out of the live list
103
104
  }
104
105
  }
105
106
  });
@@ -3,6 +3,7 @@
3
3
  // "Lost" means: the file has it, the scene does not (a normal map a material no longer has, a clip that did not load, a material replaced by another).
4
4
  // Color-space basis: three's color management manual. Color slots (map, emissiveMap) hold sRGB, data slots (normal, roughness, metalness, ao...) stay linear.
5
5
  import * as THREE from 'three';
6
+ import { sanitize } from '../base/spelling.js';
6
7
 
7
8
  // The one slot table: engine.assets.report and engine.inspect.materials judge a texture by it. A lightMap holds light, not a color or a value: a linear bake and an sRGB
8
9
  // picture are both right, so it is in neither list
@@ -10,8 +11,6 @@ export const COLOR_SLOTS = ['map', 'emissiveMap', 'specularColorMap', 'sheenColo
10
11
  export const DATA_SLOTS = ['normalMap', 'roughnessMap', 'metalnessMap', 'aoMap', 'bumpMap', 'alphaMap', 'displacementMap', 'specularMap', 'specularIntensityMap', 'clearcoatMap', 'clearcoatNormalMap',
11
12
  'clearcoatRoughnessMap', 'transmissionMap', 'thicknessMap', 'iridescenceMap', 'anisotropyMap', 'sheenRoughnessMap'];
12
13
  const SRGB = THREE.SRGBColorSpace, LINEAR = THREE.NoColorSpace;
13
- // three's PropertyBinding.sanitizeNodeName: the name the engine sees ("door.001" -> "door001")
14
- const sanitize = n => String(n ?? '').replace(/\s/g, '_').replace(/[[\].:/]/g, '');
15
14
 
16
15
  /** Color-space problems of one texture used in the given slots: [] when fine */
17
16
  function colorSpaceIssues(tex, slots) {
@@ -43,6 +43,8 @@ export class Audio {
43
43
  } });
44
44
  /** The game's current mode for rule lists, e.g. 'combat' / 'explore' (condition `state` in music and ambience rules) @type {string | null} */
45
45
  this.state = null;
46
+ // the mode belongs to the playthrough: a new game opens as the page did, a load in the mode it was saved in
47
+ engine.saves.register('audio', { notAtomic: 'sound, which an atomic op leaves alone: side effects go in after', save: () => ({ state: this.state }), load: d => { this.state = d.state ?? null; } });
46
48
  /** @internal */ this.conditions = new Map([['state', v => [].concat(v).includes(this.state)]]);
47
49
  /** @internal name -> (engine) => number: values rule data compares ({ daylight: { gt: 0.15 } }) and data volumes add up */
48
50
  this.measures = new Map();
@@ -57,12 +59,14 @@ export class Audio {
57
59
  /** @internal */ this._last = new Map(); // name -> { at, variant } (cooldown, no-repeat)
58
60
  /** @internal */ this._spatial = new Set(); // positional voices: the listener and followed objects update only while any exist
59
61
  /** @internal */ this._readySent = false;
60
- // Create or resume audio on the first click/keypress (a context created earlier is suspended and must be resumed inside a user gesture)
61
- const stop = new AbortController(), signal = AbortSignal.any([stop.signal, engine.signal]); // remove after unlocking once, or when the engine is disposed
62
- // given up only once it worked: a touch pointerdown or Escape is no activation for the browser, and the pointerup after it is
63
- const unlock = () => { this._init(); this.ctx?.resume().then(() => stop.abort(), () => {}); };
64
- for (const ev of ['pointerdown', 'pointerup', 'keydown']) addEventListener(ev, unlock, { signal });
62
+ /** @internal the game is held by the page (core/engine/page.js): the sound waits with it */ this._held = false;
63
+ // Create or resume audio on a click/keypress (a context created earlier is suspended and must be resumed inside a user gesture). Every press, not only the first:
64
+ // a touch pointerdown or Escape is no activation for the browser, and a phone suspends a running context on a call or an app switch
65
+ const unlock = () => { if (this._held) return; this._init(); if (this.ctx && this.ctx.state !== 'running') this.ctx.resume().catch(() => {}); };
66
+ for (const ev of ['pointerdown', 'pointerup', 'keydown']) addEventListener(ev, unlock, { signal: engine.signal });
65
67
  }
68
+ /** @internal page.js: the page froze the game, or let it go */
69
+ _hold(on) { this._held = on; if (this.ctx) (on ? this.ctx.suspend() : this.ctx.resume()).catch(() => {}); }
66
70
  /** @internal Close the audio context (engine.dispose calls it): playing sounds and nodes modules attached stop together */
67
71
  dispose() { this.ctx?.close(); this.ctx = null; }
68
72
 
@@ -212,6 +216,19 @@ export class Audio {
212
216
  this.packs.set(key, pack);
213
217
  for (const fn of this._packWatch) fn(key, pack);
214
218
  }
219
+ /**
220
+ * @internal A failed content load puts this pack back as it was (core/base/sections.js undo): the function that does it. Tracks music took stay defined, unnamed by any rule
221
+ * @param {any} key as contentPack @returns {() => void}
222
+ */
223
+ keepPack(key) {
224
+ const { sounds, footsteps } = this.config, was = [{ ...sounds }, { ...footsteps }], pack = this.packs.get(key);
225
+ return () => {
226
+ [sounds, footsteps].forEach((t, i) => { for (const k of Object.keys(t)) delete t[k]; Object.assign(t, was[i]); });
227
+ if (pack) this.packs.set(key, pack); else this.packs.delete(key);
228
+ const rules = pack ?? { from: '', ambience: [], music: { tracks: {}, rules: [] } };
229
+ for (const fn of this._packWatch) fn(key, rules);
230
+ };
231
+ }
215
232
  /** @internal ambience() / music() follow content packs' rules: fn(key, pack) per pack, now for each loaded one and later for new ones */
216
233
  onPack(fn) {
217
234
  for (const [k, p] of this.packs) fn(k, p);
@@ -275,3 +292,5 @@ export class Audio {
275
292
  */
276
293
  play(url, opts = {}) { return playFile(this, url, opts); }
277
294
  }
295
+
296
+ export const handRolled = [{ kind: 'audio', seen: 'an AudioContext / Audio element of its own', use: 'engine.audio: engine.audio.play(url, { bus, volume }) or named sounds, with buses and volume settings (recipe 31)', code: /\bnew\s+(?:window\.)?(?:AudioContext|webkitAudioContext)\b|\bnew\s+Audio\s*\(/ }];
package/core/base/I18n.js CHANGED
@@ -53,9 +53,10 @@ export class I18n {
53
53
  /** @internal @type {StringTables} */ this.tables = {};
54
54
  this.add(CORE);
55
55
  /** @internal Game-given text wins @type {StringTables} */ this.overrides = strings;
56
- /** Current language, e.g. 'zh-CN' ('zh' and 'zh-Hans' resolve to it, 'en-US' to 'en') @experimental */
57
- this.locale = resolveLocale(locale, this.languages);
56
+ /** @internal */ this._locale = resolveLocale(locale, this.languages);
58
57
  }
58
+ /** Current language, e.g. 'zh-CN' ('zh' and 'zh-Hans' resolve to it, 'en-US' to 'en'). Read-only: setLocale changes it, and tells i18n:change @returns {string} @experimental */
59
+ get locale() { return this._locale; }
59
60
  /**
60
61
  * Register string tables (never overrides text the game gave)
61
62
  * @param {StringTables} tables
@@ -64,7 +65,7 @@ export class I18n {
64
65
  */
65
66
  add(tables) { for (const lang in tables) this.tables[lang] = { ...this.tables[lang], ...tables[lang] }; return this; }
66
67
  /** Switch language ('auto' picks from the browser like createEngine) @param {string} l @experimental */
67
- setLocale(l) { this.locale = resolveLocale(l, this.languages); this.engine.events.emit('i18n:change', this.locale); }
68
+ setLocale(l) { this._locale = resolveLocale(l, this.languages); this.engine.events.emit('i18n:change', this._locale); }
68
69
  /** All available languages @returns {string[]} @experimental */
69
70
  get languages() { return [...new Set([...Object.keys(this.tables), ...Object.keys(this.overrides)])]; }
70
71
  /** Whether the key exists @param {string} key @returns {boolean} */
@@ -104,3 +105,5 @@ export class I18n {
104
105
  });
105
106
  }
106
107
  }
108
+
109
+ export const handRolled = [{ kind: 'language', seen: 'a language table of its own', use: 'engine.i18n: tables per language, the language setting, and text that follows a switch', quiet: /\b(engine|e|eng|ctx)\.i18n\b/, code: /\b(?:const|let|var)\s+(?:i18n|translations?|strings|locales?|languages?|lang|messages|texts?)\w*\s*=\s*\{/i, near: [{ re: /\b(?:en|zh|fr|de|es|ja|ko|ru)(?:[-_]\w+)?['"]?\s*:\s*[{'"`]/, lines: 3, on: 'raw' }] }];
@@ -9,7 +9,7 @@
9
9
  // Purely presentational randomness (particle jitter, bird-call pitch) does not use it: call Math.random() and tag the line // presentation (see packages/tools/rules/R04).
10
10
 
11
11
  import { mulberry32 } from './mulberry32.js'; // 32-bit state, plenty for gameplay
12
- import { saveValues } from '../saves/saveValues.js';
12
+ import { saveValues } from './saveValues.js';
13
13
 
14
14
  /** engine.random is the seeded random generator. Gameplay randomness (auto weather, lightning, drops, spawning) uses it so step / tests are reproducible and the state is saved with the save. */
15
15
  export class Random {
@@ -58,3 +58,5 @@ export class Random {
58
58
  v.done();
59
59
  }
60
60
  }
61
+
62
+ export const handRolled = [{ kind: 'random', seen: 'Math.random() in game code', use: 'engine.random (seeded: next / range / int / pick / chance; replays, tests and saves get the same numbers)', code: /\bMath\.random\s*\(/, notRaw: /particle|spark|dust|confetti|debris|twinkle|flicker|jitter|smoke|puff|droplet|bubble|petal|glitter|wobble/i, gameplayOnly: true }];
package/core/base/Vars.js CHANGED
@@ -4,16 +4,22 @@
4
4
  // Dialogue state.flags and quest counter/bump all point here. Writes go through the ops guard (dev): outside loading, fixed steps and ops they are reported. Loading replaces the contents in place; the flags / counters objects themselves stay the same.
5
5
 
6
6
  import { DEV } from './validate.js';
7
+ import { codedError } from './errorHints.js';
8
+ import { saveValues } from './saveValues.js';
7
9
 
8
10
  export class Vars {
9
11
  constructor(engine) {
10
12
  this.engine = engine;
11
- this.flags = {};
12
- this.counters = {};
13
+ this.flags = Object.create(null); // no prototype: a flag or counter named 'constructor' is unset like any other name
14
+ this.counters = Object.create(null);
13
15
  engine.saves.register('vars', {
14
16
  atomic: true,
15
17
  save: () => ({ flags: { ...this.flags }, counters: { ...this.counters } }), // copy: save data must not share objects with the live state
16
- load: d => { this.replace(d?.flags, d?.counters); },
18
+ load: d => {
19
+ const v = saveValues('vars'), counters = d?.counters && Object.fromEntries(Object.entries(d.counters).filter(([k, n]) => Number.isFinite(n) || (v.drop(`counters.${k}`, n), false)));
20
+ v.done();
21
+ this.replace(d?.flags, counters);
22
+ },
17
23
  });
18
24
  }
19
25
  /** Read a flag */
@@ -23,7 +29,11 @@ export class Vars {
23
29
  /** Read a counter (0 if absent) */
24
30
  counter(k) { return this.counters[k] ?? 0; }
25
31
  /** Add n to a counter (default 1) and return the new value */
26
- bump(k, n = 1) { DEV && this.engine.ops.guard('vars.bump'); return (this.counters[k] = this.counter(k) + n); }
32
+ bump(k, n = 1) {
33
+ DEV && this.engine.ops.guard('vars.bump');
34
+ if (!Number.isFinite(n)) throw codedError('engine-misuse', `vars.bump('${k}', n): n must be a finite number, got ${String(n)}`);
35
+ return (this.counters[k] = this.counter(k) + n);
36
+ }
27
37
  /** @internal Replace wholesale (for loading and net sync); a kind passed as undefined stays unchanged */
28
38
  replace(flags, counters) {
29
39
  DEV && this.engine.ops.guard('vars.replace');
@@ -7,13 +7,14 @@
7
7
 
8
8
  /**
9
9
  * Errors the engine raises by name (the message ends with "[code]"): code -> { fix, docs }. Codes are stable: tools and tests may match on them.
10
- * @type {Record<string, { fix: string, docs: string[] }>}
10
+ * brief: a hint that stays one line on the console, because its message already says where the rest is; err.fix and errorInfo still give it.
11
+ * @type {Record<string, { fix: string, docs: string[], brief?: boolean }>}
11
12
  */
12
13
  export const ERROR_CODES = {
13
14
  'save-part-threw': {
14
15
  docs: ['recipes/20-content-actions-save.md', 'api/saves.md'],
15
- fix: 'A save part\'s save() threw, so nothing was written and the previous save is kept. Fix the save() named in the message ' +
16
- '(it must return plain data).' },
16
+ fix: 'A save part\'s save() threw or returned what a save cannot hold, so nothing was written and the previous save is kept. Fix the save() named in the message ' +
17
+ '(it must return plain data; NaN and Infinity at any depth count, and the message gives the path).' },
17
18
  'save-load-threw': {
18
19
  docs: ['recipes/20-content-actions-save.md', 'api/saves.md'],
19
20
  fix: 'A save part\'s load() threw, so the game was rolled back to how it was before the load. Fix the load() named in the ' +
@@ -30,6 +31,16 @@ export const ERROR_CODES = {
30
31
  docs: ['recipes/20-content-actions-save.md', 'api/saves.md'],
31
32
  fix: 'Import only text or files made by saves.export / exportFile; attachments must be data: URLs. Nothing was fetched or ' +
32
33
  'changed.' },
34
+ 'save-key-taken': {
35
+ docs: ['recipes/20-content-actions-save.md', 'api/saves.md'],
36
+ fix: 'One owner per save key: pick another key, or call remove() on the handle of the first saves.register before registering again.' },
37
+ 'save-busy': {
38
+ docs: ['recipes/20-content-actions-save.md', 'api/saves.md'],
39
+ fix: 'Wait for the load to end (await it) before collecting. engine.saves.save waits by itself.' },
40
+ 'save-nested': {
41
+ docs: ['recipes/20-content-actions-save.md', 'api/saves.md'],
42
+ fix: "Something waits behind a state replacement that has not ended; with no sign of life for loading.timeoutMs it fails with this code. If a save part's load() or a module's afterLoad awaits it, it waits for itself: pass the turn they are given to " +
43
+ 'level.load / content.load ({ turn }). A new saves.apply / load / save or session.newGame / load / quit starts after the running one: do not await it there, or ask from a save:loaded or session:start listener.' },
33
44
  'save-autosave': {
34
45
  docs: ['recipes/20-content-actions-save.md', 'api/saves.md'],
35
46
  fix: 'saves.autosave(minutes) takes a positive number of minutes of play.' },
@@ -64,11 +75,13 @@ export const ERROR_CODES = {
64
75
  'is both a condition and a measure. Keep each name in one place.' },
65
76
  'engine-disposed': {
66
77
  docs: ['api/engine.md'],
67
- fix: 'engine.dispose() ran while start() was still loading, so start() stopped. Create a new engine instead of starting a ' +
68
- 'disposed one.' },
78
+ fix: 'engine.dispose() ran, so start() stopped or refused to run. Create a new engine instead of starting a disposed one.' },
69
79
  'skip-amount': {
70
80
  docs: ['recipes/06-clock-events.md', 'api/engine.md'],
71
81
  fix: 'engine.skip takes { to: \'06:00\' } (needs the calendar module) or { seconds: 600 } (calendar seconds, > 0).' },
82
+ 'skip-busy': {
83
+ docs: ['recipes/06-clock-events.md', 'api/engine.md'],
84
+ fix: 'Await the skip that is running (engine.skip returns its Promise), then call engine.skip again.' },
72
85
  'stream-timeout': {
73
86
  docs: ['recipes/18-world.md', 'api/stream.md'],
74
87
  fix: 'The teleport destination did not finish loading in time (terrain, colliders, nearby models). Read describe().loading or ' +
@@ -76,7 +89,7 @@ export const ERROR_CODES = {
76
89
  'stream-removed': {
77
90
  docs: ['recipes/18-world.md', 'api/stream.md'],
78
91
  fix: 'A stream source was removed (remove(), its until, or engine.dispose) before it was ready, so its whenReady rejects. Await ' +
79
- 'whenReady only on a source you keep.' },
92
+ 'whenReady only on a source you keep. stream.teleport also rejects with it when a new game or a load replaced the state during the trip: start the trip again from the new state if it is still wanted.' },
80
93
  'stream-option': {
81
94
  docs: ['recipes/18-world.md', 'api/stream.md'],
82
95
  fix: 'stream.source(position, { detail }) takes \'full\' or \'simple\'; stream.radius takes a finite number of meters or null.' },
@@ -92,10 +105,10 @@ export const ERROR_CODES = {
92
105
  fix: "engine.mod(point, { owner, set | add | mul | clamp, layer?, for?, clock?, id? }): owner is a non-empty string, exactly one of set / add / mul / clamp for a number (set for a value point); in a module ctx.mod(point, { mul }) names the module itself. haltLoop / freeze / takeCamera / debug.view name their owner the same way. Only that owner ends it, with the handle's remove()." },
93
106
  'shared-conflict': {
94
107
  docs: ['recipes/55-mods-time-wrap.md'],
95
- fix: "Two owners set one shared value on the same layer, so nothing says which one decides (dev builds throw; release builds let the later write win and warn once). Copy one fix from the message: contribute instead (mul / add), decide on another layer ({ layer }), or take it over on purpose (manual, or a set on the system layer)." },
108
+ fix: "Two owners set one shared value on the same layer, so nothing says which one decides (every build throws; the first value stays). Copy one fix from the message: contribute instead (mul / add), decide on another layer ({ layer }), or take it over on purpose (manual, or a set on the system layer)." },
96
109
  'shared-taken': {
97
110
  docs: ['recipes/55-mods-time-wrap.md', 'recipes/14-custom-module.md'],
98
- fix: "Two modules provide the same exclusive slot (provides: ['inventory']). Install only one, or swap: engine.use(mine(), { replaces: 'inventory' }) unloads the holder and its changes." },
111
+ fix: "Two modules provide the same exclusive slot (provides: ['inventory']; terrain and level both hold 'ground'). Install only one, or swap: engine.use(mine(), { replaces: 'inventory' }) unloads the holder and its changes. Terrain and level together: give both { part: true } and add compositeGround({ parts })." },
99
112
  'shared-settings': {
100
113
  docs: ['recipes/55-mods-time-wrap.md'],
101
114
  fix: "The settings layer only restricts what the scene chose: clamp or mul on a number, set: false on a value point. It cannot switch something on or raise it; leave the setting out to allow the scene's value." },
@@ -146,6 +159,10 @@ export const ERROR_CODES = {
146
159
  docs: ['recipes/15-perf.md', 'api/jobs.md'],
147
160
  fix: 'A job step ran too long or a job queued too many steps. Yield more often inside the generator (engine.jobs.add(function* ' +
148
161
  '() { ...; yield; })).' },
162
+ 'jobs-endless': {
163
+ docs: ['api/jobs.md'],
164
+ fix: 'A job with apply reached its due tick and engine.jobs.maxSteps steps were not enough to finish it, so its promise rejected and apply did not run. ' +
165
+ 'A generator that loops forever needs an end; one that is only long needs a later lag or a higher engine.jobs.maxSteps.' },
149
166
  'threads-crash': {
150
167
  docs: ['recipes/15-perf.md', 'api/engine.md'],
151
168
  fix: 'A worker failed or went silent past the lane timeout (the reason is printed with it); the lane now runs on the main thread with the same ' +
@@ -157,6 +174,9 @@ export const ERROR_CODES = {
157
174
  docs: ['recipes/58-input.md', 'api/input.md'],
158
175
  fix: 'Two owners declared one action in different input contexts. An action belongs to one context: rename one of them, or declare both in ' +
159
176
  'the same context (then they share the action).' },
177
+ 'input-seat': {
178
+ docs: ['recipes/58-input.md', 'api/input.md'],
179
+ fix: 'A seat owns its pad and keys alone. Give each seat its own pad index and keys, or remove() the seat that holds them; one seat drives one player.' },
160
180
  'input-unbound': {
161
181
  docs: ['recipes/58-input.md', 'api/input.md'],
162
182
  fix: "An action a module needs is read but no key is bound, so it never fires. Modules bind no keys: bind it with " +
@@ -188,8 +208,12 @@ export const ERROR_CODES = {
188
208
  'stage). Give both modules the same stage, or remove the before / after.' },
189
209
  'module-critical': {
190
210
  docs: ['recipes/14-custom-module.md', 'api/engine.md'],
191
- fix: 'A module declared critical: true failed in init(), so start() stopped instead of starting a broken game. The message names the module ' +
192
- 'and the reason: fix its init(), or drop critical if the game can run without it.' },
211
+ fix: 'A module declared critical: true failed in init(), or a provider it requires failed, so start() stopped instead of starting a broken game. The message names the module ' +
212
+ 'and the reason: fix that init(), or drop critical if the game can run without it.' },
213
+ 'module-contract': {
214
+ docs: ['recipes/14-custom-module.md', 'recipes/49-game-module-contract.md'],
215
+ fix: "A module provides (or another module requires) a capability the engine has a contract for, and its API lacks methods or fields that contract lists. Add them, or accept the risk " +
216
+ "if your game calls none of them: the module still runs. The behavior half of the contract is checked by runContract from @threedog/tools/contract." },
193
217
  'module-not-ready': {
194
218
  docs: ['recipes/14-custom-module.md', 'api/engine.md'],
195
219
  fix: 'start() waited longer than engine.loading.timeoutMs for modules whose isReady(e) stays false. Fix what that module waits for, ' +
@@ -207,8 +231,8 @@ export const ERROR_CODES = {
207
231
  "takes control: engine.control.take(player, { owner, layer: 'script', step })." },
208
232
  'control-conflict': {
209
233
  docs: ['recipes/57-control.md'],
210
- fix: "Two owners want the same character on the same control layer, so nothing says which one steers (dev builds throw; release builds let " +
211
- "the later one take it). End the old one first (its handle.remove()), or take another layer: base < script < cutscene (higher pauses lower)." },
234
+ fix: "Two owners want the same character on the same control layer, so nothing says which one steers, and the first keeps it (every build). " +
235
+ "End the old one first (its handle.remove()), or take another layer: base < script < cutscene (higher pauses lower)." },
212
236
  'control-net': {
213
237
  docs: ['recipes/57-control.md', 'recipes/27-net.md'],
214
238
  fix: "That character is driven by another machine (net holds its control for good). Change it where it is driven: run an op the host runs " +
@@ -264,6 +288,9 @@ export const ERROR_CODES = {
264
288
  'engine-misuse': {
265
289
  docs: ['api/engine.md'],
266
290
  fix: 'An engine call got an argument it cannot use; the message names the call and the accepted forms.' },
291
+ 'pixel-conflict': {
292
+ docs: ['recipes/62-picture-code.md', 'api/engine.md'],
293
+ fix: 'pixelSize decides the render resolution, and a camera\'s pixelSnap its view height, while they are on; something else asked for it too. The message names both: keep one, or turn it off first (engine.setPixelSize(null), or drop pixelSnap).' },
267
294
  'many-lights': {
268
295
  docs: ['recipes/09-materials-lights-models.md', 'api/lightPool.md'],
269
296
  fix: "Too many real-time lights are in the scene (the message has the count). Use engine.use(lightPool({ point: 8 })) and register torches / lamps with engine.lightPool.add(...), so a fixed small set of real lights follows the nearest sources." },
@@ -333,7 +360,7 @@ export const ERROR_CODES = {
333
360
  fix: 'An ambience rule names no sound: give sound: a name registered in audio.sounds.' },
334
361
  'camera-option': {
335
362
  docs: ['recipes/21-camera.md', 'api/cameraRig.md'],
336
- fix: 'A camera option is wrong: projection is \'perspective\' or \'orthographic\' (orthographic needs size > 0 and engine.camera), ' +
363
+ fix: 'A camera option is wrong: projection is \'perspective\' or \'orthographic\' (orthographic needs size > 0 and an EngineCamera or a real OrthographicCamera), engine.camera takes a THREE.PerspectiveCamera or THREE.OrthographicCamera, ' +
337
364
  'ground / shots use the values the message lists.' },
338
365
  'character-option': {
339
366
  docs: ['api/characters.md', 'recipes/13-animation.md', 'recipes/02-npc.md'],
@@ -379,6 +406,9 @@ export const ERROR_CODES = {
379
406
  'rigid-misuse': {
380
407
  docs: ['recipes/11-vehicles.md', 'api/rigid.md'],
381
408
  fix: "The message says which: an id already used by another body or vehicle (give each its own id); joints lost when newGame / a load rebuilt the physics world (re-create them in a rigid:rebuilt listener, recipe 11 section 3 \"Joints\"); rigid.ragdoll() got something it cannot drive (a skinned character out of its vehicle, with the bones named when they cannot be read); or a moving body left the terrain colliders and froze (raise rigid({ terrainRing }) if it must keep moving there, recipe 11 section 3)." },
409
+ 'settings-row': {
410
+ docs: ['api/settings.md'],
411
+ fix: 'settings.set() names a key no row owns, so nothing would apply it. Use a listed key, add the tab that has the row (settings({ sections })) or define the row: settings.define(key, default, apply).' },
382
412
  'settings-tab': {
383
413
  docs: ['api/settings.md'],
384
414
  fix: 'settings({ tabs }) names a built-in tab that does not exist. Use a listed built-in name, or define your own section.' },
@@ -452,6 +482,13 @@ export const ERROR_CODES = {
452
482
  docs: ['recipes/12-navmesh.md', 'api/nav.md'],
453
483
  fix: 'The navmesh could not be built from this geometry; paths fall back. The message has the builder\'s reason (usually too few ' +
454
484
  'walkable triangles or wrong cell sizes).' },
485
+ 'nav-link': {
486
+ docs: ['recipes/12-navmesh.md', 'api/nav.md'],
487
+ fix: 'A nav link needs both ends within its radius of the mesh (which stops about the agent radius short of every edge) and within maxClimb of its height, and the places ' +
488
+ 'where they meet the mesh in the same tile or neighbouring tiles (a tile is tileSize x cellSize meters). Move the end onto walkable ground, raise radius, split a long link in two, or raise tileSize.' },
489
+ 'nav-height': {
490
+ docs: ['recipes/12-navmesh.md', 'api/nav.md'],
491
+ fix: 'A height given to a path or a stop is more than a body height from every walkable surface at that spot, so the nearest surface was used. Leave y out to mean the ground, or give the height of the floor you mean.' },
455
492
  'grid-overlap': {
456
493
  docs: ['recipes/29-grid.md', 'api/grids.md'],
457
494
  fix: 'Two grid items claim the same cell; the second is skipped. Move one, or remove the other first.' },
@@ -466,7 +503,7 @@ export const ERROR_CODES = {
466
503
  fix: "provides is a list of exclusive slot names (provides: ['inventory']); a slot name must not be a shared value's name." },
467
504
  'module-replaces': {
468
505
  docs: ['recipes/14-custom-module.md'],
469
- fix: "engine.use(mine(), { replaces: 'slot' }): an installed module must hold the slot, a module in the same call must provide it, and no other module may require the old one by its module name (require the slot)." },
506
+ fix: "engine.use(mine(), { replaces: 'slot' }): an installed module must hold the slot, a module in the same call must provide it, and no other module may require the old one by its module name (require the slot). The world holds every record, so it is never replaced under modules that use it or after start(): install your world before the modules that need it." },
470
507
  'module-cycle': {
471
508
  docs: ['recipes/14-custom-module.md'],
472
509
  fix: 'before / after constraints of two or more modules point at each other. Remove one of them or give a module a different stage.' },
@@ -484,7 +521,7 @@ export const ERROR_CODES = {
484
521
  fix: 'The module name becomes engine.<name>; it must not be an existing engine property or another module name.' },
485
522
  'module-handle': {
486
523
  docs: ['recipes/14-custom-module.md', 'api/engine.md'],
487
- fix: "ctx.track(handle) (the ctx install / init receive) and engine.session.track(handle) take something with remove(), such as the result of events.on / onFixed / clock.after. A handle tracked after its module was unloaded (an async init resuming after replaces / unload) is removed at once: check what the init does after its await." },
524
+ fix: "ctx.track(handle) (the ctx install / init receive) and engine.session.track(handle) take something with remove(), such as the result of events.on / onFixed / clock.after; ctx.borrow(obj, values) takes two objects, and one property has one holder at a time: end the first borrow, or use a shared point (engine.mod) when several parties want the value. A handle tracked after its module was unloaded (an async init resuming after replaces / unload) is removed at once: check what the init does after its await." },
488
525
  'module-called': {
489
526
  docs: ['recipes/01-new-game.md', 'api/engine.md'],
490
527
  fix: 'engine.use() takes the module object: write engine.use(sky()), not engine.use(sky).' },
@@ -559,8 +596,9 @@ export const ERROR_CODES = {
559
596
  docs: ['recipes/14-custom-module.md'],
560
597
  fix: "engine.unuse(name): the module must be installed, and no other module may still require it or a slot only it provides. Unload the dependent first, or swap the provider with engine.use(mine(), { replaces: 'slot' })." },
561
598
  'picture-conflict': {
599
+ brief: true,
562
600
  docs: ['recipes/62-picture-code.md'],
563
- fix: 'Two places change this picture value inside one frame, so the earlier write never shows. Pick the one that owns the value and delete the other, or turn the second into a signal the owner reads (recipes/62-picture-code.md "Wiring picture/ parts"). Both lines are in the message.' },
601
+ fix: 'Two places write this value, so one write never shows. Pick the one that owns the value and delete the other, or turn the second into a signal the owner reads (recipes/62-picture-code.md "Wiring picture/ parts"). Both lines are in the message.' },
564
602
  'camera-kind': {
565
603
  docs: ['recipes/21-camera.md', 'api/cameraRig.md'],
566
604
  fix: 'setCamera() got an unknown camera kind. Use one of the listed kinds; for a camera of your own, take it with engine.takeCamera(owner) and place engine.camera yourself (recipes/21-camera.md).' },
@@ -40,6 +40,17 @@ export const ERROR_HINTS = [
40
40
  'three.js BufferGeometryUtils.mergeGeometries returns null when the geometries have different attributes and logs which one in the ' +
41
41
  'console just before). Check the stack for the line and what produced the value.',
42
42
  docs: ['THREE.md', 'recipes/16-dev-bridge.md'] },
43
+ // A guessed pause method (the engine has one answer: engine.freeze; `threedog check` asks this entry too, tools/types.mjs)
44
+ { id: 'fall-prevent', match: /\bpreventDefault is not a function/,
45
+ cause: "The character:fall event can no longer be cancelled: falling is the rule 'fall'. To leave a fall to the game: engine.mod('fall', { owner: 'game', id: 'player', set: false }).",
46
+ docs: ['MIGRATING-1.0.md', 'recipes/55-mods-time-wrap.md'] },
47
+ { id: 'thing-explain', match: /\.explain is not a function/,
48
+ cause: 'engine.explain is the one way to ask why: what engine.thing(id).explain() gave is engine.explain({ thing: id }).detail.',
49
+ docs: ['MIGRATING-1.0.md', 'recipes/40-scene.md'] },
50
+ { id: 'pause-guess', match: /\b(?:time\.(?:pause|stop|resume)|engine\.(?:pause|resume|stop)) is not a function/,
51
+ cause: 'The engine has no pause method of that name. To pause the world call engine.freeze(owner): it returns the handle that releases it ' +
52
+ '(handle.release()); settings({ freezeWorld: true }) does it for a menu.',
53
+ docs: ['recipes/07-flow-scenes-pause.md', 'api/engine.md'] },
43
54
  { id: 'not-function', match: /[\w$.]+ is not a function/,
44
55
  cause: 'The method name is wrong, or the module is not installed (the property is then undefined). Check spelling against api/<module>.md.',
45
56
  docs: ['api/engine.md', 'CODEMAP.md'] },
@@ -98,6 +109,6 @@ export function coded(code, message) { return `${message} [${code}]`; }
98
109
  /** Indented lines "Code" (when the message has no [code] tag) + "Possible cause" + "Read"; '' if no hint matches. @param {unknown} message */
99
110
  export function hintText(message) {
100
111
  const h = hintFor(message);
101
- if (!h) return '';
112
+ if (!h || ERROR_CODES[h.id]?.brief) return '';
102
113
  return (tagOf(String(message)) ? '' : `\n Code: ${h.id}`) + `\n Possible cause: ${h.cause}\n Read: ${h.docs.join(', ')}`;
103
114
  }