2. Windows, the Render Loop and Input

In chapter 1 everything happened inside main: GLFW, the window, GLAD and the loop.
That's fine for 50 lines, but every chapter from now on needs the same setup, plus input, plus error reporting.
So in this chapter we move the window into a small RAII class, look closely at what happens in one frame of the render loop, read the keyboard and mouse in two different ways, and switch on OpenGL's debug output, so that the driver tells us about our mistakes instead of silently ignoring them.

We also look at two ideas that the rest of the series rests on: OpenGL as a state machine, and the context that owns all of its objects.

2.1 What we build

The program still only clears the window, but now you control the color.
The background is a color in HSV (hue, saturation, value), and every input changes one part of it:

Input Effect How we read it
move the mouse left/right hue (red → yellow → green → … → red) callback
move the mouse up/down brightness (value) callback
scroll wheel saturation callback
hold ← or → rotate the hue, 0.25 turns per second polling
hold Space invert the color polling
V toggle vsync callback
E cause an OpenGL error on purpose callback
Esc quit callback

The window title shows the frame rate and the frame time, updated twice per second:

The chapter 2 window, blue, with the title OpenGL Tutorial - Chapter 2, 60 FPS, 16.67 ms

The project now has three new files in src/:

  • window.hh / window.cc: the Window class (GLFW, the window, the context, GLAD, input)
  • gl_debug.hh / gl_debug.cc: the OpenGL debug logger
  • main.cc: rewritten for the demo

CMakeLists.txt only gets the two new .cc files:

add_executable(game
  src/main.cc
  src/window.cc
  src/gl_debug.cc)

Headers don't need to be listed; the compiler finds them through the src include directory.

2.2 OpenGL is a state machine

Before we write the class, let's look at how OpenGL thinks, because it explains a lot of what we do later.

Look at these two lines from chapter 1 again:

    glClearColor(0.10f, 0.15f, 0.25f, 1.0f); // 紺色 / dark blue
    glClear(GL_COLOR_BUFFER_BIT);

glClear has no color parameter.
Instead, glClearColor stores a color in the context, and glClear uses whatever color is stored at that moment.
The color stays there until we change it, across function calls and frames.
Almost all of OpenGL works like this: there's a big set of state (the clear color, the viewport, which shader is active, whether depth testing is on, how blending works, …), functions that change the state, and functions like glClear and glDrawArrays that do work using the current state.

That's why OpenGL is called a state machine.
It's convenient, because you don't have to pass 30 parameters to every draw call.
It's also the source of most OpenGL bugs: if one part of your program turns on blending and forgets to turn it off, everything drawn afterwards is blended, and the bug shows up far away from its cause.
We'll keep that in mind and set the state we need right before we use it.

The context and its objects

All of that state lives in the context we created with glfwCreateWindow.
The context also owns all objects: buffers, textures, shaders, programs, vertex arrays, framebuffers.
An object is created by OpenGL and handed back to you as a plain number of type GLuint, its name.
You never get a pointer; you always refer to the object by its name, in the context that created it.

Two rules follow from that, and our Window class is designed around them:

  • OpenGL functions always act on the context that is current on the calling thread. We create one context, make it current once, and call OpenGL only from the main thread.
  • When the context is destroyed, all of its objects disappear with it. Deleting an object after that (for example in a destructor that runs too late) calls into a context that no longer exists. So all OpenGL objects must be destroyed before the window. In C++ that's easy: local variables are destroyed in reverse order of declaration, so we declare the Window first in main, and everything declared after it is destroyed before it.

2.3 The Window class

Here's the complete header:

// ウィンドウとOpenGLコンテキスト / the window and the OpenGL context
#pragma once

// GLADはGLFWより先にインクルードする / include GLAD before GLFW
#include <glad/glad.h>
#include <GLFW/glfw3.h>

#include <functional>

// 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<void(int key, int action, int mods)> onKey;
  std::function<void(int button, int action, int mods)> onMouseButton;
  std::function<void(double x, double y)> onCursorPos;
  std::function<void(double dx, double dy)> onScroll;
  std::function<void(int width, int height)> 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;
};

A few design decisions are worth explaining.

Why create() instead of doing everything in the constructor?
Creating a window can fail, and we don't use exceptions.
A constructor can't return an error, so the constructor does nothing, and create() returns bool.
main then reads naturally: if (!window.create(…)) return 1;.

Why neither copyable nor movable?
GLFW calls our callbacks with a GLFWwindow *, and we need to get from that back to our Window object.
We store this inside GLFW for that (2.4).
If the object were copied or moved, GLFW would still hold the old address and call into a dead object.
Deleting the copy constructor and copy assignment also prevents the compiler from generating move operations, so the class can't be moved either, and the compiler reports any attempt as an error.

Why std::function members for the callbacks?
So that main can simply assign a lambda that captures local variables, as you'll see in 2.8.
All callbacks are optional; an empty std::function is simply not called.

Why is width() the framebuffer size?
GLFW has two sizes.
The window size is in screen coordinates, which the operating system may scale.
The framebuffer size is the number of pixels we actually draw into.
On a normal monitor on Windows or X11 they're the same, but with display scaling on Wayland (or on a Mac) a 1280×720 window can have a 2560×1440 framebuffer.
OpenGL works in pixels, so width(), height() and aspect() always return the framebuffer size.
aspect() will be needed for the projection matrix in chapter 8.

2.4 Creating the window

Now window.cc, starting with the destructor and the first half of create():

#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 <windows.h>
#endif
#include "window.hh"

#include "gl_debug.hh"

#include <cstdio>

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;

The Windows lines from chapter 1 move here: windows.h at the very top (still before GLAD, which window.hh includes) and SetConsoleOutputCP at the start of create().

The destructor only undoes what actually succeeded, so it's safe even if create() failed halfway (or was never called).

glfwSetErrorCallback(callback) installs a function that GLFW calls whenever something goes wrong, with an error code and a readable description.
It's one of the few GLFW functions that may be called before glfwInit, so that even an initialization failure is reported.
Without it, a failed glfwCreateWindow just returns nullptr and you have to guess why.
With it, you get messages like "GLFW error 65543: GLX: Failed to create context: GLXBadFBConfig" (65543 is GLFW_VERSION_UNAVAILABLE).
GLFW wants a plain C function pointer here; a lambda without captures converts to one automatically, so we can write it in place.

  // 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;
  }

The hints are the ones from chapter 1, plus GLFW_OPENGL_DEBUG_CONTEXT.
A debug context tells the driver that we want detailed error reports and warnings, even if that costs some speed.
Section 2.9 uses it.
For a release build of a game you'd turn it off, but while learning, it's priceless.

Connecting the callbacks

  // 静的コールバックからこのオブジェクトに戻れるようにする / 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);

GLFW is a C library, so its callbacks are plain functions that get a GLFWwindow * as their first parameter, not a member function of our class.
glfwSetWindowUserPointer(window, pointer) stores one arbitrary pointer per window, and glfwGetWindowUserPointer(window) gives it back.
We store this, so our static callback functions can find the Window object that belongs to the GLFW window.

Each glfwSet…Callback(window, function) installs one callback.
They all return the previously installed callback, which we don't need.
None of them runs immediately: GLFW calls them later, from inside glfwPollEvents() (2.6).

The context, GLAD and the debug output

  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();

This part is the same as chapter 1, now printed on one line.
enableGlDebugOutput() comes from gl_debug.hh and is explained in 2.9.
It has to come after GLAD, because it calls OpenGL functions.

Viewport, cursor and vsync

  glfwGetFramebufferSize(glfwWindow, &fbWidth, &fbHeight);
  glViewport(0, 0, fbWidth, fbHeight);
  glfwGetCursorPos(glfwWindow, &cursorX, &cursorY);
  setVsync(true);
  return true;
}

glfwGetFramebufferSize(window, &width, &height) reads the framebuffer size in pixels.

glViewport(x, y, width, height) tells OpenGL which rectangle of the framebuffer to draw into, in pixels, with (x,y) the bottom-left corner (OpenGL's window coordinates have y going up).
It's the transform that turns normalized device coordinates (from −1 to 1) into pixels, which we'll see in action in chapter 3 and which the Linear Algebra series, chapter 12 derives.
When a context is first made current, the viewport is set to the window's size automatically, so this call isn't strictly needed here; but it is needed after every resize, and setting it explicitly makes the code independent of that rule.
Note that glClear is not limited by the viewport (only by the scissor test), so in this chapter the viewport doesn't change the result yet.

glfwGetCursorPos reads the current mouse position, so mouseX() and mouseY() are correct before the mouse has moved for the first time.

The small wrappers

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<float>(fbWidth) / static_cast<float>(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; }

  • glfwSetWindowShouldClose(window, value) sets the same flag that the close button sets. The loop sees it at the next shouldClose() and ends normally. That's how Esc will quit: we don't destroy anything in the middle of a frame.
  • glfwSetWindowTitle(window, title) changes the title bar text. It's fairly slow on some systems, which is why we only update it twice per second.
  • glfwSwapInterval(interval) sets how many monitor refreshes glfwSwapBuffers waits for: 1 is vsync on, 0 is off. It applies to the current context, so it only works after glfwMakeContextCurrent. Some drivers let the user override it in their control panel.
  • glfwGetTime() returns the seconds since glfwInit as a double, with high resolution.
  • aspect() returns 1 when the window is minimized. A minimized window has a framebuffer size of 0×0, and dividing by zero there would put inf or NaN into our projection matrix later.
  • glfwGetKey(window, key) and glfwGetMouseButton(window, button) return GLFW_PRESS or GLFW_RELEASE: the state at the time of the last glfwPollEvents().

2.5 The callbacks

The last part of window.cc contains the five static callbacks:

//------------------------------------------
// GLFWのコールバック / GLFW callbacks
//------------------------------------------

static Window *self(GLFWwindow *w) { return static_cast<Window *>(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);
}

Each one gets our object back with self() and forwards the event to the matching std::function, if one is set.
Because they're static member functions, they're allowed to touch the private members.

The parameters are worth knowing:

  • Framebuffer size: the new size in pixels. We store it and update the viewport right here, so no later chapter ever has to think about glViewport after a resize. If you only handled the window size callback (glfwSetWindowSizeCallback) instead, high-DPI screens would get the wrong viewport.
  • Key: key is a GLFW_KEY_… constant for the key's position on a US keyboard layout (so GLFW_KEY_W is the key where W is on a US keyboard, which is useful for WASD on any layout). scancode is the raw, platform-specific key code, which we ignore. action is GLFW_PRESS, GLFW_RELEASE or GLFW_REPEAT (the auto-repeat while a key is held, like in a text editor). mods is a bit mask of GLFW_MOD_SHIFT, GLFW_MOD_CONTROL, GLFW_MOD_ALT and GLFW_MOD_SUPER.
  • Mouse button: GLFW_MOUSE_BUTTON_LEFT, …_RIGHT, …_MIDDLE, with the same action and mods (no repeat).
  • Cursor position: in window coordinates, with the origin at the top-left corner and y going down. That's the opposite of glViewport and of the NDC we'll see in chapter 3, a classic source of upside-down mouse code.
  • Scroll: dx and dy are the scroll offsets since the last event. A normal mouse wheel gives dy = ±1 per notch, touchpads give small fractional values in both directions.

2.6 The render loop

Every real-time program, from this demo to a AAA game, has a loop like this at its heart:

The render loop: 1 time, 2 events, 3 update, 4 render, 5 present, then back to 1 for the next frame

  1. Time: measure how long the last frame took.
  2. Events: let the window system deliver input. Our callbacks run here.
  3. Update: move the game forward by that much time. Read held keys here.
  4. Render: draw the new frame.
  5. Present: show it.

Here it is in our main:

  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<float>(now - lastTime);
    lastTime = now;

    // 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);

    // 5. 表示 / present
    window.swapBuffers();

Delta time

dt ("delta time") is the time between this frame and the previous one, in seconds.
At 60 frames per second it's about 160≈0.0167 s, at 144 FPS about 0.0069 s.

Holding → adds 0.25f * dt to the hue every frame.
Over one second, the frames' dt values add up to 1, so the hue grows by exactly 0.25, a quarter turn of the color wheel, at any frame rate:

60⋅0.25⋅160=144⋅0.25⋅1144=0.25

If we wrote hue += 0.004f per frame instead, the color would turn more than twice as fast on a 144 Hz monitor as on a 60 Hz one, and a game written like that runs at a different speed on every computer.
So: everything that changes over time gets multiplied by dt.
(In chapter 26 we'll switch the games to a fixed time step, which is even more robust, but the idea starts here.)

Double buffering and vsync

Why "swap" buffers?
If we drew directly into the image the monitor is currently showing, you would see half-finished frames: a cleared screen, then one object, then the next.
So the framebuffer has two color buffers:

Double buffering: we draw into the back buffer while the monitor shows the front buffer, and glfwSwapBuffers exchanges them

We always draw into the back buffer, which nobody sees.
glfwSwapBuffers exchanges the two, and the finished frame becomes the front buffer that the monitor shows.

With vsync on (swap interval 1), the exchange waits for the monitor to start a new refresh.
That has two effects: the picture never shows the top part of one frame and the bottom part of another (that's called tearing), and the loop can't run faster than the monitor's refresh rate, so it doesn't heat your GPU drawing frames nobody will see.
With vsync off, the loop runs as fast as it can, which is useful for measuring performance.
Press V in the demo: the FPS in the title jumps from your monitor's rate (60, 144, …) to hundreds or thousands, but the hue still turns at the same speed while you hold →, because of dt.

Events: callbacks happen inside glfwPollEvents

glfwPollEvents() processes all events that have arrived since the last call and returns immediately.
Our callbacks run inside it, on the main thread, in the order the events happened.
So when pollEvents() returns, hue, value and saturation already contain the latest mouse input.

That's why the order in the loop matters: events first, then update, then render.
If you rendered before polling, every frame would show the input from one frame earlier.

glfwPollEvents is the right choice for games, which redraw constantly anyway.
For a tool that only needs to redraw on input, there's glfwWaitEvents(), which sleeps until an event arrives.

FPS in the title

    // 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;
}

We count frames and time, and every half second we divide.
30 frames in 0.5 s is 60 FPS, and 1000⋅0.530≈16.67 ms per frame.
The frame time in milliseconds is the more useful number for performance work: "my effect costs 2 ms" means the same at every frame rate, while "my effect costs 20 FPS" doesn't.

2.7 Callbacks or polling?

GLFW gives us two ways to read input, and the demo uses both on purpose.

Callbacks report events: "the key went down", "the mouse moved to (812, 344)", "the wheel turned one notch".
Every event is delivered exactly once, even if it happened between two frames.
Use them for things that should happen once: quitting, toggling vsync, jumping, opening a menu, typing text.

Polling asks for the state right now: "is → held down?".
Use it for things that happen continuously while a key is held: moving, turning, accelerating.
In the update step you check the key and multiply by dt.

Getting this wrong produces two classic bugs:

  • Toggling vsync with polling (if (window.keyDown(GLFW_KEY_V)) …) toggles it on every frame while the key is held, so it ends up randomly on or off.
  • Moving the player only in the key callback moves it in jerky steps: one step on press, then nothing until the keyboard's auto-repeat starts (GLFW_REPEAT), and then at the keyboard's repeat rate instead of the frame rate.

A very short tap can also be missed by polling: if a key goes down and up again between two glfwPollEvents() calls, glfwGetKey never sees it pressed.
The callback still gets both events.
In chapter 26 we'll combine both ideas into an input class that knows "pressed this frame", "held" and "released this frame".

2.8 The demo

Now the demo code in main.cc.
At the top, the controls and a small color conversion:

// 第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 <algorithm>
#include <cmath>
#include <cstdio>

// 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<int>(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;
}

HSV describes a color by its hue h (the position on the color wheel, here 0 to 1 for one full turn), its saturation s (0 is gray, 1 is the pure color) and its value v (the brightness).
The function splits the wheel into six sectors (red→yellow, yellow→green, green→cyan, cyan→blue, blue→magenta, magenta→red).
In each sector one channel is at its maximum c=v⋅s, one is 0, and one ramps between them:

x=c⋅(1−|(6hmod2)−1|),m=v−c

Finally m is added to all three channels, which lifts the darkest channel from 0 to v−c.
h - std::floor(h) wraps the hue into 0 to 1 first, so holding ← past red into negative values still works.

For example, the mouse at (800, 200) in our 1280×720 window gives h=8001280=0.625 and v=1−200720≈0.722, and the starting saturation is 0.6:

  • 6h=3.75, so we're in sector 3 (cyan→blue), which uses (0,x,c).
  • c=0.722⋅0.6≈0.433
  • x=0.433⋅(1−|1.75−1|)=0.433⋅0.25≈0.108
  • m=0.722−0.433≈0.289
  • (r,g,b)=(0+0.289,0.108+0.289,0.433+0.289)≈(0.289,0.397,0.722)

That's (74, 101, 184) in 8-bit values, exactly the blue in the screenshot above.

main and the callbacks

int main() {
  Window window;
  if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 2")) return 1;

  float hue = 0.6f, saturation = 0.6f, value = 0.35f;

  // コールバック:イベントが起きた時に一度だけ呼ばれる / 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<float>(x) / static_cast<float>(window.width());
    value = 1.0f - static_cast<float>(y) / static_cast<float>(window.height());
  };
  window.onScroll = [&](double /*dx*/, double dy) {
    saturation = std::clamp(saturation + 0.05f * static_cast<float>(dy), 0.0f, 1.0f);
  };

Window window; is the first line of main, as promised in 2.2.
The lambdas capture by reference ([&]), so they change hue, value and saturation directly.
That's safe because the locals live as long as main, and the callbacks only run inside window.pollEvents() in the loop.

  • The key lambda ignores everything except GLFW_PRESS, so holding V doesn't toggle vsync again with every auto-repeat.
  • The cursor lambda maps x from 0 to the width onto the hue 0 to 1, and y onto the brightness. Because the cursor's y goes down, we flip it with 1.0f - …, so the top of the window is bright.
  • The scroll lambda changes the saturation by 0.05 per notch and keeps it in 0 to 1 with std::clamp.

Strictly speaking, the cursor position is in window coordinates while width() is in pixels.
On Windows and X11 they're the same; with display scaling (for example on Wayland) the mouse would only reach part of the hue range.
For this demo that doesn't matter, but remember it when you need exact mouse positions in pixels: GLSL chapter 5 converts them, and we'll do the same when we need it.

When you run it, you should get colors like these:

Three screenshots: the mouse at 800, 200 gives blue; the mouse at 200, 300 after scrolling gives olive; the same with Space held gives the inverted blue-violet

2.9 OpenGL's debug output

OpenGL functions don't return error codes.
When you call a function wrongly, OpenGL ignores the call and records an error flag, and your program carries on as if nothing happened.
The classic way to find such errors is glGetError(), which returns (and clears) the oldest recorded error: GL_INVALID_ENUM, GL_INVALID_VALUE, GL_INVALID_OPERATION, GL_OUT_OF_MEMORY, …
You'd have to call it after every single OpenGL call to find out which call failed, and even then you only get a number.

Since OpenGL 4.3, there's something much better: debug output.
You give the driver a callback, and it calls it immediately, inside the failing function, with a readable message.
Here's the header:

// OpenGLのデバッグ出力 / OpenGL debug output
#pragma once

// デバッグコンテキストならglDebugMessageCallbackでロガーを登録する。登録できたらtrue。
// On a debug context, installs a logger with glDebugMessageCallback. Returns true if installed.
bool enableGlDebugOutput();

Turning it on

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;
}

  • glGetIntegerv(pname, &value) reads one piece of integer state. GL_CONTEXT_FLAGS is a bit mask, and GL_CONTEXT_FLAG_DEBUG_BIT is set if we really got a debug context. If the GLFW_OPENGL_DEBUG_CONTEXT hint is missing, we print a message and return false.
  • glEnable(cap) turns on a feature of the state machine (and glDisable(cap) turns it off). GL_DEBUG_OUTPUT turns on the message system.
  • GL_DEBUG_OUTPUT_SYNCHRONOUS makes the driver call our callback inside the OpenGL function that caused the message, on the same thread. Without it, the driver may report messages later, from another thread. Synchronous output is slower, but when you set a breakpoint in the callback, the call stack shows exactly the line that caused the error.
  • glDebugMessageCallback(callback, userParam) installs the callback. userParam is a pointer that the driver passes back to every call; we don't need it.
  • glDebugMessageControl(source, type, severity, count, ids, enabled) filters messages. GL_DONT_CARE means "any", so this call says: messages from any source, of any type, with severity GL_DEBUG_SEVERITY_NOTIFICATION, are disabled (GL_FALSE). With count and ids you could instead name individual message IDs. Notifications are things like "buffer 3 will use video memory", which some drivers print for every buffer.

The callback

// ドライバーがエラーや警告を見つけるたびに呼ばれる / 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);
}

The driver passes:

  • source: who produced the message: the API (a wrong call), the window system, the shader compiler, a third-party tool, or the application itself (glDebugMessageInsert).
  • type: an error, deprecated or undefined behavior, a portability or performance warning, a marker, or other.
  • id: a number identifying the message, chosen by the driver. The same problem has different IDs on NVIDIA, AMD and Mesa. The four IDs we skip are NVIDIA's best-known information messages (about renderbuffer and buffer memory, texture state and shader recompilation) that would otherwise flood the terminal.
  • severity: high (errors, undefined behavior), medium (serious performance problems or deprecated use), low (minor warnings) or notification.
  • length and message: the text. It's null-terminated, so we don't need length.
  • userParam: the pointer from glDebugMessageCallback.

We also skip messages from the shader compiler, because our own shader code (chapter 3 on) prints compile errors itself, with the file name; otherwise every shader error would appear twice.

APIENTRY is the calling convention OpenGL uses for callbacks (__stdcall on 32-bit Windows, nothing elsewhere).
GLAD defines it; if you leave it out, the code compiles on 64-bit systems, but the function type doesn't match on 32-bit Windows.

The three helper functions above the callback simply turn the enum values into short names:

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";
  }
}

typeName() and severityName() look exactly the same, for GL_DEBUG_TYPE_ERROR ("ERROR"), GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR, … and GL_DEBUG_SEVERITY_HIGH ("high"), …; you'll find them in the ZIP.

Trying it

Press E in the demo.
The key callback calls glEnable(GL_TEXTURE_2D), which was valid in old OpenGL (it switched on fixed-function texturing) but doesn't exist in the core profile.
On Mesa, this appears in the terminal at once:

[GL ERROR] (API, high, id 1) GL_INVALID_ENUM in glEnable(GL_TEXTURE_2D)

NVIDIA and AMD word it differently and use other IDs, but the type, source and severity are the same.
Compare that with glGetError, which would only have returned 0x0500 (GL_INVALID_ENUM) at some point later, without saying which call it was.

From now on, keep an eye on the terminal while you run the examples.
A program that draws the right picture and prints no [GL ERROR] lines is correct; one that draws the right picture by accident while printing errors will break on the next driver.

2.10 Building and running

Nothing new here: add the two files to CMakeLists.txt as shown in 2.1, then build and run from the project root as in chapter 1.

OpenGL 4.6.0 NVIDIA 577.19 / NVIDIA GeForce RTX 2060/PCIe/SSE2
vsync off
vsync on
[GL ERROR] (API, high, id 1280) GL_INVALID_ENUM error generated. Cannot enable <cap> in the current profile.

(That's after pressing V twice and E once.)
If you see "not a debug context: no GL debug output" instead, the GLFW_OPENGL_DEBUG_CONTEXT hint is missing.

2.11 How real programs do it

  • Engines wrap the window too. Unreal, Unity, Godot and every custom engine have a platform layer like our Window: one class that hides GLFW, SDL or the raw Win32/X11/Wayland code. The rest of the engine never includes glfw3.h. From chapter 25 on, ours becomes part of a small engine library.
  • Input mapping. Games don't check GLFW_KEY_SPACE in gameplay code; they map physical keys and gamepad buttons to actions ("jump", "fire") so players can rebind them. GLFW's key codes being based on key positions (not letters) is what makes WASD work on AZERTY keyboards.
  • Debug output in development builds only. Shipping games usually create a normal context. A debug context with synchronous output can be noticeably slower. A common pattern is a command-line switch or a build option for it.
  • Graphics debuggers. Tools like RenderDoc capture a frame and show every OpenGL call, the state at each draw, and the contents of every buffer and texture. They're the next step after debug output, and they work with everything in this series.
  • Frame pacing. Games usually combine vsync with a frame limiter and measure frame times, not FPS, exactly because frame time adds up linearly (2 ms + 3 ms = 5 ms), while FPS doesn't.

2.12 Summary

  • OpenGL is a state machine: functions like glClearColor set state, and functions like glClear use the current state. The state and all objects (identified by GLuint names) belong to the context, which is current on one thread.
  • All OpenGL objects must be destroyed before the context. We declare the Window first in main, so it's destroyed last.
  • Window wraps GLFW, the window, the 4.6 core debug context and GLAD. It's RAII, create() returns bool, and it can be neither copied nor moved because GLFW stores this (glfwSetWindowUserPointer).
  • Static callbacks forward events to std::function members. The framebuffer size callback updates the viewport (glViewport, origin bottom-left, in pixels).
  • The render loop: time → events (glfwPollEvents, callbacks run here) → update → render → present (glfwSwapBuffers). Multiply everything that changes over time by dt.
  • Double buffering: we draw into the back buffer; the swap shows it. Vsync (glfwSwapInterval(1)) waits for the monitor, which prevents tearing and limits the frame rate.
  • Use callbacks for one-time events (quit, toggle) and polling (glfwGetKey) for held keys.
  • Debug output (4.3): check GL_CONTEXT_FLAG_DEBUG_BIT, enable GL_DEBUG_OUTPUT and GL_DEBUG_OUTPUT_SYNCHRONOUS, install a callback with glDebugMessageCallback, filter with glDebugMessageControl.

2.13 Challenges

  1. ★ Make F11 toggle fullscreen. Use glfwGetPrimaryMonitor(), glfwGetVideoMode() and glfwSetWindowMonitor() (pass nullptr as the monitor and the old position and size to go back). The window should switch to fullscreen and back, and because the framebuffer size callback fires, the color should still fill the whole screen.
  2. ★ Use the mouse buttons: set window.onMouseButton so that a left click sets a random hue (rand() / (float)RAND_MAX). The color should jump with every click, but holding the button should not change it again.
  3. ★ Instead of the FPS, show the shortest and longest frame time of the last second in the title. With vsync on, both numbers should be close to 16.7 ms on a 60 Hz monitor; dragging the window around usually makes the maximum jump.
  4. ★★ Make the hue speed grow the longer → is held: store the time when the key was pressed, and use a speed like 0.25f * (1.0f + heldSeconds). The color should start turning slowly and get faster and faster.
  5. ★★ Cause another error on purpose: call glBindBuffer(GL_ARRAY_BUFFER, 12345) (binding a name that was never created is an error in the core profile). You should see a [GL ERROR] … GL_INVALID_OPERATION … line. Then send your own message with glDebugMessageInsert(GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_MARKER, 1, GL_DEBUG_SEVERITY_MEDIUM, -1, "hello"). You should see [GL MARKER] (application, medium, id 1) hello. Try GL_DEBUG_SEVERITY_LOW too: nothing appears, because messages of low severity are disabled by default (we only turned off notifications ourselves).
  6. ★★★ Write a frame limiter: with vsync off, wait at the end of each frame until 1/30 s has passed since the start of the frame (use std::this_thread::sleep_for, and think about why sleeping for exactly the remaining time isn't precise). The title should show about 30 FPS and 33.3 ms, and the hue should still turn at 0.25 turns per second.

Download the diff

Download the project (ZIP)

ファイル: a/CMakeLists.txt | b/CMakeLists.txt

前新
@@ -19,7 +19,10 @@ endif()
19 add_library(glad STATIC external/glad/src/glad.c) 19 add_library(glad STATIC external/glad/src/glad.c)
20 target_include_directories(glad PUBLIC external/glad/include) 20 target_include_directories(glad PUBLIC external/glad/include)
21   21  
22 add_executable(game src/main.cc) 22 add_executable(game
    23 src/main.cc
    24 src/window.cc
    25 src/gl_debug.cc)
23 target_include_directories(game PRIVATE src external/stb external/linalg) 26 target_include_directories(game PRIVATE src external/stb external/linalg)
24 target_link_libraries(game PRIVATE glad glfw) 27 target_link_libraries(game PRIVATE glad glfw)
25   28  

ファイル: /dev/null | b/src/gl_debug.cc

前新
@@ -0,0 +1,63 @@
    1 #include "gl_debug.hh"
    2  
    3 #include <glad/glad.h>
    4  
    5 #include <cstdio>
    6  
    7 static const char *sourceName(GLenum source) {
    8 switch (source) {
    9 case GL_DEBUG_SOURCE_API: return "API";
    10 case GL_DEBUG_SOURCE_WINDOW_SYSTEM: return "window system";
    11 case GL_DEBUG_SOURCE_SHADER_COMPILER: return "shader compiler";
    12 case GL_DEBUG_SOURCE_THIRD_PARTY: return "third party";
    13 case GL_DEBUG_SOURCE_APPLICATION: return "application";
    14 default: return "other";
    15 }
    16 }
    17  
    18 static const char *typeName(GLenum type) {
    19 switch (type) {
    20 case GL_DEBUG_TYPE_ERROR: return "ERROR";
    21 case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR: return "DEPRECATED";
    22 case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR: return "UNDEFINED";
    23 case GL_DEBUG_TYPE_PORTABILITY: return "PORTABILITY";
    24 case GL_DEBUG_TYPE_PERFORMANCE: return "PERFORMANCE";
    25 case GL_DEBUG_TYPE_MARKER: return "MARKER";
    26 default: return "OTHER";
    27 }
    28 }
    29  
    30 static const char *severityName(GLenum severity) {
    31 switch (severity) {
    32 case GL_DEBUG_SEVERITY_HIGH: return "high";
    33 case GL_DEBUG_SEVERITY_MEDIUM: return "medium";
    34 case GL_DEBUG_SEVERITY_LOW: return "low";
    35 default: return "notification";
    36 }
    37 }
    38  
    39 // ドライバーがエラーや警告を見つけるたびに呼ばれる / called whenever the driver finds an error or warning
    40 static void APIENTRY debugCallback(GLenum source, GLenum type, GLuint id, GLenum severity,
    41 GLsizei /*length*/, const GLchar *message, const void * /*user*/) {
    42 // NVIDIAのよくある情報メッセージは無視 / ignore common NVIDIA info messages
    43 if (id == 131169 || id == 131185 || id == 131204 || id == 131218) return;
    44 // シェーダーのエラーはファイル名付きで自分で表示する / we print shader errors ourselves, with file names
    45 if (source == GL_DEBUG_SOURCE_SHADER_COMPILER) return;
    46 fprintf(stderr, "[GL %s] (%s, %s, id %u) %s\n", typeName(type), sourceName(source), severityName(severity), id,
    47 message);
    48 }
    49  
    50 bool enableGlDebugOutput() {
    51 GLint flags = 0;
    52 glGetIntegerv(GL_CONTEXT_FLAGS, &flags);
    53 if (!(flags & GL_CONTEXT_FLAG_DEBUG_BIT)) {
    54 fprintf(stderr, "デバッグコンテキストではない / not a debug context: no GL debug output\n");
    55 return false;
    56 }
    57 glEnable(GL_DEBUG_OUTPUT);
    58 glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS); // エラーを起こした関数の中で呼ぶ / call back inside the failing function
    59 glDebugMessageCallback(debugCallback, nullptr);
    60 // 「通知」レベルは多すぎるので切る / turn off the (very chatty) notification level
    61 glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DEBUG_SEVERITY_NOTIFICATION, 0, nullptr, GL_FALSE);
    62 return true;
    63 }

ファイル: /dev/null | b/src/gl_debug.hh

前新
@@ -0,0 +1,6 @@
    1 // OpenGLのデバッグ出力 / OpenGL debug output
    2 #pragma once
    3  
    4 // デバッグコンテキストならglDebugMessageCallbackでロガーを登録する。登録できたらtrue。
    5 // On a debug context, installs a logger with glDebugMessageCallback. Returns true if installed.
    6 bool enableGlDebugOutput();

ファイル: a/src/main.cc | b/src/main.cc

前新
@@ -1,63 +1,105 @@
1 // 第1章:ウィンドウを開いて色で塗りつぶす 1 // 第2章:ウィンドウ、レンダーループ、入力
2 // Chapter 1: open a window and clear it to a colour 2 // Chapter 2: windows, the render loop and input
3   3 //
4 #ifdef _WIN32 4 // 操作 / Controls:
5 // SetConsoleOutputCPの為。GLADより先にインクルードする(APIENTRYの二重定義を防ぐ) 5 // マウス移動 / move the mouse 色相と明るさ / hue and brightness
6 // For SetConsoleOutputCP. Include it before GLAD (so APIENTRY is not defined twice) 6 // ホイール / scroll wheel 彩度 / saturation
7 #define WIN32_LEAN_AND_MEAN 7 // ←/→ を押し続ける / hold ←/→ 色相を回す / rotate the hue
8 #define NOMINMAX 8 // スペースを押し続ける / hold Space 色を反転 / invert the colour
9 #include <windows.h> 9 // V 垂直同期の切り替え / toggle vsync
10 #endif 10 // E わざとGLエラーを起こす / cause a GL error on purpose
11 // GLADはGLFWより先にインクルードする / include GLAD before GLFW 11 // Esc 終了 / quit
12 #include <glad/glad.h> 12 #include "window.hh"
13 #include <GLFW/glfw3.h>    
14   13  
    14 #include <algorithm>
    15 #include <cmath>
15 #include <cstdio> 16 #include <cstdio>
16   17  
    18 // HSV(各0〜1)からRGBへ / HSV (each 0..1) to RGB
    19 static void hsvToRgb(float h, float s, float v, float &r, float &g, float &b) {
    20 h = (h - std::floor(h)) * 6.0f; // 0〜6 / 0..6
    21 float c = v * s;
    22 float x = c * (1.0f - std::fabs(std::fmod(h, 2.0f) - 1.0f));
    23 float m = v - c;
    24 int sector = static_cast<int>(h) % 6;
    25 float rgb[6][3] = {{c, x, 0}, {x, c, 0}, {0, c, x}, {0, x, c}, {x, 0, c}, {c, 0, x}};
    26 r = rgb[sector][0] + m;
    27 g = rgb[sector][1] + m;
    28 b = rgb[sector][2] + m;
    29 }
    30  
17 int main() { 31 int main() {
18 #ifdef _WIN32 32 Window window;
19 // コンソールの出力をUTF-8にする(日本語のメッセージが文字化けしない様に) 33 if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 2")) return 1;
20 // switch the console output to UTF-8 (so the Japanese messages are not garbled)    
21 SetConsoleOutputCP(CP_UTF8);    
22 #endif    
23 // GLFWを初期化 / initialise GLFW    
24 if (!glfwInit()) {    
25 fprintf(stderr, "GLFWの初期化に失敗 / failed to initialise GLFW\n");    
26 return 1;    
27 }    
28   34  
29 // OpenGL 4.6 コアプロファイルを要求 / ask for an OpenGL 4.6 core profile context 35 float hue = 0.6f, saturation = 0.6f, value = 0.35f;
30 glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);    
31 glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 6);    
32 glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);    
33   36  
34 GLFWwindow *window = glfwCreateWindow(1280, 720, "OpenGL Tutorial - Chapter 1", nullptr, nullptr); 37 // コールバック:イベントが起きた時に一度だけ呼ばれる / callbacks: called once when an event happens
35 if (!window) { 38 window.onKey = [&](int key, int action, int /*mods*/) {
36 fprintf(stderr, "ウィンドウの作成に失敗 / failed to create the window (OpenGL 4.6 not supported?)\n"); 39 if (action != GLFW_PRESS) return;
37 glfwTerminate(); 40 if (key == GLFW_KEY_ESCAPE) window.close();
38 return 1; 41 if (key == GLFW_KEY_V) {
39 } 42 window.setVsync(!window.vsync());
40 glfwMakeContextCurrent(window); 43 printf("vsync %s\n", window.vsync() ? "on" : "off");
    44 }
    45 if (key == GLFW_KEY_E) {
    46 // コアプロファイルにGL_TEXTURE_2Dの有効化はない → GL_INVALID_ENUM
    47 // the core profile has no glEnable(GL_TEXTURE_2D) → GL_INVALID_ENUM
    48 glEnable(GL_TEXTURE_2D);
    49 }
    50 };
    51 window.onCursorPos = [&](double x, double y) {
    52 hue = static_cast<float>(x) / static_cast<float>(window.width());
    53 value = 1.0f - static_cast<float>(y) / static_cast<float>(window.height());
    54 };
    55 window.onScroll = [&](double /*dx*/, double dy) {
    56 saturation = std::clamp(saturation + 0.05f * static_cast<float>(dy), 0.0f, 1.0f);
    57 };
41   58  
42 // GLADでOpenGLの関数を読み込む / load the OpenGL functions with GLAD 59 double lastTime = window.time();
43 if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { 60 double fpsTimer = 0.0;
44 fprintf(stderr, "GLADの初期化に失敗 / failed to initialise GLAD\n"); 61 int fpsFrames = 0;
45 glfwTerminate(); 62  
46 return 1; 63 while (!window.shouldClose()) {
47 } 64 // 1. 時間:前のフレームからの経過秒数 / time: seconds since the previous frame
48 printf("OpenGL %s\n", (const char *)glGetString(GL_VERSION)); 65 double now = window.time();
49 printf("GPU: %s\n", (const char *)glGetString(GL_RENDERER)); 66 float dt = static_cast<float>(now - lastTime);
    67 lastTime = now;
50   68  
51 // メインループ / main loop 69 // 2. イベント(ここでコールバックが呼ばれる) / events (the callbacks run in here)
52 while (!glfwWindowShouldClose(window)) { 70 window.pollEvents();
53 glClearColor(0.10f, 0.15f, 0.25f, 1.0f); // 紺色 / dark blue 71  
    72 // 3. 更新:ポーリングで押しっぱなしのキーを調べる / update: poll keys that are held down
    73 // dtを掛けると、フレームレートに関係なく毎秒0.25回る / multiplying by dt makes it 0.25 turns per second at any frame rate
    74 if (window.keyDown(GLFW_KEY_RIGHT)) hue += 0.25f * dt;
    75 if (window.keyDown(GLFW_KEY_LEFT)) hue -= 0.25f * dt;
    76  
    77 float r, g, b;
    78 hsvToRgb(hue, saturation, value, r, g, b);
    79 if (window.keyDown(GLFW_KEY_SPACE)) {
    80 r = 1.0f - r;
    81 g = 1.0f - g;
    82 b = 1.0f - b;
    83 }
    84  
    85 // 4. 描画:クリアカラーは「状態」で、glClearがそれを使う / render: the clear colour is state that glClear uses
    86 glClearColor(r, g, b, 1.0f);
54 glClear(GL_COLOR_BUFFER_BIT); 87 glClear(GL_COLOR_BUFFER_BIT);
55   88  
56 glfwSwapBuffers(window); // 描いた画像を表示 / show what we drew 89 // 5. 表示 / present
57 glfwPollEvents(); // 入力やウィンドウのイベントを処理 / handle input and window events 90 window.swapBuffers();
58 }    
59   91  
60 glfwDestroyWindow(window); 92 // 0.5秒ごとにFPSをタイトルに表示 / show the FPS in the title every 0.5 s
61 glfwTerminate(); 93 fpsTimer += dt;
    94 ++fpsFrames;
    95 if (fpsTimer >= 0.5) {
    96 char title[128];
    97 snprintf(title, sizeof title, "OpenGL Tutorial - Chapter 2 | %.0f FPS (%.2f ms)", fpsFrames / fpsTimer,
    98 1000.0 * fpsTimer / fpsFrames);
    99 window.setTitle(title);
    100 fpsTimer = 0.0;
    101 fpsFrames = 0;
    102 }
    103 }
62 return 0; 104 return 0;
63 } 105 }

ファイル: /dev/null | b/src/window.cc

前新
@@ -0,0 +1,123 @@
    1 #ifdef _WIN32
    2 // SetConsoleOutputCPの為。GLADより先にインクルードする(APIENTRYの二重定義を防ぐ)
    3 // For SetConsoleOutputCP. Include it before GLAD (so APIENTRY is not defined twice)
    4 #define WIN32_LEAN_AND_MEAN
    5 #define NOMINMAX
    6 #include <windows.h>
    7 #endif
    8 #include "window.hh"
    9  
    10 #include "gl_debug.hh"
    11  
    12 #include <cstdio>
    13  
    14 Window::~Window() {
    15 if (glfwWindow) glfwDestroyWindow(glfwWindow);
    16 if (glfwStarted) glfwTerminate();
    17 }
    18  
    19 bool Window::create(int width, int height, const char *title) {
    20 #ifdef _WIN32
    21 // コンソールの出力をUTF-8にする(日本語のメッセージが文字化けしない様に)
    22 // switch the console output to UTF-8 (so the Japanese messages are not garbled)
    23 SetConsoleOutputCP(CP_UTF8);
    24 #endif
    25 // GLFWのエラーを表示(glfwInitより前に設定できる) / print GLFW errors (may be set before glfwInit)
    26 glfwSetErrorCallback([](int code, const char *description) {
    27 fprintf(stderr, "GLFWエラー / GLFW error %d: %s\n", code, description);
    28 });
    29 if (!glfwInit()) return false;
    30 glfwStarted = true;
    31  
    32 // OpenGL 4.6 コアプロファイル+デバッグコンテキスト / OpenGL 4.6 core profile + debug context
    33 glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
    34 glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 6);
    35 glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    36 glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GLFW_TRUE);
    37  
    38 glfwWindow = glfwCreateWindow(width, height, title, nullptr, nullptr);
    39 if (!glfwWindow) {
    40 fprintf(stderr, "ウィンドウの作成に失敗 / failed to create the window (OpenGL 4.6 not supported?)\n");
    41 return false;
    42 }
    43  
    44 // 静的コールバックからこのオブジェクトに戻れるようにする / lets the static callbacks find this object
    45 glfwSetWindowUserPointer(glfwWindow, this);
    46 glfwSetFramebufferSizeCallback(glfwWindow, framebufferSizeCallback);
    47 glfwSetKeyCallback(glfwWindow, keyCallback);
    48 glfwSetMouseButtonCallback(glfwWindow, mouseButtonCallback);
    49 glfwSetCursorPosCallback(glfwWindow, cursorPosCallback);
    50 glfwSetScrollCallback(glfwWindow, scrollCallback);
    51  
    52 glfwMakeContextCurrent(glfwWindow);
    53 if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) {
    54 fprintf(stderr, "GLADの初期化に失敗 / failed to initialise GLAD\n");
    55 return false;
    56 }
    57 printf("OpenGL %s / %s\n", (const char *)glGetString(GL_VERSION), (const char *)glGetString(GL_RENDERER));
    58  
    59 enableGlDebugOutput();
    60  
    61 glfwGetFramebufferSize(glfwWindow, &fbWidth, &fbHeight);
    62 glViewport(0, 0, fbWidth, fbHeight);
    63 glfwGetCursorPos(glfwWindow, &cursorX, &cursorY);
    64 setVsync(true);
    65 return true;
    66 }
    67  
    68 bool Window::shouldClose() const { return glfwWindowShouldClose(glfwWindow); }
    69 void Window::close() { glfwSetWindowShouldClose(glfwWindow, GLFW_TRUE); }
    70 void Window::pollEvents() { glfwPollEvents(); }
    71 void Window::swapBuffers() { glfwSwapBuffers(glfwWindow); }
    72 void Window::setTitle(const char *title) { glfwSetWindowTitle(glfwWindow, title); }
    73  
    74 void Window::setVsync(bool on) {
    75 vsyncOn = on;
    76 glfwSwapInterval(on ? 1 : 0); // 1 = 画面の更新を待つ / 1 = wait for the display refresh
    77 }
    78  
    79 double Window::time() const { return glfwGetTime(); }
    80  
    81 float Window::aspect() const {
    82 // 最小化するとサイズが0になる / the size becomes 0 when minimised
    83 return fbHeight > 0 ? static_cast<float>(fbWidth) / static_cast<float>(fbHeight) : 1.0f;
    84 }
    85  
    86 bool Window::keyDown(int key) const { return glfwGetKey(glfwWindow, key) == GLFW_PRESS; }
    87 bool Window::mouseButtonDown(int button) const { return glfwGetMouseButton(glfwWindow, button) == GLFW_PRESS; }
    88  
    89 //------------------------------------------
    90 // GLFWのコールバック / GLFW callbacks
    91 //------------------------------------------
    92  
    93 static Window *self(GLFWwindow *w) { return static_cast<Window *>(glfwGetWindowUserPointer(w)); }
    94  
    95 void Window::framebufferSizeCallback(GLFWwindow *w, int width, int height) {
    96 Window *win = self(w);
    97 win->fbWidth = width;
    98 win->fbHeight = height;
    99 glViewport(0, 0, width, height); // 描画範囲をウィンドウに合わせる / draw into the whole window
    100 if (win->onResize) win->onResize(width, height);
    101 }
    102  
    103 void Window::keyCallback(GLFWwindow *w, int key, int /*scancode*/, int action, int mods) {
    104 Window *win = self(w);
    105 if (win->onKey) win->onKey(key, action, mods);
    106 }
    107  
    108 void Window::mouseButtonCallback(GLFWwindow *w, int button, int action, int mods) {
    109 Window *win = self(w);
    110 if (win->onMouseButton) win->onMouseButton(button, action, mods);
    111 }
    112  
    113 void Window::cursorPosCallback(GLFWwindow *w, double x, double y) {
    114 Window *win = self(w);
    115 win->cursorX = x;
    116 win->cursorY = y;
    117 if (win->onCursorPos) win->onCursorPos(x, y);
    118 }
    119  
    120 void Window::scrollCallback(GLFWwindow *w, double dx, double dy) {
    121 Window *win = self(w);
    122 if (win->onScroll) win->onScroll(dx, dy);
    123 }

ファイル: /dev/null | b/src/window.hh

前新
@@ -0,0 +1,72 @@
    1 // ウィンドウとOpenGLコンテキスト / the window and the OpenGL context
    2 #pragma once
    3  
    4 // GLADはGLFWより先にインクルードする / include GLAD before GLFW
    5 #include <glad/glad.h>
    6 #include <GLFW/glfw3.h>
    7  
    8 #include <functional>
    9  
    10 // GLFWウィンドウとOpenGLコンテキストを持つクラス(RAII)。
    11 // A GLFW window plus its OpenGL context (RAII).
    12 // 作ったGLオブジェクトはこのWindowより先に破棄すること(mainではWindowを最初に宣言する)。
    13 // GL objects must be destroyed before this Window (declare the Window first in main).
    14 class Window {
    15 public:
    16 Window() = default;
    17 ~Window();
    18  
    19 // GLFWがthisへのポインタを持つので、コピーも移動も禁止
    20 // GLFW keeps a pointer to this object, so it can be neither copied nor moved
    21 Window(const Window &) = delete;
    22 Window &operator=(const Window &) = delete;
    23  
    24 // ウィンドウとOpenGL 4.6コアのデバッグコンテキストを作る。失敗したらfalse。
    25 // Creates the window and an OpenGL 4.6 core debug context. Returns false on failure.
    26 bool create(int width, int height, const char *title);
    27  
    28 bool shouldClose() const;
    29 void close();
    30 void pollEvents(); // イベント処理(コールバックはここで呼ばれる) / process events (callbacks run here)
    31 void swapBuffers(); // 描いた画像を表示 / present the frame
    32  
    33 void setTitle(const char *title);
    34 void setVsync(bool on);
    35 bool vsync() const { return vsyncOn; }
    36  
    37 double time() const; // glfwInitからの秒数 / seconds since glfwInit
    38  
    39 // フレームバッファのサイズ(ピクセル)。高DPIではウィンドウサイズと違う。
    40 // Framebuffer size in pixels. On high-DPI screens it differs from the window size.
    41 int width() const { return fbWidth; }
    42 int height() const { return fbHeight; }
    43 float aspect() const; // 幅÷高さ / width ÷ height
    44  
    45 // ポーリング:今押されているか / polling: is it held down right now?
    46 bool keyDown(int key) const;
    47 bool mouseButtonDown(int button) const;
    48 double mouseX() const { return cursorX; } // ウィンドウ座標、左上が原点 / window coords, origin top-left
    49 double mouseY() const { return cursorY; }
    50  
    51 // コールバック(設定は任意) / callbacks (all optional)
    52 std::function<void(int key, int action, int mods)> onKey;
    53 std::function<void(int button, int action, int mods)> onMouseButton;
    54 std::function<void(double x, double y)> onCursorPos;
    55 std::function<void(double dx, double dy)> onScroll;
    56 std::function<void(int width, int height)> onResize;
    57  
    58 GLFWwindow *handle() const { return glfwWindow; }
    59  
    60 private:
    61 static void framebufferSizeCallback(GLFWwindow *w, int width, int height);
    62 static void keyCallback(GLFWwindow *w, int key, int scancode, int action, int mods);
    63 static void mouseButtonCallback(GLFWwindow *w, int button, int action, int mods);
    64 static void cursorPosCallback(GLFWwindow *w, double x, double y);
    65 static void scrollCallback(GLFWwindow *w, double dx, double dy);
    66  
    67 GLFWwindow *glfwWindow = nullptr;
    68 bool glfwStarted = false;
    69 int fbWidth = 0, fbHeight = 0;
    70 double cursorX = 0.0, cursorY = 0.0;
    71 bool vsyncOn = true;
    72 };


コメント(0)

まだコメントはありません。