diff --git a/CMakeLists.txt b/CMakeLists.txt index 8e20e56..7a7f90f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -34,7 +34,8 @@ add_executable(game src/file_util.cc src/shader.cc src/texture.cc - src/shapes.cc) + src/shapes.cc + src/camera.cc) target_include_directories(game PRIVATE src external/stb external/linalg) target_link_libraries(game PRIVATE glad stb_image glfw) diff --git a/assets/LICENSE.txt b/assets/LICENSE.txt index cfad344..e723aa4 100644 --- a/assets/LICENSE.txt +++ b/assets/LICENSE.txt @@ -5,3 +5,4 @@ which are not part of this project). Free to use for any purpose. textures/crate.png 木箱 / wooden crate textures/emblem.png 桜の紋章 / sakura emblem +textures/floor.png 石の床 / stone floor tiles diff --git a/assets/textures/floor.png b/assets/textures/floor.png new file mode 100644 index 0000000..d95a55c Binary files /dev/null and b/assets/textures/floor.png differ diff --git a/src/camera.cc b/src/camera.cc new file mode 100644 index 0000000..d9ab0d8 --- /dev/null +++ b/src/camera.cc @@ -0,0 +1,64 @@ +#include "camera.hh" + +#include +#include + +// ピッチの限界:±89度(真上を向くとlookAtのcross(前, 上)が0になる) +// pitch limit: ±89° (looking straight up makes lookAt's cross(forward, up) zero) +constexpr float kMaxPitch = radians(89.0f); +constexpr Vec3 kWorldUp = {0.0f, 1.0f, 0.0f}; + +//------------------------------------------ +// Camera(FPS) +//------------------------------------------ + +Vec3 Camera::front() const { + // 球面座標:yawで水平に回し、pitchで持ち上げる / spherical coordinates: yaw turns horizontally, pitch lifts + return {std::cos(pitch) * std::sin(yaw), std::sin(pitch), -std::cos(pitch) * std::cos(yaw)}; +} + +Vec3 Camera::right() const { return normalize(cross(front(), kWorldUp)); } + +void Camera::turn(float dxPixels, float dyPixels) { + yaw += dxPixels * sensitivity; + pitch -= dyPixels * sensitivity; // マウスのyは下向きが正 / mouse y grows downwards + pitch = std::clamp(pitch, -kMaxPitch, kMaxPitch); +} + +void Camera::move(Vec3 direction, float dt) { + if (length(direction) == 0.0f) return; + direction = normalize(direction); // 斜めでも速さは同じ / same speed diagonally + Vec3 velocity = direction.x * right() + direction.y * kWorldUp + direction.z * front(); + position = position + (speed * dt) * velocity; +} + +void Camera::zoom(float scrollSteps) { + fov = std::clamp(fov - radians(2.0f) * scrollSteps, radians(15.0f), radians(75.0f)); +} + +Mat4 Camera::view() const { return lookAt(position, position + front(), kWorldUp); } + +Mat4 Camera::projection(float aspect) const { return perspectiveGl(fov, aspect, nearPlane, farPlane); } + +//------------------------------------------ +// OrbitCamera +//------------------------------------------ + +Vec3 OrbitCamera::position() const { + Vec3 offset = {std::cos(pitch) * std::sin(yaw), std::sin(pitch), std::cos(pitch) * std::cos(yaw)}; + return target + distance * offset; +} + +void OrbitCamera::turn(float dxPixels, float dyPixels) { + yaw -= dxPixels * sensitivity; // 右へドラッグすると物が右へ回る / drag right and the object turns right + pitch = std::clamp(pitch + dyPixels * sensitivity, -kMaxPitch, kMaxPitch); +} + +void OrbitCamera::zoom(float scrollSteps) { + // 一段ごとに10%近づく(掛け算なので遠くでも近くでも同じ感覚) / 10% closer per step (multiplicative: feels the same near and far) + distance = std::clamp(distance * std::pow(0.9f, scrollSteps), 1.5f, 50.0f); +} + +Mat4 OrbitCamera::view() const { return lookAt(position(), target, kWorldUp); } + +Mat4 OrbitCamera::projection(float aspect) const { return perspectiveGl(fov, aspect, nearPlane, farPlane); } diff --git a/src/camera.hh b/src/camera.hh new file mode 100644 index 0000000..01549f6 --- /dev/null +++ b/src/camera.hh @@ -0,0 +1,51 @@ +// カメラ / cameras +#pragma once + +#include + +// 一人称(FPS)の飛べるカメラ。向きはヨー(左右)とピッチ(上下)で表す。 +// A first-person (FPS) fly camera. Its direction is yaw (left/right) and pitch (up/down). +class Camera { +public: + Vec3 position = {0.0f, 0.0f, 3.0f}; + float yaw = 0.0f; // ラジアン。0で-Zを向き、正で右へ回る / radians. 0 looks down -Z, positive turns right + float pitch = 0.0f; // ラジアン。正で上を向く / radians. positive looks up + float fov = radians(45.0f); // 縦の視野角 / vertical field of view + float nearPlane = 0.1f, farPlane = 100.0f; + float speed = 3.0f; // 単位毎秒 / units per second + float sensitivity = 0.0025f; // ラジアン毎ピクセル / radians per pixel of mouse movement + + Vec3 front() const; // 見ている方向(単位ベクトル) / the viewing direction (unit vector) + Vec3 right() const; // 右(水平) / right (horizontal) + + // マウスの移動量(ピクセル)で向きを変える。真上・真下は向けない。 + // Turns by a mouse movement in pixels. Cannot look straight up or down. + void turn(float dxPixels, float dyPixels); + // ローカルな方向(x = 右、y = 上、z = 前)に dt 秒だけ動く / moves for dt seconds in a local direction (x right, y up, z forward) + void move(Vec3 direction, float dt); + // ホイールで視野角を変える(ズーム) / changes the field of view with the scroll wheel (zoom) + void zoom(float scrollSteps); + + Mat4 view() const; + Mat4 projection(float aspect) const; +}; + +// 注視点の周りを回るカメラ(モデルビューアーやTPS向け)。 +// A camera that orbits a target point (for model viewers and third-person games). +class OrbitCamera { +public: + Vec3 target = {0.0f, 0.0f, 0.0f}; + float distance = 8.0f; + float yaw = 0.0f; // 0で+Z側から見る / 0 looks from the +Z side + float pitch = radians(20.0f); // 正で上から見る / positive looks from above + float fov = radians(45.0f); + float nearPlane = 0.1f, farPlane = 100.0f; + float sensitivity = 0.005f; + + Vec3 position() const; + void turn(float dxPixels, float dyPixels); + void zoom(float scrollSteps); // 距離を変える / changes the distance + + Mat4 view() const; + Mat4 projection(float aspect) const; +}; diff --git a/src/main.cc b/src/main.cc index b85710d..d23da29 100644 --- a/src/main.cc +++ b/src/main.cc @@ -1,11 +1,17 @@ -// 第8章:3Dへ:座標系と深度 -// Chapter 8: going 3D: coordinate systems and depth +// 第9章:カメラ +// Chapter 9: the camera // // 操作 / Controls: -// Z 深度テストの切り替え / toggle the depth test -// スペース 一時停止 / pause -// R シェーダーを読み直す / reload the shaders -// Esc 終了 / quit +// WASD 前後左右に移動 / move forward, back, left, right +// Space / Ctrl 上昇・下降 / move up / down +// Shift 速く動く / move faster +// マウス / mouse 向きを変える(FPS)、左ドラッグで回る(オービット) / look around (FPS), drag with the left button to orbit +// ホイール / wheel ズーム(FPSは視野角、オービットは距離) / zoom (FPS: field of view, orbit: distance) +// C FPS ⇔ オービットカメラ / FPS ⇔ orbit camera +// Tab カーソルのキャプチャ切り替え / toggle cursor capture +// R シェーダーを読み直す / reload the shaders +// Esc 終了 / quit +#include "camera.hh" #include "mesh.hh" #include "shader.hh" #include "shapes.hh" @@ -17,86 +23,115 @@ #include #include -// 立方体の位置と回転軸 / where each cube is and the axis it spins around -struct CubeInfo { +// 床に置いた箱:位置(底の中心)、大きさ、Y軸周りの回転 / crates on the floor: position (bottom centre), size, yaw +struct CrateInfo { Vec3 position; - Vec3 axis; - float speed; // ラジアン毎秒 / radians per second + float size; + float angle; }; -static const CubeInfo kCubes[] = { - {{0.0f, 0.0f, 0.0f}, {0.3f, 1.0f, 0.2f}, 0.6f}, - {{2.4f, 1.2f, -3.5f}, {1.0f, 0.3f, 0.0f}, 0.9f}, - {{-2.2f, -1.0f, -2.5f}, {0.0f, 1.0f, 0.6f}, -0.7f}, - {{-3.8f, 1.6f, -7.0f}, {0.5f, 0.5f, 0.1f}, 0.5f}, - {{2.6f, -1.3f, -1.2f}, {0.2f, 0.4f, 1.0f}, -1.1f}, - {{-1.3f, 2.0f, -4.0f}, {1.0f, 0.0f, 0.4f}, 0.8f}, - {{1.0f, -0.6f, -6.5f}, {0.7f, 1.0f, 0.3f}, -0.5f}, - {{4.8f, 0.4f, -8.5f}, {0.1f, 1.0f, 0.9f}, 1.2f}, - {{-4.4f, -1.5f, -5.5f}, {0.9f, 0.2f, 0.6f}, -0.9f}, - {{0.4f, 2.6f, -9.5f}, {0.4f, 0.8f, 1.0f}, 0.7f}, +static const CrateInfo kCrates[] = { + {{0.0f, 0.0f, 0.0f}, 1.0f, 0.0f}, {{1.1f, 0.0f, 0.2f}, 1.0f, 0.3f}, + {{0.5f, 1.0f, 0.1f}, 1.0f, -0.2f}, {{-3.0f, 0.0f, -2.0f}, 2.0f, 0.6f}, + {{-3.0f, 2.0f, -2.0f}, 1.0f, 0.1f}, {{4.0f, 0.0f, -4.0f}, 1.5f, -0.5f}, + {{-6.0f, 0.0f, 3.0f}, 1.0f, 0.9f}, {{6.5f, 0.0f, 2.5f}, 1.0f, 0.2f}, + {{2.0f, 0.0f, -9.0f}, 3.0f, 0.4f}, {{-8.0f, 0.0f, -8.0f}, 2.0f, -0.3f}, + {{9.0f, 0.0f, -12.0f}, 2.5f, 0.7f}, {{-2.5f, 0.0f, 5.5f}, 0.6f, 0.5f}, }; int main() { Window window; - if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 8")) return 1; + if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 9")) return 1; std::optional shader = Shader::load("shaders/textured.vert", "shaders/textured.frag"); std::optional crate = Texture2D::load("assets/textures/crate.png"); std::optional emblem = Texture2D::load("assets/textures/emblem.png"); - if (!shader || !crate || !emblem) return 1; - - // 近いものが遠いものを隠すようにする / make near things hide far things - bool depthTest = true; + std::optional floorTexture = Texture2D::load("assets/textures/floor.png"); + if (!shader || !crate || !emblem || !floorTexture) return 1; glEnable(GL_DEPTH_TEST); - bool paused = false; + Camera fps; + fps.position = {0.0f, 1.6f, 7.0f}; // 目の高さ / eye height + fps.pitch = radians(-8.0f); + + OrbitCamera orbit; + orbit.target = {0.0f, 0.8f, 0.0f}; + orbit.distance = 9.0f; + orbit.yaw = radians(30.0f); + + bool useOrbit = false; + window.setCursorCaptured(true); // FPSはカーソルを隠して固定 / FPS: hide and lock the cursor + window.onKey = [&](int key, int action, int /*mods*/) { if (action != GLFW_PRESS) return; if (key == GLFW_KEY_ESCAPE) window.close(); - if (key == GLFW_KEY_SPACE) paused = !paused; if (key == GLFW_KEY_R && shader->reload()) printf("シェーダーを読み直した / shaders reloaded\n"); - if (key == GLFW_KEY_Z) { - depthTest = !depthTest; - if (depthTest) - glEnable(GL_DEPTH_TEST); - else - glDisable(GL_DEPTH_TEST); - printf("depth test %s\n", depthTest ? "on" : "off"); + if (key == GLFW_KEY_TAB) window.setCursorCaptured(!window.cursorCaptured()); + if (key == GLFW_KEY_C) { + useOrbit = !useOrbit; + // オービットはマウスでドラッグするのでカーソルを見せる / orbit is dragged with the mouse, so show the cursor + window.setCursorCaptured(!useOrbit); + printf("camera: %s\n", useOrbit ? "orbit" : "fps"); } }; Mesh cube = makeCube(); + // 40×40の床。テクスチャにタイル4枚なので10回繰り返すと1タイル = 1単位 + // A 40 × 40 floor. The texture holds 4 tiles, so repeating it 10 times makes one tile = one unit + Mesh floorMesh = makePlane(40.0f, 10.0f); - float t = 0.0f; double lastTime = window.time(); while (!window.shouldClose()) { double now = window.time(); float dt = static_cast(now - lastTime); lastTime = now; window.pollEvents(); - if (!paused) t += dt; + + Vec2 mouse = window.mouseDelta(); + if (useOrbit) { + if (window.mouseButtonDown(GLFW_MOUSE_BUTTON_LEFT)) orbit.turn(mouse.x, mouse.y); + orbit.zoom(window.scrollDelta()); + } else { + if (window.cursorCaptured()) fps.turn(mouse.x, mouse.y); + fps.zoom(window.scrollDelta()); + + // キーからローカルな移動方向を作る(x = 右、y = 上、z = 前) / build a local direction from the keys + Vec3 dir; + if (window.keyDown(GLFW_KEY_W)) dir.z += 1.0f; + if (window.keyDown(GLFW_KEY_S)) dir.z -= 1.0f; + if (window.keyDown(GLFW_KEY_D)) dir.x += 1.0f; + if (window.keyDown(GLFW_KEY_A)) dir.x -= 1.0f; + if (window.keyDown(GLFW_KEY_SPACE)) dir.y += 1.0f; + if (window.keyDown(GLFW_KEY_LEFT_CONTROL)) dir.y -= 1.0f; + fps.speed = window.keyDown(GLFW_KEY_LEFT_SHIFT) ? 9.0f : 3.0f; + // dtを掛けるのでフレームレートに関係なく同じ速さ / multiplied by dt: the same speed at any frame rate + fps.move(dir, dt); + } + + Mat4 view = useOrbit ? orbit.view() : fps.view(); + Mat4 proj = useOrbit ? orbit.projection(window.aspect()) : fps.projection(window.aspect()); glClearColor(0.10f, 0.15f, 0.25f, 1.0f); - // 色と深度の両方を毎フレーム消す / clear both colour and depth every frame glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - // ビュー:カメラは(0, 1.5, 6)から少し奥を見る / view: the camera at (0, 1.5, 6) looks a little into the scene - Mat4 view = lookAt({0.0f, 1.5f, 6.0f}, {0.0f, 0.0f, -2.0f}, {0.0f, 1.0f, 0.0f}); - // 投影:縦の視野角45度。アスペクト比は毎フレーム読むので、ウィンドウを変えても歪まない。 - // projection: 45° vertical field of view. The aspect ratio is read every frame, so resizing does not distort. - Mat4 proj = perspectiveGl(radians(45.0f), window.aspect(), 0.1f, 100.0f); - - crate->bind(0); - emblem->bind(1); shader->use(); - shader->set("uMix", 0.8f); - shader->set("uEmblemScale", 1.0f); shader->set("uView", view); shader->set("uProj", proj); + shader->set("uEmblemScale", 1.0f); - for (const CubeInfo &c : kCubes) { - shader->set("uModel", translate(c.position) * rotate(c.axis, t * c.speed + c.position.x)); + // 床:二枚目のテクスチャは混ぜない / the floor: no second texture + floorTexture->bind(0); + emblem->bind(1); + shader->set("uMix", 0.0f); + shader->set("uModel", Mat4::identity()); + floorMesh.draw(); + + // 箱:立方体は原点が中心なので半分持ち上げて床に置く / crates: the cube is centred, so lift it by half its size + crate->bind(0); + shader->set("uMix", 0.8f); + for (const CrateInfo &c : kCrates) { + Vec3 centre = c.position + Vec3{0.0f, 0.5f * c.size, 0.0f}; + shader->set("uModel", translate(centre) * rotateY(c.angle) * scale({c.size, c.size, c.size})); cube.draw(); } diff --git a/src/shapes.cc b/src/shapes.cc index 1f98689..d340eff 100644 --- a/src/shapes.cc +++ b/src/shapes.cc @@ -28,3 +28,16 @@ Mesh makeCube() { addFace(vertices, indices, {0, -1, 0}, {1, 0, 0}, {0, 0, 1}); // 下 -Y / bottom return Mesh(vertices, indices, kVertex3DLayout); } + +Mesh makePlane(float size, float uvRepeat) { + float h = 0.5f * size; + Vec3 n = {0.0f, 1.0f, 0.0f}; + // 上から見て反時計回り / counter-clockwise seen from above + std::vector vertices = { + {{-h, 0.0f, h}, n, {0.0f, 0.0f}}, + {{h, 0.0f, h}, n, {uvRepeat, 0.0f}}, + {{h, 0.0f, -h}, n, {uvRepeat, uvRepeat}}, + {{-h, 0.0f, -h}, n, {0.0f, uvRepeat}}, + }; + return Mesh(vertices, {0, 1, 2, 2, 3, 0}, kVertex3DLayout); +} diff --git a/src/shapes.hh b/src/shapes.hh index 9ec5c68..f9bdf1f 100644 --- a/src/shapes.hh +++ b/src/shapes.hh @@ -8,3 +8,7 @@ // A 1×1×1 cube centred on the origin. 4 vertices per face (UVs and normals differ per face, so corners // cannot be shared) = 24 vertices, 36 indices. Counter-clockwise seen from outside (for culling in chapter 16). Mesh makeCube(); + +// XZ平面上のsize×sizeの床(y = 0、法線は+Y)。UVはuvRepeat回繰り返す(GL_REPEATが必要)。 +// A size × size floor on the XZ plane (y = 0, normal +Y). UVs repeat uvRepeat times (needs GL_REPEAT). +Mesh makePlane(float size, float uvRepeat); diff --git a/src/window.cc b/src/window.cc index cf1ced1..dc1dc50 100644 --- a/src/window.cc +++ b/src/window.cc @@ -67,7 +67,20 @@ bool Window::create(int width, int height, const char *title) { bool Window::shouldClose() const { return glfwWindowShouldClose(glfwWindow); } void Window::close() { glfwSetWindowShouldClose(glfwWindow, GLFW_TRUE); } -void Window::pollEvents() { glfwPollEvents(); } +void Window::pollEvents() { + // 今回のフレームの分を数え直す(コールバックで足していく) / start counting this frame (the callbacks add to these) + frameMouseDelta = {0.0f, 0.0f}; + frameScroll = 0.0f; + glfwPollEvents(); +} + +void Window::setCursorCaptured(bool on) { + captured = on; + glfwSetInputMode(glfwWindow, GLFW_CURSOR, on ? GLFW_CURSOR_DISABLED : GLFW_CURSOR_NORMAL); + // OSのマウス加速なしの生の動き(使えれば) / raw motion without OS mouse acceleration (if available) + if (glfwRawMouseMotionSupported()) glfwSetInputMode(glfwWindow, GLFW_RAW_MOUSE_MOTION, on ? GLFW_TRUE : GLFW_FALSE); + skipNextDelta = true; +} void Window::swapBuffers() { glfwSwapBuffers(glfwWindow); } void Window::setTitle(const char *title) { glfwSetWindowTitle(glfwWindow, title); } @@ -112,6 +125,11 @@ void Window::mouseButtonCallback(GLFWwindow *w, int button, int action, int mods void Window::cursorPosCallback(GLFWwindow *w, double x, double y) { Window *win = self(w); + if (!win->skipNextDelta) { + win->frameMouseDelta.x += static_cast(x - win->cursorX); + win->frameMouseDelta.y += static_cast(y - win->cursorY); + } + win->skipNextDelta = false; win->cursorX = x; win->cursorY = y; if (win->onCursorPos) win->onCursorPos(x, y); @@ -119,5 +137,6 @@ void Window::cursorPosCallback(GLFWwindow *w, double x, double y) { void Window::scrollCallback(GLFWwindow *w, double dx, double dy) { Window *win = self(w); + win->frameScroll += static_cast(dy); if (win->onScroll) win->onScroll(dx, dy); } diff --git a/src/window.hh b/src/window.hh index c86ad98..d75aa00 100644 --- a/src/window.hh +++ b/src/window.hh @@ -4,6 +4,7 @@ // GLADはGLFWより先にインクルードする / include GLAD before GLFW #include #include +#include #include @@ -48,6 +49,15 @@ public: double mouseX() const { return cursorX; } // ウィンドウ座標、左上が原点 / window coords, origin top-left double mouseY() const { return cursorY; } + // 前のpollEvents()から今回までのマウスの移動量とホイールの回転量 / mouse movement and scroll since the last pollEvents() + Vec2 mouseDelta() const { return frameMouseDelta; } + float scrollDelta() const { return frameScroll; } + + // カーソルを隠して固定する(FPSカメラ用)。移動量は無制限に取れる。 + // Hides and locks the cursor (for FPS cameras). Movement is then unlimited. + void setCursorCaptured(bool captured); + bool cursorCaptured() const { return captured; } + // コールバック(設定は任意) / callbacks (all optional) std::function onKey; std::function onMouseButton; @@ -68,5 +78,9 @@ private: bool glfwStarted = false; int fbWidth = 0, fbHeight = 0; double cursorX = 0.0, cursorY = 0.0; + Vec2 frameMouseDelta; + float frameScroll = 0.0f; + bool captured = false; + bool skipNextDelta = true; // 最初とキャプチャ切り替え直後の飛びを無視 / ignore the jump at start and after (un)capturing bool vsyncOn = true; };