19. Uniform Buffers and Instancing

This chapter is about two things that make a renderer scale: sharing data between shaders, and drawing many copies of one object.
Since chapter 5 every uniform has belonged to one shader program, so the camera matrices were set again for every program, and since chapter 12 the lights cost dozens of set calls per program and frame.
And every object has cost at least one draw call: chapter 8 drew ten cubes with ten calls, and chapter 14 promised that we'd do better.

We fix the first problem with uniform buffer objects (UBOs): the camera and all the lights move into two blocks of memory that are written once per frame and read by every shader.
That means learning the std140 layout rules, because the bytes in our C++ structs now have to line up with what the GPU reads.
Then we fix the second problem with instancing: a ring of thousands of rocks drawn with one draw call, each with its own position, size, rotation and color, orbiting the scene with the speed of a little solar system.
At the end we measure the difference, and I'll be honest about what our measurements can and can't tell us.

19.1 What we're building

The diorama from chapter 14 now floats in the sky on a huge flattened rock, and a ring of rocks circles around it, the inner ones faster than the outer ones.
By default there are 4000 rocks, and with = and − you can go from 250 up to 64 000.

The floating diorama: the windmill island sits on a big flat rock in the sky, surrounded by a wide ring of gray-brown rocks of different sizes

The controls:

  • W, A, S, D, Space, Left Ctrl, Shift, mouse, wheel: move and look around as before
  • I: instancing (one draw call) ⇔ one draw call per rock (new)
  • = and −: double or halve the number of rocks, 250 to 64 000 (new)
  • P: pause the windmill and the ring (now also the ring)
  • 1–6: post-processing effects from chapter 17
  • C: FPS ⇔ orbit camera, V: view modes, N: day ⇔ night, F: flashlight
  • Tab: release the cursor, R: reload the shaders, Esc: quit

Every 60 frames the program writes the number of rocks, the number of draw calls and two timings into the window title and to the terminal.

Starting from chapter 18, the changes are:

  • src/uniforms.hh (new): binding point numbers, CameraBlock and the UniformBuffer class
  • src/lights.hh and src/lights.cc: std140 mirror structs, LightsBlock, and LightSet::toBlock() instead of apply(shader)
  • src/buffer.hh and src/buffer.cc: update() and bindBase()
  • src/shader.hh and src/shader.cc: uniformBlockSize() and checkUniformBlock()
  • src/mesh.hh and src/mesh.cc: InstanceData, kInstanceLayout, setInstanceBuffer() and drawInstanced()
  • src/model.hh and src/model.cc: the same two functions for whole models
  • src/gpu_timer.hh and src/gpu_timer.cc (new): timer queries
  • shaders/phong_instanced.vert (new), and every shader that needs the camera now declares the Camera block
  • src/main.cc: the new scene, and the camera and lights written once per frame
  • assets/models/rock.glb (new, 6.8 KB): a lumpy rock, 162 vertices and 320 triangles (the finished files are in the chapter's ZIP and in ch19/ of the assets ZIP)

The scene is new, so the floor, the crates and chapter 18's glass, gold and chrome objects are gone, and with them the keys M, K and X.
The sky box, the metal reflections from texture unit 3 and the post-processing pass stay.
envmap.frag, depth.frag and unlit.vert are still in shaders/, so later chapters can pick them up again; envmap.frag and unlit.vert were converted to the camera block too (depth.frag reads no camera uniforms).

19.2 Uniforms belong to programs

Here is how chapter 18 drew one frame, reduced to the camera:

    phong->use();
    phong->set("uView", v.view);
    phong->set("uProj", v.proj);
    phong->set("uViewPos", v.position);

The same lines were repeated for envmap (and the first two for skybox), and lights.apply(*phong) added 5 to 14 more set calls (53 with all twelve lights), each with a string lookup.
That's because a plain uniform is state of one program object.
Its value is stored with the program; another program that declares a uniform with the same name has its own, completely separate copy.
Two programs that both need the camera need it uploaded twice, and if you add a third shader and forget to set its matrices, it renders with whatever was there before (usually zeros, so nothing appears).

A uniform buffer object turns this around.
The data lives in an ordinary buffer object, the same kind of object as our vertex buffers since chapter 3.
A shader declares a uniform block, a named group of uniforms whose values are read from a buffer instead of being stored in the program.
Between the two sits a small table in the OpenGL context: the binding points of the GL_UNIFORM_BUFFER target, numbered from 0.
We attach a buffer to binding point 0, the shader says "my Camera block reads from binding point 0", and that's the whole connection.

Two buffers on the left, cameraUbo with 144 bytes and lightsUbo with 704 bytes, are attached with glBindBufferBase to the uniform-buffer binding points 0 and 1 in the middle. On the right, the Camera blocks of the programs phong, rocksShader and skybox all read binding point 0, and the Lights blocks of phong and rocksShader read binding point 1. Binding points 2 and 3 are reserved for later chapters

Now the camera is uploaded once per frame, and every program that declares the block sees the new values, including programs we haven't written yet.
The arrows on the right never change: a block's binding point is fixed in the shader source.
What changes per frame is the content of the buffers on the left.

A few limits are worth knowing.
OpenGL 4.6 guarantees at least 84 uniform buffer binding points (GL_MAX_UNIFORM_BUFFER_BINDINGS), at least 14 blocks per shader stage (GL_MAX_VERTEX_UNIFORM_BLOCKS and friends) and at least 16 KB per block (GL_MAX_UNIFORM_BLOCK_SIZE); desktop GPUs usually allow 64 KB.
Our two blocks are 144 and 704 bytes, far below any limit.

19.3 Declaring a block in GLSL

Every shader that needs the camera now contains exactly this text:

// カメラ(ユニフォームバッファ、結合点0、std140)。使う全部のシェーダーで同じ宣言(C++ではCameraBlock)
// The camera (uniform buffer, binding 0, std140). The same declaration in every shader that uses it (CameraBlock in C++)
layout(std140, binding = 0) uniform Camera {
  mat4 uView;
  mat4 uProj;
  vec3 uViewPos; // カメラの位置(ワールド座標) / camera position (world space)
  float uTime;   // アニメーションの時間(秒) / animation time (seconds)
};

Piece by piece:

  • uniform Camera { … }; declares a uniform block named Camera. The block name is what the C++ side uses to find it (glGetUniformBlockIndex, section 19.7). It isn't a type you can use elsewhere in GLSL.
  • There is no instance name after the closing brace, so the members are global names: the shader keeps writing uView, uProj and uViewPos as before, and no line of the lighting code had to change. With an instance name, } camera;, you'd write camera.uView instead. Both are fine; I chose the version that leaves the old code alone.
  • std140 picks a fixed memory layout, defined byte for byte by the specification. That's what lets us write a matching C++ struct. The default layout, shared, is chosen by the driver, so you'd have to ask for every member's offset at run time. packed may even remove members the shader doesn't use. For uniform blocks, std140 is the one to use.
  • binding = 0 is the binding point. This syntax exists since GLSL 4.20. Older code calls glUniformBlockBinding(program, blockIndex, 0) after linking instead, which does the same thing from C++; you'll see that in many tutorials.
  • uTime is new: the animation time in seconds (it stops while P is paused). The instanced rocks compute their orbit from it in section 19.11.

phong.vert shows the conversion in its simplest form:

#version 460 core
layout(location = 0) in vec3 aPosition;
layout(location = 1) in vec3 aNormal; // 面の向き(モデル座標) / which way the surface faces (model space)
layout(location = 2) in vec2 aUv;

// カメラ(ユニフォームバッファ、結合点0、std140)。使う全部のシェーダーで同じ宣言(C++ではCameraBlock)
// The camera (uniform buffer, binding 0, std140). The same declaration in every shader that uses it (CameraBlock in C++)
layout(std140, binding = 0) uniform Camera {
  mat4 uView;
  mat4 uProj;
  vec3 uViewPos; // カメラの位置(ワールド座標) / camera position (world space)
  float uTime;   // アニメーションの時間(秒) / animation time (seconds)
};

uniform mat4 uModel;
uniform mat3 uNormalMatrix; // 法線をワールド座標へ(モデル行列の逆行列の転置) / normals to world space (inverse transpose of uModel)

// ライティングはワールド座標で計算する / lighting is computed in world space
out vec3 vWorldPos;
out vec3 vNormal;
out vec2 vUv;
// インスタンスごとの色(第19章)。インスタンシングでないときはこのユニフォーム(既定値は白)
// The per-instance colour (chapter 19). Without instancing it comes from this uniform (white by default)
uniform vec3 uTint = vec3(1.0);
out vec3 vTint;

void main() {
  vec4 world = uModel * vec4(aPosition, 1.0);
  vWorldPos = world.xyz;
  vNormal = uNormalMatrix * aNormal; // 正規化はフラグメントシェーダーで / normalized in the fragment shader
  vUv = aUv;
  vTint = uTint;
  gl_Position = uProj * uView * world;
}

uniform mat4 uView; and uniform mat4 uProj; are gone and the block took their place.
uModel and uNormalMatrix stay plain uniforms: they change for every object, and a per-frame block is the wrong place for them.
The tint at the bottom is for the instancing part and gets explained in section 19.11; note the uniform initializer = vec3(1.0), which gives a uniform a value from the moment the program is linked, so a program that never sets uTint draws in the normal colors.

The block declaration is copied into phong.vert, phong.frag, phong_instanced.vert, skybox.vert, unlit.vert and envmap.frag.
GLSL has no #include (there's an extension, GL_ARB_shading_language_include, but it isn't available everywhere and needs extra API calls), and every declaration of a block has to be identical: same members, same types, same order.
Within one program, the vertex and fragment shaders may both declare it (phong does), and the linker treats them as one block.
If two programs declare the block differently, nothing stops you: each program simply reads the same bytes with a different layout, and you get wrong matrices.
Section 19.7 adds a check for exactly that.

19.4 The std140 layout rules

Why there are rules at all

In chapter 12 the light structs in GLSL didn't need the same layout as the C++ structs, because every member was set by name and the driver put it wherever it liked.
Now we copy a C++ struct into a buffer as raw bytes, and the shader reads those bytes at offsets the std140 rules define.
If the two disagree by even 4 bytes, every member after that point reads its neighbor's data.

The rules come from what GPUs are good at: reading aligned 16-byte chunks (four floats, a vec4).
std140 therefore aligns most things to 16 bytes.
Each type has a size and a base alignment, and every member starts at the first offset after the previous member that is a multiple of its base alignment:

offset=⌈end of the previous memberalignment⌉⋅alignment

The table

type size (bytes) base alignment notes
float, int, uint, bool 4 4 bool is 4 bytes, not 1 like in C++
vec2 8 8
vec3 12 16 a following scalar fits into the 4 bytes after it
vec4 16 16
mat3 48 16 three columns, each padded to a vec4
mat4 64 16 four vec4 columns
array of scalars or vectors 16 per element 16 every element rounded up to 16: float[4] is 64 bytes
struct members, rounded up to a multiple of 16 16 the member after a struct or an array also starts at a multiple of 16

(Matrices are column-major here, as everywhere in this series. A row_major qualifier would make the rows the padded vectors.)

Three consequences catch everyone at least once:

  • A vec3 is 16-byte aligned but only 12 bytes big. Two vec3 in a row are 32 bytes apart from start to end, with a 4-byte hole after each. A float (or int) right after a vec3 fills the hole for free.
  • A mat3 is 48 bytes, not 36. Our C++ Mat3 from chapter 10 is 9 tightly packed floats, so it can't be copied into a block as it is; chapter 10 already warned about this. Most engines send normal matrices as a mat4 for that reason.
  • Arrays of small things waste space. float weights[4] takes 64 bytes, one float per 16-byte slot. Pack such data into a vec4 instead, or use an SSBO with the std430 layout (section 19.15), where scalar arrays are tightly packed.

Worked example: the Camera block

Applying the rules to Camera:

  • mat4 uView: alignment 16, offset 0, 64 bytes, ends at 64.
  • mat4 uProj: 64 is a multiple of 16, so offset 64, ends at 128.
  • vec3 uViewPos: offset 128, 12 bytes, ends at 140.
  • float uTime: alignment 4, and 140 is a multiple of 4, so offset 140, the hole after the vec3. It ends at 144.

The block is 144 bytes, and there's no wasted byte at all.
If uTime came first, it would sit at 0, the mat4 would have to wait until 16, leaving a 12-byte hole, and the members would end at 156, which rounds up to a 160-byte block.
Order matters, and putting a scalar right after a vec3 is the classic way to use the hole.

Left: the Camera block as rows of 16 bytes. uView takes the rows at offsets 0 to 48, uProj the rows at 64 to 112, and the last row at 128 holds uViewPos in three cells and uTime in the fourth, 144 bytes in total. Top right: the 64-byte SpotLight struct with position plus cosInner, direction plus cosOuter, color plus padding and attenuation plus padding. Bottom right: the vec3 trap. In GLSL two vec3 members start at 0 and 16, but in a C++ struct without padding the second one starts at 12

The vec3 trap

The picture's bottom right shows what goes wrong most often.
In GLSL, vec3 a; vec3 b; puts b at offset 16.
Our C++ Vec3 is three floats with an alignment of 4, so struct { Vec3 a; Vec3 b; } is 24 bytes and puts b at offset 12.
Copy that struct into the buffer and the shader reads its b from bytes 16 to 27, where C++ stored b.y, b.z and whatever comes after b.
The shader's b.x is really b.y, its b.y is b.z, and its b.z belongs to the next member.
Nothing reports an error.
The colors are just wrong, or a light is in the wrong place, and every member after b is shifted too.

The cure has three parts, and we use all of them:

  1. Write the padding into the C++ struct explicitly (float pad0; after a Vec3 that has nothing to share its slot with).
  2. Check every offset with static_assert(offsetof(…) == …), so a mistake doesn't compile.
  3. Compare the size the driver computed with sizeof when the program starts (section 19.7).

Some people use alignas(16) on the C++ members instead.
That works for the start of a Vec3, but it doesn't let a following float move into the hole, and it changes sizeof(Vec3) if you put it on the type, which breaks vertex structs.
Explicit padding is more typing and much easier to read.

Worked example: the Lights block

The lights from chapter 12 now live in this block in phong.frag:

// 平行光源:向きだけ / directional light: a direction only
struct DirectionalLight {
  vec3 direction; // 光が進む向き(単位ベクトル) / the direction the light travels (unit vector)
  vec3 color;     // 0 = オフ / 0 = off
};

// 点光源:位置と減衰 / point light: a position and attenuation
struct PointLight {
  vec3 position;
  vec3 color;
  vec3 attenuation; // 定数項・一次・二次 / constant, linear, quadratic
};

// スポットライト:点光源+円錐。floatはvec3の後ろの隙間に入れる(詰め物が減る)
// spotlight: a point light + a cone. The floats sit in the gaps after the vec3s (less padding)
struct SpotLight {
  vec3 position;
  float cosInner; // 内側の円錐の半角のコサイン / cosine of the inner cone's half angle
  vec3 direction; // 円錐の軸(単位ベクトル) / the cone's axis (unit vector)
  float cosOuter; // 外側の円錐の半角のコサイン / cosine of the outer cone's half angle
  vec3 color;
  vec3 attenuation;
};

// C++側の kMaxPointLights、kMaxSpotLights と同じ / same as kMaxPointLights and kMaxSpotLights in C++
#define MAX_POINT_LIGHTS 8
#define MAX_SPOT_LIGHTS 4

// 全部の光(ユニフォームバッファ、結合点1) / all lights (uniform buffer, binding 1)
layout(std140, binding = 1) uniform Lights {
  DirectionalLight uDirLight;
  PointLight uPointLights[MAX_POINT_LIGHTS];
  SpotLight uSpotLights[MAX_SPOT_LIGHTS];
  vec3 uAmbient;        // 環境光の色と明るさ / ambient light colour and brightness
  int uPointLightCount; // 使っている数 / how many are in use
  int uSpotLightCount;
};

The member names are the ones from chapter 12, so the lighting functions didn't change.
Only the order inside SpotLight did, and here's why.
Work through the structs first:

  • DirectionalLight: direction at 0 (ends at 12), color at 16 (ends at 28). A struct's size is rounded up to 16, so it's 32 bytes.
  • PointLight: position at 0, color at 16, attenuation at 32, ending at 44, rounded up to 48 bytes.
  • SpotLight in chapter 12's order (position, direction, color, cosInner, cosOuter, attenuation): position 0, direction 16, color 32, cosInner 44 (the hole after color), cosOuter 48, attenuation 64 (a vec3 must start at a multiple of 16), ending at 76, rounded up to 80 bytes.
  • SpotLight in the new order: position 0, cosInner 12, direction 16, cosOuter 28, color 32, attenuation 48, ending at 60, rounded up to 64 bytes.

Moving each float behind a vec3 saves 16 bytes per spotlight.
Then the block:

member offset size why
uDirLight 0 32 a struct, starts at 0
uPointLights[8] 32 8 × 48 = 384 array stride 48, ends at 416
uSpotLights[4] 416 4 × 64 = 256 array stride 64, ends at 672
uAmbient 672 12 a vec3, ends at 684
uPointLightCount 684 4 an int in the hole after the vec3
uSpotLightCount 688 4 ends at 692

The members end at 692, and the block size Mesa reports is 704, rounded up to a multiple of 16 (the size of a vec4), like a struct.
Not every driver adds that last rounding: another one may report 692, and section 19.7's check accepts both.
The builder of this chapter's code didn't trust the arithmetic and asked the driver (Mesa) for the offset of every member with glGetUniformIndices and glGetActiveUniformsiv(…, GL_UNIFORM_OFFSET, …); challenge 2 has you write that dump yourself:

Terminal output listing the offsets the driver reports: uView 0, uProj 64, uViewPos 128, uTime 140, uDirLight.direction 0, uDirLight.color 16, uPointLights 0 position 32, color 48, attenuation 64, uPointLights 1 position 80, uSpotLights 0 position 416, cosInner 428, direction 432, cosOuter 444, color 448, attenuation 464, uSpotLights 1 position 480, uAmbient 672, uPointLightCount 684, uSpotLightCount 688, and the sizes Camera 144 and Lights 704, the same as in C++

Every number matches the hand calculation: the second point light starts 48 bytes after the first (80 − 32), the second spotlight 64 bytes after the first (480 − 416).
Offsets inside a block are relative to the block's start, which is why uDirLight.direction and uView are both 0: they are in different blocks.

19.5 The C++ mirrors

CameraBlock

src/uniforms.hh holds the binding point numbers, the camera struct and a short version of the rules as a reminder:

// 結合点の番号。シェーダーの layout(std140, binding = N) と同じにすること
// Binding point numbers. Must match layout(std140, binding = N) in the shaders
constexpr GLuint kCameraBinding = 0; // Camera:ビュー・射影・カメラの位置・時間 / view, projection, camera position, time
constexpr GLuint kLightsBinding = 1; // Lights:全部の光(lights.hhのLightsBlock) / all lights (LightsBlock in lights.hh)
// 2 = 影(第23章:光から見た行列) / shadows (chapter 23: light-space matrices)
// 3 = 後処理の設定(第21章:露出、ブルーム) / post-processing settings (chapter 21: exposure, bloom)

Binding points are global numbers in the context, so they're constants in one header and every chapter that adds a block takes the next free one.
2 and 3 are already reserved for the shadow and post-processing blocks of chapters 23 and 21.

// GLSL:
//   layout(std140, binding = 0) uniform Camera {
//     mat4 uView;     // offset 0
//     mat4 uProj;     // offset 64
//     vec3 uViewPos;  // offset 128
//     float uTime;    // offset 140(vec3の後ろの隙間) / (the gap after the vec3)
//   };                // 144 bytes
struct CameraBlock {
  Mat4 view;
  Mat4 proj;
  Vec3 viewPos;
  float time = 0.0f; // アニメーションの時間(秒) / animation time (seconds)
};
static_assert(offsetof(CameraBlock, proj) == 64);
static_assert(offsetof(CameraBlock, viewPos) == 128);
static_assert(offsetof(CameraBlock, time) == 140);
static_assert(sizeof(CameraBlock) == 144);

The camera block needs no padding at all: Mat4 is 16 floats (64 bytes, column-major like GLSL's mat4), and time falls exactly into the hole after viewPos.
The static_asserts still earn their keep: if someone adds a member in the wrong place, the build fails with the line that's wrong.
offsetof works here because the struct is standard-layout (only public data members of simple types).

LightsBlock

lights.hh gets the std140 versions of the three light structs, with every hole filled by hand:

struct DirectionalLightStd140 {
  Vec3 direction;
  float pad0;
  Vec3 color;
  float pad1;
};
struct PointLightStd140 {
  Vec3 position;
  float pad0;
  Vec3 color;
  float pad1;
  Vec3 attenuation;
  float pad2;
};
struct SpotLightStd140 {
  Vec3 position;
  float cosInner; // vec3の後ろの隙間に入る / fits in the gap after the vec3
  Vec3 direction;
  float cosOuter;
  Vec3 color;
  float pad0;
  Vec3 attenuation;
  float pad1;
};
struct LightsBlock {
  DirectionalLightStd140 directional;
  PointLightStd140 points[kMaxPointLights];
  SpotLightStd140 spots[kMaxSpotLights];
  Vec3 ambient;
  int pointCount;
  int spotCount;
  int pad[3];
};
static_assert(sizeof(DirectionalLightStd140) == 32 && sizeof(PointLightStd140) == 48 && sizeof(SpotLightStd140) == 64);
static_assert(offsetof(LightsBlock, points) == 32);
static_assert(offsetof(LightsBlock, spots) == 416);
static_assert(offsetof(LightsBlock, ambient) == 672);
static_assert(offsetof(LightsBlock, pointCount) == 684);
static_assert(offsetof(LightsBlock, spotCount) == 688);
static_assert(sizeof(LightsBlock) == 704);

The trailing pad0, pad1, pad2 in each struct are the "rounded up to 16" rule written out: without them a C++ array of PointLightStd140 would have a stride of 44 instead of 48.
int pad[3] at the end makes the struct 704 bytes, a multiple of 16 and the size Mesa reports.
The counts are int, never bool or size_t: both sides must agree on 4 bytes.

The user-facing PointLight, SpotLight and LightSet from chapter 12 don't change; they stay convenient (angles in radians, directions of any length, std::vector of any size).
The std140 structs are a separate, ugly-but-exact upload format, and one function converts between them.
It replaces chapter 12's apply(shader), which set every member by name:

LightsBlock LightSet::toBlock() const {
  LightsBlock b{}; // 全部0(詰め物も) / all zero (the padding too)
  b.directional.direction = normalize(directional.direction);
  b.directional.color = directional.color;

  int pointCount = static_cast<int>(points.size());
  if (pointCount > kMaxPointLights) {
    fprintf(stderr, "点光源が多すぎる / too many point lights: %d (max %d)\n", pointCount, kMaxPointLights);
    pointCount = kMaxPointLights;
  }
  for (int i = 0; i < pointCount; ++i) {
    const PointLight &p = points[static_cast<size_t>(i)];
    b.points[i].position = p.position;
    b.points[i].color = p.color;
    b.points[i].attenuation = p.attenuation;
  }
  b.pointCount = pointCount;

  int spotCount = static_cast<int>(spots.size());
  if (spotCount > kMaxSpotLights) {
    fprintf(stderr, "スポットライトが多すぎる / too many spotlights: %d (max %d)\n", spotCount, kMaxSpotLights);
    spotCount = kMaxSpotLights;
  }
  for (int i = 0; i < spotCount; ++i) {
    const SpotLight &s = spots[static_cast<size_t>(i)];
    b.spots[i].position = s.position;
    b.spots[i].direction = normalize(s.direction);
    b.spots[i].color = s.color;
    // シェーダーは角度ではなくコサインを比べる(acosを毎ピクセル計算しないため)
    // The shader compares cosines, not angles (so it does not need acos for every pixel)
    b.spots[i].cosInner = std::cos(s.innerAngle);
    b.spots[i].cosOuter = std::cos(s.outerAngle);
    b.spots[i].attenuation = s.attenuation;
  }
  b.spotCount = spotCount;
  b.ambient = ambient;
  return b;
}

LightsBlock b{} value-initializes everything, the padding included, so the unused lights are zeros and no random stack bytes ever reach the GPU.
The rest is chapter 12's code with shader.set(std::format(…)) replaced by plain struct assignments, which also means lights.cc no longer needs <format> (one less problem for Debian 12's GCC 12).
Returning the block by value (704 bytes) is cheap; the compiler constructs it directly in the caller.

19.6 Uniform buffers in C++

Two additions to Buffer

Buffer from chapter 4 creates immutable storage and fills it once.
A uniform buffer is rewritten every frame, so it gets two small functions:

  // 中身の一部を書き換える(作るときにGL_DYNAMIC_STORAGE_BITが必要) / replaces part of the contents
  // (needs GL_DYNAMIC_STORAGE_BIT at creation)
  void update(const void *data, GLsizeiptr byteCount, GLintptr offset = 0) const;
  // 番号付きの結合点に繋ぐ(ユニフォームバッファなど、第19章) / attaches to an indexed binding point
  // (uniform buffers etc., chapter 19)
  void bindBase(GLenum target, GLuint index) const { glBindBufferBase(target, index, handle); }

void Buffer::update(const void *data, GLsizeiptr byteCount, GLintptr offset) const {
  glNamedBufferSubData(handle, offset, byteCount, data);
}

glNamedBufferSubData(buffer, offset, size, data) copies size bytes from data into the buffer, starting offset bytes from its beginning:

  • buffer: the buffer object (DSA, so no binding needed).
  • offset, size: the byte range to replace. It must lie inside the buffer, or you get GL_INVALID_VALUE.
  • data: CPU memory to copy from. The copy happens before the call returns (from the application's point of view), so you may change or free data right afterwards.

The catch is the flag from chapter 4: glNamedBufferStorage with flags 0 makes the contents unchangeable, and glNamedBufferSubData on such a buffer is GL_INVALID_OPERATION (our debug callback from chapter 2 prints it).
A buffer you want to update this way must be created with GL_DYNAMIC_STORAGE_BIT.
What happens if the GPU is still reading last frame's camera while we overwrite it?
The driver takes care of it: it either waits, or (much more likely for a few hundred bytes) quietly copies our data to a new place and lets the old frame finish with the old contents.
For large buffers that change every frame, this hidden work becomes expensive, and chapter 25's sprite batcher uses persistently mapped buffers instead.

glBindBufferBase(target, index, buffer) attaches buffer to binding point index of an indexed target:

  • target: GL_UNIFORM_BUFFER here. Others with indexed binding points are GL_SHADER_STORAGE_BUFFER (section 19.15), GL_ATOMIC_COUNTER_BUFFER and GL_TRANSFORM_FEEDBACK_BUFFER.
  • index: the binding point number, 0 to GL_MAX_UNIFORM_BUFFER_BINDINGS − 1, the same number as layout(binding = …).
  • buffer: the whole buffer is attached. glBindBufferRange(target, index, buffer, offset, size) attaches only a part, which lets you pack many blocks into one buffer; the offset must then be a multiple of GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT (at most 256 bytes on any implementation).

There is no DSA version of glBindBufferBase, and none is needed: it doesn't edit the buffer, it edits the context's table of binding points.
That table is global: whatever is attached to binding point 0 is what every program's Camera block reads, until something else is attached there.

UniformBuffer

On top of Buffer sits a tiny template that owns one block:

// 一つのブロックの中身を持つユニフォームバッファ(RAII、コピー不可・移動可)。作るときに結合点に繋ぐ。
// A uniform buffer holding one block (RAII, non-copyable, movable). Attached to its binding point when created.
template <typename Block>
class UniformBuffer {
public:
  explicit UniformBuffer(GLuint bindingPoint)
      : buffer(nullptr, sizeof(Block), GL_DYNAMIC_STORAGE_BIT), binding(bindingPoint) {
    bind();
  }
  // 中身を全部書き換える(毎フレーム) / replaces the whole contents (every frame)
  void update(const Block &block) const { buffer.update(&block, sizeof(Block)); }
  // 結合点に繋ぎ直す(同じ番号に別のバッファを繋いだ後で) / re-attach to the binding point (after another
  // buffer was attached to the same number)
  void bind() const { buffer.bindBase(GL_UNIFORM_BUFFER, binding); }
  GLuint bindingPoint() const { return binding; }

private:
  Buffer buffer;
  GLuint binding;
};

The type parameter ties the buffer's size to the struct: a UniformBuffer<CameraBlock> is exactly 144 bytes, and update only accepts a CameraBlock, so you can't upload the lights into the camera buffer by accident.
nullptr as data allocates the storage without filling it; the first update fills it before the first draw.
The constructor attaches the buffer to its binding point right away, because in our program nothing else ever uses binding points 0 and 1.
bind() exists for the day something does: if you render a mirror with a second camera (chapter 17's idea), you'd attach a second camera buffer to binding point 0, draw, and call cameraUbo.bind() to put the main camera back.
Moving works because Buffer is movable; the copy constructor is implicitly deleted because Buffer's is.

19.7 Checking the layout at start-up

static_assert checks the C++ side against numbers we typed.
It can't check those numbers against the shader.
For that, Shader gets two functions:

GLint Shader::uniformBlockSize(const char *blockName) const {
  GLuint index = glGetUniformBlockIndex(program, blockName);
  if (index == GL_INVALID_INDEX) return -1;
  GLint size = 0;
  glGetActiveUniformBlockiv(program, index, GL_UNIFORM_BLOCK_DATA_SIZE, &size);
  return size;
}

bool Shader::checkUniformBlock(const char *blockName, size_t cppSize) const {
  GLint size = uniformBlockSize(blockName);
  // ドライバーによっては最後のメンバーの終わり(例:692)を、ほかは16の倍数に切り上げた値(704)を返す。
  // 16の倍数に切り上げて比べる / some drivers report where the last member ends (e.g. 692), others round up to a
  // multiple of 16 (704): compare after rounding up to 16
  if (size < 0 || ((static_cast<size_t>(size) + 15) / 16) * 16 == cppSize) return true;
  fprintf(stderr, "%s + %s: ブロック「%s」は%dバイト、C++の構造体は%zuバイト / block \"%s\" is %d bytes, the C++ struct %zu\n",
          vertexPath.c_str(), fragmentPath.c_str(), blockName, size, cppSize, blockName, size, cppSize);
  return false;
}

  • glGetUniformBlockIndex(program, name) looks up a block by its block name ("Camera", not an instance name or a member name) and returns its index in the program, or GL_INVALID_INDEX if the program has no active block of that name. A block that no stage of the program uses can be optimized away and then also counts as absent; unlit.frag never sees the lights, so a program built from unlit has no Lights block.
  • glGetActiveUniformBlockiv(program, index, pname, params) asks a question about that block. GL_UNIFORM_BLOCK_DATA_SIZE is the number of bytes the block needs in the buffer. Other useful pnames: GL_UNIFORM_BLOCK_BINDING (the binding point it reads), GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS (how many members).

checkUniformBlock returns true when the block is absent (nothing to check) or the sizes match, and prints both sizes otherwise.
"Match" means after rounding the driver's size up to a multiple of 16, as the comment says.
Drivers disagree about the end of a block: Mesa reports 704 for Lights, while another driver may report 692, where uSpotLightCount ends.
Both describe the same layout, so both must be accepted.
The price is a little precision: a shader that adds a single float at the end of Lights (696, rounded up to 704) now slips through, one more reason to keep the declarations identical.
The flip side: a C++ mirror whose sizeof isn't a multiple of 16 never passes the check, so pad the end of every block struct as LightsBlock does.
main runs it for every program right after loading the shaders:

  // C++の構造体とGLSLのブロックの大きさが合うか確かめる(std140の詰め物を間違えると違う)
  // Check that the C++ structs and the GLSL blocks have the same size (they differ if the std140 padding is wrong)
  for (const Shader *s : {&*phong, &*rocksShader, &*skybox})
    if (!s->checkUniformBlock("Camera", sizeof(CameraBlock)) || !s->checkUniformBlock("Lights", sizeof(LightsBlock)))
      return 1;

Comparing sizes isn't a complete proof: two layouts could have the same size and different offsets.
In practice almost every layout mistake (a forgotten pad, a vec3 where the C++ side has three floats, a member added on one side only) changes the size, and together with the static_asserts this has caught every mistake I've made with uniform blocks.
If you want the full check, glGetUniformIndices and glGetActiveUniformsiv(…, GL_UNIFORM_OFFSET, …) give you every member's offset, as in the screenshot in section 19.4.

19.8 Writing the blocks once per frame

In main, the two buffers are created after the shaders:

  // ユニフォームバッファ:作ったときに結合点0と1に繋がる。シェーダーはlayout(binding = …)で同じ番号を読む
  // Uniform buffers: attached to binding points 0 and 1 when created. The shaders read the same numbers through
  // layout(binding = ...)
  UniformBuffer<CameraBlock> cameraUbo(kCameraBinding);
  UniformBuffer<LightsBlock> lightsUbo(kLightsBinding);

and in the frame loop, the camera and the lights are written exactly once:

    // カメラのブロック:フレームに一度書けば、全部のシェーダーが読む(シェーダーごとのset()は要らない)
    // The camera block: written once per frame, read by every shader (no per-shader set() any more)
    float aspect = static_cast<float>(sceneFbo.width()) / static_cast<float>(sceneFbo.height());
    CameraBlock camera;
    camera.view = useOrbit ? orbit.view() : fps.view();
    camera.proj = useOrbit ? orbit.projection(aspect) : fps.projection(aspect);
    camera.viewPos = useOrbit ? orbit.position() : fps.position;
    camera.time = animTime;
    cameraUbo.update(camera);

    if (flashlightOn)
      lights.spots.push_back({.position = camera.viewPos, .direction = viewDir, .color = {1.0f, 0.95f, 0.85f}});
    lightsUbo.update(lights.toBlock()); // 光のブロックも一度だけ / the lights block, also just once

The View struct and the drawScene lambda from chapters 17 and 18 are gone.
They existed so the scene could be drawn from different cameras with the matrices passed to each program; now a camera is simply "whatever is in binding point 0".
Drawing the island looks like this, without a single camera or light uniform:

    // ビュー・射影・光はもう設定しない:ブロックから来る / no view, projection or lights to set: they come from the blocks
    phong->use();
    phong->set("uViewMode", viewMode);
    phong->set("uEnvironmentTint", environmentTint);
    scene->draw(*phong, Mat4::identity(), white, ModelPass::Opaque);
    // 浮島の下の岩:同じ岩のモデルを平たく大きく / the rock under the floating island: the same rock model, wide and flat
    rock->draw(*phong, translate({0.0f, -1.7f, 0.0f}) * scale({10.0f, 3.4f, 10.0f}), white);

The floating island is the same rock.glb as the ring, scaled to 10 × 3.4 × 10.
That's a non-uniform scale, which is fine here because Model::draw computes a proper normal matrix per node (chapter 10).
Remember that for section 19.11, where the instanced rocks take a shortcut.

The order matters in one way: the buffers must hold the new values before the draw calls that read them.
OpenGL executes commands in order, so update followed by draws is always correct; updating a block in the middle of a frame is also correct and affects only the draws after it.

19.9 Instancing: the idea

What a draw call costs

A draw call like glDrawElements looks cheap: a handful of parameters.
The work hides behind it.
Before the GPU can start, the driver has to make sure everything the draw depends on is valid and in the format the hardware wants: the program, the VAO's attribute formats and buffers, every bound texture and sampler, the uniform values that changed since the last draw, depth, blend and cull state, the framebuffer.
It translates all of that into commands for the GPU and appends them to a command buffer.
Most of that is CPU work, done for every draw call, and in OpenGL it's done again every time because the driver can't know what you changed.

For a few hundred draw calls per frame this doesn't matter.
For thousands of small objects, the CPU spends its whole frame describing work to a GPU that finishes each tiny piece in no time and then waits for the next.
This is called being CPU-bound or draw-call bound, and it was the classic limit on how many objects a game could show.

One call, many copies

Instancing draws the same mesh many times with one call: glDrawElementsInstanced takes the parameters of glDrawElements plus an instance count.
The vertex shader then runs for every vertex of every instance, and the built-in gl_InstanceID (0 to instanceCount − 1) says which instance the current vertex belongs to.
Without anything else, every instance would be drawn in the same place, so each instance needs its own data: at least a model matrix.
There are three common ways to give it to the shader:

  • A uniform array indexed by gl_InstanceID. Simple, but limited by the block size: 16 KB is only 256 mat4.
  • Instanced vertex attributes (also called instanced arrays): an ordinary vertex buffer whose attributes advance once per instance instead of once per vertex. No size limit beyond memory, works since OpenGL 3.3. That's what we use.
  • A shader storage buffer (SSBO) indexed by gl_InstanceID. The most flexible; section 19.15 talks about it.

19.10 Instance attributes

The data

mesh.hh gets the per-instance struct and its attribute layout:

// インスタンスごとのデータ(第19章):モデル行列(列4本をlocation 4〜7)と色(location 8)
// Per-instance data (chapter 19): the model matrix (its four columns at locations 4..7) and a colour (location 8)
struct InstanceData {
  Mat4 model;
  Vec3 color;
};

constexpr VertexAttrib kInstanceLayout[] = {
  {4, 4, offsetof(InstanceData, model) + 0},  // layout(location = 4) in mat4 aInstanceModel(列0 / column 0)
  {5, 4, offsetof(InstanceData, model) + 16}, // 列1 / column 1
  {6, 4, offsetof(InstanceData, model) + 32}, // 列2 / column 2
  {7, 4, offsetof(InstanceData, model) + 48}, // 列3 / column 3
  {8, 3, offsetof(InstanceData, color)},      // layout(location = 8) in vec3 aInstanceColor
};

This is the same VertexAttrib description we've used for vertices since chapter 4: location, number of components, byte offset.
Two things are new.

A mat4 attribute takes four locations.
One attribute location holds at most four components (a vec4), so the shader's layout(location = 4) in mat4 aInstanceModel occupies locations 4, 5, 6 and 7, one per column.
On the C++ side each column is its own attribute with 4 floats, 16 bytes after the previous one; Mat4 stores its columns one after another (m.c[0] to m.c[3]), which is exactly that layout.
A mat3 would take three locations, and a dmat4 (doubles) even eight.

The locations continue after the vertex attributes.
0 to 2 are position, normal and UV, and 3 is the tangent of ModelVertex (chapter 22 needs it).
Instance data starts at 4, and the color sits at 8; 9 and up are free for more per-instance data (challenge 6 uses 9).
A VAO has at least 16 attribute locations (GL_MAX_VERTEX_ATTRIBS), so there's room.

InstanceData is 76 bytes (64 + 12), and that's also the stride: unlike uniform blocks, vertex attributes only need 4-byte alignment, so no padding is required.
All 64 000 possible rocks take 4.86 MB; the default 4000 use the first 304 000 bytes.

Top: the vertex buffer at binding 0 with the vertices v0 to v161, stride 48, divisor 0. Bottom: the instance buffer at binding 1 with stride 76 and divisor 1; instance 0 is split into its four matrix columns at locations 4 to 7 and its color at location 8, followed by instance 1, instance 2 up to instance 3999. Middle: the vertex shader runs for instance 0 with v0, v1 up to v161, all reading instance 0, then for instance 1 with v0, v1 up to v161, all reading instance 1

The binding divisor

Chapter 3 split vertex input into attributes (format, location) and bindings (buffer, offset, stride), and said that chapter 19 would give a binding a divisor.
Here it is, in mesh.cc:

void Mesh::setInstanceBuffer(const Buffer &buffer, GLsizei stride, std::span<const VertexAttrib> layout) {
  constexpr GLuint kInstanceBinding = 1; // 頂点はバインディング0 / the vertices are binding 0
  glVertexArrayVertexBuffer(vertexArray, kInstanceBinding, buffer.id(), 0, stride);
  for (const VertexAttrib &a : layout) {
    glEnableVertexArrayAttrib(vertexArray, a.location);
    glVertexArrayAttribFormat(vertexArray, a.location, a.components, a.type, a.normalized, a.offset);
    glVertexArrayAttribBinding(vertexArray, a.location, kInstanceBinding);
  }
  // 1 = インスタンス1つごとに1要素進む(0なら頂点ごと) / 1 = advance one element per instance (0 = per vertex)
  glVertexArrayBindingDivisor(vertexArray, kInstanceBinding, 1);
}

The first part is the constructor's loop from chapter 4 again, with binding 1 instead of 0: attach the instance buffer to binding 1 with a stride of 76, then enable, format and connect each instance attribute to that binding.
The new call is the last one.

glVertexArrayBindingDivisor(vaobj, bindingindex, divisor) sets how often the attributes of a binding advance:

  • vaobj: the VAO.
  • bindingindex: the binding, 1 for our instance buffer. It applies to every attribute connected to that binding (all five of ours).
  • divisor: 0 (the default) means "advance once per vertex", the normal behavior. 1 means "advance once per instance": every vertex of instance 0 reads element 0, every vertex of instance 1 reads element 1, and so on. N means "advance once every N instances", which is rarely useful (e.g. 2 to give pairs of instances the same color).

For instance number i, an attribute with divisor d>0 reads element ⌊i/d⌋, and the vertex index plays no role at all.
With divisor 0 it reads the element of the current vertex, as always.

Old code uses glVertexAttribDivisor(attribute, divisor), which sets the divisor per attribute: for a matrix you'd call it four times, once per column location.
In OpenGL 4.3 that function was redefined in terms of the new model (it now sets the divisor of the binding with the same number as the attribute and connects the two), so both still work, but don't mix them on one VAO.

The common mistakes, all of which give you exploding geometry rather than an error message:

  • Forgetting the divisor. Then the instance attributes advance per vertex: vertex 0 uses rock 0's matrix, vertex 1 rock 1's, and every triangle connects corners of three different rocks. You get a sky full of long shards.
  • Wrong column offsets. The columns are at 0, 16, 32 and 48 bytes; giving all four the same offset makes every column the first one.
  • Overlapping locations. An instance attribute at location 3 would replace the tangent; the vertex buffer's data at that location would never be read.
  • Integer data with glVertexArrayAttribFormat. It converts to float. Integer attributes (an instance ID, a material index) need glVertexArrayAttribIFormat and an int/uint input in GLSL.

The draw function is short:

void Mesh::drawInstanced(GLsizei count) const {
  glBindVertexArray(vertexArray);
  if (indexCount > 0) glDrawElementsInstanced(primitive, indexCount, GL_UNSIGNED_INT, nullptr, count);
  else glDrawArraysInstanced(primitive, 0, vertexCount, count);
}

glDrawElementsInstanced(mode, count, type, indices, instancecount) is glDrawElements plus one parameter: count is still the number of indices of one instance (960 for the rock), and instancecount is the number of instances.
glDrawArraysInstanced(mode, first, count, instancecount) is the same for meshes without indices.
With instancecount = 1 they draw exactly what the non-instanced calls draw; with 0 they draw nothing.
There are also …BaseInstance variants that start the instance attributes at a given element (glDrawElementsInstancedBaseInstance); gl_InstanceID still starts at 0 there, and GLSL 4.60's gl_BaseInstance tells the shader the base.
They become important with multi-draw indirect (section 19.15).

Whole models

A glTF model has one VAO per primitive, so Model forwards both functions to each of them:

void Model::setInstanceBuffer(const Buffer &buffer, GLsizei stride, std::span<const VertexAttrib> layout) {
  for (MeshData &m : meshes)
    for (Primitive &p : m.primitives) p.mesh.setInstanceBuffer(buffer, stride, layout);
}

void Model::drawInstanced(const Shader &shader, const Texture2D &white, GLsizei count) const {
  std::vector<DrawItem> items;
  for (int root : roots) collect(root, Mat4::identity(), Mat4::identity(), true, ModelPass::All, {}, items);
  drawItems(items, shader, &white, shader.has("uNormalMatrix"), count);
}

drawInstanced collects the primitives as draw does (chapter 16), but with the identity as the model's transform: uModel is then the node's matrix inside the model, and the instance matrix is applied on top of it in the shader.
drawItems got an instances parameter that defaults to 0 and picks the call:

    if (instances > 0) p.mesh.drawInstanced(instances);
    else p.mesh.draw();

So materials, textures and double-sided culling work for instanced models exactly as for normal ones, with one draw call per primitive instead of one per primitive per copy.
Our rock has one primitive, so the whole ring is one draw call.
One instance buffer can feed several VAOs at once; all the rock's primitives (if it had several) would read the same buffer.

19.11 The instanced vertex shader

Here is shaders/phong_instanced.vert in full:

#version 460 core
// インスタンシング用のphong.vert:インスタンスごとの行列と色を頂点属性で受け取る(フラグメントシェーダーはphong.frag)
// phong.vert for instancing: the per-instance matrix and colour arrive as vertex attributes (fragment shader: phong.frag)
layout(location = 0) in vec3 aPosition;
layout(location = 1) in vec3 aNormal;
layout(location = 2) in vec2 aUv;
// location 3は接線(第22章) / location 3 is the tangent (chapter 22)
layout(location = 4) in mat4 aInstanceModel; // mat4はlocationを4つ使う(4〜7) / a mat4 takes four locations (4..7)
layout(location = 8) in vec3 aInstanceColor;

// カメラ(ユニフォームバッファ、結合点0、std140)。使う全部のシェーダーで同じ宣言(C++ではCameraBlock)
// The camera (uniform buffer, binding 0, std140). The same declaration in every shader that uses it (CameraBlock in C++)
layout(std140, binding = 0) uniform Camera {
  mat4 uView;
  mat4 uProj;
  vec3 uViewPos; // カメラの位置(ワールド座標) / camera position (world space)
  float uTime;   // アニメーションの時間(秒) / animation time (seconds)
};

uniform mat4 uModel;        // モデルの中のノードの行列 / the node's matrix inside the model
uniform mat3 uNormalMatrix; // その法線行列 / its normal matrix
uniform float uOrbitSpeed;  // 環の公転の速さ(半径8 mで、ラジアン毎秒) / orbit speed of the ring (rad/s at radius 8 m)

out vec3 vWorldPos;
out vec3 vNormal;
out vec2 vUv;
out vec3 vTint;

// Y軸周りの回転 / rotation about the Y axis
mat4 rotationY(float a) {
  float c = cos(a), s = sin(a);
  return mat4(c, 0.0, -s, 0.0, 0.0, 1.0, 0.0, 0.0, s, 0.0, c, 0.0, 0.0, 0.0, 0.0, 1.0);
}

void main() {
  // 公転:内側ほど速い(ケプラーの法則:角速度 ∝ 半径^-1.5)。C++のorbitAngle()と同じ式
  // Orbit: inner rocks are faster (Kepler: angular speed ∝ radius^-1.5). The same formula as orbitAngle() in C++
  float radius = length(aInstanceModel[3].xz);
  mat4 orbit = rotationY(uTime * uOrbitSpeed * pow(8.0 / radius, 1.5));
  mat4 model = orbit * aInstanceModel * uModel;
  vec4 world = model * vec4(aPosition, 1.0);
  vWorldPos = world.xyz;
  // 岩の拡大縮小は一様なので、法線は行列の3×3で回すだけで良い(長さはphong.fragで正規化)
  // The rocks are scaled uniformly, so the normal can simply be rotated by the 3×3 part (phong.frag normalizes it)
  vNormal = mat3(orbit * aInstanceModel) * (uNormalMatrix * aNormal);
  vUv = aUv;
  vTint = aInstanceColor;
  gl_Position = uProj * uView * world;
}

It has the same outputs as phong.vert, so the fragment shader is phong.frag, unchanged apart from the tint: main loads the program as Shader::load("shaders/phong_instanced.vert", "shaders/phong.frag").

The orbit, computed on the GPU

The instance buffer is uploaded once and never touched again.
Yet the rocks move, because the shader rotates each one about the Y axis by an angle that depends on the time from the camera block.
The angle grows with time at an angular speed that depends on the rock's distance r from the center:

θ(t)=t⋅ω8⋅(8r)1.5,ω8=0.25rad/s

The exponent is Kepler's third law: the square of an orbit's period grows with the cube of its radius, T2∝r3, so the angular speed ω=2π/T is proportional to r−1.5.
The ring's radius goes from 8 to 14.5 m, so:

  • at r=8: ω=0.25⋅1=0.25 rad/s, one orbit in 2π/0.25≈25.1 s.
  • at r=14.5: (8/14.5)1.5≈0.410, so ω≈0.102 rad/s, one orbit in about 61.3 s.

The inner edge overtakes the outer edge, which you can watch in the video.
The radius comes from the instance matrix itself: its last column, aInstanceModel[3], is the translation (GLSL indexes matrices by column), and length(….xz) is the horizontal distance from the Y axis.
A rotation about Y keeps both the distance from the axis and the height, so the formula can be evaluated on the original matrix and the rock stays in its lane forever.

rotationY builds the same matrix as rotateY in linalg.hh (Linear Algebra chapter 8).
The mat4 constructor takes its 16 numbers column by column, so the first four, (cosa,0,−sina,0), are the first column, where the X axis ends up:

𝐑y(a)=[cosa0sina00100−sina0cosa00001]

The matrix chain

model = orbit * aInstanceModel * uModel reads right to left as usual:

  1. uModel is the node's matrix inside rock.glb (the identity for this file, but a multi-node model would need it).
  2. aInstanceModel is this rock's place in the ring: scale, then a random rotation, then the translation to its spot, all baked on the CPU by makeRing in section 19.12.
  3. orbit turns the placed rock about the world's Y axis.

Swap the last two and the orbit rotation would happen in the rock's own space before it's moved out, so each rock would spin on the spot instead of traveling around the island.

Normals and the tint

The normal goes through uNormalMatrix (the node's) and then through the 3×3 part of orbit * aInstanceModel, not its inverse transpose.
That's correct only because every rock is scaled uniformly (scale({size, size, size})): a rotation is its own inverse transpose, and a uniform scale only changes the normal's length, which phong.frag normalizes away.
A non-uniform per-instance scale would tilt the normals wrong, exactly the problem chapter 10 solved; then you'd either store a normal matrix per instance (three more locations) or compute transpose(inverse(mat3(m))) per vertex, which costs a matrix inverse for every vertex of every instance.

vTint carries the instance color to the fragment shader, where one line changed:

  s.diffuse = uMaterial.diffuse * vTint * base.rgb;

The rocks share one material, and the tint varies each one's diffuse color between gray and a warm brown.
Since phong.frag now reads vTint, every vertex shader paired with it must write it, or the program fails to link.
phong.vert writes its uTint uniform, which defaults to white thanks to the initializer, so the diorama looks exactly as before without any C++ change.
The one-by-one path in section 19.12 sets uTint per rock to get the same colors without instancing.

19.12 The ring in main

Generating the instances

makeRing fills all 64 000 slots once at start-up, with a fixed pseudo-random sequence (the same random01 generator that places the grass since chapter 16):

// 浮島の周りの岩の環。位置・回転・大きさ・色は決まった乱数で / the ring of rocks around the floating island;
// position, rotation, size and colour from a fixed pseudo-random sequence
static std::vector<InstanceData> makeRing() {
  std::vector<InstanceData> rocks;
  rocks.reserve(kMaxRocks);
  std::uint32_t seed = 19;
  for (int i = 0; i < kMaxRocks; ++i) {
    // 半径:二つの乱数の平均で真ん中を濃く / radius: the mean of two randoms makes the middle denser
    float radius = 8.0f + 6.5f * 0.5f * (random01(seed) + random01(seed));
    float angle = 2.0f * PI * random01(seed);
    float height = 2.0f + 0.45f * (random01(seed) + random01(seed) + random01(seed) - 1.5f) / 1.5f;
    float u = random01(seed);
    float size = 0.08f + 0.4f * u * u * u; // 小さい岩が多い / mostly small rocks
    Vec3 axis = normalize(Vec3{random01(seed) - 0.5f, random01(seed) - 0.5f, random01(seed) - 0.5f});
    float spin = 2.0f * PI * random01(seed);
    float shade = 0.7f + 0.45f * random01(seed);
    float warm = 0.12f * (random01(seed) - 0.5f);
    InstanceData d;
    d.model = translate({radius * std::cos(angle), height, radius * std::sin(angle)}) * rotate(axis, spin) *
              scale({size, size, size});
    d.color = {shade + warm, shade, shade - warm};
    rocks.push_back(d);
  }
  return rocks;
}

A few small tricks shape the ring:

  • The mean of two random numbers is more likely near the middle than at the ends (a triangle distribution), so the ring is densest at a radius of 11.25 m and thins out towards 8 and 14.5 m.
  • The height is the mean of three random numbers, scaled to 2 ± 0.45 m: almost a bell curve, so the ring is a flat band with a few stragglers.
  • Sizes use u3: most values of u3 are small, so most rocks are pebbles of 8 cm and a few are boulders up to 48 cm.
  • Rotation about a random axis (rotate(axis, angle) from linalg.hh) hides that all rocks are the same mesh.

Because the sequence is fixed, the ring is the same every run, and the first 1000 rocks of the 64 000 are also the first 1000 of the 4000: = and − add or remove rocks without reshuffling the others.

The buffer is created once, with flags 0 (immutable, never updated), and attached to every primitive of the rock model:

  // インスタンスのバッファ:全部の岩を一度だけアップロード。描く数を変えても作り直さない(先頭からcount個使う)
  // The instance buffer: every rock uploaded once. Changing the count does not rebuild it (the first `count` are used)
  std::vector<InstanceData> ring = makeRing();
  Buffer instanceBuffer(ring.data(), static_cast<GLsizeiptr>(ring.size() * sizeof(InstanceData)));
  rock->setInstanceBuffer(instanceBuffer, sizeof(InstanceData), kInstanceLayout);

Changing the number of rocks only changes instancecount; the buffer always holds the maximum.
The CPU-side ring vector stays alive too, because the one-by-one mode reads it.

Two ways to draw the ring

The ring is drawn after the island and the grass and before the sky box (the frame order from chapter 18 still holds):

    if (instanced) {
      // インスタンシング:プリミティブ1つにつき描画呼び出し1回。公転はシェーダーがuTimeで計算する
      // Instancing: one draw call per primitive. The shader computes the orbit from uTime
      rocksShader->use();
      rocksShader->set("uViewMode", viewMode);
      rocksShader->set("uEnvironmentTint", environmentTint);
      rocksShader->set("uOrbitSpeed", kOrbitSpeed);
      rock->drawInstanced(*rocksShader, white, rockCount);
    } else {
      // 一つずつ:岩ごとにuModel・uNormalMatrix・マテリアル・uTintを設定して描画呼び出し。公転はCPUで計算
      // One by one: per rock set uModel, uNormalMatrix, the material and uTint, then a draw call. The orbit is
      // computed on the CPU
      phong->use();
      for (int i = 0; i < rockCount; ++i) {
        const InstanceData &d = ring[static_cast<size_t>(i)];
        phong->set("uTint", d.color);
        rock->draw(*phong, rotateY(orbitAngle(d.model, animTime)) * d.model, white);
      }
      phong->set("uTint", Vec3{1.0f, 1.0f, 1.0f});
    }

The instanced branch sets three uniforms and makes one draw call, whatever the count.
The one-by-one branch is how you'd draw the ring without this chapter: per rock it computes the orbit on the CPU with the same formula as the shader,

// 公転の角度:内側ほど速い(ケプラー:角速度 ∝ 半径^-1.5)。phong_instanced.vertと同じ式
// The orbit angle: inner rocks move faster (Kepler: angular speed ∝ radius^-1.5). Same formula as phong_instanced.vert
static float orbitAngle(const Mat4 &instance, float time) {
  float radius = std::sqrt(instance.c[3].x * instance.c[3].x + instance.c[3].z * instance.c[3].z);
  return time * kOrbitSpeed * std::pow(8.0f / radius, 1.5f);
}

sets the tint, and calls Model::draw, which sets uModel, computes and sets the normal matrix (a 4×4 inverse), applies the material (10 uniforms and 3 texture binds) and issues glDrawElements.
That's 13 uniform calls with a name lookup each, plus the draw call, per rock.
uTint goes back to white afterwards, otherwise the next frame's diorama would be tinted with the last rock's color.

Both branches produce the same picture.
The builder compared them pixel by pixel: out of 921 600 pixels, 127 differ by at most 13 of 255, from float rounding in the orbit and normal math (the CPU and the shader evaluate the same formulas with different rounding and in a different order):

Left: the ring drawn with instancing in one draw call. Right: the same frame drawn one by one with 4000 draw calls. The two pictures look identical

And here is the ring with 1000, 4000, 16 000 and 64 000 rocks, all drawn with one instanced call:

Four views of the scene: with 1000 rocks the ring is sparse, with 4000 (the default) it is a clear band, with 16000 it is dense, and with 64000 it is an almost solid carpet of rocks around the island

19.13 Measuring, honestly

Two clocks

The program times only the ring, with two different clocks:

    // 岩の環:ここだけ時間を測る / the ring of rocks: only this part is timed
    gpuTimer.begin();
    auto cpuStart = std::chrono::steady_clock::now();

    double cpuMs = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - cpuStart).count();
    gpuTimer.end();

std::chrono::steady_clock measures CPU time spent issuing the commands: how long our code and the driver needed to get through the branch.
It says nothing about when the GPU actually draws, because OpenGL calls return long before the GPU has done the work.

For the GPU side, OpenGL has timer queries, wrapped in src/gpu_timer.hh:

class GpuTimer {
public:
  GpuTimer();
  ~GpuTimer();
  GpuTimer(const GpuTimer &) = delete;
  GpuTimer &operator=(const GpuTimer &) = delete;

  void begin();
  void end();
  // 一番新しく届いた結果(ミリ秒)。まだ一つも届いていなければstd::nullopt
  // The most recent result that has arrived (milliseconds). std::nullopt if none has arrived yet
  std::optional<double> latestMs();

private:
  static constexpr int kQueries = 4; // 4フレーム分まで遅れて良い / results may lag up to 4 frames
  GLuint queries[kQueries] = {};
  bool pending[kQueries] = {};
  int next = 0;
  bool running = false;
  std::optional<double> latest;
};

GpuTimer::GpuTimer() { glCreateQueries(GL_TIME_ELAPSED, kQueries, queries); }

GpuTimer::~GpuTimer() { glDeleteQueries(kQueries, queries); }

void GpuTimer::begin() {
  // 使おうとしているクエリの結果がまだなら、今回は測らない(待つとCPUとGPUが同期して遅くなる)
  // If the query we would use still has no result, skip this measurement (waiting would stall CPU and GPU)
  latestMs();
  if (pending[next]) return;
  glBeginQuery(GL_TIME_ELAPSED, queries[next]);
  running = true;
}

void GpuTimer::end() {
  if (!running) return;
  glEndQuery(GL_TIME_ELAPSED);
  pending[next] = true;
  next = (next + 1) % kQueries;
  running = false;
}

std::optional<double> GpuTimer::latestMs() {
  // 古い順に、届いた結果を読む / read the results that have arrived, oldest first
  for (int k = 0; k < kQueries; ++k) {
    int i = (next + k) % kQueries;
    if (!pending[i]) continue;
    GLint available = 0;
    glGetQueryObjectiv(queries[i], GL_QUERY_RESULT_AVAILABLE, &available);
    if (!available) continue;
    GLuint64 ns = 0;
    glGetQueryObjectui64v(queries[i], GL_QUERY_RESULT, &ns); // ナノ秒 / nanoseconds
    latest = static_cast<double>(ns) / 1.0e6;
    pending[i] = false;
  }
  return latest;
}

The functions:

  • glCreateQueries(target, n, ids) creates n query objects for target (DSA; the old glGenQueries creates names without a target). GL_TIME_ELAPSED measures time; other targets count samples that pass the depth test (GL_SAMPLES_PASSED, GL_ANY_SAMPLES_PASSED) or primitives.
  • glBeginQuery(GL_TIME_ELAPSED, id) and glEndQuery(GL_TIME_ELAPSED) bracket the commands to measure. Only one query per target can be active at a time, so timer queries don't nest.
  • glGetQueryObjectiv(id, GL_QUERY_RESULT_AVAILABLE, &available) asks, without waiting, whether the GPU has finished the bracketed work.
  • glGetQueryObjectui64v(id, GL_QUERY_RESULT, &ns) reads the result: nanoseconds as a 64-bit integer. If the result isn't available yet, this call waits until it is.

That last point is why GpuTimer has four queries.
The GPU runs a frame or two behind the CPU.
If we read the result right after glEndQuery, the CPU would sit and wait until the GPU caught up, every frame, and we'd have destroyed exactly the parallelism we wanted to measure.
Instead the queries are used round-robin, results are only read once GL_QUERY_RESULT_AVAILABLE says so, and if the next query is still busy, that frame simply isn't measured.

What the numbers are

Here are the averages of frames 61 to 120 for three rock counts, both modes, recorded with the scripted harness used to make every screenshot of this series:

Terminal output. 1000 rocks: instanced 1 draw call, CPU 28.33 ms, GPU 12.15 ms; one by one 1000 draw calls, CPU 32.70 ms, GPU 12.68 ms. 4000 rocks: instanced CPU 107.57 ms, GPU 91.25 ms; one by one CPU 118.80 ms, GPU 97.21 ms. 16000 rocks: instanced CPU 395.81 ms, GPU 375.04 ms; one by one CPU 433.94 ms, GPU 412.90 ms. A note says: Mesa llvmpipe, the GPU is the CPU, not GPU numbers

Before reading anything into these, look at where they come from.
This machine has no GPU.
It runs Mesa's llvmpipe, a software rasterizer: the vertex shader, the rasterization and the fragment shader all run on CPU threads.
On llvmpipe much of the shading of a draw call happens inside the draw call itself, which is why even the single instanced call "costs" about 108 ms of CPU time at 4000 rocks, and why GL_TIME_ELAPSED here measures the software rasterizer, not a graphics card.
None of these milliseconds says anything about how fast this runs on real hardware, and I won't pretend otherwise.

There's one thing the numbers do show cleanly: the extra cost of separate draw calls, because the shading work is the same in both modes and drops out of the difference:

rocks instanced CPU one by one CPU difference per extra draw call
1 000 28.33 ms 32.70 ms 4.37 ms 4.4 µs
4 000 107.57 ms 118.80 ms 11.23 ms 2.8 µs
16 000 395.81 ms 433.94 ms 38.13 ms 2.4 µs

About 2.4 to 4.4 microseconds per rock drawn separately.
Keep in mind what that includes: not only glDrawElements, but the 13 uniform calls with their name lookups, three texture binds, a matrix inverse and Model::draw's small std::vector, in a build without optimization flags (CMake's default when no build type is given).
It's the price of "one object, one draw call" the way our engine does it, not a property of OpenGL in general.

What changes on a real GPU

On a desktop GPU, shading 4000 × 320 = 1.28 million small triangles is a small job, and with 16 000 rocks it's still not much.
The CPU side doesn't get faster, though: those microseconds per object are spent in our code and in the driver's state validation and command building, and they add up linearly with the number of objects.
So on real hardware the balance tips completely.
In instanced mode the CPU time for the ring stays tiny and doesn't grow with the count, while the one-by-one mode's CPU time grows with every rock, and at some count it becomes the whole frame: the GPU sits idle, waiting for the CPU to describe the next rock.
That's where instancing wins by a wide margin, and it's the reason every engine draws repeated objects this way.

I can't give you measured numbers for your machine, and numbers from someone else's machine would only mislead you.
Run it yourself: the window title shows the rock count, the number of draw calls and both timings, updated every second or so.
Press I to switch modes and = to add rocks, and watch the CPU column.
If the first line the program prints (the renderer from chapter 2) says llvmpipe or softpipe, you're on a software renderer too, and you'll see something like the table above.

19.14 Platform notes

  • Release builds for timing. CPU timings of a Debug build mostly measure the missing optimization. On Windows build with cmake --build build --config Release and run build\Release\game.exe from the project root; on Linux and FreeBSD configure a separate directory with cmake -S . -B build-release -DCMAKE_BUILD_TYPE=Release. Compare both modes in the same build.
  • Timer queries report real GPU times with the NVIDIA, AMD and Intel drivers on Windows and Linux, and with Mesa's hardware drivers (radeonsi, iris) on Linux and FreeBSD (via the drm-kmod graphics drivers). Inside a virtual machine or without GPU drivers you get llvmpipe; glxinfo -B (Linux, FreeBSD) shows the renderer as well.
  • The = and − keys are GLFW's GLFW_KEY_EQUAL and GLFW_KEY_MINUS, which are named after their position on a US keyboard. On a Japanese (JIS) keyboard, GLFW_KEY_EQUAL is the ^ key to the right of −; on a German keyboard it's the ´ key to the right of ß, and GLFW_KEY_MINUS is ß itself.
  • Vsync (chapter 2) limits the frame rate to the monitor's refresh rate, so frames per second won't show the difference until a mode takes longer than one refresh; the CPU timing of the ring does.

19.15 How real engines do it

  • Shader storage buffers (SSBOs). Since OpenGL 4.3, layout(std430, binding = N) buffer Name { … }; declares a block backed by a GL_SHADER_STORAGE_BUFFER. It can be huge (many megabytes, in practice limited mostly by memory), the shader can write to it, its last member can be an unsized array (InstanceData instances[];), and std430 packs arrays of scalars and vec2 tightly (a vec3 is still 16-byte aligned). Engines keep per-object data for the whole scene (matrices, material indices, bounding spheres) in SSBOs and read them with gl_InstanceID, or with an index stored in the draw command.
  • Blocks by update frequency. Our split (per frame: camera; per frame: lights; per draw: plain uniforms) is the usual idea taken further: per-frame, per-pass, per-material and per-object blocks, many of them packed into one large buffer and selected with glBindBufferRange at offsets aligned to GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT. The buffer is written through a persistent mapping as a ring of frames (chapter 25 shows the technique for sprites).
  • Multi-draw indirect. glMultiDrawElementsIndirect(mode, type, indirect, drawcount, stride) executes many draws from an array of DrawElementsIndirectCommand {count, instanceCount, firstIndex, baseVertex, baseInstance} stored in a GL_DRAW_INDIRECT_BUFFER. With all meshes in one big vertex and index buffer, one call can draw different meshes, each instanced, and gl_DrawID (GLSL 4.60) tells the shader which command it belongs to. That removes the "same mesh" limit of instancing.
  • GPU culling. Once the draw commands live in a buffer, the GPU can write them itself: a compute shader (GLSL chapter 15) tests every instance's bounding sphere against the camera frustum (and often against a depth pyramid for occlusion), appends the visible ones to an instance list and writes the counts into the indirect buffer. The CPU never even learns how many rocks are visible. Challenge 7 does the CPU version of the frustum test.
  • Vulkan and Slang. Vulkan has the same blocks (uniform and storage buffers in descriptor sets, plus small push constants), with the same std140 and std430 rules, and Slang's ConstantBuffer<T> maps to them. Everything in section 19.4 carries over directly.

19.16 Summary

  • A plain uniform belongs to one program. A uniform block reads its members from a buffer attached to a numbered binding point: glBindBufferBase(GL_UNIFORM_BUFFER, N, buffer) on the C++ side, layout(std140, binding = N) uniform Block { … }; in GLSL.
  • Without an instance name the members are global names, so converting old shaders is a matter of replacing the uniforms with the block. Every shader must declare the block identically; GLSL has no #include.
  • std140: scalars align to 4, vec2 to 8, vec3 and vec4 to 16; a vec3 is 12 bytes and a following scalar fills its hole; mat3 is 48 and mat4 64 bytes; array elements and structs are rounded up to 16. Camera = 144 bytes (uTime at 140), Lights = 704 bytes (offsets 0, 32, 416, 672, 684, 688).
  • The vec3 trap: a C++ Vec3 is 12 bytes with alignment 4, so C++ structs need explicit padding. Check with static_assert(offsetof(…)) and compare GL_UNIFORM_BLOCK_DATA_SIZE, rounded up to 16, with sizeof at start-up.
  • Buffers updated with glNamedBufferSubData need GL_DYNAMIC_STORAGE_BIT. Binding points are global context state.
  • Instancing: glDrawElementsInstanced(mode, count, type, indices, instancecount) draws a mesh instancecount times. Per-instance attributes live in a second vertex buffer at binding 1 with glVertexArrayBindingDivisor(vao, 1, 1): they advance once per instance.
  • A mat4 attribute uses four locations (4 to 7 here, one column each, offsets 0, 16, 32, 48); the instance color is at 8.
  • The orbit is computed in the vertex shader from uTime in the camera block, so the instance buffer is uploaded once and never changed. Normals with mat3(model) are only correct for uniform scale.
  • On llvmpipe the "GPU" is the CPU, so our timings aren't GPU numbers; the clean result is about 2.4 to 4.4 µs of CPU time per extra draw call. On real GPUs that per-object CPU cost is what instancing removes.

19.17 Challenges

  1. ★ Add float exposure and float pad[3] after time in the C++ CameraBlock (it grows to 160 bytes; fix its static_assert), and a float uExposure after uTime in one shader only, skybox.vert. The program should refuse to start, with checkUniformBlock reporting that phong's Camera block is 144 bytes while the C++ struct is 160; add the member to the other five shaders that declare the block and it runs again. Then remove pad[3] (and make the static_assert say 148): now it never starts, whatever the shaders say, because 148 isn't a multiple of 16 and no rounded driver size can equal it.
  2. ★ Print every member's offset yourself: collect the names ("uView", "uPointLights[1].position", …), get their indices with glGetUniformIndices and their offsets with glGetActiveUniformsiv(program, n, indices, GL_UNIFORM_OFFSET, offsets). You should get exactly the numbers in the screenshot in section 19.4.
  3. ★ Remove float pad0 from PointLightStd140 and add a float pad3 at its end, so the struct stays 48 bytes: every static_assert and the start-up size check still pass. At night (N) the lantern's light should turn a deeper orange and reach much farther, because the shader now reads its color from C++'s color.y, color.z and pad1, (1.6, 0.7, 0), and its attenuation from (0.35, 0.44, 0), which drops the quadratic term. Nothing reports an error: this is the kind of mistake a size check can't catch.
  4. ★★ Color the rocks without color data: in phong_instanced.vert, choose one of three colors with gl_InstanceID % 3. The ring should show three clearly different rock colors in a repeating pattern, with the instance color attribute unused.
  5. ★★ Move the orbit to the CPU: give InstanceData buffer storage with GL_DYNAMIC_STORAGE_BIT, rotate every matrix with orbitAngle each frame, upload the first rockCount with Buffer::update and drop the orbit from the shader. The picture should be the same, but on a hardware GPU the CPU time in the title should now grow with the rock count in instanced mode too (on llvmpipe it grew already, because the shading runs inside the draw call, so look for the extra milliseconds instead).
  6. ★★ Let every rock tumble: add a Vec4 spin to InstanceData (axis in xyz, angular speed in w) at location 9, and rotate the rock about its own axis in the shader before aInstanceModel is applied. The rocks should tumble while they orbit; check that you multiply on the correct side.
  7. ★★★ Frustum culling on the CPU: compute each rock's world position and radius every frame, test the bounding sphere against the six planes of the view frustum (Linear Algebra chapter 12; each plane is the fourth row of proj · view plus or minus one of the first three rows, divided by the length of its xyz part), write only the visible instances into a dynamic instance buffer and draw that many. Print the count: with the camera inside the ring looking outwards, far fewer than rockCount instances should be drawn, and the frame should get faster.

Download the diff

Download the project (ZIP)

ファイル: a/CMakeLists.txt | b/CMakeLists.txt

前新
@@ -42,7 +42,8 @@ add_executable(game
42 src/gltf.cc 42 src/gltf.cc
43 src/model.cc 43 src/model.cc
44 src/framebuffer.cc 44 src/framebuffer.cc
45 src/cubemap.cc) 45 src/cubemap.cc
    46 src/gpu_timer.cc)
46 target_include_directories(game PRIVATE src external/stb external/linalg) 47 target_include_directories(game PRIVATE src external/stb external/linalg)
47 target_link_libraries(game PRIVATE glad stb_image glfw) 48 target_link_libraries(game PRIVATE glad stb_image glfw)
48   49  

ファイル: a/assets/LICENSE.txt | b/assets/LICENSE.txt

前新
@@ -11,5 +11,6 @@ textures/rug.png 敷物 / a runner rug (chapter 15)
11 textures/grass_blades.png 草の葉(アルファ付き) / grass blades with alpha (chapter 16) 11 textures/grass_blades.png 草の葉(アルファ付き) / grass blades with alpha (chapter 16)
12 textures/sky/*.png 空のキューブマップの6面 / the six sky cube-map faces (chapter 18) 12 textures/sky/*.png 空のキューブマップの6面 / the six sky cube-map faces (chapter 18)
13 models/window.glb 花箱つきの窓 / a window with a flower box (chapter 16) 13 models/window.glb 花箱つきの窓 / a window with a flower box (chapter 16)
    14 models/rock.glb 岩(インスタンシング用) / a rock for instancing (chapter 19)
14 models/crate.glb 木箱のモデル / crate model 15 models/crate.glb 木箱のモデル / crate model
15 models/diorama.glb 小さな場面 / a small diorama scene 16 models/diorama.glb 小さな場面 / a small diorama scene

ファイル: /dev/null | b/assets/models/rock.glb

新しいファイル:100644 / バイナリファイル

ファイル: a/shaders/envmap.frag | b/shaders/envmap.frag

前新
@@ -6,7 +6,14 @@ in vec3 vNormal;
6   6  
7 layout(binding = 3) uniform samplerCube uEnvironment; 7 layout(binding = 3) uniform samplerCube uEnvironment;
8   8  
9 uniform vec3 uViewPos; 9 // カメラ(ユニフォームバッファ、結合点0、std140)。使う全部のシェーダーで同じ宣言(C++ではCameraBlock)
    10 // The camera (uniform buffer, binding 0, std140). The same declaration in every shader that uses it (CameraBlock in C++)
    11 layout(std140, binding = 0) uniform Camera {
    12 mat4 uView;
    13 mat4 uProj;
    14 vec3 uViewPos; // カメラの位置(ワールド座標) / camera position (world space)
    15 float uTime; // アニメーションの時間(秒) / animation time (seconds)
    16 };
10 uniform int uEnvMode; // 0 = 反射 / reflection, 1 = 屈折 / refraction, 2 = フレネル(ガラス) / Fresnel (glass) 17 uniform int uEnvMode; // 0 = 反射 / reflection, 1 = 屈折 / refraction, 2 = フレネル(ガラス) / Fresnel (glass)
11 uniform float uIor; // 屈折率(ガラス1.52、水1.33) / index of refraction (glass 1.52, water 1.33) 18 uniform float uIor; // 屈折率(ガラス1.52、水1.33) / index of refraction (glass 1.52, water 1.33)
12 uniform vec3 uTint; // 反射・屈折の色 / colour of the reflection / refraction 19 uniform vec3 uTint; // 反射・屈折の色 / colour of the reflection / refraction

ファイル: a/shaders/phong.frag | b/shaders/phong.frag

前新
@@ -2,6 +2,7 @@
2 in vec3 vWorldPos; 2 in vec3 vWorldPos;
3 in vec3 vNormal; 3 in vec3 vNormal;
4 in vec2 vUv; 4 in vec2 vUv;
    5 in vec3 vTint; // インスタンスの色(第19章) / the instance colour (chapter 19)
5   6  
6 // 表面の性質。色はそれぞれのマップと掛け合わされる / surface properties; each colour is multiplied with its map 7 // 表面の性質。色はそれぞれのマップと掛け合わされる / surface properties; each colour is multiplied with its map
7 struct Material { 8 struct Material {
@@ -25,6 +26,9 @@ layout(binding = 2) uniform sampler2D uEmissionMap;
25 layout(binding = 3) uniform samplerCube uEnvironmentMap; 26 layout(binding = 3) uniform samplerCube uEnvironmentMap;
26 uniform vec3 uEnvironmentTint; // 空の明るさ(昼1、夜は暗く) / brightness of the sky (1 by day, dark at night) 27 uniform vec3 uEnvironmentTint; // 空の明るさ(昼1、夜は暗く) / brightness of the sky (1 by day, dark at night)
27   28  
    29 // 光の構造体。std140では各vec3が16バイトの境目から始まる:C++のLightsBlockと同じ並び(lights.hh)
    30 // The light structs. In std140 each vec3 starts on a 16-byte boundary: the same layout as LightsBlock in C++ (lights.hh)
    31  
28 // 平行光源:向きだけ / directional light: a direction only 32 // 平行光源:向きだけ / directional light: a direction only
29 struct DirectionalLight { 33 struct DirectionalLight {
30 vec3 direction; // 光が進む向き(単位ベクトル) / the direction the light travels (unit vector) 34 vec3 direction; // 光が進む向き(単位ベクトル) / the direction the light travels (unit vector)
@@ -38,13 +42,14 @@ struct PointLight {
38 vec3 attenuation; // 定数項・一次・二次 / constant, linear, quadratic 42 vec3 attenuation; // 定数項・一次・二次 / constant, linear, quadratic
39 }; 43 };
40   44  
41 // スポットライト:点光源+円錐 / spotlight: a point light + a cone 45 // スポットライト:点光源+円錐。floatはvec3の後ろの隙間に入れる(詰め物が減る)
    46 // spotlight: a point light + a cone. The floats sit in the gaps after the vec3s (less padding)
42 struct SpotLight { 47 struct SpotLight {
43 vec3 position; 48 vec3 position;
44 vec3 direction; // 円錐の軸(単位ベクトル) / the cone's axis (unit vector)    
45 vec3 color;    
46 float cosInner; // 内側の円錐の半角のコサイン / cosine of the inner cone's half angle 49 float cosInner; // 内側の円錐の半角のコサイン / cosine of the inner cone's half angle
    50 vec3 direction; // 円錐の軸(単位ベクトル) / the cone's axis (unit vector)
47 float cosOuter; // 外側の円錐の半角のコサイン / cosine of the outer cone's half angle 51 float cosOuter; // 外側の円錐の半角のコサイン / cosine of the outer cone's half angle
    52 vec3 color;
48 vec3 attenuation; 53 vec3 attenuation;
49 }; 54 };
50   55  
@@ -52,14 +57,24 @@ struct SpotLight {
52 #define MAX_POINT_LIGHTS 8 57 #define MAX_POINT_LIGHTS 8
53 #define MAX_SPOT_LIGHTS 4 58 #define MAX_SPOT_LIGHTS 4
54   59  
55 uniform DirectionalLight uDirLight; 60 // 全部の光(ユニフォームバッファ、結合点1) / all lights (uniform buffer, binding 1)
56 uniform PointLight uPointLights[MAX_POINT_LIGHTS]; 61 layout(std140, binding = 1) uniform Lights {
57 uniform int uPointLightCount; // 使っている数 / how many are in use 62 DirectionalLight uDirLight;
58 uniform SpotLight uSpotLights[MAX_SPOT_LIGHTS]; 63 PointLight uPointLights[MAX_POINT_LIGHTS];
59 uniform int uSpotLightCount; 64 SpotLight uSpotLights[MAX_SPOT_LIGHTS];
    65 vec3 uAmbient; // 環境光の色と明るさ / ambient light colour and brightness
    66 int uPointLightCount; // 使っている数 / how many are in use
    67 int uSpotLightCount;
    68 };
60   69  
61 uniform vec3 uAmbient; // 環境光の色と明るさ / ambient light colour and brightness 70 // カメラ(ユニフォームバッファ、結合点0、std140)。使う全部のシェーダーで同じ宣言(C++ではCameraBlock)
62 uniform vec3 uViewPos; // カメラの位置(ワールド座標) / camera position (world space) 71 // The camera (uniform buffer, binding 0, std140). The same declaration in every shader that uses it (CameraBlock in C++)
    72 layout(std140, binding = 0) uniform Camera {
    73 mat4 uView;
    74 mat4 uProj;
    75 vec3 uViewPos; // カメラの位置(ワールド座標) / camera position (world space)
    76 float uTime; // アニメーションの時間(秒) / animation time (seconds)
    77 };
63   78  
64 // 0 = 全部、1 = 環境光、2 = 拡散反射、3 = 鏡面反射、4 = 発光、5 = 法線 79 // 0 = 全部、1 = 環境光、2 = 拡散反射、3 = 鏡面反射、4 = 発光、5 = 法線
65 // 0 = everything, 1 = ambient, 2 = diffuse, 3 = specular, 4 = emission, 5 = normals 80 // 0 = everything, 1 = ambient, 2 = diffuse, 3 = specular, 4 = emission, 5 = normals
@@ -112,7 +127,7 @@ void main() {
112 // 両面のマテリアルを裏から見ているなら、法線は裏を向く / seen from behind, a double-sided surface's normal points the other way 127 // 両面のマテリアルを裏から見ているなら、法線は裏を向く / seen from behind, a double-sided surface's normal points the other way
113 if (uMaterial.doubleSided && !gl_FrontFacing) s.normal = -s.normal; 128 if (uMaterial.doubleSided && !gl_FrontFacing) s.normal = -s.normal;
114 s.view = normalize(uViewPos - vWorldPos); 129 s.view = normalize(uViewPos - vWorldPos);
115 s.diffuse = uMaterial.diffuse * base.rgb; 130 s.diffuse = uMaterial.diffuse * vTint * base.rgb;
116 s.specular = uMaterial.specular * texture(uSpecularMap, vUv).rgb; 131 s.specular = uMaterial.specular * texture(uSpecularMap, vUv).rgb;
117 s.shininess = uMaterial.shininess; 132 s.shininess = uMaterial.shininess;
118 vec3 emission = uMaterial.emission * texture(uEmissionMap, vUv).rgb; 133 vec3 emission = uMaterial.emission * texture(uEmissionMap, vUv).rgb;

ファイル: a/shaders/phong.vert | b/shaders/phong.vert

前新
@@ -3,20 +3,32 @@ layout(location = 0) in vec3 aPosition;
3 layout(location = 1) in vec3 aNormal; // 面の向き(モデル座標) / which way the surface faces (model space) 3 layout(location = 1) in vec3 aNormal; // 面の向き(モデル座標) / which way the surface faces (model space)
4 layout(location = 2) in vec2 aUv; 4 layout(location = 2) in vec2 aUv;
5   5  
    6 // カメラ(ユニフォームバッファ、結合点0、std140)。使う全部のシェーダーで同じ宣言(C++ではCameraBlock)
    7 // The camera (uniform buffer, binding 0, std140). The same declaration in every shader that uses it (CameraBlock in C++)
    8 layout(std140, binding = 0) uniform Camera {
    9 mat4 uView;
    10 mat4 uProj;
    11 vec3 uViewPos; // カメラの位置(ワールド座標) / camera position (world space)
    12 float uTime; // アニメーションの時間(秒) / animation time (seconds)
    13 };
    14  
6 uniform mat4 uModel; 15 uniform mat4 uModel;
7 uniform mat4 uView;    
8 uniform mat4 uProj;    
9 uniform mat3 uNormalMatrix; // 法線をワールド座標へ(モデル行列の逆行列の転置) / normals to world space (inverse transpose of uModel) 16 uniform mat3 uNormalMatrix; // 法線をワールド座標へ(モデル行列の逆行列の転置) / normals to world space (inverse transpose of uModel)
10   17  
11 // ライティングはワールド座標で計算する / lighting is computed in world space 18 // ライティングはワールド座標で計算する / lighting is computed in world space
12 out vec3 vWorldPos; 19 out vec3 vWorldPos;
13 out vec3 vNormal; 20 out vec3 vNormal;
14 out vec2 vUv; 21 out vec2 vUv;
    22 // インスタンスごとの色(第19章)。インスタンシングでないときはこのユニフォーム(既定値は白)
    23 // The per-instance colour (chapter 19). Without instancing it comes from this uniform (white by default)
    24 uniform vec3 uTint = vec3(1.0);
    25 out vec3 vTint;
15   26  
16 void main() { 27 void main() {
17 vec4 world = uModel * vec4(aPosition, 1.0); 28 vec4 world = uModel * vec4(aPosition, 1.0);
18 vWorldPos = world.xyz; 29 vWorldPos = world.xyz;
19 vNormal = uNormalMatrix * aNormal; // 正規化はフラグメントシェーダーで / normalized in the fragment shader 30 vNormal = uNormalMatrix * aNormal; // 正規化はフラグメントシェーダーで / normalized in the fragment shader
20 vUv = aUv; 31 vUv = aUv;
    32 vTint = uTint;
21 gl_Position = uProj * uView * world; 33 gl_Position = uProj * uView * world;
22 } 34 }

ファイル: /dev/null | b/shaders/phong_instanced.vert

前新
@@ -0,0 +1,49 @@
    1 #version 460 core
    2 // インスタンシング用のphong.vert:インスタンスごとの行列と色を頂点属性で受け取る(フラグメントシェーダーはphong.frag)
    3 // phong.vert for instancing: the per-instance matrix and colour arrive as vertex attributes (fragment shader: phong.frag)
    4 layout(location = 0) in vec3 aPosition;
    5 layout(location = 1) in vec3 aNormal;
    6 layout(location = 2) in vec2 aUv;
    7 // location 3は接線(第22章) / location 3 is the tangent (chapter 22)
    8 layout(location = 4) in mat4 aInstanceModel; // mat4はlocationを4つ使う(4〜7) / a mat4 takes four locations (4..7)
    9 layout(location = 8) in vec3 aInstanceColor;
    10  
    11 // カメラ(ユニフォームバッファ、結合点0、std140)。使う全部のシェーダーで同じ宣言(C++ではCameraBlock)
    12 // The camera (uniform buffer, binding 0, std140). The same declaration in every shader that uses it (CameraBlock in C++)
    13 layout(std140, binding = 0) uniform Camera {
    14 mat4 uView;
    15 mat4 uProj;
    16 vec3 uViewPos; // カメラの位置(ワールド座標) / camera position (world space)
    17 float uTime; // アニメーションの時間(秒) / animation time (seconds)
    18 };
    19  
    20 uniform mat4 uModel; // モデルの中のノードの行列 / the node's matrix inside the model
    21 uniform mat3 uNormalMatrix; // その法線行列 / its normal matrix
    22 uniform float uOrbitSpeed; // 環の公転の速さ(半径8 mで、ラジアン毎秒) / orbit speed of the ring (rad/s at radius 8 m)
    23  
    24 out vec3 vWorldPos;
    25 out vec3 vNormal;
    26 out vec2 vUv;
    27 out vec3 vTint;
    28  
    29 // Y軸周りの回転 / rotation about the Y axis
    30 mat4 rotationY(float a) {
    31 float c = cos(a), s = sin(a);
    32 return mat4(c, 0.0, -s, 0.0, 0.0, 1.0, 0.0, 0.0, s, 0.0, c, 0.0, 0.0, 0.0, 0.0, 1.0);
    33 }
    34  
    35 void main() {
    36 // 公転:内側ほど速い(ケプラーの法則:角速度 ∝ 半径^-1.5)。C++のorbitAngle()と同じ式
    37 // Orbit: inner rocks are faster (Kepler: angular speed ∝ radius^-1.5). The same formula as orbitAngle() in C++
    38 float radius = length(aInstanceModel[3].xz);
    39 mat4 orbit = rotationY(uTime * uOrbitSpeed * pow(8.0 / radius, 1.5));
    40 mat4 model = orbit * aInstanceModel * uModel;
    41 vec4 world = model * vec4(aPosition, 1.0);
    42 vWorldPos = world.xyz;
    43 // 岩の拡大縮小は一様なので、法線は行列の3×3で回すだけで良い(長さはphong.fragで正規化)
    44 // The rocks are scaled uniformly, so the normal can simply be rotated by the 3×3 part (phong.frag normalizes it)
    45 vNormal = mat3(orbit * aInstanceModel) * (uNormalMatrix * aNormal);
    46 vUv = aUv;
    47 vTint = aInstanceColor;
    48 gl_Position = uProj * uView * world;
    49 }

ファイル: a/shaders/skybox.vert | b/shaders/skybox.vert

前新
@@ -3,8 +3,14 @@
3 // The sky box: a cube around the camera, textured from the inside by direction 3 // The sky box: a cube around the camera, textured from the inside by direction
4 layout(location = 0) in vec3 aPosition; // makeCube()の頂点(±0.5) / makeCube()'s vertices (±0.5) 4 layout(location = 0) in vec3 aPosition; // makeCube()の頂点(±0.5) / makeCube()'s vertices (±0.5)
5   5  
6 uniform mat4 uView; 6 // カメラ(ユニフォームバッファ、結合点0、std140)。使う全部のシェーダーで同じ宣言(C++ではCameraBlock)
7 uniform mat4 uProj; 7 // The camera (uniform buffer, binding 0, std140). The same declaration in every shader that uses it (CameraBlock in C++)
    8 layout(std140, binding = 0) uniform Camera {
    9 mat4 uView;
    10 mat4 uProj;
    11 vec3 uViewPos; // カメラの位置(ワールド座標) / camera position (world space)
    12 float uTime; // アニメーションの時間(秒) / animation time (seconds)
    13 };
8   14  
9 out vec3 vDirection; // キューブマップを引く方向 / the direction to look up the cube map with 15 out vec3 vDirection; // キューブマップを引く方向 / the direction to look up the cube map with
10   16  

ファイル: a/shaders/unlit.vert | b/shaders/unlit.vert

前新
@@ -1,9 +1,16 @@
1 #version 460 core 1 #version 460 core
2 layout(location = 0) in vec3 aPosition; 2 layout(location = 0) in vec3 aPosition;
3   3  
    4 // カメラ(ユニフォームバッファ、結合点0、std140)。使う全部のシェーダーで同じ宣言(C++ではCameraBlock)
    5 // The camera (uniform buffer, binding 0, std140). The same declaration in every shader that uses it (CameraBlock in C++)
    6 layout(std140, binding = 0) uniform Camera {
    7 mat4 uView;
    8 mat4 uProj;
    9 vec3 uViewPos; // カメラの位置(ワールド座標) / camera position (world space)
    10 float uTime; // アニメーションの時間(秒) / animation time (seconds)
    11 };
    12  
4 uniform mat4 uModel; 13 uniform mat4 uModel;
5 uniform mat4 uView;    
6 uniform mat4 uProj;    
7   14  
8 void main() { 15 void main() {
9 gl_Position = uProj * uView * uModel * vec4(aPosition, 1.0); 16 gl_Position = uProj * uView * uModel * vec4(aPosition, 1.0);

ファイル: a/src/buffer.cc | b/src/buffer.cc

前新
@@ -7,6 +7,10 @@ Buffer::Buffer(const void *data, GLsizeiptr byteCount, GLbitfield flags) : bytes
7 glNamedBufferStorage(handle, byteCount, data, flags); 7 glNamedBufferStorage(handle, byteCount, data, flags);
8 } 8 }
9   9  
    10 void Buffer::update(const void *data, GLsizeiptr byteCount, GLintptr offset) const {
    11 glNamedBufferSubData(handle, offset, byteCount, data);
    12 }
    13  
10 Buffer::~Buffer() { 14 Buffer::~Buffer() {
11 if (handle) glDeleteBuffers(1, &handle); 15 if (handle) glDeleteBuffers(1, &handle);
12 } 16 }

ファイル: a/src/buffer.hh | b/src/buffer.hh

前新
@@ -18,6 +18,13 @@ public:
18 Buffer(Buffer &&other) noexcept; 18 Buffer(Buffer &&other) noexcept;
19 Buffer &operator=(Buffer &&other) noexcept; 19 Buffer &operator=(Buffer &&other) noexcept;
20   20  
    21 // 中身の一部を書き換える(作るときにGL_DYNAMIC_STORAGE_BITが必要) / replaces part of the contents
    22 // (needs GL_DYNAMIC_STORAGE_BIT at creation)
    23 void update(const void *data, GLsizeiptr byteCount, GLintptr offset = 0) const;
    24 // 番号付きの結合点に繋ぐ(ユニフォームバッファなど、第19章) / attaches to an indexed binding point
    25 // (uniform buffers etc., chapter 19)
    26 void bindBase(GLenum target, GLuint index) const { glBindBufferBase(target, index, handle); }
    27  
21 GLuint id() const { return handle; } 28 GLuint id() const { return handle; }
22 GLsizeiptr size() const { return bytes; } 29 GLsizeiptr size() const { return bytes; }
23   30  

ファイル: /dev/null | b/src/gpu_timer.cc

前新
@@ -0,0 +1,38 @@
    1 #include "gpu_timer.hh"
    2  
    3 GpuTimer::GpuTimer() { glCreateQueries(GL_TIME_ELAPSED, kQueries, queries); }
    4  
    5 GpuTimer::~GpuTimer() { glDeleteQueries(kQueries, queries); }
    6  
    7 void GpuTimer::begin() {
    8 // 使おうとしているクエリの結果がまだなら、今回は測らない(待つとCPUとGPUが同期して遅くなる)
    9 // If the query we would use still has no result, skip this measurement (waiting would stall CPU and GPU)
    10 latestMs();
    11 if (pending[next]) return;
    12 glBeginQuery(GL_TIME_ELAPSED, queries[next]);
    13 running = true;
    14 }
    15  
    16 void GpuTimer::end() {
    17 if (!running) return;
    18 glEndQuery(GL_TIME_ELAPSED);
    19 pending[next] = true;
    20 next = (next + 1) % kQueries;
    21 running = false;
    22 }
    23  
    24 std::optional<double> GpuTimer::latestMs() {
    25 // 古い順に、届いた結果を読む / read the results that have arrived, oldest first
    26 for (int k = 0; k < kQueries; ++k) {
    27 int i = (next + k) % kQueries;
    28 if (!pending[i]) continue;
    29 GLint available = 0;
    30 glGetQueryObjectiv(queries[i], GL_QUERY_RESULT_AVAILABLE, &available);
    31 if (!available) continue;
    32 GLuint64 ns = 0;
    33 glGetQueryObjectui64v(queries[i], GL_QUERY_RESULT, &ns); // ナノ秒 / nanoseconds
    34 latest = static_cast<double>(ns) / 1.0e6;
    35 pending[i] = false;
    36 }
    37 return latest;
    38 }

ファイル: /dev/null | b/src/gpu_timer.hh

前新
@@ -0,0 +1,33 @@
    1 // GPUの時間を測る:タイマークエリ(GL_TIME_ELAPSED) / measuring GPU time with timer queries (GL_TIME_ELAPSED)
    2 #pragma once
    3  
    4 #include <glad/glad.h>
    5  
    6 #include <optional>
    7  
    8 // begin()〜end()の間のコマンドをGPUが実行するのにかかった時間。結果は数フレーム後に届くので、クエリを
    9 // 何個か順番に使い、届いたものから読む(待たない)。RAII、コピー不可・移動不可。
    10 // How long the GPU took to execute the commands between begin() and end(). The result arrives a few frames
    11 // later, so several queries are used in turn and the ones that have arrived are read (no waiting).
    12 // RAII, non-copyable, non-movable.
    13 class GpuTimer {
    14 public:
    15 GpuTimer();
    16 ~GpuTimer();
    17 GpuTimer(const GpuTimer &) = delete;
    18 GpuTimer &operator=(const GpuTimer &) = delete;
    19  
    20 void begin();
    21 void end();
    22 // 一番新しく届いた結果(ミリ秒)。まだ一つも届いていなければstd::nullopt
    23 // The most recent result that has arrived (milliseconds). std::nullopt if none has arrived yet
    24 std::optional<double> latestMs();
    25  
    26 private:
    27 static constexpr int kQueries = 4; // 4フレーム分まで遅れて良い / results may lag up to 4 frames
    28 GLuint queries[kQueries] = {};
    29 bool pending[kQueries] = {};
    30 int next = 0;
    31 bool running = false;
    32 std::optional<double> latest;
    33 };

ファイル: a/src/lights.cc | b/src/lights.cc

前新
@@ -2,14 +2,12 @@
2   2  
3 #include <cmath> 3 #include <cmath>
4 #include <cstdio> 4 #include <cstdio>
5 #include <format>    
6   5  
7 void LightSet::apply(const Shader &shader) const { 6 LightsBlock LightSet::toBlock() const {
8 shader.set("uAmbient", ambient); 7 LightsBlock b{}; // 全部0(詰め物も) / all zero (the padding too)
9 shader.set("uDirLight.direction", normalize(directional.direction)); 8 b.directional.direction = normalize(directional.direction);
10 shader.set("uDirLight.color", directional.color); 9 b.directional.color = directional.color;
11   10  
12 // 配列の要素のメンバーは「名前[番号].メンバー」で設定する / array elements: "name[index].member"    
13 int pointCount = static_cast<int>(points.size()); 11 int pointCount = static_cast<int>(points.size());
14 if (pointCount > kMaxPointLights) { 12 if (pointCount > kMaxPointLights) {
15 fprintf(stderr, "点光源が多すぎる / too many point lights: %d (max %d)\n", pointCount, kMaxPointLights); 13 fprintf(stderr, "点光源が多すぎる / too many point lights: %d (max %d)\n", pointCount, kMaxPointLights);
@@ -17,11 +15,11 @@ void LightSet::apply(const Shader &shader) const {
17 } 15 }
18 for (int i = 0; i < pointCount; ++i) { 16 for (int i = 0; i < pointCount; ++i) {
19 const PointLight &p = points[static_cast<size_t>(i)]; 17 const PointLight &p = points[static_cast<size_t>(i)];
20 shader.set(std::format("uPointLights[{}].position", i).c_str(), p.position); 18 b.points[i].position = p.position;
21 shader.set(std::format("uPointLights[{}].color", i).c_str(), p.color); 19 b.points[i].color = p.color;
22 shader.set(std::format("uPointLights[{}].attenuation", i).c_str(), p.attenuation); 20 b.points[i].attenuation = p.attenuation;
23 } 21 }
24 shader.set("uPointLightCount", pointCount); 22 b.pointCount = pointCount;
25   23  
26 int spotCount = static_cast<int>(spots.size()); 24 int spotCount = static_cast<int>(spots.size());
27 if (spotCount > kMaxSpotLights) { 25 if (spotCount > kMaxSpotLights) {
@@ -30,14 +28,16 @@ void LightSet::apply(const Shader &shader) const {
30 } 28 }
31 for (int i = 0; i < spotCount; ++i) { 29 for (int i = 0; i < spotCount; ++i) {
32 const SpotLight &s = spots[static_cast<size_t>(i)]; 30 const SpotLight &s = spots[static_cast<size_t>(i)];
33 shader.set(std::format("uSpotLights[{}].position", i).c_str(), s.position); 31 b.spots[i].position = s.position;
34 shader.set(std::format("uSpotLights[{}].direction", i).c_str(), normalize(s.direction)); 32 b.spots[i].direction = normalize(s.direction);
35 shader.set(std::format("uSpotLights[{}].color", i).c_str(), s.color); 33 b.spots[i].color = s.color;
36 // シェーダーは角度ではなくコサインを比べる(acosを毎ピクセル計算しないため) 34 // シェーダーは角度ではなくコサインを比べる(acosを毎ピクセル計算しないため)
37 // The shader compares cosines, not angles (so it does not need acos for every pixel) 35 // The shader compares cosines, not angles (so it does not need acos for every pixel)
38 shader.set(std::format("uSpotLights[{}].cosInner", i).c_str(), std::cos(s.innerAngle)); 36 b.spots[i].cosInner = std::cos(s.innerAngle);
39 shader.set(std::format("uSpotLights[{}].cosOuter", i).c_str(), std::cos(s.outerAngle)); 37 b.spots[i].cosOuter = std::cos(s.outerAngle);
40 shader.set(std::format("uSpotLights[{}].attenuation", i).c_str(), s.attenuation); 38 b.spots[i].attenuation = s.attenuation;
41 } 39 }
42 shader.set("uSpotLightCount", spotCount); 40 b.spotCount = spotCount;
    41 b.ambient = ambient;
    42 return b;
43 } 43 }

ファイル: a/src/lights.hh | b/src/lights.hh

前新
@@ -3,6 +3,7 @@
3   3  
4 #include "mathx.hh" 4 #include "mathx.hh"
5 #include "shader.hh" 5 #include "shader.hh"
    6 #include "uniforms.hh"
6   7  
7 #include <vector> 8 #include <vector>
8   9  
@@ -42,6 +43,61 @@ struct SpotLight {
42 Vec3 attenuation = kLongRange; 43 Vec3 attenuation = kLongRange;
43 }; 44 };
44   45  
    46 // ユニフォームバッファの中の光(std140の並び、第19章)。GLSLのLightsブロックと同じ:
    47 // The lights inside the uniform buffer (std140 layout, chapter 19). Same as the GLSL Lights block:
    48 // struct DirectionalLight { vec3 direction; vec3 color; }; // 32 bytes
    49 // struct PointLight { vec3 position; vec3 color; vec3 attenuation; }; // 48 bytes
    50 // struct SpotLight { vec3 position; float cosInner; vec3 direction; float cosOuter;
    51 // vec3 color; vec3 attenuation; }; // 64 bytes
    52 // layout(std140, binding = 1) uniform Lights {
    53 // DirectionalLight uDirLight; // offset 0
    54 // PointLight uPointLights[MAX_POINT_LIGHTS]; // offset 32 (8 × 48)
    55 // SpotLight uSpotLights[MAX_SPOT_LIGHTS]; // offset 416 (4 × 64)
    56 // vec3 uAmbient; // offset 672
    57 // int uPointLightCount; // offset 684
    58 // int uSpotLightCount; // offset 688
    59 // }; // 692 → 704 bytes (a multiple of 16)
    60 struct DirectionalLightStd140 {
    61 Vec3 direction;
    62 float pad0;
    63 Vec3 color;
    64 float pad1;
    65 };
    66 struct PointLightStd140 {
    67 Vec3 position;
    68 float pad0;
    69 Vec3 color;
    70 float pad1;
    71 Vec3 attenuation;
    72 float pad2;
    73 };
    74 struct SpotLightStd140 {
    75 Vec3 position;
    76 float cosInner; // vec3の後ろの隙間に入る / fits in the gap after the vec3
    77 Vec3 direction;
    78 float cosOuter;
    79 Vec3 color;
    80 float pad0;
    81 Vec3 attenuation;
    82 float pad1;
    83 };
    84 struct LightsBlock {
    85 DirectionalLightStd140 directional;
    86 PointLightStd140 points[kMaxPointLights];
    87 SpotLightStd140 spots[kMaxSpotLights];
    88 Vec3 ambient;
    89 int pointCount;
    90 int spotCount;
    91 int pad[3];
    92 };
    93 static_assert(sizeof(DirectionalLightStd140) == 32 && sizeof(PointLightStd140) == 48 && sizeof(SpotLightStd140) == 64);
    94 static_assert(offsetof(LightsBlock, points) == 32);
    95 static_assert(offsetof(LightsBlock, spots) == 416);
    96 static_assert(offsetof(LightsBlock, ambient) == 672);
    97 static_assert(offsetof(LightsBlock, pointCount) == 684);
    98 static_assert(offsetof(LightsBlock, spotCount) == 688);
    99 static_assert(sizeof(LightsBlock) == 704);
    100  
45 // シーンの全部の光 / all the lights of a scene 101 // シーンの全部の光 / all the lights of a scene
46 struct LightSet { 102 struct LightSet {
47 Vec3 ambient = {0.05f, 0.05f, 0.05f}; 103 Vec3 ambient = {0.05f, 0.05f, 0.05f};
@@ -49,7 +105,8 @@ struct LightSet {
49 std::vector<PointLight> points; 105 std::vector<PointLight> points;
50 std::vector<SpotLight> spots; 106 std::vector<SpotLight> spots;
51   107  
52 // 全部の光をシェーダーのユニフォームに設定する。最大数を超えた分は使わない。 108 // ユニフォームバッファに書く形にする(第19章。以前のapply(shader)の代わり)。最大数を超えた分は使わない。
53 // Sets all lights as shader uniforms. Lights beyond the maximum count are ignored. 109 // Converts to the uniform-buffer layout (chapter 19; replaces the former apply(shader)). Lights beyond the
54 void apply(const Shader &shader) const; 110 // maximum count are ignored.
    111 LightsBlock toBlock() const;
55 }; 112 };

ファイル: a/src/main.cc | b/src/main.cc

前新
@@ -1,5 +1,5 @@
1 // 第18章:キューブマップ 1 // 第19章:ユニフォームバッファとインスタンシング
2 // Chapter 18: cubemaps 2 // Chapter 19: uniform buffers and instancing
3 // 3 //
4 // 操作 / Controls: 4 // 操作 / Controls:
5 // WASD 前後左右に移動 / move forward, back, left, right 5 // WASD 前後左右に移動 / move forward, back, left, right
@@ -7,24 +7,25 @@
7 // Shift 速く動く / move faster 7 // Shift 速く動く / move faster
8 // マウス / mouse 向きを変える(FPS)、左ドラッグで回る(オービット) / look around (FPS), drag with the left button to orbit 8 // マウス / mouse 向きを変える(FPS)、左ドラッグで回る(オービット) / look around (FPS), drag with the left button to orbit
9 // ホイール / wheel ズーム / zoom 9 // ホイール / wheel ズーム / zoom
10 // M 手前の3つ:いろいろ → 全部反射 → 全部屈折 → 全部フレネル 10 // I 岩:インスタンシング(描画呼び出し1回) ⇔ 一つずつ(岩の数だけ呼び出し)
11 // the three objects in front: mixed → all reflection → all refraction → all Fresnel 11 // rocks: instancing (one draw call) ⇔ one by one (one draw call per rock)
12 // K 空(スカイボックス)のオン・オフ / sky box on / off 12 // = / - 岩の数を倍に・半分に(250〜64000) / double / halve the number of rocks (250..64000)
13 // X 継ぎ目のないキューブマップの補間(GL_TEXTURE_CUBE_MAP_SEAMLESS)のオン・オフ    
14 // seamless cube-map filtering (GL_TEXTURE_CUBE_MAP_SEAMLESS) on / off    
15 // 1〜6 効果:なし / 反転 / グレースケール / シャープ / ぼかし / エッジ検出 13 // 1〜6 効果:なし / 反転 / グレースケール / シャープ / ぼかし / エッジ検出
16 // effect: none / invert / grayscale / sharpen / blur / edge detection 14 // effect: none / invert / grayscale / sharpen / blur / edge detection
17 // C FPS ⇔ オービットカメラ / FPS ⇔ orbit camera 15 // C FPS ⇔ オービットカメラ / FPS ⇔ orbit camera
18 // V 表示:全部 → 環境光 → 拡散 → 鏡面 → 発光 → 法線 / view: all → ambient → diffuse → specular → emission → normals 16 // V 表示:全部 → 環境光 → 拡散 → 鏡面 → 発光 → 法線 / view: all → ambient → diffuse → specular → emission → normals
19 // N 昼 ⇔ 夜 / day ⇔ night 17 // N 昼 ⇔ 夜 / day ⇔ night
20 // F 懐中電灯のオン・オフ / flashlight on / off 18 // F 懐中電灯のオン・オフ / flashlight on / off
21 // P 風車と金色の木箱を止める・回す / pause / resume the windmill and the golden crate 19 // P 風車と岩の環を止める・動かす / pause / resume the windmill and the ring of rocks
22 // Tab カーソルのキャプチャ切り替え / toggle cursor capture 20 // Tab カーソルのキャプチャ切り替え / toggle cursor capture
23 // R シェーダーを読み直す / reload the shaders 21 // R シェーダーを読み直す / reload the shaders
24 // Esc 終了 / quit 22 // Esc 終了 / quit
    23 //
    24 // 時間はウィンドウのタイトルと標準出力に出る(60フレームごと) / timings go to the window title and stdout (every 60 frames)
25 #include "camera.hh" 25 #include "camera.hh"
26 #include "cubemap.hh" 26 #include "cubemap.hh"
27 #include "framebuffer.hh" 27 #include "framebuffer.hh"
    28 #include "gpu_timer.hh"
28 #include "lights.hh" 29 #include "lights.hh"
29 #include "material.hh" 30 #include "material.hh"
30 #include "mathx.hh" 31 #include "mathx.hh"
@@ -33,49 +34,65 @@
33 #include "shader.hh" 34 #include "shader.hh"
34 #include "shapes.hh" 35 #include "shapes.hh"
35 #include "texture.hh" 36 #include "texture.hh"
    37 #include "uniforms.hh"
36 #include "window.hh" 38 #include "window.hh"
37   39  
38 #include <algorithm> 40 #include <chrono>
39 #include <cmath> 41 #include <cmath>
40 #include <cstdint> 42 #include <cstdint>
41 #include <cstdio> 43 #include <cstdio>
42 #include <optional> 44 #include <optional>
43 #include <vector> 45 #include <vector>
44   46  
45 // 物を置く場所:位置(底の中心)とY軸周りの回転 / where things go: position (bottom centre) and yaw    
46 struct Placement { 47 struct Placement {
47 Vec3 position; 48 Vec3 position;
48 float angle; 49 float angle;
49 }; 50 };
50   51  
51 static const Placement kCrates[] = {    
52 {{5.5f, 0.0f, 1.5f}, 0.4f}, {{6.3f, 0.0f, 2.6f}, -0.3f}, {{5.9f, 1.0f, 2.0f}, 0.1f},    
53 {{-6.0f, 0.0f, -1.0f}, 0.8f}, {{-5.2f, 0.0f, 3.5f}, -0.6f},    
54 };    
55      
56 // 手前の環境マッピングの物:球二つと、木箱のモデル / the environment-mapped objects in front: two spheres and the    
57 // crate model    
58 enum EnvMode { kReflect = 0, kRefract = 1, kFresnel = 2 };    
59 struct EnvObject {    
60 Vec3 position;    
61 int mode; // 「いろいろ」のときのモード / the mode in "mixed"    
62 Vec3 tint; // 反射の色(金属の色) / reflection colour (the metal's colour)    
63 };    
64 static const EnvObject kEnvObjects[] = {    
65 {{-2.8f, 0.75f, 7.0f}, kFresnel, {1.0f, 1.0f, 1.0f}}, // ガラスの球 / glass sphere    
66 {{0.0f, 1.0f, 7.6f}, kReflect, {0.95f, 0.8f, 0.55f}}, // 金色の木箱(宙に浮いて回る) / a golden crate (hovers, tumbling)    
67 {{2.8f, 0.75f, 7.0f}, kReflect, {0.95f, 0.95f, 0.97f}}, // クロムの球 / chrome sphere    
68 };    
69      
70 static const char *const kViewModeNames[] = {"all", "ambient", "diffuse", "specular", "emission", "normals"}; 52 static const char *const kViewModeNames[] = {"all", "ambient", "diffuse", "specular", "emission", "normals"};
71 static const char *const kEffectNames[] = {"none", "invert", "grayscale", "sharpen", "blur", "edge detection"}; 53 static const char *const kEffectNames[] = {"none", "invert", "grayscale", "sharpen", "blur", "edge detection"};
72 static const char *const kEnvModeNames[] = {"mixed", "all reflection", "all refraction", "all Fresnel"}; 54  
    55 constexpr int kMaxRocks = 64000;
    56 constexpr float kOrbitSpeed = 0.25f; // 半径8 mでの公転の角速度(ラジアン毎秒) / orbital angular speed at radius 8 m (rad/s)
73   57  
74 static float random01(std::uint32_t &state) { 58 static float random01(std::uint32_t &state) {
75 state = state * 1664525u + 1013904223u; 59 state = state * 1664525u + 1013904223u;
76 return static_cast<float>(state >> 8) / 16777216.0f; 60 return static_cast<float>(state >> 8) / 16777216.0f;
77 } 61 }
78   62  
    63 // 公転の角度:内側ほど速い(ケプラー:角速度 ∝ 半径^-1.5)。phong_instanced.vertと同じ式
    64 // The orbit angle: inner rocks move faster (Kepler: angular speed ∝ radius^-1.5). Same formula as phong_instanced.vert
    65 static float orbitAngle(const Mat4 &instance, float time) {
    66 float radius = std::sqrt(instance.c[3].x * instance.c[3].x + instance.c[3].z * instance.c[3].z);
    67 return time * kOrbitSpeed * std::pow(8.0f / radius, 1.5f);
    68 }
    69  
    70 // 浮島の周りの岩の環。位置・回転・大きさ・色は決まった乱数で / the ring of rocks around the floating island;
    71 // position, rotation, size and colour from a fixed pseudo-random sequence
    72 static std::vector<InstanceData> makeRing() {
    73 std::vector<InstanceData> rocks;
    74 rocks.reserve(kMaxRocks);
    75 std::uint32_t seed = 19;
    76 for (int i = 0; i < kMaxRocks; ++i) {
    77 // 半径:二つの乱数の平均で真ん中を濃く / radius: the mean of two randoms makes the middle denser
    78 float radius = 8.0f + 6.5f * 0.5f * (random01(seed) + random01(seed));
    79 float angle = 2.0f * PI * random01(seed);
    80 float height = 2.0f + 0.45f * (random01(seed) + random01(seed) + random01(seed) - 1.5f) / 1.5f;
    81 float u = random01(seed);
    82 float size = 0.08f + 0.4f * u * u * u; // 小さい岩が多い / mostly small rocks
    83 Vec3 axis = normalize(Vec3{random01(seed) - 0.5f, random01(seed) - 0.5f, random01(seed) - 0.5f});
    84 float spin = 2.0f * PI * random01(seed);
    85 float shade = 0.7f + 0.45f * random01(seed);
    86 float warm = 0.12f * (random01(seed) - 0.5f);
    87 InstanceData d;
    88 d.model = translate({radius * std::cos(angle), height, radius * std::sin(angle)}) * rotate(axis, spin) *
    89 scale({size, size, size});
    90 d.color = {shade + warm, shade, shade - warm};
    91 rocks.push_back(d);
    92 }
    93 return rocks;
    94 }
    95  
79 static std::vector<Placement> makeGrass() { 96 static std::vector<Placement> makeGrass() {
80 std::vector<Placement> grass; 97 std::vector<Placement> grass;
81 std::uint32_t seed = 16; 98 std::uint32_t seed = 16;
@@ -87,37 +104,32 @@ static std::vector<Placement> makeGrass() {
87 for (Vec3 q : avoid) ok = ok && length(Vec3{p.x - q.x, 0, p.z - q.z}) > 1.1f; 104 for (Vec3 q : avoid) ok = ok && length(Vec3{p.x - q.x, 0, p.z - q.z}) > 1.1f;
88 if (ok) grass.push_back({p, 2.0f * PI * random01(seed)}); 105 if (ok) grass.push_back({p, 2.0f * PI * random01(seed)});
89 } 106 }
90 const Placement front[] = {{{1.5f, 0, 6.2f}, 0.3f}, {{-4.0f, 0, 7.6f}, 1.2f}, {{3.9f, 0, 5.4f}, 2.0f},    
91 {{1.4f, 0, 8.9f}, 0.7f}, {{-1.6f, 0, 8.6f}, 2.6f}};    
92 for (const Placement &p : front) grass.push_back(p);    
93 return grass; 107 return grass;
94 } 108 }
95   109  
96 // 一つのカメラから見た場面を描くのに必要なもの / what is needed to draw the scene from one camera    
97 struct View {    
98 Mat4 view, proj;    
99 Vec3 position;    
100 };    
101      
102 int main() { 110 int main() {
103 Window window; 111 Window window;
104 if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 18")) return 1; 112 if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 19")) return 1;
105   113  
106 std::optional<Shader> phong = Shader::load("shaders/phong.vert", "shaders/phong.frag"); 114 std::optional<Shader> phong = Shader::load("shaders/phong.vert", "shaders/phong.frag");
107 std::optional<Shader> post = Shader::load("shaders/post.vert", "shaders/post.frag"); 115 // インスタンシング用:頂点シェーダーだけ違う / for instancing: only the vertex shader differs
    116 std::optional<Shader> rocksShader = Shader::load("shaders/phong_instanced.vert", "shaders/phong.frag");
108 std::optional<Shader> skybox = Shader::load("shaders/skybox.vert", "shaders/skybox.frag"); 117 std::optional<Shader> skybox = Shader::load("shaders/skybox.vert", "shaders/skybox.frag");
109 // 環境マッピング:頂点シェーダーはphongと同じ(ワールド座標の位置と法線) / environment mapping: the same vertex 118 std::optional<Shader> post = Shader::load("shaders/post.vert", "shaders/post.frag");
110 // shader as phong (world-space position and normal)    
111 std::optional<Shader> envmap = Shader::load("shaders/phong.vert", "shaders/envmap.frag");    
112 std::optional<Cubemap> sky = Cubemap::loadDirectory("assets/textures/sky"); 119 std::optional<Cubemap> sky = Cubemap::loadDirectory("assets/textures/sky");
113 std::optional<Texture2D> floorTexture = Texture2D::load("assets/textures/floor.png");    
114 std::optional<Texture2D> grassTexture = Texture2D::load("assets/textures/grass_blades.png"); 120 std::optional<Texture2D> grassTexture = Texture2D::load("assets/textures/grass_blades.png");
115 if (!phong || !post || !skybox || !envmap || !sky || !floorTexture || !grassTexture) return 1; 121 if (!phong || !rocksShader || !skybox || !post || !sky || !grassTexture) return 1;
116 grassTexture->setWrap(GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE); 122 grassTexture->setWrap(GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE);
117   123  
    124 // C++の構造体とGLSLのブロックの大きさが合うか確かめる(std140の詰め物を間違えると違う)
    125 // Check that the C++ structs and the GLSL blocks have the same size (they differ if the std140 padding is wrong)
    126 for (const Shader *s : {&*phong, &*rocksShader, &*skybox})
    127 if (!s->checkUniformBlock("Camera", sizeof(CameraBlock)) || !s->checkUniformBlock("Lights", sizeof(LightsBlock)))
    128 return 1;
    129  
118 std::optional<Model> scene = Model::load("assets/models/diorama.glb"); 130 std::optional<Model> scene = Model::load("assets/models/diorama.glb");
119 std::optional<Model> crate = Model::load("assets/models/crate.glb"); 131 std::optional<Model> rock = Model::load("assets/models/rock.glb");
120 if (!scene || !crate) return 1; 132 if (!scene || !rock) return 1;
121   133  
122 const unsigned char whitePixel[4] = {255, 255, 255, 255}; 134 const unsigned char whitePixel[4] = {255, 255, 255, 255};
123 Texture2D white = Texture2D::fromPixels(whitePixel, 1, 1, {.flipY = false, .mipmaps = false}); 135 Texture2D white = Texture2D::fromPixels(whitePixel, 1, 1, {.flipY = false, .mipmaps = false});
@@ -126,34 +138,51 @@ int main() {
126 int lanternNode = scene->findNode("LanternLight"); 138 int lanternNode = scene->findNode("LanternLight");
127 Quat rotorStart = rotor >= 0 ? scene->nodes[static_cast<size_t>(rotor)].rotation : Quat{}; 139 Quat rotorStart = rotor >= 0 ? scene->nodes[static_cast<size_t>(rotor)].rotation : Quat{};
128   140  
    141 // ユニフォームバッファ:作ったときに結合点0と1に繋がる。シェーダーはlayout(binding = …)で同じ番号を読む
    142 // Uniform buffers: attached to binding points 0 and 1 when created. The shaders read the same numbers through
    143 // layout(binding = ...)
    144 UniformBuffer<CameraBlock> cameraUbo(kCameraBinding);
    145 UniformBuffer<LightsBlock> lightsUbo(kLightsBinding);
    146  
    147 // インスタンスのバッファ:全部の岩を一度だけアップロード。描く数を変えても作り直さない(先頭からcount個使う)
    148 // The instance buffer: every rock uploaded once. Changing the count does not rebuild it (the first `count` are used)
    149 std::vector<InstanceData> ring = makeRing();
    150 Buffer instanceBuffer(ring.data(), static_cast<GLsizeiptr>(ring.size() * sizeof(InstanceData)));
    151 rock->setInstanceBuffer(instanceBuffer, sizeof(InstanceData), kInstanceLayout);
    152  
129 Camera fps; 153 Camera fps;
130 fps.position = {0.0f, 2.0f, 12.5f}; 154 fps.position = {0.0f, 6.5f, 24.0f};
131 fps.pitch = radians(-6.0f); 155 fps.pitch = radians(-12.0f);
132   156  
133 OrbitCamera orbit; 157 OrbitCamera orbit;
134 orbit.target = {0.0f, 1.0f, 4.0f}; 158 orbit.target = {0.0f, 1.5f, 0.0f};
135 orbit.distance = 9.0f; 159 orbit.distance = 24.0f;
136 orbit.yaw = radians(20.0f); 160 orbit.yaw = radians(20.0f);
137   161  
138 bool useOrbit = false; 162 bool useOrbit = false, instanced = true;
139 int viewMode = 0, effect = 0, envMode = 0; 163 int viewMode = 0, effect = 0, rockCount = 4000;
140 bool night = false, flashlightOn = false, windmillMoving = true, skyOn = true, seamless = true; 164 bool night = false, flashlightOn = false, moving = true;
141 float windmillTime = 0.0f; 165 float animTime = 0.0f;
142 window.setCursorCaptured(true); 166 window.setCursorCaptured(true);
143   167  
144 // 場面を描くフレームバッファ(ウィンドウと同じ大きさ) / the framebuffer the scene is drawn into (window size)    
145 Framebuffer sceneFbo(window.width(), window.height()); 168 Framebuffer sceneFbo(window.width(), window.height());
146 if (!sceneFbo.complete()) return 1; 169 if (!sceneFbo.complete()) return 1;
147 window.onResize = [&](int width, int height) { sceneFbo.resize(width, height); }; 170 window.onResize = [&](int width, int height) { sceneFbo.resize(width, height); };
148      
149 // キューブマップの面の境目でも隣の面と補間する(GL 3.2から、全体の設定) / filter across the edges between    
150 // cube-map faces too (since GL 3.2, a global switch)    
151 glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS); 171 glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS);
152   172  
    173 // 時間の集計(60フレームの平均) / timing statistics (averaged over 60 frames)
    174 GpuTimer gpuTimer;
    175 double cpuSum = 0.0, gpuSum = 0.0;
    176 int cpuFrames = 0, gpuFrames = 0;
    177 auto resetStats = [&] {
    178 cpuSum = gpuSum = 0.0;
    179 cpuFrames = gpuFrames = 0;
    180 };
    181  
153 window.onKey = [&](int key, int action, int /*mods*/) { 182 window.onKey = [&](int key, int action, int /*mods*/) {
154 if (action != GLFW_PRESS) return; 183 if (action != GLFW_PRESS) return;
155 if (key == GLFW_KEY_ESCAPE) window.close(); 184 if (key == GLFW_KEY_ESCAPE) window.close();
156 if (key == GLFW_KEY_R && phong->reload() && post->reload() && skybox->reload() && envmap->reload()) 185 if (key == GLFW_KEY_R && phong->reload() && rocksShader->reload() && skybox->reload() && post->reload())
157 printf("シェーダーを読み直した / shaders reloaded\n"); 186 printf("シェーダーを読み直した / shaders reloaded\n");
158 if (key == GLFW_KEY_TAB) window.setCursorCaptured(!window.cursorCaptured()); 187 if (key == GLFW_KEY_TAB) window.setCursorCaptured(!window.cursorCaptured());
159 if (key == GLFW_KEY_C) { 188 if (key == GLFW_KEY_C) {
@@ -169,32 +198,22 @@ int main() {
169 effect = key - GLFW_KEY_1; 198 effect = key - GLFW_KEY_1;
170 printf("effect: %s\n", kEffectNames[effect]); 199 printf("effect: %s\n", kEffectNames[effect]);
171 } 200 }
172 if (key == GLFW_KEY_M) { 201 if (key == GLFW_KEY_I) {
173 envMode = (envMode + 1) % 4; 202 instanced = !instanced;
174 printf("environment objects: %s\n", kEnvModeNames[envMode]); 203 resetStats();
    204 printf("rocks: %s\n", instanced ? "instanced" : "one draw call per rock");
175 } 205 }
176 if (key == GLFW_KEY_K) skyOn = !skyOn; 206 if (key == GLFW_KEY_EQUAL && rockCount < kMaxRocks) rockCount *= 2;
177 if (key == GLFW_KEY_X) { 207 if (key == GLFW_KEY_MINUS && rockCount > 250) rockCount /= 2;
178 seamless = !seamless; 208 if (key == GLFW_KEY_EQUAL || key == GLFW_KEY_MINUS) {
179 if (seamless) glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS); 209 resetStats();
180 else glDisable(GL_TEXTURE_CUBE_MAP_SEAMLESS); 210 printf("rocks: %d\n", rockCount);
181 printf("seamless cube-map filtering: %s\n", seamless ? "on" : "off");    
182 } 211 }
183 if (key == GLFW_KEY_N) night = !night; 212 if (key == GLFW_KEY_N) night = !night;
184 if (key == GLFW_KEY_F) flashlightOn = !flashlightOn; 213 if (key == GLFW_KEY_F) flashlightOn = !flashlightOn;
185 if (key == GLFW_KEY_P) windmillMoving = !windmillMoving; 214 if (key == GLFW_KEY_P) moving = !moving;
186 }; 215 };
187   216  
188 // 床は空の地平線まで届くように広く(遠くはfarPlaneで切れる) / the floor is wide so it reaches the sky's horizon    
189 // (the far plane cuts it off in the distance)    
190 Mesh floorMesh = makePlane(160.0f, 40.0f);    
191 Mesh sphereMesh = makeSphere(48, 24);    
192 Mesh cubeMesh = makeCube(); // 空の箱 / the sky box    
193 Material floorMaterial;    
194 floorMaterial.diffuseMap = &*floorTexture;    
195 floorMaterial.specular = {0.15f, 0.15f, 0.15f};    
196 floorMaterial.shininess = 16.0f;    
197      
198 Mesh tuftMesh = makeCrossedQuads(3); 217 Mesh tuftMesh = makeCrossedQuads(3);
199 std::vector<Placement> grass = makeGrass(); 218 std::vector<Placement> grass = makeGrass();
200 Material grassMaterial; 219 Material grassMaterial;
@@ -202,95 +221,12 @@ int main() {
202 grassMaterial.alphaMode = AlphaMode::Mask; 221 grassMaterial.alphaMode = AlphaMode::Mask;
203 grassMaterial.specular = {0.04f, 0.04f, 0.04f}; 222 grassMaterial.specular = {0.04f, 0.04f, 0.04f};
204 grassMaterial.shininess = 8.0f; 223 grassMaterial.shininess = 8.0f;
205   224 Mesh cubeMesh = makeCube();
206 // 全画面の三角形(中身は空のVAOだけ) / the fullscreen triangle (just an empty VAO inside)    
207 FullscreenTriangle fullscreen; 225 FullscreenTriangle fullscreen;
208   226  
209 glEnable(GL_CULL_FACE); 227 glEnable(GL_CULL_FACE);
210   228  
211 LightSet lights; 229 int frame = 0;
212      
213 Vec3 environmentTint;    
214      
215 // 場面全体を今のフレームバッファに描く / draws the whole scene into the current framebuffer    
216 auto drawScene = [&](const View &v) {    
217 glEnable(GL_DEPTH_TEST);    
218 if (night) glClearColor(0.02f, 0.03f, 0.06f, 1.0f);    
219 else glClearColor(0.45f, 0.62f, 0.85f, 1.0f);    
220 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);    
221      
222 // 空はユニット3。phong(金属の映り込み)、envmap、skyboxのどれもここから読む    
223 // The sky is on unit 3: phong (metal reflections), envmap and skybox all read it from there    
224 sky->bind(3);    
225      
226 phong->use();    
227 phong->set("uView", v.view);    
228 phong->set("uProj", v.proj);    
229 phong->set("uViewPos", v.position);    
230 phong->set("uViewMode", viewMode);    
231 phong->set("uEnvironmentTint", environmentTint);    
232 lights.apply(*phong);    
233      
234 phong->set("uModel", Mat4::identity());    
235 phong->set("uNormalMatrix", normalMatrix(Mat4::identity()));    
236 floorMaterial.apply(*phong, white);    
237 floorMesh.draw();    
238 scene->draw(*phong, Mat4::identity(), white, ModelPass::Opaque);    
239 for (const Placement &c : kCrates) crate->draw(*phong, translate(c.position) * rotateY(c.angle), white, ModelPass::Opaque);    
240 grassMaterial.apply(*phong, white);    
241 glDisable(GL_CULL_FACE); // 草は両面 / grass is two-sided    
242 for (const Placement &g : grass) {    
243 Mat4 model = translate(g.position) * rotateY(g.angle) * scale({0.75f, 0.75f, 0.75f});    
244 phong->set("uModel", model);    
245 phong->set("uNormalMatrix", normalMatrix(model));    
246 tuftMesh.draw();    
247 }    
248 glEnable(GL_CULL_FACE);    
249      
250 // 環境マッピングの物 / the environment-mapped objects    
251 envmap->use();    
252 envmap->set("uView", v.view);    
253 envmap->set("uProj", v.proj);    
254 envmap->set("uViewPos", v.position);    
255 envmap->set("uEnvironmentTint", environmentTint);    
256 envmap->set("uIor", 1.52f);    
257 for (size_t i = 0; i < std::size(kEnvObjects); ++i) {    
258 const EnvObject &o = kEnvObjects[i];    
259 envmap->set("uEnvMode", envMode == 0 ? o.mode : envMode - 1);    
260 envmap->set("uTint", o.tint);    
261 if (i == 1) {    
262 // 平らな面は一つの方向しか映さない:回すと映る空が変わる。木箱の原点は底なので、中心(0, 0.5, 0)の周りで回す    
263 // A flat face reflects only one direction: turning it changes the sky it shows. The crate's origin is at its    
264 // bottom, so it turns about its centre (0, 0.5, 0)    
265 Mat4 model = translate(o.position) * rotate(normalize(Vec3{1.0f, 1.0f, 0.3f}), 0.6f * windmillTime + 0.8f) *    
266 translate({0.0f, -0.5f, 0.0f});    
267 crate->drawGeometry(*envmap, model); // uModelとuNormalMatrixだけ / only uModel and uNormalMatrix    
268 } else {    
269 Mat4 model = translate(o.position) * scale({1.5f, 1.5f, 1.5f});    
270 envmap->set("uModel", model);    
271 envmap->set("uNormalMatrix", normalMatrix(model));    
272 sphereMesh.draw();    
273 }    
274 }    
275      
276 // 空は不透明な物の後に:見えているピクセルだけ塗る(深度1のところ)。半透明な物があればその前    
277 // The sky after the opaque objects: it only fills pixels nothing covers (depth 1). Before any transparent ones    
278 if (skyOn) {    
279 // 空の深度はちょうど1.0。クリアした値も1.0なので、GL_LESSでは通らない:GL_LEQUALにする    
280 // The sky's depth is exactly 1.0, the same as the cleared value, so GL_LESS would reject it: use GL_LEQUAL    
281 glDepthFunc(GL_LEQUAL);    
282 // 箱を内側から見るので、見えるのは裏面:カリングを切る / we see the box from inside, i.e. its back faces: no culling    
283 glDisable(GL_CULL_FACE);    
284 skybox->use();    
285 skybox->set("uView", v.view);    
286 skybox->set("uProj", v.proj);    
287 skybox->set("uEnvironmentTint", environmentTint);    
288 cubeMesh.draw();    
289 glEnable(GL_CULL_FACE);    
290 glDepthFunc(GL_LESS);    
291 }    
292 };    
293      
294 double lastTime = window.time(); 230 double lastTime = window.time();
295 while (!window.shouldClose()) { 231 while (!window.shouldClose()) {
296 double now = window.time(); 232 double now = window.time();
@@ -316,22 +252,23 @@ int main() {
316 fps.move(dir, dt); 252 fps.move(dir, dt);
317 } 253 }
318   254  
319 if (windmillMoving) windmillTime += dt; 255 if (moving) animTime += dt;
320 if (rotor >= 0) 256 if (rotor >= 0)
321 scene->nodes[static_cast<size_t>(rotor)].rotation = 257 scene->nodes[static_cast<size_t>(rotor)].rotation =
322 Quat::fromAxisAngle({0.0f, 0.0f, 1.0f}, -0.8f * windmillTime) * rotorStart; 258 Quat::fromAxisAngle({0.0f, 0.0f, 1.0f}, -0.8f * animTime) * rotorStart;
323   259  
324 // アスペクト比は描き込むフレームバッファのもの(ウィンドウとは限らない) 260 // カメラのブロック:フレームに一度書けば、全部のシェーダーが読む(シェーダーごとのset()は要らない)
325 // The aspect ratio is that of the framebuffer drawn into (not necessarily the window) 261 // The camera block: written once per frame, read by every shader (no per-shader set() any more)
326 float aspect = static_cast<float>(sceneFbo.width()) / static_cast<float>(sceneFbo.height()); 262 float aspect = static_cast<float>(sceneFbo.width()) / static_cast<float>(sceneFbo.height());
327 View main; 263 CameraBlock camera;
328 main.view = useOrbit ? orbit.view() : fps.view(); 264 camera.view = useOrbit ? orbit.view() : fps.view();
329 main.proj = useOrbit ? orbit.projection(aspect) : fps.projection(aspect); 265 camera.proj = useOrbit ? orbit.projection(aspect) : fps.projection(aspect);
330 main.position = useOrbit ? orbit.position() : fps.position; 266 camera.viewPos = useOrbit ? orbit.position() : fps.position;
    267 camera.time = animTime;
    268 cameraUbo.update(camera);
331 Vec3 viewDir = useOrbit ? normalize(orbit.target - orbit.position()) : fps.front(); 269 Vec3 viewDir = useOrbit ? normalize(orbit.target - orbit.position()) : fps.front();
332   270  
333 environmentTint = night ? Vec3{0.05f, 0.06f, 0.11f} : Vec3{1.0f, 1.0f, 1.0f}; 271 LightSet lights;
334 lights = LightSet{};    
335 if (!night) { 272 if (!night) {
336 lights.ambient = {0.28f, 0.30f, 0.34f}; 273 lights.ambient = {0.28f, 0.30f, 0.34f};
337 lights.directional = {.direction = {-0.5f, -1.0f, -0.35f}, .color = {0.95f, 0.9f, 0.8f}}; 274 lights.directional = {.direction = {-0.5f, -1.0f, -0.35f}, .color = {0.95f, 0.9f, 0.8f}};
@@ -344,22 +281,99 @@ int main() {
344 } 281 }
345 } 282 }
346 if (flashlightOn) 283 if (flashlightOn)
347 lights.spots.push_back({.position = main.position, .direction = viewDir, .color = {1.0f, 0.95f, 0.85f}}); 284 lights.spots.push_back({.position = camera.viewPos, .direction = viewDir, .color = {1.0f, 0.95f, 0.85f}});
    285 lightsUbo.update(lights.toBlock()); // 光のブロックも一度だけ / the lights block, also just once
    286 Vec3 environmentTint = night ? Vec3{0.05f, 0.06f, 0.11f} : Vec3{1.0f, 1.0f, 1.0f};
348   287  
349 // 1. 場面をフレームバッファに描く / 1. draw the scene into the framebuffer 288 //------------------------------------------------------------------
    289 // 1. 場面をフレームバッファに / 1. the scene into the framebuffer
    290 //------------------------------------------------------------------
350 sceneFbo.bind(); 291 sceneFbo.bind();
351 drawScene(main); 292 glEnable(GL_DEPTH_TEST);
    293 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
    294 sky->bind(3);
    295  
    296 // ビュー・射影・光はもう設定しない:ブロックから来る / no view, projection or lights to set: they come from the blocks
    297 phong->use();
    298 phong->set("uViewMode", viewMode);
    299 phong->set("uEnvironmentTint", environmentTint);
    300 scene->draw(*phong, Mat4::identity(), white, ModelPass::Opaque);
    301 // 浮島の下の岩:同じ岩のモデルを平たく大きく / the rock under the floating island: the same rock model, wide and flat
    302 rock->draw(*phong, translate({0.0f, -1.7f, 0.0f}) * scale({10.0f, 3.4f, 10.0f}), white);
    303 grassMaterial.apply(*phong, white);
    304 glDisable(GL_CULL_FACE);
    305 for (const Placement &g : grass) {
    306 Mat4 model = translate(g.position) * rotateY(g.angle) * scale({0.75f, 0.75f, 0.75f});
    307 phong->set("uModel", model);
    308 phong->set("uNormalMatrix", normalMatrix(model));
    309 tuftMesh.draw();
    310 }
    311 glEnable(GL_CULL_FACE);
352   312  
353 // 2. 画面へ:全画面の三角形でフレームバッファのテクスチャを貼り、効果をかける 313 // 岩の環:ここだけ時間を測る / the ring of rocks: only this part is timed
354 // 3. To the screen: a fullscreen triangle samples the framebuffer's texture and applies the effect 314 gpuTimer.begin();
    315 auto cpuStart = std::chrono::steady_clock::now();
    316 if (instanced) {
    317 // インスタンシング:プリミティブ1つにつき描画呼び出し1回。公転はシェーダーがuTimeで計算する
    318 // Instancing: one draw call per primitive. The shader computes the orbit from uTime
    319 rocksShader->use();
    320 rocksShader->set("uViewMode", viewMode);
    321 rocksShader->set("uEnvironmentTint", environmentTint);
    322 rocksShader->set("uOrbitSpeed", kOrbitSpeed);
    323 rock->drawInstanced(*rocksShader, white, rockCount);
    324 } else {
    325 // 一つずつ:岩ごとにuModel・uNormalMatrix・マテリアル・uTintを設定して描画呼び出し。公転はCPUで計算
    326 // One by one: per rock set uModel, uNormalMatrix, the material and uTint, then a draw call. The orbit is
    327 // computed on the CPU
    328 phong->use();
    329 for (int i = 0; i < rockCount; ++i) {
    330 const InstanceData &d = ring[static_cast<size_t>(i)];
    331 phong->set("uTint", d.color);
    332 rock->draw(*phong, rotateY(orbitAngle(d.model, animTime)) * d.model, white);
    333 }
    334 phong->set("uTint", Vec3{1.0f, 1.0f, 1.0f});
    335 }
    336 double cpuMs = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - cpuStart).count();
    337 gpuTimer.end();
    338  
    339 // 空(第18章) / the sky (chapter 18)
    340 glDepthFunc(GL_LEQUAL);
    341 glDisable(GL_CULL_FACE);
    342 skybox->use();
    343 skybox->set("uEnvironmentTint", environmentTint);
    344 cubeMesh.draw();
    345 glEnable(GL_CULL_FACE);
    346 glDepthFunc(GL_LESS);
    347  
    348 //------------------------------------------------------------------
    349 // 2. 画面へ(第17章) / 2. to the screen (chapter 17)
    350 //------------------------------------------------------------------
355 Framebuffer::bindDefault(window.width(), window.height()); 351 Framebuffer::bindDefault(window.width(), window.height());
356 glDisable(GL_DEPTH_TEST); // 三角形一つだけ:深度は要らない / a single triangle: no depth needed 352 glDisable(GL_DEPTH_TEST);
357 post->use(); 353 post->use();
358 post->set("uEffect", effect); 354 post->set("uEffect", effect);
359 post->set("uFlipX", 0); 355 post->set("uFlipX", 0);
360 sceneFbo.color().bind(0); 356 sceneFbo.color().bind(0);
361 fullscreen.draw(); 357 fullscreen.draw();
362   358  
    359 // 時間の集計:60フレームごとにタイトルと標準出力へ / timing: every 60 frames to the title and stdout
    360 cpuSum += cpuMs;
    361 ++cpuFrames;
    362 if (std::optional<double> gpu = gpuTimer.latestMs()) {
    363 gpuSum += *gpu;
    364 ++gpuFrames;
    365 }
    366 if (++frame % 60 == 0) {
    367 int calls = instanced ? 1 : rockCount;
    368 char text[256];
    369 snprintf(text, sizeof text, "OpenGL Tutorial - Chapter 19 | %d rocks, %s: %d draw call%s, CPU %.2f ms, GPU %.2f ms",
    370 rockCount, instanced ? "instanced" : "one by one", calls, calls == 1 ? "" : "s", cpuSum / cpuFrames,
    371 gpuFrames > 0 ? gpuSum / gpuFrames : 0.0);
    372 window.setTitle(text);
    373 printf("%s\n", text + 31); // 「OpenGL Tutorial - Chapter 19 | 」の後ろ / after "OpenGL Tutorial - Chapter 19 | "
    374 resetStats();
    375 }
    376  
363 window.swapBuffers(); 377 window.swapBuffers();
364 } 378 }
365 return 0; 379 return 0;

ファイル: a/src/mesh.cc | b/src/mesh.cc

前新
@@ -56,3 +56,21 @@ void Mesh::draw() const {
56 glDrawArrays(primitive, 0, vertexCount); 56 glDrawArrays(primitive, 0, vertexCount);
57 } 57 }
58 } 58 }
    59  
    60 void Mesh::setInstanceBuffer(const Buffer &buffer, GLsizei stride, std::span<const VertexAttrib> layout) {
    61 constexpr GLuint kInstanceBinding = 1; // 頂点はバインディング0 / the vertices are binding 0
    62 glVertexArrayVertexBuffer(vertexArray, kInstanceBinding, buffer.id(), 0, stride);
    63 for (const VertexAttrib &a : layout) {
    64 glEnableVertexArrayAttrib(vertexArray, a.location);
    65 glVertexArrayAttribFormat(vertexArray, a.location, a.components, a.type, a.normalized, a.offset);
    66 glVertexArrayAttribBinding(vertexArray, a.location, kInstanceBinding);
    67 }
    68 // 1 = インスタンス1つごとに1要素進む(0なら頂点ごと) / 1 = advance one element per instance (0 = per vertex)
    69 glVertexArrayBindingDivisor(vertexArray, kInstanceBinding, 1);
    70 }
    71  
    72 void Mesh::drawInstanced(GLsizei count) const {
    73 glBindVertexArray(vertexArray);
    74 if (indexCount > 0) glDrawElementsInstanced(primitive, indexCount, GL_UNSIGNED_INT, nullptr, count);
    75 else glDrawArraysInstanced(primitive, 0, vertexCount, count);
    76 }

ファイル: a/src/mesh.hh | b/src/mesh.hh

前新
@@ -55,6 +55,21 @@ constexpr VertexAttrib kModelVertexLayout[] = {
55 {3, 4, offsetof(ModelVertex, tangent)}, // layout(location = 3) in vec4 aTangent(第22章 / chapter 22) 55 {3, 4, offsetof(ModelVertex, tangent)}, // layout(location = 3) in vec4 aTangent(第22章 / chapter 22)
56 }; 56 };
57   57  
    58 // インスタンスごとのデータ(第19章):モデル行列(列4本をlocation 4〜7)と色(location 8)
    59 // Per-instance data (chapter 19): the model matrix (its four columns at locations 4..7) and a colour (location 8)
    60 struct InstanceData {
    61 Mat4 model;
    62 Vec3 color;
    63 };
    64  
    65 constexpr VertexAttrib kInstanceLayout[] = {
    66 {4, 4, offsetof(InstanceData, model) + 0}, // layout(location = 4) in mat4 aInstanceModel(列0 / column 0)
    67 {5, 4, offsetof(InstanceData, model) + 16}, // 列1 / column 1
    68 {6, 4, offsetof(InstanceData, model) + 32}, // 列2 / column 2
    69 {7, 4, offsetof(InstanceData, model) + 48}, // 列3 / column 3
    70 {8, 3, offsetof(InstanceData, color)}, // layout(location = 8) in vec3 aInstanceColor
    71 };
    72  
58 // 一つの描画単位(RAII、コピー不可・移動可)。インデックスが空ならglDrawArraysで描く。 73 // 一つの描画単位(RAII、コピー不可・移動可)。インデックスが空ならglDrawArraysで描く。
59 // One drawable unit (RAII, non-copyable, movable). With no indices it draws with glDrawArrays. 74 // One drawable unit (RAII, non-copyable, movable). With no indices it draws with glDrawArrays.
60 class Mesh { 75 class Mesh {
@@ -75,6 +90,14 @@ public:
75 Mesh &operator=(Mesh &&other) noexcept; 90 Mesh &operator=(Mesh &&other) noexcept;
76   91  
77 void draw() const; 92 void draw() const;
    93 // 同じメッシュをcount回描く(インスタンシング、第19章)。インスタンスごとのデータはsetInstanceBufferで繋ぐ
    94 // Draws the same mesh count times (instancing, chapter 19). Per-instance data comes from setInstanceBuffer
    95 void drawInstanced(GLsizei count) const;
    96 // インスタンスごとの属性のバッファをバインディング1に繋ぐ:頂点ごとではなく、インスタンスごとに次の要素へ進む
    97 // (divisor = 1)。layoutのlocationは頂点の属性(0〜3)と重ならないこと。
    98 // Attaches a buffer of per-instance attributes to binding 1: it advances once per instance instead of once per
    99 // vertex (divisor = 1). The layout's locations must not overlap the vertex attributes (0..3).
    100 void setInstanceBuffer(const Buffer &buffer, GLsizei stride, std::span<const VertexAttrib> layout);
78   101  
79 GLuint vao() const { return vertexArray; } 102 GLuint vao() const { return vertexArray; }
80   103  

ファイル: a/src/model.cc | b/src/model.cc

前新
@@ -315,8 +315,19 @@ void Model::collect(int node, const Mat4 &parentWorld, const Mat4 &transform, bo
315 for (int child : n.children) collect(child, world, transform, hierarchy, pass, viewPos, out); 315 for (int child : n.children) collect(child, world, transform, hierarchy, pass, viewPos, out);
316 } 316 }
317   317  
    318 void Model::setInstanceBuffer(const Buffer &buffer, GLsizei stride, std::span<const VertexAttrib> layout) {
    319 for (MeshData &m : meshes)
    320 for (Primitive &p : m.primitives) p.mesh.setInstanceBuffer(buffer, stride, layout);
    321 }
    322  
    323 void Model::drawInstanced(const Shader &shader, const Texture2D &white, GLsizei count) const {
    324 std::vector<DrawItem> items;
    325 for (int root : roots) collect(root, Mat4::identity(), Mat4::identity(), true, ModelPass::All, {}, items);
    326 drawItems(items, shader, &white, shader.has("uNormalMatrix"), count);
    327 }
    328  
318 void Model::drawItems(const std::vector<DrawItem> &items, const Shader &shader, const Texture2D *white, 329 void Model::drawItems(const std::vector<DrawItem> &items, const Shader &shader, const Texture2D *white,
319 bool normals) const { 330 bool normals, GLsizei instances) const {
320 bool culling = glIsEnabled(GL_CULL_FACE); // 呼ぶ側の設定を覚えておく / remember the caller's setting 331 bool culling = glIsEnabled(GL_CULL_FACE); // 呼ぶ側の設定を覚えておく / remember the caller's setting
321 for (const DrawItem &item : items) { 332 for (const DrawItem &item : items) {
322 const Primitive &p = *item.primitive; 333 const Primitive &p = *item.primitive;
@@ -333,7 +344,8 @@ void Model::drawItems(const std::vector<DrawItem> &items, const Shader &shader,
333 // Double-sided materials (leaves, glass, sails) must be visible from behind: no culling for them 344 // Double-sided materials (leaves, glass, sails) must be visible from behind: no culling for them
334 bool noCull = culling && md.phong.doubleSided; 345 bool noCull = culling && md.phong.doubleSided;
335 if (noCull) glDisable(GL_CULL_FACE); 346 if (noCull) glDisable(GL_CULL_FACE);
336 p.mesh.draw(); 347 if (instances > 0) p.mesh.drawInstanced(instances);
    348 else p.mesh.draw();
337 if (noCull) glEnable(GL_CULL_FACE); 349 if (noCull) glEnable(GL_CULL_FACE);
338 } 350 }
339 } 351 }

ファイル: a/src/model.hh | b/src/model.hh

前新
@@ -8,6 +8,7 @@
8 #include "texture.hh" 8 #include "texture.hh"
9   9  
10 #include <optional> 10 #include <optional>
    11 #include <span>
11 #include <string> 12 #include <string>
12 #include <string_view> 13 #include <string_view>
13 #include <vector> 14 #include <vector>
@@ -70,6 +71,15 @@ public:
70 // For passes that need no colour: the depth view, outlines, and later shadows (chapter 23). 71 // For passes that need no colour: the depth view, outlines, and later shadows (chapter 23).
71 void drawGeometry(const Shader &shader, const Mat4 &transform) const; 72 void drawGeometry(const Shader &shader, const Mat4 &transform) const;
72   73  
    74 // インスタンシング(第19章):全部のプリミティブのVAOにインスタンスのバッファを繋ぐ(Mesh::setInstanceBuffer)
    75 // Instancing (chapter 19): attaches the instance buffer to every primitive's VAO (Mesh::setInstanceBuffer)
    76 void setInstanceBuffer(const Buffer &buffer, GLsizei stride, std::span<const VertexAttrib> layout);
    77 // count個のインスタンスを、プリミティブごとに描画呼び出し1回で描く。uModelはノードのモデル座標の行列で、
    78 // インスタンスの行列はシェーダーで掛ける(phong_instanced.vert:world = aInstanceModel × uModel × 位置)。
    79 // Draws count instances with one draw call per primitive. uModel is the node's model-space matrix; the shader
    80 // multiplies the instance matrix on top (phong_instanced.vert: world = aInstanceModel × uModel × position).
    81 void drawInstanced(const Shader &shader, const Texture2D &white, GLsizei count) const;
    82  
73 // 名前でノードを探す。なければ-1 / finds a node by name; -1 if none 83 // 名前でノードを探す。なければ-1 / finds a node by name; -1 if none
74 int findNode(std::string_view name) const; 84 int findNode(std::string_view name) const;
75 // ノードのモデル座標での行列(ルートからの積)。描く場所はtransform × これ 85 // ノードのモデル座標での行列(ルートからの積)。描く場所はtransform × これ
@@ -98,7 +108,8 @@ private:
98 void collect(int node, const Mat4 &parentWorld, const Mat4 &transform, bool hierarchy, ModelPass pass, 108 void collect(int node, const Mat4 &parentWorld, const Mat4 &transform, bool hierarchy, ModelPass pass,
99 Vec3 viewPos, std::vector<DrawItem> &out) const; 109 Vec3 viewPos, std::vector<DrawItem> &out) const;
100 // white == nullptrなら形だけ(drawGeometry) / white == nullptr: shape only (drawGeometry) 110 // white == nullptrなら形だけ(drawGeometry) / white == nullptr: shape only (drawGeometry)
101 void drawItems(const std::vector<DrawItem> &items, const Shader &shader, const Texture2D *white, bool normals) const; 111 void drawItems(const std::vector<DrawItem> &items, const Shader &shader, const Texture2D *white, bool normals,
    112 GLsizei instances = 0) const;
102 const MaterialData &materialOf(const Primitive &p) const; 113 const MaterialData &materialOf(const Primitive &p) const;
103 const Texture2D *texture(int index) const; // なければnullptr / nullptr if missing 114 const Texture2D *texture(int index) const; // なければnullptr / nullptr if missing
104   115  

ファイル: a/src/shader.cc | b/src/shader.cc

前新
@@ -183,3 +183,22 @@ void Shader::set(const char *name, const Mat4 &m) const {
183 // linalg.hhは列優先なので転置しない(GL_FALSE) / linalg.hh is column-major, so no transpose (GL_FALSE) 183 // linalg.hhは列優先なので転置しない(GL_FALSE) / linalg.hh is column-major, so no transpose (GL_FALSE)
184 glProgramUniformMatrix4fv(program, location(name), 1, GL_FALSE, &m.c[0].x); 184 glProgramUniformMatrix4fv(program, location(name), 1, GL_FALSE, &m.c[0].x);
185 } 185 }
    186  
    187 GLint Shader::uniformBlockSize(const char *blockName) const {
    188 GLuint index = glGetUniformBlockIndex(program, blockName);
    189 if (index == GL_INVALID_INDEX) return -1;
    190 GLint size = 0;
    191 glGetActiveUniformBlockiv(program, index, GL_UNIFORM_BLOCK_DATA_SIZE, &size);
    192 return size;
    193 }
    194  
    195 bool Shader::checkUniformBlock(const char *blockName, size_t cppSize) const {
    196 GLint size = uniformBlockSize(blockName);
    197 // ドライバーによっては最後のメンバーの終わり(例:692)を、ほかは16の倍数に切り上げた値(704)を返す。
    198 // 16の倍数に切り上げて比べる / some drivers report where the last member ends (e.g. 692), others round up to a
    199 // multiple of 16 (704): compare after rounding up to 16
    200 if (size < 0 || ((static_cast<size_t>(size) + 15) / 16) * 16 == cppSize) return true;
    201 fprintf(stderr, "%s + %s: ブロック「%s」は%dバイト、C++の構造体は%zuバイト / block \"%s\" is %d bytes, the C++ struct %zu\n",
    202 vertexPath.c_str(), fragmentPath.c_str(), blockName, size, cppSize, blockName, size, cppSize);
    203 return false;
    204 }

ファイル: a/src/shader.hh | b/src/shader.hh

前新
@@ -41,6 +41,14 @@ public:
41 void set(const char *name, const Mat3 &value) const; 41 void set(const char *name, const Mat3 &value) const;
42 void set(const char *name, const Mat4 &value) const; 42 void set(const char *name, const Mat4 &value) const;
43   43  
    44 // ユニフォームブロックの大きさ(GLが決めたバイト数)。プログラムになければ-1(第19章)
    45 // The size of a uniform block in bytes, as the GL laid it out. -1 if the program has no such block (chapter 19)
    46 GLint uniformBlockSize(const char *blockName) const;
    47 // ブロックの大きさがC++の構造体と合うか確かめる。違えばエラーを表示してfalse。ブロックがなければtrue。
    48 // Checks that a block's size matches the C++ struct. Prints an error and returns false if not; true if the
    49 // program has no such block.
    50 bool checkUniformBlock(const char *blockName, size_t cppSize) const;
    51  
44 // そのユニフォームがプログラムで使われているか(警告は出さない) / does the program use that uniform? (no warning) 52 // そのユニフォームがプログラムで使われているか(警告は出さない) / does the program use that uniform? (no warning)
45 bool has(const char *name) const { return glGetUniformLocation(program, name) >= 0; } 53 bool has(const char *name) const { return glGetUniformLocation(program, name) >= 0; }
46   54  

ファイル: /dev/null | b/src/uniforms.hh

前新
@@ -0,0 +1,66 @@
    1 // ユニフォームバッファ(UBO):いくつものシェーダーで共有するユニフォームのまとまり(第19章)
    2 // Uniform buffers (UBOs): blocks of uniforms shared by many shaders (chapter 19)
    3 #pragma once
    4  
    5 #include "buffer.hh"
    6  
    7 #include <linalg.hh>
    8  
    9 #include <cstddef>
    10  
    11 // 結合点の番号。シェーダーの layout(std140, binding = N) と同じにすること
    12 // Binding point numbers. Must match layout(std140, binding = N) in the shaders
    13 constexpr GLuint kCameraBinding = 0; // Camera:ビュー・射影・カメラの位置・時間 / view, projection, camera position, time
    14 constexpr GLuint kLightsBinding = 1; // Lights:全部の光(lights.hhのLightsBlock) / all lights (LightsBlock in lights.hh)
    15 // 2 = 影(第23章:光から見た行列) / shadows (chapter 23: light-space matrices)
    16 // 3 = 後処理の設定(第21章:露出、ブルーム) / post-processing settings (chapter 21: exposure, bloom)
    17  
    18 // std140の規則(よく使うものだけ) / the std140 rules (the common ones)
    19 // float, int, bool : 4バイト、4の倍数に置く / 4 bytes, at a multiple of 4
    20 // vec2 : 8バイト、8の倍数 / 8 bytes, at a multiple of 8
    21 // vec3, vec4 : 12・16バイト、16の倍数(vec3の後ろの4バイトにはfloatが一つ入る)
    22 // 12 / 16 bytes, at a multiple of 16 (one float fits in the 4 bytes after a vec3)
    23 // mat4 : vec4の列が4本、64バイト、16の倍数 / four vec4 columns, 64 bytes, at a multiple of 16
    24 // 配列 / arrays : 要素ごとに16の倍数に切り上げ(float[4]でも64バイト) / every element rounded up to 16 (even float[4] is 64 bytes)
    25 // 構造体 / structs : 16の倍数に置き、大きさも16の倍数に切り上げ / start at a multiple of 16, size rounded up to 16
    26 // C++の構造体は同じ並びになるように、詰め物(pad)を自分で入れる。static_assertで確かめる。
    27 // The C++ structs get explicit padding so they have the same layout; static_assert checks it.
    28  
    29 // GLSL:
    30 // layout(std140, binding = 0) uniform Camera {
    31 // mat4 uView; // offset 0
    32 // mat4 uProj; // offset 64
    33 // vec3 uViewPos; // offset 128
    34 // float uTime; // offset 140(vec3の後ろの隙間) / (the gap after the vec3)
    35 // }; // 144 bytes
    36 struct CameraBlock {
    37 Mat4 view;
    38 Mat4 proj;
    39 Vec3 viewPos;
    40 float time = 0.0f; // アニメーションの時間(秒) / animation time (seconds)
    41 };
    42 static_assert(offsetof(CameraBlock, proj) == 64);
    43 static_assert(offsetof(CameraBlock, viewPos) == 128);
    44 static_assert(offsetof(CameraBlock, time) == 140);
    45 static_assert(sizeof(CameraBlock) == 144);
    46  
    47 // 一つのブロックの中身を持つユニフォームバッファ(RAII、コピー不可・移動可)。作るときに結合点に繋ぐ。
    48 // A uniform buffer holding one block (RAII, non-copyable, movable). Attached to its binding point when created.
    49 template <typename Block>
    50 class UniformBuffer {
    51 public:
    52 explicit UniformBuffer(GLuint bindingPoint)
    53 : buffer(nullptr, sizeof(Block), GL_DYNAMIC_STORAGE_BIT), binding(bindingPoint) {
    54 bind();
    55 }
    56 // 中身を全部書き換える(毎フレーム) / replaces the whole contents (every frame)
    57 void update(const Block &block) const { buffer.update(&block, sizeof(Block)); }
    58 // 結合点に繋ぎ直す(同じ番号に別のバッファを繋いだ後で) / re-attach to the binding point (after another
    59 // buffer was attached to the same number)
    60 void bind() const { buffer.bindBase(GL_UNIFORM_BUFFER, binding); }
    61 GLuint bindingPoint() const { return binding; }
    62  
    63 private:
    64 Buffer buffer;
    65 GLuint binding;
    66 };


コメント(0)

まだコメントはありません。