castle-web-cli 0.4.204 → 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 (125) hide show
  1. package/dist/agent-failures.d.ts +3 -1
  2. package/dist/agent-failures.js +19 -0
  3. package/dist/agent-prompts.js +2 -1
  4. package/dist/agent.d.ts +3 -2
  5. package/dist/agent.js +19 -10
  6. package/dist/castle-host/host.d.ts +17 -0
  7. package/dist/castle-host/host.js +551 -4
  8. package/dist/devSessionStorage.js +65 -4
  9. package/dist/effortSupport.d.ts +7 -0
  10. package/dist/effortSupport.js +31 -0
  11. package/dist/init.js +13 -3
  12. package/dist/platformDoc.js +6 -1
  13. package/dist/serve.js +35 -2
  14. package/dist/shell/assets/{index-DHzA0-Sj.js → index-hWQTC8q6.js} +5 -5
  15. package/dist/shell/index.html +1 -1
  16. package/dist/vitePlugins.js +19 -1
  17. package/kits/base/CLAUDE.md +2 -0
  18. package/kits/base/castle.json +1 -1
  19. package/kits/base/sdk/README.md +131 -0
  20. package/kits/base/sdk/agent.d.ts +6 -0
  21. package/kits/base/sdk/agent.js +70 -0
  22. package/kits/base/sdk/castle.d.ts +4 -0
  23. package/kits/base/sdk/castle.js +2 -0
  24. package/kits/base/sdk/commands.d.ts +106 -0
  25. package/kits/base/sdk/commands.js +21 -0
  26. package/kits/base/sdk/decks.d.ts +7 -0
  27. package/kits/base/sdk/decks.js +31 -0
  28. package/kits/base/sdk/runtime.d.ts +4 -2
  29. package/kits/base/sdk/runtime.js +51 -40
  30. package/kits/base/sdk/server/storage.d.ts +44 -0
  31. package/kits/base/sdk/server/storage.js +54 -0
  32. package/kits/base/sdk/transport.d.ts +5 -1
  33. package/kits/base/sdk/transport.js +106 -23
  34. package/kits/multiplayer-2d/castle.json +4 -4
  35. package/kits/multiplayer-2d/code/client/poses.js +7 -0
  36. package/kits/multiplayer-2d/code/server/limits.js +3 -0
  37. package/kits/multiplayer-2d/code/server/ownership.js +36 -8
  38. package/kits/multiplayer-2d/code/systems/multiplayer.js +23 -2
  39. package/kits/multiplayer-3d/CLAUDE.md +12 -1
  40. package/kits/multiplayer-3d/castle.json +4 -4
  41. package/kits/multiplayer-3d/code/client/avatars.js +7 -1
  42. package/kits/multiplayer-3d/code/client/poses.js +61 -1
  43. package/kits/multiplayer-3d/code/client/steer.js +383 -0
  44. package/kits/multiplayer-3d/code/server/limits.js +3 -0
  45. package/kits/multiplayer-3d/code/server/ownership.js +114 -18
  46. package/kits/multiplayer-3d/code/server/world.js +12 -4
  47. package/kits/multiplayer-3d/code/systems/multiplayer.js +315 -34
  48. package/kits/physics-3d/CLAUDE.md +65 -7
  49. package/kits/physics-3d/castle.json +3 -3
  50. package/kits/physics-3d/docs/pxmodel-format.md +916 -15
  51. package/kits/physics-3d/engine3d/PxModelEditor.jsx +2 -2
  52. package/kits/physics-3d/engine3d/artobjects.js +218 -0
  53. package/kits/physics-3d/engine3d/blob.js +1058 -0
  54. package/kits/physics-3d/engine3d/branches.js +300 -0
  55. package/kits/physics-3d/engine3d/cage.js +496 -0
  56. package/kits/physics-3d/engine3d/cageops.js +516 -0
  57. package/kits/physics-3d/engine3d/frame.js +669 -0
  58. package/kits/physics-3d/engine3d/look.js +675 -0
  59. package/kits/physics-3d/engine3d/materialpresets.js +486 -0
  60. package/kits/physics-3d/engine3d/modelEditorWorld.js +3 -2
  61. package/kits/physics-3d/engine3d/modelrefs.js +120 -0
  62. package/kits/physics-3d/engine3d/motion.js +560 -0
  63. package/kits/physics-3d/engine3d/objtext.js +37 -0
  64. package/kits/physics-3d/engine3d/optimize.js +1083 -0
  65. package/kits/physics-3d/engine3d/paint.js +674 -0
  66. package/kits/physics-3d/engine3d/partgeometry.js +467 -0
  67. package/kits/physics-3d/engine3d/paths.js +324 -0
  68. package/kits/physics-3d/engine3d/pxmodel.js +429 -26
  69. package/kits/physics-3d/engine3d/scatter.js +102 -0
  70. package/kits/physics-3d/engine3d/sculpt.js +1148 -0
  71. package/kits/physics-3d/engine3d/surfacedetail.js +267 -0
  72. package/kits/physics-3d/engine3d/sweep.js +480 -0
  73. package/kits/physics-3d/engine3d/thumbnails.js +6 -4
  74. package/kits/physics-3d/engine3d/world3d.js +119 -17
  75. package/kits/physics-3d/eslint.config.js +13 -0
  76. package/kits/physics-3d/models/parts/axe.pxmodel +40 -0
  77. package/kits/physics-3d/models/parts/backpack.pxmodel +47 -0
  78. package/kits/physics-3d/models/parts/barrel.pxmodel +22 -0
  79. package/kits/physics-3d/models/parts/bedroll.pxmodel +28 -0
  80. package/kits/physics-3d/models/parts/belt-pouch.pxmodel +22 -0
  81. package/kits/physics-3d/models/parts/bolt.pxmodel +10 -0
  82. package/kits/physics-3d/models/parts/bracer.pxmodel +26 -0
  83. package/kits/physics-3d/models/parts/chain-span.pxmodel +12 -0
  84. package/kits/physics-3d/models/parts/chimney.pxmodel +11 -0
  85. package/kits/physics-3d/models/parts/crate.pxmodel +44 -0
  86. package/kits/physics-3d/models/parts/crystal.pxmodel +22 -0
  87. package/kits/physics-3d/models/parts/door-arched.pxmodel +12 -0
  88. package/kits/physics-3d/models/parts/engine-block.pxmodel +39 -0
  89. package/kits/physics-3d/models/parts/exhaust-pipe.pxmodel +30 -0
  90. package/kits/physics-3d/models/parts/fence-span.pxmodel +10 -0
  91. package/kits/physics-3d/models/parts/fender.pxmodel +19 -0
  92. package/kits/physics-3d/models/parts/headlight.pxmodel +24 -0
  93. package/kits/physics-3d/models/parts/hood.pxmodel +17 -0
  94. package/kits/physics-3d/models/parts/horned-helmet.pxmodel +37 -0
  95. package/kits/physics-3d/models/parts/jerry-can.pxmodel +26 -0
  96. package/kits/physics-3d/models/parts/ladder.pxmodel +10 -0
  97. package/kits/physics-3d/models/parts/lamp.pxmodel +20 -0
  98. package/kits/physics-3d/models/parts/lantern.pxmodel +30 -0
  99. package/kits/physics-3d/models/parts/leaf-cluster.pxmodel +21 -0
  100. package/kits/physics-3d/models/parts/offroad-tire.pxmodel +48 -0
  101. package/kits/physics-3d/models/parts/pauldron.pxmodel +26 -0
  102. package/kits/physics-3d/models/parts/rivet.pxmodel +8 -0
  103. package/kits/physics-3d/models/parts/rock.pxmodel +21 -0
  104. package/kits/physics-3d/models/parts/roll-bar-light.pxmodel +26 -0
  105. package/kits/physics-3d/models/parts/round-shield.pxmodel +31 -0
  106. package/kits/physics-3d/models/parts/saddlebag.pxmodel +30 -0
  107. package/kits/physics-3d/models/parts/spoked-wheel.pxmodel +39 -0
  108. package/kits/physics-3d/models/parts/staff.pxmodel +33 -0
  109. package/kits/physics-3d/models/parts/stepping-stones.pxmodel +8 -0
  110. package/kits/physics-3d/models/parts/stone-base.pxmodel +10 -0
  111. package/kits/physics-3d/models/parts/sword.pxmodel +33 -0
  112. package/kits/physics-3d/models/parts/window-lit.pxmodel +13 -0
  113. package/kits/physics-3d/models/parts/wizard-hat.pxmodel +28 -0
  114. package/kits/physics-3d/models/templates/biped-stout.pxmodel +59 -0
  115. package/kits/physics-3d/models/templates/biped-tall.pxmodel +63 -0
  116. package/kits/physics-3d/models/templates/quadruped.pxmodel +52 -0
  117. package/kits/physics-3d/scripts/render/filmstrip.js +217 -0
  118. package/kits/physics-3d/scripts/render/index.html +20 -0
  119. package/kits/physics-3d/scripts/render/sheet.js +411 -0
  120. package/kits/physics-3d/scripts/render.mjs +646 -0
  121. package/kits/real-time/castle.json +2 -2
  122. package/kits/real-time/code/client/ownership.js +14 -4
  123. package/kits/real-time/code/client/smooth.js +2 -2
  124. package/kits/real-time/code/server/session.js +20 -4
  125. package/package.json +2 -2
@@ -0,0 +1,646 @@
1
+ // `npm run render -- <model.pxmodel> [more.pxmodel ...]` -- one 1500x700
2
+ // contact sheet png per model, to look at while modeling.
3
+ //
4
+ // A sheet is the game's own camera over a whole card at game size, then eight
5
+ // labeled views on a one-meter ground grid: overhead, front, back, both sides,
6
+ // top, and two 3/4 views from above. Its header gives the part count, the
7
+ // bounds in meters and the model's cost, and is also printed after the png
8
+ // path. Sheets go to `.castle/render/<name>.png`, or to `--out <file.png>`
9
+ // when there is one model.
10
+ //
11
+ // With `--motion` the three pages are a filmstrip of the model's animation
12
+ // instead (render/sheet.js), saved as `<name>-motion.png`.
13
+ //
14
+ // The pixels come from the playtest service, the one a task agent uses. The
15
+ // script builds a scratch deck in `.castle/render/sheet-deck/` -- the page in
16
+ // `render/` plus links to this deck's imports and node_modules -- serves it on
17
+ // a free port, and stops that serve when done. A playtest takes at most six
18
+ // screenshots, so each covers two models of three pages, pressing `n` between
19
+ // pages. The pages are joined side by side here.
20
+
21
+ import { spawn } from 'node:child_process';
22
+ import * as fs from 'node:fs';
23
+ import * as net from 'node:net';
24
+ import * as path from 'node:path';
25
+ import { fileURLToPath } from 'node:url';
26
+ import * as zlib from 'node:zlib';
27
+
28
+ const KIT_RENDER_DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), 'render');
29
+ const DECK = process.cwd();
30
+ const WORK = path.join(DECK, '.castle', 'render');
31
+ const SHEET_DECK = path.join(WORK, 'sheet-deck');
32
+
33
+ // The deck's package.json sets this to the command its other scripts use.
34
+ const CLI = (process.env.CASTLE_WEB_CLI || 'castle-web').trim().split(/\s+/);
35
+
36
+ const PAGES_PER_MODEL = 3;
37
+ const MODELS_PER_PLAYTEST = 2;
38
+ const FIRST_SHOT_MS = 1800;
39
+ const SHOT_SPACING_MS = 500;
40
+ const SERVE_TIMEOUT_MS = 60_000;
41
+
42
+ //
43
+ // Models and their art
44
+ //
45
+
46
+ function artRefsOf(model) {
47
+ const refs = new Set();
48
+ for (const part of model.parts ?? []) {
49
+ const art = part.art;
50
+ let values = [];
51
+ if (typeof art === 'string' || typeof art?.ref === 'string') {
52
+ values = [art];
53
+ } else if (art && typeof art === 'object') {
54
+ values = Object.values(art);
55
+ }
56
+ for (const value of values) {
57
+ // An art object carries its ref in `ref`.
58
+ const ref = value && typeof value === 'object' ? value.ref : value;
59
+ if (typeof ref === 'string' && ref) {
60
+ refs.add(ref.replace(/#\d+$/, ''));
61
+ }
62
+ }
63
+ }
64
+ return [...refs];
65
+ }
66
+
67
+ const IMAGE_TYPES = {
68
+ '.png': 'image/png',
69
+ '.jpg': 'image/jpeg',
70
+ '.jpeg': 'image/jpeg',
71
+ '.gif': 'image/gif',
72
+ '.webp': 'image/webp',
73
+ };
74
+
75
+ // `@imports/<alias>/...` and `imports/<alias>/...` both name the import's file,
76
+ // or the deck's fork of it under `forks/<alias>/...` when that exists. Any other
77
+ // ref is relative to the deck root.
78
+ function artFile(ref) {
79
+ const relative = ref.replace(/^@/, '');
80
+ if (relative.startsWith('imports/')) {
81
+ const fork = path.join(DECK, 'forks', relative.slice('imports/'.length));
82
+ if (fs.existsSync(fork)) {
83
+ return fork;
84
+ }
85
+ }
86
+ return path.join(DECK, relative);
87
+ }
88
+
89
+ function readArt(ref) {
90
+ const file = artFile(ref);
91
+ if (!fs.existsSync(file)) {
92
+ console.warn(`missing art: ${ref}`);
93
+ return null;
94
+ }
95
+ const type = IMAGE_TYPES[path.extname(file).toLowerCase()];
96
+ if (type) {
97
+ return {
98
+ kind: 'image',
99
+ dataUrl: `data:${type};base64,${fs.readFileSync(file).toString('base64')}`,
100
+ };
101
+ }
102
+ return { kind: 'sprite', text: fs.readFileSync(file, 'utf8') };
103
+ }
104
+
105
+ // A `kind: "model"` part's `src` as a deck path, by the rule in
106
+ // engine3d/modelrefs.js: relative to the deck the referencing model is in.
107
+ function modelRefPath(src, fromPath) {
108
+ const ref = src.replace(/^\.\//, '');
109
+ if (ref.startsWith('@imports/')) {
110
+ return ref.slice(1);
111
+ }
112
+ if (ref.startsWith('imports/')) {
113
+ return ref;
114
+ }
115
+ const deck = /^(imports\/[^/]+\/)/.exec(fromPath);
116
+ return (deck ? deck[1] : '') + ref;
117
+ }
118
+
119
+ // Every model file `model` references, at any depth, into `models` (deck path
120
+ // -> text) and their parsed JSON into `found`. A path already collected is not
121
+ // read again, which also ends cycles.
122
+ function collectModels(model, fromPath, models, found) {
123
+ for (const part of model.parts ?? []) {
124
+ if (part?.kind !== 'model' || typeof part.src !== 'string' || !part.src) {
125
+ continue;
126
+ }
127
+ const key = modelRefPath(part.src, fromPath);
128
+ if (models[key] !== undefined) {
129
+ continue;
130
+ }
131
+ const file = artFile(key);
132
+ if (!fs.existsSync(file)) {
133
+ console.warn(`missing model: ${part.src} (from ${fromPath})`);
134
+ continue;
135
+ }
136
+ models[key] = fs.readFileSync(file, 'utf8');
137
+ try {
138
+ const json = JSON.parse(models[key]);
139
+ found.push(json);
140
+ collectModels(json, key, models, found);
141
+ } catch (error) {
142
+ console.warn(`${key}: ${error.message}`);
143
+ }
144
+ }
145
+ }
146
+
147
+ // What the sheet page needs for one model: its text, the text of every model
148
+ // it references, and the art all of them use. A file that is not JSON still
149
+ // gets a page, which says so.
150
+ function sheetFor(modelFile) {
151
+ const text = fs.readFileSync(modelFile, 'utf8');
152
+ const source = path.relative(DECK, path.resolve(modelFile));
153
+ let model;
154
+ try {
155
+ model = JSON.parse(text);
156
+ } catch (error) {
157
+ console.warn(`${source}: ${error.message}`);
158
+ return { source, model: text, arts: {}, models: {} };
159
+ }
160
+ const models = {};
161
+ const referenced = [];
162
+ collectModels(model, source, models, referenced);
163
+ const arts = {};
164
+ for (const ref of [model, ...referenced].flatMap(artRefsOf)) {
165
+ const art = readArt(ref);
166
+ if (art) {
167
+ arts[ref] = art;
168
+ }
169
+ }
170
+ return { source, model: text, arts, models };
171
+ }
172
+
173
+ //
174
+ // The scratch deck and its serve
175
+ //
176
+
177
+ // A link already pointing at the target is left alone, since a kept serve may
178
+ // be reading through it.
179
+ function linkTo(target, link) {
180
+ try {
181
+ if (fs.readlinkSync(link) === target) {
182
+ return;
183
+ }
184
+ } catch {
185
+ // Not a link yet.
186
+ }
187
+ fs.rmSync(link, { recursive: true, force: true });
188
+ fs.symlinkSync(target, link);
189
+ }
190
+
191
+ // A copy keeps the source's mode, and an import's files are read-only, so the
192
+ // next run could not overwrite them. The text is written to a new file instead.
193
+ function copyText(from, to) {
194
+ fs.rmSync(to, { force: true });
195
+ fs.writeFileSync(to, fs.readFileSync(from));
196
+ }
197
+
198
+ function writeSheetDeck() {
199
+ fs.mkdirSync(SHEET_DECK, { recursive: true });
200
+ for (const name of ['index.html', 'sheet.js', 'filmstrip.js']) {
201
+ copyText(path.join(KIT_RENDER_DIR, name), path.join(SHEET_DECK, name));
202
+ }
203
+ const deckConfig = JSON.parse(fs.readFileSync(path.join(DECK, 'castle.json'), 'utf8'));
204
+ fs.writeFileSync(
205
+ path.join(SHEET_DECK, 'castle.json'),
206
+ JSON.stringify({ imports: deckConfig.imports ?? {} }, null, 2)
207
+ );
208
+ fs.writeFileSync(
209
+ path.join(SHEET_DECK, 'package.json'),
210
+ JSON.stringify({ name: 'model-sheet', private: true, type: 'module' }, null, 2)
211
+ );
212
+ if (fs.existsSync(path.join(DECK, 'theme.style'))) {
213
+ copyText(path.join(DECK, 'theme.style'), path.join(SHEET_DECK, 'theme.style'));
214
+ }
215
+ linkTo(path.join(DECK, 'imports'), path.join(SHEET_DECK, 'imports'));
216
+ linkTo(path.join(DECK, 'node_modules'), path.join(SHEET_DECK, 'node_modules'));
217
+
218
+ // A deck that forks the kit's builder renders with its fork.
219
+ if (fs.existsSync(path.join(DECK, 'forks'))) {
220
+ linkTo(path.join(DECK, 'forks'), path.join(SHEET_DECK, 'forks'));
221
+ }
222
+ }
223
+
224
+ function freePort() {
225
+ return new Promise((resolve, reject) => {
226
+ const server = net.createServer();
227
+ server.once('error', reject);
228
+ server.listen(0, () => {
229
+ const { port } = server.address();
230
+ server.close(() => resolve(port));
231
+ });
232
+ });
233
+ }
234
+
235
+ async function answers(port) {
236
+ try {
237
+ return (await fetch(`http://localhost:${port}/`)).ok;
238
+ } catch {
239
+ return false;
240
+ }
241
+ }
242
+
243
+ // The serve's imports are links into this deck, so auto-update is off. The
244
+ // serve runs in its own process group, and stopping it kills the whole tree.
245
+ // With CASTLE_RENDER_KEEP=1 the serve outlives the call, and the next call
246
+ // finds it through its serve.json and uses it again. For batch jobs that
247
+ // render many times in a row.
248
+ const KEEP = process.env.CASTLE_RENDER_KEEP === '1';
249
+
250
+ // A kept serve whose process is alive is used even when it is slow to answer
251
+ // (a loaded machine): it is waited on, never started twice.
252
+ async function runningServe() {
253
+ let info;
254
+ try {
255
+ info = JSON.parse(fs.readFileSync(path.join(SHEET_DECK, '.castle', 'serve.json'), 'utf8'));
256
+ process.kill(info.pid, 0);
257
+ } catch {
258
+ return false;
259
+ }
260
+ const deadline = Date.now() + SERVE_TIMEOUT_MS;
261
+ while (Date.now() < deadline) {
262
+ if (await answers(info.port)) {
263
+ return true;
264
+ }
265
+ await new Promise((resolve) => setTimeout(resolve, 500));
266
+ }
267
+ return false;
268
+ }
269
+
270
+ // Renders in the same deck at the same time take turns starting its serve.
271
+ async function withStartLock(start) {
272
+ const lock = path.join(WORK, 'serve.lock');
273
+ fs.mkdirSync(WORK, { recursive: true });
274
+ for (;;) {
275
+ try {
276
+ fs.mkdirSync(lock);
277
+ break;
278
+ } catch {
279
+ const age =
280
+ Date.now() - (fs.statSync(lock, { throwIfNoEntry: false })?.mtimeMs ?? Date.now());
281
+ if (age > SERVE_TIMEOUT_MS * 2) {
282
+ fs.rmSync(lock, { recursive: true, force: true });
283
+ }
284
+ await new Promise((resolve) => setTimeout(resolve, 200));
285
+ }
286
+ }
287
+ try {
288
+ return await start();
289
+ } finally {
290
+ fs.rmSync(lock, { recursive: true, force: true });
291
+ }
292
+ }
293
+
294
+ async function startServe() {
295
+ const port = await freePort();
296
+ const serveJson = path.join(SHEET_DECK, '.castle', 'serve.json');
297
+ fs.rmSync(serveJson, { force: true });
298
+ let log = '';
299
+ const child = spawn(CLI[0], [...CLI.slice(1), 'serve', SHEET_DECK, '--port', String(port)], {
300
+ cwd: SHEET_DECK,
301
+ env: { ...process.env, CASTLE_NO_AUTO_UPDATE: '1' },
302
+ stdio: KEEP ? 'ignore' : ['ignore', 'pipe', 'pipe'],
303
+ detached: true,
304
+ });
305
+ if (KEEP) {
306
+ child.unref();
307
+ }
308
+ child.stdout?.on('data', (data) => (log += data));
309
+ child.stderr?.on('data', (data) => (log += data));
310
+ const stop = () => {
311
+ try {
312
+ process.kill(-child.pid, 'SIGKILL');
313
+ } catch {
314
+ // Already stopped.
315
+ }
316
+ };
317
+ const deadline = Date.now() + SERVE_TIMEOUT_MS;
318
+ while (Date.now() < deadline) {
319
+ if (child.exitCode !== null) {
320
+ throw new Error(`the sheet serve exited:\n${log}`);
321
+ }
322
+ if (fs.existsSync(serveJson) && (await answers(port))) {
323
+ return stop;
324
+ }
325
+ await new Promise((resolve) => setTimeout(resolve, 250));
326
+ }
327
+ stop();
328
+ throw new Error(`the sheet serve did not come up in ${SERVE_TIMEOUT_MS / 1000} s:\n${log}`);
329
+ }
330
+
331
+ //
332
+ // Playtest
333
+ //
334
+
335
+ // One playtest call through `castle-web mcp-playtest`, which speaks JSON-RPC
336
+ // on stdio, one message per line. Returns the screenshots as png buffers.
337
+ async function playtest(args) {
338
+ const child = spawn(CLI[0], [...CLI.slice(1), 'mcp-playtest', SHEET_DECK], {
339
+ stdio: ['pipe', 'pipe', 'inherit'],
340
+ });
341
+
342
+ // Replies are matched to calls by id. A reply never comes once the child has
343
+ // exited, so every call still waiting fails then.
344
+ const pending = new Map();
345
+ let buffered = '';
346
+ child.stdout.on('data', (chunk) => {
347
+ buffered += chunk.toString();
348
+ let cut;
349
+ while ((cut = buffered.indexOf('\n')) !== -1) {
350
+ const line = buffered.slice(0, cut).trim();
351
+ buffered = buffered.slice(cut + 1);
352
+ if (line) {
353
+ const message = JSON.parse(line);
354
+ pending.get(message.id)?.resolve(message);
355
+ pending.delete(message.id);
356
+ }
357
+ }
358
+ });
359
+ child.on('close', (code) => {
360
+ for (const waiting of pending.values()) {
361
+ waiting.reject(new Error(`mcp-playtest exited with code ${code}`));
362
+ }
363
+ pending.clear();
364
+ });
365
+ let nextId = 1;
366
+ const call = (method, params) => {
367
+ const id = nextId++;
368
+ child.stdin.write(JSON.stringify({ jsonrpc: '2.0', id, method, params }) + '\n');
369
+ return new Promise((resolve, reject) => pending.set(id, { resolve, reject }));
370
+ };
371
+
372
+ await call('initialize', {
373
+ protocolVersion: '2024-11-05',
374
+ capabilities: {},
375
+ clientInfo: { name: 'render', version: '1' },
376
+ });
377
+ const response = await call('tools/call', { name: 'playtest', arguments: args });
378
+ child.stdin.end();
379
+
380
+ const shots = [];
381
+ let text = '';
382
+ for (const part of response?.result?.content ?? []) {
383
+ if (part.type === 'image') {
384
+ shots.push(Buffer.from(part.data, 'base64'));
385
+ } else if (part.type === 'text') {
386
+ text += part.text + '\n';
387
+ }
388
+ }
389
+ if (response?.error) {
390
+ text += JSON.stringify(response.error);
391
+ }
392
+ return { shots, text };
393
+ }
394
+
395
+ // One screenshot per page, with `n` pressed halfway between shots.
396
+ function planFor(pageCount) {
397
+ const screenshots = [];
398
+ const actions = [];
399
+ for (let page = 0; page < pageCount; page++) {
400
+ const at = FIRST_SHOT_MS + page * SHOT_SPACING_MS;
401
+ screenshots.push(at);
402
+ if (page < pageCount - 1) {
403
+ actions.push({ t: at + SHOT_SPACING_MS / 2, type: 'key', key: 'n', durationMs: 50 });
404
+ }
405
+ }
406
+ return { durationMs: screenshots[screenshots.length - 1] + 200, screenshots, actions };
407
+ }
408
+
409
+ //
410
+ // Joining pngs
411
+ //
412
+
413
+ // Only the layout playtest screenshots use: 8 bits per channel, RGB or RGBA,
414
+ // not interlaced. Each row of the pixel data starts with a filter byte naming
415
+ // how the row was predicted from its neighbors; decoding adds the prediction
416
+ // back.
417
+ function decodePng(buffer) {
418
+ let offset = 8;
419
+ let header;
420
+ const data = [];
421
+ while (offset < buffer.length) {
422
+ const length = buffer.readUInt32BE(offset);
423
+ const type = buffer.toString('ascii', offset + 4, offset + 8);
424
+ const body = buffer.subarray(offset + 8, offset + 8 + length);
425
+ if (type === 'IHDR') {
426
+ header = {
427
+ width: body.readUInt32BE(0),
428
+ height: body.readUInt32BE(4),
429
+ depth: body[8],
430
+ colorType: body[9],
431
+ interlace: body[12],
432
+ };
433
+ } else if (type === 'IDAT') {
434
+ data.push(body);
435
+ }
436
+ offset += 12 + length;
437
+ }
438
+ if (
439
+ header.depth !== 8 ||
440
+ (header.colorType !== 2 && header.colorType !== 6) ||
441
+ header.interlace
442
+ ) {
443
+ throw new Error('unsupported png layout');
444
+ }
445
+ const channels = header.colorType === 6 ? 4 : 3;
446
+ const stride = header.width * channels;
447
+ const raw = zlib.inflateSync(Buffer.concat(data));
448
+ const pixels = Buffer.alloc(stride * header.height);
449
+ for (let y = 0; y < header.height; y++) {
450
+ const filter = raw[y * (stride + 1)];
451
+ const row = raw.subarray(y * (stride + 1) + 1, (y + 1) * (stride + 1));
452
+ const out = pixels.subarray(y * stride, (y + 1) * stride);
453
+ const above = y > 0 ? pixels.subarray((y - 1) * stride, y * stride) : Buffer.alloc(stride);
454
+ for (let x = 0; x < stride; x++) {
455
+ const left = x >= channels ? out[x - channels] : 0;
456
+ const up = above[x];
457
+ const upLeft = x >= channels ? above[x - channels] : 0;
458
+ let predicted = 0;
459
+ if (filter === 1) {
460
+ predicted = left;
461
+ } else if (filter === 2) {
462
+ predicted = up;
463
+ } else if (filter === 3) {
464
+ predicted = (left + up) >> 1;
465
+ } else if (filter === 4) {
466
+ // The Paeth predictor: whichever neighbor is closest to left + up - upLeft.
467
+ const estimate = left + up - upLeft;
468
+ const toLeft = Math.abs(estimate - left);
469
+ const toUp = Math.abs(estimate - up);
470
+ const toUpLeft = Math.abs(estimate - upLeft);
471
+ if (toLeft <= toUp && toLeft <= toUpLeft) {
472
+ predicted = left;
473
+ } else if (toUp <= toUpLeft) {
474
+ predicted = up;
475
+ } else {
476
+ predicted = upLeft;
477
+ }
478
+ }
479
+ out[x] = (row[x] + predicted) & 0xff;
480
+ }
481
+ }
482
+ return { width: header.width, height: header.height, channels, pixels };
483
+ }
484
+
485
+ const CRC_TABLE = Array.from({ length: 256 }, (_, n) => {
486
+ let c = n;
487
+ for (let k = 0; k < 8; k++) {
488
+ c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
489
+ }
490
+ return c >>> 0;
491
+ });
492
+
493
+ function crc32(buffer) {
494
+ let c = 0xffffffff;
495
+ for (const byte of buffer) {
496
+ c = CRC_TABLE[(c ^ byte) & 0xff] ^ (c >>> 8);
497
+ }
498
+ return (c ^ 0xffffffff) >>> 0;
499
+ }
500
+
501
+ // A png chunk is a length, a four letter type, the body, and a CRC-32 of the
502
+ // type and body.
503
+ function chunk(type, body) {
504
+ const length = Buffer.alloc(4);
505
+ length.writeUInt32BE(body.length);
506
+ const typeAndBody = Buffer.concat([Buffer.from(type, 'ascii'), body]);
507
+ const crc = Buffer.alloc(4);
508
+ crc.writeUInt32BE(crc32(typeAndBody));
509
+ return Buffer.concat([length, typeAndBody, crc]);
510
+ }
511
+
512
+ // Lay pngs of the same height and layout side by side.
513
+ function joinPngs(buffers) {
514
+ const images = buffers.map(decodePng);
515
+ const { height, channels } = images[0];
516
+ const width = images.reduce((sum, image) => sum + image.width, 0);
517
+ const stride = width * channels;
518
+ const raw = Buffer.alloc((stride + 1) * height);
519
+ for (let y = 0; y < height; y++) {
520
+ let x = y * (stride + 1) + 1;
521
+ for (const image of images) {
522
+ const rowBytes = image.width * channels;
523
+ image.pixels.copy(raw, x, y * rowBytes, (y + 1) * rowBytes);
524
+ x += rowBytes;
525
+ }
526
+ }
527
+ const header = Buffer.alloc(13);
528
+ header.writeUInt32BE(width, 0);
529
+ header.writeUInt32BE(height, 4);
530
+ header[8] = 8;
531
+ header[9] = channels === 4 ? 6 : 2;
532
+ return Buffer.concat([
533
+ Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
534
+ chunk('IHDR', header),
535
+ chunk('IDAT', zlib.deflateSync(raw)),
536
+ chunk('IEND', Buffer.alloc(0)),
537
+ ]);
538
+ }
539
+
540
+ //
541
+ // Main
542
+ //
543
+
544
+ async function renderBatch(jobs) {
545
+ fs.mkdirSync(path.join(SHEET_DECK, 'target'), { recursive: true });
546
+ fs.writeFileSync(
547
+ path.join(SHEET_DECK, 'target', 'sheet.json'),
548
+ JSON.stringify({ sheets: jobs.map((job) => ({ ...sheetFor(job.file), motion: job.motion })) })
549
+ );
550
+ const { shots, text } = await playtest(planFor(jobs.length * PAGES_PER_MODEL));
551
+ if (/sheet failed|not a pxmodel/i.test(text)) {
552
+ console.warn(text);
553
+ }
554
+ const headers = sheetHeaders(text);
555
+ jobs.forEach((job, index) => {
556
+ const pages = shots.slice(index * PAGES_PER_MODEL, (index + 1) * PAGES_PER_MODEL);
557
+ if (pages.length < PAGES_PER_MODEL) {
558
+ console.error(`no sheet for ${job.file}:\n${text}`);
559
+ process.exitCode = 1;
560
+ return;
561
+ }
562
+ fs.mkdirSync(path.dirname(path.resolve(job.out)), { recursive: true });
563
+ fs.writeFileSync(job.out, joinPngs(pages));
564
+ console.log(path.relative(DECK, path.resolve(job.out)));
565
+ const sheet = headers[index];
566
+ if (sheet) {
567
+ console.log(sheet.header.replace(/^/gm, ' '));
568
+ if (sheet.triangles > sheet.budget) {
569
+ console.log(` over budget by ${sheet.triangles - sheet.budget} triangles: simplify the heaviest parts, or raise \`triangles\` if the model needs them`);
570
+ }
571
+ }
572
+ });
573
+ }
574
+
575
+ // The page logs one `render-sheet {...}` line per model, in job order.
576
+ function sheetHeaders(text) {
577
+ const headers = [];
578
+ for (const match of text.matchAll(/render-sheet (\{.*\})/g)) {
579
+ try {
580
+ headers.push(JSON.parse(match[1]));
581
+ } catch {
582
+ headers.push(null);
583
+ }
584
+ }
585
+ return headers;
586
+ }
587
+
588
+ function parseArgs(argv) {
589
+ const files = [];
590
+ let out = null;
591
+ let motion = false;
592
+ for (let index = 0; index < argv.length; index++) {
593
+ if (argv[index] === '--out') {
594
+ out = argv[++index];
595
+ } else if (argv[index] === '--motion') {
596
+ motion = true;
597
+ } else {
598
+ files.push(argv[index]);
599
+ }
600
+ }
601
+ if (out && files.length !== 1) {
602
+ throw new Error('--out takes exactly one model');
603
+ }
604
+ const suffix = motion ? '-motion' : '';
605
+ return files.map((file) => ({
606
+ file,
607
+ motion,
608
+ out: out ?? path.join(WORK, `${path.basename(file, '.pxmodel')}${suffix}.png`),
609
+ }));
610
+ }
611
+
612
+ const jobs = parseArgs(process.argv.slice(2));
613
+ if (jobs.length === 0) {
614
+ console.error(
615
+ 'usage: npm run render -- [--motion] <model.pxmodel> [more.pxmodel ...] [--out file.png]'
616
+ );
617
+ process.exit(1);
618
+ }
619
+ for (const job of jobs) {
620
+ if (!fs.existsSync(job.file)) {
621
+ console.error(`no such file: ${job.file}`);
622
+ process.exit(1);
623
+ }
624
+ }
625
+
626
+ writeSheetDeck();
627
+ const stopServe = KEEP
628
+ ? await withStartLock(async () => ((await runningServe()) ? () => {} : startServe()))
629
+ : await startServe();
630
+
631
+ // The serve is outside this process group, so ctrl-c would leave it running.
632
+ process.on('SIGINT', () => {
633
+ if (!KEEP) {
634
+ stopServe();
635
+ }
636
+ process.exit(130);
637
+ });
638
+ try {
639
+ for (let start = 0; start < jobs.length; start += MODELS_PER_PLAYTEST) {
640
+ await renderBatch(jobs.slice(start, start + MODELS_PER_PLAYTEST));
641
+ }
642
+ } finally {
643
+ if (!KEEP) {
644
+ stopServe();
645
+ }
646
+ }
@@ -3,11 +3,11 @@
3
3
  "imports": {
4
4
  "castle.base": {
5
5
  "deckId": "yRcmH4_aYllE",
6
- "version": "2026-09-22T19:48:55.642Z"
6
+ "version": "2026-09-24T02:13:40.120Z"
7
7
  }
8
8
  },
9
9
  "autoUpdateWhenImported": true,
10
10
  "deckId": "xFVr-afOLuUQ",
11
11
  "cardId": "w6G45sy3_P_m",
12
- "publishedVersion": "2026-09-22T19:48:58.226Z"
12
+ "publishedVersion": "2026-09-24T18:05:46.175Z"
13
13
  }