diff --git a/CMakeLists.txt b/CMakeLists.txt index a7e9b1e..6e13560 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -36,7 +36,8 @@ add_executable(game src/texture.cc src/shapes.cc src/camera.cc - src/material.cc) + src/material.cc + src/lights.cc) target_include_directories(game PRIVATE src external/stb external/linalg) target_link_libraries(game PRIVATE glad stb_image glfw) diff --git a/shaders/phong.frag b/shaders/phong.frag index ad0d460..b44d791 100644 --- a/shaders/phong.frag +++ b/shaders/phong.frag @@ -12,16 +12,45 @@ struct Material { }; 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) +// 平行光源:向きだけ / directional light: a direction only +struct DirectionalLight { + vec3 direction; // 光が進む向き(単位ベクトル) / the direction the light travels (unit vector) + vec3 color; // 0 = オフ / 0 = off +}; + +// 点光源:位置と減衰 / point light: a position and attenuation +struct PointLight { + vec3 position; + vec3 color; + vec3 attenuation; // 定数項・一次・二次 / constant, linear, quadratic +}; + +// スポットライト:点光源+円錐 / spotlight: a point light + a cone +struct SpotLight { + vec3 position; + vec3 direction; // 円錐の軸(単位ベクトル) / the cone's axis (unit vector) + vec3 color; + float cosInner; // 内側の円錐の半角のコサイン / cosine of the inner cone's half angle + float cosOuter; // 外側の円錐の半角のコサイン / cosine of the outer cone's half angle + vec3 attenuation; +}; + +// C++側の kMaxPointLights、kMaxSpotLights と同じ / same as kMaxPointLights and kMaxSpotLights in C++ +#define MAX_POINT_LIGHTS 8 +#define MAX_SPOT_LIGHTS 4 + +uniform DirectionalLight uDirLight; +uniform PointLight uPointLights[MAX_POINT_LIGHTS]; +uniform int uPointLightCount; // 使っている数 / how many are in use +uniform SpotLight uSpotLights[MAX_SPOT_LIGHTS]; +uniform int uSpotLightCount; + +uniform vec3 uAmbient; // 環境光の色と明るさ / ambient light colour and brightness +uniform vec3 uViewPos; // カメラの位置(ワールド座標) / camera position (world space) // 0 = 全部、1 = 環境光、2 = 拡散反射、3 = 鏡面反射、4 = 発光、5 = 法線 // 0 = everything, 1 = ambient, 2 = diffuse, 3 = specular, 4 = emission, 5 = normals @@ -29,32 +58,72 @@ uniform int uViewMode; layout(location = 0) out vec4 out_color; +// このピクセルの表面:どの光の計算にも同じものを使う / this pixel's surface: the same for every light +struct Surface { + vec3 position; // ワールド座標 / world space + vec3 normal; // 単位ベクトル / unit vector + vec3 view; // 目へ向かう単位ベクトル / unit vector towards the eye + vec3 diffuse; // マップを掛けた拡散反射の色 / diffuse colour with the map applied + vec3 specular; // マップを掛けた鏡面反射の色 / specular colour with the map applied + float shininess; +}; + +// 一つの光の拡散反射と鏡面反射(Blinn-Phong)を足す。l = 光へ向かう単位ベクトル +// Adds one light's diffuse and specular (Blinn-Phong) light. l = unit vector towards the light +void addLight(Surface s, vec3 l, vec3 lightColor, inout vec3 diffuse, inout vec3 specular) { + float diff = max(dot(s.normal, l), 0.0); + if (diff <= 0.0) return; // 裏から照らされている / lit from behind + vec3 h = normalize(l + s.view); + diffuse += diff * s.diffuse * lightColor; + specular += pow(max(dot(s.normal, h), 0.0), s.shininess) * s.specular * lightColor; +} + +// 距離dでの減衰(k = 定数項・一次・二次) / attenuation at distance d (k = constant, linear, quadratic) +float attenuate(float d, vec3 k) { + return 1.0 / (k.x + k.y * d + k.z * d * d); +} + void main() { - // マップから、このピクセルのマテリアルを読む / read this pixel's material from the maps - vec3 diffuseColor = uMaterial.diffuse * texture(uDiffuseMap, vUv).rgb; - vec3 specularColor = uMaterial.specular * texture(uSpecularMap, vUv).rgb; + Surface s; + s.position = vWorldPos; + s.normal = normalize(vNormal); + s.view = normalize(uViewPos - vWorldPos); + s.diffuse = uMaterial.diffuse * texture(uDiffuseMap, vUv).rgb; + s.specular = uMaterial.specular * texture(uSpecularMap, vUv).rgb; + s.shininess = uMaterial.shininess; vec3 emission = uMaterial.emission * texture(uEmissionMap, vUv).rgb; - vec3 n = normalize(vNormal); - vec3 l = normalize(uLightPos - vWorldPos); - vec3 v = normalize(uViewPos - vWorldPos); - - vec3 ambient = uAmbient * diffuseColor; - float diff = max(dot(n, l), 0.0); - vec3 diffuse = diff * diffuseColor * uLightColor; - float spec = 0.0; - if (diff > 0.0) { - vec3 h = normalize(l + v); - spec = pow(max(dot(n, h), 0.0), uMaterial.shininess); + vec3 diffuse = vec3(0.0); + vec3 specular = vec3(0.0); + + // 平行光源:光へ向かう向きは進む向きの逆 / directional: towards the light = the opposite of its direction + addLight(s, -uDirLight.direction, uDirLight.color, diffuse, specular); + + // 点光源 / point lights + for (int i = 0; i < uPointLightCount; ++i) { + vec3 toLight = uPointLights[i].position - s.position; + float d = length(toLight); + addLight(s, toLight / d, uPointLights[i].color * attenuate(d, uPointLights[i].attenuation), diffuse, specular); + } + + // スポットライト:点光源に円錐の係数を掛ける / spotlights: a point light times a cone factor + for (int i = 0; i < uSpotLightCount; ++i) { + vec3 toLight = uSpotLights[i].position - s.position; + float d = length(toLight); + vec3 l = toLight / d; + // 光から見たこのピクセルの向きと円錐の軸の角度(のコサイン) / cosine of the angle between the cone axis and this pixel + float cosAngle = dot(-l, uSpotLights[i].direction); + float cone = smoothstep(uSpotLights[i].cosOuter, uSpotLights[i].cosInner, cosAngle); + if (cone <= 0.0) continue; + addLight(s, l, uSpotLights[i].color * attenuate(d, uSpotLights[i].attenuation) * cone, diffuse, specular); } - vec3 specular = spec * specularColor * uLightColor; - // 発光はライティングと関係なく足すだけ / emission does not depend on the lighting: just add it + vec3 ambient = uAmbient * s.diffuse; 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 = emission; - else if (uViewMode == 5) color = n * 0.5 + 0.5; + else if (uViewMode == 5) color = s.normal * 0.5 + 0.5; out_color = vec4(color, 1.0); } diff --git a/src/lights.cc b/src/lights.cc new file mode 100644 index 0000000..697b279 --- /dev/null +++ b/src/lights.cc @@ -0,0 +1,43 @@ +#include "lights.hh" + +#include +#include +#include + +void LightSet::apply(const Shader &shader) const { + shader.set("uAmbient", ambient); + shader.set("uDirLight.direction", normalize(directional.direction)); + shader.set("uDirLight.color", directional.color); + + // 配列の要素のメンバーは「名前[番号].メンバー」で設定する / array elements: "name[index].member" + int pointCount = static_cast(points.size()); + if (pointCount > kMaxPointLights) { + fprintf(stderr, "点光源が多すぎる / too many point lights: %d (max %d)\n", pointCount, kMaxPointLights); + pointCount = kMaxPointLights; + } + for (int i = 0; i < pointCount; ++i) { + const PointLight &p = points[static_cast(i)]; + shader.set(std::format("uPointLights[{}].position", i).c_str(), p.position); + shader.set(std::format("uPointLights[{}].color", i).c_str(), p.color); + shader.set(std::format("uPointLights[{}].attenuation", i).c_str(), p.attenuation); + } + shader.set("uPointLightCount", pointCount); + + int spotCount = static_cast(spots.size()); + if (spotCount > kMaxSpotLights) { + fprintf(stderr, "スポットライトが多すぎる / too many spotlights: %d (max %d)\n", spotCount, kMaxSpotLights); + spotCount = kMaxSpotLights; + } + for (int i = 0; i < spotCount; ++i) { + const SpotLight &s = spots[static_cast(i)]; + shader.set(std::format("uSpotLights[{}].position", i).c_str(), s.position); + shader.set(std::format("uSpotLights[{}].direction", i).c_str(), normalize(s.direction)); + shader.set(std::format("uSpotLights[{}].color", i).c_str(), s.color); + // シェーダーは角度ではなくコサインを比べる(acosを毎ピクセル計算しないため) + // The shader compares cosines, not angles (so it does not need acos for every pixel) + shader.set(std::format("uSpotLights[{}].cosInner", i).c_str(), std::cos(s.innerAngle)); + shader.set(std::format("uSpotLights[{}].cosOuter", i).c_str(), std::cos(s.outerAngle)); + shader.set(std::format("uSpotLights[{}].attenuation", i).c_str(), s.attenuation); + } + shader.set("uSpotLightCount", spotCount); +} diff --git a/src/lights.hh b/src/lights.hh new file mode 100644 index 0000000..c19da01 --- /dev/null +++ b/src/lights.hh @@ -0,0 +1,55 @@ +// 光源:平行光源・点光源・スポットライト / light casters: directional, point and spot lights +#pragma once + +#include "mathx.hh" +#include "shader.hh" + +#include + +// 減衰の定数(定数項・一次・二次)。GLSLシリーズ第9章の表から +// Attenuation constants (constant, linear, quadratic), from the table in GLSL series chapter 9 +constexpr Vec3 kShortRange = {1.0f, 0.7f, 1.8f}; // 近くだけ照らす / lights only what is close +constexpr Vec3 kMediumRange = {1.0f, 0.35f, 0.44f}; // 中くらい / medium +constexpr Vec3 kLongRange = {1.0f, 0.09f, 0.032f}; // 遠くまで届く / reaches far + +// シェーダーの MAX_POINT_LIGHTS、MAX_SPOT_LIGHTS と同じにすること +// Must match MAX_POINT_LIGHTS and MAX_SPOT_LIGHTS in the shader +constexpr int kMaxPointLights = 8; +constexpr int kMaxSpotLights = 4; + +// 平行光源(太陽・月):位置がなく、どこでも同じ向きから来る +// Directional light (sun, moon): no position, comes from the same direction everywhere +struct DirectionalLight { + Vec3 direction = {0.0f, -1.0f, 0.0f}; // 光が進む向き(光源へ向かう向きの逆) / the direction the light travels + Vec3 color = {0.0f, 0.0f, 0.0f}; // 色と明るさ。0 = オフ / colour and brightness; 0 = off +}; + +// 点光源(電球):一点から全方向へ、距離で弱くなる / point light (a bulb): all directions from one point, weaker with distance +struct PointLight { + Vec3 position; + Vec3 color = {1.0f, 1.0f, 1.0f}; + Vec3 attenuation = kMediumRange; +}; + +// スポットライト(懐中電灯):円錐の中だけ。内側の円錐から外側の円錐まで滑らかに暗くなる +// Spotlight (a flashlight): only inside a cone; fades smoothly from the inner to the outer cone +struct SpotLight { + Vec3 position; + Vec3 direction = {0.0f, -1.0f, 0.0f}; + Vec3 color = {1.0f, 1.0f, 1.0f}; + float innerAngle = radians(12.5f); // ここまで全部の明るさ(円錐の半分の角度) / full brightness up to here (half angle) + float outerAngle = radians(17.5f); // ここから先は0 / zero from here on + Vec3 attenuation = kLongRange; +}; + +// シーンの全部の光 / all the lights of a scene +struct LightSet { + Vec3 ambient = {0.05f, 0.05f, 0.05f}; + DirectionalLight directional; + std::vector points; + std::vector spots; + + // 全部の光をシェーダーのユニフォームに設定する。最大数を超えた分は使わない。 + // Sets all lights as shader uniforms. Lights beyond the maximum count are ignored. + void apply(const Shader &shader) const; +}; diff --git a/src/main.cc b/src/main.cc index 22c92bf..d88b925 100644 --- a/src/main.cc +++ b/src/main.cc @@ -1,5 +1,5 @@ -// 第11章:マテリアルとライティングマップ -// Chapter 11: materials and lighting maps +// 第12章:光源と複数のライト +// Chapter 12: light casters and multiple lights // // 操作 / Controls: // WASD 前後左右に移動 / move forward, back, left, right @@ -9,14 +9,16 @@ // ホイール / wheel ズーム / zoom // C FPS ⇔ オービットカメラ / FPS ⇔ orbit camera // V 表示:全部 → 環境光 → 拡散 → 鏡面 → 発光 → 法線 / view: all → ambient → diffuse → specular → emission → normals -// P 光を止める・動かす / pause / resume the light -// L 光を消す・点ける(発光だけが残る) / light off / on (only the emission remains) -// M 箱の鏡面反射マップのオン・オフ / crate specular map on / off -// E 箱の発光のオン・オフ / crate emission on / off +// P 点光源を止める・動かす / pause / resume the point lights +// 1 平行光源(月)のオン・オフ / directional light (the moon) on / off +// 2 点光源のオン・オフ / point lights on / off +// 3 スポットライトのオン・オフ / spotlights on / off +// F 懐中電灯のオン・オフ / flashlight on / off // Tab カーソルのキャプチャ切り替え / toggle cursor capture // R シェーダーを読み直す / reload the shaders // Esc 終了 / quit #include "camera.hh" +#include "lights.hh" #include "material.hh" #include "mathx.hh" #include "mesh.hh" @@ -75,11 +77,28 @@ static const NamedMaterial kMaterialSamples[] = { .shininess = 32.0f}}, }; +// 点光源(提灯)の中心と色 / centres and colours of the point lights (lanterns) +struct LanternInfo { + Vec3 centre; + Vec3 color; +}; + +static const LanternInfo kLanterns[] = { + {{2.6f, 1.2f, 0.2f}, {2.4f, 1.0f, 0.35f}}, // 橙 / orange + {{-1.8f, 1.0f, 0.8f}, {0.4f, 2.0f, 0.7f}}, // 緑 / green + {{4.5f, 1.6f, -4.5f}, {0.6f, 0.9f, 2.6f}}, // 青 / blue + {{-5.5f, 1.4f, -3.5f}, {2.2f, 0.5f, 1.8f}}, // 紫 / purple +}; + +// 箱の山を上から照らすスポットライト / the spotlight shining down on the pile of crates +constexpr Vec3 kStageSpotPos = {2.0f, 6.0f, 1.5f}; +constexpr Vec3 kStageSpotTarget = {0.3f, 0.5f, -0.2f}; + static const char *const kViewModeNames[] = {"all", "ambient", "diffuse", "specular", "emission", "normals"}; int main() { Window window; - if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 11")) return 1; + if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 12")) return 1; std::optional phong = Shader::load("shaders/phong.vert", "shaders/phong.frag"); std::optional unlit = Shader::load("shaders/unlit.vert", "shaders/unlit.frag"); @@ -107,10 +126,8 @@ int main() { bool useOrbit = false; int viewMode = 0; bool lightMoving = true; - bool lightOn = true; - bool useSpecularMap = true; - bool useEmission = true; - float lightTime = 0.0f; // 光の動きの時間(止められる) / time for the light's motion (can be paused) + bool directionalOn = true, pointsOn = true, spotsOn = true, flashlightOn = true; + float lightTime = 0.0f; // 点光源の動きの時間(止められる) / time for the point lights' motion (can be paused) window.setCursorCaptured(true); window.onKey = [&](int key, int action, int /*mods*/) { @@ -132,12 +149,13 @@ int main() { printf("view: %s\n", kViewModeNames[viewMode]); } if (key == GLFW_KEY_P) lightMoving = !lightMoving; - 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; + if (key == GLFW_KEY_1) directionalOn = !directionalOn; + if (key == GLFW_KEY_2) pointsOn = !pointsOn; + if (key == GLFW_KEY_3) spotsOn = !spotsOn; + if (key == GLFW_KEY_F) flashlightOn = !flashlightOn; + if (key >= GLFW_KEY_1 && key <= GLFW_KEY_3) + printf("directional %s, points %s, spots %s\n", directionalOn ? "on" : "off", pointsOn ? "on" : "off", + spotsOn ? "on" : "off"); }; printf("material spheres (left to right):"); @@ -160,7 +178,9 @@ int main() { crateMaterial.diffuseMap = &*crate; crateMaterial.specular = {1.0f, 1.0f, 1.0f}; crateMaterial.shininess = 48.0f; + crateMaterial.specularMap = &*crateSpecular; crateMaterial.emissionMap = &*crateEmission; + crateMaterial.emission = {1.0f, 1.0f, 1.0f}; double lastTime = window.time(); while (!window.shouldClose()) { @@ -187,18 +207,42 @@ int main() { fps.move(dir, dt); } - // 光は箱の山の周りを回り、少し上下する / the light circles the pile of crates, bobbing up and down a little - 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 = 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()); Vec3 viewPos = useOrbit ? orbit.position() : fps.position; + Vec3 viewDir = useOrbit ? normalize(orbit.target - orbit.position()) : fps.front(); - glClearColor(0.10f, 0.15f, 0.25f, 1.0f); + // 夜の場面:弱い環境光と青白い月 / a night scene: weak ambient light and a pale blue moon + if (lightMoving) lightTime += dt; + LightSet lights; + lights.ambient = {0.03f, 0.035f, 0.05f}; + if (directionalOn) lights.directional = {.direction = {-0.4f, -1.0f, -0.6f}, .color = {0.22f, 0.27f, 0.4f}}; + + // 色の違う点光源四つ。それぞれ自分の中心の周りをゆっくり回る + // Four coloured point lights, each slowly circling its own centre + if (pointsOn) { + for (int i = 0; i < 4; ++i) { + float a = lightTime * (0.5f + 0.15f * static_cast(i)) + static_cast(i) * 1.7f; + lights.points.push_back({.position = kLanterns[i].centre + Vec3{1.2f * std::cos(a), 0.3f * std::sin(2.0f * a), + 1.2f * std::sin(a)}, + .color = kLanterns[i].color, + .attenuation = kMediumRange}); + } + } + + // スポットライト:カメラの懐中電灯と、箱の山を上から照らすライト + // Spotlights: the camera's flashlight and a light shining down on the pile of crates + if (spotsOn) { + if (flashlightOn) + lights.spots.push_back({.position = viewPos, .direction = viewDir, .color = {1.0f, 0.95f, 0.85f}}); + lights.spots.push_back({.position = kStageSpotPos, + .direction = kStageSpotTarget - kStageSpotPos, + .color = {2.0f, 1.9f, 1.6f}, + .innerAngle = radians(16.0f), + .outerAngle = radians(24.0f)}); + } + + glClearColor(0.02f, 0.03f, 0.06f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // 一つの物を描く:モデル行列、法線行列、マテリアル / draws one object: model matrix, normal matrix, material @@ -213,20 +257,14 @@ int main() { phong->set("uView", view); phong->set("uProj", proj); phong->set("uViewPos", viewPos); - phong->set("uLightPos", lightPos); - phong->set("uLightColor", lightColor); - phong->set("uAmbient", ambient); phong->set("uViewMode", viewMode); + lights.apply(*phong); drawLit(floorMesh, Mat4::identity(), floorMaterial); - // 箱:マップのオン・オフはマテリアルのコピーで切り替える / 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}), crateNow); + drawLit(cube, translate(centre) * rotateY(c.angle) * scale({c.size, c.size, c.size}), crateMaterial); } // マテリアル見本の球を一列に / a row of sample spheres, one per material @@ -235,13 +273,21 @@ int main() { drawLit(sphere, translate({x, 0.5f, 2.6f}), kMaterialSamples[i].material); } - // 光源の目印:光の色そのまま、ライティングなし / the light's marker: the light colour itself, unlit + // 光源の目印:点光源は小さな球、スポットライトは小さな箱(懐中電灯は自分の目の位置なので描かない) + // Light markers: small spheres for point lights, small cubes for spotlights (not the flashlight: it is at our eye) 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", lightOn ? lightColor : Vec3{0.2f, 0.2f, 0.2f}); - cube.draw(); + for (const PointLight &p : lights.points) { + unlit->set("uModel", translate(p.position) * scale({0.15f, 0.15f, 0.15f})); + unlit->set("uColor", p.color); + sphere.draw(); + } + if (spotsOn) { + unlit->set("uModel", translate(kStageSpotPos) * scale({0.2f, 0.2f, 0.2f})); + unlit->set("uColor", Vec3{1.0f, 1.0f, 0.9f}); + cube.draw(); + } window.swapBuffers(); }