threedog 0.7.0 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +411 -1
- package/README.md +8 -11
- package/core/{Animator.js → assets/Animator.js} +30 -18
- package/core/{Assets.js → assets/Assets.js} +131 -56
- package/core/{Baked.js → assets/Baked.js} +4 -4
- package/core/assets/assetEntry.js +302 -0
- package/core/{assetHot.js → assets/assetHot.js} +9 -7
- package/core/{assetLoad.js → assets/assetLoad.js} +55 -16
- package/core/assets/assetLod.js +113 -0
- package/core/{assetManifest.js → assets/assetManifest.js} +19 -11
- package/core/{assetReport.js → assets/assetReport.js} +7 -14
- package/core/{namedModel.js → assets/namedModel.js} +17 -13
- package/core/{Audio.js → audio/Audio.js} +47 -25
- package/core/{audioRules.js → audio/audioRules.js} +8 -5
- package/core/{audioVoice.js → audio/audioVoice.js} +17 -30
- package/core/{Events.js → base/Events.js} +3 -3
- package/core/{I18n.js → base/I18n.js} +15 -12
- package/core/{Random.js → base/Random.js} +7 -4
- package/core/{Vars.js → base/Vars.js} +14 -4
- package/core/{easing.js → base/easing.js} +1 -1
- package/core/{errorCodes.js → base/errorCodes.js} +151 -125
- package/core/{errorHints.js → base/errorHints.js} +17 -10
- package/core/{errors.js → base/errors.js} +12 -10
- package/core/{events.generated.js → base/events.generated.js} +11 -0
- package/core/base/follows.js +26 -0
- package/core/base/math.js +66 -0
- package/core/{params.js → base/params.js} +5 -6
- package/core/base/saveValues.js +81 -0
- package/core/base/sections.js +97 -0
- package/core/base/spelling.js +32 -0
- package/core/base/util.js +32 -0
- package/core/{validate.js → base/validate.js} +34 -34
- package/core/{Engine.js → engine/Engine.js} +137 -91
- package/core/{Loading.js → engine/Loading.js} +34 -5
- package/core/{copies.js → engine/copies.js} +4 -4
- package/core/{headlessLoad.js → engine/headlessLoad.js} +32 -15
- package/core/{lifecycle.js → engine/lifecycle.js} +41 -34
- package/core/{loop.js → engine/loop.js} +88 -49
- package/core/engine/moduleSlots.js +176 -0
- package/core/{moduleTypes.js → engine/moduleTypes.js} +26 -14
- package/core/engine/modules.js +503 -0
- package/core/{page.js → engine/page.js} +59 -29
- package/core/{plugins.js → engine/plugins.js} +21 -12
- package/core/{services.js → engine/services.js} +50 -40
- package/core/{startup.js → engine/startup.js} +66 -54
- package/core/{Input.js → input/Input.js} +67 -39
- package/core/{inputContext.js → input/inputContext.js} +14 -5
- package/core/input/inputKeyboard.js +39 -0
- package/core/{inputPad.js → input/inputPad.js} +24 -3
- package/core/{inputPointer.js → input/inputPointer.js} +11 -3
- package/core/input/inputSeat.js +66 -0
- package/core/{inputTouch.js → input/inputTouch.js} +24 -7
- package/core/{Budget.js → inspect/Budget.js} +21 -20
- package/core/{DebugOverrides.js → inspect/DebugOverrides.js} +43 -18
- package/core/{Describe.js → inspect/Describe.js} +34 -26
- package/core/{Inspect.js → inspect/Inspect.js} +39 -10
- package/core/{InspectMaterials.js → inspect/InspectMaterials.js} +7 -8
- package/core/{InspectPerf.js → inspect/InspectPerf.js} +19 -13
- package/core/{InspectScene.js → inspect/InspectScene.js} +8 -5
- package/core/{MaterialInfo.js → inspect/MaterialInfo.js} +3 -2
- package/core/{UrlState.js → inspect/UrlState.js} +60 -24
- package/core/{catalog.js → inspect/catalog.js} +15 -8
- package/core/{checks.js → inspect/checks.js} +7 -5
- package/core/{debugView.js → inspect/debugView.js} +4 -4
- package/core/{describeRender.js → inspect/describeRender.js} +24 -22
- package/core/{describeText.js → inspect/describeText.js} +17 -8
- package/core/inspect/geometryWatch.js +38 -0
- package/core/{lightWatch.js → inspect/lightWatch.js} +8 -8
- package/core/inspect/metadata.generated.js +4140 -0
- package/core/{pictureWriters.js → inspect/pictureWriters.js} +130 -47
- package/core/{shaderCost.js → inspect/shaderCost.js} +1 -1
- package/core/inspect/toolDoor.js +21 -0
- package/core/inspect/valueHistory.js +35 -0
- package/core/{Ops.js → ops/Ops.js} +44 -14
- package/core/{control.js → ops/control.js} +57 -31
- package/core/ops/holds.js +140 -0
- package/core/{opsAtomic.js → ops/opsAtomic.js} +18 -5
- package/core/{opsCheck.js → ops/opsCheck.js} +11 -10
- package/core/{opsFail.js → ops/opsFail.js} +5 -7
- package/core/{opsGuard.js → ops/opsGuard.js} +3 -3
- package/core/{opsRun.js → ops/opsRun.js} +9 -6
- package/core/{owned.js → ops/owned.js} +33 -19
- package/core/{sharedPoint.js → ops/sharedPoint.js} +13 -16
- package/core/{stackFrames.js → ops/stackFrames.js} +2 -2
- package/core/{stacks.js → ops/stacks.js} +34 -15
- package/core/{wrap.js → ops/wrap.js} +8 -6
- package/core/{SaveStore.js → saves/SaveStore.js} +53 -27
- package/core/{Saves.js → saves/Saves.js} +171 -54
- package/core/saves/saveApply.js +312 -0
- package/core/{saveFiles.js → saves/saveFiles.js} +45 -38
- package/core/{saveVersions.js → saves/saveVersions.js} +24 -23
- package/core/saves/session.js +231 -0
- package/core/saves/stateReplace.js +184 -0
- package/core/{Rays.js → scene/Rays.js} +44 -30
- package/core/{Views.js → scene/Views.js} +16 -8
- package/core/{adaptive.js → scene/adaptive.js} +19 -9
- package/core/{canvasBox.js → scene/canvasBox.js} +4 -3
- package/core/scene/compositeGround.js +72 -0
- package/core/scene/floor.js +17 -0
- package/core/{gameLights.js → scene/gameLights.js} +17 -7
- package/core/{grayMap.js → scene/grayMap.js} +8 -2
- package/core/{grid.js → scene/grid.js} +6 -4
- package/core/{gridLoad.js → scene/gridLoad.js} +1 -1
- package/core/scene/ground.contract.js +14 -0
- package/core/scene/ground.js +139 -0
- package/core/{movement.js → scene/movement.js} +3 -3
- package/core/{pictureSlots.js → scene/pictureSlots.js} +2 -2
- package/core/scene/pixel.js +154 -0
- package/core/scene/pixelRatio.js +167 -0
- package/core/{sceneDelta.js → scene/sceneDelta.js} +5 -5
- package/core/{sceneMethods.js → scene/sceneMethods.js} +43 -15
- package/core/scene/stepPoses.js +60 -0
- package/core/{targeting.js → scene/targeting.js} +4 -5
- package/core/{thingExplain.js → scene/thingExplain.js} +7 -6
- package/core/{thingOps.js → scene/thingOps.js} +25 -16
- package/core/{things.js → scene/things.js} +18 -5
- package/core/{threePatches.js → scene/threePatches.js} +1 -1
- package/core/{tier.js → scene/tier.js} +10 -0
- package/core/scene/view.js +161 -0
- package/core/{Batching.js → stream/Batching.js} +85 -28
- package/core/{Stream.js → stream/Stream.js} +80 -38
- package/core/{batchGroups.js → stream/batchGroups.js} +11 -9
- package/core/{chunkStream.js → stream/chunkStream.js} +40 -0
- package/core/{scatter.js → stream/scatter.js} +7 -4
- package/core/{streamSources.js → stream/streamSources.js} +14 -8
- package/core/{Commits.js → threads/Commits.js} +17 -11
- package/core/{Jobs.js → threads/Jobs.js} +25 -13
- package/core/{Threads.js → threads/Threads.js} +21 -18
- package/core/{threadPure.js → threads/threadPure.js} +7 -5
- package/core/{threadServe.js → threads/threadServe.js} +3 -3
- package/core/{Clock.js → time/Clock.js} +20 -11
- package/core/{dayTime.js → time/dayTime.js} +5 -1
- package/core/{skip.js → time/skip.js} +28 -21
- package/core/{time.js → time/time.js} +32 -20
- package/core/{uiClock.js → time/uiClock.js} +4 -4
- package/docs/AI.md +92 -72
- package/docs/API.md +33 -28
- package/docs/CODEMAP.md +121 -200
- package/docs/COMMANDS.md +77 -70
- package/docs/CONVENTIONS.md +167 -24
- package/docs/MIGRATING-0.8.md +171 -0
- package/docs/MIGRATING-1.0.md +101 -0
- package/docs/THREE.md +140 -38
- package/docs/api/assets.md +12 -13
- package/docs/api/audio.md +6 -5
- package/docs/api/budget.md +4 -4
- package/docs/api/calendar.md +10 -11
- package/docs/api/cameraRig.md +32 -29
- package/docs/api/characters.md +35 -24
- package/docs/api/clock.md +1 -1
- package/docs/api/collider3d.md +9 -0
- package/docs/api/collision.md +12 -9
- package/docs/api/content.md +18 -17
- package/docs/api/dialogue.md +5 -4
- package/docs/api/engine.md +58 -54
- package/docs/api/events.md +17 -6
- package/docs/api/flow.md +1 -1
- package/docs/api/grids.md +1 -1
- package/docs/api/ground.md +6 -7
- package/docs/api/hud.md +2 -2
- package/docs/api/i18n.md +6 -6
- package/docs/api/input.md +9 -8
- package/docs/api/interactions.md +5 -5
- package/docs/api/inventory.md +10 -10
- package/docs/api/jobs.md +5 -5
- package/docs/api/level.md +10 -9
- package/docs/api/lightPool.md +1 -6
- package/docs/api/music.md +3 -3
- package/docs/api/nav.md +14 -12
- package/docs/api/openWorld.md +1 -1
- package/docs/api/particles.md +10 -7
- package/docs/api/photo.md +4 -2
- package/docs/api/pickups.md +3 -3
- package/docs/api/post.md +21 -5
- package/docs/api/quests.md +7 -5
- package/docs/api/rays.md +7 -7
- package/docs/api/rigid.md +29 -19
- package/docs/api/saves.md +13 -11
- package/docs/api/settings.md +9 -8
- package/docs/api/sky.md +8 -7
- package/docs/api/stream.md +8 -9
- package/docs/api/swarm.md +34 -0
- package/docs/api/terrain.md +6 -8
- package/docs/api/terrainDraw.md +2 -2
- package/docs/api/timeline.md +4 -4
- package/docs/api/tools.md +27 -22
- package/docs/api/triggers.md +2 -0
- package/docs/api/vars.md +1 -1
- package/docs/api/vegetation.md +4 -3
- package/docs/api/vegetationDraw.md +2 -2
- package/docs/api/water.md +7 -3
- package/docs/api/weather.md +27 -12
- package/docs/api/weatherDraw.md +4 -4
- package/docs/api/world.md +6 -6
- package/docs/recipes/01-new-game.md +28 -43
- package/docs/recipes/02-npc.md +21 -23
- package/docs/recipes/03-items-pickups.md +37 -53
- package/docs/recipes/04-quests.md +5 -4
- package/docs/recipes/05-props-bake.md +34 -44
- package/docs/recipes/06-clock-events.md +31 -22
- package/docs/recipes/07-flow-scenes-pause.md +30 -32
- package/docs/recipes/08-weather-sky.md +91 -37
- package/docs/recipes/09-materials-lights-models.md +25 -39
- package/docs/recipes/10-blender-level.md +22 -11
- package/docs/recipes/11-vehicles.md +44 -24
- package/docs/recipes/12-navmesh.md +60 -15
- package/docs/recipes/13-animation.md +70 -22
- package/docs/recipes/14-custom-module.md +33 -20
- package/docs/recipes/15-perf.md +51 -28
- package/docs/recipes/16-dev-bridge.md +39 -58
- package/docs/recipes/18-world.md +49 -28
- package/docs/recipes/19-shooting-picking.md +7 -4
- package/docs/recipes/20-content-actions-save.md +55 -40
- package/docs/recipes/21-camera.md +47 -25
- package/docs/recipes/22-shop-gold.md +21 -16
- package/docs/recipes/23-ops.md +28 -24
- package/docs/recipes/26-ui-parts.md +25 -14
- package/docs/recipes/27-net.md +3 -5
- package/docs/recipes/28-terrain.md +119 -23
- package/docs/recipes/29-grid.md +3 -3
- package/docs/recipes/30-templates.md +63 -30
- package/docs/recipes/31-audio.md +7 -7
- package/docs/recipes/32-action-game.md +21 -11
- package/docs/recipes/33-stream-sources.md +6 -3
- package/docs/recipes/34-environment-lighting.md +72 -25
- package/docs/recipes/35-picture-from-reference.md +20 -23
- package/docs/recipes/36-ground-plants.md +106 -0
- package/docs/recipes/40-scene.md +18 -21
- package/docs/recipes/43-shader-patches-surfaces.md +27 -48
- package/docs/recipes/44-water-weather-hooks.md +56 -50
- package/docs/recipes/45-cascaded-shadows.md +41 -20
- package/docs/recipes/46-blender-art-route.md +9 -10
- package/docs/recipes/49-game-module-contract.md +7 -6
- package/docs/recipes/50-own-renderer.md +3 -2
- package/docs/recipes/51-capability-catalog.md +14 -8
- package/docs/recipes/52-around-the-picture.md +56 -100
- package/docs/recipes/53-ground-up-close.md +61 -24
- package/docs/recipes/55-mods-time-wrap.md +17 -20
- package/docs/recipes/56-webgpu-tsl.md +28 -15
- package/docs/recipes/57-control.md +39 -12
- package/docs/recipes/58-input.md +15 -2
- package/docs/recipes/59-depth-post-effects.md +1 -1
- package/docs/recipes/60-judge-the-picture.md +30 -25
- package/docs/recipes/62-picture-code.md +129 -39
- package/docs/recipes/63-third-person-start.md +19 -5
- package/docs/recipes/64-particles.md +54 -5
- package/docs/recipes/65-swarm.md +140 -0
- package/docs/recipes/66-common-tasks.md +313 -0
- package/examples/action/.threedog/content-index.json +1 -1
- package/examples/action/GAMEMAP.md +5 -5
- package/examples/perf-island/.threedog/content-index.json +1 -0
- package/examples/{sheepisland → perf-island}/GAMEMAP.md +15 -14
- package/examples/{sheepisland → perf-island}/assets.js +1 -1
- package/examples/{sheepisland → perf-island}/main.js +8 -8
- package/examples/{sheepisland → perf-island}/models.js +1 -1
- package/examples/{sheepisland → perf-island}/params.js +1 -1
- package/examples/{sheepisland → perf-island}/picture/index.js +1 -1
- package/examples/{sheepisland → perf-island}/picture/palette.js +2 -2
- package/examples/{sheepisland → perf-island}/views.js +1 -1
- package/examples/plain-picture/GAMEMAP.md +4 -1
- package/examples/rc2d/GAMEMAP.md +4 -3
- package/examples/rc2d/main.js +1 -3
- package/examples/rc2d/rc2d.js +1 -1
- package/examples/styletest/.threedog/content-index.json +1 -1
- package/examples/styletest/GAMEMAP.md +6 -5
- package/examples/techniques/contact-shadows/contactShadows.js +1 -1
- package/examples/techniques/contact-shadows/main.js +1 -1
- package/examples/techniques/interior-light/main.js +1 -1
- package/examples/techniques/modular-building/README.md +7 -6
- package/examples/techniques/outlines-and-rim/picture/post.js +1 -1
- package/examples/techniques/procedural-animation/README.md +1 -1
- package/examples/webgpu-tsl/GAMEMAP.md +2 -1
- package/examples/world/.threedog/content-index.json +1 -1
- package/examples/world/GAMEMAP.md +9 -7
- package/examples/world/main.js +3 -3
- package/examples/world/picture/sky.js +1 -1
- package/index.d.ts +16 -12
- package/index.js +53 -32
- package/llms.txt +11 -14
- package/modules/ambience/Ambience.js +16 -11
- package/modules/calendar/Calendar.js +19 -19
- package/modules/calendar/index.js +18 -16
- package/modules/calendar/schedule.js +11 -6
- package/modules/calendar/seasons.js +7 -7
- package/modules/camera/FirstPersonCamera.js +5 -5
- package/modules/camera/FixedCamera.js +43 -30
- package/modules/camera/FollowCamera.js +24 -15
- package/modules/camera/RtsCamera.js +12 -11
- package/modules/camera/common.js +72 -37
- package/modules/camera/contract.js +1 -0
- package/modules/camera/pixelSnap.js +62 -0
- package/modules/characters/Character.js +166 -70
- package/modules/characters/NPC.js +84 -44
- package/modules/characters/assetModel.js +16 -12
- package/modules/characters/astar.js +48 -27
- package/modules/characters/behaviors.js +4 -5
- package/modules/characters/character.contract.js +21 -0
- package/modules/characters/contract.js +17 -3
- package/modules/characters/index.js +240 -226
- package/modules/characters/moveHelpers.js +88 -12
- package/modules/characters/mover.contract.js +14 -0
- package/modules/characters/movers/common.js +22 -18
- package/modules/characters/movers/manual.js +1 -1
- package/modules/characters/movers/rapier.js +18 -10
- package/modules/characters/movers/simple.js +26 -13
- package/modules/characters/movers/support.js +24 -13
- package/modules/characters/npcAvoid.js +19 -16
- package/modules/characters/npcSim.js +88 -32
- package/modules/characters/npcView.js +19 -11
- package/modules/characters/pathAsync.js +81 -29
- package/modules/characters/pathJob.js +38 -21
- package/modules/characters/pathWorker.js +1 -1
- package/modules/characters/player.js +120 -0
- package/modules/characters/playerStrings.js +2 -2
- package/modules/characters/proceduralRig.js +2 -2
- package/modules/characters/seat.js +56 -0
- package/modules/characters/useModel.js +3 -3
- package/modules/characters/vehicle.contract.js +8 -5
- package/modules/characters/walkTo.js +40 -33
- package/modules/collision/Collision.js +69 -45
- package/modules/collision/contract.js +15 -0
- package/modules/collision/grid.js +6 -1
- package/modules/content/explain.js +2 -3
- package/modules/content/fields.js +24 -3
- package/modules/content/ids.js +5 -3
- package/modules/content/index.js +132 -114
- package/modules/content/loader.js +117 -140
- package/modules/content/markers.js +25 -0
- package/modules/content/models.js +54 -17
- package/modules/content/packs.js +5 -4
- package/modules/content/parts.js +2 -2
- package/modules/content/places.js +36 -0
- package/modules/content/props.js +22 -17
- package/modules/content/rules.js +47 -61
- package/modules/content/stages.js +7 -7
- package/modules/content/templates.js +80 -49
- package/modules/content/words.js +47 -0
- package/modules/debug/DebugPanel.js +14 -45
- package/modules/flow/contract.js +2 -1
- package/modules/flow/index.js +30 -16
- package/modules/gameplay/Container.js +17 -13
- package/modules/gameplay/Containers.js +23 -6
- package/modules/gameplay/Dialogue.js +93 -34
- package/modules/gameplay/Interactions.js +93 -51
- package/modules/gameplay/Inventory.js +64 -22
- package/modules/gameplay/Quests.js +146 -30
- package/modules/gameplay/boxOps.js +8 -1
- package/modules/gameplay/dialogueBubbles.js +16 -12
- package/modules/gameplay/inventoryOps.js +11 -8
- package/modules/gameplay/pickups.js +63 -37
- package/modules/gameplay/questLog.js +4 -2
- package/modules/gameplay/questSave.js +9 -4
- package/modules/gameplay/quests.contract.js +1 -1
- package/modules/grid/Grid.js +2 -2
- package/modules/grid/Layer.js +12 -8
- package/modules/grid/index.js +28 -23
- package/modules/grid/ops.js +43 -46
- package/modules/grid/preview.js +7 -7
- package/modules/grid/tiles.js +6 -6
- package/modules/hlod/index.js +42 -57
- package/modules/hud/index.js +22 -14
- package/modules/hud/parts.js +8 -8
- package/modules/level/contract.js +16 -0
- package/modules/level/heightfield.js +29 -31
- package/modules/level/index.js +113 -161
- package/modules/level/load.js +196 -0
- package/modules/level/meshes.js +65 -0
- package/modules/level/nodes.js +40 -23
- package/modules/lights/index.js +33 -183
- package/modules/lights/slots.js +93 -0
- package/modules/lights/sources.js +90 -0
- package/modules/music/Music.js +34 -28
- package/modules/music/rules.js +1 -1
- package/modules/nav/contract.js +16 -0
- package/modules/nav/index.js +180 -49
- package/modules/nav/navPath.js +45 -10
- package/modules/net/Client.js +7 -7
- package/modules/net/Host.js +7 -7
- package/modules/net/Net.js +1 -1
- package/modules/net/index.js +6 -5
- package/modules/net/sync.js +2 -2
- package/modules/net/transports.js +2 -2
- package/modules/particles/Particles.js +95 -29
- package/modules/particles/effect.js +86 -32
- package/modules/particles/shaders.js +19 -1
- package/modules/photo/Photo.js +23 -23
- package/modules/rigid/RigidBodies.js +255 -89
- package/modules/rigid/Vehicles.js +17 -8
- package/modules/rigid/collider3d.contract.js +26 -0
- package/modules/rigid/ragdoll.js +298 -0
- package/modules/rigid/ragdollBones.js +209 -0
- package/modules/rigid/refresh.js +10 -0
- package/modules/rigid/sync.js +51 -20
- package/modules/settings/Settings.js +177 -61
- package/modules/settings/apply.js +20 -13
- package/modules/settings/sections.js +19 -14
- package/modules/settings/strings.js +2 -2
- package/modules/settings/view.js +3 -3
- package/modules/sky/Sky.js +29 -22
- package/modules/sky/clouds.js +7 -7
- package/modules/sky/dome.js +33 -20
- package/modules/sky/domeLayers.js +9 -9
- package/modules/sky/environment.js +6 -6
- package/modules/sky/frame.js +19 -10
- package/modules/sky/season.js +7 -1
- package/modules/sky/shader.js +24 -25
- package/modules/sky/skyModule.js +17 -28
- package/modules/sky/tint.js +1 -1
- package/modules/swarm/Swarm.js +356 -0
- package/modules/swarm/draw.js +68 -0
- package/modules/swarm/grid.js +63 -0
- package/modules/terrain/ChunkManager.js +71 -59
- package/modules/terrain/chunkQueries.js +7 -24
- package/modules/terrain/chunkWorker.js +1 -1
- package/modules/terrain/draw.js +14 -11
- package/modules/terrain/index.js +42 -42
- package/modules/terrain/terrainColorMap.js +6 -3
- package/modules/terrain/terrainDefaults.js +2 -1
- package/modules/terrain/terrainEdit.js +45 -29
- package/modules/terrain/terrainGen.js +19 -12
- package/modules/terrain/terrainIsland.js +2 -2
- package/modules/terrain/terrainMesh.js +7 -6
- package/modules/terrain/terrainShape.js +8 -10
- package/modules/terrain/terrainShapeMain.js +3 -3
- package/modules/timeline/Timeline.js +83 -43
- package/modules/timeline/Tween.js +25 -19
- package/modules/timeline/shots.js +24 -17
- package/modules/triggers/index.js +95 -28
- package/modules/vegetation/Vegetation.js +34 -26
- package/modules/vegetation/densityMap.js +4 -7
- package/modules/vegetation/draw.js +39 -18
- package/modules/vegetation/groundChunks.js +21 -38
- package/modules/vegetation/index.js +37 -12
- package/modules/vegetation/modelGeometry.js +3 -6
- package/modules/vegetation/nearFade.js +1 -1
- package/modules/water/Water.js +20 -16
- package/modules/water/surface.js +3 -3
- package/modules/weather/Weather.js +52 -40
- package/modules/weather/particles.js +8 -8
- package/modules/weather/weatherDraw.js +28 -23
- package/modules/world/World.js +28 -15
- package/modules/world/explain.js +1 -1
- package/modules/world/index.js +30 -17
- package/modules/world/persist.js +90 -27
- package/modules/world/pos.js +5 -5
- package/modules/world/records.js +37 -11
- package/modules/world/sim.js +78 -27
- package/modules/world/simFar.js +2 -2
- package/modules/world/state.js +43 -11
- package/modules/world/thingSource.js +20 -5
- package/modules/world/views.js +27 -14
- package/package.json +48 -7
- package/presets.js +1 -3
- package/render/PostFX.js +83 -53
- package/render/backend.js +31 -33
- package/render/cascades.js +17 -12
- package/render/cascades.tsl.js +5 -8
- package/render/daylight.js +20 -3
- package/render/detail.js +8 -7
- package/render/effects.js +28 -25
- package/render/fuse.js +3 -3
- package/render/fx/cloudShadow.tsl.js +3 -3
- package/render/fx/detail.tsl.js +1 -1
- package/render/fx/index.js +5 -10
- package/render/fx/library.tsl.js +11 -0
- package/render/fx/lighting.tsl.js +2 -1
- package/render/fx/nodeErrors.tsl.js +2 -2
- package/render/fx/objectOrigin.tsl.js +1 -2
- package/render/fx/particles.tsl.js +8 -6
- package/render/fx/patchNodes.tsl.js +5 -15
- package/render/fx/postWebGPU.tsl.js +30 -26
- package/render/fx/sky.tsl.js +15 -17
- package/render/fx/uniforms.tsl.js +4 -4
- package/render/fx/wind.tsl.js +1 -1
- package/render/fxNumbers.js +3 -0
- package/render/layers.js +2 -2
- package/render/lighting.js +5 -3
- package/render/lightmap.js +41 -21
- package/render/lights.js +6 -6
- package/render/lit.js +24 -0
- package/render/materials.js +8 -7
- package/render/mergeCommon.js +22 -0
- package/render/modeling.js +2 -2
- package/render/occlusion.js +62 -15
- package/render/ownFrame.js +4 -4
- package/render/patches.js +15 -15
- package/render/postWebGL.js +15 -12
- package/render/probes.js +41 -19
- package/render/recordSweep.js +117 -0
- package/render/shaderErrors.js +10 -9
- package/render/shadowCache.tsl.js +107 -0
- package/render/shadowTypes.js +9 -0
- package/{core → render}/shadows.js +59 -13
- package/render/slots.js +7 -7
- package/render/terms.js +22 -24
- package/render/uniformDecl.js +1 -1
- package/types/core.d.ts +336 -202
- package/types/gameplay.d.ts +254 -130
- package/types/generated/core/{Audio.d.ts → audio/Audio.d.ts} +22 -7
- package/types/generated/core/{audioVoice.d.ts → audio/audioVoice.d.ts} +2 -2
- package/types/generated/core/{Events.d.ts → base/Events.d.ts} +4 -4
- package/types/generated/core/{I18n.d.ts → base/I18n.d.ts} +8 -16
- package/types/generated/core/{Random.d.ts → base/Random.d.ts} +4 -3
- package/types/generated/core/{page.d.ts → engine/page.d.ts} +8 -9
- package/types/generated/core/{Input.d.ts → input/Input.d.ts} +28 -10
- package/types/generated/core/input/inputSeat.d.ts +26 -0
- package/types/generated/core/{Budget.d.ts → inspect/Budget.d.ts} +36 -26
- package/types/generated/core/{DebugOverrides.d.ts → inspect/DebugOverrides.d.ts} +17 -3
- package/types/generated/core/{Ops.d.ts → ops/Ops.d.ts} +6 -4
- package/types/generated/core/{control.d.ts → ops/control.d.ts} +14 -10
- package/types/generated/core/{Saves.d.ts → saves/Saves.d.ts} +62 -18
- package/types/generated/core/{session.d.ts → saves/session.d.ts} +3 -2
- package/types/generated/core/{Rays.d.ts → scene/Rays.d.ts} +8 -27
- package/types/generated/core/{Views.d.ts → scene/Views.d.ts} +2 -2
- package/types/generated/core/{Batching.d.ts → stream/Batching.d.ts} +7 -7
- package/types/generated/core/{Stream.d.ts → stream/Stream.d.ts} +22 -18
- package/types/generated/core/{Commits.d.ts → threads/Commits.d.ts} +1 -1
- package/types/generated/core/{Jobs.d.ts → threads/Jobs.d.ts} +6 -6
- package/types/generated/core/{Threads.d.ts → threads/Threads.d.ts} +4 -4
- package/types/generated/modules/calendar/Calendar.d.ts +10 -11
- package/types/generated/modules/debug/DebugPanel.d.ts +1 -9
- package/types/generated/modules/grid/Grid.d.ts +1 -0
- package/types/generated/modules/grid/Layer.d.ts +1 -1
- package/types/generated/modules/grid/index.d.ts +3 -3
- package/types/generated/modules/music/Music.d.ts +7 -5
- package/types/generated/modules/particles/Particles.d.ts +5 -4
- package/types/generated/modules/sky/Sky.d.ts +21 -10
- package/types/generated/modules/swarm/Swarm.d.ts +80 -0
- package/types/generated/modules/timeline/Timeline.d.ts +7 -5
- package/types/generated/modules/water/Water.d.ts +1 -0
- package/types/generated/modules/weather/Weather.d.ts +14 -16
- package/types/generated/modules/weather/weatherDraw.d.ts +3 -3
- package/types/generated/modules/world/World.d.ts +11 -7
- package/types/generated/render/PostFX.d.ts +21 -23
- package/types/generated/render/materials.d.ts +1 -0
- package/types/generated/render/occlusion.d.ts +9 -0
- package/types/generated/render/patches.d.ts +1 -0
- package/types/generated/ui/Focus.d.ts +1 -0
- package/types/generated/ui/UI.d.ts +1 -0
- package/types/nav.d.ts +47 -15
- package/types/physics.d.ts +150 -73
- package/types/pixel.d.ts +75 -0
- package/types/tsl.d.ts +37 -4
- package/types/world.d.ts +48 -75
- package/ui/Focus.js +10 -9
- package/ui/Parts.js +13 -5
- package/ui/UI.js +7 -7
- package/ui/defaults.js +3 -2
- package/ui/theme.js +7 -5
- package/core/assetEntry.js +0 -109
- package/core/engineCamera.js +0 -32
- package/core/ground.js +0 -104
- package/core/holds.js +0 -134
- package/core/math.js +0 -48
- package/core/moduleSlots.js +0 -100
- package/core/modules.js +0 -314
- package/core/saveApply.js +0 -210
- package/core/saveValues.js +0 -46
- package/core/session.js +0 -174
- package/core/shadowTypes.js +0 -16
- package/core/util.js +0 -17
- package/core/view.js +0 -43
- package/docs/MIGRATING-0.3.md +0 -248
- package/docs/MIGRATING-0.4.md +0 -320
- package/docs/MIGRATING-0.5.md +0 -68
- package/docs/MIGRATING-0.6.md +0 -126
- package/docs/PERF.md +0 -245
- package/docs/recipes/36-sky-ground-plants.md +0 -158
- package/docs/recipes/37-terrain-hooks.md +0 -115
- package/docs/recipes/38-environment-hooks.md +0 -67
- package/docs/recipes/42-terrain-shape.md +0 -64
- package/docs/recipes/47-island-snow-backdrop.md +0 -43
- package/docs/recipes/54-three-idioms.md +0 -88
- package/examples/plain-picture/FINDINGS.md +0 -53
- package/examples/sheepisland/.threedog/content-index.json +0 -1
- package/modules/camera/projection.js +0 -21
- /package/core/{mulberry32.js → base/mulberry32.js} +0 -0
- /package/core/{inputDefaults.js → input/inputDefaults.js} +0 -0
- /package/core/{textureBytes.js → inspect/textureBytes.js} +0 -0
- /package/core/{actor.js → ops/actor.js} +0 -0
- /package/core/{opsHistory.js → ops/opsHistory.js} +0 -0
- /package/core/{saveIds.js → saves/saveIds.js} +0 -0
- /package/core/{screenToGround.js → scene/screenToGround.js} +0 -0
- /package/core/{cells.js → stream/cells.js} +0 -0
- /package/core/{streamCells.js → stream/streamCells.js} +0 -0
- /package/core/{pureWorker.js → threads/pureWorker.js} +0 -0
- /package/examples/{sheepisland → perf-island}/content/index.js +0 -0
- /package/examples/{sheepisland → perf-island}/content/props.js +0 -0
- /package/examples/{sheepisland → perf-island}/content/templates.js +0 -0
- /package/examples/{sheepisland → perf-island}/content/vegetation.js +0 -0
- /package/examples/{sheepisland → perf-island}/picture/lights.js +0 -0
- /package/examples/{sheepisland → perf-island}/picture/materials.js +0 -0
- /package/examples/{sheepisland → perf-island}/picture/sky.js +0 -0
|
@@ -0,0 +1,312 @@
|
|
|
1
|
+
// Applying a save (split out of Saves.js): every part is checked and migrated before anything changes (saveVersions.js), then loaded in order;
|
|
2
|
+
// if anything in the load throws, every part reloads the state from just before the load (rollback), so a game is never left half-loaded.
|
|
3
|
+
// "Anything" is the whole load, not only load() itself: a listener of an event a part emits while loading (world:load) and the modules' afterLoad
|
|
4
|
+
// hooks count too. Reported on their own they let the load carry on: a hand-edited player position threw in a world:load listener and left the game
|
|
5
|
+
// frozen half-loaded (durability audit 2026-11-02).
|
|
6
|
+
// The capture lasts the whole load, past every await: an async part that emits after `await` (async load(d) { apply(d); await res(); emit(...) })
|
|
7
|
+
// is part of the load as much as its first line. The browser has no async context to tell whose code emitted after an await, so each load
|
|
8
|
+
// carries its own capture scope (Events._scopes): a part's synchronous run puts its load's scope on top; between awaits the load started last
|
|
9
|
+
// gets the errors. Only one load runs at a time, inside its turn (stateReplace.js), so that load is this one. Everything here returns a plain value
|
|
10
|
+
// while it stays synchronous: a fully synchronous save ends before apply returns. An unrelated listener that throws while a load is still settling
|
|
11
|
+
// fails that load too; gameplay is frozen while parts load, so that is rare, and the error is reported.
|
|
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
|
+
// A part about to load whose save() gives nothing to copy (null, or it threw) goes back to its new-game state; with none of that either it cannot go back, and a failed load says so.
|
|
14
|
+
import { toast } from '../../ui/UI.js';
|
|
15
|
+
import { fmt, warnOnce } from '../base/validate.js';
|
|
16
|
+
import { reportError } from '../base/errors.js';
|
|
17
|
+
import { codedError, coded } from '../base/errorHints.js';
|
|
18
|
+
import { FORMAT, readSave, parseSave, upgradePart, partVersion } from './saveVersions.js';
|
|
19
|
+
import { isObject } from '../base/util.js';
|
|
20
|
+
|
|
21
|
+
const DEV_STRINGS = {
|
|
22
|
+
loadThrew: "load() of save part '{k}' threw ({msg}); the game was rolled back to how it was before loading '{slot}'",
|
|
23
|
+
partAt: "load() of save part '{k}'", adoptAt: "load() of save part '{k}' (registered after the save was loaded)",
|
|
24
|
+
rollback: "rollback of save part '{k}' after a failed load (that part may be half-loaded; the other parts rolled back)",
|
|
25
|
+
noRollback: "save part '{k}' keeps what the failed load gave it: its save() gave nothing before the load and it has no new-game state to go back to (the other parts rolled back)",
|
|
26
|
+
notData: "save() of save part '{k}' returned {got}, which a save cannot hold; return plain data, or null when there is nothing to save",
|
|
27
|
+
notNumber: "save() of save part '{k}' holds {got} at {path}, which a save cannot hold (it would come back as null); save a finite number, or leave the field out",
|
|
28
|
+
listener: 'a listener of event {name} threw while the part loaded: {msg}',
|
|
29
|
+
hook: "afterLoad of module '{k}' threw ({msg}); the game was rolled back to how it was before loading '{slot}'",
|
|
30
|
+
notPlain: "save() of save part '{k}' returned data that cannot be copied ({msg}), so loading '{slot}' could not keep a rollback point and was refused "
|
|
31
|
+
+ 'before anything changed. save() must return plain data (no functions, DOM nodes, three objects); return a copy of what the save needs',
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
/** A save part's load threw: the error named after the part (thrown on, so the caller can roll back) */
|
|
35
|
+
const loadError = (k, err, slot) => Object.assign(codedError('save-load-threw', fmt(DEV_STRINGS.loadThrew, { k, slot, msg: err?.message ?? String(err) })), { part: k, cause: err });
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Implementation of saves.apply (see its JSDoc): checked first, applied part by part, rolled back to the pre-load state if any part throws.
|
|
39
|
+
* Runs inside a turn of s._replace; the marker is on from the first read to the last rollback step.
|
|
40
|
+
* @param {any} s the Saves instance
|
|
41
|
+
* @param {any} data
|
|
42
|
+
* @param {string} slot
|
|
43
|
+
* @returns {boolean | Promise<boolean>} a plain value when nothing waited
|
|
44
|
+
* @internal
|
|
45
|
+
*/
|
|
46
|
+
export function applySave(s, data, slot) {
|
|
47
|
+
const q = s._replace, job = q.job;
|
|
48
|
+
q.begin();
|
|
49
|
+
let out;
|
|
50
|
+
try { out = checkAndApply(s, data, slot); } catch (err) { q.end(); throw err; }
|
|
51
|
+
if (typeof out !== 'boolean') return out.finally(() => q.endOf(job));
|
|
52
|
+
q.end();
|
|
53
|
+
return out;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** The body of applySave, under the marker */
|
|
57
|
+
function checkAndApply(s, data, slot) {
|
|
58
|
+
const r = readSave(data, s.providers, slot);
|
|
59
|
+
if ('reason' in r) {
|
|
60
|
+
if (r.reason !== 'missing') { warnOnce(coded('save-refused', r.dev)); // handled: the player is told, nothing changed
|
|
61
|
+
toast(s.engine, s.engine.t('saves.' + r.reason), { kind: 'error', ms: 5000 }); }
|
|
62
|
+
return false;
|
|
63
|
+
}
|
|
64
|
+
const e = s.engine, foreign0 = s._foreign;
|
|
65
|
+
let before; // the rollback point, a copy (rollbackPoint)
|
|
66
|
+
try { before = rollbackPoint(s, slot, r.list); } catch (err) { reportError(e, err, `saves.apply('${slot}')`); return false; }
|
|
67
|
+
const ev = e.events, scope = []; // this load's capture scope: listener errors from now until the load settled (top of the file)
|
|
68
|
+
ev._scopes.push(scope);
|
|
69
|
+
const settled = () => { const i = ev._scopes.lastIndexOf(scope); if (i >= 0) ev._scopes.splice(i, 1); };
|
|
70
|
+
let out;
|
|
71
|
+
try { out = applyParts(s, e, r, slot, before, foreign0, scope); } catch (err) { settled(); throw err; }
|
|
72
|
+
if (typeof out !== 'boolean') return out.finally(settled);
|
|
73
|
+
settled();
|
|
74
|
+
return out;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** The rest of applySave, under the load's capture scope */
|
|
78
|
+
function applyParts(s, e, r, slot, before, foreign0, scope) {
|
|
79
|
+
const q = s._replace;
|
|
80
|
+
const keepResults = e.commits.invalidate(); e.ops._mark('(load)'); // old background results die with the old world; the op log shows where the load cut in
|
|
81
|
+
const generation = q.generation++;
|
|
82
|
+
q.changed();
|
|
83
|
+
s._foreign = r.foreign;
|
|
84
|
+
const fail = err => {
|
|
85
|
+
keepResults(); q.generation = generation; q.changed(true); // the old world stays, and what it was waiting for with it
|
|
86
|
+
// 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
|
|
87
|
+
// does not freeze gameplay as a code error would; a load() / listener / afterLoad that throws is a bug and goes through the error tiers
|
|
88
|
+
const refused = err?.cause?.code === 'save-bad-record';
|
|
89
|
+
if (refused) { warnOnce(err.message); toast(e, e.t('saves.corrupt'), { kind: 'error', ms: 5000 }); }
|
|
90
|
+
else reportError(e, err, err?.part ? fmt(DEV_STRINGS.partAt, { k: err.part }) : `saves.apply('${slot}')`);
|
|
91
|
+
s._foreign = foreign0;
|
|
92
|
+
const back = readSave(before, s.providers, '(rollback)');
|
|
93
|
+
// every part reloads its pre-load state; a part that throws again is reported (once) and the rest still roll back
|
|
94
|
+
const onPart = er => reportError(e, er, fmt(DEV_STRINGS.rollback, { k: er.part }), { soft: true });
|
|
95
|
+
const undone = 'list' in back ? e.ops.allow(() => runParts(s, back.list, '(rollback)', scope, onPart)) : true;
|
|
96
|
+
// a part that refused its data took none of it: it has nothing to go back from
|
|
97
|
+
for (const [k] of r.list) if (!Object.hasOwn(before.parts, k) && !(refused && k === err.part)) reportError(e, codedError('save-load-threw', fmt(DEV_STRINGS.noRollback, { k })), `saves.apply('${slot}')`, { soft: true });
|
|
98
|
+
// a session door announces its own failure, after its clocks came back
|
|
99
|
+
const failed = () => { if (!e.session._busy) e.events.emit('session:failed', { kind: 'quick', slot }); return false; };
|
|
100
|
+
if (undone === true) return failed();
|
|
101
|
+
q.hold(); // a rollback that waits on an async part holds gameplay too, whichever way the load failed
|
|
102
|
+
return undone.then(failed);
|
|
103
|
+
};
|
|
104
|
+
// 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()
|
|
105
|
+
const partsDone = () => {
|
|
106
|
+
e.ops.revision++;
|
|
107
|
+
let hooks;
|
|
108
|
+
try { hooks = afterLoad(s, e, slot, scope); } catch (err) { return fail(err); }
|
|
109
|
+
return hooks === true ? true : hooks.then(() => true, fail);
|
|
110
|
+
};
|
|
111
|
+
let out;
|
|
112
|
+
try { out = e.ops.allow(() => runParts(s, r.list, slot, scope)); } catch (err) { return fail(err); } // loading writes state outside ops on purpose (guard allows it)
|
|
113
|
+
if (out === true) return partsDone();
|
|
114
|
+
q.hold(); // a part still loading (its load() returned a Promise): gameplay waits until every part is applied. A fully sync load never takes it
|
|
115
|
+
return out.then(partsDone, fail);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** The rollback point: every part's save(), copied so a load() writing into the object its save() returned cannot change it.
|
|
119
|
+
* A part whose data cannot be copied throws (save-part-threw): without a true copy a failed load could not be undone.
|
|
120
|
+
* list: the parts about to load; those with nothing to copy take their new-game data (top of the file) */
|
|
121
|
+
function rollbackPoint(s, slot, list) {
|
|
122
|
+
const data = s._collect().data, S = s.engine.session, base = S._base ? S._baseData() : { parts: {}, versions: {} };
|
|
123
|
+
for (const [k] of list) if (!Object.hasOwn(data.parts, k) && Object.hasOwn(base.parts, k)) { data.parts[k] = base.parts[k]; data.versions[k] = base.versions[k]; }
|
|
124
|
+
for (const k of Object.keys(data.parts)) {
|
|
125
|
+
try { data.parts[k] = structuredClone(data.parts[k]); }
|
|
126
|
+
catch (err) { throw Object.assign(codedError('save-part-threw', fmt(DEV_STRINGS.notPlain, { k, slot, msg: err?.message ?? String(err) })), { cause: err }); }
|
|
127
|
+
}
|
|
128
|
+
return data;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** A listener error collected in scope since index from: the first counts as the load throwing (and the scope forgets them) */
|
|
132
|
+
function takeListenerError(scope, from) {
|
|
133
|
+
if (scope.length <= from) return;
|
|
134
|
+
const { name, err } = scope[from];
|
|
135
|
+
scope.length = from;
|
|
136
|
+
throw Object.assign(new Error(fmt(DEV_STRINGS.listener, { name, msg: err?.message ?? String(err) })), { cause: err });
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** Run one part's load with event-listener errors collected in the load's scope (on top while it runs synchronously, see the top of the file);
|
|
140
|
+
* an async load is checked once it settled, so a listener that throws after its await fails the part too */
|
|
141
|
+
function callLoad(s, fn, scope) {
|
|
142
|
+
const ev = s.engine.events, from = scope.length;
|
|
143
|
+
ev._scopes.push(scope);
|
|
144
|
+
let r;
|
|
145
|
+
try { r = fn(); } catch (err) { scope.length = from; throw err; } finally { ev._scopes.splice(ev._scopes.lastIndexOf(scope), 1); }
|
|
146
|
+
if (r && typeof r.then === 'function') return r.then(v => { takeListenerError(scope, from); return v; }, err => { scope.length = from; throw err; });
|
|
147
|
+
takeListenerError(scope, from);
|
|
148
|
+
return r;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* Load parts in order; a part returning a Promise makes the rest wait for it. A failing part throws (or rejects) with the part named,
|
|
153
|
+
* unless onFail is given (rollback): then onFail(err) is called and the next part loads anyway.
|
|
154
|
+
*/
|
|
155
|
+
function runParts(s, list, slot, scope, onFail = null) {
|
|
156
|
+
const failed = (k, err) => { const er = loadError(k, err, slot); if (!onFail) throw er; onFail(er); }, { turn } = s._replace.job;
|
|
157
|
+
const step = i => {
|
|
158
|
+
for (; i < list.length; i++) {
|
|
159
|
+
const [k, p, d] = list[i];
|
|
160
|
+
let r;
|
|
161
|
+
try { r = callLoad(s, () => p.load(d, turn), scope); } catch (err) { failed(k, err); continue; }
|
|
162
|
+
if (r && typeof r.then === 'function') return r.then(() => step(i + 1), err => { failed(k, err); return step(i + 1); });
|
|
163
|
+
}
|
|
164
|
+
return true;
|
|
165
|
+
};
|
|
166
|
+
return step(0);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* A part registered after a save was loaded (a module installed later): hand it its data from that save in a turn of its own. Idle that is now. During a
|
|
171
|
+
* replacement it is after it, whole: its first line would write into a half-loaded state, and a newer load waits for it instead of having this older data
|
|
172
|
+
* land on top. A load that replaced the state while it waited took this data with it. The data stays unattached until then, so a save still carries it.
|
|
173
|
+
* @param {any} s the Saves instance
|
|
174
|
+
* @param {string} key
|
|
175
|
+
* @internal
|
|
176
|
+
*/
|
|
177
|
+
export function adoptPart(s, key) {
|
|
178
|
+
const f = s._foreign, q = s._replace, where = fmt(DEV_STRINGS.adoptAt, { k: key });
|
|
179
|
+
q.run(null, () => {
|
|
180
|
+
const p = s.providers.get(key);
|
|
181
|
+
if (s._foreign !== f || !p || !Object.hasOwn(f.parts, key)) return;
|
|
182
|
+
const d = f.parts[key], v = f.versions[key] ?? 1;
|
|
183
|
+
delete f.parts[key]; delete f.versions[key];
|
|
184
|
+
// data the part could not take stays unattached, and collectParts writes it instead of the part's empty state: the next save must not lose it
|
|
185
|
+
const refused = err => { if (s._foreign === f) { f.parts[key] = d; f.versions[key] = v; } reportError(s.engine, err, where); };
|
|
186
|
+
try {
|
|
187
|
+
if (v > p.version) throw codedError('save-refused', `save part '${key}' is version ${v}, this build reads up to ${p.version}`);
|
|
188
|
+
const r = s.engine.ops.allow(() => p.load(upgradePart(key, p, d, v, f.whole), q.job.turn));
|
|
189
|
+
if (r && typeof r.then === 'function') return r.catch(refused);
|
|
190
|
+
} catch (err) { refused(err); }
|
|
191
|
+
}, true);
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* Load a slot; with base (a collect() result) the save goes on top of it, so a part missing from the save gets base's state (session.load).
|
|
197
|
+
* @param {any} s the Saves instance
|
|
198
|
+
* @param {string} slot
|
|
199
|
+
* @param {any} [base]
|
|
200
|
+
* @returns {Promise<boolean>}
|
|
201
|
+
* @internal Runs inside a turn of s._replace
|
|
202
|
+
*/
|
|
203
|
+
export function loadSlot(s, slot, base) {
|
|
204
|
+
let data = s._json.get(slot);
|
|
205
|
+
if (base && data != null) {
|
|
206
|
+
try {
|
|
207
|
+
const sv = parseSave(data);
|
|
208
|
+
if (isObject(sv?.parts) && (sv.versions === undefined || isObject(sv.versions))) { // other shapes go on as they are: apply refuses them with the reason
|
|
209
|
+
const own = Object.fromEntries(Object.keys(sv.parts).map(k => [k, partVersion(sv.versions, k)])); // a part without a version is version 1, not base's
|
|
210
|
+
data = { ...sv, parts: { ...base.parts, ...sv.parts }, versions: { ...base.versions, ...own } };
|
|
211
|
+
}
|
|
212
|
+
} catch { /* unreadable: apply refuses the text itself with the reason */ }
|
|
213
|
+
}
|
|
214
|
+
return applyAnnounced(s, data, slot, () => s._adopt(slot)); // continuing from it: this tab may overwrite it now (Saves._put)
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* Apply a save onto the running playthrough and say so: what is not saved ends on save:loaded, derived state rebuilds on it, and the playthrough runs from here, whichever door the save came through (session.js lists them).
|
|
219
|
+
* @param {any} s the Saves instance
|
|
220
|
+
* @param {any} data
|
|
221
|
+
* @param {string} slot
|
|
222
|
+
* @param {() => void} [done] on success, before the event
|
|
223
|
+
* @returns {Promise<boolean>}
|
|
224
|
+
* @internal Runs inside a turn of s._replace
|
|
225
|
+
*/
|
|
226
|
+
export function applyAnnounced(s, data, slot, done) {
|
|
227
|
+
const q = s._replace, job = q.job, applied = applySave(s, data, slot);
|
|
228
|
+
if (typeof applied === 'boolean') q.pause(); // only the save:loaded below is left, a microtask on
|
|
229
|
+
return Promise.resolve(applied).then(ok => { // apply already ran the modules' afterLoad hooks
|
|
230
|
+
// not when a newer load took over: the game holds that one's state, and it announces itself
|
|
231
|
+
if (ok && q.job === job) { done?.(); s.engine.session._started(); s.engine.events.emit('save:loaded', slot); }
|
|
232
|
+
return ok;
|
|
233
|
+
});
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/** Modules with an afterLoad hook rebuild what the loaded state needs nearby (models and the colliders their build adds); gameplay waits frozen
|
|
237
|
+
* until every one resolves, so the first step after `await saves.load()` never runs on missing ground or walls.
|
|
238
|
+
* applySave runs it (not only saves.load): session.newGame() / quit() apply the base data the same way and need the same rebuild.
|
|
239
|
+
* Every hook settles before the result (allSettled): a rollback must not start while another hook is still building the state being replaced.
|
|
240
|
+
* The first failure rejects, named after its module (save-load-threw), and applySave rolls back. Rollback itself does not rerun afterLoad
|
|
241
|
+
* (the world rebuilds nearby models over the next frames).
|
|
242
|
+
* The hooks run side by side, so a listener error in this phase is not pinned on one hook: once all settled, any error the load's scope
|
|
243
|
+
* collected since its parts finished fails the load (the last check before apply resolves true).
|
|
244
|
+
* Returns true when no module has a hook (nothing waited), else a Promise. The hooks start a microtask after the parts, and the marker and the
|
|
245
|
+
* freeze with them: the lines right after an unawaited apply can still step, run ops and apply again (stateReplace.js, pause). */
|
|
246
|
+
function afterLoad(s, e, slot, scope) {
|
|
247
|
+
const hooks = [...e.modules.values()].filter(m => m.afterLoad), q = s._replace;
|
|
248
|
+
if (!hooks.length) { takeListenerError(scope, 0); return true; }
|
|
249
|
+
const job = q.pause();
|
|
250
|
+
const run = () => {
|
|
251
|
+
if (!q.resume(job)) return null;
|
|
252
|
+
q.hold();
|
|
253
|
+
return Promise.allSettled(hooks.map(m => Promise.resolve().then(() => m.afterLoad(e, job.turn))));
|
|
254
|
+
};
|
|
255
|
+
return Promise.resolve().then(run).then(res => {
|
|
256
|
+
// taken over: the state is the newer load's, so nothing here may fail or roll back; what the scope caught is a listener error like any other
|
|
257
|
+
if (!res) { for (const { name, err } of scope.splice(0)) e.events.onError(name, err); return; }
|
|
258
|
+
const i = res.findIndex(r => r.status === 'rejected');
|
|
259
|
+
if (i >= 0) {
|
|
260
|
+
scope.length = 0;
|
|
261
|
+
const err = /** @type {PromiseRejectedResult} */ (res[i]).reason, k = hooks[i].name;
|
|
262
|
+
throw Object.assign(codedError('save-load-threw', fmt(DEV_STRINGS.hook, { k, slot, msg: err?.message ?? String(err) })), { cause: err });
|
|
263
|
+
}
|
|
264
|
+
takeListenerError(scope, 0);
|
|
265
|
+
});
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/** Where inside a part's data JSON would turn a number into null, as 'pos[0]', else null. seen: a cycle is JSON.stringify's to refuse, not this walk's to chase */
|
|
269
|
+
function badNumberAt(v, path = '', seen = new Set()) {
|
|
270
|
+
if (typeof v === 'number') return Number.isFinite(v) ? null : { path, got: String(v) };
|
|
271
|
+
if (v === null || typeof v !== 'object' || seen.has(v)) return null;
|
|
272
|
+
seen.add(v);
|
|
273
|
+
const list = Array.isArray(v);
|
|
274
|
+
for (const k of Object.keys(v)) {
|
|
275
|
+
const bad = badNumberAt(v[k], list ? `${path}[${k}]` : path ? `${path}.${k}` : k, seen);
|
|
276
|
+
if (bad) return bad;
|
|
277
|
+
}
|
|
278
|
+
return null;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/**
|
|
282
|
+
* What a part's save() gave, once it passed what a save can hold; throws save-part-threw otherwise. Everything that keeps a part's data goes through here, so no path turns a number into null.
|
|
283
|
+
* @param {string} k
|
|
284
|
+
* @param {{ save(): any }} p
|
|
285
|
+
* @returns {any}
|
|
286
|
+
* @internal
|
|
287
|
+
*/
|
|
288
|
+
export function partData(k, p) {
|
|
289
|
+
const d = p.save();
|
|
290
|
+
// what JSON turns into null (read back as damage, so the whole save would never load again) or drops is not save data
|
|
291
|
+
if (typeof d === 'function' || typeof d === 'symbol' || (typeof d === 'number' && !Number.isFinite(d))) throw codedError('save-part-threw', fmt(DEV_STRINGS.notData, { k, got: String(d) }));
|
|
292
|
+
// a whole save is not given up for a field: the slot keeps its last good save, by name, the way a part whose save() threw does. A silent null reads back as hp null, position null
|
|
293
|
+
const bad = badNumberAt(d);
|
|
294
|
+
if (bad) throw codedError('save-part-threw', fmt(DEV_STRINGS.notNumber, { k, ...bad }));
|
|
295
|
+
return d;
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/** Collect every part: { data, failed: [[key, error]] }. Parts of the loaded save that no module owns are carried along. */
|
|
299
|
+
export function collectParts(s) {
|
|
300
|
+
const f = s._foreign, failed = [];
|
|
301
|
+
const data = { format: FORMAT, savedAt: Date.now(), versions: { ...f.versions }, parts: { ...f.parts } }; // wall-clock: real time of the save
|
|
302
|
+
for (const [k, p] of s.providers) {
|
|
303
|
+
// a part with nothing to save (save() returns null / undefined) is left out, so a null part in a save always means damage (readSave refuses it);
|
|
304
|
+
// loading a save without it keeps that part as it is (saves.load) or gives it its new-game state (session.load)
|
|
305
|
+
if (Object.hasOwn(f.parts, k)) continue; // data this part could not take when it joined (adoptPart): it rides along until a load replaces it
|
|
306
|
+
try {
|
|
307
|
+
const d = partData(k, p);
|
|
308
|
+
if (d == null) { delete data.parts[k]; delete data.versions[k]; } else { data.parts[k] = d; data.versions[k] = p.version; }
|
|
309
|
+
} catch (e) { failed.push([k, e]); delete data.parts[k]; delete data.versions[k]; }
|
|
310
|
+
}
|
|
311
|
+
return { data, failed };
|
|
312
|
+
}
|
|
@@ -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 '
|
|
5
|
-
import { coded } from '
|
|
6
|
-
import { fmt, warnOnce } from '
|
|
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) */
|
|
@@ -13,30 +13,35 @@ export const SAVE_STRINGS = {
|
|
|
13
13
|
'zh-CN': { 'saves.failed': '存档失败:{why}(之前的存档还在)', 'saves.badFile': '这不是有效的存档文件', 'saves.imported': '存档已导入到「{slot}」', 'saves.noSlot': '没有可导出的存档',
|
|
14
14
|
'saves.tooNew': '这个存档来自更新版本的游戏,无法读取(存档没有改动)', 'saves.corrupt': '这个存档已损坏,无法读取(存档没有改动)',
|
|
15
15
|
'saves.migrate': '这个存档的版本无法升级,无法读取(存档没有改动)',
|
|
16
|
-
'saves.otherTab': '没有存档:另一个标签页刚存过「{slot}」,为了不覆盖那边更新的进度,这里没有写入。读取它继续,或存到别的位置'
|
|
16
|
+
'saves.otherTab': '没有存档:另一个标签页刚存过「{slot}」,为了不覆盖那边更新的进度,这里没有写入。读取它继续,或存到别的位置',
|
|
17
|
+
'saves.otherTabKept': '没有删除:另一个标签页刚存过「{slot}」,那边更新的进度保留了' },
|
|
17
18
|
en: { 'saves.failed': 'Save failed: {why} (the previous save is kept)', 'saves.badFile': 'This is not a valid save file',
|
|
18
19
|
'saves.imported': 'Save imported into "{slot}"', 'saves.noSlot': 'Nothing to export',
|
|
19
20
|
'saves.tooNew': 'This save is from a newer version of the game and cannot be loaded (the save is unchanged)',
|
|
20
21
|
'saves.corrupt': 'This save is damaged and cannot be loaded (the save is unchanged)',
|
|
21
22
|
'saves.migrate': 'This save\'s version cannot be upgraded, so it cannot be loaded (the save is unchanged)',
|
|
22
|
-
'saves.otherTab': 'Not saved: another tab just saved "{slot}", so this one did not overwrite that newer progress. Load it to continue, or save to another slot'
|
|
23
|
+
'saves.otherTab': 'Not saved: another tab just saved "{slot}", so this one did not overwrite that newer progress. Load it to continue, or save to another slot',
|
|
24
|
+
'saves.otherTabKept': 'Not deleted: another tab just saved "{slot}", so that newer progress was kept' },
|
|
23
25
|
};
|
|
24
26
|
const MAX_BYTES = 512 * 1024 * 1024; // a bigger "save" is not one of ours; reading it would stall the tab
|
|
25
27
|
const STRINGS = {
|
|
26
28
|
badText: '[saves] import(text): not a save ({why}); nothing was imported',
|
|
27
29
|
bad: '[saves] importFile: not a save file ({why}); nothing was imported',
|
|
30
|
+
damaged: "[saves] exportFile: attachment '{g}/{id}' holds no data and was left out of the file",
|
|
28
31
|
attachment: '[saves] importFile: attachment {i} is not a data: URL with a string group and id; nothing was imported',
|
|
29
32
|
};
|
|
30
33
|
|
|
31
34
|
/** Blob -> data: URL (attachments are stored as text in the export file) */
|
|
32
35
|
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
36
|
|
|
34
|
-
/** data: URL -> Blob without the network; null when it is not a data: URL */
|
|
37
|
+
/** data: URL -> Blob without the network; null when it is not a readable data: URL */
|
|
35
38
|
function dataUrlBlob(url, type) {
|
|
36
39
|
const m = typeof url === 'string' && /^data:([^,]*?)(;base64)?,(.*)$/s.exec(url);
|
|
37
40
|
if (!m) return null;
|
|
38
|
-
|
|
39
|
-
|
|
41
|
+
try {
|
|
42
|
+
const bytes = m[2] ? Uint8Array.from(atob(m[3]), c => c.charCodeAt(0)) : new TextEncoder().encode(decodeURIComponent(m[3]));
|
|
43
|
+
return new Blob([bytes], { type: typeof type === 'string' ? type : m[1].split(';')[0] });
|
|
44
|
+
} catch { return null; } // a hand-edited file: bad base64 or a bad % escape
|
|
40
45
|
}
|
|
41
46
|
|
|
42
47
|
/**
|
|
@@ -52,12 +57,18 @@ export async function exportSaveFile(s, slot, { files = true } = {}) {
|
|
|
52
57
|
if (!json) { toast(s.engine, s.engine.t('saves.noSlot'), { kind: 'save' }); return false; }
|
|
53
58
|
await s.flush(); // wait for freshly saved attachments to finish writing
|
|
54
59
|
const list = [];
|
|
55
|
-
|
|
60
|
+
try {
|
|
61
|
+
if (files) for (const b of await s.store.blobs()) {
|
|
62
|
+
// a row damaged outside the engine must not cost the player the whole backup
|
|
63
|
+
if (b.blob instanceof Blob) list.push({ group: b.group, id: b.id, at: b.at, meta: b.meta, type: b.blob.type, url: await toDataURL(b.blob) });
|
|
64
|
+
else warnOnce(coded('save-write', fmt(STRINGS.damaged, { g: b.group, id: b.id })));
|
|
65
|
+
}
|
|
66
|
+
} catch (e) { s._fail(e ?? new Error('attachment unreadable'), slot); return false; }
|
|
56
67
|
// 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.
|
|
68
|
+
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
69
|
const blob = new Blob([head, json, ',"files":', JSON.stringify(list), '}'], { type: 'application/json' });
|
|
59
70
|
const a = document.createElement('a'), url = URL.createObjectURL(blob);
|
|
60
|
-
a.href = url; a.download = `${s.
|
|
71
|
+
a.href = url; a.download = `${s._prefix.replace(/-save-$/, '')}-${slot}-${new Date().toISOString().slice(0, 10)}.json`;
|
|
61
72
|
document.body.appendChild(a); a.click(); a.remove();
|
|
62
73
|
setTimeout(() => URL.revokeObjectURL(url), 10000); // presentation: release only after the browser has started the download
|
|
63
74
|
return true;
|
|
@@ -75,24 +86,23 @@ export async function importSaveFile(s, file, slot = 'imported') {
|
|
|
75
86
|
file ??= await pick();
|
|
76
87
|
if (!file) return null;
|
|
77
88
|
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
|
|
89
|
+
if (file.size > MAX_BYTES) return refuse(fmt(STRINGS.bad, { why: `${Math.round(file.size / 1e6)} MB` }));
|
|
79
90
|
let obj;
|
|
80
|
-
try { obj = JSON.parse(await file.text()); } catch (e) { return refuse(STRINGS.bad
|
|
81
|
-
if (obj?.threedog !== 'save') return refuse(STRINGS.bad
|
|
82
|
-
if ((obj.format ?? 1) > FILE_FORMAT) return refuse(STRINGS.bad
|
|
91
|
+
try { obj = JSON.parse(await file.text()); } catch (e) { return refuse(fmt(STRINGS.bad, { why: e.message })); }
|
|
92
|
+
if (obj?.threedog !== 'save') return refuse(fmt(STRINGS.bad, { why: 'no "threedog": "save" marker' }));
|
|
93
|
+
if ((obj.format ?? 1) > FILE_FORMAT) return refuse(fmt(STRINGS.bad, { why: `file format ${obj.format}, this build reads up to ${FILE_FORMAT}` }));
|
|
83
94
|
const blobs = [];
|
|
84
95
|
for (const [i, p] of (Array.isArray(obj.files) ? obj.files : []).entries()) {
|
|
85
96
|
const blob = typeof p?.group === 'string' && typeof p.id === 'string' ? dataUrlBlob(p.url, p.type) : null;
|
|
86
|
-
if (!blob) return refuse(STRINGS.attachment
|
|
97
|
+
if (!blob) return refuse(fmt(STRINGS.attachment, { i: String(i) }));
|
|
87
98
|
blobs.push([p, blob]);
|
|
88
99
|
}
|
|
89
|
-
const
|
|
90
|
-
if (
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
if (!ok) return null;
|
|
100
|
+
const bad = saveProblem(s, obj.data, slot);
|
|
101
|
+
if (bad) return refuse(fmt(STRINGS.bad, { why: bad }));
|
|
102
|
+
// attachments first and all at once: a failed write then leaves nothing, and only a stored file reaches the list
|
|
103
|
+
const rows = blobs.map(([p, blob]) => ({ group: p.group, id: p.id, blob, meta: p.meta ?? null, at: Number.isFinite(p.at) ? p.at : Date.now() })); // wall-clock: ordering, as putBlob
|
|
104
|
+
try { await s._enqueue(() => s.store.putBlobs(rows)); } catch (e) { s._fail(e); return null; }
|
|
105
|
+
if (!(await putImported(s, obj.data, slot))) return null; // a failed write already showed its toast
|
|
96
106
|
s.engine.events.emit('save:imported', slot);
|
|
97
107
|
toast(s.engine, s.engine.t('saves.imported', { slot }), { kind: 'save' });
|
|
98
108
|
return slot;
|
|
@@ -109,24 +119,21 @@ export async function importSaveFile(s, file, slot = 'imported') {
|
|
|
109
119
|
export async function importText(s, text, slot) {
|
|
110
120
|
let obj;
|
|
111
121
|
try { obj = JSON.parse(decodeURIComponent(escape(atob(String(text).trim())))); } catch (e) { warnOnce(coded('save-import', fmt(STRINGS.badText, { why: e.message }))); return false; }
|
|
112
|
-
const
|
|
113
|
-
if (
|
|
114
|
-
if (
|
|
115
|
-
|
|
122
|
+
const bad = saveProblem(s, obj, slot);
|
|
123
|
+
if (bad) { warnOnce(coded('save-import', fmt(STRINGS.badText, { why: bad }))); return false; }
|
|
124
|
+
if (!(await putImported(s, obj, slot))) return false; // a failed write already showed its toast
|
|
125
|
+
s.engine.events.emit('save:imported', slot);
|
|
126
|
+
return true;
|
|
116
127
|
}
|
|
117
|
-
/**
|
|
118
|
-
|
|
119
|
-
* @param {any} s the Saves instance
|
|
120
|
-
* @param {any} obj
|
|
121
|
-
* @param {string} slot
|
|
122
|
-
* @returns {Promise<true | string>}
|
|
123
|
-
* @internal
|
|
124
|
-
*/
|
|
125
|
-
async function importData(s, obj, slot) {
|
|
128
|
+
/** Why an imported save object is not one (checked like a load), or null. Too new / unmigratable saves are kept: a newer build can load them @internal */
|
|
129
|
+
function saveProblem(s, obj, slot) {
|
|
126
130
|
const r = readSave(obj, s.providers, slot);
|
|
127
|
-
|
|
131
|
+
return r.reason === 'corrupt' || r.reason === 'missing' ? r.dev : null;
|
|
132
|
+
}
|
|
133
|
+
/** Store a checked save object; false when the write failed. savedAt comes from outside: list() sorts by it @internal */
|
|
134
|
+
function putImported(s, obj, slot) {
|
|
128
135
|
const data = parseSave(obj);
|
|
129
|
-
return
|
|
136
|
+
return s._put(slot, JSON.stringify(data), Number.isFinite(data.savedAt) ? data.savedAt : 0);
|
|
130
137
|
}
|
|
131
138
|
|
|
132
139
|
/** Open a file picker; null when cancelled */
|
|
@@ -2,8 +2,8 @@
|
|
|
2
2
|
// format is the version of the envelope itself (FORMAT); a save from a newer format is refused as a whole, one without format is format 1.
|
|
3
3
|
// Each saves.register part carries its own version and migrate steps, so one module changing its format never touches the others; a part missing from versions is version 1.
|
|
4
4
|
// Everything here runs before a load touches the game, and on a copy: a refused load leaves the game and the stored save as they were.
|
|
5
|
-
import { codedError } from '
|
|
6
|
-
import { fmt } from '
|
|
5
|
+
import { codedError } from '../base/errorHints.js';
|
|
6
|
+
import { fmt } from '../base/validate.js';
|
|
7
7
|
|
|
8
8
|
/** Version of the save envelope. Raise it only when the envelope itself changes shape (never for a part's data: that is the part's own version). */
|
|
9
9
|
export const FORMAT = 1;
|
|
@@ -15,7 +15,6 @@ const DEV = {
|
|
|
15
15
|
'To read it, run the newer build, or raise this part\'s version (with migrate steps) to match.',
|
|
16
16
|
format: 'the save envelope is format {f}, this build reads up to format {max}',
|
|
17
17
|
corrupt: "[saves] not loaded: slot '{slot}' is not a readable save ({why}). Nothing was changed and the stored save is kept as it was.",
|
|
18
|
-
badMoved: "saves.register('{k}'): movedFrom is { oldPartName: data => newData }, e.g. movedFrom: { sky: d => ({ time: d.time, day: d.day }) }",
|
|
19
18
|
noStep: "save part '{k}' is version {from} but this build is version {to}, and migrate has no step {from}: add migrate: { {from}: data => newData } to saves.register('{k}')",
|
|
20
19
|
};
|
|
21
20
|
|
|
@@ -24,16 +23,13 @@ const DEV = {
|
|
|
24
23
|
* @param {string} key
|
|
25
24
|
* @param {number} version
|
|
26
25
|
* @param {Record<string, Function>} migrate
|
|
27
|
-
* @param {Record<string, Function> | null} [movedFrom]
|
|
28
26
|
* @returns {void}
|
|
29
27
|
* @internal
|
|
30
28
|
*/
|
|
31
|
-
export function checkPartVersion(key, version, migrate
|
|
29
|
+
export function checkPartVersion(key, version, migrate) {
|
|
32
30
|
if (!Number.isInteger(version) || version < 1) throw codedError('save-version', fmt(DEV.badVersion, { k: key, v: version }));
|
|
33
|
-
if (movedFrom != null && (typeof movedFrom !== 'object' || Object.values(movedFrom).some(f => typeof f !== 'function')))
|
|
34
|
-
throw codedError('save-version', fmt(DEV.badMoved, { k: key }));
|
|
35
31
|
for (const [m, fn] of Object.entries(migrate)) {
|
|
36
|
-
if (
|
|
32
|
+
if (!/^[1-9]\d*$/.test(m) || Number(m) >= version || typeof fn !== 'function') throw codedError('save-version', fmt(DEV.badMigrate, { k: key, m, v: version }));
|
|
37
33
|
}
|
|
38
34
|
}
|
|
39
35
|
|
|
@@ -48,6 +44,15 @@ const clean = (k, v) => (k === '__proto__' ? undefined : v);
|
|
|
48
44
|
*/
|
|
49
45
|
export function parseSave(json) { return JSON.parse(typeof json === 'string' ? json : JSON.stringify(json), clean); }
|
|
50
46
|
|
|
47
|
+
/**
|
|
48
|
+
* A part's saved version; one the table does not have is version 1. Part names are the game's: 'constructor' finds Object's own in a plain lookup, as `in` does on parts.
|
|
49
|
+
* @param {Record<string, number> | undefined} versions
|
|
50
|
+
* @param {string} k
|
|
51
|
+
* @returns {number}
|
|
52
|
+
* @internal
|
|
53
|
+
*/
|
|
54
|
+
export function partVersion(versions, k) { return versions && Object.hasOwn(versions, k) ? versions[k] : 1; }
|
|
55
|
+
|
|
51
56
|
/**
|
|
52
57
|
* Upgrade one part's data from its saved version to the current one, step by step (on a copy: the caller's save stays as it was).
|
|
53
58
|
* @param {string} key
|
|
@@ -77,7 +82,7 @@ export function upgradePart(key, p, data, from, save = { parts: {}, versions: {}
|
|
|
77
82
|
* every migrate step present. Returns the parsed save (prototype-safe), the upgraded registered parts (in load order) and the parts no registered module owns
|
|
78
83
|
* (kept, so a save does not lose them), or the reason the load is refused.
|
|
79
84
|
* @param {string | object | undefined} json the stored save text, or a save object
|
|
80
|
-
* @param {Map<string, { version: number, first: boolean, migrate: Record<string, Function
|
|
85
|
+
* @param {Map<string, { version: number, first: boolean, migrate: Record<string, Function> }>} providers
|
|
81
86
|
* @param {string} slot for the message only
|
|
82
87
|
* @returns {{ data: any, list: [string, any, any][], foreign: { parts: Record<string, any>, versions: Record<string, number>, whole: any } } | { reason: 'missing' | 'corrupt' | 'tooNew' | 'migrate', dev: string }}
|
|
83
88
|
* @internal
|
|
@@ -94,21 +99,17 @@ export function readSave(json, providers, slot) {
|
|
|
94
99
|
// (collectParts leaves out a part whose save() returns null / undefined), so only a hand edit or a broken file has it
|
|
95
100
|
const nul = Object.keys(data.parts).filter(k => data.parts[k] === null);
|
|
96
101
|
if (nul.length) return { reason: 'corrupt', dev: fmt(DEV.corrupt, { slot, why: `part${nul.length > 1 ? 's' : ''} ${nul.map(k => `'${k}'`).join(', ')} is null` }) };
|
|
97
|
-
|
|
98
|
-
// a part
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
versions[k] = p.version; delete data.parts[old]; delete versions[old];
|
|
106
|
-
}
|
|
107
|
-
const list = [...providers].filter(([k]) => k in data.parts).sort((a, b) => (b[1].first ? 1 : 0) - (a[1].first ? 1 : 0));
|
|
108
|
-
const newer = list.filter(([k, p]) => (versions[k] ?? 1) > p.version).map(([k, p]) => `part '${k}' is version ${versions[k]}, this build reads up to ${p.version}`);
|
|
102
|
+
// versions decide which migrate steps run: a value that is no whole number passes every comparison, so no step ran and load() got the old shape. Parts nobody owns here
|
|
103
|
+
// count too: a part registered later reads its version from this table. Only a missing table means version 1
|
|
104
|
+
const versions = data.versions === undefined ? (data.versions = {}) : data.versions;
|
|
105
|
+
if (!versions || typeof versions !== 'object' || Array.isArray(versions)) return { reason: 'corrupt', dev: fmt(DEV.corrupt, { slot, why: `versions ${JSON.stringify(versions)}` }) };
|
|
106
|
+
const odd = Object.keys(versions).filter(k => !Number.isInteger(versions[k]) || versions[k] < 1);
|
|
107
|
+
if (odd.length) return { reason: 'corrupt', dev: fmt(DEV.corrupt, { slot, why: `version of ${odd.map(k => `'${k}'`).join(', ')}` }) };
|
|
108
|
+
const list = [...providers].filter(([k]) => Object.hasOwn(data.parts, k)).sort((a, b) => (b[1].first ? 1 : 0) - (a[1].first ? 1 : 0));
|
|
109
|
+
const newer = list.filter(([k, p]) => partVersion(versions, k) > p.version).map(([k, p]) => `part '${k}' is version ${versions[k]}, this build reads up to ${p.version}`);
|
|
109
110
|
if (newer.length) return { reason: 'tooNew', dev: fmt(DEV.tooNew, { list: newer.join('; ') }) };
|
|
110
111
|
// whole: the save as read, for migrate steps that need another part (upgradePart); kept on foreign so a part registered later (adoptPart) sees it too
|
|
111
112
|
const whole = { parts: data.parts, versions }, foreign = { parts: {}, versions: {}, whole };
|
|
112
|
-
for (const k of Object.keys(data.parts)) if (!providers.has(k)) { foreign.parts[k] = data.parts[k]; foreign.versions[k] = versions
|
|
113
|
-
try { return { data, foreign, list: list.map(([k, p]) => [k, p, upgradePart(k, p, data.parts[k], versions
|
|
113
|
+
for (const k of Object.keys(data.parts)) if (!providers.has(k)) { foreign.parts[k] = data.parts[k]; foreign.versions[k] = partVersion(versions, k); }
|
|
114
|
+
try { return { data, foreign, list: list.map(([k, p]) => [k, p, upgradePart(k, p, data.parts[k], partVersion(versions, k), whole)]) }; } catch (e) { return { reason: 'migrate', dev: e.message }; }
|
|
114
115
|
}
|