threedog 0.1.0 → 0.2.1

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 (244) hide show
  1. package/README.md +4 -4
  2. package/core/Animator.js +1 -0
  3. package/core/Assets.js +28 -0
  4. package/core/DebugOverrides.js +143 -0
  5. package/core/Describe.js +14 -3
  6. package/core/Engine.js +44 -72
  7. package/core/Events.js +59 -1
  8. package/core/I18n.js +2 -2
  9. package/core/Inspect.js +12 -32
  10. package/core/InspectScene.js +7 -3
  11. package/core/MaterialInfo.js +32 -0
  12. package/core/Ops.js +43 -59
  13. package/core/Saves.js +5 -4
  14. package/core/UrlState.js +3 -2
  15. package/core/Vars.js +1 -0
  16. package/core/Views.js +49 -0
  17. package/core/actor.js +2 -2
  18. package/core/assetReport.js +83 -0
  19. package/core/catalog.js +169 -0
  20. package/core/checks.js +67 -0
  21. package/core/claims.js +51 -0
  22. package/core/debugView.js +76 -0
  23. package/core/describeRender.js +51 -0
  24. package/core/describeText.js +11 -4
  25. package/core/errorCodes.js +33 -0
  26. package/core/errorHints.js +6 -1
  27. package/core/grid.js +127 -0
  28. package/core/gridLoad.js +19 -0
  29. package/core/holds.js +106 -0
  30. package/core/lifecycle.js +1 -0
  31. package/core/lightWatch.js +23 -3
  32. package/core/look/coreParts.js +112 -0
  33. package/core/look/layers.js +136 -0
  34. package/core/look/part.js +173 -0
  35. package/core/look/report.js +79 -0
  36. package/core/look/write.js +86 -0
  37. package/core/loop.js +22 -16
  38. package/core/modules.js +19 -5
  39. package/core/opsAtomic.js +31 -0
  40. package/core/opsCheck.js +25 -14
  41. package/core/opsFail.js +20 -0
  42. package/core/opsHistory.js +6 -6
  43. package/core/opsRun.js +77 -0
  44. package/core/params.js +132 -0
  45. package/core/renamed.js +22 -0
  46. package/core/saveApply.js +2 -2
  47. package/core/sceneMethods.js +9 -34
  48. package/core/services.js +73 -0
  49. package/core/startup.js +3 -1
  50. package/core/styleParts.js +11 -9
  51. package/core/thingExplain.js +68 -0
  52. package/core/thingOps.js +35 -24
  53. package/core/things.js +15 -1
  54. package/core/util.js +11 -0
  55. package/core/validate.js +23 -7
  56. package/docs/AI.md +93 -114
  57. package/docs/API.md +8 -9
  58. package/docs/CODEMAP.md +67 -53
  59. package/docs/COMMANDS.md +21 -7
  60. package/docs/CONVENTIONS.md +22 -11
  61. package/docs/THREE.md +3 -3
  62. package/docs/api/assets.md +3 -0
  63. package/docs/api/characters.md +5 -2
  64. package/docs/api/collision.md +4 -0
  65. package/docs/api/content.md +1 -0
  66. package/docs/api/engine.md +23 -14
  67. package/docs/api/events.md +5 -1
  68. package/docs/api/post.md +5 -4
  69. package/docs/api/saves.md +2 -1
  70. package/docs/api/sky.md +3 -3
  71. package/docs/api/style.md +8 -8
  72. package/docs/api/tools.md +5 -2
  73. package/docs/api/vegetation.md +1 -0
  74. package/docs/api/weather.md +1 -1
  75. package/docs/recipes/01-new-game.md +41 -43
  76. package/docs/recipes/02-npc.md +38 -22
  77. package/docs/recipes/03-items-pickups.md +4 -4
  78. package/docs/recipes/04-quests.md +23 -23
  79. package/docs/recipes/05-props-bake.md +5 -5
  80. package/docs/recipes/06-clock-events.md +13 -0
  81. package/docs/recipes/07-flow-scenes-pause.md +6 -2
  82. package/docs/recipes/08-weather-sky.md +6 -6
  83. package/docs/recipes/09-style-pack.md +35 -100
  84. package/docs/recipes/12-navmesh.md +22 -0
  85. package/docs/recipes/13-animation.md +25 -6
  86. package/docs/recipes/14-custom-module.md +6 -7
  87. package/docs/recipes/15-perf.md +9 -1
  88. package/docs/recipes/16-dev-bridge.md +52 -18
  89. package/docs/recipes/18-world.md +5 -2
  90. package/docs/recipes/19-shooting-picking.md +9 -8
  91. package/docs/recipes/20-content-actions-save.md +10 -10
  92. package/docs/recipes/21-camera.md +51 -2
  93. package/docs/recipes/22-shop-gold.md +16 -16
  94. package/docs/recipes/23-ops.md +46 -10
  95. package/docs/recipes/27-net.md +3 -3
  96. package/docs/recipes/28-terrain.md +2 -2
  97. package/docs/recipes/29-grid.md +47 -27
  98. package/docs/recipes/34-environment-lighting.md +11 -10
  99. package/docs/recipes/35-style-from-reference.md +41 -46
  100. package/docs/recipes/36-sky-ground-plant-looks.md +22 -20
  101. package/docs/recipes/37-terrain-look-hooks.md +34 -13
  102. package/docs/recipes/38-environment-look-hooks.md +49 -42
  103. package/docs/recipes/40-scene.md +29 -0
  104. package/docs/recipes/41-thing-registry.md +29 -0
  105. package/docs/recipes/42-terrain-shape.md +1 -1
  106. package/docs/recipes/43-shader-patches-surface-looks.md +37 -20
  107. package/docs/recipes/44-water-weather-look-hooks.md +11 -9
  108. package/docs/recipes/45-cascaded-shadows.md +2 -2
  109. package/docs/recipes/46-blender-art-route.md +26 -4
  110. package/docs/recipes/47-island-snow-backdrop.md +4 -3
  111. package/docs/recipes/48-make-material.md +70 -0
  112. package/docs/recipes/49-game-module-contract.md +71 -0
  113. package/docs/recipes/50-own-renderer.md +12 -0
  114. package/docs/recipes/51-capability-catalog.md +63 -0
  115. package/docs/recipes/52-look.md +146 -0
  116. package/docs/recipes/53-ground-up-close.md +58 -0
  117. package/examples/action/GAMEMAP.md +7 -7
  118. package/examples/action/content/index.js +2 -1
  119. package/examples/action/content/views.js +6 -0
  120. package/examples/action/main.js +3 -2
  121. package/examples/sheepisland/GAMEMAP.md +3 -4
  122. package/examples/styletest/GAMEMAP.md +3 -3
  123. package/examples/styletest/content/npcs.js +1 -1
  124. package/examples/styletest/main.js +2 -2
  125. package/examples/styletest/panel.js +3 -3
  126. package/examples/world/GAMEMAP.md +3 -3
  127. package/examples/world/content/npcs.js +1 -1
  128. package/examples/world/main.js +1 -1
  129. package/index.d.ts +35 -2
  130. package/index.js +6 -3
  131. package/llms.txt +13 -7
  132. package/modules/ambience/Ambience.js +5 -2
  133. package/modules/camera/FirstPersonCamera.js +3 -5
  134. package/modules/camera/FixedCamera.js +19 -12
  135. package/modules/camera/FollowCamera.js +14 -8
  136. package/modules/camera/RtsCamera.js +3 -5
  137. package/modules/camera/common.js +40 -10
  138. package/modules/camera/index.js +1 -1
  139. package/modules/camera/projection.js +34 -0
  140. package/modules/characters/Character.js +45 -31
  141. package/modules/characters/assetModel.js +35 -7
  142. package/modules/characters/astar.js +14 -7
  143. package/modules/characters/index.js +6 -3
  144. package/modules/characters/movers/simple.js +6 -1
  145. package/modules/characters/npcSim.js +8 -2
  146. package/modules/characters/pathAsync.js +12 -6
  147. package/modules/characters/pathJob.js +2 -1
  148. package/modules/characters/proceduralRig.js +50 -11
  149. package/modules/characters/useModel.js +22 -0
  150. package/modules/characters/walkTo.js +58 -0
  151. package/modules/collision/Collision.js +102 -4
  152. package/modules/content/explain.js +13 -0
  153. package/modules/content/index.js +3 -1
  154. package/modules/content/loader.js +3 -0
  155. package/modules/content/rules.js +1 -0
  156. package/modules/debug/DebugPanel.js +11 -5
  157. package/modules/entities/Entities.js +6 -2
  158. package/modules/flow/index.js +5 -2
  159. package/modules/gameplay/Dialogue.js +5 -2
  160. package/modules/gameplay/Interactions.js +12 -2
  161. package/modules/gameplay/Inventory.js +21 -11
  162. package/modules/gameplay/Quests.js +13 -3
  163. package/modules/gameplay/pickups.js +6 -4
  164. package/modules/grid/Layer.js +1 -1
  165. package/modules/grid/index.js +1 -1
  166. package/modules/grid/tiles.js +9 -5
  167. package/modules/hlod/index.js +5 -2
  168. package/modules/hud/index.js +5 -2
  169. package/modules/level/index.js +5 -3
  170. package/modules/lights/index.js +5 -2
  171. package/modules/music/Music.js +6 -2
  172. package/modules/nav/index.js +5 -3
  173. package/modules/net/Client.js +4 -3
  174. package/modules/net/Host.js +2 -2
  175. package/modules/net/index.js +5 -3
  176. package/modules/particles/Particles.js +1 -1
  177. package/modules/photo/Photo.js +10 -7
  178. package/modules/rigid/RigidBodies.js +5 -2
  179. package/modules/settings/Settings.js +6 -3
  180. package/modules/settings/apply.js +2 -1
  181. package/modules/sky/Sky.js +21 -19
  182. package/modules/sky/cascades.js +6 -6
  183. package/modules/sky/domeLayers.js +1 -1
  184. package/modules/sky/environment.js +39 -13
  185. package/modules/sky/fog.js +9 -6
  186. package/modules/sky/frame.js +4 -3
  187. package/modules/sky/look.js +3 -2
  188. package/modules/sky/lookFog.js +80 -0
  189. package/modules/sky/lookShadow.js +50 -0
  190. package/modules/sky/lookSky.js +108 -0
  191. package/modules/sky/shader.js +2 -2
  192. package/modules/sky/shadow.js +4 -10
  193. package/modules/sky/skyModule.js +4 -3
  194. package/modules/terrain/ChunkManager.js +2 -33
  195. package/modules/terrain/chunkLevels.js +40 -0
  196. package/modules/terrain/index.js +10 -2
  197. package/modules/terrain/lookGround.js +61 -0
  198. package/modules/timeline/Timeline.js +7 -3
  199. package/modules/timeline/Tween.js +3 -7
  200. package/modules/timeline/shots.js +6 -4
  201. package/modules/triggers/index.js +9 -2
  202. package/modules/vegetation/Vegetation.js +17 -4
  203. package/modules/vegetation/index.js +7 -4
  204. package/modules/vegetation/lookWind.js +37 -0
  205. package/modules/vegetation/nearFade.js +39 -0
  206. package/modules/water/Water.js +19 -3
  207. package/modules/water/look.js +80 -0
  208. package/modules/weather/Weather.js +22 -31
  209. package/modules/weather/look.js +75 -0
  210. package/modules/weather/particles.js +1 -1
  211. package/modules/weather/strings.js +15 -0
  212. package/modules/world/explain.js +11 -0
  213. package/modules/world/index.js +11 -4
  214. package/modules/world/thingSource.js +44 -0
  215. package/package.json +2 -1
  216. package/render/PostFX.js +48 -51
  217. package/render/detail.js +39 -15
  218. package/render/effects.js +4 -2
  219. package/render/fuse.js +12 -0
  220. package/render/lights.js +4 -2
  221. package/render/lookSurface.js +161 -0
  222. package/render/materials.js +27 -10
  223. package/render/postLook.js +86 -0
  224. package/render/surface.js +3 -1
  225. package/types/core.d.ts +223 -29
  226. package/types/gameplay.d.ts +22 -6
  227. package/types/generated/core/DebugOverrides.d.ts +52 -0
  228. package/types/generated/core/Events.d.ts +43 -0
  229. package/types/generated/core/Ops.d.ts +62 -21
  230. package/types/generated/core/Saves.d.ts +1 -0
  231. package/types/generated/core/Views.d.ts +33 -0
  232. package/types/generated/modules/debug/DebugPanel.d.ts +2 -2
  233. package/types/generated/modules/grid/Layer.d.ts +1 -0
  234. package/types/generated/modules/sky/Sky.d.ts +10 -17
  235. package/types/generated/modules/weather/Weather.d.ts +5 -15
  236. package/types/generated/render/PostFX.d.ts +20 -23
  237. package/types/generated/render/materials.d.ts +10 -0
  238. package/types/physics.d.ts +8 -0
  239. package/types/style.d.ts +35 -20
  240. package/types/world.d.ts +7 -1
  241. package/ui/Parts.js +6 -2
  242. package/ui/UI.js +1 -1
  243. package/ui/defaults.js +1 -1
  244. package/docs/api/debug.md +0 -10
@@ -29,22 +29,26 @@ async function loadGray(url) {
29
29
  import { ChunkManager } from './ChunkManager.js';
30
30
  import { DEFAULT_TERRAIN } from './terrainGen.js';
31
31
  import { checkOptions } from '../../core/validate.js';
32
+ import { readParams, keysSchema } from '../../core/params.js';
32
33
  import { compilePure } from '../../core/threadPure.js';
33
34
  import { warnOnce } from '../../core/validate.js';
34
35
  import { prepareShape, voidWatcher } from './terrainShapeMain.js';
36
+ import { defineGroundLook } from './lookGround.js';
35
37
 
36
38
  const NO_HEIGHT = 'terrain(): no height function or height map was given, so the ground is flat gray at y = 0 (a placeholder, not a look). '
37
39
  + 'Pass terrain({ height, groundType }) or a preset, e.g. terrain({ ...terrainPreset() }) with terrainPreset from @threedog/terrain-noise';
38
40
 
39
41
  export { createTerrain, DEFAULT_TERRAIN } from './terrainGen.js';
40
42
 
43
+ const TERRAIN_PARAMS = keysSchema(['viewChunks', 'density', 'material', 'viewFog', ...Object.keys(DEFAULT_TERRAIN)], { ...DEFAULT_TERRAIN, viewChunks: 4, density: 1, viewFog: false }); // defaults shown in the catalog; createTerrain applies the real ones
44
+
41
45
  export function terrain(opts = {}) {
46
+ readParams('terrain', TERRAIN_PARAMS, opts);
42
47
  const { viewChunks = 4, density = 1, material, viewFog = false, ...cfg } = opts;
43
48
  let w = null, watchVoid = null;
44
49
  return {
45
- name: 'terrain', label: 'Terrain', optional: ['vegetation'], stage: 'world',
50
+ name: 'terrain', label: 'Terrain', params: TERRAIN_PARAMS, options: opts, noSkip: 'void-fall watch only; nothing accumulates over time', optional: ['vegetation'], stage: 'world',
46
51
  install(e) {
47
- checkOptions('terrain()', opts, ['viewChunks', 'density', 'material', 'viewFog', ...Object.keys(DEFAULT_TERRAIN)]);
48
52
  const style = e.style.terrain || {};
49
53
  for (const k in cfg) if (cfg[k] === undefined) delete cfg[k];
50
54
  // a game's generator functions go to the workers as source text: checked here (outside variables name themselves) so the error points at this call
@@ -69,6 +73,9 @@ export function terrain(opts = {}) {
69
73
  w.density = density;
70
74
  w.viewFog = viewFog; // opt-in: the fog ends where the chunks end (hides the edge); otherwise createEngine({ fogFar }) / the game's fog stays
71
75
  this._cfg = terrainCfg;
76
+ // look.ground: what terrain({...}) itself was given goes on the game layer (owner 'terrain()'); the style's values are the style layer
77
+ defineGroundLook(e, w, { cfg: () => this._cfg, setCfg: c => { this._cfg = c; },
78
+ game: { colors: cfg.colors && terrainCfg.colors, biomeColors: cfg.biomeColors && terrainCfg.biomeColors, steep: cfg.steep, shading: cfg.shading, material } });
72
79
  e.setGround({
73
80
  height: (x, z) => w.T.surface(x, z),
74
81
  slope: (x, z) => w.T.slope(x, z),
@@ -99,6 +106,7 @@ export function terrain(opts = {}) {
99
106
  const needH = hm?.url && !hm.data, needM = mk?.url && !mk.data;
100
107
  if (!needH && !needM) return;
101
108
  const cfg2 = { ...this._cfg };
109
+ this._cfg = cfg2; // look.ground rebuilds from the current config
102
110
  if (needH) cfg2.heightmap = { ...hm, ...await loadGray(hm.url), url: undefined };
103
111
  if (needM) cfg2.shape = { ...cfg2.shape, mask: { ...mk, ...await loadGray(mk.url), url: undefined } };
104
112
  const species = {}; for (const sp of e.vegetation?.list() || []) species[sp.name] = sp.rule;
@@ -0,0 +1,61 @@
1
+ // look.ground: how the terrain looks (colors, variation, shading, detail layer, material). Registered by the terrain module.
2
+ // set({ colors, biomeColors, steep, variation, shading, detail })
3
+ // colors / biomeColors / steep / variation / shading are baked into the chunks by the workers: a change rebuilds every chunk (cost 'rebuild';
4
+ // edits stay). colors / biomeColors / steep are given whole (they replace the style's table), variation / detail are objects (style.terrain.*).
5
+ // patch('detail', glsl) the detail layer's `vec4 threedogDetailSample(vec2 p)` (render/detail.js); a detail object must be set too
6
+ // replace(Material | (engine) => Material) the ground material (terrain({ material }) / style.terrain.material is the first one); null gives it back
7
+ // Why not in ChunkManager.js: that file is at its size cap, and every ground option below already reached it as config before; this only
8
+ // writes the same config again when a verb changes it.
9
+ import { defineLookPart, REPLACE } from '../../core/look/part.js';
10
+ import { terrainMaterial } from '../../render/materials.js';
11
+
12
+ const GEN = ['colors', 'biomeColors', 'steep', 'variation', 'shading'];
13
+ const isObj = v => (v && typeof v === 'object' ? null : 'must be an object');
14
+
15
+ /**
16
+ * @param {any} e @param {any} w the ChunkManager
17
+ * @param {{ cfg: () => any, setCfg: (c: any) => void, game: Record<string, any> }} h the module's current terrain config, and what terrain({...}) itself passed (written as owner 'terrain()')
18
+ */
19
+ export function defineGroundLook(e, w, h) {
20
+ const st = e.style.terrain ?? {}, cfg0 = h.cfg();
21
+ const rebuild = 'rebuild';
22
+ const part = defineLookPart(e, {
23
+ id: 'ground', group: 'surface', module: 'terrain', object: () => w.terrainMat, applyAtStart: false, docs: ['recipes/52-look.md'],
24
+ params: {
25
+ colors: { type: 'any', default: {}, neutral: true, cost: rebuild, check: isObj, desc: 'palette name -> color; the whole table (a ground type without a color is neutral gray)' },
26
+ biomeColors: { type: 'any', default: {}, neutral: true, cost: rebuild, check: isObj, desc: 'ground type -> palette name(s); the whole table' },
27
+ steep: { type: 'array', default: [], neutral: true, cost: rebuild, desc: 'slope colors [{ maxNormalY, colors }]' },
28
+ variation: { type: 'any', default: null, neutral: true, cost: rebuild, check: isObj, desc: '{ blend, jitter, patches } color variation (style.terrain.variation); null = none' },
29
+ shading: { type: 'string', values: ['smooth', 'flat', 'texture'], default: 'smooth', cost: rebuild,
30
+ why: 'terrain colors are blended per grid point (smooth) so the ground has no visible facets', off: "look.ground.set({ shading: 'flat' }) for one color per triangle, or 'texture' for a per-chunk color map" },
31
+ detail: { type: 'any', default: null, neutral: true, cost: 'recompile', check: isObj, desc: '{ texture | noise | glsl, scale, strength ... } detail layer over the ground (style.terrain.detail); null = none' },
32
+ },
33
+ style: () => ({ colors: st.colors, biomeColors: st.biomeColors, steep: st.steep, variation: st.variation, shading: st.config?.shading, detail: st.detail, [REPLACE]: st.material }),
34
+ read: () => ({}),
35
+ hooks: { detail: { signature: 'vec4 threedogDetailSample(vec2 p) // rgb + height 0-1', scope: ['fragment'], example: "engine.look.ground.patch('detail', glsl)" } },
36
+ replace: { accepts: 'a Material, or (engine) => Material; null gives the style\'s back', loses: ['the style\'s terrain material (cloud shadows and season tint are added to the new one)'] },
37
+ applyReplace: () => material(), applyHook: () => material(),
38
+ apply(v, changed) {
39
+ if (changed.has('detail')) material();
40
+ if (!GEN.some(k => changed.has(k))) return;
41
+ const next = { ...h.cfg() };
42
+ for (const k of GEN) if (changed.has(k)) { if (v[k] == null) delete next[k]; else next[k] = v[k]; }
43
+ if (!next.shading) next.shading = cfg0.shading;
44
+ h.setCfg(next);
45
+ const species = {}; for (const sp of e.vegetation?.list() || []) species[sp.name] = sp.rule;
46
+ w.reinit(next, species);
47
+ },
48
+ });
49
+ // what terrain({ colors, shading, material ... }) itself was given sits on the game layer under the owner 'terrain()', so describe shows it
50
+ const given = {};
51
+ for (const k of GEN) if (h.game[k] !== undefined) given[k] = h.game[k];
52
+ if (h.game.material !== undefined) given[REPLACE] = h.game.material;
53
+ if (Object.keys(given).length) part.write('terrain()', given);
54
+ /** Rebuild the ground material from the resolved replace / detail, then every chunk picks it up */
55
+ function material() {
56
+ const impl = part.value(REPLACE) ?? null;
57
+ w.terrainMat = terrainMaterial(typeof impl === 'function' ? impl(e) : impl, e);
58
+ w.rebuild();
59
+ }
60
+ return part;
61
+ }
@@ -18,7 +18,7 @@
18
18
  // Space, which is dialogue "continue"), or click the hint on the letterbox.
19
19
  // While frozen (engine.freeze / flow 'paused') wait, tweens, camera and paths do not advance; they resume after unfreezing.
20
20
  // On skip all running tweens jump to their end and the remaining steps finish instantly (do steps still run, so state matches a normal playthrough).
21
- // Camera takeover: a camera step sets engine.cameraOverride (see camera/common.js) and restores the previous value and view after the whole run; the camera
21
+ // Camera takeover: a camera step takes the camera (engine.takeCamera, see camera/common.js) and releases its claim and restores the view after the whole run; the camera
22
22
  // module then resumes.
23
23
  // To hand the camera back midway: { camera: { release: true } }
24
24
  // General tween (usable anywhere in a game): await engine.timeline.tween(mesh, { 'position.y': 2, 'material.opacity': 0 }, 1, 'outCubic')
@@ -29,6 +29,7 @@ import { fadeScreen, uiFocus } from '../../ui/UI.js';
29
29
  import { cameraStep, pathStep, releaseCamera } from './shots.js';
30
30
  import { buildLetterbox } from './letterbox.js';
31
31
  import { checkOptions } from '../../core/validate.js';
32
+ import { readParams, keysSchema } from '../../core/params.js';
32
33
  /** @import { ModuleDef } from '../../types/core' */
33
34
  /** @import { Ease } from '../../types/common' */
34
35
  /** @import { TimelineStep, TimelinePlayOptions, TimelineOptions, TweenTo, TweenPromise } from '../../types/gameplay' */
@@ -217,6 +218,8 @@ const STRINGS = {
217
218
  en: { 'timeline.skip': '{key:skip} Skip', 'timeline.skipAction': 'Skip cutscene' },
218
219
  };
219
220
 
221
+ const TIMELINE_PARAMS = keysSchema(['skipKeys']);
222
+
220
223
  /**
221
224
  * Timeline (cutscenes, tweens) -> engine.timeline.
222
225
  * timeline({ skipKeys: ['Escape', 'Backspace'] })(timeline({ skipKeys: ['Escape', 'Backspace'] }) (Esc is the back key, dispatched by the UI focus stack)
@@ -225,11 +228,12 @@ const STRINGS = {
225
228
  * @returns {ModuleDef<Timeline>}
226
229
  */
227
230
  export function timeline(opts = {}) {
231
+ readParams('timeline', TIMELINE_PARAMS, opts);
228
232
  let t = null;
229
233
  return {
230
- name: 'timeline', label: 'Timeline', stage: 'control', before: ['cameraRig'], // before the camera, so the takeover applies on the same frame
234
+ name: 'timeline', params: TIMELINE_PARAMS, options: opts, label: 'Timeline', stage: 'control', before: ['cameraRig'], // before the camera, so the takeover applies on the same frame
231
235
  install(e) {
232
- checkOptions('timeline()', opts, ['skipKeys']); e.i18n.add(STRINGS); t = new Timeline(e, opts); e.cameraOverride ??= null;
236
+ e.i18n.add(STRINGS); t = new Timeline(e, opts);
233
237
  // a running cutscene ends with its playthrough (session waits one macrotask for its steps to settle)
234
238
  e.events.on('session:end', () => { if (t.runs.size) t.skip(); });
235
239
  return t;
@@ -9,18 +9,14 @@
9
9
  import * as THREE from 'three';
10
10
  import { ease as easing } from '../../core/easing.js';
11
11
  import { allowOwned } from '../../core/validate.js';
12
+ import { getPath } from '../../core/util.js';
12
13
 
13
14
  const COMPS = ['x', 'y', 'z', 'w'];
14
15
 
15
16
  /** 'material.color' → { obj: target.material, key: 'color' } */
16
17
  function resolve(target, path) {
17
- const parts = path.split('.');
18
- let obj = target;
19
- for (let i = 0; i < parts.length - 1; i++) {
20
- obj = obj?.[parts[i]];
21
- if (obj == null) return null;
22
- }
23
- return { obj, key: parts[parts.length - 1] };
18
+ const i = path.lastIndexOf('.'), obj = i < 0 ? target : getPath(target, path.slice(0, i));
19
+ return obj == null ? null : { obj, key: path.slice(i + 1) };
24
20
  }
25
21
 
26
22
  /** Build an interpolator for a property: returns k => apply progress k (0..1) */
@@ -1,4 +1,4 @@
1
- // Timeline camera and path steps (helper of Timeline.js): a shot takes the camera over through engine.cameraOverride and gives it back when the run ends;
1
+ // Timeline camera and path steps (helper of Timeline.js): a shot takes the camera over with engine.takeCamera (core/holds.js) and gives it back when the run ends;
2
2
  // a path moves any object (a character, the camera) along a spline. Each function takes the Timeline as `t`.
3
3
  import * as THREE from 'three';
4
4
  import { vec3 as v3 } from '../../core/math.js';
@@ -36,8 +36,10 @@ export function cameraStep(t, c, run) {
36
36
  function takeCamera(t, run) {
37
37
  const e = t.engine;
38
38
  if (!run.cam) {
39
- run.cam = { prev: e.cameraOverride ?? null, fov: e.camera.fov, look: new THREE.Vector3(), override: { owner: 'timeline', id: run.id, focus: e.focus.clone() } };
40
- e.cameraOverride = run.cam.override;
39
+ // a claim of its own (engine.takeCamera): a named view or a game holding the camera keeps its claim and gets the camera back afterwards.
40
+ // The owner carries the run id so two overlapping runs are two holders, not one overwriting the other.
41
+ const override = { owner: 'timeline:' + run.id, id: run.id, focus: e.focus.clone() };
42
+ run.cam = { fov: e.camera.fov, look: new THREE.Vector3(), override, hold: e.takeCamera(override.owner, override) };
41
43
  }
42
44
  return run.cam;
43
45
  }
@@ -46,7 +48,7 @@ export function releaseCamera(t, run) {
46
48
  const st = run.cam; if (!st) return;
47
49
  run.cam = null;
48
50
  const e = t.engine;
49
- if (e.cameraOverride === st.override) e.cameraOverride = st.prev;
51
+ st.hold.remove();
50
52
  if (e.camera.fov !== st.fov) { e.camera.fov = st.fov; e.camera.updateProjectionMatrix(); }
51
53
  }
52
54
 
@@ -32,6 +32,7 @@
32
32
  // In dev builds F4 (action triggersDebug, rebindable) toggles the display; release builds bind no key unless triggers({ keys }) names one.
33
33
  import * as THREE from 'three';
34
34
  import { checkOptions, DEV } from '../../core/validate.js';
35
+ import { readParams } from '../../core/params.js';
35
36
 
36
37
  // Zones are indexed by the grid cells their bounding box covers, so a step looks at the zones near the actor instead of every zone. A zone with its own `who`
37
38
  // (any position, unknown until it runs) or one covering more than MAX_CELLS cells goes to the always-checked `_global` list.
@@ -238,13 +239,19 @@ export class Triggers {
238
239
  }
239
240
  }
240
241
 
242
+ const TRIGGER_PARAMS = {
243
+ debug: { type: 'bool', default: false, desc: 'draw all zones as wireframes from the start' },
244
+ action: { type: 'string', default: 'triggersDebug', desc: 'input action that toggles the debug display' },
245
+ keys: { type: 'array', optional: true, desc: "keys for that toggle (default ['F4'] in dev builds, none in release)" },
246
+ };
247
+
241
248
  /** Trigger zone module. Provides engine.triggers once installed. Optional dependency: level (used by fromMarkers) */
242
249
  export function triggers(opts = {}) {
250
+ const o = readParams('triggers', TRIGGER_PARAMS, opts);
243
251
  let tr = null;
244
252
  return {
245
- name: 'triggers', label: 'Triggers', optional: ['level'], stage: 'gameplay', after: ['interactions'],
253
+ name: 'triggers', label: 'Triggers', params: TRIGGER_PARAMS, options: o, noSkip: 'zone enter/exit is re-evaluated on the next fixed step', optional: ['level'], stage: 'gameplay', after: ['interactions'],
246
254
  install(e) {
247
- checkOptions('triggers()', opts, ['debug', 'action', 'keys']);
248
255
  tr = new Triggers(e, opts);
249
256
  // audio rule condition { zone: 'cave' | ['cave', 'mine'] }: some trigger zone with that tag is occupied
250
257
  e.audio.condition('zone', v => [].concat(v).some(tag => tr.byTag(tag).some(t => t.inside)));
@@ -6,8 +6,10 @@ import { makeMaterial, applyEffects } from '../../render/materials.js';
6
6
  import { checkOptions, checkOptionsArg, warnMissing } from '../../core/validate.js';
7
7
  import { xzOf } from '../../core/math.js';
8
8
  import { GroundChunks } from './groundChunks.js';
9
+ import { swayOf } from './lookWind.js';
10
+ import { fadeBand, nearFadePatch } from './nearFade.js';
9
11
  // parameters read by vegetation.add(); keys inside rule (sent to the worker thread)
10
- const ADD_KEYS = ['geometry', 'model', 'lodGeometry', 'rule', 'wind', 'nearOnly', 'maxRing', 'lodRing', 'castShadow', 'shadowRing', 'receiveShadow', 'material', 'effects', 'doubleSided'];
12
+ const ADD_KEYS = ['geometry', 'model', 'lodGeometry', 'rule', 'wind', 'nearOnly', 'maxRing', 'lodRing', 'castShadow', 'shadowRing', 'receiveShadow', 'material', 'effects', 'doubleSided', 'fade'];
11
13
  const RULE_KEYS = ['perChunk', 'chance', 'minHeight', 'maxHeight', 'maxSlope', 'cluster', 'scale', 'stretch', 'sink', 'tintJitter', 'tints', 'biomes', 'collider', 'avoidFlat', 'salt'];
12
14
 
13
15
  // Single-instance removal/restore (chop a tree, mine a rock): records are owned by vegetation and saved with the save (save key 'vegetation', entry
@@ -70,6 +72,8 @@ export class Vegetation {
70
72
  * wind wind sway amplitude (0 disables)
71
73
  * nearOnly generate only near the player (grass, flowers)
72
74
  * maxRing not drawn beyond this ring count
75
+ * fade near-only species shrink out over a band [start, end] metres from the player instead of popping at the ring edge (default on for
76
+ * nearOnly, end = maxRing x chunk size; false = hard edge; { start, end } sets the band)
73
77
  * lodRing switch to low-poly beyond this ring count
74
78
  * castShadow / shadowRing whether to cast shadows, and within how many rings
75
79
  * material custom material, any three.js material (optional, default is the style pack's 'vegetation' role); wind, cloud
@@ -78,15 +82,19 @@ export class Vegetation {
78
82
  add(name, o) {
79
83
  checkOptions(`vegetation.add('${name}')`, o, ADD_KEYS);
80
84
  checkOptions(`vegetation.add('${name}').rule`, o.rule, RULE_KEYS);
81
- const sw = this.engine.style.wind, wind = o.wind && sw?.glsl ? { amplitude: o.wind, glsl: sw.glsl, uniforms: sw.uniforms } : o.wind; // style.wind.glsl replaces the sway shape
82
- const fx = m => o.effects === false ? m : applyEffects(m, { wind, season: 'foliage' });
85
+ const sw = swayOf(this.engine), wind = o.wind && sw ? { amplitude: o.wind, glsl: sw.glsl, uniforms: sw.uniforms } : o.wind; // look.wind 'sway' (style.wind.glsl or a game's patch) replaces the sway shape
86
+ // distance fade of near-only species (nearFade.js): on by default for them, fade: false keeps the hard ring edge, { start, end } sets the band in metres
87
+ if (o.fade && typeof o.fade === 'object') checkOptions(`vegetation.add('${name}').fade`, o.fade, ['start', 'end']);
88
+ const maxRing = o.maxRing ?? (o.nearOnly ? 1 : 99);
89
+ const band = o.effects === false ? null : fadeBand(o.fade, !!o.nearOnly, maxRing, this.host.CHUNK), nf = band && nearFadePatch(band);
90
+ const fx = m => o.effects === false ? m : applyEffects(m, { wind, season: 'foliage', patches: nf ? [nf.patch] : undefined });
83
91
  const mdl = o.model && fromModel(o.model, `vegetation.add('${name}')`);
84
92
  let lod = o.lodGeometry?.isObject3D ? fromModel(o.lodGeometry, `vegetation.add('${name}').lodGeometry`).geometry : o.lodGeometry || null;
85
93
  if (mdl && lod && !lod.groups.length) { lod = lod.clone(); lod.addGroup(0, Infinity, 0); } // a material array draws nothing without groups
86
94
  const sp = {
87
95
  name, geometry: mdl ? mdl.geometry : o.geometry, lodGeometry: lod,
88
96
  rule: { salt: hashName(name), ...(o.rule || {}) }, // random seed from the name: placement is unaffected by registration order
89
- nearOnly: !!o.nearOnly, maxRing: o.maxRing ?? (o.nearOnly ? 1 : 99), lodRing: o.lodRing ?? 1,
97
+ nearOnly: !!o.nearOnly, maxRing, fade: band, fadeUniforms: nf?.uniforms ?? null, lodRing: o.lodRing ?? 1,
90
98
  castShadow: o.castShadow ?? !o.nearOnly, shadowRing: o.shadowRing ?? 1, receiveShadow: o.receiveShadow ?? true,
91
99
  material: mdl ? mdl.materials.map(fx)
92
100
  : fx(o.material ?? makeMaterial('vegetation', { vertexColors: true, side: o.doubleSided ? THREE.DoubleSide : THREE.FrontSide }, this.engine)),
@@ -116,6 +124,11 @@ export class Vegetation {
116
124
  sp.shadowRing = ring;
117
125
  this.host.refreshLevels();
118
126
  }
127
+ /** @internal module frame hook: the fade band is centred on the view focus (the player in a follow camera) */
128
+ updateFade() {
129
+ const f = this.engine.focus;
130
+ for (const sp of this.species.values()) sp.fadeUniforms?.uNearFadeCenter.value.copy(f);
131
+ }
119
132
  /** @internal terrain plumbing */
120
133
  baseNames() { return this.list().filter(s => !s.nearOnly).map(s => s.name); }
121
134
  /** @internal terrain plumbing */
@@ -1,8 +1,10 @@
1
1
  // Vegetation module factory: engine.use(vegetation(...)). The class and its chunk plumbing are in Vegetation.js.
2
- import { checkOptions } from '../../core/validate.js';
2
+ import { readParams, keysSchema } from '../../core/params.js';
3
3
  import { Vegetation } from './Vegetation.js';
4
+ import { defineWindLook } from './lookWind.js';
4
5
 
5
6
  const OPTS = ['chunkSize', 'viewChunks', 'density', 'area', 'seed'];
7
+ const VEG_PARAMS = keysSchema(OPTS, { chunkSize: 32, viewChunks: 3, density: 1, seed: 1 }); // defaults of the own-chunks mode (without terrain)
6
8
  /**
7
9
  * Vegetation module. Provides engine.vegetation.add(name, {...}) once installed.
8
10
  * With terrain() installed first it grows on the terrain chunks and takes no options (density and view distance are terrain options).
@@ -18,10 +20,11 @@ const OPTS = ['chunkSize', 'viewChunks', 'density', 'area', 'seed'];
18
20
  * engine.vegetation.add('grass', { geometry, nearOnly: true, rule: { perChunk: 400, biomes: { lawn: 1 } } }); // only on 'lawn' surfaces
19
21
  */
20
22
  export function vegetation(opts = {}) {
21
- checkOptions('vegetation()', opts, OPTS);
23
+ readParams('vegetation', VEG_PARAMS, opts);
22
24
  let v = null, own = null, cols = null, ready = null;
23
- return { name: 'vegetation', label: 'Vegetation', stage: 'world', after: ['terrain', 'level'], optional: ['terrain', 'level'],
25
+ return { name: 'vegetation', label: 'Vegetation', params: VEG_PARAMS, options: opts, stage: 'world', after: ['terrain', 'level'], optional: ['terrain', 'level'],
24
26
  install(e) {
27
+ defineWindLook(e); // look.wind
25
28
  v = new Vegetation(e, opts);
26
29
  if (v.host !== e.terrain) {
27
30
  own = v.host;
@@ -33,7 +36,7 @@ export function vegetation(opts = {}) {
33
36
  // terrain installed after vegetation would leave two chunk tables: say where to put it
34
37
  critical: true, // a wrong install order is a setup error, not something to play on with
35
38
  init(e) { if (own && e.terrain) throw new Error('vegetation() was installed before terrain(): put terrain() first, vegetation then grows on its chunks'); },
36
- frame(dt, e) { own?.update(e.stream.sources(), e.camera); },
39
+ frame(dt, e) { v.updateFade(); own?.update(e.stream.sources(), e.camera); },
37
40
  fixed(dt) { v.tick(dt); }, skip(dt, e, done) { if (done) v.tick(1); },
38
41
  describe(e, ctx) { if (own) ctx.out.perf.vegetation = { loaded: own.stats.loaded, visible: own.stats.visible, queued: own.stats.queued }; },
39
42
  dispose() { own?.dispose(); cols?.remove(); ready?.remove(); } };
@@ -0,0 +1,37 @@
1
+ // look.wind: how plants sway. Registered by the vegetation module (it is the one that adds wind patches to its species' materials).
2
+ // set({ frequency, amplitude }) uniforms: live on every wind patch (trees already planted too)
3
+ // patch('sway', glsl) a threedogWind function (style.wind.glsl is the style layer); read when a species is ADDED, so patch before vegetation.add
4
+ // No replace: the sway patch already is the whole motion; weather's gusts (uWind) still scale it.
5
+ import { defineLookPart } from '../../core/look/part.js';
6
+ import { codedError } from '../../core/errorHints.js';
7
+ import { windCustom } from '../../render/materials.js';
8
+
9
+ const asObj = v => (typeof v === 'string' ? { glsl: v } : v);
10
+ /** The custom sway { glsl, uniforms } to give a new wind patch, or null for the built-in sway */
11
+ export function swayOf(e) { const v = e.look?.wind?.value('hook:sway'); return v ? asObj(v) : null; }
12
+
13
+ /** @param {any} e */
14
+ export function defineWindLook(e) {
15
+ if (e.look?.wind) return;
16
+ const u = e.uniforms, w = e.style.wind ?? {};
17
+ const part = defineLookPart(e, {
18
+ id: 'wind', group: 'motion', module: 'vegetation', object: () => u, docs: ['recipes/52-look.md'],
19
+ params: {
20
+ frequency: { type: 'number', default: 1, min: 0, neutral: true, cost: 'uniform', desc: 'sway speed multiplier (style.wind.frequency)' },
21
+ amplitude: { type: 'number', default: 1, min: 0, neutral: true, cost: 'uniform', desc: "multiplies every species' wind amplitude; 0 = plants stand still" },
22
+ },
23
+ style: () => ({ frequency: w.frequency, ...(w.glsl ? { 'hook:sway': { glsl: w.glsl, uniforms: w.uniforms } } : {}) }),
24
+ read: () => ({ frequency: u.uWindFreq.value, amplitude: u.uWindAmp.value }),
25
+ apply(v, changed) {
26
+ if (changed.has('frequency')) u.uWindFreq.value = v.frequency;
27
+ if (changed.has('amplitude')) u.uWindAmp.value = v.amplitude;
28
+ },
29
+ hooks: { sway: { signature: 'void threedogWind(inout vec3 transformed, vec3 ip, vec3 position)', scope: ['vertex'], example: 'engine.look.wind.patch("sway", glsl) // or { glsl, uniforms }' } },
30
+ noReplace: 'the sway patch already is the whole motion; patch("sway", glsl) rewrites it, set({ amplitude: 0 }) stops it',
31
+ });
32
+ const patch = part.patch.bind(part);
33
+ part.patch = (name, glsl, o) => { // a wrong sway function throws here, not later inside vegetation.add
34
+ if (glsl != null) { try { windCustom(asObj(glsl)); } catch (err) { throw codedError('look-param', `look.wind.patch('${name}'): ${err.message}`); } }
35
+ return patch(name, glsl, o);
36
+ };
37
+ }
@@ -0,0 +1,39 @@
1
+ // Distance fade for near-only vegetation (grass, flowers, pebbles, debris ... any species that only exists close to the player).
2
+ // Why: such species are placed per chunk ring (maxRing), so without this the ring edge is a visible line that pops in and out chunk by chunk.
3
+ // How: instances shrink toward their own base over a band [start, end] metres from the player, in the vertex shader of the species' own material:
4
+ // no extra draw call or shader program per frame (the patch is part of the material's one program), the sway of the wind patch is scaled with it, and the
5
+ // shadow pass shrinks the same way. The band ends where the ring can first end, so a clump is already gone when its chunk drops out.
6
+ import * as THREE from 'three';
7
+
8
+ const PARS = 'uniform vec2 uNearFade; uniform vec3 uNearFadeCenter;';
9
+ const VERTEX = `
10
+ {
11
+ vec4 ipo = vec4(0.0, 0.0, 0.0, 1.0);
12
+ #ifdef USE_INSTANCING
13
+ ipo = instanceMatrix * ipo;
14
+ #endif
15
+ vec3 ip = (modelMatrix * ipo).xyz;
16
+ transformed *= 1.0 - smoothstep(uNearFade.x, uNearFade.y, distance(ip.xz, uNearFadeCenter.xz));
17
+ }`;
18
+
19
+ /**
20
+ * The fade band of a species in metres from the player.
21
+ * @param {false | { start?: number, end?: number } | undefined} fade the species' fade option (undefined = default for near-only species)
22
+ * @param {boolean} nearOnly
23
+ * @param {number} maxRing rings drawn around the player
24
+ * @param {number} chunk chunk size in metres
25
+ * @returns {{ start: number, end: number } | null} null = no fade
26
+ */
27
+ export function fadeBand(fade, nearOnly, maxRing, chunk) {
28
+ if (fade === false || (fade === undefined && !nearOnly)) return null;
29
+ // the ring is guaranteed to reach maxRing x chunk in every direction (the player may stand at a chunk edge), so end the fade there
30
+ const end = fade?.end ?? maxRing * chunk, start = fade?.start ?? end * 0.65;
31
+ if (!(end > 0) || !(start >= 0) || start >= end) throw new Error(`vegetation fade: need 0 <= start < end (metres), got start ${start}, end ${end}`);
32
+ return { start, end };
33
+ }
34
+
35
+ /** The shader patch plus the uniform objects (move center each frame) @param {{ start: number, end: number }} band */
36
+ export function nearFadePatch(band) {
37
+ const uniforms = { uNearFade: { value: new THREE.Vector2(band.start, band.end) }, uNearFadeCenter: { value: new THREE.Vector3() } };
38
+ return { patch: { name: 'nearFade', cacheKey: 'v1', shadow: true, uniforms, glsl: { vertex: { pars: PARS, begin_vertex: VERTEX } } }, uniforms };
39
+ }
@@ -14,20 +14,24 @@ import * as THREE from 'three';
14
14
  import { makeMaterial } from '../../render/materials.js';
15
15
  import { placeholderTexture } from '../../render/effects.js';
16
16
  import { patchMaterial } from '../../render/patches.js';
17
- import { checkOptions, warnOnce } from '../../core/validate.js';
17
+ import { warnOnce } from '../../core/validate.js';
18
+ import { readParams, keysSchema } from '../../core/params.js';
18
19
  import { waterLook, wavesPatch, surfacePatch } from './surface.js';
20
+ import { defineWaterLook } from './look.js';
19
21
  /** @import { ModuleDef } from '../../types/core' */
20
22
  /** @import { Object3D, Material, Vector3 } from '../../types/common' */
21
23
  /** @import { WaterBody, WaterOptions } from '../../types/world' */
22
24
  // Options accepted by water(): sea / level + any appearance item that overrides the style pack's style.water
23
25
  const WATER_OPTIONS = ['sea', 'level', 'color', 'opacity', 'flat', 'waveHeight', 'waveScale', 'waveSpeed', 'fresnel', 'size', 'segments', 'normalMap',
24
26
  'normalScale', 'normalRepeat', 'normalSpeed', 'shininess', 'specular', 'material', 'depthColor', 'foam', 'glsl', 'uniforms'];
27
+ const WATER_PARAMS = keysSchema(WATER_OPTIONS);
25
28
 
26
29
  /** engine.water */
27
30
  export class Water {
28
31
  /** @internal */
29
32
  constructor(engine, opts = {}) {
30
33
  /** @internal */ this.engine = engine;
34
+ /** @internal */ this.opts = opts;
31
35
  /** @internal */ this.st = { color: 0x888888, opacity: 0.85, flat: true, waveHeight: 1, waveScale: 1, waveSpeed: 1, fresnel: 0.5,
32
36
  size: 900, segments: 150, normalScale: 0.4, normalRepeat: 0.05, normalSpeed: [0.01, 0.006], ...(engine.style.water || {}), ...opts };
33
37
  const st = this.st;
@@ -57,6 +61,7 @@ export class Water {
57
61
  this.sea = null;
58
62
  /** @internal */ this._seaChecked = st.sea === false; // global water is built on the first frame: terrain (water level) is installed by then, so no dependence on install order
59
63
  for (const b of engine.waterBodies) this._addBody(b);
64
+ defineWaterLook(this); // look.water: the style's values are its style layer, water({...}) options its 'game' layer
60
65
  engine.events.on('water:add', b => this._addBody(b));
61
66
  // material is shared by all bodies, so not engine.remove (which would dispose it); its ray registration goes too
62
67
  engine.events.on('water:remove', b => { const m = this.bodies.get(b); if (m) { engine.detach(m); engine.rays.forget(m); m.geometry.dispose(); this.bodies.delete(b); } });
@@ -70,6 +75,7 @@ export class Water {
70
75
  // normal-map scroll running; the built-in look (role 'water', waves, fresnel) is skipped. waves (and surface, when depthColor / foam /
71
76
  // glsl.surface ask for one; it needs waves before it) are offered for applyEffects({ patches })
72
77
  if (st.material) {
78
+ this._u = waves.uniforms;
73
79
  const own = st.material(e, { uniforms: waves.uniforms, waves, surface, normalMap: this.normalMap });
74
80
  if (!own?.isMaterial) throw new Error('style.water.material must return a three.js Material, e.g. material: (engine, { uniforms }) => new THREE.ShaderMaterial({ uniforms, vertexShader, fragmentShader })');
75
81
  return own;
@@ -81,15 +87,24 @@ export class Water {
81
87
  }
82
88
  const grey = new THREE.Color(0xcccccc);
83
89
  const patches = surface ? [waves, surface] : [waves];
90
+ const uFresnel = { value: st.fresnel };
91
+ this._u = { ...waves.uniforms, uFresnel }; // the live uniforms look.water.set writes
84
92
  // grazing-angle reflection: the flatter the view, the closer to the fog (horizon) color; the getter follows whatever fog exists at draw time.
85
93
  // Basic material has no normal/view variables, so it gets no reflection
86
94
  if (!('isMeshBasicMaterial' in m)) patches.push({ name: 'fresnel',
87
- uniforms: { uFresnel: { value: st.fresnel }, uFresnelColor: { get value() { return e.scene.fog?.color ?? grey; } } },
95
+ uniforms: { uFresnel, uFresnelColor: { get value() { return e.scene.fog?.color ?? grey; } } },
88
96
  glsl: { fragment: { pars: 'uniform float uFresnel; uniform vec3 uFresnelColor;', opaque_fragment: { before: `
89
97
  float threedogFres = pow(1.0 - abs(dot(normalize(vViewPosition), normal)), 3.0) * uFresnel;
90
98
  outgoingLight = mix(outgoingLight, uFresnelColor, clamp(threedogFres, 0.0, 1.0));` } } } });
91
99
  return patchMaterial(m, patches, { strict: false });
92
100
  }
101
+ /** Build the shared material again (look.water changed something structural) and hand it to every water mesh @internal */
102
+ _rebuild() {
103
+ const old = this.material;
104
+ this.material = this._material();
105
+ for (const m of [this.sea, ...this.bodies.values()]) if (m) m.material = this.material;
106
+ old.dispose();
107
+ }
93
108
  /** @internal */
94
109
  _prep(mesh, size) {
95
110
  mesh.receiveShadow = true; mesh.renderOrder = 1;
@@ -139,6 +154,7 @@ export class Water {
139
154
  * @returns {ModuleDef<Water>}
140
155
  */
141
156
  export function water(opts = {}) {
157
+ readParams('water', WATER_PARAMS, opts);
142
158
  let w = null;
143
- return { name: 'water', label: 'Water', stage: 'environment', after: ['sky'], install(e) { checkOptions('water()', opts, WATER_OPTIONS); w = new Water(e, opts); return w; }, frame(dt, e) { w.update(e.focus, dt); } };
159
+ return { name: 'water', label: 'Water', params: WATER_PARAMS, options: opts, stage: 'environment', after: ['sky'], install(e) { w = new Water(e, opts); return w; }, frame(dt, e) { w.update(e.focus, dt); } };
144
160
  }
@@ -0,0 +1,80 @@
1
+ // look.water: the water's look as a look part (recipes/52-look.md).
2
+ // set({ color, opacity, waveHeight, waveScale, waveSpeed, fresnel }) live: uniforms and material fields, no recompile
3
+ // set({ depthColor, foam }) structural: the shared material is rebuilt once (one recompile)
4
+ // patch('wave' | 'surface', glsl) the GLSL hooks of style.water.glsl (recipes/44)
5
+ // replace((engine, { uniforms, waves, surface, normalMap }) => Material) the whole surface (style.water.material)
6
+ // The style layer is style.water; the options of water({...}) are the game's own layer ('game'). Why a rebuild and not a patch of the old
7
+ // material: depthColor / foam / hooks decide which GLSL exists, and the shader is part of the material program.
8
+ import { defineLookPart, REPLACE } from '../../core/look/part.js';
9
+ import { waterLook } from './surface.js';
10
+
11
+ const WHY = 'the water module draws a plain gray, mostly opaque sea when the style gives none';
12
+ const OFF = "engine.use(water({ sea: false })) for no global water, or look.water.set({ opacity: 0 }) to hide the surface";
13
+ const KEYS = ['color', 'opacity', 'waveHeight', 'waveScale', 'waveSpeed', 'fresnel', 'depthColor', 'foam'];
14
+ const UN = { waveHeight: 'uWave', waveScale: 'uWaveScale', waveSpeed: 'uWaveSpeed', fresnel: 'uFresnel' }; // the uniforms behind the live keys
15
+ const STRUCT = ['depthColor', 'foam'];
16
+ const validate = (w, k) => v => { try { waterLook({ ...w.st, [k]: v }); return null; } catch (err) { return err.message; } };
17
+
18
+ /** @param {any} w the Water module */
19
+ export function defineWaterLook(w) {
20
+ const e = w.engine, st = w.st, g = st.glsl ?? {};
21
+ const pick = o => Object.fromEntries(KEYS.filter(k => o[k] !== undefined).map(k => [k, o[k]]));
22
+ const built = { sig: '', material: undefined };
23
+ const sig = () => JSON.stringify([st.depthColor ?? null, st.foam ?? null, st.glsl ?? null]);
24
+ built.sig = sig(); built.material = st.material;
25
+ const live = (k, v) => {
26
+ const m = w.material, u = w._u;
27
+ if (k === 'color' && !st.material && m.color) m.color.set(v);
28
+ else if (k === 'opacity' && !st.material) { const t = v < 1; m.opacity = v; if (m.transparent !== t) { m.transparent = t; m.needsUpdate = true; } }
29
+ else if (u?.[UN[k]]) u[UN[k]].value = v;
30
+ };
31
+ const rebuild = () => {
32
+ const now = sig();
33
+ if (now === built.sig && st.material === built.material) return; // the same structure again (e.g. the game layer repeating the style): nothing to do
34
+ built.sig = now; built.material = st.material;
35
+ w._rebuild();
36
+ };
37
+ const p = defineLookPart(e, {
38
+ id: 'water', group: 'surface', module: 'water', object: () => ({ material: w.material, sea: w.sea }), docs: ['recipes/52-look.md'], applyAtStart: false,
39
+ params: {
40
+ color: { type: 'any', default: 0x888888, cost: 'uniform', why: WHY, off: OFF, desc: 'base color (any THREE.Color input)' },
41
+ opacity: { type: 'number', default: 0.85, min: 0, max: 1, cost: 'uniform', why: WHY, off: OFF },
42
+ waveHeight: { type: 'number', default: 1, min: 0, neutral: true, cost: 'uniform', desc: 'multiplies the wave function (0 = flat)' },
43
+ waveScale: { type: 'number', default: 1, min: 0, neutral: true, cost: 'uniform', desc: 'world position scale fed to the wave function' },
44
+ waveSpeed: { type: 'number', default: 1, min: 0, neutral: true, cost: 'uniform', desc: 'time scale fed to the wave function' },
45
+ fresnel: { type: 'number', default: 0.5, min: 0, max: 1, cost: 'uniform', why: 'grazing angles blend toward the fog (horizon) color', off: 'look.water.set({ fresnel: 0 })' },
46
+ depthColor: { type: 'any', default: null, neutral: true, cost: 'recompile', desc: '{ shallow, deep, by: "view" | "wave", curve } or null; rebuilds the water material once', check: validate(w, 'depthColor') },
47
+ foam: { type: 'any', default: null, neutral: true, cost: 'recompile', desc: 'true | { color, start, end, opacity } or null; rebuilds the water material once', check: validate(w, 'foam') },
48
+ },
49
+ style: () => ({ ...pick(e.style.water ?? {}), ...(g.wave ? { 'hook:wave': g.wave } : {}), ...(g.surface ? { 'hook:surface': g.surface } : {}),
50
+ ...(e.style.water?.material ? { [REPLACE]: e.style.water.material } : {}) }),
51
+ read: () => ({ opacity: !st.material && w.material.opacity !== undefined ? w.material.opacity : undefined }),
52
+ apply(v, changed) {
53
+ for (const k of changed) { st[k] = v[k]; live(k, v[k]); }
54
+ if (STRUCT.some(k => changed.has(k))) rebuild();
55
+ },
56
+ hooks: {
57
+ wave: { signature: 'float threedogWaterWave(vec3 p, float t)', scope: ['uTime'], example: 'float threedogWaterWave(vec3 p, float t) { return sin(p.x + t) * 0.2; }' },
58
+ surface: { signature: 'vec4 threedogWaterSurface(vec4 base, float wave, float facing, vec3 worldPos, float time)', scope: ['uTime'],
59
+ example: 'vec4 threedogWaterSurface(vec4 base, float wave, float facing, vec3 worldPos, float time) { return vec4(base.rgb * (0.8 + wave), base.a); }' },
60
+ },
61
+ applyHook(name, glsl) {
62
+ const was = st.glsl;
63
+ st.glsl = { ...was, [name]: glsl ?? undefined };
64
+ try { waterLook(st); rebuild(); } catch (err) { st.glsl = was; throw err; }
65
+ },
66
+ replace: { accepts: '(engine, { uniforms, waves, surface, normalMap }) => THREE.Material', loses: ['built-in role "water" material, fresnel, color and opacity (your material owns them)', 'depthColor / foam unless your material uses surface'] },
67
+ // checked before any layer is written: the replace slot is a function, a GLSL hook builds (waterLook compiles it on a copy of the state)
68
+ validate: (k, v) => k === REPLACE ? (typeof v === 'function' ? null : 'is (engine, { uniforms, waves, surface, normalMap }) => THREE.Material')
69
+ : k.startsWith('hook:') ? validate(w, 'glsl')({ ...w.st.glsl, [k.slice(5)]: v }) : null,
70
+ applyReplace(impl) {
71
+ st.material = impl ?? undefined; rebuild();
72
+ },
73
+ });
74
+ // water({...}) options are the game's layer
75
+ const o = w.opts ?? {}, mine = pick(o);
76
+ if (Object.keys(mine).length) p.set(mine);
77
+ if (o.glsl) for (const k of ['wave', 'surface']) if (o.glsl[k]) p.patch(k, o.glsl[k]);
78
+ if (o.material) p.replace(o.material);
79
+ return p;
80
+ }