16. ブレンディングとフェイスカリング
此れ迄、描いたピクセルは全て、フレームバッファに前からあった物を置き換えていました。
第15章の深度テストはフラグメントを書くかどうかを決めましたが、後ろにある物と混ぜる事はさせませんでした。
木や石や漆喰なら其れで良いのですが、ガラス、草、葉、煙、そして全てのユーザーインターフェースには役に立ちません。
此の章では、パイプラインで深度テストのすぐ隣にある2つの機能を扱います。
フェイスカリングは、カメラに背を向けている三角形を、フラグメントの処理が掛かる前に捨てます。
第3章から何故反時計回りの三角形にこだわってきたのかも、やっと此処で分かります。
ブレンディングはフラグメントをフレームバッファに既にある色と混ぜます。
此れで半透明が描ける様になりますが、定番の頭痛の種も2つ付いて来ます:並べ替えと乗算済みアルファです。
其の途中で、第14章で読み込んだまま無視していたglTFの3つのアルファモードと、其れと一緒に来るdoubleSidedフラグを実装します。
16.1 此の章で作る物
第14章のジオラマの前に、花箱付きのステンドグラスの窓を4つ置き、芝生と床に草の株を52個植えます。
窓は新しいモデルwindow.glbで、glTFの3つのアルファモードを一度に全部使います。
白い枠と花箱は不透明、葉はアルファテスト、ガラスはブレンドです。
窓はわざと重ねて置いてあるので、2枚や3枚のガラス越しに見る事になります。
コードでは窓を手前から順に並べていますが、此れもわざとです。
並べ替えを忘れると間違った結果になる様に、です。
4つのキーで、正しいやり方と間違ったやり方を切り替えられます:
- K:フェイスカリング:裏面(此れからは此れが既定)→ なし → 表面 →
glFrontFace(GL_CW)で裏面 - O:半透明の物を遠い順に並べる・配列の順に描く
- B:半透明の物が深度を書く・書かない(
glDepthMask) - G:草:アルファテスト → ストレートアルファでブレンド → 乗算済みアルファでブレンド
- V、C、N、F、P、R、Tab、Esc:第14章と同じ
第15章のデモ(深度の表示、深度関数、Zファイティング、ステンシルでの選択)はmain.ccから無くなりました。
shaders/depth.fragとassets/textures/rug.pngはプロジェクトに残っていますが、使っていません。
第15章のコードからの変更:
src/material.hhとsrc/material.cc:AlphaMode、及びMaterialのalpha、alphaMode、alphaCutoff、doubleSidedsrc/model.hhとsrc/model.cc:glTFのアルファの設定をマテリアルへ、ModelPass(不透明なプリミティブだけ、又は半透明なプリミティブだけを並べ替えて描く)、両面のマテリアルではカリングを切るsrc/texture.hhとsrc/texture.cc:TextureOptions::premultiplyAlphasrc/shapes.hhとsrc/shapes.cc:草の為のmakeCrossedQuads()shaders/phong.frag:アルファ、discard、両面の法線src/main.cc:新しいシーン、カリング、不透明なパスと半透明なパスassets/models/window.glbとassets/textures/grass_blades.png(新規。完成したファイルは章のZIPとアセットのZIPのch16/に入っています)
16.2 フェイスカリング:どちらが表か
考え方
木箱の様な閉じた物には、何時でも2種類の三角形があります。
こちらを向いている側の物と、向こう側でこちらに背を向けている物です。
向こう側の物は何時も手前の物の後ろに隠れていて、何れにせよ深度テストが其のフラグメントを捨てます。
但し其れは、ラスタライザーがフラグメントを作った後で、GPUによってはフラグメントシェーダーが動いた後です。
フェイスカリングは其れをもっと早く、三角形ごと捨てます。
頂点シェーダーの後、角のウィンドウ座標が分かった時点で、ラスタライズの前です。
閉じたメッシュなら、三角形の約半分がラスタライザーに届かなくなります。
GPUは三角形が3Dでどちらを「向いて」いるかを知りません。
見るのは、三角形の角が画面上で現れる順番だけです。
其れがワインディング順(巻き順)です。
インデックスバッファに並んだ順の角が画面上で反時計回りなら、既定では其の三角形は表向きです。
三角形を裏返せば反対側から見る事になるので、同じ角が時計回りになります。
第8章からの全てのメッシュを「外から見て」反時計回りに作ってきたのは此の為で、glTFも同じ事を求めています。
正しく作られたモデルでは、外から見ると全ての表面が反時計回りです。
式
OpenGLは表か裏かを、ウィンドウ座標(ピクセル、原点は左下、yは上向き)での三角形の符号付き面積で決めます。
描く順の角について、此れは2つの辺の外積のz成分の半分です(線型代数 第5章):
なら反時計回り、なら時計回り、は丁度真横から見た三角形で、何れにせよピクセルを覆いません。
仕様書では多角形の辺についての和として書かれていますが、角が3つなら同じ数になります。
計算例として、図の左の三角形:、、。
辺はとです。
なので、平方ピクセル:正、反時計回り、表です。
(此れは本当の面積でもあります。底辺200、高さ150で、の半分です。)
裏から見ると絵は左右反転して、、、になります。
今度の辺はとで、:負、時計回り、裏です。
投影の後に画面上で調べるので、どんな透視でも何時も正しい答えになります。
3Dで調べるなら、面の法線とカメラへの向きの内積が必要で(線型代数 第4章)、そもそも法線が要ります。
画面上の符号なら、頂点シェーダーが既に出した3つの位置だけで済みます。
3つの関数
glEnable(GL_DEPTH_TEST);
// 裏面のカリング:画面上で時計回りに見える三角形(=裏)を描かない
// Back-face culling: triangles that appear clockwise on screen (= seen from behind) are not drawn
glEnable(GL_CULL_FACE);
glEnable(GL_CULL_FACE)/glDisable(GL_CULL_FACE):OpenGLではカリングは既定でオフです。其の為、間違ったワインディングが今迄表に出ませんでした。glCullFace(mode):どちらの面を捨てるか。GL_BACK(既定)、GL_FRONT、又はGL_FRONT_AND_BACK(三角形は全く描かれません。カリングは多角形にしか効かないので、点と線は描かれます)。glFrontFace(mode):どちらのワインディングを表とするか。GL_CCW(既定)又はGL_CW。
あたし達の設定は既定の組み合わせGL_BACKとGL_CCWなので、此の章からは上のglEnable1つで済みます。
Kキーは毎フレーム、他の選択肢を順に切り替えます:
// カリングの設定 / the culling setup
if (cullMode == 1) glDisable(GL_CULL_FACE);
else glEnable(GL_CULL_FACE);
glCullFace(cullMode == 2 ? GL_FRONT : GL_BACK);
glFrontFace(cullMode == 3 ? GL_CW : GL_CCW); // GL_CCW = 反時計回りが表(既定) / counter-clockwise is the front (default)
上の2枚は全く同じで、其れが要点です。
裏面のカリングは、深度テストが何れにせよ隠した三角形だけを取り除きます。
GL_FRONT(左下)では間違った側をカリングしています。
床とジオラマの芝生は上を向いた1枚の板なので完全に消え、地面越しに空が見えます。
木箱と風車の塔は内側を見せます。
奥の壁の内側の面で、間違った側から照らされているので殆ど暗いです。
よくある間違い:
- カリングを有効にしたらモデルが消える、又は内側が見える:其のワインディングは時計回りです(逆の決まりを使うツールや形式から書き出された物か、下で述べる負の拡大縮小で鏡映した物)。Kで確かめて下さい。「表」で正しく見え、「裏」でおかしいなら、ワインディングが逆です。
- 鏡映した物。 行列式が負のモデル行列(線型代数 第10章)、例えばキャラクターを鏡映する為の
scale({-1, 1, 1})は、全ての反時計回りの三角形を画面上で時計回りにします。エンジンは行列式の符号を調べ、其の描画だけglFrontFaceを反転します(glTFも、全体の変換の行列式が負のノードについて其の事をはっきり書いています)。 - 両側から見える必要がある平たい物:草、葉、帆、1枚のガラス。カリングを切る必要があり、其れが次の節の話です。
16.3 両面の表面とgl_FrontFacing
マテリアルが言う所でカリングを切る
glTFのマテリアルにはdoubleSidedフラグがあります(第13章で読み込んでいます)。
仕様は短く正確です。
falseなら裏面のカリングを有効にし、trueならカリングを無効にし、更にライティングの前に裏面の法線を反転しなければなりません。
つまり仕事が2つあり、1つはCPU、1つはシェーダーの物です。
Materialにフラグが加わり、model.ccのphongFromPbrが次の節のアルファの設定と一緒に其れをコピーします:
// 透明の扱いはglTFのまま(第16章) / alpha handling straight from glTF (chapter 16)
p.alpha = m.baseColorFactor.w;
p.alphaMode = m.alphaMode == GltfAlphaMode::Mask ? AlphaMode::Mask
: m.alphaMode == GltfAlphaMode::Blend ? AlphaMode::Blend
: AlphaMode::Opaque;
p.alphaCutoff = m.alphaCutoff;
p.doubleSided = m.doubleSided;
CPUの部分はModelにあります。
Modelは此れから2段階で描きます。
collect()が第14章のdrawNodeと同じくノードの階層をたどりますが、描く物を集めるだけで、drawItems()が其れを描きます(何故かは16.7節で説明します)。
此れがdrawItemsです:
void Model::drawItems(const std::vector<DrawItem> &items, const Shader &shader, const Texture2D *white,
bool normals) const {
bool culling = glIsEnabled(GL_CULL_FACE); // 呼ぶ側の設定を覚えておく / remember the caller's setting
for (const DrawItem &item : items) {
const Primitive &p = *item.primitive;
const MaterialData &md = materialOf(p);
shader.set("uModel", item.world);
if (normals) shader.set("uNormalMatrix", normalMatrix(item.world));
if (white) {
Material m = md.phong;
m.diffuseMap = texture(md.pbr.baseColorTexture.index); // 色 = 係数 × テクスチャ / colour = factor × texture
m.emissionMap = texture(md.pbr.emissiveTexture.index);
m.apply(shader, *white);
}
// 両面のマテリアル(葉、ガラス、帆)は裏からも見えるようにカリングを切る
// Double-sided materials (leaves, glass, sails) must be visible from behind: no culling for them
bool noCull = culling && md.phong.doubleSided;
if (noCull) glDisable(GL_CULL_FACE);
p.mesh.draw();
if (noCull) glEnable(GL_CULL_FACE);
}
}
glIsEnabled(cap)は、glEnable出来る全ての機能についてGL_TRUE又はGL_FALSEを返します。
呼び出し1回につき1度だけ尋ね、呼ぶ側の設定を其の通りに戻します。
呼ぶ側が既にカリングを切っていれば(K)、モデルも切ったままにし、呼ぶ側の知らない所でカリングを入れる事はありません。
uModelとuNormalMatrixはノード毎ではなくプリミティブ毎に設定する様になりました。
並べ替えの後では、続く2つの項目が別々のノードの物かも知れないからです。
第15章のdrawGeometryも同じdrawItemsを通る(white == nullptrで)ので、輪郭や後の影のパスもdoubleSidedを守ります。
ジオラマで両面なのは風車の帆の布だけです(第14章で既に触れました)。
窓では葉とガラスが両面です。
裏側の法線
2つ目の仕事はphong.fragにあります:
Surface s;
s.position = vWorldPos;
s.normal = normalize(vNormal);
// 両面のマテリアルを裏から見ているなら、法線は裏を向く / seen from behind, a double-sided surface's normal points the other way
if (uMaterial.doubleSided && !gl_FrontFacing) s.normal = -s.normal;
gl_FrontFacingはフラグメントシェーダーの組み込みのboolの入力です。
此のフラグメントが属する三角形が表向きならtrueで、判定は上の符号付き面積の規則とglFrontFaceの設定其の物です(点と線では何時もtrue)。
板は頂点毎に1つの法線を持ち、其れは表側から外へ向いています。
裏から見ると其の法線はこちらから離れる向きになり、addLightは見えていない側のライティングを計算してしまいます。
反転すれば、裏側に裏側自身の正しいライティングが付きます。
正面から太陽に照らされたガラスは、回り込んで影の側から見ると暗くなります。
doubleSidedはシェーダーのMaterial構造体ではboolですが、Material::applyはint(doubleSided ? 1 : 0)で設定します。
OpenGLではboolのユニフォームは其の様に設定します(glProgramUniform1i)。
glFrontFace(GL_CW)はglCullFace(GL_FRONT)ではない
カリングの画像の下の段をもう一度見て下さい。
glCullFace(GL_FRONT)もglFrontFace(GL_CW)も、あたし達の反時計回りの三角形を捨てて時計回りの物を残すので、どちらの画像でも残る三角形は同じです。
床が無く、木箱の内側が見えます。
其れなのに右の画像の方が暗いです。
クリーム色に赤い縞だった風車の帆は暗い灰色になり、ガラスと葉も暗くなっています。
違いはgl_FrontFacingです。
glCullFaceはどちらの面を捨てるかを選ぶだけで、「表」の意味は変えません。
glFrontFaceは定義其の物を変え、gl_FrontFacingも其れに従います。
帆の三角形を1つ追ってみましょう。
あたし達は其れを表側から見ているので、画面上で反時計回りです:
| 設定 | カリング? | gl_FrontFacing |
反転の後の法線 | 帆 |
|---|---|---|---|---|
GL_BACK、GL_CCW |
されない(両面) | true | 其のまま、こちら向き | 照らされる |
GL_FRONT、GL_CCW |
されない(両面) | true | 其のまま、こちら向き | 照らされる |
GL_BACK、GL_CW |
されない(両面) | false | 反転、向こう向き | 暗い |
Modelが両面のマテリアルではカリングを切るので、帆がカリングされる事はありません。
しかしGL_CWでは、OpenGLはこちらから見えている側を裏と呼ぶので、シェーダーは既に正しかった法線を反転してしまいます。
太陽が反対側を照らしている様になり、環境光の項だけが残ります。
片面の枠や木箱は反転の影響を受けないので、変わるのは両面のマテリアルだけです。
Kの4つ目のモードは、ワインディングが逆のモデルがあたし達のレンダラーでどう見えるかを丁度表しています。
間違った面がカリングされ、両面の部分は間違った側から照らされます。
其の様なモデルの直し方は、読み込み時に1度インデックスの順番を逆にする(全ての三角形でインデックスを2つ入れ替える)か、glFrontFace(GL_CW)で描く事です。
此れでカリングもgl_FrontFacingも一度に直ります。
表面をカリングしても、直るのはカリングだけです。
草:カリングを切り、法線は上
草はshapes.ccの新しい形です。
縦の板を幾つかY軸の周りに回して真ん中で交差させた物で、植物を描く定番の方法です。
Mesh makeCrossedQuads(int count) {
std::vector<Vertex3D> vertices;
std::vector<std::uint32_t> indices;
Vec3 up = {0.0f, 1.0f, 0.0f};
for (int i = 0; i < count; ++i) {
float a = PI * static_cast<float>(i) / static_cast<float>(count); // 0〜180度(板は両面なので) / 0..180° (quads are two-sided)
Vec3 r = {0.5f * std::cos(a), 0.0f, -0.5f * std::sin(a)}; // 板の右半分 / half the quad, to the right
std::uint32_t first = static_cast<std::uint32_t>(vertices.size());
vertices.push_back({-1.0f * r, up, {0.0f, 0.0f}});
vertices.push_back({r, up, {1.0f, 0.0f}});
vertices.push_back({r + up, up, {1.0f, 1.0f}});
vertices.push_back({up - r, up, {0.0f, 1.0f}});
indices.insert(indices.end(), {first, first + 1, first + 2, first + 2, first + 3, first});
}
return Mesh(vertices, indices, kVertex3DLayout);
}
0°、60°、120°の3枚の板は、どの向きから見ても同じに見えます。
180°は最初の板を裏から見た物になるので、角度はの手前(は含まない)迄です。
各板は1 × 1で、原点は下の辺の真ん中なので、translate(position)で地面に植えられます。
は下にあり、Texture2D::loadの反転と合っています。
法線は全て板の外向きではなく上を向いています。
草の葉は1ピクセルより細い物です。
板の本当の法線で照らすと、太陽が動くにつれて株の1枚が明るく、隣の1枚が真っ黒になります。
地面の法線なら地面と同じライティングになり、遠くから見た芝生は正に其の様に見えます。
又、「上」はどちら側から見ても正しいので、草にはdoubleSidedの反転が要りません。
mainはカリングを切って株を描き、前の状態に戻します:
// 草の株を一つ描く。両面から見える板なのでカリングを切る / draws one grass tuft. The quads are seen from both
// sides, so culling is turned off
auto drawTuft = [&](const Placement &g) {
Mat4 model = translate(g.position) * rotateY(g.angle) * scale({0.75f, 0.75f, 0.75f});
phong->set("uModel", model);
phong->set("uNormalMatrix", normalMatrix(model));
GLboolean culling = glIsEnabled(GL_CULL_FACE);
glDisable(GL_CULL_FACE);
tuftMesh.draw();
if (culling) glEnable(GL_CULL_FACE);
};
52個の位置はmakeGrass()が作ります。
風車、木、木箱、街灯から1.1 m離れた芝生の上の46か所の乱数の位置と、窓の間の床に手で置いた6つの株です。
乱数は<random>ではなく、小さな線型合同法の生成器state = state * 1664525 + 1013904223から取ります。
std::uniform_real_distributionはMSVCとlibstdc++で違う数を出しても良い事になっていて、あたしは皆さんの草をあたしの草と同じ所に生やしたいからです。
16.4 マテリアルのアルファ:glTFの3つのモード
glTFのマテリアルの不透明度はbaseColorFactor.a × baseColorTextureのアルファチャンネルで、alphaModeが其れをどう使うかを決めます:
| alphaMode | 意味 | 使い道 | あたし達のパス |
|---|---|---|---|
OPAQUE(既定) |
アルファを無視し、完全に不透明 | 殆ど全ての物 | 不透明 |
MASK |
アルファalphaCutoff(既定0.5)なら完全に不透明、未満なら完全に透明 |
葉、草、金網、髪の板 | 不透明、discard付き |
BLEND |
アルファで表面と後ろの物を混ぜる(「over」) | ガラス、水、煙、幽霊 | 半透明、並べ替える |
glTFの色はストレートアルファです。
テクスチャのRGBは表面の色其の物で、まだアルファを掛けていません。
其れが何故大事なのかは16.8節で分かります。
material.hhは3つのモードを同じ番号で真似るので、シェーダーでは普通のintとして使えます:
// アルファ(不透明度)の使い方。glTFのalphaModeと同じ。シェーダーでは0/1/2
// How alpha (opacity) is used. Same as glTF's alphaMode; 0/1/2 in the shader
enum class AlphaMode {
Opaque = 0, // アルファを無視して不透明に描く / ignore alpha, draw opaque
Mask = 1, // alphaCutoff未満のピクセルを捨てる(discard)。草、葉、金網 / discard pixels below alphaCutoff: grass, leaves, fences
Blend = 2, // 後ろの色と混ぜる(ブレンディング)。ガラス、煙 / mix with what is behind (blending): glass, smoke
};
そしてMaterialにフィールドが4つ加わります:
float alpha = 1.0f; // 不透明度。diffuseMapのアルファと掛ける / opacity, multiplied with diffuseMap's alpha
AlphaMode alphaMode = AlphaMode::Opaque;
float alphaCutoff = 0.5f; // Maskのしきい値 / the Mask threshold
bool doubleSided = false; // 両面:裏面では法線を反転する(カリングはModelが切る) / double-sided:
// the normal is flipped on back faces (Model turns culling off)
Material::applyが他の値と一緒に其れらを送ります:
shader.set("uMaterial.alpha", alpha);
shader.set("uMaterial.alphaMode", static_cast<int>(alphaMode));
shader.set("uMaterial.alphaCutoff", alphaCutoff);
shader.set("uMaterial.doubleSided", doubleSided ? 1 : 0); // boolのユニフォームはintで設定する / bool uniforms are set as int
phong.fragのMaterial構造体も其れに合わせて大きくなります:
struct Material {
vec3 diffuse; // 拡散反射の色 / diffuse colour
vec3 specular; // 鏡面反射の色と強さ / specular colour and strength
vec3 emission; // 発光の色 / emission colour
float shininess; // 光沢度 / shininess
float alpha; // 不透明度(diffuseマップのアルファと掛ける) / opacity (multiplied with the diffuse map's alpha)
int alphaMode; // 0 = 不透明 / opaque, 1 = マスク / mask (discard), 2 = ブレンド / blend
float alphaCutoff; // マスクのしきい値 / the mask threshold
bool doubleSided; // 裏面では法線を反転する / flip the normal on back faces
};
uniform Material uMaterial;
// C++のAlphaModeと同じ / same as AlphaMode in C++
#define ALPHA_OPAQUE 0
#define ALPHA_MASK 1
#define ALPHA_BLEND 2
既定値(アルファ1、不透明、片面)なら、今迄の全てのマテリアルは前と全く同じに動きます。
窓のモデルの4つのプリミティブで全ての場合が揃います:
| プリミティブ | alphaMode | doubleSided | テクスチャのアルファ |
|---|---|---|---|
| Frame(枠、桟、脚) | OPAQUE |
いいえ | なし |
| FlowerBox | OPAQUE |
いいえ | なし |
| Leaves(交差した板6枚) | MASK、しきい値0.5 |
はい | 葉の形、透明なテクセルに色を滲ませてある |
| Glass(板1枚) | BLEND |
はい | 鉛の線0.92、透明なガラス0.4、色ガラス0.68 |
16.5 discardによるアルファテスト
phong.fragのmainの始めでは、先ずベースカラーを読み、そもそも描く物があるかを決めます:
void main() {
vec4 base = texture(uDiffuseMap, vUv);
float alpha = uMaterial.alpha * base.a;
// マスク:しきい値未満は捨てる(色も深度も書かない)。ブレンド:完全に透明なら深度も書かないように捨てる
// Mask: discard below the threshold (writes neither colour nor depth). Blend: discard fully transparent pixels so
// they do not write depth either
if (uMaterial.alphaMode == ALPHA_MASK && alpha < uMaterial.alphaCutoff) discard;
if (uMaterial.alphaMode == ALPHA_BLEND && alpha < 1.0 / 255.0) discard;
discard(GLSL 第2章)は此のフラグメントのフラグメントシェーダーを終わらせ、何も書きません。
色も深度もステンシルも書きません。
MASKでは其れが技法の全てで、アルファテストと呼ばれます。
しきい値未満ではピクセルは存在せず、其れ以上ではピクセルは深度を書く全く普通の不透明なピクセルです。
不透明なので、アルファテストの形は並べ替えが要らず、他の物と一緒に不透明なパスに入ります。
BLENDも捨てますが、完全に透明な(8ビットのチャンネルの1段未満の)フラグメントだけです。
其れらは色を何れにせよ変えませんが、深度を書いてしまい、後から其の後ろに描かれる半透明の表面を隠してしまいます。
拡散反射の色ではbaseが前のtexture(uDiffuseMap, vUv).rgbの代わりになるので、テクスチャは1回だけ読みます:
s.diffuse = uMaterial.diffuse * base.rgb;
そして出力にやっと意味のあるアルファが入ります。
但しBLENDの時だけです:
// 不透明とマスクはアルファ1。ブレンドだけ本当のアルファを出す / opaque and mask output alpha 1; only blend outputs its alpha
out_color = vec4(color, uMaterial.alphaMode == ALPHA_BLEND ? alpha : 1.0);
不透明とマスクの表面は何時もアルファ1を書きます。
其れでフレームバッファのアルファチャンネルは何処でも1のままになります。
其れは一部のデスクトップでのウィンドウにとって(16.9節)、そしてシーンがテクスチャになる第17章にとって大事です。
mainでは、既定のモードの草は不透明なパスで、モデルの後に描きます:
if (grassMode == 0) {
// アルファテスト:アルファ < 0.5のピクセルを捨てる。ブレンドではないので並べ替えは要らない
// Alpha test: discard pixels with alpha < 0.5. This is not blending, so no sorting is needed
grassMaterial.diffuseMap = &*grassStraight;
grassMaterial.alphaMode = AlphaMode::Mask;
grassMaterial.apply(*phong, white);
for (const Placement &g : grass) drawTuft(g);
}
草のテクスチャは起動時に2回読み込みます。
1回は其のまま、1回は乗算済みで(16.8節)、下の端の葉が上の先に滲まない様に、折り返しはクランプにします:
// 同じ草の画像を二通りに:そのまま(ストレートアルファ)と、乗算済みアルファ
// The same grass image twice: as it is (straight alpha) and premultiplied
std::optional<Texture2D> grassStraight = Texture2D::load("assets/textures/grass_blades.png");
std::optional<Texture2D> grassPremultiplied =
Texture2D::load("assets/textures/grass_blades.png", {.premultiplyAlpha = true});
if (!phong || !floorTexture || !grassStraight || !grassPremultiplied) return 1;
// 草の画像は端まで描かれているので繰り返さない / the grass image reaches its edges: no repeat
grassStraight->setWrap(GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE);
grassPremultiplied->setWrap(GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE);
アルファテストには弱点が3つあり、全て此の章の画像に見えています:
- 硬く、ギザギザの縁。 ピクセルは草か草でないかのどちらかなので、全ての葉の縁が階段になります(16.8節の拡大画像の左)。1ピクセルの中に「半分の草」はありません。標準的な直し方はマルチサンプリングとアルファトゥカバレッジ(
GL_SAMPLE_ALPHA_TO_COVERAGE、第20章)で、並べ替え無しにアルファを覆われたサンプルの割合に変えます。 - 遠くの植物が薄くなる。 ミップマップ(GLSL 第11章)は細い葉のアルファを周りの透明なテクセルと平均します。遠くのミップレベルでは葉のアルファが例えば0.3になり、しきい値を下回って葉が消えます。ゲームで遠くの木が禿げるのは正に此の為です。
- 不透明より遅い。 GPUはフラグメントシェーダーの前に深度テストをして(アーリーZ)、隠れたフラグメントを飛ばしたがります。
discard出来るシェーダーは、フラグメントが深度を書くかどうかを最後にしか決めないので、深度の書き込み(GPUによってはテスト全体)が待たされます。エンジンがアルファテストの物を普通の不透明な物の後に描く理由の1つです。
16.6 ブレンディング:式
ブレンディングは何を計算するか
ブレンディングが有効な時、フレームバッファに届く色はもうフラグメントの色ではありません。
フラグメントの色、つまりソース(アルファ)と、其のピクセルのフレームバッファに既にある色、つまりデスティネーションの組み合わせです:
とはglBlendFuncで選ぶブレンド係数で、はglBlendEquationで選ぶブレンド式です。
ブレンディングはフラグメントシェーダーと深度テストの後に、ピクセル毎に、固定機能のハードウェアで行われます。
シェーダーはデスティネーションを読めず、とを渡すだけです。
普通の半透明(「此のガラスは後ろからの光の60%を通す」)では、係数はとです:
此れはデスティネーションからソースへの線型補間で、GLSL 第3章のmix(dst, src, alpha)です。
PorterとDuff(1984)は此れをover演算子と呼びました。
ソースをデスティネーションの上に、という意味です。
glTFのBLENDが意味するのも此れです。
計算例:あたし達のガラスの透明な部分で、ライティング後に、、其の後ろに草:
草が透けて見え、薄い青に色付きます。
glBlendFunc、glBlendFuncSeparate、glBlendEquation
glEnable(GL_BLEND)でブレンディングがオンになります。既定ではオフで、此の節の他の物も全て、有効にする迄は効きません。glBlendFunc(sfactor, dfactor)は4つのチャンネル全てにとを設定します。既定はGL_ONEとGL_ZEROで、「結果 = ソース」という意味です。係数を設定せずにブレンディングを有効にしても何も変わりません。glBlendFuncSeparate(srcRGB, dstRGB, srcAlpha, dstAlpha)は、色のチャンネルとアルファのチャンネルに別々の係数を設定します。glBlendEquation(mode)は2つの項の組み合わせ方を選びます(glBlendEquationSeparateはRGBとアルファで別々に)。
実際に使う係数:
| 係数 | RGBでの値 | よくある使い道 |
|---|---|---|
GL_ZERO |
0 | 項を消す |
GL_ONE |
1 | 加算の光、乗算済みアルファ |
GL_SRC_ALPHA |
ストレートアルファ(ソース) | |
GL_ONE_MINUS_SRC_ALPHA |
ストレートと乗算済みアルファ(デスティネーション) | |
GL_DST_COLOR |
乗算(「色ガラス」、上から描く影) | |
GL_SRC_COLOR、GL_ONE_MINUS_SRC_COLOR |
、 | チャンネル毎の透過 |
GL_DST_ALPHA、GL_ONE_MINUS_DST_ALPHA |
、 | アルファを持つバッファへの合成 |
GL_CONSTANT_COLOR、GL_CONSTANT_ALPHA(と其のONE MINUS) |
glBlendColorで設定した色 |
描画全体のフェード |
式はGL_FUNC_ADD(、既定)、GL_FUNC_SUBTRACT()、GL_FUNC_REVERSE_SUBTRACT()、GL_MINとGL_MAX(との成分毎の最小又は最大。此の2つは係数を無視します)です。
8ビットのフレームバッファでは、結果は保存の前に0〜1に制限されます。
あたし達の半透明なパスでの設定は次の通りです(周りのループは次の節で):
glEnable(GL_BLEND);
// 結果 = src × srcの係数 + dst × dstの係数(glBlendEquationの既定はGL_FUNC_ADD)
// result = src × src factor + dst × dst factor (glBlendEquation defaults to GL_FUNC_ADD)
glBlendEquation(GL_FUNC_ADD);
if (t.premultiplied) glBlendFuncSeparate(GL_ONE, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
else glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
glDepthMask(GL_TRUE);
glDisable(GL_BLEND);
glBlendEquation(GL_FUNC_ADD)は既定値です。
コードが何に頼っているかを書いておく為にあります。
ブレンディングもOpenGLの他の全てと同じくグローバルな状態なので、半透明なパスの後にまた切ります。
切り忘れると、次のフレームの不透明なパスもブレンドされます。
此処で正しく見えるのは不透明なフラグメントがアルファ1を書くからに過ぎず、其れより小さいアルファを書くシェーダーは後ろの物と混ざってしまいます。
何故アルファの係数を分けるか
色の係数はover演算子です。
最後の2つの引数は、フレームバッファのアルファチャンネルがどうなるかを決めます。
普通のglBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)では、アルファチャンネルも同じ係数でブレンドされます。
不透明なデスティネーション()の上では、あたし達のガラスは次の様になります:
絵は同じに見えますが、フレームバッファは「此のピクセルは76%不透明」と言っていて、其れは間違いです。
ガラスの後ろには不透明な床があります。
アルファにGL_ONE, GL_ONE_MINUS_SRC_ALPHAを使うとになり、後ろに不透明な物がある所ではアルファチャンネルは1のままです。
一般にが「ソースoverデスティネーション」の正しいアルファで、透明なテクスチャに描く時に欲しいのも此れです。
ブレンディングのよくある間違い:
- シェーダーからアルファが来ない。 係数はフラグメントシェーダーの出力のアルファを使います。
vec4(color, 1.0)を書くシェーダーでは、全ての「半透明」の物が不透明になります。 - 不透明な物をブレンドする。 不透明な物はアルファ1を書くか、ブレンディングを切って描くべきです。さもないと其のアルファがフレームバッファに漏れます。
- 複数のレンダーターゲット。
glEnable(GL_BLEND)とglBlendFuncは全ての描画バッファに効きます。glEnablei、glBlendFunci、glBlendEquationiはバッファ毎に設定します(OpenGL 4.0)。フレームバッファが複数のカラーアタッチメントを持つ様になったら(第21章)必要になります。 - 半透明の物を早く描き過ぎる。 ブレンディングはフレームバッファに今ある物と混ぜます。後から描く物は、ブレンディングにとってはガラスの後ろにありません。次の節は此の話です。
16.7 順番が大事:半透明の物の並べ替え
overは交換出来ない
2枚のガラスを重ねてブレンドしてみましょう。
カメラに近い赤と其の後ろの青で、どちらも、背景は白です。
遠い順(先に青):、次に。
近い順(先に赤):、次に。
最後に描いた表面が何時も一番大きな割合(結果の)を取り、前の物にはしか残りません。
其の為、描く順番が、どちらのガラスが手前に見えるかを決めます。
物理的に正しいのは近いガラスが最後に来る方です。
半透明の表面は、全ての不透明な物の後に、遠い物から順に描かなければなりません。
不透明な物は先に描く必要があります。
其れらはガラスが混ざる背景だからです。
ガラスの後ろの木箱を、ガラスの後に描くと考えてみて下さい。
ガラスが深度を書いていれば、ガラスが覆う所で木箱は深度テストに落ち、ガラスには木箱の代わりに空が映ります。
書いていなければ、木箱はテストに通り、ガラスの上に其のまま塗られます。
どちらにしても間違いなので、フレームは2つのパスになります:
- 全ての不透明な物とアルファテストの物を、どんな順番でも。深度テストが前後を決めます。
- 全てのブレンドする物を、遠い順に並べて、ブレンディングをオンにして。
モデルの中での並べ替え
1つのモデルが両方を持つ事もあります。
其れが、Modelが描く前に集める理由です。
第14章の再帰はプリミティブをノードの順に描いていましたが、今はパスで選り分け、半透明なパスでは順番を変える必要があります。
// どのプリミティブを描くか(マテリアルのalphaModeで分ける) / which primitives to draw (split by the material's alphaMode)
enum class ModelPass {
All, // 全部、ファイルの順に / everything, in file order
Opaque, // OpaqueとMask / Opaque and Mask
Transparent, // Blendだけ、カメラから遠い順(ブレンドの設定は呼ぶ側) / Blend only, farthest from the camera first
// (the caller sets up blending)
};
// passのプリミティブだけを描く。Transparentでは、viewPosから各プリミティブの箱の中心までの距離で遠い順に並べる。
// 両面(doubleSided)のマテリアルは、その間だけフェイスカリングを切って描く。
// Draws only the primitives of `pass`. Transparent sorts them back to front by the distance from viewPos to the
// centre of each primitive's box. Double-sided materials are drawn with face culling turned off for that draw.
void draw(const Shader &shader, const Mat4 &transform, const Texture2D &white, ModelPass pass,
Vec3 viewPos = {}) const;
model.hhのprivateの部分には、collectが作る項目があります:
// 描くもの一つ:プリミティブとそのワールド行列 / one thing to draw: a primitive and its world matrix
struct DrawItem {
const Primitive *primitive;
Mat4 world;
float distance; // カメラからの距離(Transparentの並べ替え用) / distance from the camera (for sorting)
};
collectは第14章のdrawNodeから描く部分を除いた物です:
void Model::collect(int node, const Mat4 &parentWorld, const Mat4 &transform, bool hierarchy, ModelPass pass,
Vec3 viewPos, std::vector<DrawItem> &out) const {
const GltfNode &n = nodes[static_cast<size_t>(node)];
// ワールド行列 = 親のワールド行列 × 自分のローカル行列 / world = the parent's world matrix × our local matrix
Mat4 world = (hierarchy ? parentWorld : transform) * n.localTransform();
if (n.mesh >= 0) {
for (const Primitive &p : meshes[static_cast<size_t>(n.mesh)].primitives) {
bool blend = materialOf(p).phong.alphaMode == AlphaMode::Blend;
if ((pass == ModelPass::Opaque && blend) || (pass == ModelPass::Transparent && !blend)) continue;
Vec3 c = 0.5f * (p.boundsMin + p.boundsMax);
Vec4 centre = world * Vec4{c.x, c.y, c.z, 1.0f};
out.push_back({&p, world, length(Vec3{centre.x, centre.y, centre.z} - viewPos)});
}
}
for (int child : n.children) collect(child, world, transform, hierarchy, pass, viewPos, out);
}
プリミティブの距離は、カメラから其のバウンディングボックス(第14章)の中心迄で測ります。
中心はプリミティブのワールド行列でワールド座標に変換します。
OpaqueはOPAQUEとMASKを、TransparentはBLENDを取ります。
新しいdrawは半透明なパスの時だけ並べ替えます:
void Model::draw(const Shader &shader, const Mat4 &transform, const Texture2D &white, ModelPass pass,
Vec3 viewPos) const {
std::vector<DrawItem> items;
for (int root : roots) collect(root, transform, transform, true, pass, viewPos, items);
if (pass == ModelPass::Transparent) {
// 遠いものから描く:手前の半透明が、もう描かれた後ろの色と混ざるように
// Draw the farthest first, so each nearer transparent surface mixes with what is already behind it
std::stable_sort(items.begin(), items.end(),
[](const DrawItem &a, const DrawItem &b) { return a.distance > b.distance; });
}
drawItems(items, shader, &white, true);
}
std::stable_sortは距離が等しい項目をファイルの順のままにするので、中心が同じ2つのプリミティブがフレーム毎に入れ替わってちらつく事がありません。
古いdraw(shader, transform, white, hierarchy)も残っています。
今はModelPass::AllでのcollectとdrawItemsで書かれていて、結果は第14章と同じです。
Modelはブレンドの状態に一切触れません。
どうブレンドするかは呼ぶ側が決め、モデルは何をどの順番で描くかだけを決めます。
シーン全体の並べ替え
1つのモデルの中で並べ替えるだけでは足りません。
4つの窓と(ブレンドのモードでは)52個の草の株は、お互いに並べ替える必要があります。
mainは毎フレーム1つのリストを作ります:
// 描く物の一覧:カメラからの距離、乗算済みアルファか、描く関数 / the list of things to draw: distance from the
// camera, whether it is premultiplied, and a draw function
struct Transparent {
float distance;
bool premultiplied;
std::function<void()> draw;
};
std::vector<Transparent> transparent;
for (const Placement &w : kWindows) {
Mat4 m = translate(w.position) * rotateY(w.angle);
Vec3 centre = w.position + Vec3{0.0f, 0.8f, 0.0f}; // 窓の真ん中 / the middle of the window
transparent.push_back({length(centre - viewPos), false, [&, m] {
windowModel->draw(*phong, m, white, ModelPass::Transparent, viewPos);
}});
}
if (grassMode != 0) {
grassMaterial.diffuseMap = grassMode == 2 ? &*grassPremultiplied : &*grassStraight;
grassMaterial.alphaMode = AlphaMode::Blend;
for (const Placement &g : grass) {
Vec3 centre = g.position + Vec3{0.0f, 0.35f, 0.0f};
transparent.push_back({length(centre - viewPos), grassMode == 2, [&, g] {
grassMaterial.apply(*phong, white); // 窓が別のマテリアルを設定したかも / a window may have set another material
drawTuft(g);
}});
}
}
if (sortTransparent)
std::stable_sort(transparent.begin(), transparent.end(),
[](const Transparent &a, const Transparent &b) { return a.distance > b.distance; });
各項目は距離と其れを描く関数なので、窓と草が1つの並べ替えたリストを共有出来ます。
ラムダは行列や置き場所を値で([&, m]、[&, g])、他の物を参照で捕まえます。
同じフレームの中で呼ばれるので、参照はまだ有効です。
草の項目は毎回マテリアルを設定し直します。
間に描かれた窓が自分のマテリアルを設定しているからです。
不透明なパスで窓はModelPass::Opaqueで描かれたので、此処に残っているのはガラスだけです。
窓の半透明なプリミティブは其々1つだけですが、幾つも持つモデル(ジオラマの木を使う課題)では、Model::drawが此のリストの中の自分の枠の中でプリミティブを並べ替えます。
そしてループです:
if (!blendDepthWrite) glDepthMask(GL_FALSE); // 深度テストはするが、書かない / still depth-test, but do not write
for (const Transparent &t : transparent) {
// ストレートアルファ:色 × α + 後ろ × (1 − α)。乗算済み:色(もう × α済み) + 後ろ × (1 − α)。
// アルファチャンネル自体は後半の2つの係数で1のまま:既定のフレームバッファが半透明にならないように
// Straight alpha: colour × α + behind × (1 − α). Premultiplied: colour (already × α) + behind × (1 − α).
// The last two factors keep the alpha channel at 1, so the default framebuffer does not turn translucent
if (t.premultiplied) glBlendFuncSeparate(GL_ONE, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
else glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
t.draw();
}
glDepthMask(GL_TRUE);
glDisable(GL_BLEND);
半透明の物の深度の書き込み
glDepthMask(flag)(第15章で触れました)は、深度バッファへの書き込みを有効又は無効にします。
深度テストは其のまま行われるので、不透明な壁の後ろの半透明なフラグメントは今迄通り捨てられます。
GL_FALSEは「テストはするが書かない」という意味です。
後で必ずGL_TRUEに戻さなければなりません。
次のフレームの不透明なパスの為だけでなく、glClearがマスクに従うからです。
マスクがGL_FALSEのままだと、glClear(GL_DEPTH_BUFFER_BIT)は何もしません(第15章の落とし穴です)。
全てが正しく並んでいれば、半透明の物が深度を書くかどうかで違いはありません。
手前にある表面の後に、其れより奥の半透明な物が描かれる事は無いからです。
違いが出るのは順番が間違っている時で、OとBのキーで両方の失敗が見られます:
- 並べない、深度を書く(真ん中):
kWindowsは一番近い窓が最初です。其のガラスが最初に描かれて深度を書き、其の後ろの窓のガラスは、手前のガラスが覆う所で深度テストに落ちます。手前の窓越しに他の窓の不透明な枠(不透明なパスで描いた物)は見えますが、ガラスがあるべき所は穴になります。 - 並べない、深度を書かない(右):穴は無く、全てのガラスがブレンドされますが、順番が間違っているので、後ろの窓が手前の窓の上に混ざります。後ろの暗い鉛の線が手前のガラスの上に乗り、遠いガラスが手前にある様に見えます。
多くのエンジンは半透明の物を深度の書き込み無しで描きます。
其の方が、並べ替えの間違いが穴ではなく少し違う色になるだけで済むからです。
深度を書く方にも使い道があります。
自分の中で後ろの物を隠すべき物(腕が体越しに透けて見えてはいけない半透明のキャラクター)は、先に深度だけのパスで描く事が出来ます。
あたし達はBキーで見せる物がある様に、既定では深度を書く様にしています。
並べ替えの限界
中心の点で並べ替えるのは近似で、予想出来る形で失敗します:
- 交差する表面は全く並べられません。 草の株の3枚の板は互いに交差しています。どの板も、中心の片側では他より手前に、反対側では奥にあります。どんな順番を選んでも、各板の半分は間違います。ブレンドのモードのあたし達の株には正に此の問題があり、近くで見ると、葉が切れていたり間違った順番で混ざっていたりします。
- 大きな物と小さな物。 長いガラスの壁と、其の一部の前にある小さな瓶。瓶が手前にある所でも、壁の中心の方が瓶より近い事があります。
- 1つのプリミティブの中の三角形はインデックスバッファの順に描かれ、あたし達は其れを並べ替えていません。閉じた半透明なメッシュ(ガラスの球)では、奥の三角形の一部が手前の三角形の上に見えます。凸な物の定番の技は2回描く事です。先ず
glCullFace(GL_FRONT)で(奥の内側だけ)、次にglCullFace(GL_BACK)で(手前の外側だけ)。課題5で試します。 - コスト。 並べ替えはCPUで毎フレーム行い、半透明の物は其々別の描画になり、順番が合わない他の物とまとめる事が出来ません。
本当の解決策は全く並べ替えません。
結果を順番に依存しない様にします。
概要は16.10節にあります。
一番知られている重み付きブレンドOITの考え方は、足し算と掛け算は順番を気にしない、という事です。
半透明を「over」の連続ではなく和と積として書けば、どんな順番でも同じ絵になります。
16.8 ストレートアルファと乗算済みアルファ
黒い縁
Gを1回押すと、草はストレートアルファでブレンドされます。
縁に暗い輪郭が付きます:
原因はテクスチャで、わざと其の様に作ってあります。
透明なテクセルを黒で保存していて、多くの画像エディターや書き出しツールも同じ事をします。
ストレートアルファでは、完全に透明なテクセルの色は関係無いはずです。
何しろ見えないのですから。
しかしテクセルは1つずつ描かれる訳ではありません。
バイリニアフィルタリングとミップマップ(GLSL 第11章)は隣り合うテクセルを平均し、葉の縁では緑と其の見えない黒を平均します。
計算例:の不透明な緑のテクセルの隣に透明な黒のテクセルがあり、丁度中間でサンプリングするので、其々の重みはです:
灰色の床の上にストレートアルファでブレンドすると:
本当はどうなるべきか。
ピクセルの半分が緑に覆われているので、半分が緑、半分が床で、です。
ストレートの結果が暗いのは、緑が覆う割合で2回重み付けされたからです。
1回はフィルター(黒を混ぜた)で、もう1回はGL_SRC_ALPHAで。
緑の重みはではなくになり、足りない4分の1が黒です。
乗算済みアルファ
直し方は、色を最初からアルファを掛けた形で保存する事です:。
乗算済みの色は「表面から此れだけの光が来る」という意味で、完全に透明なテクセルは、前が何色だったかに関係無く、「光も無く、覆いも無い」です。
over演算子は次の様になります:
此れがglBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA)です。
ソースは既に掛けてあるので、其のまま足します。
例では、フィルタリングしたテクセルはやはりのですが、今度は其れが半分覆われた緑のピクセルの乗算済みの色其の物で、、丁度正しい値です。
此の例だけでなく、一般に正しいです。
フィルターの重みでテクセルを平均する正しいやり方は、各色を実際に其処にある量で重み付けする事です:
乗算済みのテクセルをフィルタリングすると、とが直接計算されます。
正しい平均の乗算済みの形で、GL_ONEが其れを其のまま使います。
ストレートのテクセルをフィルタリングするとが計算され、アルファを無視するので、見えないテクセルの色が漏れ込みます。
乗算済みアルファには他にも利点があり、其の為に合成ソフト、UIツールキット、殆どのエンジンで標準になっています:
- フィルタリング、ミップマップ、拡大縮小が正しい。 縁の埋め合わせも要りません。
- 「over」が結合的になる。 2つの乗算済みの層を先に合わせ、結果を後で合成出来ます(、)。UIの層やパーティクルをテクスチャにまとめる時に必要な性質です。
- 加算と普通のブレンドが1つのモードで。 でRGB の乗算済みの色は純粋に足される光(炎、火花、まぶしさ)で、なら不透明です。1つのブレンド関数で両方が描けるので、両方の種類のパーティクルが1つの並べ替えたバッチを共有出来ます。
読み込み時に乗算する
TextureOptionsにフラグがもう1つ加わります:
// RGBにアルファを掛けてからアップロードする(乗算済みアルファ、第16章)。ミップマップもその値から作られる。
// Multiply RGB by alpha before uploading (premultiplied alpha, chapter 16). Mipmaps are then built from those values.
bool premultiplyAlpha = false;
そしてfromPixels(loadが呼びます)が、アップロードの前にピクセルのコピーに掛け算します:
Texture2D Texture2D::fromPixels(const unsigned char *rgba, int width, int height, const TextureOptions &options) {
int levels = options.mipmaps ? mipLevelCount(width, height) : 1;
Texture2D texture(width, height, options.srgb ? GL_SRGB8_ALPHA8 : GL_RGBA8, levels);
if (options.premultiplyAlpha) {
// 乗算済みアルファ:色 × アルファ。透明なピクセルの色は(何色でも)0になる
// premultiplied alpha: colour × alpha. Transparent pixels become 0 whatever colour they had
std::vector<unsigned char> pm(rgba, rgba + static_cast<size_t>(width) * static_cast<size_t>(height) * 4);
for (size_t i = 0; i < pm.size(); i += 4)
for (size_t c = 0; c < 3; ++c) pm[i + c] = static_cast<unsigned char>((pm[i + c] * pm[i + 3] + 127) / 255);
texture.upload(pm.data());
} else {
texture.upload(rgba);
}
if (options.mipmaps) texture.generateMipmaps();
return texture;
}
8ビットの値では、は整数でになります。
は最大でもで、unsigned char * unsigned charが昇格するintに楽に収まります。
127を足すと、何時も切り捨てるのではなく一番近い値に丸められます。
例えば、ならで、整数の割り算で100になります(なので、100が一番近い値です)。
此処でも順番が大事です。
ミップマップは乗算の後に、乗算済みのレベル0から作るので、全てのレベルが正しく平均されます。
ミップマップを作った後のストレートのテクスチャに乗算しても、小さいレベルには縁が残ります。
シェーダーは変わりません。
s.diffuse = uMaterial.diffuse * base.rgbは今度は乗算済みの色を掛けます。
環境光と拡散反射のライティングはs.diffuseについて線型なので、照らした結果はストレートの色を照らした結果の乗算済みの形になります。
厳密には鏡面反射の項(と発光)にもを掛けるべきですが、草の鏡面反射0.04では見えません。
ガラスでは、ハイライトに掛けないのは寧ろ望ましい事です。
殆ど透明なガラスの上の反射も、暗いガラスの上と同じ明るさであるべきで、ストレートアルファではガラスの鋭いハイライトが40%に暗くなってしまいます。
本物のレンダラーがガラスのシェーダーから乗算済みの色を出すもう1つの理由です。
窓の葉に使ったもう1つの直し方は、そもそも黒を使わない事です。
foliage.bleed()は不透明なテクセルの色を周りの透明なテクセルに写すので(画像エディターではエッジパディング又はダイレーションと呼びます)、フィルタリングは緑と緑を混ぜます。
其れはアルファテストにも役立ちます。
しきい値が0.5より低いと、同じ黒が全ての葉の周りに暗い縁として見えるからです(課題3)。
16.9 フレーム全体とプラットフォームの注意
まとめると、此の章の1フレームは次の通りです:
- カリングのモードを設定し、色と深度をクリアし、カメラとライトを設定する。
- 不透明なパス。順番は自由、ブレンディングはオフ、カリングはオン:床、ジオラマ・木箱・窓の
ModelPass::Opaque(両面の部分はModelの中でカリングを切る)、そして既定の草のモードでは、カリングを切ったアルファテストの草。 - 半透明なパス:窓(とブレンドする草)のリストを作り、遠い順に並べ、ブレンディングを有効にし、必要なら深度の書き込みを切り、各項目を其のブレンド関数で描く。
glDepthMask(GL_TRUE)に戻し、ブレンディングを切る。
此の後の章は此の順番を保ち、間に更にパスを入れます(第18章ではスカイボックスを2と3の間に、第17章ではポストプロセスを4の後に)。
プラットフォームの注意:
- ブレンディングとカリングは何処でも同じです。 バージョン1.0からOpenGLの中核にあり、Windows(Visual Studio)、Linux、FreeBSDのドライバーは同じ結果を出します。スクリーンショットはMesaのllvmpipeで作りましたが、GPUでも全く同じ絵になります。
- 透けて見えるウィンドウ。 既定のフレームバッファのアルファチャンネルが1未満になると、デスクトップによっては其れを使ってウィンドウ其の物を半透明にします。ガラス越しにデスクトップが見えてしまいます(LinuxやFreeBSDの一部のWaylandコンポジターで起きます)。其の為、不透明な表面はアルファ1を書き、ブレンド関数はアルファに
GL_ONE, GL_ONE_MINUS_SRC_ALPHAを使います。Windowsでは既定のフレームバッファのアルファチャンネルは普通無視されるので、此のバグは見逃し易く、他の人のマシンで出てきます。 - 状態のデバッグ。 RenderDoc(WindowsとLinux)は全ての描画呼び出しのブレンド、深度、カリングの状態を見せてくれるので、切り忘れた
glDisable(GL_BLEND)を探すには一番速い方法です。無ければ、glGetIntegerv(GL_CULL_FACE_MODE, …)、glGetIntegerv(GL_FRONT_FACE, …)、glIsEnabled(GL_BLEND)で今の状態を表示出来ます。
16.10 本物のエンジンではどうしているか
- レンダーキューとソートキー。 エンジンはラムダを並べ替えません。全ての描画に64ビットのキーを付け、上位ビットにパス、其の次に(不透明なら)状態の変更を減らす為のシェーダーとマテリアル、そしてアーリーZが隠れたピクセルを捨てられる様に手前から奥への大まかな深度、(半透明なら)奥から手前への深度を入れます。整数の並べ替え1回でフレーム全体の順番が決まります。
- 順番に依存しない半透明(OIT)。 重み付きブレンドOIT(McGuireとBavoil、2013年)は半透明の表面をどんな順番でも2つのターゲットに描きます。加算のブレンドでとを足していく蓄積バッファと、を掛けていく「revealage」バッファです。全画面のパスで割り算して合成します。足し算と掛け算は交換出来るので、順番は関係ありません。近似ですが(重みは深度の関数)、交差する表面やパーティクルをうまく扱え、第17章のフレームバッファだけで出来ます。正確な方法もあります。デプスピーリングは半透明の層を1パスに1枚ずつ描き、ピクセル毎の連結リスト(アトミックカウンターとシェーダーストレージバッファで作る「Aバッファ」)は全てのフラグメントを保存してピクセル毎に並べ替えます。
- アルファトゥカバレッジとディザ。 ゲームの植物は、MSAAのアルファトゥカバレッジ(第20章)と一緒にアルファテストするか、アルファを鋭くして(GLSL 第6章の
fwidthの技をアルファに使う)どの距離でも縁がくっきりする様にアルファテストし、更に覆う割合を保つ様にアルファを調整したミップマップを使います。ディファードレンダラーは物をディザのパターン(模様に従ってピクセルを1つおきに捨てる)でフェードし、テンポラルアンチエイリアスがぼかして滑らかな半透明にする事がよくあります。 - ディファードレンダラーとガラス。 Gバッファはピクセル毎に1つの表面しか持てないので、ガラスを入れられません。エンジンは不透明な世界をディファードシェーディングで照らし、其の上に半透明の物を別のフォワードのパスで描きます。あたし達の2パスのフレームと同じです。
- 何処でも乗算済み。 パーティクルシステムとUIは、フィルタリングと上の「加算とoverを一緒に」の技の為に、普通は乗算済みアルファだけで動きます。テクスチャはインポートの時に、リニアな空間で乗算されます(あたし達の乗算はsRGBで符号化された値に掛けているので、第21章で見直します)。
- よく通る所で問い合わせない。 あたし達は描画呼び出し毎に
glIsEnabledを尋ねています。エンジンはGLの状態の写しをCPU側に持ち、余計な呼び出しを丸ごと飛ばします。問い合わせはマルチスレッドのドライバーを止めてしまう事があります。
16.11 まとめ
- フェイスカリングは、画面上の面積の符号で三角形を捨てます。既定では反時計回り()が表です。
glEnable(GL_CULL_FACE)、glCullFace(GL_BACK)、glFrontFace(GL_CCW)。此の章からカリングはオンです。 - 両面の表面にはカリングを切る事と、
gl_FrontFacingがfalseの時に法線を反転する事が必要です。glFrontFace(GL_CW)はglCullFace(GL_FRONT)ではありません。gl_FrontFacingも逆にするので、両面の帆が暗くなります。 - glTFのアルファモード:
OPAQUEはアルファを無視し、MASKはalphaCutoff未満を捨て(不透明な物と一緒に描く)、BLENDは背景と混ぜ、並べ替えが必要です。不透明度 =baseColorFactor.a× テクスチャのアルファで、ストレート(乗算済みではない)です。 discardは何も書きません。アルファテストは並べ替えが要りませんが、縁が硬く、ミップマップで薄くなり、アーリーZを損ないます。- ブレンディング:結果 = (
glBlendFunc、glBlendEquation)。ストレートアルファのoverはGL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHAです。アルファにGL_ONE, GL_ONE_MINUS_SRC_ALPHAを使うglBlendFuncSeparateで、フレームバッファのアルファが正しく保たれます。 - 「over」は交換出来ません。不透明な物を先に、次に半透明な物を遠い順に描きます。
ModelはプリミティブをModelPass::Opaqueと並べ替えたModelPass::Transparentに分け、mainは全ての半透明の物を一緒に並べ替えます。glDepthMask(GL_FALSE)にすると、並べ替えの間違いが穴ではなく間違った混ざり方になります。 - 中心での並べ替えは、交差する表面とメッシュの中では失敗します。順番に依存しない半透明(重み付きブレンドOIT、デプスピーリング)やアルファトゥカバレッジが本当の解決策です。
- フィルタリングとストレートアルファの組み合わせは色をで重み付けし、見えないテクセルの色を混ぜます(黒い縁)。乗算済みアルファ(、
GL_ONE, GL_ONE_MINUS_SRC_ALPHAでブレンド)は正しくフィルタリングされます。ミップマップを作る前に乗算します。
16.12 課題
- ★ ガラスを加算にして下さい。ストレートアルファのブレンド関数を
glBlendFunc(GL_ONE, GL_ONE)に置き換えます。窓が光り、其の後ろの全ての物が明るくなり、暗くなる事は無いはずです。次に深度の書き込みを切り(B)、並べ替えを切り替えて(O)下さい。足し算は順番を気にしないので、もう何も変わらないはずです。 - ★ 光を濾すだけの本物の色ガラスの様に、ガラスを乗算にして下さい:
glBlendFunc(GL_DST_COLOR, GL_ZERO)(結果 = ソース × デスティネーション)。ガラスの後ろのシーンは其の色で色付き、暗くなり、明るくなる事は無いはずです。深度の書き込みを切ると、やはりOキーで違いが出ないはずです。 - ★ 草の
alphaCutoffを0.1に、次に0.9に変えて下さい(アルファテストのモード)。0.1では葉が太くなり、暗い縁が付くはずです(黒い透明なテクセルが不透明として描かれる様になった為)。0.9では細くなり、ミップマップのアルファが0.9に届く事が殆ど無いので、芝生の奥の株は殆どの葉を失うはずです。 - ★★
phong.fragの法線を反転する行を消し、昼に窓の後ろへ回り込んで(C)下さい。裏から見たガラスと葉が、太陽が透けて裏側を照らしている様に、表から見た時と同じ明るさになるはずです。行を戻すと、裏側は暗く、環境光だけで照らされます。 - ★★ 半透明の立方体を描いて下さい。
alphaMode = AlphaMode::Blend、alpha = 0.5のMaterialでmakeCube()を描き、半透明のリストに加えます。カリングを切ると、結果が角度(インデックスの順番)に依存するはずです。ある側からは手前の面越しに奥の面が見え、別の側からは奥の面が無いか(深度を書く時)、手前の面の上に混ざります(B)。代わりに2回描いて下さい。先ずglCullFace(GL_FRONT)で、次にglCullFace(GL_BACK)で。深度を書いても書かなくても、どの角度からでも奥の面が手前の面の後ろに見えるはずです。 - ★★ 乗算せずにストレートアルファの縁を直して下さい。
fromPixelsで、アップロードの前に透明なテクセルに色を滲ませます(アルファが0の各テクセルに、アルファが0より大きい隣のテクセルの色の平均を入れ、色が広がる様に8回程繰り返します。アルファは0のままです)。Gキーのモード1がモード2と同じに、柔らかい縁で暗い縁無しに見えるはずです。 - ★★★ 第17章の後で、半透明なパス(ガラスとブレンドする草)に重み付きブレンドの順番に依存しない半透明(McGuireとBavoil 2013)を実装して下さい。
RGBA16Fの蓄積ターゲットとR8のrevealageターゲットに、ターゲット毎に違うブレンド関数(glBlendFunci)で描き、全画面のパスで合成します。窓はどんな順番でも正しく見え、OとBのキーで目に見える違いが無くなり、ブレンドした草の株で葉が切れて見える事も無くなるはずです。
ファイル: a/assets/LICENSE.txt | b/assets/LICENSE.txt
| 前 | 新 | ||
|---|---|---|---|
| @@ -8,5 +8,7 @@ textures/floor.png 石の床 / stone floor tiles | |||
| 8 | textures/crate_specular.png 木箱の鏡面反射マップ / crate specular map | 8 | 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) | ||
| 12 | models/window.glb 花箱つきの窓 / a window with a flower box (chapter 16) | ||
| 11 | models/crate.glb 木箱のモデル / crate model | 13 | models/crate.glb 木箱のモデル / crate model |
| 12 | models/diorama.glb 小さな場面 / a small diorama scene | 14 | models/diorama.glb 小さな場面 / a small diorama scene |
ファイル: /dev/null | b/assets/models/window.glb
新しいファイル:100644 / バイナリファイル
ファイル: /dev/null | b/assets/textures/grass_blades.png
新しいファイル:100644 / バイナリファイル
ファイル: a/shaders/phong.frag | b/shaders/phong.frag
| 前 | 新 | ||
|---|---|---|---|
| @@ -9,6 +9,10 @@ struct Material { | |||
| 9 | vec3 specular; // 鏡面反射の色と強さ / specular colour and strength | 9 | vec3 specular; // 鏡面反射の色と強さ / specular colour and strength |
| 10 | vec3 emission; // 発光の色 / emission colour | 10 | vec3 emission; // 発光の色 / emission colour |
| 11 | float shininess; // 光沢度 / shininess | 11 | float shininess; // 光沢度 / shininess |
| 12 | float alpha; // 不透明度(diffuseマップのアルファと掛ける) / opacity (multiplied with the diffuse map's alpha) | ||
| 13 | int alphaMode; // 0 = 不透明 / opaque, 1 = マスク / mask (discard), 2 = ブレンド / blend | ||
| 14 | float alphaCutoff; // マスクのしきい値 / the mask threshold | ||
| 15 | bool doubleSided; // 裏面では法線を反転する / flip the normal on back faces | ||
| 12 | }; | 16 | }; |
| 13 | uniform Material uMaterial; | 17 | uniform Material uMaterial; |
| 14 | 18 | ||
| @@ -56,6 +60,11 @@ uniform vec3 uViewPos; // カメラの位置(ワールド座標) / camera po | |||
| 56 | // 0 = everything, 1 = ambient, 2 = diffuse, 3 = specular, 4 = emission, 5 = normals | 60 | // 0 = everything, 1 = ambient, 2 = diffuse, 3 = specular, 4 = emission, 5 = normals |
| 57 | uniform int uViewMode; | 61 | uniform int uViewMode; |
| 58 | 62 | ||
| 63 | // C++のAlphaModeと同じ / same as AlphaMode in C++ | ||
| 64 | #define ALPHA_OPAQUE 0 | ||
| 65 | #define ALPHA_MASK 1 | ||
| 66 | #define ALPHA_BLEND 2 | ||
| 67 | |||
| 59 | layout(location = 0) out vec4 out_color; | 68 | layout(location = 0) out vec4 out_color; |
| 60 | 69 | ||
| 61 | // このピクセルの表面:どの光の計算にも同じものを使う / this pixel's surface: the same for every light | 70 | // このピクセルの表面:どの光の計算にも同じものを使う / this pixel's surface: the same for every light |
| @@ -84,11 +93,21 @@ float attenuate(float d, vec3 k) { | |||
| 84 | } | 93 | } |
| 85 | 94 | ||
| 86 | void main() { | 95 | void main() { |
| 96 | vec4 base = texture(uDiffuseMap, vUv); | ||
| 97 | float alpha = uMaterial.alpha * base.a; | ||
| 98 | // マスク:しきい値未満は捨てる(色も深度も書かない)。ブレンド:完全に透明なら深度も書かないように捨てる | ||
| 99 | // Mask: discard below the threshold (writes neither colour nor depth). Blend: discard fully transparent pixels so | ||
| 100 | // they do not write depth either | ||
| 101 | if (uMaterial.alphaMode == ALPHA_MASK && alpha < uMaterial.alphaCutoff) discard; | ||
| 102 | if (uMaterial.alphaMode == ALPHA_BLEND && alpha < 1.0 / 255.0) discard; | ||
| 103 | |||
| 87 | Surface s; | 104 | Surface s; |
| 88 | s.position = vWorldPos; | 105 | s.position = vWorldPos; |
| 89 | s.normal = normalize(vNormal); | 106 | s.normal = normalize(vNormal); |
| 107 | // 両面のマテリアルを裏から見ているなら、法線は裏を向く / seen from behind, a double-sided surface's normal points the other way | ||
| 108 | if (uMaterial.doubleSided && !gl_FrontFacing) s.normal = -s.normal; | ||
| 90 | s.view = normalize(uViewPos - vWorldPos); | 109 | s.view = normalize(uViewPos - vWorldPos); |
| 91 | s.diffuse = uMaterial.diffuse * texture(uDiffuseMap, vUv).rgb; | 110 | s.diffuse = uMaterial.diffuse * base.rgb; |
| 92 | s.specular = uMaterial.specular * texture(uSpecularMap, vUv).rgb; | 111 | s.specular = uMaterial.specular * texture(uSpecularMap, vUv).rgb; |
| 93 | s.shininess = uMaterial.shininess; | 112 | s.shininess = uMaterial.shininess; |
| 94 | vec3 emission = uMaterial.emission * texture(uEmissionMap, vUv).rgb; | 113 | vec3 emission = uMaterial.emission * texture(uEmissionMap, vUv).rgb; |
| @@ -125,5 +144,6 @@ void main() { | |||
| 125 | else if (uViewMode == 3) color = specular; | 144 | else if (uViewMode == 3) color = specular; |
| 126 | else if (uViewMode == 4) color = emission; | 145 | else if (uViewMode == 4) color = emission; |
| 127 | else if (uViewMode == 5) color = s.normal * 0.5 + 0.5; | 146 | else if (uViewMode == 5) color = s.normal * 0.5 + 0.5; |
| 128 | out_color = vec4(color, 1.0); | 147 | // 不透明とマスクはアルファ1。ブレンドだけ本当のアルファを出す / opaque and mask output alpha 1; only blend outputs its alpha |
| 148 | out_color = vec4(color, uMaterial.alphaMode == ALPHA_BLEND ? alpha : 1.0); | ||
| 129 | } | 149 | } |
ファイル: a/src/main.cc | b/src/main.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -1,5 +1,5 @@ | |||
| 1 | // 第15章:深度テストとステンシルテスト | 1 | // 第16章:ブレンディングとフェイスカリング |
| 2 | // Chapter 15: depth and stencil testing | 2 | // Chapter 16: blending and face culling |
| 3 | // | 3 | // |
| 4 | // 操作 / Controls: | 4 | // 操作 / Controls: |
| 5 | // WASD 前後左右に移動 / move forward, back, left, right | 5 | // WASD 前後左右に移動 / move forward, back, left, right |
| @@ -7,15 +7,12 @@ | |||
| 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 | // クリック / click 物を選ぶ(FPSは左ボタンで画面の真ん中、オービットは右ボタンでカーソルの位置) | 10 | // K カリング:裏面 → なし → 表面 → 裏面だがglFrontFace(GL_CW) |
| 11 | // select an object (FPS: left button, at the centre of the screen; orbit: right button, at the cursor) | 11 | // culling: back faces → off → front faces → back faces but glFrontFace(GL_CW) |
| 12 | // E 次の物を選ぶ / select the next object | 12 | // O 半透明の物を遠い順に並べる・並べない / sort transparent objects back to front, or not |
| 13 | // T 選んだ物の輪郭を壁越しに見せる(X線)オン・オフ / show the selection outline through walls (x-ray) on / off | 13 | // B 半透明の物が深度を書く・書かない(glDepthMask) / transparent objects write depth or not (glDepthMask) |
| 14 | // Z 表示:色 → 深度(そのまま) → 深度(線型) / view: colour → depth (raw) → depth (linear) | 14 | // G 草:アルファテスト → ブレンド(ストレートアルファ) → ブレンド(乗算済みアルファ) |
| 15 | // G 深度関数:GL_LESS → GL_ALWAYS → GL_GREATER / depth function: GL_LESS → GL_ALWAYS → GL_GREATER | 15 | // grass: alpha test → blending (straight alpha) → blending (premultiplied alpha) |
| 16 | // X Zファイティングの対策:なし → ポリゴンオフセット → 3 mm持ち上げる | ||
| 17 | // z-fighting fix: none → polygon offset → lift by 3 mm | ||
| 18 | // M ニアプレーン:0.1 m ⇔ 0.1 mm / near plane: 0.1 m ⇔ 0.1 mm | ||
| 19 | // C FPS ⇔ オービットカメラ / FPS ⇔ orbit camera | 16 | // C FPS ⇔ オービットカメラ / FPS ⇔ orbit camera |
| 20 | // V 表示:全部 → 環境光 → 拡散 → 鏡面 → 発光 → 法線 / view: all → ambient → diffuse → specular → emission → normals | 17 | // V 表示:全部 → 環境光 → 拡散 → 鏡面 → 発光 → 法線 / view: all → ambient → diffuse → specular → emission → normals |
| 21 | // N 昼 ⇔ 夜 / day ⇔ night | 18 | // N 昼 ⇔ 夜 / day ⇔ night |
| @@ -37,54 +34,85 @@ | |||
| 37 | 34 | ||
| 38 | #include <algorithm> | 35 | #include <algorithm> |
| 39 | #include <cmath> | 36 | #include <cmath> |
| 37 | #include <cstdint> | ||
| 40 | #include <cstdio> | 38 | #include <cstdio> |
| 39 | #include <functional> | ||
| 41 | #include <optional> | 40 | #include <optional> |
| 41 | #include <vector> | ||
| 42 | 42 | ||
| 43 | // 木箱のモデルを置く場所:位置(底の中心)とY軸周りの回転 / where the crate models go: position (bottom centre) and yaw | 43 | // 物を置く場所:位置(底の中心)とY軸周りの回転 / where things go: position (bottom centre) and yaw |
| 44 | struct CrateInfo { | 44 | struct Placement { |
| 45 | Vec3 position; | 45 | Vec3 position; |
| 46 | float angle; | 46 | float angle; |
| 47 | }; | 47 | }; |
| 48 | 48 | ||
| 49 | static const CrateInfo kCrates[] = { | 49 | static const Placement kCrates[] = { |
| 50 | {{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 | {{5.5f, 0.0f, 1.5f}, 0.4f}, {{6.3f, 0.0f, 2.6f}, -0.3f}, {{5.9f, 1.0f, 2.0f}, 0.1f}, |
| 51 | {{-6.0f, 0.0f, -1.0f}, 0.8f}, {{-5.2f, 0.0f, 3.5f}, -0.6f}, | 51 | {{-6.0f, 0.0f, -1.0f}, 0.8f}, {{-5.2f, 0.0f, 3.5f}, -0.6f}, |
| 52 | }; | 52 | }; |
| 53 | constexpr int kCrateCount = static_cast<int>(sizeof kCrates / sizeof kCrates[0]); | ||
| 54 | 53 | ||
| 55 | // ステンシルに書く物の番号。0 = 何もない(床と敷物) / the object numbers written to the stencil buffer. 0 = nothing | 54 | // 窓はカメラから見て重なるように並べる。配列は手前の窓から:並べ替えないと順番が逆になる |
| 56 | // (the floor and the rug) | 55 | // The windows overlap as seen from the camera. The array starts with the nearest one: without sorting the order is wrong |
| 57 | constexpr int kDioramaId = kCrateCount + 1; // 木箱は1〜5 / the crates are 1..5 | 56 | static const Placement kWindows[] = { |
| 57 | {{-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}, | ||
| 58 | }; | ||
| 58 | 59 | ||
| 59 | static const char *const kViewModeNames[] = {"all", "ambient", "diffuse", "specular", "emission", "normals"}; | 60 | static const char *const kViewModeNames[] = {"all", "ambient", "diffuse", "specular", "emission", "normals"}; |
| 60 | static const char *const kDepthViewNames[] = {"colour", "depth (raw, non-linear)", "depth (linear)"}; | 61 | static const char *const kCullNames[] = {"back faces (glCullFace(GL_BACK), glFrontFace(GL_CCW))", "off", |
| 61 | static const GLenum kDepthFuncs[] = {GL_LESS, GL_ALWAYS, GL_GREATER}; | 62 | "front faces (glCullFace(GL_FRONT))", |
| 62 | static const char *const kDepthFuncNames[] = {"GL_LESS", "GL_ALWAYS", "GL_GREATER"}; | 63 | "back faces, but glFrontFace(GL_CW) (= wrong winding)"}; |
| 63 | static const char *const kZFixNames[] = {"none (z-fighting)", "polygon offset", "lifted by 3 mm"}; | 64 | static const char *const kGrassNames[] = {"alpha test (discard)", "blending, straight alpha", |
| 64 | 65 | "blending, premultiplied alpha"}; | |
| 65 | // 選んだ物の輪郭用:モデルの箱の中心を基準に、各辺がwidthずつ大きくなるように拡大する行列 | 66 | |
| 66 | // For the selection outline: a matrix that scales a model about the centre of its box so that every side grows by width | 67 | // 決まった乱数(どのコンパイラでも同じ数列。std::uniform_real_distributionは標準ライブラリごとに違う) |
| 67 | static Mat4 outlineScale(const Model &m, float width) { | 68 | // A fixed pseudo-random sequence (the same with every compiler; std::uniform_real_distribution differs between |
| 68 | Vec3 size = m.boundsMax - m.boundsMin; | 69 | // standard libraries) |
| 69 | Vec3 centre = 0.5f * (m.boundsMin + m.boundsMax); | 70 | static float random01(std::uint32_t &state) { |
| 70 | Vec3 k = {(size.x + 2.0f * width) / size.x, (size.y + 2.0f * width) / size.y, (size.z + 2.0f * width) / size.z}; | 71 | state = state * 1664525u + 1013904223u; |
| 71 | return translate(centre) * scale(k) * translate(-centre); | 72 | return static_cast<float>(state >> 8) / 16777216.0f; |
| 73 | } | ||
| 74 | |||
| 75 | // 草の株を置く:ジオラマの地面の上(風車・木・木箱・街灯を避ける)と、手前の床に少し | ||
| 76 | // Places grass tufts: on the diorama's ground (avoiding the windmill, tree, crates and lamp) and a few on the floor | ||
| 77 | static std::vector<Placement> makeGrass() { | ||
| 78 | std::vector<Placement> grass; | ||
| 79 | std::uint32_t seed = 16; | ||
| 80 | const Vec3 avoid[] = {{-1.4f, 0, -1.2f}, {-2.7f, 0, 1.7f}, {1.5f, 0, -1.4f}, {2.2f, 0, 1.6f}, {0.4f, 0, 2.5f}}; | ||
| 81 | while (grass.size() < 46) { | ||
| 82 | float r = 4.2f * std::sqrt(random01(seed)), a = 2.0f * PI * random01(seed); | ||
| 83 | Vec3 p = {r * std::cos(a), 0.12f, r * std::sin(a)}; | ||
| 84 | bool ok = true; | ||
| 85 | for (Vec3 q : avoid) ok = ok && length(Vec3{p.x - q.x, 0, p.z - q.z}) > 1.1f; | ||
| 86 | if (ok) grass.push_back({p, 2.0f * PI * random01(seed)}); | ||
| 87 | } | ||
| 88 | // 手前の床:窓の間と、カメラのすぐ近くに一つ(近くで縁を見るため) / on the floor in front: between the windows, | ||
| 89 | // and one right in front of the camera (to look at its edges up close) | ||
| 90 | const Placement front[] = {{{1.5f, 0, 6.2f}, 0.3f}, {{-2.9f, 0, 7.0f}, 1.2f}, {{3.6f, 0, 5.4f}, 2.0f}, | ||
| 91 | {{1.2f, 0, 8.9f}, 0.7f}, {{-2.6f, 0, 9.6f}, 2.6f}, {{0.6f, 0, 10.7f}, 0.5f}}; | ||
| 92 | for (const Placement &p : front) grass.push_back(p); | ||
| 93 | return grass; | ||
| 72 | } | 94 | } |
| 73 | 95 | ||
| 74 | int main() { | 96 | int main() { |
| 75 | Window window; | 97 | Window window; |
| 76 | if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 15")) return 1; | 98 | if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 16")) return 1; |
| 77 | 99 | ||
| 78 | std::optional<Shader> phong = Shader::load("shaders/phong.vert", "shaders/phong.frag"); | 100 | std::optional<Shader> phong = Shader::load("shaders/phong.vert", "shaders/phong.frag"); |
| 79 | std::optional<Shader> unlit = Shader::load("shaders/unlit.vert", "shaders/unlit.frag"); | ||
| 80 | std::optional<Shader> depthView = Shader::load("shaders/unlit.vert", "shaders/depth.frag"); | ||
| 81 | std::optional<Texture2D> floorTexture = Texture2D::load("assets/textures/floor.png"); | 101 | std::optional<Texture2D> floorTexture = Texture2D::load("assets/textures/floor.png"); |
| 82 | std::optional<Texture2D> rugTexture = Texture2D::load("assets/textures/rug.png"); | 102 | // 同じ草の画像を二通りに:そのまま(ストレートアルファ)と、乗算済みアルファ |
| 83 | if (!phong || !unlit || !depthView || !floorTexture || !rugTexture) return 1; | 103 | // The same grass image twice: as it is (straight alpha) and premultiplied |
| 104 | std::optional<Texture2D> grassStraight = Texture2D::load("assets/textures/grass_blades.png"); | ||
| 105 | std::optional<Texture2D> grassPremultiplied = | ||
| 106 | Texture2D::load("assets/textures/grass_blades.png", {.premultiplyAlpha = true}); | ||
| 107 | if (!phong || !floorTexture || !grassStraight || !grassPremultiplied) return 1; | ||
| 108 | // 草の画像は端まで描かれているので繰り返さない / the grass image reaches its edges: no repeat | ||
| 109 | grassStraight->setWrap(GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE); | ||
| 110 | grassPremultiplied->setWrap(GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE); | ||
| 84 | 111 | ||
| 85 | std::optional<Model> scene = Model::load("assets/models/diorama.glb"); | 112 | std::optional<Model> scene = Model::load("assets/models/diorama.glb"); |
| 86 | std::optional<Model> crate = Model::load("assets/models/crate.glb"); | 113 | std::optional<Model> crate = Model::load("assets/models/crate.glb"); |
| 87 | if (!scene || !crate) return 1; | 114 | std::optional<Model> windowModel = Model::load("assets/models/window.glb"); |
| 115 | if (!scene || !crate || !windowModel) return 1; | ||
| 88 | 116 | ||
| 89 | const unsigned char whitePixel[4] = {255, 255, 255, 255}; | 117 | const unsigned char whitePixel[4] = {255, 255, 255, 255}; |
| 90 | Texture2D white = Texture2D::fromPixels(whitePixel, 1, 1, {.flipY = false, .mipmaps = false}); | 118 | Texture2D white = Texture2D::fromPixels(whitePixel, 1, 1, {.flipY = false, .mipmaps = false}); |
| @@ -94,28 +122,24 @@ int main() { | |||
| 94 | Quat rotorStart = rotor >= 0 ? scene->nodes[static_cast<size_t>(rotor)].rotation : Quat{}; | 122 | Quat rotorStart = rotor >= 0 ? scene->nodes[static_cast<size_t>(rotor)].rotation : Quat{}; |
| 95 | 123 | ||
| 96 | Camera fps; | 124 | Camera fps; |
| 97 | fps.position = {0.0f, 2.4f, 13.0f}; | 125 | fps.position = {0.0f, 2.1f, 13.0f}; |
| 98 | fps.pitch = radians(-12.0f); | 126 | fps.pitch = radians(-9.0f); |
| 99 | 127 | ||
| 100 | OrbitCamera orbit; | 128 | OrbitCamera orbit; |
| 101 | orbit.target = {0.0f, 1.2f, 0.0f}; | 129 | orbit.target = {0.0f, 1.0f, 4.0f}; |
| 102 | orbit.distance = 10.0f; | 130 | orbit.distance = 9.0f; |
| 103 | orbit.yaw = radians(30.0f); | 131 | orbit.yaw = radians(20.0f); |
| 104 | 132 | ||
| 105 | bool useOrbit = false; | 133 | bool useOrbit = false; |
| 106 | int viewMode = 0, depthViewMode = 0, depthFunc = 0, zFix = 0; | 134 | int viewMode = 0, cullMode = 0, grassMode = 0; |
| 107 | bool night = false, flashlightOn = false, windmillMoving = true, xray = false, tinyNear = false; | 135 | bool night = false, flashlightOn = false, windmillMoving = true, sortTransparent = true, blendDepthWrite = true; |
| 108 | int selected = 0; // 選んでいる物の番号(0 = なし) / the selected object's number (0 = none) | ||
| 109 | bool pickRequested = false; // 次のフレームでステンシルを読む / read the stencil buffer this frame | ||
| 110 | double pickX = 0.0, pickY = 0.0; | ||
| 111 | float windmillTime = 0.0f; | 136 | float windmillTime = 0.0f; |
| 112 | window.setCursorCaptured(true); | 137 | window.setCursorCaptured(true); |
| 113 | 138 | ||
| 114 | window.onKey = [&](int key, int action, int /*mods*/) { | 139 | window.onKey = [&](int key, int action, int /*mods*/) { |
| 115 | if (action != GLFW_PRESS) return; | 140 | if (action != GLFW_PRESS) return; |
| 116 | if (key == GLFW_KEY_ESCAPE) window.close(); | 141 | if (key == GLFW_KEY_ESCAPE) window.close(); |
| 117 | if (key == GLFW_KEY_R && phong->reload() && unlit->reload() && depthView->reload()) | 142 | if (key == GLFW_KEY_R && phong->reload()) printf("シェーダーを読み直した / shaders reloaded\n"); |
| 118 | printf("シェーダーを読み直した / shaders reloaded\n"); | ||
| 119 | if (key == GLFW_KEY_TAB) window.setCursorCaptured(!window.cursorCaptured()); | 143 | if (key == GLFW_KEY_TAB) window.setCursorCaptured(!window.cursorCaptured()); |
| 120 | if (key == GLFW_KEY_C) { | 144 | if (key == GLFW_KEY_C) { |
| 121 | useOrbit = !useOrbit; | 145 | useOrbit = !useOrbit; |
| @@ -126,50 +150,26 @@ int main() { | |||
| 126 | viewMode = (viewMode + 1) % 6; | 150 | viewMode = (viewMode + 1) % 6; |
| 127 | printf("view: %s\n", kViewModeNames[viewMode]); | 151 | printf("view: %s\n", kViewModeNames[viewMode]); |
| 128 | } | 152 | } |
| 129 | if (key == GLFW_KEY_Z) { | 153 | if (key == GLFW_KEY_K) { |
| 130 | depthViewMode = (depthViewMode + 1) % 3; | 154 | cullMode = (cullMode + 1) % 4; |
| 131 | printf("view: %s\n", kDepthViewNames[depthViewMode]); | 155 | printf("culling: %s\n", kCullNames[cullMode]); |
| 132 | } | ||
| 133 | if (key == GLFW_KEY_G) { | ||
| 134 | depthFunc = (depthFunc + 1) % 3; | ||
| 135 | printf("depth function: %s\n", kDepthFuncNames[depthFunc]); | ||
| 136 | } | 156 | } |
| 137 | if (key == GLFW_KEY_X) { | 157 | if (key == GLFW_KEY_O) { |
| 138 | zFix = (zFix + 1) % 3; | 158 | sortTransparent = !sortTransparent; |
| 139 | printf("z-fighting fix: %s\n", kZFixNames[zFix]); | 159 | printf("sort transparent objects: %s\n", sortTransparent ? "on (back to front)" : "off (array order)"); |
| 140 | } | 160 | } |
| 141 | if (key == GLFW_KEY_M) { | 161 | if (key == GLFW_KEY_B) { |
| 142 | tinyNear = !tinyNear; | 162 | blendDepthWrite = !blendDepthWrite; |
| 143 | fps.nearPlane = orbit.nearPlane = tinyNear ? 0.0001f : 0.1f; | 163 | printf("transparent objects write depth: %s\n", blendDepthWrite ? "yes" : "no (glDepthMask(GL_FALSE))"); |
| 144 | printf("near plane: %g m\n", static_cast<double>(fps.nearPlane)); | ||
| 145 | } | 164 | } |
| 146 | if (key == GLFW_KEY_E) { | 165 | if (key == GLFW_KEY_G) { |
| 147 | selected = selected % kDioramaId + 1; // 1 → 2 → … → 6 → 1 | 166 | grassMode = (grassMode + 1) % 3; |
| 148 | printf("selected: %d\n", selected); | 167 | printf("grass: %s\n", kGrassNames[grassMode]); |
| 149 | } | ||
| 150 | if (key == GLFW_KEY_T) { | ||
| 151 | xray = !xray; | ||
| 152 | printf("outline through walls: %s\n", xray ? "on" : "off"); | ||
| 153 | } | 168 | } |
| 154 | if (key == GLFW_KEY_N) night = !night; | 169 | if (key == GLFW_KEY_N) night = !night; |
| 155 | if (key == GLFW_KEY_F) flashlightOn = !flashlightOn; | 170 | if (key == GLFW_KEY_F) flashlightOn = !flashlightOn; |
| 156 | if (key == GLFW_KEY_P) windmillMoving = !windmillMoving; | 171 | if (key == GLFW_KEY_P) windmillMoving = !windmillMoving; |
| 157 | }; | 172 | }; |
| 158 | window.onMouseButton = [&](int button, int action, int /*mods*/) { | ||
| 159 | if (action != GLFW_PRESS) return; | ||
| 160 | bool fpsPick = !useOrbit && button == GLFW_MOUSE_BUTTON_LEFT; | ||
| 161 | if (!fpsPick && button != GLFW_MOUSE_BUTTON_RIGHT) return; | ||
| 162 | pickRequested = true; | ||
| 163 | // FPSでカーソルを隠しているときは画面の真ん中(照準)、それ以外はカーソルの位置 | ||
| 164 | // With the cursor captured in FPS mode: the centre of the screen (the crosshair); otherwise the cursor position | ||
| 165 | bool centre = !useOrbit && window.cursorCaptured(); | ||
| 166 | // マウスはウィンドウ座標、glReadPixelsはフレームバッファのピクセル。高DPIでは違うので換算する | ||
| 167 | // The mouse is in window coordinates, glReadPixels wants framebuffer pixels; they differ on high-DPI screens | ||
| 168 | int winW = 1, winH = 1; | ||
| 169 | glfwGetWindowSize(window.handle(), &winW, &winH); | ||
| 170 | pickX = centre ? window.width() / 2.0 : window.mouseX() * window.width() / std::max(winW, 1); | ||
| 171 | pickY = centre ? window.height() / 2.0 : window.mouseY() * window.height() / std::max(winH, 1); | ||
| 172 | }; | ||
| 173 | 173 | ||
| 174 | Mesh floorMesh = makePlane(40.0f, 10.0f); | 174 | Mesh floorMesh = makePlane(40.0f, 10.0f); |
| 175 | Material floorMaterial; | 175 | Material floorMaterial; |
| @@ -177,25 +177,16 @@ int main() { | |||
| 177 | floorMaterial.specular = {0.15f, 0.15f, 0.15f}; | 177 | floorMaterial.specular = {0.15f, 0.15f, 0.15f}; |
| 178 | floorMaterial.shininess = 16.0f; | 178 | floorMaterial.shininess = 16.0f; |
| 179 | 179 | ||
| 180 | // 敷物:1×1の板を2.6 m × 5.2 mに拡大。床とまったく同じ平面(y = 0)にある / the rug: the 1 × 1 plane scaled to | 180 | Mesh tuftMesh = makeCrossedQuads(3); |
| 181 | // 2.6 m × 5.2 m. It lies in exactly the same plane as the floor (y = 0) | 181 | std::vector<Placement> grass = makeGrass(); |
| 182 | Mesh rugMesh = makePlane(1.0f, 1.0f); | 182 | Material grassMaterial; |
| 183 | Material rugMaterial; | 183 | grassMaterial.specular = {0.04f, 0.04f, 0.04f}; |
| 184 | rugMaterial.diffuseMap = &*rugTexture; | 184 | grassMaterial.shininess = 8.0f; |
| 185 | rugMaterial.specular = {0.05f, 0.05f, 0.05f}; | ||
| 186 | rugMaterial.shininess = 8.0f; | ||
| 187 | 185 | ||
| 188 | // ステンシルテストを有効にする。各物は描くときに自分の番号をステンシルに書く(下のsetStencilId) | ||
| 189 | // Enable the stencil test. Each object writes its number to the stencil buffer while it is drawn (setStencilId below) | ||
| 190 | glEnable(GL_DEPTH_TEST); | 186 | glEnable(GL_DEPTH_TEST); |
| 191 | glEnable(GL_STENCIL_TEST); | 187 | // 裏面のカリング:画面上で時計回りに見える三角形(=裏)を描かない |
| 192 | // 失敗したとき(ステンシル、深度)はそのまま、両方通ったら参照値で置き換える | 188 | // Back-face culling: triangles that appear clockwise on screen (= seen from behind) are not drawn |
| 193 | // keep the value when the stencil or depth test fails, replace it with the reference value when both pass | 189 | glEnable(GL_CULL_FACE); |
| 194 | glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE); | ||
| 195 | |||
| 196 | auto setStencilId = [](int id) { | ||
| 197 | glStencilFunc(GL_ALWAYS, id, 0xFF); // いつも通す。参照値 = id / always pass; reference value = id | ||
| 198 | }; | ||
| 199 | 190 | ||
| 200 | double lastTime = window.time(); | 191 | double lastTime = window.time(); |
| 201 | while (!window.shouldClose()) { | 192 | while (!window.shouldClose()) { |
| @@ -231,8 +222,6 @@ int main() { | |||
| 231 | Mat4 proj = useOrbit ? orbit.projection(window.aspect()) : fps.projection(window.aspect()); | 222 | Mat4 proj = useOrbit ? orbit.projection(window.aspect()) : fps.projection(window.aspect()); |
| 232 | Vec3 viewPos = useOrbit ? orbit.position() : fps.position; | 223 | Vec3 viewPos = useOrbit ? orbit.position() : fps.position; |
| 233 | Vec3 viewDir = useOrbit ? normalize(orbit.target - orbit.position()) : fps.front(); | 224 | Vec3 viewDir = useOrbit ? normalize(orbit.target - orbit.position()) : fps.front(); |
| 234 | float nearPlane = useOrbit ? orbit.nearPlane : fps.nearPlane; | ||
| 235 | float farPlane = useOrbit ? orbit.farPlane : fps.farPlane; | ||
| 236 | 225 | ||
| 237 | LightSet lights; | 226 | LightSet lights; |
| 238 | if (!night) { | 227 | if (!night) { |
| @@ -248,118 +237,106 @@ int main() { | |||
| 248 | } | 237 | } |
| 249 | if (flashlightOn) lights.spots.push_back({.position = viewPos, .direction = viewDir, .color = {1.0f, 0.95f, 0.85f}}); | 238 | if (flashlightOn) lights.spots.push_back({.position = viewPos, .direction = viewDir, .color = {1.0f, 0.95f, 0.85f}}); |
| 250 | 239 | ||
| 251 | // 深度関数。GL_GREATERでは深度バッファを0(一番手前)でクリアしないと何も通らない | 240 | // カリングの設定 / the culling setup |
| 252 | // The depth function. With GL_GREATER the depth buffer must be cleared to 0 (the nearest value), or nothing passes | 241 | if (cullMode == 1) glDisable(GL_CULL_FACE); |
| 253 | glDepthFunc(kDepthFuncs[depthFunc]); | 242 | else glEnable(GL_CULL_FACE); |
| 254 | glClearDepth(kDepthFuncs[depthFunc] == GL_GREATER ? 0.0 : 1.0); | 243 | glCullFace(cullMode == 2 ? GL_FRONT : GL_BACK); |
| 255 | glClearStencil(0); | 244 | glFrontFace(cullMode == 3 ? GL_CW : GL_CCW); // GL_CCW = 反時計回りが表(既定) / counter-clockwise is the front (default) |
| 256 | // glClearはマスクを守る:ステンシルのマスクが0x00のままだとステンシルがクリアされない | ||
| 257 | // glClear obeys the write masks: with the stencil mask left at 0x00 the stencil buffer would not be cleared | ||
| 258 | glStencilMask(0xFF); | ||
| 259 | if (depthViewMode != 0) { | ||
| 260 | float c = depthFunc == 2 ? 0.0f : 1.0f; // 深度をクリアした値と同じ灰色 / the same grey as the cleared depth | ||
| 261 | glClearColor(c, c, c, 1.0f); | ||
| 262 | } | ||
| 263 | else if (night) glClearColor(0.02f, 0.03f, 0.06f, 1.0f); | ||
| 264 | else glClearColor(0.45f, 0.62f, 0.85f, 1.0f); | ||
| 265 | glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); | ||
| 266 | |||
| 267 | // 色か深度か。どちらでも同じ順番で同じ物を描く / colour or depth: either way the same objects in the same order | ||
| 268 | const Shader &s = depthViewMode == 0 ? *phong : *depthView; | ||
| 269 | bool lit = depthViewMode == 0; | ||
| 270 | s.use(); | ||
| 271 | s.set("uView", view); | ||
| 272 | s.set("uProj", proj); | ||
| 273 | if (lit) { | ||
| 274 | s.set("uViewPos", viewPos); | ||
| 275 | s.set("uViewMode", viewMode); | ||
| 276 | lights.apply(s); | ||
| 277 | } else { | ||
| 278 | s.set("uDepthMode", depthViewMode); | ||
| 279 | s.set("uNearPlane", nearPlane); | ||
| 280 | s.set("uFarPlane", farPlane); | ||
| 281 | s.set("uDisplayRange", 30.0f); | ||
| 282 | } | ||
| 283 | 245 | ||
| 284 | // 一つの板(床・敷物)を描く / draws one flat mesh (the floor or the rug) | 246 | if (night) glClearColor(0.02f, 0.03f, 0.06f, 1.0f); |
| 285 | auto drawFlat = [&](const Mesh &mesh, const Material &material, const Mat4 &model) { | 247 | else glClearColor(0.45f, 0.62f, 0.85f, 1.0f); |
| 286 | s.set("uModel", model); | 248 | glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); |
| 287 | if (lit) { | 249 | |
| 288 | s.set("uNormalMatrix", normalMatrix(model)); | 250 | phong->use(); |
| 289 | material.apply(s, white); | 251 | phong->set("uView", view); |
| 290 | } | 252 | phong->set("uProj", proj); |
| 291 | mesh.draw(); | 253 | phong->set("uViewPos", viewPos); |
| 254 | phong->set("uViewMode", viewMode); | ||
| 255 | lights.apply(*phong); | ||
| 256 | |||
| 257 | // 草の株を一つ描く。両面から見える板なのでカリングを切る / draws one grass tuft. The quads are seen from both | ||
| 258 | // sides, so culling is turned off | ||
| 259 | auto drawTuft = [&](const Placement &g) { | ||
| 260 | Mat4 model = translate(g.position) * rotateY(g.angle) * scale({0.75f, 0.75f, 0.75f}); | ||
| 261 | phong->set("uModel", model); | ||
| 262 | phong->set("uNormalMatrix", normalMatrix(model)); | ||
| 263 | GLboolean culling = glIsEnabled(GL_CULL_FACE); | ||
| 264 | glDisable(GL_CULL_FACE); | ||
| 265 | tuftMesh.draw(); | ||
| 266 | if (culling) glEnable(GL_CULL_FACE); | ||
| 292 | }; | 267 | }; |
| 293 | 268 | ||
| 294 | setStencilId(0); | 269 | //------------------------------------------------------------------ |
| 295 | drawFlat(floorMesh, floorMaterial, Mat4::identity()); | 270 | // 1. 不透明な物(とアルファテストの物):順番は自由。深度テストが前後を決める |
| 296 | 271 | // 1. Opaque objects (and alpha-tested ones): any order; the depth test sorts them out | |
| 297 | // 敷物は床と同じ平面:どちらの深度が勝つかはピクセルごとの丸め誤差で決まる(Zファイティング) | 272 | //------------------------------------------------------------------ |
| 298 | // The rug lies in the floor's plane: which depth wins is decided by per-pixel rounding (z-fighting) | 273 | phong->set("uModel", Mat4::identity()); |
| 299 | Mat4 rugModel = translate({0.0f, zFix == 2 ? 0.003f : 0.0f, 7.6f}) * scale({2.6f, 1.0f, 5.2f}); | 274 | phong->set("uNormalMatrix", normalMatrix(Mat4::identity())); |
| 300 | if (zFix == 1) { | 275 | floorMaterial.apply(*phong, white); |
| 301 | // 深度を少しカメラ側にずらす:factor × 斜面の傾き + units × 深度バッファの最小単位。負 = 手前へ | 276 | floorMesh.draw(); |
| 302 | // shift the depth slightly towards the camera: factor × slope + units × the smallest depth step. negative = closer | 277 | scene->draw(*phong, Mat4::identity(), white, ModelPass::Opaque); |
| 303 | glEnable(GL_POLYGON_OFFSET_FILL); | 278 | for (const Placement &c : kCrates) crate->draw(*phong, translate(c.position) * rotateY(c.angle), white, ModelPass::Opaque); |
| 304 | glPolygonOffset(-1.0f, -1.0f); | 279 | for (const Placement &w : kWindows) |
| 305 | } | 280 | windowModel->draw(*phong, translate(w.position) * rotateY(w.angle), white, ModelPass::Opaque); |
| 306 | drawFlat(rugMesh, rugMaterial, rugModel); | 281 | if (grassMode == 0) { |
| 307 | glDisable(GL_POLYGON_OFFSET_FILL); | 282 | // アルファテスト:アルファ < 0.5のピクセルを捨てる。ブレンドではないので並べ替えは要らない |
| 308 | 283 | // Alpha test: discard pixels with alpha < 0.5. This is not blending, so no sorting is needed | |
| 309 | setStencilId(kDioramaId); | 284 | grassMaterial.diffuseMap = &*grassStraight; |
| 310 | if (lit) scene->draw(s, Mat4::identity(), white); | 285 | grassMaterial.alphaMode = AlphaMode::Mask; |
| 311 | else scene->drawGeometry(s, Mat4::identity()); | 286 | grassMaterial.apply(*phong, white); |
| 312 | for (int i = 0; i < kCrateCount; ++i) { | 287 | for (const Placement &g : grass) drawTuft(g); |
| 313 | setStencilId(i + 1); | ||
| 314 | Mat4 m = translate(kCrates[i].position) * rotateY(kCrates[i].angle); | ||
| 315 | if (lit) crate->draw(s, m, white); | ||
| 316 | else crate->drawGeometry(s, m); | ||
| 317 | } | 288 | } |
| 318 | 289 | ||
| 319 | // クリックした場所のステンシルの値=そこに見えている物の番号 / the stencil value under the click = the number of | 290 | //------------------------------------------------------------------ |
| 320 | // the object visible there | 291 | // 2. 半透明の物:不透明な物の後で、カメラから遠い順に / 2. Transparent objects: after the opaque ones, |
| 321 | if (pickRequested) { | 292 | // farthest from the camera first |
| 322 | pickRequested = false; | 293 | //------------------------------------------------------------------ |
| 323 | unsigned char id = 0; | 294 | // 描く物の一覧:カメラからの距離、乗算済みアルファか、描く関数 / the list of things to draw: distance from the |
| 324 | // glReadPixelsの原点は左下、マウスは左上 / glReadPixels starts at the bottom left, the mouse at the top left | 295 | // camera, whether it is premultiplied, and a draw function |
| 325 | int px = static_cast<int>(pickX), py = window.height() - 1 - static_cast<int>(pickY); | 296 | struct Transparent { |
| 326 | glReadPixels(px, py, 1, 1, GL_STENCIL_INDEX, GL_UNSIGNED_BYTE, &id); | 297 | float distance; |
| 327 | selected = id; | 298 | bool premultiplied; |
| 328 | printf("picked at (%d, %d): %d%s\n", px, py, selected, selected == 0 ? " (nothing)" : ""); | 299 | std::function<void()> draw; |
| 300 | }; | ||
| 301 | std::vector<Transparent> transparent; | ||
| 302 | for (const Placement &w : kWindows) { | ||
| 303 | Mat4 m = translate(w.position) * rotateY(w.angle); | ||
| 304 | Vec3 centre = w.position + Vec3{0.0f, 0.8f, 0.0f}; // 窓の真ん中 / the middle of the window | ||
| 305 | transparent.push_back({length(centre - viewPos), false, [&, m] { | ||
| 306 | windowModel->draw(*phong, m, white, ModelPass::Transparent, viewPos); | ||
| 307 | }}); | ||
| 329 | } | 308 | } |
| 330 | 309 | if (grassMode != 0) { | |
| 331 | // 輪郭:拡大した物を、ステンシルがその物の番号「ではない」ところだけに一色で描く | 310 | grassMaterial.diffuseMap = grassMode == 2 ? &*grassPremultiplied : &*grassStraight; |
| 332 | // The outline: draw the enlarged object in one colour, only where the stencil is NOT that object's number | 311 | grassMaterial.alphaMode = AlphaMode::Blend; |
| 333 | if (selected > 0) { | 312 | for (const Placement &g : grass) { |
| 334 | glStencilFunc(GL_NOTEQUAL, selected, 0xFF); | 313 | Vec3 centre = g.position + Vec3{0.0f, 0.35f, 0.0f}; |
| 335 | glStencilMask(0x00); // 輪郭はステンシルに書かない / the outline does not write to the stencil buffer | 314 | transparent.push_back({length(centre - viewPos), grassMode == 2, [&, g] { |
| 336 | if (xray) glDisable(GL_DEPTH_TEST); // 他の物の後ろでも見える / visible even behind other objects | 315 | grassMaterial.apply(*phong, white); // 窓が別のマテリアルを設定したかも / a window may have set another material |
| 337 | unlit->use(); | 316 | drawTuft(g); |
| 338 | unlit->set("uView", view); | 317 | }}); |
| 339 | unlit->set("uProj", proj); | ||
| 340 | unlit->set("uColor", Vec3{1.0f, 0.55f, 0.1f}); | ||
| 341 | if (selected == kDioramaId) { | ||
| 342 | scene->drawGeometry(*unlit, outlineScale(*scene, 0.06f)); | ||
| 343 | } else { | ||
| 344 | const CrateInfo &c = kCrates[selected - 1]; | ||
| 345 | crate->drawGeometry(*unlit, translate(c.position) * rotateY(c.angle) * outlineScale(*crate, 0.04f)); | ||
| 346 | } | 318 | } |
| 347 | glEnable(GL_DEPTH_TEST); | ||
| 348 | glStencilMask(0xFF); | ||
| 349 | } | 319 | } |
| 350 | 320 | if (sortTransparent) | |
| 351 | // 照準:シザーテストで小さな長方形を二つクリアするだけ(シェーダーなし) | 321 | std::stable_sort(transparent.begin(), transparent.end(), |
| 352 | // The crosshair: just clear two small rectangles with the scissor test (no shader) | 322 | [](const Transparent &a, const Transparent &b) { return a.distance > b.distance; }); |
| 353 | if (!useOrbit && window.cursorCaptured()) { | 323 | |
| 354 | int cx = window.width() / 2, cy = window.height() / 2; | 324 | glEnable(GL_BLEND); |
| 355 | glEnable(GL_SCISSOR_TEST); | 325 | // 結果 = src × srcの係数 + dst × dstの係数(glBlendEquationの既定はGL_FUNC_ADD) |
| 356 | glClearColor(1.0f, 1.0f, 1.0f, 1.0f); | 326 | // result = src × src factor + dst × dst factor (glBlendEquation defaults to GL_FUNC_ADD) |
| 357 | glScissor(cx - 8, cy - 1, 17, 3); | 327 | glBlendEquation(GL_FUNC_ADD); |
| 358 | glClear(GL_COLOR_BUFFER_BIT); | 328 | if (!blendDepthWrite) glDepthMask(GL_FALSE); // 深度テストはするが、書かない / still depth-test, but do not write |
| 359 | glScissor(cx - 1, cy - 8, 3, 17); | 329 | for (const Transparent &t : transparent) { |
| 360 | glClear(GL_COLOR_BUFFER_BIT); | 330 | // ストレートアルファ:色 × α + 後ろ × (1 − α)。乗算済み:色(もう × α済み) + 後ろ × (1 − α)。 |
| 361 | glDisable(GL_SCISSOR_TEST); | 331 | // アルファチャンネル自体は後半の2つの係数で1のまま:既定のフレームバッファが半透明にならないように |
| 332 | // Straight alpha: colour × α + behind × (1 − α). Premultiplied: colour (already × α) + behind × (1 − α). | ||
| 333 | // The last two factors keep the alpha channel at 1, so the default framebuffer does not turn translucent | ||
| 334 | if (t.premultiplied) glBlendFuncSeparate(GL_ONE, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA); | ||
| 335 | else glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA); | ||
| 336 | t.draw(); | ||
| 362 | } | 337 | } |
| 338 | glDepthMask(GL_TRUE); | ||
| 339 | glDisable(GL_BLEND); | ||
| 363 | 340 | ||
| 364 | window.swapBuffers(); | 341 | window.swapBuffers(); |
| 365 | } | 342 | } |
ファイル: a/src/material.cc | b/src/material.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -7,6 +7,10 @@ void Material::apply(const Shader &shader, const Texture2D &white) const { | |||
| 7 | shader.set("uMaterial.specular", specular); | 7 | shader.set("uMaterial.specular", specular); |
| 8 | shader.set("uMaterial.emission", emission); | 8 | shader.set("uMaterial.emission", emission); |
| 9 | shader.set("uMaterial.shininess", shininess); | 9 | shader.set("uMaterial.shininess", shininess); |
| 10 | shader.set("uMaterial.alpha", alpha); | ||
| 11 | shader.set("uMaterial.alphaMode", static_cast<int>(alphaMode)); | ||
| 12 | shader.set("uMaterial.alphaCutoff", alphaCutoff); | ||
| 13 | shader.set("uMaterial.doubleSided", doubleSided ? 1 : 0); // boolのユニフォームはintで設定する / bool uniforms are set as int | ||
| 10 | (diffuseMap ? diffuseMap : &white)->bind(0); | 14 | (diffuseMap ? diffuseMap : &white)->bind(0); |
| 11 | (specularMap ? specularMap : &white)->bind(1); | 15 | (specularMap ? specularMap : &white)->bind(1); |
| 12 | (emissionMap ? emissionMap : &white)->bind(2); | 16 | (emissionMap ? emissionMap : &white)->bind(2); |
ファイル: a/src/material.hh | b/src/material.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -5,6 +5,14 @@ | |||
| 5 | #include "shader.hh" | 5 | #include "shader.hh" |
| 6 | #include "texture.hh" | 6 | #include "texture.hh" |
| 7 | 7 | ||
| 8 | // アルファ(不透明度)の使い方。glTFのalphaModeと同じ。シェーダーでは0/1/2 | ||
| 9 | // How alpha (opacity) is used. Same as glTF's alphaMode; 0/1/2 in the shader | ||
| 10 | enum class AlphaMode { | ||
| 11 | Opaque = 0, // アルファを無視して不透明に描く / ignore alpha, draw opaque | ||
| 12 | Mask = 1, // alphaCutoff未満のピクセルを捨てる(discard)。草、葉、金網 / discard pixels below alphaCutoff: grass, leaves, fences | ||
| 13 | Blend = 2, // 後ろの色と混ぜる(ブレンディング)。ガラス、煙 / mix with what is behind (blending): glass, smoke | ||
| 14 | }; | ||
| 15 | |||
| 8 | // Blinn-Phongのマテリアル。色とマップ(テクスチャ)は掛け合わされる。マップがなければ白(=色だけ)。 | 16 | // Blinn-Phongのマテリアル。色とマップ(テクスチャ)は掛け合わされる。マップがなければ白(=色だけ)。 |
| 9 | // A Blinn-Phong material. Each colour is multiplied with its map (texture); no map means white (= the colour alone). | 17 | // A Blinn-Phong material. Each colour is multiplied with its map (texture); no map means white (= the colour alone). |
| 10 | struct Material { | 18 | struct Material { |
| @@ -13,6 +21,12 @@ struct Material { | |||
| 13 | Vec3 emission = {0.0f, 0.0f, 0.0f}; // 発光の色:光が当たらなくても見える / emission colour: visible even without light | 21 | Vec3 emission = {0.0f, 0.0f, 0.0f}; // 発光の色:光が当たらなくても見える / emission colour: visible even without light |
| 14 | float shininess = 32.0f; // 光沢度 / shininess | 22 | float shininess = 32.0f; // 光沢度 / shininess |
| 15 | 23 | ||
| 24 | float alpha = 1.0f; // 不透明度。diffuseMapのアルファと掛ける / opacity, multiplied with diffuseMap's alpha | ||
| 25 | AlphaMode alphaMode = AlphaMode::Opaque; | ||
| 26 | float alphaCutoff = 0.5f; // Maskのしきい値 / the Mask threshold | ||
| 27 | bool doubleSided = false; // 両面:裏面では法線を反転する(カリングはModelが切る) / double-sided: | ||
| 28 | // the normal is flipped on back faces (Model turns culling off) | ||
| 29 | |||
| 16 | const Texture2D *diffuseMap = nullptr; // テクスチャユニット0 / texture unit 0 | 30 | const Texture2D *diffuseMap = nullptr; // テクスチャユニット0 / texture unit 0 |
| 17 | const Texture2D *specularMap = nullptr; // テクスチャユニット1 / texture unit 1 | 31 | const Texture2D *specularMap = nullptr; // テクスチャユニット1 / texture unit 1 |
| 18 | const Texture2D *emissionMap = nullptr; // テクスチャユニット2 / texture unit 2 | 32 | const Texture2D *emissionMap = nullptr; // テクスチャユニット2 / texture unit 2 |
ファイル: a/src/model.cc | b/src/model.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -1,5 +1,6 @@ | |||
| 1 | #include "model.hh" | 1 | #include "model.hh" |
| 2 | 2 | ||
| 3 | #include <algorithm> | ||
| 3 | #include <cmath> | 4 | #include <cmath> |
| 4 | #include <cstdio> | 5 | #include <cstdio> |
| 5 | 6 | ||
| @@ -35,6 +36,13 @@ static Material phongFromPbr(const GltfMaterial &m, float metallicScale, float r | |||
| 35 | p.specular = ((n + 8.0f) / 8.0f) * f0; | 36 | p.specular = ((n + 8.0f) / 8.0f) * f0; |
| 36 | p.shininess = n; | 37 | p.shininess = n; |
| 37 | p.emission = m.emissiveStrength * m.emissiveFactor; | 38 | p.emission = m.emissiveStrength * m.emissiveFactor; |
| 39 | // 透明の扱いはglTFのまま(第16章) / alpha handling straight from glTF (chapter 16) | ||
| 40 | p.alpha = m.baseColorFactor.w; | ||
| 41 | p.alphaMode = m.alphaMode == GltfAlphaMode::Mask ? AlphaMode::Mask | ||
| 42 | : m.alphaMode == GltfAlphaMode::Blend ? AlphaMode::Blend | ||
| 43 | : AlphaMode::Opaque; | ||
| 44 | p.alphaCutoff = m.alphaCutoff; | ||
| 45 | p.doubleSided = m.doubleSided; | ||
| 38 | return p; | 46 | return p; |
| 39 | } | 47 | } |
| 40 | 48 | ||
| @@ -256,32 +264,70 @@ Mat4 Model::nodeTransform(int node) const { | |||
| 256 | } | 264 | } |
| 257 | 265 | ||
| 258 | void Model::draw(const Shader &shader, const Mat4 &transform, const Texture2D &white, bool hierarchy) const { | 266 | void Model::draw(const Shader &shader, const Mat4 &transform, const Texture2D &white, bool hierarchy) const { |
| 259 | for (int root : roots) drawNode(root, transform, transform, shader, &white, hierarchy, true); | 267 | std::vector<DrawItem> items; |
| 268 | for (int root : roots) collect(root, transform, transform, hierarchy, ModelPass::All, {}, items); | ||
| 269 | drawItems(items, shader, &white, true); | ||
| 270 | } | ||
| 271 | |||
| 272 | void Model::draw(const Shader &shader, const Mat4 &transform, const Texture2D &white, ModelPass pass, | ||
| 273 | Vec3 viewPos) const { | ||
| 274 | std::vector<DrawItem> items; | ||
| 275 | for (int root : roots) collect(root, transform, transform, true, pass, viewPos, items); | ||
| 276 | if (pass == ModelPass::Transparent) { | ||
| 277 | // 遠いものから描く:手前の半透明が、もう描かれた後ろの色と混ざるように | ||
| 278 | // Draw the farthest first, so each nearer transparent surface mixes with what is already behind it | ||
| 279 | std::stable_sort(items.begin(), items.end(), | ||
| 280 | [](const DrawItem &a, const DrawItem &b) { return a.distance > b.distance; }); | ||
| 281 | } | ||
| 282 | drawItems(items, shader, &white, true); | ||
| 260 | } | 283 | } |
| 261 | 284 | ||
| 262 | void Model::drawGeometry(const Shader &shader, const Mat4 &transform) const { | 285 | void Model::drawGeometry(const Shader &shader, const Mat4 &transform) const { |
| 263 | bool normals = shader.has("uNormalMatrix"); | 286 | std::vector<DrawItem> items; |
| 264 | for (int root : roots) drawNode(root, transform, transform, shader, nullptr, true, normals); | 287 | for (int root : roots) collect(root, transform, transform, true, ModelPass::All, {}, items); |
| 288 | drawItems(items, shader, nullptr, shader.has("uNormalMatrix")); | ||
| 289 | } | ||
| 290 | |||
| 291 | const Model::MaterialData &Model::materialOf(const Primitive &p) const { | ||
| 292 | return p.material >= 0 ? materials[static_cast<size_t>(p.material)] : defaultMaterial; | ||
| 265 | } | 293 | } |
| 266 | 294 | ||
| 267 | void Model::drawNode(int node, const Mat4 &parentWorld, const Mat4 &transform, const Shader &shader, | 295 | void Model::collect(int node, const Mat4 &parentWorld, const Mat4 &transform, bool hierarchy, ModelPass pass, |
| 268 | const Texture2D *white, bool hierarchy, bool normals) const { | 296 | Vec3 viewPos, std::vector<DrawItem> &out) const { |
| 269 | const GltfNode &n = nodes[static_cast<size_t>(node)]; | 297 | const GltfNode &n = nodes[static_cast<size_t>(node)]; |
| 270 | // ワールド行列 = 親のワールド行列 × 自分のローカル行列 / world = the parent's world matrix × our local matrix | 298 | // ワールド行列 = 親のワールド行列 × 自分のローカル行列 / world = the parent's world matrix × our local matrix |
| 271 | Mat4 world = (hierarchy ? parentWorld : transform) * n.localTransform(); | 299 | Mat4 world = (hierarchy ? parentWorld : transform) * n.localTransform(); |
| 272 | if (n.mesh >= 0) { | 300 | if (n.mesh >= 0) { |
| 273 | shader.set("uModel", world); | ||
| 274 | if (normals) shader.set("uNormalMatrix", normalMatrix(world)); | ||
| 275 | for (const Primitive &p : meshes[static_cast<size_t>(n.mesh)].primitives) { | 301 | for (const Primitive &p : meshes[static_cast<size_t>(n.mesh)].primitives) { |
| 276 | if (white) { | 302 | bool blend = materialOf(p).phong.alphaMode == AlphaMode::Blend; |
| 277 | const MaterialData &md = p.material >= 0 ? materials[static_cast<size_t>(p.material)] : defaultMaterial; | 303 | if ((pass == ModelPass::Opaque && blend) || (pass == ModelPass::Transparent && !blend)) continue; |
| 278 | Material m = md.phong; | 304 | Vec3 c = 0.5f * (p.boundsMin + p.boundsMax); |
| 279 | m.diffuseMap = texture(md.pbr.baseColorTexture.index); // 色 = 係数 × テクスチャ / colour = factor × texture | 305 | Vec4 centre = world * Vec4{c.x, c.y, c.z, 1.0f}; |
| 280 | m.emissionMap = texture(md.pbr.emissiveTexture.index); | 306 | out.push_back({&p, world, length(Vec3{centre.x, centre.y, centre.z} - viewPos)}); |
| 281 | m.apply(shader, *white); | 307 | } |
| 282 | } | 308 | } |
| 283 | p.mesh.draw(); | 309 | for (int child : n.children) collect(child, world, transform, hierarchy, pass, viewPos, out); |
| 310 | } | ||
| 311 | |||
| 312 | void Model::drawItems(const std::vector<DrawItem> &items, const Shader &shader, const Texture2D *white, | ||
| 313 | bool normals) const { | ||
| 314 | bool culling = glIsEnabled(GL_CULL_FACE); // 呼ぶ側の設定を覚えておく / remember the caller's setting | ||
| 315 | for (const DrawItem &item : items) { | ||
| 316 | const Primitive &p = *item.primitive; | ||
| 317 | const MaterialData &md = materialOf(p); | ||
| 318 | shader.set("uModel", item.world); | ||
| 319 | if (normals) shader.set("uNormalMatrix", normalMatrix(item.world)); | ||
| 320 | if (white) { | ||
| 321 | Material m = md.phong; | ||
| 322 | m.diffuseMap = texture(md.pbr.baseColorTexture.index); // 色 = 係数 × テクスチャ / colour = factor × texture | ||
| 323 | m.emissionMap = texture(md.pbr.emissiveTexture.index); | ||
| 324 | m.apply(shader, *white); | ||
| 284 | } | 325 | } |
| 326 | // 両面のマテリアル(葉、ガラス、帆)は裏からも見えるようにカリングを切る | ||
| 327 | // Double-sided materials (leaves, glass, sails) must be visible from behind: no culling for them | ||
| 328 | bool noCull = culling && md.phong.doubleSided; | ||
| 329 | if (noCull) glDisable(GL_CULL_FACE); | ||
| 330 | p.mesh.draw(); | ||
| 331 | if (noCull) glEnable(GL_CULL_FACE); | ||
| 285 | } | 332 | } |
| 286 | for (int child : n.children) drawNode(child, world, transform, shader, white, hierarchy, normals); | ||
| 287 | } | 333 | } |
ファイル: a/src/model.hh | b/src/model.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -12,6 +12,14 @@ | |||
| 12 | #include <string_view> | 12 | #include <string_view> |
| 13 | #include <vector> | 13 | #include <vector> |
| 14 | 14 | ||
| 15 | // どのプリミティブを描くか(マテリアルのalphaModeで分ける) / which primitives to draw (split by the material's alphaMode) | ||
| 16 | enum class ModelPass { | ||
| 17 | All, // 全部、ファイルの順に / everything, in file order | ||
| 18 | Opaque, // OpaqueとMask / Opaque and Mask | ||
| 19 | Transparent, // Blendだけ、カメラから遠い順(ブレンドの設定は呼ぶ側) / Blend only, farthest from the camera first | ||
| 20 | // (the caller sets up blending) | ||
| 21 | }; | ||
| 22 | |||
| 15 | // 読み込んだモデル:メッシュ(VAO)、テクスチャ、マテリアル、ノードの階層(RAII、コピー不可・移動可)。 | 23 | // 読み込んだモデル:メッシュ(VAO)、テクスチャ、マテリアル、ノードの階層(RAII、コピー不可・移動可)。 |
| 16 | // 描くときは、ノードごとに 親のワールド行列 × 自分のローカル行列 をたどる。 | 24 | // 描くときは、ノードごとに 親のワールド行列 × 自分のローカル行列 をたどる。 |
| 17 | // A loaded model: meshes (VAOs), textures, materials and the node hierarchy (RAII, non-copyable, movable). | 25 | // A loaded model: meshes (VAOs), textures, materials and the node hierarchy (RAII, non-copyable, movable). |
| @@ -50,6 +58,12 @@ public: | |||
| 50 | // Draws with transform (where the whole model goes). Binds `white` for missing maps. | 58 | // Draws with transform (where the whole model goes). Binds `white` for missing maps. |
| 51 | // hierarchy = false ignores the parents' transforms (to show why parent × child is needed). | 59 | // hierarchy = false ignores the parents' transforms (to show why parent × child is needed). |
| 52 | void draw(const Shader &shader, const Mat4 &transform, const Texture2D &white, bool hierarchy = true) const; | 60 | void draw(const Shader &shader, const Mat4 &transform, const Texture2D &white, bool hierarchy = true) const; |
| 61 | // passのプリミティブだけを描く。Transparentでは、viewPosから各プリミティブの箱の中心までの距離で遠い順に並べる。 | ||
| 62 | // 両面(doubleSided)のマテリアルは、その間だけフェイスカリングを切って描く。 | ||
| 63 | // Draws only the primitives of `pass`. Transparent sorts them back to front by the distance from viewPos to the | ||
| 64 | // centre of each primitive's box. Double-sided materials are drawn with face culling turned off for that draw. | ||
| 65 | void draw(const Shader &shader, const Mat4 &transform, const Texture2D &white, ModelPass pass, | ||
| 66 | Vec3 viewPos = {}) const; | ||
| 53 | // 形だけを描く:マテリアルもテクスチャも設定せず、ノードごとにuModelだけ(シェーダーが使っていればuNormalMatrixも)。 | 67 | // 形だけを描く:マテリアルもテクスチャも設定せず、ノードごとにuModelだけ(シェーダーが使っていればuNormalMatrixも)。 |
| 54 | // 深度の表示、輪郭、のちの影(第23章)のように、色を使わないパス用。 | 68 | // 深度の表示、輪郭、のちの影(第23章)のように、色を使わないパス用。 |
| 55 | // Draws the shape only: no materials or textures, just uModel per node (and uNormalMatrix if the shader uses it). | 69 | // Draws the shape only: no materials or textures, just uModel per node (and uNormalMatrix if the shader uses it). |
| @@ -74,9 +88,18 @@ public: | |||
| 74 | size_t textureCount() const { return textures.size(); } | 88 | size_t textureCount() const { return textures.size(); } |
| 75 | 89 | ||
| 76 | private: | 90 | private: |
| 91 | // 描くもの一つ:プリミティブとそのワールド行列 / one thing to draw: a primitive and its world matrix | ||
| 92 | struct DrawItem { | ||
| 93 | const Primitive *primitive; | ||
| 94 | Mat4 world; | ||
| 95 | float distance; // カメラからの距離(Transparentの並べ替え用) / distance from the camera (for sorting) | ||
| 96 | }; | ||
| 97 | // ノードの階層をたどってpassのプリミティブを集める / walks the node hierarchy collecting the primitives of `pass` | ||
| 98 | void collect(int node, const Mat4 &parentWorld, const Mat4 &transform, bool hierarchy, ModelPass pass, | ||
| 99 | Vec3 viewPos, std::vector<DrawItem> &out) const; | ||
| 77 | // white == nullptrなら形だけ(drawGeometry) / white == nullptr: shape only (drawGeometry) | 100 | // white == nullptrなら形だけ(drawGeometry) / white == nullptr: shape only (drawGeometry) |
| 78 | void drawNode(int node, const Mat4 &parentWorld, const Mat4 &transform, const Shader &shader, | 101 | void drawItems(const std::vector<DrawItem> &items, const Shader &shader, const Texture2D *white, bool normals) const; |
| 79 | const Texture2D *white, bool hierarchy, bool normals) const; | 102 | const MaterialData &materialOf(const Primitive &p) const; |
| 80 | const Texture2D *texture(int index) const; // なければnullptr / nullptr if missing | 103 | const Texture2D *texture(int index) const; // なければnullptr / nullptr if missing |
| 81 | 104 | ||
| 82 | std::vector<MeshData> meshes; | 105 | std::vector<MeshData> meshes; |
ファイル: a/src/shapes.cc | b/src/shapes.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -69,3 +69,20 @@ Mesh makeSphere(int segments, int rings) { | |||
| 69 | } | 69 | } |
| 70 | return Mesh(vertices, indices, kVertex3DLayout); | 70 | return Mesh(vertices, indices, kVertex3DLayout); |
| 71 | } | 71 | } |
| 72 | |||
| 73 | Mesh makeCrossedQuads(int count) { | ||
| 74 | std::vector<Vertex3D> vertices; | ||
| 75 | std::vector<std::uint32_t> indices; | ||
| 76 | Vec3 up = {0.0f, 1.0f, 0.0f}; | ||
| 77 | for (int i = 0; i < count; ++i) { | ||
| 78 | float a = PI * static_cast<float>(i) / static_cast<float>(count); // 0〜180度(板は両面なので) / 0..180° (quads are two-sided) | ||
| 79 | Vec3 r = {0.5f * std::cos(a), 0.0f, -0.5f * std::sin(a)}; // 板の右半分 / half the quad, to the right | ||
| 80 | std::uint32_t first = static_cast<std::uint32_t>(vertices.size()); | ||
| 81 | vertices.push_back({-1.0f * r, up, {0.0f, 0.0f}}); | ||
| 82 | vertices.push_back({r, up, {1.0f, 0.0f}}); | ||
| 83 | vertices.push_back({r + up, up, {1.0f, 1.0f}}); | ||
| 84 | vertices.push_back({up - r, up, {0.0f, 1.0f}}); | ||
| 85 | indices.insert(indices.end(), {first, first + 1, first + 2, first + 2, first + 3, first}); | ||
| 86 | } | ||
| 87 | return Mesh(vertices, indices, kVertex3DLayout); | ||
| 88 | } | ||
ファイル: a/src/shapes.hh | b/src/shapes.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -18,3 +18,10 @@ Mesh makePlane(float size, float uvRepeat); | |||
| 18 | // A sphere of diameter 1 centred on the origin (a UV sphere). segments = divisions around, rings = from pole to pole. | 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. | 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); | 20 | Mesh makeSphere(int segments = 32, int rings = 16); |
| 21 | |||
| 22 | // 縦の1×1の板をcount枚、Y軸の周りに等間隔で回して重ねたもの(草の株)。原点は下の辺の真ん中、UVのv = 0が下。 | ||
| 23 | // 法線はすべて上(+Y):草を地面と同じように照らすための定番のごまかし。両面から見えるのでカリングを切って描く。 | ||
| 24 | // count vertical 1 × 1 quads turned evenly about the Y axis (a tuft of grass). Origin at the middle of the bottom | ||
| 25 | // edge, v = 0 at the bottom. All normals point up (+Y): the usual trick to light grass like the ground it grows on. | ||
| 26 | // Seen from both sides, so draw it with face culling off. | ||
| 27 | Mesh makeCrossedQuads(int count = 3); | ||
ファイル: a/src/texture.cc | b/src/texture.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -42,7 +42,16 @@ Texture2D &Texture2D::operator=(Texture2D &&other) noexcept { | |||
| 42 | Texture2D Texture2D::fromPixels(const unsigned char *rgba, int width, int height, const TextureOptions &options) { | 42 | Texture2D Texture2D::fromPixels(const unsigned char *rgba, int width, int height, const TextureOptions &options) { |
| 43 | int levels = options.mipmaps ? mipLevelCount(width, height) : 1; | 43 | int levels = options.mipmaps ? mipLevelCount(width, height) : 1; |
| 44 | Texture2D texture(width, height, options.srgb ? GL_SRGB8_ALPHA8 : GL_RGBA8, levels); | 44 | Texture2D texture(width, height, options.srgb ? GL_SRGB8_ALPHA8 : GL_RGBA8, levels); |
| 45 | texture.upload(rgba); | 45 | if (options.premultiplyAlpha) { |
| 46 | // 乗算済みアルファ:色 × アルファ。透明なピクセルの色は(何色でも)0になる | ||
| 47 | // premultiplied alpha: colour × alpha. Transparent pixels become 0 whatever colour they had | ||
| 48 | std::vector<unsigned char> pm(rgba, rgba + static_cast<size_t>(width) * static_cast<size_t>(height) * 4); | ||
| 49 | for (size_t i = 0; i < pm.size(); i += 4) | ||
| 50 | for (size_t c = 0; c < 3; ++c) pm[i + c] = static_cast<unsigned char>((pm[i + c] * pm[i + 3] + 127) / 255); | ||
| 51 | texture.upload(pm.data()); | ||
| 52 | } else { | ||
| 53 | texture.upload(rgba); | ||
| 54 | } | ||
| 46 | if (options.mipmaps) texture.generateMipmaps(); | 55 | if (options.mipmaps) texture.generateMipmaps(); |
| 47 | return texture; | 56 | return texture; |
| 48 | } | 57 | } |
ファイル: a/src/texture.hh | b/src/texture.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -12,6 +12,9 @@ struct TextureOptions { | |||
| 12 | bool flipY = true; // 画像は上から、OpenGLのUVは下から / images start at the top, OpenGL UVs at the bottom | 12 | bool flipY = true; // 画像は上から、OpenGLのUVは下から / images start at the top, OpenGL UVs at the bottom |
| 13 | bool mipmaps = true; // ミップマップを作る / build mipmaps | 13 | bool mipmaps = true; // ミップマップを作る / build mipmaps |
| 14 | bool srgb = false; // 色の画像はsRGB(正しい扱いは第21章) / colour images are sRGB (handled properly in chapter 21) | 14 | bool srgb = false; // 色の画像はsRGB(正しい扱いは第21章) / colour images are sRGB (handled properly in chapter 21) |
| 15 | // RGBにアルファを掛けてからアップロードする(乗算済みアルファ、第16章)。ミップマップもその値から作られる。 | ||
| 16 | // Multiply RGB by alpha before uploading (premultiplied alpha, chapter 16). Mipmaps are then built from those values. | ||
| 17 | bool premultiplyAlpha = false; | ||
| 15 | }; | 18 | }; |
| 16 | 19 | ||
| 17 | // デコードした画像:RGBA8、上の行から順に / a decoded image: RGBA8, rows from the top | 20 | // デコードした画像:RGBA8、上の行から順に / a decoded image: RGBA8, rows from the top |
コメント(0)
まだコメントはありません。
ログインするとコメント出来ます。