castle-web-cli 0.4.232 → 0.4.233

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 (355) hide show
  1. package/dist/agent-failures.d.ts +8 -0
  2. package/dist/agent-failures.js +19 -2
  3. package/dist/agent-prompts.d.ts +1 -1
  4. package/dist/agent-prompts.js +10 -3
  5. package/dist/agent.d.ts +64 -3
  6. package/dist/agent.js +170 -81
  7. package/dist/castle-host/host.d.ts +1 -0
  8. package/dist/castle-host/host.js +51 -3
  9. package/dist/castleJson.d.ts +4 -2
  10. package/dist/castleJson.js +2 -0
  11. package/dist/check.d.ts +3 -1
  12. package/dist/check.js +11 -1
  13. package/dist/devSessionStorage.js +47 -1
  14. package/dist/importPinMismatch.d.ts +22 -0
  15. package/dist/importPinMismatch.js +77 -0
  16. package/dist/importRegression.js +3 -15
  17. package/dist/imports.d.ts +10 -3
  18. package/dist/imports.js +88 -20
  19. package/dist/index.js +5 -4
  20. package/dist/init.js +1 -1
  21. package/dist/platformDoc.js +22 -0
  22. package/dist/routerFences.d.ts +5 -0
  23. package/dist/routerFences.js +12 -2
  24. package/dist/save-deck.d.ts +5 -0
  25. package/dist/save-deck.js +37 -4
  26. package/dist/serve.js +3 -0
  27. package/dist/shell/assets/{index-D2tWM896.js → index-BjOxR-lW.js} +4 -4
  28. package/dist/shell/assets/index-MVLfNYd9.css +1 -0
  29. package/dist/shell/index.html +2 -2
  30. package/dist/taskSteer.d.ts +13 -0
  31. package/dist/taskSteer.js +22 -2
  32. package/kits/base/castle.json +1 -1
  33. package/kits/base/package-lock.json +1 -1
  34. package/kits/base/sdk/README.md +79 -2
  35. package/kits/base/sdk/avatar.d.ts +6 -2
  36. package/kits/base/sdk/avatar.js +12 -4
  37. package/kits/base/sdk/castle.d.ts +1 -1
  38. package/kits/base/sdk/commands.d.ts +14 -0
  39. package/kits/base/sdk/hub.d.ts +6 -2
  40. package/kits/base/sdk/hub.js +13 -0
  41. package/kits/base/sdk/multiplayer.js +17 -1
  42. package/kits/base/sdk/save.js +2 -1
  43. package/kits/base/sdk/server/hub.d.ts +87 -0
  44. package/kits/base/sdk/server/hub.js +70 -0
  45. package/kits/base/sdk/server/platformHandle.d.ts +31 -1
  46. package/kits/base/sdk/server/storage.d.ts +13 -0
  47. package/kits/base/sdk/server/storage.js +46 -0
  48. package/kits/base/sdk/server/wrapper.d.ts +36 -5
  49. package/kits/base/sdk/server/wrapper.js +83 -8
  50. package/kits/hub-game/CLAUDE.md +329 -11
  51. package/kits/hub-game/blueprints/avatar-10.scene +28 -0
  52. package/kits/hub-game/blueprints/avatar-11.scene +28 -0
  53. package/kits/hub-game/blueprints/avatar-12.scene +28 -0
  54. package/kits/hub-game/blueprints/avatar-13.scene +28 -0
  55. package/kits/hub-game/blueprints/avatar-14.scene +28 -0
  56. package/kits/hub-game/blueprints/avatar-15.scene +28 -0
  57. package/kits/hub-game/blueprints/avatar-4.scene +28 -0
  58. package/kits/hub-game/blueprints/avatar-5.scene +28 -0
  59. package/kits/hub-game/blueprints/avatar-6.scene +28 -0
  60. package/kits/hub-game/blueprints/avatar-7.scene +28 -0
  61. package/kits/hub-game/blueprints/avatar-8.scene +28 -0
  62. package/kits/hub-game/blueprints/avatar-9.scene +28 -0
  63. package/kits/hub-game/code/client/actorBudget.js +47 -0
  64. package/kits/hub-game/code/client/attention.js +11 -2
  65. package/kits/hub-game/code/client/avatar.js +309 -35
  66. package/kits/hub-game/code/client/avatarCap.js +228 -0
  67. package/kits/hub-game/code/client/avatarColors.js +70 -0
  68. package/kits/hub-game/code/client/avatarFaces.js +21 -0
  69. package/kits/hub-game/code/client/avatarShare.js +251 -0
  70. package/kits/hub-game/code/client/ballot.js +467 -0
  71. package/kits/hub-game/code/client/build.js +22 -0
  72. package/kits/hub-game/code/client/chrome.js +1144 -50
  73. package/kits/hub-game/code/client/companion.js +716 -0
  74. package/kits/hub-game/code/client/companionDress.js +99 -0
  75. package/kits/hub-game/code/client/decor.js +509 -0
  76. package/kits/hub-game/code/client/earned.js +131 -0
  77. package/kits/hub-game/code/client/emoteBubble.js +75 -0
  78. package/kits/hub-game/code/client/grab.js +339 -20
  79. package/kits/hub-game/code/client/hookLayer.js +299 -13
  80. package/kits/hub-game/code/client/idle.js +163 -22
  81. package/kits/hub-game/code/client/interestCap.js +81 -0
  82. package/kits/hub-game/code/client/keys.js +36 -0
  83. package/kits/hub-game/code/client/labelsNear.js +205 -0
  84. package/kits/hub-game/code/client/menuIcons.js +34 -0
  85. package/kits/hub-game/code/client/pack.js +6 -2
  86. package/kits/hub-game/code/client/packFormat.js +3 -3
  87. package/kits/hub-game/code/client/rehello.js +167 -0
  88. package/kits/hub-game/code/client/shot.js +92 -0
  89. package/kits/hub-game/code/client/sound.js +63 -8
  90. package/kits/hub-game/code/client/soundscape.js +1151 -0
  91. package/kits/hub-game/code/client/soundscapeActions.js +99 -0
  92. package/kits/hub-game/code/client/soundscapeAmbience.js +453 -0
  93. package/kits/hub-game/code/client/soundscapeBaked.js +143 -0
  94. package/kits/hub-game/code/client/soundscapeBusker.js +217 -0
  95. package/kits/hub-game/code/client/soundscapeCourt.js +200 -0
  96. package/kits/hub-game/code/client/soundscapeCrowd.js +331 -0
  97. package/kits/hub-game/code/client/soundscapeCues.js +362 -0
  98. package/kits/hub-game/code/client/soundscapeMap.js +181 -0
  99. package/kits/hub-game/code/client/soundscapeMarket.js +176 -0
  100. package/kits/hub-game/code/client/soundscapeMusic.js +126 -0
  101. package/kits/hub-game/code/client/soundscapeMusicEngine.js +460 -0
  102. package/kits/hub-game/code/client/soundscapeSimlish.js +737 -0
  103. package/kits/hub-game/code/client/soundscapeSongs.js +127 -0
  104. package/kits/hub-game/code/client/soundscapeSongsRound3.js +63 -0
  105. package/kits/hub-game/code/client/soundscapeSynthesis.js +168 -0
  106. package/kits/hub-game/code/client/soundscapeUi.js +211 -0
  107. package/kits/hub-game/code/client/soundscapeVoice.js +1209 -0
  108. package/kits/hub-game/code/client/soundscapeWaves.js +206 -0
  109. package/kits/hub-game/code/client/spin.js +101 -0
  110. package/kits/hub-game/code/client/state.js +109 -1
  111. package/kits/hub-game/code/client/stuck.js +259 -0
  112. package/kits/hub-game/code/client/talk.js +538 -47
  113. package/kits/hub-game/code/client/tiers.js +516 -27
  114. package/kits/hub-game/code/client/toastBand.js +37 -0
  115. package/kits/hub-game/code/client/together.js +32 -0
  116. package/kits/hub-game/code/client/visibility.js +43 -0
  117. package/kits/hub-game/code/client/wear.js +461 -170
  118. package/kits/hub-game/code/client/yours.js +199 -0
  119. package/kits/hub-game/code/companionSpec.js +45 -0
  120. package/kits/hub-game/code/privateText.js +7 -0
  121. package/kits/hub-game/code/server/actions.js +133 -0
  122. package/kits/hub-game/code/server/actors.js +9 -1
  123. package/kits/hub-game/code/server/ask.js +155 -0
  124. package/kits/hub-game/code/server/ballot.js +539 -0
  125. package/kits/hub-game/code/server/cells.js +100 -0
  126. package/kits/hub-game/code/server/companion.js +82 -0
  127. package/kits/hub-game/code/server/cues.js +70 -0
  128. package/kits/hub-game/code/server/decor.js +269 -0
  129. package/kits/hub-game/code/server/earned.js +461 -0
  130. package/kits/hub-game/code/server/friendBests.js +166 -0
  131. package/kits/hub-game/code/server/friendsAmong.js +232 -0
  132. package/kits/hub-game/code/server/history.js +5 -0
  133. package/kits/hub-game/code/server/hub.js +1254 -50
  134. package/kits/hub-game/code/server/idle.js +30 -11
  135. package/kits/hub-game/code/server/index.js +2 -2
  136. package/kits/hub-game/code/server/labels.js +28 -2
  137. package/kits/hub-game/code/server/manifest.js +378 -7
  138. package/kits/hub-game/code/server/menu.js +133 -0
  139. package/kits/hub-game/code/server/npcs.js +830 -80
  140. package/kits/hub-game/code/server/party.js +2 -2
  141. package/kits/hub-game/code/server/players.js +22 -0
  142. package/kits/hub-game/code/server/shot.js +110 -0
  143. package/kits/hub-game/code/server/standing.js +124 -0
  144. package/kits/hub-game/code/server/vis.js +113 -0
  145. package/kits/hub-game/code/server/wear.js +12 -0
  146. package/kits/hub-game/code/server/yours.js +59 -0
  147. package/kits/hub-game/code/shared/cues.js +9 -0
  148. package/kits/hub-game/code/shared/decor.js +41 -0
  149. package/kits/hub-game/code/shared/shot.js +19 -0
  150. package/kits/hub-game/code/shared/spin.js +57 -0
  151. package/kits/hub-game/code/systems/hub.js +845 -95
  152. package/kits/hub-game/docs/content-pack.md +1 -1
  153. package/kits/hub-game/docs/contract.md +2244 -61
  154. package/kits/hub-game/docs/home-pieces.md +64 -0
  155. package/kits/hub-game/models/avatar-10.pxmodel +28 -0
  156. package/kits/hub-game/models/avatar-11.pxmodel +28 -0
  157. package/kits/hub-game/models/avatar-12.pxmodel +27 -0
  158. package/kits/hub-game/models/avatar-13.pxmodel +24 -0
  159. package/kits/hub-game/models/avatar-14.pxmodel +29 -0
  160. package/kits/hub-game/models/avatar-15.pxmodel +24 -0
  161. package/kits/hub-game/models/avatar-4.pxmodel +29 -0
  162. package/kits/hub-game/models/avatar-5.pxmodel +27 -0
  163. package/kits/hub-game/models/avatar-6.pxmodel +26 -0
  164. package/kits/hub-game/models/avatar-7.pxmodel +25 -0
  165. package/kits/hub-game/models/avatar-8.pxmodel +24 -0
  166. package/kits/hub-game/models/avatar-9.pxmodel +30 -0
  167. package/kits/hub-game/models/earned/badge-round.pxmodel +100 -0
  168. package/kits/hub-game/models/earned/badge-shield.pxmodel +117 -0
  169. package/kits/hub-game/models/earned/badge-star.pxmodel +87 -0
  170. package/kits/hub-game/models/earned/belt-plain.pxmodel +72 -0
  171. package/kits/hub-game/models/earned/held-ball.pxmodel +43 -0
  172. package/kits/hub-game/models/earned/held-lantern.pxmodel +85 -0
  173. package/kits/hub-game/models/earned/held-net.pxmodel +57 -0
  174. package/kits/hub-game/models/earned/held-trophy.pxmodel +109 -0
  175. package/kits/hub-game/models/earned/pin-round.pxmodel +62 -0
  176. package/kits/hub-game/models/earned/sash-plain.pxmodel +66 -0
  177. package/kits/hub-game/models/earned/square/belt-plain.pxmodel +104 -0
  178. package/kits/hub-game/models/earned/square/sash-plain.pxmodel +98 -0
  179. package/kits/hub-game/models/hats/bat-clip.pxmodel +206 -0
  180. package/kits/hub-game/models/hats/beekeeper.pxmodel +149 -0
  181. package/kits/hub-game/models/hats/cap.pxmodel +162 -0
  182. package/kits/hub-game/models/hats/captain.pxmodel +178 -0
  183. package/kits/hub-game/models/hats/crooked-top.pxmodel +172 -0
  184. package/kits/hub-game/models/hats/flower-crown.pxmodel +451 -0
  185. package/kits/hub-game/models/hats/foam-crown.pxmodel +179 -0
  186. package/kits/hub-game/models/hats/lantern.pxmodel +230 -0
  187. package/kits/hub-game/models/hats/laurel.pxmodel +533 -0
  188. package/kits/hub-game/models/hats/lighthouse.pxmodel +96 -0
  189. package/kits/hub-game/models/hats/sailor.pxmodel +141 -0
  190. package/kits/hub-game/models/hats/souwester.pxmodel +131 -0
  191. package/kits/hub-game/models/hats/straw.pxmodel +139 -0
  192. package/kits/hub-game/models/hats/sunflower.pxmodel +406 -0
  193. package/kits/hub-game/models/hats/sweatband.pxmodel +112 -0
  194. package/kits/hub-game/models/hats/witch.pxmodel +147 -0
  195. package/kits/hub-game/package-lock.json +2 -0
  196. package/kits/hub-game/package.json +2 -1
  197. package/kits/hub-game/scripts/check.mjs +78 -11
  198. package/kits/hub-game/scripts/companion-follower-wire.json +1 -0
  199. package/kits/hub-game/scripts/fixtures/decor-keyless-draw.json +121 -0
  200. package/kits/hub-game/scripts/fixtures/decor-keyless.json +293 -0
  201. package/kits/hub-game/scripts/fixtures/engine-models-stub.mjs +23 -0
  202. package/kits/hub-game/scripts/fixtures/fake-dom.mjs +107 -0
  203. package/kits/hub-game/scripts/fixtures/interest-legacy.json +385 -0
  204. package/kits/hub-game/scripts/fixtures/npc-notes-v1.77.jsonl +4 -0
  205. package/kits/hub-game/scripts/fixtures/vis-shared-wire.json +1 -0
  206. package/kits/hub-game/scripts/gen-avatars.mjs +933 -16
  207. package/kits/hub-game/scripts/gen-earned.mjs +285 -0
  208. package/kits/hub-game/scripts/gen-hats.mjs +827 -0
  209. package/kits/hub-game/scripts/grab.before-orbit.mjs +400 -0
  210. package/kits/hub-game/scripts/soundscape-wave-analysis.mjs +125 -0
  211. package/kits/hub-game/scripts/test-actions-client.mjs +488 -0
  212. package/kits/hub-game/scripts/test-actions.mjs +298 -0
  213. package/kits/hub-game/scripts/test-actor-budget.mjs +44 -0
  214. package/kits/hub-game/scripts/test-actors.mjs +19 -17
  215. package/kits/hub-game/scripts/test-ask-client.mjs +358 -0
  216. package/kits/hub-game/scripts/test-ask.mjs +269 -0
  217. package/kits/hub-game/scripts/test-attention.mjs +10 -1
  218. package/kits/hub-game/scripts/test-avatar-cap.mjs +379 -0
  219. package/kits/hub-game/scripts/test-avatar-colors.mjs +72 -0
  220. package/kits/hub-game/scripts/test-avatar-models.mjs +181 -0
  221. package/kits/hub-game/scripts/test-avatar-share.mjs +318 -0
  222. package/kits/hub-game/scripts/test-avatar-wire.mjs +753 -0
  223. package/kits/hub-game/scripts/test-avatar.mjs +540 -7
  224. package/kits/hub-game/scripts/test-ballot.mjs +1001 -0
  225. package/kits/hub-game/scripts/test-build.mjs +31 -0
  226. package/kits/hub-game/scripts/test-cells.mjs +71 -0
  227. package/kits/hub-game/scripts/test-chat.mjs +662 -0
  228. package/kits/hub-game/scripts/test-classic.mjs +2 -0
  229. package/kits/hub-game/scripts/test-companion-chat.mjs +198 -0
  230. package/kits/hub-game/scripts/test-companion-client.mjs +1167 -0
  231. package/kits/hub-game/scripts/test-companion.mjs +259 -0
  232. package/kits/hub-game/scripts/test-decor-client.mjs +303 -0
  233. package/kits/hub-game/scripts/test-decor.mjs +457 -0
  234. package/kits/hub-game/scripts/test-earned-client.mjs +459 -0
  235. package/kits/hub-game/scripts/test-earned.mjs +1194 -0
  236. package/kits/hub-game/scripts/test-emote-bubble.mjs +110 -0
  237. package/kits/hub-game/scripts/test-friend-bests.mjs +435 -0
  238. package/kits/hub-game/scripts/test-grab-orbit.mjs +918 -0
  239. package/kits/hub-game/scripts/test-grab.mjs +7 -0
  240. package/kits/hub-game/scripts/test-hats.mjs +422 -168
  241. package/kits/hub-game/scripts/test-hub-leaving.mjs +203 -0
  242. package/kits/hub-game/scripts/test-hub-ops.mjs +439 -2
  243. package/kits/hub-game/scripts/test-hub-trip.mjs +716 -2
  244. package/kits/hub-game/scripts/test-hud-clear.mjs +328 -4
  245. package/kits/hub-game/scripts/test-idle.mjs +361 -1
  246. package/kits/hub-game/scripts/test-interest-cap.mjs +36 -0
  247. package/kits/hub-game/scripts/test-interest-cells.mjs +493 -0
  248. package/kits/hub-game/scripts/test-interest-client.mjs +118 -0
  249. package/kits/hub-game/scripts/test-keys.mjs +46 -1
  250. package/kits/hub-game/scripts/test-labels.mjs +596 -0
  251. package/kits/hub-game/scripts/test-manifest.mjs +207 -0
  252. package/kits/hub-game/scripts/test-menu-client.mjs +480 -0
  253. package/kits/hub-game/scripts/test-menu.mjs +296 -0
  254. package/kits/hub-game/scripts/test-npcs.mjs +1718 -12
  255. package/kits/hub-game/scripts/test-object-entry.mjs +76 -0
  256. package/kits/hub-game/scripts/test-pack.mjs +7 -0
  257. package/kits/hub-game/scripts/test-picker.mjs +314 -0
  258. package/kits/hub-game/scripts/test-rehello.mjs +1039 -0
  259. package/kits/hub-game/scripts/test-relations-among.mjs +222 -0
  260. package/kits/hub-game/scripts/test-relations-refresh.mjs +188 -0
  261. package/kits/hub-game/scripts/test-shot.mjs +756 -0
  262. package/kits/hub-game/scripts/test-soundscape.mjs +5432 -0
  263. package/kits/hub-game/scripts/test-spin.mjs +314 -0
  264. package/kits/hub-game/scripts/test-standing.mjs +416 -0
  265. package/kits/hub-game/scripts/test-stuck.mjs +1903 -0
  266. package/kits/hub-game/scripts/test-tier-cells.mjs +706 -0
  267. package/kits/hub-game/scripts/test-tiers-render.mjs +339 -0
  268. package/kits/hub-game/scripts/test-tiers.mjs +477 -2
  269. package/kits/hub-game/scripts/test-toast-band.mjs +61 -0
  270. package/kits/hub-game/scripts/test-try-on.mjs +22 -22
  271. package/kits/hub-game/scripts/test-vis.mjs +343 -0
  272. package/kits/hub-game/scripts/test-visibility.mjs +134 -0
  273. package/kits/hub-game/scripts/test-yours-chrome.mjs +166 -0
  274. package/kits/hub-game/scripts/test-yours.mjs +372 -0
  275. package/kits/multiplayer-3d/CLAUDE.md +50 -0
  276. package/kits/multiplayer-3d/castle.json +5 -5
  277. package/kits/multiplayer-3d/code/client/avatars.js +7 -0
  278. package/kits/multiplayer-3d/code/client/gait.js +65 -0
  279. package/kits/multiplayer-3d/code/client/nameTags.js +59 -4
  280. package/kits/multiplayer-3d/code/options.js +5 -0
  281. package/kits/multiplayer-3d/code/server/ownership.js +10 -2
  282. package/kits/multiplayer-3d/code/server/sceneBodies.js +12 -0
  283. package/kits/multiplayer-3d/code/server/world.js +7 -0
  284. package/kits/multiplayer-3d/code/systems/multiplayer.js +74 -4
  285. package/kits/multiplayer-3d/package.json +2 -1
  286. package/kits/multiplayer-3d/scripts/fixtures/README.md +11 -0
  287. package/kits/multiplayer-3d/scripts/fixtures/ownership-legacy.json +2 -0
  288. package/kits/multiplayer-3d/scripts/ownership-harness.mjs +102 -0
  289. package/kits/multiplayer-3d/scripts/ownership-loader.mjs +46 -0
  290. package/kits/multiplayer-3d/scripts/ownership-worker.mjs +15 -0
  291. package/kits/multiplayer-3d/scripts/record-ownership-session.mjs +98 -0
  292. package/kits/multiplayer-3d/scripts/test-eligible-claims.mjs +167 -0
  293. package/kits/multiplayer-3d/scripts/test-own-name-tag.mjs +247 -0
  294. package/kits/physics-2d/CLAUDE.md +9 -0
  295. package/kits/physics-2d/castle.json +2 -2
  296. package/kits/physics-2d/engine/scene.js +253 -1
  297. package/kits/physics-2d/engine/skyKey.js +129 -0
  298. package/kits/physics-2d/engine/stillClock.js +106 -0
  299. package/kits/physics-2d/engine/updateBudget.js +21 -0
  300. package/kits/physics-2d/scripts/test-skip-unchanged.mjs +326 -1
  301. package/kits/physics-3d/CLAUDE.md +1169 -30
  302. package/kits/physics-3d/behaviors/Player.jsx +629 -72
  303. package/kits/physics-3d/castle.json +3 -3
  304. package/kits/physics-3d/docs/pxmodel-format.md +8 -0
  305. package/kits/physics-3d/engine3d/Scene3DPlayer.jsx +69 -13
  306. package/kits/physics-3d/engine3d/actornode.js +86 -0
  307. package/kits/physics-3d/engine3d/animationBudget.js +23 -0
  308. package/kits/physics-3d/engine3d/editorWorld.js +6 -0
  309. package/kits/physics-3d/engine3d/emptynodes.js +232 -0
  310. package/kits/physics-3d/engine3d/framecap.js +96 -0
  311. package/kits/physics-3d/engine3d/gait.js +118 -0
  312. package/kits/physics-3d/engine3d/kithooks.js +47 -0
  313. package/kits/physics-3d/engine3d/look.js +507 -48
  314. package/kits/physics-3d/engine3d/lookbake.js +208 -0
  315. package/kits/physics-3d/engine3d/materialpresets.js +2 -0
  316. package/kits/physics-3d/engine3d/motion.js +39 -10
  317. package/kits/physics-3d/engine3d/nearshadows.js +37 -19
  318. package/kits/physics-3d/engine3d/optimize.js +9 -5
  319. package/kits/physics-3d/engine3d/orbitinput.js +487 -9
  320. package/kits/physics-3d/engine3d/orbitlens.js +48 -0
  321. package/kits/physics-3d/engine3d/ownmodel.js +213 -0
  322. package/kits/physics-3d/engine3d/pxmodel.js +42 -11
  323. package/kits/physics-3d/engine3d/shadowfade.js +882 -0
  324. package/kits/physics-3d/engine3d/sky.js +547 -0
  325. package/kits/physics-3d/engine3d/skylife.js +306 -0
  326. package/kits/physics-3d/engine3d/unchanged.js +11 -0
  327. package/kits/physics-3d/engine3d/viewrange.js +52 -0
  328. package/kits/physics-3d/engine3d/world3d.js +796 -69
  329. package/kits/physics-3d/main.jsx +5 -0
  330. package/kits/physics-3d/package.json +1 -1
  331. package/kits/physics-3d/scripts/look-baseline.mjs +155 -0
  332. package/kits/physics-3d/scripts/test-camera-orbit.mjs +2563 -80
  333. package/kits/physics-3d/scripts/test-drop-empty-parts.mjs +1 -1
  334. package/kits/physics-3d/scripts/test-frame-cap-bob.mjs +435 -0
  335. package/kits/physics-3d/scripts/test-frame-cap.mjs +452 -0
  336. package/kits/physics-3d/scripts/test-gait.mjs +387 -0
  337. package/kits/physics-3d/scripts/test-look-bake.mjs +1056 -0
  338. package/kits/physics-3d/scripts/test-model-parse-cache.mjs +92 -0
  339. package/kits/physics-3d/scripts/test-near-shadows.mjs +3 -0
  340. package/kits/physics-3d/scripts/test-orbit-shadow-fade.mjs +1920 -0
  341. package/kits/physics-3d/scripts/test-orbit-shift-lock.mjs +545 -0
  342. package/kits/physics-3d/scripts/test-orbit-shot.mjs +583 -0
  343. package/kits/physics-3d/scripts/test-orbit-view.mjs +230 -0
  344. package/kits/physics-3d/scripts/test-skip-empty-nodes.mjs +845 -0
  345. package/kits/physics-3d/scripts/test-sky.mjs +2470 -0
  346. package/kits/physics-3d/scripts/test-static-actors.mjs +8 -1
  347. package/kits/physics-3d/scripts/test-static-scenery.mjs +2171 -0
  348. package/kits/physics-3d/scripts/test-steady-hover.mjs +2 -0
  349. package/kits/physics-3d/scripts/test-view-range.mjs +260 -0
  350. package/kits/physics-3d/systems/physics3d.js +383 -6
  351. package/kits/real-time/castle.json +2 -2
  352. package/kits/real-time/code/server/gameHooks.js +7 -0
  353. package/kits/real-time/code/server/session.js +97 -19
  354. package/package.json +2 -2
  355. package/dist/shell/assets/index-Cf61cNfT.css +0 -1
@@ -10,24 +10,43 @@
10
10
  // `worldCharacters`: the session callbacks a place's NPCs answer in a world
11
11
  // that carries shared characters (`npcs.js`).
12
12
 
13
- import { readScene } from '@imports/castle.multiplayer-3d/code/server/sceneBodies.js';
13
+ import * as Scene from '@imports/castle.multiplayer-3d/code/server/sceneBodies.js';
14
+ import * as Cells from './cells.js';
14
15
  import * as Actors from './actors.js';
15
16
  import * as History from './history.js';
17
+ import * as Friends from './friendsAmong.js';
18
+ import { friendBests } from './friendBests.js';
16
19
  import * as Blocks from './blocks.js';
17
20
  import * as Cabinets from './cabinets.js';
18
21
  import * as Grab from './grab.js';
19
22
  import * as Idle from './idle.js';
23
+ import * as Decor from './decor.js';
24
+ import * as Actions from './actions.js';
25
+ import * as Companion from './companion.js';
26
+ import * as Ask from './ask.js';
27
+ import * as Menu from './menu.js';
28
+ import * as Cues from './cues.js';
29
+ import * as Shot from './shot.js';
30
+ import * as Vis from './vis.js';
31
+ import * as Yours from './yours.js';
20
32
  import * as Manifest from './manifest.js';
21
33
  import { setLabel, wireLabel } from './labels.js';
22
34
  import { makeNpcs } from './npcs.js';
23
35
  import * as Party from './party.js';
36
+ import { standingY } from './standing.js';
24
37
  import * as Place from './place.js';
25
38
  import * as Say from './say.js';
39
+ import * as Ballot from './ballot.js';
26
40
  import * as Wear from './wear.js';
41
+ import * as Earned from './earned.js';
27
42
  import { doorPoint } from '../client/doorFrame.js';
28
43
 
29
44
  // How many avatars the kit offers (`blueprints/avatar-<n>.scene`); contract §11.
30
- export const AVATARS = 4;
45
+ // Sixteen since v1.51: a place on an older kit takes 0-3 and draws anyone
46
+ // wearing another as 0.
47
+ export const AVATARS = 16;
48
+ // The avatars every client can draw, a town's saved before v1.51 included.
49
+ const OLD_AVATARS = 4;
31
50
 
32
51
  // Players sent together by one `hub.go` arrive together: the first arrival of a
33
52
  // group waits this long for the rest before the group is placed.
@@ -50,7 +69,11 @@ const BOARD_EVERY_MS = 60000;
50
69
  // The newest result of the game a player came back from counts as this trip's
51
70
  // for this long: the longest visit (maxDurationSec 1800) and some slack.
52
71
  const RESULT_FRESH_MS = 35 * 60 * 1000;
53
- const MAX_BOARD_DOORS = 16;
72
+ // Ghost refuses more than 16 doors per read (ghost-server
73
+ // src/utils/cauldronHubResults.ts: HUB_READ_MAX_DOORS). A door board has at
74
+ // most 10 top rows and 3 last-event winners (a few KB), so 16 stay well
75
+ // below the host channel's roughly 384 KB frame.
76
+ const BOARD_DOORS_PER_READ = 16;
54
77
  // Cabinet boards in one read: each may be 44 KB, and a read answers in one
55
78
  // frame of the host's channel (about 384 KB).
56
79
  const CABINET_BOARDS_PER_READ = 6;
@@ -60,6 +83,9 @@ const CABINET_BOARDS_PER_READ = 6;
60
83
  const JUMP_OUT = 7;
61
84
  const JUMP_SPREAD = 2;
62
85
  const JUMP_EVERY_MS = 1000;
86
+ // "Stuck?" (v1.33, a deck with `hub.stuck`): how often one player may be put
87
+ // back at the arrival for the asking.
88
+ const UNSTICK_EVERY_MS = 5000;
63
89
  // A player a client already sees counts as this much nearer when the nearest
64
90
  // are picked, so two players at about the same distance do not swap in and
65
91
  // out of its set every tick.
@@ -87,6 +113,10 @@ const USER_ID = /^\d{1,20}$/;
87
113
  // names no `fallY`: above the world's floor (-30), below any pit worth having.
88
114
  const NO_GROUND_FALL_Y = -20;
89
115
 
116
+ function hasHook(deckHooks, placeHooks, name) {
117
+ return typeof deckHooks?.[name] === 'function' || Object.values(placeHooks ?? {}).some((hooks) => typeof hooks?.[name] === 'function');
118
+ }
119
+
90
120
  // `engine` is multiplayer-3d's world (`createBody`, `removeActor`), which
91
121
  // builds and drops the bodies of actors a game spawns (`hub.spawn`).
92
122
  export function layer(castleJson, deckHooks, placeHooks, sceneExists, sceneGround = () => null, devDecks = null, engine = null) {
@@ -101,12 +131,20 @@ export function layer(castleJson, deckHooks, placeHooks, sceneExists, sceneGroun
101
131
  return { persist: false, sceneFor: () => undefined, worldCharacters: {} };
102
132
  }
103
133
  const h = newState(manifest);
134
+ // v1.53: the deck's own earned items and id, for an unlock kept in this
135
+ // session only (a guest, the dev serve).
136
+ h.unlocks = manifest.unlocks ?? null;
137
+ h.deckId = typeof castleJson?.deckId === 'string' && castleJson.deckId ? castleJson.deckId : 'local';
104
138
  h.devDecks = devDecks && typeof devDecks === 'object' ? devDecks : null;
105
139
  h.engine = engine;
106
140
  const tickRate = Number.isFinite(castleJson?.server?.tickRate) && castleJson.server.tickRate > 0 ? castleJson.server.tickRate : 20;
107
141
  const poseEvery = Math.max(1, Math.round(tickRate / POSE_HZ));
108
142
 
109
143
  return {
144
+ // Decor places own their actors on the server. Keyless decks add no hook.
145
+ ...(Object.values(manifest.places).some((place) => place.decor)
146
+ ? { allowClientGone: () => !h.place?.decor }
147
+ : {}),
110
148
  persist: false,
111
149
  poseEvery,
112
150
  poseIntervalMs: Math.round((poseEvery * 1000) / tickRate),
@@ -117,15 +155,72 @@ export function layer(castleJson, deckHooks, placeHooks, sceneExists, sceneGroun
117
155
  h.placeId = id;
118
156
  h.place = manifest.places[id];
119
157
  h.hooks = placeHooks[id] ?? deckHooks;
158
+ if (typeof h.hooks.resume === 'function') {
159
+ h.resumeDeparting ??= new Set();
160
+ }
161
+ if (h.place.resumeKeep === true) {
162
+ h.resumeKept ??= new Map();
163
+ h.resumeDeparting ??= new Set();
164
+ }
165
+ if (h.place.decor) {
166
+ h.ctx.decor = Decor.api(h);
167
+ } else {
168
+ delete h.ctx.decor;
169
+ }
170
+ if (h.place.actions === true) {
171
+ h.ctx.actions = (playerId, items) => Actions.set(h, playerId, items);
172
+ } else {
173
+ delete h.ctx.actions;
174
+ }
175
+ if (h.place.companion === true) {
176
+ h.ctx.companion = (playerId, spec) => Companion.set(h, playerId, spec);
177
+ h.ctx.companionDress = true;
178
+ h.ctx.companionPose = true;
179
+ } else {
180
+ delete h.ctx.companion;
181
+ delete h.ctx.companionDress;
182
+ delete h.ctx.companionPose;
183
+ }
184
+ if (h.place.ask === true) {
185
+ h.ctx.ask = (playerId, spec) => Ask.set(h, playerId, spec);
186
+ } else {
187
+ delete h.ctx.ask;
188
+ }
189
+ if (h.place.menu === true) {
190
+ h.ctx.menu = (playerId, spec) => Menu.set(h, playerId, spec);
191
+ } else {
192
+ delete h.ctx.menu;
193
+ }
120
194
  h.noGround = sceneGround(h.place.scene)?.none === true;
121
195
  h.fallY = h.place.fallY ?? (h.noGround ? NO_GROUND_FALL_Y : null);
122
196
  console.log(`[hub] place ${id} (${source}): ${h.place.scene}`);
123
197
  return h.place.scene;
124
198
  },
125
199
 
200
+ // ready runs before real-time's admit -> addPlayer, including the first
201
+ // tick of a fresh session. Until then no actor-based height is provable.
202
+ standingY(sim, at) {
203
+ return h.sim === sim && h.place ? standingY(h, at) : at.y;
204
+ },
205
+
126
206
  ready(sim) {
127
207
  h.sim = sim;
128
- h.actors = readScene(sim.scenePath);
208
+ h.actors = Scene.readScene(sim.scenePath);
209
+ if (h.place.interest === 'cells') {
210
+ let result;
211
+ try {
212
+ result = Cells.readCells({ cells: Scene.sceneCells?.(sim.scenePath) });
213
+ } catch {
214
+ result = { table: null, reason: 'could not be read' };
215
+ }
216
+ h.cells = result.table;
217
+ if (!h.cells) {
218
+ console.warn(`[hub] interest: cells table ${result.reason}`);
219
+ h.place = { ...h.place, nearestPlayers: h.place.nearestPlayersFallback };
220
+ delete h.place.interest;
221
+ delete h.place.nearestPlayersFallback;
222
+ }
223
+ }
129
224
  h.npcs.ready();
130
225
  h.hooks.ready?.(h.ctx);
131
226
  },
@@ -134,6 +229,34 @@ export function layer(castleJson, deckHooks, placeHooks, sceneExists, sceneGroun
134
229
  // read when the player gets a body.
135
230
  message(session, player, data) {
136
231
  h.session ??= session;
232
+ if (data?.k === 'hub-cap' && h.cells) {
233
+ if (Number.isInteger(data.n)) {
234
+ const now = Date.now();
235
+ const recent = (h.capAt.get(player.playerId) ?? []).filter((at) => now - at < 1000);
236
+ if (recent.length < 4) {
237
+ h.capAt.set(player.playerId, [...recent, now]);
238
+ h.caps.set(player.playerId, Math.max(1, Math.min(h.place.nearestPlayers, data.n)));
239
+ }
240
+ }
241
+ return;
242
+ }
243
+ // v1.91: opt-in, authenticated sender only. Client time is metadata,
244
+ // never a server clock or a way to name another player.
245
+ if (h.place?.visibility === true && data?.k === 'hub-visibility') {
246
+ const entry = h.players.get(player?.playerId);
247
+ if (!entry ||
248
+ !session.players.some((p) => p.playerId === player.playerId) ||
249
+ typeof data.visible !== 'boolean' || !Number.isFinite(data.at) || data.at < 0) {
250
+ return;
251
+ }
252
+ if (entry.visibility && (data.at < entry.visibility.at || data.visible === entry.visibility.visible)) {
253
+ return;
254
+ }
255
+ entry.visibility = { visible: data.visible, at: data.at };
256
+ entry.visibilityPending = true;
257
+ notifyVisibility(h, player.playerId);
258
+ return;
259
+ }
137
260
  if (data?.k === 'hub-hello') {
138
261
  hello(h, player, data);
139
262
  return;
@@ -150,6 +273,12 @@ export function layer(castleJson, deckHooks, placeHooks, sceneExists, sceneGroun
150
273
  whereAsk(h, player, data);
151
274
  return;
152
275
  }
276
+ // v1.33: only a deck with `hub.stuck` knows the message; in any other
277
+ // it goes on to the place's own hooks, as it always did.
278
+ if (h.manifest.stuck && data?.k === 'hub-unstick') {
279
+ (data.ask === true ? unstickAsk : unstick)(h, player);
280
+ return;
281
+ }
153
282
  if (data?.k === 'hub-goto') {
154
283
  goTo(h, player, data);
155
284
  return;
@@ -162,6 +291,12 @@ export function layer(castleJson, deckHooks, placeHooks, sceneExists, sceneGroun
162
291
  Party.message(partyDeps(h), player, data);
163
292
  return;
164
293
  }
294
+ // v1.68: only a place that declares `ballot` knows the message; in any
295
+ // other it goes on to the place's own hooks, as it always did.
296
+ if (h.place?.ballot && data?.k === 'hub-ballot') {
297
+ Ballot.message(h, player, data, h.place.ballot.lines);
298
+ return;
299
+ }
165
300
  if (data?.k === 'hub-dev-classic') {
166
301
  // The dev serve's stand-in for ghost's classic boards (`cabinets.js`).
167
302
  if (h.sim && isDevSession(h)) {
@@ -169,6 +304,22 @@ export function layer(castleJson, deckHooks, placeHooks, sceneExists, sceneGroun
169
304
  }
170
305
  return;
171
306
  }
307
+ if (h.place.decor && data?.k === 'decor') {
308
+ Decor.message(h, player?.playerId, data);
309
+ return;
310
+ }
311
+ if (h.place.actions === true && data?.k === 'hub-action') {
312
+ Actions.message(h, player?.playerId, data);
313
+ return;
314
+ }
315
+ if (h.place.ask === true && data?.k === 'hub-answer') {
316
+ Ask.message(h, player?.playerId, data);
317
+ return;
318
+ }
319
+ if (h.place.menu === true && data?.k === 'hub-menu-pick') {
320
+ Menu.message(h, player?.playerId, data);
321
+ return;
322
+ }
172
323
  if (data?.k === 'hub-grab') {
173
324
  Grab.message(h, player?.playerId, data);
174
325
  return;
@@ -198,12 +349,18 @@ export function layer(castleJson, deckHooks, placeHooks, sceneExists, sceneGroun
198
349
  const dt = h.lastPlaceAt === null ? 0 : Math.min(0.25, (sim.timeMs - h.lastPlaceAt) / 1000);
199
350
  h.lastPlaceAt = sim.timeMs;
200
351
  reconcile(h);
352
+ Friends.tick(h, userIdOf);
201
353
  // v1.28: a try-on on a player who went before saying hello goes too.
202
354
  if (Wear.tryOnUsed(h)) {
203
355
  Wear.pruneTries(h);
204
356
  }
357
+ // v1.53, v1.70: likewise wearable or home ownership before a hello.
358
+ if (Earned.needsPrune(h)) {
359
+ Earned.prune(h);
360
+ }
205
361
  readResults(h);
206
362
  arrivals(h);
363
+ if (h.place.visibility === true) {notifyVisibility(h);}
207
364
  enforceHolds(h);
208
365
  enforceSettle(h);
209
366
  Idle.tick(h);
@@ -220,19 +377,35 @@ export function layer(castleJson, deckHooks, placeHooks, sceneExists, sceneGroun
220
377
  const dt = h.lastStepAt === null ? 0 : (sim.timeMs - h.lastStepAt) / 1000;
221
378
  h.lastStepAt = sim.timeMs;
222
379
  h.hooks.step?.(h.ctx, dt);
380
+ rememberResumePoses(h);
381
+ // v1.61: no renewal callback exists unless a player holds a shot.
382
+ h.renewShots?.();
223
383
  Actors.flushTints(h);
224
384
  sendHudOverrides(h);
385
+ // v1.68: nothing in a place that has never shown a choice card.
386
+ if (h.ballotState) {
387
+ Ballot.send(h, ballotDeps(h));
388
+ }
225
389
  Actors.applyTunes(h, h.engine?.maxSpeed?.() ?? 12);
226
390
  sendLabelOverrides(h);
391
+ Vis.send(h);
227
392
  sendAvatarOverrides(h);
393
+ if (h.manifest.yourGames) {
394
+ Yours.send(h, listedDoors(h), membersOf);
395
+ }
228
396
  Party.tick(partyDeps(h));
229
397
  Wear.sendOverrides(h, blockedPairs(h));
398
+ // v1.53 earned items: nothing in a place where nobody shows one.
399
+ if (Earned.used(h)) {
400
+ Earned.sendOverrides(h, blockedPairs(h));
401
+ }
230
402
  // v1.28 `hub.tryOn`: nothing in a place that never calls it.
231
403
  if (Wear.tryOnUsed(h)) {
232
404
  Wear.sendTryOverrides(h, blockedPairs(h));
233
405
  }
234
406
  // Cabinet cards (v1.7): nothing in a place with no classic door.
235
407
  Cabinets.send(h, (playerId) => namesOf(h, blockedPairs(h)?.get(playerId) ?? []));
408
+ notifyResumes(h);
236
409
  Actors.flushHandovers(h, handovers);
237
410
  },
238
411
 
@@ -245,9 +418,36 @@ export function layer(castleJson, deckHooks, placeHooks, sceneExists, sceneGroun
245
418
  interest(sim, known) {
246
419
  const pairs = blockedPairs(h);
247
420
  const hidden = pairs ? (viewer, other) => Boolean(pairs.get(viewer)?.has(other)) : null;
421
+ if (h.cells) {
422
+ return Blocks.withoutHidden(cellPlayers(h, sim, known, hidden), pairs);
423
+ }
248
424
  return Blocks.withoutHidden(nearestPlayers(sim, known, h.place.nearestPlayers, hidden), pairs);
249
425
  },
250
426
 
427
+ ...(manifest.places[Manifest.MAIN_PLACE].interest === 'cells' ? {
428
+ objectInterest(sim) {
429
+ if (!h.cells) {
430
+ return null;
431
+ }
432
+ const views = playerCells(h, sim);
433
+ const located = new Map();
434
+ for (const [id, object] of sim.objects) {
435
+ const at = object.body?.translation?.() ?? object.at;
436
+ const cell = Cells.cellAt(h.cells, at?.x, at?.z, h.objectCells.get(id));
437
+ h.objectCells.set(id, cell);
438
+ located.set(id, cell);
439
+ }
440
+ for (const id of h.objectCells.keys()) {
441
+ if (!sim.objects.has(id)) {
442
+ h.objectCells.delete(id);
443
+ }
444
+ }
445
+ return new Map([...views].map(([viewer, { visible }]) => [viewer, new Set([...located].filter(([id, cell]) =>
446
+ visible === null || cell === null || visible.has(cell) || sim.objects.get(id).owner === viewer || h.grabs.get(viewer) === id,
447
+ ).map(([id]) => id))]));
448
+ },
449
+ } : {}),
450
+
251
451
  shutdown: () => shutdown(h),
252
452
 
253
453
  join() {
@@ -256,7 +456,13 @@ export function layer(castleJson, deckHooks, placeHooks, sceneExists, sceneGroun
256
456
  // under it rather than past the world's floor, where no pose is read.
257
457
  hubPlace: { ...Manifest.publicPlace(h.placeId, h.place), fallY: h.fallY },
258
458
  hubAv: avatars(h, blockedPairs(h)),
459
+ // v1.51, only while someone here wears one of the twelve after the first four.
460
+ ...avatars2ForJoin(h),
461
+ ...avatarColorsForJoin(h),
259
462
  ...wearingForJoin(h),
463
+ ...(h.place.companion === true && h.companionUsed ? { hubGlow: Companion.glowOf(h) } : {}),
464
+ // v1.53, only once someone here shows an earned item.
465
+ ...(h.earned.size > 0 ? earnedForJoin(h) : {}),
260
466
  hud: hudForAll(h),
261
467
  hidden: [...h.hidden],
262
468
  held: [...h.held.keys()],
@@ -272,13 +478,24 @@ export function layer(castleJson, deckHooks, placeHooks, sceneExists, sceneGroun
272
478
  ...(h.keptFor.size > 0 ? { hubKept: Grab.keptOf(h) } : {}),
273
479
  // v1.28, only while the place shows a try-on on someone.
274
480
  ...(h.trying.size > 0 ? tryingForJoin(h) : {}),
481
+ // v1.33, only a town of a deck with `hub.stuck`.
482
+ ...(stuckHere(h) ? { hubStuck: { to: arrivalName(h), ...(hasUnstick(h) ? { hook: true } : {}) } } : {}),
275
483
  };
276
484
  },
277
485
 
278
486
  delta() {
279
487
  const out = {};
280
488
  latch(h, 'hubAv', avatars(h, blockedPairs(h)), out);
489
+ latchAvatars2(h, out);
490
+ latchAvatarColors(h, out);
281
491
  latchWearing(h, out);
492
+ if (h.place.companion === true && h.companionUsed) {
493
+ latch(h, 'hubGlow', Companion.glowOf(h), out);
494
+ }
495
+ // v1.53: nothing until someone shows an earned item, then each change.
496
+ if (h.earned.size > 0 || h.sent.has('hubEarned')) {
497
+ latchEarned(h, out);
498
+ }
282
499
  latch(h, 'hud', hudForAll(h), out);
283
500
  latch(h, 'hidden', [...h.hidden], out);
284
501
  latch(h, 'held', [...h.held.keys()], out);
@@ -326,6 +543,18 @@ export function layer(castleJson, deckHooks, placeHooks, sceneExists, sceneGroun
326
543
  }
327
544
  await h.npcs.onRead(request);
328
545
  },
546
+ // v1.66: only a deck with an `npcTool` hook listens for lookups.
547
+ ...(hasHook(deckHooks, placeHooks, 'npcTool')
548
+ ? {
549
+ async onWorldCharacterTool(request, session) {
550
+ h.session ??= session;
551
+ if (!h.sim) {
552
+ return { error: 'not ready' };
553
+ }
554
+ return await h.npcs.onTool(request);
555
+ },
556
+ }
557
+ : {}),
329
558
  },
330
559
  };
331
560
  }
@@ -405,6 +634,14 @@ function logStats(h) {
405
634
  function newState(manifest) {
406
635
  const h = {
407
636
  manifest,
637
+ cells: null,
638
+ cellTick: null,
639
+ cellViews: null,
640
+ playerCells: new Map(),
641
+ objectCells: new Map(),
642
+ caps: new Map(),
643
+ capAt: new Map(),
644
+ sentMaps: new Map(),
408
645
  placeId: Manifest.MAIN_PLACE,
409
646
  place: manifest.places[Manifest.MAIN_PLACE],
410
647
  hooks: {},
@@ -437,12 +674,15 @@ function newState(manifest) {
437
674
  // `${actorId}|${doorId}` -> the door's object `doors()` hands out
438
675
  doorObjects: new Map(),
439
676
  boardsAt: 0,
677
+ boardsReading: false,
440
678
  // `${op}:${code}` refusals already logged
441
679
  refusals: new Set(),
442
680
  hud: null,
443
681
  // playerId -> spec, and what was last sent of each
444
682
  hudMe: new Map(),
445
683
  sentHudMe: new Map(),
684
+ // v1.52: private leaving lines, never part of a snapshot.
685
+ leaving: new Map(),
446
686
  hidden: new Set(),
447
687
  // playerId -> { at, facing }
448
688
  held: new Map(),
@@ -464,6 +704,8 @@ function newState(manifest) {
464
704
  ...Grab.newGrabState(),
465
705
  // what players wear on their avatars (`wear.js`, v1.4)
466
706
  ...Wear.newWearState(),
707
+ // earned items players show (`earned.js`, v1.53)
708
+ ...Earned.newEarnedState(),
467
709
  // emotes, seats and sounds (`idle.js`, v1.6)
468
710
  ...Idle.newIdleState(),
469
711
  // arcade cabinets' cards (`cabinets.js`, v1.7)
@@ -474,6 +716,10 @@ function newState(manifest) {
474
716
  ...Say.newSayState(),
475
717
  };
476
718
  h.ctx = makeContext(h);
719
+ // v1.68: `hub.ballot` only in a deck that declares the card in some place.
720
+ if (manifest.ballot) {
721
+ h.ctx.ballot = (playerIds, spec) => Ballot.ballot(h, playerIds, spec);
722
+ }
477
723
  h.npcLabel = (actorId, text, options) => setLabel(h, isSceneActor(h, actorId) ? actorId : null, text, options, true);
478
724
  h.blockedPairs = () => blockedPairs(h);
479
725
  h.npcs = makeNpcs(h);
@@ -489,6 +735,13 @@ function makeContext(h) {
489
735
  get sim() {
490
736
  return h.sim;
491
737
  },
738
+ get owner() {
739
+ const owner = h.session?.hub?.owner;
740
+ if (typeof owner === 'string' && owner.length > 0) {
741
+ return owner;
742
+ }
743
+ return !platformHub(h) && isDevSession(h) && h.manifest.house?.devOwner === 'first' ? h.devOwner ?? null : null;
744
+ },
492
745
  get place() {
493
746
  return { id: h.placeId, title: h.place.title, scene: h.place.scene, manifest: h.place };
494
747
  },
@@ -537,7 +790,10 @@ function makeContext(h) {
537
790
  h.hudMe.delete(playerId);
538
791
  }
539
792
  },
540
- hide(actorId) {
793
+ hide(actorId, options) {
794
+ if (options !== undefined) {
795
+ return Vis.set(h, actorId, options, true);
796
+ }
541
797
  if (!isSceneActor(h, actorId)) {
542
798
  return;
543
799
  }
@@ -551,7 +807,10 @@ function makeContext(h) {
551
807
  Grab.unkeep(h, actorId);
552
808
  h.sim?.bodies.get(actorId)?.setEnabled(false);
553
809
  },
554
- show(actorId) {
810
+ show(actorId, options) {
811
+ if (options !== undefined) {
812
+ return Vis.set(h, actorId, options, false);
813
+ }
555
814
  if (!h.hidden.delete(actorId)) {
556
815
  return;
557
816
  }
@@ -560,9 +819,17 @@ function makeContext(h) {
560
819
  move: (actorId, to, options) => Actors.move(h, actorId, to, options),
561
820
  tint: (actorId, color) => Actors.tint(h, actorId, color),
562
821
  mark: (playerId, spec) => Actors.mark(h, playerId, spec),
822
+ leaving: (playerId, text) => leaving(h, playerId, text),
563
823
  results: (playerId) => History.results(h, playerId),
824
+ friendsAmong: (playerId, userIds) => Friends.friendsAmong(h, playerId, userIds, userIdOf),
825
+ friendBests: (key, options) => friendBests(h, key, options, userIdOf),
564
826
  wear: (playerId, spec) => wear(h, playerId, spec),
565
827
  tryOn: (playerId, spec) => Wear.tryOn(h, playerId, spec),
828
+ wearing: (playerId) => Wear.wearing(h, playerId),
829
+ unlock: (playerId, itemId) => Earned.unlock(h, playerId, itemId, earnedDeps(h, playerId, 'unlock')),
830
+ wearEarned: (playerId, choice) => Earned.wearEarned(h, playerId, choice, earnedDeps(h, playerId, 'wearEarned')),
831
+ unlocksOf: (userIds) => Earned.unlocksOf(platformHub(h), userIds, (err) => refused(h, 'unlocks', err), h),
832
+ earned: (playerId) => Earned.earnedOf(h, playerId),
566
833
  tune: (playerId, spec) => Actors.tune(h, playerId, spec),
567
834
  spawn: (fromActorId, at) => Actors.spawn(h, fromActorId, at, h.engine),
568
835
  pose: (actorId) => Actors.pose(h, actorId),
@@ -573,11 +840,14 @@ function makeContext(h) {
573
840
  label: (actorId, text, options) => setLabel(h, isSceneActor(h, actorId) ? actorId : null, text, options, false),
574
841
  npc: (actorId) => h.npcs.handle(actorId),
575
842
  npcs: () => h.npcs.list(),
843
+ preferNpc: (playerId, npcId) => h.npcs.prefer(playerId, npcId),
576
844
  result: (playerId, value) => report(h, playerId, value),
577
845
  drop: (playerId) => Grab.drop(h, playerId),
578
846
  emote: (playerId, id) => Idle.emote(h, playerId, id),
579
847
  seat: (playerId) => Idle.seat(h, playerId),
580
848
  sound: (actorId, file, options) => Idle.sound(h, actorId, file, options),
849
+ cue: (target, name) => Cues.cue(h, target, name),
850
+ shot: (playerId, value) => Shot.shot(h, playerId, value),
581
851
  holding: (playerId) => Grab.holding(h, playerId),
582
852
  keepFor: (actorId, playerId) => Grab.keepFor(h, actorId, playerId),
583
853
  end(playerIds) {
@@ -607,33 +877,123 @@ function platformHub(h) {
607
877
  // A client's hello: the avatar it wears, the door it came through, how many
608
878
  // came with it, and what it carries back from a game (a town reads that). Where
609
879
  // the host has hub ops, the door is ghost's arrival and the result and avatar
610
- // are read from ghost (`readResults`); the client's word is not used for them.
611
- function hello(h, player, data) {
880
+ // are read from ghost (`readResults`). The hello's avatar and colour are
881
+ // provisional until that read; colours also work with the manifest opt-in.
882
+ function hello(h, player, data, synthetic = false) {
883
+ prepareResume(h, player.playerId, false);
612
884
  const clientAvatar = Number.isInteger(data.avatar) && data.avatar >= 0 && data.avatar < AVATARS ? data.avatar : 0;
885
+ const clientColor = (h.manifest.avatarColors === true || platformHub(h)) ? cleanAvatarColor(data.color) : 0;
613
886
  const party = Number.isInteger(data.party) && data.party >= 1 && data.party <= 24 ? data.party : 1;
614
887
  const known = h.players.get(player.playerId);
888
+ // A player this place let go whose connection came back still holding what
889
+ // it was sent (`greetLate`): the client's own resume hello or the place's
890
+ // late greet for it, whichever comes first, arrives them once and marks that
891
+ // stale. A game keeps the old way, so it takes no resume hello (its round
892
+ // and result belong to the visit that left), unless its place says
893
+ // `resume: true` (v1.72): then it is arrived again like any place, and the
894
+ // visit goes on. A plain hello is a fresh client (a reload), which holds
895
+ // nothing.
896
+ //
897
+ // v1.72 resume invariants, every one only in a place with `resume: true`
898
+ // (`resumes`; without the key none of this runs and nothing is stored):
899
+ // I1 one result per visit, whatever the order of leave, report and
900
+ // resume: `forget` keeps the result after the leave hook ran (which
901
+ // may report it), and the re-arrived entry gets it back;
902
+ // I2 the visit's deadline is set once, at its first arrival (`visitAt`),
903
+ // and kept across resumes, so drops never extend a visit;
904
+ // I3 restored state with a packet is sent again on resume: the end
905
+ // (`hub-end` with `again`), and the HUD, shot and the rest (`staleSent`
906
+ // and the place's own arrive);
907
+ // I4 provenance (`from`, `fromDeckId`) is written once per visit.
908
+ const back = !known && data.resume === true && Boolean(h.forgotten?.has(player.playerId));
909
+ const resumes = h.place?.result ? h.place.resume === true : false;
910
+ if (back && h.place?.result && !resumes) {
911
+ return;
912
+ }
913
+ // v1.72: what a resume place's forgotten record kept of the visit that left.
914
+ const last = back && resumes ? h.forgotten.get(player.playerId) : null;
915
+ h.forgotten?.delete(player.playerId);
916
+ h.noHelloSince?.delete(player.playerId);
917
+ if (back) {
918
+ staleSent(h, player.playerId);
919
+ } else if (resumes && known?.hello && data.resume === true) {
920
+ // v1.72: a game that resumes, still holding the player: the drop may have
921
+ // lost what it sent them, so it all goes again (the leaving line is
922
+ // re-sent by joinedAfresh below).
923
+ staleSent(h, player.playerId, false);
924
+ }
615
925
  const hub = platformHub(h);
616
926
  const arrival = hub ? hub.arrival(player.playerId) : null;
617
- const from = hub ? arrival?.doorId ?? null : typeof data.from === 'string' && data.from.length <= 32 ? data.from : null;
927
+ // A resume place's re-arrived player keeps the door they first came by
928
+ // when the platform no longer says one (its arrival goes with the leave).
929
+ const said = hub ? arrival?.doorId ?? null : typeof data.from === 'string' && data.from.length <= 32 ? data.from : null;
930
+ // I4: a resume place keeps the visit's first door, whatever a later hello says.
931
+ // A saved none is kept too: only a key never saved takes what is said now.
932
+ const keep = (key, now) => {
933
+ if (!resumes) {
934
+ return now;
935
+ }
936
+ const was = known ?? last;
937
+ return was && Object.hasOwn(was, key) ? was[key] ?? null : now;
938
+ };
939
+ const from = keep('from', said);
940
+ const fromDeckId = keep('fromDeckId', arrival?.fromDeckId ?? null);
618
941
  // A later hello with the same choice keeps the platform avatar a read found;
619
942
  // a new choice wins, and outdates any read in flight (`avatarRev`).
620
943
  const same = known?.hello && known.clientAvatar === clientAvatar;
944
+ const sameColor = same && known.clientColor === clientColor;
945
+ // A stale ballot card still waiting to be cleared survives a repeated
946
+ // resume hello, whose joinedAfresh below would otherwise drop the mark.
947
+ const ballotStale = back || h.ballotState?.sent.get(player.playerId) === STALE;
621
948
  // A hello that is not an avatar change is a client that joined afresh: it
622
949
  // holds none of the cabinet cards it was sent (v1.7).
623
950
  if (data.again !== true) {
951
+ replaySent(h, player.playerId, data.resume === true);
952
+ h.npcs.replayPreferred(player.playerId, data.resume === true);
953
+ Shot.joinedAfresh(h, player.playerId);
954
+ Vis.joinedAfresh(h, player.playerId);
955
+ Decor.joinedAfresh(h, player.playerId);
956
+ if (h.place.actions === true) {
957
+ Actions.joinedAfresh(h, player.playerId);
958
+ }
959
+ if (h.place.companion === true) {
960
+ Companion.joinedAfresh(h, player.playerId);
961
+ }
962
+ if (h.place.ask === true) {
963
+ Ask.joinedAfresh(h, player.playerId);
964
+ }
965
+ if (h.place.menu === true) {
966
+ Menu.joinedAfresh(h, player.playerId);
967
+ }
968
+ if (h.ballotState) {
969
+ Ballot.joinedAfresh(h, player.playerId);
970
+ }
624
971
  Cabinets.forget(h, player.playerId);
972
+ Friends.resend(h, player.playerId);
625
973
  // v1.28: nothing in a place that never sent a try-on to one player alone.
626
974
  Wear.joinedAfresh(h, player.playerId);
975
+ // v1.53: likewise its earned items alone, only where someone has one.
976
+ if (Earned.used(h)) {
977
+ Earned.joinedAfresh(h, player.playerId);
978
+ }
979
+ // A fresh client with a retained id has none of its private leaving line.
980
+ if (h.leaving.has(player.playerId)) {
981
+ h.session?.send(player.playerId, { k: 'hub-leaving', text: h.leaving.get(player.playerId) });
982
+ }
627
983
  }
628
984
  h.players.set(player.playerId, {
629
985
  // Who this is, kept for `leave`: by then the session has forgotten them.
986
+ ...(h.place.visibility === true && known?.visibility ? { visibility: known.visibility, visibilityPending: known.visibilityPending } : {}),
630
987
  userId: userIdOf(h, player.playerId) ?? known?.userId ?? null,
631
988
  username: usernameOf(h, player.playerId),
632
989
  avatar: same ? known.avatar : clientAvatar,
633
990
  clientAvatar,
991
+ color: sameColor ? known.color : clientColor,
992
+ clientColor,
993
+ colorRev: sameColor ? known.colorRev : (known?.colorRev ?? 0) + 1,
634
994
  avatarRev: same ? known.avatarRev : (known?.avatarRev ?? 0) + 1,
635
995
  from,
636
- fromDeckId: arrival?.fromDeckId ?? null,
996
+ fromDeckId,
637
997
  // A jump to a friend says whom (the client's word: it decides only where
638
998
  // the player appears, beside someone already in this session).
639
999
  near: typeof data.near === 'string' && USER_ID.test(data.near) ? data.near : (known?.near ?? null),
@@ -646,12 +1006,43 @@ function hello(h, player, data) {
646
1006
  helloAt: known?.hello ? known.helloAt : Date.now(),
647
1007
  arrived: known?.arrived ?? false,
648
1008
  arrivedAt: known?.arrivedAt ?? null,
649
- result: known?.result ?? null,
1009
+ result: known?.result ?? (last ? last.result ?? null : null),
650
1010
  // ghost's results of this player for `hub.results`, kept across hellos
651
1011
  history: known?.history ?? null,
652
1012
  historyFrom: known?.historyFrom ?? null,
653
- ended: known?.ended ?? false,
1013
+ ...(h.manifest.yourGames ? { hearts: known?.hearts ?? [], yoursKey: data.again === true ? known?.yoursKey : null } : {}),
1014
+ ended: known?.ended ?? (last ? last.ended === true : false),
1015
+ // v1.72 (I2, I3): only in a resume place, and only once known.
1016
+ ...(resumes && (known?.visitAt ?? last?.visitAt) !== undefined ? { visitAt: known?.visitAt ?? last.visitAt } : {}),
1017
+ ...(resumes && (known?.endWhy ?? last?.endWhy) !== undefined ? { endWhy: known?.endWhy ?? last.endWhy } : {}),
1018
+ ...(last?.ended === true || known?.endAgain === true ? { endAgain: true } : {}),
654
1019
  });
1020
+ // v1.89: hook presence opts in. Wait until the private replay was sent;
1021
+ // the entry identity also prevents a queued hello from crossing a leave.
1022
+ if (known?.arrived && !h.resumeDeparting?.has(player.playerId) && typeof h.hooks.resume === 'function') {
1023
+ const kept = h.resumeKept?.get(player.playerId);
1024
+ const body = h.sim?.players.get(player.playerId);
1025
+ const companionHello = !synthetic && data.resume === true && Boolean(body && kept?.pendingClientHello === body);
1026
+ if (companionHello) {
1027
+ delete kept.pendingClientHello;
1028
+ }
1029
+ if (synthetic && kept) {
1030
+ kept.pendingClientHello = body;
1031
+ }
1032
+ if ((data.again !== true && !companionHello) || h.resumePending?.has(player.playerId)) {
1033
+ (h.resumePending ??= new Map()).set(player.playerId, h.players.get(player.playerId));
1034
+ }
1035
+ }
1036
+ // I3: one still here whose visit ended hears the end again (a drop may
1037
+ // have lost it); one back is told once arrived (`arrivals`).
1038
+ if (resumes && known?.arrived && known.ended && data.resume === true) {
1039
+ endAgain(h, player.playerId);
1040
+ }
1041
+ Friends.prime(h, player.playerId, userIdOf);
1042
+ // After joinedAfresh above, which resets this cache.
1043
+ if (ballotStale && h.ballotState) {
1044
+ h.ballotState.sent.set(player.playerId, STALE);
1045
+ }
655
1046
  }
656
1047
 
657
1048
  // What a returning client says it brings back: the result its game sent it.
@@ -683,15 +1074,260 @@ function outcomeOrNone(outcome) {
683
1074
  // result for the visit (the host takes one for a player who has just left)
684
1075
  // and save their progress under the user id it is handed (v1.2).
685
1076
  function reconcile(h) {
1077
+ for (const playerId of h.resumeKept?.keys() ?? []) {
1078
+ prepareResume(h, playerId);
1079
+ }
1080
+ for (const id of h.playerCells.keys()) {
1081
+ if (!h.sim.players.has(id)) {
1082
+ h.playerCells.delete(id);
1083
+ h.caps.delete(id);
1084
+ h.capAt.delete(id);
1085
+ }
1086
+ }
1087
+ // A connection that sent hub-cap and left before it had a body.
1088
+ for (const id of h.caps.keys()) {
1089
+ if (!h.sim.players.has(id) && !h.session?.players.some((p) => p.playerId === id)) {
1090
+ h.caps.delete(id);
1091
+ h.capAt.delete(id);
1092
+ }
1093
+ }
1094
+ Vis.prune(h);
1095
+ Decor.prune(h);
1096
+ if (h.place.actions === true) {
1097
+ Actions.prune(h);
1098
+ }
1099
+ if (h.place.companion === true) {
1100
+ Companion.prune(h);
1101
+ }
1102
+ if (h.place.ask === true) {
1103
+ Ask.prune(h);
1104
+ }
1105
+ if (h.place.menu === true) {
1106
+ Menu.prune(h);
1107
+ }
1108
+ // A call may precede this player's first hello, as hub.wear may.
1109
+ for (const playerId of h.leaving.keys()) {
1110
+ if (!h.sim.players.has(playerId) && !h.session?.players.some((p) => p.playerId === playerId)) {
1111
+ h.leaving.delete(playerId);
1112
+ }
1113
+ }
686
1114
  for (const playerId of [...h.players.keys()]) {
687
1115
  const inSession = h.session?.players.some((p) => p.playerId === playerId);
688
1116
  if (!h.sim.players.has(playerId) && !inSession) {
689
- forget(h, playerId);
1117
+ if (!h.resumeKept?.has(playerId)) {
1118
+ forget(h, playerId);
1119
+ }
1120
+ }
1121
+ }
1122
+ greetLate(h);
1123
+ }
1124
+
1125
+ // v1.89 opt-in retention: the transport supplies no close reason. An absent
1126
+ // body is held for at most 60 wall-clock seconds; shutdown and explicit kit
1127
+ // travel still finalize the visit. Pose copies are taken after the deck's step,
1128
+ // before real-time removes a dropped body on its next roster reconciliation.
1129
+ const RESUME_KEEP_MS = 60000;
1130
+ function rememberResumePoses(h) {
1131
+ if (!h.resumeKept) {
1132
+ return;
1133
+ }
1134
+ for (const [id, entry] of h.players) {
1135
+ const body = h.sim.players.get(id);
1136
+ if (!entry.arrived || !body) {
1137
+ continue;
1138
+ }
1139
+ h.resumeKept.set(id, {
1140
+ body,
1141
+ at: { ...body.at },
1142
+ facing: body.facing,
1143
+ seenAt: Date.now(),
1144
+ ...(h.resumeKept.get(id)?.pendingClientHello ? { pendingClientHello: h.resumeKept.get(id).pendingClientHello } : {}),
1145
+ });
1146
+ }
1147
+ }
1148
+
1149
+ function prepareResume(h, playerId, greet = true) {
1150
+ const kept = h.resumeKept?.get(playerId);
1151
+ if (!kept) {
1152
+ return;
1153
+ }
1154
+ const body = h.sim?.players.get(playerId);
1155
+ const present = body && h.session?.players.some((p) => p.playerId === playerId);
1156
+ const returning = present && (kept.awayAt !== undefined || body !== kept.body);
1157
+ if (!present) {
1158
+ kept.awayAt ??= Date.now();
1159
+ }
1160
+ // A replacement body can arrive before an absent tick was observed. In that
1161
+ // case the last tick that saw the old body bounds its reconnect window.
1162
+ const since = kept.awayAt ?? kept.seenAt;
1163
+ if ((!present || returning) && (h.resumeDeparting.has(playerId) || Date.now() - since >= RESUME_KEEP_MS)) {
1164
+ forget(h, playerId);
1165
+ return;
1166
+ }
1167
+ if (!returning) {
1168
+ return;
1169
+ }
1170
+ moveBody(h, playerId, kept.at, kept.facing);
1171
+ settle(h, playerId);
1172
+ kept.body = body;
1173
+ delete kept.awayAt;
1174
+ // The silent same-id case has no fresh arrive hook. Reuse the existing hello
1175
+ // replay to restore private channels, including a cleared channel it missed.
1176
+ if (greet) {
1177
+ const entry = h.players.get(playerId);
1178
+ hello(
1179
+ h,
1180
+ { playerId },
1181
+ {
1182
+ k: 'hub-hello',
1183
+ avatar: entry.clientAvatar,
1184
+ color: entry.clientColor,
1185
+ party: 1,
1186
+ resume: true,
1187
+ },
1188
+ true,
1189
+ );
1190
+ }
1191
+ }
1192
+
1193
+ // Reconnect re-hello (a bug fix for every place, no contract version): a
1194
+ // connection that comes back inside the host's reconnect window after the place
1195
+ // let its player go (an app switch on a phone) has a body and no hello, and its
1196
+ // client, still on the same connection, never greets again (it greets a new
1197
+ // connection only), so the player would be a ghost: no HUD, no shots, no door.
1198
+ // Only a player this place let go in the last 10 minutes is greeted for, after
1199
+ // 3 s without a hello, with the avatar it last chose here (the platform's
1200
+ // avatar read still applies): a newcomer's own first hello carries its party
1201
+ // and arrival, so it is always waited for. Nothing changes until a reconnect.
1202
+ // Not in a game (a place with `result`): its round and result belong to the
1203
+ // visit that left, so it keeps the old way (a fresh join once the window ends),
1204
+ // unless its place says `resume: true` (v1.72), when it is greeted like any.
1205
+ // The client still holds what it was last sent privately (HUD, labels, tune,
1206
+ // avatars, visibility, party, ballot card, leaving line) while the place forgot
1207
+ // it, so those are marked stale and sent again, clearing what the place no
1208
+ // longer says.
1209
+ const HELLO_LATE_MS = 3000;
1210
+ // Matches no JSON a channel sends, so its next send goes out whatever it holds.
1211
+ const STALE = '\u0000stale';
1212
+ const FORGOTTEN_MS = 10 * 60 * 1000;
1213
+ function greetLate(h) {
1214
+ const now = h.sim.timeMs;
1215
+ if (!Number.isFinite(now)) {
1216
+ return;
1217
+ }
1218
+ const since = (h.noHelloSince ??= new Map());
1219
+ for (const id of [...since.keys()]) {
1220
+ if (!h.session?.players.some((p) => p.playerId === id) || h.players.get(id)?.hello) {
1221
+ since.delete(id);
1222
+ }
1223
+ }
1224
+ for (const [id, last] of h.forgotten ?? []) {
1225
+ if (now - last.at > FORGOTTEN_MS) {
1226
+ h.forgotten.delete(id);
1227
+ }
1228
+ }
1229
+ if (h.place?.result && h.place.resume !== true) {
1230
+ return;
1231
+ }
1232
+ for (const { playerId } of h.session?.players ?? []) {
1233
+ if (!h.forgotten?.has(playerId) || !h.sim.players.has(playerId) || h.players.get(playerId)?.hello) {
1234
+ continue;
1235
+ }
1236
+ const first = since.get(playerId);
1237
+ if (first === undefined) {
1238
+ since.set(playerId, now);
1239
+ continue;
1240
+ }
1241
+ if (now - first < HELLO_LATE_MS) {
1242
+ continue;
1243
+ }
1244
+ since.delete(playerId);
1245
+ hello(h, { playerId }, { k: 'hub-hello', avatar: h.forgotten.get(playerId).clientAvatar, ...(h.forgotten.get(playerId).clientColor ? { color: h.forgotten.get(playerId).clientColor } : {}), party: 1, resume: true });
1246
+ }
1247
+ }
1248
+
1249
+ // What a returning player's client still holds from before the place let it
1250
+ // go: each private channel is marked stale so its next send goes out, clearing
1251
+ // what the place no longer says. Run by `hello` for a player it let go,
1252
+ // whichever hello (the late greet's or the client's own) comes first.
1253
+ // `forgotten` false (v1.72, a resume place's player it still holds): the
1254
+ // leaving line is left to `hello`, which re-sends one that is set.
1255
+ function staleSent(h, playerId, forgotten = true) {
1256
+ for (const sent of [h.sentHudMe, h.sentLabelsMe, h.sentTunes, h.sentAvMe]) {
1257
+ sent?.set(playerId, STALE);
1258
+ }
1259
+ (h.sentVisMe ??= new Map()).set(playerId, STALE);
1260
+ h.party?.sent.set(playerId, STALE);
1261
+ if (!forgotten) {
1262
+ return;
1263
+ }
1264
+ // The leaving line has no cache: it goes out only when set, so clear it here.
1265
+ try {
1266
+ h.session?.send(playerId, { k: 'hub-leaving', text: null });
1267
+ } catch {
1268
+ // A connection that went meanwhile holds nothing.
1269
+ }
1270
+ }
1271
+
1272
+ // A fresh client holds none of its private channels. Only a non-empty last
1273
+ // send needs replaying; an unused or already empty channel stays quiet.
1274
+ // `held` (a resume hello): the client kept what it held and may have missed a
1275
+ // clear while away, so every channel ever sent goes again, empty ones too.
1276
+ function replaySent(h, playerId, held = false) {
1277
+ for (const [sent, empty] of [
1278
+ [h.sentHudMe, 'null'],
1279
+ [h.sentLabelsMe, '{}'],
1280
+ [h.sentTunes, 'null'],
1281
+ [h.sentAvMe, '{}'],
1282
+ ]) {
1283
+ if (sent?.has(playerId) && (held || sent.get(playerId) !== empty)) {
1284
+ sent.set(playerId, STALE);
1285
+ }
1286
+ }
1287
+ }
1288
+
1289
+ // Initial visibility can arrive after hello but before the player's body or
1290
+ // deck arrive hook. Keep its latest state and deliver only after arrival.
1291
+ function notifyVisibility(h, only = null) {
1292
+ for (const [playerId, entry] of only ? [[only, h.players.get(only)]] : h.players) {
1293
+ if (!entry?.visibilityPending || !entry.arrived || !h.sim?.players.has(playerId)) {continue;}
1294
+ entry.visibilityPending = false;
1295
+ try {
1296
+ const result = h.hooks.visibility?.(h.ctx, { playerId, ...entry.visibility });
1297
+ result?.catch?.(() => console.warn('[hub] visibility hook failed'));
1298
+ } catch {
1299
+ console.warn('[hub] visibility hook failed');
1300
+ }
1301
+ }
1302
+ }
1303
+
1304
+ // Dispatch after this step's private channels, once per id per step. A hook
1305
+ // may queue another hello; that belongs to the next step, not this drain.
1306
+ function notifyResumes(h) {
1307
+ if (!h.resumePending?.size) {
1308
+ return;
1309
+ }
1310
+ const pending = [...h.resumePending];
1311
+ h.resumePending.clear();
1312
+ for (const [playerId, entry] of pending) {
1313
+ if (h.players.get(playerId) !== entry || !entry.arrived || !h.sim.players.has(playerId) || !h.session?.players.some((p) => p.playerId === playerId)) {
1314
+ continue;
1315
+ }
1316
+ try {
1317
+ const result = h.hooks.resume(h.ctx, { playerId });
1318
+ if (result && typeof result.catch === 'function') {
1319
+ result.catch(() => console.warn('[hub] resume hook failed'));
1320
+ }
1321
+ } catch {
1322
+ console.warn('[hub] resume hook failed');
690
1323
  }
691
1324
  }
692
1325
  }
693
1326
 
694
1327
  function forget(h, playerId) {
1328
+ h.resumePending?.delete(playerId);
1329
+ h.resumeKept?.delete(playerId);
1330
+ h.resumeDeparting?.delete(playerId);
695
1331
  const entry = h.players.get(playerId);
696
1332
  if (entry?.arrived) {
697
1333
  // A place's hook that throws still lets the player go, once.
@@ -701,12 +1337,38 @@ function forget(h, playerId) {
701
1337
  console.warn(`[hub] leave hook failed: ${err?.message ?? err}`);
702
1338
  }
703
1339
  }
1340
+ // After the leave hook, which may have reported the visit's result.
1341
+ if (entry?.hello) {
1342
+ const kept = { clientAvatar: entry.clientAvatar, clientColor: entry.clientColor, at: h.sim.timeMs };
1343
+ // v1.72: a game that resumes keeps what its re-arrival must not lose (the
1344
+ // invariants at `hello`): the result (I1), the deadline (I2), the end
1345
+ // (I3) and the door (I4).
1346
+ if (h.place?.result && h.place.resume === true && h.place.resumeKeep !== true) {
1347
+ Object.assign(kept, {
1348
+ result: entry.result ?? null,
1349
+ ended: entry.ended === true,
1350
+ endWhy: entry.endWhy,
1351
+ visitAt: entry.visitAt,
1352
+ from: entry.from ?? null,
1353
+ fromDeckId: entry.fromDeckId ?? null,
1354
+ });
1355
+ }
1356
+ (h.forgotten ??= new Map()).set(playerId, kept);
1357
+ }
704
1358
  Party.forget(h, playerId);
705
1359
  Say.forget(h, playerId);
1360
+ if (h.ballotState) {
1361
+ Ballot.forget(h, playerId);
1362
+ }
1363
+ Friends.forget(h, playerId);
1364
+ h.caps.delete(playerId);
1365
+ h.capAt.delete(playerId);
1366
+ h.playerCells.delete(playerId);
706
1367
  h.players.delete(playerId);
707
1368
  h.held.delete(playerId);
708
1369
  h.hudMe.delete(playerId);
709
1370
  h.sentHudMe.delete(playerId);
1371
+ h.leaving.delete(playerId);
710
1372
  h.tunes.delete(playerId);
711
1373
  h.sentTunes.delete(playerId);
712
1374
  h.labelsMe.delete(playerId);
@@ -714,12 +1376,33 @@ function forget(h, playerId) {
714
1376
  h.sentAvMe.delete(playerId);
715
1377
  h.marks.delete(playerId);
716
1378
  Wear.forget(h, playerId);
1379
+ Earned.forget(h, playerId);
717
1380
  h.shut.delete(playerId);
718
1381
  h.jumpAt.delete(playerId);
719
1382
  h.whereAt.delete(playerId);
1383
+ h.unstuckAt?.delete(playerId);
1384
+ h.unstuckAskAt?.delete(playerId);
720
1385
  h.settling.delete(playerId);
721
1386
  Grab.forget(h, playerId);
722
1387
  Idle.forget(h, playerId);
1388
+ Decor.forget(h, playerId);
1389
+ if (h.place.actions === true) {
1390
+ Actions.forget(h, playerId);
1391
+ }
1392
+ if (h.place.companion === true) {
1393
+ Companion.forget(h, playerId);
1394
+ }
1395
+ if (h.place.ask === true) {
1396
+ Ask.forget(h, playerId);
1397
+ }
1398
+ if (h.place.menu === true) {
1399
+ Menu.forget(h, playerId);
1400
+ }
1401
+ if (h.cueBudgets) {
1402
+ h.cueBudgets.delete(`player:${playerId}`);
1403
+ }
1404
+ Shot.forgetPlayer(h, playerId);
1405
+ Vis.forget(h, playerId);
723
1406
  Cabinets.forget(h, playerId);
724
1407
  h.npcs.leave(playerId);
725
1408
  }
@@ -744,7 +1427,10 @@ async function shutdown(h) {
744
1427
  let timer = null;
745
1428
  await Promise.race([
746
1429
  Promise.resolve()
747
- .then(() => h.hooks.shutdown?.(h.ctx))
1430
+ .then(async () => {
1431
+ await h.hooks.shutdown?.(h.ctx);
1432
+ await Promise.all([...(h.friendBestHelpers?.values() ?? [])].map((helper) => helper.drain()));
1433
+ })
748
1434
  .catch((err) => console.warn(`[hub] shutdown hook failed: ${err?.message ?? err}`)),
749
1435
  new Promise((resolve) => {
750
1436
  timer = setTimeout(resolve, SHUTDOWN_DRAIN_MS);
@@ -785,6 +1471,10 @@ function arrivals(h) {
785
1471
  const group = waiting.map(([playerId, entry]) => {
786
1472
  entry.arrived = true;
787
1473
  entry.arrivedAt = h.sim.timeMs;
1474
+ // v1.72 (I2): a resume place's visit has one deadline, from its first arrival.
1475
+ if (h.place.resume === true && h.place.result) {
1476
+ entry.visitAt ??= entry.arrivedAt;
1477
+ }
788
1478
  if (h.held.get(playerId)?.waiting) {
789
1479
  h.held.delete(playerId);
790
1480
  }
@@ -801,24 +1491,65 @@ function arrivals(h) {
801
1491
  party: entry.party ?? 1,
802
1492
  };
803
1493
  });
1494
+ const waitedAt = new Map(group.map((g) => [g.playerId, { ...h.sim.players.get(g.playerId)?.at }]));
804
1495
  placeGroup(h, group.map((g) => g.playerId));
805
1496
  placeNearFriends(h, group);
1497
+ // v1.67: a dev house keeps its first arrival as owner for this session.
1498
+ if (!platformHub(h) && isDevSession(h) && h.manifest.house?.devOwner === 'first' && !h.devOwnerChosen) {
1499
+ h.devOwnerChosen = true;
1500
+ h.devOwner = group[0]?.userId ?? null;
1501
+ }
806
1502
  h.hooks.arrive?.(h.ctx, group);
807
1503
  for (const { playerId } of group) {
808
1504
  const body = h.sim.players.get(playerId);
809
1505
  if (body) {
1506
+ // v1.40: kept where the arrival put them, like a jump. A player waits
1507
+ // for their group at the scene's spawn, where their client agrees they
1508
+ // are; placed, that client's reports still on their way name the spawn
1509
+ // and each pulled the body a step back toward it: four back from Tag
1510
+ // were dragged 2 to 3 m off the spots the town gave them, two onto the
1511
+ // next door's pad, and were taken into its game. Only one the arrival
1512
+ // moved: a player placed where they waited has no stale report to be
1513
+ // pulled by. (A place's hold is its own spot and is left alone.)
1514
+ const was = waitedAt.get(playerId);
1515
+ if (Math.hypot(body.at.x - was.x, body.at.z - was.z) > HOLD_SLACK) {
1516
+ settle(h, playerId);
1517
+ }
810
1518
  h.session?.send(playerId, { k: 'hub-arrived', facing: body.facing });
811
1519
  }
1520
+ if (h.players.get(playerId)?.endAgain) {
1521
+ delete h.players.get(playerId).endAgain;
1522
+ endAgain(h, playerId);
1523
+ }
812
1524
  }
813
1525
  }
814
1526
 
815
- // A row at the arrival actor, facing the way the manifest says.
816
- function placeGroup(h, playerIds) {
1527
+ // v1.72 (I3): the end of a resume place's visit, again, to a client a drop
1528
+ // may have kept it from (`again`: a client already ending keeps its pause).
1529
+ function endAgain(h, playerId) {
1530
+ const entry = h.players.get(playerId);
1531
+ if (!entry?.ended) {
1532
+ return;
1533
+ }
1534
+ h.held.delete(playerId);
1535
+ Shot.stopHolding(h, playerId);
1536
+ h.session?.send(playerId, { k: 'hub-end', why: entry.endWhy ?? 'end', again: true });
1537
+ }
1538
+
1539
+ // Where the place's players arrive: the arrival actor's Transform, else the
1540
+ // scene's spawn.
1541
+ function arrivalPoint(h) {
817
1542
  const arrival = h.place.arrival;
818
1543
  const actor = arrival.actor
819
1544
  ? h.actors.find((a) => a.id === arrival.actor)
820
1545
  : h.actors.find((a) => a.components.Player);
821
- const t = actor?.components.Transform ?? h.sim.spawn ?? { x: 0, y: 1, z: 0 };
1546
+ return actor?.components.Transform ?? h.sim?.spawn ?? { x: 0, y: 1, z: 0 };
1547
+ }
1548
+
1549
+ // A row at the arrival actor, facing the way the manifest says.
1550
+ function placeGroup(h, playerIds) {
1551
+ const arrival = h.place.arrival;
1552
+ const t = arrivalPoint(h);
822
1553
  let facing;
823
1554
  if (typeof arrival.face === 'number') {
824
1555
  facing = arrival.face * DEG;
@@ -832,7 +1563,8 @@ function placeGroup(h, playerIds) {
832
1563
  const n = playerIds.length;
833
1564
  playerIds.forEach((playerId, i) => {
834
1565
  const offset = (i - (n - 1) / 2) * arrival.spread;
835
- placeAt(h, playerId, { x: t.x + across.x * offset, y: Math.max(t.y ?? 1, 1.2), z: t.z + across.z * offset }, facing);
1566
+ const at = { x: t.x + across.x * offset, y: Math.max(t.y ?? 1, 1.2), z: t.z + across.z * offset };
1567
+ placeAt(h, playerId, { ...at, y: standingY(h, at) }, facing);
836
1568
  });
837
1569
  }
838
1570
 
@@ -952,6 +1684,14 @@ function footprintHas(shape, t, at, pad) {
952
1684
  // Move a body. One placed before the joiner's WORLD snapshot is where that
953
1685
  // snapshot starts them; a later one reaches the client as a clamp.
954
1686
  function placeAt(h, playerId, at, facing) {
1687
+ // A new placement is where the player is now: whatever was keeping them at
1688
+ // an earlier one (v1.40: an arrival's) lets go, so a place that puts a
1689
+ // player somewhere just after they arrive is not undone.
1690
+ h.settling.delete(playerId);
1691
+ moveBody(h, playerId, at, facing);
1692
+ }
1693
+
1694
+ function moveBody(h, playerId, at, facing) {
955
1695
  const body = h.sim?.players.get(playerId);
956
1696
  if (!body || !at || ![at.x, at.y, at.z].every(Number.isFinite)) {
957
1697
  return;
@@ -964,8 +1704,8 @@ function placeAt(h, playerId, at, facing) {
964
1704
  body.body.setTranslation(body.at, true);
965
1705
  }
966
1706
 
967
- // After a jump (to a door's pad, beside a player) the body is kept where it
968
- // was put for a moment. The client's move reports already on their way still
1707
+ // After a jump (to a door's pad, beside a player) or an arrival (v1.40) the
1708
+ // body is kept where it was put for a moment. The client's move reports already on their way still
969
1709
  // name the spot it left, and the server's movement clamp lets each one pull
970
1710
  // the body a step back toward it: on a slow phone that dragged a player a
971
1711
  // metre or two off the pad they had just been put on, and the pad never
@@ -991,7 +1731,7 @@ function enforceSettle(h) {
991
1731
  continue;
992
1732
  }
993
1733
  if (Math.hypot(body.at.x - spot.at.x, body.at.z - spot.at.z) > HOLD_SLACK) {
994
- placeAt(h, playerId, spot.at, spot.facing);
1734
+ moveBody(h, playerId, spot.at, spot.facing);
995
1735
  }
996
1736
  }
997
1737
  }
@@ -1040,7 +1780,7 @@ function enforceDuration(h) {
1040
1780
  }
1041
1781
  const limit = h.place.maxDurationSec * 1000;
1042
1782
  for (const [playerId, entry] of h.players) {
1043
- if (entry.arrived && !entry.ended && h.sim.timeMs - entry.arrivedAt >= limit) {
1783
+ if (entry.arrived && !entry.ended && h.sim.timeMs - (entry.visitAt ?? entry.arrivedAt) >= limit) {
1044
1784
  console.log(`[hub] ${usernameOf(h, playerId)} reached maxDurationSec`);
1045
1785
  end(h, playerId, 'time');
1046
1786
  }
@@ -1091,8 +1831,13 @@ function end(h, playerId, why) {
1091
1831
  const entry = h.players.get(playerId);
1092
1832
  if (entry) {
1093
1833
  entry.ended = true;
1834
+ // v1.72 (I3): kept to say it again on resume.
1835
+ if (h.place.resume === true && h.place.result) {
1836
+ entry.endWhy = why;
1837
+ }
1094
1838
  }
1095
1839
  h.held.delete(playerId);
1840
+ Shot.stopHolding(h, playerId);
1096
1841
  h.session?.send(playerId, { k: 'hub-end', why });
1097
1842
  }
1098
1843
 
@@ -1114,13 +1859,17 @@ function jumpDoors(h) {
1114
1859
  // The Doors list's rows. An event gate leads to a game another door already
1115
1860
  // leads to, so it is listed only while its event is open, and as the event
1116
1861
  // (two rows reading "King of the Hill" was one too many).
1862
+ function listedDoors(h) {
1863
+ return jumpDoors(h).filter((door) => {
1864
+ const event = h.boards.get(door.id)?.event;
1865
+ return !event || event.open;
1866
+ });
1867
+ }
1868
+
1117
1869
  function doorList(h) {
1118
1870
  const out = [];
1119
- for (const door of jumpDoors(h)) {
1871
+ for (const door of listedDoors(h)) {
1120
1872
  const event = h.boards.get(door.id)?.event;
1121
- if (event && !event.open) {
1122
- continue;
1123
- }
1124
1873
  const row = { id: door.id, title: event ? `Event · ${door.title}`.slice(0, 48) : door.title };
1125
1874
  // What a player picking a door wants to know: today's featured door (it
1126
1875
  // is listed first), one that takes a single player, how many it needs.
@@ -1161,17 +1910,220 @@ function doorJump(h, player, data) {
1161
1910
  // two who jump there do not land in one spot; else in front of the door.
1162
1911
  const at = Party.padPoint(h, door, Math.floor(Math.random() * 6), player.playerId) ?? frontOf(door);
1163
1912
  const facing = ((door.t.rotationY ?? 0) + 180) * DEG;
1164
- placeAt(h, player.playerId, { x: at.x, y: 1.2, z: at.z }, facing);
1913
+ placeAt(h, player.playerId, { x: at.x, y: standingY(h, { ...at, y: 1.2 }), z: at.z }, facing);
1165
1914
  settle(h, player.playerId);
1166
1915
  h.session?.send(player.playerId, { k: 'hub-jumped', facing });
1167
1916
  }
1168
1917
 
1918
+ // "Stuck?" (v1.33): whether this place puts a player back at its arrival for
1919
+ // the asking. A deck with `hub.stuck`, and a town only: in a game (a place
1920
+ // with a `result`) the way to the start is the game's to give or keep -- a
1921
+ // free one would be a way out of a trap, a tag or a lost position.
1922
+ function stuckHere(h) {
1923
+ return h.manifest.stuck === true && !h.place.result;
1924
+ }
1925
+
1926
+ // What the chip calls the arrival ("the square"), or null for none: the
1927
+ // place's own `where` words for the spot (§5: "in the square", "on Race Row",
1928
+ // "at the Arcade") without their first word. Words of another shape are not
1929
+ // guessed at.
1930
+ // Whether what a place's hook returned is an answer for later (a promise, or
1931
+ // anything with a callable `then`) rather than one given at once: the hooks
1932
+ // "Stuck?" asks are synchronous, and such a result is no answer. Its `then`
1933
+ // is never called -- that is running the place's code a second time, and an
1934
+ // `async then` that throws hands back a rejection of its own. A native
1935
+ // promise is the one thing that can reject with nobody having called
1936
+ // anything, so it alone is given a handler, by the built-in `then` (not the
1937
+ // object's own, which a place may have replaced); what that returns cannot
1938
+ // reject. Called inside the caller's catch: reading `then` may throw.
1939
+ function answersLater(result) {
1940
+ if (result === null || (typeof result !== 'object' && typeof result !== 'function')) {
1941
+ return false;
1942
+ }
1943
+ if (result instanceof Promise) {
1944
+ Promise.prototype.then.call(result, undefined, () => {});
1945
+ return true;
1946
+ }
1947
+ return typeof result.then === 'function';
1948
+ }
1949
+
1950
+ function arrivalName(h) {
1951
+ // The place's part is inside one catch, as `unstickSpot`'s is: this is said
1952
+ // in the answer to a tap, which nothing of the place's may stop. A promise
1953
+ // is no words (`answersLater`).
1954
+ try {
1955
+ const t = arrivalPoint(h);
1956
+ const words = h.hooks.where?.(h.ctx, { x: t.x, y: t.y ?? 1, z: t.z });
1957
+ if (answersLater(words)) {
1958
+ return null;
1959
+ }
1960
+ const name = typeof words === 'string' ? /^(?:in|on|at) (\S.*)$/.exec(words.trim())?.[1] : null;
1961
+ return name ? name.slice(0, WHERE_TEXT_MAX) : null;
1962
+ } catch (err) {
1963
+ try {
1964
+ console.warn(`[hub] where hook failed: ${err?.message ?? err}`);
1965
+ } catch {
1966
+ console.warn('[hub] where hook failed');
1967
+ }
1968
+ return null;
1969
+ }
1970
+ }
1971
+
1972
+ // Whether the place has the `unstick` hook (v1.39). Read behind a catch like
1973
+ // everything else of the place's: a hooks object may be anything.
1974
+ function hasUnstick(h) {
1975
+ try {
1976
+ return typeof h.hooks.unstick === 'function';
1977
+ } catch {
1978
+ return false;
1979
+ }
1980
+ }
1981
+
1982
+ // v1.39: where the place itself would put a player stuck where this one is
1983
+ // (its `unstick` hook, asked with the body's own position), as `{ at,
1984
+ // facing, to }`, or null for the arrival.
1985
+ //
1986
+ // The invariant: nothing the place returns or throws can stop a tap from
1987
+ // landing somewhere valid and answering. So the whole of the place's part --
1988
+ // the call, and every read of what it returned -- is inside one catch, and
1989
+ // what leaves it is either null or a spot made here of plain numbers and a
1990
+ // plain string, which nothing after it can make throw. Null is: no hook; a
1991
+ // hook that throws, or answers null; an answer whose fields cannot be read
1992
+ // (a getter that throws); a promise or any other thenable -- the hook is
1993
+ // synchronous (`answersLater`: a native promise is silenced so that its
1994
+ // rejection is not left unhandled to end the session's process, and nothing
1995
+ // else's `then` is ever called); and an answer that is
1996
+ // not a spot: `x` and `z` finite and inside the world box, `y` (default standing
1997
+ // height when proved clear and no higher, else 1.2, as an arrival's; v1.48)
1998
+ // and `facing` (degrees; default: as the body faces) finite where given.
1999
+ // `to` is the place's name for the spot, a string of up to 40 characters, or none.
2000
+ function unstickSpot(h, playerId) {
2001
+ const body = h.sim?.players.get(playerId);
2002
+ if (!body || !hasUnstick(h)) {
2003
+ return null;
2004
+ }
2005
+ try {
2006
+ const answer = h.hooks.unstick(h.ctx, playerId, { x: body.at.x, y: body.at.y, z: body.at.z });
2007
+ if (answer === null || answer === undefined) {
2008
+ return null;
2009
+ }
2010
+ if (answersLater(answer)) {
2011
+ console.warn('[hub] unstick hook: it must answer at once, not with a promise; the arrival is used');
2012
+ return null;
2013
+ }
2014
+ if (typeof answer !== 'object') {
2015
+ console.warn('[hub] unstick hook: not a spot ({ x, z } inside the world box); the arrival is used');
2016
+ return null;
2017
+ }
2018
+ // Each field read once, here, into a value of this function's own.
2019
+ const x = answer.x;
2020
+ const z = answer.z;
2021
+ const givenY = answer.y;
2022
+ const y = givenY === undefined && [x, z].every(Number.isFinite) ? standingY(h, { x, y: 1.2, z }) : givenY;
2023
+ const facing = answer.facing;
2024
+ const name = answer.to;
2025
+ const B = Actors.BOUNDS;
2026
+ if (
2027
+ ![x, y, z].every((v) => typeof v === 'number' && Number.isFinite(v)) || Math.abs(x) > B.xz || Math.abs(z) > B.xz || y < B.low || y > B.high ||
2028
+ (facing !== undefined && !(typeof facing === 'number' && Number.isFinite(facing)))
2029
+ ) {
2030
+ console.warn('[hub] unstick hook: not a spot ({ x, z } inside the world box); the arrival is used');
2031
+ return null;
2032
+ }
2033
+ const to = typeof name === 'string' && name.trim() ? name.trim().slice(0, WHERE_TEXT_MAX) : null;
2034
+ return { at: { x, y, z }, facing: facing === undefined ? undefined : facing * DEG, to };
2035
+ } catch (err) {
2036
+ try {
2037
+ console.warn(`[hub] unstick hook failed: ${err?.message ?? err}`);
2038
+ } catch {
2039
+ console.warn('[hub] unstick hook failed');
2040
+ }
2041
+ return null;
2042
+ }
2043
+ }
2044
+
2045
+ // Whether this player may be moved by "Stuck?" at all: in a town of a deck
2046
+ // with `hub.stuck`, here, arrived, and their visit not ended.
2047
+ function mayUnstick(h, playerId) {
2048
+ const entry = playerId ? h.players.get(playerId) : null;
2049
+ return stuckHere(h) && Boolean(h.sim?.players.has(playerId)) && Boolean(entry?.arrived) && !entry.ended;
2050
+ }
2051
+
2052
+ // v1.39: what a tap would do for this player now, asked by a client about to
2053
+ // show the chip (`{ k: 'hub-unstick', ask: true }`) so its words can say where
2054
+ // the tap goes. Only a place with the `unstick` hook is asked, and answers
2055
+ // (`hub-unstick-to`): once a second, to a player who may be moved and is not
2056
+ // held. Nobody is moved by it.
2057
+ function unstickAsk(h, player) {
2058
+ const playerId = player?.playerId;
2059
+ const now = Date.now();
2060
+ const last = (h.unstuckAskAt ??= new Map());
2061
+ if (!hasUnstick(h) || !mayUnstick(h, playerId) || h.held.has(playerId) || now - (last.get(playerId) ?? -Infinity) < JUMP_EVERY_MS) {
2062
+ return;
2063
+ }
2064
+ last.set(playerId, now);
2065
+ const spot = unstickSpot(h, playerId);
2066
+ h.session?.send(playerId, { k: 'hub-unstick-to', spot: Boolean(spot), to: spot ? spot.to : arrivalName(h) });
2067
+ }
2068
+
2069
+ // A player who asked to be moved (the chrome's "Stuck?" chip and Doors row):
2070
+ // to the spot the place picks for them (v1.39, its `unstick` hook), else to
2071
+ // the arrival by the fall rule's own placement (`placeGroup`), for that one
2072
+ // player. Never in a game, never a held player or one who has not arrived or
2073
+ // has ended, once in 5 s, and counted as a jump (so not within a second of
2074
+ // one). A sitter gets up first, as for any jump.
2075
+ function unstick(h, player) {
2076
+ const playerId = player?.playerId;
2077
+ const now = Date.now();
2078
+ const last = (h.unstuckAt ??= new Map());
2079
+ if (
2080
+ !mayUnstick(h, playerId) ||
2081
+ now - (last.get(playerId) ?? -Infinity) < UNSTICK_EVERY_MS ||
2082
+ now - (h.jumpAt.get(playerId) ?? 0) < JUMP_EVERY_MS
2083
+ ) {
2084
+ return;
2085
+ }
2086
+ Idle.stand(h, playerId);
2087
+ if (h.held.has(playerId)) {
2088
+ return;
2089
+ }
2090
+ // The place is asked before anything is spent, and cannot stop what
2091
+ // follows (`unstickSpot`): from here the player is moved and answered.
2092
+ const hooked = hasUnstick(h);
2093
+ const spot = hooked ? unstickSpot(h, playerId) : null;
2094
+ last.set(playerId, now);
2095
+ h.jumpAt.set(playerId, now);
2096
+ if (spot) {
2097
+ placeAt(h, playerId, spot.at, spot.facing);
2098
+ } else {
2099
+ placeGroup(h, [playerId]);
2100
+ }
2101
+ settle(h, playerId);
2102
+ h.session?.send(playerId, {
2103
+ k: 'hub-jumped',
2104
+ facing: h.sim.players.get(playerId)?.facing ?? 0,
2105
+ // v1.39, only from a place with the hook: where the player was put.
2106
+ ...(hooked ? { stuck: { spot: Boolean(spot), to: spot ? spot.to : arrivalName(h) } } : {}),
2107
+ });
2108
+ }
2109
+
1169
2110
  // A spot in front of a door, for a jump to a door with no pad.
1170
2111
  function frontOf(door) {
1171
2112
  const t = door.t;
1172
2113
  return doorPoint({ x: t.x, z: t.z, rotationY: t.rotationY ?? 0 }, (Math.random() - 0.5) * JUMP_SPREAD, JUMP_OUT);
1173
2114
  }
1174
2115
 
2116
+ // What `ballot.js` uses of this layer (v1.68): names and avatars are the
2117
+ // kit's own, never the deck's; a player not in the session is no face.
2118
+ function ballotDeps(h) {
2119
+ return {
2120
+ blockedPairs: () => blockedPairs(h),
2121
+ namesOf: (ids) => namesOf(h, ids),
2122
+ usernameOf: (playerId) => (h.sim?.players.has(playerId) ? h.session?.players.find((p) => p.playerId === playerId)?.username ?? null : null),
2123
+ avatarOf: (playerId) => (h.players.get(playerId)?.hello ? h.players.get(playerId).avatar : null),
2124
+ };
2125
+ }
2126
+
1175
2127
  // What `say.js` uses of this layer. A deck whose manifest sets `cues` (v1.23)
1176
2128
  // hands it more; any other hands it exactly what it did.
1177
2129
  function sayDeps(h) {
@@ -1191,7 +2143,7 @@ function partyDeps(h) {
1191
2143
  placeAt(state, playerId, at, facing);
1192
2144
  settle(state, playerId);
1193
2145
  };
1194
- return { h, blockedPairs, usernameOf, placeAt: placeAndSettle, stand: Idle.stand, jumpDoors, front: frontOf };
2146
+ return { h, blockedPairs, usernameOf, standingY, placeAt: placeAndSettle, stand: Idle.stand, jumpDoors, front: frontOf };
1195
2147
  }
1196
2148
 
1197
2149
  // Where the players a client asks about are (the chrome's People list and its
@@ -1368,6 +2320,17 @@ function deckDoorPlace(h, props, deck) {
1368
2320
  };
1369
2321
  }
1370
2322
 
2323
+ // All outgoing travel paths retire the lease after sending the command.
2324
+ function sendGo(h, playerId, msg) {
2325
+ if (h.session?.send) {
2326
+ h.session.send(playerId, msg);
2327
+ Shot.stopHolding(h, playerId);
2328
+ // An explicit kit trip ends the visit rather than retaining it for a drop.
2329
+ h.resumeDeparting?.add(playerId);
2330
+ h.resumePending?.delete(playerId);
2331
+ }
2332
+ }
2333
+
1371
2334
  // Send players through one of this place's doors (contract §4), into a new
1372
2335
  // instance or, with `instance`, one this place sent players to before (a late
1373
2336
  // join). In dev the destination is a named session whose key names the place;
@@ -1417,7 +2380,7 @@ function go(h, door, playerIds, { instance } = {}) {
1417
2380
  typeof instance === 'string' && instance.startsWith(`${prefix}hub.${to}.`) ? instance : prefix + Place.devKey(to);
1418
2381
  tellWent(h, playerIds, door);
1419
2382
  for (const playerId of playerIds) {
1420
- h.session?.send(playerId, {
2383
+ sendGo(h, playerId, {
1421
2384
  k: 'hub-go',
1422
2385
  door,
1423
2386
  key,
@@ -1459,7 +2422,7 @@ function goLayer(h, door, playerIds) {
1459
2422
  return null;
1460
2423
  }
1461
2424
  for (const playerId of going) {
1462
- h.session?.send(playerId, {
2425
+ sendGo(h, playerId, {
1463
2426
  k: 'hub-go',
1464
2427
  door,
1465
2428
  key: null,
@@ -1492,7 +2455,7 @@ function goClassic(h, hub, door, playerIds) {
1492
2455
  return null;
1493
2456
  }
1494
2457
  for (const playerId of going) {
1495
- h.session?.send(playerId, {
2458
+ sendGo(h, playerId, {
1496
2459
  k: 'hub-go',
1497
2460
  door,
1498
2461
  classic: true,
@@ -1594,6 +2557,7 @@ function doorShut(h, player, data) {
1594
2557
  if (!playerId || !found) {
1595
2558
  return;
1596
2559
  }
2560
+ h.resumeDeparting?.delete(playerId);
1597
2561
  unshut(h, playerId);
1598
2562
  if (h.padDoors.has(found.id) && !h.padDoors.get(found.id).has(playerId)) {
1599
2563
  // Already stepped off while the trip was failing.
@@ -1676,7 +2640,7 @@ function padFired(h, door, pad, users, fired) {
1676
2640
  for (const userId of group) {
1677
2641
  const playerId = users.get(userId) ?? here.get(userId);
1678
2642
  if (playerId) {
1679
- h.session?.send(playerId, {
2643
+ sendGo(h, playerId, {
1680
2644
  k: 'hub-go',
1681
2645
  door,
1682
2646
  pad: pad.padId,
@@ -1711,7 +2675,14 @@ function readResults(h) {
1711
2675
  continue;
1712
2676
  }
1713
2677
  entry.read = 'reading';
1714
- users.set(userId, { playerId, avatarRev: entry.avatarRev, wearRev: h.wearRev.get(playerId) ?? 0, startedAt: Date.now() });
2678
+ users.set(userId, {
2679
+ playerId,
2680
+ avatarRev: entry.avatarRev,
2681
+ colorRev: entry.colorRev,
2682
+ wearRev: h.wearRev.get(playerId) ?? 0,
2683
+ earnedRev: h.earnedRev.get(playerId) ?? 0,
2684
+ startedAt: Date.now(),
2685
+ });
1715
2686
  }
1716
2687
  if (users.size) {
1717
2688
  hub
@@ -1732,34 +2703,66 @@ function readResults(h) {
1732
2703
  });
1733
2704
  }
1734
2705
  const now = Date.now();
1735
- if (now - h.boardsAt < BOARD_EVERY_MS) {
2706
+ if (h.boardsReading || now - h.boardsAt < BOARD_EVERY_MS) {
1736
2707
  return;
1737
2708
  }
1738
2709
  // A cabinet's board carries its pictures (v1.7), and a read answers in one
1739
2710
  // frame of the host's channel: cabinets are read apart from the doors, a
1740
- // few at a time. A place with none makes the one read it always did.
2711
+ // few at a time.
1741
2712
  const cabinets = Cabinets.cabinetDoorIds(h);
1742
2713
  const all = doors(h).map((d) => d.id);
1743
- const doorIds = all.filter((id) => !cabinets.has(id)).slice(0, MAX_BOARD_DOORS);
1744
- const batches = doorIds.length ? [doorIds] : [];
1745
- const cabinetIds = all.filter((id) => cabinets.has(id)).slice(0, MAX_BOARD_DOORS);
2714
+ const doorIds = all.filter((id) => !cabinets.has(id));
2715
+ const batches = [];
2716
+ for (let i = 0; i < doorIds.length; i += BOARD_DOORS_PER_READ) {
2717
+ batches.push(doorIds.slice(i, i + BOARD_DOORS_PER_READ));
2718
+ }
2719
+ const cabinetIds = all.filter((id) => cabinets.has(id));
1746
2720
  for (let i = 0; i < cabinetIds.length; i += CABINET_BOARDS_PER_READ) {
1747
2721
  batches.push(cabinetIds.slice(i, i + CABINET_BOARDS_PER_READ));
1748
2722
  }
1749
2723
  if (batches.length) {
1750
2724
  h.boardsAt = now;
1751
- Promise.all(batches.map((ids) => hub.readResults({ doorIds: ids })))
1752
- .then((reads) => {
1753
- h.boards = new Map(reads.flatMap((read) => Object.entries(read.boards ?? {})));
1754
- // Doors to other decks take their title and group from the boards,
1755
- // and a cabinet its card.
1756
- Cabinets.refresh(h, doors(h));
1757
- })
1758
- .catch((err) => refused(h, 'boards', err));
2725
+ h.boardsReading = true;
2726
+ readBoards(h, hub, batches)
2727
+ .catch((err) => refused(h, 'boards', err))
2728
+ .finally(() => {
2729
+ h.boardsReading = false;
2730
+ });
2731
+ }
2732
+ }
2733
+
2734
+ // Storage requests share a small in-flight budget with other hub ops. Read
2735
+ // one batch at a time, keeping the previous boards of a batch that fails.
2736
+ async function readBoards(h, hub, batches) {
2737
+ const boards = new Map(h.boards);
2738
+ for (const ids of batches) {
2739
+ try {
2740
+ const read = await hub.readResults({ doorIds: ids });
2741
+ const rows = Object.entries(read.boards ?? {});
2742
+ for (const id of ids) {
2743
+ boards.delete(id);
2744
+ }
2745
+ for (const [id, board] of rows) {
2746
+ boards.set(id, board);
2747
+ }
2748
+ h.boards = boards;
2749
+ } catch (err) {
2750
+ refused(h, 'boards', err);
2751
+ }
2752
+ }
2753
+ const listed = new Set(doors(h).map((d) => d.id));
2754
+ for (const id of boards.keys()) {
2755
+ if (!listed.has(id)) {
2756
+ boards.delete(id);
2757
+ }
1759
2758
  }
2759
+ h.boards = boards;
2760
+ // Doors to other decks take their title and group from the boards,
2761
+ // and a cabinet its card, even when another batch failed.
2762
+ Cabinets.refresh(h, doors(h));
1760
2763
  }
1761
2764
 
1762
- function applyRead(h, { playerId, avatarRev, wearRev, startedAt }, read) {
2765
+ function applyRead(h, { playerId, avatarRev, colorRev, wearRev, earnedRev, startedAt }, read) {
1763
2766
  const entry = h.players.get(playerId);
1764
2767
  if (!entry || !read) {
1765
2768
  return;
@@ -1768,10 +2771,19 @@ function applyRead(h, { playerId, avatarRev, wearRev, startedAt }, read) {
1768
2771
  History.take(h, playerId, read, startedAt);
1769
2772
  // The wearable likewise, unless the game put one on since (v1.4).
1770
2773
  Wear.applyRead(h, playerId, wearRev, read);
2774
+ // The earned item likewise, unless an unlock or choice was made since (v1.53).
2775
+ Earned.applyRead(h, playerId, earnedRev, read);
1771
2776
  // The platform avatar, unless the client chose another since the read began.
1772
2777
  if (Number.isInteger(read.avatar) && read.avatar >= 0 && read.avatar < AVATARS && entry.avatarRev === avatarRev) {
2778
+ if (entry.avatar !== read.avatar) {
2779
+ // A colour queued for the previous character cannot follow a new body.
2780
+ entry.color = cleanAvatarColor(read.avatarColor);
2781
+ }
1773
2782
  entry.avatar = read.avatar;
1774
2783
  }
2784
+ if (entry.colorRev === colorRev) {
2785
+ entry.color = cleanAvatarColor(read.avatarColor);
2786
+ }
1775
2787
  const row = entry.fromDeckId
1776
2788
  ? (read.recent ?? []).find((r) => r.deckId === entry.fromDeckId && Date.now() - Date.parse(r.at) < RESULT_FRESH_MS)
1777
2789
  : null;
@@ -1803,6 +2815,30 @@ function refused(h, op, err) {
1803
2815
  }
1804
2816
  }
1805
2817
 
2818
+ // A place's next-visit line (v1.52), latched for its player alone. Send now
2819
+ // so a subsequent hub.go or hub.end cannot overtake the line.
2820
+ function leaving(h, playerId, text) {
2821
+ if (typeof playerId !== 'string' || !(h.players.has(playerId) || h.sim?.players.has(playerId))) {
2822
+ refused(h, 'leaving', { code: 'player', message: 'a player here is required' });
2823
+ return false;
2824
+ }
2825
+ if (text !== null && typeof text !== 'string') {
2826
+ refused(h, 'leaving', { code: 'text', message: 'text must be a string or null' });
2827
+ return false;
2828
+ }
2829
+ const line = text === null ? null : text.trim().slice(0, HUD_LIMITS.text) || null;
2830
+ if ((h.leaving.get(playerId) ?? null) === line) {
2831
+ return true;
2832
+ }
2833
+ if (line === null) {
2834
+ h.leaving.delete(playerId);
2835
+ } else {
2836
+ h.leaving.set(playerId, line);
2837
+ }
2838
+ h.session?.send(playerId, { k: 'hub-leaving', text: line });
2839
+ return true;
2840
+ }
2841
+
1806
2842
  // Per-player HUD overrides go to their player alone, when they change. Where
1807
2843
  // a block hides players, each player is also sent the shared HUD as they may
1808
2844
  // read it, when that names someone the shared one leaves out.
@@ -1945,16 +2981,81 @@ function labelsOf(h) {
1945
2981
  // Every helloed player's avatar, for everyone: all but the players a block
1946
2982
  // hides from someone here, whose avatars go to each player who may see them
1947
2983
  // alone (`sendAvatarOverrides`).
2984
+ //
2985
+ // `hubAv` only ever carries one of the first four (v1.51): a client from
2986
+ // before the twelve has no blueprint for another and would not draw the
2987
+ // player at all, so one who wears 4-15 is listed there as `avatar % 4`, the
2988
+ // stand-in a v1.51 client draws for an index past its own. Who really wears
2989
+ // what is `hubAv2`, below.
1948
2990
  function avatars(h, hidden) {
1949
2991
  const out = {};
1950
2992
  for (const [playerId, entry] of h.players) {
1951
2993
  if (entry.hello && !hidden?.has(playerId)) {
2994
+ out[playerId] = standIn(entry.avatar);
2995
+ }
2996
+ }
2997
+ return out;
2998
+ }
2999
+
3000
+ function standIn(avatar) {
3001
+ return avatar < OLD_AVATARS ? avatar : avatar % OLD_AVATARS;
3002
+ }
3003
+
3004
+ // `hubAv2` (v1.51): the avatar of each player who wears one past the first
3005
+ // four, by `hubAv`'s rules of who is listed. A client that knows it draws
3006
+ // that; one from before ignores it and draws `hubAv`'s stand-in.
3007
+ function avatars2(h, hidden) {
3008
+ const out = {};
3009
+ for (const [playerId, entry] of h.players) {
3010
+ if (entry.hello && !hidden?.has(playerId) && entry.avatar >= OLD_AVATARS) {
1952
3011
  out[playerId] = entry.avatar;
1953
3012
  }
1954
3013
  }
1955
3014
  return out;
1956
3015
  }
1957
3016
 
3017
+ // In the snapshot only while someone wears one; in deltas from the first one
3018
+ // on, and `{}` once when the last is gone, so a client that had the block
3019
+ // hears that it is empty. A place where nobody ever wears one never sends the
3020
+ // key: its bytes are what they were before v1.51.
3021
+ function avatars2ForJoin(h) {
3022
+ const real = avatars2(h, blockedPairs(h));
3023
+ return Object.keys(real).length ? { hubAv2: real } : {};
3024
+ }
3025
+
3026
+ function latchAvatars2(h, out) {
3027
+ const real = avatars2(h, blockedPairs(h));
3028
+ if (Object.keys(real).length || h.sent.has('hubAv2')) {
3029
+ latch(h, 'hubAv2', real, out);
3030
+ }
3031
+ }
3032
+
3033
+ function cleanAvatarColor(color) {
3034
+ return Number.isInteger(color) && color >= 0 && color < 16 ? color : 0;
3035
+ }
3036
+
3037
+ function avatarColors(h, hidden) {
3038
+ const out = {};
3039
+ for (const [playerId, entry] of h.players) {
3040
+ if (entry.hello && !hidden?.has(playerId) && entry.color > 0) {
3041
+ out[playerId] = entry.color;
3042
+ }
3043
+ }
3044
+ return out;
3045
+ }
3046
+
3047
+ function avatarColorsForJoin(h) {
3048
+ const colors = avatarColors(h, blockedPairs(h));
3049
+ return Object.keys(colors).length ? { hubAvC: colors } : {};
3050
+ }
3051
+
3052
+ function latchAvatarColors(h, out) {
3053
+ const colors = avatarColors(h, blockedPairs(h));
3054
+ if (Object.keys(colors).length || h.sent.has('hubAvC')) {
3055
+ latch(h, 'hubAvC', colors, out);
3056
+ }
3057
+ }
3058
+
1958
3059
  // Who a block hides from whom (`blocks.js`), asked of the host once a tick
1959
3060
  // and again when the roster changes.
1960
3061
  function blockedPairs(h) {
@@ -1972,16 +3073,30 @@ function sendAvatarOverrides(h) {
1972
3073
  const hidden = blockedPairs(h);
1973
3074
  for (const playerId of h.sim.players.keys()) {
1974
3075
  const out = {};
3076
+ // v1.51: as `hubAv` and `hubAv2` are, the stand-in for everyone and the
3077
+ // avatar really worn beside it, the second only when there is one.
3078
+ const real = {};
3079
+ const colors = {};
1975
3080
  for (const shrouded of hidden?.keys() ?? []) {
1976
3081
  const entry = h.players.get(shrouded);
1977
3082
  if (entry?.hello && !hidden.get(playerId)?.has(shrouded)) {
1978
- out[shrouded] = entry.avatar;
3083
+ out[shrouded] = standIn(entry.avatar);
3084
+ if (entry.color > 0) {
3085
+ colors[shrouded] = entry.color;
3086
+ }
3087
+ if (entry.avatar >= OLD_AVATARS) {
3088
+ real[shrouded] = entry.avatar;
3089
+ }
1979
3090
  }
1980
3091
  }
1981
- const json = JSON.stringify(out);
3092
+ // The message is the whole of what this player is told here: one without
3093
+ // `hubAv2` says nobody in it wears one of the twelve (any more).
3094
+ const some = Object.keys(real).length > 0;
3095
+ const colored = Object.keys(colors).length > 0;
3096
+ const json = colored ? JSON.stringify([out, real, colors]) : some ? JSON.stringify([out, real]) : JSON.stringify(out);
1982
3097
  if ((h.sentAvMe.get(playerId) ?? '{}') !== json) {
1983
3098
  h.sentAvMe.set(playerId, json);
1984
- h.session?.send(playerId, { k: 'hub-av', hubAv: out });
3099
+ h.session?.send(playerId, { k: 'hub-av', hubAv: out, ...(some ? { hubAv2: real } : {}), ...(colored ? { hubAvC: colors } : {}) });
1985
3100
  }
1986
3101
  }
1987
3102
  }
@@ -2010,6 +3125,31 @@ function latchWearing(h, out) {
2010
3125
  }
2011
3126
  }
2012
3127
 
3128
+ // What `hub.unlock` and `hub.wearEarned` (v1.53) are handed.
3129
+ function earnedDeps(h, playerId, op) {
3130
+ return {
3131
+ platform: platformHub(h),
3132
+ userId: userIdOf(h, playerId),
3133
+ declared: h.unlocks,
3134
+ deckId: h.deckId,
3135
+ refused: (err) => refused(h, op, err),
3136
+ };
3137
+ }
3138
+
3139
+ // `hubEarned` (v1.53) as `hubWear` goes: in the snapshot only while someone
3140
+ // shows an earned item, in deltas from the first one on.
3141
+ function earnedForJoin(h) {
3142
+ const earned = Earned.earnedForAll(h, blockedPairs(h));
3143
+ return Object.keys(earned).length ? { hubEarned: earned } : {};
3144
+ }
3145
+
3146
+ function latchEarned(h, out) {
3147
+ const earned = Earned.earnedForAll(h, blockedPairs(h));
3148
+ if (Object.keys(earned).length || h.sent.has('hubEarned')) {
3149
+ latch(h, 'hubEarned', earned, out);
3150
+ }
3151
+ }
3152
+
2013
3153
  // `hubTry` (v1.28) the same way: in the snapshot only while a try-on is
2014
3154
  // shown, in deltas from the first one on, `{}` once when the last is gone.
2015
3155
  function tryingForJoin(h) {
@@ -2025,6 +3165,26 @@ function latchTrying(h, out) {
2025
3165
  }
2026
3166
 
2027
3167
  function latch(h, field, value, out) {
3168
+ if (h.cells && ['labels', 'tints', 'marks'].includes(field)) {
3169
+ const previous = h.sentMaps.get(field) ?? {};
3170
+ const next = Object.fromEntries(Object.entries(value).map(([id, v]) => [id, JSON.stringify(v)]));
3171
+ const delta = Object.create(null);
3172
+ for (const [id, json] of Object.entries(next)) {
3173
+ if (previous[id] !== json) {
3174
+ delta[id] = value[id];
3175
+ }
3176
+ }
3177
+ for (const id of Object.keys(previous)) {
3178
+ if (!Object.hasOwn(next, id)) {
3179
+ delta[id] = null;
3180
+ }
3181
+ }
3182
+ h.sentMaps.set(field, next);
3183
+ if (Object.keys(delta).length) {
3184
+ out[`${field}D`] = delta;
3185
+ }
3186
+ return;
3187
+ }
2028
3188
  const json = JSON.stringify(value);
2029
3189
  if (h.sent.get(field) !== json) {
2030
3190
  h.sent.set(field, json);
@@ -2032,6 +3192,50 @@ function latch(h, field, value, out) {
2032
3192
  }
2033
3193
  }
2034
3194
 
3195
+ // Both hooks share one body-cell and camera-neighbour lookup per tick.
3196
+ function playerCells(h, sim) {
3197
+ if (h.cellTick === sim.timeMs && h.cellViews) {
3198
+ return h.cellViews;
3199
+ }
3200
+ h.cellTick = sim.timeMs;
3201
+ h.cellViews = new Map();
3202
+ for (const [id, player] of sim.players) {
3203
+ const at = player.at;
3204
+ const cell = Cells.cellAt(h.cells, at.x, at.z, h.playerCells.get(id));
3205
+ h.playerCells.set(id, cell);
3206
+ h.cellViews.set(id, { cell, visible: Cells.visibleCells(h.cells, at.x, at.z) });
3207
+ }
3208
+ return h.cellViews;
3209
+ }
3210
+
3211
+ function cellPlayers(h, sim, known, hidden) {
3212
+ const views = playerCells(h, sim);
3213
+ const userIds = new Map([...sim.players.keys()].map((id) => [id, userIdOf(h, id)]));
3214
+ const sees = new Map();
3215
+ const now = Date.now();
3216
+ for (const [viewer, view] of views) {
3217
+ const cached = h.friendsCache?.get(viewer);
3218
+ const entry = cached && now - cached.at < cached.ttl ? cached : null;
3219
+ const friends = new Set([
3220
+ ...(entry?.ids ?? []), ...(entry?.follows ?? []), ...(entry?.followedBy ?? []),
3221
+ ]);
3222
+ const at = sim.players.get(viewer).at;
3223
+ const scored = [];
3224
+ for (const [id, candidate] of views) {
3225
+ if (id === viewer || hidden?.(viewer, id) || (view.visible !== null && candidate.cell !== null && !view.visible.has(candidate.cell))) {
3226
+ continue;
3227
+ }
3228
+ const other = sim.players.get(id).at;
3229
+ const d = (at.x - other.x) ** 2 + (at.y - other.y) ** 2 + (at.z - other.z) ** 2;
3230
+ scored.push({ id, friend: friends.has(userIds.get(id)), d: known.get(viewer)?.has(id) ? d * KEEP_NEARER ** 2 : d });
3231
+ }
3232
+ scored.sort((a, b) => Number(b.friend) - Number(a.friend) || a.d - b.d);
3233
+ const cap = Math.min(h.caps.get(viewer) ?? h.place.nearestPlayers, h.place.nearestPlayers);
3234
+ sees.set(viewer, new Set(scored.slice(0, cap).map(({ id }) => id)));
3235
+ }
3236
+ return sees;
3237
+ }
3238
+
2035
3239
  // A scene actor of the place, or a copy the game spawned.
2036
3240
  function isSceneActor(h, id) {
2037
3241
  return Actors.isActor(h, id);