threedog 1.1.0 → 1.2.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 (363) hide show
  1. package/CHANGELOG.md +879 -798
  2. package/README.md +1 -1
  3. package/core/assets/Animator.js +41 -3
  4. package/core/assets/Assets.js +100 -24
  5. package/core/assets/assetEntry.js +73 -20
  6. package/core/assets/assetHot.js +68 -16
  7. package/core/assets/assetLoad.js +6 -6
  8. package/core/assets/assetLod.js +9 -2
  9. package/core/assets/assetManifest.js +12 -2
  10. package/core/assets/assetPart.js +54 -0
  11. package/core/assets/ik.js +271 -0
  12. package/core/assets/modelNeeds.js +37 -0
  13. package/core/assets/namedModel.js +102 -29
  14. package/core/assets/nodeVisibility.js +15 -0
  15. package/core/audio/Audio.js +36 -4
  16. package/core/audio/audioReverb.js +99 -0
  17. package/core/audio/audioRules.js +1 -1
  18. package/core/audio/audioVoice.js +1 -1
  19. package/core/base/Events.js +14 -4
  20. package/core/base/Random.js +1 -1
  21. package/core/base/Vars.js +1 -1
  22. package/core/base/docRef.js +51 -0
  23. package/core/base/errorCodes.js +178 -126
  24. package/core/base/errorHints.js +9 -7
  25. package/core/base/errors.js +25 -10
  26. package/core/base/events.generated.js +2 -0
  27. package/core/base/freeParts.js +76 -0
  28. package/core/base/math.js +28 -0
  29. package/core/base/sections.js +5 -5
  30. package/core/base/validate.js +31 -3
  31. package/core/engine/Engine.js +16 -6
  32. package/core/engine/Loading.js +5 -3
  33. package/core/engine/copies.js +1 -1
  34. package/core/engine/headlessLoad.js +4 -1
  35. package/core/engine/lifecycle.js +32 -16
  36. package/core/engine/loop.js +71 -27
  37. package/core/engine/moduleSlots.js +2 -2
  38. package/core/engine/moduleTypes.js +3 -3
  39. package/core/engine/modules.js +65 -39
  40. package/core/engine/page.js +6 -3
  41. package/core/engine/services.js +6 -5
  42. package/core/engine/startup.js +5 -5
  43. package/core/input/Input.js +28 -14
  44. package/core/input/inputContext.js +28 -16
  45. package/core/input/inputKeyboard.js +31 -3
  46. package/core/input/inputPad.js +4 -0
  47. package/core/input/inputPointer.js +2 -1
  48. package/core/input/inputSeat.js +1 -1
  49. package/core/inspect/Budget.js +109 -19
  50. package/core/inspect/DebugOverrides.js +28 -4
  51. package/core/inspect/Describe.js +17 -9
  52. package/core/inspect/Inspect.js +4 -2
  53. package/core/inspect/InspectMaterials.js +3 -1
  54. package/core/inspect/InspectPerf.js +19 -9
  55. package/core/inspect/InspectScene.js +32 -7
  56. package/core/inspect/MaterialInfo.js +19 -2
  57. package/core/inspect/UrlState.js +46 -27
  58. package/core/inspect/catalog.js +28 -9
  59. package/core/inspect/debugView.js +2 -1
  60. package/core/inspect/describeRender.js +25 -13
  61. package/core/inspect/describeText.js +14 -6
  62. package/core/inspect/lightWatch.js +1 -1
  63. package/core/inspect/metadata.generated.js +35 -17
  64. package/core/inspect/pictureChecks.js +148 -0
  65. package/core/inspect/pictureMenu.js +84 -0
  66. package/core/inspect/pictureWriters.js +26 -6
  67. package/core/inspect/textureBytes.js +12 -2
  68. package/core/inspect/toolDoor.js +2 -4
  69. package/core/ops/Ops.js +11 -4
  70. package/core/ops/holds.js +27 -10
  71. package/core/ops/opsAtomic.js +15 -7
  72. package/core/ops/opsGuard.js +2 -2
  73. package/core/ops/opsRun.js +8 -7
  74. package/core/ops/sharedPoint.js +72 -21
  75. package/core/ops/stacks.js +56 -16
  76. package/core/saves/SaveStore.js +9 -3
  77. package/core/saves/Saves.js +32 -23
  78. package/core/saves/saveApply.js +96 -44
  79. package/core/saves/saveIds.js +1 -1
  80. package/core/saves/saveVersions.js +7 -5
  81. package/core/saves/session.js +17 -8
  82. package/core/saves/stateReplace.js +34 -15
  83. package/core/scene/Rays.js +52 -10
  84. package/core/scene/Views.js +13 -7
  85. package/core/scene/adaptive.js +144 -21
  86. package/core/scene/drawOnly.js +17 -0
  87. package/core/scene/gameLights.js +44 -3
  88. package/core/scene/sceneMethods.js +13 -11
  89. package/core/scene/stepPoses.js +11 -3
  90. package/core/scene/targeting.js +5 -3
  91. package/core/scene/thingOps.js +1 -1
  92. package/core/scene/tier.js +15 -0
  93. package/core/stream/Batching.js +30 -7
  94. package/core/stream/Stream.js +26 -7
  95. package/core/stream/batchGroups.js +2 -2
  96. package/core/stream/chunkStream.js +7 -5
  97. package/core/stream/prepare.js +77 -0
  98. package/core/time/skip.js +3 -1
  99. package/core/time/time.js +4 -2
  100. package/docs/AI.md +82 -83
  101. package/docs/API.md +16 -16
  102. package/docs/CODEMAP.md +16 -11
  103. package/docs/COMMANDS.md +139 -142
  104. package/docs/CONVENTIONS.md +37 -49
  105. package/docs/MIGRATING-0.8.md +2 -2
  106. package/docs/MIGRATING-1.0.md +2 -2
  107. package/docs/THREE.md +28 -35
  108. package/docs/api/assets.md +3 -1
  109. package/docs/api/audio.md +4 -2
  110. package/docs/api/budget.md +5 -0
  111. package/docs/api/characters.md +10 -8
  112. package/docs/api/collision.md +6 -4
  113. package/docs/api/engine.md +16 -16
  114. package/docs/api/events.md +3 -2
  115. package/docs/api/ground.md +6 -5
  116. package/docs/api/hud.md +4 -2
  117. package/docs/api/input.md +5 -5
  118. package/docs/api/particles.md +2 -1
  119. package/docs/api/photo.md +3 -0
  120. package/docs/api/post.md +7 -4
  121. package/docs/api/quests.md +2 -2
  122. package/docs/api/rays.md +1 -2
  123. package/docs/api/saves.md +7 -7
  124. package/docs/api/settings.md +2 -2
  125. package/docs/api/tools.md +3 -1
  126. package/docs/api/vars.md +1 -1
  127. package/docs/api/vegetation.md +4 -2
  128. package/docs/api/world.md +1 -1
  129. package/docs/recipes/01-new-game.md +16 -17
  130. package/docs/recipes/02-npc.md +22 -18
  131. package/docs/recipes/03-items-pickups.md +37 -35
  132. package/docs/recipes/04-quests.md +15 -10
  133. package/docs/recipes/05-props-bake.md +101 -95
  134. package/docs/recipes/06-clock-events.md +28 -28
  135. package/docs/recipes/07-flow-scenes-pause.md +29 -26
  136. package/docs/recipes/08-weather-sky.md +52 -64
  137. package/docs/recipes/09-materials-lights-models.md +26 -17
  138. package/docs/recipes/10-blender-level.md +15 -10
  139. package/docs/recipes/11-vehicles.md +12 -7
  140. package/docs/recipes/12-navmesh.md +44 -26
  141. package/docs/recipes/13-animation.md +56 -45
  142. package/docs/recipes/14-custom-module.md +21 -18
  143. package/docs/recipes/15-perf.md +61 -55
  144. package/docs/recipes/16-dev-bridge.md +23 -33
  145. package/docs/recipes/18-world.md +36 -42
  146. package/docs/recipes/19-shooting-picking.md +20 -15
  147. package/docs/recipes/20-content-actions-save.md +48 -56
  148. package/docs/recipes/21-camera.md +45 -54
  149. package/docs/recipes/22-shop-gold.md +12 -7
  150. package/docs/recipes/23-ops.md +25 -23
  151. package/docs/recipes/26-ui-parts.md +67 -47
  152. package/docs/recipes/27-net.md +12 -7
  153. package/docs/recipes/28-terrain.md +24 -21
  154. package/docs/recipes/29-grid.md +32 -27
  155. package/docs/recipes/30-templates.md +21 -20
  156. package/docs/recipes/31-audio.md +39 -22
  157. package/docs/recipes/32-action-game.md +19 -14
  158. package/docs/recipes/33-stream-sources.md +15 -11
  159. package/docs/recipes/34-environment-lighting.md +126 -70
  160. package/docs/recipes/35-picture-from-reference.md +8 -8
  161. package/docs/recipes/36-ground-plants.md +27 -21
  162. package/docs/recipes/40-scene.md +19 -28
  163. package/docs/recipes/43-shader-patches-surfaces.md +15 -12
  164. package/docs/recipes/44-water-weather-hooks.md +34 -31
  165. package/docs/recipes/45-cascaded-shadows.md +35 -26
  166. package/docs/recipes/46-blender-art-route.md +6 -1
  167. package/docs/recipes/49-game-module-contract.md +13 -8
  168. package/docs/recipes/50-own-renderer.md +6 -2
  169. package/docs/recipes/51-capability-catalog.md +15 -8
  170. package/docs/recipes/52-around-the-picture.md +34 -32
  171. package/docs/recipes/53-ground-up-close.md +6 -1
  172. package/docs/recipes/55-mods-time-wrap.md +27 -19
  173. package/docs/recipes/56-webgpu-tsl.md +74 -43
  174. package/docs/recipes/57-control.md +18 -13
  175. package/docs/recipes/58-input.md +26 -16
  176. package/docs/recipes/59-depth-post-effects.md +8 -3
  177. package/docs/recipes/60-judge-the-picture.md +9 -8
  178. package/docs/recipes/61-deploy.md +5 -0
  179. package/docs/recipes/62-picture-code.md +70 -79
  180. package/docs/recipes/63-third-person-start.md +47 -45
  181. package/docs/recipes/64-particles.md +22 -10
  182. package/docs/recipes/65-swarm.md +18 -13
  183. package/docs/recipes/66-common-tasks.md +38 -35
  184. package/examples/action/GAMEMAP.md +2 -3
  185. package/examples/action/main.js +3 -3
  186. package/examples/action/picture/lights.js +3 -1
  187. package/examples/perf-island/GAMEMAP.md +3 -3
  188. package/examples/perf-island/picture/lights.js +2 -1
  189. package/examples/plain-picture/GAMEMAP.md +1 -1
  190. package/examples/rc2d/GAMEMAP.md +1 -1
  191. package/examples/styletest/GAMEMAP.md +2 -2
  192. package/examples/styletest/main.js +1 -1
  193. package/examples/techniques/interior-light/README.md +3 -3
  194. package/examples/techniques/interior-light/interiorLight.js +2 -4
  195. package/examples/techniques/interior-light/picture/lights.js +2 -1
  196. package/examples/techniques/modular-building/picture/lights.js +3 -1
  197. package/examples/techniques/outlines-and-rim/picture/lights.js +3 -1
  198. package/examples/techniques/procedural-animation/README.md +1 -1
  199. package/examples/techniques/procedural-animation/main.js +1 -1
  200. package/examples/webgpu-tsl/GAMEMAP.md +1 -1
  201. package/examples/world/GAMEMAP.md +2 -3
  202. package/examples/world/art/humanoid.js +1 -1
  203. package/examples/world/main.js +6 -3
  204. package/index.d.ts +2 -2
  205. package/llms.txt +101 -0
  206. package/modules/ambience/Ambience.js +21 -5
  207. package/modules/calendar/index.js +9 -5
  208. package/modules/calendar/schedule.js +23 -8
  209. package/modules/camera/FirstPersonCamera.js +3 -1
  210. package/modules/camera/FollowCamera.js +10 -5
  211. package/modules/camera/RtsCamera.js +4 -3
  212. package/modules/camera/common.js +70 -8
  213. package/modules/camera/contract.js +1 -1
  214. package/modules/characters/Character.js +16 -10
  215. package/modules/characters/NPC.js +31 -19
  216. package/modules/characters/assetModel.js +14 -9
  217. package/modules/characters/astar.js +6 -1
  218. package/modules/characters/contract.js +2 -2
  219. package/modules/characters/index.js +34 -22
  220. package/modules/characters/movers/manual.js +1 -1
  221. package/modules/characters/movers/rapier.js +17 -2
  222. package/modules/characters/movers/simple.js +1 -1
  223. package/modules/characters/movers/support.js +16 -7
  224. package/modules/characters/npcAvoid.js +2 -2
  225. package/modules/characters/npcSim.js +3 -2
  226. package/modules/characters/pathAsync.js +24 -8
  227. package/modules/characters/pathJob.js +1 -1
  228. package/modules/characters/player.js +10 -9
  229. package/modules/characters/playerStrings.js +5 -5
  230. package/modules/characters/proceduralRig.js +5 -5
  231. package/modules/characters/useModel.js +6 -0
  232. package/modules/characters/walkTo.js +1 -1
  233. package/modules/collision/Collision.js +29 -18
  234. package/modules/collision/grid.js +22 -4
  235. package/modules/content/index.js +3 -1
  236. package/modules/content/loader.js +1 -1
  237. package/modules/content/models.js +82 -33
  238. package/modules/content/props.js +2 -1
  239. package/modules/content/rules.js +11 -5
  240. package/modules/content/templates.js +3 -3
  241. package/modules/content/words.js +2 -2
  242. package/modules/debug/DebugPanel.js +9 -9
  243. package/modules/flow/index.js +9 -6
  244. package/modules/gameplay/Dialogue.js +34 -20
  245. package/modules/gameplay/Interactions.js +19 -15
  246. package/modules/gameplay/Inventory.js +9 -4
  247. package/modules/gameplay/Quests.js +12 -10
  248. package/modules/gameplay/pickups.js +23 -11
  249. package/modules/grid/index.js +1 -1
  250. package/modules/grid/preview.js +2 -2
  251. package/modules/grid/tiles.js +1 -1
  252. package/modules/hlod/index.js +4 -1
  253. package/modules/hud/index.js +47 -10
  254. package/modules/hud/parts.js +28 -9
  255. package/modules/level/geometry.js +8 -3
  256. package/modules/level/index.js +10 -5
  257. package/modules/level/load.js +4 -2
  258. package/modules/lights/sources.js +1 -1
  259. package/modules/music/Music.js +22 -4
  260. package/modules/nav/index.js +20 -10
  261. package/modules/particles/Particles.js +31 -14
  262. package/modules/particles/effect.js +20 -5
  263. package/modules/particles/lit.js +72 -0
  264. package/modules/photo/Photo.js +72 -28
  265. package/modules/photo/pathTrace.js +106 -0
  266. package/modules/rigid/RigidBodies.js +23 -14
  267. package/modules/rigid/Vehicles.js +3 -13
  268. package/modules/rigid/sync.js +2 -1
  269. package/modules/settings/Settings.js +52 -20
  270. package/modules/settings/apply.js +23 -9
  271. package/modules/settings/sections.js +39 -6
  272. package/modules/settings/strings.js +2 -0
  273. package/modules/settings/view.js +19 -3
  274. package/modules/sky/dome.js +15 -3
  275. package/modules/sky/environment.js +28 -12
  276. package/modules/sky/fog.js +1 -1
  277. package/modules/sky/frame.js +6 -1
  278. package/modules/sky/shader.js +4 -3
  279. package/modules/sky/skyModule.js +8 -4
  280. package/modules/swarm/Swarm.js +1 -1
  281. package/modules/terrain/ChunkManager.js +61 -15
  282. package/modules/terrain/chunkJob.js +2 -2
  283. package/modules/terrain/index.js +20 -5
  284. package/modules/terrain/terrainEdit.js +8 -4
  285. package/modules/terrain/terrainTexture.js +4 -2
  286. package/modules/timeline/Timeline.js +4 -3
  287. package/modules/timeline/Tween.js +3 -0
  288. package/modules/timeline/letterbox.js +1 -0
  289. package/modules/triggers/index.js +36 -17
  290. package/modules/vegetation/Vegetation.js +81 -19
  291. package/modules/vegetation/densityMap.js +13 -8
  292. package/modules/vegetation/draw.js +147 -24
  293. package/modules/vegetation/groundChunks.js +20 -5
  294. package/modules/vegetation/index.js +3 -3
  295. package/modules/vegetation/modelGeometry.js +9 -4
  296. package/modules/water/Water.js +11 -8
  297. package/modules/weather/Weather.js +7 -2
  298. package/modules/weather/shaders.js +25 -5
  299. package/modules/weather/weatherDraw.js +20 -6
  300. package/modules/world/World.js +2 -1
  301. package/modules/world/index.js +2 -2
  302. package/modules/world/persist.js +6 -2
  303. package/modules/world/views.js +15 -2
  304. package/package.json +4 -1
  305. package/presets.js +5 -5
  306. package/render/PostFX.js +84 -41
  307. package/render/backend.js +137 -16
  308. package/render/cascades.js +3 -1
  309. package/render/cascades.tsl.js +2 -0
  310. package/render/daylight.js +7 -1
  311. package/render/detail.js +7 -4
  312. package/render/effects.js +27 -8
  313. package/render/fogLook.js +24 -0
  314. package/render/fuse.js +5 -2
  315. package/render/fx/detail.tsl.js +9 -7
  316. package/render/fx/index.js +7 -2
  317. package/render/fx/library.tsl.js +1 -0
  318. package/render/fx/lightShaft.tsl.js +114 -0
  319. package/render/fx/noise.tsl.js +25 -8
  320. package/render/fx/objectOrigin.tsl.js +39 -10
  321. package/render/fx/particles.tsl.js +23 -6
  322. package/render/fx/patchNodes.tsl.js +17 -12
  323. package/render/fx/pcss.tsl.js +51 -0
  324. package/render/fx/postWebGPU.tsl.js +89 -29
  325. package/render/fx/sky.tsl.js +3 -9
  326. package/render/fxNumbers.js +10 -4
  327. package/render/impostor.tsl.js +107 -0
  328. package/render/lighting.js +33 -1
  329. package/render/lightmap.js +42 -28
  330. package/render/lights.js +19 -3
  331. package/render/materials.js +6 -4
  332. package/render/mergeCommon.js +4 -1
  333. package/render/occlusion.js +14 -4
  334. package/render/patches.js +79 -41
  335. package/render/postRuns.js +32 -0
  336. package/render/postWebGL.js +97 -10
  337. package/render/probes.js +10 -14
  338. package/render/shaderErrors.js +2 -1
  339. package/render/shadowCache.tsl.js +33 -5
  340. package/render/shadows.js +42 -16
  341. package/render/slots.js +8 -5
  342. package/render/vertexInputs.js +52 -0
  343. package/types/core.d.ts +114 -46
  344. package/types/gameplay.d.ts +56 -23
  345. package/types/generated/core/audio/Audio.d.ts +27 -1
  346. package/types/generated/core/base/Random.d.ts +1 -1
  347. package/types/generated/core/input/Input.d.ts +6 -8
  348. package/types/generated/core/input/inputSeat.d.ts +1 -1
  349. package/types/generated/core/inspect/Budget.d.ts +26 -0
  350. package/types/generated/core/inspect/DebugOverrides.d.ts +0 -2
  351. package/types/generated/core/saves/Saves.d.ts +10 -7
  352. package/types/generated/core/saves/session.d.ts +8 -2
  353. package/types/generated/core/scene/Rays.d.ts +1 -3
  354. package/types/generated/modules/particles/Particles.d.ts +1 -1
  355. package/types/generated/modules/world/World.d.ts +2 -1
  356. package/types/generated/render/PostFX.d.ts +35 -9
  357. package/types/physics.d.ts +796 -764
  358. package/types/pixel.d.ts +1 -1
  359. package/types/tsl.d.ts +62 -1
  360. package/types/world.d.ts +12 -3
  361. package/ui/Focus.js +7 -5
  362. package/ui/Parts.js +1 -1
  363. package/ui/touchPart.js +6 -3
@@ -13,6 +13,8 @@
13
13
  // Doc paths are relative to the package docs (recipes/..., api/..., CONVENTIONS.md), same as the shipped docs.
14
14
  // Plain data (it imports only errorCodes.js, also plain data), so node tools can load it too. First pattern match wins, so put specific ones first.
15
15
  import { ERROR_CODES } from './errorCodes.js';
16
+ import { docRefsLine } from './docRef.js';
17
+ export { docRef, parseDocRef, docRefsLine, docReadCommand, docSlug } from './docRef.js';
16
18
 
17
19
 
18
20
  /** @typedef {{ id: string, match: RegExp, cause: string, docs: string[] }} ErrorHint */
@@ -27,7 +29,7 @@ export const ERROR_HINTS = [
27
29
  match: /Cannot (assign to read only property '[^']*' of object '(#<Object>|\[object Array\])'|add property [^,]*, object is not extensible|delete property '[^']*' of (#<Object>|\[object Array\]))/,
28
30
  cause: 'Definitions (content templates, items, entity types) are shared by every instance and frozen. Keep per-instance ' +
29
31
  'state on the world record (engine.world.set(id, { opened: true })) or in its container; define another template for a different kind of thing.',
30
- docs: ['recipes/30-templates.md', 'recipes/18-world.md'] },
32
+ docs: ['recipes/30-templates.md §3', 'recipes/18-world.md §2'] },
31
33
  // undefined only: a module that is not installed is undefined, never null. A read on null is another cause (null-value below), and
32
34
  // calling it "not installed" sent a reader after engine.use() when three.js mergeGeometries had returned null.
33
35
  { id: 'not-installed', match: /Cannot read properties of undefined \(reading '[\w$]+'\)|engine\.[\w$]+(\.[\w$]+)* is undefined/,
@@ -43,21 +45,21 @@ export const ERROR_HINTS = [
43
45
  // A guessed pause method (the engine has one answer: engine.freeze; `threedog check` asks this entry too, tools/types.mjs)
44
46
  { id: 'fall-prevent', match: /\bpreventDefault is not a function/,
45
47
  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'] },
48
+ docs: ['MIGRATING-1.0.md', 'recipes/55-mods-time-wrap.md §"The rules in full"'] },
47
49
  { id: 'thing-explain', match: /\.explain is not a function/,
48
50
  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'] },
51
+ docs: ['MIGRATING-1.0.md', 'recipes/40-scene.md §9'] },
50
52
  { id: 'pause-guess', match: /\b(?:time\.(?:pause|stop|resume)|engine\.(?:pause|resume|stop)) is not a function/,
51
53
  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'] },
54
+ '(handle.remove()); settings({ freezeWorld: true }) does it for a menu.',
55
+ docs: ['recipes/07-flow-scenes-pause.md §1', 'api/engine.md'] },
54
56
  { id: 'not-function', match: /[\w$.]+ is not a function/,
55
57
  cause: 'The method name is wrong, or the module is not installed (the property is then undefined). Check spelling against api/<module>.md.',
56
58
  docs: ['api/engine.md', 'CODEMAP.md'] },
57
59
  { id: 'resource-load', match: /Failed to load <(img|script|link|audio)/,
58
60
  cause: 'The browser could not load a file the page references (404 or wrong type). Check the path (files under public/ are served ' +
59
61
  'from /), the extension and the case of the name.',
60
- docs: ['api/assets.md', 'recipes/05-props-bake.md'] },
62
+ docs: ['api/assets.md', 'recipes/05-props-bake.md §2d'] },
61
63
  ];
62
64
 
63
65
 
@@ -110,5 +112,5 @@ export function coded(code, message) { return `${message} [${code}]`; }
110
112
  export function hintText(message) {
111
113
  const h = hintFor(message);
112
114
  if (!h || ERROR_CODES[h.id]?.brief) return '';
113
- return (tagOf(String(message)) ? '' : `\n Code: ${h.id}`) + `\n Possible cause: ${h.cause}\n Read: ${h.docs.join(', ')}`;
115
+ return (tagOf(String(message)) ? '' : `\n Code: ${h.id}`) + `\n Possible cause: ${h.cause}\n Read: ${docRefsLine(h.docs)}`;
114
116
  }
@@ -4,7 +4,8 @@
4
4
  // log once to the console, emit module:disabled; the game carries on -- a missing picture, sound or panel does not change game state.
5
5
  // Gameplay (all other modules, the game's own callbacks and event listeners): in dev and tests (DEV) fail hard -- freeze gameplay (freeze('error')),
6
6
  // engine.error records where and why, emits engine:error, and describe() / describeText() show it on the first line;
7
- // so a half-deducted inventory or half-updated quest does not keep running, and a test does not mistake it for normal. A release build reports once and keeps running (so the player is not stuck for the whole session).
7
+ // so a half-deducted inventory or half-updated quest does not keep running, and a test does not mistake it for normal. A release build does not freeze (so the player is not stuck
8
+ // for the whole session) but the game can still see it: engine.error keeps the first one and engine:error fires once per site; a game that cares can react (save and offer a restart).
8
9
  // soft (core steps such as rendering and stream.update): report once per site and continue.
9
10
  // engine.error is machine-readable: { where, message, code, fix, docs } (code / fix / docs come from the error itself or from the hint table, errorHints.js).
10
11
  import { DEV, fmt } from './validate.js';
@@ -19,13 +20,17 @@ const failsSoft = m => m?.type === 'picture' || m?.type === 'ui';
19
20
  /** Handle an error. key: where it happened (for display); module: the module definition that threw (none means a game callback / event listener, counted as gameplay); soft: report only once */
20
21
  export function reportError(engine, err, key, { module = null, soft = false } = {}) {
21
22
  if (failsSoft(module)) return disableModule(engine, module, err);
22
- if (!soft && DEV && !engine.error) {
23
+ // dev: the first gameplay error freezes the game. Release: no freeze, but the game can SEE it: engine.error keeps the first, engine:error fires once per site
24
+ if (!soft && (DEV ? !engine.error : !engine._hookErrors.has(key))) {
23
25
  const message = String(err?.message ?? err);
24
26
  // code + fix + docs: what to do and which page to read; at: the line that threw (the message alone often does not say which callback line)
25
- engine.error = { where: key, message, ...errorInfo(err), at: firstFrame(err) };
26
- engine.freeze('error'); // until reload, a new game included: dev must not walk past a bug, and a new playthrough on top of it would hide it. Release builds keep running
27
- console.error(fmt(STRINGS.halted, { key }) + hintText(err?.code ? `[${err.code}]` : message), err);
28
- engine.events.emit('engine:error', engine.error);
27
+ const info = { where: key, message, ...errorInfo(err), at: firstFrame(err) };
28
+ engine.error ??= info;
29
+ if (DEV) {
30
+ engine.freeze('error'); // until reload, a new game included: dev must not walk past a bug, and a new playthrough on top of it would hide it
31
+ console.error(fmt(STRINGS.halted, { key }) + hintText(err?.code ? `[${err.code}]` : message), err);
32
+ } else { engine._hookErrors.add(key); console.error(fmt(STRINGS.once, { key }), err); }
33
+ engine.events.emit('engine:error', info);
29
34
  return;
30
35
  }
31
36
  if (engine._hookErrors.has(key)) return;
@@ -53,13 +58,23 @@ export function watchRejections(engine) {
53
58
  /** An event listener threw (called by the event bus): counted as gameplay */
54
59
  export function reportListenerError(engine, name, err) { reportError(engine, err, fmt(STRINGS.listener, { name })); }
55
60
 
56
- /** Disable a picture / ui module: give back what it borrowed, remove its fixed / frame / afterRender hooks */
61
+ /** Disable a picture / ui module: remove everything it tracked (borrows given back) and its fixed / frame / afterRender hooks */
57
62
  function disableModule(engine, m, err) {
58
63
  const was = engine._modState.get(m.name);
59
64
  if (was === 'disabled') return;
60
- if (was !== 'failed') engine._modState.set(m.name, 'disabled'); // a failed init stays 'failed': that word is what blocks the modules that require it
61
- engine._returnBorrowed(m.name);
62
- for (const k in engine._hooks) engine._hooks[k] = engine._hooks[k].filter(h => h.name !== m.name);
65
+ // the same teardown as unload for what it tracked (listeners, timers, borrows, slots), so a disabled module leaves nothing running; it stays installed. A failed init stays 'failed':
66
+ // that word is what blocks the modules that require it. _setModState re-sorts, which drops its hooks and re-blocks its dependents ('disabled' counts as dead there)
67
+ engine._dropTracked(m.name);
68
+ if (was !== 'failed') engine._setModState(m, 'disabled');
63
69
  console.error(fmt(STRINGS.disabled, { type: m.type, name: m.name }), err);
64
70
  engine.events.emit('module:disabled', { name: m.name, message: String(err?.message ?? err) });
65
71
  }
72
+
73
+ /**
74
+ * @internal The one cleanup rule: remove every handle, newest first when the caller orders them so; one that throws is reported (soft) and the rest still go.
75
+ * Modules (unload, failed init) and sessions (the old playthrough's session.track handles) both clean up through it.
76
+ * @param {any} e @param {Iterable<{ remove(): void }>} handles @param {string} where @param {(h: any) => void} [first] runs before each remove(), inside its catch
77
+ */
78
+ export function removeEach(e, handles, where, first) {
79
+ for (const h of handles) { try { first?.(h); h.remove(); } catch (err) { reportError(e, err, where, { soft: true }); } }
80
+ }
@@ -13,6 +13,7 @@ export const ENGINE_EVENTS = [
13
13
  'ui:close',
14
14
  'settings:shadows',
15
15
  'settings:change',
16
+ 'post:add',
16
17
  'water:add',
17
18
  'water:remove',
18
19
  'day:start',
@@ -85,6 +86,7 @@ export const ENGINE_EVENTS = [
85
86
  'engine:error',
86
87
  'module:disabled',
87
88
  'module:restored',
89
+ 'op:rolledBack',
88
90
  'state:replaced',
89
91
  'vehicle:enter',
90
92
  'vehicle:exit',
@@ -0,0 +1,76 @@
1
+ // The one low-level GPU free (design.md 6.2): engine.remove, engine.dispose and the asset cache dispose scene parts only here, each passing its own owner test.
2
+ // Why one helper: walks with rules of their own would free a game's own material at engine.dispose and a material an asset file shares twice (once by the scene walk,
3
+ // once by the cache). The caller says what it owns; the helper walks, asks, and disposes each part at most once per call.
4
+ // The guard spec 'resource lifetime: only freeParts disposes scene parts in a walk' keeps a second walk from coming back.
5
+
6
+ // Instanced / batched objects a model clone produced: their buffers are the copy's. One a game attached to the copy (onModel) is the game's and is not in here
7
+ const CLONED = new WeakSet();
8
+ /** A model copy: SkeletonUtils.clone (a skinned part gets bones of its own), with the instance objects it produced marked as the copy's @param {any} src */
9
+ export function cloneModel(src) {
10
+ const root = skeletonClone(src);
11
+ root.traverse(o => { if (o.isInstancedMesh || o.isBatchedMesh) CLONED.add(o); });
12
+ return root;
13
+ }
14
+ /** What Assets.dropCopy frees of a model copy: its cloned bones and the instance objects its clone produced (engine.remove frees more: it is handed the whole object) */
15
+ export const copyOwns = (shared, o) => copyBones(shared, o) || CLONED.has(o);
16
+
17
+ import { clone as skeletonClone } from 'three/addons/utils/SkeletonUtils.js';
18
+
19
+ /** The geometry and materials of one object */
20
+ export const partsOf = o => [o.geometry, ...[].concat(o.material)].filter(Boolean);
21
+
22
+ /** A model copy's own bones: skeletonClone gave the copy a skeleton of its own, while its geometry is the asset's (shared). The engine made those bones */
23
+ const copyBones = (shared, o) => !!o.isSkinnedMesh && shared.has(o.geometry);
24
+
25
+ // Parts a maker shares among many of its objects and frees itself (the characters' capsule material): engine.remove and engine.dispose leave them.
26
+ // Why not assets.shared: that set says "an asset load owns it and frees it", and a module's material is no load's, so marking it there freed it never.
27
+ // A hold, not a mark: one who stops holding (a material replaced, a module unloaded) gives it back with remove(), and a part nobody keeps is ordinary
28
+ // again, so engine.remove frees a game material characters no longer use. Counted, since two holders may keep one part.
29
+ const KEPT = new WeakMap(); // part -> number of holds
30
+ /** Hold a part its holder frees or hands back itself: { part, remove() } (remove is idempotent) @template T @param {T} x @returns {{ part: T, remove(): void }} */
31
+ export function keepPart(x) {
32
+ KEPT.set(x, (KEPT.get(x) ?? 0) + 1);
33
+ let held = true;
34
+ return { part: x, remove() { if (!held) return; held = false; const n = KEPT.get(x) - 1; if (n > 0) KEPT.set(x, n); else KEPT.delete(x); } };
35
+ }
36
+ /** Whether someone holds this part (keepPart) @param {any} x */
37
+ export const kept = x => KEPT.has(x);
38
+
39
+ const run = fn => fn();
40
+
41
+ /**
42
+ * Dispose the GPU parts under roots that the caller owns, each once.
43
+ * @param {any | any[]} roots Object3D roots, each walked with traverse
44
+ * @param {(part: any) => boolean} mine true for a geometry, material or texture this caller made or was handed; a part it says no to is left alone
45
+ * @param {{ textures?: boolean, own?: (obj: any) => boolean, tidy?: (fn: () => void) => void }} [opts]
46
+ * textures: also the textures in each freed material's slots (that pass mine too). own(obj): the object's own GPU data is the caller's (instance buffers,
47
+ * a batch's textures, a light's shadow map, the bone texture). tidy wraps each dispose: engine.dispose keeps going past a game 'dispose' listener that throws.
48
+ */
49
+ export function freeParts(roots, mine, { textures = false, own = null, tidy = run } = {}) {
50
+ const done = new Set();
51
+ const free = x => {
52
+ if (!x || done.has(x) || !mine(x)) return false;
53
+ done.add(x);
54
+ if (textures && x.isMaterial) for (const k in x) if (x[k]?.isTexture) free(x[k]); // before the material, as three's own examples do
55
+ tidy(() => x.dispose());
56
+ return true;
57
+ };
58
+ for (const r of [].concat(roots)) r.traverse(o => {
59
+ if (own?.(o)) {
60
+ if ((o.isInstancedMesh || o.isBatchedMesh || o.isLight) && !done.has(o)) {
61
+ done.add(o);
62
+ if (o.isBatchedMesh && (done.has(o.geometry) || !mine(o.geometry))) {
63
+ // BatchedMesh.dispose() frees its geometry unconditionally: a geometry freed earlier in this walk, or one the caller does not own (another mesh still draws it),
64
+ // goes through the same check as any geometry, so only the batch's own textures are freed here (three's private fields; the dispose event is what the renderer listens to)
65
+ tidy(() => { for (const k of ['_matricesTexture', '_indirectTexture', '_colorsTexture', '_previousMatricesTexture']) o[k]?.dispose(); o.dispatchEvent({ type: 'dispose' }); });
66
+ } else {
67
+ tidy(() => o.dispose());
68
+ if (o.isBatchedMesh) done.add(o.geometry); // dispose() freed it with the batch: the walk below must not dispose it a second time
69
+ }
70
+ }
71
+ if (o.skeleton && !done.has(o.skeleton)) { done.add(o.skeleton); tidy(() => o.skeleton.dispose()); } // one skeleton may drive several meshes
72
+ }
73
+ free(o.geometry);
74
+ for (const m of [].concat(o.material || [])) free(m);
75
+ });
76
+ }
package/core/base/math.js CHANGED
@@ -19,6 +19,28 @@ const XZ_ERR = 'A horizontal position needs finite x and z: pass [x, y, z] (a 2-
19
19
  /** Round to one decimal (describe, budget reports) @param {number} v @returns {number} */
20
20
  export const r1 = v => Math.round(v * 10) / 10;
21
21
 
22
+ const _vp = new THREE.Matrix4();
23
+ /**
24
+ * The camera's view frustum for culling math, read with the camera's own depth convention. Why: THREE.Frustum defaults to WebGL clip depth (-1..1);
25
+ * a WebGPU camera (or one with reversed depth) has a different near plane, so a default frustum calls things drawn that the near plane cuts.
26
+ * The three inspect checks and the chunk stream share this one, so they agree with what the renderer culls.
27
+ * @param {any} cam @param {THREE.Frustum} [out] @returns {THREE.Frustum}
28
+ */
29
+ export function cameraFrustum(cam, out = new THREE.Frustum()) {
30
+ cam.updateMatrixWorld(); // also refreshes cam.matrixWorldInverse
31
+ return out.setFromProjectionMatrix(_vp.multiplyMatrices(cam.projectionMatrix, cam.matrixWorldInverse), cam.coordinateSystem, cam.reversedDepth);
32
+ }
33
+ /** Value at share q of the sorted samples (0.5 = median, 0.95 = p95; linear between neighbours), 0 for none. The one helper for "typical frame"
34
+ * readings (module timing, frame time): one long frame (a GC pause, a chunk build) moves a mean, not this @param {ArrayLike<number>} a @param {number} q */
35
+ export function quantile(a, q) {
36
+ const s = Array.from(a).sort((x, y) => x - y), n = s.length;
37
+ if (!n) return 0;
38
+ const i = (n - 1) * q, lo = Math.floor(i);
39
+ return s[lo] + (s[Math.min(n - 1, lo + 1)] - s[lo]) * (i - lo);
40
+ }
41
+ /** @param {ArrayLike<number>} a */
42
+ export const median = a => quantile(a, 0.5);
43
+
22
44
  /**
23
45
  * Show a value someone set (style post params, exposure, light intensity) without changing it: 4 significant digits, never fewer than
24
46
  * the integer part. r1 is for measurements (positions, ms); a set value rounded to one decimal misreports it (bloom 0.25 read as 0.3,
@@ -30,6 +52,12 @@ export const rv = v => (Number.isFinite(v) && v !== 0 ? Number(v.toPrecision(Mat
30
52
  /** An angle in radians as the same turn in -PI..PI; of a difference, the short way round @param {number} a @returns {number} */
31
53
  export const wrapAngle = a => Math.atan2(Math.sin(a), Math.cos(a));
32
54
 
55
+ /** rot / scale of a world record as [x, y, z]: a number is the facing about Y and a uniform scale; an array sets each axis (Euler order XYZ). The one reading,
56
+ * shared by content models and the editor, so a record turns the same wherever it is read @param {{ rot?: number | number[] }} rec */
57
+ export const rotOf = rec => Array.isArray(rec.rot) ? rec.rot : [0, rec.rot ?? 0, 0];
58
+ /** @param {{ scale?: number | number[] }} rec @param {number} [mul] */
59
+ export const scaleOf = (rec, mul = 1) => (Array.isArray(rec.scale) ? rec.scale : [rec.scale ?? 1, rec.scale ?? 1, rec.scale ?? 1]).map(v => v * mul);
60
+
33
61
  const _world = new THREE.Vector3();
34
62
  /** Where an Object3D stands: a position argument is a place in the world, and a child's .position is one in its parent's space */
35
63
  const placeOf = o => (o.parent && !o.parent.isScene ? o.getWorldPosition(_world) : o.position);
@@ -39,7 +39,7 @@ export function sectionsOf(e) {
39
39
  const bad = Object.keys(s).find(k => !KEYS.includes(k));
40
40
  if (bad) throw codedError('content-misuse', `content section "${name}" of module ${m.name}: unknown key "${bad}". Keys: ${KEYS.join(', ')}`);
41
41
  if (typeof s.commit !== 'function') throw codedError('content-misuse', `content section "${name}" of module ${m.name} needs commit(prepared, c)`);
42
- out.set(name, { owner: m.name, ...s });
42
+ out.set(name, { owner: m.name, name, ...s });
43
43
  }
44
44
  return out;
45
45
  }
@@ -70,9 +70,9 @@ export function runSections(list, c, { after = null, around = fn => fn() } = {})
70
70
  const undos = [];
71
71
  const takeBack = cause => {
72
72
  const lost = [], waits = [];
73
- const told = err => { lost.push(err); warnOnce(coded('content-misuse', `content: an undo failed, so part of a failed load may remain: ${err.message}`)); };
74
- for (const fn of undos.reverse()) {
75
- try { const r = fn(); if (typeof r?.then === 'function') waits.push(r.catch(told)); } catch (err) { told(err); } // the rest still goes back
73
+ const told = (err, s) => { lost.push(err); warnOnce(coded('rollback-incomplete', `content: undo for section '${s.name ?? '?'}' owned by module '${s.owner ?? '?'}' failed: ${err.message}. Fix the undo its commit step returns, then reload the page before retrying; the state was only partly restored.`)); };
74
+ for (const { fn, s } of undos.reverse()) {
75
+ try { const r = fn(); if (typeof r?.then === 'function') waits.push(r.catch(err => told(err, s))); } catch (err) { told(err, s); } // the rest still goes back
76
76
  }
77
77
  const fail = () => { if (lost.length) cause.notRestored = lost; throw cause; };
78
78
  if (waits.length) return Promise.all(waits).then(fail);
@@ -82,7 +82,7 @@ export function runSections(list, c, { after = null, around = fn => fn() } = {})
82
82
  try {
83
83
  for (; i < list.length; i++) {
84
84
  const undo = list[i].s.undo?.(values[i], c);
85
- if (undo) undos.push(undo);
85
+ if (undo) undos.push({ fn: undo, s: list[i].s });
86
86
  const r = list[i].s.commit(values[i], c);
87
87
  if (r === DROPPED) { if (undo) undos.pop(); list[i].gaveWay?.(); } else list[i].done?.(r);
88
88
  }
@@ -8,7 +8,7 @@
8
8
  //
9
9
  // On by default; createEngine({ validate: false }) turns it all off (for release builds). Each message warns only once.
10
10
 
11
- import { hintText, coded, codedError } from './errorHints.js';
11
+ import { hintText, hintFor, coded, codedError } from './errorHints.js';
12
12
  import { isOptions } from './util.js';
13
13
  import { closest } from './spelling.js';
14
14
  export { closest };
@@ -56,6 +56,10 @@ export const DEV_SERVER = !!ENV?.DEV;
56
56
  /** Vite's base URL ('/' outside Vite) */
57
57
  export const BASE_URL = ENV?.BASE_URL ?? '/';
58
58
  const warned = new Set();
59
+ // Dev: what warnOnce said, for describe().warnings, so an AI sees a fallback or clamp without reading the console. The first ones are kept (the first
60
+ // warning is most often the cause of the rest); later ones are only counted
61
+ const said = [], SAID_MAX = 20;
62
+ let saidCount = 0;
59
63
 
60
64
  /**
61
65
  * The one check behind every `.material = m` setter a module hands out.
@@ -91,15 +95,39 @@ export function trackValidate(on) {
91
95
 
92
96
  /**
93
97
  * Warn only once (no warning when checks are off). The one dedupe for engine warnings: modules do not keep private "already warned" sets.
94
- * @param {string} msg the text, usually coded(code, text) so it carries its fix
98
+ * @param {string | (() => string)} msg the text, usually coded(code, text) so it carries its fix; a function (with a key) builds it only when it is said,
99
+ * for a call on a hot path whose text is costly to build (a value read every frame)
95
100
  * @param {string} [key] what counts as "the same warning" when the text has changing parts (a measured value each second, a stack line); default the text
96
101
  */
97
- export function warnOnce(msg, key = msg) {
102
+ /** Whether v is a Promise or any thenable. The one test the engine's sync contracts use (syncOnly below). @param {unknown} v */
103
+ export const isThenable = v => typeof /** @type {any} */ (v)?.then === 'function';
104
+ /**
105
+ * Guard a callback whose contract is synchronous (op run, frame / fixed / render hooks, install, dispose, a listener inside a load): the engine does not await what it
106
+ * returns, so a Promise would count as done while its writes and its failure happen outside the op's rollback, the frame's error tiers or the save's transaction.
107
+ * That is a programming error: dev (and strict, always) throws a coded error naming the callback; release warns once. It never awaits the thenable.
108
+ * Callbacks that DO accept async (module init, a save part's load / afterLoad, flow.transition) must not call this.
109
+ * @param {unknown} r what the callback returned
110
+ * @param {string} what who it was: "ops.run('shop.buy')", "hook frame of module fishing"
111
+ * @param {boolean} [strict] throw in release too (an op: its failure must reach the caller)
112
+ */
113
+ export function syncOnly(r, what, strict = false) {
114
+ if (!isThenable(r)) return;
115
+ const text = `${what} returned a Promise, but it must be synchronous: the engine does not wait for it, so what it does after its first await escapes the rollback, error handling or save transaction around it. Do the async work outside (await it first, then call this with the result) and keep this callback plain`;
116
+ if (DEV || strict) throw codedError('engine-misuse', text);
117
+ warnOnce(coded('engine-misuse', text), what);
118
+ }
119
+ export function warnOnce(msg, key = /** @type {string} */ (msg)) {
120
+ if (typeof msg === 'function' && /** @type {unknown} */ (key) === msg) throw new Error('warnOnce(textFactory, key): a text factory needs a key, or every call is a new function and nothing dedupes');
98
121
  if (!enabled() || warned.has(key)) return;
99
122
  warned.add(key);
123
+ if (typeof msg === 'function') msg = msg();
124
+ if (DEV) { saidCount++; if (said.length < SAID_MAX) { const h = hintFor(msg); said.push({ code: h?.id ?? null, text: msg.replace(/ \[[a-z][a-z0-9-]*\]$/, ''), fix: h?.cause ?? null }); } }
100
125
  console.warn(DEV ? msg + hintText(msg) : msg); // the fix + doc page only in dev: release builds drop the hint table
101
126
  }
102
127
 
128
+ /** Dev: the warnings said so far on this page, { count, list: [{ code, text, fix }] } (list capped at the first 20), or null when there were none @internal */
129
+ export const warningsSaid = () => (saidCount ? { count: saidCount, list: said.map(w => ({ ...w })) } : null);
130
+
103
131
  /**
104
132
  * A dev note that is not a problem (a hot swap happened, why a shared value shows another number): console.info with the '[threedog] ' prefix,
105
133
  * silenced like warnings by validate: false. Why here and not console.info at the call: one prefix, one switch, one dedupe (R45 flags a bare call).
@@ -23,7 +23,7 @@ import { startupMethods } from './startup.js';
23
23
  import { groundMethods, flatGround } from '../scene/ground.js';
24
24
  import { actorMethods } from '../ops/actor.js';
25
25
  import { forcedTier, storedMsaa } from '../scene/tier.js';
26
- import { tier as detectTier, tierBeforeRenderer, ownMsaa, timerContext, isWebGPU, webgpuPart, watchNodePrograms } from '../../render/backend.js';
26
+ import { tier as detectTier, tierBeforeRenderer, ownMsaa, timerContext, isWebGPU, webgpuPart, watchNodePrograms, mathClasses } from '../../render/backend.js';
27
27
  import { recordSweep } from '../../render/recordSweep.js';
28
28
  import { dressNodeTwins } from '../../render/patches.js';
29
29
  import { lifecycleMethods, clearHooks, checkCanvasUsable } from './lifecycle.js';
@@ -49,6 +49,8 @@ import { probeMethods } from '../../render/probes.js';
49
49
  import { lightmapMethods } from '../../render/lightmap.js';
50
50
  import { headlessSettled } from './headlessLoad.js';
51
51
  import { coded, codedError } from '../base/errorHints.js';
52
+ // render/backend.js may not import three (threedog/tsl reaches it): its renderer borrow gets the two math classes from here
53
+ mathClasses(THREE);
52
54
  const FALLBACKS = ['webgl2', 'webgl', 'error'];
53
55
  // createEngine() options: the one table for the unknown-key and type check (dev throws with did-you-mean, release warns once), the plain
54
56
  // defaults and engine.catalog('core').params; R6 checks EngineOptions (types/core.d.ts) has exactly these keys. A key with several shapes
@@ -60,7 +62,7 @@ export const ENGINE_PARAMS = {
60
62
  pixelRatio: 'number?', pixelSize: { type: 'int', optional: true, min: 1, desc: 'real screen pixels per art pixel' }, adaptiveResolution: { type: 'bool', default: true }, targetFps: { type: 'number', default: 55, min: 1 },
61
63
  ui: 'object?', audio: 'object?', fov: { type: 'number', default: 55, min: 1, max: 179 }, near: { type: 'number', default: 0.3, min: 0 },
62
64
  locale: { type: 'string', default: 'auto' }, strings: 'object?', bindings: 'object?', saveKey: { type: 'string', default: 'game' },
63
- joystick: { type: 'string|bool', default: 'auto' }, headless: 'bool?', validate: { type: 'bool', default: true }, decoders: 'string?',
65
+ joystick: { type: 'string|bool', default: 'auto' }, blockBrowserKeys: { type: 'bool', default: true, desc: 'while playing, keys the game binds (Ctrl+S, F1, Backspace...) do not reach the browser' }, headless: 'bool?', validate: { type: 'bool', default: true }, decoders: 'string?',
64
66
  budget: 'object?', urlState: 'bool?', seed: 'number?', movement: 'object?', threads: { type: 'string|number|bool', default: 'auto' },
65
67
  pauseOnBlur: { type: 'bool', default: true }, batching: 'bool|object?', lights: { type: 'bool', default: true },
66
68
  };
@@ -117,7 +119,7 @@ export class Engine {
117
119
  const o = readParams('createEngine()', ENGINE_PARAMS, opts);
118
120
  /** @internal createEngine options as read (engine.catalog('core').params shows them with the schema) */ this._createParams = o;
119
121
  const { canvas: canvasIn, renderer: rendererName, antialias, pixelRatio, pixelSize, adaptiveResolution, targetFps, ui = {}, audio = {},
120
- fov, near, locale, strings = {}, bindings = {}, saveKey, joystick,
122
+ fov, near, locale, strings = {}, bindings = {}, saveKey, joystick, blockBrowserKeys,
121
123
  headless = new URLSearchParams(location.search).has('threedog-headless'), validate,
122
124
  decoders = null, budget = null, urlState = DEV, seed, movement, threads, pauseOnBlur, batching = {}, lights, fallback } = o;
123
125
  if (pixelSize != null) checkPixelSizeOptions(pixelSize, pixelRatio, opts.adaptiveResolution);
@@ -144,6 +146,8 @@ export class Engine {
144
146
  const r = this.renderer = gpuWanted ? newWebGPURenderer(canvas, aa) : rendererIn ?? new THREE.WebGLRenderer({ canvas, antialias: aa, powerPreference: 'high-performance' });
145
147
  /** @internal what the game asked for and what to do without WebGPU; start() fills describe().renderer from it */
146
148
  this._backendWant = rendererWant(r, rendererIn, fallback);
149
+ // the engine made this device's renderer, so its limits are the engine's to ask for (start() fills them from the adapter); a game's own renderer keeps the game's
150
+ if (gpuWanted) this._backendWant.limits = r.backend?.parameters?.requiredLimits;
147
151
  watchNodePrograms(r); // WebGPU: generated code per material, for debug.view('shaderCost') (render/backend.js)
148
152
  this._records = recordSweep(r); // WebGPU: meshes that left the scene free their records (render/recordSweep.js)
149
153
  if (isWebGPU(r)) dressNodeTwins(r); // WebGPU: classic materials get their patches as nodes (render/patches.js)
@@ -227,11 +231,13 @@ export class Engine {
227
231
  defineTerms(this); // engine.shaderTerms: the game's own cloud shadow or season tint in place of the engine's (render/terms.js)
228
232
  this._materials = registerEngine(this); // applyEffects without an engine option uses the first live engine
229
233
 
230
- createServices(this, { canvas: r.domElement, validate, locale, strings, saveKey, joystick, bindings, audio, decoders, budget, seed, headless, urlState, threads, batching });
234
+ createServices(this, { canvas: r.domElement, validate, locale, strings, saveKey, joystick, blockBrowserKeys, bindings, audio, decoders, budget, seed, headless, urlState, threads, batching });
231
235
  this.startup = null; // startup timing report (set once start() finishes)
232
236
  this._readyAt = null; // set at ready until the first frame is drawn (loop.js firstFrame)
233
237
  this._whileCompiling = []; // @internal one-time warm-ups a module queues during loading; start() runs them while the GPU compiles
234
- this._prof = null; // module hook timing (profile(true) turns it on)
238
+ this._playTiming = false; // set at the first settled frame after ready, when timing is cleared of start-up (loop.js startPlayTiming)
239
+ this._prof = null; // module hook timing: on in dev builds (a few performance.now() per hook), profile(true) turns it on in production
240
+ if (DEV) this.profile(true);
235
241
  this._afterTick = null; // at startup, checked once at the end of each frame for readiness
236
242
  // a game's own renderer keeps its own MSAA choice by default (used as is, like its pixel ratio)
237
243
  this.post = new PostFX(this, { antialias: aa ?? ownMsaa(r), authored: authoredAA ?? ownMsaa(r) });
@@ -281,7 +287,11 @@ export class Engine {
281
287
  /** The one quality value, 'low' | 'high', what everything that scales by quality reads: the device's tier, unless the player's preset says otherwise (shared point 'tier') @type {'low' | 'high'} */
282
288
  get tier() { return this.stacks.has('tier') ? this.stacks.get('tier').value() : this._deviceTier; }
283
289
  /** The device's tier, the base under a player's preset */
284
- set tier(t) { this._deviceTier = t; if (this.stacks.has('tier')) this.stacks.get('tier').base = t; }
290
+ set tier(t) {
291
+ this._deviceTier = t;
292
+ const st = this.stacks.has('tier') ? this.stacks.get('tier') : null;
293
+ if (st && st.base !== t) { st.base = t; st._changed(); } // through the stack's change path: onTierChange followers (post, cascades) run once; writing base alone told nobody
294
+ }
285
295
  /** True once the world is built (phase 'ready' or 'running'): fixed steps, ops and rendering run from here on @type {boolean} */
286
296
  get ready() { return this.phase === 'ready' || this.phase === 'running'; }
287
297
  /** @internal start() is on its way: no game time passes */
@@ -35,19 +35,21 @@ export class Loading {
35
35
  constructor(engine) {
36
36
  this.engine = engine; this.tasks = new Map();
37
37
  this._inits = new Set(); // init() of modules installed after start(), in flight
38
+ this._parts = new Set(); // their save parts taking back data a save kept for them (saveApply.js adoptPart), in flight
38
39
  /** The one limit on every wait for a load (ms): a file that gives no sign of life, a module's init or a settle that does not end fail by name after it @type {number} */
39
40
  this.timeoutMs = 120000;
40
41
  }
41
42
 
42
43
  /** @internal keep a late module init in flight until it ends (settled() waits for these) */
43
- _track(p) { this._inits.add(p); p.finally(() => this._inits.delete(p)); }
44
+ _track(p, into = this._inits) { into.add(p); p.finally(() => into.delete(p)); }
44
45
  /**
45
- * Resolves when every module installed after start() has finished its init() (also when one failed: its state is then 'failed' in engine.moduleStates and the error went through the error tiers).
46
+ * Resolves when every module installed after start() has finished its init() (also when one failed: its state is then 'failed' in engine.moduleStates and the error went through the error tiers),
47
+ * and its save parts took back what the last save kept for them, afterLoad round included: until then the load holds gameplay, as any load does (core/saves/stateReplace.js).
46
48
  * engine.use() returns the engine, so await this to know a late module is running.
47
49
  * @returns {Promise<void>}
48
50
  * @example engine.use(shop()); await engine.loading.settled(); engine.explain({ module: 'shop' }).ok // true
49
51
  */
50
- async settled() { while (this._inits.size) await Promise.allSettled([...this._inits]); }
52
+ async settled() { while (this._inits.size || this._parts.size) await Promise.allSettled([...this._inits, ...this._parts]); }
51
53
 
52
54
  /**
53
55
  * @internal The one limit: p, or fail()'s error once lastSign() (the time of the last sign of life, null: stop watching) is older than timeoutMs. It only answers the waiter; p goes on unless fail ends it.
@@ -6,7 +6,7 @@
6
6
  // A hot reload re-runs the same file (same path, a ?t= query): that is one copy, not two, so the path without the query decides.
7
7
  import { coded } from '../base/errorHints.js';
8
8
 
9
- export const VERSION = '0.9.0'; // kept equal to package.json by the "[guard] engine copies" spec
9
+ export const VERSION = '1.2.0'; // kept equal to package.json by the "[guard] engine copies" spec
10
10
 
11
11
  const KEY = Symbol.for('threedog.engine.copies');
12
12
 
@@ -30,10 +30,13 @@ const stalled = e => codedError('module-not-ready', `Still waiting after ${Math.
30
30
  * @internal The one wait for "ready to play": true once nothing is unsettled, checked per engine frame so step() advances it too; false as soon as valid() stops holding. It rejects (module-not-ready,
31
31
  * naming who still waits) after engine.loading.timeoutMs. start(), flow's transition, level:playable and the headless pump all read this, so the question has one answer and one limit.
32
32
  */
33
- export function whenSettled(e, valid = () => true) {
33
+ export function whenSettled(e, valid = () => true, rearm = false) {
34
34
  const now = () => !valid() ? false : unsettled(e).length ? null : true;
35
35
  const first = now();
36
36
  if (first !== null) return Promise.resolve(first);
37
+ // rearm: a load during play (a level, a flow transition) passes it, since its start-up cost is not play either: timing is cleared again once it settles
38
+ // (loop.js startPlayTiming). The headless pump does not: chunks streaming in while walking are play, and their spikes must stay visible
39
+ if (rearm) e._playTiming = false;
37
40
  const since = performance.now(); // measure: wall clock, so a wait with no frames to run on still ends
38
41
  let h;
39
42
  const settled = new Promise((res, rej) => {
@@ -9,17 +9,21 @@
9
9
  // - Events, onFixed / onFrame, clock timers, jobs, stream, ray registrations: core clears them all here. A module registers its own through
10
10
  // ctx.track (modules.js), so they also leave when its install rolls back or its init fails, and go before its dispose hook runs.
11
11
  // - Things core does not know about (Worker, physics world, Audio nodes, real-time timers): clean up in the module's dispose(e) hook, called in reverse install order.
12
- // - GPU memory: every geometry, material and texture in the scene, the assets cache, the post composer, then renderer.dispose().
12
+ // - GPU memory (design.md 6.2, whoever made it frees it): the scene walk gives back model copies' leases and frees only what the engine made (engineParts below);
13
+ // then the assets cache frees what its loads made, the post composer, then renderer.dispose(). A material or texture the game made stays the game's.
13
14
  // Waits across dispose, one rule: a wait in game code (model(), jobs.add, nextFixed, a cutscene, an await of what those feed) stays pending for good, because the code after it
14
15
  // belongs to a dead engine (assetEntry.js says why not reject). Two waits have to answer instead: start(), for whoever booted the engine (startup.js), and a stream source's whenReady,
15
16
  // which rejects stream-removed: dispose removes every source, and a source made afterwards is born removed.
16
17
  // Level changes do not come through here: things inside a level register with level.track(handle), and the level removes them itself on change.
17
18
 
18
19
  import { coded, codedError } from '../base/errorHints.js';
19
- import { fmt } from '../base/validate.js';
20
+ import { fmt, syncOnly } from '../base/validate.js';
20
21
  import { dropOwned } from '../ops/owned.js';
21
22
  import { reportError } from '../base/errors.js';
22
23
  import { releaseContext, memory } from '../../render/backend.js';
24
+ import { freeParts, partsOf, copyOwns, kept } from '../base/freeParts.js';
25
+ import { moduleOwnerOf } from '../scene/things.js';
26
+ import { isEngineMade } from '../../render/patches.js';
23
27
 
24
28
  /** The per-step / per-frame callback lists (onFixed, onFrame, animators, onRender, module hooks), empty: the constructor's starting state and what dispose leaves */
25
29
  export function clearHooks(e) {
@@ -35,15 +39,24 @@ const released = new WeakSet();
35
39
  /** createEngine calls it before building its renderer on a canvas */
36
40
  export function checkCanvasUsable(canvas) { if (canvas && released.has(canvas)) throw codedError('canvas-released', STRINGS.released); }
37
41
 
38
- /** Dispose the GPU data of one scene object: geometry, materials and their textures, instance buffers, shadow map, bone texture */
39
- function disposeObject(o, tidy) {
40
- tidy(() => o.geometry?.dispose());
41
- tidy(() => { if (o.isInstancedMesh || o.isBatchedMesh || o.isLight) o.dispose(); }); // instance buffers, batch textures, a light's shadow map
42
- tidy(() => o.skeleton?.dispose()); // the bone texture
43
- for (const m of [].concat(o.material || [])) {
44
- for (const k in m) if (m[k]?.isTexture) tidy(() => m[k].dispose());
45
- tidy(() => m.dispose());
46
- }
42
+ /**
43
+ * engine.dispose's owner test (design.md 6.2): the parts the engine made, never the game's or an asset load's. Engine nodes are objects a module put in
44
+ * the scene (engineOwned, or registered under 'engine:<module>') and everything under them. A material or texture is the engine's only when its maker marked
45
+ * it engine-made (markEngineMade): never inferred from the material a texture sits on, since a game texture may sit on an engine material and on a game one
46
+ * at once. A geometry only when no game node draws it (a batch draws the game's own geometry). Asset parts and kept parts (keepPart) never: their owner frees them.
47
+ */
48
+ function engineParts(e) {
49
+ const shared = e.assets.shared, T = e._things, nodes = new Set(), gameUsed = new Set();
50
+ const walk = (o, eng) => {
51
+ eng ||= !!moduleOwnerOf(o) || !!T?.byObj.get(o)?.owner?.startsWith('engine:');
52
+ if (eng) nodes.add(o); else for (const x of partsOf(o)) gameUsed.add(x);
53
+ for (const c of o.children) walk(c, eng);
54
+ };
55
+ walk(e.scene, false);
56
+ return {
57
+ mine: x => !shared.has(x) && !kept(x) && (x.isMaterial || x.isTexture ? isEngineMade(x) : !gameUsed.has(x)),
58
+ own: o => nodes.has(o) || copyOwns(shared, o),
59
+ };
47
60
  }
48
61
 
49
62
  export const lifecycleMethods = {
@@ -67,20 +80,23 @@ export const lifecycleMethods = {
67
80
  this._modState.set(m.name, 'disposed');
68
81
  this._dropTracked(m.name); // its listeners / timers go first, so nothing calls into the module while its dispose tears it down
69
82
  if (!m.dispose) continue;
70
- try { m.dispose(this); } catch (err) { reportError(this, err, coded('module-dispose', fmt(STRINGS.failed, { name: m.name })), { soft: true }); }
83
+ try { syncOnly(m.dispose(this), `dispose() of module ${m.name}`, true); } catch (err) { reportError(this, err, coded('module-dispose', fmt(STRINGS.failed, { name: m.name })), { soft: true }); }
71
84
  }
72
85
  this._abort.abort();
73
86
  tidy(() => this._untrackValidate());
74
87
  tidy(() => this._wraps?.dispose()); // engine.wrap: every wrapped method back on its object (a game object or api may outlive the engine)
88
+ tidy(() => this._adoptAdds?.remove()); // plain scene.add on a scene that outlives the engine must not call into a dead registry
89
+ tidy(() => this._gameLights?.dispose());
75
90
  tidy(() => this._picture?.dispose()); // dev tool: its scene watchers go with the engine
76
91
  tidy(() => this.debug.dispose()); // before the scene is disposed: undoes every diagnostic override and view (puts swapped materials back)
77
92
  for (const part of [this.saves, this.audio, this.time, this.commits, this.jobs, this.threads, this.stream, this.batching, this.rays, this.events]) tidy(() => part.dispose());
78
93
  clearHooks(this); this._afterTick = null;
79
- this.scene.traverse(o => disposeObject(o, tidy));
80
- // scene.environment is never disposed here: the engine's own maps (sky PMREM targets, the baseline room map) were freed above by their
81
- // owners, and anything else is the game's texture (a direct scene.environment write), which stays the game's to free
94
+ tidy(() => this.assets.forget(this.scene)); // references and leases first: each model copy gives its lease back, its animator stops
95
+ tidy(() => { const { mine, own } = engineParts(this); freeParts(this.scene, mine, { textures: true, own, tidy }); });
96
+ // scene.environment and a background texture are let go, never disposed here: the engine's own maps (sky PMREM targets, the baseline room map) were
97
+ // freed above by their owners, a skybox file is the asset cache's, and anything else is the game's texture (a direct write), which stays the game's to free
82
98
  this.scene.environment = null;
83
- tidy(() => { if (this.scene.background?.isTexture) this.scene.background.dispose(); });
99
+ if (this.scene.background?.isTexture) this.scene.background = null;
84
100
  for (const part of [this.assets, this.occlusion, this.post]) tidy(() => part.dispose());
85
101
  tidy(() => this._webglOnlyView?.remove()); this._webglOnlyView = null;
86
102
  tidy(() => this._gpu?.dispose());