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
@@ -5,7 +5,8 @@
5
5
  // Positions are always a single argument (Vector3 / Object3D / [x, y, z] / { x, z }); sizes go in the options object:
6
6
  // const h = engine.collision.addBox(house, { halfWidth: 3, halfDepth: 2, rotation: 0.3 }); h.remove();
7
7
  import { xzOf } from '../../core/math.js';
8
- import { checkOptions, checkOptionsArg } from '../../core/validate.js';
8
+ import { checkOptionsArg } from '../../core/validate.js';
9
+ import { readParams, keysSchema } from '../../core/params.js';
9
10
  import { CollisionGrid, gridBlocks } from './grid.js';
10
11
 
11
12
  /** One axis of the slab test: narrows S.t0 / S.t1 to where the ray is inside |o + d t| <= h; false when it misses */
@@ -16,7 +17,7 @@ function slab(S, o, d, h) {
16
17
  return S.t0 <= S.t1;
17
18
  }
18
19
 
19
- const BOX_KEYS = ['halfWidth', 'halfDepth', 'rotation', 'height', 'y'], CIRCLE_KEYS = ['radius', 'height'];
20
+ const BOX_KEYS = ['halfWidth', 'halfDepth', 'rotation', 'height', 'y'], CIRCLE_KEYS = ['radius', 'height'], SEG_KEYS = ['thickness', 'height', 'y'], BLOCK_KEYS = ['bounds'];
20
21
 
21
22
  export class Collision {
22
23
  /**
@@ -30,9 +31,12 @@ export class Collision {
30
31
  this.circles = []; // manually added circle colliders {x, z, r, h}
31
32
  this.boxes = []; // rectangles {x, z, hw, hd, rot, h}
32
33
  this._grid = new CollisionGrid(); // grid index: resolve / camera look only nearby instead of scanning all (circles / boxes change only via addCircle / addBox)
34
+ this._blocked = []; // addBlocked fields {fn, bounds}; empty = zero cost
35
+ this.blockedVersion = 0; // +1 on addBlocked / remove: async paths re-sample their cached ground rasters
33
36
  this.version = 0; // +1 on every static collider add/remove; the physics module syncs on it
34
37
  this._onGroundCircle = (cx, cz, r) => this._pushCircle(this._rPos, cx, cz, r, this._rRad); // built once: ground.forEachCollider callback
35
38
  this._camS = { from: null, to: null, ux: 0, uz: 0, len: 0, pad: 0, want: 0, best: 0, t0: 0, t1: 0 }; // cameraDistance scratch for its callbacks
39
+ this._lineS = { t0: 0, t1: 0 }; // lineClear slab scratch
36
40
  this._onCamCircle = (a, b, c) => this._camCircle(a, b, c);
37
41
  }
38
42
  /** Iterate all manually added static colliders (for the physics module): fn('box' | 'circle', data) */
@@ -56,6 +60,37 @@ export class Collision {
56
60
  this.boxes.push(b); this._grid.add(b, true); this.version++;
57
61
  return { remove: () => { if (!this.boxes.includes(b)) return; this.boxes = this.boxes.filter(o => o !== b); this._grid.remove(b); this.version++; } };
58
62
  }
63
+ /**
64
+ * Add a thin wall along the line a -> b (fence, wall; positions like addBox). thickness (default 0.3), height (default 6), y as in addBox.
65
+ * It is a rotated box in the same grid, so a gap between two segments is a gate. Returns a handle { remove() }
66
+ */
67
+ addSegment(a, b, opts = {}) {
68
+ checkOptionsArg('collision.addSegment()', opts, SEG_KEYS); if (typeof opts !== 'object') opts = {};
69
+ const [ax, az] = xzOf(a), [bx, bz] = xzOf(b);
70
+ // box-local +x is (cos r, -sin r) in world, so r = -atan2(dz, dx)
71
+ return this.addBox([(ax + bx) / 2, 0, (az + bz) / 2], { halfWidth: Math.hypot(bx - ax, bz - az) / 2, halfDepth: (opts.thickness ?? 0.3) / 2, rotation: -Math.atan2(bz - az, bx - ax), height: opts.height, y: opts.y });
72
+ }
73
+ /**
74
+ * Mark ground as impassable where fn(x, z) is true (river, lava, cliff edge). Walkers are stopped at its edge (sliding along it) and walkable() says no.
75
+ * fn must be pure and deterministic (no clock, no random). bounds { minX, maxX, minZ, maxZ } skips fn outside it. A bridge: have fn return false over it,
76
+ * or keep the water field exact and let fn test `!onBridge(x, z)`. findPathAsync samples fn into its ground raster (1 m cells), so give bounds to keep that cheap. Returns a handle { remove() }
77
+ */
78
+ addBlocked(fn, opts = {}) {
79
+ checkOptionsArg('collision.addBlocked()', opts, BLOCK_KEYS); if (typeof opts !== 'object') opts = {};
80
+ if (typeof fn !== 'function') throw new Error('collision.addBlocked(fn): fn(x, z) => boolean is required');
81
+ const f = { fn, bounds: opts.bounds ?? null }; this._blocked.push(f); this.version++; this.blockedVersion++;
82
+ return { remove: () => { if (!this._blocked.includes(f)) return; this._blocked = this._blocked.filter(o => o !== f); this.version++; this.blockedVersion++; } };
83
+ }
84
+ /** Is a character of `radius` standing at (x, z) touching blocked ground (centre and four points on its rim). Free when addBlocked was never used */
85
+ blockedAt(x, z, radius = this.engine.movement.radius) {
86
+ const L = this._blocked; if (!L.length) return false;
87
+ for (let i = 0; i < L.length; i++) {
88
+ const { fn, bounds: bd } = L[i];
89
+ if (bd && (x + radius < bd.minX || x - radius > bd.maxX || z + radius < bd.minZ || z - radius > bd.maxZ)) continue;
90
+ if (fn(x, z) || fn(x + radius, z) || fn(x - radius, z) || fn(x, z + radius) || fn(x, z - radius)) return true;
91
+ }
92
+ return false;
93
+ }
59
94
  /** Add collision from a three.js object's bounding box (common for house models), pad grows it outward (m). Returns a handle { remove() } */
60
95
  addObject(obj, { pad = 0 } = {}) {
61
96
  obj.updateMatrixWorld(true);
@@ -104,10 +139,70 @@ export class Collision {
104
139
 
105
140
  /** Can anyone stand here (for pathfinding): not in water, not too steep, not inside an obstacle. radius is the character radius (m, default engine.movement.radius) */
106
141
  walkable(position, { radius = this.engine.movement.radius } = {}) { const [x, z] = xzOf(position); return this.walkableAt(x, z, radius); }
142
+ /**
143
+ * Line of sight with height: is the 3D segment a -> b free of colliders (boxes, circles, terrain trees)? Positions like addBox ([x, y, z] / Vector3 / Object3D).
144
+ * Heights count: a 1 m wall does not block a sight line passing 3 m above it; a collider's `y` and `height` are honoured (no `y` = sits on the ground).
145
+ * Give real eye heights in a and b (`[x, 1.6, z]`); a plain { x, z } counts as y = 0. opts.radius (default 0) fattens the line, e.g. the character radius for "can I walk straight there".
146
+ * Ignores addBlocked fields (water is not a wall). Terrain trees have no stored height and block below `canopyHeight` above the ground. Allocates a little: not for hundreds of pairs per frame.
147
+ * opts.who: world record id of the asker; with events.traceSize > 0 every query is noted as a `sight` trace entry (data: from, to, clear), in full for who === events.traceFocus.
148
+ * @param {any} a @param {any} b @param {{ radius?: number, who?: string }} [opts]
149
+ * @returns {boolean} true = nothing in the way
150
+ * @example if (engine.collision.lineClear(guard.position, player.position, { who: 'guard-1' })) alert(); // guard sees the player
151
+ */
152
+ lineClear(a, b, opts = {}) {
153
+ const clear = this._lineClear(a, b, opts), ev = this.engine.events;
154
+ if (ev.traceSize > 0) { const A = this._vec(a), B = this._vec(b), r = x => Math.round(x * 10) / 10; ev.note('sight', { obj: opts.who, verbose: clear, data: { from: [r(A.x), r(A.y), r(A.z)], to: [r(B.x), r(B.y), r(B.z)], clear } }); } // a clear line is the common case: only kept for the focused object; a blocked one is always kept
155
+ return clear;
156
+ }
157
+ /** @internal */
158
+ _lineClear(a, b, opts) {
159
+ checkOptionsArg('collision.lineClear()', opts, ['radius', 'who']); if (typeof opts !== 'object') opts = {};
160
+ const rad = opts.radius ?? 0;
161
+ const A = this._vec(a), B = this._vec(b), dx = B.x - A.x, dz = B.z - A.z, dy = B.y - A.y;
162
+ const S = this._lineS;
163
+ // y of the segment is linear in t; an obstacle occupying t in [t0, t1] blocks if the segment's y range there overlaps [bottom, top]
164
+ const blocks = (t0, t1, bottom, top) => {
165
+ t0 = Math.max(t0, 0); t1 = Math.min(t1, 1);
166
+ if (t0 > t1) return false;
167
+ const y0 = A.y + dy * t0, y1 = A.y + dy * t1;
168
+ return Math.max(y0, y1) > bottom && Math.min(y0, y1) < top;
169
+ };
170
+ const circle = (cx, cz, r, bottom, top) => {
171
+ const ox = A.x - cx, oz = A.z - cz, R = r + rad, qa = dx * dx + dz * dz, qb = 2 * (ox * dx + oz * dz), qc = ox * ox + oz * oz - R * R;
172
+ if (qa < 1e-12) return qc < 0 && blocks(0, 1, bottom, top); // straight up / down
173
+ const disc = qb * qb - 4 * qa * qc; if (disc < 0) return false;
174
+ const sq = Math.sqrt(disc);
175
+ return blocks((-qb - sq) / (2 * qa), (-qb + sq) / (2 * qa), bottom, top);
176
+ };
177
+ const len = Math.hypot(dx, dz), mx = A.x + dx / 2, mz = A.z + dz / 2;
178
+ const list = this._grid.query(mx, mz, len / 2 + rad + 1);
179
+ for (let i = 0; i < list.length; i++) {
180
+ const it = list[i];
181
+ if (!it._b) { const g = this.engine.surface(it.x, it.z); if (circle(it.x, it.z, it.r, g, g + it.h)) return false; continue; }
182
+ const ox = A.x - it.x, oz = A.z - it.z;
183
+ const lx = ox * it.c - oz * it.s, lz = ox * it.s + oz * it.c, ldx = dx * it.c - dz * it.s, ldz = dx * it.s + dz * it.c;
184
+ S.t0 = 0; S.t1 = 1;
185
+ if (!slab(S, lx, ldx, it.hw + rad) || !slab(S, lz, ldz, it.hd + rad)) continue;
186
+ const bottom = it.y ?? this.engine.surface(it.x, it.z);
187
+ if (blocks(S.t0, S.t1, bottom, bottom + it.h)) return false;
188
+ }
189
+ let treeHit = false;
190
+ this.engine.ground.forEachCollider?.(mx, mz, len / 2 + rad + 1, (cx, cz, r) => {
191
+ if (!treeHit) { const g = this.engine.surface(cx, cz); treeHit = circle(cx, cz, r, g, g + this.canopyHeight); }
192
+ });
193
+ return !treeHit;
194
+ }
195
+ /** @internal position argument -> { x, y, z } (y 0 when only x, z are given) */
196
+ _vec(p) {
197
+ const [x, z] = xzOf(p);
198
+ const q = p.isObject3D ? p.position : p;
199
+ const y = (Array.isArray(q) ? q[1] : q.y) ?? 0;
200
+ return { x, y, z };
201
+ }
107
202
  /** @internal The collider grid (boxes and circles added through this module), read by async pathfinding on the main thread */
108
203
  get grid() { return this._grid; }
109
204
  /** Same as walkable but takes plain numbers (inner loop of A* pathfinding and spawn search, allocates nothing; like engine.surface(x, z)). radius defaults to engine.movement.radius */
110
- walkableAt(x, z, radius = this.engine.movement.radius) { return this.groundWalkable(x, z) && !this._groundBlocks(x, z, radius) && !gridBlocks(this._grid, x, z, radius); }
205
+ walkableAt(x, z, radius = this.engine.movement.radius) { return this.groundWalkable(x, z) && !this.blockedAt(x, z, radius) && !this._groundBlocks(x, z, radius) && !gridBlocks(this._grid, x, z, radius); }
111
206
  /** @internal Ground shape half of walkableAt (water, slope): a smooth field, so async pathfinding samples it on a raster; colliders are tested exactly there */
112
207
  groundWalkable(x, z) {
113
208
  const e = this.engine;
@@ -170,7 +265,10 @@ export class Collision {
170
265
  }
171
266
  }
172
267
 
268
+ const COLLISION_PARAMS = keysSchema(['maxClimb', 'canopyHeight', 'cameraPad', 'cameraMin', 'walkableWaterMargin', 'cameraOcclusion']);
269
+
173
270
  /** Collision module: lightweight character walking collision, covers the whole map. Once installed: engine.collision */
174
271
  export function collision(opts = {}) {
175
- return { name: 'collision', label: 'Collision', install(e) { checkOptions('collision()', opts, ['maxClimb', 'canopyHeight', 'cameraPad', 'cameraMin', 'walkableWaterMargin', 'cameraOcclusion']); return new Collision(e, opts); } };
272
+ readParams('collision', COLLISION_PARAMS, opts);
273
+ return { name: 'collision', params: COLLISION_PARAMS, options: opts, label: 'Collision', install(e) { return new Collision(e, opts); } };
176
274
  }
@@ -0,0 +1,13 @@
1
+ // Content's contribution to thing.explain(): rules read from the thing's template (collide, static, interact), which win over the world record's own.
2
+ const safe = f => { try { return f(); } catch { return null; } };
3
+
4
+ /** @internal */
5
+ export function contentExplain(e, t, out) {
6
+ const def = t.template ? safe(() => e.content.template(t.template)) : null;
7
+ if (!def) return;
8
+ Object.assign(out.rules, {
9
+ blocksMovement: def.collide ?? false, pickable: def.static !== false,
10
+ interact: def.interact ? { label: def.interact.label ?? null, op: def.interact.op } : null,
11
+ note: 'blocksMovement = the collision shape (box / circle) walkers stop at; blocking sight is not modelled by the engine',
12
+ });
13
+ }
@@ -1,7 +1,7 @@
1
1
  // Content loader: hands the plain data in the game's content/*.js to the engine (items, pickups, vegetation, NPCs, dialogues, quests, key actions, trigger
2
2
  // zones, props).
3
3
  // engine.use(content());
4
- // engine.assets.manifest(lowpolyAssets); // models content names (an asset pack; content never holds paths or code)
4
+ // engine.assets.manifest(yourAssets); // models content names (an asset pack; content never holds paths or code)
5
5
  // engine.content.load(data, { places: { home: { x, z } } }); // or several packs at once: load([base, dlc, level]) (packs.js)
6
6
  // Condition/effect vocabulary is in rules.js. Games add condition words (content/rules.js, or content.condition(name, { test }) in code);
7
7
  // a game's own actions are ops, called from content with { op: ['noun.verb', args] } and tested with { can: [...] }.
@@ -18,6 +18,7 @@
18
18
  // result.
19
19
  // Positions that use level markers belong to the current level: the data carries a zone, and a level change only tears down models (pickups taken and removals
20
20
  // are remembered); trigger zones are removed on level change.
21
+ import { contentExplain } from './explain.js';
21
22
  import { warnMissing, missingText } from '../../core/validate.js';
22
23
  import { reportError } from '../../core/errors.js';
23
24
  import { parseClock } from '../../core/dayTime.js';
@@ -128,6 +129,7 @@ export function content() {
128
129
  optional: ['level', 'sky', 'inventory', 'quests', 'particles', 'hud', 'vegetation', 'dialogue', 'triggers', 'collision', 'world', 'interactions', 'grids', 'rigid'],
129
130
  install(engine) {
130
131
  e = engine;
132
+ engine.explainWith(contentExplain);
131
133
  /**
132
134
  * Place a new instance of a content template at runtime (a gameplay change: call it inside an op or a fixed step); saved whole.
133
135
  * Returns the world record (kind = template name). at is a ground position ({ x, z }, [x, y, z] or an object);
@@ -83,6 +83,9 @@ export function loadContent(e, api, c, st, ids) {
83
83
  // twice never stacks its rules (a fresh key per load did); two different unnamed objects both keep theirs
84
84
  if (c.audio) e.audio.contentPack(c.name ? 'pack:' + c.name : c, c.name ? `pack "${c.name}"` : 'pack (no name)', c.audio);
85
85
 
86
+ // views: named fixed camera views (core/Views.js); defining a name again replaces it, so a hot reload just works
87
+ each(c.views, (name, v) => e.views.define(name, v));
88
+
86
89
  // vegetation: generator models go through assets.cached (baked file -> dev cache -> compute), file models give their first mesh's geometry; register all
87
90
  // kinds at the same moment once all models are ready
88
91
  // (each registration rebuilds terrain chunks; registering one by one would rebuild several times at start). content's isReady waits for them
@@ -66,6 +66,7 @@ const RULE_STRINGS = {
66
66
  props: 'props (list: model, position, facing, collision; or { template, x, z } = an instance of a template; or { id, grid, item, cell } = a grid item), streamed in on demand',
67
67
  templates: 'reusable objects (name -> model, collide, interact, container, sound, animate, state defaults, physics body); shared read-only definitions',
68
68
  audio: 'sounds by asset name, ambience and music rules as data, footsteps (sounds, ambience, music: { tracks, rules }, footsteps)',
69
+ views: 'named fixed camera views (name -> { position: [x, y, z], target?: [x, y, z], fov? }); engine.views.show(name), ?view=name, npm run shot -- -w game --view name',
69
70
  grids: 'placement grids (name -> { cell, origin, size, zone?, flat? }); layout rules, not saved',
70
71
  renames: "renamed or deleted authored ids (old id -> new id, or null = deleted on purpose): the player's saved changes follow the new id",
71
72
  rules: 'condition words added by the game ({ conditions }); actions are ops, not effect words',
@@ -1,10 +1,12 @@
1
1
  // Performance panel + time/weather debugging + stress test. Collapsed by default; F3 shows/hides it (debug({ open: true }) shows it at start). Quality, view distance and density are in the settings menu. Do not install this module in a release.
2
- import { checkOptions } from '../../core/validate.js';
2
+ import { readParams, keysSchema } from '../../core/params.js';
3
3
  import { esc } from '../../ui/UI.js';
4
4
  /** @import { ModuleDef } from '../../types/core' */
5
5
 
6
6
  // Note: the debug panel is a dev tool; its UI text is plain English, not in the string table; do not install this module in a release.
7
- /** engine.debug (F3 panel) */
7
+ // The panel sits next to the core diagnostics as engine.debug.panel (composition): engine.debug (override / clear / view) is core and works without it.
8
+ // It used to subclass DebugOverrides and replace engine.debug, which needed shared state on the engine and a module-name exception; nothing of that is left.
9
+ /** engine.debug.panel (F3 panel) */
8
10
  export class DebugPanel {
9
11
  /** @internal */
10
12
  constructor(engine, { open = false } = {}) {
@@ -145,16 +147,20 @@ export class DebugPanel {
145
147
  }
146
148
  }
147
149
 
150
+ const DEBUG_PANEL_PARAMS = keysSchema(['open']);
151
+
148
152
  /**
149
- * F3 F3 debug panel -> engine.debug: performance panel, settings, stress test. Collapsed by default; F3 shows/hides it; open: true shows it at start. Just do not install it in a release
153
+ * F3 debug panel -> engine.debug.panel: performance panel, settings, stress test. Collapsed by default; F3 shows/hides it; open: true shows it at start. Just do not install it in a release
150
154
  * @param {{ open?: boolean }} [opts]
151
155
  * @returns {ModuleDef<DebugPanel>}
152
156
  */
153
157
  export function debug(opts = {}) {
158
+ readParams('debugPanel', DEBUG_PANEL_PARAMS, opts);
154
159
  let d = null; const prof = { n: 0, t: 0, cpu: 0 };
155
160
  return {
156
- name: 'debug', label: 'Debug panel', optional: ['sky', 'weather', 'terrain'], presentation: true,
157
- install(e) { checkOptions('debug()', opts, ['open']); d = new DebugPanel(e, opts); return d; },
161
+ name: 'debugPanel', params: DEBUG_PANEL_PARAMS, options: opts, label: 'Debug panel', optional: ['sky', 'weather', 'terrain'], presentation: true,
162
+ install(e) { d = new DebugPanel(e, opts); e.debug.panel = d; return d; },
163
+ dispose(e) { if (e.debug.panel === d) e.debug.panel = null; d?.el.remove(); },
158
164
  frame(dt, e) { if (e.input.pressedRaw('debugPanel')) d.el.hidden = !d.el.hidden; },
159
165
  afterRender(dt, e) {
160
166
  d.frame(dt, e.terrain?.stats.builtThisFrame || 0);
@@ -40,6 +40,7 @@
40
40
  // Appearance: the engine ships no default models - the game supplies create(), usually from an asset pack (engine.assets.model / cached).
41
41
  import { xzOf } from '../../core/math.js';
42
42
  import { checkOptions, checkOptionsArg, missingText, warnOnce, freezeDef } from '../../core/validate.js';
43
+ import { readParams, keysSchema } from '../../core/params.js';
43
44
  import { buildEntity } from './build.js';
44
45
 
45
46
  const DEF_KEYS = ['create', 'state', 'stages', 'update', 'interact', 'collider', 'colliderHeight', 'save', 'dispose', 'canGrow'];
@@ -216,12 +217,15 @@ export class Entities {
216
217
  }
217
218
  }
218
219
 
220
+ const ENTITIES_PARAMS = keysSchema([]);
221
+
219
222
  /** Entities module. Installs engine.entities. Data lives in engine.world (needs the world module, included by openWorld). */
220
223
  export function entities(opts = {}) {
221
- checkOptions('entities()', opts, []); // takes no options: what an entity is and does goes in entities.define(type, {...})
224
+ readParams('entities', ENTITIES_PARAMS, opts);
225
+ // takes no options: what an entity is and does goes in entities.define(type, {...})
222
226
  let ents = null;
223
227
  return {
224
- name: 'entities', label: 'Entities', requires: ['world'], optional: ['sky', 'interactions', 'collision'], stage: 'gameplay', after: ['interactions', 'dialogue', 'triggers'],
228
+ name: 'entities', params: ENTITIES_PARAMS, options: opts, label: 'Entities', requires: ['world'], optional: ['sky', 'interactions', 'collision'], stage: 'gameplay', after: ['interactions', 'dialogue', 'triggers'],
225
229
  install(e) {
226
230
  ents = new Entities(e);
227
231
  return ents;
@@ -8,18 +8,22 @@
8
8
  // engine.session.newGame / load / quit move flow too: back to the start state when a playthrough ends, then 'playing' when the next starts.
9
9
  // Esc is not handled here: back goes through the UI focus stack (ui/Focus.js), and opens the settings menu when the stack is empty. Events: flow:change { from, to }, flow:transition { phase: 'start' | 'end' }.
10
10
  import { checkOptions, warnMissing } from '../../core/validate.js';
11
+ import { readParams, keysSchema } from '../../core/params.js';
11
12
  import { fadeScreen } from '../../ui/UI.js';
12
13
  /** @import { ModuleDef } from '../../types/core' */
13
14
  /** @import { Flow, FlowOptions } from '../../types/gameplay' */
14
15
 
15
16
  const STATE_KEYS = ['enter', 'exit', 'freeze', 'lockInput', 'music'];
16
17
 
18
+ const FLOW_PARAMS = keysSchema(['start']);
19
+
17
20
  /**
18
21
  * Game flow and scene transitions → engine.flow
19
22
  * @param {FlowOptions} [opts]
20
23
  * @returns {ModuleDef<Flow>}
21
24
  */
22
25
  export function flow(opts = {}) {
26
+ readParams('flow', FLOW_PARAMS, opts);
23
27
  let e = null, chain = Promise.resolve(), held = null;
24
28
  const states = new Map([['playing', {}], ['paused', { freeze: true, lockInput: true }]]);
25
29
  // turn freeze / input lock on or off for one state
@@ -82,10 +86,9 @@ export function flow(opts = {}) {
82
86
  },
83
87
  };
84
88
  return {
85
- name: 'flow', label: 'Game flow', optional: ['music'],
89
+ name: 'flow', params: FLOW_PARAMS, options: opts, label: 'Game flow', optional: ['music'],
86
90
  install(engine) {
87
91
  e = engine;
88
- checkOptions('flow()', opts, ['start']);
89
92
  // initial state (title screen etc.): entered once the world is ready, so the game can define it after use()
90
93
  if (opts.start && opts.start !== 'playing') e.events.once('engine:ready', () => api.go(opts.start));
91
94
  // a playthrough ends (engine.session): back to the start state, so its enter() runs again; a new one starts in 'playing'
@@ -17,6 +17,7 @@
17
17
  // all run them, so a choice's do (which may change gameplay state) always runs inside a logged op.
18
18
  import { uiFocus } from '../../ui/UI.js';
19
19
  import { checkOptions, warnMissing } from '../../core/validate.js';
20
+ import { readParams, keysSchema } from '../../core/params.js';
20
21
  import { dialogueBox } from './dialogueBox.js';
21
22
  // 'data' is the one slot for game-specific fields: other unknown keys stay typos (a misspelled next would silently end the dialogue)
22
23
  const NODE_KEYS = ['text', 'next', 'choices', 'do', 'speaker', 'data'], CHOICE_KEYS = ['text', 'next', 'if', 'do', 'data'];
@@ -178,14 +179,16 @@ const STRINGS = {
178
179
  en: { 'dialogue.continue': '{key} to continue ▸', 'dialogue.choice': 'Choose option' },
179
180
  };
180
181
 
182
+ const DIALOGUE_PARAMS = keysSchema(['charsPerSecond', 'advanceActions', 'choiceKeys', 'holdSeconds']);
183
+
181
184
  /** Dialogue module. Installs engine.dialogue; story flags engine.dialogue.state.flags are engine.vars.flags. Declares the UI part 'dialogue'. */
182
185
  export function dialogue(opts = {}) {
186
+ readParams('dialogue', DIALOGUE_PARAMS, opts);
183
187
  let d = null;
184
188
  return {
185
- name: 'dialogue', label: 'Dialogue', stage: 'gameplay', after: ['interactions'],
189
+ name: 'dialogue', params: DIALOGUE_PARAMS, options: opts, label: 'Dialogue', stage: 'gameplay', after: ['interactions'],
186
190
  install(e) {
187
191
  e.i18n.add(STRINGS);
188
- checkOptions('dialogue()', opts, ['charsPerSecond', 'advanceActions', 'choiceKeys', 'holdSeconds']);
189
192
  d = new Dialogue(e, opts);
190
193
  e.events.on('session:end', () => d._cancel()); // per-playthrough state (recipes/14-custom-module.md "Per-playthrough state")
191
194
  e.ui.define('dialogue', dialogueBox);
@@ -13,6 +13,7 @@ import * as THREE from 'three';
13
13
  import { worldToScreen } from '../../ui/UI.js';
14
14
  import { promptPart } from './interactionPrompt.js';
15
15
  import { checkOptions } from '../../core/validate.js';
16
+ import { readParams } from '../../core/params.js';
16
17
  import { codedError } from '../../core/errorHints.js';
17
18
  import { vec3 } from '../../core/math.js';
18
19
 
@@ -194,6 +195,14 @@ export class Interactions {
194
195
 
195
196
  const labelOf = it => typeof it.label === 'function' ? it.label() : it.label;
196
197
 
198
+ const INTERACTION_PARAMS = {
199
+ action: { type: 'string', default: 'interact', desc: 'input action that uses the interaction' },
200
+ pick: { type: 'any', optional: true, desc: "which one counts as in front of you: 'nearest' | 'facing' | 'aim' | a function (required; checked with a fix hint on install)" },
201
+ keys: { type: 'array', optional: true, desc: "keys that use it, e.g. ['KeyE'] (required unless createEngine({ bindings }) binds the action)" },
202
+ radius: { type: 'number', default: 2.5, min: 0, desc: 'reach in meters (add() can set its own)' },
203
+ promptHeight: { type: 'number', optional: true, desc: 'prompt height above the target (meters)' },
204
+ };
205
+
197
206
  /**
198
207
  * Interactions module. Installs engine.interactions.
199
208
  * pick and keys are required (the engine picks neither; presets.interactions.* bundle them). radius: default reach of add() in meters (2.5); pick: how the
@@ -209,9 +218,10 @@ const labelOf = it => typeof it.label === 'function' ? it.label() : it.label;
209
218
  * string[] }} opts
210
219
  */
211
220
  export function interactions(opts) {
221
+ const o = readParams('interactions', INTERACTION_PARAMS, opts ?? {});
212
222
  let i = null;
213
- return { name: 'interactions', label: 'Interactions', stage: 'gameplay',
214
- install(e) { checkOptions('interactions()', opts ?? {}, ['action', 'promptHeight', 'radius', 'pick', 'keys']); i = new Interactions(e, opts); defineUse(e, i); return i; },
223
+ return { name: 'interactions', label: 'Interactions', params: INTERACTION_PARAMS, options: o, noSkip: 'input and prompt state only', stage: 'gameplay',
224
+ install(e) { i = new Interactions(e, opts); defineUse(e, i); return i; },
215
225
  fixed() { i.fixed(); }, frame() { i.update(); },
216
226
  // interactions are "weak" info: when an NPC, pickup or entity already reported the same object, only add "interactable: xxx"
217
227
  describe(e, ctx) {
@@ -10,8 +10,9 @@
10
10
  // Look:
11
11
  // window UI part 'inventory' (engine.ui.set('inventory', false | { drop: true } | yourPart)); body via style.ui.templates.inventory(data, { esc, t, icon })
12
12
  // list styling CSS classes .threedog-win-inventory .threedog-row ... (override in style.ui.css)
13
- // pickups style pack style.pickup = { color, size, lift, model: (item, { color, size }) => Object3D | BufferGeometry }, or pass a mesh each time
13
+ // pickups style pack style.pickup = { color, size, lift, model: (item, { color, size }) => Object3D | BufferGeometry }, or pass a mesh each time, or set it on the item: define(id, { mesh: (item, { color, size }, e) => ... }) / { model: 'generatorName' } (item wins over style)
14
14
  import { checkOptions, warnMissing, freezeDef, moduleKeys } from '../../core/validate.js';
15
+ import { readParams } from '../../core/params.js';
15
16
  import { Container } from './Container.js';
16
17
  import { Containers } from './Containers.js';
17
18
  import { followRuntimeIds } from '../../core/saveIds.js';
@@ -38,19 +39,19 @@ export class Inventory {
38
39
  engine.i18n.add(INVENTORY_STRINGS);
39
40
  keys = moduleKeys('inventory()', action, keys, 'inventory', engine.input); // the game's key or a presets.keys bundle, never a built-in one
40
41
  if (keys.length || pad) { engine.input.define(action, keys, 'inventory.action', { pad }); engine.input.touchButton(action, 'inventory.action'); }
41
- engine.ui.define('inventory', inventoryWindow, { modal: { cancel: e => e.ui.close('inventory'), data: () => windowData(this) } });
42
+ engine.ui.define('inventory', inventoryWindow, { modal: { cancel: e => e.ui.close('inventory'), freeze: () => this.pauseGame, data: () => windowData(this) } });
42
43
  for (const ev of ['i18n:change', 'input:rebind']) engine.events.on(ev, () => this._refresh());
43
44
  // pickup state lives in world and is saved with it
44
45
  // version 1 is the current shape; raise it with a migrate step when it changes. seq: the numbering of entry keys (sword#3); a save without it continues
45
46
  // after the highest key it holds
46
- engine.saves.register('inventory', { version: 1, save: () => ({ seq: this._seq, items: this.bag._save() }), load: d => {
47
+ engine.saves.register('inventory', { atomic: true, version: 1, save: () => ({ seq: this._seq, items: this.bag._save() }), load: d => {
47
48
  this.bag._load(d?.items);
48
49
  const top = Math.max(0, ...this.bag._entries.map(x => Number(x.key.split('#')[1]) || 0));
49
50
  this._seq = Number.isInteger(d?.seq) && d.seq >= top ? d.seq : top;
50
51
  this._refresh();
51
52
  } });
52
53
  // version 2: container ids that are runtime record ids (a spawned chest) follow the world part's `kind-n` -> `kind#n` rename (world/persist.js)
53
- engine.saves.register('containers', { version: 2, migrate: { 1: followRuntimeIds }, save: () => this._containers.save(), load: d => this._containers.load(d) });
54
+ engine.saves.register('containers', { atomic: true, version: 2, migrate: { 1: followRuntimeIds }, save: () => this._containers.save(), load: d => this._containers.load(d) });
54
55
  }
55
56
 
56
57
  /** Max slots of the player inventory (Infinity = no limit). */
@@ -111,7 +112,7 @@ export class Inventory {
111
112
  */
112
113
  define(id, def) {
113
114
  if (id.includes('#')) throw new Error(`inventory.define('${id}'): '#' is reserved for entry keys (sword#3); pick an id without it`);
114
- checkOptions(`inventory.define('${id}')`, def, ['name', 'icon', 'iconUrl', 'desc', 'stack', 'color', 'weight', 'use', 'canUse', 'consume'], { loose: true }); // only near-miss spellings warn
115
+ checkOptions(`inventory.define('${id}')`, def, ['name', 'icon', 'iconUrl', 'desc', 'stack', 'color', 'weight', 'use', 'canUse', 'consume', 'mesh', 'model'], { loose: true }); // only near-miss spellings warn
115
116
  this.defs.set(id, freezeDef({ stack: this.defaultStack, name: id, ...def })); return this; // shared by every entry of this item: read-only
116
117
  }
117
118
  // using an undefined item: warn when other items are defined (none defined means the game doesn't use define)
@@ -173,6 +174,18 @@ export class Inventory {
173
174
  _refresh() { const ui = this.engine.ui; if (ui.isOpen('inventory')) ui.get('inventory')?.update(windowData(this)); }
174
175
  }
175
176
 
177
+ const INVENTORY_PARAMS = {
178
+ action: { type: 'string', default: 'inventory', desc: 'input action that opens the bag' },
179
+ keys: { type: 'array', optional: true, desc: 'keys that open the bag (required unless createEngine({ bindings }) binds the action; [] = no key)' },
180
+ pad: { type: 'array', optional: true, desc: 'gamepad buttons that open the bag' },
181
+ capacity: { type: 'number', optional: true, min: 0, desc: 'slot limit of the player inventory (default Infinity = no limit)' },
182
+ maxWeight: { type: 'number', optional: true, min: 0, desc: 'weight limit of the player inventory (default Infinity = no limit)' },
183
+ defaultStack: { type: 'number', default: 99, min: 1, desc: 'stack limit of items that set none' },
184
+ pickupRadius: { type: 'number', default: 2, min: 0, desc: 'reach of pickups that set no radius (meters)' },
185
+ bobDistance: { type: 'number', default: 60, min: 0, desc: 'pickups float and spin only within this distance of the focus (meters)' },
186
+ pauseGame: { type: 'bool', optional: true, desc: 'true: gameplay freezes while the window is open (default false)' },
187
+ };
188
+
176
189
  /**
177
190
  * Inventory module. Installs engine.inventory, the 'inventory' UI part and the ops inventory.transfer / use / drop / trade; ground pickups need world() and
178
191
  * interactions().
@@ -182,19 +195,16 @@ export class Inventory {
182
195
  * @example engine.use(inventory({ ...presets.keys.inventory, pauseGame: true })) // opening the bag with I stops the world until it closes
183
196
  */
184
197
  export function inventory(opts = {}) {
198
+ const o = readParams('inventory', INVENTORY_PARAMS, opts);
185
199
  let inv = null;
186
200
  return {
187
- name: 'inventory', label: 'Inventory', optional: ['world'],
201
+ name: 'inventory', label: 'Inventory', params: INVENTORY_PARAMS, options: o, noSkip: 'auto-pickup is spatial; no timers', optional: ['world'],
188
202
  install(e) {
189
- checkOptions('inventory()', opts, ['action', 'keys', 'pad', 'capacity', 'maxWeight', 'defaultStack', 'pickupRadius', 'bobDistance', 'pauseGame']);
190
203
  inv = new Inventory(e, opts);
191
- // pauseGame: true freezes gameplay (engine.freeze, the same mechanism flow's 'paused' and settings({ freezeWorld }) use) while the window is open.
204
+ // pauseGame: true freezes gameplay (engine.freeze('ui-inventory'), the part's own owner; the same mechanism flow's 'paused' and settings({ freezeWorld }) use) while the window is open.
192
205
  // Rendering and UI go on; the freeze is released when the window closes or the inventory is turned off with engine.ui.set('inventory', false).
193
206
  if (opts.pauseGame != null && typeof opts.pauseGame !== 'boolean') throw new Error(`inventory({ pauseGame: ${JSON.stringify(opts.pauseGame)} }): pauseGame must be true or false. Example: engine.use(inventory({ pauseGame: true }))`);
194
207
  inv.pauseGame = !!opts.pauseGame; // also settable at runtime: engine.inventory.pauseGame = true
195
- e.events.on('ui:open', id => { if (id === 'inventory' && inv.pauseGame) e.freeze('inventory'); });
196
- // always: switching pauseGame off while open must not leave the world frozen
197
- e.events.on('ui:close', id => { if (id === 'inventory') e.unfreeze('inventory'); });
198
208
  defineInventoryOps(e, inv);
199
209
  return inv;
200
210
  },
@@ -19,6 +19,7 @@
19
19
  import { toast, toggleOnKey } from '../../ui/UI.js';
20
20
  import { questLogWindow } from './questLog.js';
21
21
  import { checkOptions, warnMissing, DEV, moduleKeys } from '../../core/validate.js';
22
+ import { readParams } from '../../core/params.js';
22
23
  import { codedError } from '../../core/errorHints.js';
23
24
  import { toSaved, fromSaved, migrateV1, stepId } from './questSave.js';
24
25
 
@@ -44,7 +45,7 @@ export class Quests {
44
45
  this.win = questLogWindow(engine, this); // { open, toggle, refresh } over engine.ui
45
46
  // counters live in engine.vars
46
47
  // saved by stable step ids (questSave.js); version 1 saved positions
47
- engine.saves.register('quests', { version: 2, migrate: { 1: d => migrateV1(this.defs, d) }, save: () => this._save(), load: d => this._load(d) });
48
+ engine.saves.register('quests', { atomic: true, version: 2, migrate: { 1: d => migrateV1(this.defs, d) }, save: () => this._save(), load: d => this._load(d) });
48
49
  }
49
50
 
50
51
  /**
@@ -162,15 +163,24 @@ export class Quests {
162
163
  }
163
164
  }
164
165
 
166
+ const QUEST_PARAMS = {
167
+ action: { type: 'string', default: 'quests', desc: 'input action that opens the quest log' },
168
+ keys: { type: 'array', optional: true, desc: 'keys that open the log (required unless createEngine({ bindings }) binds the action; [] = no key)' },
169
+ pad: { type: 'array', optional: true, desc: 'gamepad buttons that open the log' },
170
+ checkInterval: { type: 'number', default: 0.5, min: 0, desc: 'seconds (game time) between quest condition checks' },
171
+ notify: { type: 'any', default: true, desc: 'true = toast, false = silent, or a function ({ type, id, text }) => void' },
172
+ };
173
+
165
174
  /**
166
175
  * Quests module. Installs engine.quests. keys / pad open the quest log: required (keys: [] for none; presets.keys.quests has J / gamepad Select) @example
167
176
  * engine.use(quests({ ...presets.keys.quests }))
168
177
  */
169
178
  export function quests(opts = {}) {
179
+ const o = readParams('quests', QUEST_PARAMS, opts);
170
180
  let q = null;
171
181
  return {
172
- name: 'quests', label: 'Quests',
173
- install(e) { checkOptions('quests()', opts, ['action', 'keys', 'pad', 'checkInterval', 'notify']); q = new Quests(e, opts); return q; },
182
+ name: 'quests', label: 'Quests', params: QUEST_PARAMS, options: o, noSkip: 'conditions are re-checked on the next fixed step after the jump',
183
+ install(e) { q = new Quests(e, opts); return q; },
174
184
  // Check quests in the fixed step (game time; not while frozen or flow is paused, so no rewards are granted while paused)
175
185
  fixed(dt) { q._t -= dt; if (q._t <= 0) { q._t = q.checkInterval; q.check(); } },
176
186
  frame(dt, e) { toggleOnKey(e, q.win, q.action); },
@@ -77,16 +77,18 @@ function take(inv, rec) {
77
77
  return { ok: true };
78
78
  }
79
79
  const NO_PICKUP = 'pickups: no style pack / model given, so items on the ground are gray boxes (a placeholder). Pass a style pack with '
80
- + "style.pickup.model(item, { color, size }), e.g. createEngine({ style: lowpoly }) with lowpoly from '@threedog/style-lowpoly'";
80
+ + "style.pickup.model(item, { color, size }), e.g. createEngine({ style: yourPack }) with a pack you made or installed";
81
81
  /** The model (built when near) + interaction for this pickup record @internal */
82
82
  function model(inv, rec) {
83
83
  const e = inv.engine, def = inv.item(rec.item), st = e.style.pickup || {};
84
84
  let obj = inv._meshes.get(rec.id);
85
85
  if (!obj) {
86
86
  const color = def.color ?? st.color ?? 0xcccccc, size = st.size ?? 0.25;
87
- // shape is the style pack's; without one a neutral box
88
- if (!st.model) warnOnce(NO_PICKUP);
89
- const m = st.model ? st.model(def, { color, size }, e) : new THREE.BoxGeometry(size, size, size);
87
+ // shape: the item definition's own (mesh function, or model = a generator name from the assets), else the style pack's; without one a neutral box
88
+ const gen = typeof def.model === 'string' ? e.assets.builder(def.model) : null;
89
+ if (typeof def.model === 'string' && !gen) warnOnce(`pickups: item '${rec.item}' has model '${def.model}' but no generator of that name is registered (assets); using the style pack shape`);
90
+ else if (!def.mesh && !gen && !st.model) warnOnce(NO_PICKUP);
91
+ const m = typeof def.mesh === 'function' ? def.mesh(def, { color, size }, e) : gen ? gen() : st.model ? st.model(def, { color, size }, e) : new THREE.BoxGeometry(size, size, size);
90
92
  obj = m.isObject3D ? m : new THREE.Mesh(m, makeMaterial('pickup', { color }, e));
91
93
  }
92
94
  obj.castShadow = true;
@@ -137,6 +137,6 @@ export class Layer {
137
137
 
138
138
  /**
139
139
  * Options of grid.layer(name, opts)
140
- * @typedef {{ tiles?: boolean | { look?: (data: Record<string, any>, cell: [number, number]) => any, lift?: number }
140
+ * @typedef {{ tiles?: boolean | { look?: (data: Record<string, any>, cell: [number, number]) => any, colors?: Record<string, number | string>, lift?: number }
141
141
  * | ((engine: any, layer: Layer) => { update?: (cells: { cell: [number, number], data: Record<string, any> }[]) => void, dispose?: () => void }) }} LayerOptions
142
142
  */
@@ -213,7 +213,7 @@ export function grids() {
213
213
  name: 'grids', label: 'Grid placement', stage: 'gameplay', requires: ['world'],
214
214
  install(e) {
215
215
  G = new Grids(e);
216
- e.saves.register('grids', { version: 2, migrate: GRIDS_MIGRATE, save: () => G.toJSON(), load: d => G.fromJSON(d) });
216
+ e.saves.register('grids', { atomic: true, version: 2, migrate: GRIDS_MIGRATE, save: () => G.toJSON(), load: d => G.fromJSON(d) });
217
217
  offOps = defineGridOps(e, G);
218
218
  subs.push(
219
219
  e.events.on('world:add', ({ id }) => G._reindex(id)),
@@ -2,7 +2,7 @@
2
2
  // whose four corners sit on engine.surface + lift, so tiles hug a ramp or terrain and work on any ground provider
3
3
  // (procedural terrain, a Blender level, a flat greenhouse floor). One merged mesh = one draw call; it is rebuilt only when
4
4
  // the layer version or the ground (level:loaded) changes.
5
- // Look: layer option tiles.look(data, cell) -> color | null, else the style pack table style.grid.tiles[layer] = { field: color }
5
+ // Look: layer option tiles.look(data, cell) -> color | null, else tiles.colors = { field: color } (call site, same shape as the style table), else the style pack table style.grid.tiles[layer] = { field: color }
6
6
  // (first truthy field in the table's order wins), else neutral gray. tiles: false = off; a function = your own part.
7
7
  import * as THREE from 'three';
8
8
  import { makeMaterial } from '../../render/materials.js';
@@ -11,20 +11,24 @@ import { surfaceOr } from '../../core/ground.js';
11
11
  const GAP = 0.03; // fraction of a cell left between tiles: keeps tiles visibly separate (crisp edges)
12
12
  const FALLBACK = 0x9a9a9a;
13
13
 
14
- /** Look function from the style pack table (null if the style has none for this layer) @internal */
15
- function styleLook(e, name) {
16
- const table = e.style.grid?.tiles?.[name];
14
+ /** Look function from a { field: color } table: the first truthy field in the table's order wins (same table shape as style.grid.tiles[layer]; the call-site option tiles.colors wins over the style) @internal */
15
+ function tableLook(table) {
17
16
  if (!table) return null;
18
17
  const order = Object.entries(table);
19
18
  return d => { for (const [f, c] of order) if (d[f]) return c; return null; };
20
19
  }
21
20
 
21
+ /** Look function from the style pack table (null if the style has none for this layer) @internal */
22
+ function styleLook(e, name) {
23
+ return tableLook(e.style.grid?.tiles?.[name]);
24
+ }
25
+
22
26
  /** Build the tile view of a layer, or null when off. Returns { frame(), dispose() } @internal */
23
27
  export function layerTiles(e, layer) {
24
28
  const t = layer.opts.tiles, name = layer.name;
25
29
  if (t === false) return null;
26
30
  if (typeof t === 'function') return customTiles(e, layer, t(e, layer));
27
- const look = (t && typeof t === 'object' && t.look) || styleLook(e, name) || (t ? () => FALLBACK : null);
31
+ const look = (t && typeof t === 'object' && (t.look || tableLook(t.colors))) || styleLook(e, name) || (t ? () => FALLBACK : null);
28
32
  if (!look) return null; // no style table and not asked for: a pure data layer
29
33
  const lift = (t && typeof t === 'object' && t.lift) ?? e.style.grid?.tileLift ?? 0.03;
30
34
  const mat = makeMaterial('decal', { vertexColors: true }, e);