GLSL 版本兼容性



我有适用于GLES 3.0的着色器:

#version 300 es
#ifdef GL_ES
precision mediump float;
#endif
in vec2 v_tex_coord;
uniform sampler2D s_texture;
uniform vec4 u_color;
out vec4 fragmentColor;
void main()
{
    fragmentColor = texture(s_texture, v_tex_coord)*u_color;
}

我希望他们使用OpenGL 4.1(不是ES)。有没有办法在一个着色器中同时声明 ES 和桌面版本?

您需要使用前缀字符串。 glShaderSource 采用一个字符串数组,这些字符串在处理之前在概念上将连接在一起。因此,您需要从着色器文件中删除#version声明,并将版本声明放入运行时生成的字符串中。像这样:

GLuint CreateShader(const std::string &shader)
{
  GLuint shaderName = glCreateShader(GL_VERTEX_SHADER);
  const GLchar *strings[2];
  if(IS_USING_GLES)
    strings[0] = "#version 300 es";
  else
    strings[0] = "#version 410 coren";
  strings[1] = (const GLchar*)shader.c_str();
  glShaderSource(shaderName, 2, strings, NULL);
  //Compile your shader and check for errors.
  return shaderName;
}

您的运行时应该知道它是 ES 还是桌面 GL。

此外,您的precision声明不需要ifdef。精度声明已经成为桌面 GL 的一部分已经有一段时间了,早在 4.1 之前。虽然不可否认,他们实际上并没有做任何事情;)

最新更新