sdl3_3d_oop_basic_game git · main
SDL3 3D OOP basic game (entities, systems, CMake)
C++ 99%git clone https://git.christianimmanuel.de/sdl-graphics/sdl3_3d_oop_basic_game.gitwget https://git.christianimmanuel.de/sdl-graphics/sdl3_3d_oop_basic_game/archive/sdl3_3d_oop_basic_game.tar.gzinit
.gitignore | 1 + CMakeLists.txt | 40 +++++++++++ README.md | 3 + camera.hpp | 43 ++++++++++++ config.hpp | 7 ++ game.cpp | 91 +++++++++++++++++++++++++ game.hpp | 38 +++++++++++ input_system.cpp | 22 ++++++ input_system.hpp | 8 +++ main.cpp | 71 +++++++++++++++++++ math.hpp | 8 +++ physics_system.cpp | 26 +++++++ physics_system.hpp | 7 ++ player.cpp | 66 ++++++++++++++++++ player.hpp | 57 ++++++++++++++++ world.cpp | 195 +++++++++++++++++++++++++++++++++++++++++++++++++++++ world.hpp | 40 +++++++++++ 17 files changed, 723 insertions(+) diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..378eac2 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +build diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..9889770 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,40 @@ +cmake_minimum_required(VERSION 3.20) + +project(idk_game LANGUAGES CXX) + +set(CMAKE_CXX_STANDARD 23) +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +find_package(SDL3 REQUIRED) + +add_executable(idk_game + main.cpp + game.cpp + input_system.cpp + physics_system.cpp + player.cpp + world.cpp +) + +target_compile_options(idk_game PRIVATE + -Wall + -Wextra + -Wshadow + -Wconversion + -Wsign-conversion + -Wnull-dereference + -Wdouble-promotion +) + +target_link_libraries(idk_game PRIVATE SDL3::SDL3) + +# cmake -B build -DCMAKE_BUILD_TYPE=Debug +target_compile_options(idk_game PRIVATE + $<$<CONFIG:Debug>:-fsanitize=address> + $<$<CONFIG:Debug>:-fno-omit-frame-pointer> + $<$<CONFIG:Debug>:-g> +) + +target_link_options(idk_game PRIVATE + $<$<CONFIG:Debug>:-fsanitize=address> +) diff --git a/README.md b/README.md new file mode 100644 index 0000000..18dac4d --- /dev/null +++ b/README.md @@ -0,0 +1,3 @@ +# SDL3 CPP 3D OOP Game + +i modified the [sdl3 02-woodeneye-008 demo](https://examples.libsdl.org/SDL3/demo/02-woodeneye-008/) to Object-Oriented CPP diff --git a/camera.hpp b/camera.hpp new file mode 100644 index 0000000..d5fccfc --- /dev/null +++ b/camera.hpp @@ -0,0 +1,43 @@ +#pragma once + +#include <SDL3/SDL.h> + +#include "math.hpp" +#include "player.hpp" + +struct Camera { + Vec3 pos{}; + uint32_t yaw{}; + int32_t pitch{}; + void syncFromPlayer(const Player& player, double alpha) + { + pos = player.interpolatedPos(alpha); + yaw = player.yaw; + pitch = player.pitch; + } +}; + +inline void buildViewMatrix(const Camera& cam, double out[9]) +{ + double bin = SDL_PI_D / 2147483648.0; + + double yaw = bin * cam.yaw; + double pitch = bin * cam.pitch; + + double cy = SDL_cos(yaw); + double sy = SDL_sin(yaw); + double cp = SDL_cos(pitch); + double sp = SDL_sin(pitch); + + out[0] = cy; + out[1] = 0; + out[2] = -sy; + + out[3] = sy * sp; + out[4] = cp; + out[5] = cy * sp; + + out[6] = sy * cp; + out[7] = -sp; + out[8] = cy * cp; +} diff --git a/config.hpp b/config.hpp new file mode 100644 index 0000000..66028e2 --- /dev/null +++ b/config.hpp @@ -0,0 +1,7 @@ +#pragma once + +static constexpr double +FIXED_DT = 1.0 / 60.0; + +static constexpr int +MAX_SUBSTEPS = 4; diff --git a/game.cpp b/game.cpp new file mode 100644 index 0000000..f245a2b --- /dev/null +++ b/game.cpp @@ -0,0 +1,91 @@ +#include "game.hpp" +#include "config.hpp" + +bool Game::init() +{ + m_state.player = Player{}; + m_state.world = World{}; + + if (!SDL_Init(SDL_INIT_VIDEO)) { + return false; + } + + if (!SDL_CreateWindowAndRenderer( + "game", + 640, 480, + SDL_WINDOW_RESIZABLE, + &m_state.window, + &m_state.renderer)) { + return false; + } + + SDL_SetRenderVSync(m_state.renderer, false); + SDL_SetWindowRelativeMouseMode(m_state.window, true); + + return true; +} + +void Game::handleEvent(const SDL_Event& event) +{ + if (event.type == SDL_EVENT_QUIT) + return; + + m_input.handleEvent(event, m_state.input, m_state.player); +} + +void Game::update(double dt_ns) +{ + double dt = dt_ns * 1e-9; + + m_state.accumulator += dt; + + m_state.player.computeMovement(m_state.input); + + int steps = 0; + + while (m_state.accumulator >= FIXED_DT && steps < MAX_SUBSTEPS) { + m_state.player.prev_pos = m_state.player.pos; + + if (m_state.player.jump_pressed && m_state.player.on_ground) { + m_state.player.vel.y = 8.4375; + m_state.player.on_ground = false; + } + + m_state.player.jump_pressed = false; + + m_physics.update( + m_state.player, + m_state.player.getAccX(), + m_state.player.getAccZ(), + FIXED_DT + ); + + PlayerCollision col = m_state.world.resolvePlayer(m_state.player); + m_state.player.applyCollision(col); + + m_state.accumulator -= FIXED_DT; + steps++; + } + + m_state.accumulator = SDL_min(m_state.accumulator, FIXED_DT * MAX_SUBSTEPS); + + m_state.alpha = m_state.accumulator / FIXED_DT; + + m_state.camera.syncFromPlayer(m_state.player, m_state.alpha); +} + +void Game::render() +{ + auto& as = m_state; + + as.camera.syncFromPlayer(as.player, as.alpha); + + as.world.draw(as.renderer, as.camera); + SDL_RenderPresent(as.renderer); +} + +AppState& Game::state() +{ return m_state; } + +void Game::shutdown() +{ } diff --git a/game.hpp b/game.hpp new file mode 100644 index 0000000..293b491 --- /dev/null +++ b/game.hpp @@ -0,0 +1,38 @@ +#pragma once + +#include <SDL3/SDL.h> + +#include "input_system.hpp" +#include "physics_system.hpp" +#include "world.hpp" +#include "player.hpp" + +struct AppState { + SDL_Window* window{}; + SDL_Renderer* renderer{}; + + Player player{}; + PlayerInputState input{}; + Camera camera{}; + World world{}; + + double accumulator{}; + double alpha{}; +}; + +class Game { +public: + bool init(); + void handleEvent(const SDL_Event& event); + void update(double dt_ns); + void render(); + + AppState& state(); + + void shutdown(); + +private: + AppState m_state{}; + InputSystem m_input; + PhysicsSystem m_physics; +}; diff --git a/input_system.cpp b/input_system.cpp new file mode 100644 index 0000000..d4ca304 --- /dev/null +++ b/input_system.cpp @@ -0,0 +1,22 @@ +#include "input_system.hpp" + +void InputSystem::handleEvent(const SDL_Event& e, PlayerInputState& input, Player& player) +{ + switch (e.type) { + case SDL_EVENT_MOUSE_MOTION: + player.addLook((int)e.motion.xrel, (int)e.motion.yrel); + break; + case SDL_EVENT_KEY_DOWN: + case SDL_EVENT_KEY_UP: { + bool down = (e.type == SDL_EVENT_KEY_DOWN); + SDL_Keycode sym = e.key.key; + + if (sym == SDLK_W) input.forward = down; + if (sym == SDLK_A) input.left = down; + if (sym == SDLK_S) input.backward = down; + if (sym == SDLK_D) input.right = down; + if (sym == SDLK_SPACE && down) player.jump_pressed = true; + break; + } + } +} diff --git a/input_system.hpp b/input_system.hpp new file mode 100644 index 0000000..2c8e219 --- /dev/null +++ b/input_system.hpp @@ -0,0 +1,8 @@ +#pragma once +#include <SDL3/SDL.h> +#include "player.hpp" + +class InputSystem { +public: + void handleEvent(const SDL_Event& e, PlayerInputState& input, Player& player); +}; diff --git a/main.cpp b/main.cpp new file mode 100644 index 0000000..e9f757b --- /dev/null +++ b/main.cpp @@ -0,0 +1,71 @@ +#define SDL_MAIN_USE_CALLBACKS 1 +#include <SDL3/SDL.h> +#include <SDL3/SDL_main.h> + +#include "config.hpp" +#include "math.hpp" +#include "game.hpp" +#include "world.hpp" +#include "player.hpp" + + +static const struct { + const char *key; + const char *value; +} extended_metadata[] = { + { SDL_PROP_APP_METADATA_CREATOR_STRING, "Nimbin" }, + { SDL_PROP_APP_METADATA_COPYRIGHT_STRING, "Placed in the public domain" }, + { SDL_PROP_APP_METADATA_TYPE_STRING, "game" } +}; + +static Game game; + + +SDL_AppResult SDL_AppInit(void** appstate, int argc, char* argv[]) +{ + (void)argc; (void) argv; + + if (!game.init()) { + return SDL_APP_FAILURE; + } + + *appstate = &game; + + return SDL_APP_CONTINUE; +} + +SDL_AppResult SDL_AppEvent(void* appstate, SDL_Event* event) +{ + Game* game_ = static_cast<Game*>(appstate); + + if (event->type == SDL_EVENT_QUIT) + return SDL_APP_SUCCESS; + + game_->handleEvent(*event); + return SDL_APP_CONTINUE; +} + +SDL_AppResult SDL_AppIterate(void* appstate) +{ + Game* game_ = static_cast<Game*>(appstate); + + static Uint64 past = SDL_GetTicksNS(); + + Uint64 now = SDL_GetTicksNS(); + Uint64 dt_ns = now - past; + past = now; + + game_->update(static_cast<double>(dt_ns)); + + game_->render(); + + return SDL_APP_CONTINUE; +} + +void SDL_AppQuit(void* appstate, SDL_AppResult result) +{ + (void)result; + Game* game_ = static_cast<Game*>(appstate); + game_->shutdown(); +} + diff --git a/math.hpp b/math.hpp new file mode 100644 index 0000000..9981861 --- /dev/null +++ b/math.hpp @@ -0,0 +1,8 @@ +#pragma once + +struct Vec3 { + double x{}, y{}, z{}; + + Vec3() = default; + Vec3(double x_, double y_, double z_) : x(x_), y(y_), z(z_) {} +}; diff --git a/physics_system.cpp b/physics_system.cpp new file mode 100644 index 0000000..f45fddd --- /dev/null +++ b/physics_system.cpp @@ -0,0 +1,26 @@ +#include "physics_system.hpp" +#include <SDL3/SDL.h> + +void PhysicsSystem::update(Player& p, double acc_x, double acc_z, double dt) { + dt = SDL_min(dt, 1.0 / 30.0); + + double rate = 6.0; + double drag = SDL_exp(-dt * rate); + double diff = 1.0 - drag; + double grav = 25.0; + + double vx = p.vel.x; + double vy = p.vel.y; + double vz = p.vel.z; + + p.vel.x -= vx * diff; + p.vel.y -= grav * dt; + p.vel.z -= vz * diff; + + p.vel.x += diff * acc_x / rate; + p.vel.z += diff * acc_z / rate; + + p.pos.x += (dt - diff/rate) * acc_x / rate + diff * vx / rate; + p.pos.y += -0.5 * grav * dt * dt + vy * dt; + p.pos.z += (dt - diff/rate) * acc_z / rate + diff * vz / rate; +} diff --git a/physics_system.hpp b/physics_system.hpp new file mode 100644 index 0000000..0f2ad93 --- /dev/null +++ b/physics_system.hpp @@ -0,0 +1,7 @@ +#pragma once +#include "player.hpp" + +class PhysicsSystem { +public: + void update(Player& player, double acc_x, double acc_z, double dt); +}; diff --git a/player.cpp b/player.cpp new file mode 100644 index 0000000..84fb27d --- /dev/null +++ b/player.cpp @@ -0,0 +1,66 @@ +#include "player.hpp" + + +Player::Player() + : pos{8.0, 0.0, 8.0}, + vel{0.0, 0.0, 0.0}, + yaw(0x20000000), + pitch(-0x08000000), + radius(0.5f), + height(1.5f) +{} + +void Player::applyCollision(const PlayerCollision& col) +{ + pos = col.pos; + vel = col.vel; + on_ground = col.hit_y; +} + + +void Player::respawn(const Vec3& spawn_pos) +{ + pos = spawn_pos; + vel = {0.0, 0.0, 0.0}; +} + +void Player::addLook(int dx, int dy) +{ + int32_t delta = dx * 0x00080000; + int32_t y = static_cast<int32_t>(yaw) - delta; + + yaw = static_cast<uint32_t>(y); + pitch = SDL_max(-0x40000000, SDL_min(0x40000000, pitch - dy * 0x00080000)); +} + +void Player::computeMovement(const PlayerInputState& input) +{ + double rad = (double)yaw * SDL_PI_D / 2147483648.0; + double c = SDL_cos(rad); + double s = SDL_sin(rad); + + double dirX = (input.right ? 1.0 : 0.0) - (input.left ? 1.0 : 0.0); + double dirZ = (input.backward ? 1.0 : 0.0) - (input.forward ? 1.0 : 0.0); + + double n = dirX * dirX + dirZ * dirZ; + + acc_x = 0; + acc_z = 0; + + if (n != 0) { + double inv = 1.0 / SDL_sqrt(n); + double mult = 60.0; + + acc_x = mult * ( c*dirX + s*dirZ) * inv; + acc_z = mult * (-s*dirX + c*dirZ) * inv; + } +} + +Vec3 Player::interpolatedPos(double alpha) const +{ + return { + prev_pos.x + (pos.x - prev_pos.x) * alpha, + prev_pos.y + (pos.y - prev_pos.y) * alpha, + prev_pos.z + (pos.z - prev_pos.z) * alpha + }; +} diff --git a/player.hpp b/player.hpp new file mode 100644 index 0000000..431a5f0 --- /dev/null +++ b/player.hpp @@ -0,0 +1,57 @@ +#pragma once + +#include <SDL3/SDL.h> + +#include "math.hpp" + +struct PlayerInputState +{ + bool forward{}; + bool left{}; + bool backward{}; + bool right{}; +}; + +struct PlayerCollision +{ + Vec3 pos{}; + Vec3 vel{}; + bool hit_x{}; + bool hit_y{}; + bool hit_z{}; +}; + +struct Player +{ +public: + Player(); + + Vec3 pos{}; + Vec3 prev_pos{}; + Vec3 vel{}; + + uint32_t yaw{}; + int32_t pitch{}; + + float radius{0.5f}; + float height{1.5f}; + + bool on_ground{false}; + bool jump_pressed{false}; + + void computeMovement(const PlayerInputState& input); + void addLook(int dx, int dy); + + void applyCollision(const PlayerCollision& col); + + Vec3 interpolatedPos(double alpha) const; + + double getAccX() const { return acc_x; } + double getAccZ() const { return acc_z; } + + void respawn(const Vec3& spawn_pos); + +private: + double acc_x{}; + double acc_z{}; +}; diff --git a/world.cpp b/world.cpp new file mode 100644 index 0000000..b741a65 --- /dev/null +++ b/world.cpp @@ -0,0 +1,195 @@ +#include "world.hpp" + +World::World() +{ + initEdges(); +} + +void World::initEdges() +{ + const float r = world_scale; + + const int map[24] = { + 0,1 , 1,3 , 3,2 , 2,0 , + 7,6 , 6,4 , 4,5 , 5,7 , + 6,2 , 3,7 , 0,4 , 5,1 + }; + + for (size_t i = 0; i < 12; i++) { + Vec3 a, b; + + for (int j = 0; j < 3; j++) { + float va = (map[i*2+0] & (1 << j)) ? r : -r; + float vb = (map[i*2+1] & (1 << j)) ? r : -r; + + if (j == 0) { a.x = va; b.x = vb; } + if (j == 1) { a.y = va; b.y = vb; } + if (j == 2) { a.z = va; b.z = vb; } + } + + edges[i] = { a, b }; + } + + size_t scale = static_cast<size_t>(world_scale); + for (size_t i = 0; i < scale; i++) { + float d = static_cast<float>(i * 2) - world_scale; + + // line z axis + edges[12 + i] = { + { -r, -r, d }, + { r, -r, d } + }; + + // line x axis + edges[12 + scale + i] = { + { d, -r, -r }, + { d, -r, r } + }; + } +} + + +static double sweepAxis(double end, double min, double max, bool& hit) +{ + hit = false; + + if (end < min) { + hit = true; + return min; + } + + if (end > max) { + hit = true; + return max; + } + + return end; +} + +PlayerCollision World::resolvePlayer(const Player& player) const +{ + PlayerCollision out; + out.vel = player.vel; + + const double min = -world_scale + player.radius; + const double max = world_scale - player.radius; + + const double minY = player.height - world_scale; + const double maxY = world_scale; + + out.pos.x = sweepAxis(player.pos.x, min, max, out.hit_x); + out.pos.y = sweepAxis(player.pos.y, minY, maxY, out.hit_y); + out.pos.z = sweepAxis(player.pos.z, min, max, out.hit_z); + + if (out.hit_x) out.vel.x = 0; + if (out.hit_y) out.vel.y = 0; + if (out.hit_z) out.vel.z = 0; + + return out; +} + + +static void drawClippedSegment( + SDL_Renderer *renderer, + float ax, float ay, float az, + float bx, float by, float bz, + float x, float y, float z, float w) +{ + if (az >= -w && bz >= -w) return; + + float dx = ax - bx; + float dy = ay - by; + + if (az > -w) { + float t = (-w - bz) / (az - bz); + ax = bx + dx * t; + ay = by + dy * t; + az = -w; + } else if (bz > -w) { + float t = (-w - az) / (bz - az); + bx = ax - dx * t; + by = ay - dy * t; + bz = -w; + } + + ax = -z * ax / az; + ay = -z * ay / az; + bx = -z * bx / bz; + by = -z * by / bz; + + SDL_RenderLine(renderer, x + ax, y - ay, x + bx, y - by); +} + +static Vec3 toCameraSpace(const Vec3& p, const double mat[9]) +{ + Vec3 out; + out.x = mat[0] * p.x + mat[1] * p.y + mat[2] * p.z; + out.y = mat[3] * p.x + mat[4] * p.y + mat[5] * p.z; + out.z = mat[6] * p.x + mat[7] * p.y + mat[8] * p.z; + return out; +} + +void World::draw(SDL_Renderer* renderer, const Camera& camera) const +{ + int w, h; + if (!SDL_GetRenderOutputSize(renderer, &w, &h)) { + return; + } + SDL_SetRenderDrawColor(renderer, 0, 0, 0, SDL_ALPHA_OPAQUE); + SDL_RenderClear(renderer); + float wf = (float)w; + float hf = (float)h; + int part_hor = 1; + int part_ver = 1; + float size_hor = wf / (static_cast<float>(part_hor)); + float size_ver = hf / (static_cast<float>(part_ver)); + float hor_origin = size_hor * 0.5f; + float ver_origin = size_ver * 0.5f; + float cam_origin = 0.5f * static_cast<float>(SDL_sqrt(size_hor * size_hor + size_ver * size_ver)); + float hor_offset = 0.0f; + float ver_offset = 0.0f; + SDL_Rect rect; + rect.x = static_cast<int>(hor_offset); + rect.y = static_cast<int>(ver_offset); + rect.w = static_cast<int>(size_hor); + rect.h = static_cast<int>(size_ver); + SDL_SetRenderClipRect(renderer, &rect); + double x0 = camera.pos.x; + double y0 = camera.pos.y; + double z0 = camera.pos.z; + + double mat[9]; + buildViewMatrix(camera, mat); + + SDL_SetRenderDrawColor(renderer, 64, 64, 64, 255); + + for (size_t k = 0; k < MAP_BOX_EDGES_LEN; k++) { + const Edge& e = edges[k]; + + Vec3 a = { e.a.x - x0, e.a.y - y0, e.a.z - z0 }; + Vec3 b = { e.b.x - x0, e.b.y - y0, e.b.z - z0 }; + + Vec3 ca = toCameraSpace(a, mat); + Vec3 cb = toCameraSpace(b, mat); + + drawClippedSegment( + renderer, + static_cast<float>(ca.x), static_cast<float>(ca.y), static_cast<float>(ca.z), + static_cast<float>(cb.x), static_cast<float>(cb.y), static_cast<float>(cb.z), + hor_origin, ver_origin, cam_origin, 1 + ); + } + + SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255); + SDL_RenderLine(renderer, hor_origin, ver_origin-10, hor_origin, ver_origin+10); + SDL_RenderLine(renderer, hor_origin-10, ver_origin, hor_origin+10, ver_origin); + + SDL_SetRenderClipRect(renderer, NULL); + SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255); +} + +Vec3 World::spawnPoint() const +{ return {0.0, 2.0, 0.0}; } + +float World::scale() const +{ return world_scale; } diff --git a/world.hpp b/world.hpp new file mode 100644 index 0000000..cf6ab44 --- /dev/null +++ b/world.hpp @@ -0,0 +1,40 @@ +#pragma once + +#include <array> + +#include "player.hpp" +#include "camera.hpp" + +#define MAP_BOX_SCALE 16 +#define MAP_BOX_EDGES_LEN (12 + MAP_BOX_SCALE * 2) + +struct Edge { + Vec3 a; + Vec3 b; +}; + +struct SweepResult { + Vec3 pos; + Vec3 vel; + bool hit_x{}; + bool hit_y{}; + bool hit_z{}; +}; + +class World { +public: + World(); + + PlayerCollision resolvePlayer(const Player& player) const; + + void draw(SDL_Renderer* renderer, const Camera& camera) const; + + Vec3 spawnPoint() const; + float scale() const; + +private: + void initEdges(); + + float world_scale{16.0f}; + std::array<Edge, MAP_BOX_EDGES_LEN> edges{}; +};