threedog 1.0.1 → 1.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 +90 -0
- package/README.md +1 -1
- package/core/assets/Animator.js +41 -3
- package/core/assets/Assets.js +100 -24
- package/core/assets/assetEntry.js +73 -20
- package/core/assets/assetHot.js +68 -16
- package/core/assets/assetLoad.js +6 -6
- package/core/assets/assetLod.js +9 -2
- package/core/assets/assetManifest.js +12 -2
- package/core/assets/assetPart.js +54 -0
- package/core/assets/ik.js +271 -0
- package/core/assets/modelNeeds.js +37 -0
- package/core/assets/namedModel.js +102 -29
- package/core/assets/nodeVisibility.js +15 -0
- package/core/audio/Audio.js +36 -4
- package/core/audio/audioReverb.js +99 -0
- package/core/audio/audioRules.js +1 -1
- package/core/audio/audioVoice.js +1 -1
- package/core/base/Events.js +14 -4
- package/core/base/Random.js +1 -1
- package/core/base/Vars.js +1 -1
- package/core/base/docRef.js +51 -0
- package/core/base/errorCodes.js +178 -126
- package/core/base/errorHints.js +9 -7
- package/core/base/errors.js +25 -10
- package/core/base/events.generated.js +2 -0
- package/core/base/freeParts.js +76 -0
- package/core/base/math.js +28 -0
- package/core/base/sections.js +5 -5
- package/core/base/validate.js +31 -3
- package/core/engine/Engine.js +16 -6
- package/core/engine/Loading.js +5 -3
- package/core/engine/copies.js +1 -1
- package/core/engine/headlessLoad.js +4 -1
- package/core/engine/lifecycle.js +32 -16
- package/core/engine/loop.js +71 -27
- package/core/engine/moduleSlots.js +2 -2
- package/core/engine/moduleTypes.js +3 -3
- package/core/engine/modules.js +65 -39
- package/core/engine/page.js +6 -3
- package/core/engine/services.js +6 -5
- package/core/engine/startup.js +5 -5
- package/core/input/Input.js +28 -14
- package/core/input/inputContext.js +28 -16
- package/core/input/inputKeyboard.js +31 -3
- package/core/input/inputPad.js +4 -0
- package/core/input/inputPointer.js +2 -1
- package/core/input/inputSeat.js +1 -1
- package/core/inspect/Budget.js +109 -19
- package/core/inspect/DebugOverrides.js +28 -4
- package/core/inspect/Describe.js +17 -9
- package/core/inspect/Inspect.js +4 -2
- package/core/inspect/InspectMaterials.js +3 -1
- package/core/inspect/InspectPerf.js +19 -9
- package/core/inspect/InspectScene.js +32 -7
- package/core/inspect/MaterialInfo.js +19 -2
- package/core/inspect/UrlState.js +46 -27
- package/core/inspect/catalog.js +28 -9
- package/core/inspect/debugView.js +2 -1
- package/core/inspect/describeRender.js +25 -13
- package/core/inspect/describeText.js +14 -6
- package/core/inspect/lightWatch.js +1 -1
- package/core/inspect/metadata.generated.js +35 -17
- package/core/inspect/pictureChecks.js +148 -0
- package/core/inspect/pictureMenu.js +84 -0
- package/core/inspect/pictureWriters.js +26 -6
- package/core/inspect/textureBytes.js +12 -2
- package/core/inspect/toolDoor.js +2 -4
- package/core/ops/Ops.js +11 -4
- package/core/ops/holds.js +27 -10
- package/core/ops/opsAtomic.js +15 -7
- package/core/ops/opsGuard.js +2 -2
- package/core/ops/opsRun.js +8 -7
- package/core/ops/sharedPoint.js +72 -21
- package/core/ops/stacks.js +56 -16
- package/core/saves/SaveStore.js +9 -3
- package/core/saves/Saves.js +32 -23
- package/core/saves/saveApply.js +96 -44
- package/core/saves/saveIds.js +1 -1
- package/core/saves/saveVersions.js +7 -5
- package/core/saves/session.js +17 -8
- package/core/saves/stateReplace.js +34 -15
- package/core/scene/Rays.js +52 -10
- package/core/scene/Views.js +13 -7
- package/core/scene/adaptive.js +144 -21
- package/core/scene/drawOnly.js +17 -0
- package/core/scene/gameLights.js +44 -3
- package/core/scene/sceneMethods.js +13 -11
- package/core/scene/stepPoses.js +11 -3
- package/core/scene/targeting.js +5 -3
- package/core/scene/thingOps.js +1 -1
- package/core/scene/tier.js +15 -0
- package/core/stream/Batching.js +30 -7
- package/core/stream/Stream.js +26 -7
- package/core/stream/batchGroups.js +2 -2
- package/core/stream/chunkStream.js +7 -5
- package/core/stream/prepare.js +77 -0
- package/core/time/skip.js +3 -1
- package/core/time/time.js +4 -2
- package/docs/AI.md +82 -83
- package/docs/API.md +16 -16
- package/docs/CODEMAP.md +16 -11
- package/docs/COMMANDS.md +31 -33
- package/docs/CONVENTIONS.md +37 -49
- package/docs/MIGRATING-0.8.md +2 -2
- package/docs/MIGRATING-1.0.md +2 -2
- package/docs/THREE.md +28 -35
- package/docs/api/assets.md +3 -1
- package/docs/api/audio.md +4 -2
- package/docs/api/budget.md +5 -0
- package/docs/api/cameraRig.md +2 -2
- package/docs/api/characters.md +10 -8
- package/docs/api/collision.md +6 -4
- package/docs/api/engine.md +16 -16
- package/docs/api/events.md +3 -2
- package/docs/api/ground.md +6 -5
- package/docs/api/hud.md +4 -2
- package/docs/api/input.md +5 -5
- package/docs/api/particles.md +2 -1
- package/docs/api/photo.md +3 -0
- package/docs/api/post.md +7 -4
- package/docs/api/quests.md +2 -2
- package/docs/api/rays.md +1 -2
- package/docs/api/saves.md +7 -7
- package/docs/api/settings.md +2 -2
- package/docs/api/tools.md +3 -1
- package/docs/api/vars.md +1 -1
- package/docs/api/vegetation.md +4 -2
- package/docs/api/world.md +1 -1
- package/docs/recipes/01-new-game.md +16 -17
- package/docs/recipes/02-npc.md +22 -18
- package/docs/recipes/03-items-pickups.md +37 -35
- package/docs/recipes/04-quests.md +15 -10
- package/docs/recipes/05-props-bake.md +101 -95
- package/docs/recipes/06-clock-events.md +28 -28
- package/docs/recipes/07-flow-scenes-pause.md +29 -26
- package/docs/recipes/08-weather-sky.md +52 -64
- package/docs/recipes/09-materials-lights-models.md +26 -17
- package/docs/recipes/10-blender-level.md +15 -10
- package/docs/recipes/11-vehicles.md +12 -7
- package/docs/recipes/12-navmesh.md +44 -26
- package/docs/recipes/13-animation.md +56 -45
- package/docs/recipes/14-custom-module.md +21 -18
- package/docs/recipes/15-perf.md +61 -55
- package/docs/recipes/16-dev-bridge.md +23 -33
- package/docs/recipes/18-world.md +36 -42
- package/docs/recipes/19-shooting-picking.md +20 -15
- package/docs/recipes/20-content-actions-save.md +48 -56
- package/docs/recipes/21-camera.md +45 -54
- package/docs/recipes/22-shop-gold.md +12 -7
- package/docs/recipes/23-ops.md +25 -23
- package/docs/recipes/26-ui-parts.md +67 -47
- package/docs/recipes/27-net.md +12 -7
- package/docs/recipes/28-terrain.md +24 -21
- package/docs/recipes/29-grid.md +32 -27
- package/docs/recipes/30-templates.md +21 -20
- package/docs/recipes/31-audio.md +39 -22
- package/docs/recipes/32-action-game.md +19 -14
- package/docs/recipes/33-stream-sources.md +15 -11
- package/docs/recipes/34-environment-lighting.md +126 -70
- package/docs/recipes/35-picture-from-reference.md +8 -8
- package/docs/recipes/36-ground-plants.md +27 -21
- package/docs/recipes/40-scene.md +19 -28
- package/docs/recipes/43-shader-patches-surfaces.md +15 -12
- package/docs/recipes/44-water-weather-hooks.md +34 -31
- package/docs/recipes/45-cascaded-shadows.md +35 -26
- package/docs/recipes/46-blender-art-route.md +6 -1
- package/docs/recipes/49-game-module-contract.md +13 -8
- package/docs/recipes/50-own-renderer.md +6 -2
- package/docs/recipes/51-capability-catalog.md +15 -8
- package/docs/recipes/52-around-the-picture.md +34 -32
- package/docs/recipes/53-ground-up-close.md +6 -1
- package/docs/recipes/55-mods-time-wrap.md +27 -19
- package/docs/recipes/56-webgpu-tsl.md +74 -43
- package/docs/recipes/57-control.md +18 -13
- package/docs/recipes/58-input.md +26 -16
- package/docs/recipes/59-depth-post-effects.md +8 -3
- package/docs/recipes/60-judge-the-picture.md +9 -8
- package/docs/recipes/61-deploy.md +5 -0
- package/docs/recipes/62-picture-code.md +70 -79
- package/docs/recipes/63-third-person-start.md +47 -45
- package/docs/recipes/64-particles.md +22 -10
- package/docs/recipes/65-swarm.md +18 -13
- package/docs/recipes/66-common-tasks.md +38 -35
- package/examples/action/GAMEMAP.md +2 -3
- package/examples/action/main.js +3 -3
- package/examples/action/picture/lights.js +3 -1
- package/examples/perf-island/GAMEMAP.md +3 -3
- package/examples/perf-island/picture/lights.js +2 -1
- package/examples/plain-picture/GAMEMAP.md +1 -1
- package/examples/rc2d/GAMEMAP.md +1 -1
- package/examples/styletest/GAMEMAP.md +2 -2
- package/examples/styletest/main.js +1 -1
- package/examples/techniques/interior-light/README.md +3 -3
- package/examples/techniques/interior-light/interiorLight.js +2 -4
- package/examples/techniques/interior-light/picture/lights.js +2 -1
- package/examples/techniques/modular-building/picture/lights.js +3 -1
- package/examples/techniques/outlines-and-rim/picture/lights.js +3 -1
- package/examples/techniques/procedural-animation/README.md +1 -1
- package/examples/techniques/procedural-animation/main.js +1 -1
- package/examples/webgpu-tsl/GAMEMAP.md +1 -1
- package/examples/world/GAMEMAP.md +2 -3
- package/examples/world/art/humanoid.js +1 -1
- package/examples/world/main.js +6 -3
- package/index.d.ts +2 -2
- package/llms.txt +101 -0
- package/modules/ambience/Ambience.js +21 -5
- package/modules/calendar/index.js +9 -5
- package/modules/calendar/schedule.js +23 -8
- package/modules/camera/FirstPersonCamera.js +3 -1
- package/modules/camera/FollowCamera.js +10 -5
- package/modules/camera/RtsCamera.js +4 -3
- package/modules/camera/common.js +70 -8
- package/modules/camera/contract.js +1 -1
- package/modules/characters/Character.js +16 -10
- package/modules/characters/NPC.js +31 -19
- package/modules/characters/assetModel.js +14 -9
- package/modules/characters/astar.js +6 -1
- package/modules/characters/contract.js +2 -2
- package/modules/characters/index.js +34 -22
- package/modules/characters/movers/manual.js +1 -1
- package/modules/characters/movers/rapier.js +17 -2
- package/modules/characters/movers/simple.js +1 -1
- package/modules/characters/movers/support.js +16 -7
- package/modules/characters/npcAvoid.js +2 -2
- package/modules/characters/npcSim.js +3 -2
- package/modules/characters/pathAsync.js +24 -8
- package/modules/characters/pathJob.js +1 -1
- package/modules/characters/player.js +10 -9
- package/modules/characters/playerStrings.js +5 -5
- package/modules/characters/proceduralRig.js +5 -5
- package/modules/characters/useModel.js +6 -0
- package/modules/characters/walkTo.js +1 -1
- package/modules/collision/Collision.js +29 -18
- package/modules/collision/grid.js +22 -4
- package/modules/content/index.js +3 -1
- package/modules/content/loader.js +1 -1
- package/modules/content/models.js +82 -33
- package/modules/content/props.js +2 -1
- package/modules/content/rules.js +11 -5
- package/modules/content/templates.js +3 -3
- package/modules/content/words.js +2 -2
- package/modules/debug/DebugPanel.js +9 -9
- package/modules/flow/index.js +9 -6
- package/modules/gameplay/Dialogue.js +34 -20
- package/modules/gameplay/Interactions.js +19 -15
- package/modules/gameplay/Inventory.js +9 -4
- package/modules/gameplay/Quests.js +12 -10
- package/modules/gameplay/pickups.js +23 -11
- package/modules/grid/index.js +1 -1
- package/modules/grid/preview.js +2 -2
- package/modules/grid/tiles.js +1 -1
- package/modules/hlod/index.js +4 -1
- package/modules/hud/index.js +47 -10
- package/modules/hud/parts.js +28 -9
- package/modules/level/geometry.js +8 -3
- package/modules/level/index.js +10 -5
- package/modules/level/load.js +4 -2
- package/modules/lights/sources.js +1 -1
- package/modules/music/Music.js +22 -4
- package/modules/nav/index.js +20 -10
- package/modules/particles/Particles.js +31 -14
- package/modules/particles/effect.js +20 -5
- package/modules/particles/lit.js +72 -0
- package/modules/photo/Photo.js +72 -28
- package/modules/photo/pathTrace.js +106 -0
- package/modules/rigid/RigidBodies.js +23 -14
- package/modules/rigid/Vehicles.js +3 -13
- package/modules/rigid/sync.js +2 -1
- package/modules/settings/Settings.js +52 -20
- package/modules/settings/apply.js +23 -9
- package/modules/settings/sections.js +39 -6
- package/modules/settings/strings.js +2 -0
- package/modules/settings/view.js +19 -3
- package/modules/sky/dome.js +15 -3
- package/modules/sky/environment.js +28 -12
- package/modules/sky/fog.js +1 -1
- package/modules/sky/frame.js +6 -1
- package/modules/sky/shader.js +4 -3
- package/modules/sky/skyModule.js +8 -4
- package/modules/swarm/Swarm.js +1 -1
- package/modules/terrain/ChunkManager.js +61 -15
- package/modules/terrain/chunkJob.js +2 -2
- package/modules/terrain/index.js +20 -5
- package/modules/terrain/terrainEdit.js +8 -4
- package/modules/terrain/terrainTexture.js +4 -2
- package/modules/timeline/Timeline.js +4 -3
- package/modules/timeline/Tween.js +3 -0
- package/modules/timeline/letterbox.js +1 -0
- package/modules/triggers/index.js +36 -17
- package/modules/vegetation/Vegetation.js +81 -19
- package/modules/vegetation/densityMap.js +13 -8
- package/modules/vegetation/draw.js +147 -24
- package/modules/vegetation/groundChunks.js +20 -5
- package/modules/vegetation/index.js +3 -3
- package/modules/vegetation/modelGeometry.js +9 -4
- package/modules/water/Water.js +11 -8
- package/modules/weather/Weather.js +7 -2
- package/modules/weather/shaders.js +25 -5
- package/modules/weather/weatherDraw.js +20 -6
- package/modules/world/World.js +2 -1
- package/modules/world/index.js +2 -2
- package/modules/world/persist.js +6 -2
- package/modules/world/views.js +15 -2
- package/package.json +4 -1
- package/presets.js +5 -5
- package/render/PostFX.js +84 -41
- package/render/backend.js +137 -16
- package/render/cascades.js +3 -1
- package/render/cascades.tsl.js +2 -0
- package/render/daylight.js +7 -1
- package/render/detail.js +7 -4
- package/render/effects.js +27 -8
- package/render/fogLook.js +24 -0
- package/render/fuse.js +5 -2
- package/render/fx/detail.tsl.js +9 -7
- package/render/fx/index.js +7 -2
- package/render/fx/library.tsl.js +1 -0
- package/render/fx/lightShaft.tsl.js +114 -0
- package/render/fx/noise.tsl.js +25 -8
- package/render/fx/objectOrigin.tsl.js +39 -10
- package/render/fx/particles.tsl.js +23 -6
- package/render/fx/patchNodes.tsl.js +17 -12
- package/render/fx/pcss.tsl.js +51 -0
- package/render/fx/postWebGPU.tsl.js +89 -29
- package/render/fx/sky.tsl.js +3 -9
- package/render/fxNumbers.js +10 -4
- package/render/impostor.tsl.js +107 -0
- package/render/lighting.js +33 -1
- package/render/lightmap.js +42 -28
- package/render/lights.js +19 -3
- package/render/materials.js +6 -4
- package/render/mergeCommon.js +4 -1
- package/render/occlusion.js +14 -4
- package/render/patches.js +79 -41
- package/render/postRuns.js +32 -0
- package/render/postWebGL.js +97 -10
- package/render/probes.js +10 -14
- package/render/shaderErrors.js +2 -1
- package/render/shadowCache.tsl.js +33 -5
- package/render/shadows.js +42 -16
- package/render/slots.js +8 -5
- package/render/vertexInputs.js +52 -0
- package/types/core.d.ts +114 -46
- package/types/gameplay.d.ts +56 -23
- package/types/generated/core/audio/Audio.d.ts +27 -1
- package/types/generated/core/base/Random.d.ts +1 -1
- package/types/generated/core/input/Input.d.ts +6 -8
- package/types/generated/core/input/inputSeat.d.ts +1 -1
- package/types/generated/core/inspect/Budget.d.ts +26 -0
- package/types/generated/core/inspect/DebugOverrides.d.ts +0 -2
- package/types/generated/core/saves/Saves.d.ts +10 -7
- package/types/generated/core/saves/session.d.ts +8 -2
- package/types/generated/core/scene/Rays.d.ts +1 -3
- package/types/generated/modules/particles/Particles.d.ts +1 -1
- package/types/generated/modules/world/World.d.ts +2 -1
- package/types/generated/render/PostFX.d.ts +35 -9
- package/types/physics.d.ts +43 -11
- package/types/pixel.d.ts +1 -1
- package/types/tsl.d.ts +62 -1
- package/types/world.d.ts +12 -3
- package/ui/Focus.js +7 -5
- package/ui/Parts.js +1 -1
- package/ui/touchPart.js +6 -3
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,96 @@
|
|
|
2
2
|
|
|
3
3
|
What changed in each version and how a game upgrades.
|
|
4
4
|
|
|
5
|
+
## 1.2.0 (2026-11-10)
|
|
6
|
+
|
|
7
|
+
- Fixed: shadows on tier 'low' no longer smear. With `engine.shadows.cascades(...)` the single low-tier map now covers `maxFar / count` (shifted toward the view), so its texels are as fine as one cascade's; a game's `count: 1` still covers all of `maxFar`. The engine sun's PCF radius follows its map size (2 on the low-tier 1024 map). A radius or map size the game set (any value other than the engine's default) is kept across tier changes. Trade-off: on tier 'low' far shadows end sooner (recipe 45).
|
|
8
|
+
- Fixed: the picture check no longer calls a light useless when it only lights `lit: true` particles; it recolors them before each capture and puts their colors back after.
|
|
9
|
+
|
|
10
|
+
- Fixed: in first person (and a follow camera's close-up), a shadow-casting point or spot light the player carries (a head lamp, a torch, within one body width of the body) is no longer shadowed by the player's hidden body, on both renderers; before, its pool had a hard black wedge on one side. The sun and other lights still cast the body's shadow; a body that is seen shadows every light as before. A point / spot light added after the camera started now gets the body's shadow too. Nothing to call (recipe 34).
|
|
11
|
+
- Changed: `settings.define(key, def, apply)` (on `engine.settings`) now draws its row in the settings menu: a switch for true/false, a slider for a number with `{ min, max, step? }` (a `limits` number row has 0..1), buttons for `{ options }`, labelled by `label` (an i18n key or text, else the key), in the tab `menu` names (default a new `options` tab, shown only while it has a row). Before, a defined row was drawn by no tab unless the game's own tab drew it, so it silently never showed. Upgrade: a row your own `addSection` tab draws needs `menu: false` (the menu warns once when it sees a row drawn twice); a row the menu cannot draw (a number without `min`/`max`, a string without `options`) or a `menu` naming a missing tab warns once. Unknown `define` options now throw in dev.
|
|
12
|
+
- New: `lightShaft(engine, opts)` in `threedog/tsl`, a cheap beam of light you can see in the air (daylight through a ceiling hole or window, a stage or lighthouse beam). A plain additive `THREE.Mesh`: sides soften by view angle, it fades where it meets geometry and near the camera, scene fog dims it, optional drifting `dust` (skipped on tier 'low'); can follow a SpotLight or DirectionalLight. WebGPURenderer only (both backends), `WebGLRenderer` throws `tsl-misuse`. Recipe 34 "Light you can see in the air" now says when to use it and when `sunShafts` / `lightVolumes`.
|
|
13
|
+
- New: `engine.audio.reverb({ sends, decay, size, wet, fade })`, one reverb send/return any bus can feed (generated impulse, no file), off until called, `null` turns it off; an ambience rule `{ reverb: 0.7, when: { zone: 'cave' } }` sets its wet by place (recipes/31 §9). `audio.info.reverb` shows it.
|
|
14
|
+
- New: particle effects take `lit: true`: the scene's point, spot, directional, ambient and hemisphere lights tint each particle's color (dust a lamp lights), the same on WebGL and WebGPU; default unchanged (recipes/64 "Lit particles").
|
|
15
|
+
- Fixed: `check` hints for a hand-made inventory and a hand-made reach check now read what the code does, not one spelling: each needs two signals of the job. A bag kept as a state field (`{ bag: [] }`, `S.bag.push(...)`, `.reduce`) is flagged when, within 3 lines, something is compared with a named capacity-like limit (`> RULES.capacity`, `>= this.maxSlots`; a number literal does not count); a distance against a named range (`Math.hypot(...) < RULES.reach`) is flagged beside a `hud.hint` or the E key. Tetris piece bags, ammo counts, a physics weight and a combat range beside an attack / use press stay quiet. Before, only `const bag = []` and a number threshold beside the E key were flagged.
|
|
16
|
+
- A `session:start` listener added right after `await engine.start()`, when the playthrough already began inside start() (`?play`, or newGame during start), now warns `session-start-missed` with the fix (listen before start, or read `engine.session.playing`); event semantics are unchanged, nothing is replayed.
|
|
17
|
+
- Docs: first-person start (recipe 63 §7) and which way `yaw` points (recipe 21 §3); a light the player carries, with a shadow (recipe 34); end screens are flow states (recipe 26 intro); ambience is "sounds by place" (recipe 31 §3); a `settings.define` row is drawn by your own tab, labelled by the text or `e.t(key)` you pass; `onRender`'s `dt` is the frame's seconds, the same as `onFrame`'s.
|
|
18
|
+
|
|
19
|
+
- Fixed: a post effect order that breaks scene depth only once a held effect turns on (outline after `ao` while a low preset holds `ao` off) is refused at `engine.post.add`; before, it was accepted and threw later inside the settings switch that turned `ao` on, half-applied.
|
|
20
|
+
- Fixed: on WebGL, `engine.shadows.cascades(light)` while another DirectionalLight (the engine sun included) casts a shadow throws `shadow-cascades` naming that light; before, every patched material failed to compile (`CSM_cascades` index out of range).
|
|
21
|
+
- Post effect params refuse NaN and Infinity (`post-effect`), at `engine.post.add` and at `handle.set`; finite values, negative and huge included, are kept as given.
|
|
22
|
+
- An atomic op's rollback is synchronous: an atomic save part whose `load()` returns a Promise is refused there (`engine-misuse`, reported; the other parts still go back) instead of being waited for, which let a failed nested op's pending load overwrite the outer op's commit. `engine.applyState` now waits for every module `applyState` hook to settle before a failure ends the request, so a slower sibling cannot write over the next request.
|
|
23
|
+
- Fixed: a settings switch (bloom, ao, a game row with `limits`) turned back on, or the settings module unloaded, gives back every effect it switched off, also one that left the row meanwhile (an old effect named `bloom` once a `glow` declares `about.acts: 'glow'`); before, that effect stayed off.
|
|
24
|
+
- `runContract` (`@threedog/tools/contract`) now returns a Promise: write `await runContract(...)`. Its small engine uses the real `saves.define` and install check, so a module the engine would refuse (a save key defined twice, an unknown field or a bad `first`, an `install` that returns a Promise) fails the contract instead of passing it, and the save round trip loads parts by `first` and waits for a part load that returns a Promise, as `saves.load` does.
|
|
25
|
+
- Rule R67 no longer checks `saves.register` calls: that name was removed.
|
|
26
|
+
- Fixed: on WebGPU a renderer borrow (a pass, an `onRender` hook) that turned off `scene.fogNode` and threw left the fog off for good; `scene.fogNode` is put back like `scene.backgroundNode`.
|
|
27
|
+
- Fixed: with WebGL cascaded shadows the path-traced photo and the gallery's `game` light saw one sun per cascade (3 cascades at intensity 2 lit like 6); they now see the one sun. The engine marks such parts (core/scene/drawOnly.js; a clone is not marked) and every scene copy leaves them out.
|
|
28
|
+
- Fixed: a path-traced photo of far plants drawn as impostor cards traced one small card per species near the origin; the cards are now left out, and `pathTraced.untraced` says the far plants are not in the traced photo.
|
|
29
|
+
- Fixed: rain and snow rebuilt on a tier change on WebGPU took the old system's internal "no texture" stand-in (freed with the old material) for the game's texture; only textures the game gave are carried over.
|
|
30
|
+
- API cleanup (one entry per job). Internal now, not public names (they still run inside the engine; a game that called one uses the form named): `stacks.mod` (use `engine.mod`, or `ctx.mod` in a module), `ground.height`, `ground.slope`, `ground.type` and `ground.waterLevel` (a ground provider still implements them; a game samples with `engine.surface / slope / groundType / waterLevel`, `engine.ground` keeps `has` and `voidY`), `engine.commits` (a module reaches it as `ctx.commits`, a game uses `engine.nextFixed`), `assets.forget` and `rays.forget` (`engine.remove` calls both), `debug.dispose`. `engine.stacks` keeps `define`, `get`, `changed` and `describe`. What a ground provider supplies is the public type `GroundProvider` (documented in `api/ground.md`); `setGround`, `ctx.ground.provide` and `compositeGround` take it (the same members as before; `compositeGround.parts` names it).
|
|
31
|
+
- Renamed: `engine.freeze(owner, { ambient: true })` -> `{ still: true }`, matching `engine.still`. `ambient` is now an unknown option and throws like any other unknown key.
|
|
32
|
+
- Removed the old names kept as aliases (a rename removes the old name in the same change, design.md 2.6; nobody wrote them): `saves.register`, `characters.createPlayer`, `input.action`, `hud.counter`, `freeze({ ambient })` (and the same on `ctx`), and the `api-renamed` warning code they used.
|
|
33
|
+
- No longer `@experimental` (they are named in the recipes and sit beside stable siblings): `engine.mod`, `engine.stateApplied`, `post.get`, `post.list`, `quests.isDone`, `quests.isFailed`, `vars.setFlag`, `input.released`, `input.keysOf`, `vegetation.isRemoved`, `vegetation.restoreInstance`, `ui.isOpen`, `settings.isOpen`, `random.int`. `saves.removeAttachment` stays `@experimental` because `saves.putAttachment`, the other half of the pair, is.
|
|
34
|
+
- The API lock (`docs/api-surface.txt`) now has an `events` group (every event name in `events.generated.js`, so a rename or removal needs a changelog line), lists `engine.debug` member by member (`debug.view`, `debug.defineView`, `debug.override`, `debug.clear`, `debug.viewModes`...; the type of `engine.debug` is the named `DebugApi`), and skips members tagged `@internal` in the hand-written declarations too. `api/*.md` no longer lists `@deprecated` aliases or `@internal` members.
|
|
35
|
+
- Verb rule R69 now also covers the ways to give back: `remove` is the verb, and `clear`, `forget`, `release`, `unload` and `dispose` are allowed only where they do what remove cannot (each exception states why in the rule and in CONVENTIONS.md). `triggers.clear` stays (it empties the whole set in one call); nothing else was renamed.
|
|
36
|
+
- explain grows a key, `{ asset: name }` (engine.explain): it says who holds an asset (lease labels such as `content:oak`, `pickups`, `model copy`) and why a pinned or retired build is still in memory. Nothing to change in a game.
|
|
37
|
+
- One state-application path. `saves.load(slot, { turn })`, `session.newGame({ turn })` and `session.quit({ turn })` take the turn a save part's `load()`, an `afterLoad` or a module's `applyState(e, params, turn)` was given, and then run inside that request, as `level.load({ turn })` does; without it they wait in line as before. `engine.applyState` is one request in the state line: a second call starts when the first ended. A part registered after its save was loaded loads like a load (ops return `'loading'` meanwhile, its `afterLoad` hooks run after it); an atomic op's rollback goes past a part that throws, waits for an async part and keeps unchanged world models; `afterLoad` skips failed, blocked and disabled modules and waits for one still initializing; a `session.track` handle whose `remove()` throws no longer stops a new game or load.
|
|
38
|
+
- Renamed: `engine.saves.register` -> `engine.saves.define`, `ctx.saves.register` -> `ctx.saves.define`; `characters.createPlayer` -> `characters.addPlayer`; `input.action` -> `input.define` (and `ctx.input`); `hud.counter` -> `hud.addCounter`, which also returns a handle `{ set(value), remove() }`. Every other named registry already says `define` (`ops.define`, `ui.define`, `stacks.define`); one verb set: `define`, `add`, `set`, `remove`, `describe` (AI.md, rule R69).
|
|
39
|
+
- Picture menu: `engine.catalog('picture')` (and `threedog catalog picture`) lists every picture capability, one row each: on now, runs here or why not, cost class, one way on, recipe, main limit; `catalog(id, { offered })` adds effects not in the chain yet (no change for existing calls). Lookup names: `module:<id>`, `op:<name>`, `capability:<id>` pick the kind; a bare name tries the capabilities (`picture`, `post`, `shadows`) first, so a game module named `picture` (the game template has one) is now `catalog('module:picture')`. Combination checks (kind `mistake`: baked light plus the fill it saw; kind `note`, facts without a must-fix: metal with no environment map, bloom before a low exposure, fog color far from a flat background, the nearest caster outside every shadow box) print in `describe().render` (`checks`) and first in `threedog shot`'s hints; `describe().render.probes[].doubled` and `.lightmap.doubled` are gone, read `describe().render.checks` (id `lit-twice`). Every `@threedog/post-effects` effect carries `about` (also on its factory).
|
|
40
|
+
- `engine.catalog(id)` and `threedog catalog` take one prefix scheme, `module:`, `op:`, `capability:`; a bare name that is both a capability and a module gives the capability: the game template's `picture` module is now `catalog('module:picture')` (`catalog('picture')` is the picture menu).
|
|
41
|
+
- Perf pass 2: `engine.inspect.perf().textureMB` (and `threedog perf`'s texture MB) reads three's `texturesSize` on WebGPU and adds shadow maps to the WebGL estimate (it read 0 with TSL or procedural materials); occlusion culling no longer drops hidden casters' shadows for a second after cascades are rebuilt, and skips the test box of a batch the camera stands in; the kept shadow map refills at most once every 8 shadow frames for instance writes (streaming batches); hlod `remove()` hands its meshes back to batching.
|
|
42
|
+
- Far trees as cards: `vegetation.define(name, { impostor: true })` (or `{ views, size }`) bakes views of the species' own model and materials and draws everything beyond `lodRing` as one card mesh per species, lit live through baked normals; no shadow there. Off by default, instead of `lodGeometry`. WebGPU only (WebGL draws the mesh and warns). `threedog perf --only=pages --renderer=webgpu --impostor` compares.
|
|
43
|
+
- Module timing (`engine.profile()`, the budget's `modules` limits, the spiky marker) counts fixed hooks one step per frame, the dearest: slow frames' catch-up steps no longer read as a physics spike. hlod no longer lets batching take a mesh it took; the kept shadow map (`engine.shadows.cache`) redraws when a kept instanced mesh is hidden, swapped, stops casting or leaves the scene (vegetation rings). `threedog perf` prints each page's worst modules as median/p95.
|
|
44
|
+
- Adaptive quality: under load the adaptive controller now walks `engine.adaptive.steps` (default: each post effect's declared `cheaper` params, then the resolution, then effects that declare `skipOnLowTier` held off) and raises them back in reverse; a game's own knob is a `{ name, down, up }` step, `['resolution']` keeps the old behavior. The perf notice's clause is now `lowered automatically: resolution 1.5 -> 1.2, reflections cheaper (...)`, and the first dev warning reads the same. A direct `renderer.setPixelRatio` now takes only the resolution step out, not the whole controller. Recipe 15 section 4b.
|
|
45
|
+
- Path-traced photos: `photo({ pathTracer: () => import('three-gpu-pathtracer/webgpu') })` and `photo.trace({ samples, seconds })` (a Promise of the shot, with `pathTraced` naming what the tracer did not draw as the game does; progress in `photo.tracing`), op `photo.trace`; `take()` is unchanged. `threedog shot --path-trace [--samples n]` writes that view as a reference picture. The tracer is the game's optional package (recipe 26).
|
|
46
|
+
- WebGPU picture, all optional: `autoExposure()` from `@threedog/post-effects/tsl` (exposure that adapts like an eye, measured on the GPU, before tone mapping); `pcss()` from `threedog/tsl`, a shadow filter for `light.shadow.filterNode` whose edge softens with distance (it reaches the engine's cascades); a `RectAreaLight` in the scene no longer needs `RectAreaLightNode.setLTC` / `RectAreaLightUniformsLib.init` from the game, on either renderer (recipe 34). Nothing changes for a game that uses none of them.
|
|
47
|
+
- Reflections on WebGPU: `reflections()` from `@threedog/post-effects/tsl` (three's `SSRNode`, mirror mode, in proportion to metalness; held on low tier; recipe 34). Post effects can ask `needsBuffers: ['metalRough']`, one 8-bit target merged into the same scene render.
|
|
48
|
+
- Streamed content whose material the renderer has not drawn yet attaches once its shaders are compiled and its textures uploaded (a task later); `budget: { gpuMemoryMB }` on WebGPU (three's own estimate).
|
|
49
|
+
- Vegetation draws fewer calls for the same picture: each chunk's plants are now frustum culled by three against every camera, so the main view skips the nearest chunks behind it and each shadow camera (every cascade) draws only the chunks inside its own box. Before, the nearest ring drew in full behind the camera and every cascade drew every casting chunk. World example: 213 -> 190 draw calls (vegetation 93 -> 57), with 3 cascades 329 -> 297 (vegetation 137 -> 75); screenshots differ no more than two runs of the same build. Chunks off the main view are no longer hidden as a whole, so trees just outside the picture keep the shadows they cast into it; a felled plant is drawn at zero scale where it stood (an all-zero matrix made the chunk's bounding sphere NaN, so rays missed every plant of that chunk). Nothing to change in a game
|
|
50
|
+
- The engine's random pattern changes once: grain, paper, stroke and dab detail, cloud shadows, sky clouds, stars, outline wobble and film grain now use one integer hash, so WebGL and WebGPU draw the same pattern (the old sin-based hash gave each GPU and backend its own). Density, size, softness and brightness are unchanged; only the arrangement moves. The public functions keep their names and meaning: `threedogHash(vec2)` (TSL `fx.hash`), `threedogNoise(vec2)` and the post snippets' `fxHash(vec2)` take any position, as before.
|
|
51
|
+
- `threedog assets check` checks `needs` on the file the engine loads (the winning entry after all packs, `optimized` included, at `public/<url>`), whatever folder is checked; `content check` warns when `collide.layer` is on a tilted prop (the same rule as the runtime warning); the MCP tools `scenario` and `verify` take `freezeReload` like the CLI's `--freeze-reload`.
|
|
52
|
+
- Model contract: a manifest model entry can declare `needs: { nodes: [...], clips: [...] }`. `threedog assets check` errors for each node or clip the glb lost (with the closest name it has), and the load warns the same line once (`[asset-needs]`). Optional; games without `needs` are unchanged. The optimized pack from `assets optimize` now replaces only the file (url, lods, node, and a generator or Texture it stands in for), so `needs` and `prepare` survive and a generator no longer shadows the optimized file. The `optimized` pack that `threedog assets optimize` writes now swaps only the file (url, lods, a part's node): the original entry's other options (`needs`, `prepare`, `params`) stay, where before the whole entry was replaced and they were lost.
|
|
53
|
+
- `threedog play`, `status`, `verify` and `scenario` now check their options with the shared strict parser: a mistyped one (`play --stopp`, `verify --freeze-relod x`) fails with the list of valid options instead of running the command the default way, and `verify` / `scenario` take one scenario name. The real options (`--stop`, `--freeze-reload`) are unchanged.
|
|
54
|
+
- A model given to `vegetation.define({ model })` now draws with the material the game made, plus only the engine's wind / season / clouds. The copy vegetation makes of each material used to keep only what three's `clone()` knows, so a NodeMaterial's own `setupLightingModel` (the `celLighting` route), a field its class never declares and a classic material's own `onBeforeCompile` were dropped and the trees drew with three's plain lighting. Every engine copy of a material (vegetation, tinted characters and pickups, terrain textures, batching) now carries them. A code-built model named in `define` (`model: 'bush'`, a manifest generator that returns an Object3D) goes through the game's `engine.assets.onModel` first, like a content prop of that name. An attribute on only some meshes of the model (uv on the leaves only) is still dropped from the species, now with a `vegetation-ignored` notice in `describe().warnings`.
|
|
55
|
+
- `temporalAA` works with the vegetation module on WebGPU. Grass with wind and the near-only fade read each instance's matrix again in every patch (4 vertex inputs each), and temporalAA's velocity buffer added 4 more, past the device's 16, so its pipeline failed and a game had to fall back to MSAA. `objectOrigin()` / `instanceOffset()` (threedog/tsl) now share one input per matrix column in a program: such grass needs 9 inputs, 13 with temporalAA. The picture is the same.
|
|
56
|
+
- A WebGPU program that needs more vertex inputs (or buffers) than the device has stops at its build with a `[vertex-inputs]` error counting what stacked up (geometry attributes, instance matrix and color, last frame's matrix for the velocity buffer, engine patches, the material's own attribute nodes) and what to do, instead of three's raw pipeline or attribute-location error. three draws its plain stand-in for that mesh.
|
|
57
|
+
- Collider layers: `collision.addBox`, `collision.addCircle`, `collision.addSegment` and `collision.addObject` take `layer: 'gate'`, and a character (`createPlayer`, `npcs.add`) takes `passes: ['gate']`. Such a body walks through those colliders and every other body is stopped; `findPath`, `characters.findPathAsync`, `walkTo`, NPC paths, the navmesh and the `rapier` mover follow it. `collision.walkable` takes `passes` too, `collision.walkableAt` and `collision.resolve` an extra `passes` argument. Nothing changes for a game that uses neither (recipe 12, "Gates some characters pass").
|
|
58
|
+
- `engine.assets.onModel((model, name) => ...)` runs the game's setup once on every model copy the engine hands out, before it is drawn (it leaves the root's place, turn and size to the placer: dev throws on a change): `assets.model` / `modelNow` / `lod`, content props and templates, pickups, character bodies and a level file. A game that recolored engine-made props with a scene sweep can drop the sweep. Games without it are unchanged.
|
|
59
|
+
- A manifest model can name one node of a multi-part file: `{ url: '/models/kit.glb', node: 'Wall.001' }`. The part sits at the origin with the turn and size it has in the file, the file loads once for all its parts, and a missing node name fails naming the close names (three's renames `Wall001`, `Fence_1` are accepted).
|
|
60
|
+
- `threedog assets optimize` follows manifest entries `{ url, node }`: the file is optimized once, the entry is re-pointed at the optimized copy with the same node, and a node the file lacks (before or after) is reported as `model-needs`, together with the entry's `needs` checked on the optimized file.
|
|
61
|
+
- Collider layers reach content and levels: `collide: { layer: 'gate' }` on a prop or template (a box, or with `circle`), and a custom property `layer` on a `col_` mesh or `collider` object in a level. Same `passes` rule as `collision.addBox`; a non-text layer on a level wall warns `level-layer-ignored`, a layer on a tilted prop `content-layer-ignored` (collider3d has no layers), and either one then stops every mover.
|
|
62
|
+
- A glTF node authored hidden with `KHR_node_visibility` (`visible: false`) now loads hidden (three 0.187 ignores the extension); its children are hidden with it. `threedog assets check` lists such nodes in one `hidden` line per file.
|
|
63
|
+
- `engine.hud.hint(id, { action, label, anchor })` (UI part `hud.hint`, @experimental): an on-screen key hint "E · Talk" (written like the interaction prompt). The key text is `engine.input.label(action)`, so it follows rebinding and keyboard / pad switching, and an action that needs a key and has none shows the `input.noKey` text, as the prompt does; `hud.button` takes `action` too and shows its key.
|
|
64
|
+
- `engine.hud.button(id, { label, run, icon, anchor })` (UI part `hud.button`): a clickable HUD button. The press never reaches the game (no shot, no look-drag, no pointer lock), focus goes back to the game after a click, and `label` goes through `engine.t`. `hud.remove(id)` takes it away.
|
|
65
|
+
- With `nav()` installed but no navmesh (procedural terrain has none, a level may still be loading), `characters.findPath` / `findPathAsync` still use collision A*, and dev builds now warn once (`nav-fallback`) saying so. Which method answers is unchanged.
|
|
66
|
+
- `followCamera` keeps distance and pitch inside `minDistance`..`maxDistance` and `minPitch`..`maxPitch` as before, and now warns once in dev when a game asks for a value outside, naming the option to widen (`[camera-clamped]`). The same for a `rtsCamera` start height and a `firstPersonCamera` start pitch.
|
|
67
|
+
- `engine.describe().warnings` (dev): every warning said on the page, `{ count, list }` with the first 20 as `{ code, text, fix }`, so an AI sees a fallback or clamp without the console. Codes for "the engine used something other than what the game gave" end in `-clamped`, `-fallback`, `-ignored` or `-replaced`.
|
|
68
|
+
- `threedog scenario` / `verify`: a `press` step fails when a game action is blocked (an open window holds input, and the message says who), instead of passing with nothing pressed. A page reload during the run fails it with the reason. `until` is checked inside the page, so it no longer costs one round trip per tick.
|
|
69
|
+
- `threedog scenario|verify <name> --freeze-reload`: the dev server ignores file saves during the run (no page reload; a saved `index.html` still reloads), and takes them again when it ends (10 minutes at most). The reload error of a run points to it.
|
|
70
|
+
- `threedog dev` fetches the game page once after it starts and prints one line with the status and the next step when it is not 200.
|
|
71
|
+
- `threedog perf --size WxH`: measure at a given window size.
|
|
72
|
+
- Rule R33 finds a world model by the nearest binding of the name (scope-aware), not any variable of that name in the file. Rule R18 no longer reads a game doc's own helper names as engine API claims.
|
|
73
|
+
- `threedog assets check` notes (one information line per kind, not a warning; `--full` lists all) when a model's node name is one three.js GLTFLoader renames (`Wall.001` -> `Wall001`, `_1` suffixes), because `engine.assets` finds the part by the renamed name.
|
|
74
|
+
- `scripts/check-public-export.mjs [dir]` (repo maintainers): exits 1 naming internal records (`HANDOFF.md`, `docs/plans/`, test records, `games/`, ...) that git tracks in the public copy; for its pre-push hook.
|
|
75
|
+
- Performance you can see: `engine.budget.notice()` (also `describe().perf.notice`) is one line, printed by `describeText`, `threedog shot` and `threedog verify`, when the game is over limits it declared itself (never the engine's own reference limits), slower than its recorded baseline, has a spiky module (p95 over 3x its median and over 2 ms), or runs at a resolution adaptive resolution lowered; nothing when all is fine. `shot --save-baseline` / `verify <name> --save-baseline` write this machine's `.threedog/perf-baseline.json` (`engine.budget.record()`, keyed by GPU, canvas size, pixel ratio and camera; not committed, new games ignore `.threedog/`); later runs with the same key compare medians past a noise margin, modules that were 0 or new included. Budget limits take `modules: { terrain: 1.5 }` (ms per frame of one module).
|
|
76
|
+
- `engine.profile()` now returns `{ module: { ms, mean, p95 } }` per frame over the last 300 frame-hook cycles (ms is the median; it used to return the average and reset on read) and is on by default in dev builds; `profile(true)` still turns it on in production. Upgrade: read `.mean` where you used the number. `threedog inspect perf` lists the five dearest modules with p95. Meaning change, same keys: frame time `cpuMs` in `describe().perf`, `inspect.perf()`, the budget and the F3 panel is now one reading, the median of the last frames (`describe().perf.cpuFrames`), where it was the last frame (the panel: a half-second average); it is still 0 before the first frame and null while halted. `describe().perf.cpu` is still the last frame by phase.
|
|
77
|
+
- A vegetation species that is grass-scale (`nearOnly`, or `maxRing: 1`) and casts shadows by default gets a hint from `threedog content check` and a dev warning from `vegetation.define`: set `castShadow: false`, or `shadowRing: 0` to keep only the nearest ring (writing `castShadow: true` keeps them and silences it).
|
|
78
|
+
- `engine.profile()` judges a module first used after start on its own cycles (it read 0 ms for its first 300), and a level load or flow transition during play clears frame and module timing again once it settles, so its start-up cost is not counted as play.
|
|
79
|
+
- An action that cannot be read is explained by every cause: an opaque context above it, `shadowed-by:<context>` (a pass-through context binds the same key), `context-off:<context>` (its own context is not on the stack) and its gate owners, in what `press` reports; `describe().holds.shadowed` lists the shadowed actions. The interaction prompt, `hud.hint` and markers write a key and its text with one helper.
|
|
80
|
+
- Health check, errors and ops: `op:rolledBack` is sent once when an atomic op's rollback finishes; `engine:error` and `engine.error` also work in release builds; an async `run` is refused only for atomic ops (a plain op may return a Promise).
|
|
81
|
+
- Health check, saves: a stack in a save that no module knows is dropped with a warning, a damaged known stack refuses the load; a save part's `first` may be a number (lower ranks load first); a failed photo save is told once; new error codes `save-provider-changed` and `fog-fallback`.
|
|
82
|
+
- Health check, picture: `vegetation.plantOf(hit)` returns the plant a ray hit (species, cx, cz, id, position) for `removeInstance`; `post.byRole(role, name?)` falls back to the effect's name when no effect declares the role in `about.acts`.
|
|
83
|
+
- Health check, colour: `renderOnce(target)` returns display pixels like the screen; WebGL direct fog is mixed in linear space (`threePatches.off('fog-linear')` turns it off); the sky environment yields to a game's own and takes the map back.
|
|
84
|
+
- Health check, tiers: tier-following defaults (sun shadow map, weather count, sky environment interval, terrain colour map); a shared boolean switch warns the writer that loses; the settings shadows row hides with no caster.
|
|
85
|
+
|
|
86
|
+
## 1.1.0 (2026-11-08)
|
|
87
|
+
|
|
88
|
+
- `threedog check` type-checks every `.js` of a game, not a list of known folders (`main.js`, `game/`, `content/`, `picture/`, `plugins/`). Code in another folder (`landmarks/`, `data/`, ...) was skipped while `check` said it passed, and a mistake there only failed in the build. Those files now count, so a game can show type errors it did not show before. Assets and tests (`public/`, `tests/`, `docs/`, `shots/`) are still left out. The game template's `tsconfig.json` includes all `.js` the same way.
|
|
89
|
+
- `threedog shot --cam x,y,z,targetX,targetY,targetZ[,fov]` places the camera at a pose without a view declared in the game (a facade, a roofline, a far backdrop). It cannot be combined with `--view`.
|
|
90
|
+
- The picture check reports meshes that lie entirely beyond `camera.far` (never drawn from there) as a fact, with the documented way to move the plane: `engine.autoView.manual('far')`.
|
|
91
|
+
- The picture check's "time barely changes the picture" line says it varied `engine.calendar.timeOfDay`; a game that switches its lights by its own presets can ignore it.
|
|
92
|
+
- API page of `followCamera`: `minPitch` and `maxPitch` state their defaults (0.05 and 1.35) and that the view cannot look up unless `minPitch` is negative.
|
|
93
|
+
- The game template's `CLAUDE.md` tells a helper's brief to start with `threedog how`, recipes 60 and 62 for the picture and a clean `check`.
|
|
94
|
+
|
|
5
95
|
## 1.0.1 (2026-11-07)
|
|
6
96
|
|
|
7
97
|
- Docs only: the install lines in the package READMEs name 1.0 (0.9 was never on npm).
|
package/README.md
CHANGED
|
@@ -20,7 +20,7 @@ import { terrainPreset } from '@threedog/terrain-noise'; // optional terrain g
|
|
|
20
20
|
|
|
21
21
|
const engine = createEngine({ canvas: document.getElementById('view'), renderer: 'webgpu' }); // no picture code yet: gray placeholders
|
|
22
22
|
engine.use(openWorld({ camera: 'follow', seed: 7, terrain: terrainPreset() }));
|
|
23
|
-
engine.characters.
|
|
23
|
+
engine.characters.addPlayer({ ...presets.player.thirdPerson });
|
|
24
24
|
engine.start();
|
|
25
25
|
```
|
|
26
26
|
The picture is the game's own: plain three.js in its `picture/` folder (what `threedog new-game` generates), reading signals from `engine.uniforms`. A new game runs on WebGPU with TSL shaders, or on WebGL with GLSL shaders through `--webgl`. A browser without WebGPU still runs the WebGPU form, on three's WebGL2 backend, slower; `describe().renderer` says why.
|
package/core/assets/Animator.js
CHANGED
|
@@ -19,6 +19,7 @@ import * as THREE from 'three';
|
|
|
19
19
|
import { warnOnce, warnMissing, missingText } from '../base/validate.js';
|
|
20
20
|
import { readParams, keysSchema } from '../base/params.js';
|
|
21
21
|
import { isOptions } from '../base/util.js';
|
|
22
|
+
import { addAim, addFeet, ikRestore, ikRun, ikClear } from './ik.js';
|
|
22
23
|
const GO_KEYS = ['fade'];
|
|
23
24
|
|
|
24
25
|
// Config keys: a typo (loops: false, state: {...}) would silently play the wrong thing, so both levels are checked like any other options
|
|
@@ -61,12 +62,24 @@ export class Animator {
|
|
|
61
62
|
// A static model (a procedural prop, a model exported without clips) has nothing to play: no dev warnings, no per-frame hook; go() / action() just return null.
|
|
62
63
|
this.hasClips = this.clips.length > 0;
|
|
63
64
|
this._hook = null;
|
|
65
|
+
/** @internal the time channel's scale for this model, () => number; a Character sets it (useModel.js). null: engine time as it is */
|
|
66
|
+
this._rate = null;
|
|
67
|
+
this._ik = []; // IK layers (ik.js), run after the mixer in the order added
|
|
68
|
+
this._ikPose = new Map(); // bone IK writes -> { q, p, n }: its pose before IK, put back before the next mixer update
|
|
69
|
+
/** @internal ground height for addFeet, (x, z, y) => y; a Character hands over its own (platforms, only while grounded) */
|
|
70
|
+
this._ground = (x, z, y) => engine.surface(x, z, y);
|
|
71
|
+
/** @internal may the feet stand now; a Character says no while it jumps or swims */
|
|
72
|
+
this._standing = () => true;
|
|
64
73
|
if (this.hasClips) {
|
|
65
74
|
this._check();
|
|
66
75
|
this.mixer.addEventListener('finished', ev => this._finished(ev.action));
|
|
67
|
-
this.
|
|
76
|
+
this._needHook();
|
|
68
77
|
}
|
|
69
78
|
}
|
|
79
|
+
/** @internal the per-frame update; a model without clips gets it only once an IK layer needs it */
|
|
80
|
+
_needHook() { this._hook ??= this.engine._onAnimate(dt => this.update(this.engine.still ? 0 : dt * (this._rate?.() ?? 1))); }
|
|
81
|
+
/** @internal */
|
|
82
|
+
_dropHook() { this._hook?.remove(); this._hook = null; }
|
|
70
83
|
/** Dev check at build time: the same problems check() returns, minus the game's action list (the Animator does not know it). */
|
|
71
84
|
_check() {
|
|
72
85
|
for (const [st, def] of Object.entries(this.states)) if (isOptions(def)) readParams(`assets.animate() ${this._where(st)}`, keysSchema(STATE_KEYS), def);
|
|
@@ -114,6 +127,28 @@ export class Animator {
|
|
|
114
127
|
return fade ?? t[`${from}>${to}`] ?? t[`*>${to}`] ?? t[`${from}>*`] ?? this.fade;
|
|
115
128
|
}
|
|
116
129
|
|
|
130
|
+
/**
|
|
131
|
+
* Turn a bone, or a chain spread from the body out, to look at a target, as the last layer on top of the clips (also on a model without clips).
|
|
132
|
+
* The last bone's forward is the model's front in its bind pose, whatever way the rig's axes point (forward: [x, y, z] in its own axes overrides).
|
|
133
|
+
* limit: degrees it may turn away from where the animation points it (beyond, it stops at the limit); speed: degrees per second; weight 0-1 fades
|
|
134
|
+
* in and out over fade seconds; target null looks ahead again. Weight 0 leaves the animation pose exactly; remove() puts it back at once.
|
|
135
|
+
* @example const look = npc.anim.addAim({ bones: ['Neck', 'Head'], target: engine.player.root, limit: 70 });
|
|
136
|
+
* look.set({ target: null }); look.remove();
|
|
137
|
+
* @param {{ bones: string | string[], target?: import('three').Object3D | import('three').Vector3 | [number, number, number] | null, limit?: number, speed?: number, weight?: number, fade?: number, forward?: [number, number, number] }} opts
|
|
138
|
+
* @returns {{ set(opts: { target?: any, limit?: number, speed?: number, weight?: number, fade?: number }): any, remove(): void, describe(): { kind: string, bones: string[], weight: number } }}
|
|
139
|
+
*/
|
|
140
|
+
addAim(opts) { return addAim(this, opts); }
|
|
141
|
+
/**
|
|
142
|
+
* Feet on the ground: each leg (upper, lower, foot) bends so the foot stands on the ground under it, and the hips lower when one foot must reach down
|
|
143
|
+
* (stairs, slopes). The ground is the model's own: engine.surface, or for a Character its walking ground with platforms (only while grounded).
|
|
144
|
+
* legs: [[upper, lower, foot], ...] bone names, found by name when left out; reach: the most a foot moves up or down (m); far: beyond this distance from
|
|
145
|
+
* the camera it fades out and asks nothing; speed: how fast a foot follows a new height (1/s); ground: (x, z, y) => height overrides the ground.
|
|
146
|
+
* @example const feet = engine.player.anim.addFeet(); feet.set({ weight: 0 });
|
|
147
|
+
* @param {{ legs?: string[][], hips?: string, reach?: number, far?: number, speed?: number, weight?: number, fade?: number, ground?: (x: number, z: number, y: number) => number }} [opts]
|
|
148
|
+
* @returns {{ set(opts: { reach?: number, far?: number, speed?: number, weight?: number, fade?: number, ground?: Function }): any, remove(): void, describe(): { kind: string, bones: string[], weight: number } }}
|
|
149
|
+
*/
|
|
150
|
+
addFeet(opts) { return addFeet(this, opts); }
|
|
151
|
+
|
|
117
152
|
/** Set a parameter for blend trees (e.g. speed). */
|
|
118
153
|
set(param, v) { this.params[param] = v; return this; }
|
|
119
154
|
|
|
@@ -228,6 +263,7 @@ export class Animator {
|
|
|
228
263
|
/** @internal Per frame: advance fades, split blend-tree weights by parameter, sync stride, then advance the mixer (the engine calls it). */
|
|
229
264
|
update(dt) {
|
|
230
265
|
if (this._held) { this.afterPose?.(dt); return; } // physics owns the bones (a ragdoll): the mixer writes nothing, attachments still follow the pose
|
|
266
|
+
if (this._ik.length) ikRestore(this);
|
|
231
267
|
let j = 0; // fade, stop faded-out layers and compact in place (no arrays per frame)
|
|
232
268
|
for (const l of this._layers) {
|
|
233
269
|
if (l.w < l.target) l.w = Math.min(l.target, l.w + dt * l.rate);
|
|
@@ -238,6 +274,7 @@ export class Animator {
|
|
|
238
274
|
this._layers.length = j;
|
|
239
275
|
this._weights();
|
|
240
276
|
this.mixer.update(dt);
|
|
277
|
+
if (this._ik.length) ikRun(this, dt); // IK is the pose's last layer, before anything is attached to it
|
|
241
278
|
this.afterPose?.(dt); // Character.onPose callbacks (the pose is final here)
|
|
242
279
|
}
|
|
243
280
|
/** @internal is action a also held by a live layer other than l? (states may share a clip, and three keeps one action per clip) */
|
|
@@ -274,10 +311,11 @@ export class Animator {
|
|
|
274
311
|
const l = this._layers.find(x => x.name === this.state), a = l?.actions[0].a, dur = a?.getClip().duration || 0;
|
|
275
312
|
const total = this._layers.reduce((s, x) => s + x.w, 0) || 1; // shown as shares, like the mixer weights (they sum to 1)
|
|
276
313
|
return { state: this.state, clip: l?.actions[0].clip ?? null, time: a ? r3(a.time) : 0, progress: dur ? r3(a.time / dur) : 0,
|
|
277
|
-
driven: !!l?.driven, ...(l?.driven && { t: r3(this._t) }), weights: Object.fromEntries(this._layers.map(x => [x.name, r3(x.w / total)]))
|
|
314
|
+
driven: !!l?.driven, ...(l?.driven && { t: r3(this._t) }), weights: Object.fromEntries(this._layers.map(x => [x.name, r3(x.w / total)])),
|
|
315
|
+
...(this._ik.length && { ik: this._ik.map(x => ({ kind: x.kind, bones: x.names, weight: r3(x.w) })) }) };
|
|
278
316
|
}
|
|
279
317
|
/** Call when no longer needed to stop per-frame updates. */
|
|
280
|
-
dispose() { this.
|
|
318
|
+
dispose() { this._dropHook(); ikClear(this); this.mixer.stopAllAction(); }
|
|
281
319
|
}
|
|
282
320
|
|
|
283
321
|
export const handRolled = [{ kind: 'animation', seen: 'an AnimationMixer of its own', use: 'engine.assets.animate(model, { states }): states, crossfades, sync with game time and pause (recipe 13)', quiet: /\bassets\.animate\b/, code: /\bnew\s+(?:THREE\.)?AnimationMixer\s*\(|\bmixer\.update\s*\(/i }];
|
package/core/assets/Assets.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// Asset management:
|
|
2
2
|
// 1. Asset manifest: register every model, texture and sound under a name; code uses names only, so swapping a file means editing the manifest.
|
|
3
3
|
// 2. Preload: load everything marked preload once at startup; the loading screen shows progress.
|
|
4
|
-
// 3. Cache and reuse: one file
|
|
4
|
+
// 3. Cache and reuse: one name loads once (two names for one file load it twice; register the file once); models return independent copies (geometry and materials shared), so you can place many.
|
|
5
5
|
// 4. Release: one count of leases, and a model copy is one (assetEntry.js takeLease); release(name) frees only when the last lease ends, trim() frees every model with no copy in use (see their docs
|
|
6
6
|
// below).
|
|
7
7
|
// 5. Compression: Draco / Meshopt models and .ktx2 textures load as-is; the decoder downloads on first use (npm run assets -- optimize produces compressed files in public/optimized/).
|
|
@@ -27,24 +27,30 @@
|
|
|
27
27
|
import { reportGltf } from './assetReport.js';
|
|
28
28
|
import * as THREE from 'three';
|
|
29
29
|
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
|
|
30
|
+
import { nodeVisibility } from './nodeVisibility.js';
|
|
30
31
|
import { MeshoptDecoder } from 'three/addons/libs/meshopt_decoder.module.js';
|
|
31
|
-
import { clone as skeletonClone } from 'three/addons/utils/SkeletonUtils.js';
|
|
32
32
|
import { warnMissing, warnOnce, fmt, DEV } from '../base/validate.js';
|
|
33
33
|
import { codedError, coded } from '../base/errorHints.js';
|
|
34
34
|
import { Animator } from './Animator.js';
|
|
35
|
-
import { waitLoad, freeEntry, retireEntry, takeLease, disposeEntries, preloadEntries, shadowDefaults, longSound } from './assetEntry.js';
|
|
35
|
+
import { waitLoad, freeEntry, retireEntry, takeLease, explainAsset, disposeEntries, preloadEntries, shadowDefaults, longSound } from './assetEntry.js';
|
|
36
|
+
import { disposeProtos } from './namedModel.js';
|
|
36
37
|
import { registerManifest, paramValues } from './assetManifest.js';
|
|
37
38
|
import { setParams } from './assetHot.js';
|
|
38
39
|
import { wrapLod } from './assetLod.js';
|
|
39
40
|
import { schemaInfo } from '../base/params.js';
|
|
40
41
|
import { loadGrid } from '../scene/gridLoad.js';
|
|
41
42
|
import { memory } from '../../render/backend.js';
|
|
43
|
+
import { freeParts, copyOwns, cloneModel } from '../base/freeParts.js';
|
|
42
44
|
|
|
43
45
|
const STRINGS = {
|
|
44
46
|
textureFailed: "{where}: texture '{name}' did not load ({msg}); {instead}. Register it (engine.assets.manifest({ textures: { name: 'file.png' } })) or check its URL",
|
|
45
47
|
notLoaded: 'assets.modelNow(\'{name}\') is null: nothing has loaded that model yet (a code-built model is built, or read from the bake cache, on its first load too). Use `engine.assets.modelNow(\'{name}\') ?? await engine.assets.model(\'{name}\')`, or mark it preload: true in the manifest and await engine.assets.preload()',
|
|
46
48
|
noLease: 'assets.lease(\'{name}\'): nothing is registered or loaded under that name, so there is no data to hold. Fix: register it in an asset pack, or load it first with assets.model / assets.texture',
|
|
47
49
|
noFont: 'assets.font(\'{name}\'): no font named {name}{known}. Register the file in an asset pack: engine.assets.manifest({ fonts: { {name}: \'/fonts/{name}.woff2\' } })',
|
|
50
|
+
twoSetups: 'assets.onModel(): a setup is already registered. One setup runs on every model, so two would leave the result to their order. Call both from one function: engine.assets.onModel((model, name) => { first(model, name); second(model, name); })',
|
|
51
|
+
asyncSetup: 'assets.onModel(): the setup returned a promise, but it must be synchronous: the model is added and drawn right after it returns. Load what it needs first (await the textures, then register the setup)',
|
|
52
|
+
movedRoot: "assets.onModel(): the setup changed the position, turn or size of the model '{name}' itself. Its placer owns those (content writes rot / scale from the record, your code places what it loads), so the change would be overwritten. Change a child instead: model.children.forEach(c => c.rotation.y += Math.PI)",
|
|
53
|
+
lateSetup: 'assets.onModel(): {n} model copies were handed out before onModel was registered and did not run the setup. Register it right after createEngine, before start(), content and the first model()',
|
|
48
54
|
sameName: 'model \'{name}\': the same name was used with two different generator functions, so the cache would mix them (keyed by name + params). Use a different name per model; if the result depends on outer variables, put them in params',
|
|
49
55
|
};
|
|
50
56
|
/** Short hash of the source (cache key; tells apart same-name, different-function cases) */
|
|
@@ -56,10 +62,11 @@ export class Assets {
|
|
|
56
62
|
this.entries = new Map(); // name -> { type, url, opts, promise, value, load, users } (who owns the data: top of assetEntry.js)
|
|
57
63
|
this.gltf = new GLTFLoader();
|
|
58
64
|
this.gltf.setMeshoptDecoder(MeshoptDecoder);
|
|
65
|
+
this.gltf.register(nodeVisibility); // a node hidden in the file stays hidden (three does not read KHR_node_visibility)
|
|
59
66
|
this.draco = null; // DRACOLoader / KTX2Loader:created on the first compressed data
|
|
60
67
|
this.ktx2 = null;
|
|
61
68
|
this.tex = new THREE.TextureLoader();
|
|
62
|
-
this.shared = new WeakSet(); // geometry and
|
|
69
|
+
this.shared = new WeakSet(); // what asset loads own: model geometry, materials and their textures, loaded textures (engine.remove / engine.dispose never dispose them; assetEntry.js share)
|
|
63
70
|
this._instances = new WeakMap(); // model copy root -> { e: the entry it was asked for by, load: the load that owns its data }
|
|
64
71
|
this._retired = new Set(); // old loads no entry points at, kept for the copies or geometry still using them
|
|
65
72
|
this._disposed = false;
|
|
@@ -68,7 +75,7 @@ export class Assets {
|
|
|
68
75
|
/**
|
|
69
76
|
* Named colors for what is made in code: a generator written with `function` reads this.palette. Plain data, read or replace it freely:
|
|
70
77
|
* it is part of the cache key, so a model or texture asked for after a write is built from the new colors. Copies already placed keep theirs,
|
|
71
|
-
* and a model's old build
|
|
78
|
+
* and a generated model's old build stays cached until engine.dispose.
|
|
72
79
|
* @example engine.assets.palette = { leaf: 0xd98a3a, bark: 0x6b4a30 };
|
|
73
80
|
* @type {Record<string, any>}
|
|
74
81
|
*/
|
|
@@ -90,10 +97,65 @@ export class Assets {
|
|
|
90
97
|
* 'rock' } } });
|
|
91
98
|
* @example import forest from 'my-forest-assets'; engine.assets.manifest(forest); // { name: 'forest', base, models: { oak: 'oak.glb' } }
|
|
92
99
|
* @example import packs from '../assets.js'; engine.assets.manifest(packs); // a list: the game's assets.js, which `npm run check` reads too
|
|
100
|
+
* @example engine.assets.manifest({ models: { wall: { url: '/models/kit.glb', node: 'Wall.001' } } }); // one node of a multi-part file: placed at the origin, the file loads once
|
|
93
101
|
* @param {import('../../types/core').AssetManifest | import('../../types/core').AssetManifest[]} [pack]
|
|
94
102
|
*/
|
|
95
103
|
manifest(pack = {}) { return registerManifest(this, pack); }
|
|
96
104
|
|
|
105
|
+
/**
|
|
106
|
+
* The game's setup for every model the engine hands out: fn(model, name) runs once on each copy, before it is added or drawn, whoever made it:
|
|
107
|
+
* assets.model / modelNow / lod, content props and templates, pickups, character bodies and a level file. Use it for what the game does to
|
|
108
|
+
* every model (its own materials, layers, userData). Synchronous; one per engine (a second throws); register it before the first model. The root's place, turn and size
|
|
109
|
+
* stay its placer's (dev throws on a change): turn or size a child.
|
|
110
|
+
* A copy shares geometry and materials with the other copies: map each original material to one of yours (a Map), or every copy draws apart and
|
|
111
|
+
* engine.batching cannot merge them. Runs on a code-built model vegetation.define takes by name (before its meshes are copied into instances), not on a bare
|
|
112
|
+
* geometry (a file model named in vegetation gives only its first mesh's geometry) or on what a game builds itself.
|
|
113
|
+
* @example const mine = new Map(); engine.assets.onModel(model => model.traverse(o => { if (o.isMesh) o.material = mine.get(o.material) ?? mine.set(o.material, toon(o.material)).get(o.material); }));
|
|
114
|
+
* @param {(model: THREE.Object3D, name: string) => void} fn
|
|
115
|
+
* @returns {{ remove(): void }}
|
|
116
|
+
*/
|
|
117
|
+
onModel(fn) {
|
|
118
|
+
if (typeof fn !== 'function') throw codedError('asset-misuse', `assets.onModel(fn): fn must be a function (got ${typeof fn})`);
|
|
119
|
+
if (this._setup) throw codedError('asset-misuse', STRINGS.twoSetups);
|
|
120
|
+
if (this._handedOut) warnOnce(coded('asset-misuse', fmt(STRINGS.lateSetup, { n: this._handedOut })));
|
|
121
|
+
this._setup = fn;
|
|
122
|
+
return { remove: () => { if (this._setup === fn) this._setup = null; } };
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* @internal The one door a model leaves by to the game or the scene: runs the onModel setup on it once. Every place that makes a copy for the game calls it
|
|
126
|
+
* (the guard test 'model setup: every clone handed to the game goes through handOut'); prototypes and the bare _copy never do
|
|
127
|
+
*/
|
|
128
|
+
handOut(root, name, { static: isStatic = false } = {}) {
|
|
129
|
+
this._handedOut = (this._handedOut ?? 0) + 1;
|
|
130
|
+
const fn = this._setup;
|
|
131
|
+
if (fn && !this._prepared?.has(root)) {
|
|
132
|
+
// one transaction: a setup that throws leaves nothing taken. The caller never gets the root, so it could not give back the copy's lease (or a LOD's levels') itself.
|
|
133
|
+
// What it holds is listed before the setup runs: a setup that took a level out and then threw would leave that level's lease outside the root
|
|
134
|
+
const held = []; root.traverse(o => { if (this._instances.has(o)) held.push(o); });
|
|
135
|
+
try {
|
|
136
|
+
const was = DEV && [...root.position.toArray(), ...root.quaternion.toArray(), ...root.scale.toArray()];
|
|
137
|
+
const r = fn(root, name);
|
|
138
|
+
if (typeof r?.then === 'function') throw codedError('asset-misuse', STRINGS.asyncSetup);
|
|
139
|
+
// the root's transform is the placer's (one writer): a setup that turned it would be undone by content's settle
|
|
140
|
+
if (was && [...root.position.toArray(), ...root.quaternion.toArray(), ...root.scale.toArray()].some((v, i) => v !== was[i])) throw codedError('asset-misuse', fmt(STRINGS.movedRoot, { name }));
|
|
141
|
+
} catch (err) { for (const o of held) this._giveBack(o); this.forget(root); throw err; } // both: and what the setup hung on it before it threw (each given back once)
|
|
142
|
+
(this._prepared ||= new WeakSet()).add(root); // only once it worked. Why a WeakSet and not userData: clone() copies userData, so a clone would look prepared
|
|
143
|
+
}
|
|
144
|
+
// after the setup: rays take the meshes it left (one it added is hit, one it removed is not). A LOD's low levels skip themselves (Rays.addStatic)
|
|
145
|
+
if (isStatic) this.addStatic(root);
|
|
146
|
+
return root;
|
|
147
|
+
}
|
|
148
|
+
/** @internal The one static-ray registration of a handed-out copy (handOut's static, content's settle): kept per root so a hot rebuild registers the new parts again (restatic). Returns { remove() } */
|
|
149
|
+
addStatic(root, opts) {
|
|
150
|
+
const s = { h: this.engine.rays.addStatic(root, opts), opts }, all = this._statics ||= new WeakMap();
|
|
151
|
+
all.get(root)?.h.remove(); all.set(root, s);
|
|
152
|
+
return { remove: () => { s.h.remove(); if (all.get(root) === s) all.delete(root); } };
|
|
153
|
+
}
|
|
154
|
+
/** @internal Register the root's parts again, with the options it was first registered with (nothing when it never was) */
|
|
155
|
+
restatic(root) { const s = this._statics?.get(root); if (s) { s.h.remove(); s.h = this.engine.rays.addStatic(root, s.opts); } }
|
|
156
|
+
/** @internal Did the game's setup run on this root (handOut, and it did not throw)? Content measures such a copy itself: the setup may have changed its size */
|
|
157
|
+
prepared(root) { return !!this._prepared?.has(root); }
|
|
158
|
+
|
|
97
159
|
/**
|
|
98
160
|
* The generator function registered under a model name (manifest models: { pine: fn } or { build }), null for a file model or an unknown name.
|
|
99
161
|
* Code rarely needs it: name the model instead (content { model: ['flower', 0xff0000] }, assets.model('flower'), item model, vegetation.define)
|
|
@@ -154,7 +216,7 @@ export class Assets {
|
|
|
154
216
|
/** @internal A model copy for a caller that cannot stand on a stand-in and may stop waiting: a failed file rejects whatever the manifest falls back to, and an aborted signal leaves the load (assetEntry.js) */
|
|
155
217
|
wholeModel(nameOrUrl, signal) {
|
|
156
218
|
const e = this._resolve(nameOrUrl, 'model');
|
|
157
|
-
return this._with(e, () => this._copy(e), { whole: true, signal });
|
|
219
|
+
return this._with(e, () => this._copy(e), { whole: true, signal }).then(root => this.handOut(root, e.name));
|
|
158
220
|
}
|
|
159
221
|
/** @internal The entry moves on from its current load (assetEntry.js) */
|
|
160
222
|
_retire(e) { retireEntry(this, e); }
|
|
@@ -187,8 +249,12 @@ export class Assets {
|
|
|
187
249
|
|
|
188
250
|
/** Get a model copy (name or path); skinned characters clone correctly. static: true registers it with engine.rays (builds ray acceleration) */
|
|
189
251
|
async model(nameOrUrl, opts = {}) {
|
|
252
|
+
return this.handOut(await this._bare(nameOrUrl, opts), this._resolve(nameOrUrl, 'model').name, opts);
|
|
253
|
+
}
|
|
254
|
+
/** @internal A copy that skips the onModel setup and static rays (handOut does both): a prototype that content and pickups clone (each clone is handed out), or a LOD level (the LOD is) */
|
|
255
|
+
_bare(nameOrUrl, opts = {}, by) {
|
|
190
256
|
const e = this._resolve(nameOrUrl, 'model');
|
|
191
|
-
return this._with(e, () => this._copy(e, opts));
|
|
257
|
+
return this._with(e, () => this._copy(e, opts, by));
|
|
192
258
|
}
|
|
193
259
|
/**
|
|
194
260
|
* A model copy as a plain THREE.LOD: the full model near, the levels of `threedog assets optimize --lod` far away (assetLod.js). Off unless called: model() never
|
|
@@ -198,7 +264,7 @@ export class Assets {
|
|
|
198
264
|
*/
|
|
199
265
|
async lod(nameOrUrl, opts = {}) {
|
|
200
266
|
const { distances, hysteresis, ...copy } = opts;
|
|
201
|
-
return wrapLod(this, nameOrUrl, await this.
|
|
267
|
+
return this.handOut(await wrapLod(this, nameOrUrl, await this._bare(nameOrUrl, copy), { distances, hysteresis }), this._resolve(nameOrUrl, 'model').name, copy);
|
|
202
268
|
}
|
|
203
269
|
/**
|
|
204
270
|
* A model copy right now if that model has already loaded, else null (never starts a load, never waits). For code that rebuilds often,
|
|
@@ -207,7 +273,7 @@ export class Assets {
|
|
|
207
273
|
*/
|
|
208
274
|
modelNow(nameOrUrl, opts = {}) {
|
|
209
275
|
const e = this.entries.get(nameOrUrl);
|
|
210
|
-
if (e?.type === 'model' && e.load?.value && !this._stale(e)) return this._copy(e, opts);
|
|
276
|
+
if (e?.type === 'model' && e.load?.value && !this._stale(e)) return this.handOut(this._copy(e, opts), e.name, opts);
|
|
211
277
|
// Why warn: generated models also need one load() first (dev reads the baked-cache GLB, release reads the baked file), so before any await model() this is null;
|
|
212
278
|
// in one playtest world.present only called modelNow, the model never showed up and nothing said why. Already loading (promise present) = no warning: that is a normal "not ready yet"
|
|
213
279
|
if (DEV && e?.type === 'model' && !e.promise) warnOnce(coded('asset-not-loaded', fmt(STRINGS.notLoaded, { name: nameOrUrl })));
|
|
@@ -221,30 +287,31 @@ export class Assets {
|
|
|
221
287
|
* @param {string} name a registered name, or a path already loaded
|
|
222
288
|
* @returns {Promise<{ name: string, remove(): void }>}
|
|
223
289
|
*/
|
|
224
|
-
async lease(name) {
|
|
290
|
+
async lease(name, by = 'assets.lease') {
|
|
225
291
|
const e = this.entries.get(name);
|
|
226
292
|
if (!e) throw codedError('unknown-name', fmt(STRINGS.noLease, { name }));
|
|
227
|
-
return this._with(e, () => this._lease(e, name));
|
|
293
|
+
return this._with(e, () => this._lease(e, name, undefined, by));
|
|
228
294
|
}
|
|
229
295
|
/** @internal the one place a lease is taken, and where describe().assets starts to report (only a game that holds something pays for the line) */
|
|
230
|
-
_lease(e, name) {
|
|
296
|
+
_lease(e, name, load, by) {
|
|
231
297
|
if (!this._reported) { this._reported = true; this.engine.describe?.add?.('assets', () => this._holders()); }
|
|
232
|
-
return takeLease(this, e, name);
|
|
298
|
+
return takeLease(this, e, name, load, by);
|
|
233
299
|
}
|
|
234
300
|
/** @internal describe().assets: leases per name (a model copy is one) and the names whose release waits for them; both empty again means every lease came back */
|
|
235
301
|
_holders() {
|
|
236
302
|
const held = [...this.entries].filter(([, e]) => e.users > 0);
|
|
237
303
|
return { leases: Object.fromEntries(held.map(([k, e]) => [k, e.users])), waiting: held.filter(([, e]) => e.releasePending).map(([k]) => k) };
|
|
238
304
|
}
|
|
305
|
+
/** @internal engine.explain({ asset }) */
|
|
306
|
+
_explain(name) { return explainAsset(this, name); }
|
|
239
307
|
/** @internal one copy of a loaded model, counted on the load that owns its data, which for a name that fell back belongs to the other entry */
|
|
240
|
-
_copy(e, { castShadow, receiveShadow
|
|
241
|
-
const load = e.load, gltf = load.value, root =
|
|
242
|
-
this._instances.set(root, { e, load, lease: this._lease(e) });
|
|
308
|
+
_copy(e, { castShadow, receiveShadow } = {}, by = 'model copy') {
|
|
309
|
+
const load = e.load, gltf = load.value, root = cloneModel(gltf.scene);
|
|
310
|
+
this._instances.set(root, { e, load, lease: this._lease(e, undefined, undefined, by) });
|
|
243
311
|
// the call, then the manifest entry; else a generator's own flags; else cast + receive (shadowDefaults, the same rule content props use)
|
|
244
312
|
shadowDefaults(root, { castShadow: castShadow ?? e.opts.castShadow, receiveShadow: receiveShadow ?? e.opts.receiveShadow });
|
|
245
313
|
root.animations = gltf.animations; // three's own place: .clone() keeps it as clips, where userData goes through JSON and the clips would come back broken
|
|
246
314
|
if (e.named) root.userData.modelName = e.name; // which named model this is; .clone() carries it, the _instances map does not (content capture reads it)
|
|
247
|
-
if (isStatic) this.engine.rays.addStatic(root);
|
|
248
315
|
return root;
|
|
249
316
|
}
|
|
250
317
|
/**
|
|
@@ -343,18 +410,27 @@ export class Assets {
|
|
|
343
410
|
_users(name) { return this.entries.get(name)?.users ?? 0; }
|
|
344
411
|
/** Called when an object is fully removed (engine.remove calls it): decrements the usage count of model copies beneath it and stops their animators */
|
|
345
412
|
forget(obj) {
|
|
346
|
-
obj.traverse(o =>
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
413
|
+
obj.traverse(o => this._giveBack(o));
|
|
414
|
+
}
|
|
415
|
+
/**
|
|
416
|
+
* @internal The one teardown of a model copy a module cloned itself (content props, pickups; engine.remove frees the same things around its own free): leases of the
|
|
417
|
+
* copy and of its LOD levels, Animators, and the bones skeletonClone gave it. Its geometry and materials are the asset's (or the prototype's) and stay.
|
|
418
|
+
* Why here and not in each module: each had a different subset (a LOD level's lease, a skinned copy's skeleton, an Animator's frame hook were left behind)
|
|
419
|
+
*/
|
|
420
|
+
dropCopy(root) { this.forget(root); freeParts(root, () => false, { own: o => copyOwns(this.shared, o) }); }
|
|
421
|
+
/** @internal One object's share: its animator stopped, its lease returned if it is a model copy. A second call does nothing (the copy is no longer listed) */
|
|
422
|
+
_giveBack(o) {
|
|
423
|
+
const anim = this._animators.get(o); if (anim) { this._animators.delete(o); anim.dispose(); }
|
|
424
|
+
const copy = this._instances.get(o); if (!copy) return;
|
|
425
|
+
this._instances.delete(o);
|
|
426
|
+
copy.lease.remove();
|
|
352
427
|
}
|
|
353
428
|
/**
|
|
354
429
|
* Release all loaded assets and decoders (engine.dispose calls it). A load still running ends and leaves nothing behind. Code awaiting one, and any later
|
|
355
430
|
* model() / texture() / font() call, stays pending for good: it never resumes against a disposed engine and never rejects during teardown
|
|
356
431
|
*/
|
|
357
432
|
dispose() {
|
|
433
|
+
disposeProtos(this.engine); // what model prototypes made (namedModel.js): no load owns it
|
|
358
434
|
disposeEntries(this);
|
|
359
435
|
this.draco?.dispose(); this.ktx2?.dispose();
|
|
360
436
|
}
|
|
@@ -378,7 +454,7 @@ export class Assets {
|
|
|
378
454
|
// their own, so nothing counts who uses it and a free would break placed props. Counting it needs those three modules to count their copies
|
|
379
455
|
return this._with(e, (g, load) => {
|
|
380
456
|
load.pinned = true;
|
|
381
|
-
return g.geometry ??
|
|
457
|
+
return g.geometry ?? cloneModel(g.scene);
|
|
382
458
|
});
|
|
383
459
|
}
|
|
384
460
|
/** Current usage: number of geometries and textures in GPU memory */
|