diff --git a/CMakeLists.txt b/CMakeLists.txt index 9ec8755..d4814ec 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -44,7 +44,9 @@ add_executable(game src/framebuffer.cc src/cubemap.cc src/gpu_timer.cc - src/tangents.cc) + src/tangents.cc + src/ibl.cc + src/pbr_material.cc) target_include_directories(game PRIVATE src external/stb external/linalg) target_link_libraries(game PRIVATE glad stb_image glfw) diff --git a/shaders/ibl_brdf.frag b/shaders/ibl_brdf.frag new file mode 100644 index 0000000..f915f1c --- /dev/null +++ b/shaders/ibl_brdf.frag @@ -0,0 +1,60 @@ +#version 460 core +// IBL(第24章):スプリットサムの後半=BRDFの積分の表(LUT)。x = n·v、y = 粗さ → (A, B)。 +// 鏡面のIBL = ぼかした映り込み × (F0 · A + B)。光と関係ないので、どの場面でも同じ表 +// IBL (chapter 24): the second half of the split sum = a table (LUT) of the BRDF integral. x = n·v, y = roughness → +// (A, B). Specular IBL = blurred reflection × (F0 · A + B). It does not depend on the lighting: the same for any scene +in vec2 vUv; + +layout(location = 0) out vec4 out_color; + +const float PI = 3.14159265359; +const uint kSamples = 256u; + +// ハマースリー点列:0〜1の正方形に均一に散らばる点(乱数より速く収束する) / the Hammersley sequence: points spread evenly +// over the unit square (converges faster than random numbers) +vec2 hammersley(uint i, uint n) { + return vec2(float(i) / float(n), float(bitfieldReverse(i)) * 2.3283064365386963e-10); +} + +// GGXの分布に従って半ベクトルHを選ぶ(重点的サンプリング)。Nの周りの接線空間で作ってワールドへ +// Picks a half vector H following the GGX distribution (importance sampling), built in tangent space around N +vec3 importanceSampleGgx(vec2 xi, vec3 n, float roughness) { + float a = roughness * roughness; + float phi = 2.0 * PI * xi.x; + float cosTheta = sqrt((1.0 - xi.y) / (1.0 + (a * a - 1.0) * xi.y)); + float sinTheta = sqrt(1.0 - cosTheta * cosTheta); + vec3 h = vec3(cos(phi) * sinTheta, sin(phi) * sinTheta, cosTheta); + vec3 up = abs(n.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0); + vec3 t = normalize(cross(up, n)); + vec3 b = cross(n, t); + return normalize(t * h.x + b * h.y + n * h.z); +} + +// IBL用のSchlick-GGXの幾何項:k = α/2(直接光ではk = (r+1)²/8) / the Schlick-GGX geometry term for IBL: k = α/2 +// (for direct light k = (r+1)²/8) +float geometrySchlick(float nDotX, float roughness) { + float k = roughness * roughness / 2.0; + return nDotX / (nDotX * (1.0 - k) + k); +} + +void main() { + float nDotV = max(vUv.x, 1e-3); + float roughness = vUv.y; + vec3 v = vec3(sqrt(1.0 - nDotV * nDotV), 0.0, nDotV); + vec3 n = vec3(0.0, 0.0, 1.0); + float a = 0.0, b = 0.0; + for (uint i = 0u; i < kSamples; ++i) { + vec3 h = importanceSampleGgx(hammersley(i, kSamples), n, roughness); + vec3 l = normalize(2.0 * dot(v, h) * h - v); + float nDotL = max(l.z, 0.0); + float nDotH = max(h.z, 0.0); + float vDotH = max(dot(v, h), 0.0); + if (nDotL <= 0.0) continue; + float g = geometrySchlick(nDotV, roughness) * geometrySchlick(nDotL, roughness); + float gVis = g * vDotH / (nDotH * nDotV); + float fc = pow(1.0 - vDotH, 5.0); // フレネルを F0 · (1 − fc) + fc に分けて二つの数にする / split Fresnel into two numbers + a += (1.0 - fc) * gVis; + b += fc * gVis; + } + out_color = vec4(a / float(kSamples), b / float(kSamples), 0.0, 1.0); +} diff --git a/shaders/ibl_irradiance.frag b/shaders/ibl_irradiance.frag new file mode 100644 index 0000000..9ca1c90 --- /dev/null +++ b/shaders/ibl_irradiance.frag @@ -0,0 +1,52 @@ +#version 460 core +// IBL(第24章):放射照度のキューブマップ。各方向Nについて、半球全体から来る空の光をcosθで重み付けして平均する。 +// 結果は「白い拡散面がNを向いていたら反射する明るさ」(= 放射照度E / π)。pbr.fragはベースカラーを掛けるだけ +// IBL (chapter 24): the irradiance cube map. For each direction N, average the sky light arriving from the whole +// hemisphere weighted by cos θ. The result is "how bright a white diffuse surface facing N looks" (= irradiance E / π); +// pbr.frag only multiplies it by the base colour +layout(binding = 0) uniform samplerCube uEnvironment; +uniform int uFace; +uniform float uSize; // この面の大きさ(ピクセル) / this face's size (pixels) +uniform float uSourceLod; // 空のどのミップマップから読むか(小さい段で十分、速い) / which sky mip level to read + // (a small one is enough, and fast) + +layout(location = 0) out vec4 out_color; + +const float PI = 3.14159265359; + +// キューブマップの面faceのピクセル(gl_FragCoord.xy)が表す方向。第18章の表(行0 = t = 0、上の行) +// The direction of pixel gl_FragCoord.xy on cube face `face`. The table of chapter 18 (row 0 = t = 0, the top row) +vec3 faceDirection(int face, vec2 fragCoord, float size) { + float sc = 2.0 * fragCoord.x / size - 1.0; + float tc = 2.0 * fragCoord.y / size - 1.0; + vec3 d; + if (face == 0) d = vec3(1.0, -tc, -sc); // +X + else if (face == 1) d = vec3(-1.0, -tc, sc); // -X + else if (face == 2) d = vec3(sc, 1.0, tc); // +Y + else if (face == 3) d = vec3(sc, -1.0, -tc); // -Y + else if (face == 4) d = vec3(sc, -tc, 1.0); // +Z + else d = vec3(-sc, -tc, -1.0); // -Z + return normalize(d); +} + +void main() { + vec3 n = faceDirection(uFace, gl_FragCoord.xy, uSize); + vec3 up = abs(n.y) < 0.999 ? vec3(0.0, 1.0, 0.0) : vec3(1.0, 0.0, 0.0); + vec3 right = normalize(cross(up, n)); + up = cross(n, right); + // 半球を等間隔の角度で:φ(周り)0〜2π、θ(天頂から)0〜π/2。sinθは小さな立体角の補正 + // The hemisphere in equal angle steps: φ (around) 0..2π, θ (from the zenith) 0..π/2. sin θ corrects the solid angle + const float delta = 0.08; + vec3 sum = vec3(0.0); + float count = 0.0; + for (float phi = 0.0; phi < 2.0 * PI; phi += delta) { + for (float theta = 0.0; theta < 0.5 * PI; theta += delta) { + vec3 t = vec3(sin(theta) * cos(phi), sin(theta) * sin(phi), cos(theta)); // 接線空間 / tangent space + vec3 dir = t.x * right + t.y * up + t.z * n; + sum += textureLod(uEnvironment, dir, uSourceLod).rgb * cos(theta) * sin(theta); + count += 1.0; + } + } + // ∫L cosθ dω ≈ (π²/count)Σ…(= E)。÷π で拡散反射の明るさ / ≈ (π²/count) Σ ... (= E); ÷ π gives the diffuse brightness + out_color = vec4(PI * sum / count, 1.0); +} diff --git a/shaders/ibl_prefilter.frag b/shaders/ibl_prefilter.frag new file mode 100644 index 0000000..25d7fc6 --- /dev/null +++ b/shaders/ibl_prefilter.frag @@ -0,0 +1,81 @@ +#version 460 core +// IBL(第24章):粗さごとにぼかした映り込み(スプリットサムの前半)。ミップマップの段mは粗さ m/(段数−1)。 +// GGXで重点的サンプリングし、N = V = R と仮定する(Karisの近似)。ぼかしが粗い点はぼけた空のミップマップから読む +// IBL (chapter 24): reflections blurred per roughness (the first half of the split sum). Mip level m is roughness +// m/(levels − 1). Importance-sampled with GGX assuming N = V = R (Karis' approximation). Coarse samples read a blurrier +// sky mip level +layout(binding = 0) uniform samplerCube uEnvironment; +uniform int uFace; +uniform float uSize; // この段の面の大きさ / this level's face size +uniform float uRoughness; +uniform float uSourceSize; // 空の0段目の面の大きさ / the sky's level-0 face size + +layout(location = 0) out vec4 out_color; + +const float PI = 3.14159265359; +const uint kSamples = 64u; + +// キューブマップの面faceのピクセル(gl_FragCoord.xy)が表す方向。第18章の表(行0 = t = 0、上の行) +// The direction of pixel gl_FragCoord.xy on cube face `face`. The table of chapter 18 (row 0 = t = 0, the top row) +vec3 faceDirection(int face, vec2 fragCoord, float size) { + float sc = 2.0 * fragCoord.x / size - 1.0; + float tc = 2.0 * fragCoord.y / size - 1.0; + vec3 d; + if (face == 0) d = vec3(1.0, -tc, -sc); // +X + else if (face == 1) d = vec3(-1.0, -tc, sc); // -X + else if (face == 2) d = vec3(sc, 1.0, tc); // +Y + else if (face == 3) d = vec3(sc, -1.0, -tc); // -Y + else if (face == 4) d = vec3(sc, -tc, 1.0); // +Z + else d = vec3(-sc, -tc, -1.0); // -Z + return normalize(d); +} +// ハマースリー点列:0〜1の正方形に均一に散らばる点(乱数より速く収束する) / the Hammersley sequence: points spread evenly +// over the unit square (converges faster than random numbers) +vec2 hammersley(uint i, uint n) { + return vec2(float(i) / float(n), float(bitfieldReverse(i)) * 2.3283064365386963e-10); +} + +// GGXの分布に従って半ベクトルHを選ぶ(重点的サンプリング)。Nの周りの接線空間で作ってワールドへ +// Picks a half vector H following the GGX distribution (importance sampling), built in tangent space around N +vec3 importanceSampleGgx(vec2 xi, vec3 n, float roughness) { + float a = roughness * roughness; + float phi = 2.0 * PI * xi.x; + float cosTheta = sqrt((1.0 - xi.y) / (1.0 + (a * a - 1.0) * xi.y)); + float sinTheta = sqrt(1.0 - cosTheta * cosTheta); + vec3 h = vec3(cos(phi) * sinTheta, sin(phi) * sinTheta, cosTheta); + vec3 up = abs(n.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0); + vec3 t = normalize(cross(up, n)); + vec3 b = cross(n, t); + return normalize(t * h.x + b * h.y + n * h.z); +} + +float distributionGgx(float nDotH, float roughness) { + float a = roughness * roughness; + float a2 = a * a; + float d = nDotH * nDotH * (a2 - 1.0) + 1.0; + return a2 / (PI * d * d); +} + +void main() { + vec3 n = faceDirection(uFace, gl_FragCoord.xy, uSize); + vec3 v = n; // 正面から見ていると仮定 / assume we look at it head-on + vec3 sum = vec3(0.0); + float weight = 0.0; + // 空の1テクセルの立体角 / the solid angle of one sky texel + float texelSolidAngle = 4.0 * PI / (6.0 * uSourceSize * uSourceSize); + for (uint i = 0u; i < kSamples; ++i) { + vec3 h = importanceSampleGgx(hammersley(i, kSamples), n, uRoughness); + vec3 l = normalize(2.0 * dot(v, h) * h - v); + float nDotL = dot(n, l); + if (nDotL <= 0.0) continue; + // この点が受け持つ立体角に合うミップマップの段(少ない点でも縞にならない) + // The mip level whose texel matches the solid angle this sample stands for (no banding with few samples) + float nDotH = max(dot(n, h), 0.0); + float pdf = distributionGgx(nDotH, uRoughness) * nDotH / (4.0 * max(dot(h, v), 0.0)) + 1e-4; + float sampleSolidAngle = 1.0 / (float(kSamples) * pdf); + float lod = uRoughness == 0.0 ? 0.0 : 0.5 * log2(sampleSolidAngle / texelSolidAngle) + 1.0; + sum += textureLod(uEnvironment, l, lod).rgb * nDotL; + weight += nDotL; + } + out_color = vec4(sum / weight, 1.0); +} diff --git a/shaders/pbr.frag b/shaders/pbr.frag new file mode 100644 index 0000000..437a751 --- /dev/null +++ b/shaders/pbr.frag @@ -0,0 +1,366 @@ +#version 460 core +// 物理ベースレンダリング(第24章):Cook–Torrance(GGX・Smith-Schlick-GGX・Fresnel–Schlick)、glTFの金属・粗さ、 +// 直接光(影付き)+空からのイメージベースドライティング。頂点シェーダーはphong.vert(またはphong_instanced.vert) +// Physically based rendering (chapter 24): Cook–Torrance (GGX, Smith-Schlick-GGX, Fresnel–Schlick), glTF's +// metallic-roughness, direct light (shadowed) + image-based lighting from the sky. Vertex shader: phong.vert (or +// phong_instanced.vert) +in vec3 vWorldPos; +in vec3 vNormal; +in vec2 vUv; +in vec3 vTint; +in vec4 vTangent; + +// glTFのpbrMetallicRoughnessと同じ(係数 × テクスチャ) / the same as glTF's pbrMetallicRoughness (factor × texture) +struct Material { + vec4 baseColor; // リニア、aは不透明度 / linear, a = opacity + float metallic; + float roughness; + vec3 emissive; + float normalScale; // 0 = 法線マップなし / 0 = no normal map + float parallaxScale; // 0 = 視差なし / 0 = no parallax + float occlusionStrength; + int alphaMode; // 0 = 不透明 / opaque, 1 = マスク / mask, 2 = ブレンド / blend + float alphaCutoff; + bool doubleSided; +}; +uniform Material uMaterial; + +layout(binding = 0) uniform sampler2D uBaseColorMap; // sRGB +layout(binding = 2) uniform sampler2D uEmissiveMap; // sRGB +layout(binding = 4) uniform sampler2D uNormalMap; // リニア、A = 高さ / linear, A = height +layout(binding = 5) uniform sampler2DShadow uShadowMap; // 第23章 / chapter 23 +layout(binding = 7) uniform sampler2D uMetallicRoughnessMap; // G = 粗さ / roughness, B = 金属度 / metallic +layout(binding = 8) uniform sampler2D uOcclusionMap; // R = 環境光の遮蔽 / ambient occlusion +layout(binding = 9) uniform samplerCube uIrradianceMap; // 拡散のIBL / diffuse IBL +layout(binding = 10) uniform samplerCube uPrefilteredMap; // 鏡面のIBL(粗さ = ミップマップ) / specular IBL (roughness = mip) +layout(binding = 11) uniform sampler2D uBrdfLut; // スプリットサムの表 / the split-sum table +uniform vec3 uEnvironmentTint; // 空の明るさ(昼1、夜は暗く):IBLに掛ける / brightness of the sky: multiplies the IBL + +// 光の構造体。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) + 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; +}; + +// カメラ(ユニフォームバッファ、結合点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) +}; + +// 影(ユニフォームバッファ、結合点2、std140)。使う全部のシェーダーで同じ宣言(C++ではShadowBlock) +// Shadows (uniform buffer, binding 2, std140). The same declaration in every shader that uses it (ShadowBlock in C++) +layout(std140, binding = 2) uniform Shadow { + mat4 uLightSpace; // ワールド → 光のクリップ座標 / world → the light's clip space + float uShadowBias; // 一定のバイアス(0〜1の深度) / constant bias (0..1 depth) + float uShadowSlopeBias; // 傾きに比例するバイアス / slope-scaled bias + float uShadowNormalOffset; // 法線方向のずらし(m) / normal offset (m) + int uShadowFilter; // 0 = 硬い / hard, 1 = 2×2, 2 = PCF 3×3, 3 = PCF 5×5 + vec2 uShadowTexel; // 1テクセルのUV / one texel in UV + int uShadowsEnabled; + int uShadowPad; +}; + +// 0 = 全部、1 = ベースカラー、2 = 金属度、3 = 粗さ、4 = 遮蔽、5 = 法線、6 = 直接光だけ、7 = IBLだけ、8 = 影 +// 0 = everything, 1 = base colour, 2 = metallic, 3 = roughness, 4 = occlusion, 5 = normals, 6 = direct light only, +// 7 = IBL only, 8 = shadow +uniform int uViewMode; +// 0 = 直接光+IBL、1 = 直接光だけ、2 = IBLだけ / 0 = direct + IBL, 1 = direct only, 2 = IBL only +uniform int uLighting = 0; +uniform bool uAlphaToCoverage = false; // 第20章 / chapter 20 +uniform bool uParallaxMapping = true; // 第22章 / chapter 22 + +#define ALPHA_OPAQUE 0 +#define ALPHA_MASK 1 +#define ALPHA_BLEND 2 + +const float PI = 3.14159265359; + +layout(location = 0) out vec4 out_color; + +// 後処理の設定(ユニフォームバッファ、結合点3、std140、第21章)。使う全部のシェーダーで同じ宣言(C++ではPostBlock) +// Post-processing settings (uniform buffer, binding 3, std140, chapter 21). The same declaration in every shader that +// uses it (PostBlock in C++) +layout(std140, binding = 3) uniform Post { + float uExposure; // 明るさの倍率 / brightness multiplier + float uBloomStrength; // ブルームの強さ / bloom strength + float uBloomThreshold; // これより明るい部分が光る(リニアのHDR値) / brighter than this glows (linear HDR value) + int uToneMapper; // 0 = クランプ / clamp, 1 = Reinhard, 2 = ACES + int uGammaMode; // 0 = シェーダー / shader, 1 = GL_FRAMEBUFFER_SRGB, 2 = なし / none, 3 = 二重 / double + int uPostView; // 0 = 完成 / final, 1 = ブルームなし / no bloom, 2 = 明るい部分 / bright part, 3 = ブルーム / bloom + int uPostPad0, uPostPad1; // std140の大きさを32バイトにそろえる / pads the block to 32 bytes +}; + +// ブルーム用の2つ目の出力(MRT、GL_COLOR_ATTACHMENT1):しきい値より明るい部分だけ(色合いは保つ) +// The second output for bloom (MRT, GL_COLOR_ATTACHMENT1): only what is brighter than the threshold (hue kept) +layout(location = 1) out vec4 out_bright; +vec3 brightPart(vec3 c) { + float l = dot(c, vec3(0.2126, 0.7152, 0.0722)); // 輝度 / luminance + return c * (max(l - uBloomThreshold, 0.0) / max(l, 1e-4)); +} + +//------------------------------------------------------------------ +// Cook–TorranceのBRDF:f = kd · base/π + D · G · F / (4 (n·l)(n·v)) +// The Cook–Torrance BRDF: f = kd · base/π + D · G · F / (4 (n·l)(n·v)) +//------------------------------------------------------------------ + +// D:法線の分布(GGX / Trowbridge-Reitz)。微小な面のうち、hを向いているものの割合。α = 粗さ²(glTF・UE4と同じ) +// D: the normal distribution (GGX / Trowbridge-Reitz): the share of microfacets facing h. α = roughness² (as glTF/UE4) +float distributionGgx(float nDotH, float roughness) { + float a = roughness * roughness; + float a2 = a * a; + float d = nDotH * nDotH * (a2 - 1.0) + 1.0; + return a2 / (PI * d * d); +} + +// G:幾何減衰(Smith法にSchlick-GGX)。微小な面が互いに影を作り、隠し合う分。直接光ではk = (r + 1)² / 8 +// G: geometric attenuation (Smith with Schlick-GGX): microfacets shadowing and masking each other. k = (r + 1)² / 8 for +// direct light +float geometrySmith(float nDotV, float nDotL, float roughness) { + float k = (roughness + 1.0) * (roughness + 1.0) / 8.0; + float gv = nDotV / (nDotV * (1.0 - k) + k); + float gl = nDotL / (nDotL * (1.0 - k) + k); + return gv * gl; +} + +// F:フレネル(Schlickの近似)。斜めから見るほど鏡のように反射する / F: Fresnel (Schlick's approximation): the more +// grazing the view, the more mirror-like +vec3 fresnelSchlick(float cosTheta, vec3 f0) { + return f0 + (1.0 - f0) * pow(clamp(1.0 - cosTheta, 0.0, 1.0), 5.0); +} +// IBL用:粗い面では斜めでも1まで上がらない(Sébastien Lagarde) / for IBL: rough surfaces do not reach 1 at grazing angles +vec3 fresnelSchlickRoughness(float cosTheta, vec3 f0, float roughness) { + return f0 + (max(vec3(1.0 - roughness), f0) - f0) * pow(clamp(1.0 - cosTheta, 0.0, 1.0), 5.0); +} + +struct Surface { + vec3 n, v; + vec3 base; // ベースカラー(リニア) / base colour (linear) + float metallic, roughness; + vec3 f0; // 正面の反射率:非金属0.04、金属はベースカラー / reflectance at normal incidence: 0.04 for dielectrics, + // the base colour for metals +}; + +// 一つの光の直接光。radiance = 面に届く光(光の色 × 減衰 × 影) +// Direct light from one light. radiance = the light reaching the surface (light colour × attenuation × shadow) +vec3 directLight(Surface s, vec3 l, vec3 radiance) { + float nDotL = max(dot(s.n, l), 0.0); + if (nDotL <= 0.0) return vec3(0.0); + vec3 h = normalize(l + s.v); + float nDotV = max(dot(s.n, s.v), 1e-4); + float nDotH = max(dot(s.n, h), 0.0); + float d = distributionGgx(nDotH, s.roughness); + float g = geometrySmith(nDotV, nDotL, s.roughness); + vec3 f = fresnelSchlick(max(dot(h, s.v), 0.0), s.f0); + vec3 specular = d * g * f / (4.0 * nDotV * nDotL + 1e-4); + // エネルギー保存:反射した分(F)は拡散しない。金属は拡散しない / energy conservation: what is reflected (F) does not + // diffuse, and metals do not diffuse at all + vec3 kd = (1.0 - f) * (1.0 - s.metallic); + // このシリーズの光の色は「正面から照らした白い拡散面の明るさ」(Blinn-Phongと同じ意味)。物理的なランバートは + // base/πなので、光の強さをπ倍して同じ明るさにする + // Our light colours mean "how bright a white diffuse surface lit head-on looks" (as with Blinn-Phong). Physical + // Lambert is base/π, so the light is scaled by π to get the same brightness + return (kd * s.base / PI + specular) * radiance * PI * nDotL; +} + +float attenuate(float d, vec3 k) { + return 1.0 / (k.x + k.y * d + k.z * d * d); +} + +// 平行光源の影(第23章):このピクセルを光のクリップ座標に移し、影の地図の深度と比べる。1 = 光が当たる、0 = 影。 +// n = 頂点の法線(法線マップ前)、l = 光へ向かう向き +// Directional-light shadow (chapter 23): move this pixel into the light's clip space and compare with the shadow map's +// depth. 1 = lit, 0 = in shadow. n = the vertex normal (before normal mapping), l = towards the light +float shadowFactor(vec3 worldPos, vec3 n, vec3 l) { + if (uShadowsEnabled == 0) return 1.0; + float cosTheta = clamp(dot(n, l), 0.0, 1.0); + // 法線方向に少しずらす(斜めの面ほど多く):影の地図の1テクセルの中で面が自分を影にする「シャドウアクネ」を防ぐ + // Push the point a little along the normal (more on tilted surfaces): prevents "shadow acne", where a surface shadows + // itself inside one shadow-map texel + vec3 p = worldPos + n * (uShadowNormalOffset * (1.0 - cosTheta)); + vec4 clip = uLightSpace * vec4(p, 1.0); + vec3 c = clip.xyz / clip.w * 0.5 + 0.5; // NDC → 0..1(UVと深度) / NDC → 0..1 (UV and depth) + if (c.z > 1.0) return 1.0; // 光の箱より奥:影なし / beyond the light's box: not shadowed + // 傾きに比例するバイアス:光に対して斜めな面ほど1テクセルの中の深度の差が大きい(tanθに比例) + // Slope-scaled bias: the more a surface tilts away from the light, the larger the depth change within one texel (∝ tan θ) + float tanTheta = sqrt(max(1.0 - cosTheta * cosTheta, 0.0)) / max(cosTheta, 0.05); + c.z -= uShadowBias + uShadowSlopeBias * min(tanTheta, 10.0); + if (uShadowFilter <= 1) return texture(uShadowMap, c); // 1回:GL_NEARESTなら硬い、GL_LINEARなら2×2 / one lookup + // PCF(percentage-closer filtering):周りの何点かで比べた結果を平均する(深度を平均するのではない) + // PCF (percentage-closer filtering): average the RESULTS of comparisons around the point (not the depths) + int r = uShadowFilter == 2 ? 1 : 2; + float sum = 0.0; + for (int y = -r; y <= r; ++y) + for (int x = -r; x <= r; ++x) sum += texture(uShadowMap, vec3(c.xy + vec2(x, y) * uShadowTexel, c.z)); + return sum / float((2 * r + 1) * (2 * r + 1)); +} + +// 視差オクルージョンマッピング(第22章):目から表面の奥へ、高さマップの層を一枚ずつ進み、最初に高さマップの +// 下に入った所のUVを返す(前の層との間は直線で補間)。v = 接線空間の目への向き。 +// ループの中は分岐なので、ミップマップの段は外で求めた微分で指定する(textureGrad) +// Parallax occlusion mapping (chapter 22): march from the eye into the surface one height layer at a time and return +// the UV where the ray first goes below the height map (interpolated linearly with the previous layer). v = the +// direction to the eye in tangent space. Inside the loop we are in a branch, so the mip level comes from derivatives +// computed outside (textureGrad) +vec2 parallaxOcclusion(vec2 uv, vec3 v, vec2 dx, vec2 dy) { + float layers = mix(32.0, 8.0, clamp(v.z, 0.0, 1.0)); // 斜めほど多く / more layers at grazing angles + float layerDepth = 1.0 / layers; + // 一層ごとのUVのずれ:視線の傾き(xy / z)× 深さ / the UV step per layer: the view's slope (xy / z) × depth + vec2 delta = v.xy / max(v.z, 0.1) * uMaterial.parallaxScale / layers; + float depth = 0.0; + float mapDepth = 1.0 - textureGrad(uNormalMap, uv, dx, dy).a; // 深さ = 1 − 高さ / depth = 1 − height + for (int i = 0; i < 32 && depth < mapDepth; ++i) { + uv -= delta; + mapDepth = 1.0 - textureGrad(uNormalMap, uv, dx, dy).a; + depth += layerDepth; + } + // 最後の2層の間で交点を補間 / interpolate the crossing between the last two layers + vec2 prev = uv + delta; + float after = mapDepth - depth; + float before = (1.0 - textureGrad(uNormalMap, prev, dx, dy).a) - depth + layerDepth; + float w = after / (after - before + 1e-6); + return mix(uv, prev, w); +} + +void main() { + // 接線空間(第22章) / tangent space (chapter 22) + vec3 geometricNormal = normalize(vNormal); + vec3 tangent = vTangent.xyz - dot(vTangent.xyz, geometricNormal) * geometricNormal; + bool hasTangent = dot(tangent, tangent) > 1e-10; + tangent = hasTangent ? normalize(tangent) : vec3(1.0, 0.0, 0.0); + vec3 bitangent = cross(geometricNormal, tangent) * (vTangent.w < 0.0 ? -1.0 : 1.0); + if (uMaterial.doubleSided && !gl_FrontFacing) geometricNormal = -geometricNormal; + + vec2 uv = vUv; + vec2 uvDx = dFdx(vUv), uvDy = dFdy(vUv); + if (uParallaxMapping && uMaterial.parallaxScale > 0.0 && hasTangent) { + vec3 toEye = normalize(uViewPos - vWorldPos); + uv = parallaxOcclusion(vUv, vec3(dot(toEye, tangent), dot(toEye, bitangent), dot(toEye, geometricNormal)), uvDx, uvDy); + } + + // ベースカラーとアルファ(第16・20章と同じ扱い) / base colour and alpha (handled as in chapters 16 and 20) + vec4 baseSample = textureGrad(uBaseColorMap, uv, uvDx, uvDy); + float alpha = uMaterial.baseColor.a * baseSample.a; + float alphaWidth = fwidth(alpha); + if (uMaterial.alphaMode == ALPHA_MASK && uAlphaToCoverage) { + alpha = (alpha - uMaterial.alphaCutoff) / max(alphaWidth, 1e-4) + 0.5; + if (alpha <= 0.0) discard; + } else if (uMaterial.alphaMode == ALPHA_MASK && alpha < uMaterial.alphaCutoff) { + discard; + } + if (uMaterial.alphaMode == ALPHA_BLEND && alpha < 1.0 / 255.0) discard; + + Surface s; + s.n = geometricNormal; + if (hasTangent && uMaterial.normalScale > 0.0) { + vec3 m = textureGrad(uNormalMap, uv, uvDx, uvDy).xyz * 2.0 - 1.0; + m.xy *= uMaterial.normalScale; + s.n = normalize(m.x * tangent + m.y * bitangent + m.z * geometricNormal); + } + s.v = normalize(uViewPos - vWorldPos); + s.base = uMaterial.baseColor.rgb * baseSample.rgb * vTint; + vec4 mr = textureGrad(uMetallicRoughnessMap, uv, uvDx, uvDy); + s.metallic = clamp(uMaterial.metallic * mr.b, 0.0, 1.0); + // 粗さ0はGGXが一点に潰れて光が消える:少しだけ残す / roughness 0 collapses GGX to a point and the highlight vanishes: + // keep a little + s.roughness = clamp(uMaterial.roughness * mr.g, 0.03, 1.0); + s.f0 = mix(vec3(0.04), s.base, s.metallic); + float occlusion = 1.0 + uMaterial.occlusionStrength * (textureGrad(uOcclusionMap, uv, uvDx, uvDy).r - 1.0); + vec3 emissive = uMaterial.emissive * textureGrad(uEmissiveMap, uv, uvDx, uvDy).rgb; + + //------------------------------------------------------------------ + // 直接光:太陽(影付き)、点光源、スポットライト / direct light: the sun (shadowed), point lights, spotlights + //------------------------------------------------------------------ + vec3 direct = vec3(0.0); + float shadow = shadowFactor(vWorldPos, geometricNormal, -uDirLight.direction); + direct += directLight(s, -uDirLight.direction, uDirLight.color * shadow); + for (int i = 0; i < uPointLightCount; ++i) { + vec3 toLight = uPointLights[i].position - vWorldPos; + float d = length(toLight); + direct += directLight(s, toLight / d, uPointLights[i].color * attenuate(d, uPointLights[i].attenuation)); + } + for (int i = 0; i < uSpotLightCount; ++i) { + vec3 toLight = uSpotLights[i].position - vWorldPos; + float d = length(toLight); + vec3 l = toLight / d; + float cone = smoothstep(uSpotLights[i].cosOuter, uSpotLights[i].cosInner, dot(-l, uSpotLights[i].direction)); + if (cone <= 0.0) continue; + direct += directLight(s, l, uSpotLights[i].color * attenuate(d, uSpotLights[i].attenuation) * cone); + } + + //------------------------------------------------------------------ + // IBL:空からの光。拡散 = 放射照度 × ベースカラー、鏡面 = ぼかした映り込み × (F0 · A + B)(スプリットサム) + // IBL: light from the sky. Diffuse = irradiance × base colour, specular = blurred reflection × (F0 · A + B) (split sum) + //------------------------------------------------------------------ + float nDotV = max(dot(s.n, s.v), 1e-4); + vec3 f = fresnelSchlickRoughness(nDotV, s.f0, s.roughness); + vec3 kd = (1.0 - f) * (1.0 - s.metallic); + vec3 irradiance = texture(uIrradianceMap, s.n).rgb; + vec3 r = reflect(-s.v, s.n); + float maxLod = float(textureQueryLevels(uPrefilteredMap) - 1); + vec3 prefiltered = textureLod(uPrefilteredMap, r, s.roughness * maxLod).rgb; + vec2 brdf = texture(uBrdfLut, vec2(nDotV, s.roughness)).rg; + // 鏡面はF0のまま:フレネルはBRDF LUTの中で積分済み(fを使うと二重になる) / the specular uses F0 itself: the BRDF + // LUT already integrates Fresnel (using f would apply it twice) + vec3 specular = prefiltered * (s.f0 * brdf.x + brdf.y); + // 遮蔽(AO)は環境光だけに掛ける(glTFの決まり) / occlusion only affects the environment light (as glTF says) + vec3 ibl = (kd * irradiance * s.base + specular) * occlusion * uEnvironmentTint; + + vec3 color = emissive; + if (uLighting != 2) color += direct; + if (uLighting != 1) color += ibl; + if (uViewMode == 1) color = s.base; + else if (uViewMode == 2) color = vec3(s.metallic); + else if (uViewMode == 3) color = vec3(s.roughness); + else if (uViewMode == 4) color = vec3(occlusion); + else if (uViewMode == 5) color = s.n * 0.5 + 0.5; + else if (uViewMode == 6) color = direct; + else if (uViewMode == 7) color = ibl; + else if (uViewMode == 8) color = vec3(shadow); + // データの表示(2〜5、8)は、sRGBにされた後でちょうどこの値になるように先にリニアへ / data views (2-5, 8): converted + // to linear first so that after the sRGB encoding the screen shows exactly this value + if ((uViewMode >= 2 && uViewMode <= 5) || uViewMode == 8) + color = mix(color / 12.92, pow((color + 0.055) / 1.055, vec3(2.4)), step(vec3(0.04045), color)); + + bool coverage = uMaterial.alphaMode == ALPHA_MASK && uAlphaToCoverage; + out_color = vec4(color, uMaterial.alphaMode == ALPHA_BLEND || coverage ? clamp(alpha, 0.0, 1.0) : 1.0); + out_bright = vec4(uViewMode == 0 ? brightPart(color) : vec3(0.0), out_color.a); +} diff --git a/src/ibl.cc b/src/ibl.cc new file mode 100644 index 0000000..8d54592 --- /dev/null +++ b/src/ibl.cc @@ -0,0 +1,113 @@ +#include "ibl.hh" + +#include +#include +#include +#include +#include + +namespace { + +// 面ごとに描くための、色の付け先だけのFBO(RAII) / an FBO with only a colour attachment, for drawing face by face (RAII) +struct FaceTarget { + GLuint fbo = 0, vao = 0; + FaceTarget() { + glCreateFramebuffers(1, &fbo); + glCreateVertexArrays(1, &vao); // 全画面の三角形(post.vert)用の空のVAO / empty VAO for the fullscreen triangle + } + ~FaceTarget() { + glDeleteFramebuffers(1, &fbo); + glDeleteVertexArrays(1, &vao); + } + FaceTarget(const FaceTarget &) = delete; + FaceTarget &operator=(const FaceTarget &) = delete; + + // キューブマップの面face・ミップマップの段levelに描く:glNamedFramebufferTextureLayerのlayerが面の番号 + // Draws into face `face`, mip level `level` of a cube map: the layer of glNamedFramebufferTextureLayer is the face + void drawFace(const Cubemap &cube, int level, int face, int size) const { + glNamedFramebufferTextureLayer(fbo, GL_COLOR_ATTACHMENT0, cube.id(), level, face); + glBindFramebuffer(GL_FRAMEBUFFER, fbo); + glViewport(0, 0, size, size); + glBindVertexArray(vao); + glDrawArrays(GL_TRIANGLES, 0, 3); + } +}; + +double elapsedMs(std::chrono::steady_clock::time_point start) { + // 本当に描き終わるまで待つ(GPUはコマンドを溜めてから実行する) / wait until drawing really finished (the GPU queues + // commands and runs them later) + glFinish(); + return std::chrono::duration(std::chrono::steady_clock::now() - start).count(); +} + +} // namespace + +std::optional Ibl::build(const Cubemap &environment, const IblSettings &settings) { + std::optional irradianceShader = Shader::load("shaders/post.vert", "shaders/ibl_irradiance.frag"); + std::optional prefilterShader = Shader::load("shaders/post.vert", "shaders/ibl_prefilter.frag"); + std::optional brdfShader = Shader::load("shaders/post.vert", "shaders/ibl_brdf.frag"); + if (!irradianceShader || !prefilterShader || !brdfShader) return std::nullopt; + + Ibl ibl; + FaceTarget target; + glDisable(GL_DEPTH_TEST); + glDisable(GL_BLEND); + environment.bind(0); + + // 1. 放射照度(拡散の環境光):ミップマップなし / 1. irradiance (diffuse environment light): no mipmaps + auto start = std::chrono::steady_clock::now(); + ibl.irradianceMap = Cubemap(settings.irradianceSize, GL_RGBA16F, 1); + irradianceShader->use(); + irradianceShader->set("uSize", static_cast(settings.irradianceSize)); + // 空の32×32くらいの段で十分 / a sky level of about 32 × 32 is enough + float sourceLod = std::max(0.0f, std::log2(static_cast(environment.size()) / 32.0f)); + irradianceShader->set("uSourceLod", sourceLod); + for (int face = 0; face < 6; ++face) { + irradianceShader->set("uFace", face); + target.drawFace(ibl.irradianceMap, 0, face, settings.irradianceSize); + } + ibl.buildMs[0] = elapsedMs(start); + + // 2. ぼかした映り込み(鏡面の環境光):段ごとに粗さを上げる / 2. blurred reflections (specular environment light): + // more roughness on every mip level + start = std::chrono::steady_clock::now(); + ibl.prefilteredMap = Cubemap(settings.prefilteredSize, GL_RGBA16F, settings.prefilteredLevels); + prefilterShader->use(); + prefilterShader->set("uSourceSize", static_cast(environment.size())); + for (int level = 0; level < settings.prefilteredLevels; ++level) { + int size = std::max(1, settings.prefilteredSize >> level); + prefilterShader->set("uSize", static_cast(size)); + // 段が1つだけなら粗さ0の段だけ(0で割らない) / a single level is just roughness 0 (no division by zero) + float roughness = settings.prefilteredLevels > 1 + ? static_cast(level) / static_cast(settings.prefilteredLevels - 1) + : 0.0f; + prefilterShader->set("uRoughness", roughness); + for (int face = 0; face < 6; ++face) { + prefilterShader->set("uFace", face); + target.drawFace(ibl.prefilteredMap, level, face, size); + } + } + ibl.buildMs[1] = elapsedMs(start); + + // 3. BRDFの表:普通の2Dテクスチャ(赤と緑の2チャンネル、半精度) / 3. the BRDF table: an ordinary 2D texture + // (red and green, half floats) + start = std::chrono::steady_clock::now(); + ibl.brdfFbo = Framebuffer(settings.brdfLutSize, settings.brdfLutSize, {.colorFormat = GL_RG16F, .depthStencilFormat = 0}); + ibl.brdfFbo.bind(); + brdfShader->use(); + glBindVertexArray(target.vao); + glDrawArrays(GL_TRIANGLES, 0, 3); + ibl.buildMs[2] = elapsedMs(start); + + glBindFramebuffer(GL_FRAMEBUFFER, 0); + printf("IBL: irradiance %d² %.0f ms, prefiltered %d² × %d levels %.0f ms, BRDF LUT %d² %.0f ms\n", + settings.irradianceSize, ibl.buildMs[0], settings.prefilteredSize, settings.prefilteredLevels, ibl.buildMs[1], + settings.brdfLutSize, ibl.buildMs[2]); + return ibl; +} + +void Ibl::bind() const { + irradianceMap.bind(kIrradianceUnit); + prefilteredMap.bind(kPrefilteredUnit); + brdfFbo.color().bind(kBrdfLutUnit); +} diff --git a/src/ibl.hh b/src/ibl.hh new file mode 100644 index 0000000..6b5ee29 --- /dev/null +++ b/src/ibl.hh @@ -0,0 +1,46 @@ +// イメージベースドライティング(IBL、第24章):空のキューブマップから、拡散と鏡面の環境光の表を起動時に作る +// Image-based lighting (IBL, chapter 24): builds the diffuse and specular environment-light tables from the sky cube map +// at start-up +#pragma once + +#include "cubemap.hh" +#include "framebuffer.hh" +#include "shader.hh" + +#include + +// 結合するテクスチャユニット(pbr.fragのlayout(binding = …)と同じ) / the texture units (same as layout(binding = ...) +// in pbr.frag) +constexpr GLuint kIrradianceUnit = 9; +constexpr GLuint kPrefilteredUnit = 10; +constexpr GLuint kBrdfLutUnit = 11; + +struct IblSettings { + int irradianceSize = 32; // 放射照度は滑らかなので小さくて良い / irradiance is smooth: small is enough + int prefilteredSize = 128; // ぼかした映り込みの0段目(粗さ0) / level 0 of the blurred reflections (roughness 0) + int prefilteredLevels = 5; // 128, 64, 32, 16, 8:粗さ0, 0.25, 0.5, 0.75, 1 / roughness 0, 0.25, 0.5, 0.75, 1 + int brdfLutSize = 128; +}; + +// IBLの3つの表(RAII、コピー不可・移動可)。作り方はシェーダー:ibl_irradiance.frag、ibl_prefilter.frag、ibl_brdf.frag +// The three IBL tables (RAII, non-copyable, movable). Made by shaders: ibl_irradiance.frag, ibl_prefilter.frag, +// ibl_brdf.frag +class Ibl { +public: + // environmentから作る(ミップマップ付きのキューブマップ)。シェーダーが読めなければstd::nullopt。かかった時間を表示する + // Builds from `environment` (a cube map with mipmaps). std::nullopt if the shaders cannot be loaded. Prints the time taken + static std::optional build(const Cubemap &environment, const IblSettings &settings = {}); + + // ユニット9、10、11に繋ぐ / binds to units 9, 10 and 11 + void bind() const; + + const Cubemap &irradiance() const { return irradianceMap; } + const Cubemap &prefiltered() const { return prefilteredMap; } + const Texture2D &brdfLut() const { return brdfFbo.color(); } + double buildMs[3] = {0.0, 0.0, 0.0}; // 放射照度、映り込み、LUT(ミリ秒) / irradiance, reflections, LUT (ms) + +private: + Cubemap irradianceMap; + Cubemap prefilteredMap; + Framebuffer brdfFbo; // 色のテクスチャがLUT(GL_RG16F) / its colour texture is the LUT (GL_RG16F) +}; diff --git a/src/main.cc b/src/main.cc index 3ea7c48..6ac219a 100644 --- a/src/main.cc +++ b/src/main.cc @@ -1,5 +1,5 @@ -// 第23章:シャドウマッピング -// Chapter 23: shadow mapping +// 第24章:物理ベースレンダリング +// Chapter 24: physically based rendering // // 操作 / Controls: // WASD 前後左右に移動 / move forward, back, left, right @@ -7,18 +7,13 @@ // Shift 速く動く / move faster // マウス / mouse 向きを変える(FPS)、左ドラッグで回る(オービット) / look around (FPS), drag with the left button to orbit // ホイール / wheel ズーム / zoom +// M PBR ⇔ Blinn-Phong(比較) / PBR ⇔ Blinn-Phong (comparison) +// L 光:直接光+IBL → 直接光だけ → IBLだけ / lighting: direct + IBL → direct only → IBL only +// K 見る場所:場面 → 球の格子(金属度 × 粗さ) → 見本の球 / look at: the scene → the sphere grid +// (metallic × roughness) → the sample spheres +// V 表示(PBR):全部 → ベースカラー → 金属度 → 粗さ → 遮蔽 → 法線 → 直接光 → IBL → 影 +// view (PBR): all → base colour → metallic → roughness → occlusion → normals → direct → IBL → shadow // H 影のオン・オフ / shadows on / off -// B バイアス:なし → 一定 → 傾き+法線ずらし → glPolygonOffset → 大きすぎ(ピーターパン) -// bias: none → constant → slope-scaled + normal offset → glPolygonOffset → too large (peter-panning) -// K 影の地図を描くときのカリング:裏面 → 表面 → なし / culling in the shadow pass: back → front → none -// G 影のフィルター:硬い → 2×2(ハードウェア) → PCF 3×3 → PCF 5×5 -// shadow filter: hard → 2 × 2 (hardware) → PCF 3 × 3 → PCF 5 × 5 -// J 光の箱:場面全体 ⇔ カメラの視錐台(手前8 m) / light box: whole scene ⇔ camera frustum (first 8 m) -// Z 影の地図の大きさ:512 → 1024 → 2048 → 4096 / shadow map size -// O 影の地図を左下に表示 / show the shadow map at the bottom left -// V 表示:全部 → 環境光 → 拡散 → 鏡面 → 発光 → 法線 → 頂点の法線 → 接線 → 従法線 → 影 -// view: all → ambient → diffuse → specular → emission → normals → vertex normals → tangents → -// bitangents → shadow // = / - 露出を上げる・下げる / exposure up / down // 1〜6 効果:なし / 反転 / グレースケール / シャープ / ぼかし / エッジ検出 // effect: none / invert / grayscale / sharpen / blur / edge detection @@ -32,11 +27,13 @@ #include "camera.hh" #include "cubemap.hh" #include "framebuffer.hh" +#include "ibl.hh" #include "lights.hh" #include "material.hh" #include "mathx.hh" #include "mesh.hh" #include "model.hh" +#include "pbr_material.hh" #include "shader.hh" #include "shapes.hh" #include "texture.hh" @@ -48,6 +45,7 @@ #include #include #include +#include #include // 物を置く場所:位置(底の中心)とY軸周りの回転 / where things go: position (bottom centre) and yaw @@ -64,9 +62,11 @@ static const Placement kCrates[] = { constexpr int kMsaaSamples = 4; // 第20章 / chapter 20 constexpr int kBloomPasses = 4; // 横+縦の組の数 / number of horizontal + vertical pairs -static const char *const kViewModeNames[] = {"all", "ambient", "diffuse", "specular", "emission", - "normals", "vertex normals", "tangents", "bitangents", "shadow"}; -constexpr int kViewModes = 10; +static const char *const kPbrViewNames[] = {"all", "base colour", "metallic", "roughness", "occlusion", + "normals", "direct only", "IBL only", "shadow"}; +static const char *const kPhongViewNames[] = {"all", "ambient", "diffuse", "specular", "emission", + "normals", "vertex normals", "tangents", "bitangents", "shadow"}; +static const char *const kLightingNames[] = {"direct + IBL", "direct only", "IBL only"}; // 影のバイアスの方法 / the shadow bias methods struct BiasMode { @@ -86,8 +86,6 @@ static const BiasMode kBiasModes[] = { {"too large: 40 cm (peter-panning)", 0.4f, 0.0f, 0.0f, false, false}, }; constexpr size_t kDefaultBias = 2; -static const char *const kCullNames[] = {"back faces", "front faces", "none"}; -static const char *const kFilterNames[] = {"hard (GL_NEAREST)", "hardware 2x2 (GL_LINEAR)", "PCF 3x3", "PCF 5x5"}; constexpr int kShadowSizes[] = {512, 1024, 2048, 4096}; // 平行光源の光から見た行列:centreを中心とする半径radiusの球を正射影の箱に収める。箱は影の地図の1テクセル単位で @@ -127,7 +125,7 @@ static std::vector makeGrass() { 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}, {{0.2f, 0, 10.0f}, 1.9f}}; + {{0.2f, 0, 10.0f}, 1.9f}}; for (const Placement &p : front) grass.push_back(p); return grass; } @@ -195,7 +193,7 @@ static std::vector makeLanterns() { int main() { Window window; - if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 23")) return 1; + if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 24")) return 1; // 画面(既定のフレームバッファ)がsRGBか:GL_FRAMEBUFFER_SRGBが効くのはsRGBのときだけ // Is the screen (the default framebuffer) sRGB? GL_FRAMEBUFFER_SRGB only has an effect if it is @@ -204,6 +202,8 @@ int main() { printf("default framebuffer encoding: %s\n", encoding == GL_SRGB ? "sRGB" : "linear"); std::optional phong = Shader::load("shaders/phong.vert", "shaders/phong.frag"); + // PBR:頂点シェーダーはphongと同じ / PBR: the same vertex shader as phong + std::optional pbr = Shader::load("shaders/phong.vert", "shaders/pbr.frag"); std::optional skybox = Shader::load("shaders/skybox.vert", "shaders/skybox.frag"); std::optional post = Shader::load("shaders/post.vert", "shaders/post.frag"); std::optional blur = Shader::load("shaders/post.vert", "shaders/blur.frag"); @@ -221,11 +221,11 @@ int main() { // 影の地図を描くシェーダーと、それを見せるシェーダー / the shader that draws the shadow map and the one that shows it std::optional shadowShader = Shader::load("shaders/shadow.vert", "shaders/shadow.frag"); std::optional shadowDebug = Shader::load("shaders/post.vert", "shaders/shadow_debug.frag"); - if (!phong || !skybox || !post || !blur || !unlit || !sky || !floorTexture || !grassTexture || !brickTexture || + if (!phong || !pbr || !skybox || !post || !blur || !unlit || !sky || !floorTexture || !grassTexture || !brickTexture || !brickNormal || !leavesTexture || !shadowShader || !shadowDebug) return 1; grassTexture->setWrap(GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE); - for (const Shader *s : {&*phong, &*skybox, &*post, &*unlit, &*shadowShader}) + for (const Shader *s : {&*phong, &*pbr, &*skybox, &*post, &*unlit, &*shadowShader}) if (!s->checkUniformBlock("Camera", sizeof(CameraBlock)) || !s->checkUniformBlock("Lights", sizeof(LightsBlock)) || !s->checkUniformBlock("Post", sizeof(PostBlock)) || !s->checkUniformBlock("Shadow", sizeof(ShadowBlock))) return 1; @@ -237,6 +237,14 @@ int main() { std::optional barrel = Model::load("assets/models/barrel.glb"); if (!scene || !crate || !barrel) return 1; + // IBL:空から、拡散(放射照度)・鏡面(ぼかした映り込み)・BRDFの表を一度だけ作る(第24章) + // IBL: build the diffuse (irradiance), specular (blurred reflections) and BRDF tables from the sky once (chapter 24) + // 作る前にシームレスなフィルタリングを有効にする:ぼかす時に面の辺をまたいで読む(18.6節) + // Seamless filtering must be on before building: the blurring reads across the faces' edges (section 18.6) + glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS); + std::optional ibl = Ibl::build(*sky); + if (!ibl) return 1; + const unsigned char whitePixel[4] = {255, 255, 255, 255}; Texture2D white = Texture2D::fromPixels(whitePixel, 1, 1, {.flipY = false, .mipmaps = false}); @@ -285,7 +293,6 @@ int main() { sceneFbo.resize(width, height); for (Framebuffer &f : bloomFbo) f.resize(width / 2, height / 2); }; - glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS); Camera fps; fps.position = {0.6f, 3.6f, 12.5f}; @@ -296,9 +303,12 @@ int main() { orbit.distance = 11.0f; orbit.yaw = radians(20.0f); - bool useOrbit = false, shadowsOn = true, fitFrustum = false, showShadowMap = false; - size_t biasMode = kDefaultBias; - int cullMode = 0, shadowFilter = static_cast(ShadowFilter::Pcf3x3); + bool useOrbit = false, shadowsOn = true, usePbr = true; + int lighting = 0, place = 0; + // 第23章の影の設定(この章では固定。キーは第23章) / the chapter 23 shadow settings (fixed here; the keys are in ch23) + const bool fitFrustum = false, showShadowMap = false; + const size_t biasMode = kDefaultBias; + const int cullMode = 0, shadowFilter = static_cast(ShadowFilter::Pcf3x3); int viewMode = 0, effect = 0; float exposureEv = 0.0f; // 露出(段、EV):倍率は2^EV / exposure in stops (EV): the multiplier is 2^EV PostBlock postSettings; @@ -309,9 +319,16 @@ int main() { 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() && skybox->reload() && post->reload() && blur->reload() && unlit->reload() && - shadowShader->reload() && shadowDebug->reload()) - printf("シェーダーを読み直した / shaders reloaded\n"); + // IBLのシェーダー(ibl_*.frag)は作るときだけ使う:読み直す = IBLを作り直す(失敗したら前のIBLのまま) + // The IBL shaders (ibl_*.frag) are only used while building: reloading them = rebuilding the IBL (the old one stays + // if that fails) + if (key == GLFW_KEY_R && phong->reload() && pbr->reload() && skybox->reload() && post->reload() && blur->reload() && + unlit->reload() && shadowShader->reload() && shadowDebug->reload()) { + if (std::optional rebuilt = Ibl::build(*sky)) { + ibl = std::move(rebuilt); + printf("シェーダーを読み直した / shaders reloaded\n"); + } + } if (key == GLFW_KEY_TAB) window.setCursorCaptured(!window.cursorCaptured()); if (key == GLFW_KEY_C) { useOrbit = !useOrbit; @@ -319,8 +336,27 @@ int main() { printf("camera: %s\n", useOrbit ? "orbit" : "fps"); } if (key == GLFW_KEY_V) { - viewMode = (viewMode + 1) % kViewModes; - printf("view: %s\n", kViewModeNames[viewMode]); + viewMode = (viewMode + 1) % (usePbr ? 9 : 10); + printf("view: %s\n", usePbr ? kPbrViewNames[viewMode] : kPhongViewNames[viewMode]); + } + if (key == GLFW_KEY_M) { + usePbr = !usePbr; + viewMode = 0; + printf("shading: %s\n", usePbr ? "PBR (Cook-Torrance + IBL)" : "Blinn-Phong"); + } + if (key == GLFW_KEY_L) { + lighting = (lighting + 1) % 3; + printf("lighting: %s\n", kLightingNames[lighting]); + } + if (key == GLFW_KEY_K) { + // 決まった場所にカメラを置く / put the camera at a fixed place + place = (place + 1) % 3; + useOrbit = false; + const Vec3 positions[] = {{0.6f, 3.6f, 12.5f}, {0.0f, 5.5f, 36.5f}, {0.0f, 1.3f, 11.4f}}; + const float pitches[] = {-17.0f, 0.0f, -14.0f}; + fps.position = positions[place]; + fps.yaw = 0.0f; + fps.pitch = radians(pitches[place]); } if (key >= GLFW_KEY_1 && key <= GLFW_KEY_6) { effect = key - GLFW_KEY_1; @@ -334,60 +370,33 @@ int main() { shadowsOn = !shadowsOn; printf("shadows: %s\n", shadowsOn ? "on" : "off"); } - if (key == GLFW_KEY_B) { - biasMode = (biasMode + 1) % std::size(kBiasModes); - printf("shadow bias: %s\n", kBiasModes[biasMode].name); - } - if (key == GLFW_KEY_K) { - cullMode = (cullMode + 1) % 3; - printf("shadow pass culling: %s\n", kCullNames[cullMode]); - } - if (key == GLFW_KEY_G) { - shadowFilter = (shadowFilter + 1) % 4; - printf("shadow filter: %s\n", kFilterNames[shadowFilter]); - } - if (key == GLFW_KEY_J) { - fitFrustum = !fitFrustum; - printf("light box: %s\n", fitFrustum ? "camera frustum (0.1-8 m)" : "whole scene"); - } - if (key == GLFW_KEY_Z) { - shadowSizeIndex = (shadowSizeIndex + 1) % std::size(kShadowSizes); - shadowFbo = Framebuffer(kShadowSizes[shadowSizeIndex], kShadowSizes[shadowSizeIndex], shadowSpec); - printf("shadow map: %d x %d\n", shadowFbo.width(), shadowFbo.height()); - } - if (key == GLFW_KEY_O) showShadowMap = !showShadowMap; if (key == GLFW_KEY_N) night = !night; if (key == GLFW_KEY_F) flashlightOn = !flashlightOn; if (key == GLFW_KEY_P) windmillMoving = !windmillMoving; }; + // 手で作るマテリアルはすべてPbrMaterial(第24章)。Blinn-Phongで描くときはtoBlinnPhongで変換する。 + // 手で選んだ色はsRGBの値なのでsrgbToLinearでリニアに + // Every hand-made material is a PbrMaterial (chapter 24); for Blinn-Phong they are converted with toBlinnPhong. + // Hand-picked colours are sRGB values, so srgbToLinear makes them linear + auto rgb = [](float r, float g, float b, float a = 1.0f) { + Vec3 c = srgbToLinear(Vec3{r, g, b}); + return Vec4{c.x, c.y, c.z, a}; + }; Mesh floorMesh = makePlane(160.0f, 40.0f); Mesh cubeMesh = makeCube(); - Material floorMaterial; - floorMaterial.diffuseMap = &*floorTexture; - floorMaterial.specular = {0.15f, 0.15f, 0.15f}; - floorMaterial.shininess = 16.0f; + PbrMaterial floorMaterial{.roughness = 0.65f, .baseColorMap = &*floorTexture}; Mesh tuftMesh = makeCrossedQuads(3); std::vector grass = makeGrass(); - Material grassMaterial; - grassMaterial.diffuseMap = &*grassTexture; - grassMaterial.alphaMode = AlphaMode::Mask; - grassMaterial.specular = {0.04f, 0.04f, 0.04f}; - grassMaterial.shininess = 8.0f; + PbrMaterial grassMaterial{.roughness = 0.9f, .alphaMode = AlphaMode::Mask, .baseColorMap = &*grassTexture}; std::vector wires = makeWires(); - // レンガの壁(5 × 2.5 m、厚さ0.3 m)、柱、球。箱のUVはメートル単位で、1 mごとにテクスチャ1枚 - // The brick wall (5 × 2.5 m, 0.3 m thick), a pillar and a sphere. Box UVs are in metres, one texture tile per metre Mesh wallMesh = makeBox({5.0f, 2.5f, 0.3f}); Mesh pillarMesh = makeBox({0.6f, 3.0f, 0.6f}); Mesh brickSphere = makeSphere(48, 24); - Material brickMaterial; - brickMaterial.diffuseMap = &*brickTexture; - brickMaterial.normalMap = &*brickNormal; - brickMaterial.specular = {0.08f, 0.08f, 0.08f}; - brickMaterial.shininess = 24.0f; - brickMaterial.parallaxScale = 0.04f; // 1枚(1 m)の4% = 4 cm の深さ / 4 % of a tile (1 m) = 4 cm deep + PbrMaterial brickMaterial{.roughness = 0.85f, .parallaxScale = 0.04f, .baseColorMap = &*brickTexture, + .normalMap = &*brickNormal}; struct Piece { const Mesh *mesh; Mat4 model; @@ -397,121 +406,115 @@ int main() { {&pillarMesh, translate({1.6f, 1.5f, 4.4f}) * rotateY(0.3f)}, {&brickSphere, translate({-2.3f, 0.6f, 6.9f}) * scale({1.2f, 1.2f, 1.2f})}, }; - // 樽の置き場所 / where the barrels stand const Placement barrels[] = {{{-0.4f, 0.0f, 5.6f}, 0.3f}, {{0.35f, 0.0f, 6.1f}, 2.0f}, {{2.6f, 0.0f, 5.9f}, 1.1f}}; - // パーゴラ:木の柱4本と、葉(切り抜き)の屋根。葉の形の影を落とす / a pergola: four wooden posts and a roof of - // (cut-out) leaves. It casts leaf-shaped shadows const Vec3 kPergola = {1.3f, 0.0f, 5.8f}; Mesh postMesh = makeBox({0.12f, 2.6f, 0.12f}); Mesh roofMesh = makePlane(2.8f, 4.0f); - Material postMaterial; - postMaterial.diffuse = srgbToLinear(Vec3{0.45f, 0.32f, 0.2f}); - postMaterial.specular = {0.05f, 0.05f, 0.05f}; - postMaterial.shininess = 8.0f; + PbrMaterial postMaterial{.baseColor = rgb(0.45f, 0.32f, 0.2f), .roughness = 0.8f}; std::vector posts; for (float x : {-1.3f, 1.3f}) for (float z : {-1.3f, 1.3f}) posts.push_back(translate(kPergola + Vec3{x, 1.3f, z})); - // 葉の板2枚(2枚目は45°回して少し上に:隙間を埋める) / two leaf layers (the second turned 45° and a little higher: - // fills the gaps) const Mat4 roofModels[] = {translate(kPergola + Vec3{0.0f, 2.6f, 0.0f}), translate(kPergola + Vec3{0.0f, 2.68f, 0.0f}) * rotateY(0.785f) * scale({0.75f, 1.0f, 0.75f})}; - Material leavesMaterial; - leavesMaterial.diffuseMap = &*leavesTexture; - leavesMaterial.alphaMode = AlphaMode::Mask; - leavesMaterial.doubleSided = true; - leavesMaterial.specular = {0.03f, 0.03f, 0.03f}; - leavesMaterial.shininess = 8.0f; - // 手で選んだ色はsRGBの値(カラーピッカーの値):シェーダーはリニアで計算するので変換する - // Hand-picked colours are sRGB values (what a colour picker shows): the shaders compute in linear space, so convert - Material wireMaterial; - wireMaterial.diffuse = srgbToLinear(Vec3{0.04f, 0.04f, 0.045f}); - wireMaterial.specular = {0.3f, 0.3f, 0.3f}; - wireMaterial.shininess = 32.0f; - - // 提灯:本体は暗い紙、発光で光る(1より明るい:HDR) / lanterns: dark paper, glowing through emission (brighter - // than 1: HDR) + PbrMaterial leavesMaterial{.roughness = 0.8f, .alphaMode = AlphaMode::Mask, .doubleSided = true, + .baseColorMap = &*leavesTexture}; + PbrMaterial wireMaterial{.baseColor = rgb(0.04f, 0.04f, 0.045f), .roughness = 0.35f}; + std::vector lanterns = makeLanterns(); - Mesh sphereMesh = makeSphere(24, 12); + Mesh sphereMesh = makeSphere(48, 24); constexpr float kLanternGlow = 6.0f; + // 見本の球:磨いた金、クロム、粗い銅、赤いプラスチック(glTFの値で、金属のベースカラー = F0) + // Sample spheres: polished gold, chrome, rough copper, red plastic (glTF values; a metal's base colour = its F0) + struct Showcase { + Vec3 position; + PbrMaterial material; + }; + const Showcase showcase[] = { + {{-1.8f, 0.35f, 8.0f}, {.baseColor = {1.0f, 0.766f, 0.336f, 1.0f}, .metallic = 1.0f, .roughness = 0.15f}}, + {{-0.6f, 0.35f, 8.3f}, {.baseColor = {0.95f, 0.95f, 0.95f, 1.0f}, .metallic = 1.0f, .roughness = 0.05f}}, + {{0.6f, 0.35f, 8.3f}, {.baseColor = {0.955f, 0.638f, 0.538f, 1.0f}, .metallic = 1.0f, .roughness = 0.55f}}, + {{1.8f, 0.35f, 8.0f}, {.baseColor = rgb(0.75f, 0.08f, 0.06f), .metallic = 0.0f, .roughness = 0.3f}}, + }; + // 金属度 × 粗さの球の格子(7 × 7):宙に浮かべる。上の行ほど金属、右の列ほど粗い(Kで見に行く) + // The metallic × roughness sphere grid (7 × 7), floating in the air: metal towards the top row, rougher to the right + // (go and look with K) + constexpr int kGrid = 7; + const Vec3 kGridCentre = {0.0f, 5.5f, 24.0f}; + const Vec4 kGridColor = rgb(0.9f, 0.35f, 0.15f); FullscreenTriangle fullscreen; glEnable(GL_CULL_FACE); - // 場面全体を今のフレームバッファに描く(ビューポートは呼ぶ側) / draws the whole scene into the current framebuffer - // (the caller sets the viewport) + // 場面全体を今のフレームバッファに描く。litはpbr(PBR)かphong(比較用のBlinn-Phong) + // Draws the whole scene into the current framebuffer. `lit` is pbr (PBR) or phong (Blinn-Phong, for comparison) Vec3 environmentTint; auto drawScene = [&] { glEnable(GL_DEPTH_TEST); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); sky->bind(3); + ibl->bind(); - phong->use(); - phong->set("uViewMode", viewMode); - - phong->set("uEnvironmentTint", environmentTint); - 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); - Material lanternMaterial; - lanternMaterial.diffuse = {0.05f, 0.03f, 0.02f}; - lanternMaterial.specular = {0.02f, 0.02f, 0.02f}; + const Shader &lit = usePbr ? *pbr : *phong; + Shading shading = usePbr ? Shading::Pbr : Shading::BlinnPhong; + auto apply = [&](const PbrMaterial &m) { + if (usePbr) m.apply(lit, white); + else toBlinnPhong(m).apply(lit, white); + }; + auto drawMesh = [&](const Mesh &mesh, const Mat4 &model) { + lit.set("uModel", model); + lit.set("uNormalMatrix", normalMatrix(model)); + mesh.draw(); + }; + lit.use(); + lit.set("uViewMode", viewMode); + lit.set("uEnvironmentTint", environmentTint); + if (usePbr) lit.set("uLighting", lighting); + + apply(floorMaterial); + drawMesh(floorMesh, Mat4::identity()); + scene->draw(lit, Mat4::identity(), white, ModelPass::Opaque, {}, shading); + for (const Placement &c : kCrates) + crate->draw(lit, translate(c.position) * rotateY(c.angle), white, ModelPass::Opaque, {}, shading); + for (const Placement &b : barrels) + barrel->draw(lit, translate(b.position) * rotateY(b.angle), white, ModelPass::Opaque, {}, shading); + PbrMaterial lanternMaterial{.baseColor = rgb(0.2f, 0.15f, 0.1f), .roughness = 0.6f}; for (const Lantern &l : lanterns) { - lanternMaterial.emission = kLanternGlow * l.color; - lanternMaterial.apply(*phong, white); - Mat4 model = translate(l.position) * scale({0.3f, 0.38f, 0.3f}); - phong->set("uModel", model); - phong->set("uNormalMatrix", normalMatrix(model)); - sphereMesh.draw(); - } - wireMaterial.apply(*phong, white); - for (const Mat4 &m : wires) { - phong->set("uModel", m); - phong->set("uNormalMatrix", normalMatrix(m)); - cubeMesh.draw(); + lanternMaterial.emissive = kLanternGlow * l.color; + apply(lanternMaterial); + drawMesh(sphereMesh, translate(l.position) * scale({0.3f, 0.38f, 0.3f})); } - // レンガ(法線マップ+視差) / the bricks (normal map + parallax) - brickMaterial.apply(*phong, white); - for (const Piece &b : bricks) { - phong->set("uModel", b.model); - phong->set("uNormalMatrix", normalMatrix(b.model)); - b.mesh->draw(); - } - for (const Placement &b : barrels) barrel->draw(*phong, translate(b.position) * rotateY(b.angle), white, ModelPass::Opaque); - postMaterial.apply(*phong, white); - for (const Mat4 &m : posts) { - phong->set("uModel", m); - phong->set("uNormalMatrix", normalMatrix(m)); - postMesh.draw(); + apply(wireMaterial); + for (const Mat4 &m : wires) drawMesh(cubeMesh, m); + apply(brickMaterial); + for (const Piece &b : bricks) drawMesh(*b.mesh, b.model); + apply(postMaterial); + for (const Mat4 &m : posts) drawMesh(postMesh, m); + for (const Showcase &sc : showcase) { + apply(sc.material); + drawMesh(sphereMesh, translate(sc.position) * scale({0.7f, 0.7f, 0.7f})); } + // 球の格子:行 = 金属度 0〜1(下から上)、列 = 粗さ 0〜1(左から右) / the grid: rows = metallic 0..1 (bottom to + // top), columns = roughness 0..1 (left to right) + for (int row = 0; row < kGrid; ++row) + for (int col = 0; col < kGrid; ++col) { + PbrMaterial m{.baseColor = kGridColor, .metallic = static_cast(row) / (kGrid - 1), + .roughness = static_cast(col) / (kGrid - 1)}; + apply(m); + Vec3 p = kGridCentre + Vec3{1.1f * (static_cast(col) - 3.0f), 1.1f * (static_cast(row) - 3.0f), 0.0f}; + drawMesh(sphereMesh, translate(p) * scale({0.9f, 0.9f, 0.9f})); + } - // 草:アルファトゥカバレッジならdiscardの代わりにサンプルの一部だけを覆う(MSAAのときだけ意味がある) - // Grass: with alpha to coverage, a fragment covers only some of the samples instead of being discarded (only - // meaningful with MSAA) + // 切り抜き(第16・20章):アルファトゥカバレッジ / cut-outs (chapters 16 and 20): alpha to coverage glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE); - phong->set("uAlphaToCoverage", 1); - // 葉の屋根(両面) / the roof of leaves (double-sided) - leavesMaterial.apply(*phong, white); + lit.set("uAlphaToCoverage", 1); glDisable(GL_CULL_FACE); - for (const Mat4 &m : roofModels) { - phong->set("uModel", m); - phong->set("uNormalMatrix", normalMatrix(m)); - roofMesh.draw(); - } - glEnable(GL_CULL_FACE); - 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(); - } + apply(leavesMaterial); + for (const Mat4 &m : roofModels) drawMesh(roofMesh, m); + apply(grassMaterial); + for (const Placement &g : grass) drawMesh(tuftMesh, translate(g.position) * rotateY(g.angle) * scale({0.75f, 0.75f, 0.75f})); glEnable(GL_CULL_FACE); - phong->set("uAlphaToCoverage", 0); + lit.set("uAlphaToCoverage", 0); glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE); glDepthFunc(GL_LEQUAL); @@ -541,6 +544,7 @@ int main() { for (const Mat4 &m : wires) drawMesh(cubeMesh, m); for (const Piece &b : bricks) drawMesh(*b.mesh, b.model); for (const Mat4 &m : posts) drawMesh(postMesh, m); + for (const Showcase &sc : showcase) drawMesh(sphereMesh, translate(sc.position) * scale({0.7f, 0.7f, 0.7f})); // 切り抜き:両面なのでカリングなし / cut-outs: two-sided, so no culling glDisable(GL_CULL_FACE); shadowShader->set("uAlphaMask", 1); @@ -621,7 +625,7 @@ int main() { // ベクトルの表示(法線・接線)は値をそのまま見せる:トーンマッピングなし、露出1(phong.fragが逆変換して出す) // The vector views (normals, tangents) show the raw values: no tone mapping, exposure 1 (phong.frag outputs them // pre-decoded) - if (viewMode >= kFirstVectorView) { + if (usePbr ? (viewMode >= 2 && viewMode <= 5) || viewMode == 8 : viewMode >= kFirstVectorView) { postSettings.exposure = 1.0f; postSettings.toneMapper = static_cast(ToneMapper::Clamp); } else { diff --git a/src/model.cc b/src/model.cc index d0fa55a..7da4552 100644 --- a/src/model.cc +++ b/src/model.cc @@ -305,7 +305,7 @@ void Model::draw(const Shader &shader, const Mat4 &transform, const Texture2D &w } void Model::draw(const Shader &shader, const Mat4 &transform, const Texture2D &white, ModelPass pass, - Vec3 viewPos) const { + Vec3 viewPos, Shading shading) const { std::vector items; for (int root : roots) collect(root, transform, transform, true, pass, viewPos, items); if (pass == ModelPass::Transparent) { @@ -314,7 +314,7 @@ void Model::draw(const Shader &shader, const Mat4 &transform, const Texture2D &w std::stable_sort(items.begin(), items.end(), [](const DrawItem &a, const DrawItem &b) { return a.distance > b.distance; }); } - drawItems(items, shader, &white, true); + drawItems(items, shader, &white, true, 0, false, shading); } void Model::drawGeometry(const Shader &shader, const Mat4 &transform) const { @@ -355,14 +355,14 @@ void Model::setInstanceBuffer(const Buffer &buffer, GLsizei stride, std::span items; for (int root : roots) collect(root, Mat4::identity(), Mat4::identity(), true, ModelPass::All, {}, items); - drawItems(items, shader, &white, shader.has("uNormalMatrix"), count); + drawItems(items, shader, &white, shader.has("uNormalMatrix"), count, false, shading); } void Model::drawItems(const std::vector &items, const Shader &shader, const Texture2D *white, - bool normals, GLsizei instances, bool depthOnly) const { + bool normals, GLsizei instances, bool depthOnly, Shading shading) const { bool culling = glIsEnabled(GL_CULL_FACE); // 呼ぶ側の設定を覚えておく / remember the caller's setting for (const DrawItem &item : items) { const Primitive &p = *item.primitive; @@ -379,6 +379,15 @@ void Model::drawItems(const std::vector &items, const Shader &shader, shader.set("uAlphaCutoff", md.phong.alphaCutoff); shader.set("uBaseAlpha", md.phong.alpha); } + } else if (white && shading == Shading::Pbr) { + // glTFの値とテクスチャそのまま(第24章) / glTF's values and textures as they are (chapter 24) + PbrMaterial m = PbrMaterial::fromGltf(md.pbr); + m.baseColorMap = texture(md.pbr.baseColorTexture.index); + m.emissiveMap = texture(md.pbr.emissiveTexture.index); + m.normalMap = texture(md.pbr.normalTexture.index); + m.metallicRoughnessMap = texture(md.pbr.metallicRoughnessTexture.index); + m.occlusionMap = texture(md.pbr.occlusionTexture.index); + m.apply(shader, *white); } else if (white) { Material m = md.phong; m.diffuseMap = texture(md.pbr.baseColorTexture.index); // 色 = 係数 × テクスチャ / colour = factor × texture diff --git a/src/model.hh b/src/model.hh index c862edf..6e42dfe 100644 --- a/src/model.hh +++ b/src/model.hh @@ -4,6 +4,7 @@ #include "gltf.hh" #include "material.hh" #include "mesh.hh" +#include "pbr_material.hh" #include "shader.hh" #include "texture.hh" @@ -21,6 +22,13 @@ enum class ModelPass { // (the caller sets up blending) }; +// どのマテリアルで描くか(第24章)。シェーダーに合わせる:phong.fragならBlinnPhong、pbr.fragならPbr +// Which material model to draw with (chapter 24). Match the shader: BlinnPhong for phong.frag, Pbr for pbr.frag +enum class Shading { + BlinnPhong, // MaterialData::phong(第14章の近似) / MaterialData::phong (the chapter 14 approximation) + Pbr, // MaterialData::pbrのglTFの値そのまま(PbrMaterial) / MaterialData::pbr's glTF values as they are +}; + // 読み込んだモデル:メッシュ(VAO)、テクスチャ、マテリアル、ノードの階層(RAII、コピー不可・移動可)。 // 描くときは、ノードごとに 親のワールド行列 × 自分のローカル行列 をたどる。 // A loaded model: meshes (VAOs), textures, materials and the node hierarchy (RAII, non-copyable, movable). @@ -63,8 +71,10 @@ public: // 両面(doubleSided)のマテリアルは、その間だけフェイスカリングを切って描く。 // Draws only the primitives of `pass`. Transparent sorts them back to front by the distance from viewPos to the // centre of each primitive's box. Double-sided materials are drawn with face culling turned off for that draw. + // shading = Pbrならマテリアルは金属・粗さ・遮蔽などのテクスチャごとPbrMaterialで設定する(第24章) + // With shading = Pbr the materials are set as PbrMaterial, with their metallic-roughness, occlusion... maps (ch. 24) void draw(const Shader &shader, const Mat4 &transform, const Texture2D &white, ModelPass pass, - Vec3 viewPos = {}) const; + Vec3 viewPos = {}, Shading shading = Shading::BlinnPhong) const; // 形だけを描く:マテリアルもテクスチャも設定せず、ノードごとにuModelだけ(シェーダーが使っていればuNormalMatrixも)。 // 深度の表示、輪郭、のちの影(第23章)のように、色を使わないパス用。 // Draws the shape only: no materials or textures, just uModel per node (and uNormalMatrix if the shader uses it). @@ -86,7 +96,8 @@ public: // インスタンスの行列はシェーダーで掛ける(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; + void drawInstanced(const Shader &shader, const Texture2D &white, GLsizei count, + Shading shading = Shading::BlinnPhong) const; // 名前でノードを探す。なければ-1 / finds a node by name; -1 if none int findNode(std::string_view name) const; @@ -117,7 +128,7 @@ private: 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, - GLsizei instances = 0, bool depthOnly = false) const; + GLsizei instances = 0, bool depthOnly = false, Shading shading = Shading::BlinnPhong) const; const MaterialData &materialOf(const Primitive &p) const; const Texture2D *texture(int index) const; // なければnullptr / nullptr if missing diff --git a/src/pbr_material.cc b/src/pbr_material.cc new file mode 100644 index 0000000..3bce1a8 --- /dev/null +++ b/src/pbr_material.cc @@ -0,0 +1,62 @@ +#include "pbr_material.hh" + +void PbrMaterial::apply(const Shader &shader, const Texture2D &white) const { + shader.set("uMaterial.baseColor", baseColor); + shader.set("uMaterial.metallic", metallic); + shader.set("uMaterial.roughness", roughness); + shader.set("uMaterial.emissive", emissive); + // 法線マップがなければ0:白(1,1,1)が平らな(0,0,1)になる(第22章) / 0 without a normal map: white (1,1,1) becomes the + // flat (0,0,1) (chapter 22) + shader.set("uMaterial.normalScale", normalMap ? normalScale : 0.0f); + shader.set("uMaterial.parallaxScale", normalMap ? parallaxScale : 0.0f); + shader.set("uMaterial.occlusionStrength", occlusionStrength); + shader.set("uMaterial.alphaMode", static_cast(alphaMode)); + shader.set("uMaterial.alphaCutoff", alphaCutoff); + shader.set("uMaterial.doubleSided", doubleSided ? 1 : 0); + (baseColorMap ? baseColorMap : &white)->bind(0); + (emissiveMap ? emissiveMap : &white)->bind(2); + (normalMap ? normalMap : &white)->bind(4); + (metallicRoughnessMap ? metallicRoughnessMap : &white)->bind(7); + (occlusionMap ? occlusionMap : &white)->bind(8); +} + +PbrMaterial PbrMaterial::fromGltf(const GltfMaterial &m) { + PbrMaterial p; + p.baseColor = m.baseColorFactor; + p.metallic = m.metallicFactor; + p.roughness = m.roughnessFactor; + p.emissive = m.emissiveStrength * m.emissiveFactor; + p.normalScale = m.normalTexture.scale; + p.occlusionStrength = m.occlusionTexture.scale; // glTFのstrengthはscaleに入っている / glTF's strength is stored in scale + p.alphaMode = m.alphaMode == GltfAlphaMode::Mask ? AlphaMode::Mask + : m.alphaMode == GltfAlphaMode::Blend ? AlphaMode::Blend + : AlphaMode::Opaque; + p.alphaCutoff = m.alphaCutoff; + p.doubleSided = m.doubleSided; + return p; +} + +Material toBlinnPhong(const PbrMaterial &m) { + Vec3 base = {m.baseColor.x, m.baseColor.y, m.baseColor.z}; + Material p; + p.diffuse = (1.0f - m.metallic) * base; + Vec3 f0 = lerp({0.04f, 0.04f, 0.04f}, base, m.metallic); + float alpha = m.roughness * m.roughness; + float n = alpha > 0.0f ? 2.0f / (alpha * alpha) - 2.0f : 1024.0f; + n = n < 1.0f ? 1.0f : n > 1024.0f ? 1024.0f : n; + p.specular = ((n + 8.0f) / 8.0f) * f0; + p.shininess = n; + p.emission = m.emissive; + p.alpha = m.baseColor.w; + p.alphaMode = m.alphaMode; + p.alphaCutoff = m.alphaCutoff; + p.doubleSided = m.doubleSided; + p.reflectivity = (m.metallic * m.metallic) * f0; + p.reflectionBlur = m.roughness; + p.diffuseMap = m.baseColorMap; + p.emissionMap = m.emissiveMap; + p.normalMap = m.normalMap; + p.normalScale = m.normalScale; + p.parallaxScale = m.parallaxScale; + return p; +} diff --git a/src/pbr_material.hh b/src/pbr_material.hh new file mode 100644 index 0000000..670e5b8 --- /dev/null +++ b/src/pbr_material.hh @@ -0,0 +1,42 @@ +// 物理ベースのマテリアル(第24章):glTFの金属・粗さモデルそのまま / a physically based material (chapter 24): exactly +// glTF's metallic-roughness model +#pragma once + +#include "gltf.hh" +#include "material.hh" +#include "mathx.hh" +#include "shader.hh" +#include "texture.hh" + +// テクスチャはすべて「係数 × テクスチャ」。ないテクスチャには白を繋ぐ(白 × 係数 = 係数)。 +// Every texture is "factor × texture". A missing texture is replaced by white (white × factor = factor). +struct PbrMaterial { + Vec4 baseColor = {1.0f, 1.0f, 1.0f, 1.0f}; // リニア、aは不透明度 / linear, a = opacity + float metallic = 0.0f; // 0 = 非金属(誘電体)、1 = 金属 / 0 = dielectric, 1 = metal + float roughness = 0.5f; // 0 = 鏡、1 = つや消し / 0 = mirror, 1 = fully matte + Vec3 emissive = {0.0f, 0.0f, 0.0f}; // 発光(HDR、強さを掛けた後) / emission (HDR, strength applied) + float normalScale = 1.0f; // glTFのnormalTexture.scale + float occlusionStrength = 1.0f; // glTFのocclusionTexture.strength + float parallaxScale = 0.0f; // 第22章の視差(OpenGLのUVの物だけ) / chapter 22 parallax (OpenGL UVs only) + AlphaMode alphaMode = AlphaMode::Opaque; + float alphaCutoff = 0.5f; + bool doubleSided = false; + + const Texture2D *baseColorMap = nullptr; // ユニット0、sRGB / unit 0, sRGB + const Texture2D *emissiveMap = nullptr; // ユニット2、sRGB / unit 2, sRGB + const Texture2D *normalMap = nullptr; // ユニット4、リニア / unit 4, linear + const Texture2D *metallicRoughnessMap = nullptr; // ユニット7:G = 粗さ、B = 金属度、リニア / unit 7: G = roughness, B = metallic + const Texture2D *occlusionMap = nullptr; // ユニット8:R = 遮蔽、リニア / unit 8: R = occlusion, linear + + // pbr.fragのuMaterialを設定し、マップを繋ぐ(ないものは白) / sets pbr.frag's uMaterial and binds the maps (white + // for missing ones) + void apply(const Shader &shader, const Texture2D &white) const; + + // glTFのマテリアルの係数(テクスチャは呼ぶ側が繋ぐ) / the factors of a glTF material (the caller attaches textures) + static PbrMaterial fromGltf(const GltfMaterial &m); +}; + +// 比較用:同じ表面をBlinn-Phongで近似する(第14章のphongFromPbrと同じ式、ただしテクスチャの平均は使わない) +// For comparison: approximate the same surface with Blinn-Phong (the formulas of chapter 14's phongFromPbr, without +// texture averages) +Material toBlinnPhong(const PbrMaterial &m);