diff --git a/assets/LICENSE.txt b/assets/LICENSE.txt index d8c94da..a439a10 100644 --- a/assets/LICENSE.txt +++ b/assets/LICENSE.txt @@ -13,4 +13,4 @@ textures/sky/*.png 空のキューブマップの6面 / the six sky cu models/window.glb 花箱つきの窓 / a window with a flower box (chapter 16) models/rock.glb 岩(インスタンシング用) / a rock for instancing (chapter 19) models/crate.glb 木箱のモデル / crate model -models/diorama.glb 小さな場面 / a small diorama scene +models/diorama.glb 小さな場面 / a small diorama scene (chapter 21) diff --git a/assets/models/diorama.glb b/assets/models/diorama.glb index dcdfeb1..c3c4f02 100644 Binary files a/assets/models/diorama.glb and b/assets/models/diorama.glb differ diff --git a/shaders/blur.frag b/shaders/blur.frag new file mode 100644 index 0000000..ca3f446 --- /dev/null +++ b/shaders/blur.frag @@ -0,0 +1,27 @@ +#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); +} diff --git a/shaders/envmap.frag b/shaders/envmap.frag index 27136ab..769e881 100644 --- a/shaders/envmap.frag +++ b/shaders/envmap.frag @@ -21,6 +21,27 @@ uniform vec3 uEnvironmentTint; // 空の明るさ(昼1、夜は暗く) / bri layout(location = 0) out vec4 out_color; +// 後処理の設定(ユニフォームバッファ、結合点3、std140、第21章)。使う全部のシェーダーで同じ宣言(C++ではPostBlock) +// Post-processing settings (uniform buffer, binding 3, std140, chapter 21). The same declaration in every shader that +// uses it (PostBlock in C++) +layout(std140, binding = 3) uniform Post { + float uExposure; // 明るさの倍率 / brightness multiplier + float uBloomStrength; // ブルームの強さ / bloom strength + float uBloomThreshold; // これより明るい部分が光る(リニアのHDR値) / brighter than this glows (linear HDR value) + int uToneMapper; // 0 = クランプ / clamp, 1 = Reinhard, 2 = ACES + int uGammaMode; // 0 = シェーダー / shader, 1 = GL_FRAMEBUFFER_SRGB, 2 = なし / none, 3 = 二重 / double + int uPostView; // 0 = 完成 / final, 1 = ブルームなし / no bloom, 2 = 明るい部分 / bright part, 3 = ブルーム / bloom + int uPostPad0, uPostPad1; // std140の大きさを32バイトにそろえる / pads the block to 32 bytes +}; + +// ブルーム用の2つ目の出力(MRT、GL_COLOR_ATTACHMENT1):しきい値より明るい部分だけ(色合いは保つ) +// The second output for bloom (MRT, GL_COLOR_ATTACHMENT1): only what is brighter than the threshold (hue kept) +layout(location = 1) out vec4 out_bright; +vec3 brightPart(vec3 c) { + float l = dot(c, vec3(0.2126, 0.7152, 0.0722)); // 輝度 / luminance + return c * (max(l - uBloomThreshold, 0.0) / max(l, 1e-4)); +} + void main() { vec3 i = normalize(vWorldPos - uViewPos); // 目から表面へ / from the eye to the surface vec3 n = normalize(vNormal); @@ -42,4 +63,5 @@ void main() { color = mix(refracted, reflected, fresnel); } out_color = vec4(color * uTint * uEnvironmentTint, 1.0); + out_bright = vec4(brightPart(out_color.rgb), 1.0); } diff --git a/shaders/phong.frag b/shaders/phong.frag index a5d9a97..f0a1f17 100644 --- a/shaders/phong.frag +++ b/shaders/phong.frag @@ -93,6 +93,27 @@ uniform bool uAlphaToCoverage = false; layout(location = 0) out vec4 out_color; +// 後処理の設定(ユニフォームバッファ、結合点3、std140、第21章)。使う全部のシェーダーで同じ宣言(C++ではPostBlock) +// Post-processing settings (uniform buffer, binding 3, std140, chapter 21). The same declaration in every shader that +// uses it (PostBlock in C++) +layout(std140, binding = 3) uniform Post { + float uExposure; // 明るさの倍率 / brightness multiplier + float uBloomStrength; // ブルームの強さ / bloom strength + float uBloomThreshold; // これより明るい部分が光る(リニアのHDR値) / brighter than this glows (linear HDR value) + int uToneMapper; // 0 = クランプ / clamp, 1 = Reinhard, 2 = ACES + int uGammaMode; // 0 = シェーダー / shader, 1 = GL_FRAMEBUFFER_SRGB, 2 = なし / none, 3 = 二重 / double + int uPostView; // 0 = 完成 / final, 1 = ブルームなし / no bloom, 2 = 明るい部分 / bright part, 3 = ブルーム / bloom + int uPostPad0, uPostPad1; // std140の大きさを32バイトにそろえる / pads the block to 32 bytes +}; + +// ブルーム用の2つ目の出力(MRT、GL_COLOR_ATTACHMENT1):しきい値より明るい部分だけ(色合いは保つ) +// The second output for bloom (MRT, GL_COLOR_ATTACHMENT1): only what is brighter than the threshold (hue kept) +layout(location = 1) out vec4 out_bright; +vec3 brightPart(vec3 c) { + float l = dot(c, vec3(0.2126, 0.7152, 0.0722)); // 輝度 / luminance + return c * (max(l - uBloomThreshold, 0.0) / max(l, 1e-4)); +} + // このピクセルの表面:どの光の計算にも同じものを使う / this pixel's surface: the same for every light struct Surface { vec3 position; // ワールド座標 / world space @@ -193,4 +214,6 @@ void main() { // alpha becomes the number of samples covered bool coverage = uMaterial.alphaMode == ALPHA_MASK && uAlphaToCoverage; 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); } diff --git a/shaders/post.frag b/shaders/post.frag index e226a17..b0cd134 100644 --- a/shaders/post.frag +++ b/shaders/post.frag @@ -1,119 +1,90 @@ #version 460 core -// ポストプロセス:フレームバッファに描いた画像を加工して画面に出す。MSAAなら解決(resolve)した後の画像(第20章) -// Post-processing: take the image drawn into a framebuffer, change it, and put it on the screen. With MSAA this is -// the resolved image (chapter 20) +// ポストプロセス(第21章):HDRの場面+ブルーム → 露出 → トーンマッピング → sRGBに変換 → 効果 +// Post-processing (chapter 21): HDR scene + bloom → exposure → tone mapping → sRGB encoding → effect in vec2 vUv; -layout(binding = 0) uniform sampler2D uScene; +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) // 0 = なし / none, 1 = 反転 / invert, 2 = グレースケール / grayscale, 3 = シャープ / sharpen, // 4 = ぼかし / blur, 5 = エッジ検出 / edge detection uniform int uEffect; -uniform bool uFxaa; // FXAA風のアンチエイリアス(第20章) / FXAA-like anti-aliasing (chapter 20) -uniform bool uMagnifier; // 右下に画面の中央を4倍に拡大して見せる / shows the centre of the screen 4× enlarged, bottom right + +// 後処理の設定(ユニフォームバッファ、結合点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 +}; layout(location = 0) out vec4 out_color; -// 明るさ(FXAAは色ではなく明るさの差で輪郭を探す) / brightness (FXAA looks for edges in brightness, not colour) -float luma(vec3 c) { return dot(c, vec3(0.299, 0.587, 0.114)); } +// 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); +} -// FXAA風(Timothy LottesのFXAA 3.11「コンソール版」を簡単にしたもの):斜めの4ピクセルの明るさから輪郭の向きを求め、 -// 輪郭に沿って何点か読んで平均する。MSAAと違って、描き終わった画像だけから作る(深度もサンプルも要らない) -// FXAA-like (a simplified version of Timothy Lottes' FXAA 3.11 "console"): estimate the edge direction from the -// brightness of the four diagonal neighbours, then average a few samples along the edge. Unlike MSAA it only needs -// the finished image (no depth, no samples) -vec3 fxaa(vec2 uv) { - vec2 texel = 1.0 / vec2(textureSize(uScene, 0)); - vec3 rgbM = texture(uScene, uv).rgb; - // OpenGLのUVは上が+y / OpenGL UVs have +y up - float lumaNW = luma(texture(uScene, uv + vec2(-1.0, 1.0) * texel).rgb); - float lumaNE = luma(texture(uScene, uv + vec2(1.0, 1.0) * texel).rgb); - float lumaSW = luma(texture(uScene, uv + vec2(-1.0, -1.0) * texel).rgb); - float lumaSE = luma(texture(uScene, uv + vec2(1.0, -1.0) * texel).rgb); - float lumaM = luma(rgbM); - float lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE))); - float lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE))); - // 明るさの差が小さければ輪郭ではない:そのまま(ほとんどのピクセルはここで終わる) - // Little contrast: not an edge, keep the pixel (most pixels stop here) - if (lumaMax - lumaMin < max(0.0312, lumaMax * 0.125)) return rgbM; +// 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) +} - // 明るさの勾配に垂直な向き=輪郭に沿った向き / perpendicular to the brightness gradient = along the edge - vec2 dir = vec2((lumaNW + lumaNE) - (lumaSW + lumaSE), (lumaNW + lumaSW) - (lumaNE + lumaSE)); - float reduce = max((lumaNW + lumaNE + lumaSW + lumaSE) * (0.25 / 8.0), 1.0 / 128.0); - float rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + reduce); - dir = clamp(dir * rcpDirMin, vec2(-8.0), vec2(8.0)) * texel; // 最大8ピクセル / at most 8 pixels +// リニア → 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)); +} - // 輪郭に沿って近い2点と遠い2点 / two near and two far samples along the edge - 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); - vec3 rgbB = rgbA * 0.5 + 0.25 * (texture(uScene, uv - dir * 0.5).rgb + texture(uScene, uv + dir * 0.5).rgb); - // 遠い点が輪郭の向こう側だった(明るさが範囲外)なら近い2点だけ / if the far samples crossed the edge (brightness out - // of range), use only the near ones - float lumaB = luma(rgbB); - return (lumaB < lumaMin || lumaB > lumaMax) ? rgbA : rgbB; +// 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; } -// 3×3のカーネル(畳み込み):周りの9ピクセルに重みを掛けて足す -// A 3×3 kernel (convolution): multiply the 9 surrounding pixels by weights and add them up vec3 convolve(vec2 uv, float k[9]) { - vec2 texel = 1.0 / vec2(textureSize(uScene, 0)); // 1ピクセルのUVでの大きさ / one pixel in UV units + 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)] * texture(uScene, uv + vec2(x, y) * texel).rgb; // 上の行から / top row first + sum += k[(1 - y) * 3 + (x + 1)] * display(uv + vec2(x, y) * texel); return sum; } -// UVの位置の最終的な色(効果をかけた後) / the final colour at a UV position (after the effect) -vec3 shade(vec2 uv) { - vec3 color = uFxaa ? fxaa(uv) : texture(uScene, uv).rgb; +void main() { + vec3 color = display(vUv); if (uEffect == 1) { color = 1.0 - color; } else if (uEffect == 2) { - // 目は緑に一番敏感:輝度の重み(Rec. 709) / the eye is most sensitive to green: luminance weights (Rec. 709) 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); // 合計1:明るさは変わらない / sums to 1: brightness unchanged - color = convolve(uv, k); + 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); // ガウスに近い / close to a Gaussian - color = convolve(uv, k); + 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); // 合計0:平らなところは黒、変化があるところだけ明るい / sums to 0: flat areas black - color = convolve(uv, k); - } - return color; -} - -void main() { - vec2 uv = vUv; - vec3 frame = vec3(-1.0); // 拡大鏡の枠の色(-1 = 枠ではない) / magnifier frame colour (-1 = not a frame pixel) - if (uMagnifier) { - // 画面の中央の96×54ピクセルを、右下の384×216ピクセルに4倍で(最近傍:1ピクセルが4×4の四角になる) - // The central 96 × 54 pixels, shown 4× in 384 × 216 pixels at the bottom right (nearest: each pixel becomes a - // 4 × 4 block) - vec2 size = vec2(textureSize(uScene, 0)); - vec2 source = vec2(96.0, 54.0); - vec2 inset0 = vec2(size.x - 16.0 - 4.0 * source.x, 16.0); - vec2 local = (gl_FragCoord.xy - inset0) / 4.0; - vec2 source0 = floor(0.5 * (size - source)); - if (all(greaterThanEqual(local, vec2(0.0))) && all(lessThan(local, source))) { - uv = (source0 + floor(local) + 0.5) / size; - } else if (all(greaterThanEqual(local, vec2(-0.75))) && all(lessThan(local, source + 0.75))) { - frame = vec3(1.0); // 拡大部分の白い枠 / white frame around the inset - } - // 拡大している場所の枠(黄色) / a yellow frame around the enlarged region - vec2 p = gl_FragCoord.xy - source0; - if (all(greaterThanEqual(p, vec2(-2.0))) && all(lessThan(p, source + 2.0)) && - !(all(greaterThanEqual(p, vec2(0.0))) && all(lessThan(p, source)))) - frame = vec3(1.0, 0.85, 0.2); + float k[9] = float[](1, 1, 1, 1, -8, 1, 1, 1, 1); + color = convolve(vUv, k); } - vec3 color = frame.x >= 0.0 ? frame : shade(uv); - // アルファは必ず1(画面が半透明にならないように) / alpha is always 1 (so the window never turns translucent) + // 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); } diff --git a/shaders/skybox.frag b/shaders/skybox.frag index 8775250..d319e79 100644 --- a/shaders/skybox.frag +++ b/shaders/skybox.frag @@ -6,10 +6,69 @@ in vec3 vDirection; layout(binding = 3) uniform samplerCube uSkybox; uniform vec3 uEnvironmentTint; // 空の明るさ(昼1、夜は暗く) / brightness of the sky (1 by day, dark at night) +uniform float uSunRadiance = 60.0; // 太陽の円盤の明るさ(平行光源の色の倍数、第21章) / the sun disc's brightness + // (a multiple of the directional light's colour, chapter 21) + +struct DirectionalLight { + vec3 direction; + vec3 color; +}; +struct PointLight { + vec3 position; + vec3 color; + vec3 attenuation; +}; +struct SpotLight { + vec3 position; + float cosInner; + vec3 direction; + float cosOuter; + vec3 color; + vec3 attenuation; +}; +// 光(結合点1):太陽の向きと色を使う。phong.fragと同じ宣言 / the lights (binding 1): for the sun's direction and +// colour. The same declaration as phong.frag +layout(std140, binding = 1) uniform Lights { + DirectionalLight uDirLight; + PointLight uPointLights[8]; + SpotLight uSpotLights[4]; + vec3 uAmbient; + int uPointLightCount; + int uSpotLightCount; +}; layout(location = 0) out vec4 out_color; +// 後処理の設定(ユニフォームバッファ、結合点3、std140、第21章)。使う全部のシェーダーで同じ宣言(C++ではPostBlock) +// Post-processing settings (uniform buffer, binding 3, std140, chapter 21). The same declaration in every shader that +// uses it (PostBlock in C++) +layout(std140, binding = 3) uniform Post { + float uExposure; // 明るさの倍率 / brightness multiplier + float uBloomStrength; // ブルームの強さ / bloom strength + float uBloomThreshold; // これより明るい部分が光る(リニアのHDR値) / brighter than this glows (linear HDR value) + int uToneMapper; // 0 = クランプ / clamp, 1 = Reinhard, 2 = ACES + int uGammaMode; // 0 = シェーダー / shader, 1 = GL_FRAMEBUFFER_SRGB, 2 = なし / none, 3 = 二重 / double + int uPostView; // 0 = 完成 / final, 1 = ブルームなし / no bloom, 2 = 明るい部分 / bright part, 3 = ブルーム / bloom + int uPostPad0, uPostPad1; // std140の大きさを32バイトにそろえる / pads the block to 32 bytes +}; + +// ブルーム用の2つ目の出力(MRT、GL_COLOR_ATTACHMENT1):しきい値より明るい部分だけ(色合いは保つ) +// The second output for bloom (MRT, GL_COLOR_ATTACHMENT1): only what is brighter than the threshold (hue kept) +layout(location = 1) out vec4 out_bright; +vec3 brightPart(vec3 c) { + float l = dot(c, vec3(0.2126, 0.7152, 0.0722)); // 輝度 / luminance + return c * (max(l - uBloomThreshold, 0.0) / max(l, 1e-4)); +} + void main() { - // 方向は正規化しなくて良い:一番大きい成分で面が決まる / no need to normalize: the largest component picks the face - out_color = vec4(uEnvironmentTint * texture(uSkybox, vDirection).rgb, 1.0); + 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); } diff --git a/shaders/unlit.frag b/shaders/unlit.frag index 01b2f1c..3a3d646 100644 --- a/shaders/unlit.frag +++ b/shaders/unlit.frag @@ -1,9 +1,32 @@ #version 460 core -// ライティングなしの一色(光源の目印用) / one colour without lighting (for light markers) +// ライティングなしの一色(光源の目印用)。HDRなので1より明るい色も使える(第21章) +// One colour without lighting (for light markers). HDR, so colours brighter than 1 work (chapter 21) uniform vec3 uColor; layout(location = 0) out vec4 out_color; +// 後処理の設定(ユニフォームバッファ、結合点3、std140、第21章)。使う全部のシェーダーで同じ宣言(C++ではPostBlock) +// Post-processing settings (uniform buffer, binding 3, std140, chapter 21). The same declaration in every shader that +// uses it (PostBlock in C++) +layout(std140, binding = 3) uniform Post { + float uExposure; // 明るさの倍率 / brightness multiplier + float uBloomStrength; // ブルームの強さ / bloom strength + float uBloomThreshold; // これより明るい部分が光る(リニアのHDR値) / brighter than this glows (linear HDR value) + int uToneMapper; // 0 = クランプ / clamp, 1 = Reinhard, 2 = ACES + int uGammaMode; // 0 = シェーダー / shader, 1 = GL_FRAMEBUFFER_SRGB, 2 = なし / none, 3 = 二重 / double + int uPostView; // 0 = 完成 / final, 1 = ブルームなし / no bloom, 2 = 明るい部分 / bright part, 3 = ブルーム / bloom + int uPostPad0, uPostPad1; // std140の大きさを32バイトにそろえる / pads the block to 32 bytes +}; + +// ブルーム用の2つ目の出力(MRT、GL_COLOR_ATTACHMENT1):しきい値より明るい部分だけ(色合いは保つ) +// The second output for bloom (MRT, GL_COLOR_ATTACHMENT1): only what is brighter than the threshold (hue kept) +layout(location = 1) out vec4 out_bright; +vec3 brightPart(vec3 c) { + float l = dot(c, vec3(0.2126, 0.7152, 0.0722)); // 輝度 / luminance + return c * (max(l - uBloomThreshold, 0.0) / max(l, 1e-4)); +} + void main() { out_color = vec4(uColor, 1.0); + out_bright = vec4(brightPart(uColor), 1.0); } diff --git a/src/cubemap.cc b/src/cubemap.cc index b2e2f3d..e17e440 100644 --- a/src/cubemap.cc +++ b/src/cubemap.cc @@ -27,7 +27,7 @@ void Cubemap::uploadFace(int face, const unsigned char *rgba) { glPixelStorei(GL_UNPACK_ALIGNMENT, 4); } -std::optional Cubemap::load(const std::array &paths) { +std::optional Cubemap::load(const std::array &paths, bool srgb) { // キューブマップの面は上の行から(RenderManの決まり)。反転しない // Cube-map faces start at the top row (the RenderMan convention). Do not flip stbi_set_flip_vertically_on_load(0); @@ -49,7 +49,7 @@ std::optional Cubemap::load(const std::array &paths) { if (face == 0) { int levels = 1; while ((width >> levels) > 0) ++levels; - cube = Cubemap(width, GL_RGBA8, levels); + cube = Cubemap(width, srgb ? GL_SRGB8_ALPHA8 : GL_RGBA8, levels); } cube.uploadFace(face, pixels); stbi_image_free(pixels); @@ -58,10 +58,10 @@ std::optional Cubemap::load(const std::array &paths) { return cube; } -std::optional Cubemap::loadDirectory(const std::string &dir, const std::string &extension) { +std::optional Cubemap::loadDirectory(const std::string &dir, const std::string &extension, bool srgb) { std::array paths; for (int i = 0; i < 6; ++i) paths[static_cast(i)] = dir + "/" + kCubeFaceNames[i] + extension; - return load(paths); + return load(paths, srgb); } Cubemap::~Cubemap() { diff --git a/src/cubemap.hh b/src/cubemap.hh index ae07169..6ffacc9 100644 --- a/src/cubemap.hh +++ b/src/cubemap.hh @@ -30,9 +30,12 @@ public: // Loads six image files (order +X, -X, +Y, -Y, +Z, -Z). No vertical flip: cube-map faces start at the top row. // All must be squares of the same size. Builds mipmaps (for blurry reflections). On failure prints the error // and returns std::nullopt. - static std::optional load(const std::array &paths); + // 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 load(const std::array &paths, bool srgb = false); // dir/px.png, dir/nx.png … を読む / loads dir/px.png, dir/nx.png, ... - static std::optional loadDirectory(const std::string &dir, const std::string &extension = ".png"); + static std::optional loadDirectory(const std::string &dir, const std::string &extension = ".png", + bool srgb = false); // 面face(0〜5)のミップマップ0段目を書き換える(RGBA8) / replaces mip level 0 of face `face` (0..5, RGBA8) void uploadFace(int face, const unsigned char *rgba); diff --git a/src/framebuffer.cc b/src/framebuffer.cc index 1622f49..e539c91 100644 --- a/src/framebuffer.cc +++ b/src/framebuffer.cc @@ -1,5 +1,6 @@ #include "framebuffer.hh" +#include #include #include @@ -11,22 +12,39 @@ Framebuffer::Framebuffer(int width, int height, const FramebufferSpec &s) : w(wi void Framebuffer::createAttachments() { actualSamples = 0; - if (spec.colorFormat != 0 && spec.samples > 0) { - // マルチサンプルの色:ピクセルごとにsamples個の色を持つレンダーバッファ。テクスチャのように読めない - // Multisampled colour: a renderbuffer with `samples` colours per pixel. It cannot be read like a texture - glCreateRenderbuffers(1, &colorSamples); - glNamedRenderbufferStorageMultisample(colorSamples, spec.samples, spec.colorFormat, w, h); - glNamedFramebufferRenderbuffer(fbo, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, colorSamples); - // ドライバーは要求以上で一番近い数を選ぶ(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(colorSamples, GL_RENDERBUFFER_SAMPLES, &actualSamples); - } else if (spec.colorFormat != 0) { - // 色:ミップマップなしのテクスチャ。端の外を読まないようにCLAMP_TO_EDGE(ぼかしのカーネルが端で反対側を拾わない) - // Colour: a texture without mipmaps. CLAMP_TO_EDGE so blur kernels at the border do not pick up the opposite side - colorTexture = Texture2D(w, h, spec.colorFormat, 1); - colorTexture.setWrap(GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE); - colorTexture.setFilter(GL_LINEAR, GL_LINEAR); - glNamedFramebufferTexture(fbo, GL_COLOR_ATTACHMENT0, colorTexture.id(), 0); // 0 = ミップマップの段 / mip level + 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(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(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(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); @@ -52,10 +70,13 @@ void Framebuffer::createAttachments() { } void Framebuffer::destroyAttachments() { - colorTexture = Texture2D(); // 古いテクスチャを消す / deletes the old texture + for (Texture2D &t : colorTextures) t = Texture2D(); // 古いテクスチャを消す / deletes the old textures + for (GLuint &rb : colorSamples) { + if (rb) glDeleteRenderbuffers(1, &rb); + rb = 0; + } if (depthStencil) glDeleteRenderbuffers(1, &depthStencil); - if (colorSamples) glDeleteRenderbuffers(1, &colorSamples); - depthStencil = colorSamples = 0; + depthStencil = 0; } bool Framebuffer::resize(int width, int height) { @@ -78,7 +99,25 @@ void Framebuffer::blitTo(const Framebuffer &target, GLbitfield mask, GLenum filt // 読む側の四角形 → 書く側の四角形。読む色はglNamedFramebufferReadBuffer(既定はGL_COLOR_ATTACHMENT0) // source rectangle → destination rectangle. The colour read comes from glNamedFramebufferReadBuffer // (GL_COLOR_ATTACHMENT0 by default) - glBlitNamedFramebuffer(fbo, target.fbo, 0, 0, w, h, 0, 0, target.w, target.h, mask, filter); + 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(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(i); + glNamedFramebufferDrawBuffers(target.fbo, target.colorCount(), drawBuffers); + glNamedFramebufferReadBuffer(fbo, GL_COLOR_ATTACHMENT0); } void Framebuffer::bind() const { @@ -98,7 +137,7 @@ Framebuffer::~Framebuffer() { Framebuffer::Framebuffer(Framebuffer &&other) noexcept : fbo(std::exchange(other.fbo, 0)), depthStencil(std::exchange(other.depthStencil, 0)), - colorSamples(std::exchange(other.colorSamples, 0)), colorTexture(std::move(other.colorTexture)), w(other.w), + colorSamples(std::exchange(other.colorSamples, {})), colorTextures(std::move(other.colorTextures)), w(other.w), h(other.h), actualSamples(other.actualSamples), spec(other.spec) {} Framebuffer &Framebuffer::operator=(Framebuffer &&other) noexcept { @@ -107,8 +146,8 @@ Framebuffer &Framebuffer::operator=(Framebuffer &&other) noexcept { if (fbo) glDeleteFramebuffers(1, &fbo); fbo = std::exchange(other.fbo, 0); depthStencil = std::exchange(other.depthStencil, 0); - colorSamples = std::exchange(other.colorSamples, 0); - colorTexture = std::move(other.colorTexture); + colorSamples = std::exchange(other.colorSamples, {}); + colorTextures = std::move(other.colorTextures); w = other.w; h = other.h; actualSamples = other.actualSamples; diff --git a/src/framebuffer.hh b/src/framebuffer.hh index 6f5e8c0..d66eb50 100644 --- a/src/framebuffer.hh +++ b/src/framebuffer.hh @@ -5,11 +5,20 @@ #include +#include + +constexpr int kMaxColorAttachments = 4; // GLは最低8を保証する / GL guarantees at least 8 + // フレームバッファに何を付けるか / what to attach to a framebuffer struct FramebufferSpec { - // 色のテクスチャの形式(0 = 色なし)。第21章のHDRではGL_RGBA16F - // The colour texture's format (0 = no colour). GL_RGBA16F for HDR in chapter 21 + // 色のテクスチャの形式(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; @@ -49,8 +58,10 @@ public: // 描いた結果。シェーダーでサンプリングできる(マルチサンプルなら空:id() == 0) // The result; can be sampled in a shader (empty for a multisampled framebuffer: id() == 0) - const Texture2D &color() const { return colorTexture; } - Texture2D &color() { return colorTexture; } + // index = 何番目の色の付け先か(MRT) / index = which colour attachment (MRT) + const Texture2D &color(int index = 0) const { return colorTextures[static_cast(index)]; } + Texture2D &color(int index = 0) { return colorTextures[static_cast(index)]; } + int colorCount() const { return spec.colorFormat != 0 ? spec.colorCount : 0; } // 別のフレームバッファへコピーする(glBlitNamedFramebuffer)。マルチサンプルから普通のフレームバッファへなら // サンプルの平均を取る:これがMSAAの「解決(resolve)」。大きさが違えば拡大・縮小する(filter = GL_LINEARなど。 @@ -59,6 +70,9 @@ public: // averages the samples: this is the MSAA "resolve". Different sizes are scaled (filter = GL_LINEAR etc.; only // the same size is allowed from a multisampled source). mask = GL_COLOR_BUFFER_BIT, GL_DEPTH_BUFFER_BIT... (depth // only with GL_NEAREST) + // 色の付け先が複数あれば、一つずつ同じ番号の付け先へコピーする(ブリットは読む色を一つしか選べない) + // With several colour attachments each one is copied into the attachment with the same number (a blit can read + // only one colour buffer at a time) void blitTo(const Framebuffer &target, GLbitfield mask = GL_COLOR_BUFFER_BIT, GLenum filter = GL_NEAREST) const; GLuint id() const { return fbo; } @@ -75,8 +89,9 @@ private: GLuint fbo = 0; GLuint depthStencil = 0; // レンダーバッファ / renderbuffer - GLuint colorSamples = 0; // マルチサンプルの色のレンダーバッファ(第20章) / multisampled colour renderbuffer (chapter 20) - Texture2D colorTexture; + // マルチサンプルの色のレンダーバッファ(第20章) / multisampled colour renderbuffers (chapter 20) + std::array colorSamples = {}; + std::array colorTextures; int w = 0, h = 0; int actualSamples = 0; FramebufferSpec spec; diff --git a/src/main.cc b/src/main.cc index d8192b7..43c6b6a 100644 --- a/src/main.cc +++ b/src/main.cc @@ -1,5 +1,5 @@ -// 第20章:アンチエイリアス -// Chapter 20: anti-aliasing +// 第21章:ガンマ補正とHDR +// Chapter 21: gamma correction and HDR // // 操作 / Controls: // WASD 前後左右に移動 / move forward, back, left, right @@ -7,12 +7,13 @@ // Shift 速く動く / move faster // マウス / mouse 向きを変える(FPS)、左ドラッグで回る(オービット) / look around (FPS), drag with the left button to orbit // ホイール / wheel ズーム / zoom -// M アンチエイリアス:なし → MSAA 2× → 4× → 8× → SSAA 2×2(GL_MAX_SAMPLESを超える数は飛ばす) -// anti-aliasing: off → MSAA 2× → 4× → 8× → SSAA 2×2 (counts above GL_MAX_SAMPLES are skipped) -// X FXAA風の後処理のオン・オフ / FXAA-like post-process on / off -// T 草のアルファトゥカバレッジのオン・オフ(MSAAのときだけ効く) / alpha to coverage for the grass on / off -// (only works with MSAA) -// Z 拡大鏡(画面の中央を4倍で右下に) / magnifier (the centre of the screen 4× at the bottom right) +// = / - 露出を上げる・下げる(0.5段ずつ) / exposure up / down (half a stop each) +// T トーンマッピング:なし(クランプ) → Reinhard → ACES / tone mapping: none (clamp) → Reinhard → ACES +// G ガンマ:シェーダー → GL_FRAMEBUFFER_SRGB → なし(間違い) → 二重(間違い) +// gamma: shader → GL_FRAMEBUFFER_SRGB → none (wrong) → double (wrong) +// B ブルームのオン・オフ / bloom on / off +// K 太陽を見る(電線の向こうの太陽にカメラを向ける) / look at the sun (aims the camera at the sun behind the wires) +// O 表示:完成 → ブルームなし → 明るい部分 → ぼかしたブルーム / view: final → no bloom → bright part → blurred bloom // 1〜6 効果:なし / 反転 / グレースケール / シャープ / ぼかし / エッジ検出 // effect: none / invert / grayscale / sharpen / blur / edge detection // C FPS ⇔ オービットカメラ / FPS ⇔ orbit camera @@ -23,11 +24,6 @@ // Tab カーソルのキャプチャ切り替え / toggle cursor capture // R シェーダーを読み直す / reload the shaders // Esc 終了 / quit -// -// ./build/game --direct [samples] フレームバッファを使わず、GLFW_SAMPLESでマルチサンプルにした画面に直接描く -// (後処理なし)。本物のGPUで画面のMSAAを試す用 -// draws straight into a screen made multisampled with GLFW_SAMPLES, without our -// framebuffers (no post-processing). For trying screen MSAA on a real GPU #include "camera.hh" #include "cubemap.hh" #include "framebuffer.hh" @@ -45,8 +41,6 @@ #include #include #include -#include -#include #include #include @@ -61,16 +55,13 @@ static const Placement kCrates[] = { {{-6.0f, 0.0f, -1.0f}, 0.8f}, {{-5.2f, 0.0f, 3.5f}, -0.6f}, }; -// アンチエイリアスの方法 / the anti-aliasing methods -struct AaMode { - const char *name; - int samples; // MSAAのサンプル数(0 = MSAAなし) / MSAA samples (0 = no MSAA) - bool ssaa; // 縦横2倍で描いて縮める(スーパーサンプリング) / draw at twice the width and height, then shrink -}; -static const AaMode kAaModes[] = { - {"off", 0, false}, {"MSAA 2x", 2, false}, {"MSAA 4x", 4, false}, {"MSAA 8x", 8, false}, {"SSAA 2x2", 0, true}, -}; +constexpr int kMsaaSamples = 4; // 第20章 / chapter 20 +constexpr int kBloomPasses = 4; // 横+縦の組の数 / number of horizontal + vertical pairs +static const char *const kToneMapperNames[] = {"none (clamp)", "Reinhard", "ACES"}; +static const char *const kGammaNames[] = {"shader (linear → sRGB in post.frag)", "GL_FRAMEBUFFER_SRGB", + "none (wrong: too dark)", "double (wrong: washed out)"}; +static const char *const kPostViewNames[] = {"final", "no bloom", "bright part (attachment 1)", "blurred bloom"}; static const char *const kViewModeNames[] = {"all", "ambient", "diffuse", "specular", "emission", "normals"}; static const char *const kEffectNames[] = {"none", "invert", "grayscale", "sharpen", "blur", "edge detection"}; @@ -150,28 +141,51 @@ static std::vector makeWires() { return wires; } -int main(int argc, char **argv) { - // --direct [samples]:画面のMSAA(GLFW_SAMPLES)を試す / try screen MSAA (GLFW_SAMPLES) - bool direct = argc > 1 && std::strcmp(argv[1], "--direct") == 0; - int windowSamples = direct ? (argc > 2 ? std::atoi(argv[2]) : 4) : 0; +// 電線に吊るした提灯:発光する球。位置と色 / paper lanterns hanging from the wires: emissive spheres, position + colour +struct Lantern { + Vec3 position; + Vec3 color; +}; +static std::vector makeLanterns() { + std::vector 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; +} +int main() { Window window; - // 普段は画面をマルチサンプルにしない:場面は自分のマルチサンプルのフレームバッファに描き、解決してから後処理する。 - // 画面がマルチサンプルでも、全画面の三角形一つには意味がない - // Normally the screen is not multisampled: the scene goes into our own multisampled framebuffer, which is - // resolved and then post-processed. A multisampled screen would be wasted on one fullscreen triangle - if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 20", windowSamples)) return 1; + if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 21")) return 1; + + // 画面(既定のフレームバッファ)が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"); std::optional phong = Shader::load("shaders/phong.vert", "shaders/phong.frag"); std::optional skybox = Shader::load("shaders/skybox.vert", "shaders/skybox.frag"); std::optional post = Shader::load("shaders/post.vert", "shaders/post.frag"); - std::optional sky = Cubemap::loadDirectory("assets/textures/sky"); - std::optional floorTexture = Texture2D::load("assets/textures/floor.png"); - std::optional grassTexture = Texture2D::load("assets/textures/grass_blades.png"); - if (!phong || !skybox || !post || !sky || !floorTexture || !grassTexture) return 1; + std::optional blur = Shader::load("shaders/post.vert", "shaders/blur.frag"); + std::optional unlit = Shader::load("shaders/unlit.vert", "shaders/unlit.frag"); + // 色の画像はsRGB(第21章):GPUが読むときにリニアに直す / colour images are sRGB (chapter 21): the GPU converts them + // to linear when sampling + std::optional sky = Cubemap::loadDirectory("assets/textures/sky", ".png", true); + std::optional floorTexture = Texture2D::load("assets/textures/floor.png", {.srgb = true}); + std::optional grassTexture = Texture2D::load("assets/textures/grass_blades.png", {.srgb = true}); + if (!phong || !skybox || !post || !blur || !unlit || !sky || !floorTexture || !grassTexture) return 1; grassTexture->setWrap(GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE); - for (const Shader *s : {&*phong, &*skybox}) - if (!s->checkUniformBlock("Camera", sizeof(CameraBlock)) || !s->checkUniformBlock("Lights", sizeof(LightsBlock))) + 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; std::optional scene = Model::load("assets/models/diorama.glb"); @@ -187,44 +201,28 @@ int main(int argc, char **argv) { UniformBuffer cameraUbo(kCameraBinding); UniformBuffer lightsUbo(kLightsBinding); - - // このGPUで使えるサンプル数の上限(llvmpipeは4) / the most samples this GPU supports (4 on llvmpipe) - GLint maxSamples = 0; - glGetIntegerv(GL_MAX_SAMPLES, &maxSamples); - printf("GL_MAX_SAMPLES = %d\n", maxSamples); - std::vector aaModes; - for (const AaMode &m : kAaModes) - if (m.samples <= maxSamples) aaModes.push_back(m); - size_t aaMode = 0; - for (size_t i = 0; i < aaModes.size(); ++i) - if (aaModes[i].samples == 4) aaMode = i; // 既定はMSAA 4× / MSAA 4× by default - - // 場面を描くフレームバッファ:MSAAなら msaaFbo に描いて sceneFbo に解決する。SSAAなら縦横2倍の ssaaFbo に描いて - // 縮める。なしなら sceneFbo に直接。後処理はいつも sceneFbo の色のテクスチャを読む - // The framebuffers the scene is drawn into: with MSAA into msaaFbo, resolved into sceneFbo; with SSAA into the - // double-size ssaaFbo, then shrunk; without AA straight into sceneFbo. Post-processing always reads sceneFbo's - // colour texture - Framebuffer sceneFbo(window.width(), window.height()); - Framebuffer msaaFbo, ssaaFbo; - auto createAaFramebuffer = [&] { - const AaMode &m = aaModes[aaMode]; - msaaFbo = Framebuffer(); - ssaaFbo = Framebuffer(); - if (m.samples > 0) { - msaaFbo = Framebuffer(window.width(), window.height(), {.samples = m.samples}); - printf("anti-aliasing: %s (requested %d samples, got %d)\n", m.name, m.samples, msaaFbo.samples()); - } else if (m.ssaa) { - ssaaFbo = Framebuffer(2 * window.width(), 2 * window.height()); - printf("anti-aliasing: %s (%d x %d)\n", m.name, ssaaFbo.width(), ssaaFbo.height()); - } else { - printf("anti-aliasing: %s\n", m.name); - } - }; - if (!direct) createAaFramebuffer(); + UniformBuffer postUbo(kPostBinding); + + // 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); - if (msaaFbo.id()) msaaFbo.resize(width, height); // サンプル数はそのまま / keeps the sample count - if (ssaaFbo.id()) ssaaFbo.resize(2 * width, 2 * height); + for (Framebuffer &f : bloomFbo) f.resize(width / 2, height / 2); }; glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS); @@ -237,8 +235,10 @@ int main(int argc, char **argv) { orbit.distance = 11.0f; orbit.yaw = radians(20.0f); - bool useOrbit = false, fxaa = false, alphaToCoverage = false, magnifier = false; + bool useOrbit = false, bloomOn = true; int viewMode = 0, effect = 0; + float exposureEv = 0.0f; // 露出(段、EV):倍率は2^EV / exposure in stops (EV): the multiplier is 2^EV + PostBlock postSettings; bool night = false, flashlightOn = false, windmillMoving = true; float windmillTime = 0.0f; window.setCursorCaptured(true); @@ -246,7 +246,7 @@ int main(int argc, char **argv) { window.onKey = [&](int key, int action, int /*mods*/) { if (action != GLFW_PRESS) return; if (key == GLFW_KEY_ESCAPE) window.close(); - if (key == GLFW_KEY_R && phong->reload() && skybox->reload() && post->reload()) + if (key == GLFW_KEY_R && phong->reload() && skybox->reload() && post->reload() && blur->reload() && unlit->reload()) printf("シェーダーを読み直した / shaders reloaded\n"); if (key == GLFW_KEY_TAB) window.setCursorCaptured(!window.cursorCaptured()); if (key == GLFW_KEY_C) { @@ -262,19 +262,34 @@ int main(int argc, char **argv) { effect = key - GLFW_KEY_1; printf("effect: %s\n", kEffectNames[effect]); } - if (key == GLFW_KEY_M && !direct) { - aaMode = (aaMode + 1) % aaModes.size(); - createAaFramebuffer(); - } - if (key == GLFW_KEY_X) { - fxaa = !fxaa; - printf("FXAA: %s\n", fxaa ? "on" : "off"); + 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)); } if (key == GLFW_KEY_T) { - alphaToCoverage = !alphaToCoverage; - printf("alpha to coverage: %s\n", alphaToCoverage ? "on" : "off"); + postSettings.toneMapper = (postSettings.toneMapper + 1) % 3; + printf("tone mapping: %s\n", kToneMapperNames[postSettings.toneMapper]); + } + if (key == GLFW_KEY_G) { + postSettings.gammaMode = (postSettings.gammaMode + 1) % 4; + printf("gamma: %s\n", kGammaNames[postSettings.gammaMode]); + } + if (key == GLFW_KEY_B) { + bloomOn = !bloomOn; + printf("bloom: %s\n", bloomOn ? "on" : "off"); + } + if (key == GLFW_KEY_K) { + // 太陽の向き(0.5, 1, 0.35)の反対側から、電線越しに見上げる / look up through the wires from the side opposite the + // sun (direction (0.5, 1, 0.35)) + useOrbit = false; + fps.position = {-3.2f, 1.7f, -7.4f}; + fps.yaw = radians(125.0f); + fps.pitch = radians(42.0f); + } + if (key == GLFW_KEY_O) { + postSettings.view = (postSettings.view + 1) % 4; + printf("post view: %s\n", kPostViewNames[postSettings.view]); } - if (key == GLFW_KEY_Z) magnifier = !magnifier; if (key == GLFW_KEY_N) night = !night; if (key == GLFW_KEY_F) flashlightOn = !flashlightOn; if (key == GLFW_KEY_P) windmillMoving = !windmillMoving; @@ -298,14 +313,22 @@ int main(int argc, char **argv) { std::vector fence = makeFence(); std::vector wires = makeWires(); Material woodMaterial; - woodMaterial.diffuse = {0.42f, 0.3f, 0.2f}; + // 手で選んだ色は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 = {0.04f, 0.04f, 0.045f}; + wireMaterial.diffuse = srgbToLinear(Vec3{0.04f, 0.04f, 0.045f}); wireMaterial.specular = {0.3f, 0.3f, 0.3f}; wireMaterial.shininess = 32.0f; + // 提灯:本体は暗い紙、発光で光る(1より明るい:HDR) / lanterns: dark paper, glowing through emission (brighter + // than 1: HDR) + std::vector lanterns = makeLanterns(); + Mesh sphereMesh = makeSphere(24, 12); + constexpr float kLanternGlow = 6.0f; + FullscreenTriangle fullscreen; glEnable(GL_CULL_FACE); @@ -326,6 +349,17 @@ int main(int argc, char **argv) { floorMesh.draw(); scene->draw(*phong, Mat4::identity(), white, ModelPass::Opaque); for (const Placement &c : kCrates) crate->draw(*phong, translate(c.position) * rotateY(c.angle), white, ModelPass::Opaque); + Material lanternMaterial; + lanternMaterial.diffuse = {0.05f, 0.03f, 0.02f}; + lanternMaterial.specular = {0.02f, 0.02f, 0.02f}; + 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(); + } for (const std::vector *list : {&fence, &wires}) { (list == &fence ? woodMaterial : wireMaterial).apply(*phong, white); for (const Mat4 &m : *list) { @@ -338,10 +372,8 @@ int main(int argc, char **argv) { // 草:アルファトゥカバレッジならdiscardの代わりにサンプルの一部だけを覆う(MSAAのときだけ意味がある) // Grass: with alpha to coverage, a fragment covers only some of the samples instead of being discarded (only // meaningful with MSAA) - bool coverage = alphaToCoverage && !direct && aaModes[aaMode].samples > 0; - if (direct) coverage = alphaToCoverage && window.samples() > 0; - if (coverage) glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE); - phong->set("uAlphaToCoverage", coverage ? 1 : 0); + glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE); + phong->set("uAlphaToCoverage", 1); grassMaterial.apply(*phong, white); glDisable(GL_CULL_FACE); for (const Placement &g : grass) { @@ -393,7 +425,7 @@ int main(int argc, char **argv) { scene->nodes[static_cast(rotor)].rotation = Quat::fromAxisAngle({0.0f, 0.0f, 1.0f}, -0.8f * windmillTime) * rotorStart; - float aspect = window.aspect(); + float aspect = static_cast(sceneFbo.width()) / static_cast(sceneFbo.height()); CameraBlock camera; camera.view = useOrbit ? orbit.view() : fps.view(); camera.proj = useOrbit ? orbit.projection(aspect) : fps.projection(aspect); @@ -402,65 +434,73 @@ int main(int argc, char **argv) { cameraUbo.update(camera); Vec3 viewDir = useOrbit ? normalize(orbit.target - orbit.position()) : fps.front(); + // 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.28f, 0.30f, 0.34f}; - lights.directional = {.direction = {-0.5f, -1.0f, -0.35f}, .color = {0.95f, 0.9f, 0.8f}}; + 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.03f, 0.035f, 0.05f}; - lights.directional = {.direction = {-0.4f, -1.0f, -0.6f}, .color = {0.15f, 0.18f, 0.28f}}; + lights.ambient = {0.012f, 0.015f, 0.025f}; + lights.directional = {.direction = {-0.4f, -1.0f, -0.6f}, .color = {0.05f, 0.07f, 0.12f}}; if (lanternNode >= 0) { Vec4 p = scene->nodeTransform(lanternNode) * Vec4{0.0f, 0.0f, 0.0f, 1.0f}; lights.points.push_back({.position = {p.x, p.y, p.z}, .color = {2.6f, 1.6f, 0.7f}, .attenuation = kMediumRange}); } + // 真ん中の電線の提灯を点光源に(最大8個) / the lanterns on the middle span become point lights (8 at most) + for (size_t i = 3; i < 6; ++i) + lights.points.push_back({.position = lanterns[i].position, .color = 1.5f * lanterns[i].color, .attenuation = kMediumRange}); } if (flashlightOn) lights.spots.push_back({.position = camera.viewPos, .direction = viewDir, .color = {1.0f, 0.95f, 0.85f}}); lightsUbo.update(lights.toBlock()); - environmentTint = night ? Vec3{0.05f, 0.06f, 0.11f} : Vec3{1.0f, 1.0f, 1.0f}; - - if (direct) { - // 画面に直接(GLFW_SAMPLESのMSAAは描くときに自動、解決はglfwSwapBuffersの中) / straight to the screen (the - // GLFW_SAMPLES MSAA happens while drawing; the resolve happens inside glfwSwapBuffers) - Framebuffer::bindDefault(window.width(), window.height()); - drawScene(); - window.swapBuffers(); - continue; - } + environmentTint = night ? Vec3{0.02f, 0.025f, 0.05f} : Vec3{1.0f, 1.0f, 1.0f}; + postSettings.exposure = std::exp2(exposureEv); + postSettings.bloomStrength = bloomOn ? 0.08f : 0.0f; + postUbo.update(postSettings); //------------------------------------------------------------------ - // 1. 場面を描き、1サンプルの sceneFbo にまとめる / 1. draw the scene and bring it into the single-sample sceneFbo + // 1. 場面をHDR・MSAAで描き、解決する(色の付け先は2つとも) / 1. draw the scene in HDR with MSAA and resolve it + // (both colour attachments) //------------------------------------------------------------------ - const AaMode &aa = aaModes[aaMode]; - if (aa.samples > 0) { - // MSAA:マルチサンプルのフレームバッファに描き、ブリットで解決(各ピクセルのサンプルを平均) - // MSAA: draw into the multisampled framebuffer, then resolve it with a blit (average each pixel's samples) - msaaFbo.bind(); - drawScene(); - msaaFbo.blitTo(sceneFbo); - } else if (aa.ssaa) { - // SSAA:縦横2倍(4倍のピクセル)で描き、GL_LINEARで半分に縮める=2×2ピクセルの平均 - // SSAA: draw at twice the width and height (4× the pixels) and shrink with GL_LINEAR = the mean of 2 × 2 pixels - ssaaFbo.bind(); - drawScene(); - ssaaFbo.blitTo(sceneFbo, GL_COLOR_BUFFER_BIT, GL_LINEAR); - } else { - sceneFbo.bind(); - drawScene(); + msaaFbo.bind(); + drawScene(); + msaaFbo.blitTo(sceneFbo); + + //------------------------------------------------------------------ + // 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(); } //------------------------------------------------------------------ - // 2. 画面へ:後処理は解決した後の画像に / 2. to the screen: post-processing works on the resolved image + // 3. 画面へ:場面+ブルーム、露出、トーンマッピング、sRGB / 3. to the screen: scene + bloom, exposure, tone + // mapping, sRGB //------------------------------------------------------------------ Framebuffer::bindDefault(window.width(), window.height()); - glDisable(GL_DEPTH_TEST); + // GammaMode 1と3:GPUが書くときにリニア→sRGBにする(画面がsRGBのときだけ効く) + // Gamma modes 1 and 3: the GPU converts linear → sRGB on write (only works if the screen is sRGB) + bool framebufferSrgb = postSettings.gammaMode == static_cast(GammaMode::FramebufferSrgb) || + postSettings.gammaMode == static_cast(GammaMode::Double); + if (framebufferSrgb) glEnable(GL_FRAMEBUFFER_SRGB); post->use(); post->set("uEffect", effect); post->set("uFlipX", 0); - post->set("uFxaa", fxaa ? 1 : 0); - post->set("uMagnifier", magnifier ? 1 : 0); - sceneFbo.color().bind(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); window.swapBuffers(); } diff --git a/src/mathx.hh b/src/mathx.hh index 13df5a1..bdedf93 100644 --- a/src/mathx.hh +++ b/src/mathx.hh @@ -4,6 +4,8 @@ #include +#include + // 3×3行列。列優先:c[列]が一つの列ベクトル(Mat4と同じ)。法線行列に使う。 // 3×3 matrix. Column-major: c[column] is one column vector (like Mat4). Used for the normal matrix. struct Mat3 { @@ -23,3 +25,9 @@ inline Mat3 toMat3(const Mat4 &m) { // The normal matrix: the upper-left 3×3 of the model matrix's inverse transpose (Linear Algebra chapter 10). // Transformed normals stay perpendicular to the surface even with non-uniform scaling. inline Mat3 normalMatrix(const Mat4 &model) { return toMat3(transpose(inverse(model))); } + +// 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)}; } diff --git a/src/model.cc b/src/model.cc index 70eeb2c..1e04cee 100644 --- a/src/model.cc +++ b/src/model.cc @@ -165,6 +165,20 @@ std::optional Model::load(const std::string &path) { // テクスチャ:埋め込まれたPNG/JPEGをデコードしてアップロード。glTFのUVは画像の左上が原点なので反転しない // Textures: decode the embedded PNG/JPEG and upload it. glTF UVs start at the image's top-left: no flipping std::vector averages(g.textures.size(), Vec4{1.0f, 1.0f, 1.0f, 1.0f}); + // どのテクスチャが色か(第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 colorUse(g.textures.size(), 0), dataUse(g.textures.size(), 0); + auto mark = [](std::vector &use, const GltfTextureRef &ref) { + if (ref.index >= 0 && static_cast(ref.index) < use.size()) ++use[static_cast(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); + } model.textures.resize(g.textures.size()); // 読めなかったものは空(id 0)=白 / ones that fail stay empty (id 0) = white for (size_t i = 0; i < g.textures.size(); ++i) { const GltfTexture &t = g.textures[i]; @@ -183,9 +197,14 @@ std::optional Model::load(const std::string &path) { averages[i] = {static_cast(sum[0] / pixels), static_cast(sum[1] / pixels), static_cast(sum[2] / pixels), static_cast(sum[3] / pixels)}; - // 色のテクスチャは本当はsRGB(第21章で直す) / colour textures are really sRGB (fixed in chapter 21) + // 同じテクスチャを色とデータの両方に使うファイルもありうる:その場合はリニアにして警告する + // 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}); + {.flipY = false, .mipmaps = true, .srgb = srgb}); if (t.sampler >= 0) { // 値はGLのenumそのもの(読み込み時に検査済み)。0 = 指定なし / the values are GL enums (validated); 0 = not given const GltfSampler &s = g.samplers[static_cast(t.sampler)]; diff --git a/src/texture.cc b/src/texture.cc index 4d8b98d..e874ed8 100644 --- a/src/texture.cc +++ b/src/texture.cc @@ -2,9 +2,22 @@ #include +#include #include #include +// 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(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(s * 255.0f + 0.5f); +} + // 1×1になるまで半分にした回数+1 / number of halvings until 1×1, plus one static int mipLevelCount(int width, int height) { int levels = 1; @@ -46,8 +59,15 @@ Texture2D Texture2D::fromPixels(const unsigned char *rgba, int width, int height // 乗算済みアルファ:色 × アルファ。透明なピクセルの色は(何色でも)0になる // premultiplied alpha: colour × alpha. Transparent pixels become 0 whatever colour they had std::vector pm(rgba, rgba + static_cast(width) * static_cast(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(v)); for (size_t i = 0; i < pm.size(); i += 4) - for (size_t c = 0; c < 3; ++c) pm[i + c] = static_cast((pm[i + c] * pm[i + 3] + 127) / 255); + for (size_t c = 0; c < 3; ++c) { + if (options.srgb) pm[i + c] = linearToSrgb(table[pm[i + c]] * static_cast(pm[i + 3]) / 255.0f); + else pm[i + c] = static_cast((pm[i + c] * pm[i + 3] + 127) / 255); + } texture.upload(pm.data()); } else { texture.upload(rgba); diff --git a/src/texture.hh b/src/texture.hh index d118af9..8ebcc25 100644 --- a/src/texture.hh +++ b/src/texture.hh @@ -11,9 +11,16 @@ struct TextureOptions { bool flipY = true; // 画像は上から、OpenGLのUVは下から / images start at the top, OpenGL UVs at the bottom bool mipmaps = true; // ミップマップを作る / build mipmaps - bool srgb = false; // 色の画像はsRGB(正しい扱いは第21章) / colour images are sRGB (handled properly in chapter 21) + // 色の画像(ベースカラー、発光)は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; }; diff --git a/src/uniforms.hh b/src/uniforms.hh index 2271638..b0cd31a 100644 --- a/src/uniforms.hh +++ b/src/uniforms.hh @@ -13,7 +13,7 @@ constexpr GLuint kCameraBinding = 0; // Camera:ビュー・射影・カメラの位置・時間 / view, projection, camera position, time constexpr GLuint kLightsBinding = 1; // Lights:全部の光(lights.hhのLightsBlock) / all lights (LightsBlock in lights.hh) // 2 = 影(第23章:光から見た行列) / shadows (chapter 23: light-space matrices) -// 3 = 後処理の設定(第21章:露出、ブルーム) / post-processing settings (chapter 21: exposure, bloom) +constexpr GLuint kPostBinding = 3; // Post:露出、トーンマッピング、ブルーム(第21章) / exposure, tone mapping, bloom (ch. 21) // std140の規則(よく使うものだけ) / the std140 rules (the common ones) // float, int, bool : 4バイト、4の倍数に置く / 4 bytes, at a multiple of 4 @@ -64,3 +64,38 @@ private: Buffer buffer; GLuint binding; }; + +// トーンマッピングの方法(post.fragのuToneMapperと同じ番号) / tone mappers (same numbers as uToneMapper in post.frag) +enum class ToneMapper { Clamp = 0, Reinhard = 1, Aces = 2 }; +// ガンマ(画面に出すときのsRGB変換)の方法(post.fragのuGammaModeと同じ番号) +// How gamma (the sRGB encoding for the screen) is applied (same numbers as uGammaMode in post.frag) +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) +}; +// 後処理を何を見せるか / 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(ToneMapper::Aces); + int gammaMode = static_cast(GammaMode::Shader); + int view = static_cast(PostView::Final); + int pad[2] = {0, 0}; +}; +static_assert(offsetof(PostBlock, bloomThreshold) == 8); +static_assert(offsetof(PostBlock, view) == 20); +static_assert(sizeof(PostBlock) == 32);