diff --git a/CMakeLists.txt b/CMakeLists.txt index 9d447d1..9ec8755 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -43,7 +43,8 @@ add_executable(game src/model.cc src/framebuffer.cc src/cubemap.cc - src/gpu_timer.cc) + src/gpu_timer.cc + src/tangents.cc) target_include_directories(game PRIVATE src external/stb external/linalg) target_link_libraries(game PRIVATE glad stb_image glfw) diff --git a/assets/LICENSE.txt b/assets/LICENSE.txt index a439a10..4aa56a3 100644 --- a/assets/LICENSE.txt +++ b/assets/LICENSE.txt @@ -14,3 +14,6 @@ models/window.glb 花箱つきの窓 / a window with a flower box (ch models/rock.glb 岩(インスタンシング用) / a rock for instancing (chapter 19) models/crate.glb 木箱のモデル / crate model models/diorama.glb 小さな場面 / a small diorama scene (chapter 21) +textures/bricks.png レンガ / bricks (chapter 22) +textures/bricks_normal.png レンガの法線マップ+高さ / brick normal map + height (chapter 22) +models/barrel.glb 樽(PBRのテクスチャ付き) / a barrel with PBR textures (chapter 22) diff --git a/assets/models/barrel.glb b/assets/models/barrel.glb new file mode 100644 index 0000000..6cc887a Binary files /dev/null and b/assets/models/barrel.glb differ diff --git a/assets/textures/bricks.png b/assets/textures/bricks.png new file mode 100644 index 0000000..55b201e Binary files /dev/null and b/assets/textures/bricks.png differ diff --git a/assets/textures/bricks_normal.png b/assets/textures/bricks_normal.png new file mode 100644 index 0000000..c42355c Binary files /dev/null and b/assets/textures/bricks_normal.png differ diff --git a/shaders/phong.frag b/shaders/phong.frag index f0a1f17..7ad7473 100644 --- a/shaders/phong.frag +++ b/shaders/phong.frag @@ -3,6 +3,7 @@ in vec3 vWorldPos; in vec3 vNormal; in vec2 vUv; in vec3 vTint; // インスタンスの色(第19章) / the instance colour (chapter 19) +in vec4 vTangent; // ワールド座標の接線、w = 従法線の向き(第22章) / world-space tangent, w = bitangent sign (chapter 22) // 表面の性質。色はそれぞれのマップと掛け合わされる / surface properties; each colour is multiplied with its map struct Material { @@ -16,12 +17,19 @@ struct Material { bool doubleSided; // 裏面では法線を反転する / flip the normal on back faces vec3 reflectivity; // 空の映り込みの強さ(0 = なし、第18章) / strength of the sky reflection (0 = none, chapter 18) float reflectionBlur; // 0 = 鏡、1 = 一番ぼやけたミップマップ / 0 = mirror, 1 = the blurriest mip level + float normalScale; // 法線マップの強さ(0 = マップなし、第22章) / normal map strength (0 = no map, chapter 22) + float parallaxScale; // 視差マッピングの深さ(UV単位、0 = なし) / parallax depth (UV units, 0 = none) }; uniform Material uMaterial; layout(binding = 0) uniform sampler2D uDiffuseMap; layout(binding = 1) uniform sampler2D uSpecularMap; layout(binding = 2) uniform sampler2D uEmissionMap; +// 法線マップ(第22章):RGB = 接線空間の法線、A = 高さ(視差マッピング用)。ユニット4 +// Normal map (chapter 22): RGB = tangent-space normal, A = height (for parallax mapping). Unit 4 +layout(binding = 4) uniform sampler2D uNormalMap; +uniform bool uNormalMapping = true; // 法線マップを使う(デバッグ用に切れる) / use normal maps (can be turned off for debugging) +uniform bool uParallaxMapping = true; // 視差マッピングを使う / use parallax mapping // 環境(空)のキューブマップ。ユニット3(第18章) / the environment (sky) cube map, unit 3 (chapter 18) layout(binding = 3) uniform samplerCube uEnvironmentMap; uniform vec3 uEnvironmentTint; // 空の明るさ(昼1、夜は暗く) / brightness of the sky (1 by day, dark at night) @@ -76,8 +84,10 @@ layout(std140, binding = 0) uniform Camera { float uTime; // アニメーションの時間(秒) / animation time (seconds) }; -// 0 = 全部、1 = 環境光、2 = 拡散反射、3 = 鏡面反射、4 = 発光、5 = 法線 -// 0 = everything, 1 = ambient, 2 = diffuse, 3 = specular, 4 = emission, 5 = normals +// 0 = 全部、1 = 環境光、2 = 拡散反射、3 = 鏡面反射、4 = 発光、5 = 法線(法線マップ後)、 +// 6 = 頂点の法線(法線マップ前)、7 = 接線、8 = 従法線(第22章) +// 0 = everything, 1 = ambient, 2 = diffuse, 3 = specular, 4 = emission, 5 = normals (after normal mapping), +// 6 = vertex normals (before normal mapping), 7 = tangents, 8 = bitangents (chapter 22) uniform int uViewMode; // アルファトゥカバレッジ(第20章):マスクのマテリアルを捨てる代わりに、アルファをMSAAのサンプルの割合にする。 @@ -139,8 +149,55 @@ float attenuate(float d, vec3 k) { return 1.0 / (k.x + k.y * d + k.z * d * d); } +// 視差オクルージョンマッピング(第22章):目から表面の奥へ、高さマップの層を一枚ずつ進み、最初に高さマップの +// 下に入った所のUVを返す(前の層との間は直線で補間)。v = 接線空間の目への向き。 +// ループの中は分岐なので、ミップマップの段は外で求めた微分で指定する(textureGrad) +// Parallax occlusion mapping (chapter 22): march from the eye into the surface one height layer at a time and return +// the UV where the ray first goes below the height map (interpolated linearly with the previous layer). v = the +// direction to the eye in tangent space. Inside the loop we are in a branch, so the mip level comes from derivatives +// computed outside (textureGrad) +vec2 parallaxOcclusion(vec2 uv, vec3 v, vec2 dx, vec2 dy) { + float layers = mix(32.0, 8.0, clamp(v.z, 0.0, 1.0)); // 斜めほど多く / more layers at grazing angles + float layerDepth = 1.0 / layers; + // 一層ごとのUVのずれ:視線の傾き(xy / z)× 深さ / the UV step per layer: the view's slope (xy / z) × depth + vec2 delta = v.xy / max(v.z, 0.1) * uMaterial.parallaxScale / layers; + float depth = 0.0; + float mapDepth = 1.0 - textureGrad(uNormalMap, uv, dx, dy).a; // 深さ = 1 − 高さ / depth = 1 − height + for (int i = 0; i < 32 && depth < mapDepth; ++i) { + uv -= delta; + mapDepth = 1.0 - textureGrad(uNormalMap, uv, dx, dy).a; + depth += layerDepth; + } + // 最後の2層の間で交点を補間 / interpolate the crossing between the last two layers + vec2 prev = uv + delta; + float after = mapDepth - depth; + float before = (1.0 - textureGrad(uNormalMap, prev, dx, dy).a) - depth + layerDepth; + float w = after / (after - before + 1e-6); + return mix(uv, prev, w); +} + void main() { - vec4 base = texture(uDiffuseMap, vUv); + // 接線空間(TBN):補間で直交が崩れるので、法線に対してもう一度グラム・シュミット(第22章) + // Tangent space (TBN): interpolation breaks the orthogonality, so Gram-Schmidt against the normal again (chapter 22) + vec3 geometricNormal = normalize(vNormal); + vec3 tangent = vTangent.xyz - dot(vTangent.xyz, geometricNormal) * geometricNormal; + bool hasTangent = dot(tangent, tangent) > 1e-10; // 接線がない頂点は(0,0,0,0) / vertices without tangents have (0,0,0,0) + tangent = hasTangent ? normalize(tangent) : vec3(1.0, 0.0, 0.0); + vec3 bitangent = cross(geometricNormal, tangent) * (vTangent.w < 0.0 ? -1.0 : 1.0); + // 両面のマテリアルを裏から見ているなら、法線は裏を向く(接線と従法線はそのまま) + // Seen from behind, a double-sided surface's normal points the other way (tangent and bitangent stay) + if (uMaterial.doubleSided && !gl_FrontFacing) geometricNormal = -geometricNormal; + + // 視差マッピング:これより後のテクスチャはすべてずらしたUVで読む / parallax mapping: every texture below is read at + // the shifted UV + vec2 uv = vUv; + vec2 uvDx = dFdx(vUv), uvDy = dFdy(vUv); + if (uParallaxMapping && uMaterial.parallaxScale > 0.0 && hasTangent) { + vec3 v = normalize(uViewPos - vWorldPos); + uv = parallaxOcclusion(vUv, vec3(dot(v, tangent), dot(v, bitangent), dot(v, geometricNormal)), uvDx, uvDy); + } + + vec4 base = textureGrad(uDiffuseMap, uv, uvDx, uvDy); float alpha = uMaterial.alpha * base.a; // アルファが1ピクセルでどれだけ変わるか(分岐の前に:fwidthは隣のピクセルと一緒に計算する) // How much alpha changes across one pixel (before any branch: fwidth is computed together with the neighbours) @@ -160,14 +217,20 @@ void main() { Surface s; s.position = vWorldPos; - s.normal = normalize(vNormal); - // 両面のマテリアルを裏から見ているなら、法線は裏を向く / seen from behind, a double-sided surface's normal points the other way - if (uMaterial.doubleSided && !gl_FrontFacing) s.normal = -s.normal; + s.normal = geometricNormal; + // 法線マップ:接線空間の法線(x, y, z)を、ワールド座標の x·T + y·B + z·N に直す。強さはxyに掛ける(glTFと同じ) + // Normal map: turn the tangent-space normal (x, y, z) into world space as x·T + y·B + z·N. The strength scales xy + // (as in glTF) + if (uNormalMapping && hasTangent && uMaterial.normalScale > 0.0) { + vec3 m = textureGrad(uNormalMap, uv, uvDx, uvDy).xyz * 2.0 - 1.0; // 0..1 → -1..1 + m.xy *= uMaterial.normalScale; + s.normal = normalize(m.x * tangent + m.y * bitangent + m.z * geometricNormal); + } s.view = normalize(uViewPos - vWorldPos); s.diffuse = uMaterial.diffuse * vTint * base.rgb; - s.specular = uMaterial.specular * texture(uSpecularMap, vUv).rgb; + s.specular = uMaterial.specular * textureGrad(uSpecularMap, uv, uvDx, uvDy).rgb; s.shininess = uMaterial.shininess; - vec3 emission = uMaterial.emission * texture(uEmissionMap, vUv).rgb; + vec3 emission = uMaterial.emission * textureGrad(uEmissionMap, uv, uvDx, uvDy).rgb; vec3 diffuse = vec3(0.0); vec3 specular = vec3(0.0); @@ -209,6 +272,13 @@ void main() { else if (uViewMode == 3) color = specular; else if (uViewMode == 4) color = emission; else if (uViewMode == 5) color = s.normal * 0.5 + 0.5; + else if (uViewMode == 6) color = geometricNormal * 0.5 + 0.5; + else if (uViewMode == 7) color = hasTangent ? tangent * 0.5 + 0.5 : vec3(0.0); + else if (uViewMode == 8) color = hasTangent ? bitangent * 0.5 + 0.5 : vec3(0.0); + // ベクトルの表示は、post.fragがsRGBにした後でちょうどこの値になるように、先にリニアへ戻しておく + // Vector views: convert to linear first, so that after post.frag's sRGB encoding the screen shows exactly this value + if (uViewMode >= 5) + color = mix(color / 12.92, pow((color + 0.055) / 1.055, vec3(2.4)), step(vec3(0.04045), color)); // 不透明とマスクはアルファ1。ブレンドだけ本当のアルファを出す。アルファトゥカバレッジのときは、このアルファが // 覆うサンプルの数になる / opaque and mask output alpha 1; only blend outputs its alpha. With alpha to coverage this // alpha becomes the number of samples covered diff --git a/shaders/phong.vert b/shaders/phong.vert index 34d7561..149eb5c 100644 --- a/shaders/phong.vert +++ b/shaders/phong.vert @@ -2,6 +2,9 @@ layout(location = 0) in vec3 aPosition; layout(location = 1) in vec3 aNormal; // 面の向き(モデル座標) / which way the surface faces (model space) layout(location = 2) in vec2 aUv; +// 接線(第22章):xyz = uが増える向き、w = 従法線の向き(±1)。(0,0,0,0) = なし +// Tangent (chapter 22): xyz = the direction in which u grows, w = the bitangent's sign (±1). (0,0,0,0) = none +layout(location = 3) in vec4 aTangent; // カメラ(ユニフォームバッファ、結合点0、std140)。使う全部のシェーダーで同じ宣言(C++ではCameraBlock) // The camera (uniform buffer, binding 0, std140). The same declaration in every shader that uses it (CameraBlock in C++) @@ -19,6 +22,7 @@ uniform mat3 uNormalMatrix; // 法線をワールド座標へ(モデル行列 out vec3 vWorldPos; out vec3 vNormal; out vec2 vUv; +out vec4 vTangent; // ワールド座標の接線と向き / world-space tangent and sign // インスタンスごとの色(第19章)。インスタンシングでないときはこのユニフォーム(既定値は白) // The per-instance colour (chapter 19). Without instancing it comes from this uniform (white by default) uniform vec3 uTint = vec3(1.0); @@ -29,6 +33,11 @@ void main() { vWorldPos = world.xyz; vNormal = uNormalMatrix * aNormal; // 正規化はフラグメントシェーダーで / normalized in the fragment shader vUv = aUv; + // 接線は面に沿う向きなので、法線行列ではなくモデル行列で変換する。鏡像(行列式が負)なら従法線も反転 + // A tangent lies along the surface, so it is transformed with the model matrix, not the normal matrix. A mirroring + // matrix (negative determinant) flips the bitangent too + mat3 m = mat3(uModel); + vTangent = vec4(m * aTangent.xyz, aTangent.w * (determinant(m) < 0.0 ? -1.0 : 1.0)); vTint = uTint; gl_Position = uProj * uView * world; } diff --git a/shaders/phong_instanced.vert b/shaders/phong_instanced.vert index dfe298f..3c009ca 100644 --- a/shaders/phong_instanced.vert +++ b/shaders/phong_instanced.vert @@ -4,7 +4,7 @@ layout(location = 0) in vec3 aPosition; layout(location = 1) in vec3 aNormal; layout(location = 2) in vec2 aUv; -// location 3は接線(第22章) / location 3 is the tangent (chapter 22) +layout(location = 3) in vec4 aTangent; // 接線(第22章) / tangent (chapter 22) layout(location = 4) in mat4 aInstanceModel; // mat4はlocationを4つ使う(4〜7) / a mat4 takes four locations (4..7) layout(location = 8) in vec3 aInstanceColor; @@ -24,6 +24,7 @@ uniform float uOrbitSpeed; // 環の公転の速さ(半径8 mで、ラジア out vec3 vWorldPos; out vec3 vNormal; out vec2 vUv; +out vec4 vTangent; out vec3 vTint; // Y軸周りの回転 / rotation about the Y axis @@ -44,6 +45,8 @@ void main() { // The rocks are scaled uniformly, so the normal can simply be rotated by the 3×3 part (phong.frag normalizes it) vNormal = mat3(orbit * aInstanceModel) * (uNormalMatrix * aNormal); vUv = aUv; + mat3 m = mat3(model); + vTangent = vec4(m * aTangent.xyz, aTangent.w * (determinant(m) < 0.0 ? -1.0 : 1.0)); vTint = aInstanceColor; gl_Position = uProj * uView * world; } diff --git a/src/main.cc b/src/main.cc index 43c6b6a..43a53e3 100644 --- a/src/main.cc +++ b/src/main.cc @@ -1,5 +1,5 @@ -// 第21章:ガンマ補正とHDR -// Chapter 21: gamma correction and HDR +// 第22章:法線マッピング +// Chapter 22: normal mapping // // 操作 / Controls: // WASD 前後左右に移動 / move forward, back, left, right @@ -7,20 +7,18 @@ // Shift 速く動く / move faster // マウス / mouse 向きを変える(FPS)、左ドラッグで回る(オービット) / look around (FPS), drag with the left button to orbit // ホイール / wheel ズーム / zoom -// = / - 露出を上げる・下げる(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 +// M 法線マップのオン・オフ / normal maps on / off +// X 視差(オクルージョン)マッピングのオン・オフ / parallax (occlusion) mapping on / off +// L 壁の前を回る点光源のオン・オフ / the point light circling in front of the wall on / off +// V 表示:全部 → 環境光 → 拡散 → 鏡面 → 発光 → 法線 → 頂点の法線 → 接線 → 従法線 +// view: all → ambient → diffuse → specular → emission → normals → vertex normals → tangents → bitangents +// = / - 露出を上げる・下げる / exposure up / down // 1〜6 効果:なし / 反転 / グレースケール / シャープ / ぼかし / エッジ検出 // effect: none / invert / grayscale / sharpen / blur / edge detection // C FPS ⇔ オービットカメラ / FPS ⇔ orbit camera -// V 表示:全部 → 環境光 → 拡散 → 鏡面 → 発光 → 法線 / view: all → ambient → diffuse → specular → emission → normals // N 昼 ⇔ 夜 / day ⇔ night // F 懐中電灯のオン・オフ / flashlight on / off -// P 風車を止める・動かす / pause / resume the windmill +// P 風車と点光源を止める・動かす / pause / resume the windmill and the point light // Tab カーソルのキャプチャ切り替え / toggle cursor capture // R シェーダーを読み直す / reload the shaders // Esc 終了 / quit @@ -58,11 +56,10 @@ static const Placement kCrates[] = { 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 kViewModeNames[] = {"all", "ambient", "diffuse", "specular", "emission", + "normals", "vertex normals", "tangents", "bitangents"}; +constexpr int kViewModes = 9; +constexpr int kFirstVectorView = 5; // ここからはベクトルを色で見せる / from here on, vectors are shown as colours static const char *const kEffectNames[] = {"none", "invert", "grayscale", "sharpen", "blur", "edge detection"}; static float random01(std::uint32_t &state) { @@ -104,20 +101,7 @@ static Mat4 beam(Vec3 a, Vec3 b, float thickness) { return m; } -// 柵と電柱と電線:細いものほどエイリアスが目立つ / a fence, poles and wires: the thinner, the worse the aliasing -static std::vector makeFence() { - std::vector fence; - Vec3 a = {-5.4f, 0.0f, 5.0f}, b = {-1.9f, 0.0f, 8.3f}; - Vec3 along = normalize(b - a); - int pickets = static_cast(length(b - a) / 0.2f); - for (int i = 0; i <= pickets; ++i) { - Vec3 p = a + (0.2f * static_cast(i)) * along; - fence.push_back(beam(p, p + Vec3{0.0f, 0.95f, 0.0f}, 0.05f)); - } - for (float y : {0.3f, 0.75f}) fence.push_back(beam(a + Vec3{0, y, 0}, b + Vec3{0, y, 0}, 0.04f)); - return fence; -} - +// 電柱と電線(第20章) / poles and wires (chapter 20) static std::vector makeWires() { std::vector wires; 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}}; @@ -163,7 +147,7 @@ static std::vector makeLanterns() { int main() { Window window; - if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 21")) return 1; + if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 22")) return 1; // 画面(既定のフレームバッファ)がsRGBか:GL_FRAMEBUFFER_SRGBが効くのはsRGBのときだけ // Is the screen (the default framebuffer) sRGB? GL_FRAMEBUFFER_SRGB only has an effect if it is @@ -181,7 +165,13 @@ int main() { 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; + // レンガ:色はsRGB、法線マップはデータなのでリニア(Aは高さ) / bricks: the colour is sRGB, the normal map is data and + // stays linear (A = height) + std::optional brickTexture = Texture2D::load("assets/textures/bricks.png", {.srgb = true}); + std::optional brickNormal = Texture2D::load("assets/textures/bricks_normal.png"); + if (!phong || !skybox || !post || !blur || !unlit || !sky || !floorTexture || !grassTexture || !brickTexture || + !brickNormal) + return 1; grassTexture->setWrap(GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE); for (const Shader *s : {&*phong, &*skybox, &*post, &*unlit}) if (!s->checkUniformBlock("Camera", sizeof(CameraBlock)) || !s->checkUniformBlock("Lights", sizeof(LightsBlock)) || @@ -190,7 +180,10 @@ int main() { std::optional scene = Model::load("assets/models/diorama.glb"); std::optional crate = Model::load("assets/models/crate.glb"); - if (!scene || !crate) return 1; + // 樽:色・金属と粗さ・法線・遮蔽のテクスチャ付き。蓋にはTANGENTがない(Modelが計算する) + // The barrel: colour, metallic-roughness, normal and occlusion textures. The lid has no TANGENT (Model computes it) + std::optional barrel = Model::load("assets/models/barrel.glb"); + if (!scene || !crate || !barrel) return 1; const unsigned char whitePixel[4] = {255, 255, 255, 255}; Texture2D white = Texture2D::fromPixels(whitePixel, 1, 1, {.flipY = false, .mipmaps = false}); @@ -227,7 +220,7 @@ int main() { glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS); Camera fps; - fps.position = {0.0f, 2.0f, 12.5f}; + fps.position = {0.3f, 1.6f, 10.0f}; fps.pitch = radians(-4.0f); OrbitCamera orbit; @@ -235,7 +228,7 @@ int main() { orbit.distance = 11.0f; orbit.yaw = radians(20.0f); - bool useOrbit = false, bloomOn = true; + bool useOrbit = false, normalMaps = true, parallax = true, movingLight = true; int viewMode = 0, effect = 0; float exposureEv = 0.0f; // 露出(段、EV):倍率は2^EV / exposure in stops (EV): the multiplier is 2^EV PostBlock postSettings; @@ -255,7 +248,7 @@ int main() { printf("camera: %s\n", useOrbit ? "orbit" : "fps"); } if (key == GLFW_KEY_V) { - viewMode = (viewMode + 1) % 6; + viewMode = (viewMode + 1) % kViewModes; printf("view: %s\n", kViewModeNames[viewMode]); } if (key >= GLFW_KEY_1 && key <= GLFW_KEY_6) { @@ -266,30 +259,15 @@ int main() { exposureEv += key == GLFW_KEY_EQUAL ? 0.5f : -0.5f; printf("exposure: %+.1f EV (x%.3g)\n", exposureEv, std::exp2(exposureEv)); } - if (key == GLFW_KEY_T) { - 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_M) { + normalMaps = !normalMaps; + printf("normal maps: %s\n", normalMaps ? "on" : "off"); } - 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_X) { + parallax = !parallax; + printf("parallax mapping: %s\n", parallax ? "on" : "off"); } + if (key == GLFW_KEY_L) movingLight = !movingLight; if (key == GLFW_KEY_N) night = !night; if (key == GLFW_KEY_F) flashlightOn = !flashlightOn; if (key == GLFW_KEY_P) windmillMoving = !windmillMoving; @@ -310,14 +288,31 @@ int main() { grassMaterial.specular = {0.04f, 0.04f, 0.04f}; grassMaterial.shininess = 8.0f; - std::vector fence = makeFence(); std::vector wires = makeWires(); - Material woodMaterial; + // レンガの壁(5 × 2.5 m、厚さ0.3 m)、柱、球。箱のUVはメートル単位で、1 mごとにテクスチャ1枚 + // The brick wall (5 × 2.5 m, 0.3 m thick), a pillar and a sphere. Box UVs are in metres, one texture tile per metre + Mesh wallMesh = makeBox({5.0f, 2.5f, 0.3f}); + Mesh pillarMesh = makeBox({0.6f, 3.0f, 0.6f}); + Mesh brickSphere = makeSphere(48, 24); + Material brickMaterial; + brickMaterial.diffuseMap = &*brickTexture; + brickMaterial.normalMap = &*brickNormal; + brickMaterial.specular = {0.08f, 0.08f, 0.08f}; + brickMaterial.shininess = 24.0f; + brickMaterial.parallaxScale = 0.04f; // 1枚(1 m)の4% = 4 cm の深さ / 4 % of a tile (1 m) = 4 cm deep + struct Piece { + const Mesh *mesh; + Mat4 model; + }; + const Piece bricks[] = { + {&wallMesh, translate({-1.6f, 1.25f, 4.2f})}, + {&pillarMesh, translate({1.6f, 1.5f, 4.4f}) * rotateY(0.3f)}, + {&brickSphere, translate({-2.3f, 0.6f, 6.9f}) * scale({1.2f, 1.2f, 1.2f})}, + }; + // 樽の置き場所 / where the barrels stand + const Placement barrels[] = {{{-0.4f, 0.0f, 5.6f}, 0.3f}, {{0.35f, 0.0f, 6.1f}, 2.0f}, {{2.6f, 0.0f, 5.9f}, 1.1f}}; // 手で選んだ色は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}; @@ -328,6 +323,8 @@ int main() { std::vector lanterns = makeLanterns(); Mesh sphereMesh = makeSphere(24, 12); constexpr float kLanternGlow = 6.0f; + const Vec3 kMovingLightColor = {1.0f, 0.75f, 0.45f}; + Vec3 movingLightPos; FullscreenTriangle fullscreen; glEnable(GL_CULL_FACE); @@ -342,6 +339,8 @@ int main() { phong->use(); phong->set("uViewMode", viewMode); + phong->set("uNormalMapping", normalMaps ? 1 : 0); + phong->set("uParallaxMapping", parallax ? 1 : 0); phong->set("uEnvironmentTint", environmentTint); phong->set("uModel", Mat4::identity()); phong->set("uNormalMatrix", normalMatrix(Mat4::identity())); @@ -360,13 +359,28 @@ int main() { 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) { - phong->set("uModel", m); - phong->set("uNormalMatrix", normalMatrix(m)); - cubeMesh.draw(); - } + wireMaterial.apply(*phong, white); + for (const Mat4 &m : wires) { + phong->set("uModel", m); + phong->set("uNormalMatrix", normalMatrix(m)); + cubeMesh.draw(); + } + // レンガ(法線マップ+視差) / the bricks (normal map + parallax) + brickMaterial.apply(*phong, white); + for (const Piece &b : bricks) { + phong->set("uModel", b.model); + phong->set("uNormalMatrix", normalMatrix(b.model)); + b.mesh->draw(); + } + for (const Placement &b : barrels) barrel->draw(*phong, translate(b.position) * rotateY(b.angle), white, ModelPass::Opaque); + // 回る点光源の目印(HDRで光る) / the marker of the circling point light (glows in HDR) + if (movingLight) { + unlit->use(); + unlit->set("uColor", 8.0f * kMovingLightColor); + Mat4 model = translate(movingLightPos) * scale({0.08f, 0.08f, 0.08f}); + unlit->set("uModel", model); + sphereMesh.draw(); + phong->use(); } // 草:アルファトゥカバレッジならdiscardの代わりにサンプルの一部だけを覆う(MSAAのときだけ意味がある) @@ -426,6 +440,9 @@ int main() { Quat::fromAxisAngle({0.0f, 0.0f, 1.0f}, -0.8f * windmillTime) * rotorStart; float aspect = static_cast(sceneFbo.width()) / static_cast(sceneFbo.height()); + // 壁の前を回る光:壁すれすれの角度から照らすと凹凸がよく見える / the light circling in front of the wall: light from + // grazing angles shows the bumps best + movingLightPos = {-1.6f + 1.8f * std::cos(0.7f * windmillTime), 1.3f + 0.6f * std::sin(1.3f * windmillTime), 4.75f}; CameraBlock camera; camera.view = useOrbit ? orbit.view() : fps.view(); camera.proj = useOrbit ? orbit.projection(aspect) : fps.projection(aspect); @@ -451,12 +468,23 @@ int main() { for (size_t i = 3; i < 6; ++i) lights.points.push_back({.position = lanterns[i].position, .color = 1.5f * lanterns[i].color, .attenuation = kMediumRange}); } + if (movingLight) + lights.points.push_back({.position = movingLightPos, .color = 2.5f * kMovingLightColor, .attenuation = kMediumRange}); if (flashlightOn) lights.spots.push_back({.position = camera.viewPos, .direction = viewDir, .color = {1.0f, 0.95f, 0.85f}}); lightsUbo.update(lights.toBlock()); 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; + postSettings.bloomStrength = 0.08f; + // ベクトルの表示(法線・接線)は値をそのまま見せる:トーンマッピングなし、露出1(phong.fragが逆変換して出す) + // The vector views (normals, tangents) show the raw values: no tone mapping, exposure 1 (phong.frag outputs them + // pre-decoded) + if (viewMode >= kFirstVectorView) { + postSettings.exposure = 1.0f; + postSettings.toneMapper = static_cast(ToneMapper::Clamp); + } else { + postSettings.toneMapper = static_cast(ToneMapper::Aces); + } postUbo.update(postSettings); //------------------------------------------------------------------ diff --git a/src/material.cc b/src/material.cc index 43d1379..e011f6f 100644 --- a/src/material.cc +++ b/src/material.cc @@ -16,4 +16,7 @@ void Material::apply(const Shader &shader, const Texture2D &white) const { (diffuseMap ? diffuseMap : &white)->bind(0); (specularMap ? specularMap : &white)->bind(1); (emissionMap ? emissionMap : &white)->bind(2); + shader.set("uMaterial.normalScale", normalMap ? normalScale : 0.0f); + shader.set("uMaterial.parallaxScale", normalMap ? parallaxScale : 0.0f); + (normalMap ? normalMap : &white)->bind(4); } diff --git a/src/material.hh b/src/material.hh index bd3ef6e..c6e3fd2 100644 --- a/src/material.hh +++ b/src/material.hh @@ -35,8 +35,17 @@ struct Material { const Texture2D *diffuseMap = nullptr; // テクスチャユニット0 / texture unit 0 const Texture2D *specularMap = nullptr; // テクスチャユニット1 / texture unit 1 const Texture2D *emissionMap = nullptr; // テクスチャユニット2 / texture unit 2 + // 法線マップ(第22章):接線空間の法線(RGB、リニア)。Aは視差マッピング用の高さ(1 = 一番高い) + // Normal map (chapter 22): tangent-space normals (RGB, linear). A = height for parallax mapping (1 = highest) + const Texture2D *normalMap = nullptr; // テクスチャユニット4 / texture unit 4 + float normalScale = 1.0f; // 凹凸の強さ(glTFのnormalTexture.scale:xyに掛ける) / bump strength (glTF's + // normalTexture.scale: multiplies x and y) + float parallaxScale = 0.0f; // 視差の深さ(UVの単位、0 = なし)。OpenGLのUV(vが上)の物だけ / parallax depth (in UV + // units, 0 = none). Only for OpenGL-convention UVs (v up) - // シェーダーのuMaterialを設定し、マップをユニット0〜2に繋ぐ。nullptrのマップの代わりにwhiteを繋ぐ。 - // Sets the shader's uMaterial and binds the maps to units 0..2. Binds `white` in place of a nullptr map. + // シェーダーのuMaterialを設定し、マップをユニット0〜2と4に繋ぐ。nullptrのマップの代わりにwhiteを繋ぐ。 + // 法線マップがなければnormalScaleを0にする:白(1,1,1)の法線は(0,0,1)になり、凹凸なし(フラグは要らない)。 + // Sets the shader's uMaterial and binds the maps to units 0..2 and 4. Binds `white` in place of a nullptr map. + // Without a normal map normalScale is set to 0: the white (1,1,1) normal becomes (0,0,1), no bumps (no flag needed). void apply(const Shader &shader, const Texture2D &white) const; }; diff --git a/src/mesh.hh b/src/mesh.hh index 4205eb4..372adf7 100644 --- a/src/mesh.hh +++ b/src/mesh.hh @@ -23,8 +23,9 @@ struct VertexAttrib { GLboolean normalized = GL_FALSE; // 整数を0〜1にするか / map integers to 0..1? }; -// 3Dの標準の頂点:位置・法線・UV。シェーダーではlocation 0, 1, 2。 -// The standard 3D vertex: position, normal, UV. Locations 0, 1, 2 in the shaders. +// 3Dの標準の頂点:位置・法線・UV。シェーダーではlocation 0, 1, 2。第22章からshapes.ccは接線付きのModelVertexを使う。 +// The standard 3D vertex: position, normal, UV. Locations 0, 1, 2 in the shaders. From chapter 22 shapes.cc uses +// ModelVertex, which also has a tangent. struct Vertex3D { Vec3 position; Vec3 normal; // 面の向き(第10章のライティングで使う) / which way the surface faces (used for lighting in chapter 10) diff --git a/src/model.cc b/src/model.cc index 1e04cee..e38413d 100644 --- a/src/model.cc +++ b/src/model.cc @@ -1,5 +1,7 @@ #include "model.hh" +#include "tangents.hh" + #include #include #include @@ -128,6 +130,14 @@ static std::optional loadPrimitive(const Gltf &g, const GltfPr indices.clear(); } + // 法線マップがあるのにTANGENTがなければ自分で計算する(glTFの仕様はMikkTSpaceを勧めるが、ここでは簡単な方法、第22章) + // A normal map but no TANGENT: compute them ourselves (the glTF spec recommends MikkTSpace; we use the simple + // method, chapter 22) + bool normalMapped = p.material >= 0 && static_cast(p.material) < g.materials.size() && + g.materials[static_cast(p.material)].normalTexture.index >= 0; + if (normalMapped && !tangents && uvs && p.mode == kGltfTriangles) + computeTangents(vertices, indices, UvConvention::Gltf); + Model::Primitive out; out.material = p.material; out.boundsMin = out.boundsMax = vertices.empty() ? Vec3{} : vertices[0].position; @@ -357,6 +367,8 @@ void Model::drawItems(const std::vector &items, const Shader &shader, Material m = md.phong; m.diffuseMap = texture(md.pbr.baseColorTexture.index); // 色 = 係数 × テクスチャ / colour = factor × texture m.emissionMap = texture(md.pbr.emissiveTexture.index); + m.normalMap = texture(md.pbr.normalTexture.index); // 第22章 / chapter 22 + m.normalScale = md.pbr.normalTexture.scale; m.apply(shader, *white); } // 両面のマテリアル(葉、ガラス、帆)は裏からも見えるようにカリングを切る diff --git a/src/shapes.cc b/src/shapes.cc index f3d35b1..927030b 100644 --- a/src/shapes.cc +++ b/src/shapes.cc @@ -1,25 +1,45 @@ #include "shapes.hh" +#include "tangents.hh" + #include #include // 一つの面(正方形)を足す。normal = 外向き、right × up = normal になるように選ぶ。 // Adds one face (a square). normal points outwards; choose right and up so that right × up = normal. -static void addFace(std::vector &vertices, std::vector &indices, Vec3 normal, Vec3 right, - Vec3 up) { +static void addFace(std::vector &vertices, std::vector &indices, Vec3 normal, Vec3 right, + Vec3 up, Vec3 half = {0.5f, 0.5f, 0.5f}, float tile = 0.0f) { std::uint32_t first = static_cast(vertices.size()); - Vec3 c = 0.5f * normal; // 面の中心 / centre of the face - Vec3 r = 0.5f * right, u = 0.5f * up; - vertices.push_back({c - r - u, normal, {0.0f, 0.0f}}); // 左下 / bottom left - vertices.push_back({c + r - u, normal, {1.0f, 0.0f}}); // 右下 / bottom right - vertices.push_back({c + r + u, normal, {1.0f, 1.0f}}); // 右上 / top right - vertices.push_back({c - r + u, normal, {0.0f, 1.0f}}); // 左上 / top left + auto extent = [&](Vec3 axis) { return std::fabs(axis.x) * half.x + std::fabs(axis.y) * half.y + std::fabs(axis.z) * half.z; }; + Vec3 c = extent(normal) * normal; // 面の中心 / centre of the face + Vec3 r = extent(right) * right, u = extent(up) * up; + // tile > 0:UVはメートル÷tile(面の大きさに合わせて繰り返す)、0:面ごとに0〜1 / tile > 0: UV = metres ÷ tile + // (repeats with the face size); 0: 0..1 per face + float su = tile > 0.0f ? 2.0f * extent(right) / tile : 1.0f, sv = tile > 0.0f ? 2.0f * extent(up) / tile : 1.0f; + vertices.push_back({c - r - u, normal, {0.0f, 0.0f}, {}}); // 左下 / bottom left + vertices.push_back({c + r - u, normal, {su, 0.0f}, {}}); // 右下 / bottom right + vertices.push_back({c + r + u, normal, {su, sv}, {}}); // 右上 / top right + vertices.push_back({c - r + u, normal, {0.0f, sv}, {}}); // 左上 / top left // 反時計回りの三角形2つ / two counter-clockwise triangles indices.insert(indices.end(), {first, first + 1, first + 2, first + 2, first + 3, first}); } +Mesh makeBox(Vec3 size, float tileSize) { + std::vector vertices; + std::vector indices; + Vec3 h = 0.5f * size; + addFace(vertices, indices, {0, 0, 1}, {1, 0, 0}, {0, 1, 0}, h, tileSize); + addFace(vertices, indices, {0, 0, -1}, {-1, 0, 0}, {0, 1, 0}, h, tileSize); + addFace(vertices, indices, {1, 0, 0}, {0, 0, -1}, {0, 1, 0}, h, tileSize); + addFace(vertices, indices, {-1, 0, 0}, {0, 0, 1}, {0, 1, 0}, h, tileSize); + addFace(vertices, indices, {0, 1, 0}, {1, 0, 0}, {0, 0, -1}, h, tileSize); + addFace(vertices, indices, {0, -1, 0}, {1, 0, 0}, {0, 0, 1}, h, tileSize); + computeTangents(vertices, indices, UvConvention::OpenGl); + return Mesh(vertices, indices, kModelVertexLayout); +} + Mesh makeCube() { - std::vector vertices; + std::vector vertices; std::vector indices; addFace(vertices, indices, {0, 0, 1}, {1, 0, 0}, {0, 1, 0}); // 前 +Z / front addFace(vertices, indices, {0, 0, -1}, {-1, 0, 0}, {0, 1, 0}); // 後 -Z / back @@ -27,24 +47,27 @@ Mesh makeCube() { addFace(vertices, indices, {-1, 0, 0}, {0, 0, 1}, {0, 1, 0}); // 左 -X / left addFace(vertices, indices, {0, 1, 0}, {1, 0, 0}, {0, 0, -1}); // 上 +Y / top addFace(vertices, indices, {0, -1, 0}, {1, 0, 0}, {0, 0, 1}); // 下 -Y / bottom - return Mesh(vertices, indices, kVertex3DLayout); + computeTangents(vertices, indices, UvConvention::OpenGl); + return Mesh(vertices, indices, kModelVertexLayout); } Mesh makePlane(float size, float uvRepeat) { float h = 0.5f * size; Vec3 n = {0.0f, 1.0f, 0.0f}; // 上から見て反時計回り / counter-clockwise seen from above - std::vector vertices = { - {{-h, 0.0f, h}, n, {0.0f, 0.0f}}, - {{h, 0.0f, h}, n, {uvRepeat, 0.0f}}, - {{h, 0.0f, -h}, n, {uvRepeat, uvRepeat}}, - {{-h, 0.0f, -h}, n, {0.0f, uvRepeat}}, + std::vector vertices = { + {{-h, 0.0f, h}, n, {0.0f, 0.0f}, {}}, + {{h, 0.0f, h}, n, {uvRepeat, 0.0f}, {}}, + {{h, 0.0f, -h}, n, {uvRepeat, uvRepeat}, {}}, + {{-h, 0.0f, -h}, n, {0.0f, uvRepeat}, {}}, }; - return Mesh(vertices, {0, 1, 2, 2, 3, 0}, kVertex3DLayout); + std::vector indices = {0, 1, 2, 2, 3, 0}; + computeTangents(vertices, indices, UvConvention::OpenGl); + return Mesh(vertices, indices, kModelVertexLayout); } Mesh makeSphere(int segments, int rings) { - std::vector vertices; + std::vector vertices; std::vector indices; for (int r = 0; r <= rings; ++r) { float phi = PI * static_cast(r) / static_cast(rings); // 0 = 北極、π = 南極 / 0 = north pole, π = south pole @@ -53,7 +76,7 @@ Mesh makeSphere(int segments, int rings) { float theta = 2.0f * PI * static_cast(s) / static_cast(segments); Vec3 n = {std::sin(phi) * std::sin(theta), std::cos(phi), std::sin(phi) * std::cos(theta)}; Vec2 uv = {static_cast(s) / static_cast(segments), 1.0f - static_cast(r) / static_cast(rings)}; - vertices.push_back({0.5f * n, n, uv}); + vertices.push_back({0.5f * n, n, uv, {}}); } } // 隣り合う二つの輪の間を四角形(三角形2つ)で埋める。極の潰れた三角形は省く。 @@ -67,22 +90,24 @@ Mesh makeSphere(int segments, int rings) { if (r != 0) indices.insert(indices.end(), {a, b + 1, a + 1}); } } - return Mesh(vertices, indices, kVertex3DLayout); + computeTangents(vertices, indices, UvConvention::OpenGl); + return Mesh(vertices, indices, kModelVertexLayout); } Mesh makeCrossedQuads(int count) { - std::vector vertices; + std::vector vertices; std::vector indices; Vec3 up = {0.0f, 1.0f, 0.0f}; for (int i = 0; i < count; ++i) { float a = PI * static_cast(i) / static_cast(count); // 0〜180度(板は両面なので) / 0..180° (quads are two-sided) Vec3 r = {0.5f * std::cos(a), 0.0f, -0.5f * std::sin(a)}; // 板の右半分 / half the quad, to the right std::uint32_t first = static_cast(vertices.size()); - vertices.push_back({-1.0f * r, up, {0.0f, 0.0f}}); - vertices.push_back({r, up, {1.0f, 0.0f}}); - vertices.push_back({r + up, up, {1.0f, 1.0f}}); - vertices.push_back({up - r, up, {0.0f, 1.0f}}); + vertices.push_back({-1.0f * r, up, {0.0f, 0.0f}, {}}); + vertices.push_back({r, up, {1.0f, 0.0f}, {}}); + vertices.push_back({r + up, up, {1.0f, 1.0f}, {}}); + vertices.push_back({up - r, up, {0.0f, 1.0f}, {}}); indices.insert(indices.end(), {first, first + 1, first + 2, first + 2, first + 3, first}); } - return Mesh(vertices, indices, kVertex3DLayout); + computeTangents(vertices, indices, UvConvention::OpenGl); + return Mesh(vertices, indices, kModelVertexLayout); } diff --git a/src/shapes.hh b/src/shapes.hh index 60e41d7..32653d9 100644 --- a/src/shapes.hh +++ b/src/shapes.hh @@ -1,8 +1,15 @@ -// よく使う形のメッシュを作る / builds meshes for common shapes +// よく使う形のメッシュを作る。頂点はModelVertex(位置・法線・UV・接線、第22章から)、UVはOpenGLの決まり(vが上へ) +// builds meshes for common shapes. Vertices are ModelVertex (position, normal, UV, tangent; from chapter 22), UVs +// in the OpenGL convention (v grows upwards) #pragma once #include "mesh.hh" +// 原点を中心とした大きさsizeの箱。UVはメートル単位でtileSizeごとに繰り返す(伸びない:壁、柱、段に。第22章) +// A box of the given size centred on the origin. UVs are in metres, repeating every tileSize (no stretching: for walls, +// pillars, steps; chapter 22) +Mesh makeBox(Vec3 size, float tileSize = 1.0f); + // 原点を中心とした1×1×1の立方体。面ごとに頂点4つ(UVと法線が面ごとに違うので共有できない)=24頂点、36インデックス。 // 外から見て反時計回り(第16章のカリング用)。 // A 1×1×1 cube centred on the origin. 4 vertices per face (UVs and normals differ per face, so corners diff --git a/src/tangents.cc b/src/tangents.cc new file mode 100644 index 0000000..fcbe3f7 --- /dev/null +++ b/src/tangents.cc @@ -0,0 +1,45 @@ +#include "tangents.hh" + +#include + +void computeTangents(std::vector &vertices, const std::vector &indices, + UvConvention convention) { + size_t n = vertices.size(); + std::vector tangent(n), bitangent(n); + size_t corners = indices.empty() ? n : indices.size(); + for (size_t t = 0; t + 2 < corners; t += 3) { + std::uint32_t i0 = indices.empty() ? static_cast(t) : indices[t]; + std::uint32_t i1 = indices.empty() ? static_cast(t + 1) : indices[t + 1]; + std::uint32_t i2 = indices.empty() ? static_cast(t + 2) : indices[t + 2]; + const ModelVertex &a = vertices[i0], &b = vertices[i1], &c = vertices[i2]; + Vec3 e1 = b.position - a.position, e2 = c.position - a.position; + Vec2 d1 = b.uv - a.uv, d2 = c.uv - a.uv; + // e1 = d1.x T + d1.y B、e2 = d2.x T + d2.y B を T(∂P/∂u)と B(∂P/∂v)について解く(2×2の逆行列) + // Solve e1 = d1.x T + d1.y B, e2 = d2.x T + d2.y B for T (∂P/∂u) and B (∂P/∂v) (a 2 × 2 inverse) + float det = d1.x * d2.y - d2.x * d1.y; + if (std::fabs(det) < 1e-12f) continue; // UVが潰れた三角形 / a triangle with degenerate UVs + float r = 1.0f / det; + Vec3 tu = r * (d2.y * e1 - d1.y * e2); + Vec3 bv = r * (d1.x * e2 - d2.x * e1); + // 正規化せずに足す:テクスチャを大きく引き伸ばす三角形ほど重みが大きい / summed unnormalized: triangles that + // stretch the texture more weigh more + for (std::uint32_t i : {i0, i1, i2}) { + tangent[i] = tangent[i] + tu; + bitangent[i] = bitangent[i] + bv; + } + } + for (size_t i = 0; i < n; ++i) { + Vec3 nrm = vertices[i].normal; + // グラム・シュミット:法線の成分を引いて垂直にする / Gram-Schmidt: remove the normal component + Vec3 t = tangent[i] - dot(nrm, tangent[i]) * nrm; + if (dot(t, t) < 1e-12f) { + // UVがない・潰れている:法線に垂直なら何でも良い / no usable UVs: any direction perpendicular to the normal + t = cross(std::fabs(nrm.y) < 0.99f ? Vec3{0.0f, 1.0f, 0.0f} : Vec3{1.0f, 0.0f, 0.0f}, nrm); + } + t = normalize(t); + // 画像の「上」:OpenGLの決まりでは+v、glTFでは-v / the image's "up": +v in the OpenGL convention, -v in glTF + Vec3 up = convention == UvConvention::OpenGl ? bitangent[i] : -bitangent[i]; + float w = dot(cross(nrm, t), up) < 0.0f ? -1.0f : 1.0f; // 鏡像のUVなら-1 / -1 for mirrored UVs + vertices[i].tangent = {t.x, t.y, t.z, w}; + } +} diff --git a/src/tangents.hh b/src/tangents.hh new file mode 100644 index 0000000..fdfdde0 --- /dev/null +++ b/src/tangents.hh @@ -0,0 +1,24 @@ +// 接線の計算(第22章):法線マップの「右」と「上」が、表面のどの向きかを頂点ごとに求める +// Computing tangents (chapter 22): for every vertex, which surface directions a normal map's "right" and "up" are +#pragma once + +#include "mesh.hh" + +#include +#include + +// UVの向きの決まり / which way the image's "up" runs in UV space +enum class UvConvention { + OpenGl, // vが上へ増える(stb_imageで反転して読んだ画像、shapes.cc) / v grows upwards (images loaded flipped, shapes.cc) + Gltf, // vが下へ増える(glTF:画像を反転しない) / v grows downwards (glTF: images are not flipped) +}; + +// 三角形の位置とUVの変化から接線(uが増える向き)を求め、頂点ごとに足して、法線に垂直にして正規化する +// (グラム・シュミット)。wは従法線の向き:cross(normal, tangent.xyz) * w が画像の「上」を向くように±1。 +// indicesが空なら頂点を3つずつ三角形として使う。三角形(GL_TRIANGLES)だけ。 +// Computes tangents (the direction in which u grows) from each triangle's position and UV differences, sums them +// per vertex, then makes them perpendicular to the normal and normalizes them (Gram-Schmidt). w is the bitangent's +// sign: ±1 so that cross(normal, tangent.xyz) * w points to the image's "up". With empty indices, every three +// vertices form a triangle. Triangles (GL_TRIANGLES) only. +void computeTangents(std::vector &vertices, const std::vector &indices, + UvConvention uv);