roamwright 0.1.1 → 0.4.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 (120) hide show
  1. package/CONTRIBUTING.md +39 -8
  2. package/README.md +74 -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/foliage.js +47 -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/index-parts.js +60 -0
  23. package/geometry/instance-visibility.js +41 -0
  24. package/geometry/instances.js +23 -0
  25. package/geometry/outline-grid.js +46 -0
  26. package/geometry/part-ranges.js +18 -0
  27. package/geometry/path-field.js +65 -0
  28. package/geometry/sagging-tube.js +58 -0
  29. package/geometry/sampled-surface.js +101 -0
  30. package/geometry/scatter-grid.js +32 -0
  31. package/geometry/sculpt.js +263 -0
  32. package/geometry/shore-grid.js +67 -0
  33. package/geometry/strata-field.js +339 -0
  34. package/geometry/strata-tiles.js +215 -0
  35. package/geometry/stream.js +94 -0
  36. package/geometry/terrain-chunks.js +304 -0
  37. package/geometry/terrain-extension.js +44 -0
  38. package/math/cell-edge.js +44 -0
  39. package/math/cloth-textures.js +83 -0
  40. package/math/cloud-textures.js +112 -0
  41. package/math/color.js +29 -0
  42. package/math/mountain-ranges.js +463 -0
  43. package/math/particle-noise.js +48 -0
  44. package/math/periodic.js +20 -0
  45. package/math/rock-texture.js +56 -0
  46. package/math/surface-textures.js +241 -0
  47. package/motion/arm-reach.js +74 -0
  48. package/motion/biped-stride.js +276 -0
  49. package/motion/crowd-alarms.js +127 -0
  50. package/motion/crowd-routine.js +183 -0
  51. package/motion/daily-clock.js +59 -0
  52. package/motion/ground-lookahead.js +29 -0
  53. package/motion/instance-sight.js +84 -0
  54. package/motion/quadruped.js +332 -0
  55. package/motion/weather.js +59 -0
  56. package/motion/wind.js +27 -0
  57. package/package.json +6 -4
  58. package/rendering/caster-motion.js +79 -0
  59. package/rendering/cell-lod.js +184 -0
  60. package/rendering/cloud-dome.js +371 -0
  61. package/rendering/cloud-field.js +83 -0
  62. package/rendering/compilation-schedule.js +34 -0
  63. package/rendering/contact-shadows.js +79 -0
  64. package/rendering/crowd-skinning.js +133 -0
  65. package/rendering/crust.js +28 -0
  66. package/rendering/daylight.js +50 -0
  67. package/rendering/far-shadow.js +186 -0
  68. package/rendering/flocks.js +323 -0
  69. package/rendering/garment-material.js +110 -0
  70. package/rendering/glow-lines.js +74 -0
  71. package/rendering/glow-shell.js +90 -0
  72. package/rendering/hair-strands.js +67 -0
  73. package/rendering/height-haze.js +129 -0
  74. package/rendering/height-probe.js +91 -0
  75. package/rendering/interior-mapping.js +19 -0
  76. package/rendering/light-budget.js +222 -0
  77. package/rendering/light-points.js +51 -0
  78. package/rendering/light-shafts.js +131 -0
  79. package/rendering/local-lights.js +28 -0
  80. package/rendering/low-light.js +13 -0
  81. package/rendering/material-lod.js +110 -0
  82. package/rendering/particle-emitters.js +223 -0
  83. package/rendering/particles.js +297 -0
  84. package/rendering/piece-batch.js +74 -20
  85. package/rendering/planar-reflection.js +175 -0
  86. package/rendering/post-shaders.js +21 -1
  87. package/rendering/post.js +4 -0
  88. package/rendering/rain-rings.js +22 -0
  89. package/rendering/road-surface.js +63 -0
  90. package/rendering/sea-shaders.js +230 -0
  91. package/rendering/shader-warmup.js +197 -0
  92. package/rendering/shadow-alignment.js +28 -0
  93. package/rendering/shadow-depth.js +129 -0
  94. package/rendering/sky-occlusion.js +187 -0
  95. package/rendering/sky.js +169 -0
  96. package/rendering/stage-lights.js +209 -0
  97. package/rendering/static-point-shadow.js +119 -0
  98. package/rendering/strata-material.js +93 -0
  99. package/rendering/stream-flow.js +36 -0
  100. package/rendering/surface-light.js +22 -0
  101. package/rendering/surface-projection.js +69 -0
  102. package/rendering/talus.js +26 -0
  103. package/rendering/terrain-rock.js +48 -0
  104. package/rendering/texture-fills.js +68 -0
  105. package/rendering/viewport.js +9 -0
  106. package/rendering/wakes.js +99 -0
  107. package/rendering/water-material.js +288 -0
  108. package/runtime/device-quality.js +27 -0
  109. package/runtime/diagnostic-log.js +80 -0
  110. package/runtime/events.js +14 -0
  111. package/runtime/first-use.js +3 -1
  112. package/runtime/frame-budget.js +49 -0
  113. package/runtime/frame-yield.js +14 -0
  114. package/runtime/gpu-timing.js +6 -3
  115. package/runtime/grid-cache.js +88 -0
  116. package/runtime/grid-rows.js +9 -0
  117. package/runtime/module-preload.js +15 -0
  118. package/runtime/search.js +69 -0
  119. package/runtime/spatial-audio.js +57 -0
  120. package/scripts/serve.py +26 -0
@@ -0,0 +1,187 @@
1
+ import * as THREE from 'three';
2
+
3
+ // Shared uniforms and shader hook for standard materials sampling a local sky visibility map.
4
+ export function createSkyOcclusionShader({minimum, underCover}) {
5
+ const uniforms = {
6
+ uSkyOpen: { value: null },
7
+ uSkyR: { value: new THREE.Vector4(0, 0, 0, 0) },
8
+ uSkyOn: { value: 0 },
9
+ };
10
+
11
+ const SKY_OPEN = /* glsl */ `
12
+ uniform sampler2D uSkyOpen; uniform vec4 uSkyR; uniform float uSkyOn;
13
+ float skyOpen(vec3 viewNormal) {
14
+ if (uSkyOn <= 0.0) return 1.0;
15
+ vec3 wp = cameraPosition - vViewPosition * mat3(viewMatrix), wn = viewNormal * mat3(viewMatrix);
16
+ vec2 uv = (wp.xz + wn.xz * 0.6 - uSkyR.xy) * vec2(uSkyR.z, -uSkyR.z), off = abs(uv - 0.5);
17
+ float reach = 1.0 - smoothstep(0.36, 0.48, max(off.x, off.y));
18
+ if (reach <= 0.0) return 1.0;
19
+ vec4 s = texture2D(uSkyOpen, uv);
20
+ float up = wp.y - uSkyR.w - s.g;
21
+ float open = up < -0.6 ? ${underCover.toFixed(2)} : mix(s.r, 1.0, clamp(up / max(s.b - s.g, 0.5), 0.0, 1.0));
22
+ return mix(1.0, ${minimum.toFixed(2)} + ${(1 - minimum).toFixed(2)} * open, uSkyOn * reach);
23
+ }
24
+ `;
25
+ function patch(sh, more = '') {
26
+ Object.assign(sh.uniforms, uniforms);
27
+ sh.fragmentShader = sh.fragmentShader
28
+ .replace('#include <common>', '#include <common>\n' + SKY_OPEN)
29
+ .replace(
30
+ '#include <lights_fragment_begin>',
31
+ `#include <lights_fragment_begin>\n#if defined( RE_IndirectDiffuse )\n ${more}\n irradiance *= skyOpen(geometryNormal);\n#endif`,
32
+ );
33
+ }
34
+ return {uniforms, patch};
35
+ }
36
+
37
+ // Two passes: record overhead caster height, then integrate the horizon in eight directions.
38
+ // The first map is available immediately. Subsequent height and horizon passes alternate frames.
39
+ export function createSkyOcclusion({renderer, scene, camera, uniforms, config, samples, ground, strength,
40
+ occludes = o => o.isMesh && o.castShadow, warmup}) {
41
+ const {compiled, warmStandIns, compilingNow} = warmup;
42
+ const heights = new THREE.WebGLRenderTarget(config.size, config.size, { minFilter: THREE.NearestFilter, magFilter: THREE.NearestFilter });
43
+ const openness = new THREE.WebGLRenderTarget(config.size, config.size, {
44
+ type: THREE.HalfFloatType,
45
+ minFilter: THREE.LinearFilter,
46
+ magFilter: THREE.LinearFilter,
47
+ depthBuffer: false,
48
+ });
49
+ uniforms.uSkyOpen.value = openness.texture;
50
+ const above = new THREE.OrthographicCamera(-config.half, config.half, config.half, -config.half, 1, config.depth);
51
+ above.rotation.set(-Math.PI / 2, 0, 0);
52
+ const depthOf = {
53
+ plain: new THREE.MeshDepthMaterial({ depthPacking: THREE.RGBADepthPacking, side: THREE.DoubleSide }),
54
+ instanced: new THREE.MeshDepthMaterial({ depthPacking: THREE.RGBADepthPacking, side: THREE.DoubleSide }),
55
+ tinted: new THREE.MeshDepthMaterial({ depthPacking: THREE.RGBADepthPacking, side: THREE.DoubleSide }),
56
+ };
57
+
58
+ const openPass = new THREE.Mesh(
59
+ new THREE.PlaneGeometry(2, 2),
60
+ new THREE.ShaderMaterial({
61
+ depthTest: false,
62
+ depthWrite: false,
63
+ uniforms: { tHeights: { value: heights.texture }, uTexel: { value: (2 * config.half) / config.size } },
64
+ vertexShader: /* glsl */ `varying vec2 vUv; void main() { vUv = uv; gl_Position = vec4(position.xy, 0.0, 1.0); }`,
65
+ fragmentShader: /* glsl */ `
66
+ #include <packing>
67
+ uniform sampler2D tHeights; uniform float uTexel; varying vec2 vUv;
68
+ float heightAt(vec2 uv) { return ${config.above.toFixed(1)} - mix(1.0, ${config.depth.toFixed(1)}, unpackRGBAToDepth(texture2D(tHeights, uv))); }
69
+ void main() {
70
+ float h0 = heightAt(vUv), sky = 0.0, tops = 0.0;
71
+ for (int i = 0; i < 8; i++) {
72
+ float a = float(i) * 0.7853982;
73
+ vec2 dir = vec2(cos(a), sin(a)) / (uTexel * ${config.size.toFixed(1)});
74
+ float rise = 0.0, top = h0;
75
+ ${samples.map(d => `{ float h = heightAt(vUv + dir * ${d.toFixed(2)}); rise = max(rise, (h - h0) / ${d.toFixed(2)}); top = max(top, h); }`).join('\n ')}
76
+ sky += 1.0 / (1.0 + rise * rise);
77
+ tops += top;
78
+ }
79
+ gl_FragColor = vec4(sky / 8.0, h0, tops / 8.0, 1.0);
80
+ }`,
81
+ }),
82
+ );
83
+ openPass.frustumCulled = false;
84
+ const passScene = new THREE.Scene().add(openPass),
85
+ passCamera = new THREE.OrthographicCamera(-1, 1, 1, -1, 0, 1);
86
+
87
+ const depthFor = o => (!occludes(o) ? null : o.isInstancedMesh ? (o.instanceColor ? depthOf.tinted : depthOf.instanced) : depthOf.plain);
88
+ const pending = Object.assign(new THREE.Vector4(), { due: false }),
89
+ hidden = [],
90
+ dressed = [],
91
+ worn = [],
92
+ _clear = new THREE.Color();
93
+ function drawHeights(atX, atZ) {
94
+ const texel = (2 * config.half) / config.size,
95
+ x = Math.round(atX / texel) * texel,
96
+ z = Math.round(atZ / texel) * texel,
97
+ y = ground(x, z);
98
+ above.position.set(x, y + config.above, z);
99
+ above.updateMatrixWorld();
100
+ const previousTarget = renderer.getRenderTarget(), face = renderer.getActiveCubeFace(), level = renderer.getActiveMipmapLevel();
101
+ const shadows = renderer.shadowMap.autoUpdate, clearAlpha = renderer.getClearAlpha(), fog = scene.fog;
102
+ renderer.getClearColor(_clear);
103
+ try {
104
+ scene.traverse(o => {
105
+ if (!o.visible || !(o.isMesh || o.isPoints || o.isLine || o.isSprite)) return;
106
+ const depth = depthFor(o);
107
+ if (!depth) {
108
+ o.visible = false;
109
+ hidden.push(o);
110
+ return;
111
+ }
112
+ dressed.push(o);
113
+ worn.push(o.material);
114
+ o.material = depth;
115
+ });
116
+ renderer.shadowMap.autoUpdate = false;
117
+ renderer.setRenderTarget(heights);
118
+ renderer.setClearColor(0xffffff, 1);
119
+ renderer.clear();
120
+ scene.fog = null;
121
+ renderer.render(scene, above);
122
+ } finally {
123
+ scene.fog = fog;
124
+ for (let i = 0; i < dressed.length; i++) dressed[i].material = worn[i];
125
+ for (let i = 0; i < hidden.length; i++) hidden[i].visible = true;
126
+ dressed.length = worn.length = hidden.length = 0;
127
+ renderer.setClearColor(_clear, clearAlpha);
128
+ renderer.setRenderTarget(previousTarget, face, level);
129
+ renderer.shadowMap.autoUpdate = shadows;
130
+ }
131
+ pending.set(x - config.half, z + config.half, 1 / (2 * config.half), y);
132
+ pending.due = true;
133
+ }
134
+ function workOutOpenness() {
135
+ const target = renderer.getRenderTarget(), face = renderer.getActiveCubeFace(), level = renderer.getActiveMipmapLevel();
136
+ renderer.setRenderTarget(openness);
137
+ try { renderer.render(passScene, passCamera); }
138
+ finally { renderer.setRenderTarget(target, face, level); }
139
+ uniforms.uSkyR.value.copy(pending);
140
+ pending.due = false;
141
+ }
142
+
143
+ function warm(root) {
144
+ const done = [warmStandIns(root, depthFor, above, heights, null)];
145
+ if (root === scene) {
146
+ const target = renderer.getRenderTarget(), face = renderer.getActiveCubeFace(), level = renderer.getActiveMipmapLevel();
147
+ renderer.setRenderTarget(openness);
148
+ try { done.push(compiled(passScene, passCamera)); }
149
+ finally { renderer.setRenderTarget(target, face, level); }
150
+ }
151
+ return Promise.all(done);
152
+ }
153
+
154
+ const drawn = { x: NaN, z: NaN, age: 0 };
155
+ function update(dt) {
156
+ const x = camera.position.x,
157
+ z = camera.position.z,
158
+ high = camera.position.y - ground(x, z),
159
+ on = strength(high);
160
+ uniforms.uSkyOn.value = on;
161
+ if (on <= 0 || compilingNow()) return;
162
+ if (pending.due) {
163
+ workOutOpenness();
164
+ return;
165
+ }
166
+ drawn.age += dt;
167
+ if (Math.hypot(x - drawn.x, z - drawn.z) < config.step && drawn.age < config.every) return;
168
+ const first = Number.isNaN(drawn.x);
169
+ drawHeights(x, z);
170
+ if (first) workOutOpenness();
171
+ drawn.x = x;
172
+ drawn.z = z;
173
+ drawn.age = 0;
174
+ }
175
+ function dispose() {
176
+ heights.dispose();
177
+ openness.dispose();
178
+ for (const depth of Object.values(depthOf)) depth.dispose();
179
+ openPass.geometry.dispose();
180
+ openPass.material.dispose();
181
+ if (uniforms.uSkyOpen.value === openness.texture) {
182
+ uniforms.uSkyOpen.value = null;
183
+ uniforms.uSkyOn.value = 0;
184
+ }
185
+ }
186
+ return {update, warm, dispose};
187
+ }
@@ -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
+ }