-
Notifications
You must be signed in to change notification settings - Fork 0
/
gl-renderer.js
2535 lines (2098 loc) · 83.6 KB
/
gl-renderer.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
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else if(typeof exports === 'object')
exports["GlRenderer"] = factory();
else
root["GlRenderer"] = factory();
})(this, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "/js/";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _renderer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1);
/* harmony default export */ __webpack_exports__["default"] = (_renderer__WEBPACK_IMPORTED_MODULE_0__["default"]);
/***/ }),
/* 1 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Renderer; });
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2);
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(4);
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_slicedToArray__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(5);
/* harmony import */ var _babel_runtime_helpers_slicedToArray__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_slicedToArray__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_toConsumableArray__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(11);
/* harmony import */ var _babel_runtime_helpers_toConsumableArray__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_toConsumableArray__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(15);
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(16);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(17);
/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _helpers__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(18);
/* harmony import */ var _default_vert_glsl__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(20);
/* harmony import */ var _default_vert_glsl__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(_default_vert_glsl__WEBPACK_IMPORTED_MODULE_8__);
/* harmony import */ var _default_frag_glsl__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(21);
/* harmony import */ var _default_frag_glsl__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(_default_frag_glsl__WEBPACK_IMPORTED_MODULE_9__);
/* harmony import */ var _default_feeback_vert_glsl__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(22);
/* harmony import */ var _default_feeback_vert_glsl__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(_default_feeback_vert_glsl__WEBPACK_IMPORTED_MODULE_10__);
var GLSL_LIBS = {};
function mapTextureCoordinate(positions) {
var size = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 3;
var texVertexData = [];
var len = positions.length;
for (var i = 0; i < len; i++) {
if (i % size < 2) texVertexData.push(0.5 * (positions[i] + 1));
}
return texVertexData;
}
function clearBuffers(gl, program) {
var buffers = program._buffers;
Object.values(buffers).forEach(function (buffer) {
gl.deleteBuffer(buffer);
});
program._buffers = {};
}
function bindTexture(gl, texture, i) {
gl.activeTexture(gl.TEXTURE0 + i);
if (Array.isArray(texture._img)) {
gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
} else {
gl.bindTexture(gl.TEXTURE_2D, texture);
}
return texture;
}
var uniformTypeMap = {
int: '1i',
ivec2: '2i',
ivec3: '3i',
ivec4: '4i',
float: '1f',
vec2: '2f',
vec3: '3f',
vec4: '4f',
mat2: 'Matrix2fv',
mat3: 'Matrix3fv',
mat4: 'Matrix4fv',
sampler1D: 'sampler1D',
sampler2D: 'sampler2D',
sampler3D: 'sampler3D',
samplerCube: 'samplerCube',
sampler1DShadow: 'sampler1DShadow',
sampler2DShadow: 'sampler2DShadow',
sampler2DRect: 'sampler2DRect',
sampler2DRectShadow: 'sampler2DRectShadow'
};
var Renderer = /*#__PURE__*/function () {
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_5___default()(Renderer, null, [{
key: "addLibs",
value: function addLibs() {
var libs = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
Object.assign(GLSL_LIBS, libs);
}
}, {
key: "FLOAT",
value: function FLOAT(points, buffer) {
return Object(_helpers__WEBPACK_IMPORTED_MODULE_7__["pointsToBuffer"])(points, Float32Array, buffer);
}
}, {
key: "UNSIGNED_BYTE",
value: function UNSIGNED_BYTE(points, buffer) {
return Object(_helpers__WEBPACK_IMPORTED_MODULE_7__["pointsToBuffer"])(points, Uint8Array, buffer);
}
}, {
key: "UNSIGNED_SHORT",
value: function UNSIGNED_SHORT(points, buffer) {
return Object(_helpers__WEBPACK_IMPORTED_MODULE_7__["pointsToBuffer"])(points, Uint16Array, buffer);
}
}, {
key: "BYTE",
value: function BYTE(points, buffer) {
return Object(_helpers__WEBPACK_IMPORTED_MODULE_7__["pointsToBuffer"])(points, Int8Array, buffer);
}
}, {
key: "SHORT",
value: function SHORT(points, buffer) {
return Object(_helpers__WEBPACK_IMPORTED_MODULE_7__["pointsToBuffer"])(points, Int16Array, buffer);
}
}]);
function Renderer(canvas) {
var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_4___default()(this, Renderer);
this.options = Object.assign({}, Renderer.defaultOptions, opts);
this.canvas = canvas;
var gl;
if (this.options.webgl2) {
gl = canvas.getContext('webgl2', this.options);
}
if (gl == null) {
gl = Object(_helpers__WEBPACK_IMPORTED_MODULE_7__["setupWebGL"])(canvas, this.options);
this.aia_ext = gl.getExtension('ANGLE_instanced_arrays');
}
this.gl = gl;
gl.viewport(0, 0, canvas.width, canvas.height); // gl.clearColor(1.0, 1.0, 1.0, 1.0);
// gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
gl.clearColor(0.0, 0.0, 0.0, 0.0);
gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
this.programs = [];
this._events = {};
}
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_5___default()(Renderer, [{
key: "_declareUniform",
// WebGLRenderingContext.uniform[1234][fi][v]()
// WebGLRenderingContext.uniformMatrix[234]fv()
value: function _declareUniform(program, name) {
var type = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '1f';
var gl = this.gl;
var uniform = gl.getUniformLocation(program, name);
var value;
var that = this;
if (/^sampler/.test(type)) {
var samplerMap = program._samplerMap;
var textures = program._bindTextures;
Object.defineProperty(program.uniforms, name, {
get: function get() {
return value;
},
set: function set(v) {
value = v;
var idx = samplerMap[name] != null ? samplerMap[name] : textures.length;
textures[idx] = v;
bindTexture(gl, v, idx);
if (!samplerMap[name]) {
samplerMap[name] = idx;
gl.uniform1i(uniform, idx);
} // gl.bindTexture(gl.TEXTURE_2D, null);
if (that.options.autoUpdate) that.update();
},
configurable: false,
enumerable: true
});
} else {
var isMatrix = type.indexOf('Matrix') === 0;
var isTypeV = !isMatrix && /v$/.test(type);
var setUniform = gl["uniform".concat(type)].bind(gl);
Object.defineProperty(program.uniforms, name, {
get: function get() {
return value;
},
set: function set(v) {
value = v;
if (typeof v === 'number') {
v = [v];
}
if (isMatrix) setUniform(uniform, false, v);else if (isTypeV) setUniform(uniform, v);else setUniform.apply(void 0, [uniform].concat(_babel_runtime_helpers_toConsumableArray__WEBPACK_IMPORTED_MODULE_3___default()(v)));
if (that.options.autoUpdate) that.update();
},
configurable: false,
enumerable: true
});
}
}
}, {
key: "_draw",
value: function _draw() {
var _this = this;
var program = this.program;
program.meshData.forEach(function (meshData, meshIndex) {
var positions = meshData.positions,
cells = meshData.cells,
instanceCount = meshData.instanceCount,
cellsCount = meshData.cellsCount,
attributes = meshData.attributes,
uniforms = meshData.uniforms,
textureCoord = meshData.textureCoord,
enableBlend = meshData.enableBlend;
var gl = _this.gl;
var mode = meshData.mode != null ? meshData.mode : gl.TRIANGLES;
if (typeof mode === 'string') {
mode = gl[mode];
}
if (enableBlend) gl.enable(gl.BLEND);else gl.disable(gl.BLEND);
gl.bindBuffer(gl.ARRAY_BUFFER, program._buffers.verticesBuffer);
gl.bufferData(gl.ARRAY_BUFFER, positions, gl.STATIC_DRAW);
if (cells) {
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, program._buffers.cellsBuffer);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, cells, gl.STATIC_DRAW);
}
var locations = [];
if (attributes) {
Object.values(attributes).forEach(function (_ref) {
var name = _ref.name,
data = _ref.data,
divisor = _ref.divisor;
gl.bindBuffer(gl.ARRAY_BUFFER, program._buffers[name]);
gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW);
if (divisor != null) {
var location = gl.getAttribLocation(program, name);
if (location >= 0) {
gl.enableVertexAttribArray(location);
locations.push(location);
if (gl.vertexAttribDivisor) {
gl.vertexAttribDivisor(location, divisor);
} else if (_this.aia_ext) {
_this.aia_ext.vertexAttribDivisorANGLE(location, divisor);
}
}
}
});
}
if (uniforms) {
Object.entries(uniforms).forEach(function (_ref2) {
var _ref3 = _babel_runtime_helpers_slicedToArray__WEBPACK_IMPORTED_MODULE_2___default()(_ref2, 2),
key = _ref3[0],
value = _ref3[1];
_this.uniforms[key] = value;
});
}
var count;
if (!cells) {
var dimension = program._dimension;
count = positions.length / dimension;
}
if (program._enableTextures && program._buffers.texCoordBuffer) {
var texVertexData = textureCoord || mapTextureCoordinate(positions, program._dimension);
gl.bindBuffer(gl.ARRAY_BUFFER, program._buffers.texCoordBuffer);
gl.bufferData(gl.ARRAY_BUFFER, Renderer.FLOAT(texVertexData), gl.STATIC_DRAW);
}
if (instanceCount != null) {
if (cells) {
if (gl.drawElementsInstanced) {
gl.drawElementsInstanced(mode, cellsCount, gl.UNSIGNED_SHORT, 0, instanceCount);
} else if (_this.aia_ext) {
_this.aia_ext.drawElementsInstancedANGLE(mode, cellsCount, gl.UNSIGNED_SHORT, 0, instanceCount);
}
} else if (gl.drawArraysInstanced) {
gl.drawArraysInstanced(mode, 0, count, instanceCount);
} else {
_this.aia_ext.drawArraysInstancedANGLE(mode, 0, count, instanceCount);
}
locations.forEach(function (location) {
if (gl.vertexAttribDivisor) {
gl.vertexAttribDivisor(location, null);
} else if (_this.aia_ext) {
_this.aia_ext.vertexAttribDivisorANGLE(location, null);
}
});
} else if (cells) {
gl.drawElements(mode, cellsCount, gl.UNSIGNED_SHORT, 0);
} else {
gl.drawArrays(mode, 0, count);
}
});
}
}, {
key: "deleteProgram",
value: function deleteProgram(program) {
var gl = this.gl;
if (this.program === program) {
this.startRender = false;
if (this._renderFrameID) {
cancelAnimationFrame(this._renderFrameID);
delete this._renderFrameID;
}
gl.useProgram(null);
}
var idx = this.programs.indexOf(program);
if (idx >= 0) {
this.programs.splice(idx, 1);
}
clearBuffers(gl, program);
gl.deleteProgram(program);
}
/**
[{
positions: ...
cells: ...
textureCoord: ...
attributes: {name: {data:..., normalize: true}},
uniforms: ...
}]
*/
}, {
key: "setMeshData",
value: function setMeshData(data) {
var _this2 = this;
if (!Array.isArray(data)) {
data = [data];
}
var program = this.program;
program.meshData = data.map(function (_ref4) {
var mode = _ref4.mode,
positions = _ref4.positions,
instanceCount = _ref4.instanceCount,
cells = _ref4.cells,
cellsCount = _ref4.cellsCount,
attributes = _ref4.attributes,
uniforms = _ref4.uniforms,
textureCoord = _ref4.textureCoord,
enableBlend = _ref4.enableBlend;
var meshData = {
positions: Renderer.FLOAT(positions),
uniforms: uniforms,
enableBlend: !!enableBlend,
textureCoord: Renderer.FLOAT(textureCoord)
};
if (cells) {
meshData.cells = Renderer.USHORT(cells);
meshData.cellsCount = cellsCount || meshData.cells.length;
}
if (mode != null) {
meshData.mode = mode;
}
if (instanceCount != null) {
if (!_this2.isWebGL2 && !_this2.aia_ext) throw new Error('Cannot use instanceCount in this rendering context, use webgl2 context instead.');else meshData.instanceCount = instanceCount;
}
if (attributes) {
var copied = {};
Object.entries(attributes).forEach(function (_ref5) {
var _ref6 = _babel_runtime_helpers_slicedToArray__WEBPACK_IMPORTED_MODULE_2___default()(_ref5, 2),
key = _ref6[0],
value = _ref6[1];
if (!program._attribute[key]) {
// throw new Error(`Invalid attribute ${key}.`);
if (false) {}
program._attribute[key] = 'ignored';
} else if (program._attribute[key] !== 'ignored') {
var _program$_attribute$k = program._attribute[key],
name = _program$_attribute$k.name,
type = _program$_attribute$k.type;
var buffer = value.data || value;
if (Array.isArray(buffer)) {
buffer = Renderer[type](buffer);
}
copied[key] = {
name: name,
data: buffer
};
if (value.divisor != null) {
if (!_this2.isWebGL2 && !_this2.aia_ext) throw new Error('Cannot use divisor in this rendering context, use webgl2 context instead.');else copied[key].divisor = value.divisor;
}
}
});
meshData.attributes = copied;
}
return meshData;
});
if (this.options.autoUpdate) this.update();
}
}, {
key: "createProgram",
value: function createProgram(fragmentShader, vertexShader) {
var _this3 = this;
// this.deleteProgram();
// this._events = {};
var enableTextures = /^\s*uniform\s+sampler/mg.test(fragmentShader);
if (fragmentShader == null) fragmentShader = _default_frag_glsl__WEBPACK_IMPORTED_MODULE_9___default.a;
if (vertexShader == null) vertexShader = enableTextures ? _default_feeback_vert_glsl__WEBPACK_IMPORTED_MODULE_10___default.a : _default_vert_glsl__WEBPACK_IMPORTED_MODULE_8___default.a;
var gl = this.gl;
var program = Object(_helpers__WEBPACK_IMPORTED_MODULE_7__["createProgram"])(gl, vertexShader, fragmentShader);
program.shaderText = {
vertexShader: vertexShader,
fragmentShader: fragmentShader
};
program._buffers = {};
program._attribute = {};
program.uniforms = {};
program._samplerMap = {};
program._bindTextures = []; // console.log(vertexShader);
var pattern = new RegExp("(?:attribute|in) vec(\\d) ".concat(this.options.vertexPosition), 'im');
var matched = vertexShader.match(pattern);
if (matched) {
program._dimension = Number(matched[1]);
}
var texCoordPattern = new RegExp("(?:attribute|in) vec(\\d) ".concat(this.options.vertexTextureCoord), 'im');
matched = vertexShader.match(texCoordPattern);
if (matched) {
program._texCoordSize = Number(matched[1]);
}
var attributePattern = /^\s*(?:attribute|in) (\w+?)(\d*) (\w+)/gim;
matched = vertexShader.match(attributePattern);
if (matched) {
for (var i = 0; i < matched.length; i++) {
var patt = /^\s*(?:attribute|in) (\w+?)(\d*) (\w+)/im;
var _matched = matched[i].match(patt);
if (_matched && _matched[3] !== this.options.vertexPosition && _matched[3] !== this.options.vertexTextureCoord) {
var _matched2 = _babel_runtime_helpers_slicedToArray__WEBPACK_IMPORTED_MODULE_2___default()(_matched, 4),
type = _matched2[1],
size = _matched2[2],
name = _matched2[3];
if (type === 'mat') size = Math.pow(size, 2);
program._buffers[name] = gl.createBuffer();
program._attribute[name] = {
name: name,
type: type,
size: Number(size) || 1
};
}
}
}
var uniformPattern = /^\s*uniform\s+(\w+)\s+(\w+)(\[\d+\])?/mg;
matched = vertexShader.match(uniformPattern) || [];
matched = matched.concat(fragmentShader.match(uniformPattern) || []);
matched.forEach(function (m) {
var _matched = m.match(/^\s*uniform\s+(\w+)\s+(\w+)(\[\d+\])?/);
var _matched$slice = _matched.slice(1),
_matched$slice2 = _babel_runtime_helpers_slicedToArray__WEBPACK_IMPORTED_MODULE_2___default()(_matched$slice, 3),
type = _matched$slice2[0],
name = _matched$slice2[1],
isTypeV = _matched$slice2[2];
type = uniformTypeMap[type];
isTypeV = !!isTypeV;
if (type.indexOf('Matrix') !== 0 && isTypeV) {
type += 'v';
}
_this3._declareUniform(program, name, type);
});
program._buffers.verticesBuffer = gl.createBuffer();
program._buffers.cellsBuffer = gl.createBuffer();
var vTexCoord = gl.getAttribLocation(program, this.options.vertexTextureCoord);
program._enableTextures = vTexCoord >= 0;
if (program._enableTextures) {
program._buffers.texCoordBuffer = gl.createBuffer();
}
this.programs.push(program);
return program;
}
}, {
key: "useProgram",
value: function useProgram(program) {
var attrOptions = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
this.startRender = false;
if (this._renderFrameID) {
cancelAnimationFrame(this._renderFrameID);
delete this._renderFrameID;
}
var gl = this.gl;
gl.useProgram(program); // this.program = program;
var dimension = program._dimension;
gl.bindBuffer(gl.ARRAY_BUFFER, program._buffers.verticesBuffer);
var vPosition = gl.getAttribLocation(program, this.options.vertexPosition);
gl.vertexAttribPointer(vPosition, dimension, gl.FLOAT, false, 0, 0);
gl.enableVertexAttribArray(vPosition);
if (program._enableTextures) {
gl.bindBuffer(gl.ARRAY_BUFFER, program._buffers.texCoordBuffer);
var vTexCoord = gl.getAttribLocation(program, this.options.vertexTextureCoord);
gl.vertexAttribPointer(vTexCoord, program._texCoordSize || 2, gl.FLOAT, false, 0, 0);
gl.enableVertexAttribArray(vTexCoord);
}
Object.entries(program._attribute).forEach(function (_ref7) {
var _ref8 = _babel_runtime_helpers_slicedToArray__WEBPACK_IMPORTED_MODULE_2___default()(_ref7, 2),
name = _ref8[0],
item = _ref8[1];
if (item !== 'ignored') {
var size = item.size;
var options = attrOptions[name] || {};
var normalize = !!options.normalize;
var bufferType = options.type || 'FLOAT';
var key = options.key || name;
if (bufferType === 'UBYTE') bufferType = 'UNSIGNED_BYTE';
if (bufferType === 'USHORT') bufferType = 'UNSIGNED_SHORT';
item.type = bufferType;
if (key && key !== name) {
program._attribute[key] = item;
}
gl.bindBuffer(gl.ARRAY_BUFFER, program._buffers[name]);
var attrib = gl.getAttribLocation(program, name); // console.log(size, gl[bufferType]);
if (attrib >= 0) {
gl.vertexAttribPointer(attrib, size, gl[bufferType], normalize, 0, 0);
gl.enableVertexAttribArray(attrib);
}
}
});
if (!program.meshData) {
var positions = [[-1, -1, 0, 1].slice(0, dimension), [1, -1, 0, 1].slice(0, dimension), [1, 1, 0, 1].slice(0, dimension), [-1, 1, 0, 1].slice(0, dimension)];
var cells = [[0, 1, 3], [3, 1, 2]];
this.setMeshData({
positions: positions,
cells: cells
});
}
return program;
}
}, {
key: "compileSync",
value: function compileSync(frag, vert) {
frag = frag || _default_frag_glsl__WEBPACK_IMPORTED_MODULE_9___default.a;
var loaded = {};
function _compile(content) {
content = content.replace(/^\s*/mg, '');
var includes = [];
var matched = content.match(/^#pragma\s+include\s+.*/mg);
if (matched) {
// console.log(matched, url);
for (var i = 0; i < matched.length; i++) {
var m = matched[i];
var _matched = m.match(/(?:<|")(.*)(?:>|")/);
if (_matched) {
var type = _matched[0].indexOf('<') === 0 ? 'lib' : 'link';
var name = _matched[1];
if (name === 'graph') name = 'graphics';
if (!loaded[name]) {
loaded[name] = true;
if (type === 'lib') {
var c = _compile(GLSL_LIBS[name]); // eslint-disable-line no-await-in-loop
includes.push(c);
} else if (type === 'link') {
throw new Error('Cannot load external links synchronously. Use compile instead of compileSync.');
}
} else {
includes.push("/* included ".concat(name, " */"));
}
}
}
includes.forEach(function (inc) {
content = content.replace(/^#pragma\s+include\s+.*/m, inc);
});
}
return content;
}
var fragmentShader = _compile(frag);
var vertexShader = vert ? _compile(vert) : null;
var program = this.createProgram(fragmentShader, vertexShader);
return program;
}
}, {
key: "compile",
value: function () {
var _compile2 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee2(frag, vert) {
var loaded, _compile, _compile3, fragmentShader, vertexShader, program;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
_compile3 = function _compile5() {
_compile3 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee(content) {
var includes, matched, i, m, _matched, type, name, c, _c;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
content = content.replace(/^\s*/mg, '');
includes = [];
matched = content.match(/^#pragma\s+include\s+.*/mg);
if (!matched) {
_context.next = 36;
break;
}
i = 0;
case 5:
if (!(i < matched.length)) {
_context.next = 35;
break;
}
m = matched[i];
_matched = m.match(/(?:<|")(.*)(?:>|")/);
if (!_matched) {
_context.next = 32;
break;
}
type = _matched[0].indexOf('<') === 0 ? 'lib' : 'link';
name = _matched[1];
if (name === 'graph') name = 'graphics';
if (loaded[name]) {
_context.next = 31;
break;
}
loaded[name] = true; // TODO: 这里可以优化成异步加载
if (!(type === 'lib')) {
_context.next = 21;
break;
}
_context.next = 17;
return _compile(GLSL_LIBS[name]);
case 17:
c = _context.sent;
// eslint-disable-line no-await-in-loop
includes.push(c);
_context.next = 29;
break;
case 21:
if (!(type === 'link')) {
_context.next = 29;
break;
}
_context.next = 24;
return Renderer.fetchShader(name);
case 24:
_c = _context.sent;
_context.next = 27;
return _compile(_c);
case 27:
_c = _context.sent;
// eslint-disable-line no-await-in-loop
includes.push(_c);
case 29:
_context.next = 32;
break;
case 31:
includes.push("/* included ".concat(name, " */"));
case 32:
i++;
_context.next = 5;
break;
case 35:
includes.forEach(function (inc) {
content = content.replace(/^#pragma\s+include\s+.*/m, inc);
});
case 36:
return _context.abrupt("return", content);
case 37:
case "end":
return _context.stop();
}
}
}, _callee);
}));
return _compile3.apply(this, arguments);
};
_compile = function _compile4(_x3) {
return _compile3.apply(this, arguments);
};
frag = frag || _default_frag_glsl__WEBPACK_IMPORTED_MODULE_9___default.a;
loaded = {};
_context2.next = 6;
return _compile(frag);
case 6:
fragmentShader = _context2.sent;
if (!vert) {
_context2.next = 13;
break;
}
_context2.next = 10;
return _compile(vert);
case 10:
_context2.t0 = _context2.sent;
_context2.next = 14;
break;
case 13:
_context2.t0 = null;
case 14:
vertexShader = _context2.t0;
program = this.createProgram(fragmentShader, vertexShader);
return _context2.abrupt("return", program);
case 17:
case "end":
return _context2.stop();
}
}
}, _callee2, this);
}));
function compile(_x, _x2) {
return _compile2.apply(this, arguments);
}
return compile;
}()
}, {
key: "load",
value: function () {
var _load = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee3(frag) {
var vert,
_args3 = arguments;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
vert = _args3.length > 1 && _args3[1] !== undefined ? _args3[1] : null;
_context3.next = 3;
return Renderer.fetchShader(frag);
case 3:
frag = _context3.sent;
if (!vert) {
_context3.next = 8;
break;
}
_context3.next = 7;
return Renderer.fetchShader(vert);
case 7:
vert = _context3.sent;
case 8:
return _context3.abrupt("return", this.compile(frag, vert));
case 9:
case "end":
return _context3.stop();
}
}
}, _callee3, this);
}));
function load(_x4) {
return _load.apply(this, arguments);
}
return load;
}()
}, {
key: "createTexture",
value: function createTexture() {
var _this4 = this;
var img = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
var _ref9 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
_ref9$wrapS = _ref9.wrapS,
wrapS = _ref9$wrapS === void 0 ? this.gl.CLAMP_TO_EDGE : _ref9$wrapS,
_ref9$wrapT = _ref9.wrapT,
wrapT = _ref9$wrapT === void 0 ? this.gl.CLAMP_TO_EDGE : _ref9$wrapT,
_ref9$minFilter = _ref9.minFilter,
minFilter = _ref9$minFilter === void 0 ? this.gl.LINEAR : _ref9$minFilter,
_ref9$magFilter = _ref9.magFilter,
magFilter = _ref9$magFilter === void 0 ? this.gl.LINEAR : _ref9$magFilter;
var gl = this.gl;
var target = Array.isArray(img) ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
this._max_texture_image_units = this._max_texture_image_units || gl.getParameter(gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
gl.activeTexture(gl.TEXTURE0 + this._max_texture_image_units - 1);
var texture = gl.createTexture();
gl.bindTexture(target, texture);
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
var _this$canvas = this.canvas,
width = _this$canvas.width,
height = _this$canvas.height;
if (img) {
if (target === gl.TEXTURE_CUBE_MAP) {