castle-web-cli 0.4.203 → 0.4.205

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 (133) hide show
  1. package/dist/agent-failures.d.ts +3 -1
  2. package/dist/agent-failures.js +19 -0
  3. package/dist/agent-prompts.d.ts +1 -0
  4. package/dist/agent-prompts.js +20 -8
  5. package/dist/agent.d.ts +5 -2
  6. package/dist/agent.js +59 -125
  7. package/dist/castle-host/host.d.ts +17 -0
  8. package/dist/castle-host/host.js +551 -4
  9. package/dist/castleJson.d.ts +1 -0
  10. package/dist/devSessionStorage.js +65 -4
  11. package/dist/effortSupport.d.ts +7 -0
  12. package/dist/effortSupport.js +31 -0
  13. package/dist/init.js +13 -3
  14. package/dist/platformDoc.js +6 -1
  15. package/dist/routerFences.d.ts +22 -0
  16. package/dist/routerFences.js +139 -0
  17. package/dist/serve.js +35 -2
  18. package/dist/shell/assets/index-b_bebkRb.css +1 -0
  19. package/dist/shell/assets/{index-CxrtbzHf.js → index-hWQTC8q6.js} +5 -5
  20. package/dist/shell/index.html +2 -2
  21. package/dist/taskAccount.d.ts +13 -0
  22. package/dist/taskAccount.js +38 -0
  23. package/dist/vitePlugins.js +19 -1
  24. package/kits/base/CLAUDE.md +2 -0
  25. package/kits/base/castle.json +1 -1
  26. package/kits/base/sdk/README.md +131 -0
  27. package/kits/base/sdk/agent.d.ts +6 -0
  28. package/kits/base/sdk/agent.js +70 -0
  29. package/kits/base/sdk/castle.d.ts +4 -0
  30. package/kits/base/sdk/castle.js +2 -0
  31. package/kits/base/sdk/commands.d.ts +106 -0
  32. package/kits/base/sdk/commands.js +21 -0
  33. package/kits/base/sdk/decks.d.ts +7 -0
  34. package/kits/base/sdk/decks.js +31 -0
  35. package/kits/base/sdk/runtime.d.ts +4 -2
  36. package/kits/base/sdk/runtime.js +51 -40
  37. package/kits/base/sdk/server/storage.d.ts +44 -0
  38. package/kits/base/sdk/server/storage.js +54 -0
  39. package/kits/base/sdk/transport.d.ts +5 -1
  40. package/kits/base/sdk/transport.js +106 -23
  41. package/kits/multiplayer-2d/castle.json +4 -4
  42. package/kits/multiplayer-2d/code/client/poses.js +7 -0
  43. package/kits/multiplayer-2d/code/server/limits.js +3 -0
  44. package/kits/multiplayer-2d/code/server/ownership.js +36 -8
  45. package/kits/multiplayer-2d/code/systems/multiplayer.js +23 -2
  46. package/kits/multiplayer-3d/CLAUDE.md +12 -1
  47. package/kits/multiplayer-3d/castle.json +4 -4
  48. package/kits/multiplayer-3d/code/client/avatars.js +7 -1
  49. package/kits/multiplayer-3d/code/client/poses.js +61 -1
  50. package/kits/multiplayer-3d/code/client/steer.js +383 -0
  51. package/kits/multiplayer-3d/code/server/limits.js +3 -0
  52. package/kits/multiplayer-3d/code/server/ownership.js +114 -18
  53. package/kits/multiplayer-3d/code/server/world.js +12 -4
  54. package/kits/multiplayer-3d/code/systems/multiplayer.js +315 -34
  55. package/kits/physics-3d/CLAUDE.md +65 -7
  56. package/kits/physics-3d/castle.json +3 -3
  57. package/kits/physics-3d/docs/pxmodel-format.md +916 -15
  58. package/kits/physics-3d/engine3d/PxModelEditor.jsx +2 -2
  59. package/kits/physics-3d/engine3d/artobjects.js +218 -0
  60. package/kits/physics-3d/engine3d/blob.js +1058 -0
  61. package/kits/physics-3d/engine3d/branches.js +300 -0
  62. package/kits/physics-3d/engine3d/cage.js +496 -0
  63. package/kits/physics-3d/engine3d/cageops.js +516 -0
  64. package/kits/physics-3d/engine3d/frame.js +669 -0
  65. package/kits/physics-3d/engine3d/look.js +675 -0
  66. package/kits/physics-3d/engine3d/materialpresets.js +486 -0
  67. package/kits/physics-3d/engine3d/modelEditorWorld.js +3 -2
  68. package/kits/physics-3d/engine3d/modelrefs.js +120 -0
  69. package/kits/physics-3d/engine3d/motion.js +560 -0
  70. package/kits/physics-3d/engine3d/objtext.js +37 -0
  71. package/kits/physics-3d/engine3d/optimize.js +1083 -0
  72. package/kits/physics-3d/engine3d/paint.js +674 -0
  73. package/kits/physics-3d/engine3d/partgeometry.js +467 -0
  74. package/kits/physics-3d/engine3d/paths.js +324 -0
  75. package/kits/physics-3d/engine3d/pxmodel.js +429 -26
  76. package/kits/physics-3d/engine3d/scatter.js +102 -0
  77. package/kits/physics-3d/engine3d/sculpt.js +1148 -0
  78. package/kits/physics-3d/engine3d/surfacedetail.js +267 -0
  79. package/kits/physics-3d/engine3d/sweep.js +480 -0
  80. package/kits/physics-3d/engine3d/thumbnails.js +6 -4
  81. package/kits/physics-3d/engine3d/world3d.js +119 -17
  82. package/kits/physics-3d/eslint.config.js +13 -0
  83. package/kits/physics-3d/models/parts/axe.pxmodel +40 -0
  84. package/kits/physics-3d/models/parts/backpack.pxmodel +47 -0
  85. package/kits/physics-3d/models/parts/barrel.pxmodel +22 -0
  86. package/kits/physics-3d/models/parts/bedroll.pxmodel +28 -0
  87. package/kits/physics-3d/models/parts/belt-pouch.pxmodel +22 -0
  88. package/kits/physics-3d/models/parts/bolt.pxmodel +10 -0
  89. package/kits/physics-3d/models/parts/bracer.pxmodel +26 -0
  90. package/kits/physics-3d/models/parts/chain-span.pxmodel +12 -0
  91. package/kits/physics-3d/models/parts/chimney.pxmodel +11 -0
  92. package/kits/physics-3d/models/parts/crate.pxmodel +44 -0
  93. package/kits/physics-3d/models/parts/crystal.pxmodel +22 -0
  94. package/kits/physics-3d/models/parts/door-arched.pxmodel +12 -0
  95. package/kits/physics-3d/models/parts/engine-block.pxmodel +39 -0
  96. package/kits/physics-3d/models/parts/exhaust-pipe.pxmodel +30 -0
  97. package/kits/physics-3d/models/parts/fence-span.pxmodel +10 -0
  98. package/kits/physics-3d/models/parts/fender.pxmodel +19 -0
  99. package/kits/physics-3d/models/parts/headlight.pxmodel +24 -0
  100. package/kits/physics-3d/models/parts/hood.pxmodel +17 -0
  101. package/kits/physics-3d/models/parts/horned-helmet.pxmodel +37 -0
  102. package/kits/physics-3d/models/parts/jerry-can.pxmodel +26 -0
  103. package/kits/physics-3d/models/parts/ladder.pxmodel +10 -0
  104. package/kits/physics-3d/models/parts/lamp.pxmodel +20 -0
  105. package/kits/physics-3d/models/parts/lantern.pxmodel +30 -0
  106. package/kits/physics-3d/models/parts/leaf-cluster.pxmodel +21 -0
  107. package/kits/physics-3d/models/parts/offroad-tire.pxmodel +48 -0
  108. package/kits/physics-3d/models/parts/pauldron.pxmodel +26 -0
  109. package/kits/physics-3d/models/parts/rivet.pxmodel +8 -0
  110. package/kits/physics-3d/models/parts/rock.pxmodel +21 -0
  111. package/kits/physics-3d/models/parts/roll-bar-light.pxmodel +26 -0
  112. package/kits/physics-3d/models/parts/round-shield.pxmodel +31 -0
  113. package/kits/physics-3d/models/parts/saddlebag.pxmodel +30 -0
  114. package/kits/physics-3d/models/parts/spoked-wheel.pxmodel +39 -0
  115. package/kits/physics-3d/models/parts/staff.pxmodel +33 -0
  116. package/kits/physics-3d/models/parts/stepping-stones.pxmodel +8 -0
  117. package/kits/physics-3d/models/parts/stone-base.pxmodel +10 -0
  118. package/kits/physics-3d/models/parts/sword.pxmodel +33 -0
  119. package/kits/physics-3d/models/parts/window-lit.pxmodel +13 -0
  120. package/kits/physics-3d/models/parts/wizard-hat.pxmodel +28 -0
  121. package/kits/physics-3d/models/templates/biped-stout.pxmodel +59 -0
  122. package/kits/physics-3d/models/templates/biped-tall.pxmodel +63 -0
  123. package/kits/physics-3d/models/templates/quadruped.pxmodel +52 -0
  124. package/kits/physics-3d/scripts/render/filmstrip.js +217 -0
  125. package/kits/physics-3d/scripts/render/index.html +20 -0
  126. package/kits/physics-3d/scripts/render/sheet.js +411 -0
  127. package/kits/physics-3d/scripts/render.mjs +646 -0
  128. package/kits/real-time/castle.json +2 -2
  129. package/kits/real-time/code/client/ownership.js +14 -4
  130. package/kits/real-time/code/client/smooth.js +2 -2
  131. package/kits/real-time/code/server/session.js +20 -4
  132. package/package.json +2 -2
  133. package/dist/shell/assets/index-CHMcsJrW.css +0 -1
@@ -0,0 +1,1083 @@
1
+ // What a `.pxmodel` costs to draw in a game, and the passes that keep the
2
+ // cost down. See the Cost section of docs/pxmodel-format.md.
3
+ //
4
+ // Builders measure their resolution in DETAIL_PIXEL, about one screen pixel
5
+ // under a third-person camera 6.5 m behind the player with a 55 degree lens,
6
+ // the closest a game usually shows a model. A part gets the detail its
7
+ // author or its kind's default asks for, but never finer than a few of
8
+ // these pixels, so small parts such as rivets and eyes are cheap.
9
+ //
10
+ // A model has a triangle budget, `triangles` at its top level. When its
11
+ // parts come to more, the heaviest are built again coarser (coarsenParts),
12
+ // their pixel doubled each time. Paint and surface detail then split the
13
+ // surface only as finely as the budget leaves room for. A game build
14
+ // (`optimize`) shrinks the heaviest meshes if the model is still over, and
15
+ // merges parts that draw alike into one mesh each.
16
+
17
+ import * as THREE from 'three';
18
+ import { mergeGeometries } from 'three/examples/jsm/utils/BufferGeometryUtils.js';
19
+ import { addOutlineAttributes } from './look';
20
+
21
+ // Meters per screen pixel under the third-person camera, and under the far
22
+ // overhead camera of the space decks.
23
+ export const DETAIL_PIXEL = 0.0085;
24
+ export const GAME_PIXEL = 0.017;
25
+
26
+ export const DEFAULT_TRIANGLES = 15000;
27
+
28
+ // A round part gets a side for about this many pixels of its outline.
29
+ const PIXELS_PER_SIDE = 3;
30
+
31
+ // A blob's grid cell and a smoothed cage's edges are about this wide.
32
+ const PIXELS_PER_CELL = 1.5;
33
+
34
+ // Paint and surface detail never split edges shorter than this.
35
+ const SMALLEST_EDGE_PIXELS = 2;
36
+
37
+ // Paint stripes and checker cells narrower than this blend into one color.
38
+ const FINEST_BAND_PIXELS = 1.5;
39
+
40
+ // A model up to this many times its budget is left to the game build's
41
+ // shrinking (fitBudget), which loses less than building parts coarser.
42
+ const SHRINKS_ALONE = 1.5;
43
+
44
+ // Parts smaller than this many meters across are built to the pixel limits
45
+ // from the start: bolts, rivets and eyes, which no view shows closely.
46
+ const TINY_SIZE = 0.1;
47
+
48
+ // Bands up to this many pixels wide blend when the budget is tight.
49
+ const WIDEST_BLENDED_PIXELS = 3;
50
+
51
+ // A part over budget is built again, first to the pixel limits and then
52
+ // with its pixel doubled, at most this many times in all.
53
+ const MOST_COARSENINGS = 4;
54
+
55
+ //
56
+ // Sizes on screen
57
+ //
58
+
59
+ // The largest of the part's scales. Geometry is built in the part's own
60
+ // units and scaled after.
61
+ function largestScale(part) {
62
+ const scale = Array.isArray(part?.scale) ? part.scale : [1, 1, 1];
63
+ return Math.max(...scale.map((value) => Math.abs(value) || 0), 1e-6);
64
+ }
65
+
66
+ // A length of `pixels` pixels in the part's own units, the finest detail
67
+ // worth building. It is 0, no limit, unless the part is coarsened to fit its
68
+ // model's budget (`coarseness`, how many times larger its pixel is) or is
69
+ // tiny: `size`, in the part's own units, under TINY_SIZE meters.
70
+ export function pixelsInPart(part, pixels, size = Infinity) {
71
+ const scale = largestScale(part);
72
+ if (!part?.coarseness && Math.abs(size) * scale >= TINY_SIZE) {
73
+ return 0;
74
+ }
75
+ return (pixels * DETAIL_PIXEL * (part?.coarseness ?? 1)) / scale;
76
+ }
77
+
78
+ // Sides for a circle of `radius` in the part's own units: enough that each
79
+ // side spans PIXELS_PER_SIDE pixels, at least `least` and at most `most`.
80
+ // Builders pass the `segments` the author wrote, or their default, as `most`.
81
+ export function circleSides(part, radius, most, least = 6) {
82
+ const circumference = 2 * Math.PI * Math.abs(radius);
83
+ const wanted = Math.ceil(circumference / pixelsInPart(part, PIXELS_PER_SIDE, 2 * radius));
84
+ return Math.max(Math.min(least, most), Math.min(most, wanted));
85
+ }
86
+
87
+ // Steps along a curve of `length` in the part's own units, one per
88
+ // PIXELS_PER_SIDE pixels, within `least` and `most`.
89
+ export function lengthSteps(part, length, most, least = 2) {
90
+ const wanted = Math.ceil(Math.abs(length) / pixelsInPart(part, PIXELS_PER_SIDE));
91
+ return Math.max(least, Math.min(most, wanted));
92
+ }
93
+
94
+ // The smallest grid cell worth sampling a blob at, in the part's own units.
95
+ export function smallestCell(part) {
96
+ return pixelsInPart(part, PIXELS_PER_CELL);
97
+ }
98
+
99
+ // How many of the `steps` subdivisions of a cage are worth making: each
100
+ // halves the edges, and steps stop once the average edge is under
101
+ // PIXELS_PER_CELL pixels. A cage asked to subdivide at all keeps one step,
102
+ // which is what rounds it.
103
+ export function subdivideSteps(cage, part, steps) {
104
+ if (steps <= 1) {
105
+ return steps;
106
+ }
107
+ let total = 0;
108
+ let count = 0;
109
+ for (const face of cage.faces) {
110
+ for (let i = 0; i < face.length; i++) {
111
+ const a = cage.vertices[face[i]];
112
+ const b = cage.vertices[face[(i + 1) % face.length]];
113
+ total += Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]);
114
+ count++;
115
+ }
116
+ }
117
+ const edge = count > 0 ? total / count : 0;
118
+ const size = [0, 1, 2].reduce((most, axis) => {
119
+ const values = cage.vertices.map((vertex) => vertex[axis]);
120
+ return Math.max(most, Math.max(...values) - Math.min(...values));
121
+ }, 0);
122
+ const wanted = Math.ceil(Math.log2(edge / pixelsInPart(part, PIXELS_PER_CELL, size)));
123
+ return Math.max(1, Math.min(steps, wanted));
124
+ }
125
+
126
+ //
127
+ // Budget
128
+ //
129
+
130
+ // Paint and surface detail always get at least this share of the budget.
131
+ const LEAST_DETAIL_SHARE = 0.5;
132
+
133
+ function triangleCount(geometry) {
134
+ const index = geometry.getIndex();
135
+ return (index ? index.count : geometry.getAttribute('position').count) / 3;
136
+ }
137
+
138
+ // The two longest sides of every triangle, in meters, as pairs in one list.
139
+ function triangleSides(geometry, scale, out) {
140
+ const position = geometry.getAttribute('position');
141
+ const index = geometry.getIndex();
142
+ const count = index ? index.count : position.count;
143
+ const points = [new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3()];
144
+ for (let n = 0; n + 2 < count; n += 3) {
145
+ for (let k = 0; k < 3; k++) {
146
+ points[k].fromBufferAttribute(position, index ? index.getX(n + k) : n + k).multiply(scale);
147
+ }
148
+ const sides = [
149
+ points[0].distanceTo(points[1]),
150
+ points[1].distanceTo(points[2]),
151
+ points[2].distanceTo(points[0]),
152
+ ].sort((a, b) => b - a);
153
+ out.push(sides[0], sides[1]);
154
+ }
155
+ }
156
+
157
+ // About how many triangles splitting every side longer than `edge` in half,
158
+ // again and again, makes: a side of length a is halved until it is short
159
+ // enough, into `pieces(a)`, and a triangle becomes about as many triangles
160
+ // as its two longest sides make pieces between them.
161
+ function splitCount(sides, edge) {
162
+ const pieces = (length) => (length <= edge ? 1 : 2 ** Math.ceil(Math.log2(length / edge)));
163
+ let total = 0;
164
+ for (let i = 0; i < sides.length; i += 2) {
165
+ total += pieces(sides[i]) * pieces(sides[i + 1]);
166
+ }
167
+ return total;
168
+ }
169
+
170
+ // How many times each part is drawn: `mirror` doubles it, `repeat` and
171
+ // `scatter` make `count`, and a copy of a parent copies its children too.
172
+ function copyCounts(model) {
173
+ const byId = new Map(model.parts.map((part) => [part.id, part]));
174
+ const own = (part) => {
175
+ let count = 1;
176
+ if (part.scatter && typeof part.scatter === 'object') {
177
+ count = Math.max(1, Math.round(part.scatter.count ?? 10));
178
+ } else if (part.repeat && typeof part.repeat === 'object') {
179
+ count = Math.max(1, Math.min(64, Math.round(part.repeat.count ?? 1)));
180
+ }
181
+ return ['x', 'y', 'z'].includes(part.mirror) ? count * 2 : count;
182
+ };
183
+ const counts = new Map();
184
+ const countOf = (part) => {
185
+ if (!counts.has(part.id)) {
186
+ const parent = byId.get(part.parent);
187
+ counts.set(part.id, own(part) * (parent ? countOf(parent) : 1));
188
+ }
189
+ return counts.get(part.id);
190
+ };
191
+ model.parts.forEach(countOf);
192
+ return counts;
193
+ }
194
+
195
+ // Builds the parts again coarser while they come to more than the budget
196
+ // leaves after paint's share: the heaviest first, enough of them to cover
197
+ // twice what is over, each held to the pixel limits and then with its pixel
198
+ // doubled. `rebuild(part, coarseness)`
199
+ // builds one part; `built` is each part's { mesh, part, source } and is
200
+ // changed in place. A part that gets no cheaper is left as it is.
201
+ export function coarsenParts(model, built, references, rebuild, fallback = DEFAULT_TRIANGLES) {
202
+ const budget = model.triangles > 0 ? model.triangles : fallback;
203
+ const counts = copyCounts(model);
204
+ const paints = built.some(({ part }) => refinesSurface(part));
205
+ let referenced = 0;
206
+ for (const { node, part } of references) {
207
+ referenced += modelCost(node).triangles * (counts.get(part.id) ?? 1);
208
+ }
209
+ const limit = budget * (paints ? 1 - LEAST_DETAIL_SHARE : 1) - referenced;
210
+ const costOf = (entry) => triangleCount(entry.mesh.geometry) * (counts.get(entry.part.id) ?? 1);
211
+ for (let round = 0; round < MOST_COARSENINGS; round++) {
212
+ const total = built.reduce((sum, entry) => sum + costOf(entry), 0);
213
+ if (total <= limit * SHRINKS_ALONE) {
214
+ return;
215
+ }
216
+ const heaviest = built.filter((entry) => !entry.settled).sort((a, b) => costOf(b) - costOf(a));
217
+ let covered = 0;
218
+ for (const entry of heaviest) {
219
+ if (covered >= 2 * (total - limit * SHRINKS_ALONE)) {
220
+ break;
221
+ }
222
+ covered += costOf(entry);
223
+ coarsen(entry, rebuild);
224
+ }
225
+ }
226
+ }
227
+
228
+ // A part stops being coarsened once doubling its pixel no longer helps.
229
+ // Its first steps may change nothing, when it is already coarser than the
230
+ // limits.
231
+ function coarsen(entry, rebuild) {
232
+ const coarseness = entry.coarseness ? entry.coarseness * 2 : 1;
233
+ const next = rebuild(entry.source, coarseness);
234
+ entry.coarseness = coarseness;
235
+ if (triangleCount(next.mesh.geometry) >= triangleCount(entry.mesh.geometry)) {
236
+ next.mesh.geometry.dispose();
237
+ entry.settled = coarseness >= 2;
238
+ return;
239
+ }
240
+ entry.mesh.geometry.dispose();
241
+ Object.assign(entry, next);
242
+ }
243
+
244
+ // The budget each referenced model gets when it sets none of its own: the
245
+ // model's budget shared evenly among its references and their copies.
246
+ export function referenceBudget(model, fallback = DEFAULT_TRIANGLES) {
247
+ const budget = model.triangles > 0 ? model.triangles : fallback;
248
+ const counts = copyCounts(model);
249
+ let references = 0;
250
+ for (const part of model.parts) {
251
+ if (part.kind === 'model') {
252
+ references += counts.get(part.id) ?? 1;
253
+ }
254
+ }
255
+ return Math.round(budget / Math.max(1, references));
256
+ }
257
+
258
+ function refinesSurface(part) {
259
+ return (
260
+ (Array.isArray(part.paint) && part.paint.length > 0) ||
261
+ part.displace > 0
262
+ );
263
+ }
264
+
265
+ // The model's triangle budget; `edge`, the shortest edge in meters that
266
+ // paint and surface detail may split down to; and `finest`, the narrowest
267
+ // paint band worth drawing. `built` is each part's base mesh before paint,
268
+ // with the part it was built from, and `references` each referenced model's
269
+ // node with its part. The triangles the other parts and the references use
270
+ // come off the budget first, and `edge` is found by halving so that
271
+ // splitting the rest fits in what is left.
272
+ export function detailFor(model, built, references = [], fallback = DEFAULT_TRIANGLES) {
273
+ const budget = model.triangles > 0 ? model.triangles : fallback;
274
+ const shortest = SMALLEST_EDGE_PIXELS * DETAIL_PIXEL;
275
+ const finest = FINEST_BAND_PIXELS * DETAIL_PIXEL;
276
+ const counts = copyCounts(model);
277
+ let fixed = 0;
278
+ const sides = [];
279
+ for (const { mesh, part } of built) {
280
+ const copies = counts.get(part.id) ?? 1;
281
+ if (refinesSurface(part)) {
282
+ const scale = new THREE.Vector3(...part.scale.map((value) => Math.abs(value) || 1));
283
+ for (let copy = 0; copy < Math.min(copies, 64); copy++) {
284
+ triangleSides(mesh.geometry, scale, sides);
285
+ }
286
+ } else {
287
+ fixed += triangleCount(mesh.geometry) * copies;
288
+ }
289
+ }
290
+ for (const { node, part } of references) {
291
+ fixed += modelCost(node).triangles * (counts.get(part.id) ?? 1);
292
+ }
293
+ const room = Math.max(budget - fixed, budget * LEAST_DETAIL_SHARE);
294
+ const edge = edgeForRoom(sides, room, shortest);
295
+
296
+ // When the budget leaves paint coarse, bands up to a few pixels wide blend
297
+ // too; wider ones are always cut.
298
+ const blended = Math.min(edge / 2, WIDEST_BLENDED_PIXELS * DETAIL_PIXEL);
299
+ return { budget, edge, finest: Math.max(finest, blended) };
300
+ }
301
+
302
+ // The shortest edge, no shorter than `shortest`, that splitting `sides`
303
+ // down to leaves at most `room` triangles.
304
+ function edgeForRoom(sides, room, shortest) {
305
+ if (sides.length === 0 || splitCount(sides, shortest) <= room) {
306
+ return shortest;
307
+ }
308
+ let short = shortest;
309
+ let long = sides.reduce((most, side) => Math.max(most, side), shortest);
310
+ for (let step = 0; step < 16 && long / short > 1.02; step++) {
311
+ const edge = Math.sqrt(short * long);
312
+ if (splitCount(sides, edge) > room) {
313
+ short = edge;
314
+ } else {
315
+ long = edge;
316
+ }
317
+ }
318
+ return long;
319
+ }
320
+
321
+ //
322
+ // Game builds
323
+ //
324
+
325
+ const placed = new THREE.Matrix4();
326
+
327
+ // three turns a mesh's triangles around when its own matrix mirrors it, but
328
+ // not per instance. Mirrored copies are drawn by an InstancedMesh that is
329
+ // itself mirrored by MIRROR (its own inverse), with MIRROR taken back out of
330
+ // each instance.
331
+ const MIRROR = new THREE.Matrix4().makeScale(-1, 1, 1);
332
+
333
+ function makeInstanced(source, capacity, mirrored) {
334
+ const instanced = new THREE.InstancedMesh(source.geometry, source.material, capacity);
335
+ if (mirrored) {
336
+ instanced.scale.x = -1;
337
+ }
338
+ return instanced;
339
+ }
340
+
341
+ // Parts the walk animation moves (animateModelParts in pxmodel.js). Each is
342
+ // merged apart from the rest, with everything under it, and so is each part
343
+ // in the model's `animation.parts` (motion.js) and every copy of one.
344
+ const ANIMATED_PARTS = ['legL', 'legR', 'armL', 'armR', 'torso'];
345
+
346
+ // Parts smaller than this radius in meters cast no shadow; at game size
347
+ // their shadow is a pixel or two.
348
+ const SHADOW_MIN_RADIUS = 0.06;
349
+
350
+ // Parts smaller than this radius get no outline (look.js), so they are
351
+ // merged apart from larger ones.
352
+ const OUTLINE_MIN_RADIUS = 0.035;
353
+
354
+ // Shrinks the model to its budget, then merges its meshes. `detail` is what
355
+ // detailFor returned. Referenced models come already built for a game, with
356
+ // their look; their repeated meshes become instanced meshes instead.
357
+ export function optimizeModel(root, model, detail) {
358
+ root.updateMatrixWorld(true);
359
+ const meshes = [];
360
+ const finished = [];
361
+ root.traverseVisible((object) => {
362
+ if (!object.isMesh) {
363
+ return;
364
+ }
365
+ if (object.userData.lookDone || object.userData.lookOutline) {
366
+ finished.push(object);
367
+ } else {
368
+ meshes.push(object);
369
+ }
370
+ });
371
+ meshes.splice(0, meshes.length, ...meshes.flatMap(splitFaces));
372
+ const anchors = animatedAnchors(root);
373
+ const referenced = finished.reduce((sum, mesh) => sum + triangleCount(mesh.geometry), 0);
374
+ fitBudget(meshes, detail.budget - referenced);
375
+ for (const mesh of meshes) {
376
+ mesh.castShadow = worldRadius(mesh) >= SHADOW_MIN_RADIUS;
377
+ }
378
+ instanceCopies(root, finished, anchors);
379
+ const kept = keptParts(model);
380
+ const mergeable = meshes.filter((mesh) => !kept.has(mesh.userData.partMesh));
381
+ mergeMeshes(root, model, mergeable, anchors);
382
+ }
383
+
384
+ // A mesh with a material per face group (a box with art per face) becomes
385
+ // one mesh per group, each of which can join a batch.
386
+ function splitFaces(mesh) {
387
+ if (!Array.isArray(mesh.material)) {
388
+ return [mesh];
389
+ }
390
+ const source = mesh.geometry;
391
+ const index = source.getIndex();
392
+ const pieces = source.groups.map((group) => {
393
+ const geometry = new THREE.BufferGeometry();
394
+ for (const [name, attribute] of Object.entries(source.attributes)) {
395
+ geometry.setAttribute(name, attribute);
396
+ }
397
+ const corners = Array.from({ length: group.count }, (_, n) => group.start + n);
398
+ geometry.setIndex(index ? corners.map((corner) => index.getX(corner)) : corners);
399
+ const piece = new THREE.Mesh(geometry, mesh.material[group.materialIndex ?? 0]);
400
+ piece.position.copy(mesh.position);
401
+ piece.quaternion.copy(mesh.quaternion);
402
+ piece.scale.copy(mesh.scale);
403
+ piece.castShadow = mesh.castShadow;
404
+ piece.receiveShadow = mesh.receiveShadow;
405
+ piece.userData = { ...mesh.userData };
406
+ mesh.parent.add(piece);
407
+ piece.updateMatrixWorld(true);
408
+ return piece;
409
+ });
410
+ mesh.removeFromParent();
411
+ return pieces;
412
+ }
413
+
414
+ // Parts never merged: those marked `keep`, whose deck may reach for their
415
+ // meshes, and those with a `tint`.
416
+ function keptParts(model) {
417
+ return new Set(model.parts.filter((part) => part.keep || part.tint).map((part) => part.id));
418
+ }
419
+
420
+ function glowKey(material) {
421
+ const emissive = material.emissive;
422
+ if (!emissive || (emissive.r === 0 && emissive.g === 0 && emissive.b === 0)) {
423
+ return '';
424
+ }
425
+ return `${emissive.getHexString()}*${material.emissiveIntensity}`;
426
+ }
427
+
428
+ function animatedAnchors(root) {
429
+ const found = ANIMATED_PARTS.map((id) => root.userData.modelParts?.get(id) ?? findPart(root, id));
430
+ const moving = new Set(root.userData.animation?.parts ?? []);
431
+ if (moving.size > 0) {
432
+ root.traverse((object) => {
433
+ if (moving.has(object.userData.partId) || moving.has(object.userData.copyOf)) {
434
+ found.push(object);
435
+ }
436
+ });
437
+ }
438
+ return new Set(found.filter(Boolean));
439
+ }
440
+
441
+ function worldRadius(mesh) {
442
+ const geometry = mesh.geometry;
443
+ if (!geometry.boundingSphere) {
444
+ geometry.computeBoundingSphere();
445
+ }
446
+ return geometry.boundingSphere.radius * mesh.matrixWorld.getMaxScaleOnAxis();
447
+ }
448
+
449
+ //
450
+ // Merging
451
+ //
452
+
453
+ // Meshes that draw alike merge into one: the same anchor (the model root, or
454
+ // the nearest animated part above), the same kind of material, the same
455
+ // look and glow, and alike in whether they get an outline. Color, roughness
456
+ // and metalness move into the vertices. A batch casts a shadow when
457
+ // one of its meshes is large enough to.
458
+ function mergeMeshes(root, model, meshes, anchors) {
459
+ const looks = new Map(model.parts.map((part) => [part.id, JSON.stringify(part.look ?? null)]));
460
+ const batches = new Map();
461
+ for (const mesh of meshes) {
462
+ const anchor = anchorOf(mesh, root, anchors);
463
+ const radius = worldRadius(mesh);
464
+ const key = [
465
+ anchor.uuid,
466
+ materialKey(mesh.material),
467
+ looks.get(mesh.userData.partMesh) ?? 'null',
468
+ radius >= OUTLINE_MIN_RADIUS,
469
+ ].join('|');
470
+ if (!batches.has(key)) {
471
+ batches.set(key, { anchor, meshes: [], radius, castShadow: false });
472
+ }
473
+ const batch = batches.get(key);
474
+ batch.meshes.push(mesh);
475
+ batch.radius = Math.min(batch.radius, radius);
476
+ batch.castShadow ||= mesh.castShadow;
477
+ }
478
+ for (const batch of batches.values()) {
479
+ if (batch.meshes.length > 1) {
480
+ mergeBatch(batch);
481
+ }
482
+ }
483
+ }
484
+
485
+ function findPart(root, id) {
486
+ let found = null;
487
+ root.traverse((object) => {
488
+ if (!found && object.userData.partId === id) {
489
+ found = object;
490
+ }
491
+ });
492
+ return found;
493
+ }
494
+
495
+ function anchorOf(mesh, root, anchors) {
496
+ for (let object = mesh.parent; object && object !== root; object = object.parent) {
497
+ if (anchors.has(object)) {
498
+ return object;
499
+ }
500
+ }
501
+ return root;
502
+ }
503
+
504
+ function materialKey(material) {
505
+ return [
506
+ material.type,
507
+ textureKey(material.map),
508
+ material.clearcoat,
509
+ glowKey(material),
510
+ material.flatShading,
511
+ material.side,
512
+ material.transparent,
513
+ material.opacity,
514
+ material.alphaTest,
515
+ ].join(',');
516
+ }
517
+
518
+ // Textures tiled with `artRepeat` are copies of one image; copies that tile
519
+ // alike draw the same.
520
+ function textureKey(map) {
521
+ if (!map) {
522
+ return '';
523
+ }
524
+ const tiling = [map.repeat.x, map.repeat.y, map.offset.x, map.offset.y, map.wrapS, map.wrapT];
525
+ return `${map.source?.uuid ?? map.uuid}:${tiling.join(':')}`;
526
+ }
527
+
528
+ // One mesh in the anchor's space in place of the batch's meshes. Its
529
+ // `partRadius` is the smallest member's, which look.js reads for outlines.
530
+ function mergeBatch({ anchor, meshes, radius, castShadow }) {
531
+ const toAnchor = new THREE.Matrix4().copy(anchor.matrixWorld).invert();
532
+ const textured = Boolean(meshes[0].material.map);
533
+ const geometries = meshes.map((mesh) =>
534
+ bakedGeometry(mesh, new THREE.Matrix4().multiplyMatrices(toAnchor, mesh.matrixWorld), textured)
535
+ );
536
+
537
+ // Outline normals are smoothed over vertices at one place, and are found
538
+ // part by part, so parts that touch keep an outline between them.
539
+ if (radius >= OUTLINE_MIN_RADIUS) {
540
+ geometries.forEach(addOutlineAttributes);
541
+ }
542
+ const geometry = mergeGeometries(geometries, false);
543
+ if (!geometry) {
544
+ return;
545
+ }
546
+ const material = meshes[0].material.clone();
547
+ material.color.set('#ffffff');
548
+ material.vertexColors = true;
549
+ finishFromVertices(material);
550
+ const merged = new THREE.Mesh(geometry, material);
551
+ merged.castShadow = castShadow;
552
+ merged.receiveShadow = true;
553
+ merged.userData.partMesh = meshes[0].userData.partMesh;
554
+ merged.userData.partRadius = radius;
555
+ merged.userData.merged = meshes.length;
556
+ for (const mesh of meshes) {
557
+ mesh.removeFromParent();
558
+ }
559
+ anchor.add(merged);
560
+ }
561
+
562
+ //
563
+ // Instanced copies
564
+ //
565
+
566
+ // Meshes of referenced models that repeat, the same geometry and material
567
+ // under the same anchor, become one InstancedMesh each: four tires are one
568
+ // call per material, and one more for their outlines.
569
+ function instanceCopies(root, meshes, anchors) {
570
+ const groups = new Map();
571
+ for (const mesh of meshes) {
572
+ const anchor = anchorOf(mesh, root, anchors);
573
+ const mirrored = mesh.matrixWorld.determinant() < 0;
574
+ const key = `${anchor.uuid}|${mesh.geometry.uuid}|${mesh.material.uuid}|${mirrored}`;
575
+ if (!groups.has(key)) {
576
+ groups.set(key, { anchor, meshes: [] });
577
+ }
578
+ groups.get(key).meshes.push(mesh);
579
+ }
580
+ const made = [];
581
+ for (const { anchor, meshes: copies } of groups.values()) {
582
+ if (copies.length > 1) {
583
+ made.push({ anchor, instanced: instancedCopy(anchor, copies) });
584
+ }
585
+ }
586
+ for (const group of groups.values()) {
587
+ if (group.meshes.length > 1) {
588
+ group.meshes.forEach((mesh) => mesh.removeFromParent());
589
+ }
590
+ }
591
+ for (const { anchor, instanced } of made) {
592
+ anchor.add(instanced);
593
+ }
594
+ }
595
+
596
+ function instancedCopy(anchor, copies) {
597
+ const toAnchor = new THREE.Matrix4().copy(anchor.matrixWorld).invert();
598
+ const first = copies[0];
599
+ const mirrored = first.matrixWorld.determinant() < 0;
600
+ const instanced = makeInstanced(first, copies.length, mirrored);
601
+ copies.forEach((mesh, n) => {
602
+ placed.multiplyMatrices(toAnchor, mesh.matrixWorld);
603
+ instanced.setMatrixAt(n, mirrored ? placed.premultiply(MIRROR) : placed);
604
+ });
605
+ instanced.castShadow = first.castShadow;
606
+ instanced.receiveShadow = first.receiveShadow;
607
+ instanced.userData = { ...first.userData };
608
+ instanced.computeBoundingSphere();
609
+ if (first.userData.lookOutline) {
610
+ instanced.raycast = () => {};
611
+ }
612
+ return instanced;
613
+ }
614
+
615
+ // The mesh's geometry moved by `matrix`, indexed, with exactly a position,
616
+ // normal, color and finish (and uv when textured). A mirrored copy has its
617
+ // triangles turned around, so they still face out.
618
+ function bakedGeometry(mesh, matrix, textured) {
619
+ const source = mesh.geometry;
620
+ const geometry = new THREE.BufferGeometry();
621
+ geometry.setAttribute('position', source.getAttribute('position').clone());
622
+ if (!source.getAttribute('normal')) {
623
+ source.computeVertexNormals();
624
+ }
625
+ geometry.setAttribute('normal', source.getAttribute('normal').clone());
626
+ const count = geometry.getAttribute('position').count;
627
+ bakeMaterial(mesh, geometry, count);
628
+ if (textured) {
629
+ const uv = source.getAttribute('uv');
630
+ geometry.setAttribute(
631
+ 'uv',
632
+ uv ? uv.clone() : new THREE.BufferAttribute(new Float32Array(count * 2), 2)
633
+ );
634
+ }
635
+ const index = source.getIndex();
636
+ const order = index ? Array.from(index.array) : Array.from({ length: count }, (_, i) => i);
637
+ if (matrix.determinant() < 0) {
638
+ for (let n = 0; n + 2 < order.length; n += 3) {
639
+ [order[n + 1], order[n + 2]] = [order[n + 2], order[n + 1]];
640
+ }
641
+ }
642
+ geometry.setIndex(order);
643
+ geometry.applyMatrix4(matrix);
644
+ return geometry;
645
+ }
646
+
647
+ // The material's color, multiplied into the vertex colors, and its
648
+ // roughness and metalness, as vertex attributes. Glow stays on the material,
649
+ // where motion.js flickers it; glowing parts only merge with the same glow.
650
+ function bakeMaterial(mesh, geometry, count) {
651
+ const material = mesh.material;
652
+ const tint = material.color;
653
+ const own = material.vertexColors ? mesh.geometry.getAttribute('color') : null;
654
+ const colors = new Float32Array(count * 3);
655
+ const finish = new Float32Array(count * 2);
656
+ for (let i = 0; i < count; i++) {
657
+ const [r, g, b] = own ? [own.getX(i), own.getY(i), own.getZ(i)] : [1, 1, 1];
658
+ colors.set([r * tint.r, g * tint.g, b * tint.b], i * 3);
659
+ finish.set([material.roughness ?? 1, material.metalness ?? 0], i * 2);
660
+ }
661
+ geometry.setAttribute('color', new THREE.BufferAttribute(colors, 3));
662
+ geometry.setAttribute('partFinish', new THREE.BufferAttribute(finish, 2));
663
+ }
664
+
665
+ const FINISH_VERTEX = /* glsl */ `
666
+ attribute vec2 partFinish;
667
+ varying vec2 vPartFinish;
668
+ `;
669
+
670
+ const FINISH_FRAGMENT = /* glsl */ `
671
+ varying vec2 vPartFinish;
672
+ `;
673
+
674
+ // The material reads roughness and metalness from each vertex, so parts
675
+ // that differ only in those draw in one call.
676
+ function finishFromVertices(material) {
677
+ const previous = material.onBeforeCompile;
678
+ const previousKey = material.customProgramCacheKey;
679
+ material.onBeforeCompile = (shader, renderer) => {
680
+ previous.call(material, shader, renderer);
681
+ shader.vertexShader = FINISH_VERTEX + shader.vertexShader;
682
+ shader.vertexShader = shader.vertexShader.replace(
683
+ '#include <begin_vertex>',
684
+ '#include <begin_vertex>\nvPartFinish = partFinish;'
685
+ );
686
+ shader.fragmentShader = FINISH_FRAGMENT + shader.fragmentShader;
687
+ shader.fragmentShader = shader.fragmentShader
688
+ .replace('#include <roughnessmap_fragment>', 'float roughnessFactor = vPartFinish.x;')
689
+ .replace('#include <metalnessmap_fragment>', 'float metalnessFactor = vPartFinish.y;');
690
+ };
691
+ material.customProgramCacheKey = () => `part-finish|${previousKey.call(material)}`;
692
+ }
693
+
694
+ //
695
+ // Budget
696
+ //
697
+
698
+ // Shrinking never merges vertices further apart than this many pixels.
699
+ const SHRINK_PIXELS = 4;
700
+
701
+ // Meshes under this many triangles are left as they are.
702
+ const SMALLEST_SHRINK = 150;
703
+
704
+ // A mesh keeps at least this share of its triangles.
705
+ const LEAST_KEPT = 0.2;
706
+
707
+ // When the model is over its budget, every mesh big enough to matter is
708
+ // shrunk by the same share, found so the total fits. Copies share their
709
+ // geometry, which is shrunk once. Textured meshes are left alone, since
710
+ // their texture coordinates would smear.
711
+ function fitBudget(meshes, budget) {
712
+ const uses = new Map();
713
+ for (const mesh of meshes) {
714
+ uses.set(mesh.geometry, (uses.get(mesh.geometry) ?? 0) + 1);
715
+ }
716
+ let fixed = 0;
717
+ let shrinkable = 0;
718
+ for (const [geometry, count] of uses) {
719
+ const triangles = triangleCount(geometry) * count;
720
+ const textured = meshes.some((mesh) => mesh.geometry === geometry && mesh.material.map);
721
+ if (textured || triangleCount(geometry) < SMALLEST_SHRINK) {
722
+ fixed += triangles;
723
+ uses.delete(geometry);
724
+ } else {
725
+ shrinkable += triangles;
726
+ }
727
+ }
728
+ if (fixed + shrinkable <= budget || shrinkable === 0) {
729
+ return;
730
+ }
731
+ const share = Math.max(LEAST_KEPT, (budget - fixed) / shrinkable);
732
+ const replaced = new Map();
733
+ for (const geometry of uses.keys()) {
734
+ const mesh = meshes.find((candidate) => candidate.geometry === geometry);
735
+ const coarsest = (SHRINK_PIXELS * DETAIL_PIXEL) / mesh.matrixWorld.getMaxScaleOnAxis();
736
+ const target = Math.ceil(triangleCount(geometry) * share);
737
+ replaced.set(geometry, shrinkGeometry(geometry, target, coarsest));
738
+ }
739
+ for (const mesh of meshes) {
740
+ mesh.geometry = replaced.get(mesh.geometry) ?? mesh.geometry;
741
+ }
742
+ }
743
+
744
+ // The geometry with its vertices clustered into a grid, coarse enough to
745
+ // leave at most `target` triangles, or as few as cells of `coarsest` leave.
746
+ // When the coarsest cells leave too few, the cell size is found by halving
747
+ // the range between too fine and too coarse.
748
+ function shrinkGeometry(geometry, target, coarsest) {
749
+ geometry.computeBoundingBox();
750
+ const size = geometry.boundingBox.getSize(new THREE.Vector3()).length();
751
+ let fine = size / 2000;
752
+ let coarse = Math.min(size / 3, coarsest);
753
+ if (fine >= coarse) {
754
+ return geometry;
755
+ }
756
+ const kinds = vertexKinds(geometry);
757
+ let best = clusterVertices(geometry, coarse, kinds);
758
+ if (triangleCount(best) >= triangleCount(geometry)) {
759
+ return geometry;
760
+ }
761
+ for (let step = 0; step < 8 && triangleCount(best) < target; step++) {
762
+ const cell = Math.sqrt(fine * coarse);
763
+ const clustered = clusterVertices(geometry, cell, kinds);
764
+ if (triangleCount(clustered) <= target) {
765
+ best = clustered;
766
+ coarse = cell;
767
+ } else {
768
+ fine = cell;
769
+ }
770
+ }
771
+ best.userData = { ...geometry.userData };
772
+ return best;
773
+ }
774
+
775
+ // A number per vertex for which way it faces and its color, each rounded to
776
+ // a few steps. Vertices of different kinds are never merged, which keeps the
777
+ // sides of thin parts, sharp edges, and the borders of paint.
778
+ function vertexKinds(geometry) {
779
+ const normal = geometry.getAttribute('normal');
780
+ const color = geometry.getAttribute('color');
781
+ const count = geometry.getAttribute('position').count;
782
+ const kinds = new Float64Array(count);
783
+ const bucket = (value, steps) => Math.round((value + 1) * steps);
784
+ for (let i = 0; i < count; i++) {
785
+ let facing = 0;
786
+ if (normal) {
787
+ facing = bucket(normal.getX(i), 1.5) * 25 + bucket(normal.getY(i), 1.5) * 5;
788
+ facing += bucket(normal.getZ(i), 1.5);
789
+ }
790
+ let shade = 0;
791
+ if (color) {
792
+ shade = bucket(color.getX(i) * 2 - 1, 6) * 169 + bucket(color.getY(i) * 2 - 1, 6) * 13;
793
+ shade += bucket(color.getZ(i) * 2 - 1, 6);
794
+ }
795
+ kinds[i] = facing * 4096 + shade;
796
+ }
797
+ return kinds;
798
+ }
799
+
800
+ // Vertex clustering: every vertex falls in a grid cell of `cell` meters, and
801
+ // all the vertices of one kind in one cell become one, at their average.
802
+ // Triangles whose corners meet in one vertex are dropped.
803
+ function clusterVertices(geometry, cell, kinds) {
804
+ const position = geometry.getAttribute('position');
805
+ const normal = geometry.getAttribute('normal');
806
+ const color = geometry.getAttribute('color');
807
+ const index = geometry.getIndex();
808
+ const low = geometry.boundingBox.min;
809
+ const ids = new Map();
810
+ const vertexOf = new Int32Array(position.count);
811
+ const sums = [];
812
+ for (let i = 0; i < position.count; i++) {
813
+ const x = Math.min(1023, Math.floor((position.getX(i) - low.x) / cell));
814
+ const y = Math.min(1023, Math.floor((position.getY(i) - low.y) / cell));
815
+ const z = Math.min(1023, Math.floor((position.getZ(i) - low.z) / cell));
816
+ const key = ((x * 1024 + y) * 1024 + z) * 524288 + kinds[i];
817
+ let id = ids.get(key);
818
+ if (id === undefined) {
819
+ id = sums.length / 10;
820
+ ids.set(key, id);
821
+ sums.push(0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
822
+ }
823
+ vertexOf[i] = id;
824
+ addVertex(sums, id * 10, i, [position, normal, color]);
825
+ }
826
+ const indices = [];
827
+ const count = index ? index.count : position.count;
828
+ for (let n = 0; n + 2 < count; n += 3) {
829
+ const a = vertexOf[index ? index.getX(n) : n];
830
+ const b = vertexOf[index ? index.getX(n + 1) : n + 1];
831
+ const c = vertexOf[index ? index.getX(n + 2) : n + 2];
832
+ if (a !== b && b !== c && c !== a) {
833
+ indices.push(a, b, c);
834
+ }
835
+ }
836
+ return clusteredGeometry(sums, indices, Boolean(normal), Boolean(color));
837
+ }
838
+
839
+ // Adds vertex `i` into the running sums of its cluster at `at`: position,
840
+ // normal and color, then a count.
841
+ function addVertex(sums, at, i, attributes) {
842
+ attributes.forEach((attribute, slot) => {
843
+ if (attribute) {
844
+ sums[at + slot * 3] += attribute.getX(i);
845
+ sums[at + slot * 3 + 1] += attribute.getY(i);
846
+ sums[at + slot * 3 + 2] += attribute.getZ(i);
847
+ }
848
+ });
849
+ sums[at + 9] += 1;
850
+ }
851
+
852
+ function clusteredGeometry(sums, indices, hasNormal, hasColor) {
853
+ const count = sums.length / 10;
854
+ const positions = new Float32Array(count * 3);
855
+ const normals = new Float32Array(count * 3);
856
+ const colors = new Float32Array(count * 3);
857
+ const direction = new THREE.Vector3();
858
+ for (let id = 0; id < count; id++) {
859
+ const at = id * 10;
860
+ const n = sums[at + 9];
861
+ positions.set([sums[at] / n, sums[at + 1] / n, sums[at + 2] / n], id * 3);
862
+ direction.set(sums[at + 3], sums[at + 4], sums[at + 5]).normalize();
863
+ normals.set([direction.x, direction.y, direction.z], id * 3);
864
+ colors.set([sums[at + 6] / n, sums[at + 7] / n, sums[at + 8] / n], id * 3);
865
+ }
866
+ const geometry = new THREE.BufferGeometry();
867
+ geometry.setAttribute('position', new THREE.BufferAttribute(positions, 3));
868
+ if (hasNormal) {
869
+ geometry.setAttribute('normal', new THREE.BufferAttribute(normals, 3));
870
+ }
871
+ if (hasColor) {
872
+ geometry.setAttribute('color', new THREE.BufferAttribute(colors, 3));
873
+ }
874
+ geometry.setIndex(indices);
875
+ return geometry;
876
+ }
877
+
878
+ //
879
+ // Placed models
880
+ //
881
+
882
+ // world3d builds each model once, keyed by everything that decides how it
883
+ // looks, and every actor placing it shares that build's geometry and
884
+ // materials. `build` makes the model the first time.
885
+ export function takeModel(cache, key, build) {
886
+ let entry = cache.get(key);
887
+ if (!entry) {
888
+ entry = { template: build(), users: 0 };
889
+ cache.set(key, entry);
890
+ }
891
+ entry.users++;
892
+ return entry.template;
893
+ }
894
+
895
+ // Gives back one actor's use of a shared build. The last one out disposes it.
896
+ export function releaseModel(cache, key, dispose) {
897
+ const entry = cache.get(key);
898
+ if (!entry) {
899
+ return;
900
+ }
901
+ entry.users--;
902
+ if (entry.users <= 0) {
903
+ dispose(entry.template);
904
+ cache.delete(key);
905
+ }
906
+ }
907
+
908
+ // A copy of a shared build for one actor, with its own part groups so the
909
+ // walk animation moves this copy alone. Geometry and materials are shared.
910
+ export function copyModel(template) {
911
+ const copy = template.clone(true);
912
+ const parts = new Map();
913
+ copy.traverse((object) => {
914
+ if (object.userData.partId) {
915
+ parts.set(object.userData.partId, object);
916
+ }
917
+ });
918
+ copy.userData.modelParts = parts;
919
+ return copy;
920
+ }
921
+
922
+ // A model with no walk-animation parts and no motion never moves inside itself.
923
+ export function isStaticModel(template) {
924
+ const parts = template.userData.modelParts;
925
+ if (template.userData.animation) {
926
+ return false;
927
+ }
928
+ return !parts || ANIMATED_PARTS.every((id) => !parts.has(id));
929
+ }
930
+
931
+ // Actors placing the same static model are drawn together: one
932
+ // InstancedMesh per mesh of the model, with an instance per actor (and per
933
+ // copy, for a mesh the model already instances). `rigs` holds each actor's
934
+ // rig group, whose world matrix places its copy.
935
+ export function makeInstances(template, scene) {
936
+ template.updateMatrixWorld(true);
937
+ const parts = [];
938
+ template.traverseVisible((object) => {
939
+ if (!object.isMesh) {
940
+ return;
941
+ }
942
+ const sides = [[], []];
943
+ for (let n = 0; n < (object.isInstancedMesh ? object.count : 1); n++) {
944
+ const local = object.matrixWorld.clone();
945
+ if (object.isInstancedMesh) {
946
+ object.getMatrixAt(n, placed);
947
+ local.multiply(placed);
948
+ }
949
+ sides[local.determinant() < 0 ? 1 : 0].push(local);
950
+ }
951
+ sides.forEach((locals, mirrored) => {
952
+ if (locals.length > 0) {
953
+ parts.push({ source: object, locals, mirrored: mirrored === 1, mesh: null, capacity: 0 });
954
+ }
955
+ });
956
+ });
957
+ const bounds = new THREE.Box3().setFromObject(template).getBoundingSphere(new THREE.Sphere());
958
+ return { scene, parts, bounds, rigs: new Set() };
959
+ }
960
+
961
+ // A copy counts as in view this far outside the camera's view, in meters,
962
+ // so a shadow cast into view from just outside it stays.
963
+ const VIEW_MARGIN = 2;
964
+
965
+ const frustum = new THREE.Frustum();
966
+ const viewMatrix = new THREE.Matrix4();
967
+ const around = new THREE.Sphere();
968
+
969
+ // Writes the placement of every actor that is shown and in `camera`'s view
970
+ // into the instanced meshes, growing them when there are more actors than
971
+ // room. An actor is shown when its rig and every group above it are.
972
+ export function drawInstances(instances, camera) {
973
+ const shown = [...instances.rigs].filter((rig) => isShown(rig) && inView(instances, rig, camera));
974
+ for (const part of instances.parts) {
975
+ const count = shown.length * part.locals.length;
976
+
977
+ // With nothing shown on the first draw there is no mesh yet; draw nothing.
978
+ if (count === 0 && !part.mesh) {
979
+ continue;
980
+ }
981
+ if (count > part.capacity || !part.mesh) {
982
+ part.capacity = Math.max(8, count * 2);
983
+ replaceInstancedMesh(instances.scene, part);
984
+ }
985
+ let n = 0;
986
+ for (const rig of shown) {
987
+ for (const local of part.locals) {
988
+ placed.multiplyMatrices(rig.matrixWorld, local);
989
+ part.mesh.setMatrixAt(n++, part.mirrored ? placed.premultiply(MIRROR) : placed);
990
+ }
991
+ }
992
+ part.mesh.count = count;
993
+ part.mesh.instanceMatrix.needsUpdate = true;
994
+ }
995
+ }
996
+
997
+ function isShown(rig) {
998
+ for (let object = rig; object; object = object.parent) {
999
+ if (!object.visible) {
1000
+ return false;
1001
+ }
1002
+ }
1003
+ return true;
1004
+ }
1005
+
1006
+ function inView(instances, rig, camera) {
1007
+ rig.updateWorldMatrix(true, false);
1008
+ if (!camera) {
1009
+ return true;
1010
+ }
1011
+ around.copy(instances.bounds).applyMatrix4(rig.matrixWorld);
1012
+ around.radius += VIEW_MARGIN;
1013
+ return frustum.intersectsSphere(around);
1014
+ }
1015
+
1016
+ // Sets `frustum` to the camera's view; drawInstances culls against it.
1017
+ export function aimInstances(camera) {
1018
+ camera.updateMatrixWorld();
1019
+ viewMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
1020
+ frustum.setFromProjectionMatrix(viewMatrix);
1021
+ }
1022
+
1023
+ // Copies are culled one by one in drawInstances, so the instanced mesh is
1024
+ // never culled as a whole.
1025
+ function replaceInstancedMesh(scene, part) {
1026
+ if (part.mesh) {
1027
+ scene.remove(part.mesh);
1028
+ part.mesh.dispose();
1029
+ }
1030
+ const { source } = part;
1031
+ const mesh = makeInstanced(source, part.capacity, part.mirrored);
1032
+ mesh.castShadow = source.castShadow;
1033
+ mesh.receiveShadow = source.receiveShadow;
1034
+ mesh.frustumCulled = false;
1035
+ mesh.userData.lookOutline = source.userData.lookOutline;
1036
+ mesh.raycast = () => {};
1037
+ part.mesh = mesh;
1038
+ scene.add(mesh);
1039
+ }
1040
+
1041
+ export function removeInstances(instances) {
1042
+ for (const part of instances.parts) {
1043
+ if (part.mesh) {
1044
+ instances.scene.remove(part.mesh);
1045
+ part.mesh.dispose();
1046
+ }
1047
+ }
1048
+ }
1049
+
1050
+ //
1051
+ // Cost
1052
+ //
1053
+
1054
+ // What drawing the node costs: its triangles, the triangles its outlines
1055
+ // (look.js) draw again, draw calls, shadow casters and materials. Instanced
1056
+ // meshes count every instance's triangles and one call.
1057
+ export function modelCost(node) {
1058
+ const cost = { triangles: 0, outlineTriangles: 0, drawCalls: 0, shadowCasters: 0, materials: 0 };
1059
+ const materials = new Set();
1060
+ node.traverseVisible((object) => {
1061
+ if (!object.isMesh) {
1062
+ return;
1063
+ }
1064
+ const geometry = object.geometry;
1065
+ const instances = object.isInstancedMesh ? object.count : 1;
1066
+ const calls = Array.isArray(object.material) ? Math.max(1, geometry.groups.length) : 1;
1067
+ const triangles = triangleCount(geometry) * instances;
1068
+ if (object.userData.lookOutline) {
1069
+ cost.outlineTriangles += triangles;
1070
+ } else {
1071
+ cost.triangles += triangles;
1072
+ }
1073
+ cost.drawCalls += calls;
1074
+ if (object.castShadow) {
1075
+ cost.shadowCasters += calls;
1076
+ }
1077
+ [object.material].flat().forEach((material) => materials.add(material));
1078
+ });
1079
+ cost.triangles = Math.round(cost.triangles);
1080
+ cost.outlineTriangles = Math.round(cost.outlineTriangles);
1081
+ cost.materials = materials.size;
1082
+ return cost;
1083
+ }