threedog 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (217) hide show
  1. package/core/Animator.js +1 -0
  2. package/core/Assets.js +16 -0
  3. package/core/DebugOverrides.js +143 -0
  4. package/core/Describe.js +14 -3
  5. package/core/Engine.js +32 -69
  6. package/core/Events.js +59 -1
  7. package/core/I18n.js +2 -2
  8. package/core/Inspect.js +12 -32
  9. package/core/InspectScene.js +7 -3
  10. package/core/MaterialInfo.js +32 -0
  11. package/core/Ops.js +43 -59
  12. package/core/Saves.js +5 -4
  13. package/core/UrlState.js +3 -2
  14. package/core/Vars.js +1 -0
  15. package/core/Views.js +49 -0
  16. package/core/actor.js +2 -2
  17. package/core/assetReport.js +83 -0
  18. package/core/catalog.js +169 -0
  19. package/core/checks.js +67 -0
  20. package/core/claims.js +51 -0
  21. package/core/debugView.js +76 -0
  22. package/core/describeRender.js +45 -0
  23. package/core/describeText.js +11 -4
  24. package/core/errorCodes.js +33 -0
  25. package/core/errorHints.js +6 -1
  26. package/core/holds.js +106 -0
  27. package/core/lifecycle.js +1 -0
  28. package/core/lightWatch.js +23 -3
  29. package/core/look/coreParts.js +112 -0
  30. package/core/look/layers.js +136 -0
  31. package/core/look/part.js +173 -0
  32. package/core/look/report.js +79 -0
  33. package/core/look/write.js +86 -0
  34. package/core/loop.js +15 -14
  35. package/core/modules.js +19 -5
  36. package/core/opsAtomic.js +31 -0
  37. package/core/opsCheck.js +25 -14
  38. package/core/opsFail.js +20 -0
  39. package/core/opsHistory.js +6 -6
  40. package/core/opsRun.js +77 -0
  41. package/core/params.js +132 -0
  42. package/core/renamed.js +21 -0
  43. package/core/saveApply.js +2 -2
  44. package/core/sceneMethods.js +9 -34
  45. package/core/services.js +73 -0
  46. package/core/startup.js +3 -1
  47. package/core/styleParts.js +2 -2
  48. package/core/thingExplain.js +68 -0
  49. package/core/thingOps.js +35 -24
  50. package/core/things.js +15 -1
  51. package/core/util.js +11 -0
  52. package/core/validate.js +23 -7
  53. package/docs/AI.md +83 -109
  54. package/docs/API.md +7 -8
  55. package/docs/CODEMAP.md +63 -51
  56. package/docs/COMMANDS.md +17 -5
  57. package/docs/CONVENTIONS.md +17 -6
  58. package/docs/THREE.md +3 -3
  59. package/docs/api/assets.md +2 -0
  60. package/docs/api/characters.md +2 -0
  61. package/docs/api/collision.md +4 -0
  62. package/docs/api/content.md +1 -0
  63. package/docs/api/engine.md +20 -11
  64. package/docs/api/events.md +5 -1
  65. package/docs/api/post.md +5 -4
  66. package/docs/api/saves.md +2 -1
  67. package/docs/api/sky.md +3 -3
  68. package/docs/api/style.md +3 -3
  69. package/docs/api/tools.md +2 -0
  70. package/docs/api/weather.md +1 -1
  71. package/docs/recipes/02-npc.md +16 -0
  72. package/docs/recipes/03-items-pickups.md +1 -1
  73. package/docs/recipes/06-clock-events.md +13 -0
  74. package/docs/recipes/07-flow-scenes-pause.md +4 -0
  75. package/docs/recipes/08-weather-sky.md +1 -1
  76. package/docs/recipes/09-style-pack.md +5 -5
  77. package/docs/recipes/12-navmesh.md +22 -0
  78. package/docs/recipes/13-animation.md +3 -0
  79. package/docs/recipes/15-perf.md +1 -1
  80. package/docs/recipes/16-dev-bridge.md +51 -17
  81. package/docs/recipes/21-camera.md +51 -2
  82. package/docs/recipes/23-ops.md +45 -9
  83. package/docs/recipes/27-net.md +1 -1
  84. package/docs/recipes/29-grid.md +1 -1
  85. package/docs/recipes/34-environment-lighting.md +9 -8
  86. package/docs/recipes/38-environment-look-hooks.md +8 -6
  87. package/docs/recipes/40-scene.md +29 -0
  88. package/docs/recipes/41-thing-registry.md +29 -0
  89. package/docs/recipes/43-shader-patches-surface-looks.md +2 -0
  90. package/docs/recipes/44-water-weather-look-hooks.md +6 -4
  91. package/docs/recipes/45-cascaded-shadows.md +1 -1
  92. package/docs/recipes/46-blender-art-route.md +22 -0
  93. package/docs/recipes/48-make-material.md +70 -0
  94. package/docs/recipes/49-game-module-contract.md +71 -0
  95. package/docs/recipes/50-own-renderer.md +12 -0
  96. package/docs/recipes/51-capability-catalog.md +63 -0
  97. package/docs/recipes/52-look.md +108 -0
  98. package/examples/action/GAMEMAP.md +5 -5
  99. package/examples/action/content/index.js +2 -1
  100. package/examples/action/content/views.js +6 -0
  101. package/examples/sheepisland/GAMEMAP.md +2 -3
  102. package/examples/styletest/GAMEMAP.md +3 -3
  103. package/examples/styletest/main.js +1 -1
  104. package/examples/styletest/panel.js +3 -3
  105. package/examples/world/GAMEMAP.md +3 -3
  106. package/index.d.ts +27 -0
  107. package/index.js +3 -1
  108. package/llms.txt +5 -0
  109. package/modules/ambience/Ambience.js +5 -2
  110. package/modules/camera/FirstPersonCamera.js +3 -5
  111. package/modules/camera/FixedCamera.js +19 -12
  112. package/modules/camera/FollowCamera.js +14 -8
  113. package/modules/camera/RtsCamera.js +3 -5
  114. package/modules/camera/common.js +40 -10
  115. package/modules/camera/index.js +1 -1
  116. package/modules/camera/projection.js +34 -0
  117. package/modules/characters/Character.js +29 -17
  118. package/modules/characters/astar.js +14 -7
  119. package/modules/characters/index.js +6 -3
  120. package/modules/characters/movers/simple.js +6 -1
  121. package/modules/characters/npcSim.js +8 -2
  122. package/modules/characters/pathAsync.js +12 -6
  123. package/modules/characters/pathJob.js +2 -1
  124. package/modules/characters/proceduralRig.js +5 -1
  125. package/modules/characters/useModel.js +22 -0
  126. package/modules/characters/walkTo.js +58 -0
  127. package/modules/collision/Collision.js +102 -4
  128. package/modules/content/explain.js +13 -0
  129. package/modules/content/index.js +2 -0
  130. package/modules/content/loader.js +3 -0
  131. package/modules/content/rules.js +1 -0
  132. package/modules/debug/DebugPanel.js +11 -5
  133. package/modules/entities/Entities.js +6 -2
  134. package/modules/flow/index.js +5 -2
  135. package/modules/gameplay/Dialogue.js +5 -2
  136. package/modules/gameplay/Interactions.js +12 -2
  137. package/modules/gameplay/Inventory.js +21 -11
  138. package/modules/gameplay/Quests.js +13 -3
  139. package/modules/gameplay/pickups.js +5 -3
  140. package/modules/grid/Layer.js +1 -1
  141. package/modules/grid/index.js +1 -1
  142. package/modules/grid/tiles.js +9 -5
  143. package/modules/hlod/index.js +5 -2
  144. package/modules/hud/index.js +5 -2
  145. package/modules/level/index.js +5 -3
  146. package/modules/lights/index.js +5 -2
  147. package/modules/music/Music.js +6 -2
  148. package/modules/nav/index.js +5 -3
  149. package/modules/net/Client.js +4 -3
  150. package/modules/net/Host.js +2 -2
  151. package/modules/net/index.js +5 -3
  152. package/modules/particles/Particles.js +1 -1
  153. package/modules/photo/Photo.js +10 -7
  154. package/modules/rigid/RigidBodies.js +5 -2
  155. package/modules/settings/Settings.js +6 -3
  156. package/modules/settings/apply.js +2 -1
  157. package/modules/sky/Sky.js +21 -19
  158. package/modules/sky/cascades.js +6 -6
  159. package/modules/sky/domeLayers.js +1 -1
  160. package/modules/sky/environment.js +39 -13
  161. package/modules/sky/fog.js +9 -6
  162. package/modules/sky/frame.js +4 -3
  163. package/modules/sky/look.js +3 -2
  164. package/modules/sky/lookFog.js +80 -0
  165. package/modules/sky/lookShadow.js +50 -0
  166. package/modules/sky/lookSky.js +108 -0
  167. package/modules/sky/shader.js +2 -2
  168. package/modules/sky/shadow.js +4 -10
  169. package/modules/sky/skyModule.js +4 -3
  170. package/modules/terrain/ChunkManager.js +2 -33
  171. package/modules/terrain/chunkLevels.js +40 -0
  172. package/modules/terrain/index.js +10 -2
  173. package/modules/terrain/lookGround.js +61 -0
  174. package/modules/timeline/Timeline.js +7 -3
  175. package/modules/timeline/Tween.js +3 -7
  176. package/modules/timeline/shots.js +6 -4
  177. package/modules/triggers/index.js +9 -2
  178. package/modules/vegetation/Vegetation.js +2 -1
  179. package/modules/vegetation/index.js +6 -3
  180. package/modules/vegetation/lookWind.js +37 -0
  181. package/modules/water/Water.js +19 -3
  182. package/modules/water/look.js +80 -0
  183. package/modules/weather/Weather.js +22 -31
  184. package/modules/weather/look.js +75 -0
  185. package/modules/weather/particles.js +1 -1
  186. package/modules/weather/strings.js +15 -0
  187. package/modules/world/explain.js +11 -0
  188. package/modules/world/index.js +11 -4
  189. package/modules/world/thingSource.js +44 -0
  190. package/package.json +1 -1
  191. package/render/PostFX.js +48 -51
  192. package/render/effects.js +4 -2
  193. package/render/fuse.js +12 -0
  194. package/render/lights.js +4 -2
  195. package/render/lookSurface.js +161 -0
  196. package/render/materials.js +27 -10
  197. package/render/postLook.js +86 -0
  198. package/render/surface.js +3 -1
  199. package/types/core.d.ts +216 -24
  200. package/types/gameplay.d.ts +10 -0
  201. package/types/generated/core/DebugOverrides.d.ts +52 -0
  202. package/types/generated/core/Events.d.ts +43 -0
  203. package/types/generated/core/Ops.d.ts +62 -21
  204. package/types/generated/core/Saves.d.ts +1 -0
  205. package/types/generated/core/Views.d.ts +33 -0
  206. package/types/generated/modules/debug/DebugPanel.d.ts +2 -2
  207. package/types/generated/modules/grid/Layer.d.ts +1 -0
  208. package/types/generated/modules/sky/Sky.d.ts +10 -17
  209. package/types/generated/modules/weather/Weather.d.ts +5 -15
  210. package/types/generated/render/PostFX.d.ts +20 -23
  211. package/types/generated/render/materials.d.ts +10 -0
  212. package/types/physics.d.ts +8 -0
  213. package/types/style.d.ts +16 -6
  214. package/ui/Parts.js +6 -2
  215. package/ui/UI.js +1 -1
  216. package/ui/defaults.js +1 -1
  217. package/docs/api/debug.md +0 -10
@@ -0,0 +1,75 @@
1
+ // look.weather: rain / snow particles, lightning flash and the overcast color as a look part (recipes/52-look.md).
2
+ // set({ 'rain.color', 'rain.speed', 'snow.size', 'lightning.brightness', overcastColor ... }) rebuilds that field's particle system once (a few ms)
3
+ // patch('rain.vertex' | 'rain.fragment' | 'snow.vertex' | 'snow.fragment', glsl) the WHOLE shader text, not a function (see shaders.js)
4
+ // replace({ rain: spec, ash: spec }) spec = the keys of style.weather.rain or { create(engine, { area, count }) => { object, update } }; null gives back
5
+ // The old engine.weather call with a field name was renamed in 0.2 (it throws): use replace({ [field]: spec }).
6
+ // Why the shader stays whole (decision #9): the rain / snow shaders move vertices and size points; a function hook would hide most of that.
7
+ import { defineLookPart, REPLACE } from '../../core/look/part.js';
8
+ import { warnOnce } from '../../core/validate.js';
9
+ import { RAIN, SNOW, dropSystem } from './particles.js';
10
+
11
+ const WHY = { rain: 'built-in rain: streaks drawn while a weather type has rain > 0', snow: 'built-in snow: flakes drawn while a weather type has snow > 0' };
12
+ const OFF = { rain: "leave 'rain' out of the weather table (no particles are built), or look.weather.set({ 'rain.opacity': 0 })", snow: "leave 'snow' out of the weather table, or look.weather.set({ 'snow.opacity': 0 })" };
13
+ const KEYS = { rain: ['color', 'opacity', 'length', 'speed', 'slant'], snow: ['color', 'opacity', 'size', 'speed', 'sway'] };
14
+ const BASE = { rain: RAIN, snow: SNOW };
15
+ const FIELDS = ['rain', 'snow'], STAGES = ['vertex', 'fragment'];
16
+
17
+ /** { 'rain.color': { type, default, why, off } ... } built from the particle defaults, so the numbers live in one place (particles.js) */
18
+ const rows = () => Object.fromEntries(FIELDS.flatMap(f => KEYS[f].map(k => [`${f}.${k}`,
19
+ { type: k === 'color' ? 'any' : 'number', default: BASE[f][k], ...(k === 'color' ? {} : { min: 0 }), cost: 'gpu', why: WHY[f], off: OFF[f] }])));
20
+
21
+ /** @param {any} w the Weather module */
22
+ export function defineWeatherLook(w) {
23
+ const e = w.engine, st = e.style.weather ?? {}, { cover, ...snowStyle } = st.snow ?? {};
24
+ const styleSpec = f => (f === 'snow' ? snowStyle : st[f] ?? {});
25
+ let applied = {}; // fields a replace() holds now: field -> spec
26
+ const rebuild = f => {
27
+ if (applied[f]) return; // replace() owns this field
28
+ if (!w.systems.has(f)) { warnOnce(`look.weather: this game's weather table has no ${f}, so there are no ${f} particles to change; add a type with ${f}: 1 to weather({ types })`); return; }
29
+ const v = p.values(), s = styleSpec(f), g = { ...s.glsl };
30
+ for (const h of STAGES) { const x = p.value(`hook:${f}.${h}`); if (x) g[h] = x; }
31
+ w._build(f, { ...s, ...Object.fromEntries(KEYS[f].map(k => [k, v[`${f}.${k}`]])), ...(Object.keys(g).length ? { glsl: g } : {}) }, BASE[f]);
32
+ };
33
+ const p = defineLookPart(e, {
34
+ id: 'weather', group: 'dynamic', module: 'weather', object: () => w.systems, docs: ['recipes/52-look.md'], applyAtStart: false,
35
+ params: {
36
+ ...rows(),
37
+ 'lightning.brightness': { type: 'number', default: 1, min: 0, neutral: true, cost: 'uniform', desc: 'how bright the sky flashes at a strike' },
38
+ overcastColor: { type: 'any', default: 0x8c8c8c, cost: 'uniform', why: 'sky and fog turn this gray as a weather type raises grey', off: 'weather types with grey: 0 never use it' },
39
+ },
40
+ style: () => ({
41
+ ...Object.fromEntries(FIELDS.flatMap(f => KEYS[f].filter(k => styleSpec(f)[k] !== undefined).map(k => [`${f}.${k}`, styleSpec(f)[k]]))),
42
+ ...Object.fromEntries(FIELDS.flatMap(f => STAGES.filter(h => styleSpec(f).glsl?.[h]).map(h => [`hook:${f}.${h}`, styleSpec(f).glsl[h]]))),
43
+ 'lightning.brightness': st.lightningBrightness, overcastColor: st.overcastColor,
44
+ }),
45
+ read: () => ({}),
46
+ apply(v, changed) {
47
+ if (changed.has('lightning.brightness')) w.flashStrength = v['lightning.brightness'];
48
+ if (changed.has('overcastColor')) w.grey.set(v.overcastColor);
49
+ for (const f of FIELDS) if ([...changed].some(k => k.startsWith(f + '.'))) rebuild(f);
50
+ },
51
+ hooks: Object.fromEntries(FIELDS.flatMap(f => STAGES.map(h => [`${f}.${h}`, { signature: 'whole GLSL shader text (copy it from modules/weather/shaders.js)', scope: ['uCam', 'uSize', 'uFallOff', 'uOpacity', 'uColor'] }]))),
52
+ applyHook(name) { rebuild(name.split('.')[0]); },
53
+ replace: { accepts: '{ <field>: spec } with spec = the keys of style.weather.rain, or { create(engine, { area, count }) => { object, update?(amount, ctx) } }; null gives the fields back',
54
+ loses: ['the style rain / snow look of every field named in the object (look.weather.set values for it are ignored while it holds)'] },
55
+ // a wrong replace value stops here, before any layer is written (the throw used to come from applyReplace, after the write)
56
+ validate: (k, v) => {
57
+ if (k !== REPLACE) return null;
58
+ if (v != null && (typeof v !== 'object' || Array.isArray(v))) return "is { <field>: spec }, e.g. replace({ ash: { shape: 'soft', color: 0x555555 } }); see recipes/44-water-weather-look-hooks.md";
59
+ const fields = [...new Set(Object.values(w.types).flatMap(t => Object.keys(t)))], bad = Object.keys(v ?? {}).find(f => !fields.includes(f));
60
+ return bad ? `no weather type has a field '${bad}'; add it to a type in weather({ types }) (e.g. ashfall: { ${bad}: 1 }), or use one of ${fields.join(', ')}` : null;
61
+ },
62
+ applyReplace(impl) {
63
+ const next = impl ?? {}, old = applied;
64
+ applied = next;
65
+ for (const f of new Set([...Object.keys(old), ...Object.keys(next)])) {
66
+ if (next[f] && next[f] === old[f]) continue; // unchanged: keep the system (and any handle the game holds)
67
+ if (next[f]) w._build(f, next[f], BASE[f]);
68
+ else if (BASE[f]) rebuild(f);
69
+ else { const s = w.systems.get(f); if (s) { dropSystem(e, s); w.systems.delete(f); } }
70
+ }
71
+ },
72
+ });
73
+ return p;
74
+ }
75
+
@@ -1,5 +1,5 @@
1
1
  // Weather particle systems (recipes/44). Built-in rain and snow are two specs of one falling-particle system; a game draws a field of its
2
- // own table (ash, petals, sparks) with engine.weather.define(field, spec), and the same call replaces rain or snow. The amount each frame is
2
+ // own table (ash, petals, sparks) with engine.look.weather.replace({ field: spec }), and the same call replaces rain or snow. The amount each frame is
3
3
  // weather.current[field], so the table's smooth blending drives particles too.
4
4
  //
5
5
  // spec (style.weather.rain / snow, or define): shape 'line' (streaks that slant with the wind) | 'round' | 'soft' | 'square' (point sprites
@@ -0,0 +1,15 @@
1
+ // Weather display names (string table weather.<name>); a game that adds a weather adds its name with i18n.add.
2
+ export const STRINGS = {
3
+ 'zh-CN': { 'weather.clear': '晴', 'weather.cloudy': '多云', 'weather.overcast': '阴', 'weather.rain': '雨', 'weather.storm': '暴雨',
4
+ 'weather.snow': '雪', 'weather.fog': '雾', 'weather.auto': '自动变化' },
5
+ en: { 'weather.clear': 'Clear', 'weather.cloudy': 'Cloudy', 'weather.overcast': 'Overcast', 'weather.rain': 'Rain', 'weather.storm': 'Storm',
6
+ 'weather.snow': 'Snow', 'weather.fog': 'Fog', 'weather.auto': 'Auto' },
7
+ };
8
+
9
+ // Errors of weather() / the weather table
10
+ export const ERR = {
11
+ types: "weather({ types }): the game's weather table, name -> { cloud, sun, fog, wind, rain, snow, grey, lightning } (left-out fields are calm), at least one; got {got}. Seven temperate ones: weather(presets.weather.temperate) with presets from 'threedog'",
12
+ field: "weather type '{k}': field {f} must be a number (every field blends smoothly on change); got {got}",
13
+ start: "weather({ start }): '{got}' is not one of this game's weather types ({list})",
14
+ pool: "weather({ autoPool }): '{got}' is not one of this game's weather types ({list})",
15
+ };
@@ -0,0 +1,11 @@
1
+ // World's contribution to thing.explain() (core/thingExplain.js): the record's fields as `state`, and the record's own collision / picking rules.
2
+ // Template rules come from the content module's explainer (content/explain.js), which runs after this and overrides these.
3
+
4
+ /** @internal Fill state and rules for a thing that has a world record */
5
+ export function worldExplain(e, t, out) {
6
+ const rec = e.world?.get(t.id);
7
+ if (!rec) return;
8
+ out.state = { ...t.fields, position: t.position };
9
+ Object.assign(out.rules, { blocksMovement: rec.collide ?? false, pickable: rec.static !== false, interact: null, note: RULES_NOTE });
10
+ }
11
+ export const RULES_NOTE = 'blocksMovement = the collision shape (box / circle) walkers stop at; blocking sight is not modelled by the engine';
@@ -2,14 +2,19 @@
2
2
  // engine.use(world()) // the openWorld() preset installs it by default
3
3
  // engine.use(world({ radius: 80 })) // distance (meters) for building models and counting as near, default 60
4
4
  // Save key world (runtime records whole, initial records only changes and removals, see the top of World.js); emits world:load after loading. The loading screen waits for world.ready (nearby models all built). describe() reports world.total / byKind / presented, and nearby records with a name go into nearby.
5
+ import { recordSource } from './thingSource.js';
5
6
  import { World } from './World.js';
6
7
  import { WORLD_MIGRATE } from './persist.js';
7
- import { checkOptions, closest, warnOnce, DEV } from '../../core/validate.js';
8
+ import { worldExplain } from './explain.js';
9
+ import { closest, warnOnce, DEV } from '../../core/validate.js';
10
+ import { readParams, keysSchema } from '../../core/params.js';
8
11
 
9
12
  const ORPHAN = '[world] the save has changes for {n} id(s) that the content no longer defines: {list}. They are kept in the save (restoring the entry brings them back); '
10
13
  + "if an entry was renamed, add the pair to content/renames.js (export default { 'oldId': 'newId' }) and the saved state follows it; 'oldId': null drops it";
11
14
  const RENAME_TARGET = '[world] content/renames.js moves saved state to {list}, which no content entry defines: fix the new id (did you mean {near}?)';
12
15
 
16
+ const WORLD_PARAMS = keysSchema(['cellSize', 'radius', 'farEvery', 'farMaxPerTick', 'buildPerFrame']);
17
+
13
18
  /**
14
19
  * World data module: installed as engine.world. Put things here that must be saved, survive level changes and keep changing while far away; models are only built while nearby
15
20
  * @example engine.use(world())
@@ -17,15 +22,17 @@ const RENAME_TARGET = '[world] content/renames.js moves saved state to {list}, w
17
22
  * @returns {import('../../types/core').ModuleDef<World>}
18
23
  */
19
24
  export function world(opts = {}) {
20
- checkOptions('world()', opts, ['cellSize', 'radius', 'farEvery', 'farMaxPerTick', 'buildPerFrame']);
25
+ readParams('world', WORLD_PARAMS, opts);
21
26
  let w = null;
22
27
  return {
23
- name: 'world', label: 'World data', stage: 'world',
28
+ name: 'world', label: 'World data', params: WORLD_PARAMS, options: opts, stage: 'world',
24
29
  install(e) {
25
30
  w = new World(e, opts);
26
31
  e.stream.player.at(() => w.center); // the default stream source sits where gameplay is simulated (world.anchor, else the player)
27
32
  e.stream.readyCheck('world', s => s.detail !== 'full' || w.ready);
28
- e.saves.register('world', { version: 3, migrate: WORLD_MIGRATE, save: () => w.toJSON(), load: d => w.fromJSON(d) });
33
+ e.saves.register('world', { atomic: true, version: 3, migrate: WORLD_MIGRATE, save: () => w.toJSON(), load: d => w.fromJSON(d) });
34
+ e._things.addSource(recordSource(w)); // engine.thing / thing.set / the shared id space reach the records through this
35
+ e.explainWith(worldExplain);
29
36
  e.budget.metric('worldRecords', () => w.records.size);
30
37
  if (DEV) { // orphans are known once content loaded (engine:ready), after a load, and per level for `<level>/<node>` ids
31
38
  const warn = () => {
@@ -0,0 +1,44 @@
1
+ // What the world module tells core about its records: engine._things.addSource(...) at install. Core knows only this shape (has / get / set / remove /
2
+ // explain, plus idOf / view / ids / restore for the model link and undo), never the World class, so engine.thing, thing.set and the shared id space
3
+ // work the same whether or not this module is installed.
4
+ const SAY = {
5
+ defined: 'defined in {at}: edit it there to change the level for good (ops change only this session), or: npx threedog content set {id} <field> <json>',
6
+ node: 'level {level} node {node}: change it in the level model',
7
+ spawned: 'made during play{op}: not in content, saved whole',
8
+ };
9
+ const NOT_FIELDS = new Set(['id', 'kind', 'position', 'zone', 'floor', 'offsetY']);
10
+
11
+ /** The record as a thing to change: id, kind, template, where it was authored (definedAt / level node / spawned by which op), model and its fields */
12
+ function describeRecord(w, id) {
13
+ const rec = w.get(id); if (!rec) return null;
14
+ const o = w.origin(id) ?? {}, fields = {};
15
+ for (const k in rec) if (!NOT_FIELDS.has(k)) fields[k] = rec[k];
16
+ const how = o.definedAt ? SAY.defined.replace('{at}', o.definedAt).replace('{id}', id) : o.node ? SAY.node.replace('{level}', o.level).replace('{node}', o.node)
17
+ : o.spawned ? SAY.spawned.replace('{op}', o.spawned.op ? ` by op ${o.spawned.op} at tick ${o.spawned.tick}` : '') : null;
18
+ return { id, kind: rec.kind, template: o.template ?? null, definedAt: o.definedAt ?? null, ...(o.templateAt && { templateAt: o.templateAt }),
19
+ ...(o.node && { level: o.level, node: o.node }), ...(o.spawned && { spawned: o.spawned }), model: o.model ?? rec.model ?? null,
20
+ position: { ...rec.position }, fields, edit: how };
21
+ }
22
+
23
+ /** @param {any} w the World @returns the record source for engine._things.addSource @internal */
24
+ export function recordSource(w) {
25
+ return {
26
+ name: 'world',
27
+ has: id => !!w.get(id),
28
+ get: id => w.get(id),
29
+ ids: () => w.query({}).map(r => r.id),
30
+ idOf: obj => w.idOf(obj),
31
+ view: id => w.view(id),
32
+ explain: id => describeRecord(w, id),
33
+ /** Change a record (position / rot / scale); returns the values it replaced (set(id, thatValue) is the undo) */
34
+ set(id, patch) {
35
+ // rot / scale are the template instance fields (templates.js); a record without them reads as rot 0, scale 1
36
+ const rec = w.get(id), before = { position: { ...rec.position }, ...(patch.rot != null && { rot: rec.rot ?? 0 }), ...(patch.scale != null && { scale: rec.scale ?? 1 }) };
37
+ w.set(id, patch);
38
+ return before;
39
+ },
40
+ /** Remove a record; returns what restore needs */
41
+ remove(id) { const rec = structuredClone(w.get(id)), authored = w.authored(id); w.remove(id); return { rec, authored }; },
42
+ restore: ({ rec, authored }) => w.restore(rec, authored),
43
+ };
44
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "threedog",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Web 3D game engine on three.js for large low-poly worlds: core + modules + style packs, built to be driven by an AI",
5
5
  "license": "MIT",
6
6
  "repository": {
package/render/PostFX.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // Post-processing as an ordered list of named effects in four slots. The engine owns no look of its own here: bloom, AO and
2
- // outline are effects a style pack registers (they come from @threedog/post-effects); games add theirs with engine.post.add().
2
+ // outline are effects a style pack registers (they come from @threedog/post-effects); games add theirs with look.post.replace([...]).
3
3
  // An effect promises only a name, params and on/off; how it draws is its create() (a three.js Pass under WebGLRenderer),
4
4
  // so a WebGPU backend can later bring its own implementation without changing callers.
5
5
  //
@@ -13,8 +13,10 @@ import * as THREE from 'three';
13
13
  import { EffectComposer } from 'three/addons/postprocessing/EffectComposer.js';
14
14
  import { RenderPass } from 'three/addons/postprocessing/RenderPass.js';
15
15
  import { OutputPass } from 'three/addons/postprocessing/OutputPass.js';
16
- import { warnMissing } from '../core/validate.js';
17
- import { FusedPass, groupFuse } from './fuse.js';
16
+ import { warnMissing, warnOnce } from '../core/validate.js';
17
+ import { renamed } from '../core/errorHints.js';
18
+ import { FusedPass, groupFuse, checkDepthOrder } from './fuse.js';
19
+ import { definePostLook } from './postLook.js';
18
20
  /** @import { Engine } from '../types/core' */
19
21
 
20
22
  /**
@@ -40,23 +42,11 @@ import { FusedPass, groupFuse } from './fuse.js';
40
42
  * RenderPixelatedPass, or the tone-mapping output); the chain throws when it would not. A pass that writes the scene depth into its own output (gl_FragDepth, then set pass.keepsDepth = true; dof does) does not count as a swap. update: apply new params in place;
41
43
  * without it set() rebuilds the implementation.
42
44
  * @typedef {{ readonly name: string, readonly slot: PostSlot, readonly order: number, readonly enabled: boolean,
43
- * readonly params: Record<string, any>, enable(on: boolean): void, set(params: Record<string, any>): void, remove(): void }} PostHandle
45
+ * readonly params: Record<string, any> }} PostHandle
44
46
  */
45
47
 
46
48
  const SLOTS = ['scene', 'hdr', 'ldr', 'final'];
47
49
 
48
- // Only the buffer the scene render wrote holds scene depth: after a pass that swaps buffers, readBuffer.depthTexture is another
49
- // target's (a fullscreen quad's, or stale). A depth reader behind such a pass would silently find nothing, so the chain refuses it.
50
- function checkDepthOrder(chain) {
51
- let swapped = null;
52
- for (const e of chain) {
53
- if (e._def?.needsDepth && swapped)
54
- throw new Error(`post effect '${e.name}' reads scene depth (needsDepth) but runs after '${swapped}', which swaps buffers, so the depth it would read is not the scene's; ` +
55
- `give '${e.name}' a lower order or an earlier slot than '${swapped}', or turn one of them off`);
56
- if (e._impl.needsSwap && !e._impl.keepsDepth) swapped ??= e.name;
57
- }
58
- }
59
-
60
50
  export class PostFX {
61
51
  /**
62
52
  * @param {Engine} engine
@@ -75,13 +65,22 @@ export class PostFX {
75
65
  /** @internal */ this._scenePass = /** @type {any} */ (null);
76
66
  /** @internal */ this._output = /** @type {any} */ (null);
77
67
  /** @internal */ this._building = true; // add() skips chain rebuilds until every style effect is in
78
- for (const e of effects) this.add(e, { enabled: enabled[e.name] ?? (e.costly && engine.tier === 'low' ? false : undefined) });
68
+ /** Why a costly effect started off (name -> reason), shown by describe().render and logged once: a silent "bloom is missing" in headless / software rendering looked like a bug @internal */
69
+ this._offWhy = /** @type {Record<string, string>} */ ({});
70
+ for (const e of effects) {
71
+ const lowOff = enabled[e.name] == null && e.costly && engine.tier === 'low';
72
+ if (lowOff) this._offWhy[e.name] = `starts off: costly effect on a low-tier device (${engine.headless ? 'headless runs use software rendering, which is low tier' : 'weak GPU or software rendering'}); turn it on with createEngine({ post: { ${e.name}: true } }) or engine.look.post.set({ '${e.name}.enabled': true })`;
73
+ this._add(e, { enabled: enabled[e.name] ?? (lowOff ? false : undefined) });
74
+ }
75
+ const why = Object.entries(this._offWhy);
76
+ if (why.length) warnOnce(`post: ${why.map(([n]) => n).join(', ')} ${why.length > 1 ? 'are' : 'is'} off by default here. ${why[0][1]}`);
79
77
  this._building = false;
80
78
  this._sync();
79
+ /** look.post: the style's effects are its style layer; look.post.set writes its 'game' layer @internal */ this._look = definePostLook(this, effects);
81
80
  }
82
81
 
83
82
  /**
84
- * MSAA on (read-only; switch with post.enable('antialias', on))
83
+ * MSAA on (read-only; switch with post.setAntialias(on))
85
84
  * @returns {boolean}
86
85
  */
87
86
  get antialias() { return this._aa; }
@@ -92,22 +91,18 @@ export class PostFX {
92
91
  get active() { return this._aa || this._list.some(e => e.enabled); }
93
92
 
94
93
  /**
95
- * Add a named effect; returns its handle. Slot and order come from the effect unless given here.
96
- * @example
97
- * import { RenderPixelatedPass } from 'three/addons/postprocessing/RenderPixelatedPass.js';
98
- * const pixels = engine.post.add({ name: 'pixelate', slot: 'scene', params: { size: 4 },
99
- * create: ({ scene, camera, width, height, params }) => new RenderPixelatedPass(params.size, scene, camera),
100
- * update: (pass, p) => pass.setPixelSize(p.size) });
101
- * pixels.set({ size: 6 }); pixels.enable(false); pixels.remove();
102
- * @param {PostEffect} effect
103
- * @param {{ slot?: PostSlot, order?: number, enabled?: boolean }} [opts]
104
- * @returns {PostHandle}
94
+ * Renamed in 0.2: throws and names the new call (engine.look.post.patch / engine.look.post.replace, recipes/52-look.md)
95
+ * @param {PostEffect} _effect
96
+ * @param {{ slot?: PostSlot, order?: number, enabled?: boolean }} [_opts]
97
+ * @returns {never}
105
98
  * @experimental
106
99
  */
107
- add(effect, { slot, order, enabled } = {}) {
100
+ add(_effect, _opts) { return renamed('postAdd'); }
101
+ /** Effects are added by look.post (patch generates a fuse effect, replace swaps the chain) with this @internal */
102
+ _add(effect, { slot, order, enabled } = {}) {
108
103
  if (!effect || typeof effect.name !== 'string' || (typeof effect.create !== 'function' && !effect.fuse))
109
- throw new Error("post.add(effect): effect needs { name: 'myEffect', create: (ctx) => pass } (or a fuse snippet, see PostEffect)");
110
- if (this.get(effect.name)) throw new Error(`post effect '${effect.name}' is already added; change it with post.get('${effect.name}').set(params), or remove() it first`);
104
+ throw new Error("post effect: needs { name: 'myEffect', create: (ctx) => pass } (or a fuse snippet, see PostEffect)");
105
+ if (this.get(effect.name)) throw new Error(`post effect '${effect.name}' is already added; change it with look.post.set({ '${effect.name}.<param>': value }), or drop it with look.post.replace([...])`);
111
106
  const s = slot ?? effect.slot ?? 'hdr';
112
107
  if (!SLOTS.includes(s)) throw new Error(`post effect '${effect.name}': unknown slot '${s}', use ${SLOTS.join(' | ')}`);
113
108
  if (effect.fuse && s === 'scene') throw new Error(`post effect '${effect.name}': a fuse snippet colors an existing image, it cannot replace the scene render; use slot 'hdr' | 'ldr' | 'final'`);
@@ -117,14 +112,17 @@ export class PostFX {
117
112
  const h = {
118
113
  name: effect.name, slot: s, order: order ?? effect.order ?? 0, enabled: enabled ?? effect.enabled ?? true,
119
114
  params: { ...effect.params }, _def: effect, _impl: /** @type {any} */ (null), _removed: false,
120
- enable(on) { const was = h.enabled; post._change(() => { h.enabled = !!on; }, () => { h.enabled = was; }); },
121
- set(p) {
115
+ enable() { return renamed('postHandle'); }, // the old handle verbs throw renamed-api; look.post writes through _enable / _set / _remove
116
+ set() { return renamed('postHandle'); },
117
+ remove() { return renamed('postHandle'); },
118
+ _enable(on) { const was = h.enabled; post._change(() => { h.enabled = !!on; }, () => { h.enabled = was; }); },
119
+ _set(p) {
122
120
  Object.assign(h.params, p);
123
121
  if (effect.fuse) { for (const p of post._fused.values()) p.refresh(); return; }
124
122
  if (!h._impl) return;
125
123
  if (effect.update) effect.update(h._impl, h.params); else { h._impl.dispose?.(); h._impl = null; post._sync(); }
126
124
  },
127
- remove() {
125
+ _remove() {
128
126
  if (h._removed) return;
129
127
  h._removed = true; h._impl?.dispose?.(); h._impl = null;
130
128
  post._list = post._list.filter(e => e !== h); post._sync();
@@ -135,32 +133,31 @@ export class PostFX {
135
133
  return h;
136
134
  }
137
135
  /**
138
- * Handle of an added effect, or undefined: engine.post.get('bloom')?.set({ strength: 0.6 })
136
+ * Read-only record of an added effect (name, slot, order, enabled, params), or undefined. Change one with engine.look.post.set({ 'bloom.strength': 0.6 })
139
137
  * @param {string} name
140
138
  * @returns {PostHandle | undefined}
141
139
  * @experimental
142
140
  */
143
141
  get(name) { return this._list.find(e => e.name === name); }
144
142
  /**
145
- * Turn an effect, or 'antialias' (MSAA), on or off; false (and a dev warning naming the effects) when no such effect is added
146
- * @example
147
- * engine.post.enable('bloom', false); engine.post.enable('antialias', true);
148
- * @param {string} name
143
+ * Renamed in 0.2: throws and names the new call (engine.look.post.set({ 'bloom.enabled': on }); MSAA: engine.post.setAntialias(on))
144
+ * @param {string} _name
145
+ * @param {boolean} _on
146
+ * @returns {never}
147
+ * @experimental
148
+ */
149
+ enable(_name, _on) { return renamed('postEnable'); }
150
+ /**
151
+ * Turn MSAA (antialiasing of the post chain) on or off. It is a render target setting, not a look part.
152
+ * @example engine.post.setAntialias(false);
149
153
  * @param {boolean} on
150
- * @returns {boolean}
154
+ * @returns {void}
151
155
  * @experimental
152
156
  */
153
- enable(name, on) {
154
- if (name === 'antialias') {
155
- this._aa = !!on;
156
- if (this.composer) for (const rt of [this.composer.renderTarget1, this.composer.renderTarget2]) { rt.samples = on ? 4 : 0; rt.dispose(); }
157
- this._sync();
158
- return true;
159
- }
160
- const h = this.get(name);
161
- if (!h) { warnMissing('post effect', name, ['antialias', ...this._list.map(e => e.name)]); return false; }
162
- h.enable(on);
163
- return true;
157
+ setAntialias(on) {
158
+ this._aa = !!on;
159
+ if (this.composer) for (const rt of [this.composer.renderTarget1, this.composer.renderTarget2]) { rt.samples = on ? 4 : 0; rt.dispose(); }
160
+ this._sync();
164
161
  }
165
162
  /**
166
163
  * Effects in render order: [{ name, slot, order, enabled }]
package/render/effects.js CHANGED
@@ -14,6 +14,7 @@ const UNIFORM_DEFAULTS = {
14
14
  uCloudScale: 0.006, // cloud size (smaller = bigger clouds)
15
15
  uCloudSpeed: () => new THREE.Vector2(0.012, 0.006), // cloud drift direction and speed
16
16
  uWindFreq: 1, // sway frequency multiplier
17
+ uWindAmp: 1, // sway amplitude multiplier (look.wind.amplitude); every wind patch's amplitude is scaled by it
17
18
  uFoliageTint: () => new THREE.Color(1, 1, 1), // season: foliage tint (driven by the sky module's calendar)
18
19
  uGroundTint: () => new THREE.Color(1, 1, 1), // season: ground tint
19
20
  uFoliageMix: 0, uGroundMix: 0, // season mode 'mix': how far the surface moves to the tint (0 = multiply, the default)
@@ -111,8 +112,9 @@ export const EFFECTS = {
111
112
  'reflectedLight.directDiffuse *= threedogCloudLight(vThreedogWorld.xz);\n reflectedLight.directSpecular *= threedogCloudLight(vThreedogWorld.xz);' } } }),
112
113
  // wind(amplitude) or wind(amplitude, { glsl, uniforms, decl }): a style's own sway function replaces the default one (see StyleWind in types/style.d.ts)
113
114
  wind: (amplitude, custom) => ({ name: 'wind', cacheKey: custom ? `${amplitude}|${hashText(custom.glsl)}` : amplitude, shadow: true,
114
- uniforms: { ...pick('uTime', 'uWind', 'uWindFreq'), ...custom?.uniforms }, glsl: {
115
- vertex: { pars: `#define THREEDOG_WIND_AMP ${(+amplitude).toFixed(4)}
115
+ uniforms: { ...pick('uTime', 'uWind', 'uWindFreq', 'uWindAmp'), ...custom?.uniforms }, glsl: {
116
+ vertex: { pars: `uniform float uWindAmp;
117
+ #define THREEDOG_WIND_AMP (${(+amplitude).toFixed(4)} * uWindAmp)
116
118
  #include <threedog_wind_pars_vertex>` + (custom
117
119
  ? `
118
120
  #define THREEDOG_WIND_CUSTOM
package/render/fuse.js CHANGED
@@ -70,3 +70,15 @@ export function groupFuse(on) {
70
70
  }
71
71
  return out;
72
72
  }
73
+
74
+ // Only the buffer the scene render wrote holds scene depth: after a pass that swaps buffers, readBuffer.depthTexture is another
75
+ // target's (a fullscreen quad's, or stale). A depth reader behind such a pass would silently find nothing, so the chain refuses it.
76
+ export function checkDepthOrder(chain) {
77
+ let swapped = null;
78
+ for (const e of chain) {
79
+ if (e._def?.needsDepth && swapped)
80
+ throw new Error(`post effect '${e.name}' reads scene depth (needsDepth) but runs after '${swapped}', which swaps buffers, so the depth it would read is not the scene's; ` +
81
+ `give '${e.name}' a lower order or an earlier slot than '${swapped}', or turn one of them off`);
82
+ if (e._impl.needsSwap && !e._impl.keepsDepth) swapped ??= e.name;
83
+ }
84
+ }
package/render/lights.js CHANGED
@@ -6,11 +6,13 @@
6
6
  import * as THREE from 'three';
7
7
 
8
8
  /** @param {any} engine @returns {{ sun: THREE.DirectionalLight, hemi: THREE.HemisphereLight }} */
9
- export function createDefaultLights(engine) {
9
+ export function createDefaultLights(engine, { add = true } = {}) {
10
10
  const hemi = new THREE.HemisphereLight(0xffffff, 0x555555, 1.2);
11
11
  const sun = new THREE.DirectionalLight(0xffffff, 2);
12
12
  sun.position.set(40, 80, 30); // above and to the side, so faces read with some shading
13
13
  sun.castShadow = false; // placeholder lighting casts no shadows; an installed sky module turns them on (sizes from style.sky.shadow)
14
- engine.scene.add(hemi, sun, sun.target);
14
+ // add: false (createEngine({ lights: false })): the objects still exist so engine.lights.sun / hemi and the sky module never hit undefined, but they
15
+ // are not in the scene, so nothing is lit by them and they cost no shader light slots; the game brings all its own lights
16
+ if (add) engine.scene.add(hemi, sun, sun.target);
15
17
  return { sun, hemi };
16
18
  }
@@ -0,0 +1,161 @@
1
+ // look.materials and look.surface (render/materials.js reads them when it makes a material).
2
+ // Why a file of its own: materials.js is near the size cap, and the two parts share one rule: a verb changes what makeMaterial does NEXT time
3
+ // (a Material already handed out is not touched, catalog / describe say appliesTo; rebuilding made materials from the spec costs a recompile each, so it is not done).
4
+ // Exception: plain numeric / color properties (LIVE_KEYS below) are written to the already-made materials of that role at once; they need no recompile.
5
+ // look.materials set({ wool: { roughness: 0.4 } }) merge into the role's spec (style.materials[role] stays below as the style layer)
6
+ // patch(name, shaderPatch, { roles }) add a named ShaderPatch (render/patches.js) to materials made for those roles
7
+ // replace(role, Material | fn) a role is this Material (cloned) / this (params, purpose, engine) => Material
8
+ // look.surface set({ lighting: { wrap, shadowTint, rim }, detail: {...}, ramp: [...], soften }) defaults for every spec-made material
9
+ // patch('lighting' | 'detail', glsl) the shared threedogLighting / threedogDetailSample function
10
+ import { defineLookPart } from '../core/look/part.js';
11
+ import * as THREE from 'three';
12
+ import { codedError } from '../core/errorHints.js';
13
+ import { isPlainObject as isPlain } from '../core/util.js';
14
+ import { rampTexture } from './lighting.js';
15
+
16
+ const asGlsl = v => (typeof v === 'string' ? { glsl: v } : v); // a hook value is a GLSL string or { glsl, uniforms }
17
+
18
+ /** A material spec key makeMaterial understands: its own keys (materials.js SPEC_KEYS + type) or a property of one of the three.js types it makes */
19
+ const probes = []; // one probe Material per three.js type, made on first use; page-wide on purpose (they are never rendered)
20
+ function knownSpecKey(k) {
21
+ if (['type', 'steps', 'ramp', 'soften', 'repeat', 'wrap', 'detail', 'lighting'].includes(k)) return true;
22
+ if (!probes.length) probes.push(...[THREE.MeshPhysicalMaterial, THREE.MeshLambertMaterial, THREE.MeshPhongMaterial, THREE.MeshToonMaterial, THREE.MeshBasicMaterial].map(C => new C()));
23
+ return probes.some(m => k in m);
24
+ }
25
+ /** Plain material properties that change at once on materials already made for the role (no shader change, so no recompile); every other key is for new materials only */
26
+ export const LIVE_KEYS = ['color', 'emissive', 'emissiveIntensity', 'roughness', 'metalness', 'opacity', 'envMapIntensity', 'shininess', 'specular'];
27
+ const COLOR_KEYS = new Set(['color', 'emissive', 'specular']);
28
+ /** Every Material made per role, per engine, as weak refs (a disposed material that nobody holds drops out) */
29
+ const LIVE = new WeakMap();
30
+ const liveOf = e => LIVE.get(e) ?? LIVE.set(e, new Map()).get(e);
31
+ /** The last Material made per role, per engine (look.materials.object(role)); kept here so materials.js never touches the part's fields */
32
+ const MADE = new WeakMap();
33
+ const madeOf = e => MADE.get(e) ?? MADE.set(e, new Map()).get(e);
34
+
35
+ /** Materials: role names are open, so the part grows `<role>.<specKey>` params as the style or a game mentions them */
36
+ export function defineMaterialsLook(e, purposes) {
37
+ const M = e.style.materials ?? {};
38
+ const params = {}, style = {};
39
+ const grow = (into, key) => { into[key] = { type: 'any', default: null, neutral: true, desc: 'a spec key of this role (type, color, roughness, steps, ramp, detail, lighting ...); null = not overridden' }; };
40
+ for (const [role, spec] of Object.entries(M)) if (isPlain(spec)) for (const [k, v] of Object.entries(spec)) { grow(params, `${role}.${k}`); style[`${role}.${k}`] = v; }
41
+ const made = madeOf(e);
42
+ const part = defineLookPart(e, {
43
+ id: 'materials', group: 'surface', module: 'core', docs: ['recipes/52-look.md'], params, style: () => style, appliesTo: `materials made after the change, except the live keys (${LIVE_KEYS.join(', ')}), which also change the materials already made for that role; type, steps, ramp, soften, repeat, wrap, detail, lighting, patch and replace are for new materials only`,
44
+ applyAtStart: false,
45
+ apply(v, changed) { // live keys: write them to the already-made materials of the role (a cleared key goes back to the style value, or stays when the style gave none)
46
+ for (const k of changed) {
47
+ const i = k.indexOf('.'), role = k.slice(0, i), prop = k.slice(i + 1);
48
+ if (i < 0 || !LIVE_KEYS.includes(prop)) continue;
49
+ const val = v[k] ?? style[k];
50
+ if (val == null) continue;
51
+ for (const ref of liveOf(e).get(role) ?? []) {
52
+ const m = ref.deref();
53
+ if (!m) { liveOf(e).get(role).delete(ref); continue; }
54
+ if (!(prop in m)) continue;
55
+ if (COLOR_KEYS.has(prop)) m[prop].set(val); else m[prop] = val;
56
+ }
57
+ }
58
+ },
59
+ // a function, not a map: look.materials.object('wool') is the last Material made for that role, object() all of them
60
+ object: () => role => (role === undefined ? Object.fromEntries(made) : made.get(role)),
61
+ // set({ wool: { roughnes: 1 } }) used to add the typo as a new key; now a role key must be one makeMaterial reads (review M7).
62
+ // normalize runs for set() and engine.debug.override alike, before the values are checked
63
+ normalize(p) {
64
+ const grown = {};
65
+ for (const [role, spec] of Object.entries(p)) if (isPlain(spec)) for (const k of Object.keys(spec)) if (!part.has(`${role}.${k}`)) {
66
+ if (!knownSpecKey(k)) throw codedError('look-param', `look.materials.set(): ${role}.${k} is not a material spec key (type, color, roughness, steps, ramp, detail, lighting or a three.js material property)`);
67
+ grow(grown, `${role}.${k}`);
68
+ }
69
+ if (Object.keys(grown).length) part.extend(grown);
70
+ return p;
71
+ },
72
+ hooks: { '<name>': { signature: 'a ShaderPatch { name, glsl, uniforms, needs } (render/patches.js); patch(name, spec, { roles: ["wool"] }) adds it to materials made for those roles (none = all)', scope: ['fragment', 'vertex'] } },
73
+ replace: { accepts: "replace('wool', Material | (params, purpose, engine) => Material); replace('wool', null) gives the role back to the style", loses: ['the role spec: type, steps, ramp, detail, lighting ... and look.materials.set keys for that role'] },
74
+ verbs: {
75
+ patch: { signature: 'patch(name, shaderPatch | null, { roles, owner })',
76
+ take(bad, name, spec, { roles, owner } = {}) {
77
+ if (typeof name !== 'string' || !name) bad("name is the patch's name, e.g. patch('snap', { glsl: {...} }, { roles: ['wool'] })");
78
+ if (spec != null && !isPlain(spec)) bad(`the patch is a ShaderPatch object { glsl: { vertex|fragment: {...} }, uniforms, needs } (render/patches.js); got ${typeof spec}`);
79
+ return [{ [`hook:${name}`]: spec == null ? null : { patch: { name, ...spec }, roles: roles ?? null } }, owner];
80
+ } },
81
+ replace: { signature: 'replace(role, Material | (params, purpose, engine) => Material | null, { owner })',
82
+ take(bad, role, impl, { owner } = {}) {
83
+ if (typeof role !== 'string') bad("the first argument is the role name, e.g. replace('wool', new THREE.MeshMatcapMaterial(...))");
84
+ if (impl != null && !impl.isMaterial && typeof impl !== 'function') bad(`give a three.js Material or a function (params, purpose, engine) => Material; got ${typeof impl}`);
85
+ return [{ [`replace:${role}`]: impl ?? null }, owner];
86
+ } },
87
+ },
88
+ });
89
+ return part;
90
+ }
91
+
92
+ /** What the games and debug layers changed for a role: { key: value } to lay over the role's spec (makeMaterial) */
93
+ export function materialOverrides(eng, role) {
94
+ const p = eng?.look?.materials, out = {};
95
+ if (!p) return out;
96
+ for (const [k] of p.resolved(role + '.')) { const v = p.top(k); if (v != null) out[k.slice(role.length + 1)] = v; }
97
+ return out;
98
+ }
99
+ /** replace(role, ...) from a game / debug layer, else undefined */
100
+ export const materialReplace = (eng, role) => eng?.look?.materials?.top(`replace:${role}`) ?? undefined;
101
+ /** Patches added with look.materials.patch for this role */
102
+ export function materialPatches(eng, role) {
103
+ const p = eng?.look?.materials, out = [];
104
+ if (p) for (const [, v] of p.resolved('hook:')) if (v && (!v.roles || v.roles.includes(role))) out.push(v.patch);
105
+ return out;
106
+ }
107
+ /** Remember the last Material made for a role (look.materials.object(role)) */
108
+ export function materialMade(eng, role, m) {
109
+ if (!eng) return;
110
+ madeOf(eng).set(role, m);
111
+ (liveOf(eng).get(role) ?? liveOf(eng).set(role, new Set()).get(role)).add(new WeakRef(m));
112
+ }
113
+
114
+ const needColor = name => v => (isPlain(v) && v.color !== undefined ? null : `needs a color, e.g. { color: '#334', strength: 0.5 } (${name})`);
115
+ /** Surface: the pack-wide lighting / detail / toon ramp every spec-made material starts from */
116
+ export function defineSurfaceLook(e) {
117
+ const L = e.style.lighting ?? {};
118
+ const keep = o => Object.fromEntries(Object.entries(o).filter(([, v]) => v != null));
119
+ const num = v => (typeof v === 'number' ? null : 'must be a number');
120
+ defineLookPart(e, {
121
+ id: 'surface', appliesTo: 'materials made after the change', group: 'surface', module: 'core', docs: ['recipes/52-look.md'],
122
+ params: {
123
+ 'lighting.wrap': { type: 'any', default: null, neutral: true, check: num, desc: 'half-lambert wrap 0-1: how far light bends past the terminator (softer shade edge); null = off' },
124
+ 'lighting.shadowTint': { type: 'any', default: null, neutral: true, check: needColor('shadowTint'), desc: '{ color, strength?, soft? } hue of the shaded side; null = off' },
125
+ 'lighting.rim': { type: 'any', default: null, neutral: true, check: needColor('rim'), desc: '{ color, strength?, power?, shadowSide? } edge light; null = off' },
126
+ detail: { type: 'any', default: null, neutral: true, check: v => (isPlain(v) ? null : 'must be a detail object, e.g. { noise: "grain", strength: 0.2 } (render/detail.js)'), desc: 'detail layer added to every spec-made material (a spec\'s own detail wins; detail: false in a spec opts out); null = none' },
127
+ ramp: { type: 'any', default: null, neutral: true, check: v => { try { rampTexture(v); return null; } catch (err) { return err.message; } }, desc: 'toon ramp for every toon material, grays or colors dark to light; null = each spec\'s own steps / ramp' },
128
+ soften: { type: 'any', default: null, neutral: true, check: num, desc: 'how much the toon bands melt into each other 0-1; used with ramp' },
129
+ },
130
+ style: () => keep({ 'lighting.wrap': L.wrap, 'lighting.shadowTint': L.shadowTint, 'lighting.rim': L.rim, 'hook:lighting': L.glsl ? { glsl: L.glsl, uniforms: L.uniforms } : null }),
131
+ hooks: {
132
+ lighting: { signature: 'void threedogLighting(inout ReflectedLight light, vec3 normal, vec3 viewDir, vec3 sunDir, float sunShadow, vec3 albedo)', scope: ['fragment'], example: 'engine.look.surface.patch("lighting", glslString)' },
133
+ detail: { signature: 'vec4 threedogDetailSample(vec2 p) // rgb + height 0-1', scope: ['fragment'], example: 'engine.look.surface.patch("detail", glslString)' },
134
+ },
135
+ noReplace: 'to swap a whole material, use engine.look.materials.replace(role, ...)',
136
+ });
137
+ }
138
+
139
+ /** The pack-wide lighting options for makeMaterial: style.lighting under any look.surface change (undefined without the part) */
140
+ export function surfaceLighting(eng) {
141
+ const p = eng?.look?.surface;
142
+ if (!p) return eng?.style?.lighting;
143
+ const o = keep3({ wrap: p.value('lighting.wrap'), shadowTint: p.value('lighting.shadowTint'), rim: p.value('lighting.rim'), ...asGlsl(p.value('hook:lighting')) });
144
+ return Object.keys(o).length ? o : undefined;
145
+ }
146
+ /** The pack-wide detail options (with the detail hook's glsl), or undefined */
147
+ export function surfaceDetail(eng) {
148
+ const p = eng?.look?.surface, d = p?.value('detail');
149
+ return d ? { ...asGlsl(p.value('hook:detail')), ...d } : undefined;
150
+ }
151
+ /** The pack-wide toon ramp { ramp, soften }, or undefined */
152
+ export function surfaceRamp(eng) {
153
+ const p = eng?.look?.surface, r = p?.value('ramp');
154
+ return r ? { ramp: r, soften: p.value('soften') ?? 0 } : undefined;
155
+ }
156
+ function keep3(o) { return Object.fromEntries(Object.entries(o).filter(([, v]) => v != null)); }
157
+ /** The ground's detail options: look.ground (style.terrain.detail under any change, plus its detail glsl hook), or style.terrain.detail without the part */
158
+ export function groundDetail(eng) {
159
+ const p = eng?.look?.ground, d = p ? p.value('detail') : eng?.style?.terrain?.detail;
160
+ return d ? { ...asGlsl(p?.value('hook:detail')), ...d } : undefined;
161
+ }