threedog 0.7.0 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +411 -1
- package/README.md +8 -11
- package/core/{Animator.js → assets/Animator.js} +30 -18
- package/core/{Assets.js → assets/Assets.js} +131 -56
- package/core/{Baked.js → assets/Baked.js} +4 -4
- package/core/assets/assetEntry.js +302 -0
- package/core/{assetHot.js → assets/assetHot.js} +9 -7
- package/core/{assetLoad.js → assets/assetLoad.js} +55 -16
- package/core/assets/assetLod.js +113 -0
- package/core/{assetManifest.js → assets/assetManifest.js} +19 -11
- package/core/{assetReport.js → assets/assetReport.js} +7 -14
- package/core/{namedModel.js → assets/namedModel.js} +17 -13
- package/core/{Audio.js → audio/Audio.js} +47 -25
- package/core/{audioRules.js → audio/audioRules.js} +8 -5
- package/core/{audioVoice.js → audio/audioVoice.js} +17 -30
- package/core/{Events.js → base/Events.js} +3 -3
- package/core/{I18n.js → base/I18n.js} +15 -12
- package/core/{Random.js → base/Random.js} +7 -4
- package/core/{Vars.js → base/Vars.js} +14 -4
- package/core/{easing.js → base/easing.js} +1 -1
- package/core/{errorCodes.js → base/errorCodes.js} +151 -125
- package/core/{errorHints.js → base/errorHints.js} +17 -10
- package/core/{errors.js → base/errors.js} +12 -10
- package/core/{events.generated.js → base/events.generated.js} +11 -0
- package/core/base/follows.js +26 -0
- package/core/base/math.js +66 -0
- package/core/{params.js → base/params.js} +5 -6
- package/core/base/saveValues.js +81 -0
- package/core/base/sections.js +97 -0
- package/core/base/spelling.js +32 -0
- package/core/base/util.js +32 -0
- package/core/{validate.js → base/validate.js} +34 -34
- package/core/{Engine.js → engine/Engine.js} +137 -91
- package/core/{Loading.js → engine/Loading.js} +34 -5
- package/core/{copies.js → engine/copies.js} +4 -4
- package/core/{headlessLoad.js → engine/headlessLoad.js} +32 -15
- package/core/{lifecycle.js → engine/lifecycle.js} +41 -34
- package/core/{loop.js → engine/loop.js} +88 -49
- package/core/engine/moduleSlots.js +176 -0
- package/core/{moduleTypes.js → engine/moduleTypes.js} +26 -14
- package/core/engine/modules.js +503 -0
- package/core/{page.js → engine/page.js} +59 -29
- package/core/{plugins.js → engine/plugins.js} +21 -12
- package/core/{services.js → engine/services.js} +50 -40
- package/core/{startup.js → engine/startup.js} +66 -54
- package/core/{Input.js → input/Input.js} +67 -39
- package/core/{inputContext.js → input/inputContext.js} +14 -5
- package/core/input/inputKeyboard.js +39 -0
- package/core/{inputPad.js → input/inputPad.js} +24 -3
- package/core/{inputPointer.js → input/inputPointer.js} +11 -3
- package/core/input/inputSeat.js +66 -0
- package/core/{inputTouch.js → input/inputTouch.js} +24 -7
- package/core/{Budget.js → inspect/Budget.js} +21 -20
- package/core/{DebugOverrides.js → inspect/DebugOverrides.js} +43 -18
- package/core/{Describe.js → inspect/Describe.js} +34 -26
- package/core/{Inspect.js → inspect/Inspect.js} +39 -10
- package/core/{InspectMaterials.js → inspect/InspectMaterials.js} +7 -8
- package/core/{InspectPerf.js → inspect/InspectPerf.js} +19 -13
- package/core/{InspectScene.js → inspect/InspectScene.js} +8 -5
- package/core/{MaterialInfo.js → inspect/MaterialInfo.js} +3 -2
- package/core/{UrlState.js → inspect/UrlState.js} +60 -24
- package/core/{catalog.js → inspect/catalog.js} +15 -8
- package/core/{checks.js → inspect/checks.js} +7 -5
- package/core/{debugView.js → inspect/debugView.js} +4 -4
- package/core/{describeRender.js → inspect/describeRender.js} +24 -22
- package/core/{describeText.js → inspect/describeText.js} +17 -8
- package/core/inspect/geometryWatch.js +38 -0
- package/core/{lightWatch.js → inspect/lightWatch.js} +8 -8
- package/core/inspect/metadata.generated.js +4140 -0
- package/core/{pictureWriters.js → inspect/pictureWriters.js} +130 -47
- package/core/{shaderCost.js → inspect/shaderCost.js} +1 -1
- package/core/inspect/toolDoor.js +21 -0
- package/core/inspect/valueHistory.js +35 -0
- package/core/{Ops.js → ops/Ops.js} +44 -14
- package/core/{control.js → ops/control.js} +57 -31
- package/core/ops/holds.js +140 -0
- package/core/{opsAtomic.js → ops/opsAtomic.js} +18 -5
- package/core/{opsCheck.js → ops/opsCheck.js} +11 -10
- package/core/{opsFail.js → ops/opsFail.js} +5 -7
- package/core/{opsGuard.js → ops/opsGuard.js} +3 -3
- package/core/{opsRun.js → ops/opsRun.js} +9 -6
- package/core/{owned.js → ops/owned.js} +33 -19
- package/core/{sharedPoint.js → ops/sharedPoint.js} +13 -16
- package/core/{stackFrames.js → ops/stackFrames.js} +2 -2
- package/core/{stacks.js → ops/stacks.js} +34 -15
- package/core/{wrap.js → ops/wrap.js} +8 -6
- package/core/{SaveStore.js → saves/SaveStore.js} +53 -27
- package/core/{Saves.js → saves/Saves.js} +171 -54
- package/core/saves/saveApply.js +312 -0
- package/core/{saveFiles.js → saves/saveFiles.js} +45 -38
- package/core/{saveVersions.js → saves/saveVersions.js} +24 -23
- package/core/saves/session.js +231 -0
- package/core/saves/stateReplace.js +184 -0
- package/core/{Rays.js → scene/Rays.js} +44 -30
- package/core/{Views.js → scene/Views.js} +16 -8
- package/core/{adaptive.js → scene/adaptive.js} +19 -9
- package/core/{canvasBox.js → scene/canvasBox.js} +4 -3
- package/core/scene/compositeGround.js +72 -0
- package/core/scene/floor.js +17 -0
- package/core/{gameLights.js → scene/gameLights.js} +17 -7
- package/core/{grayMap.js → scene/grayMap.js} +8 -2
- package/core/{grid.js → scene/grid.js} +6 -4
- package/core/{gridLoad.js → scene/gridLoad.js} +1 -1
- package/core/scene/ground.contract.js +14 -0
- package/core/scene/ground.js +139 -0
- package/core/{movement.js → scene/movement.js} +3 -3
- package/core/{pictureSlots.js → scene/pictureSlots.js} +2 -2
- package/core/scene/pixel.js +154 -0
- package/core/scene/pixelRatio.js +167 -0
- package/core/{sceneDelta.js → scene/sceneDelta.js} +5 -5
- package/core/{sceneMethods.js → scene/sceneMethods.js} +43 -15
- package/core/scene/stepPoses.js +60 -0
- package/core/{targeting.js → scene/targeting.js} +4 -5
- package/core/{thingExplain.js → scene/thingExplain.js} +7 -6
- package/core/{thingOps.js → scene/thingOps.js} +25 -16
- package/core/{things.js → scene/things.js} +18 -5
- package/core/{threePatches.js → scene/threePatches.js} +1 -1
- package/core/{tier.js → scene/tier.js} +10 -0
- package/core/scene/view.js +161 -0
- package/core/{Batching.js → stream/Batching.js} +85 -28
- package/core/{Stream.js → stream/Stream.js} +80 -38
- package/core/{batchGroups.js → stream/batchGroups.js} +11 -9
- package/core/{chunkStream.js → stream/chunkStream.js} +40 -0
- package/core/{scatter.js → stream/scatter.js} +7 -4
- package/core/{streamSources.js → stream/streamSources.js} +14 -8
- package/core/{Commits.js → threads/Commits.js} +17 -11
- package/core/{Jobs.js → threads/Jobs.js} +25 -13
- package/core/{Threads.js → threads/Threads.js} +21 -18
- package/core/{threadPure.js → threads/threadPure.js} +7 -5
- package/core/{threadServe.js → threads/threadServe.js} +3 -3
- package/core/{Clock.js → time/Clock.js} +20 -11
- package/core/{dayTime.js → time/dayTime.js} +5 -1
- package/core/{skip.js → time/skip.js} +28 -21
- package/core/{time.js → time/time.js} +32 -20
- package/core/{uiClock.js → time/uiClock.js} +4 -4
- package/docs/AI.md +92 -72
- package/docs/API.md +33 -28
- package/docs/CODEMAP.md +121 -200
- package/docs/COMMANDS.md +77 -70
- package/docs/CONVENTIONS.md +167 -24
- package/docs/MIGRATING-0.8.md +171 -0
- package/docs/MIGRATING-1.0.md +101 -0
- package/docs/THREE.md +140 -38
- package/docs/api/assets.md +12 -13
- package/docs/api/audio.md +6 -5
- package/docs/api/budget.md +4 -4
- package/docs/api/calendar.md +10 -11
- package/docs/api/cameraRig.md +32 -29
- package/docs/api/characters.md +35 -24
- package/docs/api/clock.md +1 -1
- package/docs/api/collider3d.md +9 -0
- package/docs/api/collision.md +12 -9
- package/docs/api/content.md +18 -17
- package/docs/api/dialogue.md +5 -4
- package/docs/api/engine.md +58 -54
- package/docs/api/events.md +17 -6
- package/docs/api/flow.md +1 -1
- package/docs/api/grids.md +1 -1
- package/docs/api/ground.md +6 -7
- package/docs/api/hud.md +2 -2
- package/docs/api/i18n.md +6 -6
- package/docs/api/input.md +9 -8
- package/docs/api/interactions.md +5 -5
- package/docs/api/inventory.md +10 -10
- package/docs/api/jobs.md +5 -5
- package/docs/api/level.md +10 -9
- package/docs/api/lightPool.md +1 -6
- package/docs/api/music.md +3 -3
- package/docs/api/nav.md +14 -12
- package/docs/api/openWorld.md +1 -1
- package/docs/api/particles.md +10 -7
- package/docs/api/photo.md +4 -2
- package/docs/api/pickups.md +3 -3
- package/docs/api/post.md +21 -5
- package/docs/api/quests.md +7 -5
- package/docs/api/rays.md +7 -7
- package/docs/api/rigid.md +29 -19
- package/docs/api/saves.md +13 -11
- package/docs/api/settings.md +9 -8
- package/docs/api/sky.md +8 -7
- package/docs/api/stream.md +8 -9
- package/docs/api/swarm.md +34 -0
- package/docs/api/terrain.md +6 -8
- package/docs/api/terrainDraw.md +2 -2
- package/docs/api/timeline.md +4 -4
- package/docs/api/tools.md +27 -22
- package/docs/api/triggers.md +2 -0
- package/docs/api/vars.md +1 -1
- package/docs/api/vegetation.md +4 -3
- package/docs/api/vegetationDraw.md +2 -2
- package/docs/api/water.md +7 -3
- package/docs/api/weather.md +27 -12
- package/docs/api/weatherDraw.md +4 -4
- package/docs/api/world.md +6 -6
- package/docs/recipes/01-new-game.md +28 -43
- package/docs/recipes/02-npc.md +21 -23
- package/docs/recipes/03-items-pickups.md +37 -53
- package/docs/recipes/04-quests.md +5 -4
- package/docs/recipes/05-props-bake.md +34 -44
- package/docs/recipes/06-clock-events.md +31 -22
- package/docs/recipes/07-flow-scenes-pause.md +30 -32
- package/docs/recipes/08-weather-sky.md +91 -37
- package/docs/recipes/09-materials-lights-models.md +25 -39
- package/docs/recipes/10-blender-level.md +22 -11
- package/docs/recipes/11-vehicles.md +44 -24
- package/docs/recipes/12-navmesh.md +60 -15
- package/docs/recipes/13-animation.md +70 -22
- package/docs/recipes/14-custom-module.md +33 -20
- package/docs/recipes/15-perf.md +51 -28
- package/docs/recipes/16-dev-bridge.md +39 -58
- package/docs/recipes/18-world.md +49 -28
- package/docs/recipes/19-shooting-picking.md +7 -4
- package/docs/recipes/20-content-actions-save.md +55 -40
- package/docs/recipes/21-camera.md +47 -25
- package/docs/recipes/22-shop-gold.md +21 -16
- package/docs/recipes/23-ops.md +28 -24
- package/docs/recipes/26-ui-parts.md +25 -14
- package/docs/recipes/27-net.md +3 -5
- package/docs/recipes/28-terrain.md +119 -23
- package/docs/recipes/29-grid.md +3 -3
- package/docs/recipes/30-templates.md +63 -30
- package/docs/recipes/31-audio.md +7 -7
- package/docs/recipes/32-action-game.md +21 -11
- package/docs/recipes/33-stream-sources.md +6 -3
- package/docs/recipes/34-environment-lighting.md +72 -25
- package/docs/recipes/35-picture-from-reference.md +20 -23
- package/docs/recipes/36-ground-plants.md +106 -0
- package/docs/recipes/40-scene.md +18 -21
- package/docs/recipes/43-shader-patches-surfaces.md +27 -48
- package/docs/recipes/44-water-weather-hooks.md +56 -50
- package/docs/recipes/45-cascaded-shadows.md +41 -20
- package/docs/recipes/46-blender-art-route.md +9 -10
- package/docs/recipes/49-game-module-contract.md +7 -6
- package/docs/recipes/50-own-renderer.md +3 -2
- package/docs/recipes/51-capability-catalog.md +14 -8
- package/docs/recipes/52-around-the-picture.md +56 -100
- package/docs/recipes/53-ground-up-close.md +61 -24
- package/docs/recipes/55-mods-time-wrap.md +17 -20
- package/docs/recipes/56-webgpu-tsl.md +28 -15
- package/docs/recipes/57-control.md +39 -12
- package/docs/recipes/58-input.md +15 -2
- package/docs/recipes/59-depth-post-effects.md +1 -1
- package/docs/recipes/60-judge-the-picture.md +30 -25
- package/docs/recipes/62-picture-code.md +129 -39
- package/docs/recipes/63-third-person-start.md +19 -5
- package/docs/recipes/64-particles.md +54 -5
- package/docs/recipes/65-swarm.md +140 -0
- package/docs/recipes/66-common-tasks.md +313 -0
- package/examples/action/.threedog/content-index.json +1 -1
- package/examples/action/GAMEMAP.md +5 -5
- package/examples/perf-island/.threedog/content-index.json +1 -0
- package/examples/{sheepisland → perf-island}/GAMEMAP.md +15 -14
- package/examples/{sheepisland → perf-island}/assets.js +1 -1
- package/examples/{sheepisland → perf-island}/main.js +8 -8
- package/examples/{sheepisland → perf-island}/models.js +1 -1
- package/examples/{sheepisland → perf-island}/params.js +1 -1
- package/examples/{sheepisland → perf-island}/picture/index.js +1 -1
- package/examples/{sheepisland → perf-island}/picture/palette.js +2 -2
- package/examples/{sheepisland → perf-island}/views.js +1 -1
- package/examples/plain-picture/GAMEMAP.md +4 -1
- package/examples/rc2d/GAMEMAP.md +4 -3
- package/examples/rc2d/main.js +1 -3
- package/examples/rc2d/rc2d.js +1 -1
- package/examples/styletest/.threedog/content-index.json +1 -1
- package/examples/styletest/GAMEMAP.md +6 -5
- package/examples/techniques/contact-shadows/contactShadows.js +1 -1
- package/examples/techniques/contact-shadows/main.js +1 -1
- package/examples/techniques/interior-light/main.js +1 -1
- package/examples/techniques/modular-building/README.md +7 -6
- package/examples/techniques/outlines-and-rim/picture/post.js +1 -1
- package/examples/techniques/procedural-animation/README.md +1 -1
- package/examples/webgpu-tsl/GAMEMAP.md +2 -1
- package/examples/world/.threedog/content-index.json +1 -1
- package/examples/world/GAMEMAP.md +9 -7
- package/examples/world/main.js +3 -3
- package/examples/world/picture/sky.js +1 -1
- package/index.d.ts +16 -12
- package/index.js +53 -32
- package/llms.txt +11 -14
- package/modules/ambience/Ambience.js +16 -11
- package/modules/calendar/Calendar.js +19 -19
- package/modules/calendar/index.js +18 -16
- package/modules/calendar/schedule.js +11 -6
- package/modules/calendar/seasons.js +7 -7
- package/modules/camera/FirstPersonCamera.js +5 -5
- package/modules/camera/FixedCamera.js +43 -30
- package/modules/camera/FollowCamera.js +24 -15
- package/modules/camera/RtsCamera.js +12 -11
- package/modules/camera/common.js +72 -37
- package/modules/camera/contract.js +1 -0
- package/modules/camera/pixelSnap.js +62 -0
- package/modules/characters/Character.js +166 -70
- package/modules/characters/NPC.js +84 -44
- package/modules/characters/assetModel.js +16 -12
- package/modules/characters/astar.js +48 -27
- package/modules/characters/behaviors.js +4 -5
- package/modules/characters/character.contract.js +21 -0
- package/modules/characters/contract.js +17 -3
- package/modules/characters/index.js +240 -226
- package/modules/characters/moveHelpers.js +88 -12
- package/modules/characters/mover.contract.js +14 -0
- package/modules/characters/movers/common.js +22 -18
- package/modules/characters/movers/manual.js +1 -1
- package/modules/characters/movers/rapier.js +18 -10
- package/modules/characters/movers/simple.js +26 -13
- package/modules/characters/movers/support.js +24 -13
- package/modules/characters/npcAvoid.js +19 -16
- package/modules/characters/npcSim.js +88 -32
- package/modules/characters/npcView.js +19 -11
- package/modules/characters/pathAsync.js +81 -29
- package/modules/characters/pathJob.js +38 -21
- package/modules/characters/pathWorker.js +1 -1
- package/modules/characters/player.js +120 -0
- package/modules/characters/playerStrings.js +2 -2
- package/modules/characters/proceduralRig.js +2 -2
- package/modules/characters/seat.js +56 -0
- package/modules/characters/useModel.js +3 -3
- package/modules/characters/vehicle.contract.js +8 -5
- package/modules/characters/walkTo.js +40 -33
- package/modules/collision/Collision.js +69 -45
- package/modules/collision/contract.js +15 -0
- package/modules/collision/grid.js +6 -1
- package/modules/content/explain.js +2 -3
- package/modules/content/fields.js +24 -3
- package/modules/content/ids.js +5 -3
- package/modules/content/index.js +132 -114
- package/modules/content/loader.js +117 -140
- package/modules/content/markers.js +25 -0
- package/modules/content/models.js +54 -17
- package/modules/content/packs.js +5 -4
- package/modules/content/parts.js +2 -2
- package/modules/content/places.js +36 -0
- package/modules/content/props.js +22 -17
- package/modules/content/rules.js +47 -61
- package/modules/content/stages.js +7 -7
- package/modules/content/templates.js +80 -49
- package/modules/content/words.js +47 -0
- package/modules/debug/DebugPanel.js +14 -45
- package/modules/flow/contract.js +2 -1
- package/modules/flow/index.js +30 -16
- package/modules/gameplay/Container.js +17 -13
- package/modules/gameplay/Containers.js +23 -6
- package/modules/gameplay/Dialogue.js +93 -34
- package/modules/gameplay/Interactions.js +93 -51
- package/modules/gameplay/Inventory.js +64 -22
- package/modules/gameplay/Quests.js +146 -30
- package/modules/gameplay/boxOps.js +8 -1
- package/modules/gameplay/dialogueBubbles.js +16 -12
- package/modules/gameplay/inventoryOps.js +11 -8
- package/modules/gameplay/pickups.js +63 -37
- package/modules/gameplay/questLog.js +4 -2
- package/modules/gameplay/questSave.js +9 -4
- package/modules/gameplay/quests.contract.js +1 -1
- package/modules/grid/Grid.js +2 -2
- package/modules/grid/Layer.js +12 -8
- package/modules/grid/index.js +28 -23
- package/modules/grid/ops.js +43 -46
- package/modules/grid/preview.js +7 -7
- package/modules/grid/tiles.js +6 -6
- package/modules/hlod/index.js +42 -57
- package/modules/hud/index.js +22 -14
- package/modules/hud/parts.js +8 -8
- package/modules/level/contract.js +16 -0
- package/modules/level/heightfield.js +29 -31
- package/modules/level/index.js +113 -161
- package/modules/level/load.js +196 -0
- package/modules/level/meshes.js +65 -0
- package/modules/level/nodes.js +40 -23
- package/modules/lights/index.js +33 -183
- package/modules/lights/slots.js +93 -0
- package/modules/lights/sources.js +90 -0
- package/modules/music/Music.js +34 -28
- package/modules/music/rules.js +1 -1
- package/modules/nav/contract.js +16 -0
- package/modules/nav/index.js +180 -49
- package/modules/nav/navPath.js +45 -10
- package/modules/net/Client.js +7 -7
- package/modules/net/Host.js +7 -7
- package/modules/net/Net.js +1 -1
- package/modules/net/index.js +6 -5
- package/modules/net/sync.js +2 -2
- package/modules/net/transports.js +2 -2
- package/modules/particles/Particles.js +95 -29
- package/modules/particles/effect.js +86 -32
- package/modules/particles/shaders.js +19 -1
- package/modules/photo/Photo.js +23 -23
- package/modules/rigid/RigidBodies.js +255 -89
- package/modules/rigid/Vehicles.js +17 -8
- package/modules/rigid/collider3d.contract.js +26 -0
- package/modules/rigid/ragdoll.js +298 -0
- package/modules/rigid/ragdollBones.js +209 -0
- package/modules/rigid/refresh.js +10 -0
- package/modules/rigid/sync.js +51 -20
- package/modules/settings/Settings.js +177 -61
- package/modules/settings/apply.js +20 -13
- package/modules/settings/sections.js +19 -14
- package/modules/settings/strings.js +2 -2
- package/modules/settings/view.js +3 -3
- package/modules/sky/Sky.js +29 -22
- package/modules/sky/clouds.js +7 -7
- package/modules/sky/dome.js +33 -20
- package/modules/sky/domeLayers.js +9 -9
- package/modules/sky/environment.js +6 -6
- package/modules/sky/frame.js +19 -10
- package/modules/sky/season.js +7 -1
- package/modules/sky/shader.js +24 -25
- package/modules/sky/skyModule.js +17 -28
- package/modules/sky/tint.js +1 -1
- package/modules/swarm/Swarm.js +356 -0
- package/modules/swarm/draw.js +68 -0
- package/modules/swarm/grid.js +63 -0
- package/modules/terrain/ChunkManager.js +71 -59
- package/modules/terrain/chunkQueries.js +7 -24
- package/modules/terrain/chunkWorker.js +1 -1
- package/modules/terrain/draw.js +14 -11
- package/modules/terrain/index.js +42 -42
- package/modules/terrain/terrainColorMap.js +6 -3
- package/modules/terrain/terrainDefaults.js +2 -1
- package/modules/terrain/terrainEdit.js +45 -29
- package/modules/terrain/terrainGen.js +19 -12
- package/modules/terrain/terrainIsland.js +2 -2
- package/modules/terrain/terrainMesh.js +7 -6
- package/modules/terrain/terrainShape.js +8 -10
- package/modules/terrain/terrainShapeMain.js +3 -3
- package/modules/timeline/Timeline.js +83 -43
- package/modules/timeline/Tween.js +25 -19
- package/modules/timeline/shots.js +24 -17
- package/modules/triggers/index.js +95 -28
- package/modules/vegetation/Vegetation.js +34 -26
- package/modules/vegetation/densityMap.js +4 -7
- package/modules/vegetation/draw.js +39 -18
- package/modules/vegetation/groundChunks.js +21 -38
- package/modules/vegetation/index.js +37 -12
- package/modules/vegetation/modelGeometry.js +3 -6
- package/modules/vegetation/nearFade.js +1 -1
- package/modules/water/Water.js +20 -16
- package/modules/water/surface.js +3 -3
- package/modules/weather/Weather.js +52 -40
- package/modules/weather/particles.js +8 -8
- package/modules/weather/weatherDraw.js +28 -23
- package/modules/world/World.js +28 -15
- package/modules/world/explain.js +1 -1
- package/modules/world/index.js +30 -17
- package/modules/world/persist.js +90 -27
- package/modules/world/pos.js +5 -5
- package/modules/world/records.js +37 -11
- package/modules/world/sim.js +78 -27
- package/modules/world/simFar.js +2 -2
- package/modules/world/state.js +43 -11
- package/modules/world/thingSource.js +20 -5
- package/modules/world/views.js +27 -14
- package/package.json +48 -7
- package/presets.js +1 -3
- package/render/PostFX.js +83 -53
- package/render/backend.js +31 -33
- package/render/cascades.js +17 -12
- package/render/cascades.tsl.js +5 -8
- package/render/daylight.js +20 -3
- package/render/detail.js +8 -7
- package/render/effects.js +28 -25
- package/render/fuse.js +3 -3
- package/render/fx/cloudShadow.tsl.js +3 -3
- package/render/fx/detail.tsl.js +1 -1
- package/render/fx/index.js +5 -10
- package/render/fx/library.tsl.js +11 -0
- package/render/fx/lighting.tsl.js +2 -1
- package/render/fx/nodeErrors.tsl.js +2 -2
- package/render/fx/objectOrigin.tsl.js +1 -2
- package/render/fx/particles.tsl.js +8 -6
- package/render/fx/patchNodes.tsl.js +5 -15
- package/render/fx/postWebGPU.tsl.js +30 -26
- package/render/fx/sky.tsl.js +15 -17
- package/render/fx/uniforms.tsl.js +4 -4
- package/render/fx/wind.tsl.js +1 -1
- package/render/fxNumbers.js +3 -0
- package/render/layers.js +2 -2
- package/render/lighting.js +5 -3
- package/render/lightmap.js +41 -21
- package/render/lights.js +6 -6
- package/render/lit.js +24 -0
- package/render/materials.js +8 -7
- package/render/mergeCommon.js +22 -0
- package/render/modeling.js +2 -2
- package/render/occlusion.js +62 -15
- package/render/ownFrame.js +4 -4
- package/render/patches.js +15 -15
- package/render/postWebGL.js +15 -12
- package/render/probes.js +41 -19
- package/render/recordSweep.js +117 -0
- package/render/shaderErrors.js +10 -9
- package/render/shadowCache.tsl.js +107 -0
- package/render/shadowTypes.js +9 -0
- package/{core → render}/shadows.js +59 -13
- package/render/slots.js +7 -7
- package/render/terms.js +22 -24
- package/render/uniformDecl.js +1 -1
- package/types/core.d.ts +336 -202
- package/types/gameplay.d.ts +254 -130
- package/types/generated/core/{Audio.d.ts → audio/Audio.d.ts} +22 -7
- package/types/generated/core/{audioVoice.d.ts → audio/audioVoice.d.ts} +2 -2
- package/types/generated/core/{Events.d.ts → base/Events.d.ts} +4 -4
- package/types/generated/core/{I18n.d.ts → base/I18n.d.ts} +8 -16
- package/types/generated/core/{Random.d.ts → base/Random.d.ts} +4 -3
- package/types/generated/core/{page.d.ts → engine/page.d.ts} +8 -9
- package/types/generated/core/{Input.d.ts → input/Input.d.ts} +28 -10
- package/types/generated/core/input/inputSeat.d.ts +26 -0
- package/types/generated/core/{Budget.d.ts → inspect/Budget.d.ts} +36 -26
- package/types/generated/core/{DebugOverrides.d.ts → inspect/DebugOverrides.d.ts} +17 -3
- package/types/generated/core/{Ops.d.ts → ops/Ops.d.ts} +6 -4
- package/types/generated/core/{control.d.ts → ops/control.d.ts} +14 -10
- package/types/generated/core/{Saves.d.ts → saves/Saves.d.ts} +62 -18
- package/types/generated/core/{session.d.ts → saves/session.d.ts} +3 -2
- package/types/generated/core/{Rays.d.ts → scene/Rays.d.ts} +8 -27
- package/types/generated/core/{Views.d.ts → scene/Views.d.ts} +2 -2
- package/types/generated/core/{Batching.d.ts → stream/Batching.d.ts} +7 -7
- package/types/generated/core/{Stream.d.ts → stream/Stream.d.ts} +22 -18
- package/types/generated/core/{Commits.d.ts → threads/Commits.d.ts} +1 -1
- package/types/generated/core/{Jobs.d.ts → threads/Jobs.d.ts} +6 -6
- package/types/generated/core/{Threads.d.ts → threads/Threads.d.ts} +4 -4
- package/types/generated/modules/calendar/Calendar.d.ts +10 -11
- package/types/generated/modules/debug/DebugPanel.d.ts +1 -9
- package/types/generated/modules/grid/Grid.d.ts +1 -0
- package/types/generated/modules/grid/Layer.d.ts +1 -1
- package/types/generated/modules/grid/index.d.ts +3 -3
- package/types/generated/modules/music/Music.d.ts +7 -5
- package/types/generated/modules/particles/Particles.d.ts +5 -4
- package/types/generated/modules/sky/Sky.d.ts +21 -10
- package/types/generated/modules/swarm/Swarm.d.ts +80 -0
- package/types/generated/modules/timeline/Timeline.d.ts +7 -5
- package/types/generated/modules/water/Water.d.ts +1 -0
- package/types/generated/modules/weather/Weather.d.ts +14 -16
- package/types/generated/modules/weather/weatherDraw.d.ts +3 -3
- package/types/generated/modules/world/World.d.ts +11 -7
- package/types/generated/render/PostFX.d.ts +21 -23
- package/types/generated/render/materials.d.ts +1 -0
- package/types/generated/render/occlusion.d.ts +9 -0
- package/types/generated/render/patches.d.ts +1 -0
- package/types/generated/ui/Focus.d.ts +1 -0
- package/types/generated/ui/UI.d.ts +1 -0
- package/types/nav.d.ts +47 -15
- package/types/physics.d.ts +150 -73
- package/types/pixel.d.ts +75 -0
- package/types/tsl.d.ts +37 -4
- package/types/world.d.ts +48 -75
- package/ui/Focus.js +10 -9
- package/ui/Parts.js +13 -5
- package/ui/UI.js +7 -7
- package/ui/defaults.js +3 -2
- package/ui/theme.js +7 -5
- package/core/assetEntry.js +0 -109
- package/core/engineCamera.js +0 -32
- package/core/ground.js +0 -104
- package/core/holds.js +0 -134
- package/core/math.js +0 -48
- package/core/moduleSlots.js +0 -100
- package/core/modules.js +0 -314
- package/core/saveApply.js +0 -210
- package/core/saveValues.js +0 -46
- package/core/session.js +0 -174
- package/core/shadowTypes.js +0 -16
- package/core/util.js +0 -17
- package/core/view.js +0 -43
- package/docs/MIGRATING-0.3.md +0 -248
- package/docs/MIGRATING-0.4.md +0 -320
- package/docs/MIGRATING-0.5.md +0 -68
- package/docs/MIGRATING-0.6.md +0 -126
- package/docs/PERF.md +0 -245
- package/docs/recipes/36-sky-ground-plants.md +0 -158
- package/docs/recipes/37-terrain-hooks.md +0 -115
- package/docs/recipes/38-environment-hooks.md +0 -67
- package/docs/recipes/42-terrain-shape.md +0 -64
- package/docs/recipes/47-island-snow-backdrop.md +0 -43
- package/docs/recipes/54-three-idioms.md +0 -88
- package/examples/plain-picture/FINDINGS.md +0 -53
- package/examples/sheepisland/.threedog/content-index.json +0 -1
- package/modules/camera/projection.js +0 -21
- /package/core/{mulberry32.js → base/mulberry32.js} +0 -0
- /package/core/{inputDefaults.js → input/inputDefaults.js} +0 -0
- /package/core/{textureBytes.js → inspect/textureBytes.js} +0 -0
- /package/core/{actor.js → ops/actor.js} +0 -0
- /package/core/{opsHistory.js → ops/opsHistory.js} +0 -0
- /package/core/{saveIds.js → saves/saveIds.js} +0 -0
- /package/core/{screenToGround.js → scene/screenToGround.js} +0 -0
- /package/core/{cells.js → stream/cells.js} +0 -0
- /package/core/{streamCells.js → stream/streamCells.js} +0 -0
- /package/core/{pureWorker.js → threads/pureWorker.js} +0 -0
- /package/examples/{sheepisland → perf-island}/content/index.js +0 -0
- /package/examples/{sheepisland → perf-island}/content/props.js +0 -0
- /package/examples/{sheepisland → perf-island}/content/templates.js +0 -0
- /package/examples/{sheepisland → perf-island}/content/vegetation.js +0 -0
- /package/examples/{sheepisland → perf-island}/picture/lights.js +0 -0
- /package/examples/{sheepisland → perf-island}/picture/materials.js +0 -0
- /package/examples/{sheepisland → perf-island}/picture/sky.js +0 -0
|
@@ -1,19 +1,19 @@
|
|
|
1
1
|
# The whole picture in plain three.js: signals in, picture out
|
|
2
2
|
|
|
3
|
-
**In this recipe**: the `picture/` folder (0), setup (1), signals (2), the hook (3), rules for a bigger game (3b), wiring and who wrote a value (3c), the library (3d), shared values (
|
|
4
|
-
picture parts: code from different sources in one game (
|
|
3
|
+
**In this recipe**: the `picture/` folder (0), setup (1), signals (2), the hook (3), rules for a bigger game (3b), wiring and who wrote a value (3c), the library (3d), shared values (3e),
|
|
4
|
+
picture parts: code from different sources in one game (3f), a flat look (4), pixel art, pixel-perfect camera and sprites (4b), what the engine still does (5), checking (6).
|
|
5
5
|
|
|
6
6
|
Any picture (flat illustration, toon, painterly, realistic) can be written as plain three.js in one folder of the game, the picture code: its own
|
|
7
7
|
lights, materials, fog, sky colors and post passes. The engine hands it signals (time of day, weather) and keeps doing the engineering
|
|
8
8
|
(streaming, shadows, saves, tests); it writes none of the picture's values. Working example: `examples/plain-picture/` (page `/plain-picture.html`,
|
|
9
|
-
a night street in a flat-illustration look; `picture/` is the whole picture
|
|
9
|
+
a night street in a flat-illustration look; `picture/` is the whole picture). Every value has one writer, a line in your code, so
|
|
10
10
|
"why is this wall black" has one place to look.
|
|
11
11
|
|
|
12
12
|
## 0. The `picture/` folder
|
|
13
13
|
`threedog new-game` generates it, with a gray start; it is yours to change or delete. One file per job, so the picture never piles up in one place:
|
|
14
14
|
```
|
|
15
15
|
picture/
|
|
16
|
-
index.js wiring: creates the parts, calls each part's update(signals) in one engine.onRender; no values here
|
|
16
|
+
index.js wiring: the picture module (engine.use(createPicture()), then engine.picture): creates the parts, calls each part's update(signals) in one engine.onRender; no values here
|
|
17
17
|
palette.js colors and key values for the whole game, including the tone curve
|
|
18
18
|
lights.js lights: the mapping from signals to lights
|
|
19
19
|
materials.js materials by name; other code asks for picture.materials.wall and never builds its own
|
|
@@ -22,16 +22,17 @@ picture/
|
|
|
22
22
|
shaders/*.glsl your shader code; saving one hot-reloads it
|
|
23
23
|
areas/<name>.js a large game's overrides for one area (a cave, an interior): only what differs
|
|
24
24
|
```
|
|
25
|
-
To add a part, write a file that returns `{ update(signals) }` and call it from `index.js
|
|
25
|
+
To add a part, write a file that returns `{ update(signals) }` and call it from `index.js`, handing it the module's `ctx` so what it adds leaves with the picture:
|
|
26
26
|
```js
|
|
27
27
|
// picture/sky.js: the engine's dome stays, fog is the game's
|
|
28
|
-
export function createSky(engine) {
|
|
29
|
-
|
|
30
|
-
|
|
28
|
+
export function createSky(engine, ctx) {
|
|
29
|
+
const fog = new THREE.Fog(palette.fog.color, palette.fog.near, palette.fog.far);
|
|
30
|
+
ctx.borrow(engine.scene, { fog });
|
|
31
|
+
return { update(s) { fog.color.copy(night).lerp(day, s.uDaylight.value); } };
|
|
31
32
|
}
|
|
32
33
|
// picture/post.js: engine.post.add takes a three.js Pass and keeps the chain in order (recipe 52)
|
|
33
|
-
export function createPost(engine) {
|
|
34
|
-
engine.post.add(new ShaderPass(GrainShader), { name: 'grain' });
|
|
34
|
+
export function createPost(engine, ctx) {
|
|
35
|
+
ctx.track(engine.post.add(new ShaderPass(GrainShader), { name: 'grain' }));
|
|
35
36
|
return { update() {} };
|
|
36
37
|
}
|
|
37
38
|
```
|
|
@@ -56,20 +57,21 @@ Without `calendar` and `sky()` there is no day and night: `uDaylight` stays 1 an
|
|
|
56
57
|
| `uSunDir` | unit `Vector3` toward the sun | sky |
|
|
57
58
|
| `uSunColor` | `Color` of the sun now, from the keyframes (white with no sky): `sun.color.copy(...)` | sky |
|
|
58
59
|
| `uTimeOfDay` | 0-1 (0 midnight, 0.5 noon) | calendar, else the sky's fixed time |
|
|
59
|
-
| `uRain`, `uSnow`, `
|
|
60
|
+
| `uRain`, `uSnow`, `uWeatherCloud` | 0-1 | weather state |
|
|
60
61
|
| `uWind` | wind multiplier (1 = calm) | weather state |
|
|
61
62
|
| `uWeatherLight`, `uWeatherFog` | multipliers (1 = clear): apply them to your own light and fog distance | weather state |
|
|
62
63
|
| `uViewDistance` | how far the world is meant to be seen, meters (default 600): your fog's far; the stream radius without terrain | `terrain({ viewFog: true })` |
|
|
63
|
-
| `uFoliageTint`, `uGroundTint`, `
|
|
64
|
+
| `uFoliageTint`, `uGroundTint`, `uGroundCover` | season tints, snow cover | sky + calendar |
|
|
64
65
|
| `uSkyTop`, `uSkyHorizon` | the engine dome's colors (its neutral keyframes unless the game sets them) | sky |
|
|
65
66
|
|
|
66
67
|
Read `.value` in JS, or share the object in a shader (`uniforms: { uDaylight: engine.uniforms.uDaylight }`): one object, no copy. The sky
|
|
67
|
-
colors are the engine dome's picture, not physics: a styled game keeps its own palette and mixes them in only if it wants (the
|
|
68
|
-
of the horizon). Gameplay that should change the picture (a cutscene dims the world, a status effect tints it) goes through a signal of your
|
|
68
|
+
colors are the engine dome's picture, not physics: a styled game keeps its own palette and mixes them in only if it wants. Gameplay that should change the picture (a cutscene dims the world, a status effect tints it) goes through a signal of your
|
|
69
69
|
own, read by the picture code, so the picture still has one writer.
|
|
70
70
|
|
|
71
|
+
Written every frame: `uSkyTop` and `uSkyHorizon` take `engine.sky.top` / `engine.sky.horizon`, `uDaylight` and `uTimeOfDay` take a `daylight` / `timeOfDay` measure; a direct write is lost and warns once (`signal-overwritten`). `uSunDir` (the same vector as `engine.sky.sunDir`) and `camera.aspect` stay as written: `engine.autoView.manual('sunDir', false)` gives one back.
|
|
72
|
+
|
|
71
73
|
## 3. The hook: `engine.onRender`, not `onFrame`
|
|
72
|
-
```js
|
|
74
|
+
```js fragment
|
|
73
75
|
const sun = new THREE.DirectionalLight(0xffffff, 2), hemi = new THREE.HemisphereLight(); // made once in picture/lights.js
|
|
74
76
|
engine.onRender(() => {
|
|
75
77
|
const day = engine.uniforms.uDaylight.value, rain = engine.uniforms.uRain.value;
|
|
@@ -82,10 +84,10 @@ engine.onRender(() => {
|
|
|
82
84
|
`onRender` (default `'before'`) runs once per drawn frame after every module updated, so it reads this frame's signals. `onFrame` runs before
|
|
83
85
|
the modules' frame hooks: it would read last frame's values (and noon on the very first frame). Picture code uses `onRender` only.
|
|
84
86
|
|
|
85
|
-
## 3b.
|
|
87
|
+
## 3b. Rules that keep the folder working in a bigger game
|
|
86
88
|
- **One object's state goes through a name `picture/` exports.** Signals are global, but one street lamp shot out or one flickering sign is not. Gameplay calls
|
|
87
89
|
a name of your own and never touches the light or the material:
|
|
88
|
-
```js
|
|
90
|
+
```js fragment
|
|
89
91
|
// picture/index.js
|
|
90
92
|
export const picture = { lights, materials, lamp: id => ({ off() { lamps.get(id).intensity = 0; } }) };
|
|
91
93
|
// gameplay
|
|
@@ -96,7 +98,6 @@ the modules' frame hooks: it would read last frame's values (and noon on the ver
|
|
|
96
98
|
on WebGPU stops at start and names itself. A `--webgl` game writes GLSL (recipe 43).
|
|
97
99
|
- **The picture reads the quality tier.** The engine cannot hold your code to it, so read `engine.tier` (`'low'` | `'high'`) for what costs: shadow map size,
|
|
98
100
|
real light count, post effects. The generated `lights.js` sizes its shadow map this way.
|
|
99
|
-
- **A large world:** `engine.shadows.cascades(sun, { count: 3 })` on your own light gives sharp near shadows and wide far ones (recipe 45); low tier falls back to one map.
|
|
100
101
|
|
|
101
102
|
## 3c. Wiring `picture/` parts
|
|
102
103
|
- **One `engine.onRender`, in `picture/index.js`.** It calls each part's `update(signals)` and holds no values. A part never adds its own hook: two hooks hide the order.
|
|
@@ -106,17 +107,20 @@ the modules' frame hooks: it would read last frame's values (and noon on the ver
|
|
|
106
107
|
- **Several steps in one function are fine** (`fog.color.copy(a); fog.color.lerp(b, t);`), and so is one state of the game writing a value that another state wrote in earlier frames.
|
|
107
108
|
|
|
108
109
|
Under the dev server (`npm run dev`, `threedog snap`) the engine records which line last changed each value:
|
|
109
|
-
```js
|
|
110
|
-
engine.describe('picture').picture.writers // { values: { 'fog.far': { at: 'picture/sky.js:12', framesAgo: 3 }, 'light:sun.intensity': ... }, conflicts: [...] }
|
|
111
|
-
engine.explain({
|
|
110
|
+
```js fragment
|
|
111
|
+
engine.describe('picture').picture.writers // the state at a glance, every value at once: { values: { 'fog.far': { at: 'picture/sky.js:12', framesAgo: 3 }, 'light:sun.intensity': ... }, conflicts: [...] }
|
|
112
|
+
engine.explain({ value: 'fog.far' }) // who wrote it, its last writers with frames (detail.history), a fight if one was seen, and the fix
|
|
113
|
+
engine.debug.watch('boss.hp', boss, 'hp') // any other value, by a name you choose; a Color, Vector or rotation is watched inside
|
|
112
114
|
```
|
|
113
115
|
Names are `renderer.toneMapping`, `renderer.toneMappingExposure`, `scene.fog`, `fog.near | far | density | color`, `scene.environment`, `scene.environmentIntensity`,
|
|
114
|
-
`scene.background`, `scene.backgroundIntensity`, `light:<name>.intensity | color | groundColor | position`, `material:<name>.color | emissive | opacity | emissiveIntensity
|
|
116
|
+
`scene.background`, `scene.backgroundIntensity`, `light:<name>.intensity | color | groundColor | position`, `material:<name>.color | emissive | opacity | emissiveIntensity`,
|
|
117
|
+
every id in `describe().owned` (when the engine yields, the warning and `writtenAt` name the line that took the value; an id with no plain property, like `view.pixelRatio`, answers `not tracked`), and any shared point's name.
|
|
115
118
|
`framesAgo` is how old the answer is: a value written every frame is looked at about twice a second, and `writtenSince: true` means it moved after that picture. Anything else,
|
|
116
119
|
a value set before it entered the scene, a console write, a bundled build (`threedog shot`, `npm test`), answers `not tracked` with the reason. Nothing is ever blocked.
|
|
120
|
+
Only watched values are seen, and a write that leaves a value unchanged is not, so seeing no conflict is not proof there is none.
|
|
117
121
|
|
|
118
|
-
**A conflict
|
|
119
|
-
|
|
122
|
+
**A conflict hint** is one line: `fog.far: two writers in one frame, picture/sky.js:14 and picture/rival.js:3; the last write stands`, and `engine.explain({ value: 'fog.far' })` has the history and the fix.
|
|
123
|
+
Two writers that never share a frame but keep overwriting each other read `taking turns across frames`; one state handing a value to another does not count. One line's work never reaches the screen. Decide which part owns the value, delete the other write, or turn it into a signal or a shared value the owner reads. It warns once per value.
|
|
120
124
|
Both writes going through a shared helper count as one place, the helper's line: the warning cannot see past it.
|
|
121
125
|
|
|
122
126
|
## 3d. Save to the library, pull it out
|
|
@@ -128,9 +132,8 @@ threedog lib list flat # next game: look b
|
|
|
128
132
|
threedog lib pull flat-materials # lands in picture/ (a .glsl lands in picture/shaders/)
|
|
129
133
|
```
|
|
130
134
|
A picture entry is **one plain three.js file that exports a function**, so it has to stand alone. `lib add` refuses a file that imports its siblings
|
|
131
|
-
(`./palette.js`) and names them; the entry would arrive as a half. Take the numbers as parameters instead
|
|
132
|
-
|
|
133
|
-
```js
|
|
135
|
+
(`./palette.js`) and names them; the entry would arrive as a half. Take the numbers as parameters instead:
|
|
136
|
+
```js fragment
|
|
134
137
|
/** Flat materials by name: a flat color plus an emissive copy of it that rises at night.
|
|
135
138
|
* @param {object} THREE three.js @param {Record<string, number>} palette name → hex @param {number} nightGlow emissive at full night */
|
|
136
139
|
export function flatMaterials(THREE, palette, nightGlow = 0.2) {
|
|
@@ -142,13 +145,12 @@ export function flatMaterials(THREE, palette, nightGlow = 0.2) {
|
|
|
142
145
|
} };
|
|
143
146
|
}
|
|
144
147
|
```
|
|
145
|
-
A day-and-night light group is the same shape: `dayNightLights(THREE, scene, { day, night })
|
|
146
|
-
hemisphere light, and its `update(signals)` blends them by `uDaylight`. The copy in your game is yours: pull, then adapt it to that game's picture.
|
|
148
|
+
A day-and-night light group is the same shape: `dayNightLights(THREE, scene, { day, night })`. The copy in your game is yours: pull, then adapt it to that game's picture.
|
|
147
149
|
|
|
148
|
-
##
|
|
150
|
+
## 3e. Several parts change one picture value
|
|
149
151
|
A sunset and a cutscene both dim the sun. If each writes the light, the second one's end brings back a value that is already wrong. Make the value a shared point
|
|
150
152
|
(recipe 55): everyone changes it with `engine.mod`, and one place in `picture/` reads the result and writes three.js once.
|
|
151
|
-
```js
|
|
153
|
+
```js fragment
|
|
152
154
|
// picture/lights.js: the one writer
|
|
153
155
|
const level = engine.stacks.define('sun.level', { base: 1, min: 0, save: false });
|
|
154
156
|
const sun = new THREE.DirectionalLight(0xffffff, 2);
|
|
@@ -162,27 +164,28 @@ dusk.remove();
|
|
|
162
164
|
An amount that moves takes one entry and changes it: `const wet = ctx.mod('sun.level', { mul: 1 });` once in the install, then `wet.change(1 - 0.5 * rain)` each frame. Calling `ctx.mod` every frame would pile up entries. In a module use `ctx.mod`, not `engine.mod`: the change then goes with the module.
|
|
163
165
|
`describe().shared` shows who holds it and why it reads what it reads. A value only one part writes needs none of this: write the light.
|
|
164
166
|
|
|
165
|
-
##
|
|
166
|
-
|
|
167
|
+
## 3f. Picture parts: three.js code from different sources in one game
|
|
168
|
+
The `picture/` folder of section 0 is one part holding the whole look, with slot `picture`. Use smaller parts when code has to live beside code you did not write: an entry from the library,
|
|
167
169
|
another agent's sky, a rain from an old game. A part is an ordinary module with `type: 'picture'`. There is no new layer and no new way to write a picture: inside it is plain three.js.
|
|
168
|
-
```js
|
|
170
|
+
```js fragment
|
|
169
171
|
// picture/harbor-fog.js
|
|
170
172
|
import * as THREE from 'three';
|
|
171
173
|
|
|
172
174
|
export const harborFog = ({ near = 10, far = 200 } = {}) => ({
|
|
173
175
|
name: 'harborFog', type: 'picture', provides: ['fog'],
|
|
174
176
|
install(e, ctx) {
|
|
175
|
-
e.scene
|
|
177
|
+
ctx.borrow(e.scene, { fog: new THREE.Fog(0x667788, near, far) }); // given back when the part goes
|
|
176
178
|
const flare = new THREE.PointLight(0xffaa66, 2, 30);
|
|
177
179
|
e.scene.add(flare);
|
|
178
180
|
ctx.track(e.onRender(() => { // reads signals, writes three.js
|
|
179
181
|
e.scene.fog.far = far * (1 - 0.6 * e.uniforms.uRain.value);
|
|
180
182
|
flare.intensity = 2 * (1 - e.uniforms.uDaylight.value);
|
|
181
183
|
}));
|
|
182
|
-
ctx.track({ remove() { e.scene.remove(flare); flare.dispose();
|
|
184
|
+
ctx.track({ remove() { e.scene.remove(flare); flare.dispose(); } }); // what it added goes with it
|
|
183
185
|
},
|
|
184
186
|
});
|
|
185
187
|
```
|
|
188
|
+
`ctx.borrow(obj, values)` writes properties on something the part does not own (`scene.fog`, `renderer.toneMapping`, the engine dome's `visible`) and restores them when the part goes or is disabled after an error, or on the handle's `remove()`. A value goes back only if it is still what the borrow wrote, so a fog the game set meanwhile stands. One property has one holder: a second borrow of it is refused, so a value several parts want goes on a shared point (`engine.mod`).
|
|
186
189
|
`engine.use(harborFog())` installs it, `engine.unuse('harborFog')` removes it, and `engine.use(otherFog(), { replaces: 'fog' })` swaps it. A part may use its own hooks: the single
|
|
187
190
|
`engine.onRender` of 3c is how one author keeps one folder in order, and two parts from two sources have no shared wiring file.
|
|
188
191
|
|
|
@@ -190,7 +193,7 @@ export const harborFog = ({ near = 10, far = 200 } = {}) => ({
|
|
|
190
193
|
| Kind | Example | Rule | On a collision |
|
|
191
194
|
|---|---|---|---|
|
|
192
195
|
| Only one can exist | the fog, the tone curve, the main light | take a slot: `provides: ['fog']` | a second claim stops at install (`shared-taken`); `{ replaces: 'fog' }` swaps on purpose |
|
|
193
|
-
| Several parties change it | rain and a cutscene both dim the sun | a shared value: `engine.stacks.define` and `engine.mod` (
|
|
196
|
+
| Several parties change it | rain and a cutscene both dim the sun | a shared value: `engine.stacks.define` and `engine.mod` (3e), one place writes three.js | combined by the formula |
|
|
194
197
|
| Just more things | another lamp, another mesh | add it | none, it only costs budget |
|
|
195
198
|
|
|
196
199
|
**The slot names**, so two sources spell a claim the same way (`PICTURE_SLOTS`, type `PictureSlot`). Slot names are free text, and a near miss of these in a picture module is warned about:
|
|
@@ -208,7 +211,7 @@ A part that needs another one says `requires: ['sun']`. A shared value a part de
|
|
|
208
211
|
**What the dev server reports** (`npm run dev`, `threedog snap`). It observes and blocks nothing; a bundled build has none of it. `describe('picture').picture.slots` shows who holds what, in every build.
|
|
209
212
|
- `picture-held`: a value in a held slot was written by anyone else, in any frame. It names the holder, the writer and both lines. Fix: delete the write, swap the holder, or make it a shared value.
|
|
210
213
|
In `picture.writers.values`, a held value says `writer: 'holder'` or `writer: 'stray'`; `picture.writers.held` lists the strays.
|
|
211
|
-
- `picture-conflict`: two places wrote one value in one frame (3c), with the part names when they are parts.
|
|
214
|
+
- `picture-conflict`: two places wrote one value in one frame or kept taking turns (3c), with the part names when they are parts.
|
|
212
215
|
- `picture-leftover`: a part went and left lights, objects, post effects, frame callbacks, or the fog, environment or background it wrote. It names each with its line; `picture.writers.leftovers` lists them.
|
|
213
216
|
`ctx.track` only removes what it was handed, so anything else needs a `remove()` or the part's `dispose()`.
|
|
214
217
|
|
|
@@ -217,9 +220,16 @@ not named `'sun'`. Nothing here sees that a warm lamp clashes with a cold sea: t
|
|
|
217
220
|
|
|
218
221
|
**When not to bother:** one author, one game, a `picture/` folder that works. Turn a file into a part when another source arrives, not before.
|
|
219
222
|
|
|
223
|
+
**Switching the whole look at run time.** Keep each look as a module holding `picture` and whatever other slots it writes (`provides: ['picture', 'tone', 'fog', 'sun']`), then:
|
|
224
|
+
```js fragment
|
|
225
|
+
engine.use(duskPicture(), { replaces: 'picture' }); // the old look's lights, hooks, post effects and borrowed values go first
|
|
226
|
+
for (const m of myMeshes) m.material = engine.picture.materials[m.userData.surface];
|
|
227
|
+
```
|
|
228
|
+
The old materials are disposed, and the engine cannot know which of your meshes hold them: **a mesh holding an old look's material must take the new one**, by name as above. Everything the look added itself leaves with it, as long as it went through `ctx`.
|
|
229
|
+
|
|
220
230
|
## 4. A flat illustration (one way among many)
|
|
221
231
|
Light alone turns a warm wall under a cool night fill into mud. An illustrator keeps each surface its own color and only shifts it:
|
|
222
|
-
- `MeshLambertMaterial({ color: c, emissive: c, emissiveIntensity: 0 })`: raise the emissive copy at night
|
|
232
|
+
- `MeshLambertMaterial({ color: c, emissive: c, emissiveIntensity: 0 })`: raise the emissive copy at night, so faces
|
|
223
233
|
keep their hue; or `MeshBasicMaterial` and pick each face's shade yourself (vertex colors by normal); or `MeshToonMaterial` with a `gradientMap`.
|
|
224
234
|
- A warm `HemisphereLight` at night instead of a blue one; the night reads from the sky, the windows and the lamps, not from tinting walls blue.
|
|
225
235
|
- `NoToneMapping` so the colors come out as written.
|
|
@@ -229,6 +239,86 @@ Light alone turns a warm wall under a cool night fill into mud. An illustrator k
|
|
|
229
239
|
environment map comes out too dark on faces away from the sun: raise the ambient, add an `AmbientLight`, or generate an environment (`engine.sky.environment()`).
|
|
230
240
|
`uWeatherLight` is sized for the sun: multiplying ambient by it as well darkens rain more than the sun alone does, so give ambient a share of it.
|
|
231
241
|
|
|
242
|
+
## 4b. Pixel art: low-resolution rendering with sharp scaling
|
|
243
|
+
Pixel art means drawing fewer pixels and then keeping every edge hard when they are enlarged. One engine option does the screen side:
|
|
244
|
+
- **`createEngine({ pixelSize: k })`, or `engine.setPixelSize(k)` during play.** One art pixel is k real screen pixels, every one the same width at any display scale, and it stays so through a page zoom or a move to another display. The canvas gets `image-rendering: pixelated`, and `antialias` defaults to off (it blends the edges you want hard, and can only be set at creation: passing `antialias: true` warns). A whole number of art pixels rarely fills the canvas, so the last few real pixels at the right and bottom, fewer than k, stay empty and show the page behind; the box the page laid out does not change. `engine.setPixelSize(null)` turns it off.
|
|
245
|
+
- **Nothing else changes the size while it is on.** Adaptive resolution stops, and the quality tier leaves the ratio alone. `engine.setPixelRatio` throws `pixel-conflict`, and so does `createEngine` given `pixelRatio` or `adaptiveResolution: true` as well. `engine.photo.take()` keeps the art pixels: the picture is the drawing buffer's size, whatever its `scale`. A direct `renderer.setPixelRatio` still wins, as everywhere in three.js: the engine stops fitting the canvas (recipe 52).
|
|
246
|
+
- **The menu follows.** While it is on the settings menu has no render scale or adaptive row, and no preset or stored value moves the ratio. The anti-aliasing row would still blend edges: leave it out where the game lists its tabs, `settings({ sections: [{ id: 'graphics', omit: ['antialias'] }, 'audio', 'controls', 'language', 'saves'] })`: an omitted row stays your value, and no preset or stored value moves it.
|
|
247
|
+
- **Sample sharply.** `engine.assets.texture(name, { pixelated: true })` sets `NearestFilter` for enlarging and `NearestMipmapNearestFilter` for shrinking. On a texture of
|
|
248
|
+
your own, set `magFilter` and `minFilter` to `THREE.NearestFilter`.
|
|
249
|
+
```js
|
|
250
|
+
const engine = createEngine({ canvas: document.querySelector('canvas'), pixelSize: 3 });
|
|
251
|
+
```
|
|
252
|
+
Whatever blends neighbouring pixels works against the look, so judge each post effect and any tone curve (section 4) by eye. Text and panels under `engine.uiRoot` are page elements and stay at screen
|
|
253
|
+
resolution. Objects that move by less than an art pixel shimmer; `pixelSnap` and `pixelSprite` below deal with that. `describe().render.scale.pixelSize` reports k.
|
|
254
|
+
|
|
255
|
+
**A pixel-perfect camera.** `pixelSnap` on `followCamera` or `fixedCamera` rounds the camera to the art grid on the screen's own axes, so a turned or isometric view works. It is orthographic only. A perspective camera throws `camera-option`.
|
|
256
|
+
```js fragment
|
|
257
|
+
engine.use(followCamera({ projection: 'orthographic', yaw: Math.PI / 4, pitch: 0.6, lockPitch: true, mouseLook: false,
|
|
258
|
+
pixelSnap: { pixelsPerMeter: 32, bounds: { minX: -20, maxX: 20, minZ: -20, maxZ: 20 } } }));
|
|
259
|
+
```
|
|
260
|
+
- **`pixelsPerMeter` decides the view height.** The view must show buffer height / `pixelsPerMeter` world units, or the grid and the picture disagree, so `pixelSnap` sets it, also after a resize. `size` with `pixelSnap` throws `pixel-conflict`; on `fixedCamera` every shot says `projection: 'orthographic'` and has no `size`. The wheel does not zoom: `engine.setPixelSize(k)` is the zoom that keeps art pixels whole, and it needs nothing else. If the game writes `camera.zoom` or `orthoSize` itself, a `pixel-conflict` warning says so, rounding stops, and `describe().camera.pixelSnap.agrees` reads `false` until it is put back.
|
|
261
|
+
- **`bounds`** is a world rectangle (`minY` and `maxY` are optional, 0 by default). The camera does not show past it. It is projected on the screen's axes and rounded inward, the true position is clamped, and only then rounded, so sliding along a bound stays on whole art pixels. On an axis where the level is smaller than the view, the camera centers. Turning the view changes the screen rectangle: at 45 degrees of yaw it is a box around a diamond, so the view can show the empty corners outside the level. Fill them with something, or keep the yaw near a multiple of 90 degrees.
|
|
262
|
+
- **Turns.** The grid is read fresh each frame, so a turn or a new `pixelSize` needs no reset. While the view is turning, nothing can hold still on a grid that turns with it; a `track: true` shot on `fixedCamera` turns all the time.
|
|
263
|
+
- **A cutscene** holding `engine.takeCamera` is not rounded.
|
|
264
|
+
- **The leftover.** `engine.cameraRig.pixelSnap.error` is the last rounding in art pixels on each screen axis. It is there for a game that wants to do something with it, such as sliding the final image for smooth scrolling. The engine does not do that.
|
|
265
|
+
|
|
266
|
+
**The grid on its own.** `threedog/pixel` is math and plain three.js objects, with no look of its own. `engine.cameraRig.pixelSnap.grid` is the camera's grid; `pixelGrid({ camera, pixelsPerMeter })` makes one for a camera of yours. `snap(world)` rounds a point on the screen's axes and keeps its depth, `error(world)` says by how much, `toScreen` and `toWorld` convert, and `axes()` gives right, up and forward. Round a drawn position with these, not by hand: never move what physics or a save reads.
|
|
267
|
+
|
|
268
|
+
**Sprites in a 3D view: `pixelSprite`.** It returns a plain `THREE.Mesh` with your material: a vertical plane that turns around Y with the camera's forward direction. Its height is stretched by `1 / cos(pitch)`, which the tilt of the view takes back, so one texel is one art pixel.
|
|
269
|
+
```js fragment
|
|
270
|
+
import { pixelSprite, spriteFrame } from 'threedog/pixel';
|
|
271
|
+
const hero = pixelSprite({ grid: engine.cameraRig.pixelSnap.grid, material, width: 16, height: 24, columns: 4, rows: 3, anchor: [0.5, 0], snap: 'followed' });
|
|
272
|
+
spriteFrame(hero, 5, true); // frame 5 of the sheet, mirrored
|
|
273
|
+
```
|
|
274
|
+
- Frames count left to right, top to bottom, and `width` and `height` are one frame in texels. The material is yours: set `alphaTest` for hard edges, and a nearest filter on its texture. The mesh goes in the scene, or is handed to a character as its `model` (recipe 13 section 3c). `mesh.position` stays exact; only the drawn matrix is rounded.
|
|
275
|
+
- `snap: 'world'` (the default) rounds the drawn position to the grid: use it for anything that stands or walks on its own. `snap: 'followed'` is for the one object the camera follows: rounding a follower and its camera separately makes them step on different frames, a one-pixel shake, so this one takes the camera's rounding. On anything else it would creep against the ground.
|
|
276
|
+
- Standing upright is what keeps a head out of the wall behind it: the whole figure has the depth of its feet, so no shader is needed. A plane tilted toward the camera would lean back through that wall. One case still cuts: a wall not parallel to the sprite, with the feet nearer to it than `(sprite width / 2) * |sin(angle between them)|`. Keep the collision radius above that.
|
|
277
|
+
|
|
278
|
+
**Lighting a sprite from its silhouette.** A flat plane lights flat. A normal map made from the sprite's own outline gives it a rounded edge, with no drawing work: the height is the distance from each texel to the nearest transparent one, then blurred, and the normal is its slope. This is one way among many; a hand-painted normal map goes in the same slot.
|
|
279
|
+
```js fragment
|
|
280
|
+
// picture/spriteNormals.js
|
|
281
|
+
import * as THREE from 'three';
|
|
282
|
+
export function silhouetteNormals(image, frameWidth, frameHeight, { strength = 1.5, blur = 1 } = {}) {
|
|
283
|
+
const W = image.width, H = image.height, ctx = Object.assign(document.createElement('canvas'), { width: W, height: H }).getContext('2d', { willReadFrequently: true });
|
|
284
|
+
ctx.drawImage(image, 0, 0);
|
|
285
|
+
const alpha = ctx.getImageData(0, 0, W, H).data, out = new Uint8Array(W * H * 4), w = frameWidth, h = frameHeight;
|
|
286
|
+
for (let fy = 0; fy < H; fy += h) for (let fx = 0; fx < W; fx += w) { // each frame alone: neighbouring frames must not change its outline
|
|
287
|
+
const inside = (x, y) => x >= 0 && y >= 0 && x < w && y < h && alpha[((fy + y) * W + fx + x) * 4 + 3] > 127;
|
|
288
|
+
const d = new Float32Array(w * h), at = (a, x, y) => (x < 0 || y < 0 || x >= w || y >= h ? 0 : a[y * w + x]);
|
|
289
|
+
for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) d[y * w + x] = inside(x, y) ? 1e6 : 0;
|
|
290
|
+
const pass = (x, y, s) => { // two sweeps of a chamfer distance: plenty for sprite-sized frames
|
|
291
|
+
const v = Math.min(d[y * w + x], at(d, x - s, y) + 1, at(d, x, y - s) + 1, at(d, x - s, y - s) + 1.414, at(d, x + s, y - s) + 1.414);
|
|
292
|
+
d[y * w + x] = v;
|
|
293
|
+
};
|
|
294
|
+
for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) pass(x, y, 1);
|
|
295
|
+
for (let y = h - 1; y >= 0; y--) for (let x = w - 1; x >= 0; x--) pass(x, y, -1);
|
|
296
|
+
let height = d;
|
|
297
|
+
for (let i = 0; i < blur; i++) {
|
|
298
|
+
const next = new Float32Array(w * h);
|
|
299
|
+
for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) {
|
|
300
|
+
let sum = 0;
|
|
301
|
+
for (let j = -1; j <= 1; j++) for (let k = -1; k <= 1; k++) sum += at(height, x + k, y + j);
|
|
302
|
+
next[y * w + x] = sum / 9;
|
|
303
|
+
}
|
|
304
|
+
height = next;
|
|
305
|
+
}
|
|
306
|
+
for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) {
|
|
307
|
+
const dx = (at(height, x + 1, y) - at(height, x - 1, y)) * strength, dy = (at(height, x, y - 1) - at(height, x, y + 1)) * strength; // y: rows run down, a normal's y runs up
|
|
308
|
+
const l = Math.hypot(dx, dy, 1), o = ((H - 1 - fy - y) * W + fx + x) * 4; // a DataTexture's first row is the bottom
|
|
309
|
+
out.set([(-dx / l * 0.5 + 0.5) * 255, (-dy / l * 0.5 + 0.5) * 255, (1 / l * 0.5 + 0.5) * 255, 255], o);
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
const t = new THREE.DataTexture(out, W, H);
|
|
313
|
+
t.magFilter = t.minFilter = THREE.NearestFilter; // hard art pixels, and no mipmaps: they would mix neighbouring frames
|
|
314
|
+
t.generateMipmaps = false;
|
|
315
|
+
t.colorSpace = THREE.NoColorSpace; // numbers, not colours: an sRGB read would bend every normal
|
|
316
|
+
t.needsUpdate = true;
|
|
317
|
+
return t;
|
|
318
|
+
}
|
|
319
|
+
```
|
|
320
|
+
Give it to the sprite's material as `normalMap`, on a lit material such as `MeshStandardMaterial`, next to the sheet it was made from. Measured on WebGL and on real WebGPU: a side light brightens the near half about twice as much as the far half. A sprite mirrored with `spriteFrame` lights the right way round with no change, because three.js takes the tangent direction from the UVs. A light straight overhead is the weak case. The plane's own normal is horizontal, so without a normal map the sprite goes black, and with one only its upper half lights. Add an ambient or hemisphere light, or keep the main light in front of the view.
|
|
321
|
+
|
|
232
322
|
## 5. What the engine still does with all of this off
|
|
233
323
|
- `scene.background` starts as a neutral gray: write your own color or sky.
|
|
234
324
|
- `renderer.shadowMap.enabled` is on; nothing casts until your lights do.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Third-person start: walking, camera, save, pause, menu
|
|
2
2
|
|
|
3
|
-
**In this recipe**: 1. About twenty lines · 2. What each line gives · 3. Where it stops · 4. Talk, press E, a quest, a counter · 5. Not worth it for a small game
|
|
3
|
+
**In this recipe**: 1. About twenty lines · 2. What each line gives · 3. Where it stops · 4. Talk, press E, a quest, a counter · 5. Not worth it for a small game · 6. A model made in code, placed in content
|
|
4
4
|
|
|
5
5
|
The shortest working path for a game where a character walks around a place you built yourself. It is the blank template's `main.js` plus a few lines, on any
|
|
6
6
|
ground (`--open-world` adds generated terrain and a sky on top of the same parts). The picture stays plain three.js in `picture/`; nothing here touches it.
|
|
@@ -17,10 +17,11 @@ const engine = createEngine({ canvas: document.getElementById('view'), renderer:
|
|
|
17
17
|
ui: { loading: { title: 'Pier' }, title: { title: 'Pier' } }, saveKey: 'pier' }); // start screen: Continue (once a save exists), Start, Settings
|
|
18
18
|
engine.use(world(), content(), collision(), characters(), followCamera({ pointerLock: true }), hud(), settings({ freezeWorld: true }));
|
|
19
19
|
engine.saves.autosave(0.5); // every 30 s of play
|
|
20
|
-
|
|
20
|
+
engine.use(createPicture());
|
|
21
|
+
const { picture } = engine;
|
|
21
22
|
engine.collision.addBlocked((x, z) => Math.abs(x) > 3 || Math.abs(z) > 20); // the walkable shape: here a pier 6 m by 40 m
|
|
22
23
|
engine.characters.createPlayer({ ...presets.player.thirdPerson, spawn: [0, 0, 0] });
|
|
23
|
-
engine.content.load(data
|
|
24
|
+
engine.content.load(data);
|
|
24
25
|
|
|
25
26
|
const game = { score: 0 }; // the game's own state: plain values
|
|
26
27
|
engine.saves.register('game', { version: 1, save: () => ({ ...game }), load: d => { Object.assign(game, d); } });
|
|
@@ -49,7 +50,7 @@ Each part is one line to swap and none of them holds the rest back:
|
|
|
49
50
|
- Pictures past the start screen: `threedog shot --play`.
|
|
50
51
|
|
|
51
52
|
## 4. Talk, press E, a quest, a counter
|
|
52
|
-
Add `THREE, interactions, dialogue, quests` to the import and `interactions({ ...presets.interactions.nearest }), dialogue(), quests()` to `engine.use`; E is already bound in section 1 (any other key works: `interact: ['KeyF']`; with no key at all
|
|
53
|
+
Add `THREE, interactions, dialogue, quests` to the import and `interactions({ ...presets.interactions.nearest }), dialogue(), quests()` to `engine.use`; E is already bound in section 1 (any other key works: `interact: ['KeyF']`; with no key at all dev warns with the line to add). Then, before `engine.start()`:
|
|
53
54
|
```js
|
|
54
55
|
const guide = new THREE.Mesh(new THREE.CapsuleGeometry(0.4, 1, 4, 8), new THREE.MeshStandardMaterial({ color: 0xc89a5a })); // any three.js object
|
|
55
56
|
guide.position.set(0, 0.9, -8); engine.scene.add(guide);
|
|
@@ -65,7 +66,7 @@ engine.quests.define('pier', { title: 'The pier', steps: [
|
|
|
65
66
|
engine.quests.start('pier');
|
|
66
67
|
engine.hud.counter('coins', { label: 'Coins', value: 0 }); // call again with a new value to update it
|
|
67
68
|
```
|
|
68
|
-
Dialogue flags, quest progress and what `once` and `counter` did are saved by the modules: no `register` for them. An interaction's `counter` adds 1 to the HUD counter of that name (`hud.
|
|
69
|
+
Dialogue flags, quest progress and what `once` and `counter` did are saved by the modules: no `register` for them. An interaction's `counter` adds 1 to the HUD counter of that name (`hud.bump`); read the total with `engine.hud.value('coins')`, the one place it lives. A short popup message: `toast(engine, 'Picked up a shell')` (import `toast` from `threedog`; recipe 26 §3).
|
|
69
70
|
|
|
70
71
|
A content prop with `collide` blocks the follow camera with its whole mesh; a hand-written mesh blocks it only after `engine.rays.addStatic(mesh, { occluder: true })` (recipe 21).
|
|
71
72
|
|
|
@@ -75,3 +76,16 @@ Plain three.js and `engine.setGround` are the shorter road for the things below;
|
|
|
75
76
|
- Full terrain: a flat or gently rolling island is `engine.setGround({ height: (x, z) => ... })` plus meshes. `terrain()` is for large streamed worlds.
|
|
76
77
|
- The sky module for a fixed time of day: a background color or a gradient mesh and your own lights. `sky()` is for a day that changes.
|
|
77
78
|
- Rigid vehicles: a mesh that moves by your own rule needs no physics. `rigid()` is for things that must push, roll and collide.
|
|
79
|
+
|
|
80
|
+
## 6. A model made in code, placed in content
|
|
81
|
+
Any game, any genre: the shape is code, where it stands is content. The blank game ships one example, and it is neutral gray on purpose.
|
|
82
|
+
```js
|
|
83
|
+
// assets.js: a generator returns a geometry (drawn gray) or an Object3D; it runs once per name, every placement is a clone
|
|
84
|
+
const marker = () => new THREE.CylinderGeometry(0.2, 0.25, 1.2, 12).translate(0, 0.6, 0);
|
|
85
|
+
export default [{ name: 'starter', models: { marker } }];
|
|
86
|
+
```
|
|
87
|
+
```js
|
|
88
|
+
// content/props.js: placements, each with a stable id (saved with the game)
|
|
89
|
+
export default [{ id: 'marker-1', model: 'marker', x: 0, z: -2 }, { id: 'marker-2', model: 'marker', x: 3, z: -5 }];
|
|
90
|
+
```
|
|
91
|
+
`scene.add` at startup also works, but the model stays out of GAMEMAP and the save. `world.add` at startup makes a second copy after each load unless it has `{ save: false }`, and `npm run check` warns about that. A `.glb` registered under the same name later replaces the generator with no other change (recipe 05). Before building a model or an effect from scratch, `threedog lib list` and `threedog how "<words>"` also search the library.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Particles: dust, smoke, sparks, splashes
|
|
2
2
|
|
|
3
|
-
```js
|
|
3
|
+
```js fragment
|
|
4
4
|
import { particles } from 'threedog';
|
|
5
5
|
engine.use(particles({
|
|
6
6
|
default: { color: 0xc8b89a }, // what every effect starts from
|
|
@@ -11,25 +11,74 @@ engine.particles.define('smoke', { gravity: 0.4, size: [0.5, 2] });
|
|
|
11
11
|
const chimneySmoke = engine.particles.attach('smoke', chimney, { rate: 8, offset: [0, 2, 0] });
|
|
12
12
|
chimneySmoke.remove();
|
|
13
13
|
```
|
|
14
|
-
One effect is one `THREE.Points`, one draw call. Parameters and their fallbacks
|
|
14
|
+
One effect is one `THREE.Points`, one draw call. Parameters and their fallbacks: `api/particles.md`.
|
|
15
15
|
With no options an effect is a soft gray dot.
|
|
16
16
|
|
|
17
17
|
## Where a value comes from
|
|
18
18
|
Lowest to highest: the neutral fallback, `particles({ default })`, `particles({ effects: { name } })`, `define(name, params)`, then `overrides` of one
|
|
19
19
|
`emit` or `attach`. So the game's picture can sit in one table and a line of play code writes only what it decides: `define('leaves', { max: 200 })`.
|
|
20
20
|
|
|
21
|
+
## Values over life
|
|
22
|
+
`size`, `color` and `opacity` take one value, `[birth, death]`, or more stops: evenly spaced, or timed from 0 (birth) to 1 (death).
|
|
23
|
+
```js
|
|
24
|
+
engine.particles.define('flash', { size: [0.2, 1.5, 0.4] }); // evenly spaced
|
|
25
|
+
engine.particles.define('puff', { opacity: [[0, 0], [0.1, 0.7], [1, 0]] }); // fades in, then out
|
|
26
|
+
engine.particles.define('ember', { color: [[0, 0xffffff], [0.3, 0xffaa33], [1, 0x331100]] });
|
|
27
|
+
```
|
|
28
|
+
Before the first time and after the last, the end stop holds. A stop list in `overrides` belongs to that batch.
|
|
29
|
+
|
|
30
|
+
## Fast emitters
|
|
31
|
+
`rate` is per second, so a fast emitter leaves beads. `ratePerMeter` is per meter it moves, on top of `rate`, with the particles spread along the path of that step.
|
|
32
|
+
```js fragment
|
|
33
|
+
engine.particles.define('trail', { rate: 0, ratePerMeter: 6, lifetime: [0.4, 0.6], max: 200 });
|
|
34
|
+
const trail = engine.particles.attach('trail', rocket);
|
|
35
|
+
trail.ratePerMeter = 12; // live; attach(name, object, { ratePerMeter }) sets it too
|
|
36
|
+
```
|
|
37
|
+
Set `max` to what the trail needs: a step that earns more keeps the newest. A teleport counts as moving: set `active = false` for a frame around it. While frozen nothing is born.
|
|
38
|
+
|
|
39
|
+
## Soft edges
|
|
40
|
+
`soft` is the distance in meters over which a particle fades where it meets what writes depth, so smoke on the ground has no hard line. It is off by default, set at `define`, and live
|
|
41
|
+
through `fx.uniforms.uSoft.value`.
|
|
42
|
+
```js
|
|
43
|
+
engine.particles.define('smoke', { gravity: 0.4, size: [0.5, 2], soft: 0.5 });
|
|
44
|
+
```
|
|
45
|
+
What it costs, only while a soft effect is on screen. On WebGPU, one copy of the depth buffer per render, shared by every soft effect. On WebGLRenderer a shader
|
|
46
|
+
cannot read the depth it draws into, so the scene is drawn once more, depth only, per render, shared the same way: that is real cost in a large scene, and it sees surfaces without their
|
|
47
|
+
wind, displacement or alphaTest. On WebGPURenderer's WebGL2 backend (the fallback where WebGPU is missing) three's depth copy works only with post and antialias on; elsewhere there the
|
|
48
|
+
particles draw hard and the console says so. `soft` applies to the engine's material, not to one of yours.
|
|
49
|
+
|
|
21
50
|
## The material
|
|
22
51
|
```js
|
|
23
52
|
const sparks = engine.particles.define('sparks', { blending: 'additive' });
|
|
24
|
-
sparks.material = new THREE.PointsMaterial({ size: 0.2, color: 0xffaa33 }); // drawn as given
|
|
53
|
+
sparks.material = new THREE.PointsMaterial({ size: 0.2, color: 0xffaa33 }); // WebGLRenderer: drawn as given
|
|
25
54
|
sparks.material = null; // the engine's back
|
|
26
55
|
sparks.uniforms.uMaxPx.value = 64; // live
|
|
27
56
|
```
|
|
28
57
|
`.material` is the effect's plain three.js material, `.points` what draws it. Particle age reaches the picture through the geometry attributes `aSize`,
|
|
29
58
|
`aAlpha`, `aColor`, `aAngle`: a material that ignores them shows every particle alike, and one that wants the fade reads them, as
|
|
30
|
-
`modules/particles/shaders.js` does.
|
|
59
|
+
`modules/particles/shaders.js` does. `aLife` is the life fraction, 0 at birth and 1 at death, for a flipbook, a gradient or a dissolve of your own. Empty slots stay in the
|
|
60
|
+
buffer with `aAlpha` 0, so give them size 0 as the engine's shader does.
|
|
61
|
+
```js fragment
|
|
62
|
+
// GLSL (WebGLRenderer), in the vertex shader: attribute float aLife; attribute float aAlpha;
|
|
63
|
+
// TSL (WebGPURenderer, a new game's route): import { PointsNodeMaterial } from 'three/webgpu'; import { attribute, color, mix, vec4 } from 'three/tsl';
|
|
64
|
+
const m = new PointsNodeMaterial({ transparent: true, depthWrite: false, sizeAttenuation: false });
|
|
65
|
+
m.colorNode = vec4(mix(color(0x00ff00), color(0xff0000), attribute('aLife', 'float')), attribute('aAlpha', 'float'));
|
|
66
|
+
sparks.material = m; // placed and sized by the engine's nodes, unless m sets positionNode / sizeNode (the particle's place is attribute('aPos', 'vec3'))
|
|
67
|
+
```
|
|
68
|
+
A flipbook is the same material with a texture. Each route has its own y: `uv()` runs up, `gl_PointCoord` runs down.
|
|
69
|
+
```js fragment
|
|
70
|
+
import { attribute, float, floor, mod, texture, uv, vec2, vec4 } from 'three/tsl';
|
|
71
|
+
// a 4 x 4 sheet, first frame at the top left
|
|
72
|
+
const f = floor(attribute('aLife', 'float').mul(16)), col = mod(f, 4), row = floor(f.div(4));
|
|
73
|
+
const cell = texture(sheet, vec2(uv().x.add(col).div(4), uv().y.add(float(3).sub(row)).div(4)));
|
|
74
|
+
m.colorNode = vec4(cell.rgb, cell.a.mul(attribute('aAlpha', 'float')));
|
|
75
|
+
// GLSL, in a ShaderMaterial that writes gl_PointSize from aSize, uScale and uMaxPx as shaders.js does (vLife: aLife passed on as a varying):
|
|
76
|
+
// float f = floor(vLife * 16.0); vec2 cell = vec2(mod(f, 4.0), floor(f / 4.0));
|
|
77
|
+
// vec4 c = texture2D(uSheet, vec2((gl_PointCoord.x + cell.x) / 4.0, 1.0 - (gl_PointCoord.y + cell.y) / 4.0));
|
|
78
|
+
```
|
|
79
|
+
`.uniforms` (`uMap`, `uHasMap`, `uScale`, `uMaxPx`) are written whichever material is drawn; a `ShaderMaterial` of yours can
|
|
31
80
|
share them, `uScale` being the pixels per meter at distance 1. Your material is yours: the engine never disposes it, and defining the effect again goes back to
|
|
32
|
-
the engine's. On WebGPURenderer the effect is a sprite
|
|
81
|
+
the engine's. On WebGPURenderer the effect is a sprite quad drawn once per particle, so a material of yours is a node material there (recipe 56), and any other is refused.
|
|
33
82
|
|
|
34
83
|
## Weather
|
|
35
84
|
Rain and snow are separate, because they follow the camera and fade with the weather: `engine.weather.particles` (recipe 44).
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
# Swarm: shots, crowds, pickups, debris by the thousand
|
|
2
|
+
|
|
3
|
+
```js
|
|
4
|
+
import * as THREE from 'three';
|
|
5
|
+
import { swarm } from 'threedog';
|
|
6
|
+
engine.use(swarm());
|
|
7
|
+
const bullets = engine.swarm({
|
|
8
|
+
name: 'bullets', capacity: 4096,
|
|
9
|
+
geometry: new THREE.SphereGeometry(0.1, 6, 4),
|
|
10
|
+
material: new THREE.MeshBasicMaterial({ color: 0xffffff }),
|
|
11
|
+
fields: ['vx', 'vz', 'life'], // your own number columns, beside x, y, z
|
|
12
|
+
});
|
|
13
|
+
bullets.onStep((d, i, dt) => { // set once; runs every fixed step, for each live object
|
|
14
|
+
d.x[i] += d.vx[i] * dt;
|
|
15
|
+
d.z[i] += d.vz[i] * dt;
|
|
16
|
+
return (d.life[i] -= dt) > 0; // false removes it; anything else keeps it
|
|
17
|
+
});
|
|
18
|
+
engine.onFixed(() => {
|
|
19
|
+
if (engine.input.pressed('fire')) bullets.spawn({ x: 0, y: 1, z: 0, vx: 20, life: 2 });
|
|
20
|
+
});
|
|
21
|
+
```
|
|
22
|
+
One swarm is a set of same-kind objects that the game plays with: they spawn, die, move, collide and get asked about. Their data sits in typed arrays, one
|
|
23
|
+
array per field, and they draw as one plain `THREE.InstancedMesh`: one draw call, nothing allocated per object. The geometry and material are yours and work
|
|
24
|
+
on WebGL and WebGPU alike. There is no framework behind it: a game that does not call `engine.use(swarm())` pays nothing.
|
|
25
|
+
|
|
26
|
+
## Which tool for many things
|
|
27
|
+
| The things | Use | Why |
|
|
28
|
+
|---|---|---|
|
|
29
|
+
| Hit, are hit, get counted, saved or asked about: bullets, enemies in a horde, coins, crops | `engine.swarm` | spawn, die, move and query, on the fixed step |
|
|
30
|
+
| Only seen, short-lived, no rules: dust, sparks, smoke | `engine.particles` (recipe 64) | emitters, fades and sizes over a lifetime |
|
|
31
|
+
| Placed once, do not move: fences, rocks, a crop field's scenery | `engine.batching` or `props` (recipe 05) | no per-frame work at all |
|
|
32
|
+
| Only seen, a very great number, and the game runs on WebGPU: snow, ash, star fields | GPU compute, last section | the CPU never touches them |
|
|
33
|
+
| A few dozen that each need their own logic, animation or a skeleton | one object each (`engine.characters`, plain meshes) | a swarm is same-kind objects, one geometry, no skeleton |
|
|
34
|
+
|
|
35
|
+
The test: if game rules read the thing, it is a swarm; if only eyes do, it is one of the visual tools.
|
|
36
|
+
|
|
37
|
+
## The id rule: handles and rows
|
|
38
|
+
Two numbers, never mixed up.
|
|
39
|
+
|
|
40
|
+
- A **handle** is what `spawn` returns and what `d.id[i]` holds. It names one object for as long as it lives and never names another afterwards. Keep these, in a variable or in a
|
|
41
|
+
field of any swarm: a turret's target, a homing missile's prey. A handle in a save stays good after loading that save.
|
|
42
|
+
- A **row** `i` is where the object sits now: what `onStep` and `near` pass, what `d.x[i]` reads. Removing an object moves the last row into the gap, so a
|
|
43
|
+
row means something only inside one callback or one plain loop. Never store a row.
|
|
44
|
+
|
|
45
|
+
`swarm.row(handle)` turns a handle into today's row, -1 when it is gone. `free` takes a handle; given a row by mistake it throws `[swarm-handle]`.
|
|
46
|
+
```js
|
|
47
|
+
const enemies = engine.swarm({ name: 'enemies', capacity: 2000, fields: ['hp'] });
|
|
48
|
+
let target = enemies.spawn({ x: 5, z: 2, hp: 3 }); // a handle: safe to keep
|
|
49
|
+
engine.onFixed(() => {
|
|
50
|
+
const i = enemies.row(target); // today's row, -1 once it died
|
|
51
|
+
if (i < 0) return;
|
|
52
|
+
enemies.data.hp[i] -= 1;
|
|
53
|
+
if (enemies.data.hp[i] <= 0) enemies.free(target);
|
|
54
|
+
});
|
|
55
|
+
```
|
|
56
|
+
Inside `onStep` and `near` you may `free` and `spawn` freely. A freed object counts as gone at once (`row` and `near` skip it, `count` drops), and rows only move
|
|
57
|
+
when the walk ends, so nothing is skipped or run twice. An object spawned during a walk first moves in the next step. To walk every object outside a callback:
|
|
58
|
+
`for (let i = 0; i < s.count; i++)` reading `s.data`, without removing; collect handles and free them afterwards.
|
|
59
|
+
|
|
60
|
+
## Hits: `near`
|
|
61
|
+
```js
|
|
62
|
+
const shots = engine.swarm({ name: 'shots', capacity: 1024, fields: ['vx', 'vz'] });
|
|
63
|
+
const crowd = engine.swarm({ name: 'crowd', capacity: 8000, cell: 2, fields: ['hp'] });
|
|
64
|
+
shots.onStep((d, i, dt) => {
|
|
65
|
+
d.x[i] += d.vx[i] * dt;
|
|
66
|
+
d.z[i] += d.vz[i] * dt;
|
|
67
|
+
let hit = false;
|
|
68
|
+
crowd.near(d.x[i], d.z[i], 0.6, (c, j) => {
|
|
69
|
+
hit = true;
|
|
70
|
+
if ((c.hp[j] -= 1) <= 0) crowd.free(c.id[j]);
|
|
71
|
+
return false; // false stops the query: this shot is spent
|
|
72
|
+
});
|
|
73
|
+
return !hit;
|
|
74
|
+
});
|
|
75
|
+
```
|
|
76
|
+
`near(x, z, r, cb)` calls `cb(d, i, dist2)` for each live object within `r` meters on the ground plane; height is ignored, so a game that needs it compares `d.y[i]`
|
|
77
|
+
itself. It returns how many it visited, and the order is the same every run. The grid behind it is built on the first query after things moved, once per step
|
|
78
|
+
when you only ask at one point in the step, and not at all if nobody asks. `cell` is about your usual query radius.
|
|
79
|
+
|
|
80
|
+
Inside `onStep`, `near` on the same swarm sees cells from the start of the step, with live positions for the distance. Fine for crowds keeping apart; for exact
|
|
81
|
+
answers query after the step (`engine.onFixed(fn, { phase: 'late' })`). A bullet faster than its radius per step can jump over a target: use a radius of at least
|
|
82
|
+
speed x dt / 2, or check along the path yourself. Rays: `engine.rays` does not hit instances; three's `Raycaster` on `swarm.mesh` gives `instanceId`, which is a row.
|
|
83
|
+
|
|
84
|
+
## The same thing in other games
|
|
85
|
+
Tower defence: enemies walk a path, each tower holds one handle and keeps it until `row` says -1.
|
|
86
|
+
```js
|
|
87
|
+
const creeps = engine.swarm({ name: 'creeps', capacity: 500, fields: ['along', 'hp', 'yaw'] });
|
|
88
|
+
const towers = [{ x: 4, z: 4, target: -1 }];
|
|
89
|
+
engine.onFixed(() => {
|
|
90
|
+
for (const t of towers) {
|
|
91
|
+
if (creeps.row(t.target) >= 0) continue; // still alive: keep shooting it
|
|
92
|
+
t.target = -1;
|
|
93
|
+
creeps.near(t.x, t.z, 8, (d, i) => { t.target = d.id[i]; return false; });
|
|
94
|
+
}
|
|
95
|
+
});
|
|
96
|
+
```
|
|
97
|
+
Farm game: crops grow slowly, stay where they are, and belong in the save.
|
|
98
|
+
```js
|
|
99
|
+
const crops = engine.swarm({ name: 'crops', capacity: 5000, fields: ['age', 'scale'], save: true, color: true });
|
|
100
|
+
crops.spawn({ x: 2, z: 3, scale: 0.2, color: 0x88cc44 });
|
|
101
|
+
crops.onStep((d, i, dt) => {
|
|
102
|
+
d.age[i] += dt;
|
|
103
|
+
d.scale[i] = Math.min(1, 0.2 + d.age[i] / 300);
|
|
104
|
+
});
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
## Drawing
|
|
108
|
+
- Matrices are written once per rendered frame, between the last two fixed steps (`engine.stepBlend`), so motion stays smooth at any frame rate. Writing `d.x[i]` from
|
|
109
|
+
`onFixed` is smoothed the same way.
|
|
110
|
+
- Fields named `yaw`, `pitch`, `roll` (radians, three's order `'YXZ'`) and `scale` are drawn when you list them. Without them only the position is written, which is cheapest.
|
|
111
|
+
- `color: true` adds columns `r`, `g`, `b` (linear) and the spawn key `color: 0xff8800`. Your material's colour multiplies it.
|
|
112
|
+
- `swarm.mesh` is plain three.js: set `castShadow`, `layers`, `renderOrder` on it. The instance index is the row, and `mesh.count` follows the live count.
|
|
113
|
+
- A transparent swarm draws in row order: three sorts objects, not the instances inside one, so overlapping see-through objects can blend in the wrong order.
|
|
114
|
+
- Bounds are kept up to date while matrices are written, so culling is right for the whole swarm; it is one object to the camera, so it is drawn whole or not at all.
|
|
115
|
+
- Leave out `geometry` and `material` for a swarm that only holds data, and draw it your own way from `swarm.data`.
|
|
116
|
+
|
|
117
|
+
## Time, saves, limits
|
|
118
|
+
- `onStep`'s function runs on the fixed step with the `dt` of the swarm's time channel, default `'world'`; `{ channel: 'enemies' }` joins bullet time (recipe 55). It does not run while
|
|
119
|
+
frozen, or while that channel stands still. `engine.skip` does not run it either: nothing in a swarm ages during a skip.
|
|
120
|
+
- `{ save: true }` keeps a swarm in saves, handles included. Any swarm without it is emptied by a load or a new game, so last round's bullets do not stay on the field. A saved
|
|
121
|
+
swarm with objects at start returns to them on `engine.session.newGame()`. A saved field added in a later game version starts at its default.
|
|
122
|
+
- Saves write every number of every object: fine for crops, wasteful for 50,000 bullets, which is why it is opt-in.
|
|
123
|
+
- `capacity` is fixed and all memory is taken at once. A full swarm refuses the spawn: `spawn` returns -1, `dropped` counts it, one `[swarm-full]` warning names it, and `free(-1)` is
|
|
124
|
+
harmless. `describe().swarm`, `engine.explain({ swarm: 'name' })` and `engine.counts().swarm` show the numbers. Your own `fields` are `Float64Array`, so a handle kept in one stays exact. `x`, `y`, `z` and `r`, `g`, `b` are `Float32Array`: fine for a position or a colour, not for a handle.
|
|
125
|
+
- `swarm.dispose()` removes the mesh and its GPU buffers; so do `engine.unuse('swarm')` and `engine.dispose()`. Geometry and material stay yours to dispose.
|
|
126
|
+
- A swarm is for one shape. Three enemy kinds are three swarms, or one swarm when they differ only in colour and scale.
|
|
127
|
+
|
|
128
|
+
## Pure picture: GPU compute
|
|
129
|
+
When nothing in the rules reads the things, and the game runs on WebGPU, they need not touch the CPU at all. This is plain three.js with no engine API. It needs a real
|
|
130
|
+
WebGPU device to be worth it: without one, use `engine.particles` or a swarm. Pick it over a swarm when the count is far past what the CPU should write per frame and no game
|
|
131
|
+
code needs an answer back: reading a GPU buffer takes frames, so `near` and hits are out.
|
|
132
|
+
Build it with three's TSL as in three's own compute examples (an `instancedArray` buffer, compute nodes, a `SpriteNodeMaterial` reading the buffer through `positionNode`). What the engine adds is where each call goes:
|
|
133
|
+
```js fragment
|
|
134
|
+
import 'threedog/tsl'; // before createEngine
|
|
135
|
+
const gpu = /** @type {any} */ (engine.renderer); // a WebGPURenderer: the engine's type also covers WebGL
|
|
136
|
+
await gpu.computeAsync(seed); // once, to fill the buffer
|
|
137
|
+
engine.onFrame(d => { uDt.value = engine.frozen ? 0 : d; }); // time as a uniform set here, so a freeze stops the snow
|
|
138
|
+
engine.onRender(() => { gpu.compute(fall); }); // the shader here, so it runs once per drawn frame
|
|
139
|
+
snow.frustumCulled = false; // the sprite's own bounds know nothing of the flakes
|
|
140
|
+
```
|