castle-web-cli 0.4.229 → 0.4.231

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