roamwright 0.1.1 → 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 (111) 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/creased-sheet.js +127 -0
  9. package/geometry/ear.js +97 -0
  10. package/geometry/erosion.js +106 -0
  11. package/geometry/face-grid.js +143 -0
  12. package/geometry/garment-tags.js +11 -0
  13. package/geometry/hair-gathers.js +174 -0
  14. package/geometry/hair-locks.js +156 -0
  15. package/geometry/hair-patch.js +42 -0
  16. package/geometry/hair-shell.js +186 -0
  17. package/geometry/hair-tags.js +6 -0
  18. package/geometry/head-profile.js +138 -0
  19. package/geometry/head-shape.js +499 -0
  20. package/geometry/heightfield.js +68 -0
  21. package/geometry/outline-grid.js +46 -0
  22. package/geometry/path-field.js +65 -0
  23. package/geometry/sagging-tube.js +58 -0
  24. package/geometry/sampled-surface.js +101 -0
  25. package/geometry/scatter-grid.js +32 -0
  26. package/geometry/sculpt.js +263 -0
  27. package/geometry/shore-grid.js +67 -0
  28. package/geometry/strata-field.js +339 -0
  29. package/geometry/strata-tiles.js +215 -0
  30. package/geometry/stream.js +94 -0
  31. package/geometry/terrain-chunks.js +300 -0
  32. package/geometry/terrain-extension.js +44 -0
  33. package/math/cell-edge.js +44 -0
  34. package/math/cloth-textures.js +83 -0
  35. package/math/cloud-textures.js +112 -0
  36. package/math/color.js +29 -0
  37. package/math/mountain-ranges.js +463 -0
  38. package/math/particle-noise.js +48 -0
  39. package/math/periodic.js +20 -0
  40. package/math/rock-texture.js +56 -0
  41. package/math/surface-textures.js +241 -0
  42. package/motion/arm-reach.js +74 -0
  43. package/motion/biped-stride.js +276 -0
  44. package/motion/crowd-alarms.js +127 -0
  45. package/motion/crowd-routine.js +183 -0
  46. package/motion/daily-clock.js +59 -0
  47. package/motion/instance-sight.js +84 -0
  48. package/motion/quadruped.js +332 -0
  49. package/motion/weather.js +59 -0
  50. package/motion/wind.js +27 -0
  51. package/package.json +6 -4
  52. package/rendering/caster-motion.js +79 -0
  53. package/rendering/cell-lod.js +175 -0
  54. package/rendering/cloud-dome.js +371 -0
  55. package/rendering/cloud-field.js +83 -0
  56. package/rendering/compilation-schedule.js +34 -0
  57. package/rendering/contact-shadows.js +79 -0
  58. package/rendering/crowd-skinning.js +133 -0
  59. package/rendering/crust.js +28 -0
  60. package/rendering/daylight.js +50 -0
  61. package/rendering/far-shadow.js +186 -0
  62. package/rendering/flocks.js +323 -0
  63. package/rendering/garment-material.js +110 -0
  64. package/rendering/glow-lines.js +74 -0
  65. package/rendering/glow-shell.js +90 -0
  66. package/rendering/hair-strands.js +67 -0
  67. package/rendering/height-haze.js +129 -0
  68. package/rendering/height-probe.js +91 -0
  69. package/rendering/interior-mapping.js +19 -0
  70. package/rendering/light-budget.js +222 -0
  71. package/rendering/light-points.js +51 -0
  72. package/rendering/light-shafts.js +131 -0
  73. package/rendering/local-lights.js +28 -0
  74. package/rendering/low-light.js +13 -0
  75. package/rendering/material-lod.js +110 -0
  76. package/rendering/particle-emitters.js +223 -0
  77. package/rendering/particles.js +297 -0
  78. package/rendering/planar-reflection.js +175 -0
  79. package/rendering/post-shaders.js +21 -1
  80. package/rendering/post.js +4 -0
  81. package/rendering/rain-rings.js +22 -0
  82. package/rendering/road-surface.js +63 -0
  83. package/rendering/sea-shaders.js +230 -0
  84. package/rendering/shader-warmup.js +197 -0
  85. package/rendering/shadow-alignment.js +28 -0
  86. package/rendering/shadow-depth.js +129 -0
  87. package/rendering/sky-occlusion.js +187 -0
  88. package/rendering/sky.js +169 -0
  89. package/rendering/stage-lights.js +209 -0
  90. package/rendering/static-point-shadow.js +119 -0
  91. package/rendering/strata-material.js +93 -0
  92. package/rendering/stream-flow.js +36 -0
  93. package/rendering/surface-light.js +22 -0
  94. package/rendering/surface-projection.js +69 -0
  95. package/rendering/talus.js +26 -0
  96. package/rendering/terrain-rock.js +48 -0
  97. package/rendering/texture-fills.js +68 -0
  98. package/rendering/viewport.js +9 -0
  99. package/rendering/wakes.js +99 -0
  100. package/rendering/water-material.js +288 -0
  101. package/runtime/device-quality.js +27 -0
  102. package/runtime/diagnostic-log.js +80 -0
  103. package/runtime/events.js +14 -0
  104. package/runtime/first-use.js +3 -1
  105. package/runtime/frame-yield.js +14 -0
  106. package/runtime/grid-cache.js +88 -0
  107. package/runtime/grid-rows.js +9 -0
  108. package/runtime/module-preload.js +15 -0
  109. package/runtime/search.js +69 -0
  110. package/runtime/spatial-audio.js +57 -0
  111. package/scripts/serve.py +26 -0
@@ -0,0 +1,69 @@
1
+ import { MeshStandardMaterial } from 'three';
2
+
3
+ export const projectedVaryings = 'varying vec3 vL; varying vec3 vLN; varying vec3 vHalf; varying float vSeed; varying vec2 vCW;';
4
+
5
+ // Project unit-instance geometry in local metres and track world XZ after deformation.
6
+ function projectSurfaceVertex(shader, { declarations = '', deformInstance = '', assign = '' } = {}) {
7
+ shader.vertexShader = shader.vertexShader.replace('#include <common>', '#include <common>\n' + projectedVaryings + declarations).replace(
8
+ '#include <begin_vertex>',
9
+ `/* glsl */
10
+ #include <begin_vertex>
11
+ #ifdef USE_INSTANCING
12
+ vec3 iS = vec3(length(instanceMatrix[0].xyz), length(instanceMatrix[1].xyz), length(instanceMatrix[2].xyz));
13
+ vL = position * iS; vHalf = iS * 0.5;
14
+ vSeed = fract(instanceMatrix[3].x * 0.137 + instanceMatrix[3].z * 0.291) * 8.0;
15
+ ${deformInstance}
16
+ #else
17
+ vL = position; vHalf = vec3(1000.0); vSeed = 0.0;
18
+ #endif
19
+ vLN = normal;${assign}`,
20
+ );
21
+ shader.vertexShader = shader.vertexShader.replace(
22
+ '#include <project_vertex>',
23
+ '#include <project_vertex>\n{ vec4 cw = vec4(transformed, 1.0);\n#ifdef USE_INSTANCING\ncw = instanceMatrix * cw;\n#endif\nvCW = (modelMatrix * cw).xz; }',
24
+ );
25
+ }
26
+
27
+ // Multiplies the standard material colour and sets the height used for relief.
28
+ export const triplanarColor = ({ texture, scale, gain, height }) => `/* glsl */
29
+ vec3 bw = abs(vLN); bw *= bw; bw /= (bw.x + bw.y + bw.z);
30
+ vec3 tx = texture2D(${texture}, vL.zy * ${scale}).rgb * bw.x + texture2D(${texture}, vL.xz * ${scale}).rgb * bw.y + texture2D(${texture}, vL.xy * ${scale}).rgb * bw.z;
31
+ ${height} = dot(tx, vec3(0.333));
32
+ diffuseColor.rgb *= tx * ${gain};`;
33
+
34
+ export const surfaceRelief = ({ height, strength, fadeStart, fadeEnd }) => `/* glsl */
35
+ { // relief from the procedural height ${height}, fading with distance
36
+ float bs = ${strength} * (1.0 - smoothstep(${fadeStart}, ${fadeEnd}, length(vViewPosition)));
37
+ if (bs > 0.01) {
38
+ vec3 sgx = dFdx(-vViewPosition), sgy = dFdy(-vViewPosition); float lx = length(sgx), ly = length(sgy);
39
+ if (lx > 1e-7 && ly > 1e-7) {
40
+ sgx /= lx; sgy /= ly;
41
+ vec3 r1 = cross(sgy, normal), r2 = cross(normal, sgx); float det = dot(sgx, r1);
42
+ vec3 nb = abs(det) * normal - bs * sign(det) * (dFdx(${height}) * r1 + dFdy(${height}) * r2); float l2 = dot(nb, nb);
43
+ if (l2 > 1e-8) normal = nb * inversesqrt(l2); // never normalise a zero vector: one bad pixel becomes a black block after bloom
44
+ }
45
+ }
46
+ }`;
47
+
48
+ // A standard material with metre-scale projection. Uniform wrappers are shared across compilations.
49
+ export function createProjectedMaterial(
50
+ parameters,
51
+ { cacheKey, uniforms, vertex, declarations = projectedVaryings, color, normal, finish },
52
+ ) {
53
+ if (typeof cacheKey !== 'string' || !cacheKey) throw new TypeError('A projected material needs a shader variant key');
54
+ const material = new MeshStandardMaterial(parameters);
55
+ material.customProgramCacheKey = () => cacheKey;
56
+ material.onBeforeCompile = (shader, renderer) => {
57
+ Object.assign(shader.uniforms, uniforms);
58
+ projectSurfaceVertex(shader, vertex);
59
+ shader.fragmentShader = shader.fragmentShader.replace('#include <common>', '#include <common>\n' + declarations);
60
+ if (color) shader.fragmentShader = shader.fragmentShader.replace('#include <map_fragment>', color);
61
+ if (normal)
62
+ shader.fragmentShader = shader.fragmentShader.replace(
63
+ '#include <normal_fragment_maps>',
64
+ '#include <normal_fragment_maps>\n' + normal,
65
+ );
66
+ finish?.(shader, renderer);
67
+ };
68
+ return material;
69
+ }
@@ -0,0 +1,26 @@
1
+ // Fragment shading for angular debris on a heightfield apron. Use a world position in
2
+ // metres and its derivatives, and the mean spacing of the stones. X is signed facet brightness, Y relief.
3
+ export const talusGLSL = /* glsl */ `
4
+ vec2 talusFragment(vec2 metres, vec2 dx, vec2 dy, float spacing, float seed) {
5
+ mat2 basis = mat2(0.868, -0.497, 0.497, 0.868) / spacing;
6
+ vec2 q = basis * metres;
7
+ vec2 footprint = abs(basis * dx) + abs(basis * dy);
8
+ float resolved = 1.0 - smoothstep(0.12, 0.45, max(footprint.x, footprint.y));
9
+ q.x += 0.5 * mod(floor(q.y), 2.0);
10
+ vec2 cell = floor(q), p = fract(q) - 0.5;
11
+ vec3 h = fract(vec3(cell.xyx) * vec3(0.1031, 0.11369, 0.13787) + seed);
12
+ h += dot(h, h.yzx + 19.19);
13
+ h = fract((h.xxy + h.yzz) * h.zyx);
14
+ p -= (h.xy - 0.5) * 0.14;
15
+ float angle = h.z * 6.28318;
16
+ p = mat2(cos(angle), -sin(angle), sin(angle), cos(angle)) * p;
17
+ float halfWidth = mix(0.13, 0.32, h.y);
18
+ vec2 shape = p / vec2(halfWidth, halfWidth * mix(0.5, 0.9, h.x));
19
+ // Two chipped corners and a slanted top distinguish a fragment from a round pebble.
20
+ float edge = max(max(abs(shape.x), abs(shape.y)), max(dot(shape, vec2(0.77, 0.88)), dot(shape, vec2(-0.74, -0.80))));
21
+ float aa = min(0.8, max(0.025, max(footprint.x, footprint.y) / halfWidth));
22
+ float inside = (1.0 - smoothstep(1.0 - aa, 1.0 + aa, edge)) * resolved;
23
+ float crest = max(0.0, 1.0 - edge);
24
+ float facet = mix(-0.32, 0.36, smoothstep(-aa, aa, shape.x * 0.8 + shape.y * 0.2 + h.z - 0.5));
25
+ return inside * vec2(facet + (h.x - 0.5) * 0.34, 0.28 + 0.72 * crest);
26
+ }`;
@@ -0,0 +1,48 @@
1
+ // World-space rock for a heightfield. The horizontal components of the surface normal
2
+ // weight fixed vertical projections; changing the normal never changes the coordinates.
3
+ export const terrainRockGLSL = /* glsl */ `
4
+ vec3 rockFaceSample(sampler2D grain, vec3 p, float xWeight) {
5
+ return mix(texture2D(grain, p.xy).rgb, texture2D(grain, p.zy + vec2(0.37, 0.19)).rgb, xWeight);
6
+ }
7
+ float rockBed(float height, float frequency, float phase, float footprint) {
8
+ return 0.5 + 0.5 * sin(height * frequency + phase) *
9
+ (1.0 - smoothstep(0.2, 0.5, footprint * frequency));
10
+ }
11
+ vec4 terrainRock(sampler2D grain, vec3 p, vec3 normal, vec3 darkBed, vec3 lightBed, vec3 iron, vec3 lime) {
12
+ vec2 weights = normal.xz * normal.xz;
13
+ weights *= weights;
14
+ float across = weights.x / max(weights.x + weights.y, 0.00001);
15
+ vec3 broad = rockFaceSample(grain, p * 0.021, across);
16
+ vec3 broken = rockFaceSample(grain, p * 0.13, across);
17
+ vec3 fine = rockFaceSample(grain, p * 0.68, across);
18
+ // Warped beds follow the height through corners. Individual grains keep roughly the same size in both axes.
19
+ float height = p.y + (texture2D(grain, p.xz * 0.0031).r - 0.5) * 22.0
20
+ + (broad.g - 0.5) * 3.5 + (broken.b - 0.5) * 1.5;
21
+ float footprint = fwidth(height) * 0.15915;
22
+ float major = rockBed(height, 0.83, 0.0, footprint), minor = rockBed(height, 2.57, 1.3, footprint);
23
+ float stained = rockBed(height, 0.29, 0.7, footprint), lamina = rockBed(height, 7.3, 0.0, footprint);
24
+ vec3 colour = mix(darkBed, lightBed, major * 0.6 + minor * 0.4);
25
+ colour = mix(colour, iron, smoothstep(0.62, 0.95, stained) * 0.55);
26
+ colour = mix(colour, lime, smoothstep(0.75, 1.0, minor * major) * 0.5);
27
+ colour *= (0.92 + 0.12 * lamina) * (0.85 + 0.3 * fine.r) * (0.78 + 0.44 * broad.b) * (0.72 + 0.56 * broken.g);
28
+ return vec4(colour, minor * 0.4 + lamina * 0.12 + broken.g * 0.75 + fine.r * 0.3);
29
+ }`;
30
+
31
+ // Fragment normal for a scalar height. Derivatives are evaluated across the entire quad before the grazing-angle test.
32
+ export const terrainReliefGLSL = /* glsl */ `
33
+ vec3 terrainReliefNormal(vec3 viewToEye, vec3 normal, float height, float strength, vec2 fadeMetres) {
34
+ vec3 sx = dFdx(-viewToEye), sy = dFdy(-viewToEye);
35
+ float gx = dFdx(height), gy = dFdy(height);
36
+ float bump = strength * (1.0 - smoothstep(fadeMetres.x, fadeMetres.y, length(viewToEye))) *
37
+ smoothstep(0.06, 0.4, abs(dot(normal, normalize(viewToEye))));
38
+ float lx = length(sx), ly = length(sy);
39
+ if (bump > 0.01 && lx > 1e-7 && ly > 1e-7) {
40
+ sx /= lx; sy /= ly;
41
+ vec3 r1 = cross(sy, normal), r2 = cross(normal, sx);
42
+ float det = dot(sx, r1);
43
+ vec3 tilted = abs(det) * normal - bump * sign(det) * (gx * r1 + gy * r2);
44
+ float squared = dot(tilted, tilted);
45
+ if (squared > 1e-8) return tilted * inversesqrt(squared);
46
+ }
47
+ return normal;
48
+ }`;
@@ -0,0 +1,68 @@
1
+ import * as THREE from 'three';
2
+ import { onCardOnly } from './textures.js';
3
+
4
+ // Each instance owns the startup queue for one renderer. Fill functions return RGBA bytes.
5
+ export function createTextureFills({ definitions, fillPixels, request, available = () => !!request }) {
6
+ const pending = [],
7
+ waiting = [];
8
+ let asking = false,
9
+ started = false; // once the first frame has been drawn: a texture asked for later is filled here, so it is never drawn empty
10
+
11
+ // Relative cost passed to the application’s scheduler.
12
+ const fillCost = name => definitions[name].cost ?? 1;
13
+ // An empty texture of a fill by name, repeating unless clamped, in sRGB unless it holds data, as `pixelTexture` makes one, and what
14
+ // puts pixels in it. A fill with a `depth` is a block: a texture in three dimensions.
15
+ function emptyTexture(name, opts) {
16
+ const { size, depth } = definitions[name],
17
+ texture = depth ? new THREE.Data3DTexture(null, size, size, depth) : new THREE.DataTexture(null, size, size);
18
+ texture.wrapS = texture.wrapT = texture.wrapR = opts.clamp ? THREE.ClampToEdgeWrapping : THREE.RepeatWrapping;
19
+ texture.colorSpace = opts.data ? THREE.NoColorSpace : THREE.SRGBColorSpace;
20
+ texture.anisotropy = opts.aniso || 4;
21
+ texture.magFilter = THREE.LinearFilter;
22
+ texture.minFilter = THREE.LinearMipmapLinearFilter;
23
+ texture.generateMipmaps = true;
24
+ const fill = pixels => {
25
+ texture.image.data = new Uint8Array(pixels.buffer, pixels.byteOffset, pixels.byteLength);
26
+ texture.needsUpdate = true;
27
+ onCardOnly(texture); // the card keeps it, with its mipmaps
28
+ };
29
+ return { texture, fill };
30
+ }
31
+ // The texture of a fill by name.
32
+ function filledTexture(name, opts = {}) {
33
+ const { texture, fill } = emptyTexture(name, opts),
34
+ ask = () => pending.push(request(name, fillCost(name)).then(fill, () => fill(fillPixels(name))));
35
+ if (!available() || started) fill(fillPixels(name));
36
+ else if (asking) ask();
37
+ else waiting.push(ask);
38
+ return texture;
39
+ }
40
+ // Sends the textures made so far to the workers, and every one made after this at once.
41
+ function fillTextures() {
42
+ asking = true;
43
+ for (const ask of waiting.splice(0)) ask();
44
+ }
45
+ // Kept when every texture asked for so far has its pixels: the first frame waits for it.
46
+ function texturesFilled() {
47
+ fillTextures();
48
+ started = true;
49
+ return Promise.all(pending.splice(0));
50
+ }
51
+
52
+ // A texture asked for in the world, by something built ahead of need, that is not drawn before `filled()`: filled on the pool's
53
+ // workers, or here by `fillNow()` if it is wanted before they answer.
54
+ function filledLater(name, opts = {}) {
55
+ const { texture, fill } = emptyTexture(name, opts);
56
+ let done = false;
57
+ const fillOnce = pixels => {
58
+ if (done) return;
59
+ done = true;
60
+ fill(pixels);
61
+ };
62
+ const fillNow = () => done || fillOnce(fillPixels(name));
63
+ if (available()) request(name, fillCost(name)).then(fillOnce, fillNow);
64
+ else fillNow();
65
+ return { texture, filled: () => done, fillNow };
66
+ }
67
+ return { filledLater, filledTexture, fillTextures, texturesFilled };
68
+ }
@@ -0,0 +1,9 @@
1
+ // Fit the drawing buffer to a pixel-area budget while preserving its aspect.
2
+ export function fittedPixelRatio(width, height, requested, maxPixels = Infinity) {
3
+ return Math.min(requested, Math.sqrt(maxPixels / (width * height)));
4
+ }
5
+
6
+ // Project one world unit at unit depth with a perspective camera's vertical field of view.
7
+ export function perspectivePointScale(height, fovDegrees) {
8
+ return height / (2 * Math.tan(fovDegrees * Math.PI / 360));
9
+ }
@@ -0,0 +1,99 @@
1
+ import * as THREE from 'three';
2
+
3
+ export function createWakes({ slots = 6, minSpeed = 0.25, reach = 450, ease = 4 } = {}) {
4
+ if (!Number.isInteger(slots) || slots < 1) throw new RangeError('Wake slot count must be a positive integer');
5
+ const wakeUniforms = {
6
+ uWake: { value: Array.from({ length: slots }, () => new THREE.Vector4()) }, // her middle x, z; her velocity x, z in m/s
7
+ uWakeS: { value: Array.from({ length: slots }, () => new THREE.Vector4()) }, // her length, beam in metres; 1 while in use
8
+ };
9
+ const hulls = []; // { obj, length, beam, x, z, vx, vz, known, d2 }
10
+
11
+ // Follows the hull carried by obj (her middle at its origin), `length` and `beam` metres, for as long as the page lives.
12
+ function followWake(obj, length, beam = length * 0.3) {
13
+ const hull = { obj, length, beam, x: 0, z: 0, vx: 0, vz: 0, known: false, d2: Infinity };
14
+ hulls.push(hull);
15
+ return () => {
16
+ const i = hulls.indexOf(hull);
17
+ if (i >= 0) hulls.splice(i, 1);
18
+ };
19
+ }
20
+ // Whether obj is in the scene and nothing holding it is hidden.
21
+ function shown(obj) {
22
+ let o = obj;
23
+ for (; o.parent; o = o.parent) if (!o.visible) return false;
24
+ return o.isScene === true;
25
+ }
26
+ // Each frame: how fast each hull is moving, measured from where her frame was last drawn; the nearest under way fill the slots.
27
+ function updateWakes(dt, eye) {
28
+ for (let i = 0; i < hulls.length; i++) {
29
+ const h = hulls[i],
30
+ e = h.obj.matrixWorld.elements;
31
+ h.d2 = Infinity;
32
+ if (!shown(h.obj)) {
33
+ h.known = false;
34
+ continue;
35
+ }
36
+ if (h.known && dt > 0) {
37
+ const k = Math.min(1, dt * ease);
38
+ h.vx += ((e[12] - h.x) / dt - h.vx) * k;
39
+ h.vz += ((e[14] - h.z) / dt - h.vz) * k;
40
+ } else h.vx = h.vz = 0;
41
+ h.x = e[12];
42
+ h.z = e[14];
43
+ h.known = true;
44
+ const d2 = (h.x - eye.x) ** 2 + (h.z - eye.z) ** 2;
45
+ if (d2 < reach * reach && h.vx * h.vx + h.vz * h.vz > minSpeed * minSpeed) h.d2 = d2;
46
+ }
47
+ const at = wakeUniforms.uWake.value,
48
+ size = wakeUniforms.uWakeS.value;
49
+ for (let slot = 0; slot < slots; slot++) {
50
+ let best = null;
51
+ for (let i = 0; i < hulls.length; i++) if (hulls[i].d2 < (best ? best.d2 : Infinity)) best = hulls[i];
52
+ if (!best) {
53
+ size[slot].w = 0;
54
+ continue;
55
+ }
56
+ at[slot].set(best.x, best.z, best.vx, best.vz);
57
+ size[slot].set(best.length, best.beam, 0, 1);
58
+ best.d2 = Infinity; // taken
59
+ }
60
+ }
61
+
62
+ // In the water's main, after its waves (g) are worked out: adds each wake's slope to g and its foam to the white water
63
+ // (rapid). Reads vW, g, rapid, uTime, and the water's fade of a wave by its fineness (OW).
64
+ const WAKE_GLSL = `/* glsl */
65
+ float wakePx = length(fwidth(vW.xz)); // taken before the loop, where every pixel runs it
66
+ for (int i = 0; i < ${slots} && uWakeS[0].w > 0.5; i++) { // the slots fill in order: none if the first is empty
67
+ vec4 H = uWake[i], S = uWakeS[i];
68
+ if (S.w < 0.5) continue;
69
+ vec2 rel = vW.xz - H.xy; float L = S.x, speed = length(H.zw);
70
+ if (dot(rel, rel) > L * L * 144.0) continue; // twelve of her lengths
71
+ vec2 fwd = H.zw / speed, side = vec2(-fwd.y, fwd.x);
72
+ float fromBow = L * 0.5 - dot(rel, fwd), across = dot(rel, side), off = abs(across), sgn = sign(across);
73
+ if (fromBow < -L * 0.3) continue;
74
+ float under = smoothstep(0.25, 1.5, speed), back = max(fromBow, 0.0);
75
+ float k = 9.81 / max(speed * speed, 0.6); // waves that keep pace with her: 2 pi s^2 / g apart
76
+ float arm = off - back * 0.354; // metres outside the arms of the V (19.5 degrees)
77
+ float spread = 0.7 + back * 0.09, envelope = exp(-arm * arm / (spread * spread)) * exp(-back / (L * 3.0)) * under;
78
+ // along each arm a short train of crests, feathered at 55 degrees to her track
79
+ float phase = k * 1.5 * (back * 0.819 + off * 0.574);
80
+ vec2 dPhase = k * 1.5 * (-fwd * 0.819 + side * sgn * 0.574);
81
+ g -= dPhase * (0.022 * envelope * sin(phase)) * smoothstep(0.0, L * 0.3, back) * OW(k * 1.5);
82
+ // inside the V, crests across her track
83
+ float inside = smoothstep(0.5, -1.5, arm) * exp(-back / (L * 3.0)) * under * smoothstep(0.0, L, back);
84
+ g += fwd * (0.012 * inside * k * sin(k * back)) * OW(k);
85
+ // white water: folding along her sides from the bow, and churned behind her stern, spreading as it falls astern
86
+ vec2 hullAt = vec2(-dot(rel, fwd) / (L * 0.5), across / (S.y * 0.5));
87
+ float bowWave = exp(-(length(hullAt) - 1.0) * 5.0) * smoothstep(0.9, 1.0, length(hullAt)) * smoothstep(-0.3, 0.7, -hullAt.x) * smoothstep(0.6, 2.0, speed);
88
+ float astern = back - L, aft = max(astern, 0.0), wide = S.y * (0.35 + aft / (L * 2.5));
89
+ float churn = exp(-off * off / (wide * wide)) * exp(-aft / (L * 1.4)) * smoothstep(-L * 0.5, 0.0, astern) * under;
90
+ float lace = seaLace(vW.xz * 2.0, uTime, wakePx * 2.0);
91
+ float stern = churn * mix(0.85, lace * 0.8, smoothstep(0.0, L * 0.8, aft)); // solid at her stern, breaking into lace astern
92
+ float armFoam = envelope * exp(-back / L) * lace * 0.6; // the bow wave's white running out along the arms a little way
93
+ rapid = max(rapid, clamp(bowWave * (0.55 + 0.45 * lace) + stern + armFoam, 0.0, 1.0));
94
+ }`;
95
+ const WAKE_PARS = `/* glsl */
96
+ uniform vec4 uWake[${slots}], uWakeS[${slots}];`;
97
+
98
+ return { followWake, updateWakes, WAKE_GLSL, WAKE_PARS, wakeUniforms };
99
+ }
@@ -0,0 +1,288 @@
1
+ import * as THREE from 'three';
2
+ import { FOAM_GLSL, SEA_BODY, SEA_OPACITY, SEA_WAVES } from './sea-shaders.js';
3
+ import { RAIN_GLSL, RAIN_PARS } from './rain-rings.js';
4
+ import { STREAM_FLOW_GLSL } from './stream-flow.js';
5
+ import { DEEP, FAR } from '../geometry/stream.js';
6
+
7
+ export function createWaterMaterials({ depthRect, level, seaParameters, wakes, cloudShader = 'float cloudShade(vec2 p) { return 1.0; }', cloudUniforms = {} }) {
8
+ const { WAKE_GLSL, WAKE_PARS, wakeUniforms } = wakes;
9
+ const waterMat = new THREE.ShaderMaterial({
10
+ transparent: true,
11
+ depthWrite: false,
12
+ fog: true,
13
+ uniforms: THREE.UniformsUtils.merge([
14
+ THREE.UniformsLib.fog,
15
+ {
16
+ uTime: { value: 0 },
17
+ uSunDir: { value: new THREE.Vector3() },
18
+ uSunCol: { value: new THREE.Color() },
19
+ uHorizon: { value: new THREE.Color() },
20
+ uZenith: { value: new THREE.Color() },
21
+ uDeep: { value: new THREE.Color() },
22
+ uHasDepth: { value: 1 },
23
+ uGust: { value: 0 }, // how hard a squall's wind blows: it raises the waves
24
+ uLum: { value: 1 },
25
+ uRefl: { value: null },
26
+ uReflM: { value: new THREE.Matrix4() },
27
+ uReflOn: { value: 0 },
28
+ uHarbour: { value: Array.from({ length: 3 }, () => new THREE.Vector4()) },
29
+ uDepthR: { value: depthRect.clone() }, // where the depth map lies: uv = xy + world.xz * zw
30
+ uLevel: { value: level }, // still water, which a stream's ribbon fades into
31
+ uRain: { value: 0 }, // the rain falling where the viewer is, 0 to 1
32
+ uTint: { value: new THREE.Color(1, 1, 1) }, // the water's own colour over the light's (a lake's `tint`: lime-white water is turquoise)
33
+ },
34
+ ]),
35
+ vertexShader: `/* glsl */
36
+ #include <common>
37
+ #include <fog_pars_vertex>
38
+ attribute vec2 aCurrent; attribute vec3 aFlow; attribute vec4 aBank;
39
+ varying vec3 vW, vFlow; varying vec2 vCurrent; varying vec4 vBank;
40
+ void main(){
41
+ vec4 wp = modelMatrix * vec4(position, 1.0); vW = wp.xyz;
42
+ vFlow = aFlow; vCurrent = aCurrent; vBank = aBank;
43
+ vec4 mvPosition = viewMatrix * wp; gl_Position = projectionMatrix * mvPosition;
44
+ #include <fog_vertex>
45
+ }`,
46
+ fragmentShader: `/* glsl */
47
+ uniform float uTime, uHasDepth, uLum, uReflOn, uGust; uniform vec3 uSunDir, uSunCol, uHorizon, uZenith, uDeep; uniform sampler2D uDepth, uRefl; uniform mat4 uReflM;
48
+ uniform vec4 uHarbour[3], uDepthR; uniform float uLevel; uniform vec3 uTint;
49
+ varying vec3 vW, vFlow; varying vec2 vCurrent; varying vec4 vBank;
50
+ #include <common>
51
+ #include <fog_pars_fragment>
52
+ ${cloudShader}
53
+ ${FOAM_GLSL}
54
+ ${WAKE_PARS}
55
+ ${RAIN_PARS}
56
+ #ifdef STREAM_RIFFLES
57
+ uniform vec2 uStreamSpeed;
58
+ ${STREAM_FLOW_GLSL}
59
+ #endif
60
+ #ifdef SEA
61
+ ${seaParameters}
62
+ #endif
63
+ vec2 wv(vec2 p, vec2 d, float f, float s, float a){ return d * (f * a * cos(dot(d, p) * f + uTime * s)); }
64
+ vec2 ripple(vec2 offset, vec2 stretch, float range, float phase) {
65
+ vec2 q = offset * stretch;
66
+ float d = length(q), amp = smoothstep(0.04, 0.45, d) * (1.0 - smoothstep(0.4, range, d));
67
+ return q * stretch * (amp * cos(d * 8.0 - uTime * 3.1 + phase) / max(d, 0.04));
68
+ }
69
+ void main(){
70
+ vec3 V = cameraPosition - vW; float dist = max(length(V), 0.001); V /= dist;
71
+ vec2 depthUv = uDepthR.xy + vW.xz * uDepthR.zw;
72
+ vec3 bed = texture2D(uDepth, depthUv).rgb;
73
+ float dep = mix(vBank.x, bed.r * 10.0 - 2.0, uHasDepth);
74
+ #ifdef SEA
75
+ // past the depth map's edge, whose last row its lookup repeats, the sea's depth is the one its sheet carries at each
76
+ // vertex, over the ground carried out there; and what the map says
77
+ // of its bed (calm water, a shore) is let go there, or a cape's calm shallows ran on past the edge as a band to the horizon
78
+ vec2 pastUv = max(-depthUv, depthUv - 1.0);
79
+ float pastEdge = smoothstep(0.0, 300.0, max(pastUv.x, pastUv.y) / uDepthR.z) * uHasDepth;
80
+ dep = mix(dep, vBank.x, pastEdge);
81
+ bed.gb *= 1.0 - pastEdge;
82
+ #endif
83
+ float waterline = max(dep, 0.0);
84
+ float flow = clamp(length(vCurrent), 0.0, 1.0);
85
+ vec2 p = vW.xz; p += 1.7 * vec2(sin(p.y * 0.071 + uTime * 0.09) + 0.6 * sin(p.y * 0.23 - p.x * 0.11), cos(p.x * 0.063 - uTime * 0.07) + 0.6 * cos(p.x * 0.19 + p.y * 0.13)); // bend the wave trains so they never line up
86
+ // the size of a pixel on the water, along its longer side (at a grazing look, the way the eye looks): waves finer than that
87
+ // are left out, or they shimmer as the eye moves; read from the picture itself, so a smaller picture or a lower look leaves out more
88
+ float fp = max(dist * 0.0016 / max(V.y, 0.04), max(length(dFdx(vW.xz)), length(dFdy(vW.xz))));
89
+ #define OW(f) (1.0 - smoothstep(1.5, 3.6, fp * f))
90
+ vec2 g = wv(p, vec2(0.8,0.6), 0.33, 1.0, 0.24) * OW(0.33) + wv(p, vec2(-0.5,0.866), 0.61, 1.45, 0.13) * OW(0.61)
91
+ + wv(p, vec2(0.2,-0.98), 1.37, 2.2, 0.055) * OW(1.37) + wv(p, vec2(-0.93,-0.36), 2.9, 3.0, 0.024) * OW(2.9)
92
+ + wv(p, vec2(0.6,-0.8), 6.3, 4.4, 0.009) * OW(6.3);
93
+ float nearW = 1.0 / (1.0 + dist * 0.03);
94
+ g += (wv(p, vec2(0.36,0.93), 11.0, 5.6, 0.005) * OW(11.0) + wv(p, vec2(-0.86,0.5), 17.0, 7.1, 0.0032) * OW(17.0) + wv(p, vec2(0.97,-0.24), 27.0, 9.0, 0.002) * OW(27.0) + wv(p, vec2(-0.3,-0.95), 43.0, 12.0, 0.0012) * OW(43.0)) * nearW;
95
+ float gust = sin(p.x * 0.013 + uTime * 0.05) * sin(p.y * 0.017 - uTime * 0.04) + 0.5 * sin(dot(p, vec2(0.031, -0.022)) + uTime * 0.07);
96
+ g *= (0.5 + 0.6 * smoothstep(-0.8, 0.9, gust)) * (1.0 + 1.3 * uGust); // calm slicks and wind-roughened patches; a squall's wind raises it all
97
+ g *= mix(0.39, 1.0, smoothstep(0.0, 2.9, waterline)) * (1.0 - uHasDepth * bed.b * 0.55);
98
+ float currentFleck = 0.0, rapid = 0.0;
99
+ if (flow > 0.01) {
100
+ vec2 downstream = vCurrent / flow, transverse = vec2(-downstream.y, downstream.x);
101
+ #ifdef STREAM_RIFFLES
102
+ vec4 motion = streamFlow(vFlow, vBank.w, dep, uTime * mix(uStreamSpeed.x, uStreamSpeed.y, vFlow.z), dist, fp);
103
+ g = mix(downstream * motion.y + transverse * motion.x, g, 0.22);
104
+ currentFleck = motion.z;
105
+ rapid = motion.w;
106
+ #else
107
+ float speed = mix(1.4, 4.5, vFlow.z), run = vFlow.y, crossRun = vFlow.x;
108
+ float drift = sin(crossRun * 2.1) * 0.18 + cos(crossRun * 4.1) * 0.1;
109
+ float phase = run * 3.6 - uTime * speed * (2.4 + drift) + sin(crossRun * 2.8 + run * 0.14) * 1.7;
110
+ float moving = run - uTime * speed;
111
+ float crease = moving * 1.15 + cos(crossRun * 9.5 + moving * 0.17) * 1.3;
112
+ float threads = sin(crossRun * 7.5 + cos(moving * 0.43)) * cos(moving * 0.68 + crossRun * 8.1);
113
+ vec2 current = downstream * (0.06 * cos(phase) * OW(3.6) + 0.09 * cos(crease) * OW(1.15))
114
+ + transverse * (0.052 * threads + 0.055 * cos(phase) * OW(3.6));
115
+ g = mix(current, g, 0.16);
116
+ currentFleck = smoothstep(0.61, 0.99, sin(crease)) * smoothstep(0.35, 0.9, threads) * (0.08 + 0.32 * vFlow.z) * OW(3.6);
117
+ // white water where the bed falls steeply: streaks of foam racing downstream, thickest in the fast middle, with darker
118
+ // tongues of smooth water between them and quieter water along the edges
119
+ float steep = smoothstep(0.28, 0.8, vFlow.z);
120
+ float streak = 0.5 + 0.5 * sin(crossRun * 11.0 + 2.0 * cos(moving * 0.9));
121
+ // the churn's bands wander (their phase bent by slower waves), or from the air they lay across the river as even stripes
122
+ float churn = 0.5 + 0.5 * sin(moving * 2.3 + crossRun * 5.0 + 1.6 * sin(moving * 0.37 + crossRun * 1.9))
123
+ * cos(moving * 0.7 - crossRun * 3.0 + 0.9 * sin(moving * 0.21 - crossRun * 0.8));
124
+ float banded = smoothstep(0.42, 0.95, streak * 0.55 + churn * 0.7) * mix(0.6, 1.0, OW(2.3));
125
+ // far off, or once the bands are finer than a pixel, the foam is drawn as the share of the water it covers
126
+ float even = max(smoothstep(45.0, 220.0, dist), 1.0 - OW(2.3));
127
+ rapid = steep * mix(banded, 0.38, even) * max(1.0 - 0.5 * crossRun * crossRun, 0.0) * smoothstep(0.3, 1.6, dep);
128
+ #endif
129
+ // a spring: rings spreading from the eye of its pool, where the water wells up
130
+ float eye = length(vBank.zw);
131
+ g += (downstream * vBank.z + transverse * vBank.w) * (exp(-eye * 0.8) * 0.2 * cos(eye * 5.2 - uTime * 3.3) / max(eye, 0.08) * OW(5.2));
132
+ }
133
+ if (uHasDepth > 0.5 && dist < 160.0) {
134
+ vec2 harbourRipples = vec2(0.0);
135
+ for (int i = 0; i < 3; i++) {
136
+ vec4 pier = uHarbour[i]; vec2 d = vec2(cos(pier.w - 10.0), sin(pier.w - 10.0)), r = vW.xz - pier.xy, q = vec2(dot(r, d), d.x * r.y - d.y * r.x);
137
+ if (pier.w < 0.5 || abs(q.y) > 12.0 || q.x < -13.0 || q.x > 41.0) continue;
138
+ float pile = clamp(floor((q.x - 3.0) / 6.0 + 0.5), 0.0, 5.0);
139
+ harbourRipples += ripple(q - vec2(3.0 + 6.0 * pile, sign(q.y) * 1.9), vec2(1.0), 3.8, pile);
140
+ harbourRipples += ripple(q - vec2(6.0, pier.z * 4.2), vec2(0.45, 1.0), 5.5, 1.9);
141
+ harbourRipples += ripple(q - vec2(21.0, -pier.z * 3.6), vec2(0.6, 1.0), 4.5, 3.6);
142
+ }
143
+ g += harbourRipples * 0.19 * OW(8.0);
144
+ }
145
+ #ifdef SEA
146
+ ${SEA_WAVES}
147
+ #endif
148
+ ${WAKE_GLSL}
149
+ ${RAIN_GLSL}
150
+ float fade = 1.0 / (1.0 + dist * 0.011);
151
+ vec3 N = normalize(vec3(-g.x * fade, 1.0, -g.y * fade));
152
+ float fres = 0.03 + 0.97 * pow(1.0 - max(dot(N, V), 0.0), 5.0);
153
+ vec3 R = reflect(-V, N); R.y = abs(R.y);
154
+ vec3 sky = mix(uHorizon, uZenith, pow(R.y, 0.5));
155
+ if (uReflOn > 0.01) { // the mirrored view of shore, city and sky, bent by the waves
156
+ vec4 rc = uReflM * vec4(vW, 1.0);
157
+ if (rc.w > 0.0001) {
158
+ // far off and at a grazing look the waves average out and the shore's thin band of reflection must stay where it is
159
+ float bend = clamp(V.y * 4.0, 0.15, 1.0) / (1.0 + dist * 0.02);
160
+ vec3 rf = texture2D(uRefl, clamp(rc.xy / rc.w + N.xz * vec2(0.12, 0.2) * bend, 0.003, 0.997)).rgb;
161
+ if (rf.r >= 0.0 && rf.g >= 0.0 && rf.b >= 0.0) sky = mix(sky, min(rf, vec3(24.0)), uReflOn);
162
+ }
163
+ }
164
+ float rs = max(dot(R, uSunDir), 0.0);
165
+ float lap = dep + 0.17 * sin(uTime * 1.25 + p.x * 0.29 + p.y * 0.21);
166
+ float breaks = sin(p.x * 0.53 + p.y * 0.73 - uTime * 1.15) * sin(p.y * 0.94 - p.x * 0.32) + 0.33 * gust;
167
+ float foam = uHasDepth * smoothstep(0.06, 0.22, lap) * (1.0 - smoothstep(0.27, 0.64, lap))
168
+ * smoothstep(0.24, 0.74, breaks) * bed.g * (1.0 - bed.b * 0.85) * OW(2.9);
169
+ #ifdef SEA
170
+ foam = 0.0; // the sea's white water is its own (rapid)
171
+ #endif
172
+ float shallow = 1.0 - smoothstep(0.0, 4.2, waterline);
173
+ vec3 silt = mix(vec3(0.045, 0.057, 0.030), vec3(0.043, 0.103, 0.082), bed.g);
174
+ vec3 body = mix(uDeep, silt * uLum + uDeep * 0.60, shallow);
175
+ body = mix(body, vec3(0.064, 0.084, 0.069) * uLum, flow * 0.82 * (1.0 - smoothstep(1.5, 6.0, waterline))); // running water is clouded by what it carries, but a channel's deep middle takes the depth's colour as still water does: a river was one flat grey-green beside the lake it ran into
176
+ #ifdef SEA
177
+ ${SEA_BODY}
178
+ #endif
179
+ body *= uTint;
180
+ float lit = cloudShade(vW.xz); // under a cloud the water lies darker, and the sun's glitter all but goes out
181
+ body *= lit;
182
+ float far = max(smoothstep(30.0, 700.0, dist), smoothstep(0.02, 0.5, fp));
183
+ vec3 col = mix(body, sky, fres) + uSunCol * (lit * lit * lit) * (pow(rs, mix(900.0, 70.0, far)) * mix(10.0, 1.3, far) + pow(rs, 14.0) * 0.12) + vec3(0.58, 0.66, 0.61) * (foam * 0.47 + currentFleck * 0.47) * uLum;
184
+ col = mix(col, vec3(0.78, 0.84, 0.82) * uLum, rapid * 0.86);
185
+ float opacity = mix(0.16, 0.92, 1.0 - exp(-waterline * 0.51 / max(V.y, 0.32)));
186
+ #ifdef SEA
187
+ ${SEA_OPACITY}
188
+ #endif
189
+ float edge = mix(1.0, smoothstep(-0.11, 0.21, dep), uHasDepth);
190
+ #ifdef SEA
191
+ // the sea's sheet lies under the whole land: where the map's A says the water over the bed is a lake's, only the lake's own
192
+ // sheet is drawn, or a pit's lake whose bed sinks below the sea showed the sea's level through it as a patch
193
+ if (vW.y < uLevel + 0.5) edge *= texture2D(uDepth, depthUv).a;
194
+ #endif
195
+ float riverEdge = vBank.y * smoothstep(0.1, 1.0, vBank.x) * mix(1.0, 0.83, flow * shallow); // a ribbon thins out over its banks and at its head, and its running shallows show their bed
196
+ float riverMouth = 1.0 - flow * (1.0 - smoothstep(uLevel + 0.02, uLevel + 0.5, vW.y)) * smoothstep(2.15, 2.8, bed.r * 10.0);
197
+ gl_FragColor = vec4(col, mix(opacity, 1.0, max(max(fres, foam * 0.45), rapid)) * edge * riverEdge * riverMouth);
198
+ #include <tonemapping_fragment>
199
+ #include <colorspace_fragment>
200
+ #include <fog_fragment>
201
+ }`,
202
+ });
203
+ Object.assign(waterMat.uniforms, wakeUniforms, cloudUniforms); // after the merge, which would copy them: shared, not copied
204
+ const streamMat = waterMat.clone(); // streams and open sea: no bed to read
205
+ Object.assign(streamMat.uniforms, wakeUniforms, cloudUniforms);
206
+ streamMat.uniforms.uHasDepth.value = 0;
207
+ streamMat.uniforms.uRefl = { value: null };
208
+ for (const material of [waterMat, streamMat]) stillByDefault(material);
209
+ return { waterMat, streamMat };
210
+ }
211
+ // Preserve the live lighting, clock and wake uniforms when specializing a water material.
212
+ function waterVariant(material) {
213
+ const m = material.clone();
214
+ Object.assign(m.defaultAttributeValues, material.defaultAttributeValues);
215
+ Object.assign(m.uniforms, material.uniforms);
216
+ return m;
217
+ }
218
+
219
+ export function tintedWater(material, tint) {
220
+ const m = waterVariant(material);
221
+ m.uniforms.uTint = { value: new THREE.Color(...tint) };
222
+ return m;
223
+ }
224
+
225
+ // Speeds are metres per second on level and steep reaches, respectively.
226
+ export function rippledStream(material, { speed, rapidSpeed = speed }) {
227
+ const m = waterVariant(material);
228
+ m.defines = { ...m.defines, STREAM_RIFFLES: '' };
229
+ m.uniforms.uStreamSpeed = { value: new THREE.Vector2(speed, rapidSpeed) };
230
+ return m;
231
+ }
232
+ // A sheet of open water has no current, banks or spring of its own.
233
+ function stillByDefault(material) {
234
+ material.defaultAttributeValues.aCurrent = [0, 0];
235
+ material.defaultAttributeValues.aFlow = [0, 0, 0];
236
+ material.defaultAttributeValues.aBank = [DEEP, 1, FAR, FAR];
237
+ }
238
+ // A sheet of open water that shows only in part: at each of its vertices, shareAt(x, z) of it (0 to 1, x and z its own).
239
+ export function partSheet(geometry, shareAt) {
240
+ const pos = geometry.attributes.position,
241
+ bank = new Float32Array(pos.count * 4);
242
+ for (let v = 0; v < pos.count; v++) bank.set([DEEP, shareAt(pos.getX(v), pos.getZ(v)), FAR, FAR], v * 4);
243
+ geometry.setAttribute('aBank', new THREE.BufferAttribute(bank, 4));
244
+ return geometry;
245
+ }
246
+ // A sheet of open water that knows the depth of the bed under each of its vertices past its depth map (depthAt(index), in
247
+ // metres, or null where the map tells it).
248
+ export function sheetDepths(geometry, depthAt) {
249
+ const count = geometry.attributes.position.count,
250
+ bank = new Float32Array(count * 4);
251
+ for (let v = 0; v < count; v++) bank.set([depthAt(v) ?? DEEP, 1, FAR, FAR], v * 4);
252
+ geometry.setAttribute('aBank', new THREE.BufferAttribute(bank, 4));
253
+ return geometry;
254
+ }
255
+ const SHARED = [
256
+ 'uTime',
257
+ 'uSunDir',
258
+ 'uSunCol',
259
+ 'uHorizon',
260
+ 'uZenith',
261
+ 'uLum',
262
+ 'uDeep',
263
+ 'uGust',
264
+ 'uCloudField',
265
+ 'uCloudSh',
266
+ 'uWake',
267
+ 'uWakeS',
268
+ 'uRain',
269
+ ];
270
+ export function landWater(waterMat, depth, rect, level, sea = null) {
271
+ const make = (hasDepth, own) => {
272
+ const m = waterMat.clone();
273
+ for (const k of SHARED) if (waterMat.uniforms[k]) m.uniforms[k] = waterMat.uniforms[k];
274
+ m.uniforms.uDepth = { value: depth };
275
+ m.uniforms.uDepthR.value.copy(rect);
276
+ m.uniforms.uLevel.value = level;
277
+ m.uniforms.uHasDepth.value = hasDepth;
278
+ m.uniforms.uRefl = { value: null };
279
+ if (own) {
280
+ Object.assign(m.uniforms, own);
281
+ m.defines = { SEA: '' };
282
+ }
283
+ stillByDefault(m);
284
+ return m;
285
+ };
286
+ return { open: make(1, sea), stream: make(0) };
287
+ }
288
+
@@ -0,0 +1,27 @@
1
+ const SOFTWARE = /swiftshader|llvmpipe|software|basic render/i;
2
+ const INTEGRATED = /intel|mali|adreno|powervr/i;
3
+
4
+ export function createDeviceQuality({
5
+ renderer, handheld = () => false, memoryGB = () => undefined, cores = () => undefined,
6
+ smallMemory = 2, phoneMemory = 4, desktopMemory = 8, desktopCores = 8,
7
+ }) {
8
+ // The first renderer query can block on outstanding GPU work. Cache its result for future quality changes.
9
+ let card = null;
10
+ function cardName() {
11
+ if (card !== null) return card;
12
+ const gl = renderer.getContext(),
13
+ info = gl.getExtension('WEBGL_debug_renderer_info');
14
+ return (card = String(gl.getParameter(info ? info.UNMASKED_RENDERER_WEBGL : gl.RENDERER)));
15
+ }
16
+ // True where the browser draws in software, with no graphics card: hardware acceleration is switched off, or the card is refused.
17
+ const drawnInSoftware = () => SOFTWARE.test(cardName());
18
+ function deviceQuality() {
19
+ const gpu = cardName(),
20
+ memory = memoryGB() ?? Infinity,
21
+ threads = cores() ?? desktopCores;
22
+ if (SOFTWARE.test(gpu) || memory <= smallMemory) return 'low';
23
+ if (handheld()) return memory <= phoneMemory ? 'low' : 'medium';
24
+ return threads < desktopCores || memory < desktopMemory || INTEGRATED.test(gpu) ? 'medium' : 'high';
25
+ }
26
+ return { deviceQuality, drawnInSoftware };
27
+ }