castle-web-cli 0.4.230 → 0.4.232

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 (92) hide show
  1. package/dist/castle-host/host.js +81 -0
  2. package/dist/devSaveStorage.d.ts +36 -0
  3. package/dist/devSaveStorage.js +469 -0
  4. package/dist/devSessionChild.js +22 -12
  5. package/dist/devSessionServer.js +8 -2
  6. package/dist/devSessionStorage.d.ts +9 -0
  7. package/dist/devSessionStorage.js +66 -1
  8. package/dist/init.js +1 -1
  9. package/dist/serve.js +5 -1
  10. package/dist/serverBundle.js +5 -3
  11. package/kits/base/castle.json +1 -1
  12. package/kits/base/sdk/README.md +148 -1
  13. package/kits/base/sdk/castle.d.ts +4 -0
  14. package/kits/base/sdk/castle.js +2 -0
  15. package/kits/base/sdk/commands.d.ts +15 -0
  16. package/kits/base/sdk/multiplayer.js +52 -4
  17. package/kits/base/sdk/save.d.ts +197 -0
  18. package/kits/base/sdk/save.js +525 -0
  19. package/kits/base/sdk/saveCoordinator.d.ts +39 -0
  20. package/kits/base/sdk/saveCoordinator.js +252 -0
  21. package/kits/base/sdk/server/storage.d.ts +3 -2
  22. package/kits/base/sdk/server/storage.js +25 -5
  23. package/kits/base/sdk/server/wrapper.d.ts +4 -0
  24. package/kits/base/sdk/server/wrapper.js +2 -0
  25. package/kits/base/sdk/store.d.ts +3 -2
  26. package/kits/base/sdk/store.js +5 -0
  27. package/kits/hub-game/CLAUDE.md +29 -4
  28. package/kits/hub-game/code/client/avatar.js +39 -0
  29. package/kits/hub-game/code/client/chat.js +12 -0
  30. package/kits/hub-game/code/client/chrome.js +237 -13
  31. package/kits/hub-game/code/client/grab.js +166 -7
  32. package/kits/hub-game/code/client/hats.js +26 -0
  33. package/kits/hub-game/code/client/hookLayer.js +36 -3
  34. package/kits/hub-game/code/client/hudClear.js +126 -0
  35. package/kits/hub-game/code/client/state.js +35 -1
  36. package/kits/hub-game/code/client/talk.js +10 -36
  37. package/kits/hub-game/code/client/tiers.js +505 -0
  38. package/kits/hub-game/code/client/together.js +144 -4
  39. package/kits/hub-game/code/client/wear.js +96 -14
  40. package/kits/hub-game/code/server/actors.js +5 -0
  41. package/kits/hub-game/code/server/grab.js +299 -13
  42. package/kits/hub-game/code/server/hub.js +162 -7
  43. package/kits/hub-game/code/server/manifest.js +80 -8
  44. package/kits/hub-game/code/server/npcs.js +21 -33
  45. package/kits/hub-game/code/server/party.js +75 -6
  46. package/kits/hub-game/code/server/say.js +8 -2
  47. package/kits/hub-game/code/server/wear.js +116 -11
  48. package/kits/hub-game/code/systems/hub.js +386 -21
  49. package/kits/hub-game/docs/contract.md +285 -19
  50. package/kits/hub-game/package.json +1 -1
  51. package/kits/hub-game/scripts/test-chat.mjs +32 -0
  52. package/kits/hub-game/scripts/test-grab-client.mjs +511 -0
  53. package/kits/hub-game/scripts/test-grab.mjs +857 -3
  54. package/kits/hub-game/scripts/test-hats.mjs +229 -0
  55. package/kits/hub-game/scripts/test-hub-trip.mjs +721 -0
  56. package/kits/hub-game/scripts/test-hud-clear.mjs +676 -0
  57. package/kits/hub-game/scripts/test-manifest.mjs +122 -1
  58. package/kits/hub-game/scripts/test-npcs.mjs +34 -24
  59. package/kits/hub-game/scripts/test-party.mjs +108 -4
  60. package/kits/hub-game/scripts/test-say.mjs +59 -2
  61. package/kits/hub-game/scripts/test-tiers.mjs +854 -0
  62. package/kits/hub-game/scripts/test-together.mjs +33 -1
  63. package/kits/hub-game/scripts/test-try-on.mjs +940 -0
  64. package/kits/physics-2d/CLAUDE.md +2 -0
  65. package/kits/physics-2d/castle.json +2 -2
  66. package/kits/physics-2d/engine/scene.js +127 -0
  67. package/kits/physics-2d/package.json +1 -1
  68. package/kits/physics-2d/scripts/test-skip-unchanged.mjs +298 -0
  69. package/kits/physics-3d/CLAUDE.md +531 -0
  70. package/kits/physics-3d/behaviors/Player.jsx +437 -3
  71. package/kits/physics-3d/castle.json +3 -3
  72. package/kits/physics-3d/docs/pxmodel-format.md +4 -0
  73. package/kits/physics-3d/engine3d/Scene3DPlayer.jsx +33 -1
  74. package/kits/physics-3d/engine3d/actornode.js +253 -0
  75. package/kits/physics-3d/engine3d/nearshadows.js +600 -0
  76. package/kits/physics-3d/engine3d/optimize.js +49 -0
  77. package/kits/physics-3d/engine3d/orbitinput.js +277 -0
  78. package/kits/physics-3d/engine3d/unchanged.js +153 -0
  79. package/kits/physics-3d/engine3d/world3d.js +525 -11
  80. package/kits/physics-3d/package.json +1 -1
  81. package/kits/physics-3d/scripts/Player.before-orbit.mjs +310 -0
  82. package/kits/physics-3d/scripts/Scene3DPlayer.before-orbit.jsx +337 -0
  83. package/kits/physics-3d/scripts/test-camera-follow.mjs +543 -0
  84. package/kits/physics-3d/scripts/test-camera-orbit.mjs +2105 -0
  85. package/kits/physics-3d/scripts/test-drop-empty-parts.mjs +787 -0
  86. package/kits/physics-3d/scripts/test-near-shadows.mjs +1073 -0
  87. package/kits/physics-3d/scripts/test-static-actors.mjs +667 -0
  88. package/kits/physics-3d/scripts/test-static-passes.mjs +459 -0
  89. package/kits/physics-3d/scripts/test-static-physics.mjs +128 -0
  90. package/kits/physics-3d/scripts/test-steady-hover.mjs +633 -0
  91. package/kits/physics-3d/systems/physics3d.js +273 -9
  92. package/package.json +1 -1
@@ -0,0 +1,600 @@
1
+ // Scenes that set `"engine": { "shadows": { "distance": <metres> } }`
2
+ //
3
+ // The sun's shadow camera is a fixed box (world3d.js `addLights`), so every
4
+ // caster under it is drawn a second time each frame wherever the player is,
5
+ // and a scene larger than the box has no shadows outside it. For a scene that
6
+ // asks, the sun's shadows are drawn only where they can be seen: out to
7
+ // `distance` metres from the camera.
8
+ //
9
+ // The invariant:
10
+ //
11
+ // The scene's sun, its shadow object, its shadow camera, its map and its
12
+ // target are never written by this mode. What the mode needs is its own
13
+ // objects, attached only for the duration of one renderer.render call
14
+ // inside try/finally. Outside that call the world is as main leaves it, so
15
+ // there is nothing to restore on a scene change, a throw, a dispose or a
16
+ // keyless frame.
17
+ //
18
+ // Who the key is for:
19
+ //
20
+ // The key is for a scene whose deck leaves the renderer's shadow settings
21
+ // and the drawing of the world to the engine. A deck must not set the key if
22
+ // any of its code, in any scene played in the same world, changes
23
+ // renderer.shadowMap.type, .enabled, .autoUpdate or .needsUpdate after the
24
+ // world is made; calls renderer.render or the composer itself, inside or
25
+ // between the engine's frames; calls renderWorld from inside a frame; or
26
+ // gives the world's renderer to another world. In a deck that does, shadows
27
+ // may be drawn wrongly with the key, and three.js's shadow bookkeeping for
28
+ // the sun's own map (its filter, its size) may differ from a world that
29
+ // never had the key until the world is disposed. A deck that never sets the
30
+ // key is unaffected whatever it does.
31
+ //
32
+ // (three.js keeps the shadow pass's state, the type it last drew with and the
33
+ // frustum it culls by, inside the renderer, where the engine can neither read
34
+ // it nor put it back; nothing in the kits touches any of the above after
35
+ // `makeWorld3D`.) Nothing of the renderer's is ever written by the mode.
36
+ //
37
+ // Within that, the mode draws a frame only when all of these hold; otherwise
38
+ // the frame is drawn exactly as without the key (the sun's own shadow,
39
+ // three.js's own culling), and nothing of the mode's stays allocated. They are
40
+ // cheap protection, looked at every frame, not promises about a deck outside
41
+ // the condition above. After any `renderWorld` call returns, either the mode
42
+ // drew that frame or nothing of the mode's is allocated: every way out of the
43
+ // mode (a frame drawn plain for any term, a re-entry, a throw, a dispose)
44
+ // frees its map, and a blur map were there one, at that moment (`leaveMode`):
45
+ //
46
+ // 1. the scene now playing asked, with a finite distance above 0, and the
47
+ // world is not being disposed;
48
+ // 2. `renderWorld` was not entered from inside another `renderWorld` of this
49
+ // world that had anything of the mode's to do, keyed or not, and no frame
50
+ // of this world has been entered that way before: the call inside is drawn
51
+ // plain, the sun has its own shadow back before that call draws, the mode
52
+ // is off for this world until the world is disposed
53
+ // (`world.nearShadows.off`), and the frame that was re-entered, whose map
54
+ // is freed under it, may have wrong or missing shadows, that once;
55
+ // 3. read at the start of the frame, `renderer.shadowMap.type` is
56
+ // PCFSoftShadowMap and `.enabled` and `.autoUpdate` are on, which is how
57
+ // the engine makes the renderer; and the frame before this one was also a
58
+ // frame with the key, found the same and was drawn to the end
59
+ // (`world.nearShadows.lastType`). So the first frame with the key, after a
60
+ // load or after any frame without it, is drawn plain, and three.js
61
+ // allocates and configures the sun's own map as it would have; and so is
62
+ // the frame after one that threw, and after one the mode drew that ended
63
+ // with no map on its shadow;
64
+ // 4. the sun (`world.sun`, the light world3d.js fits the bias of) is still a
65
+ // child of the scene, is the first directional light there that casts a
66
+ // shadow, has `castShadow` on, is visible and on the camera's layers, and
67
+ // its own shadow is a directional light's, has `autoUpdate` on and has its
68
+ // map. Looked at every frame: a sun removed or replaced means plain
69
+ // frames;
70
+ // 5. the camera is a perspective camera, and the sun's own box and map size
71
+ // give a texel size: its shadow camera has zoom 1 and no view offset.
72
+ //
73
+ // All of it happens inside one outermost try/finally per `renderWorld` call,
74
+ // counted on the world (`world.nearShadows.depth`): deciding the terms,
75
+ // fitting the bias, allocating, swapping, rendering, leaving, disposing. A
76
+ // call that arrives while the count is up draws plain, puts the mode off and
77
+ // makes nothing. The finally establishes the postcondition itself rather than
78
+ // trusting the paths to it: unless the mode drew this frame to the end, on a
79
+ // world not disposed, with the mode not off and a map on its shadow, nothing
80
+ // of the mode's is allocated and the sun has its own shadow. Its order makes
81
+ // that hold through a `dispose` listener that throws: first the sun gets its
82
+ // own shadow back (an assignment, which calls no one), then what is freed is
83
+ // detached and only then disposed, and looked at again after the callbacks;
84
+ // the count comes down in a finally of its own that nothing skips. A world
85
+ // that has no mode state and is playing a scene without the key does not come
86
+ // here at all: `renderWorld` runs its two statements (fit the bias, render) as
87
+ // it always did.
88
+ //
89
+ // The one write is `sun.shadow = <the mode's own shadow>` round the render and
90
+ // `sun.shadow = <the sun's own>` after it, in a `finally`, and only by the
91
+ // frame that put it there: a frame that finds the world disposed, its state
92
+ // replaced or itself re-entered touches nothing, because whoever did that has
93
+ // already given the sun its own shadow back. The mode's own shadow
94
+ // (`NearShadow`, a DirectionalLightShadow) has its own camera, map, matrix and
95
+ // frustum:
96
+ //
97
+ // - Its box is round the smallest sphere that holds the camera's view out to
98
+ // `distance`, so it is one size whichever way the camera turns, and sits a
99
+ // whole number of shadow-map texels along each of its axes, so a shadow's
100
+ // edge does not crawl as the camera moves. It looks along the sun's own
101
+ // direction, from as far as the sun is from its target, with the sun's own
102
+ // near and far: the light itself does not move.
103
+ // - Its texels are exactly the size the sun's own are (its box over its map
104
+ // size, read each frame), so the box is `map size x texel`, and the bias
105
+ // world3d.js fits to the sun's own shadow is the right one for it and is
106
+ // copied. A map that size is never larger than the sun's own in area nor
107
+ // than the renderer's largest texture on a side: a `distance` that would
108
+ // need more is drawn as the largest distance that fits.
109
+ // - The frustum it hands three.js to cull casters with is its box narrowed to
110
+ // the view's outline as the sun sees it out to `distance`, pushed out by
111
+ // everything three.js's shader moves a shadow lookup by (`lookupMargin`):
112
+ // the normal bias and the soft filter's taps. So every caster
113
+ // whose shadow can land on something the view sees within `distance` is
114
+ // drawn into the map, if it is inside the camera's depth range: shadows
115
+ // are complete out to `distance` for casters within the sun's own near and
116
+ // far along the light, measured from the mode's camera, which stands as
117
+ // far from the middle of the view's sphere (taken along the light to the
118
+ // height of the sun's target) as the sun does from its target. For the
119
+ // engine's sun (19.9 m from its target, near 0.5, far 50) that is casters
120
+ // up to 19.4 m toward the sun and 30.1 m away from it, from the ground
121
+ // under the middle of the view: what the sun's own camera draws for a view
122
+ // round its target, where a caster 25 m up the light is not drawn either.
123
+ // Farther
124
+ // points may or may not be shadowed: the box reaches past the outline, and
125
+ // a caster kept for a near point shadows far ones too. Nothing cuts
126
+ // receivers off at `distance`.
127
+ //
128
+ // three.js keeps nothing per shadow object: the shadow pass reads
129
+ // `light.shadow` (its map, `updateMatrices`, `getFrustum`) and the light
130
+ // uniforms are refilled from `light.shadow` on every render (WebGLLights
131
+ // `setup`: intensity, bias, normal bias, radius, the map-size vector, the map's
132
+ // texture and the matrix, into slots kept per light). So after the swap back
133
+ // the next render reads the sun's own again and nothing of this one is used.
134
+ // On a frame the mode draws, three.js does not draw the sun's own shadow, so
135
+ // its map and its shadow camera's matrices stay as the last plain frame left
136
+ // them.
137
+ //
138
+ // What is kept is `world.nearShadows`: the mode's shadow (`shadow`, only from
139
+ // a frame the mode drew to the next), the shadow type the frame before found
140
+ // if it was a frame with the key drawn to the end (`lastType`), whether the
141
+ // mode is off for this world (`off`), how deep in
142
+ // `renderWorld` calls the world is (`depth`) and, for the length of a frame
143
+ // the mode is drawing only, the sun and the shadow that is the sun's own
144
+ // (`frame`). A frame without the key drops it, all but `off`; `disposeWorld`
145
+ // drops it all. The map, and a
146
+ // blur map were there ever one, are taken off the shadow before they are
147
+ // disposed, once.
148
+ import * as THREE from 'three';
149
+
150
+ // How far from the point it shades three.js's shader may read the shadow map,
151
+ // across the light: what the outline is pushed out by and the box made wider
152
+ // by. For a directional light under PCFSoft (three.js r180, ShaderChunk
153
+ // shadowmap_vertex and shadowmap_pars_fragment `getShadow`):
154
+ // - the lookup is made at `position + normal * shadowNormalBias`, the normal
155
+ // of unit length, so up to |normalBias| metres off in any direction;
156
+ // - the filter snaps the lookup down to a texel (up to one texel) and reads
157
+ // from one texel before to two after, each tap the nearest texel (half a
158
+ // texel more): under three and a half texels, taken as FILTER_TEXELS;
159
+ // - `shadowBias` moves the lookup in depth only, and `shadowRadius` is not
160
+ // used by PCFSoft: neither moves it across the light.
161
+ // `normalBias` is the value drawn with that frame (the sun's own, copied).
162
+ const FILTER_TEXELS = 4;
163
+
164
+ function lookupMargin(texel, normalBias) {
165
+ return FILTER_TEXELS * texel + Math.abs(normalBias);
166
+ }
167
+ // The sphere's radius is rounded up to a whole number of these (metres), so a
168
+ // window being dragged to a new shape does not allocate a map every frame.
169
+ const RADIUS_STEP = 2;
170
+
171
+ // The sun's frustum, narrowed: a sphere must also be inside each `sides`
172
+ // half-space (`nx, ny, nz, limit` four at a time: outside when the centre is
173
+ // more than its radius past the limit along the normal).
174
+ class SliceFrustum extends THREE.Frustum {
175
+ constructor() {
176
+ super();
177
+ this.sides = [];
178
+ }
179
+
180
+ intersectsSphere(sphere) {
181
+ if (!super.intersectsSphere(sphere)) return false;
182
+ const { x, y, z } = sphere.center;
183
+ const sides = this.sides;
184
+ for (let i = 0; i < sides.length; i += 4) {
185
+ if (sides[i] * x + sides[i + 1] * y + sides[i + 2] * z - sides[i + 3] > sphere.radius) return false;
186
+ }
187
+ return true;
188
+ }
189
+ }
190
+
191
+ const CORNERS = [
192
+ [-1, -1],
193
+ [1, -1],
194
+ [1, 1],
195
+ [-1, 1],
196
+ ];
197
+ const eye = new THREE.Vector3();
198
+ const aim = new THREE.Vector3();
199
+ const toSun = new THREE.Vector3();
200
+ const point = new THREE.Vector3();
201
+ const axisX = new THREE.Vector3();
202
+ const axisY = new THREE.Vector3();
203
+ const axisZ = new THREE.Vector3();
204
+
205
+ // The engine's own shadow: made on the first frame of a scene with the key,
206
+ // so a deck that never asks makes nothing. three.js does not export the
207
+ // class by name; a light's shadow has it.
208
+ let NearShadowClass = null;
209
+
210
+ function makeNearShadow() {
211
+ NearShadowClass ??= defineNearShadow(new THREE.DirectionalLight().shadow.constructor);
212
+ return new NearShadowClass();
213
+ }
214
+
215
+ function defineNearShadow(DirectionalLightShadow) {
216
+ return class NearShadow extends DirectionalLightShadow {
217
+ constructor() {
218
+ super();
219
+ this.slice = new SliceFrustum();
220
+ // What a frame is fitted to (`fit`): the view camera, the distance drawn,
221
+ // the view's corners one metre ahead, how far along the view the sphere's
222
+ // middle is, the texel's size and the outline's margin.
223
+ this.view = null;
224
+ this.reach = 0;
225
+ this.lens = [];
226
+ this.along = 0;
227
+ this.texel = [0, 0];
228
+ this.margin = 0;
229
+ // Where `updateMatrices` puts the camera: the base class reads a light's
230
+ // and its target's world position, and is given these.
231
+ this.stand = { matrixWorld: new THREE.Matrix4(), target: { matrixWorld: new THREE.Matrix4() } };
232
+ }
233
+
234
+ getFrustum() {
235
+ this.slice.copy(super.getFrustum());
236
+ return this.slice;
237
+ }
238
+
239
+ // Called by three.js in the shadow pass, after the scene's and the view
240
+ // camera's world matrices are up to date. `light` is read, never written.
241
+ updateMatrices(light) {
242
+ const view = this.view;
243
+ if (!view) {
244
+ this.slice.sides.length = 0;
245
+ super.updateMatrices(light);
246
+ return;
247
+ }
248
+ eye.setFromMatrixPosition(light.matrixWorld);
249
+ aim.setFromMatrixPosition(light.target.matrixWorld);
250
+ toSun.subVectors(eye, aim);
251
+ // The camera's own axes, as three.js makes them from that direction.
252
+ this.place(aim, toSun);
253
+ axisX.setFromMatrixColumn(this.camera.matrixWorld, 0);
254
+ axisY.setFromMatrixColumn(this.camera.matrixWorld, 1);
255
+ axisZ.setFromMatrixColumn(this.camera.matrixWorld, 2);
256
+
257
+ // The sphere's middle, a whole number of texels along each axis, then slid
258
+ // along the sun's direction to the height the sun's target is at, which
259
+ // leaves the depth range where the sun's own has it.
260
+ const [stepX, stepY] = this.texel;
261
+ point.set(0, 0, -this.along * this.reach).applyMatrix4(view.matrixWorld);
262
+ const u = Math.round(point.dot(axisX) / stepX) * stepX;
263
+ const v = Math.round(point.dot(axisY) / stepY) * stepY;
264
+ const depth = point.dot(axisZ);
265
+ point.copy(axisX).multiplyScalar(u).addScaledVector(axisY, v);
266
+ const level = Math.abs(axisZ.y) > 1e-3;
267
+ point.addScaledVector(axisZ, level ? (aim.y - point.y) / axisZ.y : depth);
268
+ this.place(point, toSun);
269
+
270
+ // The view's outline as the sun sees it: the camera and its four corners
271
+ // `reach` ahead.
272
+ const points = [[eye.setFromMatrixPosition(view.matrixWorld).dot(axisX), eye.dot(axisY)]];
273
+ for (const [x, y] of this.lens) {
274
+ point.set(x * this.reach, y * this.reach, -this.reach).applyMatrix4(view.matrixWorld);
275
+ points.push([point.dot(axisX), point.dot(axisY)]);
276
+ }
277
+ outlineSides(this.slice.sides, points, axisX, axisY, this.margin);
278
+ }
279
+
280
+ // The camera at `target + offset` looking at `target`, and the matrices that
281
+ // follow, by the base class.
282
+ place(target, offset) {
283
+ this.stand.target.matrixWorld.makeTranslation(target.x, target.y, target.z);
284
+ this.stand.matrixWorld.makeTranslation(target.x + offset.x, target.y + offset.y, target.z + offset.z);
285
+ super.updateMatrices(this.stand);
286
+ }
287
+
288
+ // Takes the map (and a blur map, which only another shadow type would
289
+ // have made) off before disposing it, so nothing that runs from its
290
+ // `dispose` finds it here.
291
+ release() {
292
+ const { map, mapPass } = this;
293
+ this.map = null;
294
+ this.mapPass = null;
295
+ // Both are off the shadow before either is disposed, and a `dispose`
296
+ // listener that throws does not keep the other from being freed.
297
+ try {
298
+ if (map) map.dispose();
299
+ } finally {
300
+ if (mapPass) mapPass.dispose();
301
+ }
302
+ }
303
+ };
304
+ }
305
+
306
+ // The sun, if it is one the mode can draw for this frame (term 4).
307
+ function sunOf(world) {
308
+ const sun = world.sun;
309
+ if (!sun || sun.parent !== world.scene || sun.castShadow !== true || sun.isDirectionalLight !== true) return null;
310
+ if (!ownShadowIsDrawn(sun.shadow)) return null;
311
+ if (sun.visible !== true || world.scene.visible !== true || !sun.layers.test(world.camera.layers)) return null;
312
+ return world.scene.children.find((child) => child.isDirectionalLight && child.castShadow) === sun ? sun : null;
313
+ }
314
+
315
+ // Whether the sun's own shadow is one three.js draws every frame and has
316
+ // drawn: a directional light's, due an update, with its map. (One with no map
317
+ // yet would be given it by a plain frame.)
318
+ function ownShadowIsDrawn(shadow) {
319
+ return shadow?.isDirectionalLightShadow === true && shadow.autoUpdate === true && Boolean(shadow.map);
320
+ }
321
+
322
+ // Term 3, read at the start of a frame and never written: the shadow type, if
323
+ // the renderer's shadow settings are the ones the engine made it with, else
324
+ // undefined.
325
+ function shadowSettings(world) {
326
+ const pass = world.renderer?.shadowMap;
327
+ return pass?.enabled === true && pass.autoUpdate === true && pass.type === THREE.PCFSoftShadowMap ? pass.type : undefined;
328
+ }
329
+
330
+ // The frame the mode is drawing, if there is one, is over for it and the sun
331
+ // has its own shadow back. Assignments only: nothing here calls out.
332
+ function giveBack(state) {
333
+ const frame = state.frame;
334
+ state.frame = null;
335
+ if (frame && frame.sun.shadow === frame.near) frame.sun.shadow = frame.own;
336
+ }
337
+
338
+ // The one way out of the mode, for every reason and at the moment it happens:
339
+ // the sun has its own shadow back and the mode's shadow and its maps are
340
+ // freed. Everything is detached before anything is disposed, so the state
341
+ // refers to none of it when a map's `dispose` is dispatched, whatever that
342
+ // listener does, throwing included.
343
+ function leaveMode(state) {
344
+ giveBack(state);
345
+ const shadow = state.shadow;
346
+ state.shadow = null;
347
+ if (!shadow) return;
348
+ shadow.view = null;
349
+ shadow.release();
350
+ }
351
+
352
+ // For `disposeWorld`: nothing of the mode's is kept, and the sun has its own
353
+ // shadow before this returns, called from inside a frame the mode is drawing
354
+ // or not.
355
+ export function dropNearShadows(world) {
356
+ const state = world.nearShadows;
357
+ if (!state) return;
358
+ world.nearShadows = null;
359
+ state.lastType = undefined;
360
+ leaveMode(state);
361
+ }
362
+
363
+ // One `renderWorld` of a world that has mode state or whose scene asked for
364
+ // `distance` (0: it did not). `fitBias` is world3d.js fitting the bias of the
365
+ // sun's own shadow and `render` its render call; a plain frame is the two, as
366
+ // without the key.
367
+ export function renderWithNearShadows(world, distance, fitBias, render) {
368
+ const state = world.nearShadows ?? newState(world);
369
+ if (state.depth > 0) {
370
+ // Term 2: entered from inside another call. Plain, and nothing is made.
371
+ state.off = true;
372
+ state.lastType = undefined;
373
+ leaveMode(state);
374
+ fitBias();
375
+ render();
376
+ return;
377
+ }
378
+ state.depth = 1;
379
+ let drawn = false;
380
+ let returned = false;
381
+ try {
382
+ try {
383
+ drawn = guardedFrame(world, state, distance, fitBias, render);
384
+ returned = true;
385
+ } finally {
386
+ // First what must happen whatever follows and cannot call out: the sun
387
+ // has its own shadow. Then what may run someone else's code.
388
+ const frame = state.frame;
389
+ giveBack(state);
390
+ // A frame that threw is no frame before the next.
391
+ if (!returned) state.lastType = undefined;
392
+ settle(world, state, distance, drawn && returned ? frame : null);
393
+ }
394
+ } finally {
395
+ // Nothing skips this: a `dispose` listener that throws above does not
396
+ // leave the world counted as inside a call.
397
+ state.depth = 0;
398
+ }
399
+ }
400
+
401
+ function newState(world) {
402
+ world.nearShadows = { shadow: null, lastType: undefined, off: false, frame: null, depth: 0 };
403
+ return world.nearShadows;
404
+ }
405
+
406
+ // The frame, inside the guard. True when the mode drew it.
407
+ function guardedFrame(world, state, distance, fitBias, render) {
408
+ if (!(distance > 0) || world.disposed === true || state.off) {
409
+ leaveMode(state);
410
+ fitBias();
411
+ render();
412
+ return false;
413
+ }
414
+ // Term 3: whatever this frame turns out to be, it is the frame before the
415
+ // next only once it has been drawn to the end.
416
+ const type = shadowSettings(world);
417
+ const due = type !== undefined && state.lastType === type;
418
+ state.lastType = undefined;
419
+ fitBias();
420
+ const drawn = due && nearFrame(world, state, distance, render);
421
+ if (!drawn) {
422
+ leaveMode(state);
423
+ render();
424
+ }
425
+ if (!state.off) state.lastType = type;
426
+ return drawn;
427
+ }
428
+
429
+ // Draws the frame with the mode's own shadow on the sun, if the terms hold.
430
+ // False when they do not and nothing has been drawn.
431
+ function nearFrame(world, state, distance, render) {
432
+ const sun = sunOf(world);
433
+ if (!sun) return false;
434
+ state.shadow ??= makeNearShadow();
435
+ const frame = { sun, own: sun.shadow, near: state.shadow };
436
+ state.frame = frame;
437
+ // Fitting may free a map of the wrong size, whose `dispose` runs someone
438
+ // else's code: a call from there has left the mode.
439
+ if (!fit(frame.near, frame.own, world, distance) || state.frame !== frame) return false;
440
+ sun.shadow = frame.near;
441
+ render();
442
+ return true;
443
+ }
444
+
445
+ // The end of every outermost call, after the sun has its own shadow back.
446
+ // `frame` is the frame the mode drew to the end, if it did. The mode keeps its
447
+ // shadow for the next frame only if it drew this one and is still this
448
+ // world's, not off, with a map three.js drew into. Otherwise the mode is
449
+ // left, and left again should a `dispose` callback have found a way to leave
450
+ // something, or thrown.
451
+ function settle(world, state, distance, frame) {
452
+ if (frame && keeps(world, state, frame)) {
453
+ frame.near.view = null;
454
+ return;
455
+ }
456
+ // A frame the mode drew and is not keeping is no frame before the next.
457
+ if (frame) state.lastType = undefined;
458
+ try {
459
+ leaveMode(state);
460
+ } finally {
461
+ if (state.shadow || state.frame) leaveMode(state);
462
+ // A scene without the key, with nothing to remember: the world is as one
463
+ // that never had the mode, and its next frame is main's.
464
+ if (!(distance > 0) && !state.off && world.nearShadows === state) world.nearShadows = null;
465
+ }
466
+ }
467
+
468
+ // Whether the frame the mode has just drawn leaves the mode in place.
469
+ function keeps(world, state, frame) {
470
+ if (state.off || world.disposed === true || world.nearShadows !== state) return false;
471
+ return state.shadow === frame.near && Boolean(frame.near.map);
472
+ }
473
+
474
+ // The frame's numbers on the mode's own shadow, read from the sun's own, the
475
+ // view camera's lens and the renderer's limit. False when there is nothing
476
+ // sound to fit to, and the frame is drawn with the sun's own shadow.
477
+ function fit(near, own, world, distance) {
478
+ const camera = world.camera;
479
+ const texel = texelOf(own);
480
+ const lens = texel && camera?.isPerspectiveCamera === true ? lensOf(camera) : null;
481
+ const margin = texel && lookupMargin(Math.max(texel[0], texel[1]), own.normalBias);
482
+ const sphere = lens && Number.isFinite(margin) && sphereFor(lens, own, texel, margin, distance, world.renderer?.capabilities?.maxTextureSize);
483
+ if (!sphere) return false;
484
+ near.intensity = own.intensity;
485
+ near.radius = own.radius;
486
+ near.blurSamples = own.blurSamples;
487
+ near.bias = own.bias;
488
+ near.normalBias = own.normalBias;
489
+ near.view = camera;
490
+ near.reach = sphere.reach;
491
+ near.lens = lens.corners;
492
+ near.along = lens.along;
493
+ near.texel = texel;
494
+ near.margin = sphere.margin;
495
+ sizeBox(near, own.camera, sphere.radius, texel);
496
+ return true;
497
+ }
498
+
499
+ // The size of one texel of the sun's own shadow, across and up, in metres.
500
+ function texelOf(own) {
501
+ const box = own.camera;
502
+ // A zoom or a view offset changes what the box projects to; the engine's
503
+ // own camera has neither, so such a sun is drawn plain (term 5).
504
+ if (box.zoom !== 1 || box.view?.enabled === true) return null;
505
+ const x = (box.right - box.left) / own.mapSize.x;
506
+ const y = (box.top - box.bottom) / own.mapSize.y;
507
+ return x > 0 && y > 0 && Number.isFinite(x + y) ? [x, y] : null;
508
+ }
509
+
510
+ // A box of whole texels round the sphere (`map size x texel`), with the depth
511
+ // range of the sun's own, and a map of that size.
512
+ function sizeBox(near, box, radius, [texelX, texelY]) {
513
+ const width = Math.ceil((2 * radius) / texelX);
514
+ const height = Math.ceil((2 * radius) / texelY);
515
+ const halfX = (width * texelX) / 2;
516
+ const halfY = (height * texelY) / 2;
517
+ const mine = near.camera;
518
+ if (mine.right !== halfX || mine.top !== halfY || mine.near !== box.near || mine.far !== box.far) {
519
+ mine.left = -halfX;
520
+ mine.right = halfX;
521
+ mine.top = halfY;
522
+ mine.bottom = -halfY;
523
+ mine.near = box.near;
524
+ mine.far = box.far;
525
+ mine.updateProjectionMatrix();
526
+ }
527
+ // Last: three.js allocates a map of `mapSize` when there is none, and the
528
+ // old one's `dispose` may run someone else's code.
529
+ if (near.mapSize.x !== width || near.mapSize.y !== height) {
530
+ near.mapSize.set(width, height);
531
+ near.release();
532
+ }
533
+ }
534
+
535
+ // The view's corners one metre ahead, in the camera's own space, and the
536
+ // sphere on the view's axis through the camera and the farthest of them: how
537
+ // far along the axis its middle is and its radius, both per metre of view.
538
+ function lensOf(camera) {
539
+ let across = 0;
540
+ const corners = [];
541
+ for (const [x, y] of CORNERS) {
542
+ point.set(x, y, 0.5).applyMatrix4(camera.projectionMatrixInverse);
543
+ if (!(point.z < 0)) return null;
544
+ corners.push([point.x / -point.z, point.y / -point.z]);
545
+ across = Math.max(across, (point.x * point.x + point.y * point.y) / (point.z * point.z));
546
+ }
547
+ const along = Math.min(1, (across + 1) / 2);
548
+ const radiusPerMetre = along < 1 ? along : Math.sqrt(across);
549
+ return radiusPerMetre > 0 && Number.isFinite(radiusPerMetre) ? { corners, along, radiusPerMetre } : null;
550
+ }
551
+
552
+ // The sphere for `distance`, or the largest whose map is no larger than the
553
+ // sun's own in area and no longer on a side than the renderer can make
554
+ // (`side`): a distance that needs a larger one is drawn as far as that sphere
555
+ // reaches, with texels the size they were.
556
+ function sphereFor(lens, own, [texelX, texelY], margin, distance, side = Infinity) {
557
+ const texel = Math.max(texelX, texelY);
558
+ const widest = Math.min(Math.sqrt(own.mapSize.x * own.mapSize.y * texelX * texelY), side * Math.min(texelX, texelY)) / 2;
559
+ const largest = Math.floor((widest - texel) / RADIUS_STEP) * RADIUS_STEP;
560
+ const needed = Math.ceil((distance * lens.radiusPerMetre + margin + texel) / RADIUS_STEP) * RADIUS_STEP;
561
+ const radius = Math.min(needed, largest);
562
+ const reach = needed > largest ? (radius - margin - texel) / lens.radiusPerMetre : distance;
563
+ return reach > 0 && Number.isFinite(radius) ? { radius, reach, margin } : null;
564
+ }
565
+
566
+ // The outline of `points` (in the shadow camera's own right/up) as half-spaces
567
+ // in the world: one per edge of their convex hull, pushed out by `margin`.
568
+ function outlineSides(sides, points, right, up, margin) {
569
+ sides.length = 0;
570
+ const hull = convexHull(points);
571
+ if (hull.length < 3) return;
572
+ for (let i = 0; i < hull.length; i++) {
573
+ const a = hull[i];
574
+ const b = hull[(i + 1) % hull.length];
575
+ const ex = b[0] - a[0];
576
+ const ey = b[1] - a[1];
577
+ const length = Math.hypot(ex, ey);
578
+ if (!(length > 0)) continue;
579
+ // The hull runs counter-clockwise, so outside is to an edge's right.
580
+ const nu = ey / length;
581
+ const nv = -ex / length;
582
+ sides.push(right.x * nu + up.x * nv, right.y * nu + up.y * nv, right.z * nu + up.z * nv, a[0] * nu + a[1] * nv + margin);
583
+ }
584
+ }
585
+
586
+ // Andrew's monotone chain; counter-clockwise, collinear points dropped.
587
+ function convexHull(points) {
588
+ const sorted = [...points].sort((a, b) => a[0] - b[0] || a[1] - b[1]);
589
+ const turn = (o, a, b) => (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]);
590
+ const half = (list) => {
591
+ const chain = [];
592
+ for (const next of list) {
593
+ while (chain.length >= 2 && turn(chain[chain.length - 2], chain[chain.length - 1], next) <= 0) chain.pop();
594
+ chain.push(next);
595
+ }
596
+ chain.pop();
597
+ return chain;
598
+ };
599
+ return [...half(sorted), ...half(sorted.reverse())];
600
+ }
@@ -919,6 +919,55 @@ export function copyModel(template) {
919
919
  return copy;
920
920
  }
921
921
 
922
+ // For a scene that set `"engine": { "dropEmptyParts": true }` (world3d.js
923
+ // `addModelRig`): takes out of a game build the groups that draw nothing.
924
+ // Merging leaves a part's group standing where its mesh went into a batch on
925
+ // the root or on an animated part, and three.js and the engine visit every
926
+ // one of them on every frame.
927
+ //
928
+ // A group goes when neither it nor anything under it is drawn: no mesh, line,
929
+ // points, sprite, light or camera, nor anything else that is not a plain
930
+ // group. These always stay, with every group above them, and so does every
931
+ // copy of one (`mirror`, `repeat`, `scatter`, `tips`: a group marked
932
+ // `copyOf` the part):
933
+ // - a part marked `keep`, and a `slot-...` part (an attachment point: the
934
+ // format's docs let a deck parent its own parts to one), with whatever
935
+ // they hold that is not another part;
936
+ // - a part the walk moves (ANIMATED_PARTS), and one the model's `animation`
937
+ // moves: its `motion`, a gait, a clip's track (`animation.parts`).
938
+ // Nothing that stays is touched: not its parent, its transform or its
939
+ // geometry, so what is drawn is drawn from the same matrices. `model` is the
940
+ // parsed model `root` was built from.
941
+ export function dropEmptyGroups(root, model) {
942
+ const ids = new Set([...ANIMATED_PARTS, ...(root.userData.animation?.parts ?? [])]);
943
+ const named = new Set();
944
+ for (const part of model?.parts ?? []) {
945
+ if (part.keep || String(part.id).startsWith('slot-')) {
946
+ ids.add(part.id);
947
+ named.add(part.id);
948
+ }
949
+ }
950
+ const idOf = (object) => object.userData.partId ?? object.userData.copyOf;
951
+ const stays = (object) => {
952
+ if (object.type !== 'Group' && object.type !== 'Object3D') {
953
+ return true;
954
+ }
955
+ const id = idOf(object);
956
+ const kept = named.has(id);
957
+ let any = ids.has(id);
958
+ for (const child of [...object.children]) {
959
+ const own = kept && idOf(child) === undefined;
960
+ if (own || stays(child)) {
961
+ any = true;
962
+ } else {
963
+ object.remove(child);
964
+ }
965
+ }
966
+ return any;
967
+ };
968
+ stays(root);
969
+ }
970
+
922
971
  // A model with no walk-animation parts and no motion never moves inside itself.
923
972
  export function isStaticModel(template) {
924
973
  const parts = template.userData.modelParts;