threedog 0.7.0 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +411 -1
- package/README.md +8 -11
- package/core/{Animator.js → assets/Animator.js} +30 -18
- package/core/{Assets.js → assets/Assets.js} +131 -56
- package/core/{Baked.js → assets/Baked.js} +4 -4
- package/core/assets/assetEntry.js +302 -0
- package/core/{assetHot.js → assets/assetHot.js} +9 -7
- package/core/{assetLoad.js → assets/assetLoad.js} +55 -16
- package/core/assets/assetLod.js +113 -0
- package/core/{assetManifest.js → assets/assetManifest.js} +19 -11
- package/core/{assetReport.js → assets/assetReport.js} +7 -14
- package/core/{namedModel.js → assets/namedModel.js} +17 -13
- package/core/{Audio.js → audio/Audio.js} +47 -25
- package/core/{audioRules.js → audio/audioRules.js} +8 -5
- package/core/{audioVoice.js → audio/audioVoice.js} +17 -30
- package/core/{Events.js → base/Events.js} +3 -3
- package/core/{I18n.js → base/I18n.js} +15 -12
- package/core/{Random.js → base/Random.js} +7 -4
- package/core/{Vars.js → base/Vars.js} +14 -4
- package/core/{easing.js → base/easing.js} +1 -1
- package/core/{errorCodes.js → base/errorCodes.js} +151 -125
- package/core/{errorHints.js → base/errorHints.js} +17 -10
- package/core/{errors.js → base/errors.js} +12 -10
- package/core/{events.generated.js → base/events.generated.js} +11 -0
- package/core/base/follows.js +26 -0
- package/core/base/math.js +66 -0
- package/core/{params.js → base/params.js} +5 -6
- package/core/base/saveValues.js +81 -0
- package/core/base/sections.js +97 -0
- package/core/base/spelling.js +32 -0
- package/core/base/util.js +32 -0
- package/core/{validate.js → base/validate.js} +34 -34
- package/core/{Engine.js → engine/Engine.js} +137 -91
- package/core/{Loading.js → engine/Loading.js} +34 -5
- package/core/{copies.js → engine/copies.js} +4 -4
- package/core/{headlessLoad.js → engine/headlessLoad.js} +32 -15
- package/core/{lifecycle.js → engine/lifecycle.js} +41 -34
- package/core/{loop.js → engine/loop.js} +88 -49
- package/core/engine/moduleSlots.js +176 -0
- package/core/{moduleTypes.js → engine/moduleTypes.js} +26 -14
- package/core/engine/modules.js +503 -0
- package/core/{page.js → engine/page.js} +59 -29
- package/core/{plugins.js → engine/plugins.js} +21 -12
- package/core/{services.js → engine/services.js} +50 -40
- package/core/{startup.js → engine/startup.js} +66 -54
- package/core/{Input.js → input/Input.js} +67 -39
- package/core/{inputContext.js → input/inputContext.js} +14 -5
- package/core/input/inputKeyboard.js +39 -0
- package/core/{inputPad.js → input/inputPad.js} +24 -3
- package/core/{inputPointer.js → input/inputPointer.js} +11 -3
- package/core/input/inputSeat.js +66 -0
- package/core/{inputTouch.js → input/inputTouch.js} +24 -7
- package/core/{Budget.js → inspect/Budget.js} +21 -20
- package/core/{DebugOverrides.js → inspect/DebugOverrides.js} +43 -18
- package/core/{Describe.js → inspect/Describe.js} +34 -26
- package/core/{Inspect.js → inspect/Inspect.js} +39 -10
- package/core/{InspectMaterials.js → inspect/InspectMaterials.js} +7 -8
- package/core/{InspectPerf.js → inspect/InspectPerf.js} +19 -13
- package/core/{InspectScene.js → inspect/InspectScene.js} +8 -5
- package/core/{MaterialInfo.js → inspect/MaterialInfo.js} +3 -2
- package/core/{UrlState.js → inspect/UrlState.js} +60 -24
- package/core/{catalog.js → inspect/catalog.js} +15 -8
- package/core/{checks.js → inspect/checks.js} +7 -5
- package/core/{debugView.js → inspect/debugView.js} +4 -4
- package/core/{describeRender.js → inspect/describeRender.js} +24 -22
- package/core/{describeText.js → inspect/describeText.js} +17 -8
- package/core/inspect/geometryWatch.js +38 -0
- package/core/{lightWatch.js → inspect/lightWatch.js} +8 -8
- package/core/inspect/metadata.generated.js +4140 -0
- package/core/{pictureWriters.js → inspect/pictureWriters.js} +130 -47
- package/core/{shaderCost.js → inspect/shaderCost.js} +1 -1
- package/core/inspect/toolDoor.js +21 -0
- package/core/inspect/valueHistory.js +35 -0
- package/core/{Ops.js → ops/Ops.js} +44 -14
- package/core/{control.js → ops/control.js} +57 -31
- package/core/ops/holds.js +140 -0
- package/core/{opsAtomic.js → ops/opsAtomic.js} +18 -5
- package/core/{opsCheck.js → ops/opsCheck.js} +11 -10
- package/core/{opsFail.js → ops/opsFail.js} +5 -7
- package/core/{opsGuard.js → ops/opsGuard.js} +3 -3
- package/core/{opsRun.js → ops/opsRun.js} +9 -6
- package/core/{owned.js → ops/owned.js} +33 -19
- package/core/{sharedPoint.js → ops/sharedPoint.js} +13 -16
- package/core/{stackFrames.js → ops/stackFrames.js} +2 -2
- package/core/{stacks.js → ops/stacks.js} +34 -15
- package/core/{wrap.js → ops/wrap.js} +8 -6
- package/core/{SaveStore.js → saves/SaveStore.js} +53 -27
- package/core/{Saves.js → saves/Saves.js} +171 -54
- package/core/saves/saveApply.js +312 -0
- package/core/{saveFiles.js → saves/saveFiles.js} +45 -38
- package/core/{saveVersions.js → saves/saveVersions.js} +24 -23
- package/core/saves/session.js +231 -0
- package/core/saves/stateReplace.js +184 -0
- package/core/{Rays.js → scene/Rays.js} +44 -30
- package/core/{Views.js → scene/Views.js} +16 -8
- package/core/{adaptive.js → scene/adaptive.js} +19 -9
- package/core/{canvasBox.js → scene/canvasBox.js} +4 -3
- package/core/scene/compositeGround.js +72 -0
- package/core/scene/floor.js +17 -0
- package/core/{gameLights.js → scene/gameLights.js} +17 -7
- package/core/{grayMap.js → scene/grayMap.js} +8 -2
- package/core/{grid.js → scene/grid.js} +6 -4
- package/core/{gridLoad.js → scene/gridLoad.js} +1 -1
- package/core/scene/ground.contract.js +14 -0
- package/core/scene/ground.js +139 -0
- package/core/{movement.js → scene/movement.js} +3 -3
- package/core/{pictureSlots.js → scene/pictureSlots.js} +2 -2
- package/core/scene/pixel.js +154 -0
- package/core/scene/pixelRatio.js +167 -0
- package/core/{sceneDelta.js → scene/sceneDelta.js} +5 -5
- package/core/{sceneMethods.js → scene/sceneMethods.js} +43 -15
- package/core/scene/stepPoses.js +60 -0
- package/core/{targeting.js → scene/targeting.js} +4 -5
- package/core/{thingExplain.js → scene/thingExplain.js} +7 -6
- package/core/{thingOps.js → scene/thingOps.js} +25 -16
- package/core/{things.js → scene/things.js} +18 -5
- package/core/{threePatches.js → scene/threePatches.js} +1 -1
- package/core/{tier.js → scene/tier.js} +10 -0
- package/core/scene/view.js +161 -0
- package/core/{Batching.js → stream/Batching.js} +85 -28
- package/core/{Stream.js → stream/Stream.js} +80 -38
- package/core/{batchGroups.js → stream/batchGroups.js} +11 -9
- package/core/{chunkStream.js → stream/chunkStream.js} +40 -0
- package/core/{scatter.js → stream/scatter.js} +7 -4
- package/core/{streamSources.js → stream/streamSources.js} +14 -8
- package/core/{Commits.js → threads/Commits.js} +17 -11
- package/core/{Jobs.js → threads/Jobs.js} +25 -13
- package/core/{Threads.js → threads/Threads.js} +21 -18
- package/core/{threadPure.js → threads/threadPure.js} +7 -5
- package/core/{threadServe.js → threads/threadServe.js} +3 -3
- package/core/{Clock.js → time/Clock.js} +20 -11
- package/core/{dayTime.js → time/dayTime.js} +5 -1
- package/core/{skip.js → time/skip.js} +28 -21
- package/core/{time.js → time/time.js} +32 -20
- package/core/{uiClock.js → time/uiClock.js} +4 -4
- package/docs/AI.md +92 -72
- package/docs/API.md +33 -28
- package/docs/CODEMAP.md +121 -200
- package/docs/COMMANDS.md +77 -70
- package/docs/CONVENTIONS.md +167 -24
- package/docs/MIGRATING-0.8.md +171 -0
- package/docs/MIGRATING-1.0.md +101 -0
- package/docs/THREE.md +140 -38
- package/docs/api/assets.md +12 -13
- package/docs/api/audio.md +6 -5
- package/docs/api/budget.md +4 -4
- package/docs/api/calendar.md +10 -11
- package/docs/api/cameraRig.md +32 -29
- package/docs/api/characters.md +35 -24
- package/docs/api/clock.md +1 -1
- package/docs/api/collider3d.md +9 -0
- package/docs/api/collision.md +12 -9
- package/docs/api/content.md +18 -17
- package/docs/api/dialogue.md +5 -4
- package/docs/api/engine.md +58 -54
- package/docs/api/events.md +17 -6
- package/docs/api/flow.md +1 -1
- package/docs/api/grids.md +1 -1
- package/docs/api/ground.md +6 -7
- package/docs/api/hud.md +2 -2
- package/docs/api/i18n.md +6 -6
- package/docs/api/input.md +9 -8
- package/docs/api/interactions.md +5 -5
- package/docs/api/inventory.md +10 -10
- package/docs/api/jobs.md +5 -5
- package/docs/api/level.md +10 -9
- package/docs/api/lightPool.md +1 -6
- package/docs/api/music.md +3 -3
- package/docs/api/nav.md +14 -12
- package/docs/api/openWorld.md +1 -1
- package/docs/api/particles.md +10 -7
- package/docs/api/photo.md +4 -2
- package/docs/api/pickups.md +3 -3
- package/docs/api/post.md +21 -5
- package/docs/api/quests.md +7 -5
- package/docs/api/rays.md +7 -7
- package/docs/api/rigid.md +29 -19
- package/docs/api/saves.md +13 -11
- package/docs/api/settings.md +9 -8
- package/docs/api/sky.md +8 -7
- package/docs/api/stream.md +8 -9
- package/docs/api/swarm.md +34 -0
- package/docs/api/terrain.md +6 -8
- package/docs/api/terrainDraw.md +2 -2
- package/docs/api/timeline.md +4 -4
- package/docs/api/tools.md +27 -22
- package/docs/api/triggers.md +2 -0
- package/docs/api/vars.md +1 -1
- package/docs/api/vegetation.md +4 -3
- package/docs/api/vegetationDraw.md +2 -2
- package/docs/api/water.md +7 -3
- package/docs/api/weather.md +27 -12
- package/docs/api/weatherDraw.md +4 -4
- package/docs/api/world.md +6 -6
- package/docs/recipes/01-new-game.md +28 -43
- package/docs/recipes/02-npc.md +21 -23
- package/docs/recipes/03-items-pickups.md +37 -53
- package/docs/recipes/04-quests.md +5 -4
- package/docs/recipes/05-props-bake.md +34 -44
- package/docs/recipes/06-clock-events.md +31 -22
- package/docs/recipes/07-flow-scenes-pause.md +30 -32
- package/docs/recipes/08-weather-sky.md +91 -37
- package/docs/recipes/09-materials-lights-models.md +25 -39
- package/docs/recipes/10-blender-level.md +22 -11
- package/docs/recipes/11-vehicles.md +44 -24
- package/docs/recipes/12-navmesh.md +60 -15
- package/docs/recipes/13-animation.md +70 -22
- package/docs/recipes/14-custom-module.md +33 -20
- package/docs/recipes/15-perf.md +51 -28
- package/docs/recipes/16-dev-bridge.md +39 -58
- package/docs/recipes/18-world.md +49 -28
- package/docs/recipes/19-shooting-picking.md +7 -4
- package/docs/recipes/20-content-actions-save.md +55 -40
- package/docs/recipes/21-camera.md +47 -25
- package/docs/recipes/22-shop-gold.md +21 -16
- package/docs/recipes/23-ops.md +28 -24
- package/docs/recipes/26-ui-parts.md +25 -14
- package/docs/recipes/27-net.md +3 -5
- package/docs/recipes/28-terrain.md +119 -23
- package/docs/recipes/29-grid.md +3 -3
- package/docs/recipes/30-templates.md +63 -30
- package/docs/recipes/31-audio.md +7 -7
- package/docs/recipes/32-action-game.md +21 -11
- package/docs/recipes/33-stream-sources.md +6 -3
- package/docs/recipes/34-environment-lighting.md +72 -25
- package/docs/recipes/35-picture-from-reference.md +20 -23
- package/docs/recipes/36-ground-plants.md +106 -0
- package/docs/recipes/40-scene.md +18 -21
- package/docs/recipes/43-shader-patches-surfaces.md +27 -48
- package/docs/recipes/44-water-weather-hooks.md +56 -50
- package/docs/recipes/45-cascaded-shadows.md +41 -20
- package/docs/recipes/46-blender-art-route.md +9 -10
- package/docs/recipes/49-game-module-contract.md +7 -6
- package/docs/recipes/50-own-renderer.md +3 -2
- package/docs/recipes/51-capability-catalog.md +14 -8
- package/docs/recipes/52-around-the-picture.md +56 -100
- package/docs/recipes/53-ground-up-close.md +61 -24
- package/docs/recipes/55-mods-time-wrap.md +17 -20
- package/docs/recipes/56-webgpu-tsl.md +28 -15
- package/docs/recipes/57-control.md +39 -12
- package/docs/recipes/58-input.md +15 -2
- package/docs/recipes/59-depth-post-effects.md +1 -1
- package/docs/recipes/60-judge-the-picture.md +30 -25
- package/docs/recipes/62-picture-code.md +129 -39
- package/docs/recipes/63-third-person-start.md +19 -5
- package/docs/recipes/64-particles.md +54 -5
- package/docs/recipes/65-swarm.md +140 -0
- package/docs/recipes/66-common-tasks.md +313 -0
- package/examples/action/.threedog/content-index.json +1 -1
- package/examples/action/GAMEMAP.md +5 -5
- package/examples/perf-island/.threedog/content-index.json +1 -0
- package/examples/{sheepisland → perf-island}/GAMEMAP.md +15 -14
- package/examples/{sheepisland → perf-island}/assets.js +1 -1
- package/examples/{sheepisland → perf-island}/main.js +8 -8
- package/examples/{sheepisland → perf-island}/models.js +1 -1
- package/examples/{sheepisland → perf-island}/params.js +1 -1
- package/examples/{sheepisland → perf-island}/picture/index.js +1 -1
- package/examples/{sheepisland → perf-island}/picture/palette.js +2 -2
- package/examples/{sheepisland → perf-island}/views.js +1 -1
- package/examples/plain-picture/GAMEMAP.md +4 -1
- package/examples/rc2d/GAMEMAP.md +4 -3
- package/examples/rc2d/main.js +1 -3
- package/examples/rc2d/rc2d.js +1 -1
- package/examples/styletest/.threedog/content-index.json +1 -1
- package/examples/styletest/GAMEMAP.md +6 -5
- package/examples/techniques/contact-shadows/contactShadows.js +1 -1
- package/examples/techniques/contact-shadows/main.js +1 -1
- package/examples/techniques/interior-light/main.js +1 -1
- package/examples/techniques/modular-building/README.md +7 -6
- package/examples/techniques/outlines-and-rim/picture/post.js +1 -1
- package/examples/techniques/procedural-animation/README.md +1 -1
- package/examples/webgpu-tsl/GAMEMAP.md +2 -1
- package/examples/world/.threedog/content-index.json +1 -1
- package/examples/world/GAMEMAP.md +9 -7
- package/examples/world/main.js +3 -3
- package/examples/world/picture/sky.js +1 -1
- package/index.d.ts +16 -12
- package/index.js +53 -32
- package/llms.txt +11 -14
- package/modules/ambience/Ambience.js +16 -11
- package/modules/calendar/Calendar.js +19 -19
- package/modules/calendar/index.js +18 -16
- package/modules/calendar/schedule.js +11 -6
- package/modules/calendar/seasons.js +7 -7
- package/modules/camera/FirstPersonCamera.js +5 -5
- package/modules/camera/FixedCamera.js +43 -30
- package/modules/camera/FollowCamera.js +24 -15
- package/modules/camera/RtsCamera.js +12 -11
- package/modules/camera/common.js +72 -37
- package/modules/camera/contract.js +1 -0
- package/modules/camera/pixelSnap.js +62 -0
- package/modules/characters/Character.js +166 -70
- package/modules/characters/NPC.js +84 -44
- package/modules/characters/assetModel.js +16 -12
- package/modules/characters/astar.js +48 -27
- package/modules/characters/behaviors.js +4 -5
- package/modules/characters/character.contract.js +21 -0
- package/modules/characters/contract.js +17 -3
- package/modules/characters/index.js +240 -226
- package/modules/characters/moveHelpers.js +88 -12
- package/modules/characters/mover.contract.js +14 -0
- package/modules/characters/movers/common.js +22 -18
- package/modules/characters/movers/manual.js +1 -1
- package/modules/characters/movers/rapier.js +18 -10
- package/modules/characters/movers/simple.js +26 -13
- package/modules/characters/movers/support.js +24 -13
- package/modules/characters/npcAvoid.js +19 -16
- package/modules/characters/npcSim.js +88 -32
- package/modules/characters/npcView.js +19 -11
- package/modules/characters/pathAsync.js +81 -29
- package/modules/characters/pathJob.js +38 -21
- package/modules/characters/pathWorker.js +1 -1
- package/modules/characters/player.js +120 -0
- package/modules/characters/playerStrings.js +2 -2
- package/modules/characters/proceduralRig.js +2 -2
- package/modules/characters/seat.js +56 -0
- package/modules/characters/useModel.js +3 -3
- package/modules/characters/vehicle.contract.js +8 -5
- package/modules/characters/walkTo.js +40 -33
- package/modules/collision/Collision.js +69 -45
- package/modules/collision/contract.js +15 -0
- package/modules/collision/grid.js +6 -1
- package/modules/content/explain.js +2 -3
- package/modules/content/fields.js +24 -3
- package/modules/content/ids.js +5 -3
- package/modules/content/index.js +132 -114
- package/modules/content/loader.js +117 -140
- package/modules/content/markers.js +25 -0
- package/modules/content/models.js +54 -17
- package/modules/content/packs.js +5 -4
- package/modules/content/parts.js +2 -2
- package/modules/content/places.js +36 -0
- package/modules/content/props.js +22 -17
- package/modules/content/rules.js +47 -61
- package/modules/content/stages.js +7 -7
- package/modules/content/templates.js +80 -49
- package/modules/content/words.js +47 -0
- package/modules/debug/DebugPanel.js +14 -45
- package/modules/flow/contract.js +2 -1
- package/modules/flow/index.js +30 -16
- package/modules/gameplay/Container.js +17 -13
- package/modules/gameplay/Containers.js +23 -6
- package/modules/gameplay/Dialogue.js +93 -34
- package/modules/gameplay/Interactions.js +93 -51
- package/modules/gameplay/Inventory.js +64 -22
- package/modules/gameplay/Quests.js +146 -30
- package/modules/gameplay/boxOps.js +8 -1
- package/modules/gameplay/dialogueBubbles.js +16 -12
- package/modules/gameplay/inventoryOps.js +11 -8
- package/modules/gameplay/pickups.js +63 -37
- package/modules/gameplay/questLog.js +4 -2
- package/modules/gameplay/questSave.js +9 -4
- package/modules/gameplay/quests.contract.js +1 -1
- package/modules/grid/Grid.js +2 -2
- package/modules/grid/Layer.js +12 -8
- package/modules/grid/index.js +28 -23
- package/modules/grid/ops.js +43 -46
- package/modules/grid/preview.js +7 -7
- package/modules/grid/tiles.js +6 -6
- package/modules/hlod/index.js +42 -57
- package/modules/hud/index.js +22 -14
- package/modules/hud/parts.js +8 -8
- package/modules/level/contract.js +16 -0
- package/modules/level/heightfield.js +29 -31
- package/modules/level/index.js +113 -161
- package/modules/level/load.js +196 -0
- package/modules/level/meshes.js +65 -0
- package/modules/level/nodes.js +40 -23
- package/modules/lights/index.js +33 -183
- package/modules/lights/slots.js +93 -0
- package/modules/lights/sources.js +90 -0
- package/modules/music/Music.js +34 -28
- package/modules/music/rules.js +1 -1
- package/modules/nav/contract.js +16 -0
- package/modules/nav/index.js +180 -49
- package/modules/nav/navPath.js +45 -10
- package/modules/net/Client.js +7 -7
- package/modules/net/Host.js +7 -7
- package/modules/net/Net.js +1 -1
- package/modules/net/index.js +6 -5
- package/modules/net/sync.js +2 -2
- package/modules/net/transports.js +2 -2
- package/modules/particles/Particles.js +95 -29
- package/modules/particles/effect.js +86 -32
- package/modules/particles/shaders.js +19 -1
- package/modules/photo/Photo.js +23 -23
- package/modules/rigid/RigidBodies.js +255 -89
- package/modules/rigid/Vehicles.js +17 -8
- package/modules/rigid/collider3d.contract.js +26 -0
- package/modules/rigid/ragdoll.js +298 -0
- package/modules/rigid/ragdollBones.js +209 -0
- package/modules/rigid/refresh.js +10 -0
- package/modules/rigid/sync.js +51 -20
- package/modules/settings/Settings.js +177 -61
- package/modules/settings/apply.js +20 -13
- package/modules/settings/sections.js +19 -14
- package/modules/settings/strings.js +2 -2
- package/modules/settings/view.js +3 -3
- package/modules/sky/Sky.js +29 -22
- package/modules/sky/clouds.js +7 -7
- package/modules/sky/dome.js +33 -20
- package/modules/sky/domeLayers.js +9 -9
- package/modules/sky/environment.js +6 -6
- package/modules/sky/frame.js +19 -10
- package/modules/sky/season.js +7 -1
- package/modules/sky/shader.js +24 -25
- package/modules/sky/skyModule.js +17 -28
- package/modules/sky/tint.js +1 -1
- package/modules/swarm/Swarm.js +356 -0
- package/modules/swarm/draw.js +68 -0
- package/modules/swarm/grid.js +63 -0
- package/modules/terrain/ChunkManager.js +71 -59
- package/modules/terrain/chunkQueries.js +7 -24
- package/modules/terrain/chunkWorker.js +1 -1
- package/modules/terrain/draw.js +14 -11
- package/modules/terrain/index.js +42 -42
- package/modules/terrain/terrainColorMap.js +6 -3
- package/modules/terrain/terrainDefaults.js +2 -1
- package/modules/terrain/terrainEdit.js +45 -29
- package/modules/terrain/terrainGen.js +19 -12
- package/modules/terrain/terrainIsland.js +2 -2
- package/modules/terrain/terrainMesh.js +7 -6
- package/modules/terrain/terrainShape.js +8 -10
- package/modules/terrain/terrainShapeMain.js +3 -3
- package/modules/timeline/Timeline.js +83 -43
- package/modules/timeline/Tween.js +25 -19
- package/modules/timeline/shots.js +24 -17
- package/modules/triggers/index.js +95 -28
- package/modules/vegetation/Vegetation.js +34 -26
- package/modules/vegetation/densityMap.js +4 -7
- package/modules/vegetation/draw.js +39 -18
- package/modules/vegetation/groundChunks.js +21 -38
- package/modules/vegetation/index.js +37 -12
- package/modules/vegetation/modelGeometry.js +3 -6
- package/modules/vegetation/nearFade.js +1 -1
- package/modules/water/Water.js +20 -16
- package/modules/water/surface.js +3 -3
- package/modules/weather/Weather.js +52 -40
- package/modules/weather/particles.js +8 -8
- package/modules/weather/weatherDraw.js +28 -23
- package/modules/world/World.js +28 -15
- package/modules/world/explain.js +1 -1
- package/modules/world/index.js +30 -17
- package/modules/world/persist.js +90 -27
- package/modules/world/pos.js +5 -5
- package/modules/world/records.js +37 -11
- package/modules/world/sim.js +78 -27
- package/modules/world/simFar.js +2 -2
- package/modules/world/state.js +43 -11
- package/modules/world/thingSource.js +20 -5
- package/modules/world/views.js +27 -14
- package/package.json +48 -7
- package/presets.js +1 -3
- package/render/PostFX.js +83 -53
- package/render/backend.js +31 -33
- package/render/cascades.js +17 -12
- package/render/cascades.tsl.js +5 -8
- package/render/daylight.js +20 -3
- package/render/detail.js +8 -7
- package/render/effects.js +28 -25
- package/render/fuse.js +3 -3
- package/render/fx/cloudShadow.tsl.js +3 -3
- package/render/fx/detail.tsl.js +1 -1
- package/render/fx/index.js +5 -10
- package/render/fx/library.tsl.js +11 -0
- package/render/fx/lighting.tsl.js +2 -1
- package/render/fx/nodeErrors.tsl.js +2 -2
- package/render/fx/objectOrigin.tsl.js +1 -2
- package/render/fx/particles.tsl.js +8 -6
- package/render/fx/patchNodes.tsl.js +5 -15
- package/render/fx/postWebGPU.tsl.js +30 -26
- package/render/fx/sky.tsl.js +15 -17
- package/render/fx/uniforms.tsl.js +4 -4
- package/render/fx/wind.tsl.js +1 -1
- package/render/fxNumbers.js +3 -0
- package/render/layers.js +2 -2
- package/render/lighting.js +5 -3
- package/render/lightmap.js +41 -21
- package/render/lights.js +6 -6
- package/render/lit.js +24 -0
- package/render/materials.js +8 -7
- package/render/mergeCommon.js +22 -0
- package/render/modeling.js +2 -2
- package/render/occlusion.js +62 -15
- package/render/ownFrame.js +4 -4
- package/render/patches.js +15 -15
- package/render/postWebGL.js +15 -12
- package/render/probes.js +41 -19
- package/render/recordSweep.js +117 -0
- package/render/shaderErrors.js +10 -9
- package/render/shadowCache.tsl.js +107 -0
- package/render/shadowTypes.js +9 -0
- package/{core → render}/shadows.js +59 -13
- package/render/slots.js +7 -7
- package/render/terms.js +22 -24
- package/render/uniformDecl.js +1 -1
- package/types/core.d.ts +336 -202
- package/types/gameplay.d.ts +254 -130
- package/types/generated/core/{Audio.d.ts → audio/Audio.d.ts} +22 -7
- package/types/generated/core/{audioVoice.d.ts → audio/audioVoice.d.ts} +2 -2
- package/types/generated/core/{Events.d.ts → base/Events.d.ts} +4 -4
- package/types/generated/core/{I18n.d.ts → base/I18n.d.ts} +8 -16
- package/types/generated/core/{Random.d.ts → base/Random.d.ts} +4 -3
- package/types/generated/core/{page.d.ts → engine/page.d.ts} +8 -9
- package/types/generated/core/{Input.d.ts → input/Input.d.ts} +28 -10
- package/types/generated/core/input/inputSeat.d.ts +26 -0
- package/types/generated/core/{Budget.d.ts → inspect/Budget.d.ts} +36 -26
- package/types/generated/core/{DebugOverrides.d.ts → inspect/DebugOverrides.d.ts} +17 -3
- package/types/generated/core/{Ops.d.ts → ops/Ops.d.ts} +6 -4
- package/types/generated/core/{control.d.ts → ops/control.d.ts} +14 -10
- package/types/generated/core/{Saves.d.ts → saves/Saves.d.ts} +62 -18
- package/types/generated/core/{session.d.ts → saves/session.d.ts} +3 -2
- package/types/generated/core/{Rays.d.ts → scene/Rays.d.ts} +8 -27
- package/types/generated/core/{Views.d.ts → scene/Views.d.ts} +2 -2
- package/types/generated/core/{Batching.d.ts → stream/Batching.d.ts} +7 -7
- package/types/generated/core/{Stream.d.ts → stream/Stream.d.ts} +22 -18
- package/types/generated/core/{Commits.d.ts → threads/Commits.d.ts} +1 -1
- package/types/generated/core/{Jobs.d.ts → threads/Jobs.d.ts} +6 -6
- package/types/generated/core/{Threads.d.ts → threads/Threads.d.ts} +4 -4
- package/types/generated/modules/calendar/Calendar.d.ts +10 -11
- package/types/generated/modules/debug/DebugPanel.d.ts +1 -9
- package/types/generated/modules/grid/Grid.d.ts +1 -0
- package/types/generated/modules/grid/Layer.d.ts +1 -1
- package/types/generated/modules/grid/index.d.ts +3 -3
- package/types/generated/modules/music/Music.d.ts +7 -5
- package/types/generated/modules/particles/Particles.d.ts +5 -4
- package/types/generated/modules/sky/Sky.d.ts +21 -10
- package/types/generated/modules/swarm/Swarm.d.ts +80 -0
- package/types/generated/modules/timeline/Timeline.d.ts +7 -5
- package/types/generated/modules/water/Water.d.ts +1 -0
- package/types/generated/modules/weather/Weather.d.ts +14 -16
- package/types/generated/modules/weather/weatherDraw.d.ts +3 -3
- package/types/generated/modules/world/World.d.ts +11 -7
- package/types/generated/render/PostFX.d.ts +21 -23
- package/types/generated/render/materials.d.ts +1 -0
- package/types/generated/render/occlusion.d.ts +9 -0
- package/types/generated/render/patches.d.ts +1 -0
- package/types/generated/ui/Focus.d.ts +1 -0
- package/types/generated/ui/UI.d.ts +1 -0
- package/types/nav.d.ts +47 -15
- package/types/physics.d.ts +150 -73
- package/types/pixel.d.ts +75 -0
- package/types/tsl.d.ts +37 -4
- package/types/world.d.ts +48 -75
- package/ui/Focus.js +10 -9
- package/ui/Parts.js +13 -5
- package/ui/UI.js +7 -7
- package/ui/defaults.js +3 -2
- package/ui/theme.js +7 -5
- package/core/assetEntry.js +0 -109
- package/core/engineCamera.js +0 -32
- package/core/ground.js +0 -104
- package/core/holds.js +0 -134
- package/core/math.js +0 -48
- package/core/moduleSlots.js +0 -100
- package/core/modules.js +0 -314
- package/core/saveApply.js +0 -210
- package/core/saveValues.js +0 -46
- package/core/session.js +0 -174
- package/core/shadowTypes.js +0 -16
- package/core/util.js +0 -17
- package/core/view.js +0 -43
- package/docs/MIGRATING-0.3.md +0 -248
- package/docs/MIGRATING-0.4.md +0 -320
- package/docs/MIGRATING-0.5.md +0 -68
- package/docs/MIGRATING-0.6.md +0 -126
- package/docs/PERF.md +0 -245
- package/docs/recipes/36-sky-ground-plants.md +0 -158
- package/docs/recipes/37-terrain-hooks.md +0 -115
- package/docs/recipes/38-environment-hooks.md +0 -67
- package/docs/recipes/42-terrain-shape.md +0 -64
- package/docs/recipes/47-island-snow-backdrop.md +0 -43
- package/docs/recipes/54-three-idioms.md +0 -88
- package/examples/plain-picture/FINDINGS.md +0 -53
- package/examples/sheepisland/.threedog/content-index.json +0 -1
- package/modules/camera/projection.js +0 -21
- /package/core/{mulberry32.js → base/mulberry32.js} +0 -0
- /package/core/{inputDefaults.js → input/inputDefaults.js} +0 -0
- /package/core/{textureBytes.js → inspect/textureBytes.js} +0 -0
- /package/core/{actor.js → ops/actor.js} +0 -0
- /package/core/{opsHistory.js → ops/opsHistory.js} +0 -0
- /package/core/{saveIds.js → saves/saveIds.js} +0 -0
- /package/core/{screenToGround.js → scene/screenToGround.js} +0 -0
- /package/core/{cells.js → stream/cells.js} +0 -0
- /package/core/{streamCells.js → stream/streamCells.js} +0 -0
- /package/core/{pureWorker.js → threads/pureWorker.js} +0 -0
- /package/examples/{sheepisland → perf-island}/content/index.js +0 -0
- /package/examples/{sheepisland → perf-island}/content/props.js +0 -0
- /package/examples/{sheepisland → perf-island}/content/templates.js +0 -0
- /package/examples/{sheepisland → perf-island}/content/vegetation.js +0 -0
- /package/examples/{sheepisland → perf-island}/picture/lights.js +0 -0
- /package/examples/{sheepisland → perf-island}/picture/materials.js +0 -0
- /package/examples/{sheepisland → perf-island}/picture/sky.js +0 -0
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
# Content vocabulary, key actions in actions.js, saving and loading at startup
|
|
2
2
|
|
|
3
3
|
**In this recipe**: 1. Condition words / effect words · 1b. Content packs · 2. actions.js: a game's own key actions · 3. Interact keys ·
|
|
4
|
-
4. Continue and new game · Save failures and versions · Save format
|
|
4
|
+
4. Continue and new game · 4b. Best times and high scores · Save failures and versions · Save format
|
|
5
5
|
|
|
6
6
|
## 1. Condition words / effect words
|
|
7
7
|
The full vocabulary is in the last section of `../api/content.md` (**generated from `modules/content/rules.js`**, so it never goes stale):
|
|
@@ -13,6 +13,7 @@ ops, used from content as `{ op: ['noun.verb', { args }] }` / `{ can: [...] }` (
|
|
|
13
13
|
- Conditions are used in: quest step `done`, dialogue choice `if`, line variant `if`. Several entries in one object = all must hold; an array = every
|
|
14
14
|
item must hold.
|
|
15
15
|
- Effects are used in: dialogue `do`, quest `reward`, trigger zone `onEnter / onExit`. Several entries in one object, or an array, run in order.
|
|
16
|
+
- Every word runs even when one fails. `content.run` answers `{ ok: true }` or a failure with `facts.failed` (`{ word, code, facts }`); an op returning it fails with it. Dialogue `do` and triggers: listen to `content:failed`.
|
|
16
17
|
- Content validation (content-check inside `threedog check` / `threedog map`) checks the word names and how the values are written.
|
|
17
18
|
|
|
18
19
|
### A game's own data kinds (enemies, recipes, loot tables, waves…)
|
|
@@ -32,7 +33,7 @@ export default {
|
|
|
32
33
|
for (const [id, r] of Object.entries(data)) if (!ctx.data.items?.[r.makes]) ctx.err(`recipe ${id} makes unknown item ${r.makes}`);
|
|
33
34
|
},
|
|
34
35
|
map: data => Object.entries(data).map(([id, r]) => `${id} -> ${r.makes}`), // optional GAMEMAP lines
|
|
35
|
-
// optional: the keys of each entry (core/params.js format, no default); threedog check reports unknown keys, wrong types, out of range
|
|
36
|
+
// optional: the keys of each entry (core/base/params.js format, no default); threedog check reports unknown keys, wrong types, out of range
|
|
36
37
|
fields: { needs: 'object', makes: 'string', seconds: { type: 'number', min: 0, optional: true, desc: 'crafting time' } },
|
|
37
38
|
},
|
|
38
39
|
},
|
|
@@ -42,25 +43,36 @@ export default {
|
|
|
42
43
|
// content/recipes.js
|
|
43
44
|
export default { bread: { needs: { flour: 2 }, makes: 'bread' } };
|
|
44
45
|
```
|
|
45
|
-
Add `recipes` to `content/index.js` like any other file
|
|
46
|
-
|
|
46
|
+
Add `recipes` to `content/index.js` like any other file, and `rules` too: the loader knows a kind only from the `rules` it is handed (`threedog check`
|
|
47
|
+
says so when one is missing). `load` is optional: a game that imports the file itself leaves it out and still gets the check and the map entry.
|
|
48
|
+
A name `content/index.js` lists that is neither an engine file nor a registered kind is an error, and so is `content.load({ enemies })` without the kind:
|
|
49
|
+
both say how to register it. A kind may not reuse an engine file name. A file the index does not list is no content, so `threedog check` gives one warning.
|
|
50
|
+
A game's own data that the engine never reads, such as translated story text, belongs outside `content/`: a folder of its own that the game
|
|
51
|
+
imports itself, or `engine.i18n.add()` when it is text the UI fetches with `engine.t`. To have it checked and on the map, register a kind with no `load`.
|
|
47
52
|
|
|
48
|
-
**Field tables.** Every content entry has one: the engine
|
|
49
|
-
|
|
50
|
-
a kind adds `fields` as above. `threedog check` validates every entry against its table (a misspelled `scael` names `scale`), and
|
|
51
|
-
`engine.content.fields(name)` returns the same table for tools such as an editor panel, so the two cannot disagree.
|
|
53
|
+
**Field tables.** Every content entry has one: the engine's own, a template's `fields` (recipes/30-templates.md) or a kind's `fields` as above. `threedog check` validates every entry
|
|
54
|
+
against its table (a misspelled `scael` names `scale`), and `engine.content.fields(name)` returns the same table for tools such as an editor panel.
|
|
52
55
|
|
|
53
56
|
## 1b. Content packs: several data sets in one load
|
|
57
|
+
A pack with a `level` commits when its file is here. If a newer `level.load`, save load or unload comes first, the newest level stands and only the pack's `level` gives way: the rest goes in once that load has ended, on the level that won. A place only the pack's level had fails with `content-place`, as any unknown place does, and the pack goes back whole.
|
|
58
|
+
|
|
59
|
+
`content.load` answers for its own load. Bad data throws on the line. The Promise it returns resolves once the pack committed, and rejects when it failed, after the old level and registrations are back; saves and loads asked meanwhile wait for that. If the old level could not come back, `err.notRestored` lists why. A load nobody awaits is reported all the same.
|
|
60
|
+
|
|
61
|
+
```js fragment
|
|
62
|
+
try { await engine.content.load(dlc); }
|
|
63
|
+
catch (err) { showError(err.notRestored ? 'reload the game' : 'this pack is broken'); }
|
|
64
|
+
```
|
|
65
|
+
|
|
54
66
|
A content pack is the same object `content/index.js` exports (`{ items, templates, props, quests, ... }`, optional `name` for messages), shipped as a
|
|
55
67
|
folder or an npm package: data only, assets by name (never a path or a function; `npm run check` and a dev warning report both). Load several together:
|
|
56
|
-
```js
|
|
68
|
+
```js fragment
|
|
57
69
|
import base from './content/index.js';
|
|
58
70
|
import forest from 'forest-content'; // its props name templates from base and models from the forest asset pack
|
|
59
71
|
import packs from './assets.js'; // export default [forestAssets, ...]: the asset packs ({ name, base, models, textures, sounds, fonts })
|
|
60
72
|
engine.assets.manifest(packs); // the same objects `npm run check` reads the names from
|
|
61
73
|
engine.content.load([base, forest], { places: { home } });
|
|
62
74
|
```
|
|
63
|
-
- Packs load in list order, so a pack may use what an earlier one defines.
|
|
75
|
+
- Packs load in list order, so a pack may use what an earlier one defines. A pack's own `places` load with it; the `places` option goes on top (a place computed at startup).
|
|
64
76
|
- Within one call an id may live in one pack only: `items.apple` in two packs, or the same prop / pickup id, is an error naming both packs. A later,
|
|
65
77
|
separate `load` call still overrides by name on purpose (hot reload, a chapter replacing a quest).
|
|
66
78
|
- A pack may carry its sounds: `audio: { sounds, ambience, music, footsteps }` (`recipes/31-audio.md` section 8). Sounds, footsteps and music tracks
|
|
@@ -110,7 +122,7 @@ engine.interactions.pickMode = 'aim'; // switch at runtime (enter
|
|
|
110
122
|
```
|
|
111
123
|
One object with two verbs = two interactions with different key actions; each key picks among its own action, and `engine.interactions.options` lists
|
|
112
124
|
one `{ action, id, label }` per key for a prompt that shows both:
|
|
113
|
-
```js
|
|
125
|
+
```js fragment
|
|
114
126
|
engine.input.action('take', { label: 'Take', keys: ['KeyF'] });
|
|
115
127
|
engine.interactions.add(thing, { label: 'Inspect', onUse: inspect }); // E
|
|
116
128
|
engine.interactions.add(thing, { label: 'Take', action: 'take', enabled: () => ready, onUse: take }); // F
|
|
@@ -121,7 +133,7 @@ when the key is released, the actor leaves the radius, `enabled()` turns false o
|
|
|
121
133
|
`approach: true` walks the player there first (`walkTo`, stops 1.2 m away) and uses it on arrival; with `radius: Infinity` it is usable from anywhere
|
|
122
134
|
(point-and-click, "talk to the clerk across the shop"). The op `interaction.use` is the completed use in both cases (tests and the dev bridge
|
|
123
135
|
skip the hold; an approach returns `{ approaching }`, a promise of onUse's result).
|
|
124
|
-
```js
|
|
136
|
+
```js fragment
|
|
125
137
|
engine.interactions.add(well, { label: 'Pump', hold: 1.5, onUse: fill });
|
|
126
138
|
engine.interactions.add(shell, { id: 'shell-1', label: 'Pick up', once: true, counter: 'shells' }); // mesh gone after E, counted: recipe 03 "Pick and count"
|
|
127
139
|
engine.interactions.add(clerk, { label: 'Talk', radius: Infinity, approach: true, onUse: talk });
|
|
@@ -134,7 +146,7 @@ The actor is handed down, never assumed: `label / enabled / onUse` get `(object,
|
|
|
134
146
|
peer, an NPC); trigger callbacks get `(t, who, id)` and the events carry `id` (`who` may list actor ids: `who: () => [e.actor, ...peerIds]`); content
|
|
135
147
|
`has / lacks / give / take` use the bag of the running op's actor (else `engine.actor`), and `engine.content.run(effect, { actor })` /
|
|
136
148
|
`content.test(cond, { actor })` name one explicitly; trigger `onEnter / onExit` effects act for whoever crossed the zone.
|
|
137
|
-
```js
|
|
149
|
+
```js fragment
|
|
138
150
|
engine.interactions.add(door, { label: (o, { actor }) => keyOf(actor) ? 'Open' : 'Locked', onUse: (o, { actor }) => engine.ops.run('door.open', { id: o.name }, { actor }) });
|
|
139
151
|
engine.triggers.add({ position: gate, who: () => [engine.actor, ...guards], onEnter: (t, who, id) => engine.ops.run('gate.alarm', { by: id }) });
|
|
140
152
|
```
|
|
@@ -148,7 +160,9 @@ if (engine.saves.check('auto') === null) await engine.session.load('auto'); //
|
|
|
148
160
|
- `engine.session.load(slot)` and `engine.session.newGame()` both return `Promise<boolean>`: always `await`. `session.load` starts from the new-game
|
|
149
161
|
state and puts the save on top, so a part the save lacks (a module added in a later version) starts fresh instead of keeping the current run's
|
|
150
162
|
state. `engine.saves.load(slot)` is a quick load onto the running playthrough; never build Continue from it.
|
|
151
|
-
-
|
|
163
|
+
- A running cutscene and an open conversation are not saved: any load ends them without their remaining steps. Save at a point the game can continue from: a save taken inside a
|
|
164
|
+
cutscene whose last step sets the flag a quest waits for comes back without that flag.
|
|
165
|
+
- Loading restores the player, the view (the camera rig's yaw and pitch: a first-person game needs no save code for it), world data (world changes and deletions), inventory, quests, clock and random state; initial data in content files
|
|
152
166
|
(`initial`) is the same whether it is loaded before or after the save, so ignore the order.
|
|
153
167
|
- A load rebuilds the props and other world records: an Object3D your code kept from before (a door mesh, a lamp) is gone afterwards. Keep the
|
|
154
168
|
record id, not the mesh, and look it up again on `save:loaded`: `engine.world.get(id)` for the record, `engine.world.view(id)` for its model
|
|
@@ -158,6 +172,14 @@ if (engine.saves.check('auto') === null) await engine.session.load('auto'); //
|
|
|
158
172
|
- During development, to jump straight into a save: URL `?save=slot1` (`threedog state` also understands `save=`).
|
|
159
173
|
- In tests, `engine.saves.save('x'); await engine.saves.flush();` writes before reading back.
|
|
160
174
|
|
|
175
|
+
## 4b. Best times and high scores: data that outlives saves
|
|
176
|
+
Best lap times, a leaderboard or high scores belong to the player, not to one playthrough: in a save part a new game would wipe them. Persist them beside the saves, in `localStorage` under `engine.saves.storageKey(name)`, a key that shares the game's name and stays out of the save slots:
|
|
177
|
+
```js
|
|
178
|
+
const key = engine.saves.storageKey('records');
|
|
179
|
+
const records = () => JSON.parse(localStorage.getItem(key) ?? '{ "laps": [] }');
|
|
180
|
+
const addLap = time => { const r = records(); r.laps.push(time); localStorage.setItem(key, JSON.stringify(r)); };
|
|
181
|
+
```
|
|
182
|
+
|
|
161
183
|
## Save failures and versions
|
|
162
184
|
- `await engine.saves.save(slot)` is `true` only after the write is on disk; show "saved" only then. On a failed write (storage full, IndexedDB /
|
|
163
185
|
localStorage refused) it is `false`, the player already saw why, and the previous save of that slot is kept (memory follows the disk).
|
|
@@ -166,27 +188,34 @@ if (engine.saves.check('auto') === null) await engine.session.load('auto'); //
|
|
|
166
188
|
- A part whose `save()` throws makes the whole save fail (`false`, the slot keeps its previous save); a part whose `load()` throws rolls the game back
|
|
167
189
|
to how it was before the load (`false`). So does a listener of an event the load emits (`world:load`) or a module's `afterLoad` that throws. Both go
|
|
168
190
|
through the error tiers (`engine.error` in dev, code `save-part-threw` / `save-load-threw`).
|
|
191
|
+
- One replacement at a time: `saves.apply`, `saves.load` and `session.newGame` / `load` / `quit` wait their turn in the order asked, so the end state is
|
|
192
|
+
always one whole save, and a load that fails rolls back to the whole state before it. Idle, a save with only synchronous parts applies at once. While
|
|
193
|
+
a replacement runs ops return `'loading'`.
|
|
194
|
+
- A `load()` or `afterLoad` may change level or load a pack, before or after an await. It is handed the turn of its replacement; pass it on, and the call goes at once:
|
|
195
|
+
`async load(d, turn) { await fetchRoute(d); await engine.level.load(d.level, { turn }); }`. Without the turn the call counts as an outside request and waits for this load to end, so awaiting
|
|
196
|
+
it would wait for itself (dev says so after 3 s, `save-nested`). A new `saves.apply` / `load` / `save` or `session.*` starts after the running one: ask for it without awaiting it, or from a
|
|
197
|
+
`save:loaded` or `session:start` listener.
|
|
198
|
+
- A part registered while a load runs gets its data right after that load, whole, unless a newer load replaced the state first; idle it gets it before `register` returns.
|
|
169
199
|
- A save edited by hand or damaged: a `null` part makes it `'corrupt'` (a `save()` returning `null` is simply left out); a world record whose
|
|
170
200
|
position is not three finite numbers is refused and rolled back (`save-bad-record`, no gameplay error); a bad number of the clock, time
|
|
171
201
|
channels, random state or item counts is clamped or dropped with one `save-value` warning per part, and the rest loads.
|
|
172
202
|
- Two tabs of one game: a tab overwrites a slot only while it holds the copy it last read, wrote or loaded. A save over a newer one another tab
|
|
173
203
|
wrote returns `false` (toast, `save-stale`); that tab then lists the newer save, and loading it lets it save there again.
|
|
174
|
-
- `engine.saves.versions` lists the version of every part this build reads (`{ world:
|
|
204
|
+
- `engine.saves.versions` lists the version of every part this build reads (`{ world: 5, clock: 1, ... }`); raise a part's `version` with a `migrate`
|
|
175
205
|
step when its data changes shape.
|
|
176
|
-
- Import is offline and checked: `saves.import(text)` and `saves.importFile(file)`
|
|
177
|
-
attachments must be `data:` URLs (nothing is fetched).
|
|
206
|
+
- Import is offline and checked: `saves.import(text)` and `saves.importFile(file)` refuse anything that is not a save, and attachments must be `data:` URLs (nothing is fetched).
|
|
178
207
|
|
|
179
|
-
## Save format
|
|
208
|
+
## Save format
|
|
180
209
|
A save is one envelope; `engine.saves.collect()` returns it and `export` / `exportFile` carry it unchanged:
|
|
181
210
|
```js fragment
|
|
182
211
|
{ format: 1, // the envelope's own version: a save with a higher format is refused as tooNew (none = 1)
|
|
183
212
|
savedAt: 1730000000000, // real time of the save
|
|
184
|
-
versions: { world:
|
|
213
|
+
versions: { world: 5, quests: 2, clock: 1 }, // each part's version (none = 1)
|
|
185
214
|
parts: { world: {...}, quests: {...}, clock: {...}, vars: {...} } } // each saves.register part's data, by key
|
|
186
215
|
```
|
|
187
|
-
- **Parts and versions**: each `engine.saves.register(key, { version, migrate, save, load })` owns one part. When `save()` changes shape, raise
|
|
188
|
-
`version` by 1 and add `migrate[oldVersion] = data => newData`; load runs the steps in order on a copy, so `load` only sees the current shape.
|
|
189
|
-
|
|
216
|
+
- **Parts and versions**: each `engine.saves.register(key, { version, migrate, save, load })` owns one part. `load` takes one argument, the data: `load: data => …`, never `load(engine, data)`, the shape of a module hook (`npm run check` warns, rule R33). When `save()` changes shape, raise
|
|
217
|
+
`version` by 1 and add `migrate[oldVersion] = data => newData`; load runs the steps in order on a copy, so `load` only sees the current shape.
|
|
218
|
+
This is how a game's own saved data migrates across its releases (there is no other system): keep one saved file per released game version, never edit it, and load each in a test with `engine.saves.apply(sample)` (the engine does the same for its own parts in `tests/specs/save-compat.mjs`).
|
|
190
219
|
- **Parts nobody owns are kept**: a part in the loaded save whose module is not installed in this run (a feature turned off for a version) is written
|
|
191
220
|
back unchanged on every save, and handed to the module if it registers later. Only a new game drops it.
|
|
192
221
|
- **Authored baseline + per-id diff**: everything placed in a level comes from content (props, template instances, pickups, NPCs, grid items in
|
|
@@ -194,25 +223,11 @@ A save is one envelope; `engine.saves.collect()` returns it and `export` / `expo
|
|
|
194
223
|
`changed` (fields of an authored record that differ), `removed` (authored records removed), `records` (records created during play, such as
|
|
195
224
|
`engine.content.spawn`, drops and built walls, saved whole), `owed` (seconds owed, only for kinds simulated with `far`). The same content gives the same
|
|
196
225
|
world, and a new game's world part is empty: in dev, start warns about records that code created or changed before it, naming them.
|
|
197
|
-
- **Orphans are kept**: a saved change whose id the content no longer defines (an entry renamed or deleted) stays in the save and is written
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
would <!-- r18-ignore-line -->
|
|
201
|
-
move it; `describe().world.orphans` lists them. A rename in `content/renames.js` moves the state to the new id (recipe 30, "Writing the ids, <!--
|
|
202
|
-
r18-ignore-line -->
|
|
203
|
-
renaming them"). <!-- r18-ignore-line -->
|
|
204
|
-
- **Runtime ids and migration**: records made during play are `<kind>#<n>` (world part version 3). An older save's `<kind>-<n>` ids are renamed when
|
|
205
|
-
it loads, together with the owed time, container goods and fields that name them; only ids the counter could have made are touched (own kind, `n` up
|
|
206
|
-
to the saved counter, each `n` once), so an authored `crate-2` stays as it is. A migrate step that needs another part gets the whole save as its
|
|
207
|
-
second argument: `migrate: { 1: (data, save) => … }`. <!-- r18-ignore-line -->
|
|
208
|
-
- **Grid layers diff too**: cells authored in `content/grids.js` (`plot: { …, layers: { soil: [[i, j, { tilled: true }]] } }`) are the baseline;
|
|
209
|
-
the <!-- r18-ignore-line -->
|
|
210
|
-
`grids` part (version 2) stores only changed cells (`set`) and emptied authored ones (`clear`), and keeps a diff for a grid the run does not
|
|
211
|
-
have. <!-- r18-ignore-line -->
|
|
226
|
+
- **Orphans are kept**: a saved change whose id the content no longer defines (an entry renamed or deleted) stays in the save and is written back, never dropped, so reverting the content change gets the data back. Dev warns once with the closest id and the `content/renames.js` pair that would move it; `describe().world.orphans` lists them. A rename in `content/renames.js` moves the state to the new id (recipe 30, "Writing the ids, renaming them"). <!-- r18-ignore-line -->
|
|
227
|
+
- **Runtime ids**: records made during play are `<kind>#<n>`, so a runtime id never equals an authored one. A migrate step that needs another part gets the whole save as its second argument: `migrate: { 1: (data, save) => … }`. <!-- r18-ignore-line -->
|
|
228
|
+
- **Grid layers diff too**: cells authored in `content/grids.js` (`plot: { …, layers: { soil: [[i, j, { tilled: true }]] } }`) are the baseline; the `grids` part stores only changed cells (`set`) and emptied authored ones (`clear`), and keeps a diff for a grid the run does not have. <!-- r18-ignore-line -->
|
|
212
229
|
- **Stable ids, never positions**: saved data names things by stable ids. The player's vehicle is saved by `rigid.addWheeled(mesh, { id })`; quest
|
|
213
230
|
progress by step ids (`steps: [{ id: 'talk-mayor', ... }]`, recipe 04). Content edits (a new step, a new prop) then never shift an old save.
|
|
214
|
-
- **Built-in part versions**: `world` 3 (version 1 kept `records` as an array, version 2 the `<kind>-<n>` runtime ids), `quests` 2 (version 1 kept
|
|
215
|
-
step positions; the migrate step maps them to ids through the quest definitions), `containers` 2 and `grids` 2, every other part 1.
|
|
216
231
|
- The export file wraps the envelope:
|
|
217
232
|
`{ threedog: 'save', format: 1, game, slot, savedAt, data: <envelope>, files: [{ group, id, at, meta, type, url: 'data:...' }] }`.
|
|
218
|
-
- Tests: `
|
|
233
|
+
- Tests: `threedog test "Save failure"`.
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
# Camera: first / third person, top-down strategy, fixed shots, switched at runtime
|
|
2
2
|
|
|
3
3
|
**In this recipe**: 1. Press V to switch between first and third person · 2. What the engine does for you when switching · 3. Other common things ·
|
|
4
|
-
4. Over the shoulder, lock-on framing, mouse lock · 4b. Looking up, ground and walls, driving the view yourself · 5. Take over the player ·
|
|
4
|
+
4. Over the shoulder, lock-on framing, mouse lock · 4b. Looking up, ground and walls, driving the view yourself · 4c. Chase camera behind a car · 5. Take over the player ·
|
|
5
5
|
6. Orthographic view, and taking the camera over yourself · 7. Your own camera module
|
|
6
6
|
|
|
7
7
|
Four cameras; the kind names are always: `'follow'` third-person follow · `'firstPerson'` first person · `'rts'` top-down strategy · `'fixed'` fixed shots.
|
|
@@ -39,20 +39,21 @@ engine.setCamera('follow', { distance: 8, pitch: 0.3 });
|
|
|
39
39
|
## 3. Other common things
|
|
40
40
|
- **Cycling through several**:
|
|
41
41
|
`const VIEWS = ['follow', 'firstPerson', 'rts']; engine.setCamera(VIEWS[(VIEWS.indexOf(engine.cameraRig.kind) + 1) % VIEWS.length]);`
|
|
42
|
-
- **A fixed camera needs shots first**: `engine.setCamera('fixed', { shots: { hall: { position: [0, 6, 12], lookAt: [0, 0, 0] } }, start: 'hall' })`.
|
|
42
|
+
- **A fixed camera needs shots first**: `engine.setCamera('fixed', { shots: { hall: { position: [0, 6, 12], lookAt: [0, 0, 0] } }, start: 'hall' })`. A shot stays where it was placed; a view that pans at a fixed angle is the follow camera (section 6).
|
|
43
43
|
- **Camera-specific methods** exist only after switching: `engine.cameraRig.lookAt(position)` (first person), `cut('name')` (fixed shots),
|
|
44
44
|
`screenToGround(...)` (rts). Check `kind` before calling.
|
|
45
45
|
- **Teleport, then lookAt**: `await engine.stream.teleport(p); engine.cameraRig.lookAt(target);` works in that order: `lookAt` aims from the body's
|
|
46
46
|
current position, not from the last drawn frame. Call it after the move (the angles do not follow later moves).
|
|
47
|
+
- **Saves and new games**: a save holds the view (`yaw`, `pitch`), and `session.load` / `saves.load` put it back. A new playthrough rebuilds the installed camera on the same object, so a kept `const rig = engine.cameraRig` stays valid (one from `setCamera` with options does not). A kind switched to with `setCamera` is not restored: only the heading carries, so call `setCamera` again on `session:start` if the game keeps that choice.
|
|
47
48
|
- **Player movement direction follows the camera**: `engine.cameraRig.forward()` / `right()` change automatically after switching.
|
|
48
49
|
- **Cutscene takeover**: while anyone holds `engine.takeCamera(owner)` (`engine.cameraOverride` is not null) the camera module leaves the camera alone; see [the engine API](../api/engine.md).
|
|
49
50
|
- **Shooting games**: bind first-person firing to a mouse-button action, see `19-shooting-picking.md`.
|
|
50
51
|
|
|
51
52
|
## 4. Over the shoulder, lock-on framing, mouse lock (follow camera)
|
|
52
|
-
```js
|
|
53
|
+
```js fragment
|
|
53
54
|
engine.use(followCamera({ distance: 3, shoulder: 0.7, pitch: 0.15, pointerLock: true })); // shooter / action-adventure view
|
|
54
55
|
engine.cameraRig.shoulder = -0.7; // switch shoulders at any time (plain property)
|
|
55
|
-
engine.cameraRig.frame(enemy.
|
|
56
|
+
engine.cameraRig.frame(enemy.root); // lock-on: turn to "behind the player, looking at the enemy"; frame(null) lets go
|
|
56
57
|
```
|
|
57
58
|
- **`shoulder`**: meters the aim point (and so the camera) moves to the right along `right()`; negative = left, 0 = centered (default).
|
|
58
59
|
- **`pointerLock`** (default false): a click on the canvas locks the mouse, so moving it turns the view with no dragging; Esc releases, and `engine.page.releaseLock()` releases from code without opening the pause menu. Not on phones. If the browser refuses the lock the camera falls back to dragging; `describe().camera.pointerLock` is a state machine: `state` is `off` / `unsupported` / `waiting-click` / `requesting` / `locked` / `refused`, plus `covered` (what sits on the canvas centre and eats the click), `cameraOverride` (a takeover blocks locking) and `lastFailure { reason, agoSec }`; the text line shows the same.
|
|
@@ -75,7 +76,7 @@ engine.use(followCamera({ minPitch: -0.9, ground: 'shorten' })); // or the sam
|
|
|
75
76
|
`'shorten'` slides it along the arm toward the player (the view direction is kept, so you really look up);
|
|
76
77
|
`'raise'` lifts it straight up (the view direction changes: from flat ground you cannot look up);
|
|
77
78
|
`'none'` leaves it; a function `facts => position | null` gets `{ position, lookPoint, dir, arm, distance, groundY, clearance, surface, rig }`.
|
|
78
|
-
Default: `'shorten'` when `minPitch < 0`, otherwise `'raise'
|
|
79
|
+
Default: `'shorten'` when `minPitch < 0`, otherwise `'raise'`.
|
|
79
80
|
- **Walls** (with `collision()` installed) pull the arm in at once and let it out slowly; the shortest arm is `collision({ cameraMin })` (default 1.5 m).
|
|
80
81
|
**What blocks by default**: every `addCircle` / `addBox` / `addSegment` collider, over its footprint and up to its height, and every mesh registered
|
|
81
82
|
with `engine.rays.addStatic(mesh, { occluder: true })` (`level()` registers its buildings and `col_` meshes). A mesh alone blocks nothing, so a tree
|
|
@@ -91,11 +92,24 @@ engine.use(followCamera({ minPitch: -0.9, ground: 'shorten' })); // or the sam
|
|
|
91
92
|
`getView()` → `{ yaw, pitch, distance, arm, lookPoint, look }` (`look` is the 3D view direction, `arm` the actual length this frame).
|
|
92
93
|
With `mouseLook: false` the built-in mouse / stick look and wheel zoom are off and the game owns yaw and pitch (call `setView` every frame from `onFrame`).
|
|
93
94
|
|
|
95
|
+
## 4c. Chase camera behind a car
|
|
96
|
+
`addWheeled({ camera })` sets the follow camera's distance and height while seated, but the camera keeps its own yaw, so nothing swings the view behind the car. A racing view is a few lines of game code with `followCamera({ mouseLook: false })`:
|
|
97
|
+
```js fragment
|
|
98
|
+
let yaw = null;
|
|
99
|
+
engine.onFrame(dt => {
|
|
100
|
+
const q = car.body.rotation(); // car: what addWheeled returned
|
|
101
|
+
const want = Math.atan2(2 * (q.x * q.z + q.w * q.y), 1 - 2 * (q.x * q.x + q.y * q.y)) + Math.PI; // a car drives along its +z; the view looks along -z at yaw 0
|
|
102
|
+
yaw ??= want;
|
|
103
|
+
yaw += Math.atan2(Math.sin(want - yaw), Math.cos(want - yaw)) * Math.min(1, 5 * dt); // the shortest way round, catching up at 5 per second
|
|
104
|
+
engine.cameraRig.setView({ yaw });
|
|
105
|
+
});
|
|
106
|
+
```
|
|
107
|
+
|
|
94
108
|
## 5. Take over the player: your own movement, facing and lock-on
|
|
95
109
|
The engine has no default here: `createPlayer` needs `control` (a preset such as `presets.player.thirdPerson` gives keys relative to the camera, Shift
|
|
96
110
|
run, Space jump, turning toward where it walks and `cameraFollow: true`). Each piece below replaces one part and keeps the rest (world record, saving,
|
|
97
111
|
`describe().player`).
|
|
98
|
-
```js
|
|
112
|
+
```js fragment
|
|
99
113
|
import { pickTarget, switchTarget } from 'threedog';
|
|
100
114
|
|
|
101
115
|
// how the input steers the player: 'camera' (keys relative to the camera) | (player, input, dt) => ({ x, z, run? }) | null (stand still)
|
|
@@ -140,16 +154,24 @@ function steer(player, input, dt) { // called once per fixed
|
|
|
140
154
|
**Orthographic (isometric / 2.5D) with the built-in rigs.** `projection: 'orthographic'` plus `size` (world units of view height) on the fixed and follow cameras.
|
|
141
155
|
The default stays perspective. On resize the view height stays `size` and the width follows the aspect.
|
|
142
156
|
|
|
143
|
-
```js
|
|
157
|
+
```js fragment
|
|
144
158
|
// one fixed isometric shot (shorthand for a single shot named 'main')
|
|
145
159
|
engine.setCamera('fixed', { position: [14, 14, 14], lookAt: [0, 0, 0], projection: 'orthographic', size: 16 });
|
|
146
160
|
// per shot: shots: { hall: { position, lookAt, projection: 'orthographic', size: 12 }, yard: { position, lookAt } } // yard stays perspective
|
|
147
161
|
// follow the player from a fixed angle
|
|
148
|
-
engine.setCamera('follow', { pitch: 0.6, yaw: 0.8, distance: 20, projection: 'orthographic', size: 14 });
|
|
162
|
+
engine.setCamera('follow', { pitch: 0.6, yaw: 0.8, distance: 20, projection: 'orthographic', size: 14, mouseLook: false, ground: 'none' });
|
|
163
|
+
```
|
|
164
|
+
**A view that pans at a fixed angle** (isometric, tactics, city builders) is that follow camera, not a fixed shot. `mouseLook: false` stops the drag and the wheel from moving the view, and `ground: 'none'` stops hills from tilting it. It follows the player, or with no player any object the game moves:
|
|
165
|
+
```js fragment
|
|
166
|
+
const view = new THREE.Object3D(); // the point the view is centered on
|
|
167
|
+
engine.cameraRig.follow(view); // again on 'session:start': a new playthrough follows the player or nothing
|
|
168
|
+
engine.onFrame(dt => { view.position.x += engine.input.axis.x * 12 * dt; view.position.z -= engine.input.axis.y * 12 * dt; });
|
|
149
169
|
```
|
|
170
|
+
`smoothing` sets how tightly the view keeps up (higher is tighter).
|
|
150
171
|
|
|
151
|
-
|
|
152
|
-
|
|
172
|
+
A `setCamera` before play (boot code, or with the title up) is the camera every playthrough starts from, the same as passing the options to the camera module. During play it is a switch: a new playthrough goes back.
|
|
173
|
+
|
|
174
|
+
- The option is a short way to the real thing below: the rig puts a real `THREE.OrthographicCamera` in `engine.camera`, and the next perspective view brings the camera it replaced back. Pose, `near`, `far`, `zoom`, layers, the parent and anything hung on the camera go with the view. So read `engine.camera` where you use it, and do not keep a copy across a switch.
|
|
153
175
|
- Blends between two orthographic shots blend `size`; a perspective/orthographic mix switches to the target's mode at once. Switching rig kinds returns to perspective.
|
|
154
176
|
- Limits: on the follow camera the mouse wheel changes `size` (clamped to the `minDistance`/`maxDistance` ratio of the starting `distance`).
|
|
155
177
|
The `fov` slider in the settings menu has no effect. Cascaded shadows, `dof` and `outline` handle orthographic depth; a custom post pass that assumes perspective depth must do the same.
|
|
@@ -157,7 +179,7 @@ engine.setCamera('follow', { pitch: 0.6, yaw: 0.8, distance: 20, projection: 'or
|
|
|
157
179
|
**Placing the camera yourself (cutscene, photo mode, your own rig).** Take it with `engine.takeCamera(owner, { focus })`; the camera module leaves the camera alone until you `remove()` the handle.
|
|
158
180
|
Several holders can take it (a cutscene, then a named view on top): the latest is in charge, and removing it hands the camera back to the previous one, not to nobody.
|
|
159
181
|
|
|
160
|
-
```js
|
|
182
|
+
```js fragment
|
|
161
183
|
let t = 0;
|
|
162
184
|
const cam = engine.takeCamera('my-orbit', { focus: engine.player.position }); // focus (optional): where the world loads around
|
|
163
185
|
const frame = engine.onFrame(dt => {
|
|
@@ -166,23 +188,23 @@ const frame = engine.onFrame(dt => {
|
|
|
166
188
|
// done: frame.remove(); cam.remove(); // the rig resumes from its own state
|
|
167
189
|
```
|
|
168
190
|
|
|
169
|
-
To
|
|
191
|
+
To draw through your own three.js camera, assign it. A real `THREE.PerspectiveCamera` or `THREE.OrthographicCamera` is taken as it is, and any other class, a subclass too, is refused:
|
|
170
192
|
|
|
171
|
-
```js
|
|
172
|
-
const original = engine.camera
|
|
173
|
-
const ortho = new THREE.OrthographicCamera(-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
}
|
|
178
|
-
const cam = engine.takeCamera('my-ortho');
|
|
179
|
-
engine.camera = ortho; // the plain render path, cascaded shadows and modules read engine.camera live
|
|
180
|
-
ortho.position.set(10, 10, 10); ortho.lookAt(0, 0, 0); fit(); addEventListener('resize', fit);
|
|
181
|
-
// give it back: removeEventListener('resize', fit); engine.camera = original; cam.remove();
|
|
193
|
+
```js fragment
|
|
194
|
+
const original = engine.camera;
|
|
195
|
+
const ortho = new THREE.OrthographicCamera(-16, 16, 9, -9, 0.1, 500);
|
|
196
|
+
ortho.position.set(10, 10, 10); ortho.lookAt(0, 0, 0);
|
|
197
|
+
engine.camera = ortho; // rendering, post, picking, shadows, audio and the camera module go on with it
|
|
198
|
+
// give it back: engine.camera = original;
|
|
182
199
|
```
|
|
183
200
|
|
|
184
|
-
|
|
185
|
-
`projection: 'orthographic'`
|
|
201
|
+
The aspect follows the canvas, on assignment and on every resize: an orthographic camera keeps its height and its width follows. `engine.autoView.manual('aspect')` before assigning keeps your own frustum. The engine leaves `far` and `fov` of a real orthographic camera alone.
|
|
202
|
+
A camera module goes on placing the camera you assigned, and a camera you assign during a shot stays until the next view is asked for. `projection: 'orthographic', size` sets the height of a real orthographic camera; on a real perspective one the rig's own orthographic camera stands in until the next perspective view, which brings yours back. `pixelSnap` writes the height it needs. A chain taken with `engine.post.own()` is yours to point at the new camera, and a `pixelGrid` you made yourself keeps the camera you gave it.
|
|
203
|
+
|
|
204
|
+
**Side view (side-scroller).** `presets.player.sideScroller` moves the player along world X only (A / D, `z` stays) and turns it toward the move. Face the camera along -Z with `yaw: 0`, so +X is screen right (`yaw: Math.PI` looks from the far side and flips left and right), on `followCamera`:
|
|
205
|
+
```js fragment
|
|
206
|
+
engine.use(followCamera({ projection: 'orthographic', size: 15, yaw: 0, pitch: 0, lockPitch: true, distance: 40, ground: 'none', mouseLook: false }));
|
|
207
|
+
```
|
|
186
208
|
|
|
187
209
|
## 7. Your own camera module
|
|
188
210
|
Everything else in the engine reads only what `modules/camera/contract.js` lists from `engine.cameraRig`: `forward()` / `right()` (control: 'camera',
|
|
@@ -30,13 +30,15 @@ Import it in `content/index.js` and put it in the exported object (`containers`)
|
|
|
30
30
|
|
|
31
31
|
## 3. Buy, sell / consign (two ops + dialogue choices)
|
|
32
32
|
Buying and selling are things the player decides to do, so they are ops (`recipes/23-ops.md`): define them once in `main.js`, and every caller
|
|
33
|
-
(dialogue choice, a shop window button, the dev bridge, a test) runs the same `can` / `run`.
|
|
34
|
-
|
|
33
|
+
(dialogue choice, a shop window button, the dev bridge, a test) runs the same `can` / `run`. A trade is one whole step, so both are `atomic: true` (recipe 23 section 12): `run` frees room
|
|
34
|
+
first, and when the other side cannot take its part it returns `{ ok: false, code }` and the engine puts the bag and the shelf back. **Buy** needs stock on the shelf and the money.
|
|
35
35
|
**Consign**: the player puts something on the shelf, and the shelf pays when it accepts it.
|
|
36
36
|
```js
|
|
37
37
|
// main.js (after engine.use(...inventory()...))
|
|
38
38
|
const price = (e, item) => e.inventory.item(item).price ?? 1;
|
|
39
|
+
const payout = (e, item) => Math.max(1, Math.floor(price(e, item) * 0.6)); // add and remove take 1 or more, never 0
|
|
39
40
|
engine.ops.define('shop.buy', {
|
|
41
|
+
atomic: true,
|
|
40
42
|
args: { shop: 'string', item: 'string' },
|
|
41
43
|
can(e, { shop, item }, ctx) {
|
|
42
44
|
if (!e.inventory.container(shop).has(item)) return 'soldOut';
|
|
@@ -44,23 +46,30 @@ engine.ops.define('shop.buy', {
|
|
|
44
46
|
return true;
|
|
45
47
|
},
|
|
46
48
|
run(e, { shop, item }, ctx) {
|
|
47
|
-
|
|
48
|
-
e.inventory.
|
|
49
|
-
return got;
|
|
49
|
+
e.inventory.container(ctx.actor).remove('gold', price(e, item)); // first: the last coins free their slot for the goods
|
|
50
|
+
return e.inventory.transfer(shop, ctx.actor, item, 1) || { ok: false, code: 'bagFull' };
|
|
50
51
|
},
|
|
51
|
-
reasons: { soldOut: 'Shelf is empty', noMoney: 'Not enough gold' },
|
|
52
|
+
reasons: { soldOut: 'Shelf is empty', noMoney: 'Not enough gold', bagFull: 'No room in the bag' },
|
|
52
53
|
});
|
|
53
54
|
engine.ops.define('shop.sell', {
|
|
55
|
+
atomic: true,
|
|
54
56
|
args: { shop: 'string', item: 'string' },
|
|
55
|
-
can
|
|
57
|
+
can(e, { shop, item }, ctx) {
|
|
58
|
+
if (!e.inventory.container(ctx.actor).has(item)) return 'notInBag';
|
|
59
|
+
return e.inventory.container(shop).room(item) > 0 || 'shelfFull';
|
|
60
|
+
},
|
|
56
61
|
run(e, { shop, item }, ctx) {
|
|
57
|
-
const
|
|
58
|
-
e.inventory.
|
|
59
|
-
return
|
|
62
|
+
const bag = e.inventory.container(ctx.actor), pay = payout(e, item);
|
|
63
|
+
e.inventory.transfer(ctx.actor, shop, item, 1); // first: the last piece frees its slot for the gold
|
|
64
|
+
if (bag.room('gold') < pay) return { ok: false, code: 'bagFull' };
|
|
65
|
+
bag.add('gold', pay, { silent: true });
|
|
66
|
+
return 1;
|
|
60
67
|
},
|
|
68
|
+
reasons: { notInBag: 'Nothing to sell', shelfFull: 'The shelf is full', bagFull: 'No room for the gold' },
|
|
61
69
|
});
|
|
62
70
|
```
|
|
63
|
-
In the dialogue, `if: { can: [...] }` shows a choice only when
|
|
71
|
+
In the dialogue, `if: { can: [...] }` shows a choice only when `can` passes, and `do: { op: [...] }` runs it. `bagFull` comes back from `run`
|
|
72
|
+
(`r.code`), not `can`: it is only known once the goods have moved:
|
|
64
73
|
```js
|
|
65
74
|
// content/dialogues.js
|
|
66
75
|
const buyKit = ['shop.buy', { shop: 'shop-trader', item: 'medkit' }];
|
|
@@ -83,7 +92,7 @@ export default {
|
|
|
83
92
|
```
|
|
84
93
|
- The shelf id (`'shop-trader'`: a market stall, a ship's store, a vending machine) is any string, and the shelf contents are saved. A "shop window" is your own UI drawn from `shelf.list()`; its
|
|
85
94
|
buttons call `engine.ops.run('shop.buy', { shop, item })` and grey out with `engine.ops.can(...)`.
|
|
86
|
-
- Prices live on the item (`price` in items.js above), read with `e.inventory.item('medkit').price`; an item without one costs 1 here.
|
|
95
|
+
- Prices live on the item (`price` in items.js above), read with `e.inventory.item('medkit').price`; an item without one costs 1 here. A price is a whole number of 1 or more.
|
|
87
96
|
- Items with their own data (a used sword with `durability`, recipe 03): pass the entry key as `item` (`'sword#3'`, from `shelf.list()[i].key`);
|
|
88
97
|
`transfer` moves exactly that piece with its data, and `e.inventory.container(shop).get(item)` reads the data for a price
|
|
89
98
|
(`def.price * data.durability / 100`).
|
|
@@ -101,7 +110,3 @@ Loading a save replaces the whole inventory, and refreshing every frame follows
|
|
|
101
110
|
## 5. Saving
|
|
102
111
|
The inventory (gold included) and every container with contents are saved automatically; a shelf that was sold out is remembered too (`{}`), and
|
|
103
112
|
loading does not restock it. You write nothing.
|
|
104
|
-
|
|
105
|
-
## 6. Verification
|
|
106
|
-
The "shop" case in `tests/specs/containers.mjs` runs the whole flow: buy -> consign -> choice disappears when money is short -> save -> refresh and
|
|
107
|
-
load, with the shelf and gold consistent.
|
package/docs/recipes/23-ops.md
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
# Ops: one entry point for what players and NPCs do (engine.ops)
|
|
2
2
|
|
|
3
3
|
**In this recipe**: 1. Define and run · 2. Who calls it, and when · 3. Built-in ops · 4. Read the log · 5. The guard · 6. Testing ·
|
|
4
|
-
7. Scenario tests · 8. Inspect and explain · 9. Randomness ·
|
|
4
|
+
7. Scenario tests · 8. Inspect and explain · 9. Randomness · 11. Structured failures, nextFixed, and who halted the loop ·
|
|
5
5
|
12. Failing in run, atomic ops, revision
|
|
6
6
|
|
|
7
7
|
**What is an op**: one discrete thing an actor decides to do: buy, talk, attack, roll, fire, reload, craft, build, demolish. Write one with
|
|
@@ -14,6 +14,7 @@ in a module's `fixed` or `world.simulate`. Low-level functions such as `inventor
|
|
|
14
14
|
const PRICE = { bread: 5 };
|
|
15
15
|
engine.ops.define('shop.buy', {
|
|
16
16
|
desc: 'Buy from a shop shelf',
|
|
17
|
+
atomic: true, // a failed run puts everything back (section 12)
|
|
17
18
|
args: { shop: 'string', item: 'string', n: 'int?' }, // types: string number int bool position id any; ? = optional
|
|
18
19
|
can(e, { shop, item, n = 1 }, ctx) { // read-only: return true or a reason string
|
|
19
20
|
if (!e.inventory.container(shop).has(item, n)) return 'soldOut';
|
|
@@ -21,12 +22,12 @@ engine.ops.define('shop.buy', {
|
|
|
21
22
|
return true;
|
|
22
23
|
},
|
|
23
24
|
run(e, { shop, item, n = 1 }, ctx) { // runs only after can passed
|
|
24
|
-
|
|
25
|
-
e.inventory.
|
|
26
|
-
return
|
|
25
|
+
e.inventory.container(ctx.actor).remove('gold', PRICE[item] * n);
|
|
26
|
+
if (e.inventory.transfer(shop, ctx.actor, item, n) < n) return { ok: false, code: 'bagFull' };
|
|
27
|
+
return n; // plain data; becomes r.value
|
|
27
28
|
},
|
|
28
29
|
offers: (e, ctx) => [{ shop: 'shop-bakery', item: 'bread' }], // optional: arg sets possible now (ops list / dev bridge `ops`)
|
|
29
|
-
reasons: { soldOut: 'Shelf is empty', noMoney: 'Not enough gold' }, // optional developer notes
|
|
30
|
+
reasons: { soldOut: 'Shelf is empty', noMoney: 'Not enough gold', bagFull: 'No room in the bag' }, // optional developer notes
|
|
30
31
|
// optional: undo(e, args, value, ctx) reverses a finished run; engine.ops.undo('shop.buy', args, r.value) calls it ({ ok: false, code: 'noUndo', facts: { op } } without one)
|
|
31
32
|
});
|
|
32
33
|
|
|
@@ -37,7 +38,7 @@ const { ok } = engine.ops.can('shop.buy', { shop: 'shop-bakery', item: 'bread' }
|
|
|
37
38
|
Rules that keep ops replayable and network-ready:
|
|
38
39
|
- **Use `ctx.actor`, never `engine.player`.** `ctx.actor` is the world record id of whoever acts (default `engine.actor`, which is `'player'` — also
|
|
39
40
|
the player's container id — unless the game hands control to a vehicle or squad member). NPCs run the same op with `{ actor: 'npc_3' }`; where an
|
|
40
|
-
actor stands is `engine.actorPosition(ctx.actor)`.
|
|
41
|
+
actor stands is `engine.actorPosition(ctx.actor)`. `ctx` also has `source`, `tick` and `frozen`; a nested op inherits source and actor.
|
|
41
42
|
- **Args are plain data and self-contained**: no three.js objects (pass `[x, y, z]`), and anything not in world data (aim direction, a clicked build
|
|
42
43
|
position) goes in the args. Pass a fresh object each call; in dev the args are frozen because the history keeps them.
|
|
43
44
|
- **All "may I" checks live in `can`**, so `run` never stops halfway. A failure always has a reason (camelCase English). Show it to the player through
|
|
@@ -56,7 +57,8 @@ Rules that keep ops replayable and network-ready:
|
|
|
56
57
|
|
|
57
58
|
`run` is synchronous and returns at once. Between fixed steps it counts as "after step N", which replays the same. Ops still run while gameplay is
|
|
58
59
|
frozen by a menu (`ctx.frozen` is true; return `'paused'` from `can` for things that must wait); after a gameplay error (`engine.error`) every op
|
|
59
|
-
returns `'halted'`.
|
|
60
|
+
returns `'halted'`. While a save replaces the state (reading it, its parts, `afterLoad`, a rollback) every op returns
|
|
61
|
+
`'loading'` and changes nothing; try again after the load.
|
|
60
62
|
|
|
61
63
|
## 3. Built-in ops (installed with their modules)
|
|
62
64
|
| Op | Args | Reasons |
|
|
@@ -68,8 +70,12 @@ returns `'halted'`.
|
|
|
68
70
|
| `inventory.trade` | `{ take, give, takeN?, giveN?, container? }` (all or nothing in `ctx.actor`'s container; reversible with `engine.ops.undo`, recipe 03) | `noContainer` `notEnough` `full` |
|
|
69
71
|
| `inventory.use` | `{ item }` (from `ctx.actor`'s container; runs the item's `use`, see recipe 03) | `notEnough` `notUsable` or the item's `canUse` reason |
|
|
70
72
|
| `inventory.drop` | `{ item, n? }` (a pickup at the actor's feet, data kept) | `notEnough` `noWorld` `noPosition` |
|
|
71
|
-
| `thing.set` | `{ id, position?, rotation?, scale?, visible? }` (core; a world record via `world.set` / `move`, an `engine.add` object saved as an override when it has an id; undoable, recipe 40) | `noThing` `engineOwned` `recordVisible` |
|
|
73
|
+
| `thing.set` | `{ id, position?, rotation?, scale?, visible? }` (core; a world record via `world.set` / `move`, so a live character is placed with its `placeAt`, an `engine.add` object saved as an override when it has an id; undoable, recipe 40) | `noThing` `engineOwned` `recordVisible` |
|
|
72
74
|
| `thing.remove` | `{ id }` (core; undoable: an `engine.add` object is detached and kept, a record re-added) | `noThing` `engineOwned` |
|
|
75
|
+
| `pickup.take` | `{ id }` (the item goes into `ctx.actor`'s container, or its give function runs) | `unknown` `respawning` `noPosition` `tooFar` and more; `ops.list()` has them all |
|
|
76
|
+
| `npc.talk` | `{ npc, script?, channel? }` (`channel` `main` locks input, `bubble` shows lines over the NPC) | `noDialogue` `unknown` |
|
|
77
|
+
| `grid.place` · `grid.remove` · `grid.move` | `{ grid, item, cell, rotation?, level?, fields?, id? }` · `{ id }` · `{ id, cell, rotation?, grid?, level? }` (recipe 29) | `noGrid` `unknown` `notPlaced` and more; `ops.list()` has them all |
|
|
78
|
+
| `time.skip` | `{ seconds }` (core; timers, calendar events and far simulation catch up in order) | `notForward` |
|
|
73
79
|
| `photo.take` | none (`r.value` is the shot; can = `photo.canTake()`, the key emits `photo:denied { reason }`) | `denied` or yours |
|
|
74
80
|
|
|
75
81
|
## 4. Read the log
|
|
@@ -116,16 +122,18 @@ Put `<workspace>/tests/scenarios/<name>.json` in the engine package or a game; `
|
|
|
116
122
|
{ "snapshot": "after-barter", "only": ["inventory"] }
|
|
117
123
|
] }
|
|
118
124
|
```
|
|
119
|
-
- `state` is `engine.applyState` params; `"pos": "@id"` stands 1 m beside a world record. The
|
|
125
|
+
- `state` is `engine.applyState` params; `"pos": "@id"` stands 1 m beside a world record. The loop is halted first, so game time moves only in `step`
|
|
120
126
|
(seconds) and `press`.
|
|
121
127
|
- `op` steps run with `source: 'test'` (`actor` optional); `expect` is `"ok"` (default) or the failure code. A failure prints the `engine.explain` sentence.
|
|
122
128
|
- `expect` maps `describe()` paths to values (`nearby[0].name` works; numbers within 0.01; `null` = absent). `snapshot` compares with
|
|
123
129
|
`tests/snapshots/<name>.describe.json` (`only` / `ignore` / `tolerance`; write it with `threedog test <name> --update-snapshots`).
|
|
130
|
+
- A file has 120 s under `threedog test`; a long one sets `"timeout"` at the top, in milliseconds, as a spec does.
|
|
124
131
|
- Before any step runs, every op name and step field is checked; a typo fails with "did you mean". The run stops at the first failed step.
|
|
125
|
-
-
|
|
132
|
+
- `{ "until": { path: value }, "within": seconds }` reaches a state by a deadline, however the game freezes on the way; check the end with `expect`. A missed deadline, an error or a stuck load each name themselves. `step` stays strict: a `step` that moved less than asked fails, a freeze the game raised itself included: when a win window opens 0.4 s into `{ "step": 0.6 }`, the failure says how far it got and which window froze the game, and the scenario asks for that much.
|
|
133
|
+
- Use `press` only for the one test per key that proves "key -> op".
|
|
126
134
|
|
|
127
135
|
## 8. Inspect and explain
|
|
128
|
-
```js
|
|
136
|
+
```js fragment
|
|
129
137
|
engine.inspect(); // { actor: 'player', at, near: [...nearby], ops: [{ op, args, ok, code?, why? }] }: what is around and possible now
|
|
130
138
|
engine.inspect('npc_3'); // the same as another actor; engine.inspect([x, z]) around a spot
|
|
131
139
|
engine.explain({ op: 'shop.buy', args: { shop: 'bakery', item: 'bread' } }).text;
|
|
@@ -143,29 +151,25 @@ op's `run` emitted it, seq is the history seq); `chain` walks up to the root as
|
|
|
143
151
|
Gameplay randomness uses `engine.random` (`next / range / int / pick / chance`): it is saved with the game and `createEngine({ seed })` fixes it, so a
|
|
144
152
|
scenario replays the same. `Math.random` breaks both.
|
|
145
153
|
|
|
146
|
-
##
|
|
147
|
-
The engine repository's `Properties` specs (fast-check, a devDependency) runs random sequences of ops / saves / newGame inside the page in one `ev()` and checks the state rules (item totals kept, a refused op changes nothing, save then load is identical, newGame leaves nothing behind, a failed `engine.use` batch changes nothing).
|
|
148
|
-
A failure prints the shrunk minimal sequence and the seed. Replay: `FC_SEED=<seed> npm test -- "Properties: random op"`; more cases: `FC_RUNS=300` (default 25). Without fast-check installed the specs skip and say why.
|
|
149
|
-
To check a new rule, add a step kind to `stepArb` and a check in `pageRun`; turn every found sequence into a fixed regression spec.
|
|
150
|
-
|
|
151
|
-
## 11. Structured failures, nextFixed, and who paused
|
|
154
|
+
## 11. Structured failures, nextFixed, and who halted the loop
|
|
152
155
|
`can` may return a reason string (`'noMoney'`) or a structured failure. Every failed result from `run` / `can` / `undo` has `{ ok: false, code, facts, nextActions }`; a string failure becomes `code = that string`, `facts = {}`, `nextActions = []`, so read `.code` without checking the shape. `engine.inspect()`, `ops.list({ available: true })`, `engine.describe()` actions and `engine.explain({ op })` carry `facts` / `nextActions` too.
|
|
153
156
|
```js
|
|
154
|
-
engine.
|
|
157
|
+
const gold = ctx => engine.inventory.container(ctx.actor).count('gold');
|
|
158
|
+
engine.ops.define('shop.rent', {
|
|
155
159
|
can: (e, a, ctx) => gold(ctx) >= 5 || { code: 'noMoney', facts: { need: 5, have: gold(ctx) }, nextActions: [{ op: 'job.work', args: {} }] },
|
|
156
160
|
run: (e, a, ctx) => { /* ... */ },
|
|
157
161
|
});
|
|
158
|
-
const r = engine.ops.run('shop.
|
|
162
|
+
const r = engine.ops.run('shop.rent', {}); // r.ok === false, r.code === 'noMoney', r.facts.need === 5, r.nextActions[0].op === 'job.work'
|
|
159
163
|
```
|
|
160
164
|
`engine.nextFixed(fn)` runs `fn` at the start of the next fixed step and returns a Promise of its value, so a UI click or a promise callback can safely write gameplay state: `await engine.nextFixed(() => engine.ops.run('door.open', { id: 'gate' }))`. It is built on `engine.commits` and waits while frozen or loading.
|
|
161
165
|
|
|
162
|
-
Tests that
|
|
166
|
+
Tests that halt the loop name themselves (default `'game'`) and end their own halt with the handle: `const h = engine.haltLoop('my-test'); ... h.remove()`. The loop stays halted until every owner has removed theirs, so one helper cannot end another's halt.
|
|
163
167
|
|
|
164
168
|
## 12. Failing in run, atomic ops, revision
|
|
165
|
-
`run` can fail like `can`: return or throw `{ ok: false, code, facts, nextActions }` (
|
|
169
|
+
`run` can fail like `can`: return or throw `{ ok: false, code, facts, nextActions }` (`ok: false` is required). `facts` is an object (`{ need: 5 }`) or a list of `{ id, field, actual, expected? }` naming the record and field that were wrong. Every result carries `revision` (`engine.ops.revision`), a counter bumped once per committed op.
|
|
166
170
|
```js
|
|
167
171
|
engine.ops.define('craft.bread', {
|
|
168
|
-
atomic: true, // every part declared atomic
|
|
172
|
+
atomic: true, // every save part declared atomic is undone if run fails or throws
|
|
169
173
|
run(e, { oven }, ctx) {
|
|
170
174
|
e.inventory.container(ctx.actor).remove('flour', 2);
|
|
171
175
|
if (e.world.get(oven).heat < 3) return { ok: false, code: 'ovenCold', facts: [{ id: oven, field: 'heat', actual: e.world.get(oven).heat, expected: 3 }], nextActions: [{ op: 'oven.light', args: { oven } }] };
|
|
@@ -174,8 +178,8 @@ engine.ops.define('craft.bread', {
|
|
|
174
178
|
after: (e) => e.audio.sfx('ding'), // sound / animation: runs only after the op committed
|
|
175
179
|
});
|
|
176
180
|
```
|
|
177
|
-
What atomic covers
|
|
181
|
+
What atomic covers: it copies the save parts that declared `saves.register(key, { atomic: true })` (a game's own part can opt in) before `run` and loads them back on failure, so it costs one save of those per run (wrong for a per-frame op in a huge world). Events already emitted, sound, animation and any other module's state are not undone; keep such effects in `after`. Ops called from an atomic run join it (their `after` hooks run, nested first, at the outermost commit; a rolled-back outer takes back their revision). `ops.list()` and `engine.explain({ op })` report `atomic`.
|
|
178
182
|
|
|
179
183
|
Causal trace (`events.traceSize > 0`, recipe 06): failed ops are noted as `op:<name>` with their `code`; `collision.lineClear(a, b, { who })` as `sight` (blocked lines always, clear ones for the focused object only); NPC state changes as `npc:state`. A game's behavior notes its own mode switch with `engine.events.note('npc:mode', { obj: rec.id, data: { from: 'patrol', to: 'investigate' } })`; `events.traceFocus('guard-1')` makes one object verbose.
|
|
180
184
|
|
|
181
|
-
Atomic details: a rolled-back run still bumps `ops.revision` (it only goes up, never back to an old number) and its committed nested ops show in `ops.recent()` as `ok: false` with code `rolledBack`.
|
|
185
|
+
Atomic details: a rolled-back run still bumps `ops.revision` (it only goes up, never back to an old number) and its committed nested ops show in `ops.recent()` as `ok: false` with code `rolledBack`. The rollback does not run `afterLoad` and mutes the events its loads would emit, so atomic state must be plain data.
|