1 | "use strict";
|
2 | var math = require("@pixi/math"), Program = require("../shader/Program.js"), Shader = require("../shader/Shader.js"), UniformGroup = require("../shader/UniformGroup.js");
|
3 | class BatchShaderGenerator {
|
4 | |
5 |
|
6 |
|
7 |
|
8 | constructor(vertexSrc, fragTemplate) {
|
9 | if (this.vertexSrc = vertexSrc, this.fragTemplate = fragTemplate, this.programCache = {}, this.defaultGroupCache = {}, !fragTemplate.includes("%count%"))
|
10 | throw new Error('Fragment template must contain "%count%".');
|
11 | if (!fragTemplate.includes("%forloop%"))
|
12 | throw new Error('Fragment template must contain "%forloop%".');
|
13 | }
|
14 | generateShader(maxTextures) {
|
15 | if (!this.programCache[maxTextures]) {
|
16 | const sampleValues = new Int32Array(maxTextures);
|
17 | for (let i = 0; i < maxTextures; i++)
|
18 | sampleValues[i] = i;
|
19 | this.defaultGroupCache[maxTextures] = UniformGroup.UniformGroup.from({ uSamplers: sampleValues }, !0);
|
20 | let fragmentSrc = this.fragTemplate;
|
21 | fragmentSrc = fragmentSrc.replace(/%count%/gi, `${maxTextures}`), fragmentSrc = fragmentSrc.replace(/%forloop%/gi, this.generateSampleSrc(maxTextures)), this.programCache[maxTextures] = new Program.Program(this.vertexSrc, fragmentSrc);
|
22 | }
|
23 | const uniforms = {
|
24 | tint: new Float32Array([1, 1, 1, 1]),
|
25 | translationMatrix: new math.Matrix(),
|
26 | default: this.defaultGroupCache[maxTextures]
|
27 | };
|
28 | return new Shader.Shader(this.programCache[maxTextures], uniforms);
|
29 | }
|
30 | generateSampleSrc(maxTextures) {
|
31 | let src = "";
|
32 | src += `
|
33 | `, src += `
|
34 | `;
|
35 | for (let i = 0; i < maxTextures; i++)
|
36 | i > 0 && (src += `
|
37 | else `), i < maxTextures - 1 && (src += `if(vTextureId < ${i}.5)`), src += `
|
38 | {`, src += `
|
39 | color = texture2D(uSamplers[${i}], vTextureCoord);`, src += `
|
40 | }`;
|
41 | return src += `
|
42 | `, src += `
|
43 | `, src;
|
44 | }
|
45 | }
|
46 | exports.BatchShaderGenerator = BatchShaderGenerator;
|
47 |
|