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
@@ -321,8 +321,10 @@ export class Interactions {
321
321
  this._pass = ++this._passes;
322
322
  try {
323
323
  if (this._hold) this._tickHold(dt);
324
- this._presses(inp, this.engine.actor);
325
- for (const s of inp.seats) if (s.actor) this._presses(s, s.actor);
324
+ for (const actor of this.engine.localActors()) {
325
+ const src = actor === this.engine.actor ? inp : inp.seats.find(s => s.actor === actor);
326
+ if (src) this._presses(src, actor);
327
+ }
326
328
  } finally { this._pass = 0; } // as update(): a throwing use must not leave the pass open (every later pick would reuse stale positions)
327
329
  }
328
330
  /** @internal The presses of one input, engine.input or a seat, for the actor it acts for. One hold at a time: a press during someone's hold waits for it to end */
@@ -383,7 +385,7 @@ export class Interactions {
383
385
  best.object.getWorldPosition(V); V.y += best.height ?? this.promptHeight;
384
386
  const s = worldToScreen(this.engine, V);
385
387
  // progress: the running hold on this one (0-1), 0 for a hold not started, null for a plain press
386
- const progress = this.holding?.id === best.id ? this.holding.progress : best.hold > 0 ? 0 : null;
388
+ const progress = this._hold?.actor === this.engine.actor && this.holding?.id === best.id ? this.holding.progress : best.hold > 0 ? 0 : null;
387
389
  part.update({ id: best.id, action: best.action, key, label, text: keyed(key, label), x: s.x, y: s.y, onScreen: s.onScreen, use: this._use, options: this.options, progress });
388
390
  this._shown = true;
389
391
  }
@@ -404,8 +406,7 @@ export class Interactions {
404
406
  // label / enabled / onUse all get (object, { actor }): who is asking is part of the question (a door that only its owner may open, a shop that greets each
405
407
  // net peer by name), so a game never has to read engine.actor or engine.player inside them and they stay right for NPCs and peers
406
408
  const labelOf = (it, actor) => typeof it.label === 'function' ? it.label(it.object, { actor }) : it.label;
407
- // shortcut: approach walks only players (actor 'player' or a seat's); a squad / RTS game whose actor is an NPC gets 'cannotWalk' until NPC actors map to a Character
408
- const walkerOf = (e, actor) => { const c = actor === 'player' ? e.player : e.input.seats.some(s => s.actor === actor) ? e.control.characterOf(actor) : null; return c?.walkTo ? c : null; };
409
+ const walkerOf = (e, actor) => { const c = e.control.characterOf(actor) ?? (actor === 'player' ? e.player : null); return c?.walkTo ? c : null; };
409
410
 
410
411
  const INTERACTION_PARAMS = {
411
412
  action: { type: 'string', default: 'interact', desc: 'input action that uses the interaction' },
@@ -432,7 +433,7 @@ export function interactions(opts) {
432
433
  return { name: 'interactions', skipKind: 'none', type: 'rules', provides: ['interactions'], optional: ['hud'], label: 'Interactions', params: INTERACTION_PARAMS, options: o, noSkip: 'input and prompt state only', stage: 'gameplay',
433
434
  // o: the schema defaults are filled in, the class repeats none
434
435
  install(e, ctx) { e.i18n.add({ 'zh-CN': { 'module.interactions': '交互' }, en: { 'module.interactions': 'interactions' } }); i = new Interactions(e, o, ctx); defineUse(e, ctx, i); return i; },
435
- fixed(dt) { i.fixed(dt); }, frame() { i.update(); },
436
+ fixed(dt) { i.fixed(dt); }, frame() { i.update(); }, sessionEnd() { if (i._hold) i._interrupt('replaced'); },
436
437
  // interactions are "weak" info: when an NPC, pickup or entity already reported the same object, only add "interactable: xxx"
437
438
  describe(e, ctx) {
438
439
  // no key: not "interactable", and no plain "interact: X" on an NPC's line, because no player input reaches it
@@ -51,6 +51,7 @@ export class Inventory {
51
51
  this.home._load(d?.items);
52
52
  const top = Math.max(0, ...this.home._entries.map(x => Number(x.key.split('#')[1]) || 0));
53
53
  this._seq = Number.isSafeInteger(d?.seq) && d.seq >= top ? d.seq : top; // past safe whole numbers ++ stops counting and keys repeat
54
+ this._containers._touch(this.home.id);
54
55
  this._refresh();
55
56
  } });
56
57
  // 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)
@@ -110,7 +111,7 @@ export class Inventory {
110
111
  undoPoint() {
111
112
  const boxes = this._containers, seq = this._seq, tables = [this.defs, boxes.map, boxes.renames].map(keepTable);
112
113
  const was = [...boxes.map.values()].map(c => [c, { id: c.id, capacity: c.capacity, maxWeight: c.maxWeight, seeded: c.seeded, _start: c._start, _entries: c._entries.map(x => ({ ...x })) }]);
113
- return () => { for (const fn of tables) fn(); for (const [c, v] of was) Object.assign(c, v); this._seq = seq; };
114
+ return () => { for (const fn of tables) fn(); for (const [c, v] of was) Object.assign(c, v); this._seq = seq; boxes._touchAll(); };
114
115
  }
115
116
  /**
116
117
  * Move n (default 1) of an item, or of one entry by key, between containers (container or id; an actor's bag has the actor's id). Pieces keep their data and key.
@@ -146,8 +147,11 @@ export class Inventory {
146
147
  if (c) { seen.add(c.id); c._load(data[id] ?? []); }
147
148
  }
148
149
  if (only) for (const [id, c] of this._containers.map) if (!seen.has(id)) c._load([]);
150
+ if (only) this._containers._touchAll(); else for (const id of seen) this._containers._touch(id);
149
151
  this._refresh();
150
152
  }
153
+ /** @internal Subscribe to container mutations for incremental sync (zero overhead when unwatched) */
154
+ trackDirty() { return this._containers.trackDirty(); }
151
155
 
152
156
  /**
153
157
  * Define an item. stack = pieces per slot (default 99); weight counts against maxWeight; use(e, { actor, item, key, data }) makes it usable with the
@@ -205,13 +205,14 @@ export class Quests {
205
205
  if (d.onUnpaid) this._ask(id, 'onUnpaid', d.onUnpaid, answer);
206
206
  else {
207
207
  for (const f of failed) for (const [item, n] of Object.entries(f.word === 'give' ? f.facts.left : {})) (s.owed ??= {})[item] = (s.owed?.[item] ?? 0) + n;
208
+ if (s.owed) s.owedActor = this.engine.ops.actor;
208
209
  this._say('unpaid', id, this.engine.t('quests.unpaid', { title: d.title }));
209
210
  }
210
211
  this.engine.events.emit('quest:unpaid', { id, code: answer.code, failed, owed: s.owed ? { ...s.owed } : null });
211
212
  }
212
213
  /** @internal Pay a debt as far as it fits. Only when something does: add in a full bag tells the player so, and this asks twice a second. A debt that throws (the item is gone from the game) cannot be paid, ever */
213
214
  _collect(id, s) {
214
- const e = this.engine, bag = e.inventory?.of(e.ops.actor);
215
+ const e = this.engine, bag = e.inventory?.of(s.owedActor ?? e.ops.actor);
215
216
  const answer = bag && this._ask(id, 'owed reward', () => {
216
217
  for (const [item, n] of Object.entries(s.owed)) {
217
218
  if ((bag.room?.(item) ?? 1) < 1) continue; // room is the engine bag's; a replacement without it is just asked
@@ -219,7 +220,7 @@ export class Quests {
219
220
  if (got < n) s.owed[item] = n - got; else delete s.owed[item];
220
221
  }
221
222
  });
222
- if (isRunFailure(answer) || !Object.keys(s.owed).length) delete s.owed;
223
+ if (isRunFailure(answer) || !Object.keys(s.owed).length) { delete s.owed; delete s.owedActor; }
223
224
  }
224
225
  isDone(id) { return !!this._progress[id]?.done; }
225
226
  isActive(id) { const s = this._progress[id]; return !!s && !s.done && !s.failed; }
@@ -234,7 +235,7 @@ export class Quests {
234
235
  if (d.fail?.(e)) { this._fail(id, s, d); continue; }
235
236
  let advanced = false;
236
237
  // at most one pass over the steps per check: a `next` that loops back to a step already done must wait for the next check, not hang
237
- for (let n = 0; n < d.steps.length && s.step < d.steps.length && this._stepDone(id, s, d.steps[s.step]); n++) { DEV && e.ops.guard('quests.advance'); this._leave(id, s, d); advanced = true; e.events.emit('quest:step', { id, step: s.step }); }
238
+ for (let n = 0; n < d.steps.length && !s.done && !s.failed && s.step < d.steps.length && this._stepDone(id, s, d.steps[s.step]); n++) { DEV && e.ops.guard('quests.advance'); this._leave(id, s, d); advanced = true; e.events.emit('quest:step', { id, step: s.step }); }
238
239
  this._finishOrSay(id, s, d, advanced);
239
240
  }
240
241
  }
@@ -62,8 +62,8 @@ export function inventoryWindow(e, o = {}) {
62
62
  };
63
63
  }
64
64
 
65
- /** Where an actor stands (engine.actorPosition: the player body, a vehicle, a world record) @internal */
66
- const posOf = (e, actor) => actor === 'player' && !e.player ? null : e.actorPosition(actor);
65
+ /** Where an actor stands (engine.liveActorPosition: the player body, a vehicle, a world record) @internal */
66
+ const posOf = (e, actor) => e.liveActorPosition(actor);
67
67
 
68
68
  /** Define inventory.transfer / inventory.use / inventory.drop @internal */
69
69
  export function defineInventoryOps(e, ctx, inv) {
@@ -23,7 +23,7 @@ import { readParams, keysSchema } from '../../core/base/params.js';
23
23
  import { copyData } from './Container.js';
24
24
  import { failure } from '../../core/ops/opsFail.js';
25
25
  import { protoOf, holdProtos, copyLeft, protoLease } from '../../core/assets/namedModel.js';
26
- import { freeParts, cloneModel } from '../../core/base/freeParts.js';
26
+ import { freeParts, cloneModel, keepPart } from '../../core/base/freeParts.js';
27
27
  import { shadowDefaults } from '../../core/assets/assetEntry.js';
28
28
  import { codedError, coded } from '../../core/base/errorHints.js';
29
29
 
@@ -33,7 +33,6 @@ const NO_ACTORS = [];
33
33
  const DEFAULT_COLOR = 0xcccccc;
34
34
  // A net host measures peers at the position they last sent (a few steps old): pickup.take allows this much beyond the radius so a fair press is not refused
35
35
  const NET_SLACK = 1;
36
- const seatActors = e => e.input.seats.flatMap(s => s.actor && s.actor !== e.actor ? [s.actor] : NO_ACTORS);
37
36
 
38
37
  export class Pickups {
39
38
  /** @internal ctx: the module's ctx */
@@ -42,7 +41,9 @@ export class Pickups {
42
41
  /** Edge of the placeholder box (meters), read when one is built */ this.size = size;
43
42
  /** Height above the ground new pickups float at (meters) */ this.lift = lift;
44
43
  /** @internal */ this._material = neutralMaterial('pickup', { color });
44
+ /** @internal */ this._matHold = keepPart(this._material);
45
45
  /** @internal copies of the material for a pickup's own color or a vertex-colored geometry: 'color' or 'color:vc' -> material */ this._copies = new Map();
46
+ /** @internal */ this._copyHolds = [];
46
47
  /** Reach of pickups that set no radius (meters); auto pickups are taken within it */ this.radius = radius;
47
48
  /** @internal pickups float, spin and have a model only within this distance of the stream sources */ this.showDistance = showDistance;
48
49
  /**
@@ -50,7 +51,7 @@ export class Pickups {
50
51
  * from the positions it is sent). A game with NPCs that collect coins returns their ids too.
51
52
  * @type {(e: any) => string[]}
52
53
  */
53
- this.takers = takers ?? (e => e.net?.role === 'client' ? NO_ACTORS : [e.actor, ...seatActors(e), ...(e.net?.peers.map(p => p.actor) ?? NO_ACTORS)]);
54
+ this.takers = takers ?? (e => e.net?.role === 'client' ? NO_ACTORS : [...e.localActors(), ...(e.net?.peers.map(p => p.actor) ?? NO_ACTORS)]);
54
55
  // world id -> what cannot go in saved data: the game's mesh, a give function. Spawning the same id again (content / setup code on load) sets them again
55
56
  /** @internal */ this._live = new Map();
56
57
  // the reach query around each taker uses the largest auto radius in the world, read from the records rather than from spawn calls:
@@ -78,9 +79,13 @@ export class Pickups {
78
79
  const old = this._material;
79
80
  if (m === old) return;
80
81
  this._material = m;
82
+ this._matHold.remove();
83
+ for (const h of this._copyHolds) h.remove();
84
+ this._copyHolds.length = 0;
81
85
  for (const c of this._copies.values()) c.dispose();
82
86
  this._copies.clear();
83
87
  if (isEngineMade(old)) old.dispose(); // a material the game gave stays the game's
88
+ this._matHold = keepPart(m);
84
89
  const w = this.engine.world;
85
90
  // only what is built now: a pickup out of reach has no model, and one built later asks for the current material
86
91
  for (const r of w.query({ kind: 'pickup' })) w.view(r.id)?.traverse(o => { if (o.userData.pickupColor !== undefined) /** @type {any} */ (o).material = pickupMaterial(this, o); });
@@ -177,7 +182,7 @@ export class Pickups {
177
182
  }
178
183
  if (!this._autoR) return;
179
184
  for (const actor of this.takers(e)) {
180
- const p = actor === 'player' && !e.player ? null : e.actorPosition(actor); // no player body: the camera focus is not someone walking
185
+ const p = e.liveActorPosition(actor); // no player body: the camera focus is not someone walking
181
186
  if (!p) continue;
182
187
  const near = w.query({ kind: 'pickup', near: p, radius: this._autoR, where: r => r.auto && r.until == null });
183
188
  // can first: one that does not fit stays in reach every step, and only a real take belongs in the op history
@@ -196,19 +201,23 @@ function present(pk, track) {
196
201
  show: rec => rec.until == null, // waiting to respawn: no model
197
202
  build: rec => model(pk, rec),
198
203
  update: (rec, o) => { // bobbing spin: world places the model at the data position each frame first, this adds the bob on top
199
- if (!rec.auto && o.userData.useFrom !== e.interactions) { w.rebuild(rec.id); return; } // its use lives in the interactions module it was built with: another one starts empty
200
204
  if (rec.bob === false) return;
201
205
  const t = e.time.now('real'), x = rec.position.x;
202
206
  o.rotation.y = t * 1.5 + x; o.position.y = rec.position.y + Math.sin(t * 2 + x) * 0.08;
203
207
  },
204
- // only detached: a game's mesh is the game's, a model clone shares geometry / material with its prototype (protoOf), the material is shared by every pickup;
205
- // the placeholder box is the one thing built here alone, so its geometry is freed
208
+ // a game's own mesh is only detached so it stays the game's (and can return when streaming back in);
209
+ // a holder this module built goes through engine.remove so its placeholder BoxGeometry and ray/thing registrations are freed while shared assets and kept pickup materials stay
206
210
  dispose: (rec, o) => {
207
- o.userData.useHandle?.remove(); o.removeFromParent();
208
- // a holder this module built: closed first, so a model that arrives later is not added to it; its copy goes through the one copy teardown (a game's own mesh is not ours to drop)
209
- if (o.userData.copyOpen) { o.userData.copyOpen = false; o.userData.lease?.remove(); e.assets.dropCopy(o); }
210
- const own = new Set(); o.traverse(c => { if (c.userData.ownGeometry) own.add(/** @type {any} */ (c).geometry); });
211
- freeParts(o, x => own.has(x)); copyLeft(e); // copyLeft: a retired prototype's material this copy drew may go now
211
+ o.userData.useHandle?.remove();
212
+ if (o.userData.copyOpen) {
213
+ o.userData.copyOpen = false; o.userData.lease?.remove(); e.assets.dropCopy(o);
214
+ e.remove(o);
215
+ } else {
216
+ o.removeFromParent();
217
+ const own = new Set(); o.traverse(c => { if (c.userData.ownGeometry) own.add(/** @type {any} */ (c).geometry); });
218
+ freeParts(o, x => own.has(x));
219
+ }
220
+ copyLeft(e); // copyLeft: a retired prototype's material this copy drew may go now
212
221
  },
213
222
  }));
214
223
  // waiting to respawn: when due (game clock) clear until and return to the ground. Far ones are also checked once a second, so they grow back on time even when not nearby
@@ -286,6 +295,7 @@ function pickupMaterial(pk, mesh) {
286
295
  if (vc) m.vertexColors = true;
287
296
  if (isEngineMade(base)) markEngineMade(m);
288
297
  pk._copies.set(key, m);
298
+ pk._copyHolds.push(keepPart(m));
289
299
  }
290
300
  return pk._copies.get(key);
291
301
  }
@@ -359,6 +369,7 @@ export function pickups(opts = {}) {
359
369
  noSkip: 'auto pickups are spatial; respawn follows the game clock',
360
370
  install(e, ctx) {
361
371
  pk = new Pickups(e, o, ctx); defineTake(e, ctx, pk); // o: the schema defaults are filled in, the class repeats none
372
+ ctx.feeds('interactions', () => { const w = e.world; if (!w) return; for (const r of w.query({ kind: 'pickup' })) if (!r.auto && w.view(r.id)) w.rebuild(r.id); });
362
373
  ctx.track(holdProtos(e, pk)); // the model prototypes its pickups clone (namedModel.js): unloading pickups gives them back
363
374
  return pk;
364
375
  },
@@ -368,6 +379,15 @@ export function pickups(opts = {}) {
368
379
  const w = e.world;
369
380
  for (const r of w.query({ kind: 'pickup', near: ctx.center, radius: ctx.radius, where: r => r.until == null })) ctx.near(w.view(r.id) ?? r.position, { name: pk._name(r), kind: 'pickup', id: r.item ?? r.id });
370
381
  },
382
+ dispose() {
383
+ pk._matHold?.remove();
384
+ for (const h of pk._copyHolds) h.remove();
385
+ pk._copyHolds.length = 0;
386
+ for (const c of pk._copies.values()) c.dispose();
387
+ pk._copies.clear();
388
+ if (isEngineMade(pk._material)) pk._material.dispose();
389
+ pk._live.clear();
390
+ },
371
391
  };
372
392
  }
373
393
 
@@ -30,7 +30,7 @@ const indexOf = (def, id) => def.steps.findIndex((_, i) => stepId(def, i) === id
30
30
  export function toSaved(def, s) {
31
31
  const out = { step: s.done ? null : stepId(def, s.step), done: !!s.done };
32
32
  if (s.failed) out.failed = true;
33
- if (s.owed) out.owed = { ...s.owed };
33
+ if (s.owed) { out.owed = { ...s.owed }; if (s.owedActor != null) out.owedActor = s.owedActor; }
34
34
  if (s.visited?.length) out.visited = [...s.visited];
35
35
  if (s.parts) out.parts = metIds(def.steps[s.step], s.parts);
36
36
  if (s.got) out.got = Object.fromEntries(Object.entries(s.got).map(([i, flags]) => [stepId(def, +i), metIds(def.steps[+i], flags)]));
@@ -49,7 +49,7 @@ export function fromSaved(id, def, q) {
49
49
  if (step < 0) { warnOnce(coded('quest-step', fmt(STRINGS.missing, { q: id, step: String(q.step) }))); step = 0; }
50
50
  const s = { step, done: !!q.done };
51
51
  if (q.failed) s.failed = true;
52
- if (q.owed) s.owed = { ...q.owed };
52
+ if (q.owed) { s.owed = { ...q.owed }; if (typeof q.owedActor === 'string') s.owedActor = q.owedActor; }
53
53
  // a save from before visited went through the list in order, so the steps behind this one are what it left
54
54
  s.visited = Array.isArray(q.visited) ? q.visited.filter(v => typeof v === 'string' && indexOf(def, v) >= 0) : def.steps.slice(0, step).map((_, i) => stepId(def, i));
55
55
  const st = def.steps[step];
@@ -250,8 +250,14 @@ const GRID_PARAMS = {
250
250
  tileLift: { type: 'number', default: 0.03, desc: 'height of tiles above the ground (meters)' },
251
251
  };
252
252
  /**
253
- * Options of grids()
254
- * @typedef {{ ok?: any, bad?: any, previewOpacity?: number, previewHeight?: number, tiles?: Record<string, Record<string, any>>, tileLift?: number }} GridsOptions
253
+ * Options of grids().
254
+ * @typedef {object} GridsOptions
255
+ * @property {any} [ok] Preview color where an item can be placed (default 0xe0e0e0).
256
+ * @property {any} [bad] Preview color where an item cannot be placed (default 0x3a3a3a).
257
+ * @property {number} [previewOpacity] Opacity of the placement preview box (default 0.45).
258
+ * @property {number} [previewHeight] Height of the placement preview box in meters (default 0.08).
259
+ * @property {Record<string, Record<string, any>>} [tiles] Tile colors by layer name ({ layer: { field: color } }).
260
+ * @property {number} [tileLift] Height of layer tiles above the ground in meters (default 0.03).
255
261
  */
256
262
 
257
263
  /**
@@ -237,4 +237,4 @@ export function hud(opts = {}) {
237
237
  };
238
238
  }
239
239
 
240
- export const handRolled = 'none: a score line is ordinary DOM that the game owns';
240
+ export const handRolled = [{ kind: 'hud', seen: 'projecting a world point to place a DOM marker / bar by hand', use: 'engine.hud: marker(target, opts), counter(id, opts), bar(id, opts)', code: /\.project\(\s*(?:e\.|engine\.)?camera\b/, gameplayOnly: true, quiet: /\bhud\.(?:marker|bar|counter)\b/, docRef: 'recipes/04-quests.md#1' }];
@@ -91,6 +91,7 @@ export function buildHeightfield(meshes, { cellSize = 0.5, outside = 0, maxCells
91
91
  if (y > top) {
92
92
  // the old top becomes a lower layer when it can be stood on, whatever lands on it: a bridge's bottom face stamped before its deck must not erase the road under it
93
93
  if (y - top > layerGap && U[k]) addLayer(k, top, T[k]);
94
+ else if (!up && U[k]) continue; // a downward face within layerGap above a walkable floor must not overwrite that floor
94
95
  H[k] = y; T[k] = curType; U[k] = up ? 1 : 0;
95
96
  } else if (top - y > layerGap && up) addLayer(k, y, curType);
96
97
  }
@@ -70,7 +70,7 @@ import { loadLevel, dropLoad, dropAsks, finishLoad, readScene, adoptScene, addCo
70
70
  import { warnOnce } from '../../core/base/validate.js';
71
71
  import { coded } from '../../core/base/errorHints.js';
72
72
  import { checkSaveFile } from '../../core/base/saveValues.js';
73
- import { whenTurnFree } from '../../core/saves/stateReplace.js';
73
+ import { whenTurnFree, addTurnHelper } from '../../core/saves/stateReplace.js';
74
74
 
75
75
  const STRINGS = {
76
76
  'zh-CN': { 'module.level': '关卡', 'level.loadFailed': '关卡加载失败:{url}', 'level.noScene': '关卡模块需要 url 或 scene 参数' },
@@ -101,7 +101,7 @@ function levelApi(st) {
101
101
  // each handle in its own try: one that throws (a trigger's onExit) must not leave the rest, nor the level root, standing; the unload finishes, the error is reported (engine.error in dev, console in release), and the unload goes on
102
102
  for (const h of [...st.removers.splice(0), ...st.walls.splice(0)]) { try { h.remove(); } catch (err) { reportError(st.e, err, 'level unload'); } }
103
103
  if (api.root && st.o.addToScene) st.e.remove(api.root); // full removal (geometries and materials shared by assets are not disposed)
104
- st.walkMeshes.length = 0; st.hf = api.heightfield = null; st.colliders = null; st.wallsIn.reset(); st.trimeshCache = null; api.markers = {}; api.root = null; st.current = null; st.version++; dropAsks(st);
104
+ st.walkMeshes.length = 0; st.hf = api.heightfield = null; st.colliders = null; st.wallsIn.reset(); st.trimeshCache = null; st.nodeSet.clear(); api.markers = {}; api.root = null; st.current = null; st.version++; dropAsks(st);
105
105
  st.done = true; st.playable = false; // nothing is loading now: a file still on its way is dropped, and no finishLoad would ever come for it (load sets it back)
106
106
  if (source !== undefined) {
107
107
  st.unloaded = true; // a level stood and left: only then is "no level" a fact worth saving (a session that never had one saves nothing, so its new-game state keeps a level loaded later)
@@ -169,6 +169,7 @@ export function level(opts = {}) {
169
169
  // the level is the module's: scene, walls, rays and level.track handles leave with it (unuse, replaces, a failed init). Before the part: handles go newest first, so the
170
170
  // part still reads the level as it leaves
171
171
  ctx.track({ remove: () => api.unload() });
172
+ ctx.track(addTurnHelper(e, 'loadLevel', (turn, source) => api.load(source, { turn })));
172
173
  // on load, switch back to the saved level (code-built scenes have no name, record null, no switch)
173
174
  // load returns a Promise: the save system waits for the new level (old level's trigger zones are already removed by unload) before reading player
174
175
  // position etc.
@@ -98,5 +98,6 @@ export function levelNodes(e, ctx, getRoot, getCurrent) {
98
98
  dispose(rec, o) { o.userData.unstatic?.remove(); o.removeFromParent(); },
99
99
  }));
100
100
  }
101
- return { take, giveBack, check, place };
101
+ const clear = () => { nodes.clear(); };
102
+ return { take, giveBack, check, place, clear };
102
103
  }
@@ -49,7 +49,7 @@ export function lightPool(opts = {}) {
49
49
  readParams('lightPool', LIGHT_POOL_PARAMS, opts);
50
50
  const { point = 8, spot = 0, shadows = 0, every = 0.1, fade = 0.3 } = opts;
51
51
  // what sources.js and slots.js share. timer: seconds since the last choice (Infinity: choose on the next frame); time: presentation seconds for flicker
52
- const pool = { e: null, api: null, sources: [], groups: [], tmp: new THREE.Vector3(), at: new THREE.Vector3(), timer: Infinity, time: 0, seq: 0, daylight: null, point, fade };
52
+ const pool = { e: null, api: null, sources: [], groups: [], tmp: new THREE.Vector3(), at: new THREE.Vector3(), timer: Infinity, time: 0, seq: 0, gen: 0, duskCount: 0, daylight: null, point, fade };
53
53
  let cut = false, offCut = null;
54
54
 
55
55
  const api = pool.api = {
@@ -58,7 +58,25 @@ export function lightPool(opts = {}) {
58
58
  /** Distance is measured from this Object3D / position; null (default) = the camera */
59
59
  focus: opts.focus ?? null,
60
60
  /** Register a light source at a position (Object3D: it follows that object) and return its handle { set(patch), remove(), light, weight } */
61
- add(position, o = {}) { return addSource(pool, position, o); },
61
+ add(position, o = {}) {
62
+ const h = addSource(pool, position, o);
63
+ const src = pool.sources[pool.sources.length - 1];
64
+ if (src.dusk !== null) pool.duskCount++;
65
+ const origSet = h.set, origRemove = h.remove;
66
+ h.set = patch => {
67
+ const had = src.dusk !== null;
68
+ const ret = origSet(patch);
69
+ const has = src.dusk !== null;
70
+ if (had !== has) pool.duskCount += has ? 1 : -1;
71
+ return ret;
72
+ };
73
+ h.remove = () => {
74
+ const wasRemoved = src.removed;
75
+ origRemove();
76
+ if (!wasRemoved && src.removed && src.dusk !== null) pool.duskCount--;
77
+ };
78
+ return h;
79
+ },
62
80
  /** @internal How the pool is used now: lights per kind, how many are lighting something, and which source each holds; describe().lightPool is the public read */
63
81
  get stats() {
64
82
  const out = { sources: pool.sources.length, lit: 0, slots: [] };
@@ -86,7 +104,7 @@ export function lightPool(opts = {}) {
86
104
  frame(dt) {
87
105
  pool.time += dt; // presentation seconds for flicker: keeps running while gameplay is frozen, like the picture
88
106
  pool.daylight = daylightOf(pool.e);
89
- if (pool.daylight === null && pool.sources.some(s => s.dusk !== null)) warnOnce(coded('lightpool-dusk', STRINGS.noDay));
107
+ if (pool.daylight === null && pool.duskCount > 0) warnOnce(coded('lightpool-dusk', STRINGS.noDay));
90
108
  // a camera cut (a view, a fixed shot): no fade, the picture is new anyway. Twice: the first pass frees the slots of sources left behind, the
91
109
  // second hands them over. Without it `shot --view` drew the lamps of the old spot, 1/30 s after the cut and 0.3 s before any fade would end
92
110
  if (cut) { cut = false; pool.timer = 0; for (let i = 0; i < 2; i++) { assign(pool); update(pool, fade); } return; }
@@ -94,7 +112,12 @@ export function lightPool(opts = {}) {
94
112
  update(pool, dt);
95
113
  },
96
114
  // newest first: sources sharing one material each saved the value they found, so the oldest restore comes last and leaves the true original (M12)
97
- dispose() { offCut?.remove(); for (let i = pool.sources.length - 1; i >= 0; i--) restoreGlow(pool.sources[i]); for (const L of api.lights) { L.removeFromParent(); L.target?.removeFromParent(); L.dispose(); } },
115
+ dispose() {
116
+ offCut?.remove();
117
+ for (let i = pool.sources.length - 1; i >= 0; i--) { const src = pool.sources[i]; restoreGlow(src); src.slot = null; }
118
+ for (const L of api.lights) { L.removeFromParent(); L.target?.removeFromParent(); L.dispose(); }
119
+ pool.sources.length = 0; pool.groups.length = 0; api.lights.length = 0; pool.duskCount = 0;
120
+ },
98
121
  describe() {
99
122
  const u = api.stats;
100
123
  return { lights: api.lights.length, lit: u.lit, sources: u.sources, shadows: Math.max(0, Math.min(shadows, point)) };
@@ -1,5 +1,6 @@
1
1
  // The real lights: groups of slots, each slot one three.js light, and how sources are chosen for them. pool is the state lightPool() shares with sources.js.
2
2
  import { engineOwned } from '../../core/scene/things.js';
3
+ import { setLightShadowAutoUpdate } from '../../render/threeCompat.js';
3
4
  import * as THREE from 'three';
4
5
  import { vec3 } from '../../core/base/math.js';
5
6
  import { litOf, setGlow } from './sources.js';
@@ -20,7 +21,7 @@ function score(pool, src, focus) {
20
21
  function release(pool, slot) {
21
22
  const src = slot.src;
22
23
  slot.src = null; slot.want = 0; slot.light.intensity = 0;
23
- if (slot.group.shadow) slot.light.shadow.autoUpdate = false; // dark: its shadow map is not rendered again until a source takes it
24
+ if (slot.group.shadow) setLightShadowAutoUpdate(slot.light, false); // dark: its shadow map is not rendered again until a source takes it
24
25
  if (src) { src.slot = null; if (!src.removed) setGlow(pool, src, 1); }
25
26
  }
26
27
 
@@ -28,24 +29,40 @@ function release(pool, slot) {
28
29
  export function assign(pool) {
29
30
  const { sources, groups, at } = pool, f = pool.api.focus ?? pool.e.camera;
30
31
  if (f.isObject3D) f.getWorldPosition(at); else vec3(f, at); // fresh (not last frame's matrix): the camera may have just moved
31
- for (const s of sources) { s.score = score(pool, s, at); if (!s.slot && s.dusk !== null) setGlow(pool, s, 1); } // an unlit lamp's stand-in follows daylight
32
- const taken = new Set();
33
- for (const g of groups) {
32
+ for (let i = 0; i < sources.length; i++) {
33
+ const s = sources[i];
34
+ s.score = score(pool, s, at);
35
+ if (!s.slot && s.dusk !== null) setGlow(pool, s, 1); // an unlit lamp's stand-in follows daylight
36
+ }
37
+ const takenGen = pool.gen = (pool.gen ?? 0) + 1;
38
+ for (let gi = 0; gi < groups.length; gi++) {
39
+ const g = groups[gi], slots = g.slots, cap = slots.length, pick = g.pick;
40
+ const chosenGen = ++pool.gen;
41
+ let k = 0;
34
42
  // a source fading out of another group's slot waits until it is released, so it never holds two lights
35
- const pick = sources.filter(s => s.score > 0 && !taken.has(s) && g.fits(s) && (!s.slot || s.slot.group === g))
36
- .sort((a, b) => b.score - a.score).slice(0, g.slots.length);
37
- const chosen = new Set(pick);
38
- for (const s of pick) taken.add(s);
39
- for (const slot of g.slots) slot.want = slot.src && chosen.has(slot.src) ? 1 : 0;
40
- const waiting = pick.filter(s => !s.slot);
41
- for (const slot of g.slots) {
42
- if (!waiting.length) break;
43
+ for (let i = 0; i < sources.length; i++) {
44
+ const s = sources[i];
45
+ if (!(s.score > 0) || s._taken === takenGen || !g.fits(s) || (s.slot && s.slot.group !== g)) continue;
46
+ if (k < cap || s.score > pick[k - 1].score) {
47
+ let j = k < cap ? k++ : k - 1;
48
+ while (j > 0 && s.score > pick[j - 1].score) { pick[j] = pick[j - 1]; j--; }
49
+ pick[j] = s;
50
+ }
51
+ }
52
+ for (let i = 0; i < k; i++) { const s = pick[i]; s._taken = takenGen; s._chosen = chosenGen; }
53
+ for (let i = 0; i < cap; i++) { const slot = slots[i]; slot.want = slot.src && slot.src._chosen === chosenGen ? 1 : 0; }
54
+ let wi = 0;
55
+ for (let i = 0; i < cap; i++) {
56
+ while (wi < k && pick[wi].slot) wi++;
57
+ if (wi >= k) break;
58
+ const slot = slots[i];
43
59
  if (slot.src && (slot.want || slot.w > 0)) continue; // kept by its source, or still fading the old one out: next time
44
60
  if (slot.src) release(pool, slot);
45
- const s = waiting.shift();
61
+ const s = pick[wi++];
46
62
  slot.src = s; slot.want = 1; s.slot = slot;
47
- if (g.shadow) { slot.light.shadow.autoUpdate = true; slot.light.shadow.needsUpdate = true; } // lit again: render its shadow map every frame
63
+ if (g.shadow) setLightShadowAutoUpdate(slot.light, true); // lit again: render its shadow map every frame
48
64
  }
65
+ for (let i = 0; i < k; i++) pick[i] = null;
49
66
  }
50
67
  }
51
68
 
@@ -77,13 +94,13 @@ export function update(pool, dt) {
77
94
  export function makeGroup(pool, type, shadow, n) {
78
95
  if (n <= 0) return;
79
96
  const allShadow = shadow && n >= pool.point; // no plain point lights: the shadow ones also take non-casting sources, so those never stay dark
80
- const g = { type, shadow, slots: [], fits: type === 'spot' ? s => s.type === 'spot' : shadow && !allShadow ? s => s.type === 'point' && s.castShadow : s => s.type === 'point' };
97
+ const g = { type, shadow, slots: [], pick: new Array(n).fill(null), fits: type === 'spot' ? s => s.type === 'spot' : shadow && !allShadow ? s => s.type === 'point' && s.castShadow : s => s.type === 'point' };
81
98
  for (let i = 0; i < n; i++) {
82
99
  const L = type === 'spot' ? new THREE.SpotLight(0xffffff, 0) : new THREE.PointLight(0xffffff, 0);
83
100
  L.name = `lightPool_${type}${shadow ? '_shadow' : ''}_${i}`;
84
101
  L.userData.fixedCount = true; // the light-count warning (core/inspect/lightWatch.js) leaves pooled lights out: their number never grows
85
102
  L.castShadow = shadow; // fixed at creation: a shadow count that changes recompiles too
86
- if (shadow) L.shadow.autoUpdate = false; // no source yet: no shadow passes
103
+ if (shadow) setLightShadowAutoUpdate(L, false); // no source yet: no shadow passes
87
104
  pool.e.scene.add(engineOwned('lightPool', L));
88
105
  if (L.isSpotLight) pool.e.scene.add(engineOwned('lightPool', L.target));
89
106
  pool.api.lights.push(L);
@@ -5,12 +5,12 @@
5
5
  // null: NPCs steer on their own), query (the path solver), version / revision (a new mesh / a changed one: caches of this module drop on them; they count per module, so another nav says nothing by its number).
6
6
  export default {
7
7
  name: 'nav',
8
+ options: {},
8
9
  api: ['findPath', 'point', 'reach', 'mesh', 'exportMesh'],
10
+ saves: {},
11
+ describe: true,
9
12
  fields: ['ready', 'crowd', 'query', 'navMesh', 'links', 'meshes', 'version', 'revision'],
13
+ probe: { state: null, emits: [], setup: [] },
10
14
  ops: [],
11
15
  events: [],
12
- saves: {},
13
- describe: true,
14
- options: {},
15
- probe: { setup: [], emits: [], state: null },
16
16
  };
@@ -27,6 +27,7 @@ import { navSearch, OPTS } from './navPath.js';
27
27
  import { sameFloor } from '../../core/scene/floor.js';
28
28
  import { warnOnce } from '../../core/base/validate.js';
29
29
  import { coded, codedError } from '../../core/base/errorHints.js';
30
+ import { reportError } from '../../core/base/errors.js';
30
31
  import { passesOf, passesThrough } from '../collision/grid.js';
31
32
 
32
33
  const NAV_PARAMS = keysSchema(['cellSize', 'agentRadius', 'agentHeight', 'maxClimb', 'maxSlope', 'tileSize', 'crowd', 'debug', 'maxObstacles', 'maxAgents', 'arrive', 'links']);
@@ -101,6 +102,8 @@ export function nav(opts = {}) {
101
102
  if (api.helper) e.remove(api.helper); // the debug mesh is built by us: remove it completely
102
103
  api.crowd?.destroy();
103
104
  for (const m of api.meshes.values()) { m.tileCache?.destroy(); m.navMesh?.destroy(); m.query?.destroy(); }
105
+ for (const p of processes.values()) p.destroy?.();
106
+ processes.clear();
104
107
  Object.assign(api, { navMesh: null, query: null, tileCache: null, crowd: null, helper: null });
105
108
  api.obstacles?.clear();
106
109
  api.meshes.clear(); api.meshes.set(BASE, api);
@@ -276,7 +279,7 @@ export function nav(opts = {}) {
276
279
  ({ agentRadius = mv.radius, agentHeight = mv.height, maxClimb = mv.stepHeight, maxSlope = mv.maxSlope } = opts);
277
280
  api.agent = { radius: agentRadius, height: agentHeight, maxClimb, maxSlope };
278
281
  api.radius = agentRadius; api.cells = cellsOf(agentRadius); api.meshes.set(BASE, api);
279
- ctx.track(e.events.on('level:loaded', () => { if (lib) build(); else pending = true; }));
282
+ ctx.track(e.events.on('level:loaded', () => { if (lib) build().catch(err => reportError(e, err, 'nav build', { soft: true })); else pending = true; }));
280
283
  ctx.track(e.events.on('level:unloaded', () => { pending = false; if (api.ready) api.dispose(); })); // every size was cut from the level that left
281
284
  pending = !!e.level?.ready; // installed after the level loaded: that event is gone, init builds the mesh
282
285
  // fetch and compile the WASM from install on, so it loads while the page builds the world instead of inside start()'s module inits
@@ -284,8 +287,9 @@ export function nav(opts = {}) {
284
287
  wasm.catch(() => {}); // a failure is reported by init (which awaits the same promise), not as an unhandled rejection here
285
288
  return api;
286
289
  },
287
- async init() {
290
+ async init(_e, ctx) {
288
291
  [lib, gen] = await wasm;
292
+ if (ctx?.signal?.aborted) return;
289
293
  if (pending) await build();
290
294
  },
291
295
  isReady() { return !!lib && !pending; },
@@ -33,9 +33,15 @@ export class NetClient {
33
33
  for (const s of this.subs || []) s.remove();
34
34
  this.t?.close?.();
35
35
  this.t = t; this.connected = false; this.synced = false; this.n = -1; this.inbox.length = 0;
36
+ this.pending.clear(); this.glides.clear();
36
37
  this.subs = [
37
38
  t.on('open', () => { this.connected = true; this.since = this.e.time.tick; this.e.events.emit('net:open', {}); }),
38
- t.on('close', () => { this.connected = false; this.synced = false; this.e.events.emit('net:close', {}); }),
39
+ t.on('close', () => {
40
+ this.connected = false; this.synced = false;
41
+ const dropped = [...this.pending]; this.pending.clear();
42
+ for (const [seq, name] of dropped) this.e.events.emit('net:result', { seq, name, ok: false, code: 'offline', value: undefined, tick: this.e.time.tick });
43
+ this.e.events.emit('net:close', {});
44
+ }),
39
45
  t.on('message', m => { if (m && typeof m === 'object') { this.stats.in++; this.inbox.push(m); } }),
40
46
  ];
41
47
  }
@@ -48,7 +54,11 @@ export class NetClient {
48
54
  const c = this.e.ops.can(d.name, args, opts);
49
55
  if (!c.ok) return c;
50
56
  const seq = ++this.seq, out = {};
51
- for (const k in args) out[k] = typeof args[k] === 'string' ? this.map.toHost(args[k]) : args[k]; // 'player' here means this client's actor there
57
+ for (const k in args) {
58
+ const spec = d.args?.[k], ty = typeof spec === 'string' ? spec.replace(/\?$/, '') : spec?.type;
59
+ const isActorRef = ty === 'id' || ty === 'actor' || (!d.args && (k === 'id' || k === 'actor' || k === 'owner'));
60
+ out[k] = typeof args[k] === 'string' && isActorRef ? this.map.toHost(args[k]) : args[k]; // 'player' here means this client's actor there
61
+ }
52
62
  this.pending.set(seq, d.name);
53
63
  this.send({ t: 'op', seq, name: d.name, args: out });
54
64
  return { ok: true, pending: true, seq };
@@ -65,7 +75,8 @@ export class NetClient {
65
75
  handle(m) {
66
76
  const e = this.e;
67
77
  if (m.t === 's') {
68
- this.actor = m.you; this.map = idMap(m.you); this.every = m.every ?? this.every;
78
+ this.actor = m.you; this.map = idMap(m.you);
79
+ if (typeof m.every === 'number' && Number.isFinite(m.every) && m.every > 0) this.every = m.every;
69
80
  this.glides.clear();
70
81
  this.apply(m.parts, true);
71
82
  this.n = m.n; this.synced = true; this.stats.snapshots++;
@@ -100,7 +111,7 @@ export class NetClient {
100
111
  if (key === 'world' && !this.e.world) continue;
101
112
  if (key === 'containers' && !this.e.inventory) continue;
102
113
  applyPart(this.e, key, parts[key], full, opts);
103
- if (key === 'world') for (const hostId in full ? parts[key] : parts[key].set ?? {}) this.hold(this.map.toLocal(hostId));
114
+ if (key === 'world' && parts[key] && typeof parts[key] === 'object') for (const hostId in full ? parts[key] : parts[key].set ?? {}) this.hold(this.map.toLocal(hostId));
104
115
  }
105
116
  }
106
117
  /**
@@ -128,13 +139,15 @@ export class NetClient {
128
139
  if (!this.synced && this.connected && this.e.time.tick - this.since >= ASK_EVERY) { this.since = this.e.time.tick; this.send({ t: 'resync' }); }
129
140
  if (!this.glides.size) return;
130
141
  const W = this.e.world;
131
- for (const [id, g] of this.glides) {
132
- if (!W.get(id)) { this.glides.delete(id); continue; }
133
- g.t += dt;
134
- const k = Math.min(1, g.t / g.dur);
135
- W.move(id, { x: g.from.x + (g.to.x - g.from.x) * k, y: g.from.y + (g.to.y - g.from.y) * k, z: g.from.z + (g.to.z - g.from.z) * k });
136
- if (k >= 1) this.glides.delete(id);
137
- }
142
+ this.e.ops.allow(() => {
143
+ for (const [id, g] of this.glides) {
144
+ if (!W.get(id)) { this.glides.delete(id); continue; }
145
+ g.t += dt;
146
+ const k = Math.min(1, g.t / g.dur);
147
+ W.move(id, { x: g.from.x + (g.to.x - g.from.x) * k, y: g.from.y + (g.to.y - g.from.y) * k, z: g.from.z + (g.to.z - g.from.z) * k });
148
+ if (k >= 1) this.glides.delete(id);
149
+ }
150
+ });
138
151
  }
139
152
  dispose() {
140
153
  for (const s of this.subs) s.remove();