-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
825 lines (690 loc) · 29.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
<!DOCTYPE html>
<html lang="es">
<head>
<!-- TODO:
- Deferred
-->
<title> Basic WebGL2 Scene</title>
<script type="text/javascript" src="gl-matrix-min.js"></script>
<script type="text/javascript" src="shaderManager.js"></script>
<script type="text/javascript" src="utils.js"></script>
<script type="text/javascript" src="models.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dat-gui/0.7.5/dat.gui.min.js" ></script>
<script id="vs" type="x-shader/x-vertex">
#version 300 es
in vec3 position;
in vec3 color;
in vec3 normal;
uniform mat4 projection;
uniform mat4 view;
uniform mat4 model;
out vec3 vColor;
out vec3 vNormal;
out vec3 vPos;
uniform float phaseX;
uniform float phaseY;
uniform float distance;
uniform int numInstancesX;
uniform int numInstancesY;
void main(void)
{
float y = floor(float(gl_InstanceID)/float(numInstancesX));
float x = float(gl_InstanceID) - y*float(numInstancesX);
mat4 modelDisplaced = model;
modelDisplaced[3][0] = modelDisplaced[3][0] + phaseX + distance*x;
modelDisplaced[3][2] = modelDisplaced[3][2] - phaseY + distance*y;
mat4 modelView = view * modelDisplaced;
vPos = (modelDisplaced * vec4(position,1.)).xyz;
gl_Position = projection * modelView*vec4(position, 1.);
vColor = color;
vNormal = mat3(transpose(inverse(modelDisplaced))) * normal;
//vNormal = normal;
}
</script>
<script id="fs" type="x-shader/x-fragment">
#version 300 es
precision mediump float;
in vec3 vColor;
in vec3 vNormal;
in vec3 vPos;
uniform vec3 camPos;
uniform float outlineWidth;
//Obj
vec3 Ka;
vec3 Kd;
vec3 Ks;
float brightness;
vec3 Ke;
vec3 pos;
vec3 normalVector;
//Parametros de la niebla
vec3 cfog = vec3(1.0);
float df = 0.03;
uniform int nStrips;
uniform vec3 light1pos;
uniform vec3 light1int;
uniform vec3 light2dir;
uniform vec3 light2int;
// Luces
//Parametros de luz globales
float c1 = 1.0f;
float c2 = 0.0f;
float c3 = 0.1;
#define MAX_LIGHTS 10
int numLights;
struct Light {
vec4 position;
vec3 intensities;
float constAtt;
float linearAtt;
float cuadraticAtt;
vec3 Ia;
float coneAngle;
vec3 coneDir;
};
//Parametros de la luz 1 - Point
vec3 Il1 = vec3(0.6);
vec3 Ia1 = vec3(0.2);
vec3 pl1 = vec3(2);
float att1 = 0.0;
//light parameters 3 - Directional
vec3 dir = vec3(0.0, -1.0, 1.0);
vec3 Il3 = vec3(0.6);
vec3 Ia3 = vec3(0.2);
out vec4 outColor;
float getStripColorDiffuse(float c) {
return ceil(c * float(nStrips)) / float(nStrips);
}
float getStripColorSpec(float c) {
if (c > 0.1) {
float tmpC = ceil(c * float(max(nStrips/10,3))) / float(max(nStrips/10, 3));
return tmpC;
}
return 0.0;
}
vec3 shade2(Light[MAX_LIGHTS] lights) {
vec3 c = vec3(0.0);
c+= Ke;
vec3 V = camPos - pos;
float distance = length(V);
V = normalize(V);
if (dot(V,normalVector) < outlineWidth && dot(V,normalVector) > -0.1f ) {
return vec3(0.0f);
}
for (int i=0; i< numLights; i++ ) {
Light light = lights[i];
//Amibent
vec3 Iamb = Ka * light.Ia;
vec3 resi = Iamb;
vec3 L = normalize(light.position.xyz - pos * light.position.w); //point or directional
vec3 D = normalize(light.coneDir);
float cosLD = dot(-L,D);
if(cosLD >= cos(radians(light.coneAngle))) { // No se ilumninan fragmentos innecesarios
//Diff
vec3 Idiff = Kd * light.intensities * max(dot(normalVector,L),0.0);
Idiff = clamp(Idiff,0.0,1.0);
resi += Idiff;
//resi.x = getStripColorDiffuse(resi.x);
//resi.y = getStripColorDiffuse(resi.y);
//resi.z = getStripColorDiffuse(resi.z);
//Especular
vec3 H = normalize(V+L);
vec3 Ispec = Ks * light.intensities * pow( max( dot(H,normalVector), 0.0), brightness);
//Ispec.x = getStripColorSpec(Ispec.x);
//Ispec.y = getStripColorSpec(Ispec.y);
//Ispec.z = getStripColorSpec(Ispec.z);
Ispec = clamp(Ispec,0.0,1.0);
resi += Ispec;
}
if ( light.position.w == 1.0) {
float d = length(light.position.xyz - pos);
resi /= light.constAtt + ( light.linearAtt * d) +( light.cuadraticAtt * pow(d,2.0f));
}
c += resi;
}
float f = exp(-pow(df*distance,2.0f));
//c = f*c + (1.0f-f) * cfog;
return c;
}
vec3 shade(Light[MAX_LIGHTS] lights) {
vec3 c = vec3(0.0);
c+= Ke;
vec3 V = normalize(camPos - pos);
if (dot(V,normalVector) < outlineWidth && dot(V,normalVector) > -0.1f ) {
return vec3(0.0f);
}
for (int i=0; i< numLights; i++ ) {
Light light = lights[i];
//Amibent
vec3 Iamb = Ka * light.Ia;
vec3 resi = Iamb;
vec3 L = normalize(light.position.xyz - pos * light.position.w); //point or directional
vec3 D = normalize(light.coneDir);
float cosLD = dot(-L,D);
if(cosLD >= cos(radians(light.coneAngle))) { // No se ilumninan fragmentos innecesarios
//Diff
vec3 Idiff = Kd * light.intensities * max(dot(normalVector,L),0.0);
Idiff = clamp(Idiff,0.0,1.0);
resi += Idiff;
resi.x = getStripColorDiffuse(resi.x);
resi.y = getStripColorDiffuse(resi.y);
resi.z = getStripColorDiffuse(resi.z);
//Especular
vec3 R = -reflect(L,normalVector);
vec3 Ispec = Ks * light.intensities * pow( max( dot(V,R), 0.0), brightness);
Ispec = clamp(Ispec,0.0,1.0);
Ispec.x = getStripColorSpec(Ispec.x);
Ispec.y = getStripColorSpec(Ispec.y);
Ispec.z = getStripColorSpec(Ispec.z);
resi += Ispec;
}
if ( light.position.w == 1.0) {
float d = length(light.position.xyz - pos);
resi /= light.constAtt + ( light.linearAtt * d) +( light.cuadraticAtt * pow(d,2.0f));
}
c += resi;
}
float f = exp(-pow(df*pos.z,2.0f));
c = f*c + (1.0f-f) * cfog;
return c;
}
void main(void)
{
Ka = vColor;
Kd = Ka;
Ks = vec3(1.0);
Ke = vec3(0.0);
brightness = 32.0f;
pos = vPos;
normalVector = normalize(vNormal);
//pl1 = (view2 * vec4(pl1,1.0)).xyz;
//dir = (view2 * vec4(dir,0.0)).xyz;
Light lights[MAX_LIGHTS];
numLights = 2;
Light l1 = Light(vec4(light1pos,1.0), light1int,c1,c2,c3,Ia1,180.0f,vec3(1));
Light l3 = Light(vec4(light2dir,0.0f), light2int,0.0f,0.0f,0.0f,Ia3,180.0f,vec3(1));
lights[0] = l3;
lights[1] = l1;
vec3 c = shade2(lights);
c.x = getStripColorDiffuse(c.x);
c.y = getStripColorDiffuse(c.y);
c.z = getStripColorDiffuse(c.z);
outColor = vec4(c, 1.);
}
</script>
<script id="tfvs" type="x-shader/x-vertex">
#version 300 es
precision mediump float;
in vec3 position;
in vec3 normals;
uniform mat4 model;
uniform mat4 normalMat;
out vec3 pos;
out vec3 normal;
void main(void)
{
pos = (model * vec4(position,1.)).xyz;
normal = (normalMat * vec4(normals,0.)).xyz;
}
</script>
<script id="tffs" type="x-shader/x-fragment">
#version 300 es
precision mediump float;
void main(void)
{
}
</script>
</head>
<body>
<canvas id="glCanvas"></canvas>
<script type="text/javascript">
var State = function() {
this.outlineWidth = 0.6;
this.nStrips = 10;
this.model = 'sphere';
this.light1pos = [6,2,2];
this.light1int = [0, 255, 0];//[153,153,153];//[0.6, 0.6, 0.6];
this.light2dir = [12,18,4];
this.light2int = [150,70,80];//[0.6, 0.6, 0.6];
this.keyboardSens = 1;
this.instancePhaseX = 0.5;
this.instancePhaseY = 1;
this.instanceDistance = 2;
this.instanceX = 50;
this.instanceY = 50;
};
var state = new State();
//http://glmatrix.net/docs/module-mat4.html
var canvas;
var shaderProgram;
var tfShaderProgram;
var projectionLoc, viewLoc, modelLoc, camPosLoc, outlineWidthLoc, nStripsLoc, light1posLoc, light1intLoc, light2dirLoc, light2intLoc;
var tfModelLoc, tfPositionLoc, transformFeedback;
var colorLoc, positionLoc,normalLoc, tfNormalLoc;
var phaseXLoc, phaseYLoc, instDistanceLoc, numInstXLoc, numInstYLoc;
var perspMat, viewMat, modelMat, tfNormalMat;
var meshVertexs;
var meshColors;
var meshIndexs;
var meshNormals;
var vertexBuff;
var colorBuff;
var indexBuff;
var normalBuff;
var camaraPos =[0.0,0.0,5.0];
var lastFrame = new Date().getTime();
var currentDelta = 0;
var drag = false;
var prevX=0, prevY=0, dX=0, dY=0, rotX=0, rotY=0;
function mouseDown(e)
{
drag = true;
prevX = e.pageX;
prevY = e.pageY;
e.preventDefault();
};
function mouseUp(e)
{
drag=false;
};
function mouseMove(e)
{
if (drag)
{
dX = (e.pageX-prevX)*2*Math.PI/canvas.width,
dY = (e.pageY-prevY)*2*Math.PI/canvas.height;
rotX += dX;
if ( Math.abs(rotY+dY) < (Math.PI/2.0) ) rotY+=dY;
prevX = e.pageX;
prevY = e.pageY;
e.preventDefault();
}
};
var MovementDirection = {
FRONT: 1<<1,
BACK: 1<<2,
LEFT: 1<<3,
RIGHT: 1<<4,
UP: 1<<5,
DOWN: 1<<6
};
var movementFlags = 0;
function eventHandler(e) {
var keyCode = e.key;
var forward = [viewMat[2], viewMat[6], viewMat[10]];
if (forward[2] !== 0 && forward[0] !== 0) {
forward[1] = 0;
glMatrix.vec3.normalize(forward,forward);
}
switch (keyCode) {
case 'w':
movementFlags = movementFlags | MovementDirection.FRONT;
break;
case 's' :
movementFlags = movementFlags | MovementDirection.BACK;
break;
case 'a':
movementFlags = movementFlags | MovementDirection.LEFT;
break;
case 'd':
movementFlags = movementFlags | MovementDirection.RIGHT;
break;
case 'r':
movementFlags = movementFlags | MovementDirection.UP;
break;
case 'f':
movementFlags = movementFlags | MovementDirection.DOWN;
}
}
function keyupHandler(e) {
var keyCode = e.key;
switch (keyCode) {
case 'w':
movementFlags = movementFlags & ~MovementDirection.FRONT;
break;
case 's' :
movementFlags = movementFlags & ~MovementDirection.BACK;
break;
case 'a':
movementFlags = movementFlags & ~MovementDirection.LEFT;
break;
case 'd':
movementFlags = movementFlags & ~MovementDirection.RIGHT;
break;
case 'r':
movementFlags = movementFlags & ~MovementDirection.UP;
break;
case 'f':
movementFlags = movementFlags & ~MovementDirection.DOWN;
}
}
function updateCameraPos() {
let sensMult = state.keyboardSens * currentDelta * 0.001;
var right = [viewMat[0]*sensMult, viewMat[4]*sensMult, viewMat[8]*sensMult];
var up = [0.0,-sensMult,0.0];
var forward = [viewMat[2], viewMat[6], viewMat[10]];
if (forward[2] !== 0 && forward[0] !== 0) {
forward[1] = 0;
glMatrix.vec3.normalize(forward,forward);
}
forward[0] *= sensMult;
forward[1] *= sensMult;
forward[2] *= sensMult;
if(movementFlags & MovementDirection.FRONT) {
camaraPos[0] -= forward[0];
camaraPos[1] -= forward[1];
camaraPos[2] -= forward[2];
}
if(movementFlags & MovementDirection.BACK) {
camaraPos[0] += forward[0];
camaraPos[1] += forward[1];
camaraPos[2] += forward[2];
}
if(movementFlags & MovementDirection.LEFT) {
camaraPos[0] -= right[0];
camaraPos[1] -= right[1];
camaraPos[2] -= right[2];
}
if(movementFlags & MovementDirection.RIGHT) {
camaraPos[0] += right[0];
camaraPos[1] += right[1];
camaraPos[2] += right[2];
}
if(movementFlags & MovementDirection.UP) {
camaraPos[0] -= up[0];
camaraPos[1] -= up[1];
camaraPos[2] -= up[2];
}
if(movementFlags & MovementDirection.DOWN) {
camaraPos[0] += up[0];
camaraPos[1] += up[1];
camaraPos[2] += up[2];
}
}
var modelJson = {};
var tfbuf = [];
function setupTFbuffers() {
gl.bindBuffer(gl.ARRAY_BUFFER, tfbuf[0]);
gl.bufferData(gl.ARRAY_BUFFER, meshVertexs.length*4, gl.DYNAMIC_COPY);
gl.bindBuffer(gl.ARRAY_BUFFER, tfbuf[1]);
gl.bufferData(gl.ARRAY_BUFFER, meshVertexs.length*4, gl.DYNAMIC_COPY);
gl.bindBuffer(gl.ARRAY_BUFFER, tfbuf[2]);
gl.bufferData(gl.ARRAY_BUFFER, meshNormals.length*4, gl.DYNAMIC_COPY);
gl.bindBuffer(gl.ARRAY_BUFFER, tfbuf[3]);
gl.bufferData(gl.ARRAY_BUFFER, meshNormals.length*4, gl.DYNAMIC_COPY);
}
//Init function
function init()
{
canvas = document.getElementById( "glCanvas" );
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
meshVertexs = modelJson.vertexs;
meshColors = modelJson.color;
meshIndexs = modelJson.faces;
meshNormals = modelJson.normals;
//Context Inicialization
try
{
gl = canvas.getContext("webgl2");
} catch (e)
{
alert("Your browser is not webgl2 compatible!!!") ;
throw "Unable to initialize WebGL2 context";
}
//Add events
canvas.addEventListener( "mousedown", mouseDown, false );
canvas.addEventListener( "mouseup", mouseUp, false );
canvas.addEventListener( "mouseout", mouseUp, false );
canvas.addEventListener( "mousemove", mouseMove, false );
window.addEventListener("keypress", eventHandler, false);
window.addEventListener("keyup", keyupHandler, false);
//Shader initialization
tfShaderProgram = new ShaderManager( );
tfShaderProgram.createShader( document.getElementById( "tfvs" ).text.trim(), gl.VERTEX_SHADER );
tfShaderProgram.createShader( document.getElementById( "tffs" ).text.trim(), gl.FRAGMENT_SHADER );
tfShaderProgram.createProg();
gl.transformFeedbackVaryings( tfShaderProgram.program, ["pos", "normal"], gl.SEPARATE_ATTRIBS );
tfShaderProgram.linkProg();
tfShaderProgram.useProg();
tfModelLoc = gl.getUniformLocation(tfShaderProgram.program, "model");
tfNormalMat = gl.getUniformLocation(tfShaderProgram.program, "normalMat");
tfNormalLoc = gl.getAttribLocation(tfShaderProgram.program, "normals");
tfPositionLoc = gl.getAttribLocation(tfShaderProgram.program, "position");
gl.enableVertexAttribArray(tfPositionLoc);
tfbuf = [gl.createBuffer(), gl.createBuffer(), gl.createBuffer(), gl.createBuffer()];
setupTFbuffers();
transformFeedback = gl.createTransformFeedback();
gl.bindTransformFeedback(gl.TRANSFORM_FEEDBACK, transformFeedback);
shaderProgram = new ShaderManager( );
shaderProgram.createShader( document.getElementById( "vs" ).text.trim(), gl.VERTEX_SHADER );
shaderProgram.createShader( document.getElementById( "fs" ).text.trim(), gl.FRAGMENT_SHADER );
shaderProgram.createProg();
shaderProgram.linkProg();
shaderProgram.useProg();
//Attach Matrices
projLoc = gl.getUniformLocation(shaderProgram.program, "projection");
viewLoc = gl.getUniformLocation(shaderProgram.program, "view");
modelLoc = gl.getUniformLocation(shaderProgram.program, "model");
camPosLoc = gl.getUniformLocation(shaderProgram.program, "camPos");
outlineWidthLoc = gl.getUniformLocation(shaderProgram.program, "outlineWidth");
nStripsLoc = gl.getUniformLocation(shaderProgram.program,"nStrips");
light1posLoc = gl.getUniformLocation(shaderProgram.program,"light1pos");
light1intLoc = gl.getUniformLocation(shaderProgram.program,"light1int");
light2dirLoc = gl.getUniformLocation(shaderProgram.program,"light2dir");
light2intLoc = gl.getUniformLocation(shaderProgram.program,"light2int");
//Connect Buffers
colorLoc = gl.getAttribLocation(shaderProgram.program, "color");
positionLoc = gl.getAttribLocation(shaderProgram.program, "position");
normalLoc = gl.getAttribLocation(shaderProgram.program, "normal");
phaseXLoc = gl.getUniformLocation(shaderProgram.program, "phaseX");
phaseYLoc = gl.getUniformLocation(shaderProgram.program, "phaseY");
instDistanceLoc = gl.getUniformLocation(shaderProgram.program, "distance");
numInstXLoc = gl.getUniformLocation(shaderProgram.program, "numInstancesX");
numInstYLoc = gl.getUniformLocation(shaderProgram.program, "numInstancesY");
gl.enableVertexAttribArray(colorLoc);
gl.enableVertexAttribArray(positionLoc);
gl.enableVertexAttribArray(normalLoc);
//Buffer creation
vertexBuff= gl.createBuffer ();
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuff);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(meshVertexs),gl.STATIC_DRAW);
colorBuff = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER,colorBuff);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(meshColors),gl.STATIC_DRAW);
normalBuff = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, normalBuff);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(meshNormals),gl.STATIC_DRAW);
indexBuff= gl.createBuffer ();
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuff);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER,new Uint16Array(meshIndexs), gl.STATIC_DRAW);
//Matrices setup
perspMat = glMatrix.mat4.create();
glMatrix.mat4.perspective(perspMat, 45, canvas.width/canvas.height, 0.1, 100);
modelMat = glMatrix.mat4.create();
viewMat = glMatrix.mat4.create();
glMatrix.mat4.fromTranslation(viewMat, glMatrix.vec3.fromValues(-camaraPos[0], -camaraPos[1], -camaraPos[2]));
gl.uniformMatrix4fv(projLoc, false, perspMat);
gl.uniformMatrix4fv(viewLoc, false, viewMat);
gl.uniform3fv(camPosLoc, glMatrix.vec3.fromValues(camaraPos[0], camaraPos[1], camaraPos[2]));
gl.uniform1f(outlineWidthLoc, state.outlineWidth);
//Prepare render
gl.enable(gl.DEPTH_TEST);
gl.depthFunc(gl.LEQUAL);
gl.clearColor(0.0, 0.0, 0.0, 0.0);
gl.clearDepth(1.0);
draw(0);
}
//Draw funtion
function draw (time)
{
let newFrame = new Date().getTime();
currentDelta = newFrame-lastFrame;
lastFrame = newFrame;
gl.viewport(0.0, 0.0, canvas.width, canvas.height);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
//Transform feedback
let rotAngle = Math.sin(newFrame/1000);
let rotMat = glMatrix.mat4.create();
glMatrix.mat4.identity(rotMat);
glMatrix.mat4.rotate(rotMat,rotMat,rotAngle,glMatrix.vec3.fromValues(1,1,0));
let rotNormal = glMatrix.mat4.create();
glMatrix.mat4.invert(rotNormal, rotMat);
glMatrix.mat4.transpose(rotNormal, rotNormal);
tfShaderProgram.useProg();
gl.disable(gl.DEPTH_TEST);
gl.enable(gl.RASTERIZER_DISCARD);
gl.uniformMatrix4fv(tfModelLoc, false, rotMat);
gl.uniformMatrix4fv(tfNormalMat, false, rotNormal);
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuff);
gl.vertexAttribPointer(tfPositionLoc, 3, gl.FLOAT, gl.FALSE, 0, 0);
gl.bindBuffer(gl.ARRAY_BUFFER, normalBuff);
gl.vertexAttribPointer(tfNormalLoc, 3, gl.FLOAT, gl.FALSE, 0, 0);
gl.bindBufferBase(gl.TRANSFORM_FEEDBACK_BUFFER, 0, tfbuf[0]);
gl.bindBufferBase(gl.TRANSFORM_FEEDBACK_BUFFER, 1, tfbuf[2]);
gl.beginTransformFeedback(gl.POINTS);
gl.drawArrays(gl.POINTS, 0, meshVertexs.length/3);
gl.endTransformFeedback(gl.POINTS);
glMatrix.mat4.transpose(rotMat, rotMat);
glMatrix.mat4.invert(rotNormal, rotMat);
glMatrix.mat4.transpose(rotNormal, rotNormal);
gl.uniformMatrix4fv(tfModelLoc, false, rotMat);
gl.uniformMatrix4fv(tfNormalMat, false, rotNormal);
gl.bindBufferBase(gl.TRANSFORM_FEEDBACK_BUFFER, 0, tfbuf[1]);
gl.bindBufferBase(gl.TRANSFORM_FEEDBACK_BUFFER, 1, tfbuf[3]);
gl.beginTransformFeedback(gl.POINTS);
gl.drawArrays(gl.POINTS, 0, meshVertexs.length/3);
gl.endTransformFeedback(gl.POINTS);
gl.bindBufferBase(gl.TRANSFORM_FEEDBACK_BUFFER, 0, null);
gl.bindBufferBase(gl.TRANSFORM_FEEDBACK_BUFFER, 1, null);
gl.disable(gl.RASTERIZER_DISCARD);
gl.enable(gl.DEPTH_TEST);
shaderProgram.useProg();
updateCameraPos();
if (!drag) dX=dY=0;
//Matrix updates
glMatrix.mat4.identity(viewMat);
glMatrix.mat4.rotate(viewMat,viewMat,rotY,glMatrix.vec3.fromValues(1,0,0));
glMatrix.mat4.rotate(viewMat,viewMat,rotX,glMatrix.vec3.fromValues(0,1,0));
glMatrix.mat4.translate(viewMat,viewMat, glMatrix.vec3.fromValues(-camaraPos[0], -camaraPos[1], -camaraPos[2]));
//glMatrix.mat4.fromYRotation(modelMat, rotX);
// glMatrix.mat4.rotate(modelMat, modelMat, rotY, glMatrix.vec3.fromValues(1, 0, 0));
gl.uniformMatrix4fv(viewLoc, false, viewMat);
gl.uniformMatrix4fv(modelLoc, false, modelMat);
gl.uniform3fv(camPosLoc,glMatrix.vec3.fromValues(camaraPos[0],camaraPos[1],camaraPos[2]));
gl.uniform1f(outlineWidthLoc, state.outlineWidth);
gl.uniform1i(nStripsLoc,state.nStrips );
gl.uniform1i(numInstXLoc,state.instanceX );
gl.uniform1i(numInstYLoc,state.instanceY );
gl.uniform1f(instDistanceLoc, state.instanceDistance);
gl.uniform1f(phaseXLoc, 0);
gl.uniform1f(phaseYLoc, 0);
gl.uniform3fv(light1posLoc,glMatrix.vec3.fromValues(state.light1pos[0],state.light1pos[1],state.light1pos[2]));
gl.uniform3fv(light1intLoc,glMatrix.vec3.fromValues(state.light1int[0]/255,state.light1int[1]/255,state.light1int[2]/255));
gl.uniform3fv(light2dirLoc,glMatrix.vec3.fromValues(state.light2dir[0],state.light2dir[1],state.light2dir[2]));
gl.uniform3fv(light2intLoc,glMatrix.vec3.fromValues(state.light2int[0]/255,state.light2int[1]/255,state.light2int[2]/255));
//https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/vertexAttribPointer
var meshElementSize = 4 * 3; //4 bytes * (pos + color)
gl.bindBuffer(gl.ARRAY_BUFFER, tfbuf[0]);
gl.vertexAttribPointer(positionLoc, 3, gl.FLOAT, false, meshElementSize, 0 ) ;
gl.bindBuffer(gl.ARRAY_BUFFER, tfbuf[2]);
gl.vertexAttribPointer(normalLoc,3,gl.FLOAT,false,meshElementSize,0);
gl.bindBuffer(gl.ARRAY_BUFFER,colorBuff);
gl.vertexAttribPointer(colorLoc, 3, gl.FLOAT, false, meshElementSize, 0 ) ;
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuff);
//gl.drawElements(gl.TRIANGLES, meshIndexs.length , gl.UNSIGNED_SHORT, 0);
gl.drawElementsInstanced(gl.TRIANGLES, meshIndexs.length , gl.UNSIGNED_SHORT, 0, state.instanceX*state.instanceY);
gl.bindBuffer(gl.ARRAY_BUFFER, tfbuf[1]);
gl.vertexAttribPointer(positionLoc, 3, gl.FLOAT, false, meshElementSize, 0 ) ;
gl.bindBuffer(gl.ARRAY_BUFFER, tfbuf[3]);
gl.vertexAttribPointer(normalLoc,3,gl.FLOAT,false,meshElementSize,0);
gl.uniform1f(phaseXLoc, state.instancePhaseX);
gl.uniform1f(phaseYLoc, state.instancePhaseY);
//gl.drawElements(gl.TRIANGLES, meshIndexs.length , gl.UNSIGNED_SHORT, 0);
gl.drawElementsInstanced(gl.TRIANGLES, meshIndexs.length , gl.UNSIGNED_SHORT, 0, state.instanceX*state.instanceY);
//Hyper hack para que no falle el transform feedback. Unbind buffer a atributo
gl.bindBuffer(gl.ARRAY_BUFFER, normalBuff);
gl.vertexAttribPointer(normalLoc,3,gl.FLOAT,false,meshElementSize,0);
gl.flush();
window.requestAnimationFrame(draw);
};
function initGUI() {
var gui = new dat.GUI();
gui.add(state, 'outlineWidth', 0.1, 0.95);
gui.add(state, 'nStrips',2,50).step(1);
gui.add(state, 'keyboardSens',0.5,5).step(0.1);
let modelSelector = gui.add(state, 'model', ['bunny', 'cube', 'sphere', 'teapot', 'badcube', 'redbunny']);
modelSelector.onFinishChange(function(value) {
/*if(value == "cube") {
meshVertexs = cubeVertexPos;
meshIndexs = cubeTriangle;
meshNormals = cubeVertexNormal;
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuff);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(meshVertexs),gl.STATIC_DRAW);
gl.bindBuffer(gl.ARRAY_BUFFER, normalBuff);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(meshNormals),gl.STATIC_DRAW);
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuff);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER,new Uint16Array(meshIndexs), gl.STATIC_DRAW);
setupTFbuffers();
} else {*/
$.ajax({
url: value + ".json",
dataType: "json",
success: function(response) {
meshVertexs = response.vertexs;
meshColors = response.color;
meshIndexs = response.faces;
meshNormals = response.normals;
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuff);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(meshVertexs),gl.STATIC_DRAW);
gl.bindBuffer(gl.ARRAY_BUFFER,colorBuff);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(meshColors),gl.STATIC_DRAW);
gl.bindBuffer(gl.ARRAY_BUFFER, normalBuff);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(meshNormals),gl.STATIC_DRAW);
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuff);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER,new Uint16Array(meshIndexs), gl.STATIC_DRAW);
setupTFbuffers();
},
error: function(r, text, error) {
alert("Error " + error + " al cargar el modelo.\n" + text);
},
async: true
});
//}
});
const light1positions = gui.addFolder("Light 1 Pos");
light1positions.add(state.light1pos, 0).name("x");
light1positions.add(state.light1pos, 1).name("y");
light1positions.add(state.light1pos, 2).name("z");
gui.addColor(state, 'light1int').name("Light 1 color");
const light2positions = gui.addFolder("Light 2 Dir");
light2positions.add(state.light2dir, 0).name("x").step(0.1);
light2positions.add(state.light2dir, 1).name("y");
light2positions.add(state.light2dir, 2).name("z");
gui.addColor(state, 'light2int').name("Light 2 color");
const instancing = gui.addFolder("Instancing");
instancing.add(state, 'instancePhaseX', 0, 10).step(0.01);
instancing.add(state, 'instancePhaseY', 0, 10).step(0.01);
instancing.add(state, 'instanceDistance', 0, 10).step(0.01);
instancing.add(state, 'instanceX', 1, 100).step(1).name("Num instances X");
instancing.add(state, 'instanceY', 1, 100).step(1).name("Num instances Y");
}
$(window).ready(function() {
$.ajax({
url: state.model + ".json",
dataType: "json",
success: function(response) {
modelJson = response;
init();
initGUI();
},
error: function(r, text, error) {
alert("Error " + error + " al cargar el modelo.\n" + text);
},
async: true
});
});
</script>
</body>
</html>