threedog 1.1.0 → 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 +879 -798
- 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 +139 -142
- 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/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 +796 -764
- 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
|
@@ -7,6 +7,8 @@ import { vegetationModel } from '../../core/assets/namedModel.js';
|
|
|
7
7
|
import { isModelName } from '../../core/base/util.js';
|
|
8
8
|
import { DEV, warnMissing, warnOnce } from '../../core/base/validate.js';
|
|
9
9
|
import { readParams, keysSchema } from '../../core/base/params.js';
|
|
10
|
+
// radius must be finite: an Infinity radius makes the chunk loops below start at -Infinity and never advance
|
|
11
|
+
const AT_PARAMS = keysSchema(['radius', 'species'], {}, { radius: { type: 'number', min: 0, optional: true } });
|
|
10
12
|
import { reportError } from '../../core/base/errors.js';
|
|
11
13
|
import { xzOf } from '../../core/base/math.js';
|
|
12
14
|
import { GroundChunks } from './groundChunks.js';
|
|
@@ -14,7 +16,20 @@ import { fadeBand } from './nearFade.js';
|
|
|
14
16
|
import { makeDensity, thin } from './densityMap.js';
|
|
15
17
|
import { coded, codedError } from '../../core/base/errorHints.js';
|
|
16
18
|
// parameters read by vegetation.define(); keys inside rule (sent to the worker thread)
|
|
17
|
-
const ADD_KEYS = ['geometry', 'model', 'lodGeometry', 'rule', 'positions', 'densityMap', 'wind', 'nearOnly', 'maxRing', 'lodRing', 'castShadow', 'shadowRing', 'receiveShadow', 'material', 'effects', 'doubleSided', 'fade'];
|
|
19
|
+
const ADD_KEYS = ['geometry', 'model', 'lodGeometry', 'rule', 'positions', 'densityMap', 'wind', 'nearOnly', 'maxRing', 'lodRing', 'castShadow', 'shadowRing', 'receiveShadow', 'material', 'effects', 'doubleSided', 'fade', 'impostor'];
|
|
20
|
+
/**
|
|
21
|
+
* The grass-shadow hint, or null: a species that is grass-scale by its own declaration (nearOnly, or drawn in the nearest ring only: maxRing 1) and
|
|
22
|
+
* casts shadow by the engine default (castShadow ?? !nearOnly, as define() reads it) without the game having chosen: a castShadow or shadowRing
|
|
23
|
+
* written out silences it. Thousands of small plants pay a shadow draw per chunk and cascade for a speckle few see. define() warns with it in dev,
|
|
24
|
+
* content check (tools/content-check/world.mjs) reports it as a hint: one predicate for both
|
|
25
|
+
* @param {string} name @param {any} o the define() / content options @returns {string | null}
|
|
26
|
+
*/
|
|
27
|
+
export function grassShadowHint(name, o) {
|
|
28
|
+
const small = o?.nearOnly || o?.maxRing <= 1, casts = o?.castShadow ?? !o?.nearOnly;
|
|
29
|
+
if (!small || !casts || o.castShadow !== undefined || o.shadowRing !== undefined) return null;
|
|
30
|
+
return `vegetation ${name} is grass-scale (${o.nearOnly ? 'nearOnly' : 'maxRing 1'}) and casts shadows by default, a shadow draw per chunk and cascade for little to see: `
|
|
31
|
+
+ 'set castShadow: false, or shadowRing: 0 to keep them only in the nearest ring (castShadow: true keeps them and silences this)';
|
|
32
|
+
}
|
|
18
33
|
const RULE_KEYS = ['perChunk', 'chance', 'minHeight', 'maxHeight', 'maxSlope', 'cluster', 'scale', 'stretch', 'sink', 'tintJitter', 'tints', 'biomes', 'collider', 'avoidFlat', 'salt'];
|
|
19
34
|
// rule keys that only filter random attempts: with positions the game already chose every spot, so naming one is a mistake, not a no-op
|
|
20
35
|
const SCATTER_ONLY = ['perChunk', 'chance', 'minHeight', 'maxHeight', 'maxSlope', 'cluster', 'biomes', 'avoidFlat'];
|
|
@@ -36,7 +51,7 @@ function checkPositions(label, list, rule) {
|
|
|
36
51
|
// const hit = engine.vegetation.instanceAt(position, { radius: 2, species: '松树' }); // → { species, cx, cz, id, position } or null
|
|
37
52
|
// engine.vegetation.removeInstance(hit.species, hit.cx, hit.cz, hit.id, { regrowSeconds: 300 }); // grows back after 300 calendar seconds
|
|
38
53
|
// engine.vegetation.restoreInstance(...) // restore immediately
|
|
39
|
-
// Hiding: the slot goes into c.hidden[name] (the draw part draws it
|
|
54
|
+
// Hiding: the slot goes into c.hidden[name] (the draw part draws it at zero scale, count unchanged) and out of the chunk's collision circles.
|
|
40
55
|
// Regrowth: the record stores the expiry time (engine.calendar seconds), checked once per second; the clock is saved, so the countdown continues after
|
|
41
56
|
// reload.
|
|
42
57
|
const KEY_RE = /^veg:(.*):(-?\d+),(-?\d+):(\d+)$/;
|
|
@@ -50,10 +65,22 @@ function slotOf(r, id) {
|
|
|
50
65
|
}
|
|
51
66
|
|
|
52
67
|
const REMOVE_KEYS = ['regrowSeconds'];
|
|
68
|
+
// impostor: true / false or { views, size }. The numbers size render targets (views layers of size x size), and content data can carry them,
|
|
69
|
+
// so a 0, NaN or huge value is refused here instead of building an empty or enormous target
|
|
70
|
+
function checkImpostor(label, v) {
|
|
71
|
+
if (v === true || v === false) return;
|
|
72
|
+
const bad = m => { throw codedError('vegetation-option', `${label}: impostor ${m}; write impostor: true or { views: 1..64, size: 16..1024 } (whole numbers)`); };
|
|
73
|
+
if (!v || typeof v !== 'object' || Array.isArray(v)) bad(`is ${JSON.stringify(v)}`);
|
|
74
|
+
readParams(`${label}.impostor`, keysSchema(['views', 'size']), v);
|
|
75
|
+
const int = (k, lo, hi) => { const n = v[k]; if (n !== undefined && !(Number.isInteger(n) && n >= lo && n <= hi)) bad(`${k} is ${JSON.stringify(n)}`); };
|
|
76
|
+
int('views', 1, 64); int('size', 16, 1024);
|
|
77
|
+
}
|
|
53
78
|
|
|
54
79
|
export class Vegetation {
|
|
55
80
|
constructor(engine, opts = {}, ctx) {
|
|
56
81
|
this.engine = engine; this.species = new Map();
|
|
82
|
+
/** this instance is over (removed or replaced, or the engine is gone): a late model or image must not write into the world any more */
|
|
83
|
+
this._gone = () => ctx.signal?.aborted || engine.disposed;
|
|
57
84
|
// where it grows: on terrain chunks when the terrain module is installed (placed in its workers), else on vegetation's own chunks over
|
|
58
85
|
// whatever provides the ground (a level, a code-built ground, flat). Both hosts keep chunks of one shape, so everything below is shared
|
|
59
86
|
if (engine.terrain && Object.keys(opts).length) throw codedError('vegetation-option', `vegetation({ ${Object.keys(opts).join(', ')} }): with terrain() installed vegetation grows on the terrain chunks, and density / view distance are terrain options (terrain({ density, viewChunks })). The vegetation() options are for ground without terrain (a level, a code-built ground)`);
|
|
@@ -74,7 +101,7 @@ export class Vegetation {
|
|
|
74
101
|
// dev asset hot swap (core/assets/assetHot.js): a species made from a swapped model is added again with the new geometry / materials. Why here and
|
|
75
102
|
// not in the generic scene walk: a species' materials are patched copies (wind, season) and its geometry may be merged from a model
|
|
76
103
|
ctx.track(engine.assets.onSwap(s => this._swapped(s)));
|
|
77
|
-
ctx.saves.
|
|
104
|
+
ctx.saves.define('vegetation', { notAtomic: 'its load redraws the instances it hides: not plain data a rollback restores by itself',
|
|
78
105
|
save: () => {
|
|
79
106
|
const removed = {};
|
|
80
107
|
for (const [ck, m] of this._removed) { for (const [id, until] of m) removed[`veg:${ck}:${id}`] = until; }
|
|
@@ -114,18 +141,22 @@ export class Vegetation {
|
|
|
114
141
|
* fade near-only species shrink out over a band [start, end] metres from the player instead of popping at the ring edge (default on for
|
|
115
142
|
* nearOnly, end = maxRing x chunk size; false = hard edge; { start, end } sets the band)
|
|
116
143
|
* lodRing switch to low-poly beyond this ring count
|
|
144
|
+
* impostor true or { views = 8, size = 128 }: beyond lodRing draw cards baked from this species' own model and materials (one draw for all far
|
|
145
|
+
* chunks, lit live through baked normals, no shadow there). Instead of lodGeometry, not with it. WebGPU only; WebGL draws the mesh
|
|
117
146
|
* castShadow / shadowRing whether to cast shadows, and within how many rings
|
|
118
147
|
* material this species' own three.js material (optional; default is engine.vegetation.material); wind, cloud shadows, season tint and the
|
|
119
148
|
* near fade are added to it (and its shadow sways) unless effects: false
|
|
120
149
|
*/
|
|
121
150
|
define(name, o) {
|
|
122
151
|
readParams(`vegetation.define('${name}')`, keysSchema(ADD_KEYS), o);
|
|
152
|
+
const grass = DEV && grassShadowHint(name, o);
|
|
153
|
+
if (grass) warnOnce(grass, 'grass-shadow\0' + name);
|
|
123
154
|
// a model name ('pine' / ['flower', color]) means what it means in content: resolved through the same vegetationModel (cache, bake, file or
|
|
124
155
|
// generator), then added as if the geometry / Object3D had been passed. Returns a Promise of the species then; start waits for it like a density image
|
|
125
156
|
if (isModelName(o.model) || isModelName(o.lodGeometry)) {
|
|
126
157
|
const p = Promise.all([isModelName(o.model) ? vegetationModel(this.engine, o.model) : { model: o.model }, isModelName(o.lodGeometry) ? vegetationModel(this.engine, o.lodGeometry) : null])
|
|
127
158
|
.then(([main, low]) => {
|
|
128
|
-
if (this.
|
|
159
|
+
if (this._gone()) return null;
|
|
129
160
|
const { model: _m, ...rest } = o;
|
|
130
161
|
return this.define(name, { ...rest, ...(main.model ? { model: main.model } : { geometry: main.geometry ?? o.geometry }), ...(low && { lodGeometry: low.model ?? low.geometry }) });
|
|
131
162
|
});
|
|
@@ -137,6 +168,9 @@ export class Vegetation {
|
|
|
137
168
|
if (o.positions != null) checkPositions(`vegetation.define('${name}')`, o.positions, o.rule);
|
|
138
169
|
const density = o.densityMap != null ? makeDensity(o.densityMap, `vegetation.define('${name}')`) : null;
|
|
139
170
|
// distance fade band of near-only species (nearFade.js), checked here so a bad band throws at define; the draw part draws it
|
|
171
|
+
// impostor and lodGeometry both say what is drawn beyond lodRing: one owner (docs/plans/2026-11-09-impostors.md)
|
|
172
|
+
if (o.impostor && o.lodGeometry) throw codedError('vegetation-option', `vegetation.define('${name}'): impostor and lodGeometry both say what is drawn beyond lodRing; keep one`);
|
|
173
|
+
if (o.impostor != null) checkImpostor(`vegetation.define('${name}')`, o.impostor);
|
|
140
174
|
if (o.fade && typeof o.fade === 'object') readParams(`vegetation.define('${name}').fade`, keysSchema(['start', 'end']), o.fade);
|
|
141
175
|
const maxRing = o.maxRing ?? (o.nearOnly ? 1 : 99);
|
|
142
176
|
const sp = {
|
|
@@ -155,8 +189,8 @@ export class Vegetation {
|
|
|
155
189
|
// a density image still loading: this species places nothing until it is in, then every chunk is placed again. The module's init waits
|
|
156
190
|
// for those added before start, so a game never opens on a bare map; one added later fills in when its image arrives
|
|
157
191
|
if (density?.pending) {
|
|
158
|
-
// the image may arrive after engine.dispose():
|
|
159
|
-
const p = density.pending.then(() => { if (!this.
|
|
192
|
+
// the image may arrive after this instance was removed (or engine.dispose()): the terrain may stay and be another instance's, so no rebuild
|
|
193
|
+
const p = density.pending.then(() => { if (!this._gone() && this.species.get(name) === sp) this.host.rebuild(); });
|
|
160
194
|
// only species added before init took _pending are awaited by init (a failure fails start); later ones nobody awaits, so report once
|
|
161
195
|
// (soft: the species just stays empty, gameplay is not frozen for a missing image)
|
|
162
196
|
if (!this._initDone) this._pending.push(p);
|
|
@@ -269,13 +303,15 @@ export class Vegetation {
|
|
|
269
303
|
*/
|
|
270
304
|
view(v) {
|
|
271
305
|
this.views.add(v);
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
306
|
+
try { // a view that throws while the existing data is replayed is not registered: _emit would keep calling it and starve the views after it
|
|
307
|
+
for (const sp of this.species.values()) v.species?.(sp);
|
|
308
|
+
for (const c of this.host.chunks.values()) {
|
|
309
|
+
if (c.state !== 'ready') continue;
|
|
310
|
+
for (const n in c.plants) v.change?.(c, n);
|
|
311
|
+
if (c.ring != null) v.ring?.(c, c.ring);
|
|
312
|
+
if (c.inView === false) v.show?.(c, false);
|
|
313
|
+
}
|
|
314
|
+
} catch (e) { this.views.delete(v); throw e; }
|
|
279
315
|
return { remove: () => { if (!this.views.delete(v)) return; for (const c of this.host.chunks.values()) if (c.state === 'ready') v.drop?.(c); } };
|
|
280
316
|
}
|
|
281
317
|
/** @internal tell every view */
|
|
@@ -319,12 +355,25 @@ export class Vegetation {
|
|
|
319
355
|
for (const d of due) this.restoreInstance(...d);
|
|
320
356
|
}
|
|
321
357
|
|
|
358
|
+
/**
|
|
359
|
+
* The plant a ray hit, read from the hit itself (no spatial guess): the same { species, cx, cz, id, position } instanceAt returns, so it goes straight to
|
|
360
|
+
* removeInstance / key; null when the hit is not a vegetation draw mesh, or is the far impostor card
|
|
361
|
+
* @param {{ object?: any, instanceId?: number }} hit a raycast hit (engine.pick)
|
|
362
|
+
* @returns {{ species: string, cx: number, cz: number, id: number, position: Vector3 } | null}
|
|
363
|
+
*/
|
|
364
|
+
plantOf(hit) {
|
|
365
|
+
const u = hit?.object?.userData, i = hit?.instanceId, id = u?.plants?.ids?.[i];
|
|
366
|
+
if (u?.species == null || id == null) return null;
|
|
367
|
+
const a = u.plants.m, CH = this.host.chunkSize;
|
|
368
|
+
return { species: u.species, cx: u.cx, cz: u.cz, id, position: new Vector3(u.cx * CH + a[i * 16 + 12], a[i * 16 + 13], u.cz * CH + a[i * 16 + 14]) };
|
|
369
|
+
}
|
|
370
|
+
|
|
322
371
|
/**
|
|
323
372
|
* Nearest instance within radius meters (default 2) of position (loaded chunks only; species restricts to one kind): { species, cx, cz, id, position } or
|
|
324
373
|
* null
|
|
325
374
|
*/
|
|
326
375
|
instanceAt(position, opts = {}) {
|
|
327
|
-
readParams('vegetation.instanceAt()',
|
|
376
|
+
readParams('vegetation.instanceAt()', AT_PARAMS, opts);
|
|
328
377
|
const [x, z] = xzOf(position), { radius = 2, species = null } = typeof opts === 'object' && opts ? opts : {};
|
|
329
378
|
const T = this.host, CH = T.chunkSize;
|
|
330
379
|
let best = null, bestD = radius * radius;
|
|
@@ -346,24 +395,37 @@ export class Vegetation {
|
|
|
346
395
|
}
|
|
347
396
|
|
|
348
397
|
/** @internal chunk plumbing (terrain chunks and ground chunks): one species' placement result r for chunk c (data; the draw parts draw it) */
|
|
349
|
-
mount(c, name, r) {
|
|
398
|
+
mount(c, name, r, held = false) {
|
|
350
399
|
const sp = this.species.get(name);
|
|
400
|
+
if (!sp) return; // a result of a species this instance does not know (a removed instance's job, or one taken back): no plants, no colliders without a draw kind
|
|
351
401
|
// densityMap thins here, before the colliders are taken, so a dropped plant blocks nothing; survivors keep their stable ids
|
|
352
|
-
if (sp
|
|
402
|
+
if (sp.density) r = thin(r, c.cx * this.host.chunkSize, c.cz * this.host.chunkSize, sp.density.at, sp.rule.salt);
|
|
353
403
|
c.plants ||= {}; c.colliders ||= {}; c.collidersAll ||= {};
|
|
354
404
|
// none left (terrain dug, densityMap thinned all): drop the record, so the draw part tears its mesh down too and collision matches what is drawn
|
|
355
405
|
if (r.n === 0) delete c.plants[name]; else c.plants[name] = r;
|
|
356
406
|
if (r.n && r.k?.length) c.collidersAll[name] = r.k; else delete c.collidersAll[name]; // original circles (before felled trees are filtered)
|
|
407
|
+
// held: the plants are drawn but their colliders wait for release() (a near-only species whose collision takes effect on a committed tick)
|
|
408
|
+
if (held) (c.held ||= {})[name] = true; else if (c.held) delete c.held[name];
|
|
357
409
|
this.applyEdits(c, name); // felled trees stay gone after reload; sets the colliders and tells the draw parts
|
|
358
410
|
}
|
|
411
|
+
/** @internal chunk plumbing: the held colliders of a species take effect */
|
|
412
|
+
release(c, name) { if (c.held?.[name]) { delete c.held[name]; this.applyEdits(c, name); } }
|
|
359
413
|
/** @internal chunk plumbing: drop a near-only species from a chunk that moved out of its ring */
|
|
360
414
|
unmount(c, name) {
|
|
361
415
|
if (!c.plants?.[name]) return;
|
|
362
|
-
delete c.plants[name]; delete c.collidersAll?.[name];
|
|
416
|
+
delete c.plants[name]; delete c.collidersAll?.[name]; if (c.held) delete c.held[name];
|
|
363
417
|
this.applyEdits(c, name);
|
|
364
418
|
}
|
|
419
|
+
/**
|
|
420
|
+
* @internal the module is removed: on terrain the chunks stay and are not ours, so take back what this instance placed on them (plants, tree
|
|
421
|
+
* colliders, treeToken so physics drops the trunks) through unmount, then let go of the terrain. The own ground chunks go with the module
|
|
422
|
+
*/
|
|
423
|
+
detach() {
|
|
424
|
+
if (this._planter) for (const c of this.host.chunks.values()) for (const n in c.plants) this.unmount(c, n);
|
|
425
|
+
this._view?.remove(); this._planter?.remove();
|
|
426
|
+
}
|
|
365
427
|
/** @internal chunk plumbing: the chunk was released */
|
|
366
|
-
drop(c) { this._emit('drop', c); c.plants = {}; c.hidden = null; }
|
|
428
|
+
drop(c) { this._emit('drop', c); c.plants = {}; c.hidden = null; c.held = null; }
|
|
367
429
|
/** @internal chunk plumbing: the chunk's ring changed; the draw parts pick draw distance, low-poly swap and shadows from it */
|
|
368
430
|
ring(c, ring) { c.ring = ring; this._emit('ring', c, ring); }
|
|
369
431
|
|
|
@@ -373,7 +435,7 @@ export class Vegetation {
|
|
|
373
435
|
if (r) for (const id of this._removed.get(`${name}:${c.cx},${c.cz}`)?.keys() ?? []) { const s = slotOf(r, id); if (s !== undefined) hid.add(s); }
|
|
374
436
|
(c.hidden ||= {})[name] = hid.size ? hid : null;
|
|
375
437
|
// collision circles map one-to-one to instances (instance i = group i of [x, z, r]); drop the hidden ones
|
|
376
|
-
const all = r ? c.collidersAll?.[name] : null, before = c.colliders[name];
|
|
438
|
+
const all = r && !c.held?.[name] ? c.collidersAll?.[name] : null, before = c.colliders[name];
|
|
377
439
|
if (!all) delete c.colliders[name];
|
|
378
440
|
else if (!hid.size) c.colliders[name] = all;
|
|
379
441
|
else {
|
|
@@ -40,14 +40,8 @@ function roll(id, salt) {
|
|
|
40
40
|
return (h >>> 0) / 4294967296;
|
|
41
41
|
}
|
|
42
42
|
|
|
43
|
-
/** Placement result r
|
|
44
|
-
export function
|
|
45
|
-
if (!r.n) return r;
|
|
46
|
-
const keep = [];
|
|
47
|
-
for (let i = 0; i < r.n; i++) {
|
|
48
|
-
const d = at(ox + r.m[i * 16 + 12], oz + r.m[i * 16 + 14]);
|
|
49
|
-
if (d > 0 && roll(r.ids[i], salt) < d) keep.push(i);
|
|
50
|
-
}
|
|
43
|
+
/** Placement result r with only the instances at the indices `keep` (same shape as r; r itself when all stay) */
|
|
44
|
+
export function select(r, keep) {
|
|
51
45
|
if (keep.length === r.n) return r;
|
|
52
46
|
const n = keep.length, m = new Float32Array(n * 16), c = new Float32Array(n * 3), ids = new Uint32Array(n), hasK = r.k && r.k.length;
|
|
53
47
|
const k = new Float32Array(hasK ? n * 3 : 0);
|
|
@@ -57,3 +51,14 @@ export function thin(r, ox, oz, at, salt) {
|
|
|
57
51
|
});
|
|
58
52
|
return { ...r, m, c, k, ids, n };
|
|
59
53
|
}
|
|
54
|
+
|
|
55
|
+
/** Placement result r of chunk origin (ox, oz) with only the instances whose roll is under the density at their spot (same shape as r) */
|
|
56
|
+
export function thin(r, ox, oz, at, salt) {
|
|
57
|
+
if (!r.n) return r;
|
|
58
|
+
const keep = [];
|
|
59
|
+
for (let i = 0; i < r.n; i++) {
|
|
60
|
+
const d = at(ox + r.m[i * 16 + 12], oz + r.m[i * 16 + 14]);
|
|
61
|
+
if (d > 0 && roll(r.ids[i], salt) < d) keep.push(i);
|
|
62
|
+
}
|
|
63
|
+
return select(r, keep);
|
|
64
|
+
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// Vegetation drawing: draws what the vegetation data part placed. One InstancedMesh per species per chunk from the chunk's placement records
|
|
2
2
|
// (c.plants[name]: m matrices, c colors, ids, n), the species' geometry / low-poly geometry / material (wind sway, season tint, near fade
|
|
3
|
-
// patched in), ring LOD (draw distance, low-poly swap, shadow distance) and frustum visibility
|
|
3
|
+
// patched in), ring LOD (draw distance, low-poly swap, shadow distance) and frustum visibility (per mesh and per camera, by three: cullSphere). No show() hook: hiding
|
|
4
|
+
// a chunk's group off the main view also took its shadows out of every shadow pass (three skips invisible parents). Installed by vegetation() as its own module
|
|
4
5
|
// 'vegetationDraw' holding the slot 'vegetation-draw'. Its picture entries are reached through engine.vegetation: material, patches, sway(), color().
|
|
5
6
|
//
|
|
6
7
|
// Why a separate module: collision, paths, felling and instanceAt read only the data part, so a game can swap the whole plant picture
|
|
@@ -8,15 +9,16 @@
|
|
|
8
9
|
// install(e, ctx) { ctx.track(e.vegetation.view({ species(sp) {...}, change(c, name) {...c.plants[name]...}, ring(c, ring) {...}, show(c, v) {...}, drop(c) {...} })); }
|
|
9
10
|
// This file never changes placement data; it only reads it.
|
|
10
11
|
import { engineOwned } from '../../core/scene/things.js';
|
|
11
|
-
import {
|
|
12
|
+
import { drawOnly } from '../../core/scene/drawOnly.js';
|
|
13
|
+
import { needMaterial, oneForm, warnOnce } from '../../core/base/validate.js';
|
|
12
14
|
import * as THREE from 'three';
|
|
13
15
|
import { fromModel } from './modelGeometry.js';
|
|
14
16
|
import { applyEffects, windCustom } from '../../render/materials.js';
|
|
15
17
|
import { neutralMaterial } from '../../render/neutral.js';
|
|
16
|
-
import { patchMaterial, unpatchMaterial } from '../../render/patches.js';
|
|
18
|
+
import { patchMaterial, unpatchMaterial, cloneMaterial } from '../../render/patches.js';
|
|
17
19
|
import { EFFECTS, hashText } from '../../render/effects.js';
|
|
18
20
|
import { codedError } from '../../core/base/errorHints.js';
|
|
19
|
-
import { isWebGPU } from '../../render/backend.js';
|
|
21
|
+
import { isWebGPU, webgpuPart, onRendererSwap } from '../../render/backend.js';
|
|
20
22
|
import { nearFadePatch } from './nearFade.js';
|
|
21
23
|
import { scatterAttempts } from '../../core/stream/scatter.js';
|
|
22
24
|
|
|
@@ -24,6 +26,14 @@ const COLOR = 'vegetationColor'; // the patch name of vegetation.color() on ev
|
|
|
24
26
|
// The wind patch in engine.vegetation.patches has one amplitude: a shared material cannot carry each species' own (those are define()'s wind option)
|
|
25
27
|
const SHARED_SWAY = 0.05;
|
|
26
28
|
const code = v => (typeof v === 'string' ? { glsl: v } : v);
|
|
29
|
+
// what applyEffects adds to a species' material (render/effects.js names, the near fade, vegetation.color()): taken off the impostor's bake copy
|
|
30
|
+
const FX_NAMES = ['wind', 'clouds', 'season', 'world', 'detail'];
|
|
31
|
+
/** A copy of a game material without the engine's effect patches (its own patches stay) @param {any} m @param {any[]} own this species' own patches */
|
|
32
|
+
function unpatched(m, own) {
|
|
33
|
+
const c = cloneMaterial(m);
|
|
34
|
+
for (const n of [...FX_NAMES, ...own.map(p => p.name)]) unpatchMaterial(c, n);
|
|
35
|
+
return c;
|
|
36
|
+
}
|
|
27
37
|
|
|
28
38
|
/**
|
|
29
39
|
* How many instances of a placement to draw at a density. A plant with a collider is placed in full at every quality, so collision and felled ids stay the same world, and low
|
|
@@ -39,6 +49,23 @@ export function drawnPlants(rule, r, density) {
|
|
|
39
49
|
return n;
|
|
40
50
|
}
|
|
41
51
|
|
|
52
|
+
/**
|
|
53
|
+
* The culling sphere of one chunk's plants of one species, so three culls the mesh per camera: the main view skips the chunks it does not see, and
|
|
54
|
+
* each shadow camera (every cascade) draws only the chunks inside its own box. With frustumCulled off every cascade drew every casting chunk and the
|
|
55
|
+
* nearest ring drew behind the camera too: the draw count of a grassy scene, for nothing on screen. Grown by twice the largest plant: the built-in
|
|
56
|
+
* sway moves a vertex by its height x amplitude x wind, within the plant's own height while amplitude x wind stays under 1; the low-poly geometry
|
|
57
|
+
* counts too, as _level swaps it in without a recompute.
|
|
58
|
+
* shortcut: a game's own sway() moving plants farther than their height could clip them at the screen edge; then grow the margin from the sway.
|
|
59
|
+
*/
|
|
60
|
+
function cullSphere(im, k) {
|
|
61
|
+
im.boundingSphere = null; im.computeBoundingSphere(); // three: each instance matrix x the geometry's sphere, over im.count
|
|
62
|
+
const a = im.instanceMatrix.array;
|
|
63
|
+
let s2 = 0;
|
|
64
|
+
for (let o = 0; o < im.count * 16; o += 16) s2 = Math.max(s2, a[o] ** 2 + a[o + 1] ** 2 + a[o + 2] ** 2, a[o + 4] ** 2 + a[o + 5] ** 2 + a[o + 6] ** 2, a[o + 8] ** 2 + a[o + 9] ** 2 + a[o + 10] ** 2);
|
|
65
|
+
const radius = g => { if (!g) return 0; if (!g.boundingSphere) g.computeBoundingSphere(); return g.boundingSphere.radius + g.boundingSphere.center.length(); };
|
|
66
|
+
im.boundingSphere.radius += 2 * Math.sqrt(s2) * Math.max(radius(k.geometry), radius(k.lodGeometry));
|
|
67
|
+
}
|
|
68
|
+
|
|
42
69
|
export class VegetationDraw {
|
|
43
70
|
/** @param {any} e @param {any} v the vegetation data part (engine.vegetation) */
|
|
44
71
|
constructor(e, v) {
|
|
@@ -53,6 +80,12 @@ export class VegetationDraw {
|
|
|
53
80
|
/** @internal chunk record -> { group, ims: { name: InstancedMesh } } */ this.meshes = new Map();
|
|
54
81
|
this._refreshPatches();
|
|
55
82
|
this._view = v.view(this);
|
|
83
|
+
/** @internal */ this._swap = onRendererSwap(e, () => {
|
|
84
|
+
if (isWebGPU(e.renderer)) return;
|
|
85
|
+
let any = false;
|
|
86
|
+
for (const [n, k] of this.kinds) if (k.impostor) { this._dropCards(k); k.impostor = null; this._noCards(n); any = true; }
|
|
87
|
+
if (any) for (const c of this.meshes.keys()) if (c.ring != null) this.ring(c, c.ring);
|
|
88
|
+
});
|
|
56
89
|
}
|
|
57
90
|
|
|
58
91
|
/** @internal engine.vegetation.material: every species with no material or model of its own draws it, as given; null gives the neutral default back */
|
|
@@ -64,7 +97,11 @@ export class VegetationDraw {
|
|
|
64
97
|
const old = this.kinds.get(sp.name);
|
|
65
98
|
if (old?.shared) this.species(sp);
|
|
66
99
|
}
|
|
67
|
-
for (const rec of this.meshes
|
|
100
|
+
for (const [c, rec] of this.meshes) for (const n in rec.ims) {
|
|
101
|
+
const k = this.kinds.get(n), im = rec.ims[n]; if (!k) continue;
|
|
102
|
+
im.userData.base = im.material = k.material;
|
|
103
|
+
if (c.ring != null) this._level(im, this.v.get(n), k, c.ring);
|
|
104
|
+
}
|
|
68
105
|
}
|
|
69
106
|
|
|
70
107
|
/** @internal engine.vegetation.sway(): the new shape reaches the engine's own species materials; a shared material of the game is the game's to re-patch */
|
|
@@ -102,8 +139,8 @@ export class VegetationDraw {
|
|
|
102
139
|
_eachOwn(fn) {
|
|
103
140
|
for (const sp of this.v.list()) {
|
|
104
141
|
const k = this.kinds.get(sp.name);
|
|
105
|
-
if (!k || sp.source.effects === false
|
|
106
|
-
for (const m of [k.material].flat()) fn(m, sp);
|
|
142
|
+
if (!k || sp.source.effects === false) continue;
|
|
143
|
+
for (const m of [k.material === this._game ? [] : k.material, k.lodMaterial ?? []].flat()) fn(m, sp); // a low-poly model's materials are the engine's even under the game's shared one
|
|
107
144
|
}
|
|
108
145
|
}
|
|
109
146
|
|
|
@@ -125,12 +162,91 @@ export class VegetationDraw {
|
|
|
125
162
|
let lod = lodMdl ? lodMdl.geometry : o.lodGeometry || null;
|
|
126
163
|
if (mdl && lod && !lod.groups.length) { lod = lod.clone(); lod.addGroup(0, Infinity, 0); } // a material array draws nothing without groups
|
|
127
164
|
const shared = !mdl && !o.material, game = shared ? this._game : null;
|
|
165
|
+
// the impostor bakes the game's material as given: copy it before fx patches it in place (wind, clouds, season baked in, season then twice)
|
|
166
|
+
const bakeOwn = o.impostor && !mdl && o.material ? unpatched(o.material, own) : null;
|
|
128
167
|
const material = game ?? (mdl ? mdl.materials.map(fx) : fx(o.material ?? this._neutral(o)));
|
|
168
|
+
// a low-poly model keeps its own parts and materials (its groups index its own list, so the part order of the two models need not match), whatever the main one is made of
|
|
169
|
+
const lodMaterial = lodMdl ? lodMdl.materials.map(fx) : null;
|
|
129
170
|
// what was built here and is ours to free (the game's geometry and materials stay the game's); a mesh still drawing the old ones uploads them again
|
|
130
|
-
const made = [...(lodMdl?.materials ?? []), ...(lod && lod !== o.lodGeometry ? [lod] : []), ...(mdl ? [mdl.geometry, ...material] : shared && !game ? [material] : [])];
|
|
171
|
+
const made = [...new Set([...(lodMdl?.materials ?? []), ...(lodMaterial ?? []), ...(lod && lod !== o.lodGeometry ? [lod] : []), ...(mdl ? [mdl.geometry, ...material] : shared && !game ? [material] : [])])];
|
|
172
|
+
// fade: the game's shared material has none, but a low-poly model of the species has its own
|
|
131
173
|
const old = this.kinds.get(sp.name);
|
|
132
|
-
this.kinds.set(sp.name, { geometry: mdl ? mdl.geometry : o.geometry, lodGeometry: lod, fadeUniforms: game ? null : nf?.uniforms ?? null, shared, material, made
|
|
174
|
+
this.kinds.set(sp.name, { geometry: mdl ? mdl.geometry : o.geometry, lodGeometry: lod, lodMaterial, fadeUniforms: game && !lodMaterial ? null : nf?.uniforms ?? null, shared, material, made,
|
|
175
|
+
impostor: this._impostor(sp, mdl, game, bakeOwn) });
|
|
133
176
|
for (const d of old?.made ?? []) d.dispose();
|
|
177
|
+
this._dropCards(old);
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* Far cards of an impostor species (render/impostor.tsl.js): what to bake from and the one card mesh for all its far chunks, built in updateCards().
|
|
181
|
+
* The bake reads materials without the engine's patches, so wind, cloud shadow and season are not baked in (the card adds the season live):
|
|
182
|
+
* a model's own materials (fromModel patched copies of them), an unpatched copy of a species' own material, the game's shared one as drawn
|
|
183
|
+
*/
|
|
184
|
+
_impostor(sp, mdl, game, bakeOwn) {
|
|
185
|
+
const o = sp.source;
|
|
186
|
+
if (!o.impostor) return null;
|
|
187
|
+
if (!isWebGPU(this.engine.renderer)) { bakeOwn?.dispose(); this._noCards(sp.name); return null; }
|
|
188
|
+
const own = [];
|
|
189
|
+
o.model?.traverse?.(n => { if (n.isMesh) own.push(n.material); }); // fromModel's order: one group per mesh
|
|
190
|
+
const neutral = !mdl && !o.material && !game ? this._neutral(o) : null;
|
|
191
|
+
return { opts: o.impostor === true ? {} : o.impostor, src: { geometry: mdl ? mdl.geometry : o.geometry, material: mdl ? own : (bakeOwn ?? game ?? neutral), season: o.effects !== false && !game },
|
|
192
|
+
bake: null, mesh: null, dirty: true, neutral, bakeOwn };
|
|
193
|
+
}
|
|
194
|
+
_noCards(name) {
|
|
195
|
+
warnOnce(`vegetation.define('${name}'): impostor cards need the WebGPU renderer (WebGPURenderer); on WebGLRenderer this species draws its full mesh beyond lodRing too`, 'impostor-webgl\0' + name);
|
|
196
|
+
}
|
|
197
|
+
/** Free a species' far cards (redefined or disposed) */
|
|
198
|
+
_dropCards(k) {
|
|
199
|
+
const I = k?.impostor; if (!I) return;
|
|
200
|
+
if (I.mesh) { I.mesh.removeFromParent(); I.mesh.geometry.dispose(); I.mesh.material.dispose(); }
|
|
201
|
+
I.bake?.dispose(); I.neutral?.dispose(); I.bakeOwn?.dispose();
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* @internal module frame hook: rebuild the far cards of each impostor species whose chunks changed since the last frame. One mesh per species for every
|
|
205
|
+
* chunk beyond lodRing (that is the draw saved). Reads the chunk meshes' instance arrays, so felled plants (zero scale) and thinned counts carry over
|
|
206
|
+
*/
|
|
207
|
+
updateCards() {
|
|
208
|
+
for (const [name, k] of this.kinds) {
|
|
209
|
+
const I = k.impostor, sp = this.v.get(name);
|
|
210
|
+
if (!I?.dirty || !sp) continue;
|
|
211
|
+
I.dirty = false;
|
|
212
|
+
const far = [];
|
|
213
|
+
let n = 0;
|
|
214
|
+
for (const [c, rec] of this.meshes) { const im = rec.ims[name]; if (im && c.ring > sp.lodRing && c.ring <= sp.maxRing && im.count) { far.push([c, im]); n += im.count; } }
|
|
215
|
+
if (!n && !I.mesh) continue;
|
|
216
|
+
const part = webgpuPart('impostor', `vegetation '${name}' impostor`);
|
|
217
|
+
I.bake ??= part.bake(this.engine.renderer, I.src, I.opts);
|
|
218
|
+
if (!I.mesh || I.mesh.geometry.userData.capacity < n) this._cardMesh(I, part, Math.max(64, 2 ** Math.ceil(Math.log2(n || 1))), sp);
|
|
219
|
+
const g = I.mesh.geometry, C = g.attributes.aCenter.array, S = g.attributes.aShape.array, T = g.attributes.aTint.array, CH = this.v.host.chunkSize;
|
|
220
|
+
let j = 0;
|
|
221
|
+
for (const [c, im] of far) {
|
|
222
|
+
const a = im.instanceMatrix.array, col = im.instanceColor?.array;
|
|
223
|
+
for (let i = 0; i < im.count; i++, j++) {
|
|
224
|
+
const o = i * 16;
|
|
225
|
+
// yaw-and-scale matrices (placement turns plants about Y and stretches them up): yaw from column 2, across scale from column 0, up from column 1
|
|
226
|
+
C[j * 3] = c.cx * CH + a[o + 12]; C[j * 3 + 1] = a[o + 13]; C[j * 3 + 2] = c.cz * CH + a[o + 14];
|
|
227
|
+
S[j * 3] = Math.atan2(a[o + 8], a[o + 10]); S[j * 3 + 1] = Math.hypot(a[o], a[o + 2]); S[j * 3 + 2] = Math.hypot(a[o + 4], a[o + 5], a[o + 6]);
|
|
228
|
+
if (col) { T[j * 3] = col[i * 3]; T[j * 3 + 1] = col[i * 3 + 1]; T[j * 3 + 2] = col[i * 3 + 2]; } else T.fill(1, j * 3, j * 3 + 3);
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
g.instanceCount = n;
|
|
232
|
+
for (const at of [g.attributes.aCenter, g.attributes.aShape, g.attributes.aTint]) at.needsUpdate = true;
|
|
233
|
+
I.mesh.visible = n > 0;
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
_cardMesh(I, part, capacity, sp) {
|
|
237
|
+
const old = I.mesh, q = new THREE.PlaneGeometry(1, 1).translate(0, 0.5, 0), g = new THREE.InstancedBufferGeometry();
|
|
238
|
+
g.index = q.index; for (const a of ['position', 'normal', 'uv']) g.setAttribute(a, q.attributes[a]);
|
|
239
|
+
for (const a of ['aCenter', 'aShape', 'aTint']) g.setAttribute(a, new THREE.InstancedBufferAttribute(new Float32Array(capacity * 3), 3).setUsage(THREE.DynamicDrawUsage));
|
|
240
|
+
g.userData.capacity = capacity;
|
|
241
|
+
const m = new THREE.Mesh(g, old?.material ?? part.cardMaterial(I.src, I.bake));
|
|
242
|
+
// cards span every far chunk, so no per-chunk culling (two triangles a plant); no shadow (a flat card's shadow would turn with the camera)
|
|
243
|
+
m.frustumCulled = false; m.castShadow = false; m.receiveShadow = sp.receiveShadow; m.matrixAutoUpdate = false;
|
|
244
|
+
m.userData.budgetTag = 'vegetation';
|
|
245
|
+
// one 1 m quad at the origin outside the shader (positionNode places every card): a scene copy such as the path tracer leaves it out and says so
|
|
246
|
+
drawOnly('far plants drawn as impostor cards (left out: they are placed in the shader, so the traced photo has no far plants)', m);
|
|
247
|
+
if (old) { old.removeFromParent(); old.geometry.dispose(); }
|
|
248
|
+
this.engine.scene.add(engineOwned('vegetation', m));
|
|
249
|
+
I.mesh = m;
|
|
134
250
|
}
|
|
135
251
|
_neutral(o) {
|
|
136
252
|
const m = neutralMaterial('vegetation', { vertexColors: true, side: o.doubleSided ? THREE.DoubleSide : THREE.FrontSide });
|
|
@@ -141,43 +257,46 @@ export class VegetationDraw {
|
|
|
141
257
|
/** @internal view hook: c.plants[name] was placed, replaced, thinned or dropped, or which of its instances are felled changed */
|
|
142
258
|
change(c, name) {
|
|
143
259
|
const r = c.plants?.[name], rec = this.meshes.get(c), old = rec?.ims[name];
|
|
260
|
+
const I = this.kinds.get(name)?.impostor;
|
|
261
|
+
if (I) I.dirty = true; // placed, felled or gone: the far cards copy it next frame
|
|
144
262
|
if (!r) { if (old) { rec.group.remove(old); old.dispose(); delete rec.ims[name]; } return; }
|
|
145
263
|
const k = this.kinds.get(name), sp = this.v.get(name);
|
|
146
264
|
if (!k || !sp) return;
|
|
265
|
+
const t0 = performance.now(); // measure: the 'build' stage of engine.budget.cost (mesh, matrices, culling sphere)
|
|
147
266
|
let im = old;
|
|
148
|
-
if (!old || old.userData.plants !== r || old.
|
|
149
|
-
const t0 = performance.now(); // measure: the 'build' stage of engine.budget.cost
|
|
267
|
+
if (!old || old.userData.plants !== r || old.userData.base !== k.material) { // new placement (or species defined again): a new mesh
|
|
150
268
|
im = new THREE.InstancedMesh(k.geometry, k.material, r.n);
|
|
151
269
|
im.instanceColor = new THREE.InstancedBufferAttribute(r.c, 3);
|
|
152
|
-
im.
|
|
270
|
+
im.matrixAutoUpdate = false; // frustum culled by three against every camera: cullSphere() below
|
|
153
271
|
im.receiveShadow = sp.receiveShadow;
|
|
154
|
-
im.userData.plants = r; im.userData.budgetTag = 'vegetation';
|
|
272
|
+
im.userData.plants = r; im.userData.species = name; im.userData.cx = c.cx; im.userData.cz = c.cz; im.userData.base = k.material; im.userData.budgetTag = 'vegetation'; // cx, cz: plantOf reads them
|
|
155
273
|
const R = rec ?? this._chunk(c);
|
|
156
274
|
if (old) { R.group.remove(old); old.dispose(); }
|
|
157
275
|
R.group.add(im); im.updateMatrixWorld(true);
|
|
158
276
|
R.ims[name] = im;
|
|
159
|
-
this.engine.budget.cost.end('build', t0);
|
|
160
277
|
}
|
|
161
|
-
// felled instances draw
|
|
278
|
+
// felled instances draw at zero scale where they stood (count unchanged, so the other instances keep their slots). Translation and w = 1 stay:
|
|
279
|
+
// an all-zero matrix made three's bounding sphere NaN, and every ray and frustum test then missed the whole chunk
|
|
162
280
|
const a = im.instanceMatrix.array, hid = c.hidden?.[name];
|
|
163
281
|
a.set(r.m);
|
|
164
|
-
if (hid) for (const i of hid) if (i < r.n) a.fill(0, i * 16, i * 16 +
|
|
282
|
+
if (hid) for (const i of hid) if (i < r.n) a.fill(0, i * 16, i * 16 + 12);
|
|
165
283
|
im.instanceMatrix.needsUpdate = true;
|
|
166
284
|
im.count = drawnPlants(sp.rule, r, this.v.host.density);
|
|
285
|
+
cullSphere(im, k);
|
|
286
|
+
this.engine.budget.cost.end('build', t0);
|
|
167
287
|
if (c.ring != null) this._level(im, sp, k, c.ring);
|
|
168
288
|
}
|
|
169
289
|
|
|
170
290
|
/** @internal view hook: the chunk's ring changed (or shadows were switched): draw distance, low-poly swap and shadows of every species there */
|
|
171
291
|
ring(c, ring) {
|
|
172
292
|
const rec = this.meshes.get(c); if (!rec) return;
|
|
293
|
+
this._cardsDirty(rec);
|
|
173
294
|
for (const n in rec.ims) { const sp = this.v.get(n), k = this.kinds.get(n); if (sp && k) this._level(rec.ims[n], sp, k, ring); }
|
|
174
295
|
}
|
|
175
|
-
/** @internal view hook: in view or not (ring 1 is always in view, farther chunks by the camera frustum) */
|
|
176
|
-
show(c, visible) { const rec = this.meshes.get(c); if (rec) rec.group.visible = visible; }
|
|
177
296
|
/** @internal view hook: the chunk was released */
|
|
178
297
|
drop(c) {
|
|
179
298
|
const rec = this.meshes.get(c); if (!rec) return;
|
|
180
|
-
this.meshes.delete(c);
|
|
299
|
+
this.meshes.delete(c); this._cardsDirty(rec);
|
|
181
300
|
for (const n in rec.ims) rec.ims[n].dispose();
|
|
182
301
|
this.engine.scene.remove(rec.group);
|
|
183
302
|
}
|
|
@@ -188,16 +307,20 @@ export class VegetationDraw {
|
|
|
188
307
|
for (const k of this.kinds.values()) k.fadeUniforms?.uNearFadeCenter.value.copy(f);
|
|
189
308
|
}
|
|
190
309
|
|
|
310
|
+
_cardsDirty(rec) { for (const n in rec.ims) { const I = this.kinds.get(n)?.impostor; if (I) I.dirty = true; } }
|
|
311
|
+
|
|
191
312
|
_level(im, sp, k, ring) {
|
|
192
|
-
|
|
193
|
-
im.
|
|
313
|
+
// an impostor species beyond lodRing is drawn by its far cards (updateCards), so its chunk mesh hides there, shadow included
|
|
314
|
+
im.visible = ring <= sp.maxRing && !(k.impostor && ring > sp.lodRing);
|
|
315
|
+
const low = k.lodGeometry && ring > sp.lodRing;
|
|
316
|
+
im.geometry = low ? k.lodGeometry : k.geometry;
|
|
317
|
+
im.material = low && k.lodMaterial ? k.lodMaterial : k.material;
|
|
194
318
|
im.castShadow = !!this.engine.renderer?.shadowMap?.enabled && sp.castShadow && ring <= sp.shadowRing;
|
|
195
319
|
}
|
|
196
320
|
_chunk(c) {
|
|
197
321
|
const CH = this.v.host.chunkSize, g = new THREE.Group();
|
|
198
322
|
g.userData.budgetTag = 'vegetation';
|
|
199
323
|
g.position.set(c.cx * CH, 0, c.cz * CH); g.matrixAutoUpdate = false; g.updateMatrix();
|
|
200
|
-
g.visible = c.inView !== false;
|
|
201
324
|
this.engine.scene.add(engineOwned('vegetation', g)); g.updateMatrixWorld(true);
|
|
202
325
|
const rec = { group: g, ims: {} };
|
|
203
326
|
this.meshes.set(c, rec);
|
|
@@ -205,8 +328,8 @@ export class VegetationDraw {
|
|
|
205
328
|
}
|
|
206
329
|
|
|
207
330
|
dispose() {
|
|
208
|
-
this._view.remove();
|
|
209
|
-
for (const k of this.kinds.values()) for (const d of k.made) d.dispose();
|
|
331
|
+
this._view.remove(); this._swap.remove();
|
|
332
|
+
for (const k of this.kinds.values()) { for (const d of k.made) d.dispose(); this._dropCards(k); }
|
|
210
333
|
this.kinds.clear(); this._base.dispose();
|
|
211
334
|
}
|
|
212
335
|
}
|
|
@@ -11,6 +11,7 @@ import { follows } from '../../core/base/follows.js';
|
|
|
11
11
|
import * as THREE from 'three';
|
|
12
12
|
import { makePlacer, makeNoise } from '../../core/stream/scatter.js';
|
|
13
13
|
import { ChunkStream, bookCollision, collidersNear, ringsReady } from '../../core/stream/chunkStream.js';
|
|
14
|
+
import { select } from './densityMap.js';
|
|
14
15
|
|
|
15
16
|
export const GROUND_DEFAULTS = { chunkSize: 32, viewChunks: 3, density: 1, seed: 1 }; // shown by engine.catalog too
|
|
16
17
|
|
|
@@ -67,15 +68,29 @@ export class GroundChunks {
|
|
|
67
68
|
for (const c of this.chunks.values()) if (c.state === 'ready') for (const sp of this.veg.list()) if (!sp.nearOnly || c.plants[sp.name]) this._grow(c, sp);
|
|
68
69
|
}
|
|
69
70
|
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
71
|
+
// the rectangle plants may grow in, or null (unbounded). No area given: a level that provides the ground bounds it (its walkable meshes), so plants
|
|
72
|
+
// never grow past the model's edge onto the flat fallback ground around it; with no level (setGround / flat default) it is unbounded
|
|
73
|
+
_rect() {
|
|
73
74
|
const b = this.area ? null : this.engine.level?.heightfield?.bounds;
|
|
74
|
-
|
|
75
|
+
return this.area ?? (b && !b.isEmpty() ? { min: [b.min.x, b.min.z], max: [b.max.x, b.max.z] } : null);
|
|
76
|
+
}
|
|
77
|
+
_inArea(cx, cz) {
|
|
78
|
+
const a = this._rect();
|
|
75
79
|
if (!a) return true;
|
|
76
80
|
const CH = this.chunkSize;
|
|
77
81
|
return (cx + 1) * CH > a.min[0] && cx * CH < a.max[0] && (cz + 1) * CH > a.min[1] && cz * CH < a.max[1];
|
|
78
82
|
}
|
|
83
|
+
// a chunk overlapping the area still holds spots outside it: each plant (and its collider, same index) is tested by its own position
|
|
84
|
+
_clip(c, r) {
|
|
85
|
+
const a = this._rect();
|
|
86
|
+
if (!a || !r.n) return r;
|
|
87
|
+
const CH = this.chunkSize, ox = c.cx * CH, oz = c.cz * CH, keep = [];
|
|
88
|
+
for (let i = 0; i < r.n; i++) {
|
|
89
|
+
const x = ox + r.m[i * 16 + 12], z = oz + r.m[i * 16 + 14];
|
|
90
|
+
if (x >= a.min[0] && x < a.max[0] && z >= a.min[1] && z < a.max[1]) keep.push(i);
|
|
91
|
+
}
|
|
92
|
+
return select(r, keep);
|
|
93
|
+
}
|
|
79
94
|
_ring(c) { return this._stream.ring(c); }
|
|
80
95
|
|
|
81
96
|
/** @internal module frame hook: follow the ground, queue / release chunks around the sources, build within budget, LOD and culling */
|
|
@@ -122,7 +137,7 @@ export class GroundChunks {
|
|
|
122
137
|
c.sphere.radius = Math.hypot(CH / 2, CH / 2, (c.hi - c.lo) / 2 + 8);
|
|
123
138
|
}
|
|
124
139
|
_grow(c, sp) {
|
|
125
|
-
const r = this._place(c.cx, c.cz, sp.rule, this.density);
|
|
140
|
+
const r = this._clip(c, this._place(c.cx, c.cz, sp.rule, this.density));
|
|
126
141
|
for (let i = 0; i < r.n; i++) { const y = r.m[i * 16 + 13]; if (y < c.lo) c.lo = y; if (y > c.hi) c.hi = y; }
|
|
127
142
|
this.veg.mount(c, sp.name, r);
|
|
128
143
|
}
|
|
@@ -68,18 +68,18 @@ export function vegetation(opts = {}) {
|
|
|
68
68
|
async init(e) {
|
|
69
69
|
if (own && e.terrain) throw codedError('module-requires', 'vegetation() was installed before terrain(): put terrain() first, vegetation then grows on its chunks');
|
|
70
70
|
// over a level or a code-built ground these chunks are the only ones: their rows are this module's to offer (on terrain, the terrain's)
|
|
71
|
-
if (own) e.settings?.define('viewChunks', own.viewChunks, n => { if (own.viewChunks !== n) own.viewChunks = n; }).define('density', own.density, n => { if (own.density !== n) own.density = n; });
|
|
71
|
+
if (own) e.settings?.define('viewChunks', own.viewChunks, { menu: false, apply: n => { if (own.viewChunks !== n) own.viewChunks = n; } }).define('density', own.density, { menu: false, apply: n => { if (own.density !== n) own.density = n; } }); // the graphics tab draws them
|
|
72
72
|
await v.whenLoaded(); // densityMap.url images of species added before start
|
|
73
73
|
},
|
|
74
74
|
frame(dt, e) { own?.update(e.stream.sources(), e.camera); },
|
|
75
75
|
fixed(dt) { v.tick(dt); }, skip(dt, e, done) { if (done) v.tick(1); },
|
|
76
76
|
describe(e, ctx) { if (own) ctx.out.perf.vegetation = { loaded: own.stats.loaded, visible: own.stats.visible, queued: own.stats.queued }; },
|
|
77
|
-
dispose(e) { own?.dispose(); v?.
|
|
77
|
+
dispose(e) { own?.dispose(); v?.detach(); } };
|
|
78
78
|
const lookModule = {
|
|
79
79
|
// the same vegetation({...}) call (its options are the data part's; the draw part reads the species' define() options)
|
|
80
80
|
name: 'vegetationDraw', skipKind: 'none', type: 'picture', label: 'Vegetation drawing', params: VEG_PARAMS, options: opts, requires: ['vegetation'], provides: ['vegetation-draw'], stage: 'effects',
|
|
81
81
|
install(e) { e.i18n.add({ 'zh-CN': { 'module.vegetationDraw': '植被外观' }, en: { 'module.vegetationDraw': 'vegetation drawing' } }); drawPart = new VegetationDraw(e, v); return drawPart; },
|
|
82
|
-
frame() { drawPart.updateFade(); },
|
|
82
|
+
frame() { drawPart.updateFade(); drawPart.updateCards(); },
|
|
83
83
|
describe() { return { chunks: drawPart?.meshes.size ?? 0 }; },
|
|
84
84
|
dispose() { drawPart?.dispose(); drawPart = null; },
|
|
85
85
|
};
|