threedog 0.8.0 → 1.0.0

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 (372) hide show
  1. package/CHANGELOG.md +219 -4
  2. package/README.md +6 -6
  3. package/core/assets/Animator.js +2 -0
  4. package/core/assets/Assets.js +44 -13
  5. package/core/assets/assetEntry.js +87 -22
  6. package/core/assets/assetHot.js +2 -1
  7. package/core/assets/assetReport.js +1 -2
  8. package/core/audio/Audio.js +24 -5
  9. package/core/base/I18n.js +6 -3
  10. package/core/base/Random.js +3 -1
  11. package/core/base/Vars.js +14 -4
  12. package/core/base/errorCodes.js +54 -16
  13. package/core/base/errorHints.js +12 -1
  14. package/core/base/errors.js +6 -4
  15. package/core/base/events.generated.js +10 -0
  16. package/core/base/follows.js +26 -0
  17. package/core/base/math.js +15 -8
  18. package/core/base/params.js +2 -2
  19. package/core/{saves → base}/saveValues.js +24 -6
  20. package/core/base/sections.js +97 -0
  21. package/core/base/spelling.js +32 -0
  22. package/core/base/validate.js +8 -29
  23. package/core/engine/Engine.js +61 -18
  24. package/core/engine/Loading.js +30 -3
  25. package/core/engine/copies.js +1 -1
  26. package/core/engine/headlessLoad.js +30 -13
  27. package/core/engine/lifecycle.js +30 -25
  28. package/core/engine/loop.js +22 -4
  29. package/core/engine/moduleSlots.js +91 -15
  30. package/core/engine/moduleTypes.js +13 -0
  31. package/core/engine/modules.js +248 -62
  32. package/core/engine/page.js +25 -8
  33. package/core/engine/plugins.js +15 -3
  34. package/core/engine/services.js +3 -0
  35. package/core/engine/startup.js +46 -36
  36. package/core/input/Input.js +39 -19
  37. package/core/input/inputKeyboard.js +39 -0
  38. package/core/input/inputPad.js +23 -2
  39. package/core/input/inputPointer.js +3 -1
  40. package/core/input/inputSeat.js +66 -0
  41. package/core/input/inputTouch.js +23 -6
  42. package/core/inspect/DebugOverrides.js +13 -2
  43. package/core/inspect/Describe.js +10 -6
  44. package/core/inspect/Inspect.js +31 -4
  45. package/core/inspect/UrlState.js +14 -10
  46. package/core/inspect/catalog.js +12 -5
  47. package/core/inspect/describeRender.js +3 -2
  48. package/core/inspect/describeText.js +6 -2
  49. package/core/inspect/metadata.generated.js +4140 -0
  50. package/core/inspect/pictureWriters.js +117 -33
  51. package/core/inspect/toolDoor.js +21 -0
  52. package/core/inspect/valueHistory.js +35 -0
  53. package/core/ops/Ops.js +32 -7
  54. package/core/ops/control.js +48 -23
  55. package/core/ops/holds.js +4 -3
  56. package/core/ops/opsAtomic.js +18 -6
  57. package/core/ops/opsCheck.js +7 -5
  58. package/core/ops/opsFail.js +5 -7
  59. package/core/ops/opsRun.js +2 -2
  60. package/core/ops/owned.js +20 -3
  61. package/core/ops/sharedPoint.js +7 -10
  62. package/core/ops/stacks.js +22 -1
  63. package/core/saves/SaveStore.js +52 -26
  64. package/core/saves/Saves.js +122 -27
  65. package/core/saves/saveApply.js +159 -61
  66. package/core/saves/saveFiles.js +30 -25
  67. package/core/saves/saveVersions.js +20 -6
  68. package/core/saves/session.js +76 -33
  69. package/core/saves/stateReplace.js +184 -0
  70. package/core/scene/Rays.js +21 -5
  71. package/core/scene/Views.js +6 -6
  72. package/core/scene/adaptive.js +13 -10
  73. package/core/scene/canvasBox.js +2 -0
  74. package/core/scene/compositeGround.js +72 -0
  75. package/core/scene/floor.js +17 -0
  76. package/core/scene/grid.js +2 -0
  77. package/core/scene/ground.contract.js +14 -0
  78. package/core/scene/ground.js +52 -17
  79. package/core/scene/pixel.js +154 -0
  80. package/core/scene/pixelRatio.js +167 -0
  81. package/core/scene/sceneDelta.js +3 -3
  82. package/core/scene/sceneMethods.js +11 -6
  83. package/core/scene/stepPoses.js +6 -1
  84. package/core/scene/thingExplain.js +1 -1
  85. package/core/scene/thingOps.js +22 -14
  86. package/core/scene/things.js +1 -1
  87. package/core/scene/tier.js +10 -0
  88. package/core/scene/view.js +126 -9
  89. package/core/stream/Batching.js +0 -1
  90. package/core/stream/Stream.js +24 -12
  91. package/core/stream/batchGroups.js +1 -0
  92. package/core/stream/scatter.js +5 -2
  93. package/core/stream/streamSources.js +2 -1
  94. package/core/threads/Commits.js +12 -7
  95. package/core/threads/Jobs.js +15 -5
  96. package/core/threads/Threads.js +5 -2
  97. package/core/time/Clock.js +3 -1
  98. package/core/time/skip.js +10 -4
  99. package/core/time/time.js +16 -10
  100. package/docs/AI.md +89 -72
  101. package/docs/API.md +18 -14
  102. package/docs/CODEMAP.md +68 -40
  103. package/docs/COMMANDS.md +22 -23
  104. package/docs/CONVENTIONS.md +120 -17
  105. package/docs/MIGRATING-0.8.md +2 -0
  106. package/docs/MIGRATING-1.0.md +101 -0
  107. package/docs/THREE.md +65 -12
  108. package/docs/api/cameraRig.md +3 -0
  109. package/docs/api/characters.md +13 -7
  110. package/docs/api/collider3d.md +9 -0
  111. package/docs/api/content.md +16 -15
  112. package/docs/api/dialogue.md +2 -1
  113. package/docs/api/engine.md +18 -16
  114. package/docs/api/events.md +14 -4
  115. package/docs/api/ground.md +2 -2
  116. package/docs/api/i18n.md +1 -1
  117. package/docs/api/input.md +2 -1
  118. package/docs/api/interactions.md +1 -1
  119. package/docs/api/inventory.md +1 -1
  120. package/docs/api/level.md +3 -2
  121. package/docs/api/nav.md +4 -2
  122. package/docs/api/particles.md +8 -5
  123. package/docs/api/pickups.md +1 -1
  124. package/docs/api/post.md +3 -4
  125. package/docs/api/quests.md +4 -2
  126. package/docs/api/rays.md +2 -0
  127. package/docs/api/rigid.md +3 -2
  128. package/docs/api/saves.md +8 -7
  129. package/docs/api/stream.md +4 -5
  130. package/docs/api/terrain.md +3 -4
  131. package/docs/api/terrainDraw.md +1 -1
  132. package/docs/api/timeline.md +2 -2
  133. package/docs/api/tools.md +3 -1
  134. package/docs/api/triggers.md +2 -0
  135. package/docs/api/vegetationDraw.md +1 -1
  136. package/docs/api/water.md +6 -2
  137. package/docs/api/weather.md +19 -4
  138. package/docs/api/weatherDraw.md +1 -1
  139. package/docs/api/world.md +1 -1
  140. package/docs/recipes/01-new-game.md +3 -3
  141. package/docs/recipes/02-npc.md +3 -4
  142. package/docs/recipes/03-items-pickups.md +11 -11
  143. package/docs/recipes/04-quests.md +2 -0
  144. package/docs/recipes/05-props-bake.md +9 -9
  145. package/docs/recipes/06-clock-events.md +6 -6
  146. package/docs/recipes/07-flow-scenes-pause.md +18 -15
  147. package/docs/recipes/08-weather-sky.md +5 -5
  148. package/docs/recipes/09-materials-lights-models.md +3 -3
  149. package/docs/recipes/10-blender-level.md +16 -4
  150. package/docs/recipes/11-vehicles.md +18 -6
  151. package/docs/recipes/12-navmesh.md +52 -8
  152. package/docs/recipes/13-animation.md +34 -8
  153. package/docs/recipes/14-custom-module.md +20 -8
  154. package/docs/recipes/15-perf.md +4 -4
  155. package/docs/recipes/16-dev-bridge.md +9 -8
  156. package/docs/recipes/18-world.md +13 -5
  157. package/docs/recipes/19-shooting-picking.md +3 -2
  158. package/docs/recipes/20-content-actions-save.md +26 -6
  159. package/docs/recipes/21-camera.md +17 -23
  160. package/docs/recipes/22-shop-gold.md +21 -12
  161. package/docs/recipes/23-ops.md +19 -15
  162. package/docs/recipes/26-ui-parts.md +3 -2
  163. package/docs/recipes/27-net.md +3 -3
  164. package/docs/recipes/28-terrain.md +3 -3
  165. package/docs/recipes/29-grid.md +1 -1
  166. package/docs/recipes/30-templates.md +10 -13
  167. package/docs/recipes/31-audio.md +2 -2
  168. package/docs/recipes/32-action-game.md +6 -5
  169. package/docs/recipes/33-stream-sources.md +4 -1
  170. package/docs/recipes/34-environment-lighting.md +7 -8
  171. package/docs/recipes/35-picture-from-reference.md +13 -9
  172. package/docs/recipes/36-ground-plants.md +3 -2
  173. package/docs/recipes/40-scene.md +11 -10
  174. package/docs/recipes/43-shader-patches-surfaces.md +7 -7
  175. package/docs/recipes/44-water-weather-hooks.md +9 -8
  176. package/docs/recipes/45-cascaded-shadows.md +3 -4
  177. package/docs/recipes/46-blender-art-route.md +3 -3
  178. package/docs/recipes/49-game-module-contract.md +2 -1
  179. package/docs/recipes/50-own-renderer.md +1 -0
  180. package/docs/recipes/51-capability-catalog.md +14 -8
  181. package/docs/recipes/52-around-the-picture.md +4 -4
  182. package/docs/recipes/55-mods-time-wrap.md +5 -4
  183. package/docs/recipes/56-webgpu-tsl.md +12 -1
  184. package/docs/recipes/57-control.md +30 -10
  185. package/docs/recipes/58-input.md +13 -0
  186. package/docs/recipes/60-judge-the-picture.md +1 -1
  187. package/docs/recipes/62-picture-code.md +106 -48
  188. package/docs/recipes/63-third-person-start.md +2 -1
  189. package/docs/recipes/64-particles.md +53 -4
  190. package/docs/recipes/65-swarm.md +2 -2
  191. package/docs/recipes/66-common-tasks.md +313 -0
  192. package/examples/action/.threedog/content-index.json +1 -1
  193. package/examples/action/GAMEMAP.md +3 -3
  194. package/examples/perf-island/.threedog/content-index.json +1 -1
  195. package/examples/perf-island/GAMEMAP.md +3 -3
  196. package/examples/perf-island/main.js +2 -2
  197. package/examples/plain-picture/GAMEMAP.md +3 -1
  198. package/examples/rc2d/GAMEMAP.md +1 -1
  199. package/examples/rc2d/rc2d.js +1 -1
  200. package/examples/styletest/.threedog/content-index.json +1 -1
  201. package/examples/styletest/GAMEMAP.md +3 -3
  202. package/examples/webgpu-tsl/GAMEMAP.md +1 -1
  203. package/examples/world/.threedog/content-index.json +1 -1
  204. package/examples/world/GAMEMAP.md +5 -4
  205. package/examples/world/main.js +3 -3
  206. package/index.d.ts +8 -5
  207. package/index.js +22 -1
  208. package/llms.txt +2 -1
  209. package/modules/ambience/Ambience.js +5 -3
  210. package/modules/calendar/index.js +7 -5
  211. package/modules/camera/FirstPersonCamera.js +3 -3
  212. package/modules/camera/FixedCamera.js +34 -20
  213. package/modules/camera/FollowCamera.js +20 -11
  214. package/modules/camera/RtsCamera.js +1 -0
  215. package/modules/camera/common.js +33 -22
  216. package/modules/camera/pixelSnap.js +62 -0
  217. package/modules/characters/Character.js +136 -43
  218. package/modules/characters/NPC.js +60 -28
  219. package/modules/characters/assetModel.js +2 -2
  220. package/modules/characters/astar.js +47 -28
  221. package/modules/characters/character.contract.js +21 -0
  222. package/modules/characters/contract.js +17 -3
  223. package/modules/characters/index.js +94 -34
  224. package/modules/characters/moveHelpers.js +80 -15
  225. package/modules/characters/mover.contract.js +14 -0
  226. package/modules/characters/movers/common.js +6 -4
  227. package/modules/characters/movers/rapier.js +12 -5
  228. package/modules/characters/movers/simple.js +25 -12
  229. package/modules/characters/movers/support.js +18 -7
  230. package/modules/characters/npcAvoid.js +15 -12
  231. package/modules/characters/npcSim.js +75 -25
  232. package/modules/characters/npcView.js +13 -6
  233. package/modules/characters/pathAsync.js +74 -24
  234. package/modules/characters/pathJob.js +38 -21
  235. package/modules/characters/player.js +59 -47
  236. package/modules/characters/seat.js +56 -0
  237. package/modules/characters/vehicle.contract.js +8 -5
  238. package/modules/characters/walkTo.js +31 -18
  239. package/modules/collision/Collision.js +44 -26
  240. package/modules/collision/contract.js +2 -2
  241. package/modules/collision/grid.js +6 -1
  242. package/modules/content/explain.js +1 -1
  243. package/modules/content/fields.js +3 -3
  244. package/modules/content/ids.js +3 -1
  245. package/modules/content/index.js +83 -27
  246. package/modules/content/loader.js +110 -130
  247. package/modules/content/markers.js +1 -1
  248. package/modules/content/models.js +48 -14
  249. package/modules/content/packs.js +2 -1
  250. package/modules/content/places.js +5 -4
  251. package/modules/content/props.js +8 -6
  252. package/modules/content/rules.js +29 -47
  253. package/modules/content/templates.js +66 -35
  254. package/modules/content/words.js +19 -6
  255. package/modules/debug/DebugPanel.js +4 -2
  256. package/modules/flow/contract.js +1 -0
  257. package/modules/flow/index.js +24 -14
  258. package/modules/gameplay/Container.js +5 -2
  259. package/modules/gameplay/Containers.js +9 -1
  260. package/modules/gameplay/Dialogue.js +82 -25
  261. package/modules/gameplay/Interactions.js +61 -32
  262. package/modules/gameplay/Inventory.js +56 -13
  263. package/modules/gameplay/Quests.js +133 -24
  264. package/modules/gameplay/boxOps.js +7 -0
  265. package/modules/gameplay/dialogueBubbles.js +14 -9
  266. package/modules/gameplay/inventoryOps.js +11 -7
  267. package/modules/gameplay/pickups.js +43 -16
  268. package/modules/gameplay/questLog.js +4 -2
  269. package/modules/gameplay/questSave.js +6 -1
  270. package/modules/gameplay/quests.contract.js +1 -1
  271. package/modules/grid/Grid.js +1 -1
  272. package/modules/grid/Layer.js +8 -4
  273. package/modules/grid/index.js +21 -15
  274. package/modules/grid/ops.js +43 -46
  275. package/modules/grid/tiles.js +1 -1
  276. package/modules/hlod/index.js +6 -3
  277. package/modules/hud/index.js +6 -4
  278. package/modules/hud/parts.js +4 -4
  279. package/modules/level/contract.js +2 -2
  280. package/modules/level/heightfield.js +17 -21
  281. package/modules/level/index.js +83 -26
  282. package/modules/level/load.js +165 -48
  283. package/modules/level/nodes.js +34 -16
  284. package/modules/lights/index.js +6 -3
  285. package/modules/lights/sources.js +3 -1
  286. package/modules/music/Music.js +4 -2
  287. package/modules/nav/contract.js +7 -5
  288. package/modules/nav/index.js +174 -44
  289. package/modules/nav/navPath.js +45 -10
  290. package/modules/net/index.js +1 -1
  291. package/modules/particles/Particles.js +85 -22
  292. package/modules/particles/effect.js +80 -28
  293. package/modules/particles/shaders.js +17 -0
  294. package/modules/photo/Photo.js +12 -10
  295. package/modules/rigid/RigidBodies.js +200 -57
  296. package/modules/rigid/Vehicles.js +15 -5
  297. package/modules/rigid/collider3d.contract.js +26 -0
  298. package/modules/rigid/ragdoll.js +55 -44
  299. package/modules/rigid/ragdollBones.js +83 -33
  300. package/modules/rigid/refresh.js +10 -0
  301. package/modules/rigid/sync.js +46 -15
  302. package/modules/settings/Settings.js +84 -37
  303. package/modules/settings/apply.js +15 -8
  304. package/modules/settings/sections.js +7 -4
  305. package/modules/settings/strings.js +2 -2
  306. package/modules/sky/skyModule.js +3 -1
  307. package/modules/swarm/Swarm.js +16 -6
  308. package/modules/terrain/ChunkManager.js +10 -16
  309. package/modules/terrain/index.js +17 -11
  310. package/modules/terrain/terrainEdit.js +13 -2
  311. package/modules/terrain/terrainGen.js +5 -3
  312. package/modules/terrain/terrainShape.js +1 -1
  313. package/modules/timeline/Timeline.js +58 -26
  314. package/modules/timeline/Tween.js +19 -13
  315. package/modules/timeline/shots.js +19 -10
  316. package/modules/triggers/index.js +87 -20
  317. package/modules/vegetation/Vegetation.js +4 -3
  318. package/modules/vegetation/draw.js +16 -0
  319. package/modules/vegetation/groundChunks.js +10 -7
  320. package/modules/vegetation/index.js +30 -7
  321. package/modules/water/Water.js +6 -2
  322. package/modules/weather/Weather.js +16 -15
  323. package/modules/weather/weatherDraw.js +7 -6
  324. package/modules/world/World.js +20 -7
  325. package/modules/world/explain.js +1 -1
  326. package/modules/world/index.js +13 -6
  327. package/modules/world/persist.js +23 -8
  328. package/modules/world/pos.js +4 -4
  329. package/modules/world/records.js +13 -7
  330. package/modules/world/sim.js +74 -23
  331. package/modules/world/simFar.js +2 -2
  332. package/modules/world/state.js +31 -6
  333. package/modules/world/thingSource.js +16 -3
  334. package/modules/world/views.js +19 -8
  335. package/package.json +7 -1
  336. package/render/PostFX.js +47 -29
  337. package/render/backend.js +5 -1
  338. package/render/fx/particles.tsl.js +8 -6
  339. package/render/fx/postWebGPU.tsl.js +3 -3
  340. package/render/layers.js +1 -1
  341. package/render/lightmap.js +23 -3
  342. package/render/occlusion.js +43 -12
  343. package/render/patches.js +2 -2
  344. package/render/postWebGL.js +4 -3
  345. package/render/probes.js +25 -0
  346. package/render/shadows.js +2 -2
  347. package/types/core.d.ts +142 -55
  348. package/types/gameplay.d.ts +92 -40
  349. package/types/generated/core/base/I18n.d.ts +2 -2
  350. package/types/generated/core/input/Input.d.ts +16 -2
  351. package/types/generated/core/input/inputSeat.d.ts +26 -0
  352. package/types/generated/core/inspect/DebugOverrides.d.ts +15 -1
  353. package/types/generated/core/ops/Ops.d.ts +2 -1
  354. package/types/generated/core/ops/control.d.ts +12 -2
  355. package/types/generated/core/saves/Saves.d.ts +26 -6
  356. package/types/generated/core/saves/session.d.ts +1 -1
  357. package/types/generated/core/scene/Views.d.ts +1 -1
  358. package/types/generated/core/stream/Stream.d.ts +6 -4
  359. package/types/generated/modules/grid/Grid.d.ts +1 -0
  360. package/types/generated/modules/particles/Particles.d.ts +4 -3
  361. package/types/generated/modules/timeline/Timeline.d.ts +5 -4
  362. package/types/generated/modules/weather/Weather.d.ts +1 -7
  363. package/types/generated/modules/world/World.d.ts +6 -4
  364. package/types/generated/render/PostFX.d.ts +6 -14
  365. package/types/nav.d.ts +36 -4
  366. package/types/physics.d.ts +55 -7
  367. package/types/pixel.d.ts +75 -0
  368. package/types/world.d.ts +14 -8
  369. package/ui/Parts.js +9 -2
  370. package/ui/theme.js +2 -2
  371. package/core/scene/engineCamera.js +0 -32
  372. package/modules/camera/projection.js +0 -21
@@ -10,28 +10,43 @@
10
10
  // Several tabs of one game share the storage. Each write carries a rev; a tab overwrites a slot only while the stored rev is the one it last read,
11
11
  // wrote or loaded (compare-and-write in one IndexedDB transaction), so a forgotten tab's autosave can never replace newer progress made in another
12
12
  // tab: that save is refused (false, toast, save-stale). A BroadcastChannel tells the other tabs a slot changed, so their list / load see it at once.
13
+ // remove deletes the save this tab lists and no newer one. Attachments carry a rev too: a tab changes one only if it wrote it or saw it (at boot, or by reading attachments).
13
14
  /** @import { SaveProvider } from '../../types/core' */
14
15
  import { SaveStore } from './SaveStore.js';
15
16
  import { checkTypeRule } from '../engine/moduleTypes.js';
16
17
  import { toast } from '../../ui/UI.js';
17
- import { warnOnce, fmt } from '../base/validate.js';
18
- import { readParams, keysSchema } from '../base/params.js';
18
+ import { DEV, warnOnce, fmt } from '../base/validate.js';
19
+ import { readParams } from '../base/params.js';
19
20
  import { reportError } from '../base/errors.js';
20
21
  import { codedError, coded } from '../base/errorHints.js';
21
22
  import { checkPartVersion, readSave } from './saveVersions.js';
22
23
  import { exportSaveFile, importSaveFile, importText, SAVE_STRINGS } from './saveFiles.js';
23
- import { applySave, loadSlot, adoptPart, collectParts } from './saveApply.js';
24
+ import { applyAnnounced, loadSlot, adoptPart, collectParts, partData } from './saveApply.js';
24
25
  import { autosaveHook } from './session.js';
26
+ import { StateReplace } from './stateReplace.js';
25
27
 
26
28
 
27
29
  // Developer messages (console text for developers, never shown in the game UI)
28
30
  const DEV_STRINGS = {
31
+ keyTaken: "saves.register('{key}'): the key already has an owner, whose part would stop being saved",
29
32
  saveThrew: "save() of save part '{k}' threw ({msg}); slot '{slot}' was not written and keeps its previous save",
30
33
  stale: "[saves] slot '{slot}' was not written: another tab or window of this game saved it after this one last loaded or saved it, and overwriting would lose that newer progress. This tab now lists the newer save; load it to continue from it, or save into another slot",
31
34
  noIdb: '[saves] IndexedDB is unavailable (possibly private mode); saves fall back to localStorage (about 5MB cap) and attachments (such as photos) will not be saved.',
35
+ staleRemove: "[saves] slot '{slot}' was not deleted: another tab or window of this game saved it after this one last saw it. This tab lists that save again",
36
+ staleBlob: "[saves] attachment '{group}/{id}' was not changed: another tab or window of this game wrote it after this one last saw it. Read saves.attachments('{group}') first, or use another id",
37
+ busy: 'saves.collect() was called during a load, so it would hold half of each state. Wait for the load, or use saves.save, which waits by itself',
38
+ owner: "saves.register('{key}'): that key already has a part, and this one takes it over: the first owner's data is no longer saved. Remove the first part, or use another key",
32
39
  autosave: 'saves.autosave(minutes): minutes must be a positive number of minutes of play, got {got}',
40
+ protoName: "saves.register('__proto__'): a save cannot hold a part with this name (assigning it swaps the parts object's prototype, and save text drops it on reading), so its data would be lost without a word. Pick another name",
33
41
  };
34
42
 
43
+ /** What saves.register takes: without a working save and load the failure would wait for the player's first save or load */
44
+ const PROVIDER = { save: 'function', load: 'function', first: 'any?', version: 'any?', migrate: 'any?', atomic: 'any?', notAtomic: 'string?', checkNewGame: 'any?' };
45
+
46
+ /** Save data as a save file would hold it: no reference into the part's live state stays behind */
47
+ const copyData = d => JSON.parse(JSON.stringify(d));
48
+ const blobKey = (group, id) => `${group}\0${id}`;
49
+
35
50
  /** engine.saves handles saving. Each module registers "how to save and load"; supports multiple slots, autosave and export / import. */
36
51
  export class Saves {
37
52
  /** @internal */
@@ -40,12 +55,14 @@ export class Saves {
40
55
  /** @internal Start of the key names in the localStorage fallback and of the IndexedDB database name; a module asks storageKey(name) instead */
41
56
  this._prefix = prefix + 'save-';
42
57
  /** @internal */ this.providers = new Map();
58
+ /** @internal the one rule every state replacement goes through */ this._replace = new StateReplace(engine);
43
59
  /** @internal */ this._auto = null;
44
60
  /** @internal Slot -> JSON text (all saves stay in memory: list / check / export are synchronous) */ this._json = new Map();
45
61
  /** @internal Slot -> savedAt */ this._meta = new Map();
46
62
  /** @internal Disk-write queue: earlier saves are written first */ this._queue = Promise.resolve();
47
63
  /** @internal Slot -> rev of the copy in memory (a slot without a record is absent) */ this._rev = new Map();
48
64
  /** @internal Slot -> rev this tab may overwrite: the one it read at boot, last wrote or last loaded (absent = expects no record) */ this._mine = new Map();
65
+ /** @internal Attachment (blobKey) -> rev this tab last wrote or saw: what it may change */ this._blobRevs = new Map();
49
66
  /** @internal This tab's writer id (revs are `<tab>:<n>`); not gameplay and never in the save text, so saves stay reproducible */
50
67
  this._tab = globalThis.crypto?.randomUUID?.() ?? `${Date.now()}-${performance.now()}`; // wall-clock: only a fallback id, unique per tab
51
68
  /** @internal */ this._n = 0;
@@ -73,12 +90,16 @@ export class Saves {
73
90
  * version (default 1): raise it by 1 whenever what save() returns changes shape, and add migrate[oldVersion] = data => newData; load sees only the current
74
91
  * shape.
75
92
  * A save whose part is newer than this build's version is refused as a whole (load returns false, the save is kept).
76
- * A part registered after a save was loaded (a module installed later) is handed its data from that save at once.
93
+ * load(data, turn): turn is this replacement's identity. Pass it on, level.load(x, { turn }) or content.load(x, { turn }): those wait for a running load to end, except with its turn.
94
+ * A part registered after a save was loaded (a module installed later) is handed its data from that save: at once when idle, else right after the replacement under way.
77
95
  * atomic: true joins this part to atomic ops: it is copied before an atomic op runs and put back if the op fails (plain data only; afterLoad does not run on rollback).
78
96
  * checkNewGame(data): dev only, called once start() finished with this part's data in the new-game state, to warn about what should not be there yet
79
97
  * (world: records placed by code instead of content). The part knows its own format; core only hands the data over.
98
+ * Returns a handle: remove() takes the part out and keeps its data as unattached data (it rides in later saves and goes back to a part registered under
99
+ * the key later), without holding on to the part's closures. remove({ keep: false }) gives back only what the part took over at register: for a part that never ran.
80
100
  * @param {string} key
81
101
  * @param {SaveProvider} provider
102
+ * @returns {{ remove(o?: { keep?: boolean }): void }}
82
103
  * @example
83
104
  * engine.saves.register('garden', { save: () => garden.toJSON(), load: d => garden.fromJSON(d) });
84
105
  * // later the format gains beds: version 2, and a step that upgrades version-1 data
@@ -86,12 +107,26 @@ export class Saves {
86
107
  */
87
108
  register(key, provider) {
88
109
  checkTypeRule(this.engine, 'saves.register', `registered save part '${key}'`);
89
- readParams(`saves.register('${key}')`, keysSchema(['save', 'load', 'first', 'version', 'migrate', 'atomic', 'checkNewGame']), provider);
110
+ // told, not taken: the first owner would stop being saved with nothing said. A module that goes gives the key back first (ctx.saves.register), so a swap never lands here
111
+ if (this.providers.has(key)) throw codedError('save-key-taken', fmt(DEV_STRINGS.keyTaken, { key }));
112
+ readParams(`saves.register('${key}')`, PROVIDER, provider);
113
+ if (key === '__proto__') throw codedError('module-params', DEV_STRINGS.protoName);
90
114
  const { save, load, first = false, version = 1, migrate = {}, atomic = false, checkNewGame = null } = provider;
91
115
  checkPartVersion(key, version, migrate);
92
- this.providers.set(key, { save, load, first, version, migrate, atomic: atomic === true, checkNewGame });
116
+ const f = this._foreign, held = Object.hasOwn(f.parts, key) ? { data: copyData(f.parts[key]), version: f.versions[key] ?? 1 } : null;
117
+ const part = { save, load, first, version, migrate, atomic: atomic === true, checkNewGame };
118
+ if (DEV && this.providers.has(key)) warnOnce(fmt(DEV_STRINGS.owner, { key }), `save-owner-${key}`); // the newer owner takes it, as a replaced module does; the older one stops being saved
119
+ this.providers.set(key, part);
93
120
  this.engine.session._late(key); // a part registered after start() (a module installed later) joins the new-game state as it is now
94
- if (key in this._foreign.parts) adoptPart(this, key);
121
+ if (held) adoptPart(this, key);
122
+ return { remove: ({ keep = true } = {}) => {
123
+ if (this.providers.get(key) !== part) return; // a stale handle: the key belongs to someone newer
124
+ this.providers.delete(key);
125
+ let left = held;
126
+ if (keep && !Object.hasOwn(this._foreign.parts, key)) try { const d = partData(key, part); left = d == null ? null : { data: copyData(d), version }; }
127
+ catch (err) { reportError(this.engine, err, `save() of part '${key}' while it was removed`, { soft: true }); }
128
+ if (left) { this._foreign.parts[key] = left.data; this._foreign.versions[key] = left.version; }
129
+ } };
95
130
  }
96
131
  /**
97
132
  * The save versions this build reads, per part: { world: 1, clock: 1, ... }. A save whose part is newer is refused; an older one is migrated.
@@ -109,6 +144,7 @@ export class Saves {
109
144
  this._rev.set(r.slot, r.rev ?? ''); this._mine.set(r.slot, r.rev ?? ''); // also for a save made before this ran: its write comes after and expects this record
110
145
  if (!this._json.has(r.slot)) { this._json.set(r.slot, r.json); this._meta.set(r.slot, r.savedAt); }
111
146
  }
147
+ this._sawBlobs(await this.store.blobs());
112
148
  } catch (e) { this._fail(e); }
113
149
  }
114
150
  /** @internal Disk writes run in call order once storage is ready, and flush waits for them: the one place that order is kept */
@@ -127,6 +163,7 @@ export class Saves {
127
163
  /**
128
164
  * Store a binary attachment outside the world save (a photo, a replay). It rides in the queue of save writes, so flush() waits for it, and exportFile() carries it.
129
165
  * Pass a function to make the bytes when the write runs: flush() then waits for that too. Without IndexedDB it is not kept.
166
+ * Rejects with save-stale, changing nothing, when another tab wrote this id since this tab last saw it; attachments(group) is how a tab looks.
130
167
  * @example await engine.saves.putAttachment('replay', 'run-1', blob, { score: 12 });
131
168
  * @param {string} group what the attachment is for
132
169
  * @param {string} id unique inside the group; the same id replaces
@@ -136,17 +173,31 @@ export class Saves {
136
173
  * @experimental
137
174
  */
138
175
  putAttachment(group, id, blob, meta) {
139
- return this._enqueue(async () => this.store.putBlob(group, id, typeof blob === 'function' ? await blob() : blob, meta));
176
+ return this._enqueue(async () => {
177
+ const key = blobKey(group, id), rev = this._newRev();
178
+ await this.store.putBlobIf({ group, id, blob: typeof blob === 'function' ? await blob() : blob, meta: meta ?? null, at: Date.now(), rev }, this._blobRevs.get(key) ?? null).catch(e => this._blobStale(e, group, id)); // wall-clock: when the attachment was stored, used for ordering
179
+ this._blobRevs.set(key, rev);
180
+ });
181
+ }
182
+ /** Delete an attachment; no such id is fine. Rejects with save-stale as putAttachment does @param {string} group @param {string} id @returns {Promise<void>} @experimental */
183
+ removeAttachment(group, id) {
184
+ return this._enqueue(async () => {
185
+ const key = blobKey(group, id);
186
+ await this.store.deleteBlobIf(group, id, this._blobRevs.get(key) ?? null).catch(e => this._blobStale(e, group, id));
187
+ this._blobRevs.delete(key);
188
+ });
140
189
  }
141
- /** Delete an attachment; no such id is fine @param {string} group @param {string} id @returns {Promise<void>} @experimental */
142
- removeAttachment(group, id) { return this._enqueue(() => this.store.deleteBlob(group, id)); }
190
+ /** @internal */
191
+ _blobStale(e, group, id) { throw e?.stale !== undefined ? codedError('save-stale', fmt(DEV_STRINGS.staleBlob, { group, id })) : e; }
192
+ /** @internal This tab has looked at these rows: it may change them */
193
+ _sawBlobs(rows) { for (const b of rows) if (b.rev != null) this._blobRevs.set(blobKey(b.group, b.id), b.rev); return rows; }
143
194
  /**
144
195
  * The attachments of a group, once storage is ready. Empty without IndexedDB.
145
196
  * @param {string} group
146
197
  * @returns {Promise<{ group: string, id: string, at: number, blob: Blob, meta: any }[]>}
147
198
  * @experimental
148
199
  */
149
- async attachments(group) { await this.whenReady; return this.store.blobs(group); }
200
+ async attachments(group) { await this.whenReady; return this._sawBlobs(await this.store.blobs(group)); }
150
201
  /**
151
202
  * A localStorage key for what belongs to this game but is not a save (settings, a last-used tab): it shares the game's name, so two games on one site stay apart, and stays out of list().
152
203
  * @example localStorage.setItem(engine.saves.storageKey('lastTab'), 'map');
@@ -162,9 +213,11 @@ export class Saves {
162
213
  /**
163
214
  * Collect the data of every part (does not write to the browser): { format, savedAt, versions, parts }.
164
215
  * A part whose save() throws is left out and reported (engine.error in dev); save() instead refuses to write such a save.
216
+ * Throws while a load is under way: what it would return is half of each state. saves.save waits instead.
165
217
  * @returns {{ format: number, savedAt: number, versions: Record<string, number>, parts: Record<string, any> }}
166
218
  */
167
219
  collect() {
220
+ if (this.replacing) throw codedError('save-busy', DEV_STRINGS.busy);
168
221
  const { data, failed } = this._collect();
169
222
  for (const [k, e] of failed) reportError(this.engine, e, `save() of save part '${k}'`);
170
223
  return data;
@@ -188,35 +241,62 @@ export class Saves {
188
241
  * The pre-load state is a copy (structuredClone) of every part's save(), so save() may return the live object load() writes into; a part whose
189
242
  * data cannot be copied makes apply refuse (false) before anything changes.
190
243
  * The state changes synchronously unless a part's load is async; only the result is a Promise.
244
+ * One replacement runs at a time: asked for while a load, newGame or quit is under way, this waits its turn, then reads the data and takes its
245
+ * rollback point. On the line after a synchronous apply it is not waiting on anything yet, so it applies at once and takes over the afterLoad.
246
+ * Inside a part's load() or an afterLoad it starts after they return, so do not await it there.
247
+ * On success 'save:loaded' fires with slot, as for saves.load: what the game does not save (a walk) ends on it, and derived state rebuilds.
191
248
  * @param {any} data
192
- * @param {string} [slot] for messages only
249
+ * What goes around it is the same for every door (core/saves/session.js): 'save:loaded' fires with `slot`, the title closes; a rollback fires 'session:failed' { kind: 'quick', slot }.
250
+ * @param {string} [slot] for messages and the event
193
251
  * @returns {Promise<boolean>}
194
252
  */
195
- apply(data, slot = '(data)') { return applySave(this, data, slot); }
253
+ apply(data, slot = '(data)') { return this._replace.run(null, () => applyAnnounced(this, data, slot)); }
254
+
255
+ /**
256
+ * @internal True while the game state is being replaced: from reading a save through its parts, the modules' afterLoad and any rollback. Ops refuse with
257
+ * code 'loading' for that whole span; any other freeze (a menu) does not stop them.
258
+ * @type {boolean}
259
+ */
260
+ get replacing() { return this._replace.replacing; }
261
+ /**
262
+ * @internal Which saved state the game holds (StateReplace.generation). Code that waits and then writes takes it when asked and writes only if it is unchanged;
263
+ * read it with replacing off when a load that fails must not count.
264
+ * @type {number}
265
+ */
266
+ get generation() { return this._replace.generation; }
267
+ /** @internal Resolves once every replacement already in line ended, so generation says how it went: a load under way may still fail and give this state back */
268
+ settled() { return this._replace.read(async () => {}); }
196
269
  /** @internal Put a save in memory and queue the disk write; returns Promise<boolean> (write succeeded) */
197
270
  _put(slot, json, savedAt) {
198
- const prev = this._json.get(slot), prevAt = this._meta.get(slot), rev = `${this._tab}:${++this._n}`;
271
+ const rev = this._newRev();
199
272
  this._json.set(slot, json); this._meta.set(slot, savedAt);
200
273
  // expect is read when the write runs, not now: an earlier queued save of this tab moves _mine first
201
274
  return this._enqueue(() => this.store.putSlot(slot, savedAt, json, rev, this._mine.get(slot) ?? null)).then(() => {
202
275
  this._rev.set(slot, rev); this._mine.set(slot, rev);
203
276
  this._tell(slot);
204
277
  return true;
205
- }, e => {
278
+ }, async e => {
206
279
  if (e?.stale !== undefined) { // another tab wrote it: memory shows that newer save (list / load offer it); this playthrough is not written
207
280
  if (this._json.get(slot) === json) this._show(slot, e.stale);
208
281
  warnOnce(coded('save-stale', fmt(DEV_STRINGS.stale, { slot })));
209
282
  toast(this.engine, this.engine.t('saves.otherTab', { slot }), { kind: 'error', ms: 6000 });
210
283
  return false;
211
284
  }
212
- // the disk still holds the previous save, so memory goes back to it (unless a later save already replaced this one):
213
- // list / load / continue never offer a save that is not stored
214
- if (this._json.get(slot) === json) {
215
- if (prev == null) { this._json.delete(slot); this._meta.delete(slot); } else { this._json.set(slot, prev); this._meta.set(slot, prevAt); }
216
- }
285
+ await this._showStored(slot, () => this._json.get(slot) === json);
217
286
  this._fail(e, slot); return false;
218
287
  });
219
288
  }
289
+ /**
290
+ * @internal A write the store refused: memory goes back to what the disk holds (unless a later save already replaced what failed, which still() tells), so list / load / continue
291
+ * never disagree with it. Read, not remembered: the text before may be a queued save that failed too
292
+ */
293
+ async _showStored(slot, still) {
294
+ if (!still()) return;
295
+ const stored = await this.store.getSlot(slot).catch(() => null);
296
+ if (still()) this._show(slot, stored);
297
+ }
298
+ /** @internal */
299
+ _newRev() { return `${this._tab}:${++this._n}`; }
220
300
  /** @internal Memory shows a stored record (null = none); a stored record leaves the rev this tab may overwrite as it was */
221
301
  _show(slot, r) {
222
302
  if (!r) { this._json.delete(slot); this._meta.delete(slot); this._rev.delete(slot); this._mine.delete(slot); return; } // deleted: no newer progress to protect, so the next save may write
@@ -235,13 +315,16 @@ export class Saves {
235
315
  * Save into a slot (default 'auto'). Returns Promise<boolean>
236
316
  * (resolves after the write to IndexedDB: true on success, false with a toast and console error on failure).
237
317
  * The in-memory save updates immediately, so a following load / list / export sees it at once; the 'save:written' event fires only after the write succeeds.
238
- * If any part's save() throws, nothing is written and the slot keeps its previous save (false). A failed write keeps the previous save too.
318
+ * Asked for while a load, newGame or quit is under way, it waits for that to end and saves the result: a save never holds half of each state.
319
+ * If any part's save() throws, or its data holds NaN or Infinity at any depth (the message names the part and the path), nothing is written and the slot keeps its previous save (false). A failed write keeps the previous save too.
239
320
  * Show "saved" only after the result is true.
240
321
  * @param {string} [slot]
241
322
  * @returns {Promise<boolean>}
242
323
  * @example if (await engine.saves.save('slot1')) toast(engine, 'Saved'); // on false the engine already showed why
243
324
  */
244
- save(slot = 'auto') {
325
+ save(slot = 'auto') { return this._replace.read(() => this._save(slot)); }
326
+ /** @internal save, in a moment no replacement is under way */
327
+ _save(slot) {
245
328
  let data, json;
246
329
  try {
247
330
  const r = this._collect();
@@ -264,20 +347,30 @@ export class Saves {
264
347
  * @returns {Promise<boolean>}
265
348
  * @example if (!(await engine.saves.load('quick'))) toast(engine, 'No quick save');
266
349
  */
267
- load(slot = 'auto') { return this._load(slot); }
268
- /** @internal Load a slot; with base (a collect() result) the save goes on top of it, so a part missing from the save gets base's state (session.load) */
350
+ load(slot = 'auto') { return this._replace.run(null, () => this._load(slot)); }
351
+ /** @internal Load a slot inside a turn already taken; with base (a collect() result) the save goes on top of it, so a part missing from the save gets base's state (session.load) */
269
352
  _load(slot, base) { return loadSlot(this, slot, base); }
270
353
  /** All slots, newest first (synchronous, reads the in-memory index) @returns {{ slot: string, savedAt: number }[]} */
271
354
  list() {
272
355
  return [...this._meta].map(([slot, savedAt]) => ({ slot, savedAt })).sort((a, b) => b.savedAt - a.savedAt);
273
356
  }
274
- /** Delete a slot. Returns a Promise (disk write done); awaiting is optional @param {string} slot @returns {Promise<void>} */
357
+ /**
358
+ * Delete a slot. Returns a Promise (disk write done); awaiting is optional. A newer save another tab wrote meanwhile is kept: the slot lists again, with a toast (save-stale).
359
+ * A delete the store refused lists the slot again too, with a toast.
360
+ * @param {string} slot @returns {Promise<void>}
361
+ */
275
362
  remove(slot) {
276
363
  this._json.delete(slot); this._meta.delete(slot);
277
364
  // the revs are cleared when the delete runs, not now: a save queued before this remove sets _mine when its write lands,
278
365
  // and a _mine left over for a deleted record would refuse every later save of this slot as "another tab saved"
279
- return this._enqueue(async () => { await this.store.deleteSlot(slot); this._rev.delete(slot); this._mine.delete(slot); })
280
- .then(() => this._tell(slot), e => this._fail(e, slot));
366
+ // what it expects is what this tab lists (_rev): a save the note from another tab brought in is the player's to delete
367
+ return this._enqueue(async () => { await this.store.deleteSlot(slot, this._rev.get(slot) ?? null); this._rev.delete(slot); this._mine.delete(slot); })
368
+ .then(() => this._tell(slot), async e => {
369
+ if (e?.stale === undefined) { await this._showStored(slot, () => !this._json.has(slot)); return this._fail(e, slot); }
370
+ if (!this._json.has(slot)) this._show(slot, e.stale);
371
+ warnOnce(coded('save-stale', fmt(DEV_STRINGS.staleRemove, { slot })));
372
+ toast(this.engine, this.engine.t('saves.otherTabKept', { slot }), { kind: 'error', ms: 6000 });
373
+ });
281
374
  }
282
375
  /** Export as a piece of text (can be copied as a backup; synchronous, without binary attachments) @param {string} [slot] @returns {string} @experimental */
283
376
  export(slot = 'auto') { try { return btoa(unescape(encodeURIComponent(this._json.get(slot) || ''))); } catch { return ''; } }
@@ -330,3 +423,5 @@ export class Saves {
330
423
  /** @internal Stop autosave (called by engine.dispose) */
331
424
  dispose() { this._auto?.remove(); this._bc?.close(); this._bc = null; this._queue.finally(() => this.store.close()); } // close the database only after queued writes finish
332
425
  }
426
+
427
+ export const handRolled = [{ kind: 'save', seen: 'a save of its own in localStorage', use: "engine.saves: autosave(minutes), register('game', { version: 1, save, load }), and Continue on the start screen (recipe 63); versions, slots and a corrupt save are handled", quiet: /\bengine\.saves\b/, code: /\blocalStorage\.setItem\s*\(/, notRaw: /setItem\s*\(\s*(?![^,)]*(?:save|progress))[^,)]*(?:volume|mute|lang|locale|theme|music|sfx|quality|sensitiv|brightness|fullscreen|tutorial|dismiss|setting|pref|option|keybind)/i }];