-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtwgl.ts
2577 lines (2428 loc) · 104 KB
/
twgl.ts
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
/**
* The main TWGL module.
*
* @module twgl
*/
export module twgl {
export interface IShader {
vertex: string;
fragment: string;
}
export class TextureOptions {
src: any;
target: number; //gl.TEXTURE_2D;
width: number;
height: number;
color: boolean; // optional
/*
* texture filtering or generate mips based on the dimensions of the element
* unless `options.auto === false`.If `target === gl.TEXTURE_CUBE_MAP` will
* attempt to slice image into 1x6, 2x3, 3x2, or 6x1 images, one for each face.
*/
auto: boolean; // optional
constructor(src?: string) {
this.src = src;
}
}
type TextureLoadedCallback = (err: any, tex: WebGLTexture, image: HTMLImageElement) => any;
export interface IProgramInfo {
program: any;
uniformSetters: any;
attribSetters: any;
}
export class BufferInfo {
attribs: BufferAttributes;
indices: WebGLBuffer;
numElements: number;
elementType: number; //gl.UNSIGNED_INT : gl.UNSIGNED_SHORT;
remove(gl: WebGLRenderingContext) {
gl.deleteBuffer(this.indices);
this.indices = undefined;
for (var attrName in this.attribs) {
var attr = this.attribs[attrName];
gl.deleteBuffer(attr.buffer);
}
this.attribs = undefined;
}
}
export class BufferAttributes {
[key: string]: IBufferAttribute;
}
export interface IBufferAttribute {
buffer: WebGLBuffer;
numComponents: number;
type: number; // getGLTypeForTypedArray(typedArray),
normalize: boolean;
stride: number;
offset: number;
drawType: number;
}
var error = window.console && window.console.error ? window.console.error.bind(window.console) : function () { };
// make sure we don't see a global gl
var gl = undefined; // eslint-disable-line
var defaultAttribPrefix = "";
var defaultTextureColor = new Uint8Array([128, 192, 255, 255]);
var defaultTextureOptions = new TextureOptions();
/* DataType */
var BYTE = 0x1400;
var UNSIGNED_BYTE = 0x1401;
var SHORT = 0x1402;
var UNSIGNED_SHORT = 0x1403;
var INT = 0x1404;
var UNSIGNED_INT = 0x1405;
var FLOAT = 0x1406;
/* PixelFormat */
var DEPTH_COMPONENT = 0x1902;
var ALPHA = 0x1906;
var RGB = 0x1907;
var RGBA = 0x1908;
var LUMINANCE = 0x1909;
var LUMINANCE_ALPHA = 0x190A;
/* Framebuffer Object. */
var RGBA4 = 0x8056;
var RGB5_A1 = 0x8057;
var RGB565 = 0x8D62;
var DEPTH_COMPONENT16 = 0x81A5;
var STENCIL_INDEX = 0x1901;
var STENCIL_INDEX8 = 0x8D48;
var DEPTH_STENCIL = 0x84F9;
var COLOR_ATTACHMENT0 = 0x8CE0;
var DEPTH_ATTACHMENT = 0x8D00;
var STENCIL_ATTACHMENT = 0x8D20;
var DEPTH_STENCIL_ATTACHMENT = 0x821A;
/* TextureWrapMode */
var REPEAT = 0x2901; // eslint-disable-line
var CLAMP_TO_EDGE = 0x812F;
var MIRRORED_REPEAT = 0x8370; // eslint-disable-line
/* TextureMagFilter */
var NEAREST = 0x2600; // eslint-disable-line
var LINEAR = 0x2601;
/* TextureMinFilter */
var NEAREST_MIPMAP_NEAREST = 0x2700; // eslint-disable-line
var LINEAR_MIPMAP_NEAREST = 0x2701; // eslint-disable-line
var NEAREST_MIPMAP_LINEAR = 0x2702; // eslint-disable-line
var LINEAR_MIPMAP_LINEAR = 0x2703; // eslint-disable-line
/**
* Sets the default texture color.
*
* The default texture color is used when loading textures from
* urls. Because the URL will be loaded async we'd like to be
* able to use the texture immediately. By putting a 1x1 pixel
* color in the texture we can start using the texture before
* the URL has loaded.
*
* @param {number[]} color Array of 4 values in the range 0 to 1
* @memberOf module:twgl
*/
export function setDefaultTextureColor(color) {
defaultTextureColor = new Uint8Array([color[0] * 255, color[1] * 255, color[2] * 255, color[3] * 255]);
}
/**
* Sets the default attrib prefix
*
* When writing shaders I prefer to name attributes with `a_`, uniforms with `u_` and varyings with `v_`
* as it makes it clear where they came from. But, when building geometry I prefer using unprefixed names.
*
* In otherwords I'll create arrays of geometry like this
*
* var arrays = {
* position: ...
* normal: ...
* texcoord: ...
* };
*
* But need those mapped to attributes and my attributes start with `a_`.
*
* @param {string} prefix prefix for attribs
* @memberOf module:twgl
*/
export function setAttributePrefix(prefix) {
defaultAttribPrefix = prefix;
}
/**
* Gets a string for gl enum
*
* Note: Several enums are the same. Without more
* context (which function) it's impossible to always
* give the correct enum.
*
* @param {WebGLRenderingContext} gl A WebGLRenderingContext
* @param {number} value the value of the enum you want to look up.
*/
var glEnumToString_enums;
export function glEnumToString(gl, value: number) {
if (!glEnumToString_enums) {
glEnumToString_enums = {};
Object.keys(gl).forEach(function (key) {
if (typeof gl[key] === 'number') {
glEnumToString_enums[gl[key]] = key;
}
});
}
return glEnumToString_enums[value] || ("0x" + value.toString(16));
};
/**
* Creates a webgl context.
* @param {HTMLCanvasElement} canvas The canvas tag to get
* context from. If one is not passed in one will be
* created.
* @return {WebGLRenderingContext} The created context.
*/
export function create3DContext(canvas, opt_attribs?) {
var names = ["webgl", "experimental-webgl"];
var context = null;
for (var ii = 0; ii < names.length; ++ii) {
try {
context = canvas.getContext(names[ii], opt_attribs);
} catch (e) { } // eslint-disable-line
if (context) {
break;
}
}
return context;
}
/**
* Gets a WebGL context.
* @param {HTMLCanvasElement} canvas a canvas element.
* @param {WebGLContextCreationAttirbutes} [opt_attribs] optional webgl context creation attributes
* @memberOf module:twgl
*/
export function getWebGLContext(canvas, opt_attribs?): WebGLRenderingContext {
var gl = create3DContext(canvas, opt_attribs);
return gl;
}
/**
* Error Callback
* @callback ErrorCallback
* @param {string} msg error message.
* @memberOf module:twgl
*/
export function addLineNumbers(src) {
return src.split("\n").map(function (line, ndx) {
return (ndx + 1) + ": " + line;
}).join("\n");
}
/**
* Loads a shader.
* @param {WebGLRenderingContext} gl The WebGLRenderingContext to use.
* @param {string} shaderSource The shader source.
* @param {number} shaderType The type of shader.
* @param {module:twgl.ErrorCallback} opt_errorCallback callback for errors.
* @return {WebGLShader} The created shader.
*/
export function loadShader(gl, shaderSource, shaderType, opt_errorCallback) {
var errFn = opt_errorCallback || error;
// Create the shader object
var shader = gl.createShader(shaderType);
// Load the shader source
gl.shaderSource(shader, shaderSource);
// Compile the shader
gl.compileShader(shader);
// Check the compile status
var compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
if (!compiled) {
// Something went wrong during compilation; get the error
var lastError = gl.getShaderInfoLog(shader);
errFn(addLineNumbers(shaderSource) + "\n*** Error compiling shader: " + lastError);
gl.deleteShader(shader);
return null;
}
return shader;
}
/**
* Creates a program, attaches shaders, binds attrib locations, links the
* program and calls useProgram.
* @param {WebGLShader[]} shaders The shaders to attach
* @param {string[]} [opt_attribs] An array of attribs names. Locations will be assigned by index if not passed in
* @param {number[]} [opt_locations] The locations for the. A parallel array to opt_attribs letting you assign locations.
* @param {module:twgl.ErrorCallback} [opt_errorCallback] callback for errors. By default it just prints an error to the console
* on error. If you want something else pass an callback. It's passed an error message.
* @return {WebGLProgram?} the created program or null if error.
* @memberOf module:twgl
*/
export function createProgram(
gl, shaders, opt_attribs, opt_locations, opt_errorCallback) {
var errFn = opt_errorCallback || error;
var program = gl.createProgram();
shaders.forEach(function (shader) {
gl.attachShader(program, shader);
});
if (opt_attribs) {
opt_attribs.forEach(function (attrib, ndx) {
gl.bindAttribLocation(
program,
opt_locations ? opt_locations[ndx] : ndx,
attrib);
});
}
gl.linkProgram(program);
// Check the link status
var linked = gl.getProgramParameter(program, gl.LINK_STATUS);
if (!linked) {
// something went wrong with the link
var lastError = gl.getProgramInfoLog(program);
errFn("Error in program linking:" + lastError);
gl.deleteProgram(program);
return null;
}
return program;
}
/**
* Loads a shader from a script tag.
* @param {WebGLRenderingContext} gl The WebGLRenderingContext to use.
* @param {string} scriptId The id of the script tag.
* @param {number} [opt_shaderType] The type of shader. If not passed in it will
* be derived from the type of the script tag.
* @param {module:twgl.ErrorCallback} [opt_errorCallback] callback for errors.
* @return {WebGLShader?} The created shader or null if error.
*/
export function createShaderFromScript(
gl, scriptId, opt_shaderType, opt_errorCallback) {
var shaderSource = "";
var shaderType;
var shaderScript = <HTMLScriptElement>document.getElementById(scriptId);
if (!shaderScript) {
throw "*** Error: unknown script element" + scriptId;
}
shaderSource = shaderScript.text;
if (!opt_shaderType) {
if (shaderScript.type === "x-shader/x-vertex") {
shaderType = gl.VERTEX_SHADER;
} else if (shaderScript.type === "x-shader/x-fragment") {
shaderType = gl.FRAGMENT_SHADER;
} else if (shaderType !== gl.VERTEX_SHADER && shaderType !== gl.FRAGMENT_SHADER) {
throw "*** Error: unknown shader type";
}
}
return loadShader(
gl, shaderSource, opt_shaderType ? opt_shaderType : shaderType,
opt_errorCallback);
}
var defaultShaderType = [
"VERTEX_SHADER",
"FRAGMENT_SHADER",
];
/**
* Creates a program from 2 script tags.
*
* @param {WebGLRenderingContext} gl The WebGLRenderingContext
* to use.
* @param {string[]} shaderScriptIds Array of ids of the script
* tags for the shaders. The first is assumed to be the
* vertex shader, the second the fragment shader.
* @param {string[]} [opt_attribs] An array of attribs names. Locations will be assigned by index if not passed in
* @param {number[]} [opt_locations] The locations for the. A parallel array to opt_attribs letting you assign locations.
* @param {module:twgl.ErrorCallback} opt_errorCallback callback for errors. By default it just prints an error to the console
* on error. If you want something else pass an callback. It's passed an error message.
* @return {WebGLProgram} The created program.
* @memberOf module:twgl
*/
export function createProgramFromScripts(
gl, shaderScriptIds, opt_attribs, opt_locations, opt_errorCallback) {
var shaders = [];
for (var ii = 0; ii < shaderScriptIds.length; ++ii) {
var shader = createShaderFromScript(
gl, shaderScriptIds[ii], gl[defaultShaderType[ii]], opt_errorCallback);
if (!shader) {
return null;
}
shaders.push(shader);
}
return createProgram(gl, shaders, opt_attribs, opt_locations, opt_errorCallback);
}
/**
* Creates a program from 2 sources.
*
* @param {WebGLRenderingContext} gl The WebGLRenderingContext
* to use.
* @param {string[]} shaderSourcess Array of sources for the
* shaders. The first is assumed to be the vertex shader,
* the second the fragment shader.
* @param {string[]} [opt_attribs] An array of attribs names. Locations will be assigned by index if not passed in
* @param {number[]} [opt_locations] The locations for the. A parallel array to opt_attribs letting you assign locations.
* @param {module:twgl.ErrorCallback} opt_errorCallback callback for errors. By default it just prints an error to the console
* on error. If you want something else pass an callback. It's passed an error message.
* @return {WebGLProgram} The created program.
* @memberOf module:twgl
*/
export function createProgramFromSources(
gl, shaderSources: IShader, opt_attribs, opt_locations, opt_errorCallback) {
var shaders = [];
var vshader = loadShader(
gl, shaderSources.vertex, gl[defaultShaderType[0]], opt_errorCallback);
if (!vshader) {
return null;
}
var fshader = loadShader(
gl, shaderSources.fragment, gl[defaultShaderType[1]], opt_errorCallback);
if (!fshader) {
return null;
}
shaders.push(vshader);
shaders.push(fshader);
return createProgram(gl, shaders, opt_attribs, opt_locations, opt_errorCallback);
}
/**
* Returns the corresponding bind point for a given sampler type
*/
export function getBindPointForSamplerType(gl, type) {
if (type === gl.SAMPLER_2D) {
return gl.TEXTURE_2D;
}
if (type === gl.SAMPLER_CUBE) {
return gl.TEXTURE_CUBE_MAP;
}
}
/**
* @typedef {Object.<string,function>} Setters
*/
/**
* Creates setter functions for all uniforms of a shader
* program.
*
* @see {@link module:twgl.setUniforms}
*
* @param {WebGLProgram} program the program to create setters for.
* @returns {Object.<string, function>} an object with a setter by name for each uniform
* @memberOf module:twgl
*/
export function createUniformSetters(gl, program) {
var textureUnit = 0;
/**
* Creates a setter for a uniform of the given program with it's
* location embedded in the setter.
* @param {WebGLProgram} program
* @param {WebGLUniformInfo} uniformInfo
* @returns {function} the created setter.
*/
function createUniformSetter(program, uniformInfo) {
var location = gl.getUniformLocation(program, uniformInfo.name);
var type = uniformInfo.type;
// Check if this uniform is an array
var isArray = (uniformInfo.size > 1 && uniformInfo.name.substr(-3) === "[0]");
if (type === gl.FLOAT && isArray) {
return function (v) {
gl.uniform1fv(location, v);
};
}
if (type === gl.FLOAT) {
return function (v) {
gl.uniform1f(location, v);
};
}
if (type === gl.FLOAT_VEC2) {
return function (v) {
gl.uniform2fv(location, v);
};
}
if (type === gl.FLOAT_VEC3) {
return function (v) {
gl.uniform3fv(location, v);
};
}
if (type === gl.FLOAT_VEC4) {
return function (v) {
gl.uniform4fv(location, v);
};
}
if (type === gl.INT && isArray) {
return function (v) {
gl.uniform1iv(location, v);
};
}
if (type === gl.INT) {
return function (v) {
gl.uniform1i(location, v);
};
}
if (type === gl.INT_VEC2) {
return function (v) {
gl.uniform2iv(location, v);
};
}
if (type === gl.INT_VEC3) {
return function (v) {
gl.uniform3iv(location, v);
};
}
if (type === gl.INT_VEC4) {
return function (v) {
gl.uniform4iv(location, v);
};
}
if (type === gl.BOOL && isArray) {
return function (v) {
gl.uniform1iv(location, v);
};
}
if (type === gl.BOOL) {
return function (v) {
gl.uniform1i(location, v);
};
}
if (type === gl.BOOL_VEC2) {
return function (v) {
gl.uniform2iv(location, v);
};
}
if (type === gl.BOOL_VEC3) {
return function (v) {
gl.uniform3iv(location, v);
};
}
if (type === gl.BOOL_VEC4) {
return function (v) {
gl.uniform4iv(location, v);
};
}
if (type === gl.FLOAT_MAT2) {
return function (v) {
gl.uniformMatrix2fv(location, false, v);
};
}
if (type === gl.FLOAT_MAT3) {
return function (v) {
gl.uniformMatrix3fv(location, false, v);
};
}
if (type === gl.FLOAT_MAT4) {
return function (v) {
gl.uniformMatrix4fv(location, false, v);
};
}
if ((type === gl.SAMPLER_2D || type === gl.SAMPLER_CUBE) && isArray) {
var units = [];
for (var ii = 0; ii < uniformInfo.size; ++ii) {
units.push(textureUnit++);
}
return function (bindPoint, units) {
return function (textures) {
gl.uniform1iv(location, units);
textures.forEach(function (texture, index) {
gl.activeTexture(gl.TEXTURE0 + units[index]);
gl.bindTexture(bindPoint, texture);
});
};
} (getBindPointForSamplerType(gl, type), units);
}
if (type === gl.SAMPLER_2D || type === gl.SAMPLER_CUBE) {
return function (bindPoint, unit) {
return function (texture) {
gl.uniform1i(location, unit);
gl.activeTexture(gl.TEXTURE0 + unit);
gl.bindTexture(bindPoint, texture);
};
} (getBindPointForSamplerType(gl, type), textureUnit++);
}
throw ("unknown type: 0x" + type.toString(16)); // we should never get here.
}
var uniformSetters = {};
var numUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
for (var ii = 0; ii < numUniforms; ++ii) {
var uniformInfo = gl.getActiveUniform(program, ii);
if (!uniformInfo) {
break;
}
var name = uniformInfo.name;
// remove the array suffix.
if (name.substr(-3) === "[0]") {
name = name.substr(0, name.length - 3);
}
var setter = createUniformSetter(program, uniformInfo);
uniformSetters[name] = setter;
}
return uniformSetters;
}
/**
* Set uniforms and binds related textures.
*
* example:
*
* var programInfo = createProgramInfo(
* gl, ["some-vs", "some-fs");
*
* var tex1 = gl.createTexture();
* var tex2 = gl.createTexture();
*
* ... assume we setup the textures with data ...
*
* var uniforms = {
* u_someSampler: tex1,
* u_someOtherSampler: tex2,
* u_someColor: [1,0,0,1],
* u_somePosition: [0,1,1],
* u_someMatrix: [
* 1,0,0,0,
* 0,1,0,0,
* 0,0,1,0,
* 0,0,0,0,
* ],
* };
*
* gl.useProgram(program);
*
* This will automatically bind the textures AND set the
* uniforms.
*
* setUniforms(programInfo, uniforms);
*
* For the example above it is equivalent to
*
* var texUnit = 0;
* gl.activeTexture(gl.TEXTURE0 + texUnit);
* gl.bindTexture(gl.TEXTURE_2D, tex1);
* gl.uniform1i(u_someSamplerLocation, texUnit++);
* gl.activeTexture(gl.TEXTURE0 + texUnit);
* gl.bindTexture(gl.TEXTURE_2D, tex2);
* gl.uniform1i(u_someSamplerLocation, texUnit++);
* gl.uniform4fv(u_someColorLocation, [1, 0, 0, 1]);
* gl.uniform3fv(u_somePositionLocation, [0, 1, 1]);
* gl.uniformMatrix4fv(u_someMatrix, false, [
* 1,0,0,0,
* 0,1,0,0,
* 0,0,1,0,
* 0,0,0,0,
* ]);
*
* Note it is perfectly reasonable to call `setUniforms` multiple times. For example
*
* var uniforms = {
* u_someSampler: tex1,
* u_someOtherSampler: tex2,
* };
*
* var moreUniforms {
* u_someColor: [1,0,0,1],
* u_somePosition: [0,1,1],
* u_someMatrix: [
* 1,0,0,0,
* 0,1,0,0,
* 0,0,1,0,
* 0,0,0,0,
* ],
* };
*
* setUniforms(programInfo, uniforms);
* setUniforms(programInfo, moreUniforms);
*
* @param {(module:twgl.ProgramInfo|Object.<string, function>)} setters a `ProgramInfo` as returned from `createProgramInfo` or the setters returned from
* `createUniformSetters`.
* @param {Object.<string, ?>} values an object with values for the
* uniforms.
* You can pass multiple objects by putting them in an array or by calling with more arguments.For example
*
* var sharedUniforms = {
* u_fogNear: 10,
* u_projection: ...
* ...
* };
*
* var localUniforms = {
* u_world: ...
* u_diffuseColor: ...
* };
*
* twgl.setUniforms(programInfo, sharedUniforms, localUniforms);
*
* // is the same as
*
* twgl.setUniforms(programInfo, [sharedUniforms, localUniforms]);
*
* // is the same as
*
* twgl.setUniforms(programInfo, sharedUniforms);
* twgl.setUniforms(programInfo, localUniforms};
*
* @memberOf module:twgl
*/
export function setUniforms(setters, values) { // eslint-disable-line
setters = setters.uniformSetters || setters;
var numArgs = arguments.length;
for (var andx = 1; andx < numArgs; ++andx) {
var vals = arguments[andx];
if (Array.isArray(vals)) {
var numValues = vals.length;
for (var ii = 0; ii < numValues; ++ii) {
setUniforms(setters, vals[ii]);
}
} else {
for (var name in vals) {
var setter = setters[name];
if (setter) {
setter(vals[name]);
}
}
}
}
}
/**
* Creates setter functions for all attributes of a shader
* program. You can pass this to {@link module:twgl.setBuffersAndAttributes} to set all your buffers and attributes.
*
* @see {@link module:twgl.setAttributes} for example
* @param {WebGLProgram} program the program to create setters for.
* @return {Object.<string, function>} an object with a setter for each attribute by name.
* @memberOf module:twgl
*/
export function createAttributeSetters(gl, program) {
var attribSetters = {
};
function createAttribSetter(index) {
return function (b) {
gl.bindBuffer(gl.ARRAY_BUFFER, b.buffer);
gl.enableVertexAttribArray(index);
gl.vertexAttribPointer(
index, b.numComponents || b.size, b.type || gl.FLOAT, b.normalize || false, b.stride || 0, b.offset || 0);
};
}
var numAttribs = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES);
for (var ii = 0; ii < numAttribs; ++ii) {
var attribInfo = gl.getActiveAttrib(program, ii);
if (!attribInfo) {
break;
}
var index = gl.getAttribLocation(program, attribInfo.name);
attribSetters[attribInfo.name] = createAttribSetter(index);
}
return attribSetters;
}
/**
* Sets attributes and binds buffers (deprecated... use {@link module:twgl.setBuffersAndAttributes})
*
* Example:
*
* var program = createProgramFromScripts(
* gl, ["some-vs", "some-fs");
*
* var attribSetters = createAttributeSetters(program);
*
* var positionBuffer = gl.createBuffer();
* var texcoordBuffer = gl.createBuffer();
*
* var attribs = {
* a_position: {buffer: positionBuffer, numComponents: 3},
* a_texcoord: {buffer: texcoordBuffer, numComponents: 2},
* };
*
* gl.useProgram(program);
*
* This will automatically bind the buffers AND set the
* attributes.
*
* setAttributes(attribSetters, attribs);
*
* Properties of attribs. For each attrib you can add
* properties:
*
* * type: the type of data in the buffer. Default = gl.FLOAT
* * normalize: whether or not to normalize the data. Default = false
* * stride: the stride. Default = 0
* * offset: offset into the buffer. Default = 0
*
* For example if you had 3 value float positions, 2 value
* float texcoord and 4 value uint8 colors you'd setup your
* attribs like this
*
* var attribs = {
* a_position: {buffer: positionBuffer, numComponents: 3},
* a_texcoord: {buffer: texcoordBuffer, numComponents: 2},
* a_color: {
* buffer: colorBuffer,
* numComponents: 4,
* type: gl.UNSIGNED_BYTE,
* normalize: true,
* },
* };
*
* @param {Object.<string, function>} setters Attribute setters as returned from createAttributeSetters
* @param {Object.<string, module:twgl.AttribInfo>} buffers AttribInfos mapped by attribute name.
* @memberOf module:twgl
* @deprecated use {@link module:twgl.setBuffersAndAttributes}
*/
export function setAttributes(setters, buffers) {
for (var name in buffers) {
var setter = setters[name];
if (setter) {
setter(buffers[name]);
}
}
}
/**
* Sets attributes and buffers including the `ELEMENT_ARRAY_BUFFER` if appropriate
*
* Example:
*
* var programInfo = createProgramInfo(
* gl, ["some-vs", "some-fs");
*
* 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], },
* };
*
* var bufferInfo = createBufferInfoFromArrays(gl, arrays);
*
* gl.useProgram(programInfo.program);
*
* This will automatically bind the buffers AND set the
* attributes.
*
* setBuffersAndAttributes(gl, programInfo, bufferInfo);
*
* For the example above it is equivilent to
*
* gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
* gl.enableVertexAttribArray(a_positionLocation);
* gl.vertexAttribPointer(a_positionLocation, 3, gl.FLOAT, false, 0, 0);
* gl.bindBuffer(gl.ARRAY_BUFFER, texcoordBuffer);
* gl.enableVertexAttribArray(a_texcoordLocation);
* gl.vertexAttribPointer(a_texcoordLocation, 4, gl.FLOAT, false, 0, 0);
*
* @param {WebGLRenderingContext} gl A WebGLRenderingContext.
* @param {(module:twgl.ProgramInfo|Object.<string, function>)} setters A `ProgramInfo` as returned from `createProgrmaInfo` Attribute setters as returned from `createAttributeSetters`
* @param {module:twgl.BufferInfo} buffers a BufferInfo as returned from `createBufferInfoFromArrays`.
* @memberOf module:twgl
*/
export function setBuffersAndAttributes(gl, programInfo, buffers) {
setAttributes(programInfo.attribSetters || programInfo, buffers.attribs);
if (buffers.indices) {
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, buffers.indices);
}
}
/**
* @typedef {Object} ProgramInfo
* @property {WebGLProgram} program A shader program
* @property {Object<string, function>} uniformSetters object of setters as returned from createUniformSetters,
* @property {Object<string, function>} attribSetters object of setters as returned from createAttribSetters,
* @memberOf module:twgl
*/
/**
* Creates a ProgramInfo from 2 sources.
*
* A ProgramInfo contains
*
* programInfo = {
* program: WebGLProgram,
* uniformSetters: object of setters as returned from createUniformSetters,
* attribSetters: object of setters as returned from createAttribSetters,
* }
*
* @param {WebGLRenderingContext} gl The WebGLRenderingContext
* to use.
* @param {string[]} shaderSourcess Array of sources for the
* shaders or ids. The first is assumed to be the vertex shader,
* the second the fragment shader.
* @param {string[]} [opt_attribs] An array of attribs names. Locations will be assigned by index if not passed in
* @param {number[]} [opt_locations] The locations for the. A parallel array to opt_attribs letting you assign locations.
* @param {module:twgl.ErrorCallback} opt_errorCallback callback for errors. By default it just prints an error to the console
* on error. If you want something else pass an callback. It's passed an error message.
* @return {module:twgl.ProgramInfo?} The created program.
* @memberOf module:twgl
*/
export function createProgramInfo(
gl, shaderSources: IShader, opt_attribs?, opt_locations?, opt_errorCallback?): IProgramInfo {
var program = createProgramFromSources(gl, shaderSources, opt_attribs, opt_locations, opt_errorCallback);
if (!program) {
return null;
}
var uniformSetters = createUniformSetters(gl, program);
var attribSetters = createAttributeSetters(gl, program);
return {
program: program,
uniformSetters: uniformSetters,
attribSetters: attribSetters,
};
}
/**
* Resize a canvas to match the size it's displayed.
* @param {HTMLCanvasElement} canvas The canvas to resize.
* @param {number} [a] multiplier. So you can pass in `window.devicePixelRatio` if you want to.
* @return {boolean} true if the canvas was resized.
* @memberOf module:twgl
*/
export function resizeCanvasToDisplaySize(canvas, multiplier?) {
multiplier = multiplier || 1;
multiplier = Math.max(1, multiplier);
var width = canvas.clientWidth * multiplier | 0;
var height = canvas.clientHeight * multiplier | 0;
if (canvas.width !== width ||
canvas.height !== height) {
canvas.width = width;
canvas.height = height;
return true;
}
return false;
}
export function setBufferFromTypedArray(gl, type, buffer, array, drawType?) {
gl.bindBuffer(type, buffer);
gl.bufferData(type, array, drawType || gl.STATIC_DRAW);
}
export function createBufferFromTypedArray(gl, array, type?, drawType?): WebGLBuffer {
if (array instanceof WebGLBuffer) {
return array;
}
type = type || gl.ARRAY_BUFFER;
var buffer = gl.createBuffer();
setBufferFromTypedArray(gl, type, buffer, array, drawType);
return buffer;
}
function isIndices(name) {
return name === "indices";
}
function getGLTypeForTypedArray(typedArray) {
if (typedArray instanceof Int8Array) { return BYTE; } // eslint-disable-line
if (typedArray instanceof Uint8Array) { return UNSIGNED_BYTE; } // eslint-disable-line
if (typedArray instanceof Int16Array) { return SHORT; } // eslint-disable-line
if (typedArray instanceof Uint16Array) { return UNSIGNED_SHORT; } // eslint-disable-line
if (typedArray instanceof Int32Array) { return INT; } // eslint-disable-line
if (typedArray instanceof Uint32Array) { return UNSIGNED_INT; } // eslint-disable-line
if (typedArray instanceof Float32Array) { return FLOAT; } // eslint-disable-line
throw "unsupported typed array type";
}
function getTypedArrayTypeForGLType(gl, type) {
switch (type) {
case gl.BYTE: return Int8Array; // eslint-disable-line
case gl.UNSIGNED_BYTE: return Uint8Array; // eslint-disable-line
case gl.SHORT: return Int16Array; // eslint-disable-line
case gl.UNSIGNED_SHORT: return Uint16Array; // eslint-disable-line
case gl.INT: return Int32Array; // eslint-disable-line
case gl.UNSIGNED_INT: return Uint32Array; // eslint-disable-line
case gl.FLOAT: return Float32Array; // eslint-disable-line
default:
throw "unknown gl type";
}
}
// This is really just a guess. Though I can't really imagine using
// anything else? Maybe for some compression?
function getNormalizationForTypedArray(typedArray) {
if (typedArray instanceof Int8Array) { return true; } // eslint-disable-line
if (typedArray instanceof Uint8Array) { return true; } // eslint-disable-line
return false;
}
function isArrayBuffer(a) {
return a && a.buffer && a.buffer instanceof ArrayBuffer;
}
function guessNumComponentsFromName(name, length) {
var numComponents: number;
if (name.indexOf("coord") >= 0) {
numComponents = 2;
} else if (name.indexOf("color") >= 0) {
numComponents = 4;
} else {
numComponents = 3; // position, normals, indices ...
}
if (length % numComponents > 0) {
throw "can not guess numComponents. You should specify it.";
}
return numComponents;
}
function makeTypedArray(array, name?) {
if (isArrayBuffer(array)) {
return array;
}
if (isArrayBuffer(array.data)) {
return array.data;
}
if (Array.isArray(array)) {
array = {
data: array,