-
Notifications
You must be signed in to change notification settings - Fork 3.5k
/
ShaderProgram.js
641 lines (551 loc) · 19.2 KB
/
ShaderProgram.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
import Check from "../Core/Check.js";
import defaultValue from "../Core/defaultValue.js";
import defined from "../Core/defined.js";
import destroyObject from "../Core/destroyObject.js";
import DeveloperError from "../Core/DeveloperError.js";
import RuntimeError from "../Core/RuntimeError.js";
import AutomaticUniforms from "./AutomaticUniforms.js";
import ContextLimits from "./ContextLimits.js";
import createUniform from "./createUniform.js";
import createUniformArray from "./createUniformArray.js";
let nextShaderProgramId = 0;
/**
* @private
*/
function ShaderProgram(options) {
let vertexShaderText = options.vertexShaderText;
let fragmentShaderText = options.fragmentShaderText;
if (typeof spector !== "undefined") {
// The #line statements common in Cesium shaders interfere with the ability of the
// SpectorJS to show errors on the correct line. So remove them when SpectorJS
// is active.
vertexShaderText = vertexShaderText.replace(/^#line/gm, "//#line");
fragmentShaderText = fragmentShaderText.replace(/^#line/gm, "//#line");
}
const modifiedFS = handleUniformPrecisionMismatches(
vertexShaderText,
fragmentShaderText
);
this._gl = options.gl;
this._logShaderCompilation = options.logShaderCompilation;
this._debugShaders = options.debugShaders;
this._attributeLocations = options.attributeLocations;
this._program = undefined;
this._numberOfVertexAttributes = undefined;
this._vertexAttributes = undefined;
this._uniformsByName = undefined;
this._uniforms = undefined;
this._automaticUniforms = undefined;
this._manualUniforms = undefined;
this._duplicateUniformNames = modifiedFS.duplicateUniformNames;
this._cachedShader = undefined; // Used by ShaderCache
/**
* @private
*/
this.maximumTextureUnitIndex = undefined;
this._vertexShaderSource = options.vertexShaderSource;
this._vertexShaderText = options.vertexShaderText;
this._fragmentShaderSource = options.fragmentShaderSource;
this._fragmentShaderText = modifiedFS.fragmentShaderText;
/**
* @private
*/
this.id = nextShaderProgramId++;
}
ShaderProgram.fromCache = function (options) {
options = defaultValue(options, defaultValue.EMPTY_OBJECT);
//>>includeStart('debug', pragmas.debug);
Check.defined("options.context", options.context);
//>>includeEnd('debug');
return options.context.shaderCache.getShaderProgram(options);
};
ShaderProgram.replaceCache = function (options) {
options = defaultValue(options, defaultValue.EMPTY_OBJECT);
//>>includeStart('debug', pragmas.debug);
Check.defined("options.context", options.context);
//>>includeEnd('debug');
return options.context.shaderCache.replaceShaderProgram(options);
};
Object.defineProperties(ShaderProgram.prototype, {
/**
* GLSL source for the shader program's vertex shader.
* @memberof ShaderProgram.prototype
*
* @type {ShaderSource}
* @readonly
*/
vertexShaderSource: {
get: function () {
return this._vertexShaderSource;
},
},
/**
* GLSL source for the shader program's fragment shader.
* @memberof ShaderProgram.prototype
*
* @type {ShaderSource}
* @readonly
*/
fragmentShaderSource: {
get: function () {
return this._fragmentShaderSource;
},
},
vertexAttributes: {
get: function () {
initialize(this);
return this._vertexAttributes;
},
},
numberOfVertexAttributes: {
get: function () {
initialize(this);
return this._numberOfVertexAttributes;
},
},
allUniforms: {
get: function () {
initialize(this);
return this._uniformsByName;
},
},
});
function extractUniforms(shaderText) {
const uniformNames = [];
const uniformLines = shaderText.match(/uniform.*?(?![^{]*})(?=[=\[;])/g);
if (defined(uniformLines)) {
const len = uniformLines.length;
for (let i = 0; i < len; i++) {
const line = uniformLines[i].trim();
const name = line.slice(line.lastIndexOf(" ") + 1);
uniformNames.push(name);
}
}
return uniformNames;
}
function handleUniformPrecisionMismatches(
vertexShaderText,
fragmentShaderText
) {
// If a uniform exists in both the vertex and fragment shader but with different precision qualifiers,
// give the fragment shader uniform a different name. This fixes shader compilation errors on devices
// that only support mediump in the fragment shader.
const duplicateUniformNames = {};
if (!ContextLimits.highpFloatSupported || !ContextLimits.highpIntSupported) {
let i, j;
let uniformName;
let duplicateName;
const vertexShaderUniforms = extractUniforms(vertexShaderText);
const fragmentShaderUniforms = extractUniforms(fragmentShaderText);
const vertexUniformsCount = vertexShaderUniforms.length;
const fragmentUniformsCount = fragmentShaderUniforms.length;
for (i = 0; i < vertexUniformsCount; i++) {
for (j = 0; j < fragmentUniformsCount; j++) {
if (vertexShaderUniforms[i] === fragmentShaderUniforms[j]) {
uniformName = vertexShaderUniforms[i];
duplicateName = `czm_mediump_${uniformName}`;
// Update fragmentShaderText with renamed uniforms
const re = new RegExp(`${uniformName}\\b`, "g");
fragmentShaderText = fragmentShaderText.replace(re, duplicateName);
duplicateUniformNames[duplicateName] = uniformName;
}
}
}
}
return {
fragmentShaderText: fragmentShaderText,
duplicateUniformNames: duplicateUniformNames,
};
}
const consolePrefix = "[Cesium WebGL] ";
function createAndLinkProgram(gl, shader) {
const vsSource = shader._vertexShaderText;
const fsSource = shader._fragmentShaderText;
const vertexShader = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(vertexShader, vsSource);
gl.compileShader(vertexShader);
const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(fragmentShader, fsSource);
gl.compileShader(fragmentShader);
const program = gl.createProgram();
gl.attachShader(program, vertexShader);
gl.attachShader(program, fragmentShader);
gl.deleteShader(vertexShader);
gl.deleteShader(fragmentShader);
const attributeLocations = shader._attributeLocations;
if (defined(attributeLocations)) {
for (const attribute in attributeLocations) {
if (attributeLocations.hasOwnProperty(attribute)) {
gl.bindAttribLocation(
program,
attributeLocations[attribute],
attribute
);
}
}
}
gl.linkProgram(program);
let log;
if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
const debugShaders = shader._debugShaders;
// For performance, only check compile errors if there is a linker error.
if (!gl.getShaderParameter(fragmentShader, gl.COMPILE_STATUS)) {
log = gl.getShaderInfoLog(fragmentShader);
console.error(`${consolePrefix}Fragment shader compile log: ${log}`);
if (defined(debugShaders)) {
const fragmentSourceTranslation = debugShaders.getTranslatedShaderSource(
fragmentShader
);
if (fragmentSourceTranslation !== "") {
console.error(
`${consolePrefix}Translated fragment shader source:\n${fragmentSourceTranslation}`
);
} else {
console.error(`${consolePrefix}Fragment shader translation failed.`);
}
}
gl.deleteProgram(program);
throw new RuntimeError(
`Fragment shader failed to compile. Compile log: ${log}`
);
}
if (!gl.getShaderParameter(vertexShader, gl.COMPILE_STATUS)) {
log = gl.getShaderInfoLog(vertexShader);
console.error(`${consolePrefix}Vertex shader compile log: ${log}`);
if (defined(debugShaders)) {
const vertexSourceTranslation = debugShaders.getTranslatedShaderSource(
vertexShader
);
if (vertexSourceTranslation !== "") {
console.error(
`${consolePrefix}Translated vertex shader source:\n${vertexSourceTranslation}`
);
} else {
console.error(`${consolePrefix}Vertex shader translation failed.`);
}
}
gl.deleteProgram(program);
throw new RuntimeError(
`Vertex shader failed to compile. Compile log: ${log}`
);
}
log = gl.getProgramInfoLog(program);
console.error(`${consolePrefix}Shader program link log: ${log}`);
if (defined(debugShaders)) {
console.error(
`${consolePrefix}Translated vertex shader source:\n${debugShaders.getTranslatedShaderSource(
vertexShader
)}`
);
console.error(
`${consolePrefix}Translated fragment shader source:\n${debugShaders.getTranslatedShaderSource(
fragmentShader
)}`
);
}
gl.deleteProgram(program);
throw new RuntimeError(`Program failed to link. Link log: ${log}`);
}
const logShaderCompilation = shader._logShaderCompilation;
if (logShaderCompilation) {
log = gl.getShaderInfoLog(vertexShader);
if (defined(log) && log.length > 0) {
console.log(`${consolePrefix}Vertex shader compile log: ${log}`);
}
}
if (logShaderCompilation) {
log = gl.getShaderInfoLog(fragmentShader);
if (defined(log) && log.length > 0) {
console.log(`${consolePrefix}Fragment shader compile log: ${log}`);
}
}
if (logShaderCompilation) {
log = gl.getProgramInfoLog(program);
if (defined(log) && log.length > 0) {
console.log(`${consolePrefix}Shader program link log: ${log}`);
}
}
return program;
}
function findVertexAttributes(gl, program, numberOfAttributes) {
const attributes = {};
for (let i = 0; i < numberOfAttributes; ++i) {
const attr = gl.getActiveAttrib(program, i);
const location = gl.getAttribLocation(program, attr.name);
attributes[attr.name] = {
name: attr.name,
type: attr.type,
index: location,
};
}
return attributes;
}
function findUniforms(gl, program) {
const uniformsByName = {};
const uniforms = [];
const samplerUniforms = [];
const numberOfUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
for (let i = 0; i < numberOfUniforms; ++i) {
const activeUniform = gl.getActiveUniform(program, i);
const suffix = "[0]";
const uniformName =
activeUniform.name.indexOf(
suffix,
activeUniform.name.length - suffix.length
) !== -1
? activeUniform.name.slice(0, activeUniform.name.length - 3)
: activeUniform.name;
// Ignore GLSL built-in uniforms returned in Firefox.
if (uniformName.indexOf("gl_") !== 0) {
if (activeUniform.name.indexOf("[") < 0) {
// Single uniform
const location = gl.getUniformLocation(program, uniformName);
// IE 11.0.9 needs this check since getUniformLocation can return null
// if the uniform is not active (e.g., it is optimized out). Looks like
// getActiveUniform() above returns uniforms that are not actually active.
if (location !== null) {
const uniform = createUniform(
gl,
activeUniform,
uniformName,
location
);
uniformsByName[uniformName] = uniform;
uniforms.push(uniform);
if (uniform._setSampler) {
samplerUniforms.push(uniform);
}
}
} else {
// Uniform array
let uniformArray;
let locations;
let value;
let loc;
// On some platforms - Nexus 4 in Firefox for one - an array of sampler2D ends up being represented
// as separate uniforms, one for each array element. Check for and handle that case.
const indexOfBracket = uniformName.indexOf("[");
if (indexOfBracket >= 0) {
// We're assuming the array elements show up in numerical order - it seems to be true.
uniformArray = uniformsByName[uniformName.slice(0, indexOfBracket)];
// Nexus 4 with Android 4.3 needs this check, because it reports a uniform
// with the strange name webgl_3467e0265d05c3c1[1] in our globe surface shader.
if (!defined(uniformArray)) {
continue;
}
locations = uniformArray._locations;
// On the Nexus 4 in Chrome, we get one uniform per sampler, just like in Firefox,
// but the size is not 1 like it is in Firefox. So if we push locations here,
// we'll end up adding too many locations.
if (locations.length <= 1) {
value = uniformArray.value;
loc = gl.getUniformLocation(program, uniformName);
// Workaround for IE 11.0.9. See above.
if (loc !== null) {
locations.push(loc);
value.push(gl.getUniform(program, loc));
}
}
} else {
locations = [];
for (let j = 0; j < activeUniform.size; ++j) {
loc = gl.getUniformLocation(program, `${uniformName}[${j}]`);
// Workaround for IE 11.0.9. See above.
if (loc !== null) {
locations.push(loc);
}
}
uniformArray = createUniformArray(
gl,
activeUniform,
uniformName,
locations
);
uniformsByName[uniformName] = uniformArray;
uniforms.push(uniformArray);
if (uniformArray._setSampler) {
samplerUniforms.push(uniformArray);
}
}
}
}
}
return {
uniformsByName: uniformsByName,
uniforms: uniforms,
samplerUniforms: samplerUniforms,
};
}
function partitionUniforms(shader, uniforms) {
const automaticUniforms = [];
const manualUniforms = [];
for (const uniform in uniforms) {
if (uniforms.hasOwnProperty(uniform)) {
const uniformObject = uniforms[uniform];
let uniformName = uniform;
// if it's a duplicate uniform, use its original name so it is updated correctly
const duplicateUniform = shader._duplicateUniformNames[uniformName];
if (defined(duplicateUniform)) {
uniformObject.name = duplicateUniform;
uniformName = duplicateUniform;
}
const automaticUniform = AutomaticUniforms[uniformName];
if (defined(automaticUniform)) {
automaticUniforms.push({
uniform: uniformObject,
automaticUniform: automaticUniform,
});
} else {
manualUniforms.push(uniformObject);
}
}
}
return {
automaticUniforms: automaticUniforms,
manualUniforms: manualUniforms,
};
}
function setSamplerUniforms(gl, program, samplerUniforms) {
gl.useProgram(program);
let textureUnitIndex = 0;
const length = samplerUniforms.length;
for (let i = 0; i < length; ++i) {
textureUnitIndex = samplerUniforms[i]._setSampler(textureUnitIndex);
}
gl.useProgram(null);
return textureUnitIndex;
}
function initialize(shader) {
if (defined(shader._program)) {
return;
}
reinitialize(shader);
}
function reinitialize(shader) {
const oldProgram = shader._program;
const gl = shader._gl;
const program = createAndLinkProgram(gl, shader, shader._debugShaders);
const numberOfVertexAttributes = gl.getProgramParameter(
program,
gl.ACTIVE_ATTRIBUTES
);
const uniforms = findUniforms(gl, program);
const partitionedUniforms = partitionUniforms(
shader,
uniforms.uniformsByName
);
shader._program = program;
shader._numberOfVertexAttributes = numberOfVertexAttributes;
shader._vertexAttributes = findVertexAttributes(
gl,
program,
numberOfVertexAttributes
);
shader._uniformsByName = uniforms.uniformsByName;
shader._uniforms = uniforms.uniforms;
shader._automaticUniforms = partitionedUniforms.automaticUniforms;
shader._manualUniforms = partitionedUniforms.manualUniforms;
shader.maximumTextureUnitIndex = setSamplerUniforms(
gl,
program,
uniforms.samplerUniforms
);
if (oldProgram) {
shader._gl.deleteProgram(oldProgram);
}
// If SpectorJS is active, add the hook to make the shader editor work.
// https://github.com/BabylonJS/Spector.js/blob/master/documentation/extension.md#shader-editor
if (typeof spector !== "undefined") {
shader._program.__SPECTOR_rebuildProgram = function (
vertexSourceCode, // The new vertex shader source
fragmentSourceCode, // The new fragment shader source
onCompiled, // Callback triggered by your engine when the compilation is successful. It needs to send back the new linked program.
onError // Callback triggered by your engine in case of error. It needs to send the WebGL error to allow the editor to display the error in the gutter.
) {
const originalVS = shader._vertexShaderText;
const originalFS = shader._fragmentShaderText;
// SpectorJS likes to replace `!=` with `! =` for unknown reasons,
// and that causes glsl compile failures. So fix that up.
const regex = / ! = /g;
shader._vertexShaderText = vertexSourceCode.replace(regex, " != ");
shader._fragmentShaderText = fragmentSourceCode.replace(regex, " != ");
try {
reinitialize(shader);
onCompiled(shader._program);
} catch (e) {
shader._vertexShaderText = originalVS;
shader._fragmentShaderText = originalFS;
// Only pass on the WebGL error:
const errorMatcher = /(?:Compile|Link) error: ([^]*)/;
const match = errorMatcher.exec(e.message);
if (match) {
onError(match[1]);
} else {
onError(e.message);
}
}
};
}
}
ShaderProgram.prototype._bind = function () {
initialize(this);
this._gl.useProgram(this._program);
};
ShaderProgram.prototype._setUniforms = function (
uniformMap,
uniformState,
validate
) {
let len;
let i;
if (defined(uniformMap)) {
const manualUniforms = this._manualUniforms;
len = manualUniforms.length;
for (i = 0; i < len; ++i) {
const mu = manualUniforms[i];
mu.value = uniformMap[mu.name]();
}
}
const automaticUniforms = this._automaticUniforms;
len = automaticUniforms.length;
for (i = 0; i < len; ++i) {
const au = automaticUniforms[i];
au.uniform.value = au.automaticUniform.getValue(uniformState);
}
///////////////////////////////////////////////////////////////////
// It appears that assigning the uniform values above and then setting them here
// (which makes the GL calls) is faster than removing this loop and making
// the GL calls above. I suspect this is because each GL call pollutes the
// L2 cache making our JavaScript and the browser/driver ping-pong cache lines.
const uniforms = this._uniforms;
len = uniforms.length;
for (i = 0; i < len; ++i) {
uniforms[i].set();
}
if (validate) {
const gl = this._gl;
const program = this._program;
gl.validateProgram(program);
//>>includeStart('debug', pragmas.debug);
if (!gl.getProgramParameter(program, gl.VALIDATE_STATUS)) {
throw new DeveloperError(
`Program validation failed. Program info log: ${gl.getProgramInfoLog(
program
)}`
);
}
//>>includeEnd('debug');
}
};
ShaderProgram.prototype.isDestroyed = function () {
return false;
};
ShaderProgram.prototype.destroy = function () {
this._cachedShader.cache.releaseShaderProgram(this);
return undefined;
};
ShaderProgram.prototype.finalDestroy = function () {
this._gl.deleteProgram(this._program);
return destroyObject(this);
};
export default ShaderProgram;