GLShader.java 8.4 KB
Newer Older
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
1 2
package com.projectseptember.RNGL;

Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
3

Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
4 5 6 7 8 9
import static android.opengl.GLES20.*;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
10
import java.util.ArrayList;
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
11
import java.util.HashMap;
12
import java.util.List;
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
13 14 15 16 17 18 19 20
import java.util.Map;

public class GLShader {

    private final String name;
    private final String vert;
    private final String frag;
    private Map<String, Integer> uniformTypes;
21
    private List<String> uniformNames;
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
22 23 24 25
    private int program; // Program of the shader
    private int buffer[]; // the buffer currently contains 2 static triangles covering the surface
    private int pointerLoc; // The "pointer" attribute is used to iterate over vertex
    private Map<String, Integer> uniformLocations; // The uniform locations cache
26
    private Map<String, Integer> uniformSizes; // The size of the uniform variable
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
27

28 29 30
    private Integer id;
    private RNGLContext rnglContext;
    private GLShaderCompilationFailed compilationFailed;
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
31

32
    public GLShader(GLShaderData data, Integer id, RNGLContext rnglContext) {
Gaëtan Renaudeau's avatar
Gaëtan Renaudeau committed
33 34 35
        this.name = data.name;
        this.vert = data.vert;
        this.frag = data.frag;
36 37
        this.id = id;
        this.rnglContext = rnglContext;
Gaëtan Renaudeau's avatar
Gaëtan Renaudeau committed
38 39
    }

Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
40 41 42 43
    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        if (buffer != null) {
44
            // TODO: need to check if this works properly
Gaëtan Renaudeau's avatar
Gaëtan Renaudeau committed
45
            glDeleteProgram(program);
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
46 47 48 49
            glDeleteBuffers(1, buffer, 0);
        }
    }

Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
50
    public void runtimeException (String msg) {
51
        throw new GLShaderCompilationFailed(name, msg);
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
52 53
    }

Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
54
    public void bind () {
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
55 56
        ensureCompile();

Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
57
        if (!glIsProgram(program)) {
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
58
            runtimeException("not a program");
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
59 60 61 62 63 64 65 66 67 68 69 70 71
        }
        glUseProgram(program);
        glBindBuffer(GL_ARRAY_BUFFER, buffer[0]);
        glEnableVertexAttribArray(pointerLoc);
        glVertexAttribPointer(pointerLoc, 2, GL_FLOAT, false, 0, 0);
    }

    public void validate () {
        glValidateProgram(program);
        int[] validSuccess = new int[1];
        glGetProgramiv(program, GL_VALIDATE_STATUS, validSuccess, 0);
        if (validSuccess[0] == GL_FALSE) {
            glGetProgramInfoLog(program);
72
            runtimeException(glGetProgramInfoLog(program));
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
        }
    }

    public void setUniform (String name, Integer i) {
        glUniform1i(uniformLocations.get(name), i);
    }
    public void setUniform (String name, Float f) {
        glUniform1f(uniformLocations.get(name), f);
    }
    public void setUniform (String name, FloatBuffer buf, int type) {
        switch (type) {
            case GL_FLOAT_VEC2:
                glUniform2fv(uniformLocations.get(name), 1, buf);
                break;
            case GL_FLOAT_VEC3:
                glUniform3fv(uniformLocations.get(name), 1, buf);
                break;
            case GL_FLOAT_VEC4:
                glUniform4fv(uniformLocations.get(name), 1, buf);
                break;
            case GL_FLOAT_MAT2:
                glUniformMatrix2fv(uniformLocations.get(name), 1, false, buf);
                break;
            case GL_FLOAT_MAT3:
                glUniformMatrix3fv(uniformLocations.get(name), 1, false, buf);
                break;
            case GL_FLOAT_MAT4:
                glUniformMatrix4fv(uniformLocations.get(name), 1, false, buf);
                break;
            default:
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
103
                runtimeException("Unsupported case: uniform '" + name + "' type: " + type);
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
        }
    }
    public void setUniform (String name, IntBuffer buf, int type) {
        switch (type) {
            case GL_INT_VEC2:
            case GL_BOOL_VEC2:
                glUniform2iv(uniformLocations.get(name), 1, buf);
                break;
            case GL_INT_VEC3:
            case GL_BOOL_VEC3:
                glUniform3iv(uniformLocations.get(name), 1, buf);
                break;
            case GL_INT_VEC4:
            case GL_BOOL_VEC4:
                glUniform4iv(uniformLocations.get(name), 1, buf);
                break;
            default:
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
121
                runtimeException("Unsupported case: uniform '"+name+"' type: "+type);
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
122 123 124 125 126 127 128 129 130 131
        }
    }

    public String getName() {
        return name;
    }

    public Map<String, Integer> getUniformTypes() {
        return uniformTypes;
    }
132 133 134 135
    public Map<String, Integer> getUniformSizes() {
        return uniformSizes;
    }
    public List<String> getUniformNames() { return uniformNames; }
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
136

Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
137
    private int compileShader (String code, int shaderType) {
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
138 139 140 141 142 143
        int shaderHandle = glCreateShader(shaderType);
        glShaderSource(shaderHandle, code);
        glCompileShader(shaderHandle);
        int compileSuccess[] = new int[1];
        glGetShaderiv(shaderHandle, GL_COMPILE_STATUS, compileSuccess, 0);
        if (compileSuccess[0] == GL_FALSE) {
144
            runtimeException(glGetShaderInfoLog(shaderHandle));
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
145 146 147 148 149 150 151 152
            return -1;
        }
        return shaderHandle;
    }

    private void computeMeta () {
        Map<String, Integer> uniforms = new HashMap<>();
        Map<String, Integer> locations = new HashMap<>();
153 154
        Map<String, Integer> sizes = new HashMap<>();
        ArrayList<String> uniformNames = new ArrayList<>();
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
155 156

        int[] nbUniforms = new int[1];
157 158
        int[] typePointer = new int[1];
        int[] sizePointer = new int[1];
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
159 160
        glGetProgramiv(program, GL_ACTIVE_UNIFORMS, nbUniforms, 0);
        for (int i=0; i < nbUniforms[0]; i++) {
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
            String uniformName = glGetActiveUniform(program, i, sizePointer, 0, typePointer, 0);
            int size = sizePointer[0];
            int type = typePointer[0];
            if (uniformName.contains("[0]")) {
                uniformName = uniformName.substring(0, uniformName.length()-3);
            }
            uniformNames.add(uniformName);
            uniforms.put(uniformName, type);
            sizes.put(uniformName, size);
            if (size == 1) {
                int location = glGetUniformLocation(program, uniformName);
                locations.put(uniformName, location);
            }
            else {
                for (int j=0; j<size; j++) {
                    String uniformIndexName = uniformName+ "[" + j + "]";
                    int location = glGetUniformLocation(program, uniformIndexName);
                    locations.put(uniformIndexName, location);
                    uniforms.put(uniformIndexName, type);
                    sizes.put(uniformIndexName, 1);
                }
            }

Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
184 185 186
        }
        this.uniformTypes = uniforms;
        this.uniformLocations = locations;
187 188
        this.uniformSizes = sizes;
        this.uniformNames = uniformNames;
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
189 190
    }

191
    private void makeProgram () throws GLShaderCompilationFailed {
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
192
        int vertex = compileShader(vert, GL_VERTEX_SHADER);
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
193 194
        if (vertex == -1) return;

Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
195
        int fragment = compileShader(frag, GL_FRAGMENT_SHADER);
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
196 197 198 199 200 201 202 203 204 205
        if (fragment == -1) return;

        program = glCreateProgram();
        glAttachShader(program, vertex);
        glAttachShader(program, fragment);
        glLinkProgram(program);

        int[] linkSuccess = new int[1];
        glGetProgramiv(program, GL_LINK_STATUS, linkSuccess, 0);
        if (linkSuccess[0] == GL_FALSE) {
206
            runtimeException(glGetProgramInfoLog(program));
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
207 208 209 210
        }

        glUseProgram(program);

Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
211 212
        validate();

Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
213 214 215 216 217 218 219 220 221
        computeMeta();

        pointerLoc = glGetAttribLocation(program, "position");

        buffer = new int[1];
        glGenBuffers(1, buffer, 0);
        glBindBuffer(GL_ARRAY_BUFFER, buffer[0]);

        float buf[] = {
222 223 224
            -1.0f, -1.0f,
            -1.0f, 4.0f,
             4.0f,  -1.0f
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
225 226 227 228 229 230 231 232 233 234 235 236 237 238
        };
        FloatBuffer bufferData = ByteBuffer.allocateDirect(buf.length * 4)
                .order(ByteOrder.nativeOrder())
                .asFloatBuffer();
        bufferData.put(buf).position(0);

        glBufferData(GL_ARRAY_BUFFER, buf.length * 4, bufferData, GL_STATIC_DRAW);
    }

    public boolean isReady () {
        return buffer != null && uniformLocations != null;
    }

    public boolean ensureCompile() {
239 240 241 242 243 244 245 246 247 248 249 250
        if (!isReady()) {
            if (compilationFailed != null) throw compilationFailed;
            try {
                makeProgram();
                rnglContext.shaderSucceedToCompile(id, uniformTypes);
            }
            catch (GLShaderCompilationFailed e) {
                compilationFailed = e;
                rnglContext.shaderFailedToCompile(id, e);
                throw e;
            }
        }
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
251 252 253
        return isReady();
    }
}