10. 色とフォンライティング
木箱にはテクスチャと奥行きがあり、周りを歩き回る事も出来ますが、まだシールの様に見えます。
どの面も、どちらを向いていても、画像ファイルと全く同じ明るさだからです。
此の章ではシーンを照らします。
小さなランプが木箱の山の周りを回り、其方を向いた面は明るく、背を向けた面は暗くなり、光沢のある物にはハイライトが付きます。
理論はGLSLシリーズで既に学びました。
アンビエント・拡散反射・鏡面反射は第9章で、法線行列を使ったワールド座標でのライティングは第13章で扱いました。
其の為、式は簡単に復習するだけにして、此の章の殆どは其れをC++のプロジェクトに持ち込む事に使います。
ライティングのシェーダー、linalg.hhを使った法線行列(と其の為の新しいMat3型)、法線行列が無いと何が起こるかを見せられる球のメッシュ、そしてライティングのバグを見つけ易くする幾つかのデバッグ表示です。
新しいOpenGLの関数はglProgramUniformMatrix3fvだけで、残りはシェーダーの数学です。
10.1 此の章で作る物
第9章のシーンを、木箱の周りを回りながら上下する1つのポイントライトで照らします。
木箱の隣にはテクスチャの無い物が2つあります。
珊瑚色の球と、一様でない拡大縮小で潰した青い楕円体です。
楕円体はわざと置いてあります。
法線に専用の行列が必要な理由を見せてくれる物だからです。
第9章の操作(WASD、マウス、ホイール、C、Tab、R、Esc)は其のままで、新しいキーが4つあります:
- V:表示の切り替え。全部、環境光だけ、拡散反射だけ、鏡面反射だけ、法線を色で
- L:光の色の切り替え(白、電球色、緑、青)
- P:光の動きを止める・再開する
- N:法線行列のオフとオン(オフはよくある間違いを見せる)
第9章からの変更:
src/mathx.hh(新規):linalg.hhへの追加。Mat3型とnormalMatrix()src/shader.hhとsrc/shader.cc:Mat3用のset()のオーバーロードsrc/shapes.hhとsrc/shapes.cc:makeSphere()shaders/phong.vertとshaders/phong.frag(新規):ライティングのシェーダーshaders/unlit.vertとshaders/unlit.frag(新規):光源の目印の為の一色のシェーダーshaders/textured.*とassets/textures/emblem.png(削除):桜の紋章は役目を終えましたsrc/main.cc:光、球、新しいキー
mathx.hhはヘッダーだけなので、CMakeLists.txtは変わりません。
10.2 光と色
形の話の前に、色についての決まりを1つ。
表面はテクスチャのピクセルの様に色を「持っている」訳ではありません。
当たった光の各色チャンネルの或る割合を反射するのです。
其の割合をアルベドと呼びます。
アルベドがなら、赤は全部、緑は35%、青は25%を反射します。
目に届くのは、チャンネル毎に光の色とアルベドを掛けた物です:
は成分毎の掛け算で、GLSLで2つのvec3の間の*が丁度此れをします(GLSLシリーズの9.2節)。
白い光の下では、アルベド其の物が見えます。
Lキーの緑の光の下では、珊瑚色の球は
になり、暗いオリーブ色です。
球は緑を余り反射せず、光には赤が少ないからです:
表面は、光に含まれていない色を反射する事は出来ません。
ランプの色がシーン全体の雰囲気をこんなに強く変えるのも、純粋な青い光の下の赤い物が黒くなるのも其の為です。
シェーダーでは、アルベドは2つの物を掛け合わせて作ります。
色のユニフォームとテクスチャです:
vec3 albedo = uObjectColor * texture(uTexture0, vUv).rgb;
木箱と床はuObjectColor = (1, 1, 1)なので、アルベドはテクスチャです。
球にはテクスチャがありません。
其れでも同じ行を通る方法は10.7節で見ます。
正直に1つ注意しておきます。
テクスチャやフレームバッファの数字はsRGBで符号化されていて、線型な光の量ではないので、其れを掛け合わせるのは少しだけ間違っています。
理由はGLSLシリーズの10.7節で説明しました。
此のシリーズでは第21章でsRGBのテクスチャとフレームバッファを使って直します。
其れ迄は全てが一貫していて、中間の明るさが少し暗過ぎるだけです。
10.3 1ページで分かるフォンの反射モデル
モデルは3つの部分から成り、全て表面の点での幾つかの単位ベクトルから、ピクセル毎に計算します:
- :法線。表面が向いている方向
- :表面から光への向き。にあるポイントライトなら
- :表面から目への向き。カメラがにあるなら
- :其の2つの丁度真ん中のハーフベクトル。
アルベド、光の色、環境光、鏡面反射の強さ、光沢度を使うと:
- 環境光(アンビエント)は、部屋の中を跳ね回る全ての光の代わりです。此れが無いと、ランプに背を向けた側は真っ黒になります。向きが無いので、形は出ません。
- 拡散反射はランバートの余弦則です。表面は光の方を向いている時に一番多くの光を受け、真横や背を向けている時は全く受けません。2つの単位ベクトルの内積が其のコサインです(線型代数シリーズの第4章)。
- 鏡面反射はハイライトで、光其の物のぼやけた映り込みです。法線がハーフベクトルに近い所で明るくなり、指数が点の小ささと鋭さを決めます。
GLSLシリーズの9.3〜9.5節の細かい点が2つ、コードに関係します:
- 鏡面反射の項にはアルベドを掛けません。プラスチック、木、石、塗装では、ハイライトは光の色になります。(金属は違い、第11章のマテリアルでは色を付けられます。)
- 鏡面反射の項はの所でだけ計算します。光が表面の裏にあってもハーフベクトルが「上」を向く事があり、暗い側にハイライトが出てしまうからです(9.4.5節)。
フォンか、ブリン・フォンか
章のタイトルが「フォンライティング」なのは、其れが3つの部分から成るモデルの名前だからです(ブイ・トン・フォン、1975年)。
フォン自身の鏡面反射の項は、を法線で反射させてと比べる物でした。
pow(max(dot(reflect(-l, n), v), 0.0), s)です。
あたし達は代わりにジム・ブリンのハーフベクトル版を使います。
GLSLシリーズの結論と同じで、殆ど全てのエンジンや昔の固定機能のOpenGLも此方を使っていました。
浅い角度でハイライトが急に切れる事が無く、物理ベースのシェーディング(第24章)の土台になっている考え方でもあります。
課題3で元のフォンに切り替えて比べられます。
目安として、ブリン・フォンはフォンと同じ大きさのハイライトを出すのに約4倍の指数が必要です。
「フォン」という名前はもう1つの物にも使われます。
フォンシェーディングは補間した法線からピクセル毎にライティングを計算する事で、頂点毎に照らして色を補間するグーローシェーディングと対になる言葉です(GLSLシリーズの13.7節)。
あたし達は両方の「フォン」を使います。
フォン(ブリン・フォン)のモデルを、フォンシェーディングで計算します。
全てを1つの空間で
4つのベクトルは全て同じ座標空間に無ければなりません。
ライティングが決して許してくれない唯一の決まりです。
あたし達はワールド座標で計算します。
光の位置とカメラの位置は既にワールド座標の位置(カメラは第9章のposition)なので、頂点シェーダーで表面の位置と法線をモデル座標からワールド座標に移すだけです。
位置は簡単で、uModel * positionです。
面白いのは法線の方です。
10.4 法線と法線行列
メッシュには既に法線がある
第8章から、全てのVertex3Dには属性ロケーション1にnormalがあり、makeCubeは其れを各面の外向きの方向にしています(立方体に24頂点が必要な理由の1つです)。
makePlaneは床に法線を与えます。
今迄、其れを読むシェーダーがありませんでした。
此れらの法線はモデル座標です。
木箱を35°回しても、立方体の前の面はのままです。
照らすにはワールド座標の法線が必要です。
何故モデル行列は法線に使えないのか
最初に思い付くのは、法線を方向として変換する事です。
モデル行列の左上3×3(平行移動無し)、GLSLならmat3(uModel) * aNormalです。
此れは回転には使え、一様な拡大縮小でも正規化すれば大丈夫です。
でも一様でない拡大縮小では、法線が間違った方に傾きます。
ボールをyの方向に平たく潰す事を考えて下さい。
ボールの上は広く殆ど平らな面になるので、其の法線は前より上を向くはずです。
ところが法線に同じ潰しを掛けるとy成分が小さくなり、より横を向いてしまいます。
面は平らになったのに、法線は逆の方に傾いたのです。
解決策は法線行列、つまりモデル行列の3×3の部分の逆行列の転置です。
導出は線型代数シリーズの10.10節とGLSLシリーズの13.5節にあります:
理由を短く言うと、こうです。
法線は、表面の全ての接線に垂直である事、で定義されます。
接線は表面上の近い点同士の差なので、位置と同じ様に変換されます:。
新しい法線には、次が成り立って欲しいのです:
なら全ての接線で此れが成り立つので、、つまりです。
いつものモデル行列で何をするかは簡単に分かります。
の3×3の部分はです(平行移動は方向に影響しません)。
其の逆行列はで(回転の逆行列は転置)、其れを転置すると:
対角行列は其れ自身が転置と同じだからです。
つまり法線行列は、同じ様に回し、拡大縮小は掛ける代わりに割るのです。
純粋な回転なら回転其の物、一様な拡大縮小ならで、正規化すればと同じ向きになります。
mat3(uModel)が何ヶ月も問題無く見え、最初に引き伸ばした物で初めて壊れるのは其の為です。
計算例:楕円体
楕円体はで拡大縮小されています(回転は話を変えないので、省きます)。
単位球の右上の、法線がの点を取ります。
其処でのxy平面の接線はです。
確認:。
拡大縮小の後、接線はです。
素朴な法線はで:
全く垂直ではありません。
法線行列なら:
正規化すると、素朴な法線はで真上から約61°も傾いていますが、正しい法線はで、真上から約17°だけです。
真上からの光なら、拡散反射の項はy成分其の物です。
間違った法線では0.479、正しい法線では0.956です。
小石の広い上面が、本来の半分の光しか受けない事になります。
Nキーが見せるのは丁度其れです。
上の段は法線を色で(緑は「上向き」)、下の段はライティングを表示しています:
mat3(uModel)では両端近くの法線が殆ど真横を向き(赤と青)、照らされた所は帯の様に狭くなり、ハイライトも動きます。
法線行列を使うと上面は緑で、上側全体が光を受け、楕円体は本当の姿、平たい小石に見えます。
mathx.hh:Mat3とnormalMatrix
linalg.hhにはMat4、inverse、transposeがありますが、3×3の行列はありません。
ダウンロードしたlinalg.hhは決して編集しないので(新しい版で変更が上書きされてしまいます)、自分の追加は新しいヘッダーsrc/mathx.hhに入れます:
// linalg.hhに無いものを足す(ダウンロードしたlinalg.hh自体は編集しない)
// Additions to linalg.hh (the downloaded linalg.hh itself is never edited)
#pragma once
#include <linalg.hh>
// 3×3行列。列優先:c[列]が一つの列ベクトル(Mat4と同じ)。法線行列に使う。
// 3×3 matrix. Column-major: c[column] is one column vector (like Mat4). Used for the normal matrix.
struct Mat3 {
Vec3 c[3];
};
// 4×4行列の左上3×3(回転と拡大縮小の部分、平行移動は捨てる)
// The upper-left 3×3 of a 4×4 matrix (the rotation and scale part; the translation is dropped)
inline Mat3 toMat3(const Mat4 &m) {
Mat3 r;
for (int i = 0; i < 3; ++i) r.c[i] = {m.c[i].x, m.c[i].y, m.c[i].z};
return r;
}
// 法線行列:モデル行列の逆行列の転置の左上3×3(線型代数 第10章)。
// 一様でない拡大縮小があっても、変換した法線が面に垂直なままになる。
// The normal matrix: the upper-left 3×3 of the model matrix's inverse transpose (Linear Algebra chapter 10).
// Transformed normals stay perpendicular to the surface even with non-uniform scaling.
inline Mat3 normalMatrix(const Mat4 &model) { return toMat3(transpose(inverse(model))); }
Mat3はMat4が4つの列ベクトルを持つ様に3つの列ベクトルを持つので、9個のfloatはGLSLのmat3が期待する順番の通りにメモリに並びます。
わざと小さくしてあり、掛け算もコンストラクターもありません。
法線行列をGPUに運ぶ為だけに必要で、計算は全てMat4で行います。
toMat3は最初の3つの列のx、y、zをコピーします。
GLSLのmat3(m)と同じ事です。
normalMatrixは3×3の逆行列を書く代わりに、線型代数シリーズの第10章の4×4のinverseを使い回します。
モデル行列がアフィン(一番下の行が)なので、此れで良いのです。
其の時、4×4の逆行列の左上3×3は左上3×3の逆行列と全く同じになり、転置しても3×3のブロックと其の他の部分の間で何も入れ替わりません。
平行移動は転置した行列の一番下の行に移り、toMat3が其れを捨てます。
何故CPUで計算するのでしょうか?
GLSLにはinverse()とtranspose()があり、多くの頂点シェーダーでtranspose(inverse(mat3(uModel)))を見掛けます。
でも法線行列は1つの物の全ての頂点で同じで、3×3の逆行列は数十回の掛け算です。
頂点毎ではなく描画毎に1回CPUで計算するのは、タダで手に入る得です。
(4×4のinverseは約100回の掛け算で、1つの物につき1フレームに1回。何でもありません。)
shader.hhは<linalg.hh>の代わりにmathx.hhをインクルードする様になったので、Shaderを使うファイルは全てMat3も知っています。
Mat3をアップロードする:glProgramUniformMatrix3fv
Shaderにはsetのオーバーロードがもう1つ増えます。
Mat4の物の隣に宣言します:
void set(const char *name, const Mat3 &value) const;
void Shader::set(const char *name, const Mat3 &m) const {
glProgramUniformMatrix3fv(program, location(name), 1, GL_FALSE, &m.c[0].x);
}
glProgramUniformMatrix3fvは第7章のglProgramUniformMatrix4fvの3×3版で、引数も同じです:
program:ユニフォームを持つプログラム(DSAなのでglUseProgramは不要)。location:glGetUniformLocationから、警告付きのヘルパーを通して。count:行列1つ。transpose:Mat3はGLSLと同じ列優先なのでGL_FALSE。value:9個のfloatの最初へのポインター。
よくある間違いが2つあります:
mat3のユニフォームにMat4を送る(又は其の逆)。型は完全に一致しなければなりません。OpenGLはデバッグコールバックを通してGL_INVALID_OPERATIONを報告し、ユニフォームは古い値のままです。- ユニフォームバッファでも同じ並びだと思い込む。 あたし達の様な普通のユニフォームなら、隙間無く詰めた9個のfloatで正しいです。std140レイアウトのユニフォームブロック(第19章)の中では、
mat3の各列は4個のfloatに詰め物されるので、Mat3を其のままコピーする事は出来ません。其の為、法線行列を単にmat4として送るエンジンも多いです。
プラットフォーム毎の注意
此の章にはプラットフォームに依存する物はありません。
Mat3は3つのfloatの構造体が3つで、あたし達が使う全てのコンパイラー(MSVC、Linux及びFreeBSDのGCCとClang)で9個の連続したfloatとして並びます。
後の球のコードはM_PIではなくlinalg.hhのPIを使います。
M_PIは標準のC++ではなく、MSVCでは<cmath>の前に_USE_MATH_DEFINESが必要だからです。
10.5 球
立方体では法線行列の問題を見せられません。
面の法線は軸に沿っていて、軸に沿った拡大縮小をしても同じ軸に沿ったままです。
正規化すれば、素朴な結果でも正しくなってしまいます。
曲面には色々な向きの法線があるので、shapes.hhに3つ目の形を足します:
// 原点を中心とした直径1の球(UV球)。segments = 経度方向の分割数、rings = 緯度方向の分割数。
// 法線は中心から外向き。立方体と同じく外から見て反時計回り。
// A sphere of diameter 1 centred on the origin (a UV sphere). segments = divisions around, rings = from pole to pole.
// The normals point outwards from the centre. Counter-clockwise seen from outside, like the cube.
Mesh makeSphere(int segments = 32, int rings = 16);
1×1×1の立方体と同じく直径1なので、scale({1.4f, 1.4f, 1.4f})で直径1.4のボールになります。
頂点はGLSLシリーズの13.6節と同じく球面座標から作ります。
角度は北極(0)から南極()へ、角度は一周します:
Mesh makeSphere(int segments, int rings) {
std::vector<Vertex3D> vertices;
std::vector<std::uint32_t> indices;
for (int r = 0; r <= rings; ++r) {
float phi = PI * static_cast<float>(r) / static_cast<float>(rings); // 0 = 北極、π = 南極 / 0 = north pole, π = south pole
for (int s = 0; s <= segments; ++s) {
// 継ぎ目の頂点は二重(UVが0と1で違う) / the seam vertices are doubled (u = 0 and u = 1)
float theta = 2.0f * PI * static_cast<float>(s) / static_cast<float>(segments);
Vec3 n = {std::sin(phi) * std::sin(theta), std::cos(phi), std::sin(phi) * std::cos(theta)};
Vec2 uv = {static_cast<float>(s) / static_cast<float>(segments), 1.0f - static_cast<float>(r) / static_cast<float>(rings)};
vertices.push_back({0.5f * n, n, uv});
}
}
単位球上の点はです。
単位球では法線が位置其の物なので、法線はタダです。
頂点は0.5f * n(半径0.5)にあり、其の法線はnです。
では点は+Z(デフォルトのカメラの方)を向き、が増えると+Xの方に回るので、前から見るとuは左から右に増えます。
vは北極で1、南極で0で、反転した画像が使うOpenGLの決まりです。
ループは<= segmentsと<= rings迄、つまり分割数より1つ多く回ります。
各輪の最後の列はで最初の列と同じ場所にありますが、uは0ではなく1です。
此の二重の継ぎ目が無いと、輪を閉じる三角形がuを0.97から0に戻す様に補間し、テクスチャ全体を細い帯に押し込んでしまいます。
三角形は各輪を次の輪と繋ぎます:
// 隣り合う二つの輪の間を四角形(三角形2つ)で埋める。極の潰れた三角形は省く。
// Fill between neighbouring rings with quads (two triangles). Skip the degenerate triangles at the poles.
std::uint32_t row = static_cast<std::uint32_t>(segments + 1);
for (std::uint32_t r = 0; r < static_cast<std::uint32_t>(rings); ++r) {
for (std::uint32_t s = 0; s < static_cast<std::uint32_t>(segments); ++s) {
std::uint32_t a = r * row + s; // 左上 / top left
std::uint32_t b = a + row; // 左下 / bottom left
if (r != static_cast<std::uint32_t>(rings) - 1) indices.insert(indices.end(), {a, b, b + 1});
if (r != 0) indices.insert(indices.end(), {a, b + 1, a + 1});
}
}
return Mesh(vertices, indices, kVertex3DLayout);
}
輪rと輪r + 1の間の小さな四角形は、三角形(a, b, b + 1)と(a, b + 1, a + 1)になります。
どちらも立方体の面と同じく外から見て反時計回りです(第16章のフェイスカリングで大事になります)。
一番上の輪では全てのaが同じ点、北極なので、其処の三角形(a, b + 1, a + 1)は面積が0で、省きます。
一番下の輪では(a, b, b + 1)が潰れた三角形です。
デフォルトでは頂点、三角形です。
shapes.ccはstd::sinとstd::cosの為に<cmath>をインクルードする様になります。
10.6 ライティングのシェーダー
phong.vert
#version 460 core
layout(location = 0) in vec3 aPosition;
layout(location = 1) in vec3 aNormal; // 面の向き(モデル座標) / which way the surface faces (model space)
layout(location = 2) in vec2 aUv;
uniform mat4 uModel;
uniform mat4 uView;
uniform mat4 uProj;
uniform mat3 uNormalMatrix; // 法線をワールド座標へ(モデル行列の逆行列の転置) / normals to world space (inverse transpose of uModel)
// ライティングはワールド座標で計算する / lighting is computed in world space
out vec3 vWorldPos;
out vec3 vNormal;
out vec2 vUv;
void main() {
vec4 world = uModel * vec4(aPosition, 1.0);
vWorldPos = world.xyz;
vNormal = uNormalMatrix * aNormal; // 正規化はフラグメントシェーダーで / normalized in the fragment shader
vUv = aUv;
gl_Position = uProj * uView * world;
}
第9章の頂点シェーダーと比べると、ロケーション1の法線(第8章から空けておいた場所)を読み、フラグメントシェーダーに2つの物を余分に渡します。
光と目への向きの為に必要なワールド座標の位置と、ワールド座標の法線です。
ワールドの位置は1回だけ計算し、gl_Positionにも使い回します。
法線は此処では正規化しません。
ラスタライザーは法線を三角形の上で線型に補間し、2つの単位ベクトルを混ぜた物は真ん中で1より短くなるので(90°離れた2つの法線の真ん中では長さ0.71)、どの道フラグメントシェーダーで正規化しなければなりません。
2回正規化しても時間の無駄になるだけです。
phong.frag
まず宣言:
#version 460 core
in vec3 vWorldPos;
in vec3 vNormal;
in vec2 vUv;
layout(binding = 0) uniform sampler2D uTexture0; // 物体の色 / the object's colour
uniform vec3 uObjectColor; // テクスチャに掛ける色 / colour multiplied with the texture
uniform float uSpecularStrength; // 鏡面反射の強さ / specular strength
uniform float uShininess; // 光沢度(大きいほど小さく鋭いハイライト) / shininess (bigger = smaller, sharper highlight)
uniform vec3 uLightPos; // 光の位置(ワールド座標) / light position (world space)
uniform vec3 uLightColor; // 光の色と明るさ / light colour and brightness
uniform vec3 uAmbient; // 環境光の色と明るさ / ambient light colour and brightness
uniform vec3 uViewPos; // カメラの位置(ワールド座標) / camera position (world space)
// 0 = 全部、1 = 環境光だけ、2 = 拡散反射だけ、3 = 鏡面反射だけ、4 = 法線を色で
// 0 = everything, 1 = ambient only, 2 = diffuse only, 3 = specular only, 4 = normals as colours
uniform int uViewMode;
layout(location = 0) out vec4 out_color;
ユニフォームは3つの組に分かれます:
- 物体:色(テクスチャに掛ける)、ハイライトの強さと鋭さ。描画毎に変わります。第11章で此れらをマテリアルの構造体に纏めます。
- 光とカメラ:光の位置と色、環境光の色、目の位置。全てワールド座標です。フレーム毎に1回変わります。
uViewMode:デバッグ用のスイッチ。10.8節で説明します。
uAmbientは1つの強さではなくvec3です。
環境光にも色があるからです(青い空、暖かい部屋)。
課題2で其れを使います。
uLightColorも、強いランプなら1より明るく出来ます。
関数其の物は10.3節の式を1行ずつ書いた物です:
void main() {
vec3 albedo = uObjectColor * texture(uTexture0, vUv).rgb;
// 補間された法線は短くなるので正規化し直す / interpolated normals get shorter: normalize again
vec3 n = normalize(vNormal);
vec3 l = normalize(uLightPos - vWorldPos); // 面から光へ / from the surface towards the light
vec3 v = normalize(uViewPos - vWorldPos); // 面から目へ / from the surface towards the eye
// 環境光:どこからともなく来る弱い光 / ambient: weak light coming from everywhere
vec3 ambient = uAmbient * albedo;
// 拡散反射(ランバート):光に向いているほど明るい / diffuse (Lambert): brighter the more it faces the light
float diff = max(dot(n, l), 0.0);
vec3 diffuse = diff * albedo * uLightColor;
// 鏡面反射(Blinn-Phong):ハーフベクトルが法線に近いほど明るい / specular (Blinn-Phong): bright where the half vector is close to n
float spec = 0.0;
if (diff > 0.0) { // 裏から照らされた面にハイライトは出ない / no highlight on surfaces lit from behind
vec3 h = normalize(l + v);
spec = pow(max(dot(n, h), 0.0), uShininess);
}
vec3 specular = uSpecularStrength * spec * uLightColor;
vec3 color = ambient + diffuse + specular;
if (uViewMode == 1) color = ambient;
else if (uViewMode == 2) color = diffuse;
else if (uViewMode == 3) color = specular;
else if (uViewMode == 4) color = n * 0.5 + 0.5; // -1〜1を0〜1に / map -1..1 to 0..1
out_color = vec4(color, 1.0);
}
幾つか補足します:
uLightPos - vWorldPosは表面から光へ向きます。GLSLシリーズの決まりで、照らされた面ではdot(n, l)がマイナスの符号無しで正になります。第12章のディレクショナルライトは光が進む向きを保存し、シェーダーで符号を反転します。- GLSLの
pow(x, y)はで未定義なので、ifの中でもmax(..., 0.0)は残します。 if (diff > 0.0)が「裏からはハイライト無し」の決まりです。心配する程のコストはありません。隣り合うピクセルは殆ど何時も同じ分岐を通ります。- 表示モードは一番最後に
colorを上書きします。全ての項は其れでも計算されるので、モードを切り替えてもユニフォームが最適化で消される事はありません。
数字で確かめる
1つのピクセルをシェーダーで追ってみましょう。
原点の床の点、。
光は、目はで、どちらも5単位離れているので数字が綺麗になります。
表面は珊瑚色の球の設定にします。
アルベド、鏡面反射の強さ0.6、光沢度64、白い光、環境光0.15です。
向き:
なので、内積はy成分其の物です:
従って3つの項は:
赤のチャンネルが1を超えています。
フレームバッファはチャンネル毎に8ビットなので、OpenGLは書き込む時に1.0に切り詰め、ピクセルは約になります。
白っぽく色の抜けた珊瑚色、ハイライトの縁です。
色の付いた物の強いハイライトが白っぽくなって細部を失うのは、此の切り詰めの為です。
第21章では浮動小数点のバッファに描き、代わりにトーンマッピングします。
指数がどれ程効くかにも注目して下さい。
ですが、です。
此処ではハーフベクトルは法線から8°しか離れていないのに、光沢度64でハイライトはもう半分になります。
光源の為のunlitシェーダー
ランプ自体も見えるべきなので、其の位置に小さな立方体を描きます。
其れは照らされてはいけないので(ランプは自分を照らしません)、2つ目の簡単なシェーダーを使います。
unlit.vert:
#version 460 core
layout(location = 0) in vec3 aPosition;
uniform mat4 uModel;
uniform mat4 uView;
uniform mat4 uProj;
void main() {
gl_Position = uProj * uView * uModel * vec4(aPosition, 1.0);
}
とunlit.frag:
#version 460 core
// ライティングなしの一色(光源の目印用) / one colour without lighting (for light markers)
uniform vec3 uColor;
layout(location = 0) out vec4 out_color;
void main() {
out_color = vec4(uColor, 1.0);
}
頂点シェーダーはロケーション0しか宣言していません。
立方体のVAOでは法線とUVの属性も有効なままですが、問題ありません。
シェーダーが読まない属性は単に無視されます。
此のシェーダーは、あらゆるデバッグ用の形(光の位置、バウンディングボックス、レイ)の為に残しておきます。
古いtextured.vert/.fragと紋章のテクスチャは削除します。
其れで描いていた物は全て照らされる様になりました。
よくある間違い
- 補間された法線を正規化しない。 各三角形の真ん中に向かってライティングが暗くなり、メッシュの辺の模様がうっすら見えます。
- 空間を混ぜる。 モデル座標の法線とワールド座標の光の向きは、物を回さない限り正しく見えますが、回すとライティングが物と一緒に回ります。
uNormalMatrixを忘れる。 ユニフォームは0で始まるので、全ての法線がになり、ゼロベクトルのnormalizeはNaNです。黒かゴミのピクセルになります。Shader::setは存在しない名前を1回だけ警告しますが、呼び忘れた事迄は分かりません。- 光の向きが逆。
vWorldPos - uLightPosだとランプに背を向けた面が照らされます。暗いはずの側が明るいなら、真っ先に此処を確かめて下さい。
10.7 main.cc
準備
mainはシェーダーを2つ読み込み、テクスチャを1つ余分に作ります:
std::optional<Shader> phong = Shader::load("shaders/phong.vert", "shaders/phong.frag");
std::optional<Shader> unlit = Shader::load("shaders/unlit.vert", "shaders/unlit.frag");
std::optional<Texture2D> crate = Texture2D::load("assets/textures/crate.png");
std::optional<Texture2D> floorTexture = Texture2D::load("assets/textures/floor.png");
if (!phong || !unlit || !crate || !floorTexture) return 1;
glEnable(GL_DEPTH_TEST);
// 1×1の白いテクスチャ:テクスチャのない物はuObjectColorだけで色が決まる
// A 1×1 white texture: objects without a texture get their colour from uObjectColor alone
const unsigned char whitePixel[4] = {255, 255, 255, 255};
Texture2D white = Texture2D::fromPixels(whitePixel, 1, 1, {.flipY = false, .mipmaps = false});
球にはテクスチャがありませんが、シェーダーは何時もuTexture0をサンプリングします。
2つ目のシェーダーやifの代わりに、白いピクセル1つだけのテクスチャを繋ぎます。
texture()は何処でもを返し、uObjectColor * 1は色其の物です。
fromPixels(第6章)は4バイトを1×1のRGBA8のテクスチャとしてアップロードします。
mipmaps = falseなので段は1つだけで、GL_LINEARのフィルタリングを使います。
第11章では此の技を、あらゆる種類のマップの決まりにします。
カメラは第9章より少し高く、少し後ろから、14°見下ろして始まるので、光と両方の球が見えます:
Camera fps;
fps.position = {0.5f, 2.4f, 8.5f};
fps.pitch = radians(-14.0f);
新しい状態の変数が幾つか:
bool useOrbit = false;
int viewMode = 0;
int lightColorIndex = 0;
bool lightMoving = true;
bool useNormalMatrix = true;
float lightTime = 0.0f; // 光の動きの時間(止められる) / time for the light's motion (can be paused)
window.setCursorCaptured(true);
lightTimeは第7章の止められるアニメーションの時計です。
lightMovingがtrueの間だけ進むので、Pを押すと光が其の場で止まります(此の章のスクリーンショットは全て其の様にして撮りました)。
キー
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) {
bool ok = phong->reload();
ok = unlit->reload() && ok; // 両方とも読み直す / reload both, even if the first one failed
if (ok) printf("シェーダーを読み直した / shaders reloaded\n");
}
if (key == GLFW_KEY_TAB) window.setCursorCaptured(!window.cursorCaptured());
if (key == GLFW_KEY_C) {
useOrbit = !useOrbit;
window.setCursorCaptured(!useOrbit);
printf("camera: %s\n", useOrbit ? "orbit" : "fps");
}
if (key == GLFW_KEY_V) {
viewMode = (viewMode + 1) % 5;
printf("view: %s\n", kViewModeNames[viewMode]);
}
if (key == GLFW_KEY_L) lightColorIndex = (lightColorIndex + 1) % 4;
if (key == GLFW_KEY_P) lightMoving = !lightMoving;
if (key == GLFW_KEY_N) {
useNormalMatrix = !useNormalMatrix;
printf("normal matrix: %s\n", useNormalMatrix ? "on" : "off (mat3(uModel))");
}
};
Rは2つのシェーダーを読み直す様になりました。
ok = unlit->reload() && okの順番を見て下さい。
ok && unlit->reload()と書くと、最初の読み直しが失敗した時に&&が2つ目を飛ばしてしまい(短絡評価)、phong.fragに打ち間違いがあるとunlit.fragがずっと読み直されなくなります。
光の色と表示モードの名前は、ファイルの先頭にある2つの小さな表です:
// Lキーで切り替える光の色 / light colours cycled with the L key
static const Vec3 kLightColors[] = {
{1.0f, 1.0f, 1.0f}, // 白 / white
{1.0f, 0.72f, 0.42f}, // 電球の色 / warm bulb
{0.35f, 1.0f, 0.45f}, // 緑 / green
{0.45f, 0.55f, 1.0f}, // 青 / blue
};
static const char *const kViewModeNames[] = {"all", "ambient", "diffuse", "specular", "normals"};
立方体と床を作った後、mainはデフォルトの32 × 16分割で球も作ります:
Mesh cube = makeCube();
Mesh sphere = makeSphere();
Mesh floorMesh = makePlane(40.0f, 10.0f);
動く光
毎フレーム、カメラの入力の後で:
// 光は箱の山の周りを回り、少し上下する / the light circles the pile of crates, bobbing up and down a little
if (lightMoving) lightTime += dt;
Vec3 lightPos = {3.5f * std::sin(0.7f * lightTime), 2.6f + 0.6f * std::sin(1.3f * lightTime),
3.5f * std::cos(0.7f * lightTime)};
Vec3 lightColor = kLightColors[lightColorIndex];
Mat4 view = useOrbit ? orbit.view() : fps.view();
Mat4 proj = useOrbit ? orbit.projection(window.aspect()) : fps.projection(window.aspect());
Vec3 viewPos = useOrbit ? orbit.position() : fps.position;
光はY軸の周りの半径3.5の円を毎秒0.7ラジアンで動き、秒で1周します。
始まりは山の手前のです。
高さは別の速さ(毎秒1.3ラジアン)で2.0から3.2の間を揺れるので、道筋は丁度同じ形を繰り返さず、ハイライトが表面を滑っていくのが見えます。
viewPosは鏡面反射の項の為の目の位置です。
FPSカメラならpositionのフィールド、オービットカメラなら第9章の計算するposition()です。
カメラのクラスを素直なデータにしたのは其の為です。
照らす物を描く
物毎に専用のユニフォームが5つ必要なので、其れを設定して描く小さなラムダを作ります:
// 一つの物を描く:モデル行列と法線行列、物体の色、光沢 / draws one object: model and normal matrix, colour, shininess
auto drawLit = [&](const Mesh &mesh, const Mat4 &model, Vec3 color, float specular, float shininess) {
phong->set("uModel", model);
// 法線行列なしだと一様でない拡大縮小で法線が傾く / without the normal matrix, non-uniform scaling tilts the normals
phong->set("uNormalMatrix", useNormalMatrix ? normalMatrix(model) : toMat3(model));
phong->set("uObjectColor", color);
phong->set("uSpecularStrength", specular);
phong->set("uShininess", shininess);
mesh.draw();
};
法線行列はモデル行列を設定する其の場所で計算するので、2つがずれる事は決してありません。
Nでオフにすると、ラムダは代わりにtoMat3(model)を送ります。
シェーダーでmat3(uModel)が計算する物と全く同じです。
比較のスクリーンショットは、シェーダーに触らずに其の様にして作りました。
次はフレーム毎のユニフォーム:
phong->use();
phong->set("uView", view);
phong->set("uProj", proj);
phong->set("uViewPos", viewPos);
phong->set("uLightPos", lightPos);
phong->set("uLightColor", lightColor);
phong->set("uAmbient", Vec3{0.15f, 0.15f, 0.15f});
phong->set("uViewMode", viewMode);
そしてシーン:
// 床:石は少しだけ光る / the floor: stone is only slightly shiny
floorTexture->bind(0);
drawLit(floorMesh, Mat4::identity(), {1.0f, 1.0f, 1.0f}, 0.15f, 16.0f);
// 箱 / crates
crate->bind(0);
for (const CrateInfo &c : kCrates) {
Vec3 centre = c.position + Vec3{0.0f, 0.5f * c.size, 0.0f};
drawLit(cube, translate(centre) * rotateY(c.angle) * scale({c.size, c.size, c.size}), {1.0f, 1.0f, 1.0f}, 0.3f,
32.0f);
}
// テクスチャなしの球二つ:色はuObjectColorだけ。二つ目は一様でない拡大縮小(楕円体)
// Two untextured spheres: the colour is uObjectColor alone. The second one is scaled non-uniformly (an ellipsoid)
white.bind(0);
drawLit(sphere, translate({2.6f, 0.7f, 2.2f}) * scale({1.4f, 1.4f, 1.4f}), {1.0f, 0.35f, 0.25f}, 0.6f, 64.0f);
drawLit(sphere, translate({-1.8f, 0.45f, 2.4f}) * rotateY(radians(35.0f)) * scale({2.2f, 0.9f, 1.1f}),
{0.3f, 0.5f, 1.0f}, 0.6f, 64.0f);
値は、鈍い物から光る物迄、目で見て選びました:
| 物 | 色 | 鏡面反射の強さ | 光沢度 |
|---|---|---|---|
| 床(石) | テクスチャ | 0.15 | 16 |
| 木箱(木) | テクスチャ | 0.3 | 32 |
| 球(プラスチック) | 珊瑚色、青 | 0.6 | 64 |
石には弱く広い艶、球には強く小さなハイライトが付きます。
木箱は妥協です。
木は殆ど光らず、鋼の枠は光るべきです。
1つの物に1つの数字では両方は出来ません。
其れこそ第11章が鏡面反射マップで解決する問題です。
珊瑚色の球は1.4で一様に拡大縮小し、半径の0.7だけ持ち上げて床に置きます。
楕円体は高さ0.9で0.45持ち上げ、動かす前に35°回すので、長い軸がワールドの軸と揃っていません。
法線行列は回転と一様でない拡大縮小を同時に扱わなければなりません。
光の目印
最後に、unlitシェーダーでランプの目印を描きます:
// 光源の目印:光の色そのまま、ライティングなし / the light's marker: the light colour itself, unlit
unlit->use();
unlit->set("uView", view);
unlit->set("uProj", proj);
unlit->set("uModel", translate(lightPos) * scale({0.2f, 0.2f, 0.2f}));
unlit->set("uColor", lightColor);
cube.draw();
光自身の色の0.2単位の立方体です。
unlitは別のプログラムなので、専用のuViewとuProjが必要です。
ユニフォームはGLのコンテキストではなく、プログラムに属します。
第19章ではユニフォームバッファでカメラの行列をプログラム間で共有します。
10.8 表示モードでライティングをデバッグする
ライティングがおかしく見える時、3つの項の合計は読み難いです。
ハイライトの場所が違うのか、拡散反射が強過ぎるのか?
法線が間違っているのか、光の向きか?
Vキーは項を1つずつ見せて、其れに答えます:
- 環境光はアルベドの15%です。平らで、形は全くありません。
- 拡散反射が形を作ります。ランプに背を向けた面は真っ黒で、光の方を向いた木箱の前の面が一番明るいです。
- 鏡面反射は殆ど何処も黒です。球には小さく鋭い点、床には広く弱い光(光沢度16)があり、鏡の方向に近い木箱の面が少し灰色に光ります。
- 合計が普段見ている物です。
5つ目のモードは、法線其の物を色として見せます。
GLSLシリーズの9.1.2節の技です:
読み方はこうです。
x、y、zが赤、緑、青になります。
上を向いた物、はの明るい緑で、床と木箱の上面です。
カメラを向いた面、はの青紫です。
回した木箱の前面は其の混ざった色で、球は全ての色を滑らかに見せます。
此の表示で黒い面があれば、其の法線はゼロです。
立方体の隣り合う面が同じ色なら、法線が同じという事で、其れは間違いです。
光の目印はunlitシェーダーで描いているので白いままです。
此のモードは一番安上がりなライティングのデバッガーなので、此のシリーズの全てのライティングのシェーダーに残します(第11章では発光の表示が加わります)。
10.9 本物のエンジンではどうしているか
- 沢山の光を1つのシェーダーで。 あたし達の光は1つで、専用のユニフォームを持っています。本物のシーンには何十もの光があります。第12章では光を構造体の配列に、第19章ではユニフォームバッファに入れます。大きなエンジンは更に、各ピクセルが届く光だけをループするディファードやクラスタードのシェーディングを使います。
- 法線行列はキャッシュする。 エンジンは各物のワールド行列を保存し、物が動いた時だけ、其の逆行列や法線行列と一緒に計算し直します。拡大縮小が一様かを確かめ、一様なら逆行列を省くエンジンも多いです(課題7)。
- 物理ベースのシェーディング。 ブリン・フォンの数字(鏡面反射の強さ、光沢度)は作り物で、目で見て調整します。現代のエンジンは、パラメーター(ラフネス、メタルネス)が測定出来て、エネルギーを保存する物理ベースのモデルを使います。其れでもハーフベクトルを含め、同じベクトルを使います。第24章です。
- 線型なライティングとHDR。 ライティングは線型な色で計算し、1を超えられる浮動小数点のバッファに保存し、最後にトーンマッピングします。10.6節で切り詰められた赤のチャンネルも、1.264のまま残ります。第21章です。
- 此処にまだ無い物。 影がありません。山の後ろのランプは、木箱を突き抜けて手前の床を照らします(第23章)。そして減衰がありません。20単位離れた床も、ランプの真下の床と同じ明るさです(第12章)。
10.10 まとめ
- 見えるのは、チャンネル毎の光の色とアルベドの積です。表面は光に含まれない色を反射出来ません。
- フォンの反射モデルは環境光 + 拡散反射 + 鏡面反射です。鏡面反射の項にはブリン・フォンのハーフベクトルを使い、の所でだけ計算し、アルベドで色を付けません。
- ライティングのベクトルは全て1つの空間に無ければなりません。あたし達はワールド座標を使います。
vWorldPosと法線は頂点シェーダーから、光とカメラの位置はワールドの位置です。 - 法線は法線行列で変換します。ならです。
mat3(uModel)が正しいのは回転と一様な拡大縮小だけで、楕円体では違いが見え、立方体では見えません。 src/mathx.hhにはlinalg.hhへの追加、Mat3、toMat3、normalMatrixを置きます。法線行列は描画毎に1回CPUで計算し、glProgramUniformMatrix3fvでアップロードします。- 補間された法線はフラグメントシェーダーで正規化します。
- 1×1の白いテクスチャを使えば、テクスチャの無い物も同じテクスチャ付きのシェーダーを使えます。
- 各項と法線を単独で見せるデバッグ表示は、ライティングのバグを見つける一番の近道です。
10.11 課題
- ★ 2つの球の光沢度を8、32、256にして下さい(
drawLitの最後の引数)。8ではハイライトが球の大部分を覆う大きく柔らかい光に、256では小さく鋭い点になるはずです。 - ★ 環境光を青っぽく、
uAmbient = (0.05, 0.08, 0.2)にして下さい。ランプに背を向けた木箱の側面が夜空の下の物の様に暗い青になり、照らされた面は殆ど変わらないはずです。 - ★ フォンの元の鏡面反射の項に切り替えて下さい:
spec = pow(max(dot(reflect(-l, n), v), 0.0), uShininess);。同じ光沢度ではハイライトがはっきり小さくなり、浅い角度で見た床の光は手前に伸びずに丸いままになるはずです。球が前と同じ様に見える光沢度を探して下さい(64の約4分の1)。 - ★★ グーローシェーディング:ライティングを頂点シェーダーに移し(其処で
colorを計算してvec3で渡す)、フラグメントシェーダーは其れを出力するだけにして下さい。違いがはっきり分かる様にmakeSphere(12, 6)を使います。拡散反射の陰影は殆ど同じに見えますが、ハイライトは光が動くと頂点から頂点へ跳ぶ、まだらな星形の模様になり、木箱の面ではハイライトが完全に消えるはずです。照らされるのは4つの角だけだからです。 - ★★ 代わりにビュー座標でライティングして下さい。位置として
uView * worldを、法線としてmat3(uView) * uNormalMatrix * aNormalを渡し(ビュー行列は回転と平行移動なのでmat3で十分です)、uLightPosはCPUでuViewで変換し、カメラはビュー座標の原点にあるのでを使います。絵は全く同じになるはずです。全てが同じ空間にある限り、どの空間かは関係無い事の証明です。 - ★★ 2つ目の光を足して下さい。赤いランプを、もっと低い所で逆向きに回します。
uLightPos2とuLightColor2を足し、両方の拡散反射と鏡面反射を計算して足し合わせ(環境光は1回だけ)、2つ目の目印を描きます。どの球にも白と赤の2つのハイライトが付くはずです。第12章で光の配列に一般化する物です。 - ★★★ 必要無い時は逆行列を省いて下さい。3×3の部分の3つの列の長さが(0.001以内で)同じかを確かめ、同じなら
toMat3(m)を、違えば完全なnormalMatrix(m)を返すMat3 fastNormalMatrix(const Mat4 &m)を書きます。toMat3(m)が本当の法線行列より倍長いのに、其れで正しい理由を説明して下さい。1フレームの15回の照らす描画の内、何回がまだ逆行列を必要とするか数えて下さい。1回(楕円体)になり、絵は変わらないはずです。
ファイル: a/assets/LICENSE.txt | b/assets/LICENSE.txt
| 前 | 新 | ||
|---|---|---|---|
| @@ -4,5 +4,4 @@ The files in assets/ were made for this tutorial by the author (generated with t | |||
| 4 | which are not part of this project). Free to use for any purpose. | 4 | which are not part of this project). Free to use for any purpose. |
| 5 | 5 | ||
| 6 | textures/crate.png 木箱 / wooden crate | 6 | textures/crate.png 木箱 / wooden crate |
| 7 | textures/emblem.png 桜の紋章 / sakura emblem | ||
| 8 | textures/floor.png 石の床 / stone floor tiles | 7 | textures/floor.png 石の床 / stone floor tiles |
ファイル: a/assets/textures/emblem.png | /dev/null
削除されたファイル:100644 / バイナリファイル
ファイル: /dev/null | b/shaders/phong.frag
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,52 @@ | |||
| 1 | #version 460 core | ||
| 2 | in vec3 vWorldPos; | ||
| 3 | in vec3 vNormal; | ||
| 4 | in vec2 vUv; | ||
| 5 | |||
| 6 | layout(binding = 0) uniform sampler2D uTexture0; // 物体の色 / the object's colour | ||
| 7 | |||
| 8 | uniform vec3 uObjectColor; // テクスチャに掛ける色 / colour multiplied with the texture | ||
| 9 | uniform float uSpecularStrength; // 鏡面反射の強さ / specular strength | ||
| 10 | uniform float uShininess; // 光沢度(大きいほど小さく鋭いハイライト) / shininess (bigger = smaller, sharper highlight) | ||
| 11 | |||
| 12 | uniform vec3 uLightPos; // 光の位置(ワールド座標) / light position (world space) | ||
| 13 | uniform vec3 uLightColor; // 光の色と明るさ / light colour and brightness | ||
| 14 | uniform vec3 uAmbient; // 環境光の色と明るさ / ambient light colour and brightness | ||
| 15 | uniform vec3 uViewPos; // カメラの位置(ワールド座標) / camera position (world space) | ||
| 16 | |||
| 17 | // 0 = 全部、1 = 環境光だけ、2 = 拡散反射だけ、3 = 鏡面反射だけ、4 = 法線を色で | ||
| 18 | // 0 = everything, 1 = ambient only, 2 = diffuse only, 3 = specular only, 4 = normals as colours | ||
| 19 | uniform int uViewMode; | ||
| 20 | |||
| 21 | layout(location = 0) out vec4 out_color; | ||
| 22 | |||
| 23 | void main() { | ||
| 24 | vec3 albedo = uObjectColor * texture(uTexture0, vUv).rgb; | ||
| 25 | |||
| 26 | // 補間された法線は短くなるので正規化し直す / interpolated normals get shorter: normalize again | ||
| 27 | vec3 n = normalize(vNormal); | ||
| 28 | vec3 l = normalize(uLightPos - vWorldPos); // 面から光へ / from the surface towards the light | ||
| 29 | vec3 v = normalize(uViewPos - vWorldPos); // 面から目へ / from the surface towards the eye | ||
| 30 | |||
| 31 | // 環境光:どこからともなく来る弱い光 / ambient: weak light coming from everywhere | ||
| 32 | vec3 ambient = uAmbient * albedo; | ||
| 33 | |||
| 34 | // 拡散反射(ランバート):光に向いているほど明るい / diffuse (Lambert): brighter the more it faces the light | ||
| 35 | float diff = max(dot(n, l), 0.0); | ||
| 36 | vec3 diffuse = diff * albedo * uLightColor; | ||
| 37 | |||
| 38 | // 鏡面反射(Blinn-Phong):ハーフベクトルが法線に近いほど明るい / specular (Blinn-Phong): bright where the half vector is close to n | ||
| 39 | float spec = 0.0; | ||
| 40 | if (diff > 0.0) { // 裏から照らされた面にハイライトは出ない / no highlight on surfaces lit from behind | ||
| 41 | vec3 h = normalize(l + v); | ||
| 42 | spec = pow(max(dot(n, h), 0.0), uShininess); | ||
| 43 | } | ||
| 44 | vec3 specular = uSpecularStrength * spec * uLightColor; | ||
| 45 | |||
| 46 | vec3 color = ambient + diffuse + specular; | ||
| 47 | if (uViewMode == 1) color = ambient; | ||
| 48 | else if (uViewMode == 2) color = diffuse; | ||
| 49 | else if (uViewMode == 3) color = specular; | ||
| 50 | else if (uViewMode == 4) color = n * 0.5 + 0.5; // -1〜1を0〜1に / map -1..1 to 0..1 | ||
| 51 | out_color = vec4(color, 1.0); | ||
| 52 | } | ||
ファイル: /dev/null | b/shaders/phong.vert
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,22 @@ | |||
| 1 | #version 460 core | ||
| 2 | layout(location = 0) in vec3 aPosition; | ||
| 3 | layout(location = 1) in vec3 aNormal; // 面の向き(モデル座標) / which way the surface faces (model space) | ||
| 4 | layout(location = 2) in vec2 aUv; | ||
| 5 | |||
| 6 | uniform mat4 uModel; | ||
| 7 | uniform mat4 uView; | ||
| 8 | uniform mat4 uProj; | ||
| 9 | uniform mat3 uNormalMatrix; // 法線をワールド座標へ(モデル行列の逆行列の転置) / normals to world space (inverse transpose of uModel) | ||
| 10 | |||
| 11 | // ライティングはワールド座標で計算する / lighting is computed in world space | ||
| 12 | out vec3 vWorldPos; | ||
| 13 | out vec3 vNormal; | ||
| 14 | out vec2 vUv; | ||
| 15 | |||
| 16 | void main() { | ||
| 17 | vec4 world = uModel * vec4(aPosition, 1.0); | ||
| 18 | vWorldPos = world.xyz; | ||
| 19 | vNormal = uNormalMatrix * aNormal; // 正規化はフラグメントシェーダーで / normalized in the fragment shader | ||
| 20 | vUv = aUv; | ||
| 21 | gl_Position = uProj * uView * world; | ||
| 22 | } | ||
ファイル: a/shaders/textured.frag | /dev/null
| 前 | 新 | ||
|---|---|---|---|
| @@ -1,22 +0,0 @@ | |||
| 1 | #version 460 core | ||
| 2 | in vec2 vUv; | ||
| 3 | |||
| 4 | // テクスチャユニット0と1から読む(C++側はTexture2D::bind(0)、bind(1)) | ||
| 5 | // read from texture units 0 and 1 (C++ side: Texture2D::bind(0), bind(1)) | ||
| 6 | layout(binding = 0) uniform sampler2D uTexture0; | ||
| 7 | layout(binding = 1) uniform sampler2D uTexture1; | ||
| 8 | |||
| 9 | uniform float uMix; // 二枚目をどれだけ混ぜるか / how much of the second texture to mix in | ||
| 10 | uniform float uEmblemScale; // 二枚目のUVの拡大率(中心から) / UV scale for the second texture (around the centre) | ||
| 11 | |||
| 12 | layout(location = 0) out vec4 out_color; | ||
| 13 | |||
| 14 | void main() { | ||
| 15 | vec4 base = texture(uTexture0, vUv); | ||
| 16 | // 拡大したUVは0〜1をはみ出す:はみ出した部分はラップモードで決まる | ||
| 17 | // the scaled UVs leave 0..1: what appears there is decided by the wrap mode | ||
| 18 | vec2 emblemUv = (vUv - 0.5) * uEmblemScale + 0.5; | ||
| 19 | vec4 emblem = texture(uTexture1, emblemUv); | ||
| 20 | // 二枚目のアルファで混ぜる / blend by the second texture's alpha | ||
| 21 | out_color = vec4(mix(base.rgb, emblem.rgb, emblem.a * uMix), 1.0); | ||
| 22 | } | ||
ファイル: a/shaders/textured.vert | /dev/null
| 前 | 新 | ||
|---|---|---|---|
| @@ -1,15 +0,0 @@ | |||
| 1 | #version 460 core | ||
| 2 | layout(location = 0) in vec3 aPosition; | ||
| 3 | layout(location = 2) in vec2 aUv; // 1番は第10章の法線のために空けておく / location 1 is kept free for the normal (chapter 10) | ||
| 4 | |||
| 5 | uniform mat4 uModel; // モデル座標 → ワールド座標 / model space → world space | ||
| 6 | uniform mat4 uView; // ワールド座標 → ビュー座標(カメラから見た座標) / world space → view space (seen from the camera) | ||
| 7 | uniform mat4 uProj; // ビュー座標 → クリップ座標(透視投影) / view space → clip space (perspective) | ||
| 8 | |||
| 9 | out vec2 vUv; | ||
| 10 | |||
| 11 | void main() { | ||
| 12 | vUv = aUv; | ||
| 13 | // 行列は右から順に効く:モデル → ビュー → 投影 / matrices apply right to left: model → view → projection | ||
| 14 | gl_Position = uProj * uView * uModel * vec4(aPosition, 1.0); | ||
| 15 | } | ||
ファイル: /dev/null | b/shaders/unlit.frag
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,9 @@ | |||
| 1 | #version 460 core | ||
| 2 | // ライティングなしの一色(光源の目印用) / one colour without lighting (for light markers) | ||
| 3 | uniform vec3 uColor; | ||
| 4 | |||
| 5 | layout(location = 0) out vec4 out_color; | ||
| 6 | |||
| 7 | void main() { | ||
| 8 | out_color = vec4(uColor, 1.0); | ||
| 9 | } | ||
ファイル: /dev/null | b/shaders/unlit.vert
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,10 @@ | |||
| 1 | #version 460 core | ||
| 2 | layout(location = 0) in vec3 aPosition; | ||
| 3 | |||
| 4 | uniform mat4 uModel; | ||
| 5 | uniform mat4 uView; | ||
| 6 | uniform mat4 uProj; | ||
| 7 | |||
| 8 | void main() { | ||
| 9 | gl_Position = uProj * uView * uModel * vec4(aPosition, 1.0); | ||
| 10 | } | ||
ファイル: a/src/main.cc | b/src/main.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -1,25 +1,29 @@ | |||
| 1 | // 第9章:カメラ | 1 | // 第10章:色とフォンライティング |
| 2 | // Chapter 9: the camera | 2 | // Chapter 10: colors and Phong lighting |
| 3 | // | 3 | // |
| 4 | // 操作 / Controls: | 4 | // 操作 / Controls: |
| 5 | // WASD 前後左右に移動 / move forward, back, left, right | 5 | // WASD 前後左右に移動 / move forward, back, left, right |
| 6 | // Space / Ctrl 上昇・下降 / move up / down | 6 | // Space / Ctrl 上昇・下降 / move up / down |
| 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 ズーム(FPSは視野角、オービットは距離) / zoom (FPS: field of view, orbit: distance) | 9 | // ホイール / wheel ズーム / zoom |
| 10 | // C FPS ⇔ オービットカメラ / FPS ⇔ orbit camera | 10 | // C FPS ⇔ オービットカメラ / FPS ⇔ orbit camera |
| 11 | // V 表示:全部 → 環境光 → 拡散 → 鏡面 → 法線 / view: all → ambient → diffuse → specular → normals | ||
| 12 | // L 光の色を切り替える / cycle the light colour | ||
| 13 | // P 光を止める・動かす / pause / resume the light | ||
| 14 | // N 法線行列のオン・オフ(オフ=間違った法線) / normal matrix on / off (off = wrong normals) | ||
| 11 | // Tab カーソルのキャプチャ切り替え / toggle cursor capture | 15 | // Tab カーソルのキャプチャ切り替え / toggle cursor capture |
| 12 | // R シェーダーを読み直す / reload the shaders | 16 | // R シェーダーを読み直す / reload the shaders |
| 13 | // Esc 終了 / quit | 17 | // Esc 終了 / quit |
| 14 | #include "camera.hh" | 18 | #include "camera.hh" |
| 19 | #include "mathx.hh" | ||
| 15 | #include "mesh.hh" | 20 | #include "mesh.hh" |
| 16 | #include "shader.hh" | 21 | #include "shader.hh" |
| 17 | #include "shapes.hh" | 22 | #include "shapes.hh" |
| 18 | #include "texture.hh" | 23 | #include "texture.hh" |
| 19 | #include "window.hh" | 24 | #include "window.hh" |
| 20 | 25 | ||
| 21 | #include <linalg.hh> | 26 | #include <cmath> |
| 22 | |||
| 23 | #include <cstdio> | 27 | #include <cstdio> |
| 24 | #include <optional> | 28 | #include <optional> |
| 25 | 29 | ||
| @@ -39,20 +43,35 @@ static const CrateInfo kCrates[] = { | |||
| 39 | {{9.0f, 0.0f, -12.0f}, 2.5f, 0.7f}, {{-2.5f, 0.0f, 5.5f}, 0.6f, 0.5f}, | 43 | {{9.0f, 0.0f, -12.0f}, 2.5f, 0.7f}, {{-2.5f, 0.0f, 5.5f}, 0.6f, 0.5f}, |
| 40 | }; | 44 | }; |
| 41 | 45 | ||
| 46 | // Lキーで切り替える光の色 / light colours cycled with the L key | ||
| 47 | static const Vec3 kLightColors[] = { | ||
| 48 | {1.0f, 1.0f, 1.0f}, // 白 / white | ||
| 49 | {1.0f, 0.72f, 0.42f}, // 電球の色 / warm bulb | ||
| 50 | {0.35f, 1.0f, 0.45f}, // 緑 / green | ||
| 51 | {0.45f, 0.55f, 1.0f}, // 青 / blue | ||
| 52 | }; | ||
| 53 | |||
| 54 | static const char *const kViewModeNames[] = {"all", "ambient", "diffuse", "specular", "normals"}; | ||
| 55 | |||
| 42 | int main() { | 56 | int main() { |
| 43 | Window window; | 57 | Window window; |
| 44 | if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 9")) return 1; | 58 | if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 10")) return 1; |
| 45 | 59 | ||
| 46 | std::optional<Shader> shader = Shader::load("shaders/textured.vert", "shaders/textured.frag"); | 60 | std::optional<Shader> phong = Shader::load("shaders/phong.vert", "shaders/phong.frag"); |
| 61 | std::optional<Shader> unlit = Shader::load("shaders/unlit.vert", "shaders/unlit.frag"); | ||
| 47 | std::optional<Texture2D> crate = Texture2D::load("assets/textures/crate.png"); | 62 | std::optional<Texture2D> crate = Texture2D::load("assets/textures/crate.png"); |
| 48 | std::optional<Texture2D> emblem = Texture2D::load("assets/textures/emblem.png"); | ||
| 49 | std::optional<Texture2D> floorTexture = Texture2D::load("assets/textures/floor.png"); | 63 | std::optional<Texture2D> floorTexture = Texture2D::load("assets/textures/floor.png"); |
| 50 | if (!shader || !crate || !emblem || !floorTexture) return 1; | 64 | if (!phong || !unlit || !crate || !floorTexture) return 1; |
| 51 | glEnable(GL_DEPTH_TEST); | 65 | glEnable(GL_DEPTH_TEST); |
| 52 | 66 | ||
| 67 | // 1×1の白いテクスチャ:テクスチャのない物はuObjectColorだけで色が決まる | ||
| 68 | // A 1×1 white texture: objects without a texture get their colour from uObjectColor alone | ||
| 69 | const unsigned char whitePixel[4] = {255, 255, 255, 255}; | ||
| 70 | Texture2D white = Texture2D::fromPixels(whitePixel, 1, 1, {.flipY = false, .mipmaps = false}); | ||
| 71 | |||
| 53 | Camera fps; | 72 | Camera fps; |
| 54 | fps.position = {0.0f, 1.6f, 7.0f}; // 目の高さ / eye height | 73 | fps.position = {0.5f, 2.4f, 8.5f}; |
| 55 | fps.pitch = radians(-8.0f); | 74 | fps.pitch = radians(-14.0f); |
| 56 | 75 | ||
| 57 | OrbitCamera orbit; | 76 | OrbitCamera orbit; |
| 58 | orbit.target = {0.0f, 0.8f, 0.0f}; | 77 | orbit.target = {0.0f, 0.8f, 0.0f}; |
| @@ -60,24 +79,41 @@ int main() { | |||
| 60 | orbit.yaw = radians(30.0f); | 79 | orbit.yaw = radians(30.0f); |
| 61 | 80 | ||
| 62 | bool useOrbit = false; | 81 | bool useOrbit = false; |
| 63 | window.setCursorCaptured(true); // FPSはカーソルを隠して固定 / FPS: hide and lock the cursor | 82 | int viewMode = 0; |
| 83 | int lightColorIndex = 0; | ||
| 84 | bool lightMoving = true; | ||
| 85 | bool useNormalMatrix = true; | ||
| 86 | float lightTime = 0.0f; // 光の動きの時間(止められる) / time for the light's motion (can be paused) | ||
| 87 | window.setCursorCaptured(true); | ||
| 64 | 88 | ||
| 65 | window.onKey = [&](int key, int action, int /*mods*/) { | 89 | window.onKey = [&](int key, int action, int /*mods*/) { |
| 66 | if (action != GLFW_PRESS) return; | 90 | if (action != GLFW_PRESS) return; |
| 67 | if (key == GLFW_KEY_ESCAPE) window.close(); | 91 | if (key == GLFW_KEY_ESCAPE) window.close(); |
| 68 | if (key == GLFW_KEY_R && shader->reload()) printf("シェーダーを読み直した / shaders reloaded\n"); | 92 | if (key == GLFW_KEY_R) { |
| 93 | bool ok = phong->reload(); | ||
| 94 | ok = unlit->reload() && ok; // 両方とも読み直す / reload both, even if the first one failed | ||
| 95 | if (ok) printf("シェーダーを読み直した / shaders reloaded\n"); | ||
| 96 | } | ||
| 69 | if (key == GLFW_KEY_TAB) window.setCursorCaptured(!window.cursorCaptured()); | 97 | if (key == GLFW_KEY_TAB) window.setCursorCaptured(!window.cursorCaptured()); |
| 70 | if (key == GLFW_KEY_C) { | 98 | if (key == GLFW_KEY_C) { |
| 71 | useOrbit = !useOrbit; | 99 | useOrbit = !useOrbit; |
| 72 | // オービットはマウスでドラッグするのでカーソルを見せる / orbit is dragged with the mouse, so show the cursor | ||
| 73 | window.setCursorCaptured(!useOrbit); | 100 | window.setCursorCaptured(!useOrbit); |
| 74 | printf("camera: %s\n", useOrbit ? "orbit" : "fps"); | 101 | printf("camera: %s\n", useOrbit ? "orbit" : "fps"); |
| 75 | } | 102 | } |
| 103 | if (key == GLFW_KEY_V) { | ||
| 104 | viewMode = (viewMode + 1) % 5; | ||
| 105 | printf("view: %s\n", kViewModeNames[viewMode]); | ||
| 106 | } | ||
| 107 | if (key == GLFW_KEY_L) lightColorIndex = (lightColorIndex + 1) % 4; | ||
| 108 | if (key == GLFW_KEY_P) lightMoving = !lightMoving; | ||
| 109 | if (key == GLFW_KEY_N) { | ||
| 110 | useNormalMatrix = !useNormalMatrix; | ||
| 111 | printf("normal matrix: %s\n", useNormalMatrix ? "on" : "off (mat3(uModel))"); | ||
| 112 | } | ||
| 76 | }; | 113 | }; |
| 77 | 114 | ||
| 78 | Mesh cube = makeCube(); | 115 | Mesh cube = makeCube(); |
| 79 | // 40×40の床。テクスチャにタイル4枚なので10回繰り返すと1タイル = 1単位 | 116 | Mesh sphere = makeSphere(); |
| 80 | // A 40 × 40 floor. The texture holds 4 tiles, so repeating it 10 times makes one tile = one unit | ||
| 81 | Mesh floorMesh = makePlane(40.0f, 10.0f); | 117 | Mesh floorMesh = makePlane(40.0f, 10.0f); |
| 82 | 118 | ||
| 83 | double lastTime = window.time(); | 119 | double lastTime = window.time(); |
| @@ -94,8 +130,6 @@ int main() { | |||
| 94 | } else { | 130 | } else { |
| 95 | if (window.cursorCaptured()) fps.turn(mouse.x, mouse.y); | 131 | if (window.cursorCaptured()) fps.turn(mouse.x, mouse.y); |
| 96 | fps.zoom(window.scrollDelta()); | 132 | fps.zoom(window.scrollDelta()); |
| 97 | |||
| 98 | // キーからローカルな移動方向を作る(x = 右、y = 上、z = 前) / build a local direction from the keys | ||
| 99 | Vec3 dir; | 133 | Vec3 dir; |
| 100 | if (window.keyDown(GLFW_KEY_W)) dir.z += 1.0f; | 134 | if (window.keyDown(GLFW_KEY_W)) dir.z += 1.0f; |
| 101 | if (window.keyDown(GLFW_KEY_S)) dir.z -= 1.0f; | 135 | if (window.keyDown(GLFW_KEY_S)) dir.z -= 1.0f; |
| @@ -104,37 +138,69 @@ int main() { | |||
| 104 | if (window.keyDown(GLFW_KEY_SPACE)) dir.y += 1.0f; | 138 | if (window.keyDown(GLFW_KEY_SPACE)) dir.y += 1.0f; |
| 105 | if (window.keyDown(GLFW_KEY_LEFT_CONTROL)) dir.y -= 1.0f; | 139 | if (window.keyDown(GLFW_KEY_LEFT_CONTROL)) dir.y -= 1.0f; |
| 106 | fps.speed = window.keyDown(GLFW_KEY_LEFT_SHIFT) ? 9.0f : 3.0f; | 140 | fps.speed = window.keyDown(GLFW_KEY_LEFT_SHIFT) ? 9.0f : 3.0f; |
| 107 | // dtを掛けるのでフレームレートに関係なく同じ速さ / multiplied by dt: the same speed at any frame rate | ||
| 108 | fps.move(dir, dt); | 141 | fps.move(dir, dt); |
| 109 | } | 142 | } |
| 110 | 143 | ||
| 144 | // 光は箱の山の周りを回り、少し上下する / the light circles the pile of crates, bobbing up and down a little | ||
| 145 | if (lightMoving) lightTime += dt; | ||
| 146 | Vec3 lightPos = {3.5f * std::sin(0.7f * lightTime), 2.6f + 0.6f * std::sin(1.3f * lightTime), | ||
| 147 | 3.5f * std::cos(0.7f * lightTime)}; | ||
| 148 | Vec3 lightColor = kLightColors[lightColorIndex]; | ||
| 149 | |||
| 111 | Mat4 view = useOrbit ? orbit.view() : fps.view(); | 150 | Mat4 view = useOrbit ? orbit.view() : fps.view(); |
| 112 | Mat4 proj = useOrbit ? orbit.projection(window.aspect()) : fps.projection(window.aspect()); | 151 | Mat4 proj = useOrbit ? orbit.projection(window.aspect()) : fps.projection(window.aspect()); |
| 152 | Vec3 viewPos = useOrbit ? orbit.position() : fps.position; | ||
| 113 | 153 | ||
| 114 | glClearColor(0.10f, 0.15f, 0.25f, 1.0f); | 154 | glClearColor(0.10f, 0.15f, 0.25f, 1.0f); |
| 115 | glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); | 155 | glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); |
| 116 | 156 | ||
| 117 | shader->use(); | 157 | // 一つの物を描く:モデル行列と法線行列、物体の色、光沢 / draws one object: model and normal matrix, colour, shininess |
| 118 | shader->set("uView", view); | 158 | auto drawLit = [&](const Mesh &mesh, const Mat4 &model, Vec3 color, float specular, float shininess) { |
| 119 | shader->set("uProj", proj); | 159 | phong->set("uModel", model); |
| 120 | shader->set("uEmblemScale", 1.0f); | 160 | // 法線行列なしだと一様でない拡大縮小で法線が傾く / without the normal matrix, non-uniform scaling tilts the normals |
| 121 | 161 | phong->set("uNormalMatrix", useNormalMatrix ? normalMatrix(model) : toMat3(model)); | |
| 122 | // 床:二枚目のテクスチャは混ぜない / the floor: no second texture | 162 | phong->set("uObjectColor", color); |
| 163 | phong->set("uSpecularStrength", specular); | ||
| 164 | phong->set("uShininess", shininess); | ||
| 165 | mesh.draw(); | ||
| 166 | }; | ||
| 167 | |||
| 168 | phong->use(); | ||
| 169 | phong->set("uView", view); | ||
| 170 | phong->set("uProj", proj); | ||
| 171 | phong->set("uViewPos", viewPos); | ||
| 172 | phong->set("uLightPos", lightPos); | ||
| 173 | phong->set("uLightColor", lightColor); | ||
| 174 | phong->set("uAmbient", Vec3{0.15f, 0.15f, 0.15f}); | ||
| 175 | phong->set("uViewMode", viewMode); | ||
| 176 | |||
| 177 | // 床:石は少しだけ光る / the floor: stone is only slightly shiny | ||
| 123 | floorTexture->bind(0); | 178 | floorTexture->bind(0); |
| 124 | emblem->bind(1); | 179 | drawLit(floorMesh, Mat4::identity(), {1.0f, 1.0f, 1.0f}, 0.15f, 16.0f); |
| 125 | shader->set("uMix", 0.0f); | ||
| 126 | shader->set("uModel", Mat4::identity()); | ||
| 127 | floorMesh.draw(); | ||
| 128 | 180 | ||
| 129 | // 箱:立方体は原点が中心なので半分持ち上げて床に置く / crates: the cube is centred, so lift it by half its size | 181 | // 箱 / crates |
| 130 | crate->bind(0); | 182 | crate->bind(0); |
| 131 | shader->set("uMix", 0.8f); | ||
| 132 | for (const CrateInfo &c : kCrates) { | 183 | for (const CrateInfo &c : kCrates) { |
| 133 | Vec3 centre = c.position + Vec3{0.0f, 0.5f * c.size, 0.0f}; | 184 | Vec3 centre = c.position + Vec3{0.0f, 0.5f * c.size, 0.0f}; |
| 134 | shader->set("uModel", translate(centre) * rotateY(c.angle) * scale({c.size, c.size, c.size})); | 185 | drawLit(cube, translate(centre) * rotateY(c.angle) * scale({c.size, c.size, c.size}), {1.0f, 1.0f, 1.0f}, 0.3f, |
| 135 | cube.draw(); | 186 | 32.0f); |
| 136 | } | 187 | } |
| 137 | 188 | ||
| 189 | // テクスチャなしの球二つ:色はuObjectColorだけ。二つ目は一様でない拡大縮小(楕円体) | ||
| 190 | // Two untextured spheres: the colour is uObjectColor alone. The second one is scaled non-uniformly (an ellipsoid) | ||
| 191 | white.bind(0); | ||
| 192 | drawLit(sphere, translate({2.6f, 0.7f, 2.2f}) * scale({1.4f, 1.4f, 1.4f}), {1.0f, 0.35f, 0.25f}, 0.6f, 64.0f); | ||
| 193 | drawLit(sphere, translate({-1.8f, 0.45f, 2.4f}) * rotateY(radians(35.0f)) * scale({2.2f, 0.9f, 1.1f}), | ||
| 194 | {0.3f, 0.5f, 1.0f}, 0.6f, 64.0f); | ||
| 195 | |||
| 196 | // 光源の目印:光の色そのまま、ライティングなし / the light's marker: the light colour itself, unlit | ||
| 197 | unlit->use(); | ||
| 198 | unlit->set("uView", view); | ||
| 199 | unlit->set("uProj", proj); | ||
| 200 | unlit->set("uModel", translate(lightPos) * scale({0.2f, 0.2f, 0.2f})); | ||
| 201 | unlit->set("uColor", lightColor); | ||
| 202 | cube.draw(); | ||
| 203 | |||
| 138 | window.swapBuffers(); | 204 | window.swapBuffers(); |
| 139 | } | 205 | } |
| 140 | return 0; | 206 | return 0; |
ファイル: /dev/null | b/src/mathx.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,25 @@ | |||
| 1 | // linalg.hhに無いものを足す(ダウンロードしたlinalg.hh自体は編集しない) | ||
| 2 | // Additions to linalg.hh (the downloaded linalg.hh itself is never edited) | ||
| 3 | #pragma once | ||
| 4 | |||
| 5 | #include <linalg.hh> | ||
| 6 | |||
| 7 | // 3×3行列。列優先:c[列]が一つの列ベクトル(Mat4と同じ)。法線行列に使う。 | ||
| 8 | // 3×3 matrix. Column-major: c[column] is one column vector (like Mat4). Used for the normal matrix. | ||
| 9 | struct Mat3 { | ||
| 10 | Vec3 c[3]; | ||
| 11 | }; | ||
| 12 | |||
| 13 | // 4×4行列の左上3×3(回転と拡大縮小の部分、平行移動は捨てる) | ||
| 14 | // The upper-left 3×3 of a 4×4 matrix (the rotation and scale part; the translation is dropped) | ||
| 15 | inline Mat3 toMat3(const Mat4 &m) { | ||
| 16 | Mat3 r; | ||
| 17 | for (int i = 0; i < 3; ++i) r.c[i] = {m.c[i].x, m.c[i].y, m.c[i].z}; | ||
| 18 | return r; | ||
| 19 | } | ||
| 20 | |||
| 21 | // 法線行列:モデル行列の逆行列の転置の左上3×3(線型代数 第10章)。 | ||
| 22 | // 一様でない拡大縮小があっても、変換した法線が面に垂直なままになる。 | ||
| 23 | // The normal matrix: the upper-left 3×3 of the model matrix's inverse transpose (Linear Algebra chapter 10). | ||
| 24 | // Transformed normals stay perpendicular to the surface even with non-uniform scaling. | ||
| 25 | inline Mat3 normalMatrix(const Mat4 &model) { return toMat3(transpose(inverse(model))); } | ||
ファイル: a/src/shader.cc | b/src/shader.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -175,6 +175,10 @@ void Shader::set(const char *name, Vec2 v) const { glProgramUniform2f(program, l | |||
| 175 | void Shader::set(const char *name, Vec3 v) const { glProgramUniform3f(program, location(name), v.x, v.y, v.z); } | 175 | void Shader::set(const char *name, Vec3 v) const { glProgramUniform3f(program, location(name), v.x, v.y, v.z); } |
| 176 | void Shader::set(const char *name, Vec4 v) const { glProgramUniform4f(program, location(name), v.x, v.y, v.z, v.w); } | 176 | void Shader::set(const char *name, Vec4 v) const { glProgramUniform4f(program, location(name), v.x, v.y, v.z, v.w); } |
| 177 | 177 | ||
| 178 | void Shader::set(const char *name, const Mat3 &m) const { | ||
| 179 | glProgramUniformMatrix3fv(program, location(name), 1, GL_FALSE, &m.c[0].x); | ||
| 180 | } | ||
| 181 | |||
| 178 | void Shader::set(const char *name, const Mat4 &m) const { | 182 | void Shader::set(const char *name, const Mat4 &m) const { |
| 179 | // linalg.hhは列優先なので転置しない(GL_FALSE) / linalg.hh is column-major, so no transpose (GL_FALSE) | 183 | // linalg.hhは列優先なので転置しない(GL_FALSE) / linalg.hh is column-major, so no transpose (GL_FALSE) |
| 180 | glProgramUniformMatrix4fv(program, location(name), 1, GL_FALSE, &m.c[0].x); | 184 | glProgramUniformMatrix4fv(program, location(name), 1, GL_FALSE, &m.c[0].x); |
ファイル: a/src/shader.hh | b/src/shader.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -1,8 +1,9 @@ | |||
| 1 | // シェーダープログラム / a shader program | 1 | // シェーダープログラム / a shader program |
| 2 | #pragma once | 2 | #pragma once |
| 3 | 3 | ||
| 4 | #include "mathx.hh" | ||
| 5 | |||
| 4 | #include <glad/glad.h> | 6 | #include <glad/glad.h> |
| 5 | #include <linalg.hh> | ||
| 6 | 7 | ||
| 7 | #include <optional> | 8 | #include <optional> |
| 8 | #include <string> | 9 | #include <string> |
| @@ -37,6 +38,7 @@ public: | |||
| 37 | void set(const char *name, Vec2 value) const; | 38 | void set(const char *name, Vec2 value) const; |
| 38 | void set(const char *name, Vec3 value) const; | 39 | void set(const char *name, Vec3 value) const; |
| 39 | void set(const char *name, Vec4 value) const; | 40 | void set(const char *name, Vec4 value) const; |
| 41 | void set(const char *name, const Mat3 &value) const; | ||
| 40 | void set(const char *name, const Mat4 &value) const; | 42 | void set(const char *name, const Mat4 &value) const; |
| 41 | 43 | ||
| 42 | private: | 44 | private: |
ファイル: a/src/shapes.cc | b/src/shapes.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -1,5 +1,6 @@ | |||
| 1 | #include "shapes.hh" | 1 | #include "shapes.hh" |
| 2 | 2 | ||
| 3 | #include <cmath> | ||
| 3 | #include <vector> | 4 | #include <vector> |
| 4 | 5 | ||
| 5 | // 一つの面(正方形)を足す。normal = 外向き、right × up = normal になるように選ぶ。 | 6 | // 一つの面(正方形)を足す。normal = 外向き、right × up = normal になるように選ぶ。 |
| @@ -41,3 +42,30 @@ Mesh makePlane(float size, float uvRepeat) { | |||
| 41 | }; | 42 | }; |
| 42 | return Mesh(vertices, {0, 1, 2, 2, 3, 0}, kVertex3DLayout); | 43 | return Mesh(vertices, {0, 1, 2, 2, 3, 0}, kVertex3DLayout); |
| 43 | } | 44 | } |
| 45 | |||
| 46 | Mesh makeSphere(int segments, int rings) { | ||
| 47 | std::vector<Vertex3D> vertices; | ||
| 48 | std::vector<std::uint32_t> indices; | ||
| 49 | for (int r = 0; r <= rings; ++r) { | ||
| 50 | float phi = PI * static_cast<float>(r) / static_cast<float>(rings); // 0 = 北極、π = 南極 / 0 = north pole, π = south pole | ||
| 51 | for (int s = 0; s <= segments; ++s) { | ||
| 52 | // 継ぎ目の頂点は二重(UVが0と1で違う) / the seam vertices are doubled (u = 0 and u = 1) | ||
| 53 | float theta = 2.0f * PI * static_cast<float>(s) / static_cast<float>(segments); | ||
| 54 | Vec3 n = {std::sin(phi) * std::sin(theta), std::cos(phi), std::sin(phi) * std::cos(theta)}; | ||
| 55 | Vec2 uv = {static_cast<float>(s) / static_cast<float>(segments), 1.0f - static_cast<float>(r) / static_cast<float>(rings)}; | ||
| 56 | vertices.push_back({0.5f * n, n, uv}); | ||
| 57 | } | ||
| 58 | } | ||
| 59 | // 隣り合う二つの輪の間を四角形(三角形2つ)で埋める。極の潰れた三角形は省く。 | ||
| 60 | // Fill between neighbouring rings with quads (two triangles). Skip the degenerate triangles at the poles. | ||
| 61 | std::uint32_t row = static_cast<std::uint32_t>(segments + 1); | ||
| 62 | for (std::uint32_t r = 0; r < static_cast<std::uint32_t>(rings); ++r) { | ||
| 63 | for (std::uint32_t s = 0; s < static_cast<std::uint32_t>(segments); ++s) { | ||
| 64 | std::uint32_t a = r * row + s; // 左上 / top left | ||
| 65 | std::uint32_t b = a + row; // 左下 / bottom left | ||
| 66 | if (r != static_cast<std::uint32_t>(rings) - 1) indices.insert(indices.end(), {a, b, b + 1}); | ||
| 67 | if (r != 0) indices.insert(indices.end(), {a, b + 1, a + 1}); | ||
| 68 | } | ||
| 69 | } | ||
| 70 | return Mesh(vertices, indices, kVertex3DLayout); | ||
| 71 | } | ||
ファイル: a/src/shapes.hh | b/src/shapes.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -12,3 +12,9 @@ Mesh makeCube(); | |||
| 12 | // XZ平面上のsize×sizeの床(y = 0、法線は+Y)。UVはuvRepeat回繰り返す(GL_REPEATが必要)。 | 12 | // XZ平面上のsize×sizeの床(y = 0、法線は+Y)。UVはuvRepeat回繰り返す(GL_REPEATが必要)。 |
| 13 | // A size × size floor on the XZ plane (y = 0, normal +Y). UVs repeat uvRepeat times (needs GL_REPEAT). | 13 | // A size × size floor on the XZ plane (y = 0, normal +Y). UVs repeat uvRepeat times (needs GL_REPEAT). |
| 14 | Mesh makePlane(float size, float uvRepeat); | 14 | Mesh makePlane(float size, float uvRepeat); |
| 15 | |||
| 16 | // 原点を中心とした直径1の球(UV球)。segments = 経度方向の分割数、rings = 緯度方向の分割数。 | ||
| 17 | // 法線は中心から外向き。立方体と同じく外から見て反時計回り。 | ||
| 18 | // A sphere of diameter 1 centred on the origin (a UV sphere). segments = divisions around, rings = from pole to pole. | ||
| 19 | // The normals point outwards from the centre. Counter-clockwise seen from outside, like the cube. | ||
| 20 | Mesh makeSphere(int segments = 32, int rings = 16); | ||
コメント(0)
まだコメントはありません。
ログインするとコメント出来ます。