threedog 0.7.0 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +196 -1
- package/README.md +6 -9
- package/core/{Animator.js → assets/Animator.js} +28 -18
- package/core/{Assets.js → assets/Assets.js} +98 -54
- package/core/{Baked.js → assets/Baked.js} +4 -4
- package/core/assets/assetEntry.js +237 -0
- package/core/{assetHot.js → assets/assetHot.js} +7 -6
- 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} +6 -12
- package/core/{namedModel.js → assets/namedModel.js} +17 -13
- package/core/{Audio.js → audio/Audio.js} +26 -23
- 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} +10 -10
- package/core/{Random.js → base/Random.js} +5 -4
- package/core/{easing.js → base/easing.js} +1 -1
- package/core/{errorCodes.js → base/errorCodes.js} +98 -110
- package/core/{errorHints.js → base/errorHints.js} +5 -9
- package/core/{errors.js → base/errors.js} +6 -6
- package/core/{events.generated.js → base/events.generated.js} +1 -0
- package/core/{math.js → base/math.js} +15 -4
- package/core/{params.js → base/params.js} +3 -4
- package/core/base/util.js +32 -0
- package/core/{validate.js → base/validate.js} +28 -7
- package/core/{Engine.js → engine/Engine.js} +80 -77
- package/core/{Loading.js → engine/Loading.js} +4 -2
- package/core/{copies.js → engine/copies.js} +4 -4
- package/core/{headlessLoad.js → engine/headlessLoad.js} +4 -4
- package/core/{lifecycle.js → engine/lifecycle.js} +14 -12
- package/core/{loop.js → engine/loop.js} +68 -47
- package/core/{moduleSlots.js → engine/moduleSlots.js} +6 -6
- package/core/{moduleTypes.js → engine/moduleTypes.js} +13 -14
- package/core/{modules.js → engine/modules.js} +14 -11
- package/core/{page.js → engine/page.js} +36 -23
- package/core/{plugins.js → engine/plugins.js} +6 -9
- package/core/{services.js → engine/services.js} +47 -40
- package/core/{startup.js → engine/startup.js} +26 -24
- package/core/{Input.js → input/Input.js} +30 -22
- package/core/{inputContext.js → input/inputContext.js} +14 -5
- package/core/{inputPad.js → input/inputPad.js} +1 -1
- package/core/{inputPointer.js → input/inputPointer.js} +8 -2
- package/core/{inputTouch.js → input/inputTouch.js} +1 -1
- package/core/{Budget.js → inspect/Budget.js} +21 -20
- package/core/{DebugOverrides.js → inspect/DebugOverrides.js} +30 -16
- package/core/{Describe.js → inspect/Describe.js} +26 -22
- package/core/{Inspect.js → inspect/Inspect.js} +9 -7
- 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} +52 -20
- package/core/{catalog.js → inspect/catalog.js} +3 -3
- 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} +21 -20
- package/core/{describeText.js → inspect/describeText.js} +11 -6
- package/core/inspect/geometryWatch.js +38 -0
- package/core/{lightWatch.js → inspect/lightWatch.js} +8 -8
- package/core/{pictureWriters.js → inspect/pictureWriters.js} +15 -16
- package/core/{shaderCost.js → inspect/shaderCost.js} +1 -1
- package/core/{Ops.js → ops/Ops.js} +16 -11
- package/core/{control.js → ops/control.js} +13 -12
- package/core/ops/holds.js +139 -0
- package/core/{opsAtomic.js → ops/opsAtomic.js} +2 -1
- package/core/{opsCheck.js → ops/opsCheck.js} +4 -5
- package/core/{opsGuard.js → ops/opsGuard.js} +3 -3
- package/core/{opsRun.js → ops/opsRun.js} +7 -4
- package/core/{owned.js → ops/owned.js} +14 -17
- package/core/{sharedPoint.js → ops/sharedPoint.js} +8 -8
- package/core/{stackFrames.js → ops/stackFrames.js} +2 -2
- package/core/{stacks.js → ops/stacks.js} +12 -14
- package/core/{wrap.js → ops/wrap.js} +8 -6
- package/core/{SaveStore.js → saves/SaveStore.js} +1 -1
- package/core/{Saves.js → saves/Saves.js} +58 -36
- package/core/{saveApply.js → saves/saveApply.js} +13 -9
- package/core/{saveFiles.js → saves/saveFiles.js} +17 -15
- package/core/{saveValues.js → saves/saveValues.js} +20 -3
- package/core/{saveVersions.js → saves/saveVersions.js} +4 -17
- package/core/{session.js → saves/session.js} +31 -17
- package/core/{Rays.js → scene/Rays.js} +23 -25
- package/core/{Views.js → scene/Views.js} +14 -6
- package/core/{adaptive.js → scene/adaptive.js} +15 -8
- package/core/{canvasBox.js → scene/canvasBox.js} +2 -3
- package/core/{engineCamera.js → scene/engineCamera.js} +1 -1
- 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} +4 -4
- package/core/{gridLoad.js → scene/gridLoad.js} +1 -1
- package/core/{ground.js → scene/ground.js} +9 -9
- package/core/{movement.js → scene/movement.js} +3 -3
- package/core/{pictureSlots.js → scene/pictureSlots.js} +2 -2
- package/core/{sceneDelta.js → scene/sceneDelta.js} +2 -2
- package/core/{sceneMethods.js → scene/sceneMethods.js} +36 -13
- package/core/scene/stepPoses.js +55 -0
- package/core/{targeting.js → scene/targeting.js} +4 -5
- package/core/{thingExplain.js → scene/thingExplain.js} +6 -5
- package/core/{thingOps.js → scene/thingOps.js} +4 -3
- package/core/{things.js → scene/things.js} +18 -5
- package/core/{threePatches.js → scene/threePatches.js} +1 -1
- package/core/{view.js → scene/view.js} +17 -16
- package/core/{Batching.js → stream/Batching.js} +85 -27
- package/core/{Stream.js → stream/Stream.js} +60 -30
- package/core/{batchGroups.js → stream/batchGroups.js} +10 -9
- package/core/{chunkStream.js → stream/chunkStream.js} +40 -0
- package/core/{scatter.js → stream/scatter.js} +2 -2
- package/core/{streamSources.js → stream/streamSources.js} +12 -7
- package/core/{Commits.js → threads/Commits.js} +6 -5
- package/core/{Jobs.js → threads/Jobs.js} +12 -10
- package/core/{Threads.js → threads/Threads.js} +16 -16
- 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} +17 -10
- package/core/{dayTime.js → time/dayTime.js} +5 -1
- package/core/{skip.js → time/skip.js} +18 -17
- package/core/{time.js → time/time.js} +18 -12
- package/core/{uiClock.js → time/uiClock.js} +4 -4
- package/docs/AI.md +22 -19
- package/docs/API.md +24 -23
- package/docs/CODEMAP.md +76 -183
- package/docs/COMMANDS.md +66 -58
- package/docs/CONVENTIONS.md +54 -14
- package/docs/MIGRATING-0.8.md +169 -0
- package/docs/THREE.md +78 -29
- 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 +29 -29
- package/docs/api/characters.md +23 -18
- package/docs/api/clock.md +1 -1
- package/docs/api/collision.md +12 -9
- package/docs/api/content.md +6 -6
- package/docs/api/dialogue.md +3 -3
- package/docs/api/engine.md +45 -43
- package/docs/api/events.md +3 -2
- package/docs/api/flow.md +1 -1
- package/docs/api/grids.md +1 -1
- package/docs/api/ground.md +4 -5
- package/docs/api/hud.md +2 -2
- package/docs/api/i18n.md +6 -6
- package/docs/api/input.md +7 -7
- package/docs/api/interactions.md +4 -4
- package/docs/api/inventory.md +9 -9
- package/docs/api/jobs.md +5 -5
- package/docs/api/level.md +7 -7
- package/docs/api/lightPool.md +1 -6
- package/docs/api/music.md +3 -3
- package/docs/api/nav.md +10 -10
- package/docs/api/openWorld.md +1 -1
- package/docs/api/particles.md +2 -2
- package/docs/api/photo.md +4 -2
- package/docs/api/pickups.md +2 -2
- package/docs/api/post.md +20 -3
- package/docs/api/quests.md +3 -3
- package/docs/api/rays.md +5 -7
- package/docs/api/rigid.md +27 -18
- package/docs/api/saves.md +8 -7
- package/docs/api/settings.md +9 -8
- package/docs/api/sky.md +8 -7
- package/docs/api/stream.md +7 -7
- package/docs/api/swarm.md +34 -0
- package/docs/api/terrain.md +7 -8
- package/docs/api/terrainDraw.md +1 -1
- package/docs/api/timeline.md +2 -2
- package/docs/api/tools.md +25 -22
- package/docs/api/vars.md +1 -1
- package/docs/api/vegetation.md +4 -3
- package/docs/api/vegetationDraw.md +1 -1
- package/docs/api/water.md +1 -1
- package/docs/api/weather.md +9 -9
- package/docs/api/weatherDraw.md +3 -3
- package/docs/api/world.md +5 -5
- package/docs/recipes/01-new-game.md +25 -40
- package/docs/recipes/02-npc.md +19 -20
- package/docs/recipes/03-items-pickups.md +27 -43
- package/docs/recipes/04-quests.md +3 -4
- package/docs/recipes/05-props-bake.md +29 -39
- package/docs/recipes/06-clock-events.md +27 -18
- package/docs/recipes/07-flow-scenes-pause.md +12 -17
- package/docs/recipes/08-weather-sky.md +88 -34
- package/docs/recipes/09-materials-lights-models.md +22 -36
- package/docs/recipes/10-blender-level.md +6 -7
- package/docs/recipes/11-vehicles.md +30 -22
- package/docs/recipes/12-navmesh.md +9 -8
- package/docs/recipes/13-animation.md +39 -17
- package/docs/recipes/14-custom-module.md +14 -13
- package/docs/recipes/15-perf.md +49 -26
- package/docs/recipes/16-dev-bridge.md +32 -52
- package/docs/recipes/18-world.md +36 -23
- package/docs/recipes/19-shooting-picking.md +4 -2
- package/docs/recipes/20-content-actions-save.md +30 -35
- package/docs/recipes/21-camera.md +33 -5
- package/docs/recipes/22-shop-gold.md +0 -4
- package/docs/recipes/23-ops.md +10 -10
- package/docs/recipes/26-ui-parts.md +22 -12
- package/docs/recipes/27-net.md +0 -2
- package/docs/recipes/28-terrain.md +117 -21
- package/docs/recipes/29-grid.md +2 -2
- package/docs/recipes/30-templates.md +55 -19
- package/docs/recipes/31-audio.md +5 -5
- package/docs/recipes/32-action-game.md +15 -6
- package/docs/recipes/33-stream-sources.md +2 -2
- package/docs/recipes/34-environment-lighting.md +67 -19
- package/docs/recipes/35-picture-from-reference.md +10 -17
- package/docs/recipes/36-ground-plants.md +105 -0
- package/docs/recipes/40-scene.md +7 -11
- package/docs/recipes/43-shader-patches-surfaces.md +20 -41
- package/docs/recipes/44-water-weather-hooks.md +48 -43
- package/docs/recipes/45-cascaded-shadows.md +39 -17
- package/docs/recipes/46-blender-art-route.md +7 -8
- package/docs/recipes/49-game-module-contract.md +5 -5
- package/docs/recipes/50-own-renderer.md +2 -2
- package/docs/recipes/52-around-the-picture.md +54 -98
- package/docs/recipes/53-ground-up-close.md +61 -24
- package/docs/recipes/55-mods-time-wrap.md +12 -16
- package/docs/recipes/56-webgpu-tsl.md +16 -14
- package/docs/recipes/57-control.md +9 -2
- package/docs/recipes/58-input.md +2 -2
- package/docs/recipes/59-depth-post-effects.md +1 -1
- package/docs/recipes/60-judge-the-picture.md +29 -24
- package/docs/recipes/62-picture-code.md +49 -17
- package/docs/recipes/63-third-person-start.md +17 -4
- package/docs/recipes/64-particles.md +1 -1
- package/docs/recipes/65-swarm.md +140 -0
- package/examples/action/.threedog/content-index.json +1 -1
- package/examples/action/GAMEMAP.md +2 -2
- package/examples/{sheepisland → perf-island}/.threedog/content-index.json +1 -1
- package/examples/{sheepisland → perf-island}/GAMEMAP.md +12 -11
- 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 +1 -0
- package/examples/rc2d/GAMEMAP.md +3 -2
- package/examples/rc2d/main.js +1 -3
- package/examples/styletest/.threedog/content-index.json +1 -1
- package/examples/styletest/GAMEMAP.md +3 -2
- 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 +1 -0
- package/examples/world/.threedog/content-index.json +1 -1
- package/examples/world/GAMEMAP.md +4 -3
- package/examples/world/picture/sky.js +1 -1
- package/index.d.ts +8 -7
- package/index.js +31 -31
- package/llms.txt +9 -13
- package/modules/ambience/Ambience.js +11 -8
- package/modules/calendar/Calendar.js +19 -19
- package/modules/calendar/index.js +13 -13
- package/modules/calendar/schedule.js +11 -6
- package/modules/calendar/seasons.js +7 -7
- package/modules/camera/FirstPersonCamera.js +2 -2
- package/modules/camera/FixedCamera.js +14 -15
- package/modules/camera/FollowCamera.js +4 -4
- package/modules/camera/RtsCamera.js +11 -11
- package/modules/camera/common.js +48 -24
- package/modules/camera/contract.js +1 -0
- package/modules/camera/projection.js +2 -2
- package/modules/characters/Character.js +33 -30
- package/modules/characters/NPC.js +27 -19
- package/modules/characters/assetModel.js +14 -10
- package/modules/characters/astar.js +7 -5
- package/modules/characters/behaviors.js +4 -5
- package/modules/characters/contract.js +2 -2
- package/modules/characters/index.js +168 -214
- package/modules/characters/moveHelpers.js +14 -3
- package/modules/characters/movers/common.js +16 -14
- package/modules/characters/movers/manual.js +1 -1
- package/modules/characters/movers/rapier.js +7 -6
- package/modules/characters/movers/simple.js +3 -3
- package/modules/characters/movers/support.js +8 -8
- package/modules/characters/npcAvoid.js +4 -4
- package/modules/characters/npcSim.js +23 -17
- package/modules/characters/npcView.js +6 -5
- package/modules/characters/pathAsync.js +12 -10
- package/modules/characters/pathWorker.js +1 -1
- package/modules/characters/player.js +108 -0
- package/modules/characters/playerStrings.js +2 -2
- package/modules/characters/proceduralRig.js +2 -2
- package/modules/characters/useModel.js +3 -3
- package/modules/characters/walkTo.js +11 -17
- package/modules/collision/Collision.js +26 -20
- package/modules/collision/contract.js +15 -0
- package/modules/content/explain.js +1 -2
- package/modules/content/fields.js +24 -3
- package/modules/content/ids.js +2 -2
- package/modules/content/index.js +61 -99
- package/modules/content/loader.js +14 -17
- package/modules/content/markers.js +25 -0
- package/modules/content/models.js +10 -7
- package/modules/content/packs.js +3 -3
- package/modules/content/parts.js +2 -2
- package/modules/content/places.js +35 -0
- package/modules/content/props.js +17 -14
- package/modules/content/rules.js +25 -21
- package/modules/content/stages.js +7 -7
- package/modules/content/templates.js +20 -20
- package/modules/content/words.js +34 -0
- package/modules/debug/DebugPanel.js +10 -43
- package/modules/flow/contract.js +1 -1
- package/modules/flow/index.js +11 -7
- package/modules/gameplay/Container.js +12 -11
- package/modules/gameplay/Containers.js +14 -5
- package/modules/gameplay/Dialogue.js +13 -11
- package/modules/gameplay/Interactions.js +37 -24
- package/modules/gameplay/Inventory.js +8 -9
- package/modules/gameplay/Quests.js +16 -9
- package/modules/gameplay/boxOps.js +1 -1
- package/modules/gameplay/dialogueBubbles.js +3 -4
- package/modules/gameplay/inventoryOps.js +0 -1
- package/modules/gameplay/pickups.js +22 -23
- package/modules/gameplay/questSave.js +3 -3
- package/modules/grid/Grid.js +1 -1
- package/modules/grid/Layer.js +4 -4
- package/modules/grid/index.js +7 -8
- package/modules/grid/preview.js +7 -7
- package/modules/grid/tiles.js +6 -6
- package/modules/hlod/index.js +37 -55
- package/modules/hud/index.js +17 -11
- package/modules/hud/parts.js +4 -4
- package/modules/level/contract.js +16 -0
- package/modules/level/heightfield.js +12 -10
- package/modules/level/index.js +47 -152
- package/modules/level/load.js +79 -0
- package/modules/level/meshes.js +65 -0
- package/modules/level/nodes.js +6 -7
- package/modules/lights/index.js +28 -181
- package/modules/lights/slots.js +93 -0
- package/modules/lights/sources.js +88 -0
- package/modules/music/Music.js +30 -26
- package/modules/music/rules.js +1 -1
- package/modules/nav/contract.js +14 -0
- package/modules/nav/index.js +11 -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 +5 -4
- package/modules/net/sync.js +2 -2
- package/modules/net/transports.js +2 -2
- package/modules/particles/Particles.js +11 -8
- package/modules/particles/effect.js +7 -5
- package/modules/particles/shaders.js +2 -1
- package/modules/photo/Photo.js +15 -17
- package/modules/rigid/RigidBodies.js +66 -43
- package/modules/rigid/Vehicles.js +2 -3
- package/modules/rigid/ragdoll.js +287 -0
- package/modules/rigid/ragdollBones.js +159 -0
- package/modules/rigid/sync.js +6 -6
- package/modules/settings/Settings.js +108 -39
- package/modules/settings/apply.js +6 -6
- package/modules/settings/sections.js +16 -14
- 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 +14 -27
- package/modules/sky/tint.js +1 -1
- package/modules/swarm/Swarm.js +346 -0
- package/modules/swarm/draw.js +68 -0
- package/modules/swarm/grid.js +63 -0
- package/modules/terrain/ChunkManager.js +70 -52
- 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 +28 -34
- package/modules/terrain/terrainColorMap.js +6 -3
- package/modules/terrain/terrainDefaults.js +2 -1
- package/modules/terrain/terrainEdit.js +32 -27
- package/modules/terrain/terrainGen.js +17 -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 +27 -19
- package/modules/timeline/Tween.js +6 -6
- package/modules/timeline/shots.js +5 -7
- package/modules/triggers/index.js +9 -9
- package/modules/vegetation/Vegetation.js +30 -23
- package/modules/vegetation/densityMap.js +4 -7
- package/modules/vegetation/draw.js +23 -18
- package/modules/vegetation/groundChunks.js +11 -31
- package/modules/vegetation/index.js +8 -6
- package/modules/vegetation/modelGeometry.js +3 -6
- package/modules/vegetation/nearFade.js +1 -1
- package/modules/water/Water.js +16 -16
- package/modules/water/surface.js +3 -3
- package/modules/weather/Weather.js +41 -30
- package/modules/weather/particles.js +8 -8
- package/modules/weather/weatherDraw.js +22 -18
- package/modules/world/World.js +8 -8
- package/modules/world/explain.js +1 -1
- package/modules/world/index.js +18 -12
- package/modules/world/persist.js +73 -25
- package/modules/world/pos.js +4 -4
- package/modules/world/records.js +28 -8
- package/modules/world/sim.js +4 -4
- package/modules/world/state.js +12 -5
- package/modules/world/thingSource.js +4 -2
- package/modules/world/views.js +11 -9
- package/package.json +42 -7
- package/presets.js +1 -3
- package/render/PostFX.js +39 -27
- package/render/backend.js +26 -32
- 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/patchNodes.tsl.js +5 -15
- package/render/fx/postWebGPU.tsl.js +27 -23
- 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 +1 -1
- package/render/lighting.js +5 -3
- package/render/lightmap.js +20 -20
- 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 +20 -4
- package/render/ownFrame.js +4 -4
- package/render/patches.js +13 -13
- package/render/postWebGL.js +12 -10
- package/render/probes.js +16 -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 +57 -11
- package/render/slots.js +7 -7
- package/render/terms.js +22 -24
- package/render/uniformDecl.js +1 -1
- package/types/core.d.ts +200 -153
- package/types/gameplay.d.ts +163 -91
- 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} +7 -15
- 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} +12 -8
- package/types/generated/core/{Budget.d.ts → inspect/Budget.d.ts} +36 -26
- package/types/generated/core/{DebugOverrides.d.ts → inspect/DebugOverrides.d.ts} +2 -2
- package/types/generated/core/{Ops.d.ts → ops/Ops.d.ts} +4 -3
- package/types/generated/core/{control.d.ts → ops/control.d.ts} +4 -10
- package/types/generated/core/{Saves.d.ts → saves/Saves.d.ts} +37 -13
- package/types/generated/core/{session.d.ts → saves/session.d.ts} +2 -1
- package/types/generated/core/{Rays.d.ts → scene/Rays.d.ts} +8 -27
- package/types/generated/core/{Views.d.ts → scene/Views.d.ts} +1 -1
- package/types/generated/core/{Batching.d.ts → stream/Batching.d.ts} +7 -7
- package/types/generated/core/{Stream.d.ts → stream/Stream.d.ts} +18 -16
- 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/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 +1 -1
- 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 +2 -1
- package/types/generated/modules/water/Water.d.ts +1 -0
- package/types/generated/modules/weather/Weather.d.ts +16 -12
- package/types/generated/modules/weather/weatherDraw.d.ts +3 -3
- package/types/generated/modules/world/World.d.ts +5 -3
- package/types/generated/render/PostFX.d.ts +17 -11
- 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 +11 -11
- package/types/physics.d.ts +99 -70
- package/types/tsl.d.ts +37 -4
- package/types/world.d.ts +38 -71
- package/ui/Focus.js +10 -9
- package/ui/Parts.js +4 -3
- package/ui/UI.js +7 -7
- package/ui/defaults.js +3 -2
- package/ui/theme.js +5 -3
- package/core/assetEntry.js +0 -109
- package/core/holds.js +0 -134
- package/core/shadowTypes.js +0 -16
- package/core/util.js +0 -17
- 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/core/{Vars.js → base/Vars.js} +0 -0
- /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/{opsFail.js → ops/opsFail.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/{tier.js → scene/tier.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):
|
|
@@ -32,7 +32,7 @@ export default {
|
|
|
32
32
|
for (const [id, r] of Object.entries(data)) if (!ctx.data.items?.[r.makes]) ctx.err(`recipe ${id} makes unknown item ${r.makes}`);
|
|
33
33
|
},
|
|
34
34
|
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
|
|
35
|
+
// optional: the keys of each entry (core/base/params.js format, no default); threedog check reports unknown keys, wrong types, out of range
|
|
36
36
|
fields: { needs: 'object', makes: 'string', seconds: { type: 'number', min: 0, optional: true, desc: 'crafting time' } },
|
|
37
37
|
},
|
|
38
38
|
},
|
|
@@ -42,13 +42,15 @@ export default {
|
|
|
42
42
|
// content/recipes.js
|
|
43
43
|
export default { bread: { needs: { flour: 2 }, makes: 'bread' } };
|
|
44
44
|
```
|
|
45
|
-
Add `recipes` to `content/index.js` like any other file
|
|
46
|
-
|
|
45
|
+
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`
|
|
46
|
+
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.
|
|
47
|
+
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:
|
|
48
|
+
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.
|
|
49
|
+
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
|
|
50
|
+
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
51
|
|
|
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.
|
|
52
|
+
**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
|
|
53
|
+
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
54
|
|
|
53
55
|
## 1b. Content packs: several data sets in one load
|
|
54
56
|
A content pack is the same object `content/index.js` exports (`{ items, templates, props, quests, ... }`, optional `name` for messages), shipped as a
|
|
@@ -60,7 +62,7 @@ import packs from './assets.js'; // export default [f
|
|
|
60
62
|
engine.assets.manifest(packs); // the same objects `npm run check` reads the names from
|
|
61
63
|
engine.content.load([base, forest], { places: { home } });
|
|
62
64
|
```
|
|
63
|
-
- Packs load in list order, so a pack may use what an earlier one defines.
|
|
65
|
+
- 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
66
|
- 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
67
|
separate `load` call still overrides by name on purpose (hot reload, a chapter replacing a quest).
|
|
66
68
|
- A pack may carry its sounds: `audio: { sounds, ambience, music, footsteps }` (`recipes/31-audio.md` section 8). Sounds, footsteps and music tracks
|
|
@@ -148,7 +150,7 @@ if (engine.saves.check('auto') === null) await engine.session.load('auto'); //
|
|
|
148
150
|
- `engine.session.load(slot)` and `engine.session.newGame()` both return `Promise<boolean>`: always `await`. `session.load` starts from the new-game
|
|
149
151
|
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
152
|
state. `engine.saves.load(slot)` is a quick load onto the running playthrough; never build Continue from it.
|
|
151
|
-
- Loading restores the player, world data (world changes and deletions), inventory, quests, clock and random state; initial data in content files
|
|
153
|
+
- 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
154
|
(`initial`) is the same whether it is loaded before or after the save, so ignore the order.
|
|
153
155
|
- 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
156
|
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 +160,14 @@ if (engine.saves.check('auto') === null) await engine.session.load('auto'); //
|
|
|
158
160
|
- During development, to jump straight into a save: URL `?save=slot1` (`threedog state` also understands `save=`).
|
|
159
161
|
- In tests, `engine.saves.save('x'); await engine.saves.flush();` writes before reading back.
|
|
160
162
|
|
|
163
|
+
## 4b. Best times and high scores: data that outlives saves
|
|
164
|
+
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:
|
|
165
|
+
```js
|
|
166
|
+
const key = engine.saves.storageKey('records');
|
|
167
|
+
const records = () => JSON.parse(localStorage.getItem(key) ?? '{ "laps": [] }');
|
|
168
|
+
const addLap = time => { const r = records(); r.laps.push(time); localStorage.setItem(key, JSON.stringify(r)); };
|
|
169
|
+
```
|
|
170
|
+
|
|
161
171
|
## Save failures and versions
|
|
162
172
|
- `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
173
|
localStorage refused) it is `false`, the player already saw why, and the previous save of that slot is kept (memory follows the disk).
|
|
@@ -171,22 +181,21 @@ if (engine.saves.check('auto') === null) await engine.session.load('auto'); //
|
|
|
171
181
|
channels, random state or item counts is clamped or dropped with one `save-value` warning per part, and the rest loads.
|
|
172
182
|
- 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
183
|
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:
|
|
184
|
+
- `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
185
|
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).
|
|
186
|
+
- 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
187
|
|
|
179
|
-
## Save format
|
|
188
|
+
## Save format
|
|
180
189
|
A save is one envelope; `engine.saves.collect()` returns it and `export` / `exportFile` carry it unchanged:
|
|
181
190
|
```js fragment
|
|
182
191
|
{ format: 1, // the envelope's own version: a save with a higher format is refused as tooNew (none = 1)
|
|
183
192
|
savedAt: 1730000000000, // real time of the save
|
|
184
|
-
versions: { world:
|
|
193
|
+
versions: { world: 5, quests: 2, clock: 1 }, // each part's version (none = 1)
|
|
185
194
|
parts: { world: {...}, quests: {...}, clock: {...}, vars: {...} } } // each saves.register part's data, by key
|
|
186
195
|
```
|
|
187
|
-
- **Parts and versions**: each `engine.saves.register(key, { version, migrate, save, load })` owns one part. When `save()` changes shape, raise
|
|
196
|
+
- **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
|
|
188
197
|
`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. A
|
|
189
|
-
part from a newer build, or a missing step, refuses the whole load before anything changes.
|
|
198
|
+
part from a newer build, or a missing step, refuses the whole load before anything changes. 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
199
|
- **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
200
|
back unchanged on every save, and handed to the module if it registers later. Only a new game drops it.
|
|
192
201
|
- **Authored baseline + per-id diff**: everything placed in a level comes from content (props, template instances, pickups, NPCs, grid items in
|
|
@@ -194,25 +203,11 @@ A save is one envelope; `engine.saves.collect()` returns it and `export` / `expo
|
|
|
194
203
|
`changed` (fields of an authored record that differ), `removed` (authored records removed), `records` (records created during play, such as
|
|
195
204
|
`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
205
|
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 -->
|
|
206
|
+
- **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 -->
|
|
207
|
+
- **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 -->
|
|
208
|
+
- **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
209
|
- **Stable ids, never positions**: saved data names things by stable ids. The player's vehicle is saved by `rigid.addWheeled(mesh, { id })`; quest
|
|
213
210
|
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
211
|
- The export file wraps the envelope:
|
|
217
212
|
`{ threedog: 'save', format: 1, game, slot, savedAt, data: <envelope>, files: [{ group, id, at, meta, type, url: 'data:...' }] }`.
|
|
218
|
-
- Tests: `
|
|
213
|
+
- 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,11 +39,12 @@ 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`.
|
|
@@ -52,7 +53,7 @@ engine.setCamera('follow', { distance: 8, pitch: 0.3 });
|
|
|
52
53
|
```js
|
|
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,6 +92,19 @@ 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
|
|
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,
|
|
@@ -145,8 +159,17 @@ The default stays perspective. On resize the view height stays `size` and the wi
|
|
|
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
|
|
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).
|
|
171
|
+
|
|
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.
|
|
150
173
|
|
|
151
174
|
- `engine.camera` stays the one object everything holds (render, post, shadows, sky); it is flipped to an orthographic matrix, so `camera.isOrthographicCamera`
|
|
152
175
|
is true, `camera.left/right/top/bottom` are set, and `camera.zoom` still zooms. `camera.fov` is ignored while it is on.
|
|
@@ -184,6 +207,11 @@ ortho.position.set(10, 10, 10); ortho.lookAt(0, 0, 0); fit(); addEventListener('
|
|
|
184
207
|
Swapping the object only works while no post effect is active: the post chain's scene pass keeps the camera it was built with. With post effects, use
|
|
185
208
|
`projection: 'orthographic'` above instead.
|
|
186
209
|
|
|
210
|
+
**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`:
|
|
211
|
+
```js
|
|
212
|
+
engine.use(followCamera({ projection: 'orthographic', size: 15, yaw: 0, pitch: 0, lockPitch: true, distance: 40, ground: 'none', mouseLook: false }));
|
|
213
|
+
```
|
|
214
|
+
|
|
187
215
|
## 7. Your own camera module
|
|
188
216
|
Everything else in the engine reads only what `modules/camera/contract.js` lists from `engine.cameraRig`: `forward()` / `right()` (control: 'camera',
|
|
189
217
|
faceMode 'camera', targeting), `follow(object, opts?)` (createPlayer, getting in and out of a vehicle), `focusPoint()` (photo, where the world loads)
|
|
@@ -101,7 +101,3 @@ Loading a save replaces the whole inventory, and refreshing every frame follows
|
|
|
101
101
|
## 5. Saving
|
|
102
102
|
The inventory (gold included) and every container with contents are saved automatically; a shelf that was sold out is remembered too (`{}`), and
|
|
103
103
|
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
|
|
@@ -70,6 +70,10 @@ returns `'halted'`.
|
|
|
70
70
|
| `inventory.drop` | `{ item, n? }` (a pickup at the actor's feet, data kept) | `notEnough` `noWorld` `noPosition` |
|
|
71
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` |
|
|
72
72
|
| `thing.remove` | `{ id }` (core; undoable: an `engine.add` object is detached and kept, a record re-added) | `noThing` `engineOwned` |
|
|
73
|
+
| `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 |
|
|
74
|
+
| `npc.talk` | `{ npc, script?, channel? }` (`channel` `main` locks input, `bubble` shows lines over the NPC) | `noDialogue` `unknown` |
|
|
75
|
+
| `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 |
|
|
76
|
+
| `time.skip` | `{ seconds }` (core; timers, calendar events and far simulation catch up in order) | `notForward` |
|
|
73
77
|
| `photo.take` | none (`r.value` is the shot; can = `photo.canTake()`, the key emits `photo:denied { reason }`) | `denied` or yours |
|
|
74
78
|
|
|
75
79
|
## 4. Read the log
|
|
@@ -116,11 +120,12 @@ Put `<workspace>/tests/scenarios/<name>.json` in the engine package or a game; `
|
|
|
116
120
|
{ "snapshot": "after-barter", "only": ["inventory"] }
|
|
117
121
|
] }
|
|
118
122
|
```
|
|
119
|
-
- `state` is `engine.applyState` params; `"pos": "@id"` stands 1 m beside a world record. The
|
|
123
|
+
- `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
124
|
(seconds) and `press`.
|
|
121
125
|
- `op` steps run with `source: 'test'` (`actor` optional); `expect` is `"ok"` (default) or the failure code. A failure prints the `engine.explain` sentence.
|
|
122
126
|
- `expect` maps `describe()` paths to values (`nearby[0].name` works; numbers within 0.01; `null` = absent). `snapshot` compares with
|
|
123
127
|
`tests/snapshots/<name>.describe.json` (`only` / `ignore` / `tolerance`; write it with `threedog test <name> --update-snapshots`).
|
|
128
|
+
- A file has 120 s under `threedog test`; a long one sets `"timeout"` at the top, in milliseconds, as a spec does.
|
|
124
129
|
- 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
130
|
- Use `press` only for the one test per key that proves "key -> op". Examples in the engine repository: `packages/engine/tests/scenarios/`.
|
|
126
131
|
|
|
@@ -143,12 +148,7 @@ op's `run` emitted it, seq is the history seq); `chain` walks up to the root as
|
|
|
143
148
|
Gameplay randomness uses `engine.random` (`next / range / int / pick / chance`): it is saved with the game and `createEngine({ seed })` fixes it, so a
|
|
144
149
|
scenario replays the same. `Math.random` breaks both.
|
|
145
150
|
|
|
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
|
|
151
|
+
## 11. Structured failures, nextFixed, and who halted the loop
|
|
152
152
|
`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
153
|
```js
|
|
154
154
|
engine.ops.define('shop.buy', {
|
|
@@ -159,7 +159,7 @@ const r = engine.ops.run('shop.buy', {}); // r.ok === false, r.code === 'noMon
|
|
|
159
159
|
```
|
|
160
160
|
`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
161
|
|
|
162
|
-
Tests that
|
|
162
|
+
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
163
|
|
|
164
164
|
## 12. Failing in run, atomic ops, revision
|
|
165
165
|
`run` can fail like `can`: return or throw `{ ok: false, code, facts, nextActions }` (a value that merely has a `code` field is not a failure; `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. The engine never invents `nextActions`; only the op definition declares them. Every result carries `revision` (`engine.ops.revision`), a counter bumped once per committed op: "did anything change since I looked" is one compare.
|
|
@@ -174,7 +174,7 @@ engine.ops.define('craft.bread', {
|
|
|
174
174
|
after: (e) => e.audio.sfx('ding'), // sound / animation: runs only after the op committed
|
|
175
175
|
});
|
|
176
176
|
```
|
|
177
|
-
What atomic covers
|
|
177
|
+
What atomic covers: it copies the save parts that declared `saves.register(key, { atomic: true })` (the built-ins above; 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 (fine for a craft op, 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 wait for the outermost commit, and a rolled-back outer also takes back their revision). `ops.list()` and `engine.explain({ op })` report `atomic`.
|
|
178
178
|
|
|
179
179
|
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
180
|
|
|
@@ -141,7 +141,7 @@ Every entry of the UI focus stack (dialogue, `engine.ui.open` parts, `makeWindow
|
|
|
141
141
|
`makeWindow` is the one window: it opens on top of the UI focus stack, locks game input while open, closes with its close button or Esc
|
|
142
142
|
(pad B), and its buttons take the choice cursor, so it works with the keyboard, a gamepad and the mouse (opening it lets go of a locked mouse; the next click on
|
|
143
143
|
the view locks again). A window that ends something, win or lose, takes `closable: false`: no close button and Esc does nothing, so the player cannot slip back into the
|
|
144
|
-
game past it and only your buttons end it. Its picture is your `ui.css` /
|
|
144
|
+
game past it and only your buttons end it. Nothing else closes a window: a game that restarts by another road (a new game from the title, a load) closes it on `session:start`. Its picture is your `ui.css` /
|
|
145
145
|
`ui.templates[id]`. A level clear, a match score, a day's earnings or a run summary are all this:
|
|
146
146
|
```js
|
|
147
147
|
import { makeWindow } from 'threedog';
|
|
@@ -157,6 +157,7 @@ results.el.addEventListener('click', ev => { // one li
|
|
|
157
157
|
let held = null; // stop gameplay behind it (the picture keeps drawing)
|
|
158
158
|
engine.events.on('ui:open', id => { if (id === 'results') held = engine.freeze('results'); });
|
|
159
159
|
engine.events.on('ui:close', id => { if (id === 'results') { held?.remove(); held = null; } });
|
|
160
|
+
engine.events.on('session:start', () => results.toggle(false)); // a new run or a load, however it was started
|
|
160
161
|
results.toggle(true); // when the run ends; results.refresh() after the data changes
|
|
161
162
|
```
|
|
162
163
|
|
|
@@ -168,12 +169,27 @@ engine.ui.open('title'); // show it again (the setti
|
|
|
168
169
|
```
|
|
169
170
|
While the title is open gameplay is frozen, input is locked, and Esc goes to it (the settings menu does not open).
|
|
170
171
|
|
|
172
|
+
**A custom item closes the title itself.** The built-in `continue` / `start` call `e.ui.close('title')` after they load; an item you write does not, so `flow` can reach `playing` with the title still on top and no warning. End every item that leaves the title with `e.ui.close('title')`:
|
|
173
|
+
```js fragment
|
|
174
|
+
{ label: 'Tutorial', run: async e => { await e.session.newGame(); e.ui.close('title'); } }
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
### Photo mode: the picture without the interface, and hiding the interface
|
|
178
|
+
`engine.photo.take()` (op `photo.take`) draws one frame of the game canvas at a higher pixel ratio and reads it back, so the picture never contains DOM: HUD, toasts and windows are not in it (a HUD drawn into the canvas by your own render code is). To hide the interface on screen for a photo mode, hide the engine's UI root, one element that holds every part:
|
|
179
|
+
```js
|
|
180
|
+
const photoMode = on => { engine.uiRoot.style.display = on ? 'none' : ''; }; // engine ui: hud, toasts, windows, title
|
|
181
|
+
engine.photo.take(); // shot.url is the picture, the album keeps it; the DOM was never in it
|
|
182
|
+
photoMode(true); // the player's screen without interface, e.g. while a photo mode is framing
|
|
183
|
+
```
|
|
184
|
+
HUD text follows the engine locale (`createEngine({ locale })`, default `'auto'` = the browser language): a game written in English sets `locale: 'en'`, or distance labels read `50 米` on a Chinese browser.
|
|
185
|
+
|
|
171
186
|
## 6. Settings menu: only the tabs the game needs
|
|
172
187
|
```js
|
|
173
188
|
engine.use(settings({ sections: ['game', 'graphics', 'audio', 'controls', 'camera'] })); // default: graphics, audio, controls, language, saves
|
|
174
189
|
// optional built-ins by name: 'game' (resume / load / back to title), 'camera' (sensitivity, invert Y, field of view; re-applied on 'camera:change')
|
|
175
190
|
engine.settings.addSection('camera');
|
|
176
|
-
|
|
191
|
+
// leave graphics rows out: the entry { id: 'graphics', omit } in the list; an omitted row stays the game's value, and no preset or stored value moves it
|
|
192
|
+
settings({ sections: [{ id: 'graphics', omit: ['pixelRatio', 'antialias', 'adaptive'] }, 'audio', 'controls', 'language', 'saves'] });
|
|
177
193
|
|
|
178
194
|
// a tab of your own: render gets tools with the control helpers (row / toggle / range / segmented) already bound
|
|
179
195
|
engine.settings.define('subtitles', true, on => { document.body.dataset.subtitles = String(on); });
|
|
@@ -185,12 +201,13 @@ engine.settings.addSection('gameplay', {
|
|
|
185
201
|
```
|
|
186
202
|
A row that switches off an effect of your own (a post effect, a picture value): name the shared value it limits, and it works like the
|
|
187
203
|
built-in shadows row. Off holds the value off on the settings layer, so a later scene, weather or cutscene cannot turn it back on; on
|
|
188
|
-
allows whatever the scene chose. A number row from 0 to 1 is a factor on a number value. Define the row after the effect exists.
|
|
204
|
+
allows whatever the scene chose. A number row from 0 to 1 is a factor on a number value. Define the row after the effect exists. `bloom` and `ao` already have rows of their own (limiting `post.bloom.enabled` / `post.ao.enabled`), so `settings.define('bloom', ...)` throws: switch them with `engine.settings.set('bloom', false)`, or in a preset.
|
|
189
205
|
```js
|
|
190
206
|
engine.post.add(volFog); // post.volFog.enabled now exists
|
|
191
207
|
engine.settings.define('volFog', true, { limits: 'post.volFog.enabled' }); // add apply: v => ... too if the game reacts in code
|
|
192
208
|
engine.settings.define('flashCap', 1, { limits: 'sky.flash' }); // 0.5 = half of any lightning flash
|
|
193
209
|
settings({ presets: { low: { volFog: false } } }); // a preset can switch the row like any other key
|
|
210
|
+
settings({ presets: { low: { pixelRatio: 0.5 } } }); // pixelRatio in a preset: a share (0 to 1) of the ratio the engine picked for this device
|
|
194
211
|
```
|
|
195
212
|
`engine.describe().shared['post.volFog.enabled']` shows the settings entry and what the scene wanted underneath.
|
|
196
213
|
|
|
@@ -199,13 +216,6 @@ A completely different menu: don't install `settings()`; open your own with `uiF
|
|
|
199
216
|
Check what is in use: `engine.ui.describe()` → `{ loading: 'default', toast: 'off', 'hud.bar': 'custom', ... }`.
|
|
200
217
|
|
|
201
218
|
## 7. Keys, and UI that follows the world
|
|
202
|
-
- Bind keys
|
|
203
|
-
jump) in the fixed step, UI keys in the frame hook. Never `addEventListener('keydown')`, and never read `pointer.clicked` for gameplay; bind a
|
|
204
|
-
`Mouse0` action instead.
|
|
205
|
-
- A menu, vehicle or build mode that takes over keys pushes an input context: `const h = engine.input.push('menu')` (opaque) or
|
|
206
|
-
`push('vehicle', { pass: true })`, then `h.remove()`. Tests and the dev bridge press keys with `engine.input.simulate(action, down)`:
|
|
207
|
-
action names, not keys (`simulate('moveForward')` walks like a held W until `simulate('moveForward', false)`); an unknown name throws.
|
|
219
|
+
- Bind keys and read them by action name (recipe 58): gameplay keys (attack, jump) in the fixed step, UI keys in the frame hook. Never `addEventListener('keydown')`, and never read `pointer.clicked` for gameplay; bind a `Mouse0` action instead.
|
|
208
220
|
- A label over a world position: `worldToScreen(engine, pos)` gives screen coordinates for an HTML element.
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
Bind a counter to an item count (coins): `engine.onFrame(() => engine.hud.counter('coins', { icon: '🪙', label: 'Coins', value: engine.inventory.count('coin') }));`. Same id = update, unchanged value touches no DOM, and a loaded save follows automatically (recipe 22 section 4).
|
|
221
|
+
- A counter bound to an item count: recipe 22 section 4.
|
package/docs/recipes/27-net.md
CHANGED
|
@@ -4,8 +4,6 @@
|
|
|
4
4
|
puzzle, a turn-based board, trading). One player's browser is the **host** and
|
|
5
5
|
owns the game state; friends are **clients** that mirror it and ask for changes through ops. Not installed = no cost.
|
|
6
6
|
**What it is not (yet)**: action netcode. There is no client prediction or rollback, so a client's attack / roll / shot waits one round trip.
|
|
7
|
-
Souls-like and shooter games need that later step; the rules below (ops with self-contained args, state only changed in fixed steps and ops,
|
|
8
|
-
snapshot-able world data) are what it will build on.
|
|
9
7
|
|
|
10
8
|
## 1. Install
|
|
11
9
|
The same game code runs on every machine; only `role` and the transport differ.
|
|
@@ -1,10 +1,12 @@
|
|
|
1
|
-
# Terrain: your own generator, digging, raising and painting the ground
|
|
1
|
+
# Terrain: your own generator, digging, raising and painting the ground, islands
|
|
2
|
+
|
|
3
|
+
**In this recipe**: 0. Noise preset · 1. Your own generator · 2. Changing the ground · 3. Farming soil and ground types · 4. Height and snapping · 5. Where the ground ends: `shape` · 6. Replace the picture, keep play · 7. A chunk that fails · 8. Triangle cut and bounds margin · 9. Height from a grid or image
|
|
2
4
|
|
|
3
5
|
Requires module `terrain()` (in the `openWorld()` preset). The API list is in `../api/terrain.md`.
|
|
4
6
|
|
|
5
7
|
The engine always does the chunks, streaming, workers, collision and vegetation. It has **no built-in landform**: `terrain()` without a generator is
|
|
6
8
|
flat gray ground at y = 0, with a dev warning. The height and ground type come from your own two functions or a preset, and the player can change the
|
|
7
|
-
ground during play.
|
|
9
|
+
ground during play. How the ground looks: recipes 36 and 53.
|
|
8
10
|
|
|
9
11
|
Flat island (no noise): `terrain({ height: () => 2, shape: { mask: (x, z) => 25 - Math.hypot(x, z) } })`; inside `openWorld` the same object goes under `terrain:`.
|
|
10
12
|
|
|
@@ -18,21 +20,22 @@ const dry = (x, z) => riverAt(x, z, preview.noise) === 0;
|
|
|
18
20
|
```
|
|
19
21
|
Its ground types are `beach snow rock riverbank wetland savanna forest highland meadow`; the game colors them (`terrain({ colors, biomeColors })`),
|
|
20
22
|
and `terrainStrings` names them for `describe()`. Other options:
|
|
21
|
-
`heightScale mountains rivers riverWidth biomes noise island canyon` (types in the package's `index.d.ts`).
|
|
23
|
+
`heightScale mountains rivers riverWidth river biomes noise island canyon` (types in the package's `index.d.ts`).
|
|
22
24
|
|
|
23
25
|
## 1. Your own generator
|
|
24
26
|
```js
|
|
25
27
|
import { terrain } from 'threedog';
|
|
26
28
|
terrain({
|
|
27
|
-
// meters at (x, z); n = { fbm(x, z, octaves), noise(x, z), hash(x, z, salt), seed, waterLevel, params }
|
|
29
|
+
// meters at (x, z); n = { fbm(x, z, octaves), noise(x, z), hash(x, z, salt), seed, waterLevel, params }; fbm, noise and hash all give 0 to 1, not -1 to 1
|
|
30
|
+
// (fbm gathers around 0.5 and seldom reaches either end: subtract 0.5 to center it, and sample the map before choosing a cut for a ground type)
|
|
28
31
|
height: (x, z, n) => 4 + 30 * n.fbm(x * 0.004, z * 0.004) - 8 * Math.abs(Math.sin(x * 0.01)),
|
|
29
32
|
// a ground type name (null = 'default'); its colors come from biomeColors[type]
|
|
30
33
|
groundType: (x, z, h, slope) => slope > 0.8 ? 'rock' : h < 1 ? 'beach' : 'grass',
|
|
31
34
|
waterLevel: 0, // a sea at y = 0; leave it out for no water (the default is -Infinity; terrainPreset() sets 0)
|
|
32
35
|
});
|
|
33
36
|
```
|
|
34
|
-
The terrain moves the camera's far plane out to its view distance
|
|
35
|
-
the
|
|
37
|
+
The terrain moves the camera's far plane out to its view distance and leaves the fog to the game; `terrain({ viewFog: true })` (on in `openWorld()`) writes that
|
|
38
|
+
distance to the signal `engine.uniforms.uViewDistance`, which your fog code reads so the far chunk edge fades out (recipe 34). It never writes `scene.fog`.
|
|
36
39
|
Both functions run in workers, so they are **pure**: they see only their parameters and globals like `Math`. Reading a variable from outside
|
|
37
40
|
(`(x, z) => x * scale`) throws at `terrain()` and names the variable; put the number inside the function, or pass settings as plain data in
|
|
38
41
|
`terrain({ params })` and read them as `n.params`. `flatten` plots still apply on top. A new type name needs colors:
|
|
@@ -47,8 +50,6 @@ engine.ops.define('ground.level', { args: { at: 'position' }, run(e, a) {
|
|
|
47
50
|
} });
|
|
48
51
|
engine.ops.run('ground.dig', { at });
|
|
49
52
|
```
|
|
50
|
-
- One of `raise` / `lower` (meters) / `flatten` (target height), and / or `paint` (a ground type, `null` gives back the generated type). `shape` is
|
|
51
|
-
`'circle'` (default) or `'square'`, `radius` in meters.
|
|
52
53
|
- Edits snap to the terrain grid: heights to grid points, paint to whole cells of `engine.terrain.cellSize` meters (`chunkSize / resolution`, default
|
|
53
54
|
4). A shape smaller than a cell takes the nearest one. For finer paint use a higher `terrain({ resolution })` (64 gives 1 m cells); per-cell
|
|
54
55
|
gameplay state belongs in a grid layer (section 3).
|
|
@@ -72,12 +73,81 @@ engine.ops.define('path.sand', { args: { at: 'position' }, // a sandy path; a
|
|
|
72
73
|
Read the ground with `engine.surface(x, z)` (also `slope`, `groundType`, `waterAt`) and put an object on it with `engine.snapToGround(obj)`. Don't
|
|
73
74
|
raycast the terrain for this: the height function is exact and works before the chunk has a mesh.
|
|
74
75
|
|
|
75
|
-
|
|
76
|
+
## 4b. A road laid on the ground
|
|
77
|
+
|
|
78
|
+
The road and the height function must read the same data, or the road floats or sinks wherever they disagree. Write the road's shape once as plain numbers and hand them over with `terrain({ params })`. The height function runs in workers and sees only `n.params`, so it works out the centre line itself: a formula or a small table of numbers, never a curve object. Near the line it returns the road's level, and it blends to the hills further out.
|
|
79
|
+
|
|
80
|
+
```js
|
|
81
|
+
const ROAD = { R: 130, wobble: 24, level: 14, flat: 10, blend: 40 }; // the one copy of the road's shape
|
|
82
|
+
|
|
83
|
+
function height(x, z, n) {
|
|
84
|
+
const p = n.params, t = Math.atan2(z, x);
|
|
85
|
+
const centre = p.R + p.wobble * Math.sin(2 * t);
|
|
86
|
+
const k0 = Math.min(1, Math.max(0, (Math.abs(Math.hypot(x, z) - centre) - p.flat) / p.blend)), k = k0 * k0 * (3 - 2 * k0);
|
|
87
|
+
const hills = 10 + 60 * (n.fbm(x * 0.009, z * 0.009, 4) - 0.5);
|
|
88
|
+
return p.level + (hills - p.level) * k;
|
|
89
|
+
}
|
|
90
|
+
// terrain({ params: ROAD, height })
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
The road itself comes from the same numbers, with its heights read from `engine.surface`, so nothing is computed twice:
|
|
94
|
+
|
|
95
|
+
```js
|
|
96
|
+
const points = [];
|
|
97
|
+
for (let i = 0; i < 720; i++) {
|
|
98
|
+
const t = i / 720 * Math.PI * 2, r = ROAD.R + ROAD.wobble * Math.sin(2 * t), x = r * Math.cos(t), z = r * Math.sin(t);
|
|
99
|
+
points.push({ x, y: engine.surface(x, z), z });
|
|
100
|
+
}
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
Build the road's mesh from `points`, a little above the ground, and keep `flat` wider than half the road. The same data answers gameplay questions too, such as where the road is or how far a car has left it.
|
|
76
104
|
|
|
77
105
|
## 5. Where the ground ends: `shape`
|
|
106
|
+
`terrain({ shape })` decides where there is ground at all: an island, a floating rock, a world that ends. Without it the ground goes on forever. With it, ground exists only
|
|
107
|
+
where `mask > 0`; the rim is cut through the cells in straight lines, walls hang down from it, and an optional underside closes it. The keys and their defaults are `TerrainShape` in `types/world.d.ts`.
|
|
108
|
+
|
|
109
|
+
```js
|
|
110
|
+
import { createEngine, openWorld } from 'threedog';
|
|
111
|
+
|
|
112
|
+
const engine = createEngine({ canvas: document.querySelector('canvas') });
|
|
113
|
+
engine.use(openWorld({ camera: 'follow', water: false, terrain: { // water: false -- a floating island has no sea under it
|
|
114
|
+
height: (x, z, n) => 4 + 6 * n.fbm(x * 0.02, z * 0.02),
|
|
115
|
+
shape: {
|
|
116
|
+
mask: (x, z) => 60 - Math.hypot(x, z), // > 0 ground: a 60 m disc (meters read best)
|
|
117
|
+
edge: { noise: 8, size: 20, jitter: 0.6, round: 1.5 }, // ragged outline, jagged rim, top bends down 1.5 m at the edge
|
|
118
|
+
side: { depth: 3, ground: 'cliff' }, // 3 m of cliff band, colored by biomeColors.cliff
|
|
119
|
+
bottom: { depth: (x, z, n, m) => 2 + m * 0.5 + 4 * n.fbm(x * 0.1, z * 0.1), ground: 'rock' }, // hangs lower inland (m grows inward)
|
|
120
|
+
},
|
|
121
|
+
} }));
|
|
122
|
+
await engine.start();
|
|
78
123
|
|
|
79
|
-
|
|
80
|
-
|
|
124
|
+
const home = { x: 0, z: 0 };
|
|
125
|
+
engine.events.on('terrain:void', ({ who }) => { // fell off: the game decides (the engine never respawns)
|
|
126
|
+
if (who === engine.player) engine.player.placeAt(home);
|
|
127
|
+
});
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
Colors come from `terrain({ biomeColors })` as usual: add `cliff` and `rock` (a name without a color is neutral gray). The mask is pure like `height`, or a gray image.
|
|
131
|
+
Without `bottom` the island is open underneath (the cheapest choice when the camera never looks up at it). The side wall follows every bend of an `edge.round` top, so no slit shows between them.
|
|
132
|
+
|
|
133
|
+
What the rest of the engine does off the outline:
|
|
134
|
+
|
|
135
|
+
- `engine.surface(x, z)` is `-Infinity`, `engine.ground.has(x, z)` is `false`, `engine.slope` is 0, `engine.groundType` is `'void'`.
|
|
136
|
+
Check `has` before placing things: `engine.snapToGround` over the void warns once and leaves the object where it is, instead of writing an infinite y.
|
|
137
|
+
The same holds for every place-it-here entry (`engine.content.spawn`, content props, pickups, npcs, `character.placeAt`): a warning once per caller with this advice, and they keep the caller's y (or 0), never `-Infinity` (a save would turn it into NaN). Camera starts, HUD anchors, grid tiles and shot paths fall back to y 0 / the last height without a word.
|
|
138
|
+
- Characters walk off the rim and fall; pathfinding and spawn search treat the void as not walkable.
|
|
139
|
+
- Physics: the top and the walls collide (a rolling barrel stops at a wall, a ball falls off the edge); the underside does not.
|
|
140
|
+
- Vegetation never grows off the outline. `engine.terrain.edit` off it does nothing (returns `{ heights: 0, cells: 0 }`); near the rim it
|
|
141
|
+
still digs, and painting works. The outline itself cannot be edited.
|
|
142
|
+
- The player and every moving rigid body that drops below `engine.terrain.voidY` get one `terrain:void { who, position }` per fall.
|
|
143
|
+
- Global water still draws at its level: a floating island usually turns water off (`water: false` above).
|
|
144
|
+
|
|
145
|
+
Limits:
|
|
146
|
+
|
|
147
|
+
- The cut follows cell edges, so detail finer than a cell (`chunkSize / resolution`, 4 m by default) is lost. Keep `edge.size` above a cell,
|
|
148
|
+
or raise `resolution`.
|
|
149
|
+
- `shading: 'texture'`: the color map covers the top only (void pixels keep the color of the ground under them, so no seam shows at the rim, with alpha 0); sides and bottom use vertex colors or `side.material`.
|
|
150
|
+
- The mask is fixed at start; a game that wants the outline to change while playing builds that itself.
|
|
81
151
|
|
|
82
152
|
## 6. Drawing the ground and plants your own way: replace the picture, keep play
|
|
83
153
|
|
|
@@ -89,21 +159,15 @@ replaces a picture keeps all of play. A picture listens to the data part's `view
|
|
|
89
159
|
engine.use({ name: 'myGround', type: 'picture', provides: ['terrain-draw'], install(e, ctx) {
|
|
90
160
|
const meshes = new Map();
|
|
91
161
|
ctx.track(e.terrain.view({
|
|
92
|
-
add(c) { const m = buildMesh(c.data.pos, c.data.nor, c.data.col); m.position.set(c.cx * e.terrain.
|
|
93
|
-
change(c) { refill(meshes.get(c), c.data); }, // terrain.edit rewrote the arrays (
|
|
162
|
+
add(c) { const m = buildMesh(c.data.pos, c.data.nor, c.data.col); m.position.set(c.cx * e.terrain.chunkSize, 0, c.cz * e.terrain.chunkSize); e.scene.add(m); meshes.set(c, m); },
|
|
163
|
+
change(c) { refill(meshes.get(c), c.data); }, // terrain.edit rewrote the arrays (the count can differ on an 'adaptive' rim)
|
|
94
164
|
remove(c) { e.scene.remove(meshes.get(c)); meshes.delete(c); },
|
|
95
165
|
show(c, visible) { meshes.get(c).visible = visible; },
|
|
96
166
|
}));
|
|
97
167
|
} }, { replaces: 'terrain-draw' });
|
|
98
|
-
engine.use({ name: 'myPlants', type: 'picture', provides: ['vegetation-draw'], install(e, ctx) {
|
|
99
|
-
ctx.track(e.vegetation.view({
|
|
100
|
-
species(sp) { /* sp.source = what vegetation.define was given (geometry, model, material, wind) */ },
|
|
101
|
-
change(c, name) { /* c.plants[name]: { n, m (16 floats per plant, chunk-local), c (colors), ids }; c.hidden[name]: felled slots; gone = drop that mesh */ },
|
|
102
|
-
ring(c, ring) { /* LOD: ring 1 = the chunk a source stands in plus one ring around */ },
|
|
103
|
-
show(c, visible) {}, drop(c) { /* chunk released */ },
|
|
104
|
-
}));
|
|
105
|
-
} }, { replaces: 'vegetation-draw' });
|
|
106
168
|
```
|
|
169
|
+
Plants work the same way: a module with `provides: ['vegetation-draw']`, `{ replaces: 'vegetation-draw' }` and `e.vegetation.view({ species, change, ring, show, drop })` (hooks in `../api/vegetation.md`). In `change(c, name)`, `c.plants[name]` is `{ n, m (16 floats per plant, chunk-local), c (colors), ids }` and `c.hidden[name]` the felled slots; when it is gone, drop that mesh.
|
|
170
|
+
`c.data` holds `pos`, `nor`, `col`, `uv`, and `tex: { data, size }` in texture mode; `engine.terrain.generator.buildChunk(cx, cz)` returns the same raw arrays.
|
|
107
171
|
Only the material, not the meshes? `engine.terrain.material = material` swaps it on every loaded chunk in place (recipe 36).
|
|
108
172
|
|
|
109
173
|
## 7. A chunk that fails
|
|
@@ -111,3 +175,35 @@ Only the material, not the meshes? `engine.terrain.material = material` swaps it
|
|
|
111
175
|
A chunk job that throws (usually the game's `height` / `groundType` / placement rule at that spot) is tried 3 times, then the chunk stays empty
|
|
112
176
|
(no ground, no collision there): `terrain:chunkFailed` `{ cx, cz, error }` fires, the error `[terrain-chunk-failed]` names the chunk and the cause,
|
|
113
177
|
and `describe().perf.chunks.failed` counts it. Fix the rule, then `engine.terrain.retry()` sends every failed chunk again.
|
|
178
|
+
|
|
179
|
+
## 8. Triangle cut and bounds margin
|
|
180
|
+
```js
|
|
181
|
+
terrain({ diagonal: 'adaptive' }) // 'fixed' (default) | 'adaptive' | 'alternate'
|
|
182
|
+
```
|
|
183
|
+
`fixed` cuts every cell the same way. `adaptive` cuts along the diagonal with the smaller height difference, which removes
|
|
184
|
+
the zigzag ridges a fixed cut leaves on a slope; `alternate` flips every other cell (no directional bias on flat low-poly facets). `engine.surface`,
|
|
185
|
+
collision and vegetation heights follow the chosen cut, so nothing floats. It changes the walkable shape, so `recolor` does not take it.
|
|
186
|
+
|
|
187
|
+
`boundsPad: { up: 3, radius: 8 }` (meters, the defaults) is the margin of the chunk's bounding sphere: the center is raised by `up`, the radius grows
|
|
188
|
+
by `radius`. Raise it if a shader moves vertices far (wind on tall ground cover, a vertex-displacement patch) and chunks pop out at the screen edge.
|
|
189
|
+
|
|
190
|
+
## 9. Height from a grid or image
|
|
191
|
+
`sampleGrid(data, opts)` (`../api/tools.md`) turns numbers laid out on a regular grid into a function `(x, z) => value`;
|
|
192
|
+
`await engine.assets.gridFromImage(nameOrUrl, opts)` (`../api/assets.md`) reads such a grid from an image. Samples sit on the grid nodes, so
|
|
193
|
+
`width` samples span `width - 1` cells. The grid is just a field: height, moisture, a
|
|
194
|
+
ground-type weight, spawn density, a walkable mask, danger, travel cost.
|
|
195
|
+
|
|
196
|
+
`interp` is the picture between nodes, and none of them is the right one: `'nearest'` for terraces, blocky ground, tile masks and ids; `'linear'` (default) for most fields;
|
|
197
|
+
`'cubic'` for slopes without cell creases, which can overshoot beside a sharp step (`clamp: true` keeps it inside the four corner values).
|
|
198
|
+
|
|
199
|
+
```js
|
|
200
|
+
const g = await engine.assets.gridFromImage('/maps/height16.png', { range: [-5, 60] }); // meters, 16-bit file
|
|
201
|
+
const heightAt = sampleGrid(g.data, { ...g, size: [512, 512], origin: [-256, -256], interp: 'cubic', clamp: true });
|
|
202
|
+
heightAt(10, 20); // gameplay side: where to put a camp, a mine, a lighthouse
|
|
203
|
+
const wet = sampleGrid(moisture, { width: 32, height: 32, cellSize: 8 }); // a hand-made field: wetter ground grows reeds, rice, moss
|
|
204
|
+
const walk = sampleGrid(mask, { width: 64, height: 64, cellSize: 1, interp: 'nearest', outside: 0 }); // 0 / 1 per tile; off the map: not walkable
|
|
205
|
+
```
|
|
206
|
+
A terrain `height` function is recompiled in a worker and cannot capture `heightAt`, so the terrain reads the same image through its own
|
|
207
|
+
`heightmap` (bilinear, centered on `center`): `terrain({ heightmap: { ...g, size: [512, 512], min: -5, max: 60 } })` with `g` from `gridFromImage`
|
|
208
|
+
using the default `range` (it expects 0-1 values; `min`/`max` scale them). Use `sampleGrid` for everything outside the terrain module; when you need
|
|
209
|
+
a picture the terrain's bilinear read does not give (terraces: `nearest`), bake it into the data first or write the step in a `height` function.
|