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,2230 @@
1
+ // The hub system: the door, and everything a place draws that a game cannot.
2
+ // It runs after the engine's behaviors every frame and owns the trip between
3
+ // places -- the door animation, the scene swap and session switch under its
4
+ // cover, arrival where the place put you, Back, the return through the door you
5
+ // came in by -- plus the chrome a Tier 0 game speaks through: the declared HUD,
6
+ // actor labels, actors the place hid, holding the player still, the result
7
+ // ribbon, the avatar the player wears everywhere, grabbing and throwing
8
+ // the place's loose objects where it offers that (`client/grab.js`), and idle
9
+ // play -- emotes, seats and the place's sounds -- where it offers that
10
+ // (`client/idle.js`, `client/sound.js`).
11
+ //
12
+ // One engine, one iframe (HUB.md decision 2): going through a door unloads this
13
+ // place's scene, loads the next one's (`scene.requestedScene`), and moves the
14
+ // multiplayer connection to its session (`runtime.multiplayer.switchSession`),
15
+ // all behind the cover. A door to another deck mounts that deck's content pack
16
+ // (`scene.requestedContent`, docs/content-pack.md), fetched and verified while
17
+ // the door opens; a pack that fails keeps the door shut. Every trip is logged as `[hub-trip]`; with `?hubstats`
18
+ // frame rate and memory are drawn and logged as `[hub-fps]`.
19
+ //
20
+ // Where the host can say (`Hub.friends`), a place that is not a game offers the
21
+ // friends in its other layers; Join is a jump (`Hub.jump`): a hub trip to the
22
+ // same place in another session, which leaves the way back as it was.
23
+
24
+ import * as castleSdk from 'castle-web-sdk';
25
+ import { attend, fadeNames, makeAttention } from '../client/attention.js';
26
+ import { doorPoint } from '../client/doorFrame.js';
27
+ import * as Avatar from '../client/avatar.js';
28
+ import * as Cabinets from '../client/cabinets.js';
29
+ import { CHAT_BUBBLE_MS, makeChat } from '../client/chat.js';
30
+ import { makeChrome } from '../client/chrome.js';
31
+ import * as Packs from '../client/pack.js';
32
+ import * as Hub from '../client/state.js';
33
+ import { makeGrab } from '../client/grab.js';
34
+ import { makeIdle } from '../client/idle.js';
35
+ import { makeSay, REACTIONS } from '../client/say.js';
36
+ import { makeSound } from '../client/sound.js';
37
+ import { makeTalk } from '../client/talk.js';
38
+ import { makeTogether, pointerAt } from '../client/together.js';
39
+ import { makeWear } from '../client/wear.js';
40
+
41
+ // The door's three beats, in milliseconds: the door opens and the camera goes
42
+ // through it while the cover comes down; the swap and join happen under the
43
+ // cover; the cover lifts as the camera pulls back from the arrival.
44
+ const OPEN_MS = 650;
45
+ const REVEAL_MS = 700;
46
+ const LOADING_LIMIT_MS = 15000;
47
+ // How long the cover waits for the place to say where it put this player
48
+ // after the session has placed them, before it lifts anyway.
49
+ const ARRIVAL_WAIT_MS = 4000;
50
+ // A game's end waits this long, its result on screen, before the walk back.
51
+ const END_PAUSE_MS = 1200;
52
+ // A player's goals (`hub.label` with `style: "goal"`, v1.13): how many are
53
+ // pointed at, and within how many metres the distance is left off.
54
+ const GOALS_MAX = 2;
55
+ const GOAL_NEAR_M = 6;
56
+ // A way back the host refused as unavailable is asked again once, this long
57
+ // after, before the door stays shut.
58
+ const BACK_RETRY_MS = 1500;
59
+ // How many times one way somewhere recovers from a hub join lost before the
60
+ // session placed the player (`lostJoin`) before it gives up and uncovers.
61
+ const LOST_TRIES_MAX = 2;
62
+ const RIBBON_MS = 60000;
63
+ const TOAST_MS = 4000;
64
+ const DOOR_SWING_DEG = 100;
65
+ // How far below the ground a hidden actor waits.
66
+ const HIDE_DROP_M = 10000;
67
+ const STATS_EVERY_MS = 5000;
68
+ // How many doors deep a return ticket stack goes (a town, a game's lobby, its
69
+ // arena); a deeper trip forgets the oldest.
70
+ const TICKETS_MAX = 4;
71
+ // How often a place asks the host who of the player's friends is in its other
72
+ // layers, while the player is there and idle.
73
+ const FRIENDS_EVERY_MS = 20000;
74
+ // Starting next to a friend: how long after walking in a friend found here
75
+ // still moves the player beside them, and how far the player may have walked.
76
+ const START_NEAR_MS = 12000;
77
+ const START_NEAR_STAY_M = 4;
78
+ // The place takes one jump a second from a player (`JUMP_EVERY_MS` there).
79
+ const JUMP_GAP_MS = 1100;
80
+ // How long "Let's play <door>" from someone here is offered as a Go.
81
+ const PLAY_ASK_MS = 20000;
82
+ // The same player naming the same door is not offered again inside this.
83
+ const PLAY_ASK_AGAIN_MS = 60000;
84
+ // A cabinet (v1.7): how long the cover waits for the host to say it is playing
85
+ // the classic deck -- past the host's own limit on `Hub.go` (30 s), since an
86
+ // answer that lands after the kit gave up would leave the host playing a deck
87
+ // the kit thinks it never went to (`adoptLate` covers what is left of that).
88
+ const CLASSIC_LIMIT_MS = 40000;
89
+ // How far in front of a cabinet's screen the camera ends as the cover comes down.
90
+ const CABINET_CAM_OUT = 1.5;
91
+ // What the multiplayer kit is switched to while a player is away in a classic
92
+ // deck: no session. It is never joined (`leaveSession`).
93
+ const AWAY_JOIN = { mode: 'hub', handoff: null, away: true };
94
+ // Castle refuses a player it has barred from the hub at every door and at the
95
+ // town itself with this code; the kit says so plainly and does not ask again.
96
+ export const HUB_BANNED = 'CAULDRON_HUB_BANNED';
97
+ export const BANNED_TEXT = "You can't enter the town right now.";
98
+
99
+ const ease = (t) => t * t * (3 - 2 * t);
100
+ const lerp = (a, b, t) => a + (b - a) * t;
101
+ const clamp01 = (t) => Math.max(0, Math.min(1, t));
102
+
103
+ // What a return ticket keeps of the content its way back is drawn from: the
104
+ // pack's hash and where it lives, never the pack. Tickets are in
105
+ // `scene.persistent`, which rides in every move report (16 KB at most); the
106
+ // mounted pack stays in the pack cache by hash. null is this deck's own.
107
+ export function packRef(content) {
108
+ if (!content) {
109
+ return null;
110
+ }
111
+ return { sha256: content.sha256, url: content.url ?? null, sessionKeyPrefix: content.sessionKeyPrefix ?? '' };
112
+ }
113
+
114
+ // The content a `packRef` names: a cache hit, or fetched and verified again.
115
+ async function loadRef(ref, url, options) {
116
+ const where = url ?? ref.url;
117
+ if (typeof where !== 'string') {
118
+ throw new Error('the way back names no content pack');
119
+ }
120
+ const content = await Packs.loadPack(ref.sha256, where, options);
121
+ return ref.sessionKeyPrefix ? { ...content, sessionKeyPrefix: ref.sessionKeyPrefix } : content;
122
+ }
123
+
124
+ // `Hub.cancel`, whose refusal changes nothing: an acquisition expires anyway.
125
+ function cancelNow() {
126
+ return Promise.resolve(castleSdk.Hub?.cancel?.()).catch(() => {});
127
+ }
128
+
129
+ export function installSystem(runtime) {
130
+ runtime.registerSystem(new HubSystem());
131
+ }
132
+
133
+ // The session the player is in: the dev or named key, or the session a hub
134
+ // handoff placed them in. A rejoin of the same visit has the same identity, a
135
+ // fresh instance of the same game does not. It names the session joined only
136
+ // once that join has resolved (settleEnd runs only then);
137
+ // public shards share one identity, and a game is never one (doors place
138
+ // games by pad or exact key).
139
+ function sessionKey(scene) {
140
+ const target = scene.multiplayer?.target ?? null;
141
+ if (target?.mode === 'hub') {
142
+ return `hub:${target.handoff?.sessionId ?? ''}`;
143
+ }
144
+ return `${target?.mode ?? 'public'}:${target?.key ?? ''}`;
145
+ }
146
+
147
+ class HubSystem {
148
+ constructor() {
149
+ this.chrome = null;
150
+ this.trip = null;
151
+ this.pendingEnd = null;
152
+ this.endSession = null;
153
+ this.helloNet = null;
154
+ this.helloAvatar = null;
155
+ this.scenePath = null;
156
+ this.sceneKey = null;
157
+ this.doorBase = new Map();
158
+ this.stash = new Map();
159
+ this.tinted = new Map();
160
+ this.spawnedHere = new Set();
161
+ this.wear = makeWear();
162
+ this.toast = { text: '', until: 0 };
163
+ this.stats = statsWanted();
164
+ this.frames = 0;
165
+ this.fpsAt = 0;
166
+ this.fps = 0;
167
+ this.statsAt = 0;
168
+ this.tripCount = 0;
169
+ // Friends in other layers of this place: null until the host answers, and
170
+ // for good once it cannot (no hub, no friends, an older host).
171
+ this.friends = null;
172
+ // Every friend the host named, the ones in this layer included (the
173
+ // People list marks them and points the way to them).
174
+ this.friendsAll = null;
175
+ this.friendsAt = -Infinity;
176
+ this.friendsAsking = false;
177
+ this.friendsOff = false;
178
+ // Whether this host runs the hub (it answered Hub.friends), so takes
179
+ // reports; and a report in flight, or reporting refused for good.
180
+ this.hubHost = false;
181
+ this.reporting = false;
182
+ this.reportOff = false;
183
+ this.attention = makeAttention();
184
+ this.together = makeTogether();
185
+ this.say = makeSay();
186
+ // "Let's play <door>" offered to this player: the offer up now, and
187
+ // `${playerId}:${door}` -> when each was last offered.
188
+ this.playAsk = null;
189
+ this.playAsked = new Map();
190
+ this.chat = makeChat();
191
+ this.namesTouched = new WeakMap();
192
+ }
193
+
194
+ // Other players' names in a town: near ones only, and smaller
195
+ // (`attention.js`). After the multiplayer kit has placed them this frame.
196
+ fadeNames(scene) {
197
+ const place = Hub.hub.place;
198
+ const town = Boolean(place && !place.result && !this.trip);
199
+ fadeNames(scene.multiplayer, scene.actorWith('Player')?.components.Transform, town, this.namesTouched);
200
+ }
201
+
202
+ afterBehaviors(scene) {
203
+ const mp = scene.multiplayer;
204
+ if (!mp) {
205
+ return;
206
+ }
207
+ const now = performance.now();
208
+ this.chrome ??= makeChrome({
209
+ onBack: () => this.back(scene),
210
+ onAvatar: (i) => Avatar.choose(scene, i),
211
+ avatarCount: Avatar.AVATARS,
212
+ onPerson: (person, action) => this.join(this.scene, person, action),
213
+ onJumpDoor: (door) => this.goDoor(this.scene, door),
214
+ onAsk: (ask, yes) => this.answer(this.scene, ask, yes),
215
+ onLeaveParty: () => this.scene?.multiplayer?.net?.send({ k: 'hub-party', op: 'leave' }),
216
+ onReportChat: (line) => this.reportChat(line),
217
+ onReport: (person) => this.report(person),
218
+ });
219
+ Avatar.load(scene);
220
+ this.talk ??= makeTalk(this.chrome);
221
+ this.grab ??= makeGrab(this.chrome);
222
+ this.idle ??= makeIdle(this.chrome);
223
+ this.sound ??= makeSound();
224
+ if (!this.sayHooked) {
225
+ this.sayHooked = true;
226
+ this.chrome.onSay?.((what) => this.saying(what));
227
+ }
228
+ this.scene = scene;
229
+ // The host's Back control (a host that draws one, over a hub place) is
230
+ // answered the way the kit's own is: back through the door (contract §5).
231
+ if (!this.backHooked && typeof castleSdk.Hub?.onBack === 'function') {
232
+ this.backHooked = true;
233
+ castleSdk.Hub.onBack(() => this.back(this.scene));
234
+ }
235
+ const per = (scene.persistent ??= {});
236
+ per.hubTickets ??= [];
237
+ this.keepResident(scene, per.hubTickets);
238
+ // A handle for test drivers and phone measurements.
239
+ globalThis.__hub = { scene, system: this, state: Hub.hub };
240
+ globalThis.__hubPacks ??= () => Packs.cachedPacks().length;
241
+
242
+ if (sceneKeyOf(scene) !== this.sceneKey) {
243
+ this.enterScene(scene);
244
+ }
245
+ const local = scene.actorWith('Player');
246
+ this.wearAvatar(scene, local);
247
+ this.applyTune(local);
248
+ this.watchSession(scene, mp);
249
+ this.sayHello(scene, mp);
250
+ this.followPlace(scene);
251
+ this.holdFall(scene, local);
252
+ this.applySpawns(scene);
253
+ this.applyTints(scene);
254
+ // Visibility is applied once more after every other system: the
255
+ // multiplayer kit, registered after this one, writes a moving actor's
256
+ // network pose each frame, which would lift a hidden one back up.
257
+ if (this.lateFor !== scene && typeof scene.registerSystem === 'function') {
258
+ this.lateFor = scene;
259
+ scene.registerSystem({
260
+ afterBehaviors: (s) => {
261
+ this.applyVisibility(s);
262
+ this.applyWear(s);
263
+ this.fadeNames(s);
264
+ },
265
+ });
266
+ }
267
+ this.applyVisibility(scene);
268
+ this.applyWear(scene);
269
+ this.adoptLate(scene);
270
+ this.runCommands(scene, now);
271
+ this.askFriends(scene, mp, now);
272
+ this.together.frame(mp, this.friendsAll, !this.trip && this.pendingEnd === null, now, this.chrome.peopleOpen?.() === true);
273
+
274
+ this.stepEnd(scene, mp, now);
275
+ const held = Hub.hub.held.has(mp.net?.selfId?.());
276
+ this.talk.frame(scene, mp, !this.trip && this.pendingEnd === null);
277
+ // Idle play (v1.6): before input is locked, since a sitter's move is
278
+ // what gets them up (a seat is a hold).
279
+ this.idle.frame(scene, mp, local, !this.trip && this.pendingEnd === null && !this.talk.talking(), this.sceneKey);
280
+ this.idle.draw(scene, local);
281
+ this.sound.frame(scene, local, !this.trip);
282
+ if (this.trip || held || this.talk.typing() || this.chrome.chatFocused?.()) {
283
+ lockInput(scene);
284
+ }
285
+ // Grabbing and throwing (v1.3), in a place that offers it: after this
286
+ // frame's physics step, before the multiplayer kit reports what it owns.
287
+ this.grab.frame(scene, mp, local, !this.trip && this.pendingEnd === null && !this.talk.talking());
288
+ if (this.trip) {
289
+ this.stepTrip(scene, mp, local, now);
290
+ } else if (!Hub.hub.faced) {
291
+ // A join that was not a trip (the first one) faces the arrival too.
292
+ this.faceArrival(scene);
293
+ }
294
+ this.drawChrome(scene, local, now);
295
+ this.measure(scene, mp, now);
296
+ }
297
+
298
+ // The places this player will walk back into stay built while they are away
299
+ // (physics-3d's `residentScenes`): a return redraws the town from the nodes
300
+ // it left, rather than rebuilding every mesh behind the door.
301
+ keepResident(scene, tickets) {
302
+ const key = tickets.map((t) => t.key).join('|');
303
+ if (key !== this.residentKey) {
304
+ this.residentKey = key;
305
+ scene.residentScenes = new Set(tickets.map((t) => t.key));
306
+ }
307
+ }
308
+
309
+ // The place's server decides which scene this session is (contract §2). A
310
+ // runtime showing another one -- a deck opened on a scene that is not its
311
+ // main place -- switches to the place's.
312
+ followPlace(scene) {
313
+ const place = Hub.hub.place;
314
+ if (!place || this.trip || scene.requestedScene) {
315
+ return;
316
+ }
317
+ if (place.scene && scene.currentScenePath !== place.scene) {
318
+ scene.requestedScene = place.scene;
319
+ }
320
+ }
321
+
322
+ // A player falling in a place that catches falls (contract §5, `fallY`)
323
+ // stops just under it until the place puts them back: a pose past the
324
+ // world's floor is never read, so a client that kept falling would never be
325
+ // caught.
326
+ holdFall(scene, local) {
327
+ const fallY = Hub.hub.place?.fallY;
328
+ const t = local?.components.Transform;
329
+ if (typeof fallY !== 'number' || this.trip || !t || t.y >= fallY - 1) {
330
+ return;
331
+ }
332
+ t.y = fallY - 1;
333
+ scene.physics3d?.bodyOf?.(local)?.setTranslation({ x: t.x, y: t.y, z: t.z }, true);
334
+ scene.physics3d?.setVelocity?.(local, { x: 0, y: 0, z: 0 });
335
+ }
336
+
337
+ enterScene(scene) {
338
+ this.scenePath = scene.currentScenePath;
339
+ this.sceneKey = sceneKeyOf(scene);
340
+ this.doorBase.clear();
341
+ this.stash.clear();
342
+ this.tinted.clear();
343
+ this.spawnedHere.clear();
344
+ this.wear.clear(scene);
345
+ this.idle?.release();
346
+ // What was said in the place just left stays there.
347
+ this.say.clear();
348
+ this.together.clear();
349
+ this.playAsk = null;
350
+ this.playAsked.clear();
351
+ }
352
+
353
+ // Every scene load, the same scene reloaded included: the actors are the
354
+ // file's again, so what was dropped, painted or spawned in them is gone.
355
+ reset(scene) {
356
+ this.stash.clear();
357
+ this.tinted.clear();
358
+ this.spawnedHere.clear();
359
+ if (scene) {
360
+ this.wear.clear(scene);
361
+ } else {
362
+ this.wear.forget();
363
+ }
364
+ }
365
+
366
+ // What players wear (`hub.wear`, v1.4), over each avatar and this player's
367
+ // own body. Also after every other system, as visibility is: the
368
+ // multiplayer kit moves the other avatars after this one runs.
369
+ applyWear(scene) {
370
+ const self = scene.multiplayer?.net?.selfId?.() ?? null;
371
+ const style = Avatar.style();
372
+ this.wear.frame(scene, scene.actorWith('Player'), Hub.hub.wearing, (playerId) => {
373
+ const index = playerId === self ? Avatar.current(scene) : Hub.hub.avatars.get(playerId);
374
+ return Avatar.top(index, Avatar.drawn(scene.files, index, style));
375
+ });
376
+ }
377
+
378
+ // The place's tuning of this player's own controller (`hub.tune`): the
379
+ // preset's speed and jump, as the scene authored them, times the place's
380
+ // multipliers. Bounded again here; the server's clamp follows the same.
381
+ applyTune(local) {
382
+ const player = local?.components.Player;
383
+ if (!player) {
384
+ return;
385
+ }
386
+ if (this.tuneBase?.player !== player) {
387
+ this.tuneBase = { player, speed: player.speed, jumpSpeed: player.jumpSpeed };
388
+ }
389
+ const t = Hub.hub.tune;
390
+ const mul = (v, lo, hi) => (typeof v === 'number' && Number.isFinite(v) ? Math.min(hi, Math.max(lo, v)) : 1);
391
+ const speed = this.tuneBase.speed * mul(t?.speed, 0.25, 3);
392
+ const jumpSpeed = this.tuneBase.jumpSpeed * mul(t?.jump, 0.5, 2.5);
393
+ if (player.speed !== speed) {
394
+ player.speed = speed;
395
+ }
396
+ if (player.jumpSpeed !== jumpSpeed) {
397
+ player.jumpSpeed = jumpSpeed;
398
+ }
399
+ }
400
+
401
+ // The local player wears its avatar's model (contract §11), from this
402
+ // viewer's set (`Avatar.style`); asked every frame, so a set that changes
403
+ // under a running page is worn on the next one.
404
+ wearAvatar(scene, local) {
405
+ const model = local?.components.Model;
406
+ if (!model) {
407
+ return;
408
+ }
409
+ const file = Avatar.model(scene.files, Avatar.current(scene));
410
+ if (file && model.file !== file) {
411
+ model.file = file;
412
+ }
413
+ }
414
+
415
+ // Each session this runtime joins hears who it is: the avatar, the door it
416
+ // came through, how many came with it, and what it carries back. It goes
417
+ // out at once, so arrival never waits on the avatar; when the avatar
418
+ // changes (the platform's answer, a pick) it says hello again and the place
419
+ // redraws the body in the new one.
420
+ sayHello(scene, mp) {
421
+ const net = mp.net;
422
+ if (!net) {
423
+ return;
424
+ }
425
+ const avatar = Avatar.current(scene);
426
+ if (net === this.helloNet && avatar === this.helloAvatar) {
427
+ return;
428
+ }
429
+ // The same session again (the avatar changed): the place keeps what it
430
+ // knows this client holds (a cabinet's card, v1.7).
431
+ const again = net === this.helloNet;
432
+ if (!again) {
433
+ // A player who walks in (no door, no jump to a friend) starts beside a
434
+ // friend or party member who is already here, once, if one turns up in
435
+ // the first moments and the player has not walked off.
436
+ const arrivingNow = scene.persistent?.hubArriving ?? null;
437
+ this.startNear = !arrivingNow?.door && typeof arrivingNow?.near !== 'string' ? { until: performance.now() + START_NEAR_MS, at: null, asked: false } : null;
438
+ this.friendsAt = -Infinity;
439
+ // Another session (a door, a layer): what was said in the last one stays there.
440
+ this.say.clear();
441
+ this.together.clear();
442
+ this.playAsk = null;
443
+ this.playAsked.clear();
444
+ this.chat.reset();
445
+ }
446
+ this.helloNet = net;
447
+ this.helloAvatar = avatar;
448
+ const per = scene.persistent;
449
+ const arriving = per.hubArriving ?? null;
450
+ net.send({
451
+ k: 'hub-hello',
452
+ avatar,
453
+ from: arriving?.door ?? null,
454
+ party: arriving?.party ?? 1,
455
+ carry: arriving?.returning && per.hubResult ? { result: per.hubResult } : null,
456
+ // A jump to a friend: the place puts this player beside them.
457
+ ...(typeof arriving?.near === 'string' ? { near: arriving.near } : {}),
458
+ ...(again ? { again: true } : {}),
459
+ });
460
+ }
461
+
462
+ // Hide what the place hid, and put back what it showed again (contract §10).
463
+ // A hidden actor is dropped far below the ground, collider and all, rather
464
+ // than despawned: the multiplayer kit reports a despawned scene actor to the
465
+ // session as gone for good, which `show` could never undo.
466
+ // An actor the place moves (`hub.move`) has its pose written by the network
467
+ // each frame it moves, which lifts it back up: it is dropped again, and
468
+ // shown again by lifting it from wherever it is.
469
+ applyVisibility(scene) {
470
+ for (const id of Hub.hub.hidden) {
471
+ const t = scene.getActor(id)?.components.Transform;
472
+ if (t && t.y > -HIDE_DROP_M / 2) {
473
+ this.stash.set(id, true);
474
+ t.y -= HIDE_DROP_M;
475
+ }
476
+ }
477
+ for (const id of this.stash.keys()) {
478
+ if (!Hub.hub.hidden.has(id)) {
479
+ this.stash.delete(id);
480
+ const t = scene.getActor(id)?.components.Transform;
481
+ if (t && t.y < -HIDE_DROP_M / 2) {
482
+ t.y += HIDE_DROP_M;
483
+ }
484
+ }
485
+ }
486
+ }
487
+
488
+ // Copies the place spawned (`hub.spawn`, contract §10): each is its
489
+ // template's components at the copy's point, as authored (not as painted
490
+ // or hidden: the place sends the template's authored components). A copy is
491
+ // made once: one a behavior removed is left for the multiplayer kit to
492
+ // report gone. A copy the place despawned is removed without that report,
493
+ // since the place already knows, and the multiplayer kit forgets its pose
494
+ // history.
495
+ applySpawns(scene) {
496
+ const want = Hub.hub.spawned;
497
+ const mp = scene.multiplayer;
498
+ for (const [id, copy] of Object.entries(want)) {
499
+ if (this.spawnedHere.has(id) || scene.getActor(id) || mp?.gone?.has(id)) {
500
+ continue;
501
+ }
502
+ const templates = Hub.hub.spawnTemplates;
503
+ const template = Object.hasOwn(templates, copy.from) ? templates[copy.from] : null;
504
+ if (!template || typeof template !== 'object') {
505
+ continue;
506
+ }
507
+ const components = JSON.parse(JSON.stringify(template));
508
+ components.Transform = { ...components.Transform, x: copy.x, y: copy.y, z: copy.z, rotationY: copy.rotationY };
509
+ scene.spawnActor({ id, components });
510
+ this.spawnedHere.add(id);
511
+ }
512
+ for (const id of this.spawnedHere) {
513
+ if (!Object.hasOwn(want, id)) {
514
+ this.spawnedHere.delete(id);
515
+ this.stash.delete(id);
516
+ this.tinted.delete(id);
517
+ mp?.avatars?.retired?.add(id);
518
+ scene.despawnActor(id);
519
+ mp?.forgetObject?.(id);
520
+ }
521
+ }
522
+ }
523
+
524
+ // Paint what the place painted, and put back what it stopped painting
525
+ // (`hub.tint`, contract §10). A Shape that glows glows in its new colour.
526
+ applyTints(scene) {
527
+ const tints = Hub.hub.tints;
528
+ for (const [id, color] of Object.entries(tints)) {
529
+ const shape = scene.getActor(id)?.components.Shape;
530
+ if (!shape || (shape.color === color && shape.tint === color)) {
531
+ continue;
532
+ }
533
+ if (!this.tinted.has(id)) {
534
+ this.tinted.set(id, { color: shape.color, tint: shape.tint, emissive: shape.emissive });
535
+ }
536
+ // A textured face takes its colour from `tint`, a plain one from `color`.
537
+ shape.color = color;
538
+ shape.tint = color;
539
+ if (glows(this.tinted.get(id).emissive)) {
540
+ shape.emissive = dim(color);
541
+ }
542
+ }
543
+ for (const [id, authored] of this.tinted) {
544
+ if (!Object.hasOwn(tints, id)) {
545
+ this.tinted.delete(id);
546
+ const shape = scene.getActor(id)?.components.Shape;
547
+ if (shape) {
548
+ shape.color = authored.color;
549
+ shape.tint = authored.tint;
550
+ shape.emissive = authored.emissive;
551
+ }
552
+ }
553
+ }
554
+ }
555
+
556
+ // The session under this player ended without a trip of ours: the game's
557
+ // server crashed or was replaced. A game is left through the door the player
558
+ // came in by (contract §5); anywhere else the multiplayer kit rejoins.
559
+ watchSession(scene, mp) {
560
+ if (this.trip) {
561
+ // Our own switch closes the old connection; that is not an ending.
562
+ this.lastNet = null;
563
+ return;
564
+ }
565
+ const last = this.lastNet;
566
+ if (mp.net && !mp.net.closed?.()) {
567
+ this.lastNet = mp.net;
568
+ }
569
+ if (!last || !last.closed?.()) {
570
+ return;
571
+ }
572
+ this.lastNet = null;
573
+ const inGame = Boolean(Hub.hub.place?.result);
574
+ Hub.clear();
575
+ if (inGame && scene.persistent.hubTickets.length) {
576
+ this.toast = { text: 'The game ended', until: performance.now() + TOAST_MS };
577
+ this.back(scene);
578
+ }
579
+ }
580
+
581
+ runCommands(scene, now) {
582
+ while (Hub.hub.commands.length && !this.trip) {
583
+ const msg = Hub.hub.commands.shift();
584
+ if (msg.k === 'hub-go' && msg.classic) {
585
+ // A cabinet: the host plays a classic deck; this place waits (v1.7).
586
+ this.goClassic(scene, msg);
587
+ } else if (msg.k === 'hub-go' && !msg.key) {
588
+ // A pad ghost fired: the host acquires the trip (Hub.go).
589
+ this.goHub(scene, msg);
590
+ } else if (msg.k === 'hub-go') {
591
+ this.go(scene, msg);
592
+ } else if (msg.k === 'hub-result') {
593
+ scene.persistent.hubResult = { ...msg.result, at: Date.now() };
594
+ } else if (msg.k === 'hub-end') {
595
+ this.pendingEnd = now + END_PAUSE_MS;
596
+ this.endSession = sessionKey(scene);
597
+ const r = scene.persistent.hubResult;
598
+ this.toast = { text: r && Date.now() - r.at < 30000 ? resultLine(r) : 'Game over', until: now + END_PAUSE_MS + 200 };
599
+ }
600
+ }
601
+ }
602
+
603
+ // Through a door ghost fixed a group for (the place's server fired its pad):
604
+ // the host acquires the destination (`Hub.go`), whose content pack loads
605
+ // under the cover, and the join is a hub join on the handoff. The way back
606
+ // is `Hub.back`, never a remembered session.
607
+ goHub(scene, msg) {
608
+ const mp = scene.multiplayer;
609
+ const per = scene.persistent;
610
+ // The join this runtime began with, before any hub trip: the one a failed
611
+ // trip from the root of the host's trail can make again.
612
+ if (!(per.hubDepth > 0) && mp.target?.mode !== 'hub') {
613
+ per.hubRootJoin = mp.target ?? { mode: 'public' };
614
+ }
615
+ per.hubTickets.push({
616
+ scene: this.scenePath,
617
+ key: this.sceneKey,
618
+ content: packRef(scene.content),
619
+ join: mp.target ?? { mode: 'public' },
620
+ door: msg.door,
621
+ title: Hub.hub.place?.title ?? 'Back',
622
+ place: Hub.hub.place?.id ?? 'main',
623
+ // How many went through together, so the way back arrives as a group.
624
+ party: msg.party ?? 1,
625
+ hub: true,
626
+ });
627
+ if (per.hubTickets.length > TICKETS_MAX) {
628
+ per.hubTickets.shift();
629
+ }
630
+ this.startTrip(scene, {
631
+ scene: null,
632
+ content: undefined,
633
+ deck: msg.title ?? msg.door,
634
+ pending: this.resolveHub(scene, () => castleSdk.Hub.go(msg.door)),
635
+ join: null,
636
+ title: msg.title,
637
+ exitDoor: doorActor(scene, msg.door),
638
+ arrive: { door: msg.door, party: msg.party ?? 1, returning: false },
639
+ pushedTicket: true,
640
+ hubStep: 1,
641
+ });
642
+ }
643
+
644
+ // Through a cabinet (v1.7): a door to a classic deck, which the host plays
645
+ // itself over this page. It is a hub trip with no destination session and no
646
+ // content: the door-open beat and the cover, then this player leaves the
647
+ // place's session and waits under the cover (`away`) until Back, which is
648
+ // the ordinary way back (`back`) -- the same ticket a door's trip pushes,
649
+ // so `Hub.back` returns them to this place, at the cabinet. The scene is
650
+ // not swapped: the town stays as it is under the cover.
651
+ // On the dev serve (`msg.dev`, the kit's fixture) there is no host to ask:
652
+ // the ticket remembers the session left, and Back rejoins it.
653
+ goClassic(scene, msg) {
654
+ const mp = scene.multiplayer;
655
+ const per = scene.persistent;
656
+ const host = msg.dev !== true;
657
+ if (host && !(per.hubDepth > 0) && mp.target?.mode !== 'hub') {
658
+ per.hubRootJoin = mp.target ?? { mode: 'public' };
659
+ }
660
+ const ticket = {
661
+ scene: this.scenePath,
662
+ key: this.sceneKey,
663
+ content: packRef(scene.content),
664
+ join: mp.target ?? { mode: 'public' },
665
+ door: msg.door,
666
+ title: Hub.hub.place?.title ?? 'Back',
667
+ place: Hub.hub.place?.id ?? 'main',
668
+ party: 1,
669
+ ...(host ? { hub: true } : {}),
670
+ };
671
+ per.hubTickets.push(ticket);
672
+ if (per.hubTickets.length > TICKETS_MAX) {
673
+ per.hubTickets.shift();
674
+ }
675
+ this.startTrip(scene, {
676
+ scene: this.scenePath,
677
+ content: undefined,
678
+ deck: msg.title ?? msg.door,
679
+ classic: { host, ticket },
680
+ pending: host ? this.resolveClassic(() => castleSdk.Hub.go(msg.door)) : { done: true, error: null },
681
+ join: null,
682
+ title: msg.title,
683
+ exitDoor: doorActor(scene, msg.door),
684
+ arrive: { door: msg.door, party: 1, returning: false },
685
+ pushedTicket: true,
686
+ });
687
+ }
688
+
689
+ // A cabinet's acquisition: the host answers `{ status: 'ok', kind:
690
+ // 'classic' }` once it has committed the trip itself (there is no session
691
+ // to join) and is playing the deck. Anything else keeps the door shut: a
692
+ // refusal, a host without doors, and a host that answers an ordinary
693
+ // handoff (one from before cabinets), which is given back. In the chain
694
+ // with every other acquisition and cancel (`resolveHub`).
695
+ resolveClassic(acquire) {
696
+ const state = { done: false, error: null, code: null, abandoned: false, target: null };
697
+ const run = async () => {
698
+ let giveBack = false;
699
+ try {
700
+ if (typeof castleSdk.Hub?.go !== 'function') {
701
+ throw new Error('this host has no doors');
702
+ }
703
+ const handoff = await acquire();
704
+ if (handoff?.status !== 'ok') {
705
+ throw new Error(handoff?.status ?? 'unavailable');
706
+ }
707
+ if (handoff.kind !== 'classic') {
708
+ giveBack = true;
709
+ throw new Error('this host cannot play a classic deck');
710
+ }
711
+ } catch (err) {
712
+ state.error = err?.message ?? String(err);
713
+ state.code = typeof err?.code === 'string' ? err.code : null;
714
+ }
715
+ state.done = true;
716
+ if (giveBack) {
717
+ await cancelNow();
718
+ } else if (!state.error && state.abandoned) {
719
+ // The host is playing the deck after the kit stopped waiting.
720
+ this.classicLate = state;
721
+ }
722
+ };
723
+ this.hubChain = (this.hubChain ?? Promise.resolve()).then(run, run);
724
+ return state;
725
+ }
726
+
727
+ // A cabinet's trip once the cover is down: wait for the host, then away, or
728
+ // the door stays shut.
729
+ stepClassic(scene, trip, mp, now) {
730
+ const pending = trip.target.pending;
731
+ trip.marks.covered ??= now;
732
+ this.chrome.setCover(1, trip.target.title);
733
+ if (!pending.done && now - trip.startedAt < CLASSIC_LIMIT_MS) {
734
+ return;
735
+ }
736
+ if (pending.done && !pending.error) {
737
+ this.away(scene, trip.target, mp);
738
+ return;
739
+ }
740
+ if (!pending.done) {
741
+ // Should the host still answer that it is playing: `adoptLate`.
742
+ pending.abandoned = true;
743
+ pending.target = trip.target;
744
+ }
745
+ if (pending.code === HUB_BANNED) {
746
+ trip.target.stuck = BANNED_TEXT;
747
+ }
748
+ this.shutDoor(scene, trip, pending.error ?? 'it took too long', now);
749
+ }
750
+
751
+ // Away in a classic deck: this player leaves the place's session (the place
752
+ // is left, not held) and nothing runs but the cover until Back. `target` is
753
+ // the cabinet trip's.
754
+ away(scene, target, mp) {
755
+ Hub.clear();
756
+ this.leaveSession(scene, mp);
757
+ const per = scene.persistent;
758
+ if (target.classic.host) {
759
+ // The host committed the trip: its trail holds it, and it draws Back.
760
+ per.hubDepth = Math.max(0, per.hubDepth ?? 0) + 1;
761
+ } else {
762
+ this.toast = { text: 'No classic player on the dev serve. Back returns to the cabinet.', until: Infinity };
763
+ }
764
+ per.hubArriving = null;
765
+ // Nothing is brought back from a classic deck.
766
+ delete per.hubResult;
767
+ this.friends = null;
768
+ this.friendsAll = null;
769
+ this.tripCount += this.trip ? 0 : 1;
770
+ this.trip = {
771
+ n: this.trip?.n ?? this.tripCount,
772
+ target: { ...target, pending: null },
773
+ phase: 'away',
774
+ from: this.scenePath,
775
+ startedAt: performance.now(),
776
+ cam0: null,
777
+ heapBefore: heapMB(),
778
+ marks: {},
779
+ };
780
+ console.log(`[hub-trip] ${JSON.stringify({ n: this.trip.n, away: true, door: target.arrive?.door ?? target.classic.ticket?.door ?? null, deck: target.deck ?? null })}`);
781
+ }
782
+
783
+ // Out of the session, into none: the multiplayer kit closes the connection
784
+ // and drops everything drawn from it, as for any switch, and is told the
785
+ // join it was switched to has failed, which is what stops it joining: it
786
+ // retries no failed hub join, and `AWAY_JOIN` is one it could not make
787
+ // anyway. The next `switchSession` (Back) clears that.
788
+ leaveSession(scene, mp) {
789
+ mp.switchSession(scene, AWAY_JOIN, { quiet: true });
790
+ mp.joinFailed = true;
791
+ this.helloNet = null;
792
+ this.lastNet = null;
793
+ }
794
+
795
+ // The host said it is playing a classic deck after the kit had stopped
796
+ // waiting and reopened the place: follow the host, since its Back is the
797
+ // only way out of the deck it is showing.
798
+ adoptLate(scene) {
799
+ const late = this.classicLate;
800
+ if (!late || this.trip) {
801
+ return;
802
+ }
803
+ this.classicLate = null;
804
+ const tickets = scene.persistent.hubTickets;
805
+ tickets.push(late.target.classic.ticket);
806
+ if (tickets.length > TICKETS_MAX) {
807
+ tickets.shift();
808
+ }
809
+ this.away(scene, late.target, scene.multiplayer);
810
+ }
811
+
812
+ // A way back from a classic deck that could not be made: the host is still
813
+ // showing the deck, so this player stays away, under the cover, with the
814
+ // ticket back in place for the next Back.
815
+ stayAway(scene, target) {
816
+ this.trip = null;
817
+ const per = scene.persistent;
818
+ // The count `away` adds is the one already there.
819
+ if (target.classic.host) {
820
+ per.hubDepth = Math.max(0, (per.hubDepth ?? 0) - 1);
821
+ }
822
+ this.away(scene, target, scene.multiplayer);
823
+ this.toast = { text: 'Could not get back. Try again.', until: performance.now() + TOAST_MS };
824
+ }
825
+
826
+ // A hub trip's destination: acquired from the host, then its content --
827
+ // the pack the handoff names, or the one `stay.content` names for a way back
828
+ // to a place this runtime already showed when it is that very release (the
829
+ // handoff's `bundleHash`), which keeps the ticket's scene. An acquisition the trip will not join is given back
830
+ // (`Hub.cancel`). The host holds one acquisition at a time and `cancel` names
831
+ // none, so acquisitions and their cancels run one after another
832
+ // (`hubChain`): a late cancel can never reach a newer trip's acquisition.
833
+ resolveHub(scene, acquire, stay) {
834
+ const state = { done: false, content: null, error: null, join: null, stayed: false, abandoned: false };
835
+ const keep = new Set(scene.persistent.hubTickets.map((t) => t.content?.sha256).filter(Boolean));
836
+ if (scene.content) {
837
+ keep.add(scene.content.sha256);
838
+ }
839
+ const baseFiles = scene.ownContent?.files ?? scene.files;
840
+ const run = async () => {
841
+ try {
842
+ if (typeof castleSdk.Hub?.go !== 'function') {
843
+ throw new Error('this host has no doors');
844
+ }
845
+ const handoff = await acquire();
846
+ if (handoff?.status !== 'ok') {
847
+ throw new Error(handoff?.status ?? 'unavailable');
848
+ }
849
+ state.join = { mode: 'hub', handoff };
850
+ if (stay?.content && stay.content.sha256 === handoff.bundleHash) {
851
+ // Held in the pack cache, unless it was evicted: then fetched again.
852
+ state.stayed = true;
853
+ state.content = await loadRef(stay.content, handoff.contentUrl, { baseFiles, keep });
854
+ } else {
855
+ if (typeof handoff.contentUrl !== 'string' || !handoff.bundleHash) {
856
+ throw new Error('the destination has no content pack');
857
+ }
858
+ state.content = await Packs.loadPack(handoff.bundleHash, handoff.contentUrl, { baseFiles, keep });
859
+ // A way back into this deck's own place, from a pack that is the
860
+ // deck's own content (the release this page runs): keep that content,
861
+ // so the place parked when the player left is drawn again
862
+ // (`keepResident`) rather than every mesh rebuilt from the pack.
863
+ if (stay && stay.content === null && Packs.matchesOwn?.(state.content, baseFiles)) {
864
+ state.stayed = true;
865
+ state.content = null;
866
+ }
867
+ }
868
+ } catch (err) {
869
+ state.error = err?.message ?? String(err);
870
+ state.code = typeof err?.code === 'string' ? err.code : null;
871
+ }
872
+ state.done = true;
873
+ if (state.join && (state.error || state.abandoned)) {
874
+ // Already in the chain: given back before the next link runs.
875
+ await cancelNow();
876
+ }
877
+ };
878
+ this.hubChain = (this.hubChain ?? Promise.resolve()).then(run, run);
879
+ return state;
880
+ }
881
+
882
+ // Gives back the host's acquisition, after whatever is ahead of it.
883
+ cancelHub() {
884
+ this.hubChain = (this.hubChain ?? Promise.resolve()).then(cancelNow, cancelNow);
885
+ return this.hubChain;
886
+ }
887
+
888
+ // Through a door of this place: remember the way back, then go.
889
+ go(scene, msg) {
890
+ const mp = scene.multiplayer;
891
+ const per = scene.persistent;
892
+ per.hubTickets.push({
893
+ scene: this.scenePath,
894
+ key: this.sceneKey,
895
+ // The content the way back is drawn from: null is this deck's own.
896
+ content: packRef(scene.content),
897
+ join: mp.target ?? { mode: 'public' },
898
+ door: msg.door,
899
+ title: Hub.hub.place?.title ?? 'Back',
900
+ place: Hub.hub.place?.id ?? 'main',
901
+ party: msg.party ?? 1,
902
+ });
903
+ if (per.hubTickets.length > TICKETS_MAX) {
904
+ per.hubTickets.shift();
905
+ }
906
+ this.startTrip(scene, {
907
+ scene: msg.scene,
908
+ // A place of this deck is drawn from this deck's content; another
909
+ // deck's from its pack, resolved now so it loads while the door opens.
910
+ content: msg.deck ? undefined : (scene.content ?? null),
911
+ deck: msg.deck ?? null,
912
+ pending: msg.deck ? this.resolveDeck(scene, msg.deck, msg.key) : null,
913
+ join: { mode: 'named', key: msg.key },
914
+ title: msg.title,
915
+ exitDoor: doorActor(scene, msg.door),
916
+ arrive: { door: msg.door, party: msg.party ?? 1, returning: false },
917
+ pushedTicket: true,
918
+ });
919
+ }
920
+
921
+ // Another deck's content for a door: resolved, fetched, verified and
922
+ // validated off the frame loop. The trip waits for it under the cover.
923
+ resolveDeck(scene, deck, key) {
924
+ const state = { done: false, content: null, error: null };
925
+ const keep = new Set(scene.persistent.hubTickets.map((t) => t.content?.sha256).filter(Boolean));
926
+ if (scene.content) {
927
+ keep.add(scene.content.sha256);
928
+ }
929
+ const baseFiles = scene.ownContent?.files ?? scene.files;
930
+ Packs.resolveDeckDoor(deck, key)
931
+ .then((door) =>
932
+ Packs.loadPack(door.sha256, door.url, { baseFiles, keep }).then((content) => ({
933
+ ...content,
934
+ sessionKeyPrefix: door.sessionKeyPrefix,
935
+ })),
936
+ )
937
+ .then(
938
+ (content) => {
939
+ state.content = content;
940
+ state.done = true;
941
+ },
942
+ (err) => {
943
+ state.error = err?.message ?? String(err);
944
+ state.done = true;
945
+ },
946
+ );
947
+ return state;
948
+ }
949
+
950
+ // The content a ticket names, for a way back that is not a hub trip: the
951
+ // place it leads to keeps its own scene and session, so this is `stayed`.
952
+ resolveRef(scene, ref) {
953
+ const state = { done: false, content: null, error: null, join: null, stayed: true };
954
+ const keep = new Set(scene.persistent.hubTickets.map((t) => t.content?.sha256).filter(Boolean));
955
+ keep.add(ref.sha256);
956
+ if (scene.content) {
957
+ keep.add(scene.content.sha256);
958
+ }
959
+ const baseFiles = scene.ownContent?.files ?? scene.files;
960
+ loadRef(ref, null, { baseFiles, keep }).then(
961
+ (content) => {
962
+ state.content = content;
963
+ state.done = true;
964
+ },
965
+ (err) => {
966
+ state.error = err?.message ?? String(err);
967
+ state.done = true;
968
+ },
969
+ );
970
+ return state;
971
+ }
972
+
973
+ // Who of the player's friends is in another layer of this place, asked every
974
+ // little while from a place that is not a game. Dormant on a host that cannot
975
+ // say: `unavailable` (no hub support) or a refusal (a host from before
976
+ // friends) stops asking for the life of the runtime; a failed ask is retried.
977
+ askFriends(scene, mp, now) {
978
+ if (this.friendsOff || this.friendsAsking || typeof castleSdk.Hub?.friends !== 'function') {
979
+ return;
980
+ }
981
+ const place = Hub.hub.place;
982
+ const idle = !this.trip && this.pendingEnd === null && (mp.joinState?.() ?? 'joined') === 'joined';
983
+ if (!place || place.result || !idle || now - this.friendsAt < FRIENDS_EVERY_MS) {
984
+ return;
985
+ }
986
+ this.friendsAt = now;
987
+ this.friendsAsking = true;
988
+ const key = this.sceneKey;
989
+ Promise.resolve(castleSdk.Hub.friends())
990
+ .then((answer) => {
991
+ if (answer?.status !== 'ok' || !Array.isArray(answer.friends)) {
992
+ this.friendsOff = true;
993
+ this.friends = null;
994
+ this.friendsAll = null;
995
+ return;
996
+ }
997
+ this.hubHost = true;
998
+ // An answer for a place the player has since left says nothing here.
999
+ const all = this.trip || key !== this.sceneKey ? null : answer.friends.filter((f) => f && f.userId);
1000
+ this.friendsAll = all;
1001
+ this.friends = all ? all.filter((f) => !f.here) : null;
1002
+ })
1003
+ .catch((err) => {
1004
+ // A host from before friends refuses the command for good; anything else
1005
+ // (a timeout, the network) is asked again next time.
1006
+ if (err?.code === 'UNKNOWN_COMMAND' || err?.code === 'CASTLE_HOST_UNAVAILABLE') {
1007
+ this.friendsOff = true;
1008
+ }
1009
+ this.friends = null;
1010
+ this.friendsAll = null;
1011
+ })
1012
+ .finally(() => {
1013
+ this.friendsAsking = false;
1014
+ });
1015
+ }
1016
+
1017
+ // A jump the player asked for (to a door, beside someone): the place takes
1018
+ // one jump a second from a player, so one sent on the heels of another
1019
+ // (the start beside a friend) waits its turn instead of being dropped. It
1020
+ // also ends any start beside a friend still pending: the player has chosen.
1021
+ sendJump(net, message) {
1022
+ this.startNear = null;
1023
+ Hub.hub.jumpedTo = null;
1024
+ const wait = Math.max(0, JUMP_GAP_MS - (performance.now() - (this.jumpSentAt ?? -Infinity)));
1025
+ this.jumpSentAt = performance.now() + wait;
1026
+ if (wait > 0) {
1027
+ setTimeout(() => net.send(message), wait);
1028
+ } else {
1029
+ net.send(message);
1030
+ }
1031
+ }
1032
+
1033
+ // An action from the People list: the pointer on someone here (Find), an
1034
+ // invitation into the party (Invite), or Join -- beside a party member or a
1035
+ // friend in this layer (the place moves this player), into the layer of
1036
+ // this place a friend is in (a jump), or to the door of the game a friend
1037
+ // is inside.
1038
+ join(scene, person, action) {
1039
+ const net = scene?.multiplayer?.net;
1040
+ if (!net || this.trip || !person) {
1041
+ return;
1042
+ }
1043
+ const say = (text) => {
1044
+ this.toast = { text, until: performance.now() + TOAST_MS };
1045
+ };
1046
+ if (action === 'find' && person.playerId) {
1047
+ this.together.find(person.playerId);
1048
+ } else if (action === 'invite' && person.playerId) {
1049
+ net.send({ k: 'hub-party', op: 'invite', player: person.playerId });
1050
+ say(`Invited ${person.username ?? 'them'} to your party`);
1051
+ } else if (action === 'goto' && person.playerId) {
1052
+ this.sendJump(net, { k: 'hub-goto', player: person.playerId });
1053
+ } else if (action === 'door' && person.door) {
1054
+ this.sendJump(net, { k: 'hub-door-jump', door: person.door });
1055
+ // A friend inside the game is said to be; someone standing at the door
1056
+ // is simply gone to.
1057
+ if (person.playerId === null) {
1058
+ const title = Hub.hub.doors.find((d) => d.id === person.door)?.title ?? 'that game';
1059
+ say(`${person.username ?? 'Your friend'} is inside ${title}`);
1060
+ }
1061
+ } else if (action === 'jump' && person.userId) {
1062
+ this.jump(scene, { userId: person.userId, username: person.username });
1063
+ }
1064
+ }
1065
+
1066
+ // Go, from the Doors list: onto that door's pad. In a party the door is
1067
+ // proposed to the party too, and each member who says yes lands on the pad.
1068
+ goDoor(scene, door) {
1069
+ const net = scene?.multiplayer?.net;
1070
+ if (!net || !door) {
1071
+ return;
1072
+ }
1073
+ if (Hub.hub.party.members?.length && door.solo) {
1074
+ // One at a time behind this door: said before anyone goes, and nobody
1075
+ // else is asked to come.
1076
+ this.sendJump(net, { k: 'hub-door-jump', door: door.id });
1077
+ this.toast = { text: `${door.title ?? 'This door'} is a solo game · your party stays here`, until: performance.now() + TOAST_MS };
1078
+ } else if (Hub.hub.party.members?.length) {
1079
+ this.startNear = null;
1080
+ net.send({ k: 'hub-party', op: 'go', door: door.id });
1081
+ this.toast = { text: `You're on the ${door.title ?? 'door'} pad · asked your party to come`, until: performance.now() + TOAST_MS };
1082
+ } else {
1083
+ this.sendJump(net, { k: 'hub-door-jump', door: door.id });
1084
+ // The jump is instant: say where the player now stands.
1085
+ this.toast = { text: `You're at ${door.title ?? 'the door'} · stand on the pad to play`, until: performance.now() + TOAST_MS };
1086
+ }
1087
+ }
1088
+
1089
+ // Start next to a friend (a town): the first time a friend or party member
1090
+ // is known to be in this layer after walking in, the place is asked to put
1091
+ // this player beside them, and the player is told whom. Not after the
1092
+ // first moments, and not once the player has walked away from where they
1093
+ // came in: nobody is pulled back across the town.
1094
+ startBeside(scene, local, town, now) {
1095
+ const start = this.startNear;
1096
+ if (!start) {
1097
+ return;
1098
+ }
1099
+ const lt = local?.components.Transform;
1100
+ // Only the place's answer to this request counts: a jump beside the
1101
+ // player it was asked about.
1102
+ if (start.asked && Hub.hub.jumpedTo === start.asked) {
1103
+ const name = scene.multiplayer?.net?.others?.().get(Hub.hub.jumpedTo);
1104
+ Hub.hub.jumpedTo = null;
1105
+ this.startNear = null;
1106
+ if (name) {
1107
+ this.toast = { text: `You're next to ${name}`, until: now + TOAST_MS };
1108
+ }
1109
+ return;
1110
+ }
1111
+ if (!town || !lt || Hub.hub.arrivedFacing === null) {
1112
+ return;
1113
+ }
1114
+ start.at ??= { x: lt.x, z: lt.z };
1115
+ // Once asked, only the answer is awaited: the place's move is itself a move.
1116
+ if (now > start.until || (!start.asked && Math.hypot(lt.x - start.at.x, lt.z - start.at.z) > START_NEAR_STAY_M)) {
1117
+ this.startNear = null;
1118
+ return;
1119
+ }
1120
+ const who = start.asked ? null : this.together.startBeside();
1121
+ if (who) {
1122
+ start.asked = who.playerId;
1123
+ this.jumpSentAt = performance.now();
1124
+ scene.multiplayer?.net?.send({ k: 'hub-goto', player: who.playerId });
1125
+ return;
1126
+ }
1127
+ // Nobody here, but a friend is inside a game behind one of this town's
1128
+ // doors (a host that says which): the player is told, and Join is in People.
1129
+ const inside = start.asked ? null : (this.friendsAll ?? []).find((f) => typeof f.door === 'string' && Hub.hub.doors.some((d) => d.id === f.door));
1130
+ if (inside) {
1131
+ const title = Hub.hub.doors.find((d) => d.id === inside.door)?.title ?? 'a game';
1132
+ this.toast = { text: `${inside.username ?? 'A friend'} is inside ${title} · People to join`, until: now + TOAST_MS };
1133
+ this.startNear = null;
1134
+ }
1135
+ }
1136
+
1137
+ // A pick from the speech card: a reaction or a phrase goes to the place; a
1138
+ // typed line goes to the host, which sends it to whoever ghost lets read it.
1139
+ saying(what) {
1140
+ if (typeof what?.text !== 'string') {
1141
+ this.scene?.multiplayer?.net?.send({ k: 'hub-say', ...what });
1142
+ return;
1143
+ }
1144
+ this.chat.send(what.text, (status) => {
1145
+ const text = status === 'none' ? 'Nobody here can read that. Follow each other to chat.' : status === 'limited' ? 'Slow down a little.' : status === 'sent' ? null : "That didn't send.";
1146
+ if (text) {
1147
+ this.toast = { text, until: performance.now() + TOAST_MS };
1148
+ }
1149
+ });
1150
+ }
1151
+
1152
+ reportChat(line) {
1153
+ this.chat.report(line?.id, (ok) => {
1154
+ this.toast = { text: ok ? 'Reported. Thanks.' : "That report didn't go through.", until: performance.now() + TOAST_MS };
1155
+ });
1156
+ }
1157
+
1158
+ // The question the chrome puts to the player, from the place's word on
1159
+ // their party: a door their party proposed, else an invitation.
1160
+ ask() {
1161
+ const { invite, proposal } = Hub.hub.party;
1162
+ if (proposal?.asked) {
1163
+ const title = Hub.hub.doors.find((d) => d.id === proposal.door)?.title ?? 'a game';
1164
+ return { key: `go:${proposal.id}`, kind: 'go', id: proposal.id, text: `${proposal.username ?? 'Your party'}: let's play ${title}`, yes: 'Go', no: 'Not now' };
1165
+ }
1166
+ // Someone here said "Let's play <door>": Go takes this player to its pad.
1167
+ const play = this.playAsk;
1168
+ if (play && performance.now() < play.until && Hub.hub.doors.some((d) => d.id === play.door) && !invite) {
1169
+ const title = Hub.hub.doors.find((d) => d.id === play.door)?.title ?? 'a game';
1170
+ return { key: `play:${play.from}:${play.door}:${play.until}`, kind: 'play', door: play.door, text: `${play.name}: let's play ${title}`, yes: 'Go', no: 'Not now' };
1171
+ }
1172
+ if (invite) {
1173
+ return { key: `invite:${invite.from}`, kind: 'invite', from: invite.from, text: `${invite.username ?? 'Someone'} invited you to their party`, yes: 'Join party', no: 'No thanks' };
1174
+ }
1175
+ return null;
1176
+ }
1177
+
1178
+ answer(scene, ask, yes) {
1179
+ const net = scene?.multiplayer?.net;
1180
+ if (!net || !ask) {
1181
+ return;
1182
+ }
1183
+ if (ask.kind === 'play') {
1184
+ this.playAsk = null;
1185
+ if (yes) {
1186
+ this.sendJump(net, { k: 'hub-door-jump', door: ask.door });
1187
+ }
1188
+ return;
1189
+ }
1190
+ // The answer names what was asked, so it cannot land on a later question.
1191
+ if (ask.kind === 'go') {
1192
+ net.send({ k: 'hub-party', op: yes ? 'go-yes' : 'go-no', id: ask.id });
1193
+ } else {
1194
+ net.send({ k: 'hub-party', op: yes ? 'accept' : 'decline', from: ask.from });
1195
+ }
1196
+ }
1197
+
1198
+ // Into the layer of this place a friend is in: the host acquires it
1199
+ // (`Hub.jump`) and the trip is a hub trip like a door's, without a door, a
1200
+ // ticket or a step on the host's trail. The content is the place's own
1201
+ // release when the handoff names it, else the pack it names.
1202
+ jump(scene, friend) {
1203
+ if (!scene || this.trip || typeof castleSdk.Hub?.jump !== 'function' || !friend?.userId) {
1204
+ return;
1205
+ }
1206
+ const mp = scene.multiplayer;
1207
+ const per = scene.persistent;
1208
+ if (!(per.hubDepth > 0) && mp.target?.mode !== 'hub') {
1209
+ per.hubRootJoin = mp.target ?? { mode: 'public' };
1210
+ }
1211
+ const name = friend.username ?? 'a friend';
1212
+ this.friends = null;
1213
+ this.startTrip(scene, {
1214
+ scene: this.scenePath,
1215
+ content: undefined,
1216
+ deck: `${name}'s layer`,
1217
+ pending: this.resolveHub(scene, () => castleSdk.Hub.jump(friend.userId), { content: packRef(scene.content) }),
1218
+ join: null,
1219
+ title: `Joining ${name}`,
1220
+ exitDoor: null,
1221
+ arrive: { door: null, party: 1, returning: false, near: String(friend.userId) },
1222
+ jump: { left: mp.target ?? { mode: 'public' } },
1223
+ stuck: `Could not join ${name}`,
1224
+ hubStep: 0,
1225
+ });
1226
+ }
1227
+
1228
+ // Back through the door this player came in by (contract §5). With no ticket
1229
+ // -- a game played on its own -- it is a fresh instance of the same place.
1230
+ back(scene, { covered = false, attempt = 0, lost = 0, away = null } = {}) {
1231
+ // Away in a classic deck (v1.7): Back is the way out, cover already down.
1232
+ if (this.trip?.phase === 'away') {
1233
+ away = this.trip.target;
1234
+ covered = true;
1235
+ this.trip = null;
1236
+ this.toast = { text: '', until: 0 };
1237
+ }
1238
+ if (this.trip) {
1239
+ return;
1240
+ }
1241
+ const per = scene.persistent;
1242
+ const ticket = per.hubTickets.pop();
1243
+ // A place reached by a hub trip goes back the way the host says (`Hub.back`):
1244
+ // to the place in this runtime the ticket remembers, or, with no ticket, to
1245
+ // wherever ghost's return ticket leads, from its pack.
1246
+ if (ticket?.hub || (!ticket && per.hubDepth > 0)) {
1247
+ const stay = ticket ? { content: ticket.content ?? null } : undefined;
1248
+ this.startTrip(scene, {
1249
+ scene: ticket?.scene ?? null,
1250
+ // Whatever the host leads to, the content comes with the acquisition.
1251
+ content: undefined,
1252
+ deck: ticket?.title ?? 'back',
1253
+ pending: this.resolveHub(scene, () => castleSdk.Hub.back(), stay),
1254
+ retryBack: () =>
1255
+ this.resolveHub(
1256
+ scene,
1257
+ () => new Promise((resolve) => setTimeout(resolve, BACK_RETRY_MS)).then(() => castleSdk.Hub.back()),
1258
+ stay,
1259
+ ),
1260
+ join: null,
1261
+ title: ticket?.title ?? '',
1262
+ exitDoor: null,
1263
+ arriveDoor: ticket?.door ?? null,
1264
+ // Pad-mates who went out together come back together (contract §5).
1265
+ arrive: { door: ticket?.door ?? null, party: ticket?.party ?? 1, returning: Boolean(ticket) },
1266
+ ticket: ticket ?? null,
1267
+ hubStep: -1,
1268
+ attempt,
1269
+ lost,
1270
+ away,
1271
+ });
1272
+ if (covered && this.trip) {
1273
+ this.trip.startedAt -= OPEN_MS;
1274
+ }
1275
+ return;
1276
+ }
1277
+ if (!ticket) {
1278
+ const place = Hub.hub.place?.id ?? 'main';
1279
+ // Another deck's place runs that deck's server: its key keeps the prefix.
1280
+ const prefix = scene.content?.sessionKeyPrefix ?? '';
1281
+ this.startTrip(scene, {
1282
+ scene: this.scenePath,
1283
+ join: { mode: 'named', key: `${prefix}hub.${place}.${Math.random().toString(36).slice(2, 10)}` },
1284
+ title: Hub.hub.place?.title ?? '',
1285
+ exitDoor: null,
1286
+ arrive: { door: null, party: 1, returning: false },
1287
+ lost,
1288
+ });
1289
+ return;
1290
+ }
1291
+ this.startTrip(scene, {
1292
+ scene: ticket.scene,
1293
+ // Another deck's place is drawn from its pack again, out of the cache.
1294
+ content: ticket.content ? undefined : null,
1295
+ pending: ticket.content ? this.resolveRef(scene, ticket.content) : null,
1296
+ deck: ticket.title,
1297
+ join: ticket.join,
1298
+ title: ticket.title,
1299
+ exitDoor: null,
1300
+ arriveDoor: ticket.door,
1301
+ arrive: { door: ticket.door, party: ticket.party ?? 1, returning: true },
1302
+ ticket,
1303
+ lost,
1304
+ });
1305
+ if (covered && this.trip) {
1306
+ // Straight to the swap: the door already closed over the player.
1307
+ this.trip.startedAt -= OPEN_MS;
1308
+ }
1309
+ }
1310
+
1311
+ startTrip(scene, target) {
1312
+ if (this.trip) {
1313
+ return;
1314
+ }
1315
+ const cam = scene.three?.camera;
1316
+ this.tripCount += 1;
1317
+ this.trip = {
1318
+ n: this.tripCount,
1319
+ target,
1320
+ phase: 'opening',
1321
+ from: this.scenePath,
1322
+ startedAt: performance.now(),
1323
+ cam0: cam ? { x: cam.position.x, y: cam.position.y, z: cam.position.z } : null,
1324
+ heapBefore: heapMB(),
1325
+ marks: {},
1326
+ };
1327
+ scene.persistent.hubArriving = target.arrive;
1328
+ }
1329
+
1330
+ stepTrip(scene, mp, local, now) {
1331
+ const trip = this.trip;
1332
+ const elapsed = now - trip.startedAt;
1333
+ const cam = scene.three?.camera;
1334
+ if (trip.phase === 'opening') {
1335
+ const t = clamp01(elapsed / OPEN_MS);
1336
+ const door = trip.target.exitDoor ? scene.getActor(trip.target.exitDoor) : null;
1337
+ if (door) {
1338
+ this.swingDoor(door, ease(t));
1339
+ }
1340
+ if (cam && trip.cam0) {
1341
+ const e = ease(t);
1342
+ const lt = local?.components.Transform;
1343
+ if (door && isCabinet(door)) {
1344
+ // Up to the cabinet's screen (v1.7): nothing swings.
1345
+ const base = door.components.Transform;
1346
+ const inFront = doorPoint(base, 0, CABINET_CAM_OUT);
1347
+ const y = base.y ?? 1.5;
1348
+ cam.position.set(lerp(trip.cam0.x, inFront.x, e), lerp(trip.cam0.y, y + 0.1, e), lerp(trip.cam0.z, inFront.z, e));
1349
+ cam.lookAt(base.x, y, base.z);
1350
+ } else if (door) {
1351
+ // Through the doorway: the camera ends inside the frame, looking on.
1352
+ // A door faces its local +z, whatever way it is turned.
1353
+ const base = this.doorBase.get(door.id) ?? door.components.Transform;
1354
+ const inFront = doorPoint(base, 0, 0.3);
1355
+ const beyond = doorPoint(base, 0, -6);
1356
+ cam.position.set(lerp(trip.cam0.x, inFront.x, e), lerp(trip.cam0.y, 1.7, e), lerp(trip.cam0.z, inFront.z, e));
1357
+ cam.lookAt(beyond.x, 1.5, beyond.z);
1358
+ } else if (lt) {
1359
+ // No door in front of a game's player: the camera closes in on them.
1360
+ cam.position.set(lerp(trip.cam0.x, lt.x, e * 0.7), lerp(trip.cam0.y, lt.y + 1.4, e * 0.7), lerp(trip.cam0.z, lt.z, e * 0.7));
1361
+ cam.lookAt(lt.x, lt.y + 0.8, lt.z);
1362
+ }
1363
+ }
1364
+ this.chrome.setCover(clamp01((t - 0.4) / 0.6), trip.target.title);
1365
+ if (t >= 1 && trip.target.classic) {
1366
+ this.stepClassic(scene, trip, mp, now);
1367
+ return;
1368
+ }
1369
+ if (t >= 1 && !this.contentReady(scene, trip, now)) {
1370
+ return;
1371
+ }
1372
+ if (t >= 1) {
1373
+ trip.marks.covered ??= now;
1374
+ Hub.clear();
1375
+ const hubJoin = trip.target.join?.mode === 'hub' && typeof mp.joinState === 'function';
1376
+ // A hub join's messages wait for its scene: the destination's WORLD
1377
+ // must place this player in the destination, not the place it left.
1378
+ mp.switchSession(scene, trip.target.join, { quiet: true, hold: hubJoin });
1379
+ this.helloNet = null;
1380
+ // A hub join is the host's trip: nothing of the destination is
1381
+ // mounted until the host has committed it, so a refused join leaves
1382
+ // this place as it was (contract §5).
1383
+ if (hubJoin) {
1384
+ trip.phase = 'committing';
1385
+ } else {
1386
+ this.mount(scene, trip, now);
1387
+ }
1388
+ }
1389
+ return;
1390
+ }
1391
+ if (trip.phase === 'away') {
1392
+ this.chrome.setCover(1, trip.target.title);
1393
+ return;
1394
+ }
1395
+ if (trip.phase === 'committing') {
1396
+ this.chrome.setCover(1, trip.target.title);
1397
+ const state = mp.joinState();
1398
+ // 'lost' was committed too: the loading phase recovers from it.
1399
+ if (state === 'joined' || state === 'lost') {
1400
+ trip.marks.committed = now;
1401
+ const per = scene.persistent;
1402
+ per.hubDepth = Math.max(0, (per.hubDepth ?? 0) + (trip.target.hubStep ?? 0));
1403
+ this.mount(scene, trip, now);
1404
+ } else if (state === 'failed') {
1405
+ this.uncommitted(scene, trip, now);
1406
+ }
1407
+ return;
1408
+ }
1409
+ if (trip.phase === 'loading') {
1410
+ this.chrome.setCover(1, trip.target.title);
1411
+ if (scene.mountError) {
1412
+ this.mountFailed(scene, trip, now);
1413
+ return;
1414
+ }
1415
+ if (
1416
+ trip.marks.sceneLoaded === undefined &&
1417
+ !scene.requestedScene &&
1418
+ scene.currentScenePath === trip.target.scene &&
1419
+ (scene.content?.id ?? null) === trip.expectContent
1420
+ ) {
1421
+ trip.marks.sceneLoaded = now;
1422
+ // The destination is in place: its messages may now land.
1423
+ mp.release?.();
1424
+ }
1425
+ if (trip.marks.placed === undefined && mp.placed()) {
1426
+ trip.marks.placed = now;
1427
+ }
1428
+ if (mp.joinState?.() === 'lost' && this.lostJoin(scene, trip, mp, now)) {
1429
+ return;
1430
+ }
1431
+ // The root join `lostJoin` made instead, refused for good (a player
1432
+ // barred from the hub): nothing will place them, so uncover now.
1433
+ if (trip.target.lost && !trip.lost && (mp.joinState?.() === 'failed' || mp.joinError)) {
1434
+ console.warn(`[hub-door] the join that replaced a lost one failed: ${mp.joinError ?? 'refused'}`);
1435
+ trip.lost = `the join that replaced a lost one failed: ${mp.joinError ?? 'refused'}`;
1436
+ }
1437
+ const arrived = Hub.hub.arrivedFacing !== null;
1438
+ const waitedOut = trip.marks.placed !== undefined && now - trip.marks.placed > ARRIVAL_WAIT_MS;
1439
+ const ready = trip.marks.sceneLoaded !== undefined && trip.marks.placed !== undefined && (arrived || waitedOut);
1440
+ if (ready || trip.lost || now - (trip.loadingFrom ?? trip.startedAt) > LOADING_LIMIT_MS) {
1441
+ mp.release?.();
1442
+ trip.phase = 'revealing';
1443
+ trip.marks.arrived = now;
1444
+ trip.timedOut = !ready && !trip.lost;
1445
+ trip.revealAt = now;
1446
+ this.faceArrival(scene);
1447
+ const door = trip.target.arriveDoor ? scene.getActor(doorActor(scene, trip.target.arriveDoor)) : null;
1448
+ if (door) {
1449
+ this.swingDoor(door, 1);
1450
+ }
1451
+ const lt = local?.components.Transform;
1452
+ const base = door ? (this.doorBase.get(door.id) ?? door.components.Transform) : null;
1453
+ trip.camStart = base ? { x: base.x, y: 1.8, z: base.z } : lt ? { x: lt.x, y: lt.y + 1.4, z: lt.z } : null;
1454
+ }
1455
+ return;
1456
+ }
1457
+ // Revealing: the cover lifts while the camera pulls back from where the
1458
+ // player came through, and the door swings shut behind them.
1459
+ const t = clamp01((now - trip.revealAt) / REVEAL_MS);
1460
+ trip.marks.firstFrame ??= now;
1461
+ this.chrome.setCover(1 - clamp01(t / 0.6), trip.target.title);
1462
+ const door = trip.target.arriveDoor ? scene.getActor(doorActor(scene, trip.target.arriveDoor)) : null;
1463
+ if (door) {
1464
+ this.swingDoor(door, 1 - ease(clamp01((t - 0.35) / 0.65)));
1465
+ }
1466
+ const lt = local?.components.Transform;
1467
+ const follow = local && cam ? followCamera(scene, local) : null;
1468
+ if (cam && follow && trip.camStart) {
1469
+ const e = ease(t);
1470
+ cam.position.set(lerp(trip.camStart.x, follow.x, e), lerp(trip.camStart.y, follow.y, e), lerp(trip.camStart.z, follow.z, e));
1471
+ cam.lookAt(lt.x, lt.y + 0.5, lt.z);
1472
+ }
1473
+ if (t >= 1) {
1474
+ trip.marks.revealed = now;
1475
+ this.finishTrip(scene, trip);
1476
+ }
1477
+ }
1478
+
1479
+ // Whether a door to another deck has its content, once the cover is down.
1480
+ // Until then the cover holds; a pack that failed, or never came, keeps the
1481
+ // door shut: the trip turns back without leaving this place (HUB.md, Doors:
1482
+ // failure cases).
1483
+ contentReady(scene, trip, now) {
1484
+ const pending = trip.target.pending;
1485
+ if (!pending) {
1486
+ return true;
1487
+ }
1488
+ trip.marks.covered ??= now;
1489
+ this.chrome.setCover(1, trip.target.title);
1490
+ // A retried way back has its own deadline, from when it was asked again.
1491
+ if (!pending.done && now - (trip.target.pendingFrom ?? trip.startedAt) < LOADING_LIMIT_MS) {
1492
+ return false;
1493
+ }
1494
+ // A player barred from the hub is told so, and not asked for again. A way
1495
+ // back refused as unavailable is asked once more under the cover: ghost
1496
+ // refuses one while the place's session is between pins, which passes in
1497
+ // moments. Only then does the door stay shut.
1498
+ if (pending.done && pending.code === HUB_BANNED) {
1499
+ trip.target.stuck = BANNED_TEXT;
1500
+ } else if (pending.done && pending.error === 'unavailable' && trip.target.retryBack && (trip.target.attempt ?? 0) < 1) {
1501
+ trip.target.attempt = (trip.target.attempt ?? 0) + 1;
1502
+ trip.target.pending = trip.target.retryBack();
1503
+ trip.target.pendingFrom = now;
1504
+ return false;
1505
+ }
1506
+ const content = pending.content;
1507
+ const prefix = content?.sessionKeyPrefix ?? '';
1508
+ // A way back to a place this runtime already holds keeps its own content.
1509
+ const mounts = !pending.stayed || content !== null;
1510
+ const error =
1511
+ pending.error ??
1512
+ // An engine older than content mounting (physics-2d `setContent`,
1513
+ // physics-3d's loop applying `requestedContent`).
1514
+ (mounts && (typeof scene.setContent !== 'function' || !scene.mountsContent)
1515
+ ? 'this engine cannot mount another deck'
1516
+ : null) ??
1517
+ (!pending.done
1518
+ ? 'it took too long'
1519
+ : pending.stayed
1520
+ ? null
1521
+ : !content.places?.main?.scene
1522
+ ? 'it has no main place'
1523
+ : !pending.join && !trip.target.join.key.startsWith(prefix)
1524
+ ? 'its session is not the deck the pack came from'
1525
+ : null);
1526
+ trip.target.pending = null;
1527
+ if (error) {
1528
+ if (!pending.done) {
1529
+ // An acquisition still in flight is given back when it lands.
1530
+ pending.abandoned = true;
1531
+ } else if (pending.join && !pending.error) {
1532
+ // Acquired and loaded, and still not taken.
1533
+ this.cancelHub();
1534
+ }
1535
+ this.shutDoor(scene, trip, error, now);
1536
+ return false;
1537
+ }
1538
+ trip.marks.resolved = now;
1539
+ if (pending.join) {
1540
+ trip.target.join = pending.join;
1541
+ }
1542
+ if (pending.stayed) {
1543
+ trip.target.content = content;
1544
+ return true;
1545
+ }
1546
+ trip.pack = { sha: content.sha256.slice(0, 12), bytes: content.bytes, ms: content.ms, cached: content.cached };
1547
+ trip.target.content = content;
1548
+ trip.target.scene = content.places.main.scene;
1549
+ if (!trip.target.jump) {
1550
+ trip.target.title = content.places.main.title ?? trip.target.title;
1551
+ }
1552
+ return true;
1553
+ }
1554
+
1555
+ // The door stays shut: forget the way back this trip pushed, and lift the
1556
+ // cover on the place the player never left.
1557
+ shutDoor(scene, trip, why, now) {
1558
+ console.warn(`[hub-door] the door to ${trip.target.deck} stays shut: ${why}`);
1559
+ if (trip.target.away) {
1560
+ // The way back from a classic deck: still away, the ticket kept.
1561
+ if (trip.target.ticket) {
1562
+ scene.persistent.hubTickets.push(trip.target.ticket);
1563
+ }
1564
+ this.stayAway(scene, trip.target.away);
1565
+ return;
1566
+ }
1567
+ // A door of this place: its server keeps the pad from firing it again for
1568
+ // this player until they step off.
1569
+ const door = trip.target.pushedTicket ? trip.target.arrive?.door : null;
1570
+ if (door) {
1571
+ scene.multiplayer?.net?.send({ k: 'hub-shut', door });
1572
+ }
1573
+ if (trip.target.pushedTicket) {
1574
+ scene.persistent.hubTickets.pop();
1575
+ } else if (trip.target.ticket) {
1576
+ // A way back that could not be acquired: it is still the way back.
1577
+ scene.persistent.hubTickets.push(trip.target.ticket);
1578
+ }
1579
+ scene.persistent.hubArriving = null;
1580
+ trip.shut = why;
1581
+ trip.phase = 'revealing';
1582
+ trip.revealAt = now;
1583
+ trip.marks.arrived = now;
1584
+ // The door it opened swings shut again as the cover lifts.
1585
+ trip.target = { ...trip.target, scene: this.scenePath, arriveDoor: trip.target.arrive?.door ?? null, arrive: null };
1586
+ const lt = scene.actorWith('Player')?.components.Transform;
1587
+ trip.camStart = lt ? { x: lt.x, y: lt.y + 1.4, z: lt.z } : null;
1588
+ this.toast = { text: trip.target.stuck ?? 'That door is stuck', until: now + TOAST_MS };
1589
+ }
1590
+
1591
+ // The content passed every check and still failed to load: the engine has
1592
+ // put the place the player left back (physics-3d `mountError`), but the
1593
+ // session moved on, so they go back through the door they came in by,
1594
+ // cover already down.
1595
+ mountFailed(scene, trip, now) {
1596
+ console.warn(`[hub-door] ${trip.target.deck ?? trip.target.scene} failed to load: ${scene.mountError?.message ?? scene.mountError}`);
1597
+ scene.mountError = null;
1598
+ this.trip = null;
1599
+ this.toast = { text: 'That door is stuck', until: now + TOAST_MS };
1600
+ this.back(scene, { covered: true });
1601
+ }
1602
+
1603
+ // The host committed this hub trip, and the session it led to closed before
1604
+ // placing the player: a full layer refuses the socket after its hello. The
1605
+ // handoff is spent and nothing will place them, so this does not wait out
1606
+ // the loading limit. At the root of the host's trail (a way back home, a
1607
+ // jump there) ghost has used the return ticket, so `Hub.back` has nowhere to
1608
+ // go: the join this runtime began with is made again, into the place already
1609
+ // loading, and ghost's layer pick puts the player in a layer with room.
1610
+ // Anywhere deeper the player leaves by the place's way back, as a mount that
1611
+ // failed does. Each recovery counts against the way's `lost`; past
1612
+ // LOST_TRIES_MAX, or for a player barred from the hub, the cover lifts now
1613
+ // on the place with no session. Returns false when it gave up.
1614
+ lostJoin(scene, trip, mp, now) {
1615
+ const tries = trip.target.lost ?? 0;
1616
+ console.warn(`[hub-door] the session ${trip.target.deck ?? trip.target.scene} led to closed before placing this player`);
1617
+ if (tries >= LOST_TRIES_MAX || mp.joinError === HUB_BANNED) {
1618
+ trip.lost = 'the session closed before placing this player';
1619
+ return false;
1620
+ }
1621
+ const per = scene.persistent;
1622
+ if (!(per.hubDepth > 0)) {
1623
+ const rejoin = per.hubRootJoin ?? { mode: 'public' };
1624
+ trip.target.lost = tries + 1;
1625
+ trip.target.join = rejoin;
1626
+ Hub.clear();
1627
+ // Held, as the hub join was, until the destination's scene is in.
1628
+ mp.switchSession(scene, rejoin, { quiet: true, hold: trip.marks.sceneLoaded === undefined });
1629
+ this.helloNet = null;
1630
+ trip.loadingFrom = now;
1631
+ if (trip.target.stuck) {
1632
+ this.toast = { text: trip.target.stuck, until: now + TOAST_MS };
1633
+ }
1634
+ return true;
1635
+ }
1636
+ this.trip = null;
1637
+ this.toast = { text: trip.target.stuck ?? 'That door is stuck', until: now + TOAST_MS };
1638
+ // Both counts ride along, so a way that alternates between a lost join
1639
+ // and an uncommitted one still runs out.
1640
+ this.back(scene, { covered: true, attempt: trip.target.attempt ?? 0, lost: tries + 1 });
1641
+ if (!this.trip) {
1642
+ this.chrome.setCover(0);
1643
+ }
1644
+ return true;
1645
+ }
1646
+
1647
+ // The destination's content and scene, swapped in under the cover.
1648
+ mount(scene, trip, now) {
1649
+ trip.phase = 'loading';
1650
+ trip.loadingFrom = now;
1651
+ if (trip.target.content !== undefined) {
1652
+ scene.requestedContent = trip.target.content;
1653
+ }
1654
+ trip.expectContent = trip.target.content === undefined ? (scene.content?.id ?? null) : (trip.target.content?.id ?? null);
1655
+ scene.requestedScene = trip.target.scene;
1656
+ // The same scene again (a fresh instance of this place) is reloaded,
1657
+ // so the new session starts from the authored layout.
1658
+ trip.reload = trip.target.scene === this.scenePath;
1659
+ }
1660
+
1661
+ // The host did not commit a hub join (refused, or closed before its hello):
1662
+ // the player is still where they were, and nothing of the destination was
1663
+ // mounted, but the connection here was closed for the switch. A door's trip
1664
+ // rejoins the session it left when that join can be made again; one that
1665
+ // was itself a hub join cannot (its handoff is spent), so the player leaves
1666
+ // through this place's own way back. A way back that failed is tried once
1667
+ // more from where the player still is, then left to the Back control.
1668
+ uncommitted(scene, trip, now) {
1669
+ console.warn(`[hub-door] the trip to ${trip.target.deck} did not commit`);
1670
+ this.trip = null;
1671
+ this.toast = { text: trip.target.stuck ?? 'That door is stuck', until: now + TOAST_MS };
1672
+ const per = scene.persistent;
1673
+ per.hubArriving = null;
1674
+ if (trip.target.jump) {
1675
+ // A jump the host did not commit: back into the session it left, as a
1676
+ // door's trip would be, else out by this place's way back.
1677
+ const left = trip.target.jump.left;
1678
+ const rejoin = left?.mode !== 'hub' ? left : !(per.hubDepth > 0) ? (per.hubRootJoin ?? null) : null;
1679
+ if (rejoin) {
1680
+ this.startTrip(scene, {
1681
+ scene: this.scenePath,
1682
+ content: undefined,
1683
+ join: rejoin,
1684
+ title: '',
1685
+ exitDoor: null,
1686
+ arrive: { door: null, party: 1, returning: false },
1687
+ });
1688
+ if (this.trip) {
1689
+ this.trip.startedAt -= OPEN_MS;
1690
+ }
1691
+ return;
1692
+ }
1693
+ this.back(scene, { covered: true });
1694
+ return;
1695
+ }
1696
+ if (trip.target.pushedTicket) {
1697
+ const ticket = per.hubTickets.pop();
1698
+ // The session left can be joined again unless its join was a spent hub
1699
+ // handoff; at the root of the host's trail, the join this runtime began
1700
+ // with is the same place's.
1701
+ const rejoin =
1702
+ ticket?.join?.mode !== 'hub' ? ticket?.join : !(per.hubDepth > 0) ? (per.hubRootJoin ?? null) : null;
1703
+ if (ticket && rejoin) {
1704
+ this.startTrip(scene, {
1705
+ scene: this.scenePath,
1706
+ content: undefined,
1707
+ join: rejoin,
1708
+ title: ticket.title,
1709
+ exitDoor: null,
1710
+ arriveDoor: ticket.door,
1711
+ arrive: { door: ticket.door, party: ticket.party ?? 1, returning: true },
1712
+ });
1713
+ if (this.trip) {
1714
+ this.trip.startedAt -= OPEN_MS;
1715
+ }
1716
+ return;
1717
+ }
1718
+ this.back(scene, { covered: true });
1719
+ return;
1720
+ }
1721
+ if (trip.target.ticket) {
1722
+ per.hubTickets.push(trip.target.ticket);
1723
+ }
1724
+ if ((trip.target.attempt ?? 0) < 1) {
1725
+ this.back(scene, { covered: true, attempt: (trip.target.attempt ?? 0) + 1, lost: trip.target.lost ?? 0, away: trip.target.away ?? null });
1726
+ }
1727
+ if (!this.trip && trip.target.away) {
1728
+ // The way back from a classic deck did not commit: still away.
1729
+ this.stayAway(scene, trip.target.away);
1730
+ return;
1731
+ }
1732
+ if (!this.trip) {
1733
+ this.chrome.setCover(0);
1734
+ }
1735
+ }
1736
+
1737
+ // A game's end, each frame (settleEnd says what it means).
1738
+ stepEnd(scene, mp, now) {
1739
+ // A join that has resolved names the session the player is in, however
1740
+ // late it came: settle first. While a join is still pending the target
1741
+ // names nobody yet, so the end neither settles nor fires; a failed join
1742
+ // leaves the player where the end was armed, so it fires (retries).
1743
+ const joinState = mp.joinState?.() ?? 'joined';
1744
+ if (this.pendingEnd !== null && !this.trip && joinState === 'joined') {
1745
+ this.settleEnd(scene);
1746
+ }
1747
+ if (this.pendingEnd !== null && now >= this.pendingEnd && !this.trip && joinState !== 'joining') {
1748
+ // Armed until the player is out of the ended session (settleEnd): a
1749
+ // way back that fails is tried again a pause later.
1750
+ this.pendingEnd = now + END_PAUSE_MS;
1751
+ this.back(scene);
1752
+ }
1753
+ }
1754
+
1755
+ // A game's end means the player's visit to that session is over. It stays
1756
+ // armed until the player, out of any trip, has joined another session (a
1757
+ // Back taken in the end pause included, however late the join resolves),
1758
+ // never fires during a trip or a pending join, and retries Back a pause
1759
+ // apart while the player is still in the ended session (a door that stays
1760
+ // shut, a join that fails, a rejoin of the same visit).
1761
+ settleEnd(scene) {
1762
+ if (this.pendingEnd !== null && sessionKey(scene) !== this.endSession) {
1763
+ this.pendingEnd = null;
1764
+ }
1765
+ }
1766
+
1767
+ // The camera starts behind the player, the way the place faced them
1768
+ // (contract §5: arrival facing is data). The Player behavior's facing is
1769
+ // PI - camAngle.
1770
+ faceArrival(scene) {
1771
+ if (Hub.hub.arrivedFacing !== null) {
1772
+ scene.persistent.camAngle = Math.PI - Hub.hub.arrivedFacing;
1773
+ Hub.hub.faced = true;
1774
+ }
1775
+ }
1776
+
1777
+ finishTrip(scene, trip) {
1778
+ this.trip = null;
1779
+ this.chrome.setCover(0);
1780
+ // A new place or layer: ask again who is elsewhere.
1781
+ this.friends = null;
1782
+ this.friendsAll = null;
1783
+ this.friendsAt = -Infinity;
1784
+ const m = trip.marks;
1785
+ const start = trip.startedAt;
1786
+ const record = {
1787
+ n: trip.n,
1788
+ from: trip.from,
1789
+ to: trip.target.scene,
1790
+ door: trip.target.arrive?.door ?? null,
1791
+ // stepping through (the door starts opening) to the cover being down
1792
+ coverMs: Math.round(m.covered - start),
1793
+ // a door to another deck: cover down to its pack verified and ready
1794
+ resolveMs: m.resolved !== undefined ? Math.round(m.resolved - m.covered) : null,
1795
+ // the swap itself: cover down to the new scene loaded
1796
+ swapMs: Math.round((m.sceneLoaded ?? m.arrived) - m.covered),
1797
+ // cover down to the new session placing this player
1798
+ joinMs: Math.round((m.placed ?? m.arrived) - m.covered),
1799
+ // cover down to the place saying where it put them
1800
+ arriveMs: Math.round(m.arrived - m.covered),
1801
+ doorToFirstFrameMs: Math.round(m.firstFrame - start),
1802
+ doorToRevealMs: Math.round(m.revealed - start),
1803
+ timedOut: Boolean(trip.timedOut),
1804
+ // A hub join lost before placing the player: how many times this way
1805
+ // recovered from one, and why it gave up when it did.
1806
+ lostJoins: trip.target.lost ?? 0,
1807
+ lost: trip.lost ?? null,
1808
+ deck: trip.target.deck ?? null,
1809
+ pack: trip.pack ?? null,
1810
+ shut: trip.shut ?? null,
1811
+ heapBeforeMB: trip.heapBefore,
1812
+ heapAfterMB: heapMB(),
1813
+ ...gpuCounts(scene),
1814
+ };
1815
+ (globalThis.__hubTrips ??= []).push(record);
1816
+ console.log(`[hub-trip] ${JSON.stringify(record)}`);
1817
+ const r = scene.persistent.hubResult;
1818
+ if (trip.target.arrive?.returning && r) {
1819
+ this.toast = { text: `Back from ${resultLine(r)}`, until: performance.now() + TOAST_MS };
1820
+ }
1821
+ }
1822
+
1823
+ // Swing a door leaf open by `amount` (0 shut, 1 open) about its left edge,
1824
+ // in the door's own frame, so a door turned to face any way opens the same.
1825
+ swingDoor(door, amount) {
1826
+ if (isCabinet(door)) {
1827
+ return;
1828
+ }
1829
+ const t = door.components.Transform;
1830
+ if (!this.doorBase.has(door.id)) {
1831
+ this.doorBase.set(door.id, { x: t.x, z: t.z, rotationY: t.rotationY ?? 0 });
1832
+ }
1833
+ const base = this.doorBase.get(door.id);
1834
+ const half = (door.components.Shape?.width ?? 2.4) / 2;
1835
+ const hinge = doorPoint(base, -half, 0);
1836
+ const turned = ((base.rotationY + amount * DOOR_SWING_DEG) * Math.PI) / 180;
1837
+ t.x = hinge.x + Math.cos(turned) * half;
1838
+ t.z = hinge.z - Math.sin(turned) * half;
1839
+ t.rotationY = base.rotationY + amount * DOOR_SWING_DEG;
1840
+ }
1841
+
1842
+ drawChrome(scene, local, now) {
1843
+ const chrome = this.chrome;
1844
+ const place = Hub.hub.place;
1845
+ const idle = !this.trip;
1846
+ const tickets = scene.persistent.hubTickets;
1847
+ const ticket = tickets[tickets.length - 1];
1848
+ // A place that reports results is a game: it always has Back. A place that
1849
+ // does not (a town) has Back only when it was reached through a door.
1850
+ const inGame = Boolean(place?.result);
1851
+ // Away in a classic deck, the cover is down and Back is the only control.
1852
+ const away = this.trip?.phase === 'away';
1853
+ chrome.showBack(
1854
+ // While the host's trail holds a hub trip (`hubDepth`) the host draws
1855
+ // its own Back control over the place; the kit's would be a second one.
1856
+ (away || (idle && this.pendingEnd === null)) && !(scene.persistent.hubDepth > 0) && (inGame || Boolean(ticket)),
1857
+ ticket?.title ?? 'Again',
1858
+ );
1859
+ chrome.showPicker(idle && place !== null && !inGame && !this.talk.talking(), Avatar.current(scene));
1860
+ const free = idle && place !== null && this.pendingEnd === null && !this.talk.talking();
1861
+ const town = free && !inGame;
1862
+ chrome.setDoors?.(town ? Hub.hub.doors : null, Hub.hub.party.members?.length ? 'Go together' : 'Go');
1863
+ chrome.setPeople?.(free ? this.people(scene, inGame) : null, town ? this.together.partyLine() : null);
1864
+ chrome.setAsk?.(town ? this.ask() : null);
1865
+ this.startBeside(scene, local, town, now);
1866
+ // A friend or party member who just came in: say so, and point to them.
1867
+ for (const who of town ? this.together.arrivals() : []) {
1868
+ this.toast = { text: `${who.username ?? 'A friend'} is here · People to join`, until: now + TOAST_MS };
1869
+ this.together.ping(who.playerId, now, true);
1870
+ }
1871
+ // Quick reactions and phrases, in every place; what was said, as bubbles
1872
+ // (below, with the labels) and a short feed.
1873
+ const net = scene.multiplayer?.net;
1874
+ const selfId = net?.selfId?.() ?? null;
1875
+ this.say.frame(
1876
+ now,
1877
+ selfId,
1878
+ (playerId) => net?.others?.().get(playerId) ?? null,
1879
+ (playerId) => this.together.ping(playerId, now),
1880
+ // "Let's play <door>" from someone here: offer to go to that door.
1881
+ // Once from a player for a door: saying it again neither keeps the
1882
+ // card up nor brings it back after Not now, until the pause has passed.
1883
+ (playerId, name, door) => {
1884
+ const key = `${playerId}:${door}`;
1885
+ if ((this.playAsked.get(key) ?? -Infinity) > now - PLAY_ASK_AGAIN_MS) {
1886
+ return;
1887
+ }
1888
+ this.playAsked.set(key, now);
1889
+ this.playAsk = { from: playerId, name, door, until: now + PLAY_ASK_MS };
1890
+ },
1891
+ );
1892
+ // Free-text chat, where the host has it: ghost says whom this player may
1893
+ // chat with (they follow each other and both are over 13); the kit only
1894
+ // shows what it is handed.
1895
+ this.chat.frame(idle && place !== null && (scene.multiplayer?.joinState?.() ?? 'joined') === 'joined', now);
1896
+ const byUser = new Map();
1897
+ for (const [playerId, username] of net?.others?.() ?? []) {
1898
+ const userId = net.userId?.(playerId);
1899
+ if (userId) {
1900
+ byUser.set(String(userId), { playerId, username });
1901
+ }
1902
+ }
1903
+ const myUserId = selfId ? net?.userId?.(selfId) : null;
1904
+ for (const message of this.chat.incoming.splice(0)) {
1905
+ // Ghost hands a player their own lines back too; the send already drew them.
1906
+ if (!message.mine && myUserId && String(message.fromUserId) === String(myUserId)) {
1907
+ continue;
1908
+ }
1909
+ const from = message.mine ? { playerId: selfId, username: 'You' } : byUser.get(String(message.fromUserId));
1910
+ this.say.chat(now, from?.playerId ?? null, from?.username ?? message.fromUsername ?? 'Someone', message, CHAT_BUBBLE_MS);
1911
+ }
1912
+ const reach = (this.chat.peers ?? []).map((userId) => byUser.get(userId)?.username).filter(Boolean);
1913
+ // The field is always there where the host has chat, so it can be found;
1914
+ // when it cannot be used the card says why, in terms of this player alone
1915
+ // (never another player's age).
1916
+ const chatNote = !this.chat.canChat
1917
+ ? "Chat isn't available on this account"
1918
+ : reach.length
1919
+ ? `Chat reaches ${reach.slice(0, 3).join(', ')}${reach.length > 3 ? ` +${reach.length - 3}` : ''}`
1920
+ : 'Follow each other to chat. Nobody here follows you back yet.';
1921
+ const chatPart = this.chat.available() && this.chat.peers !== null
1922
+ ? { input: this.chat.canChat && reach.length > 0, note: chatNote }
1923
+ : null;
1924
+ chrome.setSay?.(free ? { reactions: REACTIONS, phrases: this.say.phrases(), chat: chatPart } : null);
1925
+ chrome.setFeed?.(idle && place !== null ? this.say.feed() : []);
1926
+ // Standing still beside someone: a small button invites them.
1927
+ const beside = town && !Hub.hub.party.invite && local ? this.together.beside(scene, local) : null;
1928
+ chrome.nearPrompt?.(
1929
+ beside ? `+ Party · ${beside.username ?? 'this player'}` : null,
1930
+ () => this.join(scene, beside, 'invite'),
1931
+ );
1932
+ // Barred from the hub: the town's own join was refused, and is not asked again.
1933
+ if (scene.multiplayer?.joinError === HUB_BANNED) {
1934
+ this.toast = { text: BANNED_TEXT, until: now + TOAST_MS };
1935
+ }
1936
+
1937
+ const spec = Hub.hub.hudMe ?? Hub.hub.hud;
1938
+ let timer = null;
1939
+ if (spec?.timer?.since !== undefined) {
1940
+ timer = Math.max(0, (Hub.simNow() - spec.timer.since) / 1000);
1941
+ } else if (spec?.timer?.until !== undefined) {
1942
+ timer = Math.max(0, (spec.timer.until - Hub.simNow()) / 1000);
1943
+ }
1944
+ chrome.setHud(idle || this.trip?.phase === 'revealing' ? spec : null, timer);
1945
+
1946
+ const cam = scene.three?.camera;
1947
+ const view = { w: window.innerWidth, h: window.innerHeight };
1948
+ const labels = [];
1949
+ // This player's goals: scene actors a `goal` label points at.
1950
+ const goals = [];
1951
+ if (cam && idle) {
1952
+ const talkingWith = this.talk.talkingWith();
1953
+ const placed = [];
1954
+ for (const [id, label] of Object.entries({ ...Hub.hub.labels, ...Hub.hub.labelsMe })) {
1955
+ // The NPC being talked with says it in the open panel, not over its head too.
1956
+ if (id === talkingWith && label.style === 'speech') {
1957
+ continue;
1958
+ }
1959
+ const at = scene.getActor(id)?.components.Transform;
1960
+ if (at && label.style === 'goal') {
1961
+ // Where the place is sending this player (v1.13): a pointer, not a label.
1962
+ goals.push({ id, at, text: label.text });
1963
+ } else if (at) {
1964
+ // A sign is drawn at any distance in a town: a street's name, or a
1965
+ // word the player must see from where they stand.
1966
+ const always = label.style === 'sign';
1967
+ placed.push({ id, at, label, always });
1968
+ }
1969
+ }
1970
+ // In a town only what the player stands by is labelled (`attention.js`).
1971
+ const lt = local?.components.Transform;
1972
+ const shown = place && !inGame && lt
1973
+ ? attend(
1974
+ this.attention,
1975
+ placed
1976
+ .filter(({ always }) => !always)
1977
+ .map(({ id, at, label }) => ({ id, d: Math.hypot(at.x - lt.x, at.z - lt.z), speech: label.style === 'speech' })),
1978
+ now,
1979
+ )
1980
+ : null;
1981
+ for (const { id, at, label, always } of placed) {
1982
+ const opacity = shown && !always ? shown.get(id) : 1;
1983
+ const screen = opacity ? project(cam, at.x, at.y + 1.6, at.z, view) : null;
1984
+ if (screen) {
1985
+ labels.push({ id, x: screen.x, y: screen.y, text: label.text, speech: label.style === 'speech', npc: label.npc === true, opacity });
1986
+ }
1987
+ }
1988
+ }
1989
+ const pointers = cam && idle && place && !inGame && this.pendingEnd === null ? this.together.pointers(scene, local, cam, view) : [];
1990
+ const me = local?.components.Transform;
1991
+ if (cam && me && this.pendingEnd === null) {
1992
+ // The nearest goals, each with how far it is.
1993
+ const near = goals.map((g) => ({ ...g, d: Math.hypot(g.at.x - me.x, g.at.z - me.z) })).sort((a, b) => a.d - b.d);
1994
+ for (const g of near.slice(0, GOALS_MAX)) {
1995
+ pointers.push(pointerAt(cam, view, { x: g.at.x, y: g.at.y + 1.6, z: g.at.z }, `goal:${g.id}`, g.d > GOAL_NEAR_M ? `${g.text} · ${Math.round(g.d)} m` : g.text));
1996
+ }
1997
+ }
1998
+ chrome.setPointers?.(pointers);
1999
+ if (cam && idle) {
2000
+ labels.push(...this.markItems(scene, local, cam, view));
2001
+ labels.push(...this.idle.labels(scene, local, cam, view, project));
2002
+ labels.push(...this.say.labels(scene, local, cam, view, project, scene.multiplayer?.net?.selfId?.() ?? null));
2003
+ }
2004
+ chrome.setLabels(labels);
2005
+
2006
+ const lt = local?.components.Transform;
2007
+ // The card of the cabinet this player stands nearest (v1.7).
2008
+ chrome.setCabinet?.(cam && idle && lt ? Cabinets.nearest(scene, lt, cam, view, project) : null, Cabinets.imageOf);
2009
+ const r = scene.persistent.hubResult;
2010
+ const showRibbon = !inGame && idle && r && Date.now() - r.at < RIBBON_MS && lt && cam;
2011
+ chrome.setRibbon(showRibbon ? project(cam, lt.x, lt.y + 1.7, lt.z, view) : null, r ? `🏅 ${resultLine(r)}` : '');
2012
+ chrome.setToast(now < this.toast.until ? this.toast.text : '');
2013
+ }
2014
+
2015
+ // The People list's rows. In a town: everyone here and the player's
2016
+ // friends, each friend with where they are and Join. In a game: the players
2017
+ // who may be reported, and no list where the host takes no reports.
2018
+ people(scene, inGame) {
2019
+ const canReport = this.canReport(scene);
2020
+ if (inGame) {
2021
+ return canReport ? this.together.rows(scene.multiplayer, null, true).filter((row) => row.actions.length) : null;
2022
+ }
2023
+ return this.together.rows(scene.multiplayer, this.friendsAll, canReport);
2024
+ }
2025
+
2026
+ // Whether the host takes reports: a production hub place (the host answered
2027
+ // Hub.friends, or the player came in by a hub trip). The roster is the
2028
+ // host's, already without anyone a block hides from this player.
2029
+ canReport(scene) {
2030
+ const per = scene.persistent ?? {};
2031
+ return !this.reportOff && typeof castleSdk.Hub?.report === 'function' && Boolean(this.hubHost || per.hubDepth > 0);
2032
+ }
2033
+
2034
+ // Reports a player to Castle (`Hub.report`), one at a time.
2035
+ report(person) {
2036
+ if (this.reporting || !person?.userId || typeof castleSdk.Hub?.report !== 'function') {
2037
+ return;
2038
+ }
2039
+ this.reporting = true;
2040
+ const say = (text) => {
2041
+ this.toast = { text, until: performance.now() + TOAST_MS };
2042
+ };
2043
+ Promise.resolve(castleSdk.Hub.report(person.userId))
2044
+ .then((answer) => {
2045
+ if (answer?.status === 'ok') {
2046
+ say('Reported. Thanks.');
2047
+ return;
2048
+ }
2049
+ this.reportOff = true;
2050
+ say("Reporting isn't available here.");
2051
+ })
2052
+ .catch((err) => {
2053
+ if (err?.code === 'UNKNOWN_COMMAND' || err?.code === 'CASTLE_HOST_UNAVAILABLE') {
2054
+ this.reportOff = true;
2055
+ }
2056
+ say("That report didn't go through. Try again later.");
2057
+ })
2058
+ .finally(() => {
2059
+ this.reporting = false;
2060
+ });
2061
+ }
2062
+
2063
+ // The tags the place put over players (`hub.mark`): over this player's own
2064
+ // body and over each other player's avatar, above the name tag.
2065
+ markItems(scene, local, cam, view) {
2066
+ const mp = scene.multiplayer;
2067
+ const self = mp?.net?.selfId?.() ?? null;
2068
+ const out = [];
2069
+ for (const [playerId, mark] of Object.entries(Hub.hub.marks)) {
2070
+ const actorId = playerId === self ? local?.id : mp?.avatars?.actors?.get(playerId);
2071
+ const at = actorId ? scene.getActor(actorId)?.components.Transform : null;
2072
+ const screen = at ? project(cam, at.x, at.y + 1.95, at.z, view) : null;
2073
+ if (screen) {
2074
+ out.push({ id: `mark:${playerId}`, x: screen.x, y: screen.y, text: mark.text || '●', color: mark.color });
2075
+ }
2076
+ }
2077
+ return out;
2078
+ }
2079
+
2080
+ measure(scene, mp, now) {
2081
+ if (!this.stats) {
2082
+ return;
2083
+ }
2084
+ this.frames += 1;
2085
+ this.lastFrame = frameCounts(scene) ?? this.lastFrame;
2086
+ if (now - this.fpsAt >= 1000) {
2087
+ this.fps = (this.frames * 1000) / (now - this.fpsAt || 1);
2088
+ this.frames = 0;
2089
+ this.fpsAt = now;
2090
+ }
2091
+ const avatars = (mp.avatars?.actors?.size ?? 0) + 1;
2092
+ const heap = heapMB();
2093
+ this.chrome.setStats(`${Math.round(this.fps)} fps · ${avatars} avatars${heap !== null ? ` · ${heap} MB` : ''}`);
2094
+ if (now - this.statsAt >= STATS_EVERY_MS) {
2095
+ this.statsAt = now;
2096
+ const record = { scene: this.scenePath, fps: Math.round(this.fps * 10) / 10, avatars, heapMB: heap, trips: this.tripCount, ...gpuCounts(scene), ...this.lastFrame };
2097
+ (globalThis.__hubFps ??= []).push(record);
2098
+ console.log(`[hub-fps] ${JSON.stringify(record)}`);
2099
+ }
2100
+ }
2101
+
2102
+ dispose() {
2103
+ this.chrome?.dispose();
2104
+ this.chrome = null;
2105
+ this.talk = null;
2106
+ this.grab?.dispose();
2107
+ this.grab = null;
2108
+ this.idle?.dispose();
2109
+ this.idle = null;
2110
+ this.sound?.dispose();
2111
+ this.sound = null;
2112
+ }
2113
+ }
2114
+
2115
+ function glows(emissive) {
2116
+ return typeof emissive === 'string' && /^#[0-9a-f]{6}$/i.test(emissive) && emissive.toLowerCase() !== '#000000';
2117
+ }
2118
+
2119
+ // A painted colour's glow: the colour at 40%.
2120
+ function dim(color) {
2121
+ const n = parseInt(color.slice(1), 16);
2122
+ const c = (shift) => Math.round(((n >> shift) & 255) * 0.4);
2123
+ return `#${((c(16) << 16) | (c(8) << 8) | c(0)).toString(16).padStart(6, '0')}`;
2124
+ }
2125
+
2126
+ // The words a result is shown in. The game wrote none of them (contract §7).
2127
+ // A result with no outcome (a time trial's time) is its title and score.
2128
+ export function resultLine(r) {
2129
+ const score = typeof r.score === 'number' ? formatScore(r.score, r.unit) : null;
2130
+ if ((r.outcome === undefined || r.outcome === null) && score) {
2131
+ return `${r.title}: ${score}`;
2132
+ }
2133
+ const outcome = r.outcome === 'win' ? 'win' : r.outcome === 'draw' ? 'draw' : 'played';
2134
+ return `${r.title}: ${outcome}${score ? ` · ${score}` : ''}`;
2135
+ }
2136
+
2137
+ function formatScore(score, unit) {
2138
+ if (unit === 'ms') {
2139
+ return `${(score / 1000).toFixed(1)} s`;
2140
+ }
2141
+ if (unit === 's') {
2142
+ return `${Math.round(score)} s`;
2143
+ }
2144
+ return `${Math.round(score)} pts`;
2145
+ }
2146
+
2147
+ // The scene's identity across contents (physics-2d `sceneKey`): a town and a
2148
+ // mounted game can both call theirs `scenes/main.scene`.
2149
+ function sceneKeyOf(scene) {
2150
+ return scene.sceneKey ?? scene.currentScenePath;
2151
+ }
2152
+
2153
+ // A cabinet (v1.7, `HubDoor.kind`): a door that does not swing.
2154
+ function isCabinet(door) {
2155
+ return door?.components?.HubDoor?.kind === 'cabinet';
2156
+ }
2157
+
2158
+ // The scene actor of a door id: the actor whose `HubDoor` names it.
2159
+ function doorActor(scene, door) {
2160
+ if (!door) {
2161
+ return null;
2162
+ }
2163
+ for (const actor of scene.getActors()) {
2164
+ if (actor.components?.HubDoor?.id === door) {
2165
+ return actor.id;
2166
+ }
2167
+ }
2168
+ return null;
2169
+ }
2170
+
2171
+ function lockInput(scene) {
2172
+ scene.keys?.clear?.();
2173
+ if (scene.moveInput) {
2174
+ scene.moveInput.active = false;
2175
+ scene.moveInput.x = 0;
2176
+ scene.moveInput.y = 0;
2177
+ }
2178
+ }
2179
+
2180
+ // Where the engine's Player behavior puts its follow camera, so a reveal ends
2181
+ // exactly where that camera takes over.
2182
+ function followCamera(scene, local) {
2183
+ const t = local.components.Transform;
2184
+ const props = local.components.Player ?? {};
2185
+ const angle = scene.persistent?.camAngle ?? Math.PI / 4;
2186
+ const distance = props.camDistance ?? 9;
2187
+ const height = props.camHeight ?? 7;
2188
+ return { x: t.x - distance * Math.sin(angle), y: t.y + height, z: t.z + distance * Math.cos(angle) };
2189
+ }
2190
+
2191
+ function project(cam, x, y, z, view) {
2192
+ const v = cam.position.clone().set(x, y, z).project(cam);
2193
+ if (v.z > 1 || v.z < -1) {
2194
+ return null;
2195
+ }
2196
+ return { x: ((v.x + 1) / 2) * view.w, y: ((1 - v.y) / 2) * view.h };
2197
+ }
2198
+
2199
+ function statsWanted() {
2200
+ try {
2201
+ return new URLSearchParams(globalThis.location?.search ?? '').has('hubstats');
2202
+ } catch {
2203
+ return false;
2204
+ }
2205
+ }
2206
+
2207
+ function heapMB() {
2208
+ const used = globalThis.performance?.memory?.usedJSHeapSize;
2209
+ return typeof used === 'number' ? Math.round((used / 1048576) * 10) / 10 : null;
2210
+ }
2211
+
2212
+ function gpuCounts(scene) {
2213
+ const info = scene.three?.renderer?.info;
2214
+ return info
2215
+ ? { geometries: info.memory.geometries, textures: info.memory.textures, programs: info.programs?.length ?? null }
2216
+ : {};
2217
+ }
2218
+
2219
+ // What the last frame drew. The composer renders several passes a frame, so
2220
+ // the counters are accumulated with three's auto reset off and cleared here.
2221
+ function frameCounts(scene) {
2222
+ const info = scene.three?.renderer?.info;
2223
+ if (!info) {
2224
+ return null;
2225
+ }
2226
+ info.autoReset = false;
2227
+ const counts = { calls: info.render.calls, triangles: info.render.triangles };
2228
+ info.reset();
2229
+ return counts;
2230
+ }