threedog 1.4.0 → 2.1.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 (184) hide show
  1. package/CHANGELOG.md +48 -0
  2. package/README.md +13 -7
  3. package/bin/threedog.mjs +42 -0
  4. package/core/assets/assetEntry.js +1 -1
  5. package/core/assets/assetPart.js +1 -1
  6. package/core/base/Events.js +7 -1
  7. package/core/base/errorCodes.js +1 -1
  8. package/core/base/events.generated.js +2 -2
  9. package/core/engine/Engine.js +11 -7
  10. package/core/engine/copies.js +1 -1
  11. package/core/engine/moduleTypes.js +1 -1
  12. package/core/engine/modules.js +23 -6
  13. package/core/engine/page.js +1 -0
  14. package/core/engine/services.js +5 -3
  15. package/core/engine/startup.js +4 -1
  16. package/core/inspect/DebugOverrides.js +2 -2
  17. package/core/inspect/InspectPerf.js +1 -1
  18. package/core/inspect/describeRender.js +0 -7
  19. package/core/inspect/metadata.generated.js +139 -50
  20. package/core/inspect/pictureChecks.js +2 -27
  21. package/core/ops/control.js +3 -3
  22. package/core/ops/holds.js +8 -3
  23. package/core/ops/sharedPoint.js +11 -2
  24. package/core/saves/saveApply.js +3 -3
  25. package/core/saves/session.js +20 -4
  26. package/core/scene/adaptive.js +5 -2
  27. package/core/scene/pixelRatio.js +39 -17
  28. package/core/scene/sceneMethods.js +1 -1
  29. package/core/scene/things.js +3 -2
  30. package/core/scene/tier.js +2 -16
  31. package/core/scene/view.js +14 -0
  32. package/core/time/skip.js +1 -1
  33. package/docs/AI.md +2 -2
  34. package/docs/CODEMAP.md +8 -8
  35. package/docs/COMMANDS.md +2 -2
  36. package/docs/CONVENTIONS.md +1 -0
  37. package/docs/THREE.md +1 -1
  38. package/docs/api/ambience.md +2 -2
  39. package/docs/api/cameraRig.md +7 -0
  40. package/docs/api/engine.md +6 -3
  41. package/docs/api/events.md +3 -3
  42. package/docs/api/particles.md +1 -1
  43. package/docs/api/photo.md +5 -0
  44. package/docs/api/pickups.md +1 -1
  45. package/docs/api/post.md +1 -1
  46. package/docs/api/rigid.md +1 -1
  47. package/docs/api/sky.md +11 -1
  48. package/docs/api/terrain.md +19 -0
  49. package/docs/api/tools.md +1 -1
  50. package/docs/recipes/01-new-game.md +1 -1
  51. package/docs/recipes/03-items-pickups.md +1 -1
  52. package/docs/recipes/05-props-bake.md +1 -1
  53. package/docs/recipes/06-clock-events.md +3 -10
  54. package/docs/recipes/07-flow-scenes-pause.md +3 -4
  55. package/docs/recipes/09-materials-lights-models.md +1 -1
  56. package/docs/recipes/10-blender-level.md +2 -2
  57. package/docs/recipes/{11-vehicles.md → 11-physics.md} +13 -5
  58. package/docs/recipes/12-navmesh.md +3 -3
  59. package/docs/recipes/14-custom-module.md +6 -5
  60. package/docs/recipes/15-perf.md +1 -1
  61. package/docs/recipes/16-dev-bridge.md +1 -1
  62. package/docs/recipes/18-world.md +1 -1
  63. package/docs/recipes/20-content-actions-save.md +0 -1
  64. package/docs/recipes/21-camera.md +11 -1
  65. package/docs/recipes/26-ui-parts.md +2 -2
  66. package/docs/recipes/27-net.md +1 -1
  67. package/docs/recipes/29-grid.md +1 -1
  68. package/docs/recipes/34-environment-lighting.md +5 -3
  69. package/docs/recipes/40-scene.md +1 -1
  70. package/docs/recipes/44-water-weather-hooks.md +1 -1
  71. package/docs/recipes/45-cascaded-shadows.md +6 -3
  72. package/docs/recipes/51-capability-catalog.md +1 -1
  73. package/docs/recipes/52-around-the-picture.md +8 -8
  74. package/docs/recipes/53-ground-up-close.md +2 -2
  75. package/docs/recipes/55-mods-time-wrap.md +6 -8
  76. package/docs/recipes/57-control.md +1 -1
  77. package/docs/recipes/59-depth-post-effects.md +1 -1
  78. package/docs/recipes/60-judge-the-picture.md +7 -7
  79. package/docs/recipes/62-picture-code.md +13 -17
  80. package/examples/action/GAMEMAP.md +4 -2
  81. package/examples/action/picture/lights.js +3 -2
  82. package/examples/perf-island/GAMEMAP.md +2 -1
  83. package/examples/perf-island/picture/lights.js +3 -2
  84. package/examples/styletest/GAMEMAP.md +2 -2
  85. package/examples/styletest/picture/env.js +1 -2
  86. package/examples/techniques/contact-shadows/README.md +1 -1
  87. package/examples/techniques/day-night-grade/picture/lights.js +3 -1
  88. package/examples/techniques/interior-light/README.md +1 -1
  89. package/examples/techniques/interior-light/picture/lights.js +4 -2
  90. package/examples/techniques/modular-building/picture/lights.js +3 -2
  91. package/examples/techniques/night-lights/README.md +1 -1
  92. package/examples/techniques/night-lights/picture/lights.js +3 -1
  93. package/examples/techniques/night-lights/picture/post.js +2 -2
  94. package/examples/techniques/outlines-and-rim/README.md +1 -1
  95. package/examples/techniques/outlines-and-rim/picture/lights.js +3 -2
  96. package/examples/techniques/procedural-animation/README.md +1 -1
  97. package/examples/techniques/procedural-animation/picture/lights.js +3 -1
  98. package/examples/techniques/procedural-surface/README.md +1 -1
  99. package/examples/techniques/procedural-surface/picture/lights.js +3 -1
  100. package/examples/techniques/stylized-shading/picture/lights.js +3 -1
  101. package/examples/techniques/wet-road/README.md +1 -1
  102. package/examples/techniques/wet-road/picture/lights.js +3 -1
  103. package/examples/webgpu-tsl/GAMEMAP.md +4 -2
  104. package/examples/webgpu-tsl/picture/lights.js +3 -1
  105. package/examples/world/GAMEMAP.md +4 -3
  106. package/examples/world/picture/lights.js +3 -1
  107. package/examples/world/picture/post.js +2 -2
  108. package/llms.txt +33 -7
  109. package/modules/camera/common.js +22 -20
  110. package/modules/camera/contract.js +1 -1
  111. package/modules/characters/Character.js +2 -2
  112. package/modules/characters/NPC.js +7 -8
  113. package/modules/characters/index.js +8 -8
  114. package/modules/characters/mover.contract.js +1 -1
  115. package/modules/characters/movers/rapier.js +7 -9
  116. package/modules/characters/npcAvoid.js +2 -2
  117. package/modules/characters/player.js +11 -15
  118. package/modules/characters/playerStrings.js +1 -2
  119. package/modules/characters/seat.js +1 -1
  120. package/modules/collision/Collision.js +1 -1
  121. package/modules/collision/grid.js +1 -1
  122. package/modules/content/index.js +4 -3
  123. package/modules/content/models.js +1 -1
  124. package/modules/content/templates.js +3 -2
  125. package/modules/flow/index.js +8 -8
  126. package/modules/gameplay/Dialogue.js +1 -1
  127. package/modules/gameplay/Inventory.js +3 -3
  128. package/modules/gameplay/Quests.js +1 -0
  129. package/modules/gameplay/inventory.contract.js +1 -1
  130. package/modules/gameplay/pickups.js +1 -1
  131. package/modules/gameplay/questLog.js +0 -1
  132. package/modules/grid/index.js +1 -1
  133. package/modules/grid/tiles.js +6 -3
  134. package/modules/hud/index.js +2 -2
  135. package/modules/level/contract.js +2 -2
  136. package/modules/level/index.js +1 -1
  137. package/modules/music/Music.js +1 -1
  138. package/modules/nav/index.js +1 -1
  139. package/modules/net/sync.js +1 -1
  140. package/modules/particles/Particles.js +12 -5
  141. package/modules/particles/effect.js +17 -3
  142. package/modules/photo/pathTrace.js +1 -1
  143. package/modules/rigid/RigidBodies.js +23 -9
  144. package/modules/rigid/ragdoll.js +1 -1
  145. package/modules/rigid/sync.js +14 -0
  146. package/modules/settings/Settings.js +3 -2
  147. package/modules/settings/apply.js +4 -3
  148. package/modules/settings/sections.js +1 -1
  149. package/modules/sky/Sky.js +9 -4
  150. package/modules/sky/environment.js +5 -3
  151. package/modules/terrain/index.js +1 -2
  152. package/modules/timeline/Timeline.js +9 -6
  153. package/modules/vegetation/Vegetation.js +1 -1
  154. package/modules/vegetation/index.js +1 -1
  155. package/modules/weather/weatherDraw.js +1 -2
  156. package/modules/world/World.js +1 -0
  157. package/modules/world/index.js +1 -0
  158. package/modules/world/persist.js +1 -1
  159. package/package.json +6 -2
  160. package/render/PostFX.js +17 -12
  161. package/render/fx/postWebGPU.tsl.js +2 -1
  162. package/render/lightmap.js +1 -1
  163. package/render/lights.js +1 -2
  164. package/render/neutral.js +1 -1
  165. package/render/patches.js +3 -3
  166. package/render/probes.js +27 -2
  167. package/render/shaderErrors.js +1 -1
  168. package/render/shadows.js +1 -3
  169. package/types/core.d.ts +16 -9
  170. package/types/gameplay.d.ts +8 -3
  171. package/types/generated/modules/sky/Sky.d.ts +4 -4
  172. package/types/generated/render/PostFX.d.ts +2 -2
  173. package/types/generated/ui/UI.d.ts +2 -1
  174. package/types/physics.d.ts +1 -1
  175. package/types/world.d.ts +4 -2
  176. package/ui/UI.js +18 -14
  177. package/ui/cursor.js +2 -2
  178. package/examples/action/.threedog/content-index.json +0 -1
  179. package/examples/perf-island/.threedog/content-index.json +0 -1
  180. package/examples/plain-picture/.threedog/content-index.json +0 -1
  181. package/examples/rc2d/.threedog/content-index.json +0 -1
  182. package/examples/styletest/.threedog/content-index.json +0 -1
  183. package/examples/webgpu-tsl/.threedog/content-index.json +0 -1
  184. package/examples/world/.threedog/content-index.json +0 -1
package/CHANGELOG.md CHANGED
@@ -2,6 +2,54 @@
2
2
 
3
3
  What changed in each version and how a game upgrades.
4
4
 
5
+ ## 2.1.0 (2026-11-18)
6
+
7
+ Upgrading from 2.0: nothing to change unless your game listens to `module:restored` (now `module:fresh`) or `settings:shadows` (follow the shared point `shadows.enabled`); the player's render-scale choice is now a ceiling for `engine.setPixelRatio` (see below). The pre-2.0 `Unreleased` notes follow.
8
+
9
+ - Changed: a render scale the player picks in settings below the device default is now a ceiling: `engine.setPixelRatio` can only go under it, and the player's `settings.reset('pixelRatio')` hands the ratio back to the game (before, the last write won and the menu choice was overridden). Nothing to change in a game; to force a ratio regardless of the player, call three.js `renderer.setPixelRatio` (the engine yields)
10
+ - Changed: event `module:restored` is now `module:fresh` (it fires for modules that are fresh after a `replaces` or a failed one put back; the old name is gone, listen to `module:fresh`)
11
+ - Fixed: a cutscene that ends on a dark step hands its cover to the scene change, so the next `flow.transition` lifts it (a lift of your own: `fadeScreen(engine, 0, { owner: 'flow' })`)
12
+ - Fixed: the api pages and `threedog catalog` now list option keys a module's options interface inherits (terrain, photo, sky, cameraRig showed them as missing)
13
+ - Fixed: grid tiles now redraw on a ground the game swaps in with `engine.setGround` (they only followed level load and unload before)
14
+ - Fixed: `fadeScreen` gains an `owner` option (default `'game'`). Each owner keeps its own cover and the screen shows the darkest, so a `flow.transition` or a cutscene no longer clears a cover the game holds
15
+ - Removed: event `settings:shadows` (follow the shared point `shadows.enabled` instead)
16
+ - Fixed: contract check: a module that registers a save part its contract does not list now fails
17
+ - Fixed: a character with `mover: 'rapier'` but no rigid module now gets a dev warning (`module-requires`) and walks with the simple mover; the rapier mover no longer reads rigid's internals (rigid gains `layered`, `layerOf(collider)`, `fitPlayerCapsule(radius)`, all @internal)
18
+ - Changed: shared points follow changes through one entry (`watch(fn)`, `setBase(v)`, both @internal); the tier follower list and `onTierChange` are gone
19
+ - Fixed: check rules: R2 counts names read through `(await load(file)).name` in tools (no more false "unused" on `handRolled`), R10 skips `*.generated.js`, R22 no longer flags README and README.zh-CN sharing a sentence
20
+
21
+ ## 2.0.0 (2026-11-16)
22
+
23
+ A major version: some games need a change to upgrade (below). 1.5.0 was prepared but never published; its changes are part of this release.
24
+
25
+ **Upgrading from 1.x**
26
+ - Install the packages together at 2.0: `npm install threedog@2 @threedog/tools@2` (and `@threedog/post-effects@2`, `@threedog/terrain-noise@2` if you use them). The `threedog` command now comes with `threedog`, not `@threedog/tools`.
27
+ - `characters()` requires `world()`: a game that installs it without `world()` or `openWorld()` adds it before: `engine.use(world(), collision(), characters())`.
28
+ - The newGame / load reset runs in one declared order (below): a game's own `world:load` listener now always runs after the player is placed back. A game that relied on running before it moves that code into a module's `worldLoad(e, info)` hook.
29
+ - A module of your own that listened to `session:end`, `world:load` or `session:start` to reset itself keeps working; to run in the declared order, use the definition hooks `sessionEnd`, `worldLoad`, `sessionStart` instead.
30
+ - Something your picture sizes from `engine.tier` when it is made (a shadow map size, a light count) follows a later change only if you listen to `tier:change` (recipe 62).
31
+ - New games start from a neutral daytime palette with the sky as the fill light; existing games are not touched.
32
+
33
+ - Changed: new games (`threedog init`, `new-game`) start from a neutral, temperate daytime palette instead of grey: sky keyframes, warm sun, muted ground, water and player colors, all in the game's `picture/palette.js`, and with a sky the sky itself is the fill light (`engine.sky.environment`). The generated `CLAUDE.md` and the palette say it is a placeholder to restyle.
34
+ - Added: `sky.keyframes()` with no argument returns a copy of the rows in use, so a picture that sets its own can give them back when it leaves. A call with rows works as before and now returns them; nothing to migrate.
35
+ - Added: the `tier:change` event ({ tier }), fired after engine.tier changes (a settings preset, game code writing it). Something sized from the tier when made (a shadow map, a light budget) had no public way to follow it, so the template, the examples and the recipes read it once and kept a low-tier start's sizes after the player picked high; they now size at creation and follow this event. Particles: an effect's default max (60 on low) now follows a tier change in place.
36
+ - Changed: the session reset (newGame / load) runs in one declared order: modules join through sessionEnd(e), worldLoad(e, info) and sessionStart(e, info) on their definition, run in engine.moduleOrder (stage, then before / after), and only then the session:end / world:load / session:start events fire. Before, the order was install order. A game's own world:load listener now always runs after the player is placed back (before, one registered at boot ran before it).
37
+ - Fixed: a module installed before the provider it requires (the order engine.use(x, { replaces }) leaves) now inits during start() and is awaited; before, start() resolved without waiting for it, and a critical one failing there did not block the start.
38
+ - Fixed: on a headless page (tests, shots) a halt taken and removed left the engine running in real time; removing the last halt now gives back the state from before it (an explicit resume still goes live).
39
+ - Fixed: after a WebGL context is restored, the GPU timer behind adaptive resolution starts over (it read the last time from before the loss, so the resolution could stay low).
40
+ - Tools: a missing Playwright browser is one line with the install command (shot, perf, the dev bridge); other launch failures name their cause. init warns when a kept index.html, vite config or dev script would keep the game from starting. A timed-out MCP check ends its whole process tree.
41
+
42
+ - Changed: `characters()` now requires `world()`, and `engine.use()` says so at install. Before, `world` was listed as optional and only `characters.addPlayer()` (or the first NPC) threw at runtime, although the player and every NPC are world records. The docs' module lists that left `world()` out (recipes 10, 11, 12, the pickups page) now include it, and a guard test checks every `engine.use` list in the docs, templates and examples against what each module requires.
43
+ - New (docs): screen shake without taking the camera, recipe 21 §6b: an offset added in `engine.onRender` and put back in `onRender(fn, { when: 'after' })`; the camera's takeover warning now names it, and a guard test holds the hook order it relies on.
44
+ - Fixed: solver settings a game writes on `engine.rigid.world.integrationParameters` (such as `numSolverIterations`, and `contact_natural_frequency`) are kept when newGame or a load rebuilds the physics world. Before, they fell back to Rapier's defaults.
45
+ - Docs: recipe 11 §3c says when bodies can be added, that `rigid.impulse` wakes a sleeping body (explosions), and that resting stacks overlap a little because of Rapier's soft contacts, not a smaller collider (more iterations do not change it).
46
+ - Renamed: `docs/recipes/11-vehicles.md` is now `docs/recipes/11-physics.md` (it covers all rigid bodies, joints and explosions, not only vehicles). No alias.
47
+ - Docs: CONVENTIONS "One task, which entry" has a hit-stop / bullet-time row (`engine.mod('time.world', ...)`, `for` in real seconds; `clock.rate` is the calendar).
48
+ - Changed: the `threedog` command now comes with the `threedog` package, and `@threedog/tools` has no bin of its own (one package may own a bin name). It runs the commands of `@threedog/tools`; with only the engine installed, `npx threedog init` used to fail with "could not determine executable to run", and now prints the line that installs `@threedog/tools`. Release both packages together: `@threedog/tools` needs an engine that carries the bin.
49
+ - Changed: the package README and `llms.txt` open with one start sequence (install, `npx threedog init`, `npx threedog play`); `llms.txt` copies it from the README so the two cannot drift. `@threedog/tools` is no longer described as optional.
50
+ - New: a new game's `CLAUDE.md` has a short "Before you call it done" checklist (compare `threedog shot` with the target style, recipes 60 and 62, `@threedog/post-effects`).
51
+ - Fixed: on WebGPU each `engine.sky.environment()` rebuild stalled the game (100 ms to seconds, once per interval while the sky moved): every material reading the environment built again for the new map. The rebuild now refills the same map; on WebGL it was already cheap. A moving day can light the scene with its own sky.
52
+
5
53
  ## 1.4.0 (2026-11-15)
6
54
 
7
55
  - New: `threedog hub`, a local web page that lists your threedog games and shows each game's screenshot wall. The points to shoot are in the game's own `shots.json` (each point takes the options of `threedog shot`: `view`, `cam`, `pos`, `at`, `play`, `time`, `weather`, `wait`, `size`, `page`). After a file of a game changes and 30 s pass with no further change, the hub shoots all its points again, one game at a time, and the page updates by itself; each point keeps its last 10 pictures, and a point that fails shows its reason. From the page you can create a game (the `threedog init` starts), add an existing game folder, open a game or its asset gallery, and re-shoot by hand. `threedog hub --shortcut` (or the page's button) puts a desktop icon that opens it (Windows). The server answers only on 127.0.0.1 and refuses requests from other web pages.
package/README.md CHANGED
@@ -2,21 +2,27 @@
2
2
 
3
3
  A web 3D game engine on three.js 0.187: **core** (rendering, main loop, input, audio, saving, UI) -> **modules** (terrain, sky and weather, physics, characters, dialogue, inventory, quests... installed on demand); all art is the game's own (`picture/` folder, `assets.js`).
4
4
 
5
- ## Install
6
- This README describes threedog 1.0 (older releases do not match it; from 0.x read `docs/MIGRATING-1.0.md`, from 0.8.0 `CHANGELOG.md`, from 0.7.0 first `docs/MIGRATING-0.8.md`). To work on the engine itself, clone the [repository](https://github.com/penstic123-code/Threedog.js-Game-Engine), run `npm install`, then `npm run new-game -- my-game`. A game in its own folder:
5
+ ## Start here
6
+ One way to start a game, in an empty folder (the same for a person and for an AI agent):
7
7
  ```sh
8
8
  npm install threedog@1 three@~0.187.0
9
- npm install @threedog/terrain-noise@1 # optional: the noise terrain generator terrainPreset() (without one the ground is flat)
10
- npm install -D vite @threedog/tools@1 # optional: the vite preset and the threedog command line
9
+ npm install -D @threedog/tools@1 # the threedog commands: init, shot, check, how, dev, play, test
10
+ npx playwright install chromium # once per machine: the headless browser behind shot, play and test
11
+ npx threedog init # writes the game (main.js, picture/, content/) and its CLAUDE.md; never overwrites a file
12
+ npm install
13
+ npx threedog play # runs the game and reports it (--stop ends it); npm run dev opens it for a person
11
14
  ```
12
- Then let it set up the folder: `npx threedog init` (flags: `--open-world` for generated ground, sky, follow camera and a player; the default is a blank scene with a camera and a gray starter picture in `picture/`) writes index.html, main.js, vite.config.js, content/, CLAUDE.md and `.mcp.json` (Claude Code then starts the threedog MCP server by itself), never overwriting a file you have. Finish with `npm install` (for what the new files need) and `npm run dev`.
15
+ Then read the new `CLAUDE.md`: it lists what the engine already has, the loop (`threedog play`, `threedog shot`, `threedog check`), the picture recipes (60 judge the picture, 62 picture code) and `@threedog/post-effects` (bloom, AO, color grading). `npx threedog how "<task words>"` finds everything else.
16
+
17
+ `init` flags: `--open-world` (generated ground, sky, follow camera and a player; it adds `@threedog/terrain-noise`), `--pixel`, `--scene-only`, `--webgl` (WebGL and GLSL instead of WebGPU and TSL). The default is a blank scene with a camera and a neutral, correctly lit starting picture in `picture/` (gray surfaces, white sun, soft shadows, AO, light bloom). It also writes `.mcp.json`, so Claude Code opened in the folder starts the threedog MCP server by itself.
18
+ `npx threedog` comes with this package and runs the commands of `@threedog/tools`; without that package installed it prints the line to install it. To work on the engine itself, clone the [repository](https://github.com/penstic123-code/Threedog.js-Game-Engine), run `npm install`, then `npm run new-game -- my-game`. This README describes threedog 1.x (from 0.x read `docs/MIGRATING-1.0.md`).
13
19
  `three` is a peer dependency: your game and the engine share one copy. Types for three come with the engine (`@types/three`, same version), so `// @ts-check` JS and TypeScript both see real three.js types.
14
20
 
15
- ## Minimal usage
21
+ ## The code, in short (the `--open-world` start)
16
22
  ```js
17
23
  import 'threedog/tsl'; // WebGPU with TSL, what a new game starts on; a game started with --webgl leaves this line out and the renderer option below
18
24
  import { createEngine, presets, openWorld } from 'threedog';
19
- import { terrainPreset } from '@threedog/terrain-noise'; // optional terrain generator (npm install @threedog/terrain-noise)
25
+ import { terrainPreset } from '@threedog/terrain-noise'; // the noise terrain generator (init --open-world adds it; without one the ground is flat)
20
26
 
21
27
  const engine = createEngine({ canvas: document.getElementById('view'), renderer: 'webgpu' }); // no picture code yet: gray placeholders
22
28
  engine.use(openWorld({ camera: 'follow', seed: 7, terrain: terrainPreset() }));
@@ -0,0 +1,42 @@
1
+ #!/usr/bin/env node
2
+ // The `threedog` command. Why it lives in the engine package and only forwards: `npx threedog init` names the package called threedog, so
3
+ // with the engine installed alone npx used to fail with "could not determine executable to run", and an AI concluded the package has no init.
4
+ // The commands themselves stay in @threedog/tools (dev-only weight: playwright, vite, typescript); this file runs them in the same process,
5
+ // or says the one line to install them. Only one package may own a bin name, so @threedog/tools has no bin of its own.
6
+ import { readFileSync, existsSync, realpathSync } from 'node:fs';
7
+ import { fileURLToPath, pathToFileURL } from 'node:url';
8
+ import { join, dirname } from 'node:path';
9
+
10
+ // The project's own install first (walking up from where the command runs): under pnpm's strict layout or Yarn PnP the engine's real folder
11
+ // cannot see @threedog/tools even when the project has it. Then the engine-relative lookup (a hoisted install, this repository's workspaces).
12
+ function findTools() {
13
+ for (let dir = process.cwd(); ; dir = dirname(dir)) {
14
+ const pkg = join(dir, 'node_modules', '@threedog', 'tools');
15
+ if (existsSync(join(pkg, 'package.json'))) return join(pkg, 'bin', 'threedog.mjs');
16
+ if (dirname(dir) === dir) break;
17
+ }
18
+ try { return join(dirname(fileURLToPath(import.meta.resolve('@threedog/tools/paths'))), 'bin', 'threedog.mjs'); } catch { return null; }
19
+ }
20
+
21
+ const found = findTools();
22
+ const { version } = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
23
+ const install = `npm install -D @threedog/tools@${version.split('.')[0]}`;
24
+ if (!found) {
25
+ console.error(`✗ The threedog commands (init, shot, check, how, dev) come with @threedog/tools, which is not installed here. Run:
26
+ ${install}
27
+ npx threedog ${process.argv.slice(2).join(' ') || 'init'}`);
28
+ process.exit(1);
29
+ }
30
+ // A half-installed or broken copy: one repair line instead of a module-not-found stack
31
+ const broken = what => { console.error(`✗ @threedog/tools is installed but incomplete (${what}). Reinstall it: ${install}`); process.exit(1); };
32
+ if (!existsSync(found)) broken(`no ${found}`);
33
+ // The real path: through a link (workspaces, pnpm) Node's module-not-found message names real paths, so the check below compares like with like
34
+ const toolsBin = realpathSync(found);
35
+ // The tools entry runs when argv[1] is its own path (it is also imported by tests, where it must not run)
36
+ process.argv[1] = toolsBin;
37
+ try { await import(pathToFileURL(toolsBin).href); }
38
+ // Only a missing file OF the tools package counts as a broken install; any other error (a game's own missing import) stays as it is
39
+ catch (e) {
40
+ const norm = s => String(s).replaceAll('\\', '/').toLowerCase(), first = e?.message?.split('\n')[0] ?? '';
41
+ if (e?.code === 'ERR_MODULE_NOT_FOUND' && norm(first).includes(`module '${norm(dirname(dirname(toolsBin)))}/`)) broken(first); else throw e;
42
+ }
@@ -91,7 +91,7 @@ function checkNeeds(name, e, g) {
91
91
  }
92
92
 
93
93
  /** Load an entry as a task in engine.loading; a registered, non-critical file that fails resolves to its fallback */
94
- export function fetchEntry(a, e) {
94
+ function fetchEntry(a, e) {
95
95
  if (a._disposed) return NEVER;
96
96
  if (a._stale(e)) retireEntry(a, e);
97
97
  if (e.promise) { if (e.load) e.load.waits++; return e.promise; }
@@ -18,7 +18,7 @@ const BONES = 'node "{node}" in {url} holds a skinned mesh whose bones are outsi
18
18
  * Geometry and materials are shared with the file (SkeletonUtils clone: a skinned part gets its own bones); the file's scene is not changed.
19
19
  * @returns {{ scene: THREE.Group, animations: THREE.AnimationClip[] }}
20
20
  */
21
- export function partOf(gltf, node, url) {
21
+ function partOf(gltf, node, url) {
22
22
  const all = [];
23
23
  gltf.scene.traverse(o => { if (o !== gltf.scene && o.name) all.push(o.name); });
24
24
  const name = all.includes(node) ? node : sanitize(node);
@@ -139,9 +139,15 @@ export class Events {
139
139
  const s = this.map.get(name); if (!s) { if (this.traceSize > 0) this._note(name); return; }
140
140
  const prev = this._cur;
141
141
  if (this.traceSize > 0) this._cur = `ev:${this._note(name)}`; // handlers run under this event: what they emit names it as parent
142
- try { for (const fn of [...s]) { if (!s.has(fn)) continue; /* removed by an earlier listener of this emit */ try { const r = fn(...args); if (this._scopes.length) syncOnly(r, `a listener of '${name}' inside a load`, true); } catch (err) { if (this._scopes.length) this._scopes.at(-1).push({ name, err }); else if (this.onError) this.onError(name, err); else console.error(`[event ${name}]`, err); } } }
142
+ try { for (const fn of [...s]) { if (!s.has(fn)) continue; /* removed by an earlier listener of this emit */ this._call(name, fn, args); } }
143
143
  finally { this._cur = prev; }
144
144
  }
145
+ /** @internal run one handler the way a listener runs: an error is collected by the load in progress (it fails it) or reported, never thrown to the caller.
146
+ * Shared with the session reset steps (engine._resetStep), so a module's reset hook fails or reports exactly as the listener it replaced did */
147
+ _call(name, fn, args) {
148
+ try { const r = fn(...args); if (this._scopes.length) syncOnly(r, `a listener of '${name}' inside a load`, true); }
149
+ catch (err) { if (this._scopes.length) this._scopes.at(-1).push({ name, err }); else if (this.onError) this.onError(name, err); else console.error(`[event ${name}]`, err); }
150
+ }
145
151
  /** @internal trace entries old -> new */
146
152
  _ordered() { const t = this._trace; return this._th ? t.slice(this._th).concat(t.slice(0, this._th)) : t; }
147
153
  /** @internal Record one trace entry, returns its id */
@@ -424,7 +424,7 @@ export const ERROR_CODES = {
424
424
  docs: ['recipes/27-net.md', 'api/net.md'],
425
425
  fix: 'net() needs role \'host\' or \'client\' and a transport; reconnect() is for clients only.' },
426
426
  'rigid-misuse': {
427
- docs: ['recipes/11-vehicles.md §3', 'api/rigid.md'],
427
+ docs: ['recipes/11-physics.md §3', 'api/rigid.md'],
428
428
  fix: "The message says which: an id already used by another body or vehicle (give each its own id); a mesh that another body or a character already owns (one object, one physics owner: remove the first, or give the second its own object); 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)." },
429
429
  'settings-row': {
430
430
  docs: ['api/settings.md'],
@@ -11,8 +11,8 @@ export const ENGINE_EVENTS = [
11
11
  'save:loaded',
12
12
  'ui:open',
13
13
  'ui:close',
14
- 'settings:shadows',
15
14
  'settings:change',
15
+ 'tier:change',
16
16
  'post:add',
17
17
  'water:add',
18
18
  'water:remove',
@@ -85,7 +85,7 @@ export const ENGINE_EVENTS = [
85
85
  'net:result',
86
86
  'engine:error',
87
87
  'module:disabled',
88
- 'module:restored',
88
+ 'module:fresh',
89
89
  'op:rolledBack',
90
90
  'state:replaced',
91
91
  'vehicle:enter',
@@ -28,7 +28,7 @@ import { recordSweep } from '../../render/recordSweep.js';
28
28
  import { dressNodeTwins } from '../../render/patches.js';
29
29
  import { lifecycleMethods, clearHooks, checkCanvasUsable } from './lifecycle.js';
30
30
  import { createAdaptive, GpuTimer } from '../scene/adaptive.js';
31
- import { firstRatio, noteDeviceBox, pixelSizeOn } from '../scene/pixelRatio.js';
31
+ import { firstRatio, defineRatio, noteDeviceBox, pixelSizeOn } from '../scene/pixelRatio.js';
32
32
  import { watchRejections } from '../base/errors.js';
33
33
  import { createMovement } from '../scene/movement.js';
34
34
  import { moduleMethods } from './modules.js';
@@ -43,7 +43,7 @@ import { installPictureWriters } from '../inspect/pictureWriters.js';
43
43
  import { ownHook } from './moduleTypes.js';
44
44
  import { defineShadows } from '../../render/shadows.js';
45
45
  import { defineTerms } from '../../render/terms.js';
46
- import { defineView, checkCamera } from '../scene/view.js';
46
+ import { defineView, defineTone, checkCamera } from '../scene/view.js';
47
47
  import { nameShaderErrors } from '../../render/shaderErrors.js';
48
48
  import { probeMethods } from '../../render/probes.js';
49
49
  import { lightmapMethods } from '../../render/lightmap.js';
@@ -130,8 +130,8 @@ export class Engine {
130
130
  const canvas = canvasIn ?? (gpuWanted ? undefined : rendererIn?.domElement);
131
131
  this.movement = createMovement(movement); // character radius / height / slope / step height: the single copy shared by collision, physics and nav
132
132
  if (opts.lights !== false) warnOnce(NO_PICTURE);
133
- // a game-supplied renderer keeps its settings: the engine configures pixel ratio, size, tone mapping and shadows only on a renderer it created itself.
134
- // One write on every renderer: info.autoReset = false below, because the frame stats count a whole frame, not each render call
133
+ // a game-supplied renderer keeps its settings: the engine configures pixel ratio, tone mapping and shadows only on a renderer it created itself.
134
+ // Written on every renderer: the drawing size follows the canvas box (core/scene/canvasBox.js; a frame of another size would stretch), and info.autoReset = false below, because the frame stats count a whole frame, not each render call
135
135
  const owned = !rendererIn || gpuWanted;
136
136
  this._ownsRenderer = owned; // dispose() releases the WebGL context only of a renderer the engine built
137
137
  if (owned) checkCanvasUsable(canvas);
@@ -165,10 +165,14 @@ export class Engine {
165
165
  /** @internal */ this.baseBackgroundHex = this.baseBackground.getHex();
166
166
  this.scene.background = this.baseBackground;
167
167
  this.stacks = new Stacks(this); // shared points: before the lights, whose shadow size reads engine.tier, and the first engine.shadows / engine.post point
168
+ // the one quality value (engine.tier): the device gives the base, the player's preset sets over it; settingsSet: here the player's choice is a choice, not a
169
+ // restriction. Defined before the lights, the first part that follows it (stacks.get('tier').watch: lights, post chain, cascades, terrain, weather)
170
+ this.stacks.define('tier', { kind: 'value', base: this._deviceTier, save: false, settingsSet: true });
168
171
  /** Placeholder lights { sun: DirectionalLight, hemi: HemisphereLight }: neutral and still; createEngine({ lights: false }) leaves them out of the scene @type {{ sun: any, hemi: any }} */
169
172
  this.lights = createDefaultLights(this, { add: lights !== false });
170
173
  // the engine's own renderer gets soft shadows by default; tone curve and environment stay three.js's defaults
171
174
  defineShadows(this, { owned }); // engine.shadows: master switch, cascades, box, budget on the lights a game hands in (render/shadows.js)
175
+ defineTone(this, { owned }); // engine.renderer.toneMapping as one owned value (core/scene/view.js)
172
176
  recordRender(this, { owned }); // baseline for describe().render (after the shadow defaults are written): which values the engine set
173
177
  // Dev server only. A bundled build (npm test, threedog shot, release) is one minified file, so a stack there names assets/index-x.js:1 for every value: a
174
178
  // wrong answer. Written as the literal, not DEV_SERVER: only the literal folds at build time, so the tracker leaves a release bundle altogether
@@ -248,6 +252,7 @@ export class Engine {
248
252
  this.ui.get('loading')?.show({});
249
253
  const adaptiveOn = adaptiveResolution && !headless;
250
254
  this.adaptive = createAdaptive({ on: adaptiveOn, target: targetFps, max: r.getPixelRatio(), held: () => pixelSizeOn(this) });
255
+ defineRatio(this); // render.pixelRatio: base, the game's setPixelRatio and the player's choice as entries; adaptive.max follows it
251
256
  this._gpu = adaptiveOn ? new GpuTimer(timerContext(r)) : null; // GPU frame time for adaptive resolution where the browser offers the timer query
252
257
  // follow the canvas's own CSS box, not the window: a canvas in a page section or editor panel renders at its own size.
253
258
  // The window event stays for a canvas outside the page (no box, falls back to the window) and for moves that do not resize the canvas
@@ -285,12 +290,11 @@ export class Engine {
285
290
 
286
291
  get waterLevel() { return this.ground.waterLevel; }
287
292
  /** 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'} */
288
- get tier() { return this.stacks.has('tier') ? this.stacks.get('tier').value() : this._deviceTier; }
293
+ get tier() { return this.stacks.get('tier').value(); }
289
294
  /** The device's tier, the base under a player's preset */
290
295
  set tier(t) {
291
296
  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
297
+ this.stacks.get('tier').setBase(t); // setBase tells the tier's followers once; a bare write to base told nobody
294
298
  }
295
299
  /** True once the world is built (phase 'ready' or 'running'): fixed steps, ops and rendering run from here on @type {boolean} */
296
300
  get ready() { return this.phase === 'ready' || this.phase === 'running'; }
@@ -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 = '1.2.0'; // kept equal to package.json by the "[guard] engine copies" spec
9
+ export const VERSION = '2.1.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
 
@@ -27,7 +27,7 @@ export const MODULE_TYPES = {
27
27
  /** How engine.skip advances a module (the skipKind field): what each word means is on ModuleDefinition in types/core.d.ts */
28
28
  export const SKIP_KINDS = ['exact', 'approx', 'step', 'none'];
29
29
  /** The time hooks a module definition may carry (engine.catalog and the generated metadata list the ones a module has) */
30
- export const TIME_HOOKS = ['fixed', 'frame', 'afterRender', 'skip', 'afterLoad'];
30
+ export const TIME_HOOKS = ['fixed', 'frame', 'afterRender', 'skip', 'sessionEnd', 'worldLoad', 'afterLoad', 'sessionStart'];
31
31
 
32
32
  const STRINGS = {
33
33
  badSkip: "module {name} has skipKind '{kind}'. Fix: use one of {list}",
@@ -6,6 +6,8 @@
6
6
  // Stages (first to last): control timeline, camera -> ground terrain, level -> environment weather, sky, water
7
7
  // -> gameplay interactions, dialogue, trigger zones -> effects particles, settings, objective markers
8
8
  // -> late (the default) characters, physics, navigation... -> audio music
9
+ // The session reset steps (sessionEnd, worldLoad, afterLoad, sessionStart: the sequence is declared in core/saves/session.js) run in this same order, so an
10
+ // order between two modules' resets is declared like any other (stage, before / after), never left to install order or to when a listener was added.
9
11
  // before / after: lists of module or capability names (not-installed names are ignored; a capability means whichever module provides it now, so the order follows a replaces);
10
12
  // they order modules only inside one stage. One that contradicts the stage order (a 'control' module with after: ['sky']) makes use() throw naming both modules and stages;
11
13
  // a cycle makes use() throw on the spot, naming the modules on it. A contradiction reached through provides throws the same way: an order must not turn into a hint after a replaces.
@@ -28,7 +30,7 @@
28
30
  // ctx.mod(point, o) = ctx.track(engine.mod(point, { ...o, owner: ctx.name })): a module's changes to shared values go with it too.
29
31
  // ctx.rule(name, default, names?) = a replaceable rule on a plain shared point: .decide(id, facts) gives a built-in name, false for manual, or what the game's function answered.
30
32
  // ctx.input.define(name, { context }) / ctx.input.bind(name, keys): the module's input declarations and bindings, gone with it too.
31
- // ctx.ops.define, ctx.saves.define, ctx.ui.define, ctx.stream.addReadyCheck, ctx.budget.metric, ctx.things.addSource / explainWith, ctx.ground.provide / addColliders:
33
+ // ctx.ops.define, ctx.saves.define, ctx.ui.define, ctx.stream.addReadyCheck, ctx.budget.metric, ctx.things.addSource / explainWith / recordsLoaded, ctx.ground.provide / addColliders:
32
34
  // the same registrars, recorded in the one scope with kind, id, owner and instance (engine.catalog(name).resources reads it). Built-in modules register only through
33
35
  // these (tools/tests/module-boundaries). A save part leaving keeps its data as unattached data of the save (Saves.define), so a module unloaded for a while loses nothing.
34
36
  // Every install is its own instance (engine._modInst: name -> token): a ctx belongs to one install, not to a name. An async init that resumes after
@@ -38,7 +40,7 @@
38
40
  // Exclusive slots: provides: ['inventory'] takes each named slot (a kind 'one' shared point, core/ops/sharedPoint.js) for the module before its install;
39
41
  // a second provider is shared-taken. requires may name a slot instead of a module. engine.use(mine(), { replaces: 'inventory' }) unloads the
40
42
  // holder first (its handles, slot, drawing parts, dispose), and puts it back if the new install fails, with its save data and content sections (_putBack). Either way the holder now is a fresh install that has none of what
41
- // others put into the old one, so 'module:restored' tells whoever fed it, once its init is done: they feed it again. The word means "this module is back and holds nothing yet", not that its old state came back; its save data did, its definitions did not.
43
+ // others put into the old one, so 'module:fresh' tells whoever fed it, once its init is done: they feed it again. The word means "this module is back and holds nothing yet", not that its old state came back; its save data did, its definitions did not.
42
44
  // critical: true on a module makes a failed init() stop engine.start() with the reason; without it a failed init is reported (picture / ui: disabled;
43
45
  // other types: error tiers in errors.js) and start() goes on.
44
46
  // Dependencies: requires must be installed first (throws if missing). optional is a soft dependency: an array is only recorded (for GAMEMAP and rule R16);
@@ -196,19 +198,19 @@ export const moduleMethods = {
196
198
  if (removed.length && plan.length) this._tellRestored(plan);
197
199
  },
198
200
  /**
199
- * @internal 'module:restored' for these fresh modules, after their init: what is fed then lands as it does on a running game, where content.load comes after init
201
+ * @internal 'module:fresh' for these fresh modules, after their init: what is fed then lands as it does on a running game, where content.load comes after init
200
202
  * (a level's own url would otherwise overtake the pack's level). Nothing in flight tells at once. One replaced again meanwhile is not told about
201
203
  */
202
204
  _tellRestored(modules) {
203
205
  const tell = () => {
204
206
  const live = modules.filter(m => this.modules.get(m.name) === m);
205
- if (live.length && !this.disposed) this.events.emit('module:restored', { modules: live });
207
+ if (live.length && !this.disposed) this.events.emit('module:fresh', { modules: live });
206
208
  };
207
209
  if (this.loading._inits.size) this.loading.settled().then(tell); else tell();
208
210
  },
209
211
  /**
210
212
  * @internal a failed swap leaves the game as it was: the replaced modules install fresh (their old handles already went), their save parts take back their data as a part registered
211
- * late does (Saves.define), and 'module:restored' tells whoever fed them, because a fresh install has no definitions, as after a swap that worked: content sections load again (modules/content).
213
+ * late does (Saves.define), and 'module:fresh' tells whoever fed them, because a fresh install has no definitions, as after a swap that worked: content sections load again (modules/content).
212
214
  * What game code defined by hand it defines again on that event. Colliders of the level and of props need no event: they check the holder themselves.
213
215
  * @param {any[]} removed in install order @param {string[]} order the module names to go back to @param {string | null} base the new-game state to go back to
214
216
  */
@@ -289,6 +291,19 @@ export const moduleMethods = {
289
291
  },
290
292
  /** @internal the one gate for module hooks, the loop's and afterLoad (saveApply.js): registered (init not run yet), initializing, failed, disabled, blocked run none */
291
293
  _runsHooks(name) { return this._modState.get(name) === 'running' && !this._modBlocked.has(name); },
294
+ /**
295
+ * @internal One step of the session reset (session.js declares the sequence): every installed module's hook of that name, in moduleOrder, each run like
296
+ * an event listener (Events._call: inside a load an error fails the load, outside it is reported). The gate is the one the listeners these hooks
297
+ * replaced had: a module whose init failed lost its listeners (_dropTracked), so it gets no reset either; one still initializing gets it (it guards itself)
298
+ */
299
+ _resetStep(step, ...args) {
300
+ if (this.events.muted > 0) return; // an atomic op's rollback puts plain data back and announces nothing (opsAtomic.js): it is no reset either
301
+ for (const name of this.moduleOrder) {
302
+ const m = this.modules.get(name), st = this._modState.get(name);
303
+ if (typeof m?.[step] !== 'function' || st === 'failed' || st === 'disabled' || st === 'disposed') continue; // disabled: a picture / ui module switched off after a throw lost its listeners too (errors.js disableModule)
304
+ this.events._call(`${name}.${step}`, () => m[step](this, ...args), []);
305
+ }
306
+ },
292
307
  /**
293
308
  * @internal may this install (token from engine._modInst) still register? It is the one under its name and not closed. Closed = its signal aborted (_dropTracked:
294
309
  * unload, rollback, failed init), set before the cleanup runs, so a late callback and a remove() that calls ctx.track during that cleanup are both refused (design 6.1)
@@ -423,7 +438,9 @@ export const moduleMethods = {
423
438
  ui: { define: owned('ui', (n, factory, def) => this.ui.define(n, factory, def)) },
424
439
  stream: { addReadyCheck: owned('ready', (n, fn) => this.stream.addReadyCheck(n, fn)) },
425
440
  budget: { metric: owned('metric', (n, read, o) => this.budget.metric(n, read, o)) },
426
- things: { addSource: ifLive(src => own('source', name, this._things.addSource(src))), explainWith: ifLive(fn => own('explainer', name, this.explainWith(fn))) },
441
+ things: { addSource: ifLive(src => own('source', name, this._things.addSource(src))), explainWith: ifLive(fn => own('explainer', name, this.explainWith(fn))),
442
+ // the records source replaced its records wholesale (a load): core runs the worldLoad reset step, then tells the game (session.js step 2)
443
+ recordsLoaded: info => { this._resetStep('worldLoad', info); this.events.emit('world:load', info); } },
427
444
  ground: { provide: provideGround, addColliders: ifLive(fn => own('colliders', name, this.addGroundColliders(fn))) },
428
445
  };
429
446
  },
@@ -87,6 +87,7 @@ export class Page {
87
87
  toast(engine, engine.t('page.gpuBack'));
88
88
  // a restored context has empty shadow maps, and a map kept on purpose (autoUpdate off, a budget) would stay blank until the game next asked for it
89
89
  setShadowUpdate(engine.renderer, engine.scene, { now: true });
90
+ engine._gpu?.reset(); // its timer queries belonged to the lost context: adaptive resolution would keep reading the last time from before the loss
90
91
  engine.events.emit('page:contextrestored');
91
92
  }, { signal });
92
93
  // WebGPU fires no canvas event, three calls this hook. Its WebGL2 backend calls it too, but there the listeners above report the loss and its return
@@ -41,7 +41,6 @@ import { defineSkipOp } from '../time/skip.js';
41
41
  import { installThings } from '../scene/thingOps.js';
42
42
  import { Plugins } from './plugins.js';
43
43
  import { watchGameLights } from '../scene/gameLights.js';
44
- import { tierChanged } from '../scene/tier.js';
45
44
 
46
45
  /**
47
46
  * Create the engine services on `engine` (called once from the Engine constructor, after the renderer, scene and uniforms exist).
@@ -82,8 +81,11 @@ export function createServices(engine, { canvas, validate, locale, strings, save
82
81
  engine._urlState = new UrlState(engine, { fromUrl: urlState });
83
82
  // who holds the engine still: three named stacks (stacks.js: same owner rules as every shared quantity, holders in describe); haltLoop / freeze / takeCamera in holds.js
84
83
  defineHoldStacks(engine);
85
- // the one quality value (engine.tier): the device gives the base, the player's preset sets over it. settingsSet: on this point the player's choice is a choice, not a restriction
86
- engine.stacks.define('tier', { kind: 'value', base: engine._deviceTier, save: false, settingsSet: true, onChange: () => tierChanged(engine) }); // the post chain and cascades follow it (core/scene/tier.js onTierChange)
84
+ // the 'tier' shared point is defined in Engine.js right after the stacks, before the lights that follow it (followers: engine.stacks.get('tier').watch(fn))
85
+ // the public 'tier:change' event (game code sizes what it makes from engine.tier): fires when the tier differs from the last one announced, so a preset equal to the device's tier says nothing.
86
+ // Nothing during dispose: settings gives its tier back then, and a follower would allocate on an engine being torn down
87
+ let announced = engine.tier;
88
+ engine.stacks.get('tier').watch(() => { if (engine.disposed) return; const t = engine.tier; if (t === announced) return; announced = t; engine.events.emit('tier:change', { tier: t }); });
87
89
  engine.commits = new Commits(engine); // background results that affect gameplay take effect on a fixed tick (see Commits.js)
88
90
  engine.ops = new Ops(engine); // one entry point for actions (define / run / can / list / recent), see Ops.js
89
91
  engine.views = new Views(engine); // named fixed camera views for repeatable screenshots (Views.js)
@@ -70,7 +70,10 @@ export const startupMethods = {
70
70
  const ls = this.ui.get('loading'), t0 = performance.now(), L = this.loading; // measure
71
71
  const ms = t => Math.round(performance.now() - t); // measure
72
72
  const timing = {}; // module name -> { init, ready } in ms (ready = time spent waiting for isReady)
73
- for (const m of this.modules.values()) if (m.init && !this._modBlocked.has(m.name)) { // a blocked one inits if its provider comes up (modules.js)
73
+ // In waves: a module that waited for its provider (one installed later, e.g. use(x, { replaces })) inits in the next wave, awaited like the rest,
74
+ // so start() resolves only after it and critical still blocks. It used to go to _initWaiting below, which does not wait
75
+ const due = () => [...this.modules.values()].filter(m => m.init && !this._modBlocked.has(m.name) && this._modState.get(m.name) === 'registered');
76
+ for (let wave = due(); wave.length; wave = due()) for (const m of wave) if (this.modules.get(m.name) === m && !this._modBlocked.has(m.name) && this._modState.get(m.name) === 'registered') { // m itself: one replaced meanwhile inits in the next wave
74
77
  const task = L._begin(m.name, 'module', { critical: !!m.critical });
75
78
  task.phase('build');
76
79
  ls?.update({ progress: 0.1, text: this.t('common.preparing', { name: this.moduleName(m) }) });
@@ -1,5 +1,5 @@
1
- // engine.debug: diagnostic overrides with an owner ("show me this without X") and the diagnostic view modes. They change only what the screen shows,
2
- // never the game state or a save, and describe().scene.overrides lists them so an AI knows the picture is not the real state. Why an owner: a tool
1
+ // engine.debug: diagnostic overrides with an owner ("show me this without X") and the diagnostic view modes. They change only what the screen shows
2
+ // (and hot-swap an asset or a shader in place, which assetHot.js and hotGlsl.js do), never the game state or a save, and describe().scene.overrides lists them so an AI knows the picture is not the real state. Why an owner: a tool
3
3
  // (view mode, probe, AI session) removes everything it set with one clear(owner), whatever it forgot to remove(); a tool never touches another owner's.
4
4
  // Generic on purpose: a patch is { visible?, material?, apply? }, and apply(obj) -> undo covers any other picture (the view modes in debugView.js use it).
5
5
  // All of engine.debug is core (it works without the debug panel); the F3 panel module only adds engine.debug.panel next to it (composition).
@@ -22,7 +22,7 @@ const NEXT = {
22
22
  lights: 'many lights: light pool, engine.use(lightPool({ point: 8 })) then engine.lightPool.add(torch, { intensity: 4, distance: 8 })',
23
23
  shadowLights: 'set castShadow = false on the lights that can go without; a point light draws six shadow maps',
24
24
  shadowMaps: 'set castShadow = false on the lights that can go without; a point light draws six shadow maps',
25
- shadowMapSize: 'pick light.shadow.mapSize from engine.tier in the picture code',
25
+ shadowMapSize: 'size it with engine.shadows.mapSize(light, n) from engine.tier in the picture code, again on tier:change',
26
26
  };
27
27
 
28
28
  // "first frame 1840 ms = script 210 + construct 40 + ..." (engine.startup.phases; startup.js); empty before the first frame
@@ -6,7 +6,6 @@ import { NoToneMapping, LinearToneMapping, ReinhardToneMapping, CineonToneMappin
6
6
  import { SHADOW_TYPES } from '../../render/shadowTypes.js';
7
7
  import { rv } from '../base/math.js';
8
8
  import { hex } from './MaterialInfo.js';
9
- import { defineOwned } from '../ops/owned.js';
10
9
  import { slotHolders } from '../scene/pictureSlots.js';
11
10
  import { isShown } from '../base/util.js';
12
11
  import { backendFacts } from '../../render/backend.js';
@@ -60,12 +59,6 @@ export function describePicture(e) {
60
59
  * @param {{ owned: boolean }} o owned: false when the game passed its own renderer
61
60
  */
62
61
  export function recordRender(e, { owned }) {
63
- // who writes tone mapping now is one owned record like every other picture value (core/ops/owned.js),
64
- // not a comparison against a remembered creation value here: a direct renderer.toneMapping write yields it ('three (engine yielded)'), quietly (once),
65
- // because that write is the documented way to change the curve. A game-supplied renderer (owned false) starts manual: the engine never wrote it
66
- e._oTone = defineOwned(e, { id: 'toneMapping', part: 'tone', key: 'toneMapping', read: () => e.renderer.toneMapping, objects: [e.renderer], once: true,
67
- write: v => { e.renderer.toneMapping = v; }, levels: { manual: 'engine.renderer.toneMapping = THREE.AgXToneMapping' } });
68
- if (owned) e._oTone.mark(); else e._oTone.manual(true, 'game renderer');
69
62
  e._renderBase = { owned };
70
63
  }
71
64