-
Notifications
You must be signed in to change notification settings - Fork 1
/
bundle.js
11004 lines (9606 loc) · 416 KB
/
bundle.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(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] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = 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;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
/*
tags: basic
<p> This example shows how to draw a mesh with regl </p>
*/
var regl = __webpack_require__(1)();
var mat4 = __webpack_require__(35);
var normals = __webpack_require__(59);
var bunny = __webpack_require__(60);
var drawBunny = regl({
vert: __webpack_require__(61),
frag: __webpack_require__(62),
// this converts the vertices of the mesh into the position attribute
attributes: {
position: bunny.positions,
normal: normals(bunny.cells, bunny.positions)
},
// and this converts the faces fo the mesh into elements
elements: bunny.cells,
uniforms: {
light: [-0.5, -1, 1.5],
model: mat4.identity([]),
view: function view(_ref) {
var tick = _ref.tick;
var t = 0.01 * tick;
return mat4.lookAt([], [30 * Math.cos(t), 2.5, 30 * Math.sin(t)], [0, 2.5, 0], [0, 1, 0]);
},
projection: function projection(_ref2) {
var viewportWidth = _ref2.viewportWidth;
var viewportHeight = _ref2.viewportHeight;
return mat4.perspective([], Math.PI / 4, viewportWidth / viewportHeight, 0.01, 1000);
}
}
});
regl.frame(function () {
regl.clear({
depth: 1,
color: [0, 0, 0, 1]
});
drawBunny();
});
/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {
var check = __webpack_require__(2)
var extend = __webpack_require__(5)
var dynamic = __webpack_require__(6)
var raf = __webpack_require__(7)
var clock = __webpack_require__(8)
var createStringStore = __webpack_require__(9)
var initWebGL = __webpack_require__(10)
var wrapExtensions = __webpack_require__(11)
var wrapLimits = __webpack_require__(12)
var wrapBuffers = __webpack_require__(13)
var wrapElements = __webpack_require__(21)
var wrapTextures = __webpack_require__(23)
var wrapRenderbuffers = __webpack_require__(26)
var wrapFramebuffers = __webpack_require__(27)
var wrapAttributes = __webpack_require__(28)
var wrapShaders = __webpack_require__(29)
var wrapRead = __webpack_require__(30)
var createCore = __webpack_require__(31)
var createStats = __webpack_require__(33)
var createTimer = __webpack_require__(34)
var GL_COLOR_BUFFER_BIT = 16384
var GL_DEPTH_BUFFER_BIT = 256
var GL_STENCIL_BUFFER_BIT = 1024
var GL_ARRAY_BUFFER = 34962
var CONTEXT_LOST_EVENT = 'webglcontextlost'
var CONTEXT_RESTORED_EVENT = 'webglcontextrestored'
var DYN_PROP = 1
var DYN_CONTEXT = 2
var DYN_STATE = 3
function find (haystack, needle) {
for (var i = 0; i < haystack.length; ++i) {
if (haystack[i] === needle) {
return i
}
}
return -1
}
module.exports = function wrapREGL (args) {
var config = initWebGL(args)
if (!config) {
return null
}
var gl = config.gl
var glAttributes = gl.getContextAttributes()
var contextLost = gl.isContextLost()
var extensionState = wrapExtensions(gl, config)
if (!extensionState) {
return null
}
var stringStore = createStringStore()
var stats = createStats()
var extensions = extensionState.extensions
var timer = createTimer(gl, extensions)
var START_TIME = clock()
var WIDTH = gl.drawingBufferWidth
var HEIGHT = gl.drawingBufferHeight
var contextState = {
tick: 0,
time: 0,
viewportWidth: WIDTH,
viewportHeight: HEIGHT,
framebufferWidth: WIDTH,
framebufferHeight: HEIGHT,
drawingBufferWidth: WIDTH,
drawingBufferHeight: HEIGHT,
pixelRatio: config.pixelRatio
}
var uniformState = {}
var drawState = {
elements: null,
primitive: 4, // GL_TRIANGLES
count: -1,
offset: 0,
instances: -1
}
var limits = wrapLimits(gl, extensions)
var bufferState = wrapBuffers(gl, stats, config)
var elementState = wrapElements(gl, extensions, bufferState, stats)
var attributeState = wrapAttributes(
gl,
extensions,
limits,
bufferState,
stringStore)
var shaderState = wrapShaders(gl, stringStore, stats, config)
var textureState = wrapTextures(
gl,
extensions,
limits,
function () { core.procs.poll() },
contextState,
stats,
config)
var renderbufferState = wrapRenderbuffers(gl, extensions, limits, stats, config)
var framebufferState = wrapFramebuffers(
gl,
extensions,
limits,
textureState,
renderbufferState,
stats)
var core = createCore(
gl,
stringStore,
extensions,
limits,
bufferState,
elementState,
textureState,
framebufferState,
uniformState,
attributeState,
shaderState,
drawState,
contextState,
timer,
config)
var readPixels = wrapRead(
gl,
framebufferState,
core.procs.poll,
contextState,
glAttributes, extensions)
var nextState = core.next
var canvas = gl.canvas
var rafCallbacks = []
var lossCallbacks = []
var restoreCallbacks = []
var destroyCallbacks = [config.onDestroy]
var activeRAF = null
function handleRAF () {
if (rafCallbacks.length === 0) {
if (timer) {
timer.update()
}
activeRAF = null
return
}
// schedule next animation frame
activeRAF = raf.next(handleRAF)
// poll for changes
poll()
// fire a callback for all pending rafs
for (var i = rafCallbacks.length - 1; i >= 0; --i) {
var cb = rafCallbacks[i]
if (cb) {
cb(contextState, null, 0)
}
}
// flush all pending webgl calls
gl.flush()
// poll GPU timers *after* gl.flush so we don't delay command dispatch
if (timer) {
timer.update()
}
}
function startRAF () {
if (!activeRAF && rafCallbacks.length > 0) {
activeRAF = raf.next(handleRAF)
}
}
function stopRAF () {
if (activeRAF) {
raf.cancel(handleRAF)
activeRAF = null
}
}
function handleContextLoss (event) {
event.preventDefault()
// set context lost flag
contextLost = true
// pause request animation frame
stopRAF()
// lose context
lossCallbacks.forEach(function (cb) {
cb()
})
}
function handleContextRestored (event) {
// clear error code
gl.getError()
// clear context lost flag
contextLost = false
// refresh state
extensionState.restore()
shaderState.restore()
bufferState.restore()
textureState.restore()
renderbufferState.restore()
framebufferState.restore()
if (timer) {
timer.restore()
}
// refresh state
core.procs.refresh()
// restart RAF
startRAF()
// restore context
restoreCallbacks.forEach(function (cb) {
cb()
})
}
if (canvas) {
canvas.addEventListener(CONTEXT_LOST_EVENT, handleContextLoss, false)
canvas.addEventListener(CONTEXT_RESTORED_EVENT, handleContextRestored, false)
}
function destroy () {
rafCallbacks.length = 0
stopRAF()
if (canvas) {
canvas.removeEventListener(CONTEXT_LOST_EVENT, handleContextLoss)
canvas.removeEventListener(CONTEXT_RESTORED_EVENT, handleContextRestored)
}
shaderState.clear()
framebufferState.clear()
renderbufferState.clear()
textureState.clear()
elementState.clear()
bufferState.clear()
if (timer) {
timer.clear()
}
destroyCallbacks.forEach(function (cb) {
cb()
})
}
function compileProcedure (options) {
check(!!options, 'invalid args to regl({...})')
check.type(options, 'object', 'invalid args to regl({...})')
function flattenNestedOptions (options) {
var result = extend({}, options)
delete result.uniforms
delete result.attributes
delete result.context
if ('stencil' in result && result.stencil.op) {
result.stencil.opBack = result.stencil.opFront = result.stencil.op
delete result.stencil.op
}
function merge (name) {
if (name in result) {
var child = result[name]
delete result[name]
Object.keys(child).forEach(function (prop) {
result[name + '.' + prop] = child[prop]
})
}
}
merge('blend')
merge('depth')
merge('cull')
merge('stencil')
merge('polygonOffset')
merge('scissor')
merge('sample')
return result
}
function separateDynamic (object) {
var staticItems = {}
var dynamicItems = {}
Object.keys(object).forEach(function (option) {
var value = object[option]
if (dynamic.isDynamic(value)) {
dynamicItems[option] = dynamic.unbox(value, option)
} else {
staticItems[option] = value
}
})
return {
dynamic: dynamicItems,
static: staticItems
}
}
// Treat context variables separate from other dynamic variables
var context = separateDynamic(options.context || {})
var uniforms = separateDynamic(options.uniforms || {})
var attributes = separateDynamic(options.attributes || {})
var opts = separateDynamic(flattenNestedOptions(options))
var stats = {
gpuTime: 0.0,
cpuTime: 0.0,
count: 0
}
var compiled = core.compile(opts, attributes, uniforms, context, stats)
var draw = compiled.draw
var batch = compiled.batch
var scope = compiled.scope
// FIXME: we should modify code generation for batch commands so this
// isn't necessary
var EMPTY_ARRAY = []
function reserve (count) {
while (EMPTY_ARRAY.length < count) {
EMPTY_ARRAY.push(null)
}
return EMPTY_ARRAY
}
function REGLCommand (args, body) {
var i
if (contextLost) {
check.raise('context lost')
}
if (typeof args === 'function') {
return scope.call(this, null, args, 0)
} else if (typeof body === 'function') {
if (typeof args === 'number') {
for (i = 0; i < args; ++i) {
scope.call(this, null, body, i)
}
return
} else if (Array.isArray(args)) {
for (i = 0; i < args.length; ++i) {
scope.call(this, args[i], body, i)
}
return
} else {
return scope.call(this, args, body, 0)
}
} else if (typeof args === 'number') {
if (args > 0) {
return batch.call(this, reserve(args | 0), args | 0)
}
} else if (Array.isArray(args)) {
if (args.length) {
return batch.call(this, args, args.length)
}
} else {
return draw.call(this, args)
}
}
return extend(REGLCommand, {
stats: stats
})
}
function clear (options) {
check(
typeof options === 'object' && options,
'regl.clear() takes an object as input')
var clearFlags = 0
core.procs.poll()
var c = options.color
if (c) {
gl.clearColor(+c[0] || 0, +c[1] || 0, +c[2] || 0, +c[3] || 0)
clearFlags |= GL_COLOR_BUFFER_BIT
}
if ('depth' in options) {
gl.clearDepth(+options.depth)
clearFlags |= GL_DEPTH_BUFFER_BIT
}
if ('stencil' in options) {
gl.clearStencil(options.stencil | 0)
clearFlags |= GL_STENCIL_BUFFER_BIT
}
check(!!clearFlags, 'called regl.clear with no buffer specified')
gl.clear(clearFlags)
}
function frame (cb) {
check.type(cb, 'function', 'regl.frame() callback must be a function')
rafCallbacks.push(cb)
function cancel () {
// FIXME: should we check something other than equals cb here?
// what if a user calls frame twice with the same callback...
//
var i = find(rafCallbacks, cb)
check(i >= 0, 'cannot cancel a frame twice')
function pendingCancel () {
var index = find(rafCallbacks, pendingCancel)
rafCallbacks[index] = rafCallbacks[rafCallbacks.length - 1]
rafCallbacks.length -= 1
if (rafCallbacks.length <= 0) {
stopRAF()
}
}
rafCallbacks[i] = pendingCancel
}
startRAF()
return {
cancel: cancel
}
}
// poll viewport
function pollViewport () {
var viewport = nextState.viewport
var scissorBox = nextState.scissor_box
viewport[0] = viewport[1] = scissorBox[0] = scissorBox[1] = 0
contextState.viewportWidth =
contextState.framebufferWidth =
contextState.drawingBufferWidth =
viewport[2] =
scissorBox[2] = gl.drawingBufferWidth
contextState.viewportHeight =
contextState.framebufferHeight =
contextState.drawingBufferHeight =
viewport[3] =
scissorBox[3] = gl.drawingBufferHeight
}
function poll () {
contextState.tick += 1
contextState.time = now()
pollViewport()
core.procs.poll()
}
function refresh () {
pollViewport()
core.procs.refresh()
if (timer) {
timer.update()
}
}
function now () {
return (clock() - START_TIME) / 1000.0
}
refresh()
function addListener (event, callback) {
check.type(callback, 'function', 'listener callback must be a function')
var callbacks
switch (event) {
case 'frame':
return frame(callback)
case 'lost':
callbacks = lossCallbacks
break
case 'restore':
callbacks = restoreCallbacks
break
case 'destroy':
callbacks = destroyCallbacks
break
default:
check.raise('invalid event, must be one of frame,lost,restore,destroy')
}
callbacks.push(callback)
return {
cancel: function () {
for (var i = 0; i < callbacks.length; ++i) {
if (callbacks[i] === callback) {
callbacks[i] = callbacks[callbacks.length - 1]
callbacks.pop()
return
}
}
}
}
}
var regl = extend(compileProcedure, {
// Clear current FBO
clear: clear,
// Short cuts for dynamic variables
prop: dynamic.define.bind(null, DYN_PROP),
context: dynamic.define.bind(null, DYN_CONTEXT),
this: dynamic.define.bind(null, DYN_STATE),
// executes an empty draw command
draw: compileProcedure({}),
// Resources
buffer: function (options) {
return bufferState.create(options, GL_ARRAY_BUFFER, false, false)
},
elements: function (options) {
return elementState.create(options, false)
},
texture: textureState.create2D,
cube: textureState.createCube,
renderbuffer: renderbufferState.create,
framebuffer: framebufferState.create,
framebufferCube: framebufferState.createCube,
// Expose context attributes
attributes: glAttributes,
// Frame rendering
frame: frame,
on: addListener,
// System limits
limits: limits,
hasExtension: function (name) {
return limits.extensions.indexOf(name.toLowerCase()) >= 0
},
// Read pixels
read: readPixels,
// Destroy regl and all associated resources
destroy: destroy,
// Direct GL state manipulation
_gl: gl,
_refresh: refresh,
poll: function () {
poll()
if (timer) {
timer.update()
}
},
// Current time
now: now,
// regl Statistics Information
stats: stats
})
config.onDone(null, regl)
return regl
}
/***/ },
/* 2 */
/***/ function(module, exports, __webpack_require__) {
// Error checking and parameter validation.
//
// Statements for the form `check.someProcedure(...)` get removed by
// a browserify transform for optimized/minified bundles.
//
/* globals btoa */
var isTypedArray = __webpack_require__(3)
var extend = __webpack_require__(5)
// only used for extracting shader names. if btoa not present, then errors
// will be slightly crappier
function decodeB64 (str) {
if (typeof btoa !== 'undefined') {
return btoa(str)
}
return 'base64:' + str
}
function raise (message) {
var error = new Error('(regl) ' + message)
console.error(error)
throw error
}
function check (pred, message) {
if (!pred) {
raise(message)
}
}
function encolon (message) {
if (message) {
return ': ' + message
}
return ''
}
function checkParameter (param, possibilities, message) {
if (!(param in possibilities)) {
raise('unknown parameter (' + param + ')' + encolon(message) +
'. possible values: ' + Object.keys(possibilities).join())
}
}
function checkIsTypedArray (data, message) {
if (!isTypedArray(data)) {
raise(
'invalid parameter type' + encolon(message) +
'. must be a typed array')
}
}
function checkTypeOf (value, type, message) {
if (typeof value !== type) {
raise(
'invalid parameter type' + encolon(message) +
'. expected ' + type + ', got ' + (typeof value))
}
}
function checkNonNegativeInt (value, message) {
if (!((value >= 0) &&
((value | 0) === value))) {
raise('invalid parameter type, (' + value + ')' + encolon(message) +
'. must be a nonnegative integer')
}
}
function checkOneOf (value, list, message) {
if (list.indexOf(value) < 0) {
raise('invalid value' + encolon(message) + '. must be one of: ' + list)
}
}
var constructorKeys = [
'gl',
'canvas',
'container',
'attributes',
'pixelRatio',
'extensions',
'optionalExtensions',
'profile',
'onDone'
]
function checkConstructor (obj) {
Object.keys(obj).forEach(function (key) {
if (constructorKeys.indexOf(key) < 0) {
raise('invalid regl constructor argument "' + key + '". must be one of ' + constructorKeys)
}
})
}
function leftPad (str, n) {
str = str + ''
while (str.length < n) {
str = ' ' + str
}
return str
}
function ShaderFile () {
this.name = 'unknown'
this.lines = []
this.index = {}
this.hasErrors = false
}
function ShaderLine (number, line) {
this.number = number
this.line = line
this.errors = []
}
function ShaderError (fileNumber, lineNumber, message) {
this.file = fileNumber
this.line = lineNumber
this.message = message
}
function guessCommand () {
var error = new Error()
var stack = (error.stack || error).toString()
var pat = /compileProcedure.*\n\s*at.*\((.*)\)/.exec(stack)
if (pat) {
return pat[1]
}
var pat2 = /compileProcedure.*\n\s*at\s+(.*)(\n|$)/.exec(stack)
if (pat2) {
return pat2[1]
}
return 'unknown'
}
function guessCallSite () {
var error = new Error()
var stack = (error.stack || error).toString()
var pat = /at REGLCommand.*\n\s+at.*\((.*)\)/.exec(stack)
if (pat) {
return pat[1]
}
var pat2 = /at REGLCommand.*\n\s+at\s+(.*)\n/.exec(stack)
if (pat2) {
return pat2[1]
}
return 'unknown'
}
function parseSource (source, command) {
var lines = source.split('\n')
var lineNumber = 1
var fileNumber = 0
var files = {
unknown: new ShaderFile(),
0: new ShaderFile()
}
files.unknown.name = files[0].name = command || guessCommand()
files.unknown.lines.push(new ShaderLine(0, ''))
for (var i = 0; i < lines.length; ++i) {
var line = lines[i]
var parts = /^\s*\#\s*(\w+)\s+(.+)\s*$/.exec(line)
if (parts) {
switch (parts[1]) {
case 'line':
var lineNumberInfo = /(\d+)(\s+\d+)?/.exec(parts[2])
if (lineNumberInfo) {
lineNumber = lineNumberInfo[1] | 0
if (lineNumberInfo[2]) {
fileNumber = lineNumberInfo[2] | 0
if (!(fileNumber in files)) {
files[fileNumber] = new ShaderFile()
}
}
}
break
case 'define':
var nameInfo = /SHADER_NAME(_B64)?\s+(.*)$/.exec(parts[2])
if (nameInfo) {
files[fileNumber].name = (nameInfo[1]
? decodeB64(nameInfo[2])
: nameInfo[2])
}
break
}
}
files[fileNumber].lines.push(new ShaderLine(lineNumber++, line))
}
Object.keys(files).forEach(function (fileNumber) {
var file = files[fileNumber]
file.lines.forEach(function (line) {
file.index[line.number] = line
})
})
return files
}
function parseErrorLog (errLog) {
var result = []
errLog.split('\n').forEach(function (errMsg) {
if (errMsg.length < 5) {
return
}
var parts = /^ERROR\:\s+(\d+)\:(\d+)\:\s*(.*)$/.exec(errMsg)
if (parts) {
result.push(new ShaderError(
parts[1] | 0,
parts[2] | 0,
parts[3].trim()))
} else if (errMsg.length > 0) {
result.push(new ShaderError('unknown', 0, errMsg))
}
})
return result
}
function annotateFiles (files, errors) {
errors.forEach(function (error) {
var file = files[error.file]
if (file) {
var line = file.index[error.line]
if (line) {
line.errors.push(error)
file.hasErrors = true
return
}
}
files.unknown.hasErrors = true
files.unknown.lines[0].errors.push(error)
})
}
function checkShaderError (gl, shader, source, type, command) {
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
var errLog = gl.getShaderInfoLog(shader)
var typeName = type === gl.FRAGMENT_SHADER ? 'fragment' : 'vertex'
checkCommandType(source, 'string', typeName + ' shader source must be a string', command)
var files = parseSource(source, command)
var errors = parseErrorLog(errLog)
annotateFiles(files, errors)
Object.keys(files).forEach(function (fileNumber) {
var file = files[fileNumber]
if (!file.hasErrors) {
return
}
var strings = ['']
var styles = ['']
function push (str, style) {
strings.push(str)
styles.push(style || '')
}
push('file number ' + fileNumber + ': ' + file.name + '\n', 'color:red;text-decoration:underline;font-weight:bold')
file.lines.forEach(function (line) {
if (line.errors.length > 0) {
push(leftPad(line.number, 4) + '| ', 'background-color:yellow; font-weight:bold')
push(line.line + '\n', 'color:red; background-color:yellow; font-weight:bold')
// try to guess token
var offset = 0
line.errors.forEach(function (error) {
var message = error.message
var token = /^\s*\'(.*)\'\s*\:\s*(.*)$/.exec(message)
if (token) {
var tokenPat = token[1]
message = token[2]
switch (tokenPat) {
case 'assign':
tokenPat = '='
break
}
offset = Math.max(line.line.indexOf(tokenPat, offset), 0)
} else {
offset = 0
}
push(leftPad('| ', 6))
push(leftPad('^^^', offset + 3) + '\n', 'font-weight:bold')
push(leftPad('| ', 6))
push(message + '\n', 'font-weight:bold')
})
push(leftPad('| ', 6) + '\n')
} else {
push(leftPad(line.number, 4) + '| ')
push(line.line + '\n', 'color:red')
}
})
if (typeof document !== 'undefined') {
styles[0] = strings.join('%c')
console.log.apply(console, styles)
} else {
console.log(strings.join(''))
}
})
check.raise('Error compiling ' + typeName + ' shader, ' + files[0].name)
}
}
function checkLinkError (gl, program, fragShader, vertShader, command) {
if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
var errLog = gl.getProgramInfoLog(program)
var fragParse = parseSource(fragShader, command)
var vertParse = parseSource(vertShader, command)
var header = 'Error linking program with vertex shader, "' +
vertParse[0].name + '", and fragment shader "' + fragParse[0].name + '"'
if (typeof document !== 'undefined') {
console.log('%c' + header + '\n%c' + errLog,
'color:red;text-decoration:underline;font-weight:bold',
'color:red')