如何让GLSL 300 es着色器在PIXI.JS中运行



我需要在片段着色器中使用textureSize()等函数,但它们在GLSL 100中不可用,这是PIXI默认使用的。如果我尝试使用它们,我会收到错误:

"textureSize'": no matching overloaded function found

如果我试图将#version 300 es添加到我的代码顶部(正如一些人建议的那样(,那么我会得到一个新的错误:

'version' : #version directive must occur before anything else, except for comments and white space

";完整着色器代码";错误附带的预览被标记为PIXI添加了额外的行,我无法删除。

我不能在版本100中使用我需要的功能,我不能在第一行之后更改版本,也不能更改第一行。

好吧,所以我在回答我自己的问题,这样就没有人需要经历这场混乱了。以下是解决方案:

首先,您需要在PIXI预处理着色器代码之后,但在编译之前更改着色器代码。你这样做:

let shaderCode = eventShaderCode;
var simpleShader = new PIXI.Filter(eventVertexShaderCode, shaderCode, this.shaderUniforms);
if (!simpleShader.program.fragmentSrc.includes("#version 300 es")) {
simpleShader.program.vertexSrc = "#version 300 es n" + simpleShader.program.vertexSrc;
simpleShader.program.fragmentSrc =
"#version 300 es n" + simpleShader.program.fragmentSrc;
}

我把代码放在if语句中,因为我的程序中有多个对象使用这个着色器,这可能会导致多次添加#version行。我不能100%确定这是怎么发生的,但我认为这与PIXI可能使用的某种缓存系统有关,因此它不必多次重新编译同一着色器。无论如何:这很重要,即使看起来没有必要。

接下来,您需要实际编写顶点着色器和片段着色器即使您只修改了一个,也需要重写两个为了方便起见,我在版本3中重新编写了这两个默认着色器,因此您可以将它们放入并根据自己的喜好进行修改。

顶点着色器:

in vec2 aVertexPosition;
uniform mat3 projectionMatrix;
out vec2 vTextureCoord;
uniform vec4 inputSize;
uniform vec4 outputFrame;
vec4 filterVertexPosition( void )
{
vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy;
return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);
}
vec2 filterTextureCoord( void )
{
return aVertexPosition * (outputFrame.zw * inputSize.zw);
}
void main(void)
{
gl_Position = filterVertexPosition();
vTextureCoord = filterTextureCoord();
}

片段着色器

precision highp float;
uniform sampler2D uSampler;
in vec2 vTextureCoord;
out vec4 color;
void main(){
color =  texture(uSampler, vTextureCoord);
}

恭喜!现在,您可以在PIXI.JS项目中使用#version 300 es了!

最新更新