I want to write an app for Android with OpenGL ES 2.0 that displays a colored rectangle, like that:
This are my 2 shaders:
// Vertex Shader attribute vec4 vPosition; void main() { gl_Position = vPosition; } // Fragment Shader uniform vec4 u_colorRGBA; void main() { gl_FragColor = u_colorRGBA; }
I can draw rectangles with different colors, but i want to draw them so each corner has a diffrent color. Can i pass variables from the vertex shader to the fragment shader to define the color of each corner? If so how do i define the variables and pass them over? Or is there another way to do it?
Answer
I figured out a way to do it:
I changed my shaders like this:
// Vertex Shader attribute vec4 inColor; varying vec4 vColor; attribute vec4 vPosition; void main() { gl_Position = vPosition; vColor = inColor; } // Fragment Shader varying vec4 vColor; void main() { gl_FragColor = vColor; }
Then i draw the rectangle like that:
public static void Draw(float vertices[], int verticesCount, float color[]) { vertexBuffer.put(vertices); vertexBuffer.position(0); GLES20.glEnableVertexAttribArray(sPosition); GLES20.glVertexAttribPointer(sPosition, 3, GLES20.GL_FLOAT, false, 0, vertexBuffer); colorBuffer.put(color); colorBuffer.position(0); GLES20.glEnableVertexAttribArray(sColor); GLES20.glVertexAttribPointer(sColor, 4, GLES20.GL_FLOAT, false, 0, colorBuffer); GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, verticesCount); // Draw GLES20.glDisableVertexAttribArray(sPosition); GLES20.glDisableVertexAttribArray(sColor); }
Is this the correct way of doing it? Or are their better ways?