18. キューブマップ
今迄、あたし達のシーンは平らな青いクリアカラーの前に立っていました。
第14章の金属が殆ど黒かったのも、周りに映す物が何も無かったからです。
此の章では、世界に周囲を与えます。
空です。
其の為の道具がキューブマップです。
6枚の正方形の画像から出来たテクスチャで、UV座標ではなく方向で読みます。
空を6枚の画像として生成し、キューブマップに読み込み、全ての物の後ろにスカイボックスとして描きます。
そして同じテクスチャを、鏡の様な反射、ガラスの様な屈折、フレネル効果にも使います。
最後には、第14章から黒かった風車の真鍮のハブに、やっとぼやけた空が映ります。
途中で、殆ど誰もが混乱するキューブマップの部分も解きほぐします。
どの面がどれで、各面のどちらが上なのか、です。
18.1 此の章で作る物
第17章のフレームバッファとポストプロセスは其のままです。
ジオラマの後ろは雲と太陽のある空になり、ジオラマの手前に環境マッピングを使う物が3つ立ちます。
ガラスの球、宙に浮いて回る金色の木箱、クロムの球です。
操作:
- W、A、S、D、スペース、左Ctrl、Shift、マウス、ホイール:今迄通り移動と見回し
- M:手前の3つ:いろいろ(ガラス、金、クロム)→ 全部反射 → 全部屈折 → 全部フレネル(新規)
- K:スカイボックスのオン・オフ(新規)
- X:継ぎ目の無いキューブマップの補間のオン・オフ(新規)
- 1〜6:第17章のポストエフェクト
- C:FPS ⇔ オービットカメラ、V:表示モード、N:昼 ⇔ 夜、F:懐中電灯
- P:風車と金色の木箱を止める・回す
- Tab:カーソルの解放、R:シェーダーを読み直す、Esc:終了
第17章からの変更:
src/cubemap.hhとsrc/cubemap.cc(新規):Cubemapクラスshaders/skybox.vert、shaders/skybox.frag(新規):スカイボックスshaders/envmap.frag(新規):反射、屈折、フレネルshaders/phong.frag:テクスチャユニット3の環境キューブマップ。金属が其れを映すsrc/material.hh、src/material.cc、src/model.cc:MaterialのreflectivityとreflectionBlur。glTFの金属度と粗さから設定するsrc/main.cc:空、手前の3つ、ずっと広い床。第17章のバックミラー、低解像度モード、窓は無くなりました(window.glbはassets/に残っていますが使いません)assets/textures/sky/(新規):px.png、nx.png、py.png、ny.png、pz.png、nz.png、其々512×512(完成したファイルは章のZIPとアセットのZIPのch18/に入っています)CMakeLists.txt:gameがsrc/cubemap.ccもコンパイルする様に
add_executable(game
src/main.cc
src/window.cc
src/gl_debug.cc
src/buffer.cc
src/mesh.cc
src/file_util.cc
src/shader.cc
src/texture.cc
src/shapes.cc
src/camera.cc
src/material.cc
src/lights.cc
src/json.cc
src/gltf.cc
src/model.cc
src/framebuffer.cc
src/cubemap.cc)
18.2 方向で読むテクスチャ
1点を囲む6つの面
内側の6つの壁に絵が描かれた立方体の真ん中に立っていると想像して下さい。
どちらを見ても、視線は丁度1つの壁の1点に当たります。
其れがキューブマップです。
全ての方向に、色が1つあります。
一番分かり易い使い道は空です。
空とは正に「全ての方向に1つの色」だからです。
でも同じ考えで、反射(鏡が視線を跳ね返す方向を読む)、屈折(ガラスが視線を曲げる方向を読む)、第23章の点光源の影(光の周りの全ての方向で、一番近い面迄の距離)、第24章のイメージベースドライティングも出来ます。
GLSLではキューブマップはsamplerCubeで、vec3で読みます:
out_color = vec4(uEnvironmentTint * texture(uSkybox, vDirection).rgb, 1.0);
UV座標はありません。
方向は正規化する必要さえありません。
とは同じテクセルになります。
大事なのは向きだけで、長さは関係無いからです。
GPUが面を選ぶ方法
ハードウェアは方向を3つのステップで面と2Dの座標に変えます。
OpenGLの仕様書に正確な表があります(8.13節「Cube Map Texture Selection」)。
- 主軸を見つける:の成分の内、絶対値が一番大きい物。其の軸と符号で面が決まる。其の成分をと呼ぶ。
- 他の2つの成分を、下の表の符号でとにする。
- で割り(方向を−1〜1の正方形である面に投影する)、−1…1を0…1に写す。
| 主軸 | 面(レイヤー) | ||
|---|---|---|---|
| +X(0) | |||
| −X(1) | |||
| +Y(2) | |||
| −Y(3) | |||
| +Z(4) | |||
| −Z(5) |
其の後のは、其の面の上で2Dテクスチャの座標と全く同じ様に使われ、普通の補間が掛かります。
全ての2Dテクスチャと同じく、は面のメモリ上の最初の行です(第6章)。
計算例
を取ります。
絶対値が一番大きいのはで、正なので、面は+X、です。
表の1行目から、、です。
512×512の面では、列、行で、px.pngの最初の行から4分の1下がった所です。
此の方向は少し上を向いていて()、画像の上の方に当たります。
つまりファイルの最初の行は本当に絵の上端です。
此の事を覚えておいて下さい。
次の節の鍵です。
18.3 面の並びと向き
6つの面と其の順番
OpenGLは面に+X、−X、+Y、−Y、+Z、−Zの順で番号を付けます。
古いenumのGL_TEXTURE_CUBE_MAP_POSITIVE_X〜GL_TEXTURE_CUBE_MAP_NEGATIVE_Zは丁度此の順番の連続した6つの値です。
其の為、古いコードはGL_TEXTURE_CUBE_MAP_POSITIVE_X + iと書きます。
DSAでは同じ順番が0〜5のレイヤー番号になります。
ファイル名も其れに合わせました:px、nx、py、ny、pz、nzです。
此の図は、前の節の表を展開した立方体として描いた物です。
各面の橙の矢印は、画像ファイルの中でとがどちらに増えるかを示し、下の2行は其れがどのワールドの方向に沿うかを示します。
4つの横の面は全てです。
画像を下に進むと、世界でも下に進みます。
そして接する辺は揃っています。
+Zの右端(、方向)は+Xの左端(、同じ方向)で、+Zの一番上の行は+Yの一番下の行です。
本物の空を同じ様に並べると、こうなります:
地平線は−X、+Z、+X、−Zを段差無しに真っ直ぐ通り、+Yの雲は横の面に続いています。
どの面のファイルも普通の絵と同じく、上が空、下が地面として保存されています。
何故面を反転しないのか
第6章では、全ての画像を読み込む時に反転しました。
画像ファイルは上の行から保存し、あたし達が手で書いたUVは絵の下端がだったので、下の行を最初にアップロードする必要があったのです。
キューブマップの表は逆を選んでいます。
4つの横の面では全てなので、上を向いた方向は小さなになります。
計算例で見た通り、は面の上端です。
表は上の行が最初に来る事を期待していて、其れは丁度ファイルが保存している順番です。
従ってキューブマップの面は其のままアップロードし、反転しません。
Cubemap::loadがstbi_set_flip_vertically_on_load(0)を呼ぶのは其の為です(18.5節)。
第14章のglTFと同じ状況です。
決めるのはOpenGLではなく、データが作られた決まりです。
第6章のTexture2D::loadの癖で、反転をオンにして面を読み込むのが定番の間違いです。
あたし達のシーンでは、こうなります:
横の面は全て上下が逆になります。
空が下、地面が上に来るので、シーンの上に灰色の天井が掛かります。
上と下の面も前後が鏡映しになり、正しい辺で横の面と繋がらなくなります。
全ての方向を一度に見るクロムの球には、其の継ぎ目が壊れた模様として現れます。
「空に地面がある」とか、立方体の辺に沿って段差が見えるスカイボックスを見たら、先ず反転を疑って下さい。
鏡に映った様な見た目:RenderManの名残
もう1つ奇妙な点があります。
バグが無いのにバグだと疑わせる点です。
立方体の内側に立ち、+Yを上にして+Zの方を見ます。
右手系のあたし達の世界では、+Xは左にあります(右 = 前 × 上 = 、線型代数 第5章)。
でも+Zの面の画像ではは+Xに向かって増えるので、画像の右半分が+X側です。
内側から見ると、どの面も左右が反転して見えます。
上の十字は、真ん中に立って見える景色の鏡像です。
理由は歴史です。
OpenGLは此の並びをPixarのRenderManの環境マップから受け継ぎ、RenderManは左手系の座標系を使います。
左手系の世界で内側に立ち、+Yを上にして+Zを見ると、+Xは本当に右にあり、面は普通の写真の様に見えます。
同じく左手系のDirect3Dも同じ表を使い、Vulkanもそうです。
実際には、壊れていない物を直そうとしない限り、何も変わりません:
- 表が定義です。
texture(cube, d)が方向dに欲しい色を返すなら、其の面は正しい。あたし達の空の生成器は正に其の表から全てのピクセルを計算するので(次の節)、太陽は在るべき所にあります。 - 十字を「正しく見せる」為に面の画像を反転したり入れ替えたりしない事。OpenGL又はDirect3D向けにキューブマップを書き出すツールは、既に此の決まりで書きます。
- 別の決まりで作られた面を受け取ったら(番号や向きが違うツールもあります)、1か所で直す事。ファイル名を変えるか、シェーダーで引く方向を変えます。例えば
texture(sky, vec3(-d.x, d.y, d.z))は環境全体を鏡映しにします。「大体合って見える」迄1枚ずつ面をいじらない事。
18.4 方向から作る空
空の面は、第6章以来の全てのアセットと同じく、此のシリーズの為に作った小さなPythonのスクリプトで作りました(assets/LICENSE.txtに載っています)。
其れは6枚の絵を描くのではなく、キューブマップの表を逆向きに使います。
大きさの面の各ピクセルについて(が上の行):
そして其の面の表の行が、此れを方向にします。
+Xなら、+Zならです。
はサンプルをテクセルの中心に置きます。
GPUの補間がテクセルの値を正確な値として扱う場所です。
其の後、色は正規化した方向だけから計算されます:
- グラデーション: 地平線の白っぽい色(0.78, 0.85, 0.93)から天頂の濃い青(0.22, 0.42, 0.78)へ、で混ぜる。
- 雲: 方向を水平な「雲の平面」に投影し(とをで割るので、地平線近くの遠い雲ほど小さくなる)、其の2Dの点のフラクタルなバリューノイズ(GLSL 第8章)で雲の量を決める。地平線の少し上で雲は消える。
- 太陽: の周りに直径約1.6°の円盤と柔らかいにじみ。第14章のシーンの太陽の向きの逆なので、見える太陽は光が来る方向にあります。
- 地平線の下: もやが、遠くの床の色に近い灰色(0.46, 0.45, 0.43)に変わる。其の為、下半分の映り込みが地面に見える。
太陽は面の何処にあるでしょうか。
です。
一番大きいのはなので+Yの面で、、、です。
すると、で、py.pngの大体ピクセル(384, 346)です。
十字の画像(1面256ピクセル、+Yは2列目)ではピクセル(448, 173)で、白い点が其処にあります。
作り方からして継ぎ目が無い
6枚の絵を別々に描くと、殆ど必ず継ぎ目が出来ます。
立方体の辺の両側の色が違う絵から来ていて、正確に一致する事は滅多に無いからです。
各面を別々にぼかしたり、各面を其々の2Dノイズテクスチャで埋めたりしても、同じ被害が出ます。
あたし達の面には、作り方からして其の問題がありません。
各ピクセルの色は方向だけの関数、で、は連続です。
グラデーション、ノイズ(画像を引かずにから計算した位置で評価する)、太陽の円盤は、全て方向と共に滑らかに変わります。
+Zの最後の列と+Xの最初の列は、同じ辺の両側に半テクセル離れたテクセルの中心です。
其の方向は面の真ん中の隣り合う2つのテクセルと同じ位近く、従って色も同じ位近いのです。
どのピクセルも自分がどの面にいるかを知りません。
辺は特別ではないのです。
面ごとの処理は、バンディング防止の±½段階のランダムなディザだけで、明るさの範囲の1/256未満なので見えません。
此れで中身は解決しました。
補間が辺をまたいで混ぜるかどうかは別の問題で、其れには専用のスイッチがあります。
18.5 Cubemapクラス
ヘッダー
Cubemapは第6章のTexture2Dと同じくRAIIのラッパーで、何時も通りコピー不可・移動可です。
ヘッダー全体です:
// キューブマップ:6枚の正方形の画像で、方向から色を引くテクスチャ(空、反射)
// Cubemaps: a texture made of six square images that is looked up by direction (skies, reflections)
#pragma once
#include <glad/glad.h>
#include <array>
#include <optional>
#include <string>
// 面の順番は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<Cubemap> load(const std::array<std::string, 6> &paths);
// dir/px.png, dir/nx.png … を読む / loads dir/px.png, dir/nx.png, ...
static std::optional<Cubemap> 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;
};
kCubeFaceNamesは面の順番をファイル名にします。
loadDirectory("assets/textures/sky")はpx.pngを最初に、nz.pngを最後に読みます。
クラスは面の大きさとミップマップの段数を覚えておきます。
面のアップロードとシェーダーのぼかしが其れを必要とするからです。
ストレージを作る
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);
}
glCreateTextures(GL_TEXTURE_CUBE_MAP, 1, &handle):2Dテクスチャ(第6章)と同じDSAの呼び出しで、ターゲットがキューブマップ。ターゲットはオブジェクトが生きている間ずっと固定で、キューブマップとして作ったテクスチャを2Dテクスチャとしてバインドする事は出来ません。glTextureStorage2D(texture, levels, internalFormat, width, height):キューブマップでは、1回の呼び出しで6面全部と其の全てのミップマップを確保します。幅と高さは等しくなければならず(面は正方形)、違うとGL_INVALID_VALUEです。全てのglTextureStorage*と同じく不変で、大きさ、形式、段数は以後変えられません。
6枚の画像を確保する関数に「2D」とある事に注目して下さい。
OpenGLはキューブマップを、大きさが同じ6枚の2Dの面と見做します。
其の為ストレージの呼び出しは2Dの物で、面が3つ目の座標として現れるのはデータをアップロードする時だけです(直ぐ後で見ます)。
512²のRGBA8の空は、0段目でバイト(6 MiB)、ミップマップで更に3分の1、合計8 MiBです。
サンプラーの状態は今迄通りglTextureParameteriで設定します:
GL_TEXTURE_WRAP_S、GL_TEXTURE_WRAP_T:GL_CLAMP_TO_EDGE。シームレスな補間(次の節)が無いと、各面は其々独立した2Dテクスチャの様に補間されます。GL_REPEATだと、面の右端のサンプルが其の面の左端のテクセルを引き込み、空の反対側の色になります。クランプすると補間は面の上に留まります。GL_TEXTURE_WRAP_R:3つ目の座標のラップモード。面が選ばれた後には3つ目の座標は残っていないので、読み出しには影響しませんが、3つ全部を設定するのはよくある習慣で、何の負担もありません。- フィルター:
Texture2Dと同じく、ミップマップがあればトリリニア。今回のミップマップは縮小の為ではなく(空が遠くて小さくなる事はありません)、18.11節のぼやけた映り込みの為です。
面のアップロード
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);
}
glTextureSubImage3D(texture, level, xoffset, yoffset, zoffset, width, height, depth, format, type, pixels)は1つの面に書き込むDSAの方法です。
zoffsetが上の順番の面の番号0〜5で、depth = 1で丁度1面を書きます。
よくある間違い:
glTextureSubImage2Dを使う。 古いAPIではglTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, …)で面をアップロードしたので、glTextureSubImage2Dが自然に思えます。でもDSAの呼び出しは面のターゲットではなくテクスチャオブジェクトを取り、面を指定する引数がありません。キューブマップに使うとエラーで、第2章のデバッグコールバックが報告します。- 1枚の画像で
depth = 6。zoffset = 0, depth = 6で6面を1回でアップロードする事も出来ますが、其の場合pixelsには6面が(+Xから)続けて入っている必要があります。1面分のメモリでdepth = 6を渡すと、其の終わりを遥かに超えて読みます。 - アラインメント。 此処の
GL_UNPACK_ALIGNMENT1は安全の為の習慣です。RGBA8の行は必ず4バイトの倍数です。3チャンネルの画像では大事です(第6章)。
参考迄に、クラス全体の古い書き方はglGenTextures+glBindTexture(GL_TEXTURE_CUBE_MAP, tex)の後、glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGBA8, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels[i])を6回と、ラップモードとフィルターの為のglTexParameteri(GL_TEXTURE_CUBE_MAP, …)です。
古いチュートリアルの殆どが此れを見せています。
可変のストレージで同じ事をします。
6つのファイルを読む
std::optional<Cubemap> Cubemap::load(const std::array<std::string, 6> &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<size_t>(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> Cubemap::loadDirectory(const std::string &dir, const std::string &extension) {
std::array<std::string, 6> paths;
for (int i = 0; i < 6; ++i) paths[static_cast<size_t>(i)] = dir + "/" + kCubeFaceNames[i] + extension;
return load(paths);
}
最初に反転を切ります。
stbのフラグは全体の設定で、Texture2D::loadがオンのままにしているかも知れないからです。
全てのファイルはRGBAにデコードされるので(desiredChannels = 4)、3チャンネルのPNGも使えます。
検査は大事です。
面は正方形で全て同じ大きさでなければならず、間違ったファイルだと黒や化けた面になるか、glTextureSubImage3Dで範囲外の読み込みになります。
最初の面が大きさを決め、段数は「1×1になる迄半分にする」です。
512なら512、256、…、1の10段です。
glGenerateTextureMipmapは2Dテクスチャと同じくキューブマップにも使え、全ての面のチェーンを作ります。
各面は其々別に縮小されるので(普通は単純なボックスフィルター)、一番小さい段は面ごとの平均に過ぎません。
其れがぼやけた映り込みにとって何を意味するかは18.11節で見ます。
18.6 継ぎ目の無い補間
辺での問題
線型補間はサンプルの位置の周りの2×2のテクセルを読んで混ぜます(GLSL 第11章)。
面の端の近くでは、其の半分が辺の外にあります。
元々のキューブマップでは(そしてOpenGLでは3.2迄、今でも既定では)、各面は独立した2Dテクスチャとして補間されていました。
足りないテクセルは隣の面からではなく、其の面自身の端から取られます(クランプ)。
其の為、丁度辺の所で面Aは自分の端の色を、面Bも自分の色を見せ、其の間は混ざりません。
512ピクセルの面の0段目では、隣り合う2つのテクセルの差なので気付きません。
でも小さいミップマップでは1つのテクセルが広い角度を覆います。
8×8の段では1テクセルが空の約11°、1×1の段では各面が1色です。
ぼやけた映り込みは其の段を読むので、シームレスな補間が無いと、立方体の辺が線として、又は6色の平らな立方体として見えてしまいます。
スイッチ
// キューブマップの面の境目でも隣の面と補間する(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);
glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS)(OpenGL 3.2からコア)は、GPUに立方体を1つの連続した面として扱わせます。
辺をまたぐ補間のフットプリントは足りないテクセルを隣の面から取り、3つの面だけが接して4つ目のテクセルが存在しない角では、代わりに普通は他の3つの平均を使います(仕様は此れを推奨していますが、正確な方法は実装に任せています)。
此れは全体の状態で、テクスチャのパラメーターではないので、起動時に1回呼べば全てのキューブマップに効きます。
今のハードウェアでは測れる程の負担は無く、切る理由はありません。
VulkanとDirect3D 11にはスイッチさえ無く、キューブマップは何時もシームレスに補間されます。
比べられる様に、Xキーで切り替えます:
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");
}
左の絵は立方体の角を真っ直ぐ見ています(ヨー45°、ピッチ35.3°:方向)。
右は、面に色を付けたプロジェクトのデバッグ用コピーの同じフレームで、本当に3つの面が真ん中で接している事を示します。
本物の空では区別が付きません。
中身に継ぎ目が無く(18.4節)、補間にも継ぎ目が無いからです。
其処でXを押しても0段目では何も変わりません。
其れが期待通りの結果です。
スイッチが効くのは18.11節の金属が読むぼやけた段で、課題5で其の違いが見えます。
18.7 スカイボックス
考え方
キューブマップを空として見る為に、カメラの周りに立方体を描き、其の各ピクセルを、カメラから其のピクセルへの方向のキューブマップの色で塗ります。
立方体がカメラを中心にしていれば、其の方向は単に立方体自身の頂点の位置を面に沿って補間した物です。
必要なジオメトリは第8章のmakeCube()(角は±0.5)だけです。
シェーダー
#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;
}
#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);
}
フラグメントシェーダーは1回読むだけです。
vDirectionは正規化されていませんが(補間された位置は立方体の面の上にあります)、其の必要はありません。
18.2節の通り、どうせ主軸で割られます。
uEnvironmentTintは夜に昼の空を暗くします。
昼は(1, 1, 1)です。
平行移動を取り除く
lookAtのビュー行列(線型代数 第11章)は、回転と平行移動を1つの行列にした物です(同じシリーズの第9章)。
mat3(uView)は左上のの部分、つまり回転を残し、mat4(…)は其れを平行移動0の行列に戻します:
此れで箱はカメラが回ると一緒に回りますが、カメラに対して動く事はありません。
100メートル歩いても、空は付いて来ます。
太陽や雲の様な、無限に遠い物は正に其の様に振る舞います。
視差がありません。
此れを忘れると、スカイボックスはワールドの原点(風車の中の何処か)に立つ1メートルの立方体になり、歩いて外に出られてしまいます。
.xyww:全ての空のピクセルの深度を1に
頂点シェーダーの後、OpenGLは、、をで割ります(第8章)。
clip.xywwと書くとがに置き換わるので、割った後は
全ての空のピクセルは、立方体の本当の大きさに関係無く、ファープレーン上にあるかの様に、取り得る一番大きな深度になります。
此れはクリッピングも解決します。
ニアプレーンは箱を切れません(角は高々 m先ですが、ニアの距離より小さい箱でも、が無くなっているので残ります)。
ファープレーンも切れません。
1×1×1の立方体が、無限に大きいかの様に見えます。
GL_LEQUAL、カリング、描く順番
drawSceneの中のスカイボックスです:
// 空は不透明な物の後に:見えているピクセルだけ塗る(深度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);
}
glDepthFunc(GL_LEQUAL)。 深度バッファは1.0にクリアされ、空の深度は丁度1.0です。既定のGL_LESS(第15章)ではテストはで偽なので、空は描かれずクリアカラーが見えます。「以下」なら何も描かれていない所で通り、全ての物の後ろでは相変わらず通りません。直後にGL_LESSに戻します。- カリング無し。 立方体の中からは面の内側、つまり裏面が見えます(立方体の三角形は外から見て反時計回り)。第16章の背面カリングは其れを全部消してしまいます。カリングを切る(又は表面をカリングする)と直ります。
- 不透明な物の後に描く。 既に物が手前にある所では空の深度テストが失敗し、GPUはフラグメントシェーダーを走らせる前に其のピクセルを捨てられます(アーリー深度テスト)。古いチュートリアルでは深度の書き込みを切って空を最初に描くのが普通でした。其れでも動きますが、画面の全てのピクセルをシェーディングしてから、其の殆どを上から塗り潰す事になります。
- 半透明な物の前に描く。 ブレンドする物は完成した背景の上に描く必要があるので(第16章)、空は2つのグループの間に入ります。此の章に半透明な物はありませんが、第19章も此の順番を守ります。
Kキーはスカイボックスを切り、代わりにクリアカラーを見せます。
GL_LEQUALを忘れた時の見た目も丁度此れです:
映り込みが変わらない事に注目して下さい。
手前の物は自分でキューブマップを読んでいます。
床は空の地平線に届く様に160 mの幅になりました。
カメラの100 m先のファープレーンが遠くで床を切り、其の先は空のもやのかかった灰色の地面が引き継ぎます。
空が全てのピクセルを覆うので、色のクリアはもう全く要りません(課題3)。
18.8 環境マッピング:反射
鏡の方向
完璧な鏡は、各ピクセルで、視線が跳ね返る方向にある物を見せます。
を目から表面の点への単位ベクトル、を其処の単位法線とすると:
線型代数 第4章の反射の式で、GLSLにはreflect(i, n)として組み込まれています。
GLSL 第9章ではフォンのハイライトに使いました。
其処と同じく、1つ目の引数は進む方向、目から表面へ向かう方向です。
簡単な確認:床を45°で見下ろすと、、なので、、で、45°上向きです。
映る物が空の様に遠くにあれば、結果は表面の点の位置ではなくだけで決まります。
でキューブマップを1回読むだけで効果の全てです。
此れを環境マッピングと呼びます。
envmap.frag
手前の物は、既にワールド座標の位置と法線を渡してくれる第10章のphong.vertと、新しいフラグメントシェーダーを使います:
#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);
}
第10章以来のライティングと同じく、全てワールド座標です。
キューブマップの方向はワールドの方向なので(+Yがワールドの上)、iとnもそうでなければなりません。
其の為にphong.vertで法線は法線行列を通り、ビュー座標の法線を此処で使うと映り込みがカメラと一緒に回ってしまいます。
uTintは映り込みに色を付けます。
(0.95, 0.8, 0.55)で木箱は金色に、(0.95, 0.95, 0.97)で球はクロムになります。
金属の映り込みは金属の色に染まります。
第14章のが言っていた事です。
クロムの球と金色の木箱が見せる物
球には全ての方向の法線があるので、クロムの球は環境全体を円盤に縮めて見せます。
上には頭上の雲、真ん中辺りに地平線、下には空の灰色の地面です。
床やジオラマは映りません。
キューブマップには空しか入っていないからで(18.13節で戻ります)、地平線の下の灰色は生成器が「地面」の代わりに置いた物です。
平らな面は違います。
法線は全て同じなので、は面の上でが変わる分しか変わりません。
平らな鏡は環境の小さな一部しか映しません。
止まっている立方体は殆ど一様な6色に見えてしまうので、金色の木箱は回っています:
// 環境マッピングの物 / 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();
}
}
EnvObjectは各物の位置、「いろいろ」の時のモード、色を持っています。
Mは3つ全部のモードを上書きします(envMode - 1)。
木箱は第14章のcrate.glbで、第15章のdrawGeometryで描きます。
此れはuModelとuNormalMatrixだけを設定し(後者はプログラムが使うかをShader::hasで確かめます)、マテリアルは繋ぎません。
envmap.fragにはuMaterialが無く、必要もありません。
木箱の原点は箱の底にあるので、中心の周りで回す為に、回転を2つの平行移動で挟みます。
先ずで中心を原点に動かし、次に回転、そしてへ移動します。
何時も通り右から左へ読みます。
球はmakeSphere(48, 24)を1.5 mに拡大した物です。
18.9 屈折
スネルの法則
ガラスに入る光は遅くなり、向きを変えます。
法線から測った前後の角度はスネルの法則に従います:
とは2つの媒質の屈折率です。
空気は1.0(正確には1.0003)、水は1.33、普通のガラスは約1.52、ダイヤモンドは2.42です。
密な媒質に入ると、光線は法線の方へ曲がります。
屈折ベクトル
角度ではなくベクトルを得る為に、線型代数 第4章の射影と壁ずり移動の節の様に、を法線に沿った部分と面に沿った部分に分けます:
比を使うと、スネルの法則はです。
面に沿った部分は向きを保ち、倍になります。
法線に沿った部分は面の中()を向き、は単位ベクトルなので長さはです:
此処でとを使いました。
2つの部分を足し、の項をまとめると:
此れが、一字一句、GLSLの仕様書によるrefract(I, N, eta)の定義です。
なら解がありません。
光線は密な媒質から出られず、全て反射されます(全反射)。
其の時refractはを返します。
此れはガラスから空気へ、臨界角を超えた時だけ起こります。
空気からガラスへはで、は何時も正です。
reflectと同じく、refractも単位ベクトルを期待します。
計算例
図の光線です:、、。
- なので、
- 、、
長さは1で、からです。
スネルの法則とも合います:。
シェーダーの中で、そして出来ない事
envmap.fragはuIor = 1.52で1.0 / uIorを渡します。
空気からガラスに入るからです。
屈折モード(Mを2回)では、両方の球がレンズの様に見えます。
真ん中からは大体後ろにある物が少し拡大されて見え、縁に向かってどんどん大きく曲がります。
下の縁の近くでは法線が下と手前を向き、屈折した光線は上に曲がるので、球は其処に空を見せます。
上の近くでは地面を見せます。
でも此れは安上がりな技です。
本物のガラス玉は入る時と出る時の2回屈折し、2回目の屈折で光線は又曲がります。
本物のガラス玉が世界を上下逆さまに小さく見せるのは其の為です。
あたし達のは1回屈折し、其の後は光線が永遠に中身の詰まったガラスを進むかの様に環境を読みます。
薄い又は殆ど平らなガラスや水面には、1回の屈折は良い近似ですが、玉では雰囲気だけです。
課題7で2回目の屈折を足します。
そして反射と同じく、キューブマップには空しか無いので、「後ろ」に見えるのは空の地平線と地面で、床や草ではありません。
18.10 フレネル:両方同時に
どれだけ反射するか
本物のガラスは反射か屈折かを選びません。
両方を行い、其の割合は角度で決まります。
湖を真上から覗き込むと底が見え、向こう岸の方へ水面を見渡すと鏡です。
正確な量は光学のフレネルの式から来ますが、グラフィックスでは殆ど何時もSchlickの近似(Christophe Schlick、1994年)を使います:
は視線と法線の間の角度なので、です。
は正面からの反射率で、第14章のマテリアル変換のと同じ物です。
ガラスでは
で約4%です。
第14章の「殆ど全ての非金属は4%近く」は此処から来ています。
水は0.020、ダイヤモンドは0.172です。
| θ | ガラスの | ||
|---|---|---|---|
| 0° | 1.0 | 0 | 0.043 |
| 45° | 0.7071 | 0.0022 | 0.045 |
| 60° | 0.5 | 0.0313 | 0.072 |
| 75° | 0.2588 | 0.2237 | 0.257 |
| 80° | 0.1736 | 0.3853 | 0.411 |
| 89° | 0.0175 | 0.9157 | 0.919 |
5乗の為に、曲線は殆どの範囲で平らで、最後の20度で急に跳ね上がります。
球では其の範囲は輪郭の周りの細い輪で、面があたし達から背を向けて行く所です。
シェーダーの中で
envmap.fragのフレネルの分岐はuIorからを、次にを計算し、混ぜます:
此れがmix(refracted, reflected, fresnel)です。
はpow(r0, 2.0)ではなくr0 * r0で計算します。
r0 = (1 − 1.52) / (1 + 1.52)は負の数で、GLSLではのpow(x, y)は未定義だからです。
其処でNaNを返すGPUもあり、黒や化けたピクセルになります。
max(dot(-i, n), 0.0)は、補間された法線が少し目から背を向ける事がある輪郭で、余弦が負にならない様にします。
既定のモードのガラスの球が此れです。
真ん中からは屈折した空が見え、縁に向かって鏡になり、映った空の明るい輪が出来ます。
其の輪こそがガラスをガラスらしく見せる物です。
屈折だけだと(下の3枚目)、寧ろ水のレンズの様に見えます。
「全部フレネル」では金色の木箱は金色のガラスになります。
面は殆ど透けていて、斜めの角度でだけ映ります。
金属は逆の振る舞いをし、は0.5〜1で色が付いています。
其の為、いろいろモードでは金とクロムに色付きの純粋な反射を使っています。
第24章では全ての面に、色の付いたで同じSchlickの式を使います。
18.11 金属がやっと何かを映す
第14章の問題
第14章ではglTFのPBRマテリアルをBlinn-Phongに変換し、正直な問題で終わりました。
金属には拡散色が無く、金属で見える物は全て反射なのに、あたし達のレンダラーには幾つかの光源以外に映す物が何も無かったのです。
風車の真鍮のハブは、ハイライトが当たらない所では黒でした。
今は環境があるので、phong.fragは空の映り込みを鏡面反射の項に足せます。
此れは予告で、本物のPBRではありません。
第24章でイメージベースドライティングを使ってきちんとやります。
マテリアルとモデル
Materialにはフィールドが2つ増えます:
// 環境(ユニット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
applyは他のメンバーと同じ様に其れを渡します:
shader.set("uMaterial.reflectivity", reflectivity);
shader.set("uMaterial.reflectionBlur", reflectionBlur);
手で作ったマテリアル(床、草)は既定の0のままで、前と全く同じに見えます。
glTFのマテリアルでは、phongFromPbrが最後に設定します:
// 空の映り込み(第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;
反射の強さは、マテリアルの(第14章:金属ならベースカラー、非金属なら0.04)に金属度の2乗を掛けた物です。
真鍮のハブでは、なので、reflectivity = (0.78, 0.6, 0.25)で、金色の映り込みが其のまま全部入ります。
鉄の街灯は(0.12, 0.12, 0.13)で、暗い灰色の映り込みです。
非金属()には何も入りません。
本物の木や漆喰も正面で4%、斜めではもっと沢山反射しますが、フレネルも無く、影も無いぼやけた空の光では、其の4%は粗い面を白っぽく褪せさせるだけでしょう。
2乗は木箱の為です。
木箱の金属度はテクスチャの平均で、(鋼の枠と木を合わせて)、です。
其のまま掛けると木箱全体がを反射し、木の全体に9%の空の色が付きます。
2乗するとで殆ど0になり、の純粋な金属には影響しません。
ピクセル毎の金属度ならきちんと解決します(第14章の課題7と第24章)。
粗い = ぼやける
reflectionBlur = roughnessです。
粗い金属は鮮明な像を映しません。
微小な凹凸が反射した光線を円錐状の方向に散らすので、各ピクセルは其の円錐の中の環境の平均を見ます。
全てのピクセルで平均を計算すると何百回も読む事になりますが、18.5節のミップマップのチェーンには既に段ごとの平均が入っています。
小さい段を読む事が、安上がりなぼかしになるのです。
phong.fragの新しい部分です:
vec3 reflectivity; // 空の映り込みの強さ(0 = なし、第18章) / strength of the sky reflection (0 = none, chapter 18)
float reflectionBlur; // 0 = 鏡、1 = 一番ぼやけたミップマップ / 0 = mirror, 1 = the blurriest mip level
// 環境(空)のキューブマップ。ユニット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)
// 空の映り込み:反射の方向でキューブマップを引く。ぼかしは小さいミップマップを使うだけ(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;
}
textureLod(sampler, P, lod)は、GPUが画面上の微分から段を選ぶ代わりに、指定した段を読みます。小数のlodは(GL_LINEAR_MIPMAP_LINEARで)一番近い2つの段を混ぜます。2Dテクスチャと同じくキューブマップでも使え、此処では方向rで読みます。textureQueryLevels(sampler)(GLSL 4.30)はテクスチャのミップマップの段数を返します。あたし達の空では10です。9段目は1面1×1なので、reflectionBlur = 1は「各面の平均の色」という意味です。reflect(-s.view, s.normal):s.viewは表面から目への向き(第10章)なので、-s.viewがreflectの期待する進む方向です。
真鍮はで段、面が約テクセルになり、柔らかいけれど空と分かる像になります。
の鉄は4.5段目を読みます。
映り込みはspecularに足されるので、表示モード3(Vを3回)でハイライトと一緒に見えます。
正直な注意が2つあります。
ボックスフィルターのミップマップは、粗い面が本当に見る物ではありません。
正しいぼかし(GGX分布で形を決めた「プリフィルター」された環境)は第24章で計算します。
そして面ごとのミップマップこそ、シームレスな補間が効く所です。
テクセルが大きく、GL_TEXTURE_CUBE_MAP_SEAMLESSが無いと、此のぼやけた映り込みに立方体の辺が現れてしまいます。
Material::applyがuMaterial.reflectivityとuMaterial.reflectionBlurも設定する様になったので、其れと一緒に使う全てのシェーダーは、新しい2つのメンバーを含むphong.fragのMaterial構造体を完全に宣言しなければなりません。
欠けていても失敗はしませんが、Shader::setが存在しないユニフォームについて警告します。
18.12 mainでまとめる
読み込み
std::optional<Shader> phong = Shader::load("shaders/phong.vert", "shaders/phong.frag");
std::optional<Shader> post = Shader::load("shaders/post.vert", "shaders/post.frag");
std::optional<Shader> 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<Shader> envmap = Shader::load("shaders/phong.vert", "shaders/envmap.frag");
std::optional<Cubemap> sky = Cubemap::loadDirectory("assets/textures/sky");
std::optional<Texture2D> floorTexture = Texture2D::load("assets/textures/floor.png");
std::optional<Texture2D> grassTexture = Texture2D::load("assets/textures/grass_blades.png");
if (!phong || !post || !skybox || !envmap || !sky || !floorTexture || !grassTexture) return 1;
環境のシェーダーは、既存のphong.vertと新しいenvmap.fragからリンクします。
空のファイルが無かったり壊れていたりすると、他の全てのアセットと同じく、Cubemap::loadのメッセージを出してプログラムが止まります。
1つの空と3つの読み手
// 空はユニット3。phong(金属の映り込み)、envmap、skyboxのどれもここから読む
// The sky is on unit 3: phong (metal reflections), envmap and skybox all read it from there
sky->bind(3);
キューブマップはフレームに1回テクスチャユニット3にバインドされ、3つのプログラムが全部其処から読みます。
金属の為のphong、手前の物の為のenvmap、そして空其の物の為のskyboxです。
ユニット0〜2はマテリアルのマップのままなので(Material::applyが描く度にバインドします)、フレームの途中で空のバインドが外れる事はありません。
シェーダーはlayout(binding = 3)でユニットを固定し、シリーズは此れから此の割り当てを守ります:
| ユニット | 中身 | 何時から |
|---|---|---|
| 0 | 拡散・ベースカラーのマップ | 第6章 |
| 1 | 鏡面反射マップ | 第11章 |
| 2 | 発光マップ | 第11章 |
| 3 | 環境キューブマップ(空) | 第18章 |
| 4以降 | 法線マップ、シャドウマップ、PBRのマップ | 第22〜24章 |
samplerCubeのユニットに2Dテクスチャを、又はsampler2Dのユニットにキューブマップを繋ぐのは定番のエラーです。
1つのユニットで2つのサンプラーの型を使って描くとGL_INVALID_OPERATIONで、正しい型の物が何もバインドされていないユニットは黒を返します。
キューブマップに専用のユニットを使えば、どちらも避けられます。
フレーム
drawSceneの中の順番は次の様になりました:
- シーンのフレームバッファの色、深度、ステンシルをクリア(第17章)。
- 空をユニット3にバインド。
phong:床、ジオラマ、木箱(ModelPass::Opaque)、カリングを切って草。envmap:2つの球と金色の木箱。GL_LEQUALとカリング無しでスカイボックス、其の後GL_LESSに戻す。- 既定のフレームバッファに戻り、第17章のポストプロセスの三角形。
夜
environmentTint = night ? Vec3{0.05f, 0.06f, 0.11f} : Vec3{1.0f, 1.0f, 1.0f};
あたし達の空は昼の空です。
夜(N)はuEnvironmentTintがスカイボックスと全ての映り込みを一緒に暗くし、月明かりに大体合う暗い青にします。
此れは代用品です。
本物のゲームなら、星と月のある夜のキューブマップに差し替えるでしょう(課題6)。
プラットフォームの注意
此の章にはプラットフォームに依る物はありません。
Windows、Linux、FreeBSDのどれでも、空の面は作業ディレクトリからの相対パスassets/textures/sky/から読むので、何時も通りプロジェクトのルートから実行して下さい(Visual Studioは既に其の様に設定されています)。
継ぎ目の無いキューブマップの補間は、OpenGL 4.6が動く全てのドライバーが対応しています。
18.13 限界と、本物のエンジンのやり方
- 静的な環境。 あたし達のキューブマップには空しか入っていません。クロムの球は風車を映さず、ガラスの球は後ろの草を見せません。遠くにある空には其れで良いのですが、近くの物には間違いです。
- リフレクションプローブ。 エンジンはレベルの彼方此方に沢山のキューブマップ(「プローブ」)を置き、其々をレベルのビルド時に自分の位置から1回レンダリングします。各物は一番近いプローブか、幾つかを混ぜた物を使います。屋内では、箱型のプローブの範囲を使って部屋の壁に合わせて反射の方向を補正し(視差補正又はボックス投影のキューブマップ)、床の映り込みが部屋と揃う様にします。
- 動的なキューブマップ。 動く物の映り込みには、毎フレームキューブマップをレンダリングします。物の中心から視野角90°の6つのカメラで、其々フレームバッファを通して1つの面に描きます(
glNamedFramebufferTextureLayerがキューブマップの1つのレイヤーを繋ぎます)。シーンを6回余分に描くので、ゲームは低い解像度を使ったり、1フレームに1〜2面だけ更新したり、遠くの物を省いたりします。課題7で作ります。 - 他の映り込み。 スクリーンスペースリフレクションは完成した画像を使い回し(画面に映っている物しか映せません)、平面反射は1つの平らな面の為にシーンを鏡映しにして描き(第17章のバックミラーの考え方)、ハードウェアのレイトレーシングは反射の光線を本当に追跡します。
- プリフィルターとイラディアンスのマップ。 あたし達のボックスフィルターのミップマップの代わりに、PBRのエンジンは各段をGGX分布でぼかしたキューブマップ(粗さごとに1段)と、空からの拡散光の為の小さな「イラディアンス」キューブマップを予め計算します。其れがイメージベースドライティングで、第24章です。
- HDRの空。 本物の空は浮動小数点の形式(
GL_RGBA16F、又はBC6Hで圧縮)で保存されます。太陽は空より何千倍も明るく、あたし達の8ビットの面では1.0で切れてしまうからです。1枚の正距円筒(緯度・経度)画像として保存し、読み込み時にキューブマップに変換する事もよくあります。HDRは第21章です。 - プロシージャルな空。 多くのゲームは空を毎フレームシェーダーで計算します(時刻に合わせた大気のモデル)。全画面の三角形で描く事が多く、各ピクセルの方向は投影 × 回転の行列の逆行列から求めるので、立方体のジオメトリは全く要りません。
- Vulkan。 キューブマップは6つの配列レイヤーを持つ2Dイメージで、
VK_IMAGE_CREATE_CUBE_COMPATIBLE_BITで作り、VK_IMAGE_VIEW_TYPE_CUBEのビューで見ます。面の順番と面の表はOpenGLと同じで、補間は何時もシームレスです。
18.14 まとめ
- キューブマップは方向で読む6つの正方形の面です。絶対値が一番大きい成分が面を選び、残りの2つを其れで割った物がになります。方向の長さは関係ありません。
- 面の順番は+X、−X、+Y、−Y、+Z、−Z(レイヤー0〜5、
GL_TEXTURE_CUBE_MAP_POSITIVE_X + i)。横の面ではなので0行目が上です。面はファイルに保存された通りにアップロードし、絶対に反転しません。 - 並びはRenderManの左手系の物なので、右手系の世界の内側からは面が鏡映しに見えます。其れが普通です。表が定義なので、面をいじらない事。
- あたし達の空は作り方からして継ぎ目がありません。全てのテクセルの色が方向の連続な関数なので、辺を挟んで隣り合うテクセルは一致します。
Cubemap:glCreateTextures(GL_TEXTURE_CUBE_MAP)、全ての面の為のglTextureStorage2D、zoffset= 面のglTextureSubImage3D、クランプのラップモード、完全なミップマップのチェーン。glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS)で補間が面の辺をまたぎます。小さいミップマップで一番効きます。- スカイボックス:
mat4(mat3(uView))で平行移動を取り除き、.xywwで全ての空のピクセルを深度1にし、GL_LEQUALでクリアした深度に対して通し、カリングを切り、不透明な物の後、半透明な物の前に描きます。 - 環境マッピング:
reflect(i, n)、スネルの法則からのrefract(i, n, 1.0 / ior)、其れを混ぜるSchlickのフレネル。全てワールド座標で。 - 金属は
reflectivity= 金属度² × で空を映し、粗さ × (段数 − 1)のtextureLodでぼかします。環境キューブマップはテクスチャユニット3です。
18.15 課題
- ★
uIorを1.52から1.33(水)と2.42(ダイヤモンド)に変えて下さい。水では球が視界をあまり曲げず、透明な窓に近く見えるはずです。ダイヤモンドでは歪みがずっと強くなり、フレネルモードではが約0.17に上がるので、映る縁が広くなるはずです。 - ★ 空をゆっくり回して下さい。
skybox.vertのvDirectionに、時間と共に増えるY軸周りの回転を掛け(uniform float uSkyAngleで渡します)、envmap.fragとphong.fragの読む方向にも同じ回転を掛けます。雲が空を流れ、球と真鍮のハブの映り込みも一緒に動くはずです。どれか1つのシェーダーを忘れると、空が動いているのに其の映り込みは止まったままです。 - ★ 色のクリアを無くして下さい。スカイボックスが全てのピクセルを覆うので、
glClearには深度とステンシルのビットだけで足ります。絵は全く同じはずです。其の後Kを押して、クリアしない色バッファに何が入っているか見て下さい。 - ★★ 色収差(分散):
envmap.fragで = 1/1.50、1/1.52、1/1.54で3回屈折させ、赤を1回目、緑を2回目、青を3回目の読み出しから取って下さい。ガラスの球の像の中で空と地面が接する所に、細い虹色の縁が出来るはずです。 - ★★ 継ぎ目を見える様にして下さい。
phong.fragで全ての金属の映り込みのlodを一時的にfloat(textureQueryLevels(uEnvironmentMap) - 2)(2×2テクセルの面)にします。真鍮のハブに粗いブロック状の映り込みが見えるはずです。Xを押すと、シームレスな補間がオフの時は映り込みの中の立方体の辺に沿ってくっきりした線が現れ、オンの時はブロックが互いに混ざるはずです。 - ★★ 夜空:同じ「方向から色」の考え方で2つ目の面のセットを書いて下さい(Pythonで、又は18.4節の面の表とstbのライターを使ってC++で、又はFBOで面にレンダリングして)。暗い青のグラデーション、細かい格子に丸めた方向のハッシュが閾値を超える所に星、夜の光の向きの反対に月の円盤。其れを2つ目の
Cubemapとして読み込み、夜はuEnvironmentTintを使う代わりに其れをユニット3にバインドします。金属とクロムの球に星と月が映るはずです。 - ★★★ クロムの球の為の動的な環境マップ:
Cubemap(256, GL_RGBA8, 1)と、256×256の深度レンダーバッファを持つフレームバッファを作ります。各面についてglNamedFramebufferTextureLayer(fbo, GL_COLOR_ATTACHMENT0, cube.id(), 0, face)で繋ぎ、球の中心から、アスペクト比1・90°の透視投影と、面の主軸の方を見るビュー行列でシーンを(球自身は除いて)描きます。「上」のベクトルは面の表から決めます(横の面は−Y、+Yは+Z、−Yは−Z)。最後に、球を描く間其のキューブマップをユニット3にバインドします。球がジオラマ、木箱、他の2つの物を映し、毎フレーム更新されるはずです。上下逆や鏡映しに見える面があれば、其の面の上のベクトルか前の方向が間違っています。
ファイル: a/CMakeLists.txt | b/CMakeLists.txt
| 前 | 新 | ||
|---|---|---|---|
| @@ -41,7 +41,8 @@ add_executable(game | |||
| 41 | src/json.cc | 41 | src/json.cc |
| 42 | src/gltf.cc | 42 | src/gltf.cc |
| 43 | src/model.cc | 43 | src/model.cc |
| 44 | src/framebuffer.cc) | 44 | src/framebuffer.cc |
| 45 | src/cubemap.cc) | ||
| 45 | target_include_directories(game PRIVATE src external/stb external/linalg) | 46 | target_include_directories(game PRIVATE src external/stb external/linalg) |
| 46 | target_link_libraries(game PRIVATE glad stb_image glfw) | 47 | target_link_libraries(game PRIVATE glad stb_image glfw) |
| 47 | 48 | ||
ファイル: a/assets/LICENSE.txt | b/assets/LICENSE.txt
| 前 | 新 | ||
|---|---|---|---|
| @@ -9,6 +9,7 @@ textures/crate_specular.png 木箱の鏡面反射マップ / crate specular map | |||
| 9 | textures/crate_emission.png 木箱の発光マップ / crate emission map | 9 | textures/crate_emission.png 木箱の発光マップ / crate emission map |
| 10 | textures/rug.png 敷物 / a runner rug (chapter 15) | 10 | textures/rug.png 敷物 / a runner rug (chapter 15) |
| 11 | textures/grass_blades.png 草の葉(アルファ付き) / grass blades with alpha (chapter 16) | 11 | textures/grass_blades.png 草の葉(アルファ付き) / grass blades with alpha (chapter 16) |
| 12 | textures/sky/*.png 空のキューブマップの6面 / the six sky cube-map faces (chapter 18) | ||
| 12 | models/window.glb 花箱つきの窓 / a window with a flower box (chapter 16) | 13 | models/window.glb 花箱つきの窓 / a window with a flower box (chapter 16) |
| 13 | models/crate.glb 木箱のモデル / crate model | 14 | models/crate.glb 木箱のモデル / crate model |
| 14 | models/diorama.glb 小さな場面 / a small diorama scene | 15 | models/diorama.glb 小さな場面 / a small diorama scene |
ファイル: /dev/null | b/assets/textures/sky/nx.png
新しいファイル:100644 / バイナリファイル
ファイル: /dev/null | b/assets/textures/sky/ny.png
新しいファイル:100644 / バイナリファイル
ファイル: /dev/null | b/assets/textures/sky/nz.png
新しいファイル:100644 / バイナリファイル
ファイル: /dev/null | b/assets/textures/sky/px.png
新しいファイル:100644 / バイナリファイル
ファイル: /dev/null | b/assets/textures/sky/py.png
新しいファイル:100644 / バイナリファイル
ファイル: /dev/null | b/assets/textures/sky/pz.png
新しいファイル:100644 / バイナリファイル
ファイル: /dev/null | b/shaders/envmap.frag
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,38 @@ | |||
| 1 | #version 460 core | ||
| 2 | // 環境マッピング:キューブマップに映った空を反射・屈折で見せる(頂点シェーダーはphong.vert) | ||
| 3 | // Environment mapping: show the sky in a cube map by reflection or refraction (vertex shader: phong.vert) | ||
| 4 | in vec3 vWorldPos; | ||
| 5 | in vec3 vNormal; | ||
| 6 | |||
| 7 | layout(binding = 3) uniform samplerCube uEnvironment; | ||
| 8 | |||
| 9 | uniform vec3 uViewPos; | ||
| 10 | uniform int uEnvMode; // 0 = 反射 / reflection, 1 = 屈折 / refraction, 2 = フレネル(ガラス) / Fresnel (glass) | ||
| 11 | uniform float uIor; // 屈折率(ガラス1.52、水1.33) / index of refraction (glass 1.52, water 1.33) | ||
| 12 | uniform vec3 uTint; // 反射・屈折の色 / colour of the reflection / refraction | ||
| 13 | uniform vec3 uEnvironmentTint; // 空の明るさ(昼1、夜は暗く) / brightness of the sky (1 by day, dark at night) | ||
| 14 | |||
| 15 | layout(location = 0) out vec4 out_color; | ||
| 16 | |||
| 17 | void main() { | ||
| 18 | vec3 i = normalize(vWorldPos - uViewPos); // 目から表面へ / from the eye to the surface | ||
| 19 | vec3 n = normalize(vNormal); | ||
| 20 | // reflect(i, n) = i - 2 dot(n, i) n:入射と同じ角度で跳ね返る / bounces off at the same angle | ||
| 21 | vec3 reflected = texture(uEnvironment, reflect(i, n)).rgb; | ||
| 22 | // refract(i, n, η):η = 入る前 ÷ 入った後の屈折率(空気1.0 → ガラス) / η = ratio of indices (air 1.0 → glass) | ||
| 23 | vec3 refracted = texture(uEnvironment, refract(i, n, 1.0 / uIor)).rgb; | ||
| 24 | |||
| 25 | vec3 color = reflected; | ||
| 26 | if (uEnvMode == 1) { | ||
| 27 | color = refracted; | ||
| 28 | } else if (uEnvMode == 2) { | ||
| 29 | // フレネル(Schlickの近似):正面からはほとんど透け、斜めからはほとんど映る | ||
| 30 | // Fresnel (Schlick's approximation): mostly see-through head-on, mostly mirror at grazing angles | ||
| 31 | // 負の数のpowはGLSLでは未定義なので、二乗は掛け算で / pow of a negative base is undefined in GLSL: square by multiplying | ||
| 32 | float r0 = (1.0 - uIor) / (1.0 + uIor); | ||
| 33 | float f0 = r0 * r0; // ガラスで約0.04 / about 0.04 for glass | ||
| 34 | float fresnel = f0 + (1.0 - f0) * pow(1.0 - max(dot(-i, n), 0.0), 5.0); | ||
| 35 | color = mix(refracted, reflected, fresnel); | ||
| 36 | } | ||
| 37 | out_color = vec4(color * uTint * uEnvironmentTint, 1.0); | ||
| 38 | } | ||
ファイル: a/shaders/phong.frag | b/shaders/phong.frag
| 前 | 新 | ||
|---|---|---|---|
| @@ -13,12 +13,17 @@ struct Material { | |||
| 13 | int alphaMode; // 0 = 不透明 / opaque, 1 = マスク / mask (discard), 2 = ブレンド / blend | 13 | int alphaMode; // 0 = 不透明 / opaque, 1 = マスク / mask (discard), 2 = ブレンド / blend |
| 14 | float alphaCutoff; // マスクのしきい値 / the mask threshold | 14 | float alphaCutoff; // マスクのしきい値 / the mask threshold |
| 15 | bool doubleSided; // 裏面では法線を反転する / flip the normal on back faces | 15 | bool doubleSided; // 裏面では法線を反転する / flip the normal on back faces |
| 16 | vec3 reflectivity; // 空の映り込みの強さ(0 = なし、第18章) / strength of the sky reflection (0 = none, chapter 18) | ||
| 17 | float reflectionBlur; // 0 = 鏡、1 = 一番ぼやけたミップマップ / 0 = mirror, 1 = the blurriest mip level | ||
| 16 | }; | 18 | }; |
| 17 | uniform Material uMaterial; | 19 | uniform Material uMaterial; |
| 18 | 20 | ||
| 19 | layout(binding = 0) uniform sampler2D uDiffuseMap; | 21 | layout(binding = 0) uniform sampler2D uDiffuseMap; |
| 20 | layout(binding = 1) uniform sampler2D uSpecularMap; | 22 | layout(binding = 1) uniform sampler2D uSpecularMap; |
| 21 | layout(binding = 2) uniform sampler2D uEmissionMap; | 23 | layout(binding = 2) uniform sampler2D uEmissionMap; |
| 24 | // 環境(空)のキューブマップ。ユニット3(第18章) / the environment (sky) cube map, unit 3 (chapter 18) | ||
| 25 | layout(binding = 3) uniform samplerCube uEnvironmentMap; | ||
| 26 | uniform vec3 uEnvironmentTint; // 空の明るさ(昼1、夜は暗く) / brightness of the sky (1 by day, dark at night) | ||
| 22 | 27 | ||
| 23 | // 平行光源:向きだけ / directional light: a direction only | 28 | // 平行光源:向きだけ / directional light: a direction only |
| 24 | struct DirectionalLight { | 29 | struct DirectionalLight { |
| @@ -137,6 +142,14 @@ void main() { | |||
| 137 | addLight(s, l, uSpotLights[i].color * attenuate(d, uSpotLights[i].attenuation) * cone, diffuse, specular); | 142 | addLight(s, l, uSpotLights[i].color * attenuate(d, uSpotLights[i].attenuation) * cone, diffuse, specular); |
| 138 | } | 143 | } |
| 139 | 144 | ||
| 145 | // 空の映り込み:反射の方向でキューブマップを引く。ぼかしは小さいミップマップを使うだけ(textureLod) | ||
| 146 | // Sky reflection: look up the cube map in the reflected direction. Blur just means a smaller mip level (textureLod) | ||
| 147 | if (uMaterial.reflectivity != vec3(0.0)) { | ||
| 148 | vec3 r = reflect(-s.view, s.normal); | ||
| 149 | float lod = uMaterial.reflectionBlur * float(textureQueryLevels(uEnvironmentMap) - 1); | ||
| 150 | specular += uMaterial.reflectivity * uEnvironmentTint * textureLod(uEnvironmentMap, r, lod).rgb; | ||
| 151 | } | ||
| 152 | |||
| 140 | vec3 ambient = uAmbient * s.diffuse; | 153 | vec3 ambient = uAmbient * s.diffuse; |
| 141 | vec3 color = ambient + diffuse + specular + emission; | 154 | vec3 color = ambient + diffuse + specular + emission; |
| 142 | if (uViewMode == 1) color = ambient; | 155 | if (uViewMode == 1) color = ambient; |
ファイル: /dev/null | b/shaders/skybox.frag
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,15 @@ | |||
| 1 | #version 460 core | ||
| 2 | in vec3 vDirection; | ||
| 3 | |||
| 4 | // 環境のキューブマップはユニット3(0〜2はマテリアルのマップ) / the environment cube map is on unit 3 | ||
| 5 | // (0..2 are the material maps) | ||
| 6 | layout(binding = 3) uniform samplerCube uSkybox; | ||
| 7 | |||
| 8 | uniform vec3 uEnvironmentTint; // 空の明るさ(昼1、夜は暗く) / brightness of the sky (1 by day, dark at night) | ||
| 9 | |||
| 10 | layout(location = 0) out vec4 out_color; | ||
| 11 | |||
| 12 | void main() { | ||
| 13 | // 方向は正規化しなくて良い:一番大きい成分で面が決まる / no need to normalize: the largest component picks the face | ||
| 14 | out_color = vec4(uEnvironmentTint * texture(uSkybox, vDirection).rgb, 1.0); | ||
| 15 | } | ||
ファイル: /dev/null | b/shaders/skybox.vert
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,19 @@ | |||
| 1 | #version 460 core | ||
| 2 | // 空の箱:カメラの周りの立方体の内側に、キューブマップを方向で貼る | ||
| 3 | // The sky box: a cube around the camera, textured from the inside by direction | ||
| 4 | layout(location = 0) in vec3 aPosition; // makeCube()の頂点(±0.5) / makeCube()'s vertices (±0.5) | ||
| 5 | |||
| 6 | uniform mat4 uView; | ||
| 7 | uniform mat4 uProj; | ||
| 8 | |||
| 9 | out vec3 vDirection; // キューブマップを引く方向 / the direction to look up the cube map with | ||
| 10 | |||
| 11 | void main() { | ||
| 12 | vDirection = aPosition; | ||
| 13 | // mat3にして戻すと平行移動が消える:空はカメラと一緒に動き、遠くにあるように見える | ||
| 14 | // Going through mat3 drops the translation: the sky moves with the camera and looks infinitely far away | ||
| 15 | vec4 clip = uProj * mat4(mat3(uView)) * vec4(aPosition, 1.0); | ||
| 16 | // z = wにすると、透視除算の後の深度がちょうど1(一番奥)になる / z = w makes the depth exactly 1 (the far end) | ||
| 17 | // after the perspective divide | ||
| 18 | gl_Position = clip.xyww; | ||
| 19 | } | ||
ファイル: /dev/null | b/src/cubemap.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,82 @@ | |||
| 1 | #include "cubemap.hh" | ||
| 2 | |||
| 3 | #include <stb_image.h> | ||
| 4 | |||
| 5 | #include <cstdio> | ||
| 6 | #include <utility> | ||
| 7 | |||
| 8 | Cubemap::Cubemap(int size, GLenum internalFormat, int levels) : faceSize(size), mipLevels(levels) { | ||
| 9 | glCreateTextures(GL_TEXTURE_CUBE_MAP, 1, &handle); | ||
| 10 | // 6面ぶんのストレージを一度に(glTextureStorage2Dで良い:キューブマップは2Dの面の集まり) | ||
| 11 | // Storage for all six faces at once (glTextureStorage2D: a cube map is a set of 2D faces) | ||
| 12 | glTextureStorage2D(handle, levels, internalFormat, size, size); | ||
| 13 | // 方向で引くので、面の端の外を読まないように3方向ともCLAMP_TO_EDGE | ||
| 14 | // Looked up by direction: CLAMP_TO_EDGE in all three directions so nothing is read past a face's edge | ||
| 15 | glTextureParameteri(handle, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); | ||
| 16 | glTextureParameteri(handle, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); | ||
| 17 | glTextureParameteri(handle, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); | ||
| 18 | glTextureParameteri(handle, GL_TEXTURE_MIN_FILTER, levels > 1 ? GL_LINEAR_MIPMAP_LINEAR : GL_LINEAR); | ||
| 19 | glTextureParameteri(handle, GL_TEXTURE_MAG_FILTER, GL_LINEAR); | ||
| 20 | } | ||
| 21 | |||
| 22 | void Cubemap::uploadFace(int face, const unsigned char *rgba) { | ||
| 23 | glPixelStorei(GL_UNPACK_ALIGNMENT, 1); | ||
| 24 | // DSAでは面を3次元目(zoffset)で選ぶ:zoffset = face、depth = 1 | ||
| 25 | // With DSA the face is chosen with the third coordinate: zoffset = face, depth = 1 | ||
| 26 | glTextureSubImage3D(handle, 0, 0, 0, face, faceSize, faceSize, 1, GL_RGBA, GL_UNSIGNED_BYTE, rgba); | ||
| 27 | glPixelStorei(GL_UNPACK_ALIGNMENT, 4); | ||
| 28 | } | ||
| 29 | |||
| 30 | std::optional<Cubemap> Cubemap::load(const std::array<std::string, 6> &paths) { | ||
| 31 | // キューブマップの面は上の行から(RenderManの決まり)。反転しない | ||
| 32 | // Cube-map faces start at the top row (the RenderMan convention). Do not flip | ||
| 33 | stbi_set_flip_vertically_on_load(0); | ||
| 34 | Cubemap cube; | ||
| 35 | for (int face = 0; face < 6; ++face) { | ||
| 36 | const std::string &path = paths[static_cast<size_t>(face)]; | ||
| 37 | int width = 0, height = 0, channels = 0; | ||
| 38 | unsigned char *pixels = stbi_load(path.c_str(), &width, &height, &channels, 4); | ||
| 39 | if (!pixels) { | ||
| 40 | fprintf(stderr, "%s: 画像を読めない / cannot load image: %s\n", path.c_str(), stbi_failure_reason()); | ||
| 41 | return std::nullopt; | ||
| 42 | } | ||
| 43 | if (width != height || (face > 0 && width != cube.faceSize)) { | ||
| 44 | fprintf(stderr, "%s: 面は全部同じ大きさの正方形であること / all faces must be squares of the same size (%d × %d)\n", | ||
| 45 | path.c_str(), width, height); | ||
| 46 | stbi_image_free(pixels); | ||
| 47 | return std::nullopt; | ||
| 48 | } | ||
| 49 | if (face == 0) { | ||
| 50 | int levels = 1; | ||
| 51 | while ((width >> levels) > 0) ++levels; | ||
| 52 | cube = Cubemap(width, GL_RGBA8, levels); | ||
| 53 | } | ||
| 54 | cube.uploadFace(face, pixels); | ||
| 55 | stbi_image_free(pixels); | ||
| 56 | } | ||
| 57 | glGenerateTextureMipmap(cube.handle); | ||
| 58 | return cube; | ||
| 59 | } | ||
| 60 | |||
| 61 | std::optional<Cubemap> Cubemap::loadDirectory(const std::string &dir, const std::string &extension) { | ||
| 62 | std::array<std::string, 6> paths; | ||
| 63 | for (int i = 0; i < 6; ++i) paths[static_cast<size_t>(i)] = dir + "/" + kCubeFaceNames[i] + extension; | ||
| 64 | return load(paths); | ||
| 65 | } | ||
| 66 | |||
| 67 | Cubemap::~Cubemap() { | ||
| 68 | if (handle) glDeleteTextures(1, &handle); | ||
| 69 | } | ||
| 70 | |||
| 71 | Cubemap::Cubemap(Cubemap &&other) noexcept | ||
| 72 | : handle(std::exchange(other.handle, 0)), faceSize(other.faceSize), mipLevels(other.mipLevels) {} | ||
| 73 | |||
| 74 | Cubemap &Cubemap::operator=(Cubemap &&other) noexcept { | ||
| 75 | if (this != &other) { | ||
| 76 | if (handle) glDeleteTextures(1, &handle); | ||
| 77 | handle = std::exchange(other.handle, 0); | ||
| 78 | faceSize = other.faceSize; | ||
| 79 | mipLevels = other.mipLevels; | ||
| 80 | } | ||
| 81 | return *this; | ||
| 82 | } | ||
ファイル: /dev/null | b/src/cubemap.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,49 @@ | |||
| 1 | // キューブマップ:6枚の正方形の画像で、方向から色を引くテクスチャ(空、反射) | ||
| 2 | // Cubemaps: a texture made of six square images that is looked up by direction (skies, reflections) | ||
| 3 | #pragma once | ||
| 4 | |||
| 5 | #include <glad/glad.h> | ||
| 6 | |||
| 7 | #include <array> | ||
| 8 | #include <optional> | ||
| 9 | #include <string> | ||
| 10 | |||
| 11 | // 面の順番はOpenGLと同じ:+X, -X, +Y, -Y, +Z, -Z(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i) | ||
| 12 | // The face order is OpenGL's: +X, -X, +Y, -Y, +Z, -Z (GL_TEXTURE_CUBE_MAP_POSITIVE_X + i) | ||
| 13 | constexpr const char *kCubeFaceNames[6] = {"px", "nx", "py", "ny", "pz", "nz"}; | ||
| 14 | |||
| 15 | // キューブマップテクスチャ(RAII、コピー不可・移動可)。DSAで作る。 | ||
| 16 | // A cube-map texture (RAII, non-copyable, movable), created with DSA. | ||
| 17 | class Cubemap { | ||
| 18 | public: | ||
| 19 | Cubemap() = default; | ||
| 20 | // 中身のないストレージを作る(size × size の面が6枚) / allocates empty storage (six size × size faces) | ||
| 21 | Cubemap(int size, GLenum internalFormat, int levels = 1); | ||
| 22 | ~Cubemap(); | ||
| 23 | Cubemap(const Cubemap &) = delete; | ||
| 24 | Cubemap &operator=(const Cubemap &) = delete; | ||
| 25 | Cubemap(Cubemap &&other) noexcept; | ||
| 26 | Cubemap &operator=(Cubemap &&other) noexcept; | ||
| 27 | |||
| 28 | // 6枚の画像ファイルから読む(順番は+X, -X, +Y, -Y, +Z, -Z)。上下反転はしない:キューブマップの面は上の行から。 | ||
| 29 | // 全部同じ大きさの正方形であること。ミップマップを作る(ぼやけた反射用)。失敗したらエラーを表示してstd::nullopt。 | ||
| 30 | // Loads six image files (order +X, -X, +Y, -Y, +Z, -Z). No vertical flip: cube-map faces start at the top row. | ||
| 31 | // All must be squares of the same size. Builds mipmaps (for blurry reflections). On failure prints the error | ||
| 32 | // and returns std::nullopt. | ||
| 33 | static std::optional<Cubemap> load(const std::array<std::string, 6> &paths); | ||
| 34 | // dir/px.png, dir/nx.png … を読む / loads dir/px.png, dir/nx.png, ... | ||
| 35 | static std::optional<Cubemap> loadDirectory(const std::string &dir, const std::string &extension = ".png"); | ||
| 36 | |||
| 37 | // 面face(0〜5)のミップマップ0段目を書き換える(RGBA8) / replaces mip level 0 of face `face` (0..5, RGBA8) | ||
| 38 | void uploadFace(int face, const unsigned char *rgba); | ||
| 39 | |||
| 40 | void bind(GLuint unit) const { glBindTextureUnit(unit, handle); } | ||
| 41 | GLuint id() const { return handle; } | ||
| 42 | int size() const { return faceSize; } | ||
| 43 | int levels() const { return mipLevels; } | ||
| 44 | |||
| 45 | private: | ||
| 46 | GLuint handle = 0; | ||
| 47 | int faceSize = 0; | ||
| 48 | int mipLevels = 0; | ||
| 49 | }; | ||
ファイル: a/src/main.cc | b/src/main.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -1,5 +1,5 @@ | |||
| 1 | // 第17章:フレームバッファとポストプロセス | 1 | // 第18章:キューブマップ |
| 2 | // Chapter 17: framebuffers and post-processing | 2 | // Chapter 18: cubemaps |
| 3 | // | 3 | // |
| 4 | // 操作 / Controls: | 4 | // 操作 / Controls: |
| 5 | // WASD 前後左右に移動 / move forward, back, left, right | 5 | // WASD 前後左右に移動 / move forward, back, left, right |
| @@ -7,19 +7,23 @@ | |||
| 7 | // Shift 速く動く / move faster | 7 | // Shift 速く動く / move faster |
| 8 | // マウス / mouse 向きを変える(FPS)、左ドラッグで回る(オービット) / look around (FPS), drag with the left button to orbit | 8 | // マウス / mouse 向きを変える(FPS)、左ドラッグで回る(オービット) / look around (FPS), drag with the left button to orbit |
| 9 | // ホイール / wheel ズーム / zoom | 9 | // ホイール / wheel ズーム / zoom |
| 10 | // M 手前の3つ:いろいろ → 全部反射 → 全部屈折 → 全部フレネル | ||
| 11 | // the three objects in front: mixed → all reflection → all refraction → all Fresnel | ||
| 12 | // K 空(スカイボックス)のオン・オフ / sky box on / off | ||
| 13 | // X 継ぎ目のないキューブマップの補間(GL_TEXTURE_CUBE_MAP_SEAMLESS)のオン・オフ | ||
| 14 | // seamless cube-map filtering (GL_TEXTURE_CUBE_MAP_SEAMLESS) on / off | ||
| 10 | // 1〜6 効果:なし / 反転 / グレースケール / シャープ / ぼかし / エッジ検出 | 15 | // 1〜6 効果:なし / 反転 / グレースケール / シャープ / ぼかし / エッジ検出 |
| 11 | // effect: none / invert / grayscale / sharpen / blur / edge detection | 16 | // effect: none / invert / grayscale / sharpen / blur / edge detection |
| 12 | // M バックミラーのオン・オフ / rear-view mirror on / off | ||
| 13 | // L 低解像度(1/4、GL_NEAREST)⇔ 普通 / low resolution (1/4, GL_NEAREST) ⇔ normal | ||
| 14 | // C FPS ⇔ オービットカメラ / FPS ⇔ orbit camera | 17 | // C FPS ⇔ オービットカメラ / FPS ⇔ orbit camera |
| 15 | // V 表示:全部 → 環境光 → 拡散 → 鏡面 → 発光 → 法線 / view: all → ambient → diffuse → specular → emission → normals | 18 | // V 表示:全部 → 環境光 → 拡散 → 鏡面 → 発光 → 法線 / view: all → ambient → diffuse → specular → emission → normals |
| 16 | // N 昼 ⇔ 夜 / day ⇔ night | 19 | // N 昼 ⇔ 夜 / day ⇔ night |
| 17 | // F 懐中電灯のオン・オフ / flashlight on / off | 20 | // F 懐中電灯のオン・オフ / flashlight on / off |
| 18 | // P 風車を止める・回す / pause / resume the windmill | 21 | // P 風車と金色の木箱を止める・回す / pause / resume the windmill and the golden crate |
| 19 | // Tab カーソルのキャプチャ切り替え / toggle cursor capture | 22 | // Tab カーソルのキャプチャ切り替え / toggle cursor capture |
| 20 | // R シェーダーを読み直す / reload the shaders | 23 | // R シェーダーを読み直す / reload the shaders |
| 21 | // Esc 終了 / quit | 24 | // Esc 終了 / quit |
| 22 | #include "camera.hh" | 25 | #include "camera.hh" |
| 26 | #include "cubemap.hh" | ||
| 23 | #include "framebuffer.hh" | 27 | #include "framebuffer.hh" |
| 24 | #include "lights.hh" | 28 | #include "lights.hh" |
| 25 | #include "material.hh" | 29 | #include "material.hh" |
| @@ -44,20 +48,28 @@ struct Placement { | |||
| 44 | float angle; | 48 | float angle; |
| 45 | }; | 49 | }; |
| 46 | 50 | ||
| 47 | // 最後の3つはカメラの後ろ(バックミラーに映る) / the last three are behind the camera (seen in the rear-view mirror) | ||
| 48 | static const Placement kCrates[] = { | 51 | static const Placement kCrates[] = { |
| 49 | {{5.5f, 0.0f, 1.5f}, 0.4f}, {{6.3f, 0.0f, 2.6f}, -0.3f}, {{5.9f, 1.0f, 2.0f}, 0.1f}, | 52 | {{5.5f, 0.0f, 1.5f}, 0.4f}, {{6.3f, 0.0f, 2.6f}, -0.3f}, {{5.9f, 1.0f, 2.0f}, 0.1f}, |
| 50 | {{-6.0f, 0.0f, -1.0f}, 0.8f}, {{-5.2f, 0.0f, 3.5f}, -0.6f}, {{-1.6f, 0.0f, 17.0f}, 0.3f}, | 53 | {{-6.0f, 0.0f, -1.0f}, 0.8f}, {{-5.2f, 0.0f, 3.5f}, -0.6f}, |
| 51 | {{-0.5f, 0.0f, 17.6f}, -0.2f}, {{-1.1f, 1.0f, 17.3f}, 0.6f}, | ||
| 52 | }; | 54 | }; |
| 53 | 55 | ||
| 54 | static const Placement kWindows[] = { | 56 | // 手前の環境マッピングの物:球二つと、木箱のモデル / the environment-mapped objects in front: two spheres and the |
| 55 | {{-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}, | 57 | // crate model |
| 56 | {{1.8f, 0.0f, 16.4f}, 2.9f}, // カメラの後ろ / behind the camera | 58 | enum EnvMode { kReflect = 0, kRefract = 1, kFresnel = 2 }; |
| 59 | struct EnvObject { | ||
| 60 | Vec3 position; | ||
| 61 | int mode; // 「いろいろ」のときのモード / the mode in "mixed" | ||
| 62 | Vec3 tint; // 反射の色(金属の色) / reflection colour (the metal's colour) | ||
| 63 | }; | ||
| 64 | static const EnvObject kEnvObjects[] = { | ||
| 65 | {{-2.8f, 0.75f, 7.0f}, kFresnel, {1.0f, 1.0f, 1.0f}}, // ガラスの球 / glass sphere | ||
| 66 | {{0.0f, 1.0f, 7.6f}, kReflect, {0.95f, 0.8f, 0.55f}}, // 金色の木箱(宙に浮いて回る) / a golden crate (hovers, tumbling) | ||
| 67 | {{2.8f, 0.75f, 7.0f}, kReflect, {0.95f, 0.95f, 0.97f}}, // クロムの球 / chrome sphere | ||
| 57 | }; | 68 | }; |
| 58 | 69 | ||
| 59 | static const char *const kViewModeNames[] = {"all", "ambient", "diffuse", "specular", "emission", "normals"}; | 70 | static const char *const kViewModeNames[] = {"all", "ambient", "diffuse", "specular", "emission", "normals"}; |
| 60 | static const char *const kEffectNames[] = {"none", "invert", "grayscale", "sharpen", "blur", "edge detection"}; | 71 | static const char *const kEffectNames[] = {"none", "invert", "grayscale", "sharpen", "blur", "edge detection"}; |
| 72 | static const char *const kEnvModeNames[] = {"mixed", "all reflection", "all refraction", "all Fresnel"}; | ||
| 61 | 73 | ||
| 62 | static float random01(std::uint32_t &state) { | 74 | static float random01(std::uint32_t &state) { |
| 63 | state = state * 1664525u + 1013904223u; | 75 | state = state * 1664525u + 1013904223u; |
| @@ -75,9 +87,8 @@ static std::vector<Placement> makeGrass() { | |||
| 75 | for (Vec3 q : avoid) ok = ok && length(Vec3{p.x - q.x, 0, p.z - q.z}) > 1.1f; | 87 | for (Vec3 q : avoid) ok = ok && length(Vec3{p.x - q.x, 0, p.z - q.z}) > 1.1f; |
| 76 | if (ok) grass.push_back({p, 2.0f * PI * random01(seed)}); | 88 | if (ok) grass.push_back({p, 2.0f * PI * random01(seed)}); |
| 77 | } | 89 | } |
| 78 | const Placement front[] = {{{1.5f, 0, 6.2f}, 0.3f}, {{-2.9f, 0, 7.0f}, 1.2f}, {{3.6f, 0, 5.4f}, 2.0f}, | 90 | const Placement front[] = {{{1.5f, 0, 6.2f}, 0.3f}, {{-4.0f, 0, 7.6f}, 1.2f}, {{3.9f, 0, 5.4f}, 2.0f}, |
| 79 | {{1.2f, 0, 8.9f}, 0.7f}, {{-2.6f, 0, 9.6f}, 2.6f}, {{0.6f, 0, 10.7f}, 0.5f}, | 91 | {{1.4f, 0, 8.9f}, 0.7f}, {{-1.6f, 0, 8.6f}, 2.6f}}; |
| 80 | {{0.4f, 0, 16.6f}, 1.0f}, {{-2.4f, 0, 16.2f}, 2.2f}}; | ||
| 81 | for (const Placement &p : front) grass.push_back(p); | 92 | for (const Placement &p : front) grass.push_back(p); |
| 82 | return grass; | 93 | return grass; |
| 83 | } | 94 | } |
| @@ -90,19 +101,23 @@ struct View { | |||
| 90 | 101 | ||
| 91 | int main() { | 102 | int main() { |
| 92 | Window window; | 103 | Window window; |
| 93 | if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 17")) return 1; | 104 | if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 18")) return 1; |
| 94 | 105 | ||
| 95 | std::optional<Shader> phong = Shader::load("shaders/phong.vert", "shaders/phong.frag"); | 106 | std::optional<Shader> phong = Shader::load("shaders/phong.vert", "shaders/phong.frag"); |
| 96 | std::optional<Shader> post = Shader::load("shaders/post.vert", "shaders/post.frag"); | 107 | std::optional<Shader> post = Shader::load("shaders/post.vert", "shaders/post.frag"); |
| 108 | std::optional<Shader> skybox = Shader::load("shaders/skybox.vert", "shaders/skybox.frag"); | ||
| 109 | // 環境マッピング:頂点シェーダーはphongと同じ(ワールド座標の位置と法線) / environment mapping: the same vertex | ||
| 110 | // shader as phong (world-space position and normal) | ||
| 111 | std::optional<Shader> envmap = Shader::load("shaders/phong.vert", "shaders/envmap.frag"); | ||
| 112 | std::optional<Cubemap> sky = Cubemap::loadDirectory("assets/textures/sky"); | ||
| 97 | std::optional<Texture2D> floorTexture = Texture2D::load("assets/textures/floor.png"); | 113 | std::optional<Texture2D> floorTexture = Texture2D::load("assets/textures/floor.png"); |
| 98 | std::optional<Texture2D> grassTexture = Texture2D::load("assets/textures/grass_blades.png"); | 114 | std::optional<Texture2D> grassTexture = Texture2D::load("assets/textures/grass_blades.png"); |
| 99 | if (!phong || !post || !floorTexture || !grassTexture) return 1; | 115 | if (!phong || !post || !skybox || !envmap || !sky || !floorTexture || !grassTexture) return 1; |
| 100 | grassTexture->setWrap(GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE); | 116 | grassTexture->setWrap(GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE); |
| 101 | 117 | ||
| 102 | std::optional<Model> scene = Model::load("assets/models/diorama.glb"); | 118 | std::optional<Model> scene = Model::load("assets/models/diorama.glb"); |
| 103 | std::optional<Model> crate = Model::load("assets/models/crate.glb"); | 119 | std::optional<Model> crate = Model::load("assets/models/crate.glb"); |
| 104 | std::optional<Model> windowModel = Model::load("assets/models/window.glb"); | 120 | if (!scene || !crate) return 1; |
| 105 | if (!scene || !crate || !windowModel) return 1; | ||
| 106 | 121 | ||
| 107 | const unsigned char whitePixel[4] = {255, 255, 255, 255}; | 122 | const unsigned char whitePixel[4] = {255, 255, 255, 255}; |
| 108 | Texture2D white = Texture2D::fromPixels(whitePixel, 1, 1, {.flipY = false, .mipmaps = false}); | 123 | Texture2D white = Texture2D::fromPixels(whitePixel, 1, 1, {.flipY = false, .mipmaps = false}); |
| @@ -112,8 +127,8 @@ int main() { | |||
| 112 | Quat rotorStart = rotor >= 0 ? scene->nodes[static_cast<size_t>(rotor)].rotation : Quat{}; | 127 | Quat rotorStart = rotor >= 0 ? scene->nodes[static_cast<size_t>(rotor)].rotation : Quat{}; |
| 113 | 128 | ||
| 114 | Camera fps; | 129 | Camera fps; |
| 115 | fps.position = {0.0f, 2.1f, 13.0f}; | 130 | fps.position = {0.0f, 2.0f, 12.5f}; |
| 116 | fps.pitch = radians(-9.0f); | 131 | fps.pitch = radians(-6.0f); |
| 117 | 132 | ||
| 118 | OrbitCamera orbit; | 133 | OrbitCamera orbit; |
| 119 | orbit.target = {0.0f, 1.0f, 4.0f}; | 134 | orbit.target = {0.0f, 1.0f, 4.0f}; |
| @@ -121,32 +136,25 @@ int main() { | |||
| 121 | orbit.yaw = radians(20.0f); | 136 | orbit.yaw = radians(20.0f); |
| 122 | 137 | ||
| 123 | bool useOrbit = false; | 138 | bool useOrbit = false; |
| 124 | int viewMode = 0, effect = 0; | 139 | int viewMode = 0, effect = 0, envMode = 0; |
| 125 | bool night = false, flashlightOn = false, windmillMoving = true, mirrorOn = true, lowRes = false; | 140 | bool night = false, flashlightOn = false, windmillMoving = true, skyOn = true, seamless = true; |
| 126 | float windmillTime = 0.0f; | 141 | float windmillTime = 0.0f; |
| 127 | window.setCursorCaptured(true); | 142 | window.setCursorCaptured(true); |
| 128 | 143 | ||
| 129 | // 場面を描くフレームバッファ(ウィンドウと同じ大きさ、低解像度なら1/4)とバックミラー用 | 144 | // 場面を描くフレームバッファ(ウィンドウと同じ大きさ) / the framebuffer the scene is drawn into (window size) |
| 130 | // The framebuffer the scene is drawn into (window size, or 1/4 in low-resolution mode) and one for the mirror | 145 | Framebuffer sceneFbo(window.width(), window.height()); |
| 131 | auto sceneSize = [&](int size) { return std::max(1, lowRes ? size / 4 : size); }; | 146 | if (!sceneFbo.complete()) return 1; |
| 132 | Framebuffer sceneFbo(sceneSize(window.width()), sceneSize(window.height())); | 147 | window.onResize = [&](int width, int height) { sceneFbo.resize(width, height); }; |
| 133 | const int mirrorWidth = 480, mirrorHeight = 150; | 148 | |
| 134 | Framebuffer mirrorFbo(mirrorWidth, mirrorHeight); | 149 | // キューブマップの面の境目でも隣の面と補間する(GL 3.2から、全体の設定) / filter across the edges between |
| 135 | if (!sceneFbo.complete() || !mirrorFbo.complete()) return 1; | 150 | // cube-map faces too (since GL 3.2, a global switch) |
| 136 | 151 | glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS); | |
| 137 | // 低解像度ではGL_NEARESTで拡大:ピクセルがはっきり見える / low resolution is magnified with GL_NEAREST: crisp pixels | ||
| 138 | auto resizeScene = [&] { | ||
| 139 | sceneFbo.resize(sceneSize(window.width()), sceneSize(window.height())); | ||
| 140 | GLenum filter = lowRes ? GL_NEAREST : GL_LINEAR; | ||
| 141 | sceneFbo.color().setFilter(filter, filter); | ||
| 142 | }; | ||
| 143 | // ウィンドウの大きさが変わったら、フレームバッファも作り直す / when the window size changes, so does the framebuffer | ||
| 144 | window.onResize = [&](int, int) { resizeScene(); }; | ||
| 145 | 152 | ||
| 146 | window.onKey = [&](int key, int action, int /*mods*/) { | 153 | window.onKey = [&](int key, int action, int /*mods*/) { |
| 147 | if (action != GLFW_PRESS) return; | 154 | if (action != GLFW_PRESS) return; |
| 148 | if (key == GLFW_KEY_ESCAPE) window.close(); | 155 | if (key == GLFW_KEY_ESCAPE) window.close(); |
| 149 | if (key == GLFW_KEY_R && phong->reload() && post->reload()) printf("シェーダーを読み直した / shaders reloaded\n"); | 156 | if (key == GLFW_KEY_R && phong->reload() && post->reload() && skybox->reload() && envmap->reload()) |
| 157 | printf("シェーダーを読み直した / shaders reloaded\n"); | ||
| 150 | if (key == GLFW_KEY_TAB) window.setCursorCaptured(!window.cursorCaptured()); | 158 | if (key == GLFW_KEY_TAB) window.setCursorCaptured(!window.cursorCaptured()); |
| 151 | if (key == GLFW_KEY_C) { | 159 | if (key == GLFW_KEY_C) { |
| 152 | useOrbit = !useOrbit; | 160 | useOrbit = !useOrbit; |
| @@ -161,18 +169,27 @@ int main() { | |||
| 161 | effect = key - GLFW_KEY_1; | 169 | effect = key - GLFW_KEY_1; |
| 162 | printf("effect: %s\n", kEffectNames[effect]); | 170 | printf("effect: %s\n", kEffectNames[effect]); |
| 163 | } | 171 | } |
| 164 | if (key == GLFW_KEY_M) mirrorOn = !mirrorOn; | 172 | if (key == GLFW_KEY_M) { |
| 165 | if (key == GLFW_KEY_L) { | 173 | envMode = (envMode + 1) % 4; |
| 166 | lowRes = !lowRes; | 174 | printf("environment objects: %s\n", kEnvModeNames[envMode]); |
| 167 | resizeScene(); | 175 | } |
| 168 | printf("scene framebuffer: %d x %d\n", sceneFbo.width(), sceneFbo.height()); | 176 | if (key == GLFW_KEY_K) skyOn = !skyOn; |
| 177 | if (key == GLFW_KEY_X) { | ||
| 178 | seamless = !seamless; | ||
| 179 | if (seamless) glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS); | ||
| 180 | else glDisable(GL_TEXTURE_CUBE_MAP_SEAMLESS); | ||
| 181 | printf("seamless cube-map filtering: %s\n", seamless ? "on" : "off"); | ||
| 169 | } | 182 | } |
| 170 | if (key == GLFW_KEY_N) night = !night; | 183 | if (key == GLFW_KEY_N) night = !night; |
| 171 | if (key == GLFW_KEY_F) flashlightOn = !flashlightOn; | 184 | if (key == GLFW_KEY_F) flashlightOn = !flashlightOn; |
| 172 | if (key == GLFW_KEY_P) windmillMoving = !windmillMoving; | 185 | if (key == GLFW_KEY_P) windmillMoving = !windmillMoving; |
| 173 | }; | 186 | }; |
| 174 | 187 | ||
| 175 | Mesh floorMesh = makePlane(40.0f, 10.0f); | 188 | // 床は空の地平線まで届くように広く(遠くはfarPlaneで切れる) / the floor is wide so it reaches the sky's horizon |
| 189 | // (the far plane cuts it off in the distance) | ||
| 190 | Mesh floorMesh = makePlane(160.0f, 40.0f); | ||
| 191 | Mesh sphereMesh = makeSphere(48, 24); | ||
| 192 | Mesh cubeMesh = makeCube(); // 空の箱 / the sky box | ||
| 176 | Material floorMaterial; | 193 | Material floorMaterial; |
| 177 | floorMaterial.diffuseMap = &*floorTexture; | 194 | floorMaterial.diffuseMap = &*floorTexture; |
| 178 | floorMaterial.specular = {0.15f, 0.15f, 0.15f}; | 195 | floorMaterial.specular = {0.15f, 0.15f, 0.15f}; |
| @@ -193,19 +210,25 @@ int main() { | |||
| 193 | 210 | ||
| 194 | LightSet lights; | 211 | LightSet lights; |
| 195 | 212 | ||
| 196 | // 場面全体を今のフレームバッファに描く(第16章の描き方:不透明 → 半透明を遠い順) | 213 | Vec3 environmentTint; |
| 197 | // Draws the whole scene into the current framebuffer (chapter 16's order: opaque, then transparent far to near) | 214 | |
| 215 | // 場面全体を今のフレームバッファに描く / draws the whole scene into the current framebuffer | ||
| 198 | auto drawScene = [&](const View &v) { | 216 | auto drawScene = [&](const View &v) { |
| 199 | glEnable(GL_DEPTH_TEST); | 217 | glEnable(GL_DEPTH_TEST); |
| 200 | if (night) glClearColor(0.02f, 0.03f, 0.06f, 1.0f); | 218 | if (night) glClearColor(0.02f, 0.03f, 0.06f, 1.0f); |
| 201 | else glClearColor(0.45f, 0.62f, 0.85f, 1.0f); | 219 | else glClearColor(0.45f, 0.62f, 0.85f, 1.0f); |
| 202 | glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); | 220 | glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); |
| 203 | 221 | ||
| 222 | // 空はユニット3。phong(金属の映り込み)、envmap、skyboxのどれもここから読む | ||
| 223 | // The sky is on unit 3: phong (metal reflections), envmap and skybox all read it from there | ||
| 224 | sky->bind(3); | ||
| 225 | |||
| 204 | phong->use(); | 226 | phong->use(); |
| 205 | phong->set("uView", v.view); | 227 | phong->set("uView", v.view); |
| 206 | phong->set("uProj", v.proj); | 228 | phong->set("uProj", v.proj); |
| 207 | phong->set("uViewPos", v.position); | 229 | phong->set("uViewPos", v.position); |
| 208 | phong->set("uViewMode", viewMode); | 230 | phong->set("uViewMode", viewMode); |
| 231 | phong->set("uEnvironmentTint", environmentTint); | ||
| 209 | lights.apply(*phong); | 232 | lights.apply(*phong); |
| 210 | 233 | ||
| 211 | phong->set("uModel", Mat4::identity()); | 234 | phong->set("uModel", Mat4::identity()); |
| @@ -214,8 +237,6 @@ int main() { | |||
| 214 | floorMesh.draw(); | 237 | floorMesh.draw(); |
| 215 | scene->draw(*phong, Mat4::identity(), white, ModelPass::Opaque); | 238 | scene->draw(*phong, Mat4::identity(), white, ModelPass::Opaque); |
| 216 | for (const Placement &c : kCrates) crate->draw(*phong, translate(c.position) * rotateY(c.angle), white, ModelPass::Opaque); | 239 | for (const Placement &c : kCrates) crate->draw(*phong, translate(c.position) * rotateY(c.angle), white, ModelPass::Opaque); |
| 217 | for (const Placement &w : kWindows) | ||
| 218 | windowModel->draw(*phong, translate(w.position) * rotateY(w.angle), white, ModelPass::Opaque); | ||
| 219 | grassMaterial.apply(*phong, white); | 240 | grassMaterial.apply(*phong, white); |
| 220 | glDisable(GL_CULL_FACE); // 草は両面 / grass is two-sided | 241 | glDisable(GL_CULL_FACE); // 草は両面 / grass is two-sided |
| 221 | for (const Placement &g : grass) { | 242 | for (const Placement &g : grass) { |
| @@ -226,15 +247,48 @@ int main() { | |||
| 226 | } | 247 | } |
| 227 | glEnable(GL_CULL_FACE); | 248 | glEnable(GL_CULL_FACE); |
| 228 | 249 | ||
| 229 | // 窓のガラス:遠い順 / the window glass, far to near | 250 | // 環境マッピングの物 / the environment-mapped objects |
| 230 | std::vector<std::pair<float, Mat4>> glass; | 251 | envmap->use(); |
| 231 | for (const Placement &w : kWindows) | 252 | envmap->set("uView", v.view); |
| 232 | glass.push_back({length(w.position + Vec3{0.0f, 0.8f, 0.0f} - v.position), translate(w.position) * rotateY(w.angle)}); | 253 | envmap->set("uProj", v.proj); |
| 233 | std::sort(glass.begin(), glass.end(), [](const auto &a, const auto &b) { return a.first > b.first; }); | 254 | envmap->set("uViewPos", v.position); |
| 234 | glEnable(GL_BLEND); | 255 | envmap->set("uEnvironmentTint", environmentTint); |
| 235 | glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA); | 256 | envmap->set("uIor", 1.52f); |
| 236 | for (const auto &g : glass) windowModel->draw(*phong, g.second, white, ModelPass::Transparent, v.position); | 257 | for (size_t i = 0; i < std::size(kEnvObjects); ++i) { |
| 237 | glDisable(GL_BLEND); | 258 | const EnvObject &o = kEnvObjects[i]; |
| 259 | envmap->set("uEnvMode", envMode == 0 ? o.mode : envMode - 1); | ||
| 260 | envmap->set("uTint", o.tint); | ||
| 261 | if (i == 1) { | ||
| 262 | // 平らな面は一つの方向しか映さない:回すと映る空が変わる。木箱の原点は底なので、中心(0, 0.5, 0)の周りで回す | ||
| 263 | // A flat face reflects only one direction: turning it changes the sky it shows. The crate's origin is at its | ||
| 264 | // bottom, so it turns about its centre (0, 0.5, 0) | ||
| 265 | Mat4 model = translate(o.position) * rotate(normalize(Vec3{1.0f, 1.0f, 0.3f}), 0.6f * windmillTime + 0.8f) * | ||
| 266 | translate({0.0f, -0.5f, 0.0f}); | ||
| 267 | crate->drawGeometry(*envmap, model); // uModelとuNormalMatrixだけ / only uModel and uNormalMatrix | ||
| 268 | } else { | ||
| 269 | Mat4 model = translate(o.position) * scale({1.5f, 1.5f, 1.5f}); | ||
| 270 | envmap->set("uModel", model); | ||
| 271 | envmap->set("uNormalMatrix", normalMatrix(model)); | ||
| 272 | sphereMesh.draw(); | ||
| 273 | } | ||
| 274 | } | ||
| 275 | |||
| 276 | // 空は不透明な物の後に:見えているピクセルだけ塗る(深度1のところ)。半透明な物があればその前 | ||
| 277 | // The sky after the opaque objects: it only fills pixels nothing covers (depth 1). Before any transparent ones | ||
| 278 | if (skyOn) { | ||
| 279 | // 空の深度はちょうど1.0。クリアした値も1.0なので、GL_LESSでは通らない:GL_LEQUALにする | ||
| 280 | // The sky's depth is exactly 1.0, the same as the cleared value, so GL_LESS would reject it: use GL_LEQUAL | ||
| 281 | glDepthFunc(GL_LEQUAL); | ||
| 282 | // 箱を内側から見るので、見えるのは裏面:カリングを切る / we see the box from inside, i.e. its back faces: no culling | ||
| 283 | glDisable(GL_CULL_FACE); | ||
| 284 | skybox->use(); | ||
| 285 | skybox->set("uView", v.view); | ||
| 286 | skybox->set("uProj", v.proj); | ||
| 287 | skybox->set("uEnvironmentTint", environmentTint); | ||
| 288 | cubeMesh.draw(); | ||
| 289 | glEnable(GL_CULL_FACE); | ||
| 290 | glDepthFunc(GL_LESS); | ||
| 291 | } | ||
| 238 | }; | 292 | }; |
| 239 | 293 | ||
| 240 | double lastTime = window.time(); | 294 | double lastTime = window.time(); |
| @@ -276,6 +330,7 @@ int main() { | |||
| 276 | main.position = useOrbit ? orbit.position() : fps.position; | 330 | main.position = useOrbit ? orbit.position() : fps.position; |
| 277 | Vec3 viewDir = useOrbit ? normalize(orbit.target - orbit.position()) : fps.front(); | 331 | Vec3 viewDir = useOrbit ? normalize(orbit.target - orbit.position()) : fps.front(); |
| 278 | 332 | ||
| 333 | environmentTint = night ? Vec3{0.05f, 0.06f, 0.11f} : Vec3{1.0f, 1.0f, 1.0f}; | ||
| 279 | lights = LightSet{}; | 334 | lights = LightSet{}; |
| 280 | if (!night) { | 335 | if (!night) { |
| 281 | lights.ambient = {0.28f, 0.30f, 0.34f}; | 336 | lights.ambient = {0.28f, 0.30f, 0.34f}; |
| @@ -295,22 +350,7 @@ int main() { | |||
| 295 | sceneFbo.bind(); | 350 | sceneFbo.bind(); |
| 296 | drawScene(main); | 351 | drawScene(main); |
| 297 | 352 | ||
| 298 | // 2. バックミラー:後ろ向きのカメラで、もう一度場面を描く(別のフレームバッファへ) | 353 | // 2. 画面へ:全画面の三角形でフレームバッファのテクスチャを貼り、効果をかける |
| 299 | // 2. The rear-view mirror: draw the scene again with a camera looking backwards (into another framebuffer) | ||
| 300 | if (mirrorOn) { | ||
| 301 | Vec3 forward = viewDir; | ||
| 302 | forward.y = 0.0f; | ||
| 303 | forward = length(forward) > 0.0f ? normalize(forward) : Vec3{0.0f, 0.0f, -1.0f}; | ||
| 304 | View rear; | ||
| 305 | rear.position = main.position; | ||
| 306 | // 水平な後ろ向きから少し下を見る / backwards and horizontal, tilted down a little | ||
| 307 | rear.view = lookAt(main.position, main.position - forward + Vec3{0.0f, -0.3f, 0.0f}, {0.0f, 1.0f, 0.0f}); | ||
| 308 | rear.proj = perspectiveGl(radians(30.0f), static_cast<float>(mirrorWidth) / static_cast<float>(mirrorHeight), 0.1f, 100.0f); | ||
| 309 | mirrorFbo.bind(); | ||
| 310 | drawScene(rear); | ||
| 311 | } | ||
| 312 | |||
| 313 | // 3. 画面へ:全画面の三角形でフレームバッファのテクスチャを貼り、効果をかける | ||
| 314 | // 3. To the screen: a fullscreen triangle samples the framebuffer's texture and applies the effect | 354 | // 3. To the screen: a fullscreen triangle samples the framebuffer's texture and applies the effect |
| 315 | Framebuffer::bindDefault(window.width(), window.height()); | 355 | Framebuffer::bindDefault(window.width(), window.height()); |
| 316 | glDisable(GL_DEPTH_TEST); // 三角形一つだけ:深度は要らない / a single triangle: no depth needed | 356 | glDisable(GL_DEPTH_TEST); // 三角形一つだけ:深度は要らない / a single triangle: no depth needed |
| @@ -320,24 +360,6 @@ int main() { | |||
| 320 | sceneFbo.color().bind(0); | 360 | sceneFbo.color().bind(0); |
| 321 | fullscreen.draw(); | 361 | fullscreen.draw(); |
| 322 | 362 | ||
| 323 | // 4. バックミラー:画面の上の小さな長方形に。枠はシザーテストでクリアして描く。左右は反転(鏡)、効果はなし | ||
| 324 | // 4. The mirror: a small rectangle at the top of the screen. The frame is a scissored clear. Flipped left-right | ||
| 325 | // (it is a mirror), no effect | ||
| 326 | if (mirrorOn) { | ||
| 327 | int x = (window.width() - mirrorWidth) / 2, y = window.height() - mirrorHeight - 16; | ||
| 328 | glEnable(GL_SCISSOR_TEST); | ||
| 329 | glScissor(x - 4, y - 4, mirrorWidth + 8, mirrorHeight + 8); | ||
| 330 | glClearColor(0.08f, 0.08f, 0.09f, 1.0f); | ||
| 331 | glClear(GL_COLOR_BUFFER_BIT); | ||
| 332 | glDisable(GL_SCISSOR_TEST); | ||
| 333 | glViewport(x, y, mirrorWidth, mirrorHeight); // 全画面の三角形がこの長方形だけを覆う / the fullscreen triangle now covers only this | ||
| 334 | post->set("uEffect", 0); | ||
| 335 | post->set("uFlipX", 1); | ||
| 336 | mirrorFbo.color().bind(0); | ||
| 337 | fullscreen.draw(); | ||
| 338 | glViewport(0, 0, window.width(), window.height()); | ||
| 339 | } | ||
| 340 | |||
| 341 | window.swapBuffers(); | 363 | window.swapBuffers(); |
| 342 | } | 364 | } |
| 343 | return 0; | 365 | return 0; |
ファイル: a/src/material.cc | b/src/material.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -11,6 +11,8 @@ void Material::apply(const Shader &shader, const Texture2D &white) const { | |||
| 11 | shader.set("uMaterial.alphaMode", static_cast<int>(alphaMode)); | 11 | shader.set("uMaterial.alphaMode", static_cast<int>(alphaMode)); |
| 12 | shader.set("uMaterial.alphaCutoff", alphaCutoff); | 12 | shader.set("uMaterial.alphaCutoff", alphaCutoff); |
| 13 | shader.set("uMaterial.doubleSided", doubleSided ? 1 : 0); // boolのユニフォームはintで設定する / bool uniforms are set as int | 13 | shader.set("uMaterial.doubleSided", doubleSided ? 1 : 0); // boolのユニフォームはintで設定する / bool uniforms are set as int |
| 14 | shader.set("uMaterial.reflectivity", reflectivity); | ||
| 15 | shader.set("uMaterial.reflectionBlur", reflectionBlur); | ||
| 14 | (diffuseMap ? diffuseMap : &white)->bind(0); | 16 | (diffuseMap ? diffuseMap : &white)->bind(0); |
| 15 | (specularMap ? specularMap : &white)->bind(1); | 17 | (specularMap ? specularMap : &white)->bind(1); |
| 16 | (emissionMap ? emissionMap : &white)->bind(2); | 18 | (emissionMap ? emissionMap : &white)->bind(2); |
ファイル: a/src/material.hh | b/src/material.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -27,6 +27,11 @@ struct Material { | |||
| 27 | bool doubleSided = false; // 両面:裏面では法線を反転する(カリングはModelが切る) / double-sided: | 27 | bool doubleSided = false; // 両面:裏面では法線を反転する(カリングはModelが切る) / double-sided: |
| 28 | // the normal is flipped on back faces (Model turns culling off) | 28 | // the normal is flipped on back faces (Model turns culling off) |
| 29 | 29 | ||
| 30 | // 環境(ユニット3のキューブマップ)の映り込み(第18章)。金属だけ。第24章のIBLまでの簡単な代わり | ||
| 31 | // Reflection of the environment (the cube map on unit 3, chapter 18). Metals only; a simple stand-in until IBL (ch24) | ||
| 32 | Vec3 reflectivity = {0.0f, 0.0f, 0.0f}; // 映り込みの色と強さ(0 = なし) / colour and strength of the reflection (0 = none) | ||
| 33 | float reflectionBlur = 0.0f; // 0 = 鏡、1 = 一番ぼやけたミップマップ / 0 = mirror, 1 = the blurriest mip level | ||
| 34 | |||
| 30 | const Texture2D *diffuseMap = nullptr; // テクスチャユニット0 / texture unit 0 | 35 | const Texture2D *diffuseMap = nullptr; // テクスチャユニット0 / texture unit 0 |
| 31 | const Texture2D *specularMap = nullptr; // テクスチャユニット1 / texture unit 1 | 36 | const Texture2D *specularMap = nullptr; // テクスチャユニット1 / texture unit 1 |
| 32 | const Texture2D *emissionMap = nullptr; // テクスチャユニット2 / texture unit 2 | 37 | const Texture2D *emissionMap = nullptr; // テクスチャユニット2 / texture unit 2 |
ファイル: a/src/model.cc | b/src/model.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -43,6 +43,12 @@ static Material phongFromPbr(const GltfMaterial &m, float metallicScale, float r | |||
| 43 | : AlphaMode::Opaque; | 43 | : AlphaMode::Opaque; |
| 44 | p.alphaCutoff = m.alphaCutoff; | 44 | p.alphaCutoff = m.alphaCutoff; |
| 45 | p.doubleSided = m.doubleSided; | 45 | p.doubleSided = m.doubleSided; |
| 46 | // 空の映り込み(第18章):金属の正面の反射率F0。金属度は平均なので二乗して、木と金属が混ざった | ||
| 47 | // マテリアル(木箱:平均0.29)がほとんど映らないようにする。粗いほどぼやける | ||
| 48 | // Reflection of the sky (chapter 18): a metal's reflectance F0. Metallic is an average, so it is squared to keep | ||
| 49 | // mixed wood-and-metal materials (the crate: average 0.29) from reflecting much. Rougher = blurrier | ||
| 50 | p.reflectivity = (metallic * metallic) * f0; | ||
| 51 | p.reflectionBlur = roughness; | ||
| 46 | return p; | 52 | return p; |
| 47 | } | 53 | } |
| 48 | 54 | ||
コメント(0)
まだコメントはありません。
ログインするとコメント出来ます。