题
我正在尝试在WebGL和JavaScript中制作一个简单的应用程序,并且在Internet上发现的一些教程时,我在创建一些基本的着色器时遇到了一个奇怪的问题。创建着色器程序的功能看起来像这样:
this.CreateShaderProgram = function(vertexShader, fragmentShader)
{
var tmp = this.gl.createProgram();
var tempVert = this.gl.createShader(this.gl.VERTEX_SHADER);
this.gl.shaderSource(tempVert, vertexShader);
this.gl.compileShader(tempVert);
if(!this.gl.getShaderParameter(tempVert, this.gl.COMPILE_STATUS)) {
this.Log("invalid shader : " + vertexShader);
return null;
};
var tempFrag = this.gl.createShader(this.gl.FRAGMENT_SHADER);
this.gl.shaderSource(tempFrag, fragmentShader);
this.gl.compileShader(tempFrag);
if(!this.gl.getShaderParameter(tempFrag, this.gl.COMPILE_STATUS)) {
this.Log("invalid shader : " + fragmentShader);
return null;
};
this.gl.attachShader(tmp, tempVert);
this.gl.attachShader(tmp, tempFrag);
return tmp;
}
两个着色器看起来像:
attribute vec3 aVertexPosition;
uniform mat4 uMVMatrix;
uniform mat4 uPMatrix;
void main(void) {
gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);
}
--------------------------------------------
#ifdef GL_ES precision highp float;
#endif
void main(void) {
gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0); };
奇怪的是,第一个顶点着色器成功地编译了,但是对于片段着色器,它在“ this.gl.compileshader(tempfrag)”上崩溃了;线,我不知道为什么。
解决方案
来自您的代码的摘要:
#ifdef GL_ES precision highp float;
#endif
应该在单独的行上:
#ifdef GL_ES
precision highp float;
#endif
这是因为阴影语言使用预处理器,很像 C预处理器. 。以开始的线 #
是跨整个行的预处理器指令。而 precision
声明不是;这只是GLSL中的正常陈述。将它们放在同一条线上会使预处理器混淆,因为它将精度语句视为指令的一部分。
ZECC使用的建议 getShaderInfoLog
对于调试这类问题也是无价的。
其他提示
如果您不知道为什么不编译,请这样更改您的代码:
this.gl.compileShader(tempFrag);
if(!this.gl.getShaderParameter(tempFrag, this.gl.COMPILE_STATUS)) {
this.Log("invalid shader : " + this.gl.getShaderInfoLog(tempFrag));
return null;
};
这应该为您提供有关错误的信息的更多信息(可能使用 #ifdef
)
不隶属于 StackOverflow