roamwright 0.4.0 → 0.20.1
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/CONTRIBUTING.md +3 -1
- package/README.md +11 -34
- package/geometry/bedding.js +141 -0
- package/geometry/builder-cells.js +42 -0
- package/geometry/builder-frame.js +47 -0
- package/geometry/builder.js +189 -177
- package/geometry/cell-mask.js +25 -0
- package/geometry/creased-sheet.js +34 -34
- package/geometry/ear.js +36 -36
- package/geometry/erosion.js +65 -42
- package/geometry/face-grid.js +65 -65
- package/geometry/foliage.js +10 -10
- package/geometry/hair-gathers.js +41 -41
- package/geometry/hair-locks.js +41 -41
- package/geometry/hair-patch.js +18 -18
- package/geometry/hair-shell.js +31 -31
- package/geometry/head-profile.js +15 -15
- package/geometry/head-shape.js +77 -77
- package/geometry/heightfield.js +27 -18
- package/geometry/index-parts.js +2 -2
- package/geometry/instance-visibility.js +12 -12
- package/geometry/instances.js +15 -15
- package/geometry/outline-grid.js +7 -7
- package/geometry/part-ranges.js +3 -3
- package/geometry/path-field.js +63 -33
- package/geometry/placement.js +52 -52
- package/geometry/point-buckets.js +50 -0
- package/geometry/primitives.js +63 -47
- package/geometry/sagging-tube.js +27 -27
- package/geometry/sampled-surface.js +109 -77
- package/geometry/scatter-grid.js +46 -6
- package/geometry/sculpt.js +93 -93
- package/geometry/shore-grid.js +77 -34
- package/geometry/strata-field.js +92 -92
- package/geometry/strata-tiles.js +91 -91
- package/geometry/stream.js +70 -48
- package/geometry/terrain-chunks.js +87 -82
- package/geometry/terrain-extension.js +6 -6
- package/index.js +5 -0
- package/math/cell-edge.js +16 -16
- package/math/cell-key.js +6 -0
- package/math/circle-clearances.js +19 -0
- package/math/cloth-textures.js +6 -6
- package/math/cloud-textures.js +20 -20
- package/math/color.js +14 -14
- package/math/curve.js +22 -22
- package/math/mountain-ranges.js +216 -165
- package/math/noise.js +101 -49
- package/math/particle-noise.js +28 -28
- package/math/periodic.js +5 -5
- package/math/random.js +24 -15
- package/math/rectangles.js +52 -0
- package/math/rock-texture.js +7 -7
- package/math/scalar.js +5 -5
- package/math/surface-textures.js +54 -54
- package/motion/arm-reach.js +24 -24
- package/motion/ballistic-arc.js +11 -0
- package/motion/biped-cycle.js +44 -0
- package/motion/biped-leg.js +37 -0
- package/motion/biped-stride.js +98 -122
- package/motion/contact-transition.js +33 -0
- package/motion/crowd-alarms.js +39 -39
- package/motion/crowd-routine.js +94 -65
- package/motion/daily-clock.js +9 -9
- package/motion/deck-surface.js +38 -0
- package/motion/ground-lookahead.js +5 -5
- package/motion/instance-sight.js +8 -8
- package/motion/player.js +36 -28
- package/motion/quadruped.js +155 -155
- package/motion/spaces.js +32 -32
- package/motion/weather.js +73 -24
- package/motion/wind.js +32 -13
- package/package.json +7 -3
- package/rendering/caster-motion.js +5 -5
- package/rendering/cell-lod.js +138 -82
- package/rendering/cloud-dome.js +28 -28
- package/rendering/cloud-field.js +2 -2
- package/rendering/compilation-schedule.js +68 -11
- package/rendering/contact-shadows.js +2 -2
- package/rendering/context.js +12 -0
- package/rendering/crowd-skinning.js +13 -13
- package/rendering/crust.js +18 -12
- package/rendering/daylight.js +3 -3
- package/rendering/detail-range.js +28 -0
- package/rendering/dispose-meshes.js +18 -0
- package/rendering/dof.js +9 -9
- package/rendering/eye-adapt.js +14 -14
- package/rendering/far-shadow.js +8 -8
- package/rendering/flocks.js +78 -78
- package/rendering/garment-material.js +17 -17
- package/rendering/glow-lines.js +13 -13
- package/rendering/hair-strands.js +20 -20
- package/rendering/height-probe.js +149 -19
- package/rendering/label-layout.js +46 -0
- package/rendering/label-range.js +38 -0
- package/rendering/light-budget.js +52 -52
- package/rendering/light-shafts.js +23 -23
- package/rendering/local-lights.js +15 -4
- package/rendering/material-lod.js +49 -49
- package/rendering/particle-emitters.js +90 -90
- package/rendering/particles.js +78 -67
- package/rendering/piece-batch.js +17 -6
- package/rendering/planar-reflection.js +38 -38
- package/rendering/post-shaders.js +17 -13
- package/rendering/post.js +71 -71
- package/rendering/rain-streaks.js +67 -0
- package/rendering/road-surface.js +11 -11
- package/rendering/sea-shaders.js +11 -11
- package/rendering/shader-warmup.js +29 -16
- package/rendering/shadow-alignment.js +4 -4
- package/rendering/shadow-depth.js +7 -7
- package/rendering/sky-occlusion.js +16 -16
- package/rendering/sky.js +16 -6
- package/rendering/stage-lights.js +6 -6
- package/rendering/static-point-shadow.js +3 -3
- package/rendering/still-casters.js +1 -1
- package/rendering/strata-material.js +10 -10
- package/rendering/stream-flow.js +10 -10
- package/rendering/taa.js +26 -26
- package/rendering/talus.js +15 -15
- package/rendering/terrain-rock.js +7 -7
- package/rendering/texture-fills.js +8 -8
- package/rendering/textures.js +28 -28
- package/rendering/wakes.js +24 -24
- package/rendering/water-material.js +36 -23
- package/rendering/world-matrices.js +38 -38
- package/runtime/diagnostic-log.js +2 -2
- package/runtime/first-use.js +33 -28
- package/runtime/frame-pacing.js +33 -0
- package/runtime/gpu-timing.js +7 -7
- package/runtime/grid-cache.js +1 -1
- package/runtime/grid-rows.js +44 -5
- package/runtime/hand-over.js +41 -23
- package/runtime/pool.js +58 -16
- package/runtime/quality-fit.js +1 -1
- package/runtime/search.js +22 -22
- package/runtime/spatial-audio.js +13 -13
- package/runtime/withdrawable-task.js +35 -0
- package/runtime/worker.js +7 -0
package/motion/weather.js
CHANGED
|
@@ -1,5 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Advance regional rain, dampness, dust and dawn mist for a world clock.
|
|
3
|
+
* @module
|
|
4
|
+
*/
|
|
5
|
+
|
|
1
6
|
import { sstep } from '../math/scalar.js';
|
|
2
7
|
|
|
8
|
+
/**
|
|
9
|
+
* Create an independent weather clock. The returned function advances the region’s
|
|
10
|
+
* spell timer and writes atmospheric intensities into a caller-owned state object.
|
|
11
|
+
* Keep that object between frames so cloud cover can build before rain and the
|
|
12
|
+
* ground can dry after it stops. Changing the region identity restarts its timer.
|
|
13
|
+
* @param {object} [options] - Weather timing and random source.
|
|
14
|
+
* @param {() => number} [options.random] - Random stream in [0, 1). Supply a seeded generator for repeatable spell timing.
|
|
15
|
+
* @param {number} [options.dawn] - Time of peak morning mist as a fraction of the day.
|
|
16
|
+
* @param {number} [options.mistWidth] - Width of the dawn mist curve in fractions of a day.
|
|
17
|
+
* @param {number} [options.fullReach] - Fraction of a local spell’s radius inside which it has full strength.
|
|
18
|
+
* @param {number} [options.dustRise] - Seconds for storm dust to rise from zero to full strength.
|
|
19
|
+
* @param {number} [options.dustSettle] - Seconds for storm dust to settle from full strength to zero.
|
|
20
|
+
* @example
|
|
21
|
+
* ```js
|
|
22
|
+
* import { mulberry32 } from 'roamwright';
|
|
23
|
+
* import { createWeather } from 'roamwright/motion/weather.js';
|
|
24
|
+
* import { createWind } from 'roamwright/motion/wind.js';
|
|
25
|
+
*
|
|
26
|
+
* const updateWeather = createWeather({ random: mulberry32(42) });
|
|
27
|
+
* const wind = createWind({ speed: 3 });
|
|
28
|
+
* const state = { wet: 0, rain: 0, damp: 0, gust: 0, dust: 0, dustStorm: 0, mist: 0, storm: -1 };
|
|
29
|
+
* const coast = { spell: 'squall', every: [30, 60], lasts: [15, 25], mist: true };
|
|
30
|
+
* function frame(elapsedSeconds, deltaSeconds, dayFraction) {
|
|
31
|
+
* updateWeather(state, deltaSeconds, dayFraction, { region: 'coast', weather: coast, x: 0, z: 0 });
|
|
32
|
+
* wind.update(elapsedSeconds, state.gust);
|
|
33
|
+
* }
|
|
34
|
+
* frame(1, 1, 0.25);
|
|
35
|
+
* ```
|
|
36
|
+
*/
|
|
3
37
|
export function createWeather({
|
|
4
38
|
random = Math.random,
|
|
5
39
|
dawn: DAWN = 0.25,
|
|
@@ -13,47 +47,62 @@ export function createWeather({
|
|
|
13
47
|
// v moved toward goal by at most step.
|
|
14
48
|
const toward = (v, goal, step) => (v < goal ? Math.min(goal, v + step) : Math.max(goal, v - step));
|
|
15
49
|
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
50
|
+
/**
|
|
51
|
+
* @param {{wet: number, rain: number, damp: number, gust: number, dust: number, dustStorm: number, mist: number, storm?: number}} weatherState -
|
|
52
|
+
* Mutable intensities. Use storm = -1 for the region’s automatic cycle, or 0–1 to override the spell strength.
|
|
53
|
+
* @param {number} deltaSeconds - Seconds since the previous update.
|
|
54
|
+
* @param {number} hour - Fraction of one day, from 0 to 1.
|
|
55
|
+
* @param {object} location - Observer and region for this frame.
|
|
56
|
+
* @param {unknown} location.region - Stable identity for the current region.
|
|
57
|
+
* @param {{spell?: string, every?: [number, number], lasts?: [number, number], mist?: boolean, reach?: number, x?: number, z?: number} | null} location.weather -
|
|
58
|
+
* Set spell to rain, squall or dust and supply minimum/maximum seconds in every and lasts.
|
|
59
|
+
* For a local spell, set its centre (x, z) and reach in world units. Null clears the weather.
|
|
60
|
+
* @param {number} location.x - Observer’s world X.
|
|
61
|
+
* @param {number} location.z - Observer’s world Z.
|
|
62
|
+
* @param {boolean} [location.running] - Advance the spell timer while true.
|
|
63
|
+
* @param {boolean} [location.quiet] - Suppress spells and dawn mist while true.
|
|
64
|
+
* @param {number} [location.ambientDust] - Local background dust intensity.
|
|
65
|
+
*/
|
|
66
|
+
function updateWeather(weatherState, deltaSeconds, hour, { region, weather: regionWeather, x, z, running = true, quiet = false, ambientDust = 0 }) {
|
|
67
|
+
if (!regionWeather) {
|
|
68
|
+
weatherState.wet = weatherState.rain = weatherState.damp = weatherState.gust = weatherState.dustStorm = weatherState.mist = 0;
|
|
69
|
+
weatherState.dust = ambientDust;
|
|
21
70
|
return;
|
|
22
71
|
}
|
|
23
72
|
if (clock.land !== region) {
|
|
24
73
|
// a land just come to: its first spell is a while off
|
|
25
74
|
clock.land = region;
|
|
26
75
|
clock.on = false;
|
|
27
|
-
clock.next =
|
|
76
|
+
clock.next = regionWeather.spell ? between(regionWeather.every) * (0.5 + 0.5 * random()) : 0;
|
|
28
77
|
}
|
|
29
|
-
if (
|
|
30
|
-
clock.next -=
|
|
78
|
+
if (regionWeather.spell && running) {
|
|
79
|
+
clock.next -= deltaSeconds;
|
|
31
80
|
if (clock.next <= 0) {
|
|
32
81
|
clock.on = !clock.on;
|
|
33
|
-
clock.next = between(clock.on ?
|
|
82
|
+
clock.next = between(clock.on ? regionWeather.lasts : regionWeather.every);
|
|
34
83
|
}
|
|
35
84
|
}
|
|
36
|
-
let spell = !
|
|
37
|
-
if (spell &&
|
|
38
|
-
const dusty =
|
|
39
|
-
squall =
|
|
85
|
+
let spell = !regionWeather.spell || quiet ? 0 : weatherState.storm >= 0 ? weatherState.storm : clock.on ? 1 : 0;
|
|
86
|
+
if (spell && regionWeather.reach) spell *= sstep(regionWeather.reach, regionWeather.reach * SPELL_FADE, Math.hypot(x - regionWeather.x, z - regionWeather.z));
|
|
87
|
+
const dusty = regionWeather.spell === 'dust',
|
|
88
|
+
squall = regionWeather.spell === 'squall',
|
|
40
89
|
wetGoal = dusty ? 0 : spell,
|
|
41
|
-
raining = wetGoal > 0.5 &&
|
|
90
|
+
raining = wetGoal > 0.5 && weatherState.wet > 0.75;
|
|
42
91
|
// clouds gather in under a minute (a squall's sooner) and break up more slowly; the rain waits for the cloud, and stops before it breaks
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
92
|
+
weatherState.wet = toward(weatherState.wet, wetGoal, deltaSeconds / (wetGoal > weatherState.wet ? (squall ? 22 : 40) : 70));
|
|
93
|
+
weatherState.rain = toward(weatherState.rain, raining ? 1 : 0, deltaSeconds / (raining ? 14 : 8));
|
|
94
|
+
weatherState.damp = toward(weatherState.damp, weatherState.rain > 0.3 ? 1 : 0, deltaSeconds / (weatherState.rain > 0.3 ? 45 : 240));
|
|
95
|
+
weatherState.gust = squall ? weatherState.wet : 0;
|
|
47
96
|
// dust: the storm's, what the viewer stands in already (local airborne dust), or a scene's own
|
|
48
|
-
|
|
49
|
-
|
|
97
|
+
weatherState.dustStorm = toward(
|
|
98
|
+
weatherState.dustStorm,
|
|
50
99
|
dusty ? spell : 0,
|
|
51
|
-
|
|
100
|
+
deltaSeconds / (dusty && spell > weatherState.dustStorm ? DUST_RISES : DUST_SETTLES),
|
|
52
101
|
);
|
|
53
|
-
|
|
54
|
-
const clear = (1 -
|
|
102
|
+
weatherState.dust = Math.max(weatherState.dustStorm, ambientDust);
|
|
103
|
+
const clear = (1 - weatherState.wet) * (1 - weatherState.dust),
|
|
55
104
|
apart = (hour - DAWN) / MIST_HOURS;
|
|
56
|
-
|
|
105
|
+
weatherState.mist = toward(weatherState.mist, regionWeather.mist && !quiet ? Math.exp(-apart * apart) * clear : 0, deltaSeconds / 6);
|
|
57
106
|
}
|
|
58
107
|
return updateWeather;
|
|
59
108
|
}
|
package/motion/wind.js
CHANGED
|
@@ -1,6 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Share the same horizontal wind between simulation code and shader effects.
|
|
3
|
+
* @module
|
|
4
|
+
*/
|
|
5
|
+
|
|
1
6
|
import { Vector2, Vector3 } from 'three';
|
|
2
7
|
import { clamp } from '../math/scalar.js';
|
|
3
8
|
|
|
9
|
+
/**
|
|
10
|
+
* Create a wind field with a slowly varying heading and gust strength. The
|
|
11
|
+
* returned wind state and uniforms keep their identity across updates. Bind the
|
|
12
|
+
* uniforms to materials once, then call `update(elapsedSeconds, squall)` per frame.
|
|
13
|
+
* @param {object} [options] - Prevailing wind and its variation.
|
|
14
|
+
* @param {number} [options.speed] - Base speed in metres per second.
|
|
15
|
+
* @param {number} [options.direction] - Heading in radians from +X toward +Z.
|
|
16
|
+
* @param {number} [options.swing] - Maximum angular deviation from the heading in radians.
|
|
17
|
+
* @param {number} [options.squallGain] - Fractional speed increase at full squall strength.
|
|
18
|
+
* @returns `wind` holds a unit direction (x, z), speed and gust. In the shader,
|
|
19
|
+
* `uWind.xy` is X/Z velocity, `uWind.z` is gust, and `uWindDrift` is accumulated displacement in metres.
|
|
20
|
+
*/
|
|
4
21
|
export function createWind({ speed: BREEZE = 1, swing: SWING = 0.16, direction: QUARTER = 0, squallGain: SQUALL = 1 } = {}) {
|
|
5
22
|
const wind = { x: 1, z: 0, speed: BREEZE, gust: 0.5 }; // (x, z): the way it blows, a unit vector; speed in metres a second; gust 0 to 1
|
|
6
23
|
// For shaders: xy the wind's velocity in metres a second (world x, z), z its gust from 0 to 1
|
|
@@ -8,20 +25,22 @@ export function createWind({ speed: BREEZE = 1, swing: SWING = 0.16, direction:
|
|
|
8
25
|
const windU = { uWind: { value: new Vector3(BREEZE, 0, 0.5) }, uWindDrift: { value: new Vector2() } };
|
|
9
26
|
let lastT = 0;
|
|
10
27
|
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
wind.
|
|
19
|
-
wind.
|
|
28
|
+
/**
|
|
29
|
+
* @param {number} elapsedSeconds - Total elapsed simulation time in seconds. Drift advances by at most 0.25 seconds per update.
|
|
30
|
+
* @param {number} squall - Squall strength from 0 to 1. Pass zero for fair weather.
|
|
31
|
+
*/
|
|
32
|
+
function updateWind(elapsedSeconds, squall) {
|
|
33
|
+
const heading = QUARTER + SWING * Math.sin(elapsedSeconds * 0.071),
|
|
34
|
+
gustStrength = clamp(0.5 + 0.22 * Math.sin(elapsedSeconds * 0.21) + 0.18 * Math.sin(elapsedSeconds * 0.077 + 1.3) + 0.1 * Math.sin(elapsedSeconds * 0.53 + 2.1), 0, 1);
|
|
35
|
+
wind.x = Math.cos(heading);
|
|
36
|
+
wind.z = Math.sin(heading);
|
|
37
|
+
wind.gust = Math.max(gustStrength, squall);
|
|
38
|
+
wind.speed = BREEZE * (0.75 + 0.5 * gustStrength) * (1 + SQUALL * squall);
|
|
20
39
|
windU.uWind.value.set(wind.x * wind.speed, wind.z * wind.speed, wind.gust);
|
|
21
|
-
const
|
|
22
|
-
lastT =
|
|
23
|
-
windU.uWindDrift.value.x += wind.x * wind.speed *
|
|
24
|
-
windU.uWindDrift.value.y += wind.z * wind.speed *
|
|
40
|
+
const deltaSeconds = Math.min(0.25, Math.max(0, elapsedSeconds - lastT)); // a long pause carries nothing far
|
|
41
|
+
lastT = elapsedSeconds;
|
|
42
|
+
windU.uWindDrift.value.x += wind.x * wind.speed * deltaSeconds;
|
|
43
|
+
windU.uWindDrift.value.y += wind.z * wind.speed * deltaSeconds;
|
|
25
44
|
}
|
|
26
45
|
return { wind, uniforms: windU, update: updateWind };
|
|
27
46
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "roamwright",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.20.1",
|
|
4
4
|
"description": "A procedural worldbuilding engine built on top of Three.js. Generate landscapes with rivers and changing weather, animate crowds, and explore on foot or in flight.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -35,14 +35,18 @@
|
|
|
35
35
|
"test": "node --test test/*.test.js",
|
|
36
36
|
"demo": "python3 scripts/serve.py",
|
|
37
37
|
"test:browser": "node test/browser.mjs",
|
|
38
|
-
"test:package": "node test/package.mjs"
|
|
38
|
+
"test:package": "node test/package.mjs",
|
|
39
|
+
"docs": "typedoc"
|
|
39
40
|
},
|
|
40
41
|
"peerDependencies": {
|
|
41
42
|
"three": "0.170.0 || 0.187.0"
|
|
42
43
|
},
|
|
43
44
|
"devDependencies": {
|
|
45
|
+
"@types/three": "0.187.0",
|
|
44
46
|
"playwright": "1.65.1",
|
|
45
|
-
"three": "0.187.0"
|
|
47
|
+
"three": "0.187.0",
|
|
48
|
+
"typedoc": "0.28.20",
|
|
49
|
+
"typescript": "5.9.3"
|
|
46
50
|
},
|
|
47
51
|
"publishConfig": {
|
|
48
52
|
"access": "public"
|
|
@@ -59,18 +59,18 @@ export function createCasterMotion({ scene, elapsed, listInterval = 2, skinnedRa
|
|
|
59
59
|
// One mesh's share: its instances within reach, each by its place in the world (by the mesh's own matrix, mostly none) and turn.
|
|
60
60
|
function shareOf(o, w, x, y, z, reach) {
|
|
61
61
|
if (!o.geometry.boundingSphere) o.geometry.computeBoundingSphere();
|
|
62
|
-
const
|
|
62
|
+
const instanceMatrices = o.instanceMatrix.array,
|
|
63
63
|
r = reach + o.geometry.boundingSphere.radius;
|
|
64
64
|
let sum = 0;
|
|
65
65
|
for (let k = 0; k < o.count; k++) {
|
|
66
66
|
const j = k * 16,
|
|
67
|
-
px =
|
|
68
|
-
py =
|
|
69
|
-
pz =
|
|
67
|
+
px = instanceMatrices[j + 12],
|
|
68
|
+
py = instanceMatrices[j + 13],
|
|
69
|
+
pz = instanceMatrices[j + 14],
|
|
70
70
|
wx = w[0] * px + w[4] * py + w[8] * pz + w[12],
|
|
71
71
|
wy = w[1] * px + w[5] * py + w[9] * pz + w[13],
|
|
72
72
|
wz = w[2] * px + w[6] * py + w[10] * pz + w[14];
|
|
73
|
-
if ((wx - x) ** 2 + (wy - y) ** 2 + (wz - z) ** 2 < r * r) sum += (k + 1) * (wx + 3 * wy + 7 * wz +
|
|
73
|
+
if ((wx - x) ** 2 + (wy - y) ** 2 + (wz - z) ** 2 < r * r) sum += (k + 1) * (wx + 3 * wy + 7 * wz + instanceMatrices[j] + 5 * instanceMatrices[j + 2]);
|
|
74
74
|
}
|
|
75
75
|
return sum;
|
|
76
76
|
}
|
package/rendering/cell-lod.js
CHANGED
|
@@ -14,104 +14,121 @@ import * as THREE from 'three';
|
|
|
14
14
|
*
|
|
15
15
|
* @param {object} [options]
|
|
16
16
|
* @param {number} [options.square=500] Metres: far copies are batched by kind within squares of this side.
|
|
17
|
+
* @param {boolean} [options.compact=false] Pack only visible transforms and colours when a cell changes.
|
|
18
|
+
* Use for static cells whose materials depend on their transform and colour, not their instance index or other instance attributes.
|
|
17
19
|
* @param {number} [options.tableWidth=64] Texels across the table of what each cell shows.
|
|
18
20
|
* @param {number} [options.thinFrom=0.45] Beyond this share of the drawing distance a thinned cell keeps `thinTo` of its instances.
|
|
19
21
|
* @param {number} [options.thinTo=0.55]
|
|
20
22
|
*/
|
|
21
|
-
export function createCellLod({ square = 500, tableWidth = 64, thinFrom = 0.45, thinTo = 0.55 } = {}) {
|
|
23
|
+
export function createCellLod({ square = 500, compact = false, tableWidth = 64, thinFrom = 0.45, thinTo = 0.55 } = {}) {
|
|
22
24
|
const table = { data: null, tex: null },
|
|
23
25
|
shown = { value: null }, // the table, as the uniform the far materials and the far shadow body share
|
|
24
|
-
batches = []
|
|
25
|
-
|
|
26
|
-
|
|
26
|
+
batches = [],
|
|
27
|
+
members = [];
|
|
28
|
+
let drawEnds = null,
|
|
29
|
+
dirty = null,
|
|
30
|
+
depth = null,
|
|
31
|
+
distanceMaterial = null;
|
|
27
32
|
|
|
28
33
|
// Hides, in the vertex shader, a copy whose cell is not showing its far copy or that lies past the cell's `count`.
|
|
29
|
-
function hideUnshown(
|
|
30
|
-
|
|
31
|
-
|
|
34
|
+
function hideUnshown(shader) {
|
|
35
|
+
shader.uniforms.uFarShown = shown;
|
|
36
|
+
shader.vertexShader = shader.vertexShader
|
|
32
37
|
.replace('#include <common>', '#include <common>\nattribute vec2 aFar; uniform sampler2D uFarShown;')
|
|
33
|
-
.replace(
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
);
|
|
38
|
+
.replace(/void\s+main\s*\(\s*(?:void)?\s*\)\s*\{/, match => `${match}
|
|
39
|
+
if (aFar.y >= texelFetch(uFarShown, ivec2(int(aFar.x) % ${tableWidth}, int(aFar.x) / ${tableWidth}), 0).r) {
|
|
40
|
+
gl_Position = vec4(2.0, 2.0, 2.0, 1.0);
|
|
41
|
+
return;
|
|
42
|
+
}`);
|
|
39
43
|
}
|
|
40
44
|
// A far copy's material: the cell's own, cloned once per material, with its own patch kept and the hiding added.
|
|
41
45
|
function farMaterial(base, cache) {
|
|
42
46
|
if (cache.has(base)) return cache.get(base);
|
|
43
|
-
const
|
|
47
|
+
const material = base.clone(),
|
|
44
48
|
inner = base.onBeforeCompile,
|
|
45
49
|
key = base.customProgramCacheKey();
|
|
46
|
-
|
|
47
|
-
inner.call(base,
|
|
48
|
-
hideUnshown(
|
|
50
|
+
material.onBeforeCompile = (shader, r) => {
|
|
51
|
+
inner.call(base, shader, r);
|
|
52
|
+
hideUnshown(shader);
|
|
49
53
|
};
|
|
50
|
-
|
|
51
|
-
cache.set(base,
|
|
52
|
-
return
|
|
54
|
+
material.customProgramCacheKey = () => key + ':far-batch';
|
|
55
|
+
cache.set(base, material);
|
|
56
|
+
return material;
|
|
53
57
|
}
|
|
54
58
|
// The shadow body of far copies that cast: the far shape itself, hidden as in the picture, so a cell casts what it shows.
|
|
55
59
|
function depthMaterial() {
|
|
56
60
|
if (depth) return depth;
|
|
57
61
|
depth = new THREE.MeshDepthMaterial({ depthPacking: THREE.RGBADepthPacking });
|
|
58
|
-
|
|
59
|
-
|
|
62
|
+
if (!compact) {
|
|
63
|
+
depth.onBeforeCompile = hideUnshown;
|
|
64
|
+
depth.customProgramCacheKey = () => 'far-batch-depth';
|
|
65
|
+
}
|
|
60
66
|
return depth;
|
|
61
67
|
}
|
|
62
68
|
|
|
63
69
|
/** Batches the far copies of `cells` (taken out of their parents) into `parent`; returns the batches. */
|
|
64
70
|
function batch(cellList, parent) {
|
|
65
|
-
const cells = cellList.filter(
|
|
71
|
+
const cells = cellList.filter(cell => cell.lo && cell.lo.isInstancedMesh),
|
|
66
72
|
groups = new Map(),
|
|
67
73
|
materials = new Map();
|
|
68
74
|
table.data = new Float32Array(tableWidth * Math.ceil(cells.length / tableWidth));
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
75
|
+
if (!compact) {
|
|
76
|
+
table.tex = new THREE.DataTexture(table.data, tableWidth, table.data.length / tableWidth, THREE.RedFormat, THREE.FloatType);
|
|
77
|
+
table.tex.needsUpdate = true;
|
|
78
|
+
shown.value = table.tex;
|
|
79
|
+
}
|
|
80
|
+
cells.forEach((cell, slot) => {
|
|
81
|
+
const lo = cell.lo,
|
|
74
82
|
key = [
|
|
75
83
|
lo.geometry.uuid,
|
|
76
84
|
lo.material.uuid,
|
|
77
85
|
lo.layers.mask,
|
|
78
86
|
lo.receiveShadow,
|
|
79
|
-
|
|
80
|
-
Math.floor(
|
|
81
|
-
Math.floor(
|
|
87
|
+
cell.mesh.castShadow,
|
|
88
|
+
Math.floor(cell.cx / square),
|
|
89
|
+
Math.floor(cell.cz / square),
|
|
82
90
|
].join('|');
|
|
83
|
-
let
|
|
84
|
-
if (!
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
91
|
+
let group = groups.get(key);
|
|
92
|
+
if (!group) groups.set(key, (group = { lo, casts: cell.mesh.castShadow, cells: [] }));
|
|
93
|
+
group.cells.push(cell);
|
|
94
|
+
cell.far = slot;
|
|
95
|
+
cell.farN = lo.instanceMatrix.count;
|
|
96
|
+
cell.lo = null;
|
|
89
97
|
lo.removeFromParent();
|
|
90
98
|
});
|
|
91
99
|
for (const { lo, casts, cells: list } of groups.values()) {
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
if (lo.instanceColor) mesh.instanceColor = new THREE.InstancedBufferAttribute(new Float32Array(n * 3), 3);
|
|
100
|
+
const instanceCount = list.reduce((total, cell) => total + cell.farN, 0),
|
|
101
|
+
geometry = new THREE.BufferGeometry();
|
|
102
|
+
for (const name in lo.geometry.attributes) geometry.setAttribute(name, lo.geometry.attributes[name]);
|
|
103
|
+
geometry.setIndex(lo.geometry.index);
|
|
104
|
+
geometry.boundingSphere = lo.geometry.boundingSphere;
|
|
105
|
+
geometry.boundingBox = lo.geometry.boundingBox;
|
|
106
|
+
const ids = compact ? null : new Float32Array(instanceCount * 2),
|
|
107
|
+
mesh = new THREE.InstancedMesh(geometry, compact ? lo.material : farMaterial(lo.material, materials), instanceCount);
|
|
108
|
+
if (lo.instanceColor) mesh.instanceColor = new THREE.InstancedBufferAttribute(new Float32Array(instanceCount * 3), 3);
|
|
102
109
|
let at = 0;
|
|
103
|
-
for (const
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
110
|
+
for (const cell of list) {
|
|
111
|
+
cell.farBatch = batches.length;
|
|
112
|
+
cell.farStart = at;
|
|
113
|
+
if (cell.lod) cell.lod.batch = cell.farBatch;
|
|
114
|
+
const src = cell.mesh.instanceMatrix.array,
|
|
115
|
+
col = cell.mesh.instanceColor?.array;
|
|
116
|
+
mesh.instanceMatrix.array.set(src.subarray(0, cell.farN * 16), at * 16);
|
|
117
|
+
if (col && mesh.instanceColor) mesh.instanceColor.array.set(col.subarray(0, cell.farN * 3), at * 3);
|
|
118
|
+
if (ids) {
|
|
119
|
+
for (let i = 0; i < cell.farN; i++) {
|
|
120
|
+
ids[(at + i) * 2] = cell.far;
|
|
121
|
+
ids[(at + i) * 2 + 1] = i;
|
|
122
|
+
}
|
|
111
123
|
}
|
|
112
|
-
at +=
|
|
124
|
+
at += cell.farN;
|
|
125
|
+
}
|
|
126
|
+
if (ids) geometry.setAttribute('aFar', new THREE.InstancedBufferAttribute(ids, 2));
|
|
127
|
+
if (compact) {
|
|
128
|
+
mesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
|
|
129
|
+
mesh.instanceColor?.setUsage(THREE.DynamicDrawUsage);
|
|
130
|
+
members.push(list);
|
|
113
131
|
}
|
|
114
|
-
geo.setAttribute('aFar', new THREE.InstancedBufferAttribute(ids, 2));
|
|
115
132
|
mesh.layers.mask = lo.layers.mask;
|
|
116
133
|
mesh.receiveShadow = lo.receiveShadow;
|
|
117
134
|
mesh.castShadow = casts; // as the near copies do
|
|
@@ -119,8 +136,10 @@ export function createCellLod({ square = 500, tableWidth = 64, thinFrom = 0.45,
|
|
|
119
136
|
mesh.customDepthMaterial = depthMaterial();
|
|
120
137
|
if (!distanceMaterial) {
|
|
121
138
|
distanceMaterial = new THREE.MeshDistanceMaterial();
|
|
122
|
-
|
|
123
|
-
|
|
139
|
+
if (!compact) {
|
|
140
|
+
distanceMaterial.onBeforeCompile = hideUnshown;
|
|
141
|
+
distanceMaterial.customProgramCacheKey = () => 'far-batch-distance';
|
|
142
|
+
}
|
|
124
143
|
}
|
|
125
144
|
mesh.customDistanceMaterial = distanceMaterial;
|
|
126
145
|
mesh.userData.partShown = true; // a pass drawing heights with a plain depth material would show every copy
|
|
@@ -130,14 +149,41 @@ export function createCellLod({ square = 500, tableWidth = 64, thinFrom = 0.45,
|
|
|
130
149
|
parent.add(mesh);
|
|
131
150
|
batches.push(mesh);
|
|
132
151
|
}
|
|
133
|
-
|
|
152
|
+
drawEnds = new Int32Array(batches.length);
|
|
153
|
+
if (compact) dirty = new Uint8Array(batches.length).fill(1);
|
|
134
154
|
return batches;
|
|
135
155
|
}
|
|
136
156
|
|
|
157
|
+
// Near cells own the immutable source records. Keep their order so overlapping
|
|
158
|
+
// surfaces and transparent instances blend exactly as in the original batch.
|
|
159
|
+
function packVisible(batchIndex) {
|
|
160
|
+
const mesh = batches[batchIndex];
|
|
161
|
+
let end = 0;
|
|
162
|
+
for (const cell of members[batchIndex]) {
|
|
163
|
+
const visibleCount = Math.min(table.data[cell.far], cell.farN);
|
|
164
|
+
if (!visibleCount) continue;
|
|
165
|
+
mesh.instanceMatrix.array.set(cell.mesh.instanceMatrix.array.subarray(0, visibleCount * 16), end * 16);
|
|
166
|
+
if (mesh.instanceColor) {
|
|
167
|
+
const colour = cell.mesh.instanceColor;
|
|
168
|
+
if (colour) mesh.instanceColor.array.set(colour.array.subarray(0, visibleCount * 3), end * 3);
|
|
169
|
+
else mesh.instanceColor.array.fill(0, end * 3, (end + visibleCount) * 3);
|
|
170
|
+
}
|
|
171
|
+
end += visibleCount;
|
|
172
|
+
}
|
|
173
|
+
mesh.count = end;
|
|
174
|
+
if (!end) return;
|
|
175
|
+
for (const attribute of [mesh.instanceMatrix, mesh.instanceColor]) {
|
|
176
|
+
if (!attribute) continue;
|
|
177
|
+
attribute.clearUpdateRanges();
|
|
178
|
+
attribute.addUpdateRange(0, end * attribute.itemSize);
|
|
179
|
+
attribute.needsUpdate = true;
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
137
183
|
// Where a cell lies and how far it is drawn, kept on it in a record of one shape: cells come from builders of many shapes,
|
|
138
184
|
// and a number read from objects of so many shapes is made anew at every read. A cell does not move.
|
|
139
|
-
const lodOf =
|
|
140
|
-
(
|
|
185
|
+
const lodOf = cell =>
|
|
186
|
+
(cell.lod ??= { cx: cell.cx, cy: cell.cy ?? 0, cz: cell.cz, r: cell.r, until: cell.until ?? Infinity, near: cell.near ?? Infinity, batch: cell.farBatch ?? -1 });
|
|
141
187
|
|
|
142
188
|
/**
|
|
143
189
|
* Each frame: near cells show their detailed mesh, far ones their batched copy, thinned beyond `thinFrom` of the drawing
|
|
@@ -147,37 +193,47 @@ export function createCellLod({ square = 500, tableWidth = 64, thinFrom = 0.45,
|
|
|
147
193
|
*/
|
|
148
194
|
function update(cells, cx, cz, distance, detail, density, cy, rangeScale = 1) {
|
|
149
195
|
let changed = false;
|
|
150
|
-
if (
|
|
196
|
+
if (drawEnds) drawEnds.fill(0);
|
|
151
197
|
for (let i = 0; i < cells.length; i++) {
|
|
152
|
-
const
|
|
153
|
-
at = lodOf(
|
|
198
|
+
const cell = cells[i],
|
|
199
|
+
at = lodOf(cell),
|
|
154
200
|
dx = cx - at.cx,
|
|
155
201
|
dz = cz - at.cz,
|
|
156
202
|
horizontalSq = dx * dx + dz * dz,
|
|
157
|
-
|
|
158
|
-
hasFar =
|
|
159
|
-
const vis =
|
|
160
|
-
nearDistance = cy === undefined ?
|
|
203
|
+
detailDistance = Math.sqrt(horizontalSq) / rangeScale - at.r,
|
|
204
|
+
hasFar = cell.lo || cell.far !== undefined;
|
|
205
|
+
const vis = detailDistance < Math.min(distance, at.until),
|
|
206
|
+
nearDistance = cy === undefined ? detailDistance : Math.sqrt(horizontalSq + (cy - at.cy) ** 2) / rangeScale - at.r,
|
|
161
207
|
hi = !hasFar || nearDistance < Math.min(detail, at.near);
|
|
162
|
-
|
|
163
|
-
if (
|
|
164
|
-
let count =
|
|
165
|
-
if (
|
|
166
|
-
count = Math.max(1, (
|
|
167
|
-
|
|
168
|
-
if (
|
|
208
|
+
cell.mesh.visible = vis && hi;
|
|
209
|
+
if (cell.lo) cell.lo.visible = vis && !hi;
|
|
210
|
+
let count = cell.farN;
|
|
211
|
+
if (cell.full !== undefined) {
|
|
212
|
+
count = Math.max(1, (cell.full * (detailDistance < distance * thinFrom ? 1 : thinTo) * density) | 0);
|
|
213
|
+
cell.mesh.count = count;
|
|
214
|
+
if (cell.lo) cell.lo.count = count;
|
|
169
215
|
}
|
|
170
|
-
if (
|
|
216
|
+
if (cell.far !== undefined) {
|
|
171
217
|
const v = vis && !hi ? count : 0;
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
218
|
+
// A single draw preserves gl_InstanceID and the order of overlapping instances.
|
|
219
|
+
// Omit its invisible tail; the shader clips gaps before doing any vertex work.
|
|
220
|
+
if (v > 0) drawEnds[at.batch] = Math.max(drawEnds[at.batch], cell.farStart + Math.min(cell.farN, v));
|
|
221
|
+
if (table.data[cell.far] !== v) {
|
|
222
|
+
table.data[cell.far] = v;
|
|
223
|
+
if (compact) dirty[at.batch] = 1;
|
|
175
224
|
changed = true;
|
|
176
225
|
}
|
|
177
226
|
}
|
|
178
227
|
}
|
|
179
|
-
if (changed) table.tex.needsUpdate = true;
|
|
180
|
-
for (let i = 0; i < batches.length; i++)
|
|
228
|
+
if (changed && table.tex) table.tex.needsUpdate = true;
|
|
229
|
+
for (let i = 0; i < batches.length; i++) {
|
|
230
|
+
if (!compact) batches[i].count = drawEnds[i];
|
|
231
|
+
else if (dirty[i]) {
|
|
232
|
+
packVisible(i);
|
|
233
|
+
dirty[i] = 0;
|
|
234
|
+
}
|
|
235
|
+
batches[i].visible = drawEnds[i] > 0;
|
|
236
|
+
}
|
|
181
237
|
}
|
|
182
238
|
|
|
183
239
|
return { batch, update, batches };
|