castle-web-cli 0.4.193 → 0.4.195

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 (101) hide show
  1. package/dist/agent-prompts.d.ts +1 -0
  2. package/dist/agent-prompts.js +14 -5
  3. package/dist/agent.js +101 -4
  4. package/dist/api.d.ts +1 -0
  5. package/dist/api.js +5 -0
  6. package/dist/bundle.js +2 -1
  7. package/dist/castleJson.d.ts +1 -2
  8. package/dist/castleJson.js +0 -39
  9. package/dist/check.js +14 -6
  10. package/dist/devSessionFrameBudget.d.ts +14 -0
  11. package/dist/devSessionFrameBudget.js +64 -0
  12. package/dist/devSessionServer.d.ts +6 -0
  13. package/dist/devSessionServer.js +38 -1
  14. package/dist/editorConfig.d.ts +1 -1
  15. package/dist/editorConfig.js +12 -4
  16. package/dist/filesChanged.js +7 -3
  17. package/dist/ide.js +28 -59
  18. package/dist/importUpdateHook.d.ts +31 -0
  19. package/dist/importUpdateHook.js +135 -0
  20. package/dist/importUpdateHookRunner.d.ts +2 -0
  21. package/dist/importUpdateHookRunner.js +24 -0
  22. package/dist/imports.js +58 -10
  23. package/dist/index.js +58 -7
  24. package/dist/init.d.ts +1 -0
  25. package/dist/init.js +15 -9
  26. package/dist/multiplayerDoc.d.ts +1 -0
  27. package/dist/multiplayerDoc.js +228 -0
  28. package/dist/native/loop.js +29 -9
  29. package/dist/platformDoc.d.ts +1 -0
  30. package/dist/platformDoc.js +25 -6
  31. package/dist/remix.js +4 -1
  32. package/dist/scriptErrors.d.ts +23 -0
  33. package/dist/scriptErrors.js +147 -0
  34. package/dist/serve.js +366 -36
  35. package/dist/serverBundle.js +1 -1
  36. package/dist/shell/assets/index-kMH1qj6D.js +449 -0
  37. package/dist/shell/index.html +1 -1
  38. package/dist/versions.d.ts +14 -0
  39. package/dist/versions.js +21 -0
  40. package/dist/viteClientStub.d.ts +18 -0
  41. package/dist/viteClientStub.js +193 -0
  42. package/dist/vitePlugins.d.ts +1 -0
  43. package/dist/vitePlugins.js +18 -0
  44. package/kits/base/CLAUDE.md +3 -3
  45. package/kits/base/castle.json +1 -3
  46. package/kits/base/sdk/README.md +17 -0
  47. package/kits/multiplayer-2d/CLAUDE.md +9 -2
  48. package/kits/multiplayer-2d/blueprints/crate.scene +32 -4
  49. package/kits/multiplayer-2d/blueprints/other-player.scene +31 -4
  50. package/kits/multiplayer-2d/blueprints/player.scene +38 -6
  51. package/kits/multiplayer-2d/blueprints/wall.scene +25 -3
  52. package/kits/multiplayer-2d/castle.json +3 -12
  53. package/kits/multiplayer-2d/test/two-client-test.mjs +4 -4
  54. package/kits/multiplayer-3d/CLAUDE.md +5 -2
  55. package/kits/multiplayer-3d/castle.json +3 -11
  56. package/kits/multiplayer-3d/scenes/main.scene +128 -0
  57. package/kits/physics-2d/CLAUDE.md +16 -11
  58. package/kits/physics-2d/behaviors/Camera.jsx +5 -6
  59. package/kits/physics-2d/behaviors/Goal.jsx +5 -2
  60. package/kits/physics-2d/behaviors/Joints.jsx +4 -3
  61. package/kits/physics-2d/behaviors/Layout.jsx +120 -3
  62. package/kits/physics-2d/behaviors/Sprite.jsx +9 -9
  63. package/kits/physics-2d/behaviors/Style.jsx +22 -15
  64. package/kits/physics-2d/behaviors/Text.jsx +7 -6
  65. package/kits/physics-2d/blueprints/ball.scene +27 -5
  66. package/kits/physics-2d/blueprints/block.scene +16 -3
  67. package/kits/physics-2d/blueprints/cauldron.scene +3 -1
  68. package/kits/physics-2d/blueprints/crate.scene +23 -4
  69. package/kits/physics-2d/blueprints/goal.scene +12 -2
  70. package/kits/physics-2d/blueprints/text.scene +13 -3
  71. package/kits/physics-2d/castle.json +2 -11
  72. package/kits/physics-2d/editors/SceneEditor.jsx +68 -5
  73. package/kits/physics-2d/editors/SelectionOverlay.jsx +27 -20
  74. package/kits/physics-2d/editors/behaviorRegistry.js +8 -2
  75. package/kits/physics-2d/engine/ErrorOverlay.jsx +69 -0
  76. package/kits/physics-2d/engine/ScenePlayer.jsx +2 -67
  77. package/kits/physics-2d/engine/blueprint.js +111 -54
  78. package/kits/physics-2d/engine/blueprintCore.js +59 -0
  79. package/kits/physics-2d/engine/collider.js +28 -17
  80. package/kits/physics-2d/engine/layout.js +61 -0
  81. package/kits/physics-2d/engine/layoutOriginMigration.js +223 -0
  82. package/kits/physics-2d/engine/liveReload.js +5 -4
  83. package/kits/physics-2d/engine/physics/PhysicsSystem.js +11 -7
  84. package/kits/physics-2d/engine/physics/controls.js +4 -8
  85. package/kits/physics-2d/engine/physics/matterBridge.js +13 -8
  86. package/kits/physics-2d/engine/scene.js +38 -34
  87. package/kits/physics-2d/engine/spriteGeometry.js +17 -9
  88. package/kits/physics-2d/engine/tap.js +4 -3
  89. package/kits/physics-2d/scenes/main.scene +59 -6
  90. package/kits/physics-2d/scenes/sandbox.scene +69 -7
  91. package/kits/physics-2d/scripts/onUpdate.mjs +199 -0
  92. package/kits/physics-3d/castle.json +0 -11
  93. package/kits/real-time/castle.json +2 -8
  94. package/kits/real-time/code/server/persist.js +14 -0
  95. package/kits/turn-based/CLAUDE.md +18 -10
  96. package/kits/turn-based/blueprints/board.scene +3 -1
  97. package/kits/turn-based/blueprints/square.scene +3 -1
  98. package/kits/turn-based/castle.json +3 -14
  99. package/kits/turn-based/code/behaviors/Board.jsx +33 -21
  100. package/package.json +1 -1
  101. package/dist/shell/assets/index-ColHKJYj.js +0 -449
@@ -1,5 +1,6 @@
1
1
  import React, { useCallback, useEffect, useRef, useState } from 'react';
2
2
  import { getColliderShapes } from '../behaviors/Collider';
3
+ import { layoutCenter, layoutOriginX, layoutOriginY, layoutXYForRect } from '../engine/layout';
3
4
  import { cardSize, screenToCard, isBehaviorEnabled } from '../engine/scene';
4
5
  import { cx, Icon, styles, useElementSize } from '../engine/ui';
5
6
 
@@ -497,6 +498,7 @@ function getSelectedColliderFrames(sceneData, actorIds, sprites) {
497
498
  // needs no such check -- it runs through `forEachBehavior`, which is
498
499
  // gated -- but this overlay reads the component directly.
499
500
  if (!layout || !isBehaviorEnabled(collider) || !shapes) return [];
501
+ const center = layoutCenter(layout);
500
502
  const isTrigger = Boolean(collider.isTrigger) || collider.kind === 'pickup';
501
503
  // One preview box per collider shape, from the shared geometry so the
502
504
  // preview matches the physics body. A circle renders as a radius-sized
@@ -545,8 +547,10 @@ function getSelectedColliderFrames(sceneData, actorIds, sprites) {
545
547
  height,
546
548
  rotation: layout.rotation ?? 0,
547
549
  shapeAngle: s.type === 'box' ? s.angle ?? 0 : 0,
548
- originX: layout.x + layout.width / 2 - x,
549
- originY: layout.y + layout.height / 2 - y,
550
+ // CSS transform-origin for the actor's rotation, relative to this
551
+ // shape's own top-left: the Layout box center, as ever.
552
+ originX: center.x - x,
553
+ originY: center.y - y,
550
554
  };
551
555
  });
552
556
  });
@@ -584,10 +588,7 @@ function getOrientedLayoutBounds(layouts, rotation) {
584
588
  }
585
589
 
586
590
  function getLayoutWorldCorners(layout) {
587
- const center = {
588
- x: layout.x + layout.width / 2,
589
- y: layout.y + layout.height / 2,
590
- };
591
+ const center = layoutCenter(layout);
591
592
  const halfW = layout.width / 2;
592
593
  const halfH = layout.height / 2;
593
594
  const rotation = layout.rotation ?? 0;
@@ -705,12 +706,17 @@ function collectLayoutStarts(sceneData, actorIds) {
705
706
  if (!wanted.has(actor.id)) continue;
706
707
  const layout = actor.components.Layout;
707
708
  if (layout) {
709
+ // Layout-shaped on purpose: the origin travels with the snapshot, so
710
+ // `layoutCenter(start)` / `layoutXYForRect(rect, start)` read and write it
711
+ // exactly as they do a live Layout.
708
712
  starts[actor.id] = {
709
713
  x: layout.x,
710
714
  y: layout.y,
711
715
  width: layout.width,
712
716
  height: layout.height,
713
717
  rotation: layout.rotation ?? 0,
718
+ originX: layoutOriginX(layout),
719
+ originY: layoutOriginY(layout),
714
720
  };
715
721
  }
716
722
  }
@@ -759,17 +765,23 @@ function moveSelected(sceneData, previewSceneData, actorIds, starts, dx, dy) {
759
765
  });
760
766
  }
761
767
 
768
+ // The rounded Layout `x`/`y` that leaves a `width`x`height` box centered on
769
+ // `center`, under the origin `start` carries. Every gesture below computes where
770
+ // the BOX should end up (as it always did) and comes back through here.
771
+ function roundedXYForBox(center, width, height, start) {
772
+ const xy = layoutXYForRect(
773
+ { x: center.x - width / 2, y: center.y - height / 2, width, height },
774
+ start
775
+ );
776
+ return { x: Math.round(xy.x), y: Math.round(xy.y) };
777
+ }
778
+
762
779
  // Common-pivot rotation: actor centers orbit the selection pivot while each
763
780
  // actor also spins by the same delta, matching a temporary group transform.
764
781
  function rotateSelected(sceneData, previewSceneData, actorIds, starts, pivot, deltaDeg) {
765
782
  return updateSelectedLayouts(sceneData, previewSceneData, actorIds, starts, (layout, start) => {
766
- const center = {
767
- x: start.x + start.width / 2,
768
- y: start.y + start.height / 2,
769
- };
770
- const nextCenter = rotatePoint(center, pivot, deltaDeg);
771
- const x = Math.round(nextCenter.x - start.width / 2);
772
- const y = Math.round(nextCenter.y - start.height / 2);
783
+ const nextCenter = rotatePoint(layoutCenter(start), pivot, deltaDeg);
784
+ const { x, y } = roundedXYForBox(nextCenter, start.width, start.height, start);
773
785
  const rotation = normalizeAngle((start.rotation ?? 0) + deltaDeg);
774
786
  if (layout.x === x && layout.y === y && (layout.rotation ?? 0) === rotation) return null;
775
787
  return { x, y, rotation };
@@ -781,11 +793,7 @@ function scaleSelected(sceneData, previewSceneData, actorIds, starts, startTrans
781
793
  const scaleX = startBounds.width === 0 ? 1 : nextLocalBounds.width / startBounds.width;
782
794
  const scaleY = startBounds.height === 0 ? 1 : nextLocalBounds.height / startBounds.height;
783
795
  return updateSelectedLayouts(sceneData, previewSceneData, actorIds, starts, (layout, start) => {
784
- const startCenter = {
785
- x: start.x + start.width / 2,
786
- y: start.y + start.height / 2,
787
- };
788
- const localCenter = worldToLocal(startCenter, startTransform);
796
+ const localCenter = worldToLocal(layoutCenter(start), startTransform);
789
797
  const nextLocalCenter = {
790
798
  x: nextLocalBounds.left + (localCenter.x - startBounds.left) * scaleX,
791
799
  y: nextLocalBounds.top + (localCenter.y - startBounds.top) * scaleY,
@@ -793,8 +801,7 @@ function scaleSelected(sceneData, previewSceneData, actorIds, starts, startTrans
793
801
  const nextCenter = localToWorld(nextLocalCenter, startTransform);
794
802
  const width = Math.max(MIN_LAYOUT_SIZE, Math.round(start.width * scaleX));
795
803
  const height = Math.max(MIN_LAYOUT_SIZE, Math.round(start.height * scaleY));
796
- const x = Math.round(nextCenter.x - width / 2);
797
- const y = Math.round(nextCenter.y - height / 2);
804
+ const { x, y } = roundedXYForBox(nextCenter, width, height, start);
798
805
  if (layout.x === x && layout.y === y && layout.width === width && layout.height === height) {
799
806
  return null;
800
807
  }
@@ -87,9 +87,15 @@ async function swapBehaviorModule(deckPath) {
87
87
  try {
88
88
  const mod = await import(/* @vite-ignore */ `${key}?t=${Date.now()}`);
89
89
  modules[key] = mod;
90
- } catch {
90
+ } catch (error) {
91
91
  // A file mid-edit may not parse. Keep the last good definition and wait for
92
- // the next save rather than emptying the registry under the editor.
92
+ // the next save rather than emptying the registry under the editor -- but
93
+ // SAY so: swallowing it silently is how a stray `function` inside a
94
+ // behavior becomes a scene that just stops updating with nothing anywhere
95
+ // to read. The console reaches the shell's logs drawer (the SDK's
96
+ // interceptConsole) and the serve log.
97
+ // eslint-disable-next-line no-console
98
+ console.error(`[castle] behavior failed to load: ${deckPath}`, error?.message ?? String(error));
93
99
  return;
94
100
  }
95
101
  behaviorClasses = collectBehaviors();
@@ -0,0 +1,69 @@
1
+ // Redbox overlay shown when a scene loop throws. Covers the canvas with the
2
+ // error name/message and stack so a broken behavior is legible instead of a
3
+ // black screen. Restart remounts the loop; fixing the code and restarting the
4
+ // serve reloads the whole preview fresh.
5
+ //
6
+ // Shared by the play surface (engine/ScenePlayer) and the scene editor's own
7
+ // edit-mode loop (editors/SceneEditor) -- a ReferenceError thrown while drawing
8
+ // a preview blanks the editor canvas exactly the same way, and used to do it
9
+ // without a word.
10
+ export function ErrorOverlay({ error, onRestart, title = 'Play error' }) {
11
+ const name = error?.name ?? 'Error';
12
+ const message = error?.message ?? String(error);
13
+ const stack = typeof error?.stack === 'string' ? error.stack : '';
14
+ return (
15
+ <div
16
+ style={{
17
+ position: 'absolute',
18
+ inset: 0,
19
+ zIndex: 2147483000,
20
+ display: 'flex',
21
+ flexDirection: 'column',
22
+ gap: 12,
23
+ padding: '20px 22px',
24
+ background: 'rgba(20, 8, 8, 0.94)',
25
+ color: '#ffd9dc',
26
+ font: "13px/1.5 'SFMono-Regular', Consolas, 'Liberation Mono', monospace",
27
+ overflow: 'auto',
28
+ boxSizing: 'border-box',
29
+ }}>
30
+ <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
31
+ <span style={{ fontSize: 15, fontWeight: 700, color: '#ff6b74' }}>{title}</span>
32
+ <button
33
+ type="button"
34
+ onClick={onRestart}
35
+ style={{
36
+ marginLeft: 'auto',
37
+ padding: '4px 12px',
38
+ border: '1px solid #a02828',
39
+ borderRadius: 4,
40
+ background: '#a02828',
41
+ color: '#fff',
42
+ font: 'inherit',
43
+ cursor: 'pointer',
44
+ }}>
45
+ Restart
46
+ </button>
47
+ </div>
48
+ <div style={{ color: '#fff', fontWeight: 600, wordBreak: 'break-word' }}>
49
+ {name}: {message}
50
+ </div>
51
+ {stack ? (
52
+ <pre
53
+ style={{
54
+ margin: 0,
55
+ whiteSpace: 'pre-wrap',
56
+ wordBreak: 'break-word',
57
+ color: '#e79aa0',
58
+ fontSize: 12,
59
+ }}>
60
+ {stack}
61
+ </pre>
62
+ ) : null}
63
+ <div style={{ color: '#c98a8f', fontSize: 12 }}>
64
+ The preview stopped. Fix the code and restart the serve to reload, or press Restart to
65
+ retry.
66
+ </div>
67
+ </div>
68
+ );
69
+ }
@@ -1,6 +1,7 @@
1
1
  import React, { useCallback, useEffect, useRef, useState } from 'react';
2
2
  import { fontsReady } from './fonts';
3
3
  import { configureSceneCanvas, makeScene } from './scene';
4
+ import { ErrorOverlay } from './ErrorOverlay';
4
5
  import { SceneUI } from './SceneUI';
5
6
  // Engine-level scene player: mount a `SceneRuntime` against a canvas, wire
6
7
  // keyboard / pointer input, run the update+draw loop, and render the
@@ -131,7 +132,7 @@ export function ScenePlayer({ sceneData, sprites, files, behaviorClasses, sceneP
131
132
  }}
132
133
  />
133
134
  <SceneUI getRuntime={getRuntime} />
134
- {error ? <PlayErrorOverlay error={error} onRestart={onRestart} /> : null}
135
+ {error ? <ErrorOverlay error={error} onRestart={onRestart} /> : null}
135
136
  </div>
136
137
  );
137
138
  }
@@ -163,69 +164,3 @@ function startPlayerLoop(canvas, ctx, runtime, onFirstFrame, onError) {
163
164
  raf = requestAnimationFrame(tick);
164
165
  return () => cancelAnimationFrame(raf);
165
166
  }
166
- // Redbox overlay shown when the play loop throws. Covers the canvas with the
167
- // error name/message and stack so a broken behavior is legible instead of a
168
- // black screen. Restart remounts the loop; fixing the code and restarting the
169
- // serve reloads the whole preview fresh.
170
- function PlayErrorOverlay({ error, onRestart }) {
171
- const name = error?.name ?? 'Error';
172
- const message = error?.message ?? String(error);
173
- const stack = typeof error?.stack === 'string' ? error.stack : '';
174
- return (
175
- <div
176
- style={{
177
- position: 'absolute',
178
- inset: 0,
179
- zIndex: 2147483000,
180
- display: 'flex',
181
- flexDirection: 'column',
182
- gap: 12,
183
- padding: '20px 22px',
184
- background: 'rgba(20, 8, 8, 0.94)',
185
- color: '#ffd9dc',
186
- font: "13px/1.5 'SFMono-Regular', Consolas, 'Liberation Mono', monospace",
187
- overflow: 'auto',
188
- boxSizing: 'border-box',
189
- }}
190
- >
191
- <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
192
- <span style={{ fontSize: 15, fontWeight: 700, color: '#ff6b74' }}>Play error</span>
193
- <button
194
- type="button"
195
- onClick={onRestart}
196
- style={{
197
- marginLeft: 'auto',
198
- padding: '4px 12px',
199
- border: '1px solid #a02828',
200
- borderRadius: 4,
201
- background: '#a02828',
202
- color: '#fff',
203
- font: 'inherit',
204
- cursor: 'pointer',
205
- }}
206
- >
207
- Restart
208
- </button>
209
- </div>
210
- <div style={{ color: '#fff', fontWeight: 600, wordBreak: 'break-word' }}>
211
- {name}: {message}
212
- </div>
213
- {stack ? (
214
- <pre
215
- style={{
216
- margin: 0,
217
- whiteSpace: 'pre-wrap',
218
- wordBreak: 'break-word',
219
- color: '#e79aa0',
220
- fontSize: 12,
221
- }}
222
- >
223
- {stack}
224
- </pre>
225
- ) : null}
226
- <div style={{ color: '#c98a8f', fontSize: 12 }}>
227
- The preview stopped. Fix the code and restart the serve to reload, or press Restart to retry.
228
- </div>
229
- </div>
230
- );
231
- }
@@ -7,21 +7,18 @@
7
7
  // (`scene.js`, so play mode and `PlayOnly` resolve blueprints too) and the
8
8
  // editors (which also mint/fork/migrate/cascade-delete blueprint files).
9
9
  import { deckPrefixOf, IMPORTS_DIR, IMPORTS_PREFIX, resolveDeckFile } from 'castle-web-sdk';
10
+ import { BLUEPRINTS_DIR, isBlueprintPath, mergeComponents, parseBlueprintText } from './blueprintCore.js';
10
11
  import { formatJson } from './files';
12
+ import { DEFAULT_ORIGIN_X, DEFAULT_ORIGIN_Y, layoutOriginX, layoutOriginY, layoutXYForRect } from './layout';
11
13
  import { DEFAULT_RESOLUTION, TRANSPARENT, serializeCompact } from './pxart';
12
14
  import { cardSize, dedupeActorId } from './scene';
13
15
 
14
- export const BLUEPRINTS_DIR = 'blueprints';
15
- export const DRAWINGS_DIR = 'drawings';
16
-
17
- // A blueprint of this deck (`blueprints/x.scene`) OR of one it imports
18
- // (`imports/<alias>/blueprints/x.scene`) -- an imported deck's blueprints are
19
- // placeable like any other, which is most of the point of importing one.
20
- const BLUEPRINT_PATH_RE = new RegExp(`^(imports/[^/]+/)?${BLUEPRINTS_DIR}/`);
16
+ // The pieces a Node script of the kit's shares with the runtime live in
17
+ // `blueprintCore.js` (no imports of its own). Re-exported so every existing
18
+ // importer of this module keeps resolving them here.
19
+ export { BLUEPRINTS_DIR, isBlueprintPath, mergeComponents, parseBlueprintText };
21
20
 
22
- export function isBlueprintPath(path) {
23
- return typeof path === 'string' && path.endsWith('.scene') && BLUEPRINT_PATH_RE.test(path);
24
- }
21
+ export const DRAWINGS_DIR = 'drawings';
25
22
 
26
23
  // Blueprints an import owns: placeable, but not editable or deletable from here
27
24
  // (they belong to the deck they came from).
@@ -53,23 +50,6 @@ export function isInheritedProp(Behavior, prop) {
53
50
  return getPropertyMeta(Behavior, prop).inherit !== false;
54
51
  }
55
52
 
56
- // Parse a blueprint file's text into { name, components } (the template
57
- // actor's components), or null if the text isn't a valid blueprint (used to
58
- // treat a tombstoned/deleted blueprint file as absent).
59
- function parseBlueprintText(text) {
60
- if (typeof text !== 'string') return null;
61
- let data;
62
- try {
63
- data = JSON.parse(text);
64
- } catch {
65
- return null;
66
- }
67
- const actor = data?.actors?.[0];
68
- if (!actor || typeof actor !== 'object' || !actor.components) return null;
69
- const name = typeof data.name === 'string' && data.name.trim() ? data.name : 'Blueprint';
70
- return { name, components: actor.components };
71
- }
72
-
73
53
  // A reference names a file the way its own deck sees it -- `drawings/rock.pxart`
74
54
  // for one of its own, `@imports/<alias>/...` for one of a deck it imports (the
75
55
  // SDK's resolveDeckFile is the single definition of that rule). Templates are
@@ -168,25 +148,6 @@ export function listBlueprints(files) {
168
148
  return out;
169
149
  }
170
150
 
171
- // Per-property merge: the blueprint template is the base, instance overrides
172
- // win per-property within each component (not whole-component replacement). A
173
- // component present on only one side appears whole.
174
- export function mergeComponents(templateComponents, instanceComponents) {
175
- const merged = {};
176
- const names = new Set([
177
- ...Object.keys(templateComponents ?? {}),
178
- ...Object.keys(instanceComponents ?? {}),
179
- ]);
180
- for (const name of names) {
181
- const templateProps = templateComponents?.[name];
182
- const instanceProps = instanceComponents?.[name];
183
- if (templateProps === undefined) merged[name] = { ...instanceProps };
184
- else if (instanceProps === undefined) merged[name] = { ...templateProps };
185
- else merged[name] = { ...templateProps, ...instanceProps };
186
- }
187
- return merged;
188
- }
189
-
190
151
  // The fully resolved components for one actor: its blueprint's template
191
152
  // merged with its own sparse overrides, or its raw components when it carries
192
153
  // no `blueprint` ref (the blueprint's own template actor, or a not-yet
@@ -501,6 +462,18 @@ function topZ(actors, files) {
501
462
  return max === -Infinity ? 0 : max + 1;
502
463
  }
503
464
 
465
+ // The Layout every blueprint the editor mints starts from. Centre origin: the
466
+ // anchor an author reaches for is the middle of the thing ("put it HERE"), and
467
+ // it keeps a resize growing from the centre rather than the top-left corner.
468
+ // The kit's shipped presets use the same centre origin.
469
+ const MINTED_TEMPLATE_LAYOUT = {
470
+ width: 50,
471
+ height: 50,
472
+ z: 0,
473
+ originX: DEFAULT_ORIGIN_X,
474
+ originY: DEFAULT_ORIGIN_Y,
475
+ };
476
+
504
477
  // A freshly minted blueprint's first instance, at the card centre and on top.
505
478
  function appendCenteredInstance(sceneData, files, blueprintFile) {
506
479
  const layout = blueprintFile.components?.Layout ?? {};
@@ -509,8 +482,16 @@ function appendCenteredInstance(sceneData, files, blueprintFile) {
509
482
  const next = structuredClone(sceneData);
510
483
  const existingIds = new Set(next.actors.map((actor) => actor.id));
511
484
  const newId = mintActorIdFromName(existingIds, blueprintFile.name);
512
- const x = Math.round((cardSize.width - width) / 2);
513
- const y = Math.round((cardSize.height - height) / 2);
485
+ // Where the BOX goes, then stated as the x/y the template's origin wants.
486
+ const { x, y } = layoutXYForRect(
487
+ {
488
+ x: Math.round((cardSize.width - width) / 2),
489
+ y: Math.round((cardSize.height - height) / 2),
490
+ width,
491
+ height,
492
+ },
493
+ layout
494
+ );
514
495
  // Guarantee the new actor renders on top of whatever's already there.
515
496
  const z = topZ(next.actors, files);
516
497
  next.actors.push({ id: newId, blueprint: blueprintFile.path, components: { Layout: { x, y, z } } });
@@ -520,7 +501,7 @@ function appendCenteredInstance(sceneData, files, blueprintFile) {
520
501
  export function addActorWithBlueprint(sceneData, files) {
521
502
  const drawingFile = { path: mintDrawingPath(files), text: blankPxArtText() };
522
503
  const components = {
523
- Layout: { width: 50, height: 50, z: 0 },
504
+ Layout: { ...MINTED_TEMPLATE_LAYOUT },
524
505
  Sprite: { file: drawingFile.path },
525
506
  };
526
507
  const minted = mintBlueprintFile(files, components);
@@ -619,7 +600,7 @@ export function createBlueprint(sceneData, files, spec) {
619
600
  const drawingPath =
620
601
  mintPathFromName(existingPaths, name, DRAWINGS_DIR, DRAWING_EXT) ?? mintDrawingPath(files);
621
602
  drawingFile = { path: drawingPath, text: blankPxArtText() };
622
- components = { Layout: { width: 50, height: 50, z: 0 }, Sprite: { file: drawingPath } };
603
+ components = { Layout: { ...MINTED_TEMPLATE_LAYOUT }, Sprite: { file: drawingPath } };
623
604
  }
624
605
  const blueprintFile = { path, name, components, text: formatBlueprintFileText(name, components) };
625
606
  const { sceneData: next, newId } = appendCenteredInstance(sceneData, files, blueprintFile);
@@ -629,6 +610,10 @@ export function createBlueprint(sceneData, files, spec) {
629
610
  // Centered, grid-snapped Layout x/y for a blueprint's template at a
630
611
  // card-space point. Shared by initial drag-in placement and the subsequent
631
612
  // moves while the drag is still in progress, so both snap identically.
613
+ //
614
+ // The BOX is what gets centered and snapped -- the same rect as before the
615
+ // origin existed -- and `layoutXYForRect` then states it as the x/y the
616
+ // template's origin means, so what lands under the cursor doesn't depend on it.
632
617
  export function blueprintDropXY(files, blueprintPath, position, snap) {
633
618
  const template = getBlueprintTemplate(files, blueprintPath);
634
619
  const layout = template?.components?.Layout ?? {};
@@ -636,10 +621,15 @@ export function blueprintDropXY(files, blueprintPath, position, snap) {
636
621
  const height = layout.height ?? 50;
637
622
  const dropX = position?.x ?? cardSize.width / 2;
638
623
  const dropY = position?.y ?? cardSize.height / 2;
639
- return {
640
- x: snapValue(dropX - width / 2, snap),
641
- y: snapValue(dropY - height / 2, snap),
642
- };
624
+ return layoutXYForRect(
625
+ {
626
+ x: snapValue(dropX - width / 2, snap),
627
+ y: snapValue(dropY - height / 2, snap),
628
+ width,
629
+ height,
630
+ },
631
+ layout
632
+ );
643
633
  }
644
634
 
645
635
  // Place a new instance of an existing blueprint at a drop point (card units,
@@ -868,6 +858,73 @@ export function renameBlueprintCascade(files, blueprintPath, nextName) {
868
858
  return { path: nextPath, name, fileRenames, writes };
869
859
  }
870
860
 
861
+ // Change a blueprint's Layout origin without moving anything on screen.
862
+ //
863
+ // The origin is inherited, so rewriting it on the template silently re-anchors
864
+ // every instance that doesn't override it: their stored x/y suddenly names a
865
+ // different point of the box, and they all jump by the fraction that moved.
866
+ // This compensates them -- `x += (nextOx - ox) * width` -- in every scene of
867
+ // this deck, the same shape as `renameBlueprintCascade`. Returns the
868
+ // { path, text } writes for the caller to apply, or null when the blueprint is
869
+ // missing/unparseable.
870
+ //
871
+ // An instance that overrides the origin ITSELF is left alone: its x/y is
872
+ // already anchored to its own value, which this change doesn't touch.
873
+ //
874
+ // Never change the origin of a blueprint another deck imports. The importers'
875
+ // scenes aren't in `files`, so their instances are out of reach here and would
876
+ // shift -- the same hazard as changing an imported blueprint's width, but
877
+ // positional.
878
+ export function setBlueprintOriginCascade(files, blueprintPath, nextOrigin) {
879
+ const template = parseBlueprintText(files?.[blueprintPath]);
880
+ if (!template) return null;
881
+ const layout = template.components?.Layout ?? {};
882
+ const originX = layoutOriginX(layout);
883
+ const originY = layoutOriginY(layout);
884
+ const nextX = nextOrigin?.originX ?? originX;
885
+ const nextY = nextOrigin?.originY ?? originY;
886
+ const components = { ...template.components, Layout: { ...layout, originX: nextX, originY: nextY } };
887
+ const text = setBlueprintTemplateComponents(files, blueprintPath, components);
888
+ if (text == null) return null;
889
+ const writes = [{ path: blueprintPath, text }];
890
+ const dx = nextX - originX;
891
+ const dy = nextY - originY;
892
+ if (dx === 0 && dy === 0) return { writes };
893
+ for (const { path, data } of parseSceneFiles(files)) {
894
+ const shifted = shiftInstancesForOrigin(files, data.actors ?? [], path, blueprintPath, dx, dy);
895
+ if (shifted) writes.push({ path, text: formatJson({ ...data, actors: shifted }) });
896
+ }
897
+ return { writes };
898
+ }
899
+
900
+ // One scene's actor list with every non-overriding instance of `blueprintPath`
901
+ // re-anchored, or null when the scene holds none to move. Merged width/height,
902
+ // because an instance inheriting its size has no `Layout.width` of its own to
903
+ // scale the fraction by.
904
+ function shiftInstancesForOrigin(files, actors, scenePath, blueprintPath, dx, dy) {
905
+ let moved = false;
906
+ const next = actors.map((actor) => {
907
+ if (!actorUsesBlueprint(actor, blueprintPath, scenePath)) return actor;
908
+ const own = actor.components?.Layout ?? {};
909
+ if (own.originX !== undefined || own.originY !== undefined) return actor;
910
+ const merged = resolveActorComponents(files, actor).Layout;
911
+ if (!merged) return actor;
912
+ moved = true;
913
+ return {
914
+ ...actor,
915
+ components: {
916
+ ...actor.components,
917
+ Layout: {
918
+ ...own,
919
+ x: (merged.x ?? 0) + dx * (merged.width ?? 0),
920
+ y: (merged.y ?? 0) + dy * (merged.height ?? 0),
921
+ },
922
+ },
923
+ };
924
+ });
925
+ return moved ? next : null;
926
+ }
927
+
871
928
  // Auto-migrate a scene's orphan actors (no `blueprint` field -- the pre-v1
872
929
  // shape) into blueprint instances: mint one blueprint per orphan (its
873
930
  // authored components split by propertyMeta, same as fork), rewrite the actor
@@ -0,0 +1,59 @@
1
+ // The blueprint facts that need nothing from the browser.
2
+ //
3
+ // `blueprint.js` is the blueprint system and it only runs in a page: it imports
4
+ // the SDK and `./scene`, whose file map comes from `import.meta.glob`. These four
5
+ // pieces need none of that, and the kit's own update migration
6
+ // (`scripts/onUpdate.mjs` via `engine/layoutOriginMigration.js`) reads a deck's
7
+ // files under plain Node. So they live here, with NO imports at all, and
8
+ // `blueprint.js` re-exports them -- there is one definition of what a blueprint
9
+ // path is and how a template merges, whichever side is asking.
10
+ //
11
+ // Same shape as `engine/pxart.js` beside `scripts/draw.mjs`: the format is the
12
+ // kit's, and a Node script of the kit's is entitled to read it.
13
+
14
+ export const BLUEPRINTS_DIR = 'blueprints';
15
+
16
+ // A blueprint of this deck (`blueprints/x.scene`) OR of one it imports
17
+ // (`imports/<alias>/blueprints/x.scene`) -- an imported deck's blueprints are
18
+ // placeable like any other, which is most of the point of importing one.
19
+ const BLUEPRINT_PATH_RE = new RegExp(`^(imports/[^/]+/)?${BLUEPRINTS_DIR}/`);
20
+
21
+ export function isBlueprintPath(path) {
22
+ return typeof path === 'string' && path.endsWith('.scene') && BLUEPRINT_PATH_RE.test(path);
23
+ }
24
+
25
+ // Parse a blueprint file's text into { name, components } (the template
26
+ // actor's components), or null if the text isn't a valid blueprint (used to
27
+ // treat a tombstoned/deleted blueprint file as absent).
28
+ export function parseBlueprintText(text) {
29
+ if (typeof text !== 'string') return null;
30
+ let data;
31
+ try {
32
+ data = JSON.parse(text);
33
+ } catch {
34
+ return null;
35
+ }
36
+ const actor = data?.actors?.[0];
37
+ if (!actor || typeof actor !== 'object' || !actor.components) return null;
38
+ const name = typeof data.name === 'string' && data.name.trim() ? data.name : 'Blueprint';
39
+ return { name, components: actor.components };
40
+ }
41
+
42
+ // Per-property merge: the blueprint template is the base, instance overrides
43
+ // win per-property within each component (not whole-component replacement). A
44
+ // component present on only one side appears whole.
45
+ export function mergeComponents(templateComponents, instanceComponents) {
46
+ const merged = {};
47
+ const names = new Set([
48
+ ...Object.keys(templateComponents ?? {}),
49
+ ...Object.keys(instanceComponents ?? {}),
50
+ ]);
51
+ for (const name of names) {
52
+ const templateProps = templateComponents?.[name];
53
+ const instanceProps = instanceComponents?.[name];
54
+ if (templateProps === undefined) merged[name] = { ...instanceProps };
55
+ else if (instanceProps === undefined) merged[name] = { ...templateProps };
56
+ else merged[name] = { ...templateProps, ...instanceProps };
57
+ }
58
+ return merged;
59
+ }