diff --git a/CMakeLists.txt b/CMakeLists.txt index 31939fd..9d447d1 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -42,7 +42,8 @@ add_executable(game src/gltf.cc src/model.cc src/framebuffer.cc - src/cubemap.cc) + src/cubemap.cc + src/gpu_timer.cc) target_include_directories(game PRIVATE src external/stb external/linalg) target_link_libraries(game PRIVATE glad stb_image glfw) diff --git a/assets/LICENSE.txt b/assets/LICENSE.txt index cb46614..d8c94da 100644 --- a/assets/LICENSE.txt +++ b/assets/LICENSE.txt @@ -11,5 +11,6 @@ textures/rug.png 敷物 / a runner rug (chapter 15) textures/grass_blades.png 草の葉(アルファ付き) / grass blades with alpha (chapter 16) textures/sky/*.png 空のキューブマップの6面 / the six sky cube-map faces (chapter 18) models/window.glb 花箱つきの窓 / a window with a flower box (chapter 16) +models/rock.glb 岩(インスタンシング用) / a rock for instancing (chapter 19) models/crate.glb 木箱のモデル / crate model models/diorama.glb 小さな場面 / a small diorama scene diff --git a/assets/models/rock.glb b/assets/models/rock.glb new file mode 100644 index 0000000..0f4cda8 Binary files /dev/null and b/assets/models/rock.glb differ diff --git a/shaders/envmap.frag b/shaders/envmap.frag index 78ebeec..27136ab 100644 --- a/shaders/envmap.frag +++ b/shaders/envmap.frag @@ -6,7 +6,14 @@ in vec3 vNormal; layout(binding = 3) uniform samplerCube uEnvironment; -uniform vec3 uViewPos; +// カメラ(ユニフォームバッファ、結合点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 int uEnvMode; // 0 = 反射 / reflection, 1 = 屈折 / refraction, 2 = フレネル(ガラス) / Fresnel (glass) uniform float uIor; // 屈折率(ガラス1.52、水1.33) / index of refraction (glass 1.52, water 1.33) uniform vec3 uTint; // 反射・屈折の色 / colour of the reflection / refraction diff --git a/shaders/phong.frag b/shaders/phong.frag index 6463bef..ecafdbe 100644 --- a/shaders/phong.frag +++ b/shaders/phong.frag @@ -2,6 +2,7 @@ in vec3 vWorldPos; in vec3 vNormal; in vec2 vUv; +in vec3 vTint; // インスタンスの色(第19章) / the instance colour (chapter 19) // 表面の性質。色はそれぞれのマップと掛け合わされる / surface properties; each colour is multiplied with its map struct Material { @@ -25,6 +26,9 @@ layout(binding = 2) uniform sampler2D uEmissionMap; layout(binding = 3) uniform samplerCube uEnvironmentMap; uniform vec3 uEnvironmentTint; // 空の明るさ(昼1、夜は暗く) / brightness of the sky (1 by day, dark at night) +// 光の構造体。std140では各vec3が16バイトの境目から始まる:C++のLightsBlockと同じ並び(lights.hh) +// The light structs. In std140 each vec3 starts on a 16-byte boundary: the same layout as LightsBlock in C++ (lights.hh) + // 平行光源:向きだけ / directional light: a direction only struct DirectionalLight { vec3 direction; // 光が進む向き(単位ベクトル) / the direction the light travels (unit vector) @@ -38,13 +42,14 @@ struct PointLight { vec3 attenuation; // 定数項・一次・二次 / constant, linear, quadratic }; -// スポットライト:点光源+円錐 / spotlight: a point light + a cone +// スポットライト:点光源+円錐。floatはvec3の後ろの隙間に入れる(詰め物が減る) +// spotlight: a point light + a cone. The floats sit in the gaps after the vec3s (less padding) struct SpotLight { vec3 position; - vec3 direction; // 円錐の軸(単位ベクトル) / the cone's axis (unit vector) - vec3 color; 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; }; @@ -52,14 +57,24 @@ struct SpotLight { #define MAX_POINT_LIGHTS 8 #define MAX_SPOT_LIGHTS 4 -uniform DirectionalLight uDirLight; -uniform PointLight uPointLights[MAX_POINT_LIGHTS]; -uniform int uPointLightCount; // 使っている数 / how many are in use -uniform SpotLight uSpotLights[MAX_SPOT_LIGHTS]; -uniform int uSpotLightCount; +// 全部の光(ユニフォームバッファ、結合点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; +}; -uniform vec3 uAmbient; // 環境光の色と明るさ / ambient light colour and brightness -uniform vec3 uViewPos; // カメラの位置(ワールド座標) / camera position (world space) +// カメラ(ユニフォームバッファ、結合点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) +}; // 0 = 全部、1 = 環境光、2 = 拡散反射、3 = 鏡面反射、4 = 発光、5 = 法線 // 0 = everything, 1 = ambient, 2 = diffuse, 3 = specular, 4 = emission, 5 = normals @@ -112,7 +127,7 @@ void main() { // 両面のマテリアルを裏から見ているなら、法線は裏を向く / seen from behind, a double-sided surface's normal points the other way if (uMaterial.doubleSided && !gl_FrontFacing) s.normal = -s.normal; s.view = normalize(uViewPos - vWorldPos); - s.diffuse = uMaterial.diffuse * base.rgb; + s.diffuse = uMaterial.diffuse * vTint * base.rgb; s.specular = uMaterial.specular * texture(uSpecularMap, vUv).rgb; s.shininess = uMaterial.shininess; vec3 emission = uMaterial.emission * texture(uEmissionMap, vUv).rgb; diff --git a/shaders/phong.vert b/shaders/phong.vert index 1dd79e8..34d7561 100644 --- a/shaders/phong.vert +++ b/shaders/phong.vert @@ -3,20 +3,32 @@ 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 mat4 uView; -uniform mat4 uProj; 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; } diff --git a/shaders/phong_instanced.vert b/shaders/phong_instanced.vert new file mode 100644 index 0000000..dfe298f --- /dev/null +++ b/shaders/phong_instanced.vert @@ -0,0 +1,49 @@ +#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; +} diff --git a/shaders/skybox.vert b/shaders/skybox.vert index d6efb54..991fe83 100644 --- a/shaders/skybox.vert +++ b/shaders/skybox.vert @@ -3,8 +3,14 @@ // The sky box: a cube around the camera, textured from the inside by direction layout(location = 0) in vec3 aPosition; // makeCube()の頂点(±0.5) / makeCube()'s vertices (±0.5) -uniform mat4 uView; -uniform mat4 uProj; +// カメラ(ユニフォームバッファ、結合点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) +}; out vec3 vDirection; // キューブマップを引く方向 / the direction to look up the cube map with diff --git a/shaders/unlit.vert b/shaders/unlit.vert index 43847fc..bbfa5cc 100644 --- a/shaders/unlit.vert +++ b/shaders/unlit.vert @@ -1,9 +1,16 @@ #version 460 core layout(location = 0) in vec3 aPosition; +// カメラ(ユニフォームバッファ、結合点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 mat4 uView; -uniform mat4 uProj; void main() { gl_Position = uProj * uView * uModel * vec4(aPosition, 1.0); diff --git a/src/buffer.cc b/src/buffer.cc index 7c3ba57..3262bc9 100644 --- a/src/buffer.cc +++ b/src/buffer.cc @@ -7,6 +7,10 @@ Buffer::Buffer(const void *data, GLsizeiptr byteCount, GLbitfield flags) : bytes glNamedBufferStorage(handle, byteCount, data, flags); } +void Buffer::update(const void *data, GLsizeiptr byteCount, GLintptr offset) const { + glNamedBufferSubData(handle, offset, byteCount, data); +} + Buffer::~Buffer() { if (handle) glDeleteBuffers(1, &handle); } diff --git a/src/buffer.hh b/src/buffer.hh index b859176..c2d4ac5 100644 --- a/src/buffer.hh +++ b/src/buffer.hh @@ -18,6 +18,13 @@ public: Buffer(Buffer &&other) noexcept; Buffer &operator=(Buffer &&other) noexcept; + // 中身の一部を書き換える(作るときに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); } + GLuint id() const { return handle; } GLsizeiptr size() const { return bytes; } diff --git a/src/gpu_timer.cc b/src/gpu_timer.cc new file mode 100644 index 0000000..9d7d506 --- /dev/null +++ b/src/gpu_timer.cc @@ -0,0 +1,38 @@ +#include "gpu_timer.hh" + +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 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(ns) / 1.0e6; + pending[i] = false; + } + return latest; +} diff --git a/src/gpu_timer.hh b/src/gpu_timer.hh new file mode 100644 index 0000000..cd68bb4 --- /dev/null +++ b/src/gpu_timer.hh @@ -0,0 +1,33 @@ +// GPUの時間を測る:タイマークエリ(GL_TIME_ELAPSED) / measuring GPU time with timer queries (GL_TIME_ELAPSED) +#pragma once + +#include + +#include + +// begin()〜end()の間のコマンドをGPUが実行するのにかかった時間。結果は数フレーム後に届くので、クエリを +// 何個か順番に使い、届いたものから読む(待たない)。RAII、コピー不可・移動不可。 +// How long the GPU took to execute the commands between begin() and end(). The result arrives a few frames +// later, so several queries are used in turn and the ones that have arrived are read (no waiting). +// RAII, non-copyable, non-movable. +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 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 latest; +}; diff --git a/src/lights.cc b/src/lights.cc index 697b279..516f352 100644 --- a/src/lights.cc +++ b/src/lights.cc @@ -2,14 +2,12 @@ #include #include -#include -void LightSet::apply(const Shader &shader) const { - shader.set("uAmbient", ambient); - shader.set("uDirLight.direction", normalize(directional.direction)); - shader.set("uDirLight.color", directional.color); +LightsBlock LightSet::toBlock() const { + LightsBlock b{}; // 全部0(詰め物も) / all zero (the padding too) + b.directional.direction = normalize(directional.direction); + b.directional.color = directional.color; - // 配列の要素のメンバーは「名前[番号].メンバー」で設定する / array elements: "name[index].member" int pointCount = static_cast(points.size()); if (pointCount > kMaxPointLights) { fprintf(stderr, "点光源が多すぎる / too many point lights: %d (max %d)\n", pointCount, kMaxPointLights); @@ -17,11 +15,11 @@ void LightSet::apply(const Shader &shader) const { } for (int i = 0; i < pointCount; ++i) { const PointLight &p = points[static_cast(i)]; - shader.set(std::format("uPointLights[{}].position", i).c_str(), p.position); - shader.set(std::format("uPointLights[{}].color", i).c_str(), p.color); - shader.set(std::format("uPointLights[{}].attenuation", i).c_str(), p.attenuation); + b.points[i].position = p.position; + b.points[i].color = p.color; + b.points[i].attenuation = p.attenuation; } - shader.set("uPointLightCount", pointCount); + b.pointCount = pointCount; int spotCount = static_cast(spots.size()); if (spotCount > kMaxSpotLights) { @@ -30,14 +28,16 @@ void LightSet::apply(const Shader &shader) const { } for (int i = 0; i < spotCount; ++i) { const SpotLight &s = spots[static_cast(i)]; - shader.set(std::format("uSpotLights[{}].position", i).c_str(), s.position); - shader.set(std::format("uSpotLights[{}].direction", i).c_str(), normalize(s.direction)); - shader.set(std::format("uSpotLights[{}].color", i).c_str(), s.color); + 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) - shader.set(std::format("uSpotLights[{}].cosInner", i).c_str(), std::cos(s.innerAngle)); - shader.set(std::format("uSpotLights[{}].cosOuter", i).c_str(), std::cos(s.outerAngle)); - shader.set(std::format("uSpotLights[{}].attenuation", i).c_str(), s.attenuation); + b.spots[i].cosInner = std::cos(s.innerAngle); + b.spots[i].cosOuter = std::cos(s.outerAngle); + b.spots[i].attenuation = s.attenuation; } - shader.set("uSpotLightCount", spotCount); + b.spotCount = spotCount; + b.ambient = ambient; + return b; } diff --git a/src/lights.hh b/src/lights.hh index c19da01..bfa3edf 100644 --- a/src/lights.hh +++ b/src/lights.hh @@ -3,6 +3,7 @@ #include "mathx.hh" #include "shader.hh" +#include "uniforms.hh" #include @@ -42,6 +43,61 @@ struct SpotLight { Vec3 attenuation = kLongRange; }; +// ユニフォームバッファの中の光(std140の並び、第19章)。GLSLのLightsブロックと同じ: +// The lights inside the uniform buffer (std140 layout, chapter 19). Same as the GLSL Lights block: +// struct DirectionalLight { vec3 direction; vec3 color; }; // 32 bytes +// struct PointLight { vec3 position; vec3 color; vec3 attenuation; }; // 48 bytes +// struct SpotLight { vec3 position; float cosInner; vec3 direction; float cosOuter; +// vec3 color; vec3 attenuation; }; // 64 bytes +// layout(std140, binding = 1) uniform Lights { +// DirectionalLight uDirLight; // offset 0 +// PointLight uPointLights[MAX_POINT_LIGHTS]; // offset 32 (8 × 48) +// SpotLight uSpotLights[MAX_SPOT_LIGHTS]; // offset 416 (4 × 64) +// vec3 uAmbient; // offset 672 +// int uPointLightCount; // offset 684 +// int uSpotLightCount; // offset 688 +// }; // 692 → 704 bytes (a multiple of 16) +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); + // シーンの全部の光 / all the lights of a scene struct LightSet { Vec3 ambient = {0.05f, 0.05f, 0.05f}; @@ -49,7 +105,8 @@ struct LightSet { std::vector points; std::vector spots; - // 全部の光をシェーダーのユニフォームに設定する。最大数を超えた分は使わない。 - // Sets all lights as shader uniforms. Lights beyond the maximum count are ignored. - void apply(const Shader &shader) const; + // ユニフォームバッファに書く形にする(第19章。以前のapply(shader)の代わり)。最大数を超えた分は使わない。 + // Converts to the uniform-buffer layout (chapter 19; replaces the former apply(shader)). Lights beyond the + // maximum count are ignored. + LightsBlock toBlock() const; }; diff --git a/src/main.cc b/src/main.cc index 6365d04..d8848e8 100644 --- a/src/main.cc +++ b/src/main.cc @@ -1,5 +1,5 @@ -// 第18章:キューブマップ -// Chapter 18: cubemaps +// 第19章:ユニフォームバッファとインスタンシング +// Chapter 19: uniform buffers and instancing // // 操作 / Controls: // WASD 前後左右に移動 / move forward, back, left, right @@ -7,24 +7,25 @@ // Shift 速く動く / move faster // マウス / mouse 向きを変える(FPS)、左ドラッグで回る(オービット) / look around (FPS), drag with the left button to orbit // ホイール / wheel ズーム / zoom -// M 手前の3つ:いろいろ → 全部反射 → 全部屈折 → 全部フレネル -// the three objects in front: mixed → all reflection → all refraction → all Fresnel -// K 空(スカイボックス)のオン・オフ / sky box on / off -// X 継ぎ目のないキューブマップの補間(GL_TEXTURE_CUBE_MAP_SEAMLESS)のオン・オフ -// seamless cube-map filtering (GL_TEXTURE_CUBE_MAP_SEAMLESS) on / off +// I 岩:インスタンシング(描画呼び出し1回) ⇔ 一つずつ(岩の数だけ呼び出し) +// rocks: instancing (one draw call) ⇔ one by one (one draw call per rock) +// = / - 岩の数を倍に・半分に(250〜64000) / double / halve the number of rocks (250..64000) // 1〜6 効果:なし / 反転 / グレースケール / シャープ / ぼかし / エッジ検出 // effect: none / invert / grayscale / sharpen / blur / edge detection // C FPS ⇔ オービットカメラ / FPS ⇔ orbit camera // V 表示:全部 → 環境光 → 拡散 → 鏡面 → 発光 → 法線 / view: all → ambient → diffuse → specular → emission → normals // N 昼 ⇔ 夜 / day ⇔ night // F 懐中電灯のオン・オフ / flashlight on / off -// P 風車と金色の木箱を止める・回す / pause / resume the windmill and the golden crate +// P 風車と岩の環を止める・動かす / pause / resume the windmill and the ring of rocks // Tab カーソルのキャプチャ切り替え / toggle cursor capture // R シェーダーを読み直す / reload the shaders // Esc 終了 / quit +// +// 時間はウィンドウのタイトルと標準出力に出る(60フレームごと) / timings go to the window title and stdout (every 60 frames) #include "camera.hh" #include "cubemap.hh" #include "framebuffer.hh" +#include "gpu_timer.hh" #include "lights.hh" #include "material.hh" #include "mathx.hh" @@ -33,49 +34,65 @@ #include "shader.hh" #include "shapes.hh" #include "texture.hh" +#include "uniforms.hh" #include "window.hh" -#include +#include #include #include #include #include #include -// 物を置く場所:位置(底の中心)とY軸周りの回転 / where things go: position (bottom centre) and yaw struct Placement { Vec3 position; float angle; }; -static const Placement kCrates[] = { - {{5.5f, 0.0f, 1.5f}, 0.4f}, {{6.3f, 0.0f, 2.6f}, -0.3f}, {{5.9f, 1.0f, 2.0f}, 0.1f}, - {{-6.0f, 0.0f, -1.0f}, 0.8f}, {{-5.2f, 0.0f, 3.5f}, -0.6f}, -}; - -// 手前の環境マッピングの物:球二つと、木箱のモデル / the environment-mapped objects in front: two spheres and the -// crate model -enum EnvMode { kReflect = 0, kRefract = 1, kFresnel = 2 }; -struct EnvObject { - Vec3 position; - int mode; // 「いろいろ」のときのモード / the mode in "mixed" - Vec3 tint; // 反射の色(金属の色) / reflection colour (the metal's colour) -}; -static const EnvObject kEnvObjects[] = { - {{-2.8f, 0.75f, 7.0f}, kFresnel, {1.0f, 1.0f, 1.0f}}, // ガラスの球 / glass sphere - {{0.0f, 1.0f, 7.6f}, kReflect, {0.95f, 0.8f, 0.55f}}, // 金色の木箱(宙に浮いて回る) / a golden crate (hovers, tumbling) - {{2.8f, 0.75f, 7.0f}, kReflect, {0.95f, 0.95f, 0.97f}}, // クロムの球 / chrome sphere -}; - static const char *const kViewModeNames[] = {"all", "ambient", "diffuse", "specular", "emission", "normals"}; static const char *const kEffectNames[] = {"none", "invert", "grayscale", "sharpen", "blur", "edge detection"}; -static const char *const kEnvModeNames[] = {"mixed", "all reflection", "all refraction", "all Fresnel"}; + +constexpr int kMaxRocks = 64000; +constexpr float kOrbitSpeed = 0.25f; // 半径8 mでの公転の角速度(ラジアン毎秒) / orbital angular speed at radius 8 m (rad/s) static float random01(std::uint32_t &state) { state = state * 1664525u + 1013904223u; return static_cast(state >> 8) / 16777216.0f; } +// 公転の角度:内側ほど速い(ケプラー:角速度 ∝ 半径^-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); +} + +// 浮島の周りの岩の環。位置・回転・大きさ・色は決まった乱数で / the ring of rocks around the floating island; +// position, rotation, size and colour from a fixed pseudo-random sequence +static std::vector makeRing() { + std::vector 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; +} + static std::vector makeGrass() { std::vector grass; std::uint32_t seed = 16; @@ -87,37 +104,32 @@ static std::vector makeGrass() { for (Vec3 q : avoid) ok = ok && length(Vec3{p.x - q.x, 0, p.z - q.z}) > 1.1f; if (ok) grass.push_back({p, 2.0f * PI * random01(seed)}); } - const Placement front[] = {{{1.5f, 0, 6.2f}, 0.3f}, {{-4.0f, 0, 7.6f}, 1.2f}, {{3.9f, 0, 5.4f}, 2.0f}, - {{1.4f, 0, 8.9f}, 0.7f}, {{-1.6f, 0, 8.6f}, 2.6f}}; - for (const Placement &p : front) grass.push_back(p); return grass; } -// 一つのカメラから見た場面を描くのに必要なもの / what is needed to draw the scene from one camera -struct View { - Mat4 view, proj; - Vec3 position; -}; - int main() { Window window; - if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 18")) return 1; + if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 19")) return 1; std::optional phong = Shader::load("shaders/phong.vert", "shaders/phong.frag"); - std::optional post = Shader::load("shaders/post.vert", "shaders/post.frag"); + // インスタンシング用:頂点シェーダーだけ違う / for instancing: only the vertex shader differs + std::optional rocksShader = Shader::load("shaders/phong_instanced.vert", "shaders/phong.frag"); std::optional skybox = Shader::load("shaders/skybox.vert", "shaders/skybox.frag"); - // 環境マッピング:頂点シェーダーはphongと同じ(ワールド座標の位置と法線) / environment mapping: the same vertex - // shader as phong (world-space position and normal) - std::optional envmap = Shader::load("shaders/phong.vert", "shaders/envmap.frag"); + std::optional post = Shader::load("shaders/post.vert", "shaders/post.frag"); std::optional sky = Cubemap::loadDirectory("assets/textures/sky"); - std::optional floorTexture = Texture2D::load("assets/textures/floor.png"); std::optional grassTexture = Texture2D::load("assets/textures/grass_blades.png"); - if (!phong || !post || !skybox || !envmap || !sky || !floorTexture || !grassTexture) return 1; + if (!phong || !rocksShader || !skybox || !post || !sky || !grassTexture) return 1; grassTexture->setWrap(GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE); + // 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; + std::optional scene = Model::load("assets/models/diorama.glb"); - std::optional crate = Model::load("assets/models/crate.glb"); - if (!scene || !crate) return 1; + std::optional rock = Model::load("assets/models/rock.glb"); + if (!scene || !rock) return 1; const unsigned char whitePixel[4] = {255, 255, 255, 255}; Texture2D white = Texture2D::fromPixels(whitePixel, 1, 1, {.flipY = false, .mipmaps = false}); @@ -126,34 +138,51 @@ int main() { int lanternNode = scene->findNode("LanternLight"); Quat rotorStart = rotor >= 0 ? scene->nodes[static_cast(rotor)].rotation : Quat{}; + // ユニフォームバッファ:作ったときに結合点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 cameraUbo(kCameraBinding); + UniformBuffer lightsUbo(kLightsBinding); + + // インスタンスのバッファ:全部の岩を一度だけアップロード。描く数を変えても作り直さない(先頭からcount個使う) + // The instance buffer: every rock uploaded once. Changing the count does not rebuild it (the first `count` are used) + std::vector ring = makeRing(); + Buffer instanceBuffer(ring.data(), static_cast(ring.size() * sizeof(InstanceData))); + rock->setInstanceBuffer(instanceBuffer, sizeof(InstanceData), kInstanceLayout); + Camera fps; - fps.position = {0.0f, 2.0f, 12.5f}; - fps.pitch = radians(-6.0f); + fps.position = {0.0f, 6.5f, 24.0f}; + fps.pitch = radians(-12.0f); OrbitCamera orbit; - orbit.target = {0.0f, 1.0f, 4.0f}; - orbit.distance = 9.0f; + orbit.target = {0.0f, 1.5f, 0.0f}; + orbit.distance = 24.0f; orbit.yaw = radians(20.0f); - bool useOrbit = false; - int viewMode = 0, effect = 0, envMode = 0; - bool night = false, flashlightOn = false, windmillMoving = true, skyOn = true, seamless = true; - float windmillTime = 0.0f; + bool useOrbit = false, instanced = true; + int viewMode = 0, effect = 0, rockCount = 4000; + bool night = false, flashlightOn = false, moving = true; + float animTime = 0.0f; window.setCursorCaptured(true); - // 場面を描くフレームバッファ(ウィンドウと同じ大きさ) / the framebuffer the scene is drawn into (window size) Framebuffer sceneFbo(window.width(), window.height()); if (!sceneFbo.complete()) return 1; window.onResize = [&](int width, int height) { sceneFbo.resize(width, height); }; - - // キューブマップの面の境目でも隣の面と補間する(GL 3.2から、全体の設定) / filter across the edges between - // cube-map faces too (since GL 3.2, a global switch) glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS); + // 時間の集計(60フレームの平均) / timing statistics (averaged over 60 frames) + GpuTimer gpuTimer; + double cpuSum = 0.0, gpuSum = 0.0; + int cpuFrames = 0, gpuFrames = 0; + auto resetStats = [&] { + cpuSum = gpuSum = 0.0; + cpuFrames = gpuFrames = 0; + }; + window.onKey = [&](int key, int action, int /*mods*/) { if (action != GLFW_PRESS) return; if (key == GLFW_KEY_ESCAPE) window.close(); - if (key == GLFW_KEY_R && phong->reload() && post->reload() && skybox->reload() && envmap->reload()) + if (key == GLFW_KEY_R && phong->reload() && rocksShader->reload() && skybox->reload() && post->reload()) printf("シェーダーを読み直した / shaders reloaded\n"); if (key == GLFW_KEY_TAB) window.setCursorCaptured(!window.cursorCaptured()); if (key == GLFW_KEY_C) { @@ -169,32 +198,22 @@ int main() { effect = key - GLFW_KEY_1; printf("effect: %s\n", kEffectNames[effect]); } - if (key == GLFW_KEY_M) { - envMode = (envMode + 1) % 4; - printf("environment objects: %s\n", kEnvModeNames[envMode]); + if (key == GLFW_KEY_I) { + instanced = !instanced; + resetStats(); + printf("rocks: %s\n", instanced ? "instanced" : "one draw call per rock"); } - if (key == GLFW_KEY_K) skyOn = !skyOn; - if (key == GLFW_KEY_X) { - seamless = !seamless; - if (seamless) glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS); - else glDisable(GL_TEXTURE_CUBE_MAP_SEAMLESS); - printf("seamless cube-map filtering: %s\n", seamless ? "on" : "off"); + if (key == GLFW_KEY_EQUAL && rockCount < kMaxRocks) rockCount *= 2; + if (key == GLFW_KEY_MINUS && rockCount > 250) rockCount /= 2; + if (key == GLFW_KEY_EQUAL || key == GLFW_KEY_MINUS) { + resetStats(); + printf("rocks: %d\n", rockCount); } if (key == GLFW_KEY_N) night = !night; if (key == GLFW_KEY_F) flashlightOn = !flashlightOn; - if (key == GLFW_KEY_P) windmillMoving = !windmillMoving; + if (key == GLFW_KEY_P) moving = !moving; }; - // 床は空の地平線まで届くように広く(遠くはfarPlaneで切れる) / the floor is wide so it reaches the sky's horizon - // (the far plane cuts it off in the distance) - Mesh floorMesh = makePlane(160.0f, 40.0f); - Mesh sphereMesh = makeSphere(48, 24); - Mesh cubeMesh = makeCube(); // 空の箱 / the sky box - Material floorMaterial; - floorMaterial.diffuseMap = &*floorTexture; - floorMaterial.specular = {0.15f, 0.15f, 0.15f}; - floorMaterial.shininess = 16.0f; - Mesh tuftMesh = makeCrossedQuads(3); std::vector grass = makeGrass(); Material grassMaterial; @@ -202,95 +221,12 @@ int main() { grassMaterial.alphaMode = AlphaMode::Mask; grassMaterial.specular = {0.04f, 0.04f, 0.04f}; grassMaterial.shininess = 8.0f; - - // 全画面の三角形(中身は空のVAOだけ) / the fullscreen triangle (just an empty VAO inside) + Mesh cubeMesh = makeCube(); FullscreenTriangle fullscreen; glEnable(GL_CULL_FACE); - LightSet lights; - - Vec3 environmentTint; - - // 場面全体を今のフレームバッファに描く / draws the whole scene into the current framebuffer - auto drawScene = [&](const View &v) { - glEnable(GL_DEPTH_TEST); - if (night) glClearColor(0.02f, 0.03f, 0.06f, 1.0f); - else glClearColor(0.45f, 0.62f, 0.85f, 1.0f); - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); - - // 空はユニット3。phong(金属の映り込み)、envmap、skyboxのどれもここから読む - // The sky is on unit 3: phong (metal reflections), envmap and skybox all read it from there - sky->bind(3); - - phong->use(); - phong->set("uView", v.view); - phong->set("uProj", v.proj); - phong->set("uViewPos", v.position); - phong->set("uViewMode", viewMode); - phong->set("uEnvironmentTint", environmentTint); - lights.apply(*phong); - - phong->set("uModel", Mat4::identity()); - phong->set("uNormalMatrix", normalMatrix(Mat4::identity())); - floorMaterial.apply(*phong, white); - floorMesh.draw(); - scene->draw(*phong, Mat4::identity(), white, ModelPass::Opaque); - for (const Placement &c : kCrates) crate->draw(*phong, translate(c.position) * rotateY(c.angle), white, ModelPass::Opaque); - grassMaterial.apply(*phong, white); - glDisable(GL_CULL_FACE); // 草は両面 / grass is two-sided - for (const Placement &g : grass) { - Mat4 model = translate(g.position) * rotateY(g.angle) * scale({0.75f, 0.75f, 0.75f}); - phong->set("uModel", model); - phong->set("uNormalMatrix", normalMatrix(model)); - tuftMesh.draw(); - } - glEnable(GL_CULL_FACE); - - // 環境マッピングの物 / the environment-mapped objects - envmap->use(); - envmap->set("uView", v.view); - envmap->set("uProj", v.proj); - envmap->set("uViewPos", v.position); - envmap->set("uEnvironmentTint", environmentTint); - envmap->set("uIor", 1.52f); - for (size_t i = 0; i < std::size(kEnvObjects); ++i) { - const EnvObject &o = kEnvObjects[i]; - envmap->set("uEnvMode", envMode == 0 ? o.mode : envMode - 1); - envmap->set("uTint", o.tint); - if (i == 1) { - // 平らな面は一つの方向しか映さない:回すと映る空が変わる。木箱の原点は底なので、中心(0, 0.5, 0)の周りで回す - // A flat face reflects only one direction: turning it changes the sky it shows. The crate's origin is at its - // bottom, so it turns about its centre (0, 0.5, 0) - Mat4 model = translate(o.position) * rotate(normalize(Vec3{1.0f, 1.0f, 0.3f}), 0.6f * windmillTime + 0.8f) * - translate({0.0f, -0.5f, 0.0f}); - crate->drawGeometry(*envmap, model); // uModelとuNormalMatrixだけ / only uModel and uNormalMatrix - } else { - Mat4 model = translate(o.position) * scale({1.5f, 1.5f, 1.5f}); - envmap->set("uModel", model); - envmap->set("uNormalMatrix", normalMatrix(model)); - sphereMesh.draw(); - } - } - - // 空は不透明な物の後に:見えているピクセルだけ塗る(深度1のところ)。半透明な物があればその前 - // The sky after the opaque objects: it only fills pixels nothing covers (depth 1). Before any transparent ones - if (skyOn) { - // 空の深度はちょうど1.0。クリアした値も1.0なので、GL_LESSでは通らない:GL_LEQUALにする - // The sky's depth is exactly 1.0, the same as the cleared value, so GL_LESS would reject it: use GL_LEQUAL - glDepthFunc(GL_LEQUAL); - // 箱を内側から見るので、見えるのは裏面:カリングを切る / we see the box from inside, i.e. its back faces: no culling - glDisable(GL_CULL_FACE); - skybox->use(); - skybox->set("uView", v.view); - skybox->set("uProj", v.proj); - skybox->set("uEnvironmentTint", environmentTint); - cubeMesh.draw(); - glEnable(GL_CULL_FACE); - glDepthFunc(GL_LESS); - } - }; - + int frame = 0; double lastTime = window.time(); while (!window.shouldClose()) { double now = window.time(); @@ -316,22 +252,23 @@ int main() { fps.move(dir, dt); } - if (windmillMoving) windmillTime += dt; + if (moving) animTime += dt; if (rotor >= 0) scene->nodes[static_cast(rotor)].rotation = - Quat::fromAxisAngle({0.0f, 0.0f, 1.0f}, -0.8f * windmillTime) * rotorStart; + Quat::fromAxisAngle({0.0f, 0.0f, 1.0f}, -0.8f * animTime) * rotorStart; - // アスペクト比は描き込むフレームバッファのもの(ウィンドウとは限らない) - // The aspect ratio is that of the framebuffer drawn into (not necessarily the window) + // カメラのブロック:フレームに一度書けば、全部のシェーダーが読む(シェーダーごとのset()は要らない) + // The camera block: written once per frame, read by every shader (no per-shader set() any more) float aspect = static_cast(sceneFbo.width()) / static_cast(sceneFbo.height()); - View main; - main.view = useOrbit ? orbit.view() : fps.view(); - main.proj = useOrbit ? orbit.projection(aspect) : fps.projection(aspect); - main.position = useOrbit ? orbit.position() : fps.position; + 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); Vec3 viewDir = useOrbit ? normalize(orbit.target - orbit.position()) : fps.front(); - environmentTint = night ? Vec3{0.05f, 0.06f, 0.11f} : Vec3{1.0f, 1.0f, 1.0f}; - lights = LightSet{}; + LightSet lights; if (!night) { lights.ambient = {0.28f, 0.30f, 0.34f}; lights.directional = {.direction = {-0.5f, -1.0f, -0.35f}, .color = {0.95f, 0.9f, 0.8f}}; @@ -344,22 +281,99 @@ int main() { } } if (flashlightOn) - lights.spots.push_back({.position = main.position, .direction = viewDir, .color = {1.0f, 0.95f, 0.85f}}); + 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 + Vec3 environmentTint = night ? Vec3{0.05f, 0.06f, 0.11f} : Vec3{1.0f, 1.0f, 1.0f}; - // 1. 場面をフレームバッファに描く / 1. draw the scene into the framebuffer + //------------------------------------------------------------------ + // 1. 場面をフレームバッファに / 1. the scene into the framebuffer + //------------------------------------------------------------------ sceneFbo.bind(); - drawScene(main); + glEnable(GL_DEPTH_TEST); + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); + sky->bind(3); + + // ビュー・射影・光はもう設定しない:ブロックから来る / 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); + grassMaterial.apply(*phong, white); + glDisable(GL_CULL_FACE); + for (const Placement &g : grass) { + Mat4 model = translate(g.position) * rotateY(g.angle) * scale({0.75f, 0.75f, 0.75f}); + phong->set("uModel", model); + phong->set("uNormalMatrix", normalMatrix(model)); + tuftMesh.draw(); + } + glEnable(GL_CULL_FACE); - // 2. 画面へ:全画面の三角形でフレームバッファのテクスチャを貼り、効果をかける - // 3. To the screen: a fullscreen triangle samples the framebuffer's texture and applies the effect + // 岩の環:ここだけ時間を測る / the ring of rocks: only this part is timed + gpuTimer.begin(); + auto cpuStart = std::chrono::steady_clock::now(); + 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(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}); + } + double cpuMs = std::chrono::duration(std::chrono::steady_clock::now() - cpuStart).count(); + gpuTimer.end(); + + // 空(第18章) / the sky (chapter 18) + glDepthFunc(GL_LEQUAL); + glDisable(GL_CULL_FACE); + skybox->use(); + skybox->set("uEnvironmentTint", environmentTint); + cubeMesh.draw(); + glEnable(GL_CULL_FACE); + glDepthFunc(GL_LESS); + + //------------------------------------------------------------------ + // 2. 画面へ(第17章) / 2. to the screen (chapter 17) + //------------------------------------------------------------------ Framebuffer::bindDefault(window.width(), window.height()); - glDisable(GL_DEPTH_TEST); // 三角形一つだけ:深度は要らない / a single triangle: no depth needed + glDisable(GL_DEPTH_TEST); post->use(); post->set("uEffect", effect); post->set("uFlipX", 0); sceneFbo.color().bind(0); fullscreen.draw(); + // 時間の集計:60フレームごとにタイトルと標準出力へ / timing: every 60 frames to the title and stdout + cpuSum += cpuMs; + ++cpuFrames; + if (std::optional gpu = gpuTimer.latestMs()) { + gpuSum += *gpu; + ++gpuFrames; + } + if (++frame % 60 == 0) { + int calls = instanced ? 1 : rockCount; + char text[256]; + snprintf(text, sizeof text, "OpenGL Tutorial - Chapter 19 | %d rocks, %s: %d draw call%s, CPU %.2f ms, GPU %.2f ms", + rockCount, instanced ? "instanced" : "one by one", calls, calls == 1 ? "" : "s", cpuSum / cpuFrames, + gpuFrames > 0 ? gpuSum / gpuFrames : 0.0); + window.setTitle(text); + printf("%s\n", text + 31); // 「OpenGL Tutorial - Chapter 19 | 」の後ろ / after "OpenGL Tutorial - Chapter 19 | " + resetStats(); + } + window.swapBuffers(); } return 0; diff --git a/src/mesh.cc b/src/mesh.cc index df3d988..7142058 100644 --- a/src/mesh.cc +++ b/src/mesh.cc @@ -56,3 +56,21 @@ void Mesh::draw() const { glDrawArrays(primitive, 0, vertexCount); } } + +void Mesh::setInstanceBuffer(const Buffer &buffer, GLsizei stride, std::span 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); +} + +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); +} diff --git a/src/mesh.hh b/src/mesh.hh index 7c75c73..4205eb4 100644 --- a/src/mesh.hh +++ b/src/mesh.hh @@ -55,6 +55,21 @@ constexpr VertexAttrib kModelVertexLayout[] = { {3, 4, offsetof(ModelVertex, tangent)}, // layout(location = 3) in vec4 aTangent(第22章 / chapter 22) }; +// インスタンスごとのデータ(第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 +}; + // 一つの描画単位(RAII、コピー不可・移動可)。インデックスが空ならglDrawArraysで描く。 // One drawable unit (RAII, non-copyable, movable). With no indices it draws with glDrawArrays. class Mesh { @@ -75,6 +90,14 @@ public: Mesh &operator=(Mesh &&other) noexcept; void draw() const; + // 同じメッシュをcount回描く(インスタンシング、第19章)。インスタンスごとのデータはsetInstanceBufferで繋ぐ + // Draws the same mesh count times (instancing, chapter 19). Per-instance data comes from setInstanceBuffer + void drawInstanced(GLsizei count) const; + // インスタンスごとの属性のバッファをバインディング1に繋ぐ:頂点ごとではなく、インスタンスごとに次の要素へ進む + // (divisor = 1)。layoutのlocationは頂点の属性(0〜3)と重ならないこと。 + // Attaches a buffer of per-instance attributes to binding 1: it advances once per instance instead of once per + // vertex (divisor = 1). The layout's locations must not overlap the vertex attributes (0..3). + void setInstanceBuffer(const Buffer &buffer, GLsizei stride, std::span layout); GLuint vao() const { return vertexArray; } diff --git a/src/model.cc b/src/model.cc index e34f3d4..70eeb2c 100644 --- a/src/model.cc +++ b/src/model.cc @@ -315,8 +315,19 @@ void Model::collect(int node, const Mat4 &parentWorld, const Mat4 &transform, bo for (int child : n.children) collect(child, world, transform, hierarchy, pass, viewPos, out); } +void Model::setInstanceBuffer(const Buffer &buffer, GLsizei stride, std::span 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 items; + for (int root : roots) collect(root, Mat4::identity(), Mat4::identity(), true, ModelPass::All, {}, items); + drawItems(items, shader, &white, shader.has("uNormalMatrix"), count); +} + void Model::drawItems(const std::vector &items, const Shader &shader, const Texture2D *white, - bool normals) const { + bool normals, GLsizei instances) const { bool culling = glIsEnabled(GL_CULL_FACE); // 呼ぶ側の設定を覚えておく / remember the caller's setting for (const DrawItem &item : items) { const Primitive &p = *item.primitive; @@ -333,7 +344,8 @@ void Model::drawItems(const std::vector &items, const Shader &shader, // Double-sided materials (leaves, glass, sails) must be visible from behind: no culling for them bool noCull = culling && md.phong.doubleSided; if (noCull) glDisable(GL_CULL_FACE); - p.mesh.draw(); + if (instances > 0) p.mesh.drawInstanced(instances); + else p.mesh.draw(); if (noCull) glEnable(GL_CULL_FACE); } } diff --git a/src/model.hh b/src/model.hh index 4d58138..153e5bb 100644 --- a/src/model.hh +++ b/src/model.hh @@ -8,6 +8,7 @@ #include "texture.hh" #include +#include #include #include #include @@ -70,6 +71,15 @@ public: // For passes that need no colour: the depth view, outlines, and later shadows (chapter 23). void drawGeometry(const Shader &shader, const Mat4 &transform) const; + // インスタンシング(第19章):全部のプリミティブのVAOにインスタンスのバッファを繋ぐ(Mesh::setInstanceBuffer) + // Instancing (chapter 19): attaches the instance buffer to every primitive's VAO (Mesh::setInstanceBuffer) + void setInstanceBuffer(const Buffer &buffer, GLsizei stride, std::span layout); + // count個のインスタンスを、プリミティブごとに描画呼び出し1回で描く。uModelはノードのモデル座標の行列で、 + // インスタンスの行列はシェーダーで掛ける(phong_instanced.vert:world = aInstanceModel × uModel × 位置)。 + // Draws count instances with one draw call per primitive. uModel is the node's model-space matrix; the shader + // multiplies the instance matrix on top (phong_instanced.vert: world = aInstanceModel × uModel × position). + void drawInstanced(const Shader &shader, const Texture2D &white, GLsizei count) const; + // 名前でノードを探す。なければ-1 / finds a node by name; -1 if none int findNode(std::string_view name) const; // ノードのモデル座標での行列(ルートからの積)。描く場所はtransform × これ @@ -98,7 +108,8 @@ private: void collect(int node, const Mat4 &parentWorld, const Mat4 &transform, bool hierarchy, ModelPass pass, Vec3 viewPos, std::vector &out) const; // white == nullptrなら形だけ(drawGeometry) / white == nullptr: shape only (drawGeometry) - void drawItems(const std::vector &items, const Shader &shader, const Texture2D *white, bool normals) const; + void drawItems(const std::vector &items, const Shader &shader, const Texture2D *white, bool normals, + GLsizei instances = 0) const; const MaterialData &materialOf(const Primitive &p) const; const Texture2D *texture(int index) const; // なければnullptr / nullptr if missing diff --git a/src/shader.cc b/src/shader.cc index 1882ed1..ec27c84 100644 --- a/src/shader.cc +++ b/src/shader.cc @@ -183,3 +183,22 @@ void Shader::set(const char *name, const Mat4 &m) const { // linalg.hhは列優先なので転置しない(GL_FALSE) / linalg.hh is column-major, so no transpose (GL_FALSE) glProgramUniformMatrix4fv(program, location(name), 1, GL_FALSE, &m.c[0].x); } + +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) + 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; +} diff --git a/src/shader.hh b/src/shader.hh index 46b8562..9a91427 100644 --- a/src/shader.hh +++ b/src/shader.hh @@ -41,6 +41,14 @@ public: void set(const char *name, const Mat3 &value) const; void set(const char *name, const Mat4 &value) const; + // ユニフォームブロックの大きさ(GLが決めたバイト数)。プログラムになければ-1(第19章) + // The size of a uniform block in bytes, as the GL laid it out. -1 if the program has no such block (chapter 19) + GLint uniformBlockSize(const char *blockName) const; + // ブロックの大きさがC++の構造体と合うか確かめる。違えばエラーを表示してfalse。ブロックがなければtrue。 + // Checks that a block's size matches the C++ struct. Prints an error and returns false if not; true if the + // program has no such block. + bool checkUniformBlock(const char *blockName, size_t cppSize) const; + // そのユニフォームがプログラムで使われているか(警告は出さない) / does the program use that uniform? (no warning) bool has(const char *name) const { return glGetUniformLocation(program, name) >= 0; } diff --git a/src/uniforms.hh b/src/uniforms.hh new file mode 100644 index 0000000..2271638 --- /dev/null +++ b/src/uniforms.hh @@ -0,0 +1,66 @@ +// ユニフォームバッファ(UBO):いくつものシェーダーで共有するユニフォームのまとまり(第19章) +// Uniform buffers (UBOs): blocks of uniforms shared by many shaders (chapter 19) +#pragma once + +#include "buffer.hh" + +#include + +#include + +// 結合点の番号。シェーダーの 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) + +// std140の規則(よく使うものだけ) / the std140 rules (the common ones) +// float, int, bool : 4バイト、4の倍数に置く / 4 bytes, at a multiple of 4 +// vec2 : 8バイト、8の倍数 / 8 bytes, at a multiple of 8 +// vec3, vec4 : 12・16バイト、16の倍数(vec3の後ろの4バイトにはfloatが一つ入る) +// 12 / 16 bytes, at a multiple of 16 (one float fits in the 4 bytes after a vec3) +// mat4 : vec4の列が4本、64バイト、16の倍数 / four vec4 columns, 64 bytes, at a multiple of 16 +// 配列 / arrays : 要素ごとに16の倍数に切り上げ(float[4]でも64バイト) / every element rounded up to 16 (even float[4] is 64 bytes) +// 構造体 / structs : 16の倍数に置き、大きさも16の倍数に切り上げ / start at a multiple of 16, size rounded up to 16 +// C++の構造体は同じ並びになるように、詰め物(pad)を自分で入れる。static_assertで確かめる。 +// The C++ structs get explicit padding so they have the same layout; static_assert checks it. + +// 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); + +// 一つのブロックの中身を持つユニフォームバッファ(RAII、コピー不可・移動可)。作るときに結合点に繋ぐ。 +// A uniform buffer holding one block (RAII, non-copyable, movable). Attached to its binding point when created. +template +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; +};