threedog 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +5 -0
- package/LICENSE +21 -0
- package/README.md +39 -2
- package/core/Animator.js +268 -0
- package/core/Assets.js +256 -0
- package/core/Audio.js +267 -0
- package/core/Baked.js +72 -0
- package/core/Batching.js +247 -0
- package/core/Budget.js +221 -0
- package/core/Clock.js +94 -0
- package/core/Commits.js +77 -0
- package/core/DebugOverrides.js +143 -0
- package/core/Describe.js +145 -0
- package/core/Engine.js +184 -0
- package/core/Events.js +153 -0
- package/core/I18n.js +94 -0
- package/core/Input.js +245 -0
- package/core/Inspect.js +77 -0
- package/core/InspectScene.js +191 -0
- package/core/Jobs.js +146 -0
- package/core/Loading.js +149 -0
- package/core/MaterialInfo.js +32 -0
- package/core/Ops.js +256 -0
- package/core/Random.js +52 -0
- package/core/Rays.js +160 -0
- package/core/SaveStore.js +85 -0
- package/core/Saves.js +254 -0
- package/core/Stream.js +279 -0
- package/core/Threads.js +158 -0
- package/core/UrlState.js +94 -0
- package/core/Vars.js +35 -0
- package/core/Views.js +49 -0
- package/core/actor.js +23 -0
- package/core/assetEntry.js +89 -0
- package/core/assetLoad.js +190 -0
- package/core/assetManifest.js +35 -0
- package/core/assetReport.js +83 -0
- package/core/audioRules.js +121 -0
- package/core/audioVoice.js +225 -0
- package/core/batchGroups.js +116 -0
- package/core/canvasBox.js +63 -0
- package/core/catalog.js +169 -0
- package/core/checks.js +67 -0
- package/core/claims.js +51 -0
- package/core/dayTime.js +15 -0
- package/core/debugView.js +76 -0
- package/core/describeRender.js +45 -0
- package/core/describeText.js +143 -0
- package/core/easing.js +34 -0
- package/core/errorCodes.js +205 -0
- package/core/errorHints.js +208 -0
- package/core/errors.js +40 -0
- package/core/events.generated.js +84 -0
- package/core/ground.js +102 -0
- package/core/holds.js +106 -0
- package/core/inputContext.js +69 -0
- package/core/inputDefaults.js +22 -0
- package/core/inputPad.js +35 -0
- package/core/inputPointer.js +48 -0
- package/core/inputTouch.js +48 -0
- package/core/lifecycle.js +69 -0
- package/core/lightWatch.js +56 -0
- package/core/look/coreParts.js +112 -0
- package/core/look/layers.js +136 -0
- package/core/look/part.js +173 -0
- package/core/look/report.js +79 -0
- package/core/look/write.js +86 -0
- package/core/loop.js +200 -0
- package/core/math.js +33 -0
- package/core/modules.js +196 -0
- package/core/movement.js +19 -0
- package/core/mulberry32.js +14 -0
- package/core/opsAtomic.js +31 -0
- package/core/opsCheck.js +97 -0
- package/core/opsFail.js +20 -0
- package/core/opsGuard.js +26 -0
- package/core/opsHistory.js +27 -0
- package/core/opsRun.js +77 -0
- package/core/page.js +78 -0
- package/core/params.js +132 -0
- package/core/pureWorker.js +5 -0
- package/core/renamed.js +21 -0
- package/core/saveApply.js +128 -0
- package/core/saveFiles.js +139 -0
- package/core/saveIds.js +53 -0
- package/core/saveVersions.js +97 -0
- package/core/scatter.js +92 -0
- package/core/sceneMethods.js +100 -0
- package/core/screenToGround.js +39 -0
- package/core/services.js +73 -0
- package/core/session.js +171 -0
- package/core/shadowTypes.js +15 -0
- package/core/skip.js +104 -0
- package/core/startup.js +135 -0
- package/core/streamCells.js +24 -0
- package/core/streamSources.js +73 -0
- package/core/styleParts.js +96 -0
- package/core/targeting.js +64 -0
- package/core/thingExplain.js +68 -0
- package/core/thingOps.js +168 -0
- package/core/things.js +212 -0
- package/core/threadPure.js +120 -0
- package/core/threadServe.js +25 -0
- package/core/tier.js +11 -0
- package/core/util.js +11 -0
- package/core/validate.js +204 -0
- package/docs/AI.md +123 -0
- package/docs/API.md +83 -0
- package/docs/CODEMAP.md +347 -0
- package/docs/COMMANDS.md +108 -0
- package/docs/CONVENTIONS.md +145 -0
- package/docs/PERF.md +217 -0
- package/docs/THREE.md +86 -0
- package/docs/api/ambience.md +15 -0
- package/docs/api/assets.md +62 -0
- package/docs/api/audio.md +53 -0
- package/docs/api/budget.md +40 -0
- package/docs/api/cameraRig.md +120 -0
- package/docs/api/characters.md +144 -0
- package/docs/api/clock.md +7 -0
- package/docs/api/collision.md +39 -0
- package/docs/api/content.md +64 -0
- package/docs/api/dialogue.md +39 -0
- package/docs/api/engine.md +199 -0
- package/docs/api/entities.md +61 -0
- package/docs/api/events.md +95 -0
- package/docs/api/flow.md +27 -0
- package/docs/api/grids.md +11 -0
- package/docs/api/ground.md +16 -0
- package/docs/api/hlod.md +34 -0
- package/docs/api/hud.md +31 -0
- package/docs/api/i18n.md +10 -0
- package/docs/api/input.md +24 -0
- package/docs/api/interactions.md +31 -0
- package/docs/api/inventory.md +66 -0
- package/docs/api/jobs.md +10 -0
- package/docs/api/level.md +41 -0
- package/docs/api/lightPool.md +56 -0
- package/docs/api/music.md +34 -0
- package/docs/api/nav.md +26 -0
- package/docs/api/net.md +14 -0
- package/docs/api/openWorld.md +24 -0
- package/docs/api/particles.md +41 -0
- package/docs/api/photo.md +15 -0
- package/docs/api/post.md +10 -0
- package/docs/api/quests.md +36 -0
- package/docs/api/rays.md +26 -0
- package/docs/api/rigid.md +84 -0
- package/docs/api/saves.md +32 -0
- package/docs/api/settings.md +36 -0
- package/docs/api/sky.md +58 -0
- package/docs/api/stream.md +31 -0
- package/docs/api/style.md +134 -0
- package/docs/api/terrain.md +34 -0
- package/docs/api/timeline.md +39 -0
- package/docs/api/tools.md +57 -0
- package/docs/api/triggers.md +56 -0
- package/docs/api/vars.md +9 -0
- package/docs/api/vegetation.md +52 -0
- package/docs/api/water.md +48 -0
- package/docs/api/weather.md +29 -0
- package/docs/api/world.md +30 -0
- package/docs/recipes/01-new-game.md +148 -0
- package/docs/recipes/02-npc.md +167 -0
- package/docs/recipes/03-items-pickups.md +158 -0
- package/docs/recipes/04-quests.md +83 -0
- package/docs/recipes/05-props-bake.md +159 -0
- package/docs/recipes/06-clock-events.md +117 -0
- package/docs/recipes/07-flow-scenes-pause.md +132 -0
- package/docs/recipes/08-weather-sky.md +74 -0
- package/docs/recipes/09-style-pack.md +234 -0
- package/docs/recipes/10-blender-level.md +67 -0
- package/docs/recipes/11-vehicles.md +55 -0
- package/docs/recipes/12-navmesh.md +79 -0
- package/docs/recipes/13-animation.md +149 -0
- package/docs/recipes/14-custom-module.md +91 -0
- package/docs/recipes/15-perf.md +78 -0
- package/docs/recipes/16-dev-bridge.md +180 -0
- package/docs/recipes/18-world.md +185 -0
- package/docs/recipes/19-shooting-picking.md +76 -0
- package/docs/recipes/20-content-actions-save.md +176 -0
- package/docs/recipes/21-camera.md +153 -0
- package/docs/recipes/22-shop-gold.md +107 -0
- package/docs/recipes/23-ops.md +175 -0
- package/docs/recipes/26-ui-parts.md +138 -0
- package/docs/recipes/27-net.md +96 -0
- package/docs/recipes/28-terrain.md +80 -0
- package/docs/recipes/29-grid.md +87 -0
- package/docs/recipes/30-templates.md +131 -0
- package/docs/recipes/31-audio.md +126 -0
- package/docs/recipes/32-action-game.md +33 -0
- package/docs/recipes/33-stream-sources.md +37 -0
- package/docs/recipes/34-environment-lighting.md +36 -0
- package/docs/recipes/35-style-from-reference.md +89 -0
- package/docs/recipes/36-sky-ground-plant-looks.md +116 -0
- package/docs/recipes/37-terrain-look-hooks.md +97 -0
- package/docs/recipes/38-environment-look-hooks.md +83 -0
- package/docs/recipes/40-scene.md +108 -0
- package/docs/recipes/41-thing-registry.md +93 -0
- package/docs/recipes/42-terrain-shape.md +64 -0
- package/docs/recipes/43-shader-patches-surface-looks.md +120 -0
- package/docs/recipes/44-water-weather-look-hooks.md +135 -0
- package/docs/recipes/45-cascaded-shadows.md +51 -0
- package/docs/recipes/46-blender-art-route.md +114 -0
- package/docs/recipes/47-island-snow-backdrop.md +44 -0
- package/docs/recipes/48-make-material.md +70 -0
- package/docs/recipes/49-game-module-contract.md +71 -0
- package/docs/recipes/50-own-renderer.md +12 -0
- package/docs/recipes/51-capability-catalog.md +63 -0
- package/docs/recipes/52-look.md +108 -0
- package/examples/action/DESIGN.md +3 -0
- package/examples/action/GAMEMAP.md +127 -0
- package/examples/action/content/actions.js +8 -0
- package/examples/action/content/audio.js +9 -0
- package/examples/action/content/index.js +10 -0
- package/examples/action/content/items.js +4 -0
- package/examples/action/content/places.js +4 -0
- package/examples/action/content/props.js +11 -0
- package/examples/action/content/templates.js +10 -0
- package/examples/action/content/views.js +6 -0
- package/examples/action/look.js +5 -0
- package/examples/action/main.js +137 -0
- package/examples/action/models.js +25 -0
- package/examples/sheepisland/GAMEMAP.md +107 -0
- package/examples/sheepisland/content/index.js +6 -0
- package/examples/sheepisland/content/props.js +19 -0
- package/examples/sheepisland/content/templates.js +5 -0
- package/examples/sheepisland/content/vegetation.js +8 -0
- package/examples/sheepisland/main.js +71 -0
- package/examples/sheepisland/params.js +25 -0
- package/examples/sheepisland/style/index.js +79 -0
- package/examples/sheepisland/style/models.js +59 -0
- package/examples/sheepisland/views.js +9 -0
- package/examples/styletest/GAMEMAP.md +135 -0
- package/examples/styletest/content/index.js +9 -0
- package/examples/styletest/content/items.js +8 -0
- package/examples/styletest/content/npcs.js +8 -0
- package/examples/styletest/content/places.js +5 -0
- package/examples/styletest/content/props.js +16 -0
- package/examples/styletest/content/templates.js +9 -0
- package/examples/styletest/content/vegetation.js +31 -0
- package/examples/styletest/look.js +11 -0
- package/examples/styletest/main.js +95 -0
- package/examples/styletest/models.js +87 -0
- package/examples/styletest/overrides.js +33 -0
- package/examples/styletest/panel.js +135 -0
- package/examples/styletest/params.js +32 -0
- package/examples/styletest/views.js +31 -0
- package/examples/world/DESIGN.md +5 -0
- package/examples/world/GAMEMAP.md +171 -0
- package/examples/world/content/actions.js +8 -0
- package/examples/world/content/audio.js +25 -0
- package/examples/world/content/bodies.js +12 -0
- package/examples/world/content/containers.js +4 -0
- package/examples/world/content/dialogues.js +33 -0
- package/examples/world/content/index.js +17 -0
- package/examples/world/content/items.js +10 -0
- package/examples/world/content/npcs.js +14 -0
- package/examples/world/content/pickups.js +11 -0
- package/examples/world/content/places.js +6 -0
- package/examples/world/content/props.js +12 -0
- package/examples/world/content/quests.js +15 -0
- package/examples/world/content/rules.js +23 -0
- package/examples/world/content/templates.js +5 -0
- package/examples/world/content/vegetation.js +32 -0
- package/examples/world/main.js +168 -0
- package/examples/world/models.js +28 -0
- package/index.d.ts +306 -0
- package/index.js +122 -0
- package/llms.txt +61 -0
- package/modules/ambience/Ambience.js +186 -0
- package/modules/camera/FirstPersonCamera.js +131 -0
- package/modules/camera/FixedCamera.js +162 -0
- package/modules/camera/FollowCamera.js +91 -0
- package/modules/camera/RtsCamera.js +132 -0
- package/modules/camera/common.js +182 -0
- package/modules/camera/index.js +11 -0
- package/modules/camera/projection.js +34 -0
- package/modules/characters/Character.js +235 -0
- package/modules/characters/NPC.js +242 -0
- package/modules/characters/assetModel.js +42 -0
- package/modules/characters/astar.js +66 -0
- package/modules/characters/behaviors.js +72 -0
- package/modules/characters/footsteps.js +13 -0
- package/modules/characters/index.js +215 -0
- package/modules/characters/moveHelpers.js +29 -0
- package/modules/characters/movers/common.js +62 -0
- package/modules/characters/movers/rapier.js +74 -0
- package/modules/characters/movers/simple.js +43 -0
- package/modules/characters/npcAvoid.js +129 -0
- package/modules/characters/npcSim.js +150 -0
- package/modules/characters/npcView.js +42 -0
- package/modules/characters/pathAsync.js +113 -0
- package/modules/characters/pathJob.js +62 -0
- package/modules/characters/pathWorker.js +7 -0
- package/modules/characters/playerStrings.js +12 -0
- package/modules/characters/proceduralRig.js +58 -0
- package/modules/characters/useModel.js +22 -0
- package/modules/characters/walkTo.js +58 -0
- package/modules/collision/Collision.js +274 -0
- package/modules/collision/grid.js +63 -0
- package/modules/content/explain.js +13 -0
- package/modules/content/ids.js +95 -0
- package/modules/content/index.js +154 -0
- package/modules/content/loader.js +190 -0
- package/modules/content/models.js +69 -0
- package/modules/content/packs.js +69 -0
- package/modules/content/props.js +89 -0
- package/modules/content/rules.js +134 -0
- package/modules/content/templates.js +189 -0
- package/modules/debug/DebugPanel.js +174 -0
- package/modules/entities/Entities.js +243 -0
- package/modules/entities/build.js +25 -0
- package/modules/entities/index.js +4 -0
- package/modules/flow/index.js +101 -0
- package/modules/gameplay/Container.js +227 -0
- package/modules/gameplay/Containers.js +89 -0
- package/modules/gameplay/Dialogue.js +219 -0
- package/modules/gameplay/Interactions.js +253 -0
- package/modules/gameplay/Inventory.js +224 -0
- package/modules/gameplay/Quests.js +205 -0
- package/modules/gameplay/boxOps.js +60 -0
- package/modules/gameplay/dialogueBox.js +48 -0
- package/modules/gameplay/interactionPrompt.js +28 -0
- package/modules/gameplay/inventoryOps.js +137 -0
- package/modules/gameplay/pickups.js +115 -0
- package/modules/gameplay/questLog.js +54 -0
- package/modules/gameplay/questSave.js +71 -0
- package/modules/grid/Grid.js +184 -0
- package/modules/grid/Layer.js +142 -0
- package/modules/grid/index.js +236 -0
- package/modules/grid/ops.js +73 -0
- package/modules/grid/preview.js +85 -0
- package/modules/grid/tiles.js +79 -0
- package/modules/hlod/index.js +167 -0
- package/modules/hud/index.js +167 -0
- package/modules/hud/parts.js +80 -0
- package/modules/level/geometry.js +46 -0
- package/modules/level/heightfield.js +160 -0
- package/modules/level/index.js +233 -0
- package/modules/level/nodes.js +84 -0
- package/modules/lights/index.js +227 -0
- package/modules/music/Music.js +294 -0
- package/modules/music/index.js +2 -0
- package/modules/music/rules.js +28 -0
- package/modules/nav/index.js +156 -0
- package/modules/nav/navPath.js +17 -0
- package/modules/net/Client.js +137 -0
- package/modules/net/Host.js +117 -0
- package/modules/net/Net.js +49 -0
- package/modules/net/index.js +77 -0
- package/modules/net/sync.js +114 -0
- package/modules/net/transports.js +118 -0
- package/modules/particles/Particles.js +179 -0
- package/modules/particles/effect.js +112 -0
- package/modules/particles/shaders.js +28 -0
- package/modules/photo/Photo.js +146 -0
- package/modules/rigid/RigidBodies.js +265 -0
- package/modules/rigid/Vehicles.js +97 -0
- package/modules/rigid/sync.js +158 -0
- package/modules/settings/Settings.js +297 -0
- package/modules/settings/apply.js +21 -0
- package/modules/settings/index.js +3 -0
- package/modules/settings/sections.js +156 -0
- package/modules/settings/strings.js +53 -0
- package/modules/settings/view.js +65 -0
- package/modules/sky/Sky.js +259 -0
- package/modules/sky/calendar.js +80 -0
- package/modules/sky/cascades.js +125 -0
- package/modules/sky/clouds.js +79 -0
- package/modules/sky/domeLayers.js +33 -0
- package/modules/sky/environment.js +141 -0
- package/modules/sky/fog.js +139 -0
- package/modules/sky/frame.js +77 -0
- package/modules/sky/layers.js +69 -0
- package/modules/sky/look.js +51 -0
- package/modules/sky/lookFog.js +80 -0
- package/modules/sky/lookShadow.js +50 -0
- package/modules/sky/lookSky.js +108 -0
- package/modules/sky/schedule.js +80 -0
- package/modules/sky/shader.js +96 -0
- package/modules/sky/shadow.js +74 -0
- package/modules/sky/skyModule.js +60 -0
- package/modules/terrain/ChunkManager.js +260 -0
- package/modules/terrain/chunkJob.js +19 -0
- package/modules/terrain/chunkLevels.js +40 -0
- package/modules/terrain/chunkQueries.js +42 -0
- package/modules/terrain/chunkWorker.js +5 -0
- package/modules/terrain/index.js +118 -0
- package/modules/terrain/lookGround.js +61 -0
- package/modules/terrain/mountTerrain.js +32 -0
- package/modules/terrain/terrainColorMap.js +41 -0
- package/modules/terrain/terrainDefaults.js +39 -0
- package/modules/terrain/terrainEdit.js +139 -0
- package/modules/terrain/terrainGen.js +155 -0
- package/modules/terrain/terrainIsland.js +131 -0
- package/modules/terrain/terrainMesh.js +92 -0
- package/modules/terrain/terrainShape.js +108 -0
- package/modules/terrain/terrainShapeMain.js +41 -0
- package/modules/terrain/terrainTexture.js +44 -0
- package/modules/timeline/Timeline.js +253 -0
- package/modules/timeline/Tween.js +114 -0
- package/modules/timeline/letterbox.js +24 -0
- package/modules/timeline/shots.js +90 -0
- package/modules/triggers/index.js +268 -0
- package/modules/vegetation/Vegetation.js +256 -0
- package/modules/vegetation/groundChunks.js +177 -0
- package/modules/vegetation/index.js +43 -0
- package/modules/vegetation/lookWind.js +37 -0
- package/modules/vegetation/modelGeometry.js +21 -0
- package/modules/water/Water.js +160 -0
- package/modules/water/look.js +80 -0
- package/modules/water/surface.js +88 -0
- package/modules/weather/Weather.js +242 -0
- package/modules/weather/look.js +75 -0
- package/modules/weather/particles.js +92 -0
- package/modules/weather/shaders.js +49 -0
- package/modules/weather/strings.js +15 -0
- package/modules/world/World.js +231 -0
- package/modules/world/cells.js +42 -0
- package/modules/world/explain.js +11 -0
- package/modules/world/index.js +71 -0
- package/modules/world/persist.js +107 -0
- package/modules/world/pos.js +20 -0
- package/modules/world/records.js +89 -0
- package/modules/world/sim.js +175 -0
- package/modules/world/simFar.js +82 -0
- package/modules/world/state.js +115 -0
- package/modules/world/thingSource.js +44 -0
- package/modules/world/views.js +182 -0
- package/package.json +66 -4
- package/presets.js +96 -0
- package/render/PostFX.js +240 -0
- package/render/detail.js +105 -0
- package/render/effects.js +144 -0
- package/render/engineUniforms.js +23 -0
- package/render/fuse.js +84 -0
- package/render/lighting.js +100 -0
- package/render/lights.js +18 -0
- package/render/lookSurface.js +161 -0
- package/render/materials.js +220 -0
- package/render/patches.js +252 -0
- package/render/postLook.js +86 -0
- package/render/surface.js +69 -0
- package/render/uniformDecl.js +29 -0
- package/types/common.d.ts +34 -0
- package/types/core.d.ts +1965 -0
- package/types/gameplay.d.ts +1822 -0
- package/types/generated/core/Audio.d.ts +200 -0
- package/types/generated/core/Batching.d.ts +47 -0
- package/types/generated/core/Budget.d.ts +90 -0
- package/types/generated/core/Commits.d.ts +31 -0
- package/types/generated/core/DebugOverrides.d.ts +52 -0
- package/types/generated/core/Events.d.ts +89 -0
- package/types/generated/core/I18n.d.ts +30 -0
- package/types/generated/core/Input.d.ts +118 -0
- package/types/generated/core/Jobs.d.ts +41 -0
- package/types/generated/core/Ops.d.ts +203 -0
- package/types/generated/core/Random.d.ts +49 -0
- package/types/generated/core/Rays.d.ts +49 -0
- package/types/generated/core/Saves.d.ts +162 -0
- package/types/generated/core/Stream.d.ts +93 -0
- package/types/generated/core/Threads.d.ts +82 -0
- package/types/generated/core/Views.d.ts +33 -0
- package/types/generated/core/audioVoice.d.ts +47 -0
- package/types/generated/core/page.d.ts +18 -0
- package/types/generated/core/session.d.ts +48 -0
- package/types/generated/modules/ambience/Ambience.d.ts +48 -0
- package/types/generated/modules/debug/DebugPanel.d.ts +24 -0
- package/types/generated/modules/flow/index.d.ts +10 -0
- package/types/generated/modules/grid/Grid.d.ts +151 -0
- package/types/generated/modules/grid/Layer.d.ts +65 -0
- package/types/generated/modules/grid/index.d.ts +86 -0
- package/types/generated/modules/hlod/index.d.ts +11 -0
- package/types/generated/modules/hud/index.d.ts +10 -0
- package/types/generated/modules/lights/index.d.ts +13 -0
- package/types/generated/modules/music/Music.d.ts +111 -0
- package/types/generated/modules/net/Net.d.ts +34 -0
- package/types/generated/modules/net/index.d.ts +53 -0
- package/types/generated/modules/net/transports.d.ts +58 -0
- package/types/generated/modules/particles/Particles.d.ts +69 -0
- package/types/generated/modules/sky/Sky.d.ts +145 -0
- package/types/generated/modules/sky/skyModule.d.ts +10 -0
- package/types/generated/modules/timeline/Timeline.d.ts +51 -0
- package/types/generated/modules/water/Water.d.ts +29 -0
- package/types/generated/modules/weather/Weather.d.ts +62 -0
- package/types/generated/modules/world/World.d.ts +242 -0
- package/types/generated/modules/world/index.d.ts +15 -0
- package/types/generated/render/PostFX.d.ts +125 -0
- package/types/generated/render/materials.d.ts +100 -0
- package/types/generated/render/patches.d.ts +41 -0
- package/types/generated/ui/Focus.d.ts +11 -0
- package/types/generated/ui/LoadingScreen.d.ts +2 -0
- package/types/generated/ui/UI.d.ts +57 -0
- package/types/nav.d.ts +52 -0
- package/types/physics.d.ts +592 -0
- package/types/style.d.ts +638 -0
- package/types/worker.d.ts +11 -0
- package/types/world.d.ts +772 -0
- package/ui/Focus.js +51 -0
- package/ui/LoadingScreen.js +42 -0
- package/ui/Parts.js +199 -0
- package/ui/UI.js +167 -0
- package/ui/defaults.js +85 -0
- package/ui/theme.js +124 -0
- package/ui/touchPart.js +49 -0
package/docs/COMMANDS.md
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
# Commands and debugging details
|
|
2
|
+
|
|
3
|
+
The scripts in `package.json` forward to the CLI `threedog` (from `@threedog/tools`; the root `build` runs each workspace's own `build`);
|
|
4
|
+
`npm run xxx` and `npx threedog xxx` are equivalent. The tools find every path through their `paths.mjs`, in the engine repository and in a game
|
|
5
|
+
installed from npm alike.
|
|
6
|
+
|
|
7
|
+
## Running one game only
|
|
8
|
+
After `-w` write the directory or the package name (inside a game directory a plain `npm run ...` does the same):
|
|
9
|
+
- Dev: `npm run dev -w games/my-game`, or from the root `npm run dev -- my-game` (part of the name is enough); no name means the engine example. To
|
|
10
|
+
change the port (default 5173; if taken it moves to the next one): `npm run dev -- my-game --port 5000` (the game name must come first, the
|
|
11
|
+
remaining arguments go to vite untouched; don't add another `--`).
|
|
12
|
+
- Test: `npm test -w games/my-game`, or `npm test -- -w my-game`; `npm test` at the root tests every workspace (engine + each game).
|
|
13
|
+
- Build: `npm run build -w games/my-game`; `npm run build` at the root builds all (every *.html in a workspace root is bundled, no change to
|
|
14
|
+
vite.config.js needed).
|
|
15
|
+
- Screenshot / bake / compress models: `npm run shot -- -w my-game / --describe-only` (`--keep` timestamped file name, `--look` pixel numbers), `npm run bake -- -w my-game`, `npm run assets -- -w my-game`.
|
|
16
|
+
- A game's tests: if `games/<game>/tests/specs.mjs` exists it runs; otherwise a smoke test runs automatically (page opens, engine ready, no console
|
|
17
|
+
errors). Minimal example:
|
|
18
|
+
```js
|
|
19
|
+
// games/my-farm/tests/specs.mjs — export a specs array, one entry per page
|
|
20
|
+
export const specs = [{
|
|
21
|
+
name: 'farm: pick up apple', // npm test -- apple matches by name substring
|
|
22
|
+
url: '/?cutscene=skip', // page path + URL parameters
|
|
23
|
+
async run({ page, check, ev, frames, wait }) {
|
|
24
|
+
// ev(fn, arg): runs in the page (engine is available). The function is serialized, so it can't use outer variables; pass them as the argument:
|
|
25
|
+
const n = await ev(id => engine.inventory.count(id), 'apple');
|
|
26
|
+
check('no apple at start', n === 0, `actual ${n}`); // check(label, passed, details on failure)
|
|
27
|
+
await page.keyboard.press('KeyE'); // page is a Playwright page: keys, clicks
|
|
28
|
+
await frames(3); // wait 3 frames of the real-time loop (software rendering is slow; waiting by frames is more reliable than wait(ms))
|
|
29
|
+
check('has apple after pickup', await ev(id => engine.inventory.count(id), 'apple') > 0);
|
|
30
|
+
},
|
|
31
|
+
}];
|
|
32
|
+
```
|
|
33
|
+
Tests run against the built bundle (not the dev server): main.js must set `window.engine = engine;` before `await engine.start()`, otherwise the
|
|
34
|
+
test waits for the engine until timeout (the error explains why).
|
|
35
|
+
- New game: `npm run new-game name`, see `recipes/01-new-game.md`.
|
|
36
|
+
|
|
37
|
+
> Git Bash (MSYS) rewrites arguments that start with `/` (`/styletest.html` turns into a Windows path). Write `shot styletest`, or set `MSYS_NO_PATHCONV=1`, or use PowerShell.
|
|
38
|
+
|
|
39
|
+
## Command table
|
|
40
|
+
| Command | When to use |
|
|
41
|
+
|---|---|
|
|
42
|
+
| `npm run dev` | Development. Browser errors are sent automatically to the terminal and to the workspace's `.threedog/errors.log` (e.g. `games/my-game/.threedog/errors.log`): read that file first when something breaks, before taking screenshots. Known error classes carry `Possible cause: …` and `Read: recipes/…` lines (table `core/errorHints.js`) |
|
|
43
|
+
| `npm run check` | Run after every change (order: if the docs need regenerating `map` -> `check` -> related tests; otherwise `check` -> related tests): hard rules + rule checks (`packages/tools/rules/`; detection and allowlists are at the top of each file; the save round trip is in npm test) + types + content validation + generated docs up to date. `-- --rule R4` runs one rule, `-- --all` lists every warning, `-- -w game` (or `npx threedog check -w game`) checks one game only: its content validation and GAMEMAP freshness (not the engine rules/types; run plain `check` before committing engine changes) |
|
|
44
|
+
| `npm run types` | Type check only (does game code misuse the engine API) |
|
|
45
|
+
| `npm test` | Full browser tests (slow). Normally `npm test -- name` runs only the related ones (matched by test-name substring, e.g. `-- HLOD`), `-- -w game` tests one game. `-- --update-snapshots` makes tests that use `expectDescribe` write their describe baselines (`tests/snapshots/*.describe.json`) instead of comparing. `npm test -- pack` (the build test): after a real build of each game, open only dist from a static server and check that the engine is ready, no 4xx resources, no console errors |
|
|
46
|
+
| `npx threedog snap-describe save|diff name [--only a,b]` | Describe snapshot instead of a screenshot: baseline of the gameplay part of `describe()` (see recipes/16-dev-bridge.md section 7); in tests one line `expectDescribe({ check, ev }, name, { only, tolerance })` from `@threedog/tools/describe-snapshot` |
|
|
47
|
+
| `threedog play` / `play --stop` | Start the game for the AI: starts the dev server if none runs (detached, output in `.threedog/dev.log`), waits for the dev bridge and the engine, prints the page address and whether a headless or a live browser page is connected. `--stop` stops the server play started |
|
|
48
|
+
| `threedog status` | One call: engine ready, loading done, page errors, running / paused / frozen. When the bridge cannot answer it names one of four causes with one next step: no server (`threedog play`), server still starting (wait, status again), page script error (`threedog errors latest`), no dev bridge installed (use `gameConfig`) |
|
|
49
|
+
| `threedog session [--minutes N]` / `session stop` / `session status` | Optional: keeps one small local process alive (127.0.0.1, token, `.threedog/session.json`) so later bridge commands skip module loading (about 0.1 to 0.15 s less per command); exits by itself after N idle minutes (default 10). Every command works the same without it: no session, a dead one or an unreachable one falls back to a direct call. Restart it after editing the tools |
|
|
50
|
+
| `threedog js --file steps.js [--verbose]` | A script that calls `assert(cond, msg)` or `expect(v).toBe/toEqual/toBeCloseTo/toBeGreaterThan(x, msg)` runs as checks in ONE call: globals `engine`, `step(seconds)`, `log(...)`; failed checks are recorded and the script goes on, a throw stops it. Output: `✓ 7 checks passed`, or the failures then `✗ 2 of 7 checks failed`; exit code 1 on failure. `--verbose` adds passes, `log` lines and the return value. A script without those calls is the plain eval |
|
|
51
|
+
| `threedog verify scenario` | Run `tests/scenarios/<scenario>.json` on the running page and print PASS / FAIL, **Tested** (ops with outcomes, describe sections compared, time advanced), **Not tested** (ops never run, sections never compared, steps skipped after a failure, key path, picture), a `Layers:` line (steps by layer: direct = op/describe call, simulated-input = bridge press; real-browser-input is always 0 and printed as not verified, visual 0 because scenario snapshots are describe, not pixels), tests that mention an error code seen, and the `threedog test` command to re-run. A page error during the run fails it. JSON adds `layers` / `layerCounts` / `evidence` (per-check layers, notProven, ops / modules coverage; text: Evidence, NOT proven, Coverage: ops ran/total with refused ones marked, modules tested / indirect / untested, lists capped with "+N more"). `threedog scenario` prints its pass line plus the same Coverage block |
|
|
52
|
+
| `threedog catalog [id] [--find word] [--json]` | What this game can do: modules, ops (args, failure codes, last attempt), saves, time. `recipes/51-capability-catalog.md` |
|
|
53
|
+
| `threedog how "<task>"` | Ranks the AI.md task rows and recipe headings for a task in your own words (also in Chinese). `recipes/51-capability-catalog.md` section 5 |
|
|
54
|
+
| `threedog explain op shop.buy shop=bakery` / `explain quest first-light` | Why an op cannot run now, or what a quest waits on (`engine.explain`). `recipes/23-ops.md` |
|
|
55
|
+
| `threedog thing <id>` | Everything about one id: definition file:line, model, materials, state, ops, save tier, how to change it (`thing.explain()`). `recipes/41-thing-registry.md` section 6 |
|
|
56
|
+
| `threedog content set <id> <field> <json> [--in props] [--dry]` (or `<id> x=12 place=home …`: several fields, one write, one check, all-or-nothing) | Write a permanent change into the content entry. `recipes/41-thing-registry.md` |
|
|
57
|
+
| `threedog loading [task]` | Loading progress and what failed, also while `start()` is stuck. `recipes/05-props-bake.md` |
|
|
58
|
+
| `threedog mcp [--allow-js]` | The dev bridge as an MCP server over stdio. `recipes/16-dev-bridge.md` section 10 |
|
|
59
|
+
| `threedog assets check new.glb --against old.glb` | What the old export had and the new one lacks. `recipes/46-blender-art-route.md` |
|
|
60
|
+
| `threedog shot --view name [--compare before.png]` | A named camera view (`engine.views.define`) and a pixel diff against an earlier picture. `recipes/46-blender-art-route.md` |
|
|
61
|
+
| `threedog skip to=06:00` / `skip seconds=600` | Jump the clock like sleeping (`engine.skip`: op `time.skip`, sky clock and time-keeping modules catch up; optional `fade=0.6 save=auto`). Needs the sky module for `to` |
|
|
62
|
+
| `threedog errors` / `errors latest [N]` / `errors --since E5` | Page errors with id (E1…), time, tick, source and count. Plain `errors` = new since the last read; `latest` = the last N (default 3), same answer every time; `--since` = after an id, never moves the read position. Every result prints a cursor |
|
|
63
|
+
| Result of every bridge command | CLI text ends with one line on the game state and the way back (`Game paused, tick 180: threedog resume restores real-time running`; frozen by a menu says which). MCP adds `structuredContent` { ok, code, summary, runtime { ready, mode running|paused|frozen, tick, headless, blockedBy[] }, data } and an `outputSchema` on every tool. `code`: ok, blocked (ran, refused), not-ready, no-server / starting / page-error / no-bridge (cannot reach the game), command-error. **Advance game time**: step, press, hold, skip, scenario, verify. **No game time**: op, state, eval, js, resume, reload. Everything else only observes. eval / js and describe with a path or --full / --all print no state line (parseable); runtime still has it |
|
|
64
|
+
| `npm run map` | Regenerate CODEMAP, API.md + api/, each game's GAMEMAP and the event-name list (generated from `EventMap` in core.d.ts; add a new event to EventMap first) after changing code, JSDoc or content (run it before `check`) |
|
|
65
|
+
| `npm run shot -- / --time 18:30 --weather rain --pos x,z` | Only when you need to see the picture; by default 1 image of 960x540 into the workspace's .threedog/shots/; **read the state as text first with `--describe-only`**. `/<page>.html` switches the page, `-w game` switches the game, `--wait seconds` advances time |
|
|
66
|
+
| `npm run shot -- styletest --view room --time dusk --weather rain` | The fixed style-judging scene (`examples/styletest`, page `/styletest.html`; a bare name is a page of the workspace). `--view` = a named camera (overview, character, water, room, path, ui), `--time` also takes day / dusk / night, `--weather` clear / rain / snow; same arguments every round, so only the style differs. `--panel` is not a shot option: open `/styletest.html?panel=1` in a browser for the workbench (recipes/35) |
|
|
67
|
+
| `npx threedog capture [page] [--top N] [--no-spector] [--full]` | Find out what a frame draws: renders one steady frame headless and prints draw calls, shadow-map draws, render passes (post effects) and the largest draws with world record id, budget tag and material purpose. Also records the WebGL command stream of that frame with Spector.js (fetched on first use into `.threedog/cache/`, not a dependency) to `.threedog/captures/`; `--no-spector` skips it |
|
|
68
|
+
| `npm run bake` | Before release, or to take code-generated models into Blender: exports public/models/baked/*.glb (`-- -w game`) |
|
|
69
|
+
| `npm run assets` | Compress glTF from art/models/ into public/models/ (names such as col_ and spawn are kept; `-- -w game`). Skips files whose source content, options and tool versions are unchanged. Prints a report per file (sizes, meshes / materials / textures / animations, final texture format, texture transfer size vs GPU memory; also `.threedog/assets-report.json`). `-- --ktx2` makes KTX2 textures; without the ktx tool it falls back to WebP and says so, `-- --ktx2 --strict` fails instead |
|
|
70
|
+
| `npm run assets -- check [glb or folder] [--json] [--strict]` | Inspect models without building (default art/models/): the level manifest (spawns, col_ colliders, trigger_ zones, npcs, markers, template / id nodes, missing templates, duplicate ids), material and color-space suspicions (data texture in a color slot, BLEND, texture without UV, oversized texture), statistics. `--json` for tools, exit 1 on errors (`--strict`: on warnings too). `npm run check` also reads the level glbs for content validation |
|
|
71
|
+
| `npm run perf` | Performance comparison (plain three.js vs engine vs per-module cost in openWorld); compare with `PERF.md` |
|
|
72
|
+
| `npx threedog content ids [-w game \| folder] [--write]` | Stateful content entries (pickups, template instances with state / container / interact / body) that rely on their index id: prints the id each has now as `-`/`+` lines (dry run); `--write` writes them into `content/*.js`. Rename later through `content/renames.js` (recipe 30) | <!-- r18-ignore-line -->
|
|
73
|
+
| `npm run doctor` | Check the environment, one line per item: ✓ passed · ✗ problem -> fix · – info only; `-- --ci` does not fail the command on problems. Checks Node version, node_modules, workspace links, package-lock consistency, `.threedog` writable, the physical copy (real path, version, package.json mtime) of engine / tools / three per context (check, run/build per game; a `MISMATCH` line when contexts use different copies, e.g. vendor/ vs node_modules), port 5173, the dev server recorded in `.threedog/dev.json`, Playwright chromium, headless WebGL2, `EXT_disjoint_timer_query_webgl2` (software rendering normally lacks it; info only). Run it first when the environment acts strange |
|
|
74
|
+
| `npm run new-style name` | New style pack from a clean template (gray neutral materials, sky, one palette, empty post, one palette-colored example model): `packages/styles/<name>`, package `@threedog/style-<name>`, workspace link and lock updated, then `style check`, `map` and `check` run. Lowercase letters, digits and hyphens only |
|
|
75
|
+
| `threedog style check [pack\|folder\|file] [--json] [--assets file]` | Check the final merged style: unknown fields (did-you-mean), world-state fields, palette keys read but not defined, color formats, post-effect conflicts, misspelled material roles / types, asset names the pack does not register; plus R34 for that pack. Exit 1 on errors. Static: it cannot prove a pack has no gameplay logic. See `recipes/35-style-from-reference.md` |
|
|
76
|
+
| `threedog style palette <image> [--n 8] [--average] [--region x,y,w,h] [--ignore-ui] [--crop out.png]` | Dominant colors of a reference picture and a one-line summary (headless Chromium reads the pixels). `--average` adds the mean color (HSL); `--region` measures one rectangle; `--ignore-ui` cuts a flat frame around the picture (edge row / column one flat color, frame 3% to 45% of the picture; a plain sky at the edge looks the same, so check with `--crop out.png`, which saves the measured area). The output says what was measured. A measurement, not a design decision |
|
|
77
|
+
| `threedog style compare <reference> <screenshot> [--region x,y,w,h] [--ref-region ..] [--shot-region ..] [--json]` | Differences as numbers: brightness, saturation, contrast (std of luma), fine detail (variance of the Laplacian of luma; read as a ratio), average and main color (hue / saturation / lightness), plus one neutral sentence ("18% darker, 2.3x more broken up"). Both pictures are scaled to one size and the note says so. **An aid to judging, not a replacement for looking; no number is a quality score and there is no "similarity %".** recipes/35 |
|
|
78
|
+
| `threedog scene [--hidden] [--limit N] [--json]` | **The mesh exists but is not drawn: use this first** (needs the running game). Lists every Mesh / Points / Line / Sprite and for each undrawn one every reason, most likely first: `visible = false` on it or a parent, layers vs camera, material flags, scale 0 / NaN, NaN position or vertices, empty geometry, behind the camera, beyond `camera.far`, outside the view. "maybe" reasons (depthWrite off, fully fogged...) do not stop drawing. `--hidden` = only undrawn; default limit 40. Code: `engine.inspect.scene()`; MCP tool `scene`. Cannot see shader output |
|
|
79
|
+
| `npm run build` | Bundle each workspace into its own dist/ |
|
|
80
|
+
|
|
81
|
+
## Reproducing a scenario and debugging
|
|
82
|
+
- Add `?time=18:30&weather=rain&pos=40,-20&save=slot1&cutscene=skip&state=name` to the URL (effective in development).
|
|
83
|
+
- In the console / tests: `engine.describeText()` reads the state as English text; `engine.step(seconds)` fast-forwards synchronously (no rendering);
|
|
84
|
+
`engine.pause()` stops the real-time loop.
|
|
85
|
+
- To wait for the page: `page.waitForFunction(() => window.engine?.stateApplied)` (start has finished and all URL parameters are applied); never read
|
|
86
|
+
`_`-prefixed private fields. When the dev bridge / `npm test` / `npm run shot` cannot reach the engine (no `window.engine` after 40 seconds, or it
|
|
87
|
+
exists but never becomes ready), the error states the page status, the latest page errors and the fix.
|
|
88
|
+
- Advancing dialogue headlessly: `engine.step(1)` lets the typing finish, then press a number key or run
|
|
89
|
+
`engine.ops.run('dialogue.choose', { index: i })` (while typing it completes the sentence first).
|
|
90
|
+
- Debug objects on window: `window.engine = engine` is already declared; for a game's own, write `/** @type {any} */ (window).game = {...}`
|
|
91
|
+
(`npm run types` reports properties on window as web hints, not errors).
|
|
92
|
+
- To operate a running game use the dev bridge, see `recipes/16-dev-bridge.md`.
|
|
93
|
+
|
|
94
|
+
## Folder guide (inside packages/engine)
|
|
95
|
+
- `core/` core: Engine (main loop, ground, step/describe), Events Input Saves Assets Audio I18n Clock Vars Jobs Stream Rays Budget UrlState Animator.
|
|
96
|
+
- `modules/` modules, one folder each, installed with `engine.use`; list in `CODEMAP.md`.
|
|
97
|
+
- `render/ ui/` material factory, post-processing; UI basics (windows, UI focus stack, toast, fadeScreen, worldToScreen).
|
|
98
|
+
- `index.js index.d.ts types/` entry and API declarations (`types/generated/` is generated from source JSDoc, never edited by hand).
|
|
99
|
+
- `packages/styles/lowpoly/` (`@threedog/style-lowpoly`, optional; the engine ships no art) the lowpoly package: `index.js` holds the style pack (all
|
|
100
|
+
look parameters) and exports the asset pack `assets`, `models.js` the procedural models in it, `shapes.js` the default humanoid and pickup shapes,
|
|
101
|
+
The bloom / outline / ao effects are in `packages/post-effects/` (`@threedog/post-effects`). The terrain preset `terrainPreset()` is a separate package, `packages/terrain-noise/` (`@threedog/terrain-noise`).
|
|
102
|
+
- `examples/world/` is the engine example (open world `/`, content-only placement). The small city (level, no terrain, no style pack, top-down) and
|
|
103
|
+
the co-op page are test pages in the engine repository (`tests/city/`, `tests/coop/`), opened at `/tests/city/index.html` and `/tests/coop/index.html`.
|
|
104
|
+
- `tests/` specs.mjs + specs/ test list, `<name>/index.html` test pages, fixtures/ test assets. `public/` art for the examples.
|
|
105
|
+
- Each game `games/<game>/`: package.json, vite.config.js (one line, gameConfig), index.html, main.js, `content/` (items npcs dialogues quests pickups
|
|
106
|
+
containers props templates triggers actions places level vegetation audio grids renames rules, plus the game's own kinds registered in
|
|
107
|
+
`content/rules.js`; only these file names are read), `public/` (art; Blender source files go in `art/models/`), DESIGN.md, GAMEMAP.md (generated), CLAUDE.md.
|
|
108
|
+
- Each workspace has its own `.threedog/` (browser error log errors.log, screenshots shots/, generated cache) and `dist/`; neither is committed.
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
# Additional conventions (read when the task is relevant)
|
|
2
|
+
|
|
3
|
+
For API details see `api/<module>.md`; this file holds conventions that don't belong to one API but cause problems when broken. `AI.md` lists each in
|
|
4
|
+
one line; the detail is here.
|
|
5
|
+
|
|
6
|
+
## World data and level ownership
|
|
7
|
+
- **World data**: game objects that must be saved, survive level changes, or change while far away go in `engine.world` (the model is built with
|
|
8
|
+
`present` only when near, the simulation runs with `simulate`).
|
|
9
|
+
Items written in content use `add(def, { initial: true })` (an id is required; a save records only changes and deletions, independent of the order
|
|
10
|
+
relative to content.load); items generated at runtime use a plain `add`; temporary ones use `{ save: false }`;
|
|
11
|
+
discrete changes use `world.set` (it emits world:change), things that change every step modify the field directly or use `move`. Usage is in `api/world.md`.
|
|
12
|
+
- **Level ownership**: world data carrying `zone: engine.world.zone` (= the current level name) gets its model built and is simulated only in that
|
|
13
|
+
level; when you leave, the data stays (content NPCs, pickups and props already work this way);
|
|
14
|
+
things that need not be kept (trigger zones, etc.) use `level.track(handle)` and are deleted automatically on level change.
|
|
15
|
+
- **Two doors, one scene**: plain three.js (`engine.add(mesh, { id })`) and templates (`engine.spawn`, props) land in the same registry;
|
|
16
|
+
`engine.thing(id)` says what it is and what a save keeps (`recipes/41-thing-registry.md`). What must be saved with its own state or edited without
|
|
17
|
+
code goes in `content/` (templates + props with ids, pickups, npcs, containers, game kinds) or the level model; a save stores only changes on top.
|
|
18
|
+
Startup code never creates what a save stores whole (rule R33): things that appear during play come from `engine.spawn` inside an op.
|
|
19
|
+
- To find leaks read `engine.counts()` (listeners, timers, geometry count; they should not grow when entering and leaving a level repeatedly).
|
|
20
|
+
|
|
21
|
+
## Textures
|
|
22
|
+
The opts of `assets.texture(name, opts)` are part of the cache key: the same image with different opts gives two separately configured textures.
|
|
23
|
+
|
|
24
|
+
## Adjusting sky brightness
|
|
25
|
+
The engine overwrites `sky.sun / sky.hemi` (intensity, color, position), `scene.fog` and the `camera` pose every frame; don't set them directly.
|
|
26
|
+
Change the light through `engine.look.lights` / `engine.look.fog` (overrides), or `engine.sky.modify` for a layer that multiplies the sky's own output
|
|
27
|
+
(which to pick: `recipes/52-look.md`). Take over the camera with `engine.takeCamera(owner)` (or a timeline camera step).
|
|
28
|
+
|
|
29
|
+
## Owners
|
|
30
|
+
Everything that holds the engine is named by an owner, and only that owner releases it. Positional `pause('menu')` and `pause({ owner: 'menu' })` are the same.
|
|
31
|
+
|
|
32
|
+
| What | Take | Release | Returns |
|
|
33
|
+
|---|---|---|---|
|
|
34
|
+
| Real-time loop | `pause(owner, { kind? })` | `resume(owner)` | handle `{ remove() }` |
|
|
35
|
+
| Gameplay freeze | `freeze(owner, { kind? })` | `unfreeze(owner)` | handle |
|
|
36
|
+
| Camera | `takeCamera(owner, { focus? })` | `handle.remove()` | handle |
|
|
37
|
+
| Debug override / view | `debug.override(owner, ...)`, `debug.view(mode, { owner })` | `debug.clear(owner)` | handle / state |
|
|
38
|
+
| Look values | `look.<part>.set(values, { owner })` | `look.<part>.clear(owner)` | handle |
|
|
39
|
+
|
|
40
|
+
## Worker limits
|
|
41
|
+
`modules/terrain/terrainGen.js` (via `chunkJob.js`) runs in a Worker and must not import three.js; a vegetation `rule` is sent to the Worker and must
|
|
42
|
+
not contain functions.
|
|
43
|
+
Workers are created only through `engine.threads.lane({ create, local })` (the same handler runs on the main thread when there are no workers); no
|
|
44
|
+
`new Worker` / `postMessage` elsewhere (`npm run check` rule R19). Worker files import only worker-safe code (a game:
|
|
45
|
+
`import { serve } from 'threedog/worker'`; inside the engine `core/threadServe.js`, `core/threadPure.js`), never `core/Threads.js` or three.js.
|
|
46
|
+
|
|
47
|
+
### Worker results that change gameplay: `engine.commits`
|
|
48
|
+
A result that changes gameplay never takes effect "when it arrives"; it takes effect on a fixed tick decided when you ask (`engine.tick + lag`,
|
|
49
|
+
default 30 steps), so threads on or off, fast or slow machine, give the same state.
|
|
50
|
+
```js
|
|
51
|
+
const t = engine.commits.request({
|
|
52
|
+
apply: r => { state.path = r; }, // runs on the due tick, with the worker result or the fallback result
|
|
53
|
+
fallback: () => computePath(from, to), // required: the SAME computation on the main thread
|
|
54
|
+
valid: () => state.gen === myGen, // still wanted? checked on the due tick
|
|
55
|
+
});
|
|
56
|
+
lane.run(job).then(r => t.resolve(r)); // when the worker replies; t.remove() if you no longer want it
|
|
57
|
+
```
|
|
58
|
+
- **The worker result has not come back by the due tick**: the main thread calls `fallback()` right then, `apply` gets that result, and
|
|
59
|
+
`engine.commits.stats.late` goes up by 1. A worker reply that arrives afterwards is ignored. So `fallback` must give the same result as the worker
|
|
60
|
+
(use one function for both) and must be fast enough to run inside one fixed step.
|
|
61
|
+
- **Dropping an old result**: `t.remove()`, or `valid()` returning false on the due tick. A save load (`saves.apply`) or `level.load` drops pending
|
|
62
|
+
commits that have no `valid` (they were requested for the old world), including `jobs.add(work, { apply })` started before it (`jobs.add` also takes
|
|
63
|
+
`valid`); a request with `valid` decides itself.
|
|
64
|
+
|
|
65
|
+
### Pure functions for workers: `engine.threads.pure(fn, label)`
|
|
66
|
+
A function sent to a worker (`world.simulate(kind, { far, worker: true })`, your own lane) is sent as source text and recompiled in an empty scope. So
|
|
67
|
+
it **cannot use outside variables, `this` or imports**, and cannot be native, bound, a class, `async` or a generator; it may use its parameters,
|
|
68
|
+
constants written inside it, and globals such as `Math`. The main thread runs the same recompiled copy, so a mistake fails the same way with threads on or off.
|
|
69
|
+
```js
|
|
70
|
+
const RATE = 1 / 600;
|
|
71
|
+
// wrong: RATE is an outside variable -> ReferenceError "RATE is not defined" (message says to put it inside)
|
|
72
|
+
engine.world.simulate('crop', { far: (rec, dt) => { rec.growth += dt * RATE; }, worker: true });
|
|
73
|
+
// right: the constant lives inside, or on the record (rec.rate)
|
|
74
|
+
engine.world.simulate('crop', { far: (rec, dt) => { rec.growth = Math.min(1, rec.growth + dt / 600); }, worker: true });
|
|
75
|
+
```
|
|
76
|
+
What is checked when: at registration (`threads.pure` / `simulate`) it checks that the function can be recompiled (not native, not async, parseable).
|
|
77
|
+
Outside variables are also scanned at registration and reported by name with the fix (a heuristic scan: it may miss a few forms such as variables
|
|
78
|
+
inside template strings, which then throw on the first call).
|
|
79
|
+
|
|
80
|
+
## Interface conventions (one style across the engine)
|
|
81
|
+
- **A position is one argument**: any API that takes a position takes it as a single argument: Vector3, Object3D (its position), `[x, y, z]` or
|
|
82
|
+
`{ x, z }` all work. Size, radius and count go in the options object after it: `collision.addBox(house, { halfWidth: 3, halfDepth: 2 })`,
|
|
83
|
+
`particles.emit('dust', p, { count: 20 })`, `entities.nearest(p, { radius, type })`. A position key inside an options object is always `position`
|
|
84
|
+
(`stream.add({ position, build })`). The only exceptions are ground sampling `engine.surface / slope / groundType / waterAt(x, z)` and
|
|
85
|
+
`ground.height(x, z)`; `{ place, x, z }` in content data is a data form.
|
|
86
|
+
- **Registrations return a handle**: anything that registers a listener, timer, continuing effect or registration (`events.on/once`,
|
|
87
|
+
`onFixed/onFrame`, `clock.after/every`, `sky.at/between/daily/onSeason`, `collision.addBox/...`, `interactions.add`, `rays.addStatic`, `stream.add`,
|
|
88
|
+
`triggers.add`, `hud.marker`, `hlod.add`, `particles.attach`, `inventory.spawnPickup`, `rigid.addBox/...`) returns a handle; `h.remove()` undoes it
|
|
89
|
+
(safe to call repeatedly), never a bare function. `remove()` undoes what that call did: models it created itself are deleted with it (such as a
|
|
90
|
+
pickup); objects you passed in are not. APIs that add an object or change business data return what their own signature says: `engine.add(obj)`
|
|
91
|
+
returns the added object, `inventory.add` returns a result, `world.add` a record; delete those with `engine.remove(obj)` / their own remove call.
|
|
92
|
+
- **Ready is always the boolean property `ready`** (to wait, `await h.whenReady`); a module's readiness hook is `isReady(e)`.
|
|
93
|
+
- **Event names are `noun:action`**: the noun is the emitter's singular camelCase name (`item`, `entity`...), the action is a lowercase verb or state
|
|
94
|
+
(`add`, `done`, `change`); a game's own events follow the same rule (`door:open`).
|
|
95
|
+
- **Time**: two fixed names, **fixed seconds** (the `dt` of `onFixed` and module hooks, `step(N)`, `engine.elapsed`; not multiplied by the time scale)
|
|
96
|
+
and **game seconds** (`engine.clock.now` = fixed seconds x `clock.timeScale`); sky time of day `engine.sky.timeOfDay` (0-1) is derived from game
|
|
97
|
+
seconds. Which one to use for movement, action timelines, cooldowns, hit-stop, crop growth, calendar and UI, and what pause / freeze /
|
|
98
|
+
`timeScale = 2` do to each: the table in `recipes/06-clock-events.md` (the only place that lists them).
|
|
99
|
+
- **Input**: gameplay keys (attack, jump, interact...) are read in the fixed step (`onFixed` / module `fixed`), where `pressed / down / released` give
|
|
100
|
+
a snapshot taken at the start of the step, so the result does not depend on frame rate and a press is never lost. UI keys (menus, toggling a view, a
|
|
101
|
+
HUD button) are read in `onFrame` / module `frame`, which gives this frame's latest state. Never read `pointer.clicked` for gameplay; bind a `Mouse0` action.
|
|
102
|
+
- **Module names**: `collision()` installs as `engine.collision` (lightweight collision: walking, camera); `rigid()` installs as `engine.rigid` (real
|
|
103
|
+
physics with Rapier).
|
|
104
|
+
- **Presets**: `openWorld()` installs only world, environment and basic modules; gameplay modules (interactions, dialogue, inventory, quests...) are
|
|
105
|
+
added by the game with `engine.use`; pass `false` for items you don't want; the camera has no default and must be named, e.g.
|
|
106
|
+
`openWorld({ camera: 'firstPerson' })` (`'follow'` / `'rts'` / `'fixed'`, a camera module, or `false`).
|
|
107
|
+
- **Errors say how to fix it**: passing an old form (a numeric position, etc.) throws and explains the fix.
|
|
108
|
+
|
|
109
|
+
## Core conventions
|
|
110
|
+
- Lighting without `sky`: every engine has `engine.lights = { sun, hemi }` (neutral); to light the scene yourself hide or adjust them and add three.js
|
|
111
|
+
lights. The engine ships no art: the humanoid, pickup shapes and flat shading live in the optional lowpoly style pack (`@threedog/style-lowpoly`:
|
|
112
|
+
`shapes.js`, `terrain.config.shading: 'flat'`); without a style pack or model the engine shows a gray capsule, a gray box and flat gray ground at y
|
|
113
|
+
= 0, with a dev warning naming the fix.
|
|
114
|
+
- Gameplay state (world, containers, vars, quests) changes only in fixed steps or inside ops; dev warns otherwise (`.threedog/ops-guard.log` after
|
|
115
|
+
`npm test`). (game side)
|
|
116
|
+
- **One source for "can walk there"**: `createEngine({ movement: { radius, height, maxSlope, stepHeight } })` -> read-only `engine.movement`;
|
|
117
|
+
collision, the Rapier capsule, navigation, A* and level steps all read it; don't write another 0.4 / 0.45 in a module. A character's position
|
|
118
|
+
belongs to the Character mover; other systems only request movement (`placeAt` / `move` / vehicle `enter`) and never set `player.position` directly.
|
|
119
|
+
- Units are meters, Y is up, north is -Z. Characters and vehicles face the model's +Z; `facing` 0 = +Z, forward = (sin f, cos f).
|
|
120
|
+
- Never call `requestAnimationFrame` or `renderer.render` yourself. **Game logic always uses fixed seconds or game seconds** (the hook's `dt`,
|
|
121
|
+
`engine.clock`; see the time table in `recipes/06-clock-events.md`); no `setTimeout` / `setInterval` / `performance.now()`: they ignore pause,
|
|
122
|
+
freeze and `engine.step` fast-forward, so they can't be tested or saved.
|
|
123
|
+
- To be saved, call `engine.saves.register(key, { save, load })` (`load` may return a Promise); `saves.save / load` always return `Promise<boolean>`,
|
|
124
|
+
so `await` them. Saved data names things by stable ids, never positions; when it changes shape raise `version` and add a `migrate` step
|
|
125
|
+
(`recipes/20-content-actions-save.md` "Save format").
|
|
126
|
+
- Day / night comes only from sky: read `sky.isDay`, use `sky.daylight` (0-1) for fades; don't judge by clock time yourself.
|
|
127
|
+
- A game's own look parameters (colors, materials) belong in its style pack (`style`) or the content, never hard-coded into logic.
|
|
128
|
+
- Whatever a style pack provides as a factory can also be passed at the call site, and the call site wins (`new Character(e, { rig })` over `style.character.create`; `spawnPickup(item, pos, { mesh })` over `style.pickup.model`); look-driven parts (sky, clouds, water, materials) are overridden with `engine.look.<part>.set / patch / replace`. A new style factory must ship with its call-site option.
|
|
129
|
+
- Vegetation `rule` must not contain functions (it is sent to a Worker).
|
|
130
|
+
- Terrain is editable: `engine.terrain.edit(pos, { lower|raise|flatten|paint })`, only inside an op or fixed step; custom
|
|
131
|
+
`terrain({ height, groundType })` must be pure functions.
|
|
132
|
+
- Loading follows the `engine.stream` sources (player + camera focus by default); display, physics and world data are separate: unloading a model
|
|
133
|
+
never removes its world record.
|
|
134
|
+
- Window blur, tab hidden, pointer lock and WebGL context loss are listened to only in `core/page.js`; modules read `engine.page` or listen to
|
|
135
|
+
`page:*`. Show "saved" only after `saves.save` returns true.
|
|
136
|
+
- Characters can name their model by asset: `style.character.model: 'hero'` or `createPlayer({ ...presets.player.thirdPerson, model: 'hero' })` builds
|
|
137
|
+
now with the placeholder body and swaps in the registered asset when it loads (`await player.whenReady`, event `character:model`); a name missing
|
|
138
|
+
from a registered manifest throws.
|
|
139
|
+
- Importing the engine makes `Mesh.prototype.customDepthMaterial` / `customDistanceMaterial` default to a depth material carrying the mesh material's
|
|
140
|
+
vertex patches, so wind-swayed meshes cast swaying shadows with nothing to set up; assigning your own value still wins. Shader time, wind and cloud
|
|
141
|
+
cover are per engine in `engine.uniforms` (share them in your own `ShaderMaterial`); with two engines on a page, pass the engine to
|
|
142
|
+
`makeMaterial(role, params, engine)`.
|
|
143
|
+
|
|
144
|
+
## Failures: which shape
|
|
145
|
+
A runtime "can't" (not enough money, shelf empty) is returned as `{ ok: false, code, facts, nextActions }` (ops.run / can / undo). Misuse (a wrong call, a typo) is a thrown `codedError`. Documented exceptions: `checkSkip` / `checkSave` return `{ ok, diffs }`, `walkTo` returns `{ status }`. Read `code`; `reason` is a deprecated alias of it until 1.0.
|
package/docs/PERF.md
ADDED
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
# Performance comparison (PERF)
|
|
2
|
+
|
|
3
|
+
> Numbers come from a cloud environment without a GPU (Chromium + SwiftShader software rendering, 1280x720, pixel ratio 1). Use them only for
|
|
4
|
+
**relative comparison**; they do not represent real-device frame rates.
|
|
5
|
+
> Reproduce: `node packages/tools/perf.mjs [frames]` (default 60 frames; it builds first, then opens
|
|
6
|
+
> `packages/engine/tests/perf/index.html` in a headless browser; both are in the engine repository, not the npm package).
|
|
7
|
+
> Startup time is also printed in the "startup time" item of `npm test` (reported only, no threshold).
|
|
8
|
+
> **Latest run (2026-10-30, wrap-up)**: cloud container with a 2-core CPU and 7 GB memory, no GPU; `npm run perf` (60 frames) run alone (not at the
|
|
9
|
+
same time as `npm test`).
|
|
10
|
+
> This machine is about 1.5-2x slower overall than the one behind the old numbers (the same plain three.js scene takes 9.6-12.2 ms, the old one 9.9
|
|
11
|
+
ms); compare across runs only through relations within the same run. Old numbers are kept in the "previous run" rows of each table.
|
|
12
|
+
|
|
13
|
+
## 0. Real-device baseline
|
|
14
|
+
|
|
15
|
+
Measured 2026-10-31 on the open-world example, before the stage 2 changes, with the in-game F3 panel "20-second stress test" (view distance 256 m, density 1x).
|
|
16
|
+
|
|
17
|
+
| Machine | Avg fps | 1% low fps | Longest frame | Chunks generated during the run |
|
|
18
|
+
|---|---|---|---|---|
|
|
19
|
+
| AMD Ryzen 7 **integrated GPU** (desktop), browser not recorded | 60.0 (vsync cap) | 53.8 | 21.0 ms | 6366 |
|
|
20
|
+
|
|
21
|
+
The average is capped by the display refresh rate, so this shows headroom exists, not how much. Not yet measured: the same machine's discrete GPU (RTX
|
|
22
|
+
5060), `npm run perf` on this machine, phones and laptop integrated GPUs.
|
|
23
|
+
|
|
24
|
+
## How it was measured
|
|
25
|
+
|
|
26
|
+
- Test page (engine repository) `packages/engine/tests/perf/index.html?mode=...`:
|
|
27
|
+
- `native`: plain three.js, 2000 cubes (shared geometry and material) + a ground + 1 directional light with shadows (2048 pixels, covering +-70 m) +
|
|
28
|
+
a hemisphere light, `renderer.render` every frame.
|
|
29
|
+
- `engine`: the same scene inside `createEngine()` (**no modules installed**), running the same sequence as the real-time loop each frame: fixed
|
|
30
|
+
step -> frame hooks (including stream/jobs) -> render -> budget sampling -> afterRender.
|
|
31
|
+
- `world`: `openWorld()` plus the gameplay modules it used to bundle (interactions, dialogue, inventory, quests, timeline, triggers, entities,
|
|
32
|
+
particles, hud; debug panel, music and ambience off), with the same seed, the same flat ground and the same vegetation as the open-world example,
|
|
33
|
+
without NPCs/quests or other content; `engine.profile()` times `fixed/frame/afterRender` for each module.
|
|
34
|
+
- `props`: `n` repeated props over 4 models placed through `world.present`, with a directional shadow; `batch=0` turns `engine.batching` off (section 3c).
|
|
35
|
+
- `city`: used by the C group of feature tests (HLOD, scenario parameters, settings freeze); not timed.
|
|
36
|
+
- Shadows: `renderer.shadowMap.render` is wrapped to count "how many times shadows were really updated" and the draw calls per update.
|
|
37
|
+
- Each item runs 3 times and the median is taken; native/engine alternate for two rounds, and every page uses a freshly opened browser (the
|
|
38
|
+
software-rendering GPU process carries the backlog of the previous page into the next; the first version of the script did not do this and the same
|
|
39
|
+
item varied 2x).
|
|
40
|
+
|
|
41
|
+
## 1. Plain three.js vs engine (no modules), 60 frames
|
|
42
|
+
|
|
43
|
+
| | CPU ms/frame | Render ms/frame | Draw calls | Triangles | Shadow draw calls |
|
|
44
|
+
|---|---|---|---|---|---|
|
|
45
|
+
| Plain three.js (round 1) | 9.55 | 9.55 | 3723 | 44666 | 1848 |
|
|
46
|
+
| Engine (round 1) | 9.87 | 9.81 | 3723 | 44666 | 1848 |
|
|
47
|
+
| Plain three.js (round 2) | 12.2 | 12.2 | 3723 | 44666 | 1848 |
|
|
48
|
+
| Engine (round 2) | 10.95 | 10.89 | 3723 | 44666 | 1848 |
|
|
49
|
+
| Previous run: plain three.js (two rounds) | 9.98 / 9.88 | | | | |
|
|
50
|
+
| Previous run: engine (two rounds) | 9.67 / 9.89 | | | | |
|
|
51
|
+
|
|
52
|
+
Between the two rounds plain three.js itself differs by 2.6 ms (software-rendering noise), and the engine falls between the two plain rounds.
|
|
53
|
+
Conclusion: draw calls and triangles are identical; the engine core's per-frame cost beyond rendering is about 0.05 ms (fixed step, frame hooks,
|
|
54
|
+
jobs/stream, budget sampling returns immediately when off), within measurement error. The engine adds no extra draws (with bloom/ambient occlusion
|
|
55
|
+
off, PostFX renders directly).
|
|
56
|
+
|
|
57
|
+
## 2. openWorld fully on, per-module cost per frame (60 frames, player moving forward at 6 m/s)
|
|
58
|
+
|
|
59
|
+
Whole frame 3.99 ms, of which rendering (submitting draw commands) 2.97 ms; 74 draw calls, 67k triangles (previous run: whole frame 1.84 ms, rendering
|
|
60
|
+
1.38 ms, 66 draw calls, 84k triangles).
|
|
61
|
+
|
|
62
|
+
| Module | ms/frame (this run) | Previous run |
|
|
63
|
+
|---|---|---|
|
|
64
|
+
| rigid (Rapier physics) | 0.56 | 0.23 |
|
|
65
|
+
| sky | 0.12 | 0.02 |
|
|
66
|
+
| cameraRig | 0.09 | 0.03 |
|
|
67
|
+
| terrain (chunk streaming, LOD, frustum) | 0.04 | 0.06 |
|
|
68
|
+
| weather | 0.02 | < 0.01 |
|
|
69
|
+
| characters / interactions / particles | 0.01 each | < 0.01-0.01 |
|
|
70
|
+
| triggers, entities, quests, timeline, water, dialogue, settings, hud, inventory | 0 | < 0.01 |
|
|
71
|
+
|
|
72
|
+
(photo is no longer installed by openWorld by default, so it is not in the table.)
|
|
73
|
+
Conclusion: module logic totals about 0.9 ms/frame (a quarter of the frame), and the biggest part is still Rapier; every item rose together with the
|
|
74
|
+
slower whole frame (slower machine), and no single module became slower.
|
|
75
|
+
particles: group X once measured 0.21 ms/frame, and this run alone it is 0.01. The world scene has no particle effects (no emit/attach); particles per
|
|
76
|
+
frame only computes one point-size ratio and then iterates an empty effect table,
|
|
77
|
+
so it cannot cost 0.2 ms; that was noise from competing for CPU with another process (the full test run), not a regression, and no code was changed.
|
|
78
|
+
The real cost is in rendering (on real devices mostly the GPU, which cannot be measured here).
|
|
79
|
+
|
|
80
|
+
## 3. Shadow parameter comparison (openWorld, 60 frames, player moving forward at 6 m/s)
|
|
81
|
+
|
|
82
|
+
| updateEvery | snap | Shadow updates | Draw calls per shadow | CPU ms/frame | Render ms/frame |
|
|
83
|
+
|---|---|---|---|---|---|
|
|
84
|
+
| 1 (default) | 0.5 (default) | 60/60 | 27 | 2.17 | 1.74 |
|
|
85
|
+
| 3 | 0.5 | 20/60 | 27 | 1.56 | 1.14 |
|
|
86
|
+
| 1 | 'texel' | 60/60 | 27 | 2.53 | 1.93 |
|
|
87
|
+
| 3 | 'texel' | 21/60 | 27 | 1.00 | 0.75 |
|
|
88
|
+
|
|
89
|
+
- `updateEvery: 3` cuts shadow drawing from 60 to 20 times per second (in this scene 27 draw calls each time -> about 1080 fewer draws per second).
|
|
90
|
+
The difference in the CPU column is hidden by software-rendering noise (the same configuration can differ by 0.5 ms between two runs), so rely on
|
|
91
|
+
"shadow updates x draw calls per update".
|
|
92
|
+
- Early update while moving: only when the shadow center is more than 1/4 of the coverage radius away from the last update point (default 17.5 m;
|
|
93
|
+
teleporting or fast movement) is the update brought forward. The first version updated "whenever the snapped cell changed", and with 'texel' (cell
|
|
94
|
+
only 0.07 m) it updated almost every frame (27/30), which saves nothing; that was changed.
|
|
95
|
+
- `snap: 'texel'` does not save performance by itself; it keeps shadow edges from flickering while moving (aligned to shadow pixels).
|
|
96
|
+
|
|
97
|
+
## 3b. HLOD (`npm test -- HLOD`, test block of 7x7 buildings + ground)
|
|
98
|
+
|
|
99
|
+
With the focus at the block center: 93 draw calls (including shadows); with the focus moved 400 m away and everything switched to proxies: 16; moving
|
|
100
|
+
back restores 93.
|
|
101
|
+
|
|
102
|
+
## 3c. Automatic batching (engine.batching), 2026-10-31
|
|
103
|
+
|
|
104
|
+
`npm run perf -- --only=props`: 3000 repeated props over 4 models (a lamp of 2 meshes, a fence, a crate, an AC unit; 3750 meshes), each a world record
|
|
105
|
+
presented as a clone of its model, spread over about 143 x 143 m (16 cells of 64 m), one directional light with shadows, 60 frames, headless Chromium
|
|
106
|
+
with ANGLE SwiftShader
|
|
107
|
+
on the user's Windows machine (perf.mjs now launches with `--use-angle=swiftshader`: plain `--use-gl=swiftshader` no longer starts WebGL there, which
|
|
108
|
+
is why section 5 shows 0 draw calls).
|
|
109
|
+
|
|
110
|
+
| | CPU ms/frame | Render ms/frame | Draw calls (incl. shadow) | Shadow draw calls | Batches | Instances |
|
|
111
|
+
|---|---|---|---|---|---|---|
|
|
112
|
+
| batching off (round 1) | 77.36 | 76.09 | 6742 | 3333 | 0 | 0 |
|
|
113
|
+
| batching on (round 1) | 7.91 | 6.26 | 156 | 79 | 56 | 3694 |
|
|
114
|
+
| batching off (round 2) | 43.77 | 42.63 | 6742 | 3333 | 0 | 0 |
|
|
115
|
+
| batching on (round 2) | 9.14 | 7.10 | 156 | 79 | 56 | 3694 |
|
|
116
|
+
|
|
117
|
+
Draw calls fall 43x (6742 -> 156); 56 of the 79 (cell, geometry, material) groups reached the threshold of 8, the other 23 (cell-edge strips) stay plain meshes.
|
|
118
|
+
The batching bookkeeping itself costs about 0.46 ms/frame with 3000 batched objects and nothing moving (a transform check per batched object plus a
|
|
119
|
+
256-object round robin that looks for parts changed behind its back). With nothing repeating it only checks a few transforms.
|
|
120
|
+
|
|
121
|
+
## 4. Open to playable (engine.startup)
|
|
122
|
+
|
|
123
|
+
| Example | Open to playable ms | start() to playable ms | Asset preload ms | First-screen chunks (terrain ready) ms | Slowest module |
|
|
124
|
+
|---|---|---|---|---|---|
|
|
125
|
+
| Open world (`/`), before optimization | 7036 | 6778 | 0 | 4319 | terrain 4319 |
|
|
126
|
+
| Open world (`/`), after optimization (median of 5) | 3067 | 2798 | 0 | 377 | rigid 2420 (Rapier download and initialization) |
|
|
127
|
+
| Small city (`/tests/city/index.html`), previous run | 2103 | 1866 | 0 | — | rigid 1863 (Rapier download and initialization) |
|
|
128
|
+
| Open world, this run (perf.mjs) | 4392 | 4116 | 0 | 1281 | rigid 2834 |
|
|
129
|
+
| Open world, this run (npm test "startup time") | 4057 | 3176 | 0 | 940 | rigid 2235 |
|
|
130
|
+
| Small city, this run (perf.mjs / npm test) | 2470 / 3094 | 2246 / 1846 | 0 | — | rigid 1511 |
|
|
131
|
+
|
|
132
|
+
This run is about 1 second slower than "after optimization", with first-screen chunks 377 -> 940-1281 ms: this machine has only 2 cores, and the
|
|
133
|
+
background chunk threads, the Rapier wasm compilation and the main thread compete for them; rigid (Rapier) is still the slowest item.
|
|
134
|
+
|
|
135
|
+
With software rendering, shader compilation and chunk upload are very slow and real devices will be much faster; use it to see "who is slowest" and
|
|
136
|
+
the change before/after a modification.
|
|
137
|
+
|
|
138
|
+
### Where the open-world startup is slow (per-frame record of chunk count, in-flight tasks, pending upload results)
|
|
139
|
+
|
|
140
|
+
Background-thread generation itself is not slow (measured in node: terrain 7 ms/chunk, all vegetation about 8 ms/chunk). The slowness is **a single
|
|
141
|
+
very long main-thread frame** (0.5-1.8 seconds per frame during loading under software rendering, longer while Rapier compiles), and the chunk
|
|
142
|
+
pipeline advances "per frame" everywhere:
|
|
143
|
+
|
|
144
|
+
1. **Dispatch per frame**: at most 4 tasks at the same time, and a result has to wait for the next frame's update before the next one is dispatched.
|
|
145
|
+
With a 1-second main-thread frame, the background thread finishes 4 (tens of milliseconds) and then idles.
|
|
146
|
+
2. **Upload limited per frame**: a 3 ms upload budget per frame; during loading results pile up to 8-14 in the queue and only about 4 are uploaded per frame.
|
|
147
|
+
3. **Ready check one frame late**: start() checks readiness with a timer every 20 ms, but the timer is often scheduled after the next frame, so after
|
|
148
|
+
all chunks are in place one more whole frame (about 1 second) is rendered before it notices.
|
|
149
|
+
4. The isReadyAround radius is 1 ring (3x3 = 9 chunks), which is reasonable and was not changed; the stream registry is empty here (0 ms); there is no
|
|
150
|
+
duplicate generation (the rebuilds of registerSpecies all happen before start).
|
|
151
|
+
|
|
152
|
+
The fixes (effective only while the loading screen is still up; behavior after entering the game is unchanged, view distance and density unchanged):
|
|
153
|
+
|
|
154
|
+
- ChunkManager: dispatch the next task as soon as a result returns (`_pump`); when the engine is not ready, do not limit the number of concurrent
|
|
155
|
+
tasks (send all to the background threads to queue, nearest first).
|
|
156
|
+
- ChunkManager: when the engine is not ready, the ring of chunks around the player (needed for the first screen) is not limited by the 3 ms upload
|
|
157
|
+
budget and is uploaded entirely within one frame; the rest still follow the budget.
|
|
158
|
+
- Engine.start: besides the timer, the real-time loop also checks readiness at the end of every frame.
|
|
159
|
+
|
|
160
|
+
Step-by-step effect (first-screen chunks ms, 2-3 runs each): originally 4254-4591 -> dispatch on result return 4359-4779 (the real bottleneck was the
|
|
161
|
+
main thread not receiving replies) -> send everything while loading 2897-3185 -> first-screen chunks without budget 2960-3185 -> check readiness at
|
|
162
|
+
the end of each frame 332-1927. The biggest remainder is rigid (Rapier wasm compilation, about 2.4 seconds), which runs in parallel with chunk generation.
|
|
163
|
+
|
|
164
|
+
## 5. Worker pool (engine.threads), 2026-10-31
|
|
165
|
+
|
|
166
|
+
Measured on the user's Windows machine (16 logical cores, so `threads: 'auto'` = 4 workers), headless Chromium. **WebGL did not start in this headless run**
|
|
167
|
+
(0 draw calls everywhere), so only CPU module timings and startup are comparable; render numbers are meaningless. Not a real-device GPU measurement.
|
|
168
|
+
|
|
169
|
+
`npm run perf`, before -> after the change (terrain moved from its own single worker to a 4-worker lane):
|
|
170
|
+
|
|
171
|
+
| | Before | After |
|
|
172
|
+
|---|---|---|
|
|
173
|
+
| openWorld whole frame ms | 0.54 | 0.61 |
|
|
174
|
+
| terrain module ms/frame | 0.06 | 0.08 |
|
|
175
|
+
| rigid module ms/frame | 0.24 | 0.27 |
|
|
176
|
+
| open world: open to playable / start() to playable ms | 821 / 340 | 1211 / 538 |
|
|
177
|
+
| town: open to playable / start() to playable ms | 804 / 358 | 947 / 394 |
|
|
178
|
+
|
|
179
|
+
The slowest item in both runs is rigid (Rapier), which this change does not touch, and it moved 339 -> 537 ms by itself: the differences are run-to-run noise,
|
|
180
|
+
not a regression. Terrain's per-frame cost stays under 0.1 ms.
|
|
181
|
+
|
|
182
|
+
World far simulation in workers (`npm test -- "threads:"`, 460 records, far every 0.05 s, 240 steps): main-thread ms per fixed step
|
|
183
|
+
threads 0 = 1.34-1.41, threads 2 = 0.95-1.10. The main thread still copies each batch (structuredClone) and diffs the result, so the gain grows with how heavy
|
|
184
|
+
`far` is; a trivial far gains little. Records are bit-identical between threads 0 and 2 at every checkpoint;
|
|
185
|
+
with threads 2 every batch used the worker result (0 late).
|
|
186
|
+
|
|
187
|
+
## 5b. Pathfinding in workers (`findPathAsync`), 2026-10-31
|
|
188
|
+
|
|
189
|
+
Same machine (16 logical cores), headless Chromium, `npm test -- "paths: findPathAsync main"`. Two headless engines get the same 300 requests;
|
|
190
|
+
"main-thread ms" is the total time of the fixed steps until every answer landed, minus the same number of steps without requests. Workers were already started
|
|
191
|
+
and held the mesh (a game pays that start-up once). Before = the synchronous `findPath` loop that NPCs used until now.
|
|
192
|
+
|
|
193
|
+
| 300 paths | Before: sync `findPath` | `findPathAsync`, threads 0 | `findPathAsync`, threads 2 |
|
|
194
|
+
|---|---|---|---|
|
|
195
|
+
| A* (40 boxes, 140 m area) | 218-266 ms | 254-294 ms | 78-90 ms (2 of 10 batches late) |
|
|
196
|
+
| Navmesh (40x40 maze) | 8-17 ms | 11-35 ms | 3 ms (0 late) |
|
|
197
|
+
|
|
198
|
+
Paths and landing steps are identical between threads 0 and 2 (also across a collider change and a crashed worker). The A* main-thread time that remains is
|
|
199
|
+
sampling the ground raster (water / slope, cached 5 s) and the batches that came back late; with real frame gaps (16 ms instead of the test's 2-4 ms)
|
|
200
|
+
fewer are late.
|
|
201
|
+
threads 0 costs a little more than the sync loop (batch building plus the raster), so `findPath` stays the call for one-off paths.
|
|
202
|
+
|
|
203
|
+
## Limitations
|
|
204
|
+
|
|
205
|
+
- SwiftShader does the GPU's work on the CPU, but WebGL commands are submitted asynchronously: "render ms" in the tables is mostly the time three.js
|
|
206
|
+
spends traversing the scene + submitting commands, and **does not include** the time to actually draw pixels. Fragment-heavy things (shadow map
|
|
207
|
+
resolution, bloom, ambient occlusion, transparent overdraw) show no difference here; check them on a real device with the F3 panel.
|
|
208
|
+
- Noise: the same configuration run repeatedly can differ by 10-30%; draw no conclusion from smaller differences.
|
|
209
|
+
- The `world` mode has no NPCs, pickups or other content, so it has fewer draw calls than the open-world example; to see the example itself, open
|
|
210
|
+
`npm run dev` and run the stress test with F3.
|
|
211
|
+
- The budget monitor (`engine.budget`) is off by default; when on, each frame adds one array write and a check once per second, and only when over the
|
|
212
|
+
limit does it traverse the scene to count by `userData.budgetTag`.
|
|
213
|
+
|
|
214
|
+
## Per-module timing
|
|
215
|
+
|
|
216
|
+
The core ships `engine.profile(true)` to turn it on and `engine.profile()` to read `{ moduleName: average milliseconds per rendered frame }` and
|
|
217
|
+
reset; the test page uses it instead of wrapping hooks itself.
|
package/docs/THREE.md
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
# When the engine lacks a feature: use three.js directly
|
|
2
|
+
|
|
3
|
+
The scene, camera, lights, characters and models in the engine are **plain three.js objects** (three 0.187). For anything the engine does not provide,
|
|
4
|
+
write it the three.js way you already know, as long as you follow the conventions below.
|
|
5
|
+
|
|
6
|
+
## Getting three.js objects from the engine
|
|
7
|
+
|
|
8
|
+
| You want | Use |
|
|
9
|
+
|---|---|
|
|
10
|
+
| THREE itself | `import { THREE } from 'threedog'` or `engine.THREE` (the same copy the engine uses) |
|
|
11
|
+
| Scene / camera / renderer | `engine.scene`, `engine.camera` (PerspectiveCamera), `engine.renderer` (WebGLRenderer) |
|
|
12
|
+
| Player, NPCs | `engine.player.object`, `engine.npcs.get('name').object` (Group); position `.position` (Vector3) |
|
|
13
|
+
| Pickups, entities | `inventory.spawnPickup(...)` returns a handle with `.object` (Mesh); entity `ent.object` (root Group), `ent.visual` (model) |
|
|
14
|
+
| Level | `engine.level.root`; markers `engine.level.marker('spawn').object / .position` |
|
|
15
|
+
| Sun, ambient light, sky dome, fog | `engine.sky.sun` (DirectionalLight), `sky.hemi` (HemisphereLight), `sky.dome`, `engine.scene.fog` |
|
|
16
|
+
| Water | `engine.water.sea` (Mesh; null when the game sets no water level), `water.material`, `water.bodies.get(body)` |
|
|
17
|
+
| Particles, rain/snow | `.points` (THREE.Points) of the value returned by `particles.define(...)`; rain / snow look in the style pack (`style.weather.rain / snow`) |
|
|
18
|
+
| Rigid bodies | `engine.rigid.addBox(mesh)` returns a handle `{ object, body, remove() }`, or null before Rapier is ready (object is your mesh; `castShadow` / `receiveShadow` keep the values you set, the engine does not change them) |
|
|
19
|
+
| Terrain chunks | `engine.terrain.chunks` (Map; each chunk has `.group` and a `.terrain` mesh) |
|
|
20
|
+
| Models, textures, animation | `await engine.assets.model('name or path')` (an Object3D copy), `assets.texture(...)`, `assets.animate(model).mixer` |
|
|
21
|
+
| Vehicles, navigation, character controller | `engine.rigid.addVehicle(mesh, ...)` returns `{ body, controller }`; `engine.nav.navMesh / query / tileCache / crowd` (they are destroyed and replaced on rebuild; code that caches them compares `engine.nav.version`); `engine.player.mover.controller` (mover: 'rapier') |
|
|
22
|
+
| glTF / compression decoders | `engine.assets.gltf` (GLTFLoader, Meshopt installed), `assets.draco` (DRACOLoader), `assets.ktx2` (KTX2Loader); the last two are created the first time compressed data is met and are null before that |
|
|
23
|
+
| Rays | `engine.raycast(origin, direction)` / `engine.pick(ndcX, ndcY)` return three hits (`object` is the mesh, `face` and `point` unchanged); `{ targets: 'all' }` hits rigid bodies too (the hit carries `entry` and `kind: 'rigid'`); the underlying `engine.rays.ray` (THREE.Raycaster, `firstHitOnly` on) |
|
|
24
|
+
| Ray acceleration (BVH) | three-mesh-bvh: on import (`import 'threedog'`) the engine replaces `Mesh.prototype.raycast` page-wide, the way three-mesh-bvh recommends, so your own `new THREE.Raycaster()` uses it too (meshes without a `boundsTree` take three's normal path); a registered mesh has `mesh.geometry.boundsTree` (MeshBVH, built only from 256 triangles up) |
|
|
25
|
+
| Streamed-in objects | `.object` of the handle returned by `engine.stream.add({ position, build })` (the Object3D that build returned; null before it is built) |
|
|
26
|
+
| Post-processing | `engine.look.post.replace([{ name, slot, create: ctx => pass }, ...])` takes any three.js Pass as a named effect in a slot (`scene` / `hdr` / `ldr` / `final`); `look.post.set({ 'name.enabled': false })` |
|
|
27
|
+
| Where the mouse points | Ground: `screenToGround(engine, input.pointer.ndcX, ndcY)` -> Vector3; objects: `engine.pick(input.pointer.ndcX, ndcY)` (registered static objects; for any object pass `{ targets: [object] }`) |
|
|
28
|
+
|
|
29
|
+
Returned positions are all `THREE.Vector3` (the camera's `forward()/right()` are planar directions `{x, z}`; positions in photo records are saveable `{x, z}`).
|
|
30
|
+
Anywhere a position is accepted it is **one argument**: Vector3 / Object3D / `[x, y, z]` / `{ x, z }` all work, and sizes go in an options object (see
|
|
31
|
+
"Interface conventions" in `CONVENTIONS.md`):
|
|
32
|
+
`collision.addCircle(mesh, { radius: 1 })`, `collision.addBox(mesh.position, { halfWidth: 2, halfDepth: 1 })`, `particles.emit('dust', mesh, { count: 20 })`,
|
|
33
|
+
`triggers.add({ position: mesh })`, `entities.spawn(t, { position: v })`, `npcs.add({ position: v })`, `spawnPickup(id, v)`, `interactions.add(v or mesh, ...)`,
|
|
34
|
+
`rigid.impulse(entry, [0, 3, 5])`, `player.placeAt(v)`. Ground sampling `engine.surface(x, z)` also accepts `engine.surface(mesh.position)`.
|
|
35
|
+
|
|
36
|
+
## Engine conventions when using three.js
|
|
37
|
+
|
|
38
|
+
1. **Materials use `makeMaterial('role', { color, ... })`**, not `new MeshLambertMaterial` directly. It returns a real three material (the type is
|
|
39
|
+
decided by the style pack); afterwards change `.map`, `.transparent` as usual.
|
|
40
|
+
2. **Adding to the scene**: `engine.add(obj)` returns obj so it fits on one line. `engine.scene.add(obj)` is plain three.js that the engine does not
|
|
41
|
+
track, and is just as legal. Plain three.js and templates (`engine.spawn`, content props) are two doors into one scene (`recipes/40-scene.md`).
|
|
42
|
+
`engine.add(obj, { id })` registers the object under a stable id so `engine.thing(id)` can say what it is and what a save keeps. To
|
|
43
|
+
attach to a character use `player.object.add(hat)`.
|
|
44
|
+
3. **Per-frame logic goes in `engine.onFrame(dt => ...)`** (movement and timing use `engine.onFixed`); it returns a handle, cancel with `h.remove()`.
|
|
45
|
+
Never call `requestAnimationFrame` or `renderer.render` yourself: the engine owns pausing, fast-forward in tests, post-processing and ordering.
|
|
46
|
+
4. **Snap to ground**: get ground height with `engine.surface(x, z)`, or `engine.snapToGround(obj, heightAboveGround)`. Don't raycast the terrain.
|
|
47
|
+
**Rays** always go through `engine.raycast / pick`: level meshes are registered automatically; register your own static objects with
|
|
48
|
+
`engine.rays.addStatic(obj)` or `assets.model(name, { static: true })`.
|
|
49
|
+
When you need a plain `THREE.Raycaster`, it also uses the BVH automatically (as long as the geometry has a boundsTree).
|
|
50
|
+
5. **Deleting**: when you no longer need an object use `engine.remove(obj)`: it removes it, unregisters it from `engine.rays` and frees the geometry
|
|
51
|
+
and materials (`obj.removeFromParent()` / `scene.remove` leak GPU memory). To take it off only temporarily and `add` it back later use
|
|
52
|
+
`engine.detach(obj)`. A copy from `assets.model()` shares resources with other copies (`remove` skips them); they are freed together by
|
|
53
|
+
`assets.release(name)`.
|
|
54
|
+
6. **Sky lighting is recomputed every frame**: to darken or tint use a modifier layer
|
|
55
|
+
`engine.sky.modify('layer', { sun, ambient, fog, tint, tintAmount })` (multipliers, layers multiply; `null` removes), and don't change
|
|
56
|
+
`sky.sun.intensity` or `sky.modifiers` (the combined result, read-only). Adding your own point lights (street lamps, campfires) is fine.
|
|
57
|
+
7. **Camera**: only change properties of `engine.camera`, never replace it with a new camera (post-processing is bound to this one). When a camera
|
|
58
|
+
module is installed it places the camera every frame; to control the view yourself take it with `const cam = engine.takeCamera('me')` and `cam.remove()` it
|
|
59
|
+
(`engine.cameraOverride` is read-only: it shows the holder in charge, or `null`).
|
|
60
|
+
8. Collision: the player only respects `engine.collision` (`addCircle / addBox / addObject(mesh)`); a mesh alone does not block anyone.
|
|
61
|
+
9. **Big code-generated things** (a city block, a whole group of houses): write them as a function registered in the manifest
|
|
62
|
+
`assets.manifest({ models: { block: buildBlock } })` and fetch with `assets.model('block')`; in development it is cached automatically, after
|
|
63
|
+
`npm run bake` it reads the file.
|
|
64
|
+
Things needed only nearby use `engine.stream.add({ position, build })`; put long loops in `engine.jobs.add(function* () { ...; yield; })` so they
|
|
65
|
+
are spread over frames and the start does not stall.
|
|
66
|
+
|
|
67
|
+
## Example: a spinning windmill (plain three.js + engine conventions)
|
|
68
|
+
This is the plain three.js door. The same windmill as a template with an id, saved and editable without code, is in `recipes/40-scene.md` §1.
|
|
69
|
+
|
|
70
|
+
```js
|
|
71
|
+
import { THREE, makeMaterial } from 'threedog';
|
|
72
|
+
const mill = new THREE.Group(), wood = makeMaterial('building', { color: 0x8a6a4a, flatShading: true });
|
|
73
|
+
const tower = new THREE.Mesh(new THREE.CylinderGeometry(0.8, 1.2, 6, 6), wood);
|
|
74
|
+
tower.position.y = 3; tower.castShadow = true;
|
|
75
|
+
const blades = new THREE.Group(); blades.position.set(0, 5.5, 1.3);
|
|
76
|
+
for (let i = 0; i < 4; i++) {
|
|
77
|
+
const arm = new THREE.Group(), sail = new THREE.Mesh(new THREE.BoxGeometry(0.5, 4, 0.08), makeMaterial('building', { color: 0xe8e0d0 }));
|
|
78
|
+
sail.position.y = 2; sail.castShadow = true; arm.rotation.z = i * Math.PI / 2; arm.add(sail); blades.add(arm);
|
|
79
|
+
}
|
|
80
|
+
mill.add(tower, blades);
|
|
81
|
+
mill.position.set(20, 0, -10);
|
|
82
|
+
engine.snapToGround(mill); // snap to ground
|
|
83
|
+
engine.add(mill);
|
|
84
|
+
engine.collision?.addCircle(mill, { radius: 1.3 }); // block the player (when the collision module is installed)
|
|
85
|
+
engine.onFrame(dt => { blades.rotation.z += dt * 1.5; });
|
|
86
|
+
```
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
# engine.ambience — ambience(opts?: AmbienceOptions)
|
|
2
|
+
|
|
3
|
+
Ambience (ambience() module)
|
|
4
|
+
|
|
5
|
+
- Options `AmbienceOptions`:
|
|
6
|
+
- `rules?: import('./core').AmbienceRule[]`
|
|
7
|
+
- `interval?: number`
|
|
8
|
+
|
|
9
|
+
## Methods and properties
|
|
10
|
+
- `ambience.add(rule: AmbienceRule) → { remove(): void }` — Add one rule; returns a handle whose remove() fades the sound out and drops the rule. Example: `const h = engine.ambience.add({ sound: 'storm-wind', when: { weather: 'storm' }, volume: 0.5 });`
|
|
11
|
+
- `ambience.rules(list: AmbienceRule[] | null)` — Replace the whole rule table (null or [] = silence)
|
|
12
|
+
- `ambience.nearWater(radius?: number) → number` — How much of the ground within `radius` meters of the listener is water (0-1), sampled at 6 points: for a water rule's volume. Example: `{ sound: 'river', volume: (e, a) => a.nearWater(20) * 0.12 } // in data: volume: { add: { nearWater: 0.12 } } (12 m)`
|
|
13
|
+
- Properties:
|
|
14
|
+
- `position: THREE.Vector3` Where the sounds are heard from: whoever the player controls (engine.actor), else the camera focus
|
|
15
|
+
- `info: { sound: string; on: boolean; volume: number }[]` What each rule is doing (debug, tests): sound name, whether its condition holds, its current target volume
|