Skip to content

Commit

Permalink
Store objects with World
Browse files Browse the repository at this point in the history
  • Loading branch information
anchpop committed Oct 11, 2024
1 parent fa1a151 commit 784d355
Show file tree
Hide file tree
Showing 13 changed files with 93 additions and 144 deletions.
4 changes: 2 additions & 2 deletions OpenGL/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ set(CMAKE_CXX_STANDARD 23)
set(VENDOR_DIR ${CMAKE_CURRENT_SOURCE_DIR}/vendor)

# Add application code
file(GLOB cpp_files "src/Application.cpp" "src/rendering/*.cpp" "src/game_objects/GameObject.cpp" "src/game_objects/Background.cpp" "src/game_objects/SquareObject.cpp", "src/Input.cpp", "src/game_objects/Tile.cpp")
file(GLOB header_files "src/Application.h" "src/rendering/*.h" "src/game_objects/GameObject.h" "src/game_objects/Background.h" "src/game_objects/SquareObject.h" "src/Input.h" "src/game_objects/Tile.h")
file(GLOB cpp_files "src/Application.cpp" "src/rendering/*.cpp" "src/game_objects/GameObject.cpp" "src/game_objects/Background.cpp" "src/game_objects/SquareObject.cpp" "src/Input.cpp" "src/game_objects/Tile.cpp" "src/World.cpp" "src/game_objects/Camera.cpp" "src/WeakMemoizeConstructor.hpp")
file(GLOB header_files "src/Application.h" "src/rendering/*.h" "src/game_objects/GameObject.h" "src/game_objects/Background.h" "src/game_objects/SquareObject.h" "src/Input.h" "src/game_objects/Tile.h" "src/World.h" "src/game_objects/Camera.h")

# Add resource files
file(GLOB_RECURSE res_files "res/*")
Expand Down
66 changes: 14 additions & 52 deletions OpenGL/src/Application.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
#include "game_objects/Background.h"
#include "game_objects/SquareObject.h"
#include "game_objects/Tile.h"
#include "World.h"

#define GL_SILENCE_DEPRECATION

Expand All @@ -50,6 +51,9 @@
#endif
#include <GLFW/glfw3.h> // Will drag system OpenGL headers


const float TICKS_PER_SECOND = 3.0f;

void setWindowIcon(GLFWwindow* window, const char* iconPath) {
int width, height, channels;
unsigned char* pixels = stbi_load(iconPath, &width, &height, &channels, 4);
Expand Down Expand Up @@ -291,6 +295,8 @@ Application::Application()
, uncapturedErrorCallbackHandle(getUncapturedErrorCallbackHandle(device))
, queue(device.getQueue())
, surfaceFormat(preferredFormat(surface, adapter)) {
glfwSetKeyCallback(window, key_callback);

glfwSetWindowUserPointer(window, this);
// Use a non-capturing lambda as resize callback
glfwSetFramebufferSizeCallback(window, [](GLFWwindow* window, int, int) {
Expand All @@ -302,6 +308,9 @@ Application::Application()

InitializeResPath();

std::string icon_path = res_path / "images" / "Logo2.png";
setWindowIcon(window, icon_path.c_str());

initialized = true;
}

Expand Down Expand Up @@ -374,12 +383,12 @@ wgpu::TextureView Application::GetNextSurfaceTextureView() {
}

// Draw a frame and handle events
void mainLoop(Application& application, Renderer& renderer, std::vector<std::unique_ptr<GameObject>>& gameobjects) {
void mainLoop(Application& application, Renderer& renderer) {
glfwPollEvents();

auto device = application.getDevice();

for (auto& gameobject : gameobjects) {
for (auto& gameobject : World::gameobjects) {
gameobject->update();
}

Expand All @@ -391,9 +400,7 @@ void mainLoop(Application& application, Renderer& renderer, std::vector<std::uni
RenderPass renderPass(encoder);
renderer.renderPass = renderPass.get();

for (auto& gameobject : gameobjects) {
gameobject->render(renderer);
}
World::RenderObjects(renderer);

// The render pass and command encoder will be ended and submitted in their destructors
}
Expand All @@ -415,11 +422,7 @@ int main(void) {
Application& application = Application::get();
Renderer renderer = Renderer();

std::vector<std::unique_ptr<GameObject>> gameobjects;
gameobjects.push_back(std::make_unique<Background>("Stars"));
gameobjects.push_back(std::make_unique<SquareObject>("Floor", DrawPriority::Floor, 0, 0, "floor.png"));
gameobjects.push_back(std::make_unique<Tile>("Tile", true, true, 1, 0));
gameobjects.push_back(std::make_unique<Tile>("Tile", false, true, 0, 1));
World::LoadMap("SpaceShip.txt");

// Not Emscripten-friendly
if (!application.initialized) {
Expand All @@ -428,7 +431,7 @@ int main(void) {

// Not emscripten-friendly
while (application.IsRunning()) {
mainLoop(application, renderer, gameobjects);
mainLoop(application, renderer);
}

application.Terminate();
Expand All @@ -437,47 +440,6 @@ int main(void) {


/*
const float TICKS_PER_SECOND = 3.0f;
/* Initialize the library * /
if (!glfwInit())
return -1;
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
// Get the primary monitor
GLFWmonitor* primaryMonitor = glfwGetPrimaryMonitor();
const GLFWvidmode* mode = glfwGetVideoMode(primaryMonitor);
// Create a fullscreen window
GLFWwindow* window = glfwCreateWindow(mode->width, mode->height, "SpaceBoom", NULL, NULL);
if (!window) {
std::cerr << "Failed to create GLFW window" << std::endl;
glfwTerminate();
return -1;
}
glfwSetKeyCallback(window, key_callback);
// Set the window icon
std::string icon_path = Renderer::ResPath() + "images/Logo2.png";
setWindowIcon(window, icon_path.c_str());
/* Make the window's context current * /
glfwMakeContextCurrent(window);
glfwSwapInterval(1);
if (glewInit() != GLEW_OK)
std::cout << "Error!" << std::endl;
std::cout << "current version of GL: " << glGetString(GL_VERSION) << std::endl;
GLCall(glEnable(GL_BLEND));
GLCall(glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA));
// Initialize ImGui
IMGUI_CHECKVERSION();
ImGui::CreateContext();
Expand Down
28 changes: 0 additions & 28 deletions OpenGL/src/Renderer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -13,34 +13,6 @@ ImFont* load_font(ImGuiIO* io, const std::string& font_name, int size) {
return font;
}

glm::mat4 CalculateMVP(std::tuple<int, int> windowSize, const glm::vec2& objectPosition, float objectRotationDegrees,
float objectScale) {
// Retrieve window size from the renderer
auto [width, height] = windowSize;

// Calculate aspect ratio
float aspectRatio = static_cast<float>(width) / static_cast<float>(height);

// Create orthographic projection matrix
float orthoWidth = Camera::scale * aspectRatio;
glm::mat4 projection =
glm::ortho(-orthoWidth / 2.0f, orthoWidth / 2.0f, -Camera::scale / 2.0f, Camera::scale / 2.0f, -1.0f, 1.0f);

// Create view matrix
glm::mat4 view = glm::translate(glm::mat4(1.0f), glm::vec3(-Camera::position, 0.0f));

// Create model matrix
glm::mat4 model = glm::translate(glm::mat4(1.0f), glm::vec3(objectPosition, 0.0f));
float rotationRadians = glm::radians(objectRotationDegrees);
model = glm::rotate(model, rotationRadians, glm::vec3(0.0f, 0.0f, 1.0f));
model = glm::scale(model, glm::vec3(objectScale, objectScale, 1.0f));

// Combine matrices to form MVP
glm::mat4 mvp = projection * view * model;

return mvp;
}

glm::vec2 Renderer::ScreenToWorldPosition(const glm::vec2& screenPos) {
// Retrieve window size from the renderer
auto [width, height] = WindowSize();
Expand Down
51 changes: 28 additions & 23 deletions OpenGL/src/World.cpp
Original file line number Diff line number Diff line change
@@ -1,30 +1,33 @@
#include "World.h"

#include <iostream>
#include <fstream>
#include "World.h"
#include <algorithm>

#include "Renderer.h"
#include "game_objects/Player.h"
#include "rendering/Renderer.h"
// #include "game_objects/Player.h"
#include "game_objects/Background.h"
#include "game_objects/Camera.h"
#include "game_objects/Tile.h"
#include "game_objects/enemies/Bomber.h"
#include "game_objects/enemies/Turret.h"
#include "game_objects/Mine.h"
// #include "game_objects/enemies/Bomber.h"
// #include "game_objects/enemies/Turret.h"
// #include "game_objects/Mine.h"

std::vector<std::shared_ptr<GameObject>> World::gameobjects = {};
std::vector<std::unique_ptr<GameObject>> World::gameobjectstoadd = {};
float World::timeSpeed = 1.0f;
bool World::settingTimeSpeed = false;
bool World::shouldTick = false;

void World::LoadMap(const std::string& map_path) {
void World::LoadMap(const std::filesystem::path& map_path) {
gameobjects.clear();

std::ifstream file(Renderer::ResPath() + map_path);
std::filesystem::path map_path_full = Application::get().res_path / "maps" / map_path;

std::ifstream file(map_path_full);

if (!file.is_open()) {
std::cerr << "Error opening file: " << map_path << std::endl;
std::cerr << "Error opening file: " << map_path_full << std::endl;
}

std::vector<std::string> lines;
Expand All @@ -43,32 +46,32 @@ void World::LoadMap(const std::string& map_path) {
size_t y = total_rows - row;
if (c != '\n') {
if (c == 'b') { // Background
gameobjects.push_back(std::make_shared<Background>(Background("Background")));
gameobjects.push_back(std::make_shared<Background>("Background"));
}
if (c == 'p') { // player
gameobjects.push_back(std::make_shared<Player>(Player("Coolbox", (float)x, (float)y)));
gameobjects.push_back(std::make_shared<Tile>(Tile("Floor", (float)x, (float)y)));
// gameobjects.push_back(std::make_shared<Player>(Player("Coolbox", (float)x, (float)y)));
gameobjects.push_back(std::make_shared<Tile>("Floor", (float)x, (float)y));
}
if (c == 'f') { // floor
gameobjects.push_back(std::make_shared<Tile>(Tile("Floor", (float)x, (float)y)));
gameobjects.push_back(std::make_shared<Tile>("Floor", (float)x, (float)y));
}
if (c == 'w') { // wall
gameobjects.push_back(std::make_shared<Tile>(Tile("Wall", true, false, (float)x, (float)y)));
gameobjects.push_back(std::make_shared<Tile>("Wall", true, false, (float)x, (float)y));
}
if (c == 'W') { // wall
gameobjects.push_back(std::make_shared<Tile>(Tile("Wall", true, true, (float)x, (float)y)));
gameobjects.push_back(std::make_shared<Tile>("Wall", true, true, (float)x, (float)y));
}
if (c == 'e') { // enemy Bomber
gameobjects.push_back(std::make_shared<Bomber>(Bomber("bomber", (float)x, (float)y)));
gameobjects.push_back(std::make_shared<Tile>(Tile("Floor", (float)x, (float)y)));
// gameobjects.push_back(std::make_shared<Bomber>(Bomber("bomber", (float)x, (float)y)));
gameobjects.push_back(std::make_shared<Tile>("Floor", (float)x, (float)y));
}
if (c == 't') { // Turret
gameobjects.push_back(std::make_shared<Turret>(Turret("turret", (float)x, (float)y)));
gameobjects.push_back(std::make_shared<Tile>(Tile("Floor", (float)x, (float)y)));
// gameobjects.push_back(std::make_shared<Turret>(Turret("turret", (float)x, (float)y)));
gameobjects.push_back(std::make_shared<Tile>("Floor", (float)x, (float)y));
}
if (c == 'm') { // Mine
gameobjects.push_back(std::make_shared<Mine>(Mine("mine", (float)x, (float)y)));
gameobjects.push_back(std::make_shared<Tile>(Tile("Floor", (float)x, (float)y)));
// gameobjects.push_back(std::make_shared<Mine>(Mine("mine", (float)x, (float)y)));
gameobjects.push_back(std::make_shared<Tile>("Floor", (float)x, (float)y));
}
}
}
Expand Down Expand Up @@ -126,6 +129,8 @@ void World::RenderObjects(Renderer& renderer) {
}

bool World::ticksPaused() {
auto player = getFirst<Player>();
return player->pauseTicks();
// TODO: uncomment
// auto player = getFirst<Player>();
// return player->pauseTicks();
return false;
}
8 changes: 5 additions & 3 deletions OpenGL/src/World.h
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
// World.h
#pragma once

#include <filesystem>
#include <functional>

#include "game_objects/GameObject.h"
#include "Renderer.h"
#include "rendering/Renderer.h"

class World {
public:
Expand All @@ -14,7 +16,7 @@ class World {

static bool ticksPaused();

static std::vector<GameObject*> get_gameobjects() {
static std::vector<GameObject*> get_gameobjects() {
// return a vector of all gameobjects and their gameobjects.children
std::vector<GameObject*> allGameObjects;
for (auto& gameobject : gameobjects) {
Expand Down Expand Up @@ -65,7 +67,7 @@ class World {
return where<T>([&](const T& obj) { return obj.tile_x == x && obj.tile_y == y; });
}

static void LoadMap(const std::string& map_path);
static void LoadMap(const std::filesystem::path& map_path);

static void UpdateObjects();
static void TickObjects();
Expand Down
4 changes: 2 additions & 2 deletions OpenGL/src/game_objects/Camera.cpp
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#include "Camera.h"

glm::vec2 Camera::position = {0.0, 0.0};
float Camera::scale = 14.0f;
glm::vec2 Camera::position = {20.0, 30.0};
float Camera::scale = 19.0f;
4 changes: 3 additions & 1 deletion OpenGL/src/game_objects/GameObject.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,6 @@ void GameObject::update() {}

void GameObject::tickUpdate() {}

void GameObject::render(Renderer& renderer) {}
void GameObject::render(Renderer& renderer) {
std::cout << "Rendering GameObject (you should not see this lol) " << name << std::endl;
}
2 changes: 1 addition & 1 deletion OpenGL/src/game_objects/SquareObject.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ SquareObject::SquareObject(const std::string& name, DrawPriority drawPriority, i
SquareObjectVertexUniform{CalculateMVP(glm::vec2{tile_x, tile_y}, 0, 1)})),
fragmentUniform(
BufferView<SquareObjectFragmentUniform>::create(SquareObjectFragmentUniform{glm::vec4(0.0f, 0.0f, 0.0f, 0.0f)})),
texture(std::make_shared<Texture>(texturePath)) {}
texture(Texture::create(texturePath)) {}

void SquareObject::render(Renderer& renderer) {
this->vertexUniform.Update(SquareObjectVertexUniform{CalculateMVP(glm::vec2{tile_x, tile_y}, 0, 1)});
Expand Down
7 changes: 3 additions & 4 deletions OpenGL/src/game_objects/Tile.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,9 @@ Tile::Tile(const std::string& name, bool wall, bool unbreakable, float x, float
: SquareObject(name, DrawPriority::Floor, x, y, "alt-wall-bright.png")
, wall(wall)
, unbreakable(unbreakable)
, wallTexture(std::make_shared<Texture>("alt-wall-bright.png"))
, wallTextureUnbreakable(std::make_shared<Texture>("alt-wall-unbreakable.png"))
, floorTexture(
std::make_shared<Texture>(std::vector<std::string>{"2-alt-floor.png", "2-alt-floor-2.png"}[rand() % 2])) {
, wallTexture(Texture::create("alt-wall-bright.png"))
, wallTextureUnbreakable(Texture::create("alt-wall-unbreakable.png"))
, floorTexture(Texture::create(std::vector<std::string>{"2-alt-floor.png", "2-alt-floor-2.png"}[rand() % 2])) {
setTexture();
}

Expand Down
2 changes: 1 addition & 1 deletion OpenGL/src/rendering/Buffer.h
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ class Buffer : public std::enable_shared_from_this<Buffer<T, Uniform>> {
freeIndices_.pop_back();
} else {
// Check if there's space in the current buffer
if (capacity_ < count_) {
if (count_ < capacity_) {
allocatedIndex = count_;
++count_;
} else {
Expand Down
27 changes: 0 additions & 27 deletions OpenGL/src/rendering/RenderPass.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
#include "CommandEncoder.h"
#include "Application.h"

#include "glm/gtc/matrix_transform.hpp"

RenderPass::RenderPass(CommandEncoder& encoder) {
auto& application = Application::get();
Expand Down Expand Up @@ -42,29 +41,3 @@ RenderPass::~RenderPass() {
wgpu::RenderPassEncoder& RenderPass::get() {
return renderPass_;
}


glm::mat4 CalculateMVP(const glm::vec2& objectPosition, float objectRotationDegrees, float objectScale) {
glm::ivec2 windowSize = Application::get().windowSize();

// Calculate aspect ratio
float aspectRatio = static_cast<float>(windowSize.x) / static_cast<float>(windowSize.y);

// Create orthographic projection matrix
float orthoWidth = 18 * aspectRatio;
glm::mat4 projection = glm::ortho(-orthoWidth / 2.0f, orthoWidth / 2.0f, -18 / 2.0f, 18 / 2.0f, -1.0f, 1.0f);

// Create view matrix
glm::mat4 view = glm::translate(glm::mat4(1.0f), glm::vec3(-glm::vec2(1, 1), 0.0f));

// Create model matrix
glm::mat4 model = glm::translate(glm::mat4(1.0f), glm::vec3(objectPosition, 0.0f));
float rotationRadians = glm::radians(objectRotationDegrees);
model = glm::rotate(model, rotationRadians, glm::vec3(0.0f, 0.0f, 1.0f));
model = glm::scale(model, glm::vec3(objectScale, objectScale, 1.0f));

// Combine matrices to form MVP
glm::mat4 mvp = projection * view * model;

return mvp;
}
Loading

0 comments on commit 784d355

Please sign in to comment.