threedog 0.7.0 → 0.8.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 (544) hide show
  1. package/CHANGELOG.md +196 -1
  2. package/README.md +6 -9
  3. package/core/{Animator.js → assets/Animator.js} +28 -18
  4. package/core/{Assets.js → assets/Assets.js} +98 -54
  5. package/core/{Baked.js → assets/Baked.js} +4 -4
  6. package/core/assets/assetEntry.js +237 -0
  7. package/core/{assetHot.js → assets/assetHot.js} +7 -6
  8. package/core/{assetLoad.js → assets/assetLoad.js} +55 -16
  9. package/core/assets/assetLod.js +113 -0
  10. package/core/{assetManifest.js → assets/assetManifest.js} +19 -11
  11. package/core/{assetReport.js → assets/assetReport.js} +6 -12
  12. package/core/{namedModel.js → assets/namedModel.js} +17 -13
  13. package/core/{Audio.js → audio/Audio.js} +26 -23
  14. package/core/{audioRules.js → audio/audioRules.js} +8 -5
  15. package/core/{audioVoice.js → audio/audioVoice.js} +17 -30
  16. package/core/{Events.js → base/Events.js} +3 -3
  17. package/core/{I18n.js → base/I18n.js} +10 -10
  18. package/core/{Random.js → base/Random.js} +5 -4
  19. package/core/{easing.js → base/easing.js} +1 -1
  20. package/core/{errorCodes.js → base/errorCodes.js} +98 -110
  21. package/core/{errorHints.js → base/errorHints.js} +5 -9
  22. package/core/{errors.js → base/errors.js} +6 -6
  23. package/core/{events.generated.js → base/events.generated.js} +1 -0
  24. package/core/{math.js → base/math.js} +15 -4
  25. package/core/{params.js → base/params.js} +3 -4
  26. package/core/base/util.js +32 -0
  27. package/core/{validate.js → base/validate.js} +28 -7
  28. package/core/{Engine.js → engine/Engine.js} +80 -77
  29. package/core/{Loading.js → engine/Loading.js} +4 -2
  30. package/core/{copies.js → engine/copies.js} +4 -4
  31. package/core/{headlessLoad.js → engine/headlessLoad.js} +4 -4
  32. package/core/{lifecycle.js → engine/lifecycle.js} +14 -12
  33. package/core/{loop.js → engine/loop.js} +68 -47
  34. package/core/{moduleSlots.js → engine/moduleSlots.js} +6 -6
  35. package/core/{moduleTypes.js → engine/moduleTypes.js} +13 -14
  36. package/core/{modules.js → engine/modules.js} +14 -11
  37. package/core/{page.js → engine/page.js} +36 -23
  38. package/core/{plugins.js → engine/plugins.js} +6 -9
  39. package/core/{services.js → engine/services.js} +47 -40
  40. package/core/{startup.js → engine/startup.js} +26 -24
  41. package/core/{Input.js → input/Input.js} +30 -22
  42. package/core/{inputContext.js → input/inputContext.js} +14 -5
  43. package/core/{inputPad.js → input/inputPad.js} +1 -1
  44. package/core/{inputPointer.js → input/inputPointer.js} +8 -2
  45. package/core/{inputTouch.js → input/inputTouch.js} +1 -1
  46. package/core/{Budget.js → inspect/Budget.js} +21 -20
  47. package/core/{DebugOverrides.js → inspect/DebugOverrides.js} +30 -16
  48. package/core/{Describe.js → inspect/Describe.js} +26 -22
  49. package/core/{Inspect.js → inspect/Inspect.js} +9 -7
  50. package/core/{InspectMaterials.js → inspect/InspectMaterials.js} +7 -8
  51. package/core/{InspectPerf.js → inspect/InspectPerf.js} +19 -13
  52. package/core/{InspectScene.js → inspect/InspectScene.js} +8 -5
  53. package/core/{MaterialInfo.js → inspect/MaterialInfo.js} +3 -2
  54. package/core/{UrlState.js → inspect/UrlState.js} +52 -20
  55. package/core/{catalog.js → inspect/catalog.js} +3 -3
  56. package/core/{checks.js → inspect/checks.js} +7 -5
  57. package/core/{debugView.js → inspect/debugView.js} +4 -4
  58. package/core/{describeRender.js → inspect/describeRender.js} +21 -20
  59. package/core/{describeText.js → inspect/describeText.js} +11 -6
  60. package/core/inspect/geometryWatch.js +38 -0
  61. package/core/{lightWatch.js → inspect/lightWatch.js} +8 -8
  62. package/core/{pictureWriters.js → inspect/pictureWriters.js} +15 -16
  63. package/core/{shaderCost.js → inspect/shaderCost.js} +1 -1
  64. package/core/{Ops.js → ops/Ops.js} +16 -11
  65. package/core/{control.js → ops/control.js} +13 -12
  66. package/core/ops/holds.js +139 -0
  67. package/core/{opsAtomic.js → ops/opsAtomic.js} +2 -1
  68. package/core/{opsCheck.js → ops/opsCheck.js} +4 -5
  69. package/core/{opsGuard.js → ops/opsGuard.js} +3 -3
  70. package/core/{opsRun.js → ops/opsRun.js} +7 -4
  71. package/core/{owned.js → ops/owned.js} +14 -17
  72. package/core/{sharedPoint.js → ops/sharedPoint.js} +8 -8
  73. package/core/{stackFrames.js → ops/stackFrames.js} +2 -2
  74. package/core/{stacks.js → ops/stacks.js} +12 -14
  75. package/core/{wrap.js → ops/wrap.js} +8 -6
  76. package/core/{SaveStore.js → saves/SaveStore.js} +1 -1
  77. package/core/{Saves.js → saves/Saves.js} +58 -36
  78. package/core/{saveApply.js → saves/saveApply.js} +13 -9
  79. package/core/{saveFiles.js → saves/saveFiles.js} +17 -15
  80. package/core/{saveValues.js → saves/saveValues.js} +20 -3
  81. package/core/{saveVersions.js → saves/saveVersions.js} +4 -17
  82. package/core/{session.js → saves/session.js} +31 -17
  83. package/core/{Rays.js → scene/Rays.js} +23 -25
  84. package/core/{Views.js → scene/Views.js} +14 -6
  85. package/core/{adaptive.js → scene/adaptive.js} +15 -8
  86. package/core/{canvasBox.js → scene/canvasBox.js} +2 -3
  87. package/core/{engineCamera.js → scene/engineCamera.js} +1 -1
  88. package/core/{gameLights.js → scene/gameLights.js} +17 -7
  89. package/core/{grayMap.js → scene/grayMap.js} +8 -2
  90. package/core/{grid.js → scene/grid.js} +4 -4
  91. package/core/{gridLoad.js → scene/gridLoad.js} +1 -1
  92. package/core/{ground.js → scene/ground.js} +9 -9
  93. package/core/{movement.js → scene/movement.js} +3 -3
  94. package/core/{pictureSlots.js → scene/pictureSlots.js} +2 -2
  95. package/core/{sceneDelta.js → scene/sceneDelta.js} +2 -2
  96. package/core/{sceneMethods.js → scene/sceneMethods.js} +36 -13
  97. package/core/scene/stepPoses.js +55 -0
  98. package/core/{targeting.js → scene/targeting.js} +4 -5
  99. package/core/{thingExplain.js → scene/thingExplain.js} +6 -5
  100. package/core/{thingOps.js → scene/thingOps.js} +4 -3
  101. package/core/{things.js → scene/things.js} +18 -5
  102. package/core/{threePatches.js → scene/threePatches.js} +1 -1
  103. package/core/{view.js → scene/view.js} +17 -16
  104. package/core/{Batching.js → stream/Batching.js} +85 -27
  105. package/core/{Stream.js → stream/Stream.js} +60 -30
  106. package/core/{batchGroups.js → stream/batchGroups.js} +10 -9
  107. package/core/{chunkStream.js → stream/chunkStream.js} +40 -0
  108. package/core/{scatter.js → stream/scatter.js} +2 -2
  109. package/core/{streamSources.js → stream/streamSources.js} +12 -7
  110. package/core/{Commits.js → threads/Commits.js} +6 -5
  111. package/core/{Jobs.js → threads/Jobs.js} +12 -10
  112. package/core/{Threads.js → threads/Threads.js} +16 -16
  113. package/core/{threadPure.js → threads/threadPure.js} +7 -5
  114. package/core/{threadServe.js → threads/threadServe.js} +3 -3
  115. package/core/{Clock.js → time/Clock.js} +17 -10
  116. package/core/{dayTime.js → time/dayTime.js} +5 -1
  117. package/core/{skip.js → time/skip.js} +18 -17
  118. package/core/{time.js → time/time.js} +18 -12
  119. package/core/{uiClock.js → time/uiClock.js} +4 -4
  120. package/docs/AI.md +22 -19
  121. package/docs/API.md +24 -23
  122. package/docs/CODEMAP.md +76 -183
  123. package/docs/COMMANDS.md +66 -58
  124. package/docs/CONVENTIONS.md +54 -14
  125. package/docs/MIGRATING-0.8.md +169 -0
  126. package/docs/THREE.md +78 -29
  127. package/docs/api/assets.md +12 -13
  128. package/docs/api/audio.md +6 -5
  129. package/docs/api/budget.md +4 -4
  130. package/docs/api/calendar.md +10 -11
  131. package/docs/api/cameraRig.md +29 -29
  132. package/docs/api/characters.md +23 -18
  133. package/docs/api/clock.md +1 -1
  134. package/docs/api/collision.md +12 -9
  135. package/docs/api/content.md +6 -6
  136. package/docs/api/dialogue.md +3 -3
  137. package/docs/api/engine.md +45 -43
  138. package/docs/api/events.md +3 -2
  139. package/docs/api/flow.md +1 -1
  140. package/docs/api/grids.md +1 -1
  141. package/docs/api/ground.md +4 -5
  142. package/docs/api/hud.md +2 -2
  143. package/docs/api/i18n.md +6 -6
  144. package/docs/api/input.md +7 -7
  145. package/docs/api/interactions.md +4 -4
  146. package/docs/api/inventory.md +9 -9
  147. package/docs/api/jobs.md +5 -5
  148. package/docs/api/level.md +7 -7
  149. package/docs/api/lightPool.md +1 -6
  150. package/docs/api/music.md +3 -3
  151. package/docs/api/nav.md +10 -10
  152. package/docs/api/openWorld.md +1 -1
  153. package/docs/api/particles.md +2 -2
  154. package/docs/api/photo.md +4 -2
  155. package/docs/api/pickups.md +2 -2
  156. package/docs/api/post.md +20 -3
  157. package/docs/api/quests.md +3 -3
  158. package/docs/api/rays.md +5 -7
  159. package/docs/api/rigid.md +27 -18
  160. package/docs/api/saves.md +8 -7
  161. package/docs/api/settings.md +9 -8
  162. package/docs/api/sky.md +8 -7
  163. package/docs/api/stream.md +7 -7
  164. package/docs/api/swarm.md +34 -0
  165. package/docs/api/terrain.md +7 -8
  166. package/docs/api/terrainDraw.md +1 -1
  167. package/docs/api/timeline.md +2 -2
  168. package/docs/api/tools.md +25 -22
  169. package/docs/api/vars.md +1 -1
  170. package/docs/api/vegetation.md +4 -3
  171. package/docs/api/vegetationDraw.md +1 -1
  172. package/docs/api/water.md +1 -1
  173. package/docs/api/weather.md +9 -9
  174. package/docs/api/weatherDraw.md +3 -3
  175. package/docs/api/world.md +5 -5
  176. package/docs/recipes/01-new-game.md +25 -40
  177. package/docs/recipes/02-npc.md +19 -20
  178. package/docs/recipes/03-items-pickups.md +27 -43
  179. package/docs/recipes/04-quests.md +3 -4
  180. package/docs/recipes/05-props-bake.md +29 -39
  181. package/docs/recipes/06-clock-events.md +27 -18
  182. package/docs/recipes/07-flow-scenes-pause.md +12 -17
  183. package/docs/recipes/08-weather-sky.md +88 -34
  184. package/docs/recipes/09-materials-lights-models.md +22 -36
  185. package/docs/recipes/10-blender-level.md +6 -7
  186. package/docs/recipes/11-vehicles.md +30 -22
  187. package/docs/recipes/12-navmesh.md +9 -8
  188. package/docs/recipes/13-animation.md +39 -17
  189. package/docs/recipes/14-custom-module.md +14 -13
  190. package/docs/recipes/15-perf.md +49 -26
  191. package/docs/recipes/16-dev-bridge.md +32 -52
  192. package/docs/recipes/18-world.md +36 -23
  193. package/docs/recipes/19-shooting-picking.md +4 -2
  194. package/docs/recipes/20-content-actions-save.md +30 -35
  195. package/docs/recipes/21-camera.md +33 -5
  196. package/docs/recipes/22-shop-gold.md +0 -4
  197. package/docs/recipes/23-ops.md +10 -10
  198. package/docs/recipes/26-ui-parts.md +22 -12
  199. package/docs/recipes/27-net.md +0 -2
  200. package/docs/recipes/28-terrain.md +117 -21
  201. package/docs/recipes/29-grid.md +2 -2
  202. package/docs/recipes/30-templates.md +55 -19
  203. package/docs/recipes/31-audio.md +5 -5
  204. package/docs/recipes/32-action-game.md +15 -6
  205. package/docs/recipes/33-stream-sources.md +2 -2
  206. package/docs/recipes/34-environment-lighting.md +67 -19
  207. package/docs/recipes/35-picture-from-reference.md +10 -17
  208. package/docs/recipes/36-ground-plants.md +105 -0
  209. package/docs/recipes/40-scene.md +7 -11
  210. package/docs/recipes/43-shader-patches-surfaces.md +20 -41
  211. package/docs/recipes/44-water-weather-hooks.md +48 -43
  212. package/docs/recipes/45-cascaded-shadows.md +39 -17
  213. package/docs/recipes/46-blender-art-route.md +7 -8
  214. package/docs/recipes/49-game-module-contract.md +5 -5
  215. package/docs/recipes/50-own-renderer.md +2 -2
  216. package/docs/recipes/52-around-the-picture.md +54 -98
  217. package/docs/recipes/53-ground-up-close.md +61 -24
  218. package/docs/recipes/55-mods-time-wrap.md +12 -16
  219. package/docs/recipes/56-webgpu-tsl.md +16 -14
  220. package/docs/recipes/57-control.md +9 -2
  221. package/docs/recipes/58-input.md +2 -2
  222. package/docs/recipes/59-depth-post-effects.md +1 -1
  223. package/docs/recipes/60-judge-the-picture.md +29 -24
  224. package/docs/recipes/62-picture-code.md +49 -17
  225. package/docs/recipes/63-third-person-start.md +17 -4
  226. package/docs/recipes/64-particles.md +1 -1
  227. package/docs/recipes/65-swarm.md +140 -0
  228. package/examples/action/.threedog/content-index.json +1 -1
  229. package/examples/action/GAMEMAP.md +2 -2
  230. package/examples/{sheepisland → perf-island}/.threedog/content-index.json +1 -1
  231. package/examples/{sheepisland → perf-island}/GAMEMAP.md +12 -11
  232. package/examples/{sheepisland → perf-island}/assets.js +1 -1
  233. package/examples/{sheepisland → perf-island}/main.js +8 -8
  234. package/examples/{sheepisland → perf-island}/models.js +1 -1
  235. package/examples/{sheepisland → perf-island}/params.js +1 -1
  236. package/examples/{sheepisland → perf-island}/picture/index.js +1 -1
  237. package/examples/{sheepisland → perf-island}/picture/palette.js +2 -2
  238. package/examples/{sheepisland → perf-island}/views.js +1 -1
  239. package/examples/plain-picture/GAMEMAP.md +1 -0
  240. package/examples/rc2d/GAMEMAP.md +3 -2
  241. package/examples/rc2d/main.js +1 -3
  242. package/examples/styletest/.threedog/content-index.json +1 -1
  243. package/examples/styletest/GAMEMAP.md +3 -2
  244. package/examples/techniques/contact-shadows/contactShadows.js +1 -1
  245. package/examples/techniques/contact-shadows/main.js +1 -1
  246. package/examples/techniques/interior-light/main.js +1 -1
  247. package/examples/techniques/modular-building/README.md +7 -6
  248. package/examples/techniques/outlines-and-rim/picture/post.js +1 -1
  249. package/examples/techniques/procedural-animation/README.md +1 -1
  250. package/examples/webgpu-tsl/GAMEMAP.md +1 -0
  251. package/examples/world/.threedog/content-index.json +1 -1
  252. package/examples/world/GAMEMAP.md +4 -3
  253. package/examples/world/picture/sky.js +1 -1
  254. package/index.d.ts +8 -7
  255. package/index.js +31 -31
  256. package/llms.txt +9 -13
  257. package/modules/ambience/Ambience.js +11 -8
  258. package/modules/calendar/Calendar.js +19 -19
  259. package/modules/calendar/index.js +13 -13
  260. package/modules/calendar/schedule.js +11 -6
  261. package/modules/calendar/seasons.js +7 -7
  262. package/modules/camera/FirstPersonCamera.js +2 -2
  263. package/modules/camera/FixedCamera.js +14 -15
  264. package/modules/camera/FollowCamera.js +4 -4
  265. package/modules/camera/RtsCamera.js +11 -11
  266. package/modules/camera/common.js +48 -24
  267. package/modules/camera/contract.js +1 -0
  268. package/modules/camera/projection.js +2 -2
  269. package/modules/characters/Character.js +33 -30
  270. package/modules/characters/NPC.js +27 -19
  271. package/modules/characters/assetModel.js +14 -10
  272. package/modules/characters/astar.js +7 -5
  273. package/modules/characters/behaviors.js +4 -5
  274. package/modules/characters/contract.js +2 -2
  275. package/modules/characters/index.js +168 -214
  276. package/modules/characters/moveHelpers.js +14 -3
  277. package/modules/characters/movers/common.js +16 -14
  278. package/modules/characters/movers/manual.js +1 -1
  279. package/modules/characters/movers/rapier.js +7 -6
  280. package/modules/characters/movers/simple.js +3 -3
  281. package/modules/characters/movers/support.js +8 -8
  282. package/modules/characters/npcAvoid.js +4 -4
  283. package/modules/characters/npcSim.js +23 -17
  284. package/modules/characters/npcView.js +6 -5
  285. package/modules/characters/pathAsync.js +12 -10
  286. package/modules/characters/pathWorker.js +1 -1
  287. package/modules/characters/player.js +108 -0
  288. package/modules/characters/playerStrings.js +2 -2
  289. package/modules/characters/proceduralRig.js +2 -2
  290. package/modules/characters/useModel.js +3 -3
  291. package/modules/characters/walkTo.js +11 -17
  292. package/modules/collision/Collision.js +26 -20
  293. package/modules/collision/contract.js +15 -0
  294. package/modules/content/explain.js +1 -2
  295. package/modules/content/fields.js +24 -3
  296. package/modules/content/ids.js +2 -2
  297. package/modules/content/index.js +61 -99
  298. package/modules/content/loader.js +14 -17
  299. package/modules/content/markers.js +25 -0
  300. package/modules/content/models.js +10 -7
  301. package/modules/content/packs.js +3 -3
  302. package/modules/content/parts.js +2 -2
  303. package/modules/content/places.js +35 -0
  304. package/modules/content/props.js +17 -14
  305. package/modules/content/rules.js +25 -21
  306. package/modules/content/stages.js +7 -7
  307. package/modules/content/templates.js +20 -20
  308. package/modules/content/words.js +34 -0
  309. package/modules/debug/DebugPanel.js +10 -43
  310. package/modules/flow/contract.js +1 -1
  311. package/modules/flow/index.js +11 -7
  312. package/modules/gameplay/Container.js +12 -11
  313. package/modules/gameplay/Containers.js +14 -5
  314. package/modules/gameplay/Dialogue.js +13 -11
  315. package/modules/gameplay/Interactions.js +37 -24
  316. package/modules/gameplay/Inventory.js +8 -9
  317. package/modules/gameplay/Quests.js +16 -9
  318. package/modules/gameplay/boxOps.js +1 -1
  319. package/modules/gameplay/dialogueBubbles.js +3 -4
  320. package/modules/gameplay/inventoryOps.js +0 -1
  321. package/modules/gameplay/pickups.js +22 -23
  322. package/modules/gameplay/questSave.js +3 -3
  323. package/modules/grid/Grid.js +1 -1
  324. package/modules/grid/Layer.js +4 -4
  325. package/modules/grid/index.js +7 -8
  326. package/modules/grid/preview.js +7 -7
  327. package/modules/grid/tiles.js +6 -6
  328. package/modules/hlod/index.js +37 -55
  329. package/modules/hud/index.js +17 -11
  330. package/modules/hud/parts.js +4 -4
  331. package/modules/level/contract.js +16 -0
  332. package/modules/level/heightfield.js +12 -10
  333. package/modules/level/index.js +47 -152
  334. package/modules/level/load.js +79 -0
  335. package/modules/level/meshes.js +65 -0
  336. package/modules/level/nodes.js +6 -7
  337. package/modules/lights/index.js +28 -181
  338. package/modules/lights/slots.js +93 -0
  339. package/modules/lights/sources.js +88 -0
  340. package/modules/music/Music.js +30 -26
  341. package/modules/music/rules.js +1 -1
  342. package/modules/nav/contract.js +14 -0
  343. package/modules/nav/index.js +11 -10
  344. package/modules/net/Client.js +7 -7
  345. package/modules/net/Host.js +7 -7
  346. package/modules/net/Net.js +1 -1
  347. package/modules/net/index.js +5 -4
  348. package/modules/net/sync.js +2 -2
  349. package/modules/net/transports.js +2 -2
  350. package/modules/particles/Particles.js +11 -8
  351. package/modules/particles/effect.js +7 -5
  352. package/modules/particles/shaders.js +2 -1
  353. package/modules/photo/Photo.js +15 -17
  354. package/modules/rigid/RigidBodies.js +66 -43
  355. package/modules/rigid/Vehicles.js +2 -3
  356. package/modules/rigid/ragdoll.js +287 -0
  357. package/modules/rigid/ragdollBones.js +159 -0
  358. package/modules/rigid/sync.js +6 -6
  359. package/modules/settings/Settings.js +108 -39
  360. package/modules/settings/apply.js +6 -6
  361. package/modules/settings/sections.js +16 -14
  362. package/modules/settings/view.js +3 -3
  363. package/modules/sky/Sky.js +29 -22
  364. package/modules/sky/clouds.js +7 -7
  365. package/modules/sky/dome.js +33 -20
  366. package/modules/sky/domeLayers.js +9 -9
  367. package/modules/sky/environment.js +6 -6
  368. package/modules/sky/frame.js +19 -10
  369. package/modules/sky/season.js +7 -1
  370. package/modules/sky/shader.js +24 -25
  371. package/modules/sky/skyModule.js +14 -27
  372. package/modules/sky/tint.js +1 -1
  373. package/modules/swarm/Swarm.js +346 -0
  374. package/modules/swarm/draw.js +68 -0
  375. package/modules/swarm/grid.js +63 -0
  376. package/modules/terrain/ChunkManager.js +70 -52
  377. package/modules/terrain/chunkQueries.js +7 -24
  378. package/modules/terrain/chunkWorker.js +1 -1
  379. package/modules/terrain/draw.js +14 -11
  380. package/modules/terrain/index.js +28 -34
  381. package/modules/terrain/terrainColorMap.js +6 -3
  382. package/modules/terrain/terrainDefaults.js +2 -1
  383. package/modules/terrain/terrainEdit.js +32 -27
  384. package/modules/terrain/terrainGen.js +17 -12
  385. package/modules/terrain/terrainIsland.js +2 -2
  386. package/modules/terrain/terrainMesh.js +7 -6
  387. package/modules/terrain/terrainShape.js +8 -10
  388. package/modules/terrain/terrainShapeMain.js +3 -3
  389. package/modules/timeline/Timeline.js +27 -19
  390. package/modules/timeline/Tween.js +6 -6
  391. package/modules/timeline/shots.js +5 -7
  392. package/modules/triggers/index.js +9 -9
  393. package/modules/vegetation/Vegetation.js +30 -23
  394. package/modules/vegetation/densityMap.js +4 -7
  395. package/modules/vegetation/draw.js +23 -18
  396. package/modules/vegetation/groundChunks.js +11 -31
  397. package/modules/vegetation/index.js +8 -6
  398. package/modules/vegetation/modelGeometry.js +3 -6
  399. package/modules/vegetation/nearFade.js +1 -1
  400. package/modules/water/Water.js +16 -16
  401. package/modules/water/surface.js +3 -3
  402. package/modules/weather/Weather.js +41 -30
  403. package/modules/weather/particles.js +8 -8
  404. package/modules/weather/weatherDraw.js +22 -18
  405. package/modules/world/World.js +8 -8
  406. package/modules/world/explain.js +1 -1
  407. package/modules/world/index.js +18 -12
  408. package/modules/world/persist.js +73 -25
  409. package/modules/world/pos.js +4 -4
  410. package/modules/world/records.js +28 -8
  411. package/modules/world/sim.js +4 -4
  412. package/modules/world/state.js +12 -5
  413. package/modules/world/thingSource.js +4 -2
  414. package/modules/world/views.js +11 -9
  415. package/package.json +42 -7
  416. package/presets.js +1 -3
  417. package/render/PostFX.js +39 -27
  418. package/render/backend.js +26 -32
  419. package/render/cascades.js +17 -12
  420. package/render/cascades.tsl.js +5 -8
  421. package/render/daylight.js +20 -3
  422. package/render/detail.js +8 -7
  423. package/render/effects.js +28 -25
  424. package/render/fuse.js +3 -3
  425. package/render/fx/cloudShadow.tsl.js +3 -3
  426. package/render/fx/detail.tsl.js +1 -1
  427. package/render/fx/index.js +5 -10
  428. package/render/fx/library.tsl.js +11 -0
  429. package/render/fx/lighting.tsl.js +2 -1
  430. package/render/fx/nodeErrors.tsl.js +2 -2
  431. package/render/fx/objectOrigin.tsl.js +1 -2
  432. package/render/fx/patchNodes.tsl.js +5 -15
  433. package/render/fx/postWebGPU.tsl.js +27 -23
  434. package/render/fx/sky.tsl.js +15 -17
  435. package/render/fx/uniforms.tsl.js +4 -4
  436. package/render/fx/wind.tsl.js +1 -1
  437. package/render/fxNumbers.js +3 -0
  438. package/render/layers.js +1 -1
  439. package/render/lighting.js +5 -3
  440. package/render/lightmap.js +20 -20
  441. package/render/lights.js +6 -6
  442. package/render/lit.js +24 -0
  443. package/render/materials.js +8 -7
  444. package/render/mergeCommon.js +22 -0
  445. package/render/modeling.js +2 -2
  446. package/render/occlusion.js +20 -4
  447. package/render/ownFrame.js +4 -4
  448. package/render/patches.js +13 -13
  449. package/render/postWebGL.js +12 -10
  450. package/render/probes.js +16 -19
  451. package/render/recordSweep.js +117 -0
  452. package/render/shaderErrors.js +10 -9
  453. package/render/shadowCache.tsl.js +107 -0
  454. package/render/shadowTypes.js +9 -0
  455. package/{core → render}/shadows.js +57 -11
  456. package/render/slots.js +7 -7
  457. package/render/terms.js +22 -24
  458. package/render/uniformDecl.js +1 -1
  459. package/types/core.d.ts +200 -153
  460. package/types/gameplay.d.ts +163 -91
  461. package/types/generated/core/{Audio.d.ts → audio/Audio.d.ts} +22 -7
  462. package/types/generated/core/{audioVoice.d.ts → audio/audioVoice.d.ts} +2 -2
  463. package/types/generated/core/{Events.d.ts → base/Events.d.ts} +4 -4
  464. package/types/generated/core/{I18n.d.ts → base/I18n.d.ts} +7 -15
  465. package/types/generated/core/{Random.d.ts → base/Random.d.ts} +4 -3
  466. package/types/generated/core/{page.d.ts → engine/page.d.ts} +8 -9
  467. package/types/generated/core/{Input.d.ts → input/Input.d.ts} +12 -8
  468. package/types/generated/core/{Budget.d.ts → inspect/Budget.d.ts} +36 -26
  469. package/types/generated/core/{DebugOverrides.d.ts → inspect/DebugOverrides.d.ts} +2 -2
  470. package/types/generated/core/{Ops.d.ts → ops/Ops.d.ts} +4 -3
  471. package/types/generated/core/{control.d.ts → ops/control.d.ts} +4 -10
  472. package/types/generated/core/{Saves.d.ts → saves/Saves.d.ts} +37 -13
  473. package/types/generated/core/{session.d.ts → saves/session.d.ts} +2 -1
  474. package/types/generated/core/{Rays.d.ts → scene/Rays.d.ts} +8 -27
  475. package/types/generated/core/{Views.d.ts → scene/Views.d.ts} +1 -1
  476. package/types/generated/core/{Batching.d.ts → stream/Batching.d.ts} +7 -7
  477. package/types/generated/core/{Stream.d.ts → stream/Stream.d.ts} +18 -16
  478. package/types/generated/core/{Commits.d.ts → threads/Commits.d.ts} +1 -1
  479. package/types/generated/core/{Jobs.d.ts → threads/Jobs.d.ts} +6 -6
  480. package/types/generated/core/{Threads.d.ts → threads/Threads.d.ts} +4 -4
  481. package/types/generated/modules/calendar/Calendar.d.ts +10 -11
  482. package/types/generated/modules/debug/DebugPanel.d.ts +1 -9
  483. package/types/generated/modules/grid/Layer.d.ts +1 -1
  484. package/types/generated/modules/grid/index.d.ts +3 -3
  485. package/types/generated/modules/music/Music.d.ts +7 -5
  486. package/types/generated/modules/particles/Particles.d.ts +1 -1
  487. package/types/generated/modules/sky/Sky.d.ts +21 -10
  488. package/types/generated/modules/swarm/Swarm.d.ts +80 -0
  489. package/types/generated/modules/timeline/Timeline.d.ts +2 -1
  490. package/types/generated/modules/water/Water.d.ts +1 -0
  491. package/types/generated/modules/weather/Weather.d.ts +16 -12
  492. package/types/generated/modules/weather/weatherDraw.d.ts +3 -3
  493. package/types/generated/modules/world/World.d.ts +5 -3
  494. package/types/generated/render/PostFX.d.ts +17 -11
  495. package/types/generated/render/materials.d.ts +1 -0
  496. package/types/generated/render/occlusion.d.ts +9 -0
  497. package/types/generated/render/patches.d.ts +1 -0
  498. package/types/generated/ui/Focus.d.ts +1 -0
  499. package/types/generated/ui/UI.d.ts +1 -0
  500. package/types/nav.d.ts +11 -11
  501. package/types/physics.d.ts +99 -70
  502. package/types/tsl.d.ts +37 -4
  503. package/types/world.d.ts +38 -71
  504. package/ui/Focus.js +10 -9
  505. package/ui/Parts.js +4 -3
  506. package/ui/UI.js +7 -7
  507. package/ui/defaults.js +3 -2
  508. package/ui/theme.js +5 -3
  509. package/core/assetEntry.js +0 -109
  510. package/core/holds.js +0 -134
  511. package/core/shadowTypes.js +0 -16
  512. package/core/util.js +0 -17
  513. package/docs/MIGRATING-0.3.md +0 -248
  514. package/docs/MIGRATING-0.4.md +0 -320
  515. package/docs/MIGRATING-0.5.md +0 -68
  516. package/docs/MIGRATING-0.6.md +0 -126
  517. package/docs/PERF.md +0 -245
  518. package/docs/recipes/36-sky-ground-plants.md +0 -158
  519. package/docs/recipes/37-terrain-hooks.md +0 -115
  520. package/docs/recipes/38-environment-hooks.md +0 -67
  521. package/docs/recipes/42-terrain-shape.md +0 -64
  522. package/docs/recipes/47-island-snow-backdrop.md +0 -43
  523. package/docs/recipes/54-three-idioms.md +0 -88
  524. package/examples/plain-picture/FINDINGS.md +0 -53
  525. /package/core/{Vars.js → base/Vars.js} +0 -0
  526. /package/core/{mulberry32.js → base/mulberry32.js} +0 -0
  527. /package/core/{inputDefaults.js → input/inputDefaults.js} +0 -0
  528. /package/core/{textureBytes.js → inspect/textureBytes.js} +0 -0
  529. /package/core/{actor.js → ops/actor.js} +0 -0
  530. /package/core/{opsFail.js → ops/opsFail.js} +0 -0
  531. /package/core/{opsHistory.js → ops/opsHistory.js} +0 -0
  532. /package/core/{saveIds.js → saves/saveIds.js} +0 -0
  533. /package/core/{screenToGround.js → scene/screenToGround.js} +0 -0
  534. /package/core/{tier.js → scene/tier.js} +0 -0
  535. /package/core/{cells.js → stream/cells.js} +0 -0
  536. /package/core/{streamCells.js → stream/streamCells.js} +0 -0
  537. /package/core/{pureWorker.js → threads/pureWorker.js} +0 -0
  538. /package/examples/{sheepisland → perf-island}/content/index.js +0 -0
  539. /package/examples/{sheepisland → perf-island}/content/props.js +0 -0
  540. /package/examples/{sheepisland → perf-island}/content/templates.js +0 -0
  541. /package/examples/{sheepisland → perf-island}/content/vegetation.js +0 -0
  542. /package/examples/{sheepisland → perf-island}/picture/lights.js +0 -0
  543. /package/examples/{sheepisland → perf-island}/picture/materials.js +0 -0
  544. /package/examples/{sheepisland → perf-island}/picture/sky.js +0 -0
@@ -1,7 +1,7 @@
1
1
  // One ownership model for every property the engine writes on its own (a sky's background, the shadow box's center, camera, pixel ratio ...).
2
2
  //
3
3
  // const o = defineOwned(engine, { id: 'view.far', part: 'view', key: 'far', read: () => camera.far, write: v => { camera.far = v; },
4
- // levels: { manual: "engine.view.manual('far')" } });
4
+ // levels: { manual: "engine.autoView.manual('far')" } });
5
5
  // per frame: o.check(); if (o.on) target.position.copy(focus); o.mark(); (or o.drive(v) when the write is one value: needs write)
6
6
  //
7
7
  // Why "the engine yields" (user decision 1, 2026-11-02): a game that writes sun.target.position directly means it. Silently writing the old value
@@ -9,10 +9,10 @@
9
9
  // to the game (mode 'yielded'), the value stays, and one warning names the explicit takeover and the hand-back. Detection runs in release builds too
10
10
  // (a few number compares per frame), so the game behaves the same with and without dev checks; only the warning text is dev-only.
11
11
  //
12
- // Modes per property: 'engine' (the engine writes it) | 'manual' (engine.view.manual(key), or the entry that hands the value to the game) | 'yielded'
13
- // (the game wrote it directly). engine.view.manual(key, false) hands any of them back. describe().owned lists them all.
14
- import { warnOnce, DEV } from './validate.js';
15
- import { codedError, coded } from './errorHints.js';
12
+ // Modes per property: 'engine' (the engine writes it) | 'manual' (engine.autoView.manual(key), or the entry that hands the value to the game) | 'yielded'
13
+ // (the game wrote it directly). engine.autoView.manual(key, false) hands any of them back. describe().owned lists them all.
14
+ import { warnOnce, DEV, fmt } from '../base/validate.js';
15
+ import { codedError, coded } from '../base/errorHints.js';
16
16
 
17
17
  const STRINGS = { // yielded: the prefix up to "stopped writing it" is matched by tests (the owned-prop tag carries the fix); the rest leads with the next calls
18
18
  yielded: '{id} was changed outside the engine, so the engine stopped writing it (your value stays). Next: {manual} to own it on purpose (no warning);{set} ' +
@@ -26,7 +26,7 @@ const exempt = new Map(); // owner -> Set of ids (strings) and objects
26
26
  const live = new Set(); // every registered property on the page: ending an exemption re-reads the ones it covered
27
27
  /**
28
28
  * Exempt properties from outside-write detection while owner animates them (a timeline tweening a light): neither a warning nor a yield.
29
- * @param {string} owner @param {Iterable<any> | false} [what] owned ids ('sun.intensity') or the three.js objects being animated; false ends it
29
+ * @param {any} owner a name or any unique key @param {Iterable<any> | false} [what] owned ids ('sun.intensity') or the three.js objects being animated; false ends it
30
30
  */
31
31
  export function allowOwned(owner, what) {
32
32
  if (what === false || what == null) {
@@ -58,8 +58,8 @@ class Owned {
58
58
  /** who took it: 'game' (manual()), or 'three' for a direct write */ this.by = 'engine';
59
59
  this._snap = null;
60
60
  this._onChange = spec.onChange;
61
- // once: the engine writes it once, at creation (renderer.toneMapping). So a direct write is the documented way to change it (yielding warns
62
- // nothing), and handing it back writes the creation value again (spec.write)
61
+ // once: the engine never writes it, it only keeps the value read here (renderer.toneMapping). So a direct write is the documented way to change it (yielding warns
62
+ // nothing), and handing it back writes that value again (spec.write)
63
63
  this._once = spec.once ? { value: this._read() } : null;
64
64
  }
65
65
  /** Does the engine write this property now */
@@ -72,8 +72,7 @@ class Owned {
72
72
  this._set('yielded', 'three');
73
73
  if (DEV && this._e.validate && !this._once) {
74
74
  const L = this.levels, back = L.back ?? L.manual.replace(/\(([^()]*)\)\s*$/, (_, a) => `(${a ? a + ', ' : ''}false)`);
75
- warnOnce(coded('owned-prop', STRINGS.yielded.replace('{id}', this.id).replace('{manual}', L.manual)
76
- .replace('{set}', L.set ? STRINGS.set.replace('{set}', L.set) : '').replace('{back}', back)));
75
+ warnOnce(coded('owned-prop', fmt(STRINGS.yielded, { id: this.id, manual: L.manual, set: L.set ? fmt(STRINGS.set, { set: L.set }) : '', back })));
77
76
  }
78
77
  }
79
78
  /**
@@ -95,14 +94,14 @@ class Owned {
95
94
  this.mode = mode; this.by = by; this.at = this._e.time?.frame ?? null;
96
95
  if (was !== mode) this._onChange?.(this);
97
96
  }
98
- /** describe().owned row: writer = who writes it now ('engine' | 'manual:<who>' | 'three (engine yielded)'); the old field name `by` throws */
97
+ /** describe().owned row: writer = who writes it now ('engine' | 'manual:<who>' | 'three (engine yielded)') */
99
98
  info() {
100
99
  return ({ part: this.part, key: this.key, writer: this.mode === 'engine' ? 'engine' : this.mode === 'yielded' ? 'three (engine yielded)' : `manual:${this.by}`, ...(this.levels.manual ? { manual: this.levels.manual } : {}) });
101
100
  }
102
101
  }
103
102
 
104
103
  /**
105
- * Written-once values (toneMapping) never meet an engine write that would notice a takeover, so describe() looks before any section reads
104
+ * Values the engine only keeps and never writes (toneMapping) meet no engine write that would notice a takeover, so describe() looks before any section reads
106
105
  * them. Why one place: the render section checked on its own, after the picture section had read the stale writer, and describe('owned') alone
107
106
  * said 'engine' for a curve the game had set
108
107
  * @param {any} engine @internal
@@ -114,7 +113,7 @@ export function checkWrittenOnce(engine) { for (const o of engine._owned?.values
114
113
  * @param {any} engine
115
114
  * @param {{ id: string, part: string, key?: string, read: () => any, write?: (v: any) => void, objects?: any[],
116
115
  * levels: { manual: string, set?: string, back?: string }, onChange?: (o: Owned) => void, once?: boolean }} spec
117
- * part: the group whose manual() takes it (engine.view.manual(key)); key: the name manual() matches (prefix match on dots: 'sun' takes
116
+ * part: the group whose manual() takes it (engine.autoView.manual(key)); key: the name manual() matches (prefix match on dots: 'sun' takes
118
117
  * 'sun.intensity' and 'sun.color'); once: written only at creation (read now is the creation value; needs write for the hand-back); levels: the copyable calls the warning quotes (manual is required); onChange: mode changed (the sky hides its dome when the game
119
118
  * takes scene.background)
120
119
  * @returns {Owned}
@@ -122,7 +121,7 @@ export function checkWrittenOnce(engine) { for (const o of engine._owned?.values
122
121
  export function defineOwned(engine, spec) {
123
122
  if (!spec?.id || !spec.part || typeof spec.read !== 'function') throw codedError('owned-misuse', 'defineOwned(engine, { id, part, read, write?, levels }): id, part and read are required');
124
123
  // the yield warning leads with this call, so a property nobody can take on purpose cannot be registered
125
- if (typeof spec.levels?.manual !== 'string' || !spec.levels.manual) throw codedError('owned-misuse', `defineOwned(engine, { id: '${spec.id}', levels: { manual } }): levels.manual is required, the copyable takeover call the warning quotes, e.g. levels: { manual: "engine.view.manual('far')" }`);
124
+ if (typeof spec.levels?.manual !== 'string' || !spec.levels.manual) throw codedError('owned-misuse', `defineOwned(engine, { id: '${spec.id}', levels: { manual } }): levels.manual is required, the copyable takeover call the warning quotes, e.g. levels: { manual: "engine.autoView.manual('far')" }`);
126
125
  const reg = engine._owned ??= new Map();
127
126
  const o = new Owned(engine, spec);
128
127
  const old = reg.get(spec.id); if (old) live.delete(old);
@@ -140,7 +139,7 @@ function ownedOf(engine, part, keys) {
140
139
  }
141
140
 
142
141
  /**
143
- * manual(keys?, on?) of a group (engine.view.manual): the game takes these properties (the engine stops writing them) or hands them back (on false).
142
+ * manual(keys?, on?) of a group (engine.autoView.manual): the game takes these properties (the engine stops writing them) or hands them back (on false).
144
143
  * Throws with the part's takeable keys when nothing matches, so a typo does not silently do nothing.
145
144
  * @returns {{ remove(): void }} remove() hands them back
146
145
  */
@@ -167,5 +166,3 @@ export function describeOwned(engine) {
167
166
  * @param {any} engine @param {string} id @param {() => (object | undefined)} row
168
167
  */
169
168
  export function ownedRow(engine, id, row) { (engine._ownedRows ??= {})[id] = row; }
170
- /** Remove an ownedRow (its module disposed) @param {any} engine @param {string} id */
171
- export function dropOwnedRow(engine, id) { if (engine._ownedRows) delete engine._ownedRows[id]; }
@@ -1,4 +1,4 @@
1
- // Shared points: the ONE way several owners change a shared thing (time channels, the calendar rate, pause / freeze / camera holders, move speed,
1
+ // Shared points: the ONE way several owners change a shared thing (time channels, the calendar rate, halt / freeze / camera holders, move speed,
2
2
  // input gates, shadows.enabled, sky.tint, post values, a game's own). One entry, one line:
3
3
  // const h = engine.mod('time.enemies', { owner: 'bullet-time', mul: 0.35, for: 2 }); // bullet time; h.remove() ends it early
4
4
  // ctx.mod('time.world', { mul: 0.8, layer: 'effect' }); // inside a module: owned by it, removed with it
@@ -17,12 +17,12 @@
17
17
  // - the settings layer only restricts: clamp { max } or mul 0..1 on a number, set false on a value point; it can never raise a number or
18
18
  // switch something on (one exception a point opts into with settingsSet: key bindings, where the player's rebinding is a replacement).
19
19
  // It sits above system: a cutscene or menu cannot turn back on what the player turned off; only debug overrides the player
20
- // - kinds: 'number' (default) | 'value' (any data: a color, a string, a boolean; set only) | 'any' (true while anyone holds it: pause, gates)
20
+ // - kinds: 'number' (default) | 'value' (any data: a color, a string, a boolean; set only) | 'any' (true while anyone holds it: freeze, gates)
21
21
  // | 'top' (the latest holder is in charge: the camera) | 'one' (an exclusive slot: a second holder is shared-taken; module `provides`)
22
22
  // Plain JS stays first-class: a game's own fields and onFixed logic never need this; it is for things several owners write.
23
- // The registry (engine.stacks: define / get / mod, save, timers, describe().shared) is core/stacks.js.
24
- import { codedError, coded } from './errorHints.js';
25
- import { DEV, warnOnce, note } from './validate.js';
23
+ // The registry (engine.stacks: define / get / mod, save, timers, describe().shared) is core/ops/stacks.js.
24
+ import { codedError, coded } from '../base/errorHints.js';
25
+ import { DEV, warnOnce, note } from '../base/validate.js';
26
26
  import { callerAt } from './stackFrames.js';
27
27
 
28
28
  /** The one layer table, lowest first. Who uses which: engine = the engine's own defaults and drivers, game = game code and
@@ -53,7 +53,7 @@ function numCheck(op, v, call) {
53
53
  }
54
54
 
55
55
  /**
56
- * pause('x') and pause({ owner: 'x' }) both work everywhere an owner is named
56
+ * freeze('x') and freeze({ owner: 'x' }) both work everywhere an owner is named
57
57
  * @param {string | { owner?: string } | undefined} a @param {any} [b] @returns {{ owner: string, opts: any }}
58
58
  */
59
59
  export function ownerArgs(a, b, fallback = 'game') {
@@ -184,7 +184,7 @@ export class Stack {
184
184
  }
185
185
  /** @internal */
186
186
  _changed(id) { this._ver++; this.all._version++; this.onChange?.(id ?? null); }
187
- /** @internal End owner's entry by name (engine holds: the pause handle); games end theirs with the handle's remove(). false when it held none @param {string} owner @param {{ id?: string }} [o] */
187
+ /** @internal End owner's entry by name (engine holds: the halt handle); games end theirs with the handle's remove(). false when it held none @param {string} owner @param {{ id?: string }} [o] */
188
188
  release(owner, { id } = {}) { return this._drop(owner, id); }
189
189
  /** Drop every entry for record id (world.remove does it, so no orphan entries) @param {string} id */
190
190
  dropId(id) { this._memo.delete(id); const m = this._by.get(id); if (!m) return; this._by.delete(id); this._changed(id); }
@@ -242,7 +242,7 @@ export class Stack {
242
242
  }
243
243
  return v;
244
244
  }
245
- /** Each holder's value in take order: [{ owner, value }] (the data an 'any' holder gave, e.g. a pause's kind) @param {string} [id] */
245
+ /** Each holder's value in take order: [{ owner, value }] (the data an 'any' holder gave, e.g. a freeze's kind) @param {string} [id] */
246
246
  entries(id) { return [...(this._map(id)?.values() ?? [])].map(e => ({ owner: e.owner, value: e.value })); }
247
247
  /** The latest holder's entry ({ owner, value }) or null: the camera in charge, the slot's holder @param {string} [id] */
248
248
  top(id) { let t = null; const m = this._map(id); if (m) for (const e of m.values()) t = e; return t; }
@@ -2,7 +2,7 @@
2
2
  // a shared point (sharedPoint.js: the conflict error names both sides' lines).
3
3
  // Why one file: the two copies of the frame regex drifted apart once already (a query string after the file name, a Windows path), and a fix made in
4
4
  // one never reached the other. Both read V8 and Firefox / Safari frame lines ("at f (http://host/src/main.js?v=1:50:7)" and "f@http://host/src/main.js:50:7").
5
- import { DEV } from './validate.js';
5
+ import { DEV } from '../base/validate.js';
6
6
  const FRAME = /\(?((?:[a-z]+:\/\/[^/\s]+)?[^\s()]+?\.[cm]?[jt]sx?)(?:\?[^:\s)]*)?:(\d+):\d+\)?\s*$/i;
7
7
  const FUNC = /^[^@\s/]*@(?=[a-z]+:\/\/)/i;
8
8
  const NAME = /^\s*(?:at\s+(?:async\s+)?([^\s(]+(?: \[as [^\]]+\])?)\s+\(|([^@\s/]+)@)/; // V8 "at name (file" / Firefox "name@file"; none for an anonymous function
@@ -26,7 +26,7 @@ const ENGINE_FRAME = /(?:engine|threedog)\/(?:core|modules|render|ui)\//; // e
26
26
  const ENGINE_PARTS = /^(?:core|modules|render|ui)\//;
27
27
  // the engine's own folder as this page's server names it. Why not only the path pattern above: a page served from the engine's folder (its tests) has
28
28
  // /core/x.js with no 'engine' in it, and a game's own core/ folder must not pass for the engine's. String work, not new URL('..', import.meta.url): a bundler reads that form as an asset
29
- const engineDir = () => import.meta.url.replace(/\?.*$/, '').replace(/[^/]*\/[^/]*$/, '');
29
+ const engineDir = () => import.meta.url.replace(/\?.*$/, '').replace(/(?:[^/]*\/){2}[^/]*$/, '');
30
30
 
31
31
  /** Is this frame file the engine's own code? @param {string} file a frame's file */
32
32
  export function engineFile(file) {
@@ -1,7 +1,7 @@
1
- // engine.stacks: the registry of every shared point (the point itself and its rules are core/sharedPoint.js). Here: define / get / mod, the timers
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 './errorHints.js';
4
- import { DEV, warnOnce } from './validate.js';
3
+ import { codedError } from '../base/errorHints.js';
4
+ import { DEV, warnOnce } from '../base/validate.js';
5
5
  import { Stack } from './sharedPoint.js';
6
6
 
7
7
  const KEYS = ['owner', 'set', 'add', 'mul', 'clamp', 'value', 'for', 'clock', 'id', 'layer'];
@@ -17,20 +17,18 @@ export class Stacks {
17
17
  /** @type {Map<string, Stack>} */ this._all = new Map();
18
18
  /** @internal saved entries of a point the game has not defined yet: applied when it does */ this._pending = {};
19
19
  this._version = 0; this._timedDirty = false;
20
- /** @internal now on a clock ('real' or a channel); core/time.js replaces it */ this._nowOf = () => 0;
21
- // since = game clock time of the take (engine.clock.now), not engine.time.now('real'): session.newGame resets the clock, so an entry a fresh
20
+ /** @internal now on a clock ('real' or a channel); core/time/time.js replaces it */ this._nowOf = () => 0;
21
+ // since = game clock time of the take (calendar seconds), not engine.time.now('real'): session.newGame resets the clock, so an entry a fresh
22
22
  // playthrough makes reads the same in every new game
23
- this._at = () => engine.clock?.now ?? 0;
24
- this._hooked = false; this._hook();
23
+ this._at = () => this._nowOf('calendar');
25
24
  }
26
25
  /** @internal saves and world:remove. The registry is made before them (Engine.js: the drawing parts' points exist from the first drawing part on);
27
- * createServices calls this again once saves and events exist */
26
+ * createServices calls this once saves and events exist */
28
27
  _hook() {
29
28
  const e = this.engine;
30
- if (this._hooked || !e.saves || !e.events) return;
31
- this._hooked = true;
32
29
  e.saves.register('stacks', { save: () => this._save(), load: d => this._load(d) });
33
- e.events.on('world:remove', ({ id }) => { for (const s of this._all.values()) if (s.per) s.dropId(id); });
30
+ // 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
+ e.events.on('world:remove', ({ id }) => { for (const s of this._all.values()) if (s.per && !s.name.startsWith('input.')) s.dropId(id); });
34
32
  }
35
33
  /**
36
34
  * Define a shared point (engine modules and games use the same call). kind: 'number' (default; base 1), 'value' (any data, set only), 'any'
@@ -43,7 +41,7 @@ export class Stacks {
43
41
  * @example engine.stacks.define('damageTaken', { per: true, min: 0 }); engine.mod('damageTaken', { owner: 'shield', id: 'player', mul: 0.5, for: 3 });
44
42
  */
45
43
  define(name, o = {}) {
46
- if (this._all.has(name)) throw codedError('mod-owner', `engine.stacks.define('${name}'): already defined; read it with engine.stacks.get('${name}')`);
44
+ if (this._all.has(name)) throw codedError('engine-misuse', `engine.stacks.define('${name}'): already defined; read it with engine.stacks.get('${name}')`);
47
45
  const s = new Stack(this, name, o);
48
46
  this._all.set(name, s);
49
47
  if (this._pending[name]) { this._loadOne(s, this._pending[name]); delete this._pending[name]; }
@@ -104,7 +102,7 @@ export class Stacks {
104
102
  return out;
105
103
  }
106
104
  /**
107
- * @internal End every entry whose time is up (core/time.js calls it after advancing the clocks), earliest first; emits mod:end for each.
105
+ * @internal End every entry whose time is up (core/time/time.js calls it after advancing the clocks), earliest first; emits mod:end for each.
108
106
  * @returns {number} how many ended
109
107
  */
110
108
  _expire() {
@@ -119,7 +117,7 @@ export class Stacks {
119
117
  }
120
118
  return due.length;
121
119
  }
122
- /** @internal smallest time left on any timed entry, converted to game seconds by toGame(clock, left) (engine.skip ends a segment there) */
120
+ /** @internal smallest time left on any timed entry, converted to calendar seconds by toGame(clock, left) (engine.skip ends a segment there) */
123
121
  _untilNext(toGame) {
124
122
  let best = Infinity;
125
123
  for (const [, e] of this._timed()) best = Math.min(best, toGame(e.clock, Math.max(0, e.until - this._nowOf(e.clock))));
@@ -10,14 +10,15 @@
10
10
  // The wrapper is installed on the object itself, so every caller of that method goes through it: the game, the module's ops (the op
11
11
  // inventory.transfer calls engine.inventory.transfer) and other modules alike. It wraps one method, not a behaviour: a rule that must hold for
12
12
  // every way items enter the bag wraps each api method that can do it (add and transfer), or uses the module's own option (maxWeight).
13
- // Only public methods: a name starting with '_' is the module's inside and throws (wrap what the contract lists, modules/<m>/contract.js).
14
- import { fmt } from './validate.js';
15
- import { codedError } from './errorHints.js';
13
+ // Wrap what the contract lists (modules/<m>/contract.js). A name starting with '_' is the module's inside: it works, and dev warns once that it may change.
14
+ import { DEV, fmt, warnOnce } from '../base/validate.js';
15
+ import { coded, codedError } from '../base/errorHints.js';
16
16
 
17
17
  const STRINGS = {
18
- target: "engine.wrap(target, method, fn): target must be a module's api object (engine.inventory, engine.flow...), got {got}",
18
+ target: 'engine.wrap(target, method, fn): target is an object with the method, such as engine.inventory or engine.flow; got {got}',
19
19
  fn: "engine.wrap(target, '{method}', fn): fn must be a function (next, ...args) => ..., e.g. (next, ...a) => next(...a)",
20
- priv: "engine.wrap(target, '{method}'): '{method}' is private (leading _); wrap a public method: {list}",
20
+ name: "engine.wrap(target, method, fn): method is a method name, got {method}; public methods: {list}",
21
+ priv: "engine.wrap({name}, '{method}'): '{method}' is the object's inside (leading _), so an engine update may change it without notice. Public methods: {list}",
21
22
  missing: "engine.wrap({name}, '{method}'): {name} has no method '{method}'; public methods: {list}",
22
23
  };
23
24
 
@@ -55,7 +56,8 @@ export class Wraps {
55
56
  if (!target || (typeof target !== 'object' && typeof target !== 'function')) throw codedError('wrap-misuse', fmt(STRINGS.target, { got: target === null ? 'null' : typeof target }), TypeError);
56
57
  if (typeof fn !== 'function') throw codedError('wrap-misuse', fmt(STRINGS.fn, { method }), TypeError);
57
58
  const name = this._name(target);
58
- if (typeof method !== 'string' || method.startsWith('_')) throw codedError('wrap-misuse', fmt(STRINGS.priv, { method: String(method), list: methodsOf(target).join(', ') }));
59
+ if (typeof method !== 'string') throw codedError('wrap-misuse', fmt(STRINGS.name, { method: String(method), list: methodsOf(target).join(', ') }));
60
+ if (DEV && method.startsWith('_')) warnOnce(coded('wrap-misuse', fmt(STRINGS.priv, { name, method, list: methodsOf(target).join(', ') })));
59
61
  let slots = this._map.get(target);
60
62
  if (!slots) this._map.set(target, slots = new Map());
61
63
  let slot = slots.get(method);
@@ -1,4 +1,4 @@
1
- import { codedError } from './errorHints.js';
1
+ import { codedError } from '../base/errorHints.js';
2
2
  // Save storage layer: uses the browser's native IndexedDB (no third-party library) and falls back to localStorage when it is unavailable. Saves uses it; modules never touch it directly.
3
3
  //
4
4
  // Two stores in the database:
@@ -10,14 +10,14 @@
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
- /** @import { SaveProvider } from '../types/core' */
13
+ /** @import { SaveProvider } from '../../types/core' */
14
14
  import { SaveStore } from './SaveStore.js';
15
- import { checkTypeRule } from './moduleTypes.js';
16
- import { toast } from '../ui/UI.js';
17
- import { warnOnce, fmt } from './validate.js';
18
- import { readParams, keysSchema } from './params.js';
19
- import { reportError } from './errors.js';
20
- import { codedError, coded } from './errorHints.js';
15
+ import { checkTypeRule } from '../engine/moduleTypes.js';
16
+ import { toast } from '../../ui/UI.js';
17
+ import { warnOnce, fmt } from '../base/validate.js';
18
+ import { readParams, keysSchema } from '../base/params.js';
19
+ import { reportError } from '../base/errors.js';
20
+ import { codedError, coded } from '../base/errorHints.js';
21
21
  import { checkPartVersion, readSave } from './saveVersions.js';
22
22
  import { exportSaveFile, importSaveFile, importText, SAVE_STRINGS } from './saveFiles.js';
23
23
  import { applySave, loadSlot, adoptPart, collectParts } from './saveApply.js';
@@ -37,8 +37,8 @@ export class Saves {
37
37
  /** @internal */
38
38
  constructor(engine, { prefix = 'game-' } = {}) {
39
39
  /** @internal */ this.engine = engine;
40
- /** Save name prefix (start of the key names in the localStorage fallback, and of the IndexedDB database name) */
41
- this.prefix = prefix + 'save-';
40
+ /** @internal Start of the key names in the localStorage fallback and of the IndexedDB database name; a module asks storageKey(name) instead */
41
+ this._prefix = prefix + 'save-';
42
42
  /** @internal */ this.providers = new Map();
43
43
  /** @internal */ this._auto = null;
44
44
  /** @internal Slot -> JSON text (all saves stay in memory: list / check / export are synchronous) */ this._json = new Map();
@@ -50,7 +50,7 @@ export class Saves {
50
50
  this._tab = globalThis.crypto?.randomUUID?.() ?? `${Date.now()}-${performance.now()}`; // wall-clock: only a fallback id, unique per tab
51
51
  /** @internal */ this._n = 0;
52
52
  /** @internal other tabs of this game: 'slot changed' notes */
53
- this._bc = typeof BroadcastChannel === 'function' ? new BroadcastChannel(this.prefix + 'db') : null;
53
+ this._bc = typeof BroadcastChannel === 'function' ? new BroadcastChannel(this._prefix + 'db') : null;
54
54
  if (this._bc) this._bc.onmessage = ev => this._remote(ev.data?.slot);
55
55
  /** @internal Parts of the last loaded save that no registered module owns (a module not installed in this build): written back unchanged on every save */
56
56
  this._foreign = { parts: {}, versions: {} };
@@ -59,8 +59,9 @@ export class Saves {
59
59
  * Storage layer: saves in the IndexedDB slots store, attachments (by group, e.g. 'photo') in the blobs store; mode 'localStorage' without IndexedDB.
60
60
  * @type {{ mode: 'idb' | 'localStorage', blobs(group?: string): Promise<{ group: string, id: string, at: number, blob: Blob, meta: any }[]>,
61
61
  * putBlob(group: string, id: string, blob: Blob, meta?: any, at?: number): Promise<void>, deleteBlob(group: string, id: string): Promise<void> }}
62
+ * @experimental
62
63
  */
63
- this.store = /** @type {any} */ (new SaveStore(this.prefix + 'db', this.prefix));
64
+ this.store = /** @type {any} */ (new SaveStore(this._prefix + 'db', this._prefix));
64
65
  /** Has the save index been read into memory? (start() waits for it; game code rarely needs to care) */
65
66
  this.ready = false;
66
67
  /** Resolves once the save index is in memory; await it only to list / load before start() @type {Promise<void>} */
@@ -73,9 +74,6 @@ export class Saves {
73
74
  * shape.
74
75
  * A save whose part is newer than this build's version is refused as a whole (load returns false, the save is kept).
75
76
  * A part registered after a save was loaded (a module installed later) is handed its data from that save at once.
76
- * movedFrom: { oldPart: data => newData } when this part's data used to be saved under another part's name (a module split in two: the calendar's
77
- * time and day were part 'sky'); an old save without this part but with oldPart hands that data, converted, to this part, and oldPart is dropped
78
- * (unless a registered part still owns that name).
79
77
  * 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).
80
78
  * 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
81
79
  * (world: records placed by code instead of content). The part knows its own format; core only hands the data over.
@@ -88,14 +86,11 @@ export class Saves {
88
86
  */
89
87
  register(key, provider) {
90
88
  checkTypeRule(this.engine, 'saves.register', `registered save part '${key}'`);
91
- readParams(`saves.register('${key}')`, keysSchema(['save', 'load', 'first', 'version', 'migrate', 'atomic', 'movedFrom', 'checkNewGame']), provider);
92
- const { save, load, first = false, version = 1, migrate = {}, atomic = false, movedFrom = null, checkNewGame = null } = provider;
93
- checkPartVersion(key, version, migrate, movedFrom);
94
- this.providers.set(key, { save, load, first, version, migrate, atomic: atomic === true, movedFrom, checkNewGame });
89
+ readParams(`saves.register('${key}')`, keysSchema(['save', 'load', 'first', 'version', 'migrate', 'atomic', 'checkNewGame']), provider);
90
+ const { save, load, first = false, version = 1, migrate = {}, atomic = false, checkNewGame = null } = provider;
91
+ checkPartVersion(key, version, migrate);
92
+ this.providers.set(key, { save, load, first, version, migrate, atomic: atomic === true, checkNewGame });
95
93
  this.engine.session._late(key); // a part registered after start() (a module installed later) joins the new-game state as it is now
96
- // registered after a save was loaded: the old part's data is still kept as foreign, move it over now (the same step readSave does on load)
97
- const F = this._foreign, old = movedFrom && !(key in F.parts) && Object.keys(movedFrom).find(o => o in F.parts && !this.providers.has(o));
98
- if (old) { F.parts[key] = movedFrom[old](structuredClone(F.parts[old])); F.versions[key] = version; delete F.parts[old]; delete F.versions[old]; }
99
94
  if (key in this._foreign.parts) adoptPart(this, key);
100
95
  }
101
96
  /**
@@ -110,18 +105,14 @@ export class Saves {
110
105
  const idb = await this.store.open();
111
106
  if (!idb) warnOnce(coded('indexeddb', DEV_STRINGS.noIdb));
112
107
  try {
113
- for (const r of await this.store.slots()) if (!this._json.has(r.slot)) {
114
- this._json.set(r.slot, r.json); this._meta.set(r.slot, r.savedAt); this._rev.set(r.slot, r.rev ?? ''); this._mine.set(r.slot, r.rev ?? '');
108
+ for (const r of await this.store.slots()) {
109
+ 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
+ if (!this._json.has(r.slot)) { this._json.set(r.slot, r.json); this._meta.set(r.slot, r.savedAt); }
115
111
  }
116
112
  } catch (e) { this._fail(e); }
117
113
  }
118
- /**
119
- * Queue a disk write (runs in call order once storage is ready; flush waits for it; used by attachments such as photos).
120
- * @template T
121
- * @param {() => Promise<T>} fn
122
- * @returns {Promise<T>}
123
- */
124
- queue(fn) {
114
+ /** @internal Disk writes run in call order once storage is ready, and flush waits for them: the one place that order is kept */
115
+ _enqueue(fn) {
125
116
  const p = this._queue.then(() => this.whenReady).then(fn);
126
117
  this._queue = p.catch(() => {});
127
118
  return p;
@@ -133,6 +124,36 @@ export class Saves {
133
124
  else warnOnce(coded('save-write', `[saves] failed to write ${slot ? `slot "${slot}"` : 'save'}: ${err?.message ?? err}`));
134
125
  toast(this.engine, why, { kind: 'error', ms: 5000 });
135
126
  }
127
+ /**
128
+ * 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
+ * Pass a function to make the bytes when the write runs: flush() then waits for that too. Without IndexedDB it is not kept.
130
+ * @example await engine.saves.putAttachment('replay', 'run-1', blob, { score: 12 });
131
+ * @param {string} group what the attachment is for
132
+ * @param {string} id unique inside the group; the same id replaces
133
+ * @param {Blob | (() => Promise<Blob>)} blob
134
+ * @param {any} [meta] plain data kept with it
135
+ * @returns {Promise<void>}
136
+ * @experimental
137
+ */
138
+ putAttachment(group, id, blob, meta) {
139
+ return this._enqueue(async () => this.store.putBlob(group, id, typeof blob === 'function' ? await blob() : blob, meta));
140
+ }
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)); }
143
+ /**
144
+ * The attachments of a group, once storage is ready. Empty without IndexedDB.
145
+ * @param {string} group
146
+ * @returns {Promise<{ group: string, id: string, at: number, blob: Blob, meta: any }[]>}
147
+ * @experimental
148
+ */
149
+ async attachments(group) { await this.whenReady; return this.store.blobs(group); }
150
+ /**
151
+ * 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
+ * @example localStorage.setItem(engine.saves.storageKey('lastTab'), 'map');
153
+ * @param {string} name
154
+ * @returns {string}
155
+ */
156
+ storageKey(name) { return this._prefix.replace(/save-$/, '') + name; }
136
157
  /** Wait for all queued disk writes to finish (for tests and before the page closes) @returns {Promise<void>} */
137
158
  flush() { return this._queue; }
138
159
 
@@ -177,7 +198,7 @@ export class Saves {
177
198
  const prev = this._json.get(slot), prevAt = this._meta.get(slot), rev = `${this._tab}:${++this._n}`;
178
199
  this._json.set(slot, json); this._meta.set(slot, savedAt);
179
200
  // expect is read when the write runs, not now: an earlier queued save of this tab moves _mine first
180
- return this.queue(() => this.store.putSlot(slot, savedAt, json, rev, this._mine.get(slot) ?? null)).then(() => {
201
+ return this._enqueue(() => this.store.putSlot(slot, savedAt, json, rev, this._mine.get(slot) ?? null)).then(() => {
181
202
  this._rev.set(slot, rev); this._mine.set(slot, rev);
182
203
  this._tell(slot);
183
204
  return true;
@@ -196,15 +217,15 @@ export class Saves {
196
217
  this._fail(e, slot); return false;
197
218
  });
198
219
  }
199
- /** @internal Memory shows a stored record (null = none); the rev this tab may overwrite stays as it was */
220
+ /** @internal Memory shows a stored record (null = none); a stored record leaves the rev this tab may overwrite as it was */
200
221
  _show(slot, r) {
201
- if (!r) { this._json.delete(slot); this._meta.delete(slot); this._rev.delete(slot); return; }
222
+ 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
202
223
  this._json.set(slot, r.json); this._meta.set(slot, r.savedAt); this._rev.set(slot, r.rev ?? '');
203
224
  }
204
225
  /** @internal Another tab changed a slot: read it again (after this tab's queued writes, so a late note cannot undo a newer own write) */
205
226
  _remote(slot) {
206
227
  if (typeof slot !== 'string' || !this._bc) return;
207
- this.queue(() => this.store.getSlot(slot)).then(r => this._show(slot, r), () => {});
228
+ this._enqueue(() => this.store.getSlot(slot)).then(r => this._show(slot, r), () => {});
208
229
  }
209
230
  /** @internal Tell the other tabs a slot changed (they read it again from storage: the note carries no save text, which can be MBs) */
210
231
  _tell(slot) { this._bc?.postMessage({ slot }); } // BroadcastChannel, not a worker
@@ -255,10 +276,10 @@ export class Saves {
255
276
  this._json.delete(slot); this._meta.delete(slot);
256
277
  // the revs are cleared when the delete runs, not now: a save queued before this remove sets _mine when its write lands,
257
278
  // and a _mine left over for a deleted record would refuse every later save of this slot as "another tab saved"
258
- return this.queue(async () => { await this.store.deleteSlot(slot); this._rev.delete(slot); this._mine.delete(slot); })
279
+ return this._enqueue(async () => { await this.store.deleteSlot(slot); this._rev.delete(slot); this._mine.delete(slot); })
259
280
  .then(() => this._tell(slot), e => this._fail(e, slot));
260
281
  }
261
- /** Export as a piece of text (can be copied as a backup; synchronous, without binary attachments) @param {string} [slot] @returns {string} */
282
+ /** Export as a piece of text (can be copied as a backup; synchronous, without binary attachments) @param {string} [slot] @returns {string} @experimental */
262
283
  export(slot = 'auto') { try { return btoa(unescape(encodeURIComponent(this._json.get(slot) || ''))); } catch { return ''; } }
263
284
  /**
264
285
  * Import text from export() into a slot (default 'imported'); checked like importFile and written before it resolves.
@@ -277,6 +298,7 @@ export class Saves {
277
298
  * @param {{ files?: boolean }} [opts]
278
299
  * @returns {Promise<boolean>}
279
300
  * @example engine.saves.exportFile('slot1');
301
+ * @experimental
280
302
  */
281
303
  exportFile(slot = 'auto', opts = {}) { return exportSaveFile(this, slot, opts); }
282
304
  /**
@@ -10,12 +10,13 @@
10
10
  // overlapping loads were never sound anyway (the second one's rollback point is the first one's half-applied state). An unrelated listener that
11
11
  // throws while a load is still settling fails that load too; gameplay is frozen while parts load, so that is rare, and the error is reported.
12
12
  // The rollback point is a copy (structuredClone of every part's save()): save() may return the live object, which load() then writes into.
13
- import { toast } from '../ui/UI.js';
14
- import { fmt, warnOnce } from './validate.js';
15
- import { reportError } from './errors.js';
16
- import { codedError, coded } from './errorHints.js';
13
+ import { toast } from '../../ui/UI.js';
14
+ import { fmt, warnOnce } from '../base/validate.js';
15
+ import { reportError } from '../base/errors.js';
16
+ import { codedError, coded } from '../base/errorHints.js';
17
17
  import { FORMAT, readSave, parseSave, upgradePart } from './saveVersions.js';
18
- import { PARTS_LOADING } from './opsFail.js';
18
+ import { PARTS_LOADING } from '../ops/opsFail.js';
19
+ import { isObject } from '../base/util.js';
19
20
 
20
21
  const DEV_STRINGS = {
21
22
  loadThrew: "load() of save part '{k}' threw ({msg}); the game was rolled back to how it was before loading '{slot}'",
@@ -59,7 +60,7 @@ function applyParts(s, e, r, slot, before, foreign0, scope) {
59
60
  e.commits.invalidate(); e.ops._mark('(load)'); // old background results die with the old world; the op log shows where the load cut in
60
61
  s._foreign = r.foreign;
61
62
  const fail = err => {
62
- // a malformed save (world/persist.js save-bad-record) is the save's fault, not the game's: refused like a corrupt save (warning + toast), so it
63
+ // a malformed save (refuseSave, save-bad-record) is the save's fault, not the game's: refused like a corrupt save (warning + toast), so it
63
64
  // does not freeze gameplay as a code error would; a load() / listener / afterLoad that throws is a bug and goes through the error tiers
64
65
  if (err?.cause?.code === 'save-bad-record') { warnOnce(err.message); toast(e, e.t('saves.corrupt'), { kind: 'error', ms: 5000 }); }
65
66
  else reportError(e, err, err?.part ? fmt(DEV_STRINGS.partAt, { k: err.part }) : `saves.apply('${slot}')`);
@@ -67,12 +68,15 @@ function applyParts(s, e, r, slot, before, foreign0, scope) {
67
68
  const back = readSave(before, s.providers, '(rollback)');
68
69
  // every part reloads its pre-load state; a part that throws again is reported (once) and the rest still roll back
69
70
  const onPart = er => reportError(e, er, fmt(DEV_STRINGS.rollback, { k: er.part }), { soft: true });
70
- return Promise.resolve('list' in back ? e.ops.allow(() => runParts(e, back.list, '(rollback)', scope, onPart)) : null).then(() => false);
71
+ const undone = 'list' in back ? e.ops.allow(() => runParts(e, back.list, '(rollback)', scope, onPart)) : true;
72
+ // a rollback that waits on an async part holds gameplay too, whichever way the load failed (the load's own hold may be gone or never taken)
73
+ const fz = undone !== true ? e.freeze(PARTS_LOADING) : null;
74
+ return Promise.resolve(undone).then(() => false).finally(() => fz?.remove());
71
75
  };
72
76
  let out;
73
77
  try { out = e.ops.allow(() => runParts(e, r.list, slot, scope)); } catch (err) { return fail(err); } // loading writes state outside ops on purpose (guard allows it)
74
78
  // a part still loading (its load() returned a Promise): gameplay waits until every part is applied -- no fixed step, no op (opsFail.js
75
- // PARTS_LOADING). Held through a rollback too, since that may wait on async parts as well. A fully sync load never takes it.
79
+ // PARTS_LOADING). A fully sync load never takes it.
76
80
  const fz = out !== true ? e.freeze(PARTS_LOADING) : null;
77
81
  const partsDone = () => { fz?.remove(); };
78
82
  // a load is a state change: ops.revision moves. afterLoad belongs to the load (Saves.apply doc): a hook that throws fails it like a part's load()
@@ -160,7 +164,7 @@ export function loadSlot(s, slot, base) {
160
164
  if (base && data != null) {
161
165
  try {
162
166
  const sv = parseSave(data);
163
- if (sv?.parts && typeof sv.parts === 'object' && !Array.isArray(sv.parts)) {
167
+ if (isObject(sv?.parts)) {
164
168
  const own = Object.fromEntries(Object.keys(sv.parts).map(k => [k, sv.versions?.[k] ?? 1])); // a part without a version is version 1, not base's
165
169
  data = { ...sv, parts: { ...base.parts, ...sv.parts }, versions: { ...base.versions, ...own } };
166
170
  }
@@ -1,9 +1,9 @@
1
1
  // Save files (.json download / restore), split out of Saves.js: the world save plus every binary attachment, for backups that survive wiped browser data.
2
2
  // File shape: { threedog: 'save', format: FILE_FORMAT, game, slot, savedAt, data: <the save envelope>, files: [{ group, id, at, meta, type, url: 'data:...' }] }.
3
3
  // Import is offline: attachments must be data: URLs and are decoded in place, never fetched.
4
- import { toast } from '../ui/UI.js';
5
- import { coded } from './errorHints.js';
6
- import { fmt, warnOnce } from './validate.js';
4
+ import { toast } from '../../ui/UI.js';
5
+ import { coded } from '../base/errorHints.js';
6
+ import { fmt, warnOnce } from '../base/validate.js';
7
7
  import { readSave, parseSave } from './saveVersions.js';
8
8
 
9
9
  /** Version of the export file wrapper (the save inside carries its own format) */
@@ -31,12 +31,14 @@ const STRINGS = {
31
31
  /** Blob -> data: URL (attachments are stored as text in the export file) */
32
32
  const toDataURL = blob => new Promise((res, rej) => { const r = new FileReader(); r.onload = () => res(r.result); r.onerror = () => rej(r.error); r.readAsDataURL(blob); });
33
33
 
34
- /** data: URL -> Blob without the network; null when it is not a data: URL */
34
+ /** data: URL -> Blob without the network; null when it is not a readable data: URL */
35
35
  function dataUrlBlob(url, type) {
36
36
  const m = typeof url === 'string' && /^data:([^,]*?)(;base64)?,(.*)$/s.exec(url);
37
37
  if (!m) return null;
38
- const bytes = m[2] ? Uint8Array.from(atob(m[3]), c => c.charCodeAt(0)) : new TextEncoder().encode(decodeURIComponent(m[3]));
39
- return new Blob([bytes], { type: typeof type === 'string' ? type : m[1].split(';')[0] });
38
+ try {
39
+ const bytes = m[2] ? Uint8Array.from(atob(m[3]), c => c.charCodeAt(0)) : new TextEncoder().encode(decodeURIComponent(m[3]));
40
+ return new Blob([bytes], { type: typeof type === 'string' ? type : m[1].split(';')[0] });
41
+ } catch { return null; } // a hand-edited file: bad base64 or a bad % escape
40
42
  }
41
43
 
42
44
  /**
@@ -54,10 +56,10 @@ export async function exportSaveFile(s, slot, { files = true } = {}) {
54
56
  const list = [];
55
57
  if (files) for (const b of await s.store.blobs()) list.push({ group: b.group, id: b.id, at: b.at, meta: b.meta, type: b.blob.type, url: await toDataURL(b.blob) });
56
58
  // splice the world save's JSON text in directly instead of parsing it again (halves memory at tens of MB)
57
- const head = `{"threedog":"save","format":${FILE_FORMAT},"game":${JSON.stringify(s.prefix)},"slot":${JSON.stringify(slot)},"savedAt":${s._meta.get(slot)},"data":`;
59
+ const head = `{"threedog":"save","format":${FILE_FORMAT},"game":${JSON.stringify(s._prefix)},"slot":${JSON.stringify(slot)},"savedAt":${JSON.stringify(s._meta.get(slot) ?? 0)},"data":`;
58
60
  const blob = new Blob([head, json, ',"files":', JSON.stringify(list), '}'], { type: 'application/json' });
59
61
  const a = document.createElement('a'), url = URL.createObjectURL(blob);
60
- a.href = url; a.download = `${s.prefix.replace(/-save-$/, '')}-${slot}-${new Date().toISOString().slice(0, 10)}.json`;
62
+ a.href = url; a.download = `${s._prefix.replace(/-save-$/, '')}-${slot}-${new Date().toISOString().slice(0, 10)}.json`;
61
63
  document.body.appendChild(a); a.click(); a.remove();
62
64
  setTimeout(() => URL.revokeObjectURL(url), 10000); // presentation: release only after the browser has started the download
63
65
  return true;
@@ -75,22 +77,22 @@ export async function importSaveFile(s, file, slot = 'imported') {
75
77
  file ??= await pick();
76
78
  if (!file) return null;
77
79
  const refuse = why => { warnOnce(coded('save-import', why)); toast(s.engine, s.engine.t('saves.badFile'), { kind: 'save' }); return null; }; // handled: the player is told, nothing changed
78
- if (file.size > MAX_BYTES) return refuse(STRINGS.bad.replace('{why}', `${Math.round(file.size / 1e6)} MB`));
80
+ if (file.size > MAX_BYTES) return refuse(fmt(STRINGS.bad, { why: `${Math.round(file.size / 1e6)} MB` }));
79
81
  let obj;
80
- try { obj = JSON.parse(await file.text()); } catch (e) { return refuse(STRINGS.bad.replace('{why}', e.message)); }
81
- if (obj?.threedog !== 'save') return refuse(STRINGS.bad.replace('{why}', 'no "threedog": "save" marker'));
82
- if ((obj.format ?? 1) > FILE_FORMAT) return refuse(STRINGS.bad.replace('{why}', `file format ${obj.format}, this build reads up to ${FILE_FORMAT}`));
82
+ try { obj = JSON.parse(await file.text()); } catch (e) { return refuse(fmt(STRINGS.bad, { why: e.message })); }
83
+ if (obj?.threedog !== 'save') return refuse(fmt(STRINGS.bad, { why: 'no "threedog": "save" marker' }));
84
+ if ((obj.format ?? 1) > FILE_FORMAT) return refuse(fmt(STRINGS.bad, { why: `file format ${obj.format}, this build reads up to ${FILE_FORMAT}` }));
83
85
  const blobs = [];
84
86
  for (const [i, p] of (Array.isArray(obj.files) ? obj.files : []).entries()) {
85
87
  const blob = typeof p?.group === 'string' && typeof p.id === 'string' ? dataUrlBlob(p.url, p.type) : null;
86
- if (!blob) return refuse(STRINGS.attachment.replace('{i}', String(i)));
88
+ if (!blob) return refuse(fmt(STRINGS.attachment, { i: String(i) }));
87
89
  blobs.push([p, blob]);
88
90
  }
89
91
  const r = await importData(s, obj.data, slot);
90
- if (r !== true) return r === 'write' ? null : refuse(STRINGS.bad.replace('{why}', r)); // a failed write already showed its toast
92
+ if (r !== true) return r === 'write' ? null : refuse(fmt(STRINGS.bad, { why: r })); // a failed write already showed its toast
91
93
  let ok = true;
92
94
  for (const [p, blob] of blobs) {
93
- try { await s.queue(() => s.store.putBlob(p.group, p.id, blob, p.meta, p.at)); } catch (e) { ok = false; s._fail(e); }
95
+ try { await s._enqueue(() => s.store.putBlob(p.group, p.id, blob, p.meta, p.at)); } catch (e) { ok = false; s._fail(e); }
94
96
  }
95
97
  if (!ok) return null;
96
98
  s.engine.events.emit('save:imported', slot);