castle-web-cli 0.4.228 → 0.4.230

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 (236) hide show
  1. package/dist/agent-prompts.d.ts +11 -3
  2. package/dist/agent-prompts.js +153 -53
  3. package/dist/agent.d.ts +2 -0
  4. package/dist/agent.js +43 -33
  5. package/dist/api.d.ts +47 -2
  6. package/dist/api.js +85 -16
  7. package/dist/castle-host/host.d.ts +91 -0
  8. package/dist/castle-host/host.js +779 -3
  9. package/dist/castleJson.d.ts +59 -0
  10. package/dist/castleJson.js +267 -3
  11. package/dist/check.js +27 -1
  12. package/dist/cloudGit.d.ts +20 -1
  13. package/dist/cloudGit.js +267 -10
  14. package/dist/contentPack.d.ts +49 -0
  15. package/dist/contentPack.js +273 -0
  16. package/dist/devExperiments.d.ts +21 -0
  17. package/dist/devExperiments.js +139 -0
  18. package/dist/devHub.d.ts +55 -0
  19. package/dist/devHub.js +187 -0
  20. package/dist/devSessionChild.js +3 -1
  21. package/dist/devSessionServer.d.ts +14 -1
  22. package/dist/devSessionServer.js +229 -44
  23. package/dist/experimentAssignment.d.ts +15 -0
  24. package/dist/experimentAssignment.js +41 -0
  25. package/dist/importCheckHook.d.ts +40 -0
  26. package/dist/importCheckHook.js +171 -0
  27. package/dist/importRegression.d.ts +15 -0
  28. package/dist/importRegression.js +100 -0
  29. package/dist/importTrust.d.ts +2 -0
  30. package/dist/importTrust.js +27 -0
  31. package/dist/importUpdateHook.d.ts +18 -0
  32. package/dist/importUpdateHook.js +31 -8
  33. package/dist/importUpdateHookRunner.js +19 -7
  34. package/dist/imports.d.ts +16 -0
  35. package/dist/imports.js +145 -33
  36. package/dist/index.js +8 -1
  37. package/dist/init.d.ts +3 -0
  38. package/dist/init.js +125 -8
  39. package/dist/install.js +4 -1
  40. package/dist/localPaths.js +4 -0
  41. package/dist/login.js +2 -2
  42. package/dist/platformDoc.js +3 -8
  43. package/dist/playPagePolicy.js +3 -1
  44. package/dist/remix.js +5 -0
  45. package/dist/routerTaskReport.d.ts +28 -0
  46. package/dist/routerTaskReport.js +56 -0
  47. package/dist/save-deck.d.ts +18 -0
  48. package/dist/save-deck.js +145 -6
  49. package/dist/serve.d.ts +8 -0
  50. package/dist/serve.js +94 -13
  51. package/dist/serverBundle.d.ts +1 -1
  52. package/dist/serverBundle.js +5 -1
  53. package/dist/sourceLineage.d.ts +42 -0
  54. package/dist/sourceLineage.js +380 -0
  55. package/dist/webSourceSync.d.ts +11 -0
  56. package/dist/webSourceSync.js +26 -9
  57. package/kits/base/CLAUDE.md +2 -3
  58. package/kits/base/castle.json +1 -1
  59. package/kits/base/sdk/README.md +301 -52
  60. package/kits/base/sdk/agent.js +4 -4
  61. package/kits/base/sdk/avatar.d.ts +12 -0
  62. package/kits/base/sdk/avatar.js +23 -0
  63. package/kits/base/sdk/castle.d.ts +6 -1
  64. package/kits/base/sdk/castle.js +3 -0
  65. package/kits/base/sdk/commands.d.ts +208 -0
  66. package/kits/base/sdk/commands.js +16 -0
  67. package/kits/base/sdk/context.d.ts +6 -0
  68. package/kits/base/sdk/experiments.d.ts +15 -0
  69. package/kits/base/sdk/experiments.js +83 -0
  70. package/kits/base/sdk/hub.d.ts +85 -0
  71. package/kits/base/sdk/hub.js +107 -0
  72. package/kits/base/sdk/multiplayer.d.ts +86 -6
  73. package/kits/base/sdk/multiplayer.js +157 -4
  74. package/kits/base/sdk/server/hub.d.ts +169 -0
  75. package/kits/base/sdk/server/hub.js +125 -0
  76. package/kits/base/sdk/server/platformHandle.d.ts +49 -2
  77. package/kits/base/sdk/server/storage.d.ts +55 -2
  78. package/kits/base/sdk/server/wrapper.d.ts +85 -6
  79. package/kits/base/sdk/server/wrapper.js +393 -30
  80. package/kits/base/sdk/transport.d.ts +2 -1
  81. package/kits/base/sdk/transport.js +13 -1
  82. package/kits/hub-game/.prettierrc +5 -0
  83. package/kits/hub-game/CLAUDE.md +146 -0
  84. package/kits/hub-game/blueprints/avatar-0.scene +28 -0
  85. package/kits/hub-game/blueprints/avatar-1.scene +28 -0
  86. package/kits/hub-game/blueprints/avatar-2.scene +28 -0
  87. package/kits/hub-game/blueprints/avatar-3.scene +28 -0
  88. package/kits/hub-game/blueprints/bean/avatar-0.scene +28 -0
  89. package/kits/hub-game/blueprints/bean/avatar-1.scene +28 -0
  90. package/kits/hub-game/blueprints/bean/avatar-2.scene +28 -0
  91. package/kits/hub-game/blueprints/bean/avatar-3.scene +28 -0
  92. package/kits/hub-game/blueprints/blocky/avatar-0.scene +28 -0
  93. package/kits/hub-game/blueprints/blocky/avatar-1.scene +28 -0
  94. package/kits/hub-game/blueprints/blocky/avatar-2.scene +28 -0
  95. package/kits/hub-game/blueprints/blocky/avatar-3.scene +28 -0
  96. package/kits/hub-game/blueprints/pixel/avatar-0.scene +28 -0
  97. package/kits/hub-game/blueprints/pixel/avatar-1.scene +28 -0
  98. package/kits/hub-game/blueprints/pixel/avatar-2.scene +28 -0
  99. package/kits/hub-game/blueprints/pixel/avatar-3.scene +28 -0
  100. package/kits/hub-game/castle.json +96 -0
  101. package/kits/hub-game/code/client/attention.js +133 -0
  102. package/kits/hub-game/code/client/avatar.js +288 -0
  103. package/kits/hub-game/code/client/cabinets.js +90 -0
  104. package/kits/hub-game/code/client/chat.js +135 -0
  105. package/kits/hub-game/code/client/chrome.js +1001 -0
  106. package/kits/hub-game/code/client/doorFrame.js +15 -0
  107. package/kits/hub-game/code/client/firstJoin.js +14 -0
  108. package/kits/hub-game/code/client/grab.js +241 -0
  109. package/kits/hub-game/code/client/hookLayer.js +230 -0
  110. package/kits/hub-game/code/client/idle.js +326 -0
  111. package/kits/hub-game/code/client/keys.js +48 -0
  112. package/kits/hub-game/code/client/pack.js +232 -0
  113. package/kits/hub-game/code/client/packFormat.js +397 -0
  114. package/kits/hub-game/code/client/say.js +127 -0
  115. package/kits/hub-game/code/client/sha256.js +80 -0
  116. package/kits/hub-game/code/client/sound.js +147 -0
  117. package/kits/hub-game/code/client/state.js +131 -0
  118. package/kits/hub-game/code/client/talk.js +259 -0
  119. package/kits/hub-game/code/client/together.js +365 -0
  120. package/kits/hub-game/code/client/wear.js +149 -0
  121. package/kits/hub-game/code/server/actors.js +627 -0
  122. package/kits/hub-game/code/server/blocks.js +103 -0
  123. package/kits/hub-game/code/server/cabinets.js +309 -0
  124. package/kits/hub-game/code/server/game.js +137 -0
  125. package/kits/hub-game/code/server/grab.js +247 -0
  126. package/kits/hub-game/code/server/history.js +96 -0
  127. package/kits/hub-game/code/server/hub.js +1904 -0
  128. package/kits/hub-game/code/server/idle.js +412 -0
  129. package/kits/hub-game/code/server/index.js +64 -0
  130. package/kits/hub-game/code/server/labels.js +59 -0
  131. package/kits/hub-game/code/server/manifest.js +527 -0
  132. package/kits/hub-game/code/server/npcs.js +745 -0
  133. package/kits/hub-game/code/server/party.js +381 -0
  134. package/kits/hub-game/code/server/place.js +43 -0
  135. package/kits/hub-game/code/server/say.js +83 -0
  136. package/kits/hub-game/code/server/wear.js +142 -0
  137. package/kits/hub-game/code/systems/hub.js +2230 -0
  138. package/kits/hub-game/docs/content-pack.md +151 -0
  139. package/kits/hub-game/docs/contract.md +1139 -0
  140. package/kits/hub-game/docs/style.md +137 -0
  141. package/kits/hub-game/drawings/blocky/castle-eye.sprite +58 -0
  142. package/kits/hub-game/drawings/blocky/dash.sprite +59 -0
  143. package/kits/hub-game/drawings/blocky/pom.sprite +59 -0
  144. package/kits/hub-game/drawings/blocky/tabby.sprite +59 -0
  145. package/kits/hub-game/drawings/pixel/castle-arm.sprite +13 -0
  146. package/kits/hub-game/drawings/pixel/castle-body.sprite +23 -0
  147. package/kits/hub-game/drawings/pixel/castle-leg.sprite +12 -0
  148. package/kits/hub-game/drawings/pixel/kai-arm.sprite +14 -0
  149. package/kits/hub-game/drawings/pixel/kai-head.sprite +24 -0
  150. package/kits/hub-game/drawings/pixel/kai-leg.sprite +15 -0
  151. package/kits/hub-game/drawings/pixel/kai-torso.sprite +18 -0
  152. package/kits/hub-game/drawings/pixel/mimi-arm.sprite +13 -0
  153. package/kits/hub-game/drawings/pixel/mimi-head.sprite +23 -0
  154. package/kits/hub-game/drawings/pixel/mimi-leg.sprite +15 -0
  155. package/kits/hub-game/drawings/pixel/mimi-torso.sprite +18 -0
  156. package/kits/hub-game/drawings/pixel/nox-arm.sprite +13 -0
  157. package/kits/hub-game/drawings/pixel/nox-head.sprite +21 -0
  158. package/kits/hub-game/drawings/pixel/nox-leg.sprite +14 -0
  159. package/kits/hub-game/drawings/pixel/nox-torso.sprite +18 -0
  160. package/kits/hub-game/eslint.config.js +20 -0
  161. package/kits/hub-game/fonts.generated.js +9 -0
  162. package/kits/hub-game/index.html +22 -0
  163. package/kits/hub-game/main.jsx +6 -0
  164. package/kits/hub-game/models/avatar-0.pxmodel +21 -0
  165. package/kits/hub-game/models/avatar-1.pxmodel +24 -0
  166. package/kits/hub-game/models/avatar-2.pxmodel +27 -0
  167. package/kits/hub-game/models/avatar-3.pxmodel +22 -0
  168. package/kits/hub-game/models/bean/avatar-0.pxmodel +19 -0
  169. package/kits/hub-game/models/bean/avatar-1.pxmodel +24 -0
  170. package/kits/hub-game/models/bean/avatar-2.pxmodel +22 -0
  171. package/kits/hub-game/models/bean/avatar-3.pxmodel +24 -0
  172. package/kits/hub-game/models/blocky/avatar-0.pxmodel +21 -0
  173. package/kits/hub-game/models/blocky/avatar-1.pxmodel +30 -0
  174. package/kits/hub-game/models/blocky/avatar-2.pxmodel +28 -0
  175. package/kits/hub-game/models/blocky/avatar-3.pxmodel +27 -0
  176. package/kits/hub-game/models/pixel/avatar-0.pxmodel +24 -0
  177. package/kits/hub-game/models/pixel/avatar-1.pxmodel +16 -0
  178. package/kits/hub-game/models/pixel/avatar-2.pxmodel +19 -0
  179. package/kits/hub-game/models/pixel/avatar-3.pxmodel +23 -0
  180. package/kits/hub-game/package-lock.json +365 -0
  181. package/kits/hub-game/package.json +32 -0
  182. package/kits/hub-game/scenes/main.scene +318 -0
  183. package/kits/hub-game/scripts/check.mjs +339 -0
  184. package/kits/hub-game/scripts/fixtures/sdk-stub.mjs +3 -0
  185. package/kits/hub-game/scripts/gen-avatars-bean.mjs +748 -0
  186. package/kits/hub-game/scripts/gen-avatars-blocky.mjs +607 -0
  187. package/kits/hub-game/scripts/gen-avatars-pixel.mjs +771 -0
  188. package/kits/hub-game/scripts/gen-avatars.mjs +621 -0
  189. package/kits/hub-game/scripts/pack.mjs +192 -0
  190. package/kits/hub-game/scripts/test-actors.mjs +666 -0
  191. package/kits/hub-game/scripts/test-attention.mjs +103 -0
  192. package/kits/hub-game/scripts/test-avatar.mjs +472 -0
  193. package/kits/hub-game/scripts/test-ban-join.mjs +194 -0
  194. package/kits/hub-game/scripts/test-blocks.mjs +351 -0
  195. package/kits/hub-game/scripts/test-chat.mjs +98 -0
  196. package/kits/hub-game/scripts/test-classic.mjs +590 -0
  197. package/kits/hub-game/scripts/test-door-jump.mjs +131 -0
  198. package/kits/hub-game/scripts/test-door.mjs +56 -0
  199. package/kits/hub-game/scripts/test-grab.mjs +331 -0
  200. package/kits/hub-game/scripts/test-hub-ops.mjs +835 -0
  201. package/kits/hub-game/scripts/test-hub-trip.mjs +1310 -0
  202. package/kits/hub-game/scripts/test-idle.mjs +518 -0
  203. package/kits/hub-game/scripts/test-interest.mjs +413 -0
  204. package/kits/hub-game/scripts/test-keys.mjs +50 -0
  205. package/kits/hub-game/scripts/test-manifest.mjs +224 -0
  206. package/kits/hub-game/scripts/test-no-forms.mjs +16 -0
  207. package/kits/hub-game/scripts/test-npcs.mjs +714 -0
  208. package/kits/hub-game/scripts/test-pack.mjs +424 -0
  209. package/kits/hub-game/scripts/test-party.mjs +286 -0
  210. package/kits/hub-game/scripts/test-say.mjs +149 -0
  211. package/kits/hub-game/scripts/test-together.mjs +183 -0
  212. package/kits/hub-game/theme.style +3 -0
  213. package/kits/multiplayer-3d/castle.json +5 -5
  214. package/kits/multiplayer-3d/code/client/avatars.js +101 -1
  215. package/kits/multiplayer-3d/code/server/players.js +4 -1
  216. package/kits/multiplayer-3d/code/server/sceneBodies.js +27 -6
  217. package/kits/multiplayer-3d/code/server/world.js +20 -7
  218. package/kits/multiplayer-3d/code/systems/multiplayer.js +222 -11
  219. package/kits/physics-2d/castle.json +2 -2
  220. package/kits/physics-2d/engine/art.js +13 -0
  221. package/kits/physics-2d/engine/assets.js +4 -2
  222. package/kits/physics-2d/engine/scene.js +25 -5
  223. package/kits/physics-3d/CLAUDE.md +6 -1
  224. package/kits/physics-3d/castle.json +3 -3
  225. package/kits/physics-3d/engine3d/Scene3DPlayer.jsx +32 -4
  226. package/kits/physics-3d/engine3d/artobjects.js +2 -2
  227. package/kits/physics-3d/engine3d/materials.js +29 -1
  228. package/kits/physics-3d/engine3d/world3d.js +65 -1
  229. package/kits/physics-3d/systems/physics3d.js +5 -2
  230. package/kits/real-time/castle.json +2 -2
  231. package/kits/real-time/code/client/connection.js +77 -7
  232. package/kits/real-time/code/client/gameHooks.js +63 -3
  233. package/kits/real-time/code/client/messages.js +7 -0
  234. package/kits/real-time/code/server/gameHooks.js +24 -0
  235. package/kits/real-time/code/server/session.js +390 -22
  236. package/package.json +2 -2
@@ -0,0 +1,326 @@
1
+ // Idle play (contract §6, v1.6), the client's half: the emote picker and Sit /
2
+ // Stand in the hub chrome, and drawing what the place says -- each player's
3
+ // emote and seated pose -- on their avatar. Only in a place whose manifest
4
+ // says `idle`; the server checks every request (`code/server/idle.js`).
5
+ //
6
+ // Avatars are pxmodels with a walk but no skeleton to pose, so an emote is a
7
+ // motion of the avatar's whole model (a hop, a spin, a sway, a bow) plus an
8
+ // emoji over its head, and sitting lowers and tips the model onto the seat.
9
+ // Both move only the model inside the actor's drawn node (physics-3d's model
10
+ // rig, a child of the node the Transform places): never the Transform, the
11
+ // body or the network pose, so nothing anyone simulates changes.
12
+
13
+ import { hub, simNow } from './state.js';
14
+
15
+ // The kit's emotes, in the picker's order, with the emoji drawn over the head.
16
+ // The server holds the same ids and durations (`EMOTES` in server/idle.js).
17
+ export const EMOTES = [
18
+ ['wave', '👋'],
19
+ ['dance', '💃'],
20
+ ['cheer', '🎉'],
21
+ ['bow', '🙇'],
22
+ ['spin', '🌀'],
23
+ ];
24
+ const EMOJI = Object.fromEntries(EMOTES);
25
+ // A seat is offered within this many flat metres of its footprint (a long
26
+ // bench is offered along its whole length, not only near its middle).
27
+ export const SIT_OFFER_M = 1.5;
28
+ // A sitter's model drops this far and tips back this much (radians).
29
+ export const SEAT_DROP_M = 0.45;
30
+ const SEAT_TILT = -0.1;
31
+ // Input that gets a sitter up.
32
+ const MOVE_KEYS = ['KeyW', 'KeyA', 'KeyS', 'KeyD', 'ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'Space'];
33
+ // A request is not sent again sooner than this.
34
+ const RESEND_MS = 400;
35
+ // The emoji rises this far over the head as the emote plays.
36
+ const EMOJI_Y = 2.25;
37
+ const EMOJI_RISE = 0.35;
38
+
39
+ const TAU = Math.PI * 2;
40
+ const smooth = (t) => t * t * (3 - 2 * t);
41
+ // 0 at either end of an emote, 1 between, so each starts and ends at rest.
42
+ const envelope = (u) => Math.min(1, u * 6, (1 - u) * 6);
43
+
44
+ // The model's offset for emote `id` a share `u` (0-1) through it, `s` seconds
45
+ // in: `y` metres up, and turns about the model's own x (a bow, + forward), y
46
+ // (a spin) and z (a sway), in radians. All zero at u = 0 and u = 1.
47
+ export function emotePose(id, u, s) {
48
+ const e = envelope(u);
49
+ switch (id) {
50
+ case 'wave':
51
+ return { y: 0, rx: 0, ry: 0, rz: Math.sin(s * TAU * 1.6) * 0.16 * e };
52
+ case 'dance':
53
+ return {
54
+ y: Math.abs(Math.sin(s * Math.PI * 2.4)) * 0.16 * e,
55
+ rx: 0,
56
+ ry: Math.sin(s * TAU * 0.6) * 0.6 * e,
57
+ rz: Math.sin(s * TAU * 1.2) * 0.14 * e,
58
+ };
59
+ case 'cheer':
60
+ return { y: Math.abs(Math.sin(Math.PI * u * 3)) * 0.45, rx: -0.12 * e, ry: 0, rz: 0 };
61
+ case 'bow':
62
+ return { y: 0, rx: Math.sin(Math.PI * u) * 0.6, ry: 0, rz: 0 };
63
+ case 'spin':
64
+ return { y: Math.sin(Math.PI * u) * 0.12, rx: 0, ry: TAU * smooth(u), rz: 0 };
65
+ default:
66
+ return null;
67
+ }
68
+ }
69
+
70
+ export function makeIdle(chrome) {
71
+ const t = {
72
+ chrome,
73
+ emote: null,
74
+ sitPressed: false,
75
+ sentAt: -Infinity,
76
+ seats: [],
77
+ seatsFor: null,
78
+ // actorId -> the rig an emote or seat moved, to put back when it ends
79
+ touched: new Map(),
80
+ // a touch jump (a tap) the Player behavior took since the last frame
81
+ jumped: false,
82
+ watched: null,
83
+ };
84
+ chrome.onEmote?.((id) => {
85
+ t.emote = id;
86
+ });
87
+ chrome.onSit?.(() => {
88
+ t.sitPressed = true;
89
+ });
90
+ return {
91
+ frame: (scene, mp, local, canAct, sceneKey) => frame(t, scene, mp, local, canAct, sceneKey),
92
+ draw: (scene, local) => draw(t, scene, local),
93
+ labels: (scene, local, cam, view, project) => labels(scene, local, cam, view, project),
94
+ // A scene swap: every model moved is put back first (the town's nodes
95
+ // may be parked and drawn again on the way back).
96
+ release: () => release(t),
97
+ dispose: () => release(t),
98
+ };
99
+ }
100
+
101
+ function frame(t, scene, mp, local, canAct, sceneKey) {
102
+ const idle = hub.place?.idle ?? null;
103
+ const net = mp.net ?? null;
104
+ const self = net?.selfId?.() ?? null;
105
+ watchJump(t, scene);
106
+ const emote = t.emote;
107
+ t.emote = null;
108
+ const can = Boolean(idle && canAct && net && self && local?.components.Transform);
109
+ t.chrome.setEmotes?.(can && idle.emotes ? EMOTES : null);
110
+ if (can && idle.emotes && emote && EMOJI[emote]) {
111
+ net.send({ k: 'hub-emote', id: emote });
112
+ }
113
+ if (!can || !idle.seats) {
114
+ // Nothing kept from a time the player could not act.
115
+ t.sitPressed = false;
116
+ t.jumped = false;
117
+ t.standWanted = false;
118
+ t.chrome.sitPrompt?.(null);
119
+ return;
120
+ }
121
+ const now = performance.now();
122
+ const mine = Object.hasOwn(hub.seated, self) ? hub.seated[self] : null;
123
+ if (mine) {
124
+ t.chrome.sitPrompt?.('Stand');
125
+ // A Stand press or a tap to jump is kept until it is sent (a resend
126
+ // waits RESEND_MS), so one made just after sitting is not lost.
127
+ t.standWanted ||= t.sitPressed || t.jumped || moving(scene);
128
+ t.sitPressed = false;
129
+ t.jumped = false;
130
+ if (t.standWanted && now - t.sentAt >= RESEND_MS) {
131
+ t.sentAt = now;
132
+ t.standWanted = false;
133
+ net.send({ k: 'hub-stand' });
134
+ }
135
+ return;
136
+ }
137
+ t.standWanted = false;
138
+ t.jumped = false;
139
+ const pressed = t.sitPressed;
140
+ t.sitPressed = false;
141
+ // A player the place holds still cannot sit.
142
+ const seat = hub.held.has(self) ? null : nearestSeat(t, scene, local, self, sceneKey);
143
+ t.chrome.sitPrompt?.(seat ? 'Sit' : null);
144
+ if (seat && pressed && now - t.sentAt >= RESEND_MS) {
145
+ t.sentAt = now;
146
+ net.send({ k: 'hub-sit', seat });
147
+ }
148
+ }
149
+
150
+ // A tap is a jump the Player behavior takes from the touch controls
151
+ // (`moveInput.consumeJump`) before this system runs, so it is noted as it is
152
+ // taken: the hub wraps the controls' handoff once per controls object.
153
+ function watchJump(t, scene) {
154
+ const input = scene.moveInput;
155
+ if (!input || input === t.watched || typeof input.consumeJump !== 'function') {
156
+ return;
157
+ }
158
+ t.watched = input;
159
+ const consume = input.consumeJump;
160
+ input.consumeJump = function consumeJump(...args) {
161
+ const had = consume.apply(this, args);
162
+ if (had) {
163
+ t.jumped = true;
164
+ }
165
+ return had;
166
+ };
167
+ }
168
+
169
+ // Whether this player is trying to move: a walk or turn key, Space, or the
170
+ // drag stick.
171
+ function moving(scene) {
172
+ const keys = scene.keys;
173
+ if (keys && MOVE_KEYS.some((code) => keys.has?.(code))) {
174
+ return true;
175
+ }
176
+ const stick = scene.moveInput;
177
+ return Boolean(stick?.active && Math.hypot(stick.x ?? 0, stick.y ?? 0) >= 0.15);
178
+ }
179
+
180
+ // The nearest free, shown seat within SIT_OFFER_M of the player, or null.
181
+ function nearestSeat(t, scene, local, self, sceneKey) {
182
+ if (t.seatsFor !== sceneKey) {
183
+ t.seatsFor = sceneKey;
184
+ t.seats = scene
185
+ .getActors()
186
+ .filter((actor) => actor.components?.HubSeat)
187
+ .map((actor) => actor.id);
188
+ }
189
+ if (!t.seats.length) {
190
+ return null;
191
+ }
192
+ const taken = new Set(Object.entries(hub.seated).filter(([id]) => id !== self).map(([, seat]) => seat));
193
+ const me = local.components.Transform;
194
+ let best = null;
195
+ for (const id of t.seats) {
196
+ const actor = hub.hidden.has(id) || taken.has(id) ? null : scene.getActor(id);
197
+ const type = actor?.components.Body?.type;
198
+ if (type === 'dynamic' || type === 'kinematic') {
199
+ // The server refuses a seat that can move (server/idle.js `seatOf`).
200
+ continue;
201
+ }
202
+ const d = actor?.components.Transform ? footprintDistance(actor, me) : Infinity;
203
+ if (d <= SIT_OFFER_M && (!best || d < best.d)) {
204
+ best = { id, d };
205
+ }
206
+ }
207
+ return best?.id ?? null;
208
+ }
209
+
210
+ // Flat distance from a point to an actor's Shape footprint (its box turned by
211
+ // rotationY, or its circle); a point inside is 0.
212
+ export function footprintDistance(actor, p) {
213
+ const t = actor.components.Transform;
214
+ const shape = actor.components.Shape ?? {};
215
+ const dx = p.x - t.x;
216
+ const dz = p.z - t.z;
217
+ if (shape.kind !== 'box' && shape.kind !== undefined) {
218
+ return Math.max(0, Math.hypot(dx, dz) - (shape.radius ?? 0));
219
+ }
220
+ const r = ((t.rotationY ?? 0) * Math.PI) / 180;
221
+ // Into the box's own frame: its width along x, its depth along z.
222
+ const lx = dx * Math.cos(r) - dz * Math.sin(r);
223
+ const lz = dx * Math.sin(r) + dz * Math.cos(r);
224
+ const ox = Math.max(0, Math.abs(lx) - (shape.width ?? 0) / 2);
225
+ const oz = Math.max(0, Math.abs(lz) - (shape.depth ?? 0) / 2);
226
+ return Math.hypot(ox, oz);
227
+ }
228
+
229
+ function actorOf(scene, local, playerId) {
230
+ const mp = scene.multiplayer;
231
+ const self = mp?.net?.selfId?.() ?? null;
232
+ return playerId === self ? (local?.id ?? null) : (mp?.avatars?.actors?.get(playerId) ?? null);
233
+ }
234
+
235
+ // The model inside an actor's drawn node: physics-3d's model rig, the node's
236
+ // child the Transform does not write. Null until the node is built.
237
+ function rigOf(scene, actorId) {
238
+ const node = scene.three?.nodes?.get?.(actorId)?.node;
239
+ const children = node?.children ?? [];
240
+ const parts = node?.userData?.modelParts;
241
+ return (parts && children.find((c) => c.userData?.modelParts === parts)) ?? (children.length === 1 ? children[0] : null);
242
+ }
243
+
244
+ // Each emote and seated pose this frame, on its avatar's model; models no
245
+ // longer moved are put back.
246
+ function draw(t, scene, local) {
247
+ const poses = new Map();
248
+ const now = simNow();
249
+ const add = (actorId, p) => {
250
+ const was = poses.get(actorId) ?? { y: 0, rx: 0, ry: 0, rz: 0 };
251
+ poses.set(actorId, { y: was.y + p.y, rx: was.rx + p.rx, ry: was.ry + p.ry, rz: was.rz + p.rz });
252
+ };
253
+ for (const [playerId, e] of Object.entries(hub.emotes)) {
254
+ const span = e.until - e.at;
255
+ const u = span > 0 ? (now - e.at) / span : 1;
256
+ const actorId = u >= 0 && u < 1 ? actorOf(scene, local, playerId) : null;
257
+ const pose = actorId ? emotePose(e.id, u, (now - e.at) / 1000) : null;
258
+ if (pose) {
259
+ add(actorId, pose);
260
+ }
261
+ }
262
+ for (const playerId of Object.keys(hub.seated)) {
263
+ const actorId = actorOf(scene, local, playerId);
264
+ if (actorId) {
265
+ add(actorId, { y: -SEAT_DROP_M, rx: SEAT_TILT, ry: 0, rz: 0 });
266
+ }
267
+ }
268
+ for (const [actorId, rig] of [...t.touched]) {
269
+ const current = rigOf(scene, actorId);
270
+ if (!poses.has(actorId) || current !== rig) {
271
+ restore(rig);
272
+ t.touched.delete(actorId);
273
+ }
274
+ }
275
+ for (const [actorId, p] of poses) {
276
+ const rig = rigOf(scene, actorId);
277
+ if (!rig) {
278
+ continue;
279
+ }
280
+ const base = (rig.userData.hubIdleBase ??= {
281
+ y: rig.position.y,
282
+ rx: rig.rotation.x,
283
+ ry: rig.rotation.y,
284
+ rz: rig.rotation.z,
285
+ });
286
+ rig.position.y = base.y + p.y;
287
+ rig.rotation.set(base.rx + p.rx, base.ry + p.ry, base.rz + p.rz);
288
+ t.touched.set(actorId, rig);
289
+ }
290
+ }
291
+
292
+ function restore(rig) {
293
+ const base = rig?.userData?.hubIdleBase;
294
+ if (!base) {
295
+ return;
296
+ }
297
+ rig.position.y = base.y;
298
+ rig.rotation.set(base.rx, base.ry, base.rz);
299
+ delete rig.userData.hubIdleBase;
300
+ }
301
+
302
+ function release(t) {
303
+ for (const rig of t.touched.values()) {
304
+ restore(rig);
305
+ }
306
+ t.touched.clear();
307
+ t.seatsFor = null;
308
+ }
309
+
310
+ // The emoji of each emote playing, over its player's head, rising and fading.
311
+ function labels(scene, local, cam, view, project) {
312
+ const out = [];
313
+ const now = simNow();
314
+ for (const [playerId, e] of Object.entries(hub.emotes)) {
315
+ const span = e.until - e.at;
316
+ const u = span > 0 ? (now - e.at) / span : 1;
317
+ const emoji = EMOJI[e.id];
318
+ const actorId = emoji && u >= 0 && u < 1 ? actorOf(scene, local, playerId) : null;
319
+ const at = actorId ? scene.getActor(actorId)?.components.Transform : null;
320
+ const screen = at ? project(cam, at.x, at.y + EMOJI_Y + EMOJI_RISE * u, at.z, view) : null;
321
+ if (screen) {
322
+ out.push({ id: `emote:${playerId}`, x: screen.x, y: screen.y, text: emoji, emote: true, opacity: Math.min(1, (1 - u) * 4) });
323
+ }
324
+ }
325
+ return out;
326
+ }
@@ -0,0 +1,48 @@
1
+ // Keys the browser would scroll with. In a hub place they move the avatar (or
2
+ // jump), and a deck page around the frame must not scroll as well: a keyboard
3
+ // scroll the frame cannot take chains up to the page that embeds it. Text
4
+ // fields keep their keys. Only a hub place builds the hub chrome, so no other
5
+ // deck's keys change.
6
+
7
+ const SCROLL_KEYS = new Set([
8
+ 'ArrowUp',
9
+ 'ArrowDown',
10
+ 'ArrowLeft',
11
+ 'ArrowRight',
12
+ 'Space',
13
+ 'PageUp',
14
+ 'PageDown',
15
+ 'Home',
16
+ 'End',
17
+ ]);
18
+
19
+ export function swallowsScroll(event) {
20
+ if (!SCROLL_KEYS.has(event.code) || event.defaultPrevented) {
21
+ return false;
22
+ }
23
+ if (event.altKey || event.ctrlKey || event.metaKey) {
24
+ return false;
25
+ }
26
+ const target = event.target;
27
+ // Space on a focused button presses it (the talk panel's Say, by Tab).
28
+ if (event.code === 'Space' && target?.tagName === 'BUTTON') {
29
+ return false;
30
+ }
31
+ return !(
32
+ target?.isContentEditable ||
33
+ target?.tagName === 'INPUT' ||
34
+ target?.tagName === 'TEXTAREA' ||
35
+ target?.tagName === 'SELECT'
36
+ );
37
+ }
38
+
39
+ // Installs the guard on `win`; returns its removal.
40
+ export function guardScrollKeys(win = globalThis) {
41
+ const onKey = (event) => {
42
+ if (swallowsScroll(event)) {
43
+ event.preventDefault();
44
+ }
45
+ };
46
+ win.addEventListener?.('keydown', onKey);
47
+ return () => win.removeEventListener?.('keydown', onKey);
48
+ }
@@ -0,0 +1,232 @@
1
+ // Content packs on the town's side (docs/content-pack.md): find the pack a
2
+ // door leads to, fetch it, verify it is the bytes its hash names, validate it
3
+ // against the format, and turn it into content the runtime can mount
4
+ // (`scene.requestedContent`). Nothing in a pack is evaluated: it is JSON, and
5
+ // this module only reads it.
6
+ //
7
+ // Verified packs are kept by hash for the page's life, a few at a time, so a
8
+ // second trip through the same door -- or back into a game -- is a cache hit.
9
+
10
+ import { collectAssets } from '@imports/castle.physics-2d/engine/assets';
11
+ // Namespaces, not named imports: a published engine older than these
12
+ // releases lacks them, and the kit must still build against it (the door
13
+ // then stays shut on `mountsContent`, systems/hub.js).
14
+ import * as Art from '@imports/castle.physics-2d/engine/art';
15
+ import * as Materials from '@imports/castle.physics-3d/engine3d/materials';
16
+ import { initialMedia } from '@imports/castle.physics-2d/engine/files';
17
+ import { validatePack } from './packFormat.js';
18
+ import { sha256Hex } from './sha256.js';
19
+
20
+ const CACHE_MAX = 3;
21
+ const RESOLVE_TIMEOUT_MS = 12000;
22
+ // The engine's own files laid over every pack: the kit's avatar blueprints and
23
+ // everything they draw (models, art, from whichever import holds them) are the
24
+ // town's, whatever a game was built with (contract §11, HUB.md decision 4).
25
+ const AVATAR_BLUEPRINT = /^(imports\/castle\.hub-game\/)?blueprints\/((blocky|bean|pixel)\/)?avatar-\d+\.scene$/;
26
+
27
+ const cache = new Map();
28
+
29
+ // Where a door to another deck leads. In production the host's `Hub.go`
30
+ // returns `{ bundleHash, contentUrl }` from ghost; on `castle-web serve` the
31
+ // serve resolves a deck its castle.json lists (`devDecks`) the same way.
32
+ // Returns `{ sha256, url, sessionKeyPrefix }` or throws.
33
+ // `key` is the session the door leads to: an instance already running keeps
34
+ // the content it started with.
35
+ export async function resolveDeckDoor(deck, key) {
36
+ const query = `deck=${encodeURIComponent(deck)}&key=${encodeURIComponent(key ?? '')}`;
37
+ const res = await fetchWithTimeout(`/__castle/content-pack/resolve?${query}`);
38
+ const body = await res.json().catch(() => null);
39
+ if (!res.ok || body?.status !== 'ok') {
40
+ throw new Error(body?.error ?? `the door to ${deck} did not resolve (HTTP ${res.status})`);
41
+ }
42
+ return body;
43
+ }
44
+
45
+ // The mountable content for a pack, from cache or fetched: `{ id, sha256, url,
46
+ // files, sprites, audio, places, bytes, ms }`. `keep` names packs in use (the place
47
+ // now and the ones the player will walk back into), which eviction skips.
48
+ // Throws when the bytes are not the pack the hash names or fail validation:
49
+ // the door stays shut.
50
+ export async function loadPack(sha256, url, { baseFiles, keep = new Set() } = {}) {
51
+ const hit = cache.get(sha256);
52
+ if (hit) {
53
+ cache.delete(sha256);
54
+ cache.set(sha256, hit);
55
+ return { ...hit, cached: true, ms: 0, fetchMs: 0 };
56
+ }
57
+ const started = performance.now();
58
+ const res = await fetchWithTimeout(url);
59
+ if (!res.ok) {
60
+ throw new Error(`the pack did not load (HTTP ${res.status})`);
61
+ }
62
+ const bytes = new Uint8Array(await res.arrayBuffer());
63
+ const got = await sha256Hex(bytes);
64
+ if (got !== sha256) {
65
+ throw new Error(`the pack is not the one its door names (${got.slice(0, 12)} != ${sha256.slice(0, 12)})`);
66
+ }
67
+ const fetchedMs = performance.now() - started;
68
+ let pack;
69
+ try {
70
+ pack = JSON.parse(new TextDecoder().decode(bytes));
71
+ } catch {
72
+ throw new Error('the pack is not JSON');
73
+ }
74
+ const { errors } = validatePack(pack, { byteLength: bytes.byteLength });
75
+ if (errors.length) {
76
+ throw new Error(`the pack was refused: ${errors.slice(0, 3).join('; ')}`);
77
+ }
78
+ const content = buildContent(sha256, pack, baseFiles ?? {});
79
+ content.url = url;
80
+ content.bytes = bytes.byteLength;
81
+ content.fetchMs = Math.round(fetchedMs);
82
+ content.ms = Math.round(performance.now() - started);
83
+ cache.set(sha256, content);
84
+ for (const [key, dropped] of cache) {
85
+ if (cache.size <= CACHE_MAX) {
86
+ break;
87
+ }
88
+ if (!keep.has(key) && key !== sha256) {
89
+ cache.delete(key);
90
+ release(dropped);
91
+ }
92
+ }
93
+ return { ...content, cached: false };
94
+ }
95
+
96
+ // A pack dropped from the cache takes its art with it: the textures baked from
97
+ // its sprites and its images (the engine's own images, laid over every pack,
98
+ // are the town's and stay).
99
+ function release(content) {
100
+ for (const art of Object.values(content.sprites)) {
101
+ if (art?.kind !== 'image') {
102
+ Materials.releaseArtTextures?.(art);
103
+ }
104
+ }
105
+ // An image is keyed by its bytes, so two packs can share one, and a pack
106
+ // can share one with the deck itself (a pack that is the deck's own content,
107
+ // `matchesOwn`): the deck's own images are never released.
108
+ const kept = new Set([...cache.values()].flatMap((other) => other.ownMedia).concat(Object.values(initialMedia)));
109
+ for (const url of content.ownMedia) {
110
+ if (!kept.has(url)) {
111
+ Materials.releaseArtTextures?.(Art.releaseImageArt?.(url));
112
+ }
113
+ }
114
+ }
115
+
116
+ // Whether a pack is this deck's own content: every file and image it carries
117
+ // is the deck's, byte for byte. A way back into the deck's own place from
118
+ // such a pack can keep the content it left (systems/hub.js).
119
+ export function matchesOwn(content, baseFiles) {
120
+ const carried = content?.carried;
121
+ if (!carried || !baseFiles) {
122
+ return false;
123
+ }
124
+ return (
125
+ carried.files.every((path) => typeof baseFiles[path] === 'string' && baseFiles[path] === content.files[path]) &&
126
+ Object.entries(carried.media).every(([path, url]) => initialMedia[path] === url) &&
127
+ Object.entries(content.audio ?? {}).every(([path, url]) => initialMedia[path] === url)
128
+ );
129
+ }
130
+
131
+ export function cachedPacks() {
132
+ return [...cache.keys()];
133
+ }
134
+
135
+ function buildContent(sha256, pack, baseFiles) {
136
+ const files = {};
137
+ for (const [path, entry] of Object.entries(pack.files)) {
138
+ files[path] = entry.text;
139
+ }
140
+ const media = {};
141
+ for (const [path, entry] of Object.entries(pack.media ?? {})) {
142
+ media[path] = `data:${entry.type};base64,${entry.base64}`;
143
+ }
144
+ for (const path of avatarClosure(baseFiles)) {
145
+ if (typeof baseFiles[path] === 'string') {
146
+ files[path] = baseFiles[path];
147
+ } else if (initialMedia[path]) {
148
+ media[path] = initialMedia[path];
149
+ }
150
+ }
151
+ const { sprites } = collectAssets(files, media);
152
+ return {
153
+ // The place's sounds, as data: URLs (code/client/sound.js). Only the
154
+ // pack's own: the engine lays none of its files over them.
155
+ audio: Object.fromEntries(Object.entries(pack.audio ?? {}).map(([path, entry]) => [path, `data:${entry.type};base64,${entry.base64}`])),
156
+ id: sha256.slice(0, 16),
157
+ sha256,
158
+ files,
159
+ sprites,
160
+ // What the pack itself carries, before the engine's own files are laid
161
+ // over it (`matchesOwn`).
162
+ carried: {
163
+ files: Object.keys(pack.files),
164
+ media: Object.fromEntries(Object.entries(pack.media ?? {}).map(([path, entry]) => [path, `data:${entry.type};base64,${entry.base64}`])),
165
+ },
166
+ ownMedia: Object.values(pack.media ?? {}).map((entry) => `data:${entry.type};base64,${entry.base64}`),
167
+ places: pack.places,
168
+ contract: pack.contract,
169
+ kit: pack.kit,
170
+ };
171
+ }
172
+
173
+ // The avatar blueprints and every file they reach, the way the exporter
174
+ // follows a place's scene (scripts/pack.mjs): a string naming a file the
175
+ // engine has is a reference, as written or inside the referencing import.
176
+ // Computed once per page: the engine's files do not change under it.
177
+ let avatarPaths = null;
178
+ function avatarClosure(baseFiles) {
179
+ if (avatarPaths) {
180
+ return avatarPaths;
181
+ }
182
+ const has = (path) => typeof baseFiles[path] === 'string' || Boolean(initialMedia[path]);
183
+ const seen = new Set();
184
+ const queue = Object.keys(baseFiles).filter((path) => AVATAR_BLUEPRINT.test(path));
185
+ while (queue.length) {
186
+ const path = queue.shift();
187
+ if (seen.has(path)) {
188
+ continue;
189
+ }
190
+ seen.add(path);
191
+ let value;
192
+ try {
193
+ value = typeof baseFiles[path] === 'string' ? JSON.parse(baseFiles[path]) : null;
194
+ } catch {
195
+ value = null;
196
+ }
197
+ const base = /^(imports\/[^/]+\/)/.exec(path)?.[1] ?? '';
198
+ for (const ref of stringsIn(value)) {
199
+ const clean = ref.replace(/#\d+$/, '').replace(/^\.\//, '').replace(/^@(?=imports\/)/, '');
200
+ for (const candidate of [clean, base && !clean.startsWith('imports/') ? base + clean : null]) {
201
+ if (candidate && has(candidate) && !seen.has(candidate)) {
202
+ queue.push(candidate);
203
+ }
204
+ }
205
+ }
206
+ }
207
+ avatarPaths = [...seen];
208
+ return avatarPaths;
209
+ }
210
+
211
+ function stringsIn(value, out = []) {
212
+ if (typeof value === 'string') {
213
+ if (value.length <= 200) {
214
+ out.push(value);
215
+ }
216
+ } else if (Array.isArray(value)) {
217
+ value.forEach((v) => stringsIn(v, out));
218
+ } else if (value && typeof value === 'object') {
219
+ Object.values(value).forEach((v) => stringsIn(v, out));
220
+ }
221
+ return out;
222
+ }
223
+
224
+ async function fetchWithTimeout(url) {
225
+ const controller = new AbortController();
226
+ const timer = setTimeout(() => controller.abort(), RESOLVE_TIMEOUT_MS);
227
+ try {
228
+ return await fetch(url, { signal: controller.signal, credentials: 'same-origin' });
229
+ } finally {
230
+ clearTimeout(timer);
231
+ }
232
+ }