12. 光源と複数のライト
第10章から、シーンの光は1つだけでした。
木箱の周りを回る小さな立方体で、どれだけ離れていても同じ強さで全方向に光を出していました。
本物のシーンには沢山の光があり、形も様々です。
太陽や月、電球や提灯、懐中電灯や舞台のスポットライト。
此の章では、決め打ちの1つの光をライトの仕組みに変えます。
3種類の光源(平行光源・点光源・スポットライト)、其れらを1つのシェーダーで自由に組み合わせる事、そして全部を毎フレームGPUに送る小さなC++のLightSetです。
ライティングの数学自体は新しくありません。
GLSLシリーズで全て作りました。
光の種類と向きの決まりは第4章、ポイントライトと減衰は第9章、スポットライトと沢山の光は第10章です。
此処では簡単に復習し、新しい部分に時間を使います。
ユニフォームとしての構造体の配列、其れをC++から設定する方法、そして数の変わる光をループするフラグメントシェーダーの組み立て方です。
此の章に新しいOpenGLの関数はありません。
12.1 此の章で作る物
第11章の木箱置き場の夜です。
青白い月が全体を少しだけ照らし、色の違う4つの提灯が置き場の上を漂い、スポットライトが真ん中の木箱の山を上から照らし、そして自分は見ている所を照らす懐中電灯を持っています:
第9〜11章の操作は其のままです(WASD、マウス、Shift、C、V、Tab、R、Esc)。
新しい物と変わった物:
- 1:平行光源(月)のオン・オフ
- 2:点光源(提灯)のオン・オフ
- 3:全てのスポットライトのオン・オフ
- F:懐中電灯のオン・オフ
- P:提灯の動きを止める・動かす
- V:第11章の表示モード(全部、環境光、拡散反射、鏡面反射、発光、法線)は其のまま動き、今度は全ての光の合計を表示します
第11章のL、M、Eキーは無くなりました。
木箱は常に鏡面反射マップと発光マップを使います。
第11章からの変更:
src/lights.hhとsrc/lights.cc(新規):光の構造体、減衰の定数、LightSetshaders/phong.frag:光の構造体、ユニフォームの配列、光の種類毎に1つのループsrc/main.cc:夜のシーン。毎フレームLightSetに組み立てるCMakeLists.txt:新しいソースファイル
phong.vertとライティング無しのシェーダーは変わりません。
12.2 3種類の光
復習
あたし達が使う光は、全てピクセル毎に2つの質問に答えます。
光はどの向きから届くのか、そしてどれだけ届くのか、です。
古典的な3つの光源は、其れに違う答え方をします:
| 光 | 光へ向かう向き | 届く量 | 例 |
|---|---|---|---|
| 平行光源 | 全てのピクセルで同じ | 常に色の全部 | 太陽、月 |
| 点光源 | ピクセルから光の位置へ | 距離で弱くなる | 電球、提灯 |
| スポットライト | 点光源と同じ | 点光源と同じ物に円錐の係数を掛ける | 懐中電灯、舞台照明 |
平行光源(ディレクショナルライト)はとても遠くにあるので、光線が平行です。
位置が無く、向きだけがあり、弱くなりません。
太陽は庭の左でも右でも同じ明るさです。
点光源(ポイントライト)には位置があります。
ワールド座標のピクセルに対して、光へ向かう向きと距離は次の通りです(GLSLシリーズの9.6.1節):
そして明るさは、GLSLシリーズの9.6.2節の減衰の多項式で距離と共に弱くなります:
は光の所で値を1に保ち、二次の項は遠くで勝つ物理的な逆二乗の部分で、一次の項は其の間の弱まり方を形作ります。
其の章の表から3行を、GLSLシリーズ第10章と同じ名前で使います:
| 名前 | 範囲(大体) | |||
|---|---|---|---|---|
kShortRange |
7 | 1.0 | 0.7 | 1.8 |
kMediumRange |
13 | 1.0 | 0.35 | 0.44 |
kLongRange |
50 | 1.0 | 0.09 | 0.032 |
スポットライトは、軸の周りの円錐の中だけを照らす点光源です。
軸と「光からピクセルへの向き」の間の角度で、ピクセルが受け取る光の量が決まります。
2つの単位ベクトルの内積は其の角度のコサインなので(線型代数シリーズの第4章)、角度其の物は必要ありません。
内側の円錐の中では全部の明るさ、外側の円錐の外では0、其の間はsmoothstepで弱めます(GLSLシリーズの10.2節):
外側の角度の方が大きいので、其のコサインは小さい方の数で、先に来ます。
smoothstepは1つ目の縁が2つ目より小さくないと未定義です。
其の後、どの光も第10・11章の1つの光と同じBlinn-Phongのコードを通り、其の色には減衰(と円錐の係数)が掛けられます。
光は単純に足し算です。
最終的な色は、環境光、全ての光の拡散反射と鏡面反射、そして発光の合計です。
向きはどちらを指すのか
此の章で正確に理解しなければならない事は此れ1つなので、丁寧に書きます。
「光の向き」は、正反対の2つのベクトルのどちらの意味にもなります(GLSLシリーズの第4章の「光の向きの決まり」):
- 光が進む向き:光から表面へ。月が右後ろの高い所にあるなら、其の光は前へ、左へ、下へ進みます。
- 光へ向かう向き:表面から光へ。ライティングの式が使うのは此方です。が「正面から当たる」という意味になるからです。
2つは正反対で、です。
此のシリーズでは、光が持つdirectionは全て光が進む向きです。
平行光源のdirectionも、スポットライトのdirection(円錐の軸、向いている先)もです。
人は光を其の様に考えますし(「スポットが木箱を向いている」「太陽が上から照らす」)、エンジンやファイル形式も其の様に保存します。
glTFのKHR_lights_punctualの光はノードのローカルな−Z軸の方へ照らし、此れも進む向きです。
シェーダーは必要な所でだけマイナスを付けてに変え、其れ以外の所では変えません。
点光源とスポットライトでは、シェーダーはどうせ位置からを計算するので、変換するのは2箇所だけです。
平行光源()と、スポットの円錐(、つまりスポットから此のピクセルへ光が進む向きを、スポット自身の進む向きと比べる)です。
間違えてもエラーにはならず、変な絵になります。
あたし達の月はdirection = {-0.4, -1, -0.6}で、正規化すると:
法線の床では:
マイナスがあれば、床は月の光の81%、にテクスチャの色を掛けた物を受け取ります。
無いと床は真っ黒になり、下を向いた面だけが照らされます。
まるで月が床の下にある様にです。
ライティングが「裏返し」に見えたら、先ず此の符号を確かめて下さい。
12.3 C++の光:lights.hh
新しいヘッダーは、減衰の定数と光の最大数から始まります:
// 光源:平行光源・点光源・スポットライト / light casters: directional, point and spot lights
#pragma once
#include "mathx.hh"
#include "shader.hh"
#include <vector>
// 減衰の定数(定数項・一次・二次)。GLSLシリーズ第9章の表から
// Attenuation constants (constant, linear, quadratic), from the table in GLSL series chapter 9
constexpr Vec3 kShortRange = {1.0f, 0.7f, 1.8f}; // 近くだけ照らす / lights only what is close
constexpr Vec3 kMediumRange = {1.0f, 0.35f, 0.44f}; // 中くらい / medium
constexpr Vec3 kLongRange = {1.0f, 0.09f, 0.032f}; // 遠くまで届く / reaches far
// シェーダーの MAX_POINT_LIGHTS、MAX_SPOT_LIGHTS と同じにすること
// Must match MAX_POINT_LIGHTS and MAX_SPOT_LIGHTS in the shader
constexpr int kMaxPointLights = 8;
constexpr int kMaxSpotLights = 4;
3つの定数は1つのVec3(x、y、z)に詰めます。
シェーダーは其れを1つのvec3として受け取るからです。
最大数は12.4節で説明します。
シェーダーの配列には決まった大きさが必要で、此の2つの数は両側で同じでなければなりません。
次に、光の種類毎に1つの構造体です:
// 平行光源(太陽・月):位置がなく、どこでも同じ向きから来る
// Directional light (sun, moon): no position, comes from the same direction everywhere
struct DirectionalLight {
Vec3 direction = {0.0f, -1.0f, 0.0f}; // 光が進む向き(光源へ向かう向きの逆) / the direction the light travels
Vec3 color = {0.0f, 0.0f, 0.0f}; // 色と明るさ。0 = オフ / colour and brightness; 0 = off
};
// 点光源(電球):一点から全方向へ、距離で弱くなる / point light (a bulb): all directions from one point, weaker with distance
struct PointLight {
Vec3 position;
Vec3 color = {1.0f, 1.0f, 1.0f};
Vec3 attenuation = kMediumRange;
};
// スポットライト(懐中電灯):円錐の中だけ。内側の円錐から外側の円錐まで滑らかに暗くなる
// Spotlight (a flashlight): only inside a cone; fades smoothly from the inner to the outer cone
struct SpotLight {
Vec3 position;
Vec3 direction = {0.0f, -1.0f, 0.0f};
Vec3 color = {1.0f, 1.0f, 1.0f};
float innerAngle = radians(12.5f); // ここまで全部の明るさ(円錐の半分の角度) / full brightness up to here (half angle)
float outerAngle = radians(17.5f); // ここから先は0 / zero from here on
Vec3 attenuation = kLongRange;
};
注目して欲しい決定が幾つかあります:
- デフォルト値付きの単純な集成体。 第11章の
Materialと同じく、コンストラクターもゲッターもありません。C++20の指示付き初期化子で、デフォルトと違う物だけを書けます。SpotLight{.position = p, .direction = d}はデフォルトの円錐と範囲の白いスポットです。メンバーは宣言の順番に書く必要があります。 - 色が明るさ。 別の「強さ」はありません。
{2.0f, 1.9f, 1.6f}は明るく暖かい光で、黒い色は光を消します。平行光源のデフォルトは黒なので、太陽の無いシーンは単に設定しないだけで良く、シェーダーには「有効」フラグが要りません。 - 平行光源には位置が無く、向き(光が進む向き、12.2節)だけがあります。デフォルトは真下です。
- スポットの角度は半角です。 軸から円錐の縁迄を、
linalg.hhの全てと同じくラジアンで測ります。12.5°と17.5°なら、全部の明るさの所が25°の幅で、35°迄弱まっていく懐中電灯の光になります。人は角度で考えるので構造体は角度を持ち、applyがフレーム毎に1回コサインに変えます。 - デフォルトの範囲が違います。 点光源は部屋を照らし(
kMediumRange)、スポットライトは大抵もっと遠くの物に向けます(kLongRange)。
最後に、シーンの全ての光の集まりです:
// シーンの全部の光 / all the lights of a scene
struct LightSet {
Vec3 ambient = {0.05f, 0.05f, 0.05f};
DirectionalLight directional;
std::vector<PointLight> points;
std::vector<SpotLight> spots;
// 全部の光をシェーダーのユニフォームに設定する。最大数を超えた分は使わない。
// Sets all lights as shader uniforms. Lights beyond the maximum count are ignored.
void apply(const Shader &shader) const;
};
環境光の色が1つ、平行光源が最大1つ(シーンの太陽や月は1つです)、そしてstd::vectorに入った好きな数の点光源とスポットライトです。
LightSetは値です。
mainはシーンの状態から毎フレーム新しい物を作るので、動く光、光を点けたり消したりするキー、カメラに付いて来る懐中電灯が、どれもとても簡単になります。
1フレームに数十個の小さな構造体は何のコストにもなりません。
12.4 GLSLの光:構造体とユニフォームの配列
構造体
phong.fragにも同じ3つの構造体を書きます。
第10・11章のユニフォームuLightPosとuLightColorは無くなり、uAmbientとuViewPosは残ります:
// 平行光源:向きだけ / directional light: a direction only
struct DirectionalLight {
vec3 direction; // 光が進む向き(単位ベクトル) / the direction the light travels (unit vector)
vec3 color; // 0 = オフ / 0 = off
};
// 点光源:位置と減衰 / point light: a position and attenuation
struct PointLight {
vec3 position;
vec3 color;
vec3 attenuation; // 定数項・一次・二次 / constant, linear, quadratic
};
// スポットライト:点光源+円錐 / spotlight: a point light + a cone
struct SpotLight {
vec3 position;
vec3 direction; // 円錐の軸(単位ベクトル) / the cone's axis (unit vector)
vec3 color;
float cosInner; // 内側の円錐の半角のコサイン / cosine of the inner cone's half angle
float cosOuter; // 外側の円錐の半角のコサイン / cosine of the outer cone's half angle
vec3 attenuation;
};
メンバーはC++の構造体と同じですが、スポットライトは角度の代わりに其のコサインを受け取ります。
GLSLの構造体はC++の物と同じメモリ配置である必要はありません。
全てのメンバーを名前で設定するので(12.5節)、ドライバーは好きな所に置けます。
其れが変わるのは第19章で、光がユニフォームバッファに移り、バイトが揃わなければならなくなる時です。
配列と数
// C++側の kMaxPointLights、kMaxSpotLights と同じ / same as kMaxPointLights and kMaxSpotLights in C++
#define MAX_POINT_LIGHTS 8
#define MAX_SPOT_LIGHTS 4
uniform DirectionalLight uDirLight;
uniform PointLight uPointLights[MAX_POINT_LIGHTS];
uniform int uPointLightCount; // 使っている数 / how many are in use
uniform SpotLight uSpotLights[MAX_SPOT_LIGHTS];
uniform int uSpotLightCount;
uniform vec3 uAmbient; // 環境光の色と明るさ / ambient light colour and brightness
uniform vec3 uViewPos; // カメラの位置(ワールド座標) / camera position (world space)
ユニフォームは構造体にも出来、構造体の配列にも出来ます。
GLSLの配列の大きさは常にコンパイル時に決まっているので、点光源8個とスポットライト4個分の場所を宣言し、此のフレームで実際に使う数をカウントとして送ります。
シェーダーはカウント迄しかループしないので、使わない要素の中身はどうでも良い事です。
消した光は使わない場所に古い値を残しますが、誰も読みません。
#defineはCと同じ様に動きます。
GLSLには#define、#if、#ifdefなどのプリプロセッサーがあります。
const int MAX_POINT_LIGHTS = 8;でも同じ様に動きます。
定数の整数式でも配列の大きさを決められるので、好きな方を選んで下さい。
大事なのは隣のコメントです。
此の数は此処とC++のkMaxPointLightsの2箇所にあり、一致しているかどうかを確かめる物は何もありません。
何故8と4の様な上限があるのでしょうか?
ユニフォームの記憶域には限りがあります。
OpenGL 4.6が保証するのは、フラグメントシェーダーのデフォルトブロックのユニフォームで最低1024成分(float)です(GL_MAX_FRAGMENT_UNIFORM_COMPONENTS)。
PointLightは9個のfloat、SpotLightは14個で、ドライバーは各vec3をvec4に切り上げる事がよくあります。
2つの配列は其の成分の128〜180個位を使い、上限には十分収まります。
大きなコストは時間の方です。
全てのピクセルが全ての光をループするので、遠くの光でも隣にある光と同じだけ掛かります。
本物のエンジンがどうしているかは12.8節で書きます。
12.5 C++から構造体の配列を設定する
ユニフォームの名前
構造体の配列の1つの要素の1つのメンバーは、どうやって設定するのでしょうか?
GLSLで書くのと全く同じ、完全な名前で設定します:
uDirLight.direction:構造体のメンバーuPointLights[2].color:構造体の配列の要素2のメンバーuPointLightCount:今迄通りの普通のユニフォーム
glGetUniformLocation(第5章)は此れらの文字列を受け付け、全ての要素の全てのメンバーが、其々自分のロケーションを持つ別々のユニフォームです。
glProgramUniform*で構造体の配列全体を1回で送る方法はありません。
其れが出来るのは基本型の配列だけです(uniform vec3 uColors[3]は1回のglProgramUniform3fvと数で設定出来ます。GLSLシリーズの10.4.2節でuLightColorsを1回のglUniform3fvで設定したのと同じです)。
構造体はメンバー毎に設定します。
Shader::setは既にconst char *の名前を受け取るので、必要なのは数字の2から"uPointLights[2].color"を作る方法だけです。
C++20には其れにぴったりの道具があります。
std::formatです。
lights.cc
#include "lights.hh"
#include <cmath>
#include <cstdio>
#include <format>
void LightSet::apply(const Shader &shader) const {
shader.set("uAmbient", ambient);
shader.set("uDirLight.direction", normalize(directional.direction));
shader.set("uDirLight.color", directional.color);
// 配列の要素のメンバーは「名前[番号].メンバー」で設定する / array elements: "name[index].member"
int pointCount = static_cast<int>(points.size());
if (pointCount > kMaxPointLights) {
fprintf(stderr, "点光源が多すぎる / too many point lights: %d (max %d)\n", pointCount, kMaxPointLights);
pointCount = kMaxPointLights;
}
for (int i = 0; i < pointCount; ++i) {
const PointLight &p = points[static_cast<size_t>(i)];
shader.set(std::format("uPointLights[{}].position", i).c_str(), p.position);
shader.set(std::format("uPointLights[{}].color", i).c_str(), p.color);
shader.set(std::format("uPointLights[{}].attenuation", i).c_str(), p.attenuation);
}
shader.set("uPointLightCount", pointCount);
std::format("uPointLights[{}].position", i)は、{}をiで置き換えたstd::stringを返します。
i = 2なら"uPointLights[2].position"です。
printfに似ていますが、大きな利点が2つあります。
各引数の型がコンパイル時に分かる事(intに合わない%dが無い)、そして間違った書式文字列がクラッシュではなくコンパイルエラーになる事です。
.c_str()はShader::setが欲しがるconst char *をくれます。
一時的な文字列は完全式の終わり迄生きているので、此れは安全です。
向きは此処、CPU上で、光とフレーム毎に1回正規化します。
其の為シーンのコードは都合の良いベクトルを何でも書け({-0.4f, -1.0f, -0.6f}や、スポットの「目標 − 位置」)、シェーダーは単位ベクトルを当てに出来ます。
linalg.hhのnormalizeはゼロベクトルに対してゼロベクトルを返すので、うっかりした向きはNaNではなく暗い光になります。
シェーダーが持てるより多くの光はプログラムの間違いなので、applyは其れをはっきり言います。
毎フレームstderrにメッセージを出し、余分な光は無視します。
比較をstd::minではなくifで書いているのは、windows.h(一部のGLADのバージョンや多くのライブラリが取り込みます)がminとmaxをマクロとして定義している為です。
スポットライトも同じ形で、変換が1つあります:
int spotCount = static_cast<int>(spots.size());
if (spotCount > kMaxSpotLights) {
fprintf(stderr, "スポットライトが多すぎる / too many spotlights: %d (max %d)\n", spotCount, kMaxSpotLights);
spotCount = kMaxSpotLights;
}
for (int i = 0; i < spotCount; ++i) {
const SpotLight &s = spots[static_cast<size_t>(i)];
shader.set(std::format("uSpotLights[{}].position", i).c_str(), s.position);
shader.set(std::format("uSpotLights[{}].direction", i).c_str(), normalize(s.direction));
shader.set(std::format("uSpotLights[{}].color", i).c_str(), s.color);
// シェーダーは角度ではなくコサインを比べる(acosを毎ピクセル計算しないため)
// The shader compares cosines, not angles (so it does not need acos for every pixel)
shader.set(std::format("uSpotLights[{}].cosInner", i).c_str(), std::cos(s.innerAngle));
shader.set(std::format("uSpotLights[{}].cosOuter", i).c_str(), std::cos(s.outerAngle));
shader.set(std::format("uSpotLights[{}].attenuation", i).c_str(), s.attenuation);
}
shader.set("uSpotLightCount", spotCount);
}
半角のstd::cosは、毎ピクセルのcos(或いはもっと悪いacos)の代わりに、此処でスポットとフレーム毎に1回だけ計算します。
ファイルをCMakeLists.txtに足します:
add_executable(game
src/main.cc
src/window.cc
src/gl_debug.cc
src/buffer.cc
src/mesh.cc
src/file_util.cc
src/shader.cc
src/texture.cc
src/shapes.cc
src/camera.cc
src/material.cc
src/lights.cc)
よくある間違い
- 2つの最大数が合っていない。 C++側がシェーダーの配列より多くの光を許すと、余分な要素の名前(
uPointLights[8].position)は存在せず、glGetUniformLocationは−1を返し、OpenGLは其の呼び出しを黙って無視します。あたし達のShaderクラスは名前毎に1回「no active uniform」の警告を出すので、其れで気付けます。逆の場合は何も壊れず、余分な場所が使われないだけです。 - 名前の打ち間違いも同じ振る舞いです。−1、警告、光無し。
uPointLight[0].color(sが無い)は定番です。 - カウントを忘れる。
uPointLightCountが無いとループは0回しか回らず(ユニフォームは0から始まります)、全ての点光源が消えている様に見えます。 - 名前の中の空白。
"uPointLights[ 2 ].color"は見つかりません。空白無しの正式な形と全く同じに書いて下さい。 - シェーダーが読まないメンバーはコンパイラーが消してしまい、其の場合もロケーションがありません。あたし達の光の構造体のメンバーは全て使われているので、此れは実験している時にだけ起こります。
プラットフォーム毎の注意:std::format
<format>はC++20の一部ですが、標準ライブラリに入ったのは他の部分より遅れました:
- Linux: GCC 13以降が必要です。Debian 13「trixie」(GCC 14)、Devuan 6「excalibur」、最近のUbuntuは問題ありません。Debian 12「bookworm」のGCC 12には
<format>が全くありません。ビルドはfatal error: format: No such file or directoryで止まります。libc++ 17以降を使うClangでも動きます。 - FreeBSD: ベースシステムのclangはlibc++を使い、現在のFreeBSDのリリースのclangなら十分新しいです。何もする必要はありません。
- Windows: Visual Studio 2022なら問題ありません(
CMAKE_CXX_STANDARD 20で/std:c++20が選ばれ、其れにstd::formatが含まれます)。
Debian 12で新しいコンパイラーを入れたくなければ、lights.ccのstd::formatを、小さなバッファへのsnprintfに置き換えて下さい。
此れはダウンロードには含まれない、回避策だけです:
// GCC 12(Debian 12)用:std::formatの代わりにsnprintf / for GCC 12 (Debian 12): snprintf instead of std::format
char name[64];
snprintf(name, sizeof(name), "uPointLights[%d].position", i);
shader.set(name, p.position);
#include <format>を消し、他の8つの名前も同じ様にします。
std::to_stringでも出来ます。
("uPointLights[" + std::to_string(i) + "].position").c_str()(#include <string>が必要)ですが、読むには長くなります。
どちらも全く同じ名前を作るので、他は何も変わりません。
此れで十分速いのか
あたし達のシーンでは、applyはフレーム毎に29回setを呼びます(環境光1、平行光源2、点光源のメンバー4 × 3とカウント1、スポットのメンバー2 × 6とカウント1)。
其々がglGetUniformLocationの文字列検索と、小さなstd::stringの確保を伴います。
光が最大数なら約50回です。
60フレーム毎秒で動くCPUにとっては何でもありませんが、光が数百個やシェーダーが沢山になると効いてきます。
第19章では光をユニフォームバッファオブジェクトに移します。
1回の呼び出しで書き込み、全てのシェーダーで共有する1つのメモリの塊です。
構造体は其の為に設計してあります。
全てのvec3のメンバーは、何も並べ替えずにvec4に埋められます。
12.6 フラグメントシェーダー
1つの表面、沢山の光
光の前に、シェーダーは今のピクセルについて光に依存しない事を全部1つの構造体に集めます:
// このピクセルの表面:どの光の計算にも同じものを使う / this pixel's surface: the same for every light
struct Surface {
vec3 position; // ワールド座標 / world space
vec3 normal; // 単位ベクトル / unit vector
vec3 view; // 目へ向かう単位ベクトル / unit vector towards the eye
vec3 diffuse; // マップを掛けた拡散反射の色 / diffuse colour with the map applied
vec3 specular; // マップを掛けた鏡面反射の色 / specular colour with the map applied
float shininess;
};
法線、視線ベクトル、マップから読む2つのマテリアルの色は、光毎ではなく1回だけ計算します。
特にテクスチャの読み込みです。
光が12個あるからといって、同じテクセルを12回読むべきではありません。
addLight:1つの光のBlinn-Phong
// 一つの光の拡散反射と鏡面反射(Blinn-Phong)を足す。l = 光へ向かう単位ベクトル
// Adds one light's diffuse and specular (Blinn-Phong) light. l = unit vector towards the light
void addLight(Surface s, vec3 l, vec3 lightColor, inout vec3 diffuse, inout vec3 specular) {
float diff = max(dot(s.normal, l), 0.0);
if (diff <= 0.0) return; // 裏から照らされている / lit from behind
vec3 h = normalize(l + s.view);
diffuse += diff * s.diffuse * lightColor;
specular += pow(max(dot(s.normal, h), 0.0), s.shininess) * s.specular * lightColor;
}
第10章のBlinn-Phongをmainから切り出し、光が何処から来るかに依存しない様にした物です。
光へ向かう向きと、減衰と円錐を既に含んだ光の色を受け取ります。
従って、どの種類の光も12.2節の2つの質問(どのか、どれだけの色か)に答えて、addLightを呼ぶだけで済みます。
光と反対を向いた表面では、第10章と同じく鏡面反射を飛ばします。
inoutは新しい物です。
GLSLにはポインターも参照も無く、引数はin(デフォルト:コピーが入る)、out(値が出てくる)、inout(コピーが入り、関数が戻る時に最後の値がコピーで戻される)の何れかです。
addLightは呼び出し側のdiffuseとspecularの合計に足していきます。
全部を1つの色に足さずに2つの合計を分けておくのは、Vキーの表示モードで全ての光を合わせた「拡散反射だけ」「鏡面反射だけ」を引き続き表示出来る様にする為です。
減衰の多項式は1行で、GLSLシリーズ第10章と同じ関数です:
// 距離dでの減衰(k = 定数項・一次・二次) / attenuation at distance d (k = constant, linear, quadratic)
float attenuate(float d, vec3 k) {
return 1.0 / (k.x + k.y * d + k.z * d * d);
}
main:表面
void main() {
Surface s;
s.position = vWorldPos;
s.normal = normalize(vNormal);
s.view = normalize(uViewPos - vWorldPos);
s.diffuse = uMaterial.diffuse * texture(uDiffuseMap, vUv).rgb;
s.specular = uMaterial.specular * texture(uSpecularMap, vUv).rgb;
s.shininess = uMaterial.shininess;
vec3 emission = uMaterial.emission * texture(uEmissionMap, vUv).rgb;
vec3 diffuse = vec3(0.0);
vec3 specular = vec3(0.0);
第11章のマテリアルのコードが、今度はsに書き込みます。
2つの合計は0から始まります。
平行光源
// 平行光源:光へ向かう向きは進む向きの逆 / directional: towards the light = the opposite of its direction
addLight(s, -uDirLight.direction, uDirLight.color, diffuse, specular);
12.2節のマイナスだけで、他には何もありません。
位置も、距離も、減衰もありません。
月が消えている時は色が黒なので、此の行は0を足します。
(ifで囲めば幾つかの命令を節約出来ますが、画面の全てのピクセルが同じ分岐を通るので、GPUにとってはどちらでも大差ありません。)
点光源
// 点光源 / point lights
for (int i = 0; i < uPointLightCount; ++i) {
vec3 toLight = uPointLights[i].position - s.position;
float d = length(toLight);
addLight(s, toLight / d, uPointLights[i].color * attenuate(d, uPointLights[i].attenuation), diffuse, specular);
}
上限がユニフォームのforループです。
GLSL 4.xでは問題無く、uPointLightCountは1回の描画の全てのピクセルで同じなので、全てのピクセルが同じ回数ループします。
GPUが一番得意な種類のループです。
ユニフォームの配列をループ変数で添字付けする事(uPointLights[i])は、デスクトップのGLSLではユニフォームの配列に対して許されています。
normalizeとlengthの代わりに、lengthを1回と割り算です。
GLSLシリーズの9.6.1節と同じで、どうせ距離が必要なので、此れなら平方根を1回しか計算しません。
提灯はどれ位の強さでしょうか?
提灯はkMediumRangeを使います:
提灯の色が1を超えているのは其の為です。
橙の提灯はで、2m離れてもが届き、床にはっきりした橙の光の溜まりが出来ます。
提灯のすぐ隣では光が1を超え、フレームバッファが白に切り詰めます。
第21章のトーンマッピング迄は其れで我慢します(GLSLシリーズの10.6節で其の問題を見ました)。
8mでは3%しか残らないので、提灯は其々置き場の自分の一角を照らします。
スポットライト
// スポットライト:点光源に円錐の係数を掛ける / spotlights: a point light times a cone factor
for (int i = 0; i < uSpotLightCount; ++i) {
vec3 toLight = uSpotLights[i].position - s.position;
float d = length(toLight);
vec3 l = toLight / d;
// 光から見たこのピクセルの向きと円錐の軸の角度(のコサイン) / cosine of the angle between the cone axis and this pixel
float cosAngle = dot(-l, uSpotLights[i].direction);
float cone = smoothstep(uSpotLights[i].cosOuter, uSpotLights[i].cosInner, cosAngle);
if (cone <= 0.0) continue;
addLight(s, l, uSpotLights[i].color * attenuate(d, uSpotLights[i].attenuation) * cone, diffuse, specular);
}
最初の3行は点光源と全く同じです。
次に円錐です。
-lはスポットから此のピクセルへの向き、つまり光が此処に来る迄に進む向きで、directionはスポットが向いている先です。
どちらも単位ベクトルなので、内積はです。
smoothstep(cosOuter, cosInner, cosAngle)は外側の円錐の外で0、内側の円錐の中で1、其の間は滑らかなS字カーブです。
continueはCと同じく次の光へ飛びます。
殆どのピクセルは殆どの円錐の外にあるので、Blinn-Phongの計算を飛ばせます。
懐中電灯のデフォルトの角度、12.5°と17.5°での計算例:
2つの円錐の丁度中間で光は約半分の強さになり、5°の間に全部から0迄弱まります。
縁が硬いと、鋭くギザギザの円になります(課題4で見られます)。
全部を合わせる
vec3 ambient = uAmbient * s.diffuse;
vec3 color = ambient + diffuse + specular + emission;
if (uViewMode == 1) color = ambient;
else if (uViewMode == 2) color = diffuse;
else if (uViewMode == 3) color = specular;
else if (uViewMode == 4) color = emission;
else if (uViewMode == 5) color = s.normal * 0.5 + 0.5;
out_color = vec4(color, 1.0);
}
第11章と同じ合計で、diffuseとspecularには全ての光源の光が入っています。
発光は相変わらずどの光にも依存しません。
全ての光を消しても、木箱の光る隙間は同じに見えます。
12.7 夜のシーン
光のデータ
main.ccの上の方、木箱とマテリアルの表の隣に:
// 点光源(提灯)の中心と色 / centres and colours of the point lights (lanterns)
struct LanternInfo {
Vec3 centre;
Vec3 color;
};
static const LanternInfo kLanterns[] = {
{{2.6f, 1.2f, 0.2f}, {2.4f, 1.0f, 0.35f}}, // 橙 / orange
{{-1.8f, 1.0f, 0.8f}, {0.4f, 2.0f, 0.7f}}, // 緑 / green
{{4.5f, 1.6f, -4.5f}, {0.6f, 0.9f, 2.6f}}, // 青 / blue
{{-5.5f, 1.4f, -3.5f}, {2.2f, 0.5f, 1.8f}}, // 紫 / purple
};
// 箱の山を上から照らすスポットライト / the spotlight shining down on the pile of crates
constexpr Vec3 kStageSpotPos = {2.0f, 6.0f, 1.5f};
constexpr Vec3 kStageSpotTarget = {0.3f, 0.5f, -0.2f};
提灯が4つで、其々回る中心と色を持ちます。
そして6mの高さに固定したスポットライトが、木箱の山の上の或る点を狙います。
キーの状態は、第11章の3つのマップの切り替えに代わります:
bool directionalOn = true, pointsOn = true, spotsOn = true, flashlightOn = true;
float lightTime = 0.0f; // 点光源の動きの時間(止められる) / time for the point lights' motion (can be paused)
if (key == GLFW_KEY_P) lightMoving = !lightMoving;
if (key == GLFW_KEY_1) directionalOn = !directionalOn;
if (key == GLFW_KEY_2) pointsOn = !pointsOn;
if (key == GLFW_KEY_3) spotsOn = !spotsOn;
if (key == GLFW_KEY_F) flashlightOn = !flashlightOn;
if (key >= GLFW_KEY_1 && key <= GLFW_KEY_3)
printf("directional %s, points %s, spots %s\n", directionalOn ? "on" : "off", pointsOn ? "on" : "off",
spotsOn ? "on" : "off");
GLFW_KEY_1〜GLFW_KEY_3は連続した数(数字のASCIIコード)なので、範囲のチェックが使えます。
木箱のマテリアルは常に両方のマップを持つ様になったので、第11章のコピーして書き換えるコードは無くなりました:
Material crateMaterial;
crateMaterial.diffuseMap = &*crate;
crateMaterial.specular = {1.0f, 1.0f, 1.0f};
crateMaterial.shininess = 48.0f;
crateMaterial.specularMap = &*crateSpecular;
crateMaterial.emissionMap = &*crateEmission;
crateMaterial.emission = {1.0f, 1.0f, 1.0f};
毎フレームLightSetを組み立てる
カメラが動いた後、フレームはカメラが何処にあって何処を見ているかを計算し、其れから光を組み立てます:
Mat4 view = useOrbit ? orbit.view() : fps.view();
Mat4 proj = useOrbit ? orbit.projection(window.aspect()) : fps.projection(window.aspect());
Vec3 viewPos = useOrbit ? orbit.position() : fps.position;
Vec3 viewDir = useOrbit ? normalize(orbit.target - orbit.position()) : fps.front();
// 夜の場面:弱い環境光と青白い月 / a night scene: weak ambient light and a pale blue moon
if (lightMoving) lightTime += dt;
LightSet lights;
lights.ambient = {0.03f, 0.035f, 0.05f};
if (directionalOn) lights.directional = {.direction = {-0.4f, -1.0f, -0.6f}, .color = {0.22f, 0.27f, 0.4f}};
viewDirは新しい物です。
FPSカメラは自分のfront()を知っていて、オービットカメラの視線の向きは「注視点 − 目」を正規化した物です。
夜はとても弱い、少し青い環境光で始まり(第11章は0.15でした)、そして月です。
暗く、青く、光は下へ、−Xと−Zの方へ進みます。
従って月は+X、+Z側の高い所、つまり開始位置の右後ろにあり、木箱のカメラの方を向いた面を照らします。
1キーで消した時は、lights.directionalはデフォルトの黒い色のままです。
// 色の違う点光源四つ。それぞれ自分の中心の周りをゆっくり回る
// Four coloured point lights, each slowly circling its own centre
if (pointsOn) {
for (int i = 0; i < 4; ++i) {
float a = lightTime * (0.5f + 0.15f * static_cast<float>(i)) + static_cast<float>(i) * 1.7f;
lights.points.push_back({.position = kLanterns[i].centre + Vec3{1.2f * std::cos(a), 0.3f * std::sin(2.0f * a),
1.2f * std::sin(a)},
.color = kLanterns[i].color,
.attenuation = kMediumRange});
}
}
各提灯は半径1.2mで自分の中心の周りを回り、1周に2回、0.3m上下します。
速さ(毎秒0.5、0.65、0.8、0.95ラジアン)と開始の角度()が違うので、揃って動く事はありません。
// スポットライト:カメラの懐中電灯と、箱の山を上から照らすライト
// Spotlights: the camera's flashlight and a light shining down on the pile of crates
if (spotsOn) {
if (flashlightOn)
lights.spots.push_back({.position = viewPos, .direction = viewDir, .color = {1.0f, 0.95f, 0.85f}});
lights.spots.push_back({.position = kStageSpotPos,
.direction = kStageSpotTarget - kStageSpotPos,
.color = {2.0f, 1.9f, 1.6f},
.innerAngle = radians(16.0f),
.outerAngle = radians(24.0f)});
}
懐中電灯は、目の位置にあって見ている方を向いた、デフォルトの角度と範囲のスポットライトです。
一人称の懐中電灯は其れだけの物です。
光が目から来るのでは視線ベクトルと等しく、ハーフベクトルも両方と等しくなり、ハイライトは照らされた物の丁度真ん中に来ます。
本物の懐中電灯も其の様になります。
舞台のスポットは「目標 − 位置」の書き方を示しています。
向きを手で計算せず、スポットが何処にあって何を見ているかを書きます。
applyが其れを正規化します:
光は約6m進んで木箱に届き、其処でkLongRangeがを残すので、色は約として届きます。
明るいですが、切り詰められはしません。
半角が16°と24°なので、6m先の光の溜まりの半径は大体m(全部の光)からm(光無し)で、山全体に十分です。
描画
phong->use();
phong->set("uView", view);
phong->set("uProj", proj);
phong->set("uViewPos", viewPos);
phong->set("uViewMode", viewMode);
lights.apply(*phong);
1行が第11章の3つの光のユニフォームに代わります。
光はフレームの全ての物で同じなので、床、木箱、球を描く前に1回だけ設定します。
drawLitは前と同じく、モデル行列、法線行列、マテリアルだけを設定します。
光源の目印は、提灯毎に其の色の小さなライティング無しの球と、舞台のスポットの小さな立方体になります:
// 光源の目印:点光源は小さな球、スポットライトは小さな箱(懐中電灯は自分の目の位置なので描かない)
// Light markers: small spheres for point lights, small cubes for spotlights (not the flashlight: it is at our eye)
unlit->use();
unlit->set("uView", view);
unlit->set("uProj", proj);
for (const PointLight &p : lights.points) {
unlit->set("uModel", translate(p.position) * scale({0.15f, 0.15f, 0.15f}));
unlit->set("uColor", p.color);
sphere.draw();
}
if (spotsOn) {
unlit->set("uModel", translate(kStageSpotPos) * scale({0.2f, 0.2f, 0.2f}));
unlit->set("uColor", Vec3{1.0f, 1.0f, 0.9f});
cube.draw();
}
目印はシェーダーが受け取ったのと同じデータ、lights.pointsをループするので、目印が光と違う所にある事は有り得ません。
2.4の様な色はフレームバッファで1に切り詰められるので、目印は光る点の様に見えます。
最後に、クリアの色を暗い夜の青、glClearColor(0.02f, 0.03f, 0.06f, 1.0f)にします。
結果
1、2、3キーで光源を1つずつ見てみます:
月だけで形が分かり、提灯が色と奥行きを与え、スポットが目を木箱に引き付けます。
合わせると、各ピクセルは単に3つの合計です。
Vキーで其の合計を項毎に見られます。
鏡面反射の表示では、木箱の鋼の縁が全ての提灯からのハイライトを同時に受けているのが分かります。
他の光が全部点いていても、懐中電灯は意外な程違いを生みます:
12.8 本物のエンジンではどうしているか
- 光の数に上限のあるフォワードレンダリング。 あたし達が作ったのは「フォワードレンダリング」です。全ての物を1回描き、其のシェーダーが光をループします。2000年代の多くのゲームは正に此れをやっていて、物毎に4〜8個の光の上限があり、レベルの全ての光を送る代わりに、CPU上で物毎に大事な光(一番近い物、一番明るい物)を選んでいました。
- 光のカリング。 減衰が決して0にならない光は、世界の全てのピクセルに影響します。エンジンは各光に範囲を与え、其の外では飛ばします。物毎、又は画面のタイルと奥行きの区切り毎に(「タイルド」と「クラスタード」のフォワードシェーディング。Doom(2016)や多くの現在のエンジンが使っています)、光の一覧はCPU又はコンピュートシェーダーで作ります。範囲は光が其処で本当に0になる時にしか使えません。物理ベースのエンジンが、丁度範囲で終わる窓を付けた逆二乗の減衰を使うのは其の為です(課題7)。glTFの
KHR_lights_punctualも光を其の様に記述します。第24章で又取り上げます。 - ディファードシェーディング。 「沢山の光」へのもう1つの答えです。全ての物を1回、幾つかのテクスチャ(法線、アルベド、鏡面反射…)に描き、其れから画面を照らします。各光は自分の範囲の中のピクセルにだけ触れます。中心となる部品は第17章(フレームバッファ)で手に入ります。
- ユニフォームバッファ。 本物のエンジンで、シェーダーとフレーム毎に50個のユニフォームを名前で設定する人は居ません。光のデータはフレーム毎に1回ユニフォームバッファ又はシェーダーストレージバッファに入れ、全てのシェーダーが其れを読みます。第19章です。
- 影。 あたし達の光は全てを突き抜けます。舞台のスポットは木箱の下の床も照らしています。シャドウマッピング(第23章)は光毎に1つの係数を足し、其れは正に減衰と円錐と同じ場所、
addLightに渡す光の色に入ります。 - 焼き込んだ光。 決して動かない光は、よくライトマップやライトプローブに前もって計算(「ベイク」)され、シェーダーは懐中電灯の様な少数の動的な光だけを扱います。
12.9 まとめ
- 3つの光源:平行光源(向きだけ、弱まらない)、点光源(位置と減衰)、スポットライト(点光源にを掛ける)。
- 光の
directionは常に光が進む向きです。シェーダーには光へ向かう向きが必要なので、平行光源はを使い、スポットの円錐はとを比べます。符号を間違えると物の裏側が照らされます。 - GLSLのユニフォームは構造体にも構造体の配列にも出来ます。配列には決まった最大の大きさがあり、カウントのユニフォームがループに使っている要素の数を教えます。C++とシェーダーの最大数は一致しなければなりません。
- 各要素の各メンバーは
uPointLights[2].colorの様な名前の別々のユニフォームです。名前はstd::formatで作ります(GCC 13以降。Debian 12ではsnprintf)。 LightSetは単純な光の構造体を持ち、毎フレーム作り直します。applyはCPU上で1回だけ向きを正規化し、スポットの角度をコサインに変えます。- フラグメントシェーダーは
Surfaceを1回埋め、光毎にaddLight(1つの光のBlinn-Phong、inoutの合計)を呼びます。光は足し算です。 - 懐中電灯は、カメラの位置にあって視線の方向を向いたスポットライトです。
12.10 課題
- ★
kLongRangeでとでの減衰、そしてでの懐中電灯(12.5°と17.5°)の円錐の係数を計算して下さい。、、約0.826になるはずです。 - ★
kLanternsに提灯を2つ足し(例えば赤と白)、ループをi < static_cast<int>(std::size(kLanterns))に変えて下さい。シェーダーには8個分の場所があるので、シェーダーに触れずに目印と色の付いた光の溜まりが6つずつ見えるはずです。 - ★ 懐中電灯を細い光(
.innerAngle = radians(6.0f), .outerAngle = radians(9.0f))にし、次に広く柔らかい光(25°と35°)にして下さい。1つ目は小さく明るい円、2つ目は長く緩やかな縁の大きな光の溜まりになるはずです。 - ★ 外側の角度はデフォルトの17.5°のまま
.innerAngle = radians(17.4f)にして、懐中電灯の縁を硬くして下さい。床に縁がギザギザの鋭い円が見えるはずで、其れがスポットに2つの円錐がある理由です。(2つを等しくしてはいけません。縁が等しいsmoothstepは未定義です。) - ★★ Nキーで昼のモードを付けて下さい。昼は平行光源が色の太陽、環境光が、クリアの色が空の青で、夜は今の通りです。Nを押すと雰囲気が一瞬で変わるはずです。昼でも提灯の光の溜まりはありますが、太陽の隣では殆どの迫力が無くなります。
- ★★ 点光源を12個入れて下さい(例えば4つの提灯を、開始の角度を変えて3回)。stderrには毎フレーム「too many point lights: 12 (max 8)」と出て、シーンを照らすのは8個だけのはずです。次に
kMaxPointLightsとMAX_POINT_LIGHTSを一緒に16にして下さい。12個全部が動き、メッセージが止まるはずです。最後に片方だけを変えて、両方の場合に何が見えるかを説明して下さい。 - ★★★ 多項式を、丁度範囲で終わる物理ベースの減衰に置き換えて下さい。
PointLightにfloat rangeを足し(C++とGLSLの両方。applyで設定)、pow(clamp(1.0 - pow(d / range, 4.0), 0.0, 1.0), 2.0) / (d * d + 1.0)を使います。範囲を4mにすると、各提灯の光の溜まりは周り4mのきれいな円で終わり、其れより遠いピクセルは正確に0を受け取るので、シェーダーは其処で其の光を飛ばせます。1、2、3mでの弱まり方をkMediumRangeと比べて下さい。
ファイル: a/CMakeLists.txt | b/CMakeLists.txt
| 前 | 新 | ||
|---|---|---|---|
| @@ -36,7 +36,8 @@ add_executable(game | |||
| 36 | src/texture.cc | 36 | src/texture.cc |
| 37 | src/shapes.cc | 37 | src/shapes.cc |
| 38 | src/camera.cc | 38 | src/camera.cc |
| 39 | src/material.cc) | 39 | src/material.cc |
| 40 | src/lights.cc) | ||
| 40 | target_include_directories(game PRIVATE src external/stb external/linalg) | 41 | target_include_directories(game PRIVATE src external/stb external/linalg) |
| 41 | target_link_libraries(game PRIVATE glad stb_image glfw) | 42 | target_link_libraries(game PRIVATE glad stb_image glfw) |
| 42 | 43 | ||
ファイル: a/shaders/phong.frag | b/shaders/phong.frag
| 前 | 新 | ||
|---|---|---|---|
| @@ -12,16 +12,45 @@ struct Material { | |||
| 12 | }; | 12 | }; |
| 13 | uniform Material uMaterial; | 13 | uniform Material uMaterial; |
| 14 | 14 | ||
| 15 | // サンプラーは構造体に入れずにbindingを指定する(構造体のメンバーにはlayoutを付けられない) | ||
| 16 | // The samplers stay outside the struct so they can have a binding (struct members cannot have a layout) | ||
| 17 | layout(binding = 0) uniform sampler2D uDiffuseMap; | 15 | layout(binding = 0) uniform sampler2D uDiffuseMap; |
| 18 | layout(binding = 1) uniform sampler2D uSpecularMap; | 16 | layout(binding = 1) uniform sampler2D uSpecularMap; |
| 19 | layout(binding = 2) uniform sampler2D uEmissionMap; | 17 | layout(binding = 2) uniform sampler2D uEmissionMap; |
| 20 | 18 | ||
| 21 | uniform vec3 uLightPos; // 光の位置(ワールド座標) / light position (world space) | 19 | // 平行光源:向きだけ / directional light: a direction only |
| 22 | uniform vec3 uLightColor; // 光の色と明るさ / light colour and brightness | 20 | struct DirectionalLight { |
| 23 | uniform vec3 uAmbient; // 環境光の色と明るさ / ambient light colour and brightness | 21 | vec3 direction; // 光が進む向き(単位ベクトル) / the direction the light travels (unit vector) |
| 24 | uniform vec3 uViewPos; // カメラの位置(ワールド座標) / camera position (world space) | 22 | vec3 color; // 0 = オフ / 0 = off |
| 23 | }; | ||
| 24 | |||
| 25 | // 点光源:位置と減衰 / point light: a position and attenuation | ||
| 26 | struct PointLight { | ||
| 27 | vec3 position; | ||
| 28 | vec3 color; | ||
| 29 | vec3 attenuation; // 定数項・一次・二次 / constant, linear, quadratic | ||
| 30 | }; | ||
| 31 | |||
| 32 | // スポットライト:点光源+円錐 / spotlight: a point light + a cone | ||
| 33 | struct SpotLight { | ||
| 34 | vec3 position; | ||
| 35 | vec3 direction; // 円錐の軸(単位ベクトル) / the cone's axis (unit vector) | ||
| 36 | vec3 color; | ||
| 37 | float cosInner; // 内側の円錐の半角のコサイン / cosine of the inner cone's half angle | ||
| 38 | float cosOuter; // 外側の円錐の半角のコサイン / cosine of the outer cone's half angle | ||
| 39 | vec3 attenuation; | ||
| 40 | }; | ||
| 41 | |||
| 42 | // C++側の kMaxPointLights、kMaxSpotLights と同じ / same as kMaxPointLights and kMaxSpotLights in C++ | ||
| 43 | #define MAX_POINT_LIGHTS 8 | ||
| 44 | #define MAX_SPOT_LIGHTS 4 | ||
| 45 | |||
| 46 | uniform DirectionalLight uDirLight; | ||
| 47 | uniform PointLight uPointLights[MAX_POINT_LIGHTS]; | ||
| 48 | uniform int uPointLightCount; // 使っている数 / how many are in use | ||
| 49 | uniform SpotLight uSpotLights[MAX_SPOT_LIGHTS]; | ||
| 50 | uniform int uSpotLightCount; | ||
| 51 | |||
| 52 | uniform vec3 uAmbient; // 環境光の色と明るさ / ambient light colour and brightness | ||
| 53 | uniform vec3 uViewPos; // カメラの位置(ワールド座標) / camera position (world space) | ||
| 25 | 54 | ||
| 26 | // 0 = 全部、1 = 環境光、2 = 拡散反射、3 = 鏡面反射、4 = 発光、5 = 法線 | 55 | // 0 = 全部、1 = 環境光、2 = 拡散反射、3 = 鏡面反射、4 = 発光、5 = 法線 |
| 27 | // 0 = everything, 1 = ambient, 2 = diffuse, 3 = specular, 4 = emission, 5 = normals | 56 | // 0 = everything, 1 = ambient, 2 = diffuse, 3 = specular, 4 = emission, 5 = normals |
| @@ -29,32 +58,72 @@ uniform int uViewMode; | |||
| 29 | 58 | ||
| 30 | layout(location = 0) out vec4 out_color; | 59 | layout(location = 0) out vec4 out_color; |
| 31 | 60 | ||
| 61 | // このピクセルの表面:どの光の計算にも同じものを使う / this pixel's surface: the same for every light | ||
| 62 | struct Surface { | ||
| 63 | vec3 position; // ワールド座標 / world space | ||
| 64 | vec3 normal; // 単位ベクトル / unit vector | ||
| 65 | vec3 view; // 目へ向かう単位ベクトル / unit vector towards the eye | ||
| 66 | vec3 diffuse; // マップを掛けた拡散反射の色 / diffuse colour with the map applied | ||
| 67 | vec3 specular; // マップを掛けた鏡面反射の色 / specular colour with the map applied | ||
| 68 | float shininess; | ||
| 69 | }; | ||
| 70 | |||
| 71 | // 一つの光の拡散反射と鏡面反射(Blinn-Phong)を足す。l = 光へ向かう単位ベクトル | ||
| 72 | // Adds one light's diffuse and specular (Blinn-Phong) light. l = unit vector towards the light | ||
| 73 | void addLight(Surface s, vec3 l, vec3 lightColor, inout vec3 diffuse, inout vec3 specular) { | ||
| 74 | float diff = max(dot(s.normal, l), 0.0); | ||
| 75 | if (diff <= 0.0) return; // 裏から照らされている / lit from behind | ||
| 76 | vec3 h = normalize(l + s.view); | ||
| 77 | diffuse += diff * s.diffuse * lightColor; | ||
| 78 | specular += pow(max(dot(s.normal, h), 0.0), s.shininess) * s.specular * lightColor; | ||
| 79 | } | ||
| 80 | |||
| 81 | // 距離dでの減衰(k = 定数項・一次・二次) / attenuation at distance d (k = constant, linear, quadratic) | ||
| 82 | float attenuate(float d, vec3 k) { | ||
| 83 | return 1.0 / (k.x + k.y * d + k.z * d * d); | ||
| 84 | } | ||
| 85 | |||
| 32 | void main() { | 86 | void main() { |
| 33 | // マップから、このピクセルのマテリアルを読む / read this pixel's material from the maps | 87 | Surface s; |
| 34 | vec3 diffuseColor = uMaterial.diffuse * texture(uDiffuseMap, vUv).rgb; | 88 | s.position = vWorldPos; |
| 35 | vec3 specularColor = uMaterial.specular * texture(uSpecularMap, vUv).rgb; | 89 | s.normal = normalize(vNormal); |
| 90 | s.view = normalize(uViewPos - vWorldPos); | ||
| 91 | s.diffuse = uMaterial.diffuse * texture(uDiffuseMap, vUv).rgb; | ||
| 92 | s.specular = uMaterial.specular * texture(uSpecularMap, vUv).rgb; | ||
| 93 | s.shininess = uMaterial.shininess; | ||
| 36 | vec3 emission = uMaterial.emission * texture(uEmissionMap, vUv).rgb; | 94 | vec3 emission = uMaterial.emission * texture(uEmissionMap, vUv).rgb; |
| 37 | 95 | ||
| 38 | vec3 n = normalize(vNormal); | 96 | vec3 diffuse = vec3(0.0); |
| 39 | vec3 l = normalize(uLightPos - vWorldPos); | 97 | vec3 specular = vec3(0.0); |
| 40 | vec3 v = normalize(uViewPos - vWorldPos); | 98 | |
| 41 | 99 | // 平行光源:光へ向かう向きは進む向きの逆 / directional: towards the light = the opposite of its direction | |
| 42 | vec3 ambient = uAmbient * diffuseColor; | 100 | addLight(s, -uDirLight.direction, uDirLight.color, diffuse, specular); |
| 43 | float diff = max(dot(n, l), 0.0); | 101 | |
| 44 | vec3 diffuse = diff * diffuseColor * uLightColor; | 102 | // 点光源 / point lights |
| 45 | float spec = 0.0; | 103 | for (int i = 0; i < uPointLightCount; ++i) { |
| 46 | if (diff > 0.0) { | 104 | vec3 toLight = uPointLights[i].position - s.position; |
| 47 | vec3 h = normalize(l + v); | 105 | float d = length(toLight); |
| 48 | spec = pow(max(dot(n, h), 0.0), uMaterial.shininess); | 106 | addLight(s, toLight / d, uPointLights[i].color * attenuate(d, uPointLights[i].attenuation), diffuse, specular); |
| 107 | } | ||
| 108 | |||
| 109 | // スポットライト:点光源に円錐の係数を掛ける / spotlights: a point light times a cone factor | ||
| 110 | for (int i = 0; i < uSpotLightCount; ++i) { | ||
| 111 | vec3 toLight = uSpotLights[i].position - s.position; | ||
| 112 | float d = length(toLight); | ||
| 113 | vec3 l = toLight / d; | ||
| 114 | // 光から見たこのピクセルの向きと円錐の軸の角度(のコサイン) / cosine of the angle between the cone axis and this pixel | ||
| 115 | float cosAngle = dot(-l, uSpotLights[i].direction); | ||
| 116 | float cone = smoothstep(uSpotLights[i].cosOuter, uSpotLights[i].cosInner, cosAngle); | ||
| 117 | if (cone <= 0.0) continue; | ||
| 118 | addLight(s, l, uSpotLights[i].color * attenuate(d, uSpotLights[i].attenuation) * cone, diffuse, specular); | ||
| 49 | } | 119 | } |
| 50 | vec3 specular = spec * specularColor * uLightColor; | ||
| 51 | 120 | ||
| 52 | // 発光はライティングと関係なく足すだけ / emission does not depend on the lighting: just add it | 121 | vec3 ambient = uAmbient * s.diffuse; |
| 53 | vec3 color = ambient + diffuse + specular + emission; | 122 | vec3 color = ambient + diffuse + specular + emission; |
| 54 | if (uViewMode == 1) color = ambient; | 123 | if (uViewMode == 1) color = ambient; |
| 55 | else if (uViewMode == 2) color = diffuse; | 124 | else if (uViewMode == 2) color = diffuse; |
| 56 | else if (uViewMode == 3) color = specular; | 125 | else if (uViewMode == 3) color = specular; |
| 57 | else if (uViewMode == 4) color = emission; | 126 | else if (uViewMode == 4) color = emission; |
| 58 | else if (uViewMode == 5) color = n * 0.5 + 0.5; | 127 | else if (uViewMode == 5) color = s.normal * 0.5 + 0.5; |
| 59 | out_color = vec4(color, 1.0); | 128 | out_color = vec4(color, 1.0); |
| 60 | } | 129 | } |
ファイル: /dev/null | b/src/lights.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,43 @@ | |||
| 1 | #include "lights.hh" | ||
| 2 | |||
| 3 | #include <cmath> | ||
| 4 | #include <cstdio> | ||
| 5 | #include <format> | ||
| 6 | |||
| 7 | void LightSet::apply(const Shader &shader) const { | ||
| 8 | shader.set("uAmbient", ambient); | ||
| 9 | shader.set("uDirLight.direction", normalize(directional.direction)); | ||
| 10 | shader.set("uDirLight.color", directional.color); | ||
| 11 | |||
| 12 | // 配列の要素のメンバーは「名前[番号].メンバー」で設定する / array elements: "name[index].member" | ||
| 13 | int pointCount = static_cast<int>(points.size()); | ||
| 14 | if (pointCount > kMaxPointLights) { | ||
| 15 | fprintf(stderr, "点光源が多すぎる / too many point lights: %d (max %d)\n", pointCount, kMaxPointLights); | ||
| 16 | pointCount = kMaxPointLights; | ||
| 17 | } | ||
| 18 | for (int i = 0; i < pointCount; ++i) { | ||
| 19 | const PointLight &p = points[static_cast<size_t>(i)]; | ||
| 20 | shader.set(std::format("uPointLights[{}].position", i).c_str(), p.position); | ||
| 21 | shader.set(std::format("uPointLights[{}].color", i).c_str(), p.color); | ||
| 22 | shader.set(std::format("uPointLights[{}].attenuation", i).c_str(), p.attenuation); | ||
| 23 | } | ||
| 24 | shader.set("uPointLightCount", pointCount); | ||
| 25 | |||
| 26 | int spotCount = static_cast<int>(spots.size()); | ||
| 27 | if (spotCount > kMaxSpotLights) { | ||
| 28 | fprintf(stderr, "スポットライトが多すぎる / too many spotlights: %d (max %d)\n", spotCount, kMaxSpotLights); | ||
| 29 | spotCount = kMaxSpotLights; | ||
| 30 | } | ||
| 31 | for (int i = 0; i < spotCount; ++i) { | ||
| 32 | const SpotLight &s = spots[static_cast<size_t>(i)]; | ||
| 33 | shader.set(std::format("uSpotLights[{}].position", i).c_str(), s.position); | ||
| 34 | shader.set(std::format("uSpotLights[{}].direction", i).c_str(), normalize(s.direction)); | ||
| 35 | shader.set(std::format("uSpotLights[{}].color", i).c_str(), s.color); | ||
| 36 | // シェーダーは角度ではなくコサインを比べる(acosを毎ピクセル計算しないため) | ||
| 37 | // The shader compares cosines, not angles (so it does not need acos for every pixel) | ||
| 38 | shader.set(std::format("uSpotLights[{}].cosInner", i).c_str(), std::cos(s.innerAngle)); | ||
| 39 | shader.set(std::format("uSpotLights[{}].cosOuter", i).c_str(), std::cos(s.outerAngle)); | ||
| 40 | shader.set(std::format("uSpotLights[{}].attenuation", i).c_str(), s.attenuation); | ||
| 41 | } | ||
| 42 | shader.set("uSpotLightCount", spotCount); | ||
| 43 | } | ||
ファイル: /dev/null | b/src/lights.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,55 @@ | |||
| 1 | // 光源:平行光源・点光源・スポットライト / light casters: directional, point and spot lights | ||
| 2 | #pragma once | ||
| 3 | |||
| 4 | #include "mathx.hh" | ||
| 5 | #include "shader.hh" | ||
| 6 | |||
| 7 | #include <vector> | ||
| 8 | |||
| 9 | // 減衰の定数(定数項・一次・二次)。GLSLシリーズ第9章の表から | ||
| 10 | // Attenuation constants (constant, linear, quadratic), from the table in GLSL series chapter 9 | ||
| 11 | constexpr Vec3 kShortRange = {1.0f, 0.7f, 1.8f}; // 近くだけ照らす / lights only what is close | ||
| 12 | constexpr Vec3 kMediumRange = {1.0f, 0.35f, 0.44f}; // 中くらい / medium | ||
| 13 | constexpr Vec3 kLongRange = {1.0f, 0.09f, 0.032f}; // 遠くまで届く / reaches far | ||
| 14 | |||
| 15 | // シェーダーの MAX_POINT_LIGHTS、MAX_SPOT_LIGHTS と同じにすること | ||
| 16 | // Must match MAX_POINT_LIGHTS and MAX_SPOT_LIGHTS in the shader | ||
| 17 | constexpr int kMaxPointLights = 8; | ||
| 18 | constexpr int kMaxSpotLights = 4; | ||
| 19 | |||
| 20 | // 平行光源(太陽・月):位置がなく、どこでも同じ向きから来る | ||
| 21 | // Directional light (sun, moon): no position, comes from the same direction everywhere | ||
| 22 | struct DirectionalLight { | ||
| 23 | Vec3 direction = {0.0f, -1.0f, 0.0f}; // 光が進む向き(光源へ向かう向きの逆) / the direction the light travels | ||
| 24 | Vec3 color = {0.0f, 0.0f, 0.0f}; // 色と明るさ。0 = オフ / colour and brightness; 0 = off | ||
| 25 | }; | ||
| 26 | |||
| 27 | // 点光源(電球):一点から全方向へ、距離で弱くなる / point light (a bulb): all directions from one point, weaker with distance | ||
| 28 | struct PointLight { | ||
| 29 | Vec3 position; | ||
| 30 | Vec3 color = {1.0f, 1.0f, 1.0f}; | ||
| 31 | Vec3 attenuation = kMediumRange; | ||
| 32 | }; | ||
| 33 | |||
| 34 | // スポットライト(懐中電灯):円錐の中だけ。内側の円錐から外側の円錐まで滑らかに暗くなる | ||
| 35 | // Spotlight (a flashlight): only inside a cone; fades smoothly from the inner to the outer cone | ||
| 36 | struct SpotLight { | ||
| 37 | Vec3 position; | ||
| 38 | Vec3 direction = {0.0f, -1.0f, 0.0f}; | ||
| 39 | Vec3 color = {1.0f, 1.0f, 1.0f}; | ||
| 40 | float innerAngle = radians(12.5f); // ここまで全部の明るさ(円錐の半分の角度) / full brightness up to here (half angle) | ||
| 41 | float outerAngle = radians(17.5f); // ここから先は0 / zero from here on | ||
| 42 | Vec3 attenuation = kLongRange; | ||
| 43 | }; | ||
| 44 | |||
| 45 | // シーンの全部の光 / all the lights of a scene | ||
| 46 | struct LightSet { | ||
| 47 | Vec3 ambient = {0.05f, 0.05f, 0.05f}; | ||
| 48 | DirectionalLight directional; | ||
| 49 | std::vector<PointLight> points; | ||
| 50 | std::vector<SpotLight> spots; | ||
| 51 | |||
| 52 | // 全部の光をシェーダーのユニフォームに設定する。最大数を超えた分は使わない。 | ||
| 53 | // Sets all lights as shader uniforms. Lights beyond the maximum count are ignored. | ||
| 54 | void apply(const Shader &shader) const; | ||
| 55 | }; | ||
ファイル: a/src/main.cc | b/src/main.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -1,5 +1,5 @@ | |||
| 1 | // 第11章:マテリアルとライティングマップ | 1 | // 第12章:光源と複数のライト |
| 2 | // Chapter 11: materials and lighting maps | 2 | // Chapter 12: light casters and multiple lights |
| 3 | // | 3 | // |
| 4 | // 操作 / Controls: | 4 | // 操作 / Controls: |
| 5 | // WASD 前後左右に移動 / move forward, back, left, right | 5 | // WASD 前後左右に移動 / move forward, back, left, right |
| @@ -9,14 +9,16 @@ | |||
| 9 | // ホイール / wheel ズーム / zoom | 9 | // ホイール / wheel ズーム / zoom |
| 10 | // C FPS ⇔ オービットカメラ / FPS ⇔ orbit camera | 10 | // C FPS ⇔ オービットカメラ / FPS ⇔ orbit camera |
| 11 | // V 表示:全部 → 環境光 → 拡散 → 鏡面 → 発光 → 法線 / view: all → ambient → diffuse → specular → emission → normals | 11 | // V 表示:全部 → 環境光 → 拡散 → 鏡面 → 発光 → 法線 / view: all → ambient → diffuse → specular → emission → normals |
| 12 | // P 光を止める・動かす / pause / resume the light | 12 | // P 点光源を止める・動かす / pause / resume the point lights |
| 13 | // L 光を消す・点ける(発光だけが残る) / light off / on (only the emission remains) | 13 | // 1 平行光源(月)のオン・オフ / directional light (the moon) on / off |
| 14 | // M 箱の鏡面反射マップのオン・オフ / crate specular map on / off | 14 | // 2 点光源のオン・オフ / point lights on / off |
| 15 | // E 箱の発光のオン・オフ / crate emission on / off | 15 | // 3 スポットライトのオン・オフ / spotlights on / off |
| 16 | // F 懐中電灯のオン・オフ / flashlight on / off | ||
| 16 | // Tab カーソルのキャプチャ切り替え / toggle cursor capture | 17 | // Tab カーソルのキャプチャ切り替え / toggle cursor capture |
| 17 | // R シェーダーを読み直す / reload the shaders | 18 | // R シェーダーを読み直す / reload the shaders |
| 18 | // Esc 終了 / quit | 19 | // Esc 終了 / quit |
| 19 | #include "camera.hh" | 20 | #include "camera.hh" |
| 21 | #include "lights.hh" | ||
| 20 | #include "material.hh" | 22 | #include "material.hh" |
| 21 | #include "mathx.hh" | 23 | #include "mathx.hh" |
| 22 | #include "mesh.hh" | 24 | #include "mesh.hh" |
| @@ -75,11 +77,28 @@ static const NamedMaterial kMaterialSamples[] = { | |||
| 75 | .shininess = 32.0f}}, | 77 | .shininess = 32.0f}}, |
| 76 | }; | 78 | }; |
| 77 | 79 | ||
| 80 | // 点光源(提灯)の中心と色 / centres and colours of the point lights (lanterns) | ||
| 81 | struct LanternInfo { | ||
| 82 | Vec3 centre; | ||
| 83 | Vec3 color; | ||
| 84 | }; | ||
| 85 | |||
| 86 | static const LanternInfo kLanterns[] = { | ||
| 87 | {{2.6f, 1.2f, 0.2f}, {2.4f, 1.0f, 0.35f}}, // 橙 / orange | ||
| 88 | {{-1.8f, 1.0f, 0.8f}, {0.4f, 2.0f, 0.7f}}, // 緑 / green | ||
| 89 | {{4.5f, 1.6f, -4.5f}, {0.6f, 0.9f, 2.6f}}, // 青 / blue | ||
| 90 | {{-5.5f, 1.4f, -3.5f}, {2.2f, 0.5f, 1.8f}}, // 紫 / purple | ||
| 91 | }; | ||
| 92 | |||
| 93 | // 箱の山を上から照らすスポットライト / the spotlight shining down on the pile of crates | ||
| 94 | constexpr Vec3 kStageSpotPos = {2.0f, 6.0f, 1.5f}; | ||
| 95 | constexpr Vec3 kStageSpotTarget = {0.3f, 0.5f, -0.2f}; | ||
| 96 | |||
| 78 | static const char *const kViewModeNames[] = {"all", "ambient", "diffuse", "specular", "emission", "normals"}; | 97 | static const char *const kViewModeNames[] = {"all", "ambient", "diffuse", "specular", "emission", "normals"}; |
| 79 | 98 | ||
| 80 | int main() { | 99 | int main() { |
| 81 | Window window; | 100 | Window window; |
| 82 | if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 11")) return 1; | 101 | if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 12")) return 1; |
| 83 | 102 | ||
| 84 | std::optional<Shader> phong = Shader::load("shaders/phong.vert", "shaders/phong.frag"); | 103 | std::optional<Shader> phong = Shader::load("shaders/phong.vert", "shaders/phong.frag"); |
| 85 | std::optional<Shader> unlit = Shader::load("shaders/unlit.vert", "shaders/unlit.frag"); | 104 | std::optional<Shader> unlit = Shader::load("shaders/unlit.vert", "shaders/unlit.frag"); |
| @@ -107,10 +126,8 @@ int main() { | |||
| 107 | bool useOrbit = false; | 126 | bool useOrbit = false; |
| 108 | int viewMode = 0; | 127 | int viewMode = 0; |
| 109 | bool lightMoving = true; | 128 | bool lightMoving = true; |
| 110 | bool lightOn = true; | 129 | bool directionalOn = true, pointsOn = true, spotsOn = true, flashlightOn = true; |
| 111 | bool useSpecularMap = true; | 130 | float lightTime = 0.0f; // 点光源の動きの時間(止められる) / time for the point lights' motion (can be paused) |
| 112 | bool useEmission = true; | ||
| 113 | float lightTime = 0.0f; // 光の動きの時間(止められる) / time for the light's motion (can be paused) | ||
| 114 | window.setCursorCaptured(true); | 131 | window.setCursorCaptured(true); |
| 115 | 132 | ||
| 116 | window.onKey = [&](int key, int action, int /*mods*/) { | 133 | window.onKey = [&](int key, int action, int /*mods*/) { |
| @@ -132,12 +149,13 @@ int main() { | |||
| 132 | printf("view: %s\n", kViewModeNames[viewMode]); | 149 | printf("view: %s\n", kViewModeNames[viewMode]); |
| 133 | } | 150 | } |
| 134 | if (key == GLFW_KEY_P) lightMoving = !lightMoving; | 151 | if (key == GLFW_KEY_P) lightMoving = !lightMoving; |
| 135 | if (key == GLFW_KEY_L) lightOn = !lightOn; | 152 | if (key == GLFW_KEY_1) directionalOn = !directionalOn; |
| 136 | if (key == GLFW_KEY_M) { | 153 | if (key == GLFW_KEY_2) pointsOn = !pointsOn; |
| 137 | useSpecularMap = !useSpecularMap; | 154 | if (key == GLFW_KEY_3) spotsOn = !spotsOn; |
| 138 | printf("specular map: %s\n", useSpecularMap ? "on" : "off"); | 155 | if (key == GLFW_KEY_F) flashlightOn = !flashlightOn; |
| 139 | } | 156 | if (key >= GLFW_KEY_1 && key <= GLFW_KEY_3) |
| 140 | if (key == GLFW_KEY_E) useEmission = !useEmission; | 157 | printf("directional %s, points %s, spots %s\n", directionalOn ? "on" : "off", pointsOn ? "on" : "off", |
| 158 | spotsOn ? "on" : "off"); | ||
| 141 | }; | 159 | }; |
| 142 | 160 | ||
| 143 | printf("material spheres (left to right):"); | 161 | printf("material spheres (left to right):"); |
| @@ -160,7 +178,9 @@ int main() { | |||
| 160 | crateMaterial.diffuseMap = &*crate; | 178 | crateMaterial.diffuseMap = &*crate; |
| 161 | crateMaterial.specular = {1.0f, 1.0f, 1.0f}; | 179 | crateMaterial.specular = {1.0f, 1.0f, 1.0f}; |
| 162 | crateMaterial.shininess = 48.0f; | 180 | crateMaterial.shininess = 48.0f; |
| 181 | crateMaterial.specularMap = &*crateSpecular; | ||
| 163 | crateMaterial.emissionMap = &*crateEmission; | 182 | crateMaterial.emissionMap = &*crateEmission; |
| 183 | crateMaterial.emission = {1.0f, 1.0f, 1.0f}; | ||
| 164 | 184 | ||
| 165 | double lastTime = window.time(); | 185 | double lastTime = window.time(); |
| 166 | while (!window.shouldClose()) { | 186 | while (!window.shouldClose()) { |
| @@ -187,18 +207,42 @@ int main() { | |||
| 187 | fps.move(dir, dt); | 207 | fps.move(dir, dt); |
| 188 | } | 208 | } |
| 189 | 209 | ||
| 190 | // 光は箱の山の周りを回り、少し上下する / the light circles the pile of crates, bobbing up and down a little | ||
| 191 | if (lightMoving) lightTime += dt; | ||
| 192 | Vec3 lightPos = {3.5f * std::sin(0.7f * lightTime), 2.6f + 0.6f * std::sin(1.3f * lightTime), | ||
| 193 | 3.5f * std::cos(0.7f * lightTime)}; | ||
| 194 | Vec3 lightColor = lightOn ? Vec3{1.0f, 1.0f, 1.0f} : Vec3{0.0f, 0.0f, 0.0f}; | ||
| 195 | Vec3 ambient = lightOn ? Vec3{0.15f, 0.15f, 0.15f} : Vec3{0.02f, 0.02f, 0.03f}; | ||
| 196 | |||
| 197 | Mat4 view = useOrbit ? orbit.view() : fps.view(); | 210 | Mat4 view = useOrbit ? orbit.view() : fps.view(); |
| 198 | Mat4 proj = useOrbit ? orbit.projection(window.aspect()) : fps.projection(window.aspect()); | 211 | Mat4 proj = useOrbit ? orbit.projection(window.aspect()) : fps.projection(window.aspect()); |
| 199 | Vec3 viewPos = useOrbit ? orbit.position() : fps.position; | 212 | Vec3 viewPos = useOrbit ? orbit.position() : fps.position; |
| 213 | Vec3 viewDir = useOrbit ? normalize(orbit.target - orbit.position()) : fps.front(); | ||
| 200 | 214 | ||
| 201 | glClearColor(0.10f, 0.15f, 0.25f, 1.0f); | 215 | // 夜の場面:弱い環境光と青白い月 / a night scene: weak ambient light and a pale blue moon |
| 216 | if (lightMoving) lightTime += dt; | ||
| 217 | LightSet lights; | ||
| 218 | lights.ambient = {0.03f, 0.035f, 0.05f}; | ||
| 219 | if (directionalOn) lights.directional = {.direction = {-0.4f, -1.0f, -0.6f}, .color = {0.22f, 0.27f, 0.4f}}; | ||
| 220 | |||
| 221 | // 色の違う点光源四つ。それぞれ自分の中心の周りをゆっくり回る | ||
| 222 | // Four coloured point lights, each slowly circling its own centre | ||
| 223 | if (pointsOn) { | ||
| 224 | for (int i = 0; i < 4; ++i) { | ||
| 225 | float a = lightTime * (0.5f + 0.15f * static_cast<float>(i)) + static_cast<float>(i) * 1.7f; | ||
| 226 | lights.points.push_back({.position = kLanterns[i].centre + Vec3{1.2f * std::cos(a), 0.3f * std::sin(2.0f * a), | ||
| 227 | 1.2f * std::sin(a)}, | ||
| 228 | .color = kLanterns[i].color, | ||
| 229 | .attenuation = kMediumRange}); | ||
| 230 | } | ||
| 231 | } | ||
| 232 | |||
| 233 | // スポットライト:カメラの懐中電灯と、箱の山を上から照らすライト | ||
| 234 | // Spotlights: the camera's flashlight and a light shining down on the pile of crates | ||
| 235 | if (spotsOn) { | ||
| 236 | if (flashlightOn) | ||
| 237 | lights.spots.push_back({.position = viewPos, .direction = viewDir, .color = {1.0f, 0.95f, 0.85f}}); | ||
| 238 | lights.spots.push_back({.position = kStageSpotPos, | ||
| 239 | .direction = kStageSpotTarget - kStageSpotPos, | ||
| 240 | .color = {2.0f, 1.9f, 1.6f}, | ||
| 241 | .innerAngle = radians(16.0f), | ||
| 242 | .outerAngle = radians(24.0f)}); | ||
| 243 | } | ||
| 244 | |||
| 245 | glClearColor(0.02f, 0.03f, 0.06f, 1.0f); | ||
| 202 | glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); | 246 | glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); |
| 203 | 247 | ||
| 204 | // 一つの物を描く:モデル行列、法線行列、マテリアル / draws one object: model matrix, normal matrix, material | 248 | // 一つの物を描く:モデル行列、法線行列、マテリアル / draws one object: model matrix, normal matrix, material |
| @@ -213,20 +257,14 @@ int main() { | |||
| 213 | phong->set("uView", view); | 257 | phong->set("uView", view); |
| 214 | phong->set("uProj", proj); | 258 | phong->set("uProj", proj); |
| 215 | phong->set("uViewPos", viewPos); | 259 | phong->set("uViewPos", viewPos); |
| 216 | phong->set("uLightPos", lightPos); | ||
| 217 | phong->set("uLightColor", lightColor); | ||
| 218 | phong->set("uAmbient", ambient); | ||
| 219 | phong->set("uViewMode", viewMode); | 260 | phong->set("uViewMode", viewMode); |
| 261 | lights.apply(*phong); | ||
| 220 | 262 | ||
| 221 | drawLit(floorMesh, Mat4::identity(), floorMaterial); | 263 | drawLit(floorMesh, Mat4::identity(), floorMaterial); |
| 222 | 264 | ||
| 223 | // 箱:マップのオン・オフはマテリアルのコピーで切り替える / crates: the maps are switched on a copy of the material | ||
| 224 | Material crateNow = crateMaterial; | ||
| 225 | crateNow.specularMap = useSpecularMap ? &*crateSpecular : nullptr; // nullptr = 白 = 全体が鋼のように光る / white = shiny all over | ||
| 226 | crateNow.emission = useEmission ? Vec3{1.0f, 1.0f, 1.0f} : Vec3{0.0f, 0.0f, 0.0f}; | ||
| 227 | for (const CrateInfo &c : kCrates) { | 265 | for (const CrateInfo &c : kCrates) { |
| 228 | Vec3 centre = c.position + Vec3{0.0f, 0.5f * c.size, 0.0f}; | 266 | Vec3 centre = c.position + Vec3{0.0f, 0.5f * c.size, 0.0f}; |
| 229 | drawLit(cube, translate(centre) * rotateY(c.angle) * scale({c.size, c.size, c.size}), crateNow); | 267 | drawLit(cube, translate(centre) * rotateY(c.angle) * scale({c.size, c.size, c.size}), crateMaterial); |
| 230 | } | 268 | } |
| 231 | 269 | ||
| 232 | // マテリアル見本の球を一列に / a row of sample spheres, one per material | 270 | // マテリアル見本の球を一列に / a row of sample spheres, one per material |
| @@ -235,13 +273,21 @@ int main() { | |||
| 235 | drawLit(sphere, translate({x, 0.5f, 2.6f}), kMaterialSamples[i].material); | 273 | drawLit(sphere, translate({x, 0.5f, 2.6f}), kMaterialSamples[i].material); |
| 236 | } | 274 | } |
| 237 | 275 | ||
| 238 | // 光源の目印:光の色そのまま、ライティングなし / the light's marker: the light colour itself, unlit | 276 | // 光源の目印:点光源は小さな球、スポットライトは小さな箱(懐中電灯は自分の目の位置なので描かない) |
| 277 | // Light markers: small spheres for point lights, small cubes for spotlights (not the flashlight: it is at our eye) | ||
| 239 | unlit->use(); | 278 | unlit->use(); |
| 240 | unlit->set("uView", view); | 279 | unlit->set("uView", view); |
| 241 | unlit->set("uProj", proj); | 280 | unlit->set("uProj", proj); |
| 242 | unlit->set("uModel", translate(lightPos) * scale({0.2f, 0.2f, 0.2f})); | 281 | for (const PointLight &p : lights.points) { |
| 243 | unlit->set("uColor", lightOn ? lightColor : Vec3{0.2f, 0.2f, 0.2f}); | 282 | unlit->set("uModel", translate(p.position) * scale({0.15f, 0.15f, 0.15f})); |
| 244 | cube.draw(); | 283 | unlit->set("uColor", p.color); |
| 284 | sphere.draw(); | ||
| 285 | } | ||
| 286 | if (spotsOn) { | ||
| 287 | unlit->set("uModel", translate(kStageSpotPos) * scale({0.2f, 0.2f, 0.2f})); | ||
| 288 | unlit->set("uColor", Vec3{1.0f, 1.0f, 0.9f}); | ||
| 289 | cube.draw(); | ||
| 290 | } | ||
| 245 | 291 | ||
| 246 | window.swapBuffers(); | 292 | window.swapBuffers(); |
| 247 | } | 293 | } |
コメント(0)
まだコメントはありません。
ログインするとコメント出来ます。