Search code examples
androidopengl-esshader

OpenGL ES - Fragment shader version


I just got started with OpenGL ES on Android, and I can't seem to specify the version of OpenGL to use in the fragment shader.

This version compiles and runs successfully

void main() {
  gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
}

But this doesn't

#version 300 es
void main() {
  gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
}

I've tried multiple version, with and without "es". The only thing that works is version 100.
Weirdly, I've added #version 300 es in the vertex shader, which works fine.

The code is compiled with

fun createProgram() {
        program = GLES32.glCreateProgram()
        val vertexShader = loadShader(GLES32.GL_VERTEX_SHADER, vertexShaderCode)
        val fragmentShader = loadShader(GLES32.GL_FRAGMENT_SHADER, fragmentShaderCode)
        GLES32.glAttachShader(program, vertexShader)
        GLES32.glAttachShader(program, fragmentShader)
        GLES32.glLinkProgram(program)
        GLES32.glUseProgram(program)
}

fun loadShader(type: Int, shaderCode: String): Int {
    return GLES32.glCreateShader(type).also { shader ->
        // add the source code to the shader and compile it
        GLES32.glShaderSource(shader, shaderCode)
        GLES32.glCompileShader(shader)

        val successPointer = ByteBuffer.allocateDirect(Int.SIZE_BYTES).asIntBuffer()
        GLES32.glGetShaderiv(shader, GLES32.GL_COMPILE_STATUS, successPointer)
        if (successPointer[0] != 0) {
            println("Couldn't compile: ${successPointer[0]} ${GLES32.glGetShaderInfoLog(shader)}")
        }
    }
}

Solution

  • Found it ! gl_FragColor was deprecated and should be replaced by a defined out. This only applies for version 3, hence the error when compiled with a later version...

    As a side note, the correct way to get the GL_COMPILE_STATUS is

    val compiled = IntArray(1)
    GLES32.glGetShaderiv(shader, GLES32.GL_COMPILE_STATUS, compiled, 0)
    if (compiled[0] != GLES32.GL_TRUE) {
        println("Couldn't compile: ${compiled[0]} ${GLES32.glGetShaderInfoLog(shader)}")
    } else {
        println("Successfully compiled!")
    }