-
Notifications
You must be signed in to change notification settings - Fork 199
Expand file tree
/
Copy pathLandscapeEngine.js
More file actions
1681 lines (1497 loc) · 65.5 KB
/
Copy pathLandscapeEngine.js
File metadata and controls
1681 lines (1497 loc) · 65.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Standalone Landscape Engine for Three.js
* Generates procedural terraced canyons, biomes (desert/grassland/snow),
* streaming chunk terrain, water, and flora. Supports realistic and low-poly modes.
* Compatible with both global <script> tag inclusion and ES module bundlers.
*/
// Handle either global THREE or bundler-imported THREE
const THREE = (typeof window !== 'undefined' && window.THREE) ? window.THREE : null;
class LandscapeEngine {
/**
* @param {Object} config
* @param {THREE.Scene} config.scene - Target Three.js Scene
* @param {number} [config.seed=8472] - Random number seed for terrain/placement
* @param {string} [config.initialBiome='grassland'] - 'grassland', 'desert', or 'snow'
* @param {string} [config.styleMode='realistic'] - 'realistic' or 'lowpoly'
* @param {THREE.Color} [config.fogColorOut] - Color object updated with current fog color
* @param {Object|false} [config.airfield] - Optional runway/airfield terrain-carving configuration. Pass false to disable.
*/
constructor({ scene, seed = 8472, initialBiome = 'grassland', styleMode = 'realistic', fogColorOut = null, airfield = undefined, flood = null }) {
if (!THREE) {
throw new Error('LandscapeEngine: Three.js (THREE) must be loaded first.');
}
this.scene = scene;
this.seed = seed;
this.currentBiomeName = initialBiome;
this.styleMode = styleMode; // 'realistic' or 'lowpoly'
this.fogColorOut = fogColorOut;
// Clip bounds (world-space AABB). When enabled, fragments outside
// the box are discarded, producing clean flat faces at the boundary.
this._clipEnabled = false;
this._clipMin = new THREE.Vector3(-1e6, -1e6, -1e6);
this._clipMax = new THREE.Vector3( 1e6, 1e6, 1e6);
this._clipPlanes = [];
// Grid Settings
this.CHUNK_SIZE = 600;
this.CHUNK_RES = 60;
this.RENDER_RADIUS = 3; // 7x7 high-detail grid around target
this.FAR_CHUNK_SIZE = 1800;
this.FAR_CHUNK_RES = 90;
this.FAR_RADIUS = 4; // 9x9 far LOD grid
this.CHUNK_BUILD_BUDGET_NEAR = 2;
this.CHUNK_BUILD_BUDGET_FAR = 2;
this.BACKDROP_MODE = false;
this.airfield = this._makeAirfieldConfig(airfield);
this.AIRFIELD_FLAT_RADIUS = this.airfield.flatRadius;
this.AIRFIELD_FLAT_R2 = this.AIRFIELD_FLAT_RADIUS * this.AIRFIELD_FLAT_RADIUS;
this.AIRFIELD_SURFACE_Y = this.airfield.surfaceY;
// Flooded-archipelago mode (planet underlay): raise the waterline and gentle the
// terrain so most of the world is ocean with small islands poking through. `flood`
// is null for the home builder, so its terrain is unchanged.
this.flood = flood;
this.HEIGHT_SCALE = (flood && flood.heightScale != null) ? flood.heightScale : 1.0;
this.FREQ_SCALE = (flood && flood.freqScale != null) ? flood.freqScale : 1.0; // higher = smaller, more scattered islands
this.WATER_LEVEL = (flood && flood.waterLevel != null) ? flood.waterLevel : 4.0;
this.VOXEL = !!(flood && flood.voxel); // render ground as blocky voxel columns
this.VOXEL_RES = (flood && flood.voxelRes) || 24; // cells per near chunk (block = size/res)
this.FAR_VOXEL_RES = (flood && flood.farVoxelRes) || 22;
this.WATER_EXTENT = 24000;
this.WATER_RUNWAY_R = this.airfield.enabled ? this.airfield.waterRunwayRadius : 0;
// Active collections
this.chunks = new Map();
this.farChunks = new Map();
this.pendingChunkBuilds = [];
this.pendingChunkKeys = new Set();
this.pendingFarChunkBuilds = [];
this.pendingFarChunkKeys = new Set();
// Avoid rebuilding wanted chunk Sets every frame when the camera is still
// inside the same near/far chunk. Landscape views are otherwise CPU-bound
// on string/Set churn even after all chunks have streamed in.
this._streamSignature = '';
this._lastWaterStepX = NaN;
this._lastWaterStepZ = NaN;
// Configuration constants
this.SEED_OX = (this.seed * 17.31) % 1000;
this.SEED_OY = (this.seed * 23.79) % 1000;
// Biome Settings
this.BIOMES = {
desert: {
strata: [
{ h: -10, c: 0x3a2218 }, { h: 6, c: 0x5a3220 },
{ h: 22, c: 0x8a4d2e }, { h: 42, c: 0xb16b40 },
{ h: 60, c: 0xc78854 }, { h: 92, c: 0xd49868 },
{ h: 130, c: 0xdfb486 }, { h: 180, c: 0xe2c79c },
{ h: 260, c: 0xdcc7a4 },
],
cliffTint: 0x7a3c22,
fogColor: 0xe8b888,
skyTop: 0x4a7ca8, skyBottom: 0xffd4a0,
groundTint: 0x6a4830, ambient: 0x2a2520,
lowPolyAmbient: 0x3a3328,
sunColor: 0xfff1d4,
hasCactus: true, pineChance: 0.55, shrubChance: 0.85,
},
snow: {
strata: [
{ h: -10, c: 0x2a2a30 }, { h: 6, c: 0x404050 },
{ h: 22, c: 0x5a5f6a }, { h: 42, c: 0x8088a0 },
{ h: 60, c: 0xb4c0cf }, { h: 92, c: 0xd4dde6 },
{ h: 130, c: 0xe8edf2 }, { h: 180, c: 0xf6f8fb },
{ h: 260, c: 0xffffff },
],
cliffTint: 0x3a3a4a,
fogColor: 0xbfd0e0,
skyTop: 0x5a7ca8, skyBottom: 0xdae4ec,
groundTint: 0x5a6878, ambient: 0x2a303a,
lowPolyAmbient: 0x3a4250,
sunColor: 0xf4f2ec,
hasCactus: false, pineChance: 0.75, shrubChance: 0.25,
},
grassland: {
strata: [
{ h: -10, c: 0x2a3818 }, { h: 6, c: 0x3e5e22 },
{ h: 22, c: 0x548030 }, { h: 42, c: 0x6a9040 },
{ h: 60, c: 0x7e9448 }, { h: 92, c: 0x8c9458 },
{ h: 130, c: 0x90886a }, { h: 180, c: 0xa09c88 },
{ h: 260, c: 0xb4b0a0 },
],
cliffTint: 0x4a3820,
fogColor: 0xc4d8c0,
skyTop: 0x6090c0, skyBottom: 0xdee8c8,
groundTint: 0x405030, ambient: 0x2a3820,
lowPolyAmbient: 0x3a4828,
sunColor: 0xfff4d0,
hasCactus: false, pineChance: 0.7, shrubChance: 0.85,
},
};
this.currentBiome = { ...this.BIOMES[this.currentBiomeName] };
this.STRATA = this.currentBiome.strata.map(s => ({ h: s.h, c: new THREE.Color(s.c) }));
this.CLIFF_TINT = new THREE.Color(this.currentBiome.cliffTint);
if (flood) {
// Seabed below the raised waterline, a sandy beach band at the shore, then grass
// and highland above — voxel-poser's calm sea + scattered sandy isles.
const W = this.WATER_LEVEL;
// Bands chosen for the VOXEL-SNAPPED island heights: a low isle peaks near
// W+90 (snaps to ~W+100 at the near step, ~W+86 far), so the green meadow
// must span well past W+100 or the island tops fall into the tan highland
// band and read as sand. Sand is a thin shore ring (W+0..+18); everything
// above is green meadow — voxel-poser's calm sea + green-hearted sandy isles.
this.STRATA = [
{ h: W - 70, c: new THREE.Color(0x163a45) }, // deep seabed (dark teal)
{ h: W - 12, c: new THREE.Color(0x2f7a72) }, // shallow seabed (teal)
{ h: W + 0.5, c: new THREE.Color(0xe9dcae) }, // wet sand at the waterline
{ h: W + 18, c: new THREE.Color(0xdcc187) }, // dry sand beach
{ h: W + 32, c: new THREE.Color(0x6fa03f) }, // grass shore
{ h: W + 90, c: new THREE.Color(0x5c8a36) }, // meadow heart (green)
{ h: W + 230, c: new THREE.Color(0x6b9a40) }, // high meadow (still green; covers island tops)
{ h: W + 360, c: new THREE.Color(0x90886a) }, // highland (only very tall terrain)
].map(s => ({ h: s.h, c: s.c }));
}
// Sun direction vector
this.sunDir = new THREE.Vector3(0.58, 0.76, 0.28).normalize();
this._initSharedShaders();
this._initSharedGeometries();
this._initWater();
}
// --- Math Helpers ---
_smoothstep(t) { return t * t * (3 - 2 * t); }
_clamp01(t) { return Math.max(0, Math.min(1, t)); }
_smoothstepRange(edge0, edge1, x) {
const t = this._clamp01((x - edge0) / (edge1 - edge0));
return this._smoothstep(t);
}
_hash2(x, y) {
const s = Math.sin((x + this.SEED_OX) * 127.1 + (y + this.SEED_OY) * 311.7) * 43758.5453;
return s - Math.floor(s);
}
_srand(a, b, salt = 0) {
const s = Math.sin(a * 12.9898 + b * 78.233 + salt * 37.719 + this.seed * 0.1417) * 43758.5453;
return s - Math.floor(s);
}
_vnoise(x, y) {
const ix = Math.floor(x), iy = Math.floor(y);
const fx = x - ix, fy = y - iy;
const u = this._smoothstep(fx), v = this._smoothstep(fy);
const a = this._hash2(ix, iy);
const b = this._hash2(ix + 1, iy);
const c = this._hash2(ix, iy + 1);
const d = this._hash2(ix + 1, iy + 1);
return a * (1 - u) * (1 - v) + b * u * (1 - v) +
c * (1 - u) * v + d * u * v;
}
_fbm(x, y, oct) {
let v = 0, a = 1, f = 1, tot = 0;
for (let i = 0; i < oct; i++) {
v += a * this._vnoise(x * f, y * f);
tot += a;
a *= 0.5; f *= 2;
}
return v / tot;
}
_makeAirfieldConfig(airfield) {
const defaults = {
enabled: true,
flatRadius: 230,
surfaceY: 0.08,
waterRunwayRadius: 420,
runwayEllipseScaleX: 1.45,
runwayEllipseScaleZ: 0.22,
runwayMaskInner: 220,
runwayMaskOuter: 560,
corridorXInner: 135,
corridorXOuter: 360,
corridorZInner: 260,
corridorZOuter: 1850,
corridorStrength: 0.96,
corridorCut: 22,
basinNoiseScale: 0.006,
basinNoiseOctaves: 2,
basinRipple: 5.5,
padFlatten: 0.998,
padCut: 3.5,
pads: [
{ x: 0, z: 0, xInner: 18, xOuter: 42, zInner: 215, zOuter: 285 },
{ x: 34, z: 150, xInner: 8, xOuter: 74, zInner: 92, zOuter: 210 },
{ x: 17, z: 116, xInner: 6, xOuter: 18, zInner: 62, zOuter: 168 },
],
};
if (airfield === false) {
return { ...defaults, enabled: false, pads: [] };
}
if (!airfield) {
return { ...defaults, pads: defaults.pads.map(p => ({ ...p })) };
}
return {
...defaults,
...airfield,
pads: Array.isArray(airfield.pads)
? airfield.pads.map(p => ({ ...p }))
: defaults.pads.map(p => ({ ...p })),
};
}
_airfieldMasks(x, z) {
const a = this.airfield;
if (!a || !a.enabled) {
return { runwayMask: 1, approachCorridor: 0, airfieldPad: 0 };
}
const runwayEllipse = Math.hypot(x * a.runwayEllipseScaleX, z * a.runwayEllipseScaleZ);
const runwayMask = this._smoothstepRange(a.runwayMaskInner, a.runwayMaskOuter, runwayEllipse);
const corridorX = 1 - this._smoothstepRange(a.corridorXInner, a.corridorXOuter, Math.abs(x));
const corridorZ = 1 - this._smoothstepRange(a.corridorZInner, a.corridorZOuter, Math.abs(z));
const approachCorridor = this._clamp01(corridorX * corridorZ);
let pad = 0;
for (const p of a.pads) {
const padX = 1 - this._smoothstepRange(p.xInner, p.xOuter, Math.abs(x - (p.x || 0)));
const padZ = 1 - this._smoothstepRange(p.zInner, p.zOuter, Math.abs(z - (p.z || 0)));
pad = Math.max(pad, padX * padZ);
}
return { runwayMask, approachCorridor, airfieldPad: this._clamp01(pad) };
}
/**
* Evaluates the absolute height of the canyon terrain at grid coordinates.
* @param {number} x - X Coordinate
* @param {number} z - Z Coordinate
* @returns {number} Height
*/
getHeight(x, z) {
const airfield = this.airfield;
const airfieldMasks = this._airfieldMasks(x, z);
let h = 0, amp = 1, freq = 0.0018 * this.FREQ_SCALE, tot = 0;
for (let i = 0; i < 5; i++) {
const n = this._vnoise(x * freq, z * freq);
h += amp * (1 - Math.abs(n * 2 - 1)); // ridged
tot += amp;
amp *= 0.5; freq *= 2;
}
h = Math.pow(h / tot, 2.4) * 260;
// Large-scale valleys
h += (this._fbm(x * 0.0006 * this.FREQ_SCALE, z * 0.0006 * this.FREQ_SCALE, 3) - 0.4) * 120;
h = Math.max(0, h);
// Terracing mesas
const step = 28;
const t = h / step;
const base = Math.floor(t);
const frac = t - base;
const tr = frac < 0.72 ? 0 : this._smoothstep((frac - 0.72) / 0.28);
h = (base + tr) * step;
// Carve runway corridor
h *= Math.max(airfieldMasks.runwayMask, 1 - airfieldMasks.approachCorridor * airfield.corridorStrength);
h = Math.max(0, h - airfieldMasks.approachCorridor * airfield.corridorCut);
// Airstrip basin details
const basinRipple = (1 - airfieldMasks.runwayMask)
* (this._fbm(x * airfield.basinNoiseScale, z * airfield.basinNoiseScale, airfield.basinNoiseOctaves) - 0.5)
* airfield.basinRipple;
h = Math.max(0, h + basinRipple);
// Airfield flatness exclusion
h *= 1 - airfieldMasks.airfieldPad * airfield.padFlatten;
h = Math.max(0, h - airfieldMasks.airfieldPad * airfield.padCut);
return h * this.HEIGHT_SCALE;
}
_strataColor(h, out) {
for (let i = 0; i < this.STRATA.length - 1; i++) {
if (h <= this.STRATA[i + 1].h) {
const t = (h - this.STRATA[i].h) / (this.STRATA[i + 1].h - this.STRATA[i].h);
out.copy(this.STRATA[i].c).lerp(this.STRATA[i + 1].c, Math.max(0, Math.min(1, t)));
return out;
}
}
out.copy(this.STRATA[this.STRATA.length - 1].c);
return out;
}
// --- Shaders Initialization ---
_initSharedShaders() {
this.SAND_VS = `
attribute vec3 color;
varying vec3 vColor;
varying vec3 vWorldPos;
varying vec3 vNormal;
void main() {
vColor = color;
vec4 wp = modelMatrix * vec4(position, 1.0);
vWorldPos = wp.xyz;
vNormal = normalize(normalMatrix * normal);
gl_Position = projectionMatrix * viewMatrix * wp;
}
`;
this.SAND_FS = `
precision highp float;
uniform vec3 sunDir;
uniform vec3 sunColor;
uniform vec3 ambientColor;
uniform vec3 skyTint;
uniform vec3 groundTint;
uniform vec3 fogColor;
uniform float fogNear;
uniform float fogFar;
uniform float hazeStrength;
uniform float hazeExponent;
uniform float clipEnabled;
uniform vec3 clipMin;
uniform vec3 clipMax;
uniform float planetDistanceEffect;
uniform vec3 planetDistanceColor;
uniform float planetDistanceDesaturate;
uniform float planetDistanceDim;
varying vec3 vColor;
varying vec3 vWorldPos;
varying vec3 vNormal;
float hash21(vec2 p) {
p = fract(p * vec2(123.34, 456.21));
p += dot(p, p + 45.32);
return fract(p.x * p.y);
}
float vnoise(vec2 p) {
vec2 i = floor(p);
vec2 f = fract(p);
f = f*f*(3.0-2.0*f);
return mix(
mix(hash21(i), hash21(i + vec2(1.0, 0.0)), f.x),
mix(hash21(i + vec2(0.0, 1.0)), hash21(i + vec2(1.0, 1.0)), f.x),
f.y
);
}
void main() {
// Clip bounds discard. The boundary is filled by opaque cut-cap
// geometry; do not fade the terrain/water to blue fog at the edge.
if (clipEnabled > 0.5) {
float dx1 = vWorldPos.x - clipMin.x;
float dx2 = clipMax.x - vWorldPos.x;
float dz1 = vWorldPos.z - clipMin.z;
float dz2 = clipMax.z - vWorldPos.z;
float minDist = min(min(dx1, dx2), min(dz1, dz2));
if (minDist < 0.0) {
discard;
}
}
vec3 N = normalize(vNormal);
vec2 uv = vWorldPos.xz;
float r1 = cos(uv.x * 0.55 + uv.y * 0.21);
float r2 = cos(uv.y * 0.62 - uv.x * 0.27 + 1.7);
float r3 = cos((uv.x + uv.y) * 0.13);
float r4 = cos(uv.x * 1.8 + uv.y * 0.6) * 0.3;
float r5 = cos(uv.y * 1.6 - uv.x * 1.2 + 0.5) * 0.3;
vec3 rippleN = normalize(vec3(
r1 * 0.06 + r3 * 0.02 + r4 * 0.025,
1.0,
r2 * 0.06 + r3 * 0.02 + r5 * 0.025
));
float flatness = smoothstep(0.55, 0.92, N.y);
vec3 perturbed = normalize(mix(N, normalize(N + (rippleN - vec3(0.0, 1.0, 0.0)) * 0.7), flatness));
vec3 L = normalize(sunDir);
float rawNdotL = dot(perturbed, L);
float NdotL = max(rawNdotL, 0.0);
float sunFacing = smoothstep(-0.18, 0.78, rawNdotL);
float hemi = perturbed.y * 0.5 + 0.5;
vec3 hemiCol = mix(groundTint, skyTint, hemi);
vec3 diffuse = vColor * (NdotL * sunColor + hemiCol * 0.45 + ambientColor);
vec3 V = normalize(cameraPosition - vWorldPos);
vec3 H = normalize(L + V);
float NdotH = max(dot(perturbed, H), 0.0);
float spec = pow(NdotH, 22.0) * 0.18 * flatness;
float sparkleNoise = vnoise(uv * 55.0);
float sparkleMask = smoothstep(0.79, 0.93, sparkleNoise) * pow(NdotH, 90.0) * flatness;
vec3 sparkle = sunColor * sparkleMask * 5.0;
float backLight = max(dot(-perturbed, L), 0.0);
vec3 backScatter = vColor * sunColor * backLight * 0.07;
float rim = 1.0 - max(dot(N, V), 0.0);
rim = pow(rim, 2.5) * 0.15;
vec3 rimCol = mix(vColor, fogColor, 0.6) * rim;
vec3 color = diffuse + spec * sunColor + sparkle + backScatter + rimCol;
color *= mix(vec3(0.72, 0.78, 0.88), vec3(1.03, 1.0, 0.97), sunFacing);
float dist = length(vWorldPos - cameraPosition);
float fogF = clamp((dist - fogNear) / (fogFar - fogNear), 0.0, 1.0);
float horizon = pow(clamp(1.0 - abs(V.y), 0.0, 1.0), hazeExponent);
float haze = clamp(fogF * (0.86 + horizon * hazeStrength), 0.0, 1.0);
vec3 hazeColor = mix(fogColor, skyTint, 0.38 + horizon * 0.22);
color = mix(color, hazeColor, haze);
// No clip-edge haze fade; cut caps fill the boundary.
if (planetDistanceEffect > 0.001) {
float distMix = clamp(planetDistanceEffect, 0.0, 1.0);
float grey = dot(color, vec3(0.299, 0.587, 0.114));
color = mix(color, vec3(grey), clamp(planetDistanceDesaturate, 0.0, 1.0) * distMix);
color = mix(color, planetDistanceColor, distMix);
color *= mix(1.0, planetDistanceDim, distMix);
}
gl_FragColor = vec4(color, 1.0);
}
`;
this.LOWPOLY_FS = `
precision highp float;
uniform vec3 sunDir;
uniform vec3 sunColor;
uniform vec3 ambientColor;
uniform vec3 skyTint;
uniform vec3 groundTint;
uniform vec3 fogColor;
uniform float fogNear;
uniform float fogFar;
uniform float hazeStrength;
uniform float hazeExponent;
uniform float clipEnabled;
uniform vec3 clipMin;
uniform vec3 clipMax;
uniform float planetDistanceEffect;
uniform vec3 planetDistanceColor;
uniform float planetDistanceDesaturate;
uniform float planetDistanceDim;
varying vec3 vColor;
varying vec3 vWorldPos;
varying vec3 vNormal;
void main() {
// Clip bounds discard. The boundary is filled by opaque cut-cap
// geometry; do not fade the terrain/water to blue fog at the edge.
if (clipEnabled > 0.5) {
float dx1 = vWorldPos.x - clipMin.x;
float dx2 = clipMax.x - vWorldPos.x;
float dz1 = vWorldPos.z - clipMin.z;
float dz2 = clipMax.z - vWorldPos.z;
float minDist = min(min(dx1, dx2), min(dz1, dz2));
if (minDist < 0.0) {
discard;
}
}
vec3 dx = dFdx(vWorldPos);
vec3 dy = dFdy(vWorldPos);
vec3 N = normalize(cross(dx, dy));
if (N.y < 0.0) N = -N;
vec3 L = normalize(sunDir);
float rawNdotL = dot(N, L);
float NdotL = max(rawNdotL, 0.0);
vec3 V = normalize(cameraPosition - vWorldPos);
vec3 H = normalize(L + V);
float band;
if (NdotL > 0.72) band = 1.00;
else if (NdotL > 0.38) band = 0.86;
else if (NdotL > 0.02) band = 0.74;
else band = 0.62;
vec3 c = vColor * 1.04;
c = floor(c * 12.0) / 12.0;
float lum = dot(c, vec3(0.299, 0.587, 0.114));
c = mix(vec3(lum), c, 1.08);
float hemi = clamp(N.y * 0.5 + 0.5, 0.0, 1.0);
vec3 hemiCol = mix(groundTint, skyTint, hemi);
float sunFacing = smoothstep(-0.18, 0.78, rawNdotL);
float backLight = max(dot(-N, L), 0.0);
float spec = pow(max(dot(N, H), 0.0), 18.0) * 0.08;
float rim = pow(1.0 - max(dot(N, V), 0.0), 2.5) * 0.12;
vec3 rimCol = mix(c, fogColor, 0.55) * rim;
vec3 shadowCol = mix(groundTint, skyTint, 0.70 + hemi * 0.24);
vec3 litCol = band * sunColor + hemiCol * 0.52 + ambientColor;
vec3 shadeCol = shadowCol * (0.56 + hemi * 0.14) + ambientColor * 0.56;
vec3 color = c * mix(shadeCol, litCol, smoothstep(-0.12, 0.34, rawNdotL));
color += spec * sunColor;
color += c * sunColor * backLight * 0.08;
color += rimCol;
color *= mix(vec3(0.84, 0.88, 0.95), vec3(1.04, 1.00, 0.96), sunFacing);
float dist = length(vWorldPos - cameraPosition);
float fogF = clamp((dist - fogNear) / (fogFar - fogNear), 0.0, 1.0);
float horizon = pow(clamp(1.0 - abs(V.y), 0.0, 1.0), hazeExponent);
float haze = clamp(fogF * (0.96 + horizon * (hazeStrength + 0.18)), 0.0, 1.0);
vec3 hazeColor = mix(fogColor, skyTint, 0.66 + horizon * 0.16);
color = mix(color, hazeColor, haze);
// No clip-edge haze fade; cut caps fill the boundary.
if (planetDistanceEffect > 0.001) {
float distMix = clamp(planetDistanceEffect, 0.0, 1.0);
float grey = dot(color, vec3(0.299, 0.587, 0.114));
color = mix(color, vec3(grey), clamp(planetDistanceDesaturate, 0.0, 1.0) * distMix);
color = mix(color, planetDistanceColor, distMix);
color *= mix(1.0, planetDistanceDim, distMix);
}
gl_FragColor = vec4(color, 1.0);
}
`;
this.sandMat = new THREE.ShaderMaterial({
uniforms: {
sunDir: { value: this.sunDir.clone() },
sunColor: { value: new THREE.Color(this.currentBiome.sunColor) },
ambientColor: { value: new THREE.Color(this.currentBiome.ambient) },
skyTint: { value: new THREE.Color(this.currentBiome.skyTop) },
groundTint: { value: new THREE.Color(this.currentBiome.groundTint) },
fogColor: { value: new THREE.Color(this.currentBiome.fogColor) },
fogNear: { value: 360 },
fogFar: { value: 6200 },
hazeStrength: { value: 0.92 },
hazeExponent: { value: 1.55 },
clipEnabled: { value: 0.0 },
clipMin: { value: this._clipMin },
clipMax: { value: this._clipMax },
planetDistanceEffect: { value: 0.0 },
planetDistanceColor: { value: new THREE.Color(this.currentBiome.fogColor) },
planetDistanceDesaturate: { value: 0.0 },
planetDistanceDim: { value: 1.0 },
},
vertexShader: this.SAND_VS,
fragmentShader: this.SAND_FS,
});
this.sandMatLowPoly = new THREE.ShaderMaterial({
uniforms: {
sunDir: { value: this.sunDir.clone() },
sunColor: { value: new THREE.Color(this.currentBiome.sunColor) },
ambientColor: { value: new THREE.Color(this.currentBiome.lowPolyAmbient) },
skyTint: { value: new THREE.Color(this.currentBiome.skyTop) },
groundTint: { value: new THREE.Color(this.currentBiome.groundTint) },
fogColor: { value: new THREE.Color(this.currentBiome.fogColor) },
fogNear: { value: 500 },
fogFar: { value: 6100 },
hazeStrength: { value: 0.98 },
hazeExponent: { value: 1.30 },
clipEnabled: { value: 0.0 },
clipMin: { value: this._clipMin },
clipMax: { value: this._clipMax },
planetDistanceEffect: { value: 0.0 },
planetDistanceColor: { value: new THREE.Color(this.currentBiome.fogColor) },
planetDistanceDesaturate: { value: 0.0 },
planetDistanceDim: { value: 1.0 },
},
vertexShader: this.SAND_VS,
fragmentShader: this.LOWPOLY_FS,
extensions: { derivatives: true },
});
}
// --- Geometry Instancing Helpers ---
_initSharedGeometries() {
this.rockGeo = (() => {
const g = new THREE.DodecahedronGeometry(1, 0);
const p = g.attributes.position;
for (let i = 0; i < p.count; i++) {
const x = p.getX(i), y = p.getY(i), z = p.getZ(i);
const n = Math.sin(x * 4.7 + this.seed) * Math.cos(y * 3.1) * Math.sin(z * 5.3);
p.setXYZ(i, x * (1 + n * 0.28), y * (1 + n * 0.18), z * (1 + n * 0.22));
}
g.computeVertexNormals();
return g;
})();
this.rockMat = new THREE.MeshLambertMaterial({ color: 0x9c6840 });
this.rockMatLowPoly = new THREE.MeshPhongMaterial({ color: 0x9c6840, flatShading: true, shininess: 0 });
this.pineGeo = this._buildPineGeo();
this.cactusGeo = this._buildCactusGeo();
this.shrubGeo = this._buildShrubGeo();
this.boulderGeo = this._buildBoulderGeo();
const localBox = new THREE.Box3(
new THREE.Vector3(-this.CHUNK_SIZE / 2 - 10, -100, -this.CHUNK_SIZE / 2 - 10),
new THREE.Vector3(this.CHUNK_SIZE / 2 + 10, 500, this.CHUNK_SIZE / 2 + 10)
);
const localSphere = localBox.getBoundingSphere(new THREE.Sphere());
for (const geo of [this.rockGeo, this.pineGeo, this.cactusGeo, this.shrubGeo, this.boulderGeo]) {
geo.boundingBox = localBox.clone();
geo.boundingSphere = localSphere.clone();
}
this.floraMat = new THREE.MeshLambertMaterial({ vertexColors: true });
this.floraMatLow = new THREE.MeshPhongMaterial({ vertexColors: true, flatShading: true, shininess: 0 });
// TinyWorld integration: use a built-in lit material only for the
// realistic visible terrain path so Three.js can apply native shadow maps
// and scene fog. Low-poly mode intentionally keeps the custom cel shader.
this.terrainMat = new THREE.MeshLambertMaterial({ vertexColors: true, fog: true });
this.terrainMat.userData = {
clipEnabled: { value: 0.0 },
planetFogEnabled: { value: 0.0 },
planetFogColor: { value: new THREE.Color(this.currentBiome.fogColor) },
planetFogNear: { value: 360 },
planetFogFar: { value: 6200 },
planetFogStrength: { value: 0.0 },
planetHazeExponent: { value: 1.45 },
planetDistanceEffect: { value: 0.0 },
planetDistanceColor: { value: new THREE.Color(this.currentBiome.fogColor) },
planetDistanceDesaturate: { value: 0.0 },
planetDistanceDim: { value: 1.0 }
};
this.terrainMat.onBeforeCompile = (shader) => {
const planetFog = this._ensurePlanetFogUniforms();
shader.uniforms.clipMin = { value: this._clipMin };
shader.uniforms.clipMax = { value: this._clipMax };
shader.uniforms.clipEnabled = this.terrainMat.userData.clipEnabled;
shader.uniforms.planetFogEnabled = planetFog.planetFogEnabled;
shader.uniforms.planetFogColor = planetFog.planetFogColor;
shader.uniforms.planetFogNear = planetFog.planetFogNear;
shader.uniforms.planetFogFar = planetFog.planetFogFar;
shader.uniforms.planetFogStrength = planetFog.planetFogStrength;
shader.uniforms.planetHazeExponent = planetFog.planetHazeExponent;
shader.uniforms.planetDistanceEffect = planetFog.planetDistanceEffect;
shader.uniforms.planetDistanceColor = planetFog.planetDistanceColor;
shader.uniforms.planetDistanceDesaturate = planetFog.planetDistanceDesaturate;
shader.uniforms.planetDistanceDim = planetFog.planetDistanceDim;
shader.vertexShader = shader.vertexShader.replace(
'#include <common>',
`#include <common>
varying vec3 vWorldPositionCustom;`
);
shader.vertexShader = shader.vertexShader.replace(
'#include <worldpos_vertex>',
`#include <worldpos_vertex>
vWorldPositionCustom = (modelMatrix * vec4(transformed, 1.0)).xyz;`
);
shader.fragmentShader = shader.fragmentShader.replace(
'#include <common>',
`#include <common>
uniform vec3 clipMin;
uniform vec3 clipMax;
uniform float clipEnabled;
uniform float planetFogEnabled;
uniform vec3 planetFogColor;
uniform float planetFogNear;
uniform float planetFogFar;
uniform float planetFogStrength;
uniform float planetHazeExponent;
uniform float planetDistanceEffect;
uniform vec3 planetDistanceColor;
uniform float planetDistanceDesaturate;
uniform float planetDistanceDim;
varying vec3 vWorldPositionCustom;`
);
shader.fragmentShader = shader.fragmentShader.replace(
'#include <fog_fragment>',
`#include <fog_fragment>
if (planetFogEnabled > 0.5) {
vec3 planetView = normalize(cameraPosition - vWorldPositionCustom);
float planetDist = length(cameraPosition - vWorldPositionCustom);
float planetRange = max(1.0, planetFogFar - planetFogNear);
float planetFogF = clamp((planetDist - planetFogNear) / planetRange, 0.0, 1.0);
float planetHorizon = pow(clamp(1.0 - abs(planetView.y), 0.0, 1.0), planetHazeExponent);
float planetFog = clamp(planetFogF * planetFogStrength * (0.76 + planetHorizon * 0.38), 0.0, 1.0);
gl_FragColor.rgb = mix(gl_FragColor.rgb, planetFogColor, planetFog);
}
if (planetDistanceEffect > 0.001) {
float distMix = clamp(planetDistanceEffect, 0.0, 1.0);
float grey = dot(gl_FragColor.rgb, vec3(0.299, 0.587, 0.114));
gl_FragColor.rgb = mix(gl_FragColor.rgb, vec3(grey), clamp(planetDistanceDesaturate, 0.0, 1.0) * distMix);
gl_FragColor.rgb = mix(gl_FragColor.rgb, planetDistanceColor, distMix);
gl_FragColor.rgb *= mix(1.0, planetDistanceDim, distMix);
}
if (clipEnabled > 0.5) {
float dx1 = vWorldPositionCustom.x - clipMin.x;
float dx2 = clipMax.x - vWorldPositionCustom.x;
float dz1 = vWorldPositionCustom.z - clipMin.z;
float dz2 = clipMax.z - vWorldPositionCustom.z;
float minDist = min(min(dx1, dx2), min(dz1, dz2));
if (minDist < 0.0) {
discard;
}
}`
);
};
}
_ensurePlanetFogUniforms() {
const u = this.terrainMat && this.terrainMat.userData;
if (!u) return null;
if (!u.planetFogEnabled || typeof u.planetFogEnabled.value === 'undefined') u.planetFogEnabled = { value: 0.0 };
if (!u.planetFogColor || !u.planetFogColor.value) u.planetFogColor = { value: new THREE.Color(this.currentBiome ? this.currentBiome.fogColor : 0xc4d8c0) };
if (!u.planetFogNear || typeof u.planetFogNear.value === 'undefined') u.planetFogNear = { value: 360 };
if (!u.planetFogFar || typeof u.planetFogFar.value === 'undefined') u.planetFogFar = { value: 6200 };
if (!u.planetFogStrength || typeof u.planetFogStrength.value === 'undefined') u.planetFogStrength = { value: 0.0 };
if (!u.planetHazeExponent || typeof u.planetHazeExponent.value === 'undefined') u.planetHazeExponent = { value: 1.45 };
if (!u.planetDistanceEffect || typeof u.planetDistanceEffect.value === 'undefined') u.planetDistanceEffect = { value: 0.0 };
if (!u.planetDistanceColor || !u.planetDistanceColor.value) u.planetDistanceColor = { value: new THREE.Color(this.currentBiome ? this.currentBiome.fogColor : 0xc4d8c0) };
if (!u.planetDistanceDesaturate || typeof u.planetDistanceDesaturate.value === 'undefined') u.planetDistanceDesaturate = { value: 0.0 };
if (!u.planetDistanceDim || typeof u.planetDistanceDim.value === 'undefined') u.planetDistanceDim = { value: 1.0 };
return u;
}
setPlanetFog(opts = {}) {
const u = this._ensurePlanetFogUniforms();
if (!u) return;
const ensureUniform = (key, fallback) => {
if (!u[key] || typeof u[key].value === 'undefined') u[key] = { value: fallback };
return u[key];
};
const fogEnabled = ensureUniform('planetFogEnabled', 0.0);
const fogColor = ensureUniform('planetFogColor', new THREE.Color(this.currentBiome ? this.currentBiome.fogColor : 0xc4d8c0));
const fogNear = ensureUniform('planetFogNear', 360);
const fogFar = ensureUniform('planetFogFar', 6200);
const fogStrength = ensureUniform('planetFogStrength', 0.0);
const hazeExponent = ensureUniform('planetHazeExponent', 1.45);
const distanceEffect = ensureUniform('planetDistanceEffect', 0.0);
const distanceColor = ensureUniform('planetDistanceColor', new THREE.Color(this.currentBiome ? this.currentBiome.fogColor : 0xc4d8c0));
const distanceDesaturate = ensureUniform('planetDistanceDesaturate', 0.0);
const distanceDim = ensureUniform('planetDistanceDim', 1.0);
const enabled = opts.enabled !== false;
fogEnabled.value = enabled ? 1.0 : 0.0;
if (opts.color !== undefined) {
if (opts.color && opts.color.isColor) fogColor.value.copy(opts.color);
else fogColor.value.set(opts.color);
}
if (Number.isFinite(Number(opts.near))) fogNear.value = Number(opts.near);
if (Number.isFinite(Number(opts.far))) fogFar.value = Number(opts.far);
if (Number.isFinite(Number(opts.strength))) fogStrength.value = Math.max(0, Number(opts.strength));
if (Number.isFinite(Number(opts.exponent))) hazeExponent.value = Math.max(0.1, Number(opts.exponent));
if (opts.distanceColor !== undefined) {
if (opts.distanceColor && opts.distanceColor.isColor) distanceColor.value.copy(opts.distanceColor);
else distanceColor.value.set(opts.distanceColor);
}
if (Number.isFinite(Number(opts.distanceEffect))) distanceEffect.value = Math.max(0, Math.min(1, Number(opts.distanceEffect)));
if (Number.isFinite(Number(opts.distanceDesaturate))) distanceDesaturate.value = Math.max(0, Math.min(1, Number(opts.distanceDesaturate)));
if (Number.isFinite(Number(opts.distanceDim))) distanceDim.value = Math.max(0.1, Math.min(1.2, Number(opts.distanceDim)));
}
_mergeColored(entries) {
let total = 0;
for (const e of entries) total += e.geo.attributes.position.count;
const positions = new Float32Array(total * 3);
const normals = new Float32Array(total * 3);
const colors = new Float32Array(total * 3);
const indices = [];
let vOff = 0;
for (const e of entries) {
const pg = e.geo;
const pn = pg.attributes.position;
pg.computeVertexNormals();
const nr = pg.attributes.normal;
for (let i = 0; i < pn.count; i++) {
positions[(vOff + i) * 3] = pn.getX(i);
positions[(vOff + i) * 3 + 1] = pn.getY(i);
positions[(vOff + i) * 3 + 2] = pn.getZ(i);
normals[(vOff + i) * 3] = nr.getX(i);
normals[(vOff + i) * 3 + 1] = nr.getY(i);
normals[(vOff + i) * 3 + 2] = nr.getZ(i);
colors[(vOff + i) * 3] = e.col.r;
colors[(vOff + i) * 3 + 1] = e.col.g;
colors[(vOff + i) * 3 + 2] = e.col.b;
}
const idx = pg.index;
if (idx) {
for (let i = 0; i < idx.count; i++) indices.push(idx.getX(i) + vOff);
} else {
for (let i = 0; i < pn.count; i++) indices.push(i + vOff);
}
vOff += pn.count;
pg.dispose();
}
const out = new THREE.BufferGeometry();
out.setAttribute('position', new THREE.BufferAttribute(positions, 3));
out.setAttribute('normal', new THREE.BufferAttribute(normals, 3));
out.setAttribute('color', new THREE.BufferAttribute(colors, 3));
out.setIndex(indices);
return out;
}
_buildPineGeo() {
const geos = [];
const trunk = new THREE.CylinderGeometry(0.22, 0.32, 2.2, 6);
trunk.translate(0, 1.1, 0);
geos.push({ geo: trunk, col: new THREE.Color(0x5d3a1a) });
for (let i = 0; i < 4; i++) {
const c = new THREE.ConeGeometry(1.5 - i * 0.22, 1.8, 6);
c.translate(0, 2.5 + i * 0.85, 0);
geos.push({ geo: c, col: new THREE.Color(i % 2 === 0 ? 0x2d6a2a : 0x3a8a38) });
}
return this._mergeColored(geos);
}
_buildCactusGeo() {
const geos = [];
const col = new THREE.Color(0x4a7a3a);
const body = new THREE.CylinderGeometry(0.35, 0.42, 2.4, 8);
body.translate(0, 1.2, 0);
geos.push({ geo: body, col });
const armL = new THREE.CylinderGeometry(0.18, 0.22, 0.9, 7);
armL.rotateZ(Math.PI / 2);
armL.translate(-0.6, 1.5, 0);
geos.push({ geo: armL, col });
const armLUp = new THREE.CylinderGeometry(0.18, 0.18, 0.7, 7);
armLUp.translate(-1.0, 1.9, 0);
geos.push({ geo: armLUp, col });
const armR = new THREE.CylinderGeometry(0.16, 0.2, 0.7, 7);
armR.rotateZ(Math.PI / 2);
armR.translate(0.5, 1.9, 0);
geos.push({ geo: armR, col });
const armRUp = new THREE.CylinderGeometry(0.16, 0.16, 0.55, 7);
armRUp.translate(0.82, 2.22, 0);
geos.push({ geo: armRUp, col });
const cap = new THREE.SphereGeometry(0.38, 7, 5);
cap.translate(0, 2.38, 0);
geos.push({ geo: cap, col });
return this._mergeColored(geos);
}
_buildShrubGeo() {
const geos = [];
for (let i = 0; i < 5; i++) {
const r = 0.35 + (i % 3) * 0.1;
const d = new THREE.DodecahedronGeometry(r, 0);
const ang = (i / 5) * Math.PI * 2;
d.translate(Math.cos(ang) * 0.3, r * 0.7, Math.sin(ang) * 0.3);
geos.push({ geo: d, col: new THREE.Color(0x7a5a2a) });
}
return this._mergeColored(geos);
}
_buildBoulderGeo() {
const geo = new THREE.IcosahedronGeometry(1, 0);
const p = geo.attributes.position;
for (let i = 0; i < p.count; i++) {
const x = p.getX(i), y = p.getY(i), z = p.getZ(i);
const n = Math.sin(x * 5.3 + this.seed) * Math.cos(y * 3.7) * Math.sin(z * 4.1);
p.setXYZ(i, x * (1 + n * 0.25), y * (1 + n * 0.20), z * (1 + n * 0.22));
}
geo.computeVertexNormals();
const cols = new Float32Array(p.count * 3);
const c = new THREE.Color(0xa07450);
for (let i = 0; i < p.count; i++) {
cols[i * 3] = c.r; cols[i * 3 + 1] = c.g; cols[i * 3 + 2] = c.b;
}
geo.setAttribute('color', new THREE.BufferAttribute(cols, 3));
return geo;
}
// --- Water Implementation ---
_initWater() {
this.waterMat = new THREE.ShaderMaterial({
uniforms: {
time: { value: 0 },
shallow: { value: new THREE.Color(0x4ea68a) },
deep: { value: new THREE.Color(0x143a46) },
skyTop: { value: new THREE.Color(this.currentBiome.skyTop) },
skyBottom: { value: new THREE.Color(this.currentBiome.skyBottom) },
cameraPos: { value: new THREE.Vector3() },
fogColor: { value: new THREE.Color(this.currentBiome.fogColor) },
fogNear: { value: 500 },
fogFar: { value: 6100 },
sunDir: { value: this.sunDir.clone() },
runwayR: { value: this.WATER_RUNWAY_R },
reflectivity: { value: 1.28 },
fresnelBoost: { value: 1.12 },
sunGlint: { value: 1.18 },
waterOpacity: { value: 0.92 },
clipEnabled: { value: 0.0 },
clipMin: { value: this._clipMin },
clipMax: { value: this._clipMax },
planetDistanceEffect: { value: 0.0 },
planetDistanceColor: { value: new THREE.Color(this.currentBiome.fogColor) },
planetDistanceDesaturate: { value: 0.0 },
planetDistanceDim: { value: 1.0 },
},
vertexShader: `
varying vec3 vWorldPos;
varying float vDist;
void main() {
vec4 wp = modelMatrix * vec4(position, 1.0);
vWorldPos = wp.xyz;
vec4 mv = viewMatrix * wp;
vDist = -mv.z;
gl_Position = projectionMatrix * mv;
}
`,
fragmentShader: `
precision highp float;
uniform float time;
uniform vec3 shallow;
uniform vec3 deep;
uniform vec3 skyTop;
uniform vec3 skyBottom;
uniform vec3 cameraPos;
uniform vec3 fogColor;
uniform float fogNear;
uniform float fogFar;
uniform vec3 sunDir;
uniform float runwayR;
uniform float reflectivity;
uniform float fresnelBoost;
uniform float sunGlint;
uniform float waterOpacity;
uniform float clipEnabled;
uniform vec3 clipMin;
uniform vec3 clipMax;
uniform float planetDistanceEffect;
uniform vec3 planetDistanceColor;
uniform float planetDistanceDesaturate;
uniform float planetDistanceDim;
varying vec3 vWorldPos;
varying float vDist;
float hash(vec2 p) {
return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453);
}
float noise(vec2 p) {
vec2 i = floor(p);
vec2 f = fract(p);
vec2 u = f * f * (3.0 - 2.0 * f);
return mix(
mix(hash(i), hash(i + vec2(1.0, 0.0)), u.x),
mix(hash(i + vec2(0.0, 1.0)), hash(i + vec2(1.0, 1.0)), u.x),
u.y
);
}
void main() {
// Clip bounds discard. The boundary is filled by opaque cut-cap
// geometry; do not fade the terrain/water to blue fog at the edge.
if (clipEnabled > 0.5) {
float dx1 = vWorldPos.x - clipMin.x;
float dx2 = clipMax.x - vWorldPos.x;
float dz1 = vWorldPos.z - clipMin.z;
float dz2 = clipMax.z - vWorldPos.z;
float minDist = min(min(dx1, dx2), min(dz1, dz2));