@wildshard/engine 0.1.17 → 0.1.19

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 (343) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/budgets/shard-size-baseline.json +10 -4
  3. package/index.html +6 -4
  4. package/lint/engine-sides.json +21 -0
  5. package/lint/host-callback-syntax.mjs +2 -1
  6. package/lint/host-callbacks.mjs +3 -3
  7. package/lint/host-files.mjs +5 -4
  8. package/lint/no-base64.mjs +3 -1
  9. package/lint/ratchet.json +0 -68
  10. package/lint/ratchet.mjs +1 -4
  11. package/lint/shard-imports.mjs +6 -7
  12. package/lint/shard-source.d.mts +9 -0
  13. package/lint/shard-source.mjs +91 -0
  14. package/lint/shardfile-boundaries.mjs +10 -8
  15. package/lint/sim-closure.mjs +6 -3
  16. package/lint/wildshard-plugin.d.ts +4 -0
  17. package/lint/wildshard-plugin.js +22 -23
  18. package/package.json +25 -16
  19. package/scripts/agent-sync.mjs +27 -8
  20. package/scripts/app-build/appCook.ts +8 -2
  21. package/scripts/app-build/catalogue.ts +10 -7
  22. package/scripts/app-build/gen.ts +22 -2
  23. package/scripts/app-build/isolation.d.mts +10 -0
  24. package/scripts/app-build/isolation.mjs +47 -0
  25. package/scripts/app-build/outputProducts.d.mts +3 -0
  26. package/scripts/app-build/outputProducts.mjs +35 -0
  27. package/scripts/app-build/previousDeploy.d.mts +2 -0
  28. package/scripts/app-build/previousDeploy.mjs +10 -1
  29. package/scripts/app-build/serviceWorker.ts +10 -3
  30. package/scripts/app-build/splitOutput.mjs +4 -2
  31. package/scripts/app-build/standaloneOutput.d.mts +1 -1
  32. package/scripts/app-build/standaloneOutput.mjs +5 -3
  33. package/scripts/app-build/titlePreloads.d.mts +8 -0
  34. package/scripts/app-build/titlePreloads.mjs +69 -0
  35. package/scripts/app-build/worldMapAtlas.ts +10 -6
  36. package/scripts/app-build-pipeline.mjs +34 -3
  37. package/scripts/built-product.mjs +1 -1
  38. package/scripts/cell-mem-bench.mjs +81 -23
  39. package/scripts/check-custom-sections-zero.mjs +1 -1
  40. package/scripts/check-devserver.mjs +3 -1
  41. package/scripts/check-models.mjs +2 -0
  42. package/scripts/check-paths.allow.json +0 -115
  43. package/scripts/check-paths.mjs +2 -2
  44. package/scripts/check-platform-ratchets.mjs +2 -3
  45. package/scripts/chromium-keychain-check.mjs +4 -2
  46. package/scripts/chromium-keychain.d.mts +1 -1
  47. package/scripts/chromium-keychain.mjs +3 -1
  48. package/scripts/ci-static.sh +1 -1
  49. package/scripts/committed-fast-checks.mjs +0 -2
  50. package/scripts/content-sw-proof.mjs +2 -1
  51. package/scripts/cook-worker.mjs +9 -3
  52. package/scripts/cook.mjs +20 -3
  53. package/scripts/devices.d.mts +4 -0
  54. package/scripts/devices.mjs +39 -0
  55. package/scripts/devserver-client.d.mts +4 -2
  56. package/scripts/devserver-client.mjs +25 -8
  57. package/scripts/docs-inputs-proof.mjs +6 -6
  58. package/scripts/doctor-proof.mjs +1 -1
  59. package/scripts/e2e-faults.mjs +159 -0
  60. package/scripts/e7-voice-staging-proof.mjs +1 -1
  61. package/scripts/gate-related-tests.mjs +1 -1
  62. package/scripts/git-source-view.mjs +1 -1
  63. package/scripts/goldens/capture.mjs +17 -5
  64. package/scripts/grid-crossing-nightly.mjs +59 -0
  65. package/scripts/grid-crossing-qa.mjs +44 -0
  66. package/scripts/grid-crossing-ratchet.d.mts +6 -0
  67. package/scripts/grid-crossing-ratchet.mjs +52 -0
  68. package/scripts/grid-crossing-report.mjs +122 -0
  69. package/scripts/grid-crossing-stages.mjs +47 -0
  70. package/scripts/grid-crossing-tour.mjs +277 -0
  71. package/scripts/grid-crossing-walk-proof.mjs +136 -18
  72. package/scripts/host-ruler/roots.mjs +2 -2
  73. package/scripts/host-ruler.d.mts +91 -0
  74. package/scripts/host-ruler.mjs +565 -0
  75. package/scripts/live-prepush.py +3 -5
  76. package/scripts/loading-flow/benchmax.mjs +3 -1
  77. package/scripts/look-loop/test_look_loop.py +1 -38
  78. package/scripts/memory-proof.mjs +213 -0
  79. package/scripts/mmo-bots.mjs +8 -2
  80. package/scripts/net-lag-proof.mjs +219 -0
  81. package/scripts/night-market-kit-budget.mjs +2 -2
  82. package/scripts/offline-proof-rules.d.mts +5 -3
  83. package/scripts/offline-proof-rules.mjs +34 -7
  84. package/scripts/offline-proof.mjs +88 -18
  85. package/scripts/{shard-platform-output.mjs → output-reader.mjs} +1 -1
  86. package/scripts/page-release/content.d.mts +9 -1
  87. package/scripts/page-release/content.mjs +131 -17
  88. package/scripts/page-release/flow.mjs +36 -10
  89. package/scripts/page-release/stamp-content.mjs +24 -0
  90. package/scripts/page-release.mjs +28 -6
  91. package/scripts/page-size.mjs +2 -1
  92. package/scripts/pin-packs.ts +1 -1
  93. package/scripts/pins.ts +4 -4
  94. package/scripts/precommit-checks.mjs +1 -7
  95. package/scripts/precommit-jobs.mjs +0 -1
  96. package/scripts/precommit-source.py +1 -9
  97. package/scripts/program-discovery.mjs +1 -1
  98. package/scripts/ring-cook.mjs +2 -1
  99. package/scripts/ring-step.ts +1 -1
  100. package/scripts/script-scenario-metrics.mjs +1 -1
  101. package/scripts/shard-output-content.d.mts +1 -1
  102. package/scripts/shard-output-content.mjs +2 -2
  103. package/scripts/shard-outputs.mjs +1 -1
  104. package/scripts/shard-public.mjs +1 -1
  105. package/scripts/shard-wire-meter.mjs +24 -9
  106. package/scripts/side-parity.mjs +4 -2
  107. package/scripts/standalone-smoke.mjs +8 -3
  108. package/scripts/tier-textures-proof.mjs +101 -0
  109. package/scripts/tier-textures.mjs +78 -0
  110. package/scripts/tile-bake-report.mjs +1 -1
  111. package/scripts/tile-bakes.mjs +1 -1
  112. package/scripts/title-assets.generated.json +2 -0
  113. package/scripts/tsconfig.json +1 -2
  114. package/scripts/vendor/basisu/LICENSE +201 -0
  115. package/scripts/vendor/basisu/basis_encoder.cjs +2 -0
  116. package/scripts/vendor/basisu/basis_encoder.wasm +0 -0
  117. package/scripts/vitest-push-guards.config.ts +1 -1
  118. package/scripts/vps/harden-apply.sh +4 -1
  119. package/scripts/vps/harden-prometheus.sh +176 -0
  120. package/scripts/vps/harden.sh +16 -0
  121. package/scripts/vps/rebuild.sh +18 -0
  122. package/scripts/vps/wildshard-config +84 -24
  123. package/scripts/worker-client-play.mjs +7 -2
  124. package/scripts/worker-client-proof.mjs +1 -1
  125. package/scripts/worker-client-slug.mjs +44 -0
  126. package/scripts/worktree-reap.mjs +5 -5
  127. package/src/.oxlintrc.json +3 -182
  128. package/src/client/app/entry.ts +47 -12
  129. package/src/client/engine/boot/bootCache.ts +2 -2
  130. package/src/client/engine/boot/bootTrace.ts +12 -4
  131. package/src/client/engine/boot/browserChunkRecovery.ts +4 -0
  132. package/src/client/engine/boot/clearDownloads.ts +5 -2
  133. package/src/client/engine/boot/contentRead.ts +11 -0
  134. package/src/client/engine/boot/gpuFiles.ts +4 -2
  135. package/src/client/engine/boot/lastEnd.ts +99 -12
  136. package/src/client/engine/boot/parsedPages.ts +127 -58
  137. package/src/client/engine/boot/texturePack.ts +2 -2
  138. package/src/client/engine/build.d.ts +2 -0
  139. package/src/client/engine/core/Game.ts +18 -0
  140. package/src/client/engine/core/bootstrap.ts +4 -1
  141. package/src/client/engine/debug/probe.ts +18 -1
  142. package/src/client/engine/fx/LightPool.ts +41 -1
  143. package/src/client/engine/net/netPlayer.ts +19 -2
  144. package/src/client/engine/net/otherPlayers.ts +55 -8
  145. package/src/client/engine/net/predictor.ts +33 -9
  146. package/src/client/engine/net/redial.ts +29 -6
  147. package/src/client/engine/pwa/cacheNames.ts +58 -1
  148. package/src/client/engine/pwa/sw.js +53 -14
  149. package/src/client/engine/render/dataLook.ts +152 -40
  150. package/src/client/engine/render/families/detail.ts +89 -0
  151. package/src/client/engine/render/families/pbr.ts +7 -1
  152. package/src/client/engine/render/look.ts +6 -0
  153. package/src/client/engine/render/lookLight.ts +103 -11
  154. package/src/client/engine/render/lookRender.ts +105 -0
  155. package/src/client/engine/render/precompile.ts +20 -14
  156. package/src/client/engine/saves/indexed.ts +2 -2
  157. package/src/client/engine/telemetry/browserErrors.ts +28 -4
  158. package/src/client/engine/telemetry/deviceSnapshot.ts +155 -0
  159. package/src/client/engine/telemetry/staleBuildReport.ts +22 -1
  160. package/src/client/engine/ui/debugOptions.ts +1 -1
  161. package/src/client/engine/ui/lookLightOption.ts +10 -6
  162. package/src/client/engine/ui/namePrompt.ts +7 -0
  163. package/src/client/game/boot/audio.generated.ts +114 -216
  164. package/src/client/game/boot/bytes.generated.ts +118 -238
  165. package/src/client/game/boot/placedSpawn.ts +35 -0
  166. package/src/client/game/boot/spawnDownload.ts +25 -6
  167. package/src/client/game/boot/versions.generated.ts +7 -7
  168. package/src/client/game/devScene/hook.ts +291 -0
  169. package/src/client/game/grid/area.ts +38 -0
  170. package/src/client/game/grid/cellLoading.ts +12 -2
  171. package/src/client/game/grid/live.ts +134 -12
  172. package/src/client/game/grid/liveSession.ts +47 -5
  173. package/src/client/game/grid/mapAtlas.ts +18 -4
  174. package/src/client/game/grid/menu.ts +4 -0
  175. package/src/client/game/grid/minimapBlend.ts +15 -5
  176. package/src/client/game/grid/neighbourPanels.ts +10 -1
  177. package/src/client/game/grid/oneWayIn.ts +5 -1
  178. package/src/client/game/grid/placedCards.ts +55 -0
  179. package/src/client/game/grid/placedCells.ts +233 -0
  180. package/src/client/game/grid/placedContent.ts +85 -0
  181. package/src/client/game/grid/prefetch.ts +9 -1
  182. package/src/client/game/grid/productInputs.ts +3 -1
  183. package/src/client/game/grid/productLeases.ts +4 -1
  184. package/src/client/game/grid/products.ts +8 -4
  185. package/src/client/game/grid/regionalRuntime.ts +6 -0
  186. package/src/client/game/grid/regionalWorld.ts +15 -2
  187. package/src/client/game/grid/roadCull.ts +44 -14
  188. package/src/client/game/grid/roadLook.ts +24 -15
  189. package/src/client/game/grid/roadLookPlatform.ts +4 -2
  190. package/src/client/game/grid/roadResources.ts +24 -0
  191. package/src/client/game/grid/roadSign.worker.ts +4 -3
  192. package/src/client/game/grid/roadSignPaint.ts +16 -5
  193. package/src/client/game/grid/roadSignPreparation.ts +4 -3
  194. package/src/client/game/grid/roadSignScale.ts +8 -0
  195. package/src/client/game/grid/roadTileBacking.ts +13 -3
  196. package/src/client/game/grid/roadTileCapture.worker.ts +3 -1
  197. package/src/client/game/grid/roadTileCaptureWorker.ts +2 -1
  198. package/src/client/game/grid/roadTileWrite.worker.ts +4 -2
  199. package/src/client/game/grid/roadTileWriter.ts +2 -1
  200. package/src/client/game/grid/screenReports.ts +39 -0
  201. package/src/client/game/grid/session.ts +29 -4
  202. package/src/client/game/grid/shardfileFar.ts +9 -3
  203. package/src/client/game/grid/softWallLook.ts +25 -8
  204. package/src/client/game/mainMenu.ts +6 -2
  205. package/src/client/game/plugin/context.ts +2 -1
  206. package/src/client/game/plugin/followedMovers.ts +7 -1
  207. package/src/client/game/quest/figures.ts +2 -0
  208. package/src/client/game/session/finish.ts +11 -1
  209. package/src/client/game/shard/titleList.ts +6 -2
  210. package/src/client/game/shardfile/assetCache.ts +4 -4
  211. package/src/client/game/shardfile/client.ts +4 -1
  212. package/src/client/game/shardfile/clientAssets.ts +9 -5
  213. package/src/client/game/shardfile/clientLibrary.ts +1 -1
  214. package/src/client/game/shardfile/clientWater.ts +51 -9
  215. package/src/client/game/shardfile/clientWorker.ts +21 -8
  216. package/src/client/game/shardfile/look.ts +8 -3
  217. package/src/client/game/shardfile/product.ts +34 -7
  218. package/src/client/game/shardfile/productChecks.ts +2 -2
  219. package/src/client/game/shardfile/productCost.ts +2 -2
  220. package/src/client/game/shardfile/readAsset.ts +2 -2
  221. package/src/client/game/shardfile/reflectingWater.ts +73 -0
  222. package/src/client/game/shardfile/seatGrace.ts +9 -0
  223. package/src/client/game/shardfile/skinPlayback.ts +1 -1
  224. package/src/client/game/systems/npc/figureRows.ts +9 -0
  225. package/src/client/game/titleDeck.ts +4 -3
  226. package/src/client/host/online/doctor.ts +2 -0
  227. package/src/client/host/online/linkScreens.ts +30 -4
  228. package/src/client/host/online/shell.ts +14 -0
  229. package/src/client/host/standalone/shell.ts +4 -0
  230. package/src/cook/game/astc6Encode.ts +55 -0
  231. package/src/cook/game/astc6Wasm.ts +176 -0
  232. package/src/cook/game/cookJob.ts +30 -6
  233. package/src/cook/game/cookWorker.ts +38 -11
  234. package/src/cook/game/entryTotals.ts +51 -24
  235. package/src/cook/game/shardCook.ts +67 -9
  236. package/src/cook/game/spawnParts.ts +33 -8
  237. package/src/cook/game/tierTextures.ts +349 -0
  238. package/src/e2e/smoke/game.ts +19 -14
  239. package/src/e2e/smoke/page-globals.d.ts +9 -8
  240. package/src/e2e/smoke/template2.spec.ts +8 -7
  241. package/src/server/engine/ai/bossContenders.ts +27 -3
  242. package/src/server/engine/ai/phases.ts +1 -1
  243. package/src/server/engine/entities/creatureRefill.ts +9 -2
  244. package/src/server/engine/net/ledgerBook.ts +2 -0
  245. package/src/server/engine/net/room.ts +15 -0
  246. package/src/server/engine/sim/respawn.ts +8 -0
  247. package/src/server/game/boss/arenaRoomEntry.ts +5 -1
  248. package/src/server/game/boss/arenaRoomNative.ts +2 -0
  249. package/src/server/game/boss/native.ts +2 -1
  250. package/src/server/game/boss/nativeWake.ts +9 -5
  251. package/src/server/game/boss/openArenaNative.ts +2 -2
  252. package/src/server/game/boss/openArenaRoom.ts +3 -1
  253. package/src/server/game/grid/room.ts +44 -3
  254. package/src/server/game/grid/simulation.ts +23 -0
  255. package/src/server/game/population/mixedRoster.ts +11 -3
  256. package/src/server/game/population/nativeBake.ts +8 -3
  257. package/src/server/game/population/nativeReturns.ts +6 -3
  258. package/src/server/game/population/roster.ts +5 -3
  259. package/src/server/game/quest/eliteDrops.ts +15 -4
  260. package/src/server/game/quest/nativeChapter.ts +1 -1
  261. package/src/server/game/quest/nativeComposition.ts +5 -1
  262. package/src/server/game/riding/nativeTaming.ts +10 -6
  263. package/src/server/game/riding/wildRefill.ts +3 -2
  264. package/src/server/game/shardfile/bossRow.ts +4 -2
  265. package/src/server/game/shardfile/homeKeeper.ts +4 -2
  266. package/src/server/host/bake/headlessWorker.ts +1 -1
  267. package/src/server/host/dedicated/cellHost.ts +98 -16
  268. package/src/server/host/dedicated/cellProtocol.ts +16 -1
  269. package/src/server/host/dedicated/cellWorker.ts +8 -5
  270. package/src/server/host/dedicated/dedicatedRoom.ts +16 -6
  271. package/src/server/host/dedicated/gridCells.ts +15 -6
  272. package/src/server/host/dedicated/loopLag.ts +21 -0
  273. package/src/server/host/dedicated/main.ts +13 -5
  274. package/src/server/host/dedicated/packReader.ts +3 -3
  275. package/src/server/host/dedicated/placementFile.ts +4 -19
  276. package/src/server/host/dedicated/roadRoom.ts +34 -4
  277. package/src/server/host/dedicated/serverMetrics.ts +126 -0
  278. package/src/server/host/dedicated/socketPump.ts +21 -4
  279. package/src/server/host/dedicated/socketTransport.ts +2 -1
  280. package/src/server/host/dedicated/workerTable.ts +15 -4
  281. package/src/server/host/dedicated/world.ts +95 -8
  282. package/src/server/host/headless.ts +1 -1
  283. package/src/server/host/headlessRuntime.ts +1 -1
  284. package/src/server/host/standalone/roadWorld.ts +15 -3
  285. package/src/server/host/standalone/serverHost.ts +4 -1
  286. package/src/server/host/standalone/serverProduct.ts +41 -11
  287. package/src/shared/engine/ai/BossBrain.ts +8 -0
  288. package/src/shared/engine/net/deviceWord.ts +138 -0
  289. package/src/shared/engine/net/socketFrames.ts +7 -4
  290. package/src/shared/game/boss/wake.ts +6 -0
  291. package/src/shared/game/devColliders.ts +47 -0
  292. package/src/shared/game/eliteSystem.ts +8 -0
  293. package/src/shared/game/grid/allocator.ts +3 -0
  294. package/src/shared/game/grid/catalogueSlot.ts +7 -0
  295. package/src/shared/game/grid/placementRows.ts +36 -0
  296. package/src/shared/game/plugin/bossRecord.ts +3 -2
  297. package/src/shared/game/shardfile/ktx2Targets.ts +23 -3
  298. package/src/shared/game/shardfile/outputDescriptor.ts +9 -5
  299. package/src/shared/game/shardfile/packReads.ts +28 -3
  300. package/src/shared/game/shardfile/serverPack.ts +9 -0
  301. package/src/shared/game/systems/looks/trampleField.ts +2 -0
  302. package/src/shared/host/formatJsonSchema.ts +2 -2
  303. package/src/tsconfig.json +1 -27
  304. package/lint/host-reviews.json +0 -14
  305. package/lint/listed-view-code.json +0 -13
  306. package/lint/platform-pending-users.json +0 -2520
  307. package/lint/platform-pending-users.md +0 -18
  308. package/scripts/cell-mem/metrics-preload.mjs +0 -65
  309. package/scripts/check-closed-components.d.mts +0 -7
  310. package/scripts/check-closed-components.mjs +0 -87
  311. package/scripts/g571-hosts.d.mts +0 -3
  312. package/scripts/g571-hosts.mjs +0 -54
  313. package/scripts/host-ruler/register-migrate.mjs +0 -242
  314. package/scripts/listed-view-code.d.mts +0 -7
  315. package/scripts/listed-view-code.mjs +0 -93
  316. package/scripts/look-loop/fit-lut.py +0 -142
  317. package/scripts/look-loop/palette-delta.py +0 -183
  318. package/scripts/look-loop/regions/driftwood-isle.json +0 -25
  319. package/scripts/look-loop/regions/far-reach.json +0 -225
  320. package/scripts/look-loop/regions/open-plot-night-market.json +0 -855
  321. package/scripts/look-loop/regions/pine-hollow.json +0 -22
  322. package/scripts/look-loop/regions/sunscar-dunes.json +0 -281
  323. package/scripts/platform-chargebacks.d.mts +0 -9
  324. package/scripts/platform-chargebacks.mjs +0 -135
  325. package/scripts/shard-component-spans.d.mts +0 -15
  326. package/scripts/shard-component-spans.mjs +0 -18
  327. package/scripts/shard-components.d.mts +0 -16
  328. package/scripts/shard-components.mjs +0 -363
  329. package/scripts/shard-platform-hosts.d.mts +0 -2
  330. package/scripts/shard-platform-hosts.mjs +0 -93
  331. package/scripts/shard-platform-sections.d.mts +0 -2
  332. package/scripts/shard-platform-sections.mjs +0 -9
  333. package/scripts/shard-platform.d.mts +0 -76
  334. package/scripts/shard-platform.mjs +0 -1072
  335. package/src/.oxfmtrc.json +0 -48
  336. package/src/scripts/ask-new.sh +0 -29
  337. package/src/scripts/asks.mjs +0 -142
  338. package/src/scripts/herdr-prompt.sh +0 -34
  339. package/src/scripts/herdr-question-open.sh +0 -67
  340. package/src/scripts/md-wrap.mjs +0 -229
  341. /package/scripts/{shard-platform-format.d.mts → node-format.d.mts} +0 -0
  342. /package/scripts/{shard-platform-format.mjs → node-format.mjs} +0 -0
  343. /package/scripts/{shard-platform-output.d.mts → output-reader.d.mts} +0 -0
@@ -180,7 +180,7 @@ export function installPopulationRoster(host: SimHost, ports: PopulationRosterPo
180
180
 
181
181
  // J109, J108: a room's herds fill again; one player's stay as they fell, and their saves never carry this row
182
182
  const REFILL_STATE = `${ROSTER_STEP}.refill`, room = (): readonly PlayerSim[] => [...host.players.values()];
183
- const refill = new CreatureRefill({ players: room, room: () => BODY_COUNT - list.filter(body => body.actor.alive).length,
183
+ const refill = new CreatureRefill({ players: room, served: () => host.respawn.served, room: () => BODY_COUNT - list.filter(body => body.actor.alive).length,
184
184
  random: () => host.rng.stream('spawn').next(), spawn: ({ kind, variant, herd, x, z, from }, yaw) => {
185
185
  const fallen = list.find(body => body.id === from)?.actor, group = hunt.herds[herd];
186
186
  if (fallen?.alive === false) retire(fallen);
@@ -190,13 +190,14 @@ export function installPopulationRoster(host: SimHost, ports: PopulationRosterPo
190
190
  const at = fallen === undefined ? -1 : group?.members.indexOf(fallen) ?? -1;
191
191
  if (at === -1) group?.members.push(a); else if (group !== undefined) group.members[at] = a;
192
192
  } });
193
+ host.events.on('world.slept', ({ seconds }) => { refill.slept(seconds); }, host.scope);
193
194
  host.events.on('actor.died', ({ actor }) => {
194
- if (host.players.size <= 1) return;
195
+ if (host.players.size <= 1 && !host.respawn.served) return;
195
196
  const a = list.find(body => body.actor.combatActor() === actor)?.actor, group = a === undefined ? undefined : hunt.herds[a.herd];
196
197
  if (a !== undefined && group !== undefined) refill.left({ kind: a.kind, variant: a.variant, herd: a.herd, x: group.cx, z: group.cz, from: a.entityId });
197
198
  }, host.scope);
198
199
  host.events.on('creature.tamed', tamed => {
199
- if (host.players.size > 1 && list.some(body => body.id === tamed.id)) refill.left({ ...tamed, from: tamed.id });
200
+ if ((host.players.size > 1 || host.respawn.served) && list.some(body => body.id === tamed.id)) refill.left({ ...tamed, from: tamed.id });
200
201
  }, host.scope);
201
202
  host.onStep(ROSTER_STEP, dt => {
202
203
  cadence.observe(dt); continuation.advance(dt); cadence.decide();
@@ -224,6 +225,7 @@ export function installPopulationRoster(host: SimHost, ports: PopulationRosterPo
224
225
  herdOwners();
225
226
  },
226
227
  });
228
+ host.events.on('world.slept', ({ seconds }) => { refill.slept(seconds); }, host.scope);
227
229
  // a restoring install: the saved list's live spawns from the host's own recipes, in order (a body retired in play leaves it)
228
230
  const saved = ports.saved, keeper = saved === undefined ? undefined : v.parse(Saved, saved.adapters.find(adapter => adapter.id === ROSTER_STEP)?.state);
229
231
  if (saved?.adapters.some(adapter => adapter.id === REFILL_STATE) === true) host.adapters.set(REFILL_STATE, refill.state);
@@ -1,4 +1,5 @@
1
1
  import { actRoutes } from '@wildshard/engine/sim/actRoutes';
2
+ import { questBooks } from '@wildshard/engine/quest/players';
2
3
  import type { SimHost } from '@wildshard/engine/sim';
3
4
  import { itemPickupFloor, ITEM_PICKUP_HOVER } from '@wildshard/engine/world/interact/pickup';
4
5
  import { pickPrompt } from '@wildshard/engine/world/interact/prompts';
@@ -10,24 +11,34 @@ const REACH_EYE = 1.68;
10
11
  const PROMPT_ABOVE = 0.5, PROMPT_RADIUS = 1.8;
11
12
  type Body = EliteCoreActor & { readonly position: { readonly x: number; readonly y: number; readonly z: number } };
12
13
 
14
+ /** SC10: the flag in each player's own book that says they took this lair's skin, in a served world. */
15
+ export const eliteSkinFlag = (id: string): string => `elite.${id}.skin`;
16
+
13
17
  /**
14
18
  * A first kill's orb on the server (J130). The rules say a lair's skin is untaken as it falls; this lays the orb out on the lair's
15
19
  * row, and a press in reach takes it. What the skin does to what's in hand is the page's, as a boss's is: the server keeps that it
16
20
  * went, so the next kill drops none.
21
+ *
22
+ * SERVER-CELLS SC10 (J328): a served world is never rebuilt, so there the skin is each player's own: a kill lays the orb out while a
23
+ * player present has not taken it, a press takes it for the presser (a flag in their own book, which goes with their save), and an
24
+ * owner's press is refused. The lair's world record (`skinTaken`) is a page's or a tape's alone.
17
25
  */
18
26
  export function eliteDrops<S extends EliteCoreScript<Body>>(host: SimHost): { readonly hooks: EliteCoreHooks<S>; readonly bind: (core: EliteCore<S>) => void } {
19
27
  const routes = actRoutes(host);
20
28
  let core: EliteCore<S> | null = null;
21
- return { bind: owner => { core = owner; }, hooks: { fell: (entry, first) => {
22
- const { animal, def } = entry.script;
23
- if (!first || animal === null || def.drop === undefined || def.drop.skin === null) return;
29
+ const owns = (player: string, id: string): boolean => { const books = questBooks(host), flag = eliteSkinFlag(id); books.claim([flag]); return books.of(player).flags.has(flag); };
30
+ const lacking = (id: string): boolean => [...host.players.keys()].some(player => !host.parked.has(player) && !owns(player, id));
31
+ return { bind: owner => { core = owner; host.events.on('world.slept', ({ seconds }) => { owner.slept(seconds); }, host.scope); }, hooks: { fell: (entry, first) => {
32
+ const { animal, def } = entry.script, served = host.respawn.served;
33
+ if (animal === null || def.drop === undefined || def.drop.skin === null || !(served ? lacking(def.id) : first)) return;
24
34
  const at = itemPickupFloor(host.physics, animal.position);
25
35
  entry.drop = { x: at.x, y: at.y + ITEM_PICKUP_HOVER, z: at.z };
26
36
  routes.claims.set(`${def.id}.reward`, player => {
27
37
  const feet = host.players.get(player)?.position, { drop } = entry;
28
- if (feet === undefined || drop === null) return;
38
+ if (feet === undefined || drop === null || (served && owns(player, def.id))) return;
29
39
  if (pickPrompt([{ position: { x: drop.x, y: drop.y + PROMPT_ABOVE, z: drop.z }, radius: PROMPT_RADIUS }], { x: feet.x, y: feet.y + REACH_EYE, z: feet.z }, host.physics) === undefined) return;
30
40
  entry.drop = null;
41
+ if (served) { questBooks(host).of(player).flags.set(eliteSkinFlag(def.id)); return; }
31
42
  const saved = core?.record(def.id);
32
43
  if (saved !== undefined) saved.skinTaken = true;
33
44
  core?.save();
@@ -37,7 +37,7 @@ export function installNativeChapterDirector(host: SimHost, director: Awaited<Re
37
37
  if (!['flag', 'phase', 'cue', 'reward'].includes(effect.kind)) throw new Error('Native chapter requires closed native effects');
38
38
  }
39
39
  const population = policy.wake === undefined ? null : mixedPopulation(host, policy.wake.population);
40
- const encounter = policy.wake === undefined ? null : installWakeBoss(host, policy.wake.encounter, policy.wake.placement);
40
+ const encounter = policy.wake === undefined || population === null ? null : installWakeBoss(host, policy.wake.encounter, policy.wake.placement, population.retireCaptain);
41
41
  const reward = policy.reward === undefined ? null : installNativeQuestChannels(host, policy.reward, { started: false, completed: false });
42
42
  const leadBody = host.players.get(books.lead.player); if (leadBody === undefined) throw new Error('Native chapter requires its player');
43
43
  const timeline = new ChapterClock(host.scope, director, rows, host.flags,
@@ -475,7 +475,11 @@ export function installNativeQuestComposition(host: SimHost, ports: NativeQuestC
475
475
  value => ammunition.prepareRestore(v.parse(v.optional(NativeAmmunitionSavedSchema), value)));
476
476
  const keys = new Set<string>(rows.saved.snapshot);
477
477
  if (rows.saved.snapshot.some(key => !parts.has(key))) throw new Error('Native saved role has no mechanic');
478
- host.onStep(rows.step, dt => { for (const phase of rows.phases) need(phases.get(phase), 'phase')(dt); secret?.(dt); countSeatFeats(); }, {
478
+ host.onStep(rows.step, dt => {
479
+ for (const phase of rows.phases) need(phases.get(phase), 'phase')(dt); secret?.(dt); countSeatFeats();
480
+ // SC10 (J328): a long-lived world forgets the purchase lines of those who left (their goods are in their own save)
481
+ if (purchases.size > 0) for (const player of purchases.keys()) if (!host.players.has(player)) purchases.delete(player);
482
+ }, {
479
483
  snapshot: () => entry.saved.encode(Object.fromEntries(rows.saved.snapshot.flatMap(key => {
480
484
  const value = need(parts.get(key), 'saved role').capture(); return value === undefined ? [] : [[key, value]];
481
485
  }))),
@@ -72,6 +72,8 @@ interface TamingSeat {
72
72
  readonly tick: (dt: number, read: boolean) => void;
73
73
  readonly shake: number; readonly roll: number;
74
74
  readonly holdOffer: (held: boolean) => void; readonly whistle: () => void;
75
+ /** SC5 (J328): its player left the room: the bodies it bonded go too, or a grid cell that never starts over gathers them past 64. */
76
+ readonly release: () => void;
75
77
  readonly save: () => { [Key in keyof v.InferOutput<typeof SessionSaved>]: v.InferOutput<typeof SessionSaved>[Key] };
76
78
  readonly load: (saved: v.InferOutput<typeof SessionSaved>, horses: readonly AnimalSim[]) => void;
77
79
  }
@@ -110,6 +112,10 @@ export function installNativeTaming(host: SimHost, context: NativeTamingContext,
110
112
  const mounted = mountedPlayerOf(host, player.id); if (mounted === undefined) throw new Error('Missing native mounted owner');
111
113
  let bond: string | null = null, pitch = 0, offer = false, heldOffer = false, calling = 0, lean = 0, shake = 0, roll = 0;
112
114
  const camera = new Vector3(), eye = new Vector3(), hurtDir = new Vector3(), mine = new Set<string>();
115
+ const retireBonded = (a: AnimalSim): void => {
116
+ mine.delete(a.entityId); creatures.retire(a.entityId); poses.delete(a.entityId);
117
+ const at = poseRows.indexOf(a); if (at === -1) throw new Error('Missing bonded pose'); poseRows.splice(at, 1);
118
+ };
113
119
  const law = new TamingSession<AnimalSim, HerdBrain<AnimalSim>>({
114
120
  profile: rows.binding,
115
121
  programs: rows.programs,
@@ -124,10 +130,7 @@ export function installNativeTaming(host: SimHost, context: NativeTamingContext,
124
130
  hud: { get offer() { return offer; }, get lean() { return lean; } }, herds: () => herds, rest: rows.rest,
125
131
  wind: () => wind, random: () => host.rng.stream('ai').next(),
126
132
  spawnBonded: (x, z, yaw, upgraded) => { const a = creatures.spawn(x, z, yaw, upgraded, mine.size); mine.add(a.entityId); addPose(a); return a; },
127
- hideStallion: a => { creatures.hide(a.entityId); }, retireBonded: a => {
128
- mine.delete(a.entityId); creatures.retire(a.entityId); poses.delete(a.entityId);
129
- const at = poseRows.indexOf(a); if (at === -1) throw new Error('Missing bonded pose'); poseRows.splice(at, 1);
130
- }, hurt: amount => {
133
+ hideStallion: a => { creatures.hide(a.entityId); }, retireBonded: a => { retireBonded(a); }, hurt: amount => {
131
134
  host.combat.hit({ source: 'env', sourceTags: ['env.ride'], target: player.health, amount, throughWalls: true,
132
135
  point: player.position, dir: hurtDir, cause: { kind: 'env.ride', label: rows.thrownLabel, text: rows.thrownLabel } });
133
136
  },
@@ -157,7 +160,8 @@ export function installNativeTaming(host: SimHost, context: NativeTamingContext,
157
160
  return taming;
158
161
  };
159
162
  const originalUpdate = law.update.bind(law);
160
- const session: TamingSeat = { player, law, get shake() { return shake; }, get roll() { return roll; }, holdOffer: held => { heldOffer = held; }, whistle: () => {
163
+ const session: TamingSeat = { player, law, get shake() { return shake; }, get roll() { return roll; }, holdOffer: held => { heldOffer = held; },
164
+ release: () => { for (const id of mine) { const a = poseRows.find(row => row.entityId === id); if (a === undefined) mine.delete(id); else retireBonded(a); } }, whistle: () => {
161
165
  const horse = law.companion;
162
166
  if (!mounted.mounted && horse !== null && horse.mem['whistle'] === 1 && mounted.canRide(horse.entityId) && horse.position.distanceTo(player.position) < 150) calling = 30;
163
167
  }, tick: (dt, read) => {
@@ -221,7 +225,7 @@ export function installNativeTaming(host: SimHost, context: NativeTamingContext,
221
225
  return best;
222
226
  };
223
227
  law.update = dt => {
224
- for (const [id, session] of sessions) if (host.players.get(id) !== session.player) sessions.delete(id);
228
+ for (const [id, session] of sessions) if (host.players.get(id) !== session.player) { session.release(); sessions.delete(id); }
225
229
  // Trust is the herd's: one voice speaks to it, the wild session closest to a stallion, or a far player would talk it down.
226
230
  const heard = sessions.size < 2 ? null : closestToWild();
227
231
  if (heard === null || first.law.phase !== 'wild' || heard === first) first.tick(dt, true);
@@ -18,16 +18,17 @@ export function installWildRefill(host: SimHost, mounts: BondedMountRoster, herd
18
18
  id: string, saved?: Readonly<Omit<SimSnapshot, 'physics'>>): (dt: number) => void {
19
19
  const state = `${id}.refill`;
20
20
  const herdOf = (actor: AnimalSim): HerdBrain<AnimalSim> | undefined => herds().find(row => row.members.includes(actor)) ?? herds()[0];
21
- const refill = new CreatureRefill({ players: () => [...host.players.values()], room: () => mounts.hidden.size,
21
+ const refill = new CreatureRefill({ players: () => [...host.players.values()], room: () => mounts.hidden.size, served: () => host.respawn.served,
22
22
  random: () => host.rng.stream('spawn').next(), spawn: ({ from, x, z }, yaw) => {
23
23
  const actor = host.entities.get(from), herd = actor === undefined ? undefined : herdOf(actor);
24
24
  if (actor === undefined || herd === undefined) return;
25
25
  mounts.reveal(from, x, z, yaw);
26
26
  herd.adoptStallion(actor); herd.addTrust(-100);
27
27
  } });
28
+ host.events.on('world.slept', ({ seconds }) => { refill.slept(seconds); }, host.scope);
28
29
  if (saved?.adapters.some(row => row.id === state) === true) host.adapters.set(state, refill.state);
29
30
  return dt => {
30
- if (host.players.size > 1) for (const hidden of mounts.hidden) {
31
+ if (host.players.size > 1 || host.respawn.served) for (const hidden of mounts.hidden) {
31
32
  if (refill.pending.some(entry => entry.from === hidden)) continue;
32
33
  const actor = host.entities.get(hidden), herd = actor === undefined ? undefined : herdOf(actor);
33
34
  if (actor !== undefined && herd !== undefined) refill.left({ kind: actor.kind, variant: actor.variant, herd: actor.herd, x: herd.cx, z: herd.cz, from: hidden });
@@ -76,8 +76,10 @@ const Saved = v.strictObject({ version: v.picklist([1, 2]), boss: Boss, fight: v
76
76
  * have this shape.
77
77
  */
78
78
  export function installBossRow(host: SimHost, spec: BossRowSpec): { boss: BossBrain; party: BossContenders; bounty: BossBounty; summon: () => void; locked: () => boolean } {
79
- const party = new BossContenders(host.players, point => spec.script.inArena(point), (player, position, yaw) => { player.position.copy(position); player.yaw = yaw; spec.returned?.(player); });
79
+ const party = new BossContenders(host.players, point => spec.script.inArena(point), (player, position, yaw) => { player.position.copy(position); player.yaw = yaw; spec.returned?.(player); },
80
+ { served: () => host.respawn.served, rearm: spec.armed === true });
80
81
  const bounty = new BossBounty(host, spec.body, spec.step);
82
+ host.events.on('world.slept', ({ seconds }) => { party.slept(seconds); }, host.scope);
81
83
  const ports = { events: host.events, player: party.player,
82
84
  lockInput: (on: boolean) => { if (actRoutes(host).introLocks === true) for (const player of host.players.values()) if (!on || spec.script.inArena(player.position)) player.moveScale = on ? 0 : 1; },
83
85
  skipHeld: () => actRoutes(host).skipHeld, respawn: party.respawn, faceToward: party.faceToward,
@@ -93,7 +95,7 @@ export function installBossRow(host: SimHost, spec: BossRowSpec): { boss: BossBr
93
95
  if (spec.armed === true) boss.arm();
94
96
  host.onStep(spec.step, dt => {
95
97
  const body = spec.body(); if (body !== null) host.focusOn(body.position);
96
- party.observe(boss);
98
+ party.observe(boss, dt);
97
99
  boss.update(dt, host.clock.now);
98
100
  }, {
99
101
  snapshot: () => { const { engaged } = party, { earned } = bounty; return JSON.stringify({ version: spec.stages === undefined ? 1 : 2, boss: boss.snapshot(), fight: spec.fight.snapshot(), ...(engaged === 0 ? {} : { engaged }), ...(earned.length === 0 ? {} : { earners: earned }) }); },
@@ -156,6 +156,8 @@ export function installHomeKeeper(host: SimHost, spec: HomeKeeperSpec, saved?: R
156
156
  const freeBody = (body: Body): void => { if (body.actor) { holders.delete(body.actor); host.retire(body.id); body.actor = null; body.brain = null; } };
157
157
  const respawn = (home: Home): void => { home.wait = 0; drawBody(home); };
158
158
  host.events.on('actor.died', ({ actor }) => { const home = homes.find(h => h.actor?.combatActor() === actor); if (home) home.wait = home.respawn; }, host.scope);
159
+ // SC10: a cell asleep with nobody in it: a fallen home's wait spends the time (it still respawns on its next tick, never asleep)
160
+ host.events.on('world.slept', ({ seconds }) => { for (const home of homes) if (home.wait > 0) home.wait = Math.max(Number.MIN_VALUE, home.wait - seconds); }, host.scope);
159
161
  host.onStep(step, dt => {
160
162
  // A boss's fight ends on blows, never on the plane: its flight follows a player down, and a fall would pay it out unstruck.
161
163
  // A held boss is a home body: under the plane it goes back to its anchor, never dies of it (HS3).
@@ -330,7 +332,7 @@ export function createNativeCreatureRoster<B extends NativeCreatureSlot>(host: S
330
332
  /** Identity lifecycle above the native body map, including dormant prewarm and permanent retirement. */
331
333
  identities: NativeActors<HuntBody>;
332
334
  /** Bind declared return rules to this roster's real identities and death events. */
333
- returns: (rows: unknown) => NativeReturns;
335
+ returns: (rows: unknown, reserved?: (id: string) => boolean) => NativeReturns;
334
336
  /** Advance native charge motion and report whether an owned live policy may move. */
335
337
  beforeBody: (id: string, dt: number) => boolean;
336
338
  /** Integrate the admitted pose, charge contact and hunted-body clearance in order. */
@@ -478,7 +480,7 @@ export function createNativeCreatureRoster<B extends NativeCreatureSlot>(host: S
478
480
  const level = saved.entities.find(entity => entity.id === item.id)?.state.flags.levelGround;
479
481
  return materialize(item, item.recipe, level ?? found.structure);
480
482
  };
481
- const returns = (input: unknown): NativeReturns => new NativeReturns(host, byId, hunt, input);
483
+ const returns = (input: unknown, reserved?: (id: string) => boolean): NativeReturns => new NativeReturns(host, byId, hunt, input, reserved);
482
484
  let poseNear = false;
483
485
  const beforeBody = (id: string, dt: number): boolean => {
484
486
  const actor = byId.get(id)?.actor;
@@ -23,7 +23,7 @@ import { simPlayerCommand, MAX_TICK_SNAPSHOT_CHARS, type HeadlessEffect, type He
23
23
  import { headlessSections } from '../../../shared/host/headlessSections';
24
24
  import { scriptAdmissionRows } from '@wildshard/format/scriptContract';
25
25
  import { validateShardfileAssets } from '@wildshard/format/assetAdmission';
26
- import { offlineMemoryAdmission, prepareAssetDecoders } from '@wildshard/format/product';
26
+ import { offlineMemoryAdmission, prepareAssetDecoders } from '@wildshard/format/shardfileAssets';
27
27
  import { leadCommands, leadPlayer } from '@wildshard/engine/sim/leadPlayer';
28
28
 
29
29
  await runTickWorker(async raw => {
@@ -3,13 +3,15 @@
3
3
  import { installAppIdentity } from '@wildshard/engine/app/identity';
4
4
  import { Scope } from '@wildshard/engine/app/scope';
5
5
  import { diagnosticNow } from '@wildshard/engine/core/clock';
6
+ import { CHUNK_HALF } from '@wildshard/engine/core/config';
6
7
  import { ServerClock } from '@wildshard/engine/net/serverClock';
7
8
  import type { GridAssembly } from '@wildshard/engine/game/grid/assembly';
8
9
  import type { GridCollisionStrip } from '@wildshard/engine/game/grid/gridCollision';
9
10
  import type { Rapier } from '@wildshard/engine/physics/rapier';
10
11
  import { DedicatedRoom, type DedicatedRoomRoad } from './dedicatedRoom';
11
- import { cellShard, gridAssembly, placeCell, roadName } from './gridCells';
12
+ import { cellShard, gridAssembly, gridCell, placeCell, roadName } from './gridCells';
12
13
  import { RoadRoom } from './roadRoom';
14
+ import { applyMotion } from '@wildshard/engine/game/grid/simulation';
13
15
  import { placedStrips } from '@wildshard/engine/game/grid/voidFloor';
14
16
  import { openRoad } from '../standalone/roadWorld';
15
17
  import type { HeadlessRuntimeInput } from '../headlessRuntime';
@@ -17,13 +19,26 @@ import type { CellOrder, WorkerNews, WorkerReading, WorkerResident } from './cel
17
19
  import { SeatTransport } from './socketPump';
18
20
 
19
21
  /** How often a worker reads itself (E7.8). */
20
- const READING_MS = 10_000;
22
+ export const READING_MS = 10_000;
21
23
  /** Enough ticks for a 10 s reading, at the worker's rate. */
22
24
  const TICKS_KEPT = 720;
23
25
  /** The save prefix a cell's stores share. Nothing outside a cell ever reads it. */
24
26
  const SAVE_PREFIX = 'wildshard.room.';
25
- /** J107: a cell everyone left starts over once it has stood empty this long, on its own timer, before anyone comes back (J320). */
27
+ /**
28
+ * SERVER-CELLS SC4 (J328): the ticks a cell runs as it opens, with nobody in it, before the worker says `booted`. A world's first ticks
29
+ * build what it builds lazily (each creature's animation channel programs, Rapier's first step, the JIT's first pass): 25 to 30 ms on an
30
+ * idle Mac, and up to 668 ms on a loaded one, which every player on the worker felt when the cell's first player arrived. One second of
31
+ * world time at boot pays it there instead.
32
+ */
33
+ export const WARM_TICKS = 60;
34
+ /**
35
+ * J107: a cell everyone left starts over once it has stood empty this long, on its own timer, before anyone comes back (J320). J328 (SC5)
36
+ * retires it for grid cells: a grid cell's world is never rebuilt, and what players spend in it comes back through its own respawns. Only
37
+ * a cell the grid doesn't place (a local run's `WORLD_CELLS`) still starts over.
38
+ */
26
39
  const EMPTY_MS = 300_000;
40
+ /** GC4: a road walker this near a cell's edge may be about to step in, so the cell does not start over under them; looked at again this often. */
41
+ const NEAR_M = 40, NEAR_RETRY_MS = 5000;
27
42
 
28
43
  /** A port as `worker_threads` and a `MessageChannel` both give it. */
29
44
  export interface CellPort { postMessage: (message: unknown, transfer?: readonly Transferable[]) => void; on?: (event: 'message', listener: (message: unknown) => void) => unknown; onmessage?: ((event: MessageEvent<unknown>) => void) | null }
@@ -36,9 +51,11 @@ export interface CellHostOptions {
36
51
  /** A shard's server inputs, by its slug. */
37
52
  readonly load: (slug: string) => Promise<HeadlessRuntimeInput>;
38
53
  /** A proof's overrides. `roomNow` is the rooms' hold and checkpoint clock; ticks keep real time. */
39
- readonly holdMs?: number; readonly emptyMs?: number; readonly roomNow?: () => number;
40
- /** What this process has resident, for the reading. */
41
- readonly memory: () => { readonly rss: number; readonly heapUsed: number };
54
+ readonly holdMs?: number; readonly emptyMs?: number; readonly roomNow?: () => number; readonly readingMs?: number;
55
+ /** What this process has resident, and this thread's own heap and buffers, for the reading. */
56
+ readonly memory: () => { readonly rss: number; readonly heapUsed: number; readonly external?: number; readonly arrayBuffers?: number };
57
+ /** SC1: this thread's event-loop lag since the last reading (`loopLag`), for `/metrics`. */
58
+ readonly lag?: () => { readonly p50: number; readonly p99: number; readonly max: number };
42
59
  /** The worker has closed: a worker exits here. */
43
60
  readonly closed?: () => void;
44
61
  /** A proof's look at each room it opens, and at its road. */
@@ -84,14 +101,27 @@ export function runCells(port: CellPort, options: CellHostOptions): { dispose: (
84
101
  /** A cell on this worker, or its road, by name. */
85
102
  const named = (name: string): Cell | RoadRoom | undefined => road !== undefined && road.name === name ? road : cells.get(name);
86
103
  const emptyMs = options.emptyMs ?? EMPTY_MS;
104
+ /** GC15 (3): cells a seat from another worker's road is arriving in: none starts over meanwhile (review SHOULD). */
105
+ const arrivals = new Set<Cell>();
106
+ /** Set by `drain`: the worker is closing, so an arrival is refused (the client retries on the next one). */
107
+ let drained = false;
87
108
  /** `startOver`, once it is made below: a start-over opens a cell, and a cell's room says when it emptied. */
88
109
  const later = { startOver: (_cell: Cell, _since: number): void => undefined };
89
110
  /** Someone stood in this world: it has something to start over from. A refused seat never got this far. */
111
+ /** SC10 (J328): when each room last had nobody in it, from its boot or its last leave. */
112
+ const asleep = new Map<DedicatedRoom, number>();
113
+ /** SC10: a room's first seat after empty time: its world took no ticks meanwhile and is never rebuilt, so it spends the time now. */
114
+ const woke = (room: DedicatedRoom): void => {
115
+ const since = asleep.get(room); asleep.delete(room);
116
+ const seconds = since === undefined ? 0 : (diagnosticNow() - since) / 1000;
117
+ if (seconds >= 1) room.host.events.emit('world.slept', { seconds });
118
+ };
90
119
  const used = (slug: string, room: DedicatedRoom): void => { const cell = cells.get(slug); if (cell !== undefined && cell.room === room) cell.used = true; };
91
- /** J107 on J320's terms: the last seat left this cell's world, so it starts over once it has stood empty `emptyMs`, nobody waiting on it. */
120
+ /** J107 on J320's terms: the last seat left this cell's world, so it starts over once it has stood empty `emptyMs`, nobody waiting on it.
121
+ * SC5 (J328): never a grid cell's. */
92
122
  const emptied = (slug: string, room: DedicatedRoom): void => {
93
123
  const cell = cells.get(slug);
94
- if (cell === undefined || cell.room !== room || disposed) return;
124
+ if (cell === undefined || cell.room !== room || disposed || gridCell(slug)) return;
95
125
  const since = cell.emptySince = diagnosticNow();
96
126
  if (cell.used) scope.timeout(emptyMs, () => { later.startOver(cell, since); });
97
127
  };
@@ -100,8 +130,14 @@ export function runCells(port: CellPort, options: CellHostOptions): { dispose: (
100
130
  const shard = cellShard(slug), begun = diagnosticNow(), input = await options.load(shard), onto = seams(slug);
101
131
  rapier ??= input.rapier;
102
132
  const room: DedicatedRoom = await DedicatedRoom.boot({ slug: shard, cell: slug, build: options.build, bootId: options.bootId(), input, now: options.roomNow ?? diagnosticNow, ...(onto === undefined ? {} : { road: onto }),
103
- post: news => { if (news.kind === 'seated') used(slug, room); else if (news.kind === 'left' && news.seats === 0) emptied(slug, room); post({ ...news, slug }); },
133
+ post: news => {
134
+ if (news.kind === 'seated') { if (news.seats === 1) woke(room); used(slug, room); } else if (news.kind === 'left' && news.seats === 0) { asleep.set(room, diagnosticNow()); emptied(slug, room); }
135
+ post({ ...news, slug });
136
+ },
104
137
  reports: { file: report => { post({ kind: 'report', slug, report }); } }, ...(options.holdMs === undefined ? {} : { holdMs: options.holdMs }),...(options.playtest===true?{playtest:row=>{post({kind:'playtest',slug,row});}}:{}) });
138
+ // SC4: its first ticks now, while nobody is in it, not on its first player's arrival.
139
+ for (let tick = 0; tick < WARM_TICKS; tick++) room.tick();
140
+ asleep.set(room, diagnosticNow());
105
141
  post({ kind: 'cell', slug, ms: diagnosticNow() - begun });
106
142
  options.booted?.(slug, room);
107
143
  return room;
@@ -115,17 +151,27 @@ export function runCells(port: CellPort, options: CellHostOptions): { dispose: (
115
151
  const reading = (): void => {
116
152
  const now = diagnosticNow(), sorted = ticks.slice().sort((a, b) => a - b), rooms = [...cells.values()].map(cell => cell.room), memory = options.memory();
117
153
  const sum = (read: (room: DedicatedRoom) => number): number => rooms.reduce((total, room) => total + read(room), 0);
118
- const row: WorkerReading = { cells: rooms.length, awake: rooms.filter(room => room.taken > 0).length, players: sum(room => room.taken - room.holding), held: sum(room => room.holding), ticks: ticked, ticksPerSecond: ticks.length / ((now - readAt) / 1000),
154
+ // SC1: a seat on this worker's road is a player too, though the road is no cell.
155
+ const onRoad = road === undefined ? 0 : road.taken - road.holding, heldOnRoad = road?.holding ?? 0;
156
+ const row: WorkerReading = { cells: rooms.length, awake: rooms.filter(room => room.taken > 0).length, players: sum(room => room.taken - room.holding) + onRoad, held: sum(room => room.holding) + heldOnRoad, ticks: ticked, ticksPerSecond: ticks.length / ((now - readAt) / 1000),
119
157
  p50: percentile(sorted, 0.5), p95: percentile(sorted, 0.95), p99: percentile(sorted, 0.99), max: sorted.at(-1) ?? 0, drops: (clock?.drops ?? 0) - dropsAt, rss: memory.rss, heap: memory.heapUsed,
120
- refused: sum(room => room.net.stats.refused), dropped: sum(room => room.net.stats.dropped), frameBytes: sum(room => room.net.stats.frameBytes), eventBytes: sum(room => room.net.stats.eventBytes) };
158
+ refused: sum(room => room.net.stats.refused), dropped: sum(room => room.net.stats.dropped), frameBytes: sum(room => room.net.stats.frameBytes), eventBytes: sum(room => room.net.stats.eventBytes),
159
+ ...(memory.external === undefined ? {} : { external: memory.external }), ...(memory.arrayBuffers === undefined ? {} : { arrayBuffers: memory.arrayBuffers }), ...(options.lag === undefined ? {} : { lag: options.lag() }) };
121
160
  readAt = now; dropsAt = clock?.drops ?? 0; ticks = [];
122
161
  post({ kind: 'reading', reading: row });
123
162
  };
124
163
  /** One start-over at a time on this worker: each boot stalls the clock of every other cell here, so they never pile up. */
125
164
  let overs: Promise<void> = Promise.resolve();
126
165
  /** The fresh world, swapped in while the cell is still empty. One that fails keeps the old world and says so; the worker plays on. */
166
+ /** GC4: a walker on this worker's road near the cell's edge, or a seat arriving from another worker's road, may step in now. */
167
+ const walkerNear = (cell: Cell): boolean => {
168
+ const origin = crossing?.assembly.cells.find(row => [cell.slug].includes(row.instance))?.origin;
169
+ return arrivals.has(cell) || (origin !== undefined && road?.near(origin, CHUNK_HALF + NEAR_M) === true);
170
+ };
127
171
  const restart = async (cell: Cell): Promise<void> => {
128
172
  if (disposed || cell.room.taken > 0) return;
173
+ // review SHOULD: a start-over queued behind others looks again when its turn comes, since a walker may have come near meanwhile
174
+ if (walkerNear(cell)) { const since = cell.emptySince; scope.timeout(NEAR_RETRY_MS, () => { later.startOver(cell, since); }); return; }
129
175
  try {
130
176
  const old = cell.room, room = await open(cell.slug);
131
177
  if (disposed) { room.dispose(); return; }
@@ -137,6 +183,8 @@ export function runCells(port: CellPort, options: CellHostOptions): { dispose: (
137
183
  if (disposed || cell.waking !== null || !cell.used || cell.room.taken > 0 || cell.emptySince !== since) return;
138
184
  const left = emptyMs - (diagnosticNow() - since);
139
185
  if (left > 0) { scope.timeout(left, () => { later.startOver(cell, since); }); return; }
186
+ // GC4: never boot a cell under a walker heading back to it: while someone on the road stands within NEAR_M of its edge, look again later
187
+ if (walkerNear(cell)) { scope.timeout(NEAR_RETRY_MS, () => { later.startOver(cell, since); }); return; }
140
188
  const job = overs.then(() => restart(cell)).finally(() => { if (cell.waking === job) cell.waking = null; });
141
189
  cell.waking = job; overs = job;
142
190
  };
@@ -196,6 +244,29 @@ export function runCells(port: CellPort, options: CellHostOptions): { dispose: (
196
244
  const moved = source.handOver(entry.device, target, entry, at);
197
245
  post({ kind: 'crossed', device: entry.device, name: entry.name, from: fromSlug, to: toSlug, moved, stays: source.holds(entry.device), body: moved ? target.bodyId(entry.device) ?? entry.body : entry.body });
198
246
  };
247
+ /**
248
+ * GC15 (3): a seat another worker's road let go walks into cell `to` here, on the socket the door moved to `port`: its body first, at `at`
249
+ * with the walker's motion, then the room hears the client's hello again and welcomes it (the client heard `travel` first).
250
+ */
251
+ const arrive = async (order: Extract<CellOrder, { kind: 'arrive' }>): Promise<void> => {
252
+ const { kind: _kind, from, to: slug, at, port: seatPort, hello, motion, ...entry } = order, cell = cells.get(slug);
253
+ // review MUST: the port's transport is made after the wait, as `seat`'s is: a close meanwhile stays queued on the port for it
254
+ const refuse = (made?: SeatTransport): void => { (made ?? new SeatTransport(seatPort)).close('retry'); post({ kind: 'crossed', device: entry.device, name: entry.name, from, to: slug, moved: false, stays: false, body: entry.body }); };
255
+ if (cell !== undefined) arrivals.add(cell);
256
+ try {
257
+ // review SHOULDs: a drained worker seats no one, and a cell that already holds this device keeps that body
258
+ if (cell === undefined || drained || !await settled(cell) || drained || cell.room.holds(entry.device)) { refuse(); return; }
259
+ const transport = new SeatTransport(seatPort), arrived = cell.room.admit(entry, transport, at);
260
+ if (typeof arrived === 'string') { refuse(transport); return; }
261
+ const player = cell.room.host.players.get(arrived.body);
262
+ if (motion !== null && player !== undefined) applyMotion(motion, player);
263
+ const client = cell.room.net.join(transport, cell.room.sim.playerOf(arrived.body));
264
+ transport.deliver('reliable', hello);
265
+ cell.room.net.travelled(client);
266
+ const moved = arrived.land(cell.room.net.live(client) ? client : null);
267
+ post({ kind: 'crossed', device: entry.device, name: entry.name, from, to: slug, moved, stays: false, body: cell.room.bodyId(entry.device) ?? entry.body });
268
+ } finally { if (cell !== undefined) arrivals.delete(cell); }
269
+ };
199
270
  const handle = (order: CellOrder): void => {
200
271
  if (order.kind === 'close') { dispose(); return; }
201
272
  // MP4.1: a line from the world reaches each awake cell here but the one that said it. A cell asleep or starting over hears nothing.
@@ -206,8 +277,12 @@ export function runCells(port: CellPort, options: CellHostOptions): { dispose: (
206
277
  return;
207
278
  }
208
279
  if (!ready) { fail(new Error('A worker was told something before it booted')); return; }
209
- if (order.kind === 'drain') { clock?.pause(); for (const { room } of cells.values()) room.drain(); road?.drain(); post({ kind: 'drained' }); return; }
280
+ if (order.kind === 'drain') { drained = true; clock?.pause(); for (const { room } of cells.values()) room.drain(); road?.drain(); post({ kind: 'drained' }); return; }
210
281
  if (order.kind === 'cross') { cross(order).catch(fail); return; }
282
+ // GC15 (3): crossings between workers, and which cells on the others a walker can stand in
283
+ if (order.kind === 'open') { road?.open(order.cells); return; }
284
+ if (order.kind === 'handOut') { const out = road !== undefined && road.name === order.from && road.handOut(order.device, order.to); if (!out) post({ kind: 'handedOut', device: order.device, from: order.from, out }); return; }
285
+ if (order.kind === 'arrive') { arrive(order).catch(fail); return; }
211
286
  if (order.kind === 'place') { placing = placing.then(() => place(order)); return; }
212
287
  const cell = named(order.slug);
213
288
  if (cell === undefined) { fail(new Error(`${order.slug} is not on this worker`)); return; }
@@ -219,8 +294,14 @@ export function runCells(port: CellPort, options: CellHostOptions): { dispose: (
219
294
  void (async (): Promise<void> => {
220
295
  const first = options.slugs[0];
221
296
  // SA34a: a worker booted after a placement (its `placed`) lays the placed cells out from the start.
222
- // GC28: a book with no grid pack reads no strips: no road to stand on, so the cells open lone (the worker's `road.pack` line says 0).
223
- if (options.road !== undefined && first !== undefined) { const assembly = gridAssembly(), strips = await options.road(), placed = placedStrips(assembly, gridAssembly(false)); if (strips.length > 0) crossing = { name: roadName(first), assembly, strips: [...strips, ...placed.strips], seams: placed.seams }; }
297
+ // ROAD-RESIDENT RR4 (Jake 11-13 ~10:35: crossing always on; replaces GC28's lone cells): a book with no grid pack reads no
298
+ // strips, so there is no road to stand on. The worker refuses its boot: `/health` never comes up and `wildshard-config`'s
299
+ // rollback keeps the last good server, instead of a server whose players can't leave their cell (the `road.pack` line says 0).
300
+ if (options.road !== undefined && first !== undefined) {
301
+ const assembly = gridAssembly(), strips = await options.road(), placed = placedStrips(assembly, gridAssembly(false));
302
+ if (strips.length === 0) throw new Error('No road: the grid pack read 0 strips (a crossing worker needs its road)');
303
+ crossing = { name: roadName(first), assembly, strips: [...strips, ...placed.strips], seams: placed.seams };
304
+ }
224
305
  for (const slug of options.slugs) { const room = await open(slug); if (disposed) return; cells.set(slug, { slug, room, emptySince: diagnosticNow(), used: false, waking: null }); }
225
306
  if (crossing !== undefined && rapier !== undefined) {
226
307
  const { name, assembly, strips } = crossing, begun = diagnosticNow();
@@ -233,8 +314,9 @@ export function runCells(port: CellPort, options: CellHostOptions): { dispose: (
233
314
  ready = true; readAt = diagnosticNow();
234
315
  clock = new ServerClock({ now: diagnosticNow, wait: (ms, run) => { const timer = scope.timeout(ms, run); return () => { scope.cancelTimer(timer); }; }, step });
235
316
  clock.start();
236
- scope.interval(READING_MS, reading);
237
- post({ kind: 'booted', ms: diagnosticNow() - started, resident: resident() });
317
+ scope.interval(options.readingMs ?? READING_MS, reading);
318
+ // GC15 (3): this worker's grid cells a walker off another worker's road can stand in (GC30's entryway ground)
319
+ post({ kind: 'booted', ms: diagnosticNow() - started, resident: resident(), ...(road === undefined ? {} : { stands: [...cells.keys()].filter(enterable) }) });
238
320
  })().catch(fail);
239
321
  return { dispose };
240
322
  }
@@ -3,6 +3,7 @@ import type { PlayerDoc } from './playerDoc';
3
3
  import type { SaveReceipt, SaveWrite } from './saves/saveStore';
4
4
  import type {PlaytestHit} from './playtest';
5
5
  import type { PlacedCell } from './gridCells';
6
+ import type { MotionSnapshot } from '@wildshard/engine/game/grid/simulation';
6
7
 
7
8
  // J182: what the door and a cell worker say to each other. Sockets stay with the door, and a seat's bytes go through its own port.
8
9
 
@@ -36,6 +37,15 @@ export type CellOrder =
36
37
  * squares, their strips, and walls round any it can't hand a seat to. `open` names the ones this worker opens and hosts.
37
38
  */
38
39
  | { readonly kind: 'place'; readonly id: number; readonly cells: readonly PlacedCell[]; readonly open: readonly string[] }
40
+ /**
41
+ * GC15 (3): a seat on this worker's road (`from`) walks into `to`, a cell on another worker. The road sends the client `travel`, lets the
42
+ * seat go and says `out` on its port with the walker's motion; the door then points the socket at `to`'s worker (`arrive`).
43
+ */
44
+ | { readonly kind: 'handOut'; readonly from: string; readonly device: string; readonly to: string }
45
+ /** GC15 (3): the seat `handOut` let go on another worker arrives in `to` at `at`: the room hears its `hello` again on the moved socket. */
46
+ | ({ readonly kind: 'arrive'; readonly from: string; readonly to: string; readonly at: ResumeAt; readonly port: MessagePort; readonly hello: ArrayBuffer; readonly motion: MotionSnapshot | null } & SeatEntry)
47
+ /** GC15 (3): cells on other workers a walker can stand in at their entryways: this worker's road drops its walls round them and crosses into them. */
48
+ | { readonly kind: 'open'; readonly cells: readonly string[] }
39
49
  | { readonly kind: 'close' };
40
50
  /** One 10 s reading of a worker (E7.8). */
41
51
  export interface WorkerReading {
@@ -43,6 +53,9 @@ export interface WorkerReading {
43
53
  readonly players: number; readonly held: number; readonly ticks: number; readonly ticksPerSecond: number;
44
54
  readonly p50: number; readonly p95: number; readonly p99: number; readonly max: number; readonly drops: number;
45
55
  readonly rss: number; readonly heap: number; readonly refused: number; readonly dropped: number; readonly frameBytes: number; readonly eventBytes: number;
56
+ /** SERVER-CELLS SC1: this worker thread's own memory beyond its heap, and its event-loop lag in ms (`loopLag`), when it measures them. */
57
+ readonly external?: number; readonly arrayBuffers?: number;
58
+ readonly lag?: { readonly p50: number; readonly p99: number; readonly max: number };
46
59
  }
47
60
  /** What a cell tells the worker it runs on. */
48
61
  export type RoomNews =
@@ -60,7 +73,9 @@ export type RoomNews =
60
73
  export interface WorkerResident { readonly cells: number; readonly road: boolean; readonly strips: number }
61
74
  /** What a worker says to the door. */
62
75
  export type WorkerNews =
63
- | { readonly kind: 'booted'; readonly ms: number; readonly resident?: WorkerResident }
76
+ | { readonly kind: 'booted'; readonly ms: number; readonly resident?: WorkerResident; /** GC15 (3): its grid cells whose entryways stand (GC30), for the other workers' roads. */ readonly stands?: readonly string[] }
77
+ /** GC15 (3): a `handOut` that let nothing go (the seat had no live link, or was gone): the crossing is off and the seat stays where it was. */
78
+ | { readonly kind: 'handedOut'; readonly device: string; readonly from: string; readonly out: boolean }
64
79
  | { readonly kind: 'failed'; readonly reason: string }
65
80
  | { readonly kind: 'found'; readonly id: number; readonly held: boolean; readonly spawn: ResumeAt }
66
81
  | { readonly kind: 'report'; readonly slug: string; readonly report: ChatReport }
@@ -10,7 +10,8 @@ import { parentPort, workerData } from 'node:worker_threads';
10
10
  import { loadRapier } from '@wildshard/engine/physics/rapier';
11
11
  import { readPackGrid, readPackProduct, type PackReads } from './packReader';
12
12
  import { runCells, type CellPort } from './cellHost';
13
- import { placeCell, type PlacedCell } from './gridCells';
13
+ import { placeCell, placedHash, type PlacedCell } from './gridCells';
14
+ import { loopLag } from './loopLag';
14
15
 
15
16
  /** What the door boots a worker with. */
16
17
  export interface CellWorkerData { readonly slugs: readonly string[]; readonly build: string; readonly origin: string; readonly cache: string; readonly holdMs?: number;readonly playtest?:boolean;
@@ -19,21 +20,23 @@ export interface CellWorkerData { readonly slugs: readonly string[]; readonly bu
19
20
  /** GC15: `WORLD_CROSSING=worker`, this worker hosts the road between its cells. */
20
21
  readonly crossing?: boolean;
21
22
  /** SA33: the cells the door had placed when it booted this worker; a worker's module state is its own. */
22
- readonly placed?: readonly PlacedCell[] }
23
+ readonly placed?: readonly PlacedCell[];
24
+ /** SERVER-CELLS SC1: `METRICS_PORT` is set, so this worker measures its event-loop lag for `/metrics`. */
25
+ readonly metrics?: boolean }
23
26
 
24
- const { slugs, build, origin, cache, holdMs, emptyMs, playtest, crossing, placed } = workerData as CellWorkerData, port = parentPort;
27
+ const { slugs, build, origin, cache, holdMs, emptyMs, playtest, crossing, placed, metrics } = workerData as CellWorkerData, port = parentPort;
25
28
  if (port === null) throw new Error('A cell runs in a worker');
26
29
  for (const row of placed ?? []) placeCell(row);
27
30
  const reads: PackReads = { fetched: 0, fetchedBytes: 0, cached: 0, refused: 0 };
28
31
  const rapier = await loadRapier(await readFile(new URL('rapier.wasm', import.meta.url)));
29
- runCells(port as unknown as CellPort, { slugs, build, bootId: () => randomBytes(4).toString('hex'), memory: () => process.memoryUsage(), closed: () => { process.exit(0); }, ...(holdMs === undefined ? {} : { holdMs }), ...(emptyMs === undefined ? {} : { emptyMs }),...(playtest===undefined?{}:{playtest}),...(crossing === true ? { road: async () => {
32
+ runCells(port as unknown as CellPort, { slugs, build, bootId: () => randomBytes(4).toString('hex'), memory: () => process.memoryUsage(), ...(metrics === true ? { lag: loopLag() } : {}), closed: () => { process.exit(0); }, ...(holdMs === undefined ? {} : { holdMs }), ...(emptyMs === undefined ? {} : { emptyMs }),...(playtest===undefined?{}:{playtest}),...(crossing === true ? { road: async () => {
30
33
  // A build whose server book has no grid pack gives a road with no strips: this line says so before anyone falls through it.
31
34
  const strips = await readPackGrid(build, { origin, cache }, reads);
32
35
  console.info(JSON.stringify({ at: 'road.pack', strips: strips.length, ...reads }));
33
36
  return strips;
34
37
  } } : {}),
35
38
  load: async slug => {
36
- const input = await readPackProduct(slug, build, rapier, { origin, cache }, reads);
39
+ const input = await readPackProduct(slug, build, rapier, { origin, cache }, reads, placedHash(slug));
37
40
  console.info(JSON.stringify({ at: 'cell.pack', slug, ...reads }));
38
41
  return input;
39
42
  } });