threedog 2.2.0 → 2.3.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 (197) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/README.md +4 -4
  3. package/core/assets/Animator.js +66 -12
  4. package/core/assets/ik.js +144 -18
  5. package/core/assets/maskLayer.js +377 -0
  6. package/core/assets/rootMotion.js +148 -0
  7. package/core/audio/Audio.js +100 -4
  8. package/core/base/errorCodes.js +6 -369
  9. package/core/base/errorCodesModules.js +378 -0
  10. package/core/engine/Engine.js +8 -5
  11. package/core/engine/Loading.js +8 -4
  12. package/core/engine/copies.js +1 -1
  13. package/core/engine/headlessLoad.js +15 -4
  14. package/core/engine/lifecycle.js +1 -0
  15. package/core/engine/loop.js +23 -3
  16. package/core/engine/moduleSlots.js +3 -7
  17. package/core/engine/modules.js +30 -58
  18. package/core/engine/startup.js +3 -3
  19. package/core/input/Input.js +7 -3
  20. package/core/input/inputContext.js +3 -2
  21. package/core/input/inputSeat.js +1 -1
  22. package/core/inspect/DebugOverrides.js +1 -1
  23. package/core/inspect/Describe.js +7 -2
  24. package/core/inspect/describeRender.js +4 -1
  25. package/core/inspect/describeText.js +2 -2
  26. package/core/inspect/metadata.generated.js +380 -74
  27. package/core/inspect/pictureMenu.js +2 -0
  28. package/core/inspect/pictureWriters.js +4 -3
  29. package/core/ops/Ops.js +9 -3
  30. package/core/ops/actor.js +10 -0
  31. package/core/ops/control.js +17 -6
  32. package/core/ops/holds.js +1 -1
  33. package/core/ops/opsAtomic.js +6 -1
  34. package/core/ops/opsGuard.js +2 -2
  35. package/core/ops/owned.js +37 -11
  36. package/core/ops/sharedPoint.js +5 -1
  37. package/core/ops/stacks.js +30 -7
  38. package/core/saves/Saves.js +0 -2
  39. package/core/saves/saveApply.js +7 -7
  40. package/core/saves/session.js +6 -3
  41. package/core/saves/stateReplace.js +71 -41
  42. package/core/scene/Rays.js +74 -26
  43. package/core/scene/canvasBox.js +9 -0
  44. package/core/scene/gameLights.js +19 -11
  45. package/core/scene/sceneDelta.js +8 -4
  46. package/core/scene/sceneMethods.js +2 -1
  47. package/core/stream/chunkStream.js +21 -0
  48. package/core/stream/dirtyWatch.js +37 -0
  49. package/core/time/skip.js +9 -6
  50. package/core/time/time.js +72 -18
  51. package/docs/AI.md +22 -21
  52. package/docs/API.md +5 -4
  53. package/docs/CODEMAP.md +16 -10
  54. package/docs/COMMANDS.md +5 -5
  55. package/docs/CONVENTIONS.md +9 -25
  56. package/docs/api/ambience.md +1 -0
  57. package/docs/api/assets.md +10 -3
  58. package/docs/api/audio.md +5 -3
  59. package/docs/api/decals.md +16 -0
  60. package/docs/api/engine.md +1 -0
  61. package/docs/api/tools.md +3 -1
  62. package/docs/api/water.md +3 -0
  63. package/docs/recipes/09-materials-lights-models.md +15 -1
  64. package/docs/recipes/13-animation.md +51 -10
  65. package/docs/recipes/16-dev-bridge.md +4 -4
  66. package/docs/recipes/31-audio.md +15 -9
  67. package/docs/recipes/34-environment-lighting.md +11 -1
  68. package/docs/recipes/44-water-weather-hooks.md +1 -0
  69. package/examples/action/.threedog/content-index.json +1 -0
  70. package/examples/perf-island/.threedog/content-index.json +1 -0
  71. package/examples/plain-picture/.threedog/content-index.json +1 -0
  72. package/examples/rc2d/.threedog/content-index.json +1 -0
  73. package/examples/styletest/.threedog/content-index.json +1 -0
  74. package/examples/techniques/outlines-and-rim/main.js +1 -1
  75. package/examples/techniques/procedural-surface/main.js +1 -1
  76. package/examples/techniques/stylized-shading/main.js +1 -1
  77. package/examples/webgpu-tsl/.threedog/content-index.json +1 -0
  78. package/examples/world/.threedog/content-index.json +1 -0
  79. package/index.d.ts +6 -2
  80. package/index.js +3 -2
  81. package/llms.txt +11 -10
  82. package/modules/ambience/Ambience.js +97 -15
  83. package/modules/camera/common.js +18 -12
  84. package/modules/characters/Character.js +30 -3
  85. package/modules/characters/NPC.js +2 -5
  86. package/modules/characters/astar.js +45 -14
  87. package/modules/characters/movers/rapier.js +53 -41
  88. package/modules/characters/movers/simple.js +37 -24
  89. package/modules/characters/npcView.js +2 -2
  90. package/modules/characters/pathAsync.js +3 -3
  91. package/modules/collision/contract.js +2 -2
  92. package/modules/content/index.js +3 -0
  93. package/modules/content/models.js +11 -4
  94. package/modules/content/templates.js +11 -11
  95. package/modules/debug/DebugPanel.js +1 -0
  96. package/modules/decals/Decals.js +393 -0
  97. package/modules/decals/index.js +1 -0
  98. package/modules/gameplay/Container.js +2 -0
  99. package/modules/gameplay/Containers.js +17 -3
  100. package/modules/gameplay/Dialogue.js +1 -1
  101. package/modules/gameplay/Interactions.js +7 -6
  102. package/modules/gameplay/Inventory.js +5 -1
  103. package/modules/gameplay/Quests.js +4 -3
  104. package/modules/gameplay/inventoryOps.js +2 -2
  105. package/modules/gameplay/pickups.js +32 -12
  106. package/modules/gameplay/questSave.js +2 -2
  107. package/modules/grid/index.js +8 -2
  108. package/modules/hud/index.js +1 -1
  109. package/modules/level/heightfield.js +1 -0
  110. package/modules/level/index.js +3 -2
  111. package/modules/level/nodes.js +2 -1
  112. package/modules/lights/index.js +27 -4
  113. package/modules/lights/slots.js +33 -16
  114. package/modules/nav/contract.js +4 -4
  115. package/modules/nav/index.js +6 -2
  116. package/modules/net/Client.js +24 -11
  117. package/modules/net/Host.js +73 -20
  118. package/modules/net/index.js +33 -21
  119. package/modules/net/sync.js +38 -8
  120. package/modules/net/transports.js +7 -3
  121. package/modules/particles/Particles.js +11 -4
  122. package/modules/particles/contract.js +6 -6
  123. package/modules/particles/effect.js +0 -1
  124. package/modules/rigid/RigidBodies.js +69 -57
  125. package/modules/rigid/Vehicles.js +8 -7
  126. package/modules/rigid/ragdoll.js +4 -6
  127. package/modules/rigid/rapierCompat.js +90 -0
  128. package/modules/rigid/sync.js +2 -5
  129. package/modules/settings/Settings.js +10 -4
  130. package/modules/sky/Sky.js +10 -2
  131. package/modules/sky/environment.js +29 -13
  132. package/modules/sky/frame.js +2 -2
  133. package/modules/sky/shader.js +5 -2
  134. package/modules/sky/skyModule.js +2 -2
  135. package/modules/swarm/Swarm.js +3 -2
  136. package/modules/swarm/grid.js +12 -7
  137. package/modules/terrain/ChunkManager.js +16 -26
  138. package/modules/triggers/index.js +5 -6
  139. package/modules/vegetation/draw.js +62 -26
  140. package/modules/vegetation/groundChunks.js +8 -22
  141. package/modules/water/Water.js +152 -24
  142. package/modules/water/surface.js +43 -20
  143. package/modules/weather/weatherDraw.js +4 -1
  144. package/modules/world/World.js +21 -2
  145. package/modules/world/index.js +5 -0
  146. package/modules/world/persist.js +1 -0
  147. package/modules/world/records.js +3 -1
  148. package/modules/world/sim.js +3 -2
  149. package/modules/world/simFar.js +4 -2
  150. package/modules/world/state.js +7 -1
  151. package/package.json +2 -2
  152. package/presets.js +30 -0
  153. package/render/PostFX.js +24 -17
  154. package/render/backend.js +72 -31
  155. package/render/cascades.js +25 -14
  156. package/render/cascades.tsl.js +32 -21
  157. package/render/fogLook.js +2 -1
  158. package/render/fx/detail.tsl.js +3 -0
  159. package/render/fx/library.tsl.js +1 -1
  160. package/render/fx/particles.tsl.js +4 -18
  161. package/render/fx/pcss.tsl.js +2 -2
  162. package/render/fx/postWebGPU.tsl.js +47 -25
  163. package/render/fx/sky.tsl.js +6 -18
  164. package/render/fx/uniforms.tsl.js +16 -0
  165. package/render/fx/water.tsl.js +24 -5
  166. package/render/fxNumbers.js +2 -0
  167. package/render/impostor.tsl.js +10 -6
  168. package/render/lights.js +6 -6
  169. package/render/occlusion.js +17 -6
  170. package/render/patches.js +40 -28
  171. package/render/postWebGL.js +6 -4
  172. package/render/reflectionProbes.js +302 -0
  173. package/render/shaderErrors.js +18 -8
  174. package/render/shadowCache.tsl.js +10 -5
  175. package/render/shadows.js +70 -49
  176. package/render/threeCompat.js +166 -0
  177. package/types/core.d.ts +33 -3
  178. package/types/gameplay.d.ts +80 -0
  179. package/types/generated/core/audio/Audio.d.ts +18 -1
  180. package/types/generated/core/ops/Ops.d.ts +2 -1
  181. package/types/generated/core/ops/control.d.ts +7 -3
  182. package/types/generated/core/saves/session.d.ts +4 -1
  183. package/types/generated/modules/ambience/Ambience.d.ts +6 -0
  184. package/types/generated/modules/debug/DebugPanel.d.ts +1 -0
  185. package/types/generated/modules/grid/index.d.ts +27 -3
  186. package/types/generated/modules/net/index.d.ts +8 -3
  187. package/types/generated/modules/sky/Sky.d.ts +1 -0
  188. package/types/generated/modules/water/Water.d.ts +15 -0
  189. package/types/generated/modules/world/index.d.ts +5 -0
  190. package/types/generated/render/patches.d.ts +5 -0
  191. package/types/physics.d.ts +66 -9
  192. package/types/tsl.d.ts +2 -0
  193. package/types/world.d.ts +2 -0
  194. package/ui/Parts.js +3 -2
  195. package/docs/MIGRATING-0.7.md +0 -39
  196. package/docs/MIGRATING-0.8.md +0 -171
  197. package/modules/rigid/refresh.js +0 -10
@@ -23,9 +23,9 @@ export function buildNpcView(m, rec) {
23
23
  id: rec.id, // stable for the interaction.use op, whether the model is built sync or async
24
24
  label: interactLabel || io.label || (() => io.op === 'npc.talk' ? e.t('npc.talk', { name: rec.name }) : rec.name), radius: io.radius,
25
25
  // the op's result is the use's result: { ok: false, code } from its can fails interaction.use with that code
26
- onUse: () => { const r = e.ops.run(io.op, { npc: rec.id, ...io.args }, { source: 'player' }); return r.ok ? r.value : r; },
26
+ onUse: (_, ctx) => { const r = e.ops.run(io.op, { npc: rec.id, ...io.args }, { source: 'player', ...(ctx?.actor !== undefined ? { actor: ctx.actor } : {}) }); return r.ok ? r.value : r; },
27
27
  });
28
- m._views.set(ch.root, { ch, use, useFrom: e.interactions });
28
+ m._views.set(ch.root, { ch, use });
29
29
  m.avoid.built.add(rec.id);
30
30
  return ch.root;
31
31
  }
@@ -121,8 +121,8 @@ export class AsyncPaths {
121
121
  tile(k, tx, tz) {
122
122
  const e = this.e;
123
123
  // another collision module counts from zero, so an equal number says nothing; a new playthrough restarts the tick, so a negative age is an old tile, not a young one
124
- const from = e.collision;
125
- if (from !== this.tilesOf) { this.tiles.clear(); this.tilesOf = from; } // the issuer beside what it issued (architecture 8.2), compared, never called
124
+ const from = e.collision, g = e.ground;
125
+ if (from !== this.tilesOf || g !== this.tilesGround) { this.tiles.clear(); this.tilesOf = from; this.tilesGround = g; } // the issuer beside what it issued (architecture 8.2), compared, never called
126
126
  const c = this.tiles.get(k), bv = e.collision.blockedVersion, age = c ? e.time.tick - c.at : -1;
127
127
  if (c && c.bv === bv && age >= 0 && age < TILE_TTL) return c;
128
128
  const data = new Uint8Array(TILE * TILE), top = new Float32Array(TILE * TILE), col = e.collision, trees = [], span = TILE * RES, body = e.movement.height;
@@ -141,7 +141,7 @@ export class AsyncPaths {
141
141
  e.ground.forEachCollider?.((tx + 0.5) * span, (tz + 0.5) * span, span * 0.71 + 3, (x, z, r) => { trees.push(x, z, r); });
142
142
  const v = { data, top, lower, trees, at: e.time.tick, bv };
143
143
  this.tiles.set(k, v);
144
- if (this.tiles.size > 4096) for (const [kk, o] of this.tiles) if (e.time.tick - o.at >= TILE_TTL) this.tiles.delete(kk);
144
+ if (this.tiles.size > 4096) for (const [kk, o] of this.tiles) { const a = e.time.tick - o.at; if (a < 0 || a >= TILE_TTL) this.tiles.delete(kk); }
145
145
  return v;
146
146
  }
147
147
  /** Forget cached tiles overlapping a world box and retire batches in flight (ground:change) */
@@ -4,12 +4,12 @@
4
4
  // colliders change (cached paths resample), maxClimb is the steepest walkable slope, grid is what the path worker queries.
5
5
  export default {
6
6
  name: 'collision',
7
+ describe: true,
7
8
  api: ['addBox', 'addCircle', 'walkableAt', 'blockedAt', 'groundWalkable', 'resolve', 'cameraDistance', 'forEachStatic', 'mirror'],
8
- fields: ['version', 'blockedVersion', 'maxClimb', 'grid'],
9
9
  ops: [],
10
10
  events: [],
11
+ fields: ['version', 'blockedVersion', 'maxClimb', 'grid'],
11
12
  saves: {},
12
- describe: true,
13
13
  options: {},
14
14
  probe: { setup: [], emits: [], state: null },
15
15
  };
@@ -35,6 +35,7 @@ import { placesOf, placeOf, offsetFrom, whereOf } from './places.js';
35
35
  import { testWords, runWords } from './words.js';
36
36
  import { setMark, marksPart } from './markers.js';
37
37
  import { codedError, coded } from '../../core/base/errorHints.js';
38
+ import { addTurnHelper } from '../../core/saves/stateReplace.js';
38
39
 
39
40
  /** The state the module's files share: loader.js and templates.js fill it on each content.load, st.e is set at install */
40
41
  function contentState() {
@@ -223,9 +224,11 @@ export function content() {
223
224
  const e = st.e = engine;
224
225
  st.track = ctx.track; // templates.js subscribes on content.load: those listeners belong to the module too
225
226
  ctx.track(holdProtos(e, api)); // the model prototypes its props and templates clone (namedModel.js): unloading content gives them back
227
+ ctx.track(addTurnHelper(e, 'loadContent', (turn, data, opts) => api.load(data, { ...opts, turn })));
226
228
  ctx.things.explainWith(contentExplain);
227
229
  ctx.saves.define('content', { ...marksPart(api, st), atomic: true });
228
230
  for (const holder of ['collision', 'collider3d']) ctx.feeds(holder, () => refit(e));
231
+ ctx.feeds('interactions', () => { if (!e.world) return; for (const [name, d] of st.templates) if (d.interact) for (const r of e.world.query({ kind: name })) if (e.world.view(r.id)) e.world.rebuild(r.id); });
229
232
  ctx.track(e.events.on('engine:ready', () => { checkOps(e, st); checkRefs(st); }));
230
233
  ctx.track(e.events.on('module:fresh', ({ modules }) => api._replay(modules)));
231
234
  ctx.track({ remove: () => { for (const m of api.markers.values()) m.remove(); api.markers.clear(); } }); // the marks stay in st.marks and the save part; only what is on screen goes
@@ -112,12 +112,19 @@ export function settle(e, rec, o, solid, mul = 1) {
112
112
  if (!e.collision) return;
113
113
  const c = base ?? ud.measure.center, ox = c.x * sv[0], oz = c.z * sv[2];
114
114
  const cx = x + ox * Math.cos(rot[1]) + oz * Math.sin(rot[1]), cz = z - ox * Math.sin(rot[1]) + oz * Math.cos(rot[1]);
115
- ud.colliders.push(base
116
- ? e.collision.addCircle({ x: cx, z: cz }, { radius: (set?.circle ?? base.width / 2) * Math.max(sv[0], sv[2]), height: size.y, occluder: blocks, layer })
117
- : e.collision.addBox({ x: cx, z: cz }, { halfWidth: size.x / 2, halfDepth: size.z / 2, rotation: rot[1], height: size.y, occluder: blocks, layer }));
115
+ const hasY = rec.floor !== undefined || rec.ground === false || !!rec.offsetY;
116
+ const cy = hasY ? o.position.y + ud.measure.center.y * sv[1] - size.y / 2 : undefined;
117
+ if (base) {
118
+ const r = (set?.circle ?? base.width / 2) * Math.max(sv[0], sv[2]);
119
+ ud.colliders.push(cy !== undefined
120
+ ? e.collision.addBox({ x: cx, z: cz }, { halfWidth: r, halfDepth: r, height: size.y, y: cy, occluder: blocks, layer })
121
+ : e.collision.addCircle({ x: cx, z: cz }, { radius: r, height: size.y, occluder: blocks, layer }));
122
+ } else {
123
+ ud.colliders.push(e.collision.addBox({ x: cx, z: cz }, { halfWidth: size.x / 2, halfDepth: size.z / 2, rotation: rot[1], height: size.y, ...(cy !== undefined && { y: cy }), occluder: blocks, layer }));
124
+ }
118
125
  }
119
126
  /** Is the model still as settle aligned it, with its collider in the holder installed now (a new one starts empty; with none there is nothing to do yet)? update asks every frame for every built prop, because world.move sends no event @internal */
120
- const fitOf = (rec, mul) => JSON.stringify([rec.position.x, rec.position.z, rec.ground === false ? rec.position.y : null, rotOf(rec), scaleOf(rec, mul)]);
127
+ const fitOf = (rec, mul) => JSON.stringify([rec.position.x, rec.position.z, rec.ground === false ? rec.position.y : null, rec.floor ?? null, rec.offsetY ?? 0, rotOf(rec), scaleOf(rec, mul)]);
121
128
  export const fits = (e, o, rec, mul = 1) => { const h = holderOf(e, rec); return (!h || o.userData.holder === h) && o.userData.fit === fitOf(rec, mul); };
122
129
  const shapeOf = (rec, mul) => JSON.stringify([rotOf(rec), scaleOf(rec, mul)]);
123
130
  /** The turn and size it was built with still hold (a body moves itself, so its place says nothing) @internal */
@@ -25,7 +25,7 @@
25
25
  // and its whole state (turn, speed, asleep) with it in the save part 'rigid'. A copy nothing moved stays out of the save.
26
26
  // Ids: an instance with state (state / container / interact / body) should have a written id (ids.js); without one dev warns.
27
27
  import { checkOptions, freezeDef, missingText, fmt, DEV } from '../../core/base/validate.js';
28
- import { xzOf, scaleOf } from '../../core/base/math.js';
28
+ import { xzOf, yOf, scaleOf } from '../../core/base/math.js';
29
29
  import { placeY } from '../../core/scene/ground.js';
30
30
  import { buildModel, settle, fits, fitsShape, unbuildModel } from './models.js';
31
31
  import { srcOf, stateful, templateId } from './ids.js';
@@ -132,10 +132,11 @@ export function placeTemplate(e, api, st, p, i, zone, ids, origin) {
132
132
 
133
133
  /** engine.content.spawn: a runtime instance (saved whole). at = position ({ x, z } or [x, y, z]; it sits on the ground, fields.y lifts it). @internal */
134
134
  export function spawnTemplate(e, st, name, at, fields = {}) {
135
- const d = templateOf(st, name), [x, z] = xzOf(at);
135
+ const d = templateOf(st, name), [x, z] = xzOf(at), refY = yOf(at);
136
136
  const own = instanceFields(name, d, fields, SPAWN_KEYS, st.templateFields.get(name));
137
+ if (refY !== undefined) own.floor = refY;
137
138
  if (d.stages) own.stageAt = e.clock.now; // a spawned copy starts its stage now (an authored placement starts on its first fixed step, stages.js)
138
- const y = placeY(e, `engine.content.spawn('${name}')`, x, z, undefined, 0) + (fields.y ?? 0);
139
+ const y = placeY(e, `engine.content.spawn('${name}')`, x, z, refY, 0) + (fields.y ?? 0);
139
140
  const rec = e.world.add({ ...(fields.id != null && { id: fields.id }), kind: name, position: { x, y, z }, ...own });
140
141
  if (DEV) e.world.setOrigin(rec.id, { template: name, templateAt: st.templateSrc.get(name) ?? null, model: d.model }); // world.add already noted the op that spawned it
141
142
  openContainer(e, name, d, rec.id, fields.items);
@@ -185,12 +186,11 @@ function present(e, api, st, name) {
185
186
  o.userData.model = JSON.stringify(model); // the built model, as text (describe / tests read it); serialized once per build, never per frame
186
187
  o.userData.modelFrom = modelSource(d, rec); // update compares this cheap key every frame: a stage with another model rebuilds the copy
187
188
  if (d.body && e.world.building(id) === mine) addBody(e, rec, o, d); // a build a load or rebuild replaced meanwhile is dropped: its body would take the id, and the saved state, from the real one
188
- o.userData.useFrom = e.interactions;
189
189
  if (d.interact && e.interactions) o.userData.use = e.interactions.add(o, {
190
190
  id, radius: d.interact.radius ?? 2.5, height: d.interact.height, action: d.interact.action,
191
- label: () => label(e, def().interact?.label, e.world.get(id)) ?? name,
192
- enabled: () => { const r = e.world.get(id), en = def().interact?.enabled; return !!r && (!en || !!en(r, e)); },
193
- onUse: () => use(e, def(), id),
191
+ label: (_, ctx) => label(e, def().interact?.label, e.world.get(id), ctx) ?? name,
192
+ enabled: (_, ctx) => { const r = e.world.get(id), en = def().interact?.enabled; return !!r && (!en || !!en(r, e, ctx)); },
193
+ onUse: (_, ctx) => use(e, def(), id, ctx?.actor),
194
194
  });
195
195
  return o;
196
196
  },
@@ -198,7 +198,6 @@ function present(e, api, st, name) {
198
198
  const d = def();
199
199
  // a stage that names another model: tear this copy down, world builds the new one next frame (the record, and so the save, is untouched)
200
200
  if (d.stages && !sameModel(o.userData, d, rec)) { e.world.rebuild(rec.id); return; }
201
- if (d.interact && o.userData.useFrom !== e.interactions) { e.world.rebuild(rec.id); return; } // its use lives in the interactions module it was built with: another one starts empty
202
201
  const mul = stageScale(d, rec);
203
202
  if (d.body) { // a body places itself. Its turn and size were built into the solver: a new one needs a new body, built where the record stands
204
203
  if (!fitsShape(o, rec, mul) || !sameBody(e, o.userData, d)) { e.world.rebuild(rec.id); return; }
@@ -305,10 +304,11 @@ function simulate(e, st, name) {
305
304
  })));
306
305
  }
307
306
 
308
- const label = (e, l, rec) => typeof l === 'function' ? l(rec, e) : l && e.i18n.has(l) ? e.t(l) : l;
307
+ const label = (e, l, rec, ctx) => typeof l === 'function' ? l(rec, e, ctx) : l && e.i18n.has(l) ? e.t(l) : l;
309
308
 
310
309
  /** Using an instance runs the template's op with its id (a gameplay action, logged), then plays the use sound if it succeeded. */
311
- function use(e, d, id) {
312
- const r = e.ops.run(d.interact.op, { id });
310
+ function use(e, d, id, actor) {
311
+ const r = e.ops.run(d.interact.op, { id }, actor !== undefined ? { actor } : undefined);
313
312
  if (r.ok && d.sound?.use) e.audio.sfx(d.sound.use);
313
+ return r.ok ? r.value : r;
314
314
  }
@@ -120,6 +120,7 @@ const DEBUG_PANEL_PARAMS = keysSchema(['open']);
120
120
  /**
121
121
  * Debug panel -> engine.debug.panel: performance panel, time and weather debugging. Collapsed by default; the action 'debugPanel' shows/hides it (presets.bindings.debug: F3); open: true shows it at start. Just do not install it in a release
122
122
  * @param {{ open?: boolean }} [opts]
123
+ * open: show the debug panel expanded at startup instead of collapsed (default false).
123
124
  * @returns {ModuleDef<DebugPanel>}
124
125
  */
125
126
  export function debug(opts = {}) {
@@ -0,0 +1,393 @@
1
+ // Conforming surface decals: bullet holes, footprints, bloodstains, scorch marks, wall graffiti and ground rings -> engine.decals.
2
+ // Clips against target meshes (DecalGeometry) or conforms to engine.surface(x, z) on procedural ground, with a ring-buffer cap and fade-out.
3
+ // Works identically on WebGLRenderer and WebGPURenderer; neutral gray until the game supplies a color, texture or material.
4
+ import * as THREE from 'three';
5
+ import { DecalGeometry } from 'three/addons/geometries/DecalGeometry.js';
6
+ import { mergeGeometries } from 'three/addons/utils/BufferGeometryUtils.js';
7
+ import { neutralMaterial } from '../../render/neutral.js';
8
+ import { placeholderTexture } from '../../render/effects.js';
9
+ import { engineOwned } from '../../core/scene/things.js';
10
+ import { vec3 } from '../../core/base/math.js';
11
+ import { readParams, keysSchema } from '../../core/base/params.js';
12
+ import { codedError } from '../../core/base/errorHints.js';
13
+
14
+ /** @import { ModuleDef } from '../../types/core' */
15
+ /** @import { DecalsOptions, DecalKindOptions, DecalAddOptions, DecalHandle } from '../../types/gameplay' */
16
+
17
+ const KIND_KEYS = ['size', 'depth', 'map', 'normalMap', 'color', 'opacity', 'lifetime', 'fade', 'max', 'material', 'attach', 'segments', 'offset'];
18
+ const KIND_SCHEMA = keysSchema(KIND_KEYS, {}, {
19
+ depth: { type: 'number', min: 0.01, optional: true, desc: 'projection box depth in meters' },
20
+ opacity: { type: 'number', min: 0, max: 1, optional: true, desc: 'starting opacity 0..1' },
21
+ lifetime: { type: 'number', min: 0, optional: true, desc: 'seconds before removal (Infinity = permanent)' },
22
+ fade: { type: 'number', min: 0, optional: true, desc: 'seconds at the end of lifetime over which opacity fades to 0' },
23
+ max: { type: 'int', min: 1, optional: true, desc: 'pool cap for this kind' },
24
+ segments: { type: 'int', min: 1, max: 32, optional: true, desc: 'grid subdivisions when conforming to terrain height' },
25
+ offset: { type: 'number', min: 0, optional: true, desc: 'surface lift in meters on ground grids' },
26
+ });
27
+ const ADD_SCHEMA = keysSchema([...KIND_KEYS, 'kind', 'target', 'normal', 'roll'], {}, {
28
+ kind: { type: 'string', optional: true, desc: 'defined decal kind name' },
29
+ roll: { type: 'number', optional: true, desc: 'rotation around the surface normal in radians' },
30
+ });
31
+ const MODULE_SCHEMA = {
32
+ max: { type: 'int', min: 1, optional: true, desc: 'global live decal cap (default 128, 64 on low tier)' },
33
+ effects: { type: 'object', optional: true, desc: 'named decal kinds defined at install' },
34
+ default: { type: 'object', optional: true, desc: 'base options every decal inherits' },
35
+ };
36
+ const PATCH_SCHEMA = keysSchema(['color', 'opacity', 'lifetime', 'fade', 'visible']);
37
+
38
+ const DEFAULT_MAX = 128;
39
+ const UP = new THREE.Vector3(0, 1, 0);
40
+ const _pos = new THREE.Vector3(), _nrm = new THREE.Vector3(), _rayOrig = new THREE.Vector3(), _rayDir = new THREE.Vector3();
41
+ const _look = new THREE.Matrix4(), _inv = new THREE.Matrix4(), _euler = new THREE.Euler(), _size3 = new THREE.Vector3();
42
+ const _box = new THREE.Box3(), _meshBox = new THREE.Box3();
43
+
44
+ function sizeVec(size, depth) {
45
+ if (Array.isArray(size)) return _size3.set(size[0] ?? 1, size[1] ?? size[0] ?? 1, size[2] ?? depth);
46
+ if (size && typeof size === 'object') return _size3.set(size.x ?? 1, size.y ?? size.x ?? 1, size.z ?? depth);
47
+ const s = typeof size === 'number' && size > 0 ? size : 1;
48
+ return _size3.set(s, s, depth);
49
+ }
50
+
51
+ function orientFor(pos, normal, roll = 0) {
52
+ _look.lookAt(pos, _rayOrig.copy(pos).add(normal), Math.abs(normal.y) > 0.99 ? _rayDir.set(0, 0, 1) : UP);
53
+ _euler.setFromRotationMatrix(_look);
54
+ if (roll) {
55
+ const q = new THREE.Quaternion().setFromRotationMatrix(_look);
56
+ const rq = new THREE.Quaternion().setFromAxisAngle(normal, roll);
57
+ q.premultiply(rq);
58
+ _euler.setFromQuaternion(q);
59
+ }
60
+ return _euler;
61
+ }
62
+
63
+ /** Collect visible meshes under root whose world bounding box intersects box */
64
+ function collectMeshes(root, box, out) {
65
+ root.updateWorldMatrix(true, false);
66
+ root.traverse(o => {
67
+ if (!o.isMesh || !o.visible || !o.geometry?.attributes?.position || o.isInstancedMesh || o.isSkinnedMesh) return;
68
+ if (!o.geometry.boundingBox) o.geometry.computeBoundingBox();
69
+ if (o.geometry.boundingBox) {
70
+ _meshBox.copy(o.geometry.boundingBox).applyMatrix4(o.matrixWorld);
71
+ if (!box.intersectsBox(_meshBox)) return;
72
+ }
73
+ out.push(o);
74
+ });
75
+ }
76
+
77
+ /** Build a ground-conforming grid in world space around pos when projecting onto heightfield terrain */
78
+ function buildGroundGrid(engine, pos, sx, sy, roll, segs, lift) {
79
+ const cols = segs, rows = segs, vx = cols + 1, vz = rows + 1;
80
+ const positions = new Float32Array(vx * vz * 3);
81
+ const normals = new Float32Array(vx * vz * 3);
82
+ const uvs = new Float32Array(vx * vz * 2);
83
+ const indices = [];
84
+ const cos = Math.cos(roll), sin = Math.sin(roll), eps = Math.max(0.15, Math.min(sx, sy) / segs);
85
+ for (let j = 0; j <= rows; j++) {
86
+ const v = j / rows, lz = (v - 0.5) * sy;
87
+ for (let i = 0; i <= cols; i++) {
88
+ const u = i / cols, lx = (u - 0.5) * sx;
89
+ const wx = pos.x + lx * cos - lz * sin, wz = pos.z + lx * sin + lz * cos;
90
+ const wy = engine.surface(wx, wz, pos.y);
91
+ const h = Number.isFinite(wy) ? wy : pos.y;
92
+ const hx = engine.surface(wx + eps, wz, pos.y), hz = engine.surface(wx, wz + eps, pos.y);
93
+ const dx = Number.isFinite(hx) ? (hx - h) / eps : 0, dz = Number.isFinite(hz) ? (hz - h) / eps : 0;
94
+ const len = Math.hypot(dx, 1, dz) || 1, nx = -dx / len, ny = 1 / len, nz = -dz / len;
95
+ const k = j * vx + i;
96
+ positions[k * 3] = wx - pos.x + nx * lift;
97
+ positions[k * 3 + 1] = h - pos.y + ny * lift;
98
+ positions[k * 3 + 2] = wz - pos.z + nz * lift;
99
+ normals[k * 3] = nx; normals[k * 3 + 1] = ny; normals[k * 3 + 2] = nz;
100
+ uvs[k * 2] = u; uvs[k * 2 + 1] = 1 - v;
101
+ }
102
+ }
103
+ for (let j = 0; j < rows; j++) for (let i = 0; i < cols; i++) {
104
+ const a = j * vx + i, b = a + 1, c = a + vx, d = c + 1;
105
+ indices.push(a, c, b, b, c, d);
106
+ }
107
+ const geo = new THREE.BufferGeometry();
108
+ geo.setAttribute('position', new THREE.BufferAttribute(positions, 3));
109
+ geo.setAttribute('normal', new THREE.BufferAttribute(normals, 3));
110
+ geo.setAttribute('uv', new THREE.BufferAttribute(uvs, 2));
111
+ geo.setIndex(indices);
112
+ return geo;
113
+ }
114
+
115
+ /** engine.decals */
116
+ export class Decals {
117
+ /** @internal */
118
+ constructor(engine, opts = {}) {
119
+ /** @internal */ this.engine = engine;
120
+ /** @internal */ this._maxGiven = opts.max ?? null;
121
+ /** @internal */ this._fallback = opts.default ?? {};
122
+ /** @internal */ this._kinds = new Map();
123
+ /** @internal */ this._live = [];
124
+ /** @internal */ this._textures = new Map();
125
+ /** @internal */ this._own = neutralMaterial('decal', { transparent: true, depthWrite: false, polygonOffset: true, polygonOffsetFactor: -4, polygonOffsetUnits: -4 });
126
+ /** @internal */ this._material = this._own;
127
+ if (opts.default) readParams('decals({ default })', KIND_SCHEMA, opts.default);
128
+ if (opts.effects) for (const [k, v] of Object.entries(opts.effects)) this.define(k, v);
129
+ }
130
+
131
+ /**
132
+ * Default base material cloned for decals that pass no `material` of their own (a neutral MeshLambertMaterial with polygonOffset until swapped).
133
+ * @type {import('../../types/common').Material}
134
+ */
135
+ get material() { return this._material; }
136
+ set material(m) {
137
+ if (!m || !m.isMaterial) throw codedError('decal-option', 'engine.decals.material must be a three.js Material');
138
+ this._material = m;
139
+ }
140
+
141
+ /** @internal */
142
+ _cap() { return this._maxGiven ?? (this.engine.tier === 'low' ? DEFAULT_MAX >> 1 : DEFAULT_MAX); }
143
+
144
+ /** @internal */
145
+ _loadTex(name, color) {
146
+ const key = `${color ? 'c' : 'n'}:${name}`;
147
+ let t = this._textures.get(key);
148
+ if (t) return t;
149
+ t = placeholderTexture(color ? 'white' : 'normal');
150
+ if (color) t.colorSpace = THREE.SRGBColorSpace;
151
+ this._textures.set(key, t);
152
+ this.engine.assets.useTexture(name, a => {
153
+ if (this._textures.get(key) !== t) return;
154
+ t.source = a.source;
155
+ if (color) t.colorSpace = THREE.SRGBColorSpace;
156
+ t.needsUpdate = true;
157
+ }, { where: 'decal texture', instead: 'the placeholder stays', opts: { color } });
158
+ return t;
159
+ }
160
+
161
+ /** @internal */
162
+ _makeMat(spec) {
163
+ const src = spec.material ?? this._material;
164
+ const mat = src.clone();
165
+ mat.transparent = true;
166
+ if (spec.material == null) {
167
+ mat.depthWrite = false;
168
+ mat.polygonOffset = true; mat.polygonOffsetFactor = -4; mat.polygonOffsetUnits = -4;
169
+ }
170
+ if (spec.opacity != null) mat.opacity = spec.opacity;
171
+ if (spec.color != null && mat.color) mat.color.set(spec.color);
172
+ if (spec.map && 'map' in mat) mat.map = typeof spec.map === 'string' ? this._loadTex(spec.map, true) : spec.map;
173
+ if (spec.normalMap && 'normalMap' in mat) mat.normalMap = typeof spec.normalMap === 'string' ? this._loadTex(spec.normalMap, false) : spec.normalMap;
174
+ return { mat, owned: true };
175
+ }
176
+
177
+ /**
178
+ * Define a named decal kind (bulletHole, footprint, ring...). Calling again with the same name updates future decals of that kind.
179
+ * @example engine.decals.define('scorch', { size: 1.4, opacity: 0.85, lifetime: 12, fade: 3, max: 32 });
180
+ * @param {string} name
181
+ * @param {DecalKindOptions} [opts]
182
+ * @returns {DecalKindOptions}
183
+ */
184
+ define(name, opts = {}) {
185
+ if (typeof name !== 'string' || !name) throw codedError('decal-option', `engine.decals.define(name, opts): name must be a non-empty string, got ${JSON.stringify(name)}`);
186
+ readParams(`decals.define('${name}')`, KIND_SCHEMA, opts);
187
+ const merged = { ...this._fallback, ...opts };
188
+ this._kinds.set(name, merged);
189
+ return merged;
190
+ }
191
+
192
+ /**
193
+ * Project a decal onto a mesh or the ground. `at` may be a raycast hit (`engine.pick` / `engine.raycast` result: `{ point, normal, face, object }`)
194
+ * or any position (`[x, y, z]`, `Vector3`, `Object3D`). Returns a handle `{ object, kind, set(patch), remove() }`.
195
+ * @example const hit = engine.pick(0, 0); if (hit) engine.decals.add(hit, { kind: 'scorch' });
196
+ * @example const ring = engine.decals.add([10, 0, -4], { size: 4, color: 0xcccccc, lifetime: 1.5 });
197
+ * @param {any} at
198
+ * @param {DecalAddOptions} [opts]
199
+ * @returns {DecalHandle}
200
+ */
201
+ add(at, opts = {}) {
202
+ if (!at) throw codedError('decal-option', 'engine.decals.add(at, opts): at must be a position or raycast hit');
203
+ readParams('decals.add()', ADD_SCHEMA, opts);
204
+ const kindName = opts.kind ?? null;
205
+ if (kindName && !this._kinds.has(kindName)) throw codedError('decal-option', `engine.decals.add(): unknown kind '${kindName}'; define it with engine.decals.define('${kindName}', ...) first`);
206
+ const spec = { ...this._fallback, ...(kindName ? this._kinds.get(kindName) : null), ...opts };
207
+ const isHit = at && typeof at === 'object' && at.point?.isVector3;
208
+ let target = spec.target ?? (isHit ? at.object : null);
209
+ if (isHit) {
210
+ _pos.copy(at.point);
211
+ const rawN = spec.normal ? vec3(spec.normal, _nrm) : (at.normal ?? at.face?.normal);
212
+ if (rawN) {
213
+ _nrm.copy(rawN);
214
+ if (!spec.normal && at.face?.normal === rawN && at.object?.matrixWorld) _nrm.transformDirection(at.object.matrixWorld);
215
+ } else _nrm.copy(UP);
216
+ } else {
217
+ vec3(at, _pos);
218
+ if (spec.normal) vec3(spec.normal, _nrm); else _nrm.copy(UP);
219
+ }
220
+ if (_nrm.lengthSq() < 1e-8) _nrm.copy(UP); else _nrm.normalize();
221
+
222
+ const depth = spec.depth ?? 0.6;
223
+ const sv = sizeVec(spec.size, depth).clone();
224
+ const roll = spec.roll ?? 0;
225
+
226
+ // Auto-probe static meshes along -normal when no target was passed
227
+ if (!target) {
228
+ _rayOrig.copy(_pos).addScaledVector(_nrm, depth * 0.5);
229
+ _rayDir.copy(_nrm).negate();
230
+ const hit = this.engine.raycast(_rayOrig, _rayDir, { maxDistance: depth * 1.5 });
231
+ if (hit?.object?.isMesh) {
232
+ target = hit.object;
233
+ _pos.copy(hit.point);
234
+ if (!spec.normal && hit.face?.normal) _nrm.copy(hit.face.normal).transformDirection(target.matrixWorld).normalize();
235
+ }
236
+ }
237
+
238
+ let geo = null, parent = this.engine.scene, local = false;
239
+ if (target) {
240
+ const half = Math.max(sv.x, sv.y, sv.z) * 0.75;
241
+ _box.min.set(_pos.x - half, _pos.y - half, _pos.z - half);
242
+ _box.max.set(_pos.x + half, _pos.y + half, _pos.z + half);
243
+ const meshes = [];
244
+ collectMeshes(target, _box, meshes);
245
+ if (meshes.length) {
246
+ const orient = orientFor(_pos, _nrm, roll);
247
+ const parts = [];
248
+ for (const m of meshes) {
249
+ const g = new DecalGeometry(m, _pos, orient, sv);
250
+ if (g.attributes.position?.count > 0) parts.push(g); else g.dispose();
251
+ }
252
+ if (parts.length === 1) geo = parts[0];
253
+ else if (parts.length > 1) { geo = mergeGeometries(parts, false); for (const p of parts) p.dispose(); }
254
+ if (geo && (spec.attach ?? (target.isMesh && !this.engine.rays?.statics?.has?.(target)))) {
255
+ target.updateWorldMatrix(true, false);
256
+ _inv.copy(target.matrixWorld).invert();
257
+ geo.applyMatrix4(_inv);
258
+ parent = target; local = true;
259
+ }
260
+ }
261
+ }
262
+ if (!geo) {
263
+ const gy = this.engine.surface(_pos.x, _pos.z, _pos.y);
264
+ if (Number.isFinite(gy) && !isHit) _pos.y = gy;
265
+ const segs = spec.segments ?? Math.max(2, Math.min(12, Math.ceil(Math.max(sv.x, sv.y) / 1.5)));
266
+ geo = buildGroundGrid(this.engine, _pos, sv.x, sv.y, roll, segs, spec.offset ?? 0.015);
267
+ local = true;
268
+ }
269
+
270
+ // Enforce per-kind and global pool caps before adding
271
+ if (kindName && spec.max) {
272
+ while (this.count(kindName) >= spec.max) { const old = this._live.find(e => e.kind === kindName); if (!old) break; old.remove(); }
273
+ }
274
+ const cap = this._cap();
275
+ while (this._live.length >= cap) this._live[0].remove();
276
+
277
+ const { mat, owned } = this._makeMat(spec);
278
+ const mesh = engineOwned('decals', new THREE.Mesh(geo, mat));
279
+ mesh.name = kindName ? `decal:${kindName}` : 'decal';
280
+ mesh.renderOrder = 2;
281
+ mesh.receiveShadow = true;
282
+ if (local && parent === this.engine.scene) mesh.position.copy(_pos);
283
+ parent.add(mesh);
284
+
285
+ const entry = {
286
+ kind: kindName, object: mesh, mat, owned, age: 0,
287
+ baseOpacity: mat.opacity ?? 1,
288
+ lifetime: spec.lifetime ?? Infinity,
289
+ fade: spec.fade ?? 0.6,
290
+ dead: false,
291
+ set: (patch = {}) => {
292
+ readParams('decal.set()', PATCH_SCHEMA, patch);
293
+ if (patch.color !== undefined && mat.color) mat.color.set(patch.color);
294
+ if (patch.opacity !== undefined) { entry.baseOpacity = patch.opacity; mat.opacity = patch.opacity; }
295
+ if (patch.lifetime !== undefined) entry.lifetime = patch.lifetime;
296
+ if (patch.fade !== undefined) entry.fade = patch.fade;
297
+ if (patch.visible !== undefined) mesh.visible = !!patch.visible;
298
+ return handle;
299
+ },
300
+ remove: () => {
301
+ if (entry.dead) return;
302
+ entry.dead = true;
303
+ const idx = this._live.indexOf(entry);
304
+ if (idx >= 0) this._live.splice(idx, 1);
305
+ mesh.removeFromParent();
306
+ geo.dispose();
307
+ if (owned) mat.dispose();
308
+ },
309
+ };
310
+ const handle = { get object() { return mesh; }, get kind() { return kindName; }, set: entry.set, remove: entry.remove };
311
+ this._live.push(entry);
312
+ return handle;
313
+ }
314
+
315
+ /**
316
+ * Remove live decals of `kind`, or every live decal when `kind` is omitted. Definitions stay.
317
+ * @param {string} [kind]
318
+ * @returns {void}
319
+ */
320
+ remove(kind) {
321
+ const copy = this._live.slice();
322
+ for (const e of copy) if (kind == null || e.kind === kind) e.remove();
323
+ }
324
+
325
+ /**
326
+ * Live decal count (for one kind, or all when omitted)
327
+ * @param {string} [kind]
328
+ * @returns {number}
329
+ */
330
+ count(kind) {
331
+ if (kind == null) return this._live.length;
332
+ let n = 0;
333
+ for (let i = 0; i < this._live.length; i++) if (this._live[i].kind === kind) n++;
334
+ return n;
335
+ }
336
+
337
+ /** @internal */
338
+ _tierChanged() {
339
+ const cap = this._cap();
340
+ while (this._live.length > cap) this._live[0].remove();
341
+ }
342
+
343
+ /** @internal */
344
+ update(dt) {
345
+ if (this.engine.frozen || dt <= 0) return;
346
+ for (let i = this._live.length - 1; i >= 0; i--) {
347
+ const e = this._live[i];
348
+ if (!Number.isFinite(e.lifetime)) continue;
349
+ e.age += dt;
350
+ if (e.age >= e.lifetime) { e.remove(); continue; }
351
+ const rem = e.lifetime - e.age;
352
+ if (e.fade > 0 && rem < e.fade) e.mat.opacity = e.baseOpacity * Math.max(0, rem / e.fade);
353
+ }
354
+ }
355
+
356
+ /** @internal */
357
+ dispose() {
358
+ this.remove();
359
+ this._own.dispose();
360
+ for (const t of this._textures.values()) t.dispose();
361
+ this._textures.clear();
362
+ this._kinds.clear();
363
+ }
364
+ }
365
+
366
+ /**
367
+ * Surface decals (bullet holes, footprints, ground rings, stains) -> engine.decals
368
+ * @param {DecalsOptions} [opts]
369
+ * @returns {ModuleDef<Decals>}
370
+ */
371
+ export function decals(opts = {}) {
372
+ readParams('decals', MODULE_SCHEMA, opts);
373
+ let d = null;
374
+ return {
375
+ name: 'decals', skipKind: 'none', type: 'picture', label: 'Decals', params: MODULE_SCHEMA, options: opts,
376
+ install(e, ctx) {
377
+ e.i18n.add({ 'zh-CN': { 'module.decals': '贴花' }, en: { 'module.decals': 'decals' } });
378
+ d = new Decals(e, opts);
379
+ ctx.track(e.events.on('tier:change', () => d._tierChanged()));
380
+ return d;
381
+ },
382
+ frame(dt) { d.update(dt); },
383
+ dispose() { d.dispose(); },
384
+ counts: () => ({ active: d.count(), kinds: d._kinds.size }),
385
+ describe() {
386
+ const byKind = {};
387
+ for (const e of d._live) { const k = e.kind ?? 'unnamed'; byKind[k] = (byKind[k] ?? 0) + 1; }
388
+ return { active: d.count(), cap: d._cap(), kinds: [...d._kinds.keys()], byKind };
389
+ },
390
+ };
391
+ }
392
+
393
+ export const handRolled = 'none: a single plane or DecalGeometry of its own is plain three.js';
@@ -0,0 +1 @@
1
+ export { decals, handRolled } from './Decals.js';
@@ -158,6 +158,7 @@ export class Container {
158
158
  e.count -= k;
159
159
  if (!e.count) this._entries.splice(at, 1);
160
160
  const out = this._place(e.id, k, d, keep, at);
161
+ this.inv._containers._touch(this.id);
161
162
  if (this._local) this.inv._refresh();
162
163
  return out;
163
164
  }
@@ -230,6 +231,7 @@ export class Container {
230
231
  */
231
232
  _emit(type, id, count, key) {
232
233
  const e = this.inv.engine;
234
+ this.inv._containers._touch(this.id);
233
235
  e.events.emit(type === 'add' ? 'item:add' : 'item:remove', { container: this.id, actor: e.ops.actor, id, key, count, total: this.count(id) });
234
236
  if (this._local) this.inv._refresh();
235
237
  }
@@ -7,10 +7,18 @@ import { checkCount } from './boxOps.js';
7
7
  import { codedError } from '../../core/base/errorHints.js';
8
8
  import { isPlainObject } from '../../core/base/util.js';
9
9
  import { refuseSave } from '../../core/base/saveValues.js';
10
+ import { addDirtyWatcher, touchDirty, touchDirtyAll } from '../../core/stream/dirtyWatch.js';
10
11
 
11
12
  /** Container table: implementation of inventory.container() / transfer(); bag is the home bag 'player' (saved as its own part, never removed). @internal */
12
13
  export class Containers {
13
- constructor(inv, bag) { this.inv = inv; this.bag = bag; this.map = new Map([[bag.id, bag]]); this.renames = new Map(); }
14
+ constructor(inv, bag) { this.inv = inv; this.bag = bag; this.map = new Map([[bag.id, bag]]); this.renames = new Map(); /** @internal */ this._watchers = null; }
15
+
16
+ /** @internal Subscribe to container mutations for incremental sync (zero overhead when unwatched) */
17
+ trackDirty() { return addDirtyWatcher(this, { read: id => this.map.get(id)?._save() }); }
18
+ /** @internal */
19
+ _touch(id) { touchDirty(this, id); }
20
+ /** @internal */
21
+ _touchAll() { touchDirtyAll(this); }
14
22
 
15
23
  /**
16
24
  * content/renames.js: a container saved under an old authored id moves to the new id (null = drop it). Remembered, so a save loaded later
@@ -27,7 +35,8 @@ export class Containers {
27
35
  this.map.delete(a);
28
36
  if (b != null) { c.id = b; this.map.set(b, c); }
29
37
  }
30
- return () => { for (const fn of back) fn(); for (const [c, id] of ids) c.id = id; };
38
+ this._touchAll();
39
+ return () => { for (const fn of back) fn(); for (const [c, id] of ids) c.id = id; this._touchAll(); };
31
40
  }
32
41
 
33
42
  get(id, opts) {
@@ -37,6 +46,7 @@ export class Containers {
37
46
  let c = this.map.get(id);
38
47
  if (!c) {
39
48
  this.map.set(id, c = new Container(this.inv, id, opts));
49
+ this._touch(id);
40
50
  // place goods only on first creation; seeding is setup, so the ops guard lets it through
41
51
  if (opts?.items) { c._start = { ...opts.items }; this._seed(c); }
42
52
  } else { // container created first by a load, game code sets the limits afterwards; if it already exists, goods are not placed again, but a later load of an older save needs them
@@ -79,7 +89,9 @@ export class Containers {
79
89
 
80
90
  remove(id) {
81
91
  if (id === this.bag.id) throw codedError('container', `The player inventory ('${id}') cannot be removed`);
82
- return this.map.delete(id);
92
+ const ok = this.map.delete(id);
93
+ if (ok) this._touch(id);
94
+ return ok;
83
95
  }
84
96
 
85
97
  /** @internal place a container's starting goods (content setup: the ops guard lets it through) */
@@ -95,6 +107,7 @@ export class Containers {
95
107
  }
96
108
  });
97
109
  c.seeded = true;
110
+ this._touch(c.id);
98
111
  }
99
112
  /** Save: non-player containers that have contents or ever had starting contents placed (an emptied one is still recorded, or a load would treat it as new and place them again) */
100
113
  save() {
@@ -117,5 +130,6 @@ export class Containers {
117
130
  for (const [id, list] of Object.entries(d || {})) { const c = this.get(id); c._load(list); c.seeded = true; }
118
131
  // entry keys are numbered across all containers: never hand out a key a loaded container already holds
119
132
  for (const c of this.map.values()) for (const e of c._entries) { const n = Number(e.key.split('#')[1]) || 0; if (n > this.inv._seq) this.inv._seq = n; }
133
+ this._touchAll();
120
134
  }
121
135
  }
@@ -156,10 +156,10 @@ export class Dialogue {
156
156
  /** @internal session:end or a load: close the dialogue without its onEnd (that callback belongs to the old playthrough: an NPC's busy flag, a say() Promise); drop bubbles */
157
157
  _cancel() {
158
158
  this._bubbles.clear(); this._asks.clear();
159
+ for (const k of [...this.scripts.keys()]) if (k.startsWith('__say_')) this.scripts.delete(k);
159
160
  const a = this.active;
160
161
  if (!a) return;
161
162
  a.onEnd = null;
162
- if (a.speaker.startsWith('__say_')) this.scripts.delete(a.speaker);
163
163
  this.end();
164
164
  }
165
165