threedog 2.0.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 (97) hide show
  1. package/CHANGELOG.md +15 -1
  2. package/core/assets/assetEntry.js +1 -1
  3. package/core/assets/assetPart.js +1 -1
  4. package/core/base/events.generated.js +1 -2
  5. package/core/engine/Engine.js +9 -5
  6. package/core/engine/copies.js +1 -1
  7. package/core/engine/modules.js +4 -4
  8. package/core/engine/services.js +5 -4
  9. package/core/inspect/DebugOverrides.js +2 -2
  10. package/core/inspect/describeRender.js +0 -7
  11. package/core/inspect/metadata.generated.js +106 -36
  12. package/core/inspect/pictureChecks.js +2 -27
  13. package/core/ops/sharedPoint.js +11 -2
  14. package/core/saves/saveApply.js +1 -1
  15. package/core/scene/adaptive.js +3 -2
  16. package/core/scene/pixelRatio.js +39 -17
  17. package/core/scene/sceneMethods.js +1 -1
  18. package/core/scene/tier.js +2 -33
  19. package/core/scene/view.js +14 -0
  20. package/core/time/skip.js +1 -1
  21. package/docs/CODEMAP.md +3 -3
  22. package/docs/api/ambience.md +2 -2
  23. package/docs/api/cameraRig.md +7 -0
  24. package/docs/api/engine.md +1 -1
  25. package/docs/api/events.md +1 -2
  26. package/docs/api/photo.md +5 -0
  27. package/docs/api/sky.md +10 -0
  28. package/docs/api/terrain.md +19 -0
  29. package/docs/api/tools.md +1 -1
  30. package/docs/recipes/05-props-bake.md +1 -1
  31. package/docs/recipes/07-flow-scenes-pause.md +3 -3
  32. package/docs/recipes/09-materials-lights-models.md +1 -1
  33. package/docs/recipes/14-custom-module.md +1 -1
  34. package/docs/recipes/15-perf.md +1 -1
  35. package/docs/recipes/16-dev-bridge.md +1 -1
  36. package/docs/recipes/18-world.md +1 -1
  37. package/docs/recipes/26-ui-parts.md +2 -2
  38. package/docs/recipes/40-scene.md +1 -1
  39. package/docs/recipes/51-capability-catalog.md +1 -1
  40. package/docs/recipes/52-around-the-picture.md +2 -2
  41. package/docs/recipes/55-mods-time-wrap.md +3 -3
  42. package/docs/recipes/57-control.md +1 -1
  43. package/docs/recipes/59-depth-post-effects.md +1 -1
  44. package/docs/recipes/60-judge-the-picture.md +5 -5
  45. package/examples/techniques/interior-light/README.md +1 -1
  46. package/examples/techniques/night-lights/README.md +1 -1
  47. package/examples/techniques/outlines-and-rim/README.md +1 -1
  48. package/examples/techniques/procedural-animation/README.md +1 -1
  49. package/examples/techniques/procedural-surface/README.md +1 -1
  50. package/examples/techniques/wet-road/README.md +1 -1
  51. package/modules/camera/contract.js +1 -1
  52. package/modules/characters/mover.contract.js +1 -1
  53. package/modules/characters/movers/rapier.js +7 -9
  54. package/modules/characters/player.js +1 -1
  55. package/modules/collision/Collision.js +1 -1
  56. package/modules/collision/grid.js +1 -1
  57. package/modules/content/index.js +2 -2
  58. package/modules/content/models.js +1 -1
  59. package/modules/flow/index.js +3 -3
  60. package/modules/gameplay/inventory.contract.js +1 -1
  61. package/modules/grid/tiles.js +6 -3
  62. package/modules/level/contract.js +2 -2
  63. package/modules/particles/Particles.js +1 -2
  64. package/modules/photo/pathTrace.js +1 -1
  65. package/modules/rigid/RigidBodies.js +13 -0
  66. package/modules/rigid/ragdoll.js +1 -1
  67. package/modules/settings/Settings.js +3 -2
  68. package/modules/settings/apply.js +4 -3
  69. package/modules/settings/sections.js +1 -1
  70. package/modules/sky/environment.js +1 -1
  71. package/modules/terrain/index.js +1 -2
  72. package/modules/timeline/Timeline.js +8 -4
  73. package/modules/vegetation/Vegetation.js +1 -1
  74. package/modules/vegetation/index.js +1 -1
  75. package/modules/weather/weatherDraw.js +1 -2
  76. package/package.json +1 -1
  77. package/render/PostFX.js +7 -7
  78. package/render/lightmap.js +1 -1
  79. package/render/lights.js +1 -2
  80. package/render/neutral.js +1 -1
  81. package/render/patches.js +3 -3
  82. package/render/probes.js +27 -2
  83. package/render/shaderErrors.js +1 -1
  84. package/render/shadows.js +1 -3
  85. package/types/core.d.ts +2 -4
  86. package/types/gameplay.d.ts +7 -2
  87. package/types/generated/ui/UI.d.ts +2 -1
  88. package/types/world.d.ts +4 -2
  89. package/ui/UI.js +18 -14
  90. package/ui/cursor.js +2 -2
  91. package/examples/action/.threedog/content-index.json +0 -1
  92. package/examples/perf-island/.threedog/content-index.json +0 -1
  93. package/examples/plain-picture/.threedog/content-index.json +0 -1
  94. package/examples/rc2d/.threedog/content-index.json +0 -1
  95. package/examples/styletest/.threedog/content-index.json +0 -1
  96. package/examples/webgpu-tsl/.threedog/content-index.json +0 -1
  97. package/examples/world/.threedog/content-index.json +0 -1
@@ -1,10 +1,9 @@
1
- // The renderer's pixel ratio has one owner, this file: every engine write goes through it, and it decides which request wins, so no two entries fight
2
- // by "who wrote last". Two modes:
3
- // ratio (the default) writeRatio: the game's and settings' engine.setPixelRatio (askRatio), adaptive resolution under it, the tier's default, a photo's
4
- // borrowed ratio.
1
+ // The renderer's pixel ratio has one owner, this file: every engine write goes through it, so no two entries fight by "who wrote last". Two modes:
2
+ // ratio (the default) the shared value render.pixelRatio is the ceiling: base the tier's default, the game's engine.setPixelRatio, the player's settings
3
+ // choice capping it (so their order never matters). Adaptive resolution writes under it, a photo borrows a ratio; writeRatio is the one write.
5
4
  // pixelSize (createEngine({ pixelSize }), engine.setPixelSize) one art pixel is k real screen pixels: the ratio is devicePixelRatio / k and fitPixelSize
6
5
  // alone sets the drawing buffer. Everything else asking for a ratio is held off, refused or kept for later: adaptive stops (engine.adaptive.on
7
- // reads false), the tier only updates what comes back when pixelSize ends, a photo keeps the art pixels, engine.setPixelRatio throws.
6
+ // reads false), the ceiling only updates what comes back when pixelSize ends, a photo keeps the art pixels, engine.setPixelRatio throws.
8
7
  // A direct renderer.setPixelRatio by the game is not refused (hard rule 4): the engine yields in both modes (view.pixelRatio in core/ops/owned.js).
9
8
  // tests/specs/pixel-size.mjs guards that no other file calls renderer.setPixelRatio.
10
9
  import { DEV, warnOnce } from '../base/validate.js';
@@ -31,26 +30,49 @@ export function writeRatio(e, p) {
31
30
  e._oPixelRatio.mark();
32
31
  }
33
32
 
34
- /**
35
- * engine.setPixelRatio. It is the game's (or settings') request: written even when the game took the ratio. It is also the new ceiling, or adaptive
36
- * resolution would climb back to the old one and undo the engine's own named entry where the raw three.js call stays. Adaptive writes through writeRatio.
37
- * @param {any} e @param {number} p
38
- */
33
+ /** The ceiling at its top again: adaptive resolution starts over from it (the ceiling moved, or the player turned adaptive off) @param {any} e */
34
+ export function topRatio(e) {
35
+ if (e._pixelSize != null) return;
36
+ writeRatio(e, e.adaptive.max);
37
+ Object.assign(e.adaptive, { lowered: false, from: null, good: 0 });
38
+ }
39
+
40
+ /** render.pixelRatio, made with engine.adaptive: its max follows the value (under pixelSize only that, for when pixelSize ends) @param {any} e */
41
+ export function defineRatio(e) {
42
+ const point = e.stacks.define('render.pixelRatio', { base: e.renderer.getPixelRatio(), save: false,
43
+ manual: "the settings entry is the player's ceiling: the game's ratio stays under it while the player keeps that choice" });
44
+ point.watch(() => { e.adaptive.max = point.value(); topRatio(e); });
45
+ }
46
+
47
+ /** engine.setPixelRatio, a game-layer set: written even when the game took the ratio (the named entry stays where the raw three.js call is) @param {any} e @param {number} p */
39
48
  export function askRatio(e, p) {
40
49
  if (e._pixelSize != null) throw codedError('pixel-conflict', `engine.setPixelRatio(${p}): pixelSize ${e._pixelSize} decides the ratio now. Keep pixelSize and drop this call, or call engine.setPixelSize(null) first`);
41
- writeRatio(e, p);
42
- Object.assign(e.adaptive, { max: p, lowered: false, from: null, good: 0 });
50
+ e.stacks.get('render.pixelRatio').take({ owner: 'game', set: p });
51
+ }
52
+
53
+ /**
54
+ * The player's settings choice; null hands the ratio back to the game (settings.reset). It stands in for the device default (engine layer: the player may
55
+ * pick above it). Under the default it is also a ceiling on the game (settings layer, which only restricts); at or above it (a 'high' preset is a share of 1)
56
+ * it limits nothing, so a full-quality choice never pulls the game's higher ratio down. Two entries, so their order does not change the result.
57
+ * @param {any} e @param {number | null} p
58
+ */
59
+ export function chooseRatio(e, p) {
60
+ const point = e.stacks.get('render.pixelRatio');
61
+ if (p == null || p >= e.adaptive.base) point.release('settings');
62
+ else point.take({ owner: 'settings', layer: 'settings', clamp: { max: p } });
63
+ if (p == null) point.release('settings.default');
64
+ else point.take({ owner: 'settings.default', layer: 'engine', set: p });
43
65
  }
44
66
 
45
67
  /**
46
- * The real device became known in start(): the tier's default ratio, unless the game chose one or does not leave the renderer to the engine. Under pixelSize
47
- * it is kept for when pixelSize ends.
48
- * @param {any} e @param {string} tier
68
+ * The device became known in start(): its default is the new base (the entries stay on top), unless the game chose one at creation or owns the renderer.
69
+ * engine.adaptive.base is only a mirror of that base, kept for readers (the settings presets' shares). @param {any} e @param {string} tier
49
70
  */
50
71
  export function tierRatio(e, tier) {
51
72
  if (!e._ownsRenderer || e._createParams.pixelRatio != null) return;
52
- const p = e.adaptive.base = defaultPixelRatio(dpr(), tier);
53
- if (e._pixelSize != null) e.adaptive.max = p; else askRatio(e, p);
73
+ const p = defaultPixelRatio(dpr(), tier);
74
+ e.stacks.get('render.pixelRatio').setBase(p);
75
+ e.adaptive.base = p;
54
76
  }
55
77
 
56
78
  /**
@@ -111,7 +111,7 @@ export const sceneMethods = {
111
111
  drawOnce(this.renderer, this.scene, camera, target);
112
112
  } finally { if (own) own.inside--; }
113
113
  },
114
- /** Render resolution, and the top adaptive resolution climbs back to. Throws while pixelSize is on (core/scene/pixelRatio.js) @param {number} p */
114
+ /** Render resolution, and the top adaptive resolution climbs back to. A ratio the player chose in settings below the device default caps it. Throws while pixelSize is on (core/scene/pixelRatio.js) @param {number} p */
115
115
  setPixelRatio(p) { askRatio(this, p); },
116
116
  /**
117
117
  * One art pixel becomes k real screen pixels, every one the same width at any display scale, and it stays so through a page zoom or a move to another display.
@@ -11,38 +11,6 @@ export function forcedTier(search = typeof location === 'undefined' ? '' : locat
11
11
  return TIERS.includes(t) ? t : null;
12
12
  }
13
13
 
14
- /** @type {WeakMap<any, Set<() => void>>} per engine: the parts that rebuild when engine.tier changes */
15
- const FOLLOWERS = new WeakMap();
16
- /**
17
- * Follow engine.tier while running: fn runs once after every change (a preset, the device found at start). Why one notice: the post chain followed
18
- * the tier and the cascades read it only when made, so a preset changed one and not the other (GPT review l2-render 2). Pixel ratio does not follow
19
- * here: a settings preset writes its own ratio, and a second writer would undo the player's. @param {any} e @param {() => void} fn @returns {{ remove(): void }}
20
- */
21
- export function onTierChange(e, fn) {
22
- if (!FOLLOWERS.has(e)) FOLLOWERS.set(e, new Set());
23
- FOLLOWERS.get(e).add(fn);
24
- return { remove: () => { FOLLOWERS.get(e)?.delete(fn); } };
25
- }
26
- /** @type {WeakMap<any, string>} per engine: the tier last announced by 'tier:change' */
27
- const ANNOUNCED = new WeakMap();
28
- /** The tier stack was just defined (core/engine/services.js): its first value is the baseline the first 'tier:change' differs from @param {any} e */
29
- export function tierDefined(e) { ANNOUNCED.set(e, e.tier); }
30
- /**
31
- * The tier stack's onChange (core/engine/services.js). The engine's own parts first, then the public 'tier:change' event: game code sizes what it
32
- * makes from engine.tier and follows this event (a shadow map, a pool), so a preset reaches it like it reaches the post chain.
33
- * The stack calls this on every take and release, also when the value stays (a preset equal to the device's tier, engine.tier written under a
34
- * preset), so the event fires only when the tier differs from the last one announced. Nothing during dispose: settings, disposed first, gives
35
- * its tier back then, and a follower would allocate (particles, a shadow map) on an engine being torn down. @param {any} e
36
- */
37
- export function tierChanged(e) {
38
- if (e.disposed) return;
39
- for (const fn of [...(FOLLOWERS.get(e) ?? [])]) fn();
40
- const t = e.tier;
41
- if (t === ANNOUNCED.get(e)) return;
42
- ANNOUNCED.set(e, t);
43
- e.events?.emit('tier:change', { tier: t });
44
- }
45
-
46
14
  /** The name under engine.saves.storageKey of a player's MSAA choice */
47
15
  export const MSAA_KEY = 'msaa';
48
16
  /**
@@ -55,7 +23,8 @@ export function storedMsaa(saveKey) {
55
23
 
56
24
  /**
57
25
  * Default render scale. High tier: the display scale up to 1.5. Low tier: at least 0.75 x display scale (1.5 on a 2x screen; a fixed 1 there
58
- * would be an upscaled blurry picture), never above 1.5 or the display scale.
26
+ * would be an upscaled blurry picture), never above 1.5 or the display scale. It is the base of render.pixelRatio (core/scene/pixelRatio.js), set from the
27
+ * device, not from tier changes while running: a preset's ratio is already a share of it.
59
28
  * @param {number} dpr @param {string} tier
60
29
  */
61
30
  export function defaultPixelRatio(dpr, tier) {
@@ -121,6 +121,20 @@ export function setProjection(e, projection = 'perspective', size = 20) {
121
121
  swapCamera(e, e._ortho.camera);
122
122
  }
123
123
 
124
+ /**
125
+ * engine.renderer.toneMapping as one owned value.
126
+ * @param {any} e
127
+ * @param {{ owned: boolean }} o owned: false when the game passed its own renderer
128
+ */
129
+ export function defineTone(e, { owned }) {
130
+ // who writes tone mapping now is one owned record like every other picture value (core/ops/owned.js),
131
+ // not a comparison against a remembered creation value here: a direct renderer.toneMapping write yields it ('three (engine yielded)'), quietly (once),
132
+ // because that write is the documented way to change the curve. A game-supplied renderer (owned false) starts manual: the engine never wrote it
133
+ e._oTone = defineOwned(e, { id: 'toneMapping', part: 'tone', key: 'toneMapping', read: () => e.renderer.toneMapping, objects: [e.renderer], once: true,
134
+ write: v => { e.renderer.toneMapping = v; }, levels: { manual: 'engine.renderer.toneMapping = THREE.AgXToneMapping' } });
135
+ if (owned) e._oTone.mark(); else e._oTone.manual(true, 'game renderer');
136
+ }
137
+
124
138
  /** @param {any} e */
125
139
  export function defineView(e) {
126
140
  const cam = () => e.camera;
package/core/time/skip.js CHANGED
@@ -115,7 +115,7 @@ export const skipMethods = {
115
115
  const end = () => { this._skipping = false; ctx.remove(); fz.remove(); off.remove(); };
116
116
  if (!(fade > 0)) { try { go(); } finally { end(); } return Promise.resolve(out); }
117
117
  const run = this.flow ? this.flow.transition(go, { fade, autosave: false, music: false })
118
- : (async () => { try { await fadeScreen(this, 1, { seconds: fade }); go(); } finally { await fadeScreen(this, 0, { seconds: fade }); } })();
118
+ : (async () => { try { await fadeScreen(this, 1, { seconds: fade, owner: 'skip' }); go(); } finally { await fadeScreen(this, 0, { seconds: fade, owner: 'skip' }); } })();
119
119
  return run.finally(end).then(() => out);
120
120
  },
121
121
  };
package/docs/CODEMAP.md CHANGED
@@ -179,7 +179,7 @@ Type = what the module may own (core/engine/moduleTypes.js): world, picture, act
179
179
  | engine:ready | core/engine/startup.js | content, flow, rigid |
180
180
  | flow:change | flow | — |
181
181
  | flow:transition | flow | — |
182
- | ground:change | terrain | characters, rigid |
182
+ | ground:change | terrain | characters, grid, rigid |
183
183
  | i18n:change | core/base/I18n.js | core/input/inputTouch.js, gameplay, hud, settings, timeline, ui/UI.js |
184
184
  | input:context | core/input/inputContext.js | — |
185
185
  | input:rebind | core/input/Input.js | gameplay, timeline, ui/UI.js |
@@ -194,7 +194,7 @@ Type = what the module may own (core/engine/moduleTypes.js): world, picture, act
194
194
  | link:enter | characters | — |
195
195
  | link:exit | characters | — |
196
196
  | module:disabled | core/base/errors.js | — |
197
- | module:restored | core/engine/modules.js | content |
197
+ | module:fresh | core/engine/modules.js | content |
198
198
  | music:change | music | — |
199
199
  | music:stinger | music | — |
200
200
  | net:close | net | — |
@@ -227,13 +227,13 @@ Type = what the module may own (core/engine/moduleTypes.js): world, picture, act
227
227
  | session:failed | core/saves/saveApply.js, core/saves/session.js | flow, rigid |
228
228
  | session:start | core/saves/session.js | — |
229
229
  | settings:change | settings | — |
230
- | settings:shadows | render/shadows.js | vegetation |
231
230
  | state:applied | core/inspect/UrlState.js | — |
232
231
  | state:placed | core/inspect/UrlState.js | camera |
233
232
  | state:replaced | core/engine/startup.js, core/saves/stateReplace.js | calendar |
234
233
  | template:stage | content | — |
235
234
  | terrain:chunkFailed | terrain | — |
236
235
  | terrain:void | rigid, terrain | — |
236
+ | tier:change | core/engine/services.js | — |
237
237
  | time:skip | core/time/skip.js | — |
238
238
  | timeline:end | timeline | — |
239
239
  | timeline:start | timeline | — |
@@ -3,8 +3,8 @@
3
3
  Ambience (ambience() module)
4
4
 
5
5
  - Options `AmbienceOptions`:
6
- - `rules?: import('./core').AmbienceRule[]`
7
- - `interval?: number`
6
+ - `rules?: import('./core').AmbienceRule[]` Rules added after the ones in createEngine({ audio: { ambience } })
7
+ - `interval?: number` Seconds between rule checks, default 0.25
8
8
 
9
9
  ## Methods and properties
10
10
  - `ambience.add(rule: AmbienceRule) → { remove(): void }` — Add one rule; returns a handle whose remove() fades the sound out and drops the rule. Example: `const h = engine.ambience.add({ sound: 'storm-wind', when: { weather: 'storm' }, volume: 0.5 });`
@@ -56,6 +56,13 @@ Current camera (one of followCamera / firstPersonCamera / fixedCamera / rtsCamer
56
56
  - `trackSmoothing?: number` (experimental) Head-follow smoothing
57
57
  - `holdDirection?: boolean` (experimental) Keep the direction when switching shots until the direction key is released
58
58
  - `ease?: Ease` Transition easing
59
+ - `position?: Vec3Like` Camera position
60
+ - `lookAt?: Vec3Like` Fixed point to look at (if omitted, it turns its head with the player)
61
+ - `track?: boolean` Turn its head with the player
62
+ - `fov?: number` Field of view (degrees)
63
+ - `at?: Vec3Like` Position used to judge the "nearest shot", defaults to position
64
+ - `projection?: 'perspective' | 'orthographic'` 'orthographic' draws this shot without perspective (isometric / 2.5D); default 'perspective'
65
+ - `size?: number` With projection 'orthographic' (required there): world units of view height; the width follows the aspect
59
66
  - rtsCamera options `RtsCameraOptions`:
60
67
  - `height?: number` Camera height above the focus (meters), default 30
61
68
  - `minHeight?: number` Zoom range (meters)
@@ -60,7 +60,7 @@
60
60
  - `engine.bakeProbes(opts: { bounds, spacing, resolution?, include?, owner? }) → Promise<ProbeSet>` — (experimental) Bake a grid of light probes from the scene as it is now: three's probe grid renders a cube at every grid point and keeps spherical harmonics, and every lit pixel inside the grid then takes its own interpolated light, on WebGL and WebGPU alike. The grid adds to whatever ambient light the scene has (hemi, environment), which the bake also saw: lower those where the probes take over (a warning and describe().render.probes say so). Outside the grid there is no probe light. A load-time cost, not per frame: 6 renders per probe, a few probes per task so the page keeps drawing; ship the result with `toJSON()` + `engine.loadProbes(json)` instead of baking at every start. Adding a grid recompiles the lit materials once: bake at start-up, not mid-play. Example: `const probes = await engine.bakeProbes({ bounds: { min: [-20, 0, -20], max: [20, 6, 20] }, spacing: 4, include: o => !o.userData.moving }); saveFile('probes.json', JSON.stringify(probes.toJSON()));`
61
61
  - `engine.loadProbes(json: ProbeData, opts?: { owner?: string }) → ProbeSet` — (experimental) A probe set from a file made by `handle.toJSON()` (no baking), on either renderer whichever one baked it. A wrong shape is refused with code `probes-data` and nothing is added. Example: `const probes = engine.loadProbes(await (await fetch('probes.json')).json());`
62
62
  - `engine.loadLightmap(file: string | ArrayBuffer, opts?: { owner?: string }) → Promise<Lightmap>` — (experimental) Put a baked lightmap on the scene: `threedog bake light` wrote the file from the meshes the game marked `userData.static = true`; this rebuilds each with its second UV set and sets plain `material.lightMap`, on WebGL and WebGPU alike. Call it once the level is built, with its lights as they will be played. Nothing runs per frame. Keep the sun real-time; the ambient light the bake saw (hemisphere, environment) has to go, or it counts twice. A wrong file is refused with code `lightmap-data` and nothing is changed. `material.lightMapIntensity` is yours. describe().render.lightmap says what was skipped, moved or doubled. Example: `const light = await engine.loadLightmap('light/level.lightmap');`
63
- - `engine.setPixelRatio(p: number)` — Render resolution, and the top adaptive resolution climbs back to. Throws while pixelSize is on
63
+ - `engine.setPixelRatio(p: number)` — Render resolution, and the top adaptive resolution climbs back to. A ratio the player chose in settings below the device default caps it. Throws while pixelSize is on
64
64
  - `engine.setPixelSize(k: number | null)` — One art pixel becomes k real screen pixels (createEngine({ pixelSize }) at runtime). While on, adaptive resolution stops, engine.setPixelRatio throws and a photo keeps the art pixels. null turns it off and brings the ratio from before back. Example: `engine.setPixelSize(3);`
65
65
  - `engine.raycast(origin: Vec3Like, dir: Vec3Like, opts?: RaycastOptions) → RayHit | null` — Ray: shoot from origin along dir, returns the nearest hit or null (by default only registered static objects are hit)
66
66
  - `engine.pick(ndcX: number, ndcY: number, opts?: RaycastOptions) → RayHit | null` — Shoot a ray through the camera from screen coordinates (-1..1, e.g. input.pointer.ndcX/ndcY). The ray comes from the camera as last drawn: a rig.yaw / rig.pitch write reaches it on the next drawn step, so several shots in one step with recoil between them cast from the rig's angles with engine.raycast (recipe 19)
@@ -22,7 +22,6 @@
22
22
  - `save:loaded` [slot: string] A save was loaded onto the running playthrough (saves.load / session.load); the argument is the slot name
23
23
  - `ui:open` [id: string] A window was opened (the argument is the window id, e.g. 'inventory')
24
24
  - `ui:close` [id: string] A window was closed
25
- - `settings:shadows` [on: boolean] Shadows were toggled
26
25
  - `settings:change` [values: Record<string, any>] A value in the settings menu changed (the argument is all setting values)
27
26
  - `tier:change` [{ tier: 'low' | 'high' }] engine.tier changed (device found at start, a preset, a write): resize what was sized from it
28
27
  - `post:add` [name: string] A post effect was added (its name)
@@ -97,7 +96,7 @@
97
96
  - `net:result` [{ seq: number; name: string; ok: boolean; code: string | null; value… Client (net): the host's answer to an op request (seq from ops.run's return value; tick is the host's), sent after the state it caused
98
97
  - `engine:error` [EngineError] A gameplay error: in development / testing gameplay is frozen; a release build keeps running and sends it once per site (engine.error holds the first; error severity levels, see engine.error)
99
98
  - `module:disabled` [{ name: string; message: string }] A picture or ui module errored and was disabled (the game continues)
100
- - `module:restored` [{ modules: any[] }]
99
+ - `module:fresh` [{ modules: any[] }]
101
100
  - `op:rolledBack` [{ op: string; parts: number }] An atomic op failed and its parts were put back (its own events already went out and stay): read derived state again. Not sent for a load's rollback (that ends in state:replaced)
102
101
  - `vehicle:enter` [{ character: Character; vehicle: Rideable }] A character boarded a vehicle
103
102
  - `vehicle:exit` [{ character: Character; vehicle: Rideable }] A character exited a vehicle
package/docs/api/photo.md CHANGED
@@ -5,6 +5,11 @@ Photo mode (photo() module)
5
5
  - Options `PhotoOptions` (also includes the fields of PhotoTakeOptions):
6
6
  - `maxAlbum?: number` (experimental) How many photos the album keeps at most, default 50
7
7
  - `pathTracer?: (() => Promise<any>) | null` (experimental) The game's import of its optional path tracer, called on the first photo.trace(): () => import('three-gpu-pathtracer/webgpu')
8
+ - `scale?: number` Resolution multiplier, default 1.6
9
+ - `shadowMapSize?: number` Shadow resolution (pixels), default 4096
10
+ - `bloom?: boolean | null` Bloom for the shot: null (default) keeps what the game's post has; true / false forces it for that shot only
11
+ - `quality?: number` Image quality 0–1
12
+ - `format?: string` Image format, e.g. 'image/jpeg'
8
13
 
9
14
  ## Methods and properties
10
15
  - `photo.take(opts?: PhotoTakeOptions) → PhotoShot` — Capture a photo now without checks. Gameplay takes photos through the op: engine.ops.run('photo.take') (checks canTake, logged)
package/docs/api/sky.md CHANGED
@@ -4,6 +4,16 @@ Sky dome and the sun / daylight / sky-color signals, from the calendar's time; i
4
4
 
5
5
  - Options `SkyOptions` (also includes the fields of Pick<SkyPictureOptions, 'clouds' | 'backdrop' | 'keyframes' | 'sunSize' | 'sunGlow' | 'sunBrightness' | 'moonColor' | 'moonBrightness' | 'starDensity' | 'dim'>):
6
6
  - `time?: string | number` The fixed time of day drawn while no calendar() is installed: 'HH:MM' or 0–1 (0.5 noon), default 0.33 (a sunset arena: sky({ time: '18:30' })). With calendar() the sky draws engine.calendar.timeOfDay and this option throws (start the day with calendar({ time }))
7
+ - `clouds?: SkyCloudOptions` Clouds in the sky (cloud cover follows the weather); see SkyCloudOptions
8
+ - `backdrop?: ColorLike` A flat background color in place of the dome (no gradient, horizon line, sun / moon disk, stars or clouds). Drawn as written (no tone mapping); a fog asked for in the default horizon color takes it (a fog.color of your own still wins). Leave out for the dome. recipes/08. Example: `backdrop: 0xefebe4`
9
+ - `keyframes?: SkyKeyframe[]` Rows [time, zenith, horizon, sunColor, ambient]. time: share of the day (0 = 00:00, 0.5 = noon), sorted, first row 0, last 1 (midnight again: same values as 0). They color the dome and the signals uSkyTop / uSkyHorizon, and light nothing: sunColor is the sun disk and the signal uSunColor, ambient dims a skybox and the weather's sky tint (recipe 08). Example: `[[0, 0x0b1030, 0x1c2440, 0x8090c0, 0.25], [0.5, 0x5a8fd0, 0xbcd4ea, 0xfff4e0, 1.1], [1, 0x0b1030, 0x1c2440, 0x8090c0, 0.25]]`
10
+ - `sunSize?: number` Sharpness exponent of the sun disk, default 900 (about 2 deg); larger = smaller. Not a size in degrees: 10 is ~20 deg, under ~3 the "disk" washes most of the sky toward the sun color
11
+ - `sunGlow?: number` Sun glow, default 0.18
12
+ - `sunBrightness?: number` (experimental) Sun brightness, default 6
13
+ - `moonColor?: ColorLike` (experimental) Color of the moon disk drawn at night, default 0xdcdcdc
14
+ - `moonBrightness?: number` (experimental) Brightness of the moon disk drawn at night, default 3
15
+ - `starDensity?: number` Share of the sky grid cells (0-1) that hold a star at night, default 0.0025 (0 = no stars). A probability, not a brightness: near 1 every cell is lit and the upper sky turns into a white sheet.
16
+ - `dim?: { tint?: boolean; stars?: boolean }` What the sky dims for every game unless the style says no (each default true; false turns that one off, the rest stay). The one place these picture decisions are switched: - tint: a sky.tint color (weather grey, a cave tint) dims with the sky's own light, so a grey rain tint stays dark at night. Example: `sky({ dim: { stars: false } }) // live: engine.sky.dim.tint = false`
7
17
 
8
18
  ## Methods and properties
9
19
  - `sky.keyframes(rows?: any[][]) → any[][]` — The day's colors, live: rows [time, zenith, horizon, sunColor, ambient] sorted from 0 to 1 (the same rows as sky({ keyframes })). Throws, changing nothing, on rows that are not sorted from 0 to 1. No argument: a copy of the rows in use (a picture gives them back on leaving). Example: `engine.sky.keyframes([[0, 0x101828, 0x202838, 0x8090b0, 0.3], [0.5, 0x4080c0, 0xc0d8e8, 0xffffff, 1.2], [1, 0x101828, 0x202838, 0x8090b0, 0.3]]);`
@@ -11,6 +11,25 @@ Procedural terrain, data part (terrain() module: chunks, heights, edits, collisi
11
11
  - `effects?: boolean` With material: false = draw it exactly as given, no cloud shadow / season / detail patch
12
12
  - `detail?: MaterialDetail | null` Detail layer over the ground: a noise, a texture asset name or your own glsl; defaults scale 0.25, strength 0.35, top-down world projection, multiply. Change it with engine.terrain.recolor({ detail })
13
13
  - `variation?: TerrainVariation` Ground color noise, baked into the chunks
14
+ - `seed?: number` Random seed; the same seed gives the same terrain
15
+ - `chunkSize?: number` Chunk edge length (meters), default 64
16
+ - `resolution?: number` Cells per chunk; smaller is more "low poly", default 16
17
+ - `waterLevel?: number` Water level (meters), default -Infinity = no water (terrainPreset() from
18
+ - `flatten?: FlattenZone[]` Flattened plots
19
+ - `biomeColors?: Record<string, string[]>` Ground type → palette color names (two are blended by noise); a type left out is neutral gray
20
+ - `steep?: SteepRule[]` Steep-slope color rule
21
+ - `heightmap?: { url?, size?, min?, max?, center?, outside?, … } | null` Heightmap (used when there is no height function): url grayscale image, size [width m, length m], min/max height (meters), center [x, z]
22
+ - `height?: ((x, z, n) => number) | string | null` Height generator: (x, z, n) => meters. Without one (and without a heightmap) the ground is flat at y = 0, a placeholder (dev warning). Runs in workers, so it must be pure (only its parameters and globals like Math); an outside variable throws at terrain() naming it. n = { fbm(x, z, octaves?), noise(x, z), hash(x, z, salt?), seed, waterLevel, params }. Example: `terrain({ height: (x, z, n) => 4 + 12 * n.fbm(x * 0.01, z * 0.01) })`
23
+ - `groundType?: ((x, z, h, slope, n) => string | null) | string | null` Ground type: (x, z, h, slope, n) => type name (null = 'default'). Pure, like height. Colors come from biomeColors[type]; vegetation rules and footsteps match by name. Example: `terrain({ groundType: (x, z, h, slope) => slope > 0.7 ? 'rock' : h < 2 ? 'beach' : 'grass' })`
24
+ - `params?: Record<string, any> | null` Plain data handed to height / groundType as n.params (a preset's settings); must be serializable
25
+ - `shading?: 'flat' | 'smooth' | 'texture'` How the ground gets its color: 'smooth' (default) blended per grid point / 'flat' one color and normal per triangle (low poly) / 'texture' per-chunk color map sampled per pixel, so color borders (a river bank) are not confined to triangle edges and the mesh can stay coarse. See recipes/53-ground-up-close.md.
26
+ - `colorResolution?: number` Texture shading: color map pixels per chunk edge (default 128, 64 on low-tier devices; independent of `resolution`)
27
+ - `normals?: 'smooth' | 'flat' | null` Texture shading only: lighting normals 'smooth' (default) / 'flat'
28
+ - `normalFn?: ((i, j, h, cell) => number[]) | string | null` Replace the smooth normal at grid point (i, j): (i, j, h, cell) => [nx, ny, nz] (any length; the engine normalizes). h(i, j) is a grid-point height, cell the grid spacing in meters. Pure, like height (workers get its source). Default: central difference of the neighbors. Example: `terrain({ normalFn: (i, j, h, cell) => [(h(i - 1, j) - h(i + 1, j)) / (2 * cell), 2, (h(i, j - 1) - h(i, j + 1)) / (2 * cell)] }) // flatter lighting`
29
+ - `diagonal?: 'fixed' | 'adaptive' | 'alternate'` How each cell is cut into two triangles: 'fixed' (default, the same diagonal everywhere) / 'adaptive' (along the diagonal with the smaller height difference, fewer zigzag ridges on slopes) / 'alternate' (flips every other cell). It is shape: engine.surface follows it
30
+ - `boundsPad?: { up?: number; radius?: number }` Chunk bounding sphere margin in meters (default { up: 3, radius: 8 }): center raised by `up`, radius grown by `radius`. Raise it when a shader moves vertices far
31
+ - `shape?: TerrainShape | null` World outline (default null = ground everywhere): an island, a floating rock, a coastline that ends
32
+ - `colors?: Record<string, ColorLike>` Palette: color name → color
14
33
 
15
34
  ## Methods and properties
16
35
  - `terrain.recolor(o?: TerrainRecolor)` — Change at run time what terrain({...}) baked in. colors, biomeColors, steep, variation, shading, normals rebuild every chunk (edits stay); detail only patches the engine's material. Throws under a draw part that replaced 'terrain-draw'. Example: `engine.terrain.recolor({ colors: { grass: 0x6a8a3a }, biomeColors: { meadow: ['grass'] } });`
package/docs/api/tools.md CHANGED
@@ -25,7 +25,7 @@
25
25
  - `toast(engine: Engine, text: string, { kind, ms }?: { kind?: string; ms?: number })` — Show a short message through the 'toast' UI part (default: top of the screen, gone after ms). A game restyles it, filters it by kind or turns it off with createEngine({ ui: { toast: false } }). kind says where it came from: 'info' (default), 'quest', 'item', 'save', 'error'.
26
26
  - `makeWindow(engine: Engine, opts: WindowOptions) → UIWindow` — A toggleable window
27
27
  - `worldToScreen(engine: Engine, pos: PositionLike) → ScreenPoint` — World coordinates (position or object) -> pixels from the canvas's top-left corner { x, y, onScreen, behind } (the UI root covers the canvas, so these place UI elements directly)
28
- - `fadeScreen(engine: Engine, to: number, opts?: { seconds?: number }) → Promise<void>` — Fade the whole screen to `to` (0 clear ... 1 fully covered) over `seconds` (default 0.5); the Promise resolves when the fade ends. fadeScreen(engine, 1, 0.5) throws in dev: fadeScreen(engine, 1, { seconds: 0.5 })
28
+ - `fadeScreen(engine: Engine, to: number, opts?: { seconds?: number; owner?: string }) → Promise<void>` — Fade the whole screen to `to` (0 clear ... 1 fully covered) over `seconds` (default 0.5); the Promise resolves when the fade ends. fadeScreen(engine, 1, 0.5) throws in dev: fadeScreen(engine, 1, { seconds: 0.5 })
29
29
  - `uiFocus(engine: Engine) → UIFocus` — (experimental) UI focus stack: windows, dialogue and cutscenes push in open order; the back key (Esc) goes to the top only; an empty stack hands it to the settings menu
30
30
  - `toggleOnKey(engine: Engine, win: { open, toggle }, action: string)` — (experimental) Window toggle key: call once per frame in a frame hook; opens on the action when closed, closes on another press when open
31
31
  - `parseClock(clock: string | number, hoursPerDay?: number) → number` — Clock time -> fraction of the day: parseClock('18:30') = 0.77; a number or numeric string ('0.25') is converted as is. hoursPerDay is hours per day, default 24
@@ -124,7 +124,7 @@ has keys, unless its bake entry says `source: 'file'`.
124
124
 
125
125
  Very detailed models (faces, sculpted shapes, hand-painted textures) are faster in Blender: export a GLB and register it (recipe 46).
126
126
 
127
- ## 2b. Many copies of one model: automatic batching
127
+ ## 2b. Many copies of one model: automatic batching (thousands of trees and rocks)
128
128
  Nothing to write for what the engine places: `engine.batching` (core) covers world record views (props, templates, grid items, `world.present`),
129
129
  `stream` builds and level files. When the same geometry + material (+ shadow flags) appears at least 8 times in one cell (256 m by default), those meshes are
130
130
  drawn by one real `THREE.InstancedMesh` per cell; fewer stay plain meshes. Each placed object stays in the scene with its own userData, record,
@@ -90,7 +90,7 @@ page's saves, so the title offers no Continue; on a running page it also ends th
90
90
  advances only on `engine.step`, so a `weather.set(name, { seconds: 0.1 })` made after `start()` is still changing (use `seconds: 0`), and an `onFrame` copy of a sky
91
91
  color is one frame old (share `engine.uniforms.uSkyHorizon` instead, recipe 08).
92
92
 
93
- ## 2. Changing scene / teleporting
93
+ ## 2. Changing scene / teleporting / spawning at a chosen spot (testing)
94
94
  ```js fragment
95
95
  // A level-based game: switch to another map
96
96
  await engine.flow.transition(async () => {
@@ -113,8 +113,8 @@ is a builder in the assets manifest (recipe 66, "Two areas built in code"); a `l
113
113
 
114
114
  Saves live in the browser's IndexedDB (falling back to localStorage, with one notice). `save()` / `remove()` / `load()` return a Promise (a failed write shows a notice), while
115
115
  `list()` / `export()` are synchronous (saves are read into memory at startup). Attachments, file backup and `storageKey`: `../api/saves.md`.
116
- For just a fade-to-black, without locking input or saving: `await fadeScreen(engine, 1, { seconds: 0.5 }); ...; await fadeScreen(engine, 0, { seconds: 0.5 });` (import from `threedog`).
117
- Fades inside a cutscene use the timeline steps `{ fade: 0.5 }`, `{ fade: 0.5, to: 0 }`.
116
+ For just a fade-to-black, without locking input or saving: `await fadeScreen(engine, 1, { seconds: 0.5 }); ...; await fadeScreen(engine, 0, { seconds: 0.5 });` (import from `threedog`). `{ owner }` names who holds the cover (default 'game'); a transition or a cutscene does not clear a cover the game holds.
117
+ Fades inside a cutscene use the timeline steps `{ fade: 0.5 }`, `{ fade: 0.5, to: 0 }`. A cutscene that ends dark hands its cover to the scene change: the next `flow.transition` lifts it (to lift it yourself, `fadeScreen(engine, 0, { owner: 'flow' })`).
118
118
 
119
119
  ## 2b. Input contexts (menus, vehicles, build mode)
120
120
  Who declares an action and who binds its keys: recipe 58.
@@ -26,7 +26,7 @@ thing that only changes pixels is a write on the module's three.js material. The
26
26
  separate package, `@threedog/terrain-noise`, because the shape of the world is gameplay. Post effects such as `bloom` / `ao` / `outline` come from
27
27
  `@threedog/post-effects` and go in as `plugins/` files (recipe 40 §1, chain order: recipe 52).
28
28
 
29
- ## 1. Materials are plain three.js
29
+ ## 1. Materials are plain three.js: which kind for which look
30
30
  `new THREE.MeshStandardMaterial(...)`, `MeshToonMaterial`, your own shading in TSL (WebGPU, recipe 56) or GLSL (WebGL only, recipe 43): all work as in any three.js project, and a plain material gets fog and
31
31
  cascaded shadows by itself. Keep them in `picture/materials.js` by name, and let other code ask for `picture.materials.wall`, so a change of picture touches one folder.
32
32
 
@@ -68,7 +68,7 @@ No subtypes: inside a type the differences are declarations (`provides`, `requir
68
68
  A module that does two kinds of thing is two definitions returned together (`weather()` returns the `weather` state and the `weatherDraw` drawing part;
69
69
  `engine.use(weather())` installs both). The warning comes once and refuses nothing: it names the module, its type, what it did, why not, and the fix. A game's own module may do what it needs; a split into two modules is usually the fix.
70
70
 
71
- ## 2. Hooks and order cheat sheet
71
+ ## 2. Hooks and order cheat sheet; who frees materials and textures when a module goes
72
72
  - `install(e, ctx)` returns the public object; `init(e, ctx)` (may be async) prepares at start; `ctx.track(handle)` ties a listener or timer to
73
73
  the module (next bullet but four); while `isReady(e)` returns false the loading screen waits for it
74
74
  (the hook is called isReady; `ready` is always a boolean property in the engine); `afterLoad(e, turn)` (may be async; recipe 20 says what `turn` is for) runs after a save loaded, to rebuild
@@ -127,7 +127,7 @@ tower.levels[1].object; // a plain THREE.LOD: read, replace, tower.addLevel(...
127
127
  then `skipOnLowTier` effects held off (a rebuild, so last; one that drops straight back waits longer). Your own knob: `{ name, down, up }`
128
128
  (down: false at its floor). `['resolution']` = scale only, `[]` = nothing.
129
129
  Only downward: what the game or player has off is no step, settings stay above it, `adaptive.on = false` puts every effect back.
130
- - `engine.setPixelRatio(p)` = the top it climbs back to; a direct `renderer.setPixelRatio` drops the resolution step; `pixelSize` stops it all (recipe 62 4b).
130
+ - `engine.setPixelRatio(p)` = the top it climbs back to, never above a ratio the player chose in settings below the device default (the slider, or a preset share under 1; `settings.reset('pixelRatio')` hands it back); a direct `renderer.setPixelRatio` drops the resolution step; `pixelSize` stops it all (recipe 62 4b).
131
131
  - `describe().render.scale`: `{ current, devicePixelRatio, upscaled, pixelSize, autoLowered, adaptive, floor, max }`. `upscaled: true` means current < devicePixelRatio, the picture
132
132
  is softer than the screen: if that looks wrong in a screenshot, check this before the style. Fixed quality: `pixelRatio: n` plus `adaptiveResolution: false`.
133
133
 
@@ -10,7 +10,7 @@ After changing code, ask the running game instead of writing a playwright script
10
10
  What the bridge changes lives in this session only: `op`, `step`, `state` and `js` alter the running game and its saves, never the level. To change
11
11
  the level, edit `content/*.js` (templates, props, npcs…) or the level model and reload the page.
12
12
 
13
- ## 1. Usage
13
+ ## 1. Usage: run a scripted check on the running game
14
14
  ```
15
15
  npm run dev -- my-game # terminal A: start the dev server first (for the engine example just npm run dev)
16
16
  threedog describe -w my-game # terminal B: look at the scene (inside the game folder you can omit -w)
@@ -152,7 +152,7 @@ function wander(rec, dt) {
152
152
  }
153
153
  ```
154
154
 
155
- ## 6. Near, far, camera, player
155
+ ## 6. Near, far, camera, player: a huge map that loads as you walk
156
156
  - **Near / far is decided by the gameplay anchor `world.anchor`**: by default the position of the player record (`engine.focus` when there is no
157
157
  player). A cutscene or photo mode moves the camera away, but the player's surroundings are still simulated as near: gameplay results do not depend
158
158
  on the camera. For a top-down strategy game centered on a base, set `W.anchor = baseObject`; set it back to `null` to restore the default.
@@ -14,7 +14,7 @@ Each name takes one value: `false` off · `true` default · `{ ...options }` def
14
14
  An end screen is a flow state (`engine.flow.define('gameOver', { freeze: true, lockInput: true })`, recipe 07 §1) showing a window with `closable: false` ("A window: results, game over", below).
15
15
  Only want different colors / layout? Use "Reskin" below, not a new part.
16
16
 
17
- ## Reskin: your picture on every default part, in one place
17
+ ## Reskin: change the look of every default part and menu, in one place
18
18
  The default parts are neutral gray on purpose. About ten lines give all of them the game's picture; do this before writing your own dialogue box or HUD:
19
19
  ```js
20
20
  const theme = { // picture/ui.js
@@ -193,7 +193,7 @@ const still = await engine.photo.trace({ samples: 128 }); // still.pathTraced.u
193
193
  ```
194
194
  HUD text follows the engine locale (`createEngine({ locale })`, default `'auto'` = the browser language): a game written in English sets `locale: 'en'`, or distance labels read `50 米` on a Chinese browser.
195
195
 
196
- ## 6. Settings menu: only the tabs the game needs
196
+ ## 6. Settings menu: only the tabs the game needs, quality options that turn off your pass
197
197
  ```js
198
198
  engine.use(settings({ sections: ['game', 'graphics', 'audio', 'controls', 'camera'] })); // default: graphics, audio, controls, language, saves
199
199
  // optional built-ins by name: 'game' (resume / load / back to title), 'camera' (sensitivity, invert Y, field of view; re-applied on 'camera:change')
@@ -13,7 +13,7 @@ Every root added with `engine.add` or `engine.scene.add` is registered: an id, w
13
13
  keeps. World records (template instances, props, pickups, NPCs, level nodes) share the same id space and the same query, so one question works for a
14
14
  plain three.js mesh and for a template instance alike. Only `engine.add(obj, { id })` gives it a stable id.
15
15
 
16
- ## 1. Two doors into one scene
16
+ ## 1. Two doors into one scene: add a mesh the save remembers, or plain scene.add
17
17
  A scene object comes in either of two ways, and both end up in the same scene:
18
18
 
19
19
  - **Plain three.js.** Build a mesh or group, `engine.scene.add(obj)` (or `engine.add(obj)`, the same registration). Nothing else is required. This is the right way for anything your code rebuilds
@@ -9,7 +9,7 @@
9
9
  that already exist: module definitions (`requires`, `optional`, `stage`, hooks), `engine.ops.define`, `engine.saves.define`,
10
10
  `engine.describe.add` and params schemas. There is no second list to keep in sync: a removed op is gone from the catalog at once.
11
11
 
12
- ## 1. Ask
12
+ ## 1. Ask: which effects, modules and ops exist and can be turned on
13
13
  ```js
14
14
  engine.catalog(); // short list: [{ id: 'sky', kind: 'module', state: 'running', stage: 'environment', ops: [], saves: ['sky'], time: 'fixed+skip' }, ...]
15
15
  engine.catalog('shop'); // one module expanded (below)
@@ -22,7 +22,7 @@ Which knob changes what on screen, and how to judge it for your picture: [recipe
22
22
  since it faces up), and three divides by π, so a total near π shows mid-tone albedos at roughly their own value under `AgXToneMapping`. AgX darkens light colors and pales saturated ones,
23
23
  so a pale or vivid palette needs more, or exposure. Walls and faces away from the sun get only their `N·L` share, and the environment (`scene.environment`) adds on top for Standard / Physical materials.
24
24
 
25
- ## Atmosphere: fog, sky
25
+ ## Atmosphere: fog, sky, view distance and field of view
26
26
 
27
27
  Fog and the placeholder lights: [recipe 34](34-environment-lighting.md). The sky: plain values and calls on `engine.sky`, [recipe 08](08-weather-sky.md). Shadows: `engine.shadows` and three.js, recipe 45. Water and weather: recipe 44.
28
28
 
@@ -46,7 +46,7 @@ engine.shaderTerms.season(kind => ({ glsl: 'diffuseColor.rgb = mix(diffuseColor.
46
46
  - `engine.shaderTerms.cloudShadow(spec)` and `engine.shaderTerms.season(spec)` put your own patch (`{ glsl, tsl, uniforms?, pars?, slot? }`, slot `lighting` / `color` by default) in place of the engine's on every material that carries the term, including ones built earlier; `false` removes the term; the handle's `remove()` gives the engine's back. The signals stay bound: `uWeatherCloud, uCloudShadow*` and `threedogCloudShadow(worldPos)`; `uFoliageTint` / `uGroundTint` / `uFoliageMix` / `uGroundMix`, `uGroundCover` (cover amount alone, x foliage, y ground) and `threedogSeason(color, kind)` (TSL: `season(color, kind)`). `season` also takes `kind => spec` (`'foliage'` | `'ground'`). A missing renderer form throws by name.
47
47
  - Cloud shadow values are signals: `engine.uniforms.uCloudShadow` (darkest, 0 = none), `uCloudShadowScale`, `uCloudShadowSpeed`. The term sits on engine materials and on what you pass to `applyEffects(mat)`; your own shader calls `threedogCloudShadow(worldPos)` (GLSL) or `cloudShadow(positionWorld)` (`threedog/tsl`). The engine adds it to no other material.
48
48
 
49
- ## Post effect chain
49
+ ## Post effect chain: your own pass, extra render passes
50
50
 
51
51
  Post-processing is an ordered list of named effects, and **`engine.post.add(x, { name, slot, order })` is the one way an effect gets
52
52
  in**: game code and the game's `plugins/` folder (a file that exports the Pass or effect) go through it, so every
@@ -41,7 +41,7 @@ engine.wrap(engine.inventory, 'add', (next, id, n = 1, o) => // a weight rule o
41
41
  carried() + weightOf(id) * n > 30 ? { ok: false, code: 'tooHeavy' } : next(id, n, o), { owner: 'weight' });
42
42
  ```
43
43
 
44
- ## The rules in full: `engine.mod(point, { owner, set | add | mul | clamp, layer?, for?, id? })`
44
+ ## The rules in full: `engine.mod(point, { owner, set | add | mul | clamp, layer?, for?, id? })`; which values are being changed now, `important` points
45
45
 
46
46
  | Layer (low to high) | Who writes it |
47
47
  |---|---|
@@ -109,11 +109,11 @@ checks that need this step's player position). The order never depends on which
109
109
  enter the bag wraps `add` and `transfer`.
110
110
  - Meant for public methods (the module's `contract.js` `api` list); a `_private` name warns once in dev and still works. `describe().wraps` lists `{ 'inventory.add': [owners] }`.
111
111
 
112
- ## Replacing a module
112
+ ## Replacing a module: swap in your own dialogue, camera or inventory system
113
113
 
114
114
  Two modules that each want to be "the" one (a sky, a tone-mapping stage, an inventory) declare an exclusive slot: `provides: ['inventory']`.
115
115
  Other modules `requires: ['inventory']` and work with whichever holds it. `engine.use(myInventory(), { replaces: 'inventory' })` unloads the
116
- holder (its tracked handles, its `ctx.mod` entries, its `dispose`) before the new install, and puts it back if that fails, with its save data and content sections. Either way the holder is a fresh install, so `module:restored` fires with the fresh modules once their `init` is done: content sections load again, as a `content.load` on a running game would (a newcomer with its own format may refuse a pack written for the old holder: that part stays out, with a warning naming the pack); game code redefines on that event what it defined by hand on the old holder. Level walls and solid props need no event: they go into whichever `collision` or `collider3d` is installed, also one that came late or came back.
116
+ holder (its tracked handles, its `ctx.mod` entries, its `dispose`) before the new install, and puts it back if that fails, with its save data and content sections. Either way the holder is a fresh install, so `module:fresh` fires with the fresh modules once their `init` is done: content sections load again, as a `content.load` on a running game would (a newcomer with its own format may refuse a pack written for the old holder: that part stays out, with a warning naming the pack); game code redefines on that event what it defined by hand on the old holder. Level walls and solid props need no event: they go into whichever `collision` or `collider3d` is installed, also one that came late or came back.
117
117
 
118
118
  Most replaceable modules have a contract (`modules/gameplay/*.contract.js`, `modules/*/contract.js`; object contract `modules/characters/vehicle.contract.js`; the rest and what cannot be replaced: CONVENTIONS.md "What can be replaced"): the api, fields, ops, events
119
119
  and save keys other code relies on, and nothing more (the engine's callers use only that surface). `await runContract(contract, () => myInventory(), { check })`
@@ -39,7 +39,7 @@ What to remember:
39
39
  - **Inside a module** use `ctx.control.take(ch, { ... })`: the owner defaults to the module, and everything it holds is handed back when the
40
40
  module goes (unloaded, rolled back, replaced).
41
41
 
42
- ## Who takes what
42
+ ## Who takes what: who drives the player body
43
43
 
44
44
  | Driver | Layer | Owner | Notes |
45
45
  |---|---|---|---|
@@ -8,7 +8,7 @@
8
8
  Fog you march through, light shafts, haze that thickens with distance, edge or focus effects: they all read the scene depth behind each pixel
9
9
  and turn it into a distance or a world position. This recipe writes one such effect with both forms, a three.js `Pass` (GLSL) for
10
10
  WebGLRenderer and a TSL node for WebGPURenderer, in one effect object. How effects are ordered, switched and tuned is recipe 52's
11
- [Post effect chain](52-around-the-picture.md#post-effect-chain); the TSL side in general is [recipe 56](56-webgpu-tsl.md#post-effects-as-nodes).
11
+ [Post effect chain](52-around-the-picture.md#post-effect-chain-your-own-pass-extra-render-passes); the TSL side in general is [recipe 56](56-webgpu-tsl.md#post-effects-as-nodes).
12
12
  For plain distance or height fog on materials, `engine.scene.fog` is enough (recipe 34).
13
13
 
14
14
  ## One effect, both renderers
@@ -36,15 +36,15 @@ shadow. `threedog examples pull sun-and-key-light` shows three routes side by si
36
36
  | Ambient / hemisphere, environment | the fill: how bright and what color the shaded side is | shadows are as deep as the style wants and still show shape; up-facing and down-facing faces differ; metals have something to reflect | your `picture/` code writes the hemisphere light and `scene.environment`, `scene.environmentIntensity` ([34](34-environment-lighting.md), [08 brightness](08-weather-sky.md#3-changing-sky-colors-sun-stars-the-day-and-night-sky)) |
37
37
  | Shadow softness | hard or blurred shadow edges | edges match the light (crisp under a clear sun, soft under cloud or for a gentle style); no stair-steps or speckle | `renderer.shadowMap.type`, `light.shadow.radius` ([45](45-cascaded-shadows.md)) |
38
38
  | Shadow distance, detail | how far shadows reach and how sharp small ones are | the area the player looks at has shadows; small props keep theirs; objects touch the ground (no gap under a foot) | `engine.shadows.box(sun, { extent })`, `engine.shadows.cascades(sun, { count, maxFar })`, `light.shadow.bias`, `mapSize` ([45](45-cascaded-shadows.md)) |
39
- | Bloom | light bleeding around bright pixels | the bright things you meant (sun, lamps, magic) glow and nothing else does; the picture does not turn milky | `engine.post.add(bloom())` from `@threedog/post-effects`, or three's `UnrealBloomPass` through `engine.post.add(pass)` ([52 Post chain](52-around-the-picture.md#post-effect-chain)) |
39
+ | Bloom | light bleeding around bright pixels | the bright things you meant (sun, lamps, magic) glow and nothing else does; the picture does not turn milky | `engine.post.add(bloom())` from `@threedog/post-effects`, or three's `UnrealBloomPass` through `engine.post.add(pass)` ([52 Post chain](52-around-the-picture.md#post-effect-chain-your-own-pass-extra-render-passes)) |
40
40
  | Light glow / halo | lamps, windows, signs that read as lit | a glowing object keeps its hue at the center (it is not a white block), has a halo where bloom is on, and lights its surroundings if it should | `material.emissive`, `engine.uniforms.uNight` ([09 §1b](09-materials-lights-models.md#night-glow-emissive-that-follows-daylight)); many lamps: `lightPool` ([09 §1b](09-materials-lights-models.md#1b-lights-and-stalls)) |
41
41
  | Water, sea | color with depth, waves, foam, what it reflects | shallow and deep read differently, the far sea meets the sky without a seam, foam sits where waves break | `engine.water.shader({ depthColor, foam })`, `engine.water.uniforms.uWave` ([44](44-water-weather-hooks.md)); own: three/addons `Water`, a `ShaderMaterial` ([44 own material](44-water-weather-hooks.md#water-your-own-material-reflections-refraction)) |
42
42
  | Wet ground | streets and stone after rain | wet is darker and glossier together, gloss shows reflections of something bright, puddles have soft edges | no engine picture: read `engine.uniforms.uRain`, then write `material.color`, `material.roughness` ([08 §7](08-weather-sky.md#7-wet-roads-and-puddles-after-rain)) |
43
- | Color grading | contrast, saturation and warm / cool shift of the whole frame | the frame has the mood you named; skin, foliage and the player's colors still read | `engine.post.add(lut())` from `@threedog/post-effects`, or `new LUTPass({ lut })` ([52 Post chain](52-around-the-picture.md#post-effect-chain)) |
43
+ | Color grading | contrast, saturation and warm / cool shift of the whole frame | the frame has the mood you named; skin, foliage and the player's colors still read | `engine.post.add(lut())` from `@threedog/post-effects`, or `new LUTPass({ lut })` ([52 Post chain](52-around-the-picture.md#post-effect-chain-your-own-pass-extra-render-passes)) |
44
44
  | Cloud shadow | moving dark patches on the ground | the patches drift slowly enough to read as clouds, are as dark as the sky is cloudy, and do not hide gameplay | `engine.uniforms.uCloudShadow`, `uCloudShadowScale`, `uCloudShadowSpeed`; clouds in the sky: `uCloudCover`, `uSkyCloudScale`, `uSkyCloudSpeed` on the dome ([08](08-weather-sky.md)); your own: `engine.shaderTerms.cloudShadow(spec)` ([52](52-around-the-picture.md)) |
45
- | Grain, vignette | film noise; darker frame corners | you notice the mood, not the effect; text and the HUD stay clean | `engine.post.add(grain())`, `engine.post.add(vignette())`; a pixel snippet: `engine.post.add({ name, fuse: { glsl }, slot: 'ldr' })` ([52 Post chain](52-around-the-picture.md#post-effect-chain)) |
46
- | Ambient occlusion | darker creases and contact corners | objects sit on the ground and corners have weight; no dark halo around thin things | `engine.post.add(ao())` ([52 Post chain](52-around-the-picture.md#post-effect-chain)) |
47
- | Outline | lines around shapes | lines help read shapes at play distance and match the style's line weight | `engine.post.add(outline())` ([52 Post chain](52-around-the-picture.md#post-effect-chain)), or three/addons `OutlinePass` |
45
+ | Grain, vignette | film noise; darker frame corners | you notice the mood, not the effect; text and the HUD stay clean | `engine.post.add(grain())`, `engine.post.add(vignette())`; a pixel snippet: `engine.post.add({ name, fuse: { glsl }, slot: 'ldr' })` ([52 Post chain](52-around-the-picture.md#post-effect-chain-your-own-pass-extra-render-passes)) |
46
+ | Ambient occlusion | darker creases and contact corners | objects sit on the ground and corners have weight; no dark halo around thin things | `engine.post.add(ao())` ([52 Post chain](52-around-the-picture.md#post-effect-chain-your-own-pass-extra-render-passes)) |
47
+ | Outline | lines around shapes | lines help read shapes at play distance and match the style's line weight | `engine.post.add(outline())` ([52 Post chain](52-around-the-picture.md#post-effect-chain-your-own-pass-extra-render-passes)), or three/addons `OutlinePass` |
48
48
  | Surface shading | how light falls across a surface (smooth, banded, flat) | materials that should differ (wood, stone, metal, cloth) differ in response, not only in color | `new THREE.MeshToonMaterial({ gradientMap })` or any material of yours; `applyEffects(mat, { lighting })`, `rampTexture` ([43](43-shader-patches-surfaces.md), [09](09-materials-lights-models.md)) |
49
49
  | God rays, volumetric fog | light shafts, fog thick in the air | shafts come from where the light is and fade when it leaves the screen | `lightShaft`, `sunShafts`, `lightVolumes` ([34](34-environment-lighting.md)); haze by depth ([59](59-depth-post-effects.md)) |
50
50
 
@@ -103,4 +103,4 @@ Rules (correctness):
103
103
  Sources: written for this repository, no code copied. Background: three.js `RectAreaLight` and `LightProbe` docs and examples (0.187), general
104
104
  architectural-visualization and game-lighting writing on window light, bounce and eye adaptation.
105
105
 
106
- This example is written in GLSL: it is the WebGL route (`threedog new-game --webgl`). A game on the default WebGPU route writes the same ideas in TSL (recipe 56).
106
+ This example is written in GLSL: it is the WebGL route (`threedog new-game --webgl`). TSL version: recipe 56.
@@ -92,4 +92,4 @@ Rules (correctness):
92
92
  Sources: written for this example; no code copied. Light units and falloff as documented for three.js physically based lights; the bloom pass
93
93
  is three's `UnrealBloomPass` through `@threedog/post-effects`.
94
94
 
95
- This example is written in GLSL: it is the WebGL route (`threedog new-game --webgl`). A game on the default WebGPU route writes the same ideas in TSL (recipe 56).
95
+ This example is written in GLSL: it is the WebGL route (`threedog new-game --webgl`). TSL version: recipe 56.
@@ -38,7 +38,7 @@ How to judge it: a shot at the real camera, with the busiest background the game
38
38
  - **Selection highlight**: a colored hull or `OutlinePass` on the selected object only.
39
39
 
40
40
  ## The engine helper (optional convenience)
41
- Copy `outlines.js` into a game; `main.js` (shapes) and `picture/` (this page's whole picture, plain three.js: lights, materials by name, the post pass) are only the demo. It gives `trackResolution(engine)` (the drawing-buffer size for screen-unit hulls),
41
+ Copy `outlines.js` into a game; only the demo around it is not part of the tool (`main.js` shapes; `picture/` has the lights, materials by name and the post pass). It gives `trackResolution(engine)` (the drawing-buffer size for screen-unit hulls),
42
42
  `addHull(mesh, { thickness, units: 'world' | 'screen', color })`, and `rimPatch({ color, strength, power, shadowSide })`.
43
43
 
44
44
  | route | how | width | cost |