3. Hello Triangle
Time to draw something.
In this chapter we draw the "hello world" of graphics programming: one orange triangle.
That needs more code than you might expect, because a triangle needs three OpenGL objects that work together: a buffer that holds the vertex data, a vertex array object that describes how to read it, and a program made of a vertex and a fragment shader.
Once those three exist, drawing is a single call, and everything in the rest of the series (models, textures, lights, the games) is built from the same three pieces.
We create the buffer and the vertex array with the modern Direct State Access functions of OpenGL 4.5.
At the end of the chapter we build the same objects again in the classic "bind to edit" style, because that's what most older tutorials and a lot of existing code use, and you should be able to read it.
3.1 What we build
Only src/main.cc changes in this chapter.
Window, the debug logger and CMakeLists.txt stay exactly as they were in chapter 2.
The new main.cc has these parts, which we'll write in this order:
- the vertex data (3.3)
createTriangleDsa(): the buffer and the vertex array, DSA style (3.4 and 3.5)- the two shaders as strings,
compileShader()andlinkProgram()(3.6) - the draw call in the render loop (3.7) and the cleanup (3.8)
createTriangleClassic(): the same objects in the classic style, chosen with--classic(3.9)
3.2 The pipeline, once more
You know the graphics pipeline from the GLSL series.
This time we look at it from the C++ side, because now we have to provide every input that the GLSL tester provided for us:
- Our C++ program copies the vertex positions into a buffer in GPU memory and then asks for a draw with
glDrawArrays. - Vertex fetch (fixed hardware) reads the data for each vertex from the buffer. It needs to know where in which buffer the data for each shader input is, and in what format. That description is the vertex array object.
- The vertex shader runs once per vertex (3 times for us) and writes the position to
gl_Position. - Primitive assembly groups the vertices into triangles (every 3 vertices make one with
GL_TRIANGLES), and the rasterizer finds all the pixels each triangle covers and creates a fragment for each. - The fragment shader runs once per fragment and writes its color to
out_color. - The color goes into the framebuffer, the back buffer from chapter 2, which
glfwSwapBuffersshows.
The two yellow boxes are the programs we write in GLSL.
Everything else is configured from C++.
(There are more optional stages, such as tessellation and geometry shaders; GLSL chapter 2 introduces them.)
3.3 The vertex data
Our triangle has three corners, each with an x, y and z position:
// 三角形の頂点(NDC:x, yは-1〜1) / triangle vertices (NDC: x and y in -1..1)
const float vertices[] = {
-0.5f, -0.5f, 0.0f, // 左下 / bottom left
0.5f, -0.5f, 0.0f, // 右下 / bottom right
0.0f, 0.5f, 0.0f, // 上 / top
};
That's nine floats, 36 bytes, one after another in memory.
OpenGL doesn't know that they're positions or that there are three of them; for now it's just bytes.
The numbers are in normalized device coordinates (NDC): the coordinate system the rasterizer works in.
In OpenGL's NDC, x goes from −1 (left edge of the viewport) to +1 (right edge), y from −1 (bottom) to +1 (top), and z from −1 to +1 for depth.
Everything outside that cube is clipped away.
The Linear Algebra series, chapter 12 explains how 3D positions get into NDC with a projection matrix; for this chapter, we simply write the positions directly in NDC.
The viewport (glViewport, chapter 2) then maps NDC to pixels:
with and y counted from the bottom.
For our corners:
- bottom left : ,
- bottom right : ,
- top : ,
So the triangle is pixels wide and pixels tall.
In NDC its width and height are both 1, but the window is 16:9, so one NDC unit is 640 pixels horizontally and only 360 vertically.
That's why the triangle looks squashed.
NDC doesn't know about the aspect ratio; we'll correct for it with a matrix in chapter 7 and with the projection in chapter 8.
3.4 Buffer objects
Now the data has to get into GPU memory.
Here's the first half of createTriangleDsa():
struct TriangleObjects {
GLuint vao = 0; // 頂点配列オブジェクト / vertex array object
GLuint vbo = 0; // 頂点バッファ / vertex buffer
};
// DSA方式(OpenGL 4.5):オブジェクトの名前を直接渡して編集する
// DSA style (OpenGL 4.5): edit objects by passing their name directly
static TriangleObjects createTriangleDsa(const float *vertices, GLsizeiptr bytes) {
TriangleObjects t;
glCreateBuffers(1, &t.vbo);
glNamedBufferStorage(t.vbo, bytes, vertices, 0); // 0 = 後から書き換えない / 0 = never updated later
TriangleObjects just keeps the two names together.
VBO stands for vertex buffer object, the traditional name for a buffer that holds vertices.
glCreateBuffers
glCreateBuffers(n, buffers) creates n new buffer objects and writes their names into the array buffers.
We create one and get its name in t.vbo.
The name is just a number (often 1 for the first buffer), and 0 is never a valid buffer name, which is why 0 means "no object" everywhere in OpenGL.
A freshly created buffer has no memory yet.
glNamedBufferStorage
glNamedBufferStorage(buffer, size, data, flags) gives the buffer its memory and fills it:
buffer: the buffer's name.size: the size in bytes (GLsizeiptris a signed integer as large as a pointer).data: a pointer to the data to copy in, ornullptrto leave the memory uninitialized.flags: what we're allowed to do with the buffer later.GL_DYNAMIC_STORAGE_BITallows updating it withglNamedBufferSubData,GL_MAP_READ_BITandGL_MAP_WRITE_BITallow mapping it into CPU memory, and there are a few more for persistent mapping. 0 means none of them: after this call, the CPU can never change the contents again.
The storage is immutable: its size and flags are fixed forever, and calling glNamedBufferStorage a second time on the same buffer is a GL_INVALID_OPERATION.
(The contents can still be changed by the GPU itself, for example by copying from another buffer.)
That sounds limiting, but it's exactly what the driver likes: it knows the buffer will never be resized or written from the CPU, so it can put it in the fastest video memory.
Our triangle never changes, so 0 is right.
When we need buffers we update every frame (uniform buffers in chapter 19, the sprite batcher in chapter 25), we'll pass GL_DYNAMIC_STORAGE_BIT or the mapping flags.
The data is copied during the call, so the vertices array doesn't need to stay alive afterwards.
A classic mistake: the function receives vertices as a pointer, and inside the function sizeof vertices would be the size of a pointer (8 bytes), not of the array.
That's why the size is computed in main, where vertices is still an array, and passed in as bytes.
If you pass 8 instead of 36, the buffer only holds the first two floats, and the triangle silently doesn't appear.
3.5 Vertex array objects
The buffer is just 36 bytes.
The vertex shader wants a vec3 aPosition for each vertex.
The vertex array object (VAO) is the description in between: for each shader input, where in which buffer its data is and what format it has.
In the DSA style this description has two parts, and keeping them apart is the key idea of this section:
- a binding (also called a binding point) is a slot that holds a buffer, an offset where the vertices start in it, and a stride, the number of bytes from one vertex to the next.
- an attribute is one input of the vertex shader, identified by its
location. It has a format (how many components of which type, and at which offset inside one vertex) and the number of the binding it reads from.
To read vertex of attribute , vertex fetch reads from this address in the buffer:
For vertex 2 of our triangle: , and the three floats at bytes 24 to 35 are , the top corner.
Here's the second half of createTriangleDsa():
glCreateVertexArrays(1, &t.vao);
// バインディング0にバッファを繋ぐ:オフセット0、一頂点あたり3つのfloat
// attach the buffer to binding 0: offset 0, 3 floats per vertex
glVertexArrayVertexBuffer(t.vao, 0, t.vbo, 0, 3 * sizeof(float));
// 属性0 = vec3のfloat、頂点の先頭から0バイト、バインディング0から読む
// attribute 0 = vec3 of floats, 0 bytes into the vertex, read from binding 0
glEnableVertexArrayAttrib(t.vao, 0);
glVertexArrayAttribFormat(t.vao, 0, 3, GL_FLOAT, GL_FALSE, 0);
glVertexArrayAttribBinding(t.vao, 0, 0);
return t;
}
glCreateVertexArrays
glCreateVertexArrays(n, arrays) works like glCreateBuffers: it creates n vertex array objects and writes their names.
A new VAO has all attributes disabled and no buffers attached.
glVertexArrayVertexBuffer
glVertexArrayVertexBuffer(vaobj, bindingindex, buffer, offset, stride) fills one binding slot:
vaobj: the VAO.bindingindex: which binding slot (0 to at least 15). We use 0.buffer: the buffer to read from.offset: in bytes, where the first vertex starts in the buffer. Ours starts at the beginning.stride: in bytes, the distance from the start of one vertex to the start of the next. Our vertices are 3 floats, 12 bytes.
Unlike the classic glVertexAttribPointer, a stride of 0 here does not mean "tightly packed"; it means every vertex reads the same bytes.
Always give the real stride.
glEnableVertexArrayAttrib
glEnableVertexArrayAttrib(vaobj, attribindex) enables an attribute.
A disabled attribute doesn't read from any buffer; the shader gets a constant value instead, which is by default.
Forgetting this call is one of the most common reasons for "my triangle doesn't appear": all three vertices end up at the origin, the triangle has no area, and nothing is drawn.
No error is reported, because reading a disabled attribute is perfectly legal.
glVertexArrayAttribFormat
glVertexArrayAttribFormat(vaobj, attribindex, size, type, normalized, relativeoffset) describes the format of one attribute:
attribindex: the attribute, which is thelocationin the shader. We use 0, matchinglayout(location = 0).size: the number of components, 1 to 4. Ours is 3 (x, y, z).type: the type of each component in the buffer:GL_FLOAT,GL_UNSIGNED_BYTE,GL_SHORT,GL_HALF_FLOAT, …normalized: only matters for integer types.GL_TRUEturns them into the range 0 to 1 (or −1 to 1), so a byte 255 becomes 1.0, which is useful for colors.GL_FALSEconverts them to float directly (255 becomes 255.0). For floats it's ignored, and we passGL_FALSE.relativeoffset: in bytes, where this attribute is inside one vertex. With only a position, it's 0. In chapter 4 we put a color after the position, at relative offset 12.
If the shader declares a vec3 but the format has fewer components, the missing ones are filled in with 0 for y and z and 1 for w.
That's why a size of 2 with a vec3 in the shader still works (challenge 5), and why gl_Position usually gets its w from vec4(aPosition, 1.0).
glVertexArrayAttribBinding
glVertexArrayAttribBinding(vaobj, attribindex, bindingindex) connects the attribute to a binding slot: attribute 0 reads from binding 0.
Why two parts?
For one attribute, splitting the description into "attribute" and "binding" looks like extra work.
It pays off as soon as there's more than one attribute.
In chapter 4, a vertex gets a position and a color: two attributes with different formats and relative offsets, but both reading from one binding with one buffer and one stride.
Switching that buffer for another one with the same layout is then a single glVertexArrayVertexBuffer call, without touching the formats.
And in chapter 19 a second binding gets a divisor, so that it advances once per instance instead of once per vertex, which is how instancing works.
Vulkan uses exactly the same model (VkVertexInputAttributeDescription and VkVertexInputBindingDescription), so this is knowledge that carries over directly.
One more rule: the core profile has no default VAO.
Every draw call needs a VAO bound, even one with no attributes (we'll use such an empty VAO for a fullscreen triangle in chapter 17).
Drawing with VAO 0 bound is a GL_INVALID_OPERATION, which our debug logger from chapter 2 reports.
3.6 Shaders and programs
The shader source
We keep the two shaders as strings in main.cc for now.
From chapter 5 on, they move into their own files.
// 頂点シェーダー:頂点ごとに一回実行される / vertex shader: runs once per vertex
static const char *kVertexShader = R"(#version 460 core
layout(location = 0) in vec3 aPosition;
void main() {
gl_Position = vec4(aPosition, 1.0); // 座標はそのままNDC / the position is already in NDC
}
)";
// フラグメントシェーダー:ピクセルごとに一回実行される / fragment shader: runs once per pixel
static const char *kFragmentShader = R"(#version 460 core
layout(location = 0) out vec4 out_color;
void main() {
out_color = vec4(1.0, 0.55, 0.15, 1.0); // オレンジ / orange
}
)";
R"( … )" is a C++ raw string literal: everything between R"( and )", including newlines and quotes, is part of the string, so the GLSL can be written as it is.
Note that #version comes directly after R"(: the #version line must be the first line of the shader (only comments and whitespace may come before it, and some drivers are strict even about that), so we don't start the string with a newline.
The GLSL itself is what you know from the GLSL series:
#version 460 coreselects GLSL 4.60 for the core profile, matching our OpenGL 4.6 context.layout(location = 0) in vec3 aPosition;is the vertex shader's input, attribute 0, the one our VAO describes. Thelocationin the shader and theattribindexin C++ must match; that's the whole connection between the two.gl_Positionis the built-in output of the vertex shader, avec4in clip space. After the vertex shader, OpenGL divides x, y and z by w; with w = 1 nothing changes, so our clip-space positions are already NDC. (Chapter 8 uses w for perspective; Linear Algebra chapter 12 explains the division.)layout(location = 0) out vec4 out_color;is the fragment shader's output. Location 0 goes to the first color buffer, which is the window's back buffer. The nameout_coloris our convention from the GLSL series; OpenGL doesn't care about the name.- The color is (255, 140, 38) in 8-bit values, orange.
Compiling a shader
// シェーダーを一つコンパイル。失敗したら0。 / compile one shader stage. Returns 0 on failure.
static GLuint compileShader(GLenum type, const char *source) {
GLuint shader = glCreateShader(type);
glShaderSource(shader, 1, &source, nullptr);
glCompileShader(shader);
GLint ok = 0;
glGetShaderiv(shader, GL_COMPILE_STATUS, &ok);
if (!ok) {
char log[2048];
glGetShaderInfoLog(shader, sizeof log, nullptr, log);
fprintf(stderr, "%sシェーダーのエラー / %s shader error:\n%s\n", type == GL_VERTEX_SHADER ? "頂点" : "フラグメント",
type == GL_VERTEX_SHADER ? "vertex" : "fragment", log);
glDeleteShader(shader);
return 0;
}
return shader;
}
OpenGL compiles GLSL at run time, inside the driver.
That's different from C++, and different from Vulkan, which takes precompiled SPIR-V.
It takes four steps:
glCreateShader(type)creates an empty shader object for one stage:GL_VERTEX_SHADER,GL_FRAGMENT_SHADER, or laterGL_GEOMETRY_SHADER,GL_TESS_CONTROL_SHADER,GL_TESS_EVALUATION_SHADER,GL_COMPUTE_SHADER. It returns the name, or 0 on failure. Unlike buffers, shaders and programs are created one at a time and their names are returned directly.glShaderSource(shader, count, strings, lengths)gives it the source code. The source can be split intocountpieces (useful for putting a common header in front of a shader); we pass one string.lengthscan give the length of each piece, or benullptrwhen the strings are null-terminated. The driver copies the text.glCompileShader(shader)compiles it. It doesn't return anything.glGetShaderiv(shader, GL_COMPILE_STATUS, &ok)asks whether it worked:GL_TRUEorGL_FALSE. If it didn't,glGetShaderInfoLog(shader, bufSize, length, infoLog)copies the compiler's messages into our buffer (at mostbufSizebytes, null-terminated).
The function returns 0 on failure, so the caller can check it like a bool.
Never skip the status check: a shader that failed to compile doesn't produce an OpenGL error, it just makes the link fail later with a much less helpful message.
Let's see what an error looks like.
Change aPosition in gl_Position = vec4(aPosition, 1.0); to aPositon and run the program.
On Mesa you get this (NVIDIA and AMD word it differently):
頂点シェーダーのエラー / vertex shader error:
0:5(21): error: `aPositon' undeclared
0:5(16): error: cannot construct `vec4' from a non-numeric data type
0:5(21) means string 0, line 5, column 21.
Line 5 counts from the #version line, which is line 1.
The second error is a consequence of the first, which is typical: always fix the first error first.
The program then exits with 1, because main checks the result (3.7).
Linking a program
// 二つのシェーダーをプログラムにリンク。失敗したら0。 / link two shaders into a program. Returns 0 on failure.
static GLuint linkProgram(GLuint vertexShader, GLuint fragmentShader) {
GLuint program = glCreateProgram();
glAttachShader(program, vertexShader);
glAttachShader(program, fragmentShader);
glLinkProgram(program);
// リンク後はシェーダーオブジェクトは要らない / the shader objects are not needed after linking
glDetachShader(program, vertexShader);
glDetachShader(program, fragmentShader);
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
GLint ok = 0;
glGetProgramiv(program, GL_LINK_STATUS, &ok);
if (!ok) {
char log[2048];
glGetProgramInfoLog(program, sizeof log, nullptr, log);
fprintf(stderr, "リンクエラー / link error:\n%s\n", log);
glDeleteProgram(program);
return 0;
}
return program;
}
A program object is the combination of all the shader stages that will run together in one draw call.
Linking checks that they fit together and produces the final GPU code.
glCreateProgram()creates an empty program and returns its name.glAttachShader(program, shader)adds a compiled shader to it.glLinkProgram(program)links everything attached. This is where outputs of one stage are matched with inputs of the next, by name or bylocation.glDetachShader(program, shader)andglDeleteShader(shader): once the program is linked, it has its own copy of the compiled code, so we don't need the shader objects any more.glDeleteShaderon a shader that is still attached only marks it for deletion; it's really deleted once it's detached. We detach first, so it's deleted immediately.glGetProgramiv(program, GL_LINK_STATUS, &ok)andglGetProgramInfoLogwork just like their shader counterparts.
A typical link error is a fragment shader input that the vertex shader doesn't write.
If you add in vec3 vColor; to the fragment shader and use it, without the matching out vec3 vColor; in the vertex shader, Mesa says:
リンクエラー / link error:
error: fragment shader input `vColor' has no matching output in the previous stage
Both shaders compile on their own; only linking can see that they don't fit together.
3.7 Drawing
Now main puts everything together:
int main(int argc, char **argv) {
// 「./build/game --classic」で古い「バインドして編集」方式でVAOを作る(結果は同じ)
// "./build/game --classic" builds the VAO with the classic bind-to-edit style (same result)
bool classic = argc > 1 && std::string_view(argv[1]) == "--classic";
Window window;
if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 3")) return 1;
window.onKey = [&](int key, int action, int /*mods*/) {
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) window.close();
};
classic selects which of the two functions builds the VAO; we come back to it in 3.9.
Window is declared first, as always, and Esc quits.
TriangleObjects triangle;
if (classic) {
printf("classic bind-to-edit style\n");
triangle = createTriangleClassic(vertices, sizeof vertices);
} else {
triangle = createTriangleDsa(vertices, sizeof vertices);
}
GLuint vs = compileShader(GL_VERTEX_SHADER, kVertexShader);
GLuint fs = compileShader(GL_FRAGMENT_SHADER, kFragmentShader);
if (!vs || !fs) return 1;
GLuint program = linkProgram(vs, fs);
if (!program) return 1;
sizeof vertices is 36 here, because vertices is the array (shown in 3.3, declared right above this code).
If a shader doesn't compile or the program doesn't link, the error is already printed and we stop.
The window and context are cleaned up by the Window destructor.
while (!window.shouldClose()) {
window.pollEvents();
glClearColor(0.10f, 0.15f, 0.25f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glUseProgram(program); // このシェーダーで描く / draw with this shader
glBindVertexArray(triangle.vao); // この頂点データで描く / draw with this vertex data
glDrawArrays(GL_TRIANGLES, 0, 3); // 頂点0から3つ = 三角形1つ / 3 vertices from vertex 0 = one triangle
window.swapBuffers();
}
Three calls draw the triangle:
glUseProgram(program)makes the program the current one. This is state, like the clear color: every following draw call uses this program until another one is made current.glUseProgram(0)means no program, and drawing without a program in the core profile gives undefined results.glBindVertexArray(vao)makes the VAO current. Even with DSA we still bind objects to draw with them; DSA only removes the need to bind objects to edit them.glDrawArrays(mode, first, count)draws.modeis the primitive type:GL_TRIANGLESmakes one triangle out of every 3 vertices (chapter 4 shows the others).firstis the first vertex to use,countthe number of vertices.
A common mistake is passing the number of floats (9) or bytes (36) as count.
With 9, OpenGL would try to read 9 vertices, 108 bytes, from our 36-byte buffer.
Reading past the end of a buffer is undefined behavior on most drivers (some return zeros, some crash, some draw garbage), and with debug output on, many drivers warn about it.
glDrawArrays doesn't wait for the GPU.
It puts a command into a queue and returns immediately; the GPU draws later, while our program is already busy with the next frame.
glfwSwapBuffers is where the frames come together.
3.8 Cleaning up
// ウィンドウ(コンテキスト)より先に削除する / delete before the window (context) goes away
glDeleteProgram(program);
glDeleteVertexArrays(1, &triangle.vao);
glDeleteBuffers(1, &triangle.vbo);
return 0;
}
glDeleteProgram(program), glDeleteVertexArrays(n, arrays) and glDeleteBuffers(n, buffers) delete the objects and free their memory.
Deleting name 0 is silently ignored, so these calls are safe even for objects that were never created.
They run at the end of main, while window still exists; the Window destructor only runs after the return.
Calling glDelete… by hand is easy to forget, and it's wrong as soon as a function returns early.
In chapter 4 we wrap buffers and VAOs in RAII classes that delete themselves in their destructor, and in chapter 5 shaders and programs.
Since Window is declared first, those objects are always destroyed before the context.
3.9 The classic bind-to-edit style
Most OpenGL tutorials, books and existing code are older than OpenGL 4.5, and they build the same objects in a different way.
You'll meet this style everywhere, so let's write it once:
// 古い方式:バインドしてから「今バインドされているもの」を編集する(多くの古いチュートリアル)
// Classic style: bind, then edit "whatever is bound" (most older tutorials)
static TriangleObjects createTriangleClassic(const float *vertices, GLsizeiptr bytes) {
TriangleObjects t;
glGenVertexArrays(1, &t.vao);
glBindVertexArray(t.vao);
glGenBuffers(1, &t.vbo);
glBindBuffer(GL_ARRAY_BUFFER, t.vbo);
glBufferData(GL_ARRAY_BUFFER, bytes, vertices, GL_STATIC_DRAW);
// 今GL_ARRAY_BUFFERにバインドされているバッファが属性0に記録される
// the buffer currently bound to GL_ARRAY_BUFFER is recorded for attribute 0
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), nullptr);
glEnableVertexAttribArray(0);
glBindVertexArray(0); // 後で誤って変更しないように外す / unbind so it is not changed by accident
return t;
}
The idea of the classic style: functions don't take the object they change.
Instead, you first bind the object to a target (a slot in the context, like GL_ARRAY_BUFFER), and the function changes whatever is bound to that target at that moment.
glGenVertexArrays(n, arrays)andglGenBuffers(n, buffers)only reserve names. The object itself is created the first time the name is bound. (This is also why DSA functions fail withGL_INVALID_OPERATIONon a name fromglGen…that was never bound: there's no object yet.)glBindVertexArray(vao)binds the VAO. From now on, every vertex attribute function changes this VAO.glBindBuffer(target, buffer)binds the buffer to the targetGL_ARRAY_BUFFER, the target for vertex data.glBufferData(target, size, data, usage)allocates and fills the memory of the buffer bound totarget. UnlikeglNamedBufferStorage, this storage is mutable: you can callglBufferDataagain with a different size.usageis a hint about how you'll use it (GL_STATIC_DRAW: written once, drawn many times;GL_DYNAMIC_DRAW: changed often;GL_STREAM_DRAW: changed every frame). It's only a hint, and drivers interpret it very differently.glVertexAttribPointer(index, size, type, normalized, stride, pointer)does the work of three DSA calls at once: the format of attributeindex(size,type,normalized), and a binding with the stride. And it records the buffer that is bound toGL_ARRAY_BUFFERright now as the attribute's source.pointeris, despite its name and type, the byte offset into that buffer (nullptr= 0). A stride of 0 here means "tightly packed".glEnableVertexAttribArray(index)enables attributeindexof the bound VAO.glBindVertexArray(0)unbinds the VAO, so that later attribute calls (for another object) don't change this one by accident.
Note what glVertexAttribPointer does with GL_ARRAY_BUFFER: it reads the binding once and remembers the buffer.
The GL_ARRAY_BUFFER binding itself is not part of the VAO; unbinding it afterwards doesn't change anything.
(The element buffer from chapter 4 is different: that binding is stored in the VAO. This kind of inconsistency is a big part of why the classic style is confusing.)
Comparing the two
| DSA (OpenGL 4.5) | Classic |
|---|---|
glCreateBuffers: the object exists immediately |
glGenBuffers: only a name; the object appears at the first bind |
glNamedBufferStorage(vbo, …): immutable, flags say what's allowed |
glBindBuffer + glBufferData(GL_ARRAY_BUFFER, …): mutable, a usage hint |
glVertexArrayVertexBuffer(vao, binding, vbo, offset, stride) |
the buffer bound to GL_ARRAY_BUFFER when glVertexAttribPointer runs |
glVertexArrayAttribFormat + glVertexArrayAttribBinding |
glVertexAttribPointer (format, stride and buffer in one) |
glEnableVertexArrayAttrib(vao, i) |
glBindVertexArray(vao) + glEnableVertexAttribArray(i) |
| every call names the object it changes | every call changes whatever is bound |
With DSA, every function says which object it changes, so there are no hidden dependencies between calls.
With bind-to-edit, the order of calls matters and the binding state leaks from one part of the program into another.
Challenge 6 shows how easily that goes wrong.
In the rest of the series we use DSA everywhere; you'll still see glBindVertexArray, glUseProgram and later glBindTextureUnit, because binding to draw is still how OpenGL works.
Trying it
The program builds the VAO with the classic function when you start it with --classic:
./build/game --classic
OpenGL 4.6.0 NVIDIA 577.19 / NVIDIA GeForce RTX 2060/PCIe/SSE2
classic bind-to-edit style
The picture is exactly the same; I compared the two outputs pixel by pixel, and they're identical.
On Windows, start build\Debug\game.exe --classic from a terminal in the project root, or in Visual Studio set the argument in the project's Properties → Debugging → Command Arguments (with Open Folder, add "args": ["--classic"] to the configuration in launch.vs.json).
3.10 When the triangle doesn't appear
A black (or here, dark blue) screen with no error is the most common result of a first triangle.
Here's a checklist, in the order I'd check it:
| Symptom or cause | What to check |
|---|---|
[GL ERROR] lines in the terminal |
Read the first one. The debug logger names the function. |
| a shader error or link error | compileShader/linkProgram print it with a line number. |
| attribute not enabled | glEnableVertexArrayAttrib(vao, 0). Without it, all vertices are and nothing is drawn, without any error. |
| location mismatch | layout(location = 0) in the shader and attribute index 0 in C++ must match. |
| wrong buffer size | sizeof of a pointer instead of the array: the buffer is too small. |
| wrong stride or count | stride in bytes (12), count in vertices (3). |
| positions outside NDC | anything outside −1 to 1 is clipped away. |
glUseProgram or glBindVertexArray missing |
both are needed before every draw (or at least once, if nothing else changes them). |
There's one more classic, which our triangle avoids by luck: winding order.
The vertices are counter-clockwise on screen (bottom left → bottom right → top), which OpenGL calls front-facing by default.
That only matters once face culling is turned on (chapter 16), but if a triangle disappears after enabling culling, its vertices are in clockwise order.
3.11 How real engines do it
- Vertex formats as data. Engines don't write
glVertexArrayAttribFormatcalls by hand for every mesh. They describe each vertex type as a small table (attribute, components, type, offset) and have one function that turns it into a VAO. We do exactly that in chapter 4 withVertexAttribandMesh. - Shaders are compiled once and cached. Compiling GLSL takes time (often milliseconds per shader), so engines compile at startup or load time, never in the middle of a frame. Many keep the compiled result with
glGetProgramBinaryor, since 4.6, ship SPIR-V (glShaderBinary+glSpecializeShader), which is also what Vulkan uses. - Few big buffers. Instead of one buffer per mesh, engines often put many meshes into a few large buffers and draw them with offsets. The binding offset in
glVertexArrayVertexBufferand thefirstparameter ofglDrawArraysare what make that possible. - Vulkan has the same pieces. A buffer (
VkBufferplus memory you allocate yourself), the vertex input description (bindings and attributes, as in 3.5), shader modules (SPIR-V) and a pipeline (like a program plus most of the state). What you learn here maps one to one.
3.12 Summary
- Drawing needs three objects: a buffer with the vertex data, a VAO that describes how to read it, and a program of linked shaders. Then
glUseProgram,glBindVertexArray,glDrawArrays. - Positions written directly in NDC go from −1 to 1. The viewport maps them to pixels, so on a 16:9 window one NDC unit is wider than it is tall (fixed in chapters 7 and 8).
glCreateBuffers+glNamedBufferStorage(buffer, size, data, flags)create an immutable buffer; flags 0 means the CPU never changes it again.- A VAO connects attributes (format: components, type, normalized, relative offset; and a binding) with bindings (buffer, offset, stride):
glVertexArrayVertexBuffer,glEnableVertexArrayAttrib,glVertexArrayAttribFormat,glVertexArrayAttribBinding. The attribute index is the shader'slocation. - A disabled attribute reads a constant . The core profile has no default VAO.
- Shaders are compiled at run time:
glCreateShader,glShaderSource,glCompileShader, checkGL_COMPILE_STATUSand printglGetShaderInfoLog. Programs:glCreateProgram,glAttachShader,glLinkProgram, checkGL_LINK_STATUS. Shader objects can be deleted after linking. glDrawArrays(mode, first, count)counts vertices.- The classic style binds objects to targets and edits "whatever is bound" (
glGenBuffers,glBindBuffer,glBufferData,glVertexAttribPointer). It works, but the hidden dependencies make it fragile. We use DSA. - Delete objects before the context goes away (RAII from chapter 4).
3.13 Challenges
- ★ Change the fragment color and turn the triangle upside down by changing the vertex positions. You should see a triangle pointing down in your new color.
- ★ Draw two triangles side by side: put 6 vertices into the array (two triangles, for example one centered at x = −0.5 and one at x = 0.5) and draw them with
glDrawArrays(GL_TRIANGLES, 0, 6). Nothing else has to change, becausesizeof verticesgrows with the array. You should see two triangles. - ★★ Draw the two triangles with two VAOs (each with its own buffer) and two programs whose fragment shaders output different colors. Before each draw, call
glUseProgramandglBindVertexArrayfor that triangle. You should see two triangles in two colors. - ★★ Make a typo in the vertex shader on purpose (for example
aPositon, as in 3.6) and read the error. Then remove the;at the end of thegl_Positionline. Which line does the error point to, and why isn't it always the line with the mistake? The program should print the error and exit with code 1. - ★★ Store the triangle with only 2 floats per vertex (x, y): 6 floats, a stride of 8 bytes, and a
sizeof 2 inglVertexArrayAttribFormat. Leave the shader'svec3 aPositionas it is. You should see exactly the same triangle, because the missing z is filled in with 0. - ★★★ In
createTriangleClassic, move theglBindBufferandglBufferDatalines afterglVertexAttribPointerand run with--classic. The triangle disappears. Explain why, using what 3.9 says about which bufferglVertexAttribPointerrecords, and why the spec doesn't even require an error here (look at the value of thepointerargument). Then explain why the same mistake is impossible withglVertexArrayVertexBuffer.
ファイル: a/src/main.cc | b/src/main.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -1,105 +1,164 @@ | |||
| 1 | // 第2章:ウィンドウ、レンダーループ、入力 | 1 | // 第3章:こんにちは三角形 |
| 2 | // Chapter 2: windows, the render loop and input | 2 | // Chapter 3: Hello Triangle |
| 3 | // | ||
| 4 | // 操作 / Controls: | ||
| 5 | // マウス移動 / move the mouse 色相と明るさ / hue and brightness | ||
| 6 | // ホイール / scroll wheel 彩度 / saturation | ||
| 7 | // ←/→ を押し続ける / hold ←/→ 色相を回す / rotate the hue | ||
| 8 | // スペースを押し続ける / hold Space 色を反転 / invert the colour | ||
| 9 | // V 垂直同期の切り替え / toggle vsync | ||
| 10 | // E わざとGLエラーを起こす / cause a GL error on purpose | ||
| 11 | // Esc 終了 / quit | ||
| 12 | #include "window.hh" | 3 | #include "window.hh" |
| 13 | 4 | ||
| 14 | #include <algorithm> | ||
| 15 | #include <cmath> | ||
| 16 | #include <cstdio> | 5 | #include <cstdio> |
| 6 | #include <string_view> | ||
| 17 | 7 | ||
| 18 | // HSV(各0〜1)からRGBへ / HSV (each 0..1) to RGB | 8 | // 頂点シェーダー:頂点ごとに一回実行される / vertex shader: runs once per vertex |
| 19 | static void hsvToRgb(float h, float s, float v, float &r, float &g, float &b) { | 9 | static const char *kVertexShader = R"(#version 460 core |
| 20 | h = (h - std::floor(h)) * 6.0f; // 0〜6 / 0..6 | 10 | layout(location = 0) in vec3 aPosition; |
| 21 | float c = v * s; | 11 | |
| 22 | float x = c * (1.0f - std::fabs(std::fmod(h, 2.0f) - 1.0f)); | 12 | void main() { |
| 23 | float m = v - c; | 13 | gl_Position = vec4(aPosition, 1.0); // 座標はそのままNDC / the position is already in NDC |
| 24 | int sector = static_cast<int>(h) % 6; | ||
| 25 | float rgb[6][3] = {{c, x, 0}, {x, c, 0}, {0, c, x}, {0, x, c}, {x, 0, c}, {c, 0, x}}; | ||
| 26 | r = rgb[sector][0] + m; | ||
| 27 | g = rgb[sector][1] + m; | ||
| 28 | b = rgb[sector][2] + m; | ||
| 29 | } | 14 | } |
| 15 | )"; | ||
| 30 | 16 | ||
| 31 | int main() { | 17 | // フラグメントシェーダー:ピクセルごとに一回実行される / fragment shader: runs once per pixel |
| 32 | Window window; | 18 | static const char *kFragmentShader = R"(#version 460 core |
| 33 | if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 2")) return 1; | 19 | layout(location = 0) out vec4 out_color; |
| 20 | |||
| 21 | void main() { | ||
| 22 | out_color = vec4(1.0, 0.55, 0.15, 1.0); // オレンジ / orange | ||
| 23 | } | ||
| 24 | )"; | ||
| 25 | |||
| 26 | // シェーダーを一つコンパイル。失敗したら0。 / compile one shader stage. Returns 0 on failure. | ||
| 27 | static GLuint compileShader(GLenum type, const char *source) { | ||
| 28 | GLuint shader = glCreateShader(type); | ||
| 29 | glShaderSource(shader, 1, &source, nullptr); | ||
| 30 | glCompileShader(shader); | ||
| 31 | |||
| 32 | GLint ok = 0; | ||
| 33 | glGetShaderiv(shader, GL_COMPILE_STATUS, &ok); | ||
| 34 | if (!ok) { | ||
| 35 | char log[2048]; | ||
| 36 | glGetShaderInfoLog(shader, sizeof log, nullptr, log); | ||
| 37 | fprintf(stderr, "%sシェーダーのエラー / %s shader error:\n%s\n", type == GL_VERTEX_SHADER ? "頂点" : "フラグメント", | ||
| 38 | type == GL_VERTEX_SHADER ? "vertex" : "fragment", log); | ||
| 39 | glDeleteShader(shader); | ||
| 40 | return 0; | ||
| 41 | } | ||
| 42 | return shader; | ||
| 43 | } | ||
| 34 | 44 | ||
| 35 | float hue = 0.6f, saturation = 0.6f, value = 0.35f; | 45 | // 二つのシェーダーをプログラムにリンク。失敗したら0。 / link two shaders into a program. Returns 0 on failure. |
| 46 | static GLuint linkProgram(GLuint vertexShader, GLuint fragmentShader) { | ||
| 47 | GLuint program = glCreateProgram(); | ||
| 48 | glAttachShader(program, vertexShader); | ||
| 49 | glAttachShader(program, fragmentShader); | ||
| 50 | glLinkProgram(program); | ||
| 51 | |||
| 52 | // リンク後はシェーダーオブジェクトは要らない / the shader objects are not needed after linking | ||
| 53 | glDetachShader(program, vertexShader); | ||
| 54 | glDetachShader(program, fragmentShader); | ||
| 55 | glDeleteShader(vertexShader); | ||
| 56 | glDeleteShader(fragmentShader); | ||
| 57 | |||
| 58 | GLint ok = 0; | ||
| 59 | glGetProgramiv(program, GL_LINK_STATUS, &ok); | ||
| 60 | if (!ok) { | ||
| 61 | char log[2048]; | ||
| 62 | glGetProgramInfoLog(program, sizeof log, nullptr, log); | ||
| 63 | fprintf(stderr, "リンクエラー / link error:\n%s\n", log); | ||
| 64 | glDeleteProgram(program); | ||
| 65 | return 0; | ||
| 66 | } | ||
| 67 | return program; | ||
| 68 | } | ||
| 69 | |||
| 70 | struct TriangleObjects { | ||
| 71 | GLuint vao = 0; // 頂点配列オブジェクト / vertex array object | ||
| 72 | GLuint vbo = 0; // 頂点バッファ / vertex buffer | ||
| 73 | }; | ||
| 74 | |||
| 75 | // DSA方式(OpenGL 4.5):オブジェクトの名前を直接渡して編集する | ||
| 76 | // DSA style (OpenGL 4.5): edit objects by passing their name directly | ||
| 77 | static TriangleObjects createTriangleDsa(const float *vertices, GLsizeiptr bytes) { | ||
| 78 | TriangleObjects t; | ||
| 79 | glCreateBuffers(1, &t.vbo); | ||
| 80 | glNamedBufferStorage(t.vbo, bytes, vertices, 0); // 0 = 後から書き換えない / 0 = never updated later | ||
| 81 | |||
| 82 | glCreateVertexArrays(1, &t.vao); | ||
| 83 | // バインディング0にバッファを繋ぐ:オフセット0、一頂点あたり3つのfloat | ||
| 84 | // attach the buffer to binding 0: offset 0, 3 floats per vertex | ||
| 85 | glVertexArrayVertexBuffer(t.vao, 0, t.vbo, 0, 3 * sizeof(float)); | ||
| 86 | // 属性0 = vec3のfloat、頂点の先頭から0バイト、バインディング0から読む | ||
| 87 | // attribute 0 = vec3 of floats, 0 bytes into the vertex, read from binding 0 | ||
| 88 | glEnableVertexArrayAttrib(t.vao, 0); | ||
| 89 | glVertexArrayAttribFormat(t.vao, 0, 3, GL_FLOAT, GL_FALSE, 0); | ||
| 90 | glVertexArrayAttribBinding(t.vao, 0, 0); | ||
| 91 | return t; | ||
| 92 | } | ||
| 36 | 93 | ||
| 37 | // コールバック:イベントが起きた時に一度だけ呼ばれる / callbacks: called once when an event happens | 94 | // 古い方式:バインドしてから「今バインドされているもの」を編集する(多くの古いチュートリアル) |
| 95 | // Classic style: bind, then edit "whatever is bound" (most older tutorials) | ||
| 96 | static TriangleObjects createTriangleClassic(const float *vertices, GLsizeiptr bytes) { | ||
| 97 | TriangleObjects t; | ||
| 98 | glGenVertexArrays(1, &t.vao); | ||
| 99 | glBindVertexArray(t.vao); | ||
| 100 | |||
| 101 | glGenBuffers(1, &t.vbo); | ||
| 102 | glBindBuffer(GL_ARRAY_BUFFER, t.vbo); | ||
| 103 | glBufferData(GL_ARRAY_BUFFER, bytes, vertices, GL_STATIC_DRAW); | ||
| 104 | |||
| 105 | // 今GL_ARRAY_BUFFERにバインドされているバッファが属性0に記録される | ||
| 106 | // the buffer currently bound to GL_ARRAY_BUFFER is recorded for attribute 0 | ||
| 107 | glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), nullptr); | ||
| 108 | glEnableVertexAttribArray(0); | ||
| 109 | |||
| 110 | glBindVertexArray(0); // 後で誤って変更しないように外す / unbind so it is not changed by accident | ||
| 111 | return t; | ||
| 112 | } | ||
| 113 | |||
| 114 | int main(int argc, char **argv) { | ||
| 115 | // 「./build/game --classic」で古い「バインドして編集」方式でVAOを作る(結果は同じ) | ||
| 116 | // "./build/game --classic" builds the VAO with the classic bind-to-edit style (same result) | ||
| 117 | bool classic = argc > 1 && std::string_view(argv[1]) == "--classic"; | ||
| 118 | |||
| 119 | Window window; | ||
| 120 | if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 3")) return 1; | ||
| 38 | window.onKey = [&](int key, int action, int /*mods*/) { | 121 | window.onKey = [&](int key, int action, int /*mods*/) { |
| 39 | if (action != GLFW_PRESS) return; | 122 | if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) window.close(); |
| 40 | if (key == GLFW_KEY_ESCAPE) window.close(); | ||
| 41 | if (key == GLFW_KEY_V) { | ||
| 42 | window.setVsync(!window.vsync()); | ||
| 43 | printf("vsync %s\n", window.vsync() ? "on" : "off"); | ||
| 44 | } | ||
| 45 | if (key == GLFW_KEY_E) { | ||
| 46 | // コアプロファイルにGL_TEXTURE_2Dの有効化はない → GL_INVALID_ENUM | ||
| 47 | // the core profile has no glEnable(GL_TEXTURE_2D) → GL_INVALID_ENUM | ||
| 48 | glEnable(GL_TEXTURE_2D); | ||
| 49 | } | ||
| 50 | }; | ||
| 51 | window.onCursorPos = [&](double x, double y) { | ||
| 52 | hue = static_cast<float>(x) / static_cast<float>(window.width()); | ||
| 53 | value = 1.0f - static_cast<float>(y) / static_cast<float>(window.height()); | ||
| 54 | }; | 123 | }; |
| 55 | window.onScroll = [&](double /*dx*/, double dy) { | 124 | |
| 56 | saturation = std::clamp(saturation + 0.05f * static_cast<float>(dy), 0.0f, 1.0f); | 125 | // 三角形の頂点(NDC:x, yは-1〜1) / triangle vertices (NDC: x and y in -1..1) |
| 126 | const float vertices[] = { | ||
| 127 | -0.5f, -0.5f, 0.0f, // 左下 / bottom left | ||
| 128 | 0.5f, -0.5f, 0.0f, // 右下 / bottom right | ||
| 129 | 0.0f, 0.5f, 0.0f, // 上 / top | ||
| 57 | }; | 130 | }; |
| 58 | 131 | ||
| 59 | double lastTime = window.time(); | 132 | TriangleObjects triangle; |
| 60 | double fpsTimer = 0.0; | 133 | if (classic) { |
| 61 | int fpsFrames = 0; | 134 | printf("classic bind-to-edit style\n"); |
| 135 | triangle = createTriangleClassic(vertices, sizeof vertices); | ||
| 136 | } else { | ||
| 137 | triangle = createTriangleDsa(vertices, sizeof vertices); | ||
| 138 | } | ||
| 139 | |||
| 140 | GLuint vs = compileShader(GL_VERTEX_SHADER, kVertexShader); | ||
| 141 | GLuint fs = compileShader(GL_FRAGMENT_SHADER, kFragmentShader); | ||
| 142 | if (!vs || !fs) return 1; | ||
| 143 | GLuint program = linkProgram(vs, fs); | ||
| 144 | if (!program) return 1; | ||
| 62 | 145 | ||
| 63 | while (!window.shouldClose()) { | 146 | while (!window.shouldClose()) { |
| 64 | // 1. 時間:前のフレームからの経過秒数 / time: seconds since the previous frame | ||
| 65 | double now = window.time(); | ||
| 66 | float dt = static_cast<float>(now - lastTime); | ||
| 67 | lastTime = now; | ||
| 68 | |||
| 69 | // 2. イベント(ここでコールバックが呼ばれる) / events (the callbacks run in here) | ||
| 70 | window.pollEvents(); | 147 | window.pollEvents(); |
| 71 | 148 | ||
| 72 | // 3. 更新:ポーリングで押しっぱなしのキーを調べる / update: poll keys that are held down | 149 | glClearColor(0.10f, 0.15f, 0.25f, 1.0f); |
| 73 | // dtを掛けると、フレームレートに関係なく毎秒0.25回る / multiplying by dt makes it 0.25 turns per second at any frame rate | ||
| 74 | if (window.keyDown(GLFW_KEY_RIGHT)) hue += 0.25f * dt; | ||
| 75 | if (window.keyDown(GLFW_KEY_LEFT)) hue -= 0.25f * dt; | ||
| 76 | |||
| 77 | float r, g, b; | ||
| 78 | hsvToRgb(hue, saturation, value, r, g, b); | ||
| 79 | if (window.keyDown(GLFW_KEY_SPACE)) { | ||
| 80 | r = 1.0f - r; | ||
| 81 | g = 1.0f - g; | ||
| 82 | b = 1.0f - b; | ||
| 83 | } | ||
| 84 | |||
| 85 | // 4. 描画:クリアカラーは「状態」で、glClearがそれを使う / render: the clear colour is state that glClear uses | ||
| 86 | glClearColor(r, g, b, 1.0f); | ||
| 87 | glClear(GL_COLOR_BUFFER_BIT); | 150 | glClear(GL_COLOR_BUFFER_BIT); |
| 88 | 151 | ||
| 89 | // 5. 表示 / present | 152 | glUseProgram(program); // このシェーダーで描く / draw with this shader |
| 90 | window.swapBuffers(); | 153 | glBindVertexArray(triangle.vao); // この頂点データで描く / draw with this vertex data |
| 154 | glDrawArrays(GL_TRIANGLES, 0, 3); // 頂点0から3つ = 三角形1つ / 3 vertices from vertex 0 = one triangle | ||
| 91 | 155 | ||
| 92 | // 0.5秒ごとにFPSをタイトルに表示 / show the FPS in the title every 0.5 s | 156 | window.swapBuffers(); |
| 93 | fpsTimer += dt; | ||
| 94 | ++fpsFrames; | ||
| 95 | if (fpsTimer >= 0.5) { | ||
| 96 | char title[128]; | ||
| 97 | snprintf(title, sizeof title, "OpenGL Tutorial - Chapter 2 | %.0f FPS (%.2f ms)", fpsFrames / fpsTimer, | ||
| 98 | 1000.0 * fpsTimer / fpsFrames); | ||
| 99 | window.setTitle(title); | ||
| 100 | fpsTimer = 0.0; | ||
| 101 | fpsFrames = 0; | ||
| 102 | } | ||
| 103 | } | 157 | } |
| 158 | |||
| 159 | // ウィンドウ(コンテキスト)より先に削除する / delete before the window (context) goes away | ||
| 160 | glDeleteProgram(program); | ||
| 161 | glDeleteVertexArrays(1, &triangle.vao); | ||
| 162 | glDeleteBuffers(1, &triangle.vbo); | ||
| 104 | return 0; | 163 | return 0; |
| 105 | } | 164 | } |
コメント(0)
まだコメントはありません。
ログインするとコメント出来ます。