From 0cedb2b0ba8696dc9bda15b94660c322252966f4 Mon Sep 17 00:00:00 2001 From: light7734 Date: Sat, 5 Jul 2025 13:28:41 +0330 Subject: [PATCH] refactor: directory structure & cmake --- .clang-format | 48 ++-- .clang-tidy | 250 ++++++++++++++++ .gitmodules | 25 +- CMakeLists.txt | 67 +---- Engine/.clang-format | 139 --------- Engine/CMakeLists.txt | 56 ---- Engine/src/Engine/Camera/Camera.cpp | 6 - Engine/src/Engine/Camera/Camera.hpp | 27 -- .../src/Engine/Camera/OrthographicCamera.cpp | 38 --- .../src/Engine/Camera/OrthographicCamera.hpp | 41 --- Engine/src/Engine/Core/Application.hpp | 54 ---- Engine/src/Engine/Core/UUID.hpp | 35 --- Engine/src/Engine/Core/Window.hpp | 73 ----- Engine/src/Engine/Debug/Logger.hpp | 43 --- Engine/src/Engine/Events/Event.hpp | 57 ---- Engine/src/Engine/Graphics/Blender.cpp | 29 -- Engine/src/Engine/Graphics/Buffers.cpp | 69 ----- Engine/src/Engine/Graphics/Framebuffer.cpp | 30 -- .../src/Engine/Graphics/GraphicsContext.cpp | 79 ------ Engine/src/Engine/Graphics/RenderCommand.cpp | 30 -- Engine/src/Engine/Graphics/RenderCommand.hpp | 37 --- Engine/src/Engine/Graphics/Renderer.hpp | 84 ------ .../RendererPrograms/QuadRendererProgram.cpp | 58 ---- .../TextureRendererProgram.cpp | 57 ---- .../TintedTextureRendererProgram.cpp | 58 ---- Engine/src/Engine/Graphics/Shader.cpp | 31 -- Engine/src/Engine/Graphics/Shader.hpp | 35 --- Engine/src/Engine/Graphics/Texture.cpp | 35 --- Engine/src/Engine/Graphics/VertexLayout.cpp | 30 -- Engine/src/Engine/Input/Input.hpp | 53 ---- Engine/src/Engine/Input/KeyCodes.hpp | 184 ------------ Engine/src/Engine/Layer/Layer.cpp | 62 ---- Engine/src/Engine/Layer/Layer.hpp | 78 ----- Engine/src/Engine/Layer/LayerStack.hpp | 51 ---- Engine/src/Engine/LightEngine.hpp | 60 ---- Engine/src/Engine/Scene/Components.hpp | 8 - .../Scene/Components/CameraComponent.hpp | 26 -- .../Components/NativeScriptComponent.hpp | 28 -- .../Components/SpriteRendererComponent.hpp | 25 -- .../Engine/Scene/Components/TagComponent.hpp | 23 -- .../Scene/Components/TransformComponent.hpp | 34 --- .../Engine/Scene/Components/UUIDComponent.hpp | 17 -- Engine/src/Engine/Scene/Entity.cpp | 16 -- Engine/src/Engine/Scene/Scene.hpp | 43 --- Engine/src/Engine/Time/Timer.cpp | 22 -- Engine/src/Engine/Time/Timer.hpp | 38 --- .../Engine/UserInterface/UserInterface.cpp | 222 --------------- Engine/src/Engine/Utility/FileManager.cpp | 81 ------ Engine/src/Engine/Utility/FileManager.hpp | 66 ----- Engine/src/Engine/Utility/ResourceManager.cpp | 72 ----- Engine/src/Engine/Utility/ResourceManager.hpp | 44 --- Engine/src/Engine/Utility/Serializer.hpp | 30 -- Engine/src/Engine/ltpch.cpp | 1 - .../GraphicsAPI/DirectX/dxFramebuffer.cpp | 94 ------ .../Platform/GraphicsAPI/DirectX/dxShader.cpp | 45 --- .../GraphicsAPI/DirectX/dxSharedContext.hpp | 31 -- .../GraphicsAPI/DirectX/dxTexture.cpp | 67 ----- .../GraphicsAPI/OpenGL/glFramebuffer.hpp | 28 -- .../GraphicsAPI/OpenGL/glGraphicsContext.cpp | 100 ------- .../GraphicsAPI/OpenGL/glSharedContext.hpp | 12 - Engine/src/Platform/OS/Linux/lWindow.cpp | 228 --------------- Engine/src/Platform/OS/Windows/wWindow.cpp | 234 --------------- Engine/src/renameall.sh | 5 - Mirror/.clang-format | 139 --------- Mirror/CMakeLists.txt | 23 -- Mirror/src/MirrorApp.cpp | 32 --- Mirror/src/Panels/PropertiesPanel.cpp | 232 --------------- .../assets/fonts/open_sans}/LICENSE.txt | 0 .../assets/fonts/open_sans}/OpenSans-Bold.ttf | Bin .../fonts/open_sans}/OpenSans-BoldItalic.ttf | Bin .../fonts/open_sans}/OpenSans-ExtraBold.ttf | Bin .../open_sans}/OpenSans-ExtraBoldItalic.ttf | Bin .../fonts/open_sans}/OpenSans-Italic.ttf | Bin .../fonts/open_sans}/OpenSans-Light.ttf | Bin .../fonts/open_sans}/OpenSans-LightItalic.ttf | Bin .../fonts/open_sans}/OpenSans-Regular.ttf | Bin .../fonts/open_sans}/OpenSans-SemiBold.ttf | Bin .../open_sans}/OpenSans-SemiBoldItalic.ttf | Bin .../Scenes => data/assets/scenes}/demo.scene | 0 .../assets/shaders/quads}/Quad_PS.glsl | 0 .../assets/shaders/quads}/Quad_VS.glsl | 0 .../assets/shaders/texture}/Texture_PS.glsl | 0 .../assets/shaders/texture}/Texture_VS.glsl | 0 .../tinted_texture}/TintedTexture_PS.glsl | 0 .../tinted_texture}/TintedTexture_VS.glsl | 0 .../assets/textures}/awesomeface.png | Bin .../engine/icons}/Asset_Directory.png | Bin .../engine/icons}/Asset_Image.png | Bin .../engine/icons}/Asset_Scene.png | Bin .../engine/icons}/Asset_Text.png | Bin {Dependencies => external}/CMakeLists.txt | 21 +- .../configurations}/imgui/imconfig.h | 0 {Dependencies => external}/imgui | 0 modules/CMakeLists.txt | 2 + modules/engine/CMakeLists.txt | 116 ++++++++ .../engine/include/engine/base/base.hpp | 36 ++- .../engine/include/engine/base/config.hpp | 0 .../engine/include/engine/base/entrypoint.hpp | 20 +- .../engine/base/portables/debug_trap.hpp | 36 ++- .../engine/include/engine/camera/camera.hpp | 35 +++ .../engine/include/engine/camera/ortho.hpp | 54 ++++ .../engine/include/engine/camera/scene.hpp | 43 ++- .../include/engine/core/application.hpp | 54 ++++ modules/engine/include/engine/core/uuid.hpp | 38 +++ modules/engine/include/engine/core/window.hpp | 99 +++++++ .../include/engine/debug/exceptions.hpp | 0 .../include/engine/debug/instrumentor.hpp | 27 +- .../engine/include/engine/debug/logger.hpp | 58 ++++ modules/engine/include/engine/engine.hpp | 61 ++++ .../engine/include/engine/events/char.hpp | 15 +- .../engine/include/engine/events/event.hpp | 63 +++++ .../engine/include/engine/events/keyboard.hpp | 31 +- .../engine/include/engine/events/mouse.hpp | 49 ++-- .../engine/include/engine/events/window.hpp | 23 +- .../include/engine/graphics/blender.hpp | 2 +- .../include/engine/graphics/buffers.hpp | 4 +- .../include/engine/graphics/framebuffer.hpp | 4 +- .../engine/graphics/graphics_context.hpp | 4 +- .../engine/graphics/render_command.hpp | 41 +++ .../include/engine/graphics/renderer.hpp | 134 +++++++++ .../graphics/renderer_programs/quad.hpp | 28 +- .../renderer_programs/renderer_program.hpp | 4 +- .../graphics/renderer_programs/texture.hpp | 26 +- .../renderer_programs/tinted_texture.hpp | 26 +- .../engine/include/engine/graphics/shader.hpp | 38 +++ .../engine/graphics/shared_context.hpp | 4 +- .../include/engine/graphics/texture.hpp | 2 +- .../include/engine/graphics/vertex_layout.hpp | 13 +- modules/engine/include/engine/input/input.hpp | 73 +++++ .../engine/include/engine/input/key_codes.hpp | 182 ++++++++++++ .../include/engine/input/mouse_codes.hpp | 4 +- modules/engine/include/engine/layer/layer.hpp | 126 +++++++++ .../include/engine/layer/layer_stack.hpp | 72 +++++ .../engine/include/engine/math/random.hpp | 0 .../platform/graphics/directx/blender.hpp | 7 +- .../platform/graphics/directx/buffers.hpp | 26 +- .../graphics/directx/framebuffers.hpp | 21 +- .../graphics/directx/graphics_context.hpp | 13 +- .../graphics/directx/render_command.hpp | 16 +- .../platform/graphics/directx/shader.hpp | 20 +- .../graphics/directx/shared_context.hpp | 54 ++++ .../platform/graphics/directx/texture.hpp | 16 +- .../graphics/directx/user_interface.hpp | 10 +- .../graphics/directx/vertex_layout.hpp | 13 +- .../platform/graphics/opengl/blender.hpp | 6 +- .../platform/graphics/opengl/buffers.hpp | 14 +- .../platform/graphics/opengl/framebuffers.hpp | 31 ++ .../graphics/opengl/graphics_context.hpp | 10 +- .../graphics/opengl/render_command.hpp | 15 +- .../platform/graphics/opengl/shader.hpp | 6 +- .../graphics/opengl/shared_context.hpp | 12 + .../platform/graphics/opengl/texture.hpp | 4 +- .../graphics/opengl/user_interface.hpp | 11 +- .../graphics/opengl/vertex_layout.hpp | 11 +- .../engine/platform/os/linux/l_window.hpp | 23 +- .../engine/platform/os/windows/w_window.cpp | 244 ++++++++++++++++ .../engine/platform/os/windows/w_window.hpp | 23 +- .../include/engine/scene/components.hpp | 8 + .../engine/scene/components/camera.hpp | 29 ++ .../engine/scene/components/native_script.hpp | 28 ++ .../scene/components/scriptable_entity.hpp | 25 +- .../scene/components/sprite_renderer.hpp | 32 +++ .../include/engine/scene/components/tag.hpp | 28 ++ .../engine/scene/components/transform.hpp | 44 +++ .../include/engine/scene/components/uuid.hpp | 18 ++ .../engine/include/engine/scene/entity.hpp | 32 ++- modules/engine/include/engine/scene/scene.hpp | 49 ++++ modules/engine/include/engine/time/timer.hpp | 50 ++++ .../engine/user_interface/user_interface.hpp | 22 +- .../include/engine/utils/file_manager.hpp | 121 ++++++++ .../include/engine/utils/resource_manager.hpp | 75 +++++ .../include/engine/utils/serializer.hpp | 29 ++ .../include/engine/utils/stringifier.hpp | 4 +- modules/engine/src/camera/camera.cpp | 6 + modules/engine/src/camera/ortho.cpp | 49 ++++ .../engine/src/camera/scene.cpp | 34 ++- .../engine/src/core/application.cpp | 41 +-- .../engine/src/core/uuid.cpp | 10 +- .../engine/src/debug/exceptions.cpp | 30 +- .../engine/src/debug/instrumentor.cpp | 30 +- .../engine/src/debug/logger.cpp | 9 +- modules/engine/src/graphics/blender.cpp | 32 +++ modules/engine/src/graphics/buffers.cpp | 107 +++++++ modules/engine/src/graphics/framebuffer.cpp | 38 +++ .../engine/src/graphics/graphics_context.cpp | 81 ++++++ .../engine/src/graphics/render_command.cpp | 37 +++ .../engine/src/graphics/renderer.cpp | 127 ++++++--- .../src/graphics/renderer_programs/quad.cpp | 76 +++++ .../graphics/renderer_programs/texture.cpp | 78 +++++ .../renderer_programs/tinted_texture.cpp | 81 ++++++ modules/engine/src/graphics/shader.cpp | 41 +++ modules/engine/src/graphics/texture.cpp | 51 ++++ modules/engine/src/graphics/vertex_layout.cpp | 41 +++ .../engine/src/input/input.cpp | 58 ++-- modules/engine/src/layer/layer.cpp | 47 +++ .../engine/src/layer/layer_stack.cpp | 28 +- .../Engine => modules/engine/src}/ltpch.hpp | 4 +- .../engine/src/math/random.cpp | 5 +- .../src/platform/graphics/directx/blender.cpp | 25 +- .../src/platform/graphics/directx/buffers.cpp | 82 ++++-- .../graphics/directx/framebuffers.cpp | 107 +++++++ .../graphics/directx/graphics_context.cpp | 85 +++--- .../graphics/directx/render_command.cpp | 41 ++- .../src/platform/graphics/directx/shader.cpp | 81 ++++++ .../src/platform/graphics/directx/texture.cpp | 80 ++++++ .../graphics/directx/user_interface.cpp | 16 +- .../graphics/directx/vertex_layout.cpp | 30 +- .../src/platform/graphics/opengl/blender.cpp | 5 +- .../src/platform/graphics/opengl/buffers.cpp | 19 +- .../platform/graphics/opengl/framebuffers.cpp | 52 +++- .../graphics/opengl/graphics_context.cpp | 116 ++++++++ .../graphics/opengl/render_command.cpp | 15 +- .../src/platform/graphics/opengl/shader.cpp | 39 +-- .../src/platform/graphics/opengl/texture.cpp | 34 ++- .../graphics/opengl/user_interface.cpp | 15 +- .../graphics/opengl/vertex_layout.cpp | 33 ++- .../engine/src/platform/os/linux/l_window.cpp | 238 ++++++++++++++++ .../src/platform/os/windows/w_window.cpp | 244 ++++++++++++++++ modules/engine/src/scene/entity.cpp | 14 + .../engine/src/scene/scene.cpp | 62 ++-- modules/engine/src/time/timer.cpp | 20 ++ .../src/user_interface/user_interface.cpp | 235 +++++++++++++++ modules/engine/src/utils/file_manager.cpp | 110 ++++++++ modules/engine/src/utils/resource_manager.cpp | 87 ++++++ .../engine/src/utils/serializer.cpp | 121 +++++--- .../engine/src/utils/stringifier.cpp | 8 +- modules/mirror/CMakeLists.txt | 14 + .../mirror/include/mirror/editor_layer.hpp | 11 +- .../include/mirror/panel/asset_browser.hpp | 7 +- .../mirror/include/mirror/panel/panel.hpp | 0 .../include/mirror/panel/properties.hpp | 15 +- .../include/mirror/panel/scene_hierarchy.hpp | 10 +- .../mirror/src/editor_layer.cpp | 26 +- modules/mirror/src/mirror.cpp | 34 +++ .../mirror/src/panel/asset_browser.cpp | 76 +++-- modules/mirror/src/panel/properties.cpp | 267 ++++++++++++++++++ .../mirror/src/panel/scene_hierarchy.cpp | 32 ++- tools/cmake/macros.cmake | 30 ++ 238 files changed, 6021 insertions(+), 4699 deletions(-) create mode 100644 .clang-tidy delete mode 100644 Engine/.clang-format delete mode 100644 Engine/CMakeLists.txt delete mode 100644 Engine/src/Engine/Camera/Camera.cpp delete mode 100644 Engine/src/Engine/Camera/Camera.hpp delete mode 100644 Engine/src/Engine/Camera/OrthographicCamera.cpp delete mode 100644 Engine/src/Engine/Camera/OrthographicCamera.hpp delete mode 100644 Engine/src/Engine/Core/Application.hpp delete mode 100644 Engine/src/Engine/Core/UUID.hpp delete mode 100644 Engine/src/Engine/Core/Window.hpp delete mode 100644 Engine/src/Engine/Debug/Logger.hpp delete mode 100644 Engine/src/Engine/Events/Event.hpp delete mode 100644 Engine/src/Engine/Graphics/Blender.cpp delete mode 100644 Engine/src/Engine/Graphics/Buffers.cpp delete mode 100644 Engine/src/Engine/Graphics/Framebuffer.cpp delete mode 100644 Engine/src/Engine/Graphics/GraphicsContext.cpp delete mode 100644 Engine/src/Engine/Graphics/RenderCommand.cpp delete mode 100644 Engine/src/Engine/Graphics/RenderCommand.hpp delete mode 100644 Engine/src/Engine/Graphics/Renderer.hpp delete mode 100644 Engine/src/Engine/Graphics/RendererPrograms/QuadRendererProgram.cpp delete mode 100644 Engine/src/Engine/Graphics/RendererPrograms/TextureRendererProgram.cpp delete mode 100644 Engine/src/Engine/Graphics/RendererPrograms/TintedTextureRendererProgram.cpp delete mode 100644 Engine/src/Engine/Graphics/Shader.cpp delete mode 100644 Engine/src/Engine/Graphics/Shader.hpp delete mode 100644 Engine/src/Engine/Graphics/Texture.cpp delete mode 100644 Engine/src/Engine/Graphics/VertexLayout.cpp delete mode 100644 Engine/src/Engine/Input/Input.hpp delete mode 100644 Engine/src/Engine/Input/KeyCodes.hpp delete mode 100644 Engine/src/Engine/Layer/Layer.cpp delete mode 100644 Engine/src/Engine/Layer/Layer.hpp delete mode 100644 Engine/src/Engine/Layer/LayerStack.hpp delete mode 100644 Engine/src/Engine/LightEngine.hpp delete mode 100644 Engine/src/Engine/Scene/Components.hpp delete mode 100644 Engine/src/Engine/Scene/Components/CameraComponent.hpp delete mode 100644 Engine/src/Engine/Scene/Components/NativeScriptComponent.hpp delete mode 100644 Engine/src/Engine/Scene/Components/SpriteRendererComponent.hpp delete mode 100644 Engine/src/Engine/Scene/Components/TagComponent.hpp delete mode 100644 Engine/src/Engine/Scene/Components/TransformComponent.hpp delete mode 100644 Engine/src/Engine/Scene/Components/UUIDComponent.hpp delete mode 100644 Engine/src/Engine/Scene/Entity.cpp delete mode 100644 Engine/src/Engine/Scene/Scene.hpp delete mode 100644 Engine/src/Engine/Time/Timer.cpp delete mode 100644 Engine/src/Engine/Time/Timer.hpp delete mode 100644 Engine/src/Engine/UserInterface/UserInterface.cpp delete mode 100644 Engine/src/Engine/Utility/FileManager.cpp delete mode 100644 Engine/src/Engine/Utility/FileManager.hpp delete mode 100644 Engine/src/Engine/Utility/ResourceManager.cpp delete mode 100644 Engine/src/Engine/Utility/ResourceManager.hpp delete mode 100644 Engine/src/Engine/Utility/Serializer.hpp delete mode 100644 Engine/src/Engine/ltpch.cpp delete mode 100644 Engine/src/Platform/GraphicsAPI/DirectX/dxFramebuffer.cpp delete mode 100644 Engine/src/Platform/GraphicsAPI/DirectX/dxShader.cpp delete mode 100644 Engine/src/Platform/GraphicsAPI/DirectX/dxSharedContext.hpp delete mode 100644 Engine/src/Platform/GraphicsAPI/DirectX/dxTexture.cpp delete mode 100644 Engine/src/Platform/GraphicsAPI/OpenGL/glFramebuffer.hpp delete mode 100644 Engine/src/Platform/GraphicsAPI/OpenGL/glGraphicsContext.cpp delete mode 100644 Engine/src/Platform/GraphicsAPI/OpenGL/glSharedContext.hpp delete mode 100644 Engine/src/Platform/OS/Linux/lWindow.cpp delete mode 100644 Engine/src/Platform/OS/Windows/wWindow.cpp delete mode 100755 Engine/src/renameall.sh delete mode 100644 Mirror/.clang-format delete mode 100644 Mirror/CMakeLists.txt delete mode 100644 Mirror/src/MirrorApp.cpp delete mode 100644 Mirror/src/Panels/PropertiesPanel.cpp rename {Assets/Fonts/OpenSans => data/assets/fonts/open_sans}/LICENSE.txt (100%) rename {Assets/Fonts/OpenSans => data/assets/fonts/open_sans}/OpenSans-Bold.ttf (100%) rename {Assets/Fonts/OpenSans => data/assets/fonts/open_sans}/OpenSans-BoldItalic.ttf (100%) rename {Assets/Fonts/OpenSans => data/assets/fonts/open_sans}/OpenSans-ExtraBold.ttf (100%) rename {Assets/Fonts/OpenSans => data/assets/fonts/open_sans}/OpenSans-ExtraBoldItalic.ttf (100%) rename {Assets/Fonts/OpenSans => data/assets/fonts/open_sans}/OpenSans-Italic.ttf (100%) rename {Assets/Fonts/OpenSans => data/assets/fonts/open_sans}/OpenSans-Light.ttf (100%) rename {Assets/Fonts/OpenSans => data/assets/fonts/open_sans}/OpenSans-LightItalic.ttf (100%) rename {Assets/Fonts/OpenSans => data/assets/fonts/open_sans}/OpenSans-Regular.ttf (100%) rename {Assets/Fonts/OpenSans => data/assets/fonts/open_sans}/OpenSans-SemiBold.ttf (100%) rename {Assets/Fonts/OpenSans => data/assets/fonts/open_sans}/OpenSans-SemiBoldItalic.ttf (100%) rename {Assets/Scenes => data/assets/scenes}/demo.scene (100%) rename {Assets/Shaders/Quad => data/assets/shaders/quads}/Quad_PS.glsl (100%) rename {Assets/Shaders/Quad => data/assets/shaders/quads}/Quad_VS.glsl (100%) rename {Assets/Shaders/Texture => data/assets/shaders/texture}/Texture_PS.glsl (100%) rename {Assets/Shaders/Texture => data/assets/shaders/texture}/Texture_VS.glsl (100%) rename {Assets/Shaders/TintedTexture => data/assets/shaders/tinted_texture}/TintedTexture_PS.glsl (100%) rename {Assets/Shaders/TintedTexture => data/assets/shaders/tinted_texture}/TintedTexture_VS.glsl (100%) rename {Assets/Textures => data/assets/textures}/awesomeface.png (100%) rename {EngineResources/Icons => data/engine/icons}/Asset_Directory.png (100%) rename {EngineResources/Icons => data/engine/icons}/Asset_Image.png (100%) rename {EngineResources/Icons => data/engine/icons}/Asset_Scene.png (100%) rename {EngineResources/Icons => data/engine/icons}/Asset_Text.png (100%) rename {Dependencies => external}/CMakeLists.txt (73%) rename {Dependencies/Configurations => external/configurations}/imgui/imconfig.h (100%) rename {Dependencies => external}/imgui (100%) create mode 100644 modules/CMakeLists.txt create mode 100644 modules/engine/CMakeLists.txt rename Engine/src/Engine/Base/Base.hpp => modules/engine/include/engine/base/base.hpp (70%) rename Engine/src/Engine/Base/Config.hpp => modules/engine/include/engine/base/config.hpp (100%) rename Engine/src/Engine/Base/EntryPoint.hpp => modules/engine/include/engine/base/entrypoint.hpp (75%) rename Engine/src/Engine/Base/Portables/DebugTrap.hpp => modules/engine/include/engine/base/portables/debug_trap.hpp (67%) create mode 100644 modules/engine/include/engine/camera/camera.hpp create mode 100644 modules/engine/include/engine/camera/ortho.hpp rename Engine/src/Engine/Camera/SceneCamera.hpp => modules/engine/include/engine/camera/scene.hpp (55%) create mode 100644 modules/engine/include/engine/core/application.hpp create mode 100644 modules/engine/include/engine/core/uuid.hpp create mode 100644 modules/engine/include/engine/core/window.hpp rename Engine/src/Engine/Debug/Exceptions.hpp => modules/engine/include/engine/debug/exceptions.hpp (100%) rename Engine/src/Engine/Debug/Instrumentor.hpp => modules/engine/include/engine/debug/instrumentor.hpp (69%) create mode 100644 modules/engine/include/engine/debug/logger.hpp create mode 100644 modules/engine/include/engine/engine.hpp rename Engine/src/Engine/Events/CharEvent.hpp => modules/engine/include/engine/events/char.hpp (63%) create mode 100644 modules/engine/include/engine/events/event.hpp rename Engine/src/Engine/Events/KeyboardEvents.hpp => modules/engine/include/engine/events/keyboard.hpp (73%) rename Engine/src/Engine/Events/MouseEvents.hpp => modules/engine/include/engine/events/mouse.hpp (67%) rename Engine/src/Engine/Events/WindowEvents.hpp => modules/engine/include/engine/events/window.hpp (79%) rename Engine/src/Engine/Graphics/Blender.hpp => modules/engine/include/engine/graphics/blender.hpp (95%) rename Engine/src/Engine/Graphics/Buffers.hpp => modules/engine/include/engine/graphics/buffers.hpp (95%) rename Engine/src/Engine/Graphics/Framebuffer.hpp => modules/engine/include/engine/graphics/framebuffer.hpp (91%) rename Engine/src/Engine/Graphics/GraphicsContext.hpp => modules/engine/include/engine/graphics/graphics_context.hpp (95%) create mode 100644 modules/engine/include/engine/graphics/render_command.hpp create mode 100644 modules/engine/include/engine/graphics/renderer.hpp rename Engine/src/Engine/Graphics/RendererPrograms/QuadRendererProgram.hpp => modules/engine/include/engine/graphics/renderer_programs/quad.hpp (58%) rename Engine/src/Engine/Graphics/RendererPrograms/RendererProgram.hpp => modules/engine/include/engine/graphics/renderer_programs/renderer_program.hpp (76%) rename Engine/src/Engine/Graphics/RendererPrograms/TextureRendererProgram.hpp => modules/engine/include/engine/graphics/renderer_programs/texture.hpp (61%) rename Engine/src/Engine/Graphics/RendererPrograms/TintedTextureRendererProgram.hpp => modules/engine/include/engine/graphics/renderer_programs/tinted_texture.hpp (61%) create mode 100644 modules/engine/include/engine/graphics/shader.hpp rename Engine/src/Engine/Graphics/SharedContext.hpp => modules/engine/include/engine/graphics/shared_context.hpp (66%) rename Engine/src/Engine/Graphics/Texture.hpp => modules/engine/include/engine/graphics/texture.hpp (95%) rename Engine/src/Engine/Graphics/VertexLayout.hpp => modules/engine/include/engine/graphics/vertex_layout.hpp (58%) create mode 100644 modules/engine/include/engine/input/input.hpp create mode 100644 modules/engine/include/engine/input/key_codes.hpp rename Engine/src/Engine/Input/MouseCodes.hpp => modules/engine/include/engine/input/mouse_codes.hpp (86%) create mode 100644 modules/engine/include/engine/layer/layer.hpp create mode 100644 modules/engine/include/engine/layer/layer_stack.hpp rename Engine/src/Engine/Math/Random.hpp => modules/engine/include/engine/math/random.hpp (100%) rename Engine/src/Platform/GraphicsAPI/DirectX/dxBlender.hpp => modules/engine/include/engine/platform/graphics/directx/blender.hpp (83%) rename Engine/src/Platform/GraphicsAPI/DirectX/dxBuffers.hpp => modules/engine/include/engine/platform/graphics/directx/buffers.hpp (69%) rename Engine/src/Platform/GraphicsAPI/DirectX/dxFramebuffer.hpp => modules/engine/include/engine/platform/graphics/directx/framebuffers.hpp (59%) rename Engine/src/Platform/GraphicsAPI/DirectX/dxGraphicsContext.hpp => modules/engine/include/engine/platform/graphics/directx/graphics_context.hpp (58%) rename Engine/src/Platform/GraphicsAPI/DirectX/dxRenderCommand.hpp => modules/engine/include/engine/platform/graphics/directx/render_command.hpp (63%) rename Engine/src/Platform/GraphicsAPI/DirectX/dxShader.hpp => modules/engine/include/engine/platform/graphics/directx/shader.hpp (54%) create mode 100644 modules/engine/include/engine/platform/graphics/directx/shared_context.hpp rename Engine/src/Platform/GraphicsAPI/DirectX/dxTexture.hpp => modules/engine/include/engine/platform/graphics/directx/texture.hpp (58%) rename Engine/src/Platform/GraphicsAPI/DirectX/dxUserInterface.hpp => modules/engine/include/engine/platform/graphics/directx/user_interface.hpp (59%) rename Engine/src/Platform/GraphicsAPI/DirectX/dxVertexLayout.hpp => modules/engine/include/engine/platform/graphics/directx/vertex_layout.hpp (60%) rename Engine/src/Platform/GraphicsAPI/OpenGL/glBlender.hpp => modules/engine/include/engine/platform/graphics/opengl/blender.hpp (73%) rename Engine/src/Platform/GraphicsAPI/OpenGL/glBuffers.hpp => modules/engine/include/engine/platform/graphics/opengl/buffers.hpp (74%) create mode 100644 modules/engine/include/engine/platform/graphics/opengl/framebuffers.hpp rename Engine/src/Platform/GraphicsAPI/OpenGL/glGraphicsContext.hpp => modules/engine/include/engine/platform/graphics/opengl/graphics_context.hpp (53%) rename Engine/src/Platform/GraphicsAPI/OpenGL/glRenderCommand.hpp => modules/engine/include/engine/platform/graphics/opengl/render_command.hpp (56%) rename Engine/src/Platform/GraphicsAPI/OpenGL/glShader.hpp => modules/engine/include/engine/platform/graphics/opengl/shader.hpp (79%) create mode 100644 modules/engine/include/engine/platform/graphics/opengl/shared_context.hpp rename Engine/src/Platform/GraphicsAPI/OpenGL/glTexture.hpp => modules/engine/include/engine/platform/graphics/opengl/texture.hpp (83%) rename Engine/src/Platform/GraphicsAPI/OpenGL/glUserInterface.hpp => modules/engine/include/engine/platform/graphics/opengl/user_interface.hpp (51%) rename Engine/src/Platform/GraphicsAPI/OpenGL/glVertexLayout.hpp => modules/engine/include/engine/platform/graphics/opengl/vertex_layout.hpp (65%) rename Engine/src/Platform/OS/Linux/lWindow.hpp => modules/engine/include/engine/platform/os/linux/l_window.hpp (51%) create mode 100644 modules/engine/include/engine/platform/os/windows/w_window.cpp rename Engine/src/Platform/OS/Windows/wWindow.hpp => modules/engine/include/engine/platform/os/windows/w_window.hpp (51%) create mode 100644 modules/engine/include/engine/scene/components.hpp create mode 100644 modules/engine/include/engine/scene/components/camera.hpp create mode 100644 modules/engine/include/engine/scene/components/native_script.hpp rename Engine/src/Engine/Scene/Components/ScriptableEntity.hpp => modules/engine/include/engine/scene/components/scriptable_entity.hpp (51%) create mode 100644 modules/engine/include/engine/scene/components/sprite_renderer.hpp create mode 100644 modules/engine/include/engine/scene/components/tag.hpp create mode 100644 modules/engine/include/engine/scene/components/transform.hpp create mode 100644 modules/engine/include/engine/scene/components/uuid.hpp rename Engine/src/Engine/Scene/Entity.hpp => modules/engine/include/engine/scene/entity.hpp (52%) create mode 100644 modules/engine/include/engine/scene/scene.hpp create mode 100644 modules/engine/include/engine/time/timer.hpp rename Engine/src/Engine/UserInterface/UserInterface.hpp => modules/engine/include/engine/user_interface/user_interface.hpp (53%) create mode 100644 modules/engine/include/engine/utils/file_manager.hpp create mode 100644 modules/engine/include/engine/utils/resource_manager.hpp create mode 100644 modules/engine/include/engine/utils/serializer.hpp rename Engine/src/Engine/Utility/Stringifier.hpp => modules/engine/include/engine/utils/stringifier.hpp (92%) create mode 100644 modules/engine/src/camera/camera.cpp create mode 100644 modules/engine/src/camera/ortho.cpp rename Engine/src/Engine/Camera/SceneCamera.cpp => modules/engine/src/camera/scene.cpp (58%) rename Engine/src/Engine/Core/Application.cpp => modules/engine/src/core/application.cpp (77%) rename Engine/src/Engine/Core/UUID.cpp => modules/engine/src/core/uuid.cpp (50%) rename Engine/src/Engine/Debug/Exceptions.cpp => modules/engine/src/debug/exceptions.cpp (69%) rename Engine/src/Engine/Debug/Instrumentor.cpp => modules/engine/src/debug/instrumentor.cpp (64%) rename Engine/src/Engine/Debug/Logger.cpp => modules/engine/src/debug/logger.cpp (89%) create mode 100644 modules/engine/src/graphics/blender.cpp create mode 100644 modules/engine/src/graphics/buffers.cpp create mode 100644 modules/engine/src/graphics/framebuffer.cpp create mode 100644 modules/engine/src/graphics/graphics_context.cpp create mode 100644 modules/engine/src/graphics/render_command.cpp rename Engine/src/Engine/Graphics/Renderer.cpp => modules/engine/src/graphics/renderer.cpp (63%) create mode 100644 modules/engine/src/graphics/renderer_programs/quad.cpp create mode 100644 modules/engine/src/graphics/renderer_programs/texture.cpp create mode 100644 modules/engine/src/graphics/renderer_programs/tinted_texture.cpp create mode 100644 modules/engine/src/graphics/shader.cpp create mode 100644 modules/engine/src/graphics/texture.cpp create mode 100644 modules/engine/src/graphics/vertex_layout.cpp rename Engine/src/Engine/Input/Input.cpp => modules/engine/src/input/input.cpp (60%) create mode 100644 modules/engine/src/layer/layer.cpp rename Engine/src/Engine/Layer/LayerStack.cpp => modules/engine/src/layer/layer_stack.cpp (57%) rename {Engine/src/Engine => modules/engine/src}/ltpch.hpp (93%) rename Engine/src/Engine/Math/Random.cpp => modules/engine/src/math/random.cpp (93%) rename Engine/src/Platform/GraphicsAPI/DirectX/dxBlender.cpp => modules/engine/src/platform/graphics/directx/blender.cpp (80%) rename Engine/src/Platform/GraphicsAPI/DirectX/dxBuffers.cpp => modules/engine/src/platform/graphics/directx/buffers.cpp (63%) create mode 100644 modules/engine/src/platform/graphics/directx/framebuffers.cpp rename Engine/src/Platform/GraphicsAPI/DirectX/dxGraphicsContext.cpp => modules/engine/src/platform/graphics/directx/graphics_context.cpp (60%) rename Engine/src/Platform/GraphicsAPI/DirectX/dxRenderCommand.cpp => modules/engine/src/platform/graphics/directx/render_command.cpp (61%) create mode 100644 modules/engine/src/platform/graphics/directx/shader.cpp create mode 100644 modules/engine/src/platform/graphics/directx/texture.cpp rename Engine/src/Platform/GraphicsAPI/DirectX/dxUserInterface.cpp => modules/engine/src/platform/graphics/directx/user_interface.cpp (79%) rename Engine/src/Platform/GraphicsAPI/DirectX/dxVertexLayout.cpp => modules/engine/src/platform/graphics/directx/vertex_layout.cpp (77%) rename Engine/src/Platform/GraphicsAPI/OpenGL/glBlender.cpp => modules/engine/src/platform/graphics/opengl/blender.cpp (94%) rename Engine/src/Platform/GraphicsAPI/OpenGL/glBuffers.cpp => modules/engine/src/platform/graphics/opengl/buffers.cpp (86%) rename Engine/src/Platform/GraphicsAPI/OpenGL/glFramebuffer.cpp => modules/engine/src/platform/graphics/opengl/framebuffers.cpp (58%) create mode 100644 modules/engine/src/platform/graphics/opengl/graphics_context.cpp rename Engine/src/Platform/GraphicsAPI/OpenGL/glRenderCommand.cpp => modules/engine/src/platform/graphics/opengl/render_command.cpp (67%) rename Engine/src/Platform/GraphicsAPI/OpenGL/glShader.cpp => modules/engine/src/platform/graphics/opengl/shader.cpp (68%) rename Engine/src/Platform/GraphicsAPI/OpenGL/glTexture.cpp => modules/engine/src/platform/graphics/opengl/texture.cpp (69%) rename Engine/src/Platform/GraphicsAPI/OpenGL/glUserInterface.cpp => modules/engine/src/platform/graphics/opengl/user_interface.cpp (81%) rename Engine/src/Platform/GraphicsAPI/OpenGL/glVertexLayout.cpp => modules/engine/src/platform/graphics/opengl/vertex_layout.cpp (78%) create mode 100644 modules/engine/src/platform/os/linux/l_window.cpp create mode 100644 modules/engine/src/platform/os/windows/w_window.cpp create mode 100644 modules/engine/src/scene/entity.cpp rename Engine/src/Engine/Scene/Scene.cpp => modules/engine/src/scene/scene.cpp (55%) create mode 100644 modules/engine/src/time/timer.cpp create mode 100644 modules/engine/src/user_interface/user_interface.cpp create mode 100644 modules/engine/src/utils/file_manager.cpp create mode 100644 modules/engine/src/utils/resource_manager.cpp rename Engine/src/Engine/Utility/Serializer.cpp => modules/engine/src/utils/serializer.cpp (56%) rename Engine/src/Engine/Utility/Stringifier.cpp => modules/engine/src/utils/stringifier.cpp (96%) create mode 100644 modules/mirror/CMakeLists.txt rename Mirror/src/EditorLayer.hpp => modules/mirror/include/mirror/editor_layer.hpp (75%) rename Mirror/src/Panels/AssetBrowser.hpp => modules/mirror/include/mirror/panel/asset_browser.hpp (86%) rename Mirror/src/Panels/Panel.hpp => modules/mirror/include/mirror/panel/panel.hpp (100%) rename Mirror/src/Panels/PropertiesPanel.hpp => modules/mirror/include/mirror/panel/properties.hpp (51%) rename Mirror/src/Panels/SceneHierarchyPanel.hpp => modules/mirror/include/mirror/panel/scene_hierarchy.hpp (71%) rename Mirror/src/EditorLayer.cpp => modules/mirror/src/editor_layer.cpp (79%) create mode 100644 modules/mirror/src/mirror.cpp rename Mirror/src/Panels/AssetBrowser.cpp => modules/mirror/src/panel/asset_browser.cpp (51%) create mode 100644 modules/mirror/src/panel/properties.cpp rename Mirror/src/Panels/SceneHierarchyPanel.cpp => modules/mirror/src/panel/scene_hierarchy.cpp (51%) create mode 100644 tools/cmake/macros.cmake diff --git a/.clang-format b/.clang-format index 5e7c904..adcd74a 100644 --- a/.clang-format +++ b/.clang-format @@ -1,28 +1,23 @@ --- # Core Language: Cpp -Standard: Cpp11 -ColumnLimit: '0' # No limit +Standard: Latest +ColumnLimit: '100' -### Bin pack ### -BinPackArguments: 'true' -BinPackParameters: 'true' +# Bin pack +BinPackArguments: 'false' +BinPackParameters: 'false' # Includes SortIncludes: 'true' IncludeBlocks: Regroup IncludeCategories: - # Current Project - - Regex: '"' - Priority: 001 - - # Custom Project Categories... - # Dependecies + # Normal includes - Regex: '<' Priority: 500 - # Custom Deependencies Categories... + # Custom include categories... # C++ includes - Regex: '[^.h .hpp]>' @@ -82,20 +77,20 @@ SpacesInContainerLiterals: 'false' SpacesInParentheses: 'false' SpacesInSquareBrackets: 'false' -### Alignment ### -PointerAlignment: Left +# Alignment +PointerAlignment: Right DerivePointerAlignment: 'false' -AlignAfterOpenBracket: Align AlignEscapedNewlines: Left +AlignAfterOpenBracket: BlockIndent AlignConsecutiveDeclarations: 'false' -AlignConsecutiveAssignments: 'true' +AlignConsecutiveAssignments: 'false' AlignConsecutiveMacros: 'true' AlignOperands: 'true' AlignTrailingComments: 'true' -### Single Line ### +# Single Line AllowShortCaseLabelsOnASingleLine: 'true' -AllowShortFunctionsOnASingleLine: Inline +AllowShortFunctionsOnASingleLine: 'false' AllowShortLambdasOnASingleLine: Inline AllowAllArgumentsOnNextLine: 'false' AllowShortLoopsOnASingleLine: 'false' @@ -103,33 +98,32 @@ AllowShortBlocksOnASingleLine: 'false' AllowAllParametersOfDeclarationOnNextLine: 'false' AllowShortIfStatementsOnASingleLine: Never -### Break ### +# Break AlwaysBreakAfterReturnType: None AlwaysBreakBeforeMultilineStrings: 'false' AlwaysBreakTemplateDeclarations: 'Yes' -BreakBeforeBinaryOperators: None +BreakBeforeBinaryOperators: All BreakBeforeTernaryOperators: 'false' BreakInheritanceList: BeforeComma -BreakStringLiterals: 'false' +BreakStringLiterals: 'true' # Penalties -PenaltyBreakAssignment: '0' +PenaltyBreakAssignment: '99999' PenaltyBreakBeforeFirstCallParameter: '0' PenaltyBreakComment: '0' PenaltyBreakFirstLessLess: '0' PenaltyBreakString: '0' PenaltyBreakTemplateDeclaration: '0' -PenaltyExcessCharacter: '0' +PenaltyExcessCharacter: '999999999' PenaltyReturnTypeOnItsOwnLine: '999999999' # Nope # Constructor Initializers ConstructorInitializerAllOnOneLineOrOnePerLine: 'true' -AllowAllConstructorInitializersOnNextLine: 'true' +AllowAllConstructorInitializersOnNextLine: 'false' BreakConstructorInitializers: BeforeComma # Comments -ReflowComments: 'false' -CommentPragmas: '^ TODO@:' +ReflowComments: 'true' FixNamespaceComments: 'true' # Misc @@ -137,3 +131,5 @@ Cpp11BracedListStyle: 'false' SortUsingDeclarations: 'true' KeepEmptyLinesAtTheStartOfBlocks: 'false' MaxEmptyLinesToKeep: '2' + +ExperimentalAutoDetectBinPacking: false diff --git a/.clang-tidy b/.clang-tidy new file mode 100644 index 0000000..f98867d --- /dev/null +++ b/.clang-tidy @@ -0,0 +1,250 @@ +--- +Checks: "-*, + +performance-unnecessary-value-param, +performance-unnecessary-copy-initialization, +performance-type-promotion-in-math-fn, +performance-trivially-destructible, +performance-noexcept-swap, +performance-noexcept-move-constructor, +performance-noexcept-destructor, +performance-no-int-to-ptr, +performance-no-automatic-move, +performance-move-constructor-init, +performance-move-const-arg, +performance-inefficient-vector-operation, +performance-inefficient-string-concatenation, +performance-inefficient-algorithm, +performance-implicit-conversion-in-loop, +performance-for-range-copy, +performance-faster-string-find, +performance-enum-size, +performance-avoid-endl, + +readability-avoid-const-params-in-decls, +readability-avoid-nested-conditional-operator, +readability-avoid-return-with-void-value, +readability-avoid-unconditional-preprocessor-if, +readability-braces-around-statements, +readability-const-return-type, +readability-container-contains, +readability-container-data-pointdr, +readability-container-size-empty, +readability-delete-null-pointer, +readability-duplicate-include, +readability-else-after-return, +readability-inconsistent-declaration-parameter-name, +readability-isolate-declaration, +readability-make-member-function-const, +readability-misleading-indentation, +readability-misplaced-array-index, +readability-named-parameter, +readability-non-const-parameter, +readability-qualified-auto, +readability-redundant-access-specifiers, +readability-redundant-casting, +readability-redundant-control-flow, +readability-redundant-declaration, +readability-redundant-function-ptr-dereference, +readability-redundant-inline-specifier, +readability-redundant-member-init, +readability-redundant-preprocessor, +readability-redundant-smartptr-get, +readability-redundant-string-cstr, +readability-reference-to-constructed-temporary, +readability-simplify-boolean-expr, +readability-simplify-subscript-expr, +readability-static-accessed-through-instance, +readability-static-definition-in-anonymous-namespace, +readability-string-compare, +readability-suspicious-call-argument, +readability-uniqueptr-delete-release, +readability-use-anyofallof +readability-use-std-min-max, +readability-function-cognitive-complexity +readability-function-size +readability-identifier-naming +readability-identifier-length +readability-magic-numbers + +modernize-avoid-bind, +modernize-avoid-c-arrays, +modernize-concat-nested-namespaces, +modernize-deprecated-headers, +modernize-deprecated-ios-base-aliases, +modernize-loop-convert, +modernize-macro-to-enum, +modernize-make-shared, +modernize-make-unique, +modernize-pass-by-value, +modernize-raw-string-literal, +modernize-redundant-void-arg, +modernize-replace-auto-ptr, +modernize-replace-disallow-copy-and-assign-macro, +modernize-replace-random-shuffle, +modernize-return-braced-init-list, +modernize-shrink-to-fit, +modernize-type-traits, +modernize-unary-static-assert, +modernize-use-auto, +modernize-use-bool-literals, +modernize-use-constraints, +modernize-use-default-member-init, +modernize-use-designated-initializers, +modernize-use-emplace, +modernize-use-equals-default, +modernize-use-equals-delete, +modernize-use-nodiscard, +modernize-use-noexcept, +modernize-use-nullptr, +modernize-use-override, +modernize-use-starts-ends-with, +modernize-use-std-numbers, +modernize-use-std-print, +modernize-use-transparent-functors, +modernize-use-uncaught-exceptions, +modernize-use-using +modernize-min-max-use-initializer-list, + +cppcoreguidelines-avoid-capturing-lambda-coroutines, +cppcoreguidelines-avoid-const-or-ref-data-members, +cppcoreguidelines-avoid-do-while, +cppcoreguidelines-avoid-goto, +cppcoreguidelines-avoid-non-const-global-variables, +cppcoreguidelines-avoid-reference-coroutine-parameters, +cppcoreguidelines-init-variables, +cppcoreguidelines-interfaces-global-init, +cppcoreguidelines-macro-usage, +cppcoreguidelines-misleading-capture-default-by-value, +cppcoreguidelines-missing-std-forward, +cppcoreguidelines-narrowing-conversions, +cppcoreguidelines-no-malloc, +cppcoreguidelines-no-suspend-with-lock, +cppcoreguidelines-owning-memory, +cppcoreguidelines-prefer-member-initializer, +cppcoreguidelines-pro-bounds-array-to-pointer-decay, +cppcoreguidelines-pro-bounds-pointer-arithmetic, +cppcoreguidelines-pro-type-const-cast, +cppcoreguidelines-pro-type-cstyle-cast, +cppcoreguidelines-pro-type-member-init, +cppcoreguidelines-pro-type-reinterpret-cast, +cppcoreguidelines-pro-type-static-cast-downcast, +cppcoreguidelines-pro-type-union-access, +cppcoreguidelines-pro-type-vararg, +cppcoreguidelines-rvalue-reference-param-not-moved, +cppcoreguidelines-slicing, +cppcoreguidelines-special-member-functions, +cppcoreguidelines-virtual-class-destructor, + +bugprone-argument-comment, +bugprone-assert-side-effect, +bugprone-assignment-in-if-condition, +bugprone-bad-signal-to-kill-thread, +bugprone-bool-pointer-implicit-conversion, +bugprone-branch-clone, +bugprone-casting-through-void, +bugprone-chained-comparison, +bugprone-compare-pointer-to-member-virtual-function, +bugprone-copy-constructor-init, +bugprone-crtp-constructor-accessibility, +bugprone-dangling-handle, +bugprone-empty-catch, +bugprone-exception-escape, +bugprone-fold-init-type, +bugprone-forward-declaration-namespace, +bugprone-forwarding-reference-overload, +bugprone-implicit-widening-of-multiplication-result, +bugprone-inaccurate-erase, +bugprone-inc-dec-in-conditions, +bugprone-incorrect-enable-if, +bugprone-incorrect-roundings, +bugprone-infinite-loop, +bugprone-integer-division, +bugprone-lambda-function-name, +bugprone-macro-parentheses, +bugprone-macro-repeated-side-effects, +bugprone-misplaced-operator-in-strlen-in-alloc, +bugprone-misplaced-pointer-arithmetic-in-alloc, +bugprone-misplaced-widening-cast, +bugprone-move-forwarding-reference, +bugprone-multi-level-implicit-pointer-conversion, +bugprone-multiple-new-in-one-expression, +bugprone-multiple-statement-macro, +bugprone-no-escape, +bugprone-non-zero-enum-to-bool-conversion, +bugprone-not-null-terminated-result, +bugprone-optional-value-conversion, +bugprone-parent-virtual-call, +bugprone-posix-return, +bugprone-redundant-branch-condition, +bugprone-reserved-identifier, +bugprone-return-const-ref-from-parameter, +bugprone-shared-ptr-array-mismatch, +bugprone-signal-handler, +bugprone-signed-char-misuse, +bugprone-sizeof-container, +bugprone-sizeof-expression, +bugprone-spuriously-wake-up-functions, +bugprone-standalone-empty, +bugprone-string-constructor, +bugprone-string-integer-assignment, +bugprone-string-literal-with-embedded-nul, +bugprone-stringview-nullptr, +bugprone-suspicious-enum-usage, +bugprone-suspicious-include, +bugprone-suspicious-memory-comparison, +bugprone-suspicious-memset-usage, +bugprone-suspicious-missing-comma, +bugprone-suspicious-realloc-usage, +bugprone-suspicious-semicolon, +bugprone-suspicious-string-compare, +bugprone-suspicious-stringview-data-usage, +bugprone-swapped-arguments, +bugprone-switch-missing-default-case, +bugprone-terminating-continue, +bugprone-throw-keyword-missing, +bugprone-too-small-loop-variable, +bugprone-unchecked-optional-access, +bugprone-undefined-memory-manipulation, +bugprone-undelegated-constructor, +bugprone-unhandled-exception-at-new, +bugprone-unhandled-self-assignment, +bugprone-unique-ptr-array-mismatch, +bugprone-unsafe-functions, +bugprone-unused-local-non-trivial-variable, +bugprone-unused-raii, +bugprone-unused-return-value, +bugprone-use-after-move, +bugprone-virtual-near-miss, + +concurrency-mt-unsafe, +concurrency-thread-canceltype-asynchronous, + +misc-use-anonymous-namespace, +misc-unused-using-decls, +misc-unused-parameters, +misc-unused-alias-decls, +misc-uniqueptr-reset-release, +misc-unconventional-assign-operator, +misc-throw-by-value-catch-by-reference, +misc-static-assert, +misc-redundant-expression, +misc-non-private-member-variables-in-classes, +misc-non-copyable-objects, +misc-no-recursion, +misc-new-delete-overloads, +misc-misplaced-const, +misc-misleading-identifier, +misc-misleading-bidirectional, +misc-header-include-cycle, +misc-definitions-in-headers, +misc-coroutine-hostile-raii, +misc-const-correctness, +misc-confusable-identifiers, + +hicpp-signed-bitwise, +hicpp-no-assembler, +hicpp-multiway-paths-covered, +hicpp-ignored-remove-result, +hicpp-exception-baseclass, +" diff --git a/.gitmodules b/.gitmodules index f6b2cc4..3d9f11c 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,25 +1,4 @@ -[submodule "Dependencies/spdlog"] - path = Dependencies/spdlog - url = https://github.com/gabime/spdlog -[submodule "Dependencies/GLFW"] - path = Dependencies/GLFW - url = https://github.com/glfw/glfw -[submodule "Dependencies/glm"] - path = Dependencies/glm - url = https://github.com/g-truc/glm -[submodule "Dependencies/imgui"] - path = Dependencies/imgui +[submodule "external/imgui"] + path = external/imgui url = https://github.com/ocornut/imgui branch = docking -[submodule "Dependencies/entt"] - path = Dependencies/entt - url = https://github.com/skypjack/entt -[submodule "Dependencies/yaml-cpp"] - path = Dependencies/yaml-cpp - url = https://github.com/jbeder/yaml-cpp -[submodule "Dependencies/shaderc"] - path = Dependencies/shaderc - url = https://github.com/google/shaderc -[submodule "Dependencies/spirv-cross"] - path = Dependencies/spirv-cross - url = https://github.com/KhronosGroup/SPIRV-Cross diff --git a/CMakeLists.txt b/CMakeLists.txt index 94d3055..d54f377 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,23 +1,8 @@ cmake_minimum_required(VERSION 4.0) - - project(Light) -set(CMAKE_CXX_STANDARD 20) +set(CMAKE_CXX_STANDARD 23) -# directories -set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib) -set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib) -set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin) - -set(CMAKE_EXPORT_COMPILE_COMMANDS True) - -set(MIRROR_DIR ${CMAKE_CURRENT_SOURCE_DIR}/Mirror/) -set(ENGINE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/Engine/) -set(DEPENDENCIES_DIR ${CMAKE_CURRENT_SOURCE_DIR}/Dependencies/) - -if(NOT MSV) - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-error") -endif() +include(${CMAKE_CURRENT_SOURCE_DIR}/tools/cmake/macros.cmake) if(WIN32) add_compile_definitions(LIGHT_PLATFORM_WINDOWS) @@ -25,11 +10,6 @@ elseif(UNIX) add_compile_definitions(LIGHT_PLATFORM_LINUX) endif() -# Projects -add_subdirectory(${ENGINE_DIR}/) -add_subdirectory(${MIRROR_DIR}/) - -# Dependencies find_package(glfw3 REQUIRED) find_package(glm REQUIRED) find_package(spdlog REQUIRED) @@ -38,44 +18,5 @@ find_package(yaml-cpp REQUIRED) find_package(EnTT REQUIRED) find_package(opengl_system REQUIRED) -add_subdirectory(${DEPENDENCIES_DIR}) -add_subdirectory(external/glad/) - -# Link -target_link_libraries( - imgui - PUBLIC glad - PUBLIC opengl::opengl - PUBLIC glm::glm - PUBLIC glfw -) - -target_link_libraries( - Engine - PUBLIC glad - PUBLIC opengl::opengl - PUBLIC glfw - PUBLIC spdlog::spdlog - PUBLIC imgui - PUBLIC stb::stb - PUBLIC yaml-cpp::yaml-cpp - PUBLIC EnTT::EnTT -) - -target_link_libraries( - Mirror - PRIVATE Engine - PRIVATE opengl::opengl - PRIVATE imgui -) - -# Precompiled headers -target_precompile_headers(Engine PUBLIC ${ENGINE_DIR}src/Engine/ltpch.hpp) - -if(MSVC) - set_property(DIRECTORY ${CMAE_CURRENT_SOURCE_DIR} PROPERTY VS_STARTUP_PROJECT Mirror) -endif() - - -set(CMAKE_BUILD_TYPE debug) -set(CMAKE_EXPORT_COMPILE_COMMANDS_ON) +add_subdirectory(./modules) +add_subdirectory(./external) diff --git a/Engine/.clang-format b/Engine/.clang-format deleted file mode 100644 index 5e7c904..0000000 --- a/Engine/.clang-format +++ /dev/null @@ -1,139 +0,0 @@ ---- -# Core -Language: Cpp -Standard: Cpp11 -ColumnLimit: '0' # No limit - -### Bin pack ### -BinPackArguments: 'true' -BinPackParameters: 'true' - -# Includes -SortIncludes: 'true' -IncludeBlocks: Regroup -IncludeCategories: - # Current Project - - Regex: '"' - Priority: 001 - - # Custom Project Categories... - - # Dependecies - - Regex: '<' - Priority: 500 - - # Custom Deependencies Categories... - - # C++ includes - - Regex: '[^.h .hpp]>' - Priority: 998 - - # C includes - - Regex: '<[^/\n]+[.]h>' - Priority: 999 - -# Braces -BreakBeforeBraces: Custom -BraceWrapping: - AfterCaseLabel: true - AfterClass: true - AfterControlStatement: true - AfterEnum: true - AfterFunction: true - AfterNamespace: false - AfterObjCDeclaration: true - AfterStruct: true - AfterUnion: true - AfterExternBlock: true - BeforeCatch: true - BeforeElse: true - IndentBraces: false - SplitEmptyFunction: true - SplitEmptyRecord: true - SplitEmptyNamespace: true - -# Indentation -UseTab: ForIndentation -TabWidth: '4' -IndentWidth: '4' -ContinuationIndentWidth: '4' -ConstructorInitializerIndentWidth: '4' -IndentCaseLabels: 'false' -IndentWrappedFunctionNames: 'true' -IndentPPDirectives: BeforeHash -NamespaceIndentation: None -AccessModifierOffset: '-4' - -# Space -SpaceAfterCStyleCast: 'false' -SpaceAfterLogicalNot: 'false' -SpaceAfterTemplateKeyword: 'false' -SpaceBeforeAssignmentOperators: 'true' -SpaceBeforeCpp11BracedList: 'true' -SpaceBeforeCtorInitializerColon: 'false' -SpaceBeforeInheritanceColon: 'false' -SpaceBeforeParens: ControlStatements -SpaceBeforeRangeBasedForLoopColon: 'true' -SpaceInEmptyParentheses: 'false' -SpacesBeforeTrailingComments: '1' -SpacesInAngles: 'false' -SpacesInCStyleCastParentheses: 'false' -SpacesInContainerLiterals: 'false' -SpacesInParentheses: 'false' -SpacesInSquareBrackets: 'false' - -### Alignment ### -PointerAlignment: Left -DerivePointerAlignment: 'false' -AlignAfterOpenBracket: Align -AlignEscapedNewlines: Left -AlignConsecutiveDeclarations: 'false' -AlignConsecutiveAssignments: 'true' -AlignConsecutiveMacros: 'true' -AlignOperands: 'true' -AlignTrailingComments: 'true' - -### Single Line ### -AllowShortCaseLabelsOnASingleLine: 'true' -AllowShortFunctionsOnASingleLine: Inline -AllowShortLambdasOnASingleLine: Inline -AllowAllArgumentsOnNextLine: 'false' -AllowShortLoopsOnASingleLine: 'false' -AllowShortBlocksOnASingleLine: 'false' -AllowAllParametersOfDeclarationOnNextLine: 'false' -AllowShortIfStatementsOnASingleLine: Never - -### Break ### -AlwaysBreakAfterReturnType: None -AlwaysBreakBeforeMultilineStrings: 'false' -AlwaysBreakTemplateDeclarations: 'Yes' -BreakBeforeBinaryOperators: None -BreakBeforeTernaryOperators: 'false' -BreakInheritanceList: BeforeComma -BreakStringLiterals: 'false' - -# Penalties -PenaltyBreakAssignment: '0' -PenaltyBreakBeforeFirstCallParameter: '0' -PenaltyBreakComment: '0' -PenaltyBreakFirstLessLess: '0' -PenaltyBreakString: '0' -PenaltyBreakTemplateDeclaration: '0' -PenaltyExcessCharacter: '0' -PenaltyReturnTypeOnItsOwnLine: '999999999' # Nope - -# Constructor Initializers -ConstructorInitializerAllOnOneLineOrOnePerLine: 'true' -AllowAllConstructorInitializersOnNextLine: 'true' -BreakConstructorInitializers: BeforeComma - -# Comments -ReflowComments: 'false' -CommentPragmas: '^ TODO@:' -FixNamespaceComments: 'true' - -# Misc -Cpp11BracedListStyle: 'false' -SortUsingDeclarations: 'true' -KeepEmptyLinesAtTheStartOfBlocks: 'false' -MaxEmptyLinesToKeep: '2' diff --git a/Engine/CMakeLists.txt b/Engine/CMakeLists.txt deleted file mode 100644 index 2c529b0..0000000 --- a/Engine/CMakeLists.txt +++ /dev/null @@ -1,56 +0,0 @@ -cmake_minimum_required(VERSION 3.16) - -if(CMAKE_COMPILER_IS_GNUCC) - add_compile_options(-w) -endif() - -if(MSVC) - add_compile_options(/MP) - add_compile_options(/W0) -endif() - -file(GLOB_RECURSE ENGINE_ALL_FILES true ABSOLUTE ${ENGINE_DIR}src/*) -file(GLOB_RECURSE ENGINE_RES_FILES true ABSOLUTE ${ENGINE_DIR}res/*) -list(LENGTH ENGINE_ALL_FILES ENGINE_ALL_FILES_COUNT) - -if(NOT WIN32) - set(DX_DIR ${ENGINE_DIR}src/Platform/GraphicsAPI/DirectX/) - set(WIN_DIR ${ENGINE_DIR}src/Platform/OS/Windows/) - - list( - REMOVE_ITEM ENGINE_ALL_FILES - ${DX_DIR}dxBlender.cpp - ${DX_DIR}dxBuffers.cpp - ${DX_DIR}dxFramebuffer.cpp - ${DX_DIR}dxGraphicsContext.cpp - ${DX_DIR}dxRenderCommand.cpp - ${DX_DIR}dxShader.cpp - ${DX_DIR}dxSharedContext.cpp - ${DX_DIR}dxTexture.cpp - ${DX_DIR}dxUserInterface.cpp - ${DX_DIR}dxVertexLayout.cpp - ${WIN_DIR}wWindow.cpp - ) -else() - file(GLOB_RECURSE HLSL_FILES true ABSOLUTE ${ENGINE_DIR}res/*.hlsl) - set_source_files_properties(${HLSL_FILES} PROPERTIES VS_TOOL_OVERRIDE "None") -endif() - -list(LENGTH ENGINE_ALL_FILES ENGINE_ALL_FILES_COUNT) - -include_directories( - ${ENGINE_DIR}src/Engine/ - ${ENGINE_DIR}src/Platform/GraphicsAPI/ - ${ENGINE_DIR}src/Platform/OS/ - ${DEPENDENCIES_DIR}GLAD/include/ - ${DEPENDENCIES_DIR}GLFW/include/ - ${DEPENDENCIES_DIR}glm/ - ${DEPENDENCIES_DIR}imgui/ - ${DEPENDENCIES_DIR}spdlog/include/ - ${DEPENDENCIES_DIR}stb_image/ - ${DEPENDENCIES_DIR}yaml-cpp/include/ - ${DEPENDENCIES_DIR}shaderc/libshaderc/include -) - -source_group(TREE ${ENGINE_DIR} FILES ${ENGINE_ALL_FILES} ${ENGINE_RES_FILES}) -add_library(Engine STATIC ${ENGINE_ALL_FILES} ${ENGINE_RES_FILES}) diff --git a/Engine/src/Engine/Camera/Camera.cpp b/Engine/src/Engine/Camera/Camera.cpp deleted file mode 100644 index 4037a86..0000000 --- a/Engine/src/Engine/Camera/Camera.cpp +++ /dev/null @@ -1,6 +0,0 @@ -#include "Camera.hpp" - -namespace Light { - - -} \ No newline at end of file diff --git a/Engine/src/Engine/Camera/Camera.hpp b/Engine/src/Engine/Camera/Camera.hpp deleted file mode 100644 index e0cd5f2..0000000 --- a/Engine/src/Engine/Camera/Camera.hpp +++ /dev/null @@ -1,27 +0,0 @@ -#pragma once - -#include "Base/Base.hpp" - -#include - -namespace Light { - -class Camera -{ -private: - glm::vec4 m_BackgroundColor = glm::vec4(1.0f, 0.0f, 0.0f, 1.0f); - -protected: - glm::mat4 m_Projection; - -public: - Camera() = default; - - inline const glm::mat4& GetProjection() const { return m_Projection; } - - inline const glm::vec4& GetBackgroundColor() const { return m_BackgroundColor; } - - inline void SetBackgroundColor(const glm::vec4& color) { m_BackgroundColor = color; } -}; - -} // namespace Light \ No newline at end of file diff --git a/Engine/src/Engine/Camera/OrthographicCamera.cpp b/Engine/src/Engine/Camera/OrthographicCamera.cpp deleted file mode 100644 index b829885..0000000 --- a/Engine/src/Engine/Camera/OrthographicCamera.cpp +++ /dev/null @@ -1,38 +0,0 @@ -#include "OrthographicCamera.hpp" - -#include -#include - -namespace Light { - -OrthographicCamera::OrthographicCamera(const glm::vec2& position, float aspectRatio, float zoomLevel, const glm::vec4& clearColor /* = glm::vec4(0.1f, 0.3f, 0.7f, 1.0f) */) - : m_Up(0.0f, 1.0f, 0.0f), m_Position(position), m_AspectRatio(aspectRatio), m_ZoomLevel(zoomLevel), m_ClearColor(clearColor) -{ -} - -void OrthographicCamera::CalculateView() -{ - m_View = glm::lookAt(glm::vec3(m_Position, 100.0f), glm::vec3(m_Position, 0.0f), m_Up); -} - -void OrthographicCamera::CalculateProjection() -{ - m_Projection = glm::ortho(-m_ZoomLevel * m_AspectRatio, - +m_ZoomLevel * m_AspectRatio, - -m_ZoomLevel, - +m_ZoomLevel, - FLT_MAX, FLT_MIN); -} - -void OrthographicCamera::OnResize(const glm::vec2& size) -{ - m_AspectRatio = size.x / size.y; - CalculateProjection(); -} - -void OrthographicCamera::Move(const glm::vec2& position) -{ - m_Position += position; -} - -} // namespace Light \ No newline at end of file diff --git a/Engine/src/Engine/Camera/OrthographicCamera.hpp b/Engine/src/Engine/Camera/OrthographicCamera.hpp deleted file mode 100644 index 5a1b891..0000000 --- a/Engine/src/Engine/Camera/OrthographicCamera.hpp +++ /dev/null @@ -1,41 +0,0 @@ -#pragma once - -#include "Base/Base.hpp" - -#include - -namespace Light { - -class OrthographicCamera -{ -private: - glm::vec2 m_Position; - float m_AspectRatio; - float m_ZoomLevel; - - const glm::vec3 m_Up; - - glm::mat4 m_Projection; - glm::mat4 m_View; - - glm::vec4 m_ClearColor; - -public: - OrthographicCamera(const glm::vec2& position, float aspectRatio, float zoomLevel, const glm::vec4& clearColor = glm::vec4(0.1f, 0.3f, 0.7f, 1.0f)); - - // CAMERA // - void CalculateView(); - void CalculateProjection(); - - void OnResize(const glm::vec2& size); - - inline const glm::mat4& GetView() const { return m_View; } - inline const glm::mat4& GetProjection() const { return m_Projection; } - - inline const glm::vec4& GetClearColor() const { return m_ClearColor; } - - // CAMERA_CONTROLLER // - void Move(const glm::vec2& position); -}; - -} // namespace Light \ No newline at end of file diff --git a/Engine/src/Engine/Core/Application.hpp b/Engine/src/Engine/Core/Application.hpp deleted file mode 100644 index 969b08c..0000000 --- a/Engine/src/Engine/Core/Application.hpp +++ /dev/null @@ -1,54 +0,0 @@ -#pragma once - -#include "Base/Base.hpp" -#include "Debug/Instrumentor.hpp" -#include "Input/Input.hpp" -#include "Layer/LayerStack.hpp" -#include "Utility/ResourceManager.hpp" - -namespace Light { - -class Window; -class Event; - -class Instrumentor; - -class Application /* singleton */ -{ -private: - static Application* s_Context; - -private: - Scope m_Logger; - Scope m_Instrumentor; - Scope m_LayerStack; - Scope m_Input; - Scope m_ResourceManager; - -protected: - Scope m_Window; - -public: - Application(const Application&) = delete; - Application& operator=(const Application&) = delete; - - virtual ~Application(); - - void GameLoop(); - - // To be defined in client project - - static void Quit(); - -protected: - Application(std::string execName, std::vector args); - -private: - void OnEvent(const Event& event); - - void LogDebugData(); -}; - -extern Application* CreateApplication(std::string execName, std::vector args); - -} // namespace Light \ No newline at end of file diff --git a/Engine/src/Engine/Core/UUID.hpp b/Engine/src/Engine/Core/UUID.hpp deleted file mode 100644 index ad33e76..0000000 --- a/Engine/src/Engine/Core/UUID.hpp +++ /dev/null @@ -1,35 +0,0 @@ -#pragma once - -#include - -namespace Light { - - class UUID - { - private: - static std::mt19937_64 s_Engine; - static std::uniform_int_distribution s_UniformDistribution; - - private: - uint64_t m_UUID; - - public: - UUID(uint64_t uuid = -1); - - operator uint64_t() const { return m_UUID; } - }; - -} - -namespace std { - - template <> - struct hash - { - std::size_t operator()(const Light::UUID& uuid) const - { - return hash()(static_cast(uuid)); - } - }; - -} \ No newline at end of file diff --git a/Engine/src/Engine/Core/Window.hpp b/Engine/src/Engine/Core/Window.hpp deleted file mode 100644 index f9e0f83..0000000 --- a/Engine/src/Engine/Core/Window.hpp +++ /dev/null @@ -1,73 +0,0 @@ -#pragma once - -#include "Base/Base.hpp" - -#include - -namespace Light { - -class Event; - -class GraphicsContext; - -struct WindowProperties -{ - std::string title; - glm::uvec2 size; - bool vsync, visible; -}; - -class Window -{ -protected: - Scope m_GraphicsContext; - WindowProperties m_Properties; - bool b_Closed; - -public: - static Scope Create(std::function callback); - - Window() - : m_GraphicsContext(nullptr), m_Properties {}, b_Closed(false) - { - } - - Window(const Window&) = delete; - Window& operator=(const Window&) = delete; - - virtual ~Window() = default; - - /* events */ - virtual void PollEvents() = 0; - virtual void OnEvent(const Event& event) = 0; - - //======================================== SETTERS ========================================// - virtual void SetProperties(const WindowProperties& properties, bool affectVisibility = false) = 0; - - virtual void SetTitle(const std::string& title) = 0; - - virtual void SetSize(const glm::uvec2& size, bool additive = false) = 0; // pass 0 for width or height for single dimension resizing - - inline void Close() { b_Closed = true; } - virtual void SetVSync(bool vsync, bool toggle = false) = 0; - virtual void SetVisibility(bool visible, bool toggle = false) = 0; - //======================================== SETTERS ========================================// - - //============================== GETTERS ==============================// - inline GraphicsContext* GetGfxContext() const { return m_GraphicsContext.get(); } - - inline const WindowProperties& GetProperties() const { return m_Properties; } - - inline const std::string& GetTitle() const { return m_Properties.title; } - - inline const glm::uvec2& GetSize() const { return m_Properties.size; } - - inline bool IsClosed() const { return b_Closed; } - inline bool IsVSync() const { return m_Properties.vsync; } - inline bool IsVisible() const { return m_Properties.visible; } - //============================== GETTERS ==============================// - -protected: -}; - -} // namespace Light \ No newline at end of file diff --git a/Engine/src/Engine/Debug/Logger.hpp b/Engine/src/Engine/Debug/Logger.hpp deleted file mode 100644 index 2513cd5..0000000 --- a/Engine/src/Engine/Debug/Logger.hpp +++ /dev/null @@ -1,43 +0,0 @@ -#pragma once -#ifndef LIGHT_LOGGER_H - #define LIGHT_LOGGER_H - - #include "Base/Base.hpp" - - #include - - #define LT_LOG_FILE_LOCATION "Logs/Logger.txt" - - #ifndef LIGHT_DIST - #define LOG(logLevel, ...) SPDLOG_LOGGER_CALL(::Light::Logger::GetEngineLogger(), spdlog::level::logLevel, __VA_ARGS__) - #else - #define LOG(logLevel, ...) SPDLOG_LOGGER_CALL(::Light::Logger::GetFileLogger(), spdlog::level::logLevel, __VA_ARGS__) - #endif - -namespace Light { - -// #todo: extend -class Logger /* singleton */ -{ -private: - static Logger* s_Context; - -private: - Ref m_EngineLogger, m_FileLogger; - std::string m_LogFilePath; - -public: - static Scope Create(); - - static inline Ref GetEngineLogger() { return s_Context->m_EngineLogger; } - static inline Ref GetFileLogger() { return s_Context->m_FileLogger; } - - void LogDebugData(); - -private: - Logger(); -}; - -} // namespace Light - -#endif diff --git a/Engine/src/Engine/Events/Event.hpp b/Engine/src/Engine/Events/Event.hpp deleted file mode 100644 index 7f96490..0000000 --- a/Engine/src/Engine/Events/Event.hpp +++ /dev/null @@ -1,57 +0,0 @@ -#pragma once - -#include "Base/Base.hpp" - -namespace Light { - -enum class EventType -{ - None = 0, - - // input - MouseMoved, - WheelScrolled, - ButtonPressed, - ButtonReleased, - KeyPressed, - KeyRepeated, - KeyReleased, - SetChar, - - // window - WindowMoved, - WindowResized, - WindowClosed, - WindowLostFocus, - WindowGainFocus, -}; - -enum EventCategory -{ - None = 0, - - WindowEventCategory = BIT(0), - InputEventCategory = BIT(1), - KeyboardEventCategory = BIT(2), - MouseEventCategory = BIT(3), -}; - -#define EVENT_TYPE(type) \ - EventType GetEventType() const override { return ::Light::EventType::type; } -#define EVENT_CATEGORY(eCategory) \ - inline bool HasCategory(EventCategory category) const override { return (eCategory)&category; } - -class Event -{ -public: - virtual EventType GetEventType() const = 0; - virtual std::string GetInfoLog() const = 0; - virtual bool HasCategory(EventCategory category) const = 0; - - friend std::ostream& operator<<(std::ostream& os, const Event& e) - { - return os << e.GetInfoLog(); - } -}; - -} // namespace Light \ No newline at end of file diff --git a/Engine/src/Engine/Graphics/Blender.cpp b/Engine/src/Engine/Graphics/Blender.cpp deleted file mode 100644 index 18cbde9..0000000 --- a/Engine/src/Engine/Graphics/Blender.cpp +++ /dev/null @@ -1,29 +0,0 @@ -#include "Blender.hpp" - -#include "OpenGL/glBlender.hpp" - -#ifdef LIGHT_PLATFORM_WINDOWS - #include "DirectX/dxBlender.hpp" - #include "DirectX/dxSharedContext.hpp" -#endif - -#include "GraphicsContext.hpp" - -namespace Light { - -Scope Blender::Create(Ref sharedContext) -{ - switch (GraphicsContext::GetGraphicsAPI()) - { - case GraphicsAPI::OpenGL: - return CreateScope(); - - case GraphicsAPI::DirectX: LT_WIN( - return CreateScope(std::static_pointer_cast(sharedContext));) - - default: - ASSERT(false, "Invalid/unsupported 'GraphicsAPI' {}", static_cast(GraphicsContext::GetGraphicsAPI())); - } -} - -} // namespace Light diff --git a/Engine/src/Engine/Graphics/Buffers.cpp b/Engine/src/Engine/Graphics/Buffers.cpp deleted file mode 100644 index 02e227c..0000000 --- a/Engine/src/Engine/Graphics/Buffers.cpp +++ /dev/null @@ -1,69 +0,0 @@ -#include "Buffers.hpp" - -#include "OpenGL/glBuffers.hpp" -#include "SharedContext.hpp" - -#ifdef LIGHT_PLATFORM_WINDOWS - #include "DirectX/dxBuffers.hpp" - #include "DirectX/dxSharedContext.hpp" -#endif - -#include "GraphicsContext.hpp" - -namespace Light { - -//================================================== CONSTANT_BUFFER ==================================================// -Scope ConstantBuffer::Create(ConstantBufferIndex index, unsigned int size, Ref sharedContext) -{ - switch (GraphicsContext::GetGraphicsAPI()) - { - case GraphicsAPI::OpenGL: - return CreateScope(index, size); - - case GraphicsAPI::DirectX: LT_WIN( - return CreateScope(index, size, std::static_pointer_cast(sharedContext));) - - default: - ASSERT(false, "Invalid/unsupported 'GraphicsAPI' {}", static_cast(GraphicsContext::GetGraphicsAPI())); - return nullptr; - } -} -//================================================== CONSTANT_BUFFER ==================================================// - -//================================================== VERTEX_BUFFER ==================================================// -Ref VertexBuffer::Create(float* vertices, unsigned int stride, unsigned int count, Ref sharedContext) -{ - switch (GraphicsContext::GetGraphicsAPI()) - { - case GraphicsAPI::OpenGL: - return CreateRef(vertices, stride, count); - - case GraphicsAPI::DirectX: LT_WIN( - return CreateRef(vertices, stride, count, std::static_pointer_cast(sharedContext));) - - default: - ASSERT(false, "Invalid/unsupported 'GraphicsAPI' {}", static_cast(GraphicsContext::GetGraphicsAPI())); - return nullptr; - } -} -//================================================== VERTEX_BUFFER ==================================================// - -//======================================== INDEX_BUFFER ========================================// -Ref IndexBuffer::Create(unsigned int* indices, unsigned int count, Ref sharedContext) -{ - switch (GraphicsContext::GetGraphicsAPI()) - { - case GraphicsAPI::OpenGL: - return CreateRef(indices, count); - - case GraphicsAPI::DirectX: LT_WIN( - return CreateRef(indices, count, std::dynamic_pointer_cast(sharedContext));) - - default: - ASSERT(false, "Invalid/unsupported 'GraphicsAPI' {}", static_cast(GraphicsContext::GetGraphicsAPI())); - return nullptr; - } -} -//======================================== INDEX_BUFFER ========================================// - -} // namespace Light diff --git a/Engine/src/Engine/Graphics/Framebuffer.cpp b/Engine/src/Engine/Graphics/Framebuffer.cpp deleted file mode 100644 index 5acc70e..0000000 --- a/Engine/src/Engine/Graphics/Framebuffer.cpp +++ /dev/null @@ -1,30 +0,0 @@ -#include "Framebuffer.hpp" - -#include "OpenGL/glFramebuffer.hpp" - -#ifdef LIGHT_PLATFORM_WINDOWS - #include "DirectX/dxFramebuffer.hpp" - #include "DirectX/dxSharedContext.hpp" -#endif - -#include "GraphicsContext.hpp" - -namespace Light { - -Ref Framebuffer::Create(const FramebufferSpecification& specification, Ref sharedContext) -{ - switch (GraphicsContext::GetGraphicsAPI()) - { - case GraphicsAPI::OpenGL: - return CreateRef(specification); - - case GraphicsAPI::DirectX: LT_WIN( - return CreateRef(specification, std::static_pointer_cast(sharedContext));) - - default: - ASSERT(false, "Invalid/unsupported 'GraphicsAPI' {}", static_cast(GraphicsContext::GetGraphicsAPI())); - return nullptr; - } -} - -} // namespace Light diff --git a/Engine/src/Engine/Graphics/GraphicsContext.cpp b/Engine/src/Engine/Graphics/GraphicsContext.cpp deleted file mode 100644 index 957479e..0000000 --- a/Engine/src/Engine/Graphics/GraphicsContext.cpp +++ /dev/null @@ -1,79 +0,0 @@ -#include "GraphicsContext.hpp" - -#include "OpenGL/glGraphicsContext.hpp" - -#ifdef LIGHT_PLATFORM_WINDOWS - #include "DirectX/dxGraphicsContext.hpp" - #include "DirectX/dxSharedContext.hpp" -#endif - -#include "Blender.hpp" // required for forward declaration -#include "Buffers.hpp" // required for forward declaration -#include "RenderCommand.hpp" // required for forward declaration -#include "Renderer.hpp" // required for forward declaration -#include "UserInterface/UserInterface.hpp" // required for forward declaration -#include "Utility/ResourceManager.hpp" // required for forward declaration - -namespace Light { - -GraphicsContext* GraphicsContext::s_Context = nullptr; - -GraphicsContext::~GraphicsContext() -{ -} - -Scope GraphicsContext::Create(GraphicsAPI api, GLFWwindow* windowHandle) -{ - // terminate 'GraphicsContext' dependent classes - if (s_Context) - { - s_Context->m_Renderer.reset(); - s_Context->m_UserInterface.reset(); - - delete s_Context; - } - - // determine the default api - if (api == GraphicsAPI::Default) - { -#if defined(LIGHT_PLATFORM_WINDOWS) - api = GraphicsAPI::DirectX; -#elif defined(LIGHT_PLATFORM_LINUX) - api = GraphicsAPI::OpenGL; -#elif defined(LIGHT_PLATFORM_MAC) - api = GraphicsAPI::OpenGL; -#endif - } - - // create gfx context - Scope scopeGfx; - switch (api) - { - // opengl - case GraphicsAPI::OpenGL: - scopeGfx = CreateScope(windowHandle); - s_Context = scopeGfx.get(); - break; - // directx - case GraphicsAPI::DirectX: LT_WIN( - scopeGfx = CreateScope(windowHandle); - s_Context = scopeGfx.get(); - break;) - - default: - ASSERT(false, "Invalid/unsupported 'GraphicsAPI' {}", Stringifier::GraphicsAPIToString(api)); - return nullptr; - } - - // create 'GraphicsContext' dependent classes - s_Context->m_UserInterface = UserInterface::Create(windowHandle, s_Context->m_SharedContext); - s_Context->m_Renderer = Renderer::Create(windowHandle, s_Context->m_SharedContext); - - // check - ASSERT(s_Context->m_UserInterface, "Failed to create UserInterface"); - ASSERT(s_Context->m_Renderer, "Failed to create Renderer"); - - return std::move(scopeGfx); -} - -} // namespace Light diff --git a/Engine/src/Engine/Graphics/RenderCommand.cpp b/Engine/src/Engine/Graphics/RenderCommand.cpp deleted file mode 100644 index 7b9cc5e..0000000 --- a/Engine/src/Engine/Graphics/RenderCommand.cpp +++ /dev/null @@ -1,30 +0,0 @@ -#include "RenderCommand.hpp" - -#include "OpenGL/glRenderCommand.hpp" - -#ifdef LIGHT_PLATFORM_WINDOWS - #include "DirectX/dxRenderCommand.hpp" - #include "DirectX/dxSharedContext.hpp" -#endif - -#include "GraphicsContext.hpp" - -namespace Light { - -Scope RenderCommand::Create(GLFWwindow* windowHandle, Ref sharedContext) -{ - switch (GraphicsContext::GetGraphicsAPI()) - { - case GraphicsAPI::OpenGL: - return CreateScope(windowHandle); - - case GraphicsAPI::DirectX: LT_WIN( - return CreateScope((std::static_pointer_cast)(sharedContext));) - - default: - ASSERT(false, "Invalid/unsupported 'GraphicsAPI' {}", static_cast(GraphicsContext::GetGraphicsAPI())); - return nullptr; - } -} - -} // namespace Light diff --git a/Engine/src/Engine/Graphics/RenderCommand.hpp b/Engine/src/Engine/Graphics/RenderCommand.hpp deleted file mode 100644 index 674a239..0000000 --- a/Engine/src/Engine/Graphics/RenderCommand.hpp +++ /dev/null @@ -1,37 +0,0 @@ -#pragma once - -#include "Base/Base.hpp" - -#include - -struct GLFWwindow; - -namespace Light { - -class SharedContext; - -class RenderCommand -{ -public: - static Scope Create(GLFWwindow* windowHandle, Ref sharedContext); - - RenderCommand(const RenderCommand&) = delete; - RenderCommand& operator=(const RenderCommand&) = delete; - - virtual ~RenderCommand() = default; - - virtual void SwapBuffers() = 0; - virtual void ClearBackBuffer(const glm::vec4& clearColor) = 0; - - virtual void Draw(unsigned int count) = 0; - virtual void DrawIndexed(unsigned int count) = 0; - - virtual void DefaultTargetFramebuffer() = 0; - - virtual void SetViewport(unsigned int x, unsigned int y, unsigned int width, unsigned int height) = 0; - -protected: - RenderCommand() = default; -}; - -} // namespace Light \ No newline at end of file diff --git a/Engine/src/Engine/Graphics/Renderer.hpp b/Engine/src/Engine/Graphics/Renderer.hpp deleted file mode 100644 index c65f806..0000000 --- a/Engine/src/Engine/Graphics/Renderer.hpp +++ /dev/null @@ -1,84 +0,0 @@ -#pragma once - -#include "Base/Base.hpp" -#include "RendererPrograms/QuadRendererProgram.hpp" -#include "RendererPrograms/TextureRendererProgram.hpp" -#include "RendererPrograms/TintedTextureRendererProgram.hpp" - -#define LT_MAX_QUAD_RENDERER_VERTICES 1028u * 4u -#define LT_MAX_TEXTURE_RENDERER_VERTICES 1028u * 4u -#define LT_MAX_TINTED_TEXTURE_RENDERER_VERTICES 1028u * 4u - -struct GLFWwindow; - -namespace Light { - -class Blender; -class ConstantBuffer; -class Framebuffer; -class RenderCommand; -class Texture; - -class SharedContext; - -class Camera; - -class WindowResizedEvent; - -class Renderer -{ -private: - static Renderer* s_Context; - - // renderer programs - QuadRendererProgram m_QuadRenderer; - TextureRendererProgram m_TextureRenderer; - TintedTextureRendererProgram m_TintedTextureRenderer; - - // constant buffers - Scope m_ViewProjectionBuffer; - - Scope m_RenderCommand; - Scope m_Blender; - - Camera* m_DefaultFramebufferCamera; - Ref m_TargetFramebuffer; - - bool m_ShouldClearBackbuffer; - -public: - static Scope Create(GLFWwindow* windowHandle, Ref sharedContext); - - static inline void DrawQuad(const glm::vec3& position, const glm::vec2& size, const glm::vec4& tint, Ref texture) { s_Context->DrawQuadImpl(position, size, tint, texture); } - static inline void DrawQuad(const glm::vec3& position, const glm::vec2& size, const glm::vec4& tint) { s_Context->DrawQuadImpl(position, size, tint); } - static inline void DrawQuad(const glm::vec3& position, const glm::vec2& size, Ref texture) { s_Context->DrawQuadImpl(position, size, texture); } - - static void DrawQuad(const glm::mat4& transform, const glm::vec4& tint, Ref texture) { s_Context->DrawQuadImpl(transform, tint, texture); } - static void DrawQuad(const glm::mat4& transform, const glm::vec4& tint) { s_Context->DrawQuadImpl(transform, tint); } - static void DrawQuad(const glm::mat4& transform, Ref texture) { s_Context->DrawQuadImpl(transform, texture); } - - static inline void BeginScene(Camera* camera, const glm::mat4& cameraTransform, const Ref& targetFrameBuffer = nullptr) { s_Context->BeginSceneImpl(camera, cameraTransform, targetFrameBuffer); } - static inline void EndScene() { s_Context->EndSceneImpl(); } - - void OnWindowResize(const WindowResizedEvent& event); - - void BeginFrame(); - void EndFrame(); - -private: - Renderer(GLFWwindow* windowHandle, Ref sharedContext); - - void DrawQuadImpl(const glm::vec3& position, const glm::vec2& size, const glm::vec4& tint, Ref texture); - void DrawQuadImpl(const glm::vec3& position, const glm::vec2& size, const glm::vec4& tint); - void DrawQuadImpl(const glm::vec3& position, const glm::vec2& size, Ref texture); - - void DrawQuadImpl(const glm::mat4& transform, const glm::vec4& tint, Ref texture); - void DrawQuadImpl(const glm::mat4& transform, const glm::vec4& tint); - void DrawQuadImpl(const glm::mat4& transform, Ref texture); - - void BeginSceneImpl(Camera* camera, const glm::mat4& cameraTransform, const Ref& targetFrameBuffer = nullptr); - void FlushScene(); - void EndSceneImpl(); -}; - -} // namespace Light \ No newline at end of file diff --git a/Engine/src/Engine/Graphics/RendererPrograms/QuadRendererProgram.cpp b/Engine/src/Engine/Graphics/RendererPrograms/QuadRendererProgram.cpp deleted file mode 100644 index 11b2a97..0000000 --- a/Engine/src/Engine/Graphics/RendererPrograms/QuadRendererProgram.cpp +++ /dev/null @@ -1,58 +0,0 @@ -#include "QuadRendererProgram.hpp" - -#include "Camera/Camera.hpp" -#include "Graphics/Buffers.hpp" -#include "Graphics/Shader.hpp" -#include "Graphics/VertexLayout.hpp" -#include "Utility/ResourceManager.hpp" - -namespace Light { - -QuadRendererProgram::QuadRendererProgram(unsigned int maxVertices, Ref sharedContext) - : m_Shader(nullptr), m_IndexBuffer(nullptr), m_VertexLayout(nullptr), m_MapCurrent(nullptr), m_MapEnd(nullptr), m_QuadCount(0u), m_MaxVertices(maxVertices) -{ - // #todo: don't use relative path - ResourceManager::LoadShader("LT_ENGINE_RESOURCES_QUAD_SHADER", "Assets/Shaders/Quad/Quad_VS.glsl", "Assets/Shaders/Quad/Quad_PS.glsl"); - - m_Shader = ResourceManager::GetShader("LT_ENGINE_RESOURCES_QUAD_SHADER"); - m_VertexBuffer = Ref(VertexBuffer::Create(nullptr, sizeof(QuadVertexData), maxVertices, sharedContext)); - m_IndexBuffer = Ref(IndexBuffer::Create(nullptr, (maxVertices / 4) * 6, sharedContext)); - m_VertexLayout = Ref(VertexLayout::Create(m_VertexBuffer, m_Shader, { { "POSITION", VertexElementType::Float4 }, { "COLOR", VertexElementType::Float4 } }, sharedContext)); -} - -bool QuadRendererProgram::Advance() -{ - m_MapCurrent += 4; - - if (m_MapCurrent >= m_MapEnd) - { - LOG(warn, "'VertexBuffer' map went beyond 'MaxVertices': {}", m_MaxVertices); - return false; - } - - m_QuadCount++; - return true; -} - -void QuadRendererProgram::Map() -{ - m_QuadCount = 0u; - - m_MapCurrent = (QuadRendererProgram::QuadVertexData*)m_VertexBuffer->Map(); - m_MapEnd = m_MapCurrent + m_MaxVertices; -} - -void QuadRendererProgram::UnMap() -{ - m_VertexBuffer->UnMap(); -} - -void QuadRendererProgram::Bind() -{ - m_Shader->Bind(); - m_VertexLayout->Bind(); - m_VertexBuffer->Bind(); - m_IndexBuffer->Bind(); -} - -} // namespace Light diff --git a/Engine/src/Engine/Graphics/RendererPrograms/TextureRendererProgram.cpp b/Engine/src/Engine/Graphics/RendererPrograms/TextureRendererProgram.cpp deleted file mode 100644 index 7181349..0000000 --- a/Engine/src/Engine/Graphics/RendererPrograms/TextureRendererProgram.cpp +++ /dev/null @@ -1,57 +0,0 @@ -#include "TextureRendererProgram.hpp" - -#include "Camera/Camera.hpp" -#include "Graphics/Buffers.hpp" -#include "Graphics/Shader.hpp" -#include "Graphics/VertexLayout.hpp" -#include "Utility/ResourceManager.hpp" - -namespace Light { - -TextureRendererProgram::TextureRendererProgram(unsigned int maxVertices, Ref sharedContext) - : m_Shader(nullptr), m_IndexBuffer(nullptr), m_VertexLayout(nullptr), m_MapCurrent(nullptr), m_MapEnd(nullptr), m_QuadCount(0u), m_MaxVertices(maxVertices) -{ - // #todo: don't use relative path - ResourceManager::LoadShader("LT_ENGINE_RESOURCES_TEXTURE_SHADER", "Assets/Shaders/Texture/Texture_VS.glsl", "Assets/Shaders/Texture/Texture_PS.glsl"); - - m_Shader = ResourceManager::GetShader("LT_ENGINE_RESOURCES_TEXTURE_SHADER"); - m_VertexBuffer = Ref(VertexBuffer::Create(nullptr, sizeof(TextureVertexData), maxVertices, sharedContext)); - m_IndexBuffer = Ref(IndexBuffer::Create(nullptr, (maxVertices / 4) * 6, sharedContext)); - m_VertexLayout = Ref(VertexLayout::Create(m_VertexBuffer, m_Shader, { { "POSITION", VertexElementType::Float4 }, { "TEXCOORD", VertexElementType::Float2 } }, sharedContext)); -} - -bool TextureRendererProgram::Advance() -{ - if (m_MapCurrent + 4 >= m_MapEnd) - { - LOG(warn, "'VertexBuffer' map went beyond 'MaxVertices': {}", m_MaxVertices); - return false; - } - - m_MapCurrent += 4; - m_QuadCount++; - return true; -} - -void TextureRendererProgram::Map() -{ - m_QuadCount = 0u; - - m_MapCurrent = (TextureRendererProgram::TextureVertexData*)m_VertexBuffer->Map(); - m_MapEnd = m_MapCurrent + m_MaxVertices; -} - -void TextureRendererProgram::UnMap() -{ - m_VertexBuffer->UnMap(); -} - -void TextureRendererProgram::Bind() -{ - m_Shader->Bind(); - m_VertexLayout->Bind(); - m_VertexBuffer->Bind(); - m_IndexBuffer->Bind(); -} - -} // namespace Light diff --git a/Engine/src/Engine/Graphics/RendererPrograms/TintedTextureRendererProgram.cpp b/Engine/src/Engine/Graphics/RendererPrograms/TintedTextureRendererProgram.cpp deleted file mode 100644 index 2404f31..0000000 --- a/Engine/src/Engine/Graphics/RendererPrograms/TintedTextureRendererProgram.cpp +++ /dev/null @@ -1,58 +0,0 @@ -#include "TintedTextureRendererProgram.hpp" - -#include "Camera/Camera.hpp" -#include "Graphics/Buffers.hpp" -#include "Graphics/Shader.hpp" -#include "Graphics/VertexLayout.hpp" -#include "Utility/ResourceManager.hpp" - -namespace Light { - -TintedTextureRendererProgram::TintedTextureRendererProgram(unsigned int maxVertices, Ref sharedContext) - : m_Shader(nullptr), m_IndexBuffer(nullptr), m_VertexLayout(nullptr), m_MapCurrent(nullptr), m_MapEnd(nullptr), m_QuadCount(0u), m_MaxVertices(maxVertices) -{ - // #todo: don't use relative path - ResourceManager::LoadShader("LT_ENGINE_RESOURCES_TINTED_TEXTURE_SHADER", "Assets/Shaders/TintedTexture/TintedTexture_VS.glsl", "Assets/Shaders/TintedTexture/TintedTexture_PS.glsl"); - - m_Shader = ResourceManager::GetShader("LT_ENGINE_RESOURCES_TINTED_TEXTURE_SHADER"); - m_VertexBuffer = Ref(VertexBuffer::Create(nullptr, sizeof(TintedTextureVertexData), maxVertices, sharedContext)); - m_IndexBuffer = Ref(IndexBuffer::Create(nullptr, (maxVertices / 4) * 6, sharedContext)); - m_VertexLayout = Ref(VertexLayout::Create(m_VertexBuffer, m_Shader, { { "POSITION", VertexElementType::Float4 }, { "TINT", VertexElementType::Float4 }, { "TEXCOORD", VertexElementType::Float2 } }, sharedContext)); -} - -bool TintedTextureRendererProgram::Advance() -{ - m_MapCurrent += 4; - - if (m_MapCurrent >= m_MapEnd) - { - LOG(warn, "'VertexBuffer' map went beyond 'MaxVertices': {}", m_MaxVertices); - return false; - } - - m_QuadCount++; - return true; -} - -void TintedTextureRendererProgram::Map() -{ - m_QuadCount = 0u; - - m_MapCurrent = (TintedTextureRendererProgram::TintedTextureVertexData*)m_VertexBuffer->Map(); - m_MapEnd = m_MapCurrent + m_MaxVertices; -} - -void TintedTextureRendererProgram::UnMap() -{ - m_VertexBuffer->UnMap(); -} - -void TintedTextureRendererProgram::Bind() -{ - m_Shader->Bind(); - m_VertexLayout->Bind(); - m_VertexBuffer->Bind(); - m_IndexBuffer->Bind(); -} - -} // namespace Light diff --git a/Engine/src/Engine/Graphics/Shader.cpp b/Engine/src/Engine/Graphics/Shader.cpp deleted file mode 100644 index 717f171..0000000 --- a/Engine/src/Engine/Graphics/Shader.cpp +++ /dev/null @@ -1,31 +0,0 @@ -#include "Shader.hpp" - -#include "OpenGL/glShader.hpp" - -#ifdef LIGHT_PLATFORM_WINDOWS - #include "DirectX/dxShader.hpp" - #include "DirectX/dxSharedContext.hpp" -#endif - -#include "GraphicsContext.hpp" - -namespace Light { - -Ref Shader::Create(BasicFileHandle vertexFile, BasicFileHandle pixelFile, Ref sharedContext) -{ - // load shader source - switch (GraphicsContext::GetGraphicsAPI()) - { - case GraphicsAPI::OpenGL: - return CreateRef(vertexFile, pixelFile); - - case GraphicsAPI::DirectX: LT_WIN( - return CreateRef(vertexFile, pixelFile, std::static_pointer_cast(sharedContext));) - - default: - ASSERT(false, "Invalid/unsupported 'GraphicsAPI' {}", static_cast(GraphicsContext::GetGraphicsAPI())); - return nullptr; - } -} - -} // namespace Light diff --git a/Engine/src/Engine/Graphics/Shader.hpp b/Engine/src/Engine/Graphics/Shader.hpp deleted file mode 100644 index 82a397b..0000000 --- a/Engine/src/Engine/Graphics/Shader.hpp +++ /dev/null @@ -1,35 +0,0 @@ -#pragma once - -#include "Base/Base.hpp" -#include "Utility/FileManager.hpp" - -#include - -namespace Light { - -class SharedContext; - -class Shader -{ -public: - enum Stage - { - NONE = 0, - VERTEX = 1, - PIXEL = 2, - GEOMETRY = 3 - }; - -public: - static Ref Create(BasicFileHandle vertexFile, BasicFileHandle pixelFile, Ref sharedContext); - - virtual ~Shader() = default; - - virtual void Bind() = 0; - virtual void UnBind() = 0; - -protected: - Shader() = default; -}; - -} // namespace Light \ No newline at end of file diff --git a/Engine/src/Engine/Graphics/Texture.cpp b/Engine/src/Engine/Graphics/Texture.cpp deleted file mode 100644 index 4ff3af7..0000000 --- a/Engine/src/Engine/Graphics/Texture.cpp +++ /dev/null @@ -1,35 +0,0 @@ -#include "Texture.hpp" - -#include "OpenGL/glTexture.hpp" - -#ifdef LIGHT_PLATFORM_WINDOWS - #include "DirectX/dxSharedContext.hpp" - #include "DirectX/dxTexture.hpp" -#endif - -#include "GraphicsContext.hpp" - -namespace Light { - -Ref Texture::Create(unsigned int width, unsigned int height, unsigned int components, unsigned char* pixels, Ref sharedContext, const std::string& filePath) -{ - switch (GraphicsContext::GetGraphicsAPI()) - { - case GraphicsAPI::OpenGL: - return CreateRef(width, height, components, pixels, filePath); - - case GraphicsAPI::DirectX: LT_WIN( - return CreateRef(width, height, components, pixels, std::static_pointer_cast(sharedContext), filePath);) - - default: - ASSERT(false, "Invalid/unsupported 'GraphicsAPI' {}", static_cast(GraphicsContext::GetGraphicsAPI())); - return nullptr; - } -} - -Texture::Texture(const std::string& filePath) - : m_FilePath(filePath) -{ -} - -} // namespace Light diff --git a/Engine/src/Engine/Graphics/VertexLayout.cpp b/Engine/src/Engine/Graphics/VertexLayout.cpp deleted file mode 100644 index ad2276a..0000000 --- a/Engine/src/Engine/Graphics/VertexLayout.cpp +++ /dev/null @@ -1,30 +0,0 @@ -#include "VertexLayout.hpp" - -#include "OpenGL/glVertexLayout.hpp" - -#ifdef LIGHT_PLATFORM_WINDOWS - #include "DirectX/dxSharedContext.hpp" - #include "DirectX/dxVertexLayout.hpp" -#endif - -#include "GraphicsContext.hpp" - -namespace Light { - -Ref VertexLayout::Create(Ref vertexBuffer, Ref shader, const std::vector>& elements, Ref sharedContext) -{ - switch (GraphicsContext::GetGraphicsAPI()) - { - case GraphicsAPI::OpenGL: - return CreateRef(vertexBuffer, elements); - - case GraphicsAPI::DirectX: LT_WIN( - return CreateRef(shader, elements, std::static_pointer_cast(sharedContext));) - - default: - ASSERT(false, "Invalid/unsupported 'GraphicsAPI' {}", static_cast(GraphicsContext::GetGraphicsAPI())); - return nullptr; - } -} - -} // namespace Light diff --git a/Engine/src/Engine/Input/Input.hpp b/Engine/src/Engine/Input/Input.hpp deleted file mode 100644 index b9832a8..0000000 --- a/Engine/src/Engine/Input/Input.hpp +++ /dev/null @@ -1,53 +0,0 @@ -#pragma once - -#include "Base/Base.hpp" - -#include -#include - -namespace Light { - -class Event; - -class Input /* singleton */ -{ -private: - static Input* s_Context; - -private: - std::array m_KeyboadKeys; - std::array m_MouseButtons; - - glm::vec2 m_MousePosition; - glm::vec2 m_MouseDelta; - float m_MouseWheelDelta; - - bool m_UserInterfaceEvents; - bool m_GameEvents; - -public: - static Scope Create(); - - static inline void ReceiveUserInterfaceEvents(bool receive, bool toggle = false) { s_Context->ReceiveUserInterfaceEventsImpl(receive, toggle); } - static inline void ReceiveGameEvents(bool receive, bool toggle = false) { s_Context->ReceieveGameEventsImpl(receive, toggle); } - - static inline bool GetKeyboardKey(int code) { return s_Context->m_KeyboadKeys[code]; } - static inline bool GetMouseButton(int code) { return s_Context->m_MouseButtons[code]; } - - static inline const glm::vec2& GetMousePosition(int code) { return s_Context->m_MousePosition; } - - void OnEvent(const Event& inputEvent); - - inline bool IsReceivingInputEvents() const { return m_UserInterfaceEvents; } - inline bool IsReceivingGameEvents() const { return m_GameEvents; } - -private: - Input(); - - void ReceiveUserInterfaceEventsImpl(bool receive, bool toggle = false); - void ReceieveGameEventsImpl(bool receive, bool toggle = false); - - void RestartInputState(); -}; - -} // namespace Light \ No newline at end of file diff --git a/Engine/src/Engine/Input/KeyCodes.hpp b/Engine/src/Engine/Input/KeyCodes.hpp deleted file mode 100644 index 44068b7..0000000 --- a/Engine/src/Engine/Input/KeyCodes.hpp +++ /dev/null @@ -1,184 +0,0 @@ -#pragma once - -#include "ltpch.hpp" - -#include - -namespace Light { - -namespace Key { -enum : uint16_t -{ - /* digits */ - D0 = 48, - D1 = 49, - D2 = 50, - D3 = 51, - D4 = 52, - D5 = 53, - D6 = 54, - D7 = 55, - D8 = 56, - D9 = 57, - Semicolon = 59, // ; - Equal = 61, // = - - /* letters */ - A = 65, - B = 66, - C = 67, - D = 68, - E = 69, - F = 70, - G = 71, - H = 72, - I = 73, - J = 74, - K = 75, - L = 76, - M = 77, - N = 78, - O = 79, - P = 80, - Q = 81, - R = 82, - S = 83, - T = 84, - U = 85, - V = 86, - W = 87, - X = 88, - Y = 89, - Z = 90, - - /* brackets */ - LeftBracket = 91, // [ - LBracket = LeftBracket, // [ - RightBracket = 93, // ] - RBracket = RightBracket, // ] - - /* arrow */ - Right = 262, - RightArrow = Right, - RArrow = Right, - Left = 263, - LeftArrow = Left, - LArrow = Left, - Down = 264, - DownArrow = Down, - DArrow = Down, - Up = 265, - UpArrow = Up, - UArrow = Up, - - /* page */ - PageUp = 266, - PageDown = 267, - - /* home/end */ - Home = 268, - End = 269, - - /* toggles */ - CapsLock = 280, - ScrollLock = 281, - NumLock = 282, - NumberLock = NumLock, - - /* function */ - F1 = 290, - F2 = 291, - F3 = 292, - F4 = 293, - F5 = 294, - F6 = 295, - F7 = 296, - F8 = 297, - F9 = 298, - F10 = 299, - F11 = 300, - F12 = 301, - F13 = 302, - F14 = 303, - F15 = 304, - F16 = 305, - F17 = 306, - F18 = 307, - F19 = 308, - F20 = 309, - F21 = 310, - F22 = 311, - F23 = 312, - F24 = 313, - F25 = 314, - - /* keypad */ - Kp0 = 320, - Kp1 = 321, - Kp2 = 322, - Kp3 = 323, - Kp4 = 324, - Kp5 = 325, - Kp6 = 326, - Kp7 = 327, - Kp8 = 328, - Kp9 = 329, - KpDecimal = 330, - KpDivide = 331, - KpMultiply = 332, - KpSubstract = 333, - KpAdd = 334, - KpEnter = 335, - KpEqual = 336, - - /* modifiers */ - LeftShift = 340, - LShift = LeftShift, - LeftControl = 341, - LControl = LeftControl, - LeftAlt = 342, - LAlt = LeftAlt, - LeftSuper = 343, - LSuper = LeftSuper, - RightShift = 344, - RShift = 344, - RightControl = 345, - RControl = 345, - RightAlt = 346, - RAlt = 346, - RightSuper = 347, - RSuper = 347, - - /* misc */ - Space = 32, - Apostrophe = 39, // ' - Quote = Apostrophe, - - Comma = 44, // , - Minus = 45, // - - Period = 46, // . - Slash = 47, // / - ForwardSlash = Slash, // / - BackSlash = 92, // \ - - GraveAccent = 96, // ` - Console = GraveAccent, - World1 = 161, // non-US #1 - World2 = 162, // non-US #2 - Escape = 256, - Esc = Escape, - Enter = 257, - Tab = 258, - BackSpace = 259, - Insert = 260, - Delete = 261, - - PrintScreen = 283, - Pause = 284, - - Menu = 348, - -}; -} - -} // namespace Light \ No newline at end of file diff --git a/Engine/src/Engine/Layer/Layer.cpp b/Engine/src/Engine/Layer/Layer.cpp deleted file mode 100644 index 33bd8a7..0000000 --- a/Engine/src/Engine/Layer/Layer.cpp +++ /dev/null @@ -1,62 +0,0 @@ -#include "Layer.hpp" - -#include "Events/CharEvent.hpp" -#include "Events/Event.hpp" -#include "Events/KeyboardEvents.hpp" -#include "Events/MouseEvents.hpp" -#include "Events/WindowEvents.hpp" - -namespace Light { - -Layer::Layer(const std::string& name) - : m_LayerName(name) -{ -} - -bool Layer::OnEvent(const Event& event) -{ - switch (event.GetEventType()) - { - /* mouse */ - // cursor - case EventType::MouseMoved: - return OnMouseMoved((MouseMovedEvent&)event); - // button - case EventType::ButtonPressed: - return OnButtonPressed((ButtonPressedEvent&)event); - case EventType::ButtonReleased: - return OnButtonReleased((ButtonReleasedEvent&)event); - // wheel - case EventType::WheelScrolled: - return OnWheelScrolled((WheelScrolledEvent&)event); - - /* keyboard */ - // key - case EventType::KeyPressed: - return OnKeyPressed((KeyPressedEvent&)event); - case EventType::KeyRepeated: - return OnKeyRepeat((KeyRepeatEvent&)event); - case EventType::KeyReleased: - return OnKeyReleased((KeyReleasedEvent&)event); - // char - case EventType::SetChar: - return OnSetChar((SetCharEvent&)event); - - /* window */ - // termination - case EventType::WindowClosed: - return OnWindowClosed((WindowClosedEvent&)event); - // size/position - case EventType::WindowResized: - return OnWindowResized((WindowResizedEvent&)event); - case EventType::WindowMoved: - return OnWindowMoved((WindowMovedEvent&)event); - // focus - case EventType::WindowLostFocus: - return OnWindowLostFocus((WindowLostFocusEvent&)event); - case EventType::WindowGainFocus: - return OnWindowGainFocus((WindowGainFocusEvent&)event); - } -} - -} // namespace Light \ No newline at end of file diff --git a/Engine/src/Engine/Layer/Layer.hpp b/Engine/src/Engine/Layer/Layer.hpp deleted file mode 100644 index 21e6fee..0000000 --- a/Engine/src/Engine/Layer/Layer.hpp +++ /dev/null @@ -1,78 +0,0 @@ -#pragma once - -#include "Base/Base.hpp" - -namespace Light { - -class Event; - -// mouse -class MouseMovedEvent; -class ButtonPressedEvent; -class ButtonReleasedEvent; -class WheelScrolledEvent; - -// keyboard -// key -class KeyPressedEvent; -class KeyRepeatEvent; -class KeyReleasedEvent; -// char -class SetCharEvent; - -// window -class WindowClosedEvent; -class WindowResizedEvent; -class WindowMovedEvent; -class WindowLostFocusEvent; -class WindowGainFocusEvent; - -class Layer -{ -protected: - std::string m_LayerName; - -public: - Layer(const std::string& name); - virtual ~Layer() = default; - - inline const std::string& GetName() const { return m_LayerName; } - - /* update */ - virtual void OnUpdate(float deltaTime) {} - virtual void OnUserInterfaceUpdate() {} - - virtual void OnRender() {} - - bool OnEvent(const Event& event); - -protected: - /* mouse */ - // cursor - virtual bool OnMouseMoved(const MouseMovedEvent& event) { return false; } - // button - virtual bool OnButtonPressed(const ButtonPressedEvent& event) { return false; } - virtual bool OnButtonReleased(const ButtonReleasedEvent& event) { return false; } - // wheel - virtual bool OnWheelScrolled(const WheelScrolledEvent& event) { return false; } - - /* keyboard */ - // key - virtual bool OnKeyPressed(const KeyPressedEvent& event) { return false; } - virtual bool OnKeyRepeat(const KeyRepeatEvent& event) { return false; } - virtual bool OnKeyReleased(const KeyReleasedEvent& event) { return false; } - // char - virtual bool OnSetChar(const SetCharEvent& event) { return false; } - - /* window */ - // termination - virtual bool OnWindowClosed(const WindowClosedEvent& event) { return false; } - // size/position - virtual bool OnWindowResized(const WindowResizedEvent& event) { return false; } - virtual bool OnWindowMoved(const WindowMovedEvent& event) { return false; } - // focus - virtual bool OnWindowLostFocus(const WindowLostFocusEvent& event) { return false; } - virtual bool OnWindowGainFocus(const WindowGainFocusEvent& event) { return false; } -}; - -} // namespace Light \ No newline at end of file diff --git a/Engine/src/Engine/Layer/LayerStack.hpp b/Engine/src/Engine/Layer/LayerStack.hpp deleted file mode 100644 index 535a98f..0000000 --- a/Engine/src/Engine/Layer/LayerStack.hpp +++ /dev/null @@ -1,51 +0,0 @@ -#pragma once - -#include "Base/Base.hpp" - -namespace Light { - -class Layer; - -class Event; - -class LayerStack /* singleton */ -{ -private: - static LayerStack* s_Context; - -private: - std::vector m_Layers; - - std::vector::iterator m_Begin; - std::vector::iterator m_End; - -public: - static Scope Create(); - - ~LayerStack(); - - // #todo: is this needed? - template - static inline void EmplaceLayer(Args&&... args) - { - s_Context->AttachLayerImpl(new T((args)...)); - } - - static inline void AttachLayer(Layer* layer) { s_Context->AttachLayerImpl(layer); } - static inline void DetachLayer(Layer* layer) { s_Context->DetachLayerImpl(layer); } - - inline bool IsEmpty() { return m_Layers.empty(); } - - std::vector::iterator begin() { return m_Layers.begin(); } - std::vector::iterator end() { return m_Layers.end(); } - std::vector::reverse_iterator rbegin() { return m_Layers.rbegin(); } - std::vector::reverse_iterator rend() { return m_Layers.rend(); } - -private: - LayerStack(); - - void AttachLayerImpl(Layer* layer); - void DetachLayerImpl(Layer* layer); -}; - -} // namespace Light \ No newline at end of file diff --git a/Engine/src/Engine/LightEngine.hpp b/Engine/src/Engine/LightEngine.hpp deleted file mode 100644 index e076a4d..0000000 --- a/Engine/src/Engine/LightEngine.hpp +++ /dev/null @@ -1,60 +0,0 @@ -#pragma once - -// core -#include "Core/Application.hpp" -#include "Core/Window.hpp" - -// camera -#include "Camera/Camera.hpp" - -// debug -#include "Debug/Logger.hpp" - -// events -#include "Events/Event.hpp" -#include "Events/KeyboardEvents.hpp" -#include "Events/MouseEvents.hpp" -#include "Events/WindowEvents.hpp" - -// graphics -#include "Graphics/Framebuffer.hpp" -#include "Graphics/GraphicsContext.hpp" -#include "Graphics/Renderer.hpp" -#include "Graphics/Texture.hpp" - -// input -#include "Input/Input.hpp" -#include "Input/KeyCodes.hpp" -#include "Input/MouseCodes.hpp" - -// layer -#include "Layer/Layer.hpp" -#include "Layer/LayerStack.hpp" - -// user interface -#include "UserInterface/UserInterface.hpp" - -// utility -#include "Utility/ResourceManager.hpp" - -// time -#include "Time/Timer.hpp" - -// base -#include "Base/Base.hpp" - -// third party -#include - -// math -#include "Math/Random.hpp" - -// scene -#include "Scene/Components.hpp" -#include "Scene/Entity.hpp" -#include "Scene/Scene.hpp" - -// entry point -#ifdef LIGHT_ENTRY_POINT - #include "Base/EntryPoint.hpp" -#endif diff --git a/Engine/src/Engine/Scene/Components.hpp b/Engine/src/Engine/Scene/Components.hpp deleted file mode 100644 index 2bc3e05..0000000 --- a/Engine/src/Engine/Scene/Components.hpp +++ /dev/null @@ -1,8 +0,0 @@ -#pragma once - -#include "Base/Base.hpp" -#include "Components/CameraComponent.hpp" -#include "Components/NativeScriptComponent.hpp" -#include "Components/SpriteRendererComponent.hpp" -#include "Components/TagComponent.hpp" -#include "Components/TransformComponent.hpp" \ No newline at end of file diff --git a/Engine/src/Engine/Scene/Components/CameraComponent.hpp b/Engine/src/Engine/Scene/Components/CameraComponent.hpp deleted file mode 100644 index 369ff22..0000000 --- a/Engine/src/Engine/Scene/Components/CameraComponent.hpp +++ /dev/null @@ -1,26 +0,0 @@ -#pragma once - -#include "Base/Base.hpp" -#include "Camera/SceneCamera.hpp" - -#include - -namespace Light { - -struct CameraComponent -{ - SceneCamera camera; - bool isPrimary; - - CameraComponent() = default; - CameraComponent(const CameraComponent&) = default; - - CameraComponent(SceneCamera _camera, bool _isPrimary = false) - : camera(_camera), isPrimary(_isPrimary) - { - } - - operator SceneCamera() { return camera; } -}; - -} // namespace Light \ No newline at end of file diff --git a/Engine/src/Engine/Scene/Components/NativeScriptComponent.hpp b/Engine/src/Engine/Scene/Components/NativeScriptComponent.hpp deleted file mode 100644 index 5bd2d0d..0000000 --- a/Engine/src/Engine/Scene/Components/NativeScriptComponent.hpp +++ /dev/null @@ -1,28 +0,0 @@ -#pragma once - -#include "Base/Base.hpp" -#include "ScriptableEntity.hpp" - -namespace Light { - -struct NativeScriptComponent -{ - NativeScript* instance; - - NativeScript* (*CreateInstance)(); - void (*DestroyInstance)(NativeScriptComponent*); - - template - void Bind() - { - CreateInstance = []() { - return static_cast(new T()); - }; - DestroyInstance = [](NativeScriptComponent* nsc) { - delete (T*)(nsc->instance); - nsc->instance = nullptr; - }; - } -}; - -} // namespace Light \ No newline at end of file diff --git a/Engine/src/Engine/Scene/Components/SpriteRendererComponent.hpp b/Engine/src/Engine/Scene/Components/SpriteRendererComponent.hpp deleted file mode 100644 index fb084b3..0000000 --- a/Engine/src/Engine/Scene/Components/SpriteRendererComponent.hpp +++ /dev/null @@ -1,25 +0,0 @@ -#pragma once - -#include "Base/Base.hpp" - -namespace Light { - -class Texture; - -struct SpriteRendererComponent -{ - Ref texture; - glm::vec4 tint; - - SpriteRendererComponent() = default; - SpriteRendererComponent(const SpriteRendererComponent&) = default; - - SpriteRendererComponent(Ref _texture, const glm::vec4& _tint = glm::vec4(1.0f, 1.0f, 1.0f, 1.0f)) - : texture(_texture), tint(_tint) - { - } - - operator Ref() { return texture; } -}; - -} // namespace Light diff --git a/Engine/src/Engine/Scene/Components/TagComponent.hpp b/Engine/src/Engine/Scene/Components/TagComponent.hpp deleted file mode 100644 index c9f502f..0000000 --- a/Engine/src/Engine/Scene/Components/TagComponent.hpp +++ /dev/null @@ -1,23 +0,0 @@ -#pragma once - -#include "Base/Base.hpp" - -namespace Light { - -struct TagComponent -{ - std::string tag = "Unnamed"; - - TagComponent() = default; - TagComponent(const TagComponent&) = default; - - TagComponent(const std::string& _tag) - : tag(_tag) - { - } - - operator std::string() { return tag; } - operator const std::string&() const { return tag; } -}; - -} // namespace Light diff --git a/Engine/src/Engine/Scene/Components/TransformComponent.hpp b/Engine/src/Engine/Scene/Components/TransformComponent.hpp deleted file mode 100644 index 1f359b5..0000000 --- a/Engine/src/Engine/Scene/Components/TransformComponent.hpp +++ /dev/null @@ -1,34 +0,0 @@ -#pragma once - -#define GLM_ENABLE_EXPERIMENTAL - -#include "Base/Base.hpp" - -#include -#include -#include - -namespace Light { - -struct TransformComponent -{ - glm::vec3 translation; - glm::vec3 scale; - glm::vec3 rotation; - - TransformComponent(const TransformComponent&) = default; - - TransformComponent(const glm::vec3& _translation = glm::vec3(0.0f, 0.0f, 0.0f), - const glm::vec3& _scale = glm::vec3(1.0f, 1.0f, 1.0f), - const glm::vec3& _rotation = glm::vec3(0.0f, 0.0f, 0.0f)) - - : translation(_translation), scale(_scale), rotation(_rotation) - { - } - - inline glm::mat4 GetTransform() const { return glm::translate(translation) * glm::rotate(rotation.z, glm::vec3(0.0f, 0.0f, 1.0f)) * glm::scale(scale); } - - operator const glm::mat4() const { return GetTransform(); } -}; - -} // namespace Light diff --git a/Engine/src/Engine/Scene/Components/UUIDComponent.hpp b/Engine/src/Engine/Scene/Components/UUIDComponent.hpp deleted file mode 100644 index 203c8da..0000000 --- a/Engine/src/Engine/Scene/Components/UUIDComponent.hpp +++ /dev/null @@ -1,17 +0,0 @@ -#pragma once - -#include "Base/Base.hpp" -#include "Core/UUID.hpp" - -namespace Light { - -struct UUIDComponent -{ - UUID uuid; - - UUIDComponent(UUID _uuid) - : uuid(_uuid) {} - UUIDComponent(const UUIDComponent&) = default; -}; - -} // namespace Light \ No newline at end of file diff --git a/Engine/src/Engine/Scene/Entity.cpp b/Engine/src/Engine/Scene/Entity.cpp deleted file mode 100644 index 22ad370..0000000 --- a/Engine/src/Engine/Scene/Entity.cpp +++ /dev/null @@ -1,16 +0,0 @@ -#include "Entity.hpp" - -#include "Scene.hpp" - -namespace Light { - -Entity::Entity(entt::entity handle, Scene* scene) - : m_Handle(handle), m_Scene(scene) -{ -} - -Entity::~Entity() -{ -} - -} // namespace Light \ No newline at end of file diff --git a/Engine/src/Engine/Scene/Scene.hpp b/Engine/src/Engine/Scene/Scene.hpp deleted file mode 100644 index 84dfd1c..0000000 --- a/Engine/src/Engine/Scene/Scene.hpp +++ /dev/null @@ -1,43 +0,0 @@ -#pragma once - -#include "Base/Base.hpp" -#include "Components/TransformComponent.hpp" -#include "Core/UUID.hpp" - -#include -#include - -namespace Light { - -class Entity; - -class Framebuffer; - -class Scene -{ -private: - friend class Entity; - friend class SceneSerializer; - friend class SceneHierarchyPanel; - -private: - entt::registry m_Registry; - -public: - Scene(); - ~Scene(); - - void OnCreate(); - - void OnUpdate(float deltaTime); - void OnRender(const Ref& targetFrameBuffer = nullptr); - - Entity CreateEntity(const std::string& name, const TransformComponent& transform = TransformComponent()); - - Entity GetEntityByTag(const std::string& tag); - -private: - Entity CreateEntityWithUUID(const std::string& name, UUID uuid, const TransformComponent& transform = TransformComponent()); -}; - -} // namespace Light \ No newline at end of file diff --git a/Engine/src/Engine/Time/Timer.cpp b/Engine/src/Engine/Time/Timer.cpp deleted file mode 100644 index e4f1fa8..0000000 --- a/Engine/src/Engine/Time/Timer.cpp +++ /dev/null @@ -1,22 +0,0 @@ -#include "Timer.hpp" - -namespace Light { - -Timer::Timer() - : m_Start(std::chrono::steady_clock::now()) -{ -} - -DeltaTimer::DeltaTimer() - : m_PreviousFrame(NULL), m_DeltaTime(60.0f / 1000.0f) -{ -} - -void DeltaTimer::Update() -{ - float currentFrame = timer.GetElapsedTime(); - m_DeltaTime = currentFrame - m_PreviousFrame; - m_PreviousFrame = currentFrame; -} - -} // namespace Light \ No newline at end of file diff --git a/Engine/src/Engine/Time/Timer.hpp b/Engine/src/Engine/Time/Timer.hpp deleted file mode 100644 index d056586..0000000 --- a/Engine/src/Engine/Time/Timer.hpp +++ /dev/null @@ -1,38 +0,0 @@ -#pragma once - -#include "Base/Base.hpp" - -#include - -namespace Light { - -class Timer -{ -private: - std::chrono::time_point m_Start; - -public: - Timer(); - - inline float GetElapsedTime() const { return (std::chrono::duration_cast(std::chrono::steady_clock::now() - m_Start).count()) / 1000.; } - - inline void Reset() { m_Start = std::chrono::steady_clock::now(); } -}; - -class DeltaTimer -{ -private: - Timer timer; - - float m_PreviousFrame; - float m_DeltaTime; - -public: - DeltaTimer(); - - void Update(); - - inline float GetDeltaTime() const { return m_DeltaTime; } -}; - -} // namespace Light \ No newline at end of file diff --git a/Engine/src/Engine/UserInterface/UserInterface.cpp b/Engine/src/Engine/UserInterface/UserInterface.cpp deleted file mode 100644 index c3ce3ff..0000000 --- a/Engine/src/Engine/UserInterface/UserInterface.cpp +++ /dev/null @@ -1,222 +0,0 @@ -#include "UserInterface.hpp" - -#include "OpenGL/glUserInterface.hpp" - -#ifdef LIGHT_PLATFORM_WINDOWS - #include "DirectX/dxSharedContext.hpp" - #include "DirectX/dxUserInterface.hpp" -#endif - -#include "Events/CharEvent.hpp" -#include "Events/Event.hpp" -#include "Events/KeyboardEvents.hpp" -#include "Events/MouseEvents.hpp" -#include "Graphics/GraphicsContext.hpp" -#include "Input/KeyCodes.hpp" - -#include - -namespace Light { - -UserInterface* UserInterface::s_Context = nullptr; - -Scope UserInterface::Create(GLFWwindow* windowHandle, Ref sharedContext) -{ - Scope scopeUserInterface = nullptr; - - switch (GraphicsContext::GetGraphicsAPI()) - { - case GraphicsAPI::OpenGL: - scopeUserInterface = CreateScope(); - break; - - case GraphicsAPI::DirectX: - LT_WIN( - scopeUserInterface = CreateScope();) - break; - - default: - ASSERT(false, "UserInterface::Create: invalid/unsupported 'GraphicsAPI' {}", static_cast(GraphicsContext::GetGraphicsAPI())); - return nullptr; - } - - scopeUserInterface->Init(windowHandle, sharedContext); - return std::move(scopeUserInterface); -} - -UserInterface::UserInterface() - : m_DockspaceFlags(ImGuiWindowFlags_MenuBar | ImGuiWindowFlags_NoDocking | ImGuiWindowFlags_NoTitleBar | - ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | - ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus) -{ - ASSERT(!s_Context, "UserInterface::UserInterface: an instance of 'UserInterface' already exists, do not construct this class!"); - s_Context = this; -} - -void UserInterface::Init(GLFWwindow* windowHandle, Ref sharedContext) -{ - // create context - IMGUI_CHECKVERSION(); - ImGui::CreateContext(); - - // configure io - ImGuiIO& io = ImGui::GetIO(); - io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; - - io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; - io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable; - - io.ConfigFlags |= ImGuiBackendFlags_PlatformHasViewports; - io.ConfigFlags |= ImGuiBackendFlags_RendererHasViewports; - - // #todo: handle this in a better way - if (std::filesystem::exists("user_gui_layout.ini")) - io.IniFilename = "user_gui_layout.ini"; - else - io.IniFilename = "default_gui_layout.ini"; - - // style - ImGui::StyleColorsDark(); - - PlatformImplementation(windowHandle, sharedContext); - - // keyboard map - io.KeyMap[ImGuiKey_Tab] = Key::Tab; - io.KeyMap[ImGuiKey_LeftArrow] = Key::LeftArrow; - io.KeyMap[ImGuiKey_RightArrow] = Key::RightArrow; - io.KeyMap[ImGuiKey_UpArrow] = Key::UpArrow; - io.KeyMap[ImGuiKey_DownArrow] = Key::DownArrow; - io.KeyMap[ImGuiKey_PageUp] = Key::PageUp; - io.KeyMap[ImGuiKey_PageDown] = Key::PageDown; - io.KeyMap[ImGuiKey_Home] = Key::Home; - io.KeyMap[ImGuiKey_End] = Key::End; - io.KeyMap[ImGuiKey_Insert] = Key::Insert; - io.KeyMap[ImGuiKey_Delete] = Key::Delete; - io.KeyMap[ImGuiKey_Backspace] = Key::BackSpace; - io.KeyMap[ImGuiKey_Space] = Key::Space; - io.KeyMap[ImGuiKey_Enter] = Key::Enter; - io.KeyMap[ImGuiKey_Escape] = Key::Escape; - io.KeyMap[ImGuiKey_KeyPadEnter] = Key::Enter; - io.KeyMap[ImGuiKey_A] = Key::A; - io.KeyMap[ImGuiKey_C] = Key::C; - io.KeyMap[ImGuiKey_V] = Key::V; - io.KeyMap[ImGuiKey_X] = Key::X; - io.KeyMap[ImGuiKey_Y] = Key::Y; - io.KeyMap[ImGuiKey_Z] = Key::Z; - - io.Fonts->AddFontFromFileTTF("Assets//Fonts/OpenSans/OpenSans-Bold.ttf", 18.0f); - io.FontDefault = io.Fonts->AddFontFromFileTTF("Assets/Fonts/OpenSans/OpenSans-Regular.ttf", 18.0f); - - SetDarkThemeColors(); -} - -void UserInterface::DockspaceBegin() -{ - ImGuiViewport* viewport = ImGui::GetMainViewport(); - ImGui::SetNextWindowPos(viewport->Pos); - ImGui::SetNextWindowSize(viewport->Size); - ImGui::SetNextWindowViewport(viewport->ID); - - ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f); - ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f); - ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f)); - ImGui::Begin("Dockspace", (bool*)0, s_Context->m_DockspaceFlags); - ImGui::PopStyleVar(3); - - ImGuiStyle& style = ImGui::GetStyle(); - float minWinSizeX = style.WindowMinSize.x; - style.WindowMinSize.x = 370.0f; - ImGui::DockSpace(ImGui::GetID("MyDockSpace"), ImVec2(0.0f, 0.0f), ImGuiDockNodeFlags_None | ImGuiWindowFlags_NoBackground); - style.WindowMinSize.x = minWinSizeX; -} - -void UserInterface::DockspaceEnd() -{ - ImGui::End(); -} - -void UserInterface::SetDarkThemeColors() -{ - ImGuiStyle& style = ImGui::GetStyle(); - ImVec4(&colors)[55] = style.Colors; - - style.WindowPadding = ImVec2(0.0f, 0.0f); - - colors[ImGuiCol_Text] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); - colors[ImGuiCol_TextDisabled] = ImVec4(0.50f, 0.50f, 0.50f, 1.00f); - - colors[ImGuiCol_WindowBg] = ImVec4(0.10f, 0.10f, 0.11f, 1.00f); - colors[ImGuiCol_ChildBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); - colors[ImGuiCol_PopupBg] = ImVec4(0.08f, 0.08f, 0.08f, 0.94f); - - colors[ImGuiCol_Border] = ImVec4(0.43f, 0.43f, 0.50f, 0.50f); - colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); - - colors[ImGuiCol_FrameBg] = ImVec4(0.20f, 0.20f, 0.21f, 1.00f); - colors[ImGuiCol_FrameBgHovered] = ImVec4(0.30f, 0.31f, 0.31f, 1.00f); - colors[ImGuiCol_FrameBgActive] = ImVec4(0.15f, 0.15f, 0.15f, 1.00f); - - colors[ImGuiCol_TitleBg] = ImVec4(0.15f, 0.15f, 0.15f, 1.00f); - colors[ImGuiCol_TitleBgActive] = ImVec4(0.15f, 0.15f, 0.15f, 1.00f); - colors[ImGuiCol_TitleBgCollapsed] = ImVec4(0.15f, 0.15f, 0.15f, 1.00f); - - colors[ImGuiCol_MenuBarBg] = ImVec4(0.14f, 0.14f, 0.14f, 1.00f); - - colors[ImGuiCol_ScrollbarBg] = ImVec4(0.02f, 0.02f, 0.02f, 0.53f); - colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.31f, 0.31f, 0.31f, 1.00f); - colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(0.41f, 0.41f, 0.41f, 1.00f); - colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(0.51f, 0.51f, 0.51f, 1.00f); - - colors[ImGuiCol_CheckMark] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f); - - colors[ImGuiCol_SliderGrab] = ImVec4(0.24f, 0.52f, 0.88f, 1.00f); - colors[ImGuiCol_SliderGrabActive] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f); - - colors[ImGuiCol_Button] = ImVec4(0.20f, 0.20f, 0.21f, 1.00f); - colors[ImGuiCol_ButtonHovered] = ImVec4(0.30f, 0.31f, 0.31f, 1.00f); - colors[ImGuiCol_ButtonActive] = ImVec4(0.15f, 0.15f, 0.15f, 1.00f); - - colors[ImGuiCol_Header] = ImVec4(0.20f, 0.20f, 0.21f, 1.00f); - colors[ImGuiCol_HeaderHovered] = ImVec4(0.30f, 0.31f, 0.31f, 1.00f); - colors[ImGuiCol_HeaderActive] = ImVec4(0.15f, 0.15f, 0.15f, 1.00f); - - colors[ImGuiCol_Separator] = ImVec4(0.43f, 0.43f, 0.50f, 0.50f); - colors[ImGuiCol_SeparatorHovered] = ImVec4(0.10f, 0.40f, 0.75f, 0.78f); - colors[ImGuiCol_SeparatorActive] = ImVec4(0.10f, 0.40f, 0.75f, 1.00f); - - colors[ImGuiCol_ResizeGrip] = ImVec4(0.26f, 0.59f, 0.98f, 0.20f); - colors[ImGuiCol_ResizeGripHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.67f); - colors[ImGuiCol_ResizeGripActive] = ImVec4(0.26f, 0.59f, 0.98f, 0.95f); - - colors[ImGuiCol_Tab] = ImVec4(0.15f, 0.15f, 0.15f, 1.00f); - colors[ImGuiCol_TabHovered] = ImVec4(0.38f, 0.38f, 0.38f, 1.00f); - colors[ImGuiCol_TabActive] = ImVec4(0.28f, 0.28f, 0.28f, 1.00f); - colors[ImGuiCol_TabUnfocused] = ImVec4(0.15f, 0.15f, 0.15f, 1.00f); - colors[ImGuiCol_TabUnfocusedActive] = ImVec4(0.20f, 0.20f, 0.21f, 1.00f); - - colors[ImGuiCol_DockingPreview] = ImVec4(0.26f, 0.59f, 0.98f, 0.70f); - colors[ImGuiCol_DockingEmptyBg] = ImVec4(0.20f, 0.20f, 0.20f, 1.00f); - - colors[ImGuiCol_PlotLines] = ImVec4(0.61f, 0.61f, 0.61f, 1.00f); - colors[ImGuiCol_PlotLinesHovered] = ImVec4(1.00f, 0.43f, 0.35f, 1.00f); - colors[ImGuiCol_PlotHistogram] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f); - colors[ImGuiCol_PlotHistogramHovered] = ImVec4(1.00f, 0.60f, 0.00f, 1.00f); - - colors[ImGuiCol_TableHeaderBg] = ImVec4(0.19f, 0.19f, 0.20f, 1.00f); - colors[ImGuiCol_TableBorderStrong] = ImVec4(0.31f, 0.31f, 0.35f, 1.00f); - colors[ImGuiCol_TableBorderLight] = ImVec4(0.23f, 0.23f, 0.25f, 1.00f); - colors[ImGuiCol_TableRowBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); - colors[ImGuiCol_TableRowBgAlt] = ImVec4(1.00f, 1.00f, 1.00f, 0.06f); - - colors[ImGuiCol_TextSelectedBg] = ImVec4(0.26f, 0.59f, 0.98f, 0.35f); - - colors[ImGuiCol_DragDropTarget] = ImVec4(1.00f, 1.00f, 0.00f, 0.90f); - - colors[ImGuiCol_NavHighlight] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f); - colors[ImGuiCol_NavWindowingHighlight] = ImVec4(1.00f, 1.00f, 1.00f, 0.70f); - colors[ImGuiCol_NavWindowingDimBg] = ImVec4(0.80f, 0.80f, 0.80f, 0.20f); - - colors[ImGuiCol_ModalWindowDimBg] = ImVec4(0.80f, 0.80f, 0.80f, 0.35f); -} - -} // namespace Light diff --git a/Engine/src/Engine/Utility/FileManager.cpp b/Engine/src/Engine/Utility/FileManager.cpp deleted file mode 100644 index c4a9f07..0000000 --- a/Engine/src/Engine/Utility/FileManager.cpp +++ /dev/null @@ -1,81 +0,0 @@ -#define STB_IMAGE_IMPLEMENTATION -#include "FileManager.hpp" - -#include - -namespace Light { - -BasicFileHandle::BasicFileHandle(uint8_t* data, uint32_t size, const std::string& path, const std::string& name, const std::string& extension) - : m_Data(data), m_Size(size), m_Path(path), m_Name(name), m_Extension(extension) -{ -} - -void BasicFileHandle::Release() -{ - delete m_Data; - m_Data = nullptr; - m_Size = 0ull; -} - - -BasicFileHandle FileManager::ReadTextFile(const std::string& path) -{ - // parse path info - std::string name = path.substr(0, path.find('.') + -1); - std::string extension = path.substr(path.find('.') + 1); - - // open file - std::ifstream file(path.c_str(), std::ios_base::in | std::ios_base::binary); - - // check - if (!file) - { - LOG(warn, "Failed to load text file: {}", path); - file.close(); - return NULL; - } - - // fetch file size - file.seekg(0, std::ios::end); - uint32_t size = file.tellg(); - file.seekg(0, std::ios::beg); - - if (!size) - LOG(warn, "Empty text file: {}", path); - - // read file - uint8_t* data = new uint8_t[size]; - file.read(reinterpret_cast(data), size); - - file.close(); - return BasicFileHandle(data, size, path, name, extension); -} - -ImageFileHandle FileManager::ReadImageFile(const std::string& path, int32_t desiredComponents) -{ - // parse path info - std::string name = path.substr(0, path.find('.') + -1); - std::string extension = path.substr(path.find('.') + 1); - - // load image - int32_t width = 0, height = 0, fetchedComponents = 0; - uint8_t* pixels = stbi_load(path.c_str(), &width, &height, &fetchedComponents, desiredComponents); - - // check - if (!pixels) - LOG(warn, "Failed to load image file: <{}>", path); - else if (fetchedComponents != desiredComponents) - LOG(warn, "Mismatch of fetched/desired components: <{}> ({}/{})", name + '.' + extension, fetchedComponents, desiredComponents); - - return ImageFileHandle(pixels, width * height, path, name, extension, width, height, fetchedComponents, desiredComponents); -} - -void ImageFileHandle::Release() -{ - stbi_image_free(reinterpret_cast(m_Data)); - m_Data = nullptr; - m_Size = 0ull; -} - - -} // namespace Light diff --git a/Engine/src/Engine/Utility/FileManager.hpp b/Engine/src/Engine/Utility/FileManager.hpp deleted file mode 100644 index b6047eb..0000000 --- a/Engine/src/Engine/Utility/FileManager.hpp +++ /dev/null @@ -1,66 +0,0 @@ -#pragma once - -#include "Base/Base.hpp" - -namespace Light { - -class BasicFileHandle -{ -public: - BasicFileHandle(uint8_t* data = nullptr, uint32_t size = 0ull, const std::string& path = "", const std::string& name = "", const std::string& extension = ""); - - virtual void Release(); - - // getters - inline uint8_t* GetData() { return m_Data; } - inline uint32_t GetSize() { return m_Size; } - - inline const std::string& GetPath() { return m_Path; } - inline const std::string& GetName() { return m_Name; } - inline const std::string& GetExtension() { return m_Extension; } - - inline const std::string& GetNameWithExtension() { return m_Name + '.' + m_Extension; } - - inline bool IsValid() const { return !!m_Data; } - - // operators - inline operator bool() const { return IsValid(); } - -protected: - // made protected for custom Free(): - uint8_t* m_Data; - uint32_t m_Size; - -private: - const std::string m_Path, m_Name, m_Extension; -}; - -class ImageFileHandle: public BasicFileHandle -{ -public: - ImageFileHandle(uint8_t* data, uint32_t size, const std::string& path, const std::string& name, const std::string& extension, - uint32_t width, uint32_t height, uint32_t components, uint32_t desiredComponents) - : BasicFileHandle(data, size, path, name, extension), m_Width(width), m_Height(height), m_Components(components), m_DesiredComponents(desiredComponents) - { - } - - void Release() override; - - // getters - inline uint32_t GetWidth() const { return m_Width; } - inline uint32_t GetHeight() const { return m_Height; } - inline uint32_t GetComponents() const { return m_Components; } - inline uint32_t GetDesiredComponents() const { return m_DesiredComponents; } - -private: - uint32_t m_Width, m_Height, m_Components, m_DesiredComponents; -}; - -class FileManager -{ -public: - static BasicFileHandle ReadTextFile(const std::string& path); - static ImageFileHandle ReadImageFile(const std::string& path, int32_t desiredComponents); -}; - -} // namespace Light diff --git a/Engine/src/Engine/Utility/ResourceManager.cpp b/Engine/src/Engine/Utility/ResourceManager.cpp deleted file mode 100644 index 64ae833..0000000 --- a/Engine/src/Engine/Utility/ResourceManager.cpp +++ /dev/null @@ -1,72 +0,0 @@ -#include "ResourceManager.hpp" - -#include "FileManager.hpp" -#include "Graphics/GraphicsContext.hpp" -#include "Graphics/Shader.hpp" -#include "Graphics/Texture.hpp" - -namespace Light { - -ResourceManager* ResourceManager::s_Context = nullptr; - -Scope ResourceManager::Create() -{ - return MakeScope(new ResourceManager()); -} - -ResourceManager::ResourceManager() - : m_Shaders {}, m_Textures {} -{ - ASSERT(!s_Context, "Repeated singleton construction"); - s_Context = this; -} - -void ResourceManager::LoadShaderImpl(const std::string& name, const std::string& vertexPath, const std::string& pixelPath) -{ - // check - ASSERT(s_Context, "Uninitliazed singleton"); - ASSERT(!vertexPath.empty(), "Empty 'vertexPath'"); - ASSERT(!pixelPath.empty(), "Empty 'pixelPath'"); - - // load files - BasicFileHandle vertexFile = FileManager::ReadTextFile(vertexPath); - BasicFileHandle pixelFile = FileManager::ReadTextFile(pixelPath); - - // check - ASSERT(vertexFile.IsValid(), "Failed to read vertex file: {}", vertexPath); - ASSERT(pixelFile.IsValid(), "Failed to read vertex file: {}", pixelPath); - - // create shader - m_Shaders[name] = Ref(Shader::Create(vertexFile, pixelFile, GraphicsContext::GetSharedContext())); - - // free file - vertexFile.Release(); - pixelFile.Release(); -} - -void ResourceManager::LoadTextureImpl(const std::string& name, const std::string& path, unsigned int desiredComponents /* = 4u */) -{ - ASSERT(s_Context, "Uninitliazed singleton"); - - // load file - ImageFileHandle imgFile = FileManager::ReadImageFile(path, desiredComponents); - - // create texture - m_Textures[name] = Ref(Texture::Create(imgFile.GetWidth(), imgFile.GetHeight(), imgFile.GetComponents(), imgFile.GetData(), GraphicsContext::GetSharedContext(), path)); - - // free file - imgFile.Release(); -} - -void ResourceManager::ReleaseTextureImpl(const std::string& name) -{ - if (!m_Textures[name]) - { - LOG(warn, "Failed to find texture named: {}", name); - return; - } - - m_Textures[name] = nullptr; -} - -} // namespace Light diff --git a/Engine/src/Engine/Utility/ResourceManager.hpp b/Engine/src/Engine/Utility/ResourceManager.hpp deleted file mode 100644 index ed2bf34..0000000 --- a/Engine/src/Engine/Utility/ResourceManager.hpp +++ /dev/null @@ -1,44 +0,0 @@ -#pragma once - -#include "Base/Base.hpp" - -namespace Light { - -class Shader; -class Texture; - -class SharedContext; - -class ResourceManager /* singleton */ -{ -private: - static ResourceManager* s_Context; - -private: - std::unordered_map> m_Shaders; - std::unordered_map> m_Textures; - -public: - static Scope Create(); - - // #todo: add geometry shader support - static inline void LoadShader(const std::string& name, const std::string& vertexPath, const std::string& pixelPath) { s_Context->LoadShaderImpl(name, vertexPath, pixelPath); } - - static inline void LoadTexture(const std::string& name, const std::string& path, unsigned int desiredComponents = 4u) { s_Context->LoadTextureImpl(name, path, desiredComponents); } - - static inline void ReleaseTexture(const std::string& name) { s_Context->ReleaseTextureImpl(name); } - - static inline Ref GetShader(const std::string& name) { return s_Context->m_Shaders[name]; } - static inline Ref GetTexture(const std::string& name) { return s_Context->m_Textures[name]; } - -private: - ResourceManager(); - - void LoadShaderImpl(const std::string& name, const std::string& vertexPath, const std::string& pixelPath); - - void LoadTextureImpl(const std::string& name, const std::string& path, unsigned int desiredComponents = 4u); - - void ReleaseTextureImpl(const std::string& name); -}; - -} // namespace Light \ No newline at end of file diff --git a/Engine/src/Engine/Utility/Serializer.hpp b/Engine/src/Engine/Utility/Serializer.hpp deleted file mode 100644 index 906aa30..0000000 --- a/Engine/src/Engine/Utility/Serializer.hpp +++ /dev/null @@ -1,30 +0,0 @@ -#pragma once - -#include "Base/Base.hpp" -#include "Scene/Entity.hpp" -#include "Scene/Scene.hpp" - -#include - -namespace Light { - -class SceneSerializer -{ -public: - SceneSerializer(const Ref& scene); - - void Serialize(const std::string& filePath); - bool Deserialize(const std::string& filePath); - - void SerializeBinary(const std::string& filePath); - bool DeserializeBinary(const std::string& filePath); - -private: - void SerializeEntity(YAML::Emitter& out, Entity entity); - -private: - Ref m_Scene; -}; - - -} // namespace Light \ No newline at end of file diff --git a/Engine/src/Engine/ltpch.cpp b/Engine/src/Engine/ltpch.cpp deleted file mode 100644 index 0a753c2..0000000 --- a/Engine/src/Engine/ltpch.cpp +++ /dev/null @@ -1 +0,0 @@ -#include "ltpch.hpp" \ No newline at end of file diff --git a/Engine/src/Platform/GraphicsAPI/DirectX/dxFramebuffer.cpp b/Engine/src/Platform/GraphicsAPI/DirectX/dxFramebuffer.cpp deleted file mode 100644 index 0da490f..0000000 --- a/Engine/src/Platform/GraphicsAPI/DirectX/dxFramebuffer.cpp +++ /dev/null @@ -1,94 +0,0 @@ -#include "dxFramebuffer.hpp" - -#include "dxSharedContext.hpp" - -namespace Light { - -dxFramebuffer::dxFramebuffer(const FramebufferSpecification& specification, Ref sharedContext) - : m_Context(sharedContext), m_Specification(specification), m_RenderTargetView(nullptr), m_ColorAttachment(nullptr), m_DepthStencilAttachment(nullptr), m_ShaderResourceView(nullptr), m_DepthStencilView(nullptr) -{ - HRESULT hr; - - D3D11_TEXTURE2D_DESC t2dDesc = {}; - t2dDesc.Width = specification.width; - t2dDesc.Height = specification.height; - t2dDesc.MipLevels = 1; - t2dDesc.ArraySize = 1; - t2dDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; - t2dDesc.SampleDesc.Count = 1u; - t2dDesc.SampleDesc.Quality = 0u; - t2dDesc.Usage = D3D11_USAGE_DEFAULT; - t2dDesc.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE; - t2dDesc.CPUAccessFlags = NULL; - t2dDesc.MiscFlags = NULL; - DXC(m_Context->GetDevice()->CreateTexture2D(&t2dDesc, nullptr, &m_ColorAttachment)); - - D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc = {}; - srvDesc.Format = t2dDesc.Format; - srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; - srvDesc.Texture2D.MipLevels = 1; - srvDesc.Texture2D.MostDetailedMip = 0; - DXC(m_Context->GetDevice()->CreateShaderResourceView(m_ColorAttachment.Get(), &srvDesc, &m_ShaderResourceView)); - - D3D11_RENDER_TARGET_VIEW_DESC rtvDesc = {}; - rtvDesc.Format = t2dDesc.Format; - rtvDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D; - rtvDesc.Texture2D.MipSlice = 0u; - DXC(m_Context->GetDevice()->CreateRenderTargetView(m_ColorAttachment.Get(), &rtvDesc, &m_RenderTargetView)); -} - -void dxFramebuffer::BindAsTarget(const glm::vec4& clearColor) -{ - FLOAT color[] = { - clearColor.r, - clearColor.g, - clearColor.b, - clearColor.a, - }; - - m_Context->GetDeviceContext()->OMSetRenderTargets(1u, m_RenderTargetView.GetAddressOf(), nullptr); - m_Context->GetDeviceContext()->ClearRenderTargetView(m_RenderTargetView.Get(), color); - - D3D11_VIEWPORT viewport; - - viewport.TopLeftX = 0; - viewport.TopLeftY = 0; - - viewport.Width = m_Specification.width; - viewport.Height = m_Specification.height; - - viewport.MinDepth = 0.0f; - viewport.MaxDepth = 1.0f; - - // set viewport - m_Context->GetDeviceContext()->RSSetViewports(1u, &viewport); -} - -void dxFramebuffer::BindAsResource() -{ - LOG(err, "NO_IMPLEMENT"); -} - -void dxFramebuffer::Resize(const glm::uvec2& size) -{ - m_Specification.width = std::clamp(size.x, 1u, 16384u); - m_Specification.height = std::clamp(size.y, 1u, 16384u); - - D3D11_TEXTURE2D_DESC textureDesc; - D3D11_RENDER_TARGET_VIEW_DESC rtvDesc; - D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc; - - m_ColorAttachment->GetDesc(&textureDesc); - m_RenderTargetView->GetDesc(&rtvDesc); - m_ShaderResourceView->GetDesc(&srvDesc); - - textureDesc.Width = m_Specification.width; - textureDesc.Height = m_Specification.height; - - HRESULT hr; - DXC(m_Context->GetDevice()->CreateTexture2D(&textureDesc, nullptr, &m_ColorAttachment)); - DXC(m_Context->GetDevice()->CreateRenderTargetView(m_ColorAttachment.Get(), &rtvDesc, &m_RenderTargetView)); - DXC(m_Context->GetDevice()->CreateShaderResourceView(m_ColorAttachment.Get(), &srvDesc, &m_ShaderResourceView)); -} - -} // namespace Light diff --git a/Engine/src/Platform/GraphicsAPI/DirectX/dxShader.cpp b/Engine/src/Platform/GraphicsAPI/DirectX/dxShader.cpp deleted file mode 100644 index b1409b9..0000000 --- a/Engine/src/Platform/GraphicsAPI/DirectX/dxShader.cpp +++ /dev/null @@ -1,45 +0,0 @@ -#include "dxShader.hpp" - -#include "dxSharedContext.hpp" - -#include - -namespace Light { - -dxShader::dxShader(BasicFileHandle vertexFile, BasicFileHandle pixelFile, Ref sharedContext) - : m_Context(sharedContext), m_VertexShader(nullptr), m_PixelShader(nullptr), m_VertexBlob(nullptr) -{ - Microsoft::WRL::ComPtr ps = nullptr, vsErr = nullptr, psErr = nullptr; - - // compile shaders (we don't use DXC here because if D3DCompile fails it throws a dxException without logging the vsErr/psErr - D3DCompile(vertexFile.GetData(), vertexFile.GetSize(), NULL, nullptr, nullptr, "main", "vs_4_0", NULL, NULL, &m_VertexBlob, &vsErr); - D3DCompile(pixelFile.GetData(), pixelFile.GetSize(), NULL, nullptr, nullptr, "main", "ps_4_0", NULL, NULL, &ps, &psErr); - - // check - ASSERT(!vsErr.Get(), "Vertex shader compile error: {}", (char*)vsErr->GetBufferPointer()); - ASSERT(!psErr.Get(), "Pixels shader compile error: {}", (char*)psErr->GetBufferPointer()); - - // create shaders - HRESULT hr; - DXC(m_Context->GetDevice()->CreateVertexShader(m_VertexBlob->GetBufferPointer(), m_VertexBlob->GetBufferSize(), NULL, &m_VertexShader)); - DXC(m_Context->GetDevice()->CreatePixelShader(ps->GetBufferPointer(), ps->GetBufferSize(), NULL, &m_PixelShader)); -} - -dxShader::~dxShader() -{ - UnBind(); -} - -void dxShader::Bind() -{ - m_Context->GetDeviceContext()->VSSetShader(m_VertexShader.Get(), nullptr, 0u); - m_Context->GetDeviceContext()->PSSetShader(m_PixelShader.Get(), nullptr, 0u); -} - -void dxShader::UnBind() -{ - m_Context->GetDeviceContext()->VSSetShader(nullptr, nullptr, 0u); - m_Context->GetDeviceContext()->PSSetShader(nullptr, nullptr, 0u); -} - -} // namespace Light diff --git a/Engine/src/Platform/GraphicsAPI/DirectX/dxSharedContext.hpp b/Engine/src/Platform/GraphicsAPI/DirectX/dxSharedContext.hpp deleted file mode 100644 index 9f08f06..0000000 --- a/Engine/src/Platform/GraphicsAPI/DirectX/dxSharedContext.hpp +++ /dev/null @@ -1,31 +0,0 @@ -#pragma once - -#include "Base/Base.hpp" -#include "Graphics/SharedContext.hpp" - -#include -#include - -namespace Light { - -class dxSharedContext: public SharedContext -{ -private: - Microsoft::WRL::ComPtr m_Device = nullptr; - Microsoft::WRL::ComPtr m_DeviceContext = nullptr; - Microsoft::WRL::ComPtr m_SwapChain = nullptr; - Microsoft::WRL::ComPtr m_RenderTargetView = nullptr; - -public: - inline Microsoft::WRL::ComPtr GetDevice() { return m_Device; } - inline Microsoft::WRL::ComPtr GetDeviceContext() { return m_DeviceContext; } - inline Microsoft::WRL::ComPtr GetSwapChain() { return m_SwapChain; } - inline Microsoft::WRL::ComPtr GetRenderTargetView() { return m_RenderTargetView; } - - inline Microsoft::WRL::ComPtr& GetDeviceRef() { return m_Device; } - inline Microsoft::WRL::ComPtr& GetDeviceContextRef() { return m_DeviceContext; } - inline Microsoft::WRL::ComPtr& GetSwapChainRef() { return m_SwapChain; } - inline Microsoft::WRL::ComPtr& GetRenderTargetViewRef() { return m_RenderTargetView; } -}; - -} // namespace Light \ No newline at end of file diff --git a/Engine/src/Platform/GraphicsAPI/DirectX/dxTexture.cpp b/Engine/src/Platform/GraphicsAPI/DirectX/dxTexture.cpp deleted file mode 100644 index 8194aef..0000000 --- a/Engine/src/Platform/GraphicsAPI/DirectX/dxTexture.cpp +++ /dev/null @@ -1,67 +0,0 @@ -#include "dxTexture.hpp" - -#include "dxSharedContext.hpp" - -namespace Light { - -dxTexture::dxTexture(unsigned int width, unsigned int height, unsigned int components, unsigned char* pixels, Ref sharedContext, const std::string& filePath) - : Texture(filePath), m_Context(sharedContext), m_Texture2D(nullptr), m_ShaderResourceView(nullptr), m_SamplerState(nullptr) -{ - // texture2d desc - D3D11_TEXTURE2D_DESC t2dDesc = {}; - t2dDesc.Width = width; - t2dDesc.Height = height; - t2dDesc.MipLevels = 0u; - t2dDesc.ArraySize = 1u; - t2dDesc.Format = components == 4u ? DXGI_FORMAT_R8G8B8A8_UNORM : - components == 3u ? DXGI_FORMAT_R8G8B8A8_UNORM : - // #todo: figure out what to do with this bitch ._. - components == 2u ? DXGI_FORMAT_R8G8_UNORM : - components == 1u ? DXGI_FORMAT_R8_UNORM : - DXGI_FORMAT_UNKNOWN; - t2dDesc.SampleDesc.Count = 1u; - t2dDesc.SampleDesc.Quality = 0u; - t2dDesc.Usage = D3D11_USAGE_DEFAULT; - t2dDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET; - t2dDesc.CPUAccessFlags = NULL; - t2dDesc.MiscFlags = D3D11_RESOURCE_MISC_GENERATE_MIPS; - - // create texture - HRESULT hr; - DXC(m_Context->GetDevice()->CreateTexture2D(&t2dDesc, nullptr, &m_Texture2D)); - m_Context->GetDeviceContext()->UpdateSubresource(m_Texture2D.Get(), 0u, nullptr, pixels, width * 4u, 0u); - - m_Texture2D->GetDesc(&t2dDesc); - - // shader resource view desc - D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc = {}; - srvDesc.Format = t2dDesc.Format; - srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; - srvDesc.Texture2D.MostDetailedMip = 0u; - srvDesc.Texture2D.MipLevels = -1; - - // create shader resource view - m_Context->GetDevice()->CreateShaderResourceView(m_Texture2D.Get(), &srvDesc, &m_ShaderResourceView); - m_Context->GetDeviceContext()->GenerateMips(m_ShaderResourceView.Get()); - - // sampler desc - D3D11_SAMPLER_DESC sDesc = {}; - sDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; - sDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; - sDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; - sDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; - sDesc.MinLOD = 0.0f; - sDesc.MipLODBias = 0.0f; - sDesc.MaxLOD = D3D11_FLOAT32_MAX; - - // create sampler - m_Context->GetDevice()->CreateSamplerState(&sDesc, &m_SamplerState); -} - -void dxTexture::Bind(unsigned int slot /* = 0u */) -{ - m_Context->GetDeviceContext()->PSSetSamplers(slot, 1u, m_SamplerState.GetAddressOf()); - m_Context->GetDeviceContext()->PSSetShaderResources(slot, 1u, m_ShaderResourceView.GetAddressOf()); -} - -} // namespace Light \ No newline at end of file diff --git a/Engine/src/Platform/GraphicsAPI/OpenGL/glFramebuffer.hpp b/Engine/src/Platform/GraphicsAPI/OpenGL/glFramebuffer.hpp deleted file mode 100644 index 19ec718..0000000 --- a/Engine/src/Platform/GraphicsAPI/OpenGL/glFramebuffer.hpp +++ /dev/null @@ -1,28 +0,0 @@ -#pragma once - -#include "Base/Base.hpp" -#include "Graphics/Framebuffer.hpp" - -namespace Light { - -class glFramebuffer: public Framebuffer -{ -private: - FramebufferSpecification m_Specification; - - unsigned int m_BufferID; - unsigned int m_ColorAttachmentID, m_DepthStencilAttachmentID; - -public: - glFramebuffer(const FramebufferSpecification& specification); - ~glFramebuffer(); - - void BindAsTarget(const glm::vec4& clearColor) override; - void BindAsResource() override; - - void Resize(const glm::uvec2& size) override; - - inline void* GetColorAttachment() override { return (void*)m_ColorAttachmentID; } -}; - -} // namespace Light \ No newline at end of file diff --git a/Engine/src/Platform/GraphicsAPI/OpenGL/glGraphicsContext.cpp b/Engine/src/Platform/GraphicsAPI/OpenGL/glGraphicsContext.cpp deleted file mode 100644 index aac787f..0000000 --- a/Engine/src/Platform/GraphicsAPI/OpenGL/glGraphicsContext.cpp +++ /dev/null @@ -1,100 +0,0 @@ -#include "glGraphicsContext.hpp" - -#include "Events/WindowEvents.hpp" -#include "Graphics/Blender.hpp" // required for forward declaration -#include "Graphics/Buffers.hpp" // required for forward declaration -#include "Graphics/RenderCommand.hpp" // required for forward declaration -#include "Graphics/Renderer.hpp" // required for forward declaration -#include "UserInterface/UserInterface.hpp" // required for forward declaration -#include "Utility/ResourceManager.hpp" // required for forward declaration - -#include - -#ifndef STOP_FUCKING_ORDERING_THESE_THE_WRONG_WAY_CLANG_FORMAT____ - #include -#endif - -namespace Light { - -glGraphicsContext::glGraphicsContext(GLFWwindow* windowHandle) - : m_WindowHandle(windowHandle) -{ - // set 'GraphicsAPI' - m_GraphicsAPI = GraphicsAPI::OpenGL; - - // make context current - glfwMakeContextCurrent(windowHandle); - - // load opengl (glad) - ASSERT(gladLoadGL(glfwGetProcAddress), "Failed to initialize opengl (glad)"); - - SetDebugMessageCallback(); -} - -void glGraphicsContext::LogDebugData() -{ - // #todo: log more information - LOG(info, "________________________________________"); - LOG(info, "GraphicsContext::"); - LOG(info, " API : OpenGL"); - // LOG(info, " Version : {}", glGetString(GL_VERSION)); - // LOG(info, " Renderer: {}", glGetString(GL_RENDERER)); - LOG(info, "________________________________________"); -} - -void glGraphicsContext::SetDebugMessageCallback() -{ - // determine log level - // #todo: set filters from config.h -#if defined(LIGHT_DEBUG) - glEnable(GL_DEBUG_OUTPUT); - glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, nullptr, GL_TRUE); - - GLuint ids[] = { - 131185 - }; - glDebugMessageControl(GL_DEBUG_SOURCE_API, GL_DEBUG_TYPE_OTHER, GL_DONT_CARE, _countof(ids), ids, GL_FALSE); -#elif defined(LIGHT_RELEASE) - glEnable(GL_DEBUG_OUTPUT); - glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, nullptr, GL_FALSE); - glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DEBUG_SEVERITY_HIGH, 0, nullptr, GL_TRUE); - glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DEBUG_SEVERITY_MEDIUM, 0, nullptr, GL_TRUE); -#else // LIGHT_DIST - return; -#endif - - /* setup message callback */ - glDebugMessageCallback([](unsigned int source, unsigned int type, - unsigned int id, unsigned int severity, - int length, const char* message, - const void* userParam) { - switch (severity) - { - case GL_DEBUG_SEVERITY_HIGH: - // throw glException(source, type, id, message); - return; - - case GL_DEBUG_SEVERITY_MEDIUM: - case GL_DEBUG_SEVERITY_LOW: - LOG(warn, "glMessageCallback: Severity: {} :: Source: {} :: Type: {} :: ID: {}", - Stringifier::glDebugMsgSeverity(severity), - Stringifier::glDebugMsgSource(source), - Stringifier::glDebugMsgType(type), - id); - LOG(warn, " {}", message); - return; - - case GL_DEBUG_SEVERITY_NOTIFICATION: - LOG(trace, "Severity: {} :: Source: {} :: Type: {} :: ID: {}", - Stringifier::glDebugMsgSeverity(severity), - Stringifier::glDebugMsgSource(source), - Stringifier::glDebugMsgType(type), - id); - LOG(trace, " {}", message); - return; - } - }, - nullptr); -} - -} // namespace Light diff --git a/Engine/src/Platform/GraphicsAPI/OpenGL/glSharedContext.hpp b/Engine/src/Platform/GraphicsAPI/OpenGL/glSharedContext.hpp deleted file mode 100644 index 70d3f7b..0000000 --- a/Engine/src/Platform/GraphicsAPI/OpenGL/glSharedContext.hpp +++ /dev/null @@ -1,12 +0,0 @@ -#pragma once - -#include "Base/Base.hpp" -#include "Graphics/SharedContext.hpp" - -namespace Light { - -class glSharedContext: public SharedContext -{ -}; - -} // namespace Light \ No newline at end of file diff --git a/Engine/src/Platform/OS/Linux/lWindow.cpp b/Engine/src/Platform/OS/Linux/lWindow.cpp deleted file mode 100644 index 12d39cd..0000000 --- a/Engine/src/Platform/OS/Linux/lWindow.cpp +++ /dev/null @@ -1,228 +0,0 @@ -#include "lWindow.hpp" - -#include "Events/CharEvent.hpp" -#include "Events/Event.hpp" -#include "Events/KeyboardEvents.hpp" -#include "Events/MouseEvents.hpp" -#include "Events/WindowEvents.hpp" -#include "Graphics/GraphicsContext.hpp" - -#include - -namespace Light { - -Scope Window::Create(std::function callback) -{ - return CreateScope(callback); -} - -lWindow::lWindow(std::function callback) - : m_Handle(nullptr), m_EventCallback(callback) -{ - // init glfw - ASSERT(glfwInit(), "lWindow::lWindow: failed to initialize 'glfw'"); - - // create window - glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); - glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 5); - glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); - glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE); - - m_Handle = glfwCreateWindow(1u, 1u, "", nullptr, nullptr); - ASSERT(m_Handle, "lWindow::lWindow: failed to create 'GLFWwindow'"); - - // bind event stuff - glfwSetWindowUserPointer(m_Handle, &m_EventCallback); - BindGlfwEvents(); - - // create graphics context - m_GraphicsContext = GraphicsContext::Create(GraphicsAPI::OpenGL, m_Handle); - ASSERT(m_GraphicsContext, "lWindow::lWindow: failed to create 'GraphicsContext'"); -} - -lWindow::~lWindow() -{ - glfwDestroyWindow(m_Handle); -} - -void lWindow::PollEvents() -{ - glfwPollEvents(); -} - -void lWindow::OnEvent(const Event& event) -{ - switch (event.GetEventType()) - { - /* closed */ - case EventType::WindowClosed: - b_Closed = true; - break; - - /* resized */ - case EventType::WindowResized: - OnWindowResize((const WindowResizedEvent&)event); - break; - } -} - -void lWindow::OnWindowResize(const WindowResizedEvent& event) -{ - m_Properties.size = event.GetSize(); -} - -void lWindow::SetProperties(const WindowProperties& properties, bool overrideVisibility /* = false */) -{ - // save the visibility status and re-assign if 'overrideVisibility' is false - bool visible = overrideVisibility ? properties.visible : m_Properties.visible; - m_Properties = properties; - m_Properties.visible = visible; - - // set properties - SetTitle(properties.title); - SetSize(properties.size); - SetVSync(properties.vsync); - SetVisibility(visible); -} - -void lWindow::SetTitle(const std::string& title) -{ - m_Properties.title = title; - - glfwSetWindowTitle(m_Handle, title.c_str()); -} - -void lWindow::SetSize(const glm::uvec2& size, bool additive /* = false */) -{ - m_Properties.size.x = size.x == 0u ? m_Properties.size.x : additive ? m_Properties.size.x + size.x : - size.x; - m_Properties.size.y = size.y == 0u ? m_Properties.size.y : additive ? m_Properties.size.y + size.y : - size.y; - - - glfwSetWindowSize(m_Handle, size.x, size.y); -} - -void lWindow::SetVSync(bool vsync, bool toggle /* = false */) -{ - m_Properties.vsync = toggle ? !m_Properties.vsync : vsync; - - glfwSwapInterval(m_Properties.vsync); -} - -void lWindow::SetVisibility(bool visible, bool toggle) -{ - m_Properties.visible = toggle ? !m_Properties.visible : visible; - - if (m_Properties.visible) - glfwShowWindow(m_Handle); - else - glfwHideWindow(m_Handle); -} - -void lWindow::BindGlfwEvents() -{ - //============================== MOUSE_EVENTS ==============================// - /* cursor position */ - glfwSetCursorPosCallback(m_Handle, [](GLFWwindow* window, double xpos, double ypos) { - std::function callback = *(std::function*)glfwGetWindowUserPointer(window); - - MouseMovedEvent event(xpos, ypos); - callback(event); - }); - - /* mouse button */ - glfwSetMouseButtonCallback(m_Handle, [](GLFWwindow* window, int button, int action, int mods) { - std::function callback = *(std::function*)glfwGetWindowUserPointer(window); - - if (action == GLFW_PRESS) - { - ButtonPressedEvent event(button); - callback(event); - } - else if (action == GLFW_RELEASE) - { - ButtonReleasedEvent event(button); - callback(event); - } - }); - - /* scroll */ - glfwSetScrollCallback(m_Handle, [](GLFWwindow* window, double xoffset, double yoffset) { - std::function callback = *(std::function*)glfwGetWindowUserPointer(window); - - WheelScrolledEvent event(yoffset); - callback(event); - }); - //============================== MOUSE_EVENTS ==============================// - - //============================== KEYBOARD_EVENTS ==============================// - /* key */ - glfwSetKeyCallback(m_Handle, [](GLFWwindow* window, int key, int scancode, int action, int mods) { - std::function callback = *(std::function*)glfwGetWindowUserPointer(window); - - if (action == GLFW_PRESS) - { - KeyPressedEvent event(key); - callback(event); - } - else if (action == GLFW_RELEASE) - { - KeyReleasedEvent event(key); - callback(event); - } - }); - /* char */ - glfwSetCharCallback(m_Handle, [](GLFWwindow* window, unsigned int character) { - std::function callback = *(std::function*)glfwGetWindowUserPointer(window); - - SetCharEvent event(character); - callback(event); - }); - - //============================== KEYBOARD_EVENTS ==============================// - - //============================== WINDOW_EVENTS ==============================// - /* window position */ - glfwSetWindowPosCallback(m_Handle, [](GLFWwindow* window, int xpos, int ypos) { - std::function callback = *(std::function*)glfwGetWindowUserPointer(window); - WindowMovedEvent event(xpos, ypos); - - callback(event); - }); - - /* window size */ - glfwSetWindowSizeCallback(m_Handle, [](GLFWwindow* window, int width, int height) { - std::function callback = *(std::function*)glfwGetWindowUserPointer(window); - WindowResizedEvent event(width, height); - - callback(event); - }); - - /* window close */ - glfwSetWindowCloseCallback(m_Handle, [](GLFWwindow* window) { - std::function callback = *(std::function*)glfwGetWindowUserPointer(window); - WindowClosedEvent event; - - callback(event); - }); - - /* window focus */ - glfwSetWindowFocusCallback(m_Handle, [](GLFWwindow* window, int focus) { - std::function callback = *(std::function*)glfwGetWindowUserPointer(window); - - if (focus == GLFW_TRUE) - { - WindowGainFocusEvent event; - callback(event); - } - else - { - WindowLostFocusEvent event; - callback(event); - } - }); - //============================== WINDOW_EVENTS ==============================// -} - -} // namespace Light diff --git a/Engine/src/Platform/OS/Windows/wWindow.cpp b/Engine/src/Platform/OS/Windows/wWindow.cpp deleted file mode 100644 index 5366103..0000000 --- a/Engine/src/Platform/OS/Windows/wWindow.cpp +++ /dev/null @@ -1,234 +0,0 @@ -#include "wWindow.hpp" - -#include "Events/CharEvent.hpp" -#include "Events/Event.hpp" -#include "Events/KeyboardEvents.hpp" -#include "Events/MouseEvents.hpp" -#include "Events/WindowEvents.hpp" -#include "Graphics/GraphicsContext.hpp" - -#include - -extern "C" -{ - // Force Machine to use Dedicated Graphics - __declspec(dllexport) unsigned long NvOptimusEnablement = 0x00000001; // NVidia - __declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1; // AMD -} - -namespace Light { - -Scope Window::Create(std::function callback) -{ - return CreateScope(callback); -} - -wWindow::wWindow(std::function callback) - : m_Handle(nullptr), m_EventCallback(callback) -{ - // init glfw - ASSERT(glfwInit(), "wWindow::wWindow: failed to initialize 'glfw'"); - - // create window - glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); - glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 5); - glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); - glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE); - - m_Handle = glfwCreateWindow(1u, 1u, "", nullptr, nullptr); - ASSERT(m_Handle, "wWindow::wWindow: glfwCreateWindow: failed to create 'GLFWwindow'"); - - // bind event stuff - glfwSetWindowUserPointer(m_Handle, &m_EventCallback); - BindGlfwEvents(); - - // create graphics context - m_GraphicsContext = GraphicsContext::Create(GraphicsAPI::DirectX, m_Handle); - ASSERT(m_GraphicsContext, "wWindow::wWindow: failed to create 'GraphicsContext'"); -} - -wWindow::~wWindow() -{ - glfwDestroyWindow(m_Handle); -} - -void wWindow::PollEvents() -{ - glfwPollEvents(); -} - -void wWindow::OnEvent(const Event& event) -{ - switch (event.GetEventType()) - { - /* closed */ - case EventType::WindowClosed: - b_Closed = true; - break; - - /* resized */ - case EventType::WindowResized: - OnWindowResize((const WindowResizedEvent&)event); - break; - } -} - -void wWindow::OnWindowResize(const WindowResizedEvent& event) -{ - m_Properties.size = event.GetSize(); -} - -void wWindow::SetProperties(const WindowProperties& properties, bool overrideVisiblity /* = false */) -{ - // save the visibility status and re-assign if 'overrideVisibility' is false - bool visible = overrideVisiblity ? properties.visible : m_Properties.visible; - m_Properties = properties; - m_Properties.visible = visible; - - // set properties - SetTitle(properties.title); - SetSize(properties.size); - SetVSync(properties.vsync); - SetVisibility(visible); -} - -void wWindow::SetTitle(const std::string& title) -{ - m_Properties.title = title; - - glfwSetWindowTitle(m_Handle, m_Properties.title.c_str()); -} - -void wWindow::SetSize(const glm::uvec2& size, bool additive /* = false */) -{ - m_Properties.size.x = size.x == 0u ? m_Properties.size.x : additive ? m_Properties.size.x + size.x : - size.x; - m_Properties.size.y = size.y == 0u ? m_Properties.size.y : additive ? m_Properties.size.y + size.y : - size.y; - - - glfwSetWindowSize(m_Handle, size.x, size.y); -} - -void wWindow::SetVSync(bool vsync, bool toggle /* = false */) -{ - m_Properties.vsync = toggle ? !m_Properties.vsync : vsync; - - glfwSwapInterval(m_Properties.vsync); -} - -void wWindow::SetVisibility(bool visible, bool toggle) -{ - m_Properties.visible = toggle ? !m_Properties.visible : visible; - - if (m_Properties.visible) - glfwShowWindow(m_Handle); - else - glfwHideWindow(m_Handle); -} - -void wWindow::BindGlfwEvents() -{ - //============================== MOUSE_EVENTS ==============================// - /* cursor position */ - glfwSetCursorPosCallback(m_Handle, [](GLFWwindow* window, double xpos, double ypos) { - std::function callback = *(std::function*)glfwGetWindowUserPointer(window); - - MouseMovedEvent event(xpos, ypos); - callback(event); - }); - - /* mouse button */ - glfwSetMouseButtonCallback(m_Handle, [](GLFWwindow* window, int button, int action, int mods) { - std::function callback = *(std::function*)glfwGetWindowUserPointer(window); - - if (action == GLFW_PRESS) - { - ButtonPressedEvent event(button); - callback(event); - } - else if (action == GLFW_RELEASE) - { - ButtonReleasedEvent event(button); - callback(event); - } - }); - - /* scroll */ - glfwSetScrollCallback(m_Handle, [](GLFWwindow* window, double xoffset, double yoffset) { - std::function callback = *(std::function*)glfwGetWindowUserPointer(window); - - WheelScrolledEvent event(yoffset); - callback(event); - }); - //============================== MOUSE_EVENTS ==============================// - - //============================== KEYBOARD_EVENTS ==============================// - /* key */ - glfwSetKeyCallback(m_Handle, [](GLFWwindow* window, int key, int scancode, int action, int mods) { - std::function callback = *(std::function*)glfwGetWindowUserPointer(window); - - if (action == GLFW_PRESS) - { - KeyPressedEvent event(key); - callback(event); - } - else if (action == GLFW_RELEASE) - { - KeyReleasedEvent event(key); - callback(event); - } - }); - /* char */ - glfwSetCharCallback(m_Handle, [](GLFWwindow* window, unsigned int character) { - std::function callback = *(std::function*)glfwGetWindowUserPointer(window); - - SetCharEvent event(character); - callback(event); - }); - - //============================== KEYBOARD_EVENTS ==============================// - - //============================== WINDOW_EVENTS ==============================// - /* window position */ - glfwSetWindowPosCallback(m_Handle, [](GLFWwindow* window, int xpos, int ypos) { - std::function callback = *(std::function*)glfwGetWindowUserPointer(window); - WindowMovedEvent event(xpos, ypos); - - callback(event); - }); - - /* window size */ - glfwSetWindowSizeCallback(m_Handle, [](GLFWwindow* window, int width, int height) { - std::function callback = *(std::function*)glfwGetWindowUserPointer(window); - WindowResizedEvent event(width, height); - - callback(event); - }); - - /* window close */ - glfwSetWindowCloseCallback(m_Handle, [](GLFWwindow* window) { - std::function callback = *(std::function*)glfwGetWindowUserPointer(window); - WindowClosedEvent event; - - callback(event); - }); - - /* window focus */ - glfwSetWindowFocusCallback(m_Handle, [](GLFWwindow* window, int focus) { - std::function callback = *(std::function*)glfwGetWindowUserPointer(window); - - if (focus == GLFW_TRUE) - { - WindowGainFocusEvent event; - callback(event); - } - else - { - WindowLostFocusEvent event; - callback(event); - } - }); - //============================== WINDOW_EVENTS ==============================// } -} -} // namespace Light diff --git a/Engine/src/renameall.sh b/Engine/src/renameall.sh deleted file mode 100755 index ccead89..0000000 --- a/Engine/src/renameall.sh +++ /dev/null @@ -1,5 +0,0 @@ -#!/bin/bash - -for f in $(find `pwd` -name "*.cppE"); do - rm "${f}" -done diff --git a/Mirror/.clang-format b/Mirror/.clang-format deleted file mode 100644 index 5e7c904..0000000 --- a/Mirror/.clang-format +++ /dev/null @@ -1,139 +0,0 @@ ---- -# Core -Language: Cpp -Standard: Cpp11 -ColumnLimit: '0' # No limit - -### Bin pack ### -BinPackArguments: 'true' -BinPackParameters: 'true' - -# Includes -SortIncludes: 'true' -IncludeBlocks: Regroup -IncludeCategories: - # Current Project - - Regex: '"' - Priority: 001 - - # Custom Project Categories... - - # Dependecies - - Regex: '<' - Priority: 500 - - # Custom Deependencies Categories... - - # C++ includes - - Regex: '[^.h .hpp]>' - Priority: 998 - - # C includes - - Regex: '<[^/\n]+[.]h>' - Priority: 999 - -# Braces -BreakBeforeBraces: Custom -BraceWrapping: - AfterCaseLabel: true - AfterClass: true - AfterControlStatement: true - AfterEnum: true - AfterFunction: true - AfterNamespace: false - AfterObjCDeclaration: true - AfterStruct: true - AfterUnion: true - AfterExternBlock: true - BeforeCatch: true - BeforeElse: true - IndentBraces: false - SplitEmptyFunction: true - SplitEmptyRecord: true - SplitEmptyNamespace: true - -# Indentation -UseTab: ForIndentation -TabWidth: '4' -IndentWidth: '4' -ContinuationIndentWidth: '4' -ConstructorInitializerIndentWidth: '4' -IndentCaseLabels: 'false' -IndentWrappedFunctionNames: 'true' -IndentPPDirectives: BeforeHash -NamespaceIndentation: None -AccessModifierOffset: '-4' - -# Space -SpaceAfterCStyleCast: 'false' -SpaceAfterLogicalNot: 'false' -SpaceAfterTemplateKeyword: 'false' -SpaceBeforeAssignmentOperators: 'true' -SpaceBeforeCpp11BracedList: 'true' -SpaceBeforeCtorInitializerColon: 'false' -SpaceBeforeInheritanceColon: 'false' -SpaceBeforeParens: ControlStatements -SpaceBeforeRangeBasedForLoopColon: 'true' -SpaceInEmptyParentheses: 'false' -SpacesBeforeTrailingComments: '1' -SpacesInAngles: 'false' -SpacesInCStyleCastParentheses: 'false' -SpacesInContainerLiterals: 'false' -SpacesInParentheses: 'false' -SpacesInSquareBrackets: 'false' - -### Alignment ### -PointerAlignment: Left -DerivePointerAlignment: 'false' -AlignAfterOpenBracket: Align -AlignEscapedNewlines: Left -AlignConsecutiveDeclarations: 'false' -AlignConsecutiveAssignments: 'true' -AlignConsecutiveMacros: 'true' -AlignOperands: 'true' -AlignTrailingComments: 'true' - -### Single Line ### -AllowShortCaseLabelsOnASingleLine: 'true' -AllowShortFunctionsOnASingleLine: Inline -AllowShortLambdasOnASingleLine: Inline -AllowAllArgumentsOnNextLine: 'false' -AllowShortLoopsOnASingleLine: 'false' -AllowShortBlocksOnASingleLine: 'false' -AllowAllParametersOfDeclarationOnNextLine: 'false' -AllowShortIfStatementsOnASingleLine: Never - -### Break ### -AlwaysBreakAfterReturnType: None -AlwaysBreakBeforeMultilineStrings: 'false' -AlwaysBreakTemplateDeclarations: 'Yes' -BreakBeforeBinaryOperators: None -BreakBeforeTernaryOperators: 'false' -BreakInheritanceList: BeforeComma -BreakStringLiterals: 'false' - -# Penalties -PenaltyBreakAssignment: '0' -PenaltyBreakBeforeFirstCallParameter: '0' -PenaltyBreakComment: '0' -PenaltyBreakFirstLessLess: '0' -PenaltyBreakString: '0' -PenaltyBreakTemplateDeclaration: '0' -PenaltyExcessCharacter: '0' -PenaltyReturnTypeOnItsOwnLine: '999999999' # Nope - -# Constructor Initializers -ConstructorInitializerAllOnOneLineOrOnePerLine: 'true' -AllowAllConstructorInitializersOnNextLine: 'true' -BreakConstructorInitializers: BeforeComma - -# Comments -ReflowComments: 'false' -CommentPragmas: '^ TODO@:' -FixNamespaceComments: 'true' - -# Misc -Cpp11BracedListStyle: 'false' -SortUsingDeclarations: 'true' -KeepEmptyLinesAtTheStartOfBlocks: 'false' -MaxEmptyLinesToKeep: '2' diff --git a/Mirror/CMakeLists.txt b/Mirror/CMakeLists.txt deleted file mode 100644 index 19f72b5..0000000 --- a/Mirror/CMakeLists.txt +++ /dev/null @@ -1,23 +0,0 @@ -cmake_minimum_required(VERSION 3.14) - -add_compile_definitions(LIGHT_PLATFORM_WINDOWS) - -include_directories( - ${ENGINE_DIR}src/Engine/ - ${MIRROR_DIR}/src/ - ${ENGINE_DIR}src/Platform/GraphicsAPI/ - ${ENGINE_DIR}src/Platform/OS/ - ${DEPENDENCIES_DIR}entt/src/ - ${DEPENDENCIES_DIR}GLAD/include/ - ${DEPENDENCIES_DIR}GLFW/include/ - ${DEPENDENCIES_DIR}glm/ - ${DEPENDENCIES_DIR}imgui/ - ${DEPENDENCIES_DIR}spdlog/include - ${DEPENDENCIES_DIR}stb_image/ - ${DEPENDENCIES_DIR}yaml-cpp/include -) - - -file(GLOB_RECURSE MIRROR_FILES true ABSOLUTE ${CMAKE_CURRENT_SOURCE_DIR}/src/* ${CMAKE_CURRENT_SOURCE_DIR}/res/*) -source_group(TREE ${MIRROR_DIR} FILES ${MIRROR_FILES}) -add_executable(Mirror ${MIRROR_FILES}) diff --git a/Mirror/src/MirrorApp.cpp b/Mirror/src/MirrorApp.cpp deleted file mode 100644 index 4b05ef4..0000000 --- a/Mirror/src/MirrorApp.cpp +++ /dev/null @@ -1,32 +0,0 @@ -#define LIGHT_ENTRY_POINT -#include "EditorLayer.hpp" - -#include - -namespace Light { - -class Mirror: public Light::Application -{ -public: - Mirror(std::string execName, std::vector args) - : Application(execName, args) - { - // Set window properties - Light::WindowProperties properties; - properties.title = "Mirror"; - properties.size = glm::uvec2(1280u, 720u); - properties.vsync = true; - - m_Window->SetProperties(properties); - - // Attach the sandbox layer - LayerStack::EmplaceLayer(("MirrorLayer"), args); - } -}; - -Application* CreateApplication(std::string execName, std::vector args) -{ - return new Mirror(execName, args); -} - -} // namespace Light diff --git a/Mirror/src/Panels/PropertiesPanel.cpp b/Mirror/src/Panels/PropertiesPanel.cpp deleted file mode 100644 index ca19346..0000000 --- a/Mirror/src/Panels/PropertiesPanel.cpp +++ /dev/null @@ -1,232 +0,0 @@ -#include "PropertiesPanel.hpp" - -#include "Scene/Components.hpp" -#include "Utility/ResourceManager.hpp" - -#include -#include -#include -#include - -namespace Light { - -void PropertiesPanel::OnUserInterfaceUpdate() -{ - ImGui::Begin("Properties"); - - if (m_EntityContext.IsValid()) - { - if (m_EntityContext.HasComponent()) - { - auto& tagComponent = m_EntityContext.GetComponent(); - - char buffer[256]; - memset(buffer, 0, sizeof(buffer)); - std::strncpy(buffer, tagComponent.tag.c_str(), sizeof(buffer)); - - if (ImGui::InputText("##Tag", buffer, sizeof(buffer))) - tagComponent.tag = std::string(buffer); - } - - ImGui::SameLine(); - ImGui::PushItemWidth(-1); - - if (ImGui::Button("Add component")) - ImGui::OpenPopup("Components"); - - if (ImGui::BeginPopup("Components")) - { - if (ImGui::Selectable("SpriteRenderer", false, m_EntityContext.HasComponent() ? ImGuiSelectableFlags_Disabled : NULL)) - m_EntityContext.AddComponent(Light::ResourceManager::GetTexture("awesomeface")); - - if (ImGui::Selectable("Camera", false, m_EntityContext.HasComponent() ? ImGuiSelectableFlags_Disabled : NULL)) - m_EntityContext.AddComponent(); - - ImGui::EndPopup(); - } - ImGui::PopItemWidth(); - - DrawComponent("Transform Component", m_EntityContext, [&](auto& transformComponent) { - DrawVec3Control("Translation", transformComponent.translation); - }); - - DrawComponent("SpriteRenderer Component", m_EntityContext, [&](auto& spriteRendererComponent) { - ImGui::ColorEdit4("Color", &spriteRendererComponent.tint[0]); - }); - - DrawComponent("Camera Component", m_EntityContext, [&](auto& cameraComponent) { - auto& camera = cameraComponent.camera; - - SceneCamera::ProjectionType projectionType = camera.GetProjectionType(); - const char* projectionTypesString[] = { "Orthographic", "Perspective" }; - - if (ImGui::BeginCombo("ProjectionType", projectionTypesString[(int)projectionType])) - { - for (int i = 0; i < 2; i++) - { - const bool isSelected = (int)projectionType == i; - if (ImGui::Selectable(projectionTypesString[i], isSelected)) - { - projectionType = (SceneCamera::ProjectionType)i; - camera.SetProjectionType(projectionType); - } - - if (isSelected) - ImGui::SetItemDefaultFocus(); - } - - ImGui::EndCombo(); - } - - if (projectionType == SceneCamera::ProjectionType::Orthographic) - { - float orthoSize, nearPlane, farPlane; - - orthoSize = camera.GetOrthographicSize(); - nearPlane = camera.GetOrthographicNearPlane(); - farPlane = camera.GetOrthographicFarPlane(); - - if (ImGui::DragFloat("Orthographic Size", &orthoSize)) - camera.SetOrthographicSize(orthoSize); - - if (ImGui::DragFloat("Near Plane", &nearPlane)) - camera.SetOrthographicNearPlane(nearPlane); - - if (ImGui::DragFloat("Far Plane", &farPlane)) - camera.SetOrthographicFarPlane(farPlane); - } - - else // perspective - { - float verticalFOV, nearPlane, farPlane; - - verticalFOV = glm::degrees(camera.GetPerspectiveVerticalFOV()); - nearPlane = camera.GetPerspectiveNearPlane(); - farPlane = camera.GetPerspectiveFarPlane(); - - if (ImGui::DragFloat("Vertical FOV", &verticalFOV)) - camera.SetPerspectiveVerticalFOV(glm::radians(verticalFOV)); - - if (ImGui::DragFloat("Near Plane", &nearPlane)) - camera.SetPerspectiveNearPlane(nearPlane); - - if (ImGui::DragFloat("Far Plane", &farPlane)) - camera.SetPerspectiveFarPlane(farPlane); - } - - ImGui::Separator(); - }); - } - - ImGui::End(); -} - -void PropertiesPanel::SetEntityContext(Entity entity) -{ - m_EntityContext = entity; -} - -void PropertiesPanel::DrawVec3Control(const std::string& label, glm::vec3& values, float resetValue /*= 0.0f*/, float columnWidth /*= 100.0f*/) -{ - ImGuiIO& io = ImGui::GetIO(); - - auto boldFont = io.Fonts->Fonts[0]; - - ImGui::Columns(2); - ImGui::SetColumnWidth(0, columnWidth); - ImGui::Text(label.c_str()); - ImGui::NextColumn(); - - ImGui::PushMultiItemsWidths(3, ImGui::CalcItemWidth()); - ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2 { 0, 0 }); - - float lineHeight = GImGui->Font->FontSize + GImGui->Style.FramePadding.y * 2.0f; - ImVec2 buttonSize = { lineHeight + 3.0f, lineHeight }; - - ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.8f, 0.1f, 0.15f, 1.0f)); - ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.9f, 0.2f, 0.2f, 1.0f)); - ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(0.8f, 0.1f, 0.15f, 1.0f)); - ImGui::PushFont(boldFont); - if (ImGui::Button("X", buttonSize)) - values.x = resetValue; - ImGui::PopFont(); - ImGui::PopStyleColor(3); - - ImGui::SameLine(); - ImGui::DragFloat("##X", &values.x, 0.1f); - ImGui::PopItemWidth(); - ImGui::SameLine(); - - ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.2f, 0.7f, 0.2f, 1.0f)); - ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.3f, 0.8f, 0.3f, 1.0f)); - ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(0.2f, 0.7f, 0.2f, 1.0f)); - ImGui::PushFont(boldFont); - if (ImGui::Button("Y", buttonSize)) - values.y = resetValue; - ImGui::PopFont(); - ImGui::PopStyleColor(3); - - ImGui::SameLine(); - ImGui::DragFloat("##Y", &values.y, 0.1f); - ImGui::PopItemWidth(); - ImGui::SameLine(); - - - ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.1f, 0.25f, 0.8f, 1.0f)); - ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.2f, 0.35f, 0.9f, 1.0f)); - ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(0.1f, 0.25f, 0.8f, 1.0f)); - ImGui::PushFont(boldFont); - if (ImGui::Button("Z", buttonSize)) - values.z = resetValue; - ImGui::PopFont(); - ImGui::PopStyleColor(3); - - ImGui::SameLine(); - ImGui::DragFloat("##Z", &values.z, 0.1f); - ImGui::PopItemWidth(); - - ImGui::PopStyleVar(); - ImGui::Columns(1); -} - - -template -void PropertiesPanel::DrawComponent(const std::string& name, Entity entity, UIFunction userInterfaceFunction) -{ - if (!entity.HasComponent()) - return; - - auto& component = entity.GetComponent(); - - ImVec2 regionAvail = ImGui::GetContentRegionAvail(); - - ImGuiTreeNodeFlags flags = ImGuiTreeNodeFlags_DefaultOpen | ImGuiTreeNodeFlags_SpanAvailWidth | ImGuiTreeNodeFlags_Framed | ImGuiTreeNodeFlags_AllowItemOverlap | ImGuiTreeNodeFlags_FramePadding; - - ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, { 4, 4 }); - float lineHeight = GImGui->Font->FontSize + GImGui->Style.FramePadding.y * 2.0f; - ImGui::Separator(); - - if (ImGui::TreeNodeEx((void*)typeid(ComponentType).hash_code(), flags, name.c_str())) - { - ImGui::PopStyleVar(); - - ImGui::SameLine(regionAvail.x - lineHeight * .5f); - if (ImGui::Button("+", { lineHeight, lineHeight })) - ImGui::OpenPopup("ComponentSettings"); - - if (ImGui::BeginPopup("ComponentSettings")) - { - if (ImGui::Selectable("Remove component")) - entity.RemoveComponent(); - - ImGui::EndPopup(); - } - - userInterfaceFunction(component); - ImGui::TreePop(); - } - else - ImGui::PopStyleVar(); -} - -} // namespace Light diff --git a/Assets/Fonts/OpenSans/LICENSE.txt b/data/assets/fonts/open_sans/LICENSE.txt similarity index 100% rename from Assets/Fonts/OpenSans/LICENSE.txt rename to data/assets/fonts/open_sans/LICENSE.txt diff --git a/Assets/Fonts/OpenSans/OpenSans-Bold.ttf b/data/assets/fonts/open_sans/OpenSans-Bold.ttf similarity index 100% rename from Assets/Fonts/OpenSans/OpenSans-Bold.ttf rename to data/assets/fonts/open_sans/OpenSans-Bold.ttf diff --git a/Assets/Fonts/OpenSans/OpenSans-BoldItalic.ttf b/data/assets/fonts/open_sans/OpenSans-BoldItalic.ttf similarity index 100% rename from Assets/Fonts/OpenSans/OpenSans-BoldItalic.ttf rename to data/assets/fonts/open_sans/OpenSans-BoldItalic.ttf diff --git a/Assets/Fonts/OpenSans/OpenSans-ExtraBold.ttf b/data/assets/fonts/open_sans/OpenSans-ExtraBold.ttf similarity index 100% rename from Assets/Fonts/OpenSans/OpenSans-ExtraBold.ttf rename to data/assets/fonts/open_sans/OpenSans-ExtraBold.ttf diff --git a/Assets/Fonts/OpenSans/OpenSans-ExtraBoldItalic.ttf b/data/assets/fonts/open_sans/OpenSans-ExtraBoldItalic.ttf similarity index 100% rename from Assets/Fonts/OpenSans/OpenSans-ExtraBoldItalic.ttf rename to data/assets/fonts/open_sans/OpenSans-ExtraBoldItalic.ttf diff --git a/Assets/Fonts/OpenSans/OpenSans-Italic.ttf b/data/assets/fonts/open_sans/OpenSans-Italic.ttf similarity index 100% rename from Assets/Fonts/OpenSans/OpenSans-Italic.ttf rename to data/assets/fonts/open_sans/OpenSans-Italic.ttf diff --git a/Assets/Fonts/OpenSans/OpenSans-Light.ttf b/data/assets/fonts/open_sans/OpenSans-Light.ttf similarity index 100% rename from Assets/Fonts/OpenSans/OpenSans-Light.ttf rename to data/assets/fonts/open_sans/OpenSans-Light.ttf diff --git a/Assets/Fonts/OpenSans/OpenSans-LightItalic.ttf b/data/assets/fonts/open_sans/OpenSans-LightItalic.ttf similarity index 100% rename from Assets/Fonts/OpenSans/OpenSans-LightItalic.ttf rename to data/assets/fonts/open_sans/OpenSans-LightItalic.ttf diff --git a/Assets/Fonts/OpenSans/OpenSans-Regular.ttf b/data/assets/fonts/open_sans/OpenSans-Regular.ttf similarity index 100% rename from Assets/Fonts/OpenSans/OpenSans-Regular.ttf rename to data/assets/fonts/open_sans/OpenSans-Regular.ttf diff --git a/Assets/Fonts/OpenSans/OpenSans-SemiBold.ttf b/data/assets/fonts/open_sans/OpenSans-SemiBold.ttf similarity index 100% rename from Assets/Fonts/OpenSans/OpenSans-SemiBold.ttf rename to data/assets/fonts/open_sans/OpenSans-SemiBold.ttf diff --git a/Assets/Fonts/OpenSans/OpenSans-SemiBoldItalic.ttf b/data/assets/fonts/open_sans/OpenSans-SemiBoldItalic.ttf similarity index 100% rename from Assets/Fonts/OpenSans/OpenSans-SemiBoldItalic.ttf rename to data/assets/fonts/open_sans/OpenSans-SemiBoldItalic.ttf diff --git a/Assets/Scenes/demo.scene b/data/assets/scenes/demo.scene similarity index 100% rename from Assets/Scenes/demo.scene rename to data/assets/scenes/demo.scene diff --git a/Assets/Shaders/Quad/Quad_PS.glsl b/data/assets/shaders/quads/Quad_PS.glsl similarity index 100% rename from Assets/Shaders/Quad/Quad_PS.glsl rename to data/assets/shaders/quads/Quad_PS.glsl diff --git a/Assets/Shaders/Quad/Quad_VS.glsl b/data/assets/shaders/quads/Quad_VS.glsl similarity index 100% rename from Assets/Shaders/Quad/Quad_VS.glsl rename to data/assets/shaders/quads/Quad_VS.glsl diff --git a/Assets/Shaders/Texture/Texture_PS.glsl b/data/assets/shaders/texture/Texture_PS.glsl similarity index 100% rename from Assets/Shaders/Texture/Texture_PS.glsl rename to data/assets/shaders/texture/Texture_PS.glsl diff --git a/Assets/Shaders/Texture/Texture_VS.glsl b/data/assets/shaders/texture/Texture_VS.glsl similarity index 100% rename from Assets/Shaders/Texture/Texture_VS.glsl rename to data/assets/shaders/texture/Texture_VS.glsl diff --git a/Assets/Shaders/TintedTexture/TintedTexture_PS.glsl b/data/assets/shaders/tinted_texture/TintedTexture_PS.glsl similarity index 100% rename from Assets/Shaders/TintedTexture/TintedTexture_PS.glsl rename to data/assets/shaders/tinted_texture/TintedTexture_PS.glsl diff --git a/Assets/Shaders/TintedTexture/TintedTexture_VS.glsl b/data/assets/shaders/tinted_texture/TintedTexture_VS.glsl similarity index 100% rename from Assets/Shaders/TintedTexture/TintedTexture_VS.glsl rename to data/assets/shaders/tinted_texture/TintedTexture_VS.glsl diff --git a/Assets/Textures/awesomeface.png b/data/assets/textures/awesomeface.png similarity index 100% rename from Assets/Textures/awesomeface.png rename to data/assets/textures/awesomeface.png diff --git a/EngineResources/Icons/Asset_Directory.png b/data/engine/icons/Asset_Directory.png similarity index 100% rename from EngineResources/Icons/Asset_Directory.png rename to data/engine/icons/Asset_Directory.png diff --git a/EngineResources/Icons/Asset_Image.png b/data/engine/icons/Asset_Image.png similarity index 100% rename from EngineResources/Icons/Asset_Image.png rename to data/engine/icons/Asset_Image.png diff --git a/EngineResources/Icons/Asset_Scene.png b/data/engine/icons/Asset_Scene.png similarity index 100% rename from EngineResources/Icons/Asset_Scene.png rename to data/engine/icons/Asset_Scene.png diff --git a/EngineResources/Icons/Asset_Text.png b/data/engine/icons/Asset_Text.png similarity index 100% rename from EngineResources/Icons/Asset_Text.png rename to data/engine/icons/Asset_Text.png diff --git a/Dependencies/CMakeLists.txt b/external/CMakeLists.txt similarity index 73% rename from Dependencies/CMakeLists.txt rename to external/CMakeLists.txt index e099a81..7d439b2 100644 --- a/Dependencies/CMakeLists.txt +++ b/external/CMakeLists.txt @@ -1,5 +1,13 @@ +# GLAD # +add_subdirectory(./glad) + +# IMGUI # cmake_minimum_required(VERSION 3.14) +set(MIRROR_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../modules/mirror/) +set(ENGINE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../modules/engine/) +set(DEPENDENCIES_DIR ${CMAKE_CURRENT_SOURCE_DIR}/) + if (CMAKE_COMPILER_IS_GNUCC) add_compile_options(-w) endif() @@ -18,7 +26,6 @@ file(GLOB IMGUI_FILES true ABSOLUTE set(BACKENDS_DIR ${CMAKE_CURRENT_SOURCE_DIR}/imgui/backends/) -include_directories(${CMAKE_CURRENT_SOURCE_DIR}/imgui) file(GLOB IMGUI_BACKEND_FILES true ABSOLUTE ${BACKENDS_DIR}imgui_impl_opengl3.cpp @@ -38,8 +45,18 @@ endif() add_compile_definitions(IMGUI_IMPL_OPENGL_LOADER_GLAD) include_directories(${DEPENDENCIES_DIR}GLFW/include) include_directories(${DEPENDENCIES_DIR}glm/) + add_library(imgui STATIC ${IMGUI_FILES} ${IMGUI_BACKEND_FILES}) +target_include_directories(imgui PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/imgui) +target_link_libraries( + imgui + PUBLIC glad + PUBLIC opengl::opengl + PUBLIC glm::glm + PUBLIC glfw +) + # Copy imconfig.h over -file(COPY ${CMAKE_CURRENT_SOURCE_DIR}/Configurations/imgui/imconfig.h +file(COPY ${CMAKE_CURRENT_SOURCE_DIR}/configurations/imgui/imconfig.h DESTINATION ${CMAKE_CURRENT_SOURCE_DIR}/imgui/) diff --git a/Dependencies/Configurations/imgui/imconfig.h b/external/configurations/imgui/imconfig.h similarity index 100% rename from Dependencies/Configurations/imgui/imconfig.h rename to external/configurations/imgui/imconfig.h diff --git a/Dependencies/imgui b/external/imgui similarity index 100% rename from Dependencies/imgui rename to external/imgui diff --git a/modules/CMakeLists.txt b/modules/CMakeLists.txt new file mode 100644 index 0000000..c3169ec --- /dev/null +++ b/modules/CMakeLists.txt @@ -0,0 +1,2 @@ +add_subdirectory(./engine) +add_subdirectory(./mirror) diff --git a/modules/engine/CMakeLists.txt b/modules/engine/CMakeLists.txt new file mode 100644 index 0000000..3fd11b7 --- /dev/null +++ b/modules/engine/CMakeLists.txt @@ -0,0 +1,116 @@ +cmake_minimum_required(VERSION 3.16) + +if(NOT WIN32) + add_library_module(engine + camera/camera.cpp + camera/ortho.cpp + camera/scene.cpp + core/application.cpp + core/uuid.cpp + debug/exceptions.cpp + debug/instrumentor.cpp + debug/logger.cpp + graphics/blender.cpp + graphics/buffers.cpp + graphics/framebuffer.cpp + graphics/graphics_context.cpp + graphics/render_command.cpp + graphics/renderer.cpp + graphics/renderer_programs/quad.cpp + graphics/renderer_programs/texture.cpp + graphics/renderer_programs/tinted_texture.cpp + graphics/shader.cpp + graphics/texture.cpp + graphics/vertex_layout.cpp + input/input.cpp + layer/layer.cpp + layer/layer_stack.cpp + math/random.cpp + platform/graphics/opengl/blender.cpp + platform/graphics/opengl/buffers.cpp + platform/graphics/opengl/framebuffers.cpp + platform/graphics/opengl/graphics_context.cpp + platform/graphics/opengl/render_command.cpp + platform/graphics/opengl/shader.cpp + platform/graphics/opengl/texture.cpp + platform/graphics/opengl/user_interface.cpp + platform/graphics/opengl/vertex_layout.cpp + platform/os/linux/l_window.cpp + scene/entity.cpp + scene/scene.cpp + time/timer.cpp + user_interface/user_interface.cpp + utils/file_manager.cpp + utils/resource_manager.cpp + utils/serializer.cpp + utils/stringifier.cpp + ) +else() + add_library_module(engine + camera/camera.cpp + camera/ortho.cpp + camera/scene.cpp + core/application.cpp + core/uuid.cpp + debug/exceptions.cpp + debug/instrumentor.cpp + debug/logger.cpp + graphics/blender.cpp + graphics/buffers.cpp + graphics/framebuffer.cpp + graphics/graphics_context.cpp + graphics/render_command.cpp + graphics/renderer.cpp + graphics/renderer_programs/quad.cpp + graphics/renderer_programs/texture.cpp + graphics/renderer_programs/tinted_texture.cpp + graphics/shader.cpp + graphics/texture.cpp + graphics/vertex_layout.cpp + input/input.cpp + layer/layer.cpp + layer/layer_stack.cpp + math/random.cpp + platform/graphics/directx/blender.cpp + platform/graphics/directx/buffers.cpp + platform/graphics/directx/framebuffers.cpp + platform/graphics/directx/graphics_context.cpp + platform/graphics/directx/render_command.cpp + platform/graphics/directx/shader.cpp + platform/graphics/directx/texture.cpp + platform/graphics/directx/user_interface.cpp + platform/graphics/directx/vertex_layout.cpp + platform/graphics/opengl/blender.cpp + platform/graphics/opengl/buffers.cpp + platform/graphics/opengl/framebuffers.cpp + platform/graphics/opengl/graphics_context.cpp + platform/graphics/opengl/render_command.cpp + platform/graphics/opengl/shader.cpp + platform/graphics/opengl/texture.cpp + platform/graphics/opengl/user_interface.cpp + platform/graphics/opengl/vertex_layout.cpp + platform/os/windows/w_window.cpp + scene/entity.cpp + scene/scene.cpp + time/timer.cpp + user_interface/user_interface.cpp + utils/file_manager.cpp + utils/resource_manager.cpp + utils/serializer.cpp + utils/stringifier.cpp + ) +endif() + +target_link_libraries( + engine + PUBLIC glad + PUBLIC opengl::opengl + PUBLIC glfw + PUBLIC spdlog::spdlog + PUBLIC imgui + PUBLIC stb::stb + PUBLIC yaml-cpp::yaml-cpp + PUBLIC EnTT::EnTT +) + +target_precompile_headers(engine PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/src/ltpch.hpp) diff --git a/Engine/src/Engine/Base/Base.hpp b/modules/engine/include/engine/base/base.hpp similarity index 70% rename from Engine/src/Engine/Base/Base.hpp rename to modules/engine/include/engine/base/base.hpp index 2748182..bbeab25 100644 --- a/Engine/src/Engine/Base/Base.hpp +++ b/modules/engine/include/engine/base/base.hpp @@ -9,13 +9,13 @@ template using Ref = std::shared_ptr; template -constexpr Ref CreateRef(Args&&... args) +constexpr Ref CreateRef(Args &&...args) { return std::make_shared(std::forward(args)...); } template -constexpr Ref MakeRef(T* rawPointer) +constexpr Ref MakeRef(T *rawPointer) { return std::shared_ptr(rawPointer); } @@ -25,13 +25,13 @@ template using Scope = std::unique_ptr; template -constexpr std::unique_ptr CreateScope(Args&&... args) +constexpr std::unique_ptr CreateScope(Args &&...args) { return std::make_unique(std::forward(args)...); } template -constexpr std::unique_ptr MakeScope(T* rawPointer) +constexpr std::unique_ptr MakeScope(T *rawPointer) { return std::unique_ptr(rawPointer); } @@ -60,7 +60,8 @@ constexpr std::unique_ptr MakeScope(T* rawPointer) #endif //========== PLATFORM ==========// -//====================================================================== OPERATIONS ======================================================================// +//====================================================================== OPERATIONS +//======================================================================// /* assertions */ #define ASSERT(x, ...) \ { \ @@ -76,36 +77,31 @@ constexpr std::unique_ptr MakeScope(T* rawPointer) #define BIT(x) 1 << x /* token */ -#define LT_PAIR_TOKEN_VALUE_TO_NAME(token) \ - { \ - token, #token \ - } -#define LT_PAIR_TOKEN_NAME_TO_VALUE(token) \ - { \ - #token, token \ - } -#define LT_TOKEN_NAME(token) #token -//====================================================================== OPERATIONS ======================================================================// +#define LT_PAIR_TOKEN_VALUE_TO_NAME(token) { token, #token } +#define LT_PAIR_TOKEN_NAME_TO_VALUE(token) { #token, token } +#define LT_TOKEN_NAME(token) #token +//====================================================================== OPERATIONS +//======================================================================// //========== ESSENTIAL_HEADERS ==========// /* config */ #ifndef LIGHT_CONFIG_H - #include "Base/Config.hpp" + #include #endif /* debug */ #ifndef LIGHT_LOGGER_H - #include "Debug/Logger.hpp" + #include #endif -#include "Debug/Exceptions.hpp" +#include /* portables */ #ifndef LIGHT_DEBUG_TRAP_H - #include "Base/Portables/DebugTrap.hpp" + #include #endif /* utility */ #ifndef LIGHT_STRINGIFIER_H - #include "Utility/Stringifier.hpp" + #include #endif //========== ESSENTIAL_HEADERS ==========// diff --git a/Engine/src/Engine/Base/Config.hpp b/modules/engine/include/engine/base/config.hpp similarity index 100% rename from Engine/src/Engine/Base/Config.hpp rename to modules/engine/include/engine/base/config.hpp diff --git a/Engine/src/Engine/Base/EntryPoint.hpp b/modules/engine/include/engine/base/entrypoint.hpp similarity index 75% rename from Engine/src/Engine/Base/EntryPoint.hpp rename to modules/engine/include/engine/base/entrypoint.hpp index b28f262..092f0ab 100644 --- a/Engine/src/Engine/Base/EntryPoint.hpp +++ b/modules/engine/include/engine/base/entrypoint.hpp @@ -5,13 +5,13 @@ #include // to be defined in client project -extern Light::Application* Light::CreateApplication(std::string execName, std::vector args); +extern Light::Application *Light::CreateApplication(); // #todo: use windows specific stuff -int main(int argc, char* argv[]) +int main(int argc, char *argv[]) { - Light::Application* application = nullptr; - int exitCode = 0; + Light::Application *application = nullptr; + int exitCode = 0; std::vector args; @@ -20,7 +20,7 @@ int main(int argc, char* argv[]) try { - application = Light::CreateApplication(argv[0], args); + application = Light::CreateApplication(); ASSERT(application, "Light::Application is not intialized"); for (int i = 0; i < argc; i++) @@ -53,16 +53,16 @@ int main(int argc, char* argv[]) #elif defined(LIGHT_PLATFORM_LINUX) - #include + #include // to be defined in client project -extern Light::Application* Light::CreateApplication(); +extern Light::Application *Light::CreateApplication(); // #todo: use linux specific stuff -int main(int argc, char* argv[]) +int main(int argc, char *argv[]) { - Light::Application* application = nullptr; - int exitCode = 0; + Light::Application *application = nullptr; + int exitCode = 0; try { diff --git a/Engine/src/Engine/Base/Portables/DebugTrap.hpp b/modules/engine/include/engine/base/portables/debug_trap.hpp similarity index 67% rename from Engine/src/Engine/Base/Portables/DebugTrap.hpp rename to modules/engine/include/engine/base/portables/debug_trap.hpp index 1e5454d..c184ecb 100644 --- a/Engine/src/Engine/Base/Portables/DebugTrap.hpp +++ b/modules/engine/include/engine/base/portables/debug_trap.hpp @@ -2,15 +2,19 @@ #ifndef LIGHT_DEBUG_TRAP_H #define LIGHT_DEBUG_TRAP_H - #include "Base/Base.hpp" + #include // https://github.com/nemequ/portable-snippets/tree/master/debug-trap #ifdef LIGHT_DIST #ifdef _MSC_VER - #define LT_DEBUG_TRAP() \ - LT_FILE_CRITICAL("DEBUG_TRAP REQUESTED AT: {}, FILE: {}, LINE: {}", \ - __FUNCSIG__, __FILE__, __LINE__) // or __FUNCSIG__ + #define LT_DEBUG_TRAP() \ + LT_FILE_CRITICAL( \ + "DEBUG_TRAP REQUESTED AT: {}, FILE: {}, LINE: {}", \ + __FUNCSIG__, \ + __FILE__, \ + __LINE__ \ + ) // or __FUNCSIG__ #else #define LT_DEBUG_TRAP() \ @@ -85,8 +89,7 @@ static inline void LT_DEBUG_TRAP(void) #elif defined(_55_) static inline void LT_DEBUG_TRAP(void) { - __asm__ __volatile__( - ";\n .if (.MNEMONIC)\n ESTOP_1\n .else\n ESTOP_1()\n .endif\n NOP"); + __asm__ __volatile__(";\n .if (.MNEMONIC)\n ESTOP_1\n .else\n ESTOP_1()\n .endif\n NOP"); } #elif defined(_64P_) @@ -119,14 +122,16 @@ static inline void LT_DEBUG_TRAP(void) #if !defined(LT_DEBUG_TRAP) #if !defined(LIGHT_IGNORE_UNDEFINED_DEBUG_TRAP) - #error \ - "failed to define LT_BREAK, define LIGHT_IGNORE_UNDEFINED_DEBUG_TRAP in Config.h to disable this error" + #error "failed to define LT_BREAK, define LIGHT_IGNORE_UNDEFINED_DEBUG_TRAP in Config.h to disable this error" #elif defined(LIGHT_DIST) #ifdef _MSC_VER - #define LT_DEBUG_TRAP() \ - LOG(critical, "DEBUG_TRAP REQUESTED AT: {}, FILE: {}, LINE: {}", \ - __FUNCSIG__, __FILE__, __LINE__) // or __FUNCSIG__ + #define LT_DEBUG_TRAP() \ + LOG(critical, \ + "DEBUG_TRAP REQUESTED AT: {}, FILE: {}, LINE: {}", \ + __FUNCSIG__, \ + __FILE__, \ + __LINE__) // or __FUNCSIG__ #else #define LT_DEBUG_TRAP() \ @@ -135,9 +140,12 @@ static inline void LT_DEBUG_TRAP(void) #endif #else /* !defined(LIGHT_DIST) */ #ifdef _MSC_VER - #define LT_DEBUG_TRAP() \ - LOG(critical, "DEBUG_TRAP REQUESTED AT: {}, FILE: {}, LINE: {}", \ - __FUNCSIG__, __FILE__, __LINE__) // or __FUNCSIG__ + #define LT_DEBUG_TRAP() \ + LOG(critical, \ + "DEBUG_TRAP REQUESTED AT: {}, FILE: {}, LINE: {}", \ + __FUNCSIG__, \ + __FILE__, \ + __LINE__) // or __FUNCSIG__ #else #define LT_DEBUG_TRAP() \ diff --git a/modules/engine/include/engine/camera/camera.hpp b/modules/engine/include/engine/camera/camera.hpp new file mode 100644 index 0000000..42ed6ef --- /dev/null +++ b/modules/engine/include/engine/camera/camera.hpp @@ -0,0 +1,35 @@ +#pragma once + +#include +#include + +namespace Light { + +class Camera +{ +private: + glm::vec4 m_BackgroundColor = glm::vec4(1.0f, 0.0f, 0.0f, 1.0f); + +protected: + glm::mat4 m_Projection; + +public: + Camera() = default; + + inline const glm::mat4 &GetProjection() const + { + return m_Projection; + } + + inline const glm::vec4 &GetBackgroundColor() const + { + return m_BackgroundColor; + } + + inline void SetBackgroundColor(const glm::vec4 &color) + { + m_BackgroundColor = color; + } +}; + +} // namespace Light diff --git a/modules/engine/include/engine/camera/ortho.hpp b/modules/engine/include/engine/camera/ortho.hpp new file mode 100644 index 0000000..08d2cdc --- /dev/null +++ b/modules/engine/include/engine/camera/ortho.hpp @@ -0,0 +1,54 @@ +#pragma once + +#include +#include + +namespace Light { + +class OrthographicCamera +{ +private: + glm::vec2 m_Position; + float m_AspectRatio; + float m_ZoomLevel; + + const glm::vec3 m_Up; + + glm::mat4 m_Projection; + glm::mat4 m_View; + + glm::vec4 m_ClearColor; + +public: + OrthographicCamera( + const glm::vec2 &position, + float aspectRatio, + float zoomLevel, + const glm::vec4 &clearColor = glm::vec4(0.1f, 0.3f, 0.7f, 1.0f) + ); + + // CAMERA // + void CalculateView(); + void CalculateProjection(); + + void OnResize(const glm::vec2 &size); + + inline const glm::mat4 &GetView() const + { + return m_View; + } + inline const glm::mat4 &GetProjection() const + { + return m_Projection; + } + + inline const glm::vec4 &GetClearColor() const + { + return m_ClearColor; + } + + // CAMERA_CONTROLLER // + void Move(const glm::vec2 &position); +}; + +} // namespace Light diff --git a/Engine/src/Engine/Camera/SceneCamera.hpp b/modules/engine/include/engine/camera/scene.hpp similarity index 55% rename from Engine/src/Engine/Camera/SceneCamera.hpp rename to modules/engine/include/engine/camera/scene.hpp index 8ef9d93..d0db48a 100644 --- a/Engine/src/Engine/Camera/SceneCamera.hpp +++ b/modules/engine/include/engine/camera/scene.hpp @@ -1,7 +1,7 @@ #pragma once -#include "Base/Base.hpp" -#include "Camera.hpp" +#include +#include namespace Light { @@ -11,7 +11,7 @@ public: enum class ProjectionType { Orthographic = 0, - Perspetcive = 1 + Perspetcive = 1 }; struct OrthographicSpecification // :#todo use this @@ -48,18 +48,39 @@ public: void SetPerspectiveFarPlane(float farPlane); void SetPerspectiveNearPlane(float nearPlane); - inline float GetOrthographicSize() const { return m_OrthographicSpecification.size; } - inline float GetOrthographicFarPlane() const { return m_OrthographicSpecification.farPlane; } - inline float GetOrthographicNearPlane() const { return m_OrthographicSpecification.nearPlane; } + inline float GetOrthographicSize() const + { + return m_OrthographicSpecification.size; + } + inline float GetOrthographicFarPlane() const + { + return m_OrthographicSpecification.farPlane; + } + inline float GetOrthographicNearPlane() const + { + return m_OrthographicSpecification.nearPlane; + } - inline float GetPerspectiveVerticalFOV() const { return m_PerspectiveSpecification.verticalFOV; } - inline float GetPerspectiveFarPlane() const { return m_PerspectiveSpecification.farPlane; } - inline float GetPerspectiveNearPlane() const { return m_PerspectiveSpecification.nearPlane; } + inline float GetPerspectiveVerticalFOV() const + { + return m_PerspectiveSpecification.verticalFOV; + } + inline float GetPerspectiveFarPlane() const + { + return m_PerspectiveSpecification.farPlane; + } + inline float GetPerspectiveNearPlane() const + { + return m_PerspectiveSpecification.nearPlane; + } - inline ProjectionType GetProjectionType() const { return m_ProjectionType; } + inline ProjectionType GetProjectionType() const + { + return m_ProjectionType; + } private: void CalculateProjection(); }; -} // namespace Light \ No newline at end of file +} // namespace Light diff --git a/modules/engine/include/engine/core/application.hpp b/modules/engine/include/engine/core/application.hpp new file mode 100644 index 0000000..2deff27 --- /dev/null +++ b/modules/engine/include/engine/core/application.hpp @@ -0,0 +1,54 @@ +#pragma once + +#include +#include +#include +#include +#include + +namespace Light { + +class Window; +class Event; + +class Instrumentor; + +class Application /* singleton */ +{ +private: + static Application *s_Context; + +private: + Scope m_Logger; + Scope m_Instrumentor; + Scope m_LayerStack; + Scope m_Input; + Scope m_ResourceManager; + +protected: + Scope m_Window; + +public: + Application(const Application &) = delete; + Application &operator=(const Application &) = delete; + + virtual ~Application(); + + void GameLoop(); + + // To be defined in client project + + static void Quit(); + +protected: + Application(); + +private: + void OnEvent(const Event &event); + + void LogDebugData(); +}; + +extern Application *CreateApplication(); + +} // namespace Light diff --git a/modules/engine/include/engine/core/uuid.hpp b/modules/engine/include/engine/core/uuid.hpp new file mode 100644 index 0000000..69ef940 --- /dev/null +++ b/modules/engine/include/engine/core/uuid.hpp @@ -0,0 +1,38 @@ +#pragma once + +#include + +namespace Light { + +class UUID +{ +private: + static std::mt19937_64 s_Engine; + static std::uniform_int_distribution s_UniformDistribution; + +private: + uint64_t m_UUID; + +public: + UUID(uint64_t uuid = -1); + + operator uint64_t() const + { + return m_UUID; + } +}; + +} // namespace Light + +namespace std { + +template<> +struct hash +{ + std::size_t operator()(const Light::UUID &uuid) const + { + return hash()(static_cast(uuid)); + } +}; + +} // namespace std diff --git a/modules/engine/include/engine/core/window.hpp b/modules/engine/include/engine/core/window.hpp new file mode 100644 index 0000000..48149fe --- /dev/null +++ b/modules/engine/include/engine/core/window.hpp @@ -0,0 +1,99 @@ +#pragma once + +#include +#include +#include + +namespace Light { + +class Event; + +struct WindowProperties +{ + std::string title; + glm::uvec2 size; + bool vsync, visible; +}; + +class Window +{ +protected: + Scope m_GraphicsContext; + WindowProperties m_Properties; + bool b_Closed; + +public: + static Scope Create(std::function callback); + + Window(): m_GraphicsContext(nullptr), m_Properties {}, b_Closed(false) + { + } + + Window(const Window &) = delete; + Window &operator=(const Window &) = delete; + + virtual ~Window() = default; + + /* events */ + virtual void PollEvents() = 0; + virtual void OnEvent(const Event &event) = 0; + + //======================================== SETTERS ========================================// + virtual void SetProperties( + const WindowProperties &properties, + bool affectVisibility = false + ) = 0; + + virtual void SetTitle(const std::string &title) = 0; + + virtual void SetSize(const glm::uvec2 &size, bool additive = false) = 0; // pass 0 for width or + // height for single + // dimension resizing + + inline void Close() + { + b_Closed = true; + } + virtual void SetVSync(bool vsync, bool toggle = false) = 0; + virtual void SetVisibility(bool visible, bool toggle = false) = 0; + //======================================== SETTERS ========================================// + + //============================== GETTERS ==============================// + inline GraphicsContext *GetGfxContext() const + { + return m_GraphicsContext.get(); + } + + inline const WindowProperties &GetProperties() const + { + return m_Properties; + } + + inline const std::string &GetTitle() const + { + return m_Properties.title; + } + + inline const glm::uvec2 &GetSize() const + { + return m_Properties.size; + } + + inline bool IsClosed() const + { + return b_Closed; + } + inline bool IsVSync() const + { + return m_Properties.vsync; + } + inline bool IsVisible() const + { + return m_Properties.visible; + } + //============================== GETTERS ==============================// + +protected: +}; + +} // namespace Light diff --git a/Engine/src/Engine/Debug/Exceptions.hpp b/modules/engine/include/engine/debug/exceptions.hpp similarity index 100% rename from Engine/src/Engine/Debug/Exceptions.hpp rename to modules/engine/include/engine/debug/exceptions.hpp diff --git a/Engine/src/Engine/Debug/Instrumentor.hpp b/modules/engine/include/engine/debug/instrumentor.hpp similarity index 69% rename from Engine/src/Engine/Debug/Instrumentor.hpp rename to modules/engine/include/engine/debug/instrumentor.hpp index 45905a9..9bd31ee 100644 --- a/Engine/src/Engine/Debug/Instrumentor.hpp +++ b/modules/engine/include/engine/debug/instrumentor.hpp @@ -1,10 +1,8 @@ #pragma once -#include "Base/Base.hpp" - #include +#include #include -#include namespace Light { @@ -20,7 +18,7 @@ struct ScopeProfileResult class Instrumentor /* singleton */ { private: - static Instrumentor* s_Context; + static Instrumentor *s_Context; private: std::ofstream m_OutputFileStream; @@ -30,18 +28,27 @@ private: public: static Scope Create(); - static inline void BeginSession(const std::string& outputPath) { s_Context->BeginSessionImpl(outputPath); } - static inline void EndSession() { s_Context->EndSessionImpl(); } + static inline void BeginSession(const std::string &outputPath) + { + s_Context->BeginSessionImpl(outputPath); + } + static inline void EndSession() + { + s_Context->EndSessionImpl(); + } - static inline void SubmitScopeProfile(const ScopeProfileResult& profileResult) { s_Context->SubmitScopeProfileImpl(profileResult); } + static inline void SubmitScopeProfile(const ScopeProfileResult &profileResult) + { + s_Context->SubmitScopeProfileImpl(profileResult); + } private: Instrumentor(); - void BeginSessionImpl(const std::string& outputPath); + void BeginSessionImpl(const std::string &outputPath); void EndSessionImpl(); - void SubmitScopeProfileImpl(const ScopeProfileResult& profileResult); + void SubmitScopeProfileImpl(const ScopeProfileResult &profileResult); }; class InstrumentorTimer @@ -51,7 +58,7 @@ private: std::chrono::time_point m_Start; public: - InstrumentorTimer(const std::string& scopeName); + InstrumentorTimer(const std::string &scopeName); ~InstrumentorTimer(); }; diff --git a/modules/engine/include/engine/debug/logger.hpp b/modules/engine/include/engine/debug/logger.hpp new file mode 100644 index 0000000..c5ee0c1 --- /dev/null +++ b/modules/engine/include/engine/debug/logger.hpp @@ -0,0 +1,58 @@ +#pragma once +#ifndef LIGHT_LOGGER_H + #define LIGHT_LOGGER_H + + #include + #include + + #define LT_LOG_FILE_LOCATION "Logs/Logger.txt" + + #ifndef LIGHT_DIST + #define LOG(logLevel, ...) \ + SPDLOG_LOGGER_CALL( \ + ::Light::Logger::GetEngineLogger(), \ + spdlog::level::logLevel, \ + __VA_ARGS__ \ + ) + #else + #define LOG(logLevel, ...) \ + SPDLOG_LOGGER_CALL( \ + ::Light::Logger::GetFileLogger(), \ + spdlog::level::logLevel, \ + __VA_ARGS__ \ + ) + #endif + +namespace Light { + +// #todo: extend +class Logger /* singleton */ +{ +private: + static Logger *s_Context; + +private: + Ref m_EngineLogger, m_FileLogger; + std::string m_LogFilePath; + +public: + static Scope Create(); + + static inline Ref GetEngineLogger() + { + return s_Context->m_EngineLogger; + } + static inline Ref GetFileLogger() + { + return s_Context->m_FileLogger; + } + + void LogDebugData(); + +private: + Logger(); +}; + +} // namespace Light + +#endif diff --git a/modules/engine/include/engine/engine.hpp b/modules/engine/include/engine/engine.hpp new file mode 100644 index 0000000..4b30d32 --- /dev/null +++ b/modules/engine/include/engine/engine.hpp @@ -0,0 +1,61 @@ +#pragma once + +// core +#include +#include + +// camera +#include + +// debug +#include + +// events +#include +#include +#include +#include +#include + +// graphics +#include +#include +#include +#include + +// input +#include +#include +#include + +// layer +#include +#include + +// user interface +#include + +// utility +#include + +// time +#include + +// base +#include + +// third party +#include + +// math +#include + +// scene +#include +#include +#include + +// entry point +#ifdef LIGHT_ENTRY_POINT + #include +#endif diff --git a/Engine/src/Engine/Events/CharEvent.hpp b/modules/engine/include/engine/events/char.hpp similarity index 63% rename from Engine/src/Engine/Events/CharEvent.hpp rename to modules/engine/include/engine/events/char.hpp index 1638911..c3dc01f 100644 --- a/Engine/src/Engine/Events/CharEvent.hpp +++ b/modules/engine/include/engine/events/char.hpp @@ -1,8 +1,7 @@ #pragma once -#include "Base/Base.hpp" -#include "Event.hpp" - +#include +#include #include namespace Light { @@ -13,12 +12,14 @@ private: const unsigned int m_Character; public: - SetCharEvent(unsigned int character) - : m_Character(character) + SetCharEvent(unsigned int character): m_Character(character) { } - inline int GetCharacter() const { return m_Character; } + inline int GetCharacter() const + { + return m_Character; + } virtual std::string GetInfoLog() const override { @@ -30,4 +31,4 @@ public: EVENT_CATEGORY(InputEventCategory | KeyboardEventCategory) }; -} // namespace Light \ No newline at end of file +} // namespace Light diff --git a/modules/engine/include/engine/events/event.hpp b/modules/engine/include/engine/events/event.hpp new file mode 100644 index 0000000..606eede --- /dev/null +++ b/modules/engine/include/engine/events/event.hpp @@ -0,0 +1,63 @@ +#pragma once + +#include + +namespace Light { + +enum class EventType +{ + None = 0, + + // input + MouseMoved, + WheelScrolled, + ButtonPressed, + ButtonReleased, + KeyPressed, + KeyRepeated, + KeyReleased, + SetChar, + + // window + WindowMoved, + WindowResized, + WindowClosed, + WindowLostFocus, + WindowGainFocus, +}; + +enum EventCategory +{ + None = 0, + + WindowEventCategory = BIT(0), + InputEventCategory = BIT(1), + KeyboardEventCategory = BIT(2), + MouseEventCategory = BIT(3), +}; + +#define EVENT_TYPE(type) \ + EventType GetEventType() const override \ + { \ + return ::Light::EventType::type; \ + } +#define EVENT_CATEGORY(eCategory) \ + inline bool HasCategory(EventCategory category) const override \ + { \ + return (eCategory) & category; \ + } + +class Event +{ +public: + virtual EventType GetEventType() const = 0; + virtual std::string GetInfoLog() const = 0; + virtual bool HasCategory(EventCategory category) const = 0; + + friend std::ostream &operator<<(std::ostream &os, const Event &e) + { + return os << e.GetInfoLog(); + } +}; + +} // namespace Light diff --git a/Engine/src/Engine/Events/KeyboardEvents.hpp b/modules/engine/include/engine/events/keyboard.hpp similarity index 73% rename from Engine/src/Engine/Events/KeyboardEvents.hpp rename to modules/engine/include/engine/events/keyboard.hpp index b91c7ec..78b2109 100644 --- a/Engine/src/Engine/Events/KeyboardEvents.hpp +++ b/modules/engine/include/engine/events/keyboard.hpp @@ -1,8 +1,7 @@ #pragma once -#include "Base/Base.hpp" -#include "Event.hpp" - +#include +#include #include namespace Light { @@ -13,12 +12,14 @@ private: const int m_Key; public: - KeyPressedEvent(int key) - : m_Key(key) + KeyPressedEvent(int key): m_Key(key) { } - inline int GetKey() const { return m_Key; } + inline int GetKey() const + { + return m_Key; + } virtual std::string GetInfoLog() const override { @@ -36,12 +37,14 @@ private: const int m_Key; public: - KeyRepeatEvent(int key) - : m_Key(key) + KeyRepeatEvent(int key): m_Key(key) { } - inline int GetKey() const { return m_Key; } + inline int GetKey() const + { + return m_Key; + } virtual std::string GetInfoLog() const override { @@ -59,12 +62,14 @@ private: const int m_Key; public: - KeyReleasedEvent(int key) - : m_Key(key) + KeyReleasedEvent(int key): m_Key(key) { } - inline int GetKey() const { return m_Key; } + inline int GetKey() const + { + return m_Key; + } virtual std::string GetInfoLog() const override { @@ -76,4 +81,4 @@ public: EVENT_CATEGORY(InputEventCategory | KeyboardEventCategory) }; -} // namespace Light \ No newline at end of file +} // namespace Light diff --git a/Engine/src/Engine/Events/MouseEvents.hpp b/modules/engine/include/engine/events/mouse.hpp similarity index 67% rename from Engine/src/Engine/Events/MouseEvents.hpp rename to modules/engine/include/engine/events/mouse.hpp index f83c3da..44211cb 100644 --- a/Engine/src/Engine/Events/MouseEvents.hpp +++ b/modules/engine/include/engine/events/mouse.hpp @@ -1,8 +1,7 @@ #pragma once -#include "Base/Base.hpp" -#include "Event.hpp" - +#include +#include #include #include @@ -14,15 +13,23 @@ private: const glm::vec2 m_Position; public: - MouseMovedEvent(float x, float y) - : m_Position(x, y) + MouseMovedEvent(float x, float y): m_Position(x, y) { } - inline const glm::vec2& GetPosition() const { return m_Position; } + inline const glm::vec2 &GetPosition() const + { + return m_Position; + } - inline float GetX() const { return m_Position.x; } - inline float GetY() const { return m_Position.y; } + inline float GetX() const + { + return m_Position.x; + } + inline float GetY() const + { + return m_Position.y; + } virtual std::string GetInfoLog() const override { @@ -40,12 +47,14 @@ private: const float m_Offset; public: - WheelScrolledEvent(float offset) - : m_Offset(offset) + WheelScrolledEvent(float offset): m_Offset(offset) { } - inline float GetOffset() const { return m_Offset; } + inline float GetOffset() const + { + return m_Offset; + } virtual std::string GetInfoLog() const override { @@ -63,12 +72,14 @@ private: const int m_Button; public: - ButtonPressedEvent(int button) - : m_Button(button) + ButtonPressedEvent(int button): m_Button(button) { } - inline int GetButton() const { return m_Button; } + inline int GetButton() const + { + return m_Button; + } virtual std::string GetInfoLog() const override { @@ -86,12 +97,14 @@ private: const int m_Button; public: - ButtonReleasedEvent(int button) - : m_Button(button) + ButtonReleasedEvent(int button): m_Button(button) { } - inline int GetButton() const { return m_Button; } + inline int GetButton() const + { + return m_Button; + } virtual std::string GetInfoLog() const override { @@ -103,4 +116,4 @@ public: EVENT_CATEGORY(InputEventCategory | MouseEventCategory) }; -} // namespace Light \ No newline at end of file +} // namespace Light diff --git a/Engine/src/Engine/Events/WindowEvents.hpp b/modules/engine/include/engine/events/window.hpp similarity index 79% rename from Engine/src/Engine/Events/WindowEvents.hpp rename to modules/engine/include/engine/events/window.hpp index 5a9ed7c..2b3365e 100644 --- a/Engine/src/Engine/Events/WindowEvents.hpp +++ b/modules/engine/include/engine/events/window.hpp @@ -1,8 +1,7 @@ #pragma once -#include "Base/Base.hpp" -#include "Event.hpp" - +#include +#include #include #include @@ -25,12 +24,14 @@ private: const glm::ivec2 m_Position; public: - WindowMovedEvent(int x, int y) - : m_Position(x, y) + WindowMovedEvent(int x, int y): m_Position(x, y) { } - const glm::ivec2& GetPosition() const { return m_Position; } + const glm::ivec2 &GetPosition() const + { + return m_Position; + } virtual std::string GetInfoLog() const override { @@ -49,12 +50,14 @@ private: const glm::uvec2 m_Size; public: - WindowResizedEvent(unsigned int width, unsigned int height) - : m_Size(width, height) + WindowResizedEvent(unsigned int width, unsigned int height): m_Size(width, height) { } - const glm::uvec2& GetSize() const { return m_Size; } + const glm::uvec2 &GetSize() const + { + return m_Size; + } virtual std::string GetInfoLog() const override { @@ -88,4 +91,4 @@ public: EVENT_CATEGORY(WindowEventCategory) }; -} // namespace Light \ No newline at end of file +} // namespace Light diff --git a/Engine/src/Engine/Graphics/Blender.hpp b/modules/engine/include/engine/graphics/blender.hpp similarity index 95% rename from Engine/src/Engine/Graphics/Blender.hpp rename to modules/engine/include/engine/graphics/blender.hpp index fd5eb95..f9a9479 100644 --- a/Engine/src/Engine/Graphics/Blender.hpp +++ b/modules/engine/include/engine/graphics/blender.hpp @@ -1,6 +1,6 @@ #pragma once -#include "Base/Base.hpp" +#include namespace Light { diff --git a/Engine/src/Engine/Graphics/Buffers.hpp b/modules/engine/include/engine/graphics/buffers.hpp similarity index 95% rename from Engine/src/Engine/Graphics/Buffers.hpp rename to modules/engine/include/engine/graphics/buffers.hpp index 6d063e5..16a77b9 100644 --- a/Engine/src/Engine/Graphics/Buffers.hpp +++ b/modules/engine/include/engine/graphics/buffers.hpp @@ -1,6 +1,6 @@ #pragma once -#include "Base/Base.hpp" +#include namespace Light { @@ -59,4 +59,4 @@ protected: IndexBuffer() = default; }; -} // namespace Light \ No newline at end of file +} // namespace Light diff --git a/Engine/src/Engine/Graphics/Framebuffer.hpp b/modules/engine/include/engine/graphics/framebuffer.hpp similarity index 91% rename from Engine/src/Engine/Graphics/Framebuffer.hpp rename to modules/engine/include/engine/graphics/framebuffer.hpp index e7c774b..16111e7 100644 --- a/Engine/src/Engine/Graphics/Framebuffer.hpp +++ b/modules/engine/include/engine/graphics/framebuffer.hpp @@ -1,6 +1,6 @@ #pragma once -#include "Base/Base.hpp" +#include #include @@ -30,4 +30,4 @@ protected: Framebuffer() = default; }; -} // namespace Light \ No newline at end of file +} // namespace Light diff --git a/Engine/src/Engine/Graphics/GraphicsContext.hpp b/modules/engine/include/engine/graphics/graphics_context.hpp similarity index 95% rename from Engine/src/Engine/Graphics/GraphicsContext.hpp rename to modules/engine/include/engine/graphics/graphics_context.hpp index adf5632..b4f2c1e 100644 --- a/Engine/src/Engine/Graphics/GraphicsContext.hpp +++ b/modules/engine/include/engine/graphics/graphics_context.hpp @@ -1,6 +1,6 @@ #pragma once -#include "Base/Base.hpp" +#include struct GLFWwindow; @@ -56,4 +56,4 @@ protected: GraphicsContext() = default; }; -} // namespace Light \ No newline at end of file +} // namespace Light diff --git a/modules/engine/include/engine/graphics/render_command.hpp b/modules/engine/include/engine/graphics/render_command.hpp new file mode 100644 index 0000000..8e7211b --- /dev/null +++ b/modules/engine/include/engine/graphics/render_command.hpp @@ -0,0 +1,41 @@ +#pragma once + +#include +#include + +struct GLFWwindow; + +namespace Light { + +class SharedContext; + +class RenderCommand +{ +public: + static Scope Create(GLFWwindow *windowHandle, Ref sharedContext); + + RenderCommand(const RenderCommand &) = delete; + RenderCommand &operator=(const RenderCommand &) = delete; + + virtual ~RenderCommand() = default; + + virtual void SwapBuffers() = 0; + virtual void ClearBackBuffer(const glm::vec4 &clearColor) = 0; + + virtual void Draw(unsigned int count) = 0; + virtual void DrawIndexed(unsigned int count) = 0; + + virtual void DefaultTargetFramebuffer() = 0; + + virtual void SetViewport( + unsigned int x, + unsigned int y, + unsigned int width, + unsigned int height + ) = 0; + +protected: + RenderCommand() = default; +}; + +} // namespace Light diff --git a/modules/engine/include/engine/graphics/renderer.hpp b/modules/engine/include/engine/graphics/renderer.hpp new file mode 100644 index 0000000..9202df5 --- /dev/null +++ b/modules/engine/include/engine/graphics/renderer.hpp @@ -0,0 +1,134 @@ +#pragma once + +#include +#include +#include +#include + +#define LT_MAX_QUAD_RENDERER_VERTICES 1028u * 4u +#define LT_MAX_TEXTURE_RENDERER_VERTICES 1028u * 4u +#define LT_MAX_TINTED_TEXTURE_RENDERER_VERTICES 1028u * 4u + +struct GLFWwindow; + +namespace Light { + +class Blender; +class ConstantBuffer; +class Framebuffer; +class RenderCommand; +class Texture; + +class SharedContext; + +class Camera; + +class WindowResizedEvent; + +class Renderer +{ +private: + static Renderer *s_Context; + + // renderer programs + QuadRendererProgram m_QuadRenderer; + TextureRendererProgram m_TextureRenderer; + TintedTextureRendererProgram m_TintedTextureRenderer; + + // constant buffers + Scope m_ViewProjectionBuffer; + + Scope m_RenderCommand; + Scope m_Blender; + + Camera *m_DefaultFramebufferCamera; + Ref m_TargetFramebuffer; + + bool m_ShouldClearBackbuffer; + +public: + static Scope Create(GLFWwindow *windowHandle, Ref sharedContext); + + static inline void DrawQuad( + const glm::vec3 &position, + const glm::vec2 &size, + const glm::vec4 &tint, + Ref texture + ) + { + s_Context->DrawQuadImpl(position, size, tint, texture); + } + static inline void DrawQuad( + const glm::vec3 &position, + const glm::vec2 &size, + const glm::vec4 &tint + ) + { + s_Context->DrawQuadImpl(position, size, tint); + } + static inline void DrawQuad( + const glm::vec3 &position, + const glm::vec2 &size, + Ref texture + ) + { + s_Context->DrawQuadImpl(position, size, texture); + } + + static void DrawQuad(const glm::mat4 &transform, const glm::vec4 &tint, Ref texture) + { + s_Context->DrawQuadImpl(transform, tint, texture); + } + static void DrawQuad(const glm::mat4 &transform, const glm::vec4 &tint) + { + s_Context->DrawQuadImpl(transform, tint); + } + static void DrawQuad(const glm::mat4 &transform, Ref texture) + { + s_Context->DrawQuadImpl(transform, texture); + } + + static inline void BeginScene( + Camera *camera, + const glm::mat4 &cameraTransform, + const Ref &targetFrameBuffer = nullptr + ) + { + s_Context->BeginSceneImpl(camera, cameraTransform, targetFrameBuffer); + } + static inline void EndScene() + { + s_Context->EndSceneImpl(); + } + + void OnWindowResize(const WindowResizedEvent &event); + + void BeginFrame(); + void EndFrame(); + +private: + Renderer(GLFWwindow *windowHandle, Ref sharedContext); + + void DrawQuadImpl( + const glm::vec3 &position, + const glm::vec2 &size, + const glm::vec4 &tint, + Ref texture + ); + void DrawQuadImpl(const glm::vec3 &position, const glm::vec2 &size, const glm::vec4 &tint); + void DrawQuadImpl(const glm::vec3 &position, const glm::vec2 &size, Ref texture); + + void DrawQuadImpl(const glm::mat4 &transform, const glm::vec4 &tint, Ref texture); + void DrawQuadImpl(const glm::mat4 &transform, const glm::vec4 &tint); + void DrawQuadImpl(const glm::mat4 &transform, Ref texture); + + void BeginSceneImpl( + Camera *camera, + const glm::mat4 &cameraTransform, + const Ref &targetFrameBuffer = nullptr + ); + void FlushScene(); + void EndSceneImpl(); +}; + +} // namespace Light diff --git a/Engine/src/Engine/Graphics/RendererPrograms/QuadRendererProgram.hpp b/modules/engine/include/engine/graphics/renderer_programs/quad.hpp similarity index 58% rename from Engine/src/Engine/Graphics/RendererPrograms/QuadRendererProgram.hpp rename to modules/engine/include/engine/graphics/renderer_programs/quad.hpp index 571e98d..369abbe 100644 --- a/Engine/src/Engine/Graphics/RendererPrograms/QuadRendererProgram.hpp +++ b/modules/engine/include/engine/graphics/renderer_programs/quad.hpp @@ -1,8 +1,7 @@ #pragma once -#include "Base/Base.hpp" -#include "RendererProgram.hpp" - +#include +#include #include namespace Light { @@ -31,10 +30,10 @@ private: Ref m_IndexBuffer; Ref m_VertexLayout; - QuadVertexData* m_MapCurrent = nullptr; - QuadVertexData* m_MapEnd = nullptr; + QuadVertexData *m_MapCurrent = nullptr; + QuadVertexData *m_MapEnd = nullptr; - unsigned int m_QuadCount = 0u; + unsigned int m_QuadCount = 0u; unsigned int m_MaxVertices = 0u; public: @@ -47,9 +46,18 @@ public: void Bind() override; - inline QuadVertexData* GetMapCurrent() { return m_MapCurrent; } - inline unsigned int GetQuadCount() const { return m_QuadCount; } - inline constexpr unsigned int GetVertexSize() const { return sizeof(QuadVertexData); } + inline QuadVertexData *GetMapCurrent() + { + return m_MapCurrent; + } + inline unsigned int GetQuadCount() const + { + return m_QuadCount; + } + inline constexpr unsigned int GetVertexSize() const + { + return sizeof(QuadVertexData); + } }; -} // namespace Light \ No newline at end of file +} // namespace Light diff --git a/Engine/src/Engine/Graphics/RendererPrograms/RendererProgram.hpp b/modules/engine/include/engine/graphics/renderer_programs/renderer_program.hpp similarity index 76% rename from Engine/src/Engine/Graphics/RendererPrograms/RendererProgram.hpp rename to modules/engine/include/engine/graphics/renderer_programs/renderer_program.hpp index bb27c41..f32d663 100644 --- a/Engine/src/Engine/Graphics/RendererPrograms/RendererProgram.hpp +++ b/modules/engine/include/engine/graphics/renderer_programs/renderer_program.hpp @@ -1,6 +1,6 @@ #pragma once -#include "Base/Base.hpp" +#include namespace Light { @@ -14,4 +14,4 @@ class RendererProgram virtual void Bind() = 0; }; -} // namespace Light \ No newline at end of file +} // namespace Light diff --git a/Engine/src/Engine/Graphics/RendererPrograms/TextureRendererProgram.hpp b/modules/engine/include/engine/graphics/renderer_programs/texture.hpp similarity index 61% rename from Engine/src/Engine/Graphics/RendererPrograms/TextureRendererProgram.hpp rename to modules/engine/include/engine/graphics/renderer_programs/texture.hpp index 285ed04..48f901d 100644 --- a/Engine/src/Engine/Graphics/RendererPrograms/TextureRendererProgram.hpp +++ b/modules/engine/include/engine/graphics/renderer_programs/texture.hpp @@ -1,8 +1,7 @@ #pragma once -#include "Base/Base.hpp" -#include "RendererProgram.hpp" - +#include +#include #include namespace Light { @@ -31,8 +30,8 @@ private: Ref m_IndexBuffer; Ref m_VertexLayout; - TextureVertexData* m_MapCurrent = nullptr; - TextureVertexData* m_MapEnd = nullptr; + TextureVertexData *m_MapCurrent = nullptr; + TextureVertexData *m_MapEnd = nullptr; unsigned int m_QuadCount; unsigned int m_MaxVertices; @@ -47,11 +46,20 @@ public: void Bind() override; - inline TextureVertexData* GetMapCurrent() { return m_MapCurrent; } + inline TextureVertexData *GetMapCurrent() + { + return m_MapCurrent; + } - inline unsigned int GetQuadCount() const { return m_QuadCount; } + inline unsigned int GetQuadCount() const + { + return m_QuadCount; + } - inline constexpr unsigned int GetVertexSize() const { return sizeof(TextureVertexData); } + inline constexpr unsigned int GetVertexSize() const + { + return sizeof(TextureVertexData); + } }; -} // namespace Light \ No newline at end of file +} // namespace Light diff --git a/Engine/src/Engine/Graphics/RendererPrograms/TintedTextureRendererProgram.hpp b/modules/engine/include/engine/graphics/renderer_programs/tinted_texture.hpp similarity index 61% rename from Engine/src/Engine/Graphics/RendererPrograms/TintedTextureRendererProgram.hpp rename to modules/engine/include/engine/graphics/renderer_programs/tinted_texture.hpp index 1fd308b..e7ff698 100644 --- a/Engine/src/Engine/Graphics/RendererPrograms/TintedTextureRendererProgram.hpp +++ b/modules/engine/include/engine/graphics/renderer_programs/tinted_texture.hpp @@ -1,8 +1,7 @@ #pragma once -#include "Base/Base.hpp" -#include "RendererProgram.hpp" - +#include +#include #include namespace Light { @@ -32,8 +31,8 @@ private: Ref m_IndexBuffer; Ref m_VertexLayout; - TintedTextureVertexData* m_MapCurrent = nullptr; - TintedTextureVertexData* m_MapEnd = nullptr; + TintedTextureVertexData *m_MapCurrent = nullptr; + TintedTextureVertexData *m_MapEnd = nullptr; unsigned int m_QuadCount; unsigned int m_MaxVertices; @@ -48,11 +47,20 @@ public: void Bind() override; - inline TintedTextureVertexData* GetMapCurrent() { return m_MapCurrent; } + inline TintedTextureVertexData *GetMapCurrent() + { + return m_MapCurrent; + } - inline unsigned int GetQuadCount() const { return m_QuadCount; } + inline unsigned int GetQuadCount() const + { + return m_QuadCount; + } - inline constexpr unsigned int GetVertexSize() const { return sizeof(TintedTextureVertexData); } + inline constexpr unsigned int GetVertexSize() const + { + return sizeof(TintedTextureVertexData); + } }; -} // namespace Light \ No newline at end of file +} // namespace Light diff --git a/modules/engine/include/engine/graphics/shader.hpp b/modules/engine/include/engine/graphics/shader.hpp new file mode 100644 index 0000000..d1ddc03 --- /dev/null +++ b/modules/engine/include/engine/graphics/shader.hpp @@ -0,0 +1,38 @@ +#pragma once + +#include +#include +#include + +namespace Light { + +class SharedContext; + +class Shader +{ +public: + enum Stage + { + NONE = 0, + VERTEX = 1, + PIXEL = 2, + GEOMETRY = 3 + }; + +public: + static Ref Create( + BasicFileHandle vertexFile, + BasicFileHandle pixelFile, + Ref sharedContext + ); + + virtual ~Shader() = default; + + virtual void Bind() = 0; + virtual void UnBind() = 0; + +protected: + Shader() = default; +}; + +} // namespace Light diff --git a/Engine/src/Engine/Graphics/SharedContext.hpp b/modules/engine/include/engine/graphics/shared_context.hpp similarity index 66% rename from Engine/src/Engine/Graphics/SharedContext.hpp rename to modules/engine/include/engine/graphics/shared_context.hpp index c687d97..53a3d83 100644 --- a/Engine/src/Engine/Graphics/SharedContext.hpp +++ b/modules/engine/include/engine/graphics/shared_context.hpp @@ -1,6 +1,6 @@ #pragma once -#include "Base/Base.hpp" +#include namespace Light { @@ -10,4 +10,4 @@ public: virtual ~SharedContext() = default; }; -} // namespace Light \ No newline at end of file +} // namespace Light diff --git a/Engine/src/Engine/Graphics/Texture.hpp b/modules/engine/include/engine/graphics/texture.hpp similarity index 95% rename from Engine/src/Engine/Graphics/Texture.hpp rename to modules/engine/include/engine/graphics/texture.hpp index 9c3266f..07b9d24 100644 --- a/Engine/src/Engine/Graphics/Texture.hpp +++ b/modules/engine/include/engine/graphics/texture.hpp @@ -1,6 +1,6 @@ #pragma once -#include "Base/Base.hpp" +#include namespace Light { diff --git a/Engine/src/Engine/Graphics/VertexLayout.hpp b/modules/engine/include/engine/graphics/vertex_layout.hpp similarity index 58% rename from Engine/src/Engine/Graphics/VertexLayout.hpp rename to modules/engine/include/engine/graphics/vertex_layout.hpp index ebe22bf..cd15773 100644 --- a/Engine/src/Engine/Graphics/VertexLayout.hpp +++ b/modules/engine/include/engine/graphics/vertex_layout.hpp @@ -1,6 +1,6 @@ #pragma once -#include "Base/Base.hpp" +#include namespace Light { @@ -34,16 +34,21 @@ enum class VertexElementType class VertexLayout { public: - static Ref Create(Ref vertexBuffer, Ref shader, const std::vector>& elements, Ref sharedContext); + static Ref Create( + Ref vertexBuffer, + Ref shader, + const std::vector> &elements, + Ref sharedContext + ); virtual ~VertexLayout() = default; ; - virtual void Bind() = 0; + virtual void Bind() = 0; virtual void UnBind() = 0; protected: VertexLayout() = default; }; -} // namespace Light \ No newline at end of file +} // namespace Light diff --git a/modules/engine/include/engine/input/input.hpp b/modules/engine/include/engine/input/input.hpp new file mode 100644 index 0000000..581f9a0 --- /dev/null +++ b/modules/engine/include/engine/input/input.hpp @@ -0,0 +1,73 @@ +#pragma once + +#include +#include +#include + +namespace Light { + +class Event; + +class Input /* singleton */ +{ +private: + static Input *s_Context; + +private: + std::array m_KeyboadKeys; + std::array m_MouseButtons; + + glm::vec2 m_MousePosition; + glm::vec2 m_MouseDelta; + float m_MouseWheelDelta; + + bool m_UserInterfaceEvents; + bool m_GameEvents; + +public: + static Scope Create(); + + static inline void ReceiveUserInterfaceEvents(bool receive, bool toggle = false) + { + s_Context->ReceiveUserInterfaceEventsImpl(receive, toggle); + } + static inline void ReceiveGameEvents(bool receive, bool toggle = false) + { + s_Context->ReceieveGameEventsImpl(receive, toggle); + } + + static inline bool GetKeyboardKey(int code) + { + return s_Context->m_KeyboadKeys[code]; + } + static inline bool GetMouseButton(int code) + { + return s_Context->m_MouseButtons[code]; + } + + static inline const glm::vec2 &GetMousePosition(int code) + { + return s_Context->m_MousePosition; + } + + void OnEvent(const Event &inputEvent); + + inline bool IsReceivingInputEvents() const + { + return m_UserInterfaceEvents; + } + inline bool IsReceivingGameEvents() const + { + return m_GameEvents; + } + +private: + Input(); + + void ReceiveUserInterfaceEventsImpl(bool receive, bool toggle = false); + void ReceieveGameEventsImpl(bool receive, bool toggle = false); + + void RestartInputState(); +}; + +} // namespace Light diff --git a/modules/engine/include/engine/input/key_codes.hpp b/modules/engine/include/engine/input/key_codes.hpp new file mode 100644 index 0000000..f2fe2ae --- /dev/null +++ b/modules/engine/include/engine/input/key_codes.hpp @@ -0,0 +1,182 @@ +#pragma once + +#include + +namespace Light { + +namespace Key { +enum : uint16_t +{ + /* digits */ + D0 = 48, + D1 = 49, + D2 = 50, + D3 = 51, + D4 = 52, + D5 = 53, + D6 = 54, + D7 = 55, + D8 = 56, + D9 = 57, + Semicolon = 59, // ; + Equal = 61, // = + + /* letters */ + A = 65, + B = 66, + C = 67, + D = 68, + E = 69, + F = 70, + G = 71, + H = 72, + I = 73, + J = 74, + K = 75, + L = 76, + M = 77, + N = 78, + O = 79, + P = 80, + Q = 81, + R = 82, + S = 83, + T = 84, + U = 85, + V = 86, + W = 87, + X = 88, + Y = 89, + Z = 90, + + /* brackets */ + LeftBracket = 91, // [ + LBracket = LeftBracket, // [ + RightBracket = 93, // ] + RBracket = RightBracket, // ] + + /* arrow */ + Right = 262, + RightArrow = Right, + RArrow = Right, + Left = 263, + LeftArrow = Left, + LArrow = Left, + Down = 264, + DownArrow = Down, + DArrow = Down, + Up = 265, + UpArrow = Up, + UArrow = Up, + + /* page */ + PageUp = 266, + PageDown = 267, + + /* home/end */ + Home = 268, + End = 269, + + /* toggles */ + CapsLock = 280, + ScrollLock = 281, + NumLock = 282, + NumberLock = NumLock, + + /* function */ + F1 = 290, + F2 = 291, + F3 = 292, + F4 = 293, + F5 = 294, + F6 = 295, + F7 = 296, + F8 = 297, + F9 = 298, + F10 = 299, + F11 = 300, + F12 = 301, + F13 = 302, + F14 = 303, + F15 = 304, + F16 = 305, + F17 = 306, + F18 = 307, + F19 = 308, + F20 = 309, + F21 = 310, + F22 = 311, + F23 = 312, + F24 = 313, + F25 = 314, + + /* keypad */ + Kp0 = 320, + Kp1 = 321, + Kp2 = 322, + Kp3 = 323, + Kp4 = 324, + Kp5 = 325, + Kp6 = 326, + Kp7 = 327, + Kp8 = 328, + Kp9 = 329, + KpDecimal = 330, + KpDivide = 331, + KpMultiply = 332, + KpSubstract = 333, + KpAdd = 334, + KpEnter = 335, + KpEqual = 336, + + /* modifiers */ + LeftShift = 340, + LShift = LeftShift, + LeftControl = 341, + LControl = LeftControl, + LeftAlt = 342, + LAlt = LeftAlt, + LeftSuper = 343, + LSuper = LeftSuper, + RightShift = 344, + RShift = 344, + RightControl = 345, + RControl = 345, + RightAlt = 346, + RAlt = 346, + RightSuper = 347, + RSuper = 347, + + /* misc */ + Space = 32, + Apostrophe = 39, // ' + Quote = Apostrophe, + + Comma = 44, // , + Minus = 45, // - + Period = 46, // . + Slash = 47, // / + ForwardSlash = Slash, // / + BackSlash = 92, // \ + + GraveAccent = 96, // ` + Console = GraveAccent, + World1 = 161, // non-US #1 + World2 = 162, // non-US #2 + Escape = 256, + Esc = Escape, + Enter = 257, + Tab = 258, + BackSpace = 259, + Insert = 260, + Delete = 261, + + PrintScreen = 283, + Pause = 284, + + Menu = 348, + +}; +} + +} // namespace Light diff --git a/Engine/src/Engine/Input/MouseCodes.hpp b/modules/engine/include/engine/input/mouse_codes.hpp similarity index 86% rename from Engine/src/Engine/Input/MouseCodes.hpp rename to modules/engine/include/engine/input/mouse_codes.hpp index 0bc16d7..6840792 100644 --- a/Engine/src/Engine/Input/MouseCodes.hpp +++ b/modules/engine/include/engine/input/mouse_codes.hpp @@ -1,7 +1,5 @@ #pragma once -#include "ltpch.hpp" - #include namespace Light { @@ -24,4 +22,4 @@ enum : uint8_t }; } -} // namespace Light \ No newline at end of file +} // namespace Light diff --git a/modules/engine/include/engine/layer/layer.hpp b/modules/engine/include/engine/layer/layer.hpp new file mode 100644 index 0000000..c481477 --- /dev/null +++ b/modules/engine/include/engine/layer/layer.hpp @@ -0,0 +1,126 @@ +#pragma once + +#include + +namespace Light { + +class Event; + +// mouse +class MouseMovedEvent; +class ButtonPressedEvent; +class ButtonReleasedEvent; +class WheelScrolledEvent; + +// keyboard +// key +class KeyPressedEvent; +class KeyRepeatEvent; +class KeyReleasedEvent; +// char +class SetCharEvent; + +// window +class WindowClosedEvent; +class WindowResizedEvent; +class WindowMovedEvent; +class WindowLostFocusEvent; +class WindowGainFocusEvent; + +class Layer +{ +protected: + std::string m_LayerName; + +public: + Layer(const std::string &name); + virtual ~Layer() = default; + + inline const std::string &GetName() const + { + return m_LayerName; + } + + /* update */ + virtual void OnUpdate(float deltaTime) + { + } + virtual void OnUserInterfaceUpdate() + { + } + + virtual void OnRender() + { + } + + bool OnEvent(const Event &event); + +protected: + /* mouse */ + // cursor + virtual bool OnMouseMoved(const MouseMovedEvent &event) + { + return false; + } + // button + virtual bool OnButtonPressed(const ButtonPressedEvent &event) + { + return false; + } + virtual bool OnButtonReleased(const ButtonReleasedEvent &event) + { + return false; + } + // wheel + virtual bool OnWheelScrolled(const WheelScrolledEvent &event) + { + return false; + } + + /* keyboard */ + // key + virtual bool OnKeyPressed(const KeyPressedEvent &event) + { + return false; + } + virtual bool OnKeyRepeat(const KeyRepeatEvent &event) + { + return false; + } + virtual bool OnKeyReleased(const KeyReleasedEvent &event) + { + return false; + } + // char + virtual bool OnSetChar(const SetCharEvent &event) + { + return false; + } + + /* window */ + // termination + virtual bool OnWindowClosed(const WindowClosedEvent &event) + { + return false; + } + // size/position + virtual bool OnWindowResized(const WindowResizedEvent &event) + { + return false; + } + virtual bool OnWindowMoved(const WindowMovedEvent &event) + { + return false; + } + // focus + virtual bool OnWindowLostFocus(const WindowLostFocusEvent &event) + { + return false; + } + virtual bool OnWindowGainFocus(const WindowGainFocusEvent &event) + { + return false; + } +}; + +} // namespace Light diff --git a/modules/engine/include/engine/layer/layer_stack.hpp b/modules/engine/include/engine/layer/layer_stack.hpp new file mode 100644 index 0000000..57dd8ea --- /dev/null +++ b/modules/engine/include/engine/layer/layer_stack.hpp @@ -0,0 +1,72 @@ +#pragma once + +#include + +namespace Light { + +class Layer; + +class Event; + +class LayerStack /* singleton */ +{ +private: + static LayerStack *s_Context; + +private: + std::vector m_Layers; + + std::vector::iterator m_Begin; + std::vector::iterator m_End; + +public: + static Scope Create(); + + ~LayerStack(); + + // #todo: is this needed? + template + static inline void EmplaceLayer(Args &&...args) + { + s_Context->AttachLayerImpl(new T((args)...)); + } + + static inline void AttachLayer(Layer *layer) + { + s_Context->AttachLayerImpl(layer); + } + static inline void DetachLayer(Layer *layer) + { + s_Context->DetachLayerImpl(layer); + } + + inline bool IsEmpty() + { + return m_Layers.empty(); + } + + std::vector::iterator begin() + { + return m_Layers.begin(); + } + std::vector::iterator end() + { + return m_Layers.end(); + } + std::vector::reverse_iterator rbegin() + { + return m_Layers.rbegin(); + } + std::vector::reverse_iterator rend() + { + return m_Layers.rend(); + } + +private: + LayerStack(); + + void AttachLayerImpl(Layer *layer); + void DetachLayerImpl(Layer *layer); +}; + +} // namespace Light diff --git a/Engine/src/Engine/Math/Random.hpp b/modules/engine/include/engine/math/random.hpp similarity index 100% rename from Engine/src/Engine/Math/Random.hpp rename to modules/engine/include/engine/math/random.hpp diff --git a/Engine/src/Platform/GraphicsAPI/DirectX/dxBlender.hpp b/modules/engine/include/engine/platform/graphics/directx/blender.hpp similarity index 83% rename from Engine/src/Platform/GraphicsAPI/DirectX/dxBlender.hpp rename to modules/engine/include/engine/platform/graphics/directx/blender.hpp index 698fead..e09fb30 100644 --- a/Engine/src/Platform/GraphicsAPI/DirectX/dxBlender.hpp +++ b/modules/engine/include/engine/platform/graphics/directx/blender.hpp @@ -1,9 +1,8 @@ #pragma once -#include "Base/Base.hpp" -#include "Graphics/Blender.hpp" - #include +#include +#include #include namespace Light { @@ -28,4 +27,4 @@ public: void Disable() override; }; -} // namespace Light \ No newline at end of file +} // namespace Light diff --git a/Engine/src/Platform/GraphicsAPI/DirectX/dxBuffers.hpp b/modules/engine/include/engine/platform/graphics/directx/buffers.hpp similarity index 69% rename from Engine/src/Platform/GraphicsAPI/DirectX/dxBuffers.hpp rename to modules/engine/include/engine/platform/graphics/directx/buffers.hpp index 805c6f8..1aa2439 100644 --- a/Engine/src/Platform/GraphicsAPI/DirectX/dxBuffers.hpp +++ b/modules/engine/include/engine/platform/graphics/directx/buffers.hpp @@ -1,9 +1,8 @@ #pragma once -#include "Base/Base.hpp" -#include "Graphics/Buffers.hpp" - #include +#include +#include #include namespace Light { @@ -22,11 +21,15 @@ private: unsigned int m_Index; public: - dxConstantBuffer(ConstantBufferIndex index, unsigned int size, Ref sharedContext); + dxConstantBuffer( + ConstantBufferIndex index, + unsigned int size, + Ref sharedContext + ); void Bind() override; - void* Map() override; + void *Map() override; void UnMap() override; }; @@ -42,13 +45,18 @@ private: unsigned int m_Stride; public: - dxVertexBuffer(float* vertices, unsigned int stride, unsigned int count, Ref sharedContext); + dxVertexBuffer( + float *vertices, + unsigned int stride, + unsigned int count, + Ref sharedContext + ); ~dxVertexBuffer(); void Bind() override; void UnBind() override; - void* Map() override; + void *Map() override; void UnMap() override; }; @@ -61,11 +69,11 @@ private: Microsoft::WRL::ComPtr m_Buffer; public: - dxIndexBuffer(unsigned int* indices, unsigned int count, Ref sharedContext); + dxIndexBuffer(unsigned int *indices, unsigned int count, Ref sharedContext); ~dxIndexBuffer(); void Bind() override; void UnBind() override; }; -} // namespace Light \ No newline at end of file +} // namespace Light diff --git a/Engine/src/Platform/GraphicsAPI/DirectX/dxFramebuffer.hpp b/modules/engine/include/engine/platform/graphics/directx/framebuffers.hpp similarity index 59% rename from Engine/src/Platform/GraphicsAPI/DirectX/dxFramebuffer.hpp rename to modules/engine/include/engine/platform/graphics/directx/framebuffers.hpp index c5ec426..f4053cc 100644 --- a/Engine/src/Platform/GraphicsAPI/DirectX/dxFramebuffer.hpp +++ b/modules/engine/include/engine/platform/graphics/directx/framebuffers.hpp @@ -1,9 +1,8 @@ #pragma once -#include "Base/Base.hpp" -#include "Graphics/Framebuffer.hpp" - #include +#include +#include #include namespace Light { @@ -24,14 +23,20 @@ private: Microsoft::WRL::ComPtr m_DepthStencilView; public: - dxFramebuffer(const FramebufferSpecification& specification, Ref sharedContext); + dxFramebuffer( + const FramebufferSpecification &specification, + Ref sharedContext + ); - inline void* GetColorAttachment() override { return (void*)m_ShaderResourceView.Get(); } + inline void *GetColorAttachment() override + { + return (void *)m_ShaderResourceView.Get(); + } - void BindAsTarget(const glm::vec4& clearColor) override; + void BindAsTarget(const glm::vec4 &clearColor) override; void BindAsResource() override; - void Resize(const glm::uvec2& size) override; + void Resize(const glm::uvec2 &size) override; }; -} // namespace Light \ No newline at end of file +} // namespace Light diff --git a/Engine/src/Platform/GraphicsAPI/DirectX/dxGraphicsContext.hpp b/modules/engine/include/engine/platform/graphics/directx/graphics_context.hpp similarity index 58% rename from Engine/src/Platform/GraphicsAPI/DirectX/dxGraphicsContext.hpp rename to modules/engine/include/engine/platform/graphics/directx/graphics_context.hpp index 867e505..48a8051 100644 --- a/Engine/src/Platform/GraphicsAPI/DirectX/dxGraphicsContext.hpp +++ b/modules/engine/include/engine/platform/graphics/directx/graphics_context.hpp @@ -1,9 +1,8 @@ #pragma once -#include "Base/Base.hpp" -#include "Graphics/GraphicsContext.hpp" - #include +#include +#include #include struct GLFWwindow; @@ -13,19 +12,19 @@ namespace Light { class dxGraphicsContext: public GraphicsContext { private: - GLFWwindow* m_WindowHandle; + GLFWwindow *m_WindowHandle; Microsoft::WRL::ComPtr m_DebugInterface; public: - dxGraphicsContext(GLFWwindow* windowHandle); + dxGraphicsContext(GLFWwindow *windowHandle); virtual void LogDebugData() override; private: - void SetupDeviceAndSwapChain(GLFWwindow* windowHandle); + void SetupDeviceAndSwapChain(GLFWwindow *windowHandle); void SetupRenderTargets(); void SetupDebugInterface(); }; -} // namespace Light \ No newline at end of file +} // namespace Light diff --git a/Engine/src/Platform/GraphicsAPI/DirectX/dxRenderCommand.hpp b/modules/engine/include/engine/platform/graphics/directx/render_command.hpp similarity index 63% rename from Engine/src/Platform/GraphicsAPI/DirectX/dxRenderCommand.hpp rename to modules/engine/include/engine/platform/graphics/directx/render_command.hpp index 1d26f53..cb08d76 100644 --- a/Engine/src/Platform/GraphicsAPI/DirectX/dxRenderCommand.hpp +++ b/modules/engine/include/engine/platform/graphics/directx/render_command.hpp @@ -1,9 +1,8 @@ #pragma once -#include "Base/Base.hpp" -#include "Graphics/RenderCommand.hpp" - #include +#include +#include #include namespace Light { @@ -19,17 +18,22 @@ public: dxRenderCommand(Ref sharedContext); virtual void SwapBuffers() override; - virtual void ClearBackBuffer(const glm::vec4& clearColor) override; + virtual void ClearBackBuffer(const glm::vec4 &clearColor) override; virtual void Draw(unsigned int count) override; virtual void DrawIndexed(unsigned int count) override; virtual void DefaultTargetFramebuffer() override; - virtual void SetViewport(unsigned int x, unsigned int y, unsigned int width, unsigned int height) override; + virtual void SetViewport( + unsigned int x, + unsigned int y, + unsigned int width, + unsigned int height + ) override; private: void SetResolution(unsigned int width, unsigned int height); }; -} // namespace Light \ No newline at end of file +} // namespace Light diff --git a/Engine/src/Platform/GraphicsAPI/DirectX/dxShader.hpp b/modules/engine/include/engine/platform/graphics/directx/shader.hpp similarity index 54% rename from Engine/src/Platform/GraphicsAPI/DirectX/dxShader.hpp rename to modules/engine/include/engine/platform/graphics/directx/shader.hpp index 3b500b4..76103b4 100644 --- a/Engine/src/Platform/GraphicsAPI/DirectX/dxShader.hpp +++ b/modules/engine/include/engine/platform/graphics/directx/shader.hpp @@ -1,10 +1,9 @@ #pragma once -#include "Base/Base.hpp" -#include "Graphics/Shader.hpp" -#include "Utility/FileManager.hpp" - #include +#include +#include +#include #include namespace Light { @@ -22,13 +21,20 @@ private: Microsoft::WRL::ComPtr m_VertexBlob; public: - dxShader(BasicFileHandle vertexFile, BasicFileHandle pixelFile, Ref sharedContext); + dxShader( + BasicFileHandle vertexFile, + BasicFileHandle pixelFile, + Ref sharedContext + ); ~dxShader(); void Bind() override; void UnBind() override; - inline Microsoft::WRL::ComPtr GetVertexBlob() { return m_VertexBlob; } + inline Microsoft::WRL::ComPtr GetVertexBlob() + { + return m_VertexBlob; + } }; -} // namespace Light \ No newline at end of file +} // namespace Light diff --git a/modules/engine/include/engine/platform/graphics/directx/shared_context.hpp b/modules/engine/include/engine/platform/graphics/directx/shared_context.hpp new file mode 100644 index 0000000..0a57914 --- /dev/null +++ b/modules/engine/include/engine/platform/graphics/directx/shared_context.hpp @@ -0,0 +1,54 @@ +#pragma once + +#include +#include +#include +#include + +namespace Light { + +class dxSharedContext: public SharedContext +{ +private: + Microsoft::WRL::ComPtr m_Device = nullptr; + Microsoft::WRL::ComPtr m_DeviceContext = nullptr; + Microsoft::WRL::ComPtr m_SwapChain = nullptr; + Microsoft::WRL::ComPtr m_RenderTargetView = nullptr; + +public: + inline Microsoft::WRL::ComPtr GetDevice() + { + return m_Device; + } + inline Microsoft::WRL::ComPtr GetDeviceContext() + { + return m_DeviceContext; + } + inline Microsoft::WRL::ComPtr GetSwapChain() + { + return m_SwapChain; + } + inline Microsoft::WRL::ComPtr GetRenderTargetView() + { + return m_RenderTargetView; + } + + inline Microsoft::WRL::ComPtr &GetDeviceRef() + { + return m_Device; + } + inline Microsoft::WRL::ComPtr &GetDeviceContextRef() + { + return m_DeviceContext; + } + inline Microsoft::WRL::ComPtr &GetSwapChainRef() + { + return m_SwapChain; + } + inline Microsoft::WRL::ComPtr &GetRenderTargetViewRef() + { + return m_RenderTargetView; + } +}; + +} // namespace Light diff --git a/Engine/src/Platform/GraphicsAPI/DirectX/dxTexture.hpp b/modules/engine/include/engine/platform/graphics/directx/texture.hpp similarity index 58% rename from Engine/src/Platform/GraphicsAPI/DirectX/dxTexture.hpp rename to modules/engine/include/engine/platform/graphics/directx/texture.hpp index 62ff41a..84516c5 100644 --- a/Engine/src/Platform/GraphicsAPI/DirectX/dxTexture.hpp +++ b/modules/engine/include/engine/platform/graphics/directx/texture.hpp @@ -1,9 +1,8 @@ #pragma once -#include "Base/Base.hpp" -#include "Graphics/Texture.hpp" - #include +#include +#include #include namespace Light { @@ -20,9 +19,16 @@ private: Microsoft::WRL::ComPtr m_SamplerState; public: - dxTexture(unsigned int width, unsigned int height, unsigned int components, unsigned char* pixels, Ref sharedContext, const std::string& filePath); + dxTexture( + unsigned int width, + unsigned int height, + unsigned int components, + unsigned char *pixels, + Ref sharedContext, + const std::string &filePath + ); void Bind(unsigned int slot = 0u) override; }; -} // namespace Light \ No newline at end of file +} // namespace Light diff --git a/Engine/src/Platform/GraphicsAPI/DirectX/dxUserInterface.hpp b/modules/engine/include/engine/platform/graphics/directx/user_interface.hpp similarity index 59% rename from Engine/src/Platform/GraphicsAPI/DirectX/dxUserInterface.hpp rename to modules/engine/include/engine/platform/graphics/directx/user_interface.hpp index e15e430..dbb3d62 100644 --- a/Engine/src/Platform/GraphicsAPI/DirectX/dxUserInterface.hpp +++ b/modules/engine/include/engine/platform/graphics/directx/user_interface.hpp @@ -1,9 +1,8 @@ #pragma once -#include "Base/Base.hpp" -#include "UserInterface/UserInterface.hpp" - #include +#include +#include #include struct GLFWwindow; @@ -18,7 +17,8 @@ public: dxUserInterface() = default; ~dxUserInterface(); - void PlatformImplementation(GLFWwindow* windowHandle, Ref sharedContext) override; + void PlatformImplementation(GLFWwindow *windowHandle, Ref sharedContext) + override; void Begin() override; void End() override; @@ -26,4 +26,4 @@ public: void LogDebugData() override; }; -} // namespace Light \ No newline at end of file +} // namespace Light diff --git a/Engine/src/Platform/GraphicsAPI/DirectX/dxVertexLayout.hpp b/modules/engine/include/engine/platform/graphics/directx/vertex_layout.hpp similarity index 60% rename from Engine/src/Platform/GraphicsAPI/DirectX/dxVertexLayout.hpp rename to modules/engine/include/engine/platform/graphics/directx/vertex_layout.hpp index d1f863d..3ac285b 100644 --- a/Engine/src/Platform/GraphicsAPI/DirectX/dxVertexLayout.hpp +++ b/modules/engine/include/engine/platform/graphics/directx/vertex_layout.hpp @@ -1,9 +1,8 @@ #pragma once -#include "Base/Base.hpp" -#include "Graphics/VertexLayout.hpp" - #include +#include +#include #include namespace Light { @@ -20,7 +19,11 @@ private: Microsoft::WRL::ComPtr m_InputLayout; public: - dxVertexLayout(Ref shader, const std::vector>& elements, Ref sharedContext); + dxVertexLayout( + Ref shader, + const std::vector> &elements, + Ref sharedContext + ); ~dxVertexLayout(); void Bind() override; @@ -30,4 +33,4 @@ private: DXGI_FORMAT GetDxgiFormat(VertexElementType type); }; -} // namespace Light \ No newline at end of file +} // namespace Light diff --git a/Engine/src/Platform/GraphicsAPI/OpenGL/glBlender.hpp b/modules/engine/include/engine/platform/graphics/opengl/blender.hpp similarity index 73% rename from Engine/src/Platform/GraphicsAPI/OpenGL/glBlender.hpp rename to modules/engine/include/engine/platform/graphics/opengl/blender.hpp index a372fed..71fcf9c 100644 --- a/Engine/src/Platform/GraphicsAPI/OpenGL/glBlender.hpp +++ b/modules/engine/include/engine/platform/graphics/opengl/blender.hpp @@ -1,7 +1,7 @@ #pragma once -#include "Base/Base.hpp" -#include "Graphics/Blender.hpp" +#include +#include namespace Light { @@ -17,4 +17,4 @@ public: void Disable() override; }; -} // namespace Light \ No newline at end of file +} // namespace Light diff --git a/Engine/src/Platform/GraphicsAPI/OpenGL/glBuffers.hpp b/modules/engine/include/engine/platform/graphics/opengl/buffers.hpp similarity index 74% rename from Engine/src/Platform/GraphicsAPI/OpenGL/glBuffers.hpp rename to modules/engine/include/engine/platform/graphics/opengl/buffers.hpp index a5f85a8..bf8c67b 100644 --- a/Engine/src/Platform/GraphicsAPI/OpenGL/glBuffers.hpp +++ b/modules/engine/include/engine/platform/graphics/opengl/buffers.hpp @@ -1,7 +1,7 @@ #pragma once -#include "Base/Base.hpp" -#include "Graphics/Buffers.hpp" +#include +#include namespace Light { @@ -18,7 +18,7 @@ public: void Bind() override; - void* Map() override; + void *Map() override; void UnMap() override; }; @@ -29,13 +29,13 @@ private: unsigned int m_BufferID; public: - glVertexBuffer(float* vertices, unsigned int stride, unsigned int count); + glVertexBuffer(float *vertices, unsigned int stride, unsigned int count); ~glVertexBuffer(); void Bind() override; void UnBind() override; - void* Map() override; + void *Map() override; void UnMap() override; }; @@ -46,11 +46,11 @@ private: unsigned int m_BufferID; public: - glIndexBuffer(unsigned int* indices, unsigned int count); + glIndexBuffer(unsigned int *indices, unsigned int count); ~glIndexBuffer(); void Bind() override; void UnBind() override; }; -} // namespace Light \ No newline at end of file +} // namespace Light diff --git a/modules/engine/include/engine/platform/graphics/opengl/framebuffers.hpp b/modules/engine/include/engine/platform/graphics/opengl/framebuffers.hpp new file mode 100644 index 0000000..03f7012 --- /dev/null +++ b/modules/engine/include/engine/platform/graphics/opengl/framebuffers.hpp @@ -0,0 +1,31 @@ +#pragma once + +#include +#include + +namespace Light { + +class glFramebuffer: public Framebuffer +{ +private: + FramebufferSpecification m_Specification; + + unsigned int m_BufferID; + unsigned int m_ColorAttachmentID, m_DepthStencilAttachmentID; + +public: + glFramebuffer(const FramebufferSpecification &specification); + ~glFramebuffer(); + + void BindAsTarget(const glm::vec4 &clearColor) override; + void BindAsResource() override; + + void Resize(const glm::uvec2 &size) override; + + inline void *GetColorAttachment() override + { + return (void *)m_ColorAttachmentID; + } +}; + +} // namespace Light diff --git a/Engine/src/Platform/GraphicsAPI/OpenGL/glGraphicsContext.hpp b/modules/engine/include/engine/platform/graphics/opengl/graphics_context.hpp similarity index 53% rename from Engine/src/Platform/GraphicsAPI/OpenGL/glGraphicsContext.hpp rename to modules/engine/include/engine/platform/graphics/opengl/graphics_context.hpp index 2e6120d..9ff5c07 100644 --- a/Engine/src/Platform/GraphicsAPI/OpenGL/glGraphicsContext.hpp +++ b/modules/engine/include/engine/platform/graphics/opengl/graphics_context.hpp @@ -1,7 +1,7 @@ #pragma once -#include "Base/Base.hpp" -#include "Graphics/GraphicsContext.hpp" +#include +#include struct GLFWwindow; @@ -10,10 +10,10 @@ namespace Light { class glGraphicsContext: public GraphicsContext { private: - GLFWwindow* m_WindowHandle; + GLFWwindow *m_WindowHandle; public: - glGraphicsContext(GLFWwindow* windowHandle); + glGraphicsContext(GLFWwindow *windowHandle); void LogDebugData() override; @@ -21,4 +21,4 @@ private: void SetDebugMessageCallback(); }; -} // namespace Light \ No newline at end of file +} // namespace Light diff --git a/Engine/src/Platform/GraphicsAPI/OpenGL/glRenderCommand.hpp b/modules/engine/include/engine/platform/graphics/opengl/render_command.hpp similarity index 56% rename from Engine/src/Platform/GraphicsAPI/OpenGL/glRenderCommand.hpp rename to modules/engine/include/engine/platform/graphics/opengl/render_command.hpp index e3ba70f..d47a6be 100644 --- a/Engine/src/Platform/GraphicsAPI/OpenGL/glRenderCommand.hpp +++ b/modules/engine/include/engine/platform/graphics/opengl/render_command.hpp @@ -1,7 +1,7 @@ #pragma once -#include "Base/Base.hpp" -#include "Graphics/RenderCommand.hpp" +#include +#include struct GLFWwindow; @@ -10,20 +10,21 @@ namespace Light { class glRenderCommand: public RenderCommand { private: - GLFWwindow* m_WindowHandle; + GLFWwindow *m_WindowHandle; public: - glRenderCommand(GLFWwindow* windowHandle); + glRenderCommand(GLFWwindow *windowHandle); void SwapBuffers() override; - void ClearBackBuffer(const glm::vec4& clearColor) override; + void ClearBackBuffer(const glm::vec4 &clearColor) override; void Draw(unsigned int count) override; void DrawIndexed(unsigned int count) override; void DefaultTargetFramebuffer() override; - void SetViewport(unsigned int x, unsigned int y, unsigned int width, unsigned int height) override; + void SetViewport(unsigned int x, unsigned int y, unsigned int width, unsigned int height) + override; }; -} // namespace Light \ No newline at end of file +} // namespace Light diff --git a/Engine/src/Platform/GraphicsAPI/OpenGL/glShader.hpp b/modules/engine/include/engine/platform/graphics/opengl/shader.hpp similarity index 79% rename from Engine/src/Platform/GraphicsAPI/OpenGL/glShader.hpp rename to modules/engine/include/engine/platform/graphics/opengl/shader.hpp index d5dbcbf..ac851c5 100644 --- a/Engine/src/Platform/GraphicsAPI/OpenGL/glShader.hpp +++ b/modules/engine/include/engine/platform/graphics/opengl/shader.hpp @@ -1,8 +1,8 @@ #pragma once -#include "Base/Base.hpp" -#include "Graphics/Shader.hpp" -#include "Utility/FileManager.hpp" +#include +#include +#include namespace Light { diff --git a/modules/engine/include/engine/platform/graphics/opengl/shared_context.hpp b/modules/engine/include/engine/platform/graphics/opengl/shared_context.hpp new file mode 100644 index 0000000..c4c1c0e --- /dev/null +++ b/modules/engine/include/engine/platform/graphics/opengl/shared_context.hpp @@ -0,0 +1,12 @@ +#pragma once + +#include +#include + +namespace Light { + +class glSharedContext: public SharedContext +{ +}; + +} // namespace Light diff --git a/Engine/src/Platform/GraphicsAPI/OpenGL/glTexture.hpp b/modules/engine/include/engine/platform/graphics/opengl/texture.hpp similarity index 83% rename from Engine/src/Platform/GraphicsAPI/OpenGL/glTexture.hpp rename to modules/engine/include/engine/platform/graphics/opengl/texture.hpp index 3fbcdbe..2f64d44 100644 --- a/Engine/src/Platform/GraphicsAPI/OpenGL/glTexture.hpp +++ b/modules/engine/include/engine/platform/graphics/opengl/texture.hpp @@ -1,7 +1,7 @@ #pragma once -#include "Base/Base.hpp" -#include "Graphics/Texture.hpp" +#include +#include namespace Light { diff --git a/Engine/src/Platform/GraphicsAPI/OpenGL/glUserInterface.hpp b/modules/engine/include/engine/platform/graphics/opengl/user_interface.hpp similarity index 51% rename from Engine/src/Platform/GraphicsAPI/OpenGL/glUserInterface.hpp rename to modules/engine/include/engine/platform/graphics/opengl/user_interface.hpp index 4235046..d81272c 100644 --- a/Engine/src/Platform/GraphicsAPI/OpenGL/glUserInterface.hpp +++ b/modules/engine/include/engine/platform/graphics/opengl/user_interface.hpp @@ -1,7 +1,7 @@ #pragma once -#include "Base/Base.hpp" -#include "UserInterface/UserInterface.hpp" +#include +#include struct GLFWwindow; @@ -10,13 +10,14 @@ namespace Light { class glUserInterface: public UserInterface { private: - GLFWwindow* m_WindowHandle; + GLFWwindow *m_WindowHandle; public: glUserInterface() = default; ~glUserInterface(); - void PlatformImplementation(GLFWwindow* windowHandle, Ref sharedContext) override; + void PlatformImplementation(GLFWwindow *windowHandle, Ref sharedContext) + override; void Begin() override; void End() override; @@ -24,4 +25,4 @@ public: void LogDebugData() override; }; -} // namespace Light \ No newline at end of file +} // namespace Light diff --git a/Engine/src/Platform/GraphicsAPI/OpenGL/glVertexLayout.hpp b/modules/engine/include/engine/platform/graphics/opengl/vertex_layout.hpp similarity index 65% rename from Engine/src/Platform/GraphicsAPI/OpenGL/glVertexLayout.hpp rename to modules/engine/include/engine/platform/graphics/opengl/vertex_layout.hpp index b1842b4..a7d3e31 100644 --- a/Engine/src/Platform/GraphicsAPI/OpenGL/glVertexLayout.hpp +++ b/modules/engine/include/engine/platform/graphics/opengl/vertex_layout.hpp @@ -1,7 +1,7 @@ #pragma once -#include "Base/Base.hpp" -#include "Graphics/VertexLayout.hpp" +#include +#include namespace Light { @@ -21,7 +21,10 @@ private: unsigned int m_ArrayID; public: - glVertexLayout(Ref buffer, const std::vector>& elements); + glVertexLayout( + Ref buffer, + const std::vector> &elements + ); ~glVertexLayout(); void Bind() override; @@ -31,4 +34,4 @@ private: glVertexElementDesc GetElementDesc(VertexElementType type, unsigned int offset); }; -} // namespace Light \ No newline at end of file +} // namespace Light diff --git a/Engine/src/Platform/OS/Linux/lWindow.hpp b/modules/engine/include/engine/platform/os/linux/l_window.hpp similarity index 51% rename from Engine/src/Platform/OS/Linux/lWindow.hpp rename to modules/engine/include/engine/platform/os/linux/l_window.hpp index 008e735..d030976 100644 --- a/Engine/src/Platform/OS/Linux/lWindow.hpp +++ b/modules/engine/include/engine/platform/os/linux/l_window.hpp @@ -1,7 +1,7 @@ #pragma once -#include "Base/Base.hpp" -#include "Core/Window.hpp" +#include +#include struct GLFWwindow; @@ -13,33 +13,34 @@ class WindowResizedEvent; class lWindow: public Window { private: - GLFWwindow* m_Handle; + GLFWwindow *m_Handle; - std::function m_EventCallback; + std::function m_EventCallback; public: - lWindow(std::function callback); + lWindow(std::function callback); ~lWindow(); /* events */ void PollEvents() override; - void OnEvent(const Event& event) override; + void OnEvent(const Event &event) override; //======================================== SETTERS ========================================// - void SetProperties(const WindowProperties& properties, bool overrideVisibility = false) override; + void SetProperties(const WindowProperties &properties, bool overrideVisibility = false) + override; - void SetTitle(const std::string& title) override; + void SetTitle(const std::string &title) override; - void SetSize(const glm::uvec2& size, bool additive = false) override; + void SetSize(const glm::uvec2 &size, bool additive = false) override; void SetVSync(bool vsync, bool toggle = false) override; void SetVisibility(bool visible, bool toggle = false) override; //======================================== SETTERS ========================================// private: - void OnWindowResize(const WindowResizedEvent& event); + void OnWindowResize(const WindowResizedEvent &event); void BindGlfwEvents(); }; -} // namespace Light \ No newline at end of file +} // namespace Light diff --git a/modules/engine/include/engine/platform/os/windows/w_window.cpp b/modules/engine/include/engine/platform/os/windows/w_window.cpp new file mode 100644 index 0000000..7ac0139 --- /dev/null +++ b/modules/engine/include/engine/platform/os/windows/w_window.cpp @@ -0,0 +1,244 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +extern "C" +{ + // Force Machine to use Dedicated Graphics + __declspec(dllexport) unsigned long NvOptimusEnablement = 0x00000001; // NVidia + __declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1; // AMD +} + +namespace Light { + +Scope Window::Create(std::function callback) +{ + return CreateScope(callback); +} + +wWindow::wWindow(std::function callback) + : m_Handle(nullptr) + , m_EventCallback(callback) +{ + // init glfw + ASSERT(glfwInit(), "wWindow::wWindow: failed to initialize 'glfw'"); + + // create window + glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); + glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 5); + glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); + glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE); + + m_Handle = glfwCreateWindow(1u, 1u, "", nullptr, nullptr); + ASSERT(m_Handle, "wWindow::wWindow: glfwCreateWindow: failed to create 'GLFWwindow'"); + + // bind event stuff + glfwSetWindowUserPointer(m_Handle, &m_EventCallback); + BindGlfwEvents(); + + // create graphics context + m_GraphicsContext = GraphicsContext::Create(GraphicsAPI::DirectX, m_Handle); + ASSERT(m_GraphicsContext, "wWindow::wWindow: failed to create 'GraphicsContext'"); +} + +wWindow::~wWindow() +{ + glfwDestroyWindow(m_Handle); +} + +void wWindow::PollEvents() +{ + glfwPollEvents(); +} + +void wWindow::OnEvent(const Event &event) +{ + switch (event.GetEventType()) + { + /* closed */ + case EventType::WindowClosed: b_Closed = true; break; + + /* resized */ + case EventType::WindowResized: OnWindowResize((const WindowResizedEvent &)event); break; + } +} + +void wWindow::OnWindowResize(const WindowResizedEvent &event) +{ + m_Properties.size = event.GetSize(); +} + +void wWindow:: + SetProperties(const WindowProperties &properties, bool overrideVisiblity /* = false */) +{ + // save the visibility status and re-assign if 'overrideVisibility' is false + bool visible = overrideVisiblity ? properties.visible : m_Properties.visible; + m_Properties = properties; + m_Properties.visible = visible; + + // set properties + SetTitle(properties.title); + SetSize(properties.size); + SetVSync(properties.vsync); + SetVisibility(visible); +} + +void wWindow::SetTitle(const std::string &title) +{ + m_Properties.title = title; + + glfwSetWindowTitle(m_Handle, m_Properties.title.c_str()); +} + +void wWindow::SetSize(const glm::uvec2 &size, bool additive /* = false */) +{ + m_Properties.size.x = size.x == 0u ? m_Properties.size.x : + additive ? m_Properties.size.x + size.x : + size.x; + m_Properties.size.y = size.y == 0u ? m_Properties.size.y : + additive ? m_Properties.size.y + size.y : + size.y; + + + glfwSetWindowSize(m_Handle, size.x, size.y); +} + +void wWindow::SetVSync(bool vsync, bool toggle /* = false */) +{ + m_Properties.vsync = toggle ? !m_Properties.vsync : vsync; + + glfwSwapInterval(m_Properties.vsync); +} + +void wWindow::SetVisibility(bool visible, bool toggle) +{ + m_Properties.visible = toggle ? !m_Properties.visible : visible; + + if (m_Properties.visible) + glfwShowWindow(m_Handle); + else + glfwHideWindow(m_Handle); +} + +void wWindow::BindGlfwEvents() +{ + //============================== MOUSE_EVENTS ==============================// + /* cursor position */ + glfwSetCursorPosCallback(m_Handle, [](GLFWwindow *window, double xpos, double ypos) { + std::function callback = *(std::function *) + glfwGetWindowUserPointer(window); + + MouseMovedEvent event(xpos, ypos); + callback(event); + }); + + /* mouse button */ + glfwSetMouseButtonCallback(m_Handle, [](GLFWwindow *window, int button, int action, int mods) { + std::function callback = *(std::function *) + glfwGetWindowUserPointer(window); + + if (action == GLFW_PRESS) + { + ButtonPressedEvent event(button); + callback(event); + } + else if (action == GLFW_RELEASE) + { + ButtonReleasedEvent event(button); + callback(event); + } + }); + + /* scroll */ + glfwSetScrollCallback(m_Handle, [](GLFWwindow *window, double xoffset, double yoffset) { + std::function callback = *(std::function *) + glfwGetWindowUserPointer(window); + + WheelScrolledEvent event(yoffset); + callback(event); + }); + //============================== MOUSE_EVENTS ==============================// + + //============================== KEYBOARD_EVENTS ==============================// + /* key */ + glfwSetKeyCallback( + m_Handle, + [](GLFWwindow *window, int key, int scancode, int action, int mods) { + std::function callback = *(std::function *) + glfwGetWindowUserPointer(window); + + if (action == GLFW_PRESS) + { + KeyPressedEvent event(key); + callback(event); + } + else if (action == GLFW_RELEASE) + { + KeyReleasedEvent event(key); + callback(event); + } + } + ); + /* char */ + glfwSetCharCallback(m_Handle, [](GLFWwindow *window, unsigned int character) { + std::function callback = *(std::function *) + glfwGetWindowUserPointer(window); + + SetCharEvent event(character); + callback(event); + }); + + //============================== KEYBOARD_EVENTS ==============================// + + //============================== WINDOW_EVENTS ==============================// + /* window position */ + glfwSetWindowPosCallback(m_Handle, [](GLFWwindow *window, int xpos, int ypos) { + std::function callback = *(std::function *) + glfwGetWindowUserPointer(window); + WindowMovedEvent event(xpos, ypos); + + callback(event); + }); + + /* window size */ + glfwSetWindowSizeCallback(m_Handle, [](GLFWwindow *window, int width, int height) { + std::function callback = *(std::function *) + glfwGetWindowUserPointer(window); + WindowResizedEvent event(width, height); + + callback(event); + }); + + /* window close */ + glfwSetWindowCloseCallback(m_Handle, [](GLFWwindow *window) { + std::function callback = *(std::function *) + glfwGetWindowUserPointer(window); + WindowClosedEvent event; + + callback(event); + }); + + /* window focus */ + glfwSetWindowFocusCallback(m_Handle, [](GLFWwindow *window, int focus) { + std::function callback = *(std::function *) + glfwGetWindowUserPointer(window); + + if (focus == GLFW_TRUE) + { + WindowGainFocusEvent event; + callback(event); + } + else + { + WindowLostFocusEvent event; + callback(event); + } + }); + //============================== WINDOW_EVENTS ==============================// } +} +} // namespace Light diff --git a/Engine/src/Platform/OS/Windows/wWindow.hpp b/modules/engine/include/engine/platform/os/windows/w_window.hpp similarity index 51% rename from Engine/src/Platform/OS/Windows/wWindow.hpp rename to modules/engine/include/engine/platform/os/windows/w_window.hpp index f25941b..dd708f3 100644 --- a/Engine/src/Platform/OS/Windows/wWindow.hpp +++ b/modules/engine/include/engine/platform/os/windows/w_window.hpp @@ -1,7 +1,7 @@ #pragma once -#include "Base/Base.hpp" -#include "Core/Window.hpp" +#include +#include struct GLFWwindow; @@ -13,33 +13,34 @@ class WindowResizedEvent; class wWindow: public Window { private: - GLFWwindow* m_Handle; + GLFWwindow *m_Handle; - std::function m_EventCallback; + std::function m_EventCallback; public: - wWindow(std::function callback); + wWindow(std::function callback); ~wWindow(); /* events */ void PollEvents() override; - void OnEvent(const Event& event) override; + void OnEvent(const Event &event) override; //======================================== SETTERS ========================================// - void SetProperties(const WindowProperties& properties, bool overrideVisibility = false) override; + void SetProperties(const WindowProperties &properties, bool overrideVisibility = false) + override; - void SetTitle(const std::string& title) override; + void SetTitle(const std::string &title) override; - void SetSize(const glm::uvec2& size, bool additive = false) override; + void SetSize(const glm::uvec2 &size, bool additive = false) override; void SetVSync(bool vsync, bool toggle = false) override; void SetVisibility(bool visible, bool toggle = false) override; //======================================== SETTERS ========================================// private: - void OnWindowResize(const WindowResizedEvent& event); + void OnWindowResize(const WindowResizedEvent &event); void BindGlfwEvents(); }; -} // namespace Light \ No newline at end of file +} // namespace Light diff --git a/modules/engine/include/engine/scene/components.hpp b/modules/engine/include/engine/scene/components.hpp new file mode 100644 index 0000000..0f20091 --- /dev/null +++ b/modules/engine/include/engine/scene/components.hpp @@ -0,0 +1,8 @@ +#pragma once + +#include +#include +#include +#include +#include +#include diff --git a/modules/engine/include/engine/scene/components/camera.hpp b/modules/engine/include/engine/scene/components/camera.hpp new file mode 100644 index 0000000..3a3a1d0 --- /dev/null +++ b/modules/engine/include/engine/scene/components/camera.hpp @@ -0,0 +1,29 @@ +#pragma once + +#include +#include +#include + +namespace Light { + +struct CameraComponent +{ + SceneCamera camera; + bool isPrimary; + + CameraComponent() = default; + CameraComponent(const CameraComponent &) = default; + + CameraComponent(SceneCamera _camera, bool _isPrimary = false) + : camera(_camera) + , isPrimary(_isPrimary) + { + } + + operator SceneCamera() + { + return camera; + } +}; + +} // namespace Light diff --git a/modules/engine/include/engine/scene/components/native_script.hpp b/modules/engine/include/engine/scene/components/native_script.hpp new file mode 100644 index 0000000..7d2e3fb --- /dev/null +++ b/modules/engine/include/engine/scene/components/native_script.hpp @@ -0,0 +1,28 @@ +#pragma once + +#include +#include + +namespace Light { + +struct NativeScriptComponent +{ + NativeScript *instance; + + NativeScript *(*CreateInstance)(); + void (*DestroyInstance)(NativeScriptComponent *); + + template + void Bind() + { + CreateInstance = []() { + return static_cast(new T()); + }; + DestroyInstance = [](NativeScriptComponent *nsc) { + delete (T *)(nsc->instance); + nsc->instance = nullptr; + }; + } +}; + +} // namespace Light diff --git a/Engine/src/Engine/Scene/Components/ScriptableEntity.hpp b/modules/engine/include/engine/scene/components/scriptable_entity.hpp similarity index 51% rename from Engine/src/Engine/Scene/Components/ScriptableEntity.hpp rename to modules/engine/include/engine/scene/components/scriptable_entity.hpp index 9c13e6d..f2ebe43 100644 --- a/Engine/src/Engine/Scene/Components/ScriptableEntity.hpp +++ b/modules/engine/include/engine/scene/components/scriptable_entity.hpp @@ -1,7 +1,7 @@ #pragma once -#include "Base/Base.hpp" -#include "Scene/Entity.hpp" +#include +#include namespace Light { @@ -14,21 +14,30 @@ private: unsigned int m_UniqueIdentifier = 0; // :#todo public: - NativeScript() = default; + NativeScript() = default; virtual ~NativeScript() = default; - inline unsigned int GetUID() const { return m_UniqueIdentifier; } + inline unsigned int GetUID() const + { + return m_UniqueIdentifier; + } template - T& GetComponent() + T &GetComponent() { return m_Entity.GetComponent(); } protected: - virtual void OnCreate() {} - virtual void OnDestroy() {} - virtual void OnUpdate(float ts) {} + virtual void OnCreate() + { + } + virtual void OnDestroy() + { + } + virtual void OnUpdate(float ts) + { + } }; } // namespace Light diff --git a/modules/engine/include/engine/scene/components/sprite_renderer.hpp b/modules/engine/include/engine/scene/components/sprite_renderer.hpp new file mode 100644 index 0000000..e44db62 --- /dev/null +++ b/modules/engine/include/engine/scene/components/sprite_renderer.hpp @@ -0,0 +1,32 @@ +#pragma once + +#include + +namespace Light { + +class Texture; + +struct SpriteRendererComponent +{ + Ref texture; + glm::vec4 tint; + + SpriteRendererComponent() = default; + SpriteRendererComponent(const SpriteRendererComponent &) = default; + + SpriteRendererComponent( + Ref _texture, + const glm::vec4 &_tint = glm::vec4(1.0f, 1.0f, 1.0f, 1.0f) + ) + : texture(_texture) + , tint(_tint) + { + } + + operator Ref() + { + return texture; + } +}; + +} // namespace Light diff --git a/modules/engine/include/engine/scene/components/tag.hpp b/modules/engine/include/engine/scene/components/tag.hpp new file mode 100644 index 0000000..63d2bd7 --- /dev/null +++ b/modules/engine/include/engine/scene/components/tag.hpp @@ -0,0 +1,28 @@ +#pragma once + +#include + +namespace Light { + +struct TagComponent +{ + std::string tag = "Unnamed"; + + TagComponent() = default; + TagComponent(const TagComponent &) = default; + + TagComponent(const std::string &_tag): tag(_tag) + { + } + + operator std::string() + { + return tag; + } + operator const std::string &() const + { + return tag; + } +}; + +} // namespace Light diff --git a/modules/engine/include/engine/scene/components/transform.hpp b/modules/engine/include/engine/scene/components/transform.hpp new file mode 100644 index 0000000..f2649c6 --- /dev/null +++ b/modules/engine/include/engine/scene/components/transform.hpp @@ -0,0 +1,44 @@ +#pragma once + +#define GLM_ENABLE_EXPERIMENTAL + +#include +#include +#include +#include + +namespace Light { + +struct TransformComponent +{ + glm::vec3 translation; + glm::vec3 scale; + glm::vec3 rotation; + + TransformComponent(const TransformComponent &) = default; + + TransformComponent( + const glm::vec3 &_translation = glm::vec3(0.0f, 0.0f, 0.0f), + const glm::vec3 &_scale = glm::vec3(1.0f, 1.0f, 1.0f), + const glm::vec3 &_rotation = glm::vec3(0.0f, 0.0f, 0.0f) + ) + + : translation(_translation) + , scale(_scale) + , rotation(_rotation) + { + } + + inline glm::mat4 GetTransform() const + { + return glm::translate(translation) * glm::rotate(rotation.z, glm::vec3(0.0f, 0.0f, 1.0f)) + * glm::scale(scale); + } + + operator const glm::mat4() const + { + return GetTransform(); + } +}; + +} // namespace Light diff --git a/modules/engine/include/engine/scene/components/uuid.hpp b/modules/engine/include/engine/scene/components/uuid.hpp new file mode 100644 index 0000000..9bae8fc --- /dev/null +++ b/modules/engine/include/engine/scene/components/uuid.hpp @@ -0,0 +1,18 @@ +#pragma once + +#include +#include + +namespace Light { + +struct UUIDComponent +{ + UUID uuid; + + UUIDComponent(UUID _uuid): uuid(_uuid) + { + } + UUIDComponent(const UUIDComponent &) = default; +}; + +} // namespace Light diff --git a/Engine/src/Engine/Scene/Entity.hpp b/modules/engine/include/engine/scene/entity.hpp similarity index 52% rename from Engine/src/Engine/Scene/Entity.hpp rename to modules/engine/include/engine/scene/entity.hpp index e4892ca..1c7443c 100644 --- a/Engine/src/Engine/Scene/Entity.hpp +++ b/modules/engine/include/engine/scene/entity.hpp @@ -1,9 +1,8 @@ #pragma once -#include "Base/Base.hpp" -#include "Components/UUIDComponent.hpp" -#include "Scene.hpp" - +#include +#include +#include #include namespace Light { @@ -12,20 +11,20 @@ class Entity { private: entt::entity m_Handle; - Scene* m_Scene; + Scene *m_Scene; public: - Entity(entt::entity handle = entt::null, Scene* registry = nullptr); + Entity(entt::entity handle = entt::null, Scene *registry = nullptr); ~Entity(); template - inline T& AddComponent(Args&&... args) + inline T &AddComponent(Args &&...args) { return m_Scene->m_Registry.emplace(m_Handle, std::forward(args)...); } template - inline T& GetComponent() + inline T &GetComponent() { return m_Scene->m_Registry.get(m_Handle); } @@ -42,11 +41,20 @@ public: m_Scene->m_Registry.remove(m_Handle); } - inline uint64_t GetUUID() { return GetComponent().uuid; } + inline uint64_t GetUUID() + { + return GetComponent().uuid; + } - inline bool IsValid() const { return m_Handle != entt::null && m_Scene != nullptr; } + inline bool IsValid() const + { + return m_Handle != entt::null && m_Scene != nullptr; + } - operator uint32_t() { return (uint32_t)m_Handle; } + operator uint32_t() + { + return (uint32_t)m_Handle; + } }; -} // namespace Light \ No newline at end of file +} // namespace Light diff --git a/modules/engine/include/engine/scene/scene.hpp b/modules/engine/include/engine/scene/scene.hpp new file mode 100644 index 0000000..2a3eff8 --- /dev/null +++ b/modules/engine/include/engine/scene/scene.hpp @@ -0,0 +1,49 @@ +#pragma once + +#include +#include +#include +#include +#include + +namespace Light { + +class Entity; + +class Framebuffer; + +class Scene +{ +private: + friend class Entity; + friend class SceneSerializer; + friend class SceneHierarchyPanel; + +private: + entt::registry m_Registry; + +public: + Scene(); + ~Scene(); + + void OnCreate(); + + void OnUpdate(float deltaTime); + void OnRender(const Ref &targetFrameBuffer = nullptr); + + Entity CreateEntity( + const std::string &name, + const TransformComponent &transform = TransformComponent() + ); + + Entity GetEntityByTag(const std::string &tag); + +private: + Entity CreateEntityWithUUID( + const std::string &name, + UUID uuid, + const TransformComponent &transform = TransformComponent() + ); +}; + +} // namespace Light diff --git a/modules/engine/include/engine/time/timer.hpp b/modules/engine/include/engine/time/timer.hpp new file mode 100644 index 0000000..c14e581 --- /dev/null +++ b/modules/engine/include/engine/time/timer.hpp @@ -0,0 +1,50 @@ +#pragma once + +#include +#include + +namespace Light { + +class Timer +{ +private: + std::chrono::time_point m_Start; + +public: + Timer(); + + inline float GetElapsedTime() const + { + return (std::chrono::duration_cast( + std::chrono::steady_clock::now() - m_Start + ) + .count()) + / 1000.; + } + + inline void Reset() + { + m_Start = std::chrono::steady_clock::now(); + } +}; + +class DeltaTimer +{ +private: + Timer timer; + + float m_PreviousFrame; + float m_DeltaTime; + +public: + DeltaTimer(); + + void Update(); + + inline float GetDeltaTime() const + { + return m_DeltaTime; + } +}; + +} // namespace Light diff --git a/Engine/src/Engine/UserInterface/UserInterface.hpp b/modules/engine/include/engine/user_interface/user_interface.hpp similarity index 53% rename from Engine/src/Engine/UserInterface/UserInterface.hpp rename to modules/engine/include/engine/user_interface/user_interface.hpp index 2d50474..702b84c 100644 --- a/Engine/src/Engine/UserInterface/UserInterface.hpp +++ b/modules/engine/include/engine/user_interface/user_interface.hpp @@ -1,7 +1,6 @@ #pragma once -#include "Base/Base.hpp" - +#include #include struct GLFWwindow; @@ -16,28 +15,31 @@ class SharedContext; class UserInterface /* singleton */ { private: - static UserInterface* s_Context; + static UserInterface *s_Context; private: ImGuiWindowFlags m_DockspaceFlags; public: - static Scope Create(GLFWwindow* windowHandle, Ref sharedContext); + static Scope Create(GLFWwindow *windowHandle, Ref sharedContext); - UserInterface(const UserInterface&) = delete; - UserInterface& operator=(const UserInterface&) = delete; + UserInterface(const UserInterface &) = delete; + UserInterface &operator=(const UserInterface &) = delete; virtual ~UserInterface() = default; - void Init(GLFWwindow* windowHandle, Ref sharedContext); + void Init(GLFWwindow *windowHandle, Ref sharedContext); static void DockspaceBegin(); static void DockspaceEnd(); - virtual void PlatformImplementation(GLFWwindow* windowHandle, Ref sharedContext) = 0; + virtual void PlatformImplementation( + GLFWwindow *windowHandle, + Ref sharedContext + ) = 0; virtual void Begin() = 0; - virtual void End() = 0; + virtual void End() = 0; virtual void LogDebugData() = 0; @@ -48,4 +50,4 @@ private: void SetDarkThemeColors(); }; -} // namespace Light \ No newline at end of file +} // namespace Light diff --git a/modules/engine/include/engine/utils/file_manager.hpp b/modules/engine/include/engine/utils/file_manager.hpp new file mode 100644 index 0000000..5b33938 --- /dev/null +++ b/modules/engine/include/engine/utils/file_manager.hpp @@ -0,0 +1,121 @@ +#pragma once + +#include + +namespace Light { + +class BasicFileHandle +{ +public: + BasicFileHandle( + uint8_t *data = nullptr, + uint32_t size = 0ull, + const std::string &path = "", + const std::string &name = "", + const std::string &extension = "" + ); + + virtual void Release(); + + // getters + inline uint8_t *GetData() + { + return m_Data; + } + inline uint32_t GetSize() + { + return m_Size; + } + + inline const std::string &GetPath() + { + return m_Path; + } + inline const std::string &GetName() + { + return m_Name; + } + inline const std::string &GetExtension() + { + return m_Extension; + } + + inline const std::string &GetNameWithExtension() + { + return m_Name + '.' + m_Extension; + } + + inline bool IsValid() const + { + return !!m_Data; + } + + // operators + inline operator bool() const + { + return IsValid(); + } + +protected: + // made protected for custom Free(): + uint8_t *m_Data; + uint32_t m_Size; + +private: + const std::string m_Path, m_Name, m_Extension; +}; + +class ImageFileHandle: public BasicFileHandle +{ +public: + ImageFileHandle( + uint8_t *data, + uint32_t size, + const std::string &path, + const std::string &name, + const std::string &extension, + uint32_t width, + uint32_t height, + uint32_t components, + uint32_t desiredComponents + ) + : BasicFileHandle(data, size, path, name, extension) + , m_Width(width) + , m_Height(height) + , m_Components(components) + , m_DesiredComponents(desiredComponents) + { + } + + void Release() override; + + // getters + inline uint32_t GetWidth() const + { + return m_Width; + } + inline uint32_t GetHeight() const + { + return m_Height; + } + inline uint32_t GetComponents() const + { + return m_Components; + } + inline uint32_t GetDesiredComponents() const + { + return m_DesiredComponents; + } + +private: + uint32_t m_Width, m_Height, m_Components, m_DesiredComponents; +}; + +class FileManager +{ +public: + static BasicFileHandle ReadTextFile(const std::string &path); + static ImageFileHandle ReadImageFile(const std::string &path, int32_t desiredComponents); +}; + +} // namespace Light diff --git a/modules/engine/include/engine/utils/resource_manager.hpp b/modules/engine/include/engine/utils/resource_manager.hpp new file mode 100644 index 0000000..f88863e --- /dev/null +++ b/modules/engine/include/engine/utils/resource_manager.hpp @@ -0,0 +1,75 @@ +#pragma once + +#include + +namespace Light { + +class Shader; +class Texture; + +class SharedContext; + +class ResourceManager /* singleton */ +{ +private: + static ResourceManager *s_Context; + +private: + std::unordered_map> m_Shaders; + std::unordered_map> m_Textures; + +public: + static Scope Create(); + + // #todo: add geometry shader support + static inline void LoadShader( + const std::string &name, + const std::string &vertexPath, + const std::string &pixelPath + ) + { + s_Context->LoadShaderImpl(name, vertexPath, pixelPath); + } + + static inline void LoadTexture( + const std::string &name, + const std::string &path, + unsigned int desiredComponents = 4u + ) + { + s_Context->LoadTextureImpl(name, path, desiredComponents); + } + + static inline void ReleaseTexture(const std::string &name) + { + s_Context->ReleaseTextureImpl(name); + } + + static inline Ref GetShader(const std::string &name) + { + return s_Context->m_Shaders[name]; + } + static inline Ref GetTexture(const std::string &name) + { + return s_Context->m_Textures[name]; + } + +private: + ResourceManager(); + + void LoadShaderImpl( + const std::string &name, + const std::string &vertexPath, + const std::string &pixelPath + ); + + void LoadTextureImpl( + const std::string &name, + const std::string &path, + unsigned int desiredComponents = 4u + ); + + void ReleaseTextureImpl(const std::string &name); +}; + +} // namespace Light diff --git a/modules/engine/include/engine/utils/serializer.hpp b/modules/engine/include/engine/utils/serializer.hpp new file mode 100644 index 0000000..f69f43b --- /dev/null +++ b/modules/engine/include/engine/utils/serializer.hpp @@ -0,0 +1,29 @@ +#pragma once + +#include +#include +#include +#include + +namespace Light { + +class SceneSerializer +{ +public: + SceneSerializer(const Ref &scene); + + void Serialize(const std::string &filePath); + bool Deserialize(const std::string &filePath); + + void SerializeBinary(const std::string &filePath); + bool DeserializeBinary(const std::string &filePath); + +private: + void SerializeEntity(YAML::Emitter &out, Entity entity); + +private: + Ref m_Scene; +}; + + +} // namespace Light diff --git a/Engine/src/Engine/Utility/Stringifier.hpp b/modules/engine/include/engine/utils/stringifier.hpp similarity index 92% rename from Engine/src/Engine/Utility/Stringifier.hpp rename to modules/engine/include/engine/utils/stringifier.hpp index cef6585..6b3a138 100644 --- a/Engine/src/Engine/Utility/Stringifier.hpp +++ b/modules/engine/include/engine/utils/stringifier.hpp @@ -2,7 +2,7 @@ #ifndef LIGHT_STRINGIFIER_H #define LIGHT_STRINGIFIER_H - #include "Base/Base.hpp" + #include namespace Light { @@ -22,4 +22,4 @@ public: } // namespace Light -#endif \ No newline at end of file +#endif diff --git a/modules/engine/src/camera/camera.cpp b/modules/engine/src/camera/camera.cpp new file mode 100644 index 0000000..80744ec --- /dev/null +++ b/modules/engine/src/camera/camera.cpp @@ -0,0 +1,6 @@ +#include + +namespace Light { + + +} diff --git a/modules/engine/src/camera/ortho.cpp b/modules/engine/src/camera/ortho.cpp new file mode 100644 index 0000000..59540e6 --- /dev/null +++ b/modules/engine/src/camera/ortho.cpp @@ -0,0 +1,49 @@ +#include +#include +#include + +namespace Light { + +OrthographicCamera::OrthographicCamera( + const glm::vec2 &position, + float aspectRatio, + float zoomLevel, + const glm::vec4 &clearColor /* = glm::vec4(0.1f, 0.3f, 0.7f, 1.0f) */ +) + : m_Up(0.0f, 1.0f, 0.0f) + , m_Position(position) + , m_AspectRatio(aspectRatio) + , m_ZoomLevel(zoomLevel) + , m_ClearColor(clearColor) +{ +} + +void OrthographicCamera::CalculateView() +{ + m_View = glm::lookAt(glm::vec3(m_Position, 100.0f), glm::vec3(m_Position, 0.0f), m_Up); +} + +void OrthographicCamera::CalculateProjection() +{ + m_Projection = glm::ortho( + -m_ZoomLevel * m_AspectRatio, + +m_ZoomLevel * m_AspectRatio, + -m_ZoomLevel, + +m_ZoomLevel, + FLT_MAX, + FLT_MIN + ); +} + +void OrthographicCamera::OnResize(const glm::vec2 &size) +{ + m_AspectRatio = size.x / size.y; + CalculateProjection(); +} + +void OrthographicCamera::Move(const glm::vec2 &position) +{ + m_Position += position; +} + +} // namespace Light diff --git a/Engine/src/Engine/Camera/SceneCamera.cpp b/modules/engine/src/camera/scene.cpp similarity index 58% rename from Engine/src/Engine/Camera/SceneCamera.cpp rename to modules/engine/src/camera/scene.cpp index ff4bf4b..08a7dfe 100644 --- a/Engine/src/Engine/Camera/SceneCamera.cpp +++ b/modules/engine/src/camera/scene.cpp @@ -1,11 +1,13 @@ -#include "SceneCamera.hpp" - +#include #include namespace Light { SceneCamera::SceneCamera() - : m_OrthographicSpecification { 1000.0f, -1.0f, 10000.0f }, m_PerspectiveSpecification { glm::radians(45.0f), 0.01f, 10000.0f }, m_AspectRatio(16.0f / 9.0f), m_ProjectionType(ProjectionType::Orthographic) + : m_OrthographicSpecification { 1000.0f, -1.0f, 10000.0f } + , m_PerspectiveSpecification { glm::radians(45.0f), 0.01f, 10000.0f } + , m_AspectRatio(16.0f / 9.0f) + , m_ProjectionType(ProjectionType::Orthographic) { CalculateProjection(); } @@ -62,20 +64,24 @@ void SceneCamera::CalculateProjection() { if (m_ProjectionType == ProjectionType::Orthographic) { - m_Projection = glm::ortho(-m_OrthographicSpecification.size * 0.5f * m_AspectRatio, - m_OrthographicSpecification.size * 0.5f * m_AspectRatio, - -m_OrthographicSpecification.size * 0.5f, - m_OrthographicSpecification.size * 0.5f, - m_OrthographicSpecification.farPlane, - m_OrthographicSpecification.nearPlane); + m_Projection = glm::ortho( + -m_OrthographicSpecification.size * 0.5f * m_AspectRatio, + m_OrthographicSpecification.size * 0.5f * m_AspectRatio, + -m_OrthographicSpecification.size * 0.5f, + m_OrthographicSpecification.size * 0.5f, + m_OrthographicSpecification.farPlane, + m_OrthographicSpecification.nearPlane + ); } else // perspective { - m_Projection = glm::perspective(m_PerspectiveSpecification.verticalFOV, - m_AspectRatio, - m_PerspectiveSpecification.nearPlane, - m_PerspectiveSpecification.farPlane); + m_Projection = glm::perspective( + m_PerspectiveSpecification.verticalFOV, + m_AspectRatio, + m_PerspectiveSpecification.nearPlane, + m_PerspectiveSpecification.farPlane + ); } } -} // namespace Light \ No newline at end of file +} // namespace Light diff --git a/Engine/src/Engine/Core/Application.cpp b/modules/engine/src/core/application.cpp similarity index 77% rename from Engine/src/Engine/Core/Application.cpp rename to modules/engine/src/core/application.cpp index 0ef549d..00ed8b7 100644 --- a/Engine/src/Engine/Core/Application.cpp +++ b/modules/engine/src/core/application.cpp @@ -1,21 +1,23 @@ -#include "Application.hpp" - -#include "Debug/Instrumentor.hpp" -#include "Events/Event.hpp" -#include "Graphics/GraphicsContext.hpp" -#include "Graphics/RenderCommand.hpp" -#include "Graphics/Renderer.hpp" -#include "Layer/Layer.hpp" -#include "Time/Timer.hpp" -#include "UserInterface/UserInterface.hpp" -#include "Window.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include namespace Light { -Application* Application::s_Context = nullptr; +Application *Application::s_Context = nullptr; -Application::Application(std::string execName, std::vector args) - : m_Instrumentor(nullptr), m_LayerStack(nullptr), m_Input(nullptr), m_Window(nullptr) +Application::Application() + : m_Instrumentor(nullptr) + , m_LayerStack(nullptr) + , m_Input(nullptr) + , m_Window(nullptr) { ASSERT(!s_Context, "Repeated singleton construction"); s_Context = this; @@ -27,7 +29,7 @@ Application::Application(std::string execName, std::vector args) m_Instrumentor->BeginSession("Logs/ProfileResults_Startup.json"); m_LayerStack = LayerStack::Create(); - m_Input = Input::Create(); + m_Input = Input::Create(); m_ResourceManager = ResourceManager::Create(); @@ -109,7 +111,7 @@ void Application::Quit() s_Context->m_Window->Close(); } -void Application::OnEvent(const Event& event) +void Application::OnEvent(const Event &event) { // window if (event.HasCategory(WindowEventCategory)) @@ -117,7 +119,9 @@ void Application::OnEvent(const Event& event) m_Window->OnEvent(event); if (event.GetEventType() == EventType::WindowResized) - m_Window->GetGfxContext()->GetRenderer()->OnWindowResize((const WindowResizedEvent&)event); + m_Window->GetGfxContext()->GetRenderer()->OnWindowResize( + (const WindowResizedEvent &)event + ); } // input @@ -125,7 +129,8 @@ void Application::OnEvent(const Event& event) { m_Input->OnEvent(event); - if (!m_Input->IsReceivingGameEvents()) // return if the event is an input event and 'Input' has disabled the game events + if (!m_Input->IsReceivingGameEvents()) // return if the event is an input event and 'Input' + // has disabled the game events return; } diff --git a/Engine/src/Engine/Core/UUID.cpp b/modules/engine/src/core/uuid.cpp similarity index 50% rename from Engine/src/Engine/Core/UUID.cpp rename to modules/engine/src/core/uuid.cpp index 2998f07..9efda4d 100644 --- a/Engine/src/Engine/Core/UUID.cpp +++ b/modules/engine/src/core/uuid.cpp @@ -1,14 +1,12 @@ -#include "UUID.hpp" - -#include "ltpch.hpp" +#include namespace Light { std::mt19937_64 UUID::s_Engine = std::mt19937_64(std::random_device()()); std::uniform_int_distribution UUID::s_UniformDistribution; -UUID::UUID(uint64_t uuid /* = -1 */) - : m_UUID(uuid == -1 ? s_UniformDistribution(s_Engine) : uuid) +UUID::UUID(uint64_t uuid /* = -1 */): m_UUID(uuid == -1 ? s_UniformDistribution(s_Engine) : uuid) { } -} // namespace Light \ No newline at end of file + +} // namespace Light diff --git a/Engine/src/Engine/Debug/Exceptions.cpp b/modules/engine/src/debug/exceptions.cpp similarity index 69% rename from Engine/src/Engine/Debug/Exceptions.cpp rename to modules/engine/src/debug/exceptions.cpp index 2fc029f..385c035 100644 --- a/Engine/src/Engine/Debug/Exceptions.cpp +++ b/modules/engine/src/debug/exceptions.cpp @@ -1,7 +1,5 @@ -#include "Exceptions.hpp" - -#include "Utility/Stringifier.hpp" - +#include +#include #include #ifdef LIGHT_PLATFORM_WINDOWS @@ -10,17 +8,18 @@ namespace Light { -FailedAssertion::FailedAssertion(const char* file, int line) +FailedAssertion::FailedAssertion(const char *file, int line) { LOG(critical, "Assertion failed in: {} (line {})", file, line); } -glException::glException(unsigned int source, unsigned int type, unsigned int id, const char* msg) +glException::glException(unsigned int source, unsigned int type, unsigned int id, const char *msg) { // #todo: improve LOG(critical, "________________________________________"); LOG(critical, "glException::glException::"); - // LOG(critical, " Severity: {}", Stringifier::glDebugMsgSeverity(GL_DEBUG_SEVERITY_HIGH)); + // LOG(critical, " Severity: {}", + // Stringifier::glDebugMsgSeverity(GL_DEBUG_SEVERITY_HIGH)); LOG(critical, " Source : {}", Stringifier::glDebugMsgSource(source)); LOG(critical, " Type : {}", Stringifier::glDebugMsgType(type)); LOG(critical, " ID : {}", id); @@ -33,13 +32,18 @@ glException::glException(unsigned int source, unsigned int type, unsigned int id } #ifdef LIGHT_PLATFORM_WINDOWS -dxException::dxException(long hr, const char* file, int line) +dxException::dxException(long hr, const char *file, int line) { - char* message; - FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, - nullptr, hr, - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), - (LPSTR)(&message), NULL, nullptr); + char *message; + FormatMessageA( + FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, + nullptr, + hr, + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), + (LPSTR)(&message), + NULL, + nullptr + ); // #todo: improve LOG(critical, "________________________________________"); diff --git a/Engine/src/Engine/Debug/Instrumentor.cpp b/modules/engine/src/debug/instrumentor.cpp similarity index 64% rename from Engine/src/Engine/Debug/Instrumentor.cpp rename to modules/engine/src/debug/instrumentor.cpp index aad9088..b25cb78 100644 --- a/Engine/src/Engine/Debug/Instrumentor.cpp +++ b/modules/engine/src/debug/instrumentor.cpp @@ -1,23 +1,25 @@ -#include "Instrumentor.hpp" +#include namespace Light { -Instrumentor* Instrumentor::s_Context = nullptr; +Instrumentor *Instrumentor::s_Context = nullptr; Scope Instrumentor::Create() { return MakeScope(new Instrumentor); } -Instrumentor::Instrumentor() - : m_CurrentSessionCount(0u) +Instrumentor::Instrumentor(): m_CurrentSessionCount(0u) { // #todo: maintenance - ASSERT(!s_Context, "An instance of 'Instrumentor' already exists, do not construct this class!"); + ASSERT( + !s_Context, + "An instance of 'Instrumentor' already exists, do not construct this class!" + ); s_Context = this; } -void Instrumentor::BeginSessionImpl(const std::string& outputPath) +void Instrumentor::BeginSessionImpl(const std::string &outputPath) { std::filesystem::create_directory(outputPath.substr(0, outputPath.find_last_of('/') + 1)); @@ -37,7 +39,7 @@ void Instrumentor::EndSessionImpl() m_OutputFileStream.close(); } -void Instrumentor::SubmitScopeProfileImpl(const ScopeProfileResult& profileResult) +void Instrumentor::SubmitScopeProfileImpl(const ScopeProfileResult &profileResult) { if (m_CurrentSessionCount++ == 0u) m_OutputFileStream << "{"; @@ -54,8 +56,9 @@ void Instrumentor::SubmitScopeProfileImpl(const ScopeProfileResult& profileResul m_OutputFileStream << "}"; } -InstrumentorTimer::InstrumentorTimer(const std::string& scopeName) - : m_Result({ scopeName, 0, 0, 0 }), m_Start(std::chrono::steady_clock::now()) +InstrumentorTimer::InstrumentorTimer(const std::string &scopeName) + : m_Result({ scopeName, 0, 0, 0 }) + , m_Start(std::chrono::steady_clock::now()) { } @@ -63,8 +66,13 @@ InstrumentorTimer::~InstrumentorTimer() { auto end = std::chrono::steady_clock::now(); - m_Result.start = std::chrono::time_point_cast(m_Start).time_since_epoch().count(); - m_Result.duration = std::chrono::time_point_cast(end).time_since_epoch().count() - m_Result.start; + m_Result.start = std::chrono::time_point_cast(m_Start) + .time_since_epoch() + .count(); + m_Result.duration = std::chrono::time_point_cast(end) + .time_since_epoch() + .count() + - m_Result.start; Instrumentor::SubmitScopeProfile(m_Result); } diff --git a/Engine/src/Engine/Debug/Logger.cpp b/modules/engine/src/debug/logger.cpp similarity index 89% rename from Engine/src/Engine/Debug/Logger.cpp rename to modules/engine/src/debug/logger.cpp index 979f954..775d461 100644 --- a/Engine/src/Engine/Debug/Logger.cpp +++ b/modules/engine/src/debug/logger.cpp @@ -1,11 +1,10 @@ -#include "Logger.hpp" - +#include #include #include namespace Light { -Logger* Logger::s_Context = nullptr; +Logger *Logger::s_Context = nullptr; Scope Logger::Create() { @@ -13,7 +12,9 @@ Scope Logger::Create() } Logger::Logger() - : m_EngineLogger(nullptr), m_FileLogger(nullptr), m_LogFilePath(LT_LOG_FILE_LOCATION) + : m_EngineLogger(nullptr) + , m_FileLogger(nullptr) + , m_LogFilePath(LT_LOG_FILE_LOCATION) { ASSERT(!s_Context, "An instance of 'Logger' already exists, do not construct this class!"); s_Context = this; diff --git a/modules/engine/src/graphics/blender.cpp b/modules/engine/src/graphics/blender.cpp new file mode 100644 index 0000000..275d091 --- /dev/null +++ b/modules/engine/src/graphics/blender.cpp @@ -0,0 +1,32 @@ +#include +#include + +#ifdef LIGHT_PLATFORM_WINDOWS + #include + #include +#endif + +#include + +namespace Light { + +Scope Blender::Create(Ref sharedContext) +{ + switch (GraphicsContext::GetGraphicsAPI()) + { + case GraphicsAPI::OpenGL: return CreateScope(); + + case GraphicsAPI::DirectX: + LT_WIN(return CreateScope(std::static_pointer_cast(sharedContext + ));) + + default: + ASSERT( + false, + "Invalid/unsupported 'GraphicsAPI' {}", + static_cast(GraphicsContext::GetGraphicsAPI()) + ); + } +} + +} // namespace Light diff --git a/modules/engine/src/graphics/buffers.cpp b/modules/engine/src/graphics/buffers.cpp new file mode 100644 index 0000000..dd45eb4 --- /dev/null +++ b/modules/engine/src/graphics/buffers.cpp @@ -0,0 +1,107 @@ +#include +#include +#include + +#ifdef LIGHT_PLATFORM_WINDOWS + #include + #include +#endif + +#include + +namespace Light { + +//================================================== CONSTANT_BUFFER +//==================================================// +Scope ConstantBuffer::Create( + ConstantBufferIndex index, + unsigned int size, + Ref sharedContext +) +{ + switch (GraphicsContext::GetGraphicsAPI()) + { + case GraphicsAPI::OpenGL: return CreateScope(index, size); + + case GraphicsAPI::DirectX: + LT_WIN(return CreateScope( + index, + size, + std::static_pointer_cast(sharedContext) + );) + + default: + ASSERT( + false, + "Invalid/unsupported 'GraphicsAPI' {}", + static_cast(GraphicsContext::GetGraphicsAPI()) + ); + return nullptr; + } +} +//================================================== CONSTANT_BUFFER +//==================================================// + +//================================================== VERTEX_BUFFER +//==================================================// +Ref VertexBuffer::Create( + float *vertices, + unsigned int stride, + unsigned int count, + Ref sharedContext +) +{ + switch (GraphicsContext::GetGraphicsAPI()) + { + case GraphicsAPI::OpenGL: return CreateRef(vertices, stride, count); + + case GraphicsAPI::DirectX: + LT_WIN(return CreateRef( + vertices, + stride, + count, + std::static_pointer_cast(sharedContext) + );) + + default: + ASSERT( + false, + "Invalid/unsupported 'GraphicsAPI' {}", + static_cast(GraphicsContext::GetGraphicsAPI()) + ); + return nullptr; + } +} +//================================================== VERTEX_BUFFER +//==================================================// + +//======================================== INDEX_BUFFER ========================================// +Ref IndexBuffer::Create( + unsigned int *indices, + unsigned int count, + Ref sharedContext +) +{ + switch (GraphicsContext::GetGraphicsAPI()) + { + case GraphicsAPI::OpenGL: return CreateRef(indices, count); + + case GraphicsAPI::DirectX: + LT_WIN(return CreateRef( + indices, + count, + std::dynamic_pointer_cast(sharedContext) + );) + + default: + ASSERT( + false, + "Invalid/unsupported 'GraphicsAPI' {}", + static_cast(GraphicsContext::GetGraphicsAPI()) + ); + return nullptr; + } +} +//======================================== INDEX_BUFFER ========================================// + +} // namespace Light diff --git a/modules/engine/src/graphics/framebuffer.cpp b/modules/engine/src/graphics/framebuffer.cpp new file mode 100644 index 0000000..28e1f26 --- /dev/null +++ b/modules/engine/src/graphics/framebuffer.cpp @@ -0,0 +1,38 @@ +#include +#include + +#ifdef LIGHT_PLATFORM_WINDOWS + #include + #include +#endif + +#include + +namespace Light { + +Ref Framebuffer::Create( + const FramebufferSpecification &specification, + Ref sharedContext +) +{ + switch (GraphicsContext::GetGraphicsAPI()) + { + case GraphicsAPI::OpenGL: return CreateRef(specification); + + case GraphicsAPI::DirectX: + LT_WIN(return CreateRef( + specification, + std::static_pointer_cast(sharedContext) + );) + + default: + ASSERT( + false, + "Invalid/unsupported 'GraphicsAPI' {}", + static_cast(GraphicsContext::GetGraphicsAPI()) + ); + return nullptr; + } +} + +} // namespace Light diff --git a/modules/engine/src/graphics/graphics_context.cpp b/modules/engine/src/graphics/graphics_context.cpp new file mode 100644 index 0000000..2ec2389 --- /dev/null +++ b/modules/engine/src/graphics/graphics_context.cpp @@ -0,0 +1,81 @@ +#include +#include + +#ifdef LIGHT_PLATFORM_WINDOWS + #include + #include +#endif + +#include // required for forward declaratio> +#include // required for forward declaratio> +#include // required for forward declaratio> +#include // required for forward declaratio> +#include // required for forward declaratio> +#include + +namespace Light { + +GraphicsContext *GraphicsContext::s_Context = nullptr; + +GraphicsContext::~GraphicsContext() +{ +} + +Scope GraphicsContext::Create(GraphicsAPI api, GLFWwindow *windowHandle) +{ + // terminate 'GraphicsContext' dependent classes + if (s_Context) + { + s_Context->m_Renderer.reset(); + s_Context->m_UserInterface.reset(); + + delete s_Context; + } + + // determine the default api + if (api == GraphicsAPI::Default) + { +#if defined(LIGHT_PLATFORM_WINDOWS) + api = GraphicsAPI::DirectX; +#elif defined(LIGHT_PLATFORM_LINUX) + api = GraphicsAPI::OpenGL; +#elif defined(LIGHT_PLATFORM_MAC) + api = GraphicsAPI::OpenGL; +#endif + } + + // create gfx context + Scope scopeGfx; + switch (api) + { + // opengl + case GraphicsAPI::OpenGL: + scopeGfx = CreateScope(windowHandle); + s_Context = scopeGfx.get(); + break; + // directx + case GraphicsAPI::DirectX: + LT_WIN(scopeGfx = CreateScope(windowHandle); s_Context = scopeGfx.get(); + break;) + + default: + ASSERT( + false, + "Invalid/unsupported 'GraphicsAPI' {}", + Stringifier::GraphicsAPIToString(api) + ); + return nullptr; + } + + // create 'GraphicsContext' dependent classes + s_Context->m_UserInterface = UserInterface::Create(windowHandle, s_Context->m_SharedContext); + s_Context->m_Renderer = Renderer::Create(windowHandle, s_Context->m_SharedContext); + + // check + ASSERT(s_Context->m_UserInterface, "Failed to create UserInterface"); + ASSERT(s_Context->m_Renderer, "Failed to create Renderer"); + + return std::move(scopeGfx); +} + +} // namespace Light diff --git a/modules/engine/src/graphics/render_command.cpp b/modules/engine/src/graphics/render_command.cpp new file mode 100644 index 0000000..cb30eac --- /dev/null +++ b/modules/engine/src/graphics/render_command.cpp @@ -0,0 +1,37 @@ +#include +#include + +#ifdef LIGHT_PLATFORM_WINDOWS + #include + #include +#endif + +#include + +namespace Light { + +Scope RenderCommand::Create( + GLFWwindow *windowHandle, + Ref sharedContext +) +{ + switch (GraphicsContext::GetGraphicsAPI()) + { + case GraphicsAPI::OpenGL: return CreateScope(windowHandle); + + case GraphicsAPI::DirectX: + LT_WIN(return CreateScope( + (std::static_pointer_cast)(sharedContext) + );) + + default: + ASSERT( + false, + "Invalid/unsupported 'GraphicsAPI' {}", + static_cast(GraphicsContext::GetGraphicsAPI()) + ); + return nullptr; + } +} + +} // namespace Light diff --git a/Engine/src/Engine/Graphics/Renderer.cpp b/modules/engine/src/graphics/renderer.cpp similarity index 63% rename from Engine/src/Engine/Graphics/Renderer.cpp rename to modules/engine/src/graphics/renderer.cpp index b9e7ebf..7749db2 100644 --- a/Engine/src/Engine/Graphics/Renderer.cpp +++ b/modules/engine/src/graphics/renderer.cpp @@ -1,88 +1,113 @@ -#include "Renderer.hpp" - -#include "Blender.hpp" -#include "Buffers.hpp" -#include "Camera/SceneCamera.hpp" -#include "Events/WindowEvents.hpp" -#include "Framebuffer.hpp" -#include "RenderCommand.hpp" -#include "Texture.hpp" - +#include +#include +#include +#include +#include +#include +#include +#include #include #include #include namespace Light { -Renderer* Renderer::s_Context = nullptr; +Renderer *Renderer::s_Context = nullptr; -Renderer::Renderer(GLFWwindow* windowHandle, Ref sharedContext) - : m_QuadRenderer(LT_MAX_QUAD_RENDERER_VERTICES, sharedContext), m_TextureRenderer(LT_MAX_TEXTURE_RENDERER_VERTICES, sharedContext), m_TintedTextureRenderer(LT_MAX_TINTED_TEXTURE_RENDERER_VERTICES, sharedContext), m_ViewProjectionBuffer(nullptr), m_RenderCommand(nullptr), m_Blender(nullptr), m_DefaultFramebufferCamera(nullptr), m_TargetFramebuffer(nullptr), m_ShouldClearBackbuffer(false) +Renderer::Renderer(GLFWwindow *windowHandle, Ref sharedContext) + : m_QuadRenderer(LT_MAX_QUAD_RENDERER_VERTICES, sharedContext) + , m_TextureRenderer(LT_MAX_TEXTURE_RENDERER_VERTICES, sharedContext) + , m_TintedTextureRenderer(LT_MAX_TINTED_TEXTURE_RENDERER_VERTICES, sharedContext) + , m_ViewProjectionBuffer(nullptr) + , m_RenderCommand(nullptr) + , m_Blender(nullptr) + , m_DefaultFramebufferCamera(nullptr) + , m_TargetFramebuffer(nullptr) + , m_ShouldClearBackbuffer(false) { ASSERT(!s_Context, "An instance of 'Renderer' already exists, do not construct this class!"); s_Context = this; - m_ViewProjectionBuffer = ConstantBuffer::Create(ConstantBufferIndex::ViewProjection, sizeof(glm::mat4), sharedContext); + m_ViewProjectionBuffer = ConstantBuffer::Create( + ConstantBufferIndex::ViewProjection, + sizeof(glm::mat4), + sharedContext + ); m_RenderCommand = RenderCommand::Create(windowHandle, sharedContext); - m_Blender = Blender::Create(sharedContext); + m_Blender = Blender::Create(sharedContext); m_Blender->Enable(BlendFactor::SRC_ALPHA, BlendFactor::INVERSE_SRC_ALPHA); } -Scope Renderer::Create(GLFWwindow* windowHandle, Ref sharedContext) +Scope Renderer::Create(GLFWwindow *windowHandle, Ref sharedContext) { return MakeScope(new Renderer(windowHandle, sharedContext)); } -void Renderer::OnWindowResize(const WindowResizedEvent& event) +void Renderer::OnWindowResize(const WindowResizedEvent &event) { m_RenderCommand->SetViewport(0u, 0u, event.GetSize().x, event.GetSize().y); } //======================================== DRAW_QUAD ========================================// /* tinted textures */ -void Renderer::DrawQuadImpl(const glm::vec3& position, const glm::vec2& size, const glm::vec4& tint, Ref texture) +void Renderer::DrawQuadImpl( + const glm::vec3 &position, + const glm::vec2 &size, + const glm::vec4 &tint, + Ref texture +) { - DrawQuad(glm::translate(glm::mat4(1.0f), position) * glm::scale(glm::mat4(1.0f), { size.x, size.y, 1.0f }), - tint, texture); + DrawQuad( + glm::translate(glm::mat4(1.0f), position) + * glm::scale(glm::mat4(1.0f), { size.x, size.y, 1.0f }), + tint, + texture + ); } /* tint */ -void Renderer::DrawQuadImpl(const glm::vec3& position, const glm::vec2& size, const glm::vec4& tint) +void Renderer::DrawQuadImpl(const glm::vec3 &position, const glm::vec2 &size, const glm::vec4 &tint) { - DrawQuad(glm::translate(glm::mat4(1.0f), position) * glm::scale(glm::mat4(1.0f), { size.x, size.y, 1.0f }), - tint); + DrawQuad( + glm::translate(glm::mat4(1.0f), position) + * glm::scale(glm::mat4(1.0f), { size.x, size.y, 1.0f }), + tint + ); } /* texture */ -void Renderer::DrawQuadImpl(const glm::vec3& position, const glm::vec2& size, Ref texture) +void Renderer::DrawQuadImpl(const glm::vec3 &position, const glm::vec2 &size, Ref texture) { - DrawQuad(glm::translate(glm::mat4(1.0f), position) * glm::scale(glm::mat4(1.0f), { size.x, size.y, 1.0f }), - texture); + DrawQuad( + glm::translate(glm::mat4(1.0f), position) + * glm::scale(glm::mat4(1.0f), { size.x, size.y, 1.0f }), + texture + ); } //======================================== DRAW_QUAD ========================================// //==================== DRAW_QUAD_TINT ====================// -void Renderer::DrawQuadImpl(const glm::mat4& transform, const glm::vec4& tint) +void Renderer::DrawQuadImpl(const glm::mat4 &transform, const glm::vec4 &tint) { // locals - QuadRendererProgram::QuadVertexData* bufferMap = m_QuadRenderer.GetMapCurrent(); + QuadRendererProgram::QuadVertexData *bufferMap = m_QuadRenderer.GetMapCurrent(); // top left bufferMap[0].position = transform * glm::vec4(-0.5f, -0.5f, 0.0f, 1.0f); - bufferMap[0].tint = tint; + bufferMap[0].tint = tint; // top right bufferMap[1].position = transform * glm::vec4(0.5f, -0.5f, 0.0f, 1.0f); - bufferMap[1].tint = tint; + bufferMap[1].tint = tint; // bottom right bufferMap[2].position = transform * glm::vec4(0.5f, 0.5f, 0.0f, 1.0f); - bufferMap[2].tint = tint; + bufferMap[2].tint = tint; // bottom left bufferMap[3].position = transform * glm::vec4(-0.5f, 0.5f, 0.0f, 1.0f); - bufferMap[3].tint = tint; + bufferMap[3].tint = tint; // advance if (!m_QuadRenderer.Advance()) @@ -94,14 +119,14 @@ void Renderer::DrawQuadImpl(const glm::mat4& transform, const glm::vec4& tint) //==================== DRAW_QUAD_TINT ====================// //==================== DRAW_QUAD_TEXTURE ====================// -void Renderer::DrawQuadImpl(const glm::mat4& transform, Ref texture) +void Renderer::DrawQuadImpl(const glm::mat4 &transform, Ref texture) { // #todo: implement a proper binding ASSERT(texture, "Texture passed to Renderer::DrawQuadImpl"); texture->Bind(); // locals - TextureRendererProgram::TextureVertexData* bufferMap = m_TextureRenderer.GetMapCurrent(); + TextureRendererProgram::TextureVertexData *bufferMap = m_TextureRenderer.GetMapCurrent(); // top left bufferMap[0].position = transform * glm::vec4(-0.5f, -0.5f, 0.0f, 1.0f); @@ -122,44 +147,47 @@ void Renderer::DrawQuadImpl(const glm::mat4& transform, Ref texture) // advance if (!m_TextureRenderer.Advance()) { - LOG(warn, "Exceeded LT_MAX_TEXTURE_RENDERER_VERTICES: {}", LT_MAX_TEXTURE_RENDERER_VERTICES); + LOG(warn, "Exceeded LT_MAX_TEXTURE_RENDERER_VERTICES: {}", LT_MAX_TEXTURE_RENDERER_VERTICES + ); FlushScene(); } } -void Renderer::DrawQuadImpl(const glm::mat4& transform, const glm::vec4& tint, Ref texture) +void Renderer::DrawQuadImpl(const glm::mat4 &transform, const glm::vec4 &tint, Ref texture) { // #todo: implement a proper binding ASSERT(texture, "Texture passed to Renderer::DrawQuadImpl"); texture->Bind(); // locals - TintedTextureRendererProgram::TintedTextureVertexData* bufferMap = m_TintedTextureRenderer.GetMapCurrent(); + TintedTextureRendererProgram::TintedTextureVertexData *bufferMap = m_TintedTextureRenderer + .GetMapCurrent(); // top left bufferMap[0].position = transform * glm::vec4(-0.5f, -0.5f, 0.0f, 1.0f); - bufferMap[0].tint = tint; + bufferMap[0].tint = tint; bufferMap[0].texcoord = { 0.0f, 0.0f }; // top right bufferMap[1].position = transform * glm::vec4(0.5f, -0.5f, 0.0f, 1.0f); - bufferMap[1].tint = tint; + bufferMap[1].tint = tint; bufferMap[1].texcoord = { 1.0f, 0.0f }; // bottom right bufferMap[2].position = transform * glm::vec4(0.5f, 0.5f, 0.0f, 1.0f); - bufferMap[2].tint = tint; + bufferMap[2].tint = tint; bufferMap[2].texcoord = { 1.0f, 1.0f }; // bottom left bufferMap[3].position = transform * glm::vec4(-0.5f, 0.5f, 0.0f, 1.0f); - bufferMap[3].tint = tint; + bufferMap[3].tint = tint; bufferMap[3].texcoord = { 0.0f, 1.0f }; // advance if (!m_TintedTextureRenderer.Advance()) { - LOG(warn, "Exceeded LT_MAX_TEXTURE_RENDERER_VERTICES: {}", LT_MAX_TEXTURE_RENDERER_VERTICES); + LOG(warn, "Exceeded LT_MAX_TEXTURE_RENDERER_VERTICES: {}", LT_MAX_TEXTURE_RENDERER_VERTICES + ); FlushScene(); } } @@ -173,12 +201,19 @@ void Renderer::BeginFrame() void Renderer::EndFrame() { m_RenderCommand->SwapBuffers(); - m_RenderCommand->ClearBackBuffer(m_DefaultFramebufferCamera ? m_DefaultFramebufferCamera->GetBackgroundColor() : glm::vec4(0.0f)); + m_RenderCommand->ClearBackBuffer( + m_DefaultFramebufferCamera ? m_DefaultFramebufferCamera->GetBackgroundColor() : + glm::vec4(0.0f) + ); m_DefaultFramebufferCamera = nullptr; } -void Renderer::BeginSceneImpl(Camera* camera, const glm::mat4& cameraTransform, const Ref& targetFrameBuffer /* = nullptr */) +void Renderer::BeginSceneImpl( + Camera *camera, + const glm::mat4 &cameraTransform, + const Ref &targetFrameBuffer /* = nullptr */ +) { // determine the target frame buffer m_TargetFramebuffer = targetFrameBuffer; @@ -192,8 +227,8 @@ void Renderer::BeginSceneImpl(Camera* camera, const glm::mat4& cameraTransform, } // update view projection buffer - glm::mat4* map = (glm::mat4*)m_ViewProjectionBuffer->Map(); - map[0] = camera->GetProjection() * glm::inverse(cameraTransform); + glm::mat4 *map = (glm::mat4 *)m_ViewProjectionBuffer->Map(); + map[0] = camera->GetProjection() * glm::inverse(cameraTransform); m_ViewProjectionBuffer->UnMap(); // map renderers diff --git a/modules/engine/src/graphics/renderer_programs/quad.cpp b/modules/engine/src/graphics/renderer_programs/quad.cpp new file mode 100644 index 0000000..64c8dea --- /dev/null +++ b/modules/engine/src/graphics/renderer_programs/quad.cpp @@ -0,0 +1,76 @@ +#include +#include +#include +#include +#include +#include + +namespace Light { + +QuadRendererProgram::QuadRendererProgram(unsigned int maxVertices, Ref sharedContext) + : m_Shader(nullptr) + , m_IndexBuffer(nullptr) + , m_VertexLayout(nullptr) + , m_MapCurrent(nullptr) + , m_MapEnd(nullptr) + , m_QuadCount(0u) + , m_MaxVertices(maxVertices) +{ + // #todo: don't use relative path + ResourceManager::LoadShader( + "LT_ENGINE_RESOURCES_QUAD_SHADER", + "Assets/Shaders/Quad/Quad_VS.glsl", + "Assets/Shaders/Quad/Quad_PS.glsl" + ); + + m_Shader = ResourceManager::GetShader("LT_ENGINE_RESOURCES_QUAD_SHADER"); + m_VertexBuffer = Ref( + VertexBuffer::Create(nullptr, sizeof(QuadVertexData), maxVertices, sharedContext) + ); + m_IndexBuffer = Ref( + IndexBuffer::Create(nullptr, (maxVertices / 4) * 6, sharedContext) + ); + m_VertexLayout = Ref(VertexLayout::Create( + m_VertexBuffer, + m_Shader, + { { "POSITION", VertexElementType::Float4 }, { "COLOR", VertexElementType::Float4 } }, + sharedContext + )); +} + +bool QuadRendererProgram::Advance() +{ + m_MapCurrent += 4; + + if (m_MapCurrent >= m_MapEnd) + { + LOG(warn, "'VertexBuffer' map went beyond 'MaxVertices': {}", m_MaxVertices); + return false; + } + + m_QuadCount++; + return true; +} + +void QuadRendererProgram::Map() +{ + m_QuadCount = 0u; + + m_MapCurrent = (QuadRendererProgram::QuadVertexData *)m_VertexBuffer->Map(); + m_MapEnd = m_MapCurrent + m_MaxVertices; +} + +void QuadRendererProgram::UnMap() +{ + m_VertexBuffer->UnMap(); +} + +void QuadRendererProgram::Bind() +{ + m_Shader->Bind(); + m_VertexLayout->Bind(); + m_VertexBuffer->Bind(); + m_IndexBuffer->Bind(); +} + +} // namespace Light diff --git a/modules/engine/src/graphics/renderer_programs/texture.cpp b/modules/engine/src/graphics/renderer_programs/texture.cpp new file mode 100644 index 0000000..5790e59 --- /dev/null +++ b/modules/engine/src/graphics/renderer_programs/texture.cpp @@ -0,0 +1,78 @@ +#include +#include +#include +#include +#include +#include + +namespace Light { + +TextureRendererProgram::TextureRendererProgram( + unsigned int maxVertices, + Ref sharedContext +) + : m_Shader(nullptr) + , m_IndexBuffer(nullptr) + , m_VertexLayout(nullptr) + , m_MapCurrent(nullptr) + , m_MapEnd(nullptr) + , m_QuadCount(0u) + , m_MaxVertices(maxVertices) +{ + // #todo: don't use relative path + ResourceManager::LoadShader( + "LT_ENGINE_RESOURCES_TEXTURE_SHADER", + "Assets/Shaders/Texture/Texture_VS.glsl", + "Assets/Shaders/Texture/Texture_PS.glsl" + ); + + m_Shader = ResourceManager::GetShader("LT_ENGINE_RESOURCES_TEXTURE_SHADER"); + m_VertexBuffer = Ref( + VertexBuffer::Create(nullptr, sizeof(TextureVertexData), maxVertices, sharedContext) + ); + m_IndexBuffer = Ref( + IndexBuffer::Create(nullptr, (maxVertices / 4) * 6, sharedContext) + ); + m_VertexLayout = Ref(VertexLayout::Create( + m_VertexBuffer, + m_Shader, + { { "POSITION", VertexElementType::Float4 }, { "TEXCOORD", VertexElementType::Float2 } }, + sharedContext + )); +} + +bool TextureRendererProgram::Advance() +{ + if (m_MapCurrent + 4 >= m_MapEnd) + { + LOG(warn, "'VertexBuffer' map went beyond 'MaxVertices': {}", m_MaxVertices); + return false; + } + + m_MapCurrent += 4; + m_QuadCount++; + return true; +} + +void TextureRendererProgram::Map() +{ + m_QuadCount = 0u; + + m_MapCurrent = (TextureRendererProgram::TextureVertexData *)m_VertexBuffer->Map(); + m_MapEnd = m_MapCurrent + m_MaxVertices; +} + +void TextureRendererProgram::UnMap() +{ + m_VertexBuffer->UnMap(); +} + +void TextureRendererProgram::Bind() +{ + m_Shader->Bind(); + m_VertexLayout->Bind(); + m_VertexBuffer->Bind(); + m_IndexBuffer->Bind(); +} + +} // namespace Light diff --git a/modules/engine/src/graphics/renderer_programs/tinted_texture.cpp b/modules/engine/src/graphics/renderer_programs/tinted_texture.cpp new file mode 100644 index 0000000..6b81d83 --- /dev/null +++ b/modules/engine/src/graphics/renderer_programs/tinted_texture.cpp @@ -0,0 +1,81 @@ +#include +#include +#include +#include +#include +#include + +namespace Light { + +TintedTextureRendererProgram::TintedTextureRendererProgram( + unsigned int maxVertices, + Ref sharedContext +) + : m_Shader(nullptr) + , m_IndexBuffer(nullptr) + , m_VertexLayout(nullptr) + , m_MapCurrent(nullptr) + , m_MapEnd(nullptr) + , m_QuadCount(0u) + , m_MaxVertices(maxVertices) +{ + // #todo: don't use relative path + ResourceManager::LoadShader( + "LT_ENGINE_RESOURCES_TINTED_TEXTURE_SHADER", + "Assets/Shaders/TintedTexture/TintedTexture_VS.glsl", + "Assets/Shaders/TintedTexture/TintedTexture_PS.glsl" + ); + + m_Shader = ResourceManager::GetShader("LT_ENGINE_RESOURCES_TINTED_TEXTURE_SHADER"); + m_VertexBuffer = Ref( + VertexBuffer::Create(nullptr, sizeof(TintedTextureVertexData), maxVertices, sharedContext) + ); + m_IndexBuffer = Ref( + IndexBuffer::Create(nullptr, (maxVertices / 4) * 6, sharedContext) + ); + m_VertexLayout = Ref(VertexLayout::Create( + m_VertexBuffer, + m_Shader, + { { "POSITION", VertexElementType::Float4 }, + { "TINT", VertexElementType::Float4 }, + { "TEXCOORD", VertexElementType::Float2 } }, + sharedContext + )); +} + +bool TintedTextureRendererProgram::Advance() +{ + m_MapCurrent += 4; + + if (m_MapCurrent >= m_MapEnd) + { + LOG(warn, "'VertexBuffer' map went beyond 'MaxVertices': {}", m_MaxVertices); + return false; + } + + m_QuadCount++; + return true; +} + +void TintedTextureRendererProgram::Map() +{ + m_QuadCount = 0u; + + m_MapCurrent = (TintedTextureRendererProgram::TintedTextureVertexData *)m_VertexBuffer->Map(); + m_MapEnd = m_MapCurrent + m_MaxVertices; +} + +void TintedTextureRendererProgram::UnMap() +{ + m_VertexBuffer->UnMap(); +} + +void TintedTextureRendererProgram::Bind() +{ + m_Shader->Bind(); + m_VertexLayout->Bind(); + m_VertexBuffer->Bind(); + m_IndexBuffer->Bind(); +} + +} // namespace Light diff --git a/modules/engine/src/graphics/shader.cpp b/modules/engine/src/graphics/shader.cpp new file mode 100644 index 0000000..14b12df --- /dev/null +++ b/modules/engine/src/graphics/shader.cpp @@ -0,0 +1,41 @@ +#include +#include + +#ifdef LIGHT_PLATFORM_WINDOWS + #include + #include +#endif + +#include + +namespace Light { + +Ref Shader::Create( + BasicFileHandle vertexFile, + BasicFileHandle pixelFile, + Ref sharedContext +) +{ + // load shader source + switch (GraphicsContext::GetGraphicsAPI()) + { + case GraphicsAPI::OpenGL: return CreateRef(vertexFile, pixelFile); + + case GraphicsAPI::DirectX: + LT_WIN(return CreateRef( + vertexFile, + pixelFile, + std::static_pointer_cast(sharedContext) + );) + + default: + ASSERT( + false, + "Invalid/unsupported 'GraphicsAPI' {}", + static_cast(GraphicsContext::GetGraphicsAPI()) + ); + return nullptr; + } +} + +} // namespace Light diff --git a/modules/engine/src/graphics/texture.cpp b/modules/engine/src/graphics/texture.cpp new file mode 100644 index 0000000..cbcd319 --- /dev/null +++ b/modules/engine/src/graphics/texture.cpp @@ -0,0 +1,51 @@ +#include +#include + +#ifdef LIGHT_PLATFORM_WINDOWS + #include + #include +#endif + +#include + +namespace Light { + +Ref Texture::Create( + unsigned int width, + unsigned int height, + unsigned int components, + unsigned char *pixels, + Ref sharedContext, + const std::string &filePath +) +{ + switch (GraphicsContext::GetGraphicsAPI()) + { + case GraphicsAPI::OpenGL: + return CreateRef(width, height, components, pixels, filePath); + + case GraphicsAPI::DirectX: + LT_WIN(return CreateRef( + width, + height, + components, + pixels, + std::static_pointer_cast(sharedContext), + filePath + );) + + default: + ASSERT( + false, + "Invalid/unsupported 'GraphicsAPI' {}", + static_cast(GraphicsContext::GetGraphicsAPI()) + ); + return nullptr; + } +} + +Texture::Texture(const std::string &filePath): m_FilePath(filePath) +{ +} + +} // namespace Light diff --git a/modules/engine/src/graphics/vertex_layout.cpp b/modules/engine/src/graphics/vertex_layout.cpp new file mode 100644 index 0000000..d9bde15 --- /dev/null +++ b/modules/engine/src/graphics/vertex_layout.cpp @@ -0,0 +1,41 @@ +#include +#include + +#ifdef LIGHT_PLATFORM_WINDOWS + #include + #include +#endif + +#include + +namespace Light { + +Ref VertexLayout::Create( + Ref vertexBuffer, + Ref shader, + const std::vector> &elements, + Ref sharedContext +) +{ + switch (GraphicsContext::GetGraphicsAPI()) + { + case GraphicsAPI::OpenGL: return CreateRef(vertexBuffer, elements); + + case GraphicsAPI::DirectX: + LT_WIN(return CreateRef( + shader, + elements, + std::static_pointer_cast(sharedContext) + );) + + default: + ASSERT( + false, + "Invalid/unsupported 'GraphicsAPI' {}", + static_cast(GraphicsContext::GetGraphicsAPI()) + ); + return nullptr; + } +} + +} // namespace Light diff --git a/Engine/src/Engine/Input/Input.cpp b/modules/engine/src/input/input.cpp similarity index 60% rename from Engine/src/Engine/Input/Input.cpp rename to modules/engine/src/input/input.cpp index 5442530..52bffea 100644 --- a/Engine/src/Engine/Input/Input.cpp +++ b/modules/engine/src/input/input.cpp @@ -1,17 +1,14 @@ -#include "Input.hpp" - -#include "Events/CharEvent.hpp" -#include "Events/Event.hpp" -#include "Events/KeyboardEvents.hpp" -#include "Events/MouseEvents.hpp" -#include "Input/KeyCodes.hpp" -#include "ltpch.hpp" - +#include +#include +#include +#include +#include +#include #include namespace Light { -Input* Input::s_Context = nullptr; +Input *Input::s_Context = nullptr; Scope Input::Create() { @@ -19,9 +16,18 @@ Scope Input::Create() } Input::Input() - : m_KeyboadKeys {}, m_MouseButtons {}, m_MousePosition {}, m_MouseDelta {}, m_MouseWheelDelta {}, m_UserInterfaceEvents(true), m_GameEvents(true) + : m_KeyboadKeys {} + , m_MouseButtons {} + , m_MousePosition {} + , m_MouseDelta {} + , m_MouseWheelDelta {} + , m_UserInterfaceEvents(true) + , m_GameEvents(true) { - ASSERT(!s_Context, "Input::Input: an instance of 'Input' already exists, do not construct this class!"); + ASSERT( + !s_Context, + "Input::Input: an instance of 'Input' already exists, do not construct this class!" + ); s_Context = this; RestartInputState(); @@ -34,7 +40,7 @@ void Input::ReceiveUserInterfaceEventsImpl(bool receive, bool toggle /* = false void Input::ReceieveGameEventsImpl(bool receive, bool toggle /*= false*/) { - bool prev = m_GameEvents; + bool prev = m_GameEvents; m_GameEvents = toggle ? !m_UserInterfaceEvents : receive; if (m_GameEvents != prev) @@ -46,24 +52,24 @@ void Input::RestartInputState() m_KeyboadKeys.fill(false); m_MouseButtons.fill(false); - m_MousePosition = glm::vec2(0.0f); - m_MouseDelta = glm::vec2(0.0f); + m_MousePosition = glm::vec2(0.0f); + m_MouseDelta = glm::vec2(0.0f); m_MouseWheelDelta = 0.0f; } -void Input::OnEvent(const Event& inputEvent) +void Input::OnEvent(const Event &inputEvent) { - ImGuiIO& io = ImGui::GetIO(); + ImGuiIO &io = ImGui::GetIO(); switch (inputEvent.GetEventType()) { //** MOUSE_EVENTS **// case EventType::MouseMoved: { - const MouseMovedEvent& event = (const MouseMovedEvent&)inputEvent; + const MouseMovedEvent &event = (const MouseMovedEvent &)inputEvent; if (m_GameEvents) { - m_MouseDelta = event.GetPosition() - m_MousePosition; + m_MouseDelta = event.GetPosition() - m_MousePosition; m_MousePosition = event.GetPosition(); } @@ -74,7 +80,7 @@ void Input::OnEvent(const Event& inputEvent) } case EventType::ButtonPressed: { - const ButtonPressedEvent& event = (const ButtonPressedEvent&)inputEvent; + const ButtonPressedEvent &event = (const ButtonPressedEvent &)inputEvent; if (m_GameEvents) m_MouseButtons[event.GetButton()] = true; @@ -86,7 +92,7 @@ void Input::OnEvent(const Event& inputEvent) } case EventType::ButtonReleased: { - const ButtonReleasedEvent& event = (const ButtonReleasedEvent&)inputEvent; + const ButtonReleasedEvent &event = (const ButtonReleasedEvent &)inputEvent; if (m_GameEvents) m_MouseButtons[event.GetButton()] = false; @@ -98,7 +104,7 @@ void Input::OnEvent(const Event& inputEvent) } case EventType::WheelScrolled: { - const WheelScrolledEvent& event = (const WheelScrolledEvent&)inputEvent; + const WheelScrolledEvent &event = (const WheelScrolledEvent &)inputEvent; if (m_GameEvents) m_MouseWheelDelta = event.GetOffset(); @@ -111,7 +117,7 @@ void Input::OnEvent(const Event& inputEvent) //** KEYBOARD_EVENTS **// case EventType::KeyPressed: { - const KeyPressedEvent& event = (const KeyPressedEvent&)inputEvent; + const KeyPressedEvent &event = (const KeyPressedEvent &)inputEvent; if (m_GameEvents) m_KeyboadKeys[event.GetKey()] = true; @@ -119,7 +125,7 @@ void Input::OnEvent(const Event& inputEvent) if (m_UserInterfaceEvents) { io.KeysDown[event.GetKey()] = true; - //if (event.GetKey() == Key::BackSpace) + // if (event.GetKey() == Key::BackSpace) // io.AddInputCharacter(Key::BackSpace); } @@ -127,7 +133,7 @@ void Input::OnEvent(const Event& inputEvent) } case EventType::KeyReleased: { - const KeyReleasedEvent& event = (const KeyReleasedEvent&)inputEvent; + const KeyReleasedEvent &event = (const KeyReleasedEvent &)inputEvent; if (m_GameEvents) m_KeyboadKeys[event.GetKey()] = false; @@ -141,7 +147,7 @@ void Input::OnEvent(const Event& inputEvent) { if (m_UserInterfaceEvents) { - const SetCharEvent& event = (const SetCharEvent&)inputEvent; + const SetCharEvent &event = (const SetCharEvent &)inputEvent; io.AddInputCharacter(event.GetCharacter()); } diff --git a/modules/engine/src/layer/layer.cpp b/modules/engine/src/layer/layer.cpp new file mode 100644 index 0000000..c1d5ec3 --- /dev/null +++ b/modules/engine/src/layer/layer.cpp @@ -0,0 +1,47 @@ +#include +#include +#include +#include +#include +#include + +namespace Light { + +Layer::Layer(const std::string &name): m_LayerName(name) +{ +} + +bool Layer::OnEvent(const Event &event) +{ + switch (event.GetEventType()) + { + /* mouse */ + // cursor + case EventType::MouseMoved: return OnMouseMoved((MouseMovedEvent &)event); + // button + case EventType::ButtonPressed: return OnButtonPressed((ButtonPressedEvent &)event); + case EventType::ButtonReleased: return OnButtonReleased((ButtonReleasedEvent &)event); + // wheel + case EventType::WheelScrolled: return OnWheelScrolled((WheelScrolledEvent &)event); + + /* keyboard */ + // key + case EventType::KeyPressed: return OnKeyPressed((KeyPressedEvent &)event); + case EventType::KeyRepeated: return OnKeyRepeat((KeyRepeatEvent &)event); + case EventType::KeyReleased: return OnKeyReleased((KeyReleasedEvent &)event); + // char + case EventType::SetChar: return OnSetChar((SetCharEvent &)event); + + /* window */ + // termination + case EventType::WindowClosed: return OnWindowClosed((WindowClosedEvent &)event); + // size/position + case EventType::WindowResized: return OnWindowResized((WindowResizedEvent &)event); + case EventType::WindowMoved: return OnWindowMoved((WindowMovedEvent &)event); + // focus + case EventType::WindowLostFocus: return OnWindowLostFocus((WindowLostFocusEvent &)event); + case EventType::WindowGainFocus: return OnWindowGainFocus((WindowGainFocusEvent &)event); + } +} + +} // namespace Light diff --git a/Engine/src/Engine/Layer/LayerStack.cpp b/modules/engine/src/layer/layer_stack.cpp similarity index 57% rename from Engine/src/Engine/Layer/LayerStack.cpp rename to modules/engine/src/layer/layer_stack.cpp index 23ae238..24c85b5 100644 --- a/Engine/src/Engine/Layer/LayerStack.cpp +++ b/modules/engine/src/layer/layer_stack.cpp @@ -1,22 +1,20 @@ -#include "LayerStack.hpp" - -#include "Events/Event.hpp" -#include "Events/KeyboardEvents.hpp" -#include "Events/MouseEvents.hpp" -#include "Events/WindowEvents.hpp" -#include "Layer.hpp" +#include +#include +#include +#include +#include +#include namespace Light { -LayerStack* LayerStack::s_Context = nullptr; +LayerStack *LayerStack::s_Context = nullptr; Scope LayerStack::Create() { return MakeScope(new LayerStack()); } -LayerStack::LayerStack() - : m_Layers {}, m_Begin(), m_End() +LayerStack::LayerStack(): m_Layers {}, m_Begin(), m_End() { ASSERT(!s_Context, "An instance of 'LayerStack' already exists, do not construct this class!") s_Context = this; @@ -24,26 +22,26 @@ LayerStack::LayerStack() LayerStack::~LayerStack() { - for (Layer* layer : m_Layers) + for (Layer *layer : m_Layers) delete layer; } -void LayerStack::AttachLayerImpl(Layer* layer) +void LayerStack::AttachLayerImpl(Layer *layer) { // #todo: handle attaching layer inside a for loop m_Layers.push_back(layer); m_Begin = m_Layers.begin(); - m_End = m_Layers.end(); + m_End = m_Layers.end(); LOG(trace, "Attached [{}]", layer->GetName()); } -void LayerStack::DetachLayerImpl(Layer* layer) +void LayerStack::DetachLayerImpl(Layer *layer) { // #todo: handle detaching layer inside a for loop m_Layers.erase(std::find(m_Layers.begin(), m_Layers.end(), layer)); m_Begin = m_Layers.begin(); - m_End = m_Layers.end(); + m_End = m_Layers.end(); LOG(trace, "Detached [{}]", layer->GetName()); } diff --git a/Engine/src/Engine/ltpch.hpp b/modules/engine/src/ltpch.hpp similarity index 93% rename from Engine/src/Engine/ltpch.hpp rename to modules/engine/src/ltpch.hpp index d198d9b..d3f2722 100644 --- a/Engine/src/Engine/ltpch.hpp +++ b/modules/engine/src/ltpch.hpp @@ -1,7 +1,7 @@ #pragma once /* engine */ -#include "Base/Base.hpp" +#include /* windows */ #ifdef _WIN32 @@ -45,4 +45,4 @@ /* c libraries */ #include -#include \ No newline at end of file +#include diff --git a/Engine/src/Engine/Math/Random.cpp b/modules/engine/src/math/random.cpp similarity index 93% rename from Engine/src/Engine/Math/Random.cpp rename to modules/engine/src/math/random.cpp index 2159e10..9d64c7a 100644 --- a/Engine/src/Engine/Math/Random.cpp +++ b/modules/engine/src/math/random.cpp @@ -1,6 +1,5 @@ -#include "Random.hpp" - #include +#include namespace Light { namespace Math { @@ -39,4 +38,4 @@ glm::vec3 RandVec3(int min, int max, int decimals /* = 0 */) return glm::vec3(r1, r2, r3); } } // namespace Math -} // namespace Light \ No newline at end of file +} // namespace Light diff --git a/Engine/src/Platform/GraphicsAPI/DirectX/dxBlender.cpp b/modules/engine/src/platform/graphics/directx/blender.cpp similarity index 80% rename from Engine/src/Platform/GraphicsAPI/DirectX/dxBlender.cpp rename to modules/engine/src/platform/graphics/directx/blender.cpp index 08e7829..7ba8ae5 100644 --- a/Engine/src/Platform/GraphicsAPI/DirectX/dxBlender.cpp +++ b/modules/engine/src/platform/graphics/directx/blender.cpp @@ -1,6 +1,5 @@ -#include "dxBlender.hpp" - -#include "dxSharedContext.hpp" +#include +#include namespace Light { @@ -37,13 +36,13 @@ dxBlender::dxBlender(Ref sharedContext) // blender desc m_Desc = {}; - m_Desc.RenderTarget[0].BlendEnable = true; - m_Desc.RenderTarget[0].SrcBlend = D3D11_BLEND_ZERO; - m_Desc.RenderTarget[0].DestBlend = D3D11_BLEND_ZERO; - m_Desc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD; - m_Desc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ZERO; - m_Desc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ONE; - m_Desc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD; + m_Desc.RenderTarget[0].BlendEnable = true; + m_Desc.RenderTarget[0].SrcBlend = D3D11_BLEND_ZERO; + m_Desc.RenderTarget[0].DestBlend = D3D11_BLEND_ZERO; + m_Desc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD; + m_Desc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ZERO; + m_Desc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ONE; + m_Desc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD; m_Desc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL; // create blend state @@ -55,8 +54,8 @@ void dxBlender::Enable(BlendFactor srcFactor, BlendFactor dstFactor) { // update desc m_Desc.RenderTarget[0].BlendEnable = true; - m_Desc.RenderTarget[0].SrcBlend = m_FactorMap.at(srcFactor); - m_Desc.RenderTarget[0].DestBlend = m_FactorMap.at(dstFactor); + m_Desc.RenderTarget[0].SrcBlend = m_FactorMap.at(srcFactor); + m_Desc.RenderTarget[0].DestBlend = m_FactorMap.at(dstFactor); // re-create blind state HRESULT hr; @@ -79,4 +78,4 @@ void dxBlender::Disable() m_Context->GetDeviceContext()->OMSetBlendState(m_BlendState.Get(), nullptr, 0xffffffff); } -} // namespace Light \ No newline at end of file +} // namespace Light diff --git a/Engine/src/Platform/GraphicsAPI/DirectX/dxBuffers.cpp b/modules/engine/src/platform/graphics/directx/buffers.cpp similarity index 63% rename from Engine/src/Platform/GraphicsAPI/DirectX/dxBuffers.cpp rename to modules/engine/src/platform/graphics/directx/buffers.cpp index 5f4a873..5068bbb 100644 --- a/Engine/src/Platform/GraphicsAPI/DirectX/dxBuffers.cpp +++ b/modules/engine/src/platform/graphics/directx/buffers.cpp @@ -1,18 +1,25 @@ -#include "dxBuffers.hpp" - -#include "dxSharedContext.hpp" +#include +#include namespace Light { -//======================================== CONSTANT_BUFFER ========================================// -dxConstantBuffer::dxConstantBuffer(ConstantBufferIndex index, unsigned int size, Ref sharedContext) - : m_Context(sharedContext), m_Buffer(nullptr), m_Map {}, m_Index(static_cast(index)) +//======================================== CONSTANT_BUFFER +//========================================// +dxConstantBuffer::dxConstantBuffer( + ConstantBufferIndex index, + unsigned int size, + Ref sharedContext +) + : m_Context(sharedContext) + , m_Buffer(nullptr) + , m_Map {} + , m_Index(static_cast(index)) { D3D11_BUFFER_DESC bDesc = {}; - bDesc.ByteWidth = size; - bDesc.Usage = D3D11_USAGE_DYNAMIC; - bDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; + bDesc.ByteWidth = size; + bDesc.Usage = D3D11_USAGE_DYNAMIC; + bDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; bDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; HRESULT hr; @@ -25,7 +32,7 @@ void dxConstantBuffer::Bind() m_Context->GetDeviceContext()->VSSetConstantBuffers(m_Index, 1u, m_Buffer.GetAddressOf()); } -void* dxConstantBuffer::Map() +void *dxConstantBuffer::Map() { m_Context->GetDeviceContext()->VSSetConstantBuffers(m_Index, 1u, m_Buffer.GetAddressOf()); m_Context->GetDeviceContext()->Map(m_Buffer.Get(), NULL, D3D11_MAP_WRITE_DISCARD, NULL, &m_Map); @@ -36,20 +43,30 @@ void dxConstantBuffer::UnMap() { m_Context->GetDeviceContext()->Unmap(m_Buffer.Get(), NULL); } -//======================================== CONSTANT_BUFFER ========================================// +//======================================== CONSTANT_BUFFER +//========================================// -//================================================== VERTEX_BUFFER ==================================================// -dxVertexBuffer::dxVertexBuffer(float* vertices, unsigned int stride, unsigned int count, Ref sharedContext) - : m_Context(sharedContext), m_Buffer(nullptr), m_Map {}, m_Stride(stride) +//================================================== VERTEX_BUFFER +//==================================================// +dxVertexBuffer::dxVertexBuffer( + float *vertices, + unsigned int stride, + unsigned int count, + Ref sharedContext +) + : m_Context(sharedContext) + , m_Buffer(nullptr) + , m_Map {} + , m_Stride(stride) { // buffer desc D3D11_BUFFER_DESC bDesc = {}; - bDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; - bDesc.Usage = D3D11_USAGE_DYNAMIC; + bDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; + bDesc.Usage = D3D11_USAGE_DYNAMIC; bDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; - bDesc.ByteWidth = count * stride; + bDesc.ByteWidth = count * stride; bDesc.StructureByteStride = stride; // create buffer @@ -62,7 +79,7 @@ dxVertexBuffer::~dxVertexBuffer() UnBind(); } -void* dxVertexBuffer::Map() +void *dxVertexBuffer::Map() { m_Context->GetDeviceContext()->Map(m_Buffer.Get(), NULL, D3D11_MAP_WRITE_DISCARD, NULL, &m_Map); return m_Map.pData; @@ -76,21 +93,28 @@ void dxVertexBuffer::UnMap() void dxVertexBuffer::Bind() { static const unsigned int offset = 0u; - m_Context->GetDeviceContext()->IASetVertexBuffers(0u, 1u, m_Buffer.GetAddressOf(), &m_Stride, &offset); + m_Context->GetDeviceContext() + ->IASetVertexBuffers(0u, 1u, m_Buffer.GetAddressOf(), &m_Stride, &offset); } void dxVertexBuffer::UnBind() { static const unsigned int offset = 0u; - static ID3D11Buffer* buffer = nullptr; + static ID3D11Buffer *buffer = nullptr; m_Context->GetDeviceContext()->IASetVertexBuffers(0u, 1u, &buffer, &m_Stride, &offset); } -//================================================== VERTEX_BUFFER ==================================================// +//================================================== VERTEX_BUFFER +//==================================================// //======================================== INDEX_BUFFER ========================================// -dxIndexBuffer::dxIndexBuffer(unsigned int* indices, unsigned int count, Ref sharedContext) - : m_Context(sharedContext), m_Buffer(nullptr) +dxIndexBuffer::dxIndexBuffer( + unsigned int *indices, + unsigned int count, + Ref sharedContext +) + : m_Context(sharedContext) + , m_Buffer(nullptr) { // generate indices if not provided bool hasIndices = !!indices; @@ -105,7 +129,7 @@ dxIndexBuffer::dxIndexBuffer(unsigned int* indices, unsigned int count, RefGetDeviceContext()->IASetIndexBuffer(buffer, DXGI_FORMAT_R32_UINT, offset); } diff --git a/modules/engine/src/platform/graphics/directx/framebuffers.cpp b/modules/engine/src/platform/graphics/directx/framebuffers.cpp new file mode 100644 index 0000000..b236307 --- /dev/null +++ b/modules/engine/src/platform/graphics/directx/framebuffers.cpp @@ -0,0 +1,107 @@ +#include +#include + +namespace Light { + +dxFramebuffer::dxFramebuffer( + const FramebufferSpecification &specification, + Ref sharedContext +) + : m_Context(sharedContext) + , m_Specification(specification) + , m_RenderTargetView(nullptr) + , m_ColorAttachment(nullptr) + , m_DepthStencilAttachment(nullptr) + , m_ShaderResourceView(nullptr) + , m_DepthStencilView(nullptr) +{ + HRESULT hr; + + D3D11_TEXTURE2D_DESC t2dDesc = {}; + t2dDesc.Width = specification.width; + t2dDesc.Height = specification.height; + t2dDesc.MipLevels = 1; + t2dDesc.ArraySize = 1; + t2dDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + t2dDesc.SampleDesc.Count = 1u; + t2dDesc.SampleDesc.Quality = 0u; + t2dDesc.Usage = D3D11_USAGE_DEFAULT; + t2dDesc.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE; + t2dDesc.CPUAccessFlags = NULL; + t2dDesc.MiscFlags = NULL; + DXC(m_Context->GetDevice()->CreateTexture2D(&t2dDesc, nullptr, &m_ColorAttachment)); + + D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc = {}; + srvDesc.Format = t2dDesc.Format; + srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; + srvDesc.Texture2D.MipLevels = 1; + srvDesc.Texture2D.MostDetailedMip = 0; + DXC(m_Context->GetDevice() + ->CreateShaderResourceView(m_ColorAttachment.Get(), &srvDesc, &m_ShaderResourceView)); + + D3D11_RENDER_TARGET_VIEW_DESC rtvDesc = {}; + rtvDesc.Format = t2dDesc.Format; + rtvDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D; + rtvDesc.Texture2D.MipSlice = 0u; + DXC(m_Context->GetDevice() + ->CreateRenderTargetView(m_ColorAttachment.Get(), &rtvDesc, &m_RenderTargetView)); +} + +void dxFramebuffer::BindAsTarget(const glm::vec4 &clearColor) +{ + FLOAT color[] = { + clearColor.r, + clearColor.g, + clearColor.b, + clearColor.a, + }; + + m_Context->GetDeviceContext() + ->OMSetRenderTargets(1u, m_RenderTargetView.GetAddressOf(), nullptr); + m_Context->GetDeviceContext()->ClearRenderTargetView(m_RenderTargetView.Get(), color); + + D3D11_VIEWPORT viewport; + + viewport.TopLeftX = 0; + viewport.TopLeftY = 0; + + viewport.Width = m_Specification.width; + viewport.Height = m_Specification.height; + + viewport.MinDepth = 0.0f; + viewport.MaxDepth = 1.0f; + + // set viewport + m_Context->GetDeviceContext()->RSSetViewports(1u, &viewport); +} + +void dxFramebuffer::BindAsResource() +{ + LOG(err, "NO_IMPLEMENT"); +} + +void dxFramebuffer::Resize(const glm::uvec2 &size) +{ + m_Specification.width = std::clamp(size.x, 1u, 16384u); + m_Specification.height = std::clamp(size.y, 1u, 16384u); + + D3D11_TEXTURE2D_DESC textureDesc; + D3D11_RENDER_TARGET_VIEW_DESC rtvDesc; + D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc; + + m_ColorAttachment->GetDesc(&textureDesc); + m_RenderTargetView->GetDesc(&rtvDesc); + m_ShaderResourceView->GetDesc(&srvDesc); + + textureDesc.Width = m_Specification.width; + textureDesc.Height = m_Specification.height; + + HRESULT hr; + DXC(m_Context->GetDevice()->CreateTexture2D(&textureDesc, nullptr, &m_ColorAttachment)); + DXC(m_Context->GetDevice() + ->CreateRenderTargetView(m_ColorAttachment.Get(), &rtvDesc, &m_RenderTargetView)); + DXC(m_Context->GetDevice() + ->CreateShaderResourceView(m_ColorAttachment.Get(), &srvDesc, &m_ShaderResourceView)); +} + +} // namespace Light diff --git a/Engine/src/Platform/GraphicsAPI/DirectX/dxGraphicsContext.cpp b/modules/engine/src/platform/graphics/directx/graphics_context.cpp similarity index 60% rename from Engine/src/Platform/GraphicsAPI/DirectX/dxGraphicsContext.cpp rename to modules/engine/src/platform/graphics/directx/graphics_context.cpp index 1cc73e2..a53bcac 100644 --- a/Engine/src/Platform/GraphicsAPI/DirectX/dxGraphicsContext.cpp +++ b/modules/engine/src/platform/graphics/directx/graphics_context.cpp @@ -1,13 +1,12 @@ -#include "dxGraphicsContext.hpp" - -#include "Events/WindowEvents.hpp" -#include "Graphics/Blender.hpp" // required for forward declaration -#include "Graphics/Buffers.hpp" // required for forward declaration -#include "Graphics/RenderCommand.hpp" // required for forward declaration -#include "Graphics/Renderer.hpp" // required for forward declaration -#include "UserInterface/UserInterface.hpp" // required for forward declaration -#include "Utility/ResourceManager.hpp" // required for forward declaration -#include "dxSharedContext.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include #define GLFW_EXPOSE_NATIVE_WIN32 #include @@ -15,8 +14,9 @@ namespace Light { -dxGraphicsContext::dxGraphicsContext(GLFWwindow* windowHandle) - : m_WindowHandle(windowHandle), m_DebugInterface(nullptr) +dxGraphicsContext::dxGraphicsContext(GLFWwindow *windowHandle) + : m_WindowHandle(windowHandle) + , m_DebugInterface(nullptr) { // set 'GraphicsAPI'; m_GraphicsAPI = GraphicsAPI::DirectX; @@ -29,7 +29,7 @@ dxGraphicsContext::dxGraphicsContext(GLFWwindow* windowHandle) SetupDebugInterface(); } -void dxGraphicsContext::SetupDeviceAndSwapChain(GLFWwindow* windowHandle) +void dxGraphicsContext::SetupDeviceAndSwapChain(GLFWwindow *windowHandle) { Ref context = std::static_pointer_cast(m_SharedContext); @@ -37,16 +37,16 @@ void dxGraphicsContext::SetupDeviceAndSwapChain(GLFWwindow* windowHandle) DXGI_SWAP_CHAIN_DESC sd = { 0 }; // buffer desc - sd.BufferDesc.Width = 1u; - sd.BufferDesc.Height = 1u; - sd.BufferDesc.RefreshRate.Numerator = NULL; // :#todo + sd.BufferDesc.Width = 1u; + sd.BufferDesc.Height = 1u; + sd.BufferDesc.RefreshRate.Numerator = NULL; // :#todo sd.BufferDesc.RefreshRate.Denominator = NULL; // :#todo - sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; - sd.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; - sd.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; + sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + sd.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; + sd.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; // sample desc (for multi sampling) #todo: implement multi-samplingz - sd.SampleDesc.Count = 1u; + sd.SampleDesc.Count = 1u; sd.SampleDesc.Quality = 0u; // #todo: support swap chains with more than 1 back-buffer @@ -55,7 +55,7 @@ void dxGraphicsContext::SetupDeviceAndSwapChain(GLFWwindow* windowHandle) // #todo: don't handle Windows's window with glfw, create it yourself sd.OutputWindow = static_cast(glfwGetWin32Window(windowHandle)); - sd.Windowed = true; + sd.Windowed = true; sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; @@ -68,18 +68,20 @@ void dxGraphicsContext::SetupDeviceAndSwapChain(GLFWwindow* windowHandle) #endif // create device and swap chain - DXC(D3D11CreateDeviceAndSwapChain(nullptr, - D3D_DRIVER_TYPE_HARDWARE, - NULL, - flags, - nullptr, - NULL, - D3D11_SDK_VERSION, - &sd, - &context->GetSwapChainRef(), - &context->GetDeviceRef(), - nullptr, - &context->GetDeviceContextRef())); + DXC(D3D11CreateDeviceAndSwapChain( + nullptr, + D3D_DRIVER_TYPE_HARDWARE, + NULL, + flags, + nullptr, + NULL, + D3D11_SDK_VERSION, + &sd, + &context->GetSwapChainRef(), + &context->GetDeviceRef(), + nullptr, + &context->GetDeviceContextRef() + )); } void dxGraphicsContext::SetupRenderTargets() @@ -93,10 +95,13 @@ void dxGraphicsContext::SetupRenderTargets() Microsoft::WRL::ComPtr backBuffer; DXC(context->GetSwapChain()->GetBuffer(0u, __uuidof(ID3D11Resource), &backBuffer)); - DXC(context->GetDevice()->CreateRenderTargetView(backBuffer.Get(), nullptr, &context->GetRenderTargetViewRef())); + DXC(context->GetDevice() + ->CreateRenderTargetView(backBuffer.Get(), nullptr, &context->GetRenderTargetViewRef()) + ); // set render target view - context->GetDeviceContext()->OMSetRenderTargets(1u, context->GetRenderTargetView().GetAddressOf(), nullptr); + context->GetDeviceContext() + ->OMSetRenderTargets(1u, context->GetRenderTargetView().GetAddressOf(), nullptr); } void dxGraphicsContext::SetupDebugInterface() @@ -120,8 +125,8 @@ void dxGraphicsContext::SetupDebugInterface() }; D3D11_INFO_QUEUE_FILTER filter = {}; - filter.DenyList.NumIDs = _countof(hide); - filter.DenyList.pIDList = hide; + filter.DenyList.NumIDs = _countof(hide); + filter.DenyList.pIDList = hide; infoQueue->AddStorageFilterEntries(&filter); infoQueue->Release(); #endif @@ -132,11 +137,11 @@ void dxGraphicsContext::LogDebugData() Ref context = std::static_pointer_cast(m_SharedContext); // locals - IDXGIDevice* DXGIDevice; - IDXGIAdapter* DXGIAdapter; + IDXGIDevice *DXGIDevice; + IDXGIAdapter *DXGIAdapter; DXGI_ADAPTER_DESC DXGIAdapterDesc; - context->GetDevice()->QueryInterface(__uuidof(IDXGIDevice), (void**)&DXGIDevice); + context->GetDevice()->QueryInterface(__uuidof(IDXGIDevice), (void **)&DXGIDevice); DXGIDevice->GetAdapter(&DXGIAdapter); DXGIAdapter->GetDesc(&DXGIAdapterDesc); diff --git a/Engine/src/Platform/GraphicsAPI/DirectX/dxRenderCommand.cpp b/modules/engine/src/platform/graphics/directx/render_command.cpp similarity index 61% rename from Engine/src/Platform/GraphicsAPI/DirectX/dxRenderCommand.cpp rename to modules/engine/src/platform/graphics/directx/render_command.cpp index a0f43e9..f0d61c0 100644 --- a/Engine/src/Platform/GraphicsAPI/DirectX/dxRenderCommand.cpp +++ b/modules/engine/src/platform/graphics/directx/render_command.cpp @@ -1,11 +1,9 @@ -#include "dxRenderCommand.hpp" - -#include "dxSharedContext.hpp" +#include +#include namespace Light { -dxRenderCommand::dxRenderCommand(Ref sharedContext) - : m_Context(sharedContext) +dxRenderCommand::dxRenderCommand(Ref sharedContext): m_Context(sharedContext) { } @@ -27,9 +25,12 @@ void dxRenderCommand::SwapBuffers() #endif } -void dxRenderCommand::ClearBackBuffer(const glm::vec4& clearColor) +void dxRenderCommand::ClearBackBuffer(const glm::vec4 &clearColor) { - m_Context->GetDeviceContext()->ClearRenderTargetView(m_Context->GetRenderTargetView().Get(), &clearColor[0]); + m_Context->GetDeviceContext()->ClearRenderTargetView( + m_Context->GetRenderTargetView().Get(), + &clearColor[0] + ); } void dxRenderCommand::Draw(unsigned int count) @@ -44,10 +45,16 @@ void dxRenderCommand::DrawIndexed(unsigned int count) void dxRenderCommand::DefaultTargetFramebuffer() { - m_Context->GetDeviceContext()->OMSetRenderTargets(1, m_Context->GetRenderTargetView().GetAddressOf(), nullptr); + m_Context->GetDeviceContext() + ->OMSetRenderTargets(1, m_Context->GetRenderTargetView().GetAddressOf(), nullptr); } -void dxRenderCommand::SetViewport(unsigned int x, unsigned int y, unsigned int width, unsigned int height) +void dxRenderCommand::SetViewport( + unsigned int x, + unsigned int y, + unsigned int width, + unsigned int height +) { // #todo: maybe call this somewhere else?? SetResolution(width, height); @@ -58,7 +65,7 @@ void dxRenderCommand::SetViewport(unsigned int x, unsigned int y, unsigned int w viewport.TopLeftX = x; viewport.TopLeftY = y; - viewport.Width = width; + viewport.Width = width; viewport.Height = height; viewport.MinDepth = 0.0f; @@ -73,20 +80,26 @@ void dxRenderCommand::SetResolution(unsigned int width, unsigned int height) HRESULT hr; // remove render target - ID3D11RenderTargetView* nullViews[] = { nullptr }; + ID3D11RenderTargetView *nullViews[] = { nullptr }; m_Context->GetDeviceContext()->OMSetRenderTargets(1u, nullViews, nullptr); m_Context->GetRenderTargetViewRef().Reset(); // resize buffer - DXC(m_Context->GetSwapChain()->ResizeBuffers(0u, width, height, DXGI_FORMAT_R8G8B8A8_UNORM, NULL)); + DXC(m_Context->GetSwapChain() + ->ResizeBuffers(0u, width, height, DXGI_FORMAT_R8G8B8A8_UNORM, NULL)); // create render target Microsoft::WRL::ComPtr backBuffer = nullptr; DXC(m_Context->GetSwapChain()->GetBuffer(0u, __uuidof(ID3D11Resource), &backBuffer)); - DXC(m_Context->GetDevice()->CreateRenderTargetView(backBuffer.Get(), nullptr, &m_Context->GetRenderTargetViewRef())); + DXC(m_Context->GetDevice()->CreateRenderTargetView( + backBuffer.Get(), + nullptr, + &m_Context->GetRenderTargetViewRef() + )); // set render target - m_Context->GetDeviceContext()->OMSetRenderTargets(1u, m_Context->GetRenderTargetView().GetAddressOf(), nullptr); + m_Context->GetDeviceContext() + ->OMSetRenderTargets(1u, m_Context->GetRenderTargetView().GetAddressOf(), nullptr); } } // namespace Light diff --git a/modules/engine/src/platform/graphics/directx/shader.cpp b/modules/engine/src/platform/graphics/directx/shader.cpp new file mode 100644 index 0000000..eabeb05 --- /dev/null +++ b/modules/engine/src/platform/graphics/directx/shader.cpp @@ -0,0 +1,81 @@ +#include +#include +#include + +namespace Light { + +dxShader::dxShader( + BasicFileHandle vertexFile, + BasicFileHandle pixelFile, + Ref sharedContext +) + : m_Context(sharedContext) + , m_VertexShader(nullptr) + , m_PixelShader(nullptr) + , m_VertexBlob(nullptr) +{ + Microsoft::WRL::ComPtr ps = nullptr, vsErr = nullptr, psErr = nullptr; + + // compile shaders (we don't use DXC here because if D3DCompile fails it throws a dxException + // without logging the vsErr/psErr + D3DCompile( + vertexFile.GetData(), + vertexFile.GetSize(), + NULL, + nullptr, + nullptr, + "main", + "vs_4_0", + NULL, + NULL, + &m_VertexBlob, + &vsErr + ); + D3DCompile( + pixelFile.GetData(), + pixelFile.GetSize(), + NULL, + nullptr, + nullptr, + "main", + "ps_4_0", + NULL, + NULL, + &ps, + &psErr + ); + + // check + ASSERT(!vsErr.Get(), "Vertex shader compile error: {}", (char *)vsErr->GetBufferPointer()); + ASSERT(!psErr.Get(), "Pixels shader compile error: {}", (char *)psErr->GetBufferPointer()); + + // create shaders + HRESULT hr; + DXC(m_Context->GetDevice()->CreateVertexShader( + m_VertexBlob->GetBufferPointer(), + m_VertexBlob->GetBufferSize(), + NULL, + &m_VertexShader + )); + DXC(m_Context->GetDevice() + ->CreatePixelShader(ps->GetBufferPointer(), ps->GetBufferSize(), NULL, &m_PixelShader)); +} + +dxShader::~dxShader() +{ + UnBind(); +} + +void dxShader::Bind() +{ + m_Context->GetDeviceContext()->VSSetShader(m_VertexShader.Get(), nullptr, 0u); + m_Context->GetDeviceContext()->PSSetShader(m_PixelShader.Get(), nullptr, 0u); +} + +void dxShader::UnBind() +{ + m_Context->GetDeviceContext()->VSSetShader(nullptr, nullptr, 0u); + m_Context->GetDeviceContext()->PSSetShader(nullptr, nullptr, 0u); +} + +} // namespace Light diff --git a/modules/engine/src/platform/graphics/directx/texture.cpp b/modules/engine/src/platform/graphics/directx/texture.cpp new file mode 100644 index 0000000..ef43c62 --- /dev/null +++ b/modules/engine/src/platform/graphics/directx/texture.cpp @@ -0,0 +1,80 @@ +#include +#include + +namespace Light { + +dxTexture::dxTexture( + unsigned int width, + unsigned int height, + unsigned int components, + unsigned char *pixels, + Ref sharedContext, + const std::string &filePath +) + : Texture(filePath) + , m_Context(sharedContext) + , m_Texture2D(nullptr) + , m_ShaderResourceView(nullptr) + , m_SamplerState(nullptr) +{ + // texture2d desc + D3D11_TEXTURE2D_DESC t2dDesc = {}; + t2dDesc.Width = width; + t2dDesc.Height = height; + t2dDesc.MipLevels = 0u; + t2dDesc.ArraySize = 1u; + t2dDesc.Format = components == 4u ? DXGI_FORMAT_R8G8B8A8_UNORM : + components == 3u ? DXGI_FORMAT_R8G8B8A8_UNORM : + // #todo: figure out what to do with this bitch ._. + components == 2u ? DXGI_FORMAT_R8G8_UNORM : + components == 1u ? DXGI_FORMAT_R8_UNORM : + DXGI_FORMAT_UNKNOWN; + t2dDesc.SampleDesc.Count = 1u; + t2dDesc.SampleDesc.Quality = 0u; + t2dDesc.Usage = D3D11_USAGE_DEFAULT; + t2dDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET; + t2dDesc.CPUAccessFlags = NULL; + t2dDesc.MiscFlags = D3D11_RESOURCE_MISC_GENERATE_MIPS; + + // create texture + HRESULT hr; + DXC(m_Context->GetDevice()->CreateTexture2D(&t2dDesc, nullptr, &m_Texture2D)); + m_Context->GetDeviceContext() + ->UpdateSubresource(m_Texture2D.Get(), 0u, nullptr, pixels, width * 4u, 0u); + + m_Texture2D->GetDesc(&t2dDesc); + + // shader resource view desc + D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc = {}; + srvDesc.Format = t2dDesc.Format; + srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; + srvDesc.Texture2D.MostDetailedMip = 0u; + srvDesc.Texture2D.MipLevels = -1; + + // create shader resource view + m_Context->GetDevice() + ->CreateShaderResourceView(m_Texture2D.Get(), &srvDesc, &m_ShaderResourceView); + m_Context->GetDeviceContext()->GenerateMips(m_ShaderResourceView.Get()); + + // sampler desc + D3D11_SAMPLER_DESC sDesc = {}; + sDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; + sDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; + sDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; + sDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; + sDesc.MinLOD = 0.0f; + sDesc.MipLODBias = 0.0f; + sDesc.MaxLOD = D3D11_FLOAT32_MAX; + + // create sampler + m_Context->GetDevice()->CreateSamplerState(&sDesc, &m_SamplerState); +} + +void dxTexture::Bind(unsigned int slot /* = 0u */) +{ + m_Context->GetDeviceContext()->PSSetSamplers(slot, 1u, m_SamplerState.GetAddressOf()); + m_Context->GetDeviceContext() + ->PSSetShaderResources(slot, 1u, m_ShaderResourceView.GetAddressOf()); +} + +} // namespace Light diff --git a/Engine/src/Platform/GraphicsAPI/DirectX/dxUserInterface.cpp b/modules/engine/src/platform/graphics/directx/user_interface.cpp similarity index 79% rename from Engine/src/Platform/GraphicsAPI/DirectX/dxUserInterface.cpp rename to modules/engine/src/platform/graphics/directx/user_interface.cpp index 74637e8..3c1cf8d 100644 --- a/Engine/src/Platform/GraphicsAPI/DirectX/dxUserInterface.cpp +++ b/modules/engine/src/platform/graphics/directx/user_interface.cpp @@ -1,7 +1,6 @@ -#include "dxUserInterface.hpp" - -#include "Input/KeyCodes.hpp" -#include "dxSharedContext.hpp" +#include +#include +#include #define GLFW_EXPOSE_NATIVE_WIN32 #include @@ -12,9 +11,12 @@ namespace Light { -void dxUserInterface::PlatformImplementation(GLFWwindow* windowHandle, Ref sharedContext) +void dxUserInterface::PlatformImplementation( + GLFWwindow *windowHandle, + Ref sharedContext +) { - ImGuiIO& io = ImGui::GetIO(); + ImGuiIO &io = ImGui::GetIO(); Ref context = std::dynamic_pointer_cast(sharedContext); ImGui_ImplWin32_Init(glfwGetWin32Window(windowHandle)); @@ -24,7 +26,7 @@ void dxUserInterface::PlatformImplementation(GLFWwindow* windowHandle, Ref +#include +#include namespace Light { -dxVertexLayout::dxVertexLayout(Ref shader, const std::vector>& elements, Ref sharedContext) - : m_Context(sharedContext), m_InputLayout(nullptr) +dxVertexLayout::dxVertexLayout( + Ref shader, + const std::vector> &elements, + Ref sharedContext +) + : m_Context(sharedContext) + , m_InputLayout(nullptr) { // occupy space for input elements std::vector inputElementsDesc; inputElementsDesc.reserve(elements.size()); // extract elements desc - for (const auto& element : elements) + for (const auto &element : elements) { inputElementsDesc.emplace_back(D3D11_INPUT_ELEMENT_DESC { element.first.c_str(), NULL, @@ -29,7 +33,13 @@ dxVertexLayout::dxVertexLayout(Ref shader, const std::vectorGetDevice()->CreateInputLayout(&inputElementsDesc[0], inputElementsDesc.size(), dxpShader->GetVertexBlob().Get()->GetBufferPointer(), dxpShader->GetVertexBlob().Get()->GetBufferSize(), &m_InputLayout)); + DXC(m_Context->GetDevice()->CreateInputLayout( + &inputElementsDesc[0], + inputElementsDesc.size(), + dxpShader->GetVertexBlob().Get()->GetBufferPointer(), + dxpShader->GetVertexBlob().Get()->GetBufferSize(), + &m_InputLayout + )); } dxVertexLayout::~dxVertexLayout() @@ -79,9 +89,7 @@ DXGI_FORMAT dxVertexLayout::GetDxgiFormat(VertexElementType type) case Light::VertexElementType::Float3: return DXGI_FORMAT_R32G32B32_FLOAT; case Light::VertexElementType::Float4: return DXGI_FORMAT_R32G32B32A32_FLOAT; - default: - ASSERT(false, "Invalid 'VertexElementType'"); - return DXGI_FORMAT_UNKNOWN; + default: ASSERT(false, "Invalid 'VertexElementType'"); return DXGI_FORMAT_UNKNOWN; } } diff --git a/Engine/src/Platform/GraphicsAPI/OpenGL/glBlender.cpp b/modules/engine/src/platform/graphics/opengl/blender.cpp similarity index 94% rename from Engine/src/Platform/GraphicsAPI/OpenGL/glBlender.cpp rename to modules/engine/src/platform/graphics/opengl/blender.cpp index 18f7151..7531d53 100644 --- a/Engine/src/Platform/GraphicsAPI/OpenGL/glBlender.cpp +++ b/modules/engine/src/platform/graphics/opengl/blender.cpp @@ -1,5 +1,4 @@ -#include "glBlender.hpp" - +#include #include namespace Light { @@ -44,4 +43,4 @@ void glBlender::Disable() glDisable(GL_BLEND); } -} // namespace Light \ No newline at end of file +} // namespace Light diff --git a/Engine/src/Platform/GraphicsAPI/OpenGL/glBuffers.cpp b/modules/engine/src/platform/graphics/opengl/buffers.cpp similarity index 86% rename from Engine/src/Platform/GraphicsAPI/OpenGL/glBuffers.cpp rename to modules/engine/src/platform/graphics/opengl/buffers.cpp index 6043713..9c716ee 100644 --- a/Engine/src/Platform/GraphicsAPI/OpenGL/glBuffers.cpp +++ b/modules/engine/src/platform/graphics/opengl/buffers.cpp @@ -1,12 +1,12 @@ -#include "glBuffers.hpp" - +#include #include namespace Light { //==================== CONSTANT_BUFFER ====================// glConstantBuffer::glConstantBuffer(ConstantBufferIndex index, unsigned int size) - : m_BufferID(NULL), m_Index(static_cast(index)) + : m_BufferID(NULL) + , m_Index(static_cast(index)) { glCreateBuffers(1, &m_BufferID); glNamedBufferData(m_BufferID, size, nullptr, GL_DYNAMIC_DRAW); @@ -24,9 +24,9 @@ void glConstantBuffer::Bind() glBindBufferBase(GL_UNIFORM_BUFFER, m_Index, m_BufferID); } -void* glConstantBuffer::Map() +void *glConstantBuffer::Map() { - void* map = glMapNamedBuffer(m_BufferID, GL_WRITE_ONLY); + void *map = glMapNamedBuffer(m_BufferID, GL_WRITE_ONLY); return map; } @@ -37,7 +37,7 @@ void glConstantBuffer::UnMap() //==================== CONSTANT_BUFFER ====================// //==================== VERTEX_BUFFER ====================// -glVertexBuffer::glVertexBuffer(float* vertices, unsigned int stride, unsigned int count) +glVertexBuffer::glVertexBuffer(float *vertices, unsigned int stride, unsigned int count) : m_BufferID(NULL) { glCreateBuffers(1, &m_BufferID); @@ -59,7 +59,7 @@ void glVertexBuffer::UnBind() glBindBuffer(GL_ARRAY_BUFFER, NULL); } -void* glVertexBuffer::Map() +void *glVertexBuffer::Map() { return glMapNamedBuffer(m_BufferID, GL_WRITE_ONLY); } @@ -71,8 +71,7 @@ void glVertexBuffer::UnMap() //==================== VERTEX_BUFFER ====================// //==================== INDEX_BUFFER ====================// -glIndexBuffer::glIndexBuffer(unsigned int* indices, unsigned int count) - : m_BufferID(NULL) +glIndexBuffer::glIndexBuffer(unsigned int *indices, unsigned int count): m_BufferID(NULL) { // generate indices if not provided bool hasIndices = !!indices; @@ -87,7 +86,7 @@ glIndexBuffer::glIndexBuffer(unsigned int* indices, unsigned int count) } // create indices - indices = new unsigned int[count]; + indices = new unsigned int[count]; unsigned int offset = 0u; for (unsigned int i = 0u; i < count; i += 6u) { diff --git a/Engine/src/Platform/GraphicsAPI/OpenGL/glFramebuffer.cpp b/modules/engine/src/platform/graphics/opengl/framebuffers.cpp similarity index 58% rename from Engine/src/Platform/GraphicsAPI/OpenGL/glFramebuffer.cpp rename to modules/engine/src/platform/graphics/opengl/framebuffers.cpp index 8af8b81..8f16f32 100644 --- a/Engine/src/Platform/GraphicsAPI/OpenGL/glFramebuffer.cpp +++ b/modules/engine/src/platform/graphics/opengl/framebuffers.cpp @@ -1,12 +1,14 @@ -#include "glFramebuffer.hpp" - +#include #include #include namespace Light { -glFramebuffer::glFramebuffer(const FramebufferSpecification& specification) - : m_Specification(specification), m_BufferID(NULL), m_ColorAttachmentID(NULL), m_DepthStencilAttachmentID(NULL) +glFramebuffer::glFramebuffer(const FramebufferSpecification &specification) + : m_Specification(specification) + , m_BufferID(NULL) + , m_ColorAttachmentID(NULL) + , m_DepthStencilAttachmentID(NULL) { Resize({ specification.width, specification.height }); } @@ -18,7 +20,7 @@ glFramebuffer::~glFramebuffer() // glDeleteTextures(1, &m_DepthStencilAttachmentID); } -void glFramebuffer::BindAsTarget(const glm::vec4& clearColor) +void glFramebuffer::BindAsTarget(const glm::vec4 &clearColor) { // #todo: use viewport instead of default x=0, y=0 glBindFramebuffer(GL_FRAMEBUFFER, m_BufferID); @@ -33,7 +35,7 @@ void glFramebuffer::BindAsResource() LOG(err, "NO_IMPLEMENT!"); } -void glFramebuffer::Resize(const glm::uvec2& size) +void glFramebuffer::Resize(const glm::uvec2 &size) { if (m_BufferID) { @@ -42,7 +44,7 @@ void glFramebuffer::Resize(const glm::uvec2& size) // glDeleteTextures(1, &m_DepthStencilAttachmentID); } - m_Specification.width = std::clamp(size.x, 1u, (unsigned int)GL_MAX_TEXTURE_SIZE); + m_Specification.width = std::clamp(size.x, 1u, (unsigned int)GL_MAX_TEXTURE_SIZE); m_Specification.height = std::clamp(size.y, 1u, (unsigned int)GL_MAX_TEXTURE_SIZE); glCreateFramebuffers(1, &m_BufferID); @@ -51,20 +53,42 @@ void glFramebuffer::Resize(const glm::uvec2& size) // create color attachment glCreateTextures(GL_TEXTURE_2D, 1, &m_ColorAttachmentID); glBindTexture(GL_TEXTURE_2D, m_ColorAttachmentID); - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, m_Specification.width, m_Specification.height, NULL, GL_RGBA, GL_UNSIGNED_BYTE, nullptr); + glTexImage2D( + GL_TEXTURE_2D, + 0, + GL_RGBA8, + m_Specification.width, + m_Specification.height, + NULL, + GL_RGBA, + GL_UNSIGNED_BYTE, + nullptr + ); glTextureParameteri(m_ColorAttachmentID, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTextureParameteri(m_ColorAttachmentID, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_ColorAttachmentID, 0); + glFramebufferTexture2D( + GL_FRAMEBUFFER, + GL_COLOR_ATTACHMENT0, + GL_TEXTURE_2D, + m_ColorAttachmentID, + 0 + ); - // glTextureStorage2D(m_ColorAttachmentID, 0, GL_RGBA8, m_Specification.width, m_Specification.height); + // glTextureStorage2D(m_ColorAttachmentID, 0, GL_RGBA8, m_Specification.width, + // m_Specification.height); // glCreateTextures(GL_TEXTURE_2D, 1, &m_DepthStencilAttachmentID); // glBindTexture(GL_TEXTURE_2D, m_DepthStencilAttachmentID); - // glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH24_STENCIL8, m_Specification.width, m_Specification.height, NULL, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8, nullptr); - // // glTextureStorage2D(m_DepthStencilAttachmentID, 0, GL_DEPTH24_STENCIL8, m_Specification.width, m_Specification.height); - // glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D, m_DepthStencilAttachmentID, 0); + // glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH24_STENCIL8, m_Specification.width, + // m_Specification.height, NULL, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8, nullptr); + // // glTextureStorage2D(m_DepthStencilAttachmentID, 0, GL_DEPTH24_STENCIL8, + // m_Specification.width, m_Specification.height); glFramebufferTexture2D(GL_FRAMEBUFFER, + // GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D, m_DepthStencilAttachmentID, 0); - ASSERT((glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE), "Framebuffer is incomplete"); + ASSERT( + (glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE), + "Framebuffer is incomplete" + ); glBindFramebuffer(GL_FRAMEBUFFER, 0); } diff --git a/modules/engine/src/platform/graphics/opengl/graphics_context.cpp b/modules/engine/src/platform/graphics/opengl/graphics_context.cpp new file mode 100644 index 0000000..d4a6e68 --- /dev/null +++ b/modules/engine/src/platform/graphics/opengl/graphics_context.cpp @@ -0,0 +1,116 @@ +#include +#include // required for forward declaratio> +#include // required for forward declaratio> +#include // required for forward declaratio> +#include // required for forward declaratio> +#include +#include // required for forward declaratio> +#include // required for forward declaratio> +#include + +#ifndef STOP_FUCKING_ORDERING_THESE_THE_WRONG_WAY_CLANG_FORMAT____ + #include +#endif + +namespace Light { + +glGraphicsContext::glGraphicsContext(GLFWwindow *windowHandle): m_WindowHandle(windowHandle) +{ + // set 'GraphicsAPI' + m_GraphicsAPI = GraphicsAPI::OpenGL; + + // make context current + glfwMakeContextCurrent(windowHandle); + + // load opengl (glad) + ASSERT(gladLoadGL(glfwGetProcAddress), "Failed to initialize opengl (glad)"); + + SetDebugMessageCallback(); +} + +void glGraphicsContext::LogDebugData() +{ + // #todo: log more information + LOG(info, "________________________________________"); + LOG(info, "GraphicsContext::"); + LOG(info, " API : OpenGL"); + // LOG(info, " Version : {}", glGetString(GL_VERSION)); + // LOG(info, " Renderer: {}", glGetString(GL_RENDERER)); + LOG(info, "________________________________________"); +} + +void glGraphicsContext::SetDebugMessageCallback() +{ + // determine log level + // #todo: set filters from config.h +#if defined(LIGHT_DEBUG) + glEnable(GL_DEBUG_OUTPUT); + glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, nullptr, GL_TRUE); + + GLuint ids[] = { 131185 }; + glDebugMessageControl( + GL_DEBUG_SOURCE_API, + GL_DEBUG_TYPE_OTHER, + GL_DONT_CARE, + _countof(ids), + ids, + GL_FALSE + ); +#elif defined(LIGHT_RELEASE) + glEnable(GL_DEBUG_OUTPUT); + glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, nullptr, GL_FALSE); + glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DEBUG_SEVERITY_HIGH, 0, nullptr, GL_TRUE); + glDebugMessageControl( + GL_DONT_CARE, + GL_DONT_CARE, + GL_DEBUG_SEVERITY_MEDIUM, + 0, + nullptr, + GL_TRUE + ); +#else // LIGHT_DIST + return; +#endif + + /* setup message callback */ + glDebugMessageCallback( + [](unsigned int source, + unsigned int type, + unsigned int id, + unsigned int severity, + int length, + const char *message, + const void *userParam) { + switch (severity) + { + case GL_DEBUG_SEVERITY_HIGH: + // throw glException(source, type, id, message); + return; + + case GL_DEBUG_SEVERITY_MEDIUM: + case GL_DEBUG_SEVERITY_LOW: + LOG(warn, + "glMessageCallback: Severity: {} :: Source: {} :: Type: {} :: ID: {}", + Stringifier::glDebugMsgSeverity(severity), + Stringifier::glDebugMsgSource(source), + Stringifier::glDebugMsgType(type), + id); + LOG(warn, " {}", message); + return; + + case GL_DEBUG_SEVERITY_NOTIFICATION: + LOG(trace, + "Severity: {} :: Source: {} :: Type: {} :: ID: {}", + Stringifier::glDebugMsgSeverity(severity), + Stringifier::glDebugMsgSource(source), + Stringifier::glDebugMsgType(type), + id); + LOG(trace, " {}", message); + return; + } + }, + nullptr + ); +} + +} // namespace Light diff --git a/Engine/src/Platform/GraphicsAPI/OpenGL/glRenderCommand.cpp b/modules/engine/src/platform/graphics/opengl/render_command.cpp similarity index 67% rename from Engine/src/Platform/GraphicsAPI/OpenGL/glRenderCommand.cpp rename to modules/engine/src/platform/graphics/opengl/render_command.cpp index f235c75..49156f3 100644 --- a/Engine/src/Platform/GraphicsAPI/OpenGL/glRenderCommand.cpp +++ b/modules/engine/src/platform/graphics/opengl/render_command.cpp @@ -1,5 +1,4 @@ -#include "glRenderCommand.hpp" - +#include #include #ifndef DONT_FUCKING_ORDER_THESSE_PLEASE_FOR_THE_LOVE_OF_GOD_CLANG_FORMAT #include @@ -7,8 +6,7 @@ namespace Light { -glRenderCommand::glRenderCommand(GLFWwindow* windowHandle) - : m_WindowHandle(windowHandle) +glRenderCommand::glRenderCommand(GLFWwindow *windowHandle): m_WindowHandle(windowHandle) { } @@ -17,7 +15,7 @@ void glRenderCommand::SwapBuffers() glfwSwapBuffers(m_WindowHandle); } -void glRenderCommand::ClearBackBuffer(const glm::vec4& clearColor) +void glRenderCommand::ClearBackBuffer(const glm::vec4 &clearColor) { glClearColor(clearColor.r, clearColor.g, clearColor.b, clearColor.a); glClear(GL_COLOR_BUFFER_BIT); @@ -38,7 +36,12 @@ void glRenderCommand::DefaultTargetFramebuffer() glBindFramebuffer(GL_FRAMEBUFFER, NULL); } -void glRenderCommand::SetViewport(unsigned int x, unsigned int y, unsigned int width, unsigned int height) +void glRenderCommand::SetViewport( + unsigned int x, + unsigned int y, + unsigned int width, + unsigned int height +) { glViewport(x, y, width, height); } diff --git a/Engine/src/Platform/GraphicsAPI/OpenGL/glShader.cpp b/modules/engine/src/platform/graphics/opengl/shader.cpp similarity index 68% rename from Engine/src/Platform/GraphicsAPI/OpenGL/glShader.cpp rename to modules/engine/src/platform/graphics/opengl/shader.cpp index 7ebf995..a6ce095 100644 --- a/Engine/src/Platform/GraphicsAPI/OpenGL/glShader.cpp +++ b/modules/engine/src/platform/graphics/opengl/shader.cpp @@ -1,15 +1,12 @@ -#include "glShader.hpp" - +#include #include #include #include #include - namespace Light { -glShader::glShader(BasicFileHandle vertexFile, BasicFileHandle pixelFile) - : m_ShaderID(0u) +glShader::glShader(BasicFileHandle vertexFile, BasicFileHandle pixelFile): m_ShaderID(0u) { // create m_ShaderID = glCreateProgram(); @@ -18,7 +15,7 @@ glShader::glShader(BasicFileHandle vertexFile, BasicFileHandle pixelFile) std::string pixelSource(pixelFile.GetData(), pixelFile.GetData() + pixelFile.GetSize()); unsigned int vertexShader = CompileShader(vertexSource, Shader::Stage::VERTEX); - unsigned int pixelShader = CompileShader(pixelSource, Shader::Stage::PIXEL); + unsigned int pixelShader = CompileShader(pixelSource, Shader::Stage::PIXEL); // attach shaders glAttachShader(m_ShaderID, vertexShader); @@ -56,13 +53,16 @@ void glShader::UnBind() // // // compile // shaderc::Compiler compiler; -// shaderc::SpvCompilationResult result = compiler.CompileGlslToSpv(reinterpret_cast(file.GetData()), stage == Shader::Stage::VERTEX ? shaderc_shader_kind::shaderc_vertex_shader : shaderc_shader_kind::shaderc_fragment_shader, file.GetName().c_str(), options); +// shaderc::SpvCompilationResult result = compiler.CompileGlslToSpv(reinterpret_cast(file.GetData()), stage == Shader::Stage::VERTEX ? +// shaderc_shader_kind::shaderc_vertex_shader : shaderc_shader_kind::shaderc_fragment_shader, +// file.GetName().c_str(), options); // // // log error // if (result.GetCompilationStatus() != shaderc_compilation_status_success) // { -// LOG(err, "Failed to compile {} shader at {}...", stage == Shader::Stage::VERTEX ? "vertex" : "pixel", file.GetPath()); -// LOG(err, " {}", result.GetErrorMessage()); +// LOG(err, "Failed to compile {} shader at {}...", stage == Shader::Stage::VERTEX ? "vertex" : +// "pixel", file.GetPath()); LOG(err, " {}", result.GetErrorMessage()); // } // // return result; @@ -71,11 +71,13 @@ void glShader::UnBind() unsigned int glShader::CompileShader(std::string source, Shader::Stage stage) { // &(address of) needs an lvalue - const char* lvalue_source = source.c_str(); - unsigned int shader = glCreateShader(stage == Shader::Stage::VERTEX ? GL_VERTEX_SHADER : - stage == Shader::Stage::PIXEL ? GL_FRAGMENT_SHADER : - stage == Shader::Stage::GEOMETRY ? GL_GEOMETRY_SHADER : - NULL); + const char *lvalue_source = source.c_str(); + unsigned int shader = glCreateShader( + stage == Shader::Stage::VERTEX ? GL_VERTEX_SHADER : + stage == Shader::Stage::PIXEL ? GL_FRAGMENT_SHADER : + stage == Shader::Stage::GEOMETRY ? GL_GEOMETRY_SHADER : + NULL + ); // compile glShaderSource(shader, 1, &lvalue_source, NULL); @@ -89,10 +91,13 @@ unsigned int glShader::CompileShader(std::string source, Shader::Stage stage) int logLength = 0; glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &logLength); - char* errorLog = (char*)alloca(logLength); + char *errorLog = (char *)alloca(logLength); glGetShaderInfoLog(shader, logLength, &logLength, &errorLog[0]); - LOG(err, "glShader::glShader: failed to compile {} shader:\n {}", stage == Shader::Stage::VERTEX ? "Vertex" : "Pixel", errorLog); + LOG(err, + "glShader::glShader: failed to compile {} shader:\n {}", + stage == Shader::Stage::VERTEX ? "Vertex" : "Pixel", + errorLog); return NULL; } @@ -104,7 +109,7 @@ unsigned int glShader::CompileShader(std::string source, Shader::Stage stage) glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &logLength); if (logLength) { - char* infoLog = (char*)alloca(logLength); + char *infoLog = (char *)alloca(logLength); glGetShaderInfoLog(shader, logLength, &logLength, &infoLog[0]); LOG(warn, infoLog); diff --git a/Engine/src/Platform/GraphicsAPI/OpenGL/glTexture.cpp b/modules/engine/src/platform/graphics/opengl/texture.cpp similarity index 69% rename from Engine/src/Platform/GraphicsAPI/OpenGL/glTexture.cpp rename to modules/engine/src/platform/graphics/opengl/texture.cpp index af5f45d..61d0cdd 100644 --- a/Engine/src/Platform/GraphicsAPI/OpenGL/glTexture.cpp +++ b/modules/engine/src/platform/graphics/opengl/texture.cpp @@ -1,11 +1,17 @@ -#include "glTexture.hpp" - +#include #include namespace Light { -glTexture::glTexture(unsigned int width, unsigned int height, unsigned int components, unsigned char* pixels, const std::string& filePath) - : Texture(filePath), m_TextureID(NULL) +glTexture::glTexture( + unsigned int width, + unsigned int height, + unsigned int components, + unsigned char *pixels, + const std::string &filePath +) + : Texture(filePath) + , m_TextureID(NULL) { // create texture glCreateTextures(GL_TEXTURE_2D, 1, &m_TextureID); @@ -21,13 +27,13 @@ glTexture::glTexture(unsigned int width, unsigned int height, unsigned int compo components == 3u ? GL_RGB : components == 2u ? GL_RG : components == 1u ? GL_RED : - NULL; + NULL; unsigned int internalFormat = format == GL_RGBA ? GL_RGBA8 : format == GL_RGB ? GL_RGB8 : format == GL_RG ? GL_RG8 : format == GL_RED ? GL_R8 : - NULL; + NULL; // check ASSERT(format, "Invalid number of components: {}", components); @@ -36,7 +42,17 @@ glTexture::glTexture(unsigned int width, unsigned int height, unsigned int compo // #todo: isn't there something like glTextureImage2D ??? // create texture and mipsmaps Bind(); - glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, width, height, 0, format, GL_UNSIGNED_BYTE, pixels); + glTexImage2D( + GL_TEXTURE_2D, + 0, + internalFormat, + width, + height, + 0, + format, + GL_UNSIGNED_BYTE, + pixels + ); glGenerateMipmap(GL_TEXTURE_2D); } @@ -51,9 +67,9 @@ void glTexture::Bind(unsigned int slot /* = 0u */) glBindTexture(GL_TEXTURE_2D, m_TextureID); } -void* glTexture::GetTexture() +void *glTexture::GetTexture() { - return (void*)(intptr_t)m_TextureID; + return (void *)(intptr_t)m_TextureID; } } // namespace Light diff --git a/Engine/src/Platform/GraphicsAPI/OpenGL/glUserInterface.cpp b/modules/engine/src/platform/graphics/opengl/user_interface.cpp similarity index 81% rename from Engine/src/Platform/GraphicsAPI/OpenGL/glUserInterface.cpp rename to modules/engine/src/platform/graphics/opengl/user_interface.cpp index 56e54eb..2bc6567 100644 --- a/Engine/src/Platform/GraphicsAPI/OpenGL/glUserInterface.cpp +++ b/modules/engine/src/platform/graphics/opengl/user_interface.cpp @@ -1,15 +1,16 @@ -#include "glUserInterface.hpp" - -#include "Input/KeyCodes.hpp" - -#include +#include #include #include +#include +#include #include namespace Light { -void glUserInterface::PlatformImplementation(GLFWwindow* windowHandle, Ref sharedContext) +void glUserInterface::PlatformImplementation( + GLFWwindow *windowHandle, + Ref sharedContext +) { m_WindowHandle = windowHandle; @@ -20,7 +21,7 @@ void glUserInterface::PlatformImplementation(GLFWwindow* windowHandle, Ref +#include #include namespace Light { -glVertexLayout::glVertexLayout(Ref buffer, const std::vector>& elements) +glVertexLayout::glVertexLayout( + Ref buffer, + const std::vector> &elements +) : m_ArrayID(NULL) { // check - ASSERT(std::dynamic_pointer_cast(buffer), "Failed to cast 'VertexBuffer' to 'glVertexBuffer'"); + ASSERT( + std::dynamic_pointer_cast(buffer), + "Failed to cast 'VertexBuffer' to 'glVertexBuffer'" + ); ASSERT(!elements.empty(), "'elements' is empty"); // local @@ -19,7 +23,7 @@ glVertexLayout::glVertexLayout(Ref buffer, const std::vector buffer, const std::vector +#include +#include +#include +#include +#include +#include +#include + +namespace Light { + +Scope Window::Create(std::function callback) +{ + return CreateScope(callback); +} + +lWindow::lWindow(std::function callback) + : m_Handle(nullptr) + , m_EventCallback(callback) +{ + // init glfw + ASSERT(glfwInit(), "lWindow::lWindow: failed to initialize 'glfw'"); + + // create window + glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); + glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 5); + glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); + glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE); + + m_Handle = glfwCreateWindow(1u, 1u, "", nullptr, nullptr); + ASSERT(m_Handle, "lWindow::lWindow: failed to create 'GLFWwindow'"); + + // bind event stuff + glfwSetWindowUserPointer(m_Handle, &m_EventCallback); + BindGlfwEvents(); + + // create graphics context + m_GraphicsContext = GraphicsContext::Create(GraphicsAPI::OpenGL, m_Handle); + ASSERT(m_GraphicsContext, "lWindow::lWindow: failed to create 'GraphicsContext'"); +} + +lWindow::~lWindow() +{ + glfwDestroyWindow(m_Handle); +} + +void lWindow::PollEvents() +{ + glfwPollEvents(); +} + +void lWindow::OnEvent(const Event &event) +{ + switch (event.GetEventType()) + { + /* closed */ + case EventType::WindowClosed: b_Closed = true; break; + + /* resized */ + case EventType::WindowResized: OnWindowResize((const WindowResizedEvent &)event); break; + } +} + +void lWindow::OnWindowResize(const WindowResizedEvent &event) +{ + m_Properties.size = event.GetSize(); +} + +void lWindow:: + SetProperties(const WindowProperties &properties, bool overrideVisibility /* = false */) +{ + // save the visibility status and re-assign if 'overrideVisibility' is false + bool visible = overrideVisibility ? properties.visible : m_Properties.visible; + m_Properties = properties; + m_Properties.visible = visible; + + // set properties + SetTitle(properties.title); + SetSize(properties.size); + SetVSync(properties.vsync); + SetVisibility(visible); +} + +void lWindow::SetTitle(const std::string &title) +{ + m_Properties.title = title; + + glfwSetWindowTitle(m_Handle, title.c_str()); +} + +void lWindow::SetSize(const glm::uvec2 &size, bool additive /* = false */) +{ + m_Properties.size.x = size.x == 0u ? m_Properties.size.x : + additive ? m_Properties.size.x + size.x : + size.x; + m_Properties.size.y = size.y == 0u ? m_Properties.size.y : + additive ? m_Properties.size.y + size.y : + size.y; + + + glfwSetWindowSize(m_Handle, size.x, size.y); +} + +void lWindow::SetVSync(bool vsync, bool toggle /* = false */) +{ + m_Properties.vsync = toggle ? !m_Properties.vsync : vsync; + + glfwSwapInterval(m_Properties.vsync); +} + +void lWindow::SetVisibility(bool visible, bool toggle) +{ + m_Properties.visible = toggle ? !m_Properties.visible : visible; + + if (m_Properties.visible) + glfwShowWindow(m_Handle); + else + glfwHideWindow(m_Handle); +} + +void lWindow::BindGlfwEvents() +{ + //============================== MOUSE_EVENTS ==============================// + /* cursor position */ + glfwSetCursorPosCallback(m_Handle, [](GLFWwindow *window, double xpos, double ypos) { + std::function callback = *(std::function *) + glfwGetWindowUserPointer(window); + + MouseMovedEvent event(xpos, ypos); + callback(event); + }); + + /* mouse button */ + glfwSetMouseButtonCallback(m_Handle, [](GLFWwindow *window, int button, int action, int mods) { + std::function callback = *(std::function *) + glfwGetWindowUserPointer(window); + + if (action == GLFW_PRESS) + { + ButtonPressedEvent event(button); + callback(event); + } + else if (action == GLFW_RELEASE) + { + ButtonReleasedEvent event(button); + callback(event); + } + }); + + /* scroll */ + glfwSetScrollCallback(m_Handle, [](GLFWwindow *window, double xoffset, double yoffset) { + std::function callback = *(std::function *) + glfwGetWindowUserPointer(window); + + WheelScrolledEvent event(yoffset); + callback(event); + }); + //============================== MOUSE_EVENTS ==============================// + + //============================== KEYBOARD_EVENTS ==============================// + /* key */ + glfwSetKeyCallback( + m_Handle, + [](GLFWwindow *window, int key, int scancode, int action, int mods) { + std::function callback = *(std::function *) + glfwGetWindowUserPointer(window); + + if (action == GLFW_PRESS) + { + KeyPressedEvent event(key); + callback(event); + } + else if (action == GLFW_RELEASE) + { + KeyReleasedEvent event(key); + callback(event); + } + } + ); + /* char */ + glfwSetCharCallback(m_Handle, [](GLFWwindow *window, unsigned int character) { + std::function callback = *(std::function *) + glfwGetWindowUserPointer(window); + + SetCharEvent event(character); + callback(event); + }); + + //============================== KEYBOARD_EVENTS ==============================// + + //============================== WINDOW_EVENTS ==============================// + /* window position */ + glfwSetWindowPosCallback(m_Handle, [](GLFWwindow *window, int xpos, int ypos) { + std::function callback = *(std::function *) + glfwGetWindowUserPointer(window); + WindowMovedEvent event(xpos, ypos); + + callback(event); + }); + + /* window size */ + glfwSetWindowSizeCallback(m_Handle, [](GLFWwindow *window, int width, int height) { + std::function callback = *(std::function *) + glfwGetWindowUserPointer(window); + WindowResizedEvent event(width, height); + + callback(event); + }); + + /* window close */ + glfwSetWindowCloseCallback(m_Handle, [](GLFWwindow *window) { + std::function callback = *(std::function *) + glfwGetWindowUserPointer(window); + WindowClosedEvent event; + + callback(event); + }); + + /* window focus */ + glfwSetWindowFocusCallback(m_Handle, [](GLFWwindow *window, int focus) { + std::function callback = *(std::function *) + glfwGetWindowUserPointer(window); + + if (focus == GLFW_TRUE) + { + WindowGainFocusEvent event; + callback(event); + } + else + { + WindowLostFocusEvent event; + callback(event); + } + }); + //============================== WINDOW_EVENTS ==============================// +} + +} // namespace Light diff --git a/modules/engine/src/platform/os/windows/w_window.cpp b/modules/engine/src/platform/os/windows/w_window.cpp new file mode 100644 index 0000000..7ac0139 --- /dev/null +++ b/modules/engine/src/platform/os/windows/w_window.cpp @@ -0,0 +1,244 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +extern "C" +{ + // Force Machine to use Dedicated Graphics + __declspec(dllexport) unsigned long NvOptimusEnablement = 0x00000001; // NVidia + __declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1; // AMD +} + +namespace Light { + +Scope Window::Create(std::function callback) +{ + return CreateScope(callback); +} + +wWindow::wWindow(std::function callback) + : m_Handle(nullptr) + , m_EventCallback(callback) +{ + // init glfw + ASSERT(glfwInit(), "wWindow::wWindow: failed to initialize 'glfw'"); + + // create window + glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); + glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 5); + glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); + glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE); + + m_Handle = glfwCreateWindow(1u, 1u, "", nullptr, nullptr); + ASSERT(m_Handle, "wWindow::wWindow: glfwCreateWindow: failed to create 'GLFWwindow'"); + + // bind event stuff + glfwSetWindowUserPointer(m_Handle, &m_EventCallback); + BindGlfwEvents(); + + // create graphics context + m_GraphicsContext = GraphicsContext::Create(GraphicsAPI::DirectX, m_Handle); + ASSERT(m_GraphicsContext, "wWindow::wWindow: failed to create 'GraphicsContext'"); +} + +wWindow::~wWindow() +{ + glfwDestroyWindow(m_Handle); +} + +void wWindow::PollEvents() +{ + glfwPollEvents(); +} + +void wWindow::OnEvent(const Event &event) +{ + switch (event.GetEventType()) + { + /* closed */ + case EventType::WindowClosed: b_Closed = true; break; + + /* resized */ + case EventType::WindowResized: OnWindowResize((const WindowResizedEvent &)event); break; + } +} + +void wWindow::OnWindowResize(const WindowResizedEvent &event) +{ + m_Properties.size = event.GetSize(); +} + +void wWindow:: + SetProperties(const WindowProperties &properties, bool overrideVisiblity /* = false */) +{ + // save the visibility status and re-assign if 'overrideVisibility' is false + bool visible = overrideVisiblity ? properties.visible : m_Properties.visible; + m_Properties = properties; + m_Properties.visible = visible; + + // set properties + SetTitle(properties.title); + SetSize(properties.size); + SetVSync(properties.vsync); + SetVisibility(visible); +} + +void wWindow::SetTitle(const std::string &title) +{ + m_Properties.title = title; + + glfwSetWindowTitle(m_Handle, m_Properties.title.c_str()); +} + +void wWindow::SetSize(const glm::uvec2 &size, bool additive /* = false */) +{ + m_Properties.size.x = size.x == 0u ? m_Properties.size.x : + additive ? m_Properties.size.x + size.x : + size.x; + m_Properties.size.y = size.y == 0u ? m_Properties.size.y : + additive ? m_Properties.size.y + size.y : + size.y; + + + glfwSetWindowSize(m_Handle, size.x, size.y); +} + +void wWindow::SetVSync(bool vsync, bool toggle /* = false */) +{ + m_Properties.vsync = toggle ? !m_Properties.vsync : vsync; + + glfwSwapInterval(m_Properties.vsync); +} + +void wWindow::SetVisibility(bool visible, bool toggle) +{ + m_Properties.visible = toggle ? !m_Properties.visible : visible; + + if (m_Properties.visible) + glfwShowWindow(m_Handle); + else + glfwHideWindow(m_Handle); +} + +void wWindow::BindGlfwEvents() +{ + //============================== MOUSE_EVENTS ==============================// + /* cursor position */ + glfwSetCursorPosCallback(m_Handle, [](GLFWwindow *window, double xpos, double ypos) { + std::function callback = *(std::function *) + glfwGetWindowUserPointer(window); + + MouseMovedEvent event(xpos, ypos); + callback(event); + }); + + /* mouse button */ + glfwSetMouseButtonCallback(m_Handle, [](GLFWwindow *window, int button, int action, int mods) { + std::function callback = *(std::function *) + glfwGetWindowUserPointer(window); + + if (action == GLFW_PRESS) + { + ButtonPressedEvent event(button); + callback(event); + } + else if (action == GLFW_RELEASE) + { + ButtonReleasedEvent event(button); + callback(event); + } + }); + + /* scroll */ + glfwSetScrollCallback(m_Handle, [](GLFWwindow *window, double xoffset, double yoffset) { + std::function callback = *(std::function *) + glfwGetWindowUserPointer(window); + + WheelScrolledEvent event(yoffset); + callback(event); + }); + //============================== MOUSE_EVENTS ==============================// + + //============================== KEYBOARD_EVENTS ==============================// + /* key */ + glfwSetKeyCallback( + m_Handle, + [](GLFWwindow *window, int key, int scancode, int action, int mods) { + std::function callback = *(std::function *) + glfwGetWindowUserPointer(window); + + if (action == GLFW_PRESS) + { + KeyPressedEvent event(key); + callback(event); + } + else if (action == GLFW_RELEASE) + { + KeyReleasedEvent event(key); + callback(event); + } + } + ); + /* char */ + glfwSetCharCallback(m_Handle, [](GLFWwindow *window, unsigned int character) { + std::function callback = *(std::function *) + glfwGetWindowUserPointer(window); + + SetCharEvent event(character); + callback(event); + }); + + //============================== KEYBOARD_EVENTS ==============================// + + //============================== WINDOW_EVENTS ==============================// + /* window position */ + glfwSetWindowPosCallback(m_Handle, [](GLFWwindow *window, int xpos, int ypos) { + std::function callback = *(std::function *) + glfwGetWindowUserPointer(window); + WindowMovedEvent event(xpos, ypos); + + callback(event); + }); + + /* window size */ + glfwSetWindowSizeCallback(m_Handle, [](GLFWwindow *window, int width, int height) { + std::function callback = *(std::function *) + glfwGetWindowUserPointer(window); + WindowResizedEvent event(width, height); + + callback(event); + }); + + /* window close */ + glfwSetWindowCloseCallback(m_Handle, [](GLFWwindow *window) { + std::function callback = *(std::function *) + glfwGetWindowUserPointer(window); + WindowClosedEvent event; + + callback(event); + }); + + /* window focus */ + glfwSetWindowFocusCallback(m_Handle, [](GLFWwindow *window, int focus) { + std::function callback = *(std::function *) + glfwGetWindowUserPointer(window); + + if (focus == GLFW_TRUE) + { + WindowGainFocusEvent event; + callback(event); + } + else + { + WindowLostFocusEvent event; + callback(event); + } + }); + //============================== WINDOW_EVENTS ==============================// } +} +} // namespace Light diff --git a/modules/engine/src/scene/entity.cpp b/modules/engine/src/scene/entity.cpp new file mode 100644 index 0000000..5082019 --- /dev/null +++ b/modules/engine/src/scene/entity.cpp @@ -0,0 +1,14 @@ +#include +#include + +namespace Light { + +Entity::Entity(entt::entity handle, Scene *scene): m_Handle(handle), m_Scene(scene) +{ +} + +Entity::~Entity() +{ +} + +} // namespace Light diff --git a/Engine/src/Engine/Scene/Scene.cpp b/modules/engine/src/scene/scene.cpp similarity index 55% rename from Engine/src/Engine/Scene/Scene.cpp rename to modules/engine/src/scene/scene.cpp index e24e7bd..90ed915 100644 --- a/Engine/src/Engine/Scene/Scene.cpp +++ b/modules/engine/src/scene/scene.cpp @@ -1,15 +1,12 @@ -#include "Scene.hpp" - -#include "Components.hpp" -#include "Entity.hpp" -#include "Graphics/Renderer.hpp" - +#include +#include +#include +#include #include namespace Light { -Scene::Scene() - : m_Registry() +Scene::Scene(): m_Registry() { } @@ -21,7 +18,7 @@ void Scene::OnCreate() { /* native scripts */ { - m_Registry.view().each([](NativeScriptComponent& nsc) { + m_Registry.view().each([](NativeScriptComponent &nsc) { if (nsc.instance == nullptr) { nsc.instance = nsc.CreateInstance(); @@ -35,26 +32,27 @@ void Scene::OnUpdate(float deltaTime) { /* native scripts */ { - m_Registry.view().each([=](NativeScriptComponent& nsc) { + m_Registry.view().each([=](NativeScriptComponent &nsc) { nsc.instance->OnUpdate(deltaTime); }); } } -void Scene::OnRender(const Ref& targetFrameBuffer /* = nullptr */) +void Scene::OnRender(const Ref &targetFrameBuffer /* = nullptr */) { - Camera* sceneCamera = nullptr; - TransformComponent* sceneCameraTransform; + Camera *sceneCamera = nullptr; + TransformComponent *sceneCameraTransform; /* scene camera */ { - m_Registry.group(entt::get).each([&](TransformComponent& transformComp, CameraComponent& cameraComp) { - if (cameraComp.isPrimary) - { - sceneCamera = &cameraComp.camera; - sceneCameraTransform = &transformComp; - } - }); + m_Registry.group(entt::get) + .each([&](TransformComponent &transformComp, CameraComponent &cameraComp) { + if (cameraComp.isPrimary) + { + sceneCamera = &cameraComp.camera; + sceneCameraTransform = &transformComp; + } + }); } /* draw quads */ @@ -63,27 +61,33 @@ void Scene::OnRender(const Ref& targetFrameBuffer /* = nullptr */) { Renderer::BeginScene(sceneCamera, *sceneCameraTransform, targetFrameBuffer); - m_Registry.group(entt::get).each([](TransformComponent& transformComp, SpriteRendererComponent& spriteRendererComp) { - Renderer::DrawQuad(transformComp, spriteRendererComp.tint, spriteRendererComp.texture); - }); + m_Registry.group(entt::get) + .each([](TransformComponent &transformComp, + SpriteRendererComponent &spriteRendererComp) { + Renderer::DrawQuad( + transformComp, + spriteRendererComp.tint, + spriteRendererComp.texture + ); + }); Renderer::EndScene(); } } } -Entity Scene::CreateEntity(const std::string& name, const TransformComponent& transform) +Entity Scene::CreateEntity(const std::string &name, const TransformComponent &transform) { return CreateEntityWithUUID(name, UUID(), transform); } -Entity Scene::GetEntityByTag(const std::string& tag) +Entity Scene::GetEntityByTag(const std::string &tag) { // TagComponent tagComp(tag); // entt::entity entity = entt::to_entity(m_Registry, tagComp); Entity entity; - m_Registry.view().each([&](TagComponent& tagComp) { + m_Registry.view().each([&](TagComponent &tagComp) { // if (tagComp.tag == tag) // entity = Entity(entt::to_entity(m_Registry, tagComp), this); }); @@ -97,7 +101,11 @@ Entity Scene::GetEntityByTag(const std::string& tag) } } -Entity Scene::CreateEntityWithUUID(const std::string& name, UUID uuid, const TransformComponent& transform) +Entity Scene::CreateEntityWithUUID( + const std::string &name, + UUID uuid, + const TransformComponent &transform +) { Entity entity { m_Registry.create(), this }; entity.AddComponent(name); diff --git a/modules/engine/src/time/timer.cpp b/modules/engine/src/time/timer.cpp new file mode 100644 index 0000000..6722d78 --- /dev/null +++ b/modules/engine/src/time/timer.cpp @@ -0,0 +1,20 @@ +#include + +namespace Light { + +Timer::Timer(): m_Start(std::chrono::steady_clock::now()) +{ +} + +DeltaTimer::DeltaTimer(): m_PreviousFrame(NULL), m_DeltaTime(60.0f / 1000.0f) +{ +} + +void DeltaTimer::Update() +{ + float currentFrame = timer.GetElapsedTime(); + m_DeltaTime = currentFrame - m_PreviousFrame; + m_PreviousFrame = currentFrame; +} + +} // namespace Light diff --git a/modules/engine/src/user_interface/user_interface.cpp b/modules/engine/src/user_interface/user_interface.cpp new file mode 100644 index 0000000..7bb2b86 --- /dev/null +++ b/modules/engine/src/user_interface/user_interface.cpp @@ -0,0 +1,235 @@ +#include +#include + +#ifdef LIGHT_PLATFORM_WINDOWS + #include + #include +#endif + +#include +#include +#include +#include +#include +#include +#include + +namespace Light { + +UserInterface *UserInterface::s_Context = nullptr; + +Scope UserInterface::Create( + GLFWwindow *windowHandle, + Ref sharedContext +) +{ + Scope scopeUserInterface = nullptr; + + switch (GraphicsContext::GetGraphicsAPI()) + { + case GraphicsAPI::OpenGL: scopeUserInterface = CreateScope(); break; + + case GraphicsAPI::DirectX: LT_WIN(scopeUserInterface = CreateScope();) break; + + default: + ASSERT( + false, + "UserInterface::Create: invalid/unsupported 'GraphicsAPI' {}", + static_cast(GraphicsContext::GetGraphicsAPI()) + ); + return nullptr; + } + + scopeUserInterface->Init(windowHandle, sharedContext); + return std::move(scopeUserInterface); +} + +UserInterface::UserInterface() + : m_DockspaceFlags( + ImGuiWindowFlags_MenuBar | ImGuiWindowFlags_NoDocking | ImGuiWindowFlags_NoTitleBar + | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove + | ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus + ) +{ + ASSERT( + !s_Context, + "UserInterface::UserInterface: an instance of 'UserInterface' already exists, do not " + "construct this class!" + ); + s_Context = this; +} + +void UserInterface::Init(GLFWwindow *windowHandle, Ref sharedContext) +{ + // create context + IMGUI_CHECKVERSION(); + ImGui::CreateContext(); + + // configure io + ImGuiIO &io = ImGui::GetIO(); + io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; + + io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; + io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable; + + io.ConfigFlags |= ImGuiBackendFlags_PlatformHasViewports; + io.ConfigFlags |= ImGuiBackendFlags_RendererHasViewports; + + // #todo: handle this in a better way + if (std::filesystem::exists("user_gui_layout.ini")) + io.IniFilename = "user_gui_layout.ini"; + else + io.IniFilename = "default_gui_layout.ini"; + + // style + ImGui::StyleColorsDark(); + + PlatformImplementation(windowHandle, sharedContext); + + // keyboard map + io.KeyMap[ImGuiKey_Tab] = Key::Tab; + io.KeyMap[ImGuiKey_LeftArrow] = Key::LeftArrow; + io.KeyMap[ImGuiKey_RightArrow] = Key::RightArrow; + io.KeyMap[ImGuiKey_UpArrow] = Key::UpArrow; + io.KeyMap[ImGuiKey_DownArrow] = Key::DownArrow; + io.KeyMap[ImGuiKey_PageUp] = Key::PageUp; + io.KeyMap[ImGuiKey_PageDown] = Key::PageDown; + io.KeyMap[ImGuiKey_Home] = Key::Home; + io.KeyMap[ImGuiKey_End] = Key::End; + io.KeyMap[ImGuiKey_Insert] = Key::Insert; + io.KeyMap[ImGuiKey_Delete] = Key::Delete; + io.KeyMap[ImGuiKey_Backspace] = Key::BackSpace; + io.KeyMap[ImGuiKey_Space] = Key::Space; + io.KeyMap[ImGuiKey_Enter] = Key::Enter; + io.KeyMap[ImGuiKey_Escape] = Key::Escape; + io.KeyMap[ImGuiKey_KeyPadEnter] = Key::Enter; + io.KeyMap[ImGuiKey_A] = Key::A; + io.KeyMap[ImGuiKey_C] = Key::C; + io.KeyMap[ImGuiKey_V] = Key::V; + io.KeyMap[ImGuiKey_X] = Key::X; + io.KeyMap[ImGuiKey_Y] = Key::Y; + io.KeyMap[ImGuiKey_Z] = Key::Z; + + io.Fonts->AddFontFromFileTTF("Assets//Fonts/OpenSans/OpenSans-Bold.ttf", 18.0f); + io.FontDefault = io.Fonts->AddFontFromFileTTF( + "Assets/Fonts/OpenSans/OpenSans-Regular.ttf", + 18.0f + ); + + SetDarkThemeColors(); +} + +void UserInterface::DockspaceBegin() +{ + ImGuiViewport *viewport = ImGui::GetMainViewport(); + ImGui::SetNextWindowPos(viewport->Pos); + ImGui::SetNextWindowSize(viewport->Size); + ImGui::SetNextWindowViewport(viewport->ID); + + ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f); + ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f)); + ImGui::Begin("Dockspace", (bool *)0, s_Context->m_DockspaceFlags); + ImGui::PopStyleVar(3); + + ImGuiStyle &style = ImGui::GetStyle(); + float minWinSizeX = style.WindowMinSize.x; + style.WindowMinSize.x = 370.0f; + ImGui::DockSpace( + ImGui::GetID("MyDockSpace"), + ImVec2(0.0f, 0.0f), + ImGuiDockNodeFlags_None | ImGuiWindowFlags_NoBackground + ); + style.WindowMinSize.x = minWinSizeX; +} + +void UserInterface::DockspaceEnd() +{ + ImGui::End(); +} + +void UserInterface::SetDarkThemeColors() +{ + ImGuiStyle &style = ImGui::GetStyle(); + ImVec4(&colors)[55] = style.Colors; + + style.WindowPadding = ImVec2(0.0f, 0.0f); + + colors[ImGuiCol_Text] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); + colors[ImGuiCol_TextDisabled] = ImVec4(0.50f, 0.50f, 0.50f, 1.00f); + + colors[ImGuiCol_WindowBg] = ImVec4(0.10f, 0.10f, 0.11f, 1.00f); + colors[ImGuiCol_ChildBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); + colors[ImGuiCol_PopupBg] = ImVec4(0.08f, 0.08f, 0.08f, 0.94f); + + colors[ImGuiCol_Border] = ImVec4(0.43f, 0.43f, 0.50f, 0.50f); + colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); + + colors[ImGuiCol_FrameBg] = ImVec4(0.20f, 0.20f, 0.21f, 1.00f); + colors[ImGuiCol_FrameBgHovered] = ImVec4(0.30f, 0.31f, 0.31f, 1.00f); + colors[ImGuiCol_FrameBgActive] = ImVec4(0.15f, 0.15f, 0.15f, 1.00f); + + colors[ImGuiCol_TitleBg] = ImVec4(0.15f, 0.15f, 0.15f, 1.00f); + colors[ImGuiCol_TitleBgActive] = ImVec4(0.15f, 0.15f, 0.15f, 1.00f); + colors[ImGuiCol_TitleBgCollapsed] = ImVec4(0.15f, 0.15f, 0.15f, 1.00f); + + colors[ImGuiCol_MenuBarBg] = ImVec4(0.14f, 0.14f, 0.14f, 1.00f); + + colors[ImGuiCol_ScrollbarBg] = ImVec4(0.02f, 0.02f, 0.02f, 0.53f); + colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.31f, 0.31f, 0.31f, 1.00f); + colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(0.41f, 0.41f, 0.41f, 1.00f); + colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(0.51f, 0.51f, 0.51f, 1.00f); + + colors[ImGuiCol_CheckMark] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f); + + colors[ImGuiCol_SliderGrab] = ImVec4(0.24f, 0.52f, 0.88f, 1.00f); + colors[ImGuiCol_SliderGrabActive] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f); + + colors[ImGuiCol_Button] = ImVec4(0.20f, 0.20f, 0.21f, 1.00f); + colors[ImGuiCol_ButtonHovered] = ImVec4(0.30f, 0.31f, 0.31f, 1.00f); + colors[ImGuiCol_ButtonActive] = ImVec4(0.15f, 0.15f, 0.15f, 1.00f); + + colors[ImGuiCol_Header] = ImVec4(0.20f, 0.20f, 0.21f, 1.00f); + colors[ImGuiCol_HeaderHovered] = ImVec4(0.30f, 0.31f, 0.31f, 1.00f); + colors[ImGuiCol_HeaderActive] = ImVec4(0.15f, 0.15f, 0.15f, 1.00f); + + colors[ImGuiCol_Separator] = ImVec4(0.43f, 0.43f, 0.50f, 0.50f); + colors[ImGuiCol_SeparatorHovered] = ImVec4(0.10f, 0.40f, 0.75f, 0.78f); + colors[ImGuiCol_SeparatorActive] = ImVec4(0.10f, 0.40f, 0.75f, 1.00f); + + colors[ImGuiCol_ResizeGrip] = ImVec4(0.26f, 0.59f, 0.98f, 0.20f); + colors[ImGuiCol_ResizeGripHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.67f); + colors[ImGuiCol_ResizeGripActive] = ImVec4(0.26f, 0.59f, 0.98f, 0.95f); + + colors[ImGuiCol_Tab] = ImVec4(0.15f, 0.15f, 0.15f, 1.00f); + colors[ImGuiCol_TabHovered] = ImVec4(0.38f, 0.38f, 0.38f, 1.00f); + colors[ImGuiCol_TabActive] = ImVec4(0.28f, 0.28f, 0.28f, 1.00f); + colors[ImGuiCol_TabUnfocused] = ImVec4(0.15f, 0.15f, 0.15f, 1.00f); + colors[ImGuiCol_TabUnfocusedActive] = ImVec4(0.20f, 0.20f, 0.21f, 1.00f); + + colors[ImGuiCol_DockingPreview] = ImVec4(0.26f, 0.59f, 0.98f, 0.70f); + colors[ImGuiCol_DockingEmptyBg] = ImVec4(0.20f, 0.20f, 0.20f, 1.00f); + + colors[ImGuiCol_PlotLines] = ImVec4(0.61f, 0.61f, 0.61f, 1.00f); + colors[ImGuiCol_PlotLinesHovered] = ImVec4(1.00f, 0.43f, 0.35f, 1.00f); + colors[ImGuiCol_PlotHistogram] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f); + colors[ImGuiCol_PlotHistogramHovered] = ImVec4(1.00f, 0.60f, 0.00f, 1.00f); + + colors[ImGuiCol_TableHeaderBg] = ImVec4(0.19f, 0.19f, 0.20f, 1.00f); + colors[ImGuiCol_TableBorderStrong] = ImVec4(0.31f, 0.31f, 0.35f, 1.00f); + colors[ImGuiCol_TableBorderLight] = ImVec4(0.23f, 0.23f, 0.25f, 1.00f); + colors[ImGuiCol_TableRowBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); + colors[ImGuiCol_TableRowBgAlt] = ImVec4(1.00f, 1.00f, 1.00f, 0.06f); + + colors[ImGuiCol_TextSelectedBg] = ImVec4(0.26f, 0.59f, 0.98f, 0.35f); + + colors[ImGuiCol_DragDropTarget] = ImVec4(1.00f, 1.00f, 0.00f, 0.90f); + + colors[ImGuiCol_NavHighlight] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f); + colors[ImGuiCol_NavWindowingHighlight] = ImVec4(1.00f, 1.00f, 1.00f, 0.70f); + colors[ImGuiCol_NavWindowingDimBg] = ImVec4(0.80f, 0.80f, 0.80f, 0.20f); + + colors[ImGuiCol_ModalWindowDimBg] = ImVec4(0.80f, 0.80f, 0.80f, 0.35f); +} + +} // namespace Light diff --git a/modules/engine/src/utils/file_manager.cpp b/modules/engine/src/utils/file_manager.cpp new file mode 100644 index 0000000..42e575e --- /dev/null +++ b/modules/engine/src/utils/file_manager.cpp @@ -0,0 +1,110 @@ +#define STB_IMAGE_IMPLEMENTATION +#include +#include + +namespace Light { + +BasicFileHandle::BasicFileHandle( + uint8_t *data, + uint32_t size, + const std::string &path, + const std::string &name, + const std::string &extension +) + : m_Data(data) + , m_Size(size) + , m_Path(path) + , m_Name(name) + , m_Extension(extension) +{ +} + +void BasicFileHandle::Release() +{ + delete m_Data; + m_Data = nullptr; + m_Size = 0ull; +} + + +BasicFileHandle FileManager::ReadTextFile(const std::string &path) +{ + // parse path info + std::string name = path.substr(0, path.find('.') + -1); + std::string extension = path.substr(path.find('.') + 1); + + // open file + std::ifstream file(path.c_str(), std::ios_base::in | std::ios_base::binary); + + // check + if (!file) + { + LOG(warn, "Failed to load text file: {}", path); + file.close(); + return NULL; + } + + // fetch file size + file.seekg(0, std::ios::end); + uint32_t size = file.tellg(); + file.seekg(0, std::ios::beg); + + if (!size) + LOG(warn, "Empty text file: {}", path); + + // read file + uint8_t *data = new uint8_t[size]; + file.read(reinterpret_cast(data), size); + + file.close(); + return BasicFileHandle(data, size, path, name, extension); +} + +ImageFileHandle FileManager::ReadImageFile(const std::string &path, int32_t desiredComponents) +{ + // parse path info + std::string name = path.substr(0, path.find('.') + -1); + std::string extension = path.substr(path.find('.') + 1); + + // load image + int32_t width = 0, height = 0, fetchedComponents = 0; + uint8_t *pixels = stbi_load( + path.c_str(), + &width, + &height, + &fetchedComponents, + desiredComponents + ); + + // check + if (!pixels) + LOG(warn, "Failed to load image file: <{}>", path); + else if (fetchedComponents != desiredComponents) + LOG(warn, + "Mismatch of fetched/desired components: <{}> ({}/{})", + name + '.' + extension, + fetchedComponents, + desiredComponents); + + return ImageFileHandle( + pixels, + width * height, + path, + name, + extension, + width, + height, + fetchedComponents, + desiredComponents + ); +} + +void ImageFileHandle::Release() +{ + stbi_image_free(reinterpret_cast(m_Data)); + m_Data = nullptr; + m_Size = 0ull; +} + + +} // namespace Light diff --git a/modules/engine/src/utils/resource_manager.cpp b/modules/engine/src/utils/resource_manager.cpp new file mode 100644 index 0000000..05789d0 --- /dev/null +++ b/modules/engine/src/utils/resource_manager.cpp @@ -0,0 +1,87 @@ +#include +#include +#include +#include +#include + +namespace Light { + +ResourceManager *ResourceManager::s_Context = nullptr; + +Scope ResourceManager::Create() +{ + return MakeScope(new ResourceManager()); +} + +ResourceManager::ResourceManager(): m_Shaders {}, m_Textures {} +{ + ASSERT(!s_Context, "Repeated singleton construction"); + s_Context = this; +} + +void ResourceManager::LoadShaderImpl( + const std::string &name, + const std::string &vertexPath, + const std::string &pixelPath +) +{ + // check + ASSERT(s_Context, "Uninitliazed singleton"); + ASSERT(!vertexPath.empty(), "Empty 'vertexPath'"); + ASSERT(!pixelPath.empty(), "Empty 'pixelPath'"); + + // load files + BasicFileHandle vertexFile = FileManager::ReadTextFile(vertexPath); + BasicFileHandle pixelFile = FileManager::ReadTextFile(pixelPath); + + // check + ASSERT(vertexFile.IsValid(), "Failed to read vertex file: {}", vertexPath); + ASSERT(pixelFile.IsValid(), "Failed to read vertex file: {}", pixelPath); + + // create shader + m_Shaders[name] = Ref( + Shader::Create(vertexFile, pixelFile, GraphicsContext::GetSharedContext()) + ); + + // free file + vertexFile.Release(); + pixelFile.Release(); +} + +void ResourceManager::LoadTextureImpl( + const std::string &name, + const std::string &path, + unsigned int desiredComponents /* = 4u */ +) +{ + ASSERT(s_Context, "Uninitliazed singleton"); + + // load file + ImageFileHandle imgFile = FileManager::ReadImageFile(path, desiredComponents); + + // create texture + m_Textures[name] = Ref(Texture::Create( + imgFile.GetWidth(), + imgFile.GetHeight(), + imgFile.GetComponents(), + imgFile.GetData(), + GraphicsContext::GetSharedContext(), + path + )); + + // free file + imgFile.Release(); +} + +void ResourceManager::ReleaseTextureImpl(const std::string &name) +{ + if (!m_Textures[name]) + { + LOG(warn, "Failed to find texture named: {}", name); + return; + } + + m_Textures[name] = nullptr; +} + +} // namespace Light diff --git a/Engine/src/Engine/Utility/Serializer.cpp b/modules/engine/src/utils/serializer.cpp similarity index 56% rename from Engine/src/Engine/Utility/Serializer.cpp rename to modules/engine/src/utils/serializer.cpp index 4317828..ed45959 100644 --- a/Engine/src/Engine/Utility/Serializer.cpp +++ b/modules/engine/src/utils/serializer.cpp @@ -1,15 +1,14 @@ -#include "Serializer.hpp" - -#include "Graphics/Texture.hpp" -#include "Scene/Components.hpp" -#include "Utility/ResourceManager.hpp" +#include +#include +#include +#include namespace YAML { template<> struct convert { - static Node encode(const glm::vec3& rhs) + static Node encode(const glm::vec3 &rhs) { Node node; node.push_back(rhs.x); @@ -18,7 +17,7 @@ struct convert return node; } - static bool decode(const Node& node, glm::vec3& rhs) + static bool decode(const Node &node, glm::vec3 &rhs) { if (!node.IsSequence() || node.size() != 3) return false; @@ -33,7 +32,7 @@ struct convert template<> struct convert { - static Node encode(const glm::vec4& rhs) + static Node encode(const glm::vec4 &rhs) { Node node; node.push_back(rhs.x); @@ -43,7 +42,7 @@ struct convert return node; } - static bool decode(const Node& node, glm::vec4& rhs) + static bool decode(const Node &node, glm::vec4 &rhs) { if (!node.IsSequence() || node.size() != 4) return false; @@ -59,26 +58,25 @@ struct convert namespace Light { -static YAML::Emitter& operator<<(YAML::Emitter& out, const glm::vec3& v) +static YAML::Emitter &operator<<(YAML::Emitter &out, const glm::vec3 &v) { out << YAML::Flow; out << YAML::BeginSeq << v.x << v.y << v.z << YAML::EndSeq; return out; } -static YAML::Emitter& operator<<(YAML::Emitter& out, const glm::vec4& v) +static YAML::Emitter &operator<<(YAML::Emitter &out, const glm::vec4 &v) { out << YAML::Flow; out << YAML::BeginSeq << v.x << v.y << v.z << v.w << YAML::EndSeq; return out; } -SceneSerializer::SceneSerializer(const Ref& scene) - : m_Scene(scene) +SceneSerializer::SceneSerializer(const Ref &scene): m_Scene(scene) { } -void SceneSerializer::Serialize(const std::string& filePath) +void SceneSerializer::Serialize(const std::string &filePath) { YAML::Emitter out; out << YAML::BeginMap; // Scene @@ -104,7 +102,7 @@ void SceneSerializer::Serialize(const std::string& filePath) fout << out.c_str(); } -bool SceneSerializer::Deserialize(const std::string& filePath) +bool SceneSerializer::Deserialize(const std::string &filePath) { std::ifstream stream(filePath); std::stringstream ss; @@ -143,19 +141,23 @@ bool SceneSerializer::Deserialize(const std::string& filePath) auto transformComponent = entity["TransformComponent"]; if (transformComponent) { - auto& entityTransforomComponent = deserializedEntity.GetComponent(); + auto &entityTransforomComponent = deserializedEntity + .GetComponent(); - entityTransforomComponent.translation = transformComponent["Translation"].as(); - entityTransforomComponent.rotation = transformComponent["Rotation"].as(); - entityTransforomComponent.scale = transformComponent["Scale"].as(); + entityTransforomComponent.translation = transformComponent["Translation"] + .as(); + entityTransforomComponent.rotation = transformComponent["Rotation"].as(); + entityTransforomComponent.scale = transformComponent["Scale"].as(); } /* #TEMPORARY SOLUTION# */ auto spriteRendererComponent = entity["SpriteRendererComponent"]; if (spriteRendererComponent) { - auto& entitySpriteRendererComponent = deserializedEntity.AddComponent(); - entitySpriteRendererComponent.tint = spriteRendererComponent["Tint"].as(); + auto &entitySpriteRendererComponent = deserializedEntity + .AddComponent(); + entitySpriteRendererComponent.tint = spriteRendererComponent["Tint"].as( + ); std::string texturePath = spriteRendererComponent["Texture"].as(); @@ -172,20 +174,36 @@ bool SceneSerializer::Deserialize(const std::string& filePath) auto cameraComponent = entity["CameraComponent"]; if (cameraComponent) { - auto& entityCameraComponent = deserializedEntity.AddComponent(); + auto &entityCameraComponent = deserializedEntity.AddComponent(); - const auto& cameraSpecifications = cameraComponent["Camera"]; - entityCameraComponent.camera.SetProjectionType((SceneCamera::ProjectionType)cameraSpecifications["ProjectionType"].as()); + const auto &cameraSpecifications = cameraComponent["Camera"]; + entityCameraComponent.camera.SetProjectionType( + (SceneCamera::ProjectionType)cameraSpecifications["ProjectionType"].as() + ); - entityCameraComponent.camera.SetOrthographicSize(cameraSpecifications["OrthographicSize"].as()); - entityCameraComponent.camera.SetOrthographicNearPlane(cameraSpecifications["OrthographicNearPlane"].as()); - entityCameraComponent.camera.SetOrthographicFarPlane(cameraSpecifications["OrthographicFarPlane"].as()); + entityCameraComponent.camera.SetOrthographicSize( + cameraSpecifications["OrthographicSize"].as() + ); + entityCameraComponent.camera.SetOrthographicNearPlane( + cameraSpecifications["OrthographicNearPlane"].as() + ); + entityCameraComponent.camera.SetOrthographicFarPlane( + cameraSpecifications["OrthographicFarPlane"].as() + ); - entityCameraComponent.camera.SetPerspectiveVerticalFOV(cameraSpecifications["PerspectiveVerticalFOV"].as()); - entityCameraComponent.camera.SetPerspectiveNearPlane(cameraSpecifications["PerspectiveNearPlane"].as()); - entityCameraComponent.camera.SetPerspectiveFarPlane(cameraSpecifications["PerspectiveFarPlane"].as()); + entityCameraComponent.camera.SetPerspectiveVerticalFOV( + cameraSpecifications["PerspectiveVerticalFOV"].as() + ); + entityCameraComponent.camera.SetPerspectiveNearPlane( + cameraSpecifications["PerspectiveNearPlane"].as() + ); + entityCameraComponent.camera.SetPerspectiveFarPlane( + cameraSpecifications["PerspectiveFarPlane"].as() + ); - entityCameraComponent.camera.SetBackgroundColor(cameraSpecifications["BackgroundColor"].as()); + entityCameraComponent.camera.SetBackgroundColor( + cameraSpecifications["BackgroundColor"].as() + ); entityCameraComponent.isPrimary = cameraComponent["IsPrimary"].as(); } @@ -197,18 +215,18 @@ bool SceneSerializer::Deserialize(const std::string& filePath) return false; } -void SceneSerializer::SerializeBinary(const std::string& filePath) +void SceneSerializer::SerializeBinary(const std::string &filePath) { LOG(err, "NO_IMPLEMENT"); } -bool SceneSerializer::DeserializeBinary(const std::string& filePath) +bool SceneSerializer::DeserializeBinary(const std::string &filePath) { LOG(err, "NO_IMPLEMENT"); return false; } -void SceneSerializer::SerializeEntity(YAML::Emitter& out, Entity entity) +void SceneSerializer::SerializeEntity(YAML::Emitter &out, Entity entity) { out << YAML::BeginMap; // entity out << YAML::Key << "Entity" << YAML::Value << entity.GetUUID(); // dummy uuid @@ -218,7 +236,7 @@ void SceneSerializer::SerializeEntity(YAML::Emitter& out, Entity entity) out << YAML::Key << "TagComponent"; out << YAML::BeginMap; // tag component - auto& tagComponent = entity.GetComponent().tag; + auto &tagComponent = entity.GetComponent().tag; out << YAML::Key << "Tag" << YAML::Value << tagComponent; out << YAML::EndMap; // tag component @@ -229,7 +247,7 @@ void SceneSerializer::SerializeEntity(YAML::Emitter& out, Entity entity) out << YAML::Key << "TransformComponent"; out << YAML::BeginMap; // transform component - auto& transformComponent = entity.GetComponent(); + auto &transformComponent = entity.GetComponent(); out << YAML::Key << "Translation" << YAML::Value << transformComponent.translation; out << YAML::Key << "Rotation" << YAML::Value << transformComponent.rotation; @@ -243,9 +261,10 @@ void SceneSerializer::SerializeEntity(YAML::Emitter& out, Entity entity) out << YAML::Key << "SpriteRendererComponent"; out << YAML::BeginMap; // sprite renderer component; - auto& spriteRendererComponent = entity.GetComponent(); + auto &spriteRendererComponent = entity.GetComponent(); - out << YAML::Key << "Texture" << YAML::Value << spriteRendererComponent.texture->GetFilePath(); + out << YAML::Key << "Texture" << YAML::Value + << spriteRendererComponent.texture->GetFilePath(); out << YAML::Key << "Tint" << YAML::Value << spriteRendererComponent.tint; out << YAML::EndMap; // sprite renderer component @@ -259,18 +278,26 @@ void SceneSerializer::SerializeEntity(YAML::Emitter& out, Entity entity) out << YAML::Key << "CameraComponent"; out << YAML::BeginMap; // camera component - auto& cameraComponent = entity.GetComponent(); + auto &cameraComponent = entity.GetComponent(); out << YAML::Key << "Camera" << YAML::Value; out << YAML::BeginMap; // camera - out << YAML::Key << "OrthographicSize" << YAML::Value << cameraComponent.camera.GetOrthographicSize(); - out << YAML::Key << "OrthographicFarPlane" << YAML::Value << cameraComponent.camera.GetOrthographicFarPlane(); - out << YAML::Key << "OrthographicNearPlane" << YAML::Value << cameraComponent.camera.GetOrthographicNearPlane(); - out << YAML::Key << "PerspectiveVerticalFOV" << YAML::Value << cameraComponent.camera.GetPerspectiveVerticalFOV(); - out << YAML::Key << "PerspectiveFarPlane" << YAML::Value << cameraComponent.camera.GetPerspectiveFarPlane(); - out << YAML::Key << "PerspectiveNearPlane" << YAML::Value << cameraComponent.camera.GetPerspectiveNearPlane(); - out << YAML::Key << "ProjectionType" << YAML::Value << (int)cameraComponent.camera.GetProjectionType(); - out << YAML::Key << "BackgroundColor" << YAML::Value << cameraComponent.camera.GetBackgroundColor(); + out << YAML::Key << "OrthographicSize" << YAML::Value + << cameraComponent.camera.GetOrthographicSize(); + out << YAML::Key << "OrthographicFarPlane" << YAML::Value + << cameraComponent.camera.GetOrthographicFarPlane(); + out << YAML::Key << "OrthographicNearPlane" << YAML::Value + << cameraComponent.camera.GetOrthographicNearPlane(); + out << YAML::Key << "PerspectiveVerticalFOV" << YAML::Value + << cameraComponent.camera.GetPerspectiveVerticalFOV(); + out << YAML::Key << "PerspectiveFarPlane" << YAML::Value + << cameraComponent.camera.GetPerspectiveFarPlane(); + out << YAML::Key << "PerspectiveNearPlane" << YAML::Value + << cameraComponent.camera.GetPerspectiveNearPlane(); + out << YAML::Key << "ProjectionType" << YAML::Value + << (int)cameraComponent.camera.GetProjectionType(); + out << YAML::Key << "BackgroundColor" << YAML::Value + << cameraComponent.camera.GetBackgroundColor(); out << YAML::EndMap; // camera out << YAML::Key << "IsPrimary" << YAML::Value << cameraComponent.isPrimary; diff --git a/Engine/src/Engine/Utility/Stringifier.cpp b/modules/engine/src/utils/stringifier.cpp similarity index 96% rename from Engine/src/Engine/Utility/Stringifier.cpp rename to modules/engine/src/utils/stringifier.cpp index a1e0730..1d21427 100644 --- a/Engine/src/Engine/Utility/Stringifier.cpp +++ b/modules/engine/src/utils/stringifier.cpp @@ -1,7 +1,5 @@ -#include "Stringifier.hpp" - -#include "Graphics/GraphicsContext.hpp" - +#include +#include #include #include @@ -84,4 +82,4 @@ std::string Stringifier::GraphicsAPIToString(GraphicsAPI api) } //==================== GRAPHICS_API ====================// -} // namespace Light \ No newline at end of file +} // namespace Light diff --git a/modules/mirror/CMakeLists.txt b/modules/mirror/CMakeLists.txt new file mode 100644 index 0000000..a5e367c --- /dev/null +++ b/modules/mirror/CMakeLists.txt @@ -0,0 +1,14 @@ +add_executable_module(mirror + editor_layer.cpp + mirror.cpp + panel/asset_browser.cpp + panel/properties.cpp + panel/scene_hierarchy.cpp +) + +target_link_libraries( + mirror + PUBLIC engine + PUBLIC opengl::opengl + PUBLIC imgui +) diff --git a/Mirror/src/EditorLayer.hpp b/modules/mirror/include/mirror/editor_layer.hpp similarity index 75% rename from Mirror/src/EditorLayer.hpp rename to modules/mirror/include/mirror/editor_layer.hpp index bcc049f..3d5e595 100644 --- a/Mirror/src/EditorLayer.hpp +++ b/modules/mirror/include/mirror/editor_layer.hpp @@ -1,11 +1,10 @@ #pragma once -#include "Panels/AssetBrowser.hpp" -#include "Panels/PropertiesPanel.hpp" -#include "Panels/SceneHierarchyPanel.hpp" - -#include +#include #include +#include +#include +#include namespace Light { @@ -31,7 +30,7 @@ private: ImVec2 m_AvailableContentRegionPrev; public: - EditorLayer(const std::string& name, const std::vector& args); + EditorLayer(const std::string &name); ~EditorLayer(); void OnUpdate(float deltaTime) override; diff --git a/Mirror/src/Panels/AssetBrowser.hpp b/modules/mirror/include/mirror/panel/asset_browser.hpp similarity index 86% rename from Mirror/src/Panels/AssetBrowser.hpp rename to modules/mirror/include/mirror/panel/asset_browser.hpp index e88513b..24f30ab 100644 --- a/Mirror/src/Panels/AssetBrowser.hpp +++ b/modules/mirror/include/mirror/panel/asset_browser.hpp @@ -1,9 +1,8 @@ #pragma once -#include "Panel.hpp" - -#include +#include #include +#include namespace Light { @@ -29,7 +28,7 @@ private: const std::filesystem::path m_AssetsPath; // TODO: Save configuration - uint32_t m_FileSize = 128u; + uint32_t m_FileSize = 128u; uint32_t m_FilePadding = 8u; Ref m_ActiveScene; diff --git a/Mirror/src/Panels/Panel.hpp b/modules/mirror/include/mirror/panel/panel.hpp similarity index 100% rename from Mirror/src/Panels/Panel.hpp rename to modules/mirror/include/mirror/panel/panel.hpp diff --git a/Mirror/src/Panels/PropertiesPanel.hpp b/modules/mirror/include/mirror/panel/properties.hpp similarity index 51% rename from Mirror/src/Panels/PropertiesPanel.hpp rename to modules/mirror/include/mirror/panel/properties.hpp index 7e3017b..d255fe3 100644 --- a/Mirror/src/Panels/PropertiesPanel.hpp +++ b/modules/mirror/include/mirror/panel/properties.hpp @@ -1,7 +1,7 @@ #pragma once -#include "Panel.hpp" -#include "Scene/Entity.hpp" +#include +#include namespace Light { @@ -11,7 +11,7 @@ private: Entity m_EntityContext; public: - PropertiesPanel() = default; + PropertiesPanel() = default; ~PropertiesPanel() = default; void OnUserInterfaceUpdate(); @@ -19,10 +19,15 @@ public: void SetEntityContext(Entity entity); private: - void DrawVec3Control(const std::string& label, glm::vec3& values, float resetValue = 0.0f, float columnWidth = 100.0f); + void DrawVec3Control( + const std::string &label, + glm::vec3 &values, + float resetValue = 0.0f, + float columnWidth = 100.0f + ); template - void DrawComponent(const std::string& name, Entity entity, UIFunction function); + void DrawComponent(const std::string &name, Entity entity, UIFunction function); }; diff --git a/Mirror/src/Panels/SceneHierarchyPanel.hpp b/modules/mirror/include/mirror/panel/scene_hierarchy.hpp similarity index 71% rename from Mirror/src/Panels/SceneHierarchyPanel.hpp rename to modules/mirror/include/mirror/panel/scene_hierarchy.hpp index 4e2a19a..d8362df 100644 --- a/Mirror/src/Panels/SceneHierarchyPanel.hpp +++ b/modules/mirror/include/mirror/panel/scene_hierarchy.hpp @@ -1,9 +1,9 @@ #pragma once -#include "Base/Base.hpp" -#include "Panel.hpp" -#include "Scene/Entity.hpp" -#include "Scene/Scene.hpp" +#include +#include +#include +#include namespace Light { @@ -25,7 +25,7 @@ public: void SetContext(Ref context, Ref propertiesPanel = nullptr); private: - void DrawNode(Entity entity, const std::string& label); + void DrawNode(Entity entity, const std::string &label); }; } // namespace Light diff --git a/Mirror/src/EditorLayer.cpp b/modules/mirror/src/editor_layer.cpp similarity index 79% rename from Mirror/src/EditorLayer.cpp rename to modules/mirror/src/editor_layer.cpp index dee6249..d69fae6 100644 --- a/Mirror/src/EditorLayer.cpp +++ b/modules/mirror/src/editor_layer.cpp @@ -1,15 +1,13 @@ -#include "EditorLayer.hpp" - -#include +#include +#include namespace Light { -EditorLayer::EditorLayer(const std::string& name, const std::vector& args) - : Layer(name), m_SceneDir(args.empty() ? "" : args[0]) +EditorLayer::EditorLayer(const std::string &name): Layer(name), m_SceneDir("") { m_Scene = CreateRef(); - m_PropertiesPanel = CreateRef(); + m_PropertiesPanel = CreateRef(); m_SceneHierarchyPanel = CreateRef(m_Scene, m_PropertiesPanel); m_ContentBrowserPanel = CreateRef(m_Scene); @@ -22,7 +20,10 @@ EditorLayer::EditorLayer(const std::string& name, const std::vector ResourceManager::LoadTexture("Awesomeface", "Assets/Textures/awesomeface.png"); Entity entity = m_Scene->CreateEntity("Awesomeface", {}); - entity.AddComponent(ResourceManager::GetTexture("Awesomeface"), glm::vec4 { 0.0f, 1.0f, 1.0f, 1.0f }); + entity.AddComponent( + ResourceManager::GetTexture("Awesomeface"), + glm::vec4 { 0.0f, 1.0f, 1.0f, 1.0f } + ); } else { @@ -54,7 +55,7 @@ void EditorLayer::OnUpdate(float deltaTime) Input::GetKeyboardKey(Key::W) ? 1.0f : 0.0f; - auto& cameraTranslation = m_CameraEntity.GetComponent().translation; + auto &cameraTranslation = m_CameraEntity.GetComponent().translation; cameraTranslation += glm::vec3(m_Direction * m_Speed * deltaTime, 0.0f); if (Input::GetKeyboardKey(Key::Escape)) @@ -79,7 +80,7 @@ void EditorLayer::OnUserInterfaceUpdate() if (m_AvailableContentRegionPrev != regionAvail) { m_Framebuffer->Resize({ regionAvail.x, regionAvail.y }); - auto& camera = m_CameraEntity.GetComponent().camera; + auto &camera = m_CameraEntity.GetComponent().camera; camera.SetViewportSize(regionAvail.x, regionAvail.y); m_AvailableContentRegionPrev = regionAvail; @@ -88,7 +89,12 @@ void EditorLayer::OnUserInterfaceUpdate() if (GraphicsContext::GetGraphicsAPI() == GraphicsAPI::DirectX) ImGui::Image(m_Framebuffer->GetColorAttachment(), regionAvail); else - ImGui::Image(m_Framebuffer->GetColorAttachment(), regionAvail, ImVec2(0, 1), ImVec2(1, 0)); + ImGui::Image( + m_Framebuffer->GetColorAttachment(), + regionAvail, + ImVec2(0, 1), + ImVec2(1, 0) + ); } ImGui::End(); diff --git a/modules/mirror/src/mirror.cpp b/modules/mirror/src/mirror.cpp new file mode 100644 index 0000000..eae76dc --- /dev/null +++ b/modules/mirror/src/mirror.cpp @@ -0,0 +1,34 @@ +#define LIGHT_ENTRY_POINT + +// +#include + +// +#include + +namespace Light { + +class Mirror: public Light::Application +{ +public: + Mirror() + { + // Set window properties + Light::WindowProperties properties; + properties.title = "Mirror"; + properties.size = glm::uvec2(1280u, 720u); + properties.vsync = true; + + m_Window->SetProperties(properties); + + // Attach the sandbox layer + LayerStack::EmplaceLayer(("MirrorLayer")); + } +}; + +Application *CreateApplication() +{ + return new Mirror(); +} + +} // namespace Light diff --git a/Mirror/src/Panels/AssetBrowser.cpp b/modules/mirror/src/panel/asset_browser.cpp similarity index 51% rename from Mirror/src/Panels/AssetBrowser.cpp rename to modules/mirror/src/panel/asset_browser.cpp index 1cc30f0..c0f889b 100644 --- a/Mirror/src/Panels/AssetBrowser.cpp +++ b/modules/mirror/src/panel/asset_browser.cpp @@ -1,13 +1,14 @@ -#include "Panels/AssetBrowser.hpp" - -#include -#include +#include +#include #include +#include namespace Light { AssetBrowserPanel::AssetBrowserPanel(Ref activeScene) - : m_CurrentDirectory("Assets"), m_AssetsPath("Assets"), m_ActiveScene(activeScene) + : m_CurrentDirectory("Assets") + , m_AssetsPath("Assets") + , m_ActiveScene(activeScene) { ResourceManager::LoadTexture("_Assets_Directory", "EngineResources/Icons/Asset_Directory.png"); ResourceManager::LoadTexture("_Assets_Scene", "EngineResources/Icons/Asset_Scene.png"); @@ -15,9 +16,9 @@ AssetBrowserPanel::AssetBrowserPanel(Ref activeScene) ResourceManager::LoadTexture("_Assets_Text", "EngineResources/Icons/Asset_Text.png"); m_DirectoryTexture = ResourceManager::GetTexture("_Assets_Directory"); - m_SceneTexture = ResourceManager::GetTexture("_Assets_Scene"); - m_ImageTexture = ResourceManager::GetTexture("_Assets_Image"); - m_TextTexture = ResourceManager::GetTexture("_Assets_Text"); + m_SceneTexture = ResourceManager::GetTexture("_Assets_Scene"); + m_ImageTexture = ResourceManager::GetTexture("_Assets_Image"); + m_TextTexture = ResourceManager::GetTexture("_Assets_Text"); } void AssetBrowserPanel::OnUserInterfaceUpdate() @@ -33,16 +34,20 @@ void AssetBrowserPanel::OnUserInterfaceUpdate() } } - ImVec2 regionAvail = ImGui::GetContentRegionAvail(); - uint32_t cellSize = m_FileSize + m_FilePadding; - uint32_t columnCount = std::clamp(static_cast(std::floor(regionAvail.x / cellSize)), 1u, 64u); + ImVec2 regionAvail = ImGui::GetContentRegionAvail(); + uint32_t cellSize = m_FileSize + m_FilePadding; + uint32_t columnCount = std::clamp( + static_cast(std::floor(regionAvail.x / cellSize)), + 1u, + 64u + ); if (ImGui::BeginTable("ContentBrowser", columnCount)) { m_DirectoryTexture->Bind(0u); - for (auto& dirEntry : std::filesystem::directory_iterator(m_CurrentDirectory)) + for (auto &dirEntry : std::filesystem::directory_iterator(m_CurrentDirectory)) { - const auto& path = dirEntry.path(); + const auto &path = dirEntry.path(); std::string extension = dirEntry.path().extension().string(); // TODO: Tidy up @@ -56,7 +61,7 @@ void AssetBrowserPanel::OnUserInterfaceUpdate() extension == ".scene" ? AssetType::Scene : - AssetType::None; + AssetType::None; // Extension not supported if (assetType == AssetType::None) @@ -71,7 +76,15 @@ void AssetBrowserPanel::OnUserInterfaceUpdate() { // Directory case AssetType::Directory: - if (ImGui::ImageButton(m_DirectoryTexture->GetTexture(), ImVec2(m_FileSize, m_FileSize), ImVec2 { 0.0f, 0.0f }, ImVec2 { 1.0f, 1.0f }, 0, ImVec4 { 0.0f, 0.0f, 0.0f, 0.0f }, ImVec4 { 1.0f, 1.0f, 1.0f, 1.0f })) + if (ImGui::ImageButton( + m_DirectoryTexture->GetTexture(), + ImVec2(m_FileSize, m_FileSize), + ImVec2 { 0.0f, 0.0f }, + ImVec2 { 1.0f, 1.0f }, + 0, + ImVec4 { 0.0f, 0.0f, 0.0f, 0.0f }, + ImVec4 { 1.0f, 1.0f, 1.0f, 1.0f } + )) { m_CurrentDirectory /= path.filename(); } @@ -79,7 +92,15 @@ void AssetBrowserPanel::OnUserInterfaceUpdate() // Scene case AssetType::Scene: - if (ImGui::ImageButton(m_SceneTexture->GetTexture(), ImVec2(m_FileSize, m_FileSize), ImVec2 { 0.0f, 0.0f }, ImVec2 { 1.0f, 1.0f }, 0, ImVec4 { 0.0f, 0.0f, 0.0f, 0.0f }, ImVec4 { 1.0f, 1.0f, 1.0f, 1.0f })) + if (ImGui::ImageButton( + m_SceneTexture->GetTexture(), + ImVec2(m_FileSize, m_FileSize), + ImVec2 { 0.0f, 0.0f }, + ImVec2 { 1.0f, 1.0f }, + 0, + ImVec4 { 0.0f, 0.0f, 0.0f, 0.0f }, + ImVec4 { 1.0f, 1.0f, 1.0f, 1.0f } + )) { SceneSerializer serializer(m_ActiveScene); LOG(info, "Attempting to deserialize: {}", path.string()); @@ -89,21 +110,36 @@ void AssetBrowserPanel::OnUserInterfaceUpdate() // Image case AssetType::Image: - if (ImGui::ImageButton(m_ImageTexture->GetTexture(), ImVec2(m_FileSize, m_FileSize), ImVec2 { 0.0f, 0.0f }, ImVec2 { 1.0f, 1.0f }, 0, ImVec4 { 0.0f, 0.0f, 0.0f, 0.0f }, ImVec4 { 1.0f, 1.0f, 1.0f, 1.0f })) + if (ImGui::ImageButton( + m_ImageTexture->GetTexture(), + ImVec2(m_FileSize, m_FileSize), + ImVec2 { 0.0f, 0.0f }, + ImVec2 { 1.0f, 1.0f }, + 0, + ImVec4 { 0.0f, 0.0f, 0.0f, 0.0f }, + ImVec4 { 1.0f, 1.0f, 1.0f, 1.0f } + )) { } break; // Text case AssetType::Text: - if (ImGui::ImageButton(m_TextTexture->GetTexture(), ImVec2(m_FileSize, m_FileSize), ImVec2 { 0.0f, 0.0f }, ImVec2 { 1.0f, 1.0f }, 0, ImVec4 { 0.0f, 0.0f, 0.0f, 0.0f }, ImVec4 { 1.0f, 1.0f, 1.0f, 1.0f })) + if (ImGui::ImageButton( + m_TextTexture->GetTexture(), + ImVec2(m_FileSize, m_FileSize), + ImVec2 { 0.0f, 0.0f }, + ImVec2 { 1.0f, 1.0f }, + 0, + ImVec4 { 0.0f, 0.0f, 0.0f, 0.0f }, + ImVec4 { 1.0f, 1.0f, 1.0f, 1.0f } + )) { } break; - default: - break; + default: break; } // Label ImGui::Text("%s", path.filename().c_str()); diff --git a/modules/mirror/src/panel/properties.cpp b/modules/mirror/src/panel/properties.cpp new file mode 100644 index 0000000..9125c6c --- /dev/null +++ b/modules/mirror/src/panel/properties.cpp @@ -0,0 +1,267 @@ +#include +#include +#include +#include +#include +#include +#include + +namespace Light { + +void PropertiesPanel::OnUserInterfaceUpdate() +{ + ImGui::Begin("Properties"); + + if (m_EntityContext.IsValid()) + { + if (m_EntityContext.HasComponent()) + { + auto &tagComponent = m_EntityContext.GetComponent(); + + char buffer[256]; + memset(buffer, 0, sizeof(buffer)); + std::strncpy(buffer, tagComponent.tag.c_str(), sizeof(buffer)); + + if (ImGui::InputText("##Tag", buffer, sizeof(buffer))) + tagComponent.tag = std::string(buffer); + } + + ImGui::SameLine(); + ImGui::PushItemWidth(-1); + + if (ImGui::Button("Add component")) + ImGui::OpenPopup("Components"); + + if (ImGui::BeginPopup("Components")) + { + if (ImGui::Selectable( + "SpriteRenderer", + false, + m_EntityContext.HasComponent() ? + ImGuiSelectableFlags_Disabled : + NULL + )) + m_EntityContext.AddComponent( + Light::ResourceManager::GetTexture("awesomeface") + ); + + if (ImGui::Selectable( + "Camera", + false, + m_EntityContext.HasComponent() ? + ImGuiSelectableFlags_Disabled : + NULL + )) + m_EntityContext.AddComponent(); + + ImGui::EndPopup(); + } + ImGui::PopItemWidth(); + + DrawComponent( + "Transform Component", + m_EntityContext, + [&](auto &transformComponent) { + DrawVec3Control("Translation", transformComponent.translation); + } + ); + + DrawComponent( + "SpriteRenderer Component", + m_EntityContext, + [&](auto &spriteRendererComponent) { + ImGui::ColorEdit4("Color", &spriteRendererComponent.tint[0]); + } + ); + + DrawComponent( + "Camera Component", + m_EntityContext, + [&](auto &cameraComponent) { + auto &camera = cameraComponent.camera; + + SceneCamera::ProjectionType projectionType = camera.GetProjectionType(); + const char *projectionTypesString[] = { "Orthographic", "Perspective" }; + + if (ImGui::BeginCombo("ProjectionType", projectionTypesString[(int)projectionType])) + { + for (int i = 0; i < 2; i++) + { + const bool isSelected = (int)projectionType == i; + if (ImGui::Selectable(projectionTypesString[i], isSelected)) + { + projectionType = (SceneCamera::ProjectionType)i; + camera.SetProjectionType(projectionType); + } + + if (isSelected) + ImGui::SetItemDefaultFocus(); + } + + ImGui::EndCombo(); + } + + if (projectionType == SceneCamera::ProjectionType::Orthographic) + { + float orthoSize, nearPlane, farPlane; + + orthoSize = camera.GetOrthographicSize(); + nearPlane = camera.GetOrthographicNearPlane(); + farPlane = camera.GetOrthographicFarPlane(); + + if (ImGui::DragFloat("Orthographic Size", &orthoSize)) + camera.SetOrthographicSize(orthoSize); + + if (ImGui::DragFloat("Near Plane", &nearPlane)) + camera.SetOrthographicNearPlane(nearPlane); + + if (ImGui::DragFloat("Far Plane", &farPlane)) + camera.SetOrthographicFarPlane(farPlane); + } + + else // perspective + { + float verticalFOV, nearPlane, farPlane; + + verticalFOV = glm::degrees(camera.GetPerspectiveVerticalFOV()); + nearPlane = camera.GetPerspectiveNearPlane(); + farPlane = camera.GetPerspectiveFarPlane(); + + if (ImGui::DragFloat("Vertical FOV", &verticalFOV)) + camera.SetPerspectiveVerticalFOV(glm::radians(verticalFOV)); + + if (ImGui::DragFloat("Near Plane", &nearPlane)) + camera.SetPerspectiveNearPlane(nearPlane); + + if (ImGui::DragFloat("Far Plane", &farPlane)) + camera.SetPerspectiveFarPlane(farPlane); + } + + ImGui::Separator(); + } + ); + } + + ImGui::End(); +} + +void PropertiesPanel::SetEntityContext(Entity entity) +{ + m_EntityContext = entity; +} + +void PropertiesPanel::DrawVec3Control( + const std::string &label, + glm::vec3 &values, + float resetValue /*= 0.0f*/, + float columnWidth /*= 100.0f*/ +) +{ + ImGuiIO &io = ImGui::GetIO(); + + auto boldFont = io.Fonts->Fonts[0]; + + ImGui::Columns(2); + ImGui::SetColumnWidth(0, columnWidth); + ImGui::Text(label.c_str()); + ImGui::NextColumn(); + + ImGui::PushMultiItemsWidths(3, ImGui::CalcItemWidth()); + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2 { 0, 0 }); + + float lineHeight = GImGui->Font->FontSize + GImGui->Style.FramePadding.y * 2.0f; + ImVec2 buttonSize = { lineHeight + 3.0f, lineHeight }; + + ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.8f, 0.1f, 0.15f, 1.0f)); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.9f, 0.2f, 0.2f, 1.0f)); + ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(0.8f, 0.1f, 0.15f, 1.0f)); + ImGui::PushFont(boldFont); + if (ImGui::Button("X", buttonSize)) + values.x = resetValue; + ImGui::PopFont(); + ImGui::PopStyleColor(3); + + ImGui::SameLine(); + ImGui::DragFloat("##X", &values.x, 0.1f); + ImGui::PopItemWidth(); + ImGui::SameLine(); + + ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.2f, 0.7f, 0.2f, 1.0f)); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.3f, 0.8f, 0.3f, 1.0f)); + ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(0.2f, 0.7f, 0.2f, 1.0f)); + ImGui::PushFont(boldFont); + if (ImGui::Button("Y", buttonSize)) + values.y = resetValue; + ImGui::PopFont(); + ImGui::PopStyleColor(3); + + ImGui::SameLine(); + ImGui::DragFloat("##Y", &values.y, 0.1f); + ImGui::PopItemWidth(); + ImGui::SameLine(); + + + ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.1f, 0.25f, 0.8f, 1.0f)); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.2f, 0.35f, 0.9f, 1.0f)); + ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(0.1f, 0.25f, 0.8f, 1.0f)); + ImGui::PushFont(boldFont); + if (ImGui::Button("Z", buttonSize)) + values.z = resetValue; + ImGui::PopFont(); + ImGui::PopStyleColor(3); + + ImGui::SameLine(); + ImGui::DragFloat("##Z", &values.z, 0.1f); + ImGui::PopItemWidth(); + + ImGui::PopStyleVar(); + ImGui::Columns(1); +} + + +template +void PropertiesPanel::DrawComponent( + const std::string &name, + Entity entity, + UIFunction userInterfaceFunction +) +{ + if (!entity.HasComponent()) + return; + + auto &component = entity.GetComponent(); + + ImVec2 regionAvail = ImGui::GetContentRegionAvail(); + + ImGuiTreeNodeFlags flags = ImGuiTreeNodeFlags_DefaultOpen | ImGuiTreeNodeFlags_SpanAvailWidth + | ImGuiTreeNodeFlags_Framed | ImGuiTreeNodeFlags_AllowItemOverlap + | ImGuiTreeNodeFlags_FramePadding; + + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, { 4, 4 }); + float lineHeight = GImGui->Font->FontSize + GImGui->Style.FramePadding.y * 2.0f; + ImGui::Separator(); + + if (ImGui::TreeNodeEx((void *)typeid(ComponentType).hash_code(), flags, name.c_str())) + { + ImGui::PopStyleVar(); + + ImGui::SameLine(regionAvail.x - lineHeight * .5f); + if (ImGui::Button("+", { lineHeight, lineHeight })) + ImGui::OpenPopup("ComponentSettings"); + + if (ImGui::BeginPopup("ComponentSettings")) + { + if (ImGui::Selectable("Remove component")) + entity.RemoveComponent(); + + ImGui::EndPopup(); + } + + userInterfaceFunction(component); + ImGui::TreePop(); + } + else + ImGui::PopStyleVar(); +} + +} // namespace Light diff --git a/Mirror/src/Panels/SceneHierarchyPanel.cpp b/modules/mirror/src/panel/scene_hierarchy.cpp similarity index 51% rename from Mirror/src/Panels/SceneHierarchyPanel.cpp rename to modules/mirror/src/panel/scene_hierarchy.cpp index 13a450d..404f559 100644 --- a/Mirror/src/Panels/SceneHierarchyPanel.cpp +++ b/modules/mirror/src/panel/scene_hierarchy.cpp @@ -1,20 +1,22 @@ -#include "SceneHierarchyPanel.hpp" - -#include "PropertiesPanel.hpp" -#include "Scene/Components.hpp" - +#include #include #include +#include +#include namespace Light { SceneHierarchyPanel::SceneHierarchyPanel() - : m_Context(nullptr), m_PropertiesPanelContext(nullptr), m_SelectionContext() + : m_Context(nullptr) + , m_PropertiesPanelContext(nullptr) + , m_SelectionContext() { } -SceneHierarchyPanel::SceneHierarchyPanel(Ref context, Ref propertiesPanel /* = nullptr */) - : m_Context(context), m_PropertiesPanelContext(propertiesPanel) +SceneHierarchyPanel:: + SceneHierarchyPanel(Ref context, Ref propertiesPanel /* = nullptr */) + : m_Context(context) + , m_PropertiesPanelContext(propertiesPanel) { } @@ -27,7 +29,7 @@ void SceneHierarchyPanel::OnUserInterfaceUpdate() for (auto entityID : m_Context->m_Registry.view()) { Entity entity(static_cast(entityID), m_Context.get()); - const std::string& tag = entity.GetComponent(); + const std::string &tag = entity.GetComponent(); DrawNode(entity, tag); }; @@ -36,7 +38,8 @@ void SceneHierarchyPanel::OnUserInterfaceUpdate() ImGui::End(); } -void SceneHierarchyPanel::SetContext(Ref context, Ref propertiesPanel /* = nullptr */) +void SceneHierarchyPanel:: + SetContext(Ref context, Ref propertiesPanel /* = nullptr */) { if (propertiesPanel) m_PropertiesPanelContext = propertiesPanel; @@ -44,13 +47,12 @@ void SceneHierarchyPanel::SetContext(Ref context, Ref pr m_Context = context; } -void SceneHierarchyPanel::DrawNode(Entity entity, const std::string& label) +void SceneHierarchyPanel::DrawNode(Entity entity, const std::string &label) { - ImGuiTreeNodeFlags flags = (m_SelectionContext == entity ? ImGuiTreeNodeFlags_Selected : NULL) | - ImGuiTreeNodeFlags_OpenOnArrow | - ImGuiTreeNodeFlags_SpanFullWidth; + ImGuiTreeNodeFlags flags = (m_SelectionContext == entity ? ImGuiTreeNodeFlags_Selected : NULL) + | ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_SpanFullWidth; - bool expanded = ImGui::TreeNodeEx((void*)(uint64_t)(uint32_t)(entity), flags, label.c_str()); + bool expanded = ImGui::TreeNodeEx((void *)(uint64_t)(uint32_t)(entity), flags, label.c_str()); if (ImGui::IsItemClicked()) { diff --git a/tools/cmake/macros.cmake b/tools/cmake/macros.cmake new file mode 100644 index 0000000..ab01d62 --- /dev/null +++ b/tools/cmake/macros.cmake @@ -0,0 +1,30 @@ +macro (add_library_module libname) + if ("${ARGN}" STREQUAL "") # Header only library + message("Adding INTERFACE library ${libname}") + add_library(${libname} INTERFACE) + target_include_directories(${libname} INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}/include) + + else () # Compiled library + set(source_files) + set(source_directory "${CMAKE_CURRENT_SOURCE_DIR}/src") + foreach (source_file ${ARGN}) + list(APPEND source_files "${source_directory}/${source_file}") + endforeach () + + message("Adding library ${libname} with source files: ${source_files}") + add_library(${libname} ${source_files}) + target_include_directories(${libname} PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include) + endif () +endmacro () + +macro (add_executable_module exename) + set(source_files) + set(source_directory "${CMAKE_CURRENT_SOURCE_DIR}/src") + foreach (source_file ${ARGN}) + list(APPEND source_files "${source_directory}/${source_file}") + endforeach () + + message("Adding executable ${exename} with source files: ${source_files}") + add_executable(${exename} ${source_files}) + target_include_directories(${exename} PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include) +endmacro ()