@bendyline/molen-client 0.0.11 → 0.0.13

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.
@@ -0,0 +1,862 @@
1
+ import * as THREE from "three";
2
+ //#region src/weather/noise.ts
3
+ function hash$1(x, y, z, seed) {
4
+ let h = Math.imul(x ^ seed, 374761393) ^ Math.imul(y, 668265263) ^ Math.imul(z, 2147483647);
5
+ h = Math.imul(h ^ h >>> 13, 1274126177);
6
+ return ((h ^ h >>> 16) >>> 0) / 4294967296;
7
+ }
8
+ const fade = (t) => t * t * t * (t * (t * 6 - 15) + 10);
9
+ const wrap = (i, period) => (i % period + period) % period;
10
+ const remap = (v, a, b) => Math.max(0, Math.min(1, (v - a) / (b - a)));
11
+ function lattice(px, py, pz, seed) {
12
+ const values = new Float32Array(px * py * pz);
13
+ for (let z = 0; z < pz; z++) for (let y = 0; y < py; y++) for (let x = 0; x < px; x++) values[(z * py + y) * px + x] = hash$1(x, y, z, seed);
14
+ return {
15
+ values,
16
+ px,
17
+ py,
18
+ pz
19
+ };
20
+ }
21
+ function bilinear(v, plane, x0, x1, y0, y1, fx, fy) {
22
+ const a = v[plane + y0 + x0], b = v[plane + y0 + x1], c = v[plane + y1 + x0], d = v[plane + y1 + x1];
23
+ const top = a + (b - a) * fx;
24
+ return top + (c + (d - c) * fx - top) * fy;
25
+ }
26
+ /** Value noise in 0–1 at (x, y, z) lattice units; z is ignored on a flat lattice. */
27
+ function value(l, x, y, z) {
28
+ const ix = Math.floor(x), iy = Math.floor(y);
29
+ const fx = fade(x - ix), fy = fade(y - iy);
30
+ const x0 = wrap(ix, l.px), x1 = wrap(ix + 1, l.px), y0 = wrap(iy, l.py) * l.px, y1 = wrap(iy + 1, l.py) * l.px;
31
+ if (l.pz === 1) return bilinear(l.values, 0, x0, x1, y0, y1, fx, fy);
32
+ const iz = Math.floor(z);
33
+ const area = l.px * l.py;
34
+ const near = bilinear(l.values, wrap(iz, l.pz) * area, x0, x1, y0, y1, fx, fy);
35
+ return near + (bilinear(l.values, wrap(iz + 1, l.pz) * area, x0, x1, y0, y1, fx, fy) - near) * fade(z - iz);
36
+ }
37
+ /** fBm of value noise, octave `o` on a lattice `2^o` times finer, normalized to 0–1. */
38
+ function octaves(base, count, seed, flat) {
39
+ return Array.from({ length: count }, (_, o) => {
40
+ const p = base * 2 ** o;
41
+ return lattice(p, p, flat ? 1 : p, seed + o * 17);
42
+ });
43
+ }
44
+ function fbm(layers, u, v, w) {
45
+ let sum = 0, total = 0, amplitude = 1;
46
+ for (const l of layers) {
47
+ sum += value(l, u * l.px, v * l.py, w * l.pz) * amplitude;
48
+ total += amplitude;
49
+ amplitude *= .5;
50
+ }
51
+ return sum / total;
52
+ }
53
+ function cells(count, seed, flat) {
54
+ const depth = flat ? 1 : count;
55
+ const points = new Float32Array(count * count * depth * 3);
56
+ for (let z = 0; z < depth; z++) for (let y = 0; y < count; y++) for (let x = 0; x < count; x++) {
57
+ const i = ((z * count + y) * count + x) * 3;
58
+ points[i] = x + hash$1(x, y, z, seed);
59
+ points[i + 1] = y + hash$1(x, y, z, seed + 1);
60
+ points[i + 2] = flat ? 0 : z + hash$1(x, y, z, seed + 2);
61
+ }
62
+ return {
63
+ points,
64
+ cells: count,
65
+ flat,
66
+ near: new Float32Array(81),
67
+ count: 0,
68
+ key: -1
69
+ };
70
+ }
71
+ /**
72
+ * Inverted Worley distance at (u, v, w) in 0–1 texture units: 1 on a feature point, 0 a cell
73
+ * away. Candidates are cached per cell, and fields are visited in texel order, so each cell's
74
+ * 27 neighbours are gathered once per row rather than per texel.
75
+ */
76
+ function worley(c, u, v, w) {
77
+ const n = c.cells;
78
+ const px = u * n, py = v * n, pz = c.flat ? 0 : w * n;
79
+ const cx = Math.floor(px), cy = Math.floor(py), cz = c.flat ? 0 : Math.floor(pz);
80
+ const key = (cz * n + cy) * n + cx;
81
+ if (key !== c.key) {
82
+ c.key = key;
83
+ let k = 0;
84
+ const zr = c.flat ? 0 : 1;
85
+ for (let dz = -zr; dz <= zr; dz++) for (let dy = -1; dy <= 1; dy++) for (let dx = -1; dx <= 1; dx++) {
86
+ const nx = cx + dx, ny = cy + dy, nz = cz + dz;
87
+ const wx = wrap(nx, n), wy = wrap(ny, n), wz = c.flat ? 0 : wrap(nz, n);
88
+ const i = ((wz * n + wy) * n + wx) * 3;
89
+ c.near[k++] = c.points[i] + (nx - wx);
90
+ c.near[k++] = c.points[i + 1] + (ny - wy);
91
+ c.near[k++] = c.points[i + 2] + (nz - wz);
92
+ }
93
+ c.count = k;
94
+ }
95
+ let best = 9;
96
+ const near = c.near;
97
+ for (let k = 0; k < c.count; k += 3) {
98
+ const ox = near[k] - px, oy = near[k + 1] - py, oz = near[k + 2] - pz;
99
+ const d = ox * ox + oy * oy + oz * oz;
100
+ if (d < best) best = d;
101
+ }
102
+ return 1 - Math.min(1, Math.sqrt(best));
103
+ }
104
+ /**
105
+ * Cloud body noise, one channel: value-noise fBm eroded by inverted Worley cells, the
106
+ * "Perlin-Worley" shape that gives cumulus their rounded, cauliflower billows.
107
+ */
108
+ function* shapeNoise(out) {
109
+ const n = 64;
110
+ const base = octaves(4, 3, 11, false);
111
+ const w = [
112
+ cells(4, 23, false),
113
+ cells(8, 29, false),
114
+ cells(16, 31, false)
115
+ ];
116
+ for (let z = 0; z < n; z++) {
117
+ const sw = (z + .5) / n;
118
+ for (let y = 0; y < n; y++) {
119
+ const sv = (y + .5) / n;
120
+ for (let x = 0; x < n; x++) {
121
+ const su = (x + .5) / n;
122
+ const cellular = worley(w[0], su, sv, sw) * .625 + worley(w[1], su, sv, sw) * .25 + worley(w[2], su, sv, sw) * .125;
123
+ out[(z * n + y) * n + x] = Math.round(remap(fbm(base, su, sv, sw), cellular - 1, 1) ** 1.2 * 255);
124
+ }
125
+ }
126
+ yield;
127
+ }
128
+ }
129
+ /** Finer Worley fBm, one channel, that wears wisps out of cloud edges. */
130
+ function* detailNoise(out) {
131
+ const n = 32;
132
+ const w = [
133
+ cells(4, 41, false),
134
+ cells(8, 43, false),
135
+ cells(16, 47, false)
136
+ ];
137
+ for (let z = 0; z < n; z++) {
138
+ const sw = (z + .5) / n;
139
+ for (let y = 0; y < n; y++) for (let x = 0; x < n; x++) {
140
+ const su = (x + .5) / n, sv = (y + .5) / n;
141
+ out[(z * n + y) * n + x] = Math.round((worley(w[0], su, sv, sw) * .625 + worley(w[1], su, sv, sw) * .25 + worley(w[2], su, sv, sw) * .125) * 255);
142
+ }
143
+ if (z % 8 === 7) yield;
144
+ }
145
+ }
146
+ /**
147
+ * The 2D weather map, RGBA: R where fair-weather cumulus form (separate cells), G how tall each
148
+ * column grows, B a tighter cellular field for stratocumulus, A broad storm cells.
149
+ */
150
+ function* weatherMap(out) {
151
+ const n = 256;
152
+ const cumulus = octaves(6, 5, 53, true);
153
+ const cumulusCells = cells(12, 59, true);
154
+ const height = octaves(4, 3, 61, true);
155
+ const strato = cells(24, 67, true);
156
+ const stratoBase = octaves(8, 4, 71, true);
157
+ const storms = cells(3, 73, true);
158
+ const stormBase = octaves(4, 4, 79, true);
159
+ for (let y = 0; y < n; y++) {
160
+ const v = (y + .5) / n;
161
+ for (let x = 0; x < n; x++) {
162
+ const u = (x + .5) / n;
163
+ const i = (y * n + x) * 4;
164
+ out[i] = Math.round(remap(fbm(cumulus, u, v, 0), 1 - worley(cumulusCells, u, v, 0) * 1.1, 1) * 255);
165
+ out[i + 1] = Math.round(fbm(height, u, v, 0) * 255);
166
+ out[i + 2] = Math.round((worley(strato, u, v, 0) * .55 + fbm(stratoBase, u, v, 0) * .45) * 255);
167
+ out[i + 3] = Math.round(remap(fbm(stormBase, u, v, 0), 1.05 - worley(storms, u, v, 0), 1) * 255);
168
+ }
169
+ if (y % 16 === 15) yield;
170
+ }
171
+ for (let channel = 0; channel < 4; channel++) {
172
+ const counts = new Float64Array(256);
173
+ for (let i = channel; i < out.length; i += 4) {
174
+ const v = out[i];
175
+ counts[v] = counts[v] + 1;
176
+ }
177
+ const level = new Uint8Array(256);
178
+ let below = 0;
179
+ for (let v = 0; v < 256; v++) {
180
+ const count = counts[v];
181
+ level[v] = Math.round((below + count / 2) / (n * n) * 255);
182
+ below += count;
183
+ }
184
+ for (let i = channel; i < out.length; i += 4) out[i] = level[out[i]];
185
+ }
186
+ }
187
+ /** Wispy, wind-combed cirrus, one channel: fBm stretched eight to one along +X. */
188
+ function* cirrusNoise(out) {
189
+ const n = 256;
190
+ const patches = [lattice(4, 4, 1, 83), lattice(8, 8, 1, 89)];
191
+ const strands = [lattice(4, 32, 1, 97), lattice(8, 64, 1, 101)];
192
+ const warp = lattice(8, 8, 1, 103);
193
+ for (let y = 0; y < n; y++) {
194
+ for (let x = 0; x < n; x++) {
195
+ const u = x / n;
196
+ const v = y / n + (value(warp, u * 8, y / n * 8, 0) * 2 - 1) * .04;
197
+ const patch = value(patches[0], u * 4, v * 4, 0) * .65 + value(patches[1], u * 8, v * 8, 0) * .35;
198
+ const strand = value(strands[0], u * 4, v * 32, 0) * .6 + value(strands[1], u * 8, v * 64, 0) * .4;
199
+ out[y * n + x] = Math.round(remap(patch * .6 + strand * .55, .42, .95) * 255);
200
+ }
201
+ if (y % 32 === 31) yield;
202
+ }
203
+ }
204
+ /** The page's cloud noise, filled in as `build` is given time. */
205
+ var CloudNoise = class {
206
+ weather = new Uint8Array(256 ** 2 * 4);
207
+ shape = new Uint8Array(64 ** 3);
208
+ detail = new Uint8Array(32 ** 3);
209
+ cirrus = new Uint8Array(256 ** 2);
210
+ ready = /* @__PURE__ */ new Set();
211
+ jobs = /* @__PURE__ */ new Map();
212
+ has(name) {
213
+ return this.ready.has(name);
214
+ }
215
+ /**
216
+ * Work on `wanted`, in order, for about `budgetMs` (Infinity finishes them). Returns whether all
217
+ * of them are ready.
218
+ */
219
+ build(wanted, budgetMs) {
220
+ const start = performance.now();
221
+ for (const name of wanted) {
222
+ if (this.ready.has(name)) continue;
223
+ let job = this.jobs.get(name);
224
+ if (!job) {
225
+ job = name === "weather" ? weatherMap(this.weather) : name === "shape" ? shapeNoise(this.shape) : name === "detail" ? detailNoise(this.detail) : cirrusNoise(this.cirrus);
226
+ this.jobs.set(name, job);
227
+ }
228
+ while (true) {
229
+ if (job.next().done) {
230
+ this.ready.add(name);
231
+ this.jobs.delete(name);
232
+ break;
233
+ }
234
+ if (performance.now() - start >= budgetMs) return false;
235
+ }
236
+ }
237
+ return true;
238
+ }
239
+ };
240
+ let shared;
241
+ /** One set per page: the fields depend on nothing but these constants. */
242
+ function cloudNoise() {
243
+ shared ??= new CloudNoise();
244
+ return shared;
245
+ }
246
+ //#endregion
247
+ //#region src/weather/clouds.ts
248
+ const QUALITY = {
249
+ low: {
250
+ steps: 10,
251
+ lightSteps: 2,
252
+ detail: false,
253
+ shadows: false
254
+ },
255
+ medium: {
256
+ steps: 20,
257
+ lightSteps: 3,
258
+ detail: false,
259
+ shadows: false
260
+ },
261
+ high: {
262
+ steps: 28,
263
+ lightSteps: 4,
264
+ detail: true,
265
+ shadows: true
266
+ },
267
+ ultra: {
268
+ steps: 44,
269
+ lightSteps: 5,
270
+ detail: true,
271
+ shadows: true
272
+ }
273
+ };
274
+ function cloudQualitySettings(quality) {
275
+ return QUALITY[quality];
276
+ }
277
+ const TYPES = {
278
+ cumulus: {
279
+ mix: [
280
+ 1,
281
+ 0,
282
+ 0,
283
+ 0
284
+ ],
285
+ frequency: 1,
286
+ topMin: .45,
287
+ baseRise: .06,
288
+ topSoft: .3,
289
+ anvil: 0,
290
+ relief: .35,
291
+ taper: .3,
292
+ shapeErosion: 1,
293
+ detailErosion: .3,
294
+ shapeTile: 1700
295
+ },
296
+ stratocumulus: {
297
+ mix: [
298
+ 0,
299
+ 0,
300
+ 1,
301
+ 0
302
+ ],
303
+ frequency: 1,
304
+ topMin: .7,
305
+ baseRise: .12,
306
+ topSoft: .5,
307
+ anvil: 0,
308
+ relief: .55,
309
+ taper: .12,
310
+ shapeErosion: .75,
311
+ detailErosion: .22,
312
+ shapeTile: 2e3
313
+ },
314
+ stratus: {
315
+ mix: [
316
+ .5,
317
+ 0,
318
+ .5,
319
+ 0
320
+ ],
321
+ frequency: .5,
322
+ topMin: .85,
323
+ baseRise: .2,
324
+ topSoft: .55,
325
+ anvil: 0,
326
+ relief: .3,
327
+ taper: .04,
328
+ shapeErosion: .3,
329
+ detailErosion: .1,
330
+ shapeTile: 4500
331
+ },
332
+ cumulonimbus: {
333
+ mix: [
334
+ 0,
335
+ 0,
336
+ 0,
337
+ 1
338
+ ],
339
+ frequency: 1,
340
+ topMin: .6,
341
+ baseRise: .04,
342
+ topSoft: .8,
343
+ anvil: 1,
344
+ relief: .25,
345
+ taper: .35,
346
+ shapeErosion: 1,
347
+ detailErosion: .28,
348
+ shapeTile: 6e3
349
+ }
350
+ };
351
+ /** Extinction per meter at full density and `clouds.density` 1. */
352
+ const EXTINCTION = .08;
353
+ /** Coverage edge width in weather-map units: how gradually a cloud thins out at its margin. */
354
+ const SOFTNESS = .15;
355
+ /** Longest stretch of a view ray marched through the slab, meters. */
356
+ const MAX_PATH = 3e4;
357
+ /** Farthest drawn cloud, meters (also bounded by the camera's far plane). */
358
+ const MAX_DISTANCE = 14e4;
359
+ /** Shell radii for views inside the slab, meters; the last range ends at the draw distance. */
360
+ const CLOUD_SHELLS = [
361
+ 3,
362
+ 30,
363
+ 250,
364
+ 2e3,
365
+ 12e3
366
+ ];
367
+ const fract = (x) => x - Math.floor(x);
368
+ const clamp = (x) => Math.max(0, Math.min(1, x));
369
+ function smooth(a, b, x) {
370
+ const t = clamp((x - a) / (b - a));
371
+ return t * t * (3 - 2 * t);
372
+ }
373
+ function hash(seed, salt) {
374
+ let h = Math.imul(seed ^ salt, 2654435761);
375
+ h = Math.imul(h ^ h >>> 15, 2246822519);
376
+ return ((h ^ h >>> 13) >>> 0) / 4294967296;
377
+ }
378
+ /**
379
+ * GPU textures over the page's shared noise arrays (see noise.ts). One set per renderer: the
380
+ * cloud-shadow uniforms of every lit shader keep the weather map for the renderer's lifetime.
381
+ */
382
+ var CloudTextures = class {
383
+ noise;
384
+ weather;
385
+ /**
386
+ * The weather map at a sixteenth of its texels (about 250 m each at the default scale), for
387
+ * cloud shadows: plain bilinear filtering of it gives their soft edges with one lookup.
388
+ */
389
+ shadow;
390
+ shape;
391
+ detail;
392
+ /** Cirrus RGBA; its alpha is rewritten for each coverage (see WeatherVisual). */
393
+ cirrus;
394
+ uploaded = /* @__PURE__ */ new Set();
395
+ constructor(noise) {
396
+ this.noise = noise;
397
+ this.weather = new THREE.DataTexture(noise.weather, 256, 256);
398
+ this.weather.wrapS = this.weather.wrapT = THREE.RepeatWrapping;
399
+ this.weather.magFilter = THREE.LinearFilter;
400
+ this.weather.minFilter = THREE.LinearMipmapLinearFilter;
401
+ this.weather.generateMipmaps = false;
402
+ this.weather.colorSpace = THREE.NoColorSpace;
403
+ this.weather.name = "molen:cloud-weather";
404
+ const shadowSize = 256 / 4;
405
+ this.shadow = new THREE.DataTexture(new Uint8Array(shadowSize ** 2 * 4), shadowSize, shadowSize);
406
+ this.shadow.wrapS = this.shadow.wrapT = THREE.RepeatWrapping;
407
+ this.shadow.magFilter = this.shadow.minFilter = THREE.LinearFilter;
408
+ this.shadow.generateMipmaps = false;
409
+ this.shadow.colorSpace = THREE.NoColorSpace;
410
+ this.shadow.name = "molen:cloud-shadow";
411
+ this.shadow.needsUpdate = true;
412
+ this.shape = volume(noise.shape, 64, "molen:cloud-shape");
413
+ this.detail = volume(noise.detail, 32, "molen:cloud-detail");
414
+ this.cirrus = new THREE.DataTexture(new Uint8Array(256 ** 2 * 4), 256, 256);
415
+ this.cirrus.wrapS = this.cirrus.wrapT = THREE.RepeatWrapping;
416
+ this.cirrus.magFilter = THREE.LinearFilter;
417
+ this.cirrus.minFilter = THREE.LinearMipmapLinearFilter;
418
+ this.cirrus.anisotropy = 8;
419
+ this.cirrus.generateMipmaps = true;
420
+ this.cirrus.colorSpace = THREE.LinearSRGBColorSpace;
421
+ this.cirrus.name = "molen:cirrus";
422
+ }
423
+ /** Upload each field once its noise is complete. Returns whether the deck can draw. */
424
+ sync() {
425
+ for (const [name, texture] of [
426
+ ["weather", this.weather],
427
+ ["shape", this.shape],
428
+ ["detail", this.detail]
429
+ ]) if (!this.uploaded.has(name) && this.noise.has(name)) {
430
+ if (texture === this.weather) {
431
+ const levels = mipChain(this.noise.weather, 256);
432
+ this.weather.mipmaps = levels;
433
+ this.shadow.image.data.set(levels[2]?.data);
434
+ this.shadow.needsUpdate = true;
435
+ }
436
+ texture.needsUpdate = true;
437
+ this.uploaded.add(name);
438
+ }
439
+ return this.uploaded.has("weather") && this.uploaded.has("shape") && this.uploaded.has("detail");
440
+ }
441
+ dispose() {
442
+ for (const texture of [
443
+ this.weather,
444
+ this.shadow,
445
+ this.shape,
446
+ this.detail,
447
+ this.cirrus
448
+ ]) texture.dispose();
449
+ }
450
+ };
451
+ /** Every level of a square RGBA8 texture, each a wrapping 2x2 box filter of the last. */
452
+ function mipChain(base, size) {
453
+ const levels = [{
454
+ data: base,
455
+ width: size,
456
+ height: size
457
+ }];
458
+ for (let from = base, n = size; n > 1; n /= 2) {
459
+ const m = n / 2;
460
+ const data = new Uint8Array(m * m * 4);
461
+ for (let y = 0; y < m; y++) for (let x = 0; x < m; x++) for (let c = 0; c < 4; c++) {
462
+ const at = (dx, dy) => from[((2 * y + dy) * n + 2 * x + dx) * 4 + c];
463
+ data[(y * m + x) * 4 + c] = at(0, 0) + at(1, 0) + at(0, 1) + at(1, 1) + 2 >> 2;
464
+ }
465
+ levels.push({
466
+ data,
467
+ width: m,
468
+ height: m
469
+ });
470
+ from = data;
471
+ }
472
+ return levels;
473
+ }
474
+ function volume(data, size, name) {
475
+ const texture = new THREE.Data3DTexture(data, size, size, size);
476
+ texture.format = THREE.RedFormat;
477
+ texture.type = THREE.UnsignedByteType;
478
+ texture.wrapS = texture.wrapT = texture.wrapR = THREE.RepeatWrapping;
479
+ texture.magFilter = texture.minFilter = THREE.LinearFilter;
480
+ texture.generateMipmaps = false;
481
+ texture.unpackAlignment = 1;
482
+ texture.colorSpace = THREE.NoColorSpace;
483
+ texture.name = name;
484
+ return texture;
485
+ }
486
+ /**
487
+ * The deck's uniform values, shared by reference with both backends' materials. Every
488
+ * position is in rendered (floating-origin) coordinates; offsets into the tiling textures are
489
+ * wrapped on the CPU in double precision, so the GPU never sees a large world coordinate.
490
+ */
491
+ var CloudUniforms = class {
492
+ /** Base, top and 1 / thickness (rendered Y), and the draw distance. */
493
+ slab = new THREE.Vector4();
494
+ /** Weather-map texels per meter, its wrapped UV offset, and coverage. */
495
+ field = new THREE.Vector4();
496
+ mix = new THREE.Vector4();
497
+ /** Shortest column, base rise, top softness, anvil. */
498
+ form = new THREE.Vector4();
499
+ /** Shape erosion, detail erosion (0 skips the detail lookup), coverage softness. */
500
+ erode = new THREE.Vector4();
501
+ /** Field relief, taper, and the blurred weather level and lift that spread an anvil. */
502
+ relief = new THREE.Vector4();
503
+ /** Billow noise repeats per meter and wrapped offset, in texture units. */
504
+ shape = new THREE.Vector4();
505
+ detail = new THREE.Vector4();
506
+ /** Steps, light steps, longest marched path (m), extinction per meter at full density. */
507
+ march = new THREE.Vector4();
508
+ /** Direction toward the light, and the farthest a light ray is marched, meters. */
509
+ sun = new THREE.Vector4();
510
+ sunColor = new THREE.Vector3();
511
+ ambientTop = new THREE.Vector3();
512
+ ambientBottom = new THREE.Vector3();
513
+ /** Forward and back scattering asymmetry, back-lobe weight, edge fade start (of distance). */
514
+ phase = new THREE.Vector4(.6, -.25, .3, .7);
515
+ /** The scene's fog for clouds: near, far, density and kind (0 none, 1 linear, 2 exp2). */
516
+ fog = new THREE.Vector4();
517
+ /** Fog color, and how far haze also fades a cloud out (see setFog). */
518
+ fogColor = new THREE.Vector4();
519
+ /** Shadow opacity of a fully cloudy column: -ln of the sunlight it lets through. */
520
+ shadowDepth = 0;
521
+ sunWarm = new THREE.Color("#fff3e2");
522
+ sunLow = new THREE.Color("#ff9a5c");
523
+ moon = new THREE.Color("#9fb3d6");
524
+ skyDay = new THREE.Color().setRGB(.42, .52, .7);
525
+ skyDusk = new THREE.Color().setRGB(.36, .28, .4);
526
+ skyNight = new THREE.Color().setRGB(.004, .006, .014);
527
+ groundDay = new THREE.Color().setRGB(.22, .24, .27);
528
+ groundNight = new THREE.Color().setRGB(.002, .003, .006);
529
+ scratch = new THREE.Color();
530
+ /**
531
+ * Fog the clouds as the scene's `fog` fogs everything else (thinner looking up). Haze also
532
+ * fades a cloud out by `fade` (0–1), so that a fully hazed cloud shows the sky's own horizon
533
+ * behind it, whichever color space the backend fogs in; a closed deck (`fade` 0) has no sky
534
+ * behind it to show and turns the fog's grey instead.
535
+ */
536
+ setFog(fog, fade) {
537
+ if (fog instanceof THREE.Fog) this.fog.set(fog.near, fog.far, 0, 1);
538
+ else if (fog instanceof THREE.FogExp2) this.fog.set(0, 0, fog.density, 2);
539
+ else this.fog.set(0, 0, 0, 0);
540
+ if (fog) this.fogColor.set(fog.color.r, fog.color.g, fog.color.b, fade);
541
+ }
542
+ /** Recompute for one frame. `far` bounds the draw distance. */
543
+ update(weather, seconds, origin, far, quality, sky) {
544
+ const { clouds, atmosphere, seed } = weather;
545
+ const type = TYPES[clouds.type];
546
+ const settings = QUALITY[quality];
547
+ const base = clouds.baseAltitude - origin[1];
548
+ this.slab.set(base, base + clouds.thickness, 1 / clouds.thickness, Math.min(MAX_DISTANCE, far));
549
+ const wind = atmosphere.windVelocity;
550
+ const sx = hash(seed, 1) * 1e5, sy = hash(seed, 2) * 1e5, sz = hash(seed, 3) * 1e5;
551
+ const ax = origin[0] - wind[0] * seconds + sx, az = origin[2] - wind[2] * seconds + sz;
552
+ const perMeter = type.frequency / clouds.scale;
553
+ this.field.set(perMeter, fract(ax * perMeter), fract(az * perMeter), clouds.coverage);
554
+ this.mix.fromArray(type.mix);
555
+ this.form.set(type.topMin, type.baseRise, type.topSoft, type.anvil);
556
+ this.erode.set(type.shapeErosion, settings.detail ? type.detailErosion : 0, SOFTNESS, 0);
557
+ this.relief.set(type.relief, type.taper, 4, .22);
558
+ const rise = seconds * .6 + sy;
559
+ const shapeTile = Math.max(type.shapeTile, clouds.thickness * .5);
560
+ const shape = 1 / shapeTile;
561
+ this.shape.set(shape, fract(ax * shape), fract((origin[1] - rise) * shape), fract(az * shape));
562
+ const detail = 1 / (shapeTile / 5.3);
563
+ this.detail.set(detail, fract(ax * detail), fract((origin[1] - rise * 1.6) * detail), fract(az * detail));
564
+ const depth = Math.min(2, Math.max(1, Math.sqrt(clouds.thickness / 900)));
565
+ this.march.set(Math.min(64, Math.round(settings.steps * depth)), settings.lightSteps, MAX_PATH, EXTINCTION * Math.max(.05, clouds.density));
566
+ this.shadowDepth = Math.min(1.6, .4 + clouds.density * clouds.thickness / 400);
567
+ const daylight = sky?.daylight ?? 1;
568
+ const sun = sky?.sunDirection ?? [
569
+ .3,
570
+ .8,
571
+ .2
572
+ ];
573
+ const moon = sky?.moonDirection;
574
+ const lightReach = Math.max(200, Math.min(4e3, clouds.thickness * 1.5));
575
+ const sunUp = smooth(-.1, .04, sun[1]);
576
+ const cover = clouds.coverage * clouds.density;
577
+ if (sunUp > 0 || !moon || moon[1] <= 0) {
578
+ this.sun.set(sun[0], sun[1], sun[2], lightReach);
579
+ this.scratch.copy(this.sunLow).lerp(this.sunWarm, smooth(.02, .35, sun[1]));
580
+ this.sunColor.set(this.scratch.r, this.scratch.g, this.scratch.b).multiplyScalar(3.2 * sunUp);
581
+ } else {
582
+ this.sun.set(moon[0], moon[1], moon[2], lightReach);
583
+ const lit = (sky?.moonIllumination ?? 0) * smooth(0, .15, moon[1]) * .12;
584
+ this.sunColor.set(this.moon.r, this.moon.g, this.moon.b).multiplyScalar(lit);
585
+ }
586
+ const dusk = (1 - smooth(0, .3, Math.abs(sun[1]))) * smooth(-.15, .05, sun[1]);
587
+ this.scratch.copy(this.skyNight).lerp(this.skyDay, daylight).lerp(this.skyDusk, dusk * .5);
588
+ const ambient = (.25 + daylight * .85) * (1 - cover * .3);
589
+ this.ambientTop.set(this.scratch.r, this.scratch.g, this.scratch.b).multiplyScalar(ambient);
590
+ this.scratch.copy(this.groundNight).lerp(this.groundDay, daylight);
591
+ this.ambientBottom.set(this.scratch.r, this.scratch.g, this.scratch.b).multiplyScalar(ambient * (1 - cover * .3));
592
+ }
593
+ };
594
+ /** Range attribute: where each proxy's march ends (m) and its share of the step count. */
595
+ const RANGE = "cloudRange";
596
+ /** A camera-centred square in the XZ plane, unit size, marching to the far side of the slab. */
597
+ function cloudDeckGeometry() {
598
+ const geometry = new THREE.PlaneGeometry(1, 1, 16, 16);
599
+ geometry.rotateX(-Math.PI / 2);
600
+ const range = new Float32Array(geometry.getAttribute("position").count * 2);
601
+ for (let i = 0; i < range.length; i += 2) range.set([1e9, 1], i);
602
+ geometry.setAttribute(RANGE, new THREE.BufferAttribute(range, 2));
603
+ return geometry;
604
+ }
605
+ /** Nested camera-centred spheres, far ones first so each draw blends over the one behind it. */
606
+ function cloudShellGeometry() {
607
+ const parts = [];
608
+ for (let i = CLOUD_SHELLS.length - 1; i >= 0; i--) {
609
+ const radius = CLOUD_SHELLS[i];
610
+ const sphere = new THREE.SphereGeometry(radius, 24, 12);
611
+ const count = sphere.getAttribute("position").count;
612
+ const range = new Float32Array(count * 2);
613
+ const end = CLOUD_SHELLS[i + 1] ?? 1e9;
614
+ for (let j = 0; j < range.length; j += 2) range.set([end, .4], j);
615
+ sphere.deleteAttribute("normal");
616
+ sphere.deleteAttribute("uv");
617
+ sphere.setAttribute(RANGE, new THREE.BufferAttribute(range, 2));
618
+ parts.push(sphere);
619
+ }
620
+ const positions = [];
621
+ const ranges = [];
622
+ const indices = [];
623
+ for (const part of parts) {
624
+ const offset = positions.length / 3;
625
+ positions.push(...part.getAttribute("position").array);
626
+ ranges.push(...part.getAttribute(RANGE).array);
627
+ for (const index of part.getIndex()?.array ?? []) indices.push(index + offset);
628
+ part.dispose();
629
+ }
630
+ const geometry = new THREE.BufferGeometry();
631
+ geometry.setAttribute("position", new THREE.Float32BufferAttribute(positions, 3));
632
+ geometry.setAttribute(RANGE, new THREE.Float32BufferAttribute(ranges, 2));
633
+ geometry.setIndex(indices);
634
+ return geometry;
635
+ }
636
+ /** Shared by both backends' shaders; kept as one string so the two stay in step. */
637
+ const GLSL_MODEL = `
638
+ uniform sampler2D cloudWeather;
639
+ uniform highp sampler3D cloudShape;
640
+ uniform highp sampler3D cloudDetail;
641
+ uniform vec4 cloudSlab;
642
+ uniform vec4 cloudField;
643
+ uniform vec4 cloudMix;
644
+ uniform vec4 cloudForm;
645
+ uniform vec4 cloudErode;
646
+ uniform vec4 cloudRelief;
647
+ uniform vec4 cloudShapeUv;
648
+ uniform vec4 cloudDetailUv;
649
+ uniform vec4 cloudMarch;
650
+ uniform vec4 cloudSun;
651
+ uniform vec3 cloudSunColor;
652
+ uniform vec3 cloudAmbientTop;
653
+ uniform vec3 cloudAmbientBottom;
654
+ uniform vec4 cloudPhase;
655
+ uniform vec4 cloudFog;
656
+ uniform vec4 cloudFogColor;
657
+
658
+ // Cloud density 0–1 at a rendered position; h receives the height fraction in the slab. A
659
+ // march step spanning many weather texels reads a blurred level (lod) and skips the billows,
660
+ // so a coarse step returns the average cloud over its length rather than a hit or a miss.
661
+ float cloudDensity(vec3 p, float lod, bool detailed, out float h) {
662
+ h = (p.y - cloudSlab.x) * cloudSlab.z;
663
+ if (h <= 0.0 || h >= 1.0) return 0.0;
664
+ vec2 uv = p.xz * cloudField.x + cloudField.yz;
665
+ vec4 w = textureLod(cloudWeather, uv, lod);
666
+ float field = dot(w, cloudMix);
667
+ // Wider margins for coarse steps, which then see a cloud's average rather than its edge.
668
+ float soft = cloudErode.z * (1.0 + lod * 0.6);
669
+ // Field values above this are cloud; coverage 1 puts it below 0, closing the layer.
670
+ float threshold = 1.0 - cloudField.w * (1.0 + soft);
671
+ // Each column's top: the height channel, lowered where the field is weak, so even a closed
672
+ // layer is lumpy and lets more light through where it is thin.
673
+ float hn = h / (mix(cloudForm.x, 1.0, w.g) * (1.0 - cloudRelief.x * (1.0 - field)));
674
+ if (hn >= 1.0) return 0.0;
675
+ // Anvils: near the top of a storm cell the cloud spreads well beyond its tower.
676
+ float spread = cloudForm.w * smoothstep(0.55, 0.9, hn);
677
+ if (spread > 0.0)
678
+ field = mix(field, max(field, dot(textureLod(cloudWeather, uv, lod + cloudRelief.z), cloudMix) + cloudRelief.w), spread);
679
+ // Clouds narrow toward their tops (domes, towers), but an anvil does not.
680
+ float cover = clamp((field - threshold - cloudRelief.y * hn * (1.0 - spread)) / soft, 0.0, 1.0);
681
+ if (cover <= 0.0) return 0.0;
682
+ float profile = smoothstep(0.0, cloudForm.y, hn) * (1.0 - smoothstep(cloudForm.z, 1.0, hn));
683
+ float body = cover * mix(profile, 1.0, spread * 0.5);
684
+ if (body <= 0.0) return 0.0;
685
+ // Flat bases: the billows carve the sides and tops, and the underside only a little.
686
+ float carve = cloudErode.x * mix(0.3, 1.0, smoothstep(0.0, 0.3, hn)) *
687
+ (1.0 - smoothstep(2.0, 4.5, lod));
688
+ float s = 1.0;
689
+ if (carve > 0.0) s = mix(1.0, textureLod(cloudShape, p * cloudShapeUv.x + cloudShapeUv.yzw, 0.0).r, carve);
690
+ float d = clamp((s - 1.0 + body) / max(body, 0.001), 0.0, 1.0) * body;
691
+ if (detailed && cloudErode.y > 0.0 && d > 0.0 && lod < 2.0) {
692
+ float n = textureLod(cloudDetail, p * cloudDetailUv.x + cloudDetailUv.yzw, 0.0).r;
693
+ // Wispy below, billowed above.
694
+ float wear = mix(n, 1.0 - n, clamp(hn * 3.0, 0.0, 1.0)) * cloudErode.y;
695
+ d = clamp((d - wear) / (1.0 - wear), 0.0, 1.0);
696
+ }
697
+ return d;
698
+ }
699
+
700
+ // Optical depth toward the light from p: doubling steps that together reach the edge of the
701
+ // layer along the light, or cloudSun.w meters if that is nearer.
702
+ float cloudLightDepth(vec3 p, float lod) {
703
+ float edge = cloudSun.y > 0.0 ? cloudSlab.y : cloudSlab.x;
704
+ float reach = abs(cloudSun.y) > 1e-4 ? min(cloudSun.w, (edge - p.y) / cloudSun.y) : cloudSun.w;
705
+ float len = reach / (exp2(cloudMarch.y) - 1.0);
706
+ float depth = 0.0;
707
+ float along = 0.0;
708
+ for (int k = 0; k < 6; k++) {
709
+ if (float(k) >= cloudMarch.y) break;
710
+ float h;
711
+ depth += cloudDensity(p + cloudSun.xyz * (along + len * 0.5), lod, false, h) * len;
712
+ along += len;
713
+ len *= 2.0;
714
+ }
715
+ return depth * cloudMarch.w;
716
+ }
717
+
718
+ float cloudPhaseHG(float c, float g) {
719
+ float g2 = g * g;
720
+ return (1.0 - g2) / pow(max(1.0 + g2 - 2.0 * g * c, 1e-4), 1.5);
721
+ }
722
+
723
+ // Premultiplied colour and opacity of the cloud along a ray from ro (unit rd), from the proxy
724
+ // at distance t0 to the end of its range; entry receives where the march starts.
725
+ vec4 cloudMarchRay(vec3 ro, vec3 rd, float t0, vec2 range, float jitter, out float entry) {
726
+ entry = t0;
727
+ float enter = 0.0;
728
+ float leave = 1e9;
729
+ if (abs(rd.y) > 1e-5) {
730
+ float tb = (cloudSlab.x - ro.y) / rd.y;
731
+ float tt = (cloudSlab.y - ro.y) / rd.y;
732
+ enter = max(min(tb, tt), 0.0);
733
+ leave = max(tb, tt);
734
+ } else if (ro.y <= cloudSlab.x || ro.y >= cloudSlab.y) {
735
+ return vec4(0.0);
736
+ }
737
+ float a = max(t0, enter);
738
+ entry = a;
739
+ float b = min(min(leave, range.x), min(cloudSlab.w, a + cloudMarch.z));
740
+ if (b <= a) return vec4(0.0);
741
+ float steps = max(2.0, floor(cloudMarch.x * range.y + 0.5));
742
+ // Through the layer, steps grow geometrically, the last up to 6 times the
743
+ // first: what shows of a cloud is its first optical depth, so the budget goes there. Along
744
+ // it (a ray grazing the layer toward the horizon) the next cloud may be anywhere, so they
745
+ // stay nearly even.
746
+ float span = mix(6.0, 1.5, smoothstep(2.0, 8.0, (b - a) * cloudSlab.z));
747
+ float growth = pow(span, 1.0 / steps);
748
+ float ds = (b - a) * (growth - 1.0) / (span - 1.0) * pow(growth, jitter);
749
+ float t = a + ds / pow(growth, jitter) * (pow(growth, jitter) - 1.0) / (growth - 1.0);
750
+ float c = dot(rd, cloudSun.xyz);
751
+ // Two lobes: a bright silver lining toward the light, a little back-scatter away from it.
752
+ float phase = mix(cloudPhaseHG(c, cloudPhase.x), cloudPhaseHG(c, cloudPhase.y), cloudPhase.z);
753
+ float transmittance = 1.0;
754
+ vec3 color = vec3(0.0);
755
+ for (int i = 0; i < 64; i++) {
756
+ if (float(i) >= steps || transmittance < 0.01) break;
757
+ vec3 p = ro + rd * t;
758
+ float stepLength = ds;
759
+ t += ds;
760
+ ds *= growth;
761
+ float lod = clamp(log2(stepLength * cloudField.x * 256.0), 0.0, 6.0);
762
+ float h;
763
+ float d = cloudDensity(p, lod, true, h);
764
+ if (d <= 0.0) continue;
765
+ float depth = cloudLightDepth(p, lod);
766
+ // Beer's law for light straight from the sun, and a diffusion term for light scattered on
767
+ // through the cloud, which falls off slowly: even a thick deck is grey underneath, not black.
768
+ float sunlight = exp(-depth) * phase + 0.3 / (1.0 + 0.08 * depth);
769
+ vec3 light = cloudSunColor * sunlight + mix(cloudAmbientBottom, cloudAmbientTop, h);
770
+ float stepTransmittance = exp(-d * cloudMarch.w * stepLength);
771
+ color += transmittance * (1.0 - stepTransmittance) * light;
772
+ transmittance *= stepTransmittance;
773
+ }
774
+ float alpha = (1.0 - transmittance) *
775
+ (1.0 - smoothstep(cloudSlab.w * cloudPhase.w, cloudSlab.w, a));
776
+ return vec4(color * (alpha / max(1.0 - transmittance, 1e-4)), alpha);
777
+ }
778
+
779
+ // Haze lies near the ground: a ray climbing to a cloud crosses less of it than its length.
780
+ float cloudFogFactor(float distance, vec3 rd) {
781
+ float depth = distance * mix(1.0, 0.35, smoothstep(0.05, 0.5, abs(rd.y)));
782
+ if (cloudFog.w < 0.5) return 0.0;
783
+ if (cloudFog.w < 1.5) return smoothstep(cloudFog.x, cloudFog.y, depth);
784
+ return 1.0 - exp(-cloudFog.z * cloudFog.z * depth * depth);
785
+ }
786
+ `;
787
+ const VERTEX = `
788
+ attribute vec2 cloudRange;
789
+ varying vec3 vCloudWorld;
790
+ varying vec2 vCloudRange;
791
+ #include <common>
792
+ #include <logdepthbuf_pars_vertex>
793
+ void main() {
794
+ vec4 world = modelMatrix * vec4(position, 1.0);
795
+ vCloudWorld = world.xyz;
796
+ vCloudRange = cloudRange;
797
+ vec4 mvPosition = viewMatrix * world;
798
+ gl_Position = projectionMatrix * mvPosition;
799
+ #include <logdepthbuf_vertex>
800
+ }
801
+ `;
802
+ const FRAGMENT = `
803
+ varying vec3 vCloudWorld;
804
+ varying vec2 vCloudRange;
805
+ #include <common>
806
+ #include <logdepthbuf_pars_fragment>
807
+ ${GLSL_MODEL}
808
+ void main() {
809
+ #include <logdepthbuf_fragment>
810
+ vec3 toProxy = vCloudWorld - cameraPosition;
811
+ float t0 = length(toProxy);
812
+ float jitter = fract(52.9829189 * fract(dot(gl_FragCoord.xy, vec2(0.06711056, 0.00583715))));
813
+ vec3 rd = toProxy / t0;
814
+ float entry;
815
+ vec4 cloud = cloudMarchRay(cameraPosition, rd, t0, vCloudRange, jitter, entry);
816
+ if (cloud.a < 0.002) discard;
817
+ gl_FragColor = vec4(cloud.rgb / cloud.a, cloud.a);
818
+ #include <tonemapping_fragment>
819
+ #include <colorspace_fragment>
820
+ // Where and how three fogs its own WebGL materials (after tone mapping, with the fog color in
821
+ // the output color space), so hazed clouds match hazed ground.
822
+ float hazed = cloudFogFactor(entry, rd);
823
+ gl_FragColor.rgb = mix(gl_FragColor.rgb, linearToOutputTexel(vec4(cloudFogColor.rgb, 1.0)).rgb, hazed);
824
+ gl_FragColor.a *= 1.0 - hazed * cloudFogColor.w;
825
+ }
826
+ `;
827
+ /** WebGL deck material reading `uniforms` and `textures` by reference. */
828
+ function createWebGlCloudMaterial(uniforms, textures) {
829
+ const material = new THREE.ShaderMaterial({
830
+ name: "molen:clouds",
831
+ uniforms: {
832
+ cloudWeather: { value: textures.weather },
833
+ cloudShape: { value: textures.shape },
834
+ cloudDetail: { value: textures.detail },
835
+ cloudSlab: { value: uniforms.slab },
836
+ cloudField: { value: uniforms.field },
837
+ cloudMix: { value: uniforms.mix },
838
+ cloudForm: { value: uniforms.form },
839
+ cloudErode: { value: uniforms.erode },
840
+ cloudRelief: { value: uniforms.relief },
841
+ cloudShapeUv: { value: uniforms.shape },
842
+ cloudDetailUv: { value: uniforms.detail },
843
+ cloudMarch: { value: uniforms.march },
844
+ cloudSun: { value: uniforms.sun },
845
+ cloudSunColor: { value: uniforms.sunColor },
846
+ cloudAmbientTop: { value: uniforms.ambientTop },
847
+ cloudAmbientBottom: { value: uniforms.ambientBottom },
848
+ cloudPhase: { value: uniforms.phase },
849
+ cloudFog: { value: uniforms.fog },
850
+ cloudFogColor: { value: uniforms.fogColor }
851
+ },
852
+ vertexShader: VERTEX,
853
+ fragmentShader: FRAGMENT,
854
+ transparent: true,
855
+ depthWrite: false,
856
+ side: THREE.DoubleSide
857
+ });
858
+ material.forceSinglePass = true;
859
+ return material;
860
+ }
861
+ //#endregion
862
+ export { cloudShellGeometry as a, cloudQualitySettings as i, CloudUniforms as n, createWebGlCloudMaterial as o, cloudDeckGeometry as r, cloudNoise as s, CloudTextures as t };