liveBook · Manning

Vertex attribute

As explained in Systems Programming with Zig

A vertex attribute is a piece of per-vertex data, such as position, color, or texture coordinates, supplied to a graphics pipeline.

A triangle needs three vertices, and each vertex needs data for the vertex shader. A vertex attribute is one piece of that per-vertex input, such as a position. Think of attributes as shader parameters supplied from buffers: the shader processes one set at a time. section 7.4.4 section 7.4.5

In OpenGL, a vertex buffer object (VBO) stores the data but does not describe its meaning. A vertex array object (VAO) preserves the attribute configuration that tells OpenGL how to interpret it. Draw calls specify how many vertices to process. section 7.4.4 section 7.4.5

Listing 7.13 Properly storing our vertices
var triangle_vbo: c_uint = undefined;
c.glGenBuffers(1, &triangle_vbo); #1
defer c.glDeleteBuffers(1, &triangle_vbo); #1

{
    c.glBindBuffer(c.GL_ARRAY_BUFFER, triangle_vbo); #2
    defer c.glBindBuffer(c.GL_ARRAY_BUFFER, 0); #3

    c.glBufferData( #4
        c.GL_ARRAY_BUFFER, #5
        triangle.len * @sizeOf(f32), #6
        @ptrCast(&triangle), #7
        c.GL_STATIC_DRAW, #8
    );
}

This Zig listing creates a VBO, binds it to GL_ARRAY_BUFFER, and uploads the triangle data. GL_STATIC_DRAW is a usage hint, not a guarantee about where the data lives. section 7.4.5

Listing 7.14 Explaining our vertices to the VAO
{ #1
    c.glBindBuffer(c.GL_ARRAY_BUFFER, triangle_vbo); #2
    defer c.glBindBuffer(c.GL_ARRAY_BUFFER, 0); #2

    c.glBindVertexArray(vao); #3
    defer c.glBindVertexArray(0); #3

    c.glVertexAttribPointer(
        0, #4
        2, #5
        c.GL_FLOAT, #6
        c.GL_FALSE, #7
        2 * @sizeOf(f32), #8
        @ptrFromInt(0), #9
    );
    c.glEnableVertexAttribArray(0); #10
}

With the VBO and VAO bound, this configures attribute 0 as two floats per vertex, with a stride of two floats and a zero-byte offset, then enables it. section 7.4.5

Binding is implicit state: buffer operations act on the object currently bound to a target. Keep bindings short-lived and use Zig’s defer to reset them to 0; invisible state is a fine way to collect invisible failures. section 7.4.5

How Systems Programming with Zig covers it

How deep it goes
Explains buffer storage, binding, attribute layout, and enabling through a triangle setup.
Examples
Uses a triangle with a two-float attribute, uploaded to a VBO and configured in a VAO.
What you can do after
Apply it via OpenGL to upload and configure vertex data for a shader.
How it connects
Connects vertex shaders, vertex buffer objects, vertex array objects, and the rasterization pipeline.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Systems Programming with Zig. The section links point to the parts of the book it draws on.