threedog 1.0.1 → 1.2.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 +90 -0
- package/README.md +1 -1
- package/core/assets/Animator.js +41 -3
- package/core/assets/Assets.js +100 -24
- package/core/assets/assetEntry.js +73 -20
- package/core/assets/assetHot.js +68 -16
- package/core/assets/assetLoad.js +6 -6
- package/core/assets/assetLod.js +9 -2
- package/core/assets/assetManifest.js +12 -2
- package/core/assets/assetPart.js +54 -0
- package/core/assets/ik.js +271 -0
- package/core/assets/modelNeeds.js +37 -0
- package/core/assets/namedModel.js +102 -29
- package/core/assets/nodeVisibility.js +15 -0
- package/core/audio/Audio.js +36 -4
- package/core/audio/audioReverb.js +99 -0
- package/core/audio/audioRules.js +1 -1
- package/core/audio/audioVoice.js +1 -1
- package/core/base/Events.js +14 -4
- package/core/base/Random.js +1 -1
- package/core/base/Vars.js +1 -1
- package/core/base/docRef.js +51 -0
- package/core/base/errorCodes.js +178 -126
- package/core/base/errorHints.js +9 -7
- package/core/base/errors.js +25 -10
- package/core/base/events.generated.js +2 -0
- package/core/base/freeParts.js +76 -0
- package/core/base/math.js +28 -0
- package/core/base/sections.js +5 -5
- package/core/base/validate.js +31 -3
- package/core/engine/Engine.js +16 -6
- package/core/engine/Loading.js +5 -3
- package/core/engine/copies.js +1 -1
- package/core/engine/headlessLoad.js +4 -1
- package/core/engine/lifecycle.js +32 -16
- package/core/engine/loop.js +71 -27
- package/core/engine/moduleSlots.js +2 -2
- package/core/engine/moduleTypes.js +3 -3
- package/core/engine/modules.js +65 -39
- package/core/engine/page.js +6 -3
- package/core/engine/services.js +6 -5
- package/core/engine/startup.js +5 -5
- package/core/input/Input.js +28 -14
- package/core/input/inputContext.js +28 -16
- package/core/input/inputKeyboard.js +31 -3
- package/core/input/inputPad.js +4 -0
- package/core/input/inputPointer.js +2 -1
- package/core/input/inputSeat.js +1 -1
- package/core/inspect/Budget.js +109 -19
- package/core/inspect/DebugOverrides.js +28 -4
- package/core/inspect/Describe.js +17 -9
- package/core/inspect/Inspect.js +4 -2
- package/core/inspect/InspectMaterials.js +3 -1
- package/core/inspect/InspectPerf.js +19 -9
- package/core/inspect/InspectScene.js +32 -7
- package/core/inspect/MaterialInfo.js +19 -2
- package/core/inspect/UrlState.js +46 -27
- package/core/inspect/catalog.js +28 -9
- package/core/inspect/debugView.js +2 -1
- package/core/inspect/describeRender.js +25 -13
- package/core/inspect/describeText.js +14 -6
- package/core/inspect/lightWatch.js +1 -1
- package/core/inspect/metadata.generated.js +35 -17
- package/core/inspect/pictureChecks.js +148 -0
- package/core/inspect/pictureMenu.js +84 -0
- package/core/inspect/pictureWriters.js +26 -6
- package/core/inspect/textureBytes.js +12 -2
- package/core/inspect/toolDoor.js +2 -4
- package/core/ops/Ops.js +11 -4
- package/core/ops/holds.js +27 -10
- package/core/ops/opsAtomic.js +15 -7
- package/core/ops/opsGuard.js +2 -2
- package/core/ops/opsRun.js +8 -7
- package/core/ops/sharedPoint.js +72 -21
- package/core/ops/stacks.js +56 -16
- package/core/saves/SaveStore.js +9 -3
- package/core/saves/Saves.js +32 -23
- package/core/saves/saveApply.js +96 -44
- package/core/saves/saveIds.js +1 -1
- package/core/saves/saveVersions.js +7 -5
- package/core/saves/session.js +17 -8
- package/core/saves/stateReplace.js +34 -15
- package/core/scene/Rays.js +52 -10
- package/core/scene/Views.js +13 -7
- package/core/scene/adaptive.js +144 -21
- package/core/scene/drawOnly.js +17 -0
- package/core/scene/gameLights.js +44 -3
- package/core/scene/sceneMethods.js +13 -11
- package/core/scene/stepPoses.js +11 -3
- package/core/scene/targeting.js +5 -3
- package/core/scene/thingOps.js +1 -1
- package/core/scene/tier.js +15 -0
- package/core/stream/Batching.js +30 -7
- package/core/stream/Stream.js +26 -7
- package/core/stream/batchGroups.js +2 -2
- package/core/stream/chunkStream.js +7 -5
- package/core/stream/prepare.js +77 -0
- package/core/time/skip.js +3 -1
- package/core/time/time.js +4 -2
- package/docs/AI.md +82 -83
- package/docs/API.md +16 -16
- package/docs/CODEMAP.md +16 -11
- package/docs/COMMANDS.md +31 -33
- package/docs/CONVENTIONS.md +37 -49
- package/docs/MIGRATING-0.8.md +2 -2
- package/docs/MIGRATING-1.0.md +2 -2
- package/docs/THREE.md +28 -35
- package/docs/api/assets.md +3 -1
- package/docs/api/audio.md +4 -2
- package/docs/api/budget.md +5 -0
- package/docs/api/cameraRig.md +2 -2
- package/docs/api/characters.md +10 -8
- package/docs/api/collision.md +6 -4
- package/docs/api/engine.md +16 -16
- package/docs/api/events.md +3 -2
- package/docs/api/ground.md +6 -5
- package/docs/api/hud.md +4 -2
- package/docs/api/input.md +5 -5
- package/docs/api/particles.md +2 -1
- package/docs/api/photo.md +3 -0
- package/docs/api/post.md +7 -4
- package/docs/api/quests.md +2 -2
- package/docs/api/rays.md +1 -2
- package/docs/api/saves.md +7 -7
- package/docs/api/settings.md +2 -2
- package/docs/api/tools.md +3 -1
- package/docs/api/vars.md +1 -1
- package/docs/api/vegetation.md +4 -2
- package/docs/api/world.md +1 -1
- package/docs/recipes/01-new-game.md +16 -17
- package/docs/recipes/02-npc.md +22 -18
- package/docs/recipes/03-items-pickups.md +37 -35
- package/docs/recipes/04-quests.md +15 -10
- package/docs/recipes/05-props-bake.md +101 -95
- package/docs/recipes/06-clock-events.md +28 -28
- package/docs/recipes/07-flow-scenes-pause.md +29 -26
- package/docs/recipes/08-weather-sky.md +52 -64
- package/docs/recipes/09-materials-lights-models.md +26 -17
- package/docs/recipes/10-blender-level.md +15 -10
- package/docs/recipes/11-vehicles.md +12 -7
- package/docs/recipes/12-navmesh.md +44 -26
- package/docs/recipes/13-animation.md +56 -45
- package/docs/recipes/14-custom-module.md +21 -18
- package/docs/recipes/15-perf.md +61 -55
- package/docs/recipes/16-dev-bridge.md +23 -33
- package/docs/recipes/18-world.md +36 -42
- package/docs/recipes/19-shooting-picking.md +20 -15
- package/docs/recipes/20-content-actions-save.md +48 -56
- package/docs/recipes/21-camera.md +45 -54
- package/docs/recipes/22-shop-gold.md +12 -7
- package/docs/recipes/23-ops.md +25 -23
- package/docs/recipes/26-ui-parts.md +67 -47
- package/docs/recipes/27-net.md +12 -7
- package/docs/recipes/28-terrain.md +24 -21
- package/docs/recipes/29-grid.md +32 -27
- package/docs/recipes/30-templates.md +21 -20
- package/docs/recipes/31-audio.md +39 -22
- package/docs/recipes/32-action-game.md +19 -14
- package/docs/recipes/33-stream-sources.md +15 -11
- package/docs/recipes/34-environment-lighting.md +126 -70
- package/docs/recipes/35-picture-from-reference.md +8 -8
- package/docs/recipes/36-ground-plants.md +27 -21
- package/docs/recipes/40-scene.md +19 -28
- package/docs/recipes/43-shader-patches-surfaces.md +15 -12
- package/docs/recipes/44-water-weather-hooks.md +34 -31
- package/docs/recipes/45-cascaded-shadows.md +35 -26
- package/docs/recipes/46-blender-art-route.md +6 -1
- package/docs/recipes/49-game-module-contract.md +13 -8
- package/docs/recipes/50-own-renderer.md +6 -2
- package/docs/recipes/51-capability-catalog.md +15 -8
- package/docs/recipes/52-around-the-picture.md +34 -32
- package/docs/recipes/53-ground-up-close.md +6 -1
- package/docs/recipes/55-mods-time-wrap.md +27 -19
- package/docs/recipes/56-webgpu-tsl.md +74 -43
- package/docs/recipes/57-control.md +18 -13
- package/docs/recipes/58-input.md +26 -16
- package/docs/recipes/59-depth-post-effects.md +8 -3
- package/docs/recipes/60-judge-the-picture.md +9 -8
- package/docs/recipes/61-deploy.md +5 -0
- package/docs/recipes/62-picture-code.md +70 -79
- package/docs/recipes/63-third-person-start.md +47 -45
- package/docs/recipes/64-particles.md +22 -10
- package/docs/recipes/65-swarm.md +18 -13
- package/docs/recipes/66-common-tasks.md +38 -35
- package/examples/action/GAMEMAP.md +2 -3
- package/examples/action/main.js +3 -3
- package/examples/action/picture/lights.js +3 -1
- package/examples/perf-island/GAMEMAP.md +3 -3
- package/examples/perf-island/picture/lights.js +2 -1
- package/examples/plain-picture/GAMEMAP.md +1 -1
- package/examples/rc2d/GAMEMAP.md +1 -1
- package/examples/styletest/GAMEMAP.md +2 -2
- package/examples/styletest/main.js +1 -1
- package/examples/techniques/interior-light/README.md +3 -3
- package/examples/techniques/interior-light/interiorLight.js +2 -4
- package/examples/techniques/interior-light/picture/lights.js +2 -1
- package/examples/techniques/modular-building/picture/lights.js +3 -1
- package/examples/techniques/outlines-and-rim/picture/lights.js +3 -1
- package/examples/techniques/procedural-animation/README.md +1 -1
- package/examples/techniques/procedural-animation/main.js +1 -1
- package/examples/webgpu-tsl/GAMEMAP.md +1 -1
- package/examples/world/GAMEMAP.md +2 -3
- package/examples/world/art/humanoid.js +1 -1
- package/examples/world/main.js +6 -3
- package/index.d.ts +2 -2
- package/llms.txt +101 -0
- package/modules/ambience/Ambience.js +21 -5
- package/modules/calendar/index.js +9 -5
- package/modules/calendar/schedule.js +23 -8
- package/modules/camera/FirstPersonCamera.js +3 -1
- package/modules/camera/FollowCamera.js +10 -5
- package/modules/camera/RtsCamera.js +4 -3
- package/modules/camera/common.js +70 -8
- package/modules/camera/contract.js +1 -1
- package/modules/characters/Character.js +16 -10
- package/modules/characters/NPC.js +31 -19
- package/modules/characters/assetModel.js +14 -9
- package/modules/characters/astar.js +6 -1
- package/modules/characters/contract.js +2 -2
- package/modules/characters/index.js +34 -22
- package/modules/characters/movers/manual.js +1 -1
- package/modules/characters/movers/rapier.js +17 -2
- package/modules/characters/movers/simple.js +1 -1
- package/modules/characters/movers/support.js +16 -7
- package/modules/characters/npcAvoid.js +2 -2
- package/modules/characters/npcSim.js +3 -2
- package/modules/characters/pathAsync.js +24 -8
- package/modules/characters/pathJob.js +1 -1
- package/modules/characters/player.js +10 -9
- package/modules/characters/playerStrings.js +5 -5
- package/modules/characters/proceduralRig.js +5 -5
- package/modules/characters/useModel.js +6 -0
- package/modules/characters/walkTo.js +1 -1
- package/modules/collision/Collision.js +29 -18
- package/modules/collision/grid.js +22 -4
- package/modules/content/index.js +3 -1
- package/modules/content/loader.js +1 -1
- package/modules/content/models.js +82 -33
- package/modules/content/props.js +2 -1
- package/modules/content/rules.js +11 -5
- package/modules/content/templates.js +3 -3
- package/modules/content/words.js +2 -2
- package/modules/debug/DebugPanel.js +9 -9
- package/modules/flow/index.js +9 -6
- package/modules/gameplay/Dialogue.js +34 -20
- package/modules/gameplay/Interactions.js +19 -15
- package/modules/gameplay/Inventory.js +9 -4
- package/modules/gameplay/Quests.js +12 -10
- package/modules/gameplay/pickups.js +23 -11
- package/modules/grid/index.js +1 -1
- package/modules/grid/preview.js +2 -2
- package/modules/grid/tiles.js +1 -1
- package/modules/hlod/index.js +4 -1
- package/modules/hud/index.js +47 -10
- package/modules/hud/parts.js +28 -9
- package/modules/level/geometry.js +8 -3
- package/modules/level/index.js +10 -5
- package/modules/level/load.js +4 -2
- package/modules/lights/sources.js +1 -1
- package/modules/music/Music.js +22 -4
- package/modules/nav/index.js +20 -10
- package/modules/particles/Particles.js +31 -14
- package/modules/particles/effect.js +20 -5
- package/modules/particles/lit.js +72 -0
- package/modules/photo/Photo.js +72 -28
- package/modules/photo/pathTrace.js +106 -0
- package/modules/rigid/RigidBodies.js +23 -14
- package/modules/rigid/Vehicles.js +3 -13
- package/modules/rigid/sync.js +2 -1
- package/modules/settings/Settings.js +52 -20
- package/modules/settings/apply.js +23 -9
- package/modules/settings/sections.js +39 -6
- package/modules/settings/strings.js +2 -0
- package/modules/settings/view.js +19 -3
- package/modules/sky/dome.js +15 -3
- package/modules/sky/environment.js +28 -12
- package/modules/sky/fog.js +1 -1
- package/modules/sky/frame.js +6 -1
- package/modules/sky/shader.js +4 -3
- package/modules/sky/skyModule.js +8 -4
- package/modules/swarm/Swarm.js +1 -1
- package/modules/terrain/ChunkManager.js +61 -15
- package/modules/terrain/chunkJob.js +2 -2
- package/modules/terrain/index.js +20 -5
- package/modules/terrain/terrainEdit.js +8 -4
- package/modules/terrain/terrainTexture.js +4 -2
- package/modules/timeline/Timeline.js +4 -3
- package/modules/timeline/Tween.js +3 -0
- package/modules/timeline/letterbox.js +1 -0
- package/modules/triggers/index.js +36 -17
- package/modules/vegetation/Vegetation.js +81 -19
- package/modules/vegetation/densityMap.js +13 -8
- package/modules/vegetation/draw.js +147 -24
- package/modules/vegetation/groundChunks.js +20 -5
- package/modules/vegetation/index.js +3 -3
- package/modules/vegetation/modelGeometry.js +9 -4
- package/modules/water/Water.js +11 -8
- package/modules/weather/Weather.js +7 -2
- package/modules/weather/shaders.js +25 -5
- package/modules/weather/weatherDraw.js +20 -6
- package/modules/world/World.js +2 -1
- package/modules/world/index.js +2 -2
- package/modules/world/persist.js +6 -2
- package/modules/world/views.js +15 -2
- package/package.json +4 -1
- package/presets.js +5 -5
- package/render/PostFX.js +84 -41
- package/render/backend.js +137 -16
- package/render/cascades.js +3 -1
- package/render/cascades.tsl.js +2 -0
- package/render/daylight.js +7 -1
- package/render/detail.js +7 -4
- package/render/effects.js +27 -8
- package/render/fogLook.js +24 -0
- package/render/fuse.js +5 -2
- package/render/fx/detail.tsl.js +9 -7
- package/render/fx/index.js +7 -2
- package/render/fx/library.tsl.js +1 -0
- package/render/fx/lightShaft.tsl.js +114 -0
- package/render/fx/noise.tsl.js +25 -8
- package/render/fx/objectOrigin.tsl.js +39 -10
- package/render/fx/particles.tsl.js +23 -6
- package/render/fx/patchNodes.tsl.js +17 -12
- package/render/fx/pcss.tsl.js +51 -0
- package/render/fx/postWebGPU.tsl.js +89 -29
- package/render/fx/sky.tsl.js +3 -9
- package/render/fxNumbers.js +10 -4
- package/render/impostor.tsl.js +107 -0
- package/render/lighting.js +33 -1
- package/render/lightmap.js +42 -28
- package/render/lights.js +19 -3
- package/render/materials.js +6 -4
- package/render/mergeCommon.js +4 -1
- package/render/occlusion.js +14 -4
- package/render/patches.js +79 -41
- package/render/postRuns.js +32 -0
- package/render/postWebGL.js +97 -10
- package/render/probes.js +10 -14
- package/render/shaderErrors.js +2 -1
- package/render/shadowCache.tsl.js +33 -5
- package/render/shadows.js +42 -16
- package/render/slots.js +8 -5
- package/render/vertexInputs.js +52 -0
- package/types/core.d.ts +114 -46
- package/types/gameplay.d.ts +56 -23
- package/types/generated/core/audio/Audio.d.ts +27 -1
- package/types/generated/core/base/Random.d.ts +1 -1
- package/types/generated/core/input/Input.d.ts +6 -8
- package/types/generated/core/input/inputSeat.d.ts +1 -1
- package/types/generated/core/inspect/Budget.d.ts +26 -0
- package/types/generated/core/inspect/DebugOverrides.d.ts +0 -2
- package/types/generated/core/saves/Saves.d.ts +10 -7
- package/types/generated/core/saves/session.d.ts +8 -2
- package/types/generated/core/scene/Rays.d.ts +1 -3
- package/types/generated/modules/particles/Particles.d.ts +1 -1
- package/types/generated/modules/world/World.d.ts +2 -1
- package/types/generated/render/PostFX.d.ts +35 -9
- package/types/physics.d.ts +43 -11
- package/types/pixel.d.ts +1 -1
- package/types/tsl.d.ts +62 -1
- package/types/world.d.ts +12 -3
- package/ui/Focus.js +7 -5
- package/ui/Parts.js +1 -1
- package/ui/touchPart.js +6 -3
package/core/saves/saveApply.js
CHANGED
|
@@ -12,7 +12,7 @@
|
|
|
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
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
14
|
import { toast } from '../../ui/UI.js';
|
|
15
|
-
import { fmt, warnOnce } from '../base/validate.js';
|
|
15
|
+
import { fmt, warnOnce, isThenable, syncOnly } from '../base/validate.js';
|
|
16
16
|
import { reportError } from '../base/errors.js';
|
|
17
17
|
import { codedError, coded } from '../base/errorHints.js';
|
|
18
18
|
import { FORMAT, readSave, parseSave, upgradePart, partVersion } from './saveVersions.js';
|
|
@@ -23,6 +23,7 @@ const DEV_STRINGS = {
|
|
|
23
23
|
partAt: "load() of save part '{k}'", adoptAt: "load() of save part '{k}' (registered after the save was loaded)",
|
|
24
24
|
rollback: "rollback of save part '{k}' after a failed load (that part may be half-loaded; the other parts rolled back)",
|
|
25
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
|
+
changed: "save part '{k}' was unloaded or replaced while '{slot}' was loading, so its data had nobody to take it; the load failed and rolled back (the data stays in the save)",
|
|
26
27
|
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
28
|
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
29
|
listener: 'a listener of event {name} threw while the part loaded: {msg}',
|
|
@@ -44,45 +45,57 @@ const loadError = (k, err, slot) => Object.assign(codedError('save-load-threw',
|
|
|
44
45
|
* @internal
|
|
45
46
|
*/
|
|
46
47
|
export function applySave(s, data, slot) {
|
|
48
|
+
return marked(s, () => {
|
|
49
|
+
const r = readSave(data, s.providers, slot);
|
|
50
|
+
if ('reason' in r) {
|
|
51
|
+
if (r.reason !== 'missing') { warnOnce(coded('save-refused', r.dev)); // handled: the player is told, nothing changed
|
|
52
|
+
toast(s.engine, s.engine.t('saves.' + r.reason), { kind: 'error', ms: 5000 }); }
|
|
53
|
+
return false;
|
|
54
|
+
}
|
|
55
|
+
return applyRead(s, r, slot, false);
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** fn under the marker, from its first line until what it returned settled (top of stateReplace.js) */
|
|
60
|
+
function marked(s, fn) {
|
|
47
61
|
const q = s._replace, job = q.job;
|
|
48
62
|
q.begin();
|
|
49
63
|
let out;
|
|
50
|
-
try { out =
|
|
64
|
+
try { out = fn(); } catch (err) { q.end(); throw err; }
|
|
51
65
|
if (typeof out !== 'boolean') return out.finally(() => q.endOf(job));
|
|
52
66
|
q.end();
|
|
53
67
|
return out;
|
|
54
68
|
}
|
|
55
69
|
|
|
56
|
-
/**
|
|
57
|
-
|
|
58
|
-
|
|
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
|
-
}
|
|
70
|
+
/** Apply parts already read and migrated (r.list): the one part-application protocol. late: one part registered after its save was loaded (adoptPart);
|
|
71
|
+
* it adds to the state instead of replacing it, so the parts nobody owns, background results and the saved-state generation stay, and only that part rolls back */
|
|
72
|
+
function applyRead(s, r, slot, late) {
|
|
64
73
|
const e = s.engine, foreign0 = s._foreign;
|
|
65
74
|
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; }
|
|
75
|
+
try { before = rollbackPoint(s, slot, r.list, late); } catch (err) { reportError(e, err, `saves.apply('${slot}')`); return false; }
|
|
67
76
|
const ev = e.events, scope = []; // this load's capture scope: listener errors from now until the load settled (top of the file)
|
|
68
77
|
ev._scopes.push(scope);
|
|
69
78
|
const settled = () => { const i = ev._scopes.lastIndexOf(scope); if (i >= 0) ev._scopes.splice(i, 1); };
|
|
70
79
|
let out;
|
|
71
|
-
try { out = applyParts(s, e, r, slot, before, foreign0, scope); } catch (err) { settled(); throw err; }
|
|
80
|
+
try { out = applyParts(s, e, r, slot, before, foreign0, scope, late); } catch (err) { settled(); throw err; }
|
|
72
81
|
if (typeof out !== 'boolean') return out.finally(settled);
|
|
73
82
|
settled();
|
|
74
83
|
return out;
|
|
75
84
|
}
|
|
76
85
|
|
|
77
86
|
/** 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
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
87
|
+
function applyParts(s, e, r, slot, before, foreign0, scope, late) {
|
|
88
|
+
const q = s._replace, turn = q.job.turn, generation = q.generation;
|
|
89
|
+
let keepResults = () => {};
|
|
90
|
+
if (!late) {
|
|
91
|
+
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
|
|
92
|
+
q.generation++; q.changed();
|
|
93
|
+
s._foreign = r.foreign;
|
|
94
|
+
}
|
|
95
|
+
const reached = new Set();
|
|
84
96
|
const fail = err => {
|
|
85
|
-
keepResults();
|
|
97
|
+
keepResults();
|
|
98
|
+
if (!late) { q.generation = generation; q.changed(true); } // the old world stays, and what it was waiting for with it
|
|
86
99
|
// 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
100
|
// 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
101
|
const refused = err?.cause?.code === 'save-bad-record';
|
|
@@ -91,12 +104,11 @@ function applyParts(s, e, r, slot, before, foreign0, scope) {
|
|
|
91
104
|
s._foreign = foreign0;
|
|
92
105
|
const back = readSave(before, s.providers, '(rollback)');
|
|
93
106
|
// every part reloads its pre-load state; a part that throws again is reported (once) and the rest still roll back
|
|
94
|
-
const
|
|
95
|
-
const undone = 'list' in back ? e.ops.allow(() => runParts(s, back.list, '(rollback)', scope, onPart)) : true;
|
|
107
|
+
const undone = 'list' in back ? e.ops.allow(() => runParts(s, back.list, '(rollback)', scope, onRollback(e), turn)) : true;
|
|
96
108
|
// 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('
|
|
109
|
+
for (const [k] of r.list) if (reached.has(k) && !Object.hasOwn(before.parts, k) && !(refused && k === err.part)) reportError(e, codedError('rollback-incomplete', fmt(DEV_STRINGS.noRollback, { k })), `saves.apply('${slot}')`);
|
|
98
110
|
// 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; };
|
|
111
|
+
const failed = () => { if (!e.session._busy && !late) e.events.emit('session:failed', { kind: 'quick', slot }); return false; };
|
|
100
112
|
if (undone === true) return failed();
|
|
101
113
|
q.hold(); // a rollback that waits on an async part holds gameplay too, whichever way the load failed
|
|
102
114
|
return undone.then(failed);
|
|
@@ -109,7 +121,7 @@ function applyParts(s, e, r, slot, before, foreign0, scope) {
|
|
|
109
121
|
return hooks === true ? true : hooks.then(() => true, fail);
|
|
110
122
|
};
|
|
111
123
|
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)
|
|
124
|
+
try { out = e.ops.allow(() => runParts(s, r.list, slot, scope, null, turn, reached)); } catch (err) { return fail(err); } // loading writes state outside ops on purpose (guard allows it)
|
|
113
125
|
if (out === true) return partsDone();
|
|
114
126
|
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
127
|
return out.then(partsDone, fail);
|
|
@@ -118,8 +130,9 @@ function applyParts(s, e, r, slot, before, foreign0, scope) {
|
|
|
118
130
|
/** The rollback point: every part's save(), copied so a load() writing into the object its save() returned cannot change it.
|
|
119
131
|
* A part whose data cannot be copied throws (save-part-threw): without a true copy a failed load could not be undone.
|
|
120
132
|
* 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) {
|
|
133
|
+
function rollbackPoint(s, slot, list, late) {
|
|
122
134
|
const data = s._collect().data, S = s.engine.session, base = S._base ? S._baseData() : { parts: {}, versions: {} };
|
|
135
|
+
if (late) for (const k of Object.keys(data.parts)) if (!list.some(([n]) => n === k)) { delete data.parts[k]; delete data.versions[k]; } // only the late part loads, so only it goes back
|
|
123
136
|
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
137
|
for (const k of Object.keys(data.parts)) {
|
|
125
138
|
try { data.parts[k] = structuredClone(data.parts[k]); }
|
|
@@ -149,23 +162,44 @@ function callLoad(s, fn, scope) {
|
|
|
149
162
|
}
|
|
150
163
|
|
|
151
164
|
/**
|
|
152
|
-
*
|
|
153
|
-
*
|
|
165
|
+
* The one loop that calls a part's load(): a load, its rollback, a late part, an atomic op's rollback. Parts load in order; a part returning a Promise makes
|
|
166
|
+
* the rest wait for it, except with sync (an atomic op's rollback): there a Promise is refused as at the other sync-only sites (syncOnly), reported, and the
|
|
167
|
+
* next part loads at once. That rollback has to be whole before the op returns: the outer op of a nested failure goes on, commits and runs its after hooks
|
|
168
|
+
* right after, and a part load still pending would then write the old value over it, its change events past the mute. A failing part throws (or rejects) with the part named, unless onFail is given (rollback): then onFail(err) is called and the next
|
|
169
|
+
* part loads anyway. A part whose provider is no longer the one registered under its key (its module unloaded or replaced while an earlier part awaited)
|
|
170
|
+
* cannot take the data read for that provider (review l2 #4): the load fails with save-provider-changed and rolls back, a rollback reports it and goes on. turn: the replacement's identity for load(); none outside one (an atomic op's rollback).
|
|
154
171
|
*/
|
|
155
|
-
function runParts(s, list, slot, scope, onFail =
|
|
156
|
-
const failed = (k, err) => { const er = loadError(k, err, slot); if (!onFail) throw er; onFail(er); }
|
|
172
|
+
function runParts(s, list, slot, scope, onFail, turn, reached, sync = false) {
|
|
173
|
+
const failed = (k, err, own) => { const er = own ? Object.assign(own, { part: k }) : loadError(k, err, slot); if (!onFail) throw er; onFail(er); };
|
|
157
174
|
const step = i => {
|
|
158
175
|
for (; i < list.length; i++) {
|
|
159
176
|
const [k, p, d] = list[i];
|
|
177
|
+
if (s.providers.get(k) !== p) { failed(k, null, codedError('save-provider-changed', fmt(DEV_STRINGS.changed, { k, slot }))); continue; } // a rollback reports it and goes on; a load fails and rolls back
|
|
160
178
|
let r;
|
|
179
|
+
reached?.add(k); // a part that started loading may hold half of the new data; one never reached holds nothing of it
|
|
161
180
|
try { r = callLoad(s, () => p.load(d, turn), scope); } catch (err) { failed(k, err); continue; }
|
|
162
|
-
if (r
|
|
181
|
+
if (!isThenable(r)) continue;
|
|
182
|
+
if (sync) { try { syncOnly(r, `save part '${k}' load() in ${slot}`, true); } catch (err) { failed(k, null, err); } continue; }
|
|
183
|
+
return r.then(() => step(i + 1), err => { failed(k, err); return step(i + 1); });
|
|
163
184
|
}
|
|
164
185
|
return true;
|
|
165
186
|
};
|
|
166
187
|
return step(0);
|
|
167
188
|
}
|
|
168
189
|
|
|
190
|
+
/** A rollback goes past a part that throws again: reported once (a gameplay error: engine.error / engine:error, not soft, an incomplete rollback is a broken state), and the rest still go back */
|
|
191
|
+
const onRollback = e => er => reportError(e, er, fmt(DEV_STRINGS.rollback, { k: er.part }));
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* Put plain part data back outside a load (an atomic op's rollback, core/ops/opsAtomic.js): the same loop, past a part that throws, synchronous only:
|
|
195
|
+
* a part whose load() returns a Promise is reported (engine-misuse) and not waited for. A normal load keeps waiting for async parts.
|
|
196
|
+
* @param {any} s the Saves instance
|
|
197
|
+
* @param {[string, any, any][]} list
|
|
198
|
+
* @param {string} where
|
|
199
|
+
* @internal
|
|
200
|
+
*/
|
|
201
|
+
export const restoreParts = (s, list, where) => { runParts(s, list, where, [], onRollback(s.engine), undefined, undefined, true); };
|
|
202
|
+
|
|
169
203
|
/**
|
|
170
204
|
* 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
205
|
* 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
|
|
@@ -174,21 +208,34 @@ function runParts(s, list, slot, scope, onFail = null) {
|
|
|
174
208
|
* @param {string} key
|
|
175
209
|
* @internal
|
|
176
210
|
*/
|
|
177
|
-
export function adoptPart(s, key) {
|
|
178
|
-
const f = s._foreign, q = s._replace, where = fmt(DEV_STRINGS.adoptAt, { k: key });
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
211
|
+
export function adoptPart(s, key, part) {
|
|
212
|
+
const f = s._foreign, q = s._replace, where = fmt(DEV_STRINGS.adoptAt, { k: key }), L = s.engine.loading;
|
|
213
|
+
// engine.loading.settled() waits for it: use(mod); await loading.settled() says the module runs with its data back, and gameplay is no longer held for it.
|
|
214
|
+
// Its own set, not the inits': a failed replaces tells module:restored once the inits are done, and its content must land on the line after use() threw
|
|
215
|
+
L._track(q.run(null, () => {
|
|
216
|
+
// the provider this data was kept for: one removed meanwhile, or another under the same key, does not get it (review l2 #4)
|
|
217
|
+
if (s._foreign !== f || s.providers.get(key) !== part || !Object.hasOwn(f.parts, key)) return;
|
|
182
218
|
const d = f.parts[key], v = f.versions[key] ?? 1;
|
|
183
219
|
delete f.parts[key]; delete f.versions[key];
|
|
184
220
|
// 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
|
|
221
|
+
const back = () => { if (s._foreign === f && !Object.hasOwn(f.parts, key)) { f.parts[key] = d; f.versions[key] = v; } };
|
|
222
|
+
let list;
|
|
186
223
|
try {
|
|
187
|
-
if (v >
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
224
|
+
if (v > part.version) throw codedError('save-refused', `save part '${key}' is version ${v}, this build reads up to ${part.version}`);
|
|
225
|
+
list = [[key, part, upgradePart(key, part, d, v, f.whole)]];
|
|
226
|
+
} catch (err) {
|
|
227
|
+
back();
|
|
228
|
+
if (err?.code === 'save-refused') warnOnce(err.message); // handled like an ordinary load's version refusal: newer data kept, nothing reported as an engine error
|
|
229
|
+
else reportError(s.engine, err, where);
|
|
230
|
+
return;
|
|
231
|
+
}
|
|
232
|
+
// the protocol of a load: marker, freeze while it waits, a rollback point of this part, afterLoad. Called bare, ops and fixed steps would read a half-loaded part
|
|
233
|
+
part.adopting = true; // a remove() meanwhile keeps this data, not the half-loaded state (Saves.define)
|
|
234
|
+
const done = ok => { part.adopting = false; if (!ok) back(); return ok; };
|
|
235
|
+
let out;
|
|
236
|
+
try { out = marked(s, () => applyRead(s, { list }, `(late part '${key}')`, true)); } catch (err) { done(false); throw err; }
|
|
237
|
+
return typeof out === 'boolean' ? done(out) : out.then(done);
|
|
238
|
+
}, { behind: true }), L._parts);
|
|
192
239
|
}
|
|
193
240
|
|
|
194
241
|
|
|
@@ -244,12 +291,17 @@ export function applyAnnounced(s, data, slot, done) {
|
|
|
244
291
|
* 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
292
|
* freeze with them: the lines right after an unawaited apply can still step, run ops and apply again (stateReplace.js, pause). */
|
|
246
293
|
function afterLoad(s, e, slot, scope) {
|
|
247
|
-
const
|
|
248
|
-
if (!
|
|
294
|
+
const has = [...e.modules.values()].filter(m => m.afterLoad), q = s._replace;
|
|
295
|
+
if (!has.length) { takeListenerError(scope, 0); return true; }
|
|
249
296
|
const job = q.pause();
|
|
250
|
-
|
|
297
|
+
let hooks = [];
|
|
298
|
+
const run = async () => {
|
|
251
299
|
if (!q.resume(job)) return null;
|
|
252
300
|
q.hold();
|
|
301
|
+
// the loop hooks' gate (_runsHooks): a failed, blocked, disabled or still initializing module rebuilds nothing, so no afterLoad reads what its init has not
|
|
302
|
+
// built (review l2 #10). Not waited for: an init that defines a save part (a late job holding the turn) and then awaits a load would wait for this very job.
|
|
303
|
+
// Its init builds for the state that stands when it runs
|
|
304
|
+
hooks = has.filter(m => e._runsHooks(m.name));
|
|
253
305
|
return Promise.allSettled(hooks.map(m => Promise.resolve().then(() => m.afterLoad(e, job.turn))));
|
|
254
306
|
};
|
|
255
307
|
return Promise.resolve().then(run).then(res => {
|
package/core/saves/saveIds.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// Record ids inside save data, for upgrade steps (saves.
|
|
1
|
+
// Record ids inside save data, for upgrade steps (saves.define migrate). Shared by the world part and every part that keys data by a record id
|
|
2
2
|
// (containers): when the world part renames ids, those parts must rename the same ones, and core is the one place both may import from.
|
|
3
3
|
// Runtime record ids: world save part version 2 numbered them `<kind>-<n>`, version 3 `<kind>#<n>` (an authored id may not contain `#`,
|
|
4
4
|
// so the two can never collide; modules/content/ids.js).
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Save format and per-part versions. A save is the envelope { format, savedAt, versions: { part: n }, parts: { part: data } }:
|
|
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
|
-
// Each saves.
|
|
3
|
+
// Each saves.define 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
5
|
import { codedError } from '../base/errorHints.js';
|
|
6
6
|
import { fmt } from '../base/validate.js';
|
|
@@ -9,15 +9,17 @@ import { fmt } from '../base/validate.js';
|
|
|
9
9
|
export const FORMAT = 1;
|
|
10
10
|
|
|
11
11
|
const DEV = {
|
|
12
|
-
badVersion: "saves.
|
|
13
|
-
badMigrate: "saves.
|
|
12
|
+
badVersion: "saves.define('{k}'): version must be a whole number >= 1 (raise it by 1 whenever this part's saved data changes shape), got {v}",
|
|
13
|
+
badMigrate: "saves.define('{k}'): migrate is { fromVersion: data => newData }, e.g. migrate: { 1: d => ({ ...d, gold: 0 }) }; key {m} is not a version below {v}",
|
|
14
14
|
tooNew: "[saves] not loaded: {list}. The save comes from a newer build of the game, which this build cannot read; nothing was changed and the save is kept. " +
|
|
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
|
-
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.
|
|
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.define('{k}')",
|
|
19
19
|
};
|
|
20
20
|
|
|
21
|
+
// first: true loads before the rest (rank 0); a number ranks it (lower earlier: the level 0, the zones that need the level 1); no first = after them all
|
|
22
|
+
const firstRank = p => p.first === true ? 0 : Number.isFinite(p.first) ? p.first : Infinity;
|
|
21
23
|
/**
|
|
22
24
|
* Validate a part's version and migrate steps at register time (a typo shows up at once, not when an old save happens to be read).
|
|
23
25
|
* @param {string} key
|
|
@@ -105,7 +107,7 @@ export function readSave(json, providers, slot) {
|
|
|
105
107
|
if (!versions || typeof versions !== 'object' || Array.isArray(versions)) return { reason: 'corrupt', dev: fmt(DEV.corrupt, { slot, why: `versions ${JSON.stringify(versions)}` }) };
|
|
106
108
|
const odd = Object.keys(versions).filter(k => !Number.isInteger(versions[k]) || versions[k] < 1);
|
|
107
109
|
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]
|
|
110
|
+
const list = [...providers].filter(([k]) => Object.hasOwn(data.parts, k)).sort((a, b) => { const x = firstRank(a[1]), y = firstRank(b[1]); return x < y ? -1 : x > y ? 1 : 0; }); // stable: equal ranks keep install order
|
|
109
111
|
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}`);
|
|
110
112
|
if (newer.length) return { reason: 'tooNew', dev: fmt(DEV.tooNew, { list: newer.join('; ') }) };
|
|
111
113
|
// 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
|
package/core/saves/session.js
CHANGED
|
@@ -20,13 +20,15 @@
|
|
|
20
20
|
// A replacement that fails (a save part's load() threw: saveApply rolled the data back) keeps the old playthrough: tracked handles, function timers
|
|
21
21
|
// and clocks stay as they were, background results still land, no 'session:start' or title follows, 'session:failed' { kind, slot? } fires instead (flow goes back to the state it left).
|
|
22
22
|
// What session:end already ended stays ended (the music stopped, a running cutscene was skipped to its end).
|
|
23
|
-
import { codedError } from '../base/errorHints.js';
|
|
24
|
-
import {
|
|
23
|
+
import { codedError, coded } from '../base/errorHints.js';
|
|
24
|
+
import { removeEach, reportError } from '../base/errors.js';
|
|
25
|
+
import { DEV as IS_DEV, fmt } from '../base/validate.js';
|
|
25
26
|
import { applySave, partData } from './saveApply.js';
|
|
26
27
|
import { readSave } from './saveVersions.js';
|
|
27
28
|
|
|
28
29
|
const DEV = {
|
|
29
30
|
early: 'engine.session.{fn}() was called before engine.start() finished: the new-game state is captured when loading completes. Call it from a button or after `await engine.start()`.',
|
|
31
|
+
missed: "a 'session:start' listener was added after engine.start() returned, but the playthrough had already started inside start() (?play, or newGame / load during start): it waits for the next new game and did not run for this one. Add it before `await engine.start()`, or read the state after start (engine.session.playing, engine.events.recent('session:start')).",
|
|
30
32
|
badHandle: 'engine.session.track(handle): handle must have remove(), like the result of engine.events.on / onFixed / clock.after. Got {got}.'
|
|
31
33
|
};
|
|
32
34
|
|
|
@@ -100,7 +102,7 @@ export class Session {
|
|
|
100
102
|
delete base.parts[key]; delete base.versions[key];
|
|
101
103
|
this._lateParts.add(key);
|
|
102
104
|
// its save() cannot run yet, or has nothing to save (like collectParts): newGame leaves this part as it is. Data a save cannot hold is said now: it would refuse every save too
|
|
103
|
-
try { const d = partData(key, p); if (d != null) { base.parts[key] = d; base.versions[key] = p.version; } } catch (err) { if (err?.code === 'save-part-threw')
|
|
105
|
+
try { const d = partData(key, p); if (d != null) { base.parts[key] = d; base.versions[key] = p.version; } } catch (err) { if (err?.code === 'save-part-threw') reportError(this.engine, err, `new-game baseline of save part '${key}'`); }
|
|
104
106
|
this._base = JSON.stringify(base);
|
|
105
107
|
}
|
|
106
108
|
|
|
@@ -136,12 +138,13 @@ export class Session {
|
|
|
136
138
|
/**
|
|
137
139
|
* Start a new playthrough from the state the game had right after start(). Returns Promise<boolean> (false only if a save part failed to load: the
|
|
138
140
|
* old playthrough then goes on, with its data, listeners and timers, and 'session:failed' fires instead of 'session:start').
|
|
141
|
+
* @param {{ turn?: object }} [o] turn: the running request's own (what a save part's load(), an afterLoad or a module's applyState was given): the call then runs inside that request instead of waiting behind it for itself, as level.load({ turn }) does
|
|
139
142
|
* @returns {Promise<boolean>}
|
|
140
143
|
* @example
|
|
141
144
|
* // a "Restart" button in a game-over screen
|
|
142
145
|
* restartBtn.onclick = () => engine.session.newGame();
|
|
143
146
|
*/
|
|
144
|
-
newGame() { return this._turn('new', () => this._begin('newGame', () => this._applyBase(), { kind: 'new' })); }
|
|
147
|
+
newGame({ turn } = {}) { return this._turn('new', () => this._begin('newGame', () => this._applyBase(), { kind: 'new' }), turn); }
|
|
145
148
|
|
|
146
149
|
/**
|
|
147
150
|
* Continue from a save (or retry from a checkpoint) with nothing of the current playthrough left over: the new-game state with the save on top,
|
|
@@ -164,23 +167,25 @@ export class Session {
|
|
|
164
167
|
/**
|
|
165
168
|
* End the playthrough and show the title screen (the title part when the game turned it on; flow returns to its start state).
|
|
166
169
|
* The state behind the title is the new-game state, so nothing from the old playthrough runs while the title is up.
|
|
170
|
+
* @param {{ turn?: object }} [o] turn: the running request's own (what a save part's load(), an afterLoad or a module's applyState was given): the call then runs inside that request instead of waiting behind it for itself, as level.load({ turn }) does
|
|
167
171
|
* @returns {Promise<boolean>}
|
|
168
172
|
* @example settingsBackToTitle.onclick = () => engine.session.quit();
|
|
169
173
|
*/
|
|
170
|
-
quit() {
|
|
174
|
+
quit({ turn } = {}) {
|
|
171
175
|
return this._turn('quit', async () => {
|
|
172
176
|
const ok = await this._reset('quit', () => this._applyBase());
|
|
173
177
|
if (ok) this._over = !this.engine.ui.open('title'); // ui.open answers false with no title part
|
|
174
178
|
else this.engine.events.emit('session:failed', { kind: 'quit' }); // rolled back: the old playthrough goes on, so no title over it
|
|
175
179
|
return ok;
|
|
176
|
-
});
|
|
180
|
+
}, turn);
|
|
177
181
|
}
|
|
178
182
|
|
|
179
183
|
/**
|
|
180
184
|
* @internal A session replacement takes its turn with every other one (stateReplace.js). The same request joins the last in line (a double-clicked
|
|
181
185
|
* Restart); another one waits: joined, a load asked during ?play's new game answered true and never loaded.
|
|
186
|
+
* turn: the running request's own, when it asks (applyState): then it runs inside that request, as level.load({ turn }) does.
|
|
182
187
|
*/
|
|
183
|
-
_turn(what, run) { return this.engine.saves._replace.run(what, run); }
|
|
188
|
+
_turn(what, run, turn) { return this.engine.saves._replace.run(what, run, { turn }); }
|
|
184
189
|
|
|
185
190
|
/** @internal the new-game state as save data (_reset already refused a call before start() finished) */
|
|
186
191
|
_baseData() { return JSON.parse(this._base); }
|
|
@@ -193,6 +198,9 @@ export class Session {
|
|
|
193
198
|
const ok = await this._reset(fn, apply);
|
|
194
199
|
if (ok) this._started();
|
|
195
200
|
this.engine.events.emit(ok ? 'session:start' : 'session:failed', info);
|
|
201
|
+
// ?play starts the first run inside engine.start(), so a session:start listener attached after `await engine.start()` misses it silently; hint once.
|
|
202
|
+
// Mark only when fired during start(), and hint only once start() returned (phase 'running') with no tick yet; later listeners are waiting for the next run.
|
|
203
|
+
if (ok && this.engine.phase !== 'running') this.engine.events._firedNow('session:start', () => this.engine.phase === 'running', coded('session-start-missed', DEV.missed));
|
|
196
204
|
return ok;
|
|
197
205
|
}
|
|
198
206
|
|
|
@@ -218,7 +226,8 @@ export class Session {
|
|
|
218
226
|
if (!ok) return false; // rolled back: the old playthrough's tracked handles and timers stay, so it goes on as it was (review 0.4 core B3)
|
|
219
227
|
// shortcut: tracked handles stay registered while apply runs, so one may hear the load's own events (world:load); removing them first
|
|
220
228
|
// would make a failed load unrecoverable. Upgrade if a game needs it: suspend tracked handles during apply instead
|
|
221
|
-
|
|
229
|
+
// one remove() that throws is reported and the switch goes on: stopping here would leave the new data in with no session id, timers or rebase (review l2 #11)
|
|
230
|
+
removeEach(e, oldHandles, 'remove() of a handle session.track held', h => this._tracked.delete(h));
|
|
222
231
|
this.id++;
|
|
223
232
|
e.time._restoreFn(this._timers, oldTimers); // event timers came back with the save; function timers are the boot-time ones, each with its original delay, and those apply set up
|
|
224
233
|
e.commits.rebase(); // requests that outlived the load (a nextFixed, terrain colliders) were due on the old tick count, minutes away now that tick restarted
|
|
@@ -8,6 +8,9 @@
|
|
|
8
8
|
// the caller's next lines) and a direct apply / load on those lines runs at once and takes over. The older job's hooks are then skipped:
|
|
9
9
|
// they would rebuild for a state that is gone, and the newer job's hooks rebuild for the one that stayed. Not past something already in line:
|
|
10
10
|
// apply(x); save('s'); apply(y) would store y.
|
|
11
|
+
// A late part's job (adoptPart) adds to the state, it replaces nothing, so paused it holds nobody back: a read (a save, a content commit) on those lines goes
|
|
12
|
+
// at once, and another late part takes over, its afterLoad round rebuilding for both. Held, use(content()); content.load(...) or a failed replaces putting
|
|
13
|
+
// its module back would leave the next line without its data until a microtask later; nothing it skips is half loaded (paused means every part is in).
|
|
11
14
|
// - One marker. `replacing` is true from reading the save through its parts, afterLoad and any rollback; begin() / end() bracket that span
|
|
12
15
|
// (saveApply.js). Ops read it (opsFail.js) instead of knowing freeze names, so a game's own freeze never looks like a load and a load never
|
|
13
16
|
// looks like a menu. A session's turn is longer than the marker on purpose: session:end listeners (a skipped cutscene's last steps) and
|
|
@@ -51,6 +54,7 @@ export class StateReplace {
|
|
|
51
54
|
/** True from reading a save until its load or rollback ended */ this.replacing = false;
|
|
52
55
|
/** The freeze while the replacement waits on something */ this.freeze = null;
|
|
53
56
|
/** How many stateTurns are open */ this.turns = 0;
|
|
57
|
+
/** Restore jobs (restoring) not ended yet: while any is, end() leaves the marker and the freeze on */ this.restores = 0;
|
|
54
58
|
/** Which saved state the game holds: moves when a load starts changing parts, goes back when it fails. A level change does not move it, so what a level load's caller asked next survives (commits.epoch moves for both) */ this.generation = 0;
|
|
55
59
|
}
|
|
56
60
|
|
|
@@ -58,15 +62,18 @@ export class StateReplace {
|
|
|
58
62
|
* Run fn when its turn comes: at once when idle, else after the jobs before it. Returns what fn returned, as a Promise.
|
|
59
63
|
* @param {string | null} key same key as the last job in line: join it instead of running again
|
|
60
64
|
* @param {() => any} fn
|
|
61
|
-
* @param {boolean} [
|
|
65
|
+
* @param {{ behind?: boolean, whole?: boolean, turn?: object }} [o] behind: a late part (adoptPart), fn adds to the state the running job leaves: it takes over only a paused late part's job (_passable).
|
|
66
|
+
* whole: the job is one request from its first line to its last (a scene request, applyState), so it never pauses for a direct apply to take over.
|
|
67
|
+
* turn: the turn of the request asking. When it is the running one, fn is part of that request and runs now, inside it: in line it would wait for itself
|
|
62
68
|
* @returns {Promise<any>}
|
|
63
69
|
*/
|
|
64
|
-
run(key, fn, behind = false) {
|
|
70
|
+
run(key, fn, { behind = false, whole = false, turn } = {}) {
|
|
71
|
+
if (turn && this.job?.turn === turn) { try { return Promise.resolve(fn()); } catch (err) { return Promise.reject(err); } }
|
|
65
72
|
const last = this.waiting.at(-1) ?? this.job;
|
|
66
73
|
if (key && last?.key === key) return last.done;
|
|
67
|
-
const job = { key, fn, done: null, settle: null, paused: false, turn: Object.freeze({}) };
|
|
74
|
+
const job = { key, fn, done: null, settle: null, paused: false, whole, behind, turn: Object.freeze({}) };
|
|
68
75
|
job.done = new Promise(res => { job.settle = res; });
|
|
69
|
-
if (this.job && (behind || !this.job.paused || this.waiting.length)) this._line(job); else this._start(job);
|
|
76
|
+
if (this.job && (behind && !this._passable() || !this.job.paused || this.waiting.length)) this._line(job); else this._start(job);
|
|
70
77
|
return job.done;
|
|
71
78
|
}
|
|
72
79
|
|
|
@@ -76,7 +83,7 @@ export class StateReplace {
|
|
|
76
83
|
* @returns {Promise<any>}
|
|
77
84
|
*/
|
|
78
85
|
read(fn) {
|
|
79
|
-
if (!this.job) return fn();
|
|
86
|
+
if (!this.job || this._passable()) return fn();
|
|
80
87
|
let give;
|
|
81
88
|
const job = { key: null, fn: () => { try { give(fn()); } catch (err) { give(Promise.reject(err)); } }, done: new Promise(res => { give = res; }), settle() {}, paused: false }; // a throw reaches the one who asked, and the line goes on
|
|
82
89
|
this._line(job);
|
|
@@ -88,10 +95,10 @@ export class StateReplace {
|
|
|
88
95
|
* @param {Promise<any>} p
|
|
89
96
|
*/
|
|
90
97
|
restoring(p) {
|
|
91
|
-
|
|
92
|
-
this
|
|
93
|
-
const
|
|
94
|
-
|
|
98
|
+
// the job ends itself once p settled and its turn came (_start's next). Asked while another job runs (an atomic op inside applyState), that job's own end()
|
|
99
|
+
// must not drop the marker, and nothing else would raise it again: restores keeps it on until this one ends
|
|
100
|
+
const job = { key: null, fn: () => p, done: p, settle() {}, paused: false, restoring: true };
|
|
101
|
+
this.restores++; this.begin(); this.hold();
|
|
95
102
|
if (this.job) this.waiting.unshift(job); else this._start(job);
|
|
96
103
|
}
|
|
97
104
|
|
|
@@ -113,18 +120,30 @@ export class StateReplace {
|
|
|
113
120
|
_start(job) {
|
|
114
121
|
this.job = job; this.moved = performance.now(); // measure: a sign of life for those in line
|
|
115
122
|
const next = () => {
|
|
123
|
+
if (this.job !== job) return; // not its turn any more: taken over
|
|
124
|
+
if (job.restoring) { this.restores--; this.end(); } // the old state is whole again: gameplay and the line go on
|
|
125
|
+
// the notice is still this job's turn: a load asked in a state:replaced listener goes in line. Were the turn cleared first, that load would start at once and the
|
|
126
|
+
// job in line beside it right after (review l2 #1). Not paused either: a paused job would let it take over and skip the line
|
|
127
|
+
job.paused = false;
|
|
128
|
+
if (job.changed) this.engine.events.emit('state:replaced', { undone: job.changed === 'undone' });
|
|
116
129
|
if (this.job !== job) return;
|
|
117
130
|
this.job = null;
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
if (n) this._start(n);
|
|
121
|
-
}; // not its turn any more: taken over
|
|
131
|
+
this._next();
|
|
132
|
+
};
|
|
122
133
|
let out;
|
|
123
134
|
try { out = job.fn(); } catch (err) { out = Promise.reject(err); }
|
|
124
135
|
if (typeof out?.then === 'function') out.then(next, next);
|
|
125
136
|
else next();
|
|
126
137
|
job.settle(out);
|
|
127
138
|
}
|
|
139
|
+
/** A paused late part's job with nobody in line: what comes next does not wait for its afterLoad round (top of the file) */
|
|
140
|
+
_passable() { return !!this.job?.paused && this.job.behind && !this.waiting.length; }
|
|
141
|
+
/** The one place the next job starts: only when no job holds the turn, so a job ending inside another's notice cannot start a second one beside it */
|
|
142
|
+
_next() {
|
|
143
|
+
if (this.job) return;
|
|
144
|
+
const n = this.waiting.shift();
|
|
145
|
+
if (n) this._start(n);
|
|
146
|
+
}
|
|
128
147
|
|
|
129
148
|
/** The state starts being replaced (the marker's span: top of the file) */
|
|
130
149
|
begin() { this.replacing = true; }
|
|
@@ -134,7 +153,7 @@ export class StateReplace {
|
|
|
134
153
|
* apply, and a job already holding the freeze is mid-load, so neither pauses. Returns the job, for resume */
|
|
135
154
|
pause() {
|
|
136
155
|
const job = this.job;
|
|
137
|
-
if (!job.key && !this.freeze) { job.paused = true; this.replacing = false; }
|
|
156
|
+
if (!job.key && !job.whole && !this.freeze) { job.paused = true; this.replacing = false; }
|
|
138
157
|
return job;
|
|
139
158
|
}
|
|
140
159
|
/** The wait ended: false when a newer job took over, else the marker is back on */
|
|
@@ -148,7 +167,7 @@ export class StateReplace {
|
|
|
148
167
|
/** The replacement waits on something: stop fixed steps until end() */
|
|
149
168
|
hold() { this.freeze ??= this.engine.freeze(FREEZE); }
|
|
150
169
|
/** The load or its rollback ended */
|
|
151
|
-
end() { this.replacing = false; this.freeze?.remove(); this.freeze = null; }
|
|
170
|
+
end() { if (this.restores) return; this.replacing = false; this.freeze?.remove(); this.freeze = null; }
|
|
152
171
|
}
|
|
153
172
|
|
|
154
173
|
/**
|