threedog 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +5 -0
- package/LICENSE +21 -0
- package/README.md +39 -2
- package/core/Animator.js +268 -0
- package/core/Assets.js +256 -0
- package/core/Audio.js +267 -0
- package/core/Baked.js +72 -0
- package/core/Batching.js +247 -0
- package/core/Budget.js +221 -0
- package/core/Clock.js +94 -0
- package/core/Commits.js +77 -0
- package/core/DebugOverrides.js +143 -0
- package/core/Describe.js +145 -0
- package/core/Engine.js +184 -0
- package/core/Events.js +153 -0
- package/core/I18n.js +94 -0
- package/core/Input.js +245 -0
- package/core/Inspect.js +77 -0
- package/core/InspectScene.js +191 -0
- package/core/Jobs.js +146 -0
- package/core/Loading.js +149 -0
- package/core/MaterialInfo.js +32 -0
- package/core/Ops.js +256 -0
- package/core/Random.js +52 -0
- package/core/Rays.js +160 -0
- package/core/SaveStore.js +85 -0
- package/core/Saves.js +254 -0
- package/core/Stream.js +279 -0
- package/core/Threads.js +158 -0
- package/core/UrlState.js +94 -0
- package/core/Vars.js +35 -0
- package/core/Views.js +49 -0
- package/core/actor.js +23 -0
- package/core/assetEntry.js +89 -0
- package/core/assetLoad.js +190 -0
- package/core/assetManifest.js +35 -0
- package/core/assetReport.js +83 -0
- package/core/audioRules.js +121 -0
- package/core/audioVoice.js +225 -0
- package/core/batchGroups.js +116 -0
- package/core/canvasBox.js +63 -0
- package/core/catalog.js +169 -0
- package/core/checks.js +67 -0
- package/core/claims.js +51 -0
- package/core/dayTime.js +15 -0
- package/core/debugView.js +76 -0
- package/core/describeRender.js +45 -0
- package/core/describeText.js +143 -0
- package/core/easing.js +34 -0
- package/core/errorCodes.js +205 -0
- package/core/errorHints.js +208 -0
- package/core/errors.js +40 -0
- package/core/events.generated.js +84 -0
- package/core/ground.js +102 -0
- package/core/holds.js +106 -0
- package/core/inputContext.js +69 -0
- package/core/inputDefaults.js +22 -0
- package/core/inputPad.js +35 -0
- package/core/inputPointer.js +48 -0
- package/core/inputTouch.js +48 -0
- package/core/lifecycle.js +69 -0
- package/core/lightWatch.js +56 -0
- package/core/look/coreParts.js +112 -0
- package/core/look/layers.js +136 -0
- package/core/look/part.js +173 -0
- package/core/look/report.js +79 -0
- package/core/look/write.js +86 -0
- package/core/loop.js +200 -0
- package/core/math.js +33 -0
- package/core/modules.js +196 -0
- package/core/movement.js +19 -0
- package/core/mulberry32.js +14 -0
- package/core/opsAtomic.js +31 -0
- package/core/opsCheck.js +97 -0
- package/core/opsFail.js +20 -0
- package/core/opsGuard.js +26 -0
- package/core/opsHistory.js +27 -0
- package/core/opsRun.js +77 -0
- package/core/page.js +78 -0
- package/core/params.js +132 -0
- package/core/pureWorker.js +5 -0
- package/core/renamed.js +21 -0
- package/core/saveApply.js +128 -0
- package/core/saveFiles.js +139 -0
- package/core/saveIds.js +53 -0
- package/core/saveVersions.js +97 -0
- package/core/scatter.js +92 -0
- package/core/sceneMethods.js +100 -0
- package/core/screenToGround.js +39 -0
- package/core/services.js +73 -0
- package/core/session.js +171 -0
- package/core/shadowTypes.js +15 -0
- package/core/skip.js +104 -0
- package/core/startup.js +135 -0
- package/core/streamCells.js +24 -0
- package/core/streamSources.js +73 -0
- package/core/styleParts.js +96 -0
- package/core/targeting.js +64 -0
- package/core/thingExplain.js +68 -0
- package/core/thingOps.js +168 -0
- package/core/things.js +212 -0
- package/core/threadPure.js +120 -0
- package/core/threadServe.js +25 -0
- package/core/tier.js +11 -0
- package/core/util.js +11 -0
- package/core/validate.js +204 -0
- package/docs/AI.md +123 -0
- package/docs/API.md +83 -0
- package/docs/CODEMAP.md +347 -0
- package/docs/COMMANDS.md +108 -0
- package/docs/CONVENTIONS.md +145 -0
- package/docs/PERF.md +217 -0
- package/docs/THREE.md +86 -0
- package/docs/api/ambience.md +15 -0
- package/docs/api/assets.md +62 -0
- package/docs/api/audio.md +53 -0
- package/docs/api/budget.md +40 -0
- package/docs/api/cameraRig.md +120 -0
- package/docs/api/characters.md +144 -0
- package/docs/api/clock.md +7 -0
- package/docs/api/collision.md +39 -0
- package/docs/api/content.md +64 -0
- package/docs/api/dialogue.md +39 -0
- package/docs/api/engine.md +199 -0
- package/docs/api/entities.md +61 -0
- package/docs/api/events.md +95 -0
- package/docs/api/flow.md +27 -0
- package/docs/api/grids.md +11 -0
- package/docs/api/ground.md +16 -0
- package/docs/api/hlod.md +34 -0
- package/docs/api/hud.md +31 -0
- package/docs/api/i18n.md +10 -0
- package/docs/api/input.md +24 -0
- package/docs/api/interactions.md +31 -0
- package/docs/api/inventory.md +66 -0
- package/docs/api/jobs.md +10 -0
- package/docs/api/level.md +41 -0
- package/docs/api/lightPool.md +56 -0
- package/docs/api/music.md +34 -0
- package/docs/api/nav.md +26 -0
- package/docs/api/net.md +14 -0
- package/docs/api/openWorld.md +24 -0
- package/docs/api/particles.md +41 -0
- package/docs/api/photo.md +15 -0
- package/docs/api/post.md +10 -0
- package/docs/api/quests.md +36 -0
- package/docs/api/rays.md +26 -0
- package/docs/api/rigid.md +84 -0
- package/docs/api/saves.md +32 -0
- package/docs/api/settings.md +36 -0
- package/docs/api/sky.md +58 -0
- package/docs/api/stream.md +31 -0
- package/docs/api/style.md +134 -0
- package/docs/api/terrain.md +34 -0
- package/docs/api/timeline.md +39 -0
- package/docs/api/tools.md +57 -0
- package/docs/api/triggers.md +56 -0
- package/docs/api/vars.md +9 -0
- package/docs/api/vegetation.md +52 -0
- package/docs/api/water.md +48 -0
- package/docs/api/weather.md +29 -0
- package/docs/api/world.md +30 -0
- package/docs/recipes/01-new-game.md +148 -0
- package/docs/recipes/02-npc.md +167 -0
- package/docs/recipes/03-items-pickups.md +158 -0
- package/docs/recipes/04-quests.md +83 -0
- package/docs/recipes/05-props-bake.md +159 -0
- package/docs/recipes/06-clock-events.md +117 -0
- package/docs/recipes/07-flow-scenes-pause.md +132 -0
- package/docs/recipes/08-weather-sky.md +74 -0
- package/docs/recipes/09-style-pack.md +234 -0
- package/docs/recipes/10-blender-level.md +67 -0
- package/docs/recipes/11-vehicles.md +55 -0
- package/docs/recipes/12-navmesh.md +79 -0
- package/docs/recipes/13-animation.md +149 -0
- package/docs/recipes/14-custom-module.md +91 -0
- package/docs/recipes/15-perf.md +78 -0
- package/docs/recipes/16-dev-bridge.md +180 -0
- package/docs/recipes/18-world.md +185 -0
- package/docs/recipes/19-shooting-picking.md +76 -0
- package/docs/recipes/20-content-actions-save.md +176 -0
- package/docs/recipes/21-camera.md +153 -0
- package/docs/recipes/22-shop-gold.md +107 -0
- package/docs/recipes/23-ops.md +175 -0
- package/docs/recipes/26-ui-parts.md +138 -0
- package/docs/recipes/27-net.md +96 -0
- package/docs/recipes/28-terrain.md +80 -0
- package/docs/recipes/29-grid.md +87 -0
- package/docs/recipes/30-templates.md +131 -0
- package/docs/recipes/31-audio.md +126 -0
- package/docs/recipes/32-action-game.md +33 -0
- package/docs/recipes/33-stream-sources.md +37 -0
- package/docs/recipes/34-environment-lighting.md +36 -0
- package/docs/recipes/35-style-from-reference.md +89 -0
- package/docs/recipes/36-sky-ground-plant-looks.md +116 -0
- package/docs/recipes/37-terrain-look-hooks.md +97 -0
- package/docs/recipes/38-environment-look-hooks.md +83 -0
- package/docs/recipes/40-scene.md +108 -0
- package/docs/recipes/41-thing-registry.md +93 -0
- package/docs/recipes/42-terrain-shape.md +64 -0
- package/docs/recipes/43-shader-patches-surface-looks.md +120 -0
- package/docs/recipes/44-water-weather-look-hooks.md +135 -0
- package/docs/recipes/45-cascaded-shadows.md +51 -0
- package/docs/recipes/46-blender-art-route.md +114 -0
- package/docs/recipes/47-island-snow-backdrop.md +44 -0
- package/docs/recipes/48-make-material.md +70 -0
- package/docs/recipes/49-game-module-contract.md +71 -0
- package/docs/recipes/50-own-renderer.md +12 -0
- package/docs/recipes/51-capability-catalog.md +63 -0
- package/docs/recipes/52-look.md +108 -0
- package/examples/action/DESIGN.md +3 -0
- package/examples/action/GAMEMAP.md +127 -0
- package/examples/action/content/actions.js +8 -0
- package/examples/action/content/audio.js +9 -0
- package/examples/action/content/index.js +10 -0
- package/examples/action/content/items.js +4 -0
- package/examples/action/content/places.js +4 -0
- package/examples/action/content/props.js +11 -0
- package/examples/action/content/templates.js +10 -0
- package/examples/action/content/views.js +6 -0
- package/examples/action/look.js +5 -0
- package/examples/action/main.js +137 -0
- package/examples/action/models.js +25 -0
- package/examples/sheepisland/GAMEMAP.md +107 -0
- package/examples/sheepisland/content/index.js +6 -0
- package/examples/sheepisland/content/props.js +19 -0
- package/examples/sheepisland/content/templates.js +5 -0
- package/examples/sheepisland/content/vegetation.js +8 -0
- package/examples/sheepisland/main.js +71 -0
- package/examples/sheepisland/params.js +25 -0
- package/examples/sheepisland/style/index.js +79 -0
- package/examples/sheepisland/style/models.js +59 -0
- package/examples/sheepisland/views.js +9 -0
- package/examples/styletest/GAMEMAP.md +135 -0
- package/examples/styletest/content/index.js +9 -0
- package/examples/styletest/content/items.js +8 -0
- package/examples/styletest/content/npcs.js +8 -0
- package/examples/styletest/content/places.js +5 -0
- package/examples/styletest/content/props.js +16 -0
- package/examples/styletest/content/templates.js +9 -0
- package/examples/styletest/content/vegetation.js +31 -0
- package/examples/styletest/look.js +11 -0
- package/examples/styletest/main.js +95 -0
- package/examples/styletest/models.js +87 -0
- package/examples/styletest/overrides.js +33 -0
- package/examples/styletest/panel.js +135 -0
- package/examples/styletest/params.js +32 -0
- package/examples/styletest/views.js +31 -0
- package/examples/world/DESIGN.md +5 -0
- package/examples/world/GAMEMAP.md +171 -0
- package/examples/world/content/actions.js +8 -0
- package/examples/world/content/audio.js +25 -0
- package/examples/world/content/bodies.js +12 -0
- package/examples/world/content/containers.js +4 -0
- package/examples/world/content/dialogues.js +33 -0
- package/examples/world/content/index.js +17 -0
- package/examples/world/content/items.js +10 -0
- package/examples/world/content/npcs.js +14 -0
- package/examples/world/content/pickups.js +11 -0
- package/examples/world/content/places.js +6 -0
- package/examples/world/content/props.js +12 -0
- package/examples/world/content/quests.js +15 -0
- package/examples/world/content/rules.js +23 -0
- package/examples/world/content/templates.js +5 -0
- package/examples/world/content/vegetation.js +32 -0
- package/examples/world/main.js +168 -0
- package/examples/world/models.js +28 -0
- package/index.d.ts +306 -0
- package/index.js +122 -0
- package/llms.txt +61 -0
- package/modules/ambience/Ambience.js +186 -0
- package/modules/camera/FirstPersonCamera.js +131 -0
- package/modules/camera/FixedCamera.js +162 -0
- package/modules/camera/FollowCamera.js +91 -0
- package/modules/camera/RtsCamera.js +132 -0
- package/modules/camera/common.js +182 -0
- package/modules/camera/index.js +11 -0
- package/modules/camera/projection.js +34 -0
- package/modules/characters/Character.js +235 -0
- package/modules/characters/NPC.js +242 -0
- package/modules/characters/assetModel.js +42 -0
- package/modules/characters/astar.js +66 -0
- package/modules/characters/behaviors.js +72 -0
- package/modules/characters/footsteps.js +13 -0
- package/modules/characters/index.js +215 -0
- package/modules/characters/moveHelpers.js +29 -0
- package/modules/characters/movers/common.js +62 -0
- package/modules/characters/movers/rapier.js +74 -0
- package/modules/characters/movers/simple.js +43 -0
- package/modules/characters/npcAvoid.js +129 -0
- package/modules/characters/npcSim.js +150 -0
- package/modules/characters/npcView.js +42 -0
- package/modules/characters/pathAsync.js +113 -0
- package/modules/characters/pathJob.js +62 -0
- package/modules/characters/pathWorker.js +7 -0
- package/modules/characters/playerStrings.js +12 -0
- package/modules/characters/proceduralRig.js +58 -0
- package/modules/characters/useModel.js +22 -0
- package/modules/characters/walkTo.js +58 -0
- package/modules/collision/Collision.js +274 -0
- package/modules/collision/grid.js +63 -0
- package/modules/content/explain.js +13 -0
- package/modules/content/ids.js +95 -0
- package/modules/content/index.js +154 -0
- package/modules/content/loader.js +190 -0
- package/modules/content/models.js +69 -0
- package/modules/content/packs.js +69 -0
- package/modules/content/props.js +89 -0
- package/modules/content/rules.js +134 -0
- package/modules/content/templates.js +189 -0
- package/modules/debug/DebugPanel.js +174 -0
- package/modules/entities/Entities.js +243 -0
- package/modules/entities/build.js +25 -0
- package/modules/entities/index.js +4 -0
- package/modules/flow/index.js +101 -0
- package/modules/gameplay/Container.js +227 -0
- package/modules/gameplay/Containers.js +89 -0
- package/modules/gameplay/Dialogue.js +219 -0
- package/modules/gameplay/Interactions.js +253 -0
- package/modules/gameplay/Inventory.js +224 -0
- package/modules/gameplay/Quests.js +205 -0
- package/modules/gameplay/boxOps.js +60 -0
- package/modules/gameplay/dialogueBox.js +48 -0
- package/modules/gameplay/interactionPrompt.js +28 -0
- package/modules/gameplay/inventoryOps.js +137 -0
- package/modules/gameplay/pickups.js +115 -0
- package/modules/gameplay/questLog.js +54 -0
- package/modules/gameplay/questSave.js +71 -0
- package/modules/grid/Grid.js +184 -0
- package/modules/grid/Layer.js +142 -0
- package/modules/grid/index.js +236 -0
- package/modules/grid/ops.js +73 -0
- package/modules/grid/preview.js +85 -0
- package/modules/grid/tiles.js +79 -0
- package/modules/hlod/index.js +167 -0
- package/modules/hud/index.js +167 -0
- package/modules/hud/parts.js +80 -0
- package/modules/level/geometry.js +46 -0
- package/modules/level/heightfield.js +160 -0
- package/modules/level/index.js +233 -0
- package/modules/level/nodes.js +84 -0
- package/modules/lights/index.js +227 -0
- package/modules/music/Music.js +294 -0
- package/modules/music/index.js +2 -0
- package/modules/music/rules.js +28 -0
- package/modules/nav/index.js +156 -0
- package/modules/nav/navPath.js +17 -0
- package/modules/net/Client.js +137 -0
- package/modules/net/Host.js +117 -0
- package/modules/net/Net.js +49 -0
- package/modules/net/index.js +77 -0
- package/modules/net/sync.js +114 -0
- package/modules/net/transports.js +118 -0
- package/modules/particles/Particles.js +179 -0
- package/modules/particles/effect.js +112 -0
- package/modules/particles/shaders.js +28 -0
- package/modules/photo/Photo.js +146 -0
- package/modules/rigid/RigidBodies.js +265 -0
- package/modules/rigid/Vehicles.js +97 -0
- package/modules/rigid/sync.js +158 -0
- package/modules/settings/Settings.js +297 -0
- package/modules/settings/apply.js +21 -0
- package/modules/settings/index.js +3 -0
- package/modules/settings/sections.js +156 -0
- package/modules/settings/strings.js +53 -0
- package/modules/settings/view.js +65 -0
- package/modules/sky/Sky.js +259 -0
- package/modules/sky/calendar.js +80 -0
- package/modules/sky/cascades.js +125 -0
- package/modules/sky/clouds.js +79 -0
- package/modules/sky/domeLayers.js +33 -0
- package/modules/sky/environment.js +141 -0
- package/modules/sky/fog.js +139 -0
- package/modules/sky/frame.js +77 -0
- package/modules/sky/layers.js +69 -0
- package/modules/sky/look.js +51 -0
- package/modules/sky/lookFog.js +80 -0
- package/modules/sky/lookShadow.js +50 -0
- package/modules/sky/lookSky.js +108 -0
- package/modules/sky/schedule.js +80 -0
- package/modules/sky/shader.js +96 -0
- package/modules/sky/shadow.js +74 -0
- package/modules/sky/skyModule.js +60 -0
- package/modules/terrain/ChunkManager.js +260 -0
- package/modules/terrain/chunkJob.js +19 -0
- package/modules/terrain/chunkLevels.js +40 -0
- package/modules/terrain/chunkQueries.js +42 -0
- package/modules/terrain/chunkWorker.js +5 -0
- package/modules/terrain/index.js +118 -0
- package/modules/terrain/lookGround.js +61 -0
- package/modules/terrain/mountTerrain.js +32 -0
- package/modules/terrain/terrainColorMap.js +41 -0
- package/modules/terrain/terrainDefaults.js +39 -0
- package/modules/terrain/terrainEdit.js +139 -0
- package/modules/terrain/terrainGen.js +155 -0
- package/modules/terrain/terrainIsland.js +131 -0
- package/modules/terrain/terrainMesh.js +92 -0
- package/modules/terrain/terrainShape.js +108 -0
- package/modules/terrain/terrainShapeMain.js +41 -0
- package/modules/terrain/terrainTexture.js +44 -0
- package/modules/timeline/Timeline.js +253 -0
- package/modules/timeline/Tween.js +114 -0
- package/modules/timeline/letterbox.js +24 -0
- package/modules/timeline/shots.js +90 -0
- package/modules/triggers/index.js +268 -0
- package/modules/vegetation/Vegetation.js +256 -0
- package/modules/vegetation/groundChunks.js +177 -0
- package/modules/vegetation/index.js +43 -0
- package/modules/vegetation/lookWind.js +37 -0
- package/modules/vegetation/modelGeometry.js +21 -0
- package/modules/water/Water.js +160 -0
- package/modules/water/look.js +80 -0
- package/modules/water/surface.js +88 -0
- package/modules/weather/Weather.js +242 -0
- package/modules/weather/look.js +75 -0
- package/modules/weather/particles.js +92 -0
- package/modules/weather/shaders.js +49 -0
- package/modules/weather/strings.js +15 -0
- package/modules/world/World.js +231 -0
- package/modules/world/cells.js +42 -0
- package/modules/world/explain.js +11 -0
- package/modules/world/index.js +71 -0
- package/modules/world/persist.js +107 -0
- package/modules/world/pos.js +20 -0
- package/modules/world/records.js +89 -0
- package/modules/world/sim.js +175 -0
- package/modules/world/simFar.js +82 -0
- package/modules/world/state.js +115 -0
- package/modules/world/thingSource.js +44 -0
- package/modules/world/views.js +182 -0
- package/package.json +66 -4
- package/presets.js +96 -0
- package/render/PostFX.js +240 -0
- package/render/detail.js +105 -0
- package/render/effects.js +144 -0
- package/render/engineUniforms.js +23 -0
- package/render/fuse.js +84 -0
- package/render/lighting.js +100 -0
- package/render/lights.js +18 -0
- package/render/lookSurface.js +161 -0
- package/render/materials.js +220 -0
- package/render/patches.js +252 -0
- package/render/postLook.js +86 -0
- package/render/surface.js +69 -0
- package/render/uniformDecl.js +29 -0
- package/types/common.d.ts +34 -0
- package/types/core.d.ts +1965 -0
- package/types/gameplay.d.ts +1822 -0
- package/types/generated/core/Audio.d.ts +200 -0
- package/types/generated/core/Batching.d.ts +47 -0
- package/types/generated/core/Budget.d.ts +90 -0
- package/types/generated/core/Commits.d.ts +31 -0
- package/types/generated/core/DebugOverrides.d.ts +52 -0
- package/types/generated/core/Events.d.ts +89 -0
- package/types/generated/core/I18n.d.ts +30 -0
- package/types/generated/core/Input.d.ts +118 -0
- package/types/generated/core/Jobs.d.ts +41 -0
- package/types/generated/core/Ops.d.ts +203 -0
- package/types/generated/core/Random.d.ts +49 -0
- package/types/generated/core/Rays.d.ts +49 -0
- package/types/generated/core/Saves.d.ts +162 -0
- package/types/generated/core/Stream.d.ts +93 -0
- package/types/generated/core/Threads.d.ts +82 -0
- package/types/generated/core/Views.d.ts +33 -0
- package/types/generated/core/audioVoice.d.ts +47 -0
- package/types/generated/core/page.d.ts +18 -0
- package/types/generated/core/session.d.ts +48 -0
- package/types/generated/modules/ambience/Ambience.d.ts +48 -0
- package/types/generated/modules/debug/DebugPanel.d.ts +24 -0
- package/types/generated/modules/flow/index.d.ts +10 -0
- package/types/generated/modules/grid/Grid.d.ts +151 -0
- package/types/generated/modules/grid/Layer.d.ts +65 -0
- package/types/generated/modules/grid/index.d.ts +86 -0
- package/types/generated/modules/hlod/index.d.ts +11 -0
- package/types/generated/modules/hud/index.d.ts +10 -0
- package/types/generated/modules/lights/index.d.ts +13 -0
- package/types/generated/modules/music/Music.d.ts +111 -0
- package/types/generated/modules/net/Net.d.ts +34 -0
- package/types/generated/modules/net/index.d.ts +53 -0
- package/types/generated/modules/net/transports.d.ts +58 -0
- package/types/generated/modules/particles/Particles.d.ts +69 -0
- package/types/generated/modules/sky/Sky.d.ts +145 -0
- package/types/generated/modules/sky/skyModule.d.ts +10 -0
- package/types/generated/modules/timeline/Timeline.d.ts +51 -0
- package/types/generated/modules/water/Water.d.ts +29 -0
- package/types/generated/modules/weather/Weather.d.ts +62 -0
- package/types/generated/modules/world/World.d.ts +242 -0
- package/types/generated/modules/world/index.d.ts +15 -0
- package/types/generated/render/PostFX.d.ts +125 -0
- package/types/generated/render/materials.d.ts +100 -0
- package/types/generated/render/patches.d.ts +41 -0
- package/types/generated/ui/Focus.d.ts +11 -0
- package/types/generated/ui/LoadingScreen.d.ts +2 -0
- package/types/generated/ui/UI.d.ts +57 -0
- package/types/nav.d.ts +52 -0
- package/types/physics.d.ts +592 -0
- package/types/style.d.ts +638 -0
- package/types/worker.d.ts +11 -0
- package/types/world.d.ts +772 -0
- package/ui/Focus.js +51 -0
- package/ui/LoadingScreen.js +42 -0
- package/ui/Parts.js +199 -0
- package/ui/UI.js +167 -0
- package/ui/defaults.js +85 -0
- package/ui/theme.js +124 -0
- package/ui/touchPart.js +49 -0
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
# Custom module
|
|
2
|
+
|
|
3
|
+
When to write a module: a "mechanic" that has its own state, per-frame logic and saving, and that other games might use too (fishing, farming,
|
|
4
|
+
stamina). Something that belongs to one game only goes in `games/<game>/`;
|
|
5
|
+
a general one goes in `modules/<name>/index.js` inside the engine and is exported from the engine's `index.js` (then the three hard rules apply: no
|
|
6
|
+
hard-coded art or text, no importing another module's internal files).
|
|
7
|
+
|
|
8
|
+
## 1. Template (example: stamina, in the game folder as `games/<game>/stamina.js`)
|
|
9
|
+
```js
|
|
10
|
+
// Stamina: running drains it, standing recovers it; at 0 you can't run. engine.stamina.value is 0..max
|
|
11
|
+
import { checkOptions } from 'threedog'; // inside an engine module write '../../core/validate.js'
|
|
12
|
+
|
|
13
|
+
export function stamina(opts = {}) {
|
|
14
|
+
checkOptions('stamina()', opts, ['max', 'drain', 'regen']); // a misspelled option name gets a console hint with the fix
|
|
15
|
+
const { max = 100, drain = 20, regen = 10 } = opts;
|
|
16
|
+
let e = null, baseRun = null, shown = -1;
|
|
17
|
+
const api = {
|
|
18
|
+
value: max, max,
|
|
19
|
+
/** Eating restores stamina */
|
|
20
|
+
restore(n) { api.value = Math.min(max, api.value + n); },
|
|
21
|
+
};
|
|
22
|
+
return {
|
|
23
|
+
name: 'stamina', label: '体力', requires: ['characters'], optional: ['hud'], stage: 'gameplay', // once installed, engine.stamina === api
|
|
24
|
+
install(engine) {
|
|
25
|
+
e = engine;
|
|
26
|
+
e.i18n.add({ 'zh-CN': { 'stamina.label': '体力' }, en: { 'stamina.label': 'Stamina' } }); // don't hard-code UI text
|
|
27
|
+
e.saves.register('stamina', { save: () => api.value, load: v => { if (typeof v === 'number') api.value = v; } });
|
|
28
|
+
return api;
|
|
29
|
+
},
|
|
30
|
+
fixed(dt) { // timing and value changes go in fixed (60 Hz, doesn't run while paused)
|
|
31
|
+
const p = e.player; if (!p) return;
|
|
32
|
+
baseRun ??= p.runSpeed;
|
|
33
|
+
api.value = p.state === 'run' ? Math.max(0, api.value - drain * dt) : Math.min(max, api.value + regen * dt);
|
|
34
|
+
p.runSpeed = api.value > 0 ? baseRun : p.speed; // no stamina: walk only
|
|
35
|
+
},
|
|
36
|
+
frame() { // UI goes in frame; update only when the value changed (hud.bar redraws on every call)
|
|
37
|
+
const v = Math.round(api.value);
|
|
38
|
+
if (v !== shown) { shown = v; e.hud?.bar('stamina', { value: v, max, label: e.t('stamina.label') }); }
|
|
39
|
+
},
|
|
40
|
+
describe() { return { value: Math.round(api.value), max }; }, // this becomes describe().stamina
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
```
|
|
44
|
+
Install it: `engine.use(openWorld({ camera: 'follow', ...}), stamina({ max: 80 }))` (dependencies must be installed first).
|
|
45
|
+
|
|
46
|
+
## 2. Hooks and order cheat sheet
|
|
47
|
+
- `install(e)` returns the public object; `init(e)` (may be async) prepares at start; while `isReady(e)` returns false the loading screen waits for it
|
|
48
|
+
(the hook is called isReady; `ready` is always a boolean property in the engine); `afterLoad(e)` (may be async) runs after a save loaded, to rebuild
|
|
49
|
+
what the loaded state needs nearby, with gameplay frozen until it resolves.
|
|
50
|
+
- `fixed(dt, e)` movement, timing, gameplay keys (`input.pressed` read in fixed is this step's snapshot, independent of frame rate); `frame(dt, e)`
|
|
51
|
+
animation, camera, UI (it reads this frame's latest input); `afterRender(dt, e)` after rendering.
|
|
52
|
+
- `describe(e, ctx)`: the return value goes into `describe().<module name>`; `ctx.near(object or {x,z}, { name, kind })` reports things nearby.
|
|
53
|
+
- `applyState(e, p)`: called by `engine.applyState` / URL parameters; it only receives the keys `time`, `weather` and `cutscene`.
|
|
54
|
+
- `stage`: when the hooks run (first -> last): `control` timeline, camera -> `world` terrain, level -> `environment` weather, sky, water -> `gameplay`
|
|
55
|
+
interactions, dialogue, entities -> `presentation` particles, objective markers -> `late` (the default) characters, physics -> `audio` music. Within
|
|
56
|
+
a stage, to read another module's result for this frame, write `after: ['its-name']` (or `before`); across stages the stage always wins, so a
|
|
57
|
+
`before` / `after` that contradicts it (a `control` module `after` an `audio` one) makes `engine.use` throw `module-order` naming both modules: give
|
|
58
|
+
them the same stage or drop the line. `engine.use(a, b)` is all-or-nothing: if `b` fails, nothing of `a` stays installed.
|
|
59
|
+
- Between modules: notify with `e.events.emit('stamina:empty')` and let others `on` it; use optional dependencies as `e.hud?.` and list them in
|
|
60
|
+
`optional: ['hud']` (for engine modules R16 of `npm run check` verifies this). Never import another module's files directly.
|
|
61
|
+
- A module the game cannot run without sets `critical: true`: if its `init` fails, `engine.start()` rejects with the module name and reason (default
|
|
62
|
+
false: a failed init is reported and start goes on). A module installed after start gets no `fixed` / `frame` before its `init` finished:
|
|
63
|
+
`engine.moduleStates` shows `initializing` / `running` / `failed`, and `await engine.loading.settled()` waits for it. A module whose `isReady` never
|
|
64
|
+
turns true makes `start()` reject after `engine.loading.timeoutMs` (default 120 s), naming it.
|
|
65
|
+
- Presentation modules (gameplay works without them) set `presentation: true`: an error in their hooks only disables that module; an error in a
|
|
66
|
+
gameplay module freezes the game in development/tests and is recorded in `engine.error`.
|
|
67
|
+
- Cleanup is not written by hand: events, onFixed/onFrame, clock, jobs, stream, ray registrations and scene GPU memory are collected by
|
|
68
|
+
`engine.dispose()`. DOM listeners use `addEventListener(type, fn, { signal: engine.signal })`, and UI elements attach to `engine.uiRoot` (not
|
|
69
|
+
`document.body`).
|
|
70
|
+
The `dispose(e)` hook only collects what the core can't, such as Workers, the physics world and real-time timers, and is called in reverse install order.
|
|
71
|
+
- While frozen (`engine.freeze`, flow pause) `fixed` is skipped entirely and `frame` still runs: check `e.frozen` before gameplay decisions.
|
|
72
|
+
- Changing what a saved part looks like: raise its version and add one upgrade step per old version, e.g.
|
|
73
|
+
`e.saves.register('stamina', { version: 2, migrate: { 1: v => ({ value: v }) }, save, load })`. `load` only ever sees the current shape; a save
|
|
74
|
+
written by a newer build is refused (load returns false, the save is kept).
|
|
75
|
+
- Saved state the module writes joins the ops guard (experimental): `e.ops.guard('stamina.set')` in each writing method (a no-op in production builds,
|
|
76
|
+
no DEV check needed), `e.ops.allow(fn)` around writes that are allowed anyway (recipe 23 section 5).
|
|
77
|
+
- **Per-playthrough state** (one hook for every module): state that is not a save part but belongs to the current playthrough (an open dialogue, a
|
|
78
|
+
trigger's `inside` / `once`, markers derived from quests, a pending request) is dropped on `e.events.on('session:end', ...)`: it fires before
|
|
79
|
+
`engine.session` newGame / load / quit replaces the state. State derived from save parts is rebuilt on `'session:start'` (newGame / load) and
|
|
80
|
+
`'save:loaded'` (`saves.load`). Save parts themselves need nothing: the session applies the new-game state or the save. A module's `describe()`
|
|
81
|
+
should show such state, because the session spec (`npm test -- Session`) compares every installed module's describe after two new games.
|
|
82
|
+
- When you only need a per-frame callback and no module structure: `const h = engine.onFrame(dt => ...)` / `engine.onFixed`, and `h.remove()` cancels it.
|
|
83
|
+
|
|
84
|
+
## 3. Extra steps when it goes into the engine
|
|
85
|
+
- Write the declarations and JSDoc in `index.d.ts` (or `types/*.d.ts`) of the engine package; `npm run types` checks that the exports of index.js are declared.
|
|
86
|
+
- Add look parameters to the style pack (see `09-style-pack.md`), put text in i18n, then `npm run map` to generate API.md + `api/` / CODEMAP.md.
|
|
87
|
+
|
|
88
|
+
## 4. Verify
|
|
89
|
+
- `npm run check` (hard rules + types + generated docs up to date).
|
|
90
|
+
- In a test: watch `stamina.value` in the describe returned by `engine.step(2)`; `engine.saves.collect().parts.stamina` shows the save content.
|
|
91
|
+
- Add an automated test: write one entry like those in `tests/specs/*.mjs` and run only it with `npm test -- name`.
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
# Performance investigation (F3, budget, profile, describe().perf)
|
|
2
|
+
|
|
3
|
+
Order: first use numbers to decide which category is over (frame rate? draw calls? CPU? startup?), then find who takes the most, and after changing,
|
|
4
|
+
compare before/after with the same method.
|
|
5
|
+
Note: cloud tests use software rendering (SwiftShader), so the numbers are for **relative comparison** only; for real-device results ask the user to
|
|
6
|
+
press F3 in the browser. Measurement method and reference data are in `../PERF.md`.
|
|
7
|
+
|
|
8
|
+
## 1. Where things stand
|
|
9
|
+
- **F3 panel** (`debug()` module, included in openWorld, collapsed by default, press F3 to open): frame rate, CPU ms/frame, draw calls, triangles,
|
|
10
|
+
chunks visible/loaded, vegetation instances, chunk upload ms, pending generation, time of day;
|
|
11
|
+
with a budget set it also shows over-limit items and startup time; the "20-second stress test" makes the player run forward fast automatically and
|
|
12
|
+
reports the average frame rate and the worst frame at the end.
|
|
13
|
+
- **Text**: `engine.describe().perf` =
|
|
14
|
+
`{ fps, cpuMs, cpu, apply, drawCalls, triangles, pixelRatio, budget, startup, stream, batching, jobs, commits, chunks?, vegetation? }`;
|
|
15
|
+
the perf line of `npm run shot -- / --describe-only` (in headless mode fps/cpu are `-`; look at draw calls and triangles).
|
|
16
|
+
- **CPU time of a frame**: `engine.cpuMs` is the main-thread time from input to the end of the afterRender hooks; `engine.cpuPhases` splits it into
|
|
17
|
+
`fixed` (input + fixed steps), `frame` (frame hooks, stream, jobs), `render` (draw submission, upload of new objects, shader compiles) and `afterRender`.
|
|
18
|
+
GPU time is not in it. With `npm run perf -- --only=stream` the stream-in numbers below are measured for you.
|
|
19
|
+
- **Applying background results** (`engine.budget.cost.report()`, also `describe().perf.apply` and the budget categories `applyBuildMs` ...): terrain
|
|
20
|
+
chunks, vegetation, colliders and stream builds come back from workers or jobs and are paid for on the main thread, in stages: `transit` (worker round
|
|
21
|
+
trip minus the worker's own compute: queueing and structured clone, an async wait, approximate), `build` (creating the three.js objects), `collider`
|
|
22
|
+
(physics colliders), `upload` (extra render time of the frames that first draw new objects: GPU upload and shader compile, approximate), `stream`
|
|
23
|
+
(the synchronous part of a `stream.add` build callback). Per stage: `n`, `totalMs`, `maxMs`, smoothed `frameMs`, and `bytes` (transit).
|
|
24
|
+
- **Startup**: `engine.startup` = `{ totalMs, startMs, preloadMs, streamMs, compileMs, modules: { name: { init, ready } } }`; `npm test` also prints a
|
|
25
|
+
startup line (with the slowest module) for each item.
|
|
26
|
+
|
|
27
|
+
## 2. Set a budget (so going over reports itself)
|
|
28
|
+
Off by default and costs nothing. The game gives the limits in `createEngine` (only the given categories are checked):
|
|
29
|
+
```js
|
|
30
|
+
const engine = createEngine({ canvas, style, budget: { drawCalls: 250, fps: 55, low1: 30, triangles: 600000, chunkApplyMs: 3, rigidBodies: 300, startupMs: 5000 } });
|
|
31
|
+
// or at runtime: engine.budget.enable({ drawCalls: 200 });
|
|
32
|
+
const r = engine.budget.report(); // { ok, over: [{ category, value, limit, top }] }; going over also prints one console hint
|
|
33
|
+
```
|
|
34
|
+
`top` lists the biggest draw-call users grouped by an object's `userData.budgetTag`. Tag your own things to see who it is:
|
|
35
|
+
```js
|
|
36
|
+
house.userData.budgetTag = 'houses'; // children inherit the parent's tag; untagged ones count as 'other'
|
|
37
|
+
engine.budget.byTag(); // [{ tag, drawCalls, triangles }...], largest first
|
|
38
|
+
engine.budget.metric('fishCount', () => fish.length, { limit: 50 }); // a module's own category
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
## 3. Whose CPU is slow
|
|
42
|
+
```js
|
|
43
|
+
engine.profile(true); // start timing each module's fixed/frame/afterRender
|
|
44
|
+
// ...run for a few seconds (engine.step(3) in a test doesn't render; the real-time loop is more accurate: wait a few seconds)
|
|
45
|
+
engine.profile(); // { terrain: 0.06, rigid: 0.23, ... } average milliseconds per rendered frame; cleared after reading
|
|
46
|
+
engine.profile(false);
|
|
47
|
+
```
|
|
48
|
+
`onFrame/onFixed` callbacks are not in the module timings; if you suspect them, temporarily turn them into a small module (see `14-custom-module.md`)
|
|
49
|
+
and they get timed.
|
|
50
|
+
|
|
51
|
+
## 4. Common fixes
|
|
52
|
+
| Symptom | Fix |
|
|
53
|
+
|---|---|
|
|
54
|
+
| Many draw calls | Use `vegetation` / InstancedMesh for repeated objects; install `hlod()` for a block of buildings; share geometry and materials between copies of a model (`assets.model` shares by default) |
|
|
55
|
+
| Expensive shadows | Style pack `sky.shadow.updateEvery: 3` (update every 3 frames), reduce `mapSize`/`extent`; filter `createEngine({ shadowType: 'basic' })` (hard edge, cheapest) / `'pcf'` (default) / `'vsm'` (softest, costliest), switch live with `engine.look.shadow.set({ type: 'vsm', radius: 3 })` (radius: pcf and vsm only; blurSamples: vsm only; a switch recompiles materials, so avoid doing it every frame); the vegetation species option `shadowRing` (default 1) sets within how many chunk rings it casts shadows; change it while playing with `engine.vegetation.setShadowRing('tree', 0)` |
|
|
56
|
+
| Stutter while walking | Put generation work in `engine.jobs.add(function* () { ...; yield; })` or `engine.stream.add`; chunk upload budget `engine.terrain.applyBudgetMs` |
|
|
57
|
+
| Slow start | Look at which is slowest in `engine.startup.modules`; `npm run bake` for large models; preload only the necessary assets |
|
|
58
|
+
| Slow physics | Keep dynamic rigid bodies within a few hundred (the `rigidBodies` budget); `rigid({ terrainRing: 1 })` |
|
|
59
|
+
| Too much loaded at once | Each `engine.stream` source loads its own surroundings: remove sources you no longer need, give a far camera `physics: false` and a `radius`, use `detail: 'simple'` for a distant view (recipe 18 section 10) |
|
|
60
|
+
|
|
61
|
+
**Main thread busy with simulation or pure computation: use workers.** `createEngine({ threads: 'auto' | n | false })`, default 'auto';
|
|
62
|
+
false = all on the main thread, same results.
|
|
63
|
+
- Many far records: `world.simulate(kind, { far, worker: true })` (recipe 18 section 7).
|
|
64
|
+
- Many paths per step (NPC crowds, AI squads): `engine.characters.findPathAsync(from, to, done)` (recipe 12 section 4); built-in NPCs already use it.
|
|
65
|
+
- Your own worker script: `engine.threads.lane({ create: () => new Worker(new URL('./w.js', import.meta.url), { type: 'module' }), local: makeHandler })`;
|
|
66
|
+
the worker file is `serve(makeHandler())` from `threedog/worker`. Results that change gameplay go through `engine.commits`.
|
|
67
|
+
|
|
68
|
+
**Two worker rules** (full text and examples in `../CONVENTIONS.md`, "Worker limits"):
|
|
69
|
+
- `engine.commits`: when the due tick comes and the worker has not replied, the main thread runs your `fallback()` and applies that (a later reply is
|
|
70
|
+
ignored). The engine does not clear pending requests on save load or level change, so give every request a `valid()` that checks identity
|
|
71
|
+
(generation counter, record still exists, same zone) or call `t.remove()`.
|
|
72
|
+
- `engine.threads.pure(fn)` / `world.simulate(..., { worker: true })`: the function is recompiled from its source, so it cannot capture outside
|
|
73
|
+
variables or imports; put constants inside it. A bad outside variable is reported by name on the first call.
|
|
74
|
+
|
|
75
|
+
## 5. Verify (once before and once after, under the same conditions)
|
|
76
|
+
- `npm run perf` (native vs engine vs per-module cost of openWorld), compared with the tables in `../PERF.md`; differences under 10-30% are noise.
|
|
77
|
+
- Compare a specific scenario: `npm run shot -- / --pos x,z --time 12:00 --describe-only` to see draw calls and triangles.
|
|
78
|
+
- Related tests: `npm test -- 性能预算`, `npm test -- 阴影`, `npm test -- startup time`. Attach the before/after numbers when reporting.
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
# Dev bridge: operate the running game from the terminal (npx threedog describe / step / press / op...)
|
|
2
|
+
|
|
3
|
+
Purpose: after changing code, don't write a playwright script or take a screenshot; just ask "what does the game look like now", advance time, press
|
|
4
|
+
keys, change state. Output is English, three lines or fewer, to save tokens.
|
|
5
|
+
|
|
6
|
+
What the bridge changes lives in this session only: `op`, `step`, `state` and `js` alter the running game and its saves, never the level. To change
|
|
7
|
+
the level, edit `content/*.js` (templates, props, npcs…) or the level model and reload the page.
|
|
8
|
+
|
|
9
|
+
## 1. Usage
|
|
10
|
+
```
|
|
11
|
+
npm run dev -- my-game # terminal A: start the dev server first (for the engine example just npm run dev)
|
|
12
|
+
npx threedog describe -w my-game # terminal B: look at the scene (inside the game folder you can omit -w)
|
|
13
|
+
```
|
|
14
|
+
No browser needs to be open: when the first command arrives, the dev server itself opens a headless page with Playwright (`?threedog-headless`; the
|
|
15
|
+
game only advances on step); once you open the page in a browser, commands go to the real page you clicked most recently.
|
|
16
|
+
|
|
17
|
+
| Command | What it does | Example output |
|
|
18
|
+
|---|---|---|
|
|
19
|
+
| `describe` | One-line scene summary: position / time and weather / nearby / quest | `player (4.0, 7.0) in forest · 07:11 day 1 · clear` |
|
|
20
|
+
| `describe --full` | The state as text, summary first (`engine.describeText()`: at most 30 lines, the nearest things, one line per module with its key counts, and a last line on how to expand). Details: `describe <path>` for one part, `engine.describeText({ full: true })` for everything | `quests: active[1], done=0, failed=0` |
|
|
21
|
+
| `describe --all` | Everything: every nearby thing and every module's full data (`describeText({ full: true })`); large, prefer a path | |
|
|
22
|
+
| `describe render` | How the picture is set: tone mapping, exposure, shadow filter, post effects with params, default lights, each tagged `engine` (default), `style` or `game` (changed after). Also the `renderer:` lines of `describe --full`. Information only, never warns | `{ "toneMapping": { "value": "aces", "by": "style" }, ... }` |
|
|
23
|
+
| `describe player.position` | Player coordinates { x, y, z } (numbers) | `{ "x": 4, "y": 1.2, "z": 7 }` |
|
|
24
|
+
| `describe player.state` | Just one item of `engine.describe()` (dotted path, `--max characters`) | `"idle"` |
|
|
25
|
+
| `step 2` | Advance 2 game seconds (deterministic; a real-time page is paused first) | `✓ Stepped 2 s · player (4.0, 7.0) in forest · 07:20 day 1` |
|
|
26
|
+
| `press interact` | Press an action name or key once (`KeyE`, `e`, `Escape`). **It advances game time**: 0.1 s held + one rendered frame of 1/60 s, about 0.117 s in total; shorten the hold with `--for 0.02` when timing matters | `✓ Pressed menu (Escape) · … · window open: settings` |
|
|
27
|
+
| `hold moveForward 1.5` | Hold for 1.5 seconds | `✓ Held moveForward (KeyW) for 1.5 s · player (-0.6, 3.0) …` |
|
|
28
|
+
| `skip to=06:00` / `skip seconds=600` | Jump the clock like sleeping (`engine.skip`) | `✓ Skipped to 06:00 → 21600 · … 06:00 day 2` |
|
|
29
|
+
| `ops` | What the player can do now: every op offer checked with `can` (`recipes/23-ops.md`) | `✓ shop.buy item=bread · ✗ shop.buy item=cake (soldOut)` |
|
|
30
|
+
| `op shop.buy shop=bakery item=bread n=2` | Run a game op (source `bridge`, **no time passes**). Values follow the op's `args` shape (`n=2` a number, `position=3,0,-2` an array). **Change state with this, not `js`**: `js` writes skip the op log | `✓ shop.buy → 2 · Bag gold×2 bread×2` / `✗ shop.buy: noMoney (Not enough gold)` |
|
|
31
|
+
| `inspect` / `inspect npc_3` / `inspect 10,-4` | What is around the player and which ops it can do now, with reasons (`engine.inspect`, recipes/23-ops.md section 8) | `player at (4, 7) · near: 老渔夫 1 m` / `✗ barter.buy shop=fisher-basket item=feather (soldOut: …)` |
|
|
32
|
+
| `pick 480,270` | What is at that screen pixel: record id, kind, template, the content file and line that defines it, its fields (recipes/30-templates.md section 5) | `✓ chest-home (kind chest, template chest) …` / `defined in content/props.js:14: edit it there …` |
|
|
33
|
+
| `explain op barter.buy shop=fisher-basket item=berry` / `explain quest first-light` | Why an op cannot run now (the reason and the op's note on fixing it first; `--full` adds the last attempt and events around it), or where a quest is stuck (`engine.explain`) | `✗ barter.buy {...} cannot run now: noFilm (Not enough film)` |
|
|
34
|
+
| `scenario barter` | Run `tests/scenarios/barter.json` (recipes/23-ops.md section 7); prints failed checks, leaves it paused | `✓ barter: 6 checks passed` |
|
|
35
|
+
| `state time=18:30 weather=rain pos=40,-20` | Set the scene (like URL parameters: time weather pos save wait cutscene state) | `✓ Set · 18:30 day 1 · rain` |
|
|
36
|
+
| `js "engine.sky.timeOfDay"` (alias `eval`) | Evaluate an expression in the page; `engine` is available directly and `await` works inside; multi-line statements need their own `return` (e.g. `js "const p = engine.player.position; return p.x + p.z"`). Long scripts: `js --file script.js` | `✓ 0.77` |
|
|
37
|
+
| `snap name` | Screenshot to `.threedog/shots/name.png` | `✓ Screenshot .threedog/shots/t1.png (163 KB)` |
|
|
38
|
+
| `snap-describe save` / `snap-describe diff` + name | Describe snapshot instead of a screenshot: save the gameplay part of `describe()` as a baseline, or print how the running page differs from it (section 7) | `✗ describe "market" differs from the baseline in 1 place:` |
|
|
39
|
+
| `errors` | Page errors added since last time (full log: `.threedog/errors.log`). Known classes get a cause + recipe line (section 8) | `✗ 1 new error` / `✗ 3 new errors` / `✓ No new errors` |
|
|
40
|
+
| `loading` / `loading hero` | What loading waits for, what failed (file, HTTP status, fallback) and whether it blocks the start; works while `start()` is stuck. With a name: that task with its manifest and path (`recipes/05-props-bake.md` section 3) | `… waiting: decoding model "hero" (…)` / `✗ Loading finished, 4/5 ok, 1 failed` |
|
|
41
|
+
| `reload` / `resume` | Reload the page / resume real-time running | |
|
|
42
|
+
|
|
43
|
+
## 2. Notes
|
|
44
|
+
- **Smallest scenario** (`tests/scenarios/coins.json` <!-- r18-ignore-line -->, then `npx threedog verify coins` or `scenario coins`; `verify` with no file says "Have: none"):
|
|
45
|
+
`{ "name": "coins", "url": "/", "state": { "pos": "6,4" }, "steps": [ { "step": 1 }, { "expect": { "inventory.items.coin": 1 } } ] }`
|
|
46
|
+
- **Teleport + `step 1` collects `auto` pickups** (`state pos=`, `player.placeAt`): the pickup check runs in the fixed step after any move.
|
|
47
|
+
- **`shot` always starts a fresh game** (`?save=slot1` loads one); after playing use `snap name`. `shot --keep` adds a timestamp to the file name (no overwrite); `shot --look` prints mean luminance / saturation and the share of overexposed (>=250) and dark (<=20) pixels.
|
|
48
|
+
- **`step` / `press` pause the real page**; resume with `npx threedog resume` when done (they pause as owner `threedog`, so a game's own pause stays). A headless page only advances on step anyway.
|
|
49
|
+
- **Run state** is printed after `step` / `press` / `skip` / `resume` and by `npx threedog status`: `running`, `title-frozen` (title screen waiting for start), `test-paused` (only the bridge paused it), `paused(by owners)` (every `pause` / `freeze` owner, e.g. `ui-inventory`) or `loading`. The same object is `engine.runState` and `describe().time.run`: `{ state, by, blockedBy }`, where `blockedBy` lists what keeps input from driving the game (opaque input contexts such as `win-settings`, `ui-title`, `dialogue`, `cutscene`, plus `error` and `loading`); the bridge and the MCP tools copy it as-is. A test that pauses passes `pause(owner, { kind: 'test' })` to read as `test-paused`.
|
|
50
|
+
- **Who holds what**: `describe().time.heldBy` lists every pause, freeze, camera and debug-view holder in one shape `[{ owner, at }]` (`at` = file:line of the first take), so a stuck pause or a camera nobody gave back has a name.
|
|
51
|
+
- **`snap` on a real page captures only the canvas** (not the HTML UI); on a headless page it captures the whole page. To see UI state use `describe`
|
|
52
|
+
(`ui.windows`, dialogue).
|
|
53
|
+
- **Keys go through `engine.input` like a real keyboard**: action names are translated to keyboard keys (gamepad buttons are ignored); when a window
|
|
54
|
+
locks input, menu-type actions (`pressedRaw`) are still received.
|
|
55
|
+
- **In your own page scripts and tests do the same with `engine.input.simulate(action, down = true)`** (it goes through the same path as `press`, and
|
|
56
|
+
works with `engine.step`): `engine.input.simulate('jump'); engine.step(1 / 60); engine.input.simulate('jump', false)`. Never call `_keyDown` /
|
|
57
|
+
`_keyUp` (internal).
|
|
58
|
+
- `describe` by default gives only the 3 nearest things and the first quest; for detail use a path (`quests.active`, `nearby`, `world`) or `--full`;
|
|
59
|
+
|
|
60
|
+
- Several pages: `--page /<page>.html` picks the path; `-w name` picks the workspace.
|
|
61
|
+
- To change the port: `npm run dev -- my-game --port 5000`; the CLI finds the port from `.threedog/dev.json`, so you don't need to specify it again.
|
|
62
|
+
- If a command never becomes ready: most likely `main.js` doesn't set `window.engine = engine;` (it must come before `await engine.start()`). Under
|
|
63
|
+
the dev server `engine.start()` attaches it automatically, but the bundled build used by npm test does not; the timeout error says whether the page
|
|
64
|
+
has `window.engine`, `engine.ready`, and the latest page errors.
|
|
65
|
+
- Error messages give the cause and the next step, e.g. "no running dev server -> run npm run dev first".
|
|
66
|
+
|
|
67
|
+
## 2b. A scripted playthrough, and three kinds of check
|
|
68
|
+
```
|
|
69
|
+
npx threedog state pos=0,0 time=12:00 # known start
|
|
70
|
+
npx threedog hold moveForward 1.5 # walk (real key path, advances 1.5 s)
|
|
71
|
+
npx threedog press interact # one key press (~0.117 s)
|
|
72
|
+
npx threedog step 2 # let things happen
|
|
73
|
+
npx threedog js "engine.player.position.x > 1" # state assertion: read the ✓ true / false
|
|
74
|
+
npx threedog snap after-walk # only now look at pixels
|
|
75
|
+
```
|
|
76
|
+
The same steps as a file: `tests/scenarios/<name>.json` with `{ "press": … }`, `{ "step": … }`, `{ "expect": { path: value } }` (section 9; no `hold` there).
|
|
77
|
+
- **State checks** (`op`, `expect`, `describe`, `js`): fast and exact, but they skip input. They prove rules, not that the player can reach them.
|
|
78
|
+
- **Simulated-input checks** (`press`, `hold`, `engine.input.simulate`): bridge key events through the game's input path, never a physical keyboard/mouse. `verify` prints `Layers: direct N, simulated-input N, real-browser-input 0 (not verified), visual 0`, then an **Evidence** block (each check's layer and what it asserted), a fixed **NOT proven** line (pointer lock and mouse look, real GPU/visuals, real FPS) and **Coverage** (ops run vs defined, refused ops counted as run and marked; modules in three groups: tested = an op ran, indirect = no op but describe section compared / save part changed / events fired, untested; lists capped at 10 with "+N more"; uses `engine.catalog()`). `threedog scenario` prints the same Coverage block; the full lists are in `--json` (`data.evidence.coverage`, `data.coverage`). Not yet covered: content ids (defined vs touched).
|
|
79
|
+
- **Visual checks** (`snap`, `shot --look`): the only ones that see the look (exposure, color, UI overlap). Slowest; take them last.
|
|
80
|
+
|
|
81
|
+
## 3. Windows / PowerShell notes
|
|
82
|
+
- **Quote commas**: PowerShell splits `pos=1,-8` into two arguments and the coordinates become NaN. Write `npx threedog state "pos=1,-8"` (the bridge
|
|
83
|
+
reports an error and shows this tip when pos is not two numbers).
|
|
84
|
+
- Wrap the whole js / eval expression in **double quotes** and use single quotes for strings inside: `npx threedog js "engine.vars.counter('score')"`.
|
|
85
|
+
PowerShell expands `$variables` inside double quotes; to pass `$` literally wrap the whole thing in single quotes.
|
|
86
|
+
- **Write a command on a single line**: a multi-line here-string passed to a native command often silently returns nothing in PowerShell. Put several
|
|
87
|
+
statements on one line separated by semicolons, or write them to a file and use `npx threedog js --file script.js` (no quoting or newline worries).
|
|
88
|
+
- Some terminal sandboxes (Bash) block commands containing the word `eval`: use `js`, not `eval`.
|
|
89
|
+
- Paths containing Chinese characters are fine; inside the game folder you can omit `-w`.
|
|
90
|
+
|
|
91
|
+
## 3b. Speed, a session, and checks in one call
|
|
92
|
+
|
|
93
|
+
Why a command used to take seconds: `npx` itself costs about 2.5 s on Windows (npm starts, resolves the bin) before threedog runs at all; threedog added a second node process (about 0.25 s) and a cold first request. Measured on the engine example, per command: `npx threedog describe` 3.2 s; `node node_modules/@threedog/tools/bin/threedog.mjs describe` 0.83 s before, 0.50 s now (one process, lazy imports); with a session 0.4 s (node start alone is 0.27 s).
|
|
94
|
+
|
|
95
|
+
- For a many-step test call the bin directly (`node node_modules/@threedog/tools/bin/threedog.mjs ...`, or `node_modules/.bin/threedog`) instead of `npx`.
|
|
96
|
+
- `npx threedog session` starts a background process that serves later commands; it exits after 10 idle minutes (`--minutes N`), `session stop` ends it. Commands behave identically with or without it.
|
|
97
|
+
- `threedog js --file steps.js`: put the whole test in one file and run it once. Inside: `assert(cond, msg)`, `expect(v).toBe(x)` (also `toEqual`, `toBeCloseTo(x, tol)`, `toBeGreaterThan`), `step(seconds)`, `log(...)`, and `engine`. The output is only the failures and one summary line, exit code 1 on failure, so ten steps cost one round trip and a few tokens:
|
|
98
|
+
|
|
99
|
+
```js
|
|
100
|
+
step(2);
|
|
101
|
+
const before = engine.tick;
|
|
102
|
+
step(1);
|
|
103
|
+
expect(engine.tick).toBeGreaterThan(before, 'time advanced');
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
## 4. Let describe see the game's own state
|
|
107
|
+
A game's own state (score, number of targets, crops) is not in `describe` by default. **Small games use this**: register it in one line, no module needed:
|
|
108
|
+
```js
|
|
109
|
+
engine.describe.add('range', () => ({ score, targets: targets.length })); // the returned handle's .remove() cancels it
|
|
110
|
+
```
|
|
111
|
+
After that `npx threedog describe range` shows it, and `describeText()` includes it too. The name must not collide with a core field (player, time...)
|
|
112
|
+
or a module name; if the callback throws, only this item shows `{ error }` and the rest are unaffected.
|
|
113
|
+
**Large games write their systems as modules** (see 14-custom-module.md) and use the module's `describe(e, ctx)` hook: the return value likewise goes
|
|
114
|
+
into `describe().<module name>`, and `ctx.near()` can report "things nearby".
|
|
115
|
+
|
|
116
|
+
## 5. Safety
|
|
117
|
+
The bridge exists only in the dev server (`apply: 'serve'`); built and preview output contains no bridge code (`npm test -- "dev bridge"` checks
|
|
118
|
+
this). The command entry point `POST /__threedog/cmd` accepts only local connections, requires the random token in `.threedog/dev.json`, the Host must
|
|
119
|
+
be localhost, and anything carrying an Origin (sent from a web page) is rejected.
|
|
120
|
+
|
|
121
|
+
## 6. Reuse in scenario tests
|
|
122
|
+
The bridge commands are built on one small driver, `{ evaluate(src, arg), screenshot(), reload?() }`. The dev bridge's driver forwards the three to
|
|
123
|
+
the dev server. For your own tests, `import { pageDriver, runScenario } from '@threedog/tools/scenario'` (the public entry; the command runner behind
|
|
124
|
+
the bridge is internal) gives the same driver for a Playwright `page` and runs a scenario file through it.
|
|
125
|
+
|
|
126
|
+
## 7. Describe snapshots instead of screenshots
|
|
127
|
+
A baseline is the gameplay part of `engine.describe()` saved as JSON (`<workspace>/tests/snapshots/<name>.describe.json`, commit it). `perf` and
|
|
128
|
+
`time.elapsed` are dropped; numbers compare within a tolerance (default 0.5); a list of things with an `id` or `name` is compared by that key, so a
|
|
129
|
+
reordered `nearby` is not a change. A difference comes out as text, e.g. `player.x: 10 -> 14 (changed 4, tolerance 0.5)` or `nearby[Cow]: added {...}`.
|
|
130
|
+
|
|
131
|
+
```
|
|
132
|
+
npx threedog snap-describe save market-noon --only player,quests,nearby # write / overwrite the baseline
|
|
133
|
+
npx threedog snap-describe diff market-noon --only player,quests,nearby # compare the running page with it (exit code 1 if different)
|
|
134
|
+
```
|
|
135
|
+
Options: `--only a,b.c` (compare just these fields; dotted paths allowed), `--ignore x.y` (extra fields to skip), `--tolerance 1`. Use the same
|
|
136
|
+
`--only` for save and diff.
|
|
137
|
+
|
|
138
|
+
In a test, one line (the page must already be in the state to freeze; use `engine.pause()` and `engine.step()` first):
|
|
139
|
+
```
|
|
140
|
+
import { expectDescribe } from '@threedog/tools/describe-snapshot'; // in the engine's own specs: '../../../tools/describe-snapshot.mjs'
|
|
141
|
+
await expectDescribe({ check, ev }, 'market-noon', { only: ['player', 'quests', 'nearby'], tolerance: { default: 0.5, player: 1 } });
|
|
142
|
+
```
|
|
143
|
+
Update after an intended change: `threedog test <name> --update-snapshots` (writes instead of comparing) or `threedog snap-describe save <name>`.
|
|
144
|
+
Review the JSON diff in git before committing. Take a screenshot only when the look changed.
|
|
145
|
+
|
|
146
|
+
## 8. Errors carry a code, a fix and a doc page
|
|
147
|
+
Every error the engine raises by name carries a stable **code**: `err.code`, `err.fix` (what to do) and `err.docs` (pages to read), and its message
|
|
148
|
+
ends with `[code]` (e.g. `clock.every(seconds): ... [clock-interval]`), so logs show it too. Other known classes (missing `world()`, non-plain world
|
|
149
|
+
data, duplicate ids, unknown option / name, module order, asset 404, ...) get the code of the hint whose pattern matches. Dev text adds `Code: …`
|
|
150
|
+
(when the message has no tag), `Possible cause: …` and `Read: recipes/…, api/…`. The same data shows in `engine.error`
|
|
151
|
+
(`{ where, message, code, fix, docs }`), the first line of `describeText()`, `.threedog/errors.log` and `threedog errors`. Tables:
|
|
152
|
+
`core/errorCodes.js` (`ERROR_CODES`: code -> fix, doc pages; a code never changes meaning) and `core/errorHints.js` <!-- r18-ignore-line -->
|
|
153
|
+
(`ERROR_HINTS`: pattern, cause, doc pages; `codedError(code, message)` builds a coded error). To cover a new class append an entry
|
|
154
|
+
(a pattern class also needs a sample message in the engine repository's `packages/tools/tests/ai-tools.mjs`).
|
|
155
|
+
|
|
156
|
+
## 9. Reusable scenarios
|
|
157
|
+
`engine.applyState({ time, weather, pos, ... })` (also URL parameters) sets up a scenario in one call; `engine.defineState(name, params)` names a
|
|
158
|
+
combination so tests and scenarios reuse it.
|
|
159
|
+
|
|
160
|
+
## 10. MCP server: Claude Code, Cursor and other MCP clients
|
|
161
|
+
`npx threedog mcp` runs the dev bridge as an MCP server over stdio. Each command becomes a tool (`play`, `status`, `describe`, `step`, `press`, `hold`, `skip`, `state`, `ops`,
|
|
162
|
+
`op`, `catalog`, `inspect`, `scene`, `pick`, `thing`, `explain`, `errors`, `loading`, `snap`, `snap_describe`, `scenario`, `verify`, `reload`, `resume`;
|
|
163
|
+
tests/mcp.mjs fails when this list and the server's tools differ) and returns the same text as the
|
|
164
|
+
command line; `snap` also returns the PNG as an image. It finds the dev server through `.threedog/dev.json` like the CLI; with none running, call the `play` tool (it starts the server and waits for the bridge)
|
|
165
|
+
(or start `npm run dev` yourself; a tool call without a server answers with that fix). It is only a local client of the bridge and opens no port; every check in section 5 still applies. As
|
|
166
|
+
with the command line, the `op` and `step` tools change the current session and its saves; the level itself changes only by editing content files.
|
|
167
|
+
|
|
168
|
+
Claude Code (in the game folder; in the engine repository add `-w name` after `mcp`):
|
|
169
|
+
```
|
|
170
|
+
claude mcp add threedog -- npx threedog mcp
|
|
171
|
+
```
|
|
172
|
+
Cursor, `.cursor/mcp.json` in the game folder: <!-- r18-ignore-line -->
|
|
173
|
+
```
|
|
174
|
+
{ "mcpServers": { "threedog": { "command": "npx", "args": ["threedog", "mcp"] } } }
|
|
175
|
+
```
|
|
176
|
+
On native Windows, wrap npx in cmd: `claude mcp add threedog -- cmd /c npx threedog mcp` (Cursor: `"command": "cmd", "args": ["/c", "npx", "threedog", "mcp"]`).
|
|
177
|
+
Faster and the same on every OS: point it at the installed bin with plain node, from the project folder: `claude mcp add threedog -- node node_modules/@threedog/tools/bin/threedog.mjs mcp` (the server starts once per session, so npx only costs at start, but node also avoids `cmd /c`). `npm run new-game` writes a `.mcp.json` like this into the new game, so opening the game folder in Claude Code picks it up.
|
|
178
|
+
|
|
179
|
+
The `js` tool (arbitrary code in the page) is off by default; `threedog mcp --allow-js` enables it, for development only. Other options: `-w name`
|
|
180
|
+
(workspace), `--page /<page>.html` (page path).
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
# World data: things that must be saved, grow, and keep changing while far away
|
|
2
|
+
|
|
3
|
+
Requires module `world()` (already included in the `openWorld()` preset). The interaction prompts in the examples need
|
|
4
|
+
`interactions({ ...presets.interactions.nearest })`, the inventory needs `inventory({ ...presets.keys.inventory })`. The API list is in
|
|
5
|
+
`../api/world.md`; this page explains how to use it and what the rules are.
|
|
6
|
+
|
|
7
|
+
Anything in the game that "must remember its state, survive level changes, and keep changing while far away" (chests, NPCs, zombies, crops, trees the
|
|
8
|
+
player planted, the player itself) is one **plain data record** in `engine.world`: a stable id, a kind, a position, plus your own fields. The model is
|
|
9
|
+
just how it looks when the camera is near; unloading a chunk / level tears down only the model and never loses the data; a save stores only data; far
|
|
10
|
+
away, with no model, the data is still simulated.
|
|
11
|
+
A decorative rock is a props entry in `content/props.js` (an authored record, saved only if play moves or removes it); `engine.add(mesh)` is for
|
|
12
|
+
transient effects. Everything placed in a level comes from content, so a new game equals the content (in dev, start warns about records code created before it).
|
|
13
|
+
Many copies of one interactive object (chests, beds, campfires) with the same model, interaction and container: define it once as a content template
|
|
14
|
+
and place instances (recipe 30-templates.md); the template is the shared read-only definition, the record holds only the instance state.
|
|
15
|
+
|
|
16
|
+
## 1. Three steps: data, look, change
|
|
17
|
+
```js
|
|
18
|
+
const W = engine.world;
|
|
19
|
+
W.add({ id: 'zombie_1', kind: 'zombie', position: [10, 0, -4], hp: 10 }); // fields must be plain values; without an id one is numbered automatically (saved)
|
|
20
|
+
W.present('zombie', {
|
|
21
|
+
build: rec => new THREE.Mesh(zombieGeo, zombieMat), // required: built when the camera is near (may be async); world adds it to the scene at rec.position
|
|
22
|
+
update: (rec, obj, dt) => { obj.visible = rec.hp > 0; }, // optional: called every frame for records that have a model; change the look from the data
|
|
23
|
+
dispose: (rec, obj) => engine.remove(obj), // optional: first argument is the data, second the model; this is the default
|
|
24
|
+
show: rec => rec.hp > 0, // optional: false = this record has no model right now (picked up, waiting to respawn)
|
|
25
|
+
radius: 40, // optional: how near to build the model (meters or a function); default world.radius (60)
|
|
26
|
+
});
|
|
27
|
+
W.simulate('zombie', {
|
|
28
|
+
near: (rec, dt, obj) => { W.move(rec.id, { x: rec.position.x + dt, z: rec.position.z }); }, // near the player: every fixed step; obj may not be built yet (null), gameplay must not depend on it
|
|
29
|
+
far: (rec, dt) => { rec.hp = Math.min(10, rec.hp + dt * 0.1); }, // far away: once every farEvery seconds; dt is accumulated seconds (it can catch up a long time at once)
|
|
30
|
+
});
|
|
31
|
+
```
|
|
32
|
+
- If `build` throws, fails, or returns something that is not an object, the error is reported once and does not block the loading screen
|
|
33
|
+
(`world.ready`); it retries when you walk away and come back.
|
|
34
|
+
- `show` is re-evaluated when `world.set` changes data of that kind. Calling `present` again for the same kind tears down old models with the old
|
|
35
|
+
dispose and rebuilds them with the new one.
|
|
36
|
+
- Animation, particles and other things that only matter per frame go in `present.update`, not in simulate.
|
|
37
|
+
|
|
38
|
+
## 2. How to change data
|
|
39
|
+
- Discrete changes (open a chest, switch growth stage, get picked up, change direction) use `W.set(id, { opened: true })`: it emits `world:change` and
|
|
40
|
+
re-evaluates `show`. Don't `set` every step. id / kind cannot be changed (to change the kind, remove then add).
|
|
41
|
+
- Things that change every step (position, timers, pathfinding state) are changed directly on the rec's fields inside simulate, and position with
|
|
42
|
+
`W.move`: no event, cheap.
|
|
43
|
+
- Both ways are saved (a save compares contents, it does not rely on events). `move` emits no event: if the look needs to follow position, compare in
|
|
44
|
+
`update` (see `content/props.js`).
|
|
45
|
+
- Don't hold a rec object for long: loading a save replaces it with a new object. Keep the id and call `W.get(id)` when you need it.
|
|
46
|
+
- Position forms: Vector3 / object / `[x, y, z]` / `{ x, z }` (a missing y keeps the old one). In development NaN or an array with only two numbers
|
|
47
|
+
throws immediately.
|
|
48
|
+
|
|
49
|
+
## 3. Example: a crop grows with game time, press E to harvest when ripe
|
|
50
|
+
The key idea: **don't accumulate every step; record the time it was planted, `plantedAt = clock.now`, and growth = now - planted time**. Whether the
|
|
51
|
+
player walked away, loaded a save, or fast-forwarded with `engine.step(60)`, the result is right, and no simulate is needed.
|
|
52
|
+
```js
|
|
53
|
+
import { presets, THREE, makeMaterial } from 'threedog';
|
|
54
|
+
|
|
55
|
+
const GROW = 120; // ripe after 120 game seconds (the unit of clock.now)
|
|
56
|
+
const growth = rec => Math.min(1, (engine.clock.now - rec.plantedAt) / GROW); // 0..1
|
|
57
|
+
const geo = new THREE.ConeGeometry(0.25, 0.8, 6);
|
|
58
|
+
|
|
59
|
+
engine.world.present('crop', {
|
|
60
|
+
build(rec) {
|
|
61
|
+
const m = new THREE.Mesh(geo, makeMaterial('prop', { color: 0x6aa84f }));
|
|
62
|
+
m.castShadow = true;
|
|
63
|
+
m.userData.use = engine.interactions.add(m, { label: '收获', radius: 2, enabled: () => growth(rec) >= 1, onUse: () => harvest(rec) }); // can be harvested only when ripe
|
|
64
|
+
return m;
|
|
65
|
+
},
|
|
66
|
+
update(rec, obj) { // grows bigger, changes color when ripe
|
|
67
|
+
const g = growth(rec);
|
|
68
|
+
obj.scale.setScalar(0.3 + 0.7 * g);
|
|
69
|
+
obj.material.color.setHex(g >= 1 ? 0xe8a33d : 0x6aa84f);
|
|
70
|
+
},
|
|
71
|
+
dispose(rec, obj) { obj.userData.use.remove(); engine.remove(obj); }, // an interaction you registered yourself must be removed yourself
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
function harvest(rec) {
|
|
75
|
+
engine.inventory.add('carrot', 2);
|
|
76
|
+
engine.world.remove(rec.id); // delete the data after harvesting (the model goes with it). To "grow back after a while": world.set(rec.id, { plantedAt: engine.clock.now }); to hide temporarily: return false from show
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function plant(x, z) { // the player plants one
|
|
80
|
+
return engine.world.add({ kind: 'crop', position: { x, y: engine.surface(x, z), z }, plantedAt: engine.clock.now });
|
|
81
|
+
}
|
|
82
|
+
```
|
|
83
|
+
Test: `plant(2, 2)` -> `engine.step(130)` (fast-forward 130 game seconds) -> the player walks next to it -> `engine.ops.run('interaction.use')` ->
|
|
84
|
+
`engine.inventory.count('carrot')`.
|
|
85
|
+
|
|
86
|
+
## 4. Data written in content: `initial`
|
|
87
|
+
Things that exist from the start (3 crops already in the field, chests on the map) use `add(def, { initial: true })` and must have a stable id. **A
|
|
88
|
+
save records only their changes and deletions**: if the content changes (one more crop is placed), an old save shows it too; a deleted one stays gone
|
|
89
|
+
after loading, and a deleted field is "no such field" after loading; it does not matter whether `content.load` runs before or after loading the save.
|
|
90
|
+
```js
|
|
91
|
+
for (const [i, p] of [[0, 0], [2, 0], [4, 0]].entries())
|
|
92
|
+
engine.world.add({ id: `crop-start-${i}`, kind: 'crop', position: { x: p[0], z: p[1] }, plantedAt: 0 }, { initial: true });
|
|
93
|
+
```
|
|
94
|
+
When placement should be "random but identical on every start", use `engine.random.seeded(seed)` (an independent generator that does not touch the
|
|
95
|
+
saved `engine.random`):
|
|
96
|
+
```js
|
|
97
|
+
const rnd = engine.random.seeded(7);
|
|
98
|
+
for (let i = 0; i < 20; i++) engine.world.add({ id: `rock-${i}`, kind: 'rock', position: { x: rnd.range(-40, 40), z: rnd.range(-40, 40) } }, { initial: true });
|
|
99
|
+
```
|
|
100
|
+
These loops show what content loaders do. In a game, put such entries in `content/props.js` (a loop inside the content file is fine): each then gets a
|
|
101
|
+
source line (`engine.world.origin(id).definedAt` in dev builds) and a new game stays equal to the content.
|
|
102
|
+
Gameplay randomness (drops, lightning, wander turns) still uses `engine.random` (saved; after loading it continues the same sequence). Records
|
|
103
|
+
generated at runtime (planted by the player, spawned) are saved whole; `add(def, { save: false })` is not saved (temporary things). The rules are
|
|
104
|
+
described at the top of `modules/world/persist.js`.
|
|
105
|
+
World models are in the thing registry too (`engine.thing(id)` answers with the record, saved `'record'`): do not move them from code. Change the
|
|
106
|
+
record (`ops.run('thing.set', { id, position })`, `world.set` / `world.move`); dev reports code that moves a `positionFrom: 'record'` model, and
|
|
107
|
+
`engine.add` of a model throws (recipe 41).
|
|
108
|
+
|
|
109
|
+
A world record's model belongs to the scene too (`40-scene.md`; `engine.thing(id)` shows it, recipe 41). Do not move that model from code: the record owns its <!-- r18-ignore-line -->
|
|
110
|
+
position, so change the record (`world.set`, `world.move`) and the model follows.
|
|
111
|
+
|
|
112
|
+
## 5. Example: something that wanders
|
|
113
|
+
For enemies that chase the player / wandering NPCs there is the ready-made `engine.npcs.behavior(name, { near, far })` + `engine.npcs.avoid` (mutual
|
|
114
|
+
avoidance), see recipe 02 "Changing behavior / custom behavior"; below is the pure world version without NPCs.
|
|
115
|
+
```js
|
|
116
|
+
engine.world.present('chicken', { build: rec => makeChicken() });
|
|
117
|
+
engine.world.simulate('chicken', {
|
|
118
|
+
near: (rec, dt) => wander(rec, dt), // near: a small step every fixed step
|
|
119
|
+
far: (rec, dt) => wander(rec, dt), // far: catch up once every farEvery seconds
|
|
120
|
+
farEvery: 2,
|
|
121
|
+
});
|
|
122
|
+
function wander(rec, dt) {
|
|
123
|
+
const a = rec.heading ?? 0;
|
|
124
|
+
engine.world.move(rec.id, { x: rec.position.x + Math.sin(a) * 1.2 * dt, z: rec.position.z + Math.cos(a) * 1.2 * dt });
|
|
125
|
+
if (engine.random.chance(0.01)) engine.world.set(rec.id, { heading: engine.random.range(0, Math.PI * 2) });
|
|
126
|
+
}
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
## 6. Near, far, camera, player
|
|
130
|
+
- **Near / far is decided by the gameplay anchor `world.anchor`**: by default the position of the player record (`engine.focus` when there is no
|
|
131
|
+
player). A cutscene or photo mode moves the camera away, but the player's surroundings are still simulated as near: gameplay results do not depend
|
|
132
|
+
on the camera. For a top-down strategy game centered on a base, set `W.anchor = baseObject`; set it back to `null` to restore the default.
|
|
133
|
+
- **The player is a record too**: the id and kind added by `createPlayer` are both `'player'`; position, facing, motion state (vx, vz, vy, facing,
|
|
134
|
+
grounded...) and which vehicle it is on (vehicle) live in the record and are saved, and it is never torn down by walking away. Only the character's
|
|
135
|
+
mover changes the position and then writes it back to the record; **move the player with `player.placeAt(position)`, not `world.move('player')`**
|
|
136
|
+
(the mover would overwrite it on the next step). On load the player is put back from the record.
|
|
137
|
+
- **Models are built around the stream sources** (section 10, `33-stream-sources.md`): by default the player (`engine.stream.player`, follows
|
|
138
|
+
`world.anchor`) and the camera
|
|
139
|
+
focus (`engine.stream.camera`). Built inside the radius of any source, torn down beyond 1.25x of all of them, with an error of at most 8 meters; at
|
|
140
|
+
most `world.buildPerFrame` are built per frame (default 8, unlimited while loading), and `ready` waits until all are built. Tearing a model down
|
|
141
|
+
never touches its record.
|
|
142
|
+
- `positionFrom: 'view'` (the model moves itself, for example an NPC driven by the character mover): near simulation builds the model on the spot and
|
|
143
|
+
copies the model position back to the data at the end of every fixed step; when not simulated near, the data decides and the model follows the data.
|
|
144
|
+
A model moved by a physics body saves its position, not the physics solver state: after a load, resting bodies settle again and can differ by ~0.01
|
|
145
|
+
mm, so replays that must match exactly should not depend on physics props.
|
|
146
|
+
- Radius: present / simulate each take their own `radius` (meters or a function); without it they follow `world.radius` (default 60).
|
|
147
|
+
|
|
148
|
+
## 7. Time and ordering rules (nothing lost, nothing doubled, loading a save is bit-identical)
|
|
149
|
+
- The dt of both near and far is accumulated fixed-step seconds (not multiplied by `clock.timeScale`). For one record, whether near, far, or
|
|
150
|
+
alternating, the dts add up to the elapsed time: on the step going from far to near, `far` first catches up the owed time, then `near` runs.
|
|
151
|
+
- **Kinds that only define far** (crops) are not split into near and far; even when you stand next to them they advance at the far pace. **Kinds that
|
|
152
|
+
only define near** are not simulated far away, and the owed time is not caught up.
|
|
153
|
+
- Near: at the start of each step, the records inside the radius are gathered and simulated one by one **sorted by id** (independent of insertion
|
|
154
|
+
order and loading; when near records affect each other, running continuously and saving then loading give bit-identical results).
|
|
155
|
+
- Far: records are bucketed by id and taken in turns (one round every `farEvery` seconds), at most `world.farMaxPerTick` records per fixed step
|
|
156
|
+
(default 500); the rest queue for the next step, and dt keeps accumulating without loss. It counts records, not milliseconds, so the result does not
|
|
157
|
+
depend on how fast the machine is.
|
|
158
|
+
- The owed time and the simulation step count are saved: after loading they are caught up the same way, and the same save gives the same result
|
|
159
|
+
however many fixed steps run per frame. For things measured by game clock (grows in a few days, respawns at a time), record `engine.clock.now` and compare.
|
|
160
|
+
- **Far in workers** (many far records, e.g. thousands of crops): `W.simulate('crop', { far, worker: true })`. Each step's far batch is copied and run
|
|
161
|
+
in `engine.threads` workers, then written back 4 fixed steps later through `engine.commits`; if a reply is late the same function runs on the main
|
|
162
|
+
thread, so threads on / off / slow give **bit-identical** records. Only fields far changed are written back (gameplay changes to other fields during
|
|
163
|
+
those 4 steps are kept). `far` must be self-contained: it is recompiled from source and sees only `(rec, dt)` and globals like `Math`; an outside
|
|
164
|
+
variable throws `... x is not defined. Put constants inside the function, or store the value on the record` (also with `threads: false`, so you find
|
|
165
|
+
it in development). Limit: a save taken while a batch is in flight re-simulates that stretch after loading (equal within float tolerance, not bit-identical).
|
|
166
|
+
|
|
167
|
+
## 8. Querying nearby things
|
|
168
|
+
```js
|
|
169
|
+
const list = engine.world.query({ kind: 'zombie', near: engine.player, radius: 30, where: z => z.hp > 0 }); // array, nearest first
|
|
170
|
+
let crowd = 0;
|
|
171
|
+
engine.world.forEachNear(engine.player, 5, (rec, d2) => { if (rec.kind === 'zombie') crowd++; }); // no allocation, no sorting
|
|
172
|
+
engine.world.get(id); engine.world.view(id); // the data / the current model (null when far)
|
|
173
|
+
```
|
|
174
|
+
For things that query neighbors every step (hundreds of zombies avoiding each other) use `forEachNear`; inside the callback don't add / remove / move,
|
|
175
|
+
note them down and change them after the loop.
|
|
176
|
+
|
|
177
|
+
## 9. zone and data limits
|
|
178
|
+
- A record can carry a `zone` (for example the level name); once `world.zone` is set, records with a different zone get no model and no near
|
|
179
|
+
simulation, and the data stays when the level changes.
|
|
180
|
+
- Data must be plain values (numbers, strings, booleans, arrays, plain objects): in development, putting a three.js object or a function in it throws
|
|
181
|
+
immediately and explains the fix — models go in present, logic goes in simulate.
|
|
182
|
+
|
|
183
|
+
## 10. Stream sources: what is loaded where (teleport, far camera)
|
|
184
|
+
Moved to `33-stream-sources.md`: the shared source list of `engine.stream`, `await engine.stream.teleport(p)`, `engine.stream.source(...)` for a photo
|
|
185
|
+
camera or a far view.
|