roamwright 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/CONTRIBUTING.md +39 -8
  2. package/README.md +53 -24
  3. package/examples/viaduct-camera.js +40 -0
  4. package/examples/viaduct-landscape.js +81 -0
  5. package/examples/viaduct.css +75 -0
  6. package/examples/viaduct.html +47 -0
  7. package/examples/viaduct.js +332 -0
  8. package/geometry/builder.js +11 -14
  9. package/geometry/creased-sheet.js +127 -0
  10. package/geometry/ear.js +97 -0
  11. package/geometry/erosion.js +106 -0
  12. package/geometry/face-grid.js +143 -0
  13. package/geometry/garment-tags.js +11 -0
  14. package/geometry/hair-gathers.js +174 -0
  15. package/geometry/hair-locks.js +156 -0
  16. package/geometry/hair-patch.js +42 -0
  17. package/geometry/hair-shell.js +186 -0
  18. package/geometry/hair-tags.js +6 -0
  19. package/geometry/head-profile.js +138 -0
  20. package/geometry/head-shape.js +499 -0
  21. package/geometry/heightfield.js +68 -0
  22. package/geometry/outline-grid.js +46 -0
  23. package/geometry/path-field.js +65 -0
  24. package/geometry/sagging-tube.js +58 -0
  25. package/geometry/sampled-surface.js +101 -0
  26. package/geometry/scatter-grid.js +32 -0
  27. package/geometry/sculpt.js +263 -0
  28. package/geometry/shore-grid.js +67 -0
  29. package/geometry/strata-field.js +339 -0
  30. package/geometry/strata-tiles.js +215 -0
  31. package/geometry/stream.js +94 -0
  32. package/geometry/terrain-chunks.js +300 -0
  33. package/geometry/terrain-extension.js +44 -0
  34. package/math/cell-edge.js +44 -0
  35. package/math/cloth-textures.js +83 -0
  36. package/math/cloud-textures.js +112 -0
  37. package/math/color.js +29 -0
  38. package/math/curve.js +3 -4
  39. package/math/mountain-ranges.js +463 -0
  40. package/math/particle-noise.js +48 -0
  41. package/math/periodic.js +20 -0
  42. package/math/rock-texture.js +56 -0
  43. package/math/surface-textures.js +241 -0
  44. package/motion/arm-reach.js +74 -0
  45. package/motion/biped-stride.js +276 -0
  46. package/motion/crowd-alarms.js +127 -0
  47. package/motion/crowd-routine.js +183 -0
  48. package/motion/daily-clock.js +59 -0
  49. package/motion/instance-sight.js +84 -0
  50. package/motion/quadruped.js +332 -0
  51. package/motion/weather.js +59 -0
  52. package/motion/wind.js +27 -0
  53. package/package.json +6 -4
  54. package/rendering/caster-motion.js +79 -0
  55. package/rendering/cell-lod.js +175 -0
  56. package/rendering/cloud-dome.js +371 -0
  57. package/rendering/cloud-field.js +83 -0
  58. package/rendering/compilation-schedule.js +34 -0
  59. package/rendering/contact-shadows.js +79 -0
  60. package/rendering/crowd-skinning.js +133 -0
  61. package/rendering/crust.js +28 -0
  62. package/rendering/daylight.js +50 -0
  63. package/rendering/far-shadow.js +186 -0
  64. package/rendering/flocks.js +323 -0
  65. package/rendering/garment-material.js +110 -0
  66. package/rendering/glow-lines.js +74 -0
  67. package/rendering/glow-shell.js +90 -0
  68. package/rendering/hair-strands.js +67 -0
  69. package/rendering/height-haze.js +129 -0
  70. package/rendering/height-probe.js +91 -0
  71. package/rendering/interior-mapping.js +19 -0
  72. package/rendering/light-budget.js +222 -0
  73. package/rendering/light-points.js +51 -0
  74. package/rendering/light-shafts.js +131 -0
  75. package/rendering/local-lights.js +28 -0
  76. package/rendering/low-light.js +13 -0
  77. package/rendering/material-lod.js +110 -0
  78. package/rendering/particle-emitters.js +223 -0
  79. package/rendering/particles.js +297 -0
  80. package/rendering/planar-reflection.js +175 -0
  81. package/rendering/post-shaders.js +21 -1
  82. package/rendering/post.js +8 -5
  83. package/rendering/rain-rings.js +22 -0
  84. package/rendering/road-surface.js +63 -0
  85. package/rendering/sea-shaders.js +230 -0
  86. package/rendering/shader-warmup.js +197 -0
  87. package/rendering/shadow-alignment.js +28 -0
  88. package/rendering/shadow-depth.js +129 -0
  89. package/rendering/sky-occlusion.js +187 -0
  90. package/rendering/sky.js +169 -0
  91. package/rendering/stage-lights.js +209 -0
  92. package/rendering/static-point-shadow.js +119 -0
  93. package/rendering/still-casters.js +6 -11
  94. package/rendering/strata-material.js +93 -0
  95. package/rendering/stream-flow.js +36 -0
  96. package/rendering/surface-light.js +22 -0
  97. package/rendering/surface-projection.js +69 -0
  98. package/rendering/talus.js +26 -0
  99. package/rendering/terrain-rock.js +48 -0
  100. package/rendering/texture-fills.js +68 -0
  101. package/rendering/viewport.js +9 -0
  102. package/rendering/wakes.js +99 -0
  103. package/rendering/water-material.js +288 -0
  104. package/rendering/world-matrices.js +4 -6
  105. package/runtime/device-quality.js +27 -0
  106. package/runtime/diagnostic-log.js +80 -0
  107. package/runtime/events.js +14 -0
  108. package/runtime/first-use.js +3 -1
  109. package/runtime/frame-yield.js +14 -0
  110. package/runtime/grid-cache.js +88 -0
  111. package/runtime/grid-rows.js +9 -0
  112. package/runtime/module-preload.js +15 -0
  113. package/runtime/quality-fit.js +5 -9
  114. package/runtime/search.js +69 -0
  115. package/runtime/spatial-audio.js +57 -0
  116. package/scripts/serve.py +26 -0
@@ -0,0 +1,169 @@
1
+ import * as THREE from 'three';
2
+
3
+ export function createSky({ field, dome, moonRadius: MOON_RADIUS = 0.0347 }) {
4
+ const {
5
+ fieldGLSL: CLOUD_FIELD_PARS,
6
+ dip: DIP,
7
+ projection: FLARE,
8
+ fadeStart: LOWEST,
9
+ fadeEnd: WHOLE,
10
+ uniforms: cloudU,
11
+ sheetSpan: CLOUD_SHEET,
12
+ } = field;
13
+ const { sampleGLSL: DOME_PARS, uniforms: domeU } = dome;
14
+ const skyMat = new THREE.ShaderMaterial({
15
+ side: THREE.BackSide,
16
+ depthWrite: false,
17
+ fog: false,
18
+ uniforms: {
19
+ uSunDir: { value: new THREE.Vector3() },
20
+ uMoonDir: { value: new THREE.Vector3() },
21
+ uMoonLit: { value: 1 }, // how bright the moon is for its phase: its halo's strength
22
+ uZenith: { value: new THREE.Color() },
23
+ uHorizon: { value: new THREE.Color() },
24
+ uSunCol: { value: new THREE.Color() },
25
+ uNight: { value: 0 },
26
+ uDusk: { value: 0 },
27
+ uDay: { value: 1 },
28
+ uLow: { value: 0 },
29
+ uTime: { value: 0 },
30
+ uCloud: { value: 0.5 }, // the field's value where cloud begins: the lower, the more of the sky is covered
31
+ uWet: { value: 0 },
32
+ uDust: { value: 0 }, // how much blown sand is in the air: it hides the stars and pales the sun and moon
33
+ uThin: { value: 0 }, // how far the sky is closed over by a thin, dry sheet of cloud (a scene's own sky), not by rain cloud
34
+ uGlow: { value: new THREE.Color(0, 0, 0) },
35
+ uGlowDir: { value: new THREE.Vector3(0, -1, 0) },
36
+ uCloudField: cloudU.uCloudField,
37
+ uCloudAt: { value: new THREE.Vector2() }, // where the sheet lies over the viewer, for the thin high cloud
38
+ uCloudDir: { value: new THREE.Vector3(0, 1, 0) }, // towards the light on the clouds: the sun, or by night the moon
39
+ uCloudLight: { value: new THREE.Color() }, // that light: white by day, gold as the sun sinks, rose after it has set
40
+ ...domeU,
41
+ },
42
+ vertexShader: `/* glsl */ varying vec3 vDir;
43
+ void main(){ vDir = position; vec4 p = projectionMatrix * vec4(mat3(viewMatrix) * position, 1.0); gl_Position = p.xyww; }`,
44
+ fragmentShader: `/* glsl */
45
+ uniform float uMoonLit;
46
+ uniform vec3 uSunDir, uMoonDir, uZenith, uHorizon, uSunCol, uGlow, uGlowDir, uCloudDir, uCloudLight;
47
+ uniform float uNight, uDusk, uDay, uLow, uTime, uCloud, uWet, uDust, uThin;
48
+ uniform vec2 uCloudAt;
49
+ ${CLOUD_FIELD_PARS}
50
+ ${DOME_PARS}
51
+ varying vec3 vDir;
52
+ const float SHEET = ${(FLARE / CLOUD_SHEET).toFixed(6)}; // the sheet's share of a unit of the layer
53
+ const float MANY = 0.86; // how much of the light scattered many times in a cloud comes out of it,
54
+ const float ONCE = 0.5; // and of the light scattered once
55
+ float hash12(vec2 p){ vec3 p3 = fract(vec3(p.xyx) * .1031); p3 += dot(p3, p3.yzx + 33.33); return fract((p3.x + p3.y) * p3.z); }
56
+ float hash13(vec3 p){ p = fract(p * .1031); p += dot(p, p.zyx + 31.32); return fract((p.x + p.y) * p.z); }
57
+ float vn(vec2 p){ vec2 i = floor(p), f = fract(p); f = f*f*(3.-2.*f);
58
+ return mix(mix(hash12(i), hash12(i+vec2(1,0)), f.x), mix(hash12(i+vec2(0,1)), hash12(i+vec2(1,1)), f.x), f.y); }
59
+ // where a direction meets the clouds' base, on the sheet
60
+ vec2 sheetAt(vec3 d){ return d.xz / (max(d.y, 0.0) + ${DIP}) * SHEET + uCloudAt; }
61
+ // how much of a cloud is drawn at a direction's height: none low in the sky, over the roofs and hills (cloud-field.js)
62
+ float aloft(float y){ return smoothstep(${LOWEST}, ${WHOLE}, y); }
63
+ // how much of the light a drop sends on at an angle from the way it came (c the cosine): g > 0 mostly onwards
64
+ float sentOn(float c, float g){ float k = 1.0 + g * g - 2.0 * g * c; return (1.0 - g * g) / (k * sqrt(k)); }
65
+ // the clouds in a direction: rgb the light they send to the eye, a how much of the sky behind them they hide
66
+ vec4 clouds(vec3 d, vec3 behind){
67
+ vec4 dome = cloudDome(d);
68
+ vec3 sky = mix(vec3(dot(uHorizon, vec3(0.3, 0.5, 0.2))), mix(uHorizon, uZenith, 0.35 + 0.35 * uLow), 0.55 + 0.2 * uLow); // the sky's own light on a cloud: greyed, bluer than the horizon, and cool against the gold of a low sun
69
+ sky *= 1.0 + 0.3 * uDusk + 0.9 * uWet; // at dusk the whole sky glows; under rain cloud all the light there is comes down through the cloud
70
+ float toLight = dot(d, uCloudDir);
71
+ // light scattered once goes mostly on the way it came, so a thin edge before the sun is the brightest thing in the sky; a little comes back
72
+ float once = 0.35 * sentOn(toLight, 0.75) + 0.45 * sentOn(toLight, 0.4) + 0.2 * sentOn(toLight, -0.3);
73
+ vec3 lit = uCloudLight * (dome.r * MANY * (1.0 + 0.15 * toLight) + dome.g * ONCE * once) + sky * dome.b;
74
+ // a closed, dry sky is a thin sheet: pale with the light that comes through it, a little darker where it hangs thicker, bright round the sun
75
+ vec3 sheet = (uCloudLight * (0.55 + 0.12 * sentOn(toLight, 0.6)) + sky * 0.6) * (0.55 * dome.a + 1.1 * dome.b);
76
+ lit = mix(lit, sheet, uThin);
77
+ float far = exp(-d.y * 7.0); // far clouds sink into the haze over the horizon
78
+ lit = mix(lit, behind * dome.a, far * 0.8);
79
+ return vec4(lit, dome.a) * aloft(d.y);
80
+ }
81
+ #ifdef SKY_MASK
82
+ uniform sampler2D tDepth; uniform vec2 uPx;
83
+ #endif
84
+ void main(){
85
+ vec3 d = normalize(vDir);
86
+ #ifdef SKY_MASK
87
+ // what blocks the light shafts: anything solid (it wrote depth) fully, cloud by how thick it lies (its thin edges pass the light), open sky not at all
88
+ gl_FragColor = vec4(texture2D(tDepth, gl_FragCoord.xy * uPx).x < 1.0 ? 1.0 : d.y > 0.0 ? smoothstep(0.3, 1.0, cloudDome(d).a) * aloft(d.y) * 0.75 : 0.0);
89
+ return;
90
+ #endif
91
+ float up = max(d.y, 0.0);
92
+ float sd = max(dot(d, uSunDir), 0.0), md = max(dot(d, uMoonDir), 0.0);
93
+ // scattering-style gradient: dense air at the horizon, deep colour overhead
94
+ // while the sun is low the gold lies round the sun's side of the horizon; the far side stays cool, and the blue comes down nearer
95
+ float toSun = dot(d, uSunDir) * 0.5 + 0.5;
96
+ vec3 hor = mix(mix(uHorizon, uZenith, 0.5 * uLow), uHorizon, toSun * toSun);
97
+ vec3 col = mix(hor, uZenith, pow(up, mix(0.42, 0.3, uLow)));
98
+ // warm forward scattering toward a low sun
99
+ col += vec3(1.0, 0.42, 0.14) * uDusk * pow(sd, 6.0) * (1.0 - up) * 0.7;
100
+ col += uSunCol * uLow * (pow(sd, 3.0) * 0.3 + pow(sd, 14.0) * 0.35) * (1.0 - 0.75 * up); // and a wide glow of its own colour through the thick low air
101
+ col += uSunCol * uDay * (pow(sd, 48.0) * 0.22 + pow(sd, 900.0) * 1.2) * (1.0 - 0.45 * uLow);
102
+ // light from a source below the horizon
103
+ vec3 gd = normalize(vec3(uGlowDir.x, 0.0, uGlowDir.z) + 1e-5);
104
+ float gw = pow(max(dot(normalize(vec3(d.x, 0.0, d.z) + 1e-5), gd), 0.0), 2.5) * pow(1.0 - up, 3.0);
105
+ col += uGlow * gw;
106
+ vec3 air = col; // the sky's own colour in this direction, which far clouds sink into
107
+ vec4 cl = d.y > 0.0 ? clouds(d, air) : vec4(0.0);
108
+ // sun disc
109
+ col += uSunCol * smoothstep(0.99955, 0.99985, dot(d, uSunDir)) * 28.0 * (1.0 - 0.6 * uLow) * (1.0 - 0.8 * uDust) * step(-0.05, d.y); // dimmed and reddened by the air it shines through when low
110
+ // stars
111
+ vec3 sp = d * 190.0; vec3 ip = floor(sp);
112
+ float sr = hash13(ip);
113
+ float star = step(0.9965, sr) * smoothstep(0.42, 0.0, length(fract(sp) - 0.5));
114
+ star *= 0.6 + 0.4 * sin(uTime * (1.5 + sr * 40.0) + sr * 90.0);
115
+ col += vec3(0.8, 0.9, 1.0) * star * uNight * 2.2 * smoothstep(0.0, 0.2, d.y) * (1.0 - uDust);
116
+ // moon disc with soft halo and a hint of maria
117
+ float mdisc = smoothstep(0.99925, 0.99955, md), mlit = 0.0;
118
+ if (mdisc > 0.0) {
119
+ // its phase: the face is a sphere lit from the sun's side, the rest of it faint with the light the world throws back
120
+ vec3 mo = (d - uMoonDir * md) / ${MOON_RADIUS};
121
+ vec3 mn = mo - uMoonDir * sqrt(max(1.0 - dot(mo, mo), 0.0));
122
+ mlit = mix(0.03, 1.0, smoothstep(-0.03, 0.09, dot(mn, uSunDir)));
123
+ }
124
+ float mtex = 0.75 + 0.25 * vn(d.xy * 60.0 + d.z * 31.0);
125
+ col += vec3(0.80, 0.86, 1.0) * (mdisc * mlit * mtex * 2.4 + (pow(md, 220.0) * 0.20 + pow(md, 24.0) * 0.035) * uMoonLit) * (0.25 + 0.75 * uNight) * (1.0 - 0.8 * uDust);
126
+ if (d.y > 0.0) {
127
+ // a thin veil of high cloud, far above the layer: only well up the sky, where it does not draw out into streaks
128
+ vec2 across = sheetAt(d) * ${field.textureSize.toFixed(1)}; // in texels
129
+ float fine = min(log2(max(length(dFdx(across)), length(dFdy(across)))), 7.0); // the sheet's level of detail a pixel can show
130
+ float high = textureLod(uCloudField, sheetAt(d) * 0.45 + 0.37, max(fine - 1.0, 0.0)).b;
131
+ float veil = smoothstep(0.5, 0.95, high) * smoothstep(0.1, 0.45, d.y) * smoothstep(0.95, 0.6, uCloud) * 0.26 * (1.0 - 0.6 * uNight);
132
+ col = mix(col, uCloudLight * (0.8 + 1.2 * pow(sd, 6.0)) + mix(uHorizon, uZenith, 0.3) * 0.6, veil);
133
+ col = col * (1.0 - cl.a) + cl.rgb + uGlow * gw * 1.6 * cl.a; // the clouds hide what lies behind them, the sun, moon and stars too; smoke and cloud over a fire are lit from beneath
134
+ }
135
+ gl_FragColor = vec4(col, 1.0);
136
+ #include <tonemapping_fragment>
137
+ #include <colorspace_fragment>
138
+ }`,
139
+ });
140
+ const skyMesh = new THREE.Mesh(new THREE.SphereGeometry(1, 32, 16), skyMat);
141
+ skyMesh.frustumCulled = false;
142
+ skyMesh.renderOrder = -1000;
143
+
144
+ // The same sky drawn as the light-shaft pass's mask (post.js), sharing the sky's uniforms; the scene's colour has no alpha to carry it.
145
+ const skyMask = new THREE.Mesh(
146
+ skyMesh.geometry,
147
+ new THREE.ShaderMaterial({
148
+ side: THREE.BackSide,
149
+ depthTest: false,
150
+ depthWrite: false,
151
+ fog: false,
152
+ uniforms: { ...skyMat.uniforms, tDepth: { value: null }, uPx: { value: new THREE.Vector2() } },
153
+ defines: { SKY_MASK: 1 },
154
+ vertexShader: skyMat.vertexShader,
155
+ fragmentShader: skyMat.fragmentShader,
156
+ }),
157
+ );
158
+ skyMask.frustumCulled = false;
159
+ return {
160
+ mesh: skyMesh,
161
+ mask: skyMask,
162
+ material: skyMat,
163
+ dispose() {
164
+ skyMesh.geometry.dispose();
165
+ skyMat.dispose();
166
+ skyMask.material.dispose();
167
+ },
168
+ };
169
+ }
@@ -0,0 +1,209 @@
1
+ import * as THREE from 'three';
2
+ import { clamp, lerp, sstep } from '../math/scalar.js';
3
+
4
+ /**
5
+ * Lights for a filmed stage, moved with its camera each frame: a fill over the stage by night that becomes a key beside the lens
6
+ * for a closer shot (and for a near shot by day, so a face with the sun behind it is read); a rim behind the players by night, low
7
+ * and to one side, so dark clothes against dark ground keep an edge; and the warm light a fire behind the players throws back at
8
+ * them from the lens's side. Each keeps its strength on the subject whatever the lens's distance. A jump of the lens is a cut,
9
+ * where the lights take their new strength at once.
10
+ *
11
+ * @param {object} options
12
+ * @param {THREE.SpotLight} options.fill The fill and key (a spot whose cone becomes a half-sphere when it is a fill).
13
+ * @param {THREE.SpotLight} options.rim The rim.
14
+ * @param {THREE.PointLight} options.bounce The fire's bounce.
15
+ * @param {{ position: THREE.Vector3, intensity: number, on: boolean }} [options.fire] The brightest fire near the stage.
16
+ * @param {THREE.Color} [options.moonColor] The fill's colour by night.
17
+ * @param {THREE.Color} [options.dayColor] The key's colour by day.
18
+ * @param {object} [options.tuning] Overrides of the constants below.
19
+ */
20
+ export function createStageLights({
21
+ fill,
22
+ rim,
23
+ bounce,
24
+ fire = { position: new THREE.Vector3(), intensity: 0, on: false },
25
+ moonColor = new THREE.Color(0xa9bfe6),
26
+ dayColor = new THREE.Color(0xfff0dc),
27
+ tuning = {},
28
+ }) {
29
+ const T = {
30
+ key: 0.55, // a closer shot's key light: its strength where the subject stands
31
+ keyNear: 5, // a near shot has the key too, in full at keyNear metres from its aim, none past keyFar, by day
32
+ keyFar: 9,
33
+ keyDay: [0.6, 0.9], // from this daylight to this one
34
+ nightFill: 1.25, // the fill over a night stage: its strength where the camera looks,
35
+ nightKey: 0.9, // and how much stronger a closer shot's key is by night
36
+ fillUp: 4.5, // the fill hangs at least this far above the stage, and higher by this share of the lens's distance
37
+ fillRise: 0.3,
38
+ fillRoom: 12, // a lens nearer its aim than this hangs the fill lower in step, down to this share of fillUp
39
+ fillLowest: 0.3,
40
+ decay: 1.2, // how the lights fall off with distance
41
+ keyUp: 1.1, // how far above the lens the key hangs, and how far to one side, in metres
42
+ keyAside: 1.6,
43
+ keySide: 0.8, // the key stands this share of the way from the subject to the lens,
44
+ keyReach: 4.8, // but never further from the subject than this many metres
45
+ keyTop: 3.6, // held in close, it rises in step, up to this many metres over the lens
46
+ keySpread: 1.6, // its cone takes in this many metres round the aim at the subject's distance,
47
+ keySoft: 0.55, // its outer part, by this share of the cone's angle, fading to its edge
48
+ keyCut: 1.5, // and it reaches this many times the subject's distance, fading before
49
+ fillRange: 48, // the fill by night reaches this many metres,
50
+ fillCone: Math.PI / 2, // pointing straight down with its cone opened to a half-sphere
51
+ fillSoft: 0.05,
52
+ rim: 6, // the rim's strength where the players stand
53
+ rimBack: 0.35, // how far behind them, as a share of the lens's distance, between these many metres,
54
+ rimNearest: 3,
55
+ rimFurthest: 12,
56
+ rimUp: 1.2, // how far above the aim, and higher by this share of the lens's distance
57
+ rimRise: 0.12,
58
+ rimSpread: 0.35, // the width its cone takes in at the players, as a share of the lens's distance, at least rimLeast metres
59
+ rimLeast: 1.6,
60
+ rimAside: 0.7, // and to one side, as a share of how far behind
61
+ rimCut: 1.4, // it reaches this many times its distance to them, fading before
62
+ bounce: 0.45, // the warm light thrown back by a fire behind the players: this share of the fire's own light on them,
63
+ bounceAt: 0.45, // from this share of the way from them to the lens, at most bounceNearest metres off
64
+ bounceNearest: 3,
65
+ bounceUp: 0.6, // and this far above the aim
66
+ bounceReach: 14, // a fire further than this from the players throws nothing back
67
+ cutJump: 2.5, // metres the lens moves in one frame that make a cut
68
+ ...tuning,
69
+ };
70
+ const keyAtSubject = (1 - T.keyCut ** -4) ** 2, // the share of its strength the fading leaves it at the subject
71
+ rimAtSubject = (1 - T.rimCut ** -4) ** 2;
72
+ const back = new THREE.Vector3(),
73
+ key = new THREE.Vector3(),
74
+ lastLens = new THREE.Vector3(),
75
+ toFire = new THREE.Vector3();
76
+
77
+ // Points a light standing where it is: at `subject` as a key, its cone taking in the subject; with none, straight down as a fill.
78
+ function aim(light, subject) {
79
+ if (subject) {
80
+ const reach = light.position.distanceTo(subject);
81
+ light.target.position.copy(subject);
82
+ light.angle = Math.atan(T.keySpread / reach);
83
+ light.penumbra = T.keySoft;
84
+ light.distance = reach * T.keyCut;
85
+ } else {
86
+ light.target.position.copy(light.position);
87
+ light.target.position.y -= 1;
88
+ light.angle = T.fillCone;
89
+ light.penumbra = T.fillSoft;
90
+ light.distance = T.fillRange;
91
+ }
92
+ }
93
+ function lightRim(p, l, reach, night, ease) {
94
+ const behind = clamp(reach * T.rimBack, T.rimNearest, T.rimFurthest);
95
+ back.set(l.x - p.x, 0, l.z - p.z).normalize();
96
+ rim.position.copy(l).addScaledVector(back, behind);
97
+ rim.position.x -= back.z * behind * T.rimAside;
98
+ rim.position.z += back.x * behind * T.rimAside;
99
+ rim.position.y += T.rimUp + T.rimRise * reach;
100
+ rim.target.position.copy(l);
101
+ const dist = rim.position.distanceTo(l);
102
+ rim.angle = Math.atan(Math.max(T.rimLeast, reach * T.rimSpread) / dist);
103
+ rim.distance = dist * T.rimCut;
104
+ rim.color.copy(moonColor);
105
+ rim.intensity += ((T.rim * night * dist ** T.decay) / rimAtSubject - rim.intensity) * ease;
106
+ }
107
+ function lightBounce(p, l, reach, ease) {
108
+ toFire.subVectors(fire.position, l);
109
+ const fireDist = Math.max(1, toFire.length()),
110
+ behind = fire.on ? clamp(toFire.normalize().dot(back), 0, 1) * (1 - clamp(fireDist / T.bounceReach, 0, 1)) : 0;
111
+ bounce.position.copy(l).lerp(p, Math.min(T.bounceAt, T.bounceNearest / Math.max(reach, 0.01)));
112
+ bounce.position.y += T.bounceUp;
113
+ const near = Math.max(0.5, bounce.position.distanceTo(l));
114
+ bounce.distance = near * 2.5;
115
+ bounce.intensity += (T.bounce * behind * fire.intensity * (near / fireDist) ** 2 - bounce.intensity) * ease;
116
+ }
117
+
118
+ /**
119
+ * Places and sets the lights for a lens at `p` looking at `l` this frame. `closer`: a closer shot (a key in full, and eased in
120
+ * faster); `day`: the share of daylight, 0 to 1; `dt`: seconds since the last frame. Returns whether the lens jumped (a cut).
121
+ */
122
+ function update(p, l, closer, day, dt) {
123
+ const reach = p.distanceTo(l),
124
+ room = 1 - clamp(reach / T.fillRoom, 0, 1) ** 2,
125
+ held = Math.max(1, (T.keySide * reach) / T.keyReach), // how many times nearer the subject the key is held than its share
126
+ keyOut = (T.keySide * reach) / held,
127
+ keyUp = Math.min(T.keyUp * held, T.keyTop),
128
+ keyed = closer ? 1 : sstep(T.keyFar, T.keyNear, reach) * sstep(T.keyDay[0], T.keyDay[1], day);
129
+ // where the key stands beside the lens, and where the fill hangs over the stage: the light moves between them as the shot
130
+ // comes in, and is aimed at the subject as soon as it is any part a key
131
+ key.copy(l).lerp(p, T.keySide / held);
132
+ key.y += keyUp;
133
+ key.addScaledVector(back.set(p.z - l.z, 0, l.x - p.x).normalize(), T.keyAside);
134
+ fill.position.copy(l).lerp(p, lerp(0.3, 0.85, room));
135
+ fill.position.y += Math.max(T.fillUp * clamp(reach / T.fillRoom, T.fillLowest, 1), T.fillRise * reach);
136
+ fill.position.lerp(key, keyed);
137
+ aim(fill, keyed > 0 ? l : null);
138
+ fill.color.lerpColors(moonColor, dayColor, day);
139
+ const night = 1 - day,
140
+ keyReach = (reach / held) * Math.sqrt((keyOut * keyOut + keyUp * keyUp) / (keyOut * keyOut + T.keyUp * T.keyUp)),
141
+ strength =
142
+ T.nightFill * night * fill.position.distanceTo(l) ** T.decay +
143
+ (keyed * T.key * (1 + T.nightKey * night) * keyReach ** T.decay) / keyAtSubject;
144
+ const cut = lastLens.distanceToSquared(p) > T.cutJump * T.cutJump;
145
+ lastLens.copy(p);
146
+ const ease = cut ? 1 : Math.min(1, dt * (closer ? 12 : 2));
147
+ fill.intensity += (strength - fill.intensity) * ease;
148
+ lightRim(p, l, reach, night, ease);
149
+ lightBounce(p, l, reach, ease);
150
+ return cut;
151
+ }
152
+
153
+ return { update, aim };
154
+ }
155
+
156
+ /**
157
+ * Frames a shot made for a wide screen on a narrower one: the camera draws back along its line of sight until about the same width
158
+ * of the stage is in view, as far as it can go before `blocked(x, y, z)`; what width that leaves out, a wider lens takes in.
159
+ * The returned function moves `shot.p` (from its aim `shot.l`), eases `shot.drawn` (start it at -1) and returns the lens in degrees.
160
+ */
161
+ export function createNarrowFraming({
162
+ blocked,
163
+ stageAspect = 1.5,
164
+ keepWidth = 0.85,
165
+ keepLens = 0.55,
166
+ maxDrawBack = 2.2,
167
+ drawStep = 0.5,
168
+ widestLens = 94,
169
+ } = {}) {
170
+ const back = new THREE.Vector3();
171
+ return function frameNarrow(shot, longLens, dt, baseFov, wideFov, aspect) {
172
+ const lens = baseFov - longLens * keepLens,
173
+ framed = Math.tan(((wideFov - longLens) * Math.PI) / 360) * stageAspect,
174
+ seen = Math.tan((lens * Math.PI) / 360) * aspect,
175
+ need = (keepWidth * framed) / seen, // how many times wider the view must be
176
+ reach = back.subVectors(shot.p, shot.l).length();
177
+ if (need <= 1 || reach < 1e-3) return lens;
178
+ back.divideScalar(reach);
179
+ const want = reach * (Math.min(maxDrawBack, need) - 1);
180
+ let free = 0;
181
+ while (free < want) {
182
+ const s = Math.min(want, free + drawStep);
183
+ if (blocked(shot.p.x + back.x * s, shot.p.y + back.y * s, shot.p.z + back.z * s)) break;
184
+ free = s;
185
+ }
186
+ shot.drawn = shot.drawn < 0 ? free : shot.drawn + (free - shot.drawn) * Math.min(1, dt * 4);
187
+ shot.p.addScaledVector(back, shot.drawn);
188
+ const left = need / (1 + shot.drawn / reach);
189
+ return left <= 1 ? lens : Math.min(widestLens, (Math.atan(Math.tan((lens * Math.PI) / 360) * left) * 360) / Math.PI);
190
+ };
191
+ }
192
+
193
+ /**
194
+ * Samples a camera's keys at time t: keys are [seconds, x, y, z, lookX, lookY, lookZ, cut, lens], a key flagged as a cut held
195
+ * until its time and then jumped to. Writes { src, dst, u } into `out` (u smoothstepped between src and dst).
196
+ */
197
+ export function cameraKeyAt(keys, t, out) {
198
+ let i = 0;
199
+ while (i < keys.length - 2 && keys[i + 1][0] <= t) i++;
200
+ const a = keys[i],
201
+ b = keys[i + 1],
202
+ cutNext = !!b[7];
203
+ let u = cutNext ? 0 : clamp((t - a[0]) / (b[0] - a[0]), 0, 1);
204
+ u = u * u * (3 - 2 * u);
205
+ out.src = cutNext && t >= b[0] ? b : a;
206
+ out.dst = cutNext ? out.src : b;
207
+ out.u = u;
208
+ return out;
209
+ }
@@ -0,0 +1,119 @@
1
+ import * as THREE from 'three';
2
+ import {still, STILL_LAYER} from './still-casters.js';
3
+
4
+ // Cache the static layer of one point shadow. Mark its casters and install the matching
5
+ // shadow depth hooks (custom batch casters may implement keptAway in their own hooks).
6
+ export function createStaticPointShadow(renderer) {
7
+ const shadowMap = renderer.shadowMap;
8
+ const renderShadows = shadowMap.render;
9
+ const only = [];
10
+ const view = new THREE.Camera();
11
+ view.layers.set(STILL_LAYER);
12
+ const origin = new THREE.Vector3(NaN, NaN, NaN), current = new THREE.Vector3();
13
+ let light, map, picture, cachedSum, cachedNear, cachedFar, cachedType, stale = true;
14
+ let previousClear;
15
+
16
+ function framebuffer(target, face) {
17
+ const fb = renderer.properties.get(target).__webglFramebuffer;
18
+ return target.isWebGLCubeRenderTarget ? fb[face] : fb;
19
+ }
20
+
21
+ function copyFace(source, destination, face) {
22
+ const gl = renderer.getContext();
23
+ const {width, height} = destination;
24
+ gl.bindFramebuffer(gl.READ_FRAMEBUFFER, framebuffer(source, face));
25
+ gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, framebuffer(destination, face));
26
+ gl.blitFramebuffer(0, 0, width, height, 0, 0, width, height, gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT, gl.NEAREST);
27
+ gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer(map, renderer.getActiveCubeFace()));
28
+ }
29
+
30
+ function clear(color, depth, stencil) {
31
+ if (renderer.getRenderTarget() === map) copyFace(picture, map, renderer.getActiveCubeFace());
32
+ else previousClear.call(renderer, color, depth, stencil);
33
+ }
34
+
35
+ function capture(scene) {
36
+ const shadow = light.shadow;
37
+ still.round++;
38
+ still.sum = 0;
39
+ renderShadows.call(shadowMap, only, scene, view);
40
+ const next = shadow.map;
41
+ if (!next) return false;
42
+ if (next !== map || next.width !== picture?.width || next.height !== picture?.height) {
43
+ picture?.dispose();
44
+ if (next.isWebGLCubeRenderTarget) {
45
+ picture = new THREE.WebGLCubeRenderTarget(next.width);
46
+ const depth = next.depthTexture;
47
+ picture.depthTexture = new depth.constructor(next.width, depth.type);
48
+ picture.depthTexture.format = depth.format;
49
+ picture.depthTexture.compareFunction = depth.compareFunction;
50
+ picture.depthTexture.minFilter = depth.minFilter;
51
+ picture.depthTexture.magFilter = depth.magFilter;
52
+ } else picture = new THREE.WebGLRenderTarget(next.width, next.height);
53
+ renderer.initRenderTarget(picture);
54
+ }
55
+ map = next;
56
+ const target = renderer.getRenderTarget(), face = renderer.getActiveCubeFace(), level = renderer.getActiveMipmapLevel();
57
+ try {
58
+ renderer.setRenderTarget(map);
59
+ for (let f = 0; f < (map.isWebGLCubeRenderTarget ? 6 : 1); f++) copyFace(map, picture, f);
60
+ } finally { renderer.setRenderTarget(target, face, level); }
61
+ origin.copy(current);
62
+ cachedNear = shadow.camera.near;
63
+ cachedFar = shadow.camera.far;
64
+ cachedType = shadowMap.type;
65
+ cachedSum = still.sum;
66
+ stale = false;
67
+ return true;
68
+ }
69
+
70
+ function shadows(lights, scene, camera) {
71
+ const shadow = light.shadow;
72
+ const requested = this.needsUpdate;
73
+ let usable = this.enabled && (this.autoUpdate || requested) && (shadow.autoUpdate || shadow.needsUpdate) &&
74
+ lights.includes(light) && this.type !== THREE.VSMShadowMap && !(shadow.camera.layers.mask & ~1);
75
+ // The membership counters belong to a single light. Full draws remain correct for other point lights.
76
+ if (usable) for (const other of lights) {
77
+ if (other !== light && other.isPointLight) {
78
+ stale = true;
79
+ usable = false;
80
+ break;
81
+ }
82
+ }
83
+ if (!usable) { renderShadows.call(this, lights, scene, camera); return; }
84
+ current.setFromMatrixPosition(light.matrixWorld);
85
+ if (stale || map !== shadow.map || !origin.equals(current) || cachedNear !== shadow.camera.near ||
86
+ cachedFar !== (light.distance || shadow.camera.far) || cachedType !== this.type ||
87
+ (map.isWebGLCubeRenderTarget && map.width !== shadow.mapSize.x)) {
88
+ const captured = capture(scene);
89
+ shadow.needsUpdate = true;
90
+ this.needsUpdate = requested;
91
+ if (!captured) { renderShadows.call(this, lights, scene, camera); return; }
92
+ }
93
+ previousClear = renderer.clear;
94
+ still.kept = true;
95
+ still.sum = 0;
96
+ renderer.clear = clear;
97
+ try {
98
+ renderShadows.call(this, lights, scene, camera);
99
+ stale = still.sum !== cachedSum;
100
+ } finally {
101
+ renderer.clear = previousClear;
102
+ still.kept = false;
103
+ }
104
+ }
105
+
106
+ function keep(lightToCache) {
107
+ if (!lightToCache?.isPointLight) throw new TypeError('Expected a point light');
108
+ light = only[0] = lightToCache;
109
+ stale = true;
110
+ shadowMap.render = shadows;
111
+ }
112
+ function dispose() {
113
+ if (shadowMap.render === shadows) shadowMap.render = renderShadows;
114
+ picture?.dispose();
115
+ picture = map = light = null;
116
+ only.length = 0;
117
+ }
118
+ return {keep, stale: () => stale, dispose};
119
+ }
@@ -1,12 +1,7 @@
1
- // ════════════════════════════════════════════════════════════════════════
2
- // What stands still in a flame's shadow
3
- // ════════════════════════════════════════════════════════════════════════
4
- // A flame's shadow is six draws of everything round it, and most of that (a town's batches, a set's kit, a city's timber) never
5
- // moves: a shadow cache draws it once into a kept picture, and each later redraw starts from that picture and draws only
6
- // what moves over it. What stands still carries STILL_LAYER, by which that one draw picks it out. While the picture is drawn over
7
- // (`still.kept`), a still caster that is in it as it stands leaves itself out (the shadow renderer); one that is
8
- // not (shown since, a batch whose pieces changed, a mesh that moved) is drawn as ever and the picture is marked to be drawn again.
9
- // Each adds which it is to `still.sum` in both draws, so that one hidden since is missed by the sum and is noticed too.
1
+ // A point-light shadow has six faces. Cache static casters once, then draw
2
+ // dynamic geometry over that depth on subsequent passes. STILL_LAYER selects
3
+ // the static casters. The revision and membership sum invalidate the cache
4
+ // when a caster moves, changes geometry, appears or disappears.
10
5
  const STILL_LAYER = 2,
11
6
  STILL_BIT = 1 << STILL_LAYER;
12
7
  const still = { kept: false, sum: 0, round: 0 }; // round: which drawing of the kept picture this is
@@ -17,8 +12,8 @@ const isStill = object => (object.layers.mask & STILL_BIT) !== 0;
17
12
  // Where a mesh stands, how it is turned (about any axis) and its size, as one number
18
13
  const placeOf = e => e[12] * 1.37 + e[13] * 2.11 + e[14] * 0.59 + e[0] * 5.3 + e[1] * 3.3 + e[2] * 4.1 + e[5] * 1.9 + e[6] * 2.7;
19
14
 
20
- // In a flame's shadow: whether a still caster is left out of this draw, being in the kept picture as `as` says it stands now (a
21
- // batch's count of changes to its pieces, a mesh's place). It is noted either way.
15
+ // Record a caster during cache generation. On subsequent draws, skip it only
16
+ // when its cached revision still matches the caller-supplied transform or batch revision.
22
17
  function keptAway(object, as) {
23
18
  if (!still.kept) {
24
19
  object.keptIn = still.round;
@@ -0,0 +1,93 @@
1
+ import { MeshStandardMaterial, MeshDepthMaterial, RGBADepthPacking, Color } from 'three';
2
+
3
+ import { terrainReliefGLSL } from './terrain-rock.js';
4
+
5
+ const CLIFF_FRAG_HEAD = `/* glsl */
6
+ uniform vec3 uDark, uLight, uIron, uShale, uDust, uLichen, uCrust, uSnow;
7
+ uniform sampler2D uRockTex; uniform float uSnowline;
8
+ varying vec3 vWP, vWN; varying vec4 vRock; varying float vYY; float gH = 0.5; float gSnow = 0.0;
9
+ vec3 rockTri(vec3 p, vec3 bw, float s, float o) { return texture2D(uRockTex, p.zy * s + o).rgb * bw.x + texture2D(uRockTex, p.xz * s + o).rgb * bw.y + texture2D(uRockTex, p.xy * s + o).rgb * bw.z; }`;
10
+ const CLIFF_FRAG = `/* glsl */
11
+ #include <color_fragment>
12
+ {
13
+ vec3 wn = normalize(vWN), bw = abs(wn); bw *= bw; bw *= bw; bw /= bw.x + bw.y + bw.z;
14
+ float vd = length(vViewPosition), nearK = 1.0 - smoothstep(10.0, 55.0, vd), midK = 1.0 - smoothstep(60.0, 320.0, vd);
15
+ float px = length(fwidth(vWP)); // metres to a pixel
16
+ // each scale's relief is let go before its grain is finer than a pixel, or its slope taken pixel to pixel lies as a stipple
17
+ float k1 = 1.0 - smoothstep(0.003, 0.009, px), k2 = 1.0 - smoothstep(0.017, 0.05, px), k3 = 1.0 - smoothstep(0.1, 0.3, px);
18
+ vec3 f3 = rockTri(vWP, bw, 0.041, 0.57), f2 = vec3(0.5, 0.0, f3.b), f1 = vec3(0.5, 0.0, 0.5); // the finer scales only where they show
19
+ if (midK > 0.0) f2 = mix(f2, rockTri(vWP, bw, 0.23, 0.31), midK);
20
+ if (nearK > 0.0) f1 = rockTri(vWP, bw, 1.37, 0.0);
21
+ float t = vRock.x, hard = vRock.y, cav = vRock.z, m = vRock.w;
22
+ vec3 rock = mix(uDark, uLight, t); // grey-brown to pale buff, bed by bed
23
+ rock = mix(rock, uIron, smoothstep(0.8, 0.93, t) * 0.75); // a few beds stained with iron
24
+ rock = mix(rock, uShale, smoothstep(0.16, 0.04, t) * 0.7); // and a few dark ones
25
+ float lam = sin(vYY * 7.3 + f2.r * 4.0) * 0.5 + 0.5;
26
+ rock *= 1.0 - 0.1 * (1.0 - hard) * lam * midK * (1.0 - smoothstep(0.08, 0.2, fwidth(vYY))); // soft beds split into thin laminae
27
+ float gl = max(dot(vColor.rgb, vec3(0.3, 0.55, 0.15)), 0.02);
28
+ rock *= mix(vec3(1.0), clamp(vColor.rgb / gl, 0.7, 1.4), 0.35); // the hue of the ground round it
29
+ rock *= (0.68 + 0.64 * mix(0.5, f1.r, nearK)) * (0.78 + 0.44 * f2.r) * (0.82 + 0.36 * f3.r);
30
+ rock *= 1.0 - 0.16 * f2.g * nearK - 0.16 * f1.g * nearK; // cracks, seen from near
31
+ // Weathering follows the rock grain in fixed world space, including on a curving face.
32
+ float streak = mix(f3.b, f2.b, 0.35);
33
+ float top = smoothstep(0.52, 0.86, wn.y);
34
+ rock *= mix(0.8 + 0.4 * smoothstep(0.3, 0.7, streak), 1.0, smoothstep(0.25, 0.55, wn.y));
35
+ rock *= 1.0 - 0.55 * cav;
36
+ vec3 dust = mix(uDust, vColor.rgb, 0.3) * (0.75 + 0.5 * f2.r);
37
+ rock = mix(rock, dust, top * (0.35 + 0.35 * f3.g) * (1.0 - 0.4 * hard)); // dust and grit on the ledges
38
+ float lich = smoothstep(0.58, 0.78, f3.b * 0.55 + f2.b * 0.45 + 0.1 * top) * (0.35 + 0.65 * top);
39
+ rock = mix(rock, uLichen * (0.6 + 0.8 * f1.r), lich * 0.42); // grey-green lichen, thickest on the tops
40
+ rock = mix(rock, uCrust * (0.7 + 0.5 * f1.r), smoothstep(0.83, 0.92, f2.b) * smoothstep(0.4, 0.7, f3.b) * 0.5 * nearK); // and a few orange crusts
41
+ float foot = 1.0 - smoothstep(0.12, 0.5, m);
42
+ rock = mix(rock, vColor.rgb * (0.85 + 0.45 * f2.r) * 1.35, foot * 0.8); // where it rises out of the ground
43
+ float snowline = uSnowline + (f3.g - 0.5) * 60.0;
44
+ gSnow = smoothstep(snowline, snowline + 30.0, vWP.y) * smoothstep(0.66, 0.86, wn.y + (f2.r - 0.5) * 0.25) * 0.9;
45
+ rock = mix(rock, uSnow * (0.92 + 0.1 * f1.r), gSnow); // snow lies on the high ledges
46
+ rock *= rockShade(vWP.xz); // the clouds' shadows, as on the ground below
47
+ diffuseColor.rgb = rock;
48
+ gH = ((f1.r - 0.5) - f1.g * 1.2) * 0.35 * nearK * k1 + ((f2.r - 0.5) - f2.g * nearK) * 0.9 * midK * k2 + (f3.r - 0.5) * 0.6 * k3 - cav * 0.8;
49
+ gH *= 1.0 - gSnow * 0.8;
50
+ }`;
51
+ const CLIFF_BUMP = `/* glsl */
52
+ #include <normal_fragment_maps>
53
+ normal = terrainReliefNormal(vViewPosition, normal, gH, 2.2, vec2(40.0, 260.0));`;
54
+ // Positions and normals are expressed in the same terrain frame as the sample coordinates.
55
+ const STATIC_VERTEX = `attribute vec4 aRock; attribute float aYY;
56
+ vec3 cP, cN; float cHide;
57
+ void cliffMorph() { cP = position; cN = normal; cHide = 0.0; }`;
58
+ const FULL_LIGHT = 'float rockShade(vec2 xz) { return 1.0; }';
59
+
60
+ export function createStrataMaterial({ texture, palette, snowline = 1e7, shading = FULL_LIGHT, vertex = STATIC_VERTEX, uniforms = {} }) {
61
+ const head = vertex + '\nvarying vec3 vWP, vWN; varying vec4 vRock; varying float vYY;';
62
+ const m = new MeshStandardMaterial({ vertexColors: true, roughness: 0.93 });
63
+ const colors = {};
64
+ for (const key of ['dark', 'light', 'iron', 'shale', 'dust', 'lichen', 'crust', 'snow']) {
65
+ const rgb = palette[key];
66
+ if (!rgb || rgb.length !== 3 || !rgb.every(Number.isFinite)) throw new TypeError('Expected a linear RGB triple for ' + key);
67
+ colors['u' + key[0].toUpperCase() + key.slice(1)] = { value: new Color(...rgb) };
68
+ }
69
+ m.onBeforeCompile = sh => {
70
+ Object.assign(sh.uniforms, uniforms, colors, { uRockTex: { value: texture }, uSnowline: { value: snowline } });
71
+ sh.vertexShader = sh.vertexShader
72
+ .replace('#include <common>', '#include <common>\n' + head)
73
+ .replace('#include <beginnormal_vertex>', 'cliffMorph(); vec3 objectNormal = cN;')
74
+ .replace('#include <begin_vertex>', 'vec3 transformed = cP; vWP = cP; vWN = cN; vRock = aRock; vYY = aYY;')
75
+ .replace('#include <project_vertex>', '#include <project_vertex>\nif (cHide > 0.5) gl_Position = vec4(2.0, 2.0, 2.0, 1.0);');
76
+ sh.fragmentShader = sh.fragmentShader
77
+ .replace('#include <common>', '#include <common>\n' + shading + '\n' + CLIFF_FRAG_HEAD + '\n' + terrainReliefGLSL)
78
+ .replace('#include <color_fragment>', CLIFF_FRAG)
79
+ .replace('#include <roughnessmap_fragment>', '#include <roughnessmap_fragment>\nroughnessFactor = mix(roughnessFactor, 0.62, gSnow);')
80
+ .replace('#include <normal_fragment_maps>', CLIFF_BUMP);
81
+ };
82
+ m.customProgramCacheKey = () => 'strata:' + vertex + ':' + shading;
83
+ const depth = new MeshDepthMaterial({ depthPacking: RGBADepthPacking });
84
+ depth.onBeforeCompile = sh => {
85
+ Object.assign(sh.uniforms, uniforms);
86
+ sh.vertexShader = sh.vertexShader
87
+ .replace('#include <common>', '#include <common>\n' + vertex)
88
+ .replace('#include <begin_vertex>', 'cliffMorph(); vec3 transformed = cP;')
89
+ .replace('#include <project_vertex>', '#include <project_vertex>\nif (cHide > 0.5) gl_Position = vec4(2.0, 2.0, 2.0, 1.0);');
90
+ };
91
+ depth.customProgramCacheKey = () => 'strata-depth:' + vertex;
92
+ return { material: m, depth };
93
+ }
@@ -0,0 +1,36 @@
1
+ // Flow-local coordinates are in metres. Skew and warp the ripples so the crests
2
+ // stay in short, staggered patches as they travel downstream.
3
+ export const STREAM_FLOW_GLSL = /* glsl */ `
4
+ float streamWaveDetail(float footprint, float frequency) {
5
+ return 1.0 - smoothstep(1.05, 2.8, footprint * frequency);
6
+ }
7
+
8
+ vec4 streamFlow(vec3 flow, float acrossMetres, float depth, float travel, float distanceToEye, float footprint) {
9
+ vec2 q = vec2(acrossMetres, flow.y - travel);
10
+ footprint = max(footprint, max(length(dFdx(q)), length(dFdy(q))));
11
+ vec2 broad = vec2(0.78, 0.24), middle = vec2(-1.35, 0.43), fine = vec2(2.4, 1.22);
12
+ vec2 broadWarp = vec2(0.33, -0.22), middleWarp = vec2(0.38, 0.28), fineWarp = vec2(-0.58, 0.63);
13
+ float a = dot(q, broadWarp), b = dot(q, middleWarp), c = dot(q, fineWarp);
14
+ float broadPhase = dot(q, broad) + 1.55 * sin(a);
15
+ float middlePhase = dot(q, middle) + 1.35 * cos(b);
16
+ float finePhase = dot(q, fine) + 0.9 * sin(c);
17
+ vec2 broadRate = broad + 1.55 * cos(a) * broadWarp;
18
+ vec2 middleRate = middle - 1.35 * sin(b) * middleWarp;
19
+ vec2 fineRate = fine + 0.9 * cos(c) * fineWarp;
20
+ float broadDetail = streamWaveDetail(footprint, length(broadRate));
21
+ float middleDetail = streamWaveDetail(footprint, length(middleRate));
22
+ float fineDetail = streamWaveDetail(footprint, length(fineRate));
23
+ float packet = 0.5 + 0.5 * sin(dot(q, vec2(0.23, -0.19)) + 0.9 * sin(b));
24
+ vec2 slope = 0.085 * broadRate * cos(broadPhase) * broadDetail * (0.38 + 0.62 * packet)
25
+ + 0.048 * middleRate * cos(middlePhase) * middleDetail * (1.0 - 0.55 * packet)
26
+ + 0.016 * fineRate * cos(finePhase) * fineDetail;
27
+ float fleck = smoothstep(0.66, 0.98, sin(middlePhase)) * smoothstep(0.54, 0.95, packet)
28
+ * (0.08 + 0.32 * flow.z) * middleDetail;
29
+ float broken = smoothstep(0.32, 0.84, 0.55 * packet + 0.45 * (0.5 + 0.5 * sin(broadPhase)));
30
+ float even = max(smoothstep(45.0, 220.0, distanceToEye), 1.0 - broadDetail);
31
+ float rapid = smoothstep(0.28, 0.8, flow.z) * mix(broken, 0.38, even)
32
+ * max(1.0 - 0.5 * flow.x * flow.x, 0.0) * smoothstep(0.3, 1.6, depth);
33
+ float bank = 1.0 - 0.65 * smoothstep(0.62, 1.0, abs(flow.x));
34
+ return vec4(slope * bank, fleck * bank, rapid);
35
+ }
36
+ `;