diff --git a/CMakeLists.txt b/CMakeLists.txt index 7a7f90f..a7e9b1e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -35,7 +35,8 @@ add_executable(game src/shader.cc src/texture.cc src/shapes.cc - src/camera.cc) + src/camera.cc + src/material.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 472c901..520234a 100644 --- a/assets/LICENSE.txt +++ b/assets/LICENSE.txt @@ -3,5 +3,7 @@ assets/ のファイルはこのチュートリアルのために作者が自作 The files in assets/ were made for this tutorial by the author (generated with the author's own Python scripts, which are not part of this project). Free to use for any purpose. -textures/crate.png 木箱 / wooden crate -textures/floor.png 石の床 / stone floor tiles +textures/crate.png 木箱 / wooden crate +textures/floor.png 石の床 / stone floor tiles +textures/crate_specular.png 木箱の鏡面反射マップ / crate specular map +textures/crate_emission.png 木箱の発光マップ / crate emission map diff --git a/assets/textures/crate_emission.png b/assets/textures/crate_emission.png new file mode 100644 index 0000000..4f9772b Binary files /dev/null and b/assets/textures/crate_emission.png differ diff --git a/assets/textures/crate_specular.png b/assets/textures/crate_specular.png new file mode 100644 index 0000000..7aa9a15 Binary files /dev/null and b/assets/textures/crate_specular.png differ diff --git a/shaders/phong.frag b/shaders/phong.frag index 0ac0d6d..ad0d460 100644 --- a/shaders/phong.frag +++ b/shaders/phong.frag @@ -3,50 +3,58 @@ in vec3 vWorldPos; in vec3 vNormal; in vec2 vUv; -layout(binding = 0) uniform sampler2D uTexture0; // 物体の色 / the object's colour - -uniform vec3 uObjectColor; // テクスチャに掛ける色 / colour multiplied with the texture -uniform float uSpecularStrength; // 鏡面反射の強さ / specular strength -uniform float uShininess; // 光沢度(大きいほど小さく鋭いハイライト) / shininess (bigger = smaller, sharper highlight) +// 表面の性質。色はそれぞれのマップと掛け合わされる / surface properties; each colour is multiplied with its map +struct Material { + vec3 diffuse; // 拡散反射の色 / diffuse colour + vec3 specular; // 鏡面反射の色と強さ / specular colour and strength + vec3 emission; // 発光の色 / emission colour + float shininess; // 光沢度 / shininess +}; +uniform Material uMaterial; + +// サンプラーは構造体に入れずにbindingを指定する(構造体のメンバーにはlayoutを付けられない) +// The samplers stay outside the struct so they can have a binding (struct members cannot have a layout) +layout(binding = 0) uniform sampler2D uDiffuseMap; +layout(binding = 1) uniform sampler2D uSpecularMap; +layout(binding = 2) uniform sampler2D uEmissionMap; uniform vec3 uLightPos; // 光の位置(ワールド座標) / light position (world space) uniform vec3 uLightColor; // 光の色と明るさ / light colour and brightness uniform vec3 uAmbient; // 環境光の色と明るさ / ambient light colour and brightness uniform vec3 uViewPos; // カメラの位置(ワールド座標) / camera position (world space) -// 0 = 全部、1 = 環境光だけ、2 = 拡散反射だけ、3 = 鏡面反射だけ、4 = 法線を色で -// 0 = everything, 1 = ambient only, 2 = diffuse only, 3 = specular only, 4 = normals as colours +// 0 = 全部、1 = 環境光、2 = 拡散反射、3 = 鏡面反射、4 = 発光、5 = 法線 +// 0 = everything, 1 = ambient, 2 = diffuse, 3 = specular, 4 = emission, 5 = normals uniform int uViewMode; layout(location = 0) out vec4 out_color; void main() { - vec3 albedo = uObjectColor * texture(uTexture0, vUv).rgb; + // マップから、このピクセルのマテリアルを読む / read this pixel's material from the maps + vec3 diffuseColor = uMaterial.diffuse * texture(uDiffuseMap, vUv).rgb; + vec3 specularColor = uMaterial.specular * texture(uSpecularMap, vUv).rgb; + vec3 emission = uMaterial.emission * texture(uEmissionMap, vUv).rgb; - // 補間された法線は短くなるので正規化し直す / interpolated normals get shorter: normalize again vec3 n = normalize(vNormal); - vec3 l = normalize(uLightPos - vWorldPos); // 面から光へ / from the surface towards the light - vec3 v = normalize(uViewPos - vWorldPos); // 面から目へ / from the surface towards the eye - - // 環境光:どこからともなく来る弱い光 / ambient: weak light coming from everywhere - vec3 ambient = uAmbient * albedo; + vec3 l = normalize(uLightPos - vWorldPos); + vec3 v = normalize(uViewPos - vWorldPos); - // 拡散反射(ランバート):光に向いているほど明るい / diffuse (Lambert): brighter the more it faces the light + vec3 ambient = uAmbient * diffuseColor; float diff = max(dot(n, l), 0.0); - vec3 diffuse = diff * albedo * uLightColor; - - // 鏡面反射(Blinn-Phong):ハーフベクトルが法線に近いほど明るい / specular (Blinn-Phong): bright where the half vector is close to n + vec3 diffuse = diff * diffuseColor * uLightColor; float spec = 0.0; - if (diff > 0.0) { // 裏から照らされた面にハイライトは出ない / no highlight on surfaces lit from behind + if (diff > 0.0) { vec3 h = normalize(l + v); - spec = pow(max(dot(n, h), 0.0), uShininess); + spec = pow(max(dot(n, h), 0.0), uMaterial.shininess); } - vec3 specular = uSpecularStrength * spec * uLightColor; + vec3 specular = spec * specularColor * uLightColor; - vec3 color = ambient + diffuse + specular; + // 発光はライティングと関係なく足すだけ / emission does not depend on the lighting: just add it + vec3 color = ambient + diffuse + specular + emission; if (uViewMode == 1) color = ambient; else if (uViewMode == 2) color = diffuse; else if (uViewMode == 3) color = specular; - else if (uViewMode == 4) color = n * 0.5 + 0.5; // -1〜1を0〜1に / map -1..1 to 0..1 + else if (uViewMode == 4) color = emission; + else if (uViewMode == 5) color = n * 0.5 + 0.5; out_color = vec4(color, 1.0); } diff --git a/src/main.cc b/src/main.cc index 82ba258..22c92bf 100644 --- a/src/main.cc +++ b/src/main.cc @@ -1,5 +1,5 @@ -// 第10章:色とフォンライティング -// Chapter 10: colors and Phong lighting +// 第11章:マテリアルとライティングマップ +// Chapter 11: materials and lighting maps // // 操作 / Controls: // WASD 前後左右に移動 / move forward, back, left, right @@ -8,14 +8,16 @@ // マウス / mouse 向きを変える(FPS)、左ドラッグで回る(オービット) / look around (FPS), drag with the left button to orbit // ホイール / wheel ズーム / zoom // C FPS ⇔ オービットカメラ / FPS ⇔ orbit camera -// V 表示:全部 → 環境光 → 拡散 → 鏡面 → 法線 / view: all → ambient → diffuse → specular → normals -// L 光の色を切り替える / cycle the light colour +// V 表示:全部 → 環境光 → 拡散 → 鏡面 → 発光 → 法線 / view: all → ambient → diffuse → specular → emission → normals // P 光を止める・動かす / pause / resume the light -// N 法線行列のオン・オフ(オフ=間違った法線) / normal matrix on / off (off = wrong normals) +// L 光を消す・点ける(発光だけが残る) / light off / on (only the emission remains) +// M 箱の鏡面反射マップのオン・オフ / crate specular map on / off +// E 箱の発光のオン・オフ / crate emission on / off // Tab カーソルのキャプチャ切り替え / toggle cursor capture // R シェーダーを読み直す / reload the shaders // Esc 終了 / quit #include "camera.hh" +#include "material.hh" #include "mathx.hh" #include "mesh.hh" #include "shader.hh" @@ -25,6 +27,7 @@ #include #include +#include #include // 床に置いた箱:位置(底の中心)、大きさ、Y軸周りの回転 / crates on the floor: position (bottom centre), size, yaw @@ -43,29 +46,52 @@ static const CrateInfo kCrates[] = { {{9.0f, 0.0f, -12.0f}, 2.5f, 0.7f}, {{-2.5f, 0.0f, 5.5f}, 0.6f, 0.5f}, }; -// Lキーで切り替える光の色 / light colours cycled with the L key -static const Vec3 kLightColors[] = { - {1.0f, 1.0f, 1.0f}, // 白 / white - {1.0f, 0.72f, 0.42f}, // 電球の色 / warm bulb - {0.35f, 1.0f, 0.45f}, // 緑 / green - {0.45f, 0.55f, 1.0f}, // 青 / blue +// 色だけのマテリアル(古典的なOpenGLのマテリアル表から。表のambientは使わない:環境光 = uAmbient × diffuse) +// Colour-only materials (from the classic OpenGL material table; its ambient column is not used: +// our ambient light is uAmbient × diffuse) +struct NamedMaterial { + const char *name; + Material material; }; -static const char *const kViewModeNames[] = {"all", "ambient", "diffuse", "specular", "normals"}; +static const NamedMaterial kMaterialSamples[] = { + {"gold", {.diffuse = {0.75164f, 0.60648f, 0.22648f}, + .specular = {0.628281f, 0.555802f, 0.366065f}, + .shininess = 51.2f}}, + {"silver", {.diffuse = {0.50754f, 0.50754f, 0.50754f}, + .specular = {0.508273f, 0.508273f, 0.508273f}, + .shininess = 51.2f}}, + {"copper", {.diffuse = {0.7038f, 0.27048f, 0.0828f}, + .specular = {0.256777f, 0.137622f, 0.086014f}, + .shininess = 12.8f}}, + {"jade", {.diffuse = {0.54f, 0.89f, 0.63f}, + .specular = {0.316228f, 0.316228f, 0.316228f}, + .shininess = 12.8f}}, + {"ruby", {.diffuse = {0.61424f, 0.04136f, 0.04136f}, + .specular = {0.727811f, 0.626959f, 0.626959f}, + .shininess = 76.8f}}, + {"cyan plastic", {.diffuse = {0.0f, 0.50980392f, 0.50980392f}, + .specular = {0.50196078f, 0.50196078f, 0.50196078f}, + .shininess = 32.0f}}, +}; + +static const char *const kViewModeNames[] = {"all", "ambient", "diffuse", "specular", "emission", "normals"}; int main() { Window window; - if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 10")) return 1; + if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 11")) return 1; std::optional phong = Shader::load("shaders/phong.vert", "shaders/phong.frag"); std::optional unlit = Shader::load("shaders/unlit.vert", "shaders/unlit.frag"); std::optional crate = Texture2D::load("assets/textures/crate.png"); + std::optional crateSpecular = Texture2D::load("assets/textures/crate_specular.png"); + std::optional crateEmission = Texture2D::load("assets/textures/crate_emission.png"); std::optional floorTexture = Texture2D::load("assets/textures/floor.png"); - if (!phong || !unlit || !crate || !floorTexture) return 1; + if (!phong || !unlit || !crate || !crateSpecular || !crateEmission || !floorTexture) return 1; glEnable(GL_DEPTH_TEST); - // 1×1の白いテクスチャ:テクスチャのない物はuObjectColorだけで色が決まる - // A 1×1 white texture: objects without a texture get their colour from uObjectColor alone + // 1×1の白いテクスチャ:マップのないマテリアルの代わり(白を掛けても色は変わらない) + // A 1×1 white texture: stands in for missing maps (multiplying by white changes nothing) const unsigned char whitePixel[4] = {255, 255, 255, 255}; Texture2D white = Texture2D::fromPixels(whitePixel, 1, 1, {.flipY = false, .mipmaps = false}); @@ -80,9 +106,10 @@ int main() { bool useOrbit = false; int viewMode = 0; - int lightColorIndex = 0; bool lightMoving = true; - bool useNormalMatrix = true; + bool lightOn = true; + bool useSpecularMap = true; + bool useEmission = true; float lightTime = 0.0f; // 光の動きの時間(止められる) / time for the light's motion (can be paused) window.setCursorCaptured(true); @@ -101,21 +128,40 @@ int main() { printf("camera: %s\n", useOrbit ? "orbit" : "fps"); } if (key == GLFW_KEY_V) { - viewMode = (viewMode + 1) % 5; + viewMode = (viewMode + 1) % 6; printf("view: %s\n", kViewModeNames[viewMode]); } - if (key == GLFW_KEY_L) lightColorIndex = (lightColorIndex + 1) % 4; if (key == GLFW_KEY_P) lightMoving = !lightMoving; - if (key == GLFW_KEY_N) { - useNormalMatrix = !useNormalMatrix; - printf("normal matrix: %s\n", useNormalMatrix ? "on" : "off (mat3(uModel))"); + if (key == GLFW_KEY_L) lightOn = !lightOn; + if (key == GLFW_KEY_M) { + useSpecularMap = !useSpecularMap; + printf("specular map: %s\n", useSpecularMap ? "on" : "off"); } + if (key == GLFW_KEY_E) useEmission = !useEmission; }; + printf("material spheres (left to right):"); + for (const NamedMaterial &m : kMaterialSamples) printf(" %s", m.name); + printf("\n"); + Mesh cube = makeCube(); Mesh sphere = makeSphere(); Mesh floorMesh = makePlane(40.0f, 10.0f); + // 床:石は少しだけ光る / the floor: stone is only slightly shiny + Material floorMaterial; + floorMaterial.diffuseMap = &*floorTexture; + floorMaterial.specular = {0.15f, 0.15f, 0.15f}; + floorMaterial.shininess = 16.0f; + + // 箱:三枚のマップ。鏡面反射マップで金属の枠だけが光り、発光マップで隙間が光る + // The crate: three maps. The specular map makes only the metal frame shiny, the emission map lights the gaps + Material crateMaterial; + crateMaterial.diffuseMap = &*crate; + crateMaterial.specular = {1.0f, 1.0f, 1.0f}; + crateMaterial.shininess = 48.0f; + crateMaterial.emissionMap = &*crateEmission; + double lastTime = window.time(); while (!window.shouldClose()) { double now = window.time(); @@ -145,7 +191,8 @@ int main() { if (lightMoving) lightTime += dt; Vec3 lightPos = {3.5f * std::sin(0.7f * lightTime), 2.6f + 0.6f * std::sin(1.3f * lightTime), 3.5f * std::cos(0.7f * lightTime)}; - Vec3 lightColor = kLightColors[lightColorIndex]; + Vec3 lightColor = lightOn ? Vec3{1.0f, 1.0f, 1.0f} : Vec3{0.0f, 0.0f, 0.0f}; + Vec3 ambient = lightOn ? Vec3{0.15f, 0.15f, 0.15f} : Vec3{0.02f, 0.02f, 0.03f}; Mat4 view = useOrbit ? orbit.view() : fps.view(); Mat4 proj = useOrbit ? orbit.projection(window.aspect()) : fps.projection(window.aspect()); @@ -154,14 +201,11 @@ int main() { glClearColor(0.10f, 0.15f, 0.25f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - // 一つの物を描く:モデル行列と法線行列、物体の色、光沢 / draws one object: model and normal matrix, colour, shininess - auto drawLit = [&](const Mesh &mesh, const Mat4 &model, Vec3 color, float specular, float shininess) { + // 一つの物を描く:モデル行列、法線行列、マテリアル / draws one object: model matrix, normal matrix, material + auto drawLit = [&](const Mesh &mesh, const Mat4 &model, const Material &material) { phong->set("uModel", model); - // 法線行列なしだと一様でない拡大縮小で法線が傾く / without the normal matrix, non-uniform scaling tilts the normals - phong->set("uNormalMatrix", useNormalMatrix ? normalMatrix(model) : toMat3(model)); - phong->set("uObjectColor", color); - phong->set("uSpecularStrength", specular); - phong->set("uShininess", shininess); + phong->set("uNormalMatrix", normalMatrix(model)); + material.apply(*phong, white); mesh.draw(); }; @@ -171,34 +215,32 @@ int main() { phong->set("uViewPos", viewPos); phong->set("uLightPos", lightPos); phong->set("uLightColor", lightColor); - phong->set("uAmbient", Vec3{0.15f, 0.15f, 0.15f}); + phong->set("uAmbient", ambient); phong->set("uViewMode", viewMode); - // 床:石は少しだけ光る / the floor: stone is only slightly shiny - floorTexture->bind(0); - drawLit(floorMesh, Mat4::identity(), {1.0f, 1.0f, 1.0f}, 0.15f, 16.0f); + drawLit(floorMesh, Mat4::identity(), floorMaterial); - // 箱 / crates - crate->bind(0); + // 箱:マップのオン・オフはマテリアルのコピーで切り替える / crates: the maps are switched on a copy of the material + Material crateNow = crateMaterial; + crateNow.specularMap = useSpecularMap ? &*crateSpecular : nullptr; // nullptr = 白 = 全体が鋼のように光る / white = shiny all over + crateNow.emission = useEmission ? Vec3{1.0f, 1.0f, 1.0f} : Vec3{0.0f, 0.0f, 0.0f}; for (const CrateInfo &c : kCrates) { Vec3 centre = c.position + Vec3{0.0f, 0.5f * c.size, 0.0f}; - drawLit(cube, translate(centre) * rotateY(c.angle) * scale({c.size, c.size, c.size}), {1.0f, 1.0f, 1.0f}, 0.3f, - 32.0f); + drawLit(cube, translate(centre) * rotateY(c.angle) * scale({c.size, c.size, c.size}), crateNow); } - // テクスチャなしの球二つ:色はuObjectColorだけ。二つ目は一様でない拡大縮小(楕円体) - // Two untextured spheres: the colour is uObjectColor alone. The second one is scaled non-uniformly (an ellipsoid) - white.bind(0); - drawLit(sphere, translate({2.6f, 0.7f, 2.2f}) * scale({1.4f, 1.4f, 1.4f}), {1.0f, 0.35f, 0.25f}, 0.6f, 64.0f); - drawLit(sphere, translate({-1.8f, 0.45f, 2.4f}) * rotateY(radians(35.0f)) * scale({2.2f, 0.9f, 1.1f}), - {0.3f, 0.5f, 1.0f}, 0.6f, 64.0f); + // マテリアル見本の球を一列に / a row of sample spheres, one per material + for (size_t i = 0; i < std::size(kMaterialSamples); ++i) { + float x = (static_cast(i) - 2.5f) * 1.25f; + drawLit(sphere, translate({x, 0.5f, 2.6f}), kMaterialSamples[i].material); + } // 光源の目印:光の色そのまま、ライティングなし / the light's marker: the light colour itself, unlit unlit->use(); unlit->set("uView", view); unlit->set("uProj", proj); unlit->set("uModel", translate(lightPos) * scale({0.2f, 0.2f, 0.2f})); - unlit->set("uColor", lightColor); + unlit->set("uColor", lightOn ? lightColor : Vec3{0.2f, 0.2f, 0.2f}); cube.draw(); window.swapBuffers(); diff --git a/src/material.cc b/src/material.cc new file mode 100644 index 0000000..3edff0c --- /dev/null +++ b/src/material.cc @@ -0,0 +1,13 @@ +#include "material.hh" + +void Material::apply(const Shader &shader, const Texture2D &white) const { + // 構造体のユニフォームは「変数名.メンバー名」で一つずつ設定する + // uniforms in a struct are set one by one as "variable.member" + shader.set("uMaterial.diffuse", diffuse); + shader.set("uMaterial.specular", specular); + shader.set("uMaterial.emission", emission); + shader.set("uMaterial.shininess", shininess); + (diffuseMap ? diffuseMap : &white)->bind(0); + (specularMap ? specularMap : &white)->bind(1); + (emissionMap ? emissionMap : &white)->bind(2); +} diff --git a/src/material.hh b/src/material.hh new file mode 100644 index 0000000..b2b211d --- /dev/null +++ b/src/material.hh @@ -0,0 +1,23 @@ +// マテリアル:物体の表面の性質 / material: the properties of an object's surface +#pragma once + +#include "mathx.hh" +#include "shader.hh" +#include "texture.hh" + +// Blinn-Phongのマテリアル。色とマップ(テクスチャ)は掛け合わされる。マップがなければ白(=色だけ)。 +// A Blinn-Phong material. Each colour is multiplied with its map (texture); no map means white (= the colour alone). +struct Material { + Vec3 diffuse = {1.0f, 1.0f, 1.0f}; // 拡散反射の色(物体の色) / diffuse colour (the object's colour) + Vec3 specular = {0.5f, 0.5f, 0.5f}; // 鏡面反射の色と強さ / specular colour and strength + Vec3 emission = {0.0f, 0.0f, 0.0f}; // 発光の色:光が当たらなくても見える / emission colour: visible even without light + float shininess = 32.0f; // 光沢度 / shininess + + const Texture2D *diffuseMap = nullptr; // テクスチャユニット0 / texture unit 0 + const Texture2D *specularMap = nullptr; // テクスチャユニット1 / texture unit 1 + const Texture2D *emissionMap = nullptr; // テクスチャユニット2 / texture unit 2 + + // シェーダーの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. + void apply(const Shader &shader, const Texture2D &white) const; +};