-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
844 lines (677 loc) · 31.3 KB
/
index.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Terrain</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdn.tailwindcss.com"></script>
<style>
body,
html {
margin: 0;
padding: 0;
overflow: hidden;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
background-color: #1a202c;
}
#canvas-container {
width: 75vw;
height: 100vh;
}
#webgl-canvas {
width: 100%;
height: 100%;
display: block;
}
#info {
width: 25vw;
height: 100vh;
background-color: #2d3748;
color: #fff;
padding: 20px;
box-sizing: border-box;
display: flex;
flex-direction: column;
justify-content: center;
}
#fps-counter {
font-size: 2rem;
font-weight: bold;
}
</style>
</head>
<body>
<div id="canvas-container">
<canvas id="webgl-canvas"></canvas>
</div>
<div id="info" class="flex flex-col justify-center items-center">
<div id="fps-counter" class="my-2 h-10">FPS: 0.0</div>
<!-- List of sliders for settings -->
<div class="flex flex-col justify-left items-left w-full">
<div class="flex flex-row justify-between items-center my-2">
<label for="fov" class="mx-2">FOV</label>
<input type="range" id="fov" name="fov" min="30.0" max="100.0" value="45.0" step="1.0"
class="flex-grow mx-2">
<span id="fov-value" class="mx-2">45</span>
</div>
<div class="flex flex-row justify-between items-center my-2">
<label for="chunk-scale" class="mx-2">Chunk Scale</label>
<input type="range" id="chunk-scale" name="chunk-scale" min="1.0" max="32.0" value="32.0" step="1.0"
class="flex-grow mx-2">
<span id="chunk-scale-value" class="mx-2">32</span>
</div>
<div class="flex flex-row justify-between items-center my-2">
<label for="elevation-scale" class="mx-2">Chunk Elevation Scale</label>
<input type="range" id="elevation-scale" name="elevation-scale" min="1.0" max="50.0" value="32.0"
step="0.5" class="flex-grow mx-2">
<span id="elevation-scale-value" class="mx-2">32</span>
</div>
<div class="flex flex-col justify-left items-left w-full">
<label for="noisegen-gain" class="mx-2">Noise Generator Gain</label>
<input type="range" id="noisegen-gain" name="noisegen-gain" min="0.01" max="1.0" value="0.5" step="0.01"
class="flex-grow mx-2">
<span id="noisegen-gain-value" class="mx-2">0.5</span>
<script>
document.getElementById('noisegen-gain').addEventListener('input', function () {
document.getElementById('noisegen-gain-value').innerText = this.value;
});
</script>
</div>
<div class="flex flex-col justify-left items-left w-full">
<label for="noisegen-lacunarity" class="mx-2">Noise Generator Lacunarity</label>
<input type="range" id="noisegen-lacunarity" name="noisegen-lacunarity" min="0.0" max="4.0" value="2.0"
step="0.01" class="flex-grow mx-2">
<span id="noisegen-lacunarity-value" class="mx-2">2.0</span>
<script>
document.getElementById('noisegen-lacunarity').addEventListener('input', function () {
document.getElementById('noisegen-lacunarity-value').innerText = this.value;
});
</script>
</div>
</div>
<!-- Color Picker for sunlight -->
<div class="flex flex-col justify-left items-left w-full">
<label for="sun-color" class="mx-2">Sunlight Color</label>
<input type="color" id="sun-color" name="sun-color" value="#fdfbd3" class="flex-grow mx-2">
<span id="sun-color-value" class="mx-2">#fdfbd3</span>
<script>
document.getElementById('sun-color').addEventListener('input', function () {
console.log(this.value);
document.getElementById('sun-color-value').innerText = this.value;
});
</script>
</div>
</div>
<script>
// update the value of the slider
document.getElementById('fov').addEventListener('input', function () {
document.getElementById('fov-value').innerText = this.value;
});
document.getElementById('chunk-scale').addEventListener('input', function () {
document.getElementById('chunk-scale-value').innerText = this.value;
});
document.getElementById('elevation-scale').addEventListener('input', function () {
document.getElementById('elevation-scale-value').innerText = this.value;
});
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gl-matrix/2.8.1/gl-matrix-min.js"></script>
<script src="./common.js"></script>
<script>
const canvas = document.getElementById('webgl-canvas');
const gl = canvas.getContext('webgl2');
if (!gl) {
alert("WebGL 2.0 isn't available in your browser.");
}
// enable MSAA
fbm_drawer = new FBM(gl);
// Vertex shader program
const vsSource = `#version 300 es
in vec4 aVertexPosition;
in vec4 aVertexUv;
uniform mat4 uModelMatrix;
uniform mat4 uViewMatrix;
uniform mat4 uProjectionMatrix;
out highp vec3 vWorldPosition;
out highp vec2 vUv;
out highp float vHeight;
uniform sampler2D uNoiseSampler;
void main(void) {
float h = texture(uNoiseSampler, aVertexUv.xy).r;
vec4 deformed = (uModelMatrix * (aVertexPosition + vec4(0.0, 0.0, h - 1.0/2.0, 0.0)));
vWorldPosition = deformed.xyz;
gl_Position = uProjectionMatrix * uViewMatrix * deformed;
vUv = aVertexUv.xy;
vHeight = h;
}
`;
// Fragment shader program
const fsSource = `#version 300 es
#line 147
precision highp float;
uniform sampler2D uSampler;
uniform sampler2D uNoiseSampler;
uniform sampler2D uNormalSampler;
uniform sampler2D uRoughnessSampler;
uniform sampler2D uSamplerSnow;
uniform sampler2D uNormalSamplerSnow;
uniform sampler2D uRoughnessSamplerSnow;
uniform samplerCube uSkybox;
uniform mat4 uModelMatrix;
uniform mat4 uViewMatrix;
uniform vec4 uCameraPosition;
uniform vec4 uSunColor;
uniform vec4 uSunDirection;
in highp vec3 vWorldPosition;
in highp vec2 vUv;
in highp float vHeight;
out vec4 fragColor;
// coming from the top right of the screen
const highp float ambient = 0.05;
void main(void) {
vec3 dx = dFdx(vWorldPosition.xyz);
vec3 dy = dFdy(vWorldPosition.xyz);
vec3 face_normal = normalize(cross(dx, dy));
// height-dependent texture fetch
// around 0.8, blend between grass and snow
vec3 normal_grass = normalize(texture(uNormalSampler, vUv).xyz);
vec3 normal_snow = normalize(texture(uNormalSampler, vUv).xyz);
vec3 color_grass = texture(uSampler, vUv).rgb;
vec3 color_snow = texture(uSamplerSnow, vUv).rgb;
float roughness_grass = texture(uRoughnessSampler, vUv).r;
float roughness_snow = texture(uRoughnessSamplerSnow, vUv).r;
float blend = smoothstep(0.7, 0.8, 1.0 - vHeight);
vec3 normal = mix(normal_grass, normal_grass, blend);
vec3 albedo = mix(color_grass, color_snow, blend);
float roughness = mix(roughness_grass, roughness_snow, blend);
// TBN
vec3 T = normalize(dx);
vec3 B = normalize(dy);
vec3 N = normalize(face_normal);
mat3 TBN = mat3(T, B, N);
normal = normalize(normal * 2.0 - 1.0);
normal = normalize(TBN * normal);
vec3 sun_dir = -uSunDirection.xyz;
float diffuse = max(dot(normal, sun_dir), 0.0);
vec3 view_dir = normalize(uCameraPosition.xyz - vWorldPosition.xyz);
vec3 half_dir = normalize(sun_dir + view_dir);
float specular = 0.0;
if (diffuse > 0.0) {
specular = pow(max(dot(normal, half_dir), 0.0), 8.0) * (1.0 - roughness) * 0.75;
}
// ambient light from the skybox
vec3 R = reflect(view_dir, normal);
vec3 skybox_color = texture(uSkybox, R).rgb * (1.0 - roughness) * 0.25;
float light = (diffuse + specular);
vec3 color = albedo * (ambient + skybox_color + uSunColor.rgb * light);
// gamma
color = pow(color, vec3(1.0 / 2.2));
fragColor = vec4(color, 1.0);
}
`;
const shaderProgram = initShaderProgram(gl, vsSource, fsSource);
const programInfo = {
program: shaderProgram,
attr_locations: {
v_pos: gl.getAttribLocation(shaderProgram, 'aVertexPosition'),
v_uv: gl.getAttribLocation(shaderProgram, 'aVertexUv'),
},
u_locations: {
proj_mat: gl.getUniformLocation(shaderProgram, 'uProjectionMatrix'),
view_mat: gl.getUniformLocation(shaderProgram, 'uViewMatrix'),
model_mat: gl.getUniformLocation(shaderProgram, 'uModelMatrix'),
u_camera_position: gl.getUniformLocation(shaderProgram, 'uCameraPosition'),
u_sun_color: gl.getUniformLocation(shaderProgram, 'uSunColor'),
u_sun_direction: gl.getUniformLocation(shaderProgram, 'uSunDirection'),
},
u_texture: gl.getUniformLocation(shaderProgram, 'uSampler'),
u_noise_texture: gl.getUniformLocation(shaderProgram, 'uNoiseSampler'),
u_normals_texture: gl.getUniformLocation(shaderProgram, 'uNormalSampler'),
u_roughness_texture: gl.getUniformLocation(shaderProgram, 'uRoughnessSampler'),
u_cube_texture: gl.getUniformLocation(shaderProgram, 'uSkybox'),
};
// INIT "GLOBALS"
let chunk_scale = 32.0;
let chunk_elevation_scale = 32.0;
let spawn_radius = 5.0;
let chunks = {};
let last_time = 0.0;
let camera = {
yaw: 0.0,
pitch: 0.0,
sensitivity: 0.002,
is_locked: false,
delta_x: 0.0,
delta_y: 0.0,
position: vec3.fromValues(0.0, 5.0, -10.0),
up: vec3.fromValues(0.0, 1.0, 0.0),
front: vec3.fromValues(0.0, 0.0, 1.0),
speed: 0.005,
sprint_multiplier: 4.0,
fov: 45.0,
keys: {
"w": false,
"a": false,
"s": false,
"d": false,
"shift": false,
"space": false,
"ctrl": false
}
};
let sun = {
distance: 80.0,
angle: 0.0,
color: vec3.fromValues(253.0 / 255.0, 251.0 / 255.0, 211.0 / 255.0), // Homebase Sunlight / #fdfbd3
light_dir: vec3.fromValues(0.0, 0.0, 0.0), // Ditto
};
// DECLARE PERIODIC EVENTS
// schema: {name: string, interval: number, func: function}
lambdas = [
{
"name": "spawn_chunks",
"interval": 100.0, // ms
"offset": 0.0, // ms
"exec_first": true,
"func": function () {
let center = vec2.fromValues(camera.position[0], camera.position[2]);
center = vec2.scale(center, center, 1.0 / chunk_scale);
center = vec2.floor(center, center);
for (let x = -spawn_radius; x < spawn_radius; x++) {
for (let z = -spawn_radius; z < spawn_radius; z++) {
// restrict to circle
const grid_value = vec2.fromValues(x, z);
const chunk_coords = vec2.add(vec2.create(), center, grid_value);
const hash = `${chunk_coords[0]}_${chunk_coords[1]}`;
if (vec2.squaredLength(grid_value) < spawn_radius * spawn_radius) {
if (!chunks[hash]) {
chunks[hash] = {
"coordinate": chunk_coords,
"elevation": new NoiseTexture2D(gl, 128, 128)
};
fbm_drawer.sample_fbm(gl, chunks[hash].elevation.texture, 42, 128, 128, chunk_coords[0], chunk_coords[1]);
}
}
}
}
}
},
{
"name": "despawn_chunks",
"interval": 100.0, // ms
"offset": 50.0, // ms
"exec_first": true,
"func": function () {
to_delete = [];
for (let key in chunks) {
let chunk = chunks[key];
let x = chunk.coordinate[0];
let z = chunk.coordinate[1];
// position relative to player
let player_pos = vec2.fromValues(camera.position[0], camera.position[2]);
let player_chunk_coords = vec2.scale(player_pos, player_pos, 1.0 / chunk_scale);
player_chunk_coords = vec2.floor(player_chunk_coords, player_chunk_coords);
if (Math.abs(player_chunk_coords[0] - x) > spawn_radius || Math.abs(player_chunk_coords[1] - z) > spawn_radius) {
// pop from chunks
to_delete.push(key);
}
}
for (let key of to_delete) {
delete chunks[key];
}
}
},
];
// for each lambda, after offset time, register the lambda to be called every interval time
for (let lambda of lambdas) {
setTimeout(function () {
if (lambda.exec_first) {
lambda.func();
}
setInterval(lambda.func, lambda.interval);
}, lambda.offset);
}
// DECLARE EVENT LISTENERS
listeners = [
{
"name": "window_resize",
"exec_first": true,
"trigger": "resize",
"func": function () {
const displayWidth = canvas.clientWidth;
const displayHeight = canvas.clientHeight;
if (canvas.width !== displayWidth || canvas.height !== displayHeight) {
canvas.width = displayWidth;
canvas.height = displayHeight;
gl.viewport(0, 0, canvas.width, canvas.height);
}
}
},
{
"name": "mouse_lock",
"exec_first": false,
"trigger": "click",
"func": function () {
if (canvas.requestPointerLock) {
canvas.requestPointerLock();
} else if (canvas.mozRequestPointerLock) {
canvas.mozRequestPointerLock();
} else if (canvas.webkitRequestPointerLock) {
canvas.webkitRequestPointerLock();
}
}
},
{
"name": "mouse_unlock",
"exec_first": false,
"trigger": "pointerlockchange",
"func": function () {
if (document.pointerLockElement === canvas ||
document.mozPointerLockElement === canvas ||
document.webkitPointerLockElement === canvas) {
canvas.focus();
camera.is_locked = true;
} else {
camera.is_locked = false;
}
}
},
{
"name": "mouse_move",
"exec_first": false,
"trigger": "mousemove",
"func": function (event) {
if (camera.is_locked) {
camera.delta_x = event.movementX || event.mozMovementX || event.webkitMovementX || 0;
camera.delta_y = -(event.movementY || event.mozMovementY || event.webkitMovementY || 0);
}
}
},
{
"name": "handle_keydown",
"exec_first": false,
"trigger": "keydown",
"func": function (event) {
key = event.key.toLowerCase();
camera.keys[key] = true;
}
}, {
"name": "handle_keyup",
"exec_first": false,
"trigger": "keyup",
"func": function (event) {
key = event.key.toLowerCase();
camera.keys[key] = false;
}
},
]
// inject event listeners
for (let listener of listeners) {
if (listener.exec_first) {
listener.func();
}
window.addEventListener(listener.trigger, listener.func);
}
document.addEventListener('pointerlockerror', function () {
console.error("Pointer lock failed.");
});
// add
// listeners for the sliders
document.getElementById('fov').addEventListener('input', function () {
camera.fov = parseFloat(this.value);
});
document.getElementById('chunk-scale').addEventListener('input', function () {
chunk_scale = parseFloat(this.value);
});
document.getElementById('elevation-scale').addEventListener('input', function () {
chunk_elevation_scale = parseFloat(this.value);
});
document.getElementById('sun-color').addEventListener('input', function () {
function hexToRgb(hex) {
// https://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
} : null;
}
let color = hexToRgb(this.value);
sun.color = vec3.fromValues(color.r / 255.0, color.g / 255.0, color.b / 255.0);
});
document.getElementById('noisegen-gain').addEventListener('input', function () {
fbm_drawer.gain = parseFloat(this.value);
update_noise();
});
document.getElementById('noisegen-lacunarity').addEventListener('input', function () {
fbm_drawer.lacunarity = parseFloat(this.value);
update_noise();
});
function update_noise() {
for (let key in chunks) {
let chunk = chunks[key];
fbm_drawer.sample_fbm(gl, chunk.elevation.texture, 42, 128, 128, chunk.coordinate[0], chunk.coordinate[1]);
}
}
// PREP NOISE TARGET
// vertices 3
// uvs 2
// normals 3
buffers = gen_quad(gl, 128);
const ANISOTROPIC_FILTERING = 2;
// RENDER LOOP
let grass = new ImageTexture2D(gl, "textures/grass_diffuse.png", {
wrap_s: gl.REPEAT,
wrap_t: gl.REPEAT,
generate_mipmaps: true,
anisotropy: ANISOTROPIC_FILTERING
});
let grass_normals = new ImageTexture2D(gl, "textures/grass_normal.png", {
wrap_s: gl.REPEAT,
wrap_t: gl.REPEAT,
generate_mipmaps: true,
anisotropy: ANISOTROPIC_FILTERING
});
let grass_roughness = new ImageTexture2D(gl, "textures/grass_roughness.png", {
wrap_s: gl.REPEAT,
wrap_t: gl.REPEAT,
generate_mipmaps: true,
anisotropy: ANISOTROPIC_FILTERING
});
let snow = new ImageTexture2D(gl, "textures/snow_diffuse.png", {
wrap_s: gl.REPEAT,
wrap_t: gl.REPEAT,
generate_mipmaps: true,
anisotropy: ANISOTROPIC_FILTERING
});
let snow_normals = new ImageTexture2D(gl, "textures/snow_normal.png", {
wrap_s: gl.REPEAT,
wrap_t: gl.REPEAT,
generate_mipmaps: true,
anisotropy: ANISOTROPIC_FILTERING
});
let snow_roughness = new ImageTexture2D(gl, "textures/snow_roughness.png", {
wrap_s: gl.REPEAT,
wrap_t: gl.REPEAT,
generate_mipmaps: true,
anisotropy: ANISOTROPIC_FILTERING
});
skybox = new Skybox(gl, new Cubemap(gl, [
"skybox/right.jpg",
"skybox/left.jpg",
"skybox/top.jpg",
"skybox/bottom.jpg",
"skybox/front.jpg",
"skybox/back.jpg",
]));
function render() {
let time = performance.now();
let delta_time = time - last_time;
last_time = time;
// update view matrix
let speed = camera.speed;
if (camera.keys["shift"]) {
speed *= camera.sprint_multiplier;
}
speed *= delta_time;
if (camera.keys["w"] || camera.keys["arrowup"]) {
camera.position = vec3.add(camera.position, camera.position, vec3.scale(vec3.create(), camera.front, speed));
}
if (camera.keys["s"] || camera.keys["arrowdown"]) {
camera.position = vec3.sub(camera.position, camera.position, vec3.scale(vec3.create(), camera.front, speed));
}
if (camera.keys["a"] || camera.keys["arrowleft"]) {
camera.position = vec3.sub(camera.position, camera.position, vec3.scale(vec3.create(), vec3.normalize(vec3.create(), vec3.cross(vec3.create(), camera.front, camera.up)), speed));
}
if (camera.keys["d"] || camera.keys["arrowright"]) {
camera.position = vec3.add(camera.position, camera.position, vec3.scale(vec3.create(), vec3.normalize(vec3.create(), vec3.cross(vec3.create(), camera.front, camera.up)), speed));
}
if (camera.keys[" "]) {
camera.position = vec3.add(camera.position, camera.position, vec3.scale(vec3.create(), camera.up, speed));
}
if (camera.keys["control"]) {
camera.position = vec3.sub(camera.position, camera.position, vec3.scale(vec3.create(), camera.up, speed));
}
if (camera.keys["r"]) {
camera.position = vec3.fromValues(0.0, 5.0, -10.0);
}
if (camera.is_locked) {
camera.yaw += camera.delta_x * camera.sensitivity;
camera.pitch += camera.delta_y * camera.sensitivity;
if (camera.pitch > Math.PI / 2 - 0.01) {
camera.pitch = Math.PI / 2 - 0.01;
}
if (camera.pitch < -Math.PI / 2 + 0.01) {
camera.pitch = -Math.PI / 2 + 0.01;
}
camera.delta_x = 0.0;
camera.delta_y = 0.0;
}
const front = vec3.fromValues(
Math.cos(camera.yaw) * Math.cos(camera.pitch),
Math.sin(camera.pitch),
Math.sin(camera.yaw) * Math.cos(camera.pitch)
);
camera.front = vec3.normalize(camera.front, front);
const viewMatrix = mat4.lookAt(mat4.create(), camera.position,
vec3.add(vec3.create(), camera.position, camera.front),
camera.up);
gl.clearColor(0., 0., 0., 1.0);
gl.enable(gl.DEPTH_TEST);
gl.depthFunc(gl.LEQUAL);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
const fieldOfView = camera.fov * Math.PI / 180;
const aspect = gl.canvas.clientWidth / gl.canvas.clientHeight;
const zNear = 0.1;
const zFar = 100.0;
const projectionMatrix = mat4.create();
mat4.perspective(projectionMatrix, fieldOfView, aspect, zNear, zFar);
// Draw Skybox
// Camera direction when looking at the sun from the origin
// Float32Array(3) [ -0.4189602732658386, 0.7617435455322266, -0.49418529868125916 ]
sun.position = vec3.fromValues(
camera.position[0] + sun.distance * Math.cos(sun.angle),
camera.position[1] + sun.distance * Math.sin(sun.angle),
camera.position[2]
);
sun.light_dir = vec3.fromValues(
-0.4189602732658386,
0.7617435455322266,
-0.49418529868125916
);
sun.light_dir = vec3.normalize(sun.light_dir, vec3.negate(sun.light_dir, sun.light_dir));
gl.useProgram(skybox.program);
gl.bindVertexArray(skybox.skybox.vao);
gl.disable(gl.DEPTH_TEST);
gl.disable(gl.CULL_FACE);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
const skyboxModelMat = mat4.create();
mat4.translate(skyboxModelMat, skyboxModelMat, camera.position);
mat4.scale(skyboxModelMat, skyboxModelMat, [50.0, 50.0, 50.0]);
const modelViewMatrix = mat4.create();
mat4.multiply(modelViewMatrix, viewMatrix, skyboxModelMat);
gl.uniformMatrix4fv(skybox.program.info.uModelViewMatrix, false, modelViewMatrix);
gl.uniformMatrix4fv(skybox.program.info.uProjectionMatrix, false, projectionMatrix);
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_CUBE_MAP, skybox.cubemap.cubemap);
gl.uniform1i(skybox.program.info.uCubemap, 0);
gl.drawElements(gl.TRIANGLES, skybox.skybox.n_elements, gl.UNSIGNED_SHORT, 0);
gl.useProgram(programInfo.program);
gl.bindVertexArray(buffers.vao);
gl.enable(gl.DEPTH_TEST);
gl.enable(gl.CULL_FACE);
gl.uniformMatrix4fv(programInfo.u_locations.proj_mat, false, projectionMatrix);
gl.uniformMatrix4fv(programInfo.u_locations.view_mat, false, viewMatrix);
gl.uniform4fv(programInfo.u_locations.u_camera_position, vec4.fromValues(camera.position[0], camera.position[1], camera.position[2], 1.0));
gl.uniform4fv(programInfo.u_locations.u_sun_color, vec4.fromValues(sun.color[0], sun.color[1], sun.color[2], 1.0));
gl.uniform4fv(programInfo.u_locations.u_sun_direction, vec4.fromValues(sun.light_dir[0], sun.light_dir[1], sun.light_dir[2], 1.0));
gl.activeTexture(gl.TEXTURE1);
gl.bindTexture(gl.TEXTURE_2D, grass.texture);
gl.uniform1i(programInfo.u_texture, 1);
gl.activeTexture(gl.TEXTURE2);
gl.bindTexture(gl.TEXTURE_2D, grass_normals.texture);
gl.uniform1i(programInfo.u_normals_texture, 2);
gl.activeTexture(gl.TEXTURE3);
gl.bindTexture(gl.TEXTURE_CUBE_MAP, skybox.cubemap.cubemap);
gl.uniform1i(programInfo.u_cube_texture, 3);
gl.activeTexture(gl.TEXTURE4);
gl.bindTexture(gl.TEXTURE_2D, grass_roughness.texture);
gl.uniform1i(programInfo.u_roughness_texture, 4);
gl.activeTexture(gl.TEXTURE5);
gl.bindTexture(gl.TEXTURE_2D, snow.texture);
gl.uniform1i(programInfo.u_sampler_snow, 5);
gl.activeTexture(gl.TEXTURE6);
gl.bindTexture(gl.TEXTURE_2D, snow_normals.texture);
gl.uniform1i(programInfo.u_normal_sampler_snow, 6);
gl.activeTexture(gl.TEXTURE7);
gl.bindTexture(gl.TEXTURE_2D, snow_roughness.texture);
gl.uniform1i(programInfo.u_roughness_sampler_snow, 7);
const camera_frustum = calculate_frustum(projectionMatrix, viewMatrix);
for (let key in chunks) {
let chunk = chunks[key];
// Frustum culling
const chunk_world_pos = vec3.fromValues(chunk.coordinate[0] * chunk_scale, 0.0, chunk.coordinate[1] * chunk_scale);
const chunk_world_radius = Math.sqrt(2) * chunk_scale * 0.5 * 2.0;
// check if the chunk is in the frustum
let in_frustum = false;
for (let plane of camera_frustum) {
let distance = vec3.dot(plane, chunk_world_pos) + plane[3];
if (distance < -chunk_world_radius) {
in_frustum = false;
break;
}
in_frustum = true;
}
if (!in_frustum) {
continue;
}
const terrainModelMat = mat4.create();
mat4.translate(terrainModelMat, terrainModelMat, [chunk.coordinate[0] * chunk_scale,
-chunk_elevation_scale * 0.5
, chunk.coordinate[1] * chunk_scale]);
mat4.scale(terrainModelMat, terrainModelMat,
[chunk_scale,
chunk_elevation_scale,
chunk_scale]);
mat4.rotate(terrainModelMat, terrainModelMat, Math.PI / 2, [1.0, 0.0, 0.0]);
gl.uniformMatrix4fv(programInfo.u_locations.model_mat, false, terrainModelMat);
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, chunk.elevation.texture);
gl.uniform1i(programInfo.u_noise_texture, 0);
gl.drawElements(gl.TRIANGLES, buffers.n_elements, gl.UNSIGNED_SHORT, 0);
}
gl.drawElements(gl.TRIANGLES, buffers.n_elements, gl.UNSIGNED_SHORT, 0);
gl.disable(gl.CULL_FACE);
gl.disable(gl.DEPTH_TEST);
// update fps counter
let fps = 1000.0 / delta_time;
document.getElementById('fps-counter').innerText = `FPS: ${fps.toFixed(2)}`;
requestAnimationFrame(render);
}
render();
</script>
</body>
</html>