threedog 0.0.0-stage → 0.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 +5 -0
- package/LICENSE +21 -0
- package/README.md +39 -2
- package/core/Animator.js +268 -0
- package/core/Assets.js +256 -0
- package/core/Audio.js +267 -0
- package/core/Baked.js +72 -0
- package/core/Batching.js +247 -0
- package/core/Budget.js +221 -0
- package/core/Clock.js +94 -0
- package/core/Commits.js +77 -0
- package/core/DebugOverrides.js +143 -0
- package/core/Describe.js +145 -0
- package/core/Engine.js +184 -0
- package/core/Events.js +153 -0
- package/core/I18n.js +94 -0
- package/core/Input.js +245 -0
- package/core/Inspect.js +77 -0
- package/core/InspectScene.js +191 -0
- package/core/Jobs.js +146 -0
- package/core/Loading.js +149 -0
- package/core/MaterialInfo.js +32 -0
- package/core/Ops.js +256 -0
- package/core/Random.js +52 -0
- package/core/Rays.js +160 -0
- package/core/SaveStore.js +85 -0
- package/core/Saves.js +254 -0
- package/core/Stream.js +279 -0
- package/core/Threads.js +158 -0
- package/core/UrlState.js +94 -0
- package/core/Vars.js +35 -0
- package/core/Views.js +49 -0
- package/core/actor.js +23 -0
- package/core/assetEntry.js +89 -0
- package/core/assetLoad.js +190 -0
- package/core/assetManifest.js +35 -0
- package/core/assetReport.js +83 -0
- package/core/audioRules.js +121 -0
- package/core/audioVoice.js +225 -0
- package/core/batchGroups.js +116 -0
- package/core/canvasBox.js +63 -0
- package/core/catalog.js +169 -0
- package/core/checks.js +67 -0
- package/core/claims.js +51 -0
- package/core/dayTime.js +15 -0
- package/core/debugView.js +76 -0
- package/core/describeRender.js +45 -0
- package/core/describeText.js +143 -0
- package/core/easing.js +34 -0
- package/core/errorCodes.js +205 -0
- package/core/errorHints.js +208 -0
- package/core/errors.js +40 -0
- package/core/events.generated.js +84 -0
- package/core/ground.js +102 -0
- package/core/holds.js +106 -0
- package/core/inputContext.js +69 -0
- package/core/inputDefaults.js +22 -0
- package/core/inputPad.js +35 -0
- package/core/inputPointer.js +48 -0
- package/core/inputTouch.js +48 -0
- package/core/lifecycle.js +69 -0
- package/core/lightWatch.js +56 -0
- package/core/look/coreParts.js +112 -0
- package/core/look/layers.js +136 -0
- package/core/look/part.js +173 -0
- package/core/look/report.js +79 -0
- package/core/look/write.js +86 -0
- package/core/loop.js +200 -0
- package/core/math.js +33 -0
- package/core/modules.js +196 -0
- package/core/movement.js +19 -0
- package/core/mulberry32.js +14 -0
- package/core/opsAtomic.js +31 -0
- package/core/opsCheck.js +97 -0
- package/core/opsFail.js +20 -0
- package/core/opsGuard.js +26 -0
- package/core/opsHistory.js +27 -0
- package/core/opsRun.js +77 -0
- package/core/page.js +78 -0
- package/core/params.js +132 -0
- package/core/pureWorker.js +5 -0
- package/core/renamed.js +21 -0
- package/core/saveApply.js +128 -0
- package/core/saveFiles.js +139 -0
- package/core/saveIds.js +53 -0
- package/core/saveVersions.js +97 -0
- package/core/scatter.js +92 -0
- package/core/sceneMethods.js +100 -0
- package/core/screenToGround.js +39 -0
- package/core/services.js +73 -0
- package/core/session.js +171 -0
- package/core/shadowTypes.js +15 -0
- package/core/skip.js +104 -0
- package/core/startup.js +135 -0
- package/core/streamCells.js +24 -0
- package/core/streamSources.js +73 -0
- package/core/styleParts.js +96 -0
- package/core/targeting.js +64 -0
- package/core/thingExplain.js +68 -0
- package/core/thingOps.js +168 -0
- package/core/things.js +212 -0
- package/core/threadPure.js +120 -0
- package/core/threadServe.js +25 -0
- package/core/tier.js +11 -0
- package/core/util.js +11 -0
- package/core/validate.js +204 -0
- package/docs/AI.md +123 -0
- package/docs/API.md +83 -0
- package/docs/CODEMAP.md +347 -0
- package/docs/COMMANDS.md +108 -0
- package/docs/CONVENTIONS.md +145 -0
- package/docs/PERF.md +217 -0
- package/docs/THREE.md +86 -0
- package/docs/api/ambience.md +15 -0
- package/docs/api/assets.md +62 -0
- package/docs/api/audio.md +53 -0
- package/docs/api/budget.md +40 -0
- package/docs/api/cameraRig.md +120 -0
- package/docs/api/characters.md +144 -0
- package/docs/api/clock.md +7 -0
- package/docs/api/collision.md +39 -0
- package/docs/api/content.md +64 -0
- package/docs/api/dialogue.md +39 -0
- package/docs/api/engine.md +199 -0
- package/docs/api/entities.md +61 -0
- package/docs/api/events.md +95 -0
- package/docs/api/flow.md +27 -0
- package/docs/api/grids.md +11 -0
- package/docs/api/ground.md +16 -0
- package/docs/api/hlod.md +34 -0
- package/docs/api/hud.md +31 -0
- package/docs/api/i18n.md +10 -0
- package/docs/api/input.md +24 -0
- package/docs/api/interactions.md +31 -0
- package/docs/api/inventory.md +66 -0
- package/docs/api/jobs.md +10 -0
- package/docs/api/level.md +41 -0
- package/docs/api/lightPool.md +56 -0
- package/docs/api/music.md +34 -0
- package/docs/api/nav.md +26 -0
- package/docs/api/net.md +14 -0
- package/docs/api/openWorld.md +24 -0
- package/docs/api/particles.md +41 -0
- package/docs/api/photo.md +15 -0
- package/docs/api/post.md +10 -0
- package/docs/api/quests.md +36 -0
- package/docs/api/rays.md +26 -0
- package/docs/api/rigid.md +84 -0
- package/docs/api/saves.md +32 -0
- package/docs/api/settings.md +36 -0
- package/docs/api/sky.md +58 -0
- package/docs/api/stream.md +31 -0
- package/docs/api/style.md +134 -0
- package/docs/api/terrain.md +34 -0
- package/docs/api/timeline.md +39 -0
- package/docs/api/tools.md +57 -0
- package/docs/api/triggers.md +56 -0
- package/docs/api/vars.md +9 -0
- package/docs/api/vegetation.md +52 -0
- package/docs/api/water.md +48 -0
- package/docs/api/weather.md +29 -0
- package/docs/api/world.md +30 -0
- package/docs/recipes/01-new-game.md +148 -0
- package/docs/recipes/02-npc.md +167 -0
- package/docs/recipes/03-items-pickups.md +158 -0
- package/docs/recipes/04-quests.md +83 -0
- package/docs/recipes/05-props-bake.md +159 -0
- package/docs/recipes/06-clock-events.md +117 -0
- package/docs/recipes/07-flow-scenes-pause.md +132 -0
- package/docs/recipes/08-weather-sky.md +74 -0
- package/docs/recipes/09-style-pack.md +234 -0
- package/docs/recipes/10-blender-level.md +67 -0
- package/docs/recipes/11-vehicles.md +55 -0
- package/docs/recipes/12-navmesh.md +79 -0
- package/docs/recipes/13-animation.md +149 -0
- package/docs/recipes/14-custom-module.md +91 -0
- package/docs/recipes/15-perf.md +78 -0
- package/docs/recipes/16-dev-bridge.md +180 -0
- package/docs/recipes/18-world.md +185 -0
- package/docs/recipes/19-shooting-picking.md +76 -0
- package/docs/recipes/20-content-actions-save.md +176 -0
- package/docs/recipes/21-camera.md +153 -0
- package/docs/recipes/22-shop-gold.md +107 -0
- package/docs/recipes/23-ops.md +175 -0
- package/docs/recipes/26-ui-parts.md +138 -0
- package/docs/recipes/27-net.md +96 -0
- package/docs/recipes/28-terrain.md +80 -0
- package/docs/recipes/29-grid.md +87 -0
- package/docs/recipes/30-templates.md +131 -0
- package/docs/recipes/31-audio.md +126 -0
- package/docs/recipes/32-action-game.md +33 -0
- package/docs/recipes/33-stream-sources.md +37 -0
- package/docs/recipes/34-environment-lighting.md +36 -0
- package/docs/recipes/35-style-from-reference.md +89 -0
- package/docs/recipes/36-sky-ground-plant-looks.md +116 -0
- package/docs/recipes/37-terrain-look-hooks.md +97 -0
- package/docs/recipes/38-environment-look-hooks.md +83 -0
- package/docs/recipes/40-scene.md +108 -0
- package/docs/recipes/41-thing-registry.md +93 -0
- package/docs/recipes/42-terrain-shape.md +64 -0
- package/docs/recipes/43-shader-patches-surface-looks.md +120 -0
- package/docs/recipes/44-water-weather-look-hooks.md +135 -0
- package/docs/recipes/45-cascaded-shadows.md +51 -0
- package/docs/recipes/46-blender-art-route.md +114 -0
- package/docs/recipes/47-island-snow-backdrop.md +44 -0
- package/docs/recipes/48-make-material.md +70 -0
- package/docs/recipes/49-game-module-contract.md +71 -0
- package/docs/recipes/50-own-renderer.md +12 -0
- package/docs/recipes/51-capability-catalog.md +63 -0
- package/docs/recipes/52-look.md +108 -0
- package/examples/action/DESIGN.md +3 -0
- package/examples/action/GAMEMAP.md +127 -0
- package/examples/action/content/actions.js +8 -0
- package/examples/action/content/audio.js +9 -0
- package/examples/action/content/index.js +10 -0
- package/examples/action/content/items.js +4 -0
- package/examples/action/content/places.js +4 -0
- package/examples/action/content/props.js +11 -0
- package/examples/action/content/templates.js +10 -0
- package/examples/action/content/views.js +6 -0
- package/examples/action/look.js +5 -0
- package/examples/action/main.js +137 -0
- package/examples/action/models.js +25 -0
- package/examples/sheepisland/GAMEMAP.md +107 -0
- package/examples/sheepisland/content/index.js +6 -0
- package/examples/sheepisland/content/props.js +19 -0
- package/examples/sheepisland/content/templates.js +5 -0
- package/examples/sheepisland/content/vegetation.js +8 -0
- package/examples/sheepisland/main.js +71 -0
- package/examples/sheepisland/params.js +25 -0
- package/examples/sheepisland/style/index.js +79 -0
- package/examples/sheepisland/style/models.js +59 -0
- package/examples/sheepisland/views.js +9 -0
- package/examples/styletest/GAMEMAP.md +135 -0
- package/examples/styletest/content/index.js +9 -0
- package/examples/styletest/content/items.js +8 -0
- package/examples/styletest/content/npcs.js +8 -0
- package/examples/styletest/content/places.js +5 -0
- package/examples/styletest/content/props.js +16 -0
- package/examples/styletest/content/templates.js +9 -0
- package/examples/styletest/content/vegetation.js +31 -0
- package/examples/styletest/look.js +11 -0
- package/examples/styletest/main.js +95 -0
- package/examples/styletest/models.js +87 -0
- package/examples/styletest/overrides.js +33 -0
- package/examples/styletest/panel.js +135 -0
- package/examples/styletest/params.js +32 -0
- package/examples/styletest/views.js +31 -0
- package/examples/world/DESIGN.md +5 -0
- package/examples/world/GAMEMAP.md +171 -0
- package/examples/world/content/actions.js +8 -0
- package/examples/world/content/audio.js +25 -0
- package/examples/world/content/bodies.js +12 -0
- package/examples/world/content/containers.js +4 -0
- package/examples/world/content/dialogues.js +33 -0
- package/examples/world/content/index.js +17 -0
- package/examples/world/content/items.js +10 -0
- package/examples/world/content/npcs.js +14 -0
- package/examples/world/content/pickups.js +11 -0
- package/examples/world/content/places.js +6 -0
- package/examples/world/content/props.js +12 -0
- package/examples/world/content/quests.js +15 -0
- package/examples/world/content/rules.js +23 -0
- package/examples/world/content/templates.js +5 -0
- package/examples/world/content/vegetation.js +32 -0
- package/examples/world/main.js +168 -0
- package/examples/world/models.js +28 -0
- package/index.d.ts +306 -0
- package/index.js +122 -0
- package/llms.txt +61 -0
- package/modules/ambience/Ambience.js +186 -0
- package/modules/camera/FirstPersonCamera.js +131 -0
- package/modules/camera/FixedCamera.js +162 -0
- package/modules/camera/FollowCamera.js +91 -0
- package/modules/camera/RtsCamera.js +132 -0
- package/modules/camera/common.js +182 -0
- package/modules/camera/index.js +11 -0
- package/modules/camera/projection.js +34 -0
- package/modules/characters/Character.js +235 -0
- package/modules/characters/NPC.js +242 -0
- package/modules/characters/assetModel.js +42 -0
- package/modules/characters/astar.js +66 -0
- package/modules/characters/behaviors.js +72 -0
- package/modules/characters/footsteps.js +13 -0
- package/modules/characters/index.js +215 -0
- package/modules/characters/moveHelpers.js +29 -0
- package/modules/characters/movers/common.js +62 -0
- package/modules/characters/movers/rapier.js +74 -0
- package/modules/characters/movers/simple.js +43 -0
- package/modules/characters/npcAvoid.js +129 -0
- package/modules/characters/npcSim.js +150 -0
- package/modules/characters/npcView.js +42 -0
- package/modules/characters/pathAsync.js +113 -0
- package/modules/characters/pathJob.js +62 -0
- package/modules/characters/pathWorker.js +7 -0
- package/modules/characters/playerStrings.js +12 -0
- package/modules/characters/proceduralRig.js +58 -0
- package/modules/characters/useModel.js +22 -0
- package/modules/characters/walkTo.js +58 -0
- package/modules/collision/Collision.js +274 -0
- package/modules/collision/grid.js +63 -0
- package/modules/content/explain.js +13 -0
- package/modules/content/ids.js +95 -0
- package/modules/content/index.js +154 -0
- package/modules/content/loader.js +190 -0
- package/modules/content/models.js +69 -0
- package/modules/content/packs.js +69 -0
- package/modules/content/props.js +89 -0
- package/modules/content/rules.js +134 -0
- package/modules/content/templates.js +189 -0
- package/modules/debug/DebugPanel.js +174 -0
- package/modules/entities/Entities.js +243 -0
- package/modules/entities/build.js +25 -0
- package/modules/entities/index.js +4 -0
- package/modules/flow/index.js +101 -0
- package/modules/gameplay/Container.js +227 -0
- package/modules/gameplay/Containers.js +89 -0
- package/modules/gameplay/Dialogue.js +219 -0
- package/modules/gameplay/Interactions.js +253 -0
- package/modules/gameplay/Inventory.js +224 -0
- package/modules/gameplay/Quests.js +205 -0
- package/modules/gameplay/boxOps.js +60 -0
- package/modules/gameplay/dialogueBox.js +48 -0
- package/modules/gameplay/interactionPrompt.js +28 -0
- package/modules/gameplay/inventoryOps.js +137 -0
- package/modules/gameplay/pickups.js +115 -0
- package/modules/gameplay/questLog.js +54 -0
- package/modules/gameplay/questSave.js +71 -0
- package/modules/grid/Grid.js +184 -0
- package/modules/grid/Layer.js +142 -0
- package/modules/grid/index.js +236 -0
- package/modules/grid/ops.js +73 -0
- package/modules/grid/preview.js +85 -0
- package/modules/grid/tiles.js +79 -0
- package/modules/hlod/index.js +167 -0
- package/modules/hud/index.js +167 -0
- package/modules/hud/parts.js +80 -0
- package/modules/level/geometry.js +46 -0
- package/modules/level/heightfield.js +160 -0
- package/modules/level/index.js +233 -0
- package/modules/level/nodes.js +84 -0
- package/modules/lights/index.js +227 -0
- package/modules/music/Music.js +294 -0
- package/modules/music/index.js +2 -0
- package/modules/music/rules.js +28 -0
- package/modules/nav/index.js +156 -0
- package/modules/nav/navPath.js +17 -0
- package/modules/net/Client.js +137 -0
- package/modules/net/Host.js +117 -0
- package/modules/net/Net.js +49 -0
- package/modules/net/index.js +77 -0
- package/modules/net/sync.js +114 -0
- package/modules/net/transports.js +118 -0
- package/modules/particles/Particles.js +179 -0
- package/modules/particles/effect.js +112 -0
- package/modules/particles/shaders.js +28 -0
- package/modules/photo/Photo.js +146 -0
- package/modules/rigid/RigidBodies.js +265 -0
- package/modules/rigid/Vehicles.js +97 -0
- package/modules/rigid/sync.js +158 -0
- package/modules/settings/Settings.js +297 -0
- package/modules/settings/apply.js +21 -0
- package/modules/settings/index.js +3 -0
- package/modules/settings/sections.js +156 -0
- package/modules/settings/strings.js +53 -0
- package/modules/settings/view.js +65 -0
- package/modules/sky/Sky.js +259 -0
- package/modules/sky/calendar.js +80 -0
- package/modules/sky/cascades.js +125 -0
- package/modules/sky/clouds.js +79 -0
- package/modules/sky/domeLayers.js +33 -0
- package/modules/sky/environment.js +141 -0
- package/modules/sky/fog.js +139 -0
- package/modules/sky/frame.js +77 -0
- package/modules/sky/layers.js +69 -0
- package/modules/sky/look.js +51 -0
- package/modules/sky/lookFog.js +80 -0
- package/modules/sky/lookShadow.js +50 -0
- package/modules/sky/lookSky.js +108 -0
- package/modules/sky/schedule.js +80 -0
- package/modules/sky/shader.js +96 -0
- package/modules/sky/shadow.js +74 -0
- package/modules/sky/skyModule.js +60 -0
- package/modules/terrain/ChunkManager.js +260 -0
- package/modules/terrain/chunkJob.js +19 -0
- package/modules/terrain/chunkLevels.js +40 -0
- package/modules/terrain/chunkQueries.js +42 -0
- package/modules/terrain/chunkWorker.js +5 -0
- package/modules/terrain/index.js +118 -0
- package/modules/terrain/lookGround.js +61 -0
- package/modules/terrain/mountTerrain.js +32 -0
- package/modules/terrain/terrainColorMap.js +41 -0
- package/modules/terrain/terrainDefaults.js +39 -0
- package/modules/terrain/terrainEdit.js +139 -0
- package/modules/terrain/terrainGen.js +155 -0
- package/modules/terrain/terrainIsland.js +131 -0
- package/modules/terrain/terrainMesh.js +92 -0
- package/modules/terrain/terrainShape.js +108 -0
- package/modules/terrain/terrainShapeMain.js +41 -0
- package/modules/terrain/terrainTexture.js +44 -0
- package/modules/timeline/Timeline.js +253 -0
- package/modules/timeline/Tween.js +114 -0
- package/modules/timeline/letterbox.js +24 -0
- package/modules/timeline/shots.js +90 -0
- package/modules/triggers/index.js +268 -0
- package/modules/vegetation/Vegetation.js +256 -0
- package/modules/vegetation/groundChunks.js +177 -0
- package/modules/vegetation/index.js +43 -0
- package/modules/vegetation/lookWind.js +37 -0
- package/modules/vegetation/modelGeometry.js +21 -0
- package/modules/water/Water.js +160 -0
- package/modules/water/look.js +80 -0
- package/modules/water/surface.js +88 -0
- package/modules/weather/Weather.js +242 -0
- package/modules/weather/look.js +75 -0
- package/modules/weather/particles.js +92 -0
- package/modules/weather/shaders.js +49 -0
- package/modules/weather/strings.js +15 -0
- package/modules/world/World.js +231 -0
- package/modules/world/cells.js +42 -0
- package/modules/world/explain.js +11 -0
- package/modules/world/index.js +71 -0
- package/modules/world/persist.js +107 -0
- package/modules/world/pos.js +20 -0
- package/modules/world/records.js +89 -0
- package/modules/world/sim.js +175 -0
- package/modules/world/simFar.js +82 -0
- package/modules/world/state.js +115 -0
- package/modules/world/thingSource.js +44 -0
- package/modules/world/views.js +182 -0
- package/package.json +66 -4
- package/presets.js +96 -0
- package/render/PostFX.js +240 -0
- package/render/detail.js +105 -0
- package/render/effects.js +144 -0
- package/render/engineUniforms.js +23 -0
- package/render/fuse.js +84 -0
- package/render/lighting.js +100 -0
- package/render/lights.js +18 -0
- package/render/lookSurface.js +161 -0
- package/render/materials.js +220 -0
- package/render/patches.js +252 -0
- package/render/postLook.js +86 -0
- package/render/surface.js +69 -0
- package/render/uniformDecl.js +29 -0
- package/types/common.d.ts +34 -0
- package/types/core.d.ts +1965 -0
- package/types/gameplay.d.ts +1822 -0
- package/types/generated/core/Audio.d.ts +200 -0
- package/types/generated/core/Batching.d.ts +47 -0
- package/types/generated/core/Budget.d.ts +90 -0
- package/types/generated/core/Commits.d.ts +31 -0
- package/types/generated/core/DebugOverrides.d.ts +52 -0
- package/types/generated/core/Events.d.ts +89 -0
- package/types/generated/core/I18n.d.ts +30 -0
- package/types/generated/core/Input.d.ts +118 -0
- package/types/generated/core/Jobs.d.ts +41 -0
- package/types/generated/core/Ops.d.ts +203 -0
- package/types/generated/core/Random.d.ts +49 -0
- package/types/generated/core/Rays.d.ts +49 -0
- package/types/generated/core/Saves.d.ts +162 -0
- package/types/generated/core/Stream.d.ts +93 -0
- package/types/generated/core/Threads.d.ts +82 -0
- package/types/generated/core/Views.d.ts +33 -0
- package/types/generated/core/audioVoice.d.ts +47 -0
- package/types/generated/core/page.d.ts +18 -0
- package/types/generated/core/session.d.ts +48 -0
- package/types/generated/modules/ambience/Ambience.d.ts +48 -0
- package/types/generated/modules/debug/DebugPanel.d.ts +24 -0
- package/types/generated/modules/flow/index.d.ts +10 -0
- package/types/generated/modules/grid/Grid.d.ts +151 -0
- package/types/generated/modules/grid/Layer.d.ts +65 -0
- package/types/generated/modules/grid/index.d.ts +86 -0
- package/types/generated/modules/hlod/index.d.ts +11 -0
- package/types/generated/modules/hud/index.d.ts +10 -0
- package/types/generated/modules/lights/index.d.ts +13 -0
- package/types/generated/modules/music/Music.d.ts +111 -0
- package/types/generated/modules/net/Net.d.ts +34 -0
- package/types/generated/modules/net/index.d.ts +53 -0
- package/types/generated/modules/net/transports.d.ts +58 -0
- package/types/generated/modules/particles/Particles.d.ts +69 -0
- package/types/generated/modules/sky/Sky.d.ts +145 -0
- package/types/generated/modules/sky/skyModule.d.ts +10 -0
- package/types/generated/modules/timeline/Timeline.d.ts +51 -0
- package/types/generated/modules/water/Water.d.ts +29 -0
- package/types/generated/modules/weather/Weather.d.ts +62 -0
- package/types/generated/modules/world/World.d.ts +242 -0
- package/types/generated/modules/world/index.d.ts +15 -0
- package/types/generated/render/PostFX.d.ts +125 -0
- package/types/generated/render/materials.d.ts +100 -0
- package/types/generated/render/patches.d.ts +41 -0
- package/types/generated/ui/Focus.d.ts +11 -0
- package/types/generated/ui/LoadingScreen.d.ts +2 -0
- package/types/generated/ui/UI.d.ts +57 -0
- package/types/nav.d.ts +52 -0
- package/types/physics.d.ts +592 -0
- package/types/style.d.ts +638 -0
- package/types/worker.d.ts +11 -0
- package/types/world.d.ts +772 -0
- package/ui/Focus.js +51 -0
- package/ui/LoadingScreen.js +42 -0
- package/ui/Parts.js +199 -0
- package/ui/UI.js +167 -0
- package/ui/defaults.js +85 -0
- package/ui/theme.js +124 -0
- package/ui/touchPart.js +49 -0
package/core/Rays.js
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
// Rays: engine.raycast / engine.pick, with the registry engine.rays.
|
|
2
|
+
// engine.raycast(origin, direction, { far, targets: 'static' | 'all' | [objects...], filter }) -> { point, distance, normal, object, face, entry?, kind? } | null
|
|
3
|
+
// engine.pick(ndcX, ndcY) // cast from screen coordinates (-1..1)
|
|
4
|
+
// hit.thing // point -> thing (computed when read): { id, kind, template, definedAt, model, mesh, material, fields, edit } (core/Inspect.js thingOf)
|
|
5
|
+
// engine.rays.addStatic(levelRoot) // register static objects (builds a BVH for speed); returns a handle { remove() }
|
|
6
|
+
// engine.rays.addProvider((origin, dir, far) => hit | null) // a module merges its own hits (rigid adds rigid bodies once installed); asked only when targets is 'all'
|
|
7
|
+
//
|
|
8
|
+
// Acceleration uses three-mesh-bvh: importing this file patches three's prototypes the way it recommends (Mesh.prototype.raycast etc.),
|
|
9
|
+
// after which any mesh with geometry.boundsTree takes the fast path and the rest fall back to three's per-triangle check.
|
|
10
|
+
// By default only visible objects are hit (itself and every parent visible) and they must be in the scene; occluders: true hits only camera blockers (including hidden col_ collision meshes).
|
|
11
|
+
// Exception: an object with userData.rayVisible = true still counts as visible while hidden, for hiding that merely swaps in something else on screen (hlod marks the original this way when it hides it far away and shows the merged proxy).
|
|
12
|
+
// A registered mesh is unregistered automatically when its geometry is disposed; engine.remove unregisters too.
|
|
13
|
+
// Terrain chunks and instanced vegetation are not registered (use engine.surface for ground height and vegetation.instanceAt for trees).
|
|
14
|
+
/** @import { Handle, Vec3Like } from '../types/common' */
|
|
15
|
+
/** @import { RaycastOptions, RayHit, RayProvider } from '../types/core' */
|
|
16
|
+
import * as THREE from 'three';
|
|
17
|
+
import { vec3 } from './math.js';
|
|
18
|
+
import { acceleratedRaycast, computeBoundsTree, disposeBoundsTree } from 'three-mesh-bvh';
|
|
19
|
+
import { thingOf } from './Inspect.js';
|
|
20
|
+
|
|
21
|
+
THREE.BufferGeometry.prototype.computeBoundsTree = computeBoundsTree;
|
|
22
|
+
THREE.BufferGeometry.prototype.disposeBoundsTree = disposeBoundsTree;
|
|
23
|
+
THREE.Mesh.prototype.raycast = acceleratedRaycast;
|
|
24
|
+
|
|
25
|
+
// Meshes under this many triangles get no BVH (blocky buildings etc.: the per-triangle check is faster)
|
|
26
|
+
const BVH_MIN = 256;
|
|
27
|
+
const triangles = g => (g.index ? g.index.count : g.attributes.position.count) / 3;
|
|
28
|
+
const _v = new THREE.Vector3(), _d = new THREE.Vector3(), _ndc = new THREE.Vector2(), _sph = new THREE.Sphere();
|
|
29
|
+
|
|
30
|
+
/** Cheap broadphase per static: does the ray pass the mesh's world bounding sphere within far? (the same test Mesh.raycast starts with, done before the parent walk) */
|
|
31
|
+
// Measured (5000 statics, 4 casts a frame, node): about 12 ms -> 3-5 ms per frame; caching the world sphere per static was slower than recomputing it.
|
|
32
|
+
// Still O(statics): a spatial grid over statics is the next step if a game registers tens of thousands.
|
|
33
|
+
function mayHit(ray, m, far) {
|
|
34
|
+
const g = m.geometry;
|
|
35
|
+
if (!g.boundingSphere) g.computeBoundingSphere();
|
|
36
|
+
_sph.copy(g.boundingSphere).applyMatrix4(m.matrixWorld);
|
|
37
|
+
if (!ray.intersectsSphere(_sph)) return false;
|
|
38
|
+
return far === Infinity || ray.origin.distanceTo(_sph.center) - _sph.radius <= far;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** engine.rays is the ray registry (engine.raycast hits whatever is registered here). */
|
|
42
|
+
export class Rays {
|
|
43
|
+
/** @internal */
|
|
44
|
+
constructor(engine) {
|
|
45
|
+
/** @internal */ this.engine = engine;
|
|
46
|
+
/** @internal */ this.providers = [];
|
|
47
|
+
/** Registered mesh -> { refs: registration count, occ: camera-blocker registration count } @type {Map<THREE.Object3D, { refs: number, occ: number }>} */
|
|
48
|
+
this.statics = new Map();
|
|
49
|
+
/** The three.js Raycaster (firstHitOnly is on) @type {any} */
|
|
50
|
+
this.ray = new THREE.Raycaster();
|
|
51
|
+
this.ray.firstHitOnly = true; // only the nearest hit per mesh (faster with a BVH)
|
|
52
|
+
this.ray.layers.enable(31); // originals drawn through engine.batching sit on layer 31 (core/batchGroups.js BATCH_LAYER) and must still be hit
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Register a static object and every mesh under it (an array also works; meshes over 256 triangles get a BVH); occluder: true also blocks the camera. Returns a handle { remove() }.
|
|
56
|
+
* Only visible objects are hit; hiding that just swaps in something else on screen (such as the far-away hlod original) is marked userData.rayVisible = true and is still hit.
|
|
57
|
+
* Unregisters automatically on geometry dispose or engine.remove.
|
|
58
|
+
* @param {THREE.Object3D | THREE.Object3D[]} obj
|
|
59
|
+
* @param {{ occluder?: boolean }} [opts]
|
|
60
|
+
* @returns {Handle}
|
|
61
|
+
* @example engine.rays.addStatic(house, { occluder: true });
|
|
62
|
+
*/
|
|
63
|
+
addStatic(obj, opts = {}) {
|
|
64
|
+
const { occluder = false } = opts;
|
|
65
|
+
const added = [];
|
|
66
|
+
for (const o of [].concat(obj)) o.traverse(m => {
|
|
67
|
+
if (!m.isMesh || m.isInstancedMesh || m.isSkinnedMesh || !m.geometry?.attributes.position) return;
|
|
68
|
+
if (!m.geometry.boundsTree && triangles(m.geometry) >= BVH_MIN) m.geometry.computeBoundsTree();
|
|
69
|
+
let s = this.statics.get(m);
|
|
70
|
+
if (!s) {
|
|
71
|
+
s = { refs: 0, occ: 0, geometry: m.geometry, onDispose: () => this._drop(m) };
|
|
72
|
+
m.geometry.addEventListener('dispose', s.onDispose);
|
|
73
|
+
}
|
|
74
|
+
s.refs++; if (occluder) s.occ++;
|
|
75
|
+
this.statics.set(m, s); added.push(m);
|
|
76
|
+
});
|
|
77
|
+
return { remove: () => {
|
|
78
|
+
for (const m of added.splice(0)) {
|
|
79
|
+
const s = this.statics.get(m); if (!s) continue;
|
|
80
|
+
s.refs--; if (occluder) s.occ--;
|
|
81
|
+
if (s.refs <= 0) this._drop(m);
|
|
82
|
+
}
|
|
83
|
+
} };
|
|
84
|
+
}
|
|
85
|
+
/** Unregister every mesh under the object (engine.remove calls this automatically) @param {THREE.Object3D} obj */
|
|
86
|
+
forget(obj) { obj.traverse(m => this._drop(m)); }
|
|
87
|
+
/** @internal */
|
|
88
|
+
_drop(m) {
|
|
89
|
+
const s = this.statics.get(m); if (!s) return;
|
|
90
|
+
s.geometry.removeEventListener('dispose', s.onDispose);
|
|
91
|
+
this.statics.delete(m);
|
|
92
|
+
}
|
|
93
|
+
/** @internal Clear all registrations (called by engine.dispose) */
|
|
94
|
+
dispose() { for (const m of [...this.statics.keys()]) this._drop(m); this.providers = []; }
|
|
95
|
+
/** A module merges its own hits (rigid adds rigid bodies; asked only when targets is 'all'). Returns a handle { remove() } @param {RayProvider} fn @returns {Handle} */
|
|
96
|
+
addProvider(fn) {
|
|
97
|
+
this.providers.push(fn);
|
|
98
|
+
return { remove: () => { this.providers = this.providers.filter(f => f !== fn); } };
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Cast a ray from origin along dir and return the nearest hit or null (same as engine.raycast).
|
|
102
|
+
* @param {Vec3Like} origin
|
|
103
|
+
* @param {Vec3Like} dir
|
|
104
|
+
* @param {RaycastOptions} [opts]
|
|
105
|
+
* @returns {RayHit | null}
|
|
106
|
+
*/
|
|
107
|
+
cast(origin, dir, opts = {}) {
|
|
108
|
+
const { far = Infinity, targets = 'static', filter = null, occluders = false } = opts;
|
|
109
|
+
const o = vec3(origin, _v), d = vec3(dir, _d).normalize();
|
|
110
|
+
this.ray.set(o, d); this.ray.near = 0; this.ray.far = far;
|
|
111
|
+
return this._cast(o, d, far, targets, filter, occluders);
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Cast from screen coordinates (-1..1) through the camera (same as engine.pick).
|
|
115
|
+
* @param {number} ndcX
|
|
116
|
+
* @param {number} ndcY
|
|
117
|
+
* @param {RaycastOptions} [opts]
|
|
118
|
+
* @returns {RayHit | null}
|
|
119
|
+
*/
|
|
120
|
+
pick(ndcX, ndcY, opts = {}) {
|
|
121
|
+
const { far = Infinity, targets = 'static', filter = null } = opts;
|
|
122
|
+
this.ray.setFromCamera(_ndc.set(ndcX, ndcY), this.engine.camera);
|
|
123
|
+
this.ray.far = far;
|
|
124
|
+
return this._cast(this.ray.ray.origin, this.ray.ray.direction, far, targets, filter, false);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** @internal */
|
|
128
|
+
_cast(o, d, far, targets, filter, occluders) {
|
|
129
|
+
const scene = this.engine.scene, hits = [];
|
|
130
|
+
let best = null;
|
|
131
|
+
const take = h => { if (h && h.distance <= far && (!best || h.distance < best.distance) && (!filter || filter(h))) best = h; };
|
|
132
|
+
if (Array.isArray(targets)) {
|
|
133
|
+
this.ray.firstHitOnly = false;
|
|
134
|
+
for (const h of this.ray.intersectObjects(targets, true)) { if (h.object.isMesh && shown(h.object)) { take(toHit(h)); if (best) break; } }
|
|
135
|
+
this.ray.firstHitOnly = true;
|
|
136
|
+
} else {
|
|
137
|
+
const ray = this.ray.ray;
|
|
138
|
+
for (const [m, s] of this.statics) {
|
|
139
|
+
if (!mayHit(ray, m, far)) continue; // most statics are nowhere near the ray: skip them before walking parents
|
|
140
|
+
if (occluders ? !s.occ || !inScene(m, scene) : !shown(m, scene)) continue;
|
|
141
|
+
hits.length = 0; m.raycast(this.ray, hits);
|
|
142
|
+
for (const h of hits) take(toHit(h));
|
|
143
|
+
}
|
|
144
|
+
if (targets === 'all') for (const p of this.providers) take(p(o.clone(), d.clone(), far));
|
|
145
|
+
}
|
|
146
|
+
if (best) { const e = this.engine, h = best; Object.defineProperty(h, 'thing', { get: () => thingOf(e, h.object, h), configurable: true }); } // computed only when read
|
|
147
|
+
return best;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
// Shown: itself and all parents visible (or marked userData.rayVisible); with a scene given it must also be in that scene
|
|
152
|
+
function shown(o, scene) {
|
|
153
|
+
for (let p = o; p; p = p.parent) { if (!p.visible && !p.userData.rayVisible) return false; if (p === scene) return true; }
|
|
154
|
+
return !scene;
|
|
155
|
+
}
|
|
156
|
+
function inScene(o, scene) { for (let p = o; p; p = p.parent) if (p === scene) return true; return false; }
|
|
157
|
+
function toHit(h) {
|
|
158
|
+
const normal = h.face ? h.face.normal.clone().transformDirection(h.object.matrixWorld) : null;
|
|
159
|
+
return { point: h.point, distance: h.distance, normal, object: h.object, face: h.face };
|
|
160
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
// Save storage layer: uses the browser's native IndexedDB (no third-party library) and falls back to localStorage when it is unavailable. Saves uses it; modules never touch it directly.
|
|
2
|
+
//
|
|
3
|
+
// Two stores in the database:
|
|
4
|
+
// slots key slot, value { slot, savedAt, json } world saves (json is JSON text, with no localStorage 5MB cap)
|
|
5
|
+
// blobs key [group, id], value { group, id, at, blob, meta } binary attachments (group tells the purpose, e.g. photos are 'photo'), stored separately and kept out of the world save
|
|
6
|
+
// On the localStorage fallback: only world saves are stored (key prefix + slot); attachments are not persisted (blobs reads return empty, writes are ignored).
|
|
7
|
+
// Every method returns a Promise; a failed write (quota, IndexedDB error) rejects and Saves reports it in one place.
|
|
8
|
+
|
|
9
|
+
const STORES = { slots: { keyPath: 'slot' }, blobs: { keyPath: ['group', 'id'] } };
|
|
10
|
+
|
|
11
|
+
/** Turn an IDBRequest / IDBTransaction into a Promise */
|
|
12
|
+
const req = r => new Promise((res, rej) => { r.onsuccess = () => res(r.result); r.onerror = () => rej(r.error); });
|
|
13
|
+
const tx = t => new Promise((res, rej) => { t.oncomplete = () => res(); t.onerror = t.onabort = () => rej(t.error); });
|
|
14
|
+
|
|
15
|
+
export class SaveStore {
|
|
16
|
+
/** @param {string} name Database name (each game's saveKey differs, so they do not interfere) @param {string} prefix Key prefix for the localStorage fallback */
|
|
17
|
+
constructor(name, prefix) {
|
|
18
|
+
this.name = name; this.prefix = prefix;
|
|
19
|
+
/** 'idb' | 'localStorage': meaningful only after open() completes */
|
|
20
|
+
this.mode = 'idb';
|
|
21
|
+
this.db = null;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Open the database; on failure (private mode, disabled) switch to localStorage. Returns whether IndexedDB is in use. */
|
|
25
|
+
async open() {
|
|
26
|
+
try {
|
|
27
|
+
if (typeof indexedDB === 'undefined') throw new Error('indexedDB is unavailable');
|
|
28
|
+
const r = indexedDB.open(this.name, 1);
|
|
29
|
+
r.onupgradeneeded = () => { for (const [n, o] of Object.entries(STORES)) if (!r.result.objectStoreNames.contains(n)) r.result.createObjectStore(n, o); };
|
|
30
|
+
this.db = await req(r);
|
|
31
|
+
this.db.onversionchange = () => this.db.close(); // yield when another tab wants to upgrade the database
|
|
32
|
+
return true;
|
|
33
|
+
} catch { this.mode = 'localStorage'; return false; }
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
_tx(store, mode = 'readonly') { return this.db.transaction(store, mode); }
|
|
37
|
+
|
|
38
|
+
/** All world saves: [{ slot, savedAt, json }] */
|
|
39
|
+
async slots() {
|
|
40
|
+
if (this.mode === 'localStorage') {
|
|
41
|
+
const out = [];
|
|
42
|
+
for (let i = 0; i < localStorage.length; i++) {
|
|
43
|
+
const k = localStorage.key(i);
|
|
44
|
+
if (!k.startsWith(this.prefix)) continue;
|
|
45
|
+
const json = localStorage.getItem(k);
|
|
46
|
+
try { out.push({ slot: k.slice(this.prefix.length), savedAt: JSON.parse(json).savedAt, json }); } catch { /* skip corrupt saves */ }
|
|
47
|
+
}
|
|
48
|
+
return out;
|
|
49
|
+
}
|
|
50
|
+
return req(this._tx('slots').objectStore('slots').getAll());
|
|
51
|
+
}
|
|
52
|
+
async putSlot(slot, savedAt, json) {
|
|
53
|
+
if (this.mode === 'localStorage') { localStorage.setItem(this.prefix + slot, json); return; }
|
|
54
|
+
const t = this._tx('slots', 'readwrite');
|
|
55
|
+
t.objectStore('slots').put({ slot, savedAt, json });
|
|
56
|
+
await tx(t);
|
|
57
|
+
}
|
|
58
|
+
async deleteSlot(slot) {
|
|
59
|
+
if (this.mode === 'localStorage') { localStorage.removeItem(this.prefix + slot); return; }
|
|
60
|
+
const t = this._tx('slots', 'readwrite');
|
|
61
|
+
t.objectStore('slots').delete(slot);
|
|
62
|
+
await tx(t);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** One group of attachments, newest first: [{ group, id, at, blob, meta }]; omit group for all */
|
|
66
|
+
async blobs(group) {
|
|
67
|
+
if (this.mode === 'localStorage') return [];
|
|
68
|
+
const all = await req(this._tx('blobs').objectStore('blobs').getAll());
|
|
69
|
+
return all.filter(b => group == null || b.group === group).sort((a, b) => b.at - a.at);
|
|
70
|
+
}
|
|
71
|
+
async putBlob(group, id, blob, meta = null, at = Date.now()) { // wall-clock: when the attachment was stored, used for ordering
|
|
72
|
+
if (this.mode === 'localStorage') return;
|
|
73
|
+
const t = this._tx('blobs', 'readwrite');
|
|
74
|
+
t.objectStore('blobs').put({ group, id, at, blob, meta });
|
|
75
|
+
await tx(t);
|
|
76
|
+
}
|
|
77
|
+
async deleteBlob(group, id) {
|
|
78
|
+
if (this.mode === 'localStorage') return;
|
|
79
|
+
const t = this._tx('blobs', 'readwrite');
|
|
80
|
+
t.objectStore('blobs').delete([group, id]);
|
|
81
|
+
await tx(t);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
close() { this.db?.close(); this.db = null; }
|
|
85
|
+
}
|
package/core/Saves.js
ADDED
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
// Saves: each module registers "how to save and load", and saving collects them all. Supports multiple slots, autosave, and export / import (text, file).
|
|
2
|
+
//
|
|
3
|
+
// engine.saves.register('garden', { version: 2, migrate: { 1: d => ({ ...d, beds: [] }) }, save, load }); // shape changed: raise version, add the step
|
|
4
|
+
// if (await engine.saves.save('slot1')) toast(engine, 'Saved'); await engine.saves.load('slot1'); // both return Promise<boolean>
|
|
5
|
+
// Text export / import and .json files (with attachments): saveFiles.js. Applying a save (checks, rollback): saveApply.js. Format: recipe 20 "Save format".
|
|
6
|
+
// Failure paths never lose data: a part whose save() throws, or a failed write, keeps the previous save (false + toast); a corrupt / newer / unmigratable
|
|
7
|
+
// save is refused before anything changes; a part whose load() throws rolls the game back to before the load.
|
|
8
|
+
// Storage: IndexedDB (SaveStore.js; localStorage fallback with a one-time warning). Every save is read into memory before start(), so list / check /
|
|
9
|
+
// export are synchronous; save / remove change memory first, then queue the disk write.
|
|
10
|
+
/** @import { SaveProvider } from '../types/core' */
|
|
11
|
+
import { SaveStore } from './SaveStore.js';
|
|
12
|
+
import { toast } from '../ui/UI.js';
|
|
13
|
+
import { warnOnce, checkOptions, fmt } from './validate.js';
|
|
14
|
+
import { reportError } from './errors.js';
|
|
15
|
+
import { codedError, coded } from './errorHints.js';
|
|
16
|
+
import { checkPartVersion, readSave } from './saveVersions.js';
|
|
17
|
+
import { exportSaveFile, importSaveFile, importText, SAVE_STRINGS } from './saveFiles.js';
|
|
18
|
+
import { applySave, loadSlot, adoptPart, afterLoad, collectParts } from './saveApply.js';
|
|
19
|
+
import { autosaveHook } from './session.js';
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
// Developer messages (console text for developers, never shown in the game UI)
|
|
23
|
+
const DEV_STRINGS = {
|
|
24
|
+
saveThrew: "save() of save part '{k}' threw ({msg}); slot '{slot}' was not written and keeps its previous save",
|
|
25
|
+
noIdb: '[saves] IndexedDB is unavailable (possibly private mode); saves fall back to localStorage (about 5MB cap) and attachments (such as photos) will not be saved.',
|
|
26
|
+
autosave: 'saves.autosave(minutes): minutes must be a positive number of minutes of play, got {got}',
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
/** engine.saves handles saving. Each module registers "how to save and load"; supports multiple slots, autosave and export / import. */
|
|
30
|
+
export class Saves {
|
|
31
|
+
/** @internal */
|
|
32
|
+
constructor(engine, { prefix = 'game-' } = {}) {
|
|
33
|
+
/** @internal */ this.engine = engine;
|
|
34
|
+
/** Save name prefix (start of the key names in the localStorage fallback, and of the IndexedDB database name) */
|
|
35
|
+
this.prefix = prefix + 'save-';
|
|
36
|
+
/** @internal */ this.providers = new Map();
|
|
37
|
+
/** @internal */ this._auto = null;
|
|
38
|
+
/** @internal Slot -> JSON text (all saves stay in memory: list / check / export are synchronous) */ this._json = new Map();
|
|
39
|
+
/** @internal Slot -> savedAt */ this._meta = new Map();
|
|
40
|
+
/** @internal Disk-write queue: earlier saves are written first */ this._queue = Promise.resolve();
|
|
41
|
+
/** @internal Parts of the last loaded save that no registered module owns (a module not installed in this build): written back unchanged on every save */
|
|
42
|
+
this._foreign = { parts: {}, versions: {} };
|
|
43
|
+
engine.i18n.add(SAVE_STRINGS);
|
|
44
|
+
/**
|
|
45
|
+
* Storage layer: saves in the IndexedDB slots store, attachments (by group, e.g. 'photo') in the blobs store; mode 'localStorage' without IndexedDB.
|
|
46
|
+
* @type {{ mode: 'idb' | 'localStorage', blobs(group?: string): Promise<{ group: string, id: string, at: number, blob: Blob, meta: any }[]>,
|
|
47
|
+
* putBlob(group: string, id: string, blob: Blob, meta?: any, at?: number): Promise<void>, deleteBlob(group: string, id: string): Promise<void> }}
|
|
48
|
+
*/
|
|
49
|
+
this.store = /** @type {any} */ (new SaveStore(this.prefix + 'db', this.prefix));
|
|
50
|
+
/** Has the save index been read into memory? (start() waits for it; game code rarely needs to care) */
|
|
51
|
+
this.ready = false;
|
|
52
|
+
/** Resolves once the save index is in memory; await it only to list / load before start() @type {Promise<void>} */
|
|
53
|
+
this.whenReady = this._init().then(() => { this.ready = true; });
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Register "how to save and load"; key is this part's name in the save. Parts with first: true load first (the level); a load returning a Promise makes later
|
|
57
|
+
* parts wait.
|
|
58
|
+
* version (default 1): raise it by 1 whenever what save() returns changes shape, and add migrate[oldVersion] = data => newData; load sees only the current
|
|
59
|
+
* shape.
|
|
60
|
+
* A save whose part is newer than this build's version is refused as a whole (load returns false, the save is kept).
|
|
61
|
+
* A part registered after a save was loaded (a module installed later) is handed its data from that save at once.
|
|
62
|
+
* atomic: true joins this part to atomic ops: it is copied before an atomic op runs and put back if the op fails (plain data only; afterLoad does not run on rollback).
|
|
63
|
+
* @param {string} key
|
|
64
|
+
* @param {SaveProvider} provider
|
|
65
|
+
* @example
|
|
66
|
+
* engine.saves.register('garden', { save: () => garden.toJSON(), load: d => garden.fromJSON(d) });
|
|
67
|
+
* // later the format gains beds: version 2, and a step that upgrades version-1 data
|
|
68
|
+
* engine.saves.register('garden', { version: 2, migrate: { 1: d => ({ ...d, beds: [] }) }, save: () => garden.toJSON(), load: d => garden.fromJSON(d) });
|
|
69
|
+
*/
|
|
70
|
+
register(key, provider) {
|
|
71
|
+
checkOptions(`saves.register('${key}')`, provider, ['save', 'load', 'first', 'version', 'migrate', 'atomic']);
|
|
72
|
+
const { save, load, first = false, version = 1, migrate = {}, atomic = false } = provider;
|
|
73
|
+
checkPartVersion(key, version, migrate);
|
|
74
|
+
this.providers.set(key, { save, load, first, version, migrate, atomic: atomic === true });
|
|
75
|
+
this.engine.session._late(key); // a part registered after start() (a module installed later) joins the new-game state as it is now
|
|
76
|
+
if (key in this._foreign.parts) adoptPart(this, key);
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* The save versions this build reads, per part: { world: 1, clock: 1, ... }. A save whose part is newer is refused; an older one is migrated.
|
|
80
|
+
* @returns {Record<string, number>}
|
|
81
|
+
*/
|
|
82
|
+
get versions() { return Object.fromEntries([...this.providers].map(([k, p]) => [k, p.version])); }
|
|
83
|
+
|
|
84
|
+
// ---------- storage ----------
|
|
85
|
+
/** @internal */
|
|
86
|
+
async _init() {
|
|
87
|
+
const idb = await this.store.open();
|
|
88
|
+
if (!idb) warnOnce(coded('indexeddb', DEV_STRINGS.noIdb));
|
|
89
|
+
try {
|
|
90
|
+
for (const r of await this.store.slots()) if (!this._json.has(r.slot)) { this._json.set(r.slot, r.json); this._meta.set(r.slot, r.savedAt); }
|
|
91
|
+
} catch (e) { this._fail(e); }
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Queue a disk write (runs in call order once storage is ready; flush waits for it; used by attachments such as photos).
|
|
95
|
+
* @template T
|
|
96
|
+
* @param {() => Promise<T>} fn
|
|
97
|
+
* @returns {Promise<T>}
|
|
98
|
+
*/
|
|
99
|
+
queue(fn) {
|
|
100
|
+
const p = this._queue.then(() => this.whenReady).then(fn);
|
|
101
|
+
this._queue = p.catch(() => {});
|
|
102
|
+
return p;
|
|
103
|
+
}
|
|
104
|
+
/** @internal A save failed: console (or the error tiers, for a part that threw) plus an on-screen toast, never silent */
|
|
105
|
+
_fail(err, slot, report = false) {
|
|
106
|
+
const why = this.engine.t('saves.failed', { why: err?.name === 'QuotaExceededError' ? 'storage full' : err?.message || String(err) });
|
|
107
|
+
if (report) reportError(this.engine, err, `saves.save('${slot}')`);
|
|
108
|
+
else console.error(coded('save-write', `[saves] failed to write ${slot ? `slot "${slot}"` : 'save'}`), err);
|
|
109
|
+
toast(this.engine, why, { kind: 'error', ms: 5000 });
|
|
110
|
+
}
|
|
111
|
+
/** Wait for all queued disk writes to finish (for tests and before the page closes) @returns {Promise<void>} */
|
|
112
|
+
flush() { return this._queue; }
|
|
113
|
+
|
|
114
|
+
/** @internal Collect every part: { data, failed: [[key, error]] }. Parts of the loaded save that no module owns are carried along. */
|
|
115
|
+
_collect() { return collectParts(this); }
|
|
116
|
+
/**
|
|
117
|
+
* Collect the data of every part (does not write to the browser): { format, savedAt, versions, parts }.
|
|
118
|
+
* A part whose save() throws is left out and reported (engine.error in dev); save() instead refuses to write such a save.
|
|
119
|
+
* @returns {{ format: number, savedAt: number, versions: Record<string, number>, parts: Record<string, any> }}
|
|
120
|
+
*/
|
|
121
|
+
collect() {
|
|
122
|
+
const { data, failed } = this._collect();
|
|
123
|
+
for (const [k, e] of failed) reportError(this.engine, e, `save() of save part '${k}'`);
|
|
124
|
+
return data;
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Can this slot be loaded? null when it can, else why not (checked without touching the game):
|
|
128
|
+
* 'missing' | 'corrupt' (unreadable) | 'tooNew' (a newer save format or part) | 'migrate' (an upgrade step is missing or throws).
|
|
129
|
+
* @param {string} [slot]
|
|
130
|
+
* @returns {null | 'missing' | 'corrupt' | 'tooNew' | 'migrate'}
|
|
131
|
+
* @example if (engine.saves.check('slot1') === 'tooNew') showUpdateHint();
|
|
132
|
+
*/
|
|
133
|
+
check(slot = 'auto') { const r = readSave(this._json.get(slot), this.providers, slot); return 'reason' in r ? r.reason : null; }
|
|
134
|
+
/**
|
|
135
|
+
* Apply a save's data (an object from collect(), or save text) onto the running game. Resolves true when every part loaded.
|
|
136
|
+
* Refused before anything changes (false, toast) when the data is corrupt, from a newer build or cannot be migrated.
|
|
137
|
+
* After every part loaded it runs the modules' afterLoad hooks (gameplay frozen until they resolve), for saves.load, session.newGame / quit and direct calls
|
|
138
|
+
* alike.
|
|
139
|
+
* If a part's load throws, the game is rolled back to how it was before (every part reloads its pre-load state) and it resolves false; the error goes through
|
|
140
|
+
* the error tiers.
|
|
141
|
+
* The state changes synchronously unless a part's load is async; only the result is a Promise.
|
|
142
|
+
* @param {any} data
|
|
143
|
+
* @param {string} [slot] for messages only
|
|
144
|
+
* @returns {Promise<boolean>}
|
|
145
|
+
*/
|
|
146
|
+
apply(data, slot = '(data)') { return applySave(this, data, slot).then(async ok => { if (ok) { this.engine.ops.revision++; await afterLoad(this.engine); } return ok; }); } // a load is a state change: ops.revision moves
|
|
147
|
+
/** @internal Put a save in memory and queue the disk write; returns Promise<boolean> (write succeeded) */
|
|
148
|
+
_put(slot, json, savedAt) {
|
|
149
|
+
const prev = this._json.get(slot), prevAt = this._meta.get(slot);
|
|
150
|
+
this._json.set(slot, json); this._meta.set(slot, savedAt);
|
|
151
|
+
return this.queue(() => this.store.putSlot(slot, savedAt, json)).then(() => true, e => {
|
|
152
|
+
// the disk still holds the previous save, so memory goes back to it (unless a later save already replaced this one):
|
|
153
|
+
// list / load / continue never offer a save that is not stored
|
|
154
|
+
if (this._json.get(slot) === json) {
|
|
155
|
+
if (prev == null) { this._json.delete(slot); this._meta.delete(slot); } else { this._json.set(slot, prev); this._meta.set(slot, prevAt); }
|
|
156
|
+
}
|
|
157
|
+
this._fail(e, slot); return false;
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* Save into a slot (default 'auto'). Returns Promise<boolean>
|
|
162
|
+
* (resolves after the write to IndexedDB: true on success, false with a toast and console error on failure).
|
|
163
|
+
* The in-memory save updates immediately, so a following load / list / export sees it at once; the 'save:written' event fires only after the write succeeds.
|
|
164
|
+
* If any part's save() throws, nothing is written and the slot keeps its previous save (false). A failed write keeps the previous save too.
|
|
165
|
+
* Show "saved" only after the result is true.
|
|
166
|
+
* @param {string} [slot]
|
|
167
|
+
* @returns {Promise<boolean>}
|
|
168
|
+
* @example if (await engine.saves.save('slot1')) toast(engine, 'Saved'); // on false the engine already showed why
|
|
169
|
+
*/
|
|
170
|
+
save(slot = 'auto') {
|
|
171
|
+
let data, json;
|
|
172
|
+
try {
|
|
173
|
+
const r = this._collect();
|
|
174
|
+
if (r.failed.length) {
|
|
175
|
+
const [k, err] = r.failed[0];
|
|
176
|
+
this._fail(Object.assign(codedError('save-part-threw', fmt(DEV_STRINGS.saveThrew, { k, slot, msg: err?.message ?? String(err) })), { cause: err }), slot, true);
|
|
177
|
+
return Promise.resolve(false);
|
|
178
|
+
}
|
|
179
|
+
data = r.data; json = JSON.stringify(data);
|
|
180
|
+
} catch (e) { this._fail(e, slot); return Promise.resolve(false); }
|
|
181
|
+
return this._put(slot, json, data.savedAt).then(ok => { if (ok) this.engine.events.emit('save:written', slot); return ok; });
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
184
|
+
* Load a slot onto the running playthrough (a quick load: what the game added during play stays) and resolve true on success; the 'save:loaded' event fires
|
|
185
|
+
* on success.
|
|
186
|
+
* A missing slot resolves false; a corrupt / too new / unmigratable save resolves false with a toast and changes nothing; a part whose load throws rolls the
|
|
187
|
+
* game back.
|
|
188
|
+
* To continue or retry with nothing of the current playthrough left over, use engine.session.load(slot).
|
|
189
|
+
* @param {string} [slot]
|
|
190
|
+
* @returns {Promise<boolean>}
|
|
191
|
+
* @example if (!(await engine.saves.load('quick'))) toast(engine, 'No quick save');
|
|
192
|
+
*/
|
|
193
|
+
load(slot = 'auto') { return this._load(slot); }
|
|
194
|
+
/** @internal Load a slot; with base (a collect() result) the save goes on top of it, so a part missing from the save gets base's state (session.load) */
|
|
195
|
+
_load(slot, base) { return loadSlot(this, slot, base); }
|
|
196
|
+
/** All slots, newest first (synchronous, reads the in-memory index) @returns {{ slot: string, savedAt: number }[]} */
|
|
197
|
+
list() {
|
|
198
|
+
return [...this._meta].map(([slot, savedAt]) => ({ slot, savedAt })).sort((a, b) => b.savedAt - a.savedAt);
|
|
199
|
+
}
|
|
200
|
+
/** Delete a slot. Returns a Promise (disk write done); awaiting is optional @param {string} slot @returns {Promise<void>} */
|
|
201
|
+
remove(slot) {
|
|
202
|
+
this._json.delete(slot); this._meta.delete(slot);
|
|
203
|
+
return this.queue(() => this.store.deleteSlot(slot)).catch(e => this._fail(e, slot));
|
|
204
|
+
}
|
|
205
|
+
/** Export as a piece of text (can be copied as a backup; synchronous, without binary attachments) @param {string} [slot] @returns {string} */
|
|
206
|
+
export(slot = 'auto') { try { return btoa(unescape(encodeURIComponent(this._json.get(slot) || ''))); } catch { return ''; } }
|
|
207
|
+
/**
|
|
208
|
+
* Import text from export() into a slot (default 'imported'); checked like importFile and written before it resolves.
|
|
209
|
+
* Resolves true once stored (save:imported fires), false when the text is not a save or the write failed. It does not load the slot.
|
|
210
|
+
* @param {string} text
|
|
211
|
+
* @param {string} [slot]
|
|
212
|
+
* @returns {Promise<boolean>}
|
|
213
|
+
*/
|
|
214
|
+
import(text, slot = 'imported') { return importText(this, text, slot); }
|
|
215
|
+
|
|
216
|
+
// ---------- files ----------
|
|
217
|
+
/**
|
|
218
|
+
* Download a save file (.json): the save plus every binary attachment (as data: text, so the file is larger; { files: false } exports the save only).
|
|
219
|
+
* Restores everything when browser data is wiped on a phone. Returns Promise<boolean>.
|
|
220
|
+
* @param {string} [slot]
|
|
221
|
+
* @param {{ files?: boolean }} [opts]
|
|
222
|
+
* @returns {Promise<boolean>}
|
|
223
|
+
* @example engine.saves.exportFile('slot1');
|
|
224
|
+
*/
|
|
225
|
+
exportFile(slot = 'auto', opts = {}) { return exportSaveFile(this, slot, opts); }
|
|
226
|
+
/**
|
|
227
|
+
* Restore from a save file into slot (default 'imported', so a shared file never overwrites 'auto'). file is a File / Blob; omit it to open a file picker.
|
|
228
|
+
* Everything is checked first (file marker and format, the save inside, attachments must be data: URLs: nothing is fetched).
|
|
229
|
+
* Returns the slot name on success, and null if cancelled, the file is invalid or the write failed (a toast was already shown). It restores the slot only and
|
|
230
|
+
* does not load it.
|
|
231
|
+
* @param {Blob} [file]
|
|
232
|
+
* @param {string} [slot]
|
|
233
|
+
* @returns {Promise<string | null>}
|
|
234
|
+
*/
|
|
235
|
+
importFile(file, slot) { return importSaveFile(this, file, slot); }
|
|
236
|
+
|
|
237
|
+
/**
|
|
238
|
+
* Autosave into 'auto' every `minutes` minutes of play: counted in fixed seconds, so it waits while paused, frozen or in a menu that freezes the game,
|
|
239
|
+
* and it never saves while no playthrough runs (the title screen, during newGame / load / quit) or after a gameplay error. Returns a handle; remove() stops
|
|
240
|
+
* it.
|
|
241
|
+
* Calling it again replaces the previous autosave.
|
|
242
|
+
* @param {number} [minutes]
|
|
243
|
+
* @returns {{ remove(): void }}
|
|
244
|
+
* @example engine.saves.autosave(3); // once at boot: it waits by itself while no playthrough runs
|
|
245
|
+
*/
|
|
246
|
+
autosave(minutes = 3) {
|
|
247
|
+
if (!(minutes > 0) || !Number.isFinite(minutes)) throw codedError('save-autosave', fmt(DEV_STRINGS.autosave, { got: JSON.stringify(minutes) }));
|
|
248
|
+
this._auto?.remove();
|
|
249
|
+
const h = autosaveHook(this, minutes * 60, () => { if (this._auto === h) this._auto = null; });
|
|
250
|
+
return (this._auto = h);
|
|
251
|
+
}
|
|
252
|
+
/** @internal Stop autosave (called by engine.dispose) */
|
|
253
|
+
dispose() { this._auto?.remove(); this._queue.finally(() => this.store.close()); } // close the database only after queued writes finish
|
|
254
|
+
}
|