diff --git a/CMakeLists.txt b/CMakeLists.txt index 03bec6c..ae113a6 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -22,7 +22,9 @@ target_include_directories(glad PUBLIC external/glad/include) add_executable(game src/main.cc src/window.cc - src/gl_debug.cc) + src/gl_debug.cc + src/buffer.cc + src/mesh.cc) target_include_directories(game PRIVATE src external/stb external/linalg) target_link_libraries(game PRIVATE glad glfw) diff --git a/src/buffer.cc b/src/buffer.cc new file mode 100644 index 0000000..7c3ba57 --- /dev/null +++ b/src/buffer.cc @@ -0,0 +1,25 @@ +#include "buffer.hh" + +#include + +Buffer::Buffer(const void *data, GLsizeiptr byteCount, GLbitfield flags) : bytes(byteCount) { + glCreateBuffers(1, &handle); + glNamedBufferStorage(handle, byteCount, data, flags); +} + +Buffer::~Buffer() { + if (handle) glDeleteBuffers(1, &handle); +} + +// 移動したら元のオブジェクトは空(0)になる / a moved-from object becomes empty (0) +Buffer::Buffer(Buffer &&other) noexcept + : handle(std::exchange(other.handle, 0)), bytes(std::exchange(other.bytes, 0)) {} + +Buffer &Buffer::operator=(Buffer &&other) noexcept { + if (this != &other) { + if (handle) glDeleteBuffers(1, &handle); + handle = std::exchange(other.handle, 0); + bytes = std::exchange(other.bytes, 0); + } + return *this; +} diff --git a/src/buffer.hh b/src/buffer.hh new file mode 100644 index 0000000..b859176 --- /dev/null +++ b/src/buffer.hh @@ -0,0 +1,27 @@ +// GPUのバッファ / a GPU buffer +#pragma once + +#include + +// バッファオブジェクト(RAII、コピー不可・移動可)。 +// A buffer object (RAII, non-copyable, movable). +class Buffer { +public: + Buffer() = default; + // 不変ストレージ(glNamedBufferStorage)を作ってdataをコピーする。flags=0なら後から書き換えられない。 + // Creates immutable storage (glNamedBufferStorage) and copies data in. flags = 0: cannot be updated later. + Buffer(const void *data, GLsizeiptr byteCount, GLbitfield flags = 0); + ~Buffer(); + + Buffer(const Buffer &) = delete; + Buffer &operator=(const Buffer &) = delete; + Buffer(Buffer &&other) noexcept; + Buffer &operator=(Buffer &&other) noexcept; + + GLuint id() const { return handle; } + GLsizeiptr size() const { return bytes; } + +private: + GLuint handle = 0; + GLsizeiptr bytes = 0; +}; diff --git a/src/main.cc b/src/main.cc index 3bdaa14..4d7fc86 100644 --- a/src/main.cc +++ b/src/main.cc @@ -1,29 +1,50 @@ -// 第3章:こんにちは三角形 -// Chapter 3: Hello Triangle +// 第4章:頂点属性とインデックスバッファ +// Chapter 4: vertex attributes and index buffers +// +// 操作 / Controls: P ワイヤーフレーム切り替え / toggle wireframe, Esc 終了 / quit +#include "mesh.hh" #include "window.hh" +#include + +#include +#include #include -#include +#include + +// 位置と色を交互に並べた(インターリーブ)頂点 / a vertex with position and colour interleaved +struct ColorVertex { + Vec3 position; + Vec3 color; +}; + +// この形式をVAOに教える / tells the VAO about this format +constexpr VertexAttrib kColorVertexLayout[] = { + {0, 3, offsetof(ColorVertex, position)}, // layout(location = 0) in vec3 aPosition + {1, 3, offsetof(ColorVertex, color)}, // layout(location = 1) in vec3 aColor +}; -// 頂点シェーダー:頂点ごとに一回実行される / vertex shader: runs once per vertex static const char *kVertexShader = R"(#version 460 core layout(location = 0) in vec3 aPosition; +layout(location = 1) in vec3 aColor; + +out vec3 vColor; // フラグメントシェーダーへ(補間される) / to the fragment shader (interpolated) void main() { - gl_Position = vec4(aPosition, 1.0); // 座標はそのままNDC / the position is already in NDC + vColor = aColor; + gl_Position = vec4(aPosition, 1.0); } )"; -// フラグメントシェーダー:ピクセルごとに一回実行される / fragment shader: runs once per pixel static const char *kFragmentShader = R"(#version 460 core +in vec3 vColor; layout(location = 0) out vec4 out_color; void main() { - out_color = vec4(1.0, 0.55, 0.15, 1.0); // オレンジ / orange + out_color = vec4(vColor, 1.0); } )"; -// シェーダーを一つコンパイル。失敗したら0。 / compile one shader stage. Returns 0 on failure. static GLuint compileShader(GLenum type, const char *source) { GLuint shader = glCreateShader(type); glShaderSource(shader, 1, &source, nullptr); @@ -42,14 +63,11 @@ static GLuint compileShader(GLenum type, const char *source) { return shader; } -// 二つのシェーダーをプログラムにリンク。失敗したら0。 / link two shaders into a program. Returns 0 on failure. static GLuint linkProgram(GLuint vertexShader, GLuint fragmentShader) { GLuint program = glCreateProgram(); glAttachShader(program, vertexShader); glAttachShader(program, fragmentShader); glLinkProgram(program); - - // リンク後はシェーダーオブジェクトは要らない / the shader objects are not needed after linking glDetachShader(program, vertexShader); glDetachShader(program, fragmentShader); glDeleteShader(vertexShader); @@ -67,75 +85,113 @@ static GLuint linkProgram(GLuint vertexShader, GLuint fragmentShader) { return program; } -struct TriangleObjects { - GLuint vao = 0; // 頂点配列オブジェクト / vertex array object - GLuint vbo = 0; // 頂点バッファ / vertex buffer -}; +// NDCは横に引き伸ばされる(1280×720)ので、計算で作る図形はxを縮める。第8章で投影行列が解決する。 +// NDC is stretched horizontally (1280×720), so generated shapes shrink x. Chapter 8's projection fixes this. +constexpr float kAspectFix = 720.0f / 1280.0f; -// DSA方式(OpenGL 4.5):オブジェクトの名前を直接渡して編集する -// DSA style (OpenGL 4.5): edit objects by passing their name directly -static TriangleObjects createTriangleDsa(const float *vertices, GLsizeiptr bytes) { - TriangleObjects t; - glCreateBuffers(1, &t.vbo); - glNamedBufferStorage(t.vbo, bytes, vertices, 0); // 0 = 後から書き換えない / 0 = never updated later - - glCreateVertexArrays(1, &t.vao); - // バインディング0にバッファを繋ぐ:オフセット0、一頂点あたり3つのfloat - // attach the buffer to binding 0: offset 0, 3 floats per vertex - glVertexArrayVertexBuffer(t.vao, 0, t.vbo, 0, 3 * sizeof(float)); - // 属性0 = vec3のfloat、頂点の先頭から0バイト、バインディング0から読む - // attribute 0 = vec3 of floats, 0 bytes into the vertex, read from binding 0 - glEnableVertexArrayAttrib(t.vao, 0); - glVertexArrayAttribFormat(t.vao, 0, 3, GL_FLOAT, GL_FALSE, 0); - glVertexArrayAttribBinding(t.vao, 0, 0); - return t; +// 色相(0〜1)から鮮やかな色 / a saturated colour from a hue in 0..1 +static Vec3 hueColor(float h) { + auto channel = [h](float offset) { + return 0.5f + 0.5f * std::cos(2.0f * PI * (h + offset)); + }; + return {channel(0.0f), channel(2.0f / 3.0f), channel(1.0f / 3.0f)}; } -// 古い方式:バインドしてから「今バインドされているもの」を編集する(多くの古いチュートリアル) -// Classic style: bind, then edit "whatever is bound" (most older tutorials) -static TriangleObjects createTriangleClassic(const float *vertices, GLsizeiptr bytes) { - TriangleObjects t; - glGenVertexArrays(1, &t.vao); - glBindVertexArray(t.vao); - - glGenBuffers(1, &t.vbo); - glBindBuffer(GL_ARRAY_BUFFER, t.vbo); - glBufferData(GL_ARRAY_BUFFER, bytes, vertices, GL_STATIC_DRAW); +// 中心+周りの頂点で正多角形。インデックスで中心を共有する。 +// A regular polygon from a centre plus a ring of vertices. The indices share the centre vertex. +static Mesh makePolygon(Vec2 center, float radius, int sides) { + std::vector vertices = {{{center.x, center.y, 0.0f}, {1.0f, 1.0f, 1.0f}}}; + std::vector indices; + for (int i = 0; i < sides; ++i) { + float a = 2.0f * PI * static_cast(i) / static_cast(sides); + vertices.push_back({{center.x + radius * kAspectFix * std::cos(a), center.y + radius * std::sin(a), 0.0f}, + hueColor(static_cast(i) / static_cast(sides))}); + std::uint32_t current = static_cast(i + 1); + std::uint32_t next = static_cast((i + 1) % sides + 1); + indices.insert(indices.end(), {0, current, next}); // 三角形一つ / one triangle + } + return Mesh(vertices, indices, kColorVertexLayout); +} - // 今GL_ARRAY_BUFFERにバインドされているバッファが属性0に記録される - // the buffer currently bound to GL_ARRAY_BUFFER is recorded for attribute 0 - glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), nullptr); - glEnableVertexAttribArray(0); +// 5×3の点 / a 5×3 grid of points +static Mesh makePoints(Vec2 center) { + std::vector vertices; + for (int y = 0; y < 3; ++y) + for (int x = 0; x < 5; ++x) + vertices.push_back({{center.x + (static_cast(x) - 2.0f) * 0.07f, center.y + (static_cast(y) - 1.0f) * 0.12f, 0.0f}, + hueColor(static_cast(x + 5 * y) / 15.0f)}); + return Mesh(vertices, {}, kColorVertexLayout, GL_POINTS); +} - glBindVertexArray(0); // 後で誤って変更しないように外す / unbind so it is not changed by accident - return t; +// 星形の線(GL_LINE_LOOPは最後の頂点と最初を繋ぐ) / a star outline (GL_LINE_LOOP joins the last vertex to the first) +static Mesh makeStar(Vec2 center, float radius) { + std::vector vertices; + for (int i = 0; i < 10; ++i) { + float a = PI * 0.5f + PI * static_cast(i) / 5.0f; + float r = (i % 2 == 0) ? radius : radius * 0.4f; + vertices.push_back({{center.x + r * kAspectFix * std::cos(a), center.y + r * std::sin(a), 0.0f}, + hueColor(static_cast(i) / 10.0f)}); + } + return Mesh(vertices, {}, kColorVertexLayout, GL_LINE_LOOP); } -int main(int argc, char **argv) { - // 「./build/game --classic」で古い「バインドして編集」方式でVAOを作る(結果は同じ) - // "./build/game --classic" builds the VAO with the classic bind-to-edit style (same result) - bool classic = argc > 1 && std::string_view(argv[1]) == "--classic"; +// 波打つリボン(GL_TRIANGLE_STRIPは頂点を一つ足すごとに三角形が一つ増える) +// A wavy ribbon (GL_TRIANGLE_STRIP: every extra vertex adds one triangle) +static Mesh makeRibbon(Vec2 center) { + std::vector vertices; + for (int i = 0; i < 10; ++i) { + float t = static_cast(i) / 9.0f; + float x = center.x + (t - 0.5f) * 0.45f; + float wave = 0.08f * std::sin(t * 2.0f * PI); + Vec3 color = hueColor(t * 0.5f); + vertices.push_back({{x, center.y + wave - 0.08f, 0.0f}, color}); + vertices.push_back({{x, center.y + wave + 0.08f, 0.0f}, 0.6f * color}); + } + return Mesh(vertices, {}, kColorVertexLayout, GL_TRIANGLE_STRIP); +} +int main() { Window window; - if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 3")) return 1; + if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 4")) return 1; + + bool wireframe = false; window.onKey = [&](int key, int action, int /*mods*/) { - if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) window.close(); + if (action != GLFW_PRESS) return; + if (key == GLFW_KEY_ESCAPE) window.close(); + if (key == GLFW_KEY_P) { + wireframe = !wireframe; + // 三角形を線で描く(デバッグに便利) / draw triangles as lines (handy for debugging) + glPolygonMode(GL_FRONT_AND_BACK, wireframe ? GL_LINE : GL_FILL); + } }; - // 三角形の頂点(NDC:x, yは-1〜1) / triangle vertices (NDC: x and y in -1..1) - const float vertices[] = { - -0.5f, -0.5f, 0.0f, // 左下 / bottom left - 0.5f, -0.5f, 0.0f, // 右下 / bottom right - 0.0f, 0.5f, 0.0f, // 上 / top + // 1. 色付きの三角形:色は三角形の中で補間される / a coloured triangle: colours are interpolated inside it + std::vector triangleVertices = { + {{-0.85f, 0.20f, 0.0f}, {1.0f, 0.0f, 0.0f}}, // 赤 / red + {{-0.35f, 0.20f, 0.0f}, {0.0f, 1.0f, 0.0f}}, // 緑 / green + {{-0.60f, 0.75f, 0.0f}, {0.0f, 0.0f, 1.0f}}, // 青 / blue + }; + Mesh triangle(triangleVertices, {}, kColorVertexLayout); + + // 2. 四角形:頂点4つ+インデックス6つ(三角形2つが2頂点を共有) + // A quad: 4 vertices + 6 indices (the two triangles share 2 vertices) + std::vector quadVertices = { + {{-0.14f, 0.20f, 0.0f}, {1.0f, 0.8f, 0.2f}}, // 0 左下 / bottom left + {{ 0.14f, 0.20f, 0.0f}, {1.0f, 0.3f, 0.3f}}, // 1 右下 / bottom right + {{ 0.14f, 0.70f, 0.0f}, {0.6f, 0.2f, 0.8f}}, // 2 右上 / top right + {{-0.14f, 0.70f, 0.0f}, {0.2f, 0.6f, 1.0f}}, // 3 左上 / top left + }; + std::vector quadIndices = { + 0, 1, 2, // 一つ目の三角形 / first triangle + 2, 3, 0, // 二つ目の三角形 / second triangle }; + Mesh quad(quadVertices, quadIndices, kColorVertexLayout); - TriangleObjects triangle; - if (classic) { - printf("classic bind-to-edit style\n"); - triangle = createTriangleClassic(vertices, sizeof vertices); - } else { - triangle = createTriangleDsa(vertices, sizeof vertices); - } + // 3〜6. 計算で作る図形(VAOはそれぞれ別) / generated shapes (each has its own VAO) + Mesh hexagon = makePolygon({0.6f, 0.45f}, 0.27f, 6); + Mesh points = makePoints({-0.6f, -0.45f}); + Mesh star = makeStar({0.0f, -0.45f}, 0.3f); + Mesh ribbon = makeRibbon({0.6f, -0.45f}); GLuint vs = compileShader(GL_VERTEX_SHADER, kVertexShader); GLuint fs = compileShader(GL_FRAGMENT_SHADER, kFragmentShader); @@ -143,22 +199,25 @@ int main(int argc, char **argv) { GLuint program = linkProgram(vs, fs); if (!program) return 1; + glPointSize(10.0f); // GL_POINTSの大きさ(ピクセル) / size of GL_POINTS in pixels + while (!window.shouldClose()) { window.pollEvents(); glClearColor(0.10f, 0.15f, 0.25f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); - glUseProgram(program); // このシェーダーで描く / draw with this shader - glBindVertexArray(triangle.vao); // この頂点データで描く / draw with this vertex data - glDrawArrays(GL_TRIANGLES, 0, 3); // 頂点0から3つ = 三角形1つ / 3 vertices from vertex 0 = one triangle + glUseProgram(program); + triangle.draw(); + quad.draw(); + hexagon.draw(); + points.draw(); + star.draw(); + ribbon.draw(); window.swapBuffers(); } - // ウィンドウ(コンテキスト)より先に削除する / delete before the window (context) goes away glDeleteProgram(program); - glDeleteVertexArrays(1, &triangle.vao); - glDeleteBuffers(1, &triangle.vbo); - return 0; + return 0; // メッシュはここで自動的に削除される / the meshes are deleted automatically here } diff --git a/src/mesh.cc b/src/mesh.cc new file mode 100644 index 0000000..df3d988 --- /dev/null +++ b/src/mesh.cc @@ -0,0 +1,58 @@ +#include "mesh.hh" + +#include + +Mesh::Mesh(const void *vertexData, GLsizeiptr vertexBytes, GLsizei stride, GLsizei numVertices, + const std::vector &indices, std::span layout, GLenum mode) + : vertexBuffer(vertexData, vertexBytes), vertexCount(numVertices), + indexCount(static_cast(indices.size())), primitive(mode) { + glCreateVertexArrays(1, &vertexArray); + + // 頂点バッファをバインディング0に繋ぐ / attach the vertex buffer to binding 0 + glVertexArrayVertexBuffer(vertexArray, 0, vertexBuffer.id(), 0, stride); + + // 各属性の形式と、どのバインディングから読むか / each attribute's format and which binding it reads + for (const VertexAttrib &a : layout) { + glEnableVertexArrayAttrib(vertexArray, a.location); + glVertexArrayAttribFormat(vertexArray, a.location, a.components, a.type, a.normalized, a.offset); + glVertexArrayAttribBinding(vertexArray, a.location, 0); + } + + // インデックスバッファはVAOに一つだけ / a VAO has exactly one index buffer + if (!indices.empty()) { + indexBuffer = Buffer(indices.data(), static_cast(indices.size() * sizeof(std::uint32_t))); + glVertexArrayElementBuffer(vertexArray, indexBuffer.id()); + } +} + +Mesh::~Mesh() { + if (vertexArray) glDeleteVertexArrays(1, &vertexArray); +} + +Mesh::Mesh(Mesh &&other) noexcept + : vertexArray(std::exchange(other.vertexArray, 0)), vertexBuffer(std::move(other.vertexBuffer)), + indexBuffer(std::move(other.indexBuffer)), vertexCount(other.vertexCount), indexCount(other.indexCount), + primitive(other.primitive) {} + +Mesh &Mesh::operator=(Mesh &&other) noexcept { + if (this != &other) { + if (vertexArray) glDeleteVertexArrays(1, &vertexArray); + vertexArray = std::exchange(other.vertexArray, 0); + vertexBuffer = std::move(other.vertexBuffer); + indexBuffer = std::move(other.indexBuffer); + vertexCount = other.vertexCount; + indexCount = other.indexCount; + primitive = other.primitive; + } + return *this; +} + +void Mesh::draw() const { + glBindVertexArray(vertexArray); + if (indexCount > 0) { + // インデックスで頂点を選ぶ / pick vertices through the indices + glDrawElements(primitive, indexCount, GL_UNSIGNED_INT, nullptr); + } else { + glDrawArrays(primitive, 0, vertexCount); + } +} diff --git a/src/mesh.hh b/src/mesh.hh new file mode 100644 index 0000000..d00ee20 --- /dev/null +++ b/src/mesh.hh @@ -0,0 +1,56 @@ +// メッシュ:頂点配列オブジェクト+頂点バッファ+インデックスバッファ +// Mesh: a vertex array object + vertex buffer + index buffer +#pragma once + +#include "buffer.hh" + +#include +#include +#include + +// 頂点属性一つの説明(DSAのglVertexArrayAttribFormatに渡す内容)。 +// 頂点の形式はこれの配列で表す(例:constexpr VertexAttrib kLayout[] = {...}) +// Describes one vertex attribute (what glVertexArrayAttribFormat needs). +// A vertex format is an array of these (e.g. constexpr VertexAttrib kLayout[] = {...}) +struct VertexAttrib { + GLuint location; // シェーダーの layout(location = N) / the shader's layout(location = N) + GLint components; // 成分の数(vec3なら3) / number of components (3 for a vec3) + GLuint offset; // 頂点の先頭からのバイト数(offsetof) / bytes from the vertex start (offsetof) + GLenum type = GL_FLOAT; // 成分の型 / component type + GLboolean normalized = GL_FALSE; // 整数を0〜1にするか / map integers to 0..1? +}; + +// 一つの描画単位(RAII、コピー不可・移動可)。インデックスが空ならglDrawArraysで描く。 +// One drawable unit (RAII, non-copyable, movable). With no indices it draws with glDrawArrays. +class Mesh { +public: + Mesh() = default; + + // 任意の頂点構造体の配列から作る / build from an array of any vertex struct + template + Mesh(const std::vector &vertices, const std::vector &indices, + std::span layout, GLenum mode = GL_TRIANGLES) + : Mesh(vertices.data(), static_cast(vertices.size() * sizeof(Vertex)), + static_cast(sizeof(Vertex)), static_cast(vertices.size()), indices, layout, mode) {} + + ~Mesh(); + Mesh(const Mesh &) = delete; + Mesh &operator=(const Mesh &) = delete; + Mesh(Mesh &&other) noexcept; + Mesh &operator=(Mesh &&other) noexcept; + + void draw() const; + + GLuint vao() const { return vertexArray; } + +private: + Mesh(const void *vertexData, GLsizeiptr vertexBytes, GLsizei stride, GLsizei numVertices, + const std::vector &indices, std::span layout, GLenum mode); + + GLuint vertexArray = 0; + Buffer vertexBuffer; + Buffer indexBuffer; + GLsizei vertexCount = 0; + GLsizei indexCount = 0; + GLenum primitive = GL_TRIANGLES; // GL_TRIANGLES, GL_LINES, GL_POINTS… +};