diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000..0fd78d3 --- /dev/null +++ b/.clang-format @@ -0,0 +1,12 @@ +BasedOnStyle: Google +ColumnLimit: 100 + +SortIncludes: false + +AllowShortFunctionsOnASingleLine: Empty +AllowShortBlocksOnASingleLine: Empty +ReflowComments: false + +PenaltyBreakAssignment: 1000 +PenaltyBreakBeforeFirstCallParameter: 1000 +BinPackArguments: false diff --git a/.github/workflows/format-ci.yml b/.github/workflows/format-ci.yml new file mode 100644 index 0000000..4460ff0 --- /dev/null +++ b/.github/workflows/format-ci.yml @@ -0,0 +1,18 @@ +name: Format Check + +on: + pull_request: + push: + branches: [ main ] + +jobs: + format: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Install clang-format + run: sudo apt install clang-format + + - name: Check formatting + run: python3 format.py --check diff --git a/core/component/audio_source.cpp b/core/component/audio_source.cpp index 5934e8d..12c8b93 100644 --- a/core/component/audio_source.cpp +++ b/core/component/audio_source.cpp @@ -2,18 +2,19 @@ namespace SpaceEngine { -//AudioSource::AudioSource() = default; +// AudioSource::AudioSource() = default; // -//void AudioSource::setAudio(const std::string& path) { +// void AudioSource::setAudio(const std::string& path) { // m_audioPath = path; -//// m_audio = ResourceManager::load(path, std::dynamic_pointer_cast(shared_from_this())); +//// m_audio = ResourceManager::load(path, +/// std::dynamic_pointer_cast(shared_from_this())); //} // -//void AudioSource::play() const { +// void AudioSource::play() const { // if (m_audio) { // // TODO: waiting for Audio system // // Audio::playSound(m_audio->getData()); // } //} -} +} // namespace SpaceEngine diff --git a/core/component/audio_source.hpp b/core/component/audio_source.hpp index acc33a5..b72fff5 100644 --- a/core/component/audio_source.hpp +++ b/core/component/audio_source.hpp @@ -8,13 +8,13 @@ namespace SpaceEngine { struct AudioSource { -// explicit AudioSource(); -// -// void setAudio(const std::string& path); -// void play() const; -// -// std::shared_ptr m_audio; -// std::string m_audioPath; + // explicit AudioSource(); + // + // void setAudio(const std::string& path); + // void play() const; + // + // std::shared_ptr m_audio; + // std::string m_audioPath; }; -} +} // namespace SpaceEngine diff --git a/core/component/camera.cpp b/core/component/camera.cpp index a261d59..fec290d 100644 --- a/core/component/camera.cpp +++ b/core/component/camera.cpp @@ -19,27 +19,31 @@ glm::mat4 Camera::getViewMatrix(const World& world, Entity e) const { } glm::mat4 Camera::getProjectionMatrix() const { - if (projectionType == ProjectionType::PERSPECTIVE) { - glm::mat4 projection = glm::perspective(glm::radians(fieldOfView), aspectRatio, nearPlane, farPlane); - projection[1][1] *= -1; - return projection; - } else { - const float width = orthographicSize * aspectRatio; - const float height = orthographicSize; - glm::mat4 projection = glm::ortho(-width, width, -height, height, nearPlane, farPlane); - projection[1][1] *= -1; - return projection; + glm::mat4 projection; + switch (projectionType) { + case ProjectionType::PERSPECTIVE: + projection = glm::perspective(glm::radians(fieldOfView), aspectRatio, nearPlane, farPlane); + break; + case ProjectionType::ORTHOGRAPHIC: + projection = glm::ortho(-orthographicSize * aspectRatio, + orthographicSize * aspectRatio, + -orthographicSize, + orthographicSize, + nearPlane, + farPlane); + break; } + + projection[1][1] *= -1; + return projection; } void Camera::updateCameraVectors() { - front = glm::normalize(glm::vec3( - cos(glm::radians(yaw)) * cos(glm::radians(pitch)), - sin(glm::radians(pitch)), - sin(glm::radians(yaw)) * cos(glm::radians(pitch)) - )); + front = glm::normalize(glm::vec3(cos(glm::radians(yaw)) * cos(glm::radians(pitch)), + sin(glm::radians(pitch)), + sin(glm::radians(yaw)) * cos(glm::radians(pitch)))); right = glm::normalize(glm::cross(front, worldUp)); up = glm::normalize(glm::cross(right, front)); } -} +} // namespace SpaceEngine diff --git a/core/component/camera.hpp b/core/component/camera.hpp index bc68b25..cd202d4 100644 --- a/core/component/camera.hpp +++ b/core/component/camera.hpp @@ -1,21 +1,16 @@ #pragma once -#include "glm/glm.hpp" -#include "glm/gtc/matrix_transform.hpp" - #include "../imgui/imgui_impl_opengl3.h" - -#include "ecs/world.hpp" -#include "ecs/entity.hpp" #include "component/transform.hpp" +#include "ecs/entity.hpp" +#include "ecs/world.hpp" +#include "glm/glm.hpp" +#include "glm/gtc/matrix_transform.hpp" namespace SpaceEngine { struct Camera { - enum class ProjectionType { - PERSPECTIVE, - ORTHOGRAPHIC - }; + enum class ProjectionType { PERSPECTIVE, ORTHOGRAPHIC }; glm::vec3 front{}; glm::vec3 up{}; @@ -26,7 +21,7 @@ struct Camera { ProjectionType projectionType = ProjectionType::PERSPECTIVE; float fieldOfView = 45.0f; - float aspectRatio = 16.0f/9.0f; + float aspectRatio = 16.0f / 9.0f; float nearPlane = 0.1f; float farPlane = 100.0f; @@ -40,4 +35,4 @@ struct Camera { void updateCameraVectors(); }; -} +} // namespace SpaceEngine diff --git a/core/component/light.cpp b/core/component/light.cpp index b4c667b..82bb3a3 100644 --- a/core/component/light.cpp +++ b/core/component/light.cpp @@ -2,8 +2,6 @@ namespace SpaceEngine { -Light::Light() { +Light::Light() {} -} - -} +} // namespace SpaceEngine diff --git a/core/component/light.hpp b/core/component/light.hpp index 90e4524..e54b4d9 100644 --- a/core/component/light.hpp +++ b/core/component/light.hpp @@ -4,11 +4,7 @@ namespace SpaceEngine { -enum LightType { - POINT, - DIRECTIONAL, - SPOT -}; +enum LightType { POINT, DIRECTIONAL, SPOT }; struct Light { float intensity = 1.0f; @@ -22,4 +18,4 @@ struct Light { Light(); }; -} +} // namespace SpaceEngine diff --git a/core/component/model_renderer.cpp b/core/component/model_renderer.cpp index a25d769..e9efa8a 100644 --- a/core/component/model_renderer.cpp +++ b/core/component/model_renderer.cpp @@ -11,4 +11,4 @@ void ModelRenderer::setModel() { model = std::make_shared(path.c_str()); } -} \ No newline at end of file +} // namespace SpaceEngine \ No newline at end of file diff --git a/core/component/model_renderer.hpp b/core/component/model_renderer.hpp index e699ad7..9535a35 100644 --- a/core/component/model_renderer.hpp +++ b/core/component/model_renderer.hpp @@ -1,16 +1,18 @@ #pragma once -#include "model/model.hpp" #include +#include "model/model.hpp" + namespace SpaceEngine { struct ModelRenderer { std::shared_ptr model; - std::string path; // TODO this should not be a path + std::string path; // TODO this should not be a path ModelRenderer(); - void setModel(); // TODO can't remember why I did it like this, should be refactored + void setModel(); // TODO can't remember why I did it like this, should be + // refactored }; -} +} // namespace SpaceEngine diff --git a/core/component/physic.cpp b/core/component/physic.cpp index ce5dbab..7389b37 100644 --- a/core/component/physic.cpp +++ b/core/component/physic.cpp @@ -9,4 +9,4 @@ Physic::Physic() { this->gravity = false; } -} +} // namespace SpaceEngine diff --git a/core/component/physic.hpp b/core/component/physic.hpp index 4eeb539..38dae5f 100644 --- a/core/component/physic.hpp +++ b/core/component/physic.hpp @@ -11,4 +11,4 @@ struct Physic { Physic(); }; -} \ No newline at end of file +} // namespace SpaceEngine \ No newline at end of file diff --git a/core/component/script.hpp b/core/component/script.hpp index c065fc1..e33f15a 100644 --- a/core/component/script.hpp +++ b/core/component/script.hpp @@ -49,4 +49,4 @@ struct Script { virtual void onEnable(); }; -} +} // namespace SpaceEngine diff --git a/core/component/transform.cpp b/core/component/transform.cpp index 7555ddf..a6ab8ad 100644 --- a/core/component/transform.cpp +++ b/core/component/transform.cpp @@ -2,11 +2,11 @@ namespace SpaceEngine { -Transform::Transform(const std::string &name) { +Transform::Transform(const std::string& name) { this->name = name; this->position = Vec3f(); this->rotation = Vec3f(); this->scale = Vec3f(1.0f, 1.0f, 1.0f); } -} +} // namespace SpaceEngine diff --git a/core/component/transform.hpp b/core/component/transform.hpp index 10f3dfc..ac97a82 100644 --- a/core/component/transform.hpp +++ b/core/component/transform.hpp @@ -1,18 +1,19 @@ #pragma once #include + #include "maths/vector.hpp" namespace SpaceEngine { struct Transform { -public: - std::string name; // TODO stay for now but will be in its own component soon + public: + std::string name; // TODO stay for now but will be in its own component soon Vec3f position; Vec3f rotation; Vec3f scale; - explicit Transform(const std::string &name); + explicit Transform(const std::string& name); }; -} \ No newline at end of file +} // namespace SpaceEngine \ No newline at end of file diff --git a/core/ecs/entity.hpp b/core/ecs/entity.hpp index 4d6948f..bf5312e 100644 --- a/core/ecs/entity.hpp +++ b/core/ecs/entity.hpp @@ -5,15 +5,14 @@ namespace SpaceEngine { struct Entity { - u32 id{}; + u32 id{}; - bool operator==(const Entity& other) const { - return id == other.id; - } - - bool operator!=(const Entity& other) const { - return id != other.id; - } + bool operator==(const Entity& other) const { + return id == other.id; + } + bool operator!=(const Entity& other) const { + return id != other.id; + } }; -} +} // namespace SpaceEngine diff --git a/core/ecs/storage.hpp b/core/ecs/storage.hpp index 1f3382c..3001480 100644 --- a/core/ecs/storage.hpp +++ b/core/ecs/storage.hpp @@ -5,52 +5,60 @@ namespace SpaceEngine { class IStorage { -public: - virtual ~IStorage() = default; - virtual void remove(u32 id) = 0; - virtual void clear() = 0; + public: + virtual ~IStorage() = default; + virtual void remove(u32 id) = 0; + virtual void clear() = 0; }; -template -class Storage final : public IStorage{ -private: - std::unordered_map data; -public: - bool has(u32 id) const { - return data.find(id) != data.end(); - } +template +class Storage final : public IStorage { + private: + std::unordered_map data; - T& get(u32 id) { - auto it = data.find(id); - if (it == data.end()) throw std::runtime_error("Storage::get: missing component"); - return it->second; - } + public: + bool has(u32 id) const { + return data.find(id) != data.end(); + } - const T& get(u32 id) const { - auto it = data.find(id); - if (it == data.end()) throw std::runtime_error("Storage::get: missing component"); - return it->second; + T& get(u32 id) { + auto it = data.find(id); + if (it == data.end()) { + throw std::runtime_error("Storage::get: missing component"); } + return it->second; + } - T& add(u32 id, T value) { - auto [it, inserted] = data.emplace(id, std::move(value)); - if (!inserted) { - it->second = std::move(value); - } - return it->second; + const T& get(u32 id) const { + auto it = data.find(id); + if (it == data.end()) { + throw std::runtime_error("Storage::get: missing component"); } + return it->second; + } - void remove(u32 id) override { - data.erase(id); + T& add(u32 id, T value) { + auto [it, inserted] = data.emplace(id, std::move(value)); + if (!inserted) { + it->second = std::move(value); } + return it->second; + } - void clear() override { - data.clear(); - } + void remove(u32 id) override { + data.erase(id); + } - auto& raw() { return data; } - const auto& raw() const { return data; } + void clear() override { + data.clear(); + } + auto& raw() { + return data; + } + const auto& raw() const { + return data; + } }; -} \ No newline at end of file +} // namespace SpaceEngine \ No newline at end of file diff --git a/core/ecs/world.hpp b/core/ecs/world.hpp index 5153b90..ca06ce3 100644 --- a/core/ecs/world.hpp +++ b/core/ecs/world.hpp @@ -1,179 +1,190 @@ #pragma once -#include -#include #include +#include +#include -#include "types/types.hpp" #include "entity.hpp" #include "storage.hpp" +#include "types/types.hpp" namespace SpaceEngine { class World { -private: - std::unordered_map> storages; - u32 next_id = 0; - - template - Storage& storage() { - auto key = std::type_index(typeid(T)); - auto it = storages.find(key); - if (it == storages.end()) { - auto ptr = std::make_unique>(); - auto *raw = ptr.get(); - storages.emplace(key, std::move(ptr)); - return *raw; - } - return *static_cast*>(it->second.get()); - } - - template - const Storage& storage() const { - return const_cast(this)->storage(); - } - -public: - World() = default; - ~World() = default; - - Entity create() { - u32 id = next_id++; - return Entity{id}; - } - - void destroy(Entity e) { - for (auto& [_, storage] : storages) { - storage->remove(e.id); - } - } - - template - bool has_component(Entity e) const { - return storage().has(e.id); + private: + std::unordered_map> storages; + u32 next_id = 0; + + template + Storage& storage() { + auto key = std::type_index(typeid(T)); + auto it = storages.find(key); + if (it == storages.end()) { + auto ptr = std::make_unique>(); + auto* raw = ptr.get(); + storages.emplace(key, std::move(ptr)); + return *raw; } - - template - T& add_component(Entity e, T value) { - return storage().add(e.id, std::move(value)); - } - - template - void remove_component(Entity e) { - storage().remove(e.id); + return *static_cast*>(it->second.get()); + } + + template + const Storage& storage() const { + return const_cast(this)->storage(); + } + + public: + World() = default; + ~World() = default; + + Entity create() { + u32 id = next_id++; + return Entity{id}; + } + + void destroy(Entity e) { + for (auto& [_, storage] : storages) { + storage->remove(e.id); } + } + + template + bool has_component(Entity e) const { + return storage().has(e.id); + } + + template + T& add_component(Entity e, T value) { + return storage().add(e.id, std::move(value)); + } + + template + void remove_component(Entity e) { + storage().remove(e.id); + } + + template + T& get_component(Entity e) { + return storage().get(e.id); + } + + template + const T& get_component(Entity e) const { + return storage().get(e.id); + } + + template + class View1 { + public: + explicit View1(const World& w) : world(w), st(&w.storage()) {} + + class Iterator { + public: + using MapIt = typename std::unordered_map::const_iterator; + Iterator(const World& w, const std::unordered_map* map, MapIt it, MapIt end) + : world(w), map(map), it(it), end(end) {} + Entity operator*() const { + return Entity{it->first}; + } + Iterator& operator++() { + ++it; + return *this; + } + bool operator!=(const Iterator& other) const { + return it != other.it; + } + + private: + const World& world; + const std::unordered_map* map; + MapIt it; + MapIt end; + }; - template - T& get_component(Entity e) { - return storage().get(e.id); + Iterator begin() const { + const auto& m = st->raw(); + return Iterator{world, &m, m.begin(), m.end()}; } - template - const T& get_component(Entity e) const { - return storage().get(e.id); + Iterator end() const { + const auto& m = st->raw(); + return Iterator{world, &m, m.end(), m.end()}; } - template - class View1 { - public: - explicit View1(const World& w) : world(w), st(&w.storage()) {} - - class Iterator { - public: - using MapIt = typename std::unordered_map::const_iterator; - Iterator(const World& w, const std::unordered_map* map, MapIt it, MapIt end): world(w), map(map), it(it), end(end) {} - Entity operator*() const { return Entity{ it->first }; } - Iterator& operator++() { - ++it; - return *this; - } - bool operator !=(const Iterator& other) const { return it != other.it; } - private: - const World& world; - const std::unordered_map* map; - MapIt it; - MapIt end; - }; - - Iterator begin() const { - const auto& m = st-> raw(); - return Iterator{ world, &m, m.begin(), m.end() }; + private: + const World& world; + const Storage* st; + }; + + template + class View2 { + public: + explicit View2(const World& w) : world(w), a(&w.storage()) {} + + class Iterator { + public: + using MapIt = typename std::unordered_map::const_iterator; + + Iterator(const World& w, const std::unordered_map* amap, MapIt it, MapIt end) + : world(w), amap(amap), it(it), end(end) { + skip_invalid(); + } + + Entity operator*() const { + return Entity{it->first}; + } + + Iterator& operator++() { + ++it; + skip_invalid(); + return *this; + } + + bool operator!=(const Iterator& other) const { + return it != other.it; + } + + private: + void skip_invalid() { + while (it != end) { + Entity e{it->first}; + if (world.has_component(e)) { + return; + } + ++it; } + } - Iterator end() const { - const auto& m = st->raw(); - return Iterator{ world, &m, m.end(), m.end() }; - } - - private: - const World& world; - const Storage* st; + const World& world; + const std::unordered_map* amap; + MapIt it; + MapIt end; }; - template - class View2 { - public: - explicit View2(const World& w) : world(w), a(&w.storage()) {} - - class Iterator { - public: - using MapIt = typename std::unordered_map::const_iterator; - - Iterator(const World& w, - const std::unordered_map* amap, - MapIt it, - MapIt end) - : world(w), amap(amap), it(it), end(end) { - skip_invalid(); - } - - Entity operator*() const { return Entity{ it->first }; } - - Iterator& operator++() { - ++it; - skip_invalid(); - return *this; - } - - bool operator!=(const Iterator& other) const { return it != other.it; } - - private: - void skip_invalid() { - while (it != end) { - Entity e{ it->first }; - if (world.has_component(e)) { - return; - } - ++it; - } - } - - const World& world; - const std::unordered_map* amap; - MapIt it; - MapIt end; - }; - - Iterator begin() const { - const auto& m = a->raw(); - return Iterator(world, &m, m.begin(), m.end()); - } + Iterator begin() const { + const auto& m = a->raw(); + return Iterator(world, &m, m.begin(), m.end()); + } - Iterator end() const { - const auto& m = a->raw(); - return Iterator(world, &m, m.end(), m.end()); - } + Iterator end() const { + const auto& m = a->raw(); + return Iterator(world, &m, m.end(), m.end()); + } - private: - const World& world; - const Storage* a; - }; + private: + const World& world; + const Storage* a; + }; - template - View1 view() const { return View1(*this); } + template + View1 view() const { + return View1(*this); + } - template - View2 view() const { return View2(*this); } + template + View2 view() const { + return View2(*this); + } }; -} \ No newline at end of file +} // namespace SpaceEngine \ No newline at end of file diff --git a/core/input/binding.hpp b/core/input/binding.hpp index b569c31..824936f 100644 --- a/core/input/binding.hpp +++ b/core/input/binding.hpp @@ -4,11 +4,7 @@ namespace SpaceEngine { -enum class InputEventType { - OnPress, - OnRelease, - OnHold -}; +enum class InputEventType { OnPress, OnRelease, OnHold }; struct Binding { std::size_t id = 0; @@ -19,4 +15,4 @@ struct Binding { InputEventType type = InputEventType::OnPress; }; -} +} // namespace SpaceEngine diff --git a/core/input/input.cpp b/core/input/input.cpp index b22ed65..f851e02 100644 --- a/core/input/input.cpp +++ b/core/input/input.cpp @@ -22,37 +22,42 @@ float Input::s_scroll = 0.0f; float Input::s_scrollDelta = 0.0f; constexpr auto AllKeys = std::to_array({ - #define KEY_ENTRY(name, glfw) KeyCode::name, +#define KEY_ENTRY(name, glfw) KeyCode::name, KEYCODES(KEY_ENTRY) - #undef KEY_ENTRY +#undef KEY_ENTRY }); constexpr auto AllMouseButtons = std::to_array({ - #define MOUSE_ENTRY(name, glfw) MouseButton::name, - MOUSE_BUTTONS(MOUSE_ENTRY) - #undef MOUSE_ENTRY +#define MOUSE_ENTRY(name, glfw) MouseButton::name, + MOUSE_BUTTONS(MOUSE_ENTRY) +#undef MOUSE_ENTRY }); - int glfwKeyFromKeyCode(const KeyCode key) { switch (key) { - #define DEFINE_CASE(name, glfw) case KeyCode::name: return glfw; - KEYCODES(DEFINE_CASE) - #undef DEFINE_CASE - default: return GLFW_KEY_UNKNOWN; +#define DEFINE_CASE(name, glfw) \ + case KeyCode::name: \ + return glfw; + KEYCODES(DEFINE_CASE) +#undef DEFINE_CASE + default: + return GLFW_KEY_UNKNOWN; } } int glfwButtonFromMouseButton(const MouseButton button) { switch (button) { - #define DEFINE_CASE(name, glfw) case MouseButton::name: return glfw; - MOUSE_BUTTONS(DEFINE_CASE) - #undef DEFINE_CASE - default: return -1; +#define DEFINE_CASE(name, glfw) \ + case MouseButton::name: \ + return glfw; + MOUSE_BUTTONS(DEFINE_CASE) +#undef DEFINE_CASE + default: + return -1; } } -static void glfwScrollCallback(GLFWwindow* /*window*/, const double /*xoffset*/, const double yoffset) { +static void glfwScrollCallback(GLFWwindow*, double, const double yoffset) { Input::onScroll(yoffset); } @@ -92,18 +97,42 @@ void Input::update() { s_deltaY = s_lastMouseY - s_mouseY; } -bool Input::isKeyPressed(const KeyCode key) { return s_currentKeys[key]; } -bool Input::isKeyJustPressed(const KeyCode key) { return s_currentKeys[key] && !s_previousKeys[key]; } -bool Input::isKeyReleased(const KeyCode key) { return !s_currentKeys[key] && s_previousKeys[key]; } -bool Input::isMouseButtonPressed(const MouseButton button) { return s_currentMouseButtons[button]; } -bool Input::isMouseButtonJustPressed(const MouseButton button) { return s_currentMouseButtons[button] && !s_previousMouseButtons[button]; } -bool Input::isMouseButtonReleased(const MouseButton button) { return !s_currentMouseButtons[button] && s_previousMouseButtons[button]; } -float Input::getMouseX() { return s_mouseX; } -float Input::getMouseY() { return s_mouseY; } -float Input::getMouseDeltaX() { return s_deltaX; } -float Input::getMouseDeltaY() { return s_deltaY; } -float Input::getScroll() { return s_scroll; } -float Input::getScrollDelta() { return s_scrollDelta; } +bool Input::isKeyPressed(const KeyCode key) { + return s_currentKeys[key]; +} +bool Input::isKeyJustPressed(const KeyCode key) { + return s_currentKeys[key] && !s_previousKeys[key]; +} +bool Input::isKeyReleased(const KeyCode key) { + return !s_currentKeys[key] && s_previousKeys[key]; +} +bool Input::isMouseButtonPressed(const MouseButton button) { + return s_currentMouseButtons[button]; +} +bool Input::isMouseButtonJustPressed(const MouseButton button) { + return s_currentMouseButtons[button] && !s_previousMouseButtons[button]; +} +bool Input::isMouseButtonReleased(const MouseButton button) { + return !s_currentMouseButtons[button] && s_previousMouseButtons[button]; +} +float Input::getMouseX() { + return s_mouseX; +} +float Input::getMouseY() { + return s_mouseY; +} +float Input::getMouseDeltaX() { + return s_deltaX; +} +float Input::getMouseDeltaY() { + return s_deltaY; +} +float Input::getScroll() { + return s_scroll; +} +float Input::getScrollDelta() { + return s_scrollDelta; +} float Input::consumeScrollDelta() { const float scrollDelta = s_scrollDelta; @@ -111,4 +140,4 @@ float Input::consumeScrollDelta() { return scrollDelta; } -} +} // namespace SpaceEngine diff --git a/core/input/input.hpp b/core/input/input.hpp index e194119..9aa959d 100644 --- a/core/input/input.hpp +++ b/core/input/input.hpp @@ -1,232 +1,77 @@ #pragma once -#include "keycodes.def" -#include "mouse_buttons.def" -#include "log/logger.hpp" - -#include #include #include #include +#include -#include "binding.hpp" #include "GLFW/glfw3.h" +#include "binding.hpp" +#include "keycodes.def" +#include "log/logger.hpp" +#include "mouse_buttons.def" namespace SpaceEngine { enum class KeyCode { - #define DEFINE_ENUM(name, _) name, - KEYCODES(DEFINE_ENUM) - #undef DEFINE_ENUM +#define DEFINE_ENUM(name, _) name, + KEYCODES(DEFINE_ENUM) +#undef DEFINE_ENUM }; enum class MouseButton { - #define DEFINE_ENUM(name, _) name, - MOUSE_BUTTONS(DEFINE_ENUM) - #undef DEFINE_ENUM +#define DEFINE_ENUM(name, _) name, + MOUSE_BUTTONS(DEFINE_ENUM) +#undef DEFINE_ENUM }; -/** - * Input class handles keyboard and mouse state tracking and input bindings. - * Provides per-frame update and access to current input status, as well as - * support for callback bindings to key or mouse events. - */ class Input { -public: - - /** - * Initialize the Input system with the given GLFW window. - * @param window: A pointer to the GLFW window. - */ + public: static void init(GLFWwindow* window); - /** - * Update the current and previous state of inputs. - * Is called once per frame. - */ static void update(); - /** - * Check if a key is currently being pressed. - * @param key: The key to check. - * @return True if the key is pressed, false otherwise. - */ static bool isKeyPressed(KeyCode key); - - /** - * Check if a key was just pressed during the current frame. - * @param key: The key to check. - * @return True if the key was just pressed, false otherwise. - */ static bool isKeyJustPressed(KeyCode key); - - /** - * Check if a key was just released during the current frame. - * @param key: The key to check. - * @return True if the key was just released, false otherwise. - */ static bool isKeyReleased(KeyCode key); - - /** - * Check if a mouse button is currently being pressed. - * @param button: The mouse button to check. - * @return True if the button is pressed, false otherwise. - */ static bool isMouseButtonPressed(MouseButton button); - - /** - * Check if a mouse button was just pressed during the current frame. - * @param button: The mouse button to check. - * @return True if the button was just pressed, false otherwise. - */ static bool isMouseButtonJustPressed(MouseButton button); - - /** - * Check if a mouse button was just released during the current frame. - * @param button: The mouse button to check. - * @return True if the button was just released, false otherwise. - */ static bool isMouseButtonReleased(MouseButton button); - - /** - * Get the current mouse X position. - * @return The horizontal mouse position in window coordinates. - */ static float getMouseX(); - - /** - * Get the current mouse Y position. - * @return The vertical mouse position in window coordinates. - */ static float getMouseY(); - - /** - * Get the horizontal mouse movement since the last frame. - * @return The delta X of the mouse. - */ static float getMouseDeltaX(); - - /** - * Get the vertical mouse movement since the last frame. - * @return The delta Y of the mouse. - */ static float getMouseDeltaY(); - - /** - * Get the accumulated scroll offset. - * @return The current scroll value. - */ static float getScroll(); - - /** - * Get the scroll change since the last frame. - * @return The scroll delta value. - */ static float getScrollDelta(); - - /** - * Get and consume the scroll delta value. - * @note This should be used instead of the basic getScrollDelta. - * @return The scroll delta value. - */ static float consumeScrollDelta(); - - /** - * Internal handler for scroll input events. - * @param offset: The scroll offset reported by GLFW. - */ static void onScroll(double offset); - /** - * Execute the bindings of the specified key - * @param key: The key to simulate. - * @param type: The event type to simulate. - */ static void simulateKey(KeyCode key, InputEventType type = InputEventType::OnPress); + static void simulateMouseButton(MouseButton button, + InputEventType type = InputEventType::OnPress); - /** - * Execute the bindings of the specified mouse button - * @param button: The button to simulate. - * @param type: The event type to simulate. - */ - static void simulateMouseButton(MouseButton button, InputEventType type = InputEventType::OnPress); - - /** - * Bind a callback to a key event. - * @param key: The key to bind. - * @param callback: Function to call on the event. - * @param remainingCalls: Number of times the binding should trigger (-1 for infinite). - * @param type: The input event type (press, release, hold). - * @param description: A short description of the binding (for debugging/logging). - * @param enabled: Either the binding is enabled or not. - * @return The unique ID of the binding. - */ - static std::size_t bindKey(KeyCode key, std::function callback, int remainingCalls = -1, InputEventType type = InputEventType::OnHold, const std::string &description = "", bool enabled = true); - - /** - * Bind a callback to a mouse button event. - * @param button: The mouse button to bind. - * @param callback: Function to call on the event. - * @param remainingCalls: Number of times the binding should trigger (-1 for infinite). - * @param type: The input event type (press, release, hold). - * @param description: A short description of the binding (for debugging/logging). - * @param enabled: Either the binding is enabled or not. - * @return The unique ID of the binding. - */ - static std::size_t bindMouseButton(MouseButton button, std::function callback, int remainingCalls = -1, InputEventType type = InputEventType::OnHold, const std::string &description = "", bool enabled = true); - - /** - * Unbind a specific input callback using its binding ID. - * @param id: The binding ID to remove. - */ - static void unbind(std::size_t id); + static std::size_t bindKey(KeyCode key, std::function callback, int remainingCalls = -1, + InputEventType type = InputEventType::OnHold, + const std::string& description = "", bool enabled = true); - /** - * Unbind all callbacks associated with a specific key. - * @param key: The key to unbind. - */ - static void unbindKey(KeyCode key); + static std::size_t bindMouseButton(MouseButton button, std::function callback, + int remainingCalls = -1, + InputEventType type = InputEventType::OnHold, + const std::string& description = "", bool enabled = true); - /** - * Unbind all callbacks associated with a specific mouse button. - * @param button: The mouse button to unbind. - */ + static void unbind(std::size_t id); + static void unbindKey(KeyCode key); static void unbindMouseButton(MouseButton button); - /** - * Remove all key bindings from the system. - */ static void clearKeyBindings(); - - /** - * Remove all mouse button bindings from the system. - */ static void clearMouseButtonBindings(); - - /** - * Remove all bindings, both key and mouse. - */ static void clearAllBindings(); - - /** - * Execute all eligible key and mouse callbacks based on input state. - */ static void dispatchBindings(); - /** - * Enable the binding of a specific key or mouse button. - * @param id: The binding ID to toggle. - */ static void enableBinding(std::size_t id); - - /** - * Disable the binding of a specific key or mouse button. - * @param id - */ static void disableBinding(std::size_t id); - -private: + private: static GLFWwindow* s_window; static std::unordered_map s_currentKeys; @@ -250,4 +95,4 @@ class Input { static std::size_t s_nextBindingId; }; -} +} // namespace SpaceEngine diff --git a/core/input/input_binding.cpp b/core/input/input_binding.cpp index 0b84666..0f8e9a6 100644 --- a/core/input/input_binding.cpp +++ b/core/input/input_binding.cpp @@ -5,9 +5,11 @@ namespace SpaceEngine { std::unordered_map> Input::s_keyBindings; std::unordered_map> Input::s_mouseBindings; - -std::size_t Input::bindKey(const KeyCode key, std::function callback, const int remainingCalls, const InputEventType type, const std::string &description, const bool enabled) { - if (remainingCalls == 0) throw std::invalid_argument("[Input] Cannot bind key with 0 remaining calls."); +std::size_t Input::bindKey(const KeyCode key, std::function callback, + const int remainingCalls, const InputEventType type, + const std::string& description, const bool enabled) { + if (remainingCalls == 0) + throw std::invalid_argument("[Input] Cannot bind key with 0 remaining calls."); Binding binding; binding.id = s_nextBindingId++; binding.description = description; @@ -19,8 +21,11 @@ std::size_t Input::bindKey(const KeyCode key, std::function callback, co return binding.id; } -std::size_t Input::bindMouseButton(const MouseButton button, std::function callback, const int remainingCalls, const InputEventType type, const std::string &description, const bool enabled) { - if (remainingCalls == 0) throw std::invalid_argument("[Input] Cannot bind mouse button with 0 remaining calls."); +std::size_t Input::bindMouseButton(const MouseButton button, std::function callback, + const int remainingCalls, const InputEventType type, + const std::string& description, const bool enabled) { + if (remainingCalls == 0) + throw std::invalid_argument("[Input] Cannot bind mouse button with 0 remaining calls."); Binding binding; binding.id = s_nextBindingId++; binding.description = description; @@ -43,7 +48,8 @@ void Input::dispatchBindings() { try { binding.callback(); } catch (const std::exception& e) { - Logger::error(std::string("[Input] Exception in key callback: ") + e.what() + "\n" + "std::weak_ptr should be used instead of raw pointers"); + Logger::error(std::string("[Input] Exception in key callback: ") + e.what() + "\n" + + "std::weak_ptr should be used instead of raw pointers"); } catch (...) { Logger::error("[Input] Unknown exception in key callback."); } @@ -61,7 +67,8 @@ void Input::dispatchBindings() { try { binding.callback(); } catch (const std::exception& e) { - Logger::error(std::string("[Input] Exception in key callback: ") + e.what() + "\n" + "std::weak_ptr should be used instead of raw pointers"); + Logger::error(std::string("[Input] Exception in key callback: ") + e.what() + "\n" + + "std::weak_ptr should be used instead of raw pointers"); } catch (...) { Logger::error("[Input] Unknown exception in key callback."); } @@ -71,7 +78,7 @@ void Input::dispatchBindings() { } void Input::unbind(const size_t id) { - for (auto &bindings: s_keyBindings | std::views::values) { + for (auto& bindings : s_keyBindings | std::views::values) { for (auto it = bindings.begin(); it != bindings.end(); ++it) { if (it->id == id) { bindings.erase(it); @@ -79,7 +86,7 @@ void Input::unbind(const size_t id) { } } } - for (auto &bindings: s_mouseBindings | std::views::values) { + for (auto& bindings : s_mouseBindings | std::views::values) { for (auto it = bindings.begin(); it != bindings.end(); ++it) { if (it->id == id) { bindings.erase(it); @@ -111,63 +118,57 @@ void Input::clearAllBindings() { } void Input::simulateKey(const KeyCode key, const InputEventType type) { - for (const auto& binding : s_keyBindings[key]) { + for (auto& binding : s_keyBindings[key]) { if (!binding.enabled) continue; - if (binding.type == type) { - if (binding.remainingCalls == 0) continue; - binding.callback(); - binding.remainingCalls -= 1; - } + if (binding.type != type) continue; + if (binding.remainingCalls == 0) continue; + binding.callback(); + --binding.remainingCalls; } } void Input::simulateMouseButton(const MouseButton button, const InputEventType type) { - for (const auto& binding : s_mouseBindings[button]) { + for (auto& binding : s_mouseBindings[button]) { if (!binding.enabled) continue; - if (binding.type == type) { - if (binding.remainingCalls == 0) continue; - binding.callback(); - binding.remainingCalls -= 1; - } + if (binding.type != type) continue; + if (binding.remainingCalls == 0) continue; + binding.callback(); + --binding.remainingCalls; } } void Input::enableBinding(const std::size_t id) { - for (auto &bindings: s_keyBindings | std::views::values) { - for (const auto &binding : bindings) { - if (binding.id == id) { - binding.enabled = true; - return; - } + for (auto& bindings : s_keyBindings | std::views::values) { + for (auto& binding : bindings) { + if (binding.id != id) continue; + binding.enabled = true; + return; } } - for (auto &bindings: s_mouseBindings | std::views::values) { - for (const auto &binding : bindings) { - if (binding.id == id) { - binding.enabled = true; - return; - } + for (auto& bindings : s_mouseBindings | std::views::values) { + for (auto& binding : bindings) { + if (binding.id != id) continue; + binding.enabled = true; + return; } } } void Input::disableBinding(const std::size_t id) { - for (auto &bindings: s_keyBindings | std::views::values) { - for (const auto &binding : bindings) { - if (binding.id == id) { - binding.enabled = false; - return; - } + for (auto& bindings : s_keyBindings | std::views::values) { + for (auto& binding : bindings) { + if (binding.id != id) continue; + binding.enabled = false; + return; } } - for (auto &bindings: s_mouseBindings | std::views::values) { - for (const auto &binding : bindings) { - if (binding.id == id) { - binding.enabled = false; - return; - } + for (auto& bindings : s_mouseBindings | std::views::values) { + for (auto& binding : bindings) { + if (binding.id != id) continue; + binding.enabled = false; + return; } } } -} +} // namespace SpaceEngine diff --git a/core/log/log.cpp b/core/log/log.cpp index 67f7bd2..1077290 100644 --- a/core/log/log.cpp +++ b/core/log/log.cpp @@ -2,31 +2,34 @@ namespace SpaceEngine { -Log::Log(const LogLevel level, const LogType type, std::string message) - : level(level), type(type), message(std::move(message)), timestamp(std::chrono::system_clock::now()) {} +Log::Log(const LogLevel level, const LogType type, std::string message) + : level(level), + type(type), + message(std::move(message)), + timestamp(std::chrono::system_clock::now()) {} std::string Log::toString() const { - std::ostringstream stream; - auto timeT = std::chrono::system_clock::to_time_t(timestamp); - std::tm tm{}; - #ifdef _WIN32 - localtime_s(&tm, &timeT); - #else - localtime_r(&timeT, &tm); - #endif - stream << "[" << std::put_time(&tm, "%Y-%m-%d %H:%M:%S") << "] "; - stream << "[" << LogLevelToString(level) << "] "; - stream << "[" << LogTypeToString(type) << "] - "; - stream << message; - return stream.str(); + std::ostringstream stream; + auto timeT = std::chrono::system_clock::to_time_t(timestamp); + std::tm tm{}; +#ifdef _WIN32 + localtime_s(&tm, &timeT); +#else + localtime_r(&timeT, &tm); +#endif + stream << "[" << std::put_time(&tm, "%Y-%m-%d %H:%M:%S") << "] "; + stream << "[" << LogLevelToString(level) << "] "; + stream << "[" << LogTypeToString(type) << "] - "; + stream << message; + return stream.str(); } std::string Log::LogLevelToString(const LogLevel level) { - return logLevels[static_cast(level)]; + return logLevels[static_cast(level)]; } std::string Log::LogTypeToString(const LogType type) { - return logTypes[static_cast(type)]; + return logTypes[static_cast(type)]; } -} +} // namespace SpaceEngine diff --git a/core/log/log.hpp b/core/log/log.hpp index 913d65f..087d987 100644 --- a/core/log/log.hpp +++ b/core/log/log.hpp @@ -1,79 +1,41 @@ #pragma once -#include -#include +#include #include #include -#include +#include +#include #include namespace SpaceEngine { -enum LogLevel { - DEBUG, - INFORMATION, - WARNING, - ERROR, - FATAL -}; +enum LogLevel { DEBUG, INFORMATION, WARNING, ERROR, FATAL }; -enum LogType { - None, - Core, - Rendering, - Audio, - Input, - Editor, - Scripting, - AssetLoading -}; +enum LogType { None, Core, Rendering, Audio, Input, Editor, Scripting, AssetLoading }; -inline constexpr std::array logLevels = { - "DEBUG", "INFORMATION", "WARNING", "ERROR", "FATAL" -}; +inline constexpr std::array logLevels = {"DEBUG", + "INFORMATION", + "WARNING", + "ERROR", + "FATAL"}; -inline constexpr std::array logTypes = { - "None", "Core", "Rendering", "Audio", "Input", "Editor", "Scripting", "AssetLoading" -}; +inline constexpr std::array logTypes = + {"None", "Core", "Rendering", "Audio", "Input", "Editor", "Scripting", "AssetLoading"}; -/** - * @brief Class representing a log entry. - */ class Log { -public: + public: LogLevel level; LogType type; std::string title; std::string message; std::chrono::system_clock::time_point timestamp; - /** - * @brief Constructor for Log class. - * @param level The log level. - * @param type The log type. - * @param message The log message. - */ - Log(LogLevel level, LogType type, std::string message); + Log(LogLevel level, LogType type, std::string message); - /** - * @brief Converts the log entry to a string representation. - * @return The log entry as a string. - */ [[nodiscard]] std::string toString() const; - /** - * @brief Converts a log level to its string representation. - * @param level The log level. - * @return The string representation of the log level. - */ static std::string LogLevelToString(LogLevel level); - - /** - * @brief Converts a log type to its string representation. - * @param type The log type. - * @return The string representation of the log type. - */ static std::string LogTypeToString(LogType type); }; -} +} // namespace SpaceEngine diff --git a/core/log/log_filter.cpp b/core/log/log_filter.cpp index 6810903..f82f4d0 100644 --- a/core/log/log_filter.cpp +++ b/core/log/log_filter.cpp @@ -25,4 +25,4 @@ bool LogFilter::matches(const Log& log) const { return matchesLevel && matchesType && matchesKeyword; } -} \ No newline at end of file +} // namespace SpaceEngine \ No newline at end of file diff --git a/core/log/log_filter.hpp b/core/log/log_filter.hpp index 24d8022..2fdc7a4 100644 --- a/core/log/log_filter.hpp +++ b/core/log/log_filter.hpp @@ -1,14 +1,14 @@ #pragma once -#include #include +#include #include "log/log.hpp" namespace SpaceEngine { class LogFilter { -public: + public: std::set levels; std::set types; std::string keyword; @@ -18,4 +18,4 @@ class LogFilter { [[nodiscard]] bool matches(const Log& log) const; }; -} +} // namespace SpaceEngine diff --git a/core/log/logger.cpp b/core/log/logger.cpp index bf9d024..e9519a1 100644 --- a/core/log/logger.cpp +++ b/core/log/logger.cpp @@ -31,10 +31,9 @@ void Logger::fatal(const std::string& message) { std::vector Logger::getLogEntries() { std::vector filteredLogs; - for (const auto& log: logEntries) { - if (filter.matches(log)) { - filteredLogs.push_back(log); - } + for (const auto& log : logEntries) { + if (!filter.matches(log)) continue; + filteredLogs.push_back(log); } return filteredLogs; } @@ -43,4 +42,4 @@ void Logger::clearLogEntries() { logEntries.clear(); } -} +} // namespace SpaceEngine diff --git a/core/log/logger.hpp b/core/log/logger.hpp index bb83aef..d79a882 100644 --- a/core/log/logger.hpp +++ b/core/log/logger.hpp @@ -9,16 +9,9 @@ namespace SpaceEngine { class Logger { -public: + public: static LogFilter filter; - /** - * @brief Logs a message with the specified log level, type, title, and message. - * - * @param level The log level of the message. - * @param type The type of the log entry. - * @param message The message of the log entry. - */ static void log(LogLevel level, LogType type, const std::string& message); static void debug(const std::string& message); static void info(const std::string& message); @@ -28,13 +21,10 @@ class Logger { static std::vector getLogEntries(); - /** - * @brief Clears all log entries. - */ static void clearLogEntries(); -private: + private: static std::vector logEntries; }; -} +} // namespace SpaceEngine diff --git a/core/maths/vector.hpp b/core/maths/vector.hpp index ee2a10f..ee7752f 100644 --- a/core/maths/vector.hpp +++ b/core/maths/vector.hpp @@ -2,14 +2,14 @@ #include #include -#include #include +#include namespace SpaceEngine { -template +template class Vector { -public: + public: std::array data; // Constructors @@ -69,9 +69,12 @@ class Vector { // Aliases -template using Vec2 = Vector; -template using Vec3 = Vector; -template using Vec4 = Vector; +template +using Vec2 = Vector; +template +using Vec3 = Vector; +template +using Vec4 = Vector; using Vec2b = Vec2; using Vec3b = Vec3; @@ -93,6 +96,6 @@ using Vec2d = Vec2; using Vec3d = Vec3; using Vec4d = Vec4; -} +} // namespace SpaceEngine #include "vector.inl" diff --git a/core/maths/vector.inl b/core/maths/vector.inl index ca04c6e..30edcf9 100644 --- a/core/maths/vector.inl +++ b/core/maths/vector.inl @@ -3,23 +3,23 @@ namespace SpaceEngine { -template +template constexpr Vector::Vector(T val) { data.fill(val); } -template -template -constexpr Vector::Vector(Args&&... args) : data{ static_cast(args)... } {} +template +template +constexpr Vector::Vector(Args&&... args) : data{static_cast(args)...} {} -template +template constexpr Vector::Vector(const Vector& vec) { for (std::size_t i = 0; i < N; ++i) { data[i] = vec.data[i]; } } -template +template constexpr Vector::Vector(const Vector& vec, T val) { for (std::size_t i = 0; i < N - 1; ++i) { data[i] = vec.data[i]; @@ -27,55 +27,55 @@ constexpr Vector::Vector(const Vector& vec, T val) { data[N - 1] = val; } -template +template constexpr const T& Vector::x() const { static_assert(N >= 1, "Vector does not have an X component."); return data[0]; } -template +template constexpr T& Vector::x() { static_assert(N >= 1, "Vector does not have an X component."); return data[0]; } -template +template constexpr const T& Vector::y() const { static_assert(N >= 2, "Vector does not have a Y component."); return data[1]; } -template +template constexpr T& Vector::y() { static_assert(N >= 2, "Vector does not have a Y component."); return data[1]; } -template +template constexpr const T& Vector::z() const { static_assert(N >= 3, "Vector does not have a Z component."); return data[2]; } -template +template constexpr T& Vector::z() { static_assert(N >= 3, "Vector does not have a Z component."); return data[2]; } -template +template constexpr const T& Vector::w() const { static_assert(N >= 4, "Vector does not have a W component."); return data[3]; } -template +template constexpr T& Vector::w() { static_assert(N >= 4, "Vector does not have a W component."); return data[3]; } -template +template constexpr Vector Vector::operator-() const { Vector result; for (std::size_t i = 0; i < N; ++i) { @@ -84,7 +84,7 @@ constexpr Vector Vector::operator-() const { return result; } -template +template constexpr Vector Vector::operator+(const Vector& vec) const { Vector result; for (std::size_t i = 0; i < N; ++i) { @@ -93,7 +93,7 @@ constexpr Vector Vector::operator+(const Vector& vec) const { return result; } -template +template constexpr Vector Vector::operator+(T val) const { Vector result; for (std::size_t i = 0; i < N; ++i) { @@ -102,7 +102,7 @@ constexpr Vector Vector::operator+(T val) const { return result; } -template +template constexpr Vector Vector::operator-(const Vector& vec) const { Vector result; for (std::size_t i = 0; i < N; ++i) { @@ -111,7 +111,7 @@ constexpr Vector Vector::operator-(const Vector& vec) const { return result; } -template +template constexpr Vector Vector::operator-(T val) const { Vector result; for (std::size_t i = 0; i < N; ++i) { @@ -120,7 +120,7 @@ constexpr Vector Vector::operator-(T val) const { return result; } -template +template constexpr Vector Vector::operator*(T val) const { Vector result; for (std::size_t i = 0; i < N; ++i) { @@ -129,7 +129,7 @@ constexpr Vector Vector::operator*(T val) const { return result; } -template +template constexpr Vector Vector::operator*(const Vector& vec) const { Vector result; for (std::size_t i = 0; i < N; ++i) { @@ -138,7 +138,7 @@ constexpr Vector Vector::operator*(const Vector& vec) const { return result; } -template +template constexpr Vector Vector::operator/(T val) const { Vector result; for (std::size_t i = 0; i < N; ++i) { @@ -147,7 +147,7 @@ constexpr Vector Vector::operator/(T val) const { return result; } -template +template constexpr Vector Vector::operator/(const Vector& vec) const { Vector result; for (std::size_t i = 0; i < N; ++i) { @@ -156,7 +156,7 @@ constexpr Vector Vector::operator/(const Vector& vec) const { return result; } -template +template constexpr Vector& Vector::operator+=(const Vector& vec) { for (std::size_t i = 0; i < N; ++i) { data[i] += vec.data[i]; @@ -164,7 +164,7 @@ constexpr Vector& Vector::operator+=(const Vector& vec) { return *this; } -template +template constexpr Vector& Vector::operator+=(T val) { for (std::size_t i = 0; i < N; ++i) { data[i] += val; @@ -172,7 +172,7 @@ constexpr Vector& Vector::operator+=(T val) { return *this; } -template +template constexpr Vector& Vector::operator-=(const Vector& vec) { for (std::size_t i = 0; i < N; ++i) { data[i] -= vec.data[i]; @@ -180,7 +180,7 @@ constexpr Vector& Vector::operator-=(const Vector& vec) { return *this; } -template +template constexpr Vector& Vector::operator-=(T val) { for (std::size_t i = 0; i < N; ++i) { data[i] -= val; @@ -188,7 +188,7 @@ constexpr Vector& Vector::operator-=(T val) { return *this; } -template +template constexpr Vector& Vector::operator*=(T val) { for (std::size_t i = 0; i < N; ++i) { data[i] *= val; @@ -196,7 +196,7 @@ constexpr Vector& Vector::operator*=(T val) { return *this; } -template +template constexpr Vector& Vector::operator*=(const Vector& vec) { for (std::size_t i = 0; i < N; ++i) { data[i] *= vec.data[i]; @@ -204,7 +204,7 @@ constexpr Vector& Vector::operator*=(const Vector& vec) { return *this; } -template +template constexpr Vector& Vector::operator/=(T val) { for (std::size_t i = 0; i < N; ++i) { data[i] /= val; @@ -212,7 +212,7 @@ constexpr Vector& Vector::operator/=(T val) { return *this; } -template +template constexpr Vector& Vector::operator/=(const Vector& vec) { for (std::size_t i = 0; i < N; ++i) { data[i] /= vec.data[i]; @@ -220,17 +220,17 @@ constexpr Vector& Vector::operator/=(const Vector& vec) { return *this; } -template +template constexpr const T& Vector::operator[](std::size_t index) const { return data[index]; } -template +template constexpr T& Vector::operator[](std::size_t index) { return data[index]; } -template +template constexpr bool Vector::operator==(const Vector& vec) const { for (std::size_t i = 0; i < N; ++i) { if (data[i] != vec.data[i]) { @@ -240,12 +240,12 @@ constexpr bool Vector::operator==(const Vector& vec) const { return true; } -template +template constexpr bool Vector::operator!=(const Vector& vec) const { return !(*this == vec); } -template +template std::ostream& operator<<(std::ostream& stream, const Vector& vec) { stream << "("; for (std::size_t i = 0; i < N; ++i) { @@ -256,7 +256,7 @@ std::ostream& operator<<(std::ostream& stream, const Vector& vec) { return stream; } -template +template constexpr float Vector::dot(const Vector& vec) const { float result = 0; for (std::size_t i = 0; i < N; ++i) { @@ -265,7 +265,7 @@ constexpr float Vector::dot(const Vector& vec) const { return result; } -template +template constexpr Vector Vector::cross(const Vector& vec) const { static_assert(N == 3, "Error: Cross product need 3 dimensions vectors."); Vector result; @@ -275,4 +275,4 @@ constexpr Vector Vector::cross(const Vector& vec) const { return result; } -} +} // namespace SpaceEngine diff --git a/core/model/model.cpp b/core/model/model.cpp index 27036d9..a4cd3e9 100644 --- a/core/model/model.cpp +++ b/core/model/model.cpp @@ -2,21 +2,21 @@ namespace SpaceEngine { -Model::Model(const char *path) { +Model::Model(const char* path) { loadModel(path); } -void Model::draw(Shader &shader) { - for(auto & mesh : meshes) { +void Model::draw(Shader& shader) { + for (auto& mesh : meshes) { mesh.draw(shader); } } void Model::loadModel(const std::string& path) { Assimp::Importer import; - const aiScene *scene = import.ReadFile(path, aiProcess_Triangulate | aiProcess_FlipUVs); + const aiScene* scene = import.ReadFile(path, aiProcess_Triangulate | aiProcess_FlipUVs); - if(!scene || scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode) { + if (!scene || scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode) { std::ostringstream msg; msg << "ERROR::ASSIMP:: " << import.GetErrorString(); Logger::error(msg.str()); @@ -28,27 +28,27 @@ void Model::loadModel(const std::string& path) { processNode(scene->mRootNode, scene); } -void Model::processNode(const aiNode *node, const aiScene *scene) { +void Model::processNode(const aiNode* node, const aiScene* scene) { /* Processing all meshes */ - for(unsigned int i = 0; i < node->mNumMeshes; i++) { - aiMesh *mesh = scene->mMeshes[node->mMeshes[i]]; + for (unsigned int i = 0; i < node->mNumMeshes; i++) { + aiMesh* mesh = scene->mMeshes[node->mMeshes[i]]; meshes.push_back(processMesh(mesh, scene)); } /* Processing all children */ - for(unsigned int i = 0; i < node->mNumChildren; i++) { + for (unsigned int i = 0; i < node->mNumChildren; i++) { processNode(node->mChildren[i], scene); } } -ModelMesh Model::processMesh(aiMesh *mesh, const aiScene *scene) { +ModelMesh Model::processMesh(aiMesh* mesh, const aiScene* scene) { std::vector vertices; std::vector indices; std::vector textures; - for(unsigned int i = 0; i < mesh->mNumVertices; i++) { + for (unsigned int i = 0; i < mesh->mNumVertices; i++) { ModelVertex vertex{}; - glm::vec3 vector; // placeholder vector + glm::vec3 vector; // placeholder vector // position vector.x = mesh->mVertices[i].x; @@ -57,7 +57,7 @@ ModelMesh Model::processMesh(aiMesh *mesh, const aiScene *scene) { vertex.position = vector; // normals - if(mesh->HasNormals()) { + if (mesh->HasNormals()) { vector.x = mesh->mNormals[i].x; vector.y = mesh->mNormals[i].y; vector.z = mesh->mNormals[i].z; @@ -65,7 +65,7 @@ ModelMesh Model::processMesh(aiMesh *mesh, const aiScene *scene) { } // process materials - if(mesh->mTextureCoords[0]) { + if (mesh->mTextureCoords[0]) { glm::vec2 vec; vec.x = mesh->mTextureCoords[0][i].x; vec.y = mesh->mTextureCoords[0][i].y; @@ -77,41 +77,51 @@ ModelMesh Model::processMesh(aiMesh *mesh, const aiScene *scene) { } // process indices - for(unsigned int i = 0; i < mesh->mNumFaces; i++) { + for (unsigned int i = 0; i < mesh->mNumFaces; i++) { aiFace face = mesh->mFaces[i]; - for(unsigned int j = 0; j < face.mNumIndices; j++) { + for (unsigned int j = 0; j < face.mNumIndices; j++) { indices.push_back(face.mIndices[j]); } } - aiMaterial *material = scene->mMaterials[mesh->mMaterialIndex]; + aiMaterial* material = scene->mMaterials[mesh->mMaterialIndex]; // diffuse maps - std::vector diffuseMaps = loadMaterialTextures(material, aiTextureType_DIFFUSE, "texture_diffuse"); + std::vector diffuseMaps = loadMaterialTextures(material, + aiTextureType_DIFFUSE, + "texture_diffuse"); textures.insert(textures.end(), diffuseMaps.begin(), diffuseMaps.end()); // specular maps - std::vector specularMaps = loadMaterialTextures(material, aiTextureType_SPECULAR, "texture_specular"); + std::vector specularMaps = loadMaterialTextures(material, + aiTextureType_SPECULAR, + "texture_specular"); textures.insert(textures.end(), specularMaps.begin(), specularMaps.end()); // normal maps - std::vector normalMaps = loadMaterialTextures(material, aiTextureType_HEIGHT, "texture_normal"); + std::vector normalMaps = loadMaterialTextures(material, + aiTextureType_HEIGHT, + "texture_normal"); textures.insert(textures.end(), normalMaps.begin(), normalMaps.end()); // height maps - std::vector heightMaps = loadMaterialTextures(material, aiTextureType_AMBIENT, "texture_height"); + std::vector heightMaps = loadMaterialTextures(material, + aiTextureType_AMBIENT, + "texture_height"); textures.insert(textures.end(), heightMaps.begin(), heightMaps.end()); return {vertices, indices, textures}; } -std::vector Model::loadMaterialTextures(const aiMaterial *mat, const aiTextureType type, const std::string& typeName) { +std::vector Model::loadMaterialTextures(const aiMaterial* mat, + const aiTextureType type, + const std::string& typeName) { std::vector textures; - for(unsigned int i = 0; i < mat->GetTextureCount(type); i++) { + for (unsigned int i = 0; i < mat->GetTextureCount(type); i++) { aiString str; mat->GetTexture(type, i, &str); bool skip = false; - for(auto & tex : textures_loaded) { - if(std::strcmp(tex.path.data(), str.C_Str()) == 0) { + for (auto& tex : textures_loaded) { + if (std::strcmp(tex.path.data(), str.C_Str()) == 0) { textures.push_back(tex); skip = true; break; @@ -130,7 +140,7 @@ std::vector Model::loadMaterialTextures(const aiMaterial *mat, con return textures; } -unsigned int textureFromFile(const char *path, const std::string &directory, bool /*gamma*/) { +unsigned int textureFromFile(const char* path, const std::string& directory, bool /*gamma*/) { auto filename = std::string(path); filename = directory + '/' + filename; unsigned int textureID; @@ -138,14 +148,26 @@ unsigned int textureFromFile(const char *path, const std::string &directory, boo int width, height, nrComponents; - if(unsigned char *data = stbi_load(filename.c_str(), &width, &height, &nrComponents, 0)) { + if (unsigned char* data = stbi_load(filename.c_str(), &width, &height, &nrComponents, 0)) { GLenum format = 0; - if(nrComponents == 1) { format = GL_RED; } - else if (nrComponents == 3) { format = GL_RGB; } - else if (nrComponents == 4) { format = GL_RGBA; } + if (nrComponents == 1) { + format = GL_RED; + } else if (nrComponents == 3) { + format = GL_RGB; + } else if (nrComponents == 4) { + format = GL_RGBA; + } glBindTexture(GL_TEXTURE_2D, textureID); - glTexImage2D(GL_TEXTURE_2D, 0, static_cast(format), width, height, 0, format, GL_UNSIGNED_BYTE, data); + glTexImage2D(GL_TEXTURE_2D, + 0, + static_cast(format), + width, + height, + 0, + format, + GL_UNSIGNED_BYTE, + data); glGenerateMipmap(GL_TEXTURE_2D); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); @@ -163,4 +185,4 @@ unsigned int textureFromFile(const char *path, const std::string &directory, boo return textureID; } -} \ No newline at end of file +} // namespace SpaceEngine \ No newline at end of file diff --git a/core/model/model.hpp b/core/model/model.hpp index 9b035b8..30022c5 100644 --- a/core/model/model.hpp +++ b/core/model/model.hpp @@ -1,37 +1,37 @@ #pragma once -#include -#include #include +#include +#include #include "assimp/Importer.hpp" -#include "assimp/scene.h" #include "assimp/postprocess.h" -#include "stb_image.h" - +#include "assimp/scene.h" #include "log/logger.hpp" #include "model/model_mesh.hpp" #include "model/model_texture.hpp" #include "shader/shader.hpp" +#include "stb_image.h" namespace SpaceEngine { -unsigned int textureFromFile(const char *path, const std::string &directory, bool gamma = false); +unsigned int textureFromFile(const char* path, const std::string& directory, bool gamma = false); class Model { -public: - explicit Model(const char *path); - void draw(Shader &shader); + public: + explicit Model(const char* path); + void draw(Shader& shader); std::string directory; -private: + private: std::vector textures_loaded; std::vector meshes; void loadModel(const std::string& path); - void processNode(const aiNode *node, const aiScene *scene); - ModelMesh processMesh(aiMesh *mesh, const aiScene *scene); - std::vector loadMaterialTextures(const aiMaterial *mat, aiTextureType type, const std::string& typeName); + void processNode(const aiNode* node, const aiScene* scene); + ModelMesh processMesh(aiMesh* mesh, const aiScene* scene); + std::vector loadMaterialTextures(const aiMaterial* mat, aiTextureType type, + const std::string& typeName); }; -} \ No newline at end of file +} // namespace SpaceEngine \ No newline at end of file diff --git a/core/model/model_mesh.cpp b/core/model/model_mesh.cpp index 0d68d73..c721600 100644 --- a/core/model/model_mesh.cpp +++ b/core/model/model_mesh.cpp @@ -2,7 +2,9 @@ namespace SpaceEngine { -ModelMesh::ModelMesh(const std::vector &vertices, const std::vector &indices, const std::vector &textures) { +ModelMesh::ModelMesh(const std::vector& vertices, + const std::vector& indices, + const std::vector& textures) { this->vertices = vertices; this->indices = indices; this->textures = textures; @@ -18,10 +20,16 @@ void ModelMesh::setupMesh() { glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); - glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(ModelVertex), &vertices[0], GL_STATIC_DRAW); + glBufferData(GL_ARRAY_BUFFER, + vertices.size() * sizeof(ModelVertex), + &vertices[0], + GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); - glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(unsigned int), &indices[0], GL_STATIC_DRAW); + glBufferData(GL_ELEMENT_ARRAY_BUFFER, + indices.size() * sizeof(unsigned int), + &indices[0], + GL_STATIC_DRAW); // vertex positions glEnableVertexAttribArray(0); @@ -29,38 +37,67 @@ void ModelMesh::setupMesh() { // vertex normals glEnableVertexAttribArray(1); - glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(ModelVertex), reinterpret_cast(offsetof(ModelVertex, normal))); + glVertexAttribPointer(1, + 3, + GL_FLOAT, + GL_FALSE, + sizeof(ModelVertex), + reinterpret_cast(offsetof(ModelVertex, normal))); // vertex texture coords glEnableVertexAttribArray(2); - glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(ModelVertex), reinterpret_cast(offsetof(ModelVertex, texCoords))); + glVertexAttribPointer(2, + 2, + GL_FLOAT, + GL_FALSE, + sizeof(ModelVertex), + reinterpret_cast(offsetof(ModelVertex, texCoords))); // vertex tangent glEnableVertexAttribArray(3); - glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, sizeof(ModelVertex), reinterpret_cast(offsetof(ModelVertex, tangent))); + glVertexAttribPointer(3, + 3, + GL_FLOAT, + GL_FALSE, + sizeof(ModelVertex), + reinterpret_cast(offsetof(ModelVertex, tangent))); // vertex bitangent glEnableVertexAttribArray(4); - glVertexAttribPointer(4, 3, GL_FLOAT, GL_FALSE, sizeof(ModelVertex), reinterpret_cast(offsetof(ModelVertex, bitangent))); + glVertexAttribPointer(4, + 3, + GL_FLOAT, + GL_FALSE, + sizeof(ModelVertex), + reinterpret_cast(offsetof(ModelVertex, bitangent))); // ids glEnableVertexAttribArray(5); - glVertexAttribIPointer(5, 4, GL_INT, sizeof(ModelVertex), reinterpret_cast(offsetof(ModelVertex, m_BoneIDs))); + glVertexAttribIPointer(5, + 4, + GL_INT, + sizeof(ModelVertex), + reinterpret_cast(offsetof(ModelVertex, m_BoneIDs))); // weights glEnableVertexAttribArray(6); - glVertexAttribPointer(6, 4, GL_FLOAT, GL_FALSE, sizeof(ModelVertex), reinterpret_cast(offsetof(ModelVertex, m_Weights))); + glVertexAttribPointer(6, + 4, + GL_FLOAT, + GL_FALSE, + sizeof(ModelVertex), + reinterpret_cast(offsetof(ModelVertex, m_Weights))); glBindVertexArray(0); } -void ModelMesh::draw(const Shader &shader) const { +void ModelMesh::draw(const Shader& shader) const { unsigned int diffuseNr = 1; unsigned int specularNr = 1; unsigned int normalNr = 1; unsigned int heightNr = 1; - for(unsigned int i = 0; i < textures.size(); i++) { + for (unsigned int i = 0; i < textures.size(); i++) { glActiveTexture(GL_TEXTURE0 + i); std::string number; std::string name = textures[i].type; @@ -84,4 +121,4 @@ void ModelMesh::draw(const Shader &shader) const { glActiveTexture(GL_TEXTURE0); } -} +} // namespace SpaceEngine diff --git a/core/model/model_mesh.hpp b/core/model/model_mesh.hpp index 1f35bcb..128c51d 100644 --- a/core/model/model_mesh.hpp +++ b/core/model/model_mesh.hpp @@ -2,24 +2,25 @@ #include -#include "model/model_vertex.hpp" #include "model/model_texture.hpp" +#include "model/model_vertex.hpp" #include "shader/shader.hpp" namespace SpaceEngine { class ModelMesh { -public: + public: std::vector vertices; std::vector indices; std::vector textures; - ModelMesh(const std::vector &vertices, const std::vector &indices, const std::vector &textures); - void draw(const Shader &shader) const; + ModelMesh(const std::vector& vertices, const std::vector& indices, + const std::vector& textures); + void draw(const Shader& shader) const; -private: + private: unsigned int VAO{}, VBO{}, EBO{}; void setupMesh(); }; -} +} // namespace SpaceEngine diff --git a/core/model/model_texture.hpp b/core/model/model_texture.hpp index b4d6181..4163591 100644 --- a/core/model/model_texture.hpp +++ b/core/model/model_texture.hpp @@ -10,4 +10,4 @@ struct ModelTexture { std::string path; }; -} \ No newline at end of file +} // namespace SpaceEngine \ No newline at end of file diff --git a/core/model/model_vertex.hpp b/core/model/model_vertex.hpp index 2a79ee3..3ae2134 100644 --- a/core/model/model_vertex.hpp +++ b/core/model/model_vertex.hpp @@ -13,10 +13,10 @@ struct ModelVertex { glm::vec3 tangent; glm::vec3 bitangent; - //bone indexes which will influence this vertex - int m_BoneIDs[MAX_BONE_INFLUENCE]; - //weights from each bone - float m_Weights[MAX_BONE_INFLUENCE]; + // bone indexes which will influence this vertex + int m_BoneIDs[MAX_BONE_INFLUENCE]; + // weights from each bone + float m_Weights[MAX_BONE_INFLUENCE]; }; -} \ No newline at end of file +} // namespace SpaceEngine \ No newline at end of file diff --git a/core/renderer/renderer.cpp b/core/renderer/renderer.cpp index 2f6ff6b..bdfbd5f 100644 --- a/core/renderer/renderer.cpp +++ b/core/renderer/renderer.cpp @@ -35,7 +35,11 @@ void Renderer::setupFramebuffer(const int width, const int height) { glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, nullptr); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, textureColorBuffer, 0); + glFramebufferTexture2D(GL_FRAMEBUFFER, + GL_COLOR_ATTACHMENT0, + GL_TEXTURE_2D, + textureColorBuffer, + 0); // Create renderbuffer for depth and stencil glGenRenderbuffers(1, &rbo); @@ -62,7 +66,8 @@ void Renderer::resize(const int width, const int height) { glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, width, height); } -void Renderer::render(const glm::mat4& viewMatrix, const glm::mat4& projectionMatrix, const std::shared_ptr& scene) const { +void Renderer::render(const glm::mat4& viewMatrix, const glm::mat4& projectionMatrix, + const std::shared_ptr& scene) const { if (!scene) { return; } @@ -73,7 +78,10 @@ void Renderer::render(const glm::mat4& viewMatrix, const glm::mat4& projectionMa glm::vec4 clearColor(0.1f, 0.1f, 0.1f, 1.0f); const auto camera = scene->world.get_component(scene->selectedCamera); - clearColor = glm::vec4(camera.skyboxColor.x, camera.skyboxColor.y, camera.skyboxColor.z, camera.skyboxColor.w); + clearColor = glm::vec4(camera.skyboxColor.x, + camera.skyboxColor.y, + camera.skyboxColor.z, + camera.skyboxColor.w); glClearColor(clearColor.r, clearColor.g, clearColor.b, clearColor.a); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); @@ -91,12 +99,8 @@ void Renderer::render(const glm::mat4& viewMatrix, const glm::mat4& projectionMa auto model = glm::mat4(1.0f); // Apply transformations - model = glm::translate(model, glm::vec3(tf.position.x(), - tf.position.y(), - tf.position.z())); - model = glm::scale(model, glm::vec3(tf.scale.x(), - tf.scale.y(), - tf.scale.z())); + model = glm::translate(model, glm::vec3(tf.position.x(), tf.position.y(), tf.position.z())); + model = glm::scale(model, glm::vec3(tf.scale.x(), tf.scale.y(), tf.scale.z())); model = glm::rotate(model, glm::radians(tf.rotation.x()), glm::vec3(1.0f, 0.0f, 0.0f)); model = glm::rotate(model, glm::radians(tf.rotation.y()), glm::vec3(0.0f, 1.0f, 0.0f)); model = glm::rotate(model, glm::radians(tf.rotation.z()), glm::vec3(0.0f, 0.0f, 1.0f)); @@ -108,4 +112,4 @@ void Renderer::render(const glm::mat4& viewMatrix, const glm::mat4& projectionMa glBindFramebuffer(GL_FRAMEBUFFER, 0); } -} \ No newline at end of file +} // namespace SpaceEngine \ No newline at end of file diff --git a/core/renderer/renderer.hpp b/core/renderer/renderer.hpp index 4f02735..7cd23cb 100644 --- a/core/renderer/renderer.hpp +++ b/core/renderer/renderer.hpp @@ -18,16 +18,19 @@ namespace SpaceEngine { class Renderer { -public: + public: Renderer(); ~Renderer(); bool initialize(int width, int height); - void render(const glm::mat4& viewMatrix, const glm::mat4& projectionMatrix, const std::shared_ptr& scene) const; - [[nodiscard]] unsigned int getRenderedTexture() const { return textureColorBuffer; } + void render(const glm::mat4& viewMatrix, const glm::mat4& projectionMatrix, + const std::shared_ptr& scene) const; + [[nodiscard]] unsigned int getRenderedTexture() const { + return textureColorBuffer; + } void resize(int width, int height); -private: + private: void setupFramebuffer(int width, int height); unsigned int fbo; @@ -38,4 +41,4 @@ class Renderer { int viewportHeight; }; -} \ No newline at end of file +} // namespace SpaceEngine \ No newline at end of file diff --git a/core/scene/scene.cpp b/core/scene/scene.cpp index 331c331..9b0125e 100644 --- a/core/scene/scene.cpp +++ b/core/scene/scene.cpp @@ -10,4 +10,4 @@ Scene::Scene() { selectedCamera = camera; } -} +} // namespace SpaceEngine diff --git a/core/scene/scene.hpp b/core/scene/scene.hpp index 70d1097..1c70871 100644 --- a/core/scene/scene.hpp +++ b/core/scene/scene.hpp @@ -1,18 +1,18 @@ #pragma once +#include #include #include -#include +#include "component/camera.hpp" +#include "component/transform.hpp" #include "ecs/entity.hpp" #include "ecs/world.hpp" -#include "component/transform.hpp" -#include "component/camera.hpp" namespace SpaceEngine { -class Scene{ -public: +class Scene { + public: std::string name; World world; @@ -22,4 +22,4 @@ class Scene{ Scene(); }; -} +} // namespace SpaceEngine diff --git a/core/shader/shader.cpp b/core/shader/shader.cpp index 96c2b3c..a6c6e74 100644 --- a/core/shader/shader.cpp +++ b/core/shader/shader.cpp @@ -2,7 +2,8 @@ namespace SpaceEngine { -Shader::Shader(const char* vertexPath, const char* fragmentPath, const char* geometryPath = nullptr) { +Shader::Shader(const char* vertexPath, const char* fragmentPath, + const char* geometryPath = nullptr) { // Retrieve source code. std::string vertexCode; std::string fragmentCode; @@ -34,14 +35,14 @@ Shader::Shader(const char* vertexPath, const char* fragmentPath, const char* geo vertexCode = vShaderStream.str(); fragmentCode = fShaderStream.str(); - if(geometryPath != nullptr) { + if (geometryPath != nullptr) { gShaderFile.open(geometryPath); std::stringstream gShaderStream; gShaderStream << gShaderFile.rdbuf(); gShaderFile.close(); geometryCode = gShaderStream.str(); } - } catch(std::ifstream::failure& e) { + } catch (std::ifstream::failure& e) { std::cout << "ERROR::SHADER::FILE_NOT_SUCCESSFULLY_READ" << e.what() << std::endl; } @@ -64,8 +65,8 @@ Shader::Shader(const char* vertexPath, const char* fragmentPath, const char* geo checkCompileErrors(fragment, "FRAGMENT"); unsigned int geometry = 0; - if(geometryPath != nullptr) { - const char *gShaderCode = geometryCode.c_str(); + if (geometryPath != nullptr) { + const char* gShaderCode = geometryCode.c_str(); geometry = glCreateShader(GL_GEOMETRY_SHADER); glShaderSource(geometry, 1, &gShaderCode, nullptr); glCompileShader(geometry); @@ -76,7 +77,7 @@ Shader::Shader(const char* vertexPath, const char* fragmentPath, const char* geo id = glCreateProgram(); glAttachShader(id, vertex); glAttachShader(id, fragment); - if(geometryPath != nullptr) { + if (geometryPath != nullptr) { glAttachShader(id, geometry); } glLinkProgram(id); @@ -84,58 +85,61 @@ Shader::Shader(const char* vertexPath, const char* fragmentPath, const char* geo glDeleteShader(vertex); glDeleteShader(fragment); - if(geometryPath != nullptr) { + if (geometryPath != nullptr) { glDeleteShader(geometry); } } -void Shader::use() const { glUseProgram(id); } +void Shader::use() const { + glUseProgram(id); +} -void Shader::setBool(const std::string &name, const bool value) const { +void Shader::setBool(const std::string& name, const bool value) const { glUniform1i(glGetUniformLocation(id, name.c_str()), static_cast(value)); } -void Shader::setInt(const std::string &name, const int value) const { +void Shader::setInt(const std::string& name, const int value) const { glUniform1i(glGetUniformLocation(id, name.c_str()), value); } -void Shader::setFloat(const std::string &name, const float value) const { +void Shader::setFloat(const std::string& name, const float value) const { glUniform1f(glGetUniformLocation(id, name.c_str()), value); } -void Shader::setVec2(const std::string &name, const glm::vec2 &value) const { +void Shader::setVec2(const std::string& name, const glm::vec2& value) const { glUniform2fv(glGetUniformLocation(id, name.c_str()), 1, &value[0]); } -void Shader::setVec2(const std::string &name, const float x, const float y) const { +void Shader::setVec2(const std::string& name, const float x, const float y) const { glUniform2f(glGetUniformLocation(id, name.c_str()), x, y); } -void Shader::setVec3(const std::string &name, const glm::vec3 &value) const { +void Shader::setVec3(const std::string& name, const glm::vec3& value) const { glUniform3fv(glGetUniformLocation(id, name.c_str()), 1, &value[0]); } -void Shader::setVec3(const std::string &name, const float x, const float y, const float z) const { +void Shader::setVec3(const std::string& name, const float x, const float y, const float z) const { glUniform3f(glGetUniformLocation(id, name.c_str()), x, y, z); } -void Shader::setVec4(const std::string &name, const glm::vec4 &value) const { +void Shader::setVec4(const std::string& name, const glm::vec4& value) const { glUniform4fv(glGetUniformLocation(id, name.c_str()), 1, &value[0]); } -void Shader::setVec4(const std::string &name, const float x, const float y, const float z, const float w) const { +void Shader::setVec4(const std::string& name, const float x, const float y, const float z, + const float w) const { glUniform4f(glGetUniformLocation(id, name.c_str()), x, y, z, w); } -void Shader::setMat2(const std::string &name, const glm::mat2 &mat) const { +void Shader::setMat2(const std::string& name, const glm::mat2& mat) const { glUniformMatrix2fv(glGetUniformLocation(id, name.c_str()), 1, GL_FALSE, &mat[0][0]); } -void Shader::setMat3(const std::string &name, const glm::mat3 &mat) const { +void Shader::setMat3(const std::string& name, const glm::mat3& mat) const { glUniformMatrix3fv(glGetUniformLocation(id, name.c_str()), 1, GL_FALSE, &mat[0][0]); } -void Shader::setMat4(const std::string &name, const glm::mat4 &mat) const { +void Shader::setMat4(const std::string& name, const glm::mat4& mat) const { glUniformMatrix4fv(glGetUniformLocation(id, name.c_str()), 1, GL_FALSE, &mat[0][0]); } @@ -143,19 +147,20 @@ void Shader::checkCompileErrors(const GLuint shader, const std::string& type) { GLint success; GLchar infoLog[1024]; - if(type != "PROGRAM") { + if (type != "PROGRAM") { glGetShaderiv(shader, GL_COMPILE_STATUS, &success); - if(!success) { + if (!success) { glGetShaderInfoLog(shader, 1024, nullptr, infoLog); - std::cout << "ERROR::SHADER::COMPILATION_ERROR of type: " << type << "\n" << infoLog << std::endl; + std::cout << "ERROR::SHADER::COMPILATION_ERROR of type: " << type << "\n" + << infoLog << std::endl; } } else { glGetProgramiv(shader, GL_LINK_STATUS, &success); - if(!success) { + if (!success) { glGetProgramInfoLog(shader, 1024, nullptr, infoLog); std::cout << "ERROR::SHADER::LINKING_ERROR of type: " << type << "\n" << infoLog << std::endl; } } } -} +} // namespace SpaceEngine diff --git a/core/shader/shader.hpp b/core/shader/shader.hpp index 7e50c19..0b001df 100644 --- a/core/shader/shader.hpp +++ b/core/shader/shader.hpp @@ -1,153 +1,36 @@ #pragma once -#include #include -#include #include +#include +#include #include "glad/glad.h" #include "glm/glm.hpp" namespace SpaceEngine { -/* - * The Shader class represents a shader program in OpenGL, encapsulating vertex, fragment, and geometry shaders. - * - * Properties: - * - id (unsigned int): Program ID of the shader. - * - * Constructors: - * - Shader(const char* vertexPath, const char* fragmentPath, const char* geometryPath): Reads and builds the shader from provided file paths. - * - * Methods: - * - void use(): Activates the shader for rendering. - * - void setBool(const std::string& name, bool value) const: Sets a boolean uniform value in the shader. - * - void setInt(const std::string& name, int value) const: Sets an integer uniform value in the shader. - * - void setFloat(const std::string& name, float value) const: Sets a floating-point uniform value in the shader. - * - void setVec2(const std::string &name, const glm::vec2 &value) const: Sets a 2D vector uniform value in the shader. - * - void setVec2(const std::string &name, float x, float y) const: Sets a 2D vector uniform value in the shader. - * - void setVec3(const std::string &name, const glm::vec3 &value) const: Sets a 3D vector uniform value in the shader. - * - void setVec3(const std::string &name, float x, float y, float z) const: Sets a 3D vector uniform value in the shader. - * - void setVec4(const std::string &name, const glm::vec4 &value) const: Sets a 4D vector uniform value in the shader. - * - void setVec4(const std::string &name, float x, float y, float z, float w) const: Sets a 4D vector uniform value in the shader. - * - void setMat2(const std::string &name, const glm::mat2 &mat) const: Sets a 2x2 matrix uniform value in the shader. - * - void setMat3(const std::string &name, const glm::mat3 &mat) const: Sets a 3x3 matrix uniform value in the shader. - * - void setMat4(const std::string &name, const glm::mat4 &mat) const: Sets a 4x4 matrix uniform value in the shader. - * - void checkCompileErrors(GLuint shader, std::string type): Checks and logs compilation errors for a shader. - */ class Shader { -public: - unsigned int id; // Program id + public: + unsigned int id; - /** - * @brief Constructor that reads and builds the shader from provided file paths. - * @param vertexPath: Path to the vertex shader file. - * @param fragmentPath: Path to the fragment shader file. - * @param geometryPath: Path to the geometry shader file. - */ Shader(const char* vertexPath, const char* fragmentPath, const char* geometryPath); - /** - * @brief activate the shader for rendering. - */ void use() const; - /** - * @brief Set a boolean uniform value in the shader. - * @param name: Name of the boolean uniform. - * @param value: Boolean value to set. - */ void setBool(const std::string& name, bool value) const; - - /** - * @brief Set an integer uniform value in the shader. - * @param name: Name of the integer uniform. - * @param value: Integer value to set. - */ void setInt(const std::string& name, int value) const; - - /** - * @brief Set a floating-point uniform value in the shader. - * @param name: Name of the float uniform. - * @param value: Float value to set. - */ void setFloat(const std::string& name, float value) const; - - /** - * @brief Set a 2D vector uniform value in the shader. - * @param name: Name of the vector uniform. - * @param value: glm::vec2 value to set. - */ - void setVec2(const std::string &name, const glm::vec2 &value) const; - - /** - * @brief Set a 2D vector uniform value in the shader. - * @param name: Name of the vector uniform. - * @param x: x-component of the vector. - * @param y: y-component of the vector. - */ - void setVec2(const std::string &name, float x, float y) const; - - /** - * @brief Set a 3D vector uniform value in the shader. - * @param name: Name of the vector uniform. - * @param value: glm::vec3 value to set. - */ - void setVec3(const std::string &name, const glm::vec3 &value) const; - - /** - * @brief Set a 3D vector uniform value in the shader. - * @param name: Name of the vector uniform. - * @param x: x-component of the vector. - * @param y: y-component of the vector. - * @param z: z-component of the vector. - */ - void setVec3(const std::string &name, float x, float y, float z) const; - - /** - * @brief Set a 4D vector uniform value in the shader. - * @param name: Name of the vector uniform. - * @param value: glm::vec4 value to set. - */ - void setVec4(const std::string &name, const glm::vec4 &value) const; - - /** - * @brief Set a 4D vector uniform value in the shader. - * @param name: Name of the vector uniform. - * @param x: x-component of the vector. - * @param y: y-component of the vector. - * @param z: z-component of the vector. - * @param w: w-component of the vector. - */ - void setVec4(const std::string &name, float x, float y, float z, float w) const; - - /** - * @brief Set a 2x2 matrix uniform value in the shader. - * @param name: Name of the matrix uniform. - * @param mat: glm::mat2 value to set. - */ - void setMat2(const std::string &name, const glm::mat2 &mat) const; - - /** - * @brief Set a 3x3 matrix uniform value in the shader. - * @param name: Name of the matrix uniform. - * @param mat: glm::mat3 value to set. - */ - void setMat3(const std::string &name, const glm::mat3 &mat) const; - - /** - * @brief Set a 4x4 matrix uniform value in the shader. - * @param name: Name of the matrix uniform. - * @param mat: glm::mat4 value to set. - */ - void setMat4(const std::string &name, const glm::mat4 &mat) const; - - /** - * @brief Check and log compilation errors for a shader. - * @param shader: ID of the shader to check. - * @param type: Type of the shader (vertex, fragment, geometry). - */ + void setVec2(const std::string& name, const glm::vec2& value) const; + void setVec2(const std::string& name, float x, float y) const; + void setVec3(const std::string& name, const glm::vec3& value) const; + void setVec3(const std::string& name, float x, float y, float z) const; + void setVec4(const std::string& name, const glm::vec4& value) const; + void setVec4(const std::string& name, float x, float y, float z, float w) const; + void setMat2(const std::string& name, const glm::mat2& mat) const; + void setMat3(const std::string& name, const glm::mat3& mat) const; + void setMat4(const std::string& name, const glm::mat4& mat) const; static void checkCompileErrors(GLuint shader, const std::string& type); }; -} \ No newline at end of file +} // namespace SpaceEngine \ No newline at end of file diff --git a/core/time/time.cpp b/core/time/time.cpp index 83eb7d5..44d81fa 100644 --- a/core/time/time.cpp +++ b/core/time/time.cpp @@ -45,4 +45,4 @@ void Time::setTimeScale(const float scale) { s_timeScale = scale; } -} +} // namespace SpaceEngine diff --git a/core/time/time.hpp b/core/time/time.hpp index d349db4..87deaf8 100644 --- a/core/time/time.hpp +++ b/core/time/time.hpp @@ -5,7 +5,7 @@ namespace SpaceEngine { class Time { -public: + public: static void init(); static void update(); static void setTimeScale(float scale); @@ -15,7 +15,7 @@ class Time { static float unscaledDeltaTime(); static float timeScale(); -private: + private: static std::chrono::steady_clock::time_point s_startTime; static std::chrono::steady_clock::time_point s_lastFrameTime; @@ -25,4 +25,4 @@ class Time { static float s_timeScale; }; -} +} // namespace SpaceEngine diff --git a/core/types/types.hpp b/core/types/types.hpp index 636a356..9dc2ba6 100644 --- a/core/types/types.hpp +++ b/core/types/types.hpp @@ -1,16 +1,16 @@ #pragma once -#include #include +#include namespace SpaceEngine { -using u8 = std::uint8_t; +using u8 = std::uint8_t; using u16 = std::uint16_t; using u32 = std::uint32_t; using u64 = std::uint64_t; -using i8 = std::int8_t; +using i8 = std::int8_t; using i16 = std::int16_t; using i32 = std::int32_t; using i64 = std::int64_t; @@ -20,5 +20,4 @@ using f64 = double; using usize = std::size_t; -} - +} // namespace SpaceEngine diff --git a/editor/editor_camera/editor_camera.cpp b/editor/editor_camera/editor_camera.cpp index 4bafe59..dbda42b 100644 --- a/editor/editor_camera/editor_camera.cpp +++ b/editor/editor_camera/editor_camera.cpp @@ -30,8 +30,12 @@ void EditorCamera::processMouseMovement(float xOffset, float yOffset, const bool pitch += yOffset; if (constrainPitch) { - if (pitch > 89.0f) { pitch = 89.0f; } - if (pitch < -89.0f) { pitch = -89.0f; } + if (pitch > 89.0f) { + pitch = 89.0f; + } + if (pitch < -89.0f) { + pitch = -89.0f; + } } updateCameraVectors(); @@ -39,8 +43,12 @@ void EditorCamera::processMouseMovement(float xOffset, float yOffset, const bool void EditorCamera::processMouseScroll(const float yOffset) { fieldOfView -= yOffset; - if (fieldOfView < 1.0f ) { fieldOfView = 1.0f; } - if (fieldOfView > 179.0f ) { fieldOfView = 179.0f; } + if (fieldOfView < 1.0f) { + fieldOfView = 1.0f; + } + if (fieldOfView > 179.0f) { + fieldOfView = 179.0f; + } } glm::mat4 EditorCamera::getEditorViewMatrix() const { @@ -50,7 +58,10 @@ glm::mat4 EditorCamera::getEditorViewMatrix() const { glm::mat4 EditorCamera::getEditorProjectionMatrix() const { if (projectionType == ProjectionType::PERSPECTIVE) { - glm::mat4 projection = glm::perspective(glm::radians(fieldOfView), aspectRatio, nearPlane, farPlane); + glm::mat4 projection = glm::perspective(glm::radians(fieldOfView), + aspectRatio, + nearPlane, + farPlane); projection[1][1] *= -1; return projection; } @@ -61,4 +72,4 @@ glm::mat4 EditorCamera::getEditorProjectionMatrix() const { return projection; } -} \ No newline at end of file +} // namespace SpaceEditor \ No newline at end of file diff --git a/editor/editor_camera/editor_camera.hpp b/editor/editor_camera/editor_camera.hpp index 038ae17..5beb94f 100644 --- a/editor/editor_camera/editor_camera.hpp +++ b/editor/editor_camera/editor_camera.hpp @@ -2,20 +2,14 @@ #include +#include "component/camera.hpp" #include "glad/glad.h" #include "glm/glm.hpp" #include "glm/gtc/matrix_transform.hpp" -#include "component/camera.hpp" - namespace SpaceEditor { -enum CameraMovement { - FORWARD, - BACKWARD, - LEFT, - RIGHT -}; +enum CameraMovement { FORWARD, BACKWARD, LEFT, RIGHT }; constexpr float SPEED = 2.5f; constexpr float SENSITIVITY = 0.1f; @@ -37,17 +31,21 @@ constexpr float SENSITIVITY = 0.1f; * - zoom (float): The zoom level of the camera. * * Methods: - * - EditorCamera(glm::vec3 position, glm::vec3 up, float yaw, float pitch): Constructor with vector. + * - EditorCamera(glm::vec3 position, glm::vec3 up, float yaw, float pitch): + * Constructor with vector. * - glm::mat4 getViewMatrix(): Get the view matrix of the camera. - * - void processKeyboard(CameraMovement direction, float deltaTime): Process keyboard input to move the camera. - * - void processMouseMovement(float xOffset, float yOffset, bool constrainPitch = true): Process mouse movement to update camera angles. - * - void processMouseScroll(float yOffset): Process mouse scroll to update zoom level. + * - void processKeyboard(CameraMovement direction, float deltaTime): Process + * keyboard input to move the camera. + * - void processMouseMovement(float xOffset, float yOffset, bool constrainPitch + * = true): Process mouse movement to update camera angles. + * - void processMouseScroll(float yOffset): Process mouse scroll to update zoom + * level. */ class EditorCamera final : public SpaceEngine::Camera { -public: - glm::vec3 position{}; /* The position of the camera. */ - float movementSpeed = SPEED; /* The speed at which the camera moves. */ - float mouseSensitivity = SENSITIVITY; /* The sensitivity of the mouse movement. */ + public: + glm::vec3 position{}; /* The position of the camera. */ + float movementSpeed = SPEED; /* The speed at which the camera moves. */ + float mouseSensitivity = SENSITIVITY; /* The sensitivity of the mouse movement. */ /** * @brief Constructor with vector. @@ -56,7 +54,8 @@ class EditorCamera final : public SpaceEngine::Camera { /** * @brief Process keyboard input to move the camera. - * @param direction: The direction of movement (FORWARD, BACKWARD, LEFT, RIGHT). + * @param direction: The direction of movement (FORWARD, BACKWARD, LEFT, + * RIGHT). * @param deltaTime: Time between the current frame and the last frame. */ void processKeyboard(enum CameraMovement direction, float deltaTime); @@ -75,7 +74,7 @@ class EditorCamera final : public SpaceEngine::Camera { */ void processMouseScroll(float yOffset); - /** + /** * @brief Get the view matrix of the camera. * @return The view matrix. */ @@ -88,4 +87,4 @@ class EditorCamera final : public SpaceEngine::Camera { [[nodiscard]] glm::mat4 getEditorProjectionMatrix() const; }; -} \ No newline at end of file +} // namespace SpaceEditor \ No newline at end of file diff --git a/editor/editor_gui/component_viewer.cpp b/editor/editor_gui/component_viewer.cpp index 4971f31..b096735 100644 --- a/editor/editor_gui/component_viewer.cpp +++ b/editor/editor_gui/component_viewer.cpp @@ -4,8 +4,8 @@ namespace SpaceEditor { void EditorGui::initComponentViewers() { this->componentViewers[std::type_index(typeid(Transform))] = [](World& world, Entity e) { - if (!world.has_component(e)) return; - auto& transform = world.get_component(e); + if (!world.has_component(e)) return; + auto& transform = world.get_component(e); if (ImGui::CollapsingHeader("Transform")) { ImGui::Text("Name"); ImGui::SameLine(100); @@ -38,9 +38,9 @@ void EditorGui::initComponentViewers() { }; this->componentViewers[std::type_index(typeid(Physic))] = [](World& world, Entity e) { - if (!world.has_component(e)) return; - auto& physic = world.get_component(e); - if (ImGui::CollapsingHeader("Physic")) { + if (!world.has_component(e)) return; + auto& physic = world.get_component(e); + if (ImGui::CollapsingHeader("Physic")) { ImGui::Text("Mass"); ImGui::SameLine(100); ImGui::InputFloat("##physic_mass", &physic.mass); @@ -57,9 +57,9 @@ void EditorGui::initComponentViewers() { }; this->componentViewers[std::type_index(typeid(ModelRenderer))] = [](World& world, Entity e) { - if (!world.has_component(e)) return; - auto& modelRenderer = world.get_component(e); - if (ImGui::CollapsingHeader("Model Renderer")) { + if (!world.has_component(e)) return; + auto& modelRenderer = world.get_component(e); + if (ImGui::CollapsingHeader("Model Renderer")) { ImGui::Text("Model path"); ImGui::SameLine(); ImGui::InputText("##model_renderer.path", &modelRenderer.path); @@ -71,15 +71,18 @@ void EditorGui::initComponentViewers() { }; this->componentViewers[std::type_index(typeid(Camera))] = [](World& world, Entity e) { - if (!world.has_component(e)) return; - auto& camera = world.get_component(e); - if (ImGui::CollapsingHeader("Camera")) { + if (!world.has_component(e)) return; + auto& camera = world.get_component(e); + if (ImGui::CollapsingHeader("Camera")) { // Projection Type ImGui::Text("Projection Type"); ImGui::SameLine(100); - const char* projectionTypes[] = { "Perspective", "Orthographic" }; + const char* projectionTypes[] = {"Perspective", "Orthographic"}; int currentType = static_cast(camera.projectionType); - if (ImGui::Combo("##camera.projectionType", ¤tType, projectionTypes, IM_ARRAYSIZE(projectionTypes))) { + if (ImGui::Combo("##camera.projectionType", + ¤tType, + projectionTypes, + IM_ARRAYSIZE(projectionTypes))) { camera.projectionType = static_cast(currentType); } @@ -106,7 +109,11 @@ void EditorGui::initComponentViewers() { else { ImGui::Text("Orthographic Size"); ImGui::SameLine(100); - ImGui::InputFloat("##camera.orthographicSize", &camera.orthographicSize, 0.1f, 1.0f, "%.2f"); + ImGui::InputFloat("##camera.orthographicSize", + &camera.orthographicSize, + 0.1f, + 1.0f, + "%.2f"); } // Camera orientation @@ -128,9 +135,9 @@ void EditorGui::initComponentViewers() { ImGui::Separator(); ImGui::SetNextItemWidth(200); ImGui::Text("Visual Settings"); - ImGui::ColorPicker4("Skybox color", reinterpret_cast(&camera.skyboxColor)); + ImGui::ColorPicker4("Skybox color", reinterpret_cast(&camera.skyboxColor)); } }; } -} +} // namespace SpaceEditor diff --git a/editor/editor_gui/editor_gui.cpp b/editor/editor_gui/editor_gui.cpp index b9070d0..07f5565 100644 --- a/editor/editor_gui/editor_gui.cpp +++ b/editor/editor_gui/editor_gui.cpp @@ -11,93 +11,92 @@ EditorGui::EditorGui(const unsigned int sceneTexture, const unsigned int renderT void EditorGui::display() { displayBar(); - if (showInspector) { displayInspector(); } - if (showHierarchy) { displayHierarchy(); } - if (showProject) { displayProject(); } - if (showRender) { displayRender(); } - if (showConsole) { displayConsole(); } - if (showScene) { displayScene(); } -// if (showResourceManager) { displayResourceManager(); } // TODO: introduce back when refactor complete + if (showInspector) displayInspector(); + if (showHierarchy) displayHierarchy(); + if (showProject) displayProject(); + if (showRender) displayRender(); + if (showConsole) displayConsole(); + if (showScene) displayScene(); } void EditorGui::displayBar() { - /* Top bar options */ - if (ImGui::BeginMainMenuBar()) { - if (ImGui::BeginMenu("File")) { - if (ImGui::MenuItem("New", "CTRL+N")) { - scene = std::make_shared(); - } - if (ImGui::MenuItem("Open", "CTRL+O")) {} - if (ImGui::MenuItem("Save", "CTRL+S")) {} - if (ImGui::MenuItem("Save as", "CTRL+SHIFT+S")) {} - ImGui::Separator(); - if (ImGui::MenuItem("Import", "CTRL+I???")) {} - if (ImGui::MenuItem("Export", "CTRL+E???")) {} - ImGui::Separator(); - if (ImGui::MenuItem("Quit", "CTRL+W???")) {} - ImGui::EndMenu(); - } + if (!ImGui::BeginMainMenuBar()) { + ImGui::EndMainMenuBar(); + return; + } - if (ImGui::BeginMenu("Edit")) { - if (ImGui::MenuItem("Undo", "CTRL+Z")) {} - if (ImGui::MenuItem("Redo", "CTRL+Y", false, false)) {} - ImGui::Separator(); - if (ImGui::MenuItem("Cut", "CTRL+X")) {} - if (ImGui::MenuItem("Copy", "CTRL+C")) {} - if (ImGui::MenuItem("Paste", "CTRL+V")) {} - ImGui::EndMenu(); + if (ImGui::BeginMenu("File")) { + if (ImGui::MenuItem("New", "CTRL+N")) { + scene = std::make_shared(); } + if (ImGui::MenuItem("Open", "CTRL+O")) {} + if (ImGui::MenuItem("Save", "CTRL+S")) {} + if (ImGui::MenuItem("Save as", "CTRL+SHIFT+S")) {} + ImGui::Separator(); + if (ImGui::MenuItem("Import", "CTRL+I???")) {} + if (ImGui::MenuItem("Export", "CTRL+E???")) {} + ImGui::Separator(); + if (ImGui::MenuItem("Quit", "CTRL+W???")) {} + ImGui::EndMenu(); + } + + if (ImGui::BeginMenu("Edit")) { + if (ImGui::MenuItem("Undo", "CTRL+Z")) {} + if (ImGui::MenuItem("Redo", "CTRL+Y", false, false)) {} + ImGui::Separator(); + if (ImGui::MenuItem("Cut", "CTRL+X")) {} + if (ImGui::MenuItem("Copy", "CTRL+C")) {} + if (ImGui::MenuItem("Paste", "CTRL+V")) {} + ImGui::EndMenu(); + } - if (ImGui::BeginMenu("Add")) { - if (ImGui::MenuItem("Empty", "??")) { - if (scene) { - Entity e = scene->world.create(); - selectedEntity = e; - scene->world.add_component(e, Transform{"new entity"}); - } + if (ImGui::BeginMenu("Add")) { + if (ImGui::MenuItem("Empty", "??")) { + if (scene) { + Entity e = scene->world.create(); + selectedEntity = e; + scene->world.add_component(e, Transform{"new entity"}); } - ImGui::Separator(); - // 2D Forms - if (ImGui::MenuItem("Circle", "??")) {} - if (ImGui::MenuItem("Quad", "??")) {} - ImGui::Separator(); - // 3D Forms - if (ImGui::MenuItem("Sphere", "??")) {} - if (ImGui::MenuItem("Cube", "??")) {} - if (ImGui::MenuItem("Cylinder", "??")) {} - ImGui::EndMenu(); } + ImGui::Separator(); + // 2D Forms + if (ImGui::MenuItem("Circle", "??")) {} + if (ImGui::MenuItem("Quad", "??")) {} + ImGui::Separator(); + // 3D Forms + if (ImGui::MenuItem("Sphere", "??")) {} + if (ImGui::MenuItem("Cube", "??")) {} + if (ImGui::MenuItem("Cylinder", "??")) {} + ImGui::EndMenu(); + } - if (ImGui::BeginMenu("Window")) { - if (ImGui::MenuItem("Zoom in", "CTRL+PGUP")) {} - if (ImGui::MenuItem("Zoom out", "CTRL+PGDN")) {} - ImGui::Separator(); - ImGui::Checkbox("Inspector", &showInspector); - ImGui::Checkbox("Hierarchy", &showHierarchy); - ImGui::Checkbox("Project", &showProject); - ImGui::Checkbox("Scene", &showScene); - ImGui::Checkbox("Render", &showRender); - ImGui::Separator(); -// ImGui::Checkbox("Resource Manager", &showResourceManager); // TODO: introduce back when refactor complete - ImGui::Separator(); - if (ImGui::MenuItem("Toggle fullscreen", "F11")) {} - ImGui::Separator(); - // TODO: Add layouts - ImGui::Separator(); - if (ImGui::MenuItem("Reset layout", "CTRL+SHIFT+R")) {} - ImGui::Separator(); - if (ImGui::Checkbox("Wireframe Mode", &polygonMode)) { - if (polygonMode) { - glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); - } else { - glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); - } + if (ImGui::BeginMenu("Window")) { + if (ImGui::MenuItem("Zoom in", "CTRL+PGUP")) {} + if (ImGui::MenuItem("Zoom out", "CTRL+PGDN")) {} + ImGui::Separator(); + ImGui::Checkbox("Inspector", &showInspector); + ImGui::Checkbox("Hierarchy", &showHierarchy); + ImGui::Checkbox("Project", &showProject); + ImGui::Checkbox("Scene", &showScene); + ImGui::Checkbox("Render", &showRender); + ImGui::Separator(); + if (ImGui::MenuItem("Toggle fullscreen", "F11")) {} + ImGui::Separator(); + // TODO: Add layouts + ImGui::Separator(); + if (ImGui::MenuItem("Reset layout", "CTRL+SHIFT+R")) {} + ImGui::Separator(); + if (ImGui::Checkbox("Wireframe Mode", &polygonMode)) { + if (polygonMode) { + glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); + } else { + glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); } - ImGui::EndMenu(); } - - ImGui::EndMainMenuBar(); + ImGui::EndMenu(); } + + ImGui::EndMainMenuBar(); } void EditorGui::displayInspector() { @@ -106,6 +105,12 @@ void EditorGui::displayInspector() { return; } + if (!scene) { + ImGui::TextDisabled("No scene loaded"); + ImGui::End(); + return; + } + if (!selectedEntity) { ImGui::TextDisabled("No entity selected"); ImGui::End(); @@ -123,192 +128,172 @@ void EditorGui::displayInspector() { } void EditorGui::displayHierarchy() { - if (ImGui::Begin("Hierarchy")) { - if (scene) { - int index = 0; - for (auto entity : scene->world.view()) { - std::string uniqueLabel = scene->world.get_component(entity).name + "##" + std::to_string(index); - if (ImGui::Selectable(uniqueLabel.c_str(), selectedEntity == entity)) { - selectedEntity = entity; - } - index++; - } + if (!ImGui::Begin("Hierarchy")) { + ImGui::End(); + return; + } + + if (!scene) { + ImGui::TextDisabled("No scene loaded"); + ImGui::End(); + return; + } + + for (Entity entity : scene->world.view()) { + const auto& transform = scene->world.get_component(entity); + ImGui::PushID(entity.id); + if (ImGui::Selectable(transform.name.c_str(), selectedEntity == entity)) { + selectedEntity = entity; } + ImGui::PopID(); } ImGui::End(); } void EditorGui::displayProject() const { - if (ImGui::Begin("Project")) { - // TODO: Display project tree + if (!ImGui::Begin("Project")) { + ImGui::End(); + return; } + // TODO: Display project tree ImGui::End(); } void EditorGui::displayRender() const { - if (ImGui::Begin("Render")) { - if (scene) { - const ImVec2 window_size = ImGui::GetContentRegionAvail(); - constexpr float aspect_ratio = 1920.0f / 1080.0f; - const float window_aspect_ratio = window_size.x / window_size.y; - - ImVec2 image_size; - if (window_aspect_ratio > aspect_ratio) { - image_size = ImVec2(window_size.y * aspect_ratio, window_size.y); - } else { - image_size = ImVec2(window_size.x, window_size.x / aspect_ratio); - } + if (!ImGui::Begin("Render")) { + ImGui::End(); + return; + } - ImGui::Image(reinterpret_cast(renderTexture), image_size); - } + if (!scene) { + ImGui::TextDisabled("No scene loaded"); + ImGui::End(); + return; } + + const ImVec2 window_size = ImGui::GetContentRegionAvail(); + constexpr float aspect_ratio = 1920.0f / 1080.0f; + const float window_aspect_ratio = window_size.x / window_size.y; + + ImVec2 image_size; + if (window_aspect_ratio > aspect_ratio) { + image_size = ImVec2(window_size.y * aspect_ratio, window_size.y); + } else { + image_size = ImVec2(window_size.x, window_size.x / aspect_ratio); + } + + ImGui::Image(reinterpret_cast(renderTexture), image_size); ImGui::End(); } void EditorGui::displayConsole() { - if (ImGui::Begin("Console")) { - ImGui::Text("Search: "); - ImGui::SameLine(); - ImGui::InputText("##log_search", &Logger::filter.keyword); - ImGui::SeparatorText("Logs"); - for (const auto& log : Logger::getLogEntries()) { - std::string text = log.toString(); - ImGui::Text("%s", text.c_str()); - } + if (!ImGui::Begin("Console")) { + ImGui::End(); + return; + } + + ImGui::Text("Search: "); + ImGui::SameLine(); + ImGui::InputText("##log_search", &Logger::filter.keyword); + ImGui::SeparatorText("Logs"); + for (const auto& log : Logger::getLogEntries()) { + std::string text = log.toString(); + ImGui::Text("%s", text.c_str()); } ImGui::End(); } void EditorGui::displayScene() { - if (showScene) { - ImGui::Begin("Scene"); - if (scene) { - sceneHovered = ImGui::IsWindowHovered(); - - const ImVec2 window_size = ImGui::GetContentRegionAvail(); - constexpr float aspect_ratio = 1920.0f / 1080.0f; - const float window_aspect_ratio = window_size.x / window_size.y; - - ImVec2 image_size; - if (window_aspect_ratio > aspect_ratio) { - image_size = ImVec2(window_size.y * aspect_ratio, window_size.y); - } else { - image_size = ImVec2(window_size.x, window_size.x / aspect_ratio); - } + if (!ImGui::Begin("Scene")) { + ImGui::End(); + return; + } - ImGui::Image(reinterpret_cast(sceneTexture), image_size); - } + if (!scene) { + ImGui::TextDisabled("No scene loaded"); ImGui::End(); + return; } + + sceneHovered = ImGui::IsWindowHovered(); + + const ImVec2 window_size = ImGui::GetContentRegionAvail(); + constexpr float aspect_ratio = 1920.0f / 1080.0f; + const float window_aspect_ratio = window_size.x / window_size.y; + + ImVec2 image_size; + if (window_aspect_ratio > aspect_ratio) { + image_size = ImVec2(window_size.y * aspect_ratio, window_size.y); + } else { + image_size = ImVec2(window_size.x, window_size.x / aspect_ratio); + } + + ImGui::Image(reinterpret_cast(sceneTexture), image_size); + ImGui::End(); } -// -//void EditorGui::displayResourceManager() { // TODO: introduce back when refactor complete -// if (ImGui::Begin("Resource Manager")) { -// if (ImGui::BeginTable("ResourceTable", 5, ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | ImGuiTableFlags_Resizable)) { -// ImGui::TableSetupColumn("Type", ImGuiTableColumnFlags_WidthFixed); -// ImGui::TableSetupColumn("Path", ImGuiTableColumnFlags_WidthStretch); -// ImGui::TableSetupColumn("Alive", ImGuiTableColumnFlags_WidthFixed); -// ImGui::TableSetupColumn("Users Count", ImGuiTableColumnFlags_WidthFixed); -// ImGui::TableSetupColumn("Users", ImGuiTableColumnFlags_WidthFixed); -// ImGui::TableHeadersRow(); -// for (const auto& [typeIndex, resMap] : ResourceManager::getResources()) { -// const std::string typeName = typeIndex.name(); -// for (const auto& [path, resPtr] : resMap) { -// ImGui::TableNextRow(); -// ImGui::TableSetColumnIndex(0); -// ImGui::TextUnformatted(resPtr->getTypeName()); -// ImGui::TableSetColumnIndex(1); -// ImGui::TextUnformatted(path.c_str()); -// ImGui::TableSetColumnIndex(2); -// const float alive = resPtr->getTimeSinceLoad().count(); -// ImGui::Text("%.2fs", alive); -// ImGui::TableSetColumnIndex(3); -// const auto& userMap = ResourceManager::getResourceUsers(); -// const size_t userCount = userMap.contains(path) ? userMap.at(path).size() : 0; -// ImGui::Text("%zu", userCount); -// ImGui::TableSetColumnIndex(4); -// if (userCount == 0) { -// ImGui::TextDisabled("None"); -// } else { -// for (const auto& weak : userMap.at(path)) { -// if (auto user = weak.lock()) { -// auto* user_ptr = user.get(); -// ImGui::Text("- %s", typeid(*user_ptr).name()); -// } else { -// ImGui::TextDisabled("- expired"); -// } -// } -// } -// } -// } -// ImGui::EndTable(); -// } -// ImGui::End(); -// } -//} void EditorGui::cherryTheme() { - // cherry colors, 3 intensities - #define HI(v) ImVec4(0.502f, 0.075f, 0.256f, v) - #define MED(v) ImVec4(0.455f, 0.198f, 0.301f, v) - #define LOW(v) ImVec4(0.232f, 0.201f, 0.271f, v) - // backgrounds (@todo: complete with BG_MED, BG_LOW) - #define BG(v) ImVec4(0.200f, 0.220f, 0.270f, v) - // text - #define TEXT(v) ImVec4(0.860f, 0.930f, 0.890f, v) - - auto &style = ImGui::GetStyle(); - style.Colors[ImGuiCol_Text] = TEXT(0.78f); - style.Colors[ImGuiCol_TextDisabled] = TEXT(0.28f); - style.Colors[ImGuiCol_WindowBg] = ImVec4(0.13f, 0.14f, 0.17f, 1.00f); - style.Colors[ImGuiCol_WindowBg] = BG( 0.58f); - style.Colors[ImGuiCol_PopupBg] = BG( 0.9f); - style.Colors[ImGuiCol_Border] = ImVec4(0.31f, 0.31f, 1.00f, 0.00f); - style.Colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); - style.Colors[ImGuiCol_FrameBg] = BG( 1.00f); - style.Colors[ImGuiCol_FrameBgHovered] = MED( 0.78f); - style.Colors[ImGuiCol_FrameBgActive] = MED( 1.00f); - style.Colors[ImGuiCol_TitleBg] = LOW( 1.00f); - style.Colors[ImGuiCol_TitleBgActive] = HI( 1.00f); - style.Colors[ImGuiCol_TitleBgCollapsed] = BG( 0.75f); - style.Colors[ImGuiCol_MenuBarBg] = BG( 0.47f); - style.Colors[ImGuiCol_ScrollbarBg] = BG( 1.00f); - style.Colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.09f, 0.15f, 0.16f, 1.00f); - style.Colors[ImGuiCol_ScrollbarGrabHovered] = MED( 0.78f); - style.Colors[ImGuiCol_ScrollbarGrabActive] = MED( 1.00f); - style.Colors[ImGuiCol_CheckMark] = ImVec4(0.71f, 0.22f, 0.27f, 1.00f); - style.Colors[ImGuiCol_SliderGrab] = ImVec4(0.47f, 0.77f, 0.83f, 0.14f); - style.Colors[ImGuiCol_SliderGrabActive] = ImVec4(0.71f, 0.22f, 0.27f, 1.00f); - style.Colors[ImGuiCol_Button] = ImVec4(0.47f, 0.77f, 0.83f, 0.14f); - style.Colors[ImGuiCol_ButtonHovered] = MED( 0.86f); - style.Colors[ImGuiCol_ButtonActive] = MED( 1.00f); - style.Colors[ImGuiCol_Header] = MED( 0.76f); - style.Colors[ImGuiCol_HeaderHovered] = MED( 0.86f); - style.Colors[ImGuiCol_HeaderActive] = HI( 1.00f); - style.Colors[ImGuiCol_ButtonHovered] = MED( 0.78f); - style.Colors[ImGuiCol_ButtonActive] = MED( 1.00f); - style.Colors[ImGuiCol_ResizeGrip] = ImVec4(0.47f, 0.77f, 0.83f, 0.04f); - style.Colors[ImGuiCol_ResizeGripHovered] = MED( 0.78f); - style.Colors[ImGuiCol_ResizeGripActive] = MED( 1.00f); - style.Colors[ImGuiCol_PlotLines] = TEXT(0.63f); - style.Colors[ImGuiCol_PlotLinesHovered] = MED( 1.00f); - style.Colors[ImGuiCol_PlotHistogram] = TEXT(0.63f); - style.Colors[ImGuiCol_PlotHistogramHovered] = MED( 1.00f); - style.Colors[ImGuiCol_TextSelectedBg] = MED( 0.43f); - style.Colors[ImGuiCol_ModalWindowDimBg] = BG( 0.73f); - - style.WindowPadding = ImVec2(6, 4); - style.WindowRounding = 0.0f; - style.FramePadding = ImVec2(5, 2); - style.FrameRounding = 3.0f; - style.ItemSpacing = ImVec2(7, 1); - style.ItemInnerSpacing = ImVec2(1, 1); - style.TouchExtraPadding = ImVec2(0, 0); - style.IndentSpacing = 6.0f; - style.ScrollbarSize = 12.0f; - style.ScrollbarRounding = 16.0f; - style.GrabMinSize = 20.0f; - style.GrabRounding = 2.0f; +// cherry colors, 3 intensities +#define HI(v) ImVec4(0.502f, 0.075f, 0.256f, v) +#define MED(v) ImVec4(0.455f, 0.198f, 0.301f, v) +#define LOW(v) ImVec4(0.232f, 0.201f, 0.271f, v) +// backgrounds (@todo: complete with BG_MED, BG_LOW) +#define BG(v) ImVec4(0.200f, 0.220f, 0.270f, v) +// text +#define TEXT(v) ImVec4(0.860f, 0.930f, 0.890f, v) + + auto& style = ImGui::GetStyle(); + style.Colors[ImGuiCol_Text] = TEXT(0.78f); + style.Colors[ImGuiCol_TextDisabled] = TEXT(0.28f); + style.Colors[ImGuiCol_WindowBg] = ImVec4(0.13f, 0.14f, 0.17f, 1.00f); + style.Colors[ImGuiCol_WindowBg] = BG(0.58f); + style.Colors[ImGuiCol_PopupBg] = BG(0.9f); + style.Colors[ImGuiCol_Border] = ImVec4(0.31f, 0.31f, 1.00f, 0.00f); + style.Colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); + style.Colors[ImGuiCol_FrameBg] = BG(1.00f); + style.Colors[ImGuiCol_FrameBgHovered] = MED(0.78f); + style.Colors[ImGuiCol_FrameBgActive] = MED(1.00f); + style.Colors[ImGuiCol_TitleBg] = LOW(1.00f); + style.Colors[ImGuiCol_TitleBgActive] = HI(1.00f); + style.Colors[ImGuiCol_TitleBgCollapsed] = BG(0.75f); + style.Colors[ImGuiCol_MenuBarBg] = BG(0.47f); + style.Colors[ImGuiCol_ScrollbarBg] = BG(1.00f); + style.Colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.09f, 0.15f, 0.16f, 1.00f); + style.Colors[ImGuiCol_ScrollbarGrabHovered] = MED(0.78f); + style.Colors[ImGuiCol_ScrollbarGrabActive] = MED(1.00f); + style.Colors[ImGuiCol_CheckMark] = ImVec4(0.71f, 0.22f, 0.27f, 1.00f); + style.Colors[ImGuiCol_SliderGrab] = ImVec4(0.47f, 0.77f, 0.83f, 0.14f); + style.Colors[ImGuiCol_SliderGrabActive] = ImVec4(0.71f, 0.22f, 0.27f, 1.00f); + style.Colors[ImGuiCol_Button] = ImVec4(0.47f, 0.77f, 0.83f, 0.14f); + style.Colors[ImGuiCol_ButtonHovered] = MED(0.86f); + style.Colors[ImGuiCol_ButtonActive] = MED(1.00f); + style.Colors[ImGuiCol_Header] = MED(0.76f); + style.Colors[ImGuiCol_HeaderHovered] = MED(0.86f); + style.Colors[ImGuiCol_HeaderActive] = HI(1.00f); + style.Colors[ImGuiCol_ButtonHovered] = MED(0.78f); + style.Colors[ImGuiCol_ButtonActive] = MED(1.00f); + style.Colors[ImGuiCol_ResizeGrip] = ImVec4(0.47f, 0.77f, 0.83f, 0.04f); + style.Colors[ImGuiCol_ResizeGripHovered] = MED(0.78f); + style.Colors[ImGuiCol_ResizeGripActive] = MED(1.00f); + style.Colors[ImGuiCol_PlotLines] = TEXT(0.63f); + style.Colors[ImGuiCol_PlotLinesHovered] = MED(1.00f); + style.Colors[ImGuiCol_PlotHistogram] = TEXT(0.63f); + style.Colors[ImGuiCol_PlotHistogramHovered] = MED(1.00f); + style.Colors[ImGuiCol_TextSelectedBg] = MED(0.43f); + style.Colors[ImGuiCol_ModalWindowDimBg] = BG(0.73f); + + style.WindowPadding = ImVec2(6, 4); + style.WindowRounding = 0.0f; + style.FramePadding = ImVec2(5, 2); + style.FrameRounding = 3.0f; + style.ItemSpacing = ImVec2(7, 1); + style.ItemInnerSpacing = ImVec2(1, 1); + style.TouchExtraPadding = ImVec2(0, 0); + style.IndentSpacing = 6.0f; + style.ScrollbarSize = 12.0f; + style.ScrollbarRounding = 16.0f; + style.GrabMinSize = 20.0f; + style.GrabRounding = 2.0f; style.WindowTitleAlign.x = 0.50f; @@ -317,4 +302,4 @@ void EditorGui::cherryTheme() { style.WindowBorderSize = 1.0f; } -} \ No newline at end of file +} // namespace SpaceEditor \ No newline at end of file diff --git a/editor/editor_gui/editor_gui.hpp b/editor/editor_gui/editor_gui.hpp index 5e8cbc6..50148fd 100644 --- a/editor/editor_gui/editor_gui.hpp +++ b/editor/editor_gui/editor_gui.hpp @@ -1,32 +1,30 @@ #pragma once -#include -#include #include #include #include +#include +#include +#include "component/camera.hpp" +#include "component/light.hpp" +#include "component/model_renderer.hpp" +#include "component/physic.hpp" +#include "component/transform.hpp" +#include "ecs/world.hpp" #include "imgui/imgui_impl_glfw.h" #include "imgui/imgui_stdlib.h" - #include "log/logger.hpp" #include "scene/scene.hpp" -#include "ecs/world.hpp" - -#include "component/transform.hpp" -#include "component/camera.hpp" -#include "component/physic.hpp" -#include "component/model_renderer.hpp" -#include "component/light.hpp" -using SpaceEngine::Scene; -using SpaceEngine::World; -using SpaceEngine::Entity; -using SpaceEngine::Transform; -using SpaceEngine::Physic; -using SpaceEngine::ModelRenderer; using SpaceEngine::Camera; +using SpaceEngine::Entity; using SpaceEngine::Logger; +using SpaceEngine::ModelRenderer; +using SpaceEngine::Physic; +using SpaceEngine::Scene; +using SpaceEngine::Transform; +using SpaceEngine::World; namespace SpaceEditor { @@ -37,7 +35,6 @@ class EditorGui { bool showScene = true; bool showRender = true; bool showConsole = true; -// bool showResourceManager = false; // TODO: introduce back when refactor complete bool polygonMode = true; unsigned int sceneTexture; @@ -53,9 +50,8 @@ class EditorGui { void displayScene(); void displayRender() const; void displayConsole(); -// void displayResourceManager(); // TODO: introduce back when refactor complete -public: + public: std::shared_ptr scene = nullptr; std::optional selectedEntity; @@ -70,4 +66,4 @@ class EditorGui { static void cherryTheme(); }; -} \ No newline at end of file +} // namespace SpaceEditor \ No newline at end of file diff --git a/editor/main.cpp b/editor/main.cpp index be2e03d..a7a445d 100644 --- a/editor/main.cpp +++ b/editor/main.cpp @@ -10,7 +10,7 @@ #include "renderer/renderer.hpp" /* TODO: REMOVE */ -#include "input/input.hpp" // TODO: switch from using glfw input system to the engine input system +#include "input/input.hpp" // TODO: switch from using glfw input system to the engine input system #include "ecs/world.hpp" #include "component/camera.hpp" @@ -27,8 +27,8 @@ using namespace SpaceEditor; // Camera EditorCamera camera; -float lastX = 1920.0f / 2.0; -float lastY = 1080.0 / 2.0; +float lastX = 1920.0f / 2.0; +float lastY = 1080.0 / 2.0; bool firstMouse = true; // timing @@ -57,22 +57,22 @@ int main() { return -1; } - #if defined(IMGUI_IMPL_OPENGL_ES2) - auto glsl_version = "#version 100"; - glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2); - glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0); - glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_ES_API); - #elif defined(__APPLE__) - auto glsl_version = "#version 150"; - glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); - glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); - glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); - glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); - #else - auto glsl_version = "#version 130"; - glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); - glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0); - #endif +#if defined(IMGUI_IMPL_OPENGL_ES2) + auto glsl_version = "#version 100"; + glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2); + glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0); + glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_ES_API); +#elif defined(__APPLE__) + auto glsl_version = "#version 150"; + glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); + glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); + glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); + glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); +#else + auto glsl_version = "#version 130"; + glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); + glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0); +#endif GLFWwindow* window = glfwCreateWindow(1920, 1080, "Space Engine", nullptr, nullptr); if (window == nullptr) { @@ -102,7 +102,7 @@ int main() { // Initialize renderers sceneRenderer = std::make_unique(); renderViewRenderer = std::make_unique(); - + if (!sceneRenderer->initialize(1920, 1080) || !renderViewRenderer->initialize(1920, 1080)) { std::cout << "Failed to initialize renderers" << std::endl; return -1; @@ -111,7 +111,8 @@ int main() { // Setup ImGui context IMGUI_CHECKVERSION(); ImGui::CreateContext(); - ImGuiIO& io = ImGui::GetIO(); (void)io; + ImGuiIO& io = ImGui::GetIO(); + (void)io; io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; @@ -121,7 +122,8 @@ int main() { ImGui_ImplGlfw_InitForOpenGL(window, true); ImGui_ImplOpenGL3_Init(glsl_version); - auto gui = EditorGui(sceneRenderer->getRenderedTexture(), renderViewRenderer->getRenderedTexture()); + auto gui = EditorGui(sceneRenderer->getRenderedTexture(), + renderViewRenderer->getRenderedTexture()); //TODO : Remove too auto scene = std::make_shared(); @@ -141,18 +143,14 @@ int main() { lastFrame = currentFrame; Input::update(); - Input::dispatchBindings(); // TODO only supposed to be in the game code + Input::dispatchBindings(); // TODO only supposed to be in the game code if (gui.inspectorFocus) { // Keyboard inputs handling - if (Input::isKeyPressed(KeyCode::W)) - camera.processKeyboard(FORWARD, deltaTime); - if (Input::isKeyPressed(KeyCode::S)) - camera.processKeyboard(BACKWARD, deltaTime); - if (Input::isKeyPressed(KeyCode::A)) - camera.processKeyboard(LEFT, deltaTime); - if (Input::isKeyPressed(KeyCode::D)) - camera.processKeyboard(RIGHT, deltaTime); + if (Input::isKeyPressed(KeyCode::W)) camera.processKeyboard(FORWARD, deltaTime); + if (Input::isKeyPressed(KeyCode::S)) camera.processKeyboard(BACKWARD, deltaTime); + if (Input::isKeyPressed(KeyCode::A)) camera.processKeyboard(LEFT, deltaTime); + if (Input::isKeyPressed(KeyCode::D)) camera.processKeyboard(RIGHT, deltaTime); // Mouse movements handling const float currentX = Input::getMouseX(); @@ -171,15 +169,17 @@ int main() { // Zoom handling if (Input::getScrollDelta() != 0.0f) { - camera.processMouseScroll(Input::consumeScrollDelta() * 5); // TODO: Not hardcode this + camera.processMouseScroll(Input::consumeScrollDelta() * 5); // TODO: Not hardcode this } // Rendering scene and render view in editor sceneRenderer->render(camera.getEditorViewMatrix(), camera.getProjectionMatrix(), scene); - if (scene) { // TODO rework this + if (scene) { // TODO rework this const auto sceneCamera = scene->selectedCamera; Camera camera = scene->world.get_component(sceneCamera); - renderViewRenderer->render(camera.getViewMatrix(scene->world, sceneCamera), camera.getProjectionMatrix(), scene); + renderViewRenderer->render(camera.getViewMatrix(scene->world, sceneCamera), + camera.getProjectionMatrix(), + scene); } // Clear the main framebuffer @@ -194,7 +194,8 @@ int main() { ImGui::NewFrame(); ImGui::DockSpaceOverViewport(); - if (!gui.inspectorFocus && gui.sceneHovered && Input::isMouseButtonPressed(MouseButton::Right)) { + if (!gui.inspectorFocus && gui.sceneHovered && + Input::isMouseButtonPressed(MouseButton::Right)) { gui.inspectorFocus = true; glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); } else if (gui.inspectorFocus && !Input::isMouseButtonPressed(MouseButton::Right)) { diff --git a/format.py b/format.py new file mode 100644 index 0000000..36c04dd --- /dev/null +++ b/format.py @@ -0,0 +1,44 @@ +import subprocess +import sys + +EXTS = (".c", ".cc", ".cpp", ".h", ".hpp", ".inl") +EXCLUDE_PREFIX = ("libs/", "build/") + +CHECK_MODE = "--check" in sys.argv + + +def run(cmd): + result = subprocess.run(cmd) + if result.returncode != 0: + sys.exit(result.returncode) + + +output = subprocess.check_output(["git", "ls-files"], text=True) + +files = [] +for line in output.splitlines(): + if not line.endswith(EXTS): + continue + + if line.startswith(EXCLUDE_PREFIX): + continue + + files.append(line) + +if not files: + print("No files to format") + sys.exit(0) + +cmd = ["clang-format"] + +if CHECK_MODE: + cmd += ["--dry-run", "--Werror"] +else: + cmd += ["-i"] + +cmd += files + +print("Running:", " ".join(cmd)) +run(cmd) + +print("Done.") diff --git a/project_template/main.cpp b/project_template/main.cpp index 6ddc3b3..cdd25e5 100644 --- a/project_template/main.cpp +++ b/project_template/main.cpp @@ -1,30 +1,29 @@ -#include #include +#include -#include "shader/shader.hpp" +#include "model/model.hpp" // maybe removed soon +#include "renderer/renderer.hpp" #include "scene/scene.hpp" +#include "shader/shader.hpp" #include "space/space.hpp" -#include "model/model.hpp" // maybe removed soon -#include "renderer/renderer.hpp" /* TODO: REMOVE */ /* DEBUG */ -#include "entity/entity.hpp" +#include "component/camera.hpp" #include "component/component.hpp" -#include "component/transform.hpp" -#include "component/physic.hpp" #include "component/model_renderer.hpp" -#include "component/camera.hpp" - +#include "component/physic.hpp" +#include "component/transform.hpp" +#include "entity/entity.hpp" // OPENGL TEST TODO REMOVE #define STB_IMAGE_IMPLEMENTATION -#include "stb_image.h" - #include #include #include +#include "stb_image.h" + using namespace SpaceEngine; // timing @@ -46,23 +45,22 @@ int main() { return -1; } - - #if defined(IMGUI_IMPL_OPENGL_ES2) - const char* glsl_version = "#version 100"; - glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2); - glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0); - glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_ES_API); - #elif defined(__APPLE__) - const char* glsl_version = "#version 150"; - glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); - glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); - glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); - glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); - #else - const char* glsl_version = "#version 130"; - glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); - glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0); - #endif +#if defined(IMGUI_IMPL_OPENGL_ES2) + const char* glsl_version = "#version 100"; + glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2); + glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0); + glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_ES_API); +#elif defined(__APPLE__) + const char* glsl_version = "#version 150"; + glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); + glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); + glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); + glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); +#else + const char* glsl_version = "#version 130"; + glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); + glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0); +#endif // Create a window with graphic context GLFWwindow* window = glfwCreateWindow(1280, 720, "Space Engine", nullptr, nullptr); @@ -92,7 +90,7 @@ int main() { // Initialize renderer renderer = std::make_unique(); - if (!renderer->initialize(1920, 1080)) { // TODO: Not hardcode resolution + if (!renderer->initialize(1920, 1080)) { // TODO: Not hardcode resolution std::cout << "Failed to initialize renderer" << std::endl; return -1; } diff --git a/tests/main.cpp b/tests/main.cpp index c6e5910..3937460 100644 --- a/tests/main.cpp +++ b/tests/main.cpp @@ -1,7 +1,7 @@ -#include -#include #include #include +#include +#include extern int testVector2(); extern int testVector3(); @@ -17,13 +17,13 @@ struct TestFunction { }; TestFunction test_fn[] = { - {"testVector2", testVector2}, - {"testVector3", testVector3}, - {"testVector4", testVector4}, - {"testLog", testLog}, - {"testLogger", testLogger}, - {"TestTime", testTime}, - {"testInputBinding", testInputBinding}, + {"testVector2", testVector2}, + {"testVector3", testVector3}, + {"testVector4", testVector4}, + {"testLog", testLog}, + {"testLogger", testLogger}, + {"TestTime", testTime}, + {"testInputBinding", testInputBinding}, }; void run_all_tests() { @@ -31,15 +31,15 @@ void run_all_tests() { std::cout << "\033[1;37mRunning tests . . .\033[0m" << std::endl; size_t max_length = 0; - for (const auto&[name, function] : test_fn) { + for (const auto& [name, function] : test_fn) { if (const size_t test_length = strlen(name); test_length > max_length) { max_length = test_length; } } - for (const auto&[name, function] : test_fn) { - std::cout << - "\033[1;37mRunning test: " << std::setw(static_cast(max_length)) << std::left << name << " \033[0m"; + for (const auto& [name, function] : test_fn) { + std::cout << "\033[1;37mRunning test: " << std::setw(static_cast(max_length)) << std::left + << name << " \033[0m"; if (const int result = function(); result == 0) { std::cout << "\033[1;32mPassed\033[0m" << std::endl; } else { @@ -62,8 +62,7 @@ int main() { try { std::filesystem::remove_all((sourceDir / "generated").string()); std::filesystem::create_directory((sourceDir / "generated").string()); - } - catch(const std::exception& e) { + } catch (const std::exception& e) { std::cerr << e.what() << '\n'; } diff --git a/tests/test.hpp b/tests/test.hpp index 15693f4..cf30ae9 100644 --- a/tests/test.hpp +++ b/tests/test.hpp @@ -1,10 +1,11 @@ #pragma once -#define custom_assert(expression, message) \ - if (!(expression)) { \ - std::cout << "\033[1;31mAssertion Failed: " << message << "\033[0m" << std::endl; \ - std::cerr << "Failed condition: " << #expression << "\nIn file: " << __FILE__ << ", line " << __LINE__ << std::endl; \ - return 1; \ +#define custom_assert(expression, message) \ + if (!(expression)) { \ + std::cout << "\033[1;31mAssertion Failed: " << message << "\033[0m" << std::endl; \ + std::cerr << "Failed condition: " << #expression << "\nIn file: " << __FILE__ << ", line " \ + << __LINE__ << std::endl; \ + return 1; \ } #include \ No newline at end of file diff --git a/tests/test_entity.cpp b/tests/test_entity.cpp index b88d56f..a8069fc 100644 --- a/tests/test_entity.cpp +++ b/tests/test_entity.cpp @@ -1,30 +1,36 @@ -#include "test.hpp" #include "component/camera.hpp" +#include "test.hpp" using namespace SpaceEngine; -int testEntity() { //TODO use new ecs -// const auto ent1 = Entity::create("ent1"); -// const auto ent2 = Entity::create("ent2"); -// -// const auto tf1 = ent1->getComponent(); -// custom_assert(tf1 != nullptr, "Entity getComponent failed."); -// -// custom_assert(ent1->addComponent("test") == false, "Entity adding duplicate component prevention failed."); -// -// ent1->addComponent(); -// custom_assert(ent1->getComponent() != nullptr, "Entity addComponent failed."); -// -// ent1->getComponent()->position.x() = 25.74f; -// custom_assert(ent1->getComponent()->position.x() == 25.74f, "Entity component modification failed") -// -// ent1->removeComponent(); -// custom_assert(ent1->getComponent() == nullptr, "Entity removeComponent failed"); -// -// ent1->addChild(ent2); -// custom_assert(ent1->findChild("ent2") == ent2, "Entity findChild with name failed"); -// -// ent1->removeChild("ent2"); -// custom_assert(ent1->findChild("ent2") == nullptr, "Entity removeChild with name failed"); +int testEntity() { // TODO use new ecs + // const auto ent1 = Entity::create("ent1"); + // const auto ent2 = Entity::create("ent2"); + // + // const auto tf1 = ent1->getComponent(); + // custom_assert(tf1 != nullptr, "Entity getComponent failed."); + // + // custom_assert(ent1->addComponent("test") == false, "Entity + // adding duplicate component prevention failed."); + // + // ent1->addComponent(); + // custom_assert(ent1->getComponent() != nullptr, "Entity + // addComponent failed."); + // + // ent1->getComponent()->position.x() = 25.74f; + // custom_assert(ent1->getComponent()->position.x() == 25.74f, + // "Entity component modification failed") + // + // ent1->removeComponent(); + // custom_assert(ent1->getComponent() == nullptr, "Entity + // removeComponent failed"); + // + // ent1->addChild(ent2); + // custom_assert(ent1->findChild("ent2") == ent2, "Entity findChild with name + // failed"); + // + // ent1->removeChild("ent2"); + // custom_assert(ent1->findChild("ent2") == nullptr, "Entity removeChild with + // name failed"); return 0; } diff --git a/tests/test_input_binding.cpp b/tests/test_input_binding.cpp index ea5dd08..0aabf85 100644 --- a/tests/test_input_binding.cpp +++ b/tests/test_input_binding.cpp @@ -1,5 +1,5 @@ -#include "test.hpp" #include "input/input.hpp" +#include "test.hpp" using namespace SpaceEngine; @@ -9,12 +9,14 @@ int testInputBinding() { int onceCallCount = 0; // Bind to key - const auto keyId = Input::bindKey(KeyCode::A, [&]() { keyCallCount++; }, -1, InputEventType::OnPress); + const auto + keyId = Input::bindKey(KeyCode::A, [&]() { keyCallCount++; }, -1, InputEventType::OnPress); Input::simulateKey(KeyCode::A); custom_assert(keyCallCount == 1, "Key binding did not trigger"); // Bind to mouse button - const auto mouseId = Input::bindMouseButton(MouseButton::Left, [&]() { mouseCallCount++; }, -1, InputEventType::OnPress); + const auto mouseId = Input:: + bindMouseButton(MouseButton::Left, [&]() { mouseCallCount++; }, -1, InputEventType::OnPress); Input::simulateMouseButton(MouseButton::Left); custom_assert(mouseCallCount == 1, "Mouse binding did not trigger"); @@ -46,7 +48,8 @@ int testInputBinding() { // Rebind for clearing tests Input::bindKey(KeyCode::C, [&]() { keyCallCount++; }, -1, InputEventType::OnPress); - Input::bindMouseButton(MouseButton::Right, [&]() { mouseCallCount++; }, -1, InputEventType::OnPress); + Input:: + bindMouseButton(MouseButton::Right, [&]() { mouseCallCount++; }, -1, InputEventType::OnPress); Input::clearKeyBindings(); Input::clearMouseButtonBindings(); Input::simulateKey(KeyCode::C); @@ -56,7 +59,8 @@ int testInputBinding() { // Final cleanup Input::bindKey(KeyCode::D, [&]() { keyCallCount++; }, -1, InputEventType::OnPress); - Input::bindMouseButton(MouseButton::Button4, [&]() { mouseCallCount++; }, -1, InputEventType::OnPress); + Input::bindMouseButton( + MouseButton::Button4, [&]() { mouseCallCount++; }, -1, InputEventType::OnPress); Input::clearAllBindings(); Input::simulateKey(KeyCode::D); custom_assert(keyCallCount == 2, "All bindings should have been cleared"); diff --git a/tests/test_log.cpp b/tests/test_log.cpp index cefea3a..a38594d 100644 --- a/tests/test_log.cpp +++ b/tests/test_log.cpp @@ -1,5 +1,5 @@ -#include "test.hpp" #include "log/log.hpp" +#include "test.hpp" using namespace SpaceEngine; @@ -20,7 +20,8 @@ int testLog() { const std::chrono::system_clock::time_point now = std::chrono::system_clock::now(); const std::chrono::system_clock::time_point minTimestamp = now - std::chrono::seconds(1); const std::chrono::system_clock::time_point maxTimestamp = now + std::chrono::seconds(1); - custom_assert(log.timestamp >= minTimestamp && log.timestamp <= maxTimestamp, "Log timestamp incorrect"); + custom_assert(log.timestamp >= minTimestamp && log.timestamp <= maxTimestamp, + "Log timestamp incorrect"); // Test LogLevelToString() method const std::string logLevelString = Log::LogLevelToString(LogLevel::WARNING); diff --git a/tests/test_logger.cpp b/tests/test_logger.cpp index eb06e4c..00be478 100644 --- a/tests/test_logger.cpp +++ b/tests/test_logger.cpp @@ -1,5 +1,5 @@ -#include "test.hpp" #include "log/logger.hpp" +#include "test.hpp" using namespace SpaceEngine; @@ -7,15 +7,25 @@ int testLogger() { // Add log entries Logger::log(LogLevel::DEBUG, LogType::Core, "Core subsystem initialized successfully."); Logger::log(LogLevel::INFORMATION, LogType::Rendering, "OpenGL context created: Version 4.5"); - Logger::log(LogLevel::WARNING, LogType::Audio, "Audio file 'background.mp3' not found, using fallback."); + Logger::log(LogLevel::WARNING, + LogType::Audio, + "Audio file 'background.mp3' not found, using fallback."); Logger::log(LogLevel::ERROR, LogType::Scripting, "Undefined variable in playerMovement script."); Logger::log(LogLevel::FATAL, LogType::Editor, "Unhandled exception caught: Access violation."); - Logger::log(LogLevel::DEBUG, LogType::AssetLoading, "Started loading asset bundle 'environment.pack'."); + Logger::log(LogLevel::DEBUG, + LogType::AssetLoading, + "Started loading asset bundle 'environment.pack'."); Logger::info("Custom control scheme loaded for gamepad."); - Logger::log(LogLevel::WARNING, LogType::AssetLoading, "High-resolution texture 'forest.png' may affect performance."); + Logger::log(LogLevel::WARNING, + LogType::AssetLoading, + "High-resolution texture 'forest.png' may affect performance."); Logger::error("Failed to compile vertex shader 'basic.vert'."); - Logger::log(LogLevel::DEBUG, LogType::Scripting, "Player script attached to entity 'PlayerCharacter'."); - Logger::log(LogLevel::DEBUG, LogType::Scripting, "Enemy script attached to entity 'EnemyController'."); + Logger::log(LogLevel::DEBUG, + LogType::Scripting, + "Player script attached to entity 'PlayerCharacter'."); + Logger::log(LogLevel::DEBUG, + LogType::Scripting, + "Enemy script attached to entity 'EnemyController'."); // Check if the log entries are added correctly custom_assert(Logger::getLogEntries().size() == 11, "Logger log method failed"); @@ -24,11 +34,13 @@ int testLogger() { Logger::filter.setLogLevel(LogLevel::DEBUG, true); custom_assert(Logger::getLogEntries().size() == 4, "Logger log level filter method failed"); - // Check if the filters retrieve the correct entries with log level/type filter. + // Check if the filters retrieve the correct entries with log level/type + // filter. Logger::filter.setLogType(LogType::Scripting, true); custom_assert(Logger::getLogEntries().size() == 2, "Logger log type filter method failed"); - // Check if the filters retrieve the correct entries with log level/type/keyword filter. + // Check if the filters retrieve the correct entries with log + // level/type/keyword filter. Logger::filter.keyword = "Enemy"; custom_assert(Logger::getLogEntries().size() == 1, "Logger keyword filter method failed"); diff --git a/tests/test_time.cpp b/tests/test_time.cpp index a2cfced..e6f18a0 100644 --- a/tests/test_time.cpp +++ b/tests/test_time.cpp @@ -16,6 +16,7 @@ int testTime() { constexpr float epsilon = 0.001f; custom_assert(std::abs(deltaTime - expected) < epsilon, - "deltaTime (" << deltaTime << ") != unscaledDeltaTime * scale (" << expected << ")"); + "deltaTime (" << deltaTime << ") != unscaledDeltaTime * scale (" << expected + << ")"); return 0; } diff --git a/tests/test_vector2.cpp b/tests/test_vector2.cpp index b84b24d..b730f3a 100644 --- a/tests/test_vector2.cpp +++ b/tests/test_vector2.cpp @@ -1,5 +1,5 @@ -#include "test.hpp" #include "maths/vector.hpp" +#include "test.hpp" using namespace SpaceEngine; @@ -13,14 +13,14 @@ int testVector2() { // Vector/Scalar addition custom_assert(vec1 + 3 == Vec2f(4.0f, 5.0f), "Vec2f scalar addition failed") - // Vector/Vector subtraction - custom_assert(vec1 - vec2 == Vec2f(-2.0f, -3.0f), "Vec2f subtraction failed"); + // Vector/Vector subtraction + custom_assert(vec1 - vec2 == Vec2f(-2.0f, -3.0f), "Vec2f subtraction failed"); // Vector/Scalar subtraction custom_assert(vec2 - 3 == Vec2f(0.0f, 2.0f), "Vec2f scalar subtraction failed") - // Multiplication by a scalar - custom_assert(vec1 * 2.0 == Vec2f(2.0f, 4.0f), "Vec2f scalar multiplication failed"); + // Multiplication by a scalar + custom_assert(vec1 * 2.0 == Vec2f(2.0f, 4.0f), "Vec2f scalar multiplication failed"); // Division by a scalar custom_assert(vec1 / 2.0 == Vec2f(0.5f, 1.0f), "Vec2f scalar division failed"); diff --git a/tests/test_vector3.cpp b/tests/test_vector3.cpp index 517419a..809eaf4 100644 --- a/tests/test_vector3.cpp +++ b/tests/test_vector3.cpp @@ -1,5 +1,5 @@ -#include "test.hpp" #include "maths/vector.hpp" +#include "test.hpp" using namespace SpaceEngine; @@ -64,7 +64,7 @@ int testVector3() { // inequality custom_assert(vec1 != vec2, "Vec3f inequality failed"); - // extension + // extension const auto extendedVec = Vec4f(vec1, 4.0f); custom_assert(extendedVec == Vec4f(1.0f, 2.0f, 3.0f, 4.0f), "Vec3f to Vec4f extension failed"); diff --git a/tests/test_vector4.cpp b/tests/test_vector4.cpp index 88afb3c..4d067e7 100644 --- a/tests/test_vector4.cpp +++ b/tests/test_vector4.cpp @@ -1,5 +1,5 @@ -#include "test.hpp" #include "maths/vector.hpp" +#include "test.hpp" using namespace SpaceEngine; @@ -56,7 +56,8 @@ int testVector4() { custom_assert(vec3 == Vec4f(0.5f, 1.0f, 1.5f, 2.0f), "Vec4f /= failed"); // operator[] - custom_assert(vec1[0] == 1.0f && vec1[1] == 2.0f && vec1[2] == 3.0f && vec1[3] == 4.0f, "Vec4f operator[] failed"); + custom_assert(vec1[0] == 1.0f && vec1[1] == 2.0f && vec1[2] == 3.0f && vec1[3] == 4.0f, + "Vec4f operator[] failed"); // equality custom_assert(vec1 == Vec4f(1.0f, 2.0f, 3.0f, 4.0f), "Vec4f equality failed"); @@ -65,7 +66,7 @@ int testVector4() { custom_assert(vec1 != vec2, "Vec4f inequality failed"); // truncation to Vec3f - custom_assert(Vec3f(vec1) == Vec3f(1.0f, 2.0f,3.0f), "Vec4f to Vec3f truncation failed"); + custom_assert(Vec3f(vec1) == Vec3f(1.0f, 2.0f, 3.0f), "Vec4f to Vec3f truncation failed"); // dot product custom_assert(vec1.dot(vec2) == 70.0f, "Vec4f dot product failed");