diff --git a/CMakeLists.txt b/CMakeLists.txt index eb822bf..03bec6c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -19,7 +19,10 @@ endif() add_library(glad STATIC external/glad/src/glad.c) target_include_directories(glad PUBLIC external/glad/include) -add_executable(game src/main.cc) +add_executable(game + src/main.cc + src/window.cc + src/gl_debug.cc) target_include_directories(game PRIVATE src external/stb external/linalg) target_link_libraries(game PRIVATE glad glfw) diff --git a/src/gl_debug.cc b/src/gl_debug.cc new file mode 100644 index 0000000..19f9df4 --- /dev/null +++ b/src/gl_debug.cc @@ -0,0 +1,63 @@ +#include "gl_debug.hh" + +#include + +#include + +static const char *sourceName(GLenum source) { + switch (source) { + case GL_DEBUG_SOURCE_API: return "API"; + case GL_DEBUG_SOURCE_WINDOW_SYSTEM: return "window system"; + case GL_DEBUG_SOURCE_SHADER_COMPILER: return "shader compiler"; + case GL_DEBUG_SOURCE_THIRD_PARTY: return "third party"; + case GL_DEBUG_SOURCE_APPLICATION: return "application"; + default: return "other"; + } +} + +static const char *typeName(GLenum type) { + switch (type) { + case GL_DEBUG_TYPE_ERROR: return "ERROR"; + case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR: return "DEPRECATED"; + case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR: return "UNDEFINED"; + case GL_DEBUG_TYPE_PORTABILITY: return "PORTABILITY"; + case GL_DEBUG_TYPE_PERFORMANCE: return "PERFORMANCE"; + case GL_DEBUG_TYPE_MARKER: return "MARKER"; + default: return "OTHER"; + } +} + +static const char *severityName(GLenum severity) { + switch (severity) { + case GL_DEBUG_SEVERITY_HIGH: return "high"; + case GL_DEBUG_SEVERITY_MEDIUM: return "medium"; + case GL_DEBUG_SEVERITY_LOW: return "low"; + default: return "notification"; + } +} + +// ドライバーがエラーや警告を見つけるたびに呼ばれる / called whenever the driver finds an error or warning +static void APIENTRY debugCallback(GLenum source, GLenum type, GLuint id, GLenum severity, + GLsizei /*length*/, const GLchar *message, const void * /*user*/) { + // NVIDIAのよくある情報メッセージは無視 / ignore common NVIDIA info messages + if (id == 131169 || id == 131185 || id == 131204 || id == 131218) return; + // シェーダーのエラーはファイル名付きで自分で表示する / we print shader errors ourselves, with file names + if (source == GL_DEBUG_SOURCE_SHADER_COMPILER) return; + fprintf(stderr, "[GL %s] (%s, %s, id %u) %s\n", typeName(type), sourceName(source), severityName(severity), id, + message); +} + +bool enableGlDebugOutput() { + GLint flags = 0; + glGetIntegerv(GL_CONTEXT_FLAGS, &flags); + if (!(flags & GL_CONTEXT_FLAG_DEBUG_BIT)) { + fprintf(stderr, "デバッグコンテキストではない / not a debug context: no GL debug output\n"); + return false; + } + glEnable(GL_DEBUG_OUTPUT); + glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS); // エラーを起こした関数の中で呼ぶ / call back inside the failing function + glDebugMessageCallback(debugCallback, nullptr); + // 「通知」レベルは多すぎるので切る / turn off the (very chatty) notification level + glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DEBUG_SEVERITY_NOTIFICATION, 0, nullptr, GL_FALSE); + return true; +} diff --git a/src/gl_debug.hh b/src/gl_debug.hh new file mode 100644 index 0000000..73fb0c8 --- /dev/null +++ b/src/gl_debug.hh @@ -0,0 +1,6 @@ +// OpenGLのデバッグ出力 / OpenGL debug output +#pragma once + +// デバッグコンテキストならglDebugMessageCallbackでロガーを登録する。登録できたらtrue。 +// On a debug context, installs a logger with glDebugMessageCallback. Returns true if installed. +bool enableGlDebugOutput(); diff --git a/src/main.cc b/src/main.cc index d28637d..331f1e5 100644 --- a/src/main.cc +++ b/src/main.cc @@ -1,63 +1,105 @@ -// 第1章:ウィンドウを開いて色で塗りつぶす -// Chapter 1: open a window and clear it to a colour - -#ifdef _WIN32 -// SetConsoleOutputCPの為。GLADより先にインクルードする(APIENTRYの二重定義を防ぐ) -// For SetConsoleOutputCP. Include it before GLAD (so APIENTRY is not defined twice) -#define WIN32_LEAN_AND_MEAN -#define NOMINMAX -#include -#endif -// GLADはGLFWより先にインクルードする / include GLAD before GLFW -#include -#include +// 第2章:ウィンドウ、レンダーループ、入力 +// Chapter 2: windows, the render loop and input +// +// 操作 / Controls: +// マウス移動 / move the mouse 色相と明るさ / hue and brightness +// ホイール / scroll wheel 彩度 / saturation +// ←/→ を押し続ける / hold ←/→ 色相を回す / rotate the hue +// スペースを押し続ける / hold Space 色を反転 / invert the colour +// V 垂直同期の切り替え / toggle vsync +// E わざとGLエラーを起こす / cause a GL error on purpose +// Esc 終了 / quit +#include "window.hh" +#include +#include #include +// HSV(各0〜1)からRGBへ / HSV (each 0..1) to RGB +static void hsvToRgb(float h, float s, float v, float &r, float &g, float &b) { + h = (h - std::floor(h)) * 6.0f; // 0〜6 / 0..6 + float c = v * s; + float x = c * (1.0f - std::fabs(std::fmod(h, 2.0f) - 1.0f)); + float m = v - c; + int sector = static_cast(h) % 6; + float rgb[6][3] = {{c, x, 0}, {x, c, 0}, {0, c, x}, {0, x, c}, {x, 0, c}, {c, 0, x}}; + r = rgb[sector][0] + m; + g = rgb[sector][1] + m; + b = rgb[sector][2] + m; +} + int main() { -#ifdef _WIN32 - // コンソールの出力をUTF-8にする(日本語のメッセージが文字化けしない様に) - // switch the console output to UTF-8 (so the Japanese messages are not garbled) - SetConsoleOutputCP(CP_UTF8); -#endif - // GLFWを初期化 / initialise GLFW - if (!glfwInit()) { - fprintf(stderr, "GLFWの初期化に失敗 / failed to initialise GLFW\n"); - return 1; - } + Window window; + if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 2")) return 1; - // OpenGL 4.6 コアプロファイルを要求 / ask for an OpenGL 4.6 core profile context - glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); - glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 6); - glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); + float hue = 0.6f, saturation = 0.6f, value = 0.35f; - GLFWwindow *window = glfwCreateWindow(1280, 720, "OpenGL Tutorial - Chapter 1", nullptr, nullptr); - if (!window) { - fprintf(stderr, "ウィンドウの作成に失敗 / failed to create the window (OpenGL 4.6 not supported?)\n"); - glfwTerminate(); - return 1; - } - glfwMakeContextCurrent(window); + // コールバック:イベントが起きた時に一度だけ呼ばれる / callbacks: called once when an event happens + window.onKey = [&](int key, int action, int /*mods*/) { + if (action != GLFW_PRESS) return; + if (key == GLFW_KEY_ESCAPE) window.close(); + if (key == GLFW_KEY_V) { + window.setVsync(!window.vsync()); + printf("vsync %s\n", window.vsync() ? "on" : "off"); + } + if (key == GLFW_KEY_E) { + // コアプロファイルにGL_TEXTURE_2Dの有効化はない → GL_INVALID_ENUM + // the core profile has no glEnable(GL_TEXTURE_2D) → GL_INVALID_ENUM + glEnable(GL_TEXTURE_2D); + } + }; + window.onCursorPos = [&](double x, double y) { + hue = static_cast(x) / static_cast(window.width()); + value = 1.0f - static_cast(y) / static_cast(window.height()); + }; + window.onScroll = [&](double /*dx*/, double dy) { + saturation = std::clamp(saturation + 0.05f * static_cast(dy), 0.0f, 1.0f); + }; - // GLADでOpenGLの関数を読み込む / load the OpenGL functions with GLAD - if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { - fprintf(stderr, "GLADの初期化に失敗 / failed to initialise GLAD\n"); - glfwTerminate(); - return 1; - } - printf("OpenGL %s\n", (const char *)glGetString(GL_VERSION)); - printf("GPU: %s\n", (const char *)glGetString(GL_RENDERER)); + double lastTime = window.time(); + double fpsTimer = 0.0; + int fpsFrames = 0; + + while (!window.shouldClose()) { + // 1. 時間:前のフレームからの経過秒数 / time: seconds since the previous frame + double now = window.time(); + float dt = static_cast(now - lastTime); + lastTime = now; - // メインループ / main loop - while (!glfwWindowShouldClose(window)) { - glClearColor(0.10f, 0.15f, 0.25f, 1.0f); // 紺色 / dark blue + // 2. イベント(ここでコールバックが呼ばれる) / events (the callbacks run in here) + window.pollEvents(); + + // 3. 更新:ポーリングで押しっぱなしのキーを調べる / update: poll keys that are held down + // dtを掛けると、フレームレートに関係なく毎秒0.25回る / multiplying by dt makes it 0.25 turns per second at any frame rate + if (window.keyDown(GLFW_KEY_RIGHT)) hue += 0.25f * dt; + if (window.keyDown(GLFW_KEY_LEFT)) hue -= 0.25f * dt; + + float r, g, b; + hsvToRgb(hue, saturation, value, r, g, b); + if (window.keyDown(GLFW_KEY_SPACE)) { + r = 1.0f - r; + g = 1.0f - g; + b = 1.0f - b; + } + + // 4. 描画:クリアカラーは「状態」で、glClearがそれを使う / render: the clear colour is state that glClear uses + glClearColor(r, g, b, 1.0f); glClear(GL_COLOR_BUFFER_BIT); - glfwSwapBuffers(window); // 描いた画像を表示 / show what we drew - glfwPollEvents(); // 入力やウィンドウのイベントを処理 / handle input and window events - } + // 5. 表示 / present + window.swapBuffers(); - glfwDestroyWindow(window); - glfwTerminate(); + // 0.5秒ごとにFPSをタイトルに表示 / show the FPS in the title every 0.5 s + fpsTimer += dt; + ++fpsFrames; + if (fpsTimer >= 0.5) { + char title[128]; + snprintf(title, sizeof title, "OpenGL Tutorial - Chapter 2 | %.0f FPS (%.2f ms)", fpsFrames / fpsTimer, + 1000.0 * fpsTimer / fpsFrames); + window.setTitle(title); + fpsTimer = 0.0; + fpsFrames = 0; + } + } return 0; } diff --git a/src/window.cc b/src/window.cc new file mode 100644 index 0000000..cf1ced1 --- /dev/null +++ b/src/window.cc @@ -0,0 +1,123 @@ +#ifdef _WIN32 +// SetConsoleOutputCPの為。GLADより先にインクルードする(APIENTRYの二重定義を防ぐ) +// For SetConsoleOutputCP. Include it before GLAD (so APIENTRY is not defined twice) +#define WIN32_LEAN_AND_MEAN +#define NOMINMAX +#include +#endif +#include "window.hh" + +#include "gl_debug.hh" + +#include + +Window::~Window() { + if (glfwWindow) glfwDestroyWindow(glfwWindow); + if (glfwStarted) glfwTerminate(); +} + +bool Window::create(int width, int height, const char *title) { +#ifdef _WIN32 + // コンソールの出力をUTF-8にする(日本語のメッセージが文字化けしない様に) + // switch the console output to UTF-8 (so the Japanese messages are not garbled) + SetConsoleOutputCP(CP_UTF8); +#endif + // GLFWのエラーを表示(glfwInitより前に設定できる) / print GLFW errors (may be set before glfwInit) + glfwSetErrorCallback([](int code, const char *description) { + fprintf(stderr, "GLFWエラー / GLFW error %d: %s\n", code, description); + }); + if (!glfwInit()) return false; + glfwStarted = true; + + // OpenGL 4.6 コアプロファイル+デバッグコンテキスト / OpenGL 4.6 core profile + debug context + glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); + glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 6); + glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); + glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GLFW_TRUE); + + glfwWindow = glfwCreateWindow(width, height, title, nullptr, nullptr); + if (!glfwWindow) { + fprintf(stderr, "ウィンドウの作成に失敗 / failed to create the window (OpenGL 4.6 not supported?)\n"); + return false; + } + + // 静的コールバックからこのオブジェクトに戻れるようにする / lets the static callbacks find this object + glfwSetWindowUserPointer(glfwWindow, this); + glfwSetFramebufferSizeCallback(glfwWindow, framebufferSizeCallback); + glfwSetKeyCallback(glfwWindow, keyCallback); + glfwSetMouseButtonCallback(glfwWindow, mouseButtonCallback); + glfwSetCursorPosCallback(glfwWindow, cursorPosCallback); + glfwSetScrollCallback(glfwWindow, scrollCallback); + + glfwMakeContextCurrent(glfwWindow); + if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { + fprintf(stderr, "GLADの初期化に失敗 / failed to initialise GLAD\n"); + return false; + } + printf("OpenGL %s / %s\n", (const char *)glGetString(GL_VERSION), (const char *)glGetString(GL_RENDERER)); + + enableGlDebugOutput(); + + glfwGetFramebufferSize(glfwWindow, &fbWidth, &fbHeight); + glViewport(0, 0, fbWidth, fbHeight); + glfwGetCursorPos(glfwWindow, &cursorX, &cursorY); + setVsync(true); + return true; +} + +bool Window::shouldClose() const { return glfwWindowShouldClose(glfwWindow); } +void Window::close() { glfwSetWindowShouldClose(glfwWindow, GLFW_TRUE); } +void Window::pollEvents() { glfwPollEvents(); } +void Window::swapBuffers() { glfwSwapBuffers(glfwWindow); } +void Window::setTitle(const char *title) { glfwSetWindowTitle(glfwWindow, title); } + +void Window::setVsync(bool on) { + vsyncOn = on; + glfwSwapInterval(on ? 1 : 0); // 1 = 画面の更新を待つ / 1 = wait for the display refresh +} + +double Window::time() const { return glfwGetTime(); } + +float Window::aspect() const { + // 最小化するとサイズが0になる / the size becomes 0 when minimised + return fbHeight > 0 ? static_cast(fbWidth) / static_cast(fbHeight) : 1.0f; +} + +bool Window::keyDown(int key) const { return glfwGetKey(glfwWindow, key) == GLFW_PRESS; } +bool Window::mouseButtonDown(int button) const { return glfwGetMouseButton(glfwWindow, button) == GLFW_PRESS; } + +//------------------------------------------ +// GLFWのコールバック / GLFW callbacks +//------------------------------------------ + +static Window *self(GLFWwindow *w) { return static_cast(glfwGetWindowUserPointer(w)); } + +void Window::framebufferSizeCallback(GLFWwindow *w, int width, int height) { + Window *win = self(w); + win->fbWidth = width; + win->fbHeight = height; + glViewport(0, 0, width, height); // 描画範囲をウィンドウに合わせる / draw into the whole window + if (win->onResize) win->onResize(width, height); +} + +void Window::keyCallback(GLFWwindow *w, int key, int /*scancode*/, int action, int mods) { + Window *win = self(w); + if (win->onKey) win->onKey(key, action, mods); +} + +void Window::mouseButtonCallback(GLFWwindow *w, int button, int action, int mods) { + Window *win = self(w); + if (win->onMouseButton) win->onMouseButton(button, action, mods); +} + +void Window::cursorPosCallback(GLFWwindow *w, double x, double y) { + Window *win = self(w); + win->cursorX = x; + win->cursorY = y; + if (win->onCursorPos) win->onCursorPos(x, y); +} + +void Window::scrollCallback(GLFWwindow *w, double dx, double dy) { + Window *win = self(w); + if (win->onScroll) win->onScroll(dx, dy); +} diff --git a/src/window.hh b/src/window.hh new file mode 100644 index 0000000..c86ad98 --- /dev/null +++ b/src/window.hh @@ -0,0 +1,72 @@ +// ウィンドウとOpenGLコンテキスト / the window and the OpenGL context +#pragma once + +// GLADはGLFWより先にインクルードする / include GLAD before GLFW +#include +#include + +#include + +// GLFWウィンドウとOpenGLコンテキストを持つクラス(RAII)。 +// A GLFW window plus its OpenGL context (RAII). +// 作ったGLオブジェクトはこのWindowより先に破棄すること(mainではWindowを最初に宣言する)。 +// GL objects must be destroyed before this Window (declare the Window first in main). +class Window { +public: + Window() = default; + ~Window(); + + // GLFWがthisへのポインタを持つので、コピーも移動も禁止 + // GLFW keeps a pointer to this object, so it can be neither copied nor moved + Window(const Window &) = delete; + Window &operator=(const Window &) = delete; + + // ウィンドウとOpenGL 4.6コアのデバッグコンテキストを作る。失敗したらfalse。 + // Creates the window and an OpenGL 4.6 core debug context. Returns false on failure. + bool create(int width, int height, const char *title); + + bool shouldClose() const; + void close(); + void pollEvents(); // イベント処理(コールバックはここで呼ばれる) / process events (callbacks run here) + void swapBuffers(); // 描いた画像を表示 / present the frame + + void setTitle(const char *title); + void setVsync(bool on); + bool vsync() const { return vsyncOn; } + + double time() const; // glfwInitからの秒数 / seconds since glfwInit + + // フレームバッファのサイズ(ピクセル)。高DPIではウィンドウサイズと違う。 + // Framebuffer size in pixels. On high-DPI screens it differs from the window size. + int width() const { return fbWidth; } + int height() const { return fbHeight; } + float aspect() const; // 幅÷高さ / width ÷ height + + // ポーリング:今押されているか / polling: is it held down right now? + bool keyDown(int key) const; + bool mouseButtonDown(int button) const; + double mouseX() const { return cursorX; } // ウィンドウ座標、左上が原点 / window coords, origin top-left + double mouseY() const { return cursorY; } + + // コールバック(設定は任意) / callbacks (all optional) + std::function onKey; + std::function onMouseButton; + std::function onCursorPos; + std::function onScroll; + std::function onResize; + + GLFWwindow *handle() const { return glfwWindow; } + +private: + static void framebufferSizeCallback(GLFWwindow *w, int width, int height); + static void keyCallback(GLFWwindow *w, int key, int scancode, int action, int mods); + static void mouseButtonCallback(GLFWwindow *w, int button, int action, int mods); + static void cursorPosCallback(GLFWwindow *w, double x, double y); + static void scrollCallback(GLFWwindow *w, double dx, double dy); + + GLFWwindow *glfwWindow = nullptr; + bool glfwStarted = false; + int fbWidth = 0, fbHeight = 0; + double cursorX = 0.0, cursorY = 0.0; + bool vsyncOn = true; +};