diff --git a/CMakeLists.txt b/CMakeLists.txt index 749e8e9..31939fd 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -41,7 +41,8 @@ add_executable(game src/json.cc src/gltf.cc src/model.cc - src/framebuffer.cc) + src/framebuffer.cc + src/cubemap.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 0207210..cb46614 100644 --- a/assets/LICENSE.txt +++ b/assets/LICENSE.txt @@ -9,6 +9,7 @@ textures/crate_specular.png 木箱の鏡面反射マップ / crate specular map textures/crate_emission.png 木箱の発光マップ / crate emission map textures/rug.png 敷物 / a runner rug (chapter 15) textures/grass_blades.png 草の葉(アルファ付き) / grass blades with alpha (chapter 16) +textures/sky/*.png 空のキューブマップの6面 / the six sky cube-map faces (chapter 18) models/window.glb 花箱つきの窓 / a window with a flower box (chapter 16) models/crate.glb 木箱のモデル / crate model models/diorama.glb 小さな場面 / a small diorama scene diff --git a/assets/textures/sky/nx.png b/assets/textures/sky/nx.png new file mode 100644 index 0000000..63f2cc8 Binary files /dev/null and b/assets/textures/sky/nx.png differ diff --git a/assets/textures/sky/ny.png b/assets/textures/sky/ny.png new file mode 100644 index 0000000..88b26ab Binary files /dev/null and b/assets/textures/sky/ny.png differ diff --git a/assets/textures/sky/nz.png b/assets/textures/sky/nz.png new file mode 100644 index 0000000..5272bd9 Binary files /dev/null and b/assets/textures/sky/nz.png differ diff --git a/assets/textures/sky/px.png b/assets/textures/sky/px.png new file mode 100644 index 0000000..d2778b3 Binary files /dev/null and b/assets/textures/sky/px.png differ diff --git a/assets/textures/sky/py.png b/assets/textures/sky/py.png new file mode 100644 index 0000000..4b0caa7 Binary files /dev/null and b/assets/textures/sky/py.png differ diff --git a/assets/textures/sky/pz.png b/assets/textures/sky/pz.png new file mode 100644 index 0000000..66ea367 Binary files /dev/null and b/assets/textures/sky/pz.png differ diff --git a/shaders/envmap.frag b/shaders/envmap.frag new file mode 100644 index 0000000..78ebeec --- /dev/null +++ b/shaders/envmap.frag @@ -0,0 +1,38 @@ +#version 460 core +// 環境マッピング:キューブマップに映った空を反射・屈折で見せる(頂点シェーダーはphong.vert) +// Environment mapping: show the sky in a cube map by reflection or refraction (vertex shader: phong.vert) +in vec3 vWorldPos; +in vec3 vNormal; + +layout(binding = 3) uniform samplerCube uEnvironment; + +uniform vec3 uViewPos; +uniform int uEnvMode; // 0 = 反射 / reflection, 1 = 屈折 / refraction, 2 = フレネル(ガラス) / Fresnel (glass) +uniform float uIor; // 屈折率(ガラス1.52、水1.33) / index of refraction (glass 1.52, water 1.33) +uniform vec3 uTint; // 反射・屈折の色 / colour of the reflection / refraction +uniform vec3 uEnvironmentTint; // 空の明るさ(昼1、夜は暗く) / brightness of the sky (1 by day, dark at night) + +layout(location = 0) out vec4 out_color; + +void main() { + vec3 i = normalize(vWorldPos - uViewPos); // 目から表面へ / from the eye to the surface + vec3 n = normalize(vNormal); + // reflect(i, n) = i - 2 dot(n, i) n:入射と同じ角度で跳ね返る / bounces off at the same angle + vec3 reflected = texture(uEnvironment, reflect(i, n)).rgb; + // refract(i, n, η):η = 入る前 ÷ 入った後の屈折率(空気1.0 → ガラス) / η = ratio of indices (air 1.0 → glass) + vec3 refracted = texture(uEnvironment, refract(i, n, 1.0 / uIor)).rgb; + + vec3 color = reflected; + if (uEnvMode == 1) { + color = refracted; + } else if (uEnvMode == 2) { + // フレネル(Schlickの近似):正面からはほとんど透け、斜めからはほとんど映る + // Fresnel (Schlick's approximation): mostly see-through head-on, mostly mirror at grazing angles + // 負の数のpowはGLSLでは未定義なので、二乗は掛け算で / pow of a negative base is undefined in GLSL: square by multiplying + float r0 = (1.0 - uIor) / (1.0 + uIor); + float f0 = r0 * r0; // ガラスで約0.04 / about 0.04 for glass + float fresnel = f0 + (1.0 - f0) * pow(1.0 - max(dot(-i, n), 0.0), 5.0); + color = mix(refracted, reflected, fresnel); + } + out_color = vec4(color * uTint * uEnvironmentTint, 1.0); +} diff --git a/shaders/phong.frag b/shaders/phong.frag index 1cf41bf..6463bef 100644 --- a/shaders/phong.frag +++ b/shaders/phong.frag @@ -13,12 +13,17 @@ struct Material { int alphaMode; // 0 = 不透明 / opaque, 1 = マスク / mask (discard), 2 = ブレンド / blend float alphaCutoff; // マスクのしきい値 / the mask threshold 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 }; uniform Material uMaterial; layout(binding = 0) uniform sampler2D uDiffuseMap; layout(binding = 1) uniform sampler2D uSpecularMap; layout(binding = 2) uniform sampler2D uEmissionMap; +// 環境(空)のキューブマップ。ユニット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) // 平行光源:向きだけ / directional light: a direction only struct DirectionalLight { @@ -137,6 +142,14 @@ void main() { addLight(s, l, uSpotLights[i].color * attenuate(d, uSpotLights[i].attenuation) * cone, diffuse, specular); } + // 空の映り込み:反射の方向でキューブマップを引く。ぼかしは小さいミップマップを使うだけ(textureLod) + // Sky reflection: look up the cube map in the reflected direction. Blur just means a smaller mip level (textureLod) + if (uMaterial.reflectivity != vec3(0.0)) { + vec3 r = reflect(-s.view, s.normal); + float lod = uMaterial.reflectionBlur * float(textureQueryLevels(uEnvironmentMap) - 1); + specular += uMaterial.reflectivity * uEnvironmentTint * textureLod(uEnvironmentMap, r, lod).rgb; + } + vec3 ambient = uAmbient * s.diffuse; vec3 color = ambient + diffuse + specular + emission; if (uViewMode == 1) color = ambient; diff --git a/shaders/skybox.frag b/shaders/skybox.frag new file mode 100644 index 0000000..8775250 --- /dev/null +++ b/shaders/skybox.frag @@ -0,0 +1,15 @@ +#version 460 core +in vec3 vDirection; + +// 環境のキューブマップはユニット3(0〜2はマテリアルのマップ) / the environment cube map is on unit 3 +// (0..2 are the material maps) +layout(binding = 3) uniform samplerCube uSkybox; + +uniform vec3 uEnvironmentTint; // 空の明るさ(昼1、夜は暗く) / brightness of the sky (1 by day, dark at night) + +layout(location = 0) out vec4 out_color; + +void main() { + // 方向は正規化しなくて良い:一番大きい成分で面が決まる / no need to normalize: the largest component picks the face + out_color = vec4(uEnvironmentTint * texture(uSkybox, vDirection).rgb, 1.0); +} diff --git a/shaders/skybox.vert b/shaders/skybox.vert new file mode 100644 index 0000000..d6efb54 --- /dev/null +++ b/shaders/skybox.vert @@ -0,0 +1,19 @@ +#version 460 core +// 空の箱:カメラの周りの立方体の内側に、キューブマップを方向で貼る +// The sky box: a cube around the camera, textured from the inside by direction +layout(location = 0) in vec3 aPosition; // makeCube()の頂点(±0.5) / makeCube()'s vertices (±0.5) + +uniform mat4 uView; +uniform mat4 uProj; + +out vec3 vDirection; // キューブマップを引く方向 / the direction to look up the cube map with + +void main() { + vDirection = aPosition; + // mat3にして戻すと平行移動が消える:空はカメラと一緒に動き、遠くにあるように見える + // Going through mat3 drops the translation: the sky moves with the camera and looks infinitely far away + vec4 clip = uProj * mat4(mat3(uView)) * vec4(aPosition, 1.0); + // z = wにすると、透視除算の後の深度がちょうど1(一番奥)になる / z = w makes the depth exactly 1 (the far end) + // after the perspective divide + gl_Position = clip.xyww; +} diff --git a/src/cubemap.cc b/src/cubemap.cc new file mode 100644 index 0000000..b2e2f3d --- /dev/null +++ b/src/cubemap.cc @@ -0,0 +1,82 @@ +#include "cubemap.hh" + +#include + +#include +#include + +Cubemap::Cubemap(int size, GLenum internalFormat, int levels) : faceSize(size), mipLevels(levels) { + glCreateTextures(GL_TEXTURE_CUBE_MAP, 1, &handle); + // 6面ぶんのストレージを一度に(glTextureStorage2Dで良い:キューブマップは2Dの面の集まり) + // Storage for all six faces at once (glTextureStorage2D: a cube map is a set of 2D faces) + glTextureStorage2D(handle, levels, internalFormat, size, size); + // 方向で引くので、面の端の外を読まないように3方向ともCLAMP_TO_EDGE + // Looked up by direction: CLAMP_TO_EDGE in all three directions so nothing is read past a face's edge + glTextureParameteri(handle, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTextureParameteri(handle, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + glTextureParameteri(handle, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); + glTextureParameteri(handle, GL_TEXTURE_MIN_FILTER, levels > 1 ? GL_LINEAR_MIPMAP_LINEAR : GL_LINEAR); + glTextureParameteri(handle, GL_TEXTURE_MAG_FILTER, GL_LINEAR); +} + +void Cubemap::uploadFace(int face, const unsigned char *rgba) { + glPixelStorei(GL_UNPACK_ALIGNMENT, 1); + // DSAでは面を3次元目(zoffset)で選ぶ:zoffset = face、depth = 1 + // With DSA the face is chosen with the third coordinate: zoffset = face, depth = 1 + glTextureSubImage3D(handle, 0, 0, 0, face, faceSize, faceSize, 1, GL_RGBA, GL_UNSIGNED_BYTE, rgba); + glPixelStorei(GL_UNPACK_ALIGNMENT, 4); +} + +std::optional Cubemap::load(const std::array &paths) { + // キューブマップの面は上の行から(RenderManの決まり)。反転しない + // Cube-map faces start at the top row (the RenderMan convention). Do not flip + stbi_set_flip_vertically_on_load(0); + Cubemap cube; + for (int face = 0; face < 6; ++face) { + const std::string &path = paths[static_cast(face)]; + int width = 0, height = 0, channels = 0; + unsigned char *pixels = stbi_load(path.c_str(), &width, &height, &channels, 4); + if (!pixels) { + fprintf(stderr, "%s: 画像を読めない / cannot load image: %s\n", path.c_str(), stbi_failure_reason()); + return std::nullopt; + } + if (width != height || (face > 0 && width != cube.faceSize)) { + fprintf(stderr, "%s: 面は全部同じ大きさの正方形であること / all faces must be squares of the same size (%d × %d)\n", + path.c_str(), width, height); + stbi_image_free(pixels); + return std::nullopt; + } + if (face == 0) { + int levels = 1; + while ((width >> levels) > 0) ++levels; + cube = Cubemap(width, GL_RGBA8, levels); + } + cube.uploadFace(face, pixels); + stbi_image_free(pixels); + } + glGenerateTextureMipmap(cube.handle); + return cube; +} + +std::optional Cubemap::loadDirectory(const std::string &dir, const std::string &extension) { + std::array paths; + for (int i = 0; i < 6; ++i) paths[static_cast(i)] = dir + "/" + kCubeFaceNames[i] + extension; + return load(paths); +} + +Cubemap::~Cubemap() { + if (handle) glDeleteTextures(1, &handle); +} + +Cubemap::Cubemap(Cubemap &&other) noexcept + : handle(std::exchange(other.handle, 0)), faceSize(other.faceSize), mipLevels(other.mipLevels) {} + +Cubemap &Cubemap::operator=(Cubemap &&other) noexcept { + if (this != &other) { + if (handle) glDeleteTextures(1, &handle); + handle = std::exchange(other.handle, 0); + faceSize = other.faceSize; + mipLevels = other.mipLevels; + } + return *this; +} diff --git a/src/cubemap.hh b/src/cubemap.hh new file mode 100644 index 0000000..ae07169 --- /dev/null +++ b/src/cubemap.hh @@ -0,0 +1,49 @@ +// キューブマップ:6枚の正方形の画像で、方向から色を引くテクスチャ(空、反射) +// Cubemaps: a texture made of six square images that is looked up by direction (skies, reflections) +#pragma once + +#include + +#include +#include +#include + +// 面の順番はOpenGLと同じ:+X, -X, +Y, -Y, +Z, -Z(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i) +// The face order is OpenGL's: +X, -X, +Y, -Y, +Z, -Z (GL_TEXTURE_CUBE_MAP_POSITIVE_X + i) +constexpr const char *kCubeFaceNames[6] = {"px", "nx", "py", "ny", "pz", "nz"}; + +// キューブマップテクスチャ(RAII、コピー不可・移動可)。DSAで作る。 +// A cube-map texture (RAII, non-copyable, movable), created with DSA. +class Cubemap { +public: + Cubemap() = default; + // 中身のないストレージを作る(size × size の面が6枚) / allocates empty storage (six size × size faces) + Cubemap(int size, GLenum internalFormat, int levels = 1); + ~Cubemap(); + Cubemap(const Cubemap &) = delete; + Cubemap &operator=(const Cubemap &) = delete; + Cubemap(Cubemap &&other) noexcept; + Cubemap &operator=(Cubemap &&other) noexcept; + + // 6枚の画像ファイルから読む(順番は+X, -X, +Y, -Y, +Z, -Z)。上下反転はしない:キューブマップの面は上の行から。 + // 全部同じ大きさの正方形であること。ミップマップを作る(ぼやけた反射用)。失敗したらエラーを表示してstd::nullopt。 + // 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); + // 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"); + + // 面face(0〜5)のミップマップ0段目を書き換える(RGBA8) / replaces mip level 0 of face `face` (0..5, RGBA8) + void uploadFace(int face, const unsigned char *rgba); + + void bind(GLuint unit) const { glBindTextureUnit(unit, handle); } + GLuint id() const { return handle; } + int size() const { return faceSize; } + int levels() const { return mipLevels; } + +private: + GLuint handle = 0; + int faceSize = 0; + int mipLevels = 0; +}; diff --git a/src/main.cc b/src/main.cc index 1e8e3c4..6365d04 100644 --- a/src/main.cc +++ b/src/main.cc @@ -1,5 +1,5 @@ -// 第17章:フレームバッファとポストプロセス -// Chapter 17: framebuffers and post-processing +// 第18章:キューブマップ +// Chapter 18: cubemaps // // 操作 / Controls: // WASD 前後左右に移動 / move forward, back, left, right @@ -7,19 +7,23 @@ // Shift 速く動く / move faster // マウス / mouse 向きを変える(FPS)、左ドラッグで回る(オービット) / look around (FPS), drag with the left button to orbit // ホイール / wheel ズーム / zoom +// M 手前の3つ:いろいろ → 全部反射 → 全部屈折 → 全部フレネル +// the three objects in front: mixed → all reflection → all refraction → all Fresnel +// K 空(スカイボックス)のオン・オフ / sky box on / off +// X 継ぎ目のないキューブマップの補間(GL_TEXTURE_CUBE_MAP_SEAMLESS)のオン・オフ +// seamless cube-map filtering (GL_TEXTURE_CUBE_MAP_SEAMLESS) on / off // 1〜6 効果:なし / 反転 / グレースケール / シャープ / ぼかし / エッジ検出 // effect: none / invert / grayscale / sharpen / blur / edge detection -// M バックミラーのオン・オフ / rear-view mirror on / off -// L 低解像度(1/4、GL_NEAREST)⇔ 普通 / low resolution (1/4, GL_NEAREST) ⇔ normal // 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 golden crate // Tab カーソルのキャプチャ切り替え / toggle cursor capture // R シェーダーを読み直す / reload the shaders // Esc 終了 / quit #include "camera.hh" +#include "cubemap.hh" #include "framebuffer.hh" #include "lights.hh" #include "material.hh" @@ -44,20 +48,28 @@ struct Placement { float angle; }; -// 最後の3つはカメラの後ろ(バックミラーに映る) / the last three are behind the camera (seen in the rear-view mirror) static const Placement kCrates[] = { - {{5.5f, 0.0f, 1.5f}, 0.4f}, {{6.3f, 0.0f, 2.6f}, -0.3f}, {{5.9f, 1.0f, 2.0f}, 0.1f}, - {{-6.0f, 0.0f, -1.0f}, 0.8f}, {{-5.2f, 0.0f, 3.5f}, -0.6f}, {{-1.6f, 0.0f, 17.0f}, 0.3f}, - {{-0.5f, 0.0f, 17.6f}, -0.2f}, {{-1.1f, 1.0f, 17.3f}, 0.6f}, + {{5.5f, 0.0f, 1.5f}, 0.4f}, {{6.3f, 0.0f, 2.6f}, -0.3f}, {{5.9f, 1.0f, 2.0f}, 0.1f}, + {{-6.0f, 0.0f, -1.0f}, 0.8f}, {{-5.2f, 0.0f, 3.5f}, -0.6f}, }; -static const Placement kWindows[] = { - {{-0.75f, 0.0f, 8.7f}, 0.15f}, {{2.6f, 0.0f, 7.4f}, -0.3f}, {{-0.3f, 0.0f, 7.3f}, 0.1f}, {{0.25f, 0.0f, 5.9f}, 0.05f}, - {{1.8f, 0.0f, 16.4f}, 2.9f}, // カメラの後ろ / behind the camera +// 手前の環境マッピングの物:球二つと、木箱のモデル / the environment-mapped objects in front: two spheres and the +// crate model +enum EnvMode { kReflect = 0, kRefract = 1, kFresnel = 2 }; +struct EnvObject { + Vec3 position; + int mode; // 「いろいろ」のときのモード / the mode in "mixed" + Vec3 tint; // 反射の色(金属の色) / reflection colour (the metal's colour) +}; +static const EnvObject kEnvObjects[] = { + {{-2.8f, 0.75f, 7.0f}, kFresnel, {1.0f, 1.0f, 1.0f}}, // ガラスの球 / glass sphere + {{0.0f, 1.0f, 7.6f}, kReflect, {0.95f, 0.8f, 0.55f}}, // 金色の木箱(宙に浮いて回る) / a golden crate (hovers, tumbling) + {{2.8f, 0.75f, 7.0f}, kReflect, {0.95f, 0.95f, 0.97f}}, // クロムの球 / chrome sphere }; static const char *const kViewModeNames[] = {"all", "ambient", "diffuse", "specular", "emission", "normals"}; static const char *const kEffectNames[] = {"none", "invert", "grayscale", "sharpen", "blur", "edge detection"}; +static const char *const kEnvModeNames[] = {"mixed", "all reflection", "all refraction", "all Fresnel"}; static float random01(std::uint32_t &state) { state = state * 1664525u + 1013904223u; @@ -75,9 +87,8 @@ static std::vector makeGrass() { for (Vec3 q : avoid) ok = ok && length(Vec3{p.x - q.x, 0, p.z - q.z}) > 1.1f; if (ok) grass.push_back({p, 2.0f * PI * random01(seed)}); } - const Placement front[] = {{{1.5f, 0, 6.2f}, 0.3f}, {{-2.9f, 0, 7.0f}, 1.2f}, {{3.6f, 0, 5.4f}, 2.0f}, - {{1.2f, 0, 8.9f}, 0.7f}, {{-2.6f, 0, 9.6f}, 2.6f}, {{0.6f, 0, 10.7f}, 0.5f}, - {{0.4f, 0, 16.6f}, 1.0f}, {{-2.4f, 0, 16.2f}, 2.2f}}; + const Placement front[] = {{{1.5f, 0, 6.2f}, 0.3f}, {{-4.0f, 0, 7.6f}, 1.2f}, {{3.9f, 0, 5.4f}, 2.0f}, + {{1.4f, 0, 8.9f}, 0.7f}, {{-1.6f, 0, 8.6f}, 2.6f}}; for (const Placement &p : front) grass.push_back(p); return grass; } @@ -90,19 +101,23 @@ struct View { int main() { Window window; - if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 17")) return 1; + if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 18")) return 1; std::optional phong = Shader::load("shaders/phong.vert", "shaders/phong.frag"); std::optional post = Shader::load("shaders/post.vert", "shaders/post.frag"); + std::optional skybox = Shader::load("shaders/skybox.vert", "shaders/skybox.frag"); + // 環境マッピング:頂点シェーダーはphongと同じ(ワールド座標の位置と法線) / environment mapping: the same vertex + // shader as phong (world-space position and normal) + std::optional envmap = Shader::load("shaders/phong.vert", "shaders/envmap.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 || !post || !floorTexture || !grassTexture) return 1; + if (!phong || !post || !skybox || !envmap || !sky || !floorTexture || !grassTexture) return 1; grassTexture->setWrap(GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE); std::optional scene = Model::load("assets/models/diorama.glb"); std::optional crate = Model::load("assets/models/crate.glb"); - std::optional windowModel = Model::load("assets/models/window.glb"); - if (!scene || !crate || !windowModel) return 1; + if (!scene || !crate) return 1; const unsigned char whitePixel[4] = {255, 255, 255, 255}; Texture2D white = Texture2D::fromPixels(whitePixel, 1, 1, {.flipY = false, .mipmaps = false}); @@ -112,8 +127,8 @@ int main() { Quat rotorStart = rotor >= 0 ? scene->nodes[static_cast(rotor)].rotation : Quat{}; Camera fps; - fps.position = {0.0f, 2.1f, 13.0f}; - fps.pitch = radians(-9.0f); + fps.position = {0.0f, 2.0f, 12.5f}; + fps.pitch = radians(-6.0f); OrbitCamera orbit; orbit.target = {0.0f, 1.0f, 4.0f}; @@ -121,32 +136,25 @@ int main() { orbit.yaw = radians(20.0f); bool useOrbit = false; - int viewMode = 0, effect = 0; - bool night = false, flashlightOn = false, windmillMoving = true, mirrorOn = true, lowRes = false; + int viewMode = 0, effect = 0, envMode = 0; + bool night = false, flashlightOn = false, windmillMoving = true, skyOn = true, seamless = true; float windmillTime = 0.0f; window.setCursorCaptured(true); - // 場面を描くフレームバッファ(ウィンドウと同じ大きさ、低解像度なら1/4)とバックミラー用 - // The framebuffer the scene is drawn into (window size, or 1/4 in low-resolution mode) and one for the mirror - auto sceneSize = [&](int size) { return std::max(1, lowRes ? size / 4 : size); }; - Framebuffer sceneFbo(sceneSize(window.width()), sceneSize(window.height())); - const int mirrorWidth = 480, mirrorHeight = 150; - Framebuffer mirrorFbo(mirrorWidth, mirrorHeight); - if (!sceneFbo.complete() || !mirrorFbo.complete()) return 1; - - // 低解像度ではGL_NEARESTで拡大:ピクセルがはっきり見える / low resolution is magnified with GL_NEAREST: crisp pixels - auto resizeScene = [&] { - sceneFbo.resize(sceneSize(window.width()), sceneSize(window.height())); - GLenum filter = lowRes ? GL_NEAREST : GL_LINEAR; - sceneFbo.color().setFilter(filter, filter); - }; - // ウィンドウの大きさが変わったら、フレームバッファも作り直す / when the window size changes, so does the framebuffer - window.onResize = [&](int, int) { resizeScene(); }; + // 場面を描くフレームバッファ(ウィンドウと同じ大きさ) / the framebuffer the scene is drawn into (window size) + Framebuffer sceneFbo(window.width(), window.height()); + if (!sceneFbo.complete()) return 1; + window.onResize = [&](int width, int height) { sceneFbo.resize(width, height); }; + + // キューブマップの面の境目でも隣の面と補間する(GL 3.2から、全体の設定) / filter across the edges between + // cube-map faces too (since GL 3.2, a global switch) + glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS); 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() && post->reload()) printf("シェーダーを読み直した / shaders reloaded\n"); + if (key == GLFW_KEY_R && phong->reload() && post->reload() && skybox->reload() && envmap->reload()) + printf("シェーダーを読み直した / shaders reloaded\n"); if (key == GLFW_KEY_TAB) window.setCursorCaptured(!window.cursorCaptured()); if (key == GLFW_KEY_C) { useOrbit = !useOrbit; @@ -161,18 +169,27 @@ int main() { effect = key - GLFW_KEY_1; printf("effect: %s\n", kEffectNames[effect]); } - if (key == GLFW_KEY_M) mirrorOn = !mirrorOn; - if (key == GLFW_KEY_L) { - lowRes = !lowRes; - resizeScene(); - printf("scene framebuffer: %d x %d\n", sceneFbo.width(), sceneFbo.height()); + if (key == GLFW_KEY_M) { + envMode = (envMode + 1) % 4; + printf("environment objects: %s\n", kEnvModeNames[envMode]); + } + if (key == GLFW_KEY_K) skyOn = !skyOn; + if (key == GLFW_KEY_X) { + seamless = !seamless; + if (seamless) glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS); + else glDisable(GL_TEXTURE_CUBE_MAP_SEAMLESS); + printf("seamless cube-map filtering: %s\n", seamless ? "on" : "off"); } if (key == GLFW_KEY_N) night = !night; if (key == GLFW_KEY_F) flashlightOn = !flashlightOn; if (key == GLFW_KEY_P) windmillMoving = !windmillMoving; }; - Mesh floorMesh = makePlane(40.0f, 10.0f); + // 床は空の地平線まで届くように広く(遠くはfarPlaneで切れる) / the floor is wide so it reaches the sky's horizon + // (the far plane cuts it off in the distance) + Mesh floorMesh = makePlane(160.0f, 40.0f); + Mesh sphereMesh = makeSphere(48, 24); + Mesh cubeMesh = makeCube(); // 空の箱 / the sky box Material floorMaterial; floorMaterial.diffuseMap = &*floorTexture; floorMaterial.specular = {0.15f, 0.15f, 0.15f}; @@ -193,19 +210,25 @@ int main() { LightSet lights; - // 場面全体を今のフレームバッファに描く(第16章の描き方:不透明 → 半透明を遠い順) - // Draws the whole scene into the current framebuffer (chapter 16's order: opaque, then transparent far to near) + Vec3 environmentTint; + + // 場面全体を今のフレームバッファに描く / draws the whole scene into the current framebuffer auto drawScene = [&](const View &v) { glEnable(GL_DEPTH_TEST); if (night) glClearColor(0.02f, 0.03f, 0.06f, 1.0f); else glClearColor(0.45f, 0.62f, 0.85f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); + // 空はユニット3。phong(金属の映り込み)、envmap、skyboxのどれもここから読む + // The sky is on unit 3: phong (metal reflections), envmap and skybox all read it from there + sky->bind(3); + phong->use(); phong->set("uView", v.view); phong->set("uProj", v.proj); phong->set("uViewPos", v.position); phong->set("uViewMode", viewMode); + phong->set("uEnvironmentTint", environmentTint); lights.apply(*phong); phong->set("uModel", Mat4::identity()); @@ -214,8 +237,6 @@ int main() { 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); - for (const Placement &w : kWindows) - windowModel->draw(*phong, translate(w.position) * rotateY(w.angle), white, ModelPass::Opaque); grassMaterial.apply(*phong, white); glDisable(GL_CULL_FACE); // 草は両面 / grass is two-sided for (const Placement &g : grass) { @@ -226,15 +247,48 @@ int main() { } glEnable(GL_CULL_FACE); - // 窓のガラス:遠い順 / the window glass, far to near - std::vector> glass; - for (const Placement &w : kWindows) - glass.push_back({length(w.position + Vec3{0.0f, 0.8f, 0.0f} - v.position), translate(w.position) * rotateY(w.angle)}); - std::sort(glass.begin(), glass.end(), [](const auto &a, const auto &b) { return a.first > b.first; }); - glEnable(GL_BLEND); - glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA); - for (const auto &g : glass) windowModel->draw(*phong, g.second, white, ModelPass::Transparent, v.position); - glDisable(GL_BLEND); + // 環境マッピングの物 / the environment-mapped objects + envmap->use(); + envmap->set("uView", v.view); + envmap->set("uProj", v.proj); + envmap->set("uViewPos", v.position); + envmap->set("uEnvironmentTint", environmentTint); + envmap->set("uIor", 1.52f); + for (size_t i = 0; i < std::size(kEnvObjects); ++i) { + const EnvObject &o = kEnvObjects[i]; + envmap->set("uEnvMode", envMode == 0 ? o.mode : envMode - 1); + envmap->set("uTint", o.tint); + if (i == 1) { + // 平らな面は一つの方向しか映さない:回すと映る空が変わる。木箱の原点は底なので、中心(0, 0.5, 0)の周りで回す + // A flat face reflects only one direction: turning it changes the sky it shows. The crate's origin is at its + // bottom, so it turns about its centre (0, 0.5, 0) + Mat4 model = translate(o.position) * rotate(normalize(Vec3{1.0f, 1.0f, 0.3f}), 0.6f * windmillTime + 0.8f) * + translate({0.0f, -0.5f, 0.0f}); + crate->drawGeometry(*envmap, model); // uModelとuNormalMatrixだけ / only uModel and uNormalMatrix + } else { + Mat4 model = translate(o.position) * scale({1.5f, 1.5f, 1.5f}); + envmap->set("uModel", model); + envmap->set("uNormalMatrix", normalMatrix(model)); + sphereMesh.draw(); + } + } + + // 空は不透明な物の後に:見えているピクセルだけ塗る(深度1のところ)。半透明な物があればその前 + // The sky after the opaque objects: it only fills pixels nothing covers (depth 1). Before any transparent ones + if (skyOn) { + // 空の深度はちょうど1.0。クリアした値も1.0なので、GL_LESSでは通らない:GL_LEQUALにする + // The sky's depth is exactly 1.0, the same as the cleared value, so GL_LESS would reject it: use GL_LEQUAL + glDepthFunc(GL_LEQUAL); + // 箱を内側から見るので、見えるのは裏面:カリングを切る / we see the box from inside, i.e. its back faces: no culling + glDisable(GL_CULL_FACE); + skybox->use(); + skybox->set("uView", v.view); + skybox->set("uProj", v.proj); + skybox->set("uEnvironmentTint", environmentTint); + cubeMesh.draw(); + glEnable(GL_CULL_FACE); + glDepthFunc(GL_LESS); + } }; double lastTime = window.time(); @@ -276,6 +330,7 @@ int main() { main.position = useOrbit ? orbit.position() : fps.position; Vec3 viewDir = useOrbit ? normalize(orbit.target - orbit.position()) : fps.front(); + environmentTint = night ? Vec3{0.05f, 0.06f, 0.11f} : Vec3{1.0f, 1.0f, 1.0f}; lights = LightSet{}; if (!night) { lights.ambient = {0.28f, 0.30f, 0.34f}; @@ -295,22 +350,7 @@ int main() { sceneFbo.bind(); drawScene(main); - // 2. バックミラー:後ろ向きのカメラで、もう一度場面を描く(別のフレームバッファへ) - // 2. The rear-view mirror: draw the scene again with a camera looking backwards (into another framebuffer) - if (mirrorOn) { - Vec3 forward = viewDir; - forward.y = 0.0f; - forward = length(forward) > 0.0f ? normalize(forward) : Vec3{0.0f, 0.0f, -1.0f}; - View rear; - rear.position = main.position; - // 水平な後ろ向きから少し下を見る / backwards and horizontal, tilted down a little - rear.view = lookAt(main.position, main.position - forward + Vec3{0.0f, -0.3f, 0.0f}, {0.0f, 1.0f, 0.0f}); - rear.proj = perspectiveGl(radians(30.0f), static_cast(mirrorWidth) / static_cast(mirrorHeight), 0.1f, 100.0f); - mirrorFbo.bind(); - drawScene(rear); - } - - // 3. 画面へ:全画面の三角形でフレームバッファのテクスチャを貼り、効果をかける + // 2. 画面へ:全画面の三角形でフレームバッファのテクスチャを貼り、効果をかける // 3. To the screen: a fullscreen triangle samples the framebuffer's texture and applies the effect Framebuffer::bindDefault(window.width(), window.height()); glDisable(GL_DEPTH_TEST); // 三角形一つだけ:深度は要らない / a single triangle: no depth needed @@ -320,24 +360,6 @@ int main() { sceneFbo.color().bind(0); fullscreen.draw(); - // 4. バックミラー:画面の上の小さな長方形に。枠はシザーテストでクリアして描く。左右は反転(鏡)、効果はなし - // 4. The mirror: a small rectangle at the top of the screen. The frame is a scissored clear. Flipped left-right - // (it is a mirror), no effect - if (mirrorOn) { - int x = (window.width() - mirrorWidth) / 2, y = window.height() - mirrorHeight - 16; - glEnable(GL_SCISSOR_TEST); - glScissor(x - 4, y - 4, mirrorWidth + 8, mirrorHeight + 8); - glClearColor(0.08f, 0.08f, 0.09f, 1.0f); - glClear(GL_COLOR_BUFFER_BIT); - glDisable(GL_SCISSOR_TEST); - glViewport(x, y, mirrorWidth, mirrorHeight); // 全画面の三角形がこの長方形だけを覆う / the fullscreen triangle now covers only this - post->set("uEffect", 0); - post->set("uFlipX", 1); - mirrorFbo.color().bind(0); - fullscreen.draw(); - glViewport(0, 0, window.width(), window.height()); - } - window.swapBuffers(); } return 0; diff --git a/src/material.cc b/src/material.cc index 4553e35..43d1379 100644 --- a/src/material.cc +++ b/src/material.cc @@ -11,6 +11,8 @@ void Material::apply(const Shader &shader, const Texture2D &white) const { shader.set("uMaterial.alphaMode", static_cast(alphaMode)); shader.set("uMaterial.alphaCutoff", alphaCutoff); shader.set("uMaterial.doubleSided", doubleSided ? 1 : 0); // boolのユニフォームはintで設定する / bool uniforms are set as int + shader.set("uMaterial.reflectivity", reflectivity); + shader.set("uMaterial.reflectionBlur", reflectionBlur); (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 index f32bf54..bd3ef6e 100644 --- a/src/material.hh +++ b/src/material.hh @@ -27,6 +27,11 @@ struct Material { bool doubleSided = false; // 両面:裏面では法線を反転する(カリングはModelが切る) / double-sided: // the normal is flipped on back faces (Model turns culling off) + // 環境(ユニット3のキューブマップ)の映り込み(第18章)。金属だけ。第24章のIBLまでの簡単な代わり + // Reflection of the environment (the cube map on unit 3, chapter 18). Metals only; a simple stand-in until IBL (ch24) + Vec3 reflectivity = {0.0f, 0.0f, 0.0f}; // 映り込みの色と強さ(0 = なし) / colour and strength of the reflection (0 = none) + float reflectionBlur = 0.0f; // 0 = 鏡、1 = 一番ぼやけたミップマップ / 0 = mirror, 1 = the blurriest mip level + const Texture2D *diffuseMap = nullptr; // テクスチャユニット0 / texture unit 0 const Texture2D *specularMap = nullptr; // テクスチャユニット1 / texture unit 1 const Texture2D *emissionMap = nullptr; // テクスチャユニット2 / texture unit 2 diff --git a/src/model.cc b/src/model.cc index 75eb929..e34f3d4 100644 --- a/src/model.cc +++ b/src/model.cc @@ -43,6 +43,12 @@ static Material phongFromPbr(const GltfMaterial &m, float metallicScale, float r : AlphaMode::Opaque; p.alphaCutoff = m.alphaCutoff; p.doubleSided = m.doubleSided; + // 空の映り込み(第18章):金属の正面の反射率F0。金属度は平均なので二乗して、木と金属が混ざった + // マテリアル(木箱:平均0.29)がほとんど映らないようにする。粗いほどぼやける + // Reflection of the sky (chapter 18): a metal's reflectance F0. Metallic is an average, so it is squared to keep + // mixed wood-and-metal materials (the crate: average 0.29) from reflecting much. Rougher = blurrier + p.reflectivity = (metallic * metallic) * f0; + p.reflectionBlur = roughness; return p; }