7. Transformations
Until now, every position on the screen came straight from the vertex data.
In chapter 6 the crate square was even squeezed by hand (0.8f * 720.0f / 1280.0f) so that it would look square on a 16:9 window.
That works for one picture, but a game has to move, turn and resize hundreds of things every frame, and nobody wants to rewrite vertex buffers for that.
The answer is the one the Linear Algebra series spent several chapters building: matrices.
In this chapter we connect linalg.hh to OpenGL.
We'll upload a matrix to a shader, build a model matrix from scale, rotation and translation, and draw the same square twice in two different places with two different animations.
There is very little new OpenGL here, but the ideas in this chapter carry every chapter after it.
7.1 What we're building
One 1×1 square of vertex data, drawn twice per frame:
- bottom right: a crate that keeps spinning around its own center
- top left: a smaller crate whose size pulses
The controls:
- Space: pause the animation
- R: reload the shaders (from chapter 5)
- Esc: quit
The code starts from the end of chapter 6.
Only two files change: shaders/textured.vert and src/main.cc.
The fragment shader, the Mesh, Shader and Texture2D classes and CMakeLists.txt stay exactly as they were.
7.2 Why matrices instead of moving vertices
There are two ways to move a square to the right.
The first is to change the x coordinate of its four vertices on the CPU and upload the vertex buffer again.
The second is to leave the vertex buffer alone and tell the vertex shader "add 0.6 to every x before you output it".
The first way gets expensive fast.
A character model has tens of thousands of vertices, and rewriting them all every frame just to move it one step is a waste of time and bus bandwidth.
Worse, if ten objects share the same mesh (ten crates, a forest of the same tree), the CPU approach needs ten copies of the vertex data.
The second way sends one matrix per object, 64 bytes, and the GPU applies it to every vertex in parallel.
The mesh stays in GPU memory untouched, in its own coordinate system, which we call model space (also object space or local space).
The matrix that takes a vertex from model space to its place in the scene is the model matrix.
In chapter 9 of the Linear Algebra series we built it as from the scale, rotation and translation matrices of chapter 8 and chapter 9.
This chapter puts that formula on the GPU.
7.3 Getting a Mat4 into a shader
How linalg.hh stores a matrix
Here is the matrix type from linalg.hh, the header you downloaded in chapter 1 into external/linalg/:
// 4×4行列。列優先:c[列]が一つの列ベクトル。
// 4×4 matrix. Column-major: c[column] is one column vector.
struct Mat4 {
Vec4 c[4];
// 行row・列colの要素(0始まり) / element at row, col (0-based)
float &at(int row, int col) {
float *p = &c[col].x;
return p[row];
}
float at(int row, int col) const {
const float *p = &c[col].x;
return p[row];
}
static Mat4 identity() {
Mat4 m;
m.c[0] = {1, 0, 0, 0};
m.c[1] = {0, 1, 0, 0};
m.c[2] = {0, 0, 1, 0};
m.c[3] = {0, 0, 0, 1};
return m;
}
};
A Mat4 is four Vec4 columns, one after another.
Each Vec4 is four floats with no padding, so the whole matrix is 16 floats (64 bytes) in a row in memory, column by column.
That order is called column-major.
For example, translate({0.6f, -0.3f, 0.0f}) puts the translation into the last column, and the memory looks like this:
c[0] = (1, 0, 0, 0) floats 0..3
c[1] = (0, 1, 0, 0) floats 4..7
c[2] = (0, 0, 1, 0) floats 8..11
c[3] = (0.6, -0.3, 0, 1) floats 12..15 <- the translation
In math we write that matrix with the translation in the right-hand column:
So the 16 floats in memory are the columns of the matrix you see on paper, not its rows.
GLSL's mat4 uses exactly the same convention, which is why we chose it for linalg.hh (Linear Algebra series, chapter 7).
That one decision saves us a lot of trouble now.
glProgramUniformMatrix4fv
Back in chapter 5 our Shader class already got a set overload for matrices.
We didn't use it yet; this chapter is where it earns its place:
void Shader::set(const char *name, const Mat4 &m) const {
// linalg.hhは列優先なので転置しない(GL_FALSE) / linalg.hh is column-major, so no transpose (GL_FALSE)
glProgramUniformMatrix4fv(program, location(name), 1, GL_FALSE, &m.c[0].x);
}
glProgramUniformMatrix4fv copies matrices into a uniform of a program.
Its parameters:
program: the program object that owns the uniform. This is the DSA version, so the program does not have to be bound withglUseProgramfirst (chapter 5).location: the uniform's location, fromglGetUniformLocation(ourlocation()helper looks it up and warns once if it is −1).count: how many matrices. 1 for a singlemat4; for an array likeuniform mat4 uBones[64]you can upload many at once.transpose:GL_FALSEmeans "the floats are already column-major".GL_TRUEmeans "these are rows, please transpose them".value: a pointer to the first float.&m.c[0].xis the x of the first column, and the other 15 floats follow it.
There is a whole family of these: glProgramUniformMatrix2fv, 3fv, 4fv, and non-square ones like glProgramUniformMatrix3x4fv.
The f means float and the v means "pointer to values" (vector).
The old non-DSA call is glUniformMatrix4fv(location, count, transpose, value), which writes into whatever program is currently bound by glUseProgram; most tutorials on the web use that one.
Common mistakes
Passing GL_TRUE.
This is the classic one.
Many C++ math libraries (and most of DirectX) store matrices row by row, so you'll see GL_TRUE in a lot of example code.
With our column-major Mat4 it's wrong, and the result is not a crash but a strange picture, which is harder to debug.
OpenGL then uses the transpose : the rotation turns the other way (the transpose of a rotation is its inverse, chapter 10), and the translation ends up in the bottom row, where it changes .
In section 7.5 we'll compute where a corner of our square should land, ; with GL_TRUE the same corner comes out as , so after the divide by it sits near the center and the whole square looks warped, like a bad perspective.
If your objects shrink towards the middle of the screen and distort when they "move", check this flag first.
Uploading to the wrong type.
The uniform in the shader must really be a mat4.
Calling the Matrix4fv function on a mat3 or a vec4 uniform generates GL_INVALID_OPERATION, and our debug logger from chapter 2 prints it.
A uniform that doesn't exist.
If you misspell the name, or declare uModel but never use it (the compiler removes unused uniforms), the location is −1.
OpenGL silently ignores uploads to −1; our Shader::location prints no active uniform "uModl" once, so you'll notice.
Pointing at a temporary.
&m.c[0].x must point at a Mat4 that is still alive during the call.
Writing &translate(t).c[0].x inline is rejected by GCC and Clang ("taking address of rvalue"), and that's a good thing. The const Mat4 & parameter is the safe way: the temporary lives until set returns, and OpenGL copies the 64 bytes immediately.
7.4 The vertex shader
Now the shader side.
Here is the complete shaders/textured.vert for this chapter:
#version 460 core
layout(location = 0) in vec3 aPosition;
layout(location = 2) in vec2 aUv; // 1番は第10章の法線のために空けておく / location 1 is kept free for the normal (chapter 10)
uniform mat4 uModel; // モデル座標 → ワールド座標 / model space → world space
uniform mat4 uProj; // 投影(この章ではアスペクト比の補正だけ) / projection (only the aspect-ratio fix in this chapter)
out vec2 vUv;
void main() {
vUv = aUv;
// 行列は右から順に効く:先にuModel、次にuProj / matrices apply right to left: uModel first, then uProj
gl_Position = uProj * uModel * vec4(aPosition, 1.0);
}
Three things are new.
uniform mat4 uModel; declares a 4×4 float matrix that the C++ side fills.
We use the series' naming from the GLSL series: uModel, uView, uProj (the view matrix arrives in the next chapter).
vec4(aPosition, 1.0) turns the 3D position into a 4D one with .
A 4×4 matrix needs four components, and is what makes translation work: it's the homogeneous coordinate trick from chapter 9 of the Linear Algebra series.
A point gets (it moves when translated); a direction like a normal would get (it doesn't).
Forgetting this and writing vec4(aPosition, 0.0) is a common mistake: rotation and scale still work, but translation silently does nothing.
uProj * uModel * vec4(...) applies the matrices.
In GLSL, * between a mat4 and a vec4 is the real matrix–vector product (unlike Slang's *, which is component-wise; there you'd write mul).
With column vectors, the matrix closest to the vector is applied first.
So we read this right to left: first uModel places the square, then uProj adjusts the result for the screen.
The full formula is:
One more detail: matrix multiplication is associative, so (uProj * uModel) * v and uProj * (uModel * v) give the same result.
As written, the shader multiplies left to right: the matrix–matrix product uProj * uModel (64 multiplications) for every vertex, then one matrix–vector product (16 more), and most drivers don't optimize that away.
For four vertices it doesn't matter.
For a big mesh you'd either write uProj * (uModel * v) or multiply the matrices once on the CPU and upload the product; we'll come back to that in chapter 19.
7.5 The model matrix: T R S
On the C++ side, main.cc gets a small helper:
// TRS:拡大縮小 → 回転 → 平行移動の順に効く(行列は右から掛かる)
// TRS: scale, then rotate, then translate (matrices apply from the right)
static Mat4 trs(Vec3 translation, float angleZ, Vec3 scaling) {
return translate(translation) * rotateZ(angleZ) * scale(scaling);
}
translate, rotateZ and scale are straight from linalg.hh (Linear Algebra chapters 8 and 9), and operator* between two Mat4 is the matrix product from chapter 7.
We only rotate around Z because our square lies flat in the XY plane, facing us along +Z.
A positive angle turns it counter-clockwise on screen, by the right-hand rule.
Angles are in radians, like everywhere in this series.
The order is the important part.
Because the matrices are applied right to left, means:
- scale the square around its own center,
- rotate it around its own center,
- move it to its place.
That is almost always what you want for placing an object, which is why the formula has a name.
Worked example: one corner
Let's follow the top-right corner of the square, , through the bottom-right crate's matrix trs({0.6f, -0.3f, 0.0f}, t, {0.8f, 0.8f, 1.0f}) at the moment (45°, about 0.785 s after the start).
Scale by 0.8: .
Rotate by 45°, with :
Translate by : .
The same thing as one matrix.
Multiplying out gives the rotation scaled by 0.8 in the top-left corner and the translation in the last column:
The corner points straight up from the crate's center, as it should after a 45° turn of a square.
This is what the left half of the picture below shows: the dashed square is the vertex data in model space, the yellow one is the result, and the pink dot is our corner.
The wrong order
Swap the first two matrices and write rotateZ(t) * translate(…) * scale(…) instead.
Now the square is moved first and rotated afterwards, and rotation always turns around the origin, not around the square.
The center swings 45° around to about , as on the right of the picture, and as grows the crate flies in a circle of radius around the middle of the screen.
That's not a bug in OpenGL; it's what the matrices say.
Sometimes it's even what you want (a planet orbiting a sun), and that's challenges 1 and 7.
The Linear Algebra series shows more wrong orders and how to rotate around any pivot in section 9.6 and 9.7.
7.6 A square in model space
Now that matrices decide the size and position, the vertex data can be as simple as possible.
The TexturedVertex struct and its layout stay as in chapter 6, but the square is now a plain 1×1 square around the origin:
// 原点を中心とした1×1の正方形(モデル座標)。大きさと位置は行列で決める。
// A 1×1 square centred on the origin (model space). Size and position now come from matrices.
std::vector<TexturedVertex> vertices = {
{{-0.5f, -0.5f, 0.0f}, {0.0f, 0.0f}},
{{ 0.5f, -0.5f, 0.0f}, {1.0f, 0.0f}},
{{ 0.5f, 0.5f, 0.0f}, {1.0f, 1.0f}},
{{-0.5f, 0.5f, 0.0f}, {0.0f, 1.0f}},
};
Mesh quad(vertices, {0, 1, 2, 2, 3, 0}, kTexturedVertexLayout);
The hx/hy aspect fix from chapter 6 is gone.
Centring the square on the origin is not just tidiness.
Scale and rotation work around the origin of model space, so the origin is the object's pivot.
If the square went from to instead, it would spin around its bottom-left corner.
Artists choose the pivot of a model for the same reason: a door's origin sits on its hinge, a character's between the feet.
7.7 The simplest projection
NDC (normalized device coordinates, chapter 3) go from −1 to 1 in both x and y, whatever the window's shape.
On a 1280×720 window, one unit of x is 640 pixels but one unit of y only 360, so a square in NDC is drawn 1.78 times wider than it is tall.
In chapter 6 we fixed that in the vertex data.
Now it becomes a matrix, uProj, that divides x by the aspect ratio:
// 一番簡単な「投影」:xをアスペクト比で割って、正方形を正方形に見せる(第8章で本物の投影行列)
// The simplest "projection": divide x by the aspect ratio so squares look square (real projection in chapter 8)
shader->set("uProj", scale({1.0f / window.aspect(), 1.0f, 1.0f}));
window.aspect() (chapter 2) is width ÷ height of the framebuffer, , so x is multiplied by .
Finishing the worked example: our corner becomes
and the viewport (chapter 3, and section 12.8 of the Linear Algebra series) turns that into pixels:
counted from the bottom of the window, as OpenGL does (264 pixels from the top).
Because the aspect ratio is read every frame, resizing the window keeps squares square: the framebuffer-size callback from chapter 2 updates the viewport and aspect(), and the next frame uses the new value.
Try it: drag the window very wide or very tall.
What this matrix does not do is perspective; everything is flat and the same size at any depth.
Chapter 8 replaces this line with a real projection matrix from perspectiveGl.
7.8 Drawing the same mesh twice
Here is the drawing part of the render loop:
glClearColor(0.10f, 0.15f, 0.25f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
crate->bind(0);
emblem->bind(1);
shader->use();
shader->set("uMix", 0.8f);
shader->set("uEmblemScale", 1.0f);
// 一番簡単な「投影」:xをアスペクト比で割って、正方形を正方形に見せる(第8章で本物の投影行列)
// The simplest "projection": divide x by the aspect ratio so squares look square (real projection in chapter 8)
shader->set("uProj", scale({1.0f / window.aspect(), 1.0f, 1.0f}));
// 同じ四角形を違う行列で二回描く / draw the same quad twice with different matrices
// 1. 右下:回り続ける / bottom right: keeps rotating
shader->set("uModel", trs({0.6f, -0.3f, 0.0f}, t, {0.8f, 0.8f, 1.0f}));
quad.draw();
// 2. 左上:大きさが脈打つ / top left: its size pulses
float s = 0.5f + 0.15f * std::sin(t * 3.0f);
shader->set("uModel", trs({-0.6f, 0.35f, 0.0f}, 0.0f, {s, s, 1.0f}));
quad.draw();
The pattern is: set the uniforms that are the same for everything once (uProj, the textures, uMix), then for each object set its own uModel and draw.
It works because a uniform's value is state stored in the program object, and every draw call uses the values that are set at the moment it's issued.
OpenGL executes commands in order, so the first quad.draw() sees the first matrix and the second sees the second, even though the GPU may actually run both draws later.
uEmblemScale is 1 now, so each crate shows one sakura emblem instead of the 2×2 grid from chapter 6.
The two crates:
- The bottom-right one is at , scaled to 0.8 and rotated by radians: one radian per second, a full turn every seconds, counter-clockwise.
- The top-left one is at , not rotated, with a size that swings between 0.35 and 0.65 every seconds.
This "one mesh, many matrices" pattern is how every engine draws: chapter 8 draws ten cubes from one cube mesh, the games draw hundreds of sprites from one quad, and chapter 19 does it for thousands of objects in a single draw call with instancing.
7.9 Time and pausing
The rest of main.cc changes only a little.
The keys from chapter 6 are gone; Space now pauses:
bool paused = false;
window.onKey = [&](int key, int action, int /*mods*/) {
if (action != GLFW_PRESS) return;
if (key == GLFW_KEY_ESCAPE) window.close();
if (key == GLFW_KEY_SPACE) paused = !paused;
if (key == GLFW_KEY_R && shader->reload()) printf("シェーダーを読み直した / shaders reloaded\n");
};
And the animation uses its own clock, t, instead of window.time():
float t = 0.0f; // アニメーションの時間 / animation time
double lastTime = window.time();
while (!window.shouldClose()) {
double now = window.time();
float dt = static_cast<float>(now - lastTime);
lastTime = now;
window.pollEvents();
if (!paused) t += dt;
If we used window.time() directly, pausing would be impossible: the clock keeps running, and when you unpause, the crate would jump to where it would have been.
Adding up dt only while not paused gives an animation time that simply stops.
This is the same delta-time idea as in chapter 2, and the same thing games do for a pause menu or slow motion (multiply dt by 0.25 before adding it).
std::sin needs <cmath>, which replaces <algorithm> in the include list (we no longer need std::clamp).
The WrapMode table and the border color from chapter 6 are deleted.
The complete file is in the ZIP, and the diff below the chapter shows every changed line.
Platform notes
Nothing in this chapter is platform-specific, but two small things trip people up on Windows:
- MSVC's
<cmath>doesn't defineM_PIunless you define_USE_MATH_DEFINESbefore including it. We don't need it:linalg.hhhas its ownPIandradians(). - With
/W4, MSVC warns (C4244) when adoubleresult is stored in afloat, for examplefloat s = 0.5f + 0.15f * std::sin(t * 3.0);. Keep the literals as3.0fandstd::sinpicks itsfloatoverload. GCC and Clang only warn about this with-Wconversion.
On Linux and FreeBSD everything works as in chapter 6.
7.10 How real engines do it
- Position, rotation, scale, not matrices. Engines store each object's transform as three parts: a position vector, a rotation (usually a quaternion, Linear Algebra chapter 13) and a scale. The editor shows those numbers, gameplay code changes them, and the TRS matrix is rebuilt only when something moved. Our
trs()is a tiny version of that. - Hierarchies. A wheel is placed relative to its car, a sword relative to a hand. The wheel's world matrix is
carMatrix * wheelMatrix, the parent's matrix times the child's. We'll build this in chapter 14 when we load glTF scenes, and challenge 7 is a small preview. - Combine on the CPU. Instead of uploading
uProjanduModelseparately and multiplying per vertex, many engines upload oneuModelViewProjper object, plus the model matrix alone for lighting. Chapter 19 moves the shared matrices into a uniform buffer. - 2D engines use the same idea. A sprite engine's "transform" is still a TRS matrix, often a 3×3 one in 2D. Our games in part 6 use exactly this chapter's code path.
7.11 Summary
- A mesh lives in model space; the model matrix moves it into the scene. Uploading 64 bytes per object is much cheaper than rewriting vertices.
linalg.hh'sMat4is column-major like GLSL'smat4: upload it withglProgramUniformMatrix4fv(program, loc, 1, GL_FALSE, &m.c[0].x).GL_TRUEwould transpose it and give a warped picture.- In the shader,
gl_Position = uProj * uModel * vec4(aPosition, 1.0); matrices apply right to left, and makes translation work. - scales and rotates around the object's own origin (its pivot), then moves it. Swapping the order makes it orbit the origin instead.
uProj = scale({1 / aspect, 1, 1})keeps squares square at any window size; chapter 8 replaces it with a perspective projection.- One mesh can be drawn many times with different uniforms, because each draw uses the uniform values set at the moment it's issued.
- An animation clock built from
dtcan be paused or slowed down; the wall clock can't.
7.12 Challenges
- ★ Change the bottom-right crate's matrix to
rotateZ(t) * translate({0.6f, -0.3f, 0.0f}) * scale({0.8f, 0.8f, 1.0f}). The crate should now circle around the center of the window while it turns, as in the right half of the diagram in 7.5. - ★ Draw a third quad with a negative scale,
scale({-0.5f, 0.5f, 1.0f}), at . You should see a mirrored crate: the diagonal brace and the emblem's petals point the other way. - ★ By hand, compute where the corner of the top-left crate lands in NDC when (at ). You should get and .
- ★★ Make the top-left quad follow the mouse. Convert
window.mouseX()/mouseY()to NDC (, , with , the window size), multiply x bywindow.aspect()to undouProj, and use the result as the translation. The crate's center should sit exactly under the cursor at any window size. (On a high-DPI screen, useglfwGetWindowSizefor and : cursor positions are in window units, not framebuffer pixels.) - ★★ Rotate the bottom-right crate around a corner instead of its center, with
translate({0.6f, -0.3f, 0.0f}) * rotateZ(t) * translate({0.5f, 0.5f, 0.0f}). Before running it, work out which corner becomes the pivot. The bottom-left corner should stay fixed at while the rest of the crate swings around it. - ★★ Upload the matrix with
GL_TRUEby editingShader::settemporarily. Check that the result matches section 7.3: the crate rotates the wrong way, stays near the center and looks distorted. Then change it back. - ★★★ Build a tiny solar system from one quad: a sun at the origin spinning slowly, a planet with
sun * rotateZ(t) * translate({0.6f, 0, 0}) * scale(…), and a moon whose matrix starts from the planet's matrix (before the planet's scale) times its own rotation and translation. The moon should circle the planet while the planet circles the sun. Think about why the planet's scale must not be part of the moon's parent matrix.
ファイル: a/shaders/textured.vert | b/shaders/textured.vert
| 前 | 新 | ||
|---|---|---|---|
| @@ -2,9 +2,13 @@ | |||
| 2 | layout(location = 0) in vec3 aPosition; | 2 | layout(location = 0) in vec3 aPosition; |
| 3 | layout(location = 2) in vec2 aUv; // 1番は第10章の法線のために空けておく / location 1 is kept free for the normal (chapter 10) | 3 | layout(location = 2) in vec2 aUv; // 1番は第10章の法線のために空けておく / location 1 is kept free for the normal (chapter 10) |
| 4 | 4 | ||
| 5 | uniform mat4 uModel; // モデル座標 → ワールド座標 / model space → world space | ||
| 6 | uniform mat4 uProj; // 投影(この章ではアスペクト比の補正だけ) / projection (only the aspect-ratio fix in this chapter) | ||
| 7 | |||
| 5 | out vec2 vUv; | 8 | out vec2 vUv; |
| 6 | 9 | ||
| 7 | void main() { | 10 | void main() { |
| 8 | vUv = aUv; | 11 | vUv = aUv; |
| 9 | gl_Position = vec4(aPosition, 1.0); | 12 | // 行列は右から順に効く:先にuModel、次にuProj / matrices apply right to left: uModel first, then uProj |
| 13 | gl_Position = uProj * uModel * vec4(aPosition, 1.0); | ||
| 10 | } | 14 | } |
ファイル: a/src/main.cc | b/src/main.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -1,12 +1,10 @@ | |||
| 1 | // 第6章:テクスチャ | 1 | // 第7章:変換 |
| 2 | // Chapter 6: textures | 2 | // Chapter 7: transformations |
| 3 | // | 3 | // |
| 4 | // 操作 / Controls: | 4 | // 操作 / Controls: |
| 5 | // ↑/↓ 二枚目のテクスチャを混ぜる量 / how much of the second texture to mix in | 5 | // スペース 一時停止 / pause |
| 6 | // F フィルタ:線型⇔最近傍 / filtering: linear ⇔ nearest | 6 | // R シェーダーを読み直す / reload the shaders |
| 7 | // W 二枚目のラップモードを切り替え / cycle the second texture's wrap mode | 7 | // Esc 終了 / quit |
| 8 | // R シェーダーを読み直す / reload the shaders | ||
| 9 | // Esc 終了 / quit | ||
| 10 | #include "mesh.hh" | 8 | #include "mesh.hh" |
| 11 | #include "shader.hh" | 9 | #include "shader.hh" |
| 12 | #include "texture.hh" | 10 | #include "texture.hh" |
| @@ -14,100 +12,85 @@ | |||
| 14 | 12 | ||
| 15 | #include <linalg.hh> | 13 | #include <linalg.hh> |
| 16 | 14 | ||
| 17 | #include <algorithm> | 15 | #include <cmath> |
| 18 | #include <cstddef> | 16 | #include <cstddef> |
| 19 | #include <cstdio> | 17 | #include <cstdio> |
| 20 | #include <optional> | 18 | #include <optional> |
| 21 | #include <vector> | 19 | #include <vector> |
| 22 | 20 | ||
| 23 | // 位置とテクスチャ座標(UV) / position and texture coordinates (UV) | ||
| 24 | struct TexturedVertex { | 21 | struct TexturedVertex { |
| 25 | Vec3 position; | 22 | Vec3 position; |
| 26 | Vec2 uv; | 23 | Vec2 uv; |
| 27 | }; | 24 | }; |
| 28 | 25 | ||
| 29 | constexpr VertexAttrib kTexturedVertexLayout[] = { | 26 | constexpr VertexAttrib kTexturedVertexLayout[] = { |
| 30 | {0, 3, offsetof(TexturedVertex, position)}, // layout(location = 0) in vec3 aPosition | 27 | {0, 3, offsetof(TexturedVertex, position)}, |
| 31 | {2, 2, offsetof(TexturedVertex, uv)}, // layout(location = 2) in vec2 aUv | 28 | {2, 2, offsetof(TexturedVertex, uv)}, |
| 32 | }; | 29 | }; |
| 33 | 30 | ||
| 34 | struct WrapMode { | 31 | // TRS:拡大縮小 → 回転 → 平行移動の順に効く(行列は右から掛かる) |
| 35 | GLenum mode; | 32 | // TRS: scale, then rotate, then translate (matrices apply from the right) |
| 36 | const char *name; | 33 | static Mat4 trs(Vec3 translation, float angleZ, Vec3 scaling) { |
| 37 | }; | 34 | return translate(translation) * rotateZ(angleZ) * scale(scaling); |
| 38 | static const WrapMode kWrapModes[] = { | 35 | } |
| 39 | {GL_REPEAT, "GL_REPEAT"}, | ||
| 40 | {GL_MIRRORED_REPEAT, "GL_MIRRORED_REPEAT"}, | ||
| 41 | {GL_CLAMP_TO_EDGE, "GL_CLAMP_TO_EDGE"}, | ||
| 42 | {GL_CLAMP_TO_BORDER, "GL_CLAMP_TO_BORDER"}, | ||
| 43 | }; | ||
| 44 | 36 | ||
| 45 | int main() { | 37 | int main() { |
| 46 | Window window; | 38 | Window window; |
| 47 | if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 6")) return 1; | 39 | if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 7")) return 1; |
| 48 | 40 | ||
| 49 | std::optional<Shader> shader = Shader::load("shaders/textured.vert", "shaders/textured.frag"); | 41 | std::optional<Shader> shader = Shader::load("shaders/textured.vert", "shaders/textured.frag"); |
| 50 | std::optional<Texture2D> crate = Texture2D::load("assets/textures/crate.png"); | 42 | std::optional<Texture2D> crate = Texture2D::load("assets/textures/crate.png"); |
| 51 | std::optional<Texture2D> emblem = Texture2D::load("assets/textures/emblem.png"); | 43 | std::optional<Texture2D> emblem = Texture2D::load("assets/textures/emblem.png"); |
| 52 | if (!shader || !crate || !emblem) return 1; | 44 | if (!shader || !crate || !emblem) return 1; |
| 53 | 45 | ||
| 54 | // GL_CLAMP_TO_BORDERの時、UVが0〜1の外ならこの色 / with GL_CLAMP_TO_BORDER, UVs outside 0..1 get this colour | 46 | bool paused = false; |
| 55 | const float borderColor[4] = {0.95f, 0.75f, 0.85f, 1.0f}; | ||
| 56 | glTextureParameterfv(emblem->id(), GL_TEXTURE_BORDER_COLOR, borderColor); | ||
| 57 | |||
| 58 | float mixAmount = 0.8f; | ||
| 59 | bool nearest = false; | ||
| 60 | int wrapIndex = 0; | ||
| 61 | |||
| 62 | window.onKey = [&](int key, int action, int /*mods*/) { | 47 | window.onKey = [&](int key, int action, int /*mods*/) { |
| 63 | if (action != GLFW_PRESS) return; | 48 | if (action != GLFW_PRESS) return; |
| 64 | if (key == GLFW_KEY_ESCAPE) window.close(); | 49 | if (key == GLFW_KEY_ESCAPE) window.close(); |
| 50 | if (key == GLFW_KEY_SPACE) paused = !paused; | ||
| 65 | if (key == GLFW_KEY_R && shader->reload()) printf("シェーダーを読み直した / shaders reloaded\n"); | 51 | if (key == GLFW_KEY_R && shader->reload()) printf("シェーダーを読み直した / shaders reloaded\n"); |
| 66 | if (key == GLFW_KEY_F) { | ||
| 67 | nearest = !nearest; | ||
| 68 | for (Texture2D *t : {&*crate, &*emblem}) { | ||
| 69 | if (nearest) | ||
| 70 | t->setFilter(GL_NEAREST_MIPMAP_NEAREST, GL_NEAREST); // 一番近いテクセル / the nearest texel | ||
| 71 | else | ||
| 72 | t->setFilter(GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR); // 周りの4テクセルを補間 / blend the 4 around | ||
| 73 | } | ||
| 74 | printf("filter: %s\n", nearest ? "nearest" : "linear"); | ||
| 75 | } | ||
| 76 | if (key == GLFW_KEY_W) { | ||
| 77 | wrapIndex = (wrapIndex + 1) % 4; | ||
| 78 | emblem->setWrap(kWrapModes[wrapIndex].mode, kWrapModes[wrapIndex].mode); | ||
| 79 | printf("wrap: %s\n", kWrapModes[wrapIndex].name); | ||
| 80 | } | ||
| 81 | }; | 52 | }; |
| 82 | 53 | ||
| 83 | // 画面の中央の正方形(xは16:9のために縮める) / a square in the middle of the screen (x shrunk for 16:9) | 54 | // 原点を中心とした1×1の正方形(モデル座標)。大きさと位置は行列で決める。 |
| 84 | const float hx = 0.8f * 720.0f / 1280.0f, hy = 0.8f; | 55 | // A 1×1 square centred on the origin (model space). Size and position now come from matrices. |
| 85 | std::vector<TexturedVertex> vertices = { | 56 | std::vector<TexturedVertex> vertices = { |
| 86 | {{-hx, -hy, 0.0f}, {0.0f, 0.0f}}, // 左下 = UV (0, 0) / bottom left = UV (0, 0) | 57 | {{-0.5f, -0.5f, 0.0f}, {0.0f, 0.0f}}, |
| 87 | {{ hx, -hy, 0.0f}, {1.0f, 0.0f}}, // 右下 / bottom right | 58 | {{ 0.5f, -0.5f, 0.0f}, {1.0f, 0.0f}}, |
| 88 | {{ hx, hy, 0.0f}, {1.0f, 1.0f}}, // 右上 / top right | 59 | {{ 0.5f, 0.5f, 0.0f}, {1.0f, 1.0f}}, |
| 89 | {{-hx, hy, 0.0f}, {0.0f, 1.0f}}, // 左上 / top left | 60 | {{-0.5f, 0.5f, 0.0f}, {0.0f, 1.0f}}, |
| 90 | }; | 61 | }; |
| 91 | Mesh quad(vertices, {0, 1, 2, 2, 3, 0}, kTexturedVertexLayout); | 62 | Mesh quad(vertices, {0, 1, 2, 2, 3, 0}, kTexturedVertexLayout); |
| 92 | 63 | ||
| 64 | float t = 0.0f; // アニメーションの時間 / animation time | ||
| 93 | double lastTime = window.time(); | 65 | double lastTime = window.time(); |
| 94 | while (!window.shouldClose()) { | 66 | while (!window.shouldClose()) { |
| 95 | double now = window.time(); | 67 | double now = window.time(); |
| 96 | float dt = static_cast<float>(now - lastTime); | 68 | float dt = static_cast<float>(now - lastTime); |
| 97 | lastTime = now; | 69 | lastTime = now; |
| 98 | window.pollEvents(); | 70 | window.pollEvents(); |
| 99 | 71 | if (!paused) t += dt; | |
| 100 | if (window.keyDown(GLFW_KEY_UP)) mixAmount = std::clamp(mixAmount + dt, 0.0f, 1.0f); | ||
| 101 | if (window.keyDown(GLFW_KEY_DOWN)) mixAmount = std::clamp(mixAmount - dt, 0.0f, 1.0f); | ||
| 102 | 72 | ||
| 103 | glClearColor(0.10f, 0.15f, 0.25f, 1.0f); | 73 | glClearColor(0.10f, 0.15f, 0.25f, 1.0f); |
| 104 | glClear(GL_COLOR_BUFFER_BIT); | 74 | glClear(GL_COLOR_BUFFER_BIT); |
| 105 | 75 | ||
| 106 | crate->bind(0); // ユニット0 → uTexture0 / unit 0 → uTexture0 | 76 | crate->bind(0); |
| 107 | emblem->bind(1); // ユニット1 → uTexture1 / unit 1 → uTexture1 | 77 | emblem->bind(1); |
| 108 | shader->use(); | 78 | shader->use(); |
| 109 | shader->set("uMix", mixAmount); | 79 | shader->set("uMix", 0.8f); |
| 110 | shader->set("uEmblemScale", 2.0f); | 80 | shader->set("uEmblemScale", 1.0f); |
| 81 | |||
| 82 | // 一番簡単な「投影」:xをアスペクト比で割って、正方形を正方形に見せる(第8章で本物の投影行列) | ||
| 83 | // The simplest "projection": divide x by the aspect ratio so squares look square (real projection in chapter 8) | ||
| 84 | shader->set("uProj", scale({1.0f / window.aspect(), 1.0f, 1.0f})); | ||
| 85 | |||
| 86 | // 同じ四角形を違う行列で二回描く / draw the same quad twice with different matrices | ||
| 87 | // 1. 右下:回り続ける / bottom right: keeps rotating | ||
| 88 | shader->set("uModel", trs({0.6f, -0.3f, 0.0f}, t, {0.8f, 0.8f, 1.0f})); | ||
| 89 | quad.draw(); | ||
| 90 | |||
| 91 | // 2. 左上:大きさが脈打つ / top left: its size pulses | ||
| 92 | float s = 0.5f + 0.15f * std::sin(t * 3.0f); | ||
| 93 | shader->set("uModel", trs({-0.6f, 0.35f, 0.0f}, 0.0f, {s, s, 1.0f})); | ||
| 111 | quad.draw(); | 94 | quad.draw(); |
| 112 | 95 | ||
| 113 | window.swapBuffers(); | 96 | window.swapBuffers(); |
コメント(0)
まだコメントはありません。
ログインするとコメント出来ます。