21. ガンマ補正とHDR
第6章からずっと「色は第21章で直します」と約束して来ました。
此れが其の章です。
今迄ずっと、2つの事が黙って間違っていました。
1つ目に、ライティングの計算で掛けたり足したりしていた数字は光の量ではなく、画像ファイルのsRGBで符号化された値でした。
2つ目に、全ての結果は書き込む時に0〜1に押し込まれていたので、提灯は白い壁より明るくなれず、太陽も雲より明るくなれませんでした。
1つ目の問題はガンマ補正で直します。
色は入って来る時に線型の光にデコードし、シェーディングは全て線型の光で行い、画面へ出す時にもう一度エンコードします。
2つ目の問題はHDR(ハイダイナミックレンジ)で直します。
場面はどんな明るさでも持てる浮動小数点のフレームバッファに描き、最後に露出とトーンマッパーが其れを絵にします。
本物の明るさが手に入れば、ブルームは殆どおまけで付いて来ます。白より明るい物は周りに滲んで光ります。
途中でマルチレンダーターゲット、3つ目のユニフォームブロック、そして色が正しくなって初めて見える様になった、第13章のアセットの間違いにも出会います。
21.1 此の章で作る物
第20章の場面(床、ジオラマ、木箱、柵、電線の付いた電柱、草、空)に、電線の下に吊るした9つの提灯が加わります。
昼の絵は前より落ち着いて自然に見えます。
色はもう白っぽくなく、明るい漆喰や木箱の上面も細部が残ります:
夜(N)には、提灯はテクスチャが持てるどんな値よりもずっと明るく光り、ブルームが其の光を柔らかい光の輪に広げます:
操作:
- W、A、S、D、スペース、左Ctrl、Shift、マウス、ホイール:今迄通り移動と見回し
- =と−:露出を半段ずつ上げる・下げる(新規)
- T:トーンマッピング:なし(クランプ) → Reinhard → ACES(新規)
- G:ガンマ:シェーダー →
GL_FRAMEBUFFER_SRGB→ なし(間違い) → 二重(間違い)(新規) - B:ブルームのオン・オフ(新規)
- O:後処理の表示:完成 → ブルームなし → 明るい部分 → ぼかしたブルーム(新規)
- K:電線越しに太陽を見る(新規)
- 1〜6:第17章のポストプロセスの効果
- C:FPS ⇔ オービットカメラ、V:表示モード、N:昼 ⇔ 夜、F:懐中電灯、P:風車を止める
- Tab:カーソルの解放、R:シェーダーを読み直す、Esc:終了
第20章のアンチエイリアスのメニューは無くなりました。
キーのM、X、T(アルファトゥカバレッジ)、Z、FXAA風のパス、拡大鏡、--directです。
MSAAは4サンプルに固定され(kMsaaSamples)、草のアルファトゥカバレッジは常にオンで、Window::createのsamples引数は後の為に残してあります。
第20章からの変更:
src/texture.hhとsrc/texture.cc:TextureOptions::srgbが遂に使われる様になり、乗算済みアルファは線型空間で計算するsrc/cubemap.hhとsrc/cubemap.cc:loadとloadDirectoryにsrgb引数src/model.cc:glTFのベースカラーと発光のテクスチャはsRGB、其れ以外のテクスチャは線型のままsrc/mathx.hh:コードに書いた色の為のsrgbToLinear()src/framebuffer.hhとsrc/framebuffer.cc:色の付け先を複数(colorCount、color(i))、blitToは其の全てをコピーするsrc/uniforms.hh:結合点3のPostブロックと、列挙型ToneMapper、GammaMode、PostViewshaders/post.frag:書き直し(ブルーム、露出、トーンマッピング、sRGBエンコード、其の後に効果)shaders/blur.frag(新規):ガウスぼかしの1方向shaders/skybox.frag:HDRの太陽。phong.frag、unlit.frag、envmap.frag、skybox.fragは全て2つ目の出力を書くsrc/main.cc:HDRのフレームバッファ、ブルームのパス、提灯、明るい光、新しいキーassets/models/diorama.glb:線型の色の係数で作り直し(21.4節)(完成したファイルは章のZIPとアセットのZIPのch21/に入っています)
21.2 線型の光とsRGB:おさらい
GLSLシリーズの第10.7章でガンマを詳しく説明したので、此処では短くまとめます。
画像ファイルの数字は光の量ではありません。
目は明るい色調より暗い色調の違いをずっと良く見分けるので、8ビットの画像は256段階の殆どを暗い方に使う非線型の符号化、sRGBを使います。
モニターは値を光に変える時に其の符号化を元に戻します。
保存された値0.5(255の内128)で、画面は白の半分の光を出すのではなく、約21%しか出しません。
正確なsRGBの曲線(IEC 61966-2-1)は、黒の近くに短い直線の部分があり、其れ以外は2.4乗です。
を線型の光の量、を符号化した値とし、どちらも0〜1とすると:
2つの部分はちゃんと繋がっています。で、累乗の方も其処で同じ値になります。
全体としては、良く知られた近似と殆ど同じ様に振る舞いますが、全く同じではありません:
- 半分の光は、つまり255の内188として保存されます。近似では、186です。
- 値はにデコードされ、近似のより少し小さくなります。
- 2つの符号化の一番大きな違いは黒の近くです。で正確な曲線は低く、255の内約8.5段階です。直線の部分は、曲線が0で無限に急にならない為にあります。
- 256段階の内188段階が半分より少ない光を表し、其の内118段階は18%(写真家の言う「中間のグレー」)より少ない光です。其れが此の符号化の目的です。
現代のレンダラーは全て、3つの部分から成る規則に従っています:
- 符号化された色(画像、目で選んだ色)は全て線型の光にデコードする。
- シェーディング、ブレンド、ぼかしは全て線型の値で行う。
- 一番最後に1回だけ、画面の為にエンコードする。
今迄のパイプラインは手順1と3を飛ばしていました。
両端で符号化を無視していたので、ライティング無しのテクスチャは保存された通りに出て、其の為第6章は正しく見えました。
然し其の間の全て、ライティング、ブレンド、第17章のぼかしのカーネル、第20章のMSAAの平均は、符号化された数字で計算していました。
其の計算が正しいのは線型の数字の時だけです。
21.3 sRGBテクスチャ
サンプラーにデコードさせる
手順1はOpenGLが無料でやってくれます。
内部形式がGL_SRGB8_ALPHA8のテクスチャはGL_RGBA8と同じ8ビットの値を保存しますが、シェーダーがサンプリングする度に、GPUがR、G、BをsRGBから線型に変換します。
シェーダーは命令を1つも増やさずに線型の値を受け取ります。
細かい点:
- 変換はテクセル毎に、フィルタリングの前に行う事になっています。バイリニアで読む4つのテクセルを先にデコードしてから平均するので、正しい順番です。(仕様はフィルタリングの後のデコードも許していますが、勧めてはおらず、今のGPUは先にデコードします。)
- アルファは変換されません。
GL_SRGB8_ALPHA8で符号化されているのはRGBだけで、アルファは線型の覆う割合です。GL_SRGB8はアルファの無い同じ形式です。 - ミップマップ。 sRGBテクスチャの
glGenerateTextureMipmapは、仕様に沿ったドライバーでは線型空間で平均します(Mesaはそうします)。符号化された値を平均すると、縮小したテクスチャが暗くなります。 - 読み戻し。
glGetTextureImageは線型の値ではなく、保存された符号化済みのバイトを返します。sRGBテクスチャの生のバイトをサンプリングしたい時は、glTextureViewで同じストレージのGL_RGBA8のビューをもう1つ作れます。
TextureOptionsには第6章からsrgbフラグがあり、Texture2D::fromPixelsは既に其れで形式を選んでいます。
ヘッダーで変わったのはコメントだけです:
struct TextureOptions {
bool flipY = true; // 画像は上から、OpenGLのUVは下から / images start at the top, OpenGL UVs at the bottom
bool mipmaps = true; // ミップマップを作る / build mipmaps
// 色の画像(ベースカラー、発光)はtrue:GL_SRGB8_ALPHA8になり、読むときにGPUがリニアに直す(第21章)。
// データ(法線、金属・粗さ、遮蔽、高さ)はfalseのまま:値そのものに意味がある
// true for colour images (base colour, emission): the texture becomes GL_SRGB8_ALPHA8 and the GPU converts to
// linear when sampling (chapter 21). Keep false for data (normals, metallic-roughness, occlusion, height): the
// values themselves mean something
bool srgb = false;
// RGBにアルファを掛けてからアップロードする(乗算済みアルファ、第16章)。ミップマップもその値から作られる。
// Multiply RGB by alpha before uploading (premultiplied alpha, chapter 16). Mipmaps are then built from those values.
// srgbなら、リニアに直してから掛けてsRGBに戻す(第21章) / with srgb the colour is converted to linear, multiplied and
// converted back to sRGB (chapter 21)
bool premultiplyAlpha = false;
};
どの画像が色か
規則は簡単に言えて、間違えるのも簡単です。色を表す画像だけがsRGBです。
床、草の葉、木箱の木目、ベースカラー又は発光のテクスチャは、誰かが描いたり撮影したりした絵なのでsRGBです。
法線マップ、金属度・粗さのマップ、遮蔽のマップ、高さのマップ、ルックアップテーブルはデータです。
数字は向きや割合や距離を意味していて、変えずにシェーダーに届かなければなりません。
逆にすると何が起こるか見てみましょう。
平らな法線マップは「傾き無し」として128を保存します。で、、殆ど丁度0です。
sRGBとしてアップロードすると、サンプラーは0.502を0.216にデコードし、シェーダーはを計算します。
全ての法線が大きく傾き、エラーメッセージ無しに全体のライティングが間違います。
128として保存された粗さ0.5も同じく0.216として届き、ずっとつやつやした表面になります。
main.ccでは、2つの画像ファイルと空が色です:
// 色の画像はsRGB(第21章):GPUが読むときにリニアに直す / colour images are sRGB (chapter 21): the GPU converts them
// to linear when sampling
std::optional<Cubemap> sky = Cubemap::loadDirectory("assets/textures/sky", ".png", true);
std::optional<Texture2D> floorTexture = Texture2D::load("assets/textures/floor.png", {.srgb = true});
std::optional<Texture2D> grassTexture = Texture2D::load("assets/textures/grass_blades.png", {.srgb = true});
Cubemapにも同じオプションが付きました。
両方の関数の最後の普通のboolで、既定値はfalseなので、古い呼び出しは意味が変わりません:
// srgb = true:色の画像なのでGL_SRGB8_ALPHA8にする(第21章。空はtrue) / srgb = true: a colour image, stored as
// GL_SRGB8_ALPHA8 (chapter 21; true for skies)
static std::optional<Cubemap> load(const std::array<std::string, 6> &paths, bool srgb = false);
// dir/px.png, dir/nx.png … を読む / loads dir/px.png, dir/nx.png, ...
static std::optional<Cubemap> loadDirectory(const std::string &dir, const std::string &extension = ".png",
bool srgb = false);
Cubemap::loadの中で変わるのはストレージの形式だけです:
if (face == 0) {
int levels = 1;
while ((width >> levels) > 0) ++levels;
cube = Cubemap(width, srgb ? GL_SRGB8_ALPHA8 : GL_RGBA8, levels);
}
glTFのテクスチャ
モデルでは、どれがどれかはファイルが教えてくれます。
glTF 2.0は、ベースカラーと発光のテクスチャをsRGB、其れ以外の全て(金属度・粗さ、法線、遮蔽)を線型と決めています。
glTFの1つのテクスチャは幾つものマテリアルから使われる事があるので、Model::loadは先に各テクスチャの使われ方を数えます:
// どのテクスチャが色か(第21章):ベースカラーと発光はsRGB、ほかはデータなのでリニア(glTFの仕様どおり)
// Which textures hold colours (chapter 21): base colour and emissive are sRGB, the rest is data and linear (as the
// glTF spec says)
std::vector<int> colorUse(g.textures.size(), 0), dataUse(g.textures.size(), 0);
auto mark = [](std::vector<int> &use, const GltfTextureRef &ref) {
if (ref.index >= 0 && static_cast<size_t>(ref.index) < use.size()) ++use[static_cast<size_t>(ref.index)];
};
for (const GltfMaterial &m : g.materials) {
mark(colorUse, m.baseColorTexture);
mark(colorUse, m.emissiveTexture);
mark(dataUse, m.metallicRoughnessTexture);
mark(dataUse, m.normalTexture);
mark(dataUse, m.occlusionTexture);
}
そしてアップロードする時にテクスチャ毎に決めます:
// 同じテクスチャを色とデータの両方に使うファイルもありうる:その場合はリニアにして警告する
// A file may use the same texture both as a colour and as data: then it stays linear, with a warning
bool srgb = colorUse[i] > 0 && dataUse[i] == 0;
if (colorUse[i] > 0 && dataUse[i] > 0)
fprintf(stderr, "%s: textures[%zu] は色にもデータにも使われている:リニアで読む / is used both as colour and as data: "
"loaded as linear\n", path.c_str(), i);
Texture2D texture = Texture2D::fromPixels(image->rgba.data(), image->width, image->height,
{.flipY = false, .mipmaps = true, .srgb = srgb});
色にもデータにも使われるテクスチャは、厳密に言えば壊れたファイルです(OpenGLの1つのテクスチャの形式は1つです)。
其の為警告を出して線型のままにします。
代わりに同じ画像から2つのテクスチャを作る事も出来ますが、其のコードを書く程の価値は無いと思いました。
第14章のBlinn-Phongの近似は金属度・粗さのテクスチャをCPUで平均しますが、今でも生のバイトを平均しています。
其のテクスチャは線型なので、其れで正しいです。
乗算済みアルファを線型空間で
第16章で、乗算済みアルファにもう一度戻ると約束しました。
premultiplyAlphaはアップロードの前に各色にアルファを掛けますが、今迄は保存された値に掛けていました。
sRGBテクスチャでは其れは符号化された値で、符号化された値を掛けるのは光を掛けるのと同じではありません。
両方のオプションがオンの時、fromPixelsはデコードし、掛け、もう一度エンコードする様になりました:
// sRGBの8ビット値 → リニア(0〜1)。IEC 61966-2-1の式(2.2乗に近いが、暗いところは直線)
// An sRGB 8-bit value → linear (0..1). The IEC 61966-2-1 formula (close to a 2.2 power, a straight line near black)
static float srgbToLinear(unsigned char v) {
float c = static_cast<float>(v) / 255.0f;
return c <= 0.04045f ? c / 12.92f : std::pow((c + 0.055f) / 1.055f, 2.4f);
}
static unsigned char linearToSrgb(float c) {
float s = c <= 0.0031308f ? c * 12.92f : 1.055f * std::pow(c, 1.0f / 2.4f) - 0.055f;
return static_cast<unsigned char>(s * 255.0f + 0.5f);
}
Texture2D Texture2D::fromPixels(const unsigned char *rgba, int width, int height, const TextureOptions &options) {
int levels = options.mipmaps ? mipLevelCount(width, height) : 1;
Texture2D texture(width, height, options.srgb ? GL_SRGB8_ALPHA8 : GL_RGBA8, levels);
if (options.premultiplyAlpha) {
// 乗算済みアルファ:色 × アルファ。透明なピクセルの色は(何色でも)0になる
// premultiplied alpha: colour × alpha. Transparent pixels become 0 whatever colour they had
std::vector<unsigned char> pm(rgba, rgba + static_cast<size_t>(width) * static_cast<size_t>(height) * 4);
// sRGBの値にそのまま掛けると、暗い縁が暗くなりすぎる:リニアで掛ける / multiplying the sRGB-encoded values directly
// makes dark edges too dark: multiply in linear space
float table[256];
for (int v = 0; v < 256; ++v) table[v] = srgbToLinear(static_cast<unsigned char>(v));
for (size_t i = 0; i < pm.size(); i += 4)
for (size_t c = 0; c < 3; ++c) {
if (options.srgb) pm[i + c] = linearToSrgb(table[pm[i + c]] * static_cast<float>(pm[i + 3]) / 255.0f);
else pm[i + c] = static_cast<unsigned char>((pm[i + c] * pm[i + 3] + 127) / 255);
}
texture.upload(pm.data());
} else {
texture.upload(rgba);
}
if (options.mipmaps) texture.generateMipmaps();
return texture;
}
256要素の表は、全てのピクセルの全てのチャンネルでstd::powを呼ばない為の物です。入力は256通りしかありません。
違いを見る為に、値200、アルファ128の半透明の縁のピクセルを考えます:
- 古いやり方:(整数の割り算)。サンプラーは100を0.127にデコードします。
- 新しいやり方:200は0.578にデコードされ、を掛けると0.290で、其れは147にエンコードされます。此れが欲しい物、不透明なピクセルの半分の光です。
古い結果は本来の半分より少ない光しか無く、其の為乗算済みの縁は暗い輪郭がある様に見えていました。
線型のテクスチャ(srgb = false)は古い整数の式のままです。其方では其れで既に正しいからです。
21.4 コードとglTFファイルの中の色
手で選んだ色
全ての色が画像から来る訳ではありません。
柵の木と電線の色は、第20章であたしが画面で気に入った数字を打ち込んだ物です。
目で選んだ値、カラーピッカーや画像編集ソフトの値もsRGBの値なので、手順1が必要です。
mathx.hhにfloatとVec3用に同じ式が加わります:
// sRGBの色(カラーピッカーや画像編集ソフトの値、0〜1)→ リニア(第21章)。シェーダーの計算はリニアで行う
// An sRGB colour (the values of colour pickers and image editors, 0..1) → linear (chapter 21). Shaders compute in
// linear space
inline float srgbToLinear(float c) { return c <= 0.04045f ? c / 12.92f : std::pow((c + 0.055f) / 1.055f, 2.4f); }
inline Vec3 srgbToLinear(Vec3 c) { return {srgbToLinear(c.x), srgbToLinear(c.y), srgbToLinear(c.z)}; }
そしてmain.ccはマテリアルを作る時に1回だけ、選んだ色を変換します:
Material woodMaterial;
// 手で選んだ色はsRGBの値(カラーピッカーの値):シェーダーはリニアで計算するので変換する
// Hand-picked colours are sRGB values (what a colour picker shows): the shaders compute in linear space, so convert
woodMaterial.diffuse = srgbToLinear(Vec3{0.42f, 0.3f, 0.2f});
woodMaterial.specular = {0.05f, 0.05f, 0.05f};
woodMaterial.shininess = 8.0f;
Material wireMaterial;
wireMaterial.diffuse = srgbToLinear(Vec3{0.04f, 0.04f, 0.045f});
wireMaterial.specular = {0.3f, 0.3f, 0.3f};
wireMaterial.shininess = 32.0f;
木の色は線型の光でになります。
驚く程小さな数字に見えますが、同じ茶色です。フレームを画面用にエンコードすれば、は又0.42として出て来ます。
鏡面反射の強さと光の色は其のままです。
其れらは誰かが画面で選んだ色ではなく、物理的な量(「どれだけの光か」)で、定義からして線型です。
訂正:glTFの係数が間違っていた
glTFにも同じ区別があり、仕様ははっきりしています。テクスチャはsRGBですが、baseColorFactorとemissiveFactorは線型です。
第13章でdiorama.glb、あたしが目で選んだ色を其のまま係数に書いていました。
此れは間違いで、8章の間見えませんでした。
何処でもガンマを無視するレンダラーでは、ピッカーの値を線型の様に使っても、画面には選んだ通りに出るからです。
正しいパイプラインでは同じ数字が線型の光として扱われてもう一度エンコードされるので、全ての係数が意図よりずっと淡く出ます。
此の章から、プロジェクトには作り直したジオラマが入っています。
選んだ色を全て書き込む前にsRGBの式で変換します。
例えば漆喰の0.86は0.71に、葉のはになります。
第13〜20章のスナップショットには元の儘のファイルが入っています。
crate.glbは作り直す必要がありませんでした。係数が全て1で、1はどちらの符号化でも1だからです。
比べると、何故わざわざ書くのかが分かります:
左は第20章です。間違っていますが、一貫して間違っていて、光は其れに合わせて調整してありました。
真ん中は、全てのsrgbをfalseにして古いジオラマを使った、此の章の一時的なビルドです。
最後のエンコードがデコードされていない値を明るくし、場面が白っぽくなります。
半分だけのガンマパイプラインの典型的な症状です。
右では、全てが1回デコードされ、1回エンコードされています。
他のツールで作ったGLBファイルを持っているなら、何もする必要はありません。Blenderの物等のエクスポーターは、仕様通りに線型の係数を書きます。
21.5 画面の為のエンコード
手順3の2つのやり方
フレームの最後に、線型の結果をエンコードしなければなりません。
OpenGLには2つのやり方があります:
- シェーダーで。 ポストプロセスのパスが
linearToSrgb関数を呼び、エンコード済みの値を普通のフレームバッファに書きます。 - ハードウェアで。
glEnable(GL_FRAMEBUFFER_SRGB)にすると、GPUがシェーダーの出力を書く時にエンコードします。但し、色の付け先がsRGBで符号化されたフレームバッファの時だけです。ブレンドがオンなら、書く先を先にデコードし、線型空間でブレンドしてから結果をエンコードします。
どちらでも良く、両方やるのが典型的な間違いです。
2つ目のやり方がウィンドウで使えるかどうかは既定のフレームバッファ次第で、其れはあたし達の物ではなく、ウィンドウシステムとドライバーが作ります。
何を貰ったかは聞く事が出来ます:
// 画面(既定のフレームバッファ)がsRGBか:GL_FRAMEBUFFER_SRGBが効くのはsRGBのときだけ
// Is the screen (the default framebuffer) sRGB? GL_FRAMEBUFFER_SRGB only has an effect if it is
GLint encoding = 0;
glGetNamedFramebufferAttachmentParameteriv(0, GL_BACK_LEFT, GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING, &encoding);
printf("default framebuffer encoding: %s\n", encoding == GL_SRGB ? "sRGB" : "linear");
glGetNamedFramebufferAttachmentParameteriv(framebuffer, attachment, pname, params)は、フレームバッファの1つの付け先について聞きます。
フレームバッファ0は既定のフレームバッファで、其の付け先はGL_COLOR_ATTACHMENT0ではなくバッファの名前で指定します。
GL_BACK_LEFTはあたし達が描く後ろのバッファで、GL_FRONT_LEFT、GL_DEPTH、GL_STENCILもあります。
GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODINGはGL_SRGB又はGL_LINEARを返します。
あたしのテスト用のマシンでは、プログラムは次の様に表示します:
default framebuffer encoding: sRGB
此のシリーズが何故シェーダーでエンコードするのか
あたしのテスト用のマシンではGL_FRAMEBUFFER_SRGBが効きます。
其れでもpost.fragでエンコードするのには、3つの理由があります:
- 既定のフレームバッファがsRGBに対応している保証は無く、特にLinuxのデスクトップでは対応していない事が良くあります。GLFWには其の為のウィンドウのヒント
GLFW_SRGB_CAPABLEがありますが、ヒントでしかありません。システムが其の様なフレームバッファを用意出来なければ線型の物が来て、glEnable(GL_FRAMEBUFFER_SRGB)は黙って何もしません。すると絵が暗過ぎて、しかも一部のマシンだけです。Windowsでは逆の驚きがあり、頼まなくてもsRGB対応のフレームバッファをくれるドライバーもあります。シェーダーでエンコードすれば、何処でも同じ絵になります。 - エンコード済みの値が欲しい効果がある。 第17章のグレースケールとエッジ検出、FXAA風のフィルター、ディザリング、UIは、全て目に見える物に近い値で一番上手く働きます。シェーダーでエンコードすれば、其の直後の同じパスで其れらを実行出来ます。
- 見る場所が1つ。 HDRから最後の8ビット迄、色のパイプライン全体が1つの関数
display()(21.11節)にあるので、うっかり二重にエンコードする間違いが起き難くなります。
エンコードは21.2節の正確な曲線で、分岐無しで書いてあります:
// リニア → sRGB(IEC 61966-2-1)。おおよそ pow(c, 1/2.2) / linear → sRGB, roughly pow(c, 1/2.2)
vec3 linearToSrgb(vec3 c) {
return mix(c * 12.92, 1.055 * pow(c, vec3(1.0 / 2.4)) - 0.055, step(vec3(0.0031308), c));
}
step(edge, x)は成分毎にx < edgeの所で0、其れ以外で1なので、mixは境界より下では直線の部分を、上では累乗の部分を選びます(GLSLの章と同じ技です)。
両方の部分を全てのピクセルで計算しますが、其れで構いません。
入力は既に0〜1にトーンマッピングされている(21.8節)ので、powが負の数を受け取る事はありません。
Gキー:4つの組み合わせ全て
此の決定を目で見られる様に、post.fragは後処理のブロック(21.10節)からuGammaModeを読み、main.ccは必要なモードの時だけ、最後の描画の前後でGL_FRAMEBUFFER_SRGBをオンにします:
Framebuffer::bindDefault(window.width(), window.height());
// GammaMode 1と3:GPUが書くときにリニア→sRGBにする(画面がsRGBのときだけ効く)
// Gamma modes 1 and 3: the GPU converts linear → sRGB on write (only works if the screen is sRGB)
bool framebufferSrgb = postSettings.gammaMode == static_cast<int>(GammaMode::FramebufferSrgb) ||
postSettings.gammaMode == static_cast<int>(GammaMode::Double);
if (framebufferSrgb) glEnable(GL_FRAMEBUFFER_SRGB);
post->use();
post->set("uEffect", effect);
post->set("uFlipX", 0);
sceneFbo.color(0).bind(0);
bloomFbo[1].color().bind(1); // 最後の縦のパスの結果 / the result of the last vertical pass
sceneFbo.color(1).bind(2);
fullscreen.draw();
glDisable(GL_FRAMEBUFFER_SRGB);
モードはuniforms.hhの列挙型で、シェーダーと同じ番号です:
enum class GammaMode {
Shader = 0, // post.fragで変換(このシリーズの選択) / encoded in post.frag (the series' choice)
FramebufferSrgb = 1, // glEnable(GL_FRAMEBUFFER_SRGB):GPUが書くときに変換 / the GPU encodes on write
None = 2, // 変換なし(間違い:暗すぎる) / no encoding (wrong: too dark)
Double = 3, // 両方(間違い:白っぽい) / both (wrong: washed out)
};
最初の2つのモードを、全体の大きさのフレームでピクセル毎に比べました。
255の内1より大きく違うチャンネルは1つも無く、少しでも違う値は8%だけです。
其れは丸めの違いです。シェーダーはエンコードした値をfloatで書いてフレームバッファが8ビットに丸め、ハードウェアの方は線型の値を自分の丸めでエンコードします。
エンコード無しは暗過ぎてコントラストが強過ぎます。第20章を線型のライティングで描いたら、丁度此の様に見えたはずです。
最後の絵は二重にエンコードした時の白っぽさで、実際に良くある間違いの形です。
モード3ではpost.fragがモード0と同じ行で1回エンコードし(21.11節で見ます)、其の上でmain.ccがGL_FRAMEBUFFER_SRGBもオンにするので、エンコード済みの値をハードウェアがもう1回エンコードします。
sRGBに対応したあたしのテスト用のマシンでピクセルを確かめたところ、2回のエンコードと一致しました。
線型の既定のフレームバッファではGL_FRAMEBUFFER_SRGBは何もしないので、モード3はモード0と、モード1はモード2と全く同じに見えます。
つまり此のバグは、sRGBに対応した画面のマシンで動かす迄隠れています。
何れにせよ、2つの見た目を覚えておいて下さい。暗過ぎるなら誰もエンコードしていない、白っぽいなら誰かがエンコードし過ぎています。
GL_FRAMEBUFFER_SRGBはGL_BLENDと同じくグローバルな状態です。
あたし達の浮動小数点のフレームバッファは其れを無視します(影響を受けるのはsRGBの付け先だけです)。
然し、余計なglEnableが残っていると、後で加えるGL_SRGB8_ALPHA8の描画先への書き込みもエンコードしてしまうので、プログラムは其れが必要な描画の直後にオフにします。
21.6 HDR:浮動小数点のフレームバッファ
何故0〜1では足りないのか
光は足し合わされ、線型の光では合計が大きくなります。
風車の漆喰の壁の上の方は、になる角度で太陽を向いています(太陽は長さ1.1715のの向きに進みます)。
此の章の太陽、環境光、漆喰の線型の色で、赤のチャンネルは
で、色全体は鏡面反射の光の前でです。
8ビットのフレームバッファは3つのチャンネル全てを1に切ります。壁は平らな白になり、陰影が消え、色も失われます。
提灯はもっと酷いです。発光は色の6倍で、此れから加える太陽の円盤は白の百倍以上明るいです。
直し方は、場面をそういう値を持てる形式で保存し、どう見せるかは最後に決める事です。
半精度浮動小数点:GL_RGBA16F
GL_RGBA16Fはピクセル毎に4つの半精度浮動小数点数、合計8バイトを保存します。
半精度浮動小数点数は符号1ビット、指数5ビット、仮数10ビットです:
- 一番大きな値はで、どんな場面にも十分過ぎます。
- 精度は相対的です。1段階は値が0.01でも1000でも其の値のです。物差しのミリより写真の段に近く、光にとても合っています。8ビットにエンコードした後では、0.1%は1段階の約で、見えません。
- 負の値も使えます(シャープの様に負の重みを持つカーネルは其れを作る事があります)。
- 浮動小数点の色のバッファに書いた値は切られません。其れが肝心な所です。
GL_RGBA8ではGPUがシェーダーの出力を0〜1に切ります。
Framebufferクラスは第17章からどんな色の形式も受け付けるので、main.ccのフレームバッファは其れを頼むだけです:
// HDRのフレームバッファ(第21章):色はGL_RGBA16F(1より明るい値も負の値も持てる半精度の浮動小数点)。
// 付け先0 = 場面の色、付け先1 = ブルームにする明るい部分(MRT)。MSAA(第20章)で描いて sceneFbo に解決する
// HDR framebuffers (chapter 21): the colour is GL_RGBA16F (half floats that can hold values above 1, and negative
// ones). Attachment 0 = the scene colour, attachment 1 = the bright part for bloom (MRT). Drawn with MSAA
// (chapter 20) and resolved into sceneFbo
const FramebufferSpec hdrSpec = {.colorFormat = GL_RGBA16F, .colorCount = 2};
FramebufferSpec msaaSpec = hdrSpec;
msaaSpec.samples = kMsaaSamples;
Framebuffer msaaFbo(window.width(), window.height(), msaaSpec);
Framebuffer sceneFbo(window.width(), window.height(), hdrSpec);
// ブルームのぼかしは半分の大きさで(4分の1のピクセル数:速く、広くぼける)。深度は要らない
// The bloom blur runs at half size (a quarter of the pixels: faster, and it spreads further). No depth needed
const FramebufferSpec bloomSpec = {.colorFormat = GL_RGBA16F, .depthStencilFormat = 0};
Framebuffer bloomFbo[2] = {Framebuffer(window.width() / 2, window.height() / 2, bloomSpec),
Framebuffer(window.width() / 2, window.height() / 2, bloomSpec)};
if (!msaaFbo.complete() || !sceneFbo.complete() || !bloomFbo[0].complete()) return 1;
window.onResize = [&](int width, int height) {
msaaFbo.resize(width, height);
sceneFbo.resize(width, height);
for (Framebuffer &f : bloomFbo) f.resize(width / 2, height / 2);
};
colorCountは新しく、次の節の話題です。
msaaFboは第20章の4× MSAAのままです。MSAAは浮動小数点の形式でもGL_RGBA8と全く同じ様に働き、解決では浮動小数点のサンプルを平均します。
2つのbloomFboはぼかしのパスが全画面の三角形を描くだけなので、深度の付け先がありません。
明るい光、明るい提灯
HDRでは光は必要なだけ明るくして良いです。
第20章の光は何も酷く切れない様に調整していましたが、今は現実に近くなり、太陽は空の環境光の約10倍明るいです(輝度で比べると):
// HDRなので光は1より明るくて良い:真昼の太陽は環境光の何倍も明るい
// With HDR, lights may be brighter than 1: the midday sun is many times brighter than the ambient light
LightSet lights;
if (!night) {
lights.ambient = {0.20f, 0.24f, 0.33f};
lights.directional = {.direction = {-0.5f, -1.0f, -0.35f}, .color = {2.6f, 2.45f, 2.2f}};
} else {
lights.ambient = {0.012f, 0.015f, 0.025f};
lights.directional = {.direction = {-0.4f, -1.0f, -0.6f}, .color = {0.05f, 0.07f, 0.12f}};
提灯は暗い紙のマテリアルと強い発光を持つ球で、発光は色のkLanternGlow = 6倍です:
// 電線に吊るした提灯:発光する球。位置と色 / paper lanterns hanging from the wires: emissive spheres, position + colour
struct Lantern {
Vec3 position;
Vec3 color;
};
static std::vector<Lantern> makeLanterns() {
std::vector<Lantern> lanterns;
const Vec3 poles[] = {{-9.0f, 0.0f, -3.0f}, {-3.0f, 0.0f, -5.5f}, {4.0f, 0.0f, -5.0f}, {10.0f, 0.0f, -2.0f}};
const Vec3 colors[] = {{1.0f, 0.45f, 0.12f}, {1.0f, 0.2f, 0.1f}, {1.0f, 0.75f, 0.3f}};
int k = 0;
for (size_t i = 0; i + 1 < std::size(poles); ++i) {
Vec3 from = poles[i] + Vec3{0.0f, 4.04f, 0.0f}, to = poles[i + 1] + Vec3{0.0f, 4.04f, 0.0f};
for (float t : {0.25f, 0.5f, 0.75f}) {
Vec3 p = lerp(from, to, t) - Vec3{0.0f, 1.6f * t * (1.0f - t) + 0.25f, 0.0f}; // 電線の下 / under the wire
lanterns.push_back({p, colors[k++ % 3]});
}
}
return lanterns;
}
各区間の真ん中の電線の25 cm下に吊るしてあり、其の電線は第20章と同じ放物線でたるんでいます。
drawSceneでは他の物と同じ様にphongで描きます:
Material lanternMaterial;
lanternMaterial.diffuse = {0.05f, 0.03f, 0.02f};
lanternMaterial.specular = {0.02f, 0.02f, 0.02f};
for (const Lantern &l : lanterns) {
lanternMaterial.emission = kLanternGlow * l.color;
lanternMaterial.apply(*phong, white);
Mat4 model = translate(l.position) * scale({0.3f, 0.38f, 0.3f});
phong->set("uModel", model);
phong->set("uNormalMatrix", normalMatrix(model));
sphereMesh.draw();
}
オレンジの提灯の発光はです。
第20章なら其れはに切られて淡い黄色になっていましたが、HDRでは色が残り、どう見えるかはトーンマッパーが決めます。
夜には、真ん中の区間の3つの提灯が点光源にもなり(色の1.5 *)、下の木箱を照らします。残りの6つは光るだけです。
スカイボックスのHDRの太陽
第18章の空の面は8ビットの画像なので、其の太陽の円盤は1で切れていて、白い雲より明るくありません。
空を浮動小数点の画像で作り直す代わりに、skybox.fragはLightsブロック(結合点1、phong.fragと同じ宣言)を読み、平行光源が来る丁度其の方向に明るい太陽を描き足します:
uniform float uSunRadiance = 60.0; // 太陽の円盤の明るさ(平行光源の色の倍数、第21章) / the sun disc's brightness
// (a multiple of the directional light's colour, chapter 21)
void main() {
vec3 d = normalize(vDirection);
// 空の画像はLDR(sRGB、最大1):太陽の円盤も1で切れている。HDRの太陽を光の向きに描き足す
// The sky images are LDR (sRGB, at most 1): even the sun disc is clipped at 1. Add an HDR sun in the light's direction
vec3 color = uEnvironmentTint * texture(uSkybox, d).rgb;
float c = dot(d, -uDirLight.direction);
float disc = smoothstep(cos(radians(1.6)), cos(radians(1.2)), c);
float glow = 0.02 * exp((c - 1.0) * 300.0);
color += uDirLight.color * (uSunRadiance * disc + uSunRadiance * glow);
out_color = vec4(color, 1.0);
out_bright = vec4(brightPart(color), 1.0);
}
cは見ている方向と太陽へ向かう方向の間の角度のコサインです。
1.6°と1.2°のコサインの間のsmoothstepで、縁が柔らかい円盤になります。
本物の太陽の半径は約0.27°しかありませんが、小さなウィンドウでは大きな円盤の方が良く見えます。
円盤の中の太陽はで、見える太陽と場面を照らす光が結び付いています。太陽の色を変えれば円盤も付いて来ます。
光の輪は角度と共に弱くなります。中心ではを足し、5°では約、10°ではだけです。
空の面は21.3節のsRGBのキューブマップから読むので、青は線型の光として届きます。
夜には同じコードが月明かりの方向に「月」を描き、明るさは月の光の色の60倍です。
out_brightは2つ目の出力で、其れが次の話です。
21.7 2つの出力を同時に:マルチレンダーターゲット
明るい部分
ブルーム(21.11節)には、しきい値より明るい物全ての画像が必要です。
場面を読む別のパスで計算する事も出来ますが、もっと安い方法があります。
フラグメントシェーダーは全てのピクセルの最終的な色を既に知っているので、明るい部分を同時に、2つ目の色の付け先に書けます。
此れをマルチレンダーターゲット(MRT)と言います。
GLSL側では、2つ目の出力にlayout(location = 1)を付けます:
// ブルーム用の2つ目の出力(MRT、GL_COLOR_ATTACHMENT1):しきい値より明るい部分だけ(色合いは保つ)
// The second output for bloom (MRT, GL_COLOR_ATTACHMENT1): only what is brighter than the threshold (hue kept)
layout(location = 1) out vec4 out_bright;
vec3 brightPart(vec3 c) {
float l = dot(c, vec3(0.2126, 0.7152, 0.0722)); // 輝度 / luminance
return c * (max(l - uBloomThreshold, 0.0) / max(l, 1e-4));
}
brightPartはRec. 709の重みで輝度を計算し(第17章のグレースケールと同じく緑が一番効きます)、がしきい値をどれだけ超えているかで色全体を拡大縮小します:
ベクトル全体を拡大縮小するので色合いが保たれ、オレンジの提灯はオレンジに光ります。
そして係数は丁度しきい値で0から始まるので、光はぱっと点くのではなく柔らかく現れます。
オレンジの提灯では、なら係数はで、明るい部分はです。
21.6節の漆喰の壁はで、色の34%だけを加えるので、日の当たる白い面も少し光ります。カメラのレンズも同じ事をします。
max(l, 1e-4)は黒いピクセルで0で割らない為です。
phong.fragの最後で両方の出力を書きます:
out_color = vec4(color, uMaterial.alphaMode == ALPHA_BLEND || coverage ? clamp(alpha, 0.0, 1.0) : 1.0);
// デバッグ表示(uViewMode > 0)は光らせない / debug views do not glow
out_bright = vec4(uViewMode == 0 ? brightPart(color) : vec3(0.0), out_color.a);
明るい出力も同じアルファを使うので、透明な物は2つの付け先に同じ様にブレンドされます。
skybox.frag、unlit.frag、envmap.fragにも同じ行が入りました。
此れは親切ではなく規則です。複数の付け先を持つフレームバッファに描くシェーダーは、全ての出力を書かなければなりません。
シェーダーがlocation = 1を書かなければ、其のシェーダーが描いた所の付け先1の中身は未定義で、あるドライバーでは前のフレームの光が、別のドライバーではゴミが見えます。
付け先と描画バッファ
C++側では、FramebufferSpecに数が加わります:
// フレームバッファに何を付けるか / what to attach to a framebuffer
struct FramebufferSpec {
// 色のテクスチャの形式(0 = 色なし)。HDRではGL_RGBA16F(第21章)
// The colour texture's format (0 = no colour). GL_RGBA16F for HDR (chapter 21)
GLenum colorFormat = GL_RGBA8;
// 色の付け先の数(MRT、第21章):GL_COLOR_ATTACHMENT0〜。全部colorFormat。シェーダーは
// layout(location = i) out … でi番目に書く(最大kMaxColorAttachments)
// The number of colour attachments (MRT, chapter 21): GL_COLOR_ATTACHMENT0... All use colorFormat. A shader writes
// the i-th one with layout(location = i) out ... (at most kMaxColorAttachments)
int colorCount = 1;
// 深度・ステンシルのレンダーバッファの形式(0 = なし)。サンプラーで読まないのでテクスチャでなくて良い
// The depth-stencil renderbuffer's format (0 = none). It is never sampled, so it need not be a texture
GLenum depthStencilFormat = GL_DEPTH24_STENCIL8;
// マルチサンプル(MSAA、第20章):1ピクセルあたりのサンプル数。0 = 普通のフレームバッファ(色はテクスチャ)。
// 1以上なら色も深度もマルチサンプルのレンダーバッファになり、サンプラーでは読めない:blitToで普通の
// フレームバッファに解決(resolve)してから使う。ドライバーは要求以上の数を選ぶことがある(samples()で確かめる)。
// Multisampling (MSAA, chapter 20): samples per pixel. 0 = an ordinary framebuffer (the colour is a texture).
// 1 or more makes both colour and depth multisampled renderbuffers, which cannot be sampled: resolve them into
// an ordinary framebuffer with blitTo first. The driver may pick more samples than requested (check samples()).
int samples = 0;
};
新しいメンバーはcolorFormatの直後にあるので、{.colorFormat = GL_RGBA16F, .colorCount = 2}の様な指示付き初期化子が自然に読めます(C++では宣言の順番で書かなければなりません)。
全ての付け先が1つの形式を共有します。必要なのは其れだけで、クラスも小さく保てます。
1つだった色のテクスチャとレンダーバッファは、決まった最大数の配列になりました:
constexpr int kMaxColorAttachments = 4; // GLは最低8を保証する / GL guarantees at least 8
// マルチサンプルの色のレンダーバッファ(第20章) / multisampled colour renderbuffers (chapter 20)
std::array<GLuint, kMaxColorAttachments> colorSamples = {};
std::array<Texture2D, kMaxColorAttachments> colorTextures;
そしてcolor()は番号を取ります。既定値は0なので、今ある全ての呼び出しは「最初の付け先」の意味のままです:
// 描いた結果。シェーダーでサンプリングできる(マルチサンプルなら空:id() == 0)
// The result; can be sampled in a shader (empty for a multisampled framebuffer: id() == 0)
// index = 何番目の色の付け先か(MRT) / index = which colour attachment (MRT)
const Texture2D &color(int index = 0) const { return colorTextures[static_cast<size_t>(index)]; }
Texture2D &color(int index = 0) { return colorTextures[static_cast<size_t>(index)]; }
int colorCount() const { return spec.colorFormat != 0 ? spec.colorCount : 0; }
createAttachmentsは付け先をループで作り、其の後で出力の行き先をOpenGLに教えます:
void Framebuffer::createAttachments() {
actualSamples = 0;
int count = colorCount();
if (count > kMaxColorAttachments) {
fprintf(stderr, "色の付け先が多すぎる / too many colour attachments: %d (max %d)\n", count, kMaxColorAttachments);
count = spec.colorCount = kMaxColorAttachments;
}
GLenum drawBuffers[kMaxColorAttachments];
for (int i = 0; i < count; ++i) {
GLenum attachment = GL_COLOR_ATTACHMENT0 + static_cast<GLenum>(i);
drawBuffers[i] = attachment;
if (spec.samples > 0) {
// マルチサンプルの色:ピクセルごとにsamples個の色を持つレンダーバッファ。テクスチャのように読めない
// Multisampled colour: a renderbuffer with `samples` colours per pixel. It cannot be read like a texture
GLuint &rb = colorSamples[static_cast<size_t>(i)];
glCreateRenderbuffers(1, &rb);
glNamedRenderbufferStorageMultisample(rb, spec.samples, spec.colorFormat, w, h);
glNamedFramebufferRenderbuffer(fbo, attachment, GL_RENDERBUFFER, rb);
// ドライバーは要求以上で一番近い数を選ぶ(llvmpipeは4だけ:2を頼んでも4になる)
// The driver picks the nearest supported count at or above the request (llvmpipe has only 4: asking for 2 gives 4)
glGetNamedRenderbufferParameteriv(rb, GL_RENDERBUFFER_SAMPLES, &actualSamples);
} else {
// 色:ミップマップなしのテクスチャ。端の外を読まないようにCLAMP_TO_EDGE(ぼかしのカーネルが端で反対側を拾わない)
// Colour: a texture without mipmaps. CLAMP_TO_EDGE so blur kernels at the border do not pick up the opposite side
Texture2D &t = colorTextures[static_cast<size_t>(i)];
t = Texture2D(w, h, spec.colorFormat, 1);
t.setWrap(GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE);
t.setFilter(GL_LINEAR, GL_LINEAR);
glNamedFramebufferTexture(fbo, attachment, t.id(), 0); // 0 = ミップマップの段 / mip level
}
}
if (count > 0) {
// フラグメントシェーダーの出力location iを、i番目の付け先に書く(既定ではATTACHMENT0だけ)
// Fragment output location i goes to attachment i (by default only ATTACHMENT0 is written)
glNamedFramebufferDrawBuffers(fbo, count, drawBuffers);
} else {
// 色を描かない(例:影の深度だけ、第23章) / no colour drawn (e.g. shadow depth only, chapter 23)
glNamedFramebufferDrawBuffer(fbo, GL_NONE);
glNamedFramebufferReadBuffer(fbo, GL_NONE);
}
GL_COLOR_ATTACHMENT1にテクスチャを付けるだけでは足りません。
シェーダーの出力と付け先の間には、フレームバッファの描画バッファのリストがあり、新しいフレームバッファには1つしか入っていません。
出力0はGL_COLOR_ATTACHMENT0へ行き、其れ以外の出力は何処にも行きません。
glNamedFramebufferDrawBuffers(framebuffer, n, bufs)はリスト全体を設定します。フラグメントの出力のロケーションiはbufs[i]に書かれます。各要素はGL_COLOR_ATTACHMENTi又はGL_NONEで、nは最大GL_MAX_DRAW_BUFFERS(最低8)です。あたし達は分かり易い対応、ロケーションiを付け先iにします。glNamedFramebufferDrawBuffer(framebuffer, buf)は要素1つの版で、此処では深度だけのフレームバッファに使います。
リストはフレームバッファオブジェクトの物なので、付け先を作る時に1回設定します。
resize()はcreateAttachmentsを呼ぶので、其の時にもう一度設定されます。
OpenGLは最低8個の色の付け先(GL_MAX_COLOR_ATTACHMENTS)を保証します。あたし達の上限4は配列の大きさに過ぎません。
フレームバッファに描画バッファが複数あると、更に2つの事が変わります:
glEnable(GL_BLEND)とglBlendFuncは其の全てに掛かります。此処では其れで良いのですが、glEnablei(GL_BLEND, i)とglBlendFunci(i, …)(OpenGL 4.0)で描画バッファ毎にブレンドを設定出来ます。第16章で触れた通りです。glClearは全ての描画バッファをクリアするので、明るい部分の付け先は毎フレーム黒から始まります。其れで正しいです。
2つの付け先を解決する
第20章のblitToは1回のglBlitNamedFramebufferでMSAAを解決していました。
付け先が2つになると其れでは足りず、理由はブリットの規則にあります。
ブリットは1つの読み込みバッファ(glNamedFramebufferReadBufferで選ぶ)から、書く先の全ての描画バッファにコピーします。
1回のブリットでは付け先0を読み、場面の色をsceneFboの両方の付け先にコピーしてしまいます:
其の為blitToは付け先毎に1回ブリットし、毎回読む側の読み込みバッファと書く側の描画バッファを同じ付け先に絞り、最後に全てを元に戻します:
void Framebuffer::blitTo(const Framebuffer &target, GLbitfield mask, GLenum filter) const {
// 読む側の四角形 → 書く側の四角形。読む色はglNamedFramebufferReadBuffer(既定はGL_COLOR_ATTACHMENT0)
// source rectangle → destination rectangle. The colour read comes from glNamedFramebufferReadBuffer
// (GL_COLOR_ATTACHMENT0 by default)
int colors = (mask & GL_COLOR_BUFFER_BIT) ? std::min(colorCount(), target.colorCount()) : 0;
if (colors <= 1) {
glBlitNamedFramebuffer(fbo, target.fbo, 0, 0, w, h, 0, 0, target.w, target.h, mask, filter);
return;
}
// 複数の色:読む色(ReadBuffer)と書く色(DrawBuffer)を一つずつ選んでコピーし、最後に元に戻す
// Several colours: pick one read buffer and one draw buffer at a time, copy, and restore them afterwards
for (int i = 0; i < colors; ++i) {
GLenum attachment = GL_COLOR_ATTACHMENT0 + static_cast<GLenum>(i);
glNamedFramebufferReadBuffer(fbo, attachment);
glNamedFramebufferDrawBuffer(target.fbo, attachment);
// 深度とステンシルは1回目だけ / depth and stencil only the first time
GLbitfield m = i == 0 ? mask : GL_COLOR_BUFFER_BIT;
glBlitNamedFramebuffer(fbo, target.fbo, 0, 0, w, h, 0, 0, target.w, target.h, m, filter);
}
GLenum drawBuffers[kMaxColorAttachments];
for (int i = 0; i < target.colorCount(); ++i) drawBuffers[i] = GL_COLOR_ATTACHMENT0 + static_cast<GLenum>(i);
glNamedFramebufferDrawBuffers(target.fbo, target.colorCount(), drawBuffers);
glNamedFramebufferReadBuffer(fbo, GL_COLOR_ATTACHMENT0);
}
glNamedFramebufferReadBuffer(framebuffer, src)は、読み込みとブリットがデータを取る色のバッファを選びます。フレームバッファオブジェクトの既定はGL_COLOR_ATTACHMENT0です。
深度とステンシルは読み込みバッファと描画バッファの影響を受けず、2回コピーするのは無駄なので、最初のブリットだけでコピーします。
最後に元に戻す事は見た目以上に大事です。
其れが無いとsceneFboの描画バッファのリストは付け先1だけのままになり、もし直接描いたら(第20章の「AAなし」モードの様に)、出力0が何処にも行きません。
21.8 トーンマッピング
HDRから画面へ
フレームの最後には、約0.001(夜の影)から156(太陽)迄の値を持つ線型のHDRの画像があります。
画面が見せられるのは0〜1です。
トーンマッパーは一方の範囲をもう一方に押し込む曲線で、GLSLの第10.6章で考え方を紹介しました。
post.fragには3つあり、Tで選びます:
// ACESフィルムの曲線の近似(Krzysztof Narkowicz 2015):肩がなだらかで、暗部は少し締まる
// An approximation of the ACES filmic curve (Krzysztof Narkowicz 2015): a soft shoulder, slightly deeper shadows
vec3 aces(vec3 x) {
return clamp((x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14), 0.0, 1.0);
}
// HDR(0〜∞)→ 画面の0〜1(まだリニア) / HDR (0..∞) → the screen's 0..1 (still linear)
vec3 toneMap(vec3 c) {
if (uToneMapper == 1) return c / (1.0 + c); // Reinhard:明るいほど1に近づく / approaches 1 as it gets brighter
if (uToneMapper == 2) return aces(c);
return clamp(c, 0.0, 1.0); // なし:1より上は切れる(白飛び) / none: everything above 1 is clipped (blown out)
}
3つとも全てチャンネル毎に働き、0〜1の線型の値を出力します。sRGBのエンコードは其の後です。
式で書くと、を1つのチャンネルのHDRの値として:
幾つかの典型的な値がどうなるかです(括弧の中はエンコード後の8ビットのsRGBの段階):
| 入力 | クランプ | Reinhard | ACES |
|---|---|---|---|
| 0.05 | 0.050(63) | 0.048(62) | 0.044(59) |
| 0.18 | 0.180(118) | 0.153(109) | 0.267(141) |
| 0.5 | 0.500(188) | 0.333(156) | 0.616(206) |
| 1 | 1.000(255) | 0.500(188) | 0.804(232) |
| 2 | 1.000(255) | 0.667(213) | 0.915(245) |
| 4 | 1.000(255) | 0.800(231) | 0.973(252) |
| 16 | 1.000(255) | 0.941(248) | 1.000(255) |
- クランプは第20章が暗黙にしていた事です。1迄は其のままで、其れより上は全て同じ白です。21.6節の漆喰の壁は3つのチャンネル全てで白になり、陰影も色も消えます。
- Reinhardは切れません。4と16はまだ違います。然し中間の色調も含めて全てを圧縮します。入力1は0.5、丸1段暗くなり、絵は灰色で平らに見えます。正しく見せるには露出を上げる必要があり、すると今度はハイライトが1の近くに詰まります。
- ACESは写真フィルムの反応の形をしています。トウがあり、黒の近くでの傾きはしかないので、一番暗い影は少し暗く深くなります。中間の色調を持ち上げ(中間のグレー0.18は0.267になります)、絵を明るく保ちます。そしてハイライトをなだらかに丸める柔らかいショルダーがあり、で1になります(分子と分母が等しくなる所:)。エンコードの後では約6.4で既に255になります。
此処のACESの曲線は、映画業界のACESの基準の変換をKrzysztof Narkowiczが2015年に近似した物で、チャンネル毎の1つの有理関数です。
安くて見た目が良いので人気があります。
チャンネル毎なので、とても明るい色では一番強いチャンネルが他より早く白に近付き、明るく鮮やかな光は少し黄色や白の方にずれます。
本物のACESの変換は其れを避ける為に別の色空間で計算します。21.16節に他の選択肢を挙げます。
21.9 露出
トーンマッパーの前に、色は露出を掛けられます。丁度カメラの露出と同じです。
写真家は露出を段、又はEVで数えます。1段で光が倍又は半分になります。
=と−のキーは半段ずつ変えます:
if (key == GLFW_KEY_EQUAL || key == GLFW_KEY_MINUS) {
exposureEv += key == GLFW_KEY_EQUAL ? 0.5f : -0.5f;
printf("exposure: %+.1f EV (x%.3g)\n", exposureEv, std::exp2(exposureEv));
}
そして毎フレーム、倍率が後処理のブロックに入ります:
postSettings.exposure = std::exp2(exposureEv);
postSettings.bloomStrength = bloomOn ? 0.08f : 0.0f;
postUbo.update(postSettings);
std::exp2(x)はです。
=を2回、−を1回押すと次の様に表示されます:
exposure: +0.5 EV (x1.41)
exposure: +1.0 EV (x2)
exposure: +0.5 EV (x1.41)
つまり−2 EVは倍、+2 EVは4倍、半段は倍です。
露出は場面ではなくカメラの性質です。
此の分離こそがHDRで得られる物です。
光は物理的な明るさのまま(太陽は本当に空の10倍)で、夜の場面が暗過ぎて見えなければ、月を明るくするのではなく「絞り」を開けます。
21.16節でゲームがどうやって露出を自動で決めるかを説明し、課題5で簡単な版を作ります。
1つの設計上の選択に注意して下さい。ブルームのしきい値は露出の前の場面の値と比べるので、露出は光の明るさの見え方を変えますが、どのピクセルが光るかは変えません。
21.10 Postブロック
露出、ブルームの強さ、しきい値、トーンマッパー、ガンマのモード、後処理の表示はpost.fragが使い、しきい値は(out_brightの為に)全ての場面のシェーダーも使います。
其れはユニフォームブロックの仕事で、第19章で結合点3を其の為に予約してありました。
使う全てのシェーダーが同じ文を宣言します:
// 後処理の設定(ユニフォームバッファ、結合点3、std140、第21章)。使う全部のシェーダーで同じ宣言(C++ではPostBlock)
// Post-processing settings (uniform buffer, binding 3, std140, chapter 21). The same declaration in every shader that
// uses it (PostBlock in C++)
layout(std140, binding = 3) uniform Post {
float uExposure; // 明るさの倍率 / brightness multiplier
float uBloomStrength; // ブルームの強さ / bloom strength
float uBloomThreshold; // これより明るい部分が光る(リニアのHDR値) / brighter than this glows (linear HDR value)
int uToneMapper; // 0 = クランプ / clamp, 1 = Reinhard, 2 = ACES
int uGammaMode; // 0 = シェーダー / shader, 1 = GL_FRAMEBUFFER_SRGB, 2 = なし / none, 3 = 二重 / double
int uPostView; // 0 = 完成 / final, 1 = ブルームなし / no bloom, 2 = 明るい部分 / bright part, 3 = ブルーム / bloom
int uPostPad0, uPostPad1; // std140の大きさを32バイトにそろえる / pads the block to 32 bytes
};
第19章のstd140の規則なら簡単です。4の倍数に揃う4バイトのスカラーが8つ、オフセット0、4、8、12、16、20、24、28で、32バイトです。
最後の2つのメンバーはわざと入れた詰め物です。
其れが無いとブロックは24で終わり、第19章で分かった通り、ドライバーによってブロックの大きさを「最後のメンバーの終わり」で返す物と16に切り上げて返す物があります。
詰め物があれば何処でも32です。
C++の写しは、結合点と列挙型と一緒にuniforms.hhにあります:
constexpr GLuint kPostBinding = 3; // Post:露出、トーンマッピング、ブルーム(第21章) / exposure, tone mapping, bloom (ch. 21)
// トーンマッピングの方法(post.fragのuToneMapperと同じ番号) / tone mappers (same numbers as uToneMapper in post.frag)
enum class ToneMapper { Clamp = 0, Reinhard = 1, Aces = 2 };
// 後処理を何を見せるか / what the post pass shows
enum class PostView { Final = 0, NoBloom = 1, Bright = 2, Bloom = 3 };
// GLSL:
// layout(std140, binding = 3) uniform Post {
// float uExposure; // offset 0:明るさの倍率(2^EV) / brightness multiplier (2^EV)
// float uBloomStrength; // 4:ブルームを足す強さ / how much bloom is added
// float uBloomThreshold; // 8:これより明るい部分が光る(リニアのHDR値) / brighter than this glows (linear HDR)
// int uToneMapper; // 12
// int uGammaMode; // 16
// int uPostView; // 20
// }; // 24 → 32 bytes
struct PostBlock {
float exposure = 1.0f;
float bloomStrength = 0.08f;
float bloomThreshold = 1.0f;
int toneMapper = static_cast<int>(ToneMapper::Aces);
int gammaMode = static_cast<int>(GammaMode::Shader);
int view = static_cast<int>(PostView::Final);
int pad[2] = {0, 0};
};
static_assert(offsetof(PostBlock, bloomThreshold) == 8);
static_assert(offsetof(PostBlock, view) == 20);
static_assert(sizeof(PostBlock) == 32);
列挙型は構造体の中ではintとして持ちます。C++の列挙型の大きさは保証されておらず、シェーダーは4バイトのintを読むからです。
bloomStrengthの既定値は此の章で使う強さの0.08です。其れでもmain.ccは毎フレーム、アップロードの前に設定します(0.08、Bなら0)。
main.ccでは、此のバッファは他の2つの隣のもう1つのUniformBufferです:
UniformBuffer<CameraBlock> cameraUbo(kCameraBinding);
UniformBuffer<LightsBlock> lightsUbo(kLightsBinding);
UniformBuffer<PostBlock> postUbo(kPostBinding);
そして第19章の起動時の確認は、ブロックを宣言するかも知れない全てのプログラムで3つのブロック全てを確かめる様になりました:
for (const Shader *s : {&*phong, &*skybox, &*post, &*unlit})
if (!s->checkUniformBlock("Camera", sizeof(CameraBlock)) || !s->checkUniformBlock("Lights", sizeof(LightsBlock)) ||
!s->checkUniformBlock("Post", sizeof(PostBlock)))
return 1;
checkUniformBlockはプログラムが使っていないブロックにはtrueを返すので、(Cameraブロックを持たない)postも其の部分は通ります。
unlitは此の章では何も描きません。新しいPostの宣言がコンパイルされて確かめられる様に読み込んでいます。
21.11 ブルーム
考え方
夜に明るいランプを見ると、周りに光の輪が見えます。
光が目やカメラのレンズの中で散乱するので、とても明るい物は周りに漏れ出します。
白迄しか見せられない画面では、光の輪は「此れは白より明るい」と伝える一番良い方法でもあります。
ブルームは3つの手順で其れを真似します:
- しきい値より明るい部分だけを取り出す。21.7節の明るい部分の付け先です。
- 其の画像を大きくぼかす。
- ぼかした画像を少しだけ、トーンマッピングの前に場面に足す。
Oキーで各手順を見られます。完成した絵、ブルーム無しの絵、明るい部分の付け先、ぼかしたブルームです。
プログラムは毎回名前を表示します:
post view: no bloom
post view: bright part (attachment 1)
post view: blurred bloom
post view: final
分離可能なガウスを折りたたむ
ぼかしはガウスぼかしで、第17章の3×3のぼかしと同じく分離可能です。
2Dのガウスは、横の1Dのぼかしの後に縦の1Dのぼかしをかけた物と同じです。
のカーネルならピクセル毎に81回テクスチャを読みますが、9回読むパスを2回なら18回です。
重みはパスカルの三角形から来ます。第17章の1-2-1のカーネルと同じ考え方です。
12段目は1、12、66、220、495、792、924、792、495、220、66、12、1です。
両端の小さい2つずつ(殆ど何も足しません)を捨てて真ん中の9つを残すと、合計は4070です:
但しです。
此のカーネルの標準偏差はテクセルです。
更に1つの技で読み込みを殆ど半分に出来ます。
GL_LINEARのフィルタリングでは、2つのテクセルの中心の間を読むと、其の重み付き平均が無料で返って来ます。
其の為、テクセル1と2を別々に読んでとを掛ける代わりに、ハードウェアが2つをの割合で混ぜる様な其の間の位置で1回読み、を掛けます:
9タップが5回の読み込みになります。中心と、及びテクセルです。
重みの合計は1のままです:。
此れがblur.fragの全てです。頂点シェーダーには第17章のpost.vertを使います:
#version 460 core
// ブルームのぼかし(第21章):分離可能なガウスぼかしの1方向。横と縦を交互に何度もかける(ピンポン)
// Bloom blur (chapter 21): one direction of a separable Gaussian blur. Applied horizontally and vertically in turn,
// several times (ping-pong)
in vec2 vUv;
layout(binding = 0) uniform sampler2D uImage;
uniform vec2 uDirection; // (1, 0) = 横 / horizontal, (0, 1) = 縦 / vertical(入力のテクセル単位 / in input texels)
layout(location = 0) out vec4 out_color;
void main() {
// 9タップのガウス(パスカルの三角形の12段目から両端の1と12を除いた物:中央924、左右に792, 495, 220, 66、/4070)を、
// 線型補間で5回の読み込みにまとめたもの:隣り合う2テクセルの間を読めば、GPUが重み付きで平均してくれる
// A 9-tap Gaussian (row 12 of Pascal's triangle without the outer 1 and 12: centre 924, then 792, 495, 220, 66 on
// each side, /4070) folded into 5 reads with linear filtering: reading between two neighbouring texels makes the
// GPU average them with the right weights
const float offsets[3] = float[](0.0, 1.3846153846, 3.2307692308);
const float weights[3] = float[](0.2270270270, 0.3162162162, 0.0702702703);
vec2 step = uDirection / vec2(textureSize(uImage, 0));
vec3 sum = texture(uImage, vUv).rgb * weights[0];
for (int i = 1; i < 3; ++i) {
sum += texture(uImage, vUv + offsets[i] * step).rgb * weights[i];
sum += texture(uImage, vUv - offsets[i] * step).rgb * weights[i];
}
out_color = vec4(sum, 1.0);
}
コメントにある通り、配列の数字は上で見た、両端を除いた12段目です。
多くのチュートリアルで見掛ける8段目の重み1、8、28、56、70(256分の)なら、折りたたんだオフセットは1.3333と3.1111になり、少しだけ狭いカーネルになります。
textureSize(uImage, 0)はミップマップ0段目のテクセル単位の大きさなので、stepは入力の画像の1テクセルを、uDirectionの方向にUV単位で表した物です。
フレームバッファのテクスチャはGL_CLAMP_TO_EDGE(第17章)なので、端の外を読むと画面の反対側に回り込まずに縁が繰り返されます。
半分の大きさでピンポン
横と縦のパスを1回ずつでは、柔らかいけれど狭い光にしかなりません。
広い光にするには其れを繰り返し、一方のフレームバッファから読んでもう一方に書くのを行ったり来たりします。此れがピンポンです。
そして其れを半分の解像度、640 × 360で行います。ピクセル数は4分の1で、1テクセルの歩幅は画面のピクセルで2倍になります:
//------------------------------------------------------------------
// 2. ブルーム:明るい部分(付け先1)を半分の大きさで、横・縦・横・縦…とぼかす(ピンポン)
// 2. Bloom: blur the bright part (attachment 1) at half size, horizontally, vertically, ... (ping-pong)
//------------------------------------------------------------------
glDisable(GL_DEPTH_TEST);
blur->use();
for (int pass = 0; pass < 2 * kBloomPasses; ++pass) {
bloomFbo[pass % 2].bind();
// 最初は全体の大きさの明るい部分から(線型補間で2×2の平均も取れる)、あとは前のパスの結果から
// The first pass reads the full-size bright part (linear filtering also averages 2 × 2), later passes read the
// previous result
(pass == 0 ? sceneFbo.color(1) : bloomFbo[(pass + 1) % 2].color()).bind(0);
blur->set("uDirection", pass % 2 == 0 ? Vec2{1.0f, 0.0f} : Vec2{0.0f, 1.0f});
fullscreen.draw();
}
kBloomPasses = 4なので、パスは8回です:
| パス | 読む物 | 書く先 | 方向 |
|---|---|---|---|
| 0 | sceneFbo.color(1)、1280 × 720 |
bloomFbo[0] |
横 |
| 1 | bloomFbo[0] |
bloomFbo[1] |
縦 |
| 2 | bloomFbo[1] |
bloomFbo[0] |
横 |
| 3 | bloomFbo[0] |
bloomFbo[1] |
縦 |
| 4〜7 | 同じ事をもう一度 |
最後のパスはbloomFbo[1]に書くので、ポストプロセスのパスはbloomFbo[1].color()を繋ぎます。
(pass + 1) % 2は「もう一方」です。
フレームバッファは、自分の色のテクスチャに描きながら其れを読んではいけません(第17章の唯一の規則)が、ピンポンなら其れが保証されます。
Framebuffer::bind()はビューポートを設定し、此処では其れが大事です。ブルームのフレームバッファは画面の半分の大きさだからです。
最初のパスが縮小の手順です。
半分の大きさの各ピクセルは丁度全体の大きさの4つのテクセルの角に位置するので、縦方向では線型のフィルターが無料で2行を平均し、横方向では5回の読み込みが全体の大きさのテクセルを覆います。
副作用が1つあります。最初の横のパスは全体の大きさのテクセルで進み(stepは入力の大きさから来ます)、後のパスは全て半分の大きさのテクセルで進みます。
明るい1ピクセルで8回のパスをシミュレーションしてみたところ、最終的な光は横で、縦で画面ピクセルでした。
丸い提灯では違いは見えない程小さいですが、此れで何処から来るのか分かりました。
コストは場面と比べると小さいです。8パス × 5回 × 230 400ピクセルで、1フレーム当たり920万回の読み込みです。
全体の大きさで9 × 9のパスを1回する時(81 × 921 600 = 7460万回)の8分の1です。
足し戻す
合成はpost.fragの、任意のUVの位置の最終的な表示用の色を作る関数で行います:
// UVの位置の表示用の色(0〜1)。ガンマのモード0と3ではsRGBにした後、1と2ではまだリニア
// The display colour at a UV position (0..1): sRGB-encoded in gamma modes 0 and 3, still linear in 1 and 2
vec3 display(vec2 uv) {
vec3 hdr = texture(uScene, uv).rgb;
if (uPostView == 0) hdr += uBloomStrength * texture(uBloom, uv).rgb;
else if (uPostView == 2) hdr = texture(uBright, uv).rgb;
else if (uPostView == 3) hdr = texture(uBloom, uv).rgb;
vec3 c = toneMap(hdr * uExposure);
// 効果はsRGBにしてから(人の目に近い空間で) / effects are applied after sRGB encoding (closer to how we see)
// モード3ではmain.ccがGL_FRAMEBUFFER_SRGBも有効にするので、GPUがもう一度エンコードする(わざと二重)
// In mode 3 main.cc also enables GL_FRAMEBUFFER_SRGB, so the GPU encodes a second time (doubled on purpose)
if (uGammaMode == 0 || uGammaMode == 3) c = linearToSrgb(c);
return c;
}
色のパイプライン全体が7行です。場面に0.08倍のブルームを足し、露出を掛け、トーンマッピングし、エンコードします。
ブルームのテクスチャは半分の大きさで、サンプラーの線型のフィルターが滑らかに拡大します。此れだけぼやけた物の低い解像度は誰にも見えません。
ブルームはトーンマッピングの前に線型のHDRで足すので、光の様に見えます。
暗い通りに0.3を足せばはっきり見えますが、日の当たる壁に同じ0.3を足しても、曲線のショルダーの下で殆ど消えます。
強さ0.08は小さく見えますが、提灯の明るい部分はぼかして広がる前は約4なので、其の8%でもはっきり見える光の輪になります。
uScene、uBloom、uBrightは、post.fragの最初で宣言した通りユニット0、1、2です:
layout(binding = 0) uniform sampler2D uScene; // RGBA16F、リニア / linear
layout(binding = 1) uniform sampler2D uBloom; // ぼかした明るい部分(半分の大きさ) / the blurred bright part (half size)
layout(binding = 2) uniform sampler2D uBright; // ぼかす前の明るい部分(表示用) / the bright part before blurring (for display)
ブルームは夜の場面を成り立たせる物ですが、一番良く見えるのは太陽です(K):
そして夜の、他は全て同じで「LDRの考え方」とHDRを比べた物です:
左の提灯は白い点です。チャンネルが切れた瞬間に色が失われました。
右ではACESがオレンジ、赤、黄色を保ち、ブルームが其れらが明るい事を目に伝えます。
21.12 ポストプロセスのパスとフレーム全体
エンコードの後の効果
post.fragの残りは第17章の効果で、今は表示用の値に掛かります:
vec3 convolve(vec2 uv, float k[9]) {
vec2 texel = 1.0 / vec2(textureSize(uScene, 0));
vec3 sum = vec3(0.0);
for (int y = -1; y <= 1; ++y)
for (int x = -1; x <= 1; ++x)
sum += k[(1 - y) * 3 + (x + 1)] * display(uv + vec2(x, y) * texel);
return sum;
}
void main() {
vec3 color = display(vUv);
if (uEffect == 1) {
color = 1.0 - color;
} else if (uEffect == 2) {
color = vec3(dot(color, vec3(0.2126, 0.7152, 0.0722)));
} else if (uEffect == 3) {
float k[9] = float[](-1, -1, -1, -1, 9, -1, -1, -1, -1);
color = convolve(vUv, k);
} else if (uEffect == 4) {
float k[9] = float[](1.0 / 16, 2.0 / 16, 1.0 / 16, 2.0 / 16, 4.0 / 16, 2.0 / 16, 1.0 / 16, 2.0 / 16, 1.0 / 16);
color = convolve(vUv, k);
} else if (uEffect == 5) {
float k[9] = float[](1, 1, 1, 1, -8, 1, 1, 1, 1);
color = convolve(vUv, k);
}
// uGammaMode 1(GL_FRAMEBUFFER_SRGB)と2(なし)はリニアのまま出す:1ではGPUが書くときに変換する
// Modes 1 (GL_FRAMEBUFFER_SRGB) and 2 (none) output linear values: with 1 the GPU encodes while writing
out_color = vec4(clamp(color, 0.0, 1.0), 1.0);
}
convolveは9つのタップ毎にdisplayを呼ぶので、カーネルはトーンマッピングとエンコードも含めて、画面が隣のピクセルで見せる物を丁度見ます。
其の為カーネルの効果がオンの間は、ピクセル毎に9回トーンマッピングします。デモなら構いませんが、本物のエンジンなら表示用の画像を先にテクスチャに書き、其れにカーネルを掛けます。
反転、グレースケール、エッジ検出はエンコード済みの値で計算し、其れはあたし達が明るさの違いを見る見方に近い(sRGBは其の為に作られました)ので、輪郭は第17章と同じ様に見えます。
第20章のFXAAのパスは此のファイルから無くなりました。戻すなら、其れも此処、エンコードの後に置きます。FXAAの輪郭の検出は表示用の値に合わせて調整されているからです。
フレームの最初から最後まで
main.ccのループの中身は次の通りになりました。
3つのユニフォームブロックを更新し、場面をmsaaFboに描き、解決し、8回のぼかしのパスを実行し、ポストプロセスのパスをウィンドウに描きます:
//------------------------------------------------------------------
// 1. 場面をHDR・MSAAで描き、解決する(色の付け先は2つとも) / 1. draw the scene in HDR with MSAA and resolve it
// (both colour attachments)
//------------------------------------------------------------------
msaaFbo.bind();
drawScene();
msaaFbo.blitTo(sceneFbo);
其の後に21.11節のブルームのループと、21.5節のポストプロセスの描画が続きます。
カメラのアスペクト比は、ウィンドウではなくsceneFboから取る様になりました(sceneFbo.width() / sceneFbo.height())。
大きさは同じですが、射影は常に其れが描く画像と合っているべきです。
第10章の表示モード(V)も、今は露出、トーンマッピング、エンコードを通るので、法線の表示は前より明るく見えます。
其れで正しいです。其れらの色は光ではなくデバッグ用のデータで、明るい部分も書かない(uViewMode > 0ではout_brightは0)ので、光る事もありません。
21.13 落とし穴
- 二重のエンコード、又はエンコード無し。 白っぽいなら2回エンコードしています(シェーダーと
GL_FRAMEBUFFER_SRGB、又はデータとして読んだsRGBテクスチャをもう一度エンコード)。暗くてコントラストが強過ぎるなら1回もしていません。画像ファイルから画面迄の繋がりを確かめて下さい。 - データのsRGBテクスチャ。 法線や粗さのマップをsRGBでアップロードすると、エラー無しに間違います(21.3節)。sRGBなのは色の画像だけです。
- 線型として使った選んだ色。 カラーピッカー、画像編集ソフト、又は第13章のあたしのジオラマの様な物からの色は変換しなければなりません。glTFの係数は定義から線型で、色のglTFテクスチャはsRGBです。
- 出力の書き忘れ。 付け先が2つのフレームバッファに描く全てのシェーダーは
out_brightを書かなければなりません。そうでないと、其のシェーダーが描いた所の付け先1は未定義です。 - 2つの付け先に1回のブリット。 ブリットは1つの読み込みバッファを読み、全ての描画バッファに書きます。付け先毎に解決し、其の後で描画バッファを元に戻します。
- MSAAはトーンマッピングの前に平均する。 夜空0.01の前の6.0の提灯が4つのサンプルの内1つを覆うと、解決の結果は1.51で、ACESは其れを255の内241にします。2つなら250、4つなら254です。縁は実質的に又硬い段差になり、MSAAがあっても明るい縁はギザギザに見えます。サンプルを先にトーンマッピングしてから平均すれば、段階は12、137、187、224、254で、滑らかな縁になります。課題7で其れをします。
- ブレンドは全ての描画バッファに掛かる。 透明な物は明るい部分も同じアルファでブレンドします(其の為
out_brightはout_color.aを写します)。 - グローバルなsRGBの状態。
GL_FRAMEBUFFER_SRGBはオンの間、全てのsRGBのフレームバッファの付け先に影響します。必要な描画の前後でだけオンにして下さい。 - 露出はライティングではない。 絵が暗過ぎるなら、先に露出を変えて下さい。光を明るくすると光同士の関係が変わりますが、露出は変えません。
21.14 性能:HDRの形式を選ぶ
GL_RGBA16Fは当然の選択ですが、ただではありません。
1280 × 720での此の章のフレームバッファのメモリです:
| フレームバッファ | 形式 | 1ピクセルのバイト数 | メモリ |
|---|---|---|---|
msaaFboの色、付け先2つ × 4サンプル |
GL_RGBA16F |
64 | 56.3 MiB |
msaaFboの深度・ステンシル、4サンプル |
GL_DEPTH24_STENCIL8 |
16 | 14.1 MiB |
sceneFboの色、付け先2つ |
GL_RGBA16F |
16 | 14.1 MiB |
bloomFbo × 2、640 × 360 |
GL_RGBA16F |
8 | 3.5 MiB |
マルチサンプルの色だけで第20章(4サンプルのGL_RGBA8の付け先1つ、14.1 MiB)の4倍で、全ての描画呼び出しの全てのピクセルが、サンプル毎に2倍のバイトを2つの付け先に書きます。
もっと小さいHDRの形式もあります。GL_R11F_G11F_B10Fは3つの浮動小数点数を32ビットに詰め、GL_RGBA16Fの半分の大きさです。
赤と緑は仮数6ビットと指数5ビット、青は5ビットと5ビットで、符号ビットもアルファもありません。
トレードオフ:
- アルファが無い。 あたし達のフレームバッファには要りません。アルファトゥカバレッジとブレンドは保存されたアルファではなくフラグメントのアルファを使い、ポストプロセスのパスはどうせアルファ1を出力します。
- 負の値が無い。 光は決して負になりません。負の値の途中結果を作るのは負の重みを持つ効果(シャープ)だけで、あたし達の効果はエンコードの後で動きます。
- 精度が低い。 1段階は赤と緑で値の最大、青でです(半精度浮動小数点数は0.1%)。トーンマッピングとエンコードの後、中間のグレーの辺りで1.6%の段階は8ビットの約1.1段階、3.1%の段階は約2.2段階なので、とても滑らかな青のグラデーション(晴れた空)では薄い縞が見える事があります。
- 範囲は同じ。 一番大きな値は65 024(赤、緑)と64 512(青)で、半精度浮動小数点数の65 504と殆ど同じです。
両方をあたしのテスト用のマシンで測りました。
此のマシンはMesaのllvmpipe、つまりソフトウェアラスタライザーで動く2コアの仮想マシンです。
第19章と同じく此れはCPUの時間で、±30〜40%ぶれ、GPUについては何も言えません。
4× MSAAでGL_RGBA16Fの付け先2つでは1フレーム約210 ms、GL_R11F_G11F_B10Fの付け先2つでは約78 msで、倍速くなりました。
比べる為に、MSAAでGL_RGBA16Fの付け先1つは約155 ms、MSAA無しは約85 msでした。
llvmpipeではマルチサンプルの浮動小数点の描画は高く、バイトを半分にする効果がとても大きいです。
デスクトップのGPUでは違いは本物ですが、ずっと小さいです。
描画がメモリの帯域で決まるのは重い場面だけで、GPUは内部でフレームバッファを圧縮します。
此のシリーズはGL_RGBA16Fのままにします。驚きの無い形式(後の章が欲しければアルファがあり、精度が問題になる事も無い)で、後の章は其れを前提にしているからです。
GL_R11F_G11F_B10Fは速さの為の選択肢として書いておきます。課題4で其れに切り替えます。
ソフトウェアレンダラーや弱いノートPCのGPUなら、MSAAのサンプルを減らす事と一緒に、最初に試す事です。
21.15 プラットフォーム毎の注意
- 既定のフレームバッファの符号化。 プログラムを実行し、起動時の
default framebuffer encodingの行を見て下さい。Windows(Visual Studioのビルド)では、NVIDIAの様に頼まなくてもウィンドウをsRGB対応にするドライバーがあります。LinuxとFreeBSDのMesaでは、GLFWが選ぶvisual又はconfig次第です。glfwWindowHint(GLFW_SRGB_CAPABLE, GLFW_TRUE)で頼めますが、柔らかい制約です。あたし達のシェーダーでのエンコードなら、此の何れも絵を変えません。其れに依存するのはGのモード1だけです。 - =と−のキーは
GLFW_KEY_EQUALとGLFW_KEY_MINUSで、USの配列に因んだ名前です(JISとドイツ語の配列での位置は第19章の注意にあります)。 - 浮動小数点の形式(
GL_RGBA16F、GL_R11F_G11F_B10F)はOpenGL 4.xで描画出来る事が必須の形式で、デスクトップのドライバーはMSAAでも対応しています。確かめる事はありません。違い得るのはサンプル数だけです(第20章)。 - ソフトウェアレンダラー。
glxinfo -B(Linux、FreeBSD)又は起動時に表示されるレンダラーの行がllvmpipeやsoftpipeなら、此の章の4× MSAAでは1フレームに5分の1秒程掛かると思って下さい。試している間はkMsaaSamplesを0にするか、GL_R11F_G11F_B10Fを試して下さい。
21.16 本物のエンジンではどうしているか
- 物理的な単位と自動露出。 UnrealやFrostbiteの様なエンジンは、物理的な光の単位(太陽はルクス、ランプはカンデラ又はルーメン)と、絞り、シャッター、ISOを持つカメラのモデル、又は単にEV100を使います。露出はフレームの対数輝度の平均(輝度のヒストグラム又はミップマップの連鎖)から自動で調整され、目の様にゆっくり変わります。課題5はミップマップの連鎖の版です。
- より良いトーンマッパー。 Narkowiczの曲線はチャンネル毎の近似です。Stephen HillのACESの近似は曲線の前後に行列を掛け、本物のACESのパイプラインは自分の色空間で計算します。AgX(Blender 4.0からの既定)やKhronos PBR Neutralの様な新しい演算子は、鮮やかなハイライトでのチャンネル毎の曲線の色ずれを避けます。
- ミップマップの連鎖のブルーム。 しきい値と決まったぼかしの代わりに、今殆どのエンジンが真似しているCall of Duty: Advanced Warfareのブルーム(Jimenez、2014年)は、HDRの画像全体を13タップのフィルターで6回縮小し、テントフィルターで拡大し直しながら各段を足します。しきい値が無く(全てが少しだけ光り、明るい部分は沢山光ります)、とても広く、コストは同じ位です。課題6です。
- カラーグレーディング。 トーンマッピングの後で、ゲームはカラーグレードを掛けます。普通は、アーティストがスクリーンショットから画像編集ソフトで作った3Dのルックアップテクスチャ(例えば32 × 32 × 32)です。
- HDRディスプレイ。 HDR10のモニターは別の符号化(SMPTE ST 2084のPQ曲線)とニトでの本物の明るさを受け取ります。トーンマッパーは1ではなく、ディスプレイの最大の明るさに合わせます。Vulkanでは
VK_COLOR_SPACE_HDR10_ST2084_EXTの様なスワップチェーンの色空間で、OpenGLには其れを頼む移植性のある方法がありません。 - VulkanとSlang。 Vulkanには
GL_FRAMEBUFFER_SRGBのスイッチがありません。スワップチェーンの形式を選び、VK_FORMAT_B8G8R8A8_SRGB(ハードウェアがエンコード)又はVK_FORMAT_B8G8R8A8_UNORM(シェーダーでエンコード)で、21.5節と同じ判断になります。テクスチャはVK_FORMAT_R8G8B8A8_SRGBを使います。マルチレンダーターゲットはレンダーパス又はダイナミックレンダリングの色の付け先で、ぼかしのパスは同じ全画面の三角形です。此の章の式は全て其のまま使えます。
21.17 まとめ
- 画像ファイルと選んだ色はsRGBで符号化されています。光の計算が正しいのは線型の値の時だけです。入る時にデコードし、線型で計算し、出る時に1回だけエンコードします。正確な曲線:より下は、其れ以外は。
GL_SRGB8_ALPHA8ならサンプラーが無料でデコードします(テクセル毎、フィルタリングの前。アルファは線型のまま)。sRGBなのは色の画像だけで、ベースカラー、発光、スプライト、空です。法線、金属度・粗さ、遮蔽、高さのマップは線型のままです。- 乗算済みアルファは線型空間で計算しなければなりません。手で選んだ色は
srgbToLinearを通します。glTFの係数は仕様で線型と決まっていて、第13章の生成スクリプトは其れを間違えていました。作り直したジオラマで直りました。 - 画面の為のエンコードは
post.fragで行います。GL_FRAMEBUFFER_SRGBでも同じ絵になります(此処では255の内1以内)が、既定のフレームバッファがsRGB対応の時だけで、其れは保証されていません。両方は決してしません。 - HDR:場面は
GL_RGBA16F(半精度浮動小数点数、最大65 504、0.1%の段階、切られない)に描きます。光は物理的に明るくて良く、スカイボックスはLightsブロックからHDRの太陽を足します。 - MRT:
layout(location = 1) outとglNamedFramebufferDrawBuffersで、同じパスで2枚目の画像を書きます。全てのシェーダーが全ての出力を書かなければなりません。ブリットは1つの読み込みバッファを全ての描画バッファにコピーするので、blitToは付け先毎に解決します。 - トーンマッピングはHDRを0〜1にします。クランプ、Reinhard 、トウと7.24で1になるショルダーを持つACES(Narkowicz)。其の前に露出がを掛けます。
- Postブロック(結合点3、32バイト)は露出、ブルームの設定、トーンマッパー、ガンマのモード、表示を持ち、ポストプロセスのパスと全ての場面のシェーダーが読みます。
- ブルーム:明るい部分(輝度が1より上、色合いは保つ) → 線型補間で5回の読み込みに折りたたんだ9タップのガウスを、半分の大きさで4 ×(横+縦)回ピンポン → トーンマッピングの前に0.08 × ブルームを足す。
- 4× MSAAで
GL_RGBA16F× 2は重く(サンプルだけで56 MiB)、GL_R11F_G11F_B10Fは其れを半分にします(llvmpipeで1フレーム約210 ms → 約78 ms、CPUの時間)。代わりにアルファ、符号、精度を失います。
21.18 課題
- ★ 床のテクスチャを
srgb無しでアップロードして下さい(main.ccの{.srgb = true}を消します)。床は正しい色の木箱や草の隣で淡く白っぽく見えるはずです。そして、ライティングとトーンマッピングを無視して、床の128のテクセルが画面で何段階になるかを両方の場合について手で計算して下さい。デコードしてもう一度エンコードすれば128のままです。デコードしなければ値が、188段階にエンコードされます。 - ★
linearToSrgbの中身をpow(c, vec3(1.0 / 2.2))に置き換えて下さい。絵は殆ど同じに見え、一番暗い色調だけが少し変わるはずです。21.2節を使って一番大きな違い(黒の近くで約8.5段階)を予想し、夜の場面で探して下さい。 - ★ 白色点を持つ「拡張Reinhard」を4つ目のトーンマッパーとして加えて下さい。で、入力4が丁度1に、入力1が0.53になる事を紙の上で確かめて下さい。画面ではReinhardに似ていますが灰色っぽさが減り、4以上の物は全て本当の白になるはずです。
- ★★
hdrSpecを(ブルームのフレームバッファも)GL_R11F_G11F_B10Fに切り替え、フレームの前後のタイマー又は第19章のGpuTimerでフレームの時間を比べて下さい。絵は同じに見え、フレームはかなり速くなるはずです(llvmpipeで約2.7倍、GPUではずっと少なく)。晴れた空に縞が無いか探して下さい。 - ★★ 自動露出:解決の後、
sceneFboの輝度の対数を小さな浮動小数点のテクスチャに計算し、glGenerateTextureMipmapでミップマップを作り、ポストプロセスのシェーダーで1 × 1の段を読み(最後の段でtextureLod)、平均が中間のグレーになる様に露出をにして下さい。CPU又は1 × 1のフレームバッファで時間的に滑らかにします。太陽(K)から地面に視線を戻すと、目が慣れる様に絵が徐々に明るくなるはずです。 - ★★ しきい値のブルームをミップマップの連鎖のブルームに置き換えて下さい。解決した場面を13タップのフィルターで6回、どんどん小さくなるフレームバッファに縮小し、3 × 3のテントフィルターで拡大しながら各段を1つ大きい段に足し、結果を強さ約0.04、しきい値無しで足します。光はもっと広く滑らかになり、日の当たる漆喰が薄く光り、提灯の周りにブロック状のアーティファクトは出ないはずです。
- ★★★ 解決の前にトーンマッピングして下さい。
msaaFboの色をマルチサンプルのテクスチャ(GL_TEXTURE_2D_MULTISAMPLEにglTextureStorage2DMultisample)にし、各サンプルをtexelFetch(sampler2DMS, p, i)で読み、サンプル毎にに変換してから平均し、で元に戻すシェーダーで解決します。Brian Karisが紹介した技です。夜空の前の提灯と太陽の縁が、第20章の普通の縁と同じ位滑らかになり、全体の明るさは変わらないはずです。
ファイル: a/assets/LICENSE.txt | b/assets/LICENSE.txt
| 前 | 新 | ||
|---|---|---|---|
| @@ -13,4 +13,4 @@ textures/sky/*.png 空のキューブマップの6面 / the six sky cu | |||
| 13 | models/window.glb 花箱つきの窓 / a window with a flower box (chapter 16) | 13 | models/window.glb 花箱つきの窓 / a window with a flower box (chapter 16) |
| 14 | models/rock.glb 岩(インスタンシング用) / a rock for instancing (chapter 19) | 14 | models/rock.glb 岩(インスタンシング用) / a rock for instancing (chapter 19) |
| 15 | models/crate.glb 木箱のモデル / crate model | 15 | models/crate.glb 木箱のモデル / crate model |
| 16 | models/diorama.glb 小さな場面 / a small diorama scene | 16 | models/diorama.glb 小さな場面 / a small diorama scene (chapter 21) |
ファイル: a/assets/models/diorama.glb | b/assets/models/diorama.glb
バイナリファイル
ファイル: /dev/null | b/shaders/blur.frag
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,27 @@ | |||
| 1 | #version 460 core | ||
| 2 | // ブルームのぼかし(第21章):分離可能なガウスぼかしの1方向。横と縦を交互に何度もかける(ピンポン) | ||
| 3 | // Bloom blur (chapter 21): one direction of a separable Gaussian blur. Applied horizontally and vertically in turn, | ||
| 4 | // several times (ping-pong) | ||
| 5 | in vec2 vUv; | ||
| 6 | |||
| 7 | layout(binding = 0) uniform sampler2D uImage; | ||
| 8 | uniform vec2 uDirection; // (1, 0) = 横 / horizontal, (0, 1) = 縦 / vertical(入力のテクセル単位 / in input texels) | ||
| 9 | |||
| 10 | layout(location = 0) out vec4 out_color; | ||
| 11 | |||
| 12 | void main() { | ||
| 13 | // 9タップのガウス(パスカルの三角形の12段目から両端の1と12を除いた物:中央924、左右に792, 495, 220, 66、/4070)を、 | ||
| 14 | // 線型補間で5回の読み込みにまとめたもの:隣り合う2テクセルの間を読めば、GPUが重み付きで平均してくれる | ||
| 15 | // A 9-tap Gaussian (row 12 of Pascal's triangle without the outer 1 and 12: centre 924, then 792, 495, 220, 66 on | ||
| 16 | // each side, /4070) folded into 5 reads with linear filtering: reading between two neighbouring texels makes the | ||
| 17 | // GPU average them with the right weights | ||
| 18 | const float offsets[3] = float[](0.0, 1.3846153846, 3.2307692308); | ||
| 19 | const float weights[3] = float[](0.2270270270, 0.3162162162, 0.0702702703); | ||
| 20 | vec2 step = uDirection / vec2(textureSize(uImage, 0)); | ||
| 21 | vec3 sum = texture(uImage, vUv).rgb * weights[0]; | ||
| 22 | for (int i = 1; i < 3; ++i) { | ||
| 23 | sum += texture(uImage, vUv + offsets[i] * step).rgb * weights[i]; | ||
| 24 | sum += texture(uImage, vUv - offsets[i] * step).rgb * weights[i]; | ||
| 25 | } | ||
| 26 | out_color = vec4(sum, 1.0); | ||
| 27 | } | ||
ファイル: a/shaders/envmap.frag | b/shaders/envmap.frag
| 前 | 新 | ||
|---|---|---|---|
| @@ -21,6 +21,27 @@ uniform vec3 uEnvironmentTint; // 空の明るさ(昼1、夜は暗く) / bri | |||
| 21 | 21 | ||
| 22 | layout(location = 0) out vec4 out_color; | 22 | layout(location = 0) out vec4 out_color; |
| 23 | 23 | ||
| 24 | // 後処理の設定(ユニフォームバッファ、結合点3、std140、第21章)。使う全部のシェーダーで同じ宣言(C++ではPostBlock) | ||
| 25 | // Post-processing settings (uniform buffer, binding 3, std140, chapter 21). The same declaration in every shader that | ||
| 26 | // uses it (PostBlock in C++) | ||
| 27 | layout(std140, binding = 3) uniform Post { | ||
| 28 | float uExposure; // 明るさの倍率 / brightness multiplier | ||
| 29 | float uBloomStrength; // ブルームの強さ / bloom strength | ||
| 30 | float uBloomThreshold; // これより明るい部分が光る(リニアのHDR値) / brighter than this glows (linear HDR value) | ||
| 31 | int uToneMapper; // 0 = クランプ / clamp, 1 = Reinhard, 2 = ACES | ||
| 32 | int uGammaMode; // 0 = シェーダー / shader, 1 = GL_FRAMEBUFFER_SRGB, 2 = なし / none, 3 = 二重 / double | ||
| 33 | int uPostView; // 0 = 完成 / final, 1 = ブルームなし / no bloom, 2 = 明るい部分 / bright part, 3 = ブルーム / bloom | ||
| 34 | int uPostPad0, uPostPad1; // std140の大きさを32バイトにそろえる / pads the block to 32 bytes | ||
| 35 | }; | ||
| 36 | |||
| 37 | // ブルーム用の2つ目の出力(MRT、GL_COLOR_ATTACHMENT1):しきい値より明るい部分だけ(色合いは保つ) | ||
| 38 | // The second output for bloom (MRT, GL_COLOR_ATTACHMENT1): only what is brighter than the threshold (hue kept) | ||
| 39 | layout(location = 1) out vec4 out_bright; | ||
| 40 | vec3 brightPart(vec3 c) { | ||
| 41 | float l = dot(c, vec3(0.2126, 0.7152, 0.0722)); // 輝度 / luminance | ||
| 42 | return c * (max(l - uBloomThreshold, 0.0) / max(l, 1e-4)); | ||
| 43 | } | ||
| 44 | |||
| 24 | void main() { | 45 | void main() { |
| 25 | vec3 i = normalize(vWorldPos - uViewPos); // 目から表面へ / from the eye to the surface | 46 | vec3 i = normalize(vWorldPos - uViewPos); // 目から表面へ / from the eye to the surface |
| 26 | vec3 n = normalize(vNormal); | 47 | vec3 n = normalize(vNormal); |
| @@ -42,4 +63,5 @@ void main() { | |||
| 42 | color = mix(refracted, reflected, fresnel); | 63 | color = mix(refracted, reflected, fresnel); |
| 43 | } | 64 | } |
| 44 | out_color = vec4(color * uTint * uEnvironmentTint, 1.0); | 65 | out_color = vec4(color * uTint * uEnvironmentTint, 1.0); |
| 66 | out_bright = vec4(brightPart(out_color.rgb), 1.0); | ||
| 45 | } | 67 | } |
ファイル: a/shaders/phong.frag | b/shaders/phong.frag
| 前 | 新 | ||
|---|---|---|---|
| @@ -93,6 +93,27 @@ uniform bool uAlphaToCoverage = false; | |||
| 93 | 93 | ||
| 94 | layout(location = 0) out vec4 out_color; | 94 | layout(location = 0) out vec4 out_color; |
| 95 | 95 | ||
| 96 | // 後処理の設定(ユニフォームバッファ、結合点3、std140、第21章)。使う全部のシェーダーで同じ宣言(C++ではPostBlock) | ||
| 97 | // Post-processing settings (uniform buffer, binding 3, std140, chapter 21). The same declaration in every shader that | ||
| 98 | // uses it (PostBlock in C++) | ||
| 99 | layout(std140, binding = 3) uniform Post { | ||
| 100 | float uExposure; // 明るさの倍率 / brightness multiplier | ||
| 101 | float uBloomStrength; // ブルームの強さ / bloom strength | ||
| 102 | float uBloomThreshold; // これより明るい部分が光る(リニアのHDR値) / brighter than this glows (linear HDR value) | ||
| 103 | int uToneMapper; // 0 = クランプ / clamp, 1 = Reinhard, 2 = ACES | ||
| 104 | int uGammaMode; // 0 = シェーダー / shader, 1 = GL_FRAMEBUFFER_SRGB, 2 = なし / none, 3 = 二重 / double | ||
| 105 | int uPostView; // 0 = 完成 / final, 1 = ブルームなし / no bloom, 2 = 明るい部分 / bright part, 3 = ブルーム / bloom | ||
| 106 | int uPostPad0, uPostPad1; // std140の大きさを32バイトにそろえる / pads the block to 32 bytes | ||
| 107 | }; | ||
| 108 | |||
| 109 | // ブルーム用の2つ目の出力(MRT、GL_COLOR_ATTACHMENT1):しきい値より明るい部分だけ(色合いは保つ) | ||
| 110 | // The second output for bloom (MRT, GL_COLOR_ATTACHMENT1): only what is brighter than the threshold (hue kept) | ||
| 111 | layout(location = 1) out vec4 out_bright; | ||
| 112 | vec3 brightPart(vec3 c) { | ||
| 113 | float l = dot(c, vec3(0.2126, 0.7152, 0.0722)); // 輝度 / luminance | ||
| 114 | return c * (max(l - uBloomThreshold, 0.0) / max(l, 1e-4)); | ||
| 115 | } | ||
| 116 | |||
| 96 | // このピクセルの表面:どの光の計算にも同じものを使う / this pixel's surface: the same for every light | 117 | // このピクセルの表面:どの光の計算にも同じものを使う / this pixel's surface: the same for every light |
| 97 | struct Surface { | 118 | struct Surface { |
| 98 | vec3 position; // ワールド座標 / world space | 119 | vec3 position; // ワールド座標 / world space |
| @@ -193,4 +214,6 @@ void main() { | |||
| 193 | // alpha becomes the number of samples covered | 214 | // alpha becomes the number of samples covered |
| 194 | bool coverage = uMaterial.alphaMode == ALPHA_MASK && uAlphaToCoverage; | 215 | bool coverage = uMaterial.alphaMode == ALPHA_MASK && uAlphaToCoverage; |
| 195 | out_color = vec4(color, uMaterial.alphaMode == ALPHA_BLEND || coverage ? clamp(alpha, 0.0, 1.0) : 1.0); | 216 | out_color = vec4(color, uMaterial.alphaMode == ALPHA_BLEND || coverage ? clamp(alpha, 0.0, 1.0) : 1.0); |
| 217 | // デバッグ表示(uViewMode > 0)は光らせない / debug views do not glow | ||
| 218 | out_bright = vec4(uViewMode == 0 ? brightPart(color) : vec3(0.0), out_color.a); | ||
| 196 | } | 219 | } |
ファイル: a/shaders/post.frag | b/shaders/post.frag
| 前 | 新 | ||
|---|---|---|---|
| @@ -1,119 +1,90 @@ | |||
| 1 | #version 460 core | 1 | #version 460 core |
| 2 | // ポストプロセス:フレームバッファに描いた画像を加工して画面に出す。MSAAなら解決(resolve)した後の画像(第20章) | 2 | // ポストプロセス(第21章):HDRの場面+ブルーム → 露出 → トーンマッピング → sRGBに変換 → 効果 |
| 3 | // Post-processing: take the image drawn into a framebuffer, change it, and put it on the screen. With MSAA this is | 3 | // Post-processing (chapter 21): HDR scene + bloom → exposure → tone mapping → sRGB encoding → effect |
| 4 | // the resolved image (chapter 20) | ||
| 5 | in vec2 vUv; | 4 | in vec2 vUv; |
| 6 | 5 | ||
| 7 | layout(binding = 0) uniform sampler2D uScene; | 6 | layout(binding = 0) uniform sampler2D uScene; // RGBA16F、リニア / linear |
| 7 | layout(binding = 1) uniform sampler2D uBloom; // ぼかした明るい部分(半分の大きさ) / the blurred bright part (half size) | ||
| 8 | layout(binding = 2) uniform sampler2D uBright; // ぼかす前の明るい部分(表示用) / the bright part before blurring (for display) | ||
| 8 | 9 | ||
| 9 | // 0 = なし / none, 1 = 反転 / invert, 2 = グレースケール / grayscale, 3 = シャープ / sharpen, | 10 | // 0 = なし / none, 1 = 反転 / invert, 2 = グレースケール / grayscale, 3 = シャープ / sharpen, |
| 10 | // 4 = ぼかし / blur, 5 = エッジ検出 / edge detection | 11 | // 4 = ぼかし / blur, 5 = エッジ検出 / edge detection |
| 11 | uniform int uEffect; | 12 | uniform int uEffect; |
| 12 | uniform bool uFxaa; // FXAA風のアンチエイリアス(第20章) / FXAA-like anti-aliasing (chapter 20) | 13 | |
| 13 | uniform bool uMagnifier; // 右下に画面の中央を4倍に拡大して見せる / shows the centre of the screen 4× enlarged, bottom right | 14 | // 後処理の設定(ユニフォームバッファ、結合点3、std140、第21章)。使う全部のシェーダーで同じ宣言(C++ではPostBlock) |
| 15 | // Post-processing settings (uniform buffer, binding 3, std140, chapter 21). The same declaration in every shader that | ||
| 16 | // uses it (PostBlock in C++) | ||
| 17 | layout(std140, binding = 3) uniform Post { | ||
| 18 | float uExposure; // 明るさの倍率 / brightness multiplier | ||
| 19 | float uBloomStrength; // ブルームの強さ / bloom strength | ||
| 20 | float uBloomThreshold; // これより明るい部分が光る(リニアのHDR値) / brighter than this glows (linear HDR value) | ||
| 21 | int uToneMapper; // 0 = クランプ / clamp, 1 = Reinhard, 2 = ACES | ||
| 22 | int uGammaMode; // 0 = シェーダー / shader, 1 = GL_FRAMEBUFFER_SRGB, 2 = なし / none, 3 = 二重 / double | ||
| 23 | int uPostView; // 0 = 完成 / final, 1 = ブルームなし / no bloom, 2 = 明るい部分 / bright part, 3 = ブルーム / bloom | ||
| 24 | int uPostPad0, uPostPad1; // std140の大きさを32バイトにそろえる / pads the block to 32 bytes | ||
| 25 | }; | ||
| 14 | 26 | ||
| 15 | layout(location = 0) out vec4 out_color; | 27 | layout(location = 0) out vec4 out_color; |
| 16 | 28 | ||
| 17 | // 明るさ(FXAAは色ではなく明るさの差で輪郭を探す) / brightness (FXAA looks for edges in brightness, not colour) | 29 | // ACESフィルムの曲線の近似(Krzysztof Narkowicz 2015):肩がなだらかで、暗部は少し締まる |
| 18 | float luma(vec3 c) { return dot(c, vec3(0.299, 0.587, 0.114)); } | 30 | // An approximation of the ACES filmic curve (Krzysztof Narkowicz 2015): a soft shoulder, slightly deeper shadows |
| 31 | vec3 aces(vec3 x) { | ||
| 32 | return clamp((x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14), 0.0, 1.0); | ||
| 33 | } | ||
| 19 | 34 | ||
| 20 | // FXAA風(Timothy LottesのFXAA 3.11「コンソール版」を簡単にしたもの):斜めの4ピクセルの明るさから輪郭の向きを求め、 | 35 | // HDR(0〜∞)→ 画面の0〜1(まだリニア) / HDR (0..∞) → the screen's 0..1 (still linear) |
| 21 | // 輪郭に沿って何点か読んで平均する。MSAAと違って、描き終わった画像だけから作る(深度もサンプルも要らない) | 36 | vec3 toneMap(vec3 c) { |
| 22 | // FXAA-like (a simplified version of Timothy Lottes' FXAA 3.11 "console"): estimate the edge direction from the | 37 | if (uToneMapper == 1) return c / (1.0 + c); // Reinhard:明るいほど1に近づく / approaches 1 as it gets brighter |
| 23 | // brightness of the four diagonal neighbours, then average a few samples along the edge. Unlike MSAA it only needs | 38 | if (uToneMapper == 2) return aces(c); |
| 24 | // the finished image (no depth, no samples) | 39 | return clamp(c, 0.0, 1.0); // なし:1より上は切れる(白飛び) / none: everything above 1 is clipped (blown out) |
| 25 | vec3 fxaa(vec2 uv) { | 40 | } |
| 26 | vec2 texel = 1.0 / vec2(textureSize(uScene, 0)); | ||
| 27 | vec3 rgbM = texture(uScene, uv).rgb; | ||
| 28 | // OpenGLのUVは上が+y / OpenGL UVs have +y up | ||
| 29 | float lumaNW = luma(texture(uScene, uv + vec2(-1.0, 1.0) * texel).rgb); | ||
| 30 | float lumaNE = luma(texture(uScene, uv + vec2(1.0, 1.0) * texel).rgb); | ||
| 31 | float lumaSW = luma(texture(uScene, uv + vec2(-1.0, -1.0) * texel).rgb); | ||
| 32 | float lumaSE = luma(texture(uScene, uv + vec2(1.0, -1.0) * texel).rgb); | ||
| 33 | float lumaM = luma(rgbM); | ||
| 34 | float lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE))); | ||
| 35 | float lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE))); | ||
| 36 | // 明るさの差が小さければ輪郭ではない:そのまま(ほとんどのピクセルはここで終わる) | ||
| 37 | // Little contrast: not an edge, keep the pixel (most pixels stop here) | ||
| 38 | if (lumaMax - lumaMin < max(0.0312, lumaMax * 0.125)) return rgbM; | ||
| 39 | 41 | ||
| 40 | // 明るさの勾配に垂直な向き=輪郭に沿った向き / perpendicular to the brightness gradient = along the edge | 42 | // リニア → sRGB(IEC 61966-2-1)。おおよそ pow(c, 1/2.2) / linear → sRGB, roughly pow(c, 1/2.2) |
| 41 | vec2 dir = vec2((lumaNW + lumaNE) - (lumaSW + lumaSE), (lumaNW + lumaSW) - (lumaNE + lumaSE)); | 43 | vec3 linearToSrgb(vec3 c) { |
| 42 | float reduce = max((lumaNW + lumaNE + lumaSW + lumaSE) * (0.25 / 8.0), 1.0 / 128.0); | 44 | return mix(c * 12.92, 1.055 * pow(c, vec3(1.0 / 2.4)) - 0.055, step(vec3(0.0031308), c)); |
| 43 | float rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + reduce); | 45 | } |
| 44 | dir = clamp(dir * rcpDirMin, vec2(-8.0), vec2(8.0)) * texel; // 最大8ピクセル / at most 8 pixels | ||
| 45 | 46 | ||
| 46 | // 輪郭に沿って近い2点と遠い2点 / two near and two far samples along the edge | 47 | // UVの位置の表示用の色(0〜1)。ガンマのモード0と3ではsRGBにした後、1と2ではまだリニア |
| 47 | vec3 rgbA = 0.5 * (texture(uScene, uv + dir * (1.0 / 3.0 - 0.5)).rgb + texture(uScene, uv + dir * (2.0 / 3.0 - 0.5)).rgb); | 48 | // The display colour at a UV position (0..1): sRGB-encoded in gamma modes 0 and 3, still linear in 1 and 2 |
| 48 | vec3 rgbB = rgbA * 0.5 + 0.25 * (texture(uScene, uv - dir * 0.5).rgb + texture(uScene, uv + dir * 0.5).rgb); | 49 | vec3 display(vec2 uv) { |
| 49 | // 遠い点が輪郭の向こう側だった(明るさが範囲外)なら近い2点だけ / if the far samples crossed the edge (brightness out | 50 | vec3 hdr = texture(uScene, uv).rgb; |
| 50 | // of range), use only the near ones | 51 | if (uPostView == 0) hdr += uBloomStrength * texture(uBloom, uv).rgb; |
| 51 | float lumaB = luma(rgbB); | 52 | else if (uPostView == 2) hdr = texture(uBright, uv).rgb; |
| 52 | return (lumaB < lumaMin || lumaB > lumaMax) ? rgbA : rgbB; | 53 | else if (uPostView == 3) hdr = texture(uBloom, uv).rgb; |
| 54 | vec3 c = toneMap(hdr * uExposure); | ||
| 55 | // 効果はsRGBにしてから(人の目に近い空間で) / effects are applied after sRGB encoding (closer to how we see) | ||
| 56 | // モード3ではmain.ccがGL_FRAMEBUFFER_SRGBも有効にするので、GPUがもう一度エンコードする(わざと二重) | ||
| 57 | // In mode 3 main.cc also enables GL_FRAMEBUFFER_SRGB, so the GPU encodes a second time (doubled on purpose) | ||
| 58 | if (uGammaMode == 0 || uGammaMode == 3) c = linearToSrgb(c); | ||
| 59 | return c; | ||
| 53 | } | 60 | } |
| 54 | 61 | ||
| 55 | // 3×3のカーネル(畳み込み):周りの9ピクセルに重みを掛けて足す | ||
| 56 | // A 3×3 kernel (convolution): multiply the 9 surrounding pixels by weights and add them up | ||
| 57 | vec3 convolve(vec2 uv, float k[9]) { | 62 | vec3 convolve(vec2 uv, float k[9]) { |
| 58 | vec2 texel = 1.0 / vec2(textureSize(uScene, 0)); // 1ピクセルのUVでの大きさ / one pixel in UV units | 63 | vec2 texel = 1.0 / vec2(textureSize(uScene, 0)); |
| 59 | vec3 sum = vec3(0.0); | 64 | vec3 sum = vec3(0.0); |
| 60 | for (int y = -1; y <= 1; ++y) | 65 | for (int y = -1; y <= 1; ++y) |
| 61 | for (int x = -1; x <= 1; ++x) | 66 | for (int x = -1; x <= 1; ++x) |
| 62 | sum += k[(1 - y) * 3 + (x + 1)] * texture(uScene, uv + vec2(x, y) * texel).rgb; // 上の行から / top row first | 67 | sum += k[(1 - y) * 3 + (x + 1)] * display(uv + vec2(x, y) * texel); |
| 63 | return sum; | 68 | return sum; |
| 64 | } | 69 | } |
| 65 | 70 | ||
| 66 | // UVの位置の最終的な色(効果をかけた後) / the final colour at a UV position (after the effect) | 71 | void main() { |
| 67 | vec3 shade(vec2 uv) { | 72 | vec3 color = display(vUv); |
| 68 | vec3 color = uFxaa ? fxaa(uv) : texture(uScene, uv).rgb; | ||
| 69 | if (uEffect == 1) { | 73 | if (uEffect == 1) { |
| 70 | color = 1.0 - color; | 74 | color = 1.0 - color; |
| 71 | } else if (uEffect == 2) { | 75 | } else if (uEffect == 2) { |
| 72 | // 目は緑に一番敏感:輝度の重み(Rec. 709) / the eye is most sensitive to green: luminance weights (Rec. 709) | ||
| 73 | color = vec3(dot(color, vec3(0.2126, 0.7152, 0.0722))); | 76 | color = vec3(dot(color, vec3(0.2126, 0.7152, 0.0722))); |
| 74 | } else if (uEffect == 3) { | 77 | } else if (uEffect == 3) { |
| 75 | float k[9] = float[](-1, -1, -1, | 78 | float k[9] = float[](-1, -1, -1, -1, 9, -1, -1, -1, -1); |
| 76 | -1, 9, -1, | 79 | color = convolve(vUv, k); |
| 77 | -1, -1, -1); // 合計1:明るさは変わらない / sums to 1: brightness unchanged | ||
| 78 | color = convolve(uv, k); | ||
| 79 | } else if (uEffect == 4) { | 80 | } else if (uEffect == 4) { |
| 80 | float k[9] = float[](1.0 / 16, 2.0 / 16, 1.0 / 16, | 81 | float k[9] = float[](1.0 / 16, 2.0 / 16, 1.0 / 16, 2.0 / 16, 4.0 / 16, 2.0 / 16, 1.0 / 16, 2.0 / 16, 1.0 / 16); |
| 81 | 2.0 / 16, 4.0 / 16, 2.0 / 16, | 82 | color = convolve(vUv, k); |
| 82 | 1.0 / 16, 2.0 / 16, 1.0 / 16); // ガウスに近い / close to a Gaussian | ||
| 83 | color = convolve(uv, k); | ||
| 84 | } else if (uEffect == 5) { | 83 | } else if (uEffect == 5) { |
| 85 | float k[9] = float[](1, 1, 1, | 84 | float k[9] = float[](1, 1, 1, 1, -8, 1, 1, 1, 1); |
| 86 | 1, -8, 1, | 85 | color = convolve(vUv, k); |
| 87 | 1, 1, 1); // 合計0:平らなところは黒、変化があるところだけ明るい / sums to 0: flat areas black | ||
| 88 | color = convolve(uv, k); | ||
| 89 | } | ||
| 90 | return color; | ||
| 91 | } | ||
| 92 | |||
| 93 | void main() { | ||
| 94 | vec2 uv = vUv; | ||
| 95 | vec3 frame = vec3(-1.0); // 拡大鏡の枠の色(-1 = 枠ではない) / magnifier frame colour (-1 = not a frame pixel) | ||
| 96 | if (uMagnifier) { | ||
| 97 | // 画面の中央の96×54ピクセルを、右下の384×216ピクセルに4倍で(最近傍:1ピクセルが4×4の四角になる) | ||
| 98 | // The central 96 × 54 pixels, shown 4× in 384 × 216 pixels at the bottom right (nearest: each pixel becomes a | ||
| 99 | // 4 × 4 block) | ||
| 100 | vec2 size = vec2(textureSize(uScene, 0)); | ||
| 101 | vec2 source = vec2(96.0, 54.0); | ||
| 102 | vec2 inset0 = vec2(size.x - 16.0 - 4.0 * source.x, 16.0); | ||
| 103 | vec2 local = (gl_FragCoord.xy - inset0) / 4.0; | ||
| 104 | vec2 source0 = floor(0.5 * (size - source)); | ||
| 105 | if (all(greaterThanEqual(local, vec2(0.0))) && all(lessThan(local, source))) { | ||
| 106 | uv = (source0 + floor(local) + 0.5) / size; | ||
| 107 | } else if (all(greaterThanEqual(local, vec2(-0.75))) && all(lessThan(local, source + 0.75))) { | ||
| 108 | frame = vec3(1.0); // 拡大部分の白い枠 / white frame around the inset | ||
| 109 | } | ||
| 110 | // 拡大している場所の枠(黄色) / a yellow frame around the enlarged region | ||
| 111 | vec2 p = gl_FragCoord.xy - source0; | ||
| 112 | if (all(greaterThanEqual(p, vec2(-2.0))) && all(lessThan(p, source + 2.0)) && | ||
| 113 | !(all(greaterThanEqual(p, vec2(0.0))) && all(lessThan(p, source)))) | ||
| 114 | frame = vec3(1.0, 0.85, 0.2); | ||
| 115 | } | 86 | } |
| 116 | vec3 color = frame.x >= 0.0 ? frame : shade(uv); | 87 | // uGammaMode 1(GL_FRAMEBUFFER_SRGB)と2(なし)はリニアのまま出す:1ではGPUが書くときに変換する |
| 117 | // アルファは必ず1(画面が半透明にならないように) / alpha is always 1 (so the window never turns translucent) | 88 | // Modes 1 (GL_FRAMEBUFFER_SRGB) and 2 (none) output linear values: with 1 the GPU encodes while writing |
| 118 | out_color = vec4(clamp(color, 0.0, 1.0), 1.0); | 89 | out_color = vec4(clamp(color, 0.0, 1.0), 1.0); |
| 119 | } | 90 | } |
ファイル: a/shaders/skybox.frag | b/shaders/skybox.frag
| 前 | 新 | ||
|---|---|---|---|
| @@ -6,10 +6,69 @@ in vec3 vDirection; | |||
| 6 | layout(binding = 3) uniform samplerCube uSkybox; | 6 | layout(binding = 3) uniform samplerCube uSkybox; |
| 7 | 7 | ||
| 8 | uniform vec3 uEnvironmentTint; // 空の明るさ(昼1、夜は暗く) / brightness of the sky (1 by day, dark at night) | 8 | uniform vec3 uEnvironmentTint; // 空の明るさ(昼1、夜は暗く) / brightness of the sky (1 by day, dark at night) |
| 9 | uniform float uSunRadiance = 60.0; // 太陽の円盤の明るさ(平行光源の色の倍数、第21章) / the sun disc's brightness | ||
| 10 | // (a multiple of the directional light's colour, chapter 21) | ||
| 11 | |||
| 12 | struct DirectionalLight { | ||
| 13 | vec3 direction; | ||
| 14 | vec3 color; | ||
| 15 | }; | ||
| 16 | struct PointLight { | ||
| 17 | vec3 position; | ||
| 18 | vec3 color; | ||
| 19 | vec3 attenuation; | ||
| 20 | }; | ||
| 21 | struct SpotLight { | ||
| 22 | vec3 position; | ||
| 23 | float cosInner; | ||
| 24 | vec3 direction; | ||
| 25 | float cosOuter; | ||
| 26 | vec3 color; | ||
| 27 | vec3 attenuation; | ||
| 28 | }; | ||
| 29 | // 光(結合点1):太陽の向きと色を使う。phong.fragと同じ宣言 / the lights (binding 1): for the sun's direction and | ||
| 30 | // colour. The same declaration as phong.frag | ||
| 31 | layout(std140, binding = 1) uniform Lights { | ||
| 32 | DirectionalLight uDirLight; | ||
| 33 | PointLight uPointLights[8]; | ||
| 34 | SpotLight uSpotLights[4]; | ||
| 35 | vec3 uAmbient; | ||
| 36 | int uPointLightCount; | ||
| 37 | int uSpotLightCount; | ||
| 38 | }; | ||
| 9 | 39 | ||
| 10 | layout(location = 0) out vec4 out_color; | 40 | layout(location = 0) out vec4 out_color; |
| 11 | 41 | ||
| 42 | // 後処理の設定(ユニフォームバッファ、結合点3、std140、第21章)。使う全部のシェーダーで同じ宣言(C++ではPostBlock) | ||
| 43 | // Post-processing settings (uniform buffer, binding 3, std140, chapter 21). The same declaration in every shader that | ||
| 44 | // uses it (PostBlock in C++) | ||
| 45 | layout(std140, binding = 3) uniform Post { | ||
| 46 | float uExposure; // 明るさの倍率 / brightness multiplier | ||
| 47 | float uBloomStrength; // ブルームの強さ / bloom strength | ||
| 48 | float uBloomThreshold; // これより明るい部分が光る(リニアのHDR値) / brighter than this glows (linear HDR value) | ||
| 49 | int uToneMapper; // 0 = クランプ / clamp, 1 = Reinhard, 2 = ACES | ||
| 50 | int uGammaMode; // 0 = シェーダー / shader, 1 = GL_FRAMEBUFFER_SRGB, 2 = なし / none, 3 = 二重 / double | ||
| 51 | int uPostView; // 0 = 完成 / final, 1 = ブルームなし / no bloom, 2 = 明るい部分 / bright part, 3 = ブルーム / bloom | ||
| 52 | int uPostPad0, uPostPad1; // std140の大きさを32バイトにそろえる / pads the block to 32 bytes | ||
| 53 | }; | ||
| 54 | |||
| 55 | // ブルーム用の2つ目の出力(MRT、GL_COLOR_ATTACHMENT1):しきい値より明るい部分だけ(色合いは保つ) | ||
| 56 | // The second output for bloom (MRT, GL_COLOR_ATTACHMENT1): only what is brighter than the threshold (hue kept) | ||
| 57 | layout(location = 1) out vec4 out_bright; | ||
| 58 | vec3 brightPart(vec3 c) { | ||
| 59 | float l = dot(c, vec3(0.2126, 0.7152, 0.0722)); // 輝度 / luminance | ||
| 60 | return c * (max(l - uBloomThreshold, 0.0) / max(l, 1e-4)); | ||
| 61 | } | ||
| 62 | |||
| 12 | void main() { | 63 | void main() { |
| 13 | // 方向は正規化しなくて良い:一番大きい成分で面が決まる / no need to normalize: the largest component picks the face | 64 | vec3 d = normalize(vDirection); |
| 14 | out_color = vec4(uEnvironmentTint * texture(uSkybox, vDirection).rgb, 1.0); | 65 | // 空の画像はLDR(sRGB、最大1):太陽の円盤も1で切れている。HDRの太陽を光の向きに描き足す |
| 66 | // The sky images are LDR (sRGB, at most 1): even the sun disc is clipped at 1. Add an HDR sun in the light's direction | ||
| 67 | vec3 color = uEnvironmentTint * texture(uSkybox, d).rgb; | ||
| 68 | float c = dot(d, -uDirLight.direction); | ||
| 69 | float disc = smoothstep(cos(radians(1.6)), cos(radians(1.2)), c); | ||
| 70 | float glow = 0.02 * exp((c - 1.0) * 300.0); | ||
| 71 | color += uDirLight.color * (uSunRadiance * disc + uSunRadiance * glow); | ||
| 72 | out_color = vec4(color, 1.0); | ||
| 73 | out_bright = vec4(brightPart(color), 1.0); | ||
| 15 | } | 74 | } |
ファイル: a/shaders/unlit.frag | b/shaders/unlit.frag
| 前 | 新 | ||
|---|---|---|---|
| @@ -1,9 +1,32 @@ | |||
| 1 | #version 460 core | 1 | #version 460 core |
| 2 | // ライティングなしの一色(光源の目印用) / one colour without lighting (for light markers) | 2 | // ライティングなしの一色(光源の目印用)。HDRなので1より明るい色も使える(第21章) |
| 3 | // One colour without lighting (for light markers). HDR, so colours brighter than 1 work (chapter 21) | ||
| 3 | uniform vec3 uColor; | 4 | uniform vec3 uColor; |
| 4 | 5 | ||
| 5 | layout(location = 0) out vec4 out_color; | 6 | layout(location = 0) out vec4 out_color; |
| 6 | 7 | ||
| 8 | // 後処理の設定(ユニフォームバッファ、結合点3、std140、第21章)。使う全部のシェーダーで同じ宣言(C++ではPostBlock) | ||
| 9 | // Post-processing settings (uniform buffer, binding 3, std140, chapter 21). The same declaration in every shader that | ||
| 10 | // uses it (PostBlock in C++) | ||
| 11 | layout(std140, binding = 3) uniform Post { | ||
| 12 | float uExposure; // 明るさの倍率 / brightness multiplier | ||
| 13 | float uBloomStrength; // ブルームの強さ / bloom strength | ||
| 14 | float uBloomThreshold; // これより明るい部分が光る(リニアのHDR値) / brighter than this glows (linear HDR value) | ||
| 15 | int uToneMapper; // 0 = クランプ / clamp, 1 = Reinhard, 2 = ACES | ||
| 16 | int uGammaMode; // 0 = シェーダー / shader, 1 = GL_FRAMEBUFFER_SRGB, 2 = なし / none, 3 = 二重 / double | ||
| 17 | int uPostView; // 0 = 完成 / final, 1 = ブルームなし / no bloom, 2 = 明るい部分 / bright part, 3 = ブルーム / bloom | ||
| 18 | int uPostPad0, uPostPad1; // std140の大きさを32バイトにそろえる / pads the block to 32 bytes | ||
| 19 | }; | ||
| 20 | |||
| 21 | // ブルーム用の2つ目の出力(MRT、GL_COLOR_ATTACHMENT1):しきい値より明るい部分だけ(色合いは保つ) | ||
| 22 | // The second output for bloom (MRT, GL_COLOR_ATTACHMENT1): only what is brighter than the threshold (hue kept) | ||
| 23 | layout(location = 1) out vec4 out_bright; | ||
| 24 | vec3 brightPart(vec3 c) { | ||
| 25 | float l = dot(c, vec3(0.2126, 0.7152, 0.0722)); // 輝度 / luminance | ||
| 26 | return c * (max(l - uBloomThreshold, 0.0) / max(l, 1e-4)); | ||
| 27 | } | ||
| 28 | |||
| 7 | void main() { | 29 | void main() { |
| 8 | out_color = vec4(uColor, 1.0); | 30 | out_color = vec4(uColor, 1.0); |
| 31 | out_bright = vec4(brightPart(uColor), 1.0); | ||
| 9 | } | 32 | } |
ファイル: a/src/cubemap.cc | b/src/cubemap.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -27,7 +27,7 @@ void Cubemap::uploadFace(int face, const unsigned char *rgba) { | |||
| 27 | glPixelStorei(GL_UNPACK_ALIGNMENT, 4); | 27 | glPixelStorei(GL_UNPACK_ALIGNMENT, 4); |
| 28 | } | 28 | } |
| 29 | 29 | ||
| 30 | std::optional<Cubemap> Cubemap::load(const std::array<std::string, 6> &paths) { | 30 | std::optional<Cubemap> Cubemap::load(const std::array<std::string, 6> &paths, bool srgb) { |
| 31 | // キューブマップの面は上の行から(RenderManの決まり)。反転しない | 31 | // キューブマップの面は上の行から(RenderManの決まり)。反転しない |
| 32 | // Cube-map faces start at the top row (the RenderMan convention). Do not flip | 32 | // Cube-map faces start at the top row (the RenderMan convention). Do not flip |
| 33 | stbi_set_flip_vertically_on_load(0); | 33 | stbi_set_flip_vertically_on_load(0); |
| @@ -49,7 +49,7 @@ std::optional<Cubemap> Cubemap::load(const std::array<std::string, 6> &paths) { | |||
| 49 | if (face == 0) { | 49 | if (face == 0) { |
| 50 | int levels = 1; | 50 | int levels = 1; |
| 51 | while ((width >> levels) > 0) ++levels; | 51 | while ((width >> levels) > 0) ++levels; |
| 52 | cube = Cubemap(width, GL_RGBA8, levels); | 52 | cube = Cubemap(width, srgb ? GL_SRGB8_ALPHA8 : GL_RGBA8, levels); |
| 53 | } | 53 | } |
| 54 | cube.uploadFace(face, pixels); | 54 | cube.uploadFace(face, pixels); |
| 55 | stbi_image_free(pixels); | 55 | stbi_image_free(pixels); |
| @@ -58,10 +58,10 @@ std::optional<Cubemap> Cubemap::load(const std::array<std::string, 6> &paths) { | |||
| 58 | return cube; | 58 | return cube; |
| 59 | } | 59 | } |
| 60 | 60 | ||
| 61 | std::optional<Cubemap> Cubemap::loadDirectory(const std::string &dir, const std::string &extension) { | 61 | std::optional<Cubemap> Cubemap::loadDirectory(const std::string &dir, const std::string &extension, bool srgb) { |
| 62 | std::array<std::string, 6> paths; | 62 | std::array<std::string, 6> paths; |
| 63 | for (int i = 0; i < 6; ++i) paths[static_cast<size_t>(i)] = dir + "/" + kCubeFaceNames[i] + extension; | 63 | for (int i = 0; i < 6; ++i) paths[static_cast<size_t>(i)] = dir + "/" + kCubeFaceNames[i] + extension; |
| 64 | return load(paths); | 64 | return load(paths, srgb); |
| 65 | } | 65 | } |
| 66 | 66 | ||
| 67 | Cubemap::~Cubemap() { | 67 | Cubemap::~Cubemap() { |
ファイル: a/src/cubemap.hh | b/src/cubemap.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -30,9 +30,12 @@ public: | |||
| 30 | // Loads six image files (order +X, -X, +Y, -Y, +Z, -Z). No vertical flip: cube-map faces start at the top row. | 30 | // Loads six image files (order +X, -X, +Y, -Y, +Z, -Z). No vertical flip: cube-map faces start at the top row. |
| 31 | // All must be squares of the same size. Builds mipmaps (for blurry reflections). On failure prints the error | 31 | // All must be squares of the same size. Builds mipmaps (for blurry reflections). On failure prints the error |
| 32 | // and returns std::nullopt. | 32 | // and returns std::nullopt. |
| 33 | static std::optional<Cubemap> load(const std::array<std::string, 6> &paths); | 33 | // srgb = true:色の画像なのでGL_SRGB8_ALPHA8にする(第21章。空はtrue) / srgb = true: a colour image, stored as |
| 34 | // GL_SRGB8_ALPHA8 (chapter 21; true for skies) | ||
| 35 | static std::optional<Cubemap> load(const std::array<std::string, 6> &paths, bool srgb = false); | ||
| 34 | // dir/px.png, dir/nx.png … を読む / loads dir/px.png, dir/nx.png, ... | 36 | // dir/px.png, dir/nx.png … を読む / loads dir/px.png, dir/nx.png, ... |
| 35 | static std::optional<Cubemap> loadDirectory(const std::string &dir, const std::string &extension = ".png"); | 37 | static std::optional<Cubemap> loadDirectory(const std::string &dir, const std::string &extension = ".png", |
| 38 | bool srgb = false); | ||
| 36 | 39 | ||
| 37 | // 面face(0〜5)のミップマップ0段目を書き換える(RGBA8) / replaces mip level 0 of face `face` (0..5, RGBA8) | 40 | // 面face(0〜5)のミップマップ0段目を書き換える(RGBA8) / replaces mip level 0 of face `face` (0..5, RGBA8) |
| 38 | void uploadFace(int face, const unsigned char *rgba); | 41 | void uploadFace(int face, const unsigned char *rgba); |
ファイル: a/src/framebuffer.cc | b/src/framebuffer.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -1,5 +1,6 @@ | |||
| 1 | #include "framebuffer.hh" | 1 | #include "framebuffer.hh" |
| 2 | 2 | ||
| 3 | #include <algorithm> | ||
| 3 | #include <cstdio> | 4 | #include <cstdio> |
| 4 | #include <utility> | 5 | #include <utility> |
| 5 | 6 | ||
| @@ -11,22 +12,39 @@ Framebuffer::Framebuffer(int width, int height, const FramebufferSpec &s) : w(wi | |||
| 11 | 12 | ||
| 12 | void Framebuffer::createAttachments() { | 13 | void Framebuffer::createAttachments() { |
| 13 | actualSamples = 0; | 14 | actualSamples = 0; |
| 14 | if (spec.colorFormat != 0 && spec.samples > 0) { | 15 | int count = colorCount(); |
| 15 | // マルチサンプルの色:ピクセルごとにsamples個の色を持つレンダーバッファ。テクスチャのように読めない | 16 | if (count > kMaxColorAttachments) { |
| 16 | // Multisampled colour: a renderbuffer with `samples` colours per pixel. It cannot be read like a texture | 17 | fprintf(stderr, "色の付け先が多すぎる / too many colour attachments: %d (max %d)\n", count, kMaxColorAttachments); |
| 17 | glCreateRenderbuffers(1, &colorSamples); | 18 | count = spec.colorCount = kMaxColorAttachments; |
| 18 | glNamedRenderbufferStorageMultisample(colorSamples, spec.samples, spec.colorFormat, w, h); | 19 | } |
| 19 | glNamedFramebufferRenderbuffer(fbo, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, colorSamples); | 20 | GLenum drawBuffers[kMaxColorAttachments]; |
| 20 | // ドライバーは要求以上で一番近い数を選ぶ(llvmpipeは4だけ:2を頼んでも4になる) | 21 | for (int i = 0; i < count; ++i) { |
| 21 | // The driver picks the nearest supported count at or above the request (llvmpipe has only 4: asking for 2 gives 4) | 22 | GLenum attachment = GL_COLOR_ATTACHMENT0 + static_cast<GLenum>(i); |
| 22 | glGetNamedRenderbufferParameteriv(colorSamples, GL_RENDERBUFFER_SAMPLES, &actualSamples); | 23 | drawBuffers[i] = attachment; |
| 23 | } else if (spec.colorFormat != 0) { | 24 | if (spec.samples > 0) { |
| 24 | // 色:ミップマップなしのテクスチャ。端の外を読まないようにCLAMP_TO_EDGE(ぼかしのカーネルが端で反対側を拾わない) | 25 | // マルチサンプルの色:ピクセルごとにsamples個の色を持つレンダーバッファ。テクスチャのように読めない |
| 25 | // Colour: a texture without mipmaps. CLAMP_TO_EDGE so blur kernels at the border do not pick up the opposite side | 26 | // Multisampled colour: a renderbuffer with `samples` colours per pixel. It cannot be read like a texture |
| 26 | colorTexture = Texture2D(w, h, spec.colorFormat, 1); | 27 | GLuint &rb = colorSamples[static_cast<size_t>(i)]; |
| 27 | colorTexture.setWrap(GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE); | 28 | glCreateRenderbuffers(1, &rb); |
| 28 | colorTexture.setFilter(GL_LINEAR, GL_LINEAR); | 29 | glNamedRenderbufferStorageMultisample(rb, spec.samples, spec.colorFormat, w, h); |
| 29 | glNamedFramebufferTexture(fbo, GL_COLOR_ATTACHMENT0, colorTexture.id(), 0); // 0 = ミップマップの段 / mip level | 30 | glNamedFramebufferRenderbuffer(fbo, attachment, GL_RENDERBUFFER, rb); |
| 31 | // ドライバーは要求以上で一番近い数を選ぶ(llvmpipeは4だけ:2を頼んでも4になる) | ||
| 32 | // The driver picks the nearest supported count at or above the request (llvmpipe has only 4: asking for 2 gives 4) | ||
| 33 | glGetNamedRenderbufferParameteriv(rb, GL_RENDERBUFFER_SAMPLES, &actualSamples); | ||
| 34 | } else { | ||
| 35 | // 色:ミップマップなしのテクスチャ。端の外を読まないようにCLAMP_TO_EDGE(ぼかしのカーネルが端で反対側を拾わない) | ||
| 36 | // Colour: a texture without mipmaps. CLAMP_TO_EDGE so blur kernels at the border do not pick up the opposite side | ||
| 37 | Texture2D &t = colorTextures[static_cast<size_t>(i)]; | ||
| 38 | t = Texture2D(w, h, spec.colorFormat, 1); | ||
| 39 | t.setWrap(GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE); | ||
| 40 | t.setFilter(GL_LINEAR, GL_LINEAR); | ||
| 41 | glNamedFramebufferTexture(fbo, attachment, t.id(), 0); // 0 = ミップマップの段 / mip level | ||
| 42 | } | ||
| 43 | } | ||
| 44 | if (count > 0) { | ||
| 45 | // フラグメントシェーダーの出力location iを、i番目の付け先に書く(既定ではATTACHMENT0だけ) | ||
| 46 | // Fragment output location i goes to attachment i (by default only ATTACHMENT0 is written) | ||
| 47 | glNamedFramebufferDrawBuffers(fbo, count, drawBuffers); | ||
| 30 | } else { | 48 | } else { |
| 31 | // 色を描かない(例:影の深度だけ、第23章) / no colour drawn (e.g. shadow depth only, chapter 23) | 49 | // 色を描かない(例:影の深度だけ、第23章) / no colour drawn (e.g. shadow depth only, chapter 23) |
| 32 | glNamedFramebufferDrawBuffer(fbo, GL_NONE); | 50 | glNamedFramebufferDrawBuffer(fbo, GL_NONE); |
| @@ -52,10 +70,13 @@ void Framebuffer::createAttachments() { | |||
| 52 | } | 70 | } |
| 53 | 71 | ||
| 54 | void Framebuffer::destroyAttachments() { | 72 | void Framebuffer::destroyAttachments() { |
| 55 | colorTexture = Texture2D(); // 古いテクスチャを消す / deletes the old texture | 73 | for (Texture2D &t : colorTextures) t = Texture2D(); // 古いテクスチャを消す / deletes the old textures |
| 74 | for (GLuint &rb : colorSamples) { | ||
| 75 | if (rb) glDeleteRenderbuffers(1, &rb); | ||
| 76 | rb = 0; | ||
| 77 | } | ||
| 56 | if (depthStencil) glDeleteRenderbuffers(1, &depthStencil); | 78 | if (depthStencil) glDeleteRenderbuffers(1, &depthStencil); |
| 57 | if (colorSamples) glDeleteRenderbuffers(1, &colorSamples); | 79 | depthStencil = 0; |
| 58 | depthStencil = colorSamples = 0; | ||
| 59 | } | 80 | } |
| 60 | 81 | ||
| 61 | bool Framebuffer::resize(int width, int height) { | 82 | bool Framebuffer::resize(int width, int height) { |
| @@ -78,7 +99,25 @@ void Framebuffer::blitTo(const Framebuffer &target, GLbitfield mask, GLenum filt | |||
| 78 | // 読む側の四角形 → 書く側の四角形。読む色はglNamedFramebufferReadBuffer(既定はGL_COLOR_ATTACHMENT0) | 99 | // 読む側の四角形 → 書く側の四角形。読む色はglNamedFramebufferReadBuffer(既定はGL_COLOR_ATTACHMENT0) |
| 79 | // source rectangle → destination rectangle. The colour read comes from glNamedFramebufferReadBuffer | 100 | // source rectangle → destination rectangle. The colour read comes from glNamedFramebufferReadBuffer |
| 80 | // (GL_COLOR_ATTACHMENT0 by default) | 101 | // (GL_COLOR_ATTACHMENT0 by default) |
| 81 | glBlitNamedFramebuffer(fbo, target.fbo, 0, 0, w, h, 0, 0, target.w, target.h, mask, filter); | 102 | int colors = (mask & GL_COLOR_BUFFER_BIT) ? std::min(colorCount(), target.colorCount()) : 0; |
| 103 | if (colors <= 1) { | ||
| 104 | glBlitNamedFramebuffer(fbo, target.fbo, 0, 0, w, h, 0, 0, target.w, target.h, mask, filter); | ||
| 105 | return; | ||
| 106 | } | ||
| 107 | // 複数の色:読む色(ReadBuffer)と書く色(DrawBuffer)を一つずつ選んでコピーし、最後に元に戻す | ||
| 108 | // Several colours: pick one read buffer and one draw buffer at a time, copy, and restore them afterwards | ||
| 109 | for (int i = 0; i < colors; ++i) { | ||
| 110 | GLenum attachment = GL_COLOR_ATTACHMENT0 + static_cast<GLenum>(i); | ||
| 111 | glNamedFramebufferReadBuffer(fbo, attachment); | ||
| 112 | glNamedFramebufferDrawBuffer(target.fbo, attachment); | ||
| 113 | // 深度とステンシルは1回目だけ / depth and stencil only the first time | ||
| 114 | GLbitfield m = i == 0 ? mask : GL_COLOR_BUFFER_BIT; | ||
| 115 | glBlitNamedFramebuffer(fbo, target.fbo, 0, 0, w, h, 0, 0, target.w, target.h, m, filter); | ||
| 116 | } | ||
| 117 | GLenum drawBuffers[kMaxColorAttachments]; | ||
| 118 | for (int i = 0; i < target.colorCount(); ++i) drawBuffers[i] = GL_COLOR_ATTACHMENT0 + static_cast<GLenum>(i); | ||
| 119 | glNamedFramebufferDrawBuffers(target.fbo, target.colorCount(), drawBuffers); | ||
| 120 | glNamedFramebufferReadBuffer(fbo, GL_COLOR_ATTACHMENT0); | ||
| 82 | } | 121 | } |
| 83 | 122 | ||
| 84 | void Framebuffer::bind() const { | 123 | void Framebuffer::bind() const { |
| @@ -98,7 +137,7 @@ Framebuffer::~Framebuffer() { | |||
| 98 | 137 | ||
| 99 | Framebuffer::Framebuffer(Framebuffer &&other) noexcept | 138 | Framebuffer::Framebuffer(Framebuffer &&other) noexcept |
| 100 | : fbo(std::exchange(other.fbo, 0)), depthStencil(std::exchange(other.depthStencil, 0)), | 139 | : fbo(std::exchange(other.fbo, 0)), depthStencil(std::exchange(other.depthStencil, 0)), |
| 101 | colorSamples(std::exchange(other.colorSamples, 0)), colorTexture(std::move(other.colorTexture)), w(other.w), | 140 | colorSamples(std::exchange(other.colorSamples, {})), colorTextures(std::move(other.colorTextures)), w(other.w), |
| 102 | h(other.h), actualSamples(other.actualSamples), spec(other.spec) {} | 141 | h(other.h), actualSamples(other.actualSamples), spec(other.spec) {} |
| 103 | 142 | ||
| 104 | Framebuffer &Framebuffer::operator=(Framebuffer &&other) noexcept { | 143 | Framebuffer &Framebuffer::operator=(Framebuffer &&other) noexcept { |
| @@ -107,8 +146,8 @@ Framebuffer &Framebuffer::operator=(Framebuffer &&other) noexcept { | |||
| 107 | if (fbo) glDeleteFramebuffers(1, &fbo); | 146 | if (fbo) glDeleteFramebuffers(1, &fbo); |
| 108 | fbo = std::exchange(other.fbo, 0); | 147 | fbo = std::exchange(other.fbo, 0); |
| 109 | depthStencil = std::exchange(other.depthStencil, 0); | 148 | depthStencil = std::exchange(other.depthStencil, 0); |
| 110 | colorSamples = std::exchange(other.colorSamples, 0); | 149 | colorSamples = std::exchange(other.colorSamples, {}); |
| 111 | colorTexture = std::move(other.colorTexture); | 150 | colorTextures = std::move(other.colorTextures); |
| 112 | w = other.w; | 151 | w = other.w; |
| 113 | h = other.h; | 152 | h = other.h; |
| 114 | actualSamples = other.actualSamples; | 153 | actualSamples = other.actualSamples; |
ファイル: a/src/framebuffer.hh | b/src/framebuffer.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -5,11 +5,20 @@ | |||
| 5 | 5 | ||
| 6 | #include <glad/glad.h> | 6 | #include <glad/glad.h> |
| 7 | 7 | ||
| 8 | #include <array> | ||
| 9 | |||
| 10 | constexpr int kMaxColorAttachments = 4; // GLは最低8を保証する / GL guarantees at least 8 | ||
| 11 | |||
| 8 | // フレームバッファに何を付けるか / what to attach to a framebuffer | 12 | // フレームバッファに何を付けるか / what to attach to a framebuffer |
| 9 | struct FramebufferSpec { | 13 | struct FramebufferSpec { |
| 10 | // 色のテクスチャの形式(0 = 色なし)。第21章のHDRではGL_RGBA16F | 14 | // 色のテクスチャの形式(0 = 色なし)。HDRではGL_RGBA16F(第21章) |
| 11 | // The colour texture's format (0 = no colour). GL_RGBA16F for HDR in chapter 21 | 15 | // The colour texture's format (0 = no colour). GL_RGBA16F for HDR (chapter 21) |
| 12 | GLenum colorFormat = GL_RGBA8; | 16 | GLenum colorFormat = GL_RGBA8; |
| 17 | // 色の付け先の数(MRT、第21章):GL_COLOR_ATTACHMENT0〜。全部colorFormat。シェーダーは | ||
| 18 | // layout(location = i) out … でi番目に書く(最大kMaxColorAttachments) | ||
| 19 | // The number of colour attachments (MRT, chapter 21): GL_COLOR_ATTACHMENT0... All use colorFormat. A shader writes | ||
| 20 | // the i-th one with layout(location = i) out ... (at most kMaxColorAttachments) | ||
| 21 | int colorCount = 1; | ||
| 13 | // 深度・ステンシルのレンダーバッファの形式(0 = なし)。サンプラーで読まないのでテクスチャでなくて良い | 22 | // 深度・ステンシルのレンダーバッファの形式(0 = なし)。サンプラーで読まないのでテクスチャでなくて良い |
| 14 | // The depth-stencil renderbuffer's format (0 = none). It is never sampled, so it need not be a texture | 23 | // The depth-stencil renderbuffer's format (0 = none). It is never sampled, so it need not be a texture |
| 15 | GLenum depthStencilFormat = GL_DEPTH24_STENCIL8; | 24 | GLenum depthStencilFormat = GL_DEPTH24_STENCIL8; |
| @@ -49,8 +58,10 @@ public: | |||
| 49 | 58 | ||
| 50 | // 描いた結果。シェーダーでサンプリングできる(マルチサンプルなら空:id() == 0) | 59 | // 描いた結果。シェーダーでサンプリングできる(マルチサンプルなら空:id() == 0) |
| 51 | // The result; can be sampled in a shader (empty for a multisampled framebuffer: id() == 0) | 60 | // The result; can be sampled in a shader (empty for a multisampled framebuffer: id() == 0) |
| 52 | const Texture2D &color() const { return colorTexture; } | 61 | // index = 何番目の色の付け先か(MRT) / index = which colour attachment (MRT) |
| 53 | Texture2D &color() { return colorTexture; } | 62 | 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)]; } | ||
| 64 | int colorCount() const { return spec.colorFormat != 0 ? spec.colorCount : 0; } | ||
| 54 | 65 | ||
| 55 | // 別のフレームバッファへコピーする(glBlitNamedFramebuffer)。マルチサンプルから普通のフレームバッファへなら | 66 | // 別のフレームバッファへコピーする(glBlitNamedFramebuffer)。マルチサンプルから普通のフレームバッファへなら |
| 56 | // サンプルの平均を取る:これがMSAAの「解決(resolve)」。大きさが違えば拡大・縮小する(filter = GL_LINEARなど。 | 67 | // サンプルの平均を取る:これがMSAAの「解決(resolve)」。大きさが違えば拡大・縮小する(filter = GL_LINEARなど。 |
| @@ -59,6 +70,9 @@ public: | |||
| 59 | // averages the samples: this is the MSAA "resolve". Different sizes are scaled (filter = GL_LINEAR etc.; only | 70 | // averages the samples: this is the MSAA "resolve". Different sizes are scaled (filter = GL_LINEAR etc.; only |
| 60 | // the same size is allowed from a multisampled source). mask = GL_COLOR_BUFFER_BIT, GL_DEPTH_BUFFER_BIT... (depth | 71 | // the same size is allowed from a multisampled source). mask = GL_COLOR_BUFFER_BIT, GL_DEPTH_BUFFER_BIT... (depth |
| 61 | // only with GL_NEAREST) | 72 | // only with GL_NEAREST) |
| 73 | // 色の付け先が複数あれば、一つずつ同じ番号の付け先へコピーする(ブリットは読む色を一つしか選べない) | ||
| 74 | // With several colour attachments each one is copied into the attachment with the same number (a blit can read | ||
| 75 | // only one colour buffer at a time) | ||
| 62 | void blitTo(const Framebuffer &target, GLbitfield mask = GL_COLOR_BUFFER_BIT, GLenum filter = GL_NEAREST) const; | 76 | void blitTo(const Framebuffer &target, GLbitfield mask = GL_COLOR_BUFFER_BIT, GLenum filter = GL_NEAREST) const; |
| 63 | 77 | ||
| 64 | GLuint id() const { return fbo; } | 78 | GLuint id() const { return fbo; } |
| @@ -75,8 +89,9 @@ private: | |||
| 75 | 89 | ||
| 76 | GLuint fbo = 0; | 90 | GLuint fbo = 0; |
| 77 | GLuint depthStencil = 0; // レンダーバッファ / renderbuffer | 91 | GLuint depthStencil = 0; // レンダーバッファ / renderbuffer |
| 78 | GLuint colorSamples = 0; // マルチサンプルの色のレンダーバッファ(第20章) / multisampled colour renderbuffer (chapter 20) | 92 | // マルチサンプルの色のレンダーバッファ(第20章) / multisampled colour renderbuffers (chapter 20) |
| 79 | Texture2D colorTexture; | 93 | std::array<GLuint, kMaxColorAttachments> colorSamples = {}; |
| 94 | std::array<Texture2D, kMaxColorAttachments> colorTextures; | ||
| 80 | int w = 0, h = 0; | 95 | int w = 0, h = 0; |
| 81 | int actualSamples = 0; | 96 | int actualSamples = 0; |
| 82 | FramebufferSpec spec; | 97 | FramebufferSpec spec; |
ファイル: a/src/main.cc | b/src/main.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -1,5 +1,5 @@ | |||
| 1 | // 第20章:アンチエイリアス | 1 | // 第21章:ガンマ補正とHDR |
| 2 | // Chapter 20: anti-aliasing | 2 | // Chapter 21: gamma correction and HDR |
| 3 | // | 3 | // |
| 4 | // 操作 / Controls: | 4 | // 操作 / Controls: |
| 5 | // WASD 前後左右に移動 / move forward, back, left, right | 5 | // WASD 前後左右に移動 / move forward, back, left, right |
| @@ -7,12 +7,13 @@ | |||
| 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 アンチエイリアス:なし → MSAA 2× → 4× → 8× → SSAA 2×2(GL_MAX_SAMPLESを超える数は飛ばす) | 10 | // = / - 露出を上げる・下げる(0.5段ずつ) / exposure up / down (half a stop each) |
| 11 | // anti-aliasing: off → MSAA 2× → 4× → 8× → SSAA 2×2 (counts above GL_MAX_SAMPLES are skipped) | 11 | // T トーンマッピング:なし(クランプ) → Reinhard → ACES / tone mapping: none (clamp) → Reinhard → ACES |
| 12 | // X FXAA風の後処理のオン・オフ / FXAA-like post-process on / off | 12 | // G ガンマ:シェーダー → GL_FRAMEBUFFER_SRGB → なし(間違い) → 二重(間違い) |
| 13 | // T 草のアルファトゥカバレッジのオン・オフ(MSAAのときだけ効く) / alpha to coverage for the grass on / off | 13 | // gamma: shader → GL_FRAMEBUFFER_SRGB → none (wrong) → double (wrong) |
| 14 | // (only works with MSAA) | 14 | // B ブルームのオン・オフ / bloom on / off |
| 15 | // Z 拡大鏡(画面の中央を4倍で右下に) / magnifier (the centre of the screen 4× at the bottom right) | 15 | // K 太陽を見る(電線の向こうの太陽にカメラを向ける) / look at the sun (aims the camera at the sun behind the wires) |
| 16 | // O 表示:完成 → ブルームなし → 明るい部分 → ぼかしたブルーム / view: final → no bloom → bright part → blurred bloom | ||
| 16 | // 1〜6 効果:なし / 反転 / グレースケール / シャープ / ぼかし / エッジ検出 | 17 | // 1〜6 効果:なし / 反転 / グレースケール / シャープ / ぼかし / エッジ検出 |
| 17 | // effect: none / invert / grayscale / sharpen / blur / edge detection | 18 | // effect: none / invert / grayscale / sharpen / blur / edge detection |
| 18 | // C FPS ⇔ オービットカメラ / FPS ⇔ orbit camera | 19 | // C FPS ⇔ オービットカメラ / FPS ⇔ orbit camera |
| @@ -23,11 +24,6 @@ | |||
| 23 | // Tab カーソルのキャプチャ切り替え / toggle cursor capture | 24 | // Tab カーソルのキャプチャ切り替え / toggle cursor capture |
| 24 | // R シェーダーを読み直す / reload the shaders | 25 | // R シェーダーを読み直す / reload the shaders |
| 25 | // Esc 終了 / quit | 26 | // Esc 終了 / quit |
| 26 | // | ||
| 27 | // ./build/game --direct [samples] フレームバッファを使わず、GLFW_SAMPLESでマルチサンプルにした画面に直接描く | ||
| 28 | // (後処理なし)。本物のGPUで画面のMSAAを試す用 | ||
| 29 | // draws straight into a screen made multisampled with GLFW_SAMPLES, without our | ||
| 30 | // framebuffers (no post-processing). For trying screen MSAA on a real GPU | ||
| 31 | #include "camera.hh" | 27 | #include "camera.hh" |
| 32 | #include "cubemap.hh" | 28 | #include "cubemap.hh" |
| 33 | #include "framebuffer.hh" | 29 | #include "framebuffer.hh" |
| @@ -45,8 +41,6 @@ | |||
| 45 | #include <cmath> | 41 | #include <cmath> |
| 46 | #include <cstdint> | 42 | #include <cstdint> |
| 47 | #include <cstdio> | 43 | #include <cstdio> |
| 48 | #include <cstdlib> | ||
| 49 | #include <cstring> | ||
| 50 | #include <optional> | 44 | #include <optional> |
| 51 | #include <vector> | 45 | #include <vector> |
| 52 | 46 | ||
| @@ -61,16 +55,13 @@ static const Placement kCrates[] = { | |||
| 61 | {{-6.0f, 0.0f, -1.0f}, 0.8f}, {{-5.2f, 0.0f, 3.5f}, -0.6f}, | 55 | {{-6.0f, 0.0f, -1.0f}, 0.8f}, {{-5.2f, 0.0f, 3.5f}, -0.6f}, |
| 62 | }; | 56 | }; |
| 63 | 57 | ||
| 64 | // アンチエイリアスの方法 / the anti-aliasing methods | 58 | constexpr int kMsaaSamples = 4; // 第20章 / chapter 20 |
| 65 | struct AaMode { | 59 | constexpr int kBloomPasses = 4; // 横+縦の組の数 / number of horizontal + vertical pairs |
| 66 | const char *name; | ||
| 67 | int samples; // MSAAのサンプル数(0 = MSAAなし) / MSAA samples (0 = no MSAA) | ||
| 68 | bool ssaa; // 縦横2倍で描いて縮める(スーパーサンプリング) / draw at twice the width and height, then shrink | ||
| 69 | }; | ||
| 70 | static const AaMode kAaModes[] = { | ||
| 71 | {"off", 0, false}, {"MSAA 2x", 2, false}, {"MSAA 4x", 4, false}, {"MSAA 8x", 8, false}, {"SSAA 2x2", 0, true}, | ||
| 72 | }; | ||
| 73 | 60 | ||
| 61 | static const char *const kToneMapperNames[] = {"none (clamp)", "Reinhard", "ACES"}; | ||
| 62 | static const char *const kGammaNames[] = {"shader (linear → sRGB in post.frag)", "GL_FRAMEBUFFER_SRGB", | ||
| 63 | "none (wrong: too dark)", "double (wrong: washed out)"}; | ||
| 64 | static const char *const kPostViewNames[] = {"final", "no bloom", "bright part (attachment 1)", "blurred bloom"}; | ||
| 74 | static const char *const kViewModeNames[] = {"all", "ambient", "diffuse", "specular", "emission", "normals"}; | 65 | static const char *const kViewModeNames[] = {"all", "ambient", "diffuse", "specular", "emission", "normals"}; |
| 75 | static const char *const kEffectNames[] = {"none", "invert", "grayscale", "sharpen", "blur", "edge detection"}; | 66 | static const char *const kEffectNames[] = {"none", "invert", "grayscale", "sharpen", "blur", "edge detection"}; |
| 76 | 67 | ||
| @@ -150,28 +141,51 @@ static std::vector<Mat4> makeWires() { | |||
| 150 | return wires; | 141 | return wires; |
| 151 | } | 142 | } |
| 152 | 143 | ||
| 153 | int main(int argc, char **argv) { | 144 | // 電線に吊るした提灯:発光する球。位置と色 / paper lanterns hanging from the wires: emissive spheres, position + colour |
| 154 | // --direct [samples]:画面のMSAA(GLFW_SAMPLES)を試す / try screen MSAA (GLFW_SAMPLES) | 145 | struct Lantern { |
| 155 | bool direct = argc > 1 && std::strcmp(argv[1], "--direct") == 0; | 146 | Vec3 position; |
| 156 | int windowSamples = direct ? (argc > 2 ? std::atoi(argv[2]) : 4) : 0; | 147 | Vec3 color; |
| 148 | }; | ||
| 149 | static std::vector<Lantern> makeLanterns() { | ||
| 150 | std::vector<Lantern> lanterns; | ||
| 151 | const Vec3 poles[] = {{-9.0f, 0.0f, -3.0f}, {-3.0f, 0.0f, -5.5f}, {4.0f, 0.0f, -5.0f}, {10.0f, 0.0f, -2.0f}}; | ||
| 152 | const Vec3 colors[] = {{1.0f, 0.45f, 0.12f}, {1.0f, 0.2f, 0.1f}, {1.0f, 0.75f, 0.3f}}; | ||
| 153 | int k = 0; | ||
| 154 | for (size_t i = 0; i + 1 < std::size(poles); ++i) { | ||
| 155 | Vec3 from = poles[i] + Vec3{0.0f, 4.04f, 0.0f}, to = poles[i + 1] + Vec3{0.0f, 4.04f, 0.0f}; | ||
| 156 | for (float t : {0.25f, 0.5f, 0.75f}) { | ||
| 157 | Vec3 p = lerp(from, to, t) - Vec3{0.0f, 1.6f * t * (1.0f - t) + 0.25f, 0.0f}; // 電線の下 / under the wire | ||
| 158 | lanterns.push_back({p, colors[k++ % 3]}); | ||
| 159 | } | ||
| 160 | } | ||
| 161 | return lanterns; | ||
| 162 | } | ||
| 157 | 163 | ||
| 164 | int main() { | ||
| 158 | Window window; | 165 | Window window; |
| 159 | // 普段は画面をマルチサンプルにしない:場面は自分のマルチサンプルのフレームバッファに描き、解決してから後処理する。 | 166 | if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 21")) return 1; |
| 160 | // 画面がマルチサンプルでも、全画面の三角形一つには意味がない | 167 | |
| 161 | // Normally the screen is not multisampled: the scene goes into our own multisampled framebuffer, which is | 168 | // 画面(既定のフレームバッファ)がsRGBか:GL_FRAMEBUFFER_SRGBが効くのはsRGBのときだけ |
| 162 | // resolved and then post-processed. A multisampled screen would be wasted on one fullscreen triangle | 169 | // Is the screen (the default framebuffer) sRGB? GL_FRAMEBUFFER_SRGB only has an effect if it is |
| 163 | if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 20", windowSamples)) return 1; | 170 | GLint encoding = 0; |
| 171 | glGetNamedFramebufferAttachmentParameteriv(0, GL_BACK_LEFT, GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING, &encoding); | ||
| 172 | printf("default framebuffer encoding: %s\n", encoding == GL_SRGB ? "sRGB" : "linear"); | ||
| 164 | 173 | ||
| 165 | std::optional<Shader> phong = Shader::load("shaders/phong.vert", "shaders/phong.frag"); | 174 | std::optional<Shader> phong = Shader::load("shaders/phong.vert", "shaders/phong.frag"); |
| 166 | std::optional<Shader> skybox = Shader::load("shaders/skybox.vert", "shaders/skybox.frag"); | 175 | std::optional<Shader> skybox = Shader::load("shaders/skybox.vert", "shaders/skybox.frag"); |
| 167 | std::optional<Shader> post = Shader::load("shaders/post.vert", "shaders/post.frag"); | 176 | std::optional<Shader> post = Shader::load("shaders/post.vert", "shaders/post.frag"); |
| 168 | std::optional<Cubemap> sky = Cubemap::loadDirectory("assets/textures/sky"); | 177 | std::optional<Shader> blur = Shader::load("shaders/post.vert", "shaders/blur.frag"); |
| 169 | std::optional<Texture2D> floorTexture = Texture2D::load("assets/textures/floor.png"); | 178 | std::optional<Shader> unlit = Shader::load("shaders/unlit.vert", "shaders/unlit.frag"); |
| 170 | std::optional<Texture2D> grassTexture = Texture2D::load("assets/textures/grass_blades.png"); | 179 | // 色の画像はsRGB(第21章):GPUが読むときにリニアに直す / colour images are sRGB (chapter 21): the GPU converts them |
| 171 | if (!phong || !skybox || !post || !sky || !floorTexture || !grassTexture) return 1; | 180 | // to linear when sampling |
| 181 | std::optional<Cubemap> sky = Cubemap::loadDirectory("assets/textures/sky", ".png", true); | ||
| 182 | std::optional<Texture2D> floorTexture = Texture2D::load("assets/textures/floor.png", {.srgb = true}); | ||
| 183 | std::optional<Texture2D> grassTexture = Texture2D::load("assets/textures/grass_blades.png", {.srgb = true}); | ||
| 184 | if (!phong || !skybox || !post || !blur || !unlit || !sky || !floorTexture || !grassTexture) return 1; | ||
| 172 | grassTexture->setWrap(GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE); | 185 | grassTexture->setWrap(GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE); |
| 173 | for (const Shader *s : {&*phong, &*skybox}) | 186 | for (const Shader *s : {&*phong, &*skybox, &*post, &*unlit}) |
| 174 | if (!s->checkUniformBlock("Camera", sizeof(CameraBlock)) || !s->checkUniformBlock("Lights", sizeof(LightsBlock))) | 187 | if (!s->checkUniformBlock("Camera", sizeof(CameraBlock)) || !s->checkUniformBlock("Lights", sizeof(LightsBlock)) || |
| 188 | !s->checkUniformBlock("Post", sizeof(PostBlock))) | ||
| 175 | return 1; | 189 | return 1; |
| 176 | 190 | ||
| 177 | std::optional<Model> scene = Model::load("assets/models/diorama.glb"); | 191 | std::optional<Model> scene = Model::load("assets/models/diorama.glb"); |
| @@ -187,44 +201,28 @@ int main(int argc, char **argv) { | |||
| 187 | 201 | ||
| 188 | UniformBuffer<CameraBlock> cameraUbo(kCameraBinding); | 202 | UniformBuffer<CameraBlock> cameraUbo(kCameraBinding); |
| 189 | UniformBuffer<LightsBlock> lightsUbo(kLightsBinding); | 203 | UniformBuffer<LightsBlock> lightsUbo(kLightsBinding); |
| 190 | 204 | UniformBuffer<PostBlock> postUbo(kPostBinding); | |
| 191 | // このGPUで使えるサンプル数の上限(llvmpipeは4) / the most samples this GPU supports (4 on llvmpipe) | 205 | |
| 192 | GLint maxSamples = 0; | 206 | // HDRのフレームバッファ(第21章):色はGL_RGBA16F(1より明るい値も負の値も持てる半精度の浮動小数点)。 |
| 193 | glGetIntegerv(GL_MAX_SAMPLES, &maxSamples); | 207 | // 付け先0 = 場面の色、付け先1 = ブルームにする明るい部分(MRT)。MSAA(第20章)で描いて sceneFbo に解決する |
| 194 | printf("GL_MAX_SAMPLES = %d\n", maxSamples); | 208 | // HDR framebuffers (chapter 21): the colour is GL_RGBA16F (half floats that can hold values above 1, and negative |
| 195 | std::vector<AaMode> aaModes; | 209 | // ones). Attachment 0 = the scene colour, attachment 1 = the bright part for bloom (MRT). Drawn with MSAA |
| 196 | for (const AaMode &m : kAaModes) | 210 | // (chapter 20) and resolved into sceneFbo |
| 197 | if (m.samples <= maxSamples) aaModes.push_back(m); | 211 | const FramebufferSpec hdrSpec = {.colorFormat = GL_RGBA16F, .colorCount = 2}; |
| 198 | size_t aaMode = 0; | 212 | FramebufferSpec msaaSpec = hdrSpec; |
| 199 | for (size_t i = 0; i < aaModes.size(); ++i) | 213 | msaaSpec.samples = kMsaaSamples; |
| 200 | if (aaModes[i].samples == 4) aaMode = i; // 既定はMSAA 4× / MSAA 4× by default | 214 | Framebuffer msaaFbo(window.width(), window.height(), msaaSpec); |
| 201 | 215 | Framebuffer sceneFbo(window.width(), window.height(), hdrSpec); | |
| 202 | // 場面を描くフレームバッファ:MSAAなら msaaFbo に描いて sceneFbo に解決する。SSAAなら縦横2倍の ssaaFbo に描いて | 216 | // ブルームのぼかしは半分の大きさで(4分の1のピクセル数:速く、広くぼける)。深度は要らない |
| 203 | // 縮める。なしなら sceneFbo に直接。後処理はいつも sceneFbo の色のテクスチャを読む | 217 | // The bloom blur runs at half size (a quarter of the pixels: faster, and it spreads further). No depth needed |
| 204 | // The framebuffers the scene is drawn into: with MSAA into msaaFbo, resolved into sceneFbo; with SSAA into the | 218 | const FramebufferSpec bloomSpec = {.colorFormat = GL_RGBA16F, .depthStencilFormat = 0}; |
| 205 | // double-size ssaaFbo, then shrunk; without AA straight into sceneFbo. Post-processing always reads sceneFbo's | 219 | Framebuffer bloomFbo[2] = {Framebuffer(window.width() / 2, window.height() / 2, bloomSpec), |
| 206 | // colour texture | 220 | Framebuffer(window.width() / 2, window.height() / 2, bloomSpec)}; |
| 207 | Framebuffer sceneFbo(window.width(), window.height()); | 221 | if (!msaaFbo.complete() || !sceneFbo.complete() || !bloomFbo[0].complete()) return 1; |
| 208 | Framebuffer msaaFbo, ssaaFbo; | ||
| 209 | auto createAaFramebuffer = [&] { | ||
| 210 | const AaMode &m = aaModes[aaMode]; | ||
| 211 | msaaFbo = Framebuffer(); | ||
| 212 | ssaaFbo = Framebuffer(); | ||
| 213 | if (m.samples > 0) { | ||
| 214 | msaaFbo = Framebuffer(window.width(), window.height(), {.samples = m.samples}); | ||
| 215 | printf("anti-aliasing: %s (requested %d samples, got %d)\n", m.name, m.samples, msaaFbo.samples()); | ||
| 216 | } else if (m.ssaa) { | ||
| 217 | ssaaFbo = Framebuffer(2 * window.width(), 2 * window.height()); | ||
| 218 | printf("anti-aliasing: %s (%d x %d)\n", m.name, ssaaFbo.width(), ssaaFbo.height()); | ||
| 219 | } else { | ||
| 220 | printf("anti-aliasing: %s\n", m.name); | ||
| 221 | } | ||
| 222 | }; | ||
| 223 | if (!direct) createAaFramebuffer(); | ||
| 224 | window.onResize = [&](int width, int height) { | 222 | window.onResize = [&](int width, int height) { |
| 223 | msaaFbo.resize(width, height); | ||
| 225 | sceneFbo.resize(width, height); | 224 | sceneFbo.resize(width, height); |
| 226 | if (msaaFbo.id()) msaaFbo.resize(width, height); // サンプル数はそのまま / keeps the sample count | 225 | for (Framebuffer &f : bloomFbo) f.resize(width / 2, height / 2); |
| 227 | if (ssaaFbo.id()) ssaaFbo.resize(2 * width, 2 * height); | ||
| 228 | }; | 226 | }; |
| 229 | glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS); | 227 | glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS); |
| 230 | 228 | ||
| @@ -237,8 +235,10 @@ int main(int argc, char **argv) { | |||
| 237 | orbit.distance = 11.0f; | 235 | orbit.distance = 11.0f; |
| 238 | orbit.yaw = radians(20.0f); | 236 | orbit.yaw = radians(20.0f); |
| 239 | 237 | ||
| 240 | bool useOrbit = false, fxaa = false, alphaToCoverage = false, magnifier = false; | 238 | bool useOrbit = false, bloomOn = true; |
| 241 | int viewMode = 0, effect = 0; | 239 | int viewMode = 0, effect = 0; |
| 240 | float exposureEv = 0.0f; // 露出(段、EV):倍率は2^EV / exposure in stops (EV): the multiplier is 2^EV | ||
| 241 | PostBlock postSettings; | ||
| 242 | bool night = false, flashlightOn = false, windmillMoving = true; | 242 | bool night = false, flashlightOn = false, windmillMoving = true; |
| 243 | float windmillTime = 0.0f; | 243 | float windmillTime = 0.0f; |
| 244 | window.setCursorCaptured(true); | 244 | window.setCursorCaptured(true); |
| @@ -246,7 +246,7 @@ int main(int argc, char **argv) { | |||
| 246 | window.onKey = [&](int key, int action, int /*mods*/) { | 246 | window.onKey = [&](int key, int action, int /*mods*/) { |
| 247 | if (action != GLFW_PRESS) return; | 247 | if (action != GLFW_PRESS) return; |
| 248 | if (key == GLFW_KEY_ESCAPE) window.close(); | 248 | if (key == GLFW_KEY_ESCAPE) window.close(); |
| 249 | if (key == GLFW_KEY_R && phong->reload() && skybox->reload() && post->reload()) | 249 | if (key == GLFW_KEY_R && phong->reload() && skybox->reload() && post->reload() && blur->reload() && unlit->reload()) |
| 250 | printf("シェーダーを読み直した / shaders reloaded\n"); | 250 | printf("シェーダーを読み直した / shaders reloaded\n"); |
| 251 | if (key == GLFW_KEY_TAB) window.setCursorCaptured(!window.cursorCaptured()); | 251 | if (key == GLFW_KEY_TAB) window.setCursorCaptured(!window.cursorCaptured()); |
| 252 | if (key == GLFW_KEY_C) { | 252 | if (key == GLFW_KEY_C) { |
| @@ -262,19 +262,34 @@ int main(int argc, char **argv) { | |||
| 262 | effect = key - GLFW_KEY_1; | 262 | effect = key - GLFW_KEY_1; |
| 263 | printf("effect: %s\n", kEffectNames[effect]); | 263 | printf("effect: %s\n", kEffectNames[effect]); |
| 264 | } | 264 | } |
| 265 | if (key == GLFW_KEY_M && !direct) { | 265 | if (key == GLFW_KEY_EQUAL || key == GLFW_KEY_MINUS) { |
| 266 | aaMode = (aaMode + 1) % aaModes.size(); | 266 | exposureEv += key == GLFW_KEY_EQUAL ? 0.5f : -0.5f; |
| 267 | createAaFramebuffer(); | 267 | printf("exposure: %+.1f EV (x%.3g)\n", exposureEv, std::exp2(exposureEv)); |
| 268 | } | ||
| 269 | if (key == GLFW_KEY_X) { | ||
| 270 | fxaa = !fxaa; | ||
| 271 | printf("FXAA: %s\n", fxaa ? "on" : "off"); | ||
| 272 | } | 268 | } |
| 273 | if (key == GLFW_KEY_T) { | 269 | if (key == GLFW_KEY_T) { |
| 274 | alphaToCoverage = !alphaToCoverage; | 270 | postSettings.toneMapper = (postSettings.toneMapper + 1) % 3; |
| 275 | printf("alpha to coverage: %s\n", alphaToCoverage ? "on" : "off"); | 271 | printf("tone mapping: %s\n", kToneMapperNames[postSettings.toneMapper]); |
| 272 | } | ||
| 273 | if (key == GLFW_KEY_G) { | ||
| 274 | postSettings.gammaMode = (postSettings.gammaMode + 1) % 4; | ||
| 275 | printf("gamma: %s\n", kGammaNames[postSettings.gammaMode]); | ||
| 276 | } | ||
| 277 | if (key == GLFW_KEY_B) { | ||
| 278 | bloomOn = !bloomOn; | ||
| 279 | printf("bloom: %s\n", bloomOn ? "on" : "off"); | ||
| 280 | } | ||
| 281 | if (key == GLFW_KEY_K) { | ||
| 282 | // 太陽の向き(0.5, 1, 0.35)の反対側から、電線越しに見上げる / look up through the wires from the side opposite the | ||
| 283 | // sun (direction (0.5, 1, 0.35)) | ||
| 284 | useOrbit = false; | ||
| 285 | fps.position = {-3.2f, 1.7f, -7.4f}; | ||
| 286 | fps.yaw = radians(125.0f); | ||
| 287 | fps.pitch = radians(42.0f); | ||
| 288 | } | ||
| 289 | if (key == GLFW_KEY_O) { | ||
| 290 | postSettings.view = (postSettings.view + 1) % 4; | ||
| 291 | printf("post view: %s\n", kPostViewNames[postSettings.view]); | ||
| 276 | } | 292 | } |
| 277 | if (key == GLFW_KEY_Z) magnifier = !magnifier; | ||
| 278 | if (key == GLFW_KEY_N) night = !night; | 293 | if (key == GLFW_KEY_N) night = !night; |
| 279 | if (key == GLFW_KEY_F) flashlightOn = !flashlightOn; | 294 | if (key == GLFW_KEY_F) flashlightOn = !flashlightOn; |
| 280 | if (key == GLFW_KEY_P) windmillMoving = !windmillMoving; | 295 | if (key == GLFW_KEY_P) windmillMoving = !windmillMoving; |
| @@ -298,14 +313,22 @@ int main(int argc, char **argv) { | |||
| 298 | std::vector<Mat4> fence = makeFence(); | 313 | std::vector<Mat4> fence = makeFence(); |
| 299 | std::vector<Mat4> wires = makeWires(); | 314 | std::vector<Mat4> wires = makeWires(); |
| 300 | Material woodMaterial; | 315 | Material woodMaterial; |
| 301 | woodMaterial.diffuse = {0.42f, 0.3f, 0.2f}; | 316 | // 手で選んだ色はsRGBの値(カラーピッカーの値):シェーダーはリニアで計算するので変換する |
| 317 | // Hand-picked colours are sRGB values (what a colour picker shows): the shaders compute in linear space, so convert | ||
| 318 | woodMaterial.diffuse = srgbToLinear(Vec3{0.42f, 0.3f, 0.2f}); | ||
| 302 | woodMaterial.specular = {0.05f, 0.05f, 0.05f}; | 319 | woodMaterial.specular = {0.05f, 0.05f, 0.05f}; |
| 303 | woodMaterial.shininess = 8.0f; | 320 | woodMaterial.shininess = 8.0f; |
| 304 | Material wireMaterial; | 321 | Material wireMaterial; |
| 305 | wireMaterial.diffuse = {0.04f, 0.04f, 0.045f}; | 322 | wireMaterial.diffuse = srgbToLinear(Vec3{0.04f, 0.04f, 0.045f}); |
| 306 | wireMaterial.specular = {0.3f, 0.3f, 0.3f}; | 323 | wireMaterial.specular = {0.3f, 0.3f, 0.3f}; |
| 307 | wireMaterial.shininess = 32.0f; | 324 | wireMaterial.shininess = 32.0f; |
| 308 | 325 | ||
| 326 | // 提灯:本体は暗い紙、発光で光る(1より明るい:HDR) / lanterns: dark paper, glowing through emission (brighter | ||
| 327 | // than 1: HDR) | ||
| 328 | std::vector<Lantern> lanterns = makeLanterns(); | ||
| 329 | Mesh sphereMesh = makeSphere(24, 12); | ||
| 330 | constexpr float kLanternGlow = 6.0f; | ||
| 331 | |||
| 309 | FullscreenTriangle fullscreen; | 332 | FullscreenTriangle fullscreen; |
| 310 | glEnable(GL_CULL_FACE); | 333 | glEnable(GL_CULL_FACE); |
| 311 | 334 | ||
| @@ -326,6 +349,17 @@ int main(int argc, char **argv) { | |||
| 326 | floorMesh.draw(); | 349 | floorMesh.draw(); |
| 327 | scene->draw(*phong, Mat4::identity(), white, ModelPass::Opaque); | 350 | scene->draw(*phong, Mat4::identity(), white, ModelPass::Opaque); |
| 328 | for (const Placement &c : kCrates) crate->draw(*phong, translate(c.position) * rotateY(c.angle), white, ModelPass::Opaque); | 351 | for (const Placement &c : kCrates) crate->draw(*phong, translate(c.position) * rotateY(c.angle), white, ModelPass::Opaque); |
| 352 | Material lanternMaterial; | ||
| 353 | lanternMaterial.diffuse = {0.05f, 0.03f, 0.02f}; | ||
| 354 | lanternMaterial.specular = {0.02f, 0.02f, 0.02f}; | ||
| 355 | for (const Lantern &l : lanterns) { | ||
| 356 | lanternMaterial.emission = kLanternGlow * l.color; | ||
| 357 | lanternMaterial.apply(*phong, white); | ||
| 358 | Mat4 model = translate(l.position) * scale({0.3f, 0.38f, 0.3f}); | ||
| 359 | phong->set("uModel", model); | ||
| 360 | phong->set("uNormalMatrix", normalMatrix(model)); | ||
| 361 | sphereMesh.draw(); | ||
| 362 | } | ||
| 329 | for (const std::vector<Mat4> *list : {&fence, &wires}) { | 363 | for (const std::vector<Mat4> *list : {&fence, &wires}) { |
| 330 | (list == &fence ? woodMaterial : wireMaterial).apply(*phong, white); | 364 | (list == &fence ? woodMaterial : wireMaterial).apply(*phong, white); |
| 331 | for (const Mat4 &m : *list) { | 365 | for (const Mat4 &m : *list) { |
| @@ -338,10 +372,8 @@ int main(int argc, char **argv) { | |||
| 338 | // 草:アルファトゥカバレッジならdiscardの代わりにサンプルの一部だけを覆う(MSAAのときだけ意味がある) | 372 | // 草:アルファトゥカバレッジならdiscardの代わりにサンプルの一部だけを覆う(MSAAのときだけ意味がある) |
| 339 | // Grass: with alpha to coverage, a fragment covers only some of the samples instead of being discarded (only | 373 | // Grass: with alpha to coverage, a fragment covers only some of the samples instead of being discarded (only |
| 340 | // meaningful with MSAA) | 374 | // meaningful with MSAA) |
| 341 | bool coverage = alphaToCoverage && !direct && aaModes[aaMode].samples > 0; | 375 | glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE); |
| 342 | if (direct) coverage = alphaToCoverage && window.samples() > 0; | 376 | phong->set("uAlphaToCoverage", 1); |
| 343 | if (coverage) glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE); | ||
| 344 | phong->set("uAlphaToCoverage", coverage ? 1 : 0); | ||
| 345 | grassMaterial.apply(*phong, white); | 377 | grassMaterial.apply(*phong, white); |
| 346 | glDisable(GL_CULL_FACE); | 378 | glDisable(GL_CULL_FACE); |
| 347 | for (const Placement &g : grass) { | 379 | for (const Placement &g : grass) { |
| @@ -393,7 +425,7 @@ int main(int argc, char **argv) { | |||
| 393 | scene->nodes[static_cast<size_t>(rotor)].rotation = | 425 | scene->nodes[static_cast<size_t>(rotor)].rotation = |
| 394 | Quat::fromAxisAngle({0.0f, 0.0f, 1.0f}, -0.8f * windmillTime) * rotorStart; | 426 | Quat::fromAxisAngle({0.0f, 0.0f, 1.0f}, -0.8f * windmillTime) * rotorStart; |
| 395 | 427 | ||
| 396 | float aspect = window.aspect(); | 428 | float aspect = static_cast<float>(sceneFbo.width()) / static_cast<float>(sceneFbo.height()); |
| 397 | CameraBlock camera; | 429 | CameraBlock camera; |
| 398 | camera.view = useOrbit ? orbit.view() : fps.view(); | 430 | camera.view = useOrbit ? orbit.view() : fps.view(); |
| 399 | camera.proj = useOrbit ? orbit.projection(aspect) : fps.projection(aspect); | 431 | camera.proj = useOrbit ? orbit.projection(aspect) : fps.projection(aspect); |
| @@ -402,65 +434,73 @@ int main(int argc, char **argv) { | |||
| 402 | cameraUbo.update(camera); | 434 | cameraUbo.update(camera); |
| 403 | Vec3 viewDir = useOrbit ? normalize(orbit.target - orbit.position()) : fps.front(); | 435 | Vec3 viewDir = useOrbit ? normalize(orbit.target - orbit.position()) : fps.front(); |
| 404 | 436 | ||
| 437 | // HDRなので光は1より明るくて良い:真昼の太陽は環境光の何倍も明るい | ||
| 438 | // With HDR, lights may be brighter than 1: the midday sun is many times brighter than the ambient light | ||
| 405 | LightSet lights; | 439 | LightSet lights; |
| 406 | if (!night) { | 440 | if (!night) { |
| 407 | lights.ambient = {0.28f, 0.30f, 0.34f}; | 441 | lights.ambient = {0.20f, 0.24f, 0.33f}; |
| 408 | lights.directional = {.direction = {-0.5f, -1.0f, -0.35f}, .color = {0.95f, 0.9f, 0.8f}}; | 442 | lights.directional = {.direction = {-0.5f, -1.0f, -0.35f}, .color = {2.6f, 2.45f, 2.2f}}; |
| 409 | } else { | 443 | } else { |
| 410 | lights.ambient = {0.03f, 0.035f, 0.05f}; | 444 | lights.ambient = {0.012f, 0.015f, 0.025f}; |
| 411 | lights.directional = {.direction = {-0.4f, -1.0f, -0.6f}, .color = {0.15f, 0.18f, 0.28f}}; | 445 | lights.directional = {.direction = {-0.4f, -1.0f, -0.6f}, .color = {0.05f, 0.07f, 0.12f}}; |
| 412 | if (lanternNode >= 0) { | 446 | if (lanternNode >= 0) { |
| 413 | Vec4 p = scene->nodeTransform(lanternNode) * Vec4{0.0f, 0.0f, 0.0f, 1.0f}; | 447 | Vec4 p = scene->nodeTransform(lanternNode) * Vec4{0.0f, 0.0f, 0.0f, 1.0f}; |
| 414 | lights.points.push_back({.position = {p.x, p.y, p.z}, .color = {2.6f, 1.6f, 0.7f}, .attenuation = kMediumRange}); | 448 | lights.points.push_back({.position = {p.x, p.y, p.z}, .color = {2.6f, 1.6f, 0.7f}, .attenuation = kMediumRange}); |
| 415 | } | 449 | } |
| 450 | // 真ん中の電線の提灯を点光源に(最大8個) / the lanterns on the middle span become point lights (8 at most) | ||
| 451 | for (size_t i = 3; i < 6; ++i) | ||
| 452 | lights.points.push_back({.position = lanterns[i].position, .color = 1.5f * lanterns[i].color, .attenuation = kMediumRange}); | ||
| 416 | } | 453 | } |
| 417 | if (flashlightOn) | 454 | if (flashlightOn) |
| 418 | lights.spots.push_back({.position = camera.viewPos, .direction = viewDir, .color = {1.0f, 0.95f, 0.85f}}); | 455 | lights.spots.push_back({.position = camera.viewPos, .direction = viewDir, .color = {1.0f, 0.95f, 0.85f}}); |
| 419 | lightsUbo.update(lights.toBlock()); | 456 | lightsUbo.update(lights.toBlock()); |
| 420 | environmentTint = night ? Vec3{0.05f, 0.06f, 0.11f} : Vec3{1.0f, 1.0f, 1.0f}; | 457 | environmentTint = night ? Vec3{0.02f, 0.025f, 0.05f} : Vec3{1.0f, 1.0f, 1.0f}; |
| 421 | 458 | postSettings.exposure = std::exp2(exposureEv); | |
| 422 | if (direct) { | 459 | postSettings.bloomStrength = bloomOn ? 0.08f : 0.0f; |
| 423 | // 画面に直接(GLFW_SAMPLESのMSAAは描くときに自動、解決はglfwSwapBuffersの中) / straight to the screen (the | 460 | postUbo.update(postSettings); |
| 424 | // GLFW_SAMPLES MSAA happens while drawing; the resolve happens inside glfwSwapBuffers) | ||
| 425 | Framebuffer::bindDefault(window.width(), window.height()); | ||
| 426 | drawScene(); | ||
| 427 | window.swapBuffers(); | ||
| 428 | continue; | ||
| 429 | } | ||
| 430 | 461 | ||
| 431 | //------------------------------------------------------------------ | 462 | //------------------------------------------------------------------ |
| 432 | // 1. 場面を描き、1サンプルの sceneFbo にまとめる / 1. draw the scene and bring it into the single-sample sceneFbo | 463 | // 1. 場面をHDR・MSAAで描き、解決する(色の付け先は2つとも) / 1. draw the scene in HDR with MSAA and resolve it |
| 464 | // (both colour attachments) | ||
| 433 | //------------------------------------------------------------------ | 465 | //------------------------------------------------------------------ |
| 434 | const AaMode &aa = aaModes[aaMode]; | 466 | msaaFbo.bind(); |
| 435 | if (aa.samples > 0) { | 467 | drawScene(); |
| 436 | // MSAA:マルチサンプルのフレームバッファに描き、ブリットで解決(各ピクセルのサンプルを平均) | 468 | msaaFbo.blitTo(sceneFbo); |
| 437 | // MSAA: draw into the multisampled framebuffer, then resolve it with a blit (average each pixel's samples) | 469 | |
| 438 | msaaFbo.bind(); | 470 | //------------------------------------------------------------------ |
| 439 | drawScene(); | 471 | // 2. ブルーム:明るい部分(付け先1)を半分の大きさで、横・縦・横・縦…とぼかす(ピンポン) |
| 440 | msaaFbo.blitTo(sceneFbo); | 472 | // 2. Bloom: blur the bright part (attachment 1) at half size, horizontally, vertically, ... (ping-pong) |
| 441 | } else if (aa.ssaa) { | 473 | //------------------------------------------------------------------ |
| 442 | // SSAA:縦横2倍(4倍のピクセル)で描き、GL_LINEARで半分に縮める=2×2ピクセルの平均 | 474 | glDisable(GL_DEPTH_TEST); |
| 443 | // SSAA: draw at twice the width and height (4× the pixels) and shrink with GL_LINEAR = the mean of 2 × 2 pixels | 475 | blur->use(); |
| 444 | ssaaFbo.bind(); | 476 | for (int pass = 0; pass < 2 * kBloomPasses; ++pass) { |
| 445 | drawScene(); | 477 | bloomFbo[pass % 2].bind(); |
| 446 | ssaaFbo.blitTo(sceneFbo, GL_COLOR_BUFFER_BIT, GL_LINEAR); | 478 | // 最初は全体の大きさの明るい部分から(線型補間で2×2の平均も取れる)、あとは前のパスの結果から |
| 447 | } else { | 479 | // The first pass reads the full-size bright part (linear filtering also averages 2 × 2), later passes read the |
| 448 | sceneFbo.bind(); | 480 | // previous result |
| 449 | drawScene(); | 481 | (pass == 0 ? sceneFbo.color(1) : bloomFbo[(pass + 1) % 2].color()).bind(0); |
| 482 | blur->set("uDirection", pass % 2 == 0 ? Vec2{1.0f, 0.0f} : Vec2{0.0f, 1.0f}); | ||
| 483 | fullscreen.draw(); | ||
| 450 | } | 484 | } |
| 451 | 485 | ||
| 452 | //------------------------------------------------------------------ | 486 | //------------------------------------------------------------------ |
| 453 | // 2. 画面へ:後処理は解決した後の画像に / 2. to the screen: post-processing works on the resolved image | 487 | // 3. 画面へ:場面+ブルーム、露出、トーンマッピング、sRGB / 3. to the screen: scene + bloom, exposure, tone |
| 488 | // mapping, sRGB | ||
| 454 | //------------------------------------------------------------------ | 489 | //------------------------------------------------------------------ |
| 455 | Framebuffer::bindDefault(window.width(), window.height()); | 490 | Framebuffer::bindDefault(window.width(), window.height()); |
| 456 | glDisable(GL_DEPTH_TEST); | 491 | // GammaMode 1と3:GPUが書くときにリニア→sRGBにする(画面がsRGBのときだけ効く) |
| 492 | // Gamma modes 1 and 3: the GPU converts linear → sRGB on write (only works if the screen is sRGB) | ||
| 493 | bool framebufferSrgb = postSettings.gammaMode == static_cast<int>(GammaMode::FramebufferSrgb) || | ||
| 494 | postSettings.gammaMode == static_cast<int>(GammaMode::Double); | ||
| 495 | if (framebufferSrgb) glEnable(GL_FRAMEBUFFER_SRGB); | ||
| 457 | post->use(); | 496 | post->use(); |
| 458 | post->set("uEffect", effect); | 497 | post->set("uEffect", effect); |
| 459 | post->set("uFlipX", 0); | 498 | post->set("uFlipX", 0); |
| 460 | post->set("uFxaa", fxaa ? 1 : 0); | 499 | sceneFbo.color(0).bind(0); |
| 461 | post->set("uMagnifier", magnifier ? 1 : 0); | 500 | bloomFbo[1].color().bind(1); // 最後の縦のパスの結果 / the result of the last vertical pass |
| 462 | sceneFbo.color().bind(0); | 501 | sceneFbo.color(1).bind(2); |
| 463 | fullscreen.draw(); | 502 | fullscreen.draw(); |
| 503 | glDisable(GL_FRAMEBUFFER_SRGB); | ||
| 464 | 504 | ||
| 465 | window.swapBuffers(); | 505 | window.swapBuffers(); |
| 466 | } | 506 | } |
ファイル: a/src/mathx.hh | b/src/mathx.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -4,6 +4,8 @@ | |||
| 4 | 4 | ||
| 5 | #include <linalg.hh> | 5 | #include <linalg.hh> |
| 6 | 6 | ||
| 7 | #include <cmath> | ||
| 8 | |||
| 7 | // 3×3行列。列優先:c[列]が一つの列ベクトル(Mat4と同じ)。法線行列に使う。 | 9 | // 3×3行列。列優先:c[列]が一つの列ベクトル(Mat4と同じ)。法線行列に使う。 |
| 8 | // 3×3 matrix. Column-major: c[column] is one column vector (like Mat4). Used for the normal matrix. | 10 | // 3×3 matrix. Column-major: c[column] is one column vector (like Mat4). Used for the normal matrix. |
| 9 | struct Mat3 { | 11 | struct Mat3 { |
| @@ -23,3 +25,9 @@ inline Mat3 toMat3(const Mat4 &m) { | |||
| 23 | // The normal matrix: the upper-left 3×3 of the model matrix's inverse transpose (Linear Algebra chapter 10). | 25 | // The normal matrix: the upper-left 3×3 of the model matrix's inverse transpose (Linear Algebra chapter 10). |
| 24 | // Transformed normals stay perpendicular to the surface even with non-uniform scaling. | 26 | // Transformed normals stay perpendicular to the surface even with non-uniform scaling. |
| 25 | inline Mat3 normalMatrix(const Mat4 &model) { return toMat3(transpose(inverse(model))); } | 27 | inline Mat3 normalMatrix(const Mat4 &model) { return toMat3(transpose(inverse(model))); } |
| 28 | |||
| 29 | // sRGBの色(カラーピッカーや画像編集ソフトの値、0〜1)→ リニア(第21章)。シェーダーの計算はリニアで行う | ||
| 30 | // An sRGB colour (the values of colour pickers and image editors, 0..1) → linear (chapter 21). Shaders compute in | ||
| 31 | // linear space | ||
| 32 | inline float srgbToLinear(float c) { return c <= 0.04045f ? c / 12.92f : std::pow((c + 0.055f) / 1.055f, 2.4f); } | ||
| 33 | inline Vec3 srgbToLinear(Vec3 c) { return {srgbToLinear(c.x), srgbToLinear(c.y), srgbToLinear(c.z)}; } | ||
ファイル: a/src/model.cc | b/src/model.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -165,6 +165,20 @@ std::optional<Model> Model::load(const std::string &path) { | |||
| 165 | // テクスチャ:埋め込まれたPNG/JPEGをデコードしてアップロード。glTFのUVは画像の左上が原点なので反転しない | 165 | // テクスチャ:埋め込まれたPNG/JPEGをデコードしてアップロード。glTFのUVは画像の左上が原点なので反転しない |
| 166 | // Textures: decode the embedded PNG/JPEG and upload it. glTF UVs start at the image's top-left: no flipping | 166 | // Textures: decode the embedded PNG/JPEG and upload it. glTF UVs start at the image's top-left: no flipping |
| 167 | std::vector<Vec4> averages(g.textures.size(), Vec4{1.0f, 1.0f, 1.0f, 1.0f}); | 167 | std::vector<Vec4> averages(g.textures.size(), Vec4{1.0f, 1.0f, 1.0f, 1.0f}); |
| 168 | // どのテクスチャが色か(第21章):ベースカラーと発光はsRGB、ほかはデータなのでリニア(glTFの仕様どおり) | ||
| 169 | // Which textures hold colours (chapter 21): base colour and emissive are sRGB, the rest is data and linear (as the | ||
| 170 | // glTF spec says) | ||
| 171 | std::vector<int> colorUse(g.textures.size(), 0), dataUse(g.textures.size(), 0); | ||
| 172 | auto mark = [](std::vector<int> &use, const GltfTextureRef &ref) { | ||
| 173 | if (ref.index >= 0 && static_cast<size_t>(ref.index) < use.size()) ++use[static_cast<size_t>(ref.index)]; | ||
| 174 | }; | ||
| 175 | for (const GltfMaterial &m : g.materials) { | ||
| 176 | mark(colorUse, m.baseColorTexture); | ||
| 177 | mark(colorUse, m.emissiveTexture); | ||
| 178 | mark(dataUse, m.metallicRoughnessTexture); | ||
| 179 | mark(dataUse, m.normalTexture); | ||
| 180 | mark(dataUse, m.occlusionTexture); | ||
| 181 | } | ||
| 168 | model.textures.resize(g.textures.size()); // 読めなかったものは空(id 0)=白 / ones that fail stay empty (id 0) = white | 182 | model.textures.resize(g.textures.size()); // 読めなかったものは空(id 0)=白 / ones that fail stay empty (id 0) = white |
| 169 | for (size_t i = 0; i < g.textures.size(); ++i) { | 183 | for (size_t i = 0; i < g.textures.size(); ++i) { |
| 170 | const GltfTexture &t = g.textures[i]; | 184 | const GltfTexture &t = g.textures[i]; |
| @@ -183,9 +197,14 @@ std::optional<Model> Model::load(const std::string &path) { | |||
| 183 | averages[i] = {static_cast<float>(sum[0] / pixels), static_cast<float>(sum[1] / pixels), | 197 | averages[i] = {static_cast<float>(sum[0] / pixels), static_cast<float>(sum[1] / pixels), |
| 184 | static_cast<float>(sum[2] / pixels), static_cast<float>(sum[3] / pixels)}; | 198 | static_cast<float>(sum[2] / pixels), static_cast<float>(sum[3] / pixels)}; |
| 185 | 199 | ||
| 186 | // 色のテクスチャは本当はsRGB(第21章で直す) / colour textures are really sRGB (fixed in chapter 21) | 200 | // 同じテクスチャを色とデータの両方に使うファイルもありうる:その場合はリニアにして警告する |
| 201 | // A file may use the same texture both as a colour and as data: then it stays linear, with a warning | ||
| 202 | bool srgb = colorUse[i] > 0 && dataUse[i] == 0; | ||
| 203 | if (colorUse[i] > 0 && dataUse[i] > 0) | ||
| 204 | fprintf(stderr, "%s: textures[%zu] は色にもデータにも使われている:リニアで読む / is used both as colour and as data: " | ||
| 205 | "loaded as linear\n", path.c_str(), i); | ||
| 187 | Texture2D texture = Texture2D::fromPixels(image->rgba.data(), image->width, image->height, | 206 | Texture2D texture = Texture2D::fromPixels(image->rgba.data(), image->width, image->height, |
| 188 | {.flipY = false, .mipmaps = true}); | 207 | {.flipY = false, .mipmaps = true, .srgb = srgb}); |
| 189 | if (t.sampler >= 0) { | 208 | if (t.sampler >= 0) { |
| 190 | // 値はGLのenumそのもの(読み込み時に検査済み)。0 = 指定なし / the values are GL enums (validated); 0 = not given | 209 | // 値はGLのenumそのもの(読み込み時に検査済み)。0 = 指定なし / the values are GL enums (validated); 0 = not given |
| 191 | const GltfSampler &s = g.samplers[static_cast<size_t>(t.sampler)]; | 210 | const GltfSampler &s = g.samplers[static_cast<size_t>(t.sampler)]; |
ファイル: a/src/texture.cc | b/src/texture.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -2,9 +2,22 @@ | |||
| 2 | 2 | ||
| 3 | #include <stb_image.h> | 3 | #include <stb_image.h> |
| 4 | 4 | ||
| 5 | #include <cmath> | ||
| 5 | #include <cstdio> | 6 | #include <cstdio> |
| 6 | #include <utility> | 7 | #include <utility> |
| 7 | 8 | ||
| 9 | // sRGBの8ビット値 → リニア(0〜1)。IEC 61966-2-1の式(2.2乗に近いが、暗いところは直線) | ||
| 10 | // An sRGB 8-bit value → linear (0..1). The IEC 61966-2-1 formula (close to a 2.2 power, a straight line near black) | ||
| 11 | static float srgbToLinear(unsigned char v) { | ||
| 12 | float c = static_cast<float>(v) / 255.0f; | ||
| 13 | return c <= 0.04045f ? c / 12.92f : std::pow((c + 0.055f) / 1.055f, 2.4f); | ||
| 14 | } | ||
| 15 | |||
| 16 | static unsigned char linearToSrgb(float c) { | ||
| 17 | float s = c <= 0.0031308f ? c * 12.92f : 1.055f * std::pow(c, 1.0f / 2.4f) - 0.055f; | ||
| 18 | return static_cast<unsigned char>(s * 255.0f + 0.5f); | ||
| 19 | } | ||
| 20 | |||
| 8 | // 1×1になるまで半分にした回数+1 / number of halvings until 1×1, plus one | 21 | // 1×1になるまで半分にした回数+1 / number of halvings until 1×1, plus one |
| 9 | static int mipLevelCount(int width, int height) { | 22 | static int mipLevelCount(int width, int height) { |
| 10 | int levels = 1; | 23 | int levels = 1; |
| @@ -46,8 +59,15 @@ Texture2D Texture2D::fromPixels(const unsigned char *rgba, int width, int height | |||
| 46 | // 乗算済みアルファ:色 × アルファ。透明なピクセルの色は(何色でも)0になる | 59 | // 乗算済みアルファ:色 × アルファ。透明なピクセルの色は(何色でも)0になる |
| 47 | // premultiplied alpha: colour × alpha. Transparent pixels become 0 whatever colour they had | 60 | // premultiplied alpha: colour × alpha. Transparent pixels become 0 whatever colour they had |
| 48 | std::vector<unsigned char> pm(rgba, rgba + static_cast<size_t>(width) * static_cast<size_t>(height) * 4); | 61 | std::vector<unsigned char> pm(rgba, rgba + static_cast<size_t>(width) * static_cast<size_t>(height) * 4); |
| 62 | // sRGBの値にそのまま掛けると、暗い縁が暗くなりすぎる:リニアで掛ける / multiplying the sRGB-encoded values directly | ||
| 63 | // makes dark edges too dark: multiply in linear space | ||
| 64 | float table[256]; | ||
| 65 | for (int v = 0; v < 256; ++v) table[v] = srgbToLinear(static_cast<unsigned char>(v)); | ||
| 49 | for (size_t i = 0; i < pm.size(); i += 4) | 66 | for (size_t i = 0; i < pm.size(); i += 4) |
| 50 | for (size_t c = 0; c < 3; ++c) pm[i + c] = static_cast<unsigned char>((pm[i + c] * pm[i + 3] + 127) / 255); | 67 | for (size_t c = 0; c < 3; ++c) { |
| 68 | if (options.srgb) pm[i + c] = linearToSrgb(table[pm[i + c]] * static_cast<float>(pm[i + 3]) / 255.0f); | ||
| 69 | else pm[i + c] = static_cast<unsigned char>((pm[i + c] * pm[i + 3] + 127) / 255); | ||
| 70 | } | ||
| 51 | texture.upload(pm.data()); | 71 | texture.upload(pm.data()); |
| 52 | } else { | 72 | } else { |
| 53 | texture.upload(rgba); | 73 | texture.upload(rgba); |
ファイル: a/src/texture.hh | b/src/texture.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -11,9 +11,16 @@ | |||
| 11 | struct TextureOptions { | 11 | struct TextureOptions { |
| 12 | bool flipY = true; // 画像は上から、OpenGLのUVは下から / images start at the top, OpenGL UVs at the bottom | 12 | bool flipY = true; // 画像は上から、OpenGLのUVは下から / images start at the top, OpenGL UVs at the bottom |
| 13 | bool mipmaps = true; // ミップマップを作る / build mipmaps | 13 | bool mipmaps = true; // ミップマップを作る / build mipmaps |
| 14 | bool srgb = false; // 色の画像はsRGB(正しい扱いは第21章) / colour images are sRGB (handled properly in chapter 21) | 14 | // 色の画像(ベースカラー、発光)はtrue:GL_SRGB8_ALPHA8になり、読むときにGPUがリニアに直す(第21章)。 |
| 15 | // データ(法線、金属・粗さ、遮蔽、高さ)はfalseのまま:値そのものに意味がある | ||
| 16 | // true for colour images (base colour, emission): the texture becomes GL_SRGB8_ALPHA8 and the GPU converts to | ||
| 17 | // linear when sampling (chapter 21). Keep false for data (normals, metallic-roughness, occlusion, height): the | ||
| 18 | // values themselves mean something | ||
| 19 | bool srgb = false; | ||
| 15 | // RGBにアルファを掛けてからアップロードする(乗算済みアルファ、第16章)。ミップマップもその値から作られる。 | 20 | // RGBにアルファを掛けてからアップロードする(乗算済みアルファ、第16章)。ミップマップもその値から作られる。 |
| 16 | // Multiply RGB by alpha before uploading (premultiplied alpha, chapter 16). Mipmaps are then built from those values. | 21 | // Multiply RGB by alpha before uploading (premultiplied alpha, chapter 16). Mipmaps are then built from those values. |
| 22 | // srgbなら、リニアに直してから掛けてsRGBに戻す(第21章) / with srgb the colour is converted to linear, multiplied and | ||
| 23 | // converted back to sRGB (chapter 21) | ||
| 17 | bool premultiplyAlpha = false; | 24 | bool premultiplyAlpha = false; |
| 18 | }; | 25 | }; |
| 19 | 26 | ||
ファイル: a/src/uniforms.hh | b/src/uniforms.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -13,7 +13,7 @@ | |||
| 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 | // 2 = 影(第23章:光から見た行列) / shadows (chapter 23: light-space matrices) |
| 16 | // 3 = 後処理の設定(第21章:露出、ブルーム) / post-processing settings (chapter 21: exposure, bloom) | 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) |
| 19 | // float, int, bool : 4バイト、4の倍数に置く / 4 bytes, at a multiple of 4 | 19 | // float, int, bool : 4バイト、4の倍数に置く / 4 bytes, at a multiple of 4 |
| @@ -64,3 +64,38 @@ private: | |||
| 64 | Buffer buffer; | 64 | Buffer buffer; |
| 65 | GLuint binding; | 65 | GLuint binding; |
| 66 | }; | 66 | }; |
| 67 | |||
| 68 | // トーンマッピングの方法(post.fragのuToneMapperと同じ番号) / tone mappers (same numbers as uToneMapper in post.frag) | ||
| 69 | enum class ToneMapper { Clamp = 0, Reinhard = 1, Aces = 2 }; | ||
| 70 | // ガンマ(画面に出すときのsRGB変換)の方法(post.fragのuGammaModeと同じ番号) | ||
| 71 | // How gamma (the sRGB encoding for the screen) is applied (same numbers as uGammaMode in post.frag) | ||
| 72 | enum class GammaMode { | ||
| 73 | Shader = 0, // post.fragで変換(このシリーズの選択) / encoded in post.frag (the series' choice) | ||
| 74 | FramebufferSrgb = 1, // glEnable(GL_FRAMEBUFFER_SRGB):GPUが書くときに変換 / the GPU encodes on write | ||
| 75 | None = 2, // 変換なし(間違い:暗すぎる) / no encoding (wrong: too dark) | ||
| 76 | Double = 3, // 両方(間違い:白っぽい) / both (wrong: washed out) | ||
| 77 | }; | ||
| 78 | // 後処理を何を見せるか / what the post pass shows | ||
| 79 | enum class PostView { Final = 0, NoBloom = 1, Bright = 2, Bloom = 3 }; | ||
| 80 | |||
| 81 | // GLSL: | ||
| 82 | // layout(std140, binding = 3) uniform Post { | ||
| 83 | // float uExposure; // offset 0:明るさの倍率(2^EV) / brightness multiplier (2^EV) | ||
| 84 | // float uBloomStrength; // 4:ブルームを足す強さ / how much bloom is added | ||
| 85 | // float uBloomThreshold; // 8:これより明るい部分が光る(リニアのHDR値) / brighter than this glows (linear HDR) | ||
| 86 | // int uToneMapper; // 12 | ||
| 87 | // int uGammaMode; // 16 | ||
| 88 | // int uPostView; // 20 | ||
| 89 | // }; // 24 → 32 bytes | ||
| 90 | struct PostBlock { | ||
| 91 | float exposure = 1.0f; | ||
| 92 | float bloomStrength = 0.08f; | ||
| 93 | float bloomThreshold = 1.0f; | ||
| 94 | int toneMapper = static_cast<int>(ToneMapper::Aces); | ||
| 95 | int gammaMode = static_cast<int>(GammaMode::Shader); | ||
| 96 | int view = static_cast<int>(PostView::Final); | ||
| 97 | int pad[2] = {0, 0}; | ||
| 98 | }; | ||
| 99 | static_assert(offsetof(PostBlock, bloomThreshold) == 8); | ||
| 100 | static_assert(offsetof(PostBlock, view) == 20); | ||
| 101 | static_assert(sizeof(PostBlock) == 32); | ||
コメント(0)
まだコメントはありません。
ログインするとコメント出来ます。