threedog 1.1.0 → 1.3.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 (370) hide show
  1. package/CHANGELOG.md +893 -798
  2. package/README.md +1 -1
  3. package/core/assets/Animator.js +41 -3
  4. package/core/assets/Assets.js +100 -24
  5. package/core/assets/assetEntry.js +73 -20
  6. package/core/assets/assetHot.js +68 -16
  7. package/core/assets/assetLoad.js +6 -6
  8. package/core/assets/assetLod.js +9 -2
  9. package/core/assets/assetManifest.js +12 -2
  10. package/core/assets/assetPart.js +54 -0
  11. package/core/assets/ik.js +271 -0
  12. package/core/assets/modelNeeds.js +37 -0
  13. package/core/assets/namedModel.js +102 -29
  14. package/core/assets/nodeVisibility.js +15 -0
  15. package/core/audio/Audio.js +36 -4
  16. package/core/audio/audioReverb.js +99 -0
  17. package/core/audio/audioRules.js +1 -1
  18. package/core/audio/audioVoice.js +1 -1
  19. package/core/base/Events.js +14 -4
  20. package/core/base/Random.js +1 -1
  21. package/core/base/Vars.js +1 -1
  22. package/core/base/docRef.js +51 -0
  23. package/core/base/errorCodes.js +187 -126
  24. package/core/base/errorHints.js +9 -7
  25. package/core/base/errors.js +25 -10
  26. package/core/base/events.generated.js +2 -0
  27. package/core/base/freeParts.js +76 -0
  28. package/core/base/math.js +28 -0
  29. package/core/base/sections.js +5 -5
  30. package/core/base/validate.js +31 -3
  31. package/core/engine/Engine.js +17 -7
  32. package/core/engine/Loading.js +5 -3
  33. package/core/engine/copies.js +1 -1
  34. package/core/engine/headlessLoad.js +4 -1
  35. package/core/engine/lifecycle.js +32 -16
  36. package/core/engine/loop.js +71 -27
  37. package/core/engine/moduleSlots.js +2 -2
  38. package/core/engine/moduleTypes.js +3 -3
  39. package/core/engine/modules.js +65 -39
  40. package/core/engine/page.js +6 -3
  41. package/core/engine/services.js +6 -5
  42. package/core/engine/startup.js +8 -7
  43. package/core/input/Input.js +28 -14
  44. package/core/input/inputContext.js +28 -16
  45. package/core/input/inputKeyboard.js +31 -3
  46. package/core/input/inputPad.js +4 -0
  47. package/core/input/inputPointer.js +2 -1
  48. package/core/input/inputSeat.js +1 -1
  49. package/core/inspect/Budget.js +109 -19
  50. package/core/inspect/DebugOverrides.js +28 -4
  51. package/core/inspect/Describe.js +17 -9
  52. package/core/inspect/Inspect.js +4 -2
  53. package/core/inspect/InspectMaterials.js +3 -1
  54. package/core/inspect/InspectPerf.js +19 -9
  55. package/core/inspect/InspectScene.js +32 -7
  56. package/core/inspect/MaterialInfo.js +19 -2
  57. package/core/inspect/UrlState.js +50 -28
  58. package/core/inspect/catalog.js +28 -9
  59. package/core/inspect/debugView.js +2 -1
  60. package/core/inspect/describeRender.js +25 -13
  61. package/core/inspect/describeText.js +14 -6
  62. package/core/inspect/lightWatch.js +1 -1
  63. package/core/inspect/metadata.generated.js +35 -17
  64. package/core/inspect/pictureChecks.js +148 -0
  65. package/core/inspect/pictureMenu.js +84 -0
  66. package/core/inspect/pictureWriters.js +26 -6
  67. package/core/inspect/textureBytes.js +12 -2
  68. package/core/inspect/toolDoor.js +2 -4
  69. package/core/ops/Ops.js +11 -4
  70. package/core/ops/holds.js +27 -10
  71. package/core/ops/opsAtomic.js +15 -7
  72. package/core/ops/opsGuard.js +2 -2
  73. package/core/ops/opsRun.js +8 -7
  74. package/core/ops/sharedPoint.js +72 -21
  75. package/core/ops/stacks.js +56 -16
  76. package/core/saves/SaveStore.js +9 -3
  77. package/core/saves/Saves.js +32 -23
  78. package/core/saves/saveApply.js +96 -44
  79. package/core/saves/saveIds.js +1 -1
  80. package/core/saves/saveVersions.js +7 -5
  81. package/core/saves/session.js +17 -8
  82. package/core/saves/stateReplace.js +34 -15
  83. package/core/scene/Rays.js +52 -10
  84. package/core/scene/Views.js +36 -15
  85. package/core/scene/adaptive.js +144 -21
  86. package/core/scene/drawOnly.js +17 -0
  87. package/core/scene/gameLights.js +47 -4
  88. package/core/scene/sceneMethods.js +13 -11
  89. package/core/scene/stepPoses.js +11 -3
  90. package/core/scene/targeting.js +5 -3
  91. package/core/scene/thingOps.js +1 -1
  92. package/core/scene/tier.js +15 -0
  93. package/core/stream/Batching.js +30 -7
  94. package/core/stream/Stream.js +26 -7
  95. package/core/stream/batchGroups.js +2 -2
  96. package/core/stream/chunkStream.js +7 -5
  97. package/core/stream/prepare.js +77 -0
  98. package/core/time/skip.js +3 -1
  99. package/core/time/time.js +4 -2
  100. package/docs/AI.md +82 -83
  101. package/docs/API.md +16 -16
  102. package/docs/CODEMAP.md +17 -11
  103. package/docs/COMMANDS.md +139 -142
  104. package/docs/CONVENTIONS.md +37 -49
  105. package/docs/MIGRATING-0.8.md +2 -2
  106. package/docs/MIGRATING-1.0.md +2 -2
  107. package/docs/THREE.md +30 -35
  108. package/docs/api/assets.md +3 -1
  109. package/docs/api/audio.md +4 -2
  110. package/docs/api/budget.md +5 -0
  111. package/docs/api/characters.md +10 -8
  112. package/docs/api/collision.md +6 -4
  113. package/docs/api/engine.md +16 -16
  114. package/docs/api/events.md +3 -2
  115. package/docs/api/ground.md +6 -5
  116. package/docs/api/hud.md +4 -2
  117. package/docs/api/input.md +5 -5
  118. package/docs/api/particles.md +2 -1
  119. package/docs/api/photo.md +3 -0
  120. package/docs/api/post.md +7 -4
  121. package/docs/api/quests.md +2 -2
  122. package/docs/api/rays.md +1 -2
  123. package/docs/api/saves.md +7 -7
  124. package/docs/api/settings.md +2 -2
  125. package/docs/api/tools.md +3 -1
  126. package/docs/api/vars.md +1 -1
  127. package/docs/api/vegetation.md +4 -2
  128. package/docs/api/world.md +1 -1
  129. package/docs/recipes/01-new-game.md +16 -17
  130. package/docs/recipes/02-npc.md +22 -18
  131. package/docs/recipes/03-items-pickups.md +37 -35
  132. package/docs/recipes/04-quests.md +15 -10
  133. package/docs/recipes/05-props-bake.md +101 -95
  134. package/docs/recipes/06-clock-events.md +28 -28
  135. package/docs/recipes/07-flow-scenes-pause.md +29 -26
  136. package/docs/recipes/08-weather-sky.md +52 -64
  137. package/docs/recipes/09-materials-lights-models.md +26 -17
  138. package/docs/recipes/10-blender-level.md +15 -10
  139. package/docs/recipes/11-vehicles.md +12 -7
  140. package/docs/recipes/12-navmesh.md +44 -26
  141. package/docs/recipes/13-animation.md +56 -45
  142. package/docs/recipes/14-custom-module.md +21 -18
  143. package/docs/recipes/15-perf.md +61 -55
  144. package/docs/recipes/16-dev-bridge.md +24 -33
  145. package/docs/recipes/18-world.md +36 -42
  146. package/docs/recipes/19-shooting-picking.md +20 -15
  147. package/docs/recipes/20-content-actions-save.md +48 -56
  148. package/docs/recipes/21-camera.md +45 -54
  149. package/docs/recipes/22-shop-gold.md +12 -7
  150. package/docs/recipes/23-ops.md +25 -23
  151. package/docs/recipes/26-ui-parts.md +67 -47
  152. package/docs/recipes/27-net.md +12 -7
  153. package/docs/recipes/28-terrain.md +24 -21
  154. package/docs/recipes/29-grid.md +32 -27
  155. package/docs/recipes/30-templates.md +21 -20
  156. package/docs/recipes/31-audio.md +39 -22
  157. package/docs/recipes/32-action-game.md +19 -14
  158. package/docs/recipes/33-stream-sources.md +15 -11
  159. package/docs/recipes/34-environment-lighting.md +126 -70
  160. package/docs/recipes/35-picture-from-reference.md +8 -8
  161. package/docs/recipes/36-ground-plants.md +27 -21
  162. package/docs/recipes/40-scene.md +19 -28
  163. package/docs/recipes/43-shader-patches-surfaces.md +15 -12
  164. package/docs/recipes/44-water-weather-hooks.md +34 -31
  165. package/docs/recipes/45-cascaded-shadows.md +35 -26
  166. package/docs/recipes/46-blender-art-route.md +7 -2
  167. package/docs/recipes/49-game-module-contract.md +13 -8
  168. package/docs/recipes/50-own-renderer.md +6 -2
  169. package/docs/recipes/51-capability-catalog.md +15 -8
  170. package/docs/recipes/52-around-the-picture.md +34 -32
  171. package/docs/recipes/53-ground-up-close.md +6 -1
  172. package/docs/recipes/55-mods-time-wrap.md +27 -19
  173. package/docs/recipes/56-webgpu-tsl.md +75 -43
  174. package/docs/recipes/57-control.md +18 -13
  175. package/docs/recipes/58-input.md +26 -16
  176. package/docs/recipes/59-depth-post-effects.md +8 -3
  177. package/docs/recipes/60-judge-the-picture.md +10 -9
  178. package/docs/recipes/61-deploy.md +5 -0
  179. package/docs/recipes/62-picture-code.md +72 -79
  180. package/docs/recipes/63-third-person-start.md +48 -45
  181. package/docs/recipes/64-particles.md +22 -10
  182. package/docs/recipes/65-swarm.md +18 -13
  183. package/docs/recipes/66-common-tasks.md +38 -35
  184. package/examples/action/.threedog/content-index.json +1 -1
  185. package/examples/action/GAMEMAP.md +2 -3
  186. package/examples/action/main.js +3 -3
  187. package/examples/action/picture/lights.js +3 -1
  188. package/examples/perf-island/.threedog/content-index.json +1 -1
  189. package/examples/perf-island/GAMEMAP.md +3 -3
  190. package/examples/perf-island/picture/lights.js +2 -1
  191. package/examples/plain-picture/GAMEMAP.md +1 -1
  192. package/examples/rc2d/GAMEMAP.md +1 -1
  193. package/examples/styletest/.threedog/content-index.json +1 -1
  194. package/examples/styletest/GAMEMAP.md +2 -2
  195. package/examples/styletest/main.js +1 -1
  196. package/examples/techniques/interior-light/README.md +3 -3
  197. package/examples/techniques/interior-light/interiorLight.js +2 -4
  198. package/examples/techniques/interior-light/picture/lights.js +2 -1
  199. package/examples/techniques/modular-building/picture/lights.js +3 -1
  200. package/examples/techniques/outlines-and-rim/picture/lights.js +3 -1
  201. package/examples/techniques/procedural-animation/README.md +1 -1
  202. package/examples/techniques/procedural-animation/main.js +1 -1
  203. package/examples/webgpu-tsl/GAMEMAP.md +1 -1
  204. package/examples/world/.threedog/content-index.json +1 -1
  205. package/examples/world/GAMEMAP.md +2 -3
  206. package/examples/world/art/humanoid.js +1 -1
  207. package/examples/world/main.js +6 -3
  208. package/index.d.ts +2 -2
  209. package/llms.txt +101 -0
  210. package/modules/ambience/Ambience.js +21 -5
  211. package/modules/calendar/index.js +9 -5
  212. package/modules/calendar/schedule.js +23 -8
  213. package/modules/camera/FirstPersonCamera.js +3 -1
  214. package/modules/camera/FollowCamera.js +10 -5
  215. package/modules/camera/RtsCamera.js +4 -3
  216. package/modules/camera/common.js +70 -8
  217. package/modules/camera/contract.js +1 -1
  218. package/modules/characters/Character.js +16 -10
  219. package/modules/characters/NPC.js +31 -19
  220. package/modules/characters/assetModel.js +14 -9
  221. package/modules/characters/astar.js +6 -1
  222. package/modules/characters/contract.js +2 -2
  223. package/modules/characters/index.js +34 -22
  224. package/modules/characters/movers/manual.js +1 -1
  225. package/modules/characters/movers/rapier.js +17 -2
  226. package/modules/characters/movers/simple.js +1 -1
  227. package/modules/characters/movers/support.js +16 -7
  228. package/modules/characters/npcAvoid.js +2 -2
  229. package/modules/characters/npcSim.js +3 -2
  230. package/modules/characters/pathAsync.js +24 -8
  231. package/modules/characters/pathJob.js +1 -1
  232. package/modules/characters/player.js +10 -9
  233. package/modules/characters/playerStrings.js +5 -5
  234. package/modules/characters/proceduralRig.js +5 -5
  235. package/modules/characters/useModel.js +6 -0
  236. package/modules/characters/walkTo.js +1 -1
  237. package/modules/collision/Collision.js +29 -18
  238. package/modules/collision/grid.js +22 -4
  239. package/modules/content/index.js +3 -1
  240. package/modules/content/loader.js +1 -1
  241. package/modules/content/models.js +82 -33
  242. package/modules/content/props.js +2 -1
  243. package/modules/content/rules.js +11 -5
  244. package/modules/content/templates.js +3 -3
  245. package/modules/content/words.js +2 -2
  246. package/modules/debug/DebugPanel.js +9 -9
  247. package/modules/flow/index.js +9 -6
  248. package/modules/gameplay/Dialogue.js +34 -20
  249. package/modules/gameplay/Interactions.js +19 -15
  250. package/modules/gameplay/Inventory.js +9 -4
  251. package/modules/gameplay/Quests.js +12 -10
  252. package/modules/gameplay/pickups.js +23 -11
  253. package/modules/grid/index.js +1 -1
  254. package/modules/grid/preview.js +2 -2
  255. package/modules/grid/tiles.js +1 -1
  256. package/modules/hlod/index.js +4 -1
  257. package/modules/hud/index.js +47 -10
  258. package/modules/hud/parts.js +28 -9
  259. package/modules/level/geometry.js +8 -3
  260. package/modules/level/index.js +10 -5
  261. package/modules/level/load.js +4 -2
  262. package/modules/lights/sources.js +1 -1
  263. package/modules/music/Music.js +22 -4
  264. package/modules/nav/index.js +20 -10
  265. package/modules/particles/Particles.js +31 -14
  266. package/modules/particles/effect.js +20 -5
  267. package/modules/particles/lit.js +72 -0
  268. package/modules/photo/Photo.js +72 -28
  269. package/modules/photo/pathTrace.js +106 -0
  270. package/modules/rigid/RigidBodies.js +23 -14
  271. package/modules/rigid/Vehicles.js +3 -13
  272. package/modules/rigid/sync.js +2 -1
  273. package/modules/settings/Settings.js +52 -20
  274. package/modules/settings/apply.js +23 -9
  275. package/modules/settings/sections.js +39 -6
  276. package/modules/settings/strings.js +2 -0
  277. package/modules/settings/view.js +19 -3
  278. package/modules/sky/dome.js +15 -3
  279. package/modules/sky/environment.js +28 -12
  280. package/modules/sky/fog.js +1 -1
  281. package/modules/sky/frame.js +6 -1
  282. package/modules/sky/shader.js +4 -3
  283. package/modules/sky/skyModule.js +8 -4
  284. package/modules/swarm/Swarm.js +1 -1
  285. package/modules/terrain/ChunkManager.js +61 -15
  286. package/modules/terrain/chunkJob.js +2 -2
  287. package/modules/terrain/index.js +20 -5
  288. package/modules/terrain/terrainEdit.js +8 -4
  289. package/modules/terrain/terrainTexture.js +4 -2
  290. package/modules/timeline/Timeline.js +4 -3
  291. package/modules/timeline/Tween.js +3 -0
  292. package/modules/timeline/letterbox.js +1 -0
  293. package/modules/triggers/index.js +36 -17
  294. package/modules/vegetation/Vegetation.js +81 -19
  295. package/modules/vegetation/densityMap.js +13 -8
  296. package/modules/vegetation/draw.js +147 -24
  297. package/modules/vegetation/groundChunks.js +20 -5
  298. package/modules/vegetation/index.js +3 -3
  299. package/modules/vegetation/modelGeometry.js +9 -4
  300. package/modules/water/Water.js +11 -8
  301. package/modules/weather/Weather.js +7 -2
  302. package/modules/weather/shaders.js +25 -5
  303. package/modules/weather/weatherDraw.js +20 -6
  304. package/modules/world/World.js +2 -1
  305. package/modules/world/index.js +2 -2
  306. package/modules/world/persist.js +6 -2
  307. package/modules/world/views.js +15 -2
  308. package/package.json +5 -1
  309. package/presets.js +5 -5
  310. package/render/PostFX.js +102 -42
  311. package/render/backend.js +142 -16
  312. package/render/bindingLimits.js +59 -0
  313. package/render/cascades.js +3 -1
  314. package/render/cascades.tsl.js +2 -0
  315. package/render/daylight.js +7 -1
  316. package/render/detail.js +7 -4
  317. package/render/effects.js +27 -8
  318. package/render/fogLook.js +24 -0
  319. package/render/fuse.js +5 -2
  320. package/render/fx/compareLevel.tsl.js +23 -0
  321. package/render/fx/detail.tsl.js +9 -7
  322. package/render/fx/index.js +9 -2
  323. package/render/fx/library.tsl.js +1 -0
  324. package/render/fx/lightShaft.tsl.js +114 -0
  325. package/render/fx/noise.tsl.js +25 -8
  326. package/render/fx/objectOrigin.tsl.js +39 -10
  327. package/render/fx/particles.tsl.js +23 -6
  328. package/render/fx/patchNodes.tsl.js +17 -12
  329. package/render/fx/pcss.tsl.js +51 -0
  330. package/render/fx/postWebGPU.tsl.js +104 -29
  331. package/render/fx/sky.tsl.js +3 -9
  332. package/render/fxNumbers.js +10 -4
  333. package/render/impostor.tsl.js +107 -0
  334. package/render/lighting.js +33 -1
  335. package/render/lightmap.js +42 -28
  336. package/render/lights.js +19 -3
  337. package/render/materials.js +6 -4
  338. package/render/mergeCommon.js +4 -1
  339. package/render/occlusion.js +14 -4
  340. package/render/patches.js +79 -41
  341. package/render/postRuns.js +32 -0
  342. package/render/postWebGL.js +97 -10
  343. package/render/probes.js +10 -14
  344. package/render/shaderErrors.js +44 -7
  345. package/render/shadowCache.tsl.js +33 -5
  346. package/render/shadows.js +42 -16
  347. package/render/slots.js +8 -5
  348. package/render/vertexInputs.js +52 -0
  349. package/types/core.d.ts +115 -47
  350. package/types/gameplay.d.ts +56 -23
  351. package/types/generated/core/audio/Audio.d.ts +27 -1
  352. package/types/generated/core/base/Random.d.ts +1 -1
  353. package/types/generated/core/input/Input.d.ts +6 -8
  354. package/types/generated/core/input/inputSeat.d.ts +1 -1
  355. package/types/generated/core/inspect/Budget.d.ts +26 -0
  356. package/types/generated/core/inspect/DebugOverrides.d.ts +0 -2
  357. package/types/generated/core/saves/Saves.d.ts +10 -7
  358. package/types/generated/core/saves/session.d.ts +8 -2
  359. package/types/generated/core/scene/Rays.d.ts +1 -3
  360. package/types/generated/core/scene/Views.d.ts +17 -3
  361. package/types/generated/modules/particles/Particles.d.ts +1 -1
  362. package/types/generated/modules/world/World.d.ts +2 -1
  363. package/types/generated/render/PostFX.d.ts +35 -9
  364. package/types/physics.d.ts +796 -764
  365. package/types/pixel.d.ts +1 -1
  366. package/types/tsl.d.ts +62 -1
  367. package/types/world.d.ts +12 -3
  368. package/ui/Focus.js +7 -5
  369. package/ui/Parts.js +1 -1
  370. package/ui/touchPart.js +6 -3
@@ -21,7 +21,7 @@
21
21
  // Plain JS stays first-class: a game's own fields and onFixed logic never need this; it is for things several owners write.
22
22
  // The registry (engine.stacks: define / get / mod, save, timers, describe().shared) is core/ops/stacks.js.
23
23
  import { codedError } from '../base/errorHints.js';
24
- import { DEV, note } from '../base/validate.js';
24
+ import { DEV, note, warnOnce } from '../base/validate.js';
25
25
  import { callerAt } from './stackFrames.js';
26
26
 
27
27
  /** The one layer table, lowest first. Who uses which: engine = the engine's own defaults and drivers, game = game code and
@@ -63,13 +63,21 @@ export function ownerArgs(a, b, fallback = 'game') {
63
63
  /** 'sky.flash' or 'move.speed[player]': the name a message and describe().shared use */
64
64
  const label = (name, id) => (id == null ? name : `${name}[${id}]`);
65
65
 
66
+ /** a value as describe / how-strings / the changed line print it (a rule's value may be a function; JSON.stringify(undefined) is undefined) */
67
+ export const showValue = v => (typeof v === 'number' ? String(+v.toFixed(4)) : typeof v === 'function' ? 'function' : JSON.stringify(v) ?? String(v));
68
+
66
69
  /** One shared point. Made by engine.stacks.define; games normally only call engine.mod(name, ...) and read value(). */
67
70
  export class Stack {
68
71
  /** @param {any} all the registry @param {string} name @param {any} o */
69
- constructor(all, name, { kind = 'number', base, min = -Infinity, max = Infinity, save = true, onChange = null, per = false, manual = null, settingsSet = false }) {
72
+ constructor(all, name, { kind = 'number', base, min = -Infinity, max = Infinity, save = true, onChange = null, per = false, manual = null, settingsSet = false, important = false }) {
70
73
  if (!KINDS.includes(kind)) throw fail(`engine.stacks.define('${name}', { kind }): kind is ${KINDS.join(' / ')}, got ${JSON.stringify(kind)}`);
74
+ if (typeof important !== 'boolean') throw codedError('shared-value', `engine.stacks.define('${name}', { important }): important is true or false, got ${shown(important)}. Fix: { important: true }`);
71
75
  this.all = all; this.name = name; this.kind = kind;
76
+ /** stays on the "values being changed now" line (stacks.changed) even at its base */
77
+ this.important = important;
72
78
  this.base = base ?? (kind === 'number' ? 1 : kind === 'any' ? false : null);
79
+ // a number point's base is validated like min / max: NaN would pass the nullish default and every read would stay NaN whatever the bounds are
80
+ if (kind === 'number' && !Number.isFinite(this.base)) throw codedError('shared-value', `engine.stacks.define('${name}', { base }): base is a finite number, got ${shown(this.base)}. Fix: { base: 1 }`);
73
81
  for (const [k, b] of [['min', min], ['max', max]]) if (typeof b !== 'number' || Number.isNaN(b)) throw codedError('shared-value', `engine.stacks.define('${name}', { ${k} }): ${k} is a number (leave it out for no bound), got ${shown(b)}`);
74
82
  if (min > max) throw codedError('shared-value', `engine.stacks.define('${name}', { min, max }): min must be <= max, got min ${min} > max ${max}. Fix: { min: ${max}, max: ${min} }`);
75
83
  this.min = min; this.max = max; this.save = save; this.per = per; this.onChange = onChange;
@@ -90,6 +98,28 @@ export class Stack {
90
98
  * @returns {{ owner: string, remove(): void, change(value: any): boolean }}
91
99
  */
92
100
  take(o) {
101
+ const { owner, layer, op, value, clock, at } = this._entry(o);
102
+ const m = this._map(o.id, true), old = m.get(owner);
103
+ this._clash(m, owner, op, layer, at);
104
+ // the clock is asked before the old entry goes: an unknown channel throws, and the entry that was there must still be there then
105
+ const until = o.for != null ? this.all._nowOf(clock) + o.for : null;
106
+ // Taking again: delete the old entry and put a new object at the end. Why not edit in place: the Map order would not change, so neither the
107
+ // 'top' latest nor the latest set would be it; and the old handle would then remove the new value. A new object makes a stale handle's _drop miss.
108
+ m.delete(owner);
109
+ // where: the code line of the first take (dev only). Kept on rewrites, so a weather module re-taking every frame costs no stack walk
110
+ const ent = { owner, id: o.id ?? null, since: this.all._at(), where: old ? old.where : callerAt(), op, value, layer, clock, until };
111
+ m.set(owner, ent);
112
+ this.all.engine._picture?.sharedTook(this.name, ent); // dev server only: the point's history for explain({ value })
113
+ if (ent.until != null) this.all._timedDirty = true;
114
+ this._changed(o.id);
115
+ return { owner, remove: () => { this._drop(owner, o.id, ent); }, change: v => this._rewrite(ent, v, at) };
116
+ }
117
+ /**
118
+ * @internal The one check of an entry (owner, layer, the op and its value, per id, for), the same for engine.mod and for a save putting entries back (_fromSave):
119
+ * a load that skipped it let a damaged save make a point NaN. Throws naming the call; touches nothing.
120
+ * @returns {{ owner: string, layer: string, op: string | null, value: any, clock: string, at: string }}
121
+ */
122
+ _entry(o) {
93
123
  const { owner } = o, at = label(this.name, o.id);
94
124
  if (!owner || typeof owner !== 'string') throw fail(`engine.mod('${at}', { owner }): owner is a non-empty string naming who changes it, e.g. 'my-menu', got ${JSON.stringify(owner)}`);
95
125
  const layer = o.layer ?? 'game';
@@ -108,18 +138,27 @@ export class Stack {
108
138
  if (this.per === true && o.id == null) throw fail(`engine.mod('${this.name}'): this point is per record, pass { id }, e.g. { owner: '${owner}', id: 'slime_3', ... }`);
109
139
  const clock = o.clock ?? 'real';
110
140
  if (o.for != null && !(o.for >= 0 && Number.isFinite(o.for))) throw fail(`engine.mod('${at}', { for }): for is seconds >= 0 on clock '${clock}', got ${JSON.stringify(o.for)}`);
111
- const m = this._map(o.id, true), old = m.get(owner);
112
- this._clash(m, owner, op, layer, at);
113
- // Taking again: delete the old entry and put a new object at the end. Why not edit in place: the Map order would not change, so neither the
114
- // 'top' latest nor the latest set would be it; and the old handle would then remove the new value. A new object makes a stale handle's _drop miss.
115
- m.delete(owner);
116
- // where: the code line of the first take (dev only). Kept on rewrites, so a weather module re-taking every frame costs no stack walk
117
- const ent = { owner, id: o.id ?? null, since: this.all._at(), where: old ? old.where : callerAt(), op, value, layer, clock, until: o.for != null ? this.all._nowOf(clock) + o.for : null };
118
- m.set(owner, ent);
119
- this.all.engine._picture?.sharedTook(this.name, ent); // dev server only: the point's history for explain({ value })
120
- if (ent.until != null) this.all._timedDirty = true;
121
- this._changed(o.id);
122
- return { owner, remove: () => { this._drop(owner, o.id, ent); }, change: v => this._rewrite(ent, v, at) };
141
+ return { owner, layer, op, value, clock, at };
142
+ }
143
+ /**
144
+ * @internal A saved list of entries ({ owner, id, op, value, layer, clock, left }) checked as engine.mod would take them, one after another: each entry by _entry,
145
+ * and the list by the conflict rule (two owners setting one layer). Why the list on its own: the entries a load keeps (system / settings / debug) are on other
146
+ * layers than the saved ones, so they cannot clash with them. Throws on the first bad entry and touches nothing (the caller keeps what the point had).
147
+ * @param {any} list @param {(layer: any) => string} layerOf how the registry files a saved layer @returns {any[]} the entries, normalized
148
+ */
149
+ _fromSave(list, layerOf) {
150
+ if (!Array.isArray(list)) throw fail(`'${this.name}': a list of entries, got ${shown(list)}`);
151
+ const seen = new Map(); // id -> owner -> entry: the list's own conflict check
152
+ return list.map(e => {
153
+ if (!e || typeof e !== 'object') throw fail(`'${this.name}': an entry is an object, got ${shown(e)}`);
154
+ const op = e.op, left = e.left == null ? undefined : Math.max(0, e.left); // a timer already due loads as due
155
+ const o = { owner: e.owner, id: e.id ?? undefined, layer: layerOf(e.layer), clock: e.clock ?? 'real', for: left, ...(NUM_OPS.includes(op) ? { [op]: e.value } : {}) };
156
+ const c = this._entry(o), m = seen.get(o.id ?? '') ?? new Map();
157
+ seen.set(o.id ?? '', m);
158
+ this._clash(m, c.owner, c.op, c.layer, c.at);
159
+ m.set(c.owner, { owner: c.owner, op: c.op, layer: c.layer, where: null });
160
+ return { owner: c.owner, id: o.id ?? null, op: c.op, value: c.value, layer: c.layer, clock: c.clock, left: left ?? null };
161
+ });
123
162
  }
124
163
  /** @internal the settings layer only restricts: a number goes down (mul 0..1, clamp with only a max), a value point goes off (set false).
125
164
  * Checked on take and on handle.change, so a settings entry cannot be raised afterwards either */
@@ -213,10 +252,19 @@ export class Stack {
213
252
  return v;
214
253
  }
215
254
  /** @internal dev, once per point and owner: a game-layer set is shown as another number because effects above changed it. Not a warning
216
- * (that is the rule: effects apply on top of what the game set); it says why the screen differs and how to lock the number. */
255
+ * (that is the rule: effects apply on top of what the game set); it says why the screen differs and how to lock the number.
256
+ * A switch is a warning instead: the lower layer's set loses outright, so it names the holder and its layer. */
217
257
  _hint(list, v, id) {
218
258
  let lead = null;
219
259
  for (const e of list) if (e.op === 'set' && (!lead || LAYERS[e.layer] >= LAYERS[lead.layer])) lead = e;
260
+ // a switch: the set in charge wins, and a lower-layer set that said the other thing gets nothing on screen, so say who holds it (a warning: the writer's intent is lost)
261
+ if (typeof v === 'boolean') {
262
+ if (lead) for (const e of list) if (e.op === 'set' && e.value !== v && LAYERS[e.layer] < LAYERS[lead.layer]) {
263
+ warnOnce(`'${e.owner}' set ${label(this.name, id)} ${e.value} (${e.layer} layer), but '${lead.owner}' holds it ${lead.value} on the ${lead.layer} layer, which wins; the shown value is ${v}. `
264
+ + `Lift that hold, or set it from a layer above ${lead.layer}, if ${e.value} is wanted.`, `shared-hint:${this.name}:${e.owner}`);
265
+ }
266
+ return;
267
+ }
220
268
  if (!lead || lead.layer !== 'game' || typeof v !== 'number' || Math.abs(v - lead.value) < 1e-9) return;
221
269
  const above = list.filter(e => LAYERS[e.layer] > LAYERS.game);
222
270
  if (!above.length) return;
@@ -265,8 +313,11 @@ export class Stack {
265
313
  let lead = null;
266
314
  if (LAYERED.has(this.kind)) { for (const e of list) if (e.op === 'set' && (!lead || LAYERS[e.layer] >= LAYERS[lead.layer])) lead = e; }
267
315
  else lead = this.kind === 'any' ? list[0] : list.at(-1);
268
- /** @type {{ value: any, writer: string, layer?: string, at?: string, also?: object[], how?: string }} */
269
- const r = { value: this.value(id ?? undefined), writer: lead ? lead.owner : 'default' };
316
+ // the base this record is read with: a mover passes the character's own speed to value(id, base), the memo keeps the last one read; the
317
+ // define-time base is only the fallback (a point nobody has read yet)
318
+ const base = this._memo.has(id ?? '') ? this._memo.get(id ?? '').base : this.base;
319
+ /** @type {{ value: any, base: any, writer: string, layer?: string, at?: string, also?: object[], how?: string }} */
320
+ const r = { value: this.value(id ?? undefined, base), base, writer: lead ? lead.owner : 'default' };
270
321
  if (lead?.layer && LAYERED.has(this.kind)) r.layer = lead.layer;
271
322
  if (lead?.where) r.at = lead.where;
272
323
  const hiddenBelow = lead && LAYERED.has(this.kind) ? LAYERS[lead.layer] : -Infinity;
@@ -275,13 +326,13 @@ export class Stack {
275
326
  if (LAYERED.has(this.kind) ? LAYERS[e.layer] < hiddenBelow : this.kind === 'top') h.hidden = true;
276
327
  return h;
277
328
  });
278
- if (LAYERED.has(this.kind)) r.how = this._how(list, lead, hiddenBelow);
329
+ if (LAYERED.has(this.kind)) r.how = this._how(list, lead, hiddenBelow, base);
279
330
  return r;
280
331
  }
281
332
  /** @internal how the value was combined, in the order it was: "cave 180 × storm 0.6" (layer order, then set / add / mul / clamp) */
282
- _how(list, lead, from) {
283
- const show = v => (typeof v === 'number' ? String(+v.toFixed(4)) : typeof v === 'function' ? 'function' : JSON.stringify(v)); // a rule's value may be a function
284
- const parts = lead ? [] : [`default ${show(this.base)}`];
333
+ _how(list, lead, from, base = this.base) {
334
+ const show = showValue;
335
+ const parts = lead ? [] : [`default ${show(base)}`];
285
336
  for (const L of Object.values(LAYERS)) {
286
337
  if (L < from) continue;
287
338
  const es = list.filter(e => LAYERS[e.layer] === L);
@@ -1,14 +1,20 @@
1
1
  // engine.stacks: the registry of every shared point (the point itself and its rules are core/ops/sharedPoint.js). Here: define / get / mod, the timers
2
2
  // behind `for`, saving entries, and describe().shared. Kept apart from sharedPoint.js only for size: the rules read without the bookkeeping between.
3
- import { codedError } from '../base/errorHints.js';
3
+ import { codedError, coded } from '../base/errorHints.js';
4
+ import { refuseSave } from '../base/saveValues.js';
4
5
  import { DEV, warnOnce } from '../base/validate.js';
5
- import { Stack } from './sharedPoint.js';
6
+ import { Stack, showValue } from './sharedPoint.js';
6
7
 
8
+ const BAD_SAVED = "[saves] shared value '{name}' in the save was not restored ({why}); the save is from a build that defined it differently. The next save writes what is defined now";
7
9
  const KEYS = ['owner', 'set', 'add', 'mul', 'clamp', 'value', 'for', 'clock', 'id', 'layer'];
8
10
  // Saved: engine / game / effect entries (what the playthrough did). Not saved: system / debug (menus, cutscenes, debug: "what the
9
11
  // screen is doing now", retaken after a load), settings (the settings module re-applies the player's choices from its own prefs)
10
12
  const SAVED = new Set(['engine', 'game', 'effect']);
11
13
  const saved = e => SAVED.has(e.layer);
14
+ const layerOf = l => (SAVED.has(l) ? l : 'game');
15
+ // a saved entry of a point not defined yet: only its shape can be checked before the point says its kind (the rest is checked when it is defined)
16
+ const OPS = ['set', 'add', 'mul', 'clamp'];
17
+ const entryShape = e => !!e && typeof e === 'object' && typeof e.owner === 'string' && !!e.owner && OPS.includes(e.op) && (e.left == null || Number.isFinite(e.left));
12
18
 
13
19
  /** engine.stacks: every shared point by name; engine.mod(name, o) is the one way to change one */
14
20
  export class Stacks {
@@ -26,7 +32,7 @@ export class Stacks {
26
32
  * createServices calls this once saves and events exist */
27
33
  _hook() {
28
34
  const e = this.engine;
29
- e.saves.register('stacks', { notAtomic: 'a mod is ended through the handle its owner keeps, which a load cannot put back', save: () => this._save(), load: d => this._load(d) });
35
+ e.saves.define('stacks', { notAtomic: 'a mod is ended through the handle its owner keeps, which a load cannot put back', save: () => this._save(), load: d => this._load(d) });
30
36
  // input.keys and input.gate key their entries by action name, not record id: a removed record 'fire' must not unbind the action 'fire'
31
37
  e.events.on('world:remove', ({ id }) => { for (const s of this._all.values()) if (s.per && !s.name.startsWith('input.')) s.dropId(id); });
32
38
  }
@@ -36,7 +42,7 @@ export class Stacks {
36
42
  * per: true = one value per record id (mod with { id }); per: 'optional' = an entry with { id } is that record's, one without is every record's
37
43
  * (move.speed: haste on the player, mud on everyone). save: false keeps it out of saves (screen state like the camera holder).
38
44
  * manual: the copyable takeover call the conflict error offers (a drawing part's manual()).
39
- * @param {string} name @param {{ kind?: 'number' | 'value' | 'any' | 'top' | 'one', base?: any, min?: number, max?: number, per?: boolean | 'optional', save?: boolean, manual?: string, settingsSet?: boolean, onChange?: (id: string | null) => void }} [o]
45
+ * @param {string} name @param {{ kind?: 'number' | 'value' | 'any' | 'top' | 'one', base?: any, min?: number, max?: number, per?: boolean | 'optional', save?: boolean, manual?: string, settingsSet?: boolean, important?: boolean, onChange?: (id: string | null) => void }} [o]
40
46
  * @returns {Stack}
41
47
  * @example engine.stacks.define('damageTaken', { per: true, min: 0 }); engine.mod('damageTaken', { owner: 'shield', id: 'player', mul: 0.5, for: 3 });
42
48
  */
@@ -44,7 +50,7 @@ export class Stacks {
44
50
  if (this._all.has(name)) throw codedError('engine-misuse', `engine.stacks.define('${name}'): already defined; read it with engine.stacks.get('${name}')`);
45
51
  const s = new Stack(this, name, o);
46
52
  this._all.set(name, s);
47
- if (this._pending[name]) { this._loadOne(s, this._pending[name]); delete this._pending[name]; }
53
+ if (this._pending[name]) { this._loadOne(s, this._pending[name]); delete this._pending[name]; } // checked now that the kind is known
48
54
  return s;
49
55
  }
50
56
  /**
@@ -79,6 +85,7 @@ export class Stacks {
79
85
  /** Names of every point */
80
86
  list() { return [...this._all.keys()]; }
81
87
  /**
88
+ * @internal The entry behind engine.mod (services.js hands it out): games and modules call engine.mod / ctx.mod; stacks.define, get, changed and describe stay public.
82
89
  * The one entry: change a shared point; returns a handle whose remove() ends only this owner's entry.
83
90
  * @param {string} name @param {{ owner: string, set?: any, add?: number, mul?: number, clamp?: { min?: number, max?: number }, value?: any, for?: number, clock?: string, id?: string, layer?: 'engine' | 'game' | 'effect' | 'system' | 'settings' | 'debug' }} o
84
91
  * @returns {{ owner: string, remove(): void, change(value: any): boolean }} remove() ends it; change(v) rewrites its value in place (same op, layer)
@@ -92,16 +99,41 @@ export class Stacks {
92
99
  * { 'time.enemies': { value, writer, layer?, at?, how?, also: [{ owner, layer, op, value, left?, at?, hidden? }] } }.
93
100
  * Per-record points show as 'move.speed[player]'; a per: 'optional' point's every-record entries as 'move.speed[*]'.
94
101
  */
95
- describe() {
96
- const out = {};
102
+ describe(rows = this._rows()) { return Object.fromEntries(rows.filter(x => x.has).map(x => [x.label, x.row])); }
103
+ /** @internal one snapshot of every point's row (describe() and changed() take it, so a describe builds the rows once). has = the point has entries */
104
+ _rows() {
105
+ const out = [], add = (label, s, row, has) => out.push({ label, s, row, has });
97
106
  for (const s of this._all.values()) {
98
107
  if (s.per) {
99
- for (const id of s.ids()) out[`${s.name}[${id}]`] = s.row(id);
100
- if (s.size()) out[`${s.name}[*]`] = s.row();
101
- } else if (s.size()) out[s.name] = s.row();
108
+ for (const id of s.ids()) add(`${s.name}[${id}]`, s, s.row(id), true);
109
+ if (s.size()) add(`${s.name}[*]`, s, s.row(), true);
110
+ } else add(s.name, s, s.row(), s.size() > 0);
102
111
  }
103
112
  return out;
104
113
  }
114
+ /**
115
+ * The values being changed now: [{ name, base, now, how, text }], at most `max`, the furthest from base first. A point is in when its value is off
116
+ * its base (the base the record is read with, e.g. the character's own speed), a settings entry caps it, or it was defined with
117
+ * { important: true } (then also at base). Only number / value points: a hold or the camera slot has no base to be off. Two owners setting one
118
+ * layer throws at take, so a conflict never exists to list here.
119
+ * describeText's "Values being changed now" line and the dev panel's folder both read this, nothing computes it a second way.
120
+ * @param {number} [max] @param {ReturnType<Stacks['_rows']>} [snap] rows already taken (describe passes its own)
121
+ * @example engine.stacks.changed() // [{ name: 'move.speed[player]', base: 6, now: 4.2, how: 'default 6 × haste 1.4 × mud 0.5' }]
122
+ */
123
+ changed(max = 5, snap = this._rows()) {
124
+ const same = (a, b) => a === b || JSON.stringify(a) === JSON.stringify(b);
125
+ const rows = [];
126
+ for (const { label: name, s, row: r, has } of snap) {
127
+ if (s.kind !== 'number' && s.kind !== 'value') continue;
128
+ const off = has && !same(r.value, r.base), capped = r.layer === 'settings' || r.also.some(h => h.layer === 'settings');
129
+ if (!off && !capped && !s.important) continue;
130
+ const far = off ? (s.kind === 'number' ? Math.abs(r.value - r.base) / Math.max(Math.abs(r.base), 1) : 1) : 0;
131
+ rows.push({ name, base: r.base, now: r.value, how: r.how, text: `${name} ${showValue(r.base)} → ${showValue(r.value)}${r.how ? ` (${r.how})` : ''}`, far, keep: s.important });
132
+ }
133
+ // important points are picked first (they must not fall off the cap), then the list is ordered by distance from base
134
+ const pick = rows.sort((a, b) => b.keep - a.keep || b.far - a.far).slice(0, max);
135
+ return pick.sort((a, b) => b.far - a.far).map(({ far, keep, ...row }) => row);
136
+ }
105
137
  /**
106
138
  * Everything one owner changes now, grouped the other way round from describe().shared: "what did rainyNight change?"
107
139
  * @param {string} owner a module name, a game owner ('bullet-time'), 'settings', ...
@@ -148,7 +180,8 @@ export class Stacks {
148
180
  _rebase(clock, delta) { for (const [, e] of this._timed()) if (e.clock === clock) e.until += delta; }
149
181
  /** @internal number and value points; entries below the settings layer */
150
182
  _save() {
151
- const out = {};
183
+ // entries of a point the game has not defined yet ride along (shape-checked on load), as Time keeps channels not defined yet: else the next save lost them
184
+ const out = { ...this._pending };
152
185
  for (const s of this._all.values()) {
153
186
  if (s.save === false || (s.kind !== 'number' && s.kind !== 'value')) continue;
154
187
  const list = [];
@@ -163,20 +196,27 @@ export class Stacks {
163
196
  /** @internal a load replaces every saved (engine..effect) entry; system / settings / debug entries stay (the menu that holds them is still up) */
164
197
  _load(d) {
165
198
  this._pending = {};
166
- for (const s of this._all.values()) if (s.save !== false && (s.kind === 'number' || s.kind === 'value')) this._loadOne(s, d?.[s.name] ?? []);
167
- for (const [k, v] of Object.entries(d ?? {})) if (!this._all.has(k)) this._pending[k] = v;
199
+ for (const s of this._all.values()) if (s.save !== false && (s.kind === 'number' || s.kind === 'value')) this._loadOne(s, d != null && Object.hasOwn(d, s.name) ? d[s.name] : []); // [] only when absent: an explicit null is damage, refused by the check
200
+ for (const [k, v] of Object.entries(d ?? {})) if (!this._all.has(k)) {
201
+ if (Array.isArray(v) && v.every(entryShape)) this._pending[k] = v;
202
+ else warnOnce(coded('save-value', BAD_SAVED.replace('{name}', k).replace('{why}', 'not a list of { owner, op, value } entries'))); // a stack this code no longer defines (an old save): dropped with one warning, never a reason to refuse the save
203
+ }
168
204
  }
169
205
  /**
170
206
  * @internal Replace s's saved entries with list. An owner that holds an entry now and also in the save keeps the SAME entry object, rewritten
171
207
  * with the saved values: handles taken before the load (engine.mod, ctx.mod) still remove() / change() it. A new object here made every such
172
208
  * handle stale in silence (a slow zone's time.world mul 0.5 stayed after leaving the zone).
209
+ * The list is checked first, as engine.mod checks (Stack._fromSave): a list that fails changes nothing on s and is reported once; the rest of the save loads.
173
210
  */
174
- _loadOne(s, list) {
211
+ _loadOne(s, raw) {
212
+ let list;
213
+ try { list = s._fromSave(raw, layerOf); }
214
+ catch (err) { refuseSave('stacks', s.name, 'is not a valid list: ' + err.message, raw); }
175
215
  const had = new Map();
176
216
  for (const m of [...s._by.values()]) for (const e of [...m.values()]) if (saved(e)) { had.set(`${e.id ?? ''}\0${e.owner}`, e); s._drop(e.owner, e.id, e); }
177
217
  for (const e of list) {
178
- const m = s._map(e.id, true), clock = e.clock ?? 'real', old = had.get(`${e.id ?? ''}\0${e.owner}`);
179
- const fields = { since: this._at(), op: e.op, value: e.value, layer: SAVED.has(e.layer) ? e.layer : 'game', clock, until: e.left == null ? null : this._nowOf(clock) + e.left };
218
+ const m = s._map(e.id, true), clock = e.clock, old = had.get(`${e.id ?? ''}\0${e.owner}`);
219
+ const fields = { since: this._at(), op: e.op, value: e.value, layer: e.layer, clock, until: e.left == null ? null : this._nowOf(clock) + e.left };
180
220
  m.set(e.owner, old ? Object.assign(old, fields) : { owner: e.owner, id: e.id ?? null, where: null, ...fields });
181
221
  this._timedDirty = true;
182
222
  s._changed(e.id);
@@ -29,6 +29,7 @@ export class SaveStore {
29
29
  /** 'idb' | 'localStorage': meaningful only after open() completes */
30
30
  this.mode = 'idb';
31
31
  this.db = null;
32
+ /** @internal why open() fell back to localStorage */ this.openError = null;
32
33
  }
33
34
 
34
35
  /** Open the database; on failure (private mode, disabled) switch to localStorage. Returns whether IndexedDB is in use. */
@@ -40,9 +41,12 @@ export class SaveStore {
40
41
  this.db = await req(r);
41
42
  this.db.onversionchange = () => this.db.close(); // yield when another tab wants to upgrade the database
42
43
  return true;
43
- } catch { this.mode = 'localStorage'; return false; }
44
+ } catch (e) { this.mode = 'localStorage'; this.openError = e; return false; } // kept: the warning names the real cause, not always private mode
44
45
  }
45
46
 
47
+ /** Attachments live only in IndexedDB: in localStorage mode a write says so (save-write) instead of resolving as stored */
48
+ _needIdb(b) { if (this.mode === 'localStorage') throw codedError('save-write', `attachment '${b.group}/${b.id}' was not stored: IndexedDB is unavailable, so attachments (such as photos) are not kept`); }
49
+
46
50
  _tx(store, mode = 'readonly') { return this.db.transaction(store, mode); }
47
51
 
48
52
  /** All world saves: [{ slot, savedAt, json }] */
@@ -117,7 +121,8 @@ export class SaveStore {
117
121
  /** Several attachments in one transaction: all stored or none (a restore must not leave half of them) */
118
122
  async putBlobs(list) {
119
123
  list.forEach(checkBlob);
120
- if (this.mode === 'localStorage' || !list.length) return;
124
+ if (!list.length) return;
125
+ this._needIdb(list[0]);
121
126
  const t = this._tx('blobs', 'readwrite'), st = t.objectStore('blobs');
122
127
  try { for (const b of list) st.put(b); } catch (e) { t.abort(); throw e; }
123
128
  await tx(t);
@@ -132,7 +137,8 @@ export class SaveStore {
132
137
  /** @internal One attachment, only if no other tab claimed the row since the rev this tab saw (putSlot's compare). row: as stored, with its own rev */
133
138
  async putBlobIf(row, expect) {
134
139
  checkBlob(row);
135
- if (this.mode !== 'localStorage') return this._change('blobs', [row.group, row.id], cur => claimed(cur, expect), st => st.put(row));
140
+ this._needIdb(row);
141
+ return this._change('blobs', [row.group, row.id], cur => claimed(cur, expect), st => st.put(row));
136
142
  }
137
143
  /** @internal deleteBlob with the same compare */
138
144
  async deleteBlobIf(group, id, expect) {
@@ -1,6 +1,6 @@
1
1
  // Saves: each module registers "how to save and load", and saving collects them all. Supports multiple slots, autosave, and export / import (text, file).
2
2
  //
3
- // engine.saves.register('garden', { version: 2, migrate: { 1: d => ({ ...d, beds: [] }) }, save, load }); // shape changed: raise version, add the step
3
+ // engine.saves.define('garden', { version: 2, migrate: { 1: d => ({ ...d, beds: [] }) }, save, load }); // shape changed: raise version, add the step
4
4
  // if (await engine.saves.save('slot1')) toast(engine, 'Saved'); await engine.saves.load('slot1'); // both return Promise<boolean>
5
5
  // Text export / import and .json files (with attachments): saveFiles.js. Applying a save (checks, rollback): saveApply.js. Format: recipe 20 "Save format".
6
6
  // Failure paths never lose data: a part whose save() throws, or a failed write, keeps the previous save (false + toast); a corrupt / newer / unmigratable
@@ -28,19 +28,21 @@ import { StateReplace } from './stateReplace.js';
28
28
 
29
29
  // Developer messages (console text for developers, never shown in the game UI)
30
30
  const DEV_STRINGS = {
31
- keyTaken: "saves.register('{key}'): the key already has an owner, whose part would stop being saved",
31
+ keyTaken: "saves.define('{key}'): the key already has an owner, whose part would stop being saved",
32
32
  saveThrew: "save() of save part '{k}' threw ({msg}); slot '{slot}' was not written and keeps its previous save",
33
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",
34
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
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
+ badFirst: "saves.define('{key}'): first must be true, false or a finite number (lower loads earlier, true counts as 0), got {got}",
36
37
  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
38
  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",
39
+ owner: "saves.define('{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",
39
40
  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",
41
+ asyncAtomic: "saves.define('{key}'): an atomic part's load must be synchronous, but it is an async function. An atomic op's rollback puts the part back before the op returns; a load still running after its first await would write the old data over what the outer op committed, its events past the mute. Make load plain (do the async work before), or drop atomic: true",
42
+ protoName: "saves.define('__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",
41
43
  };
42
44
 
43
- /** What saves.register takes: without a working save and load the failure would wait for the player's first save or load */
45
+ /** What saves.define takes: without a working save and load the failure would wait for the player's first save or load */
44
46
  const PROVIDER = { save: 'function', load: 'function', first: 'any?', version: 'any?', migrate: 'any?', atomic: 'any?', notAtomic: 'string?', checkNewGame: 'any?' };
45
47
 
46
48
  /** Save data as a save file would hold it: no reference into the part's live state stays behind */
@@ -85,14 +87,14 @@ export class Saves {
85
87
  this.whenReady = this._init().then(() => { this.ready = true; });
86
88
  }
87
89
  /**
88
- * Register "how to save and load"; key is this part's name in the save. Parts with first: true load first (the level); a load returning a Promise makes later
90
+ * Define "how to save and load"; key is this part's name in the save. Parts with first: true load first (the level); first may be a number, lower loads earlier, true counts as 0 (zones that need the level: 1); a load returning a Promise makes later
89
91
  * parts wait.
90
92
  * version (default 1): raise it by 1 whenever what save() returns changes shape, and add migrate[oldVersion] = data => newData; load sees only the current
91
93
  * shape.
92
94
  * A save whose part is newer than this build's version is refused as a whole (load returns false, the save is kept).
93
95
  * 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
96
  * 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.
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).
97
+ * 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; load synchronous: an async function is refused here).
96
98
  * 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
97
99
  * (world: records placed by code instead of content). The part knows its own format; core only hands the data over.
98
100
  * 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
@@ -101,29 +103,33 @@ export class Saves {
101
103
  * @param {SaveProvider} provider
102
104
  * @returns {{ remove(o?: { keep?: boolean }): void }}
103
105
  * @example
104
- * engine.saves.register('garden', { save: () => garden.toJSON(), load: d => garden.fromJSON(d) });
106
+ * engine.saves.define('garden', { save: () => garden.toJSON(), load: d => garden.fromJSON(d) });
105
107
  * // later the format gains beds: version 2, and a step that upgrades version-1 data
106
- * engine.saves.register('garden', { version: 2, migrate: { 1: d => ({ ...d, beds: [] }) }, save: () => garden.toJSON(), load: d => garden.fromJSON(d) });
108
+ * engine.saves.define('garden', { version: 2, migrate: { 1: d => ({ ...d, beds: [] }) }, save: () => garden.toJSON(), load: d => garden.fromJSON(d) });
107
109
  */
108
- register(key, provider) {
109
- checkTypeRule(this.engine, 'saves.register', `registered save part '${key}'`);
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
110
+ define(key, provider) {
111
+ checkTypeRule(this.engine, 'saves.define', `defined save part '${key}'`);
112
+ // told, not taken: the first owner would stop being saved with nothing said. A module that goes gives the key back first (ctx.saves.define), so a swap never lands here
111
113
  if (this.providers.has(key)) throw codedError('save-key-taken', fmt(DEV_STRINGS.keyTaken, { key }));
112
- readParams(`saves.register('${key}')`, PROVIDER, provider);
114
+ readParams(`saves.define('${key}')`, PROVIDER, provider);
115
+ if (provider.first !== undefined && typeof provider.first !== 'boolean' && !Number.isFinite(provider.first)) throw codedError('module-params', fmt(DEV_STRINGS.badFirst, { key, got: JSON.stringify(provider.first) }));
113
116
  if (key === '__proto__') throw codedError('module-params', DEV_STRINGS.protoName);
114
117
  const { save, load, first = false, version = 1, migrate = {}, atomic = false, checkNewGame = null } = provider;
118
+ // shortcut: only a load declared async is known here; a plain function that returns a Promise is refused when the rollback meets it (restoreParts, saveApply.js)
119
+ if (atomic === true && load.constructor?.name === 'AsyncFunction') throw codedError('module-params', fmt(DEV_STRINGS.asyncAtomic, { key }));
115
120
  checkPartVersion(key, version, migrate);
116
121
  const f = this._foreign, held = Object.hasOwn(f.parts, key) ? { data: copyData(f.parts[key]), version: f.versions[key] ?? 1 } : null;
117
122
  const part = { save, load, first, version, migrate, atomic: atomic === true, checkNewGame };
118
123
  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
124
  this.providers.set(key, part);
120
- this.engine.session._late(key); // a part registered after start() (a module installed later) joins the new-game state as it is now
121
- if (held) adoptPart(this, key);
125
+ try { this.engine.session._late(key); } // a part registered after start() (a module installed later) joins the new-game state as it is now
126
+ catch (err) { this.providers.delete(key); this.engine.session._lateParts.delete(key); throw err; } // define() hands back no handle on a throw, so the key must not stay taken
127
+ if (held) adoptPart(this, key, part);
122
128
  return { remove: ({ keep = true } = {}) => {
123
129
  if (this.providers.get(key) !== part) return; // a stale handle: the key belongs to someone newer
124
130
  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 }; }
131
+ let left = held; // removed while its late data loads (adoptPart): that data goes back unattached, not the half-loaded state
132
+ if (keep && !part.adopting && !Object.hasOwn(this._foreign.parts, key)) try { const d = partData(key, part); left = d == null ? null : { data: copyData(d), version }; }
127
133
  catch (err) { reportError(this.engine, err, `save() of part '${key}' while it was removed`, { soft: true }); }
128
134
  if (left) { this._foreign.parts[key] = left.data; this._foreign.versions[key] = left.version; }
129
135
  } };
@@ -138,7 +144,7 @@ export class Saves {
138
144
  /** @internal */
139
145
  async _init() {
140
146
  const idb = await this.store.open();
141
- if (!idb) warnOnce(coded('indexeddb', DEV_STRINGS.noIdb));
147
+ if (!idb) warnOnce(coded('indexeddb', DEV_STRINGS.noIdb + (this.store.openError ? ` (IndexedDB said: ${this.store.openError.message})` : '')));
142
148
  try {
143
149
  for (const r of await this.store.slots()) {
144
150
  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
@@ -162,7 +168,7 @@ export class Saves {
162
168
  }
163
169
  /**
164
170
  * 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.
165
- * Pass a function to make the bytes when the write runs: flush() then waits for that too. Without IndexedDB it is not kept.
171
+ * Pass a function to make the bytes when the write runs: flush() then waits for that too. Without IndexedDB it is not kept: it rejects with save-write.
166
172
  * 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.
167
173
  * @example await engine.saves.putAttachment('replay', 'run-1', blob, { score: 12 });
168
174
  * @param {string} group what the attachment is for
@@ -292,7 +298,9 @@ export class Saves {
292
298
  */
293
299
  async _showStored(slot, still) {
294
300
  if (!still()) return;
295
- const stored = await this.store.getSlot(slot).catch(() => null);
301
+ let stored;
302
+ try { stored = await this.store.getSlot(slot); }
303
+ catch (e) { reportError(this.engine, e, `saves slot '${slot}' could not be read back after a failed write; the list keeps the last known record, which the disk may not hold`, { soft: true }); return; } // "cannot read" is not "no save": dropping the slot would hide a save that may exist
296
304
  if (still()) this._show(slot, stored);
297
305
  }
298
306
  /** @internal */
@@ -344,10 +352,11 @@ export class Saves {
344
352
  * game back.
345
353
  * To continue or retry with nothing of the current playthrough left over, use engine.session.load(slot).
346
354
  * @param {string} [slot]
355
+ * @param {{ turn?: object }} [o] turn: the running request's own (what a save part's load(), an afterLoad or a module's applyState was given): the call then runs inside that request instead of waiting behind it for itself, as level.load({ turn }) does
347
356
  * @returns {Promise<boolean>}
348
357
  * @example if (!(await engine.saves.load('quick'))) toast(engine, 'No quick save');
349
358
  */
350
- load(slot = 'auto') { return this._replace.run(null, () => this._load(slot)); }
359
+ load(slot = 'auto', { turn } = {}) { return this._replace.run(null, () => this._load(slot), { turn }); }
351
360
  /** @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) */
352
361
  _load(slot, base) { return loadSlot(this, slot, base); }
353
362
  /** All slots, newest first (synchronous, reads the in-memory index) @returns {{ slot: string, savedAt: number }[]} */
@@ -421,7 +430,7 @@ export class Saves {
421
430
  return (this._auto = h);
422
431
  }
423
432
  /** @internal Stop autosave (called by engine.dispose) */
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
433
+ dispose() { this._auto?.remove(); this._bc?.close(); this._bc = null; this._queue.then(() => this.whenReady).catch(() => {}).finally(() => this.store.close()); } // close the database only after queued writes finish and the open (which sets store.db later) is done
425
434
  }
426
435
 
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 }];
436
+ export const handRolled = [{ kind: 'save', seen: 'a save of its own in localStorage', use: "engine.saves: autosave(minutes), define('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 }];