Brain Dump

Vertex Attributes

Tags
opengl

Vertex attributes refer to the data we pass into vertex shaders. This data comes from memory managed in VBOs.

After declaring and binding a VBO we can declare it as a vertex-attribute pointer.

glVertexAttribPointer(
    0,                 // Location of attribute in shader that we're referencing.
    3,                 // Size Of The Vector Being Configured (Vec3) for this vertex attribute.
    GL_FLOAT,          // The Kind Of Data Stored In The Vector.
    GL_FALSE,          // Whether we want to normalise the data into [[id:7067ae56-52a3-4049-b4d6-0e647c38a8ba][NDC]].
    3 * sizeof(float), // The space from this vertex attribute to the next. I.E. how many bytes until this vertex ends and the next begins.
    (void*)0           // The offset of where position-data. If we have extra data after vertex positions, we want to skip over them.
);

We also have to enable a vertex attribute after assigning it. By default vertex-attributes are disabled.

glEnableVertexAttribArray(0); // enable the vertex-attribute at 0.

Limits

OpenGL guarantees at least 16 4-component vertex-attribute spots exist, however more may be available. See GL_MAX_VERTEX_ATTRIBS.

Example

Here's how vertex attributes fit into the order of drawing in OpenGL.

// 0. create and assign a VBO.
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
// 1. then set the vertex attributes pointers for this VBO
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);

Note That glVertexAttribPointer approach inherently assumes we're working with a collection of vertices.

float vertices[] = {
    // positions         // colors
     0.5f, -0.5f, 0.0f,  1.0f, 0.0f, 0.0f,   // bottom right
    -0.5f, -0.5f, 0.0f,  0.0f, 1.0f, 0.0f,   // bottom left
     0.0f,  0.5f, 0.0f,  0.0f, 0.0f, 1.0f    // top
};

// position attribute - begins at an offset of 0 and repeats every 6 floats.
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
// color attribute - begins at an offset of 3 and repeats every 6 floats.
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)(3* sizeof(float)));
glEnableVertexAttribArray(1);

Links to this note