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,560 @@
1
+ // Motion for `.pxmodel` parts: the per-part `motion` field (waves, spin,
2
+ // flicker, blink), the gaits named by part id (four legs, wings, tail, head),
3
+ // and the model's named `clips`, played from game code. See the Animation
4
+ // section of docs/pxmodel-format.md.
5
+ //
6
+ // The biped walk is animateModelParts in pxmodel.js. It runs first each frame
7
+ // and sets its channels outright; motion here adds to what it leaves.
8
+
9
+ const DEG = Math.PI / 180;
10
+ const TAU = Math.PI * 2;
11
+
12
+ // Part ids with a gait of their own here.
13
+ export const GAIT_PARTS = ['legFL', 'legFR', 'legBL', 'legBR', 'wingL', 'wingR', 'tail', 'head'];
14
+
15
+ const CHANNELS = ['rotate', 'move', 'scale'];
16
+
17
+ // A blink squashes the part to this height for this many seconds.
18
+ const BLINK_SCALE = 0.1;
19
+ const BLINK_SECONDS = 0.15;
20
+
21
+ // Flicker picks a new brightness this many times a second at speed 1.
22
+ const FLICKER_RATE = 10;
23
+
24
+ // The walk phase advances this many radians per meter, as in
25
+ // animateModelParts, and a walk is full at WALK_SPEED meters per second.
26
+ const STRIDE = 2.4;
27
+ const WALK_SPEED = 5;
28
+
29
+ // How fast a node rises or falls over the ground. A scene whose
30
+ // `userData.groundHeight(x, z)` is set (a deck's terrain) has slopes, and
31
+ // walking up one is not a fall; without it this is plain vertical speed.
32
+ export function airSpeed(node, position, last, dt) {
33
+ const groundHeight = node.parent?.userData?.groundHeight;
34
+ if (typeof groundHeight !== 'function') {
35
+ return (position.y - last.y) / dt;
36
+ }
37
+ const over = position.y - groundHeight(position.x, position.z);
38
+ const lastOver = last.y - groundHeight(last.x, last.z);
39
+ return (over - lastOver) / dt;
40
+ }
41
+
42
+ //
43
+ // Reading the model
44
+ //
45
+
46
+ function finite(value, fallback) {
47
+ return Number.isFinite(value) ? value : fallback;
48
+ }
49
+
50
+ function readVec3(value) {
51
+ if (!Array.isArray(value)) {
52
+ return null;
53
+ }
54
+ return [0, 1, 2].map((i) => finite(value[i], 0));
55
+ }
56
+
57
+ function readMotion(raw) {
58
+ if (!raw || typeof raw !== 'object') {
59
+ return null;
60
+ }
61
+ return {
62
+ rotate: readVec3(raw.rotate),
63
+ move: readVec3(raw.move),
64
+ scale: readVec3(raw.scale),
65
+ spin: readVec3(raw.spin),
66
+ speed: finite(raw.speed, 1),
67
+ phase: finite(raw.phase, 0),
68
+ when: ['idle', 'walk'].includes(raw.when) ? raw.when : 'always',
69
+ flicker: finite(raw.flicker, 0),
70
+ blink: raw.blink > 0 ? raw.blink : 0,
71
+ };
72
+ }
73
+
74
+ // `ripple: true` spreads one whole cycle over a part's copies; a number is
75
+ // the phase step from one copy to the next.
76
+ function rippleStep(part) {
77
+ if (Number.isFinite(part.ripple)) {
78
+ return part.ripple;
79
+ }
80
+ if (part.ripple !== true) {
81
+ return 0;
82
+ }
83
+ const count = part.repeat?.count ?? part.scatter?.count ?? 1;
84
+ return 1 / Math.max(1, count);
85
+ }
86
+
87
+ // Keys are `[time, [x, y, z]]`, kept in time order.
88
+ function readKeys(raw) {
89
+ if (!Array.isArray(raw)) {
90
+ return [];
91
+ }
92
+ return raw
93
+ .filter((key) => Array.isArray(key) && Number.isFinite(key[0]))
94
+ .map((key) => [key[0], readVec3(key[1]) ?? [0, 0, 0]])
95
+ .sort((a, b) => a[0] - b[0]);
96
+ }
97
+
98
+ function readClip(raw) {
99
+ if (!raw || typeof raw !== 'object' || !raw.tracks || typeof raw.tracks !== 'object') {
100
+ return null;
101
+ }
102
+ const tracks = {};
103
+ let end = 0;
104
+ for (const [id, channels] of Object.entries(raw.tracks)) {
105
+ const track = {};
106
+ for (const channel of CHANNELS) {
107
+ const keys = readKeys(channels?.[channel]);
108
+ if (keys.length > 0) {
109
+ track[channel] = keys;
110
+ end = Math.max(end, keys[keys.length - 1][0]);
111
+ }
112
+ }
113
+ tracks[id] = track;
114
+ }
115
+ return { duration: raw.duration > 0 ? raw.duration : end, tracks };
116
+ }
117
+
118
+ // What moves in a model, or null for a still one: `parts` is every part id
119
+ // that moves (motion, a gait of its own, or a clip track), which optimize.js
120
+ // keeps apart from merging. The result is plain JSON, since node clones copy
121
+ // it with the node's userData.
122
+ export function modelAnimation(model) {
123
+ const ids = new Set(model.parts.map((part) => part.id));
124
+ const motion = {};
125
+ const ripple = {};
126
+ for (const part of model.parts) {
127
+ const list = [part.motion].flat().map(readMotion).filter(Boolean);
128
+ if (list.length > 0) {
129
+ motion[part.id] = list;
130
+ ripple[part.id] = rippleStep(part);
131
+ }
132
+ }
133
+ const clips = {};
134
+ for (const [name, raw] of Object.entries(model.clips ?? {})) {
135
+ const clip = readClip(raw);
136
+ if (clip) {
137
+ clips[name] = clip;
138
+ }
139
+ }
140
+
141
+ // A `head` only looks around on a model that walks, so a hammer's head or a
142
+ // statue's stays put.
143
+ const walks = ['legL', 'legR', 'legFL', 'legFR', 'legBL', 'legBR'].some((id) => ids.has(id));
144
+ const moving = [
145
+ ...Object.keys(motion),
146
+ ...GAIT_PARTS.filter((id) => id !== 'head' || walks),
147
+ ...Object.values(clips).flatMap((clip) => Object.keys(clip.tracks)),
148
+ ];
149
+ const parts = [...new Set(moving)].filter((id) => ids.has(id));
150
+ if (parts.length === 0 && Object.keys(clips).length === 0) {
151
+ return null;
152
+ }
153
+ return { parts, motion, ripple, clips, walks };
154
+ }
155
+
156
+ //
157
+ // Clips
158
+ //
159
+
160
+ // Plays the model clip `name` once on the actor's model. Callable from a
161
+ // behavior: `playModelClip(actor, 'wave')`. A clip the model lacks does
162
+ // nothing; a new call restarts the clip.
163
+ export function playModelClip(actor, name) {
164
+ const runtime = actor?.runtime;
165
+ if (!runtime) {
166
+ return;
167
+ }
168
+ runtime.modelClip = { name, count: (runtime.modelClip?.count ?? 0) + 1 };
169
+ }
170
+
171
+ function updateClip(state, actor, dt) {
172
+ const request = actor?.runtime?.modelClip;
173
+ if (request && request.count !== state.clipCount) {
174
+ state.clipCount = request.count;
175
+ const clip = state.animation.clips[request.name];
176
+ state.clip = clip ? { clip, time: 0 } : null;
177
+ return;
178
+ }
179
+ if (state.clip) {
180
+ state.clip.time += dt;
181
+ if (state.clip.time > state.clip.clip.duration) {
182
+ state.clip = null;
183
+ }
184
+ }
185
+ }
186
+
187
+ // The value at `time`, eased in and out between keys.
188
+ function sampleKeys(keys, time) {
189
+ if (time <= keys[0][0]) {
190
+ return keys[0][1];
191
+ }
192
+ for (let n = 1; n < keys.length; n++) {
193
+ const [end, to] = keys[n];
194
+ if (time <= end) {
195
+ const [start, from] = keys[n - 1];
196
+ const t = (time - start) / Math.max(1e-6, end - start);
197
+ const s = t * t * (3 - 2 * t);
198
+ return from.map((value, i) => value + (to[i] - value) * s);
199
+ }
200
+ }
201
+ return keys[keys.length - 1][1];
202
+ }
203
+
204
+ // A clip track sets its channels from the rest pose, over whatever the walk
205
+ // or motion did to them.
206
+ function applyClip(pose, target, state) {
207
+ const track = state.clip?.clip.tracks[target.id];
208
+ if (!track) {
209
+ return;
210
+ }
211
+ const time = state.clip.time;
212
+ const rest = target.rest;
213
+ for (let i = 0; i < 3; i++) {
214
+ if (track.move) {
215
+ pose[i] = rest[i] + sampleKeys(track.move, time)[i];
216
+ }
217
+ if (track.rotate) {
218
+ pose[3 + i] = rest[3 + i] + sampleKeys(track.rotate, time)[i] * DEG;
219
+ }
220
+ if (track.scale) {
221
+ pose[6 + i] = rest[6 + i] * (1 + sampleKeys(track.scale, time)[i]);
222
+ }
223
+ }
224
+ }
225
+
226
+ //
227
+ // Walking
228
+ //
229
+
230
+ // How much the node walks (0 to 1), how much it is in the air, and a phase
231
+ // that advances with distance walked, observed from its position.
232
+ function observeWalk(walk, node, dt) {
233
+ const p = node.position;
234
+ if (walk.last) {
235
+ const speed = Math.hypot(p.x - walk.last.x, p.z - walk.last.z) / dt;
236
+ const rise = airSpeed(node, p, walk.last, dt);
237
+ walk.amount += (Math.min(1, speed / WALK_SPEED) - walk.amount) * Math.min(1, dt * 10);
238
+ walk.air += ((Math.abs(rise) > 1.2 ? 1 : 0) - walk.air) * Math.min(1, dt * 8);
239
+ walk.phase += Math.min(speed, 8) * STRIDE * dt;
240
+ }
241
+ walk.last = { x: p.x, y: p.y, z: p.z };
242
+ }
243
+
244
+ // Diagonal legs move together: front left with back right.
245
+ const LEG_SIDES = { legFL: 1, legBR: 1, legFR: -1, legBL: -1 };
246
+
247
+ function gaitLeg(pose, target, state) {
248
+ const walk = state.walk;
249
+ const swing = Math.sin(walk.phase) * 0.6 * walk.amount * (1 - walk.air);
250
+
251
+ // In the air the front legs reach forward and the back legs back.
252
+ const tuck = target.id.startsWith('legF') ? -0.5 : 0.5;
253
+ pose[3] += LEG_SIDES[target.id] * swing + tuck * walk.air;
254
+ }
255
+
256
+ // Wings beat fast while moving or in the air and slowly at rest. A wing on
257
+ // the -x side turns the other way, so both rise together.
258
+ function gaitWing(pose, target, state, dt) {
259
+ const walk = state.walk;
260
+ const active = Math.max(walk.amount, walk.air);
261
+ target.cycle += TAU * dt * (0.5 + 3 * active);
262
+ pose[5] += target.side * Math.sin(target.cycle) * (10 + 40 * active) * DEG;
263
+ }
264
+
265
+ function gaitTail(pose, target, state, dt) {
266
+ const amount = state.walk.amount;
267
+ target.cycle += TAU * dt * (0.7 + 2.3 * amount);
268
+ pose[4] += Math.sin(target.cycle) * (12 + 10 * amount) * DEG;
269
+ }
270
+
271
+ // Two slow waves of different lengths, so the looking around does not repeat
272
+ // visibly. It fades out while walking.
273
+ function gaitHead(pose, target, state) {
274
+ const time = state.clock;
275
+ const idle = 1 - state.walk.amount;
276
+ const yaw = Math.sin(TAU * 0.13 * time) * 18 + Math.sin(TAU * 0.31 * time + 1) * 7;
277
+ const pitch = Math.sin(TAU * 0.21 * time + 2) * 4;
278
+ pose[4] += yaw * DEG * idle;
279
+ pose[3] += pitch * DEG * idle;
280
+ }
281
+
282
+ const GAITS = {
283
+ legFL: gaitLeg,
284
+ legFR: gaitLeg,
285
+ legBL: gaitLeg,
286
+ legBR: gaitLeg,
287
+ wingL: gaitWing,
288
+ wingR: gaitWing,
289
+ tail: gaitTail,
290
+ head: gaitHead,
291
+ };
292
+
293
+ //
294
+ // Motion
295
+ //
296
+
297
+ function whenWeight(when, walk) {
298
+ if (when === 'idle') {
299
+ return 1 - walk.amount;
300
+ }
301
+ if (when === 'walk') {
302
+ return walk.amount;
303
+ }
304
+ return 1;
305
+ }
306
+
307
+ // Smooth noise from -1 to 1: random values at whole numbers, eased between.
308
+ function noise(x, seed) {
309
+ const random = (n) => {
310
+ const s = Math.sin(n * 127.1 + seed * 311.7) * 43758.5453;
311
+ return (s - Math.floor(s)) * 2 - 1;
312
+ };
313
+ const whole = Math.floor(x);
314
+ const t = x - whole;
315
+ const a = random(whole);
316
+ return a + (random(whole + 1) - a) * t * t * (3 - 2 * t);
317
+ }
318
+
319
+ function applyWave(pose, motion, wave) {
320
+ for (let i = 0; i < 3; i++) {
321
+ if (motion.move) {
322
+ pose[i] += motion.move[i] * wave;
323
+ }
324
+ if (motion.rotate) {
325
+ pose[3 + i] += motion.rotate[i] * DEG * wave;
326
+ }
327
+ if (motion.scale) {
328
+ pose[6 + i] *= 1 + motion.scale[i] * wave;
329
+ }
330
+ }
331
+ }
332
+
333
+ function applyMotion(pose, motion, target, state, dt) {
334
+ const weight = whenWeight(motion.when, state.walk);
335
+ const cycles = motion.speed * state.clock + motion.phase + target.ripple;
336
+ applyWave(pose, motion, Math.sin(TAU * cycles) * weight);
337
+ if (motion.spin) {
338
+ for (let i = 0; i < 3; i++) {
339
+ target.spin[i] = (target.spin[i] + motion.spin[i] * dt * weight) % 360;
340
+ pose[3 + i] += target.spin[i] * DEG;
341
+ }
342
+ }
343
+ if (motion.blink && weight > 0.5) {
344
+ const period = motion.blink;
345
+ const at =
346
+ (((state.clock + (motion.phase + target.ripple) * period) % period) + period) % period;
347
+ if (at < BLINK_SECONDS) {
348
+ pose[7] *= BLINK_SCALE;
349
+ }
350
+ }
351
+ if (motion.flicker) {
352
+ const bright =
353
+ 1 + motion.flicker * noise(state.clock * motion.speed * FLICKER_RATE, target.index);
354
+ setGlow(target, Math.max(0, bright * weight + (1 - weight)));
355
+ }
356
+ }
357
+
358
+ //
359
+ // Glow
360
+ //
361
+
362
+ // The meshes of a flickering part, with their own copy of what holds the
363
+ // glow: a material, or for a merged batch (optimize.js) the geometry's
364
+ // per-vertex glow. The part's children are theirs to flicker.
365
+ function glowSources(object) {
366
+ const sources = [];
367
+ const visit = (node) => {
368
+ for (const child of node.children) {
369
+ if (child.userData.partId || child.userData.copyOf) {
370
+ continue;
371
+ }
372
+ if (child.isMesh && !child.userData.lookOutline) {
373
+ sources.push(ownGlow(child));
374
+ }
375
+ visit(child);
376
+ }
377
+ };
378
+ visit(object);
379
+ return sources;
380
+ }
381
+
382
+ function ownGlow(mesh) {
383
+ const vertexGlow = mesh.geometry.getAttribute('partGlow');
384
+ if (vertexGlow) {
385
+ mesh.geometry = mesh.geometry.clone();
386
+ const attribute = mesh.geometry.getAttribute('partGlow');
387
+ return { attribute, base: Float32Array.from(attribute.array) };
388
+ }
389
+ const shared = mesh.material;
390
+ if (Array.isArray(shared)) {
391
+ return { materials: [] };
392
+ }
393
+
394
+ // Material.clone leaves out the shader hooks look.js and optimize.js add.
395
+ const own = shared.clone();
396
+ own.onBeforeCompile = shared.onBeforeCompile;
397
+ own.customProgramCacheKey = shared.customProgramCacheKey;
398
+ mesh.material = own;
399
+ return { material: own, base: own.emissiveIntensity };
400
+ }
401
+
402
+ function setGlow(target, bright) {
403
+ for (const source of (target.glow ??= glowSources(target.object))) {
404
+ if (source.material) {
405
+ source.material.emissiveIntensity = source.base * bright;
406
+ } else if (source.attribute) {
407
+ const array = source.attribute.array;
408
+ for (let i = 0; i < array.length; i++) {
409
+ array[i] = source.base[i] * bright;
410
+ }
411
+ source.attribute.needsUpdate = true;
412
+ }
413
+ }
414
+ }
415
+
416
+ //
417
+ // Poses
418
+ //
419
+
420
+ // A pose is nine numbers: position, rotation (radians) and scale.
421
+ function readPose(object) {
422
+ const { position, rotation, scale } = object;
423
+ return [
424
+ position.x,
425
+ position.y,
426
+ position.z,
427
+ rotation.x,
428
+ rotation.y,
429
+ rotation.z,
430
+ scale.x,
431
+ scale.y,
432
+ scale.z,
433
+ ];
434
+ }
435
+
436
+ function writePose(object, pose) {
437
+ object.position.set(pose[0], pose[1], pose[2]);
438
+ object.rotation.set(pose[3], pose[4], pose[5]);
439
+ object.scale.set(pose[6], pose[7], pose[8]);
440
+ }
441
+
442
+ // Where the part starts this frame: the rest pose, except for channels
443
+ // someone else (the biped walk) set since this module last wrote them.
444
+ function frameBase(target) {
445
+ const current = readPose(target.object);
446
+ if (!target.written) {
447
+ return target.rest.slice();
448
+ }
449
+ return current.map((value, i) => (value !== target.written[i] ? value : target.rest[i]));
450
+ }
451
+
452
+ function poseTarget(target, state, dt) {
453
+ const pose = frameBase(target);
454
+ target.gait?.(pose, target, state, dt);
455
+ for (const motion of target.motions) {
456
+ applyMotion(pose, motion, target, state, dt);
457
+ }
458
+ applyClip(pose, target, state);
459
+ writePose(target.object, pose);
460
+ target.written = pose;
461
+ }
462
+
463
+ //
464
+ // Per actor
465
+ //
466
+
467
+ // The copy made last of a part (by mirror, repeat, scatter or tips) holds the
468
+ // part's pivot; the holders around it carry only the copy's placement.
469
+ function copyTarget(object) {
470
+ const id = object.userData.copyOf;
471
+ if (!id || object.children.some((child) => child.userData.copyOf === id)) {
472
+ return null;
473
+ }
474
+ return id;
475
+ }
476
+
477
+ function makeTarget(object, id, index, animation) {
478
+ const motions = animation.motion[id] ?? [];
479
+
480
+ // A wing's side comes from its pivot, or its name when it sits on x = 0.
481
+ const x = object.position.x;
482
+ const side = x !== 0 ? Math.sign(x) : id === 'wingR' ? -1 : 1;
483
+ return {
484
+ object,
485
+ id,
486
+ index,
487
+ rest: readPose(object),
488
+ written: null,
489
+ motions,
490
+ gait: motions.length === 0 && (id !== 'head' || animation.walks) ? (GAITS[id] ?? null) : null,
491
+ ripple: (animation.ripple[id] ?? 0) * index,
492
+ side,
493
+ cycle: 0,
494
+ spin: [0, 0, 0],
495
+ glow: null,
496
+ };
497
+ }
498
+
499
+ // A start time from the actor's id, so copies of one model placed side by
500
+ // side do not move in step.
501
+ function startClock(actor) {
502
+ const id = String(actor?.id ?? '');
503
+ let hash = 0;
504
+ for (let i = 0; i < id.length; i++) {
505
+ hash = (hash * 31 + id.charCodeAt(i)) >>> 0;
506
+ }
507
+ return (hash % 1000) / 100;
508
+ }
509
+
510
+ function setupMotion(entry, actor) {
511
+ const rig = entry.node.children.find((child) => child.userData.animation);
512
+ const animation = rig?.userData.animation;
513
+ if (!animation) {
514
+ return null;
515
+ }
516
+ const wanted = new Set(animation.parts);
517
+ const counts = new Map();
518
+ const targets = [];
519
+ rig.traverse((object) => {
520
+ const id = object.userData.partId ?? copyTarget(object);
521
+ if (!wanted.has(id)) {
522
+ return;
523
+ }
524
+ const index = counts.get(id) ?? 0;
525
+ counts.set(id, index + 1);
526
+ targets.push(makeTarget(object, id, index, animation));
527
+ });
528
+ return {
529
+ animation,
530
+ targets,
531
+ clock: startClock(actor),
532
+ walk: { amount: 0, air: 0, phase: 0, last: null },
533
+ clip: null,
534
+ clipCount: 0,
535
+ };
536
+ }
537
+
538
+ // Moves one actor's model parts for a frame. Called after
539
+ // animateModelParts, with the actor whose clips to play (optional). dt of 0
540
+ // (editor views) leaves the model in its rest pose. The first call finds the
541
+ // parts and moves nothing.
542
+ export function animateMotion(entry, dt, actor = null) {
543
+ if (!(dt > 0)) {
544
+ return;
545
+ }
546
+ if (entry.motionState === undefined) {
547
+ entry.motionState = setupMotion(entry, actor);
548
+ return;
549
+ }
550
+ const state = entry.motionState;
551
+ if (!state) {
552
+ return;
553
+ }
554
+ state.clock += dt;
555
+ observeWalk(state.walk, entry.node, dt);
556
+ updateClip(state, actor, dt);
557
+ for (const target of state.targets) {
558
+ poseTarget(target, state, dt);
559
+ }
560
+ }
@@ -0,0 +1,37 @@
1
+ // OBJ text as a mesh: `v x y z` lines are vertices and `f a b c ...` lines are
2
+ // faces, the plain format most 3d tools and many language models can write.
3
+ //
4
+ // Face entries may be `a`, `a/t`, `a//n` or `a/t/n`; only the vertex index is
5
+ // used, counting from 1, and a negative index counts back from the last
6
+ // vertex. Every other line (normals, texture points, groups, materials,
7
+ // comments) is ignored. `unit` scales every coordinate, so a model can be
8
+ // written in whole numbers -- centimeters with `unit: 0.01`.
9
+
10
+ export function objCage(text, unit = 1) {
11
+ if (typeof text !== 'string') {
12
+ return null;
13
+ }
14
+ const scale = Number.isFinite(unit) && unit > 0 ? unit : 1;
15
+ const vertices = [];
16
+ const faces = [];
17
+ for (const raw of text.split('\n')) {
18
+ const line = raw.trim();
19
+ if (line.startsWith('v ')) {
20
+ const [x, y, z] = line.slice(2).trim().split(/\s+/).map(Number);
21
+ vertices.push([x, y, z].map((value) => (Number.isFinite(value) ? value * scale : 0)));
22
+ } else if (line.startsWith('f ')) {
23
+ const face = line
24
+ .slice(2)
25
+ .trim()
26
+ .split(/\s+/)
27
+ .map((entry) => {
28
+ const index = parseInt(entry.split('/')[0], 10);
29
+ return index < 0 ? vertices.length + index : index - 1;
30
+ });
31
+ if (face.length >= 3 && face.every((index) => Number.isInteger(index) && index >= 0)) {
32
+ faces.push(face);
33
+ }
34
+ }
35
+ }
36
+ return vertices.length && faces.length ? { vertices, faces } : null;
37
+ }