Sending data to a shader using per vertex attributes and VBOs - Fish-In-A-Suit/Conquest GitHub Wiki
Per vertex attributes are declared with the keyword in (inside a shader written in GLSL). Data for tgese attributes must be supplied by the "main source code" - the game engine.
//vertex shader
#version 400
in vec3 VertexPosition;
in vec3 VertexColour;
out vec3 Colour;
void main() {
Colour = VertexColour;
gl_Position = vec4(VertexPosition, 1)
//gl_Position is a built-in output variable
}
//fragment shader
#version 400
in vec3 Colour;
out vec4 FragColour;
void main() {
FragColour = vec4(Colour, 1);
}
- Define the mapping prior to linking the program
glBindAttribLocation(programID, 0, "VertexPosition")
glBindAttribLocation(programID, 0, "VertexColour")
- Create the VAO
int vaoID = glGenVertexArrays();
- Create and populate vertex buffer objects for each attribute
float[] positionData = {
-0.5f, 0.5f, 0f,
-0.5f, -0.5f, 0f,
0.5f, -0.5f, 0f,
0.5f, 0.5f, 0f
};
int[] indices = {
0, 1, 3, //top left triangle (V0, V1, V3)
3, 1, 2 //bottom right triangle (V3, V1, V2)
};
float[] colourData = {
1.0f, 0.0f, 0.0f,
0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 1.0f,
1.0f, 1.0f, 0.0f
};
- Transform the array data to corresponding array type
FloatBuffer positionBuffer = BufferUtils.createFloatBuffer(positionData.length);
positionBuffer.put(positionData).flip();
IntBuffer indicesBuffer = BufferUtils.createIntBuffer(indices.length);
indicesBuffer.put(indices).flip();
FloatBuffer colourBuffer = BufferUtils.createFloatBuffer(colourData.length);
colourBuffer.put(colourData).flip();
- Create and populate vertex buffer objects for each attribute
posVboID = glGenBuffers();
glBindBuffer(GL_ARRAY_BUFFER, posVboID);
glBufferData(GL_ARRAY_BUFFER, positionBuffer, GL_STATIC_DRAW);
colourVboID = glGenBuffers();
glBindBuffer(GL_ARRAY_BUFFER, colourVboID);
glBufferData(GL_ARRAY_BUFFER, colourBuffer, GL_STATIC_DRAW);
indicesVboID = glGenBuffers();
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indicesVboID);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indicesBuffer, GL_STATIC_DRAW);
The target GL_ARRAY_BUFFER is used whenever storing vertex attribute data.
- Create and bind to a vertex array object, which stores the relationship between the buffers and the input attributes
glBindVertexArray(vaoID);
glEnableVertexAttribArray(0); //position
glEnableVertexAttribArray(1); //colour
glBindBuffer(GL_ARRAY_BUFFER, positionsVboID);
glVertexAttribPointer(0, 3, GL_, false, 0, 0);
glBindBuffer(GL_ARRAY_BUFFER, colourVboID);
glVertexAttribPointer(0, 3, GL_FLOAT, false, 0, 0);
- In the render function, bind the vao and the indices vbo and call glDrawElements:
glBindVertexArray(vaoID);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh.getIndicesVboID());
glDrawElements(GL_TRIANGLES, positionData.length, GL_UNSIGNED_INT, 0);