23. シャドウマッピング
第10章から、あたし達の太陽は自分の方を向いた全ての面を照らしてきました。
間に壁が立っていてもです。
今迄のライティングがやっていない事が1つだけあります。
光への向きは知っていても、其の道が空いているかどうかは知らないのです。
影が無いと物は床から浮いて見え、何処に立っているのかが分かり難くなります。
此の章では、太陽にシャドウマッピングで本物の影を付けます。
殆ど全てのリアルタイムレンダラーが主な光に使っている技法です。
まずシーンを太陽から見て深度テクスチャに描き、其の後で普通にシーンを描く時に、全てのピクセルが其のテクスチャに「太陽はあたしを見たのか、其れともあたしより手前の何かを見たのか」と尋ねます。
考え方は2文で済みますが、綺麗な影を得るには此の章の残り全部が必要です。
光の正射影の箱、テクセルのスナップ、シャドウアクネと其れを治すバイアス、ピーターパン現象、そしてフィルタリングです。
其々にデモのキーがあるので、問題を自分の目で確かめられます。
23.1 此の章で作る物
第22章のシーンは其のままです。
レンガの壁、柱、レンガの球、樽、ジオラマ、木箱、電線と提灯の付いた電柱、草、空です。
新しいのは樽の上のパーゴラです。
木の柱4本と、アルファテストした葉の2層の屋根で出来ていて、太陽が樽と床と壁に葉の形のまだらな影を落とします。
床の影が見える様に、カメラは前より高く後ろの(0.6, 3.6, 12.5)から始まり、17°見下ろしています。
操作:
- W、A、S、D、スペース、左Ctrl、Shift、マウス、ホイール:今迄通り移動と見回し
- H:影のオン・オフ(新規)
- B:バイアスの方法:なし、一定1 cm、傾き+法線方向のずらし(既定)、
glPolygonOffsetだけ、40 cm(新規) - K:シャドウパスのカリング:裏面(既定)、表面、なし(新規)
- G:影のフィルター:硬い、ハードウェア2×2、PCF 3×3(既定)、PCF 5×5(新規)
- J:光の箱:シーン全体を囲む(既定)、又はカメラの視野の手前8 mを囲む(新規)
- Z:シャドウマップの大きさ:512、1024、2048(既定)、4096(新規)
- O:シャドウマップを左下に表示(新規)
- V:表示モード。10番目の「shadow」が増え、影の係数だけを見せます
- =と−:露出、1〜6:ポストプロセスの効果
- C:FPS ⇔ オービットカメラ、N:昼 ⇔ 夜、F:懐中電灯、P:風車を止める
- Tab:カーソルの解放、R:シェーダーを読み直す、Esc:終了
第22章からの変更:
src/framebuffer.hhとsrc/framebuffer.cc:FramebufferSpec::depthTextureとdepth()src/texture.hhとsrc/texture.cc:setBorderColor()とsetCompare()src/uniforms.hh:kShadowBinding、ShadowBlock、enum class ShadowFiltersrc/model.hhとsrc/model.cc:シャドウパス用のdrawDepth()shaders/shadow.vert、shaders/shadow.frag、shaders/shadow_debug.frag(新規)shaders/phong.frag:Shadowブロック、テクスチャユニット5のシャドウマップ、shadowFactor()、表示モード9src/main.cc:パーゴラ、シャドウパス、lightSpaceMatrix()、バイアスのモード、新しいキーassets/textures/leaves.png(新規、11 KB):第16章の葉の塊をテクスチャとして保存した物(完成したファイルは章のZIPとアセットのZIPのch23/に入っています)
壁の前を回っていた点光源と、第22章のキーM、X、Lは無くなりました。
法線マッピングと視差マッピングはオンの儘です。
第21章のガンマモードの名残のGL_FRAMEBUFFER_SRGBの行も消しました。
第22章でガンマモードを「シェーダー」に固定したので、もう何もしていなかったからです。
23.2 考え方:まず光から見る
或る点と光の間に何かがあれば、其の点は影の中です。
太陽の様な平行光源では「間」は1つの決まった向きに沿った事なので、ピクセル毎の問いは「此の点から太陽の方へ歩いたら、何かにぶつかるか」です。
GLSL 第14章のレイマーチャーは、2本目のレイを進めて丁度此の問いに答えました。
ラスタライザーは三角形の中をレイで進めないので、問いを逆にして光の方に尋ねます。
其の為1フレームにパスが2つになります:
- シャドウパス。 光の所に「カメラ」を置いて光の向きを向かせ、シーンを深度だけで描きます。出来た深度テクスチャの各テクセルには、其のテクセルの光線に沿って光が最初に当たる面迄の距離が入ります。此のテクスチャがシャドウマップです。
- シーンパス。 今迄通り本物のカメラからシーンを描きます。各ピクセルのワールド座標を同じ光の行列で変換すると、シャドウマップの中の其のテクセルと、光からの自分の距離が分かります。自分の距離の方が保存された距離より大きければ、光に近い何かが覆っています:影です。同じなら、光は丁度此の面に届いています:光が当たります。
太陽はとても遠いので光線は平行です。
其の為光の「カメラ」は正射影、つまり視錐台ではなく箱を使います。
線型代数 第12章でもシャドウマップの話として触れた通りです。
此れでシャドウマップの全てのテクセルがワールドの同じ広さを覆い、保存される深度は距離に対して線型になります。
此の章の残りは全て、手順2の「同じ」が決して丁度同じにはならない事への対処です。
シャドウマップはテクセル毎に深度を1つしか持たず、1つのテクセルはワールドの或る範囲を覆い、其の範囲の中のピクセルは範囲の別の場所で計算された値と比べられるのです。
23.3 深度テクスチャを持つフレームバッファ
第17章から、Framebufferは深度にレンダーバッファを使ってきました。
深度を読み返す物が何も無かったからです。
シャドウマップはシーンパスでサンプリングする必要があるので、深度はテクスチャでなければなりません。
FramebufferSpecの新しいフィールド1つで其れを頼みます:
// 深度をレンダーバッファではなくテクスチャにする(影の地図、第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;
};
そしてFramebufferにはTexture2D depthTexのメンバーと、color()の隣に取り出す関数が増えます:
// 深度のテクスチャ(spec.depthTextureのときだけ、ほかは空) / the depth texture (only with spec.depthTexture, else empty)
const Texture2D &depth() const { return depthTex; }
Texture2D &depth() { return depthTex; }
createAttachments()には深度の付け先を作る方法が2つになりました:
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) {
stencilの判定は、両方の分岐で使える様にレンダーバッファの分岐の外へ移しました。
destroyAttachments()とムーブの演算は、色のテクスチャと同じ様にdepthTexを消したり移したりします。
1行ずつ見ます:
Texture2D(w, h, spec.depthStencilFormat, 1)はglTextureStorage2D(handle, 1, GL_DEPTH_COMPONENT32F, w, h)を呼びます。内部形式が深度の形式なら深度テクスチャになります。テクセル毎に0〜1の値が1つで、色はありません。GL_DEPTH_COMPONENT32Fは32ビットの浮動小数点で保存し、GL_DEPTH_COMPONENT24とGL_DEPTH_COMPONENT16はメモリを節約する固定小数点の代わりです。ミップマップの段は1つだけです。シャドウマップにミップマップは作りません。glNamedFramebufferTexture(fbo, GL_DEPTH_ATTACHMENT, texture, level)は、深度バッファがある筈の場所にテクスチャを付けます。後はラスタライザーが、レンダーバッファの時と全く同じ様に全てのフラグメントの深度を書き込みます。深度とステンシルをまとめた形式ならGL_DEPTH_STENCIL_ATTACHMENTに付けます。- 両方の向きの
GL_CLAMP_TO_BORDERは、0〜1の外を読んだ時に、繰り返しや端の引き伸ばしではなく決まった境界色を返させます。深度テクスチャでは境界色の赤の成分が深度なので、setBorderColor(1, 1, 1, 1)は「シャドウマップの外では、一番近い面は無限に遠い」という意味です。光の箱の外は全て光が当たります。 GL_LINEARは普通のテクスチャなら深度を混ぜますが、比較モードと一緒だともっと役に立つ事をします。23.9節で見ます。- マルチサンプルの深度テクスチャ(
GL_TEXTURE_2D_MULTISAMPLE)もありますが、シャドウマップでは要らないので、其の組み合わせではエラーを表示するだけです。
Texture2Dの新しい2つの関数は薄いラッパーです:
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)
}
glTextureParameterfv(texture, GL_TEXTURE_BORDER_COLOR, color)はfloatを4つ(RGBA)受け取ります。配列用なのがfvの版です。GL_TEXTURE_COMPARE_MODEをGL_COMPARE_REF_TO_TEXTUREにすると、テクスチャが比較モードになります。読み取りはもう保存された深度を返しません。代わりにシェーダーが座標と一緒に参照値の深度を渡し、テクスチャユニットが其れを保存された値と比べて、比較の結果、1.0か0.0を返します。GL_TEXTURE_COMPARE_FUNCは比べ方を選びます。GL_LEQUALでは参照値 ≤ 保存値の時に1になり、「此のピクセルは、光が最初に当たった面と同じか其れより光に近い」と読めます:光が当たります。GL_LESS、GL_GEQUAL等、第15章の深度関数も使えます。
比較モードのテクスチャは、GLSLのシャドウサンプラー型sampler2DShadowで読まなければなりません。
読み方は23.7節で見せます。
普通のsampler2Dで読むのは未定義の動作です。
Mesaは0か1を返し、他のドライバーは何を返しても構いません。
其れでも生の深度を見る方法は23.10節で見せます。
mainは色を全く持たないシャドウ用のフレームバッファを作ります:
// 影の地図:色なし、深度だけのテクスチャ(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;
第17章からcolorFormat = 0は「色なし」の意味でした。
createAttachments()は描画と読み取りのバッファをGL_NONEにします。
OpenGL 4.1より前では、色の付け先の無いフレームバッファが完全になるには此れが必要でしたし、今でも意図を示してくれます。
kShadowSizesは{512, 1024, 2048, 4096}で、Zは新しいFramebufferを作って其の中を順に回ります(% std::size(kShadowSizes)で先頭に戻ります)。
テクスチャのストレージは大きさを変えられないからです。
テクセル1つ4バイトなので、2048²のシャドウマップは16 MiB、4096²は64 MiBを使います。
深度テクスチャでよくある間違い:
- 比較モードを忘れて
sampler2DShadowで読む:結果は未定義です(全部光が当たるか、全部暗い事が多い)。 - 境界色ではなく
GL_CLAMP_TO_EDGE又はGL_REPEAT:光の箱の外で、床がシャドウマップの反対側の影を繰り返すか、シャドウマップの端に触れている物の影が続きます。 - specに色の付け先を残す:動きますが、全てのテクセルが誰も読まない色も書きます。
23.4 結合点2のShadowブロック
第19章でユニフォームバッファの結合点2を影の為に予約しました。
uniforms.hhが其処を埋めます:
constexpr GLuint kShadowBinding = 2; // Shadow:光から見た行列と影の設定(第23章) / light-space matrix + settings (ch. 23)
// 影の地図の読み方(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<int>(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);
第19章のstd140の規則で見ると、隠れた詰め物は要りません:
| メンバー | 型 | std140のアラインメント | オフセット | C++ |
|---|---|---|---|---|
uLightSpace |
mat4 |
16 | 0 | Mat4、64バイト |
uShadowBias |
float |
4 | 64 | float |
uShadowSlopeBias |
float |
4 | 68 | float |
uShadowNormalOffset |
float |
4 | 72 | float |
uShadowFilter |
int |
4 | 76 | int |
uShadowTexel |
vec2 |
8 | 80 | Vec2、8バイト |
uShadowsEnabled |
int |
4 | 88 | int |
uShadowPad |
int |
4 | 92 | int、ブロックを96に切り上げる |
vec2は8バイトの境目が必要で、80は其の境目なので、前の4つのスカラーは隙間無く詰まります。
GLSLの宣言は其の儘shadow.vertとphong.fragにコピーしてあります:
// 影(ユニフォームバッファ、結合点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;
};
mainは他の3つの隣にUniformBuffer<ShadowBlock> shadowUbo(kShadowBinding);を作り、第19章の起動時の確認には新しいブロックと新しいプログラムが加わりました:
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("Shadow", sizeof(ShadowBlock)))
return 1;
ブロックを宣言していないプログラムは確認を通ります(大きさが−1になる為)。
其の為skyboxやpostにShadowが無くても問題ありません。
23.5 光の行列
回転、其れから正射影の箱
シャドウパスには太陽のビュー行列と射影行列が要り、其の2つを掛けて1つのuLightSpaceにします。
太陽には位置が無く向きしかないので、其の「カメラ」は光の線の上なら何処に置いても構いません。
大事なのは何方を向くかと、ワールドのどの箱を覆うかです。
関数全体です:
// 平行光源の光から見た行列: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<float>(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;
}
順に見ます:
- ビューは純粋な回転です。 線型代数 第11章の
lookAt(eye, target, up)は、前の向きから右・上・後ろの基底を作ります。目を原点に、目標をdに置くと平行移動の列は0になり、行列は光が−Zの向きに進む様にワールドを回すだけです。upのヒントはdと平行であってはいけないので(外積が0になります)、真上の太陽では代わりに+Zを使います。 - 光の座標で箱を置きます。
cは覆いたい球の中心を、回した座標で見た物です。cx − rからcx + r、cy − rからcy + rの正射影の箱は其の周りの一辺2rの正方形を覆い、orthographicGlが其の正方形をNDCの−1〜1に写します(導き方は線型代数 第12章)。正射影では、目が原点に「ある」かどうかは関係ありません。大事なのは平面だけです。 - 奥行き。 ビューの前にある点のzは負で、光に沿った距離は−zです。球は距離−c.z − rから−c.z + rに広がります。ニアプレーンは更に光の方へ20 m引き寄せます。球の外にある物も、球の中に影を落とせるからです。すぐ外の電柱や、カメラの上の屋根がそうです。ニアプレーンより手前の物はシャドウパスで切り取られ、何の影も落としません。
depthRangeは箱の奥行きをメートルで返し、23.8節のバイアスの変換に使います。 - スナップ。
cxとcyはテクセル単位に切り捨てます。何故かは此の節の最後で説明します。
既定の数字で例を計算します。
太陽は(−0.5, −1, −0.35)の向きに進むので、正規化するとです。
シーンの球は中心(0, 1, 2.5)、半径r = 9.5 mで、シャドウマップの幅は2048テクセルなので、1テクセルが覆うのは
です。
回した中心はです。
は切り捨てで−221になるので、同じ様にからです。
箱はテクセルの格子に乗る為に0.24テクセルと0.25テクセル動きました。
奥行きは、なので、箱の奥行きは mです。
ニアプレーンが負なのは変に見えますが、回転の為に選んだ原点より「後ろ」に平面がある、というだけの事です。
正射影の行列は気にしません。
行列のzの行の倍率はです。
光に沿って1メートル進むとNDCの深度が0.0513変わり、0〜1の深度では其の半分の変わります。
箱が何を囲むか(キーJ)
箱は出来るだけ小さい方が良いです。
箱が小さい程テクセルが小さくなり、影が鋭くなるからです。
でも画面上で影を受ける可能性のある全ての点を含んでいなければなりません。
コードは球を当てはめ、Jで2つの球を切り替えます:
// 光の箱:場面全体を囲む球か、カメラの視錐台の手前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<float>(shadowFbo.width()));
- シーンに合わせる(既定)。 ジオラマの全てを囲む、手で測った球です。太陽は動かないので、行列は毎フレーム同じです。単純で安定していますが、カメラの後ろの部分にもテクセルを使いますし、規模が大きくなると通用しません。10倍大きいレベルなら、10倍広い箱と10倍大きいテクセルが必要になります。
- 視錐台に合わせる(J)。 視野角とアスペクト比から、線型代数 第12章の視錐台と全く同じ様に0.1 m〜8 mのカメラの視野の角を作り、其れを通る球を求めます。8つの角はカメラに対して動かないので、其の平均と、平均から一番遠い距離は、カメラが動いても回っても変わりません。球の半径は一定です。此れがスナップの為に大事です。
プログラムは60フレーム毎に出来たテクセルの大きさを表示します。
既定の時と、其の後で視錐台に合わせた時は此うなります:
light box radius 9.50 m: 9.3 mm per shadow texel
light box: camera frustum (0.1-8 m)
light box radius 7.83 m: 7.6 mm per shadow texel
7.83 mを確かめましょう。
縦の視野角が45°で窓が1280 × 720なら、8 mの所の遠い長方形は高さの半分が m、幅の半分が mです。
近い角はとても小さいので、8つの角の平均は視線の軸の上の mの所にあります。
遠い角は其処から m先なので、半径は
です。
此処ではシーンに合わせた時よりテクセルが18 %小さいだけです。
あたし達のシーンが小さいからです。
でも視錐台に合わせる方はレベルの大きさに関係無く同じ大きさで、代わりに手前8 mより大分先には全く影が付かなくなります。
其処は箱の外なので、読み取りが境界に当たり、境界は「光が当たる」と言うからです。
此のトレードオフを解決するのがカスケード(23.12節)です。
テクセルのスナップ:縁が止まっている理由
Jをオンにすると、箱はカメラに付いて動きます。
滑らかに付いて行くと、影の縁がちらつきます。
太陽も影を落とす物も動いていないのに、カメラが動く度に縁が最大1テクセル分這い回って揺れるのです。
理由は、ワールドの中でテクセルの境目が何処に来るかです。
光の座標でxを測ると、箱はから始まり、テクセルはを覆います。
影を落とす物は、其れが中心を覆うテクセルに描かれます(ラスタライズの規則)。
従って影の縁は必ずテクセルの境目、何処かのに来ます。
がテクセルの端数だけ変わると全ての境目が一緒に動き、影を落とす物の中に入るテクセルの中心の組が変わって、縁が跳びます:
スナップはをテクセル単位に固定します。
と(Nは偶数)から、箱の端は
になり、テクセルの境目は、つまりどのでもワールドの同じ位置の組(の整数倍全て)に来ます。
カメラが動いても箱は丁度テクセル単位で滑り、ワールドの同じ点が同じテクセルの中心に乗り、影は全く同じになります。
yも同じです。
深度はスナップしませんし、其の必要もありません。
ニアプレーンとファープレーンが動くと、保存される深度と比べる深度が同じだけ変わるので、比較の結果は(浮動小数点の丸めを除いて)変わりません。
スナップが効くのは自体が変わらない時だけです。
視錐台にぴったりの箱(光の座標での角を囲む長方形)は、カメラが回ると大きさが変わり、が変わって、又全ての境目が動いてしまいます。
其の為コードは球を当てはめます。
半径が一定なのでも一定で、箱はカメラではなく光と一緒に回るので向きも変わりません。
代わりに箱は必要より少し大きくなります。
課題3でスナップを外し、縁が這い回るのを見ます。
23.6 シャドウパス
2つの小さなシェーダー
シャドウパスに要るのは深度だけなので、シェーダーはとても小さいです:
#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);
}
#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;
}
頂点シェーダーは第8章のuProj * uView * uModelを、カメラの代わりに光の行列にした物です。
頂点レイアウトのロケーション0と2だけを使い、法線と接線の属性は単に無視されます。
フラグメントシェーダーには出力がありません。
深度テストがgl_FragCoord.zを自分で深度の付け先に書き込み、フレームバッファに色の付け先が無いので、他に書く物が無いのです。
不透明な物だけなら空でも構いません。
discardは切り抜きの為で、後で見ます。
影を落とす物を全部描く
drawShadowCastersは、シャドウシェーダーを使いマテリアルを使わないdrawSceneの写しです:
// 影を落とす物を全部、影の地図に描く(深度だけ)。切り抜き(草、葉)はテクスチャのアルファで捨てる
// 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);
};
全ての物がdrawSceneと同じモデル行列を使います。
此れは破ってはいけない唯一の規則です。
影を落とす物の行列が影を受ける物の行列と違えば、其処に無い物の影が計算されます。
床も描いています。
此のシーンでは何の影も落としませんが、「不透明な物は全部影を落とす」が一番単純な規則で、描画呼び出し1回で済みます。
スカイボックスは描きません。
無限に遠くにあり、シャドウマップを覆ってしまうだけだからです。
モデルの後でuAlphaMaskを又0にするのは、drawDepthが最後のプリミティブに必要だった値の儘にしておくからです。
パス自体はフレームの手順0で、シーンより前です:
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);
shadowFbo.bind()は(第17章から)ビューポートもシャドウマップの大きさにします。
自分で書く時に忘れ易い所です。
窓のビューポートの儘だと、2048²のシャドウマップの隅しか埋まらないか、もっと小さいシャドウマップの端の外に描こうとします。
glClear(GL_DEPTH_BUFFER_BIT)は全てのテクセルを1、一番奥の深度に戻します。
カリングとポリゴンオフセットの行は23.8節のバイアスの実験の為の物で、最後に状態は第16章の既定に戻ります。
パスの後、深度テクスチャは此のシリーズが其の為に予約したテクスチャユニット5に繋ぎます。
順番が大事です。
描き込んでいるフレームバッファに付いていて、同時に今のプログラムがサンプリングしているテクスチャはフィードバックループで、結果は未定義です。
あたし達のシャドウマップは次のフレームのシャドウパス迄ユニット5に繋がった儘ですが、shadow.vertとshadow.fragはユニット5のサンプラーを宣言していないので、其処で書いている間に其れを読む物はありません。
ユニット0は別です。
shadow.fragのuBaseMapはユニット0にあり、23.10節のシャドウマップの重ね表示はシャドウマップをユニット0に繋ぐので、重ね表示は終わった後でユニット0にwhiteを戻します。
切り抜きは切り抜きの影を落とす
パーゴラの葉は、葉の間のアルファが0のテクスチャを貼った平らな四角形です。
シーンパスでは第16章のアルファテスト(又は第20章のアルファトゥカバレッジ)が其れを切り抜きます。
シャドウパスでも同じ事をしなければ、四角形が其々べったりした長方形の影を落とします:
其れがshadow.fragのdiscardの役目です。
uAlphaMaskがオンなら、ユニット0のベースカラーのテクスチャを頂点のUVで読み、アルファがしきい値より小さいフラグメントを捨てます。
其処には深度が書かれず、隙間から太陽が差し込みます。
mainではパーゴラの屋根と草は手で作ったメッシュなので、drawShadowCastersが自分でユニフォームを設定し、leavesTextureとgrassTextureを繋ぎます。
どちらも両面なので、カリングは切ります。
glTFのモデルでは、新しいdrawDepthでModelがマテリアル毎に同じ事をします:
// 影の地図の深度だけを描く(第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;
void Model::drawDepth(const Shader &shader, const Mat4 &transform, const Texture2D &white) const {
std::vector<DrawItem> items;
for (int root : roots) collect(root, transform, transform, true, ModelPass::Opaque, {}, items);
drawItems(items, shader, &white, false, 0, true);
}
ModelPass::Opaqueは、第16章からの不透明なシーンパスと同じく、OPAQUEとMASKのプリミティブを集めます。
drawItemsにはdepthOnlyのフラグが増え、マテリアル全部を適用する代わりに此れだけをします:
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) {
しきい値とアルファの係数はglTFのマテリアルから来ます。
drawItemsの其の先にある両面の処理は、シーンパスと全く同じ様に両面のプリミティブのカリングを切ります。
此の章のGLBファイルには実はMASKのマテリアルが1つもありません(ジオラマの木は不透明です)。
でも第16章のwindow.glbにはあり、MASKを持つモデルは全て、mainに何も足さなくても葉の形の影を落とします。
第15章の古いdrawGeometryは其の儘で、アルファの事は何も知りません。
あたし達のレンダラーではBLENDのプリミティブは影を落としません。
此れは設計上の選択です。
光を完全に遮るガラスはおかしく見えますし、半分の影や色の付いた影には、色付きの2つ目のシャドウマップが要ります。
ゲームでは「ガラスは何も落とさない」の方が大抵良い簡略化です。
23.7 phong.fragでシャドウマップを読む
シーンのシェーダーは、新しいサンプラー型でユニット5のシャドウマップを宣言します:
// 影の地図(第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;
そして太陽の影の係数を計算します:
// 平行光源の影(第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));
}
バイアスの2行(23.8節)は一旦置いておくと、中心は4つの手順です:
uLightSpace * vec4(p, 1.0)はワールド座標を光のクリップ座標に移します。シャドウパスが影を落とす物に掛けたのと同じ変換です。- wで割り(正射影の行列なら常に1ですが、此の行は透視投影のスポットライトの行列でも使えます)、NDCの−1〜1を、テクスチャ座標と深度バッファの0〜1に写します。3つの成分全てに
* 0.5 + 0.5です。OpenGLの深度バッファは既定のglDepthRange(0, 1)でを保存するので、c.zは保存された深度と其の儘比べられます。 c.z > 1.0は、点が箱のファープレーンより奥にあるという事です。其処には何も描かれていないので、光が当たる事にします。横に箱の外にある点には判定が要りません。c.xyが0〜1の外になり、境界色が深度1を返すからです。sampler2DShadowのtexture(uShadowMap, c)はvec3を受け取ります。xとyはテクスチャ座標で、zは参照値の深度です。テクスチャユニットがzを保存された深度とGL_LEQUALで比べ、1.0(光が当たる)か0.0(影)を返します。GL_LINEARなら幾つかの結果を混ぜた値です。
呼び出しは太陽のaddLightの直前にあります:
// 平行光源:光へ向かう向きは進む向きの逆。影を掛ける(第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);
光の色に係数を掛けると、影の中では其の光の拡散反射と鏡面反射の両方が消えます。
環境光、発光、空の映り込み、他の光は残ります。
本物の影も其うです。
1つの光を遮るのであって、全ての光を遮るのではありません。
夜は月が平行光源なので、其のかすかな影も付きます。
一方、提灯と懐中電灯は影を落としません。
シャドウマップを持つのは平行光源だけです。
nは頂点の法線(geometricNormal、両面の裏面での反転の後)で、法線マップの後の法線ではありません。
バイアスは面と光の角度で決まり、シャドウマップが見たのは幾何学的な面だからです。
法線マップの法線を使うと、バイアスがレンガ毎に跳び、全ての目地に沿って影がちらつきます。
表示モード9(Vを9回)はvec3(shadow)を色として書くので、影の係数だけが見えます。
太陽が届く所は白、届かない所は黒です。
23.9節のフィルターの比較の最後のパネルが此の表示です。
そしてHで全体を切れます:
23.8 シャドウアクネとバイアス
アクネは何処から来るか
Bを3回押して(バイアス「なし」)みると、光の当たる面が縞模様や輪やモアレで一杯になります。
此れがシャドウアクネで、面が自分自身に影を落としているのです。
シャドウマップはテクセル毎に、テクセルの中心で取った深度を1つ保存します。
同じテクセルの別の場所にあるピクセルは、自分の正確な深度を其の値と比べます。
光から斜めに傾いた面では、テクセルの半分が保存された深度より奥になります:
面が光の像の平面と角度を成すなら(此れは面の法線と光への向きの角度でもあり、です、線型代数 第4章)、幅の1テクセルの間に深度は
だけ変わります。
最も近いテクセルを1回読むだけなら、ピクセルは保存された中心から最大で半テクセル離れているので、誤差は最大です。
23.9節のハードウェアの2×2フィルターでは、1回の読み取りが1テクセル丸ごと離れた隣のテクセルとも比べるので、誤差は最大です。
誤差が悪い向きに出たピクセルは全て、面の「後ろ」にいる事になって自分に影を落とします。
誤差は各テクセルの中で滑らかに変わるので、模様はテクセルの格子と一緒に繰り返します:縞です。
其の上に深度の丸め誤差が加わり、光の方を向いた面にも斑点が出ます。
治し方はバイアスです。
ピクセルの本当の深度より、少なくとも誤差の分だけ光に近い深度で比べます。
23.5節の太陽の向き()と、既定の2048²のシャドウマップの9.28 mmのテクセルで、此のシーンの2つの面の数字を出すと此うなります:
| 面 | 法線 | cos θ | θ | tan θ | 2048²でのΔ = s tan θ | 512²では |
|---|---|---|---|---|---|---|
| 床 | (0, 1, 0) | 0.8536 | 31.4° | 0.610 | 5.7 mm | 22.6 mm |
| 壁の正面 | (0, 0, 1) | 0.2988 | 72.6° | 3.194 | 29.6 mm | 118.5 mm |
一定、傾きに比例、法線方向のずらし
Bはバイアスの選び方を5つ切り替えます:
// 影のバイアスの方法 / 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;
mainは選んだモードを毎フレームブロックの3つのメンバーに直します:
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<float>(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<float>(shadowFbo.width()), 1.0f / static_cast<float>(shadowFbo.height())};
shadowBlock.enabled = shadowsOn ? 1 : 0;
shadowUbo.update(shadowBlock);
光の射影は正射影なので、深度は距離に対して線型です。
光に沿った1メートルは0〜1の深度の、此処ではです。
其の為全てのバイアスをメートルで(又はテクセルで決めてunitでメートルに直して)選び、depthRangeで1回割ります。
シェーダーは箱の奥行きを知る必要がありません。
法線方向のずらしはワールドの距離なので、メートルの儘です。
シェーダーでは、飛ばした2行が仕事をします:
- 一定のバイアス:
c.z -= uShadowBias。B →「constant 1 cm」は0.01 / 39 ≈ 0.000256を引きます。床(5.7 mm必要)には足りますが、壁(29.6 mm)には足りません。其の為床は綺麗になっても、壁と樽の側面にはアクネが残ります。 - 傾きに比例するバイアス:
uShadowSlopeBias * min(tanTheta, 10.0)。誤差と全く同じ様にと共に大きくなります。tanThetaはでcosThetaから求め、分母は最低0.05に保ち、結果は10(θ ≈ 84°)で頭打ちにします。すれすれの角度ではタンジェントは無限に大きくなり、無限のバイアスは其処の影を全部消してしまうからです。 - 法線方向のずらし:
p = worldPos + n * (uShadowNormalOffset * (1.0 - cosTheta))。読む前に、点を法線に沿って面から離します。すると点は光の方へも、シャドウマップの中で横にも動き、保存された深度が光に近い側の面の物であるテクセルに入ります。傾きに比例するバイアスが苦労する所、光とほぼ平行な面で一番効きます。の係数は、光の方を向いた面では此れを0にします。其処では影をずらすだけだからです。
既定のモードは3つ全てを組み合わせます。
一定の部分が0.5テクセル、傾きがの1当たり1テクセル、法線方向のずらしが3テクセルです。
傾きの1テクセルは2×2フィルターので、半テクセルは丸めの分です。
床では深度のバイアスがテクセル ≈ 10.3 mm、法線方向のずらしがテクセル ≈ 4.1 mmです。
壁の正面ではテクセル ≈ 34.3 mm、法線方向のずらしがテクセル ≈ 19.5 mmです。
どちらも表のΔより大きく、どちらも物に比べて小さいので、目に見えて動く影はありません。
テクセルで測る
誤差はテクセルの大きさに比例し、テクセルの大きさはシャドウマップの大きさと箱で決まります。
或るシャドウマップの大きさに合わせたメートルのバイアスは、他の全ての大きさでは間違いです。
一定の1 cmは2048²では1.08テクセルですが、512²では0.27テクセルしかなく、其処では床(22.6 mm必要)にもアクネが戻ります。
其の為既定のモードは値をテクセルで持ち、毎フレーム
を掛けます。
512²ではバイアスのメートルは2048²の4倍、4096²では半分になり、視錐台に合わせた小さい箱でも縮みます。
バイアスは常に「半テクセル+傾き1当たり1テクセル」なので、どのシャドウマップの大きさでも、どの箱でも効きます。
既定のバイアスでZを押すと、影がブロック状になるか鋭くなるだけです。
Bで「constant 1 cm」にしてからZで512にすると、アクネが戻ってきます。
5つのモード全てを樽と床で並べ、6つ目のパネルにバイアス無しの表面カリング(K、後で見ます)を加えた物です:
ピーターパン現象
パネル5は逆の問題を匂わせています。
B →「40 cm」は深度を0.4 m、2048²では43テクセル引くので、影を落とす物から(光に沿って)40 cm以内の全ての点が、其の物より「手前」と見なされます。
影がピーターパンの影の様に、其れを落とす物から外れてしまうのです。
木の影は幹から離れた所から始まり、草の葉の小さな影は完全に消えます。
太陽の側からは殆ど見えません。
隙間は影を落とす物の後ろに隠れているからです。
影が落ちる側に回り込んで下さい:
従ってバイアスは釣り合いです。
少な過ぎるとアクネ、多過ぎるとピーターパン現象になり、傾きに比例しテクセルで測る既定のバイアスは、何処でも効く最小値の近くに留まります。
glPolygonOffset:ラスタライザーでのバイアス
B →「glPolygonOffset(2, 4) only」はシェーダーで全くバイアスを使いません。
代わりにシャドウパスが、保存される深度を光から遠ざけます:
glEnable(GL_POLYGON_OFFSET_FILL)は、塗り潰すポリゴンの深度のオフセットをオンにします(glPolygonMode用に_LINEと_POINTの版もあります)。glPolygonOffset(factor, units)は全てのフラグメントの深度にを足します。はウィンドウ座標でのポリゴンの深度の最大の傾き(xとyのピクセル当たりの深度の変化から成る勾配の長さで、実装は其の大きい方で近似しても構いません)、は深度バッファが区別出来る一番小さい深度の差です。固定小数点の形式では実装依存の定数、あたし達のGL_DEPTH_COMPONENT32Fの様な浮動小数点の形式では、をポリゴンの中の一番大きい深度の指数としてなので、深度と共に大きくなります。
シャドウパスの「ピクセル」はテクセルなので、はテクセル当たりの深度の変化、深度の単位でのあたし達のです。
factor = 2は、ハードウェアが三角形毎に計算する2テクセル分の傾きに比例するバイアスで、unitsは一定の部分です。
単純でただなので人気がありますが、unitsは深度の形式とドライバー毎に調整が要り、オフセットはシャドウマップに焼き込まれるので、影を受ける側に合わせられません。
パネル4では、此のシーンでは既定と同じくらい良く効いています。
表面カリング(キーK)
Kはシャドウパスのカリングを変えます。
裏面(既定)→ 表面 → なし、です。
glCullFace(GL_FRONT)だと、シャドウマップには光から背けた面、つまり閉じた物の向こう側の深度が保存されます。
光の当たる表面は保存された深度より物の厚み丸ごと手前にあるので、バイアス無しでも其処にアクネは出ません(パネル6)。
アクネは裏面に移りますが、裏面は太陽から背を向けているのでaddLightは元々日光を与えず、何も見えません。
落とし穴が2つあります。
閉じたメッシュでしか効きません。
床の様な片面の平面には保存する裏面が無いので、丸ごとカリングされてシャドウマップから消えます(床には害がありませんが、薄い屋根なら致命的です)。
とても薄い物では隙間が殆ど出来ません。
そして物が地面に触れている所では、保存される裏面が物の底になるので、接している所に細い線で光が漏れる事があります。
其の為既定は裏面カリング+バイアスです。
K →「なし」は両面を描きますが、閉じたメッシュでは手前の表面が深度テストに勝つので、裏面カリングと同じシャドウマップになります。
23.9 柔らかい縁:ハードウェアの2×2とPCF
Gはシャドウマップの読み方を4つ切り替えます:
// 硬い影は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<int>(ShadowFilter::Hard) ? GL_NEAREST : GL_LINEAR;
shadowFbo.depth().setFilter(shadowFilterMode, shadowFilterMode);
- 硬い(
GL_NEAREST、1回の読み取り):各ピクセルは1つのテクセルの0か1を受け取り、縁にはテクセルの格子が階段として見えます。此処では幅9.3 mmで、カメラが近いので見えます。 - ハードウェア2×2(
GL_LINEAR、1回の読み取り):比較モードのテクスチャでは、GL_LINEARは深度を混ぜません。テクスチャユニットは読む点の周りの4つのテクセル其々と参照値を比べ、4つの結果を双線型の重みで混ぜます。仕様は正確な方法を実装に任せていますが、実際には今のデスクトップのドライバーは此の重み付きの2×2をしますし、スクリーンショットの通りMesaのllvmpipeもします。1回の読み取りのコストで、1テクセル幅の滑らかな坂が出来ます。 - PCF 3×3(既定)とPCF 5×5:percentage-closer filtering(PCF)は1テクセルずつ離れた何回かの読み取りの平均を取ります。各読み取りが既にハードウェアの2×2の比較なので、9回の読み取りは4 × 4、25回は6 × 6のテクセルのブロックと比べます。
大事な事は名前に書いてあります。
平均するのは通った比較の割合であって、決して深度ではありません。
先に3 × 3のブロックの深度を平均してから1回比べると、遮る物の深度と床の深度の間の何処かの値になり、其の1回の比較はやはり0か1で、少し違う場所になるだけです。
縁は硬い儘です。
0と1の平均だけが、柔らかい縁の中間の値を出します。
此の柔らかい縁の幅は一定で、3 × 3なら2〜3テクセルです。
影を落とす物と受ける物の距離には関係ありません。
本物の影は接している所で鋭く、離れる程柔らかくなります(太陽には大きさがあるからです)が、PCFだけでは其れを表せません。
其れが出来る技法は23.14節で触れます。
PCFのループは、フィルターの選択については一様な制御フローの中にありますが、其の前の早期returnは違います。
其の為原理的には其処でのtexture()の暗黙の微分は未定義です(第22章の注意)。
ミップマップの段が1つのシャドウマップでは違いはありません。
選ぶ段が無いからです。
Zでシャドウマップの大きさと、其れと共にテクセルの大きさが変わります:
| シャドウマップ | メモリ | テクセル、シーンに合わせる(r = 9.5 m) | テクセル、視錐台に合わせる(r = 7.83 m) |
|---|---|---|---|
| 512² | 1 MiB | 37.1 mm | 30.6 mm |
| 1024² | 4 MiB | 18.6 mm | 15.3 mm |
| 2048² | 16 MiB | 9.3 mm | 7.6 mm |
| 4096² | 64 MiB | 4.6 mm | 3.8 mm |
512²(上の5番目のパネル)では、3 × 3のPCFは4 × 37 ≈ 15 cmに亘って平均します。
葉1枚の幅(8〜13 cm)より大きいので、まだらな模様が塊になってしまいます。
23.10 シャドウマップを見る:サンプラーオブジェクト
Oを押すと左下の隅にシャドウマップが出ます。
近い面は暗く、遠い面は明るく見えます:
深度を見せるには値として読まなければなりませんが、テクスチャは比較モードで、sampler2Dでの読み取りは未定義です。
重ねて表示する間だけ比較を切ってまた入れる事も出来ますが、OpenGLにはもっと綺麗な道具があります。
サンプラーオブジェクトです。
サンプラーオブジェクトはサンプリングの状態(フィルター、ラップのモード、境界色、LODの範囲、比較)だけを持ち、画像は持ちません。
テクスチャユニットに繋ぐと、其のユニットに繋がったテクスチャのサンプリングの状態より優先されます。
mainは起動時に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);
そしてポストプロセスのパスの後で、重ねて表示するのに使います:
// 影の地図を左下に(比較なしのサンプラーで深度を読む) / 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());
}
glCreateSamplers(n, samplers)はサンプラーオブジェクトをn個作ります(OpenGL 4.5のDSA版。glGenSamplersが3.3の元の物です)。glSamplerParameteri(sampler, pname, value)はglTextureParameteriと同じパラメーターをサンプラーに設定します。此処では比較モードGL_NONEと最近傍のフィルターです。境界色用のglSamplerParameterfvもあります。glBindSampler(unit, sampler)はテクスチャユニットに繋ぎます。ユニットはただの番号で、此処では0です。GL_TEXTURE0ではありません。glActiveTextureのコードから書き換える時の定番の間違いです。glBindSampler(unit, 0)で外すと、ユニットは又テクスチャ自身の状態を使います。glBindSampler(0, 0)が戻すのはサンプラーだけです。深度テクスチャ自身は次のフレーム迄ユニット0に残り、其処ではshadow.fragが結合点0にuBaseMapを宣言していて、其のテクスチャは書き込み中の深度の付け先なので、フィードバックループになり得ます。white.bind(0)で外します。glDeleteSamplers(1, &rawDepthSampler)はmainの最後で解放します。他のGLオブジェクトの様にRAIIのラッパーにするのが綺麗ですが、1つの章で1つのサンプラーなので其の儘書きました。
エンジンは全てにサンプラーオブジェクトを使う事が良くあります。
テクスチャは画像だけを持ち、数個のサンプラー(線型で繰り返し、線型でクランプ、最近傍、影の比較)をユニット毎に繋ぎます。
VulkanとSlangが画像とサンプラーを分けているのも同じ考え方です。
重ねて表示するのは、post.vertの画面全体の三角形を320 × 320のビューポートで、此のフラグメントシェーダーで描いた物です:
#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
}
第15章の透視投影の深度と違って、正射影の深度は線型化が要りません。
でもシーンは箱の奥の部分しか埋めていません。
球の手前に余分な20 mがあるので、球の一番近い点で既に深度は、中心で約0.76です。
pow(d, 4.0)が其の範囲を引き伸ばします。
0.51は0.07に、0.76は0.33になるので、近くの影を落とす物が床より暗く見えます。
重ねた表示はpost.fragの後で既定のフレームバッファに直接描くので、トーンマッピングはされません。
画像の一部ではなく、デバッグ用の表示です。
23.11 影のコスト
あたし達のテスト用のマシンにはGPUがありません(其の意味は第19章で説明しました)。
其の為測ったフレームの時間は2つのCPUコアで動くMesaのllvmpipeの時間で、絶対的な数字は本物のグラフィックスカードについて何も語りません。
分かるのは其のレンダラーでの相対的なコストです。
時間にはばらつきがあるので、大体の値です:
| 設定 | フレームの時間(影オフに対して) |
|---|---|
| 影オフ(H) | 1.00 |
| 既定:2048²、PCF 3×3 | 約1.5 |
| 4096²、PCF 3×3 | 約1.65 |
| 2048²、PCF 5×5 | 約1.85 |
シャドウパス自体は、シーンの2回目の安い描画です。
深度だけで、フラグメントの仕事は殆どありません。
残りの大部分は読み取りです。
シェーディングされる約90万ピクセル(1280 × 720 = 921 600。MSAAでもピクセル毎のシェーディングは1回です)の其々が、PCF 3×3では9回、5×5では25回比べます。
本物のGPUでは、深度のパスも比較も速く、フィルタリングのハードウェアが2×2の比較を1回の読み取りで行います。
数字が欲しければ、第19章のタイマークエリで自分のマシンで測って下さい。
23.12 太陽1つの先へ:点光源とカスケード(概要)
此の節の内容は、此の章のコードには実装していません。
シャドウマッピングが此処から何処へ行くかの地図です。
点光源の影
点光源は全ての向きに光るので、2Dのシャドウマップ1枚には其の見る物が収まりません。
定番の答えは深度のキューブマップです。
シーンを6回、キューブの面毎に1回、光の所に置いた90°の透視投影のカメラで描きます。
面の表は第18章のスカイボックスと同じです。
- 保存先は
Cubemap(size, GL_DEPTH_COMPONENT32F, 1)で、glNamedFramebufferTextureLayer(fbo, GL_DEPTH_ATTACHMENT, cube, 0, face)で面を1つずつ付けるか、gl_Layerを書くジオメトリシェーダー(GLSL 第15章)で6面全部を1回のパスで描きます。 - 透視投影の深度は線型ではないので(第15章)、深度のシェーダーは代わりに線型の距離を書くのが普通です:
gl_FragDepth = length(fragPos - lightPos) / farPlane。 - 読む時は光からピクセルへの向きを使います。
texture(samplerCube, fragPos - lightPos).r * farPlaneが保存された距離で、length(fragPos - lightPos) - biasと比べます。又はsamplerCubeShadowが、距離を参照値としてハードウェアで比べます。 - PCFは其のベクトルの周りの少しずつ違う向きで何回か読みます。
- テクスチャユニットの計画では、此のキューブの為にユニット6を予約してあります。
コストは光1つ・1フレーム当たりシーンのパス6回です。
其の為エンジンは影を持つ点光源を数個に限り、静的な物は何かが動いた時だけ更新し、遠くの光には小さいシャドウマップを与えるか、何も与えません。
スポットライト
スポットライトは簡単な場合です。
正射影の行列の代わりにperspectiveGl(2 · outerAngle, 1, near, far) * lookAt(position, position + direction, up)を使った、透視投影のシャドウマップ1枚です。
shadowFactorは其の儘使えます。
もうwで割っているからです。
注意が要るのはバイアスだけです。
透視投影の深度は線型ではないので、メートルのバイアスはもう1回の割り算では深度に直せません。
課題4で此の方法で懐中電灯に影を付けます。
カスケードシャドウマップ
23.5節でジレンマを見ました。
レベル全体を囲む箱はテクセルが巨大で、視野の手前数メートルを囲む箱は其の先に影を付けません。
カスケードシャドウマップ(CSM)は両方を使います。
視錐台を距離で幾つかの切片に切り、切片毎に自分の光の箱と自分のシャドウマップを持たせるのです。
- 各カスケードは、あたし達の視錐台に合わせる方法と全く同じに合わせてスナップします。切片を囲む球、テクセルのスナップ、同じ
lightSpaceMatrixです。 - シャドウマップは大抵1つの配列テクスチャ(深度の形式の
GL_TEXTURE_2D_ARRAY、sampler2DArrayShadowで読む)に入り、Shadowブロックは行列の配列と切れ目の距離に育ちます。結合点2は丁度其の為に予約してありました。 - フラグメントシェーダーはピクセルのビュー座標の深度からカスケードを選び、鋭さの変わり目が線として見えない様に、切れ目を跨いで混ぜます。
- 欲しいテクセルの密度は距離と共に下がるので、切れ目の距離は大抵、均等な分け方と対数的な分け方の間で選びます。
第36〜39章のTPSのレベルは、あたし達の9.5 mの球よりずっと大きいので、シーンに合わせる方法は使えません。
TPSでは箱をカメラの視錐台の手前15〜25 mに合わせ、あたし達と同じ様にテクセルをスナップします。
其れで足りなければ、2つのカスケードが自然な次の一歩です。
23.13 プラットフォーム毎の注意
- 比較結果のハードウェアの2×2フィルタリングは、仕様では実装依存です。実際にはWindows、Linux、FreeBSDの今のドライバー(NVIDIA、AMD、Intel、llvmpipeを含むMesa)は双線型の重み付きの版をするので、何処でも似た柔らかい縁が見えます。全く同じピクセルではありません。
glPolygonOffsetのunitsには決まった大きさがありません。GL_DEPTH_COMPONENT24の様な固定小数点の形式では1段が実装依存で、GL_DEPTH_COMPONENT32Fではポリゴン毎の深度で変わります。其の為units = 4は、形式を変えると、箱の別の所では、そして実際には別のドライバーでも、違う絶対的なオフセットになる事があります。此の章のシェーダーのバイアスは其うではなく、其れも既定にした理由の1つです。- 比較モードのテクスチャを
sampler2Dで読むのは未定義です。Mesaは0か1を返し、深度を返すドライバーも、ゴミを返すドライバーもあります。深度を見るには必ずサンプラーオブジェクトか、2つ目のテクスチャビューを使って下さい。 - Zのキーは
GLFW_KEY_Zで、GLFWはキーをUSキーボードでの位置で名付けています(第19章で=と−について書いた通りです)。ドイツ語のキーボードではYと書かれたキー、フランス語のキーボードではWと書かれたキーです。B、G、H、J、K、Oは3つの配列全てで同じ場所です。 - メモリ:4096²の32ビットの深度のシャドウマップはビデオメモリを64 MiB使います。システムのメモリを共有する内蔵GPUでは、2048²と視錐台に合わせる方法を選んで下さい。
23.14 本物のエンジンではどうしているか
- 20 mの代わりに深度のクランプ。 シャドウパスの間
glEnable(GL_DEPTH_CLAMP)にすると、ニアプレーンより手前のフラグメントは切り取られず、深度がニアプレーンに留められます(「パンケーキング」)。光と箱の間の物も深度を書くので、ニアプレーンを球の所に置けて、深度の範囲全てを大事な部分に使えます。 textureGatherとtextureProj。textureGather(sampler2DShadow, uv, ref)は2×2のブロックの4つの比較結果をvec4として1回で返すので、自分で重みを付けた大きなPCFのカーネルが4分の1の読み取りで済みます。textureProj(sampler2DShadow, vec4)は4番目の成分で割ってくれるので、透視投影(スポットライト)のシャドウマップに向いています。- より良いカーネル。 規則正しい格子の代わりに、ピクセル毎にランダムに回した8〜16タップのポアソンディスクを使うと、縞が細かいノイズになり、其れをTAAやぼかしが消します(課題6)。
- 距離と共に柔らかくなる影。 PCSS(percentage-closer soft shadows)は、まずシャドウマップの中で遮る物を探し、遮る物と受ける物の距離と光の大きさから半影の幅を見積もってから、其の幅のPCFをします。分散シャドウマップ(VSM)と指数シャドウマップ(ESM)は深度の代わりに深度のモーメントを保存し、普通のテクスチャの様にぼかしたりミップマップにしたり出来ますが、代わりに光の滲み(light bleeding)が出ます。
- キャッシュ。 静的な物は動かないので、エンジンは其れをシャドウマップに1回(又はカスケードの更新毎に1回)だけ描き、動く物だけを毎フレーム上に描き直し、遠いカスケードは数フレーム毎に更新します。
- コンタクトシャドウ。 光の方への画面空間での短いレイマーチ(GLSL 第14章の影のレイと同じですが、深度バッファの中で)が、シャドウマップの1テクセルより小さい細かい影を足します。
- インスタンシングで描く物。 第19章の岩の様にインスタンシングで描く物には、インスタンシング用の影の頂点シェーダー(
uLightSpace * aInstanceModel * uModel)が要ります。此のシーンには其うした物が無いので、此の章にはまだ入れていません。 - VulkanとSlang。 名前が違うだけで同じ技法です。付け先としての深度のイメージ、
compareEnableとcompareOpを持つサンプラー、SlangのSamplerComparisonStateとSampleCmpです。VulkanのNDCの深度は元々0〜1なので、其処では* 0.5 + 0.5の深度の部分が無くなります。xとyの部分は残ります。VulkanのNDCのyは下向きですが、シャドウマップは書く時も読む時も同じNDCからテクセルへの対応を通るので、読み取りでyを反転する必要はありません。
23.15 まとめ
- シャドウマッピングは、光から見た深度を深度テクスチャに描き、其の後で全てのピクセルの光からの深度を保存された深度と比べます。大きければ、より近い何かが覆っています。
FramebufferSpec::depthTextureは深度の付け先を、GL_DEPTH_ATTACHMENTに付けたTexture2D(GL_DEPTH_COMPONENT32F)にします。GL_CLAMP_TO_BORDERと境界1(箱の外 = 光が当たる)、比較モード(GL_COMPARE_REF_TO_TEXTURE、GL_LEQUAL)付きです。- 比較モードのテクスチャは
sampler2DShadowで読みます。texture(s, vec3(uv, ref))が比較の結果0〜1を返します。あたし達のはテクスチャユニット5にあり、シャドウパスの後で繋ぎます。シャドウパスのシェーダーはユニット5を読まず、重ね表示はユニット0にwhiteを繋ぎ直すので、書いている間にシャドウマップを読む物はありません。 - 結合点2のShadowブロック(96バイト)は、
uLightSpace、深度又はメートルの3つのバイアス、フィルター、テクセルの大きさ、オン・オフを持ちます。 lightSpaceMatrixは、原点から光に沿った回転だけのlookAtに、球を囲むorthographicGlを掛けた物です(シーン:r 9.5 m、2048²で1テクセル9.3 mm。視錐台の0.1〜8 mの切片:r 7.83 m、7.6 mm)。光の方へ20 m余分に取ります。- テクセルのスナップは箱の端をテクセルの大きさの倍数に置くので、テクセルの境目がワールドの同じ位置に留まり、影の縁が這い回りません。箱の大きさが一定である必要があるので球を使います。
- シャドウアクネは、傾いた面でテクセル毎に深度が1つしか無い事から来ます。テクセル当たりの誤差はです。既定のバイアスは傾きに比例するバイアス+法線方向のずらしで、テクセルで測ります(0.5 + 1 · tan θ、法線方向のずらし3 · (1 − cos θ))。其の為どのシャドウマップの大きさでも、どの箱でも効きます。
- バイアスが多過ぎるとピーターパン現象になります。
glPolygonOffset(factor, units)はシャドウパスでのハードウェアの傾きのバイアスです。表面カリングは閉じたメッシュではアクネを避けますが、片面の物では失敗します。 - 比較モードのテクスチャの
GL_LINEARは2×2の比較結果を混ぜます。PCFは1テクセルずつ離れた其の様な読み取りを何回か平均します(3×3 → 4 × 4テクセル、5×5 → 6 × 6)。平均するのは結果で、決して深度ではありません。 - アルファテストした物は、シャドウパスでもテクスチャと
discardが要ります(MASKのマテリアルではModel::drawDepthが其れをします)。此処ではBLENDは何も落としません。 - サンプラーオブジェクト(
glCreateSamplers、glSamplerParameteri、glBindSampler)は、ユニット毎にテクスチャのサンプリングの状態より優先されるので、生の深度を見られます。 - llvmpipeでは既定の影でフレームが約1.5倍長くなりました。GPUでのコストはずっと小さいです。点光源(キューブ)の影とカスケードが次の一歩で、TPSにはカメラに合わせた箱かカスケードが要ります。
23.16 課題
- ★ 昼の太陽の向きを(−1, −0.5, −0.2)に変えて下さい。動かす前に床のとを計算します。約0.44と2.04になり、1 cmのバイアスは1テクセルの深度の変化(2048²で約19 mm)より小さい筈です。夕方の長い影、B →「constant 1 cm」での床のアクネ、既定のバイアスでの綺麗な床が見える筈です。
- ★
kShadowSizesの先頭か最後に新しい要素として256を足し(先頭に足すと2048は番号3に移るので、既定を2048の儘にするにはshadowSizeIndexを3にします)、2048から256迄Zを何回押せば良いか考え、其の回数Zを押して、Gで硬いフィルターにして下さい。1テクセルの幅は cmになり、パーゴラの柱の幅の半分より大きいです。柱の影はブロックの鎖になり、葉の模様は消える筈です。 - ★★
lightSpaceMatrixのテクセルのスナップを外し(c.xとc.yを其の儘使う)、Jを押してWかAでゆっくり歩いて下さい。柱と葉の影の縁が這い回ってちらつき、スナップすると止まっている筈です。Jがオフなら箱が動かないので、違いは全く見えない筈です。 - ★★ 懐中電灯に影を付けて下さい。深度テクスチャの2つ目のフレームバッファと、2つ目の光の行列
perspectiveGl(2 · outerAngle, 1, 0.1, 30) * lookAt(pos, pos + dir, up)を使い、影が物の後ろに隠れない様にスポットライトをカメラの0.3 m右下に動かします。夜にFを押すと、樽が壁に、各樽の左上へ影を落とす筈です。 - ★★ 2つのカスケード:0.1〜8 m用と8〜40 m用の2048²のシャドウマップを1枚ずつ、其々視錐台に合わせる方法と同じに合わせてスナップし、
phong.fragでピクセルのカメラからの距離で選んで下さい。近くの影はJオンの時と同じくらい鋭い儘で、遠くの木箱と電柱にも影が戻る筈です。 - ★★ 3×3の格子を、半径1.5テクセルのポアソンディスク上の12タップに置き換え、
gl_FragCoord.xyのハッシュ(GLSL 第8章)から作ったランダムな角度でピクセル毎に回して下さい。半影はPCF 3×3より柔らかく見え、格子の規則正しい段の代わりに細かいノイズになる筈です。読み取りは9回ではなく12回です。 - ★★★ 夜のジオラマの提灯に点光源の影を付けて下さい。23.12節の通りテクスチャユニット6に深度のキューブマップを置き、90°の透視投影のカメラで6回描き、
gl_FragDepthに線型の距離を書きます。提灯が木箱と草の影を全ての向きへ外向きに落とす筈です。
ファイル: a/assets/LICENSE.txt | b/assets/LICENSE.txt
| 前 | 新 | ||
|---|---|---|---|
| @@ -17,3 +17,4 @@ models/diorama.glb 小さな場面 / a small diorama scene (chapter 21 | |||
| 17 | textures/bricks.png レンガ / bricks (chapter 22) | 17 | textures/bricks.png レンガ / bricks (chapter 22) |
| 18 | textures/bricks_normal.png レンガの法線マップ+高さ / brick normal map + height (chapter 22) | 18 | textures/bricks_normal.png レンガの法線マップ+高さ / brick normal map + height (chapter 22) |
| 19 | models/barrel.glb 樽(PBRのテクスチャ付き) / a barrel with PBR textures (chapter 22) | 19 | models/barrel.glb 樽(PBRのテクスチャ付き) / a barrel with PBR textures (chapter 22) |
| 20 | textures/leaves.png 葉(アルファ付き) / leaves with alpha (chapter 23) | ||
ファイル: /dev/null | b/assets/textures/leaves.png
新しいファイル:100644 / バイナリファイル
ファイル: a/shaders/phong.frag | b/shaders/phong.frag
| 前 | 新 | ||
|---|---|---|---|
| @@ -28,6 +28,9 @@ layout(binding = 2) uniform sampler2D uEmissionMap; | |||
| 28 | // 法線マップ(第22章):RGB = 接線空間の法線、A = 高さ(視差マッピング用)。ユニット4 | 28 | // 法線マップ(第22章):RGB = 接線空間の法線、A = 高さ(視差マッピング用)。ユニット4 |
| 29 | // Normal map (chapter 22): RGB = tangent-space normal, A = height (for parallax mapping). Unit 4 | 29 | // Normal map (chapter 22): RGB = tangent-space normal, A = height (for parallax mapping). Unit 4 |
| 30 | layout(binding = 4) uniform sampler2D uNormalMap; | 30 | layout(binding = 4) uniform sampler2D uNormalMap; |
| 31 | // 影の地図(第23章):深度テクスチャ、比較モード。texture(s, vec3(uv, 深さ))は0〜1(影〜光) | ||
| 32 | // The shadow map (chapter 23): a depth texture in comparison mode. texture(s, vec3(uv, depth)) gives 0..1 (shadow..lit) | ||
| 33 | layout(binding = 5) uniform sampler2DShadow uShadowMap; | ||
| 31 | uniform bool uNormalMapping = true; // 法線マップを使う(デバッグ用に切れる) / use normal maps (can be turned off for debugging) | 34 | uniform bool uNormalMapping = true; // 法線マップを使う(デバッグ用に切れる) / use normal maps (can be turned off for debugging) |
| 32 | uniform bool uParallaxMapping = true; // 視差マッピングを使う / use parallax mapping | 35 | uniform bool uParallaxMapping = true; // 視差マッピングを使う / use parallax mapping |
| 33 | // 環境(空)のキューブマップ。ユニット3(第18章) / the environment (sky) cube map, unit 3 (chapter 18) | 36 | // 環境(空)のキューブマップ。ユニット3(第18章) / the environment (sky) cube map, unit 3 (chapter 18) |
| @@ -84,10 +87,23 @@ layout(std140, binding = 0) uniform Camera { | |||
| 84 | float uTime; // アニメーションの時間(秒) / animation time (seconds) | 87 | float uTime; // アニメーションの時間(秒) / animation time (seconds) |
| 85 | }; | 88 | }; |
| 86 | 89 | ||
| 90 | // 影(ユニフォームバッファ、結合点2、std140)。使う全部のシェーダーで同じ宣言(C++ではShadowBlock) | ||
| 91 | // Shadows (uniform buffer, binding 2, std140). The same declaration in every shader that uses it (ShadowBlock in C++) | ||
| 92 | layout(std140, binding = 2) uniform Shadow { | ||
| 93 | mat4 uLightSpace; // ワールド → 光のクリップ座標 / world → the light's clip space | ||
| 94 | float uShadowBias; // 一定のバイアス(0〜1の深度) / constant bias (0..1 depth) | ||
| 95 | float uShadowSlopeBias; // 傾きに比例するバイアス / slope-scaled bias | ||
| 96 | float uShadowNormalOffset; // 法線方向のずらし(m) / normal offset (m) | ||
| 97 | int uShadowFilter; // 0 = 硬い / hard, 1 = 2×2, 2 = PCF 3×3, 3 = PCF 5×5 | ||
| 98 | vec2 uShadowTexel; // 1テクセルのUV / one texel in UV | ||
| 99 | int uShadowsEnabled; | ||
| 100 | int uShadowPad; | ||
| 101 | }; | ||
| 102 | |||
| 87 | // 0 = 全部、1 = 環境光、2 = 拡散反射、3 = 鏡面反射、4 = 発光、5 = 法線(法線マップ後)、 | 103 | // 0 = 全部、1 = 環境光、2 = 拡散反射、3 = 鏡面反射、4 = 発光、5 = 法線(法線マップ後)、 |
| 88 | // 6 = 頂点の法線(法線マップ前)、7 = 接線、8 = 従法線(第22章) | 104 | // 6 = 頂点の法線(法線マップ前)、7 = 接線、8 = 従法線(第22章)、9 = 影(第23章) |
| 89 | // 0 = everything, 1 = ambient, 2 = diffuse, 3 = specular, 4 = emission, 5 = normals (after normal mapping), | 105 | // 0 = everything, 1 = ambient, 2 = diffuse, 3 = specular, 4 = emission, 5 = normals (after normal mapping), |
| 90 | // 6 = vertex normals (before normal mapping), 7 = tangents, 8 = bitangents (chapter 22) | 106 | // 6 = vertex normals (before normal mapping), 7 = tangents, 8 = bitangents (chapter 22), 9 = shadow (chapter 23) |
| 91 | uniform int uViewMode; | 107 | uniform int uViewMode; |
| 92 | 108 | ||
| 93 | // アルファトゥカバレッジ(第20章):マスクのマテリアルを捨てる代わりに、アルファをMSAAのサンプルの割合にする。 | 109 | // アルファトゥカバレッジ(第20章):マスクのマテリアルを捨てる代わりに、アルファをMSAAのサンプルの割合にする。 |
| @@ -149,6 +165,34 @@ float attenuate(float d, vec3 k) { | |||
| 149 | return 1.0 / (k.x + k.y * d + k.z * d * d); | 165 | return 1.0 / (k.x + k.y * d + k.z * d * d); |
| 150 | } | 166 | } |
| 151 | 167 | ||
| 168 | // 平行光源の影(第23章):このピクセルを光のクリップ座標に移し、影の地図の深度と比べる。1 = 光が当たる、0 = 影。 | ||
| 169 | // n = 頂点の法線(法線マップ前)、l = 光へ向かう向き | ||
| 170 | // Directional-light shadow (chapter 23): move this pixel into the light's clip space and compare with the shadow map's | ||
| 171 | // depth. 1 = lit, 0 = in shadow. n = the vertex normal (before normal mapping), l = towards the light | ||
| 172 | float shadowFactor(vec3 worldPos, vec3 n, vec3 l) { | ||
| 173 | if (uShadowsEnabled == 0) return 1.0; | ||
| 174 | float cosTheta = clamp(dot(n, l), 0.0, 1.0); | ||
| 175 | // 法線方向に少しずらす(斜めの面ほど多く):影の地図の1テクセルの中で面が自分を影にする「シャドウアクネ」を防ぐ | ||
| 176 | // Push the point a little along the normal (more on tilted surfaces): prevents "shadow acne", where a surface shadows | ||
| 177 | // itself inside one shadow-map texel | ||
| 178 | vec3 p = worldPos + n * (uShadowNormalOffset * (1.0 - cosTheta)); | ||
| 179 | vec4 clip = uLightSpace * vec4(p, 1.0); | ||
| 180 | vec3 c = clip.xyz / clip.w * 0.5 + 0.5; // NDC → 0..1(UVと深度) / NDC → 0..1 (UV and depth) | ||
| 181 | if (c.z > 1.0) return 1.0; // 光の箱より奥:影なし / beyond the light's box: not shadowed | ||
| 182 | // 傾きに比例するバイアス:光に対して斜めな面ほど1テクセルの中の深度の差が大きい(tanθに比例) | ||
| 183 | // Slope-scaled bias: the more a surface tilts away from the light, the larger the depth change within one texel (∝ tan θ) | ||
| 184 | float tanTheta = sqrt(max(1.0 - cosTheta * cosTheta, 0.0)) / max(cosTheta, 0.05); | ||
| 185 | c.z -= uShadowBias + uShadowSlopeBias * min(tanTheta, 10.0); | ||
| 186 | if (uShadowFilter <= 1) return texture(uShadowMap, c); // 1回:GL_NEARESTなら硬い、GL_LINEARなら2×2 / one lookup | ||
| 187 | // PCF(percentage-closer filtering):周りの何点かで比べた結果を平均する(深度を平均するのではない) | ||
| 188 | // PCF (percentage-closer filtering): average the RESULTS of comparisons around the point (not the depths) | ||
| 189 | int r = uShadowFilter == 2 ? 1 : 2; | ||
| 190 | float sum = 0.0; | ||
| 191 | for (int y = -r; y <= r; ++y) | ||
| 192 | for (int x = -r; x <= r; ++x) sum += texture(uShadowMap, vec3(c.xy + vec2(x, y) * uShadowTexel, c.z)); | ||
| 193 | return sum / float((2 * r + 1) * (2 * r + 1)); | ||
| 194 | } | ||
| 195 | |||
| 152 | // 視差オクルージョンマッピング(第22章):目から表面の奥へ、高さマップの層を一枚ずつ進み、最初に高さマップの | 196 | // 視差オクルージョンマッピング(第22章):目から表面の奥へ、高さマップの層を一枚ずつ進み、最初に高さマップの |
| 153 | // 下に入った所のUVを返す(前の層との間は直線で補間)。v = 接線空間の目への向き。 | 197 | // 下に入った所のUVを返す(前の層との間は直線で補間)。v = 接線空間の目への向き。 |
| 154 | // ループの中は分岐なので、ミップマップの段は外で求めた微分で指定する(textureGrad) | 198 | // ループの中は分岐なので、ミップマップの段は外で求めた微分で指定する(textureGrad) |
| @@ -235,8 +279,10 @@ void main() { | |||
| 235 | vec3 diffuse = vec3(0.0); | 279 | vec3 diffuse = vec3(0.0); |
| 236 | vec3 specular = vec3(0.0); | 280 | vec3 specular = vec3(0.0); |
| 237 | 281 | ||
| 238 | // 平行光源:光へ向かう向きは進む向きの逆 / directional: towards the light = the opposite of its direction | 282 | // 平行光源:光へ向かう向きは進む向きの逆。影を掛ける(第23章) / directional: towards the light = the opposite of its |
| 239 | addLight(s, -uDirLight.direction, uDirLight.color, diffuse, specular); | 283 | // direction. Shadowed (chapter 23) |
| 284 | float shadow = shadowFactor(vWorldPos, geometricNormal, -uDirLight.direction); | ||
| 285 | addLight(s, -uDirLight.direction, uDirLight.color * shadow, diffuse, specular); | ||
| 240 | 286 | ||
| 241 | // 点光源 / point lights | 287 | // 点光源 / point lights |
| 242 | for (int i = 0; i < uPointLightCount; ++i) { | 288 | for (int i = 0; i < uPointLightCount; ++i) { |
| @@ -275,6 +321,7 @@ void main() { | |||
| 275 | else if (uViewMode == 6) color = geometricNormal * 0.5 + 0.5; | 321 | else if (uViewMode == 6) color = geometricNormal * 0.5 + 0.5; |
| 276 | else if (uViewMode == 7) color = hasTangent ? tangent * 0.5 + 0.5 : vec3(0.0); | 322 | else if (uViewMode == 7) color = hasTangent ? tangent * 0.5 + 0.5 : vec3(0.0); |
| 277 | else if (uViewMode == 8) color = hasTangent ? bitangent * 0.5 + 0.5 : vec3(0.0); | 323 | else if (uViewMode == 8) color = hasTangent ? bitangent * 0.5 + 0.5 : vec3(0.0); |
| 324 | else if (uViewMode == 9) color = vec3(shadow); | ||
| 278 | // ベクトルの表示は、post.fragがsRGBにした後でちょうどこの値になるように、先にリニアへ戻しておく | 325 | // ベクトルの表示は、post.fragがsRGBにした後でちょうどこの値になるように、先にリニアへ戻しておく |
| 279 | // Vector views: convert to linear first, so that after post.frag's sRGB encoding the screen shows exactly this value | 326 | // Vector views: convert to linear first, so that after post.frag's sRGB encoding the screen shows exactly this value |
| 280 | if (uViewMode >= 5) | 327 | if (uViewMode >= 5) |
ファイル: /dev/null | b/shaders/shadow.frag
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,15 @@ | |||
| 1 | #version 460 core | ||
| 2 | // 影の地図のフラグメントシェーダー:色は書かない(深度はGPUが書く)。葉や草は切り抜く | ||
| 3 | // Shadow-map fragment shader: no colour is written (the GPU writes the depth). Leaves and grass are cut out | ||
| 4 | in vec2 vUv; | ||
| 5 | |||
| 6 | layout(binding = 0) uniform sampler2D uBaseMap; // Maskのときのベースカラー(アルファ) / base colour for Mask (alpha) | ||
| 7 | uniform bool uAlphaMask; // 切り抜くか / cut out? | ||
| 8 | uniform float uAlphaCutoff; | ||
| 9 | uniform float uBaseAlpha; // マテリアルのアルファ係数 / the material's alpha factor | ||
| 10 | |||
| 11 | void main() { | ||
| 12 | // 透明な部分が影を落とさないように捨てる:葉の形の影になる / discard the transparent parts so they cast no shadow: | ||
| 13 | // the shadow gets the leaves' shape | ||
| 14 | if (uAlphaMask && uBaseAlpha * texture(uBaseMap, vUv).a < uAlphaCutoff) discard; | ||
| 15 | } | ||
ファイル: /dev/null | b/shaders/shadow.vert
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,26 @@ | |||
| 1 | #version 460 core | ||
| 2 | // 影の地図(第23章):光から見た深度だけを描く / shadow map (chapter 23): draws only the depth seen from the light | ||
| 3 | layout(location = 0) in vec3 aPosition; | ||
| 4 | layout(location = 2) in vec2 aUv; // 切り抜き(Mask)用 / for cut-outs (Mask) | ||
| 5 | |||
| 6 | // 影(ユニフォームバッファ、結合点2、std140)。使う全部のシェーダーで同じ宣言(C++ではShadowBlock) | ||
| 7 | // Shadows (uniform buffer, binding 2, std140). The same declaration in every shader that uses it (ShadowBlock in C++) | ||
| 8 | layout(std140, binding = 2) uniform Shadow { | ||
| 9 | mat4 uLightSpace; // ワールド → 光のクリップ座標 / world → the light's clip space | ||
| 10 | float uShadowBias; // 一定のバイアス(0〜1の深度) / constant bias (0..1 depth) | ||
| 11 | float uShadowSlopeBias; // 傾きに比例するバイアス / slope-scaled bias | ||
| 12 | float uShadowNormalOffset; // 法線方向のずらし(m) / normal offset (m) | ||
| 13 | int uShadowFilter; // 0 = 硬い / hard, 1 = 2×2, 2 = PCF 3×3, 3 = PCF 5×5 | ||
| 14 | vec2 uShadowTexel; // 1テクセルのUV / one texel in UV | ||
| 15 | int uShadowsEnabled; | ||
| 16 | int uShadowPad; | ||
| 17 | }; | ||
| 18 | |||
| 19 | uniform mat4 uModel; | ||
| 20 | |||
| 21 | out vec2 vUv; | ||
| 22 | |||
| 23 | void main() { | ||
| 24 | vUv = aUv; | ||
| 25 | gl_Position = uLightSpace * uModel * vec4(aPosition, 1.0); | ||
| 26 | } | ||
ファイル: /dev/null | b/shaders/shadow_debug.frag
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,15 @@ | |||
| 1 | #version 460 core | ||
| 2 | // 影の地図を見せる(第23章):深度テクスチャを灰色で。比較なしのサンプラーオブジェクトで読む | ||
| 3 | // Shows the shadow map (chapter 23): the depth texture as grey. Read through a sampler object without comparison | ||
| 4 | in vec2 vUv; | ||
| 5 | |||
| 6 | layout(binding = 0) uniform sampler2D uDepth; | ||
| 7 | |||
| 8 | layout(location = 0) out vec4 out_color; | ||
| 9 | |||
| 10 | void main() { | ||
| 11 | // 正射影なので深度は距離に比例(線型):そのまま見せられる。近い = 暗い | ||
| 12 | // Orthographic, so depth is proportional to distance (linear): it can be shown as it is. Near = dark | ||
| 13 | float d = texture(uDepth, vUv).r; | ||
| 14 | out_color = vec4(vec3(pow(d, 4.0)), 1.0); // 奥の範囲を広げる / spreads the far range | ||
| 15 | } | ||
ファイル: a/src/framebuffer.cc | b/src/framebuffer.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -50,7 +50,18 @@ void Framebuffer::createAttachments() { | |||
| 50 | glNamedFramebufferDrawBuffer(fbo, GL_NONE); | 50 | glNamedFramebufferDrawBuffer(fbo, GL_NONE); |
| 51 | glNamedFramebufferReadBuffer(fbo, GL_NONE); | 51 | glNamedFramebufferReadBuffer(fbo, GL_NONE); |
| 52 | } | 52 | } |
| 53 | if (spec.depthStencilFormat != 0) { | 53 | bool stencil = spec.depthStencilFormat == GL_DEPTH24_STENCIL8 || spec.depthStencilFormat == GL_DEPTH32F_STENCIL8; |
| 54 | if (spec.depthStencilFormat != 0 && spec.depthTexture) { | ||
| 55 | if (spec.samples > 0) fprintf(stderr, "マルチサンプルの深度テクスチャは未対応 / multisampled depth textures are not supported\n"); | ||
| 56 | // 深度テクスチャ(影の地図):外側(光の箱の外)は1 = 一番奥なので影にならない | ||
| 57 | // A depth texture (shadow map): outside (beyond the light's box) reads 1 = farthest, so it is never in shadow | ||
| 58 | depthTex = Texture2D(w, h, spec.depthStencilFormat, 1); | ||
| 59 | depthTex.setWrap(GL_CLAMP_TO_BORDER, GL_CLAMP_TO_BORDER); | ||
| 60 | depthTex.setBorderColor(1.0f, 1.0f, 1.0f, 1.0f); | ||
| 61 | depthTex.setFilter(GL_LINEAR, GL_LINEAR); | ||
| 62 | depthTex.setCompare(true); | ||
| 63 | glNamedFramebufferTexture(fbo, stencil ? GL_DEPTH_STENCIL_ATTACHMENT : GL_DEPTH_ATTACHMENT, depthTex.id(), 0); | ||
| 64 | } else if (spec.depthStencilFormat != 0) { | ||
| 54 | glCreateRenderbuffers(1, &depthStencil); | 65 | glCreateRenderbuffers(1, &depthStencil); |
| 55 | // 色と深度のサンプル数は同じでなければならない(違うとフレームバッファが不完全)。要求ではなく、色が実際に | 66 | // 色と深度のサンプル数は同じでなければならない(違うとフレームバッファが不完全)。要求ではなく、色が実際に |
| 56 | // 貰った数を使う(色が無ければ要求の数) / colour and depth must have the same number of samples (otherwise the | 67 | // 貰った数を使う(色が無ければ要求の数) / colour and depth must have the same number of samples (otherwise the |
| @@ -63,7 +74,6 @@ void Framebuffer::createAttachments() { | |||
| 63 | if (depthSamples > 0 && actualSamples == 0) | 74 | if (depthSamples > 0 && actualSamples == 0) |
| 64 | glGetNamedRenderbufferParameteriv(depthStencil, GL_RENDERBUFFER_SAMPLES, &actualSamples); | 75 | glGetNamedRenderbufferParameteriv(depthStencil, GL_RENDERBUFFER_SAMPLES, &actualSamples); |
| 65 | // GL_DEPTH24_STENCIL8なら深度とステンシルの両方に付ける / GL_DEPTH24_STENCIL8 attaches as both depth and stencil | 76 | // GL_DEPTH24_STENCIL8なら深度とステンシルの両方に付ける / GL_DEPTH24_STENCIL8 attaches as both depth and stencil |
| 66 | bool stencil = spec.depthStencilFormat == GL_DEPTH24_STENCIL8 || spec.depthStencilFormat == GL_DEPTH32F_STENCIL8; | ||
| 67 | glNamedFramebufferRenderbuffer(fbo, stencil ? GL_DEPTH_STENCIL_ATTACHMENT : GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, | 77 | glNamedFramebufferRenderbuffer(fbo, stencil ? GL_DEPTH_STENCIL_ATTACHMENT : GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, |
| 68 | depthStencil); | 78 | depthStencil); |
| 69 | } | 79 | } |
| @@ -71,6 +81,7 @@ void Framebuffer::createAttachments() { | |||
| 71 | 81 | ||
| 72 | void Framebuffer::destroyAttachments() { | 82 | void Framebuffer::destroyAttachments() { |
| 73 | for (Texture2D &t : colorTextures) t = Texture2D(); // 古いテクスチャを消す / deletes the old textures | 83 | for (Texture2D &t : colorTextures) t = Texture2D(); // 古いテクスチャを消す / deletes the old textures |
| 84 | depthTex = Texture2D(); | ||
| 74 | for (GLuint &rb : colorSamples) { | 85 | for (GLuint &rb : colorSamples) { |
| 75 | if (rb) glDeleteRenderbuffers(1, &rb); | 86 | if (rb) glDeleteRenderbuffers(1, &rb); |
| 76 | rb = 0; | 87 | rb = 0; |
| @@ -137,7 +148,8 @@ Framebuffer::~Framebuffer() { | |||
| 137 | 148 | ||
| 138 | Framebuffer::Framebuffer(Framebuffer &&other) noexcept | 149 | Framebuffer::Framebuffer(Framebuffer &&other) noexcept |
| 139 | : fbo(std::exchange(other.fbo, 0)), depthStencil(std::exchange(other.depthStencil, 0)), | 150 | : fbo(std::exchange(other.fbo, 0)), depthStencil(std::exchange(other.depthStencil, 0)), |
| 140 | colorSamples(std::exchange(other.colorSamples, {})), colorTextures(std::move(other.colorTextures)), w(other.w), | 151 | colorSamples(std::exchange(other.colorSamples, {})), colorTextures(std::move(other.colorTextures)), |
| 152 | depthTex(std::move(other.depthTex)), w(other.w), | ||
| 141 | h(other.h), actualSamples(other.actualSamples), spec(other.spec) {} | 153 | h(other.h), actualSamples(other.actualSamples), spec(other.spec) {} |
| 142 | 154 | ||
| 143 | Framebuffer &Framebuffer::operator=(Framebuffer &&other) noexcept { | 155 | Framebuffer &Framebuffer::operator=(Framebuffer &&other) noexcept { |
| @@ -148,6 +160,7 @@ Framebuffer &Framebuffer::operator=(Framebuffer &&other) noexcept { | |||
| 148 | depthStencil = std::exchange(other.depthStencil, 0); | 160 | depthStencil = std::exchange(other.depthStencil, 0); |
| 149 | colorSamples = std::exchange(other.colorSamples, {}); | 161 | colorSamples = std::exchange(other.colorSamples, {}); |
| 150 | colorTextures = std::move(other.colorTextures); | 162 | colorTextures = std::move(other.colorTextures); |
| 163 | depthTex = std::move(other.depthTex); | ||
| 151 | w = other.w; | 164 | w = other.w; |
| 152 | h = other.h; | 165 | h = other.h; |
| 153 | actualSamples = other.actualSamples; | 166 | actualSamples = other.actualSamples; |
ファイル: a/src/framebuffer.hh | b/src/framebuffer.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -29,6 +29,11 @@ struct FramebufferSpec { | |||
| 29 | // 1 or more makes both colour and depth multisampled renderbuffers, which cannot be sampled: resolve them into | 29 | // 1 or more makes both colour and depth multisampled renderbuffers, which cannot be sampled: resolve them into |
| 30 | // an ordinary framebuffer with blitTo first. The driver may pick more samples than requested (check samples()). | 30 | // an ordinary framebuffer with blitTo first. The driver may pick more samples than requested (check samples()). |
| 31 | int samples = 0; | 31 | int samples = 0; |
| 32 | // 深度をレンダーバッファではなくテクスチャにする(影の地図、第23章)。depthStencilFormatは | ||
| 33 | // GL_DEPTH_COMPONENT24 / 32Fなど。比較モードon、GL_LINEAR、外側はGL_CLAMP_TO_BORDERで1。depth()で読む | ||
| 34 | // Make the depth a texture instead of a renderbuffer (shadow maps, chapter 23). depthStencilFormat is | ||
| 35 | // GL_DEPTH_COMPONENT24 / 32F etc. Comparison mode on, GL_LINEAR, GL_CLAMP_TO_BORDER with 1 outside. Read it with depth() | ||
| 36 | bool depthTexture = false; | ||
| 32 | }; | 37 | }; |
| 33 | 38 | ||
| 34 | // フレームバッファオブジェクト(FBO):色のテクスチャ+深度・ステンシルのレンダーバッファ(RAII、コピー不可・移動可)。DSAで作る。 | 39 | // フレームバッファオブジェクト(FBO):色のテクスチャ+深度・ステンシルのレンダーバッファ(RAII、コピー不可・移動可)。DSAで作る。 |
| @@ -62,6 +67,9 @@ public: | |||
| 62 | const Texture2D &color(int index = 0) const { return colorTextures[static_cast<size_t>(index)]; } | 67 | const Texture2D &color(int index = 0) const { return colorTextures[static_cast<size_t>(index)]; } |
| 63 | Texture2D &color(int index = 0) { return colorTextures[static_cast<size_t>(index)]; } | 68 | Texture2D &color(int index = 0) { return colorTextures[static_cast<size_t>(index)]; } |
| 64 | int colorCount() const { return spec.colorFormat != 0 ? spec.colorCount : 0; } | 69 | int colorCount() const { return spec.colorFormat != 0 ? spec.colorCount : 0; } |
| 70 | // 深度のテクスチャ(spec.depthTextureのときだけ、ほかは空) / the depth texture (only with spec.depthTexture, else empty) | ||
| 71 | const Texture2D &depth() const { return depthTex; } | ||
| 72 | Texture2D &depth() { return depthTex; } | ||
| 65 | 73 | ||
| 66 | // 別のフレームバッファへコピーする(glBlitNamedFramebuffer)。マルチサンプルから普通のフレームバッファへなら | 74 | // 別のフレームバッファへコピーする(glBlitNamedFramebuffer)。マルチサンプルから普通のフレームバッファへなら |
| 67 | // サンプルの平均を取る:これがMSAAの「解決(resolve)」。大きさが違えば拡大・縮小する(filter = GL_LINEARなど。 | 75 | // サンプルの平均を取る:これがMSAAの「解決(resolve)」。大きさが違えば拡大・縮小する(filter = GL_LINEARなど。 |
| @@ -92,6 +100,7 @@ private: | |||
| 92 | // マルチサンプルの色のレンダーバッファ(第20章) / multisampled colour renderbuffers (chapter 20) | 100 | // マルチサンプルの色のレンダーバッファ(第20章) / multisampled colour renderbuffers (chapter 20) |
| 93 | std::array<GLuint, kMaxColorAttachments> colorSamples = {}; | 101 | std::array<GLuint, kMaxColorAttachments> colorSamples = {}; |
| 94 | std::array<Texture2D, kMaxColorAttachments> colorTextures; | 102 | std::array<Texture2D, kMaxColorAttachments> colorTextures; |
| 103 | Texture2D depthTex; // 第23章 / chapter 23 | ||
| 95 | int w = 0, h = 0; | 104 | int w = 0, h = 0; |
| 96 | int actualSamples = 0; | 105 | int actualSamples = 0; |
| 97 | FramebufferSpec spec; | 106 | FramebufferSpec spec; |
ファイル: a/src/main.cc | b/src/main.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -1,5 +1,5 @@ | |||
| 1 | // 第22章:法線マッピング | 1 | // 第23章:シャドウマッピング |
| 2 | // Chapter 22: normal mapping | 2 | // Chapter 23: shadow mapping |
| 3 | // | 3 | // |
| 4 | // 操作 / Controls: | 4 | // 操作 / Controls: |
| 5 | // WASD 前後左右に移動 / move forward, back, left, right | 5 | // WASD 前後左右に移動 / move forward, back, left, right |
| @@ -7,18 +7,25 @@ | |||
| 7 | // Shift 速く動く / move faster | 7 | // Shift 速く動く / move faster |
| 8 | // マウス / mouse 向きを変える(FPS)、左ドラッグで回る(オービット) / look around (FPS), drag with the left button to orbit | 8 | // マウス / mouse 向きを変える(FPS)、左ドラッグで回る(オービット) / look around (FPS), drag with the left button to orbit |
| 9 | // ホイール / wheel ズーム / zoom | 9 | // ホイール / wheel ズーム / zoom |
| 10 | // M 法線マップのオン・オフ / normal maps on / off | 10 | // H 影のオン・オフ / shadows on / off |
| 11 | // X 視差(オクルージョン)マッピングのオン・オフ / parallax (occlusion) mapping on / off | 11 | // B バイアス:なし → 一定 → 傾き+法線ずらし → glPolygonOffset → 大きすぎ(ピーターパン) |
| 12 | // L 壁の前を回る点光源のオン・オフ / the point light circling in front of the wall on / off | 12 | // bias: none → constant → slope-scaled + normal offset → glPolygonOffset → too large (peter-panning) |
| 13 | // V 表示:全部 → 環境光 → 拡散 → 鏡面 → 発光 → 法線 → 頂点の法線 → 接線 → 従法線 | 13 | // K 影の地図を描くときのカリング:裏面 → 表面 → なし / culling in the shadow pass: back → front → none |
| 14 | // view: all → ambient → diffuse → specular → emission → normals → vertex normals → tangents → bitangents | 14 | // G 影のフィルター:硬い → 2×2(ハードウェア) → PCF 3×3 → PCF 5×5 |
| 15 | // shadow filter: hard → 2 × 2 (hardware) → PCF 3 × 3 → PCF 5 × 5 | ||
| 16 | // J 光の箱:場面全体 ⇔ カメラの視錐台(手前8 m) / light box: whole scene ⇔ camera frustum (first 8 m) | ||
| 17 | // Z 影の地図の大きさ:512 → 1024 → 2048 → 4096 / shadow map size | ||
| 18 | // O 影の地図を左下に表示 / show the shadow map at the bottom left | ||
| 19 | // V 表示:全部 → 環境光 → 拡散 → 鏡面 → 発光 → 法線 → 頂点の法線 → 接線 → 従法線 → 影 | ||
| 20 | // view: all → ambient → diffuse → specular → emission → normals → vertex normals → tangents → | ||
| 21 | // bitangents → shadow | ||
| 15 | // = / - 露出を上げる・下げる / exposure up / down | 22 | // = / - 露出を上げる・下げる / exposure up / down |
| 16 | // 1〜6 効果:なし / 反転 / グレースケール / シャープ / ぼかし / エッジ検出 | 23 | // 1〜6 効果:なし / 反転 / グレースケール / シャープ / ぼかし / エッジ検出 |
| 17 | // effect: none / invert / grayscale / sharpen / blur / edge detection | 24 | // effect: none / invert / grayscale / sharpen / blur / edge detection |
| 18 | // C FPS ⇔ オービットカメラ / FPS ⇔ orbit camera | 25 | // C FPS ⇔ オービットカメラ / FPS ⇔ orbit camera |
| 19 | // N 昼 ⇔ 夜 / day ⇔ night | 26 | // N 昼 ⇔ 夜 / day ⇔ night |
| 20 | // F 懐中電灯のオン・オフ / flashlight on / off | 27 | // F 懐中電灯のオン・オフ / flashlight on / off |
| 21 | // P 風車と点光源を止める・動かす / pause / resume the windmill and the point light | 28 | // P 風車を止める・動かす / pause / resume the windmill |
| 22 | // Tab カーソルのキャプチャ切り替え / toggle cursor capture | 29 | // Tab カーソルのキャプチャ切り替え / toggle cursor capture |
| 23 | // R シェーダーを読み直す / reload the shaders | 30 | // R シェーダーを読み直す / reload the shaders |
| 24 | // Esc 終了 / quit | 31 | // Esc 終了 / quit |
| @@ -36,6 +43,7 @@ | |||
| 36 | #include "uniforms.hh" | 43 | #include "uniforms.hh" |
| 37 | #include "window.hh" | 44 | #include "window.hh" |
| 38 | 45 | ||
| 46 | #include <algorithm> | ||
| 39 | #include <cmath> | 47 | #include <cmath> |
| 40 | #include <cstdint> | 48 | #include <cstdint> |
| 41 | #include <cstdio> | 49 | #include <cstdio> |
| @@ -56,9 +64,49 @@ static const Placement kCrates[] = { | |||
| 56 | constexpr int kMsaaSamples = 4; // 第20章 / chapter 20 | 64 | constexpr int kMsaaSamples = 4; // 第20章 / chapter 20 |
| 57 | constexpr int kBloomPasses = 4; // 横+縦の組の数 / number of horizontal + vertical pairs | 65 | constexpr int kBloomPasses = 4; // 横+縦の組の数 / number of horizontal + vertical pairs |
| 58 | 66 | ||
| 59 | static const char *const kViewModeNames[] = {"all", "ambient", "diffuse", "specular", "emission", | 67 | static const char *const kViewModeNames[] = {"all", "ambient", "diffuse", "specular", "emission", |
| 60 | "normals", "vertex normals", "tangents", "bitangents"}; | 68 | "normals", "vertex normals", "tangents", "bitangents", "shadow"}; |
| 61 | constexpr int kViewModes = 9; | 69 | constexpr int kViewModes = 10; |
| 70 | |||
| 71 | // 影のバイアスの方法 / the shadow bias methods | ||
| 72 | struct BiasMode { | ||
| 73 | const char *name; | ||
| 74 | float constant; // m(inTexelsならテクセルの大きさの倍数) / m (multiples of the texel size if inTexels) | ||
| 75 | float slope; // tanθ当たり / per unit of tan θ | ||
| 76 | float normalOffset; // 法線方向のずらし / push along the normal | ||
| 77 | bool polygonOffset; // 影の地図を描くときにglPolygonOffset / glPolygonOffset while drawing the shadow map | ||
| 78 | bool inTexels; // 値を影の地図の1テクセルのワールドでの大きさで測る:地図の大きさを変えても効き目が同じ | ||
| 79 | // values measured in the world size of one shadow-map texel: works the same at any map size | ||
| 80 | }; | ||
| 81 | static const BiasMode kBiasModes[] = { | ||
| 82 | {"none (shadow acne)", 0.0f, 0.0f, 0.0f, false, false}, | ||
| 83 | {"constant 1 cm", 0.01f, 0.0f, 0.0f, false, false}, | ||
| 84 | {"slope-scaled + normal offset (in texels)", 0.5f, 1.0f, 3.0f, false, true}, | ||
| 85 | {"glPolygonOffset(2, 4) only", 0.0f, 0.0f, 0.0f, true, false}, | ||
| 86 | {"too large: 40 cm (peter-panning)", 0.4f, 0.0f, 0.0f, false, false}, | ||
| 87 | }; | ||
| 88 | constexpr size_t kDefaultBias = 2; | ||
| 89 | static const char *const kCullNames[] = {"back faces", "front faces", "none"}; | ||
| 90 | static const char *const kFilterNames[] = {"hard (GL_NEAREST)", "hardware 2x2 (GL_LINEAR)", "PCF 3x3", "PCF 5x5"}; | ||
| 91 | constexpr int kShadowSizes[] = {512, 1024, 2048, 4096}; | ||
| 92 | |||
| 93 | // 平行光源の光から見た行列:centreを中心とする半径radiusの球を正射影の箱に収める。箱は影の地図の1テクセル単位で | ||
| 94 | // 動かす(カメラが動いても影の縁がちらつかない)。depthRangeに箱の奥行き(m)を返す | ||
| 95 | // The directional light's matrix: an orthographic box enclosing the sphere (centre, radius). The box moves in whole | ||
| 96 | // shadow-map texels (shadow edges do not shimmer when the camera moves). Returns the box depth (m) in depthRange | ||
| 97 | static Mat4 lightSpaceMatrix(Vec3 lightDir, Vec3 centre, float radius, int mapSize, float &depthRange) { | ||
| 98 | Vec3 d = normalize(lightDir); | ||
| 99 | Vec3 up = std::fabs(d.y) > 0.99f ? Vec3{0.0f, 0.0f, 1.0f} : Vec3{0.0f, 1.0f, 0.0f}; | ||
| 100 | Mat4 view = lookAt({0.0f, 0.0f, 0.0f}, d, up); // 回転だけ:光の向きを-Zに / rotation only: the light along -Z | ||
| 101 | Vec4 c = view * Vec4{centre.x, centre.y, centre.z, 1.0f}; | ||
| 102 | float texel = 2.0f * radius / static_cast<float>(mapSize); | ||
| 103 | float cx = std::floor(c.x / texel) * texel, cy = std::floor(c.y / texel) * texel; | ||
| 104 | // 奥行き:球の手前に20 m余分に(箱の外の、光と球の間にある物も影を落とすように) | ||
| 105 | // Depth: 20 m extra in front of the sphere (so casters between the light and the sphere still cast) | ||
| 106 | float nearPlane = -c.z - radius - 20.0f, farPlane = -c.z + radius; | ||
| 107 | depthRange = farPlane - nearPlane; | ||
| 108 | return orthographicGl(cx - radius, cx + radius, cy - radius, cy + radius, nearPlane, farPlane) * view; | ||
| 109 | } | ||
| 62 | constexpr int kFirstVectorView = 5; // ここからはベクトルを色で見せる / from here on, vectors are shown as colours | 110 | constexpr int kFirstVectorView = 5; // ここからはベクトルを色で見せる / from here on, vectors are shown as colours |
| 63 | static const char *const kEffectNames[] = {"none", "invert", "grayscale", "sharpen", "blur", "edge detection"}; | 111 | static const char *const kEffectNames[] = {"none", "invert", "grayscale", "sharpen", "blur", "edge detection"}; |
| 64 | 112 | ||
| @@ -147,7 +195,7 @@ static std::vector<Lantern> makeLanterns() { | |||
| 147 | 195 | ||
| 148 | int main() { | 196 | int main() { |
| 149 | Window window; | 197 | Window window; |
| 150 | if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 22")) return 1; | 198 | if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 23")) return 1; |
| 151 | 199 | ||
| 152 | // 画面(既定のフレームバッファ)がsRGBか:GL_FRAMEBUFFER_SRGBが効くのはsRGBのときだけ | 200 | // 画面(既定のフレームバッファ)がsRGBか:GL_FRAMEBUFFER_SRGBが効くのはsRGBのときだけ |
| 153 | // Is the screen (the default framebuffer) sRGB? GL_FRAMEBUFFER_SRGB only has an effect if it is | 201 | // Is the screen (the default framebuffer) sRGB? GL_FRAMEBUFFER_SRGB only has an effect if it is |
| @@ -169,13 +217,17 @@ int main() { | |||
| 169 | // stays linear (A = height) | 217 | // stays linear (A = height) |
| 170 | std::optional<Texture2D> brickTexture = Texture2D::load("assets/textures/bricks.png", {.srgb = true}); | 218 | std::optional<Texture2D> brickTexture = Texture2D::load("assets/textures/bricks.png", {.srgb = true}); |
| 171 | std::optional<Texture2D> brickNormal = Texture2D::load("assets/textures/bricks_normal.png"); | 219 | std::optional<Texture2D> brickNormal = Texture2D::load("assets/textures/bricks_normal.png"); |
| 220 | std::optional<Texture2D> leavesTexture = Texture2D::load("assets/textures/leaves.png", {.srgb = true}); | ||
| 221 | // 影の地図を描くシェーダーと、それを見せるシェーダー / the shader that draws the shadow map and the one that shows it | ||
| 222 | std::optional<Shader> shadowShader = Shader::load("shaders/shadow.vert", "shaders/shadow.frag"); | ||
| 223 | std::optional<Shader> shadowDebug = Shader::load("shaders/post.vert", "shaders/shadow_debug.frag"); | ||
| 172 | if (!phong || !skybox || !post || !blur || !unlit || !sky || !floorTexture || !grassTexture || !brickTexture || | 224 | if (!phong || !skybox || !post || !blur || !unlit || !sky || !floorTexture || !grassTexture || !brickTexture || |
| 173 | !brickNormal) | 225 | !brickNormal || !leavesTexture || !shadowShader || !shadowDebug) |
| 174 | return 1; | 226 | return 1; |
| 175 | grassTexture->setWrap(GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE); | 227 | grassTexture->setWrap(GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE); |
| 176 | for (const Shader *s : {&*phong, &*skybox, &*post, &*unlit}) | 228 | for (const Shader *s : {&*phong, &*skybox, &*post, &*unlit, &*shadowShader}) |
| 177 | if (!s->checkUniformBlock("Camera", sizeof(CameraBlock)) || !s->checkUniformBlock("Lights", sizeof(LightsBlock)) || | 229 | if (!s->checkUniformBlock("Camera", sizeof(CameraBlock)) || !s->checkUniformBlock("Lights", sizeof(LightsBlock)) || |
| 178 | !s->checkUniformBlock("Post", sizeof(PostBlock))) | 230 | !s->checkUniformBlock("Post", sizeof(PostBlock)) || !s->checkUniformBlock("Shadow", sizeof(ShadowBlock))) |
| 179 | return 1; | 231 | return 1; |
| 180 | 232 | ||
| 181 | std::optional<Model> scene = Model::load("assets/models/diorama.glb"); | 233 | std::optional<Model> scene = Model::load("assets/models/diorama.glb"); |
| @@ -195,6 +247,22 @@ int main() { | |||
| 195 | UniformBuffer<CameraBlock> cameraUbo(kCameraBinding); | 247 | UniformBuffer<CameraBlock> cameraUbo(kCameraBinding); |
| 196 | UniformBuffer<LightsBlock> lightsUbo(kLightsBinding); | 248 | UniformBuffer<LightsBlock> lightsUbo(kLightsBinding); |
| 197 | UniformBuffer<PostBlock> postUbo(kPostBinding); | 249 | UniformBuffer<PostBlock> postUbo(kPostBinding); |
| 250 | UniformBuffer<ShadowBlock> shadowUbo(kShadowBinding); | ||
| 251 | |||
| 252 | // 影の地図:色なし、深度だけのテクスチャ(32ビット浮動小数点)。比較モード・GL_LINEAR・外側は1 | ||
| 253 | // The shadow map: no colour, only a depth texture (32-bit float). Comparison mode, GL_LINEAR, 1 outside | ||
| 254 | size_t shadowSizeIndex = 2; | ||
| 255 | const FramebufferSpec shadowSpec = {.colorFormat = 0, .depthStencilFormat = GL_DEPTH_COMPONENT32F, .depthTexture = true}; | ||
| 256 | Framebuffer shadowFbo(kShadowSizes[shadowSizeIndex], kShadowSizes[shadowSizeIndex], shadowSpec); | ||
| 257 | if (!shadowFbo.complete()) return 1; | ||
| 258 | // 影の地図を「見る」ためのサンプラーオブジェクト:比較なし。ユニットに繋ぐとテクスチャ自身の設定より優先される | ||
| 259 | // A sampler object for *looking at* the shadow map: no comparison. Bound to a unit, it overrides the texture's own | ||
| 260 | // sampling state | ||
| 261 | GLuint rawDepthSampler = 0; | ||
| 262 | glCreateSamplers(1, &rawDepthSampler); | ||
| 263 | glSamplerParameteri(rawDepthSampler, GL_TEXTURE_COMPARE_MODE, GL_NONE); | ||
| 264 | glSamplerParameteri(rawDepthSampler, GL_TEXTURE_MIN_FILTER, GL_NEAREST); | ||
| 265 | glSamplerParameteri(rawDepthSampler, GL_TEXTURE_MAG_FILTER, GL_NEAREST); | ||
| 198 | 266 | ||
| 199 | // HDRのフレームバッファ(第21章):色はGL_RGBA16F(1より明るい値も負の値も持てる半精度の浮動小数点)。 | 267 | // HDRのフレームバッファ(第21章):色はGL_RGBA16F(1より明るい値も負の値も持てる半精度の浮動小数点)。 |
| 200 | // 付け先0 = 場面の色、付け先1 = ブルームにする明るい部分(MRT)。MSAA(第20章)で描いて sceneFbo に解決する | 268 | // 付け先0 = 場面の色、付け先1 = ブルームにする明るい部分(MRT)。MSAA(第20章)で描いて sceneFbo に解決する |
| @@ -220,15 +288,17 @@ int main() { | |||
| 220 | glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS); | 288 | glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS); |
| 221 | 289 | ||
| 222 | Camera fps; | 290 | Camera fps; |
| 223 | fps.position = {0.3f, 1.6f, 10.0f}; | 291 | fps.position = {0.6f, 3.6f, 12.5f}; |
| 224 | fps.pitch = radians(-4.0f); | 292 | fps.pitch = radians(-17.0f); |
| 225 | 293 | ||
| 226 | OrbitCamera orbit; | 294 | OrbitCamera orbit; |
| 227 | orbit.target = {0.0f, 1.0f, 2.0f}; | 295 | orbit.target = {0.0f, 1.0f, 2.0f}; |
| 228 | orbit.distance = 11.0f; | 296 | orbit.distance = 11.0f; |
| 229 | orbit.yaw = radians(20.0f); | 297 | orbit.yaw = radians(20.0f); |
| 230 | 298 | ||
| 231 | bool useOrbit = false, normalMaps = true, parallax = true, movingLight = true; | 299 | bool useOrbit = false, shadowsOn = true, fitFrustum = false, showShadowMap = false; |
| 300 | size_t biasMode = kDefaultBias; | ||
| 301 | int cullMode = 0, shadowFilter = static_cast<int>(ShadowFilter::Pcf3x3); | ||
| 232 | int viewMode = 0, effect = 0; | 302 | int viewMode = 0, effect = 0; |
| 233 | float exposureEv = 0.0f; // 露出(段、EV):倍率は2^EV / exposure in stops (EV): the multiplier is 2^EV | 303 | float exposureEv = 0.0f; // 露出(段、EV):倍率は2^EV / exposure in stops (EV): the multiplier is 2^EV |
| 234 | PostBlock postSettings; | 304 | PostBlock postSettings; |
| @@ -239,7 +309,8 @@ int main() { | |||
| 239 | window.onKey = [&](int key, int action, int /*mods*/) { | 309 | window.onKey = [&](int key, int action, int /*mods*/) { |
| 240 | if (action != GLFW_PRESS) return; | 310 | if (action != GLFW_PRESS) return; |
| 241 | if (key == GLFW_KEY_ESCAPE) window.close(); | 311 | if (key == GLFW_KEY_ESCAPE) window.close(); |
| 242 | if (key == GLFW_KEY_R && phong->reload() && skybox->reload() && post->reload() && blur->reload() && unlit->reload()) | 312 | if (key == GLFW_KEY_R && phong->reload() && skybox->reload() && post->reload() && blur->reload() && unlit->reload() && |
| 313 | shadowShader->reload() && shadowDebug->reload()) | ||
| 243 | printf("シェーダーを読み直した / shaders reloaded\n"); | 314 | printf("シェーダーを読み直した / shaders reloaded\n"); |
| 244 | if (key == GLFW_KEY_TAB) window.setCursorCaptured(!window.cursorCaptured()); | 315 | if (key == GLFW_KEY_TAB) window.setCursorCaptured(!window.cursorCaptured()); |
| 245 | if (key == GLFW_KEY_C) { | 316 | if (key == GLFW_KEY_C) { |
| @@ -259,15 +330,32 @@ int main() { | |||
| 259 | exposureEv += key == GLFW_KEY_EQUAL ? 0.5f : -0.5f; | 330 | exposureEv += key == GLFW_KEY_EQUAL ? 0.5f : -0.5f; |
| 260 | printf("exposure: %+.1f EV (x%.3g)\n", exposureEv, std::exp2(exposureEv)); | 331 | printf("exposure: %+.1f EV (x%.3g)\n", exposureEv, std::exp2(exposureEv)); |
| 261 | } | 332 | } |
| 262 | if (key == GLFW_KEY_M) { | 333 | if (key == GLFW_KEY_H) { |
| 263 | normalMaps = !normalMaps; | 334 | shadowsOn = !shadowsOn; |
| 264 | printf("normal maps: %s\n", normalMaps ? "on" : "off"); | 335 | printf("shadows: %s\n", shadowsOn ? "on" : "off"); |
| 336 | } | ||
| 337 | if (key == GLFW_KEY_B) { | ||
| 338 | biasMode = (biasMode + 1) % std::size(kBiasModes); | ||
| 339 | printf("shadow bias: %s\n", kBiasModes[biasMode].name); | ||
| 265 | } | 340 | } |
| 266 | if (key == GLFW_KEY_X) { | 341 | if (key == GLFW_KEY_K) { |
| 267 | parallax = !parallax; | 342 | cullMode = (cullMode + 1) % 3; |
| 268 | printf("parallax mapping: %s\n", parallax ? "on" : "off"); | 343 | printf("shadow pass culling: %s\n", kCullNames[cullMode]); |
| 269 | } | 344 | } |
| 270 | if (key == GLFW_KEY_L) movingLight = !movingLight; | 345 | if (key == GLFW_KEY_G) { |
| 346 | shadowFilter = (shadowFilter + 1) % 4; | ||
| 347 | printf("shadow filter: %s\n", kFilterNames[shadowFilter]); | ||
| 348 | } | ||
| 349 | if (key == GLFW_KEY_J) { | ||
| 350 | fitFrustum = !fitFrustum; | ||
| 351 | printf("light box: %s\n", fitFrustum ? "camera frustum (0.1-8 m)" : "whole scene"); | ||
| 352 | } | ||
| 353 | if (key == GLFW_KEY_Z) { | ||
| 354 | shadowSizeIndex = (shadowSizeIndex + 1) % std::size(kShadowSizes); | ||
| 355 | shadowFbo = Framebuffer(kShadowSizes[shadowSizeIndex], kShadowSizes[shadowSizeIndex], shadowSpec); | ||
| 356 | printf("shadow map: %d x %d\n", shadowFbo.width(), shadowFbo.height()); | ||
| 357 | } | ||
| 358 | if (key == GLFW_KEY_O) showShadowMap = !showShadowMap; | ||
| 271 | if (key == GLFW_KEY_N) night = !night; | 359 | if (key == GLFW_KEY_N) night = !night; |
| 272 | if (key == GLFW_KEY_F) flashlightOn = !flashlightOn; | 360 | if (key == GLFW_KEY_F) flashlightOn = !flashlightOn; |
| 273 | if (key == GLFW_KEY_P) windmillMoving = !windmillMoving; | 361 | if (key == GLFW_KEY_P) windmillMoving = !windmillMoving; |
| @@ -311,6 +399,28 @@ int main() { | |||
| 311 | }; | 399 | }; |
| 312 | // 樽の置き場所 / where the barrels stand | 400 | // 樽の置き場所 / where the barrels stand |
| 313 | 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}}; | 401 | 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}}; |
| 402 | // パーゴラ:木の柱4本と、葉(切り抜き)の屋根。葉の形の影を落とす / a pergola: four wooden posts and a roof of | ||
| 403 | // (cut-out) leaves. It casts leaf-shaped shadows | ||
| 404 | const Vec3 kPergola = {1.3f, 0.0f, 5.8f}; | ||
| 405 | Mesh postMesh = makeBox({0.12f, 2.6f, 0.12f}); | ||
| 406 | Mesh roofMesh = makePlane(2.8f, 4.0f); | ||
| 407 | Material postMaterial; | ||
| 408 | postMaterial.diffuse = srgbToLinear(Vec3{0.45f, 0.32f, 0.2f}); | ||
| 409 | postMaterial.specular = {0.05f, 0.05f, 0.05f}; | ||
| 410 | postMaterial.shininess = 8.0f; | ||
| 411 | std::vector<Mat4> posts; | ||
| 412 | for (float x : {-1.3f, 1.3f}) | ||
| 413 | for (float z : {-1.3f, 1.3f}) posts.push_back(translate(kPergola + Vec3{x, 1.3f, z})); | ||
| 414 | // 葉の板2枚(2枚目は45°回して少し上に:隙間を埋める) / two leaf layers (the second turned 45° and a little higher: | ||
| 415 | // fills the gaps) | ||
| 416 | const Mat4 roofModels[] = {translate(kPergola + Vec3{0.0f, 2.6f, 0.0f}), | ||
| 417 | translate(kPergola + Vec3{0.0f, 2.68f, 0.0f}) * rotateY(0.785f) * scale({0.75f, 1.0f, 0.75f})}; | ||
| 418 | Material leavesMaterial; | ||
| 419 | leavesMaterial.diffuseMap = &*leavesTexture; | ||
| 420 | leavesMaterial.alphaMode = AlphaMode::Mask; | ||
| 421 | leavesMaterial.doubleSided = true; | ||
| 422 | leavesMaterial.specular = {0.03f, 0.03f, 0.03f}; | ||
| 423 | leavesMaterial.shininess = 8.0f; | ||
| 314 | // 手で選んだ色はsRGBの値(カラーピッカーの値):シェーダーはリニアで計算するので変換する | 424 | // 手で選んだ色はsRGBの値(カラーピッカーの値):シェーダーはリニアで計算するので変換する |
| 315 | // Hand-picked colours are sRGB values (what a colour picker shows): the shaders compute in linear space, so convert | 425 | // Hand-picked colours are sRGB values (what a colour picker shows): the shaders compute in linear space, so convert |
| 316 | Material wireMaterial; | 426 | Material wireMaterial; |
| @@ -323,8 +433,7 @@ int main() { | |||
| 323 | std::vector<Lantern> lanterns = makeLanterns(); | 433 | std::vector<Lantern> lanterns = makeLanterns(); |
| 324 | Mesh sphereMesh = makeSphere(24, 12); | 434 | Mesh sphereMesh = makeSphere(24, 12); |
| 325 | constexpr float kLanternGlow = 6.0f; | 435 | constexpr float kLanternGlow = 6.0f; |
| 326 | const Vec3 kMovingLightColor = {1.0f, 0.75f, 0.45f}; | 436 | |
| 327 | Vec3 movingLightPos; | ||
| 328 | 437 | ||
| 329 | FullscreenTriangle fullscreen; | 438 | FullscreenTriangle fullscreen; |
| 330 | glEnable(GL_CULL_FACE); | 439 | glEnable(GL_CULL_FACE); |
| @@ -339,8 +448,7 @@ int main() { | |||
| 339 | 448 | ||
| 340 | phong->use(); | 449 | phong->use(); |
| 341 | phong->set("uViewMode", viewMode); | 450 | phong->set("uViewMode", viewMode); |
| 342 | phong->set("uNormalMapping", normalMaps ? 1 : 0); | 451 | |
| 343 | phong->set("uParallaxMapping", parallax ? 1 : 0); | ||
| 344 | phong->set("uEnvironmentTint", environmentTint); | 452 | phong->set("uEnvironmentTint", environmentTint); |
| 345 | phong->set("uModel", Mat4::identity()); | 453 | phong->set("uModel", Mat4::identity()); |
| 346 | phong->set("uNormalMatrix", normalMatrix(Mat4::identity())); | 454 | phong->set("uNormalMatrix", normalMatrix(Mat4::identity())); |
| @@ -373,14 +481,11 @@ int main() { | |||
| 373 | b.mesh->draw(); | 481 | b.mesh->draw(); |
| 374 | } | 482 | } |
| 375 | for (const Placement &b : barrels) barrel->draw(*phong, translate(b.position) * rotateY(b.angle), white, ModelPass::Opaque); | 483 | for (const Placement &b : barrels) barrel->draw(*phong, translate(b.position) * rotateY(b.angle), white, ModelPass::Opaque); |
| 376 | // 回る点光源の目印(HDRで光る) / the marker of the circling point light (glows in HDR) | 484 | postMaterial.apply(*phong, white); |
| 377 | if (movingLight) { | 485 | for (const Mat4 &m : posts) { |
| 378 | unlit->use(); | 486 | phong->set("uModel", m); |
| 379 | unlit->set("uColor", 8.0f * kMovingLightColor); | 487 | phong->set("uNormalMatrix", normalMatrix(m)); |
| 380 | Mat4 model = translate(movingLightPos) * scale({0.08f, 0.08f, 0.08f}); | 488 | postMesh.draw(); |
| 381 | unlit->set("uModel", model); | ||
| 382 | sphereMesh.draw(); | ||
| 383 | phong->use(); | ||
| 384 | } | 489 | } |
| 385 | 490 | ||
| 386 | // 草:アルファトゥカバレッジならdiscardの代わりにサンプルの一部だけを覆う(MSAAのときだけ意味がある) | 491 | // 草:アルファトゥカバレッジならdiscardの代わりにサンプルの一部だけを覆う(MSAAのときだけ意味がある) |
| @@ -388,6 +493,15 @@ int main() { | |||
| 388 | // meaningful with MSAA) | 493 | // meaningful with MSAA) |
| 389 | glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE); | 494 | glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE); |
| 390 | phong->set("uAlphaToCoverage", 1); | 495 | phong->set("uAlphaToCoverage", 1); |
| 496 | // 葉の屋根(両面) / the roof of leaves (double-sided) | ||
| 497 | leavesMaterial.apply(*phong, white); | ||
| 498 | glDisable(GL_CULL_FACE); | ||
| 499 | for (const Mat4 &m : roofModels) { | ||
| 500 | phong->set("uModel", m); | ||
| 501 | phong->set("uNormalMatrix", normalMatrix(m)); | ||
| 502 | roofMesh.draw(); | ||
| 503 | } | ||
| 504 | glEnable(GL_CULL_FACE); | ||
| 391 | grassMaterial.apply(*phong, white); | 505 | grassMaterial.apply(*phong, white); |
| 392 | glDisable(GL_CULL_FACE); | 506 | glDisable(GL_CULL_FACE); |
| 393 | for (const Placement &g : grass) { | 507 | for (const Placement &g : grass) { |
| @@ -409,6 +523,37 @@ int main() { | |||
| 409 | glDepthFunc(GL_LESS); | 523 | glDepthFunc(GL_LESS); |
| 410 | }; | 524 | }; |
| 411 | 525 | ||
| 526 | // 影を落とす物を全部、影の地図に描く(深度だけ)。切り抜き(草、葉)はテクスチャのアルファで捨てる | ||
| 527 | // Draws every shadow caster into the shadow map (depth only). Cut-outs (grass, leaves) discard by texture alpha | ||
| 528 | auto drawShadowCasters = [&] { | ||
| 529 | shadowShader->use(); | ||
| 530 | shadowShader->set("uAlphaMask", 0); | ||
| 531 | auto drawMesh = [&](const Mesh &mesh, const Mat4 &model) { | ||
| 532 | shadowShader->set("uModel", model); | ||
| 533 | mesh.draw(); | ||
| 534 | }; | ||
| 535 | drawMesh(floorMesh, Mat4::identity()); | ||
| 536 | scene->drawDepth(*shadowShader, Mat4::identity(), white); | ||
| 537 | for (const Placement &c : kCrates) crate->drawDepth(*shadowShader, translate(c.position) * rotateY(c.angle), white); | ||
| 538 | for (const Placement &b : barrels) barrel->drawDepth(*shadowShader, translate(b.position) * rotateY(b.angle), white); | ||
| 539 | shadowShader->set("uAlphaMask", 0); | ||
| 540 | for (const Lantern &l : lanterns) drawMesh(sphereMesh, translate(l.position) * scale({0.3f, 0.38f, 0.3f})); | ||
| 541 | for (const Mat4 &m : wires) drawMesh(cubeMesh, m); | ||
| 542 | for (const Piece &b : bricks) drawMesh(*b.mesh, b.model); | ||
| 543 | for (const Mat4 &m : posts) drawMesh(postMesh, m); | ||
| 544 | // 切り抜き:両面なのでカリングなし / cut-outs: two-sided, so no culling | ||
| 545 | glDisable(GL_CULL_FACE); | ||
| 546 | shadowShader->set("uAlphaMask", 1); | ||
| 547 | shadowShader->set("uAlphaCutoff", 0.5f); | ||
| 548 | shadowShader->set("uBaseAlpha", 1.0f); | ||
| 549 | leavesTexture->bind(0); | ||
| 550 | for (const Mat4 &m : roofModels) drawMesh(roofMesh, m); | ||
| 551 | grassTexture->bind(0); | ||
| 552 | for (const Placement &g : grass) drawMesh(tuftMesh, translate(g.position) * rotateY(g.angle) * scale({0.75f, 0.75f, 0.75f})); | ||
| 553 | shadowShader->set("uAlphaMask", 0); | ||
| 554 | }; | ||
| 555 | |||
| 556 | int frame = 0; | ||
| 412 | double lastTime = window.time(); | 557 | double lastTime = window.time(); |
| 413 | while (!window.shouldClose()) { | 558 | while (!window.shouldClose()) { |
| 414 | double now = window.time(); | 559 | double now = window.time(); |
| @@ -440,9 +585,7 @@ int main() { | |||
| 440 | Quat::fromAxisAngle({0.0f, 0.0f, 1.0f}, -0.8f * windmillTime) * rotorStart; | 585 | Quat::fromAxisAngle({0.0f, 0.0f, 1.0f}, -0.8f * windmillTime) * rotorStart; |
| 441 | 586 | ||
| 442 | float aspect = static_cast<float>(sceneFbo.width()) / static_cast<float>(sceneFbo.height()); | 587 | float aspect = static_cast<float>(sceneFbo.width()) / static_cast<float>(sceneFbo.height()); |
| 443 | // 壁の前を回る光:壁すれすれの角度から照らすと凹凸がよく見える / the light circling in front of the wall: light from | 588 | |
| 444 | // grazing angles shows the bumps best | ||
| 445 | movingLightPos = {-1.6f + 1.8f * std::cos(0.7f * windmillTime), 1.3f + 0.6f * std::sin(1.3f * windmillTime), 4.75f}; | ||
| 446 | CameraBlock camera; | 589 | CameraBlock camera; |
| 447 | camera.view = useOrbit ? orbit.view() : fps.view(); | 590 | camera.view = useOrbit ? orbit.view() : fps.view(); |
| 448 | camera.proj = useOrbit ? orbit.projection(aspect) : fps.projection(aspect); | 591 | camera.proj = useOrbit ? orbit.projection(aspect) : fps.projection(aspect); |
| @@ -468,8 +611,7 @@ int main() { | |||
| 468 | for (size_t i = 3; i < 6; ++i) | 611 | for (size_t i = 3; i < 6; ++i) |
| 469 | lights.points.push_back({.position = lanterns[i].position, .color = 1.5f * lanterns[i].color, .attenuation = kMediumRange}); | 612 | lights.points.push_back({.position = lanterns[i].position, .color = 1.5f * lanterns[i].color, .attenuation = kMediumRange}); |
| 470 | } | 613 | } |
| 471 | if (movingLight) | 614 | |
| 472 | lights.points.push_back({.position = movingLightPos, .color = 2.5f * kMovingLightColor, .attenuation = kMediumRange}); | ||
| 473 | if (flashlightOn) | 615 | if (flashlightOn) |
| 474 | lights.spots.push_back({.position = camera.viewPos, .direction = viewDir, .color = {1.0f, 0.95f, 0.85f}}); | 616 | lights.spots.push_back({.position = camera.viewPos, .direction = viewDir, .color = {1.0f, 0.95f, 0.85f}}); |
| 475 | lightsUbo.update(lights.toBlock()); | 617 | lightsUbo.update(lights.toBlock()); |
| @@ -487,6 +629,70 @@ int main() { | |||
| 487 | } | 629 | } |
| 488 | postUbo.update(postSettings); | 630 | postUbo.update(postSettings); |
| 489 | 631 | ||
| 632 | //------------------------------------------------------------------ | ||
| 633 | // 0. 影の地図:太陽から見た深度(第23章) / 0. the shadow map: depth as seen from the sun (chapter 23) | ||
| 634 | //------------------------------------------------------------------ | ||
| 635 | // 光の箱:場面全体を囲む球か、カメラの視錐台の手前8 mを囲む球 / the light box: a sphere around the whole scene, | ||
| 636 | // or a sphere around the first 8 m of the camera frustum | ||
| 637 | Vec3 fitCentre = {0.0f, 1.0f, 2.5f}; | ||
| 638 | float fitRadius = 9.5f; | ||
| 639 | if (fitFrustum) { | ||
| 640 | float nearPlane = 0.1f, farPlane = 8.0f, fov = useOrbit ? orbit.fov : fps.fov; | ||
| 641 | Vec3 f = viewDir, r = normalize(cross(f, Vec3{0.0f, 1.0f, 0.0f})), u = cross(r, f); | ||
| 642 | float th = std::tan(0.5f * fov); | ||
| 643 | Vec3 corners[8]; | ||
| 644 | int k = 0; | ||
| 645 | for (float dist : {nearPlane, farPlane}) | ||
| 646 | for (float sy : {-1.0f, 1.0f}) | ||
| 647 | for (float sx : {-1.0f, 1.0f}) | ||
| 648 | corners[k++] = camera.viewPos + dist * f + (sx * dist * th * aspect) * r + (sy * dist * th) * u; | ||
| 649 | // 中心は8つの角の平均、半径は一番遠い角まで(カメラが回っても大きさは変わらない) | ||
| 650 | // Centre = the mean of the 8 corners, radius = to the farthest corner (its size does not change as the camera turns) | ||
| 651 | fitCentre = {0.0f, 0.0f, 0.0f}; | ||
| 652 | for (Vec3 c : corners) fitCentre = fitCentre + 0.125f * c; | ||
| 653 | fitRadius = 0.0f; | ||
| 654 | for (Vec3 c : corners) fitRadius = std::max(fitRadius, length(c - fitCentre)); | ||
| 655 | } | ||
| 656 | if (frame++ % 60 == 5) printf("light box radius %.2f m: %.1f mm per shadow texel\n", fitRadius, 2000.0f * fitRadius / static_cast<float>(shadowFbo.width())); | ||
| 657 | const BiasMode &bias = kBiasModes[biasMode]; | ||
| 658 | float depthRange = 1.0f; | ||
| 659 | ShadowBlock shadowBlock; | ||
| 660 | shadowBlock.lightSpace = lightSpaceMatrix(lights.directional.direction, fitCentre, fitRadius, shadowFbo.width(), depthRange); | ||
| 661 | // バイアスはメートルで決めて、0〜1の深度に直す(正射影なので深度は距離に比例) / biases are chosen in metres and | ||
| 662 | // converted to 0..1 depth (orthographic: depth is proportional to distance) | ||
| 663 | float unit = bias.inTexels ? 2.0f * fitRadius / static_cast<float>(shadowFbo.width()) : 1.0f; // m | ||
| 664 | shadowBlock.bias = bias.constant * unit / depthRange; | ||
| 665 | shadowBlock.slopeBias = bias.slope * unit / depthRange; | ||
| 666 | shadowBlock.normalOffset = bias.normalOffset * unit; | ||
| 667 | shadowBlock.filter = shadowFilter; | ||
| 668 | shadowBlock.texel = {1.0f / static_cast<float>(shadowFbo.width()), 1.0f / static_cast<float>(shadowFbo.height())}; | ||
| 669 | shadowBlock.enabled = shadowsOn ? 1 : 0; | ||
| 670 | shadowUbo.update(shadowBlock); | ||
| 671 | // 硬い影はGL_NEAREST、それ以外はGL_LINEAR(比較の結果を2×2で補間) / hard shadows use GL_NEAREST, the others | ||
| 672 | // GL_LINEAR (the comparison results are blended 2 × 2) | ||
| 673 | GLenum shadowFilterMode = shadowFilter == static_cast<int>(ShadowFilter::Hard) ? GL_NEAREST : GL_LINEAR; | ||
| 674 | shadowFbo.depth().setFilter(shadowFilterMode, shadowFilterMode); | ||
| 675 | |||
| 676 | if (shadowsOn) { | ||
| 677 | shadowFbo.bind(); | ||
| 678 | glEnable(GL_DEPTH_TEST); | ||
| 679 | glClear(GL_DEPTH_BUFFER_BIT); | ||
| 680 | if (cullMode == 1) glCullFace(GL_FRONT); // 表面を捨て、裏面の深度を保存する / keep the back faces' depth | ||
| 681 | if (cullMode == 2) glDisable(GL_CULL_FACE); | ||
| 682 | if (bias.polygonOffset) { | ||
| 683 | // ハードウェアの傾きバイアス:深度 += factor × 傾き + units × 最小の深度の差 / hardware slope bias: | ||
| 684 | // depth += factor × slope + units × the smallest depth step | ||
| 685 | glEnable(GL_POLYGON_OFFSET_FILL); | ||
| 686 | glPolygonOffset(2.0f, 4.0f); | ||
| 687 | } | ||
| 688 | drawShadowCasters(); | ||
| 689 | glDisable(GL_POLYGON_OFFSET_FILL); | ||
| 690 | glCullFace(GL_BACK); | ||
| 691 | glEnable(GL_CULL_FACE); | ||
| 692 | } | ||
| 693 | // 影の地図はユニット5(描き終わってから繋ぐ) / the shadow map goes on unit 5 (after it has been drawn) | ||
| 694 | shadowFbo.depth().bind(5); | ||
| 695 | |||
| 490 | //------------------------------------------------------------------ | 696 | //------------------------------------------------------------------ |
| 491 | // 1. 場面をHDR・MSAAで描き、解決する(色の付け先は2つとも) / 1. draw the scene in HDR with MSAA and resolve it | 697 | // 1. 場面をHDR・MSAAで描き、解決する(色の付け先は2つとも) / 1. draw the scene in HDR with MSAA and resolve it |
| 492 | // (both colour attachments) | 698 | // (both colour attachments) |
| @@ -516,11 +722,6 @@ int main() { | |||
| 516 | // mapping, sRGB | 722 | // mapping, sRGB |
| 517 | //------------------------------------------------------------------ | 723 | //------------------------------------------------------------------ |
| 518 | Framebuffer::bindDefault(window.width(), window.height()); | 724 | Framebuffer::bindDefault(window.width(), window.height()); |
| 519 | // GammaMode 1と3:GPUが書くときにリニア→sRGBにする(画面がsRGBのときだけ効く) | ||
| 520 | // Gamma modes 1 and 3: the GPU converts linear → sRGB on write (only works if the screen is sRGB) | ||
| 521 | bool framebufferSrgb = postSettings.gammaMode == static_cast<int>(GammaMode::FramebufferSrgb) || | ||
| 522 | postSettings.gammaMode == static_cast<int>(GammaMode::Double); | ||
| 523 | if (framebufferSrgb) glEnable(GL_FRAMEBUFFER_SRGB); | ||
| 524 | post->use(); | 725 | post->use(); |
| 525 | post->set("uEffect", effect); | 726 | post->set("uEffect", effect); |
| 526 | post->set("uFlipX", 0); | 727 | post->set("uFlipX", 0); |
| @@ -528,9 +729,25 @@ int main() { | |||
| 528 | bloomFbo[1].color().bind(1); // 最後の縦のパスの結果 / the result of the last vertical pass | 729 | bloomFbo[1].color().bind(1); // 最後の縦のパスの結果 / the result of the last vertical pass |
| 529 | sceneFbo.color(1).bind(2); | 730 | sceneFbo.color(1).bind(2); |
| 530 | fullscreen.draw(); | 731 | fullscreen.draw(); |
| 531 | glDisable(GL_FRAMEBUFFER_SRGB); | 732 | |
| 733 | // 影の地図を左下に(比較なしのサンプラーで深度を読む) / the shadow map at the bottom left (depth read through the | ||
| 734 | // sampler without comparison) | ||
| 735 | if (showShadowMap) { | ||
| 736 | glViewport(16, 16, 320, 320); | ||
| 737 | shadowDebug->use(); | ||
| 738 | shadowFbo.depth().bind(0); | ||
| 739 | glBindSampler(0, rawDepthSampler); | ||
| 740 | fullscreen.draw(); | ||
| 741 | glBindSampler(0, 0); // ユニット0はテクスチャ自身の設定に戻る / unit 0 goes back to the texture's own state | ||
| 742 | // 影の地図をユニット0から外す:次のシャドウパスではshadow.fragのuBaseMapがユニット0で、描き込み中の深度を | ||
| 743 | // 読むとフィードバックループになる / take the shadow map off unit 0: in the next shadow pass shadow.frag's | ||
| 744 | // uBaseMap is on unit 0, and reading the depth being written would be a feedback loop | ||
| 745 | white.bind(0); | ||
| 746 | glViewport(0, 0, window.width(), window.height()); | ||
| 747 | } | ||
| 532 | 748 | ||
| 533 | window.swapBuffers(); | 749 | window.swapBuffers(); |
| 534 | } | 750 | } |
| 751 | glDeleteSamplers(1, &rawDepthSampler); | ||
| 535 | return 0; | 752 | return 0; |
| 536 | } | 753 | } |
ファイル: a/src/model.cc | b/src/model.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -323,6 +323,12 @@ void Model::drawGeometry(const Shader &shader, const Mat4 &transform) const { | |||
| 323 | drawItems(items, shader, nullptr, shader.has("uNormalMatrix")); | 323 | drawItems(items, shader, nullptr, shader.has("uNormalMatrix")); |
| 324 | } | 324 | } |
| 325 | 325 | ||
| 326 | void Model::drawDepth(const Shader &shader, const Mat4 &transform, const Texture2D &white) const { | ||
| 327 | std::vector<DrawItem> items; | ||
| 328 | for (int root : roots) collect(root, transform, transform, true, ModelPass::Opaque, {}, items); | ||
| 329 | drawItems(items, shader, &white, false, 0, true); | ||
| 330 | } | ||
| 331 | |||
| 326 | const Model::MaterialData &Model::materialOf(const Primitive &p) const { | 332 | const Model::MaterialData &Model::materialOf(const Primitive &p) const { |
| 327 | return p.material >= 0 ? materials[static_cast<size_t>(p.material)] : defaultMaterial; | 333 | return p.material >= 0 ? materials[static_cast<size_t>(p.material)] : defaultMaterial; |
| 328 | } | 334 | } |
| @@ -356,14 +362,24 @@ void Model::drawInstanced(const Shader &shader, const Texture2D &white, GLsizei | |||
| 356 | } | 362 | } |
| 357 | 363 | ||
| 358 | void Model::drawItems(const std::vector<DrawItem> &items, const Shader &shader, const Texture2D *white, | 364 | void Model::drawItems(const std::vector<DrawItem> &items, const Shader &shader, const Texture2D *white, |
| 359 | bool normals, GLsizei instances) const { | 365 | bool normals, GLsizei instances, bool depthOnly) const { |
| 360 | bool culling = glIsEnabled(GL_CULL_FACE); // 呼ぶ側の設定を覚えておく / remember the caller's setting | 366 | bool culling = glIsEnabled(GL_CULL_FACE); // 呼ぶ側の設定を覚えておく / remember the caller's setting |
| 361 | for (const DrawItem &item : items) { | 367 | for (const DrawItem &item : items) { |
| 362 | const Primitive &p = *item.primitive; | 368 | const Primitive &p = *item.primitive; |
| 363 | const MaterialData &md = materialOf(p); | 369 | const MaterialData &md = materialOf(p); |
| 364 | shader.set("uModel", item.world); | 370 | shader.set("uModel", item.world); |
| 365 | if (normals) shader.set("uNormalMatrix", normalMatrix(item.world)); | 371 | if (normals) shader.set("uNormalMatrix", normalMatrix(item.world)); |
| 366 | if (white) { | 372 | if (white && depthOnly) { |
| 373 | // 影:切り抜き(Mask)だけテクスチャのアルファが要る / shadows: only cut-outs (Mask) need the texture's alpha | ||
| 374 | bool mask = md.phong.alphaMode == AlphaMode::Mask; | ||
| 375 | shader.set("uAlphaMask", mask ? 1 : 0); | ||
| 376 | if (mask) { | ||
| 377 | const Texture2D *base = texture(md.pbr.baseColorTexture.index); | ||
| 378 | (base ? base : white)->bind(0); | ||
| 379 | shader.set("uAlphaCutoff", md.phong.alphaCutoff); | ||
| 380 | shader.set("uBaseAlpha", md.phong.alpha); | ||
| 381 | } | ||
| 382 | } else if (white) { | ||
| 367 | Material m = md.phong; | 383 | Material m = md.phong; |
| 368 | m.diffuseMap = texture(md.pbr.baseColorTexture.index); // 色 = 係数 × テクスチャ / colour = factor × texture | 384 | m.diffuseMap = texture(md.pbr.baseColorTexture.index); // 色 = 係数 × テクスチャ / colour = factor × texture |
| 369 | m.emissionMap = texture(md.pbr.emissiveTexture.index); | 385 | m.emissionMap = texture(md.pbr.emissiveTexture.index); |
ファイル: a/src/model.hh | b/src/model.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -71,6 +71,14 @@ public: | |||
| 71 | // For passes that need no colour: the depth view, outlines, and later shadows (chapter 23). | 71 | // For passes that need no colour: the depth view, outlines, and later shadows (chapter 23). |
| 72 | void drawGeometry(const Shader &shader, const Mat4 &transform) const; | 72 | void drawGeometry(const Shader &shader, const Mat4 &transform) const; |
| 73 | 73 | ||
| 74 | // 影の地図の深度だけを描く(第23章)。OpaqueとMaskのプリミティブ(Blendは影を落とさない)。Maskのマテリアルは | ||
| 75 | // ベースカラーのテクスチャ(なければwhite)をユニット0に繋ぎ、uAlphaMask = 1、uAlphaCutoff、uBaseAlphaを設定する | ||
| 76 | // (シェーダーがdiscardで葉の形に切り抜く)。ほかはuAlphaMask = 0。両面のマテリアルはカリングを切る。 | ||
| 77 | // Draws depth only, for shadow maps (chapter 23). Opaque and Mask primitives (Blend casts no shadow). For Mask | ||
| 78 | // materials the base colour texture (or white) goes on unit 0 and uAlphaMask = 1, uAlphaCutoff and uBaseAlpha are | ||
| 79 | // set (the shader discards to cut out leaves); otherwise uAlphaMask = 0. Double-sided materials turn culling off. | ||
| 80 | void drawDepth(const Shader &shader, const Mat4 &transform, const Texture2D &white) const; | ||
| 81 | |||
| 74 | // インスタンシング(第19章):全部のプリミティブのVAOにインスタンスのバッファを繋ぐ(Mesh::setInstanceBuffer) | 82 | // インスタンシング(第19章):全部のプリミティブのVAOにインスタンスのバッファを繋ぐ(Mesh::setInstanceBuffer) |
| 75 | // Instancing (chapter 19): attaches the instance buffer to every primitive's VAO (Mesh::setInstanceBuffer) | 83 | // Instancing (chapter 19): attaches the instance buffer to every primitive's VAO (Mesh::setInstanceBuffer) |
| 76 | void setInstanceBuffer(const Buffer &buffer, GLsizei stride, std::span<const VertexAttrib> layout); | 84 | void setInstanceBuffer(const Buffer &buffer, GLsizei stride, std::span<const VertexAttrib> layout); |
| @@ -109,7 +117,7 @@ private: | |||
| 109 | Vec3 viewPos, std::vector<DrawItem> &out) const; | 117 | Vec3 viewPos, std::vector<DrawItem> &out) const; |
| 110 | // white == nullptrなら形だけ(drawGeometry) / white == nullptr: shape only (drawGeometry) | 118 | // white == nullptrなら形だけ(drawGeometry) / white == nullptr: shape only (drawGeometry) |
| 111 | void drawItems(const std::vector<DrawItem> &items, const Shader &shader, const Texture2D *white, bool normals, | 119 | void drawItems(const std::vector<DrawItem> &items, const Shader &shader, const Texture2D *white, bool normals, |
| 112 | GLsizei instances = 0) const; | 120 | GLsizei instances = 0, bool depthOnly = false) const; |
| 113 | const MaterialData &materialOf(const Primitive &p) const; | 121 | const MaterialData &materialOf(const Primitive &p) const; |
| 114 | const Texture2D *texture(int index) const; // なければnullptr / nullptr if missing | 122 | const Texture2D *texture(int index) const; // なければnullptr / nullptr if missing |
| 115 | 123 | ||
ファイル: a/src/texture.cc | b/src/texture.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -128,3 +128,13 @@ std::optional<Image> decodeImage(const unsigned char *bytes, size_t size, bool f | |||
| 128 | stbi_image_free(pixels); | 128 | stbi_image_free(pixels); |
| 129 | return image; | 129 | return image; |
| 130 | } | 130 | } |
| 131 | |||
| 132 | void Texture2D::setBorderColor(float r, float g, float b, float a) { | ||
| 133 | const float color[4] = {r, g, b, a}; | ||
| 134 | glTextureParameterfv(handle, GL_TEXTURE_BORDER_COLOR, color); | ||
| 135 | } | ||
| 136 | |||
| 137 | void Texture2D::setCompare(bool on) { | ||
| 138 | glTextureParameteri(handle, GL_TEXTURE_COMPARE_MODE, on ? GL_COMPARE_REF_TO_TEXTURE : GL_NONE); | ||
| 139 | glTextureParameteri(handle, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL); // 手前か同じなら1(光が当たる) / 1 if nearer or equal (lit) | ||
| 140 | } | ||
ファイル: a/src/texture.hh | b/src/texture.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -62,6 +62,14 @@ public: | |||
| 62 | 62 | ||
| 63 | void setFilter(GLenum minFilter, GLenum magFilter); | 63 | void setFilter(GLenum minFilter, GLenum magFilter); |
| 64 | void setWrap(GLenum wrapS, GLenum wrapT); | 64 | void setWrap(GLenum wrapS, GLenum wrapT); |
| 65 | // GL_CLAMP_TO_BORDERで外側を読んだときの色(影の地図では1 = 一番奥 = 影なし、第23章) | ||
| 66 | // The colour read outside with GL_CLAMP_TO_BORDER (1 = farthest = not in shadow for shadow maps, chapter 23) | ||
| 67 | void setBorderColor(float r, float g, float b, float a); | ||
| 68 | // 深度テクスチャの比較モード(第23章):onなら sampler2DShadow で texture(s, vec3(uv, 深さ)) が | ||
| 69 | // 「深さ <= 保存された深度」の結果(0か1、GL_LINEARなら周りの4テクセルの結果の補間)を返す | ||
| 70 | // Depth comparison mode for depth textures (chapter 23): when on, texture(s, vec3(uv, depth)) on a sampler2DShadow | ||
| 71 | // returns the result of "depth <= stored depth" (0 or 1; with GL_LINEAR the interpolated results of 4 texels) | ||
| 72 | void setCompare(bool on); | ||
| 65 | 73 | ||
| 66 | // テクスチャユニットunitに繋ぐ(シェーダーの layout(binding = unit)) / attach to texture unit `unit` | 74 | // テクスチャユニットunitに繋ぐ(シェーダーの layout(binding = unit)) / attach to texture unit `unit` |
| 67 | void bind(GLuint unit) const { glBindTextureUnit(unit, handle); } | 75 | void bind(GLuint unit) const { glBindTextureUnit(unit, handle); } |
ファイル: a/src/uniforms.hh | b/src/uniforms.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -12,7 +12,7 @@ | |||
| 12 | // Binding point numbers. Must match layout(std140, binding = N) in the shaders | 12 | // Binding point numbers. Must match layout(std140, binding = N) in the shaders |
| 13 | constexpr GLuint kCameraBinding = 0; // Camera:ビュー・射影・カメラの位置・時間 / view, projection, camera position, time | 13 | constexpr GLuint kCameraBinding = 0; // Camera:ビュー・射影・カメラの位置・時間 / view, projection, camera position, time |
| 14 | constexpr GLuint kLightsBinding = 1; // Lights:全部の光(lights.hhのLightsBlock) / all lights (LightsBlock in lights.hh) | 14 | constexpr GLuint kLightsBinding = 1; // Lights:全部の光(lights.hhのLightsBlock) / all lights (LightsBlock in lights.hh) |
| 15 | // 2 = 影(第23章:光から見た行列) / shadows (chapter 23: light-space matrices) | 15 | constexpr GLuint kShadowBinding = 2; // Shadow:光から見た行列と影の設定(第23章) / light-space matrix + settings (ch. 23) |
| 16 | constexpr GLuint kPostBinding = 3; // Post:露出、トーンマッピング、ブルーム(第21章) / exposure, tone mapping, bloom (ch. 21) | 16 | constexpr GLuint kPostBinding = 3; // Post:露出、トーンマッピング、ブルーム(第21章) / exposure, tone mapping, bloom (ch. 21) |
| 17 | 17 | ||
| 18 | // std140の規則(よく使うものだけ) / the std140 rules (the common ones) | 18 | // std140の規則(よく使うものだけ) / the std140 rules (the common ones) |
| @@ -99,3 +99,37 @@ struct PostBlock { | |||
| 99 | static_assert(offsetof(PostBlock, bloomThreshold) == 8); | 99 | static_assert(offsetof(PostBlock, bloomThreshold) == 8); |
| 100 | static_assert(offsetof(PostBlock, view) == 20); | 100 | static_assert(offsetof(PostBlock, view) == 20); |
| 101 | static_assert(sizeof(PostBlock) == 32); | 101 | static_assert(sizeof(PostBlock) == 32); |
| 102 | |||
| 103 | // 影の地図の読み方(phong.fragのuShadowFilterと同じ番号) / how the shadow map is filtered (same numbers as uShadowFilter) | ||
| 104 | enum class ShadowFilter { | ||
| 105 | Hard = 0, // GL_NEARESTで1回:ギザギザ / one GL_NEAREST lookup: jagged | ||
| 106 | Hardware2x2 = 1, // GL_LINEARで1回:GPUが4テクセルの比較結果を補間 / one GL_LINEAR lookup: the GPU blends 4 comparisons | ||
| 107 | Pcf3x3 = 2, // GL_LINEARで3×3回(PCF) / 3 × 3 GL_LINEAR lookups (PCF) | ||
| 108 | Pcf5x5 = 3, // 5×5回 / 5 × 5 lookups | ||
| 109 | }; | ||
| 110 | |||
| 111 | // GLSL: | ||
| 112 | // layout(std140, binding = 2) uniform Shadow { | ||
| 113 | // mat4 uLightSpace; // offset 0:ワールド → 光のクリップ座標 / world → the light's clip space | ||
| 114 | // float uShadowBias; // 64:深度から引く一定の量(0〜1の深度) / constant offset subtracted (0..1 depth) | ||
| 115 | // float uShadowSlopeBias; // 68:面が光に対して斜めなほど大きく / grows as the surface tilts away from the light | ||
| 116 | // float uShadowNormalOffset;// 72:法線方向にずらす距離(m) / distance pushed along the normal (m) | ||
| 117 | // int uShadowFilter; // 76 | ||
| 118 | // vec2 uShadowTexel; // 80:1テクセルのUV / one texel in UV units | ||
| 119 | // int uShadowsEnabled; // 88 | ||
| 120 | // int uShadowPad; // 92 | ||
| 121 | // }; // 96 bytes | ||
| 122 | struct ShadowBlock { | ||
| 123 | Mat4 lightSpace; | ||
| 124 | float bias = 0.0f; | ||
| 125 | float slopeBias = 0.0f; | ||
| 126 | float normalOffset = 0.0f; | ||
| 127 | int filter = static_cast<int>(ShadowFilter::Pcf3x3); | ||
| 128 | Vec2 texel; | ||
| 129 | int enabled = 1; | ||
| 130 | int pad = 0; | ||
| 131 | }; | ||
| 132 | static_assert(offsetof(ShadowBlock, bias) == 64); | ||
| 133 | static_assert(offsetof(ShadowBlock, texel) == 80); | ||
| 134 | static_assert(offsetof(ShadowBlock, enabled) == 88); | ||
| 135 | static_assert(sizeof(ShadowBlock) == 96); | ||
コメント(0)
まだコメントはありません。
ログインするとコメント出来ます。