diff --git a/assets/LICENSE.txt b/assets/LICENSE.txt index 4aa56a3..6d0c8dd 100644 --- a/assets/LICENSE.txt +++ b/assets/LICENSE.txt @@ -17,3 +17,4 @@ models/diorama.glb 小さな場面 / a small diorama scene (chapter 21 textures/bricks.png レンガ / bricks (chapter 22) textures/bricks_normal.png レンガの法線マップ+高さ / brick normal map + height (chapter 22) models/barrel.glb 樽(PBRのテクスチャ付き) / a barrel with PBR textures (chapter 22) +textures/leaves.png 葉(アルファ付き) / leaves with alpha (chapter 23) diff --git a/assets/textures/leaves.png b/assets/textures/leaves.png new file mode 100644 index 0000000..5a4c633 Binary files /dev/null and b/assets/textures/leaves.png differ diff --git a/shaders/phong.frag b/shaders/phong.frag index 7ad7473..7164965 100644 --- a/shaders/phong.frag +++ b/shaders/phong.frag @@ -28,6 +28,9 @@ layout(binding = 2) uniform sampler2D uEmissionMap; // 法線マップ(第22章):RGB = 接線空間の法線、A = 高さ(視差マッピング用)。ユニット4 // Normal map (chapter 22): RGB = tangent-space normal, A = height (for parallax mapping). Unit 4 layout(binding = 4) uniform sampler2D uNormalMap; +// 影の地図(第23章):深度テクスチャ、比較モード。texture(s, vec3(uv, 深さ))は0〜1(影〜光) +// The shadow map (chapter 23): a depth texture in comparison mode. texture(s, vec3(uv, depth)) gives 0..1 (shadow..lit) +layout(binding = 5) uniform sampler2DShadow uShadowMap; uniform bool uNormalMapping = true; // 法線マップを使う(デバッグ用に切れる) / use normal maps (can be turned off for debugging) uniform bool uParallaxMapping = true; // 視差マッピングを使う / use parallax mapping // 環境(空)のキューブマップ。ユニット3(第18章) / the environment (sky) cube map, unit 3 (chapter 18) @@ -84,10 +87,23 @@ layout(std140, binding = 0) uniform Camera { 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 = 接線、8 = 従法線(第22章) +// 6 = 頂点の法線(法線マップ前)、7 = 接線、8 = 従法線(第22章)、9 = 影(第23章) // 0 = everything, 1 = ambient, 2 = diffuse, 3 = specular, 4 = emission, 5 = normals (after normal mapping), -// 6 = vertex normals (before normal mapping), 7 = tangents, 8 = bitangents (chapter 22) +// 6 = vertex normals (before normal mapping), 7 = tangents, 8 = bitangents (chapter 22), 9 = shadow (chapter 23) uniform int uViewMode; // アルファトゥカバレッジ(第20章):マスクのマテリアルを捨てる代わりに、アルファをMSAAのサンプルの割合にする。 @@ -149,6 +165,34 @@ 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) @@ -235,8 +279,10 @@ void main() { vec3 diffuse = vec3(0.0); vec3 specular = vec3(0.0); - // 平行光源:光へ向かう向きは進む向きの逆 / directional: towards the light = the opposite of its direction - addLight(s, -uDirLight.direction, uDirLight.color, diffuse, specular); + // 平行光源:光へ向かう向きは進む向きの逆。影を掛ける(第23章) / directional: towards the light = the opposite of its + // direction. Shadowed (chapter 23) + float shadow = shadowFactor(vWorldPos, geometricNormal, -uDirLight.direction); + addLight(s, -uDirLight.direction, uDirLight.color * shadow, diffuse, specular); // 点光源 / point lights for (int i = 0; i < uPointLightCount; ++i) { @@ -275,6 +321,7 @@ void main() { else if (uViewMode == 6) color = geometricNormal * 0.5 + 0.5; else if (uViewMode == 7) color = hasTangent ? tangent * 0.5 + 0.5 : vec3(0.0); else if (uViewMode == 8) color = hasTangent ? bitangent * 0.5 + 0.5 : vec3(0.0); + else if (uViewMode == 9) color = vec3(shadow); // ベクトルの表示は、post.fragがsRGBにした後でちょうどこの値になるように、先にリニアへ戻しておく // Vector views: convert to linear first, so that after post.frag's sRGB encoding the screen shows exactly this value if (uViewMode >= 5) diff --git a/shaders/shadow.frag b/shaders/shadow.frag new file mode 100644 index 0000000..8b3b409 --- /dev/null +++ b/shaders/shadow.frag @@ -0,0 +1,15 @@ +#version 460 core +// 影の地図のフラグメントシェーダー:色は書かない(深度はGPUが書く)。葉や草は切り抜く +// Shadow-map fragment shader: no colour is written (the GPU writes the depth). Leaves and grass are cut out +in vec2 vUv; + +layout(binding = 0) uniform sampler2D uBaseMap; // Maskのときのベースカラー(アルファ) / base colour for Mask (alpha) +uniform bool uAlphaMask; // 切り抜くか / cut out? +uniform float uAlphaCutoff; +uniform float uBaseAlpha; // マテリアルのアルファ係数 / the material's alpha factor + +void main() { + // 透明な部分が影を落とさないように捨てる:葉の形の影になる / discard the transparent parts so they cast no shadow: + // the shadow gets the leaves' shape + if (uAlphaMask && uBaseAlpha * texture(uBaseMap, vUv).a < uAlphaCutoff) discard; +} diff --git a/shaders/shadow.vert b/shaders/shadow.vert new file mode 100644 index 0000000..8436f3d --- /dev/null +++ b/shaders/shadow.vert @@ -0,0 +1,26 @@ +#version 460 core +// 影の地図(第23章):光から見た深度だけを描く / shadow map (chapter 23): draws only the depth seen from the light +layout(location = 0) in vec3 aPosition; +layout(location = 2) in vec2 aUv; // 切り抜き(Mask)用 / for cut-outs (Mask) + +// 影(ユニフォームバッファ、結合点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; +}; + +uniform mat4 uModel; + +out vec2 vUv; + +void main() { + vUv = aUv; + gl_Position = uLightSpace * uModel * vec4(aPosition, 1.0); +} diff --git a/shaders/shadow_debug.frag b/shaders/shadow_debug.frag new file mode 100644 index 0000000..e063ecd --- /dev/null +++ b/shaders/shadow_debug.frag @@ -0,0 +1,15 @@ +#version 460 core +// 影の地図を見せる(第23章):深度テクスチャを灰色で。比較なしのサンプラーオブジェクトで読む +// Shows the shadow map (chapter 23): the depth texture as grey. Read through a sampler object without comparison +in vec2 vUv; + +layout(binding = 0) uniform sampler2D uDepth; + +layout(location = 0) out vec4 out_color; + +void main() { + // 正射影なので深度は距離に比例(線型):そのまま見せられる。近い = 暗い + // Orthographic, so depth is proportional to distance (linear): it can be shown as it is. Near = dark + float d = texture(uDepth, vUv).r; + out_color = vec4(vec3(pow(d, 4.0)), 1.0); // 奥の範囲を広げる / spreads the far range +} diff --git a/src/framebuffer.cc b/src/framebuffer.cc index e539c91..0d8e107 100644 --- a/src/framebuffer.cc +++ b/src/framebuffer.cc @@ -50,7 +50,18 @@ void Framebuffer::createAttachments() { glNamedFramebufferDrawBuffer(fbo, GL_NONE); glNamedFramebufferReadBuffer(fbo, GL_NONE); } - if (spec.depthStencilFormat != 0) { + bool stencil = spec.depthStencilFormat == GL_DEPTH24_STENCIL8 || spec.depthStencilFormat == GL_DEPTH32F_STENCIL8; + if (spec.depthStencilFormat != 0 && spec.depthTexture) { + if (spec.samples > 0) fprintf(stderr, "マルチサンプルの深度テクスチャは未対応 / multisampled depth textures are not supported\n"); + // 深度テクスチャ(影の地図):外側(光の箱の外)は1 = 一番奥なので影にならない + // A depth texture (shadow map): outside (beyond the light's box) reads 1 = farthest, so it is never in shadow + depthTex = Texture2D(w, h, spec.depthStencilFormat, 1); + depthTex.setWrap(GL_CLAMP_TO_BORDER, GL_CLAMP_TO_BORDER); + depthTex.setBorderColor(1.0f, 1.0f, 1.0f, 1.0f); + depthTex.setFilter(GL_LINEAR, GL_LINEAR); + depthTex.setCompare(true); + glNamedFramebufferTexture(fbo, stencil ? GL_DEPTH_STENCIL_ATTACHMENT : GL_DEPTH_ATTACHMENT, depthTex.id(), 0); + } else if (spec.depthStencilFormat != 0) { glCreateRenderbuffers(1, &depthStencil); // 色と深度のサンプル数は同じでなければならない(違うとフレームバッファが不完全)。要求ではなく、色が実際に // 貰った数を使う(色が無ければ要求の数) / colour and depth must have the same number of samples (otherwise the @@ -63,7 +74,6 @@ void Framebuffer::createAttachments() { if (depthSamples > 0 && actualSamples == 0) glGetNamedRenderbufferParameteriv(depthStencil, GL_RENDERBUFFER_SAMPLES, &actualSamples); // GL_DEPTH24_STENCIL8なら深度とステンシルの両方に付ける / GL_DEPTH24_STENCIL8 attaches as both depth and stencil - bool stencil = spec.depthStencilFormat == GL_DEPTH24_STENCIL8 || spec.depthStencilFormat == GL_DEPTH32F_STENCIL8; glNamedFramebufferRenderbuffer(fbo, stencil ? GL_DEPTH_STENCIL_ATTACHMENT : GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depthStencil); } @@ -71,6 +81,7 @@ void Framebuffer::createAttachments() { void Framebuffer::destroyAttachments() { for (Texture2D &t : colorTextures) t = Texture2D(); // 古いテクスチャを消す / deletes the old textures + depthTex = Texture2D(); for (GLuint &rb : colorSamples) { if (rb) glDeleteRenderbuffers(1, &rb); rb = 0; @@ -137,7 +148,8 @@ Framebuffer::~Framebuffer() { Framebuffer::Framebuffer(Framebuffer &&other) noexcept : fbo(std::exchange(other.fbo, 0)), depthStencil(std::exchange(other.depthStencil, 0)), - colorSamples(std::exchange(other.colorSamples, {})), colorTextures(std::move(other.colorTextures)), w(other.w), + colorSamples(std::exchange(other.colorSamples, {})), colorTextures(std::move(other.colorTextures)), + depthTex(std::move(other.depthTex)), w(other.w), h(other.h), actualSamples(other.actualSamples), spec(other.spec) {} Framebuffer &Framebuffer::operator=(Framebuffer &&other) noexcept { @@ -148,6 +160,7 @@ Framebuffer &Framebuffer::operator=(Framebuffer &&other) noexcept { depthStencil = std::exchange(other.depthStencil, 0); colorSamples = std::exchange(other.colorSamples, {}); colorTextures = std::move(other.colorTextures); + depthTex = std::move(other.depthTex); w = other.w; h = other.h; actualSamples = other.actualSamples; diff --git a/src/framebuffer.hh b/src/framebuffer.hh index d66eb50..25636a5 100644 --- a/src/framebuffer.hh +++ b/src/framebuffer.hh @@ -29,6 +29,11 @@ struct FramebufferSpec { // 1 or more makes both colour and depth multisampled renderbuffers, which cannot be sampled: resolve them into // an ordinary framebuffer with blitTo first. The driver may pick more samples than requested (check samples()). int samples = 0; + // 深度をレンダーバッファではなくテクスチャにする(影の地図、第23章)。depthStencilFormatは + // GL_DEPTH_COMPONENT24 / 32Fなど。比較モードon、GL_LINEAR、外側はGL_CLAMP_TO_BORDERで1。depth()で読む + // Make the depth a texture instead of a renderbuffer (shadow maps, chapter 23). depthStencilFormat is + // GL_DEPTH_COMPONENT24 / 32F etc. Comparison mode on, GL_LINEAR, GL_CLAMP_TO_BORDER with 1 outside. Read it with depth() + bool depthTexture = false; }; // フレームバッファオブジェクト(FBO):色のテクスチャ+深度・ステンシルのレンダーバッファ(RAII、コピー不可・移動可)。DSAで作る。 @@ -62,6 +67,9 @@ public: const Texture2D &color(int index = 0) const { return colorTextures[static_cast(index)]; } Texture2D &color(int index = 0) { return colorTextures[static_cast(index)]; } int colorCount() const { return spec.colorFormat != 0 ? spec.colorCount : 0; } + // 深度のテクスチャ(spec.depthTextureのときだけ、ほかは空) / the depth texture (only with spec.depthTexture, else empty) + const Texture2D &depth() const { return depthTex; } + Texture2D &depth() { return depthTex; } // 別のフレームバッファへコピーする(glBlitNamedFramebuffer)。マルチサンプルから普通のフレームバッファへなら // サンプルの平均を取る:これがMSAAの「解決(resolve)」。大きさが違えば拡大・縮小する(filter = GL_LINEARなど。 @@ -92,6 +100,7 @@ private: // マルチサンプルの色のレンダーバッファ(第20章) / multisampled colour renderbuffers (chapter 20) std::array colorSamples = {}; std::array colorTextures; + Texture2D depthTex; // 第23章 / chapter 23 int w = 0, h = 0; int actualSamples = 0; FramebufferSpec spec; diff --git a/src/main.cc b/src/main.cc index 43a53e3..3ea7c48 100644 --- a/src/main.cc +++ b/src/main.cc @@ -1,5 +1,5 @@ -// 第22章:法線マッピング -// Chapter 22: normal mapping +// 第23章:シャドウマッピング +// Chapter 23: shadow mapping // // 操作 / Controls: // WASD 前後左右に移動 / move forward, back, left, right @@ -7,18 +7,25 @@ // Shift 速く動く / move faster // マウス / mouse 向きを変える(FPS)、左ドラッグで回る(オービット) / look around (FPS), drag with the left button to orbit // ホイール / wheel ズーム / zoom -// M 法線マップのオン・オフ / normal maps on / off -// X 視差(オクルージョン)マッピングのオン・オフ / parallax (occlusion) mapping on / off -// L 壁の前を回る点光源のオン・オフ / the point light circling in front of the wall on / off -// V 表示:全部 → 環境光 → 拡散 → 鏡面 → 発光 → 法線 → 頂点の法線 → 接線 → 従法線 -// view: all → ambient → diffuse → specular → emission → normals → vertex normals → tangents → bitangents +// 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 // C FPS ⇔ オービットカメラ / FPS ⇔ orbit camera // N 昼 ⇔ 夜 / day ⇔ night // F 懐中電灯のオン・オフ / flashlight on / off -// P 風車と点光源を止める・動かす / pause / resume the windmill and the point light +// P 風車を止める・動かす / pause / resume the windmill // Tab カーソルのキャプチャ切り替え / toggle cursor capture // R シェーダーを読み直す / reload the shaders // Esc 終了 / quit @@ -36,6 +43,7 @@ #include "uniforms.hh" #include "window.hh" +#include #include #include #include @@ -56,9 +64,49 @@ 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"}; -constexpr int kViewModes = 9; +static const char *const kViewModeNames[] = {"all", "ambient", "diffuse", "specular", "emission", + "normals", "vertex normals", "tangents", "bitangents", "shadow"}; +constexpr int kViewModes = 10; + +// 影のバイアスの方法 / the shadow bias methods +struct BiasMode { + const char *name; + float constant; // m(inTexelsならテクセルの大きさの倍数) / m (multiples of the texel size if inTexels) + float slope; // tanθ当たり / per unit of tan θ + float normalOffset; // 法線方向のずらし / push along the normal + bool polygonOffset; // 影の地図を描くときにglPolygonOffset / glPolygonOffset while drawing the shadow map + bool inTexels; // 値を影の地図の1テクセルのワールドでの大きさで測る:地図の大きさを変えても効き目が同じ + // values measured in the world size of one shadow-map texel: works the same at any map size +}; +static const BiasMode kBiasModes[] = { + {"none (shadow acne)", 0.0f, 0.0f, 0.0f, false, false}, + {"constant 1 cm", 0.01f, 0.0f, 0.0f, false, false}, + {"slope-scaled + normal offset (in texels)", 0.5f, 1.0f, 3.0f, false, true}, + {"glPolygonOffset(2, 4) only", 0.0f, 0.0f, 0.0f, true, false}, + {"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テクセル単位で +// 動かす(カメラが動いても影の縁がちらつかない)。depthRangeに箱の奥行き(m)を返す +// The directional light's matrix: an orthographic box enclosing the sphere (centre, radius). The box moves in whole +// shadow-map texels (shadow edges do not shimmer when the camera moves). Returns the box depth (m) in depthRange +static Mat4 lightSpaceMatrix(Vec3 lightDir, Vec3 centre, float radius, int mapSize, float &depthRange) { + Vec3 d = normalize(lightDir); + Vec3 up = std::fabs(d.y) > 0.99f ? Vec3{0.0f, 0.0f, 1.0f} : Vec3{0.0f, 1.0f, 0.0f}; + Mat4 view = lookAt({0.0f, 0.0f, 0.0f}, d, up); // 回転だけ:光の向きを-Zに / rotation only: the light along -Z + Vec4 c = view * Vec4{centre.x, centre.y, centre.z, 1.0f}; + float texel = 2.0f * radius / static_cast(mapSize); + float cx = std::floor(c.x / texel) * texel, cy = std::floor(c.y / texel) * texel; + // 奥行き:球の手前に20 m余分に(箱の外の、光と球の間にある物も影を落とすように) + // Depth: 20 m extra in front of the sphere (so casters between the light and the sphere still cast) + float nearPlane = -c.z - radius - 20.0f, farPlane = -c.z + radius; + depthRange = farPlane - nearPlane; + return orthographicGl(cx - radius, cx + radius, cy - radius, cy + radius, nearPlane, farPlane) * view; +} constexpr int kFirstVectorView = 5; // ここからはベクトルを色で見せる / from here on, vectors are shown as colours static const char *const kEffectNames[] = {"none", "invert", "grayscale", "sharpen", "blur", "edge detection"}; @@ -147,7 +195,7 @@ static std::vector makeLanterns() { int main() { Window window; - if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 22")) return 1; + if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 23")) return 1; // 画面(既定のフレームバッファ)がsRGBか:GL_FRAMEBUFFER_SRGBが効くのはsRGBのときだけ // Is the screen (the default framebuffer) sRGB? GL_FRAMEBUFFER_SRGB only has an effect if it is @@ -169,13 +217,17 @@ int main() { // stays linear (A = height) std::optional brickTexture = Texture2D::load("assets/textures/bricks.png", {.srgb = true}); std::optional brickNormal = Texture2D::load("assets/textures/bricks_normal.png"); + std::optional leavesTexture = Texture2D::load("assets/textures/leaves.png", {.srgb = true}); + // 影の地図を描くシェーダーと、それを見せるシェーダー / 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 || - !brickNormal) + !brickNormal || !leavesTexture || !shadowShader || !shadowDebug) return 1; grassTexture->setWrap(GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE); - for (const Shader *s : {&*phong, &*skybox, &*post, &*unlit}) + for (const Shader *s : {&*phong, &*skybox, &*post, &*unlit, &*shadowShader}) if (!s->checkUniformBlock("Camera", sizeof(CameraBlock)) || !s->checkUniformBlock("Lights", sizeof(LightsBlock)) || - !s->checkUniformBlock("Post", sizeof(PostBlock))) + !s->checkUniformBlock("Post", sizeof(PostBlock)) || !s->checkUniformBlock("Shadow", sizeof(ShadowBlock))) return 1; std::optional scene = Model::load("assets/models/diorama.glb"); @@ -195,6 +247,22 @@ int main() { UniformBuffer cameraUbo(kCameraBinding); UniformBuffer lightsUbo(kLightsBinding); UniformBuffer postUbo(kPostBinding); + UniformBuffer shadowUbo(kShadowBinding); + + // 影の地図:色なし、深度だけのテクスチャ(32ビット浮動小数点)。比較モード・GL_LINEAR・外側は1 + // The shadow map: no colour, only a depth texture (32-bit float). Comparison mode, GL_LINEAR, 1 outside + size_t shadowSizeIndex = 2; + const FramebufferSpec shadowSpec = {.colorFormat = 0, .depthStencilFormat = GL_DEPTH_COMPONENT32F, .depthTexture = true}; + Framebuffer shadowFbo(kShadowSizes[shadowSizeIndex], kShadowSizes[shadowSizeIndex], shadowSpec); + if (!shadowFbo.complete()) return 1; + // 影の地図を「見る」ためのサンプラーオブジェクト:比較なし。ユニットに繋ぐとテクスチャ自身の設定より優先される + // A sampler object for *looking at* the shadow map: no comparison. Bound to a unit, it overrides the texture's own + // sampling state + GLuint rawDepthSampler = 0; + glCreateSamplers(1, &rawDepthSampler); + glSamplerParameteri(rawDepthSampler, GL_TEXTURE_COMPARE_MODE, GL_NONE); + glSamplerParameteri(rawDepthSampler, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glSamplerParameteri(rawDepthSampler, GL_TEXTURE_MAG_FILTER, GL_NEAREST); // HDRのフレームバッファ(第21章):色はGL_RGBA16F(1より明るい値も負の値も持てる半精度の浮動小数点)。 // 付け先0 = 場面の色、付け先1 = ブルームにする明るい部分(MRT)。MSAA(第20章)で描いて sceneFbo に解決する @@ -220,15 +288,17 @@ int main() { glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS); Camera fps; - fps.position = {0.3f, 1.6f, 10.0f}; - fps.pitch = radians(-4.0f); + fps.position = {0.6f, 3.6f, 12.5f}; + fps.pitch = radians(-17.0f); OrbitCamera orbit; orbit.target = {0.0f, 1.0f, 2.0f}; orbit.distance = 11.0f; orbit.yaw = radians(20.0f); - bool useOrbit = false, normalMaps = true, parallax = true, movingLight = true; + bool useOrbit = false, shadowsOn = true, fitFrustum = false, showShadowMap = false; + size_t biasMode = kDefaultBias; + 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; @@ -239,7 +309,8 @@ 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()) + if (key == GLFW_KEY_R && phong->reload() && skybox->reload() && post->reload() && blur->reload() && unlit->reload() && + shadowShader->reload() && shadowDebug->reload()) printf("シェーダーを読み直した / shaders reloaded\n"); if (key == GLFW_KEY_TAB) window.setCursorCaptured(!window.cursorCaptured()); if (key == GLFW_KEY_C) { @@ -259,15 +330,32 @@ int main() { exposureEv += key == GLFW_KEY_EQUAL ? 0.5f : -0.5f; printf("exposure: %+.1f EV (x%.3g)\n", exposureEv, std::exp2(exposureEv)); } - if (key == GLFW_KEY_M) { - normalMaps = !normalMaps; - printf("normal maps: %s\n", normalMaps ? "on" : "off"); + if (key == GLFW_KEY_H) { + 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_X) { - parallax = !parallax; - printf("parallax mapping: %s\n", parallax ? "on" : "off"); + if (key == GLFW_KEY_K) { + cullMode = (cullMode + 1) % 3; + printf("shadow pass culling: %s\n", kCullNames[cullMode]); } - if (key == GLFW_KEY_L) movingLight = !movingLight; + 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; @@ -311,6 +399,28 @@ int main() { }; // 樽の置き場所 / 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; + 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; @@ -323,8 +433,7 @@ int main() { std::vector lanterns = makeLanterns(); Mesh sphereMesh = makeSphere(24, 12); constexpr float kLanternGlow = 6.0f; - const Vec3 kMovingLightColor = {1.0f, 0.75f, 0.45f}; - Vec3 movingLightPos; + FullscreenTriangle fullscreen; glEnable(GL_CULL_FACE); @@ -339,8 +448,7 @@ int main() { phong->use(); phong->set("uViewMode", viewMode); - phong->set("uNormalMapping", normalMaps ? 1 : 0); - phong->set("uParallaxMapping", parallax ? 1 : 0); + phong->set("uEnvironmentTint", environmentTint); phong->set("uModel", Mat4::identity()); phong->set("uNormalMatrix", normalMatrix(Mat4::identity())); @@ -373,14 +481,11 @@ int main() { b.mesh->draw(); } for (const Placement &b : barrels) barrel->draw(*phong, translate(b.position) * rotateY(b.angle), white, ModelPass::Opaque); - // 回る点光源の目印(HDRで光る) / the marker of the circling point light (glows in HDR) - if (movingLight) { - unlit->use(); - unlit->set("uColor", 8.0f * kMovingLightColor); - Mat4 model = translate(movingLightPos) * scale({0.08f, 0.08f, 0.08f}); - unlit->set("uModel", model); - sphereMesh.draw(); - phong->use(); + postMaterial.apply(*phong, white); + for (const Mat4 &m : posts) { + phong->set("uModel", m); + phong->set("uNormalMatrix", normalMatrix(m)); + postMesh.draw(); } // 草:アルファトゥカバレッジならdiscardの代わりにサンプルの一部だけを覆う(MSAAのときだけ意味がある) @@ -388,6 +493,15 @@ int main() { // meaningful with MSAA) glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE); phong->set("uAlphaToCoverage", 1); + // 葉の屋根(両面) / the roof of leaves (double-sided) + leavesMaterial.apply(*phong, white); + 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) { @@ -409,6 +523,37 @@ int main() { glDepthFunc(GL_LESS); }; + // 影を落とす物を全部、影の地図に描く(深度だけ)。切り抜き(草、葉)はテクスチャのアルファで捨てる + // Draws every shadow caster into the shadow map (depth only). Cut-outs (grass, leaves) discard by texture alpha + auto drawShadowCasters = [&] { + shadowShader->use(); + shadowShader->set("uAlphaMask", 0); + auto drawMesh = [&](const Mesh &mesh, const Mat4 &model) { + shadowShader->set("uModel", model); + mesh.draw(); + }; + drawMesh(floorMesh, Mat4::identity()); + scene->drawDepth(*shadowShader, Mat4::identity(), white); + for (const Placement &c : kCrates) crate->drawDepth(*shadowShader, translate(c.position) * rotateY(c.angle), white); + for (const Placement &b : barrels) barrel->drawDepth(*shadowShader, translate(b.position) * rotateY(b.angle), white); + shadowShader->set("uAlphaMask", 0); + for (const Lantern &l : lanterns) drawMesh(sphereMesh, translate(l.position) * scale({0.3f, 0.38f, 0.3f})); + 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); + // 切り抜き:両面なのでカリングなし / cut-outs: two-sided, so no culling + glDisable(GL_CULL_FACE); + shadowShader->set("uAlphaMask", 1); + shadowShader->set("uAlphaCutoff", 0.5f); + shadowShader->set("uBaseAlpha", 1.0f); + leavesTexture->bind(0); + for (const Mat4 &m : roofModels) drawMesh(roofMesh, m); + grassTexture->bind(0); + for (const Placement &g : grass) drawMesh(tuftMesh, translate(g.position) * rotateY(g.angle) * scale({0.75f, 0.75f, 0.75f})); + shadowShader->set("uAlphaMask", 0); + }; + + int frame = 0; double lastTime = window.time(); while (!window.shouldClose()) { double now = window.time(); @@ -440,9 +585,7 @@ int main() { Quat::fromAxisAngle({0.0f, 0.0f, 1.0f}, -0.8f * windmillTime) * rotorStart; float aspect = static_cast(sceneFbo.width()) / static_cast(sceneFbo.height()); - // 壁の前を回る光:壁すれすれの角度から照らすと凹凸がよく見える / the light circling in front of the wall: light from - // grazing angles shows the bumps best - movingLightPos = {-1.6f + 1.8f * std::cos(0.7f * windmillTime), 1.3f + 0.6f * std::sin(1.3f * windmillTime), 4.75f}; + CameraBlock camera; camera.view = useOrbit ? orbit.view() : fps.view(); camera.proj = useOrbit ? orbit.projection(aspect) : fps.projection(aspect); @@ -468,8 +611,7 @@ int main() { for (size_t i = 3; i < 6; ++i) lights.points.push_back({.position = lanterns[i].position, .color = 1.5f * lanterns[i].color, .attenuation = kMediumRange}); } - if (movingLight) - lights.points.push_back({.position = movingLightPos, .color = 2.5f * kMovingLightColor, .attenuation = kMediumRange}); + if (flashlightOn) lights.spots.push_back({.position = camera.viewPos, .direction = viewDir, .color = {1.0f, 0.95f, 0.85f}}); lightsUbo.update(lights.toBlock()); @@ -487,6 +629,70 @@ int main() { } postUbo.update(postSettings); + //------------------------------------------------------------------ + // 0. 影の地図:太陽から見た深度(第23章) / 0. the shadow map: depth as seen from the sun (chapter 23) + //------------------------------------------------------------------ + // 光の箱:場面全体を囲む球か、カメラの視錐台の手前8 mを囲む球 / the light box: a sphere around the whole scene, + // or a sphere around the first 8 m of the camera frustum + Vec3 fitCentre = {0.0f, 1.0f, 2.5f}; + float fitRadius = 9.5f; + if (fitFrustum) { + float nearPlane = 0.1f, farPlane = 8.0f, fov = useOrbit ? orbit.fov : fps.fov; + Vec3 f = viewDir, r = normalize(cross(f, Vec3{0.0f, 1.0f, 0.0f})), u = cross(r, f); + float th = std::tan(0.5f * fov); + Vec3 corners[8]; + int k = 0; + for (float dist : {nearPlane, farPlane}) + for (float sy : {-1.0f, 1.0f}) + for (float sx : {-1.0f, 1.0f}) + corners[k++] = camera.viewPos + dist * f + (sx * dist * th * aspect) * r + (sy * dist * th) * u; + // 中心は8つの角の平均、半径は一番遠い角まで(カメラが回っても大きさは変わらない) + // Centre = the mean of the 8 corners, radius = to the farthest corner (its size does not change as the camera turns) + fitCentre = {0.0f, 0.0f, 0.0f}; + for (Vec3 c : corners) fitCentre = fitCentre + 0.125f * c; + fitRadius = 0.0f; + for (Vec3 c : corners) fitRadius = std::max(fitRadius, length(c - fitCentre)); + } + if (frame++ % 60 == 5) printf("light box radius %.2f m: %.1f mm per shadow texel\n", fitRadius, 2000.0f * fitRadius / static_cast(shadowFbo.width())); + const BiasMode &bias = kBiasModes[biasMode]; + float depthRange = 1.0f; + ShadowBlock shadowBlock; + shadowBlock.lightSpace = lightSpaceMatrix(lights.directional.direction, fitCentre, fitRadius, shadowFbo.width(), depthRange); + // バイアスはメートルで決めて、0〜1の深度に直す(正射影なので深度は距離に比例) / biases are chosen in metres and + // converted to 0..1 depth (orthographic: depth is proportional to distance) + float unit = bias.inTexels ? 2.0f * fitRadius / static_cast(shadowFbo.width()) : 1.0f; // m + shadowBlock.bias = bias.constant * unit / depthRange; + shadowBlock.slopeBias = bias.slope * unit / depthRange; + shadowBlock.normalOffset = bias.normalOffset * unit; + shadowBlock.filter = shadowFilter; + shadowBlock.texel = {1.0f / static_cast(shadowFbo.width()), 1.0f / static_cast(shadowFbo.height())}; + shadowBlock.enabled = shadowsOn ? 1 : 0; + shadowUbo.update(shadowBlock); + // 硬い影はGL_NEAREST、それ以外はGL_LINEAR(比較の結果を2×2で補間) / hard shadows use GL_NEAREST, the others + // GL_LINEAR (the comparison results are blended 2 × 2) + GLenum shadowFilterMode = shadowFilter == static_cast(ShadowFilter::Hard) ? GL_NEAREST : GL_LINEAR; + shadowFbo.depth().setFilter(shadowFilterMode, shadowFilterMode); + + if (shadowsOn) { + shadowFbo.bind(); + glEnable(GL_DEPTH_TEST); + glClear(GL_DEPTH_BUFFER_BIT); + if (cullMode == 1) glCullFace(GL_FRONT); // 表面を捨て、裏面の深度を保存する / keep the back faces' depth + if (cullMode == 2) glDisable(GL_CULL_FACE); + if (bias.polygonOffset) { + // ハードウェアの傾きバイアス:深度 += factor × 傾き + units × 最小の深度の差 / hardware slope bias: + // depth += factor × slope + units × the smallest depth step + glEnable(GL_POLYGON_OFFSET_FILL); + glPolygonOffset(2.0f, 4.0f); + } + drawShadowCasters(); + glDisable(GL_POLYGON_OFFSET_FILL); + glCullFace(GL_BACK); + glEnable(GL_CULL_FACE); + } + // 影の地図はユニット5(描き終わってから繋ぐ) / the shadow map goes on unit 5 (after it has been drawn) + shadowFbo.depth().bind(5); + //------------------------------------------------------------------ // 1. 場面をHDR・MSAAで描き、解決する(色の付け先は2つとも) / 1. draw the scene in HDR with MSAA and resolve it // (both colour attachments) @@ -516,11 +722,6 @@ int main() { // mapping, sRGB //------------------------------------------------------------------ Framebuffer::bindDefault(window.width(), window.height()); - // GammaMode 1と3:GPUが書くときにリニア→sRGBにする(画面がsRGBのときだけ効く) - // Gamma modes 1 and 3: the GPU converts linear → sRGB on write (only works if the screen is sRGB) - bool framebufferSrgb = postSettings.gammaMode == static_cast(GammaMode::FramebufferSrgb) || - postSettings.gammaMode == static_cast(GammaMode::Double); - if (framebufferSrgb) glEnable(GL_FRAMEBUFFER_SRGB); post->use(); post->set("uEffect", effect); post->set("uFlipX", 0); @@ -528,9 +729,25 @@ int main() { bloomFbo[1].color().bind(1); // 最後の縦のパスの結果 / the result of the last vertical pass sceneFbo.color(1).bind(2); fullscreen.draw(); - glDisable(GL_FRAMEBUFFER_SRGB); + + // 影の地図を左下に(比較なしのサンプラーで深度を読む) / the shadow map at the bottom left (depth read through the + // sampler without comparison) + if (showShadowMap) { + glViewport(16, 16, 320, 320); + shadowDebug->use(); + shadowFbo.depth().bind(0); + glBindSampler(0, rawDepthSampler); + fullscreen.draw(); + glBindSampler(0, 0); // ユニット0はテクスチャ自身の設定に戻る / unit 0 goes back to the texture's own state + // 影の地図をユニット0から外す:次のシャドウパスではshadow.fragのuBaseMapがユニット0で、描き込み中の深度を + // 読むとフィードバックループになる / take the shadow map off unit 0: in the next shadow pass shadow.frag's + // uBaseMap is on unit 0, and reading the depth being written would be a feedback loop + white.bind(0); + glViewport(0, 0, window.width(), window.height()); + } window.swapBuffers(); } + glDeleteSamplers(1, &rawDepthSampler); return 0; } diff --git a/src/model.cc b/src/model.cc index e38413d..d0fa55a 100644 --- a/src/model.cc +++ b/src/model.cc @@ -323,6 +323,12 @@ void Model::drawGeometry(const Shader &shader, const Mat4 &transform) const { drawItems(items, shader, nullptr, shader.has("uNormalMatrix")); } +void Model::drawDepth(const Shader &shader, const Mat4 &transform, const Texture2D &white) const { + std::vector items; + for (int root : roots) collect(root, transform, transform, true, ModelPass::Opaque, {}, items); + drawItems(items, shader, &white, false, 0, true); +} + const Model::MaterialData &Model::materialOf(const Primitive &p) const { return p.material >= 0 ? materials[static_cast(p.material)] : defaultMaterial; } @@ -356,14 +362,24 @@ void Model::drawInstanced(const Shader &shader, const Texture2D &white, GLsizei } void Model::drawItems(const std::vector &items, const Shader &shader, const Texture2D *white, - bool normals, GLsizei instances) const { + bool normals, GLsizei instances, bool depthOnly) const { bool culling = glIsEnabled(GL_CULL_FACE); // 呼ぶ側の設定を覚えておく / remember the caller's setting for (const DrawItem &item : items) { const Primitive &p = *item.primitive; const MaterialData &md = materialOf(p); shader.set("uModel", item.world); if (normals) shader.set("uNormalMatrix", normalMatrix(item.world)); - if (white) { + if (white && depthOnly) { + // 影:切り抜き(Mask)だけテクスチャのアルファが要る / shadows: only cut-outs (Mask) need the texture's alpha + bool mask = md.phong.alphaMode == AlphaMode::Mask; + shader.set("uAlphaMask", mask ? 1 : 0); + if (mask) { + const Texture2D *base = texture(md.pbr.baseColorTexture.index); + (base ? base : white)->bind(0); + shader.set("uAlphaCutoff", md.phong.alphaCutoff); + shader.set("uBaseAlpha", md.phong.alpha); + } + } else if (white) { Material m = md.phong; m.diffuseMap = texture(md.pbr.baseColorTexture.index); // 色 = 係数 × テクスチャ / colour = factor × texture m.emissionMap = texture(md.pbr.emissiveTexture.index); diff --git a/src/model.hh b/src/model.hh index 153e5bb..c862edf 100644 --- a/src/model.hh +++ b/src/model.hh @@ -71,6 +71,14 @@ 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; + // 影の地図の深度だけを描く(第23章)。OpaqueとMaskのプリミティブ(Blendは影を落とさない)。Maskのマテリアルは + // ベースカラーのテクスチャ(なければwhite)をユニット0に繋ぎ、uAlphaMask = 1、uAlphaCutoff、uBaseAlphaを設定する + // (シェーダーがdiscardで葉の形に切り抜く)。ほかはuAlphaMask = 0。両面のマテリアルはカリングを切る。 + // Draws depth only, for shadow maps (chapter 23). Opaque and Mask primitives (Blend casts no shadow). For Mask + // materials the base colour texture (or white) goes on unit 0 and uAlphaMask = 1, uAlphaCutoff and uBaseAlpha are + // set (the shader discards to cut out leaves); otherwise uAlphaMask = 0. Double-sided materials turn culling off. + void drawDepth(const Shader &shader, const Mat4 &transform, const Texture2D &white) 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); @@ -109,7 +117,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) const; + GLsizei instances = 0, bool depthOnly = false) const; const MaterialData &materialOf(const Primitive &p) const; const Texture2D *texture(int index) const; // なければnullptr / nullptr if missing diff --git a/src/texture.cc b/src/texture.cc index e874ed8..8b6788d 100644 --- a/src/texture.cc +++ b/src/texture.cc @@ -128,3 +128,13 @@ std::optional decodeImage(const unsigned char *bytes, size_t size, bool f stbi_image_free(pixels); return image; } + +void Texture2D::setBorderColor(float r, float g, float b, float a) { + const float color[4] = {r, g, b, a}; + glTextureParameterfv(handle, GL_TEXTURE_BORDER_COLOR, color); +} + +void Texture2D::setCompare(bool on) { + glTextureParameteri(handle, GL_TEXTURE_COMPARE_MODE, on ? GL_COMPARE_REF_TO_TEXTURE : GL_NONE); + glTextureParameteri(handle, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL); // 手前か同じなら1(光が当たる) / 1 if nearer or equal (lit) +} diff --git a/src/texture.hh b/src/texture.hh index 8ebcc25..09c4b7a 100644 --- a/src/texture.hh +++ b/src/texture.hh @@ -62,6 +62,14 @@ public: void setFilter(GLenum minFilter, GLenum magFilter); void setWrap(GLenum wrapS, GLenum wrapT); + // GL_CLAMP_TO_BORDERで外側を読んだときの色(影の地図では1 = 一番奥 = 影なし、第23章) + // The colour read outside with GL_CLAMP_TO_BORDER (1 = farthest = not in shadow for shadow maps, chapter 23) + void setBorderColor(float r, float g, float b, float a); + // 深度テクスチャの比較モード(第23章):onなら sampler2DShadow で texture(s, vec3(uv, 深さ)) が + // 「深さ <= 保存された深度」の結果(0か1、GL_LINEARなら周りの4テクセルの結果の補間)を返す + // Depth comparison mode for depth textures (chapter 23): when on, texture(s, vec3(uv, depth)) on a sampler2DShadow + // returns the result of "depth <= stored depth" (0 or 1; with GL_LINEAR the interpolated results of 4 texels) + void setCompare(bool on); // テクスチャユニットunitに繋ぐ(シェーダーの layout(binding = unit)) / attach to texture unit `unit` void bind(GLuint unit) const { glBindTextureUnit(unit, handle); } diff --git a/src/uniforms.hh b/src/uniforms.hh index b0cd31a..840124f 100644 --- a/src/uniforms.hh +++ b/src/uniforms.hh @@ -12,7 +12,7 @@ // 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) +constexpr GLuint kShadowBinding = 2; // Shadow:光から見た行列と影の設定(第23章) / light-space matrix + settings (ch. 23) constexpr GLuint kPostBinding = 3; // Post:露出、トーンマッピング、ブルーム(第21章) / exposure, tone mapping, bloom (ch. 21) // std140の規則(よく使うものだけ) / the std140 rules (the common ones) @@ -99,3 +99,37 @@ struct PostBlock { static_assert(offsetof(PostBlock, bloomThreshold) == 8); static_assert(offsetof(PostBlock, view) == 20); static_assert(sizeof(PostBlock) == 32); + +// 影の地図の読み方(phong.fragのuShadowFilterと同じ番号) / how the shadow map is filtered (same numbers as uShadowFilter) +enum class ShadowFilter { + Hard = 0, // GL_NEARESTで1回:ギザギザ / one GL_NEAREST lookup: jagged + Hardware2x2 = 1, // GL_LINEARで1回:GPUが4テクセルの比較結果を補間 / one GL_LINEAR lookup: the GPU blends 4 comparisons + Pcf3x3 = 2, // GL_LINEARで3×3回(PCF) / 3 × 3 GL_LINEAR lookups (PCF) + Pcf5x5 = 3, // 5×5回 / 5 × 5 lookups +}; + +// GLSL: +// layout(std140, binding = 2) uniform Shadow { +// mat4 uLightSpace; // offset 0:ワールド → 光のクリップ座標 / world → the light's clip space +// float uShadowBias; // 64:深度から引く一定の量(0〜1の深度) / constant offset subtracted (0..1 depth) +// float uShadowSlopeBias; // 68:面が光に対して斜めなほど大きく / grows as the surface tilts away from the light +// float uShadowNormalOffset;// 72:法線方向にずらす距離(m) / distance pushed along the normal (m) +// int uShadowFilter; // 76 +// vec2 uShadowTexel; // 80:1テクセルのUV / one texel in UV units +// int uShadowsEnabled; // 88 +// int uShadowPad; // 92 +// }; // 96 bytes +struct ShadowBlock { + Mat4 lightSpace; + float bias = 0.0f; + float slopeBias = 0.0f; + float normalOffset = 0.0f; + int filter = static_cast(ShadowFilter::Pcf3x3); + Vec2 texel; + int enabled = 1; + int pad = 0; +}; +static_assert(offsetof(ShadowBlock, bias) == 64); +static_assert(offsetof(ShadowBlock, texel) == 80); +static_assert(offsetof(ShadowBlock, enabled) == 88); +static_assert(sizeof(ShadowBlock) == 96);