【问题标题】:Why my OpenGL custom shader gives me this error?为什么我的 OpenGL 自定义着色器给我这个错误?
【发布时间】:2020-04-16 09:47:06
【问题描述】:

我在 XCode11 上为我的 macOS 应用程序使用带有 cocos2d 3.17 的自定义着色器,但我遇到了一些问题。

myShader.frag

#ifdef GL_ES
 precision lowp float;
#endif

uniform sampler2D u_texture;
varying lowp vec4 v_fragmentColor;
uniform mat4 u_rotation;

void main()
{
  mat4 t1= mat4(1);
  mat4 t2= mat4(1);
  t1[3] = vec4(-0.5,-0.5,1,1);
  t2[3] = vec4(+0.5,+0.5,1,1);
  vec2 pos = (t2 * u_rotation * t1 * vec4(gl_PointCoord, 0, 1)).xy;
  gl_FragColor  =  v_fragmentColor * texture2D(u_texture, pos);
}

myShader.vert

attribute vec4 a_position;
uniform float u_pointSize;
uniform lowp vec4 u_fragmentColor;
varying lowp vec4 v_fragmentColor;

void main()
{
  gl_Position     = CC_MVPMatrix * a_position;
  gl_PointSize    = u_pointSize;
  v_fragmentColor = u_fragmentColor;
}

使用这个配置我有这个错误:

cocos2d: ERROR: 0:21: 'vec4' : 语法错误:语法错误

关于 myShader.vert

我不明白,我觉得很好。

【问题讨论】:

    标签: c++ opengl-es glsl shader cocos2d-x


    【解决方案1】:

    着色器是为OpenGL ES (GLSL ES 1.00) 编写的。当您尝试使用 "desktop" OpenGL 编译着色器时,由于精度限定符,您会遇到错误。

    删除顶点着色器中的精度限定符:

    attribute vec4 a_position;
    uniform float u_pointSize;
    uniform vec4 u_fragmentColor;
    varying vec4 v_fragmentColor;
    
    void main()
    {
      gl_Position     = CC_MVPMatrix * a_position;
      gl_PointSize    = u_pointSize;
      v_fragmentColor = u_fragmentColor;
    }
    

    和片段着色器:

    #ifdef GL_ES
     precision lowp float;
    #endif
    
    uniform sampler2D u_texture;
    varying vec4 v_fragmentColor;
    uniform mat4 u_rotation;
    
    // [...]
    

    在 GLSL 1.30 (OpenGL 3.0) 代码可移植性(不是为了功能)中添加了精确限定符,但之前的版本不支持它们。
    (由于您没有指定版本,因此您使用的是 GLSL 1.00)


    或者,您可以使用宏作为精度限定符:

    #ifdef GL_ES
    #define LOWP lowp 
    #else
    #define LOWP
    #endif
    
    attribute vec4 a_position;
    uniform float u_pointSize;
    uniform LOWP vec4 u_fragmentColor;
    varying LOWP vec4 v_fragmentColor;
    
    // [...]
    
    #ifdef GL_ES
    precision lowp float;
    #define LOWP lowp 
    #else
    #define LOWP
    #endif
    
    uniform sampler2D u_texture;
    varying LOWP vec4 v_fragmentColor;
    uniform mat4 u_rotation;
    
    // [...]
    

    【讨论】:

    • 非常感谢您的回答!我忘了说这是iOS应用程序的移植,这是因为这是用OpenGLES编写的。我改变了它,但现在出现了这个错误:cocos2d: ERROR: 0:33: Use of undeclared identifier 'gl_PointCoord' ERROR: 0:34: Use of undeclared identifier 'pos' for the myShader.frag... 我想这是为了版本,所以我添加了 #version 120 但是 cocos2d: ERROR: 0:18: '' : #version 必须出现在程序中的任何其他语句之前...
    • @ele_elion gl_PointCoord 适用于任何 GLSL 版本。你混淆了顶点着色器和片段着色器吗? 2.#version must occur before any是由于cocos2d在shader代码中添加了一些代码(可能是宏)造成的。
    • 我仔细检查了一下,实际上是片段着色器给了我错误..这是什么意思?
    • 另一件事:我在网上查了一下,发现 OpenGL 文档中有一个错误,说明 gl_PointCoord 是 1.1 的功能,而实际上它是在 1.2 中引入的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-25
    • 2011-06-09
    • 2013-12-28
    • 2011-09-07
    • 1970-01-01
    • 2022-08-12
    相关资源
    最近更新 更多