Copy source files from the 2D "game engine"
This commit is contained in:
parent
7cd1b06550
commit
6c828dfba7
9
cpp/Makefile
Normal file
9
cpp/Makefile
Normal file
@ -0,0 +1,9 @@
|
||||
all: test zomberman
|
||||
# TODO add extra warnings
|
||||
# TODO linter?
|
||||
|
||||
zomberman: src/main.cpp src/array.hpp
|
||||
g++ -Wall -ggdb3 -lSDL3 -lSDL3_image -std=c++23 -lGLEW -lGL -o zomberman src/main.cpp
|
||||
|
||||
test: src/test.cpp src/array.hpp
|
||||
g++ -Wall -Wextra -Wpedantic -ggdb3 -std=c++23 -lgtest -o test src/test.cpp
|
BIN
cpp/resources/archive_org_bomberman_sprites.png
Normal file
BIN
cpp/resources/archive_org_bomberman_sprites.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 125 KiB |
BIN
cpp/resources/bomb.png
Normal file
BIN
cpp/resources/bomb.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 2.5 KiB |
BIN
cpp/resources/bomb.xcf
Normal file
BIN
cpp/resources/bomb.xcf
Normal file
Binary file not shown.
BIN
cpp/resources/explosion.png
Normal file
BIN
cpp/resources/explosion.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 578 B |
BIN
cpp/resources/explosion.xcf
Normal file
BIN
cpp/resources/explosion.xcf
Normal file
Binary file not shown.
BIN
cpp/resources/player.png
Normal file
BIN
cpp/resources/player.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 10 KiB |
BIN
cpp/resources/player.xcf
Normal file
BIN
cpp/resources/player.xcf
Normal file
Binary file not shown.
BIN
cpp/resources/wall.png
Normal file
BIN
cpp/resources/wall.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 410 B |
BIN
cpp/resources/wall.xcf
Normal file
BIN
cpp/resources/wall.xcf
Normal file
Binary file not shown.
202
cpp/src/array.hpp
Normal file
202
cpp/src/array.hpp
Normal file
@ -0,0 +1,202 @@
|
||||
#include "log.hpp"
|
||||
#include <expected>
|
||||
#include <iostream>
|
||||
#include <stack>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace array { // TODO rename to container or something
|
||||
|
||||
template <typename U>
|
||||
concept Deletable = requires(U u) {
|
||||
{ delete u } -> std::same_as<void>;
|
||||
};
|
||||
|
||||
//
|
||||
// Unordered dynamic container with contiguous memory
|
||||
// with fast deleting and adding
|
||||
//
|
||||
template <typename T> class Pool {
|
||||
|
||||
// Pair type and helper functions
|
||||
|
||||
using pair_t = std::pair<bool, T>;
|
||||
|
||||
static T &get_item(pair_t &X) { return std::get<1>(X); }
|
||||
|
||||
static bool is_valid(const pair_t &X) { return std::get<0>(X); }
|
||||
|
||||
static bool &validity(pair_t &X) { return std::get<0>(X); }
|
||||
|
||||
public:
|
||||
// Forward declaration for Iterator
|
||||
class Iterator;
|
||||
|
||||
Pool(size_t prealloc_size = 16) {
|
||||
LOG_DEBUG(".");
|
||||
Realloc(prealloc_size);
|
||||
}
|
||||
|
||||
Pool(const Pool &p) = delete;
|
||||
Pool(Pool &&p) = delete;
|
||||
|
||||
~Pool() {
|
||||
LOG_DEBUG(".");
|
||||
delete[] m_Pool;
|
||||
}
|
||||
|
||||
template <typename U> void Add(U &&u) {
|
||||
EnsureAddCapacity(1);
|
||||
auto idx = m_FreeIdx.top();
|
||||
get_item(m_Pool[idx]) = std::forward<U>(u);
|
||||
validity(m_Pool[idx]) = true;
|
||||
m_FreeIdx.pop();
|
||||
m_Size++;
|
||||
}
|
||||
|
||||
void Remove(Iterator &it) {
|
||||
// Calculate the index from the iterator's pointer
|
||||
size_t index = it.ptr - m_Pool;
|
||||
|
||||
// Validate the iterator points to a valid element
|
||||
if (index >= m_Capacity || !is_valid(m_Pool[index])) {
|
||||
throw std::logic_error("Invalid iterator for removal");
|
||||
}
|
||||
|
||||
// Delete if deletable
|
||||
if constexpr (Deletable<T>)
|
||||
delete get_item(m_Pool[index]);
|
||||
|
||||
// Mark as invalid and add to free list
|
||||
validity(m_Pool[index]) = false;
|
||||
m_FreeIdx.push(index);
|
||||
m_Size--;
|
||||
|
||||
// Advance iterator to next valid element
|
||||
it.ptr++;
|
||||
it.iter_until_valid();
|
||||
}
|
||||
|
||||
void Remove(size_t index) {
|
||||
index_check(index);
|
||||
if constexpr (Deletable<T>)
|
||||
delete get_item(m_Pool[index]);
|
||||
validity(m_Pool[index]) = false;
|
||||
m_Size--;
|
||||
}
|
||||
|
||||
T &operator[](size_t index) {
|
||||
index_check(index);
|
||||
return get_item(m_Pool[index]);
|
||||
}
|
||||
|
||||
const T &operator[](size_t index) const {
|
||||
index_check(index);
|
||||
return get_item(m_Pool[index]);
|
||||
}
|
||||
|
||||
friend std::ostream &operator<<(std::ostream &os, const Pool &obj) {
|
||||
os << "Pool( Size: " << obj.m_Size << ", capacity: " << obj.m_Capacity
|
||||
<< "\n";
|
||||
for (size_t i = 0; i < obj.m_Capacity; i++) {
|
||||
os << "\t" << (std::get<bool>(obj.m_Pool[i]) ? "VALID" : "INVALID")
|
||||
<< "\n";
|
||||
}
|
||||
os << "\n)";
|
||||
return os;
|
||||
}
|
||||
|
||||
auto Size() const { return m_Size; }
|
||||
|
||||
auto Capacity() const { return m_Capacity; }
|
||||
|
||||
// Iterating related
|
||||
class Iterator {
|
||||
friend class Pool; // Allow Pool to access private members
|
||||
|
||||
public:
|
||||
Iterator(pair_t *start, pair_t *stop) : ptr(start), end_ptr(stop) {
|
||||
iter_until_valid();
|
||||
}
|
||||
|
||||
T &operator*() const { return get_item(*ptr); }
|
||||
|
||||
Iterator &operator++() {
|
||||
if (ptr != end_ptr) {
|
||||
ptr++;
|
||||
iter_until_valid();
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
bool operator!=(const Iterator &other) const { return ptr != other.ptr; }
|
||||
|
||||
bool operator==(const Iterator &other) const { return ptr == other.ptr; }
|
||||
|
||||
private:
|
||||
pair_t *ptr = nullptr;
|
||||
pair_t *end_ptr = nullptr;
|
||||
|
||||
void iter_until_valid() {
|
||||
while (ptr < end_ptr && !is_valid(*ptr)) {
|
||||
ptr++;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
Iterator begin() { return Iterator(m_Pool, m_Pool + m_Capacity); }
|
||||
Iterator end() { return Iterator(m_Pool + m_Capacity, m_Pool + m_Capacity); }
|
||||
|
||||
private:
|
||||
pair_t *m_Pool = nullptr;
|
||||
// TODO use unique_ptr
|
||||
std::stack<size_t> m_FreeIdx;
|
||||
|
||||
size_t m_Capacity = 0;
|
||||
size_t m_Size = 0;
|
||||
|
||||
void index_check(size_t index) const {
|
||||
if (index >= m_Capacity) {
|
||||
throw std::out_of_range("Out of range");
|
||||
}
|
||||
if (!is_valid(m_Pool[index])) {
|
||||
throw std::logic_error("Invalid item");
|
||||
}
|
||||
}
|
||||
|
||||
void Realloc(size_t requested_capacity) {
|
||||
// Calculate new capacity
|
||||
size_t new_capacity = m_Capacity > 0 ? m_Capacity : 1;
|
||||
while (new_capacity < requested_capacity) {
|
||||
new_capacity *= 2;
|
||||
}
|
||||
LOG_DEBUG("Realloc from ", m_Capacity, " to ", new_capacity);
|
||||
// Alloc new pool and copy from old pool
|
||||
pair_t *new_pool = new pair_t[new_capacity];
|
||||
size_t new_idx = 0;
|
||||
size_t old_capacity = m_Capacity;
|
||||
for (size_t old_idx = 0; old_idx < old_capacity; old_idx++) {
|
||||
if (is_valid(m_Pool[old_idx])) {
|
||||
new_pool[new_idx++] = std::move(m_Pool[old_idx]);
|
||||
}
|
||||
}
|
||||
// Remaining new items are all free
|
||||
while (new_idx < new_capacity) {
|
||||
m_FreeIdx.push(new_idx);
|
||||
validity(new_pool[new_idx++]) = false;
|
||||
}
|
||||
// Swap and free the old pool
|
||||
std::swap(m_Pool, new_pool);
|
||||
delete[] new_pool;
|
||||
// Update state variables
|
||||
m_Capacity = new_capacity;
|
||||
// m_Size stays the same
|
||||
}
|
||||
|
||||
void EnsureAddCapacity(size_t additional_elements) {
|
||||
if (m_Size + additional_elements > m_Capacity) {
|
||||
Realloc(m_Size + additional_elements);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
} /* namespace array */
|
57
cpp/src/log.hpp
Normal file
57
cpp/src/log.hpp
Normal file
@ -0,0 +1,57 @@
|
||||
#pragma once
|
||||
|
||||
#include <iostream>
|
||||
|
||||
#define LOG_CRITICAL(...) Log::critical(__PRETTY_FUNCTION__, ": ", __VA_ARGS__)
|
||||
#define LOG_ERROR(...) Log::error(__PRETTY_FUNCTION__, ": ", __VA_ARGS__)
|
||||
#define LOG_WARNING(...) Log::warning(__PRETTY_FUNCTION__, ": ", __VA_ARGS__)
|
||||
#define LOG_INFO(...) Log::info(__PRETTY_FUNCTION__, ": ", __VA_ARGS__)
|
||||
#define LOG_DEBUG(...) Log::debug(__PRETTY_FUNCTION__, ": ", __VA_ARGS__)
|
||||
#define LOG_PROFILING_DEBUG(...) \
|
||||
Log::profiling_debug(__PRETTY_FUNCTION__, ": ", __VA_ARGS__)
|
||||
|
||||
namespace Log {
|
||||
enum class LevelTypes {
|
||||
CRITICAL = 0, // Things that crash
|
||||
ERROR, // Bad stuff, but we can go on
|
||||
WARNING, // Minor inconvenience
|
||||
INFO, // Normal stuff
|
||||
DEBUG, // Everything. Will slow down execution
|
||||
PROFILING_DEBUG, // including constructors etc.
|
||||
};
|
||||
|
||||
// Set logging level here
|
||||
constexpr LevelTypes Level = LevelTypes::DEBUG;
|
||||
|
||||
template <LevelTypes FUNC_LEVEL, typename... Args>
|
||||
void _print(const Args &...args) {
|
||||
if constexpr (Level < FUNC_LEVEL) {
|
||||
return;
|
||||
}
|
||||
(std::cout << ... << args) << std::endl;
|
||||
}
|
||||
|
||||
template <typename... Args> void critical(const Args &...args) {
|
||||
_print<LevelTypes::CRITICAL>("CRITICAL: ", args...);
|
||||
}
|
||||
|
||||
template <typename... Args> void error(const Args &...args) {
|
||||
_print<LevelTypes::ERROR>("ERROR: ", args...);
|
||||
}
|
||||
|
||||
template <typename... Args> void warning(const Args &...args) {
|
||||
_print<LevelTypes::WARNING>("WARNING: ", args...);
|
||||
}
|
||||
|
||||
template <typename... Args> void info(const Args &...args) {
|
||||
_print<LevelTypes::INFO>("INFO: ", args...);
|
||||
}
|
||||
|
||||
template <typename... Args> void debug(const Args &...args) {
|
||||
_print<LevelTypes::DEBUG>("DEBUG: ", args...);
|
||||
}
|
||||
|
||||
template <typename... Args> void profiling_debug(const Args &...args) {
|
||||
_print<LevelTypes::PROFILING_DEBUG>("PROFILING_DEBUG: ", args...);
|
||||
}
|
||||
} // namespace Log
|
885
cpp/src/main.cpp
Normal file
885
cpp/src/main.cpp
Normal file
@ -0,0 +1,885 @@
|
||||
#include <cassert>
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <cstdlib>
|
||||
#include <expected>
|
||||
#include <iostream>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <thread>
|
||||
#include <unordered_set>
|
||||
#include <vector>
|
||||
|
||||
#include "array.hpp"
|
||||
#include "log.hpp"
|
||||
#include "math.hpp"
|
||||
|
||||
//
|
||||
// Utils
|
||||
//
|
||||
|
||||
//
|
||||
// Math stuff
|
||||
//
|
||||
|
||||
// Forward declarations
|
||||
class Sprite;
|
||||
class Sound;
|
||||
class UserAction;
|
||||
|
||||
//
|
||||
// UI stuff. This is the part directly dependent on the SDL
|
||||
//
|
||||
|
||||
// containers
|
||||
|
||||
#include <GL/glew.h>
|
||||
#include <SDL3/SDL.h>
|
||||
#include <SDL3_image/SDL_image.h>
|
||||
|
||||
class Sound {
|
||||
public:
|
||||
Sound() { LOG_DEBUG("."); }
|
||||
|
||||
Sound(const Sound &x) { LOG_DEBUG("."); }
|
||||
|
||||
Sound(Sound &&x) noexcept { LOG_DEBUG("."); }
|
||||
|
||||
~Sound() { LOG_DEBUG("."); }
|
||||
};
|
||||
|
||||
class AudioOutput {
|
||||
public:
|
||||
AudioOutput() { LOG_DEBUG("."); }
|
||||
AudioOutput(const AudioOutput &x) = delete;
|
||||
AudioOutput(AudioOutput &&x) = delete;
|
||||
~AudioOutput() { LOG_DEBUG("."); }
|
||||
|
||||
std::expected<void, std::string> Init() {
|
||||
LOG_INFO("Initialing audio output");
|
||||
return {};
|
||||
}
|
||||
|
||||
void PlaySound(Sound &s);
|
||||
};
|
||||
|
||||
class Sprite {
|
||||
public:
|
||||
Sprite() : m_Texture(nullptr, SDL_DestroyTexture) {}
|
||||
Sprite(std::string path, Vec2D<float> center) : Sprite() {
|
||||
LoadImage(path, center);
|
||||
}
|
||||
int m_R = 0;
|
||||
int m_G = 0;
|
||||
int m_B = 0;
|
||||
int m_A = 0;
|
||||
Sprite(const Sprite &x) = delete;
|
||||
Sprite(Sprite &&x) = delete;
|
||||
~Sprite() { LOG_DEBUG("."); }
|
||||
void LoadImage(std::string path, Vec2D<float> image_center = {0.0, 0.0}) {
|
||||
LOG_INFO("Loading image ", path);
|
||||
assert(m_Renderer != nullptr);
|
||||
|
||||
auto surface = std::unique_ptr<SDL_Surface, decltype(&SDL_DestroySurface)>(
|
||||
IMG_Load(path.c_str()), SDL_DestroySurface);
|
||||
|
||||
if (surface == nullptr) {
|
||||
LOG_ERROR("IMG_Load failed to load ", path);
|
||||
throw std::runtime_error("Failed to load resources");
|
||||
}
|
||||
|
||||
m_Texture = std::unique_ptr<SDL_Texture, decltype(&SDL_DestroyTexture)>(
|
||||
SDL_CreateTextureFromSurface(m_Renderer.get(), surface.get()),
|
||||
SDL_DestroyTexture);
|
||||
if (m_Texture == nullptr) {
|
||||
LOG_ERROR("SDL_CreateTextureFromSurface failed");
|
||||
throw std::runtime_error("Failed to load resources");
|
||||
}
|
||||
float w, h;
|
||||
SDL_GetTextureSize(m_Texture.get(), &w, &h);
|
||||
m_Size = {w, h};
|
||||
m_ImageCenter = image_center;
|
||||
}
|
||||
|
||||
// Renderer is shared for all class instances - we need it in order
|
||||
// to create textures from images
|
||||
static void SetRenderer(std::shared_ptr<SDL_Renderer> renderer) {
|
||||
m_Renderer = renderer;
|
||||
}
|
||||
|
||||
// GetTexture cannot return pointer to const, as SDL_RenderTexture modifies it
|
||||
SDL_Texture *GetTexture() { return m_Texture.get(); }
|
||||
|
||||
Vec2D<float> GetSize() const { return m_Size; }
|
||||
Vec2D<float> GetCenter() const { return m_ImageCenter; }
|
||||
|
||||
private:
|
||||
static std::shared_ptr<SDL_Renderer> m_Renderer;
|
||||
std::unique_ptr<SDL_Texture, decltype(&SDL_DestroyTexture)> m_Texture;
|
||||
Vec2D<float> m_Size;
|
||||
Vec2D<float> m_ImageCenter;
|
||||
float m_TextureWidth = 0;
|
||||
float m_TextureHeight = 0;
|
||||
};
|
||||
std::shared_ptr<SDL_Renderer> Sprite::m_Renderer = nullptr;
|
||||
|
||||
// User interface classes
|
||||
|
||||
class Window {
|
||||
public:
|
||||
Window(const Window &x) = delete;
|
||||
Window(Window &&x) = delete;
|
||||
Window(int width, int height) : m_Width(width), m_Height(height) {
|
||||
LOG_DEBUG(".");
|
||||
}
|
||||
|
||||
std::expected<void, std::string> Init() {
|
||||
LOG_DEBUG(".");
|
||||
|
||||
if (SDL_Init(SDL_INIT_VIDEO) == false) {
|
||||
return std::unexpected(std::string("SDL could not initialize! Error: ") +
|
||||
SDL_GetError());
|
||||
}
|
||||
m_Window = SDL_CreateWindow("SDL2 Window", m_Width, m_Height,
|
||||
SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE);
|
||||
if (m_Window == nullptr) {
|
||||
std::atexit(SDL_Quit);
|
||||
return std::unexpected(
|
||||
std::string("Window could not be created! Error: ") + SDL_GetError());
|
||||
}
|
||||
|
||||
m_Context = SDL_GL_CreateContext(m_Window);
|
||||
if (m_Context == nullptr) {
|
||||
SDL_DestroyWindow(m_Window);
|
||||
std::atexit(SDL_Quit);
|
||||
return std::unexpected(
|
||||
std::string("GL context could not be created! Error: ") +
|
||||
SDL_GetError());
|
||||
}
|
||||
|
||||
if (glewInit() != GLEW_OK) {
|
||||
SDL_GL_DestroyContext(m_Context);
|
||||
SDL_DestroyWindow(m_Window);
|
||||
std::atexit(SDL_Quit);
|
||||
return std::unexpected("GLEW init failed!");
|
||||
}
|
||||
|
||||
// Resize();
|
||||
|
||||
m_Renderer = std::shared_ptr<SDL_Renderer>(
|
||||
SDL_CreateRenderer(m_Window, NULL), SDL_DestroyRenderer);
|
||||
if (m_Renderer == nullptr) {
|
||||
SDL_DestroyWindow(m_Window);
|
||||
std::atexit(SDL_Quit);
|
||||
return std::unexpected(
|
||||
std::string("Renderer could not be created! Error: ") +
|
||||
SDL_GetError());
|
||||
}
|
||||
|
||||
// Set renderer to the Sprite class
|
||||
Sprite::SetRenderer(m_Renderer);
|
||||
|
||||
// TODO this needs to be tied to map size
|
||||
SDL_SetRenderScale(m_Renderer.get(), 1.0f, 1.0f);
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
~Window() {
|
||||
// SDL_DestroyRenderer(m_Renderer); // handled by shared_ptr
|
||||
SDL_GL_DestroyContext(m_Context);
|
||||
SDL_DestroyWindow(m_Window);
|
||||
std::atexit(SDL_Quit);
|
||||
LOG_DEBUG(".");
|
||||
}
|
||||
|
||||
void DrawSprite(const Vec2D<float> &position, Sprite &s) {
|
||||
Vec2D<float> size = s.GetSize();
|
||||
Vec2D<float> img_center = s.GetCenter();
|
||||
SDL_FRect rect = {position.x - img_center.x, position.y - img_center.y,
|
||||
size.x, size.y};
|
||||
SDL_RenderTexture(m_Renderer.get(), s.GetTexture(), nullptr, &rect);
|
||||
}
|
||||
|
||||
void ClearWindow() {
|
||||
SDL_SetRenderDrawColor(m_Renderer.get(), 50, 50, 50, 255);
|
||||
SDL_RenderClear(m_Renderer.get());
|
||||
}
|
||||
|
||||
void Flush() { SDL_RenderPresent(m_Renderer.get()); }
|
||||
|
||||
void DrawCircle(const Vec2D<float> &position, float radius) {
|
||||
int cx = static_cast<int>(position.x);
|
||||
int cy = static_cast<int>(position.y);
|
||||
SDL_SetRenderDrawColor(m_Renderer.get(), 255, 0, 0, 255);
|
||||
for (int i = 0; i < 360; ++i) {
|
||||
double a = i * M_PI / 180.0;
|
||||
SDL_RenderPoint(m_Renderer.get(),
|
||||
cx + static_cast<int>(std::round(radius * std::cos(a))),
|
||||
cy + static_cast<int>(std::round(radius * std::sin(a))));
|
||||
}
|
||||
}
|
||||
|
||||
std::shared_ptr<SDL_Renderer> m_Renderer = nullptr;
|
||||
SDL_Window *m_Window;
|
||||
SDL_GLContext m_Context;
|
||||
|
||||
private:
|
||||
uint32_t m_Width;
|
||||
uint32_t m_Height;
|
||||
};
|
||||
|
||||
class UserAction {
|
||||
public:
|
||||
enum class Type { NONE, EXIT, MOVE, CROUCH, STAND, FIRE };
|
||||
|
||||
UserAction() = default;
|
||||
|
||||
UserAction(Type t) : type(t) {}
|
||||
|
||||
UserAction(Type t, char key) : type(t), Argument{.key = key} {}
|
||||
|
||||
UserAction(Type t, Vec2D<float> v) : type(t), Argument{.position = v} {}
|
||||
|
||||
~UserAction() = default;
|
||||
|
||||
Type type;
|
||||
|
||||
union {
|
||||
Vec2D<float> position;
|
||||
char key;
|
||||
} Argument;
|
||||
};
|
||||
|
||||
class UserInput {
|
||||
public:
|
||||
UserInput()
|
||||
: // pre-alloc some space
|
||||
m_Actions(10) {
|
||||
LOG_DEBUG(".");
|
||||
};
|
||||
|
||||
UserInput(const UserInput &x) = delete;
|
||||
UserInput(UserInput &&x) = delete;
|
||||
~UserInput() { LOG_DEBUG("."); };
|
||||
|
||||
std::expected<void, std::string> Init() { return {}; }
|
||||
|
||||
const std::vector<UserAction> &GetActions() {
|
||||
m_Actions.clear();
|
||||
static Vec2D<float> move_direction = {0.0f, 0.0f};
|
||||
static bool send_move_action = false;
|
||||
SDL_Event event;
|
||||
|
||||
while (SDL_PollEvent(&event)) {
|
||||
if (event.type == SDL_EVENT_KEY_DOWN || event.type == SDL_EVENT_KEY_UP) {
|
||||
bool key_down = event.type == SDL_EVENT_KEY_DOWN ? true : false;
|
||||
SDL_KeyboardEvent kbd_event = event.key;
|
||||
if (kbd_event.repeat) {
|
||||
// SDL repeats KEY_DOWN if key is held down, we ignore that
|
||||
continue;
|
||||
}
|
||||
LOG_DEBUG("Key '", static_cast<char>(kbd_event.key),
|
||||
key_down ? "' down" : "' up");
|
||||
|
||||
switch (kbd_event.key) {
|
||||
case 'q':
|
||||
m_Actions.emplace_back(UserAction::Type::EXIT);
|
||||
// further processing of inputs is not needed
|
||||
return m_Actions;
|
||||
case 'w':
|
||||
case 's':
|
||||
case 'a':
|
||||
case 'd':
|
||||
case SDLK_UP:
|
||||
case SDLK_DOWN:
|
||||
case SDLK_LEFT:
|
||||
case SDLK_RIGHT: {
|
||||
static std::map<char, Vec2D<float>> move_base{
|
||||
{'w', {0.0, 1.0}},
|
||||
{'s', {0.0, -1.0}},
|
||||
{'a', {1.0, 0.0}},
|
||||
{'d', {-1.0, 0.0}},
|
||||
{static_cast<char>(SDLK_UP), {0.0, 1.0}},
|
||||
{static_cast<char>(SDLK_DOWN), {0.0, -1.0}},
|
||||
{static_cast<char>(SDLK_LEFT), {1.0, 0.0}},
|
||||
{static_cast<char>(SDLK_RIGHT), {-1.0, 0.0}},
|
||||
};
|
||||
|
||||
float direction = key_down ? -1.0f : 1.0f;
|
||||
send_move_action = true;
|
||||
move_direction += move_base[kbd_event.key] * direction;
|
||||
break;
|
||||
}
|
||||
case SDLK_SPACE:
|
||||
if (key_down)
|
||||
m_Actions.emplace_back(UserAction::Type::FIRE);
|
||||
break;
|
||||
default:
|
||||
LOG_INFO("Key '", static_cast<char>(kbd_event.key), "' not mapped");
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
// TODO uncomment, for now too much noise
|
||||
// LOG_WARNING("Action not processed");
|
||||
}
|
||||
}
|
||||
if (send_move_action) {
|
||||
m_Actions.emplace_back(UserAction::Type::MOVE,
|
||||
move_direction.normalized());
|
||||
send_move_action = false;
|
||||
}
|
||||
return m_Actions;
|
||||
}
|
||||
|
||||
private:
|
||||
std::vector<UserAction> m_Actions;
|
||||
};
|
||||
|
||||
//
|
||||
// Game classes
|
||||
//
|
||||
|
||||
class Entity {
|
||||
public:
|
||||
enum class Type : std::uint8_t {
|
||||
NONE,
|
||||
PLAYER,
|
||||
WALL,
|
||||
BOMB,
|
||||
ZOMBIE,
|
||||
ITEM,
|
||||
BOX,
|
||||
EXPLOSION,
|
||||
COUNT // must be last
|
||||
};
|
||||
|
||||
Entity(Vec2D<float> position = {0.0f, 0.0f}) : m_Position(position) {
|
||||
LOG_DEBUG("spawning entity at position ", position);
|
||||
}
|
||||
|
||||
friend std::ostream &operator<<(std::ostream &os, const Entity &obj) {
|
||||
static constexpr std::array<std::string_view,
|
||||
static_cast<size_t>(Entity::Type::COUNT)>
|
||||
type_name{"NONE", "PLAYER", "WALL", "BOMB", "ZOMBIE", "ITEM", "BOX"};
|
||||
size_t idx = static_cast<size_t>(obj.GetType());
|
||||
assert(idx < type_name.size());
|
||||
os << type_name[idx];
|
||||
return os;
|
||||
}
|
||||
|
||||
virtual Sprite &GetSprite() = 0;
|
||||
virtual constexpr float GetCollisionRadius() const = 0;
|
||||
virtual constexpr float GetCollisionRadiusSquared() {
|
||||
return GetCollisionRadius() * GetCollisionRadius();
|
||||
}
|
||||
// TODO virtual float GetCollisionRadius() const
|
||||
|
||||
virtual constexpr Type GetType() const = 0;
|
||||
void SetFlagExpired() { m_FlagExpired = true; }
|
||||
bool IsFlaggedExpired() { return m_FlagExpired; }
|
||||
|
||||
const Vec2D<float> &GetPosition() const { return m_Position; }
|
||||
void SetPosition(Vec2D<float> new_pos) { m_Position = new_pos; }
|
||||
|
||||
const Vec2D<float> &GetActualVelocity() const { return m_ActualVelocity; }
|
||||
const Vec2D<float> &GetRequestedVelocity() const {
|
||||
return m_RequestedVelocity;
|
||||
}
|
||||
void SetActualVelocity(const Vec2D<float> &new_velocity) {
|
||||
m_ActualVelocity = new_velocity;
|
||||
}
|
||||
void SetRequestedVelocity(const Vec2D<float> &new_velocity) {
|
||||
m_RequestedVelocity = new_velocity;
|
||||
}
|
||||
|
||||
void ZeroActualVelocityInDirection(Vec2D<float> direction) {
|
||||
// Vectors e1, e2 form the basis for a local coord system,
|
||||
// where e1 is formed by the direction where we want to zero-out
|
||||
// the velocity, and e2 is the orthogonal vector.
|
||||
// Scalars q1, q2 are coordinates for e1, e2 basis.
|
||||
Vec2D<float> e1 = direction.normalized();
|
||||
Vec2D<float> e2 = e1.orthogonal();
|
||||
|
||||
// q1 * e1 + q2 * e2 = v, from this follows:
|
||||
auto &v = GetActualVelocity();
|
||||
float q2 = (v.y * e1.x - v.x * e1.y) / (e2.y * e1.x - e2.x * e1.y);
|
||||
float q1 = (v.x - q2 * e2.x) / e1.x;
|
||||
|
||||
// We then zero-out the q1, but only if it's positive - meaning
|
||||
// it is aiming in the direction of "direction", not out.
|
||||
// (otherwise we're not able to move out from collision with
|
||||
// another object)
|
||||
if (q1 > 0.0f) {
|
||||
SetActualVelocity(q2 * e2);
|
||||
}
|
||||
}
|
||||
|
||||
virtual void Update(float time_delta) {
|
||||
m_Position += m_ActualVelocity * time_delta;
|
||||
}
|
||||
|
||||
virtual bool IsMovable() const = 0;
|
||||
virtual bool IsCollidable() const = 0;
|
||||
|
||||
protected:
|
||||
Vec2D<float> m_Position;
|
||||
Vec2D<float> m_ActualVelocity;
|
||||
Vec2D<float> m_RequestedVelocity;
|
||||
|
||||
private:
|
||||
bool m_FlagExpired = false;
|
||||
static constexpr float m_CollisionRadiusSq = 1000.0f;
|
||||
};
|
||||
|
||||
class Explosion final : public Entity {
|
||||
public:
|
||||
Explosion(Vec2D<float> position) : Entity(position) {
|
||||
LOG_DEBUG(".");
|
||||
if (m_Sprite == nullptr) {
|
||||
LoadResources();
|
||||
}
|
||||
}
|
||||
Explosion(const Explosion &) = delete;
|
||||
Explosion(Explosion &&) = delete;
|
||||
~Explosion() = default;
|
||||
|
||||
Sprite &GetSprite() override {
|
||||
assert(m_Sprite != nullptr);
|
||||
return *m_Sprite;
|
||||
}
|
||||
|
||||
void Update(float time_delta) override {
|
||||
m_ExpirationTime -= time_delta;
|
||||
if (m_ExpirationTime < 0.0f) {
|
||||
this->SetFlagExpired();
|
||||
}
|
||||
Entity::Update(time_delta);
|
||||
}
|
||||
|
||||
constexpr float GetCollisionRadius() const override { return 30.0f; }
|
||||
constexpr Type GetType() const { return Entity::Type::EXPLOSION; }
|
||||
bool IsMovable() const override { return false; }
|
||||
bool IsCollidable() const override { return false; }
|
||||
|
||||
private:
|
||||
void LoadResources() {
|
||||
m_Sprite = std::make_unique<Sprite>("resources/explosion.png",
|
||||
Vec2D<float>{25.0f, 25.0f});
|
||||
}
|
||||
static std::unique_ptr<Sprite> m_Sprite;
|
||||
float m_ExpirationTime = 100.0f;
|
||||
};
|
||||
std::unique_ptr<Sprite> Explosion::m_Sprite = nullptr;
|
||||
|
||||
class Player;
|
||||
|
||||
class Bomb final : public Entity {
|
||||
public:
|
||||
Bomb(Vec2D<float> position, const Player& creator) :
|
||||
Entity(position),
|
||||
m_CreatingPlayer(creator)
|
||||
{
|
||||
LOG_DEBUG(".");
|
||||
if (m_Sprite == nullptr) {
|
||||
LoadResources();
|
||||
}
|
||||
}
|
||||
Bomb(const Bomb &x) = delete;
|
||||
Bomb(Bomb &&x) = delete;
|
||||
|
||||
Sprite &GetSprite() override {
|
||||
assert(m_Sprite != nullptr);
|
||||
return *m_Sprite;
|
||||
}
|
||||
void Update(float time_delta) override {
|
||||
m_ExpirationTime -= time_delta;
|
||||
if (m_ExpirationTime < 0.0f) {
|
||||
this->SetFlagExpired();
|
||||
}
|
||||
Entity::Update(time_delta);
|
||||
}
|
||||
|
||||
constexpr float GetCollisionRadius() const override { return 30.0f; }
|
||||
constexpr Type GetType() const { return Entity::Type::BOMB; }
|
||||
bool IsMovable() const override { return false; }
|
||||
bool IsCollidable() const override { return true; }
|
||||
void SpawnExplosions()
|
||||
{
|
||||
// TODO spawn 4 explosions
|
||||
}
|
||||
|
||||
const Player& GetCreatingPlayer() { return m_CreatingPlayer; }
|
||||
|
||||
private:
|
||||
void LoadResources() {
|
||||
m_Sprite = std::make_unique<Sprite>("resources/bomb.png",
|
||||
Vec2D<float>{25.0f, 40.0f});
|
||||
}
|
||||
static std::unique_ptr<Sprite> m_Sprite;
|
||||
float m_ExpirationTime = 100.0f;
|
||||
const Player& m_CreatingPlayer;
|
||||
};
|
||||
|
||||
std::unique_ptr<Sprite> Bomb::m_Sprite;
|
||||
|
||||
class Item final : public Entity {
|
||||
public:
|
||||
void OnPickup(Entity &other);
|
||||
|
||||
constexpr float GetCollisionRadius() const override { return 50.0f; }
|
||||
bool IsMovable() const override { return false; }
|
||||
bool IsCollidable() const override { return true; }
|
||||
};
|
||||
|
||||
class Wall final : public Entity {
|
||||
public:
|
||||
Wall(Vec2D<float> pos = {0.0f, 0.0f}) : Entity(pos) {
|
||||
LOG_DEBUG(".");
|
||||
if (m_Sprite == nullptr) {
|
||||
LoadResources();
|
||||
}
|
||||
}
|
||||
Wall(const Wall &x) = delete;
|
||||
Wall(Wall &&x) = delete;
|
||||
|
||||
Sprite &GetSprite() override {
|
||||
assert(m_Sprite != nullptr);
|
||||
return *m_Sprite;
|
||||
}
|
||||
constexpr Entity::Type GetType() const override { return Entity::Type::WALL; }
|
||||
constexpr float GetCollisionRadius() const override { return 50.0f; }
|
||||
bool IsMovable() const override { return false; }
|
||||
bool IsCollidable() const override { return true; }
|
||||
|
||||
private:
|
||||
void LoadResources() {
|
||||
m_Sprite = std::make_unique<Sprite>("resources/wall.png",
|
||||
Vec2D<float>{50.0f, 50.0f});
|
||||
}
|
||||
static std::unique_ptr<Sprite> m_Sprite;
|
||||
};
|
||||
std::unique_ptr<Sprite> Wall::m_Sprite;
|
||||
|
||||
class Player final : public Entity {
|
||||
public:
|
||||
Player() {
|
||||
LOG_DEBUG(".");
|
||||
if (m_Sprite == nullptr) {
|
||||
LoadResources();
|
||||
}
|
||||
}
|
||||
Player(const Player &x) = delete;
|
||||
Player(Player &&x) = delete;
|
||||
|
||||
Sprite &GetSprite() override {
|
||||
assert(m_Sprite != nullptr);
|
||||
return *m_Sprite;
|
||||
}
|
||||
|
||||
std::shared_ptr<Bomb> CreateBomb() {
|
||||
return std::make_shared<Bomb>(this->GetPosition(), *this);
|
||||
}
|
||||
|
||||
constexpr Entity::Type GetType() const override {
|
||||
return Entity::Type::PLAYER;
|
||||
}
|
||||
constexpr float GetCollisionRadius() const override { return 50.0f; }
|
||||
bool IsMovable() const override { return true; }
|
||||
bool IsCollidable() const override { return true; }
|
||||
|
||||
private:
|
||||
void LoadResources() {
|
||||
m_Sprite = std::make_unique<Sprite>("resources/player.png",
|
||||
Vec2D<float>{38.0f, 46.0f});
|
||||
}
|
||||
static std::unique_ptr<Sprite> m_Sprite;
|
||||
};
|
||||
|
||||
std::unique_ptr<Sprite> Player::m_Sprite;
|
||||
|
||||
using Collision = std::pair<std::shared_ptr<Entity>, std::shared_ptr<Entity>>;
|
||||
|
||||
// Game class - TODO Game will be interface,
|
||||
// implementations will be LocalGame and RemoteGame (server)?
|
||||
// Class with game logic should be identical for remote and local games
|
||||
// GameLoop <--> Game
|
||||
// GameLoop <--> GameClient <========> GameServer <--> Game
|
||||
|
||||
class Game {
|
||||
public:
|
||||
Game(int width, int height) : m_Width(width), m_Height(height) {
|
||||
LOG_DEBUG(".");
|
||||
}
|
||||
|
||||
~Game() { LOG_DEBUG("."); }
|
||||
|
||||
Game(const Game &m) = delete;
|
||||
Game(Game &&m) = delete;
|
||||
|
||||
void AddEntity(std::shared_ptr<Entity> e) {
|
||||
// TODO emplace_back
|
||||
m_Entities.push_back(e);
|
||||
}
|
||||
|
||||
void CreateMap() {
|
||||
m_Entities.clear();
|
||||
m_Player = std::make_shared<Player>();
|
||||
m_Player->SetPosition(Vec2D<float>{200.0f, 200.0f});
|
||||
m_Entities.push_back(m_Player);
|
||||
LOG_INFO("Re-creating random map");
|
||||
// add some entities
|
||||
size_t map_size_bricks = 8;
|
||||
auto wall = std::make_shared<Wall>();
|
||||
auto wall_size = wall->GetSprite().GetSize();
|
||||
Vec2D<float> offset{100.0f, 100.0f};
|
||||
for (size_t u = 0; u < map_size_bricks; u++) {
|
||||
Vec2D<float> pos{offset.x + wall_size.x * u, offset.y};
|
||||
m_Entities.push_back(std::make_shared<Wall>(pos));
|
||||
}
|
||||
for (size_t u = 1; u < map_size_bricks; u++) {
|
||||
Vec2D<float> pos{offset.x, offset.y + u * wall_size.y};
|
||||
m_Entities.push_back(std::make_shared<Wall>(pos));
|
||||
}
|
||||
for (size_t u = 0; u < map_size_bricks; u++) {
|
||||
Vec2D<float> pos{offset.x + wall_size.x * u,
|
||||
offset.y + map_size_bricks * wall_size.y};
|
||||
m_Entities.push_back(std::make_shared<Wall>(pos));
|
||||
}
|
||||
for (size_t u = 0; u < map_size_bricks; u++) {
|
||||
Vec2D<float> pos{offset.x + map_size_bricks * wall_size.x,
|
||||
offset.y + u * wall_size.y};
|
||||
m_Entities.push_back(std::make_shared<Wall>(pos));
|
||||
}
|
||||
// TODO tady jsi skoncil - problem s tim ze ne vsechny steny se spawnou, bud
|
||||
// jsou spatne cykly, nebo to souvisi s tim ze se obcas nespawnou bomby -
|
||||
// investigovat
|
||||
}
|
||||
|
||||
std::shared_ptr<Player> GetPlayer() { return m_Player; }
|
||||
|
||||
Vec2D<float> GetRandomPosition() const { return Vec2D<float>{0.0, 0.0}; }
|
||||
|
||||
std::vector<std::shared_ptr<Entity>> &GetEntities() { return m_Entities; }
|
||||
|
||||
void UpdateEntities() {
|
||||
float time_delta = 1.0f;
|
||||
|
||||
// Remove entities marked as expired and handle expiry logic (e.g. bomb
|
||||
// exploding); for all other entities, reset the actual velocity to the
|
||||
// requested; actual velocity will be updated later with collisions
|
||||
for (auto &entity : m_Entities) {
|
||||
if (entity->IsFlaggedExpired()) {
|
||||
ExpiryGameLogic(*entity);
|
||||
auto it = std::find(m_Entities.begin(), m_Entities.end(), entity);
|
||||
if (it != m_Entities.end()) {
|
||||
std::swap(*it, m_Entities.back());
|
||||
m_Entities.pop_back();
|
||||
}
|
||||
} else {
|
||||
// Actual velocity might be changed later by collisions
|
||||
entity->SetActualVelocity(entity->GetRequestedVelocity());
|
||||
}
|
||||
}
|
||||
|
||||
// Handle collisions:
|
||||
// - update actual velocity for colliding objects
|
||||
// - handle collision logic
|
||||
auto &collisions = GetEntityCollisions();
|
||||
// LOG_DEBUG("number of collisions: ", collisions.size());
|
||||
for (auto &collision : collisions) {
|
||||
Entity &A = *std::get<0>(collision);
|
||||
Entity &B = *std::get<1>(collision);
|
||||
if (!A.IsMovable())
|
||||
continue;
|
||||
// modify actual speed
|
||||
// LOG_DEBUG("Collision: A is ", A, ", B is ", B);
|
||||
Vec2D<float> AB = B.GetPosition() - A.GetPosition();
|
||||
A.ZeroActualVelocityInDirection(AB);
|
||||
// handle logic
|
||||
CollisionGameLogic(A, B);
|
||||
}
|
||||
|
||||
// Update entities: this advances animations,
|
||||
// internal timers, and updates positions (with velocity
|
||||
// modified by the collision handling)
|
||||
for (auto &entity : m_Entities) {
|
||||
entity->Update(time_delta);
|
||||
}
|
||||
}
|
||||
|
||||
void CollisionGameLogic(Entity &A, Entity &B) {
|
||||
if (A.GetType() == Entity::Type::PLAYER) {
|
||||
// LOG_DEBUG("got player");
|
||||
if (B.GetType() == Entity::Type::EXPLOSION) {
|
||||
LOG_DEBUG("got player and bomb");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void ExpiryGameLogic(Entity &entity)
|
||||
{
|
||||
switch (entity.GetType()) {
|
||||
case Entity::Type::BOMB:
|
||||
{
|
||||
Bomb& bomb = static_cast<Bomb&>(entity);
|
||||
bomb.SpawnExplosions();
|
||||
break;
|
||||
}
|
||||
case Entity::Type::EXPLOSION:
|
||||
|
||||
break;
|
||||
// non-expiring classes
|
||||
case Entity::Type::PLAYER:
|
||||
case Entity::Type::WALL:
|
||||
case Entity::Type::ZOMBIE:
|
||||
case Entity::Type::ITEM:
|
||||
case Entity::Type::BOX:
|
||||
default:
|
||||
assert(false);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
const std::vector<Collision> &GetEntityCollisions() {
|
||||
static std::vector<Collision> m_Collisions;
|
||||
|
||||
m_Collisions.clear();
|
||||
for (const auto &entity_A : m_Entities) {
|
||||
for (const auto &entity_B : m_Entities) {
|
||||
if (entity_A == entity_B)
|
||||
continue;
|
||||
if (!entity_A->IsCollidable() || !entity_B->IsCollidable())
|
||||
continue;
|
||||
// check distance of player to given entity
|
||||
auto position_A = entity_A->GetPosition();
|
||||
auto position_B = entity_B->GetPosition();
|
||||
auto distance_sq = position_A.distance_squared(position_B);
|
||||
auto collision_distance_sq =
|
||||
entity_A->GetCollisionRadiusSquared() +
|
||||
entity_B->GetCollisionRadiusSquared() +
|
||||
2 * entity_A->GetCollisionRadius() * entity_B->GetCollisionRadius();
|
||||
// TODO use vector instructions
|
||||
if (distance_sq < collision_distance_sq) {
|
||||
m_Collisions.emplace_back(Collision(entity_A, entity_B));
|
||||
}
|
||||
}
|
||||
}
|
||||
return m_Collisions;
|
||||
}
|
||||
|
||||
void HandleActions(const std::vector<UserAction> &actions) {
|
||||
for (const auto &action : actions) {
|
||||
if (action.type == UserAction::Type::EXIT) {
|
||||
LOG_INFO("Exit requested");
|
||||
m_ExitRequested = true;
|
||||
} else if (action.type == UserAction::Type::FIRE) {
|
||||
LOG_INFO("Fire");
|
||||
AddEntity(m_Player->CreateBomb());
|
||||
} else if (action.type == UserAction::Type::MOVE) {
|
||||
LOG_INFO("Move direction ", action.Argument.position);
|
||||
m_Player->SetRequestedVelocity(action.Argument.position * 4.0f);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
bool IsCollisionBoxVisible() const { return m_DrawCollisionBox; }
|
||||
bool IsExitRequested() const { return m_ExitRequested; }
|
||||
|
||||
private:
|
||||
int m_Width;
|
||||
int m_Height;
|
||||
bool m_ExitRequested = false;
|
||||
bool m_DrawCollisionBox = true;
|
||||
std::vector<std::shared_ptr<Entity>> m_Entities;
|
||||
std::shared_ptr<Player> m_Player;
|
||||
};
|
||||
|
||||
// GameLoop class handles user input and audio/video output,
|
||||
// client side only. No game logic should be handled here.
|
||||
|
||||
class GameLoop {
|
||||
public:
|
||||
GameLoop() = default;
|
||||
|
||||
void Run() {
|
||||
LOG_INFO("Running the game");
|
||||
while (!m_Game->IsExitRequested()) {
|
||||
m_Game->HandleActions(m_UserInput->GetActions());
|
||||
m_Game->UpdateEntities();
|
||||
|
||||
m_Window->ClearWindow();
|
||||
for (auto &entity : m_Game->GetEntities()) {
|
||||
m_Window->DrawSprite(entity->GetPosition(), entity->GetSprite());
|
||||
if (m_Game->IsCollisionBoxVisible()) {
|
||||
m_Window->DrawCircle(entity->GetPosition(),
|
||||
entity->GetCollisionRadius());
|
||||
}
|
||||
}
|
||||
m_Window->Flush();
|
||||
// TODO measure fps
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(30));
|
||||
}
|
||||
}
|
||||
|
||||
inline void SetGame(std::unique_ptr<Game> x) { m_Game = std::move(x); }
|
||||
inline void SetWindow(std::unique_ptr<Window> x) { m_Window = std::move(x); }
|
||||
inline void SetUserInput(std::unique_ptr<UserInput> x) {
|
||||
m_UserInput = std::move(x);
|
||||
}
|
||||
inline void SetAudioOutput(std::unique_ptr<AudioOutput> x) {
|
||||
m_AudioOutput = std::move(x);
|
||||
}
|
||||
|
||||
private:
|
||||
std::unique_ptr<Game> m_Game;
|
||||
std::unique_ptr<Window> m_Window;
|
||||
std::unique_ptr<UserInput> m_UserInput;
|
||||
std::unique_ptr<AudioOutput> m_AudioOutput;
|
||||
};
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
constexpr int error = -1;
|
||||
|
||||
/*
|
||||
* Initialize the input/output system
|
||||
*/
|
||||
|
||||
auto window = std::make_unique<Window>(640, 480); // the holy resolution
|
||||
// auto window_init = window->Init();
|
||||
if (auto initialized = window->Init(); !initialized) {
|
||||
LOG_ERROR(initialized.error());
|
||||
return error;
|
||||
}
|
||||
|
||||
auto user_input = std::make_unique<UserInput>();
|
||||
if (auto initialized = user_input->Init(); !initialized) {
|
||||
LOG_ERROR(initialized.error());
|
||||
return error;
|
||||
}
|
||||
|
||||
auto audio_output = std::make_unique<AudioOutput>();
|
||||
if (auto initialized = audio_output->Init(); !initialized) {
|
||||
LOG_ERROR(initialized.error());
|
||||
return error;
|
||||
}
|
||||
|
||||
/*
|
||||
* Initialize the map and run the game
|
||||
*/
|
||||
|
||||
// some menu should be used to configure the game itself,
|
||||
// e.g. set map size, type, local or remote game,
|
||||
// optionally game server...
|
||||
// for now we go directly to the game
|
||||
|
||||
auto game = std::make_unique<Game>(50, 50);
|
||||
game->CreateMap();
|
||||
|
||||
auto game_loop = GameLoop{};
|
||||
game_loop.SetWindow(std::move(window));
|
||||
game_loop.SetUserInput(std::move(user_input));
|
||||
game_loop.SetAudioOutput(std::move(audio_output));
|
||||
game_loop.SetGame(std::move(game));
|
||||
game_loop.Run();
|
||||
}
|
88
cpp/src/math.hpp
Normal file
88
cpp/src/math.hpp
Normal file
@ -0,0 +1,88 @@
|
||||
#pragma once
|
||||
|
||||
#include <cassert>
|
||||
#include <cmath>
|
||||
#include <concepts>
|
||||
#include <iostream>
|
||||
|
||||
template <typename T> struct Vec2D {
|
||||
public:
|
||||
Vec2D() = default;
|
||||
~Vec2D() = default;
|
||||
|
||||
Vec2D &operator+=(const Vec2D &other) {
|
||||
x += other.x;
|
||||
y += other.y;
|
||||
return *this;
|
||||
}
|
||||
|
||||
friend Vec2D operator+(const Vec2D &a, const Vec2D &b) {
|
||||
return Vec2D{a.x + b.x, a.y + b.y};
|
||||
}
|
||||
|
||||
friend Vec2D operator-(const Vec2D &a, const Vec2D &b) {
|
||||
return Vec2D{a.x - b.x, a.y - b.y};
|
||||
}
|
||||
|
||||
friend Vec2D operator*(float k, const Vec2D &v) {
|
||||
return Vec2D{k * v.x, k * v.y};
|
||||
}
|
||||
|
||||
Vec2D operator*(float b) const { return Vec2D{b * x, b * y}; }
|
||||
|
||||
T distance_squared(const Vec2D &other) const {
|
||||
T dx = x - other.x;
|
||||
T dy = y - other.y;
|
||||
return dx * dx + dy * dy;
|
||||
}
|
||||
|
||||
T distance(const Vec2D &other) const
|
||||
requires std::floating_point<T>
|
||||
{
|
||||
return sqrt(distance_squared(other));
|
||||
}
|
||||
|
||||
void normalize()
|
||||
requires std::floating_point<T>
|
||||
{
|
||||
auto length = sqrt(x * x + y * y);
|
||||
if (length < 1e-6) {
|
||||
x = y = 0;
|
||||
} else {
|
||||
x /= length;
|
||||
y /= length;
|
||||
}
|
||||
}
|
||||
|
||||
Vec2D normalized()
|
||||
requires std::floating_point<T>
|
||||
{
|
||||
Vec2D v(*this);
|
||||
v.normalize();
|
||||
return v;
|
||||
}
|
||||
|
||||
Vec2D orthogonal()
|
||||
{
|
||||
Vec2D v(*this);
|
||||
|
||||
std::swap(v.x, v.y);
|
||||
v.x = -v.x;
|
||||
return v;
|
||||
}
|
||||
|
||||
template <typename U> Vec2D(std::initializer_list<U> list) {
|
||||
assert(list.size() == 2);
|
||||
auto first_element = *list.begin();
|
||||
auto second_element = *(list.begin() + 1);
|
||||
x = static_cast<T>(first_element);
|
||||
y = static_cast<T>(second_element);
|
||||
}
|
||||
|
||||
T x, y;
|
||||
|
||||
friend std::ostream &operator<<(std::ostream &os, const Vec2D &obj) {
|
||||
os << "( " << obj.x << ", " << obj.y << ")";
|
||||
return os;
|
||||
}
|
||||
};
|
158
cpp/src/test.cpp
Normal file
158
cpp/src/test.cpp
Normal file
@ -0,0 +1,158 @@
|
||||
#include <cassert>
|
||||
#include <cmath>
|
||||
#include <concepts>
|
||||
#include <gtest/gtest.h>
|
||||
#include <sstream>
|
||||
#include <unordered_set>
|
||||
|
||||
#include "array.hpp"
|
||||
#include "log.hpp"
|
||||
#include "math.hpp"
|
||||
|
||||
// Vec2D Tests
|
||||
TEST(Vec2D, DefaultConstruction) {
|
||||
Vec2D<int> v;
|
||||
// Default values are uninitialized, but we can test basic functionality
|
||||
v.x = 0;
|
||||
v.y = 0;
|
||||
ASSERT_EQ(v.x, 0);
|
||||
ASSERT_EQ(v.y, 0);
|
||||
}
|
||||
|
||||
TEST(Vec2D, InitializerListConstruction) {
|
||||
Vec2D<int> v{3, 4};
|
||||
ASSERT_EQ(v.x, 3);
|
||||
ASSERT_EQ(v.y, 4);
|
||||
|
||||
Vec2D<float> vf{1.5f, 2.5f};
|
||||
ASSERT_FLOAT_EQ(vf.x, 1.5f);
|
||||
ASSERT_FLOAT_EQ(vf.y, 2.5f);
|
||||
|
||||
// Test type conversion
|
||||
Vec2D<float> vd{1, 2}; // int to float
|
||||
ASSERT_FLOAT_EQ(vd.x, 1.0f);
|
||||
ASSERT_FLOAT_EQ(vd.y, 2.0f);
|
||||
}
|
||||
|
||||
TEST(Vec2D, Addition) {
|
||||
Vec2D<int> a{1, 2};
|
||||
Vec2D<int> b{3, 4};
|
||||
|
||||
Vec2D<int> c = a + b;
|
||||
ASSERT_EQ(c.x, 4);
|
||||
ASSERT_EQ(c.y, 6);
|
||||
|
||||
// Test that original vectors are unchanged
|
||||
ASSERT_EQ(a.x, 1);
|
||||
ASSERT_EQ(a.y, 2);
|
||||
ASSERT_EQ(b.x, 3);
|
||||
ASSERT_EQ(b.y, 4);
|
||||
}
|
||||
|
||||
TEST(Vec2D, AdditionAssignment) {
|
||||
Vec2D<int> a{1, 2};
|
||||
Vec2D<int> b{3, 4};
|
||||
|
||||
a += b;
|
||||
ASSERT_EQ(a.x, 4);
|
||||
ASSERT_EQ(a.y, 6);
|
||||
|
||||
// Test that b is unchanged
|
||||
ASSERT_EQ(b.x, 3);
|
||||
ASSERT_EQ(b.y, 4);
|
||||
}
|
||||
|
||||
TEST(Vec2D, ScalarMultiplication) {
|
||||
Vec2D<int> v{2, 3};
|
||||
|
||||
Vec2D<int> result = v * 2.0f;
|
||||
ASSERT_EQ(result.x, 4);
|
||||
ASSERT_EQ(result.y, 6);
|
||||
|
||||
// Test with float vector
|
||||
Vec2D<float> vf{1.5f, 2.5f};
|
||||
Vec2D<float> resultf = vf * 2.0f;
|
||||
ASSERT_FLOAT_EQ(resultf.x, 3.0f);
|
||||
ASSERT_FLOAT_EQ(resultf.y, 5.0f);
|
||||
}
|
||||
|
||||
TEST(Vec2D, Normalization) {
|
||||
Vec2D<float> v{3.0f, 4.0f}; // Length = 5
|
||||
|
||||
v.normalize();
|
||||
ASSERT_FLOAT_EQ(v.x, 0.6f);
|
||||
ASSERT_FLOAT_EQ(v.y, 0.8f);
|
||||
|
||||
// Check that length is approximately 1
|
||||
float length = sqrt(v.x * v.x + v.y * v.y);
|
||||
ASSERT_NEAR(length, 1.0f, 1e-6f);
|
||||
}
|
||||
|
||||
TEST(Vec2D, NormalizedCopy) {
|
||||
Vec2D<float> v{3.0f, 4.0f};
|
||||
Vec2D<float> normalized = v.normalized();
|
||||
|
||||
// Original should be unchanged
|
||||
ASSERT_FLOAT_EQ(v.x, 3.0f);
|
||||
ASSERT_FLOAT_EQ(v.y, 4.0f);
|
||||
|
||||
// Normalized copy should be unit length
|
||||
ASSERT_FLOAT_EQ(normalized.x, 0.6f);
|
||||
ASSERT_FLOAT_EQ(normalized.y, 0.8f);
|
||||
|
||||
float length =
|
||||
sqrt(normalized.x * normalized.x + normalized.y * normalized.y);
|
||||
ASSERT_NEAR(length, 1.0f, 1e-6f);
|
||||
}
|
||||
|
||||
TEST(Vec2D, ZeroVectorNormalization) {
|
||||
Vec2D<float> v{0.0f, 0.0f};
|
||||
|
||||
v.normalize();
|
||||
ASSERT_FLOAT_EQ(v.x, 0.0f);
|
||||
ASSERT_FLOAT_EQ(v.y, 0.0f);
|
||||
|
||||
// Test normalized() as well
|
||||
Vec2D<float> v2{0.0f, 0.0f};
|
||||
Vec2D<float> normalized = v2.normalized();
|
||||
ASSERT_FLOAT_EQ(normalized.x, 0.0f);
|
||||
ASSERT_FLOAT_EQ(normalized.y, 0.0f);
|
||||
}
|
||||
|
||||
TEST(Vec2D, VerySmallVectorNormalization) {
|
||||
Vec2D<float> v{1e-7f, 1e-7f}; // Very small vector
|
||||
|
||||
v.normalize();
|
||||
// Should be treated as zero vector
|
||||
ASSERT_FLOAT_EQ(v.x, 0.0f);
|
||||
ASSERT_FLOAT_EQ(v.y, 0.0f);
|
||||
}
|
||||
|
||||
TEST(Vec2D, OutputOperator) {
|
||||
Vec2D<int> v{42, 24};
|
||||
|
||||
std::ostringstream oss;
|
||||
oss << v;
|
||||
ASSERT_EQ(oss.str(), "( 42, 24)");
|
||||
}
|
||||
|
||||
TEST(Vec2D, ChainedOperations) {
|
||||
Vec2D<float> a{1.0f, 2.0f};
|
||||
Vec2D<float> b{3.0f, 4.0f};
|
||||
|
||||
// Test chaining: (a + b) * 2.0f
|
||||
Vec2D<float> result = (a + b) * 2.0f;
|
||||
ASSERT_FLOAT_EQ(result.x, 8.0f);
|
||||
ASSERT_FLOAT_EQ(result.y, 12.0f);
|
||||
|
||||
// Test chaining with assignment
|
||||
a += b;
|
||||
a = a * 0.5f;
|
||||
ASSERT_FLOAT_EQ(a.x, 2.0f);
|
||||
ASSERT_FLOAT_EQ(a.y, 3.0f);
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
::testing::InitGoogleTest(&argc, argv);
|
||||
return RUN_ALL_TESTS();
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user