5. A Shader Class and Uniforms
Our shaders still live in C++ strings inside main.cc.
Every change to a shader means recompiling the program, and the error messages from the driver point at line numbers inside a string literal.
That's fine for a triangle, but we're going to write a lot of shaders in this series.
In this chapter the shaders move into their own files, and a Shader class loads, compiles and links them.
When something goes wrong it prints file:line: message together with the offending source line, the same on Mesa, NVIDIA and AMD.
Then we pass values from C++ to the shaders with uniforms, animate the scene with time, and add a hot reload key: edit a shader, press R, and see the change without restarting.
If you followed the GLSL series, this is the playground's reload key again, now as a reusable class with the modern DSA uniform functions.
5.1 What we'll build
The six shapes from chapter 4, but alive:
- A wave of brightness runs across the whole screen from left to right.
- The quad pulses between its own colors and orange.
- The hexagon bobs up and down.
All three effects come from three uniforms: one time value for the whole frame, and a tint and an offset that change between draws.
The controls: R reloads the shaders, P toggles wireframe as before, Esc quits.
The project grows by two pairs of files: file_util.hh/.cc reads a text file, and shader.hh/.cc is the shader class.
The shaders themselves go into a new shaders/ folder.
The compile and link helpers from chapter 3 leave main.cc and move into shader.cc.
CMakeLists.txt lists the two new sources:
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)
5.2 Shaders in files
The two shaders from chapter 4 move into shaders/shapes.vert and shaders/shapes.frag, with some additions.
The vertex shader gets an offset:
#version 460 core
layout(location = 0) in vec3 aPosition;
layout(location = 1) in vec3 aColor;
uniform vec2 uOffset; // NDCでの移動量 / offset in NDC
out vec3 vColor;
void main() {
vColor = aColor;
gl_Position = vec4(aPosition.xy + uOffset, aPosition.z, 1.0);
}
And the fragment shader a time and a tint:
#version 460 core
in vec3 vColor;
uniform float uTime; // 秒 / seconds
uniform vec3 uTint; // 図形ごとの色 / per-shape colour
layout(location = 0) out vec4 out_color;
void main() {
// 画面を左から右へ流れる明るさの波 / a wave of brightness moving across the screen
float wave = 0.75 + 0.25 * sin(uTime * 3.0 - gl_FragCoord.x * 0.02);
out_color = vec4(vColor * uTint * wave, 1.0);
}
The file extensions .vert and .frag are only a convention (OpenGL never sees the file name), but many editors and tools such as glslangValidator use them to recognize the stage.
I'll explain the new uniform lines in 5.7.
gl_FragCoord is a built-in input of the fragment shader: the window position of the pixel being shaded, in pixels, with the origin at the bottom left (the GLSL series lists all built-ins).
So the brightness wave depends on the pixel's x coordinate and on the time:
A sine goes from −1 to 1, so wave goes from to : the colors are dimmed to half at most.
Along x, the sine repeats every pixels, so about four bright bands fit across the 1280-pixel window.
And a crest of the wave sits where is constant, that is at : the bands move to the right at 150 pixels per second.
The working directory
The program now opens shaders/shapes.vert with a relative path.
Relative paths are resolved against the process's working directory, not against the folder of the executable.
So the program must be started from the project root, as chapter 1 explained:
- Linux and FreeBSD: run
./build/gamefrom the project root, notcd build && ./game. - Visual Studio with the generated solution: our
CMakeLists.txtsetsVS_DEBUGGER_WORKING_DIRECTORYto the project root, so F5 just works. - Visual Studio with Open Folder: this mode ignores that property. If the program says it can't open the shaders, open the debug settings of
game(Debug → Debug and Launch Settings for game) and add"currentDir": "${workspaceRoot}"to its configuration inlaunch.vs.json.
If you get it wrong, you'll see this instead of a window (the messages are bilingual, like all our output):
shaders/shapes.vert: 開けない / cannot open (プロジェクトのルートから実行した? / running from the project root?)
shaders/shapes.frag: 開けない / cannot open (プロジェクトのルートから実行した? / running from the project root?)
Note: On Windows, save shader files as UTF-8 without a byte order mark (in Visual Studio: File → Save As → the arrow next to Save → Save with Encoding → "Unicode (UTF-8 without signature)"). Some drivers reject the invisible BOM bytes before #version. Japanese comments themselves are fine: since GLSL 4.20 the source character set is UTF-8.
5.3 Reading a file
The file helper is tiny:
// ファイルの読み込み / reading files
#pragma once
#include <optional>
#include <string>
// ファイル全体を文字列として読む。開けなければstd::nullopt。
// Reads a whole file into a string. std::nullopt if it cannot be opened.
std::optional<std::string> readTextFile(const std::string &path);
#include "file_util.hh"
#include <fstream>
#include <sstream>
std::optional<std::string> readTextFile(const std::string &path) {
// バイナリモード:Windowsで改行が変換されないように / binary mode: no newline conversion on Windows
std::ifstream file(path, std::ios::binary);
if (!file) return std::nullopt;
std::ostringstream text;
text << file.rdbuf();
return text.str();
}
std::ifstream opens the file; if that fails (wrong path, no permission), the stream converts to false and we return std::nullopt.
Remember that our code never throws, so "maybe a value" is expressed with std::optional and the caller decides what to do.
text << file.rdbuf() copies the whole file into a string stream in one go.
The std::ios::binary flag deserves a word.
In text mode, the Windows C++ library converts every CR LF line ending to LF while reading.
In binary mode we get the bytes exactly as they are on disk, on every platform.
The GLSL compiler accepts both line endings, and our error printer below only looks for the LF at the end of each line, so binary mode makes the behavior identical everywhere.
5.4 The Shader class
Here is the interface:
// シェーダープログラム / a shader program
#pragma once
#include <glad/glad.h>
#include <linalg.hh>
#include <optional>
#include <string>
#include <unordered_set>
// ファイルから読み込んだシェーダープログラム(RAII、コピー不可・移動可)。
// A shader program loaded from files (RAII, non-copyable, movable).
class Shader {
public:
Shader() = default;
~Shader();
Shader(const Shader &) = delete;
Shader &operator=(const Shader &) = delete;
Shader(Shader &&other) noexcept;
Shader &operator=(Shader &&other) noexcept;
// 頂点・フラグメントシェーダーのファイルから作る。失敗したらエラーを表示してstd::nullopt。
// Builds a program from vertex and fragment shader files. On failure prints the errors and returns std::nullopt.
static std::optional<Shader> load(const std::string &vertexPath, const std::string &fragmentPath);
// ファイルを読み直す。失敗したら古いプログラムをそのまま使い続け、falseを返す。
// Re-reads the files. On failure keeps using the old program and returns false.
bool reload();
void use() const { glUseProgram(program); }
GLuint id() const { return program; }
// ユニフォームを設定(DSA:glProgramUniform*なので use() は不要)
// Set uniforms (DSA: glProgramUniform*, so use() is not needed)
void set(const char *name, int value) const;
void set(const char *name, float value) const;
void set(const char *name, Vec2 value) const;
void set(const char *name, Vec3 value) const;
void set(const char *name, Vec4 value) const;
void set(const char *name, const Mat4 &value) const;
private:
GLint location(const char *name) const;
GLuint program = 0;
std::string vertexPath, fragmentPath;
mutable std::unordered_set<std::string> warned; // 見つからない名前は一度だけ警告 / warn once per missing name
};
It follows the Buffer pattern from chapter 4 (RAII, non-copyable, movable), with two differences:
- Creation can fail, because a shader may not compile. So instead of a public constructor there is a factory function
Shader::loadthat returnsstd::optional<Shader>. If it returns a value, the program is valid. - The class remembers its file paths, so that
reload()can read the same files again.
The rest of this section and the next ones walk through shader.cc from the bottom up: compiling one stage, linking, printing errors, loading and reloading, and setting uniforms.
Compiling one stage
compileStage is chapter 3's compileShader with a file instead of a string, and with a log buffer of the right size:
// 一つのステージ(頂点・フラグメント…)をファイルからコンパイル。失敗したら0。
// Compiles one stage (vertex, fragment, ...) from a file. Returns 0 on failure.
static GLuint compileStage(GLenum type, const std::string &path) {
std::optional<std::string> source = readTextFile(path);
if (!source) {
fprintf(stderr, "%s: 開けない / cannot open (プロジェクトのルートから実行した? / running from the project root?)\n",
path.c_str());
return 0;
}
GLuint shader = glCreateShader(type);
const char *text = source->c_str();
glShaderSource(shader, 1, &text, nullptr);
glCompileShader(shader);
GLint ok = 0;
glGetShaderiv(shader, GL_COMPILE_STATUS, &ok);
if (!ok) {
GLint length = 0;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &length);
std::string log(static_cast<size_t>(length > 1 ? length : 1), '\0');
glGetShaderInfoLog(shader, length, nullptr, log.data());
printShaderLog(path, *source, log.c_str());
glDeleteShader(shader);
return 0;
}
return shader;
}
glShaderSource(shader, count, strings, lengths) takes an array of strings, which the compiler concatenates.
We pass one string (count = 1) and nullptr for the lengths, which means "each string ends at its null terminator".
The array form is how some engines prepend a common header (#version and #defines) to every shader without copying the source.
New is glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &length).
It returns the length of the compiler's log including the terminating null, or 0 if there is no log.
Chapter 3 used a fixed 2048-byte array, which cuts off long error lists; now the string is exactly as large as needed.
We only print the log on failure: on success some drivers write warnings or even "compiled successfully" messages into it, which would only be noise.
Linking
buildProgram compiles both stages and links them, as in chapter 3:
// 頂点とフラグメントをリンク。失敗したら0。 / links a vertex and a fragment shader. Returns 0 on failure.
static GLuint buildProgram(const std::string &vertexPath, const std::string &fragmentPath) {
GLuint vs = compileStage(GL_VERTEX_SHADER, vertexPath);
GLuint fs = compileStage(GL_FRAGMENT_SHADER, fragmentPath);
if (!vs || !fs) {
glDeleteShader(vs); // 0は無視される / 0 is silently ignored
glDeleteShader(fs);
return 0;
}
GLuint program = glCreateProgram();
glAttachShader(program, vs);
glAttachShader(program, fs);
glLinkProgram(program);
glDetachShader(program, vs);
glDetachShader(program, fs);
glDeleteShader(vs);
glDeleteShader(fs);
GLint ok = 0;
glGetProgramiv(program, GL_LINK_STATUS, &ok);
if (!ok) {
char log[4096];
glGetProgramInfoLog(program, sizeof log, nullptr, log);
fprintf(stderr, "%s + %s: リンクエラー / link error:\n%s\n", vertexPath.c_str(), fragmentPath.c_str(), log);
glDeleteProgram(program);
return 0;
}
return program;
}
If one stage fails, we still compile the other, so that one run shows all errors.
glDeleteShader(0) is explicitly allowed and does nothing, which keeps the cleanup short.
Link errors (for example a fragment shader in that no vertex shader out matches) have no file and line, so we print the two file names and the log as it is.
5.5 Readable error messages
Every driver formats its compile errors differently.
Here's the same kind of message from the three big families:
| Driver | Log line |
|---|---|
| Mesa (Linux, FreeBSD) | 0:12(5): error: ... |
| NVIDIA | 0(12) : error C1008: ... |
| AMD and Intel on Windows | ERROR: 0:12: ... |
The first number is the source string index (always 0 for us, since we pass a single string), the second is the line, and Mesa adds the column in parentheses.
parseLogLine finds a 0: or 0( that starts a word, reads the line number after it, and cuts out the location so that only the message remains:
// コンパイラのログの一行から行番号を探し、位置の部分を取り除いたメッセージをmessageに入れる。行番号がなければ0。
// Mesa: "0:12(5): error: ..."
// NVIDIA: "0(12) : error C1008: ..."
// AMD/Intel: "ERROR: 0:12: ..."
// Finds the line number in one line of the compiler log and stores the message without the location
// in message. Returns 0 if there is no line number.
static int parseLogLine(std::string_view line, std::string &message) {
for (size_t i = 0; i + 2 < line.size(); ++i) {
bool startOk = (i == 0 || line[i - 1] == ' ');
if (!startOk || line[i] != '0' || (line[i + 1] != ':' && line[i + 1] != '(')) continue;
int number = 0;
size_t j = i + 2;
while (j < line.size() && line[j] >= '0' && line[j] <= '9') number = number * 10 + (line[j++] - '0');
if (j == i + 2) continue;
size_t rest = line.find(": ", j); // 位置の後の「: 」 / the ": " after the location
rest = rest == std::string_view::npos ? j : rest + 2;
message = std::string(line.substr(0, i)) + std::string(line.substr(rest));
return number;
}
message = std::string(line);
return 0;
}
For the Mesa line 0:12(5): error: x, the loop stops at , reads the digits 1 and 2 into number (, then ), finds the ": " after (5), and keeps error: x.
For AMD's ERROR: 0:12: x, the match is at , and the text before it (ERROR: ) is kept in front of the message.
sourceLine returns line of the source by skipping newlines, and printShaderLog puts it all together, one log line at a time:
// ソースのn行目(1始まり) / line n of the source (1-based)
static std::string_view sourceLine(std::string_view source, int n) {
size_t start = 0;
for (int i = 1; i < n; ++i) {
start = source.find('\n', start);
if (start == std::string_view::npos) return {};
++start;
}
size_t end = source.find('\n', start);
return source.substr(start, end == std::string_view::npos ? std::string_view::npos : end - start);
}
// エラーを「ファイル:行: メッセージ」の形で表示し、その行のソースも見せる
// Prints errors as "file:line: message" and shows that source line
static void printShaderLog(const std::string &path, std::string_view source, std::string_view log) {
while (!log.empty()) {
size_t end = log.find('\n');
std::string_view line = log.substr(0, end);
log = end == std::string_view::npos ? std::string_view{} : log.substr(end + 1);
if (line.empty()) continue;
std::string message;
int n = parseLogLine(line, message);
if (n > 0) {
std::string_view code = sourceLine(source, n);
fprintf(stderr, "%s:%d: %s\n %4d | %.*s\n", path.c_str(), n, message.c_str(), n, static_cast<int>(code.size()),
code.data());
} else {
fprintf(stderr, "%s: %s\n", path.c_str(), message.c_str());
}
}
}
The %.*s format prints a string_view, which isn't null-terminated, by passing its length as an int first.
Here is the result for a fragment shader where I misspelled vColor as vColr, and a vertex shader where I removed the ; after uniform vec2 uOffset:
shaders/shapes.vert:7: error: syntax error, unexpected OUT_TOK, expecting ',' or ';'
7 | out vec3 vColor;
shaders/shapes.frag:12: error: `vColr' undeclared
12 | out_color = vec4(vColr * uTint * wave, 1.0);
shaders/shapes.frag:12: error: operands to arithmetic operators must be numeric
12 | out_color = vec4(vColr * uTint * wave, 1.0);
shaders/shapes.frag:12: error: operands to arithmetic operators must be numeric
12 | out_color = vec4(vColr * uTint * wave, 1.0);
shaders/shapes.frag:12: error: cannot construct `vec4' from a non-numeric data type
12 | out_color = vec4(vColr * uTint * wave, 1.0);
Two lessons from this output that hold for every compiler, not only for GLSL:
- The first error is the real one. The three lines after
vColr' undeclaredare consequences: an undeclared name has no type, so the multiplication and the constructor fail as well. Fix the first error and compile again. - A missing
;is reported on the next line that doesn't fit. The semicolon is missing on line 5, but line 6 is empty, and only theouton line 7 tells the parser that the declaration didn't end. When the error line looks correct, look at the line above it.
The format file:line: message is the same as GCC's and Clang's, so editors such as Vim, Emacs or VS Code can jump to the error from the output.
5.6 Loading and reloading
load builds the program and wraps it into a Shader:
std::optional<Shader> Shader::load(const std::string &vertexPath, const std::string &fragmentPath) {
GLuint program = buildProgram(vertexPath, fragmentPath);
if (!program) return std::nullopt;
Shader shader;
shader.program = program;
shader.vertexPath = vertexPath;
shader.fragmentPath = fragmentPath;
return shader;
}
reload builds a new program from the same files and only replaces the old one if that worked:
bool Shader::reload() {
GLuint fresh = buildProgram(vertexPath, fragmentPath);
if (!fresh) return false; // 古いプログラムを残す / keep the old program
glDeleteProgram(program);
program = fresh;
warned.clear();
return true;
}
Why not compile into the existing program object?
Because then a typo would leave us without a working program, and the screen would go black until the shader is fixed.
With a fresh program, a failed reload prints the errors and the old shader keeps drawing.
That makes hot reload pleasant: save with a typo, press R, read the error, fix it, press R again, and the window never stops showing something.
There is one consequence to keep in mind.
A new program object starts with all uniforms at 0, and its uniform locations may be different from the old one's.
So after a reload, every uniform must be set again.
Our demo sets all uniforms every frame anyway, so you won't notice, but if you ever set a uniform only once at startup, it will be 0 after the first reload.
This is also why reload clears the warned set (5.7) and why the class doesn't cache locations.
The destructor and the move operations follow the usual pattern:
Shader::~Shader() {
if (program) glDeleteProgram(program);
}
Shader::Shader(Shader &&other) noexcept
: program(std::exchange(other.program, 0)), vertexPath(std::move(other.vertexPath)),
fragmentPath(std::move(other.fragmentPath)), warned(std::move(other.warned)) {}
Shader &Shader::operator=(Shader &&other) noexcept {
if (this != &other) {
if (program) glDeleteProgram(program);
program = std::exchange(other.program, 0);
vertexPath = std::move(other.vertexPath);
fragmentPath = std::move(other.fragmentPath);
warned = std::move(other.warned);
}
return *this;
}
5.7 Uniforms
A uniform is a shader variable whose value comes from the application and is the same for every vertex and every pixel of one draw call.
That's where the name comes from: it's uniform across the draw.
Attributes change per vertex, interpolated outputs change per pixel, and uniforms change only when the application changes them.
The GLSL series covers the uniform qualifier from the shader side; here we look at the OpenGL side.
Each uniform of a linked program has a location, an integer that the C++ side uses to address it.
The values live in the program object.
Two programs that both declare uTime have two separate uTime values.
Finding a location
glGetUniformLocation(program, name) returns the location of the uniform called name, or −1 if the program has no active uniform of that name:
GLint Shader::location(const char *name) const {
GLint loc = glGetUniformLocation(program, name);
// -1:名前の間違い、または使われていないので最適化で消された
// -1: a typo, or the uniform is unused and the compiler removed it
if (loc < 0 && warned.insert(name).second)
fprintf(stderr, "%s + %s: ユニフォーム「%s」がない / no active uniform \"%s\"\n", vertexPath.c_str(),
fragmentPath.c_str(), name, name);
return loc;
}
"Active" is the important word.
The GLSL compiler removes every uniform that doesn't contribute to the output, so a uniform that you declare but never use has no location.
If I remove uTint from the expression in shapes.frag and press R, the program tells me once:
shaders/shapes.vert + shaders/shapes.frag: ユニフォーム「uTint」がない / no active uniform "uTint"
The name is right, but the uniform no longer exists in the compiled program.
That's why the warning only says "no active uniform" and doesn't claim a typo.
The warned set makes sure we see each name once and not 60 times per second; it is mutable because set is a const function (setting a uniform doesn't change our C++ object).
glGetUniformLocation is a string lookup inside the driver.
Calling it for every set is fine at our scale of a few dozen calls per frame; challenge 3 caches the locations, and chapter 19 replaces many single uniforms with uniform buffers.
Setting a value: glProgramUniform
Our set overloads each call one function of the glProgramUniform family:
// location が -1 なら glProgramUniform* は何もしない / with location -1, glProgramUniform* does nothing
void Shader::set(const char *name, int value) const { glProgramUniform1i(program, location(name), value); }
void Shader::set(const char *name, float value) const { glProgramUniform1f(program, location(name), value); }
void Shader::set(const char *name, Vec2 v) const { glProgramUniform2f(program, location(name), v.x, v.y); }
void Shader::set(const char *name, Vec3 v) const { glProgramUniform3f(program, location(name), v.x, v.y, v.z); }
void Shader::set(const char *name, Vec4 v) const { glProgramUniform4f(program, location(name), v.x, v.y, v.z, v.w); }
void Shader::set(const char *name, const Mat4 &m) const {
// linalg.hhは列優先なので転置しない(GL_FALSE) / linalg.hh is column-major, so no transpose (GL_FALSE)
glProgramUniformMatrix4fv(program, location(name), 1, GL_FALSE, &m.c[0].x);
}
The pattern is glProgramUniform{count}{type}(program, location, values…):
program: the program whose uniform we set. This is the DSA part.location: fromglGetUniformLocation. If it is −1, the call is silently ignored, which is why a missing uniform is a warning and not a crash.- the suffix gives the number of components (1 to 4) and the type (
iforint,uiforunsigned int,fforfloat). SoglProgramUniform3fsets avec3. - the
vvariants, likeglProgramUniformMatrix4fv(program, location, count, transpose, value), take a pointer tocountvalues instead. For matrices,transpose = GL_FALSEmeans "the data is column-major", which is howMat4from linalg.hh stores it. We need that overload from chapter 7 on.
The glProgramUniform functions exist since OpenGL 4.1.
Most older tutorials use glUniform3f(location, x, y, z) instead, which has no program parameter: it sets the uniform of whatever program glUseProgram made current.
That's the bind-to-edit style from chapter 3 again, with the same trap: set a uniform before glUseProgram, and it goes to the previous program (or causes GL_INVALID_OPERATION if there is none).
With glProgramUniform, set works at any time, and use() is only needed for drawing.
The type of the call must match the type in the shader exactly.
OpenGL doesn't convert: an int for a float uniform is an error.
If I write shader->set("uTime", 1) (an int literal, so the int overload is chosen), the debug logger from chapter 2 reports it every frame:
[GL ERROR] (API, high, id 1) GL_INVALID_OPERATION in glUniform1("uTime"@2 is float, not int)
(The wording is Mesa's; other drivers say the same in other words.)
The fix is 1.0f.
For the same reason set has separate overloads for Vec2, Vec3 and Vec4: glProgramUniform3f on a vec2 uniform is an error too.
Note: Samplers (chapter 6) are integer uniforms that hold a texture unit number, so theintoverload is the one that sets them. We'll set their units in the shader withlayout(binding = N)instead, so we never need it for that.
Common mistakes with uniforms, in one place:
- Forgetting to set a uniform. It keeps the value 0. A tint of (0, 0, 0) makes everything black, and a scale of 0 makes everything vanish.
- Wrong type or component count.
GL_INVALID_OPERATION, see above. - Setting it on the wrong program. Each program has its own values, so a uniform set on program A doesn't affect program B, even if the names are the same.
- Expecting
glGetUniformLocationto find an unused uniform. It returns −1 after the compiler removed it.
5.8 Using the class in main
main loads the shader right after creating the window, and quits if that fails:
int main() {
Window window;
if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 5")) return 1;
// シェーダーはファイルから読む(作業ディレクトリ=プロジェクトのルート)
// shaders are read from files (working directory = project root)
std::optional<Shader> shader = Shader::load("shaders/shapes.vert", "shaders/shapes.frag");
if (!shader) return 1;
The R key calls reload and reports success; on failure reload has already printed the errors:
bool wireframe = false;
window.onKey = [&](int key, int action, int /*mods*/) {
if (action != GLFW_PRESS) return;
if (key == GLFW_KEY_ESCAPE) window.close();
if (key == GLFW_KEY_R) {
// 失敗しても古いシェーダーで描き続ける / on failure we keep drawing with the old shader
if (shader->reload()) printf("シェーダーを読み直した / shaders reloaded\n");
}
if (key == GLFW_KEY_P) {
wireframe = !wireframe;
// 三角形を線で描く(デバッグに便利) / draw triangles as lines (handy for debugging)
glPolygonMode(GL_FRONT_AND_BACK, wireframe ? GL_LINE : GL_FILL);
}
};
The meshes are created exactly as in chapter 4.
The draw loop is where the uniforms come in:
while (!window.shouldClose()) {
window.pollEvents();
glClearColor(0.10f, 0.15f, 0.25f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
float t = static_cast<float>(window.time());
const Vec3 white = {1.0f, 1.0f, 1.0f};
shader->use();
// フレームに一回:全ての描画で同じ値 / once per frame: the same value for every draw
shader->set("uTime", t);
// 描画ごと:ユニフォームは次に変えるまでプログラムに残る
// per draw: a uniform keeps its value in the program until we change it
shader->set("uOffset", Vec2{0.0f, 0.0f});
shader->set("uTint", white);
triangle.draw();
points.draw();
star.draw();
ribbon.draw();
// 四角形:色が白とオレンジの間で変わる / the quad: colour moves between white and orange
float pulse = 0.5f + 0.5f * std::sin(t * 2.0f);
shader->set("uTint", lerp(white, Vec3{1.0f, 0.5f, 0.1f}, pulse));
quad.draw();
// 六角形:上下に揺れる / the hexagon bobs up and down
shader->set("uTint", white);
shader->set("uOffset", Vec2{0.0f, 0.1f * std::sin(t * 3.0f)});
hexagon.draw();
window.swapBuffers();
}
return 0; // シェーダーとメッシュはここで自動的に削除される / the shader and meshes are deleted automatically here
}
window.time() is glfwGetTime() from chapter 2: seconds since GLFW started, as a double.
We convert it to float because that's what the shader uses.
(A float has about 7 significant digits, so after many hours of running, uTime loses precision and animations start to stutter. Engines wrap the time or send it as a smaller "time since the level started". For us it doesn't matter.)
The important idea of this loop: a uniform keeps its value in the program until we change it.
Setting a uniform is not part of the draw call; it changes the program's state, and every draw afterwards sees the new value.
So the order of set and draw calls decides what each shape gets:
| Draw | uOffset |
uTint |
|---|---|---|
| triangle, points, star, ribbon | (0, 0) | white |
| quad | (0, 0) | between white and orange |
| hexagon | (0, 0.1 sin 3t) | white |
uTime is set once per frame and is the same for all six.
The offset and tint are set back to their neutral values at the top of each frame, because otherwise the triangle would inherit the hexagon's offset from the previous frame and bob along with it.
(Try it: remove the uOffset line before triangle.draw(), and from the second frame on all six shapes bob together with the hexagon.)
The quad's tint uses lerp from linalg.hh:
with white and orange .
At , and the tint is , a light peach.
At it's pure orange, at pure white, and repeats every seconds.
In the shader, the tint is multiplied component-wise with the vertex colors, so the red channel is kept and green and blue are reduced: the quad's blue and purple corners turn dark.
The hexagon's offset is in NDC units.
NDC spans 2 units over 720 pixels vertically, so 0.1 is pixels up and down.
5.9 Hot reload in practice
Run the program, open shaders/shapes.frag in your editor, and change the last line to
out_color = vec4((1.0 - vColor) * uTint * wave, 1.0);
Save and press R in the window.
The terminal prints シェーダーを読み直した / shaders reloaded, and all colors are inverted at once, while the animation keeps running.
Now make a mistake on purpose, save, and press R again: the errors appear in the terminal, and the window keeps showing the last working version.
This loop of edit, save, reload, look takes about a second, compared to a full rebuild and restart.
For shader work that difference is huge, which is why every engine has some form of it.
Ours is the simplest form, a key press; challenge 4 turns it into automatic reloading when the file changes.
Note: Reloading only re-reads the shader files. Changes to main.cc still need a rebuild. And if you change the interface of a shader, for example by adding an attribute, the C++ side has to match before the change makes sense.
5.10 How real engines do it
- Uniform buffers instead of single uniforms. Setting dozens of uniforms one by one per draw is slow. Engines group them into blocks (per frame, per material, per object) and upload each block as one buffer. Chapter 19 does this, and Vulkan only has blocks.
- Cached locations or reflection. Engines query all active uniforms once after linking (
glGetProgramiv(GL_ACTIVE_UNIFORMS)andglGetActiveUniform), store their locations and types, and check the C++ value against the type before uploading. - Include files and permutations. GLSL has no
#include(challenge 6 adds one). Engines prepend shared code and#defines, and compile many variants of one shader (with and without shadows, skinning, fog, …). - Offline compilation. Instead of compiling GLSL text at startup, many engines compile shaders ahead of time to SPIR-V (
glShaderBinarywithGL_SHADER_BINARY_FORMAT_SPIR_V, OpenGL 4.6) or cache the driver's binary withglGetProgramBinary. Vulkan only accepts SPIR-V; the Slang and Vulkan series after this one work that way. - File watchers. Editors watch the shader folder (
inotifyon Linux,kqueueon FreeBSD,ReadDirectoryChangesWon Windows) and reload changed shaders automatically, keeping the old version on error, just like ourreload.
5.11 Summary
- Shaders live in
shaders/*.vertandshaders/*.fragand are loaded relative to the working directory: always run from the project root. Shader::loadreturnsstd::optional<Shader>; errors are printed asfile:line: messageplus the source line, for Mesa, NVIDIA and AMD log formats.- The first compiler error is the real one; a missing
;shows up on a later line. reloadbuilds a new program and swaps it in only on success. A new program has all uniforms at 0, so set uniforms every frame.- Uniforms are per-program state, constant during a draw.
glGetUniformLocationreturns −1 for names that aren't active;glProgramUniform*sets a value withoutglUseProgram, and the type must match exactly. - A uniform keeps its value until it is changed, so the order of
setanddrawcalls decides what each draw sees.
5.12 Challenges
- ★ Add a
uniform float uSpeed;toshapes.fragthat replaces the3.0in the wave, and change it with the ↑ and ↓ keys (usewindow.keyDownanddtfrom chapter 2, and clamp it to 0..10). The bands should speed up, slow down and stop at 0. - ★ While the program runs, change
shapes.fragso that it outputs only the wave as gray (vec4(vec3(wave), 1.0)) and pressR. You should see gray shapes with moving bright bands. Then leave a typo in it and pressR: the error appears, and the gray shapes stay. - ★★ Cache the uniform locations in an
std::unordered_map<std::string, GLint>insideShader, filled on first use and cleared inreload. The output must be identical. Count how manyglGetUniformLocationcalls happen per frame before and after (from 6 to 0 after the first frame). - ★★ Implement automatic reloading: once per second, compare
std::filesystem::last_write_timeof both shader files with the time of the last load, and callreload()when one changed. Saving a shader file should update the window without pressingR. What happens if your editor saves the file in two steps? - ★★ Make the triangle follow the mouse with
uOffset: convertwindow.mouseX()andmouseY()from window pixels (origin top left, y down) to an NDC offset (y up). The triangle should move with the cursor; if it moves the wrong way vertically, you forgot to flip y. - ★★★ Add
#includesupport tocompileStage: before compiling, replace every line#include "name.glsl"with the contents ofshaders/name.glsl. Then move the wave into a function inshaders/common.glsl. Keep the error messages correct: an error in the included file must namecommon.glsland its own line number (hint: GLSL's#linedirective, or a table that maps the combined line numbers back to files).
ファイル: a/CMakeLists.txt | b/CMakeLists.txt
| 前 | 新 | ||
|---|---|---|---|
| @@ -24,7 +24,9 @@ add_executable(game | |||
| 24 | src/window.cc | 24 | src/window.cc |
| 25 | src/gl_debug.cc | 25 | src/gl_debug.cc |
| 26 | src/buffer.cc | 26 | src/buffer.cc |
| 27 | src/mesh.cc) | 27 | src/mesh.cc |
| 28 | src/file_util.cc | ||
| 29 | src/shader.cc) | ||
| 28 | target_include_directories(game PRIVATE src external/stb external/linalg) | 30 | target_include_directories(game PRIVATE src external/stb external/linalg) |
| 29 | target_link_libraries(game PRIVATE glad glfw) | 31 | target_link_libraries(game PRIVATE glad glfw) |
| 30 | 32 | ||
ファイル: /dev/null | b/shaders/shapes.frag
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,13 @@ | |||
| 1 | #version 460 core | ||
| 2 | in vec3 vColor; | ||
| 3 | |||
| 4 | uniform float uTime; // 秒 / seconds | ||
| 5 | uniform vec3 uTint; // 図形ごとの色 / per-shape colour | ||
| 6 | |||
| 7 | layout(location = 0) out vec4 out_color; | ||
| 8 | |||
| 9 | void main() { | ||
| 10 | // 画面を左から右へ流れる明るさの波 / a wave of brightness moving across the screen | ||
| 11 | float wave = 0.75 + 0.25 * sin(uTime * 3.0 - gl_FragCoord.x * 0.02); | ||
| 12 | out_color = vec4(vColor * uTint * wave, 1.0); | ||
| 13 | } | ||
ファイル: /dev/null | b/shaders/shapes.vert
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,12 @@ | |||
| 1 | #version 460 core | ||
| 2 | layout(location = 0) in vec3 aPosition; | ||
| 3 | layout(location = 1) in vec3 aColor; | ||
| 4 | |||
| 5 | uniform vec2 uOffset; // NDCでの移動量 / offset in NDC | ||
| 6 | |||
| 7 | out vec3 vColor; | ||
| 8 | |||
| 9 | void main() { | ||
| 10 | vColor = aColor; | ||
| 11 | gl_Position = vec4(aPosition.xy + uOffset, aPosition.z, 1.0); | ||
| 12 | } | ||
ファイル: /dev/null | b/src/file_util.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,13 @@ | |||
| 1 | #include "file_util.hh" | ||
| 2 | |||
| 3 | #include <fstream> | ||
| 4 | #include <sstream> | ||
| 5 | |||
| 6 | std::optional<std::string> readTextFile(const std::string &path) { | ||
| 7 | // バイナリモード:Windowsで改行が変換されないように / binary mode: no newline conversion on Windows | ||
| 8 | std::ifstream file(path, std::ios::binary); | ||
| 9 | if (!file) return std::nullopt; | ||
| 10 | std::ostringstream text; | ||
| 11 | text << file.rdbuf(); | ||
| 12 | return text.str(); | ||
| 13 | } | ||
ファイル: /dev/null | b/src/file_util.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,9 @@ | |||
| 1 | // ファイルの読み込み / reading files | ||
| 2 | #pragma once | ||
| 3 | |||
| 4 | #include <optional> | ||
| 5 | #include <string> | ||
| 6 | |||
| 7 | // ファイル全体を文字列として読む。開けなければstd::nullopt。 | ||
| 8 | // Reads a whole file into a string. std::nullopt if it cannot be opened. | ||
| 9 | std::optional<std::string> readTextFile(const std::string &path); | ||
ファイル: a/src/main.cc | b/src/main.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -1,8 +1,12 @@ | |||
| 1 | // 第4章:頂点属性とインデックスバッファ | 1 | // 第5章:シェーダークラスとユニフォーム |
| 2 | // Chapter 4: vertex attributes and index buffers | 2 | // Chapter 5: a shader class and uniforms |
| 3 | // | 3 | // |
| 4 | // 操作 / Controls: P ワイヤーフレーム切り替え / toggle wireframe, Esc 終了 / quit | 4 | // 操作 / Controls: |
| 5 | // R シェーダーを読み直す / reload the shaders | ||
| 6 | // P ワイヤーフレーム切り替え / toggle wireframe | ||
| 7 | // Esc 終了 / quit | ||
| 5 | #include "mesh.hh" | 8 | #include "mesh.hh" |
| 9 | #include "shader.hh" | ||
| 6 | #include "window.hh" | 10 | #include "window.hh" |
| 7 | 11 | ||
| 8 | #include <linalg.hh> | 12 | #include <linalg.hh> |
| @@ -10,6 +14,7 @@ | |||
| 10 | #include <cmath> | 14 | #include <cmath> |
| 11 | #include <cstddef> | 15 | #include <cstddef> |
| 12 | #include <cstdio> | 16 | #include <cstdio> |
| 17 | #include <optional> | ||
| 13 | #include <vector> | 18 | #include <vector> |
| 14 | 19 | ||
| 15 | // 位置と色を交互に並べた(インターリーブ)頂点 / a vertex with position and colour interleaved | 20 | // 位置と色を交互に並べた(インターリーブ)頂点 / a vertex with position and colour interleaved |
| @@ -24,67 +29,6 @@ constexpr VertexAttrib kColorVertexLayout[] = { | |||
| 24 | {1, 3, offsetof(ColorVertex, color)}, // layout(location = 1) in vec3 aColor | 29 | {1, 3, offsetof(ColorVertex, color)}, // layout(location = 1) in vec3 aColor |
| 25 | }; | 30 | }; |
| 26 | 31 | ||
| 27 | static const char *kVertexShader = R"(#version 460 core | ||
| 28 | layout(location = 0) in vec3 aPosition; | ||
| 29 | layout(location = 1) in vec3 aColor; | ||
| 30 | |||
| 31 | out vec3 vColor; // フラグメントシェーダーへ(補間される) / to the fragment shader (interpolated) | ||
| 32 | |||
| 33 | void main() { | ||
| 34 | vColor = aColor; | ||
| 35 | gl_Position = vec4(aPosition, 1.0); | ||
| 36 | } | ||
| 37 | )"; | ||
| 38 | |||
| 39 | static const char *kFragmentShader = R"(#version 460 core | ||
| 40 | in vec3 vColor; | ||
| 41 | layout(location = 0) out vec4 out_color; | ||
| 42 | |||
| 43 | void main() { | ||
| 44 | out_color = vec4(vColor, 1.0); | ||
| 45 | } | ||
| 46 | )"; | ||
| 47 | |||
| 48 | static GLuint compileShader(GLenum type, const char *source) { | ||
| 49 | GLuint shader = glCreateShader(type); | ||
| 50 | glShaderSource(shader, 1, &source, nullptr); | ||
| 51 | glCompileShader(shader); | ||
| 52 | |||
| 53 | GLint ok = 0; | ||
| 54 | glGetShaderiv(shader, GL_COMPILE_STATUS, &ok); | ||
| 55 | if (!ok) { | ||
| 56 | char log[2048]; | ||
| 57 | glGetShaderInfoLog(shader, sizeof log, nullptr, log); | ||
| 58 | fprintf(stderr, "%sシェーダーのエラー / %s shader error:\n%s\n", type == GL_VERTEX_SHADER ? "頂点" : "フラグメント", | ||
| 59 | type == GL_VERTEX_SHADER ? "vertex" : "fragment", log); | ||
| 60 | glDeleteShader(shader); | ||
| 61 | return 0; | ||
| 62 | } | ||
| 63 | return shader; | ||
| 64 | } | ||
| 65 | |||
| 66 | static GLuint linkProgram(GLuint vertexShader, GLuint fragmentShader) { | ||
| 67 | GLuint program = glCreateProgram(); | ||
| 68 | glAttachShader(program, vertexShader); | ||
| 69 | glAttachShader(program, fragmentShader); | ||
| 70 | glLinkProgram(program); | ||
| 71 | glDetachShader(program, vertexShader); | ||
| 72 | glDetachShader(program, fragmentShader); | ||
| 73 | glDeleteShader(vertexShader); | ||
| 74 | glDeleteShader(fragmentShader); | ||
| 75 | |||
| 76 | GLint ok = 0; | ||
| 77 | glGetProgramiv(program, GL_LINK_STATUS, &ok); | ||
| 78 | if (!ok) { | ||
| 79 | char log[2048]; | ||
| 80 | glGetProgramInfoLog(program, sizeof log, nullptr, log); | ||
| 81 | fprintf(stderr, "リンクエラー / link error:\n%s\n", log); | ||
| 82 | glDeleteProgram(program); | ||
| 83 | return 0; | ||
| 84 | } | ||
| 85 | return program; | ||
| 86 | } | ||
| 87 | |||
| 88 | // NDCは横に引き伸ばされる(1280×720)ので、計算で作る図形はxを縮める。第8章で投影行列が解決する。 | 32 | // NDCは横に引き伸ばされる(1280×720)ので、計算で作る図形はxを縮める。第8章で投影行列が解決する。 |
| 89 | // NDC is stretched horizontally (1280×720), so generated shapes shrink x. Chapter 8's projection fixes this. | 33 | // NDC is stretched horizontally (1280×720), so generated shapes shrink x. Chapter 8's projection fixes this. |
| 90 | constexpr float kAspectFix = 720.0f / 1280.0f; | 34 | constexpr float kAspectFix = 720.0f / 1280.0f; |
| @@ -152,12 +96,21 @@ static Mesh makeRibbon(Vec2 center) { | |||
| 152 | 96 | ||
| 153 | int main() { | 97 | int main() { |
| 154 | Window window; | 98 | Window window; |
| 155 | if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 4")) return 1; | 99 | if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 5")) return 1; |
| 100 | |||
| 101 | // シェーダーはファイルから読む(作業ディレクトリ=プロジェクトのルート) | ||
| 102 | // shaders are read from files (working directory = project root) | ||
| 103 | std::optional<Shader> shader = Shader::load("shaders/shapes.vert", "shaders/shapes.frag"); | ||
| 104 | if (!shader) return 1; | ||
| 156 | 105 | ||
| 157 | bool wireframe = false; | 106 | bool wireframe = false; |
| 158 | window.onKey = [&](int key, int action, int /*mods*/) { | 107 | window.onKey = [&](int key, int action, int /*mods*/) { |
| 159 | if (action != GLFW_PRESS) return; | 108 | if (action != GLFW_PRESS) return; |
| 160 | if (key == GLFW_KEY_ESCAPE) window.close(); | 109 | if (key == GLFW_KEY_ESCAPE) window.close(); |
| 110 | if (key == GLFW_KEY_R) { | ||
| 111 | // 失敗しても古いシェーダーで描き続ける / on failure we keep drawing with the old shader | ||
| 112 | if (shader->reload()) printf("シェーダーを読み直した / shaders reloaded\n"); | ||
| 113 | } | ||
| 161 | if (key == GLFW_KEY_P) { | 114 | if (key == GLFW_KEY_P) { |
| 162 | wireframe = !wireframe; | 115 | wireframe = !wireframe; |
| 163 | // 三角形を線で描く(デバッグに便利) / draw triangles as lines (handy for debugging) | 116 | // 三角形を線で描く(デバッグに便利) / draw triangles as lines (handy for debugging) |
| @@ -193,12 +146,6 @@ int main() { | |||
| 193 | Mesh star = makeStar({0.0f, -0.45f}, 0.3f); | 146 | Mesh star = makeStar({0.0f, -0.45f}, 0.3f); |
| 194 | Mesh ribbon = makeRibbon({0.6f, -0.45f}); | 147 | Mesh ribbon = makeRibbon({0.6f, -0.45f}); |
| 195 | 148 | ||
| 196 | GLuint vs = compileShader(GL_VERTEX_SHADER, kVertexShader); | ||
| 197 | GLuint fs = compileShader(GL_FRAGMENT_SHADER, kFragmentShader); | ||
| 198 | if (!vs || !fs) return 1; | ||
| 199 | GLuint program = linkProgram(vs, fs); | ||
| 200 | if (!program) return 1; | ||
| 201 | |||
| 202 | glPointSize(10.0f); // GL_POINTSの大きさ(ピクセル) / size of GL_POINTS in pixels | 149 | glPointSize(10.0f); // GL_POINTSの大きさ(ピクセル) / size of GL_POINTS in pixels |
| 203 | 150 | ||
| 204 | while (!window.shouldClose()) { | 151 | while (!window.shouldClose()) { |
| @@ -207,17 +154,33 @@ int main() { | |||
| 207 | glClearColor(0.10f, 0.15f, 0.25f, 1.0f); | 154 | glClearColor(0.10f, 0.15f, 0.25f, 1.0f); |
| 208 | glClear(GL_COLOR_BUFFER_BIT); | 155 | glClear(GL_COLOR_BUFFER_BIT); |
| 209 | 156 | ||
| 210 | glUseProgram(program); | 157 | float t = static_cast<float>(window.time()); |
| 158 | const Vec3 white = {1.0f, 1.0f, 1.0f}; | ||
| 159 | |||
| 160 | shader->use(); | ||
| 161 | // フレームに一回:全ての描画で同じ値 / once per frame: the same value for every draw | ||
| 162 | shader->set("uTime", t); | ||
| 163 | |||
| 164 | // 描画ごと:ユニフォームは次に変えるまでプログラムに残る | ||
| 165 | // per draw: a uniform keeps its value in the program until we change it | ||
| 166 | shader->set("uOffset", Vec2{0.0f, 0.0f}); | ||
| 167 | shader->set("uTint", white); | ||
| 211 | triangle.draw(); | 168 | triangle.draw(); |
| 212 | quad.draw(); | ||
| 213 | hexagon.draw(); | ||
| 214 | points.draw(); | 169 | points.draw(); |
| 215 | star.draw(); | 170 | star.draw(); |
| 216 | ribbon.draw(); | 171 | ribbon.draw(); |
| 217 | 172 | ||
| 173 | // 四角形:色が白とオレンジの間で変わる / the quad: colour moves between white and orange | ||
| 174 | float pulse = 0.5f + 0.5f * std::sin(t * 2.0f); | ||
| 175 | shader->set("uTint", lerp(white, Vec3{1.0f, 0.5f, 0.1f}, pulse)); | ||
| 176 | quad.draw(); | ||
| 177 | |||
| 178 | // 六角形:上下に揺れる / the hexagon bobs up and down | ||
| 179 | shader->set("uTint", white); | ||
| 180 | shader->set("uOffset", Vec2{0.0f, 0.1f * std::sin(t * 3.0f)}); | ||
| 181 | hexagon.draw(); | ||
| 182 | |||
| 218 | window.swapBuffers(); | 183 | window.swapBuffers(); |
| 219 | } | 184 | } |
| 220 | 185 | return 0; // シェーダーとメッシュはここで自動的に削除される / the shader and meshes are deleted automatically here | |
| 221 | glDeleteProgram(program); | ||
| 222 | return 0; // メッシュはここで自動的に削除される / the meshes are deleted automatically here | ||
| 223 | } | 186 | } |
ファイル: /dev/null | b/src/shader.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,181 @@ | |||
| 1 | #include "shader.hh" | ||
| 2 | |||
| 3 | #include "file_util.hh" | ||
| 4 | |||
| 5 | #include <cstdio> | ||
| 6 | #include <string_view> | ||
| 7 | #include <utility> | ||
| 8 | |||
| 9 | // コンパイラのログの一行から行番号を探し、位置の部分を取り除いたメッセージをmessageに入れる。行番号がなければ0。 | ||
| 10 | // Mesa: "0:12(5): error: ..." | ||
| 11 | // NVIDIA: "0(12) : error C1008: ..." | ||
| 12 | // AMD/Intel: "ERROR: 0:12: ..." | ||
| 13 | // Finds the line number in one line of the compiler log and stores the message without the location | ||
| 14 | // in message. Returns 0 if there is no line number. | ||
| 15 | static int parseLogLine(std::string_view line, std::string &message) { | ||
| 16 | for (size_t i = 0; i + 2 < line.size(); ++i) { | ||
| 17 | bool startOk = (i == 0 || line[i - 1] == ' '); | ||
| 18 | if (!startOk || line[i] != '0' || (line[i + 1] != ':' && line[i + 1] != '(')) continue; | ||
| 19 | int number = 0; | ||
| 20 | size_t j = i + 2; | ||
| 21 | while (j < line.size() && line[j] >= '0' && line[j] <= '9') number = number * 10 + (line[j++] - '0'); | ||
| 22 | if (j == i + 2) continue; | ||
| 23 | size_t rest = line.find(": ", j); // 位置の後の「: 」 / the ": " after the location | ||
| 24 | rest = rest == std::string_view::npos ? j : rest + 2; | ||
| 25 | message = std::string(line.substr(0, i)) + std::string(line.substr(rest)); | ||
| 26 | return number; | ||
| 27 | } | ||
| 28 | message = std::string(line); | ||
| 29 | return 0; | ||
| 30 | } | ||
| 31 | |||
| 32 | // ソースのn行目(1始まり) / line n of the source (1-based) | ||
| 33 | static std::string_view sourceLine(std::string_view source, int n) { | ||
| 34 | size_t start = 0; | ||
| 35 | for (int i = 1; i < n; ++i) { | ||
| 36 | start = source.find('\n', start); | ||
| 37 | if (start == std::string_view::npos) return {}; | ||
| 38 | ++start; | ||
| 39 | } | ||
| 40 | size_t end = source.find('\n', start); | ||
| 41 | return source.substr(start, end == std::string_view::npos ? std::string_view::npos : end - start); | ||
| 42 | } | ||
| 43 | |||
| 44 | // エラーを「ファイル:行: メッセージ」の形で表示し、その行のソースも見せる | ||
| 45 | // Prints errors as "file:line: message" and shows that source line | ||
| 46 | static void printShaderLog(const std::string &path, std::string_view source, std::string_view log) { | ||
| 47 | while (!log.empty()) { | ||
| 48 | size_t end = log.find('\n'); | ||
| 49 | std::string_view line = log.substr(0, end); | ||
| 50 | log = end == std::string_view::npos ? std::string_view{} : log.substr(end + 1); | ||
| 51 | if (line.empty()) continue; | ||
| 52 | |||
| 53 | std::string message; | ||
| 54 | int n = parseLogLine(line, message); | ||
| 55 | if (n > 0) { | ||
| 56 | std::string_view code = sourceLine(source, n); | ||
| 57 | fprintf(stderr, "%s:%d: %s\n %4d | %.*s\n", path.c_str(), n, message.c_str(), n, static_cast<int>(code.size()), | ||
| 58 | code.data()); | ||
| 59 | } else { | ||
| 60 | fprintf(stderr, "%s: %s\n", path.c_str(), message.c_str()); | ||
| 61 | } | ||
| 62 | } | ||
| 63 | } | ||
| 64 | |||
| 65 | // 一つのステージ(頂点・フラグメント…)をファイルからコンパイル。失敗したら0。 | ||
| 66 | // Compiles one stage (vertex, fragment, ...) from a file. Returns 0 on failure. | ||
| 67 | static GLuint compileStage(GLenum type, const std::string &path) { | ||
| 68 | std::optional<std::string> source = readTextFile(path); | ||
| 69 | if (!source) { | ||
| 70 | fprintf(stderr, "%s: 開けない / cannot open (プロジェクトのルートから実行した? / running from the project root?)\n", | ||
| 71 | path.c_str()); | ||
| 72 | return 0; | ||
| 73 | } | ||
| 74 | GLuint shader = glCreateShader(type); | ||
| 75 | const char *text = source->c_str(); | ||
| 76 | glShaderSource(shader, 1, &text, nullptr); | ||
| 77 | glCompileShader(shader); | ||
| 78 | |||
| 79 | GLint ok = 0; | ||
| 80 | glGetShaderiv(shader, GL_COMPILE_STATUS, &ok); | ||
| 81 | if (!ok) { | ||
| 82 | GLint length = 0; | ||
| 83 | glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &length); | ||
| 84 | std::string log(static_cast<size_t>(length > 1 ? length : 1), '\0'); | ||
| 85 | glGetShaderInfoLog(shader, length, nullptr, log.data()); | ||
| 86 | printShaderLog(path, *source, log.c_str()); | ||
| 87 | glDeleteShader(shader); | ||
| 88 | return 0; | ||
| 89 | } | ||
| 90 | return shader; | ||
| 91 | } | ||
| 92 | |||
| 93 | // 頂点とフラグメントをリンク。失敗したら0。 / links a vertex and a fragment shader. Returns 0 on failure. | ||
| 94 | static GLuint buildProgram(const std::string &vertexPath, const std::string &fragmentPath) { | ||
| 95 | GLuint vs = compileStage(GL_VERTEX_SHADER, vertexPath); | ||
| 96 | GLuint fs = compileStage(GL_FRAGMENT_SHADER, fragmentPath); | ||
| 97 | if (!vs || !fs) { | ||
| 98 | glDeleteShader(vs); // 0は無視される / 0 is silently ignored | ||
| 99 | glDeleteShader(fs); | ||
| 100 | return 0; | ||
| 101 | } | ||
| 102 | GLuint program = glCreateProgram(); | ||
| 103 | glAttachShader(program, vs); | ||
| 104 | glAttachShader(program, fs); | ||
| 105 | glLinkProgram(program); | ||
| 106 | glDetachShader(program, vs); | ||
| 107 | glDetachShader(program, fs); | ||
| 108 | glDeleteShader(vs); | ||
| 109 | glDeleteShader(fs); | ||
| 110 | |||
| 111 | GLint ok = 0; | ||
| 112 | glGetProgramiv(program, GL_LINK_STATUS, &ok); | ||
| 113 | if (!ok) { | ||
| 114 | char log[4096]; | ||
| 115 | glGetProgramInfoLog(program, sizeof log, nullptr, log); | ||
| 116 | fprintf(stderr, "%s + %s: リンクエラー / link error:\n%s\n", vertexPath.c_str(), fragmentPath.c_str(), log); | ||
| 117 | glDeleteProgram(program); | ||
| 118 | return 0; | ||
| 119 | } | ||
| 120 | return program; | ||
| 121 | } | ||
| 122 | |||
| 123 | std::optional<Shader> Shader::load(const std::string &vertexPath, const std::string &fragmentPath) { | ||
| 124 | GLuint program = buildProgram(vertexPath, fragmentPath); | ||
| 125 | if (!program) return std::nullopt; | ||
| 126 | Shader shader; | ||
| 127 | shader.program = program; | ||
| 128 | shader.vertexPath = vertexPath; | ||
| 129 | shader.fragmentPath = fragmentPath; | ||
| 130 | return shader; | ||
| 131 | } | ||
| 132 | |||
| 133 | bool Shader::reload() { | ||
| 134 | GLuint fresh = buildProgram(vertexPath, fragmentPath); | ||
| 135 | if (!fresh) return false; // 古いプログラムを残す / keep the old program | ||
| 136 | glDeleteProgram(program); | ||
| 137 | program = fresh; | ||
| 138 | warned.clear(); | ||
| 139 | return true; | ||
| 140 | } | ||
| 141 | |||
| 142 | Shader::~Shader() { | ||
| 143 | if (program) glDeleteProgram(program); | ||
| 144 | } | ||
| 145 | |||
| 146 | Shader::Shader(Shader &&other) noexcept | ||
| 147 | : program(std::exchange(other.program, 0)), vertexPath(std::move(other.vertexPath)), | ||
| 148 | fragmentPath(std::move(other.fragmentPath)), warned(std::move(other.warned)) {} | ||
| 149 | |||
| 150 | Shader &Shader::operator=(Shader &&other) noexcept { | ||
| 151 | if (this != &other) { | ||
| 152 | if (program) glDeleteProgram(program); | ||
| 153 | program = std::exchange(other.program, 0); | ||
| 154 | vertexPath = std::move(other.vertexPath); | ||
| 155 | fragmentPath = std::move(other.fragmentPath); | ||
| 156 | warned = std::move(other.warned); | ||
| 157 | } | ||
| 158 | return *this; | ||
| 159 | } | ||
| 160 | |||
| 161 | GLint Shader::location(const char *name) const { | ||
| 162 | GLint loc = glGetUniformLocation(program, name); | ||
| 163 | // -1:名前の間違い、または使われていないので最適化で消された | ||
| 164 | // -1: a typo, or the uniform is unused and the compiler removed it | ||
| 165 | if (loc < 0 && warned.insert(name).second) | ||
| 166 | fprintf(stderr, "%s + %s: ユニフォーム「%s」がない / no active uniform \"%s\"\n", vertexPath.c_str(), | ||
| 167 | fragmentPath.c_str(), name, name); | ||
| 168 | return loc; | ||
| 169 | } | ||
| 170 | |||
| 171 | // location が -1 なら glProgramUniform* は何もしない / with location -1, glProgramUniform* does nothing | ||
| 172 | void Shader::set(const char *name, int value) const { glProgramUniform1i(program, location(name), value); } | ||
| 173 | void Shader::set(const char *name, float value) const { glProgramUniform1f(program, location(name), value); } | ||
| 174 | void Shader::set(const char *name, Vec2 v) const { glProgramUniform2f(program, location(name), v.x, v.y); } | ||
| 175 | void Shader::set(const char *name, Vec3 v) const { glProgramUniform3f(program, location(name), v.x, v.y, v.z); } | ||
| 176 | void Shader::set(const char *name, Vec4 v) const { glProgramUniform4f(program, location(name), v.x, v.y, v.z, v.w); } | ||
| 177 | |||
| 178 | void Shader::set(const char *name, const Mat4 &m) const { | ||
| 179 | // linalg.hhは列優先なので転置しない(GL_FALSE) / linalg.hh is column-major, so no transpose (GL_FALSE) | ||
| 180 | glProgramUniformMatrix4fv(program, location(name), 1, GL_FALSE, &m.c[0].x); | ||
| 181 | } | ||
ファイル: /dev/null | b/src/shader.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,48 @@ | |||
| 1 | // シェーダープログラム / a shader program | ||
| 2 | #pragma once | ||
| 3 | |||
| 4 | #include <glad/glad.h> | ||
| 5 | #include <linalg.hh> | ||
| 6 | |||
| 7 | #include <optional> | ||
| 8 | #include <string> | ||
| 9 | #include <unordered_set> | ||
| 10 | |||
| 11 | // ファイルから読み込んだシェーダープログラム(RAII、コピー不可・移動可)。 | ||
| 12 | // A shader program loaded from files (RAII, non-copyable, movable). | ||
| 13 | class Shader { | ||
| 14 | public: | ||
| 15 | Shader() = default; | ||
| 16 | ~Shader(); | ||
| 17 | Shader(const Shader &) = delete; | ||
| 18 | Shader &operator=(const Shader &) = delete; | ||
| 19 | Shader(Shader &&other) noexcept; | ||
| 20 | Shader &operator=(Shader &&other) noexcept; | ||
| 21 | |||
| 22 | // 頂点・フラグメントシェーダーのファイルから作る。失敗したらエラーを表示してstd::nullopt。 | ||
| 23 | // Builds a program from vertex and fragment shader files. On failure prints the errors and returns std::nullopt. | ||
| 24 | static std::optional<Shader> load(const std::string &vertexPath, const std::string &fragmentPath); | ||
| 25 | |||
| 26 | // ファイルを読み直す。失敗したら古いプログラムをそのまま使い続け、falseを返す。 | ||
| 27 | // Re-reads the files. On failure keeps using the old program and returns false. | ||
| 28 | bool reload(); | ||
| 29 | |||
| 30 | void use() const { glUseProgram(program); } | ||
| 31 | GLuint id() const { return program; } | ||
| 32 | |||
| 33 | // ユニフォームを設定(DSA:glProgramUniform*なので use() は不要) | ||
| 34 | // Set uniforms (DSA: glProgramUniform*, so use() is not needed) | ||
| 35 | void set(const char *name, int value) const; | ||
| 36 | void set(const char *name, float value) const; | ||
| 37 | void set(const char *name, Vec2 value) const; | ||
| 38 | void set(const char *name, Vec3 value) const; | ||
| 39 | void set(const char *name, Vec4 value) const; | ||
| 40 | void set(const char *name, const Mat4 &value) const; | ||
| 41 | |||
| 42 | private: | ||
| 43 | GLint location(const char *name) const; | ||
| 44 | |||
| 45 | GLuint program = 0; | ||
| 46 | std::string vertexPath, fragmentPath; | ||
| 47 | mutable std::unordered_set<std::string> warned; // 見つからない名前は一度だけ警告 / warn once per missing name | ||
| 48 | }; | ||
コメント(0)
まだコメントはありません。
ログインするとコメント出来ます。