forked from gfxfundamentals/webgl-fundamentals
-
Notifications
You must be signed in to change notification settings - Fork 0
/
webgl-less-code-more-fun.html
653 lines (579 loc) · 28.5 KB
/
webgl-less-code-more-fun.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
<!DOCTYPE html>
<!-- this file is auto-generated from webgl/lessons/webgl-less-code-more-fun.md. Do not edited directly -->
<!--
Copyright 2012, Gregg Tavares.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Gregg Tavares. nor the names of his
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, target-densitydpi=160dpi, initial-scale=1.0, user-scalable=yes">
<meta property="og:title" content="WebGL - Less Code, More Fun" />
<meta property="og:type" content="website" />
<meta property="og:image" content="http://webglfundamentals.org/webgl/lessons/resources/webglfundamentals.jpg" />
<meta property="og:description" content="Ways to make programming WebGL less verbose" />
<meta property="og:url" content="http://webglfundamentals.org/webgl/lessons/webgl-less-code-more-fun.html" />
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:site" content="@greggman" />
<meta name="twitter:creator" content="@greggman" />
<meta name="twitter:domain" content="webglfundamentals.org" />
<meta name="twitter:title" content="WebGL - Less Code, More Fun" />
<meta name="twitter:url" content="http://webglfundamentals.org/webgl/lessons/webgl-less-code-more-fun.html" />
<meta name="twitter:description" content="Ways to make programming WebGL less verbose" />
<meta name="twitter:image:src" content="http://webglfundamentals.org/webgl/lessons/resources/webglfundamentals.jpg" />
<title>WebGL - Less Code, More Fun</title>
<link href="/webgl/lessons/resources/webglfundamentals-icon.png" rel="shortcut icon" type="image/png">
<link rel="stylesheet" href="/webgl/lessons/resources/base.css" type="text/css" />
<link rel="stylesheet" href="/webgl/lessons/resources/lesson.css" type="text/css" />
</head>
<body>
<div class="webgl_header">
<h1><a href="/">WebGLFundamentals.org</a></h1>
</div>
<div class="container">
<div class="lesson-title">
<h1>WebGL - Less Code, More Fun</h1>
</div>
<div class="row">
<div class="col-sm-8 lesson-main">
<p>This post is a continuation of a series of posts about WebGL.
The first <a href="webgl-fundamentals.html">started with fundamentals</a>.
If you haven't read those please view them first.</p>
<p>WebGL programs require that you write shader programs which you have to compile and link and then
you have to look up the locations of the inputs to those shader programs. These inputs are called
uniforms and attributes and the code required to look up their locations can be wordy and tedious.</p>
<p>Assume we've got the <a href="webgl-boilerplate.html">typical boilerplate WebGL code for
compiling and linking shader programs</a>. Given a set of shaders like this.</p>
<p>vertex shader:</p>
<pre class="prettyprint">
uniform mat4 u_worldViewProjection;
uniform vec3 u_lightWorldPos;
uniform mat4 u_world;
uniform mat4 u_viewInverse;
uniform mat4 u_worldInverseTranspose;
attribute vec4 a_position;
attribute vec3 a_normal;
attribute vec2 a_texcoord;
varying vec4 v_position;
varying vec2 v_texCoord;
varying vec3 v_normal;
varying vec3 v_surfaceToLight;
varying vec3 v_surfaceToView;
void main() {
v_texCoord = a_texcoord;
v_position = (u_worldViewProjection * a_position);
v_normal = (u_worldInverseTranspose * vec4(a_normal, 0)).xyz;
v_surfaceToLight = u_lightWorldPos - (u_world * a_position).xyz;
v_surfaceToView = (u_viewInverse[3] - (u_world * a_position)).xyz;
gl_Position = v_position;
}
</pre>
<p>fragment shader:</p>
<pre class="prettyprint">
precision mediump float;
varying vec4 v_position;
varying vec2 v_texCoord;
varying vec3 v_normal;
varying vec3 v_surfaceToLight;
varying vec3 v_surfaceToView;
uniform vec4 u_lightColor;
uniform vec4 u_ambient;
uniform sampler2D u_diffuse;
uniform vec4 u_specular;
uniform float u_shininess;
uniform float u_specularFactor;
vec4 lit(float l ,float h, float m) {
return vec4(1.0,
max(l, 0.0),
(l > 0.0) ? pow(max(0.0, h), m) : 0.0,
1.0);
}
void main() {
vec4 diffuseColor = texture2D(u_diffuse, v_texCoord);
vec3 a_normal = normalize(v_normal);
vec3 surfaceToLight = normalize(v_surfaceToLight);
vec3 surfaceToView = normalize(v_surfaceToView);
vec3 halfVector = normalize(surfaceToLight + surfaceToView);
vec4 litR = lit(dot(a_normal, surfaceToLight),
dot(a_normal, halfVector), u_shininess);
vec4 outColor = vec4((
u_lightColor * (diffuseColor * litR.y + diffuseColor * u_ambient +
u_specular * litR.z * u_specularFactor)).rgb,
diffuseColor.a);
gl_FragColor = outColor;
}
</pre>
<p>You'd end up having to write code like this to look up and set all the various values to draw.</p>
<pre class="prettyprint">
// At initialization time
var u_worldViewProjectionLoc = gl.getUniformLocation(program, "u_worldViewProjection");
var u_lightWorldPosLoc = gl.getUniformLocation(program, "u_lightWorldPos");
var u_worldLoc = gl.getUniformLocation(program, "u_world");
var u_viewInverseLoc = gl.getUniformLocation(program, "u_viewInverse");
var u_worldInverseTransposeLoc = gl.getUniformLocation(program, "u_worldInverseTranspose");
var u_lightColorLoc = gl.getUniformLocation(program, "u_lightColor");
var u_ambientLoc = gl.getUniformLocation(program, "u_ambient");
var u_diffuseLoc = gl.getUniformLocation(program, "u_diffuse");
var u_specularLoc = gl.getUniformLocation(program, "u_specular");
var u_shininessLoc = gl.getUniformLocation(program, "u_shininess");
var u_specularFactorLoc = gl.getUniformLocation(program, "u_specularFactor");
var a_positionLoc = gl.getAttribLocation(program, "a_position");
var a_normalLoc = gl.getAttribLocation(program, "a_normal");
var a_texCoordLoc = gl.getAttribLocation(program, "a_texcoord");
// At init or draw time depending on use.
var someWorldViewProjectionMat = computeWorldViewProjectionMatrix();
var lightWorldPos = [100, 200, 300];
var worldMat = computeWorldMatrix();
var viewInverseMat = computeInverseViewMatrix();
var worldInverseTransposeMat = computeWorldInverseTransposeMatrix();
var lightColor = [1, 1, 1, 1];
var ambientColor = [0.1, 0.1, 0.1, 1];
var diffuseTextureUnit = 0;
var specularColor = [1, 1, 1, 1];
var shininess = 60;
var specularFactor = 1;
// At draw time
gl.useProgram(program);
// Setup all the buffers and attributes
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
gl.enableVertexAttribArray(a_positionLoc);
gl.vertexAttribPointer(a_positionLoc, positionNumComponents, gl.FLOAT, false, 0, 0);
gl.bindBuffer(gl.ARRAY_BUFFER, normalBuffer);
gl.enableVertexAttribArray(a_normalLoc);
gl.vertexAttribPointer(a_normalLoc, normalNumComponents, gl.FLOAT, false, 0, 0);
gl.bindBuffer(gl.ARRAY_BUFFER, texcoordBuffer);
gl.enableVertexAttribArray(a_texcoordLoc);
gl.vertexAttribPointer(a_texcoordLoc, texcoordNumComponents, gl.FLOAT, 0, 0);
// Setup the textures used
gl.activeTexture(gl.TEXTURE0 + diffuseTextureUnit);
gl.bindTexture(gl.TEXTURE_2D, diffuseTexture);
// Set all the uniforms.
gl.uniformMatrix4fv(u_worldViewProjectionLoc, false, someWorldViewProjectionMat);
gl.uniform3fv(u_lightWorldPosLoc, lightWorldPos);
gl.uniformMatrix4fv(u_worldLoc, worldMat);
gl.uniformMatrix4fv(u_viewInverseLoc, viewInverseMat);
gl.uniformMatrix4fv(u_worldInverseTransposeLoc, worldInverseTransposeMat);
gl.uniform4fv(u_lightColorLoc, lightColor);
gl.uniform4fv(u_ambientLoc, ambientColor);
gl.uniform1i(u_diffuseLoc, diffuseTextureUnit);
gl.uniform4fv(u_specularLoc, specularColor);
gl.uniform1f(u_shininessLoc, shininess);
gl.uniform1f(u_specularFactorLoc, specularFactor);
gl.drawArrays(...);
</pre>
<p>That's a lot of typing.</p>
<p>There are lots of ways to simplify this. One suggestion is to ask WebGL to tell us all
the uniforms and locations and then setup functions to set them for us. We can then pass in
JavaScript objects to set our settings much more easily. If that's clear as mud well,
our code would look something like this</p>
<pre class="prettyprint">
// At initialiation time
var uniformSetters = createUniformSetters(gl, program);
var attribSetters = createAttributeSetters(gl, program);
var attribs = {
a_position: { buffer: positionBuffer, numComponents: 3, },
a_normal: { buffer: normalBuffer, numComponents: 3, },
a_texcoord: { buffer: texcoordBuffer, numComponents: 2, },
};
// At init time or draw time depending on use.
var uniforms = {
u_worldViewProjection: computeWorldViewProjectionMatrix(...),
u_lightWorldPos: [100, 200, 300],
u_world: computeWorldMatrix(),
u_viewInverse: computeInverseViewMatrix(),
u_worldInverseTranspose: computeWorldInverseTransposeMatrix(),
u_lightColor: [1, 1, 1, 1],
u_ambient: [0.1, 0.1, 0.1, 1],
u_diffuse: diffuseTexture,
u_specular: [1, 1, 1, 1],
u_shininess: 60,
u_specularFactor: 1,
};
// At draw time
gl.useProgram(program);
// Setup all the buffers and attributes
setAttributes(attribSetters, attribs);
// Set all the uniforms and textures used.
setUniforms(uniformSetters, uniforms);
gl.drawArrays(...);
</pre>
<p>That seems a heck of a lot smaller, easier, and less code to me.</p>
<p>You can even use multiple JavaScript objects if it suits you. For example</p>
<pre class="prettyprint">
// At initialiation time
var uniformSetters = createUniformSetters(gl, program);
var attribSetters = createAttributeSetters(gl, program);
var attribs = {
a_position: { buffer: positionBuffer, numComponents: 3, },
a_normal: { buffer: normalBuffer, numComponents: 3, },
a_texcoord: { buffer: texcoordBuffer, numComponents: 2, },
};
// At init time or draw time depending
var uniformsThatAreTheSameForAllObjects = {
u_lightWorldPos: [100, 200, 300],
u_viewInverse: computeInverseViewMatrix(),
u_lightColor: [1, 1, 1, 1],
};
var uniformsThatAreComputedForEachObject = {
u_worldViewProjection: perspective(...),
u_world: computeWorldMatrix(),
u_worldInverseTranspose: computeWorldInverseTransposeMatrix(),
};
var objects = [
{ translation: [10, 50, 100],
materialUniforms: {
u_ambient: [0.1, 0.1, 0.1, 1],
u_diffuse: diffuseTexture,
u_specular: [1, 1, 1, 1],
u_shininess: 60,
u_specularFactor: 1,
},
},
{ translation: [-120, 20, 44],
materialUniforms: {
u_ambient: [0.1, 0.2, 0.1, 1],
u_diffuse: someOtherDiffuseTexture,
u_specular: [1, 1, 0, 1],
u_shininess: 30,
u_specularFactor: 0.5,
},
},
{ translation: [200, -23, -78],
materialUniforms: {
u_ambient: [0.2, 0.2, 0.1, 1],
u_diffuse: yetAnotherDiffuseTexture,
u_specular: [1, 0, 0, 1],
u_shininess: 45,
u_specularFactor: 0.7,
},
},
];
// At draw time
gl.useProgram(program);
// Setup the parts that are common for all objects
setAttributes(attribSetters, attribs);
setUniforms(uniformSetters, uniformThatAreTheSameForAllObjects);
objects.forEach(function(object) {
computeMatricesForObject(object, uniformsThatAreComputedForEachObject);
setUniforms(uniformSetters, uniformThatAreComputedForEachObject);
setUniforms(unifromSetters, objects.materialUniforms);
gl.drawArrays(...);
});
</pre>
<p>Here's an example using these helper functions</p>
<p><div>
<iframe class="webgl_example" style="width: 400px; height: 300px;" src="../webgl-less-code-more-fun.html"></iframe>
<a class="webgl_center" href="../webgl-less-code-more-fun.html" target="_blank">click here to open in a separate window</a>
</div>
</p>
<p>Let's take it a tiny step further. In the code above we setup a variable <code>attribs</code> with the buffers we created.
Not shown is the code to setup those buffers. For example if you want to make positions, normals and texture
coordinates you might need code like this</p>
<pre><code>// a single triangle
var positions = [0, -10, 0, 10, 10, 0, -10, 10, 0];
var texcoords = [0.5, 0, 1, 1, 0, 1];
var normals = [0, 0, 1, 0, 0, 1, 0, 0, 1];
var positionBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW);
var texcoordBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, texcoordsBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(texcoords), gl.STATIC_DRAW);
var normalBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, normalBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(normals), gl.STATIC_DRAW);
</code></pre><p>Looks like a pattern we can simplify as well.</p>
<pre><code>// a single triangle
var arrays = {
position: { numComponents: 3, data: [0, -10, 0, 10, 10, 0, -10, 10, 0], },
texcoord: { numComponents: 2, data: [0.5, 0, 1, 1, 0, 1], },
normal: { numComponents: 3, data: [0, 0, 1, 0, 0, 1, 0, 0, 1], },
};
var bufferInfo = createBufferInfoFromArrays(gl, arrays);
</code></pre><p>Much shorter! Now we can do this at render time</p>
<pre><code>// Setup all the needed buffers and attributes.
setBuffersAndAttributes(gl, attribSetters, bufferInfo);
...
// Draw the geometry.
gl.drawArrays(gl.TRIANGLES, 0, bufferInfo.numElements);
</code></pre><p>Here's that</p>
<p><div>
<iframe class="webgl_example" style="width: 400px; height: 300px;" src="../webgl-less-code-more-fun-triangle.html"></iframe>
<a class="webgl_center" href="../webgl-less-code-more-fun-triangle.html" target="_blank">click here to open in a separate window</a>
</div>
</p>
<p>This will even work if we have indices. setAttribsAndBuffers will set all the attributes
and setup the <code>ELEMENT_ARRAY_BUFFER</code> with your <code>indices</code> so you can call <code>gl.drawElements</code>.</p>
<pre><code>// an indexed quad
var arrays = {
position: { numComponents: 3, data: [0, 0, 0, 10, 0, 0, 0, 10, 0, 10, 10, 0], },
texcoord: { numComponents: 2, data: [0, 0, 0, 1, 1, 0, 1, 1], },
normal: { numComponents: 3, data: [0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1], },
indices: { numComponents: 3, data: [0, 1, 2, 1, 2, 3], },
};
var bufferInfo = createBufferInfoFromTypedArray(gl, arrays);
</code></pre><p>and at render time we can call <code>gl.drawElements</code> instead of <code>gl.drawArrays</code>.</p>
<pre><code>// Setup all the needed buffers and attributes.
setBuffersAndAttributes(gl, attribSetters, bufferInfo);
...
// Draw the geometry.
gl.drawElements(gl.TRIANGLES, bufferInfo.numElements, gl.UNSIGNED_SHORT, 0);
</code></pre><p>Here's that</p>
<p><div>
<iframe class="webgl_example" style="width: 400px; height: 300px;" src="../webgl-less-code-more-fun-quad.html"></iframe>
<a class="webgl_center" href="../webgl-less-code-more-fun-quad.html" target="_blank">click here to open in a separate window</a>
</div>
</p>
<p><code>createBufferInfoFromArrays</code> basically makes an object that looks like this</p>
<pre><code> bufferInfo = {
numElements: 4, // or whatever the number of elements is
indices: WebGLBuffer, // this property will not exist if there are no indices
attribs: {
a_position: { buffer: WebGLBuffer, numComponents: 3, },
a_normal: { buffer: WebGLBuffer, numComponents: 3, },
a_texcoord: { buffer: WebGLBuffer, numComponents: 2, },
},
};
</code></pre><p>And <code>setBuffersAndAttributes</code> uses that object to set all the buffers and attributes.</p>
<p>Finally we can go what I consider possibly too far. Given <code>position</code> almost always has 3 components (x, y, z)
and <code>texcoords</code> almost always 2, indices 3, and normals 3, we can just let the system guess the number
of components.</p>
<pre><code>// an indexed quad
var arrays = {
position: [0, 0, 0, 10, 0, 0, 0, 10, 0, 10, 10, 0],
texcoord: [0, 0, 0, 1, 1, 0, 1, 1],
normal: [0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1],
indices: [0, 1, 2, 1, 2, 3],
};
</code></pre><p>And that version</p>
<p><div>
<iframe class="webgl_example" style="width: 400px; height: 300px;" src="../webgl-less-code-more-fun-quad-guess.html"></iframe>
<a class="webgl_center" href="../webgl-less-code-more-fun-quad-guess.html" target="_blank">click here to open in a separate window</a>
</div>
</p>
<p>I'm not sure I personally like that style. Guessing bugs me because it can guess wrong. For example
I might choose to stick an extra set of texture coordinates in my texcoord attribute and it will
guess 2 and be wrong. Of course if it guesses wrong you can just specify it like the example above.
I guess I worry if the guessing code changes people's stuff might break. It's up to you. Some people
like things to be what they consider as simple as possible.</p>
<p>Why don't we look at the attributes on the shader program to figure out the number of components?
That's because it's common to supply 3 components (x, y, z) from a buffer but use a <code>vec4</code> in
the shader. For attibutes WebGL will set <code>w = 1</code> automatically. But that means we can't easily
know the user's intent since what they declared in their shader might not match the number of
components they provide.</p>
<p>Looking for more patterns there's this</p>
<pre><code>var program = createProgramFromScripts(gl, ["vertexshader", "fragmentshader"]);
var uniformSetters = createUniformSetters(gl, program);
var attribSetters = createAttributeSetters(gl, program);
</code></pre><p>Let's simplify that too into just</p>
<pre><code>var programInfo = createProgramInfo(gl, ["vertexshader", "fragmentshader"]);
</code></pre><p>Which returns something like</p>
<pre><code>programInfo = {
program: WebGLProgram, // program we just compiled
uniformSetters: ..., // setters as returned from createUniformSetters,
attribSetters: ..., // setters as returned from createAttribSetters,
}
</code></pre><p>And that's yet one more minor simplification. This will come in handy once we start using
multiple programs since it automatically keeps the setters with the program they are associated with.</p>
<p><div>
<iframe class="webgl_example" style="width: 400px; height: 300px;" src="../webgl-less-code-more-fun-quad-programinfo.html"></iframe>
<a class="webgl_center" href="../webgl-less-code-more-fun-quad-programinfo.html" target="_blank">click here to open in a separate window</a>
</div>
</p>
<p>Anyway, this is the style I try to write my own WebGL programs.
For the lessons on these tutorials though I've felt like I have to use the standard <strong>verbose</strong>
ways so people don't get confused about what is WebGL and what is my own style. At some point
though showing all the steps gets in the way of the point so going forward some lessons will
be using this style.</p>
<p>Feel free to use this style in your own code. The functions <code>createUniformSetters</code>, <code>createAttributeSetters</code>,
<code>createBufferInfoFromArrays</code>, <code>setUniforms</code>, and <code>setBuffersAndAttributes</code> are included in the
<a href="https://github.com/greggman/webgl-fundamentals/blob/master/webgl/resources/webgl-utils.js"><code>webgl-utils.js</code></a>
file used by all the samples. If you want something slightly more organized check out <a href="http://twgljs.org">TWGL.js</a>.</p>
<p>Next up, <a href="webgl-drawing-multiple-things.html">drawing multiple things</a>.</p>
<div class="webgl_bottombar">
<h3>Can we use the setters directly?</h3>
<p>
For those of you familar with JavaScript you might be wondering if you can use the setters
directly like this.
</p>
<pre class="prettyprint">
// At initialiation time
var uniformSetters = createUniformSetters(program);
// At draw time
uniformSetters.u_ambient([1, 0, 0, 1]); // set the ambient color to red.
</pre>
<p>The reason this is not a good idea is because when you're working with GLSL you might
modify the shaders from time to time, often to debug. Let's say we were not seeing
anything on the screen in our program. One of the first things I do when nothing
is appearing is to simplify my shaders. For example I might change the fragment shader
to the simplest thing possible</p>
<pre class="prettyprint showlinemods">
// fragment shader
precision mediump float;
varying vec4 v_position;
varying vec2 v_texCoord;
varying vec3 v_normal;
varying vec3 v_surfaceToLight;
varying vec3 v_surfaceToView;
uniform vec4 u_lightColor;
uniform vec4 u_ambient;
uniform sampler2D u_diffuse;
uniform vec4 u_specular;
uniform float u_shininess;
uniform float u_specularFactor;
vec4 lit(float l ,float h, float m) {
return vec4(1.0,
max(l, 0.0),
(l > 0.0) ? pow(max(0.0, h), m) : 0.0,
1.0);
}
void main() {
vec4 diffuseColor = texture2D(u_diffuse, v_texCoord);
vec3 a_normal = normalize(v_normal);
vec3 surfaceToLight = normalize(v_surfaceToLight);
vec3 surfaceToView = normalize(v_surfaceToView);
vec3 halfVector = normalize(surfaceToLight + surfaceToView);
vec4 litR = lit(dot(a_normal, surfaceToLight),
dot(a_normal, halfVector), u_shininess);
vec4 outColor = vec4((
u_lightColor * (diffuseColor * litR.y + diffuseColor * u_ambient +
u_specular * litR.z * u_specularFactor)).rgb,
diffuseColor.a);
gl_FragColor = outColor;
* gl_FragColor = vec4(0,1,0,1); // <!--- just green
}
</pre>
<p>Notice I just added a line that sets <code>gl_FragColor</code> to a constant color.
Most drivers will see that none of the previous lines in the file actually contribute
to the result. As such they'll optimize out all of our uniforms. The next time we run the program
when we call <code>createUniformSetters</code> it won't create a setter for <code>u_ambient</code> so the
code above that calls <code>uniformSetters.u_ambient()</code> directly will fail with</p>
<pre class="prettyprint">
TypeError: undefined is not a function
</pre>
<p><code>setUniforms</code> solves that issue. It only sets those uniforms that actually exist</p>
</div>
<hr/>
<div>
<div>Questions? <a href="http://stackoverflow.com/questions/tagged/webgl">Ask on stackoverflow</a>.</div>
<div>Issue/Bug? <a href="http://github.com/greggman/webgl-fundamentals/issues">Create an issue on github</a>.</div>
<div id="disqus_thread"></div>
<script type="text/javascript">
/* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */
var disqus_shortname = 'webglfundamentals'; // required: replace example with your forum shortname
var disqus_identifier = 'WebGL - Less Code, More Fun';
var disqus_title = 'WebGL - Less Code, More Fun';
/* * * DON'T EDIT BELOW THIS LINE * * */
(function() {
if (window.location.hostname.indexOf("webglfundamentals.org") < 0) {
return;
}
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
</script>
<noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
<a href="http://disqus.com" class="dsq-brlink">comments powered by <span class="logo-disqus">Disqus</span></a>
</div>
</div>
<div class="col-sm-3 col-sm-offset-1 lesson-sidebar">
<select id="language">
</select>
<ul>
<li>Fundamentals</li>
<ul>
<li><a href="/webgl/lessons/webgl-fundamentals.html">WebGL Fundamentals</a></li>
<li><a href="/webgl/lessons/webgl-how-it-works.html">WebGL How It Works</a></li>
<li><a href="/webgl/lessons/webgl-shaders-and-glsl.html">WebGL Shaders and GLSL</a></li>
</ul>
<li>Image Processing</li>
<ul>
<li><a href="/webgl/lessons/webgl-image-processing.html">WebGL Image Processing</a></li>
<li><a href="/webgl/lessons/webgl-image-processing-continued.html">WebGL Image Processing Continued</a></li>
</ul>
<li>2D translation, rotation, scale, matrix math</li>
<ul>
<li><a href="/webgl/lessons/webgl-2d-translation.html">WebGL 2D Translation</a></li>
<li><a href="/webgl/lessons/webgl-2d-rotation.html">WebGL 2D Rotation</a></li>
<li><a href="/webgl/lessons/webgl-2d-scale.html">WebGL 2D Scale</a></li>
<li><a href="/webgl/lessons/webgl-2d-matrices.html">WebGL 2D Matrices</a></li>
</ul>
<li>3D</li>
<ul>
<li><a href="/webgl/lessons/webgl-3d-orthographic.html">WebGL - Orthographic 3D</a></li>
<li><a href="/webgl/lessons/webgl-3d-perspective.html">WebGL 3D Perspective</a></li>
<li><a href="/webgl/lessons/webgl-3d-camera.html">WebGL 3D - Cameras</a></li>
</ul>
<li>Structure and Organization</li>
<ul>
<li><a href="/webgl/lessons/webgl-less-code-more-fun.html">WebGL - Less Code, More Fun</a></li>
<li><a href="/webgl/lessons/webgl-drawing-multiple-things.html">WebGL - Drawing Multiple Things</a></li>
<li><a href="/webgl/lessons/webgl-scene-graph.html">WebGL - Scene Graphs</a></li>
</ul>
<li>Text</li>
<ul>
<li><a href="/webgl/lessons/webgl-text-html.html">WebGL Text - HTML</a>
<li><a href="/webgl/lessons/webgl-text-canvas2d.html">WebGL Text - Canvas 2D</a>
<li><a href="/webgl/lessons/webgl-text-texture.html">WebGL Text - Using a Texture</a>
<li><a href="/webgl/lessons/webgl-text-glyphs.html">WebGL Text - Using a Glyph Texture</a>
</ul>
<li>Misc</li>
<ul>
<li><a href="/webgl/lessons/webgl-boilerplate.html">WebGL Boilerplate</a></li>
<li><a href="/webgl/lessons/webgl-resizing-the-canvas.html">WebGL Resizing the Canvas</a></li>
<li><a href="/webgl/lessons/webgl-animation.html">WebGL - Animation</a></li>
<li><a href="/webgl/lessons/webgl-3d-textures.html">WebGL 3D - Textures</a></li>
<li><a href="/webgl/lessons/webgl-2-textures.html">WebGL Using 2 or More Textures</a></li>
<li><a href="/webgl/lessons/webgl-and-alpha.html">WebGL and Alpha</a></li>
<li><a href="/webgl/lessons/webgl-2d-vs-3d-library.html">WebGL - 2D vs 3D libraries</a></li>
<li><a href="/webgl/lessons/webgl-anti-patterns.html">WebGL - Anti-Patterns</a></li>
</ul>
</ul>
<ul>
<li><a href="/docs/">Helper API Docs</a></li>
<li><a href="http://twgljs.org">TWGL, A tiny WebGL helper library</a></li>
<li><a href="https://github.com/greggman/webgl-fundamentals">github</a></li>
</ul>
</div>
</div>
</div>
</body>
<script src="/3rdparty/jquery-1.11.2.min.js"></script>
<script src="/webgl/lessons/resources/prettify.js"></script>
<script src="/webgl/lessons/resources/lesson.js"></script>
<script src="/langdb.js"></script>
<script src="/webgl/lessons/resources/languages.js"></script>
<script src="//cdn.webglstats.com/stat.js" defer="defer" async="async"></script>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-59804936-1', 'auto');
ga('send', 'pageview');
</script>
</html>