forked from skeelogy/skunami.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
skunami.js
2803 lines (2341 loc) · 116 KB
/
skunami.js
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
/**
* @fileOverview GPU height field water simulations for Three.js flat planes
* @author Skeel Lee <skeel@skeelogy.com>
* @version 1.0.2
*
* @example
* //How to setup a water sim:
*
* //create a plane as the water
* var WATER_SIZE = 10;
* var WATER_RES = 256;
* waterGeom = new THREE.PlaneGeometry(WATER_SIZE, WATER_SIZE, WATER_RES - 1, WATER_RES - 1);
* waterGeom.applyMatrix(new THREE.Matrix4().makeRotationX(-Math.PI / 2));
* waterMesh = new THREE.Mesh(waterGeom, null); //a custom material will automatically be assigned later
* scene.add(waterMesh);
*
* //create a GpuPipeModelWater instance (as an example)
* var gpuWater = new SKUNAMI.GpuPipeModelWater({
* renderer: renderer,
* scene: scene,
* mesh: waterMesh,
* size: WATER_SIZE,
* res: WATER_RES,
* dampingFactor: 0.995,
* multisteps: 1
* });
*
* //update every frame
* renderer.clear();
* gpuWater.update(dt); //have to do this after clear but before render
* renderer.render(scene, camera);
*
* @example
* //How to interact with the water:
*
* //disturb (i.e. cause ripples on water surface)
* var position = detectIntersection(); //do ray-intersection tests, for example, to determine where the user is clicking on the water plane
* var waterDisturbAmount = 0.15;
* var waterDisturbRadius = 0.25;
* gpuWater.disturb(position, waterDisturbAmount, waterDisturbRadius);
*
* //source (i.e. add water to simulation, only available for GpuPipeModelWater)
* var waterSourceAmount = 0.2;
* var waterSourceRadius = 0.7;
* gpuWater.source(position, waterSourceAmount, waterSourceRadius);
*
* //sink (i.e. remove water from simulation, only available for GpuPipeModelWater)
* var waterSinkAmount = -0.5;
* var waterSinkRadius = 0.7;
* gpuWater.source(position, waterSinkAmount, waterSinkRadius);
*
* @example
* //How to flood the scene over time:
*
* var floodRate = 10; //cubic scene units per unit time
*
* //add some volume every frame
* var dV = floodRate * dt;
* gpuWater.flood(dV);
*/
/**
* @namespace
*/
var SKUNAMI = SKUNAMI || { version: '1.0.2' };
console.log('Using SKUNAMI ' + SKUNAMI.version);
/**
* Abstract base class for GPU height field water simulations
* @constructor
* @abstract
*/
SKUNAMI.GpuHeightFieldWater = function (options) {
if (typeof options.mesh === 'undefined') {
throw new Error('mesh not specified');
}
this.__mesh = options.mesh;
if (typeof options.renderer === 'undefined') {
throw new Error('renderer not specified');
}
this.__renderer = options.renderer;
if (typeof options.size === 'undefined') {
throw new Error('size not specified');
}
this.__size = options.size;
if (typeof options.scene === 'undefined') {
throw new Error('scene not specified');
}
this.__scene = options.scene;
if (typeof options.res === 'undefined') {
throw new Error('res not specified');
}
this.__res = options.res;
if (typeof options.dampingFactor === 'undefined') {
throw new Error('dampingFactor not specified');
}
this.__dampingFactor = options.dampingFactor;
//number of full steps to take per frame, to speed up some of algorithms that are slow to propagate at high mesh resolutions.
//this is different from substeps which are reduces dt per step for stability.
this.__multisteps = options.multisteps || 1;
this.__shouldDisplayWaterTexture = false;
this.__shouldDisplayObstaclesTexture = false;
this.__gravity = 9.81;
this.__density = options.density || 1000; //default to 1000 kg per cubic metres
this.__halfSize = this.__size / 2.0;
this.__segmentSize = this.__size / this.__res;
this.__segmentSizeSquared = this.__segmentSize * this.__segmentSize;
this.__texelSize = 1.0 / this.__res;
this.__disturbMapHasUpdated = false;
this.__isDisturbing = false;
this.__disturbUvPos = new THREE.Vector2();
this.__disturbAmount = 0;
this.__disturbRadius = 0.0025 * this.__size;
this.__linearFloatRgbaParams = {
minFilter: THREE.LinearFilter,
magFilter: THREE.LinearFilter,
wrapS: THREE.ClampToEdgeWrapping,
wrapT: THREE.ClampToEdgeWrapping,
format: THREE.RGBAFormat,
stencilBuffer: false,
depthBuffer: false,
type: THREE.FloatType
};
this.__nearestFloatRgbaParams = {
minFilter: THREE.NearestFilter,
magFilter: THREE.NearestFilter,
wrapS: THREE.ClampToEdgeWrapping,
wrapT: THREE.ClampToEdgeWrapping,
format: THREE.RGBAFormat,
stencilBuffer: false,
depthBuffer: false,
type: THREE.FloatType
};
//create a boundary texture
this.__boundaryData = new Float32Array(4 * this.__res * this.__res);
//camera depth range (for obstacles)
this.__rttObstaclesCameraRange = 50.0;
this.__pixelByteData = new Uint8Array(this.__res * this.__res * 4);
this.__staticObstacles = [];
this.__dynObstacles = [];
this.__shouldUpdateStaticObstacle = false;
this.__callbacks = {};
this.__initCounter = 5;
this.__init();
//setup obstacles
this.__setupObstaclesScene();
};
/**
* Gets whether the water texture should be displayed
* @returns {boolean} Whether the water texture should be displayed
*/
SKUNAMI.GpuHeightFieldWater.prototype.getShouldDisplayWaterTexture = function () {
return this.__shouldDisplayWaterTexture;
};
/**
* Sets whether the water texture should be displayed
* @param {boolean} value Whether the water texture should be displayed
*/
SKUNAMI.GpuHeightFieldWater.prototype.setShouldDisplayWaterTexture = function (value) {
this.__shouldDisplayWaterTexture = value;
};
/**
* Gets whether the obstacles texture should be displayed
* @returns {boolean} Whether the obstacles texture should be displayed
*/
SKUNAMI.GpuHeightFieldWater.prototype.getShouldDisplayObstaclesTexture = function () {
return this.__shouldDisplayObstaclesTexture;
};
/**
* Sets whether the obstacles texture should be displayed
* @param {boolean} value Whether the obstacles texture should be displayed
*/
SKUNAMI.GpuHeightFieldWater.prototype.setShouldDisplayObstaclesTexture = function (value) {
this.__shouldDisplayObstaclesTexture = value;
};
SKUNAMI.GpuHeightFieldWater.prototype.__init = function () {
this.__checkExtensions();
this.__setupRttScene();
//setup a reset material for clearing render targets
this.__resetMaterial = new THREE.ShaderMaterial({
uniforms: {
uColor: { type: 'v4', value: new THREE.Vector4() }
},
vertexShader: this.__shaders.vert['passUv'],
fragmentShader: this.__shaders.frag['setColor']
});
//create an empty texture because the default value of textures does not seem to be 0?
if (this.__supportsTextureFloatLinear) {
this.__emptyTexture = new THREE.WebGLRenderTarget(this.__res, this.__res, this.__linearFloatRgbaParams);
} else {
this.__emptyTexture = new THREE.WebGLRenderTarget(this.__res, this.__res, this.__nearestFloatRgbaParams);
}
this.__emptyTexture.generateMipmaps = false;
this.__clearRenderTarget(this.__emptyTexture, 0.0, 0.0, 0.0, 0.0);
//create a DataTexture for the boundary, with filtering type based on whether linear filtering is available
if (this.__supportsTextureFloatLinear) {
//use linear with mipmapping
this.__boundaryTexture = new THREE.DataTexture(null, this.__res, this.__res, THREE.RGBAFormat, THREE.FloatType);
this.__boundaryTexture.generateMipmaps = true;
} else {
//resort to nearest filter only, without mipmapping
this.__boundaryTexture = new THREE.DataTexture(null, this.__res, this.__res, THREE.RGBAFormat, THREE.FloatType, undefined, THREE.ClampToEdgeWrapping, THREE.ClampToEdgeWrapping, THREE.NearestFilter, THREE.NearestFilter);
this.__boundaryTexture.generateMipmaps = false;
}
this.__initDataAndTextures();
this.__setupRttRenderTargets();
this.__setupShaders();
this.__setupVtf();
//init parallel reducer
this.__pr = new SKPR.ParallelReducer(this.__renderer, this.__res, 1);
};
SKUNAMI.GpuHeightFieldWater.prototype.__getWaterFragmentShaderContent = function () {
throw new Error('Abstract method not implemented');
};
SKUNAMI.GpuHeightFieldWater.prototype.__shaders = {
vert: {
pass: [
//Pass-through vertex shader for passing just the transformed position to fragment shader
"void main() {",
"gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);",
"}"
].join('\n'),
passUv: [
//Pass-through vertex shader for passing interpolated UVs to fragment shader
"varying vec2 vUv;",
"void main() {",
"vUv = vec2(uv.x, uv.y);",
"gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);",
"}"
].join('\n'),
heightMap: [
//Vertex shader that displaces vertices in local Y based on a texture
"uniform sampler2D uTexture;",
"uniform vec2 uTexelSize;",
"uniform vec2 uTexelWorldSize;",
"uniform float uHeightMultiplier;",
"varying vec3 vViewPos;",
"varying vec3 vViewNormal;",
"varying vec2 vUv;",
THREE.ShaderChunk['shadowmap_pars_vertex'],
"void main() {",
"vUv = uv;",
//displace y based on texel value
"vec4 t = texture2D(uTexture, vUv) * uHeightMultiplier;",
"vec3 displacedPos = vec3(position.x, t.r, position.z);",
//find normal
"vec2 du = vec2(uTexelSize.r, 0.0);",
"vec2 dv = vec2(0.0, uTexelSize.g);",
"vec3 vecPosU = vec3(displacedPos.x + uTexelWorldSize.r,",
"texture2D(uTexture, vUv + du).r * uHeightMultiplier,",
"displacedPos.z) - displacedPos;",
"vec3 vecNegU = vec3(displacedPos.x - uTexelWorldSize.r,",
"texture2D(uTexture, vUv - du).r * uHeightMultiplier,",
"displacedPos.z) - displacedPos;",
"vec3 vecPosV = vec3(displacedPos.x,",
"texture2D(uTexture, vUv + dv).r * uHeightMultiplier,",
"displacedPos.z - uTexelWorldSize.g) - displacedPos;",
"vec3 vecNegV = vec3(displacedPos.x,",
"texture2D(uTexture, vUv - dv).r * uHeightMultiplier,",
"displacedPos.z + uTexelWorldSize.g) - displacedPos;",
"vViewNormal = normalize(normalMatrix * 0.25 * (cross(vecPosU, vecPosV) + cross(vecPosV, vecNegU) + cross(vecNegU, vecNegV) + cross(vecNegV, vecPosU)));",
"vec4 worldPosition = modelMatrix * vec4(displacedPos, 1.0);",
"vec4 viewPos = modelViewMatrix * vec4(displacedPos, 1.0);",
"vViewPos = viewPos.rgb;",
"gl_Position = projectionMatrix * viewPos;",
THREE.ShaderChunk['shadowmap_vertex'],
"}"
].join('\n')
},
frag: {
lambert: [
"uniform vec3 uBaseColor;",
"uniform vec3 uAmbientLightColor;",
"uniform float uAmbientLightIntensity;",
"varying vec3 vViewPos;",
"varying vec3 vViewNormal;",
"varying vec2 vUv;",
"#if MAX_DIR_LIGHTS > 0",
"uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
"uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
"#endif",
THREE.ShaderChunk['shadowmap_pars_fragment'],
"void main() {",
//ambient component
"vec3 ambient = uAmbientLightColor * uAmbientLightIntensity;",
//diffuse component
"vec3 diffuse = vec3(0.0);",
"#if MAX_DIR_LIGHTS > 0",
"for (int i = 0; i < MAX_DIR_LIGHTS; i++) {",
"vec4 lightVector = viewMatrix * vec4(directionalLightDirection[i], 0.0);",
"float normalModulator = dot(normalize(vViewNormal), normalize(lightVector.xyz));",
"diffuse += normalModulator * directionalLightColor[i];",
"}",
"#endif",
"gl_FragColor = vec4(uBaseColor * (ambient + diffuse), 1.0);",
THREE.ShaderChunk['shadowmap_fragment'],
"}"
].join('\n'),
hfWater_disturb: [
//Fragment shader for disturbing water simulations
"uniform sampler2D uTexture;",
"uniform sampler2D uStaticObstaclesTexture;",
"uniform sampler2D uDisturbTexture;",
"uniform int uUseObstacleTexture;",
//disturb is masked by obstacles
"uniform int uIsDisturbing;",
"uniform float uDisturbAmount;",
"uniform float uDisturbRadius;",
"uniform vec2 uDisturbPos;",
//source is not masked by obstacles
"uniform int uIsSourcing;",
"uniform float uSourceAmount;",
"uniform float uSourceRadius;",
"uniform vec2 uSourcePos;",
//flood is source for every cell
"uniform int uIsFlooding;",
"uniform float uFloodAmount;",
"varying vec2 vUv;",
"void main() {",
//read texture from previous step
//r channel: height
"vec4 t = texture2D(uTexture, vUv);",
"float inObstacle;",
"if (uUseObstacleTexture == 1) {",
"vec4 tObstacles = texture2D(uStaticObstaclesTexture, vUv);",
"inObstacle = tObstacles.r;",
"} else {",
//if not using obstacle texture, it means we can just determine this info from the water height.
//no water means it is in obstacle.
"inObstacle = float(t.r < 0.0);",
"}",
//add disturb (will be masked by obstacles)
"if (uIsDisturbing == 1) {",
"float len = length(vUv - vec2(uDisturbPos.x, 1.0 - uDisturbPos.y));",
"t.r += uDisturbAmount * (1.0 - smoothstep(0.0, uDisturbRadius, len)) * (1.0 - inObstacle);",
"}",
//add source (will not be masked by obstacles, otherwise if an area has no water, you can never source into it anymore)
"if (uIsSourcing == 1) {",
"float len = length(vUv - vec2(uSourcePos.x, 1.0 - uSourcePos.y));",
"t.r += uSourceAmount * (1.0 - smoothstep(0.0, uSourceRadius, len));",
"}",
//read disturb texture and just add this amount into the system
//r channel: disturb amount
"vec4 tDisturb = texture2D(uDisturbTexture, vUv);",
"t.r += tDisturb.r;",
//add flood
"if (uIsFlooding == 1) {", //this is used for pipe model water only
"t.r += uFloodAmount;",
"}",
//write out to texture for next step
"gl_FragColor = t;",
"}"
].join('\n'),
hfWater_muellerGdc2008: [
//GPU version of "Fast Water Simulation for Games Using Height Fields" (Matthias Mueller-Fisher, GDC2008)
//NOTE: I have added in mean height in the calculations, purely because of the flooding system.
//It is not necessary if you do not need to rise the water level.
"uniform sampler2D uTexture;",
"uniform vec2 uTexelSize;",
"uniform vec2 uTexelWorldSize;",
"uniform float uDampingFactor;",
"uniform float uHorizontalSpeed;",
"uniform float uDt;",
"uniform float uMeanHeight;",
"varying vec2 vUv;",
"void main() {",
//r channel: height
//g channel: vertical vel
//b channel: UNUSED
//a channel: prev mean height
//read texture from previous step
"vec4 t = texture2D(uTexture, vUv);",
//remove previous mean height first to bring back to 0 height
"t.r -= t.a;",
//propagate
"vec2 du = vec2(uTexelSize.r, 0.0);",
"vec2 dv = vec2(0.0, uTexelSize.g);",
"float acc = uHorizontalSpeed * uHorizontalSpeed * (",
"texture2D(uTexture,vUv+du).r",
"+ texture2D(uTexture,vUv-du).r",
"+ texture2D(uTexture,vUv+dv).r",
"+ texture2D(uTexture,vUv-dv).r",
"- 4.0 * t.a - 4.0 * t.r) / (uTexelWorldSize.x * uTexelWorldSize.x);",
"t.g += acc * uDt;", //TODO: use a better integrator
"t.g *= uDampingFactor;",
//update
"t.r += t.g * uDt;", //TODO: use a better integrator
//add new mean height
"t.r += uMeanHeight;",
//store new mean height
"t.a = uMeanHeight;",
//write out to texture for next step
"gl_FragColor = t;",
"}"
].join('\n'),
hfWater_muellerGdc2008Hw: [
//GPU version of HelloWorld code of "Fast Water Simulation for Games Using Height Fields" (Matthias Mueller-Fisher, GDC2008)
//NOTE: I have added in mean height in the calculations, purely because of the flooding system.
//It is not necessary if you do not need to rise the water level.
"uniform sampler2D uTexture;",
"uniform vec2 uTexelSize;",
"uniform float uDampingFactor;",
"uniform float uMeanHeight;",
"varying vec2 vUv;",
"void main() {",
//r channel: height
//g channel: vertDeriv
//b channel: UNUSED
//a channel: prev mean height
//read texture from previous step
"vec4 t = texture2D(uTexture, vUv);",
//remove previous mean height first to bring back to 0 height
"t.r -= t.a;",
//propagate
"vec2 du = vec2(uTexelSize.r, 0.0);",
"vec2 dv = vec2(0.0, uTexelSize.g);",
"t.g += 0.25 * (texture2D(uTexture,vUv+du).r",
"+ texture2D(uTexture,vUv-du).r",
"+ texture2D(uTexture,vUv+dv).r",
"+ texture2D(uTexture,vUv-dv).r - 4.0 * t.a) - t.r;",
"t.g *= uDampingFactor;",
//update
"t.r += t.g;",
//add new mean height
"t.r += uMeanHeight;",
//store new mean height
"t.a = uMeanHeight;",
//write out to texture for next step
"gl_FragColor = t;",
"}"
].join('\n'),
hfWater_xWater: [
//GPU version of X Water
//NOTE: I have added in mean height in the calculations, purely because of the flooding system.
//It is not necessary if you do not need to rise the water level.
"uniform sampler2D uTexture;",
"uniform vec2 uTexelSize;",
"uniform float uDampingFactor;",
"uniform float uMeanHeight;",
"varying vec2 vUv;",
"void main() {",
//r channel: height
//g channel: field1
//b channel: field2
//a channel: prev mean height
//read texture from previous step
"vec4 t = texture2D(uTexture, vUv);",
//remove previous mean height first to bring back to 0 height
"t.r -= t.a;",
//propagate
"vec2 du = vec2(uTexelSize.r, 0.0);",
"vec2 dv = vec2(0.0, uTexelSize.g);",
"t.b = 0.5 * (texture2D(uTexture,vUv+du).r",
"+ texture2D(uTexture,vUv-du).r",
"+ texture2D(uTexture,vUv+dv).r",
"+ texture2D(uTexture,vUv-dv).r - 4.0 * t.a) - t.b;",
"t.b *= uDampingFactor;",
//update
"t.r = t.b;",
//add new mean height
"t.r += uMeanHeight;",
//store new mean height
"t.a = uMeanHeight;",
//swap buffers
"float temp = t.g;",
"t.g = t.b;",
"t.b = temp;",
//write out to texture for next step
"gl_FragColor = t;",
"}"
].join('\n'),
hfWater_tessendorfIWave_convolve: [
//GPU version of "Interactive Water Surfaces" (Jerry Tessendorf, Game Programming Gems 4).
//This is the convolution pre-pass to find the vertical derivative.
//have to use #define here to get compile-time constant values,
//otherwise there are problems in the double-for-loop and indexing into array.
//remember to change this radius value after changing that in the GpuTessendorfIWaveWater class.
"#define KERNEL_RADIUS 2",
"#define KERNEL_WIDTH (2 * (KERNEL_RADIUS) + 1)",
"uniform sampler2D uWaterTexture;",
"uniform vec2 uTexelSize;",
"uniform float uKernel[KERNEL_WIDTH * KERNEL_WIDTH];",
"varying vec2 vUv;",
"void main() {",
//read water texture
//r channel: height
//g channel: prev height
//b channel: vertical derivative
//a channel: prev mean height
"vec4 tWater = texture2D(uWaterTexture, vUv);",
//propagate
"tWater.b = 0.0;",
"float fk, fl;",
"vec4 tWaterNeighbour;",
"for (int k = -KERNEL_RADIUS; k <= KERNEL_RADIUS; k++) {",
"fk = float(k);",
"for (int l = -KERNEL_RADIUS; l <= KERNEL_RADIUS; l++) {",
"fl = float(l);",
"tWaterNeighbour = texture2D(uWaterTexture, vec2(vUv.r + fk * uTexelSize.r, vUv.g + fl * uTexelSize.g));",
"tWater.b += uKernel[(k + KERNEL_RADIUS) * KERNEL_WIDTH + (l + KERNEL_RADIUS)] * (tWaterNeighbour.r - tWaterNeighbour.a);",
"}",
"}",
//write out to texture for next step
"gl_FragColor = tWater;",
"}"
].join('\n'),
hfWater_tessendorfIWave: [
//GPU version of "Interactive Water Surfaces" (Jerry Tessendorf, Game Programming Gems 4).
//Need to run convolve fragment shader first before running this.
//NOTE: I have added in mean height in the calculations, purely because of the flooding system.
//It is not necessary if you do not need to rise the water level.
"uniform sampler2D uWaterTexture;",
"uniform float uTwoMinusDampTimesDt;",
"uniform float uOnePlusDampTimesDt;",
"uniform float uGravityTimesDtTimesDt;",
"uniform float uMeanHeight;",
"varying vec2 vUv;",
"void main() {",
//read water texture
//r channel: height
//g channel: prev height
//b channel: vertical derivative
//a channel: prev mean height
"vec4 tWater = texture2D(uWaterTexture, vUv);",
//remove previous mean height first to bring back to 0 height
"tWater.r -= tWater.a;",
//propagate
"float temp = tWater.r;",
"tWater.r = (tWater.r * uTwoMinusDampTimesDt",
"- tWater.g",
"- tWater.b * uGravityTimesDtTimesDt) / uOnePlusDampTimesDt;",
"tWater.g = temp;",
//add new mean height
"tWater.r += uMeanHeight;",
//store new mean height
"tWater.a = uMeanHeight;",
//write out to texture for next step
"gl_FragColor = tWater;",
"}"
].join('\n'),
hfWater_pipeModel_calcFlux: [
//GPU version of pipe model water.
//This is the pre-pass to calculate flux.
"uniform sampler2D uTerrainTexture;",
"uniform sampler2D uWaterTexture;",
"uniform sampler2D uFluxTexture;",
"uniform sampler2D uStaticObstaclesTexture;",
"uniform sampler2D uBoundaryTexture;",
"uniform vec2 uTexelSize;",
"uniform float uDampingFactor;",
"uniform float uHeightToFluxFactor;",
"uniform float uSegmentSizeSquared;",
"uniform float uDt;",
"uniform float uMinWaterHeight;",
"varying vec2 vUv;",
"void main() {",
"vec2 du = vec2(uTexelSize.r, 0.0);",
"vec2 dv = vec2(0.0, uTexelSize.g);",
//read terrain texture
//r channel: terrain height
"vec4 tTerrain = texture2D(uTerrainTexture, vUv);",
//read water texture
//r channel: water height
//g, b channels: vel
//a channel: UNUSED
"vec4 tWater = texture2D(uWaterTexture, vUv);",
//read static obstacle texture
//r channel: height
"vec4 tObstacle = texture2D(uStaticObstaclesTexture, vUv);",
"float waterHeight = tWater.r;",
"float totalHeight = max(tTerrain.r, tObstacle.r) + waterHeight;",
//read flux texture
//r channel: fluxR
//g channel: fluxL
//b channel: fluxB
//a channel: fluxT
"vec4 tFlux = texture2D(uFluxTexture, vUv);",
//calculate new flux
"tFlux *= uDampingFactor;",
"vec4 neighbourTotalHeights = vec4(texture2D(uWaterTexture, vUv + du).r + max(texture2D(uTerrainTexture, vUv + du).r, texture2D(uStaticObstaclesTexture, vUv + du).r),",
"texture2D(uWaterTexture, vUv - du).r + max(texture2D(uTerrainTexture, vUv - du).r, texture2D(uStaticObstaclesTexture, vUv - du).r),",
"texture2D(uWaterTexture, vUv - dv).r + max(texture2D(uTerrainTexture, vUv - dv).r, texture2D(uStaticObstaclesTexture, vUv - dv).r),",
"texture2D(uWaterTexture, vUv + dv).r + max(texture2D(uTerrainTexture, vUv + dv).r, texture2D(uStaticObstaclesTexture, vUv + dv).r));",
"tFlux += (totalHeight - neighbourTotalHeights) * uHeightToFluxFactor;",
"tFlux = max(vec4(0.0), tFlux);",
//read boundary texture
//r channel: fluxR
//g channel: fluxL
//b channel: fluxB
//a channel: fluxT
"vec4 tBoundary = texture2D(uBoundaryTexture, vUv);",
//multiply flux with boundary texture to mask out fluxes
"tFlux *= tBoundary;",
//scale down outflow if it is more than available volume in the column
"float currVol = (waterHeight - uMinWaterHeight) * uSegmentSizeSquared;",
"float outVol = uDt * (tFlux.r + tFlux.g + tFlux.b + tFlux.a);",
"tFlux *= min(1.0, currVol / outVol);",
//write out to texture for next step
"gl_FragColor = tFlux;",
"}"
].join('\n'),
hfWater_pipeModel: [
//GPU version of pipe model water.
//Need to run the flux calculation pre-pass first before running this.
"uniform sampler2D uWaterTexture;",
"uniform sampler2D uFluxTexture;",
"uniform vec2 uTexelSize;",
"uniform float uSegmentSize;",
"uniform float uDt;",
"uniform float uMinWaterHeight;",
"varying vec2 vUv;",
"void main() {",
"vec2 du = vec2(uTexelSize.r, 0.0);",
"vec2 dv = vec2(0.0, uTexelSize.g);",
//read water texture
//r channel: water height
//g channel: horizontal velocity x
//b channel: horizontal velocity z
//a channel: UNUSED
"vec4 tWater = texture2D(uWaterTexture, vUv);",
//read flux textures
//r channel: fluxR
//g channel: fluxL
//b channel: fluxB
//a channel: fluxT
"vec4 tFlux = texture2D(uFluxTexture, vUv);",
"vec4 tFluxPixelLeft = texture2D(uFluxTexture, vUv-du);",
"vec4 tFluxPixelRight = texture2D(uFluxTexture, vUv+du);",
"vec4 tFluxPixelTop = texture2D(uFluxTexture, vUv+dv);",
"vec4 tFluxPixelBottom = texture2D(uFluxTexture, vUv-dv);",
"float avgWaterHeight = tWater.r;",
//calculate new height
"float fluxOut = tFlux.r + tFlux.g + tFlux.b + tFlux.a;",
"float fluxIn = tFluxPixelLeft.r + tFluxPixelRight.g + tFluxPixelTop.b + tFluxPixelBottom.a;",
"tWater.r += (fluxIn - fluxOut) * uDt / (uSegmentSize * uSegmentSize);",
"tWater.r = max(uMinWaterHeight, tWater.r);",
"avgWaterHeight = 0.5 * (avgWaterHeight + tWater.r);", //this will get the average height of that from before and after the change
//calculate horizontal velocities, from amount of water passing through per unit time
"if (avgWaterHeight == 0.0) {", //prevent division by 0
"tWater.g = 0.0;",
"tWater.b = 0.0;",
"} else {",
"float threshold = float(tWater.r > 0.2);", //0/1 threshold value for masking out weird velocities at terrain edges
"float segmentSizeTimesAvgWaterHeight = uSegmentSize * avgWaterHeight;",
"tWater.g = threshold * 0.5 * (tFluxPixelLeft.r - tFlux.g + tFlux.r - tFluxPixelRight.g) / segmentSizeTimesAvgWaterHeight;",
"tWater.b = threshold * 0.5 * (tFluxPixelTop.b - tFlux.a + tFlux.b - tFluxPixelBottom.a) / segmentSizeTimesAvgWaterHeight;",
"}",
//write out to texture for next step
"gl_FragColor = tWater;",
"}"
].join('\n'),
setColor: [
//Fragment shader to set colors on a render target
"uniform vec4 uColor;",
"void main() {",
"gl_FragColor = uColor;",
"}"
].join('\n'),
setColorMasked: [
//Fragment shader to set colors on specific channels while keeping the rest of the channels intact
"uniform sampler2D uTexture;",
"uniform vec4 uColor;",
"uniform vec4 uChannelMask;",
"varying vec2 vUv;",
"void main() {",
"vec4 t = texture2D(uTexture, vUv);",
"gl_FragColor = (vec4(1.0) - uChannelMask) * t + uChannelMask * uColor;",
"}"
].join('\n'),
setSolidAlpha: [
//Fragment shader that sets alpha for the given texture to 1.0
"uniform sampler2D uTexture;",
"varying vec2 vUv;",
"void main() {",
"gl_FragColor = vec4(texture2D(uTexture, vUv).rgb, 1.0);",
"}"
].join('\n'),
hfWater_obstacles_static: [
//Fragment shader to calculate static obstacles texture
"uniform sampler2D uObstacleTopTexture;",
"uniform float uHalfRange;",
"varying vec2 vUv;",
"void main() {",
//read texture for obstacle
//r, g, b channels: depth (all these channels contain same value)
//a channel: alpha
"vec4 tTop = texture2D(uObstacleTopTexture, vUv);",
//convert top value to world height
"float topHeight = (uHalfRange - tTop.r) * tTop.a;",
//write out to texture for next step
"gl_FragColor = vec4(topHeight, 0.0, 0.0, 1.0);",
"}"
].join('\n'),
hfWater_obstacles_dynamic: [
//Fragment shader to accumulate an obstacle texture
"uniform sampler2D uObstaclesTexture;",
"uniform sampler2D uObstacleTopTexture;",
"uniform sampler2D uObstacleBottomTexture;",
"uniform sampler2D uWaterTexture;",
"uniform sampler2D uTerrainTexture;",
"uniform float uHalfRange;",
"varying vec2 vUv;",
"void main() {",
//read texture from previous step
//r channel: whether in obstacle or not (accumulated)
//g channel: height of water displaced (accumulated)
//b channel: height of water displaced from previous step (accumulated)
//a channel: height of water displaced (only for current rendered object)
"vec4 t = texture2D(uObstaclesTexture, vUv);",
//read texture for obstacle
//r, g, b channels: depth (all these channels contain same value)
//a channel: alpha
"vec4 tTop = texture2D(uObstacleTopTexture, vUv);",
"vec4 tBottom = texture2D(uObstacleBottomTexture, vec2(vUv.x, 1.0-vUv.y));",
//read texture for water and terrain
//r channel: height
//other channels: other data which are not used here
"vec4 tWater = texture2D(uWaterTexture, vUv);",
"vec4 tTerrain = texture2D(uTerrainTexture, vUv);",
"float waterHeight = tWater.r + tTerrain.r;",
//convert top and bottom into same space (water plane at height of 0, upwards positive)
"float bottomHeight = (tBottom.r - uHalfRange - waterHeight) * tBottom.a;",
"float topHeight = (uHalfRange - waterHeight - tTop.r) * tTop.a;",
//compare the top and bottom depths to determine if water is in obstacle
"bool inObstacle = bottomHeight < 0.0 && topHeight > 0.0;",
//also calculate amount of water displaced
"float displacedHeight;",
"if (bottomHeight > 0.0) {",
//totally above water, so there is no water displaced
"displacedHeight = 0.0;",
"} else if (topHeight < 0.0) {",
//totally below water, so water displaced height is top minus bottom
"displacedHeight = topHeight - bottomHeight;",
"} else {",
//partially submerged, so water displaced is water level minus bottom (which is just negative of bottom)
"displacedHeight = -bottomHeight;",
"}",
//write out to texture for next step
"gl_FragColor = vec4(max(t.r, float(inObstacle)), t.g + displacedHeight, t.b, displacedHeight);",
"}"
].join('\n'),
encodeFloat: [
//Fragment shader that encodes float value in input R channel to 4 unsigned bytes in output RGBA channels
//Most of this code is from original GLSL codes from Piotr Janik, only slight modifications are done to fit the needs of this script
//http://concord-consortium.github.io/lab/experiments/webgl-gpgpu/script.js
//Using method 1 of the code.
"uniform sampler2D uTexture;",
"uniform vec4 uChannelMask;",
"varying vec2 vUv;",
"float shift_right(float v, float amt) {",
"v = floor(v) + 0.5;",
"return floor(v / exp2(amt));",
"}",
"float shift_left(float v, float amt) {",
"return floor(v * exp2(amt) + 0.5);",
"}",
"float mask_last(float v, float bits) {",
"return mod(v, shift_left(1.0, bits));",
"}",
"float extract_bits(float num, float from, float to) {",
"from = floor(from + 0.5);",
"to = floor(to + 0.5);",
"return mask_last(shift_right(num, from), to - from);",
"}",
"vec4 encode_float(float val) {",
"if (val == 0.0) {",
"return vec4(0.0, 0.0, 0.0, 0.0);",
"}",
"float sign = val > 0.0 ? 0.0 : 1.0;",
"val = abs(val);",
"float exponent = floor(log2(val));",