olha
olha

Reputation: 2262

GLSL versions compatibility

I have shaders which work with 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;
}

I'd like them to work with OpenGL 4.1 (not ES). Does there exist a way to declare both ES and desktop versions in one shader?

Upvotes: 1

Views: 605

Answers (1)

Nicol Bolas
Nicol Bolas

Reputation: 473407

You will need to use a prefix string. glShaderSource takes an array of strings, which will conceptually be concatenated together before processing. So you will need to remove the #version declaration from your shader files and put the version declaration into a string that is generated at runtime. Something like this:

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 core\n";

  strings[1] = (const GLchar*)shader.c_str();
  glShaderSource(shaderName, 2, strings, NULL);

  //Compile your shader and check for errors.

  return shaderName;
}

Your runtime should know whether it's ES or desktop GL.

Also, there is no need for that ifdef around your precision statement. Precision declarations have been part of desktop GL for a while, well before 4.1. Though admittedly, they don't actually do anything ;)

Upvotes: 3

Related Questions