From b3b127a6ea2f9b2e08585e023ec4dee1d96abfaf Mon Sep 17 00:00:00 2001 From: Mag1str02 Date: Wed, 20 Nov 2024 13:32:11 +0300 Subject: [PATCH 01/15] Added windows build workflow --- .github/workflows/build.yml | 59 ++++++++++++++++++++++++++++--------- 1 file changed, 45 insertions(+), 14 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index cd5a7d2..16141f9 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -7,6 +7,41 @@ on: branches: [ "main" ] jobs: + BuildWindows: + runs-on: windows-latest + + strategy: + fail-fast: false + + matrix: + build_type: [RelWithDebInfo] + + steps: + - name: Checkout Repository + uses: actions/checkout@v4 + with: + submodules: 'true' + - name: Install clang + uses: msys2/setup-msys2@v2 + with: + location: D:\ + update: true + install: >- + mingw-w64-clang-x86_64-clang + mingw-w64-clang-x86_64-ninja + - name: Add msys to path + run: | + echo "D:\msys64\clang64\bin\" | Out-File -Append -FilePath $env:GITHUB_PATH -Encoding utf8 + - name: Build + uses: threeal/cmake-action@v2.0.0 + with: + source-dir: ${{ github.workspace }} + build-dir: ${{ github.workspace }}/build + generator: Ninja + cxx-compiler: clang++ + c-compiler: clang + build-args: --target DummyEditor --parallel 16 --config ${{ matrix.build_type }} + options: CMAKE_BUILD_TYPE=${{ matrix.build_type }} BuildUbuntu: runs-on: ubuntu-latest @@ -30,17 +65,13 @@ jobs: uses: actions/checkout@v4 with: submodules: 'true' - - name: Set reusable strings - id: strings - shell: bash - run: | - echo "build-output-dir=${{ github.workspace }}/build" >> "$GITHUB_OUTPUT" - - name: CMake Configure - run: > - cmake -B ${{ steps.strings.outputs.build-output-dir }} - -DCMAKE_CXX_COMPILER=${{ matrix.cpp_compiler }} - -DCMAKE_C_COMPILER=${{ matrix.c_compiler }} - -DCMAKE_BUILD_TYPE=${{ matrix.build_type }} - -S ${{ github.workspace }} - - name: Cmake Build - run: cmake --build ${{ steps.strings.outputs.build-output-dir }} --config ${{ matrix.build_type }} --target DummyEditor --parallel 16 + - name: Build + uses: threeal/cmake-action@v2.0.0 + with: + source-dir: ${{ github.workspace }} + build-dir: ${{ github.workspace }}/build + generator: Unix Makefiles + cxx-compiler: clang++ + c-compiler: clang + build-args: --target DummyEditor --parallel 16 --config ${{ matrix.build_type }} + options: CMAKE_BUILD_TYPE=${{ matrix.build_type }} \ No newline at end of file From 1a45548278959bc018cfd03dac41ba79f9135bea Mon Sep 17 00:00:00 2001 From: Mag1str02 Date: Wed, 20 Nov 2024 14:58:52 +0300 Subject: [PATCH 02/15] Fixed ubuntu workflow --- .github/workflows/build.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 16141f9..2f389a2 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -71,7 +71,7 @@ jobs: source-dir: ${{ github.workspace }} build-dir: ${{ github.workspace }}/build generator: Unix Makefiles - cxx-compiler: clang++ - c-compiler: clang + cxx-compiler: ${{ matrix.cpp_compiler }} + c-compiler: ${{ matrix.c_compiler }} build-args: --target DummyEditor --parallel 16 --config ${{ matrix.build_type }} options: CMAKE_BUILD_TYPE=${{ matrix.build_type }} \ No newline at end of file From d805ecfb8e71f7f89d27820bf428776978bf5075 Mon Sep 17 00:00:00 2001 From: Mag1str02 Date: Wed, 20 Nov 2024 15:00:57 +0300 Subject: [PATCH 03/15] Added linter workflow --- .clang-tidy | 45 ++++++++++++++++++ .github/workflows/code_style.yml | 27 ----------- .github/workflows/{build.yml => main.yml} | 57 +++++++++++++++++++---- CMake/Compiler.cmake | 7 ++- DummyEngine/Utils/Types/UUID.h | 1 - 5 files changed, 98 insertions(+), 39 deletions(-) create mode 100644 .clang-tidy delete mode 100644 .github/workflows/code_style.yml rename .github/workflows/{build.yml => main.yml} (53%) diff --git a/.clang-tidy b/.clang-tidy new file mode 100644 index 0000000..ff0413e --- /dev/null +++ b/.clang-tidy @@ -0,0 +1,45 @@ +--- + +Checks: '-*,cppcoreguidelines-avoid-goto,cppcoreguidelines-pro-type-const-cast, google-runtime-int, modernize-use-nullptr, readability-braces-around-statements, readability-container-size-empty, readability-redundant-control-flow, readability-identifier-naming, readability-simplify-boolean-expr, google-build-using-namespace, readability-implicit-bool-conversion, google-explicit-constructor' + +CheckOptions: + - key: readability-identifier-naming.NamespaceCase + value: lower_case + - key: readability-identifier-naming.ClassCase + value: CamelCase + - key: readability-identifier-naming.StructCase + value: CamelCase + - key: readability-identifier-naming.TypedefCase + value: CamelCase + - key: readability-identifier-naming.TypeAliasCase + value: CamelCase + - key: readability-identifier-naming.FunctionCase + value: CamelCase + - key: readability-identifier-naming.ParameterCase + value: lower_case + - key: readability-identifier-naming.VariableCase + value: lower_case + - key: readability-identifier-naming.PrivateMemberCase + value: lower_case + - key: readability-identifier-naming.PrivateMemberSuffix + value: '_' + - key: readability-identifier-naming.GlobalConstantCase + value: CamelCase + - key: readability-identifier-naming.GlobalConstantPrefix + value: k + - key: readability-identifier-naming.StaticConstantCase + value: CamelCase + - key: readability-identifier-naming.StaticConstantPrefix + value: k + - key: readability-identifier-naming.ConstexprVariableCase + value: CamelCase + - key: readability-identifier-naming.ConstexprVariablePrefix + value: k + - key: readability-identifier-naming.TypeTemplateParameterCase + value: CamelCase + - key: readability-simplify-boolean-expr.ChainedConditionalReturn + value: '1' + - key: readability-simplify-boolean-expr.ChainedConditionalAssignment + value: '1' + - key: readability-identifier-naming.TypeTemplateParameterIgnoredRegexp + value: expr-type \ No newline at end of file diff --git a/.github/workflows/code_style.yml b/.github/workflows/code_style.yml deleted file mode 100644 index 275dcce..0000000 --- a/.github/workflows/code_style.yml +++ /dev/null @@ -1,27 +0,0 @@ -name: Style Checks - -on: - push: - branches: [ "main" ] - pull_request: - branches: [ "main" ] - -jobs: - FormatCheck: - runs-on: ubuntu-latest - - strategy: - fail-fast: false - - steps: - - uses: actions/checkout@v4 - - name: Check DummyEngine Format - uses: jidicula/clang-format-action@v4.13.0 - with: - clang-format-version: '18' - check-path: 'DummyEngine' - - name: Check DummyEditor Format - uses: jidicula/clang-format-action@v4.13.0 - with: - clang-format-version: '18' - check-path: 'DummyEditor' diff --git a/.github/workflows/build.yml b/.github/workflows/main.yml similarity index 53% rename from .github/workflows/build.yml rename to .github/workflows/main.yml index 2f389a2..5720216 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/main.yml @@ -1,4 +1,4 @@ -name: Build Checks +name: Checks on: push: @@ -9,13 +9,11 @@ on: jobs: BuildWindows: runs-on: windows-latest - + name: Build Windows strategy: fail-fast: false - matrix: build_type: [RelWithDebInfo] - steps: - name: Checkout Repository uses: actions/checkout@v4 @@ -44,20 +42,18 @@ jobs: options: CMAKE_BUILD_TYPE=${{ matrix.build_type }} BuildUbuntu: runs-on: ubuntu-latest - + name: Build Ubuntu strategy: fail-fast: false - matrix: build_type: [RelWithDebInfo] c_compiler: [clang-19] cpp_compiler: [clang++-19] - steps: - name: Install Packages run: | sudo apt update - sudo apt install libwayland-dev libxkbcommon-dev libxrandr-dev libxinerama-dev libxcursor-dev libxi-dev libgtk-3-dev + sudo apt install libwayland-dev libxkbcommon-dev libxrandr-dev libxinerama-dev libxcursor-dev libxi-dev libgtk-3-dev ninja-build wget https://apt.llvm.org/llvm.sh chmod +x llvm.sh sudo ./llvm.sh 19 all @@ -70,8 +66,49 @@ jobs: with: source-dir: ${{ github.workspace }} build-dir: ${{ github.workspace }}/build - generator: Unix Makefiles + generator: Ninja cxx-compiler: ${{ matrix.cpp_compiler }} c-compiler: ${{ matrix.c_compiler }} build-args: --target DummyEditor --parallel 16 --config ${{ matrix.build_type }} - options: CMAKE_BUILD_TYPE=${{ matrix.build_type }} \ No newline at end of file + options: CMAKE_BUILD_TYPE=${{ matrix.build_type }} + Linter: + runs-on: ubuntu-latest + name: Clang Tidy + strategy: + fail-fast: false + steps: + - uses: actions/checkout@v4 + with: + submodules: 'true' + - name: Install Packages + run: | + sudo apt update + sudo apt install libwayland-dev libxkbcommon-dev libxrandr-dev libxinerama-dev libxcursor-dev libxi-dev libgtk-3-dev + wget https://apt.llvm.org/llvm.sh + chmod +x llvm.sh + sudo ./llvm.sh 19 all + - name: Configure Cmake + uses: threeal/cmake-action@v2.0.0 + with: + source-dir: ${{ github.workspace }} + build-dir: ${{ github.workspace }}/build + generator: Unix Makefiles + cxx-compiler: clang++-19 + c-compiler: clang-19 + options: CMAKE_BUILD_TYPE=RelWithDebInfo CMAKE_EXPORT_COMPILE_COMMANDS=ON FORCE_NO_PCH=ON + run-build: false + - uses: cpp-linter/cpp-linter-action@v2 + id: linter + with: + style: 'file' + tidy-checks: '' + verbosity: debug + version: 18 + files-changed-only: false + database: '${{ github.workspace }}/build' + repo-root: '${{ github.workspace }}' + ignore: '${{ github.workspace }}/build|${{ github.workspace }}/Examples|${{ github.workspace }}/Sandbox' + step-summary: true + - name: Check Linter Results + if: steps.linter.outputs.checks-failed > 0 + run: exit 1 \ No newline at end of file diff --git a/CMake/Compiler.cmake b/CMake/Compiler.cmake index 4fdb7a7..3c5263d 100644 --- a/CMake/Compiler.cmake +++ b/CMake/Compiler.cmake @@ -6,11 +6,16 @@ set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/../Sandbox) set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/../Sandbox) set(ENABLE_PRECOMPILED_HEADERS OFF) - if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -stdlib=libc++") set(ENABLE_PRECOMPILED_HEADERS ON) endif() +option(FORCE_NO_PCH "Prevent PCH" OFF) +if (${FORCE_NO_PCH}) + set(ENABLE_PRECOMPILED_HEADERS OFF) +endif() + +message(STATUS "Precompiled headers: ${ENABLE_PRECOMPILED_HEADERS}") function(add_warnings TARGET) target_compile_options(${TARGET} PUBLIC -Wall -Wextra -Wpedantic -Wno-extra-semi -Wno-missing-field-initializers -Werror) diff --git a/DummyEngine/Utils/Types/UUID.h b/DummyEngine/Utils/Types/UUID.h index 2670cde..9c271fc 100644 --- a/DummyEngine/Utils/Types/UUID.h +++ b/DummyEngine/Utils/Types/UUID.h @@ -9,7 +9,6 @@ namespace DE { static UUID Generate(); UUID() = default; - UUID(const UUID&) = default; UUID(const std::string& str); operator std::string() const; From ae29fb3f39069f8509dbbd40bef58c4e8c3e5b9d Mon Sep 17 00:00:00 2001 From: Mag1str02 Date: Wed, 20 Nov 2024 21:56:46 +0300 Subject: [PATCH 04/15] Added option to compile with clang tidy --- CMake/Compiler.cmake | 10 ++++++++-- DummyEngine/CMakeLists.txt | 3 +++ 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/CMake/Compiler.cmake b/CMake/Compiler.cmake index 3c5263d..b00b7bd 100644 --- a/CMake/Compiler.cmake +++ b/CMake/Compiler.cmake @@ -1,3 +1,6 @@ +option(ENABLE_CLANG_TIDY_ON_COMPILATION "Run clang tidy during compilation" OFF) +option(FORCE_NO_PCH "Prevent PCH" OFF) + set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIC -fno-omit-frame-pointer") @@ -10,16 +13,19 @@ if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -stdlib=libc++") set(ENABLE_PRECOMPILED_HEADERS ON) endif() -option(FORCE_NO_PCH "Prevent PCH" OFF) if (${FORCE_NO_PCH}) set(ENABLE_PRECOMPILED_HEADERS OFF) endif() +if(${ENABLE_CLANG_TIDY_ON_COMPILATION}) + find_program(CLANG_TIDY_EXE NAMES "clang-tidy" REQUIRED) + set(CLANG_TIDY_COMMAND "${CLANG_TIDY_EXE}" "-p" "${CMAKE_CURRENT_SOURCE_DIR}/build") +endif() + message(STATUS "Precompiled headers: ${ENABLE_PRECOMPILED_HEADERS}") function(add_warnings TARGET) target_compile_options(${TARGET} PUBLIC -Wall -Wextra -Wpedantic -Wno-extra-semi -Wno-missing-field-initializers -Werror) - if (${ENABLE_PRECOMPILED_HEADERS}) target_compile_options(${TARGET} PUBLIC -Winvalid-pch) endif() diff --git a/DummyEngine/CMakeLists.txt b/DummyEngine/CMakeLists.txt index 9c222ef..1070983 100644 --- a/DummyEngine/CMakeLists.txt +++ b/DummyEngine/CMakeLists.txt @@ -19,4 +19,7 @@ add_warnings(DummyEngineLib) if (${ENABLE_PRECOMPILED_HEADERS}) target_precompile_headers(DummyEngineLib PUBLIC ${ENGINE_PRECOMPILED_HEADERS}) +endif() +if (${ENABLE_CLANG_TIDY_ON_COMPILATION}) + set_target_properties(DummyEngineLib PROPERTIES CXX_CLANG_TIDY "${CLANG_TIDY_COMMAND}") endif() \ No newline at end of file From 2897bfde46548f1fe673499187b9d5e0c6a0c27d Mon Sep 17 00:00:00 2001 From: Mag1str0 Date: Wed, 20 Nov 2024 22:20:43 +0300 Subject: [PATCH 05/15] Added cmake options --- .github/workflows/main.yml | 6 +++--- .gitignore | 1 + CMake/All.cmake | 5 +++++ CMake/Compiler.cmake | 9 +++------ CMake/Options.cmake | 12 ++++++++++++ DummyEngine/CMakeLists.txt | 2 +- 6 files changed, 25 insertions(+), 10 deletions(-) create mode 100644 CMake/Options.cmake diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 5720216..12d99ae 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -95,19 +95,19 @@ jobs: generator: Unix Makefiles cxx-compiler: clang++-19 c-compiler: clang-19 - options: CMAKE_BUILD_TYPE=RelWithDebInfo CMAKE_EXPORT_COMPILE_COMMANDS=ON FORCE_NO_PCH=ON + options: CMAKE_BUILD_TYPE=RelWithDebInfo CMAKE_EXPORT_COMPILE_COMMANDS=ON DE_FORCE_NO_PCH=ON run-build: false - uses: cpp-linter/cpp-linter-action@v2 id: linter with: style: 'file' tidy-checks: '' - verbosity: debug + verbosity: info version: 18 files-changed-only: false database: '${{ github.workspace }}/build' repo-root: '${{ github.workspace }}' - ignore: '${{ github.workspace }}/build|${{ github.workspace }}/Examples|${{ github.workspace }}/Sandbox' + ignore: 'build/**|Examples/**|Sandbox/**' step-summary: true - name: Check Linter Results if: steps.linter.outputs.checks-failed > 0 diff --git a/.gitignore b/.gitignore index b3cdef6..673c034 100644 --- a/.gitignore +++ b/.gitignore @@ -20,3 +20,4 @@ Sandbox/**.dylib Sandbox/**.so** Sandbox/*.yml +Config.cmake \ No newline at end of file diff --git a/CMake/All.cmake b/CMake/All.cmake index de99d09..d481f8a 100644 --- a/CMake/All.cmake +++ b/CMake/All.cmake @@ -1,3 +1,8 @@ +if (EXISTS ${CMAKE_SOURCE_DIR}/Config.cmake) + include(Config.cmake) +endif() + +include(CMake/Options.cmake) include(CMake/Platform.cmake) include(CMake/Utils.cmake) include(CMake/Compiler.cmake) \ No newline at end of file diff --git a/CMake/Compiler.cmake b/CMake/Compiler.cmake index b00b7bd..fa79b28 100644 --- a/CMake/Compiler.cmake +++ b/CMake/Compiler.cmake @@ -1,6 +1,3 @@ -option(ENABLE_CLANG_TIDY_ON_COMPILATION "Run clang tidy during compilation" OFF) -option(FORCE_NO_PCH "Prevent PCH" OFF) - set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIC -fno-omit-frame-pointer") @@ -13,11 +10,11 @@ if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -stdlib=libc++") set(ENABLE_PRECOMPILED_HEADERS ON) endif() -if (${FORCE_NO_PCH}) +if (${DE_FORCE_NO_PCH}) set(ENABLE_PRECOMPILED_HEADERS OFF) endif() -if(${ENABLE_CLANG_TIDY_ON_COMPILATION}) - find_program(CLANG_TIDY_EXE NAMES "clang-tidy" REQUIRED) +if(${DE_ENABLE_CLANG_TIDY_ON_COMPILATION}) + find_program(CLANG_TIDY_EXE NAMES "clang-tidy" "clang-tidy-17" "clang-tidy-18" "clang-tidy-19" REQUIRED) set(CLANG_TIDY_COMMAND "${CLANG_TIDY_EXE}" "-p" "${CMAKE_CURRENT_SOURCE_DIR}/build") endif() diff --git a/CMake/Options.cmake b/CMake/Options.cmake new file mode 100644 index 0000000..c8626f7 --- /dev/null +++ b/CMake/Options.cmake @@ -0,0 +1,12 @@ +macro(set_option option help value) + option(${option} ${help} ${value}) + if(${option}) + message(STATUS "${option}: ON") + else() + message(STATUS "${option}: OFF") + endif() +endmacro() + +set_option(DE_ENABLE_CLANG_TIDY_ON_COMPILATION "Run clang tidy during compilation" OFF) +set_option(DE_FORCE_NO_PCH "Prevent PCH" OFF) + diff --git a/DummyEngine/CMakeLists.txt b/DummyEngine/CMakeLists.txt index 1070983..1458b0f 100644 --- a/DummyEngine/CMakeLists.txt +++ b/DummyEngine/CMakeLists.txt @@ -20,6 +20,6 @@ add_warnings(DummyEngineLib) if (${ENABLE_PRECOMPILED_HEADERS}) target_precompile_headers(DummyEngineLib PUBLIC ${ENGINE_PRECOMPILED_HEADERS}) endif() -if (${ENABLE_CLANG_TIDY_ON_COMPILATION}) +if (${DE_ENABLE_CLANG_TIDY_ON_COMPILATION}) set_target_properties(DummyEngineLib PROPERTIES CXX_CLANG_TIDY "${CLANG_TIDY_COMMAND}") endif() \ No newline at end of file From 8e5366499765e7c7a436d9b802b135018a9a0a1d Mon Sep 17 00:00:00 2001 From: Mag1str02 Date: Thu, 21 Nov 2024 11:03:38 +0300 Subject: [PATCH 06/15] Added clang tidy warnings as errors option --- CMake/Compiler.cmake | 4 ++++ CMake/Options.cmake | 1 + 2 files changed, 5 insertions(+) diff --git a/CMake/Compiler.cmake b/CMake/Compiler.cmake index fa79b28..3576c7a 100644 --- a/CMake/Compiler.cmake +++ b/CMake/Compiler.cmake @@ -16,6 +16,10 @@ endif() if(${DE_ENABLE_CLANG_TIDY_ON_COMPILATION}) find_program(CLANG_TIDY_EXE NAMES "clang-tidy" "clang-tidy-17" "clang-tidy-18" "clang-tidy-19" REQUIRED) set(CLANG_TIDY_COMMAND "${CLANG_TIDY_EXE}" "-p" "${CMAKE_CURRENT_SOURCE_DIR}/build") + message(STATUS "TIDY COMMAND: [${CLANG_TIDY_COMMAND}]") + if (${DE_CLANG_TIDY_WARNINGS_AS_ERRORS}) + set(CLANG_TIDY_COMMAND ${CLANG_TIDY_COMMAND} "--warnings-as-errors=*") + endif() endif() diff --git a/CMake/Options.cmake b/CMake/Options.cmake index c8626f7..9765784 100644 --- a/CMake/Options.cmake +++ b/CMake/Options.cmake @@ -8,5 +8,6 @@ macro(set_option option help value) endmacro() set_option(DE_ENABLE_CLANG_TIDY_ON_COMPILATION "Run clang tidy during compilation" OFF) +set_option(DE_CLANG_TIDY_WARNINGS_AS_ERRORS "Set clang warnings as errors" OFF) set_option(DE_FORCE_NO_PCH "Prevent PCH" OFF) From f5a94afabea54143a9cdddbd5366e319eb837bba Mon Sep 17 00:00:00 2001 From: Mag1str02 Date: Fri, 22 Nov 2024 00:38:01 +0300 Subject: [PATCH 07/15] MASSIVE STYLE CHANGES --- .clang-tidy | 16 +- DummyEditor/DummyEngineInclude.h | 8 - DummyEditor/Editor.cpp | 4 +- DummyEditor/EditorLayer.cpp | 272 +++++----- DummyEditor/EditorLayer.h | 70 +-- DummyEditor/ImGuiUtils/ImGuiManager.cpp | 36 +- DummyEditor/ImGuiUtils/ImGuiManager.h | 15 +- DummyEditor/ImGuiUtils/ImGuiPanel.cpp | 8 +- DummyEditor/ImGuiUtils/ImGuiPanel.h | 10 +- DummyEditor/ImGuiUtils/ImGuiUtils.cpp | 98 ++-- DummyEditor/ImGuiUtils/ImGuiUtils.h | 32 +- DummyEditor/Panels/InspectorPanel.cpp | 130 ++--- DummyEditor/Panels/InspectorPanel.h | 12 +- DummyEditor/Panels/MenuBar.cpp | 13 +- DummyEditor/Panels/MenuBar.h | 7 +- DummyEditor/Panels/ProfilerPanel.cpp | 21 +- DummyEditor/Panels/ProfilerPanel.h | 8 +- DummyEditor/Panels/RendererPanel.cpp | 44 +- DummyEditor/Panels/RendererPanel.h | 12 +- DummyEditor/Panels/SceneHierarchyPanel.cpp | 79 +-- DummyEditor/Panels/SceneHierarchyPanel.h | 20 +- DummyEditor/Panels/ThemePanel.cpp | 45 +- DummyEditor/Panels/ThemePanel.h | 10 +- DummyEditor/Panels/ViewportPanel.cpp | 22 +- DummyEditor/Panels/ViewportPanel.h | 14 +- .../Platform/Linux/Scripting/Compiler.cpp | 6 +- .../Platform/Macos/Scripting/Compiler.cpp | 4 +- .../Platform/Windows/Scripting/Compiler.cpp | 35 +- DummyEditor/Scripting/Compiler.cpp | 25 +- DummyEditor/Scripting/Compiler.h | 11 +- DummyEditor/Scripting/ScriptManager.cpp | 59 +-- DummyEditor/Scripting/ScriptManager.h | 28 +- .../Scripts/EditorCameraController.cpp | 12 +- DummyEngine/CMakeLists.txt | 4 + DummyEngine/Core/Animations/Animation.cpp | 16 +- DummyEngine/Core/Animations/Animation.h | 22 +- DummyEngine/Core/Animations/Animator.cpp | 46 +- DummyEngine/Core/Animations/Animator.h | 17 +- DummyEngine/Core/Animations/Bone.cpp | 74 ++- DummyEngine/Core/Animations/Bone.h | 39 +- DummyEngine/Core/Application/Application.cpp | 92 ++-- DummyEngine/Core/Application/Application.h | 27 +- DummyEngine/Core/Application/Config.cpp | 89 ++-- DummyEngine/Core/Application/Config.h | 93 ++-- DummyEngine/Core/Application/EntryPoint.h | 11 +- DummyEngine/Core/Application/Event.h | 92 ++-- DummyEngine/Core/Application/FileSystem.cpp | 32 +- DummyEngine/Core/Application/FileSystem.h | 7 +- DummyEngine/Core/Application/ImGuiLayer.cpp | 16 +- DummyEngine/Core/Application/ImGuiLayer.h | 4 +- DummyEngine/Core/Application/Initializer.cpp | 24 +- DummyEngine/Core/Application/Initializer.h | 10 +- DummyEngine/Core/Application/Input.cpp | 10 +- DummyEngine/Core/Application/Input.h | 9 +- DummyEngine/Core/Application/KeyCodes.h | 2 +- DummyEngine/Core/Application/Layer.h | 12 +- DummyEngine/Core/Application/Window.cpp | 131 +++-- DummyEngine/Core/Application/Window.h | 39 +- DummyEngine/Core/Console/Console.cpp | 103 ++-- DummyEngine/Core/Console/Console.hpp | 25 +- DummyEngine/Core/Console/ConsoleLayer.cpp | 68 ++- DummyEngine/Core/Console/ConsoleLayer.hpp | 20 +- DummyEngine/Core/ECS/ComponentArray.hpp | 38 +- DummyEngine/Core/ECS/ComponentManager.hpp | 78 +-- DummyEngine/Core/ECS/ECS.h | 94 ++-- DummyEngine/Core/ECS/Entity.hpp | 52 +- DummyEngine/Core/ECS/EntityManager.hpp | 40 +- DummyEngine/Core/ECS/Storage.hpp | 52 +- DummyEngine/Core/ECS/StorageView.hpp | 34 +- DummyEngine/Core/ECS/System.hpp | 8 +- DummyEngine/Core/ECS/SystemManager.hpp | 18 +- .../Core/Objects/Cameras/FPSCamera.cpp | 106 ++-- DummyEngine/Core/Objects/Cameras/FPSCamera.h | 29 +- .../Core/Objects/LightSources/LightSource.cpp | 5 +- .../Core/Objects/LightSources/LightSource.h | 25 +- DummyEngine/Core/Physics/ConvexCollider.cpp | 387 +++++++------- DummyEngine/Core/Physics/ConvexCollider.hpp | 28 +- DummyEngine/Core/Physics/ForceQueue.cpp | 25 - DummyEngine/Core/Physics/ForceQueue.hpp | 26 - DummyEngine/Core/Physics/PhysicsComponent.h | 26 +- DummyEngine/Core/Physics/SceneConstants.cpp | 8 - DummyEngine/Core/Physics/SceneConstants.hpp | 15 - DummyEngine/Core/Physics/Solver.cpp | 419 +++++++-------- DummyEngine/Core/Physics/Solver.hpp | 53 +- DummyEngine/Core/Physics/Utils.cpp | 26 +- DummyEngine/Core/Physics/Utils.hpp | 18 +- .../Core/Rendering/Renderer/BufferLayout.cpp | 60 +-- .../Core/Rendering/Renderer/BufferLayout.h | 36 +- .../Core/Rendering/Renderer/Context.cpp | 10 +- DummyEngine/Core/Rendering/Renderer/Context.h | 6 +- .../Core/Rendering/Renderer/CubeMap.cpp | 8 +- DummyEngine/Core/Rendering/Renderer/CubeMap.h | 7 +- .../Core/Rendering/Renderer/FrameBuffer.cpp | 8 +- .../Core/Rendering/Renderer/FrameBuffer.h | 13 +- .../Core/Rendering/Renderer/LocalBuffer.cpp | 41 +- .../Core/Rendering/Renderer/LocalBuffer.h | 19 +- .../Core/Rendering/Renderer/RenderAPI.h | 5 +- .../Core/Rendering/Renderer/RenderStructs.cpp | 112 +++-- .../Core/Rendering/Renderer/RenderStructs.h | 53 +- .../Core/Rendering/Renderer/Renderer.cpp | 235 ++++----- .../Core/Rendering/Renderer/Renderer.h | 75 +-- .../Core/Rendering/Renderer/Shader.cpp | 7 +- DummyEngine/Core/Rendering/Renderer/Shader.h | 6 +- .../Core/Rendering/Renderer/SkyBox.cpp | 69 +-- DummyEngine/Core/Rendering/Renderer/SkyBox.h | 25 +- .../Core/Rendering/Renderer/Texture.cpp | 8 +- DummyEngine/Core/Rendering/Renderer/Texture.h | 7 +- .../Core/Rendering/Renderer/UniformBuffer.cpp | 8 +- .../Core/Rendering/Renderer/UniformBuffer.h | 8 +- .../Core/Rendering/Renderer/VertexArray.cpp | 6 +- .../Core/Rendering/Renderer/VertexArray.h | 11 +- .../Core/Rendering/Renderer/VertexBuffer.cpp | 8 +- .../Core/Rendering/Renderer/VertexBuffer.h | 8 +- .../Rendering/RendererOpenGL/GLContext.cpp | 13 +- .../Core/Rendering/RendererOpenGL/GLContext.h | 11 +- .../Rendering/RendererOpenGL/GLCubeMap.cpp | 22 +- .../Core/Rendering/RendererOpenGL/GLCubeMap.h | 14 +- .../Core/Rendering/RendererOpenGL/GLDebug.cpp | 19 +- .../Core/Rendering/RendererOpenGL/GLDebug.h | 10 +- .../RendererOpenGL/GLFrameBuffer.cpp | 83 +-- .../Rendering/RendererOpenGL/GLFrameBuffer.h | 19 +- .../Rendering/RendererOpenGL/GLRenderAPI.cpp | 15 +- .../Rendering/RendererOpenGL/GLRenderAPI.h | 6 +- .../Rendering/RendererOpenGL/GLShader.cpp | 81 +-- .../Core/Rendering/RendererOpenGL/GLShader.h | 15 +- .../Rendering/RendererOpenGL/GLTexture.cpp | 89 ++-- .../Core/Rendering/RendererOpenGL/GLTexture.h | 62 +-- .../RendererOpenGL/GLUniformBuffer.cpp | 35 +- .../RendererOpenGL/GLUniformBuffer.h | 24 +- .../Core/Rendering/RendererOpenGL/GLUtils.cpp | 9 +- .../Core/Rendering/RendererOpenGL/GLUtils.h | 12 +- .../RendererOpenGL/GLVertexArray.cpp | 60 +-- .../Rendering/RendererOpenGL/GLVertexArray.h | 18 +- .../RendererOpenGL/GLVertexBuffer.cpp | 83 +-- .../Rendering/RendererOpenGL/GLVertexBuffer.h | 25 +- .../Core/ResourceManaging/AssetManager.cpp | 69 +-- .../Core/ResourceManaging/AssetManager.h | 19 +- DummyEngine/Core/ResourceManaging/Assets.h | 45 +- .../Core/ResourceManaging/HandleManager.h | 174 ------- DummyEngine/Core/ResourceManaging/RawData.cpp | 51 +- DummyEngine/Core/ResourceManaging/RawData.h | 97 ++-- .../Core/ResourceManaging/ResourceManager.cpp | 100 ++-- .../Core/ResourceManaging/ResourceManager.h | 20 +- DummyEngine/Core/Scene/Components.cpp | 17 +- DummyEngine/Core/Scene/Components.h | 73 +-- DummyEngine/Core/Scene/Scene.cpp | 138 ++--- DummyEngine/Core/Scene/Scene.h | 31 +- DummyEngine/Core/Scene/SceneHierarchy.cpp | 148 +++--- DummyEngine/Core/Scene/SceneHierarchy.h | 63 ++- DummyEngine/Core/Scene/SceneRenderer.cpp | 241 ++++----- DummyEngine/Core/Scene/SceneRenderer.h | 78 +-- DummyEngine/Core/Scripting/Script.cpp | 22 +- DummyEngine/Core/Scripting/Script.h | 44 +- DummyEngine/Core/Scripting/ScriptClass.cpp | 22 +- DummyEngine/Core/Scripting/ScriptClass.h | 19 +- DummyEngine/Core/Scripting/ScriptEngine.cpp | 247 +++++---- DummyEngine/Core/Scripting/ScriptEngine.h | 41 +- DummyEngine/Core/Scripting/SharedObject.h | 10 +- DummyEngine/DummyEngine.h | 45 +- .../Linux/Core/Scripting/SharedObject.cpp | 13 +- .../Platform/Linux/Utils/Debug/Demangler.cpp | 6 +- .../Platform/Linux/Utils/Debug/Demangler.h | 7 +- .../Platform/Linux/Utils/Debug/StackTrace.cpp | 9 +- .../Macos/Core/Scripting/SharedObject.cpp | 8 +- .../Platform/Macos/Utils/Debug/Demangler.cpp | 4 +- .../Platform/Macos/Utils/Debug/Demangler.h | 4 +- .../Platform/Macos/Utils/Debug/StackTrace.cpp | 4 +- .../Windows/Core/Scripting/SharedObject.cpp | 67 +-- .../Windows/Utils/Debug/Demangler.cpp | 8 +- .../Platform/Windows/Utils/Debug/Demangler.h | 7 +- .../Windows/Utils/Debug/StackTrace.cpp | 108 +--- DummyEngine/Sources.cmake | 4 +- DummyEngine/ToolBox/Editors/TextureEditor.cpp | 6 +- DummyEngine/ToolBox/Editors/TextureEditor.h | 8 +- DummyEngine/ToolBox/Loaders/ModelLoader.cpp | 220 ++++---- DummyEngine/ToolBox/Loaders/ModelLoader.h | 46 +- DummyEngine/ToolBox/Loaders/SceneLoader.cpp | 475 +++++++++--------- DummyEngine/ToolBox/Loaders/SceneLoader.h | 26 +- DummyEngine/ToolBox/Loaders/TextureLoader.cpp | 40 +- DummyEngine/ToolBox/Loaders/TextureLoader.h | 11 +- DummyEngine/Utils/Base.h | 18 - DummyEngine/Utils/Base/Constants.h | 12 - DummyEngine/Utils/Base/GLMIncludes.h | 9 - DummyEngine/Utils/Base/STDIncludes.h | 29 -- DummyEngine/Utils/DS/Trie.cpp | 51 +- DummyEngine/Utils/DS/Trie.hpp | 18 +- DummyEngine/Utils/Debug/Assert.cpp | 14 +- DummyEngine/Utils/Debug/Assert.h | 20 +- DummyEngine/Utils/Debug/Demangler.h | 2 +- DummyEngine/Utils/Debug/Logger.cpp | 97 ++-- DummyEngine/Utils/Debug/Logger.h | 85 ++-- DummyEngine/Utils/Debug/Profiler.cpp | 41 +- DummyEngine/Utils/Debug/Profiler.h | 37 +- DummyEngine/Utils/Debug/StackTrace.h | 6 +- .../{Base => Helpers}/CompilerSpecific.h | 10 +- DummyEngine/Utils/Helpers/Conversions.cpp | 8 +- DummyEngine/Utils/Helpers/Conversions.h | 9 +- DummyEngine/Utils/Helpers/Random.cpp | 13 +- DummyEngine/Utils/Helpers/Random.h | 6 +- DummyEngine/Utils/Helpers/STDAdapters.h | 27 + DummyEngine/Utils/Helpers/Singleton.h | 76 +-- .../Utils/Helpers/StringOperations.cpp | 9 +- DummyEngine/Utils/Helpers/StringOperations.h | 8 +- DummyEngine/Utils/Helpers/Timer.cpp | 18 +- DummyEngine/Utils/Helpers/Timer.h | 10 +- DummyEngine/Utils/PCH/GLMIncludes.h | 9 + DummyEngine/Utils/PCH/PCH.h | 22 + DummyEngine/Utils/PCH/STDIncludes.h | 29 ++ DummyEngine/Utils/ScriptIncludes.h | 12 - DummyEngine/Utils/Types/Constants.h | 10 + DummyEngine/Utils/Types/STDAdapters.h | 25 - DummyEngine/Utils/Types/Types.cpp | 14 +- DummyEngine/Utils/Types/Types.h | 23 +- DummyEngine/Utils/Types/UUID.cpp | 34 +- DummyEngine/Utils/Types/UUID.h | 22 +- Examples/EmptyApplication.cpp | 8 +- Examples/Test.cpp | 2 +- .../Scripts/BasicScripts/SquareMovement.cpp | 32 +- .../Assets/Scripts/Gate/GateController.cpp | 52 +- Sandbox/Assets/Scripts/Gate/SinMovement.cpp | 22 +- Sandbox/Assets/Scripts/Grass/Grass.cpp | 40 +- Sandbox/Assets/Scripts/Sky/SkyController.cpp | 22 +- Sandbox/Assets/Scripts/SphereSpawner.cpp | 17 - 223 files changed, 4640 insertions(+), 4797 deletions(-) delete mode 100644 DummyEditor/DummyEngineInclude.h delete mode 100644 DummyEngine/Core/Physics/ForceQueue.cpp delete mode 100644 DummyEngine/Core/Physics/ForceQueue.hpp delete mode 100644 DummyEngine/Core/Physics/SceneConstants.cpp delete mode 100644 DummyEngine/Core/Physics/SceneConstants.hpp delete mode 100644 DummyEngine/Core/ResourceManaging/HandleManager.h delete mode 100644 DummyEngine/Utils/Base.h delete mode 100644 DummyEngine/Utils/Base/Constants.h delete mode 100644 DummyEngine/Utils/Base/GLMIncludes.h delete mode 100644 DummyEngine/Utils/Base/STDIncludes.h rename DummyEngine/Utils/{Base => Helpers}/CompilerSpecific.h (78%) create mode 100644 DummyEngine/Utils/Helpers/STDAdapters.h create mode 100644 DummyEngine/Utils/PCH/GLMIncludes.h create mode 100644 DummyEngine/Utils/PCH/PCH.h create mode 100644 DummyEngine/Utils/PCH/STDIncludes.h delete mode 100644 DummyEngine/Utils/ScriptIncludes.h create mode 100644 DummyEngine/Utils/Types/Constants.h delete mode 100644 DummyEngine/Utils/Types/STDAdapters.h delete mode 100644 Sandbox/Assets/Scripts/SphereSpawner.cpp diff --git a/.clang-tidy b/.clang-tidy index ff0413e..2471391 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -1,10 +1,10 @@ --- -Checks: '-*,cppcoreguidelines-avoid-goto,cppcoreguidelines-pro-type-const-cast, google-runtime-int, modernize-use-nullptr, readability-braces-around-statements, readability-container-size-empty, readability-redundant-control-flow, readability-identifier-naming, readability-simplify-boolean-expr, google-build-using-namespace, readability-implicit-bool-conversion, google-explicit-constructor' +Checks: '-*,cppcoreguidelines-avoid-goto,cppcoreguidelines-pro-type-const-cast, google-runtime-int, modernize-use-nullptr, readability-container-size-empty, readability-redundant-control-flow, readability-identifier-naming, readability-implicit-bool-conversion, google-explicit-constructor' CheckOptions: - key: readability-identifier-naming.NamespaceCase - value: lower_case + value: CamelCase - key: readability-identifier-naming.ClassCase value: CamelCase - key: readability-identifier-naming.StructCase @@ -42,4 +42,14 @@ CheckOptions: - key: readability-simplify-boolean-expr.ChainedConditionalAssignment value: '1' - key: readability-identifier-naming.TypeTemplateParameterIgnoredRegexp - value: expr-type \ No newline at end of file + value: expr-type + - key: readability-identifier-naming.StaticVariableCase + value: CamelCase + - key: readability-identifier-naming.StaticVariablePrefix + value: 's' + - key: readability-identifier-naming.GlobalVariableCase + value: CamelCase + - key: readability-identifier-naming.GlobalVariablePrefix + value: 'g' + - key: readability-identifier-naming.PublicMemberCase + value: CamelCase \ No newline at end of file diff --git a/DummyEditor/DummyEngineInclude.h b/DummyEditor/DummyEngineInclude.h deleted file mode 100644 index 24e4ed7..0000000 --- a/DummyEditor/DummyEngineInclude.h +++ /dev/null @@ -1,8 +0,0 @@ -#pragma once - -#include -#include -#include -#include - -#include "DummyEngine/DummyEngine.h" diff --git a/DummyEditor/Editor.cpp b/DummyEditor/Editor.cpp index d6f8098..f2ba30c 100644 --- a/DummyEditor/Editor.cpp +++ b/DummyEditor/Editor.cpp @@ -1,8 +1,8 @@ #include "DummyEditor/EditorLayer.h" #include "DummyEngine/Core/Application/EntryPoint.h" -namespace DE { +namespace DummyEngine { void SetupApplication() { Application::PushLayer(new EditorLayer()); } -} // namespace DE +} // namespace DummyEngine diff --git a/DummyEditor/EditorLayer.cpp b/DummyEditor/EditorLayer.cpp index 6b37068..d8d5d23 100644 --- a/DummyEditor/EditorLayer.cpp +++ b/DummyEditor/EditorLayer.cpp @@ -2,9 +2,17 @@ #include "DummyEditor/Scripting/Compiler.h" #include "DummyEditor/Scripting/ScriptManager.h" +#include "DummyEngine/Core/Application/Config.h" +#include "DummyEngine/Core/Application/FileSystem.h" +#include "DummyEngine/Core/Application/Input.h" #include "DummyEngine/Core/Console/Console.hpp" +#include "DummyEngine/Core/Objects/LightSources/LightSource.h" +#include "DummyEngine/Core/ResourceManaging/AssetManager.h" +#include "DummyEngine/Core/ResourceManaging/ResourceManager.h" +#include "DummyEngine/Core/Scene/Components.h" +#include "DummyEngine/ToolBox/Loaders/TextureLoader.h" -namespace DE { +namespace DummyEngine { //*___Layer________________________________________________________________________________________________________________________________________________________________________________________ @@ -12,17 +20,17 @@ namespace DE { Compiler::Initialize(); ScriptManager::Initialize(); - m_ImGuiManager.LoadEditorResources(); - m_ImGuiManager.AddPanel(&m_Viewport); - m_ImGuiManager.AddPanel(&m_FBOViewport); - m_ImGuiManager.AddPanel(&m_SceneHierarchy); - m_ImGuiManager.AddPanel(&m_Inspector); - m_ImGuiManager.AddPanel(&m_Profiler); - m_ImGuiManager.AddPanel(&m_ThemePanel); - m_ImGuiManager.AddPanel(&m_RendererPanel); - m_ImGuiManager.SetMenuBar(&m_MenuBar); + imgui_manager_.LoadEditorResources(); + imgui_manager_.AddPanel(&viewport_); + imgui_manager_.AddPanel(&shadow_viewport_); + imgui_manager_.AddPanel(&scene_hierarchy_); + imgui_manager_.AddPanel(&inspector_); + imgui_manager_.AddPanel(&profiler_); + imgui_manager_.AddPanel(&theme_panel_); + imgui_manager_.AddPanel(&renderer_panel_); + imgui_manager_.SetMenuBar(&menu_bar_); - m_TSSystem = CreateRef(); + ts_system_ = CreateRef(); LoadIcons(); } void EditorLayer::OnUpdate(float dt) { @@ -31,30 +39,30 @@ namespace DE { ProcessControlls(dt); if (Console::GetBool("r_shadowmap_fbo")) { - m_FBOViewport.SetFrameBuffer(m_CurrentScene->GetRenderer()->GetShadowMap()); - m_FBOViewport.UseDepthAttachment(true); + shadow_viewport_.SetFrameBuffer(current_scene_->GetRenderer()->GetShadowMap()); + shadow_viewport_.UseDepthAttachment(true); } - switch (m_SceneState) { + switch (scene_state_) { case SceneState::Running: { - Entity camera = (m_CurrentScene->HasCamera() ? Entity() : m_EditorCamera); - m_CurrentScene->OnUpdate(dt); - m_CurrentScene->OnViewPortResize(m_Viewport.GetWidth(), m_Viewport.GetHeight()); - m_CurrentScene->OnRender(camera); + Entity camera = (current_scene_->HasCamera() ? Entity() : editor_camera_); + current_scene_->OnUpdate(dt); + current_scene_->OnViewPortResize(viewport_.GetWidth(), viewport_.GetHeight()); + current_scene_->OnRender(camera); break; } case SceneState::Step: - m_CurrentScene->OnUpdate(dt); - m_CurrentScene->OnViewPortResize(m_Viewport.GetWidth(), m_Viewport.GetHeight()); - m_CurrentScene->OnRender(m_EditorCamera); - m_SceneState = SceneState::Paused; + current_scene_->OnUpdate(dt); + current_scene_->OnViewPortResize(viewport_.GetWidth(), viewport_.GetHeight()); + current_scene_->OnRender(editor_camera_); + scene_state_ = SceneState::Paused; break; case SceneState::Paused: case SceneState::Editing: - m_TSSystem->Update(dt); - m_EditorCamera.Get()->OnUpdate(dt); - m_CurrentScene->OnViewPortResize(m_Viewport.GetWidth(), m_Viewport.GetHeight()); - m_CurrentScene->OnRender(m_EditorCamera); + ts_system_->Update(dt); + editor_camera_.Get()->OnUpdate(dt); + current_scene_->OnViewPortResize(viewport_.GetWidth(), viewport_.GetHeight()); + current_scene_->OnRender(editor_camera_); break; case SceneState::None: break; default: DE_ASSERT(false, "Unsupported SceneState"); break; @@ -63,11 +71,11 @@ namespace DE { void EditorLayer::OnImGuiRender() { DE_PROFILE_SCOPE("EditorLayer OnImGuiRender"); - if (m_CurrentScene) { - m_Inspector.SetActiveEntity(m_SceneHierarchy.GetActiveEntity()); + if (current_scene_) { + inspector_.SetActiveEntity(scene_hierarchy_.GetActiveEntity()); } - m_ImGuiManager.OnImGui(); + imgui_manager_.OnImGui(); // ImGui::ShowDemoWindow(); // ImGui::Begin("Cal"); // ImGui::ShowStyleEditor(); @@ -75,7 +83,7 @@ namespace DE { // ImGui::ShowStackToolWindow(); } void EditorLayer::OnDetach() { - if (m_CurrentScene) { + if (current_scene_) { CloseScene(); } @@ -88,19 +96,19 @@ namespace DE { void EditorLayer::ActionOpenScene() { Path p = OpenSceneDialog(); if (!p.empty()) { - if (m_CurrentScene) { + if (current_scene_) { CloseScene(); } OpenScene(p); } } void EditorLayer::ActionCloseScene() { - if (m_CurrentScene) { + if (current_scene_) { CloseScene(); } } void EditorLayer::ActionSaveScene() { - if (m_CurrentScene) { + if (current_scene_) { Path p = SaveSceneDialog(); if (!p.empty()) { SaveScene(p); @@ -108,198 +116,198 @@ namespace DE { } } void EditorLayer::ActionCreateScene() { - if (m_CurrentScene) { + if (current_scene_) { CloseScene(); } OpenScene(Path()); } void EditorLayer::ActionBuild() { - if (m_CurrentScene) { + if (current_scene_) { ReloadScripts(); } } void EditorLayer::ActionBuildAndRun() { - if (m_CurrentScene) { + if (current_scene_) { ReloadScripts(); - if (m_SceneScriptState == SceneScriptState::Compiled) { + if (scene_script_state_ == SceneScriptState::Compiled) { RunScene(); } } } void EditorLayer::ActionRunScene() { - if (m_CurrentScene && m_SceneScriptState != SceneScriptState::Uncompiled) { + if (current_scene_ && scene_script_state_ != SceneScriptState::Uncompiled) { RunScene(); } } void EditorLayer::ActionStopScene() { - if (m_CurrentScene) { + if (current_scene_) { StopScene(); } } void EditorLayer::ActionPauseScene() { - if (m_CurrentScene && m_SceneState == SceneState::Running) { - m_SceneState = SceneState::Paused; - m_CurrentScene->OnRuntimePause(); + if (current_scene_ && scene_state_ == SceneState::Running) { + scene_state_ = SceneState::Paused; + current_scene_->OnRuntimePause(); } } void EditorLayer::ActionResumeScene() { - if (m_CurrentScene && m_SceneState == SceneState::Paused) { - m_SceneState = SceneState::Running; - m_CurrentScene->OnRuntimeResume(); + if (current_scene_ && scene_state_ == SceneState::Paused) { + scene_state_ = SceneState::Running; + current_scene_->OnRuntimeResume(); } } void EditorLayer::ActionStepScene() { - if (m_CurrentScene && m_SceneState == SceneState::Paused) { - m_SceneState = SceneState::Step; + if (current_scene_ && scene_state_ == SceneState::Paused) { + scene_state_ = SceneState::Step; } } //*___Editor_______________________________________________________________________________________________________________________________________________________________________________________ - EditorLayer::EditorLayer() : Layer("EditorLayer"), m_FBOViewport("fbo_viewport") { - DE_ASSERT(s_Instance == nullptr, "Editor layer already created"); - s_Instance = this; + EditorLayer::EditorLayer() : Layer("EditorLayer"), shadow_viewport_("fbo_viewport") { + DE_ASSERT(gInstance == nullptr, "Editor layer already created"); + gInstance = this; } EditorLayer::~EditorLayer() { - s_Instance = nullptr; + gInstance = nullptr; } EditorLayer& EditorLayer::Get() { - return *s_Instance; + return *gInstance; } ImGuiManager& EditorLayer::GetImGuiManager() { - return m_ImGuiManager; + return imgui_manager_; } EditorLayer::SceneScriptState EditorLayer::GetSceneScriptState() const { - return m_SceneScriptState; + return scene_script_state_; } EditorLayer::SceneState EditorLayer::GetSceneState() const { - return m_SceneState; + return scene_state_; } EditorLayer::InputState EditorLayer::GetInputState() const { - return m_InputState; + return input_state_; } EditorLayer::Resources& EditorLayer::GetResources() { - return m_Resources; + return resources_; } Ref EditorLayer::GetScene() const { - return m_CurrentScene; + return current_scene_; } //*___Helpers______________________________________________________________________________________________________________________________________________________________________________________ void EditorLayer::ReloadScripts() { - auto res = ScriptManager::ReloadScripts(m_SceneFileData.assets.scripts, m_CurrentScene); - if (m_SceneScriptState == SceneScriptState::Uncompiled) { + auto res = ScriptManager::ReloadScripts(scene_file_data_.Assets.Scripts, current_scene_); + if (scene_script_state_ == SceneScriptState::Uncompiled) { if (res) { - m_SceneScriptState = SceneScriptState::Compiled; + scene_script_state_ = SceneScriptState::Compiled; } } - if (m_SceneScriptState == SceneScriptState::Compiled || m_SceneScriptState == SceneScriptState::OldCompiled) { + if (scene_script_state_ == SceneScriptState::Compiled || scene_script_state_ == SceneScriptState::OldCompiled) { if (res) { - m_SceneScriptState = SceneScriptState::Compiled; + scene_script_state_ = SceneScriptState::Compiled; } else { - m_SceneScriptState = SceneScriptState::OldCompiled; + scene_script_state_ = SceneScriptState::OldCompiled; } } } Path EditorLayer::OpenSceneDialog() { - return FileSystem::OpenFileDialog("Dummy Engine Scene (*.yml)", "yml", Config::GetPath(DE_CFG_SCENE_PATH)); + return FileSystem::OpenFileDialog("Dummy Engine Scene (*.yml)", "yml", Config::Get().ScenePath); } Path EditorLayer::SaveSceneDialog() { - return FileSystem::SaveFileDialog("Dummy Engine Scene (*.yml)", "yml", "", Config::GetPath(DE_CFG_SCENE_PATH)); + return FileSystem::SaveFileDialog("Dummy Engine Scene (*.yml)", "yml", "", Config::Get().ScenePath); } void EditorLayer::OpenScene(const Path& scene_path) { if (scene_path.empty()) { - m_SceneFileData = SceneFileData(); - m_CurrentScene = CreateRef(); + scene_file_data_ = SceneFileData(); + current_scene_ = CreateRef(); } else { auto res = SceneLoader::LoadScene(scene_path); if (!res) { return; } - m_SceneFileData = res.value(); + scene_file_data_ = res.value(); LoadAssets(); - if (!ScriptManager::LoadScripts(m_SceneFileData.assets.scripts)) { + if (!ScriptManager::LoadScripts(scene_file_data_.Assets.Scripts)) { return; } - m_CurrentScene = SceneLoader::Serialize(m_SceneFileData.hierarchy); - if (m_CurrentScene == nullptr) { + current_scene_ = SceneLoader::Serialize(scene_file_data_.Hierarchy); + if (current_scene_ == nullptr) { return; } - m_CurrentScene->GetRenderer()->settings = m_SceneFileData.settings; + current_scene_->GetRenderer()->Settings = scene_file_data_.Settings; } PrepareScene(); - ScriptManager::AttachScripts(m_CurrentScene); - m_Viewport.SetFrameBuffer(m_CurrentScene->GetRenderer()->GetFrameBuffer()); - m_SceneState = SceneState::Editing; - m_SceneScriptState = SceneScriptState::Compiled; - m_CurrentScene->LoadPhysics(m_CurrentScene); + ScriptManager::AttachScripts(current_scene_); + viewport_.SetFrameBuffer(current_scene_->GetRenderer()->GetFrameBuffer()); + scene_state_ = SceneState::Editing; + scene_script_state_ = SceneScriptState::Compiled; + current_scene_->LoadPhysics(current_scene_); LOG_INFO("Opened scene"); } void EditorLayer::SaveScene(const Path& path) { - m_SceneFileData.hierarchy = SceneLoader::Deserialize(m_CurrentScene); - m_SceneFileData.settings = m_CurrentScene->GetRenderer()->settings; - SceneLoader::SaveScene(m_SceneFileData, path); + scene_file_data_.Hierarchy = SceneLoader::Deserialize(current_scene_); + scene_file_data_.Settings = current_scene_->GetRenderer()->Settings; + SceneLoader::SaveScene(scene_file_data_, path); } void EditorLayer::CloseScene() { - m_Inspector.SetActiveEntity(Entity()); - m_CurrentScene = nullptr; - m_SceneState = SceneState::None; - m_SceneScriptState = SceneScriptState::Uncompiled; + inspector_.SetActiveEntity(Entity()); + current_scene_ = nullptr; + scene_state_ = SceneState::None; + scene_script_state_ = SceneScriptState::Uncompiled; ResourceManager::Clear(); - ScriptManager::UnloadScripts(m_SceneFileData.assets.scripts); + ScriptManager::UnloadScripts(scene_file_data_.Assets.Scripts); UnloadAssets(); LOG_INFO("Closed scene"); } void EditorLayer::RunScene() { - m_CurrentScene->OnRuntimeStart(); - m_SceneState = SceneState::Running; + current_scene_->OnRuntimeStart(); + scene_state_ = SceneState::Running; } void EditorLayer::StopScene() { - m_CurrentScene->OnRuntimeStop(); - m_SceneState = SceneState::Editing; + current_scene_->OnRuntimeStop(); + scene_state_ = SceneState::Editing; } void EditorLayer::LoadAssets() { - for (const auto& asset : m_SceneFileData.assets.textures) { + for (const auto& asset : scene_file_data_.Assets.Textures) { AssetManager::AddTextureAsset(asset); } - for (const auto& asset : m_SceneFileData.assets.scripts) { + for (const auto& asset : scene_file_data_.Assets.Scripts) { AssetManager::AddScriptAsset(asset); } - for (const auto& asset : m_SceneFileData.assets.render_meshes) { + for (const auto& asset : scene_file_data_.Assets.RenderMeshes) { AssetManager::AddRenderMeshAsset(asset); } - for (const auto& asset : m_SceneFileData.assets.shaders) { + for (const auto& asset : scene_file_data_.Assets.Shaders) { AssetManager::AddShaderAsset(asset); } } void EditorLayer::UnloadAssets() { - for (const auto& asset : m_SceneFileData.assets.textures) { - AssetManager::RemoveTextureAsset(asset.id); + for (const auto& asset : scene_file_data_.Assets.Textures) { + AssetManager::RemoveTextureAsset(asset.ID); } - for (const auto& asset : m_SceneFileData.assets.scripts) { - AssetManager::RemoveScriptAsset(asset.id); + for (const auto& asset : scene_file_data_.Assets.Scripts) { + AssetManager::RemoveScriptAsset(asset.ID); } - for (const auto& asset : m_SceneFileData.assets.render_meshes) { - AssetManager::RemoveRenderMeshAsset(asset.id); + for (const auto& asset : scene_file_data_.Assets.RenderMeshes) { + AssetManager::RemoveRenderMeshAsset(asset.ID); } - for (const auto& asset : m_SceneFileData.assets.shaders) { - AssetManager::RemoveShaderAsset(asset.id); + for (const auto& asset : scene_file_data_.Assets.Shaders) { + AssetManager::RemoveShaderAsset(asset.ID); } } void EditorLayer::PrepareScene() { - m_EditorCamera = m_CurrentScene->CreateEntity("Editor Camera", false); - m_EditorCamera.AddComponent(); - m_EditorCamera.AddComponent(); - m_EditorCamera.AddComponent(ScriptEngine::CreateScript(ScriptManager::EditorScript("EditorCameraController"))); + editor_camera_ = current_scene_->CreateEntity("Editor Camera", false); + editor_camera_.AddComponent(); + editor_camera_.AddComponent(); + editor_camera_.AddComponent(ScriptEngine::CreateScript(ScriptManager::EditorScript("EditorCameraController"))); - m_CurrentScene->AttachSystem(m_TSSystem); - m_SceneHierarchy.SetActiveScene(m_CurrentScene); - m_Inspector.SetScene(m_CurrentScene); - m_RendererPanel.SetScene(m_CurrentScene); - m_Inspector.SetActiveEntity(m_SceneHierarchy.GetActiveEntity()); + current_scene_->AttachSystem(ts_system_); + scene_hierarchy_.SetActiveScene(current_scene_); + inspector_.SetScene(current_scene_); + renderer_panel_.SetScene(current_scene_); + inspector_.SetActiveEntity(scene_hierarchy_.GetActiveEntity()); } void EditorLayer::ProcessControlls(float) { @@ -311,12 +319,12 @@ namespace DE { } } if (Input::KeyDown(Key::LeftControl)) { - if (Input::KeyReleased(Key::GraveAccent) && m_CurrentScene != nullptr) { - m_InputState = (m_InputState == InputState::ViewPort ? InputState::NonSpecified : InputState::ViewPort); + if (Input::KeyReleased(Key::GraveAccent) && current_scene_ != nullptr) { + input_state_ = (input_state_ == InputState::ViewPort ? InputState::NonSpecified : InputState::ViewPort); SetMouseLockToggleEvent event; BroadcastEvent(event); } - if (m_InputState != InputState::ViewPort) { + if (input_state_ != InputState::ViewPort) { if (Input::KeyReleased(Key::O)) { ActionOpenScene(); } @@ -331,9 +339,9 @@ namespace DE { } } } - if (m_EditorCamera.Valid()) { - bool& active = m_EditorCamera.Get()->GetField("active"); - if (m_InputState == InputState::ViewPort) { + if (editor_camera_.Valid()) { + bool& active = editor_camera_.Get()->GetField("active_"); + if (input_state_ == InputState::ViewPort) { active = true; } else { active = false; @@ -343,12 +351,12 @@ namespace DE { void EditorLayer::LoadEditorResources() {} void EditorLayer::LoadIcons() { - auto play_data = TextureLoader::Load({Config::GetPath(DE_CFG_EXECUTABLE_PATH) / "Editor/Icons/PlayButton.png"}); - auto pause_data = TextureLoader::Load({Config::GetPath(DE_CFG_EXECUTABLE_PATH) / "Editor/Icons/PauseButton.png"}); - auto step_data = TextureLoader::Load({Config::GetPath(DE_CFG_EXECUTABLE_PATH) / "Editor/Icons/StepButton.png"}); - auto stop_data = TextureLoader::Load({Config::GetPath(DE_CFG_EXECUTABLE_PATH) / "Editor/Icons/StopButton.png"}); - auto build_data = TextureLoader::Load({Config::GetPath(DE_CFG_EXECUTABLE_PATH) / "Editor/Icons/BuildButton.png"}); - auto build_and_run_data = TextureLoader::Load({Config::GetPath(DE_CFG_EXECUTABLE_PATH) / "Editor/Icons/BuildAndRunButton.png"}); + auto play_data = TextureLoader::Load({Config::Get().ExecutablePath / "Editor/Icons/PlayButton.png"}); + auto pause_data = TextureLoader::Load({Config::Get().ExecutablePath / "Editor/Icons/PauseButton.png"}); + auto step_data = TextureLoader::Load({Config::Get().ExecutablePath / "Editor/Icons/StepButton.png"}); + auto stop_data = TextureLoader::Load({Config::Get().ExecutablePath / "Editor/Icons/StopButton.png"}); + auto build_data = TextureLoader::Load({Config::Get().ExecutablePath / "Editor/Icons/BuildButton.png"}); + auto build_and_run_data = TextureLoader::Load({Config::Get().ExecutablePath / "Editor/Icons/BuildAndRunButton.png"}); DE_ASSERT(play_data, "Failed to load play icon"); DE_ASSERT(pause_data, "Failed to load pause icon"); @@ -357,22 +365,22 @@ namespace DE { DE_ASSERT(build_data, "Failed to load build icon"); DE_ASSERT(build_and_run_data, "Failed to load build and run icon"); - m_Resources.play_icon = Texture::Create({*play_data}); - m_Resources.pause_icon = Texture::Create({*pause_data}); - m_Resources.step_icon = Texture::Create({*step_data}); - m_Resources.stop_icon = Texture::Create({*stop_data}); - m_Resources.build_icon = Texture::Create({*build_data}); - m_Resources.build_and_run_icon = Texture::Create({*build_and_run_data}); + resources_.PlayIcon = Texture::Create({*play_data}); + resources_.PauseIcon = Texture::Create({*pause_data}); + resources_.StepIcon = Texture::Create({*step_data}); + resources_.StopIcon = Texture::Create({*stop_data}); + resources_.BuildIcon = Texture::Create({*build_data}); + resources_.BuildAndRunIcon = Texture::Create({*build_and_run_data}); } //*___Other________________________________________________________________________________________________________________________________________________________________________________________ void TransformSyncSystem::Update(float) { for (auto entity : View()) { - entity.Get().position = entity.Get().translation; + entity.Get().Position = entity.Get().Translation; } } - EditorLayer* EditorLayer::s_Instance = nullptr; + EditorLayer* EditorLayer::gInstance = nullptr; -} // namespace DE \ No newline at end of file +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEditor/EditorLayer.h b/DummyEditor/EditorLayer.h index 0a4453a..5d048d4 100644 --- a/DummyEditor/EditorLayer.h +++ b/DummyEditor/EditorLayer.h @@ -1,6 +1,5 @@ #pragma once -#include "DummyEditor/DummyEngineInclude.h" #include "DummyEditor/ImGuiUtils/ImGuiManager.h" #include "DummyEditor/Panels/InspectorPanel.h" #include "DummyEditor/Panels/MenuBar.h" @@ -10,7 +9,13 @@ #include "DummyEditor/Panels/ThemePanel.h" #include "DummyEditor/Panels/ViewportPanel.h" -namespace DE { +#include "DummyEngine/Core/Application/Layer.h" +#include "DummyEngine/ToolBox/Loaders/SceneLoader.h" +#include "DummyEngine/Utils/Debug/Logger.h" + +namespace DummyEngine { + + class Texture; class TransformSyncSystem : public System { public: @@ -25,8 +30,8 @@ namespace DE { void Update(float dt) override; }; - class EditorLayer : public DE::Layer { - LOGGER_AUTHOR(EditorLayer); + class EditorLayer : public DummyEngine::Layer { + LOG_AUTHOR(EditorLayer); public: enum class SceneState { @@ -43,12 +48,12 @@ namespace DE { }; enum class InputState { NonSpecified = 0, ViewPort }; struct Resources { - Ref play_icon; - Ref pause_icon; - Ref step_icon; - Ref stop_icon; - Ref build_icon; - Ref build_and_run_icon; + Ref PlayIcon; + Ref PauseIcon; + Ref StepIcon; + Ref StopIcon; + Ref BuildIcon; + Ref BuildAndRunIcon; }; //*___Layer____________________________________________________________________________________________________________________________________________________________________________________ @@ -107,26 +112,27 @@ namespace DE { void LoadEditorResources(); void LoadIcons(); - SceneScriptState m_SceneScriptState = SceneScriptState::Uncompiled; - InputState m_InputState = InputState::NonSpecified; - SceneState m_SceneState = SceneState::None; - - ImGuiManager m_ImGuiManager; - ViewportPanel m_Viewport; - ViewportPanel m_FBOViewport; - SceneHierarchyPanel m_SceneHierarchy; - InspectorPanel m_Inspector; - ProfilerPanel m_Profiler; - ThemePanel m_ThemePanel; - MenuBar m_MenuBar; - RendererPanel m_RendererPanel; - - Ref m_CurrentScene; - SceneFileData m_SceneFileData; - Entity m_EditorCamera; - Ref m_TSSystem; - - Resources m_Resources; - static EditorLayer* s_Instance; + SceneScriptState scene_script_state_ = SceneScriptState::Uncompiled; + InputState input_state_ = InputState::NonSpecified; + SceneState scene_state_ = SceneState::None; + + ImGuiManager imgui_manager_; + ViewportPanel viewport_; + ViewportPanel shadow_viewport_; + SceneHierarchyPanel scene_hierarchy_; + InspectorPanel inspector_; + ProfilerPanel profiler_; + ThemePanel theme_panel_; + MenuBar menu_bar_; + RendererPanel renderer_panel_; + + Ref current_scene_; + SceneFileData scene_file_data_; + Entity editor_camera_; + Ref ts_system_; + + Resources resources_; + + static EditorLayer* gInstance; }; -} // namespace DE \ No newline at end of file +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEditor/ImGuiUtils/ImGuiManager.cpp b/DummyEditor/ImGuiUtils/ImGuiManager.cpp index 04e7b2d..6e394ce 100644 --- a/DummyEditor/ImGuiUtils/ImGuiManager.cpp +++ b/DummyEditor/ImGuiUtils/ImGuiManager.cpp @@ -1,36 +1,44 @@ -#include "DummyEditor/ImGuiUtils/ImGuiManager.h" +#include "ImGuiManager.h" -namespace DE { +#include "DummyEditor/ImGuiUtils/ImGuiIcons.h" +#include "DummyEditor/ImGuiUtils/ImGuiUtils.h" + +#include "DummyEngine/Core/Application/Config.h" +#include "DummyEngine/Utils/Types/Types.h" + +#include + +namespace DummyEngine { void ImGuiManager::SetMenuBar(ImGuiPanel* bar) { - m_MenuBar = bar; + menu_bar_ = bar; } void ImGuiManager::AddPanel(ImGuiPanel* panel) { - m_Panels.push_back(panel); + panels_.push_back(panel); } void ImGuiManager::OnImGui() { CreateDockingSpace(); - for (auto panel : m_Panels) { + for (auto panel : panels_) { panel->OnImGui(); } } const std::vector& ImGuiManager::GetPanels() { - return m_Panels; + return panels_; } void ImGuiManager::LoadEditorResources() { ImGuiIO& io = ImGui::GetIO(); - Path font_dir = Config::GetPath(DE_CFG_EXECUTABLE_PATH) / "Editor" / "Fonts"; - Path icon_font_path = Config::GetPath(DE_CFG_EXECUTABLE_PATH) / "Editor" / "Icons" / "IconsMaterialDesign.ttf"; + Path font_dir = Config::Get().ExecutablePath / "Editor" / "Fonts"; + Path icon_font_path = Config::Get().ExecutablePath / "Editor" / "Icons" / "IconsMaterialDesign.ttf"; for (const auto& entry : fs::directory_iterator(font_dir)) { // TODO: font size to settings - io.Fonts->AddFontFromFileTTF(entry.path().string().c_str(), ImGuiUtils::Constants::BasicFontSize); - static const ImWchar icons_ranges[] = {ICON_MIN_MD, ICON_MAX_16_MD, 0}; - ImFontConfig icons_config; + io.Fonts->AddFontFromFileTTF(entry.path().string().c_str(), ImGuiUtils::Constants::kBasicFontSize); + static constexpr ImWchar kIconsRanges[] = {ICON_MIN_MD, ICON_MAX_16_MD, 0}; // do not remove static : - ) + ImFontConfig icons_config; icons_config.MergeMode = true; icons_config.PixelSnapH = true; icons_config.GlyphOffset = {0.f, 4.f}; - io.Fonts->AddFontFromFileTTF(icon_font_path.string().c_str(), ImGuiUtils::Constants::BasicFontSize + 1, &icons_config, icons_ranges); + io.Fonts->AddFontFromFileTTF(icon_font_path.string().c_str(), ImGuiUtils::Constants::kBasicFontSize + 1, &icons_config, kIconsRanges); } } void ImGuiManager::CreateDockingSpace() { @@ -52,7 +60,7 @@ namespace DE { ImGuiID dockspace_id = ImGui::GetID("MyDockSpace"); ImGui::DockSpace(dockspace_id, ImVec2(0.0f, 0.0f), ImGuiDockNodeFlags_None); - m_MenuBar->OnImGui(); + menu_bar_->OnImGui(); ImGui::End(); } -} // namespace DE \ No newline at end of file +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEditor/ImGuiUtils/ImGuiManager.h b/DummyEditor/ImGuiUtils/ImGuiManager.h index 314a98f..04fd290 100644 --- a/DummyEditor/ImGuiUtils/ImGuiManager.h +++ b/DummyEditor/ImGuiUtils/ImGuiManager.h @@ -1,10 +1,10 @@ #pragma once -#include "DummyEditor/DummyEngineInclude.h" #include "DummyEditor/ImGuiUtils/ImGuiPanel.h" -#include "DummyEditor/ImGuiUtils/ImGuiUtils.h" -namespace DE { +#include + +namespace DummyEngine { class ImGuiManager { public: ImGuiManager() = default; @@ -17,8 +17,9 @@ namespace DE { void LoadEditorResources(); private: - void CreateDockingSpace(); - ImGuiPanel* m_MenuBar; - std::vector m_Panels; + void CreateDockingSpace(); + + ImGuiPanel* menu_bar_; + std::vector panels_; }; -} // namespace DE \ No newline at end of file +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEditor/ImGuiUtils/ImGuiPanel.cpp b/DummyEditor/ImGuiUtils/ImGuiPanel.cpp index 0b17085..b1da184 100644 --- a/DummyEditor/ImGuiUtils/ImGuiPanel.cpp +++ b/DummyEditor/ImGuiUtils/ImGuiPanel.cpp @@ -1,6 +1,7 @@ -#include "DummyEditor/ImGuiUtils/ImGuiPanel.h" +#include "ImGuiPanel.h" + +namespace DummyEngine { -namespace DE { void ImGuiPanel::Enable() { m_Controller = true; } @@ -13,4 +14,5 @@ namespace DE { const std::string& ImGuiPanel::GetName() const { return m_Name; } -} // namespace DE \ No newline at end of file + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEditor/ImGuiUtils/ImGuiPanel.h b/DummyEditor/ImGuiUtils/ImGuiPanel.h index 5f2555a..0bec62e 100644 --- a/DummyEditor/ImGuiUtils/ImGuiPanel.h +++ b/DummyEditor/ImGuiUtils/ImGuiPanel.h @@ -1,12 +1,12 @@ #pragma once -#include "DummyEditor/DummyEngineInclude.h" -#include "DummyEditor/ImGuiUtils/ImGuiUtils.h" +#include + +namespace DummyEngine { -namespace DE { class ImGuiPanel { public: - ImGuiPanel(const std::string& name) : m_Name(name) {} + explicit ImGuiPanel(const std::string& name) : m_Name(name) {} virtual ~ImGuiPanel() = default; virtual void OnImGui() = 0; @@ -19,4 +19,4 @@ namespace DE { bool m_Controller = true; std::string m_Name = "UnnamedPanel"; }; -} // namespace DE +} // namespace DummyEngine diff --git a/DummyEditor/ImGuiUtils/ImGuiUtils.cpp b/DummyEditor/ImGuiUtils/ImGuiUtils.cpp index e6df882..17545fc 100644 --- a/DummyEditor/ImGuiUtils/ImGuiUtils.cpp +++ b/DummyEditor/ImGuiUtils/ImGuiUtils.cpp @@ -1,7 +1,15 @@ -#include "DummyEditor/ImGuiUtils/ImGuiUtils.h" +#include "ImGuiUtils.h" + +#include "DummyEngine/Core/Rendering/Renderer/Renderer.h" +#include "DummyEngine/Core/Scene/Components.h" +#include "DummyEngine/Core/Scene/Scene.h" + +#include + +namespace DummyEngine { -namespace DE { namespace ImGuiUtils { + ScopedID::ScopedID(int cnt) { ImGui::PushID(cnt); } @@ -38,10 +46,10 @@ namespace DE { } void EditProperty(std::string name, ImGuiDataType type, void* value, float speed, const void* min, const void* max) { - ImGui::SetCursorPosX(Constants::DefaultLeftPadding); + ImGui::SetCursorPosX(Constants::kDefaultLeftPadding); ImGui::TextUnformatted(name.c_str()); ImGui::NextColumn(); - ImGui::SetNextItemWidth(Constants::DefaultRightPadding); + ImGui::SetNextItemWidth(Constants::kDefaultRightPadding); name.insert(name.begin(), 2, '#'); ImGui::DragScalar(name.c_str(), type, value, speed, min, max); ImGui::NextColumn(); @@ -77,7 +85,7 @@ namespace DE { EditProperty(name, ImGuiDataType_S64, &value); } void EditProperty(const std::string& name, bool& value, PropertyType) { - ImGui::SetCursorPosX(Constants::DefaultLeftPadding); + ImGui::SetCursorPosX(Constants::kDefaultLeftPadding); ImGui::TextUnformatted(name.c_str()); ImGui::NextColumn(); ImGui::SetNextItemWidth(-1); @@ -85,52 +93,52 @@ namespace DE { ImGui::NextColumn(); } void EditProperty(std::string name, std::string& value, PropertyType) { - ImGui::SetCursorPosX(Constants::DefaultLeftPadding); + ImGui::SetCursorPosX(Constants::kDefaultLeftPadding); ImGui::TextUnformatted(name.c_str()); ImGui::NextColumn(); - ImGui::SetNextItemWidth(Constants::DefaultRightPadding); + ImGui::SetNextItemWidth(Constants::kDefaultRightPadding); name.insert(name.begin(), 2, '#'); ImGui::InputText(name.c_str(), &value); ImGui::NextColumn(); } void EditProperty(std::string name, Vec2& vec, PropertyType) { - ImGui::SetCursorPosX(Constants::DefaultLeftPadding); + ImGui::SetCursorPosX(Constants::kDefaultLeftPadding); ImGui::TextUnformatted(name.c_str()); ImGui::NextColumn(); - ImGui::SetNextItemWidth(Constants::DefaultRightPadding); + ImGui::SetNextItemWidth(Constants::kDefaultRightPadding); name.insert(name.begin(), 2, '#'); ImGui::DragFloat2(name.c_str(), &vec.x); ImGui::NextColumn(); } void EditProperty(std::string name, Vec3& vec, PropertyType property_type) { - ImGui::SetCursorPosX(Constants::DefaultLeftPadding); + ImGui::SetCursorPosX(Constants::kDefaultLeftPadding); ImGui::TextUnformatted(name.c_str()); ImGui::NextColumn(); name.insert(name.begin(), 2, '#'); switch (property_type) { case PropertyType::Color: - ImGui::SetNextItemWidth(Constants::ColorPading); + ImGui::SetNextItemWidth(Constants::kColorPading); ImGui::ColorEdit3(name.c_str(), &vec.x, ImGuiColorEditFlags_NoLabel); break; default: - ImGui::SetNextItemWidth(Constants::DefaultRightPadding); + ImGui::SetNextItemWidth(Constants::kDefaultRightPadding); ImGui::DragFloat3(name.c_str(), &vec.x); break; } ImGui::NextColumn(); } void EditProperty(std::string name, Vec4& vec, PropertyType property_type) { - ImGui::SetCursorPosX(Constants::DefaultLeftPadding); + ImGui::SetCursorPosX(Constants::kDefaultLeftPadding); ImGui::TextUnformatted(name.c_str()); ImGui::NextColumn(); name.insert(name.begin(), 2, '#'); switch (property_type) { case PropertyType::Color: - ImGui::SetNextItemWidth(Constants::ColorPading); + ImGui::SetNextItemWidth(Constants::kColorPading); ImGui::ColorEdit4(name.c_str(), &vec.x, ImGuiColorEditFlags_NoLabel); break; default: - ImGui::SetNextItemWidth(Constants::DefaultRightPadding); + ImGui::SetNextItemWidth(Constants::kDefaultRightPadding); ImGui::DragFloat4(name.c_str(), &vec.x); break; } @@ -140,7 +148,7 @@ namespace DE { EditProperty(name, *(Vec4*)&vec, property_type); } void EditProperty(const std::string& name, Entity& entity, Ref scene) { - ImGui::SetCursorPosX(Constants::DefaultLeftPadding); + ImGui::SetCursorPosX(Constants::kDefaultLeftPadding); ImGui::TextUnformatted(name.c_str()); ImGui::NextColumn(); std::string preview = "Invalid entity"; @@ -148,11 +156,11 @@ namespace DE { preview = entity.Get(); } int cnt = 0; - ImGui::SetNextItemWidth(Constants::ColorPading); + ImGui::SetNextItemWidth(Constants::kColorPading); if (ImGui::BeginCombo("##EntitySelect", preview.c_str())) { for (auto e : scene->View()) { ImGuiUtils::ScopedID id(cnt++); - if (ImGui::Selectable(e.Get().tag.c_str(), entity == e)) { + if (ImGui::Selectable(e.Get().Tag.c_str(), entity == e)) { entity = e; } } @@ -168,27 +176,27 @@ namespace DE { float orm_speed = 0.01; ImGui::Separator(); - ImGui::SetCursorPosX(ImGuiUtils::Constants::DefaultLeftPadding); + ImGui::SetCursorPosX(ImGuiUtils::Constants::kDefaultLeftPadding); ImGui::Text("Type"); ImGui::NextColumn(); ImGui::SetNextItemWidth(-1); - ImGui::Combo("##Material Type", (int*)&mat.type, mat_types, IM_ARRAYSIZE(mat_types)); + ImGui::Combo("##Material Type", (int*)&mat.Type, mat_types, IM_ARRAYSIZE(mat_types)); ImGui::NextColumn(); ImGui::Separator(); - switch (mat.type) { + switch (mat.Type) { case MaterialType::PBR: { - auto emission_map = (mat.emission_map ? mat.emission_map : Renderer::GetTexture(Renderer::Textures::White)); - auto albedo_map = (mat.albedo_map ? mat.albedo_map : Renderer::GetTexture(Renderer::Textures::White)); - auto normal_map = (mat.normal_map ? mat.normal_map : Renderer::GetTexture(Renderer::Textures::Normal)); - auto orm_map = (mat.orm_map ? mat.orm_map : Renderer::GetTexture(Renderer::Textures::White)); + auto emission_map = (mat.EmissionMap ? mat.EmissionMap : Renderer::GetTexture(Renderer::Textures::White)); + auto albedo_map = (mat.AlbedoMap ? mat.AlbedoMap : Renderer::GetTexture(Renderer::Textures::White)); + auto normal_map = (mat.NormalMap ? mat.NormalMap : Renderer::GetTexture(Renderer::Textures::Normal)); + auto orm_map = (mat.ORMMap ? mat.ORMMap : Renderer::GetTexture(Renderer::Textures::White)); - ImGuiUtils::EditProperty("AmbientColor", mat.ambient, ImGuiUtils::PropertyType::Color); - ImGuiUtils::EditProperty("EmissionColor", mat.emission, ImGuiUtils::PropertyType::Color); - ImGuiUtils::EditProperty("AlbedoColor", mat.albedo, ImGuiUtils::PropertyType::Color); - ImGuiUtils::EditProperty("AmbientOcclusion", ImGuiDataType_Float, &mat.orm.r, orm_speed, &min_orm, &max_orm); - ImGuiUtils::EditProperty("Roughness", ImGuiDataType_Float, &mat.orm.g, orm_speed, &min_orm, &max_orm); - ImGuiUtils::EditProperty("Metallic", ImGuiDataType_Float, &mat.orm.b, orm_speed, &min_orm, &max_orm); - ImGuiUtils::EditProperty("EmissionStrength", ImGuiDataType_Float, &mat.emission_strength, orm_speed, &min_shininess, nullptr); + ImGuiUtils::EditProperty("AmbientColor", mat.Ambient, ImGuiUtils::PropertyType::Color); + ImGuiUtils::EditProperty("EmissionColor", mat.Emission, ImGuiUtils::PropertyType::Color); + ImGuiUtils::EditProperty("AlbedoColor", mat.Albedo, ImGuiUtils::PropertyType::Color); + ImGuiUtils::EditProperty("AmbientOcclusion", ImGuiDataType_Float, &mat.ORM.r, orm_speed, &min_orm, &max_orm); + ImGuiUtils::EditProperty("Roughness", ImGuiDataType_Float, &mat.ORM.g, orm_speed, &min_orm, &max_orm); + ImGuiUtils::EditProperty("Metallic", ImGuiDataType_Float, &mat.ORM.b, orm_speed, &min_orm, &max_orm); + ImGuiUtils::EditProperty("EmissionStrength", ImGuiDataType_Float, &mat.EmissionStrength, orm_speed, &min_shininess, nullptr); ImGui::Separator(); ImGuiUtils::EditTexture("AlbedoMap", albedo_map); ImGui::Separator(); @@ -201,17 +209,17 @@ namespace DE { break; } case MaterialType::Phong: { - auto emission_map = (mat.emission_map ? mat.emission_map : Renderer::GetTexture(Renderer::Textures::White)); - auto normal_map = (mat.normal_map ? mat.normal_map : Renderer::GetTexture(Renderer::Textures::Normal)); - auto diffuse_map = (mat.diffuse_map ? mat.diffuse_map : Renderer::GetTexture(Renderer::Textures::White)); - auto specular_map = (mat.specular_map ? mat.specular_map : Renderer::GetTexture(Renderer::Textures::White)); + auto emission_map = (mat.EmissionMap ? mat.EmissionMap : Renderer::GetTexture(Renderer::Textures::White)); + auto normal_map = (mat.NormalMap ? mat.NormalMap : Renderer::GetTexture(Renderer::Textures::Normal)); + auto diffuse_map = (mat.DiffuseMap ? mat.DiffuseMap : Renderer::GetTexture(Renderer::Textures::White)); + auto specular_map = (mat.SpecularMap ? mat.SpecularMap : Renderer::GetTexture(Renderer::Textures::White)); - ImGuiUtils::EditProperty("AmbientColor", mat.ambient, ImGuiUtils::PropertyType::Color); - ImGuiUtils::EditProperty("EmissionColor", mat.emission, ImGuiUtils::PropertyType::Color); - ImGuiUtils::EditProperty("DiffuseColor", mat.diffuse, ImGuiUtils::PropertyType::Color); - ImGuiUtils::EditProperty("Specular", mat.specular, ImGuiUtils::PropertyType::Color); - ImGuiUtils::EditProperty("EmissionStrength", ImGuiDataType_Float, &mat.emission_strength, orm_speed, &min_shininess, nullptr); - ImGuiUtils::EditProperty("Shininess", ImGuiDataType_Float, &mat.shininess, orm_speed, &min_shininess, nullptr); + ImGuiUtils::EditProperty("AmbientColor", mat.Ambient, ImGuiUtils::PropertyType::Color); + ImGuiUtils::EditProperty("EmissionColor", mat.Emission, ImGuiUtils::PropertyType::Color); + ImGuiUtils::EditProperty("DiffuseColor", mat.Diffuse, ImGuiUtils::PropertyType::Color); + ImGuiUtils::EditProperty("Specular", mat.Specular, ImGuiUtils::PropertyType::Color); + ImGuiUtils::EditProperty("EmissionStrength", ImGuiDataType_Float, &mat.EmissionStrength, orm_speed, &min_shininess, nullptr); + ImGuiUtils::EditProperty("Shininess", ImGuiDataType_Float, &mat.Shininess, orm_speed, &min_shininess, nullptr); ImGui::Separator(); ImGuiUtils::EditTexture("DiffuseMap", diffuse_map); ImGui::Separator(); @@ -228,12 +236,12 @@ namespace DE { } } void EditTexture(const std::string& name, Ref texture, const ImVec2 tex_size) { - ImGui::SetCursorPosX(ImGuiUtils::Constants::DefaultLeftPadding); + ImGui::SetCursorPosX(ImGuiUtils::Constants::kDefaultLeftPadding); ImGui::TextUnformatted(name.c_str()); ImGui::NextColumn(); - ImGui::SetNextItemWidth(ImGuiUtils::Constants::DefaultRightPadding); + ImGui::SetNextItemWidth(ImGuiUtils::Constants::kDefaultRightPadding); ImGui::Image(texture->GetRendererId(), tex_size); ImGui::NextColumn(); } } // namespace ImGuiUtils -} // namespace DE \ No newline at end of file +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEditor/ImGuiUtils/ImGuiUtils.h b/DummyEditor/ImGuiUtils/ImGuiUtils.h index ca3e677..5d7b1b9 100644 --- a/DummyEditor/ImGuiUtils/ImGuiUtils.h +++ b/DummyEditor/ImGuiUtils/ImGuiUtils.h @@ -1,24 +1,32 @@ #pragma once -#include "DummyEditor/DummyEngineInclude.h" -#include "DummyEditor/ImGuiUtils/ImGuiIcons.h" +#include "DummyEngine/Utils/Types/Types.h" + +#include + +namespace DummyEngine { + + class Event; + class Entity; + struct Material; + class Texture; + class Scene; -namespace DE { namespace ImGuiUtils { class ScopedID { public: - ScopedID(int cnt); - ScopedID(const char* str); - ScopedID(const std::string& str); - ScopedID(const void* ptr); + explicit ScopedID(int cnt); + explicit ScopedID(const char* str); + explicit ScopedID(const std::string& str); + explicit ScopedID(const void* ptr); ~ScopedID(); }; namespace Constants { - constexpr S32 BasicFontSize = 16; - constexpr S32 ColorPading = -1; - constexpr S32 DefaultRightPadding = -23; - constexpr S32 DefaultLeftPadding = 25; + constexpr S32 kBasicFontSize = 16; + constexpr S32 kColorPading = -1; + constexpr S32 kDefaultRightPadding = -23; + constexpr S32 kDefaultLeftPadding = 25; } // namespace Constants void ClampRoundValue(Vec3& vec, float min, float max); @@ -61,4 +69,4 @@ namespace DE { void EditTexture(const std::string& name, Ref texture, const ImVec2 tex_size = {128, 128}); } // namespace ImGuiUtils -} // namespace DE +} // namespace DummyEngine diff --git a/DummyEditor/Panels/InspectorPanel.cpp b/DummyEditor/Panels/InspectorPanel.cpp index 47a7ff3..297b2df 100644 --- a/DummyEditor/Panels/InspectorPanel.cpp +++ b/DummyEditor/Panels/InspectorPanel.cpp @@ -1,6 +1,20 @@ -#include "DummyEditor/Panels/InspectorPanel.h" +#include "InspectorPanel.h" -namespace DE { +#include "DummyEditor/ImGuiUtils/ImGuiIcons.h" +#include "DummyEditor/ImGuiUtils/ImGuiUtils.h" + +#include "DummyEngine/Core/Objects/Cameras/FPSCamera.h" +#include "DummyEngine/Core/Objects/LightSources/LightSource.h" +#include "DummyEngine/Core/Physics/PhysicsComponent.h" +#include "DummyEngine/Core/Scene/Components.h" +#include "DummyEngine/Core/Scripting/Script.h" +#include "DummyEngine/Core/Scripting/ScriptEngine.h" +#include "DummyEngine/Utils/Debug/Demangler.h" // IWYU pragma: keep +#include "DummyEngine/Utils/Debug/Profiler.h" + +#include + +namespace DummyEngine { ImGuiDataType_ ScriptFieldTypeToImGuiType(ScriptFieldType type) { switch (type) { @@ -15,40 +29,40 @@ namespace DE { } template void InspectorPanel::DrawComponentWidget() { - if (m_Entity.Has()) { + if (entity_.Has()) { std::string header = ICON_MD_REPORT_PROBLEM " " + DemangledName(); if (ImGui::CollapsingHeader(header.c_str(), ImGuiTreeNodeFlags_DefaultOpen)) { - ImGui::SetCursorPosX(ImGuiUtils::Constants::DefaultLeftPadding); + ImGui::SetCursorPosX(ImGuiUtils::Constants::kDefaultLeftPadding); ImGui::Text("Widget for %s not yet implmented", DemangledName().c_str()); } } } template <> void InspectorPanel::DrawComponentWidget() { - if (m_Entity.Has()) { + if (entity_.Has()) { if (ImGui::CollapsingHeader(ICON_MD_OPEN_IN_FULL " Transformation", ImGuiTreeNodeFlags_DefaultOpen)) { - auto& transform = m_Entity.Get(); + auto& transform = entity_.Get(); ImGui::Columns(2); - ImGuiUtils::EditProperty("Translation", transform.translation); - ImGuiUtils::EditProperty("Scale", transform.scale); - ImGuiUtils::EditProperty("Rotation", transform.rotation); + ImGuiUtils::EditProperty("Translation", transform.Translation); + ImGuiUtils::EditProperty("Scale", transform.Scale); + ImGuiUtils::EditProperty("Rotation", transform.Rotation); ImGui::Columns(1); } } } template <> void InspectorPanel::DrawComponentWidget() { - if (m_Entity.Has()) { - auto& component = m_Entity.Get(); + if (entity_.Has()) { + auto& component = entity_.Get(); if (ImGui::CollapsingHeader(ICON_MD_BADGE " Tag", ImGuiTreeNodeFlags_DefaultOpen)) { ImGui::Columns(2); - ImGuiUtils::EditProperty("Tag", component.tag); + ImGuiUtils::EditProperty("Tag", component.Tag); ImGui::Columns(1); } } } template <> void InspectorPanel::DrawComponentWidget() { - if (m_Entity.Has()) { - auto& component = m_Entity.Get(); + if (entity_.Has()) { + auto& component = entity_.Get(); if (ImGui::CollapsingHeader(ICON_MD_DESCRIPTION " Script", ImGuiTreeNodeFlags_DefaultOpen)) { ImGui::Columns(2); if (component.Valid()) { @@ -83,67 +97,67 @@ namespace DE { } } template <> void InspectorPanel::DrawComponentWidget() { - if (m_Entity.Has()) { + if (entity_.Has()) { if (ImGui::CollapsingHeader(ICON_MD_VIDEOCAM " FPSCamera", ImGuiTreeNodeFlags_DefaultOpen)) { - auto& camera = m_Entity.Get(); + auto& camera = entity_.Get(); ImGui::Columns(2); - ImGuiUtils::EditProperty("Position", camera.m_Position); - ImGuiUtils::EditProperty("NearPlane", camera.m_NearPlane); - ImGuiUtils::EditProperty("FarPlane", camera.m_FarPlane); - ImGuiUtils::EditProperty("FIeldOfView", camera.m_FOV); + ImGuiUtils::EditProperty("Position", camera.Position); + ImGuiUtils::EditProperty("NearPlane", camera.NearPlane); + ImGuiUtils::EditProperty("FarPlane", camera.FarPlane); + ImGuiUtils::EditProperty("FIeldOfView", camera.FOV); ImGui::Columns(1); if (ImGui::Button("Select as main camera", {ImGui::GetContentRegionAvail().x, 20})) { - m_Scene.lock()->SetCamera(m_Entity); + scene_.lock()->SetCamera(entity_); } } } } template <> void InspectorPanel::DrawComponentWidget() { - if (m_Entity.Has()) { + if (entity_.Has()) { if (ImGui::CollapsingHeader(ICON_MD_LIGHTBULB " LightSoruce", ImGuiTreeNodeFlags_DefaultOpen)) { - auto& source = m_Entity.Get(); + auto& source = entity_.Get(); const char* light_types[] = {"Directional", "Point", "Spot"}; ImGui::Columns(2); - ImGui::SetCursorPosX(ImGuiUtils::Constants::DefaultLeftPadding); + ImGui::SetCursorPosX(ImGuiUtils::Constants::kDefaultLeftPadding); ImGui::Text("Type"); ImGui::NextColumn(); ImGui::SetNextItemWidth(-1); - ImGui::Combo("##Light Type", (int*)&source.type, light_types, IM_ARRAYSIZE(light_types)); + ImGui::Combo("##Light Type", (int*)&source.Type, light_types, IM_ARRAYSIZE(light_types)); ImGui::NextColumn(); ImGui::Separator(); // ImGuiUtils::EditProperty("Ambient", source.ambient, ImGuiUtils::PropertyType::Color); - ImGuiUtils::EditProperty("Diffuse", source.diffuse, ImGuiUtils::PropertyType::Color); - ImGuiUtils::EditProperty("Specular", source.specular, ImGuiUtils::PropertyType::Color); + ImGuiUtils::EditProperty("Diffuse", source.Diffuse, ImGuiUtils::PropertyType::Color); + ImGuiUtils::EditProperty("Specular", source.Specular, ImGuiUtils::PropertyType::Color); - if (source.type == LightSourceType::Point || source.type == LightSourceType::Spot) { - ImGuiUtils::EditProperty("CLQ", source.clq); + if (source.Type == LightSourceType::Point || source.Type == LightSourceType::Spot) { + ImGuiUtils::EditProperty("CLQ", source.CLQ); } - if (source.type == LightSourceType::Spot || source.type == LightSourceType::Direction) { - ImGuiUtils::EditProperty("Direction", source.direction); + if (source.Type == LightSourceType::Spot || source.Type == LightSourceType::Direction) { + ImGuiUtils::EditProperty("Direction", source.Direction); } - if (source.type == LightSourceType::Spot || source.type == LightSourceType::Point) { - ImGuiUtils::EditProperty("Position", source.position); + if (source.Type == LightSourceType::Spot || source.Type == LightSourceType::Point) { + ImGuiUtils::EditProperty("Position", source.Position); } - if (source.type == LightSourceType::Spot) { - ImGuiUtils::EditProperty("Inner Cone", source.inner_cone_cos); - ImGuiUtils::EditProperty("Outer Cone", source.outer_cone_cos); + if (source.Type == LightSourceType::Spot) { + ImGuiUtils::EditProperty("Inner Cone", source.InnerConeCosinus); + ImGuiUtils::EditProperty("Outer Cone", source.OuterConeCosinus); } ImGui::Columns(1); } } } template <> void InspectorPanel::DrawComponentWidget() { - if (m_Entity.Has()) { + if (entity_.Has()) { if (ImGui::CollapsingHeader(ICON_MD_TOKEN " RenderMesh", ImGuiTreeNodeFlags_DefaultOpen)) { - auto& meshes = m_Entity.Get()->GetSubMeshes(); + auto& meshes = entity_.Get()->GetSubMeshes(); int cnt = 0; for (auto& mesh : meshes) { std::string name = std::format("Mesh_{}", cnt); if (ImGui::TreeNode(name.c_str())) { ImGui::Columns(2); - ImGuiUtils::EditProperty(mesh.material); + ImGuiUtils::EditProperty(mesh.Material); ImGui::Columns(1); ImGui::TreePop(); } @@ -154,17 +168,17 @@ namespace DE { } template <> void InspectorPanel::DrawComponentWidget() { - if (m_Entity.Has()) { + if (entity_.Has()) { if (ImGui::CollapsingHeader(" PhysicsComponent", ImGuiTreeNodeFlags_DefaultOpen)) { - auto& phys = m_Entity.Get(); + auto& phys = entity_.Get(); const float min_mas = 0; ImGui::Columns(2); - ImGuiUtils::EditProperty("Speed", phys.speed); - ImGuiUtils::EditProperty("Rotspeed", phys.rot_speed); - ImGuiUtils::EditProperty("InvMass", ImGuiDataType_Float, &phys.inv_mass, 0.01, &min_mas); - ImGuiUtils::EditProperty("InvInertia", ImGuiDataType_Float, &phys.inv_inertia, 0.01, &min_mas); - ImGuiUtils::EditProperty("Collidable", phys.collidable); - ImGuiUtils::EditProperty("Gravity", phys.gravity); + ImGuiUtils::EditProperty("Speed", phys.Speed); + ImGuiUtils::EditProperty("Rotspeed", phys.RotationSpeed); + ImGuiUtils::EditProperty("InvMass", ImGuiDataType_Float, &phys.InvertedMass, 0.01, &min_mas); + ImGuiUtils::EditProperty("InvInertia", ImGuiDataType_Float, &phys.InvertedInertia, 0.01, &min_mas); + ImGuiUtils::EditProperty("Collidable", phys.Collidable); + ImGuiUtils::EditProperty("Gravity", phys.Gravity); ImGui::Columns(1); } } @@ -174,8 +188,8 @@ namespace DE { DE_PROFILE_SCOPE("InspectorPanel OnImGui"); if (m_Controller) { if (ImGui::Begin(ICON_MD_INFO " Inspector")) { - auto scene = m_Scene.lock(); - if (scene && m_Entity.Valid()) { + auto scene = scene_.lock(); + if (scene && entity_.Valid()) { DrawComponentWidget(); DrawComponentWidget(); DrawComponentWidget(); @@ -195,23 +209,23 @@ namespace DE { ImGui::OpenPopup("AddComponentPopup"); } if (ImGui::BeginPopup("AddComponentPopup")) { - if (!m_Entity.Has() && ImGui::Selectable(ICON_MD_OPEN_IN_FULL "Transform")) { - m_Entity.Add(); + if (!entity_.Has() && ImGui::Selectable(ICON_MD_OPEN_IN_FULL "Transform")) { + entity_.Add(); } - if (!m_Entity.Has() && ImGui::Selectable(ICON_MD_LIGHTBULB "LightSource")) { - m_Entity.Add(); + if (!entity_.Has() && ImGui::Selectable(ICON_MD_LIGHTBULB "LightSource")) { + entity_.Add(); } - if (!m_Entity.Has() && ImGui::Selectable(ICON_MD_VIDEOCAM "Camera")) { - m_Entity.Add(); + if (!entity_.Has() && ImGui::Selectable(ICON_MD_VIDEOCAM "Camera")) { + entity_.Add(); } ImGui::EndPopup(); } } void InspectorPanel::SetActiveEntity(Entity entity) { - m_Entity = entity; + entity_ = entity; } void InspectorPanel::SetScene(WeakRef scene) { - m_Scene = scene; + scene_ = scene; } -} // namespace DE \ No newline at end of file +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEditor/Panels/InspectorPanel.h b/DummyEditor/Panels/InspectorPanel.h index a22bb1e..ee2a4b7 100644 --- a/DummyEditor/Panels/InspectorPanel.h +++ b/DummyEditor/Panels/InspectorPanel.h @@ -2,7 +2,11 @@ #include "DummyEditor/ImGuiUtils/ImGuiPanel.h" -namespace DE { +#include "DummyEngine/Core/ECS/ECS.h" + +namespace DummyEngine { + class Scene; + class InspectorPanel : public ImGuiPanel { public: InspectorPanel() : ImGuiPanel("Inspector") {} @@ -15,7 +19,7 @@ namespace DE { private: template void DrawComponentWidget(); - Entity m_Entity; - WeakRef m_Scene; + Entity entity_; + WeakRef scene_; }; -} // namespace DE \ No newline at end of file +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEditor/Panels/MenuBar.cpp b/DummyEditor/Panels/MenuBar.cpp index eec5bce..f3fa253 100644 --- a/DummyEditor/Panels/MenuBar.cpp +++ b/DummyEditor/Panels/MenuBar.cpp @@ -1,8 +1,13 @@ -#include "DummyEditor/Panels/MenuBar.h" +#include "MenuBar.h" #include "DummyEditor/EditorLayer.h" +#include "DummyEditor/ImGuiUtils/ImGuiUtils.h" -namespace DE { +#include "DummyEngine/Utils/Debug/Profiler.h" + +#include + +namespace DummyEngine { void MenuBar::OnImGui() { DE_PROFILE_SCOPE("MenuBar OnImGui"); @@ -41,9 +46,9 @@ namespace DE { int cnt = 0; for (auto panel : editor.GetImGuiManager().GetPanels()) { ImGuiUtils::ScopedID id(++cnt); - ImGui::MenuItem(panel->GetName().c_str(), NULL, &panel->GetController()); + ImGui::MenuItem(panel->GetName().c_str(), nullptr, &panel->GetController()); } ImGui::EndMenu(); } } -} // namespace DE \ No newline at end of file +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEditor/Panels/MenuBar.h b/DummyEditor/Panels/MenuBar.h index 1e0c3cc..775dd62 100644 --- a/DummyEditor/Panels/MenuBar.h +++ b/DummyEditor/Panels/MenuBar.h @@ -1,9 +1,9 @@ #pragma once -#include "DummyEditor/DummyEngineInclude.h" #include "DummyEditor/ImGuiUtils/ImGuiPanel.h" -namespace DE { +namespace DummyEngine { + class EditorLayer; class MenuBar : public ImGuiPanel { public: @@ -14,4 +14,5 @@ namespace DE { void ViewMenu(); void FileMenu(); }; -} // namespace DE \ No newline at end of file + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEditor/Panels/ProfilerPanel.cpp b/DummyEditor/Panels/ProfilerPanel.cpp index c1c302a..5dcdef0 100644 --- a/DummyEditor/Panels/ProfilerPanel.cpp +++ b/DummyEditor/Panels/ProfilerPanel.cpp @@ -1,13 +1,19 @@ -#include "DummyEditor/Panels/ProfilerPanel.h" +#include "ProfilerPanel.h" + +#include "DummyEditor/ImGuiUtils/ImGuiIcons.h" +#include "DummyEditor/ImGuiUtils/ImGuiUtils.h" + +#include + +namespace DummyEngine { -namespace DE { void ProfilerPanel::OnImGui() { DE_PROFILE_SCOPE("ProfilerPanel OnImGui"); if (m_Controller) { if (ImGui::Begin(ICON_MD_SPEED " Profiler")) { #if DE_ENABLE_PROFILER - RenderTimeLapse(Profiler::GetOldestFrame().m_TimeLapses, 0); + RenderTimeLapse(Profiler::GetOldestFrame().Timelapses, 0); #endif } ImGui::End(); @@ -18,16 +24,17 @@ namespace DE { ImGuiUtils::ScopedID id(index); ImGuiTreeNodeFlags flags = ImGuiTreeNodeFlags_None | ImGuiTreeNodeFlags_SpanFullWidth | ImGuiTreeNodeFlags_SpanAvailWidth | ImGuiTreeNodeFlags_DefaultOpen; - auto& name = time_lapses[index].m_Name; + auto& name = time_lapses[index].Name; auto duration = time_lapses[index].StrDuration(); - if (time_lapses[index].m_Childs.empty()) { + if (time_lapses[index].Childs.empty()) { flags |= ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_Bullet; } if (ImGui::TreeNodeEx(name.c_str(), flags, "%s: %s", name.c_str(), duration.c_str())) { - for (auto child : time_lapses[index].m_Childs) { + for (auto child : time_lapses[index].Childs) { RenderTimeLapse(time_lapses, child); } ImGui::TreePop(); } } -} // namespace DE \ No newline at end of file + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEditor/Panels/ProfilerPanel.h b/DummyEditor/Panels/ProfilerPanel.h index 27a142e..8414599 100644 --- a/DummyEditor/Panels/ProfilerPanel.h +++ b/DummyEditor/Panels/ProfilerPanel.h @@ -2,7 +2,10 @@ #include "DummyEditor/ImGuiUtils/ImGuiPanel.h" -namespace DE { +#include "DummyEngine/Utils/Debug/Profiler.h" + +namespace DummyEngine { + class ProfilerPanel : public ImGuiPanel { public: ProfilerPanel() : ImGuiPanel("Profiler") {} @@ -11,4 +14,5 @@ namespace DE { private: void RenderTimeLapse(const std::vector& time_lapses, U32 index); }; -} // namespace DE \ No newline at end of file + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEditor/Panels/RendererPanel.cpp b/DummyEditor/Panels/RendererPanel.cpp index 09c1564..189e986 100644 --- a/DummyEditor/Panels/RendererPanel.cpp +++ b/DummyEditor/Panels/RendererPanel.cpp @@ -1,12 +1,21 @@ -#include "DummyEditor/Panels/RendererPanel.h" +#include "RendererPanel.h" -namespace DE { +#include "DummyEditor/ImGuiUtils/ImGuiIcons.h" +#include "DummyEditor/ImGuiUtils/ImGuiUtils.h" + +#include "DummyEngine/Core/Scene/Scene.h" +#include "DummyEngine/Core/Scene/SceneRenderer.h" +#include "DummyEngine/Utils/Debug/Profiler.h" + +#include + +namespace DummyEngine { void RendererPanel::OnImGui() { DE_PROFILE_SCOPE("RendererPanel OnImGui"); if (m_Controller) { if (ImGui::Begin(ICON_MD_PHOTO_CAMERA " Renderer")) { - auto scene = m_Scene.lock(); + auto scene = scene_.lock(); if (scene) { const float mix_exposure = 0; const float min_gamma = 0.01; @@ -16,28 +25,28 @@ namespace DE { const float min_strength = 0; const float max_strength = 1; - auto& settings = scene->GetRenderer()->settings; + auto& settings = scene->GetRenderer()->Settings; ImGui::Separator(); ImGui::Columns(2); - ImGuiUtils::EditProperty("Bloom", settings.bloom); - ImGuiUtils::EditProperty("Treshold", ImGuiDataType_Float, &settings.bloom_threshold, 0.01, &settings.bloom_soft_threshold); + ImGuiUtils::EditProperty("Bloom", settings.Bloom); + ImGuiUtils::EditProperty("Treshold", ImGuiDataType_Float, &settings.BloomThreshold, 0.01, &settings.BloomSoftThreshold); ImGuiUtils::EditProperty( - "SoftTreshold", ImGuiDataType_Float, &settings.bloom_soft_threshold, 0.01, &min_threshold, &settings.bloom_threshold); - ImGuiUtils::EditProperty("Radius", ImGuiDataType_Float, &settings.bloom_radius, 0.001, &min_radius); - ImGuiUtils::EditProperty("Strength", ImGuiDataType_Float, &settings.bloom_strength, 0.001, &min_strength, &max_strength); - ImGuiUtils::EditProperty("Depth", ImGuiDataType_U32, &settings.bloom_depth, 0.01, &min_depth); + "SoftTreshold", ImGuiDataType_Float, &settings.BloomSoftThreshold, 0.01, &min_threshold, &settings.BloomThreshold); + ImGuiUtils::EditProperty("Radius", ImGuiDataType_Float, &settings.BloomRadius, 0.001, &min_radius); + ImGuiUtils::EditProperty("Strength", ImGuiDataType_Float, &settings.BloomStrength, 0.001, &min_strength, &max_strength); + ImGuiUtils::EditProperty("Depth", ImGuiDataType_U32, &settings.BloomDepth, 0.01, &min_depth); ImGui::Columns(1); ImGui::Separator(); ImGui::Columns(2); - ImGuiUtils::EditProperty("ToneMapping", settings.gamma_tone_mapping); - ImGuiUtils::EditProperty("Exposure", ImGuiDataType_Float, &settings.exposure, 0.01, &mix_exposure); - ImGuiUtils::EditProperty("Gamma", ImGuiDataType_Float, &settings.gamma, 0.01, &min_gamma); + ImGuiUtils::EditProperty("ToneMapping", settings.GammaToneMapping); + ImGuiUtils::EditProperty("Exposure", ImGuiDataType_Float, &settings.Exposure, 0.01, &mix_exposure); + ImGuiUtils::EditProperty("Gamma", ImGuiDataType_Float, &settings.Gamma, 0.01, &min_gamma); ImGui::Columns(1); ImGui::Separator(); ImGui::Columns(2); - ImGuiUtils::EditProperty("DirectionalShadowMap", settings.use_directional_shadow_map); - ImGuiUtils::EditProperty("PointShadows", settings.use_point_shadows); + ImGuiUtils::EditProperty("DirectionalShadowMap", settings.UseDirectionalShadowMap); + ImGuiUtils::EditProperty("PointShadows", settings.UsePointShadows); ImGui::Columns(1); ImGui::Separator(); } @@ -46,6 +55,7 @@ namespace DE { } } void RendererPanel::SetScene(Ref scene) { - m_Scene = scene; + scene_ = scene; } -} // namespace DE \ No newline at end of file + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEditor/Panels/RendererPanel.h b/DummyEditor/Panels/RendererPanel.h index e8cef33..3b51baf 100644 --- a/DummyEditor/Panels/RendererPanel.h +++ b/DummyEditor/Panels/RendererPanel.h @@ -2,7 +2,12 @@ #include "DummyEditor/ImGuiUtils/ImGuiPanel.h" -namespace DE { +#include "DummyEngine/Utils/Types/Types.h" + +namespace DummyEngine { + + class Scene; + class RendererPanel : public ImGuiPanel { public: RendererPanel() : ImGuiPanel("Renderer") {} @@ -11,6 +16,7 @@ namespace DE { void SetScene(Ref scene); private: - WeakRef m_Scene; + WeakRef scene_; }; -} // namespace DE \ No newline at end of file + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEditor/Panels/SceneHierarchyPanel.cpp b/DummyEditor/Panels/SceneHierarchyPanel.cpp index b9cee6e..30f538f 100644 --- a/DummyEditor/Panels/SceneHierarchyPanel.cpp +++ b/DummyEditor/Panels/SceneHierarchyPanel.cpp @@ -1,20 +1,30 @@ -#include "DummyEditor/Panels/SceneHierarchyPanel.h" +#include "SceneHierarchyPanel.h" + +#include "DummyEditor/ImGuiUtils/ImGuiIcons.h" +#include "DummyEditor/ImGuiUtils/ImGuiUtils.h" + +#include "DummyEngine/Core/Scene/Components.h" +#include "DummyEngine/Utils/Debug/Profiler.h" + +#include +#include + +namespace DummyEngine { -namespace DE { void SceneHierarchyPanel::SetActiveScene(WeakRef scene) { - m_Scene = scene; - m_SelectedNode = SceneHierarchy::Node(); + scene_ = scene; + selected_node_ = SceneHierarchy::Node(); } void SceneHierarchyPanel::OnImGui() { DE_PROFILE_SCOPE("SceneHierarchyPanel OnImGui"); if (m_Controller) { if (ImGui::Begin(ICON_MD_ACCOUNT_TREE " Scene Hierarchy")) { - auto scene = m_Scene.lock(); + auto scene = scene_.lock(); if (scene) { - if (!m_WasTarget) { - m_To = SceneHierarchy::Node(); + if (!was_target_) { + to_ = SceneHierarchy::Node(); } - m_WasTarget = false; + was_target_ = false; ShowNode(scene->GetHierarchyRoot()); } } @@ -23,9 +33,9 @@ namespace DE { } Entity SceneHierarchyPanel::GetActiveEntity() { - auto scene = m_Scene.lock(); - if (scene && m_SelectedNode.IsEntity()) { - return m_SelectedNode.GetEntity(); + auto scene = scene_.lock(); + if (scene && selected_node_.IsEntity()) { + return selected_node_.GetEntity(); } return Entity(); } @@ -33,7 +43,7 @@ namespace DE { void SceneHierarchyPanel::ShowNodeContextMenu(SceneHierarchy::Node node) { if (node.IsFolder()) { if (ImGui::MenuItem("Create Entity")) { - auto entity = m_Scene.lock()->CreateEntity("Entity", false); + auto entity = scene_.lock()->CreateEntity("Entity", false); node.AddEntity(entity); ImGui::CloseCurrentPopup(); } @@ -42,10 +52,10 @@ namespace DE { ImGui::CloseCurrentPopup(); } if (ImGui::MenuItem("Rename")) { - m_Rename = node; + rename_ = node; ImGui::CloseCurrentPopup(); } - if (node.GetID() && ImGui::MenuItem("Delete")) { + if (node.GetID() != 0 && ImGui::MenuItem("Delete")) { auto parent = node.GetParent(); for (auto c : node.GetChilds()) { parent.Attach(c); @@ -57,7 +67,7 @@ namespace DE { if (node.IsEntity()) { if (ImGui::MenuItem("Clone")) { auto parent = node.GetParent(); - auto entity = m_Scene.lock()->CloneEntity(node.GetEntity()); + auto entity = scene_.lock()->CloneEntity(node.GetEntity()); parent.AddEntity(entity); ImGui::CloseCurrentPopup(); } @@ -72,7 +82,7 @@ namespace DE { bool open; if (node.IsFolder()) { ImGuiTreeNodeFlags flags = ImGuiTreeNodeFlags_DefaultOpen; - if (node != m_Rename) { + if (node != rename_) { flags |= ImGuiTreeNodeFlags_SpanFullWidth | ImGuiTreeNodeFlags_SpanAvailWidth; } ImGuiUtils::ScopedID id(node.GetID()); @@ -85,11 +95,11 @@ namespace DE { DropTarget(node); DragTarget(node); ImGui::SameLine(); - if (m_Rename == node) { + if (rename_ == node) { ImGui::SetKeyboardFocusHere(); if (ImGui::InputText( - "###FolderRename", &m_Rename.GetName(), ImGuiInputTextFlags_AutoSelectAll | ImGuiInputTextFlags_EnterReturnsTrue)) { - m_Rename = SceneHierarchy::Node(); + "###FolderRename", &rename_.GetName(), ImGuiInputTextFlags_AutoSelectAll | ImGuiInputTextFlags_EnterReturnsTrue)) { + rename_ = SceneHierarchy::Node(); } } else { ImGui::Text("%s", node.GetName().c_str()); @@ -107,11 +117,11 @@ namespace DE { if (node.IsEntity()) { ImGuiUtils::ScopedID id(node.GetID()); auto entity = node.GetEntity(); - std::string name = " " ICON_MD_CHECK_BOX_OUTLINE_BLANK " " + entity.Get().tag; - bool is_selected = (m_SelectedNode.IsEntity() ? m_SelectedNode.GetEntity() == entity : false); + std::string name = " " ICON_MD_CHECK_BOX_OUTLINE_BLANK " " + entity.Get().Tag; + bool is_selected = (selected_node_.IsEntity() ? selected_node_.GetEntity() == entity : false); if (ImGui::Selectable(name.c_str(), is_selected, ImGuiSelectableFlags_AllowDoubleClick | ImGuiSelectableFlags_SpanAllColumns) && ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left)) { - m_SelectedNode = node; + selected_node_ = node; } if (ImGui::BeginPopupContextItem()) { ShowNodeContextMenu(node); @@ -126,29 +136,29 @@ namespace DE { void SceneHierarchyPanel::DragTarget(SceneHierarchy::Node node) { ImGui::PushStyleVar(ImGuiStyleVar_Alpha, 1.0f); if (ImGui::BeginDragDropSource(ImGuiDragDropFlags_SourceNoHoldToOpenOthers)) { - m_From = node; - ImGui::Text("%s", GetDNDText(node, m_To).c_str()); + from_ = node; + ImGui::Text("%s", GetDNDText(node, to_).c_str()); ImGui::SetDragDropPayload("DND_HIERARCHY_NODE", &node, sizeof(node), ImGuiCond_Once); ImGui::EndDragDropSource(); } ImGui::PopStyleVar(); } void SceneHierarchyPanel::DropTarget(SceneHierarchy::Node node) { - if (!PossibleDND(m_From, node)) { + if (!PossibleDND(from_, node)) { return; } if (ImGui::BeginDragDropTarget()) { - m_To = node; - m_WasTarget = true; + to_ = node; + was_target_ = true; if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload("DND_HIERARCHY_NODE")) { auto from = *(SceneHierarchy::Node*)payload->Data; - if (from.Valid() && m_To.IsFolder()) { - m_To.Attach(from); + if (from.Valid() && to_.IsFolder()) { + to_.Attach(from); } - if (from.IsEntity() && m_To.IsEntity()) { - auto parent = m_To.GetParent(); + if (from.IsEntity() && to_.IsEntity()) { + auto parent = to_.GetParent(); auto folder = parent.AddFolder("Folder"); - folder.Attach(m_To); + folder.Attach(to_); folder.Attach(from); } } @@ -182,7 +192,7 @@ namespace DE { return message; } if (to.IsEntity() && from.IsEntity()) { - return "Create Folder with " + to.GetEntity().Get().tag + " and " + from.GetEntity().Get().tag; + return "Create Folder with " + to.GetEntity().Get().Tag + " and " + from.GetEntity().Get().Tag; } if (to.IsFolder() && from.Valid()) { std::string message = "Moving "; @@ -198,4 +208,5 @@ namespace DE { } return "Something went wrong"; } -} // namespace DE \ No newline at end of file + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEditor/Panels/SceneHierarchyPanel.h b/DummyEditor/Panels/SceneHierarchyPanel.h index a9b847f..70bd3d9 100644 --- a/DummyEditor/Panels/SceneHierarchyPanel.h +++ b/DummyEditor/Panels/SceneHierarchyPanel.h @@ -2,7 +2,10 @@ #include "DummyEditor/ImGuiUtils/ImGuiPanel.h" -namespace DE { +#include "DummyEngine/Core/Scene/Scene.h" + +namespace DummyEngine { + class SceneHierarchyPanel : public ImGuiPanel { public: SceneHierarchyPanel() : ImGuiPanel("Scene Hierarchy") {} @@ -19,11 +22,12 @@ namespace DE { bool PossibleDND(SceneHierarchy::Node from, SceneHierarchy::Node to); std::string GetDNDText(SceneHierarchy::Node from, SceneHierarchy::Node to); - WeakRef m_Scene; - SceneHierarchy::Node m_SelectedNode; - SceneHierarchy::Node m_From; - SceneHierarchy::Node m_To; - SceneHierarchy::Node m_Rename; - bool m_WasTarget = false; + WeakRef scene_; + SceneHierarchy::Node selected_node_; + SceneHierarchy::Node from_; + SceneHierarchy::Node to_; + SceneHierarchy::Node rename_; + bool was_target_ = false; }; -} // namespace DE \ No newline at end of file + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEditor/Panels/ThemePanel.cpp b/DummyEditor/Panels/ThemePanel.cpp index d0d615d..b0995ab 100644 --- a/DummyEditor/Panels/ThemePanel.cpp +++ b/DummyEditor/Panels/ThemePanel.cpp @@ -1,18 +1,21 @@ -#include "DummyEditor/Panels/ThemePanel.h" +#include "ThemePanel.h" -namespace DE { +#include "DummyEditor/ImGuiUtils/ImGuiIcons.h" +#include "DummyEngine/Utils/Debug/Profiler.h" + +namespace DummyEngine { ThemePanel::ThemePanel() : ImGuiPanel("ThemePanel") { SetDefaultTheme(); SetDefaultStyle(); } void ThemePanel::SetTheme(const EditorTheme& theme) { - m_ActiveTheme = theme; - m_ActiveTheme.Apply(); + active_theme_ = theme; + active_theme_.Apply(); } void ThemePanel::SetDefaultTheme() { - m_ActiveTheme = EditorTheme(); - m_ActiveTheme.Apply(); + active_theme_ = EditorTheme(); + active_theme_.Apply(); } void ThemePanel::OnImGui() { @@ -21,23 +24,23 @@ namespace DE { if (ImGui::Begin(ICON_MD_BRUSH " ThemePanel")) { ImGui::Separator(); ImGui::Columns(2); - ImGuiUtils::EditProperty("Background", m_ActiveTheme.Background, ImGuiUtils::PropertyType::Color); - ImGuiUtils::EditProperty("FieldBackground", m_ActiveTheme.FieldBackground, ImGuiUtils::PropertyType::Color); - ImGuiUtils::EditProperty("TitleBar", m_ActiveTheme.TitleBar, ImGuiUtils::PropertyType::Color); - ImGuiUtils::EditProperty("MenuBar", m_ActiveTheme.MenuBar, ImGuiUtils::PropertyType::Color); - ImGuiUtils::EditProperty("Header", m_ActiveTheme.Header, ImGuiUtils::PropertyType::Color); + ImGuiUtils::EditProperty("Background", active_theme_.Background, ImGuiUtils::PropertyType::Color); + ImGuiUtils::EditProperty("FieldBackground", active_theme_.FieldBackground, ImGuiUtils::PropertyType::Color); + ImGuiUtils::EditProperty("TitleBar", active_theme_.TitleBar, ImGuiUtils::PropertyType::Color); + ImGuiUtils::EditProperty("MenuBar", active_theme_.MenuBar, ImGuiUtils::PropertyType::Color); + ImGuiUtils::EditProperty("Header", active_theme_.Header, ImGuiUtils::PropertyType::Color); - ImGuiUtils::EditProperty("Text", m_ActiveTheme.Text, ImGuiUtils::PropertyType::Color); - ImGuiUtils::EditProperty("TextDisabled", m_ActiveTheme.TextDisabled, ImGuiUtils::PropertyType::Color); - ImGuiUtils::EditProperty("WidgetInactive", m_ActiveTheme.WidgetInactive, ImGuiUtils::PropertyType::Color); - ImGuiUtils::EditProperty("WidgetHovered", m_ActiveTheme.WidgetHovered, ImGuiUtils::PropertyType::Color); - ImGuiUtils::EditProperty("WidgetActive", m_ActiveTheme.WidgetActive, ImGuiUtils::PropertyType::Color); - ImGuiUtils::EditProperty("Button", m_ActiveTheme.Button, ImGuiUtils::PropertyType::Color); - ImGuiUtils::EditProperty("CheckMark", m_ActiveTheme.CheckMark, ImGuiUtils::PropertyType::Color); - ImGuiUtils::EditProperty("Default", m_ActiveTheme.Default, ImGuiUtils::PropertyType::Color); + ImGuiUtils::EditProperty("Text", active_theme_.Text, ImGuiUtils::PropertyType::Color); + ImGuiUtils::EditProperty("TextDisabled", active_theme_.TextDisabled, ImGuiUtils::PropertyType::Color); + ImGuiUtils::EditProperty("WidgetInactive", active_theme_.WidgetInactive, ImGuiUtils::PropertyType::Color); + ImGuiUtils::EditProperty("WidgetHovered", active_theme_.WidgetHovered, ImGuiUtils::PropertyType::Color); + ImGuiUtils::EditProperty("WidgetActive", active_theme_.WidgetActive, ImGuiUtils::PropertyType::Color); + ImGuiUtils::EditProperty("Button", active_theme_.Button, ImGuiUtils::PropertyType::Color); + ImGuiUtils::EditProperty("CheckMark", active_theme_.CheckMark, ImGuiUtils::PropertyType::Color); + ImGuiUtils::EditProperty("Default", active_theme_.Default, ImGuiUtils::PropertyType::Color); ImGui::Columns(1); ImGui::Separator(); - m_ActiveTheme.Apply(); + active_theme_.Apply(); } ImGui::End(); } @@ -134,4 +137,4 @@ namespace DE { colors[ImGuiCol_NavWindowingDimBg] = Default; colors[ImGuiCol_ModalWindowDimBg] = Default; } -} // namespace DE +} // namespace DummyEngine diff --git a/DummyEditor/Panels/ThemePanel.h b/DummyEditor/Panels/ThemePanel.h index 5ac9662..5b2b423 100644 --- a/DummyEditor/Panels/ThemePanel.h +++ b/DummyEditor/Panels/ThemePanel.h @@ -1,9 +1,11 @@ #pragma once -#include "DummyEditor/DummyEngineInclude.h" #include "DummyEditor/ImGuiUtils/ImGuiPanel.h" +#include "DummyEditor/ImGuiUtils/ImGuiUtils.h" -namespace DE { +#include + +namespace DummyEngine { struct EditorTheme { std::string Name; @@ -37,7 +39,7 @@ namespace DE { private: void SetDefaultStyle(); - EditorTheme m_ActiveTheme; + EditorTheme active_theme_; }; -} // namespace DE +} // namespace DummyEngine //*Enums for colors diff --git a/DummyEditor/Panels/ViewportPanel.cpp b/DummyEditor/Panels/ViewportPanel.cpp index e9d1f23..64d4971 100644 --- a/DummyEditor/Panels/ViewportPanel.cpp +++ b/DummyEditor/Panels/ViewportPanel.cpp @@ -1,8 +1,12 @@ -#include "DummyEditor/Panels/ViewportPanel.h" +#include "ViewportPanel.h" #include "DummyEditor/EditorLayer.h" -namespace DE { +#include "DummyEditor/ImGuiUtils/ImGuiIcons.h" +#include "DummyEngine/Core/Rendering/Renderer/FrameBuffer.h" + +namespace DummyEngine { + void ViewportPanel::OnImGui() { DE_PROFILE_SCOPE("ViewportPanel OnImGui"); if (m_Controller) { @@ -70,7 +74,7 @@ namespace DE { if (play) { ImGui::SetCursorPos(cursor_pos); cursor_pos.x += button_size.x + button_padding.x; - if (ImGui::ImageButton("Play", resources.play_icon->GetRendererId(), button_size)) { + if (ImGui::ImageButton("Play", resources.PlayIcon->GetRendererId(), button_size)) { if (state == State::Editing) { editor.ActionRunScene(); } else { @@ -81,35 +85,35 @@ namespace DE { if (pause) { ImGui::SetCursorPos(cursor_pos); cursor_pos.x += button_size.x + button_padding.x; - if (ImGui::ImageButton("Pause", resources.pause_icon->GetRendererId(), button_size)) { + if (ImGui::ImageButton("Pause", resources.PauseIcon->GetRendererId(), button_size)) { editor.ActionPauseScene(); } } if (step) { ImGui::SetCursorPos(cursor_pos); cursor_pos.x += button_size.x + button_padding.x; - if (ImGui::ImageButton("Step", resources.step_icon->GetRendererId(), button_size)) { + if (ImGui::ImageButton("Step", resources.StepIcon->GetRendererId(), button_size)) { editor.ActionStepScene(); } } if (stop) { ImGui::SetCursorPos(cursor_pos); cursor_pos.x += button_size.x + button_padding.x; - if (ImGui::ImageButton("Stop", resources.stop_icon->GetRendererId(), button_size)) { + if (ImGui::ImageButton("Stop", resources.StopIcon->GetRendererId(), button_size)) { editor.ActionStopScene(); } } if (build) { ImGui::SetCursorPos(cursor_pos); cursor_pos.x += button_size.x + button_padding.x; - if (ImGui::ImageButton("Build", resources.build_icon->GetRendererId(), button_size)) { + if (ImGui::ImageButton("Build", resources.BuildIcon->GetRendererId(), button_size)) { editor.ActionBuild(); } } if (build_and_run) { ImGui::SetCursorPos(cursor_pos); cursor_pos.x += button_size.x + button_padding.x; - if (ImGui::ImageButton("BuildAndRun", resources.build_and_run_icon->GetRendererId(), button_size)) { + if (ImGui::ImageButton("BuildAndRun", resources.BuildAndRunIcon->GetRendererId(), button_size)) { editor.ActionBuildAndRun(); } } @@ -117,4 +121,4 @@ namespace DE { void ViewportPanel::SetFrameBuffer(Ref buffer) { m_FrameBuffer = buffer; } -} // namespace DE \ No newline at end of file +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEditor/Panels/ViewportPanel.h b/DummyEditor/Panels/ViewportPanel.h index 33e2b2d..5a089ec 100644 --- a/DummyEditor/Panels/ViewportPanel.h +++ b/DummyEditor/Panels/ViewportPanel.h @@ -2,11 +2,18 @@ #include "DummyEditor/ImGuiUtils/ImGuiPanel.h" -namespace DE { +#include "DummyEngine/Utils/Types/Types.h" + +#include + +namespace DummyEngine { + + class FrameBuffer; + class ViewportPanel : public ImGuiPanel { public: ViewportPanel() : ImGuiPanel("Viewport") {} - ViewportPanel(const std::string& panelName) : ImGuiPanel(panelName) {} + explicit ViewportPanel(const std::string& panel_name) : ImGuiPanel(panel_name) {} virtual void OnImGui() override; void ToolPanel(); @@ -20,4 +27,5 @@ namespace DE { ImVec2 m_ViewportSize; WeakRef m_FrameBuffer; }; -} // namespace DE \ No newline at end of file + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEditor/Platform/Linux/Scripting/Compiler.cpp b/DummyEditor/Platform/Linux/Scripting/Compiler.cpp index c588bdf..3bda5fd 100644 --- a/DummyEditor/Platform/Linux/Scripting/Compiler.cpp +++ b/DummyEditor/Platform/Linux/Scripting/Compiler.cpp @@ -1,8 +1,8 @@ #include "DummyEditor/Scripting/Compiler.h" -namespace DE { +namespace DummyEngine { class LinuxCompilerImpl : public CompilerImpl { - LOGGER_AUTHOR(Compiler) + LOG_AUTHOR(Compiler) public: LinuxCompilerImpl() { AddDefine("DE_PLATFORM_LINUX"); } virtual bool Compile(const Path& source, const Path& destination) { @@ -122,4 +122,4 @@ namespace DE { return CreateScope(); } -}; // namespace DE \ No newline at end of file +}; // namespace DummyEngine \ No newline at end of file diff --git a/DummyEditor/Platform/Macos/Scripting/Compiler.cpp b/DummyEditor/Platform/Macos/Scripting/Compiler.cpp index eba9790..85a7fa7 100644 --- a/DummyEditor/Platform/Macos/Scripting/Compiler.cpp +++ b/DummyEditor/Platform/Macos/Scripting/Compiler.cpp @@ -1,6 +1,6 @@ #include "DummyEditor/Scripting/Compiler.h" -namespace DE { +namespace DummyEngine { class CompilerImpl { public: bool Compile(const Path& source, const Path& destination) { @@ -156,4 +156,4 @@ namespace DE { m_Impl->AddDefine(source); } -}; // namespace DE \ No newline at end of file +}; // namespace DummyEngine \ No newline at end of file diff --git a/DummyEditor/Platform/Windows/Scripting/Compiler.cpp b/DummyEditor/Platform/Windows/Scripting/Compiler.cpp index c835044..6058dd2 100644 --- a/DummyEditor/Platform/Windows/Scripting/Compiler.cpp +++ b/DummyEditor/Platform/Windows/Scripting/Compiler.cpp @@ -1,8 +1,13 @@ #include "DummyEditor/Scripting/Compiler.h" -namespace DE { +#include "DummyEngine/Core/Application/FileSystem.h" +#include "DummyEngine/Utils/Debug/Logger.h" + +#include + +namespace DummyEngine { class WindowsCompilerImpl : public CompilerImpl { - LOGGER_AUTHOR(Compiler) + LOG_AUTHOR(Compiler) public: WindowsCompilerImpl() { AddDefine("DE_PLATFORM_WINDOWS"); } virtual bool Compile(const Path& source, const Path& destination) { @@ -53,12 +58,12 @@ namespace DE { int res = system(link_command.c_str()); return res == 0; } - virtual void AddIncludeDir(const Path& dir) { m_IncludeDirs.insert(dir); } - virtual void DeleteIncludeDir(const Path& dir) { m_IncludeDirs.erase(dir); } - virtual void AddLinkLibrary(const Path& library) { m_Libraries.insert(library); } - virtual void DeleteLinkLibrary(const Path& library) { m_Libraries.erase(library); } - virtual void AddDefine(const std::string& define) { m_Defines.insert(define); } - virtual void DeleteDefine(const std::string& define) { m_Defines.erase(define); } + virtual void AddIncludeDir(const Path& dir) { include_dirs_.insert(dir); } + virtual void DeleteIncludeDir(const Path& dir) { include_dirs_.erase(dir); } + virtual void AddLinkLibrary(const Path& library) { libraries_.insert(library); } + virtual void DeleteLinkLibrary(const Path& library) { libraries_.erase(library); } + virtual void AddDefine(const std::string& define) { defines_.insert(define); } + virtual void DeleteDefine(const std::string& define) { defines_.erase(define); } private: std::string GetCompiler() { @@ -69,7 +74,7 @@ namespace DE { std::string AddIncludeDirArguments() { std::string res; - for (const auto& dir : m_IncludeDirs) { + for (const auto& dir : include_dirs_) { res.append(" -I "); res.append(dir.string()); } @@ -88,7 +93,7 @@ namespace DE { } std::string AddLinkArgs() { std::string res; - for (auto lib : m_Libraries) { + for (auto lib : libraries_) { std::string name = lib.stem().string(); lib.remove_filename(); if (lib.empty()) { @@ -103,7 +108,7 @@ namespace DE { } std::string AddDefines() { std::string res; - for (const auto& def : m_Defines) { + for (const auto& def : defines_) { res.append(" -D"); res.append(def); } @@ -113,13 +118,13 @@ namespace DE { return " -o " + destination.string() + "/" + library_name + ".dll"; } - std::unordered_set m_IncludeDirs; - std::unordered_set m_Libraries; - std::unordered_set m_Defines; + std::unordered_set include_dirs_; + std::unordered_set libraries_; + std::unordered_set defines_; }; Scope Compiler::CreateCompilerImpl() { return CreateScope(); } -}; // namespace DE +}; // namespace DummyEngine diff --git a/DummyEditor/Scripting/Compiler.cpp b/DummyEditor/Scripting/Compiler.cpp index f6fea85..98aa6c3 100644 --- a/DummyEditor/Scripting/Compiler.cpp +++ b/DummyEditor/Scripting/Compiler.cpp @@ -1,10 +1,11 @@ -#include "DummyEditor/Scripting/Compiler.h" +#include "Compiler.h" + +namespace DummyEngine { -namespace DE { SINGLETON_BASE(Compiler); S_INITIALIZE() { - m_Impl = CreateCompilerImpl(); + impl_ = CreateCompilerImpl(); AddIncludeDir(".."); AddIncludeDir("../Dependencies/GLM"); AddIncludeDir("../Dependencies/TRACY/public"); @@ -20,38 +21,38 @@ namespace DE { return Unit(); } S_METHOD_IMPL(bool, Compile, (const Path& source, const Path& destination), (source, destination)) { - return m_Impl->Compile(source, destination); + return impl_->Compile(source, destination); } S_METHOD_IMPL(bool, Link, (const std::vector& sources, const Path& destination, const std::string& library_name), (sources, destination, library_name)) { - return m_Impl->Link(sources, destination, library_name); + return impl_->Link(sources, destination, library_name); } S_METHOD_IMPL(Unit, AddIncludeDir, (const Path& dir), (dir)) { - m_Impl->AddIncludeDir(dir); + impl_->AddIncludeDir(dir); return Unit(); } S_METHOD_IMPL(Unit, DeleteIncludeDir, (const Path& dir), (dir)) { - m_Impl->DeleteIncludeDir(dir); + impl_->DeleteIncludeDir(dir); return Unit(); } S_METHOD_IMPL(Unit, AddLinkLibrary, (const Path& dir), (dir)) { - m_Impl->AddLinkLibrary(dir); + impl_->AddLinkLibrary(dir); return Unit(); } S_METHOD_IMPL(Unit, DeleteLinkLibrary, (const Path& dir), (dir)) { - m_Impl->DeleteLinkLibrary(dir); + impl_->DeleteLinkLibrary(dir); return Unit(); } S_METHOD_IMPL(Unit, AddDefine, (const std::string& dir), (dir)) { - m_Impl->AddDefine(dir); + impl_->AddDefine(dir); return Unit(); } S_METHOD_IMPL(Unit, DeleteDefine, (const std::string& dir), (dir)) { - m_Impl->DeleteDefine(dir); + impl_->DeleteDefine(dir); return Unit(); } -} // namespace DE \ No newline at end of file +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEditor/Scripting/Compiler.h b/DummyEditor/Scripting/Compiler.h index 848918b..ba6d8d0 100644 --- a/DummyEditor/Scripting/Compiler.h +++ b/DummyEditor/Scripting/Compiler.h @@ -1,6 +1,9 @@ -#include "DummyEditor/DummyEngineInclude.h" +#pragma once -namespace DE { +#include "DummyEngine/Utils/Helpers/Singleton.h" +#include "DummyEngine/Utils/Types/Types.h" + +namespace DummyEngine { class CompilerImpl { public: virtual ~CompilerImpl() = default; @@ -28,6 +31,6 @@ namespace DE { S_METHOD_DEF(Unit, DeleteDefine, (const std::string& source)); private: - Scope m_Impl; + Scope impl_; }; -} // namespace DE \ No newline at end of file +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEditor/Scripting/ScriptManager.cpp b/DummyEditor/Scripting/ScriptManager.cpp index b96fb52..75d046d 100644 --- a/DummyEditor/Scripting/ScriptManager.cpp +++ b/DummyEditor/Scripting/ScriptManager.cpp @@ -1,10 +1,13 @@ -#include "DummyEditor/Scripting/ScriptManager.h" +#include "ScriptManager.h" #include "DummyEditor/Scripting/Compiler.h" -namespace DE { +#include "DummyEngine/Core/Application/Config.h" +#include "DummyEngine/Core/ResourceManaging/AssetManager.h" + +namespace DummyEngine { Path PathToCompiledScript(Path path) { - return Config::GetPath(DE_CFG_SCRIPT_CACHE_PATH) / (fs::relative(path, Config::GetPath(DE_CFG_SCRIPT_PATH)).string() + ".o"); + return Config::Get().ScriptCachePath / (fs::relative(path, Config::Get().ScriptPath).string() + ".o"); } SINGLETON_BASE(ScriptManager); @@ -42,18 +45,18 @@ namespace DE { } for (const auto& script : scripts) { - ScriptEngine::AddScript(script.id); + ScriptEngine::AddScript(script.ID); } LOG_INFO("Loaded script for scene"); return true; } S_METHOD_IMPL(Unit, UnloadScripts, (const std::vector& scripts), (scripts)) { for (const auto& script : scripts) { - ScriptEngine::DeleteScript(script.id); + ScriptEngine::DeleteScript(script.ID); } - if (!m_LibraryName.empty()) { - ScriptEngine::DeleteLibrary(m_LibraryName); - m_LibraryName.clear(); + if (!library_name_.empty()) { + ScriptEngine::DeleteLibrary(library_name_); + library_name_.clear(); } LOG_INFO("Unloaded scripts"); return Unit(); @@ -100,8 +103,8 @@ namespace DE { return Unit(); } S_METHOD_IMPL(UUID, EditorScript, (const std::string& name), (name)) { - DE_ASSERT(m_EditorScriptNameToId.contains(name), "There is no editor script with name {}", name); - return m_EditorScriptNameToId.at(name); + DE_ASSERT(editor_script_name_to_id_.contains(name), "There is no editor script with name {}", name); + return editor_script_name_to_id_.at(name); } ScriptManager::ScriptStates ScriptManager::SaveSciptStates(Ref scene) { @@ -186,22 +189,22 @@ namespace DE { void ScriptManager::LoadEditorLibrary() { Ref library = CreateRef(); - bool editor_library_loaded = library->Load(Config::GetPath(DE_CFG_EXECUTABLE_PATH), DE_EDITOR_LIBRARY_NAME); + bool editor_library_loaded = library->Load(Config::Get().ExecutablePath, DE_EDITOR_LIBRARY_NAME); DE_ASSERT(editor_library_loaded, "Failed to load editor library {}", DE_EDITOR_LIBRARY_NAME); ScriptEngine::AddLibrary(library); } void ScriptManager::LoadEditorScripts() { - for (const auto& asset : m_EditorScriptAssets) { + for (const auto& asset : editor_script_assets_) { AssetManager::AddScriptAsset(asset); - ScriptEngine::AddScript(asset.id); + ScriptEngine::AddScript(asset.ID); } } std::vector ScriptManager::RecompilationList(const std::vector& scripts) { std::vector recompile_ids; for (size_t i = 0; i < scripts.size(); ++i) { - DE_ASSERT(fs::exists(scripts[i].path), "Failed to find script source file {}", scripts[i].path.string()); - if (NeedToCompile(scripts[i].path)) { + DE_ASSERT(fs::exists(scripts[i].Path), "Failed to find script source file {}", scripts[i].Path); + if (NeedToCompile(scripts[i].Path)) { recompile_ids.push_back(i); } } @@ -209,35 +212,35 @@ namespace DE { } std::optional ScriptManager::CompileSelected(const std::vector& scripts, const std::vector ids) { for (auto id : ids) { - if (!Compiler::Compile(scripts[id].path, PathToCompiledScript(scripts[id].path))) { - return scripts[id].path; + if (!Compiler::Compile(scripts[id].Path, PathToCompiledScript(scripts[id].Path))) { + return scripts[id].Path; } - m_CompiledScripts.insert(scripts[id].path); + compiler_scripts_.insert(scripts[id].Path); } return {}; } std::optional ScriptManager::LinkLibrary(const std::vector& scripts) { std::vector compiled_sources; for (const auto& script : scripts) { - compiled_sources.push_back(PathToCompiledScript(script.path)); + compiled_sources.push_back(PathToCompiledScript(script.Path)); } std::string new_name = AvailableName(); - return (Compiler::Link(compiled_sources, Config::GetPath(DE_CFG_SCRIPT_CACHE_PATH), new_name) ? new_name : std::optional()); + return (Compiler::Link(compiled_sources, Config::Get().ScriptCachePath, new_name) ? new_name : std::optional()); } bool ScriptManager::SwapLibrary(const std::string& name) { Ref library = CreateRef(); - if (!library->Load(Config::GetPath(DE_CFG_SCRIPT_CACHE_PATH), name)) { + if (!library->Load(Config::Get().ScriptCachePath, name)) { return false; } - if (!m_LibraryName.empty()) { - ScriptEngine::DeleteLibrary(m_LibraryName); + if (!library_name_.empty()) { + ScriptEngine::DeleteLibrary(library_name_); } ScriptEngine::AddLibrary(library); - m_LibraryName = name; + library_name_ = name; return true; } bool ScriptManager::NeedToCompile(const Path& path) { - if (!m_CompiledScripts.contains(path)) { + if (!compiler_scripts_.contains(path)) { return true; } Path object = PathToCompiledScript(path); @@ -248,9 +251,9 @@ namespace DE { } std::string ScriptManager::AvailableName() { // TODO: Generate available name properly - if (m_LibraryName.empty()) { + if (library_name_.empty()) { return "ScriptLibrary0"; } - return (m_LibraryName.back() == '0' ? "ScriptLibrary1" : "ScriptLibrary0"); + return (library_name_.back() == '0' ? "ScriptLibrary1" : "ScriptLibrary0"); } -} // namespace DE \ No newline at end of file +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEditor/Scripting/ScriptManager.h b/DummyEditor/Scripting/ScriptManager.h index f3e018c..5336b91 100644 --- a/DummyEditor/Scripting/ScriptManager.h +++ b/DummyEditor/Scripting/ScriptManager.h @@ -1,8 +1,19 @@ -#include "DummyEditor/DummyEngineInclude.h" -namespace DE { +#pragma once + +#include "DummyEngine/Core/ResourceManaging/Assets.h" +#include "DummyEngine/Core/Scripting/ScriptEngine.h" +#include "DummyEngine/Utils/Debug/Logger.h" +#include "DummyEngine/Utils/Helpers/Singleton.h" + +#include + +namespace DummyEngine { + class Scene; + class Entity; + class ScriptManager : public Singleton { - LOGGER_AUTHOR(ScriptManager) + LOG_AUTHOR(ScriptManager) SINGLETON(ScriptManager) public: S_METHOD_DEF(bool, LoadScripts, (const std::vector& scripts)); @@ -31,14 +42,15 @@ namespace DE { bool NeedToCompile(const Path& path); std::string AvailableName(); - std::unordered_set m_CompiledScripts; - std::string m_LibraryName; + std::unordered_set compiler_scripts_; + std::string library_name_; - const std::vector m_EditorScriptAssets = { + const std::vector editor_script_assets_ = { {UUID("0000000000000000000000000000f001"), "EditorCameraController", Path()} }; - const std::unordered_map m_EditorScriptNameToId = { + const std::unordered_map editor_script_name_to_id_ = { {"EditorCameraController", UUID("0000000000000000000000000000f001")} }; }; -} // namespace DE \ No newline at end of file + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEditor/Scripts/EditorCameraController.cpp b/DummyEditor/Scripts/EditorCameraController.cpp index 08f8021..a4e25dc 100644 --- a/DummyEditor/Scripts/EditorCameraController.cpp +++ b/DummyEditor/Scripts/EditorCameraController.cpp @@ -1,13 +1,13 @@ -#include "DummyEditor/DummyEngineInclude.h" +#include "DummyEngine/DummyEngine.h" -using namespace DE; +using namespace DummyEngine; class EditorCameraController : public Script { SCRIPT(EditorCameraController) public: virtual void OnUpdate(float dt) override { auto& camera = Get(); - if (active) { + if (active_) { float speed = 15; float sensitivity = 0.07; @@ -39,11 +39,11 @@ class EditorCameraController : public Script { camera.MoveInWorld(Vec3(0.0f, -1.0f, 0.0f) * speed * dt); } } - Get().translation = camera.GetPos(); + Get().Translation = camera.GetPos(); } private: - bool active = false; + bool active_ = false; }; -SCRIPT_BASE(EditorCameraController, FIELD(active)) +SCRIPT_BASE(EditorCameraController, FIELD(active_)) diff --git a/DummyEngine/CMakeLists.txt b/DummyEngine/CMakeLists.txt index 1458b0f..bade05b 100644 --- a/DummyEngine/CMakeLists.txt +++ b/DummyEngine/CMakeLists.txt @@ -22,4 +22,8 @@ if (${ENABLE_PRECOMPILED_HEADERS}) endif() if (${DE_ENABLE_CLANG_TIDY_ON_COMPILATION}) set_target_properties(DummyEngineLib PROPERTIES CXX_CLANG_TIDY "${CLANG_TIDY_COMMAND}") +endif() + +if ("${CMAKE_PLATFORM}" STREQUAL "WINDOWS") + target_compile_definitions(DummyEngineLib PUBLIC YAML_CPP_STATIC_DEFINE) endif() \ No newline at end of file diff --git a/DummyEngine/Core/Animations/Animation.cpp b/DummyEngine/Core/Animations/Animation.cpp index 41a00c7..015a211 100644 --- a/DummyEngine/Core/Animations/Animation.cpp +++ b/DummyEngine/Core/Animations/Animation.cpp @@ -1,19 +1,21 @@ #include "DummyEngine/Core/Animations/Animation.h" -namespace DE { +namespace DummyEngine { + BoneInfo* Animation::GetBone(const std::string& name) { - return (m_BoneNameToID.contains(name) ? &m_Bones[m_BoneNameToID[name]] : nullptr); + return (bone_name_to_id_.contains(name) ? &bones_[bone_name_to_id_[name]] : nullptr); } float Animation::GetTicksPerSecond() { - return m_TicksPerSecond; + return ticks_per_second_; } float Animation::GetDuration() { - return m_Duration; + return duration_; } const Animation::Node& Animation::GetRootNode() { - return m_RootNode; + return root_node_; } const std::unordered_map& Animation::GetBoneIDMap() { - return m_BoneNameToID; + return bone_name_to_id_; } -} // namespace DE + +} // namespace DummyEngine diff --git a/DummyEngine/Core/Animations/Animation.h b/DummyEngine/Core/Animations/Animation.h index 96081fb..96dadaa 100644 --- a/DummyEngine/Core/Animations/Animation.h +++ b/DummyEngine/Core/Animations/Animation.h @@ -2,13 +2,14 @@ #include "DummyEngine/Core/Animations/Bone.h" -namespace DE { +namespace DummyEngine { + class Animation { public: struct Node { - Mat4 transformation = Mat4(1.0); - std::string name; - std::vector childrens; + Mat4 Transformation = Mat4(1.0); + std::string Name; + std::vector Childrens; }; Animation() = default; @@ -21,10 +22,11 @@ namespace DE { private: friend class ModelLoader; - float m_Duration; - int m_TicksPerSecond; - Node m_RootNode; - std::vector m_Bones; - std::unordered_map m_BoneNameToID; + float duration_; + int ticks_per_second_; + Node root_node_; + std::vector bones_; + std::unordered_map bone_name_to_id_; }; -} // namespace DE + +} // namespace DummyEngine diff --git a/DummyEngine/Core/Animations/Animator.cpp b/DummyEngine/Core/Animations/Animator.cpp index 5db868f..78838ff 100644 --- a/DummyEngine/Core/Animations/Animator.cpp +++ b/DummyEngine/Core/Animations/Animator.cpp @@ -1,45 +1,47 @@ -#include "DummyEngine/Core/Animations/Animator.h" +#include "Animator.h" #include "DummyEngine/Core/Rendering/Renderer/Shader.h" -namespace DE { - Animator::Animator(Ref animation) : m_FinalBoneMatrices(MAX_BONES, Mat4(1.0f)) { - m_CurrentTime = 0.0; - m_CurrentAnimation = animation; - CalculateBoneTransform(&m_CurrentAnimation->GetRootNode(), Mat4(1.0f)); +namespace DummyEngine { + + Animator::Animator(Ref animation) : final_bone_matrices_(MAX_BONES, Mat4(1.0f)) { + current_time_ = 0.0; + current_animation_ = animation; + CalculateBoneTransform(¤t_animation_->GetRootNode(), Mat4(1.0f)); } void Animator::SetTime(float tm) { - auto next_time = fmod(tm, m_CurrentAnimation->GetDuration()); + auto next_time = fmod(tm, current_animation_->GetDuration()); // printf("Setting time %.06f\n", tm); - if (next_time != m_CurrentTime) { - m_CurrentTime = next_time; - CalculateBoneTransform(&m_CurrentAnimation->GetRootNode(), Mat4(1.0f)); + if (next_time != current_time_) { + current_time_ = next_time; + CalculateBoneTransform(¤t_animation_->GetRootNode(), Mat4(1.0f)); } } void Animator::UpdateAnimation(float dt) { - SetTime(m_CurrentAnimation->GetTicksPerSecond() * dt + m_CurrentTime); + SetTime(current_animation_->GetTicksPerSecond() * dt + current_time_); } void Animator::SetMatricies(Ref shader, const std::string& name) { - for (U32 i = 0; i < m_FinalBoneMatrices.size(); ++i) { - shader->SetMat4(std::format("{}[{}]", name, i), m_FinalBoneMatrices[i]); + for (U32 i = 0; i < final_bone_matrices_.size(); ++i) { + shader->SetMat4(std::format("{}[{}]", name, i), final_bone_matrices_[i]); } } Ref Animator::GetAnimation() { - return m_CurrentAnimation; + return current_animation_; } void Animator::CalculateBoneTransform(const Animation::Node* node, Mat4 parent_transform) { - Mat4 node_transform = node->transformation; - BoneInfo* bone_info = m_CurrentAnimation->GetBone(node->name); - if (bone_info) { - node_transform = bone_info->bone.GetTransform(m_CurrentTime); - m_FinalBoneMatrices[bone_info->bone.GetBoneID()] = parent_transform * node_transform * bone_info->offset; + Mat4 node_transform = node->Transformation; + BoneInfo* bone_info = current_animation_->GetBone(node->Name); + if (bone_info != nullptr) { + node_transform = bone_info->Bone.GetTransform(current_time_); + final_bone_matrices_[bone_info->Bone.GetBoneID()] = parent_transform * node_transform * bone_info->Offset; } Mat4 final_transform = parent_transform * node_transform; - for (U32 i = 0; i < node->childrens.size(); ++i) { - CalculateBoneTransform(&node->childrens[i], final_transform); + for (U32 i = 0; i < node->Childrens.size(); ++i) { + CalculateBoneTransform(&node->Childrens[i], final_transform); } } -} // namespace DE \ No newline at end of file + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Animations/Animator.h b/DummyEngine/Core/Animations/Animator.h index 4d71db0..87694fc 100644 --- a/DummyEngine/Core/Animations/Animator.h +++ b/DummyEngine/Core/Animations/Animator.h @@ -2,11 +2,13 @@ #include "DummyEngine/Core/Animations/Animation.h" -namespace DE { +namespace DummyEngine { + class Shader; class Animator { public: - Animator(Ref animation); + explicit Animator(Ref animation); + void SetTime(float tm); Ref GetAnimation(); @@ -14,10 +16,11 @@ namespace DE { void SetMatricies(Ref shader, const std::string& name = "u_BoneMatrices"); private: - void CalculateBoneTransform(const Animation::Node* node, Mat4 parentTransform); + void CalculateBoneTransform(const Animation::Node* node, Mat4 parent_transform); - std::vector m_FinalBoneMatrices; - Ref m_CurrentAnimation; - float m_CurrentTime; + std::vector final_bone_matrices_; + Ref current_animation_; + float current_time_; }; -} // namespace DE \ No newline at end of file + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Animations/Bone.cpp b/DummyEngine/Core/Animations/Bone.cpp index 6b3c908..03fa25c 100644 --- a/DummyEngine/Core/Animations/Bone.cpp +++ b/DummyEngine/Core/Animations/Bone.cpp @@ -1,19 +1,20 @@ -#include "DummyEngine/Core/Animations/Bone.h" +#include "Bone.h" -namespace DE { - Bone::Bone(const std::string& name, U32 ID) : m_Name(name), m_ID(ID), m_LocalTransform(1.0f) {} +namespace DummyEngine { - Mat4 Bone::GetTransform(float animationTime) { - Mat4 translation = InterpolatePosition(animationTime); - Mat4 rotation = InterpolateRotation(animationTime); - Mat4 scale = InterpolateScaling(animationTime); + Bone::Bone(const std::string& name, U32 id) : name_(name), id_(id) {} + + Mat4 Bone::GetTransform(float animation_time) { + Mat4 translation = InterpolatePosition(animation_time); + Mat4 rotation = InterpolateRotation(animation_time); + Mat4 scale = InterpolateScaling(animation_time); return translation * rotation * scale; } std::string Bone::GetBoneName() const { - return m_Name; + return name_; } U32 Bone::GetBoneID() const { - return m_ID; + return id_; } float Bone::GetScaleFactor(float prev_time, float next_time, float time) { @@ -25,73 +26,68 @@ namespace DE { } U32 Bone::GetPositionIndex(float time) { - for (U32 i = 0; i < m_Positions.size() - 1; ++i) { - if (time < m_Positions[i + 1].time_stamp) { + for (U32 i = 0; i < positions_.size() - 1; ++i) { + if (time < positions_[i + 1].TimeStamp) { return i; } } - return m_Positions.size() - 1; + return positions_.size() - 1; } U32 Bone::GetRotationIndex(float time) { - for (U32 i = 0; i < m_Rotations.size() - 1; ++i) { - if (time < m_Rotations[i + 1].time_stamp) { + for (U32 i = 0; i < rotations_.size() - 1; ++i) { + if (time < rotations_[i + 1].TimeStamp) { return i; } } - return m_Rotations.size() - 1; + return rotations_.size() - 1; } U32 Bone::GetScaleIndex(float time) { - for (U32 i = 0; i < m_Scales.size() - 1; ++i) { - if (time < m_Scales[i + 1].time_stamp) { + for (U32 i = 0; i < scales_.size() - 1; ++i) { + if (time < scales_[i + 1].TimeStamp) { return i; } } - return m_Scales.size() - 1; + return scales_.size() - 1; } Mat4 Bone::InterpolatePosition(float time) { - if (m_Positions.empty()) { + if (positions_.empty()) { return Mat4(1.0); } U32 i = GetPositionIndex(time); - // printf("pos %d\n", i); - if (i + 1 == m_Positions.size()) { - return glm::translate(Mat4(1.0f), m_Positions.back().position); + if (i + 1 == positions_.size()) { + return glm::translate(Mat4(1.0f), positions_.back().Position); } - float scale = GetScaleFactor(m_Positions[i].time_stamp, m_Positions[i + 1].time_stamp, time); - // printf("pos %d %.06f %.06f %.06f\n", i, scale, m_Positions[i].time_stamp, m_Positions[i + 1].time_stamp); - glm::vec3 pos = glm::mix(m_Positions[i].position, m_Positions[i + 1].position, scale); + float scale = GetScaleFactor(positions_[i].TimeStamp, positions_[i + 1].TimeStamp, time); + glm::vec3 pos = glm::mix(positions_[i].Position, positions_[i + 1].Position, scale); return glm::translate(Mat4(1.0f), pos); } Mat4 Bone::InterpolateRotation(float time) { - if (m_Rotations.empty()) { + if (rotations_.empty()) { return Mat4(1.0); } U32 i = GetRotationIndex(time); - if (i + 1 == m_Rotations.size()) { - return glm::toMat4(glm::normalize(m_Rotations.back().orientation)); + if (i + 1 == rotations_.size()) { + return glm::toMat4(glm::normalize(rotations_.back().Orientation)); } - float scale = GetScaleFactor(m_Rotations[i].time_stamp, m_Rotations[i + 1].time_stamp, time); - glm::quat rotation = glm::slerp(m_Rotations[i].orientation, m_Rotations[i + 1].orientation, scale); - // printf("rot %d %.06f %.06f %.06f\n", i, scale, m_Rotations[i].time_stamp, m_Rotations[i + 1].time_stamp); + float scale = GetScaleFactor(rotations_[i].TimeStamp, rotations_[i + 1].TimeStamp, time); + glm::quat rotation = glm::slerp(rotations_[i].Orientation, rotations_[i + 1].Orientation, scale); return glm::toMat4(glm::normalize(rotation)); } Mat4 Bone::InterpolateScaling(float time) { - if (m_Scales.empty()) { + if (scales_.empty()) { return Mat4(1.0); } U32 i = GetScaleIndex(time); - // printf("scale %d\n", i); - if (i + 1 == m_Scales.size()) { - return glm::scale(Mat4(1.0f), m_Scales.back().scale); + if (i + 1 == scales_.size()) { + return glm::scale(Mat4(1.0f), scales_.back().Scale); } - float scale = GetScaleFactor(m_Scales[i].time_stamp, m_Scales[i + 1].time_stamp, time); - glm::vec3 scaling = glm::mix(m_Scales[i].scale, m_Scales[i + 1].scale, scale); - // printf("scale %d %.06f %.06f %.06f\n", i, scale, m_Scales[i].time_stamp, m_Scales[i + 1].time_stamp); + float scale = GetScaleFactor(scales_[i].TimeStamp, scales_[i + 1].TimeStamp, time); + glm::vec3 scaling = glm::mix(scales_[i].Scale, scales_[i + 1].Scale, scale); return glm::scale(Mat4(1.0f), scaling); } -} // namespace DE +} // namespace DummyEngine /* */ \ No newline at end of file diff --git a/DummyEngine/Core/Animations/Bone.h b/DummyEngine/Core/Animations/Bone.h index 622b221..000815e 100644 --- a/DummyEngine/Core/Animations/Bone.h +++ b/DummyEngine/Core/Animations/Bone.h @@ -1,29 +1,30 @@ #pragma once -#include "DummyEngine/Utils/Base.h" +#include "DummyEngine/Utils/Types/Types.h" + +namespace DummyEngine { -namespace DE { struct KeyPosition { - Vec3 position; - float time_stamp; + Vec3 Position; + float TimeStamp; }; struct KeyRotation { - Quaternion orientation; - float time_stamp; + Quaternion Orientation; + float TimeStamp; }; struct KeyScale { - Vec3 scale; - float time_stamp; + Vec3 Scale; + float TimeStamp; }; class Bone { public: Bone() = default; - Bone(const std::string& name, U32 ID); + Bone(const std::string& name, U32 id); - Mat4 GetTransform(float animationTime); + Mat4 GetTransform(float animation_time); std::string GetBoneName() const; U32 GetBoneID() const; @@ -41,16 +42,16 @@ namespace DE { private: friend class ModelLoader; - std::vector m_Positions; - std::vector m_Rotations; - std::vector m_Scales; + std::vector positions_; + std::vector rotations_; + std::vector scales_; - std::string m_Name; - U32 m_ID; - Mat4 m_LocalTransform; + std::string name_; + U32 id_; }; struct BoneInfo { - Bone bone; - Mat4 offset = Mat4(1.0); + Bone Bone; + Mat4 Offset = Mat4(1.0); }; -} // namespace DE \ No newline at end of file + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Application/Application.cpp b/DummyEngine/Core/Application/Application.cpp index 858fb32..af59f6f 100644 --- a/DummyEngine/Core/Application/Application.cpp +++ b/DummyEngine/Core/Application/Application.cpp @@ -1,45 +1,53 @@ -#include "DummyEngine/Core/Application/Application.h" +#include "Application.h" +#include "DummyEngine/Core/Application/ImGuiLayer.h" +#include "DummyEngine/Core/Application/Input.h" +#include "DummyEngine/Core/Application/Window.h" +#include "DummyEngine/Core/Console/ConsoleLayer.hpp" #include "DummyEngine/Core/Rendering/Renderer/Renderer.h" +#include "DummyEngine/Utils/Debug/Profiler.h" + +#include + +namespace DummyEngine { -namespace DE { SINGLETON_BASE(Application); S_INITIALIZE() { // TODO: Customizeble name - m_Window = new Window(WindowState{.mode = WindowMode::Windowed, .name = "DummyEngine", .width = 1280, .height = 720}); - DE_ASSERT(m_Window, "Failed to allocate Windows"); - m_Window->SetEventCallback([](Event& e) { Application::OnEvent(e); }); + window_ = new Window(WindowState{.Mode = WindowMode::Windowed, .Name = "DummyEngine", .Width = 1280, .Height = 720}); + DE_ASSERT(window_, "Failed to allocate Windows"); + window_->SetEventCallback([](Event& e) { Application::OnEvent(e); }); - m_ImGuiLayer = new ImGuiLayer(); - DE_ASSERT(m_ImGuiLayer, "Failed to allocate ImGuiLayer"); - PushLayer(m_ImGuiLayer); + imgui_layer_ = new ImGuiLayer(); + DE_ASSERT(imgui_layer_, "Failed to allocate ImGuiLayer"); + PushLayer(imgui_layer_); - m_ConsoleLayer = new ConsoleLayer(); - DE_ASSERT(m_ConsoleLayer, "Failed to allocate ConsoleLayer"); - PushLayer(m_ConsoleLayer); + console_layer_ = new ConsoleLayer(); + DE_ASSERT(console_layer_, "Failed to allocate ConsoleLayer"); + PushLayer(console_layer_); SetUpCallbacks(); return Unit(); } S_TERMINATE() { - for (auto layer : m_Layers) { + for (auto layer : layers_) { layer->OnDetach(); delete layer; } - m_Layers.clear(); - delete m_Window; + layers_.clear(); + delete window_; return Unit(); } S_METHOD_IMPL(Unit, PushLayer, (Layer * layer), (layer)) { - m_Layers.push_back(layer); - layer->m_EventCallback = [](Event& e) { Application::OnEvent(e); }; + layers_.push_back(layer); + layer->event_callback_ = [](Event& e) { Application::OnEvent(e); }; layer->OnAttach(); return Unit(); } S_METHOD_IMPL(Unit, OnEvent, (Event & event), (event)) { - m_EventDispatcher.Dispatch(event); - for (auto it = m_Layers.rbegin(); it != m_Layers.rend(); ++it) { + event_dispatcher_.Dispatch(event); + for (auto it = layers_.rbegin(); it != layers_.rend(); ++it) { (*it)->OnEvent(event); } return Unit(); @@ -48,7 +56,7 @@ namespace DE { double frame_begin = glfwGetTime(); double frame_end; double prev_frame_time = 0.001; - while (!m_ShouldClose) { + while (!should_close_) { DE_PROFILER_BEGIN_FRAME(); DE_PROFILE_SCOPE("Aplication loop"); @@ -59,22 +67,22 @@ namespace DE { Renderer::BeginFrame(); Input::NewFrame(); - m_Window->OnUpdate(); + window_->OnUpdate(); { DE_PROFILE_SCOPE("Layers OnUpdate"); - for (auto layer : m_Layers) { + for (auto layer : layers_) { layer->OnUpdate(prev_frame_time); } } { DE_PROFILE_SCOPE("Layers OnImGuiRender"); Renderer::SetDefaultFrameBuffer(); - m_ImGuiLayer->BeginFrame(); - for (auto layer : m_Layers) { + imgui_layer_->BeginFrame(); + for (auto layer : layers_) { layer->OnImGuiRender(); } - m_ImGuiLayer->EndFrame(); + imgui_layer_->EndFrame(); } Renderer::EndFrame(); @@ -82,38 +90,38 @@ namespace DE { return Unit(); } S_METHOD_IMPL(Window&, GetWindow, (), ()) { - return *m_Window; + return *window_; } void Application::SetUpCallbacks() { - m_EventDispatcher.AddEventListener([this](WindowResizeEvent& event) { OnWindowResize(event); }); - m_EventDispatcher.AddEventListener([this](WindowCloseEvent& event) { OnWindowClose(event); }); - m_EventDispatcher.AddEventListener( - [this](SetWindowModeFullscreenEvent& event) { m_Window->FullScreen(event.GetMonitorId()); }); - m_EventDispatcher.AddEventListener( - [this](SetWindowModeWindowedEvent& event) { m_Window->Windowed(event.GetWidth(), event.GetHeight(), event.GetXPos(), event.GetYPos()); }); - m_EventDispatcher.AddEventListener([this](SetMouseLockEvent& event) { - m_Window->LockMouse(); + event_dispatcher_.AddEventListener([this](WindowResizeEvent& event) { OnWindowResize(event); }); + event_dispatcher_.AddEventListener([this](WindowCloseEvent& event) { OnWindowClose(event); }); + event_dispatcher_.AddEventListener( + [this](SetWindowModeFullscreenEvent& event) { window_->FullScreen(event.GetMonitorId()); }); + event_dispatcher_.AddEventListener( + [this](SetWindowModeWindowedEvent& event) { window_->Windowed(event.GetWidth(), event.GetHeight(), event.GetXPos(), event.GetYPos()); }); + event_dispatcher_.AddEventListener([this](SetMouseLockEvent& event) { + window_->LockMouse(); Input::OnEvent(event); }); - m_EventDispatcher.AddEventListener([this](SetMouseUnlockEvent& event) { - m_Window->UnlockMouse(); + event_dispatcher_.AddEventListener([this](SetMouseUnlockEvent& event) { + window_->UnlockMouse(); Input::OnEvent(event); }); - m_EventDispatcher.AddEventListener([this](SetMouseLockToggleEvent& event) { - m_Window->ToggleMouseLock(); + event_dispatcher_.AddEventListener([this](SetMouseLockToggleEvent& event) { + window_->ToggleMouseLock(); Input::OnEvent(event); }); - m_EventDispatcher.AddEventListener(Input::OnEvent); - m_EventDispatcher.AddEventListener(Input::OnEvent); - m_EventDispatcher.AddEventListener(Input::OnEvent); + event_dispatcher_.AddEventListener(Input::OnEvent); + event_dispatcher_.AddEventListener(Input::OnEvent); + event_dispatcher_.AddEventListener(Input::OnEvent); } void Application::OnWindowResize(WindowResizeEvent& e) { Renderer::SetViewport(e.GetWidth(), e.GetHeight()); } void Application::OnWindowClose(WindowCloseEvent&) { - m_ShouldClose = true; + should_close_ = true; } -} // namespace DE +} // namespace DummyEngine diff --git a/DummyEngine/Core/Application/Application.h b/DummyEngine/Core/Application/Application.h index 7326c4f..ae98ffb 100644 --- a/DummyEngine/Core/Application/Application.h +++ b/DummyEngine/Core/Application/Application.h @@ -1,11 +1,14 @@ #pragma once -#include "DummyEngine/Core/Application/ImGuiLayer.h" -#include "DummyEngine/Core/Application/Input.h" -#include "DummyEngine/Core/Application/Window.h" -#include "DummyEngine/Core/Console/ConsoleLayer.hpp" +#include "DummyEngine/Core/Application/Event.h" +#include "DummyEngine/Utils/Helpers/Singleton.h" -namespace DE { +namespace DummyEngine { + + class Window; + class ConsoleLayer; + class ImGuiLayer; + class Layer; class Application : public Singleton { SINGLETON(Application) @@ -23,11 +26,11 @@ namespace DE { void OnWindowResize(WindowResizeEvent& e); void OnWindowClose(WindowCloseEvent& e); - bool m_ShouldClose; - EventDispatcher m_EventDispatcher; - std::vector m_Layers; - ImGuiLayer* m_ImGuiLayer; - ConsoleLayer* m_ConsoleLayer; - Window* m_Window; + bool should_close_; + EventDispatcher event_dispatcher_; + std::vector layers_; + ImGuiLayer* imgui_layer_; + ConsoleLayer* console_layer_; + Window* window_; }; -} // namespace DE \ No newline at end of file +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Application/Config.cpp b/DummyEngine/Core/Application/Config.cpp index d61cb24..c8a206c 100644 --- a/DummyEngine/Core/Application/Config.cpp +++ b/DummyEngine/Core/Application/Config.cpp @@ -1,66 +1,39 @@ -#include "DummyEngine/Core/Application/Config.h" +#include "Config.h" -namespace DE { - Config::Configs Config::m_Configs; +#include - U32 Config::GetI(U32 setting) { - switch (setting) { - case DE_CFG_MAX_COMPILE_ERROR_LEN: return m_Configs.c_MaxShaderCompileErrorLen; - case DE_CFG_MAX_INPUT_FRAME_AMOUNT: return m_Configs.c_MaxInputFrameAmount; - default: DE_ASSERT(false, "Wrong config requested {}", setting); - } - return 0; - } - float Config::GetF(U32 setting) { - switch (setting) { - case DE_CFG_DEFAULT_CAMERA_FOV: return m_Configs.c_DefaultCameraFOV; - case DE_CFG_DEFAULT_CAMERA_ASPECT: return m_Configs.c_DefaultCameraAspect; - case DE_CFG_DEFAULT_CAMERA_NEAR_PLANE: return m_Configs.c_DefaultCameraNearPlane; - case DE_CFG_DEFAULT_CAMERA_FAR_PLANE: return m_Configs.c_DefaultCameraFarPlane; - default: DE_ASSERT(false, "Wrong config requested {}", setting); - } - return 0; - } - Path Config::GetPath(U32 setting) { - switch (setting) { - case DE_CFG_EXECUTABLE_PATH: return m_Configs.c_ExecutablePath; - case DE_CFG_ASSET_PATH: return m_Configs.c_AssetPath; - case DE_CFG_LOG_PATH: return m_Configs.c_LogPath; - case DE_CFG_MODEL_PATH: return m_Configs.c_ModelPath; - case DE_CFG_SHADER_PATH: return m_Configs.c_ShaderPath; - case DE_CFG_TEXTURE_PATH: return m_Configs.c_TexturePath; - case DE_CFG_SCRIPT_PATH: return m_Configs.c_ScriptPath; - case DE_CFG_CACHE_PATH: return m_Configs.c_CachePath; - case DE_CFG_SCRIPT_CACHE_PATH: return m_Configs.c_ScriptCachePath; - case DE_CFG_FONT_PATH: return m_Configs.c_FontPath; - case DE_CFG_SCENE_PATH: return m_Configs.c_ScenePath; - default: DE_ASSERT(false, "Wrong config requested {}", setting); - } - return Path("."); +namespace DummyEngine { + + SINGLETON_BASE(Config); + + S_INITIALIZE() { + fields_.ExecutablePath = fs::current_path(); + std::cout << "Executable path: " << fields_.ExecutablePath.string() << std::endl; + + fields_.AssetPath = fields_.ExecutablePath / "Assets"; + fields_.LogPath = fields_.ExecutablePath / "Logs"; + fields_.ModelPath = fields_.AssetPath / "Models"; + fields_.ShaderPath = fields_.AssetPath / "Shaders"; + fields_.TexturePath = fields_.AssetPath / "Textures"; + fields_.ScriptPath = fields_.AssetPath / "Scripts"; + fields_.CachePath = fields_.ExecutablePath / "Cache"; + fields_.ScriptCachePath = fields_.CachePath / "Scripts"; + fields_.FontPath = fields_.AssetPath / "Fonts"; + fields_.ScenePath = fields_.AssetPath / "Scenes"; + + fields_.RendererAPI = API::OpenGL; + + return Unit(); } - API Config::GetRenderAPI() { - return m_Configs.c_RenderAPI; + S_TERMINATE() { + return Unit(); } - void Config::Initialize() { - m_Configs.c_ExecutablePath = fs::current_path(); - std::cout << "Executable path: " << m_Configs.c_ExecutablePath.string() << std::endl; - - m_Configs.c_AssetPath = m_Configs.c_ExecutablePath / "Assets"; - m_Configs.c_LogPath = m_Configs.c_ExecutablePath / "Logs"; - m_Configs.c_ModelPath = m_Configs.c_AssetPath / "Models"; - m_Configs.c_ShaderPath = m_Configs.c_AssetPath / "Shaders"; - m_Configs.c_TexturePath = m_Configs.c_AssetPath / "Textures"; - m_Configs.c_ScriptPath = m_Configs.c_AssetPath / "Scripts"; - m_Configs.c_CachePath = m_Configs.c_ExecutablePath / "Cache"; - m_Configs.c_ScriptCachePath = m_Configs.c_CachePath / "Scripts"; - m_Configs.c_FontPath = m_Configs.c_AssetPath / "Fonts"; - m_Configs.c_ScenePath = m_Configs.c_AssetPath / "Scenes"; - m_Configs.c_RenderAPI = API::OpenGL; + S_METHOD_IMPL(const Config::Fields&, Get, (), ()) { + return fields_; } - void Config::Terminate() {} - Path RelativeToExecutable(const Path& path) { - return fs::relative(path, Config::GetPath(DE_CFG_EXECUTABLE_PATH)); + S_METHOD_IMPL(Path, RelativeToExecutable, (const Path& path), (path)) { + return fs::relative(path, fields_.ExecutablePath); } -} // namespace DE \ No newline at end of file +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Application/Config.h b/DummyEngine/Core/Application/Config.h index 9441ccc..66767ad 100644 --- a/DummyEngine/Core/Application/Config.h +++ b/DummyEngine/Core/Application/Config.h @@ -1,72 +1,41 @@ #pragma once -#include "DummyEngine/Utils/Base.h" - -namespace DE { - -#define DE_CFG_MAX_COMPILE_ERROR_LEN 1 -#define DE_CFG_MAX_INPUT_FRAME_AMOUNT 2 - -#define DE_CFG_DEFAULT_CAMERA_FOV 1 -#define DE_CFG_DEFAULT_CAMERA_ASPECT 2 -#define DE_CFG_DEFAULT_CAMERA_NEAR_PLANE 3 -#define DE_CFG_DEFAULT_CAMERA_FAR_PLANE 4 - -#define DE_CFG_EXECUTABLE_PATH 1 -#define DE_CFG_ASSET_PATH 2 -#define DE_CFG_LOG_PATH 3 -#define DE_CFG_MODEL_PATH 4 -#define DE_CFG_SHADER_PATH 5 -#define DE_CFG_TEXTURE_PATH 6 -#define DE_CFG_SCRIPT_PATH 7 -#define DE_CFG_FONT_PATH 8 -#define DE_CFG_SCENE_PATH 11 - -#define DE_CFG_CACHE_PATH 9 -#define DE_CFG_SCRIPT_CACHE_PATH 10 - -#define DE_CFG_RENDER_API 1 - - // TODO: Singleton +#include "DummyEngine/Utils/Helpers/Singleton.h" +#include "DummyEngine/Utils/Types/Types.h" + +namespace DummyEngine { + + class Config : public Singleton { + SINGLETON(Config) + + struct Fields { + U32 MaxShaderCompileErrorLen = 512; + U32 MaxInputFrameAmount = 100; + U32 MaxMessageTypeLength = 7; + + Path ExecutablePath; + Path ShaderPath; + Path ModelPath; + Path AssetPath; + Path LogPath; + Path TexturePath; + Path CachePath; + Path ScriptPath; + Path ScriptCachePath; + Path FontPath; + Path ScenePath; + + API RendererAPI; + }; - class Config { public: - static U32 GetI(U32 setting); - static float GetF(U32 setting); - static Path GetPath(U32 setting); - - static API GetRenderAPI(); + S_METHOD_DEF(const Fields&, Get, ()); - static void Initialize(); - static void Terminate(); + S_METHOD_DEF(Path, RelativeToExecutable, (const Path& path)); private: - struct Configs { - U32 c_MaxShaderCompileErrorLen = 512; - U32 c_MaxInputFrameAmount = 100; - U32 c_MaxMessageTypeLength = 7; - - float c_DefaultCameraFOV = 90.0f; - float c_DefaultCameraAspect = 16.0f / 9.0f; - float c_DefaultCameraNearPlane = 0.1f; - float c_DefaultCameraFarPlane = 2'000'000.0f; - - Path c_ExecutablePath; - Path c_ShaderPath; - Path c_ModelPath; - Path c_AssetPath; - Path c_LogPath; - Path c_TexturePath; - Path c_CachePath; - Path c_ScriptPath; - Path c_ScriptCachePath; - Path c_FontPath; - Path c_ScenePath; - - API c_RenderAPI; - }; - static Configs m_Configs; + Fields fields_; }; Path RelativeToExecutable(const Path& path); -} // namespace DE \ No newline at end of file +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Application/EntryPoint.h b/DummyEngine/Core/Application/EntryPoint.h index 8b31022..52fb62b 100644 --- a/DummyEngine/Core/Application/EntryPoint.h +++ b/DummyEngine/Core/Application/EntryPoint.h @@ -2,20 +2,19 @@ #include "DummyEngine/Core/Application/Application.h" #include "DummyEngine/Core/Application/Initializer.h" -#include "DummyEngine/Utils/Base.h" -namespace DE { +namespace DummyEngine { extern void SetupApplication(); } int main() { try { - DE::Initializer::Initialize(); + DummyEngine::Initializer::Initialize(); - DE::SetupApplication(); - DE::Application::Run(); + DummyEngine::SetupApplication(); + DummyEngine::Application::Run(); - DE::Initializer::Terminate(); + DummyEngine::Initializer::Terminate(); } catch (const std::exception& e) { LOG_FATAL_AS("EntryPoint", "Unhandled exeption occured: {}", e.what()); return -1; diff --git a/DummyEngine/Core/Application/Event.h b/DummyEngine/Core/Application/Event.h index 7fcfaba..f0732ce 100644 --- a/DummyEngine/Core/Application/Event.h +++ b/DummyEngine/Core/Application/Event.h @@ -1,8 +1,8 @@ #pragma once -#include "DummyEngine/Utils/Base.h" +#include "DummyEngine/Utils/Types/Types.h" -namespace DE { +namespace DummyEngine { template using EventCallback = std::function; enum class EventType { @@ -43,17 +43,17 @@ namespace DE { public: template void AddEventListener(EventCallback callback) { auto base_callback = [func = std::move(callback)](Event& e) { func(static_cast(e)); }; - m_EventCallbacks[(size_t)ListeningEvent::Type()].push_back(base_callback); + event_callbacks_[(size_t)ListeningEvent::Type()].push_back(base_callback); } void Dispatch(Event& event) { - for (auto& callback : m_EventCallbacks[(size_t)(event.GetType())]) { + for (auto& callback : event_callbacks_[(size_t)(event.GetType())]) { callback(event); } } private: - std::array>, static_cast(EventType::Count)> m_EventCallbacks; + std::array>, static_cast(EventType::Count)> event_callbacks_; }; #define EVENT_TYPE(type) \ @@ -68,16 +68,16 @@ namespace DE { class WindowResizeEvent : public Event { public: - WindowResizeEvent(U32 width, U32 height) : m_Width(width), m_Height(height) {} + WindowResizeEvent(U32 width, U32 height) : width_(width), height_(height) {} - U32 GetWidth() const { return m_Width; } - U32 GetHeight() const { return m_Height; } + U32 GetWidth() const { return width_; } + U32 GetHeight() const { return height_; } EVENT_TYPE(WindowResize); private: - U32 m_Width; - U32 m_Height; + U32 width_; + U32 height_; }; class WindowCloseEvent : public Event { public: @@ -88,106 +88,106 @@ namespace DE { class KeyPressedEvent : public Event { public: - KeyPressedEvent(U32 key) : m_KeyKode(key) {} + explicit KeyPressedEvent(U32 key) : key_code_(key) {} - U32 GetKey() const { return m_KeyKode; } + U32 GetKey() const { return key_code_; } EVENT_TYPE(KeyPressed); private: - U32 m_KeyKode; + U32 key_code_; }; class KeyReleasedEvent : public Event { public: - KeyReleasedEvent(U32 key) : m_KeyKode(key) {} + explicit KeyReleasedEvent(U32 key) : key_code_(key) {} - U32 GetKey() const { return m_KeyKode; } + U32 GetKey() const { return key_code_; } EVENT_TYPE(KeyReleased); private: - U32 m_KeyKode; + U32 key_code_; }; class MouseButtonPressedEvent : public Event { public: - MouseButtonPressedEvent(U32 key) : m_KeyKode(key) {} + explicit MouseButtonPressedEvent(U32 key) : key_code_(key) {} - U32 GetKey() const { return m_KeyKode; } + U32 GetKey() const { return key_code_; } EVENT_TYPE(MouseButtonPressed); private: - U32 m_KeyKode; + U32 key_code_; }; class MouseButtonReleasedEvent : public Event { public: - MouseButtonReleasedEvent(U32 key) : m_KeyKode(key) {} + explicit MouseButtonReleasedEvent(U32 key) : key_code_(key) {} - U32 GetKey() const { return m_KeyKode; } + U32 GetKey() const { return key_code_; } EVENT_TYPE(MouseButtonReleased); private: - U32 m_KeyKode; + U32 key_code_; }; class MouseScrolledEvent : public Event { public: - MouseScrolledEvent(float x_offset, float y_offset) : m_XPos(x_offset), m_YPos(y_offset) {} + MouseScrolledEvent(float x_offset, float y_offset) : x_pos_(x_offset), y_pos_(y_offset) {} - float GetXOffset() const { return m_XPos; } - float GetYOffset() const { return m_YPos; } + float GetXOffset() const { return x_pos_; } + float GetYOffset() const { return y_pos_; } EVENT_TYPE(MouseScrolled); private: - float m_XPos; - float m_YPos; + float x_pos_; + float y_pos_; }; class MouseMovedCallback : public Event { public: - MouseMovedCallback(float x_pos, float y_pos) : m_XPos(x_pos), m_YPos(y_pos) {} + MouseMovedCallback(float x_pos, float y_pos) : x_pos_(x_pos), y_pos_(y_pos) {} - float GetXPos() const { return m_XPos; } - float GetYPos() const { return m_YPos; } + float GetXPos() const { return x_pos_; } + float GetYPos() const { return y_pos_; } EVENT_TYPE(MouseMoved); private: - float m_XPos; - float m_YPos; + float x_pos_; + float y_pos_; }; //*Triggering class SetWindowModeWindowedEvent : public Event { public: - SetWindowModeWindowedEvent(U32 width = 1280, U32 height = 720, U32 x_pos = 100, U32 y_pos = 100) : - m_Width(width), m_Height(height), m_XPos(x_pos), m_YPos(y_pos) {} + explicit SetWindowModeWindowedEvent(U32 width = 1280, U32 height = 720, U32 x_pos = 100, U32 y_pos = 100) : + width_(width), height_(height), x_pos_(x_pos), y_pos_(y_pos) {} - U32 GetWidth() const { return m_Width; } - U32 GetHeight() const { return m_Height; } - U32 GetXPos() const { return m_XPos; } - U32 GetYPos() const { return m_YPos; } + U32 GetWidth() const { return width_; } + U32 GetHeight() const { return height_; } + U32 GetXPos() const { return x_pos_; } + U32 GetYPos() const { return y_pos_; } EVENT_TYPE(SetWindowModeWindowed); private: - U32 m_Width; - U32 m_Height; - U32 m_XPos; - U32 m_YPos; + U32 width_; + U32 height_; + U32 x_pos_; + U32 y_pos_; }; class SetWindowModeFullscreenEvent : public Event { public: - SetWindowModeFullscreenEvent(U32 monitor_id) : m_MonitorId(monitor_id) {} + explicit SetWindowModeFullscreenEvent(U32 monitor_id) : monitor_id_(monitor_id) {} - U32 GetMonitorId() const { return m_MonitorId; } + U32 GetMonitorId() const { return monitor_id_; } EVENT_TYPE(SetWindowModeFullscreen); private: - U32 m_MonitorId; + U32 monitor_id_; }; class SetMouseLockEvent : public Event { @@ -209,4 +209,4 @@ namespace DE { EVENT_TYPE(SetMouseLockToggle); }; -} // namespace DE \ No newline at end of file +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Application/FileSystem.cpp b/DummyEngine/Core/Application/FileSystem.cpp index 00bb66f..a75587d 100644 --- a/DummyEngine/Core/Application/FileSystem.cpp +++ b/DummyEngine/Core/Application/FileSystem.cpp @@ -1,22 +1,22 @@ -#include "DummyEngine/Core/Application/FileSystem.h" +#include "FileSystem.h" #include -namespace DE { +namespace DummyEngine { using namespace std::string_literals; Path FileSystem::OpenFileDialog(const std::string& description, const std::string& filter, const Path& default_path) { Path path = Path(); NFD_Init(); - nfdchar_t* outPath; - nfdfilteritem_t filterItem[1] = { + nfdchar_t* out_path; + nfdfilteritem_t filter_item[1] = { {description.c_str(), filter.c_str()} }; - nfdresult_t result = NFD_OpenDialog(&outPath, filterItem, 1, default_path.empty() ? nullptr : default_path.string().c_str()); + nfdresult_t result = NFD_OpenDialog(&out_path, filter_item, 1, default_path.empty() ? nullptr : default_path.string().c_str()); if (result == NFD_OKAY) { - path = Path(outPath); - NFD_FreePath(outPath); + path = Path(out_path); + NFD_FreePath(out_path); } NFD_Quit(); return path; @@ -28,19 +28,18 @@ namespace DE { const Path& default_path) { Path path = Path(); NFD_Init(); - nfdchar_t* outPath; - nfdfilteritem_t filterItem[1] = { - {description.c_str(), filter.c_str()} - }; - nfdresult_t result = NFD_SaveDialog(&outPath, - filterItem, + nfdchar_t* out_path; + nfdfilteritem_t filter_item = {description.c_str(), filter.c_str()}; + + nfdresult_t result = NFD_SaveDialog(&out_path, + &filter_item, 1, (default_path.empty() ? nullptr : default_path.string().c_str()), (default_name.empty() ? nullptr : default_name.c_str())); if (result == NFD_OKAY) { - std::string s(outPath); + std::string s(out_path); path = Path(s); - NFD_FreePath(outPath); + NFD_FreePath(out_path); } NFD_Quit(); return path; @@ -52,4 +51,5 @@ namespace DE { bool FileSystem::CreateDirectory(const Path& path) { return fs::create_directories(path); } -} // namespace DE \ No newline at end of file + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Application/FileSystem.h b/DummyEngine/Core/Application/FileSystem.h index d588eec..ffe7e96 100644 --- a/DummyEngine/Core/Application/FileSystem.h +++ b/DummyEngine/Core/Application/FileSystem.h @@ -1,8 +1,9 @@ #pragma once -#include "DummyEngine/Utils/Base.h" +#include "DummyEngine/Utils/Types/Types.h" + +namespace DummyEngine { -namespace DE { class FileSystem { public: static Path OpenFileDialog(const std::string& description, const std::string& filter, const Path& default_path = Path()); @@ -15,4 +16,4 @@ namespace DE { static bool CreateDirectory(const Path& path); }; -} // namespace DE \ No newline at end of file +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Application/ImGuiLayer.cpp b/DummyEngine/Core/Application/ImGuiLayer.cpp index 6716dff..ad65f98 100644 --- a/DummyEngine/Core/Application/ImGuiLayer.cpp +++ b/DummyEngine/Core/Application/ImGuiLayer.cpp @@ -1,4 +1,8 @@ -#include "DummyEngine/Core/Application/ImGuiLayer.h" +#include "ImGuiLayer.h" + +#include "DummyEngine/Core/Application/Application.h" +#include "DummyEngine/Core/Application/Window.h" +#include "DummyEngine/Utils/Debug/Profiler.h" // clang-format off #include @@ -8,9 +12,7 @@ #include // clang-format on -#include "DummyEngine/Core/Application/Application.h" - -namespace DE { +namespace DummyEngine { ImGuiLayer::ImGuiLayer() : Layer("ImGuiLayer") {} @@ -23,7 +25,7 @@ namespace DE { io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable; ImGui::StyleColorsDark(); - ImGui_ImplGlfw_InitForOpenGL(Application::Get().m_Window->m_Window, true); + ImGui_ImplGlfw_InitForOpenGL(Application::GetInstance().window_->window_, true); ImGui_ImplOpenGL3_Init("#version 410"); } @@ -47,7 +49,7 @@ namespace DE { ImGui::Render(); ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); - if (ImGui::GetIO().ConfigFlags & ImGuiConfigFlags_ViewportsEnable) { + if ((ImGui::GetIO().ConfigFlags & ImGuiConfigFlags_ViewportsEnable) != 0) { GLFWwindow* backup_current_context = glfwGetCurrentContext(); ImGui::UpdatePlatformWindows(); ImGui::RenderPlatformWindowsDefault(); @@ -56,4 +58,4 @@ namespace DE { } } -} // namespace DE +} // namespace DummyEngine diff --git a/DummyEngine/Core/Application/ImGuiLayer.h b/DummyEngine/Core/Application/ImGuiLayer.h index c759fbc..c9142df 100644 --- a/DummyEngine/Core/Application/ImGuiLayer.h +++ b/DummyEngine/Core/Application/ImGuiLayer.h @@ -2,7 +2,7 @@ #include "DummyEngine/Core/Application/Layer.h" -namespace DE { +namespace DummyEngine { class ImGuiLayer : public Layer { public: @@ -16,4 +16,4 @@ namespace DE { void EndFrame(); }; -} // namespace DE +} // namespace DummyEngine diff --git a/DummyEngine/Core/Application/Initializer.cpp b/DummyEngine/Core/Application/Initializer.cpp index 2cfa332..bb47bb6 100644 --- a/DummyEngine/Core/Application/Initializer.cpp +++ b/DummyEngine/Core/Application/Initializer.cpp @@ -1,28 +1,30 @@ -#include "DummyEngine/Core/Application/Initializer.h" - -// clang-format off -#include -// clang-format on +#include "Initializer.h" #include "DummyEngine/Core/Application/Application.h" #include "DummyEngine/Core/Application/Config.h" +#include "DummyEngine/Core/Application/Input.h" #include "DummyEngine/Core/Console/Console.hpp" #include "DummyEngine/Core/Rendering/Renderer/Renderer.h" #include "DummyEngine/Core/ResourceManaging/AssetManager.h" #include "DummyEngine/Core/ResourceManaging/ResourceManager.h" #include "DummyEngine/Core/Scripting/ScriptEngine.h" -#include "DummyEngine/Utils/Base.h" +#include "DummyEngine/Utils/Debug/Profiler.h" + +#include +#include -namespace DE { - void error_callback(int, const char* description) { +namespace DummyEngine { + static void ErrorCallback(int, const char* description) { fprintf(stderr, "Error: %s\n", description); fflush(stderr); } + void Initializer::Initialize() { PreInitialize(); DepInitialize(); EngineInitialize(); } + void Initializer::Terminate() { EngineTerminate(); DepTerminate(); @@ -40,10 +42,10 @@ namespace DE { LOG_INFO("Initializing dependencies"); //* Init GLFW { - if (!glfwInit()) { + if (glfwInit() == GLFW_FALSE) { DE_ASSERT(false, "Failed to initialize GLFW"); } - glfwSetErrorCallback(error_callback); + glfwSetErrorCallback(ErrorCallback); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); @@ -85,4 +87,4 @@ namespace DE { Config::Terminate(); Profiler::Terminate(); } -} // namespace DE +} // namespace DummyEngine diff --git a/DummyEngine/Core/Application/Initializer.h b/DummyEngine/Core/Application/Initializer.h index 14d0d13..0c88bc5 100644 --- a/DummyEngine/Core/Application/Initializer.h +++ b/DummyEngine/Core/Application/Initializer.h @@ -1,10 +1,11 @@ #pragma once -#include "DummyEngine/Utils/Base.h" +#include "DummyEngine/Utils/Debug/Logger.h" + +namespace DummyEngine { -namespace DE { class Initializer { - LOGGER_AUTHOR(Initializer) + LOG_AUTHOR(Initializer) public: static void Initialize(); static void Terminate(); @@ -18,4 +19,5 @@ namespace DE { static void DepTerminate(); static void PostTerminate(); }; -} // namespace DE \ No newline at end of file + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Application/Input.cpp b/DummyEngine/Core/Application/Input.cpp index 144e27d..ec58e4a 100644 --- a/DummyEngine/Core/Application/Input.cpp +++ b/DummyEngine/Core/Application/Input.cpp @@ -1,14 +1,16 @@ -#include "DummyEngine/Core/Application/Input.h" +#include "Input.h" -#include +#include "DummyEngine/Core/Application/Config.h" +#include "DummyEngine/Utils/Debug/Profiler.h" -namespace DE { +namespace DummyEngine { InputFrame::InputFrame() { key_states.resize((size_t)Key::Last); } SINGLETON_BASE(Input); S_INITIALIZE() { + m_MaxFrameAmount = Config::Get().MaxInputFrameAmount; m_EventDispatcher.AddEventListener([this](KeyPressedEvent& event) { DE_ASSERT(m_CurrentFrame.key_states.size() > event.GetKey(), "Bad key code: {}", event.GetKey()); m_CurrentFrame.key_states[event.GetKey()] = true; @@ -76,4 +78,4 @@ namespace DE { return !m_Frames[0].key_states.at((size_t)key); } -} // namespace DE \ No newline at end of file +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Application/Input.h b/DummyEngine/Core/Application/Input.h index f427b42..8c8d6b7 100644 --- a/DummyEngine/Core/Application/Input.h +++ b/DummyEngine/Core/Application/Input.h @@ -2,9 +2,9 @@ #include "DummyEngine/Core/Application/Event.h" #include "DummyEngine/Core/Application/KeyCodes.h" -#include "DummyEngine/Utils/Base.h" +#include "DummyEngine/Utils/Helpers/Singleton.h" -namespace DE { +namespace DummyEngine { struct InputFrame { bool mouse_locked = false; @@ -35,6 +35,7 @@ namespace DE { InputFrame m_CurrentFrame; EventDispatcher m_EventDispatcher; std::deque m_Frames; - size_t m_MaxFrameAmount = 100; + size_t m_MaxFrameAmount; }; -} // namespace DE \ No newline at end of file + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Application/KeyCodes.h b/DummyEngine/Core/Application/KeyCodes.h index 43af878..5a5b8e2 100644 --- a/DummyEngine/Core/Application/KeyCodes.h +++ b/DummyEngine/Core/Application/KeyCodes.h @@ -1,6 +1,6 @@ #pragma once -namespace DE { +namespace DummyEngine { enum class Key { None = 0, Space = 32, diff --git a/DummyEngine/Core/Application/Layer.h b/DummyEngine/Core/Application/Layer.h index 3f0199b..52340d2 100644 --- a/DummyEngine/Core/Application/Layer.h +++ b/DummyEngine/Core/Application/Layer.h @@ -1,12 +1,12 @@ #pragma once #include "DummyEngine/Core/Application/Event.h" -#include "DummyEngine/Utils/Base.h" -namespace DE { +namespace DummyEngine { + class Layer { public: - Layer(const std::string& name = "Layer") : m_Name(name) {} + explicit Layer(const std::string& name = "Layer") : m_Name(name) {} virtual ~Layer() = default; virtual void OnAttach() {} @@ -17,7 +17,7 @@ namespace DE { const std::string& GetName() const { return m_Name; } - void BroadcastEvent(Event& event) { m_EventCallback(event); } + void BroadcastEvent(Event& event) { event_callback_(event); } protected: std::string m_Name; @@ -25,7 +25,7 @@ namespace DE { private: friend class Application; - EventCallback m_EventCallback; + EventCallback event_callback_; }; -} // namespace DE \ No newline at end of file +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Application/Window.cpp b/DummyEngine/Core/Application/Window.cpp index 5daf9f1..c260779 100644 --- a/DummyEngine/Core/Application/Window.cpp +++ b/DummyEngine/Core/Application/Window.cpp @@ -1,11 +1,11 @@ -#include "DummyEngine/Core/Application/Window.h" +#include "Window.h" -#include +#include "DummyEngine/Utils/Debug/Profiler.h" -#include "DummyEngine/Core/ECS/ECS.h" -#include "DummyEngine/Core/Rendering/Renderer/Renderer.h" +#include +#include -namespace DE { +namespace DummyEngine { GLFWmonitor* GetMonitor(U32 id) { int monitors_amount = 0; @@ -14,116 +14,115 @@ namespace DE { return monitors[id]; } - Window::Window(const WindowState& state) : m_State(state) { - m_Window = glfwCreateWindow(1280, 720, m_State.name.c_str(), NULL, NULL); - // glfwSwapInterval(0); - DE_ASSERT(m_Window, "Failed to create GLFW Window {}", m_State.name); - LOG_INFO("Window created: {}", m_State.name); + Window::Window(const WindowState& state) : state_(state) { + window_ = glfwCreateWindow(1280, 720, state_.Name.c_str(), nullptr, nullptr); + DE_ASSERT(window_, "Failed to create GLFW Window {}", state_.Name); + LOG_INFO("Window created: {}", state_.Name); - m_Context = Context::Create(m_Window); - m_Context->Load(); + context_ = Context::Create(window_); + context_->Load(); SetupCallbacks(); Invalidate(); } Window::~Window() { - glfwDestroyWindow(m_Window); + glfwDestroyWindow(window_); } void Window::SetIcon(Path path) { GLFWimage icon; - icon.pixels = stbi_load(path.string().c_str(), &icon.width, &icon.height, 0, 4); + icon.pixels = stbi_load(path.string().c_str(), &icon.width, &icon.height, nullptr, 4); - if (!icon.pixels) { + if (icon.pixels == nullptr) { LOG_WARNING("Failed to set window icon {}", path); return; } - glfwSetWindowIcon(m_Window, 1, &icon); + glfwSetWindowIcon(window_, 1, &icon); stbi_image_free(icon.pixels); } void Window::FullScreen(U32 id) { - m_State.mode = WindowMode::FullScreen; - m_State.monitor_id = id; + state_.Mode = WindowMode::FullScreen; + state_.MonitorID = id; Invalidate(); } void Window::Windowed(U32 width, U32 height, U32 x_pos, U32 y_pos) { - m_State.mode = WindowMode::Windowed; - m_State.width = width; - m_State.height = height; - m_State.x_pos = x_pos; - m_State.y_pos = y_pos; + state_.Mode = WindowMode::Windowed; + state_.Width = width; + state_.Height = height; + state_.PosX = x_pos; + state_.PosY = y_pos; Invalidate(); } void Window::LockMouse() { - m_State.mouse_locked = true; - glfwSetInputMode(m_Window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); + state_.MouseLocked = true; + glfwSetInputMode(window_, GLFW_CURSOR, GLFW_CURSOR_DISABLED); } void Window::UnlockMouse() { - m_State.mouse_locked = false; - glfwSetInputMode(m_Window, GLFW_CURSOR, GLFW_CURSOR_NORMAL); + state_.MouseLocked = false; + glfwSetInputMode(window_, GLFW_CURSOR, GLFW_CURSOR_NORMAL); } void Window::ToggleMouseLock() { - if (m_State.mouse_locked) { - glfwSetInputMode(m_Window, GLFW_CURSOR, GLFW_CURSOR_NORMAL); + if (state_.MouseLocked) { + glfwSetInputMode(window_, GLFW_CURSOR, GLFW_CURSOR_NORMAL); } else { - glfwSetInputMode(m_Window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); + glfwSetInputMode(window_, GLFW_CURSOR, GLFW_CURSOR_DISABLED); } - m_State.mouse_locked = !m_State.mouse_locked; + state_.MouseLocked = !state_.MouseLocked; } void Window::OnUpdate() { DE_PROFILE_SCOPE("Window OnUpdate"); glfwPollEvents(); - m_Context->SwapBuffers(); + context_->SwapBuffers(); } void Window::SetEventCallback(EventCallback callback) { - m_State.event_callback = callback; + state_.EventCallback = callback; } const WindowState& Window::GetState() const { - return m_State; + return state_; } void Window::Invalidate() { - DE_ASSERT(m_State.mode != WindowMode::None, "Wrong window mode"); - DE_ASSERT(m_State.width != 0 && m_State.height != 0, "Wrong window size ({},{}) expected non 0 sides", m_State.width, m_State.height); - if (m_State.mode == WindowMode::Windowed) { - glfwSetWindowMonitor(m_Window, nullptr, m_State.x_pos, m_State.y_pos, m_State.width, m_State.height, 1000); + DE_ASSERT(state_.Mode != WindowMode::None, "Wrong window mode"); + DE_ASSERT(state_.Width != 0 && state_.Height != 0, "Wrong window size ({},{}) expected non 0 sides", state_.Width, state_.Height); + if (state_.Mode == WindowMode::Windowed) { + glfwSetWindowMonitor(window_, nullptr, state_.PosX, state_.PosY, state_.Width, state_.Height, 1000); } - if (m_State.mode == WindowMode::FullScreen) { - GLFWmonitor* monitor = GetMonitor(m_State.monitor_id); + if (state_.Mode == WindowMode::FullScreen) { + GLFWmonitor* monitor = GetMonitor(state_.MonitorID); const GLFWvidmode* mode = glfwGetVideoMode(monitor); - m_State.height = mode->height; - m_State.width = mode->width; - m_State.x_pos = 0; - m_State.y_pos = 0; - glfwSetWindowMonitor(m_Window, monitor, 0, 0, mode->width, mode->height, mode->refreshRate); + state_.Height = mode->height; + state_.Width = mode->width; + state_.PosX = 0; + state_.PosY = 0; + glfwSetWindowMonitor(window_, monitor, 0, 0, mode->width, mode->height, mode->refreshRate); } } void Window::SetupCallbacks() { - glfwSetWindowUserPointer(m_Window, &m_State); + glfwSetWindowUserPointer(window_, &state_); - glfwSetWindowSizeCallback(m_Window, [](GLFWwindow* window, int width, int height) { + glfwSetWindowSizeCallback(window_, [](GLFWwindow* window, int width, int height) { WindowState& state = *(WindowState*)glfwGetWindowUserPointer(window); - state.width = width; - state.height = height; + state.Width = width; + state.Height = height; WindowResizeEvent event(width, height); - state.event_callback(event); + state.EventCallback(event); }); - glfwSetWindowCloseCallback(m_Window, [](GLFWwindow* window) { + glfwSetWindowCloseCallback(window_, [](GLFWwindow* window) { WindowState& state = *(WindowState*)glfwGetWindowUserPointer(window); WindowCloseEvent event; - state.event_callback(event); + state.EventCallback(event); }); - glfwSetKeyCallback(m_Window, [](GLFWwindow* window, int key, int, int action, int) { + glfwSetKeyCallback(window_, [](GLFWwindow* window, int key, int, int action, int) { if (key == -1) { return; } @@ -131,50 +130,50 @@ namespace DE { switch (action) { case GLFW_PRESS: { KeyPressedEvent event(key); - state.event_callback(event); + state.EventCallback(event); break; } case GLFW_RELEASE: { KeyReleasedEvent event(key); - state.event_callback(event); + state.EventCallback(event); break; } case GLFW_REPEAT: { KeyPressedEvent event(key); - state.event_callback(event); + state.EventCallback(event); break; } } }); - glfwSetMouseButtonCallback(m_Window, [](GLFWwindow* window, int button, int action, int) { + glfwSetMouseButtonCallback(window_, [](GLFWwindow* window, int button, int action, int) { WindowState& state = *(WindowState*)glfwGetWindowUserPointer(window); switch (action) { case GLFW_PRESS: { MouseButtonPressedEvent event(button); - state.event_callback(event); + state.EventCallback(event); break; } case GLFW_RELEASE: { MouseButtonReleasedEvent event(button); - state.event_callback(event); + state.EventCallback(event); break; } } }); - glfwSetScrollCallback(m_Window, [](GLFWwindow* window, double xOffset, double yOffset) { + glfwSetScrollCallback(window_, [](GLFWwindow* window, double x_offset, double y_offset) { WindowState& state = *(WindowState*)glfwGetWindowUserPointer(window); - MouseScrolledEvent event((float)xOffset, (float)yOffset); - state.event_callback(event); + MouseScrolledEvent event((float)x_offset, (float)y_offset); + state.EventCallback(event); }); - glfwSetCursorPosCallback(m_Window, [](GLFWwindow* window, double xPos, double yPos) { + glfwSetCursorPosCallback(window_, [](GLFWwindow* window, double x_pos, double y_pos) { WindowState& state = *(WindowState*)glfwGetWindowUserPointer(window); - MouseMovedCallback event((float)xPos, (float)yPos); - state.event_callback(event); + MouseMovedCallback event((float)x_pos, (float)y_pos); + state.EventCallback(event); }); } -} // namespace DE \ No newline at end of file +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Application/Window.h b/DummyEngine/Core/Application/Window.h index 8ed3776..d6d3bbc 100644 --- a/DummyEngine/Core/Application/Window.h +++ b/DummyEngine/Core/Application/Window.h @@ -1,31 +1,32 @@ #pragma once -#include #include "DummyEngine/Core/Application/Event.h" #include "DummyEngine/Core/Rendering/Renderer/Context.h" -#include "DummyEngine/Utils/Base.h" +#include "DummyEngine/Utils/Debug/Logger.h" -namespace DE { +struct GLFWWindow; + +namespace DummyEngine { enum class WindowMode { None = 0, Windowed, FullScreen }; struct WindowState { - WindowMode mode = WindowMode::Windowed; - std::string name = "Window"; - U32 width = 1280; - U32 height = 720; - U32 x_pos = 100; - U32 y_pos = 100; - U32 monitor_id = 0; - bool mouse_locked = false; - - EventCallback event_callback = {}; + WindowMode Mode = WindowMode::Windowed; + std::string Name = "Window"; + U32 Width = 1280; + U32 Height = 720; + U32 PosX = 100; + U32 PosY = 100; + U32 MonitorID = 0; + bool MouseLocked = false; + + EventCallback EventCallback = {}; }; class Window { - LOGGER_AUTHOR(Window) + LOG_AUTHOR(Window) public: - Window(const WindowState& state = WindowState()); + explicit Window(const WindowState& state = WindowState()); ~Window(); void OnUpdate(); @@ -48,8 +49,8 @@ namespace DE { void SetupCallbacks(); void Invalidate(); - WindowState m_State; - GLFWwindow* m_Window; - Scope m_Context; + WindowState state_; + GLFWwindow* window_; + Scope context_; }; -} // namespace DE \ No newline at end of file +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Console/Console.cpp b/DummyEngine/Core/Console/Console.cpp index 7da8b78..e5b9e61 100644 --- a/DummyEngine/Core/Console/Console.cpp +++ b/DummyEngine/Core/Console/Console.cpp @@ -1,23 +1,20 @@ -// -// Created by balanda on 9/29/2023. -// - #include "Console.hpp" -namespace DE { +namespace DummyEngine { + SINGLETON_BASE(Console); S_INITIALIZE() { - m_Commands = {"clear", "exit", "r_shadowmap_resize"}; - m_Variables["r_shadowmap_width"] = 1920ll; - m_Variables["r_shadowmap_height"] = 1080ll; - m_Variables["r_shadowmap_fbo"] = false; - m_Variables["r_psm_size"] = 2048ll; - m_Variables["r_psm_near"] = 0.1f; - m_Variables["r_psm_far"] = 50.f; - m_Variables["testInt"] = 534ll; - m_Variables["testBool"] = true; - m_Variables["testFloat"] = 0.5f; - m_Variables["testDouble"] = .234; + commands_ = {"clear", "exit", "r_shadowmap_resize"}; + variables_["r_shadowmap_width"] = 1920ll; + variables_["r_shadowmap_height"] = 1080ll; + variables_["r_shadowmap_fbo"] = false; + variables_["r_psm_size"] = 2048ll; + variables_["r_psm_near"] = 0.1f; + variables_["r_psm_far"] = 50.f; + variables_["testInt"] = 534ll; + variables_["testBool"] = true; + variables_["testFloat"] = 0.5f; + variables_["testDouble"] = .234; return Unit(); } S_TERMINATE() { @@ -25,32 +22,32 @@ namespace DE { } S_METHOD_IMPL(void, ExecuteCommand, (std::string & cmd), (cmd)) { - m_CmdHistory.push_back(cmd); + cmd_history_.push_back(cmd); if (cmd.find(' ') != std::string::npos) { size_t pos = cmd.find(' '); const auto& var_name = cmd.substr(0, pos); - if (m_Variables.find(var_name) != m_Variables.end()) { - auto& value = m_Variables[var_name]; + if (variables_.find(var_name) != variables_.end()) { + auto& value = variables_[var_name]; std::string new_value = cmd.substr(pos + 1); if (std::holds_alternative(value)) { - m_Variables[var_name] = new_value; + variables_[var_name] = new_value; } else if (std::holds_alternative(value)) { - int64_t unmarshalled = std::stoll(new_value); - m_Variables[var_name] = unmarshalled; + int64_t unmarshalled = std::stoll(new_value); + variables_[var_name] = unmarshalled; } else if (std::holds_alternative(value)) { - float unmarshalled = std::stof(new_value); - m_Variables[var_name] = unmarshalled; + float unmarshalled = std::stof(new_value); + variables_[var_name] = unmarshalled; } else if (std::holds_alternative(value)) { - double unmarshalled = std::stod(new_value); - m_Variables[var_name] = unmarshalled; + double unmarshalled = std::stod(new_value); + variables_[var_name] = unmarshalled; } else if (std::holds_alternative(value)) { if (new_value == "true") { - m_Variables[var_name] = true; + variables_[var_name] = true; } else if (new_value == "false") { - m_Variables[var_name] = false; + variables_[var_name] = false; } else { - int64_t unmarshalled = std::stoll(new_value); - m_Variables[var_name] = unmarshalled ? true : false; + int64_t unmarshalled = std::stoll(new_value); + variables_[var_name] = unmarshalled != 0 ? true : false; } } else { LOG_ERROR("Unknown type in cmd {}", cmd); @@ -60,38 +57,38 @@ namespace DE { if (cmd == "clear") { ClearLogs(); } - if (m_Callback.find(cmd) != m_Callback.end()) { - m_Callback[cmd](); + if (callback_.find(cmd) != callback_.end()) { + callback_[cmd](); } } S_METHOD_IMPL(void, OnCommand, (std::string cmd, std::function func), (cmd, func)) { - m_Callback[cmd] = func; + callback_[cmd] = func; } S_METHOD_IMPL(void, PushLog, (std::string log), (log)) { - m_LogHistory.push_back(log); + log_history_.push_back(log); } S_METHOD_IMPL(void, ClearLogs, (), ()) { - m_LogHistory.clear(); - m_LogHistory.shrink_to_fit(); + log_history_.clear(); + log_history_.shrink_to_fit(); } S_METHOD_IMPL(std::vector&, GetLogHistory, (), ()) { - return m_LogHistory; + return log_history_; } S_METHOD_IMPL(std::vector&, GetCmdHistory, (), ()) { - return m_CmdHistory; + return cmd_history_; } S_METHOD_IMPL(std::string, VarToString, (const std::string& var), (var)) { - if (m_Variables.find(var) == m_Variables.end()) { + if (variables_.find(var) == variables_.end()) { LOG_WARNING("Undefined variable {}", var); return "undefined"; } - auto& value = m_Variables[var]; + auto& value = variables_[var]; if (std::holds_alternative(value)) { return std::get(value); } else if (std::holds_alternative(value)) { @@ -108,45 +105,45 @@ namespace DE { } S_METHOD_IMPL(int64_t, GetInt, (std::string var), (var)) { - if (m_Variables.find(var) == m_Variables.end()) { + if (variables_.find(var) == variables_.end()) { LOG_WARNING("Undefined variable {}", var); return -1; } - return std::get(m_Variables[var]); + return std::get(variables_[var]); } S_METHOD_IMPL(float, GetFloat, (std::string var), (var)) { - if (m_Variables.find(var) == m_Variables.end()) { + if (variables_.find(var) == variables_.end()) { LOG_WARNING("Undefined variable {}", var); return -1; } - return std::get(m_Variables[var]); + return std::get(variables_[var]); } S_METHOD_IMPL(double, GetDouble, (std::string var), (var)) { - if (m_Variables.find(var) == m_Variables.end()) { + if (variables_.find(var) == variables_.end()) { LOG_WARNING("Undefined variable {}", var); return -1; } - return std::get(m_Variables[var]); + return std::get(variables_[var]); } S_METHOD_IMPL(std::string, GetString, (std::string var), (var)) { - if (m_Variables.find(var) == m_Variables.end()) { + if (variables_.find(var) == variables_.end()) { LOG_WARNING("Undefined variable {}", var); return "undefined"; } - return std::get(m_Variables[var]); + return std::get(variables_[var]); } S_METHOD_IMPL(bool, GetBool, (std::string var), (var)) { - if (m_Variables.find(var) == m_Variables.end()) { + if (variables_.find(var) == variables_.end()) { LOG_WARNING("Undefined variable {}", var); return false; } - return std::get(m_Variables[var]); + return std::get(variables_[var]); } S_METHOD_IMPL(std::vector, GetHints, (std::string & cmd), (cmd)) { - std::vector candidates(m_Commands); - for (const auto& [key, val] : m_Variables) { + std::vector candidates(commands_); + for (const auto& [key, val] : variables_) { candidates.push_back(key + " " + VarToString(key)); } std::vector result; @@ -159,4 +156,4 @@ namespace DE { } return result; } -} // namespace DE \ No newline at end of file +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Console/Console.hpp b/DummyEngine/Core/Console/Console.hpp index 73ea646..58c0658 100644 --- a/DummyEngine/Core/Console/Console.hpp +++ b/DummyEngine/Core/Console/Console.hpp @@ -1,15 +1,17 @@ #define once -#include "DummyEngine/Utils/Base.h" -#include "DummyEngine/Utils/Base/STDIncludes.h" +#include "DummyEngine/Utils/Debug/Logger.h" #include "DummyEngine/Utils/Helpers/Singleton.h" #include "DummyEngine/Utils/Types/Types.h" -namespace DE { - using ConsoleVariable = std::variant; +#include + +namespace DummyEngine { class Console : public Singleton { - LOGGER_AUTHOR(Console) + using Variable = std::variant; + + LOG_AUTHOR(Console) SINGLETON(Console) private: S_METHOD_DEF(std::string, VarToString, (const std::string& var)) @@ -27,10 +29,11 @@ namespace DE { S_METHOD_DEF(std::string, GetString, (std::string var)) S_METHOD_DEF(std::vector, GetHints, (std::string & cmd)) private: - std::vector m_CmdHistory; - std::vector m_LogHistory; - std::map m_Variables; - std::map> m_Callback; - std::vector m_Commands; + std::vector cmd_history_; + std::vector log_history_; + std::map variables_; + std::map> callback_; + std::vector commands_; }; -} // namespace DE \ No newline at end of file + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Console/ConsoleLayer.cpp b/DummyEngine/Core/Console/ConsoleLayer.cpp index 222874d..3c67d4d 100644 --- a/DummyEngine/Core/Console/ConsoleLayer.cpp +++ b/DummyEngine/Core/Console/ConsoleLayer.cpp @@ -1,66 +1,64 @@ -// -// Created by balanda on 9/29/2023. -// - #include "ConsoleLayer.hpp" -#include "DummyEditor/DummyEngineInclude.h" #include "DummyEngine/Core/Application/Input.h" #include "DummyEngine/Core/Application/KeyCodes.h" #include "DummyEngine/Core/Console/Console.hpp" -namespace DE { +#include +#include + +namespace DummyEngine { void ConsoleLayer::OnUpdate(float) { if (Input::KeyPressed(Key::I) && Input::KeyDown(Key::LeftShift)) { - if (!m_Show) { - m_JustOpened = true; + if (!show_) { + just_opened_ = true; } - m_Show = !m_Show; + show_ = !show_; } } void ConsoleLayer::OnImGuiRender() { - if (m_Show) { + if (show_) { if (ImGui::Begin("Console")) { - if (m_historyPosition >= Console::GetCmdHistory().size()) { - m_Command = ""; - m_historyPosition = Console::GetCmdHistory().size() - 1; + if (history_position_ >= Console::GetCmdHistory().size()) { + command_ = ""; + history_position_ = Console::GetCmdHistory().size() - 1; } - if (m_historyPosition < 0) { - m_historyPosition = Console::GetCmdHistory().size() - 1; + if (history_position_ < 0) { + history_position_ = Console::GetCmdHistory().size() - 1; } if (Input::KeyReleased(Key::Up)) { LOG_DEBUG("CmdHistoryLength = {}, Position = {}, cmd = {}", Console::GetCmdHistory().size(), - m_historyPosition, - Console::GetCmdHistory()[m_historyPosition]); - m_Command = Console::GetCmdHistory()[m_historyPosition]; - m_historyPosition--; - m_JustOpened = true; + history_position_, + Console::GetCmdHistory()[history_position_]); + command_ = Console::GetCmdHistory()[history_position_]; + history_position_--; + just_opened_ = true; } if (Input::KeyReleased(Key::Down)) { - m_Command = Console::GetCmdHistory()[m_historyPosition]; - m_historyPosition++; - m_JustOpened = true; + command_ = Console::GetCmdHistory()[history_position_]; + history_position_++; + just_opened_ = true; } - if (m_JustOpened) { - m_JustOpened = false; + if (just_opened_) { + just_opened_ = false; ImGui::SetKeyboardFocusHere(); } if (ImGui::InputTextWithHint( - "##", "command", &m_Command, ImGuiInputTextFlags_EnterReturnsTrue | ImGuiInputTextFlags_AlwaysOverwrite)) { - m_historyPosition = Console::GetCmdHistory().size() - 1; - Console::ExecuteCommand(m_Command); - m_ScrollToBottom = true; - m_Command = ""; - m_JustOpened = true; + "##", "command", &command_, ImGuiInputTextFlags_EnterReturnsTrue | ImGuiInputTextFlags_AlwaysOverwrite)) { + history_position_ = Console::GetCmdHistory().size() - 1; + Console::ExecuteCommand(command_); + scroll_to_bottom_ = true; + command_ = ""; + just_opened_ = true; } if (ImGui::IsItemFocused()) { ImGui::SetNextWindowPos(ImVec2(ImGui::GetItemRectMin().x, ImGui::GetItemRectMax().y)); if (ImGui::BeginTooltip()) { ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 1)); - const auto& tips = Console::GetHints(m_Command); + const auto& tips = Console::GetHints(command_); if (!tips.empty()) { for (const auto& tip : tips) { ImGui::TextUnformatted(tip.c_str()); @@ -81,9 +79,9 @@ namespace DE { for (const auto& line : Console::GetLogHistory()) { ImGui::TextUnformatted(line.data()); } - if (m_ScrollToBottom) { + if (scroll_to_bottom_) { ImGui::SetScrollHereY(); - m_ScrollToBottom = false; + scroll_to_bottom_ = false; } ImGui::PopStyleVar(); ImGui::EndChild(); @@ -95,4 +93,4 @@ namespace DE { void ConsoleLayer::OnAttach() {} void ConsoleLayer::OnDetach() {} -} // namespace DE +} // namespace DummyEngine diff --git a/DummyEngine/Core/Console/ConsoleLayer.hpp b/DummyEngine/Core/Console/ConsoleLayer.hpp index 6b6e924..941fbcd 100644 --- a/DummyEngine/Core/Console/ConsoleLayer.hpp +++ b/DummyEngine/Core/Console/ConsoleLayer.hpp @@ -1,9 +1,12 @@ #pragma once + #include "DummyEngine/Core/Application/Layer.h" +#include "DummyEngine/Utils/Debug/Logger.h" + +namespace DummyEngine { -namespace DE { class ConsoleLayer : public Layer { - LOGGER_AUTHOR(ConsoleLayer) + LOG_AUTHOR(ConsoleLayer) public: void OnAttach() override; void OnUpdate(float dt) override; @@ -11,10 +14,11 @@ namespace DE { void OnDetach() override; private: - bool m_Show = false; - std::string m_Command; - U32 m_historyPosition = 0; - bool m_ScrollToBottom = true; - bool m_JustOpened = false; + bool show_ = false; + std::string command_; + U32 history_position_ = 0; + bool scroll_to_bottom_ = true; + bool just_opened_ = false; }; -} // namespace DE \ No newline at end of file + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/ECS/ComponentArray.hpp b/DummyEngine/Core/ECS/ComponentArray.hpp index c1990cb..a924c81 100644 --- a/DummyEngine/Core/ECS/ComponentArray.hpp +++ b/DummyEngine/Core/ECS/ComponentArray.hpp @@ -1,30 +1,30 @@ #pragma once -namespace DE { +namespace DummyEngine { template void* ComponentArray::AddComponent(U32 id, void* component) { - DE_ASSERT(!m_EntityToIndex.contains(id), "Adding component which already exists to entity {}", id); - m_EntityToIndex[id] = m_ComponentArray.size(); - m_IndexToEntity.push_back(id); - m_ComponentArray.emplace_back(std::move(*reinterpret_cast(component))); - return &m_ComponentArray[m_EntityToIndex[id]]; + DE_ASSERT(!entity_to_index_.contains(id), "Adding component which already exists to entity {}", id); + entity_to_index_[id] = component_array_.size(); + index_to_entity_.push_back(id); + component_array_.emplace_back(std::move(*reinterpret_cast(component))); + return &component_array_[entity_to_index_[id]]; } template void* ComponentArray::GetComponent(U32 id) { - DE_ASSERT(m_EntityToIndex.contains(id), "Accessing non-existing component of entity {}", id); - return &m_ComponentArray[m_EntityToIndex[id]]; + DE_ASSERT(entity_to_index_.contains(id), "Accessing non-existing component of entity {}", id); + return &component_array_[entity_to_index_[id]]; } template bool ComponentArray::HasComponent(U32 id) { - return m_EntityToIndex.contains(id); + return entity_to_index_.contains(id); } template void ComponentArray::RemoveComponent(U32 id) { - DE_ASSERT(m_EntityToIndex.contains(id), "Removing non-existing component from entity {}", id); - U32 index = m_EntityToIndex[id]; - if (index != m_ComponentArray.size() - 1) { - m_ComponentArray[index] = std::move(m_ComponentArray.back()); - m_IndexToEntity[index] = m_IndexToEntity.back(); - m_EntityToIndex[m_IndexToEntity.back()] = index; + DE_ASSERT(entity_to_index_.contains(id), "Removing non-existing component from entity {}", id); + U32 index = entity_to_index_[id]; + if (index != component_array_.size() - 1) { + component_array_[index] = std::move(component_array_.back()); + index_to_entity_[index] = index_to_entity_.back(); + entity_to_index_[index_to_entity_.back()] = index; } - m_ComponentArray.pop_back(); - m_IndexToEntity.pop_back(); - m_EntityToIndex.erase(id); + component_array_.pop_back(); + index_to_entity_.pop_back(); + entity_to_index_.erase(id); } -} // namespace DE +} // namespace DummyEngine diff --git a/DummyEngine/Core/ECS/ComponentManager.hpp b/DummyEngine/Core/ECS/ComponentManager.hpp index 25e8cff..8aa77d4 100644 --- a/DummyEngine/Core/ECS/ComponentManager.hpp +++ b/DummyEngine/Core/ECS/ComponentManager.hpp @@ -1,53 +1,53 @@ #pragma once -namespace DE { +namespace DummyEngine { #ifdef ECS_IMPLEMENTATION bool Signature::Get(U64 id) const { - return (m_Data.size() <= (id >> 6) ? false : (m_Data[id >> 6] >> (id & 63)) & 1); + return (data_.size() <= (id >> 6) ? false : (data_[id >> 6] >> (id & 63)) & 1); } void Signature::Set(U64 id, bool value) { - if (m_Data.size() <= id >> 6) { - m_Data.resize((id >> 6) + 1); + if (data_.size() <= id >> 6) { + data_.resize((id >> 6) + 1); } - m_Data[id >> 6] &= ~(1 << (id & 63)); - m_Data[id >> 6] |= ((U64)value << (id & 63)); + data_[id >> 6] &= ~(1 << (id & 63)); + data_[id >> 6] |= ((U64)value << (id & 63)); } bool Signature::Matches(const Signature& required) const { size_t i; - size_t mn = std::min(required.m_Data.size(), m_Data.size()); + size_t mn = std::min(required.data_.size(), data_.size()); for (i = 0; i < mn; ++i) { - if ((m_Data[i] & required.m_Data[i]) != required.m_Data[i]) { + if ((data_[i] & required.data_[i]) != required.data_[i]) { return false; } } - while (i < required.m_Data.size()) { - if (required.m_Data[i++]) { + while (i < required.data_.size()) { + if (required.data_[i++]) { return false; } } return true; } - ComponentManager::ComponentManager(Storage* storage) : m_Storage(storage) {} + ComponentManager::ComponentManager(Storage* storage) : storage_(storage) {} void ComponentManager::Destroy(U32 entity_id) { - Entity e = m_Storage->GetEntity(entity_id); - for (const auto& [id, array] : m_ComponentArrays) { + Entity e = storage_->GetEntity(entity_id); + for (const auto& [id, array] : component_arrays_) { if (array->HasComponent(entity_id)) { - m_RemoveHandlers[id](e); + remove_handlers_[id](e); array->RemoveComponent(entity_id); } } - m_Signatures[entity_id] = Signature(); + signatures_[entity_id] = Signature(); } bool ComponentManager::Matches(U32 id, const Signature& signature) const { - if (m_Signatures.size() <= id) { + if (signatures_.size() <= id) { return false; } - return m_Signatures.at(id).Matches(signature); + return signatures_.at(id).Matches(signature); } void ComponentManager::ValidateSignature(U32 entity_id) { - while (m_Signatures.size() < entity_id + 1) { - m_Signatures.push_back(Signature()); + while (signatures_.size() < entity_id + 1) { + signatures_.push_back(Signature()); } } @@ -55,20 +55,20 @@ namespace DE { template void ComponentManager::SetAddHandler(std::function func) { RegisterComponent(); - m_AddHandlers[INDEX(ComponentType)] = func; + add_handlers_[INDEX(ComponentType)] = func; } template void ComponentManager::SetRemoveHandler(std::function func) { RegisterComponent(); - m_RemoveHandlers[INDEX(ComponentType)] = func; + remove_handlers_[INDEX(ComponentType)] = func; } template ComponentType* ComponentManager::AddComponent(U32 entity_id, const ComponentType& component) { RegisterComponent(); ValidateSignature(entity_id); - m_Signatures[entity_id].Set(m_ComponentId[INDEX(ComponentType)], true); + signatures_[entity_id].Set(component_id_[INDEX(ComponentType)], true); auto* c = reinterpret_cast( - m_ComponentArrays[INDEX(ComponentType)]->AddComponent(entity_id, const_cast(&component))); - m_AddHandlers[INDEX(ComponentType)](m_Storage->GetEntity(entity_id)); + component_arrays_[INDEX(ComponentType)]->AddComponent(entity_id, const_cast(&component))); + add_handlers_[INDEX(ComponentType)](storage_->GetEntity(entity_id)); return c; } template ComponentType* ComponentManager::GetComponent(U32 entity_id) { @@ -76,28 +76,28 @@ namespace DE { if (!HasComponent(entity_id)) { return nullptr; } - return reinterpret_cast(m_ComponentArrays[INDEX(ComponentType)]->GetComponent(entity_id)); + return reinterpret_cast(component_arrays_[INDEX(ComponentType)]->GetComponent(entity_id)); } template void ComponentManager::RemoveComponent(U32 entity_id) { ValidateSignature(entity_id); if (HasComponent(entity_id)) { - m_RemoveHandlers[INDEX(ComponentType)](m_Storage->GetEntity(entity_id)); - m_Signatures[entity_id].Set(m_ComponentId[INDEX(ComponentType)], false); - m_ComponentArrays[INDEX(ComponentType)]->RemoveComponent(entity_id); + remove_handlers_[INDEX(ComponentType)](storage_->GetEntity(entity_id)); + signatures_[entity_id].Set(component_id_[INDEX(ComponentType)], false); + component_arrays_[INDEX(ComponentType)]->RemoveComponent(entity_id); } } template bool ComponentManager::HasComponent(U32 entity_id) const { - if (m_Signatures.size() < entity_id + 1 || m_ComponentId.find(INDEX(ComponentType)) == m_ComponentId.end()) { + if (signatures_.size() < entity_id + 1 || component_id_.find(INDEX(ComponentType)) == component_id_.end()) { return false; } - return m_Signatures.at(entity_id).Get(m_ComponentId.at(INDEX(ComponentType))); + return signatures_.at(entity_id).Get(component_id_.at(INDEX(ComponentType))); } template Signature ComponentManager::BuildSignature() { if (!ValidateComponents()) { Signature res; - res.Set(m_ComponentId.size(), true); + res.Set(component_id_.size(), true); return res; } return GetSignature(); @@ -107,7 +107,7 @@ namespace DE { return true; } template bool ComponentManager::ValidateComponents() const { - if (m_ComponentId.find(INDEX(T)) == m_ComponentId.end()) { + if (component_id_.find(INDEX(T)) == component_id_.end()) { return false; } return ValidateComponents(); @@ -118,17 +118,17 @@ namespace DE { } template Signature ComponentManager::GetSignature() const { Signature res = GetSignature(); - res.Set(m_ComponentId.at(INDEX(T)), true); + res.Set(component_id_.at(INDEX(T)), true); return res; } template void ComponentManager::RegisterComponent() { - if (m_ComponentId.find(INDEX(ComponentType)) == m_ComponentId.end()) { + if (component_id_.find(INDEX(ComponentType)) == component_id_.end()) { auto default_handler = [](Entity) {}; - m_ComponentId[INDEX(ComponentType)] = m_ComponentId.size(); - m_ComponentArrays[INDEX(ComponentType)] = std::make_shared>(ComponentArray()); - m_AddHandlers[INDEX(ComponentType)] = default_handler; - m_RemoveHandlers[INDEX(ComponentType)] = default_handler; + component_id_[INDEX(ComponentType)] = component_id_.size(); + component_arrays_[INDEX(ComponentType)] = std::make_shared>(ComponentArray()); + add_handlers_[INDEX(ComponentType)] = default_handler; + remove_handlers_[INDEX(ComponentType)] = default_handler; } } -} // namespace DE \ No newline at end of file +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/ECS/ECS.h b/DummyEngine/Core/ECS/ECS.h index d267eb6..e7d687a 100644 --- a/DummyEngine/Core/ECS/ECS.h +++ b/DummyEngine/Core/ECS/ECS.h @@ -1,10 +1,14 @@ #pragma once -#include "DummyEngine/Utils/Base.h" +#include "DummyEngine/Utils/Debug/Assert.h" // IWYU pragma: export +#include "DummyEngine/Utils/Types/Types.h" + +#include #define INDEX(type) std::type_index(typeid(type)) -namespace DE { +namespace DummyEngine { + //*___CLASS_DECLARATIONS___________________________________________________________________________________________________________________________________________________________________________________________________ class Entity; class Storage; @@ -35,9 +39,9 @@ namespace DE { virtual void RemoveComponent(U32 id); private: - std::unordered_map m_EntityToIndex; - std::vector m_IndexToEntity; - std::vector m_ComponentArray; + std::unordered_map entity_to_index_; + std::vector index_to_entity_; + std::vector component_array_; }; class Signature { @@ -47,7 +51,7 @@ namespace DE { bool Matches(const Signature& required) const; size_t Size() const { size_t size = 0; - for (size_t i = 0; i < 64 * m_Data.size(); ++i) { + for (size_t i = 0; i < 64 * data_.size(); ++i) { if (Get(i)) { ++size; } @@ -56,11 +60,11 @@ namespace DE { } private: - std::vector m_Data; + std::vector data_; }; class ComponentManager { public: - ComponentManager(Storage* storage); + explicit ComponentManager(Storage* storage); template ComponentType* AddComponent(U32 entity_id, const ComponentType& component); template ComponentType* GetComponent(U32 entity_id); @@ -84,12 +88,12 @@ namespace DE { void ValidateSignature(U32 entity_id); template void RegisterComponent(); - std::unordered_map> m_ComponentArrays; - std::unordered_map m_ComponentId; - std::unordered_map> m_AddHandlers; - std::unordered_map> m_RemoveHandlers; - std::vector m_Signatures; - Storage* m_Storage; + std::unordered_map> component_arrays_; + std::unordered_map component_id_; + std::unordered_map> add_handlers_; + std::unordered_map> remove_handlers_; + std::vector signatures_; + Storage* storage_; }; //*___ENTITY_MANAGER___________________________________________________________________________________________________________________________________________________________________________________________ @@ -108,9 +112,9 @@ namespace DE { U32 EndEntity() const; private: - std::vector m_Generations; - std::vector m_States; - std::queue m_AvailableEntities; + std::vector generations_; + std::vector states_; + std::queue available_entities_; }; //*___SYSTEM_MANAGER___________________________________________________________________________________________________________________________________________________________________________________________ @@ -128,20 +132,20 @@ namespace DE { friend class SystemManager; void Bind(Storage* storage); - Storage* m_Storage; + Storage* storage_; }; class SystemManager { public: - SystemManager(Storage* storage); + explicit SystemManager(Storage* storage); void Update(float dt); template void AddDependency(); template void AttachSystem(std::shared_ptr system); private: - std::vector> m_Systems; - std::unordered_map m_SystemId; - std::vector> m_DependencyGraph; - Storage* m_Storage; + std::vector> systems_; + std::unordered_map system_ids_; + std::vector> dependency_graph_; + Storage* storage_; }; //*___ENTITY____________________________________________________________________________________________________________________________________________________________________________________________________ @@ -173,9 +177,9 @@ namespace DE { friend struct std::hash; friend class Storage; - U32 m_ID; - U32 m_Gen; - WeakRef m_Storage; + U32 id_; + U32 gen_; + WeakRef storage_; }; //*___STORAGE___________________________________________________________________________________________________________________________________________________________________________________________ @@ -215,9 +219,9 @@ namespace DE { template bool HasComponent(U32 id, U32 gen) const; template void RemoveComponent(U32 id, U32 gen); - EntityManager m_EntityManager; - ComponentManager m_ComponentManager; - SystemManager m_SystemManager; + EntityManager entity_manager_; + ComponentManager component_manager_; + SystemManager system_manager_; }; template class StorageView { public: @@ -233,28 +237,28 @@ namespace DE { private: friend class StorageView; - U32 m_ID; - StorageView* m_View; + U32 id_; + StorageView* view_; }; - Iterator begin(); - Iterator end(); + Iterator begin(); // NOLINT + Iterator end(); // NOLINT bool Empty(); private: friend class Storage; - StorageView(Storage* storage); + explicit StorageView(Storage* storage); - Signature m_Signature; - Storage* m_Storage; + Signature signature_; + Storage* storage_; }; -} // namespace DE +} // namespace DummyEngine -#include "DummyEngine/Core/ECS/ComponentArray.hpp" -#include "DummyEngine/Core/ECS/ComponentManager.hpp" -#include "DummyEngine/Core/ECS/Entity.hpp" -#include "DummyEngine/Core/ECS/EntityManager.hpp" -#include "DummyEngine/Core/ECS/Storage.hpp" -#include "DummyEngine/Core/ECS/StorageView.hpp" -#include "DummyEngine/Core/ECS/System.hpp" -#include "DummyEngine/Core/ECS/SystemManager.hpp" \ No newline at end of file +#include "DummyEngine/Core/ECS/ComponentArray.hpp" // IWYU pragma: export +#include "DummyEngine/Core/ECS/ComponentManager.hpp" // IWYU pragma: export +#include "DummyEngine/Core/ECS/Entity.hpp" // IWYU pragma: export +#include "DummyEngine/Core/ECS/EntityManager.hpp" // IWYU pragma: export +#include "DummyEngine/Core/ECS/Storage.hpp" // IWYU pragma: export +#include "DummyEngine/Core/ECS/StorageView.hpp" // IWYU pragma: export +#include "DummyEngine/Core/ECS/System.hpp" // IWYU pragma: export +#include "DummyEngine/Core/ECS/SystemManager.hpp" // IWYU pragma: export \ No newline at end of file diff --git a/DummyEngine/Core/ECS/Entity.hpp b/DummyEngine/Core/ECS/Entity.hpp index e125d48..688ed1e 100644 --- a/DummyEngine/Core/ECS/Entity.hpp +++ b/DummyEngine/Core/ECS/Entity.hpp @@ -1,69 +1,69 @@ #pragma once -namespace DE { +namespace DummyEngine { #ifdef ECS_IMPLEMENTATION - Entity::Entity() : m_ID(0), m_Gen(0) {} + Entity::Entity() : id_(0), gen_(0) {} bool Entity::Valid() const { - auto storage = m_Storage.lock(); - return storage && storage->Valid(m_ID, m_Gen); + auto storage = storage_.lock(); + return storage && storage->Valid(id_, gen_); } void Entity::Destroy() { - auto storage = m_Storage.lock(); + auto storage = storage_.lock(); if (storage) { - storage->Destroy(m_ID, m_Gen); + storage->Destroy(id_, gen_); } *this = Entity(); } bool Entity::operator==(const Entity& other) const { - return m_ID == other.m_ID && m_Gen == other.m_Gen && m_Storage.lock() == other.m_Storage.lock(); + return id_ == other.id_ && gen_ == other.gen_ && storage_.lock() == other.storage_.lock(); } bool Entity::operator!=(const Entity& other) const { - return m_ID != other.m_ID || m_Gen != other.m_Gen || m_Storage.lock() != other.m_Storage.lock(); + return id_ != other.id_ || gen_ != other.gen_ || storage_.lock() != other.storage_.lock(); } #endif template ComponentType* Entity::AddComponent(ComponentType component) { - auto storage = m_Storage.lock(); - return (storage ? storage->AddComponent(m_ID, m_Gen, component) : nullptr); + auto storage = storage_.lock(); + return (storage ? storage->AddComponent(id_, gen_, component) : nullptr); } template ComponentType* Entity::GetComponent() { - auto storage = m_Storage.lock(); - return (storage ? storage->GetComponent(m_ID, m_Gen) : nullptr); + auto storage = storage_.lock(); + return (storage ? storage->GetComponent(id_, gen_) : nullptr); } template ComponentType& Entity::Add(ComponentType component) { - auto storage = m_Storage.lock(); + auto storage = storage_.lock(); DE_ASSERT(storage, "Adding component to entity with destructed storage"); - auto ptr = storage->AddComponent(m_ID, m_Gen, component); - // DE_ASSERT(ptr, "Failed to add (", DemangledName(), ") to entity (", m_ID, ")"); + auto ptr = storage->AddComponent(id_, gen_, component); + // DE_ASSERT(ptr, "Failed to add (", DemangledName(), ") to entity (", id_, ")"); return *ptr; } template ComponentType& Entity::Get() { - auto storage = m_Storage.lock(); - auto ptr = storage->GetComponent(m_ID, m_Gen); - // DE_ASSERT(ptr, "Failed to get (", DemangledName(), ") of entity (", m_ID, ")"); + auto storage = storage_.lock(); + auto ptr = storage->GetComponent(id_, gen_); + // DE_ASSERT(ptr, "Failed to get (", DemangledName(), ") of entity (", id_, ")"); return *ptr; } template bool Entity::Has() const { - auto storage = m_Storage.lock(); + auto storage = storage_.lock(); if (!storage) { return false; } - return storage->HasComponent(m_ID, m_Gen); + return storage->HasComponent(id_, gen_); } template void Entity::Remove() { - auto storage = m_Storage.lock(); + auto storage = storage_.lock(); if (storage) { - storage->RemoveComponent(m_ID, m_Gen); + storage->RemoveComponent(id_, gen_); } } -} // namespace DE +} // namespace DummyEngine namespace std { - template <> struct hash { - std::size_t operator()(const DE::Entity& entity) const { - return hash()(((U64)entity.m_ID << 32) + entity.m_Gen) ^ hash()(reinterpret_cast(entity.m_Storage.lock().get())); + template <> struct hash { + std::size_t operator()(const DummyEngine::Entity& entity) const { + return hash()(((U64)entity.id_ << 32) + entity.gen_) ^ hash()(reinterpret_cast(entity.storage_.lock().get())); } }; } // namespace std \ No newline at end of file diff --git a/DummyEngine/Core/ECS/EntityManager.hpp b/DummyEngine/Core/ECS/EntityManager.hpp index f52d7bc..60b9f06 100644 --- a/DummyEngine/Core/ECS/EntityManager.hpp +++ b/DummyEngine/Core/ECS/EntityManager.hpp @@ -1,48 +1,48 @@ #pragma once -namespace DE { +namespace DummyEngine { #ifdef ECS_IMPLEMENTATION std::pair EntityManager::CreateEntity() { - if (m_AvailableEntities.empty()) { - m_AvailableEntities.push(m_States.size()); - m_States.push_back(false); - m_Generations.push_back(0); + if (available_entities_.empty()) { + available_entities_.push(states_.size()); + states_.push_back(false); + generations_.push_back(0); } - auto id = m_AvailableEntities.front(); - m_AvailableEntities.pop(); - m_States[id] = true; - ++m_Generations[id]; - return std::make_pair(id, m_Generations[id]); + auto id = available_entities_.front(); + available_entities_.pop(); + states_[id] = true; + ++generations_[id]; + return std::make_pair(id, generations_[id]); } void EntityManager::Destroy(U32 id) { - m_States[id] = false; - m_AvailableEntities.push(id); + states_[id] = false; + available_entities_.push(id); } bool EntityManager::Valid(U32 id, U32 gen) const { - return m_States[id] && m_Generations[id] == gen; + return states_[id] && generations_[id] == gen; } U32 EntityManager::NextEntity(U32 id) const { - if (id >= m_States.size()) { - return m_States.size(); + if (id >= states_.size()) { + return states_.size(); } do { ++id; - } while (id < m_States.size() && !m_States[id]); + } while (id < states_.size() && !states_[id]); return id; } U32 EntityManager::Generation(U32 id) const { - return m_Generations[id]; + return generations_[id]; } U32 EntityManager::BeginEntity() const { U32 res = 0; - while (res < m_States.size() && !m_States[res]) { + while (res < states_.size() && !states_[res]) { ++res; } return res; } U32 EntityManager::EndEntity() const { - return m_States.size(); + return states_.size(); } #endif -} // namespace DE \ No newline at end of file +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/ECS/Storage.hpp b/DummyEngine/Core/ECS/Storage.hpp index 347e631..02d5e51 100644 --- a/DummyEngine/Core/ECS/Storage.hpp +++ b/DummyEngine/Core/ECS/Storage.hpp @@ -1,40 +1,40 @@ #pragma once -namespace DE { +namespace DummyEngine { #ifdef ECS_IMPLEMENTATION - Storage::Storage() : m_ComponentManager(this), m_SystemManager(this) {} + Storage::Storage() : component_manager_(this), system_manager_(this) {} void Storage::Destruct() { - for (U32 id = m_EntityManager.BeginEntity(); id != m_EntityManager.EndEntity(); id = m_EntityManager.NextEntity(id)) { - m_ComponentManager.Destroy(id); - m_EntityManager.Destroy(id); + for (U32 id = entity_manager_.BeginEntity(); id != entity_manager_.EndEntity(); id = entity_manager_.NextEntity(id)) { + component_manager_.Destroy(id); + entity_manager_.Destroy(id); } } Entity Storage::CreateEntity() { - auto [id, gen] = m_EntityManager.CreateEntity(); + auto [id, gen] = entity_manager_.CreateEntity(); Entity ent; - ent.m_ID = id; - ent.m_Gen = gen; - ent.m_Storage = weak_from_this(); + ent.id_ = id; + ent.gen_ = gen; + ent.storage_ = weak_from_this(); return ent; } void Storage::UpdateSystems(float dt) { - m_SystemManager.Update(dt); + system_manager_.Update(dt); } Entity Storage::GetEntity(U32 id) { Entity res; - res.m_ID = id; - res.m_Gen = m_EntityManager.Generation(id); - res.m_Storage = weak_from_this(); + res.id_ = id; + res.gen_ = entity_manager_.Generation(id); + res.storage_ = weak_from_this(); return res; } bool Storage::Valid(U32 id, U32 gen) const { - return m_EntityManager.Valid(id, gen); + return entity_manager_.Valid(id, gen); } void Storage::Destroy(U32 id, U32 gen) { - if (m_EntityManager.Valid(id, gen)) { - m_ComponentManager.Destroy(id); - m_EntityManager.Destroy(id); + if (entity_manager_.Valid(id, gen)) { + component_manager_.Destroy(id); + entity_manager_.Destroy(id); } } #endif @@ -43,29 +43,29 @@ namespace DE { } template void Storage::SetAddHandler(std::function func) { - m_ComponentManager.SetAddHandler(func); + component_manager_.SetAddHandler(func); } template void Storage::SetRemoveHandler(std::function func) { - m_ComponentManager.SetRemoveHandler(func); + component_manager_.SetRemoveHandler(func); } template void Storage::AttachSystem(std::shared_ptr system) { - m_SystemManager.AttachSystem(system); + system_manager_.AttachSystem(system); } template ComponentType* Storage::AddComponent(U32 id, U32 gen, const ComponentType& component) { - return (m_EntityManager.Valid(id, gen) ? m_ComponentManager.AddComponent(id, component) : nullptr); + return (entity_manager_.Valid(id, gen) ? component_manager_.AddComponent(id, component) : nullptr); } template ComponentType* Storage::GetComponent(U32 id, U32 gen) { - return (m_EntityManager.Valid(id, gen) ? m_ComponentManager.GetComponent(id) : nullptr); + return (entity_manager_.Valid(id, gen) ? component_manager_.GetComponent(id) : nullptr); } template bool Storage::HasComponent(U32 id, U32 gen) const { - return (m_EntityManager.Valid(id, gen) ? m_ComponentManager.HasComponent(id) : false); + return (entity_manager_.Valid(id, gen) ? component_manager_.HasComponent(id) : false); } template void Storage::RemoveComponent(U32 id, U32 gen) { - if (m_EntityManager.Valid(id, gen)) { - m_ComponentManager.RemoveComponent(id); + if (entity_manager_.Valid(id, gen)) { + component_manager_.RemoveComponent(id); } } -} // namespace DE \ No newline at end of file +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/ECS/StorageView.hpp b/DummyEngine/Core/ECS/StorageView.hpp index ae1f482..5cb3789 100644 --- a/DummyEngine/Core/ECS/StorageView.hpp +++ b/DummyEngine/Core/ECS/StorageView.hpp @@ -1,28 +1,28 @@ #pragma once -namespace DE { +namespace DummyEngine { - template StorageView::Iterator::Iterator(U32 id, StorageView* v) : m_ID(id), m_View(v) {} + template StorageView::Iterator::Iterator(U32 id, StorageView* v) : id_(id), view_(v) {} template bool StorageView::Iterator::operator==(const Iterator& other) const { - return m_View == other.m_View && m_ID == other.m_ID; + return view_ == other.view_ && id_ == other.id_; } template bool StorageView::Iterator::operator!=(const Iterator& other) const { - return m_View != other.m_View || m_ID != other.m_ID; + return view_ != other.view_ || id_ != other.id_; } - template StorageView::StorageView(Storage* storage) : m_Storage(storage) { - m_Signature = m_Storage->m_ComponentManager.BuildSignature(); + template StorageView::StorageView(Storage* storage) : storage_(storage) { + signature_ = storage_->component_manager_.BuildSignature(); } template typename StorageView::Iterator StorageView::begin() { - Iterator res(m_Storage->m_EntityManager.BeginEntity(), this); - if (!m_Storage->m_ComponentManager.Matches(res.m_ID, m_Signature)) { + Iterator res(storage_->entity_manager_.BeginEntity(), this); + if (!storage_->component_manager_.Matches(res.id_, signature_)) { ++res; } return res; } template typename StorageView::Iterator StorageView::end() { - return Iterator(m_Storage->m_EntityManager.EndEntity(), this); + return Iterator(storage_->entity_manager_.EndEntity(), this); } template bool StorageView::Empty() { return begin() == end(); @@ -30,23 +30,23 @@ namespace DE { template typename StorageView::Iterator& StorageView::Iterator::operator++() { do { - m_ID = m_View->m_Storage->m_EntityManager.NextEntity(m_ID); - } while (m_ID != m_View->m_Storage->m_EntityManager.EndEntity() && !m_View->m_Storage->m_ComponentManager.Matches(m_ID, m_View->m_Signature)); + id_ = view_->storage_->entity_manager_.NextEntity(id_); + } while (id_ != view_->storage_->entity_manager_.EndEntity() && !view_->storage_->component_manager_.Matches(id_, view_->signature_)); return *this; } template typename StorageView::Iterator StorageView::Iterator::operator++(int) { auto res = *this; do { - m_ID = m_View->m_Storage->m_EntityManager.NextEntity(m_ID); - } while (m_ID != m_View->m_Storage->m_EntityManager.EndEntity() && m_View->m_Storage->m_ComponentManager.Matches(m_ID, m_View->m_Signature)); + id_ = view_->storage_->entity_manager_.NextEntity(id_); + } while (id_ != view_->storage_->entity_manager_.EndEntity() && view_->storage_->component_manager_.Matches(id_, view_->signature_)); return res; } template Entity StorageView::Iterator::operator*() { Entity res; - res.m_ID = m_ID; - res.m_Gen = m_View->m_Storage->m_EntityManager.Generation(m_ID); - res.m_Storage = m_View->m_Storage->weak_from_this(); + res.id_ = id_; + res.gen_ = view_->storage_->entity_manager_.Generation(id_); + res.storage_ = view_->storage_->weak_from_this(); return res; } -} // namespace DE \ No newline at end of file +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/ECS/System.hpp b/DummyEngine/Core/ECS/System.hpp index 2a9db2a..a9ec375 100644 --- a/DummyEngine/Core/ECS/System.hpp +++ b/DummyEngine/Core/ECS/System.hpp @@ -1,12 +1,12 @@ #pragma once -namespace DE { +namespace DummyEngine { #ifdef ECS_IMPLEMENTATION void System::Bind(Storage* storage) { - m_Storage = storage; + storage_ = storage; } #endif template StorageView System::View() { - return m_Storage->View(); + return storage_->View(); } -} // namespace DE \ No newline at end of file +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/ECS/SystemManager.hpp b/DummyEngine/Core/ECS/SystemManager.hpp index e0decb1..4bfc013 100644 --- a/DummyEngine/Core/ECS/SystemManager.hpp +++ b/DummyEngine/Core/ECS/SystemManager.hpp @@ -1,23 +1,23 @@ #pragma once -namespace DE { +namespace DummyEngine { #ifdef ECS_IMPLEMENTATION SystemManager::SystemManager(Storage* storage) { - m_Storage = storage; + storage_ = storage; } void SystemManager::Update(float dt) { - for (auto& system : m_Systems) { + for (auto& system : systems_) { system->Update(dt); } } #endif template void SystemManager::AddDependency() {} template void SystemManager::AttachSystem(std::shared_ptr system) { - if (m_SystemId.find(INDEX(SystemType)) == m_SystemId.end()) { - size_t sz = m_SystemId.size(); - m_SystemId[INDEX(SystemType)] = sz; - m_Systems.push_back(system); - m_Systems.back()->Bind(m_Storage); + if (system_ids_.find(INDEX(SystemType)) == system_ids_.end()) { + size_t sz = system_ids_.size(); + system_ids_[INDEX(SystemType)] = sz; + systems_.push_back(system); + systems_.back()->Bind(storage_); } } -} // namespace DE +} // namespace DummyEngine diff --git a/DummyEngine/Core/Objects/Cameras/FPSCamera.cpp b/DummyEngine/Core/Objects/Cameras/FPSCamera.cpp index d8119e2..33dcffb 100644 --- a/DummyEngine/Core/Objects/Cameras/FPSCamera.cpp +++ b/DummyEngine/Core/Objects/Cameras/FPSCamera.cpp @@ -1,74 +1,76 @@ -#include "DummyEngine/Core/Objects/Cameras/FPSCamera.h" +#include "FPSCamera.h" -#ifndef M_PI -#define M_PI 3.14159265358979323846f -#endif +#include // IWYU pragma: export -namespace DE { +namespace DummyEngine { FPSCamera::FPSCamera() { SetDir(Vec3(0.0f, 0.0f, -1.0f)); } FPSCamera::FPSCamera(Vec3 camera_position) : FPSCamera() { - m_Position = camera_position; + Position = camera_position; } FPSCamera::FPSCamera(Vec3 camera_position, Vec3 camera_direction) : FPSCamera(camera_position) { - m_Direction = glm::normalize(camera_direction); - m_Right = glm::normalize(glm::cross(m_Direction, m_WorldUp)); - m_Up = glm::normalize(glm::cross(m_Right, m_Direction)); - m_FarPlane = 100; - m_NearPlane = -10; + Direction = glm::normalize(camera_direction); + Right = glm::normalize(glm::cross(Direction, WorldUp)); + Up = glm::normalize(glm::cross(Right, Direction)); + FarPlane = 100; + NearPlane = -10; } void FPSCamera::MoveInWorld(const Vec3& delta) { - m_Position += delta; + Position += delta; } void FPSCamera::MoveInLocal(const Vec3& delta) { - m_Position += delta.x * m_Right; - m_Position += delta.y * m_Up; - m_Position += delta.z * m_Direction; + Position += delta.x * Right; + Position += delta.y * Up; + Position += delta.z * Direction; } void FPSCamera::RotateY(float angle) { - SetDir(glm::rotate(m_Direction, glm::radians(-angle), m_WorldUp)); + SetDir(glm::rotate(Direction, glm::radians(-angle), WorldUp)); } void FPSCamera::RotateX(float angle) { angle *= -1; float critical_angle = 89.0f; - float h_angle = glm::angle(m_Direction, m_WorldUp) * 180 / M_PI; + float h_angle = glm::angle(Direction, WorldUp) * 180 / M_PI; h_angle = -90.0f + (180 - h_angle); float new_h_angle = angle + h_angle; - if (new_h_angle > critical_angle) new_h_angle = critical_angle; - if (new_h_angle < -critical_angle) new_h_angle = -critical_angle; - SetDir(glm::rotate(m_Direction, glm::radians(new_h_angle - h_angle), m_Right)); + if (new_h_angle > critical_angle) { + new_h_angle = critical_angle; + } + if (new_h_angle < -critical_angle) { + new_h_angle = -critical_angle; + } + SetDir(glm::rotate(Direction, glm::radians(new_h_angle - h_angle), Right)); } Mat4 FPSCamera::GetProjectionMatrix() const { Mat4 projection = Mat4(1.0f); - projection = glm::perspective(glm::radians(m_FOV), m_Aspect, m_NearPlane, m_FarPlane); + projection = glm::perspective(glm::radians(FOV), Aspect, NearPlane, FarPlane); return projection; } Mat4 FPSCamera::GetOrthoProjectionMatrix() const { Mat4 projection = Mat4(1.0f); - projection = glm::ortho(-100.f, 100.f, -100.f, 100.f, m_NearPlane, m_FarPlane); + projection = glm::ortho(-100.f, 100.f, -100.f, 100.f, NearPlane, FarPlane); return projection; } Mat4 FPSCamera::GetViewMatrix() const { Mat4 view = Mat4(1.0f); Mat4 buff = Mat4(1.0f); - buff[0][0] = m_Right.x; - buff[1][0] = m_Right.y; - buff[2][0] = m_Right.z; - buff[0][1] = m_Up.x; - buff[1][1] = m_Up.y; - buff[2][1] = m_Up.z; - buff[0][2] = -m_Direction.x; - buff[1][2] = -m_Direction.y; - buff[2][2] = -m_Direction.z; + buff[0][0] = Right.x; + buff[1][0] = Right.y; + buff[2][0] = Right.z; + buff[0][1] = Up.x; + buff[1][1] = Up.y; + buff[2][1] = Up.z; + buff[0][2] = -Direction.x; + buff[1][2] = -Direction.y; + buff[2][2] = -Direction.z; view = view * buff; - view = glm::translate(view, -m_Position); + view = glm::translate(view, -Position); return view; } Mat4 FPSCamera::GetViewProjection() const { @@ -76,51 +78,51 @@ namespace DE { } Vec3 FPSCamera::GetPos() const { - return m_Position; + return Position; } Vec3 FPSCamera::GetDir() const { - return m_Direction; + return Direction; } float FPSCamera::GetFov() const { - return m_FOV; + return FOV; } float FPSCamera::GetAspect() const { - return m_Aspect; + return Aspect; } float FPSCamera::GetNearPlane() const { - return m_NearPlane; + return NearPlane; } float FPSCamera::GetFarPlane() const { - return m_FarPlane; + return FarPlane; } void FPSCamera::LookAt(Vec3 point) { - m_Direction = glm::normalize(point - m_Position); + Direction = glm::normalize(point - Position); } void FPSCamera::SetDir(Vec3 camera_direction) { - m_Direction = glm::normalize(camera_direction); - m_Right = glm::normalize(glm::cross(m_Direction, m_WorldUp)); - m_Up = glm::normalize(glm::cross(m_Right, m_Direction)); + Direction = glm::normalize(camera_direction); + Right = glm::normalize(glm::cross(Direction, WorldUp)); + Up = glm::normalize(glm::cross(Right, Direction)); } void FPSCamera::SetPos(Vec3 pos) { - m_Position = pos; + Position = pos; } void FPSCamera::SetFov(float fov) { - m_FOV = fov; - if (m_FOV > 179.0f) { - m_FOV = 179.0f; + FOV = fov; + if (FOV > 179.0f) { + FOV = 179.0f; } - if (m_FOV < 1.0f) { - m_FOV = 1.0f; + if (FOV < 1.0f) { + FOV = 1.0f; } } void FPSCamera::SetAspect(float aspect) { - m_Aspect = aspect; + Aspect = aspect; } void FPSCamera::SetNearPlane(float dist) { - m_NearPlane = dist; + NearPlane = dist; } void FPSCamera::SetFarPlane(float dist) { - m_FarPlane = dist; + FarPlane = dist; } -} // namespace DE \ No newline at end of file +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Objects/Cameras/FPSCamera.h b/DummyEngine/Core/Objects/Cameras/FPSCamera.h index 99edfe2..57fa723 100644 --- a/DummyEngine/Core/Objects/Cameras/FPSCamera.h +++ b/DummyEngine/Core/Objects/Cameras/FPSCamera.h @@ -1,27 +1,27 @@ #pragma once -#include "DummyEngine/Utils/Base.h" +#include "DummyEngine/Utils/Types/Constants.h" +#include "DummyEngine/Utils/Types/Types.h" -namespace DE { - class SceneLoader; +namespace DummyEngine { class FPSCamera { // TODO: Rework when render graph implemented public: - float m_FOV = Constants::DefaultCameraFOV; - float m_Aspect = Constants::DefaultCameraAspect; - float m_NearPlane = Constants::DefaultCameraNearPlane; - float m_FarPlane = Constants::DefaultCameraFarPlane; + float FOV = Constants::kDefaultCameraFOV; + float Aspect = Constants::kDefaultCameraAspect; + float NearPlane = Constants::kDefaultCameraNearPlane; + float FarPlane = Constants::kDefaultCameraFarPlane; - Vec3 m_WorldUp = Vec3(0.0f, 1.0f, 0.0f); - Vec3 m_Position = Vec3(0.0f, 0.0f, 0.0f); - Vec3 m_Direction; - Vec3 m_Right; - Vec3 m_Up; + Vec3 WorldUp = Vec3(0.0f, 1.0f, 0.0f); + Vec3 Position = Vec3(0.0f, 0.0f, 0.0f); + Vec3 Direction; + Vec3 Right; + Vec3 Up; FPSCamera(); - FPSCamera(Vec3 camera_position); FPSCamera(Vec3 camera_position, Vec3 camera_direction); + explicit FPSCamera(Vec3 camera_position); Mat4 GetViewMatrix() const; Mat4 GetProjectionMatrix() const; @@ -48,4 +48,5 @@ namespace DE { void MoveInWorld(const Vec3& delta); void MoveInLocal(const Vec3& delta); }; -} // namespace DE \ No newline at end of file + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Objects/LightSources/LightSource.cpp b/DummyEngine/Core/Objects/LightSources/LightSource.cpp index 2148360..70a2005 100644 --- a/DummyEngine/Core/Objects/LightSources/LightSource.cpp +++ b/DummyEngine/Core/Objects/LightSources/LightSource.cpp @@ -1,6 +1,6 @@ #include "DummyEngine/Core/Objects/LightSources/LightSource.h" -namespace DE { +namespace DummyEngine { std::string LightSourceTypeToString(LightSourceType type) { switch (type) { @@ -24,4 +24,5 @@ namespace DE { default: return 0; } } -} // namespace DE \ No newline at end of file + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Objects/LightSources/LightSource.h b/DummyEngine/Core/Objects/LightSources/LightSource.h index b151bf0..70a00a4 100644 --- a/DummyEngine/Core/Objects/LightSources/LightSource.h +++ b/DummyEngine/Core/Objects/LightSources/LightSource.h @@ -1,8 +1,9 @@ #pragma once -#include "DummyEngine/Utils/Base.h" +#include "DummyEngine/Utils/Types/Types.h" + +namespace DummyEngine { -namespace DE { enum class LightSourceType { Direction = 0, Point = 1, @@ -14,15 +15,15 @@ namespace DE { U32 LightSourceTypeToId(LightSourceType type); struct LightSource { - LightSourceType type; - Vec3 ambient = Vec3(1.0f); - Vec3 diffuse = Vec3(1.0f); - Vec3 specular = Vec3(1.0f); - Vec3 direction = Vec3(0.0f, -1.0f, 0.0f); - Vec3 position = Vec3(0.0f); - Vec3 clq = Vec3(1.0f, 0.007f, 0.0002f); - float outer_cone_cos; - float inner_cone_cos; + LightSourceType Type; + Vec3 Ambient = Vec3(1.0f); + Vec3 Diffuse = Vec3(1.0f); + Vec3 Specular = Vec3(1.0f); + Vec3 Direction = Vec3(0.0f, -1.0f, 0.0f); + Vec3 Position = Vec3(0.0f); + Vec3 CLQ = Vec3(1.0f, 0.007f, 0.0002f); + float OuterConeCosinus; + float InnerConeCosinus; }; -} // namespace DE \ No newline at end of file +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Physics/ConvexCollider.cpp b/DummyEngine/Core/Physics/ConvexCollider.cpp index cee701d..981f2f8 100644 --- a/DummyEngine/Core/Physics/ConvexCollider.cpp +++ b/DummyEngine/Core/Physics/ConvexCollider.cpp @@ -1,236 +1,239 @@ #include "ConvexCollider.hpp" #include "DummyEngine/Core/Physics/Utils.hpp" -#include "DummyEngine/Utils/Base.h" - -void DE::Physics::ConvexHitbox::Build(const std::vector& mesh) { - float min_x = mesh[0].x, max_x = mesh[0].x; - float min_y = mesh[0].y, max_y = mesh[0].y; - float min_z = mesh[0].z, max_z = mesh[0].z; - _center_of_mass = Vec3(0); - _center_of_mass += mesh[0]; - for (size_t i = 1; i < mesh.size(); i++) { - min_x = std::min(min_x, mesh[i].x); - min_y = std::min(min_y, mesh[i].y); - min_z = std::min(min_z, mesh[i].z); - - max_x = std::max(max_x, mesh[i].x); - max_y = std::max(max_y, mesh[i].y); - max_z = std::max(max_z, mesh[i].z); - - _center_of_mass += mesh[i]; - } - _center_of_mass /= mesh.size(); +namespace DummyEngine { - _points.emplace_back(min_x, min_y, min_z); - _points.emplace_back(max_x, min_y, min_z); - _points.emplace_back(min_x, max_y, min_z); - _points.emplace_back(min_x, min_y, max_z); - _points.emplace_back(max_x, max_y, min_z); - _points.emplace_back(min_x, max_y, max_z); - _points.emplace_back(max_x, min_y, max_z); - _points.emplace_back(max_x, max_y, max_z); + void Physics::ConvexHitbox::Build(const std::vector& mesh) { + float min_x = mesh[0].x, max_x = mesh[0].x; + float min_y = mesh[0].y, max_y = mesh[0].y; + float min_z = mesh[0].z, max_z = mesh[0].z; + center_of_mass_ = Vec3(0); + center_of_mass_ += mesh[0]; + for (size_t i = 1; i < mesh.size(); i++) { + min_x = std::min(min_x, mesh[i].x); + min_y = std::min(min_y, mesh[i].y); + min_z = std::min(min_z, mesh[i].z); - _edges.resize(8); + max_x = std::max(max_x, mesh[i].x); + max_y = std::max(max_y, mesh[i].y); + max_z = std::max(max_z, mesh[i].z); - _edges[0].push_back(1); - _edges[0].push_back(2); - _edges[0].push_back(3); + center_of_mass_ += mesh[i]; + } - _edges[1].push_back(0); - _edges[1].push_back(4); - _edges[1].push_back(6); + center_of_mass_ /= mesh.size(); - _edges[2].push_back(0); - _edges[2].push_back(4); - _edges[2].push_back(5); + points_.emplace_back(min_x, min_y, min_z); + points_.emplace_back(max_x, min_y, min_z); + points_.emplace_back(min_x, max_y, min_z); + points_.emplace_back(min_x, min_y, max_z); + points_.emplace_back(max_x, max_y, min_z); + points_.emplace_back(min_x, max_y, max_z); + points_.emplace_back(max_x, min_y, max_z); + points_.emplace_back(max_x, max_y, max_z); - _edges[3].push_back(0); - _edges[3].push_back(5); - _edges[3].push_back(6); + edges_.resize(8); - _edges[4].push_back(1); - _edges[4].push_back(2); - _edges[4].push_back(7); + edges_[0].push_back(1); + edges_[0].push_back(2); + edges_[0].push_back(3); - _edges[5].push_back(2); - _edges[5].push_back(3); - _edges[5].push_back(7); + edges_[1].push_back(0); + edges_[1].push_back(4); + edges_[1].push_back(6); - _edges[6].push_back(1); - _edges[6].push_back(3); - _edges[6].push_back(7); + edges_[2].push_back(0); + edges_[2].push_back(4); + edges_[2].push_back(5); - _edges[7].push_back(4); - _edges[7].push_back(5); - _edges[7].push_back(6); + edges_[3].push_back(0); + edges_[3].push_back(5); + edges_[3].push_back(6); - _size = 8; -} + edges_[4].push_back(1); + edges_[4].push_back(2); + edges_[4].push_back(7); -DE::Physics::ConvexCollider::ConvexCollider(const DE::Ref& hitbox) : _hitbox(hitbox), _transform(1) {} + edges_[5].push_back(2); + edges_[5].push_back(3); + edges_[5].push_back(7); -void DE::Physics::ConvexCollider::UpdateTransformationMatrix(const DE::Mat4& transform) { - _transform = transform; -} + edges_[6].push_back(1); + edges_[6].push_back(3); + edges_[6].push_back(7); -DE::Vec3 DE::Physics::ConvexCollider::GetPoint(const size_t idx) const { - Vec4 cpt(_hitbox->_points[idx], 1); - cpt = _transform * cpt; - return cpt; -} + edges_[7].push_back(4); + edges_[7].push_back(5); + edges_[7].push_back(6); -DE::Vec3 DE::Physics::ConvexCollider::Collide(const DE::Physics::ConvexCollider& oth) const { - std::vector axis; - for (U32 i = 1; i < DE::Physics::UNIQUE_FACES; ++i) { - Vec3 A = GetPoint(i) - GetPoint(0); - Vec3 B = GetPoint((i + 1) % (UNIQUE_FACES - 1) + 1) - GetPoint(0); - axis.push_back(glm::normalize(glm::cross(A, B))); + size_ = 8; } - for (U32 i = 1; i < DE::Physics::UNIQUE_FACES; ++i) { - Vec3 A = oth.GetPoint(i) - oth.GetPoint(0); - Vec3 B = oth.GetPoint((i + 1) % (UNIQUE_FACES - 1) + 1) - oth.GetPoint(0); - axis.push_back(glm::normalize(glm::cross(A, B))); + Physics::ConvexCollider::ConvexCollider(const Ref& hitbox) : hitbox_(hitbox), transform_(1) {} + + void Physics::ConvexCollider::UpdateTransformationMatrix(const Mat4& transform) { + transform_ = transform; } - for (U32 i = 1; i < DE::Physics::UNIQUE_FACES; ++i) { - Vec3 A = GetPoint(i) - GetPoint(0); - for (U32 j = 1; j < DE::Physics::UNIQUE_FACES; ++j) { - Vec3 B = oth.GetPoint((j + 1) % (UNIQUE_FACES - 1) + 1) - oth.GetPoint(0); - Vec3 cross = glm::cross(A, B); - if (glm::length(cross) == 0) { - axis.push_back(glm::normalize(cross)); - } - } + Vec3 Physics::ConvexCollider::GetPoint(const size_t idx) const { + Vec4 cpt(hitbox_->points_[idx], 1); + cpt = transform_ * cpt; + return cpt; } - Vec3 norm(1e9); - for (auto axle : axis) { - float min_a, max_a, min_b, max_b; - for (size_t i = 0; i < _hitbox->_points.size(); i++) { - float proj = glm::dot(GetPoint(i), axle); - if (i == 0 || proj < min_a) { - min_a = proj; - } - if (i == 0 || proj > max_a) { - max_a = proj; + Vec3 Physics::ConvexCollider::Collide(const Physics::ConvexCollider& oth) const { + std::vector axis; + for (U32 i = 1; i < Physics::kUniqueFaces; ++i) { + Vec3 a = GetPoint(i) - GetPoint(0); + Vec3 b = GetPoint((i + 1) % (kUniqueFaces - 1) + 1) - GetPoint(0); + axis.push_back(glm::normalize(glm::cross(a, b))); + } + + for (U32 i = 1; i < Physics::kUniqueFaces; ++i) { + Vec3 a = oth.GetPoint(i) - oth.GetPoint(0); + Vec3 b = oth.GetPoint((i + 1) % (kUniqueFaces - 1) + 1) - oth.GetPoint(0); + axis.push_back(glm::normalize(glm::cross(a, b))); + } + + for (U32 i = 1; i < Physics::kUniqueFaces; ++i) { + Vec3 a = GetPoint(i) - GetPoint(0); + for (U32 j = 1; j < Physics::kUniqueFaces; ++j) { + Vec3 b = oth.GetPoint((j + 1) % (kUniqueFaces - 1) + 1) - oth.GetPoint(0); + Vec3 cross = glm::cross(a, b); + if (glm::length(cross) == 0) { + axis.push_back(glm::normalize(cross)); + } } } - for (size_t i = 0; i < oth._hitbox->_points.size(); i++) { - float proj = glm::dot(oth.GetPoint(i), axle); - if (i == 0 || proj < min_b) { - min_b = proj; + Vec3 norm(1e9); + for (auto axle : axis) { + float min_a, max_a, min_b, max_b; + for (size_t i = 0; i < hitbox_->points_.size(); i++) { + float proj = glm::dot(GetPoint(i), axle); + if (i == 0 || proj < min_a) { + min_a = proj; + } + if (i == 0 || proj > max_a) { + max_a = proj; + } } - if (i == 0 || proj > max_b) { - max_b = proj; + + for (size_t i = 0; i < oth.hitbox_->points_.size(); i++) { + float proj = glm::dot(oth.GetPoint(i), axle); + if (i == 0 || proj < min_b) { + min_b = proj; + } + if (i == 0 || proj > max_b) { + max_b = proj; + } } - } - std::array pts{min_a, min_b, max_a, max_b}; - std::sort(pts.begin(), pts.end()); + std::array pts{min_a, min_b, max_a, max_b}; + std::sort(pts.begin(), pts.end()); - float sum = max_a - min_a + max_b - min_b; - float len = pts[3] - pts[0]; - if (sum <= len) { - return Vec3(0); + float sum = max_a - min_a + max_b - min_b; + float len = pts[3] - pts[0]; + if (sum <= len) { + return Vec3(0); + } + float intersection_len = pts[2] - pts[1]; + if (intersection_len < glm::length(norm)) { + norm = axle * intersection_len; + if (pts[0] != min_a) { + norm *= -1; + } + } } - float intersection_len = pts[2] - pts[1]; - if (intersection_len < glm::length(norm)) { - norm = axle * intersection_len; - if (pts[0] != min_a) { - norm *= -1; + return norm; + } + Vec3 Physics::ConvexCollider::GetCollisionPoint(const Vec3& collision_normal, int& cnt) const { + Vec3 norm = glm::normalize(collision_normal); + float best = glm::dot(norm, GetPoint(0)); + for (const auto& pt : hitbox_->points_) { + best = std::max(best, glm::dot(norm, TransformPoint(pt))); + } + Vec3 sum(0); + cnt = 0; + for (const auto& pt : hitbox_->points_) { + TransformPoint(pt); + if (std::abs(glm::dot(norm, TransformPoint(pt)) - best) < 1e-7) { + cnt++; + sum += TransformPoint(pt); } } + return sum / static_cast(cnt); } - return norm; -} -DE::Vec3 DE::Physics::ConvexCollider::GetCollisionPoint(const DE::Vec3& collisionNormal, int& cnt) const { - Vec3 norm = glm::normalize(collisionNormal); - float best = glm::dot(norm, GetPoint(0)); - for (const auto& pt : _hitbox->_points) { - best = std::max(best, glm::dot(norm, TransformPoint(pt))); + Vec3 Physics::ConvexCollider::Normalize(const Vec3& vec) const { + Vec4 cpt(vec, 1); + cpt = glm::inverse(transform_) * cpt; + return cpt; } - Vec3 sum(0); - cnt = 0; - for (const auto& pt : _hitbox->_points) { - TransformPoint(pt); - if (std::abs(glm::dot(norm, TransformPoint(pt)) - best) < 1e-7) { - cnt++; - sum += TransformPoint(pt); - } + Vec3 Physics::ConvexCollider::GetCenterOfMass() const { + return hitbox_->center_of_mass_; } - return sum / static_cast(cnt); -} -DE::Vec3 DE::Physics::ConvexCollider::Normalize(const DE::Vec3& vec) const { - Vec4 cpt(vec, 1); - cpt = glm::inverse(_transform) * cpt; - return cpt; -} -DE::Vec3 DE::Physics::ConvexCollider::GetCenterOfMass() const { - return _hitbox->_center_of_mass; -} -DE::Vec3 DE::Physics::ConvexCollider::TransformPoint(const DE::Vec3& vec) const { - Vec4 cpt(vec, 1); - cpt = _transform * cpt; - return cpt; -} - -std::vector DE::Physics::ConvexCollider::GetCollisionCenter(const DE::Vec3& collisionNormal, const DE::Vec3& planePt, float& area) const { - Plane pl(collisionNormal, planePt); - std::vector side(_hitbox->_size, false); - std::vector pts_res; - for (size_t i = 0; i < _hitbox->_size; i++) { - Vec3 pt = GetPoint(i); - side[i] = (pl.distance(pt) >= 0); + Vec3 Physics::ConvexCollider::TransformPoint(const Vec3& vec) const { + Vec4 cpt(vec, 1); + cpt = transform_ * cpt; + return cpt; } - for (size_t i = 0; i < _hitbox->_size; i++) { - Vec3 lhs = GetPoint(i); - if (pl.distance(lhs) == 0) { - // LOG_DEBUG("GCC PTA {}", lhs); - pts_res.push_back(lhs); + + std::vector Physics::ConvexCollider::GetCollisionCenter(const Vec3& collision_normal, const Vec3& plane_pt, float& area) const { + Plane pl(collision_normal, plane_pt); + std::vector side(hitbox_->size_, false); + std::vector pts_res; + for (size_t i = 0; i < hitbox_->size_; i++) { + Vec3 pt = GetPoint(i); + side[i] = (pl.Distance(pt) >= 0); } - for (const auto& j : _hitbox->_edges[i]) { - if (side[i] == side[j]) continue; - Vec3 rhs = GetPoint(j); - Vec3 pt = pl.intersectionPoint(lhs, rhs); - // LOG_DEBUG("GCC PTI {}", pt); - pts_res.push_back(pt); + for (size_t i = 0; i < hitbox_->size_; i++) { + Vec3 lhs = GetPoint(i); + if (pl.Distance(lhs) == 0) { + // LOG_DEBUG("GCC PTA {}", lhs); + pts_res.push_back(lhs); + } + for (const auto& j : hitbox_->edges_[i]) { + if (side[i] == side[j]) continue; + Vec3 rhs = GetPoint(j); + Vec3 pt = pl.IntersectionPoint(lhs, rhs); + // LOG_DEBUG("GCC PTI {}", pt); + pts_res.push_back(pt); + } + } + Vec3 center(0), u, v; + bool calc_area = false; + float x_min, y_min, x_max, y_max; + if (pts_res.size() > 2) { + calc_area = true; + u = glm::normalize(pts_res[1] - pts_res[0]); + v = glm::normalize(glm::cross(u, collision_normal)); + + float x = glm::dot(pts_res[0], u); + float y = glm::dot(pts_res[0], v); + x_min = x_max = x; + y_min = y_max = y; + } else { + area = 0; + } + for (const Vec3& pt : pts_res) { + center += pt; + if (calc_area) { + float x = glm::dot(pt, u); + float y = glm::dot(pt, v); + x_min = std::min(x_min, x); + x_max = std::max(x_max, x); + y_min = std::min(y_min, y); + y_max = std::max(y_max, y); + } + } + if (pts_res.empty()) { + area = -1; } - } - Vec3 center(0), U, V; - bool calc_area = false; - float x_min, y_min, x_max, y_max; - if (pts_res.size() > 2) { - calc_area = true; - U = glm::normalize(pts_res[1] - pts_res[0]); - V = glm::normalize(glm::cross(U, collisionNormal)); - - float x = glm::dot(pts_res[0], U); - float y = glm::dot(pts_res[0], V); - x_min = x_max = x; - y_min = y_max = y; - } else { - area = 0; - } - for (const Vec3& pt : pts_res) { - center += pt; if (calc_area) { - float x = glm::dot(pt, U); - float y = glm::dot(pt, V); - x_min = std::min(x_min, x); - x_max = std::max(x_max, x); - y_min = std::min(y_min, y); - y_max = std::max(y_max, y); + area = (y_max - y_min) * (x_max - x_min); // we dont want real area, simple aabb's area should help a lot } + return pts_res; } - if (pts_res.empty()) { - area = -1; - } - if (calc_area) { - area = (y_max - y_min) * (x_max - x_min); // we dont want real area, simple aabb's area should help a lot - } - return pts_res; -} + +} // namespace DummyEngine diff --git a/DummyEngine/Core/Physics/ConvexCollider.hpp b/DummyEngine/Core/Physics/ConvexCollider.hpp index 89c7228..190a404 100644 --- a/DummyEngine/Core/Physics/ConvexCollider.hpp +++ b/DummyEngine/Core/Physics/ConvexCollider.hpp @@ -1,10 +1,10 @@ #pragma once -#include - #include "DummyEngine/Utils/Debug/Logger.h" -namespace DE::Physics { +#include + +namespace DummyEngine::Physics { class ConvexHitbox { public: @@ -12,14 +12,14 @@ namespace DE::Physics { private: friend class ConvexCollider; - Vec3 _center_of_mass; - std::vector _points; - std::vector> _edges; - size_t _size; + Vec3 center_of_mass_; + std::vector points_; + std::vector> edges_; + size_t size_; }; class ConvexCollider { - LOGGER_AUTHOR(ConvexCollider) + LOG_AUTHOR(ConvexCollider) public: ConvexCollider() = delete; ConvexCollider(const ConvexCollider&) = delete; @@ -30,8 +30,8 @@ namespace DE::Physics { Vec3 GetPoint(size_t idx) const; Vec3 TransformPoint(const Vec3& vec) const; Vec3 Collide(const ConvexCollider& oth) const; - Vec3 GetCollisionPoint(const Vec3& collisionNormal, int& cnt) const; - std::vector GetCollisionCenter(const Vec3& collisionNormal, const Vec3& planePt, float& area) const; + Vec3 GetCollisionPoint(const Vec3& collision_normal, int& cnt) const; + std::vector GetCollisionCenter(const Vec3& collision_normal, const Vec3& plane_pt, float& area) const; Vec3 Normalize(const Vec3& vec) const; Vec3 GetCenterOfMass() const; @@ -39,9 +39,9 @@ namespace DE::Physics { private: friend class ConvexHitbox; - Ref _hitbox; - Mat4 _transform{}; + Ref hitbox_; + Mat4 transform_{}; }; - const U32 UNIQUE_FACES = 4; -} // namespace DE::Physics \ No newline at end of file + constexpr U32 kUniqueFaces = 4; +} // namespace DummyEngine::Physics \ No newline at end of file diff --git a/DummyEngine/Core/Physics/ForceQueue.cpp b/DummyEngine/Core/Physics/ForceQueue.cpp deleted file mode 100644 index abea43b..0000000 --- a/DummyEngine/Core/Physics/ForceQueue.cpp +++ /dev/null @@ -1,25 +0,0 @@ -#include "ForceQueue.hpp" -namespace DE::Physics { - - bool operator<(const QueueObject& lhs, const QueueObject& rhs) { - return lhs.dt < rhs.dt; - } - - ForceQueue* ForceQueue::_instance = nullptr; - - ForceQueue* ForceQueue::getInstance() { - if (ForceQueue::_instance == nullptr) { - ForceQueue::_instance = new ForceQueue(); - } - return ForceQueue::_instance; - } - - void ForceQueue::ApplyForce(double dt, UUID entity_id, Vec3 dest, Vec3 force) { - _queue.push(QueueObject{dt, entity_id, dest, force}); - } - - const QueueObject* ForceQueue::pull() { - return &_queue.top(); - } - -} // namespace DE::Physics diff --git a/DummyEngine/Core/Physics/ForceQueue.hpp b/DummyEngine/Core/Physics/ForceQueue.hpp deleted file mode 100644 index 8f06f4a..0000000 --- a/DummyEngine/Core/Physics/ForceQueue.hpp +++ /dev/null @@ -1,26 +0,0 @@ -#pragma once - -#include "DummyEngine/Utils/Types/Types.h" -#include "DummyEngine/Utils/Types/UUID.h" - -namespace DE::Physics { - - struct QueueObject { - double dt; - - UUID entity_id; - - Vec3 dest, force; - }; - - class ForceQueue { - static ForceQueue* getInstance(); - const QueueObject* pull(); - void ApplyForce(double dt, UUID entity_id, Vec3 dest, Vec3 force); - - private: - std::priority_queue _queue; - static ForceQueue* _instance; - }; - -} // namespace DE::Physics \ No newline at end of file diff --git a/DummyEngine/Core/Physics/PhysicsComponent.h b/DummyEngine/Core/Physics/PhysicsComponent.h index b64d555..0225a31 100644 --- a/DummyEngine/Core/Physics/PhysicsComponent.h +++ b/DummyEngine/Core/Physics/PhysicsComponent.h @@ -1,15 +1,19 @@ #pragma once -namespace DE::Physics { +#include "DummyEngine/Utils/Types/Types.h" + +namespace DummyEngine::Physics { + struct PhysicsComponent { - Vec3 speed; - Vec3 rot_speed; - float inv_mass; - float inv_inertia; - bool collidable; - bool gravity; - - Vec3 force; - Vec3 torque; + Vec3 Speed; + Vec3 RotationSpeed; + float InvertedMass; + float InvertedInertia; + bool Collidable; + bool Gravity; + + Vec3 Force; + Vec3 Torque; }; -} // namespace DE::Physics \ No newline at end of file + +} // namespace DummyEngine::Physics \ No newline at end of file diff --git a/DummyEngine/Core/Physics/SceneConstants.cpp b/DummyEngine/Core/Physics/SceneConstants.cpp deleted file mode 100644 index 61f7beb..0000000 --- a/DummyEngine/Core/Physics/SceneConstants.cpp +++ /dev/null @@ -1,8 +0,0 @@ -#include "SceneConstants.hpp" - -const DE::Vec3& DE::Physics::SceneConstants::getGravity() const { - return _gravity; -} -void DE::Physics::SceneConstants::setGravity(const DE::Vec3& gravity) { - SceneConstants::_gravity = gravity; -} diff --git a/DummyEngine/Core/Physics/SceneConstants.hpp b/DummyEngine/Core/Physics/SceneConstants.hpp deleted file mode 100644 index 645a8db..0000000 --- a/DummyEngine/Core/Physics/SceneConstants.hpp +++ /dev/null @@ -1,15 +0,0 @@ -#pragma once - -#include "DummyEngine/Utils/Types/Types.h" -namespace DE::Physics { - - class SceneConstants { - public: - const Vec3& getGravity() const; - void setGravity(const Vec3& gravity); - - private: - Vec3 _gravity; - }; - -} // namespace DE::Physics \ No newline at end of file diff --git a/DummyEngine/Core/Physics/Solver.cpp b/DummyEngine/Core/Physics/Solver.cpp index 74c454d..e44360c 100644 --- a/DummyEngine/Core/Physics/Solver.cpp +++ b/DummyEngine/Core/Physics/Solver.cpp @@ -1,234 +1,257 @@ #include "Solver.hpp" -#include "PhysicsComponent.h" -#include "Utils.hpp" - +#include "DummyEngine/Core/Physics/PhysicsComponent.h" +#include "DummyEngine/Core/Physics/Utils.hpp" #include "DummyEngine/Core/ResourceManaging/ResourceManager.h" +#include "DummyEngine/Core/Scene/Components.h" +#include "DummyEngine/Core/Scene/Scene.h" -void DE::Physics::Solver::LoadScene(const DE::Ref& scene) { - if (!scene) { - return; - } - _scene = scene; - _constants = CreateRef(); - _constants->setGravity(Vec3(0, -4, 0)); - _time = 0; - for (auto entity : scene->View()) { - UUID id = entity.Get().id; - auto hitbox = ResourceManager::GetHitBox(id); - if (hitbox) { - _colliders.insert({entity.GetComponent()->Get(), CreateRef(*hitbox)}); +#include + +namespace DummyEngine { + + void Physics::Solver::LoadScene(const Ref& scene) { + if (!scene) { + return; } - } -} + scene_ = scene; + constants_.Gravity = Vec3(0, -4, 0); -void DE::Physics::Solver::OnUpdate(double dt) { - auto scene = _scene.lock(); - if (!scene) { - return; - } - _frame++; - double curr_dt = 0; - while (curr_dt < dt) { - curr_dt += NextInteraction(dt - curr_dt); - } -} - -double DE::Physics::Solver::NextInteraction(double dt) { - auto scene = _scene.lock(); - const int SUBTICKS = 10; - std::vector collidableEntities; - for (auto entity : scene->View()) { - auto& phys = entity.Get(); - if (phys.collidable) { - collidableEntities.push_back(entity.Get().Get()); + time_ = 0; + for (auto entity : scene->View()) { + UUID id = entity.Get().ID; + auto hitbox = ResourceManager::GetHitBox(id); + if (hitbox) { + colliders_.insert({entity.GetComponent()->Get(), CreateRef(*hitbox)}); + } } } - float delta = dt / SUBTICKS; - for (int subtick = 0; subtick < SUBTICKS; subtick++) { - for (const auto& id : collidableEntities) { - _colliders[id]->UpdateTransformationMatrix(scene->GetByID(id).Get().GetTransform()); + + void Physics::Solver::OnUpdate(double dt) { + auto scene = scene_.lock(); + if (!scene) { + return; } + frame_++; + double curr_dt = 0; + while (curr_dt < dt) { + curr_dt += NextInteraction(dt - curr_dt); + } + } + + double Physics::Solver::NextInteraction(double dt) { + auto scene = scene_.lock(); + constexpr int kSubtics = 10; + std::vector collidable_entities; for (auto entity : scene->View()) { auto& phys = entity.Get(); - if (phys.gravity) { - phys.speed += _constants->getGravity() * delta; + if (phys.Collidable) { + collidable_entities.push_back(entity.Get().Get()); } - // phys.speed += phys.force * phys.inv_mass * delta; - // phys.rot_speed += phys.torque * phys.inv_inertia * delta; - // if (subtick == 0) { - // phys.speed *= 0.999f; - // phys.rot_speed *= 0.999f; - // } } - for (const auto& lhs : collidableEntities) { - for (const auto& rhs : collidableEntities) { - if (lhs == rhs) { - continue; + float delta = dt / kSubtics; + for (int subtick = 0; subtick < kSubtics; subtick++) { + for (const auto& id : collidable_entities) { + colliders_[id]->UpdateTransformationMatrix(scene->GetByID(id).Get().GetTransform()); + } + for (auto entity : scene->View()) { + auto& phys = entity.Get(); + if (phys.Gravity) { + phys.Speed += constants_.Gravity * delta; } - if (lhs.Hex() >= rhs.Hex()) continue; - auto lhsCollider = _colliders[lhs]; - auto rhsCollider = _colliders[rhs]; - auto collisionNormal = lhsCollider->Collide(*rhsCollider); - if (collisionNormal == Vec3(0)) { - if (mem.find({lhs, rhs}) != mem.end()) { - mem.erase(mem.find({lhs, rhs})); + // phys.speed += phys.force * phys.inv_mass * delta; + // phys.rot_speed += phys.torque * phys.inv_inertia * delta; + // if (subtick == 0) { + // phys.speed *= 0.999f; + // phys.rot_speed *= 0.999f; + // } + } + for (const auto& lhs : collidable_entities) { + for (const auto& rhs : collidable_entities) { + if (lhs == rhs) { + continue; + } + if (lhs.Hex() >= rhs.Hex()) continue; + auto lhs_collider = colliders_[lhs]; + auto rhs_collider = colliders_[rhs]; + auto collision_normal = lhs_collider->Collide(*rhs_collider); + if (collision_normal == Vec3(0)) { + auto it = Memory.find({lhs, rhs}); + if (it != Memory.end()) { + Memory.erase(it); + } + continue; } - continue; - } - bool warmStart = mem.find({lhs, rhs}) != mem.end(); + bool warm_start = Memory.find({lhs, rhs}) != Memory.end(); - // Calc collision point - int lhs_cnt = 0, rhs_cnt = 0; - auto lhs_pt = lhsCollider->GetCollisionPoint(collisionNormal, lhs_cnt); - auto rhs_pt = rhsCollider->GetCollisionPoint(-collisionNormal, rhs_cnt); + // Calc collision point + int lhs_cnt = 0, rhs_cnt = 0; + auto lhs_pt = lhs_collider->GetCollisionPoint(collision_normal, lhs_cnt); + auto rhs_pt = rhs_collider->GetCollisionPoint(-collision_normal, rhs_cnt); - LOG_DEBUG("LHS_PT {}", lhs_pt); - LOG_DEBUG("RHS_PT {}", rhs_pt); - float lhs_area = 0, rhs_area = 0; - auto rhs_pts = lhsCollider->GetCollisionCenter(collisionNormal, rhs_pt, rhs_area); - auto lhs_pts = rhsCollider->GetCollisionCenter(-collisionNormal, lhs_pt, lhs_area); + // LOG_DEBUG("LHS_PT {}", lhs_pt); + // LOG_DEBUG("RHS_PT {}", rhs_pt); + float lhs_area = 0, rhs_area = 0; + auto lhs_pts = rhs_collider->GetCollisionCenter(-collision_normal, lhs_pt, lhs_area); + auto rhs_pts = lhs_collider->GetCollisionCenter(collision_normal, rhs_pt, rhs_area); - auto collision_pts = lhs_pts; - Plane dst_pl(collisionNormal, rhs_pt); - if (lhs_area < 0 || rhs_area < lhs_area) { - collision_pts = rhs_pts; - dst_pl = Plane(-collisionNormal, lhs_pt); - } - for (const auto& collision_pt : collision_pts) { - LOG_DEBUG("CollisionPT {}", collision_pt); - float penetration = std::abs(dst_pl.distance(collision_pt)); - - auto collisionNormal_n = glm::normalize(collisionNormal); - LOG_DEBUG("CollisionNormal {}", collisionNormal_n); - auto lhs_com = lhsCollider->TransformPoint(lhsCollider->GetCenterOfMass()); - auto rhs_com = rhsCollider->TransformPoint(rhsCollider->GetCenterOfMass()); - - auto lhs_r = collision_pt - lhs_com; - auto rhs_r = collision_pt - rhs_com; - LOG_DEBUG("lhs_r {}", lhs_r); - LOG_DEBUG("rhs_r {}", rhs_r); - - Vec3 tangent = glm::normalize(glm::cross(collisionNormal_n, glm::normalize(Vec3(1) + collisionNormal_n))); - Vec3 tangent_b = glm::normalize(glm::cross(collisionNormal_n, tangent)); - - auto list_iterator = mem[{lhs, rhs}].begin(); - if (warmStart) { - for (; list_iterator != mem[{lhs, rhs}].end(); list_iterator++) { - Collision& cl = *list_iterator; - if (glm::length(collisionNormal_n - cl.collision_normal) > 0.01) { - continue; - } - if (glm::length(cl.lhs_pt - collision_pt) < 0.001 && glm::length(cl.rhs_pt - collision_pt) < 0.001) { - break; + auto collision_pts = lhs_pts; + Plane dst_pl(collision_normal, rhs_pt); + if (lhs_area < 0 || rhs_area < lhs_area) { + collision_pts = rhs_pts; + dst_pl = Plane(-collision_normal, lhs_pt); + } + for (const auto& collision_pt : collision_pts) { + // LOG_DEBUG("CollisionPT {}", collision_pt); + float penetration = std::abs(dst_pl.Distance(collision_pt)); + + auto collision_normal_n = glm::normalize(collision_normal); + // LOG_DEBUG("CollisionNormal {}", collision_normal_n); + auto lhs_com = lhs_collider->TransformPoint(lhs_collider->GetCenterOfMass()); + auto rhs_com = rhs_collider->TransformPoint(rhs_collider->GetCenterOfMass()); + + auto lhs_r = collision_pt - lhs_com; + auto rhs_r = collision_pt - rhs_com; + // LOG_DEBUG("LhsR {}", lhs_r); + // LOG_DEBUG("RhsR {}", rhs_r); + + Vec3 tangent = glm::normalize(glm::cross(collision_normal_n, glm::normalize(Vec3(1) + collision_normal_n))); + Vec3 tangent_b = glm::normalize(glm::cross(collision_normal_n, tangent)); + + auto list_iterator = Memory[{lhs, rhs}].begin(); + if (warm_start) { + for (; list_iterator != Memory[{lhs, rhs}].end(); list_iterator++) { + Collision& cl = *list_iterator; + if (glm::length(collision_normal_n - cl.CollisionNormal) > 0.01) { + continue; + } + if (glm::length(cl.LhsPt - collision_pt) < 0.001 && glm::length(cl.RhsPt - collision_pt) < 0.001) { + break; + } } + } else { + list_iterator = Memory[{lhs, rhs}].end(); } - } else { - list_iterator = mem[{lhs, rhs}].end(); - } - if (!warmStart || list_iterator == mem[{lhs, rhs}].end()) { - Collision col{lhs, rhs, collision_pt, collisionNormal_n, penetration, collision_pt, collision_pt, lhs_r, rhs_r}; - col.jN = InitJacobian(col, collisionNormal_n, delta, true); - col.jT = InitJacobian(col, tangent, delta, false); - col.jTb = InitJacobian(col, tangent_b, delta, false); - mem[{lhs, rhs}].push_back(col); - list_iterator = mem[{lhs, rhs}].end(); - list_iterator--; + if (!warm_start || list_iterator == Memory[{lhs, rhs}].end()) { + Collision col{ + .Source = lhs, + .Destination = rhs, + .Origin = collision_pt, + .CollisionNormal = collision_normal_n, + .Penetration = penetration, + .LhsPt = collision_pt, + .RhsPt = collision_pt, + .LhsR = lhs_r, + .RhsR = rhs_r, + }; + col.JN = InitJacobian(col, collision_normal_n, delta, true); + col.JT = InitJacobian(col, tangent, delta, false); + col.JTb = InitJacobian(col, tangent_b, delta, false); + Memory[{lhs, rhs}].push_back(col); + list_iterator = Memory[{lhs, rhs}].end(); + list_iterator--; + } + Collision& col = *list_iterator; + col.Origin = collision_pt; + col.CollisionNormal = collision_normal_n; + col.Penetration = penetration; + col.LhsPt = collision_pt; + col.RhsPt = collision_pt; + col.LhsR = lhs_r; + col.RhsR = rhs_r; + col.Frame = frame_; } - Collision& col = *list_iterator; - col.origin = collision_pt; - col.collision_normal = collisionNormal_n; - col.penetration = penetration; - col.lhs_pt = collision_pt; - col.rhs_pt = collision_pt; - col.lhs_r = lhs_r; - col.rhs_r = rhs_r; - col.frame = _frame; } } - } - for (auto& [ids, cols] : mem) { - cols.remove_if([&](const auto& el) { return el.frame != _frame; }); - } + for (auto& [ids, cols] : Memory) { + for (S32 i = 0; i < S32(cols.size()); ++i) { + if (cols[i].Frame != frame_) { + cols.erase(cols.begin() + i); + --i; + } + } + } - for (auto& [ids, cols] : mem) { - for (auto& col : cols) { - for (int i = 0; i < 25; i++) { - Resolve(col.jN, col, delta, true, nullptr); - Resolve(col.jT, col, delta, false, &col.jN); - Resolve(col.jTb, col, delta, false, &col.jN); + for (auto& [ids, cols] : Memory) { + for (auto& col : cols) { + for (int i = 0; i < 25; i++) { + Resolve(col.JN, col, delta, true, nullptr); + Resolve(col.JT, col, delta, false, &col.JN); + Resolve(col.JTb, col, delta, false, &col.JN); + } } } - } - for (auto entity : scene->View()) { - auto& phys = entity.Get(); - auto& transform = entity.Get(); - transform.translation += phys.speed * delta; - transform.rotation += phys.rot_speed * 360.f / static_cast(2 * M_PI) * delta; - transform.rotation.x -= std::floor(transform.rotation.x / 360) * 360; - transform.rotation.y -= std::floor(transform.rotation.y / 360) * 360; - transform.rotation.z -= std::floor(transform.rotation.z / 360) * 360; + for (auto entity : scene->View()) { + auto& phys = entity.Get(); + auto& transform = entity.Get(); + transform.Translation += phys.Speed * delta; + transform.Rotation += phys.RotationSpeed * 360.f / static_cast(2 * M_PI) * delta; + transform.Rotation.x -= std::floor(transform.Rotation.x / 360) * 360; + transform.Rotation.y -= std::floor(transform.Rotation.y / 360) * 360; + transform.Rotation.z -= std::floor(transform.Rotation.z / 360) * 360; + } } + time_ += dt; + return dt; } - _time += dt; - return dt; -} -DE::Physics::Jacobian DE::Physics::Solver::InitJacobian(DE::Physics::Collision& collision, DE::Vec3 dir, float dt, bool is_normal) { - auto scene = _scene.lock(); - Jacobian j; - j.m_va = -dir; - j.m_wa = -glm::cross(collision.lhs_r, dir); - j.m_vb = dir; - j.m_wb = glm::cross(collision.rhs_r, dir); - - j.m_bias = .0f; - - auto lhs_phys = scene->GetByID(collision.src).GetComponent(); - auto rhs_phys = scene->GetByID(collision.dest).GetComponent(); - - if (is_normal) { - float beta = .5f; - float rest = 0.01f; - - Vec3 relativeVel = - -lhs_phys->speed - glm::cross(lhs_phys->rot_speed, collision.lhs_r) + rhs_phys->speed + glm::cross(rhs_phys->rot_speed, collision.rhs_r); - float closingVel = glm::dot(relativeVel, dir); - j.m_bias = -(beta / dt) * std::max(.0f, collision.penetration - 0.01f) + rest * closingVel; + Physics::Jacobian Physics::Solver::InitJacobian(Physics::Collision& collision, Vec3 dir, float dt, bool is_normal) { + auto scene = scene_.lock(); + Jacobian j; + j.VA = -dir; + j.WA = -glm::cross(collision.LhsR, dir); + j.VB = dir; + j.WB = glm::cross(collision.RhsR, dir); + + j.Bias = .0f; + + auto lhs_phys = scene->GetByID(collision.Source).GetComponent(); + auto rhs_phys = scene->GetByID(collision.Destination).GetComponent(); + + if (is_normal) { + float beta = .5f; + float rest = 0.01f; + + Vec3 relative_vel = -lhs_phys->Speed - glm::cross(lhs_phys->RotationSpeed, collision.LhsR) + rhs_phys->Speed + + glm::cross(rhs_phys->RotationSpeed, collision.RhsR); + float closing_vel = glm::dot(relative_vel, dir); + j.Bias = -(beta / dt) * std::max(.0f, collision.Penetration - 0.01f) + rest * closing_vel; + } + + float inv_mass = lhs_phys->InvertedMass + rhs_phys->InvertedMass + glm::dot(j.WA, lhs_phys->InvertedInertia * j.WA) + + glm::dot(j.WB, rhs_phys->InvertedInertia * j.WB); + j.EffectiveMass = 1.f / inv_mass; + j.TotatlLambda = 0; + return j; } + void Physics::Solver::Resolve(Physics::Jacobian& j, Physics::Collision& collision, float, bool is_normal, Physics::Jacobian* jn) { + auto scene = scene_.lock(); + + auto lhs_phys = scene->GetByID(collision.Source).GetComponent(); + auto rhs_phys = scene->GetByID(collision.Destination).GetComponent(); + + float jv = glm::dot(j.VA, lhs_phys->Speed) + glm::dot(j.WA, lhs_phys->RotationSpeed) + glm::dot(j.VB, rhs_phys->Speed) + + glm::dot(j.WB, rhs_phys->RotationSpeed); + + float lambda = j.EffectiveMass * (-(jv + j.Bias)); + + float old_total_lambda = j.TotatlLambda; + if (is_normal) { + j.TotatlLambda = std::max(.0f, j.TotatlLambda + lambda); + } else { + float friction = 0.2f; + float max_friction = friction * jn->TotatlLambda; + j.TotatlLambda = std::max(-max_friction, std::min(max_friction, j.TotatlLambda + lambda)); + } + lambda = j.TotatlLambda - old_total_lambda; - float inv_mass = - lhs_phys->inv_mass + rhs_phys->inv_mass + glm::dot(j.m_wa, lhs_phys->inv_inertia * j.m_wa) + glm::dot(j.m_wb, rhs_phys->inv_inertia * j.m_wb); - j.m_effective_mass = 1.f / inv_mass; - j.m_totalLambda = 0; - return j; -} -void DE::Physics::Solver::Resolve(DE::Physics::Jacobian& j, DE::Physics::Collision& collision, float, bool is_normal, DE::Physics::Jacobian* jn) { - auto scene = _scene.lock(); - - auto lhs_phys = scene->GetByID(collision.src).GetComponent(); - auto rhs_phys = scene->GetByID(collision.dest).GetComponent(); - - float jv = glm::dot(j.m_va, lhs_phys->speed) + glm::dot(j.m_wa, lhs_phys->rot_speed) + glm::dot(j.m_vb, rhs_phys->speed) + - glm::dot(j.m_wb, rhs_phys->rot_speed); - - float lambda = j.m_effective_mass * (-(jv + j.m_bias)); - - float oldTotalLambda = j.m_totalLambda; - if (is_normal) { - j.m_totalLambda = std::max(.0f, j.m_totalLambda + lambda); - } else { - float friction = 0.2f; - float maxFriction = friction * jn->m_totalLambda; - j.m_totalLambda = std::max(-maxFriction, std::min(maxFriction, j.m_totalLambda + lambda)); + lhs_phys->Speed += lhs_phys->InvertedMass * j.VA * lambda; + lhs_phys->RotationSpeed += lhs_phys->InvertedInertia * j.WA * lambda; + rhs_phys->Speed += rhs_phys->InvertedMass * j.VB * lambda; + rhs_phys->RotationSpeed += rhs_phys->InvertedInertia * j.WB * lambda; } - lambda = j.m_totalLambda - oldTotalLambda; - lhs_phys->speed += lhs_phys->inv_mass * j.m_va * lambda; - lhs_phys->rot_speed += lhs_phys->inv_inertia * j.m_wa * lambda; - rhs_phys->speed += rhs_phys->inv_mass * j.m_vb * lambda; - rhs_phys->rot_speed += rhs_phys->inv_inertia * j.m_wb * lambda; -} +} // namespace DummyEngine diff --git a/DummyEngine/Core/Physics/Solver.hpp b/DummyEngine/Core/Physics/Solver.hpp index 4ba2af4..b5e70f9 100644 --- a/DummyEngine/Core/Physics/Solver.hpp +++ b/DummyEngine/Core/Physics/Solver.hpp @@ -1,52 +1,57 @@ #pragma once -#include +#include "DummyEngine/Core/Physics/ConvexCollider.hpp" -#include "ConvexCollider.hpp" -#include "DummyEngine/Core/Scene/Scene.h" -#include "SceneConstants.hpp" +#include +#include -namespace DE { +namespace DummyEngine { class Scene; } -namespace DE::Physics { +namespace DummyEngine::Physics { struct Jacobian { - Vec3 m_va, m_wa, m_vb, m_wb; - float m_bias, m_effective_mass, m_totalLambda; + Vec3 VA, WA, VB, WB; + float Bias; + float EffectiveMass; + float TotatlLambda; }; struct Collision { - UUID src, dest; - Vec3 origin; - Vec3 collision_normal; - float penetration; + UUID Source, Destination; + Vec3 Origin; + Vec3 CollisionNormal; + float Penetration; - Vec3 lhs_pt, rhs_pt; - Vec3 lhs_r, rhs_r; + Vec3 LhsPt, RhsPt; + Vec3 LhsR, RhsR; - Jacobian jN, jT, jTb; - size_t frame; + Jacobian JN, JT, JTb; + size_t Frame; + }; + + struct SceneConstants { + Vec3 Gravity; }; class Solver { public: - void LoadScene(const Ref& scene); + void LoadScene(const Ref& scene); void OnUpdate(double dt); double NextInteraction(double dt); Jacobian InitJacobian(Collision& collision, Vec3 dir, float dt, bool is_normal); void Resolve(Jacobian& j, Collision& collision, float dt, bool is_normal, Jacobian* jn); - std::map, std::list> mem; + std::map, std::vector> Memory; private: - WeakRef _scene; - Ref _constants; - std::unordered_map> _colliders; - double _time = 0; - size_t _frame = 0; + WeakRef scene_; + SceneConstants constants_; + std::unordered_map> colliders_; + double time_ = 0; + size_t frame_ = 0; }; -} // namespace DE::Physics \ No newline at end of file +} // namespace DummyEngine::Physics \ No newline at end of file diff --git a/DummyEngine/Core/Physics/Utils.cpp b/DummyEngine/Core/Physics/Utils.cpp index 648f1a4..ad886a8 100644 --- a/DummyEngine/Core/Physics/Utils.cpp +++ b/DummyEngine/Core/Physics/Utils.cpp @@ -1,23 +1,23 @@ #include "Utils.hpp" -namespace DE::Physics { +namespace DummyEngine::Physics { - Plane::Plane(Vec3 normal, double_t d) : m_Normal(normal), m_D(d) {} - Plane::Plane(Vec3 normal, Vec3 pt) : m_Normal(normal), m_D(-glm::dot(normal, pt)) {} - Vec3 Plane::intersectionPoint(Vec3 p1, Vec3 p2) const { - if (glm::dot(m_Normal, p2 - p1) == 0) { + Plane::Plane(Vec3 normal, double_t d) : normal_(normal), d_(d) {} + Plane::Plane(Vec3 normal, Vec3 pt) : normal_(normal), d_(-glm::dot(normal, pt)) {} + Vec3 Plane::IntersectionPoint(Vec3 p1, Vec3 p2) const { + if (glm::dot(normal_, p2 - p1) == 0) { return (p1 + p2) / 2.f; } - return p1 + (p2 - p1) * (-distance(p1) / glm::dot(m_Normal, p2 - p1)); + return p1 + (p2 - p1) * (-Distance(p1) / glm::dot(normal_, p2 - p1)); }; - void Plane::invert() { - m_Normal = -m_Normal; + void Plane::Invert() { + normal_ = -normal_; } - Vec3 Plane::getNormal() const { - return m_Normal; + Vec3 Plane::GetNormal() const { + return normal_; } - float Plane::distance(Vec3 q) const { - return glm::dot(m_Normal, q) + m_D; + float Plane::Distance(Vec3 q) const { + return glm::dot(normal_, q) + d_; } -} // namespace DE::Physics \ No newline at end of file +} // namespace DummyEngine::Physics \ No newline at end of file diff --git a/DummyEngine/Core/Physics/Utils.hpp b/DummyEngine/Core/Physics/Utils.hpp index 6a0d1c2..cc31cb5 100644 --- a/DummyEngine/Core/Physics/Utils.hpp +++ b/DummyEngine/Core/Physics/Utils.hpp @@ -1,20 +1,22 @@ +#pragma once + #include "DummyEngine/Utils/Types/Types.h" -namespace DE::Physics { +namespace DummyEngine::Physics { class Plane { public: Plane(Vec3 normal, double_t d); Plane(Vec3 normal, Vec3 pt); - Vec3 intersectionPoint(Vec3 p1, Vec3 p2) const; - void invert(); - Vec3 getNormal() const; - float distance(Vec3 q) const; + Vec3 IntersectionPoint(Vec3 p1, Vec3 p2) const; + void Invert(); + Vec3 GetNormal() const; + float Distance(Vec3 q) const; private: - Vec3 m_Normal; - float m_D; + Vec3 normal_; + float d_; }; -} // namespace DE::Physics \ No newline at end of file +} // namespace DummyEngine::Physics \ No newline at end of file diff --git a/DummyEngine/Core/Rendering/Renderer/BufferLayout.cpp b/DummyEngine/Core/Rendering/Renderer/BufferLayout.cpp index 91639f5..82614cd 100644 --- a/DummyEngine/Core/Rendering/Renderer/BufferLayout.cpp +++ b/DummyEngine/Core/Rendering/Renderer/BufferLayout.cpp @@ -1,10 +1,12 @@ -#include "DummyEngine/Core/Rendering/Renderer/BufferLayout.h" +#include "BufferLayout.h" -namespace DE { +#include "DummyEngine/Utils/Debug/Assert.h" + +namespace DummyEngine { //*~~~BufferElement~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - BufferElement::BufferElement(BufferElementType type, bool normalized) : type(type), size(SizeOfElementType(type)), normalized(normalized) {} + BufferElement::BufferElement(BufferElementType type, bool normalized) : Type(type), Size(SizeOfElementType(type)), Normalized(normalized) {} U32 BufferElement::SizeOfElementType(BufferElementType type) { switch (type) { case BufferElementType::Float: return 4; @@ -20,7 +22,7 @@ namespace DE { } } U32 BufferElement::ComponentCount() const { - switch (type) { + switch (Type) { case BufferElementType::Float: return 1; case BufferElementType::Float2: return 2; case BufferElementType::Float3: return 3; @@ -37,31 +39,31 @@ namespace DE { //*~~~BufferLayout~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BufferLayout::BufferLayout(std::initializer_list elements, U32 divisor) : - m_Elements(elements), m_Type(BufferLayoutType::Vertex), m_Divisor(divisor) {} + elements_(elements), type_(BufferLayoutType::Vertex), divisor_(divisor) {} void BufferLayout::SetLayoutType(BufferLayoutType type) { - m_Type = type; + type_ = type; CalculateOffsetsAndStride(); } void BufferLayout::CalculateOffsetsAndStride() { - switch (m_Type) { + switch (type_) { case BufferLayoutType::Vertex: { U32 offset = 0; - for (auto& element : m_Elements) { - element.offset = offset; - offset += element.size; + for (auto& element : elements_) { + element.Offset = offset; + offset += element.Size; } - m_Stride = offset; + stride_ = offset; break; } case BufferLayoutType::Uniform: { U32 offset = 0; - for (auto& element : m_Elements) { - switch (element.type) { + for (auto& element : elements_) { + switch (element.Type) { case BufferElementType::Float: case BufferElementType::Int: { - element.offset = offset; - offset += element.size; + element.Offset = offset; + offset += element.Size; break; } case BufferElementType::Float2: @@ -69,8 +71,8 @@ namespace DE { if (offset % 8 != 0) { offset += 4; } - element.offset = offset; - offset += element.size; + element.Offset = offset; + offset += element.Size; break; } case BufferElementType::Float3: @@ -81,8 +83,8 @@ namespace DE { if (offset % 16 != 0) { offset += 16 - offset % 16; } - element.offset = offset; - offset += element.size; + element.Offset = offset; + offset += element.Size; break; } default: break; @@ -91,7 +93,7 @@ namespace DE { if (offset % 16 != 0) { offset += 16 - offset % 16; } - m_Stride = offset; + stride_ = offset; break; } default: break; @@ -99,26 +101,26 @@ namespace DE { } std::vector::iterator BufferLayout::begin() { - return m_Elements.begin(); + return elements_.begin(); } std::vector::iterator BufferLayout::end() { - return m_Elements.end(); + return elements_.end(); } std::vector::const_iterator BufferLayout::begin() const { - return m_Elements.begin(); + return elements_.begin(); } std::vector::const_iterator BufferLayout::end() const { - return m_Elements.end(); + return elements_.end(); } const BufferElement& BufferLayout::operator[](U32 index) const { - DE_ASSERT(index >= 0 && index < m_Elements.size(), "Index out of bounce {} should be between [0,{})", index, m_Elements.size()); - return m_Elements[index]; + DE_ASSERT(index >= 0 && index < elements_.size(), "Index out of bounce {} should be between [0,{})", index, elements_.size()); + return elements_[index]; } U32 BufferLayout::GetStride() const { - return m_Stride; + return stride_; } U32 BufferLayout::GetDivisor() const { - return m_Divisor; + return divisor_; } -} // namespace DE \ No newline at end of file +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Rendering/Renderer/BufferLayout.h b/DummyEngine/Core/Rendering/Renderer/BufferLayout.h index 4a803f7..d7ee0dd 100644 --- a/DummyEngine/Core/Rendering/Renderer/BufferLayout.h +++ b/DummyEngine/Core/Rendering/Renderer/BufferLayout.h @@ -1,16 +1,19 @@ #pragma once -#include "DummyEngine/Utils/Base.h" +#include "DummyEngine/Utils/Types/Types.h" + +namespace DummyEngine { -namespace DE { struct BufferElement { - BufferElementType type; - U32 size; - size_t offset; - bool normalized; + public: + BufferElementType Type; + U32 Size; + size_t Offset; + bool Normalized; + public: BufferElement() = default; - BufferElement(BufferElementType type, bool normalized = false); + BufferElement(BufferElementType type, bool normalized = false); // NOLINT U32 ComponentCount() const; @@ -24,10 +27,10 @@ namespace DE { BufferLayout() = default; BufferLayout(std::initializer_list elements, U32 divisor = 0); - std::vector::iterator begin(); - std::vector::iterator end(); - std::vector::const_iterator begin() const; - std::vector::const_iterator end() const; + std::vector::iterator begin(); // NOLINT + std::vector::iterator end(); // NOLINT + std::vector::const_iterator begin() const; // NOLINT + std::vector::const_iterator end() const; // NOLINT const BufferElement& operator[](U32 index) const; U32 GetStride() const; @@ -37,10 +40,11 @@ namespace DE { private: void CalculateOffsetsAndStride(); - std::vector m_Elements; - BufferLayoutType m_Type; - U32 m_Stride; - U32 m_Divisor; + private: + std::vector elements_; + BufferLayoutType type_; + U32 stride_; + U32 divisor_; }; -} // namespace DE \ No newline at end of file +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Rendering/Renderer/Context.cpp b/DummyEngine/Core/Rendering/Renderer/Context.cpp index 8ae39a3..5e6981d 100644 --- a/DummyEngine/Core/Rendering/Renderer/Context.cpp +++ b/DummyEngine/Core/Rendering/Renderer/Context.cpp @@ -1,13 +1,13 @@ -#include "DummyEngine/Core/Rendering/Renderer/Context.h" +#include "Context.h" #include "DummyEngine/Core/Application/Config.h" -#include "DummyEngine/Core/Rendering/Renderer/Renderer.h" #include "DummyEngine/Core/Rendering/RendererOpenGL/GLContext.h" +#include "DummyEngine/Utils/Debug/Assert.h" -namespace DE { +namespace DummyEngine { Scope Context::Create(GLFWwindow* window) { - switch (Config::GetRenderAPI()) { + switch (Config::Get().RendererAPI) { // Use config because renderer is not yet initialized case API::OpenGL: return CreateScope(window); case API::Vulkan: { DE_ASSERT(false, "Attempt to create Context on VulkanAPI which is currently unsupported."); @@ -22,4 +22,4 @@ namespace DE { } return nullptr; } -} // namespace DE \ No newline at end of file +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Rendering/Renderer/Context.h b/DummyEngine/Core/Rendering/Renderer/Context.h index cea19f3..eb6e594 100644 --- a/DummyEngine/Core/Rendering/Renderer/Context.h +++ b/DummyEngine/Core/Rendering/Renderer/Context.h @@ -1,10 +1,10 @@ #pragma once -#include "DummyEngine/Utils/Base.h" +#include "DummyEngine/Utils/Types/Types.h" struct GLFWwindow; -namespace DE { +namespace DummyEngine { class Context { public: @@ -16,4 +16,4 @@ namespace DE { static Scope Create(GLFWwindow* window); }; -} // namespace DE \ No newline at end of file +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Rendering/Renderer/CubeMap.cpp b/DummyEngine/Core/Rendering/Renderer/CubeMap.cpp index 5231a7e..9c80716 100644 --- a/DummyEngine/Core/Rendering/Renderer/CubeMap.cpp +++ b/DummyEngine/Core/Rendering/Renderer/CubeMap.cpp @@ -1,9 +1,10 @@ -#include "DummyEngine/Core/Rendering/Renderer/CubeMap.h" +#include "CubeMap.h" #include "DummyEngine/Core/Rendering/Renderer/Renderer.h" #include "DummyEngine/Core/Rendering/RendererOpenGL/GLCubeMap.h" -namespace DE { +namespace DummyEngine { + Ref CubeMap::Create(const Ref texture_data) { switch (Renderer::CurrentAPI()) { case API::OpenGL: return CreateRef(texture_data); @@ -36,4 +37,5 @@ namespace DE { } return nullptr; } -} // namespace DE \ No newline at end of file + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Rendering/Renderer/CubeMap.h b/DummyEngine/Core/Rendering/Renderer/CubeMap.h index d20e659..7c80586 100644 --- a/DummyEngine/Core/Rendering/Renderer/CubeMap.h +++ b/DummyEngine/Core/Rendering/Renderer/CubeMap.h @@ -2,9 +2,9 @@ #include "DummyEngine/Core/Rendering/Renderer/Texture.h" #include "DummyEngine/Core/ResourceManaging/RawData.h" -#include "DummyEngine/Utils/Base.h" -namespace DE { +namespace DummyEngine { + class CubeMap { public: virtual ~CubeMap() = default; @@ -14,4 +14,5 @@ namespace DE { static Ref Create(const Ref texture_data); static Ref Create(U32 size, Texture::Format format, Texture::Channels channels, bool gen_mipmap = false, bool depth_map = false); }; -} // namespace DE \ No newline at end of file + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Rendering/Renderer/FrameBuffer.cpp b/DummyEngine/Core/Rendering/Renderer/FrameBuffer.cpp index 8771f84..0dc2c68 100644 --- a/DummyEngine/Core/Rendering/Renderer/FrameBuffer.cpp +++ b/DummyEngine/Core/Rendering/Renderer/FrameBuffer.cpp @@ -1,9 +1,10 @@ -#include "DummyEngine/Core/Rendering/Renderer/FrameBuffer.h" +#include "FrameBuffer.h" #include "DummyEngine/Core/Rendering/Renderer/Renderer.h" #include "DummyEngine/Core/Rendering/RendererOpenGL/GLFrameBuffer.h" -namespace DE { +namespace DummyEngine { + Ref FrameBuffer::Create(const FrameBufferProperties& properties) { switch (Renderer::CurrentAPI()) { case API::OpenGL: return CreateRef(properties); @@ -20,4 +21,5 @@ namespace DE { } return nullptr; } -} // namespace DE \ No newline at end of file + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Rendering/Renderer/FrameBuffer.h b/DummyEngine/Core/Rendering/Renderer/FrameBuffer.h index 114c4eb..54b4450 100644 --- a/DummyEngine/Core/Rendering/Renderer/FrameBuffer.h +++ b/DummyEngine/Core/Rendering/Renderer/FrameBuffer.h @@ -2,16 +2,16 @@ #include "DummyEngine/Core/Rendering/Renderer/CubeMap.h" #include "DummyEngine/Core/Rendering/Renderer/Texture.h" -#include "DummyEngine/Utils/Base.h" -namespace DE { +namespace DummyEngine { + struct FrameBufferProperties { - U32 width = 0; - U32 height = 0; + U32 Width = 0; + U32 Height = 0; }; struct FrameBufferAttchment { - Ref m_Texture; + Ref Texture; }; class FrameBuffer { @@ -37,4 +37,5 @@ namespace DE { virtual const FrameBufferProperties& GetProperties() const = 0; static Ref Create(const FrameBufferProperties& properties); }; -} // namespace DE \ No newline at end of file + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Rendering/Renderer/LocalBuffer.cpp b/DummyEngine/Core/Rendering/Renderer/LocalBuffer.cpp index 733bf6a..07fee3a 100644 --- a/DummyEngine/Core/Rendering/Renderer/LocalBuffer.cpp +++ b/DummyEngine/Core/Rendering/Renderer/LocalBuffer.cpp @@ -1,40 +1,43 @@ -#include "DummyEngine/Core/Rendering/Renderer/LocalBuffer.h" +#include "LocalBuffer.h" + +#include "DummyEngine/Utils/Debug/Assert.h" + +namespace DummyEngine { -namespace DE { //*~~~LocalBufferNode~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - LocalBufferNode::LocalBufferNode(LocalBuffer* buffer, U8* pointer) : m_Buffer(buffer), m_Pointer(pointer) {} + LocalBufferNode::LocalBufferNode(LocalBuffer* buffer, U8* pointer) : buffer_(buffer), pointer_(pointer) {} LocalBufferNode& LocalBufferNode::operator=(const LocalBufferNode& other) { - DE_ASSERT(m_Buffer == other.m_Buffer, "Trying to assign LocalBufferNodes from diffrent LocalBuffers"); - std::memcpy(m_Pointer, other.m_Pointer, m_Buffer->m_Layout.GetStride()); + DE_ASSERT(buffer_ == other.buffer_, "Trying to assign LocalBufferNodes from diffrent LocalBuffers"); + std::memcpy(pointer_, other.pointer_, buffer_->layout_.GetStride()); return *this; } //*~~~LocalBuffer~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - LocalBuffer::LocalBuffer() : m_Data(nullptr), m_Size(0) {} + LocalBuffer::LocalBuffer() : data_(nullptr), size_(0) {} LocalBuffer::~LocalBuffer() { - if (m_Data) { - delete[] m_Data; + if (data_ != nullptr) { + delete[] data_; } } - LocalBufferNode LocalBuffer::at(U32 index) { - return LocalBufferNode(this, m_Data + index * m_Layout.GetStride()); + LocalBufferNode LocalBuffer::At(U32 index) { + return LocalBufferNode(this, data_ + index * layout_.GetStride()); } void LocalBuffer::SetData(const void* data, U32 size) { - DE_ASSERT(m_Size == size, "Wrong data size {} expected {}", size, m_Size); - memcpy(m_Data, data, m_Size); + DE_ASSERT(size_ == size, "Wrong data size {} expected {}", size, size_); + memcpy(data_, data, size_); } void LocalBuffer::Allocate(const BufferLayout& layout, U32 size) { - m_Layout = layout; - Allocate(size * m_Layout.GetStride()); + layout_ = layout; + Allocate(size * layout_.GetStride()); } void LocalBuffer::Allocate(U32 size) { - if (m_Data) { - delete[] m_Data; + if (data_ != nullptr) { + delete[] data_; } - m_Data = (U8*)malloc(size); - m_Size = size; + data_ = (U8*)malloc(size); + size_ = size; } -} // namespace DE \ No newline at end of file +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Rendering/Renderer/LocalBuffer.h b/DummyEngine/Core/Rendering/Renderer/LocalBuffer.h index dc44aaa..189dc6c 100644 --- a/DummyEngine/Core/Rendering/Renderer/LocalBuffer.h +++ b/DummyEngine/Core/Rendering/Renderer/LocalBuffer.h @@ -1,9 +1,8 @@ #pragma once #include "DummyEngine/Core/Rendering/Renderer/BufferLayout.h" -#include "DummyEngine/Utils/Base.h" -namespace DE { +namespace DummyEngine { // TODO: Weak ptr stuff class LocalBufferNode; class LocalBuffer { @@ -14,7 +13,7 @@ namespace DE { void SetData(const void* data, U32 size); void Allocate(const BufferLayout& layout, U32 size); - LocalBufferNode at(U32 index); + LocalBufferNode At(U32 index); private: void Allocate(U32 size); @@ -23,13 +22,13 @@ namespace DE { friend class GLUniformBuffer; friend class LocalBufferNode; - BufferLayout m_Layout; - U8* m_Data; - U32 m_Size; + BufferLayout layout_; + U8* data_; + U32 size_; }; class LocalBufferNode { public: - template T& Get(U32 index) { return *(T*)(m_Pointer + m_Buffer->m_Layout[index].offset); } + template T& Get(U32 index) { return *(T*)(pointer_ + buffer_->layout_[index].Offset); } LocalBufferNode& operator=(const LocalBufferNode& other); private: @@ -37,7 +36,7 @@ namespace DE { friend class LocalBuffer; - LocalBuffer* m_Buffer; - U8* m_Pointer; + LocalBuffer* buffer_; + U8* pointer_; }; -} // namespace DE \ No newline at end of file +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Rendering/Renderer/RenderAPI.h b/DummyEngine/Core/Rendering/Renderer/RenderAPI.h index aab6f43..af86784 100644 --- a/DummyEngine/Core/Rendering/Renderer/RenderAPI.h +++ b/DummyEngine/Core/Rendering/Renderer/RenderAPI.h @@ -1,9 +1,8 @@ #pragma once #include "DummyEngine/Core/Rendering/Renderer/VertexArray.h" -#include "DummyEngine/Utils/Base.h" -namespace DE { +namespace DummyEngine { enum class RenderSetting { None = 0, DepthTest, MultiSampling, FaceCulling, DepthMask }; enum class RenderPrimitive { None = 0, Triangle, Line, Point }; class RenderAPI { @@ -29,4 +28,4 @@ namespace DE { virtual API GetAPI() = 0; }; -} // namespace DE \ No newline at end of file +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Rendering/Renderer/RenderStructs.cpp b/DummyEngine/Core/Rendering/Renderer/RenderStructs.cpp index 0f97a1d..0aee918 100644 --- a/DummyEngine/Core/Rendering/Renderer/RenderStructs.cpp +++ b/DummyEngine/Core/Rendering/Renderer/RenderStructs.cpp @@ -1,37 +1,39 @@ -#include "DummyEngine/Core/Rendering/Renderer/RenderStructs.h" +#include "RenderStructs.h" +#include "DummyEngine/Core/Animations/Animator.h" #include "DummyEngine/Core/Rendering/Renderer/Renderer.h" +#include "DummyEngine/Utils/Types/Types.h" -namespace DE { +namespace DummyEngine { void Material::Apply(Ref shader, const std::string& uniform_name) const { - if (diffuse_map) { - diffuse_map->Bind(1); + if (DiffuseMap) { + DiffuseMap->Bind(1); } else { Renderer::GetTexture(Renderer::Textures::White)->Bind(1); } - if (normal_map) { - normal_map->Bind(2); + if (NormalMap) { + NormalMap->Bind(2); } else { Renderer::GetTexture(Renderer::Textures::Normal)->Bind(2); } - if (specular_map) { - specular_map->Bind(3); + if (SpecularMap) { + SpecularMap->Bind(3); } else { Renderer::GetTexture(Renderer::Textures::White)->Bind(3); } - if (albedo_map) { - albedo_map->Bind(4); + if (AlbedoMap) { + AlbedoMap->Bind(4); } else { Renderer::GetTexture(Renderer::Textures::White)->Bind(4); } - if (orm_map) { - orm_map->Bind(5); + if (ORMMap) { + ORMMap->Bind(5); } else { Renderer::GetTexture(Renderer::Textures::White)->Bind(5); } - if (emission_map) { - emission_map->Bind(6); + if (EmissionMap) { + EmissionMap->Bind(6); } else { Renderer::GetTexture(Renderer::Textures::White)->Bind(6); } @@ -41,14 +43,14 @@ namespace DE { shader->SetInt(uniform_name + ".m_AlbedoMap", 4); shader->SetInt(uniform_name + ".m_ORMMap", 5); shader->SetInt(uniform_name + ".m_EmissionMap", 6); - shader->SetFloat3(uniform_name + ".m_Albedo", albedo); - shader->SetFloat3(uniform_name + ".m_ORM", orm); - shader->SetFloat3(uniform_name + ".m_Ambient", ambient); - shader->SetFloat3(uniform_name + ".m_Diffuse", diffuse); - shader->SetFloat3(uniform_name + ".m_Specular", specular); - shader->SetFloat3(uniform_name + ".m_Emission", emission); - shader->SetFloat(uniform_name + ".m_Shininess", shininess); - shader->SetFloat(uniform_name + ".m_EmissionStrength", emission_strength); + shader->SetFloat3(uniform_name + ".m_Albedo", Albedo); + shader->SetFloat3(uniform_name + ".m_ORM", ORM); + shader->SetFloat3(uniform_name + ".m_Ambient", Ambient); + shader->SetFloat3(uniform_name + ".m_Diffuse", Diffuse); + shader->SetFloat3(uniform_name + ".m_Specular", Specular); + shader->SetFloat3(uniform_name + ".m_Emission", Emission); + shader->SetFloat(uniform_name + ".m_Shininess", Shininess); + shader->SetFloat(uniform_name + ".m_EmissionStrength", EmissionStrength); } Ref SetupTexture(Ref texture_data) { if (texture_data) { @@ -57,22 +59,22 @@ namespace DE { return nullptr; } void Material::FillData(const MaterialData& material) { - type = material.type; - shininess = material.shininess; + Type = material.Type; + Shininess = material.Shininess; - emission = material.emission; - ambient = material.ambient; - albedo = material.albedo; - diffuse = material.diffuse; - specular = material.specular; - orm = material.orm; + Emission = material.Emission; + Ambient = material.Ambient; + Albedo = material.Albedo; + Diffuse = material.Diffuse; + Specular = material.Specular; + ORM = material.ORM; - albedo_map = SetupTexture(material.albedo_map); - normal_map = SetupTexture(material.normal_map); - orm_map = SetupTexture(material.orm_map); - diffuse_map = SetupTexture(material.diffuse_map); - specular_map = SetupTexture(material.specular_map); - emission_map = SetupTexture(material.emission_map); + AlbedoMap = SetupTexture(material.AlbedoMap); + NormalMap = SetupTexture(material.NormalMap); + ORMMap = SetupTexture(material.ORMMap); + DiffuseMap = SetupTexture(material.DiffuseMap); + SpecularMap = SetupTexture(material.SpecularMap); + EmissionMap = SetupTexture(material.EmissionMap); } void RenderSubMesh::FillData(const RenderSubMeshData& data) { @@ -85,19 +87,19 @@ namespace DE { BufferElementType::Float4, BufferElementType::Float4}); - vertex_array = VertexArray::Create(); + VertexArray = VertexArray::Create(); - Ref vertex_buffer = VertexBuffer::Create(layout, data.vertices.size(), &data.vertices[0]); - Ref index_buffer = IndexBuffer::Create(&data.indices[0], data.indices.size()); - material.FillData(data.material); + Ref vertex_buffer = VertexBuffer::Create(layout, data.Vertices.size(), &data.Vertices[0]); + Ref index_buffer = IndexBuffer::Create(&data.Indices[0], data.Indices.size()); + Material.FillData(data.Material); - vertex_array->AddVertexBuffer(vertex_buffer); - vertex_array->SetIndexBuffer(index_buffer); + VertexArray->AddVertexBuffer(vertex_buffer); + VertexArray->SetIndexBuffer(index_buffer); } RenderSubMesh RenderSubMesh::Copy() const { RenderSubMesh res; - res.material = material; - res.vertex_array = vertex_array->Copy(); + res.Material = Material; + res.VertexArray = VertexArray->Copy(); return res; } RenderMesh::RenderMesh(Ref data) { @@ -105,23 +107,23 @@ namespace DE { } Ref RenderMesh::Copy() const { Ref res = CreateRef(); - res->m_SubMeshes.resize(m_SubMeshes.size()); - res->p_Animator = p_Animator; - for (size_t i = 0; i < m_SubMeshes.size(); ++i) { - res->m_SubMeshes[i] = m_SubMeshes[i].Copy(); + res->sub_meshes_.resize(sub_meshes_.size()); + res->Animator = Animator; + for (size_t i = 0; i < sub_meshes_.size(); ++i) { + res->sub_meshes_[i] = sub_meshes_[i].Copy(); } return res; } std::vector& RenderMesh::GetSubMeshes() { - return m_SubMeshes; + return sub_meshes_; } void RenderMesh::FillData(Ref data) { - m_SubMeshes.resize(data->meshes.size()); - if (data->animation) { - p_Animator = CreateRef(data->animation); + sub_meshes_.resize(data->Meshes.size()); + if (data->Animation) { + Animator = CreateRef(data->Animation); } - for (size_t i = 0; i < data->meshes.size(); ++i) { - m_SubMeshes[i].FillData(data->meshes[i]); + for (size_t i = 0; i < data->Meshes.size(); ++i) { + sub_meshes_[i].FillData(data->Meshes[i]); } } -} // namespace DE \ No newline at end of file +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Rendering/Renderer/RenderStructs.h b/DummyEngine/Core/Rendering/Renderer/RenderStructs.h index d77a942..bae103b 100644 --- a/DummyEngine/Core/Rendering/Renderer/RenderStructs.h +++ b/DummyEngine/Core/Rendering/Renderer/RenderStructs.h @@ -4,36 +4,35 @@ #include "DummyEngine/Core/Rendering/Renderer/Shader.h" #include "DummyEngine/Core/Rendering/Renderer/Texture.h" #include "DummyEngine/Core/Rendering/Renderer/VertexArray.h" -#include "DummyEngine/Utils/Base.h" -namespace DE { +namespace DummyEngine { struct Material { - MaterialType type = MaterialType::None; - float shininess = 64; - float emission_strength = 0; - - Vec3 albedo = Vec3(1.0f); - Vec3 orm = Vec3(1.0f); - Vec3 diffuse = Vec3(1.0f); - Vec3 specular = Vec3(1.0f); - Vec3 ambient = Vec3(1.0f); - Vec3 emission = Vec3(0.0f); - - Ref albedo_map; - Ref normal_map; - Ref orm_map; - Ref diffuse_map; - Ref specular_map; - Ref emission_map; + MaterialType Type = MaterialType::None; + float Shininess = 64; + float EmissionStrength = 0; + + Vec3 Albedo = Vec3(1.0f); + Vec3 ORM = Vec3(1.0f); + Vec3 Diffuse = Vec3(1.0f); + Vec3 Specular = Vec3(1.0f); + Vec3 Ambient = Vec3(1.0f); + Vec3 Emission = Vec3(0.0f); + + Ref AlbedoMap; + Ref NormalMap; + Ref ORMMap; + Ref DiffuseMap; + Ref SpecularMap; + Ref EmissionMap; void Apply(Ref shader, const std::string& uniform_name = "u_Material") const; void FillData(const MaterialData& material); }; struct RenderSubMesh { - Material material; - Ref vertex_array; + Material Material; + Ref VertexArray; RenderSubMesh Copy() const; void FillData(const RenderSubMeshData& data); @@ -42,17 +41,19 @@ namespace DE { class RenderMesh { public: RenderMesh() {} - RenderMesh(Ref data); + explicit RenderMesh(Ref data); + Ref Copy() const; std::vector& GetSubMeshes(); + void FillData(Ref data); - void FillData(Ref data); - Ref p_Animator; + Ref Animator; private: friend class Renderer; friend class RenderMeshInstance; - std::vector m_SubMeshes; + std::vector sub_meshes_; }; -} // namespace DE \ No newline at end of file + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Rendering/Renderer/Renderer.cpp b/DummyEngine/Core/Rendering/Renderer/Renderer.cpp index 510ecd2..e427e3d 100644 --- a/DummyEngine/Core/Rendering/Renderer/Renderer.cpp +++ b/DummyEngine/Core/Rendering/Renderer/Renderer.cpp @@ -1,34 +1,35 @@ -#include "DummyEngine/Core/Rendering/Renderer/Renderer.h" +#include "Renderer.h" // TODO: Remove glad #include #include "DummyEngine/Core/Application/Config.h" +#include "DummyEngine/Core/Objects/Cameras/FPSCamera.h" +#include "DummyEngine/Core/Rendering/Renderer/BufferLayout.h" #include "DummyEngine/Core/Rendering/Renderer/FrameBuffer.h" -#include "DummyEngine/Core/Rendering/RendererOpenGL/GLDebug.h" +#include "DummyEngine/Core/Rendering/Renderer/RenderStructs.h" +#include "DummyEngine/Core/Rendering/Renderer/Shader.h" #include "DummyEngine/Core/Rendering/RendererOpenGL/GLRenderAPI.h" -#include "DummyEngine/Core/ResourceManaging/ResourceManager.h" -#include "DummyEngine/ToolBox/Loaders/TextureLoader.h" -namespace DE { +namespace DummyEngine { SINGLETON_BASE(Renderer); S_INITIALIZE() { - switch (Config::GetRenderAPI()) { - case API::OpenGL: m_RenderAPI = CreateScope(); break; + switch (Config::Get().RendererAPI) { + case API::OpenGL: render_api_ = CreateScope(); break; case API::Vulkan: { DE_ASSERT(false, "Attempt to init Renderer with VulkanAPI which is currently unsupported"); - m_RenderAPI = nullptr; + render_api_ = nullptr; break; } case API::None: { DE_ASSERT(false, "Attempt to init Renderer without RenderingAPI"); - m_RenderAPI = nullptr; + render_api_ = nullptr; break; } } - m_RenderAPI->SetDefaultState(); + render_api_->SetDefaultState(); GenResources(); LOG_INFO("Renderer initialized"); return Unit(); @@ -38,28 +39,28 @@ namespace DE { } S_METHOD_IMPL(Unit, SetViewport, (U32 width, U32 height), (width, height)) { - m_RenderAPI->SetViewport(0, 0, width, height); + render_api_->SetViewport(0, 0, width, height); return Unit(); } S_METHOD_IMPL(Unit, BeginFrame, (), ()) { - m_FrameStatistics.Reset(); + frame_statistics_.Reset(); return Unit(); } S_METHOD_IMPL(Unit, EndFrame, (), ()) { return Unit(); } S_METHOD_IMPL(Unit, Clear, (), ()) { - m_RenderAPI->Clear(); + render_api_->Clear(); return Unit(); } S_METHOD_IMPL(Unit, Submit, (Ref vertex_array, Ref shader, const Mat4& transform), (vertex_array, shader, transform)) { shader->Bind(); shader->SetMat4("u_Transform", transform); - m_RenderAPI->DrawIndexed(vertex_array); + render_api_->DrawIndexed(vertex_array); - ++m_FrameStatistics.m_DrawCallsAmount; - ++m_FrameStatistics.m_DrawnInstances; + ++frame_statistics_.DrawCallsAmount; + ++frame_statistics_.DrawnInstances; return Unit(); } S_METHOD_IMPL(Unit, @@ -68,34 +69,34 @@ namespace DE { (mesh, shader, transform, is_depthmap)) { shader->Bind(); shader->SetMat4("u_Transform", transform); - for (const auto& sub_mesh : mesh->m_SubMeshes) { + for (const auto& sub_mesh : mesh->sub_meshes_) { if (!is_depthmap) { - sub_mesh.material.Apply(shader); + sub_mesh.Material.Apply(shader); } - sub_mesh.vertex_array->Bind(); - m_RenderAPI->DrawIndexed(sub_mesh.vertex_array); + sub_mesh.VertexArray->Bind(); + render_api_->DrawIndexed(sub_mesh.VertexArray); - ++m_FrameStatistics.m_DrawCallsAmount; - ++m_FrameStatistics.m_DrawnInstances; + ++frame_statistics_.DrawCallsAmount; + ++frame_statistics_.DrawnInstances; } return Unit(); } S_METHOD_IMPL(Unit, Submit, (Ref cube_map, const FPSCamera& camera, const Mat4& transform), (cube_map, camera, transform)) { cube_map->Bind(11); - auto shader = m_Resources.skybox; + auto shader = resources_.Skybox; shader->Bind(); shader->SetInt("u_SkyBox", 11); shader->SetMat4("u_Transform", transform); shader->SetMat4("u_Projection", camera.GetProjectionMatrix()); shader->SetMat4("u_View", camera.GetViewMatrix()); shader->SetFloat("u_SkyBoxLOD", cube_map->GetLOD()); - m_RenderAPI->Disable(RenderSetting::DepthMask); - m_RenderAPI->DrawIndexed(m_Resources.cube); - m_RenderAPI->Enable(RenderSetting::DepthMask); + render_api_->Disable(RenderSetting::DepthMask); + render_api_->DrawIndexed(resources_.Cube); + render_api_->Enable(RenderSetting::DepthMask); - ++m_FrameStatistics.m_DrawCallsAmount; - ++m_FrameStatistics.m_DrawnInstances; + ++frame_statistics_.DrawCallsAmount; + ++frame_statistics_.DrawnInstances; return Unit(); } @@ -105,16 +106,16 @@ namespace DE { (texture, threshold, soft_threshold, radius, depth, strength)) { Ref result = FrameBuffer::Create({texture->GetWidth(), texture->GetHeight()}); - m_Resources.brightness_filter->Bind(); - m_Resources.brightness_filter->SetInt("u_Texture", 1); - m_Resources.brightness_filter->SetFloat("u_Treshold", threshold); - m_Resources.brightness_filter->SetFloat("u_SoftTreshold", soft_threshold); + resources_.BrightnessFilter->Bind(); + resources_.BrightnessFilter->SetInt("u_Texture", 1); + resources_.BrightnessFilter->SetFloat("u_Treshold", threshold); + resources_.BrightnessFilter->SetFloat("u_SoftTreshold", soft_threshold); texture->Bind(1); result->AddColorAttachment(texture->GetFormat(), texture->GetChannels()); result->Bind(); SetViewport(texture->GetWidth(), texture->GetHeight()); Clear(); - Submit(m_Resources.screen_quad, m_Resources.brightness_filter); + Submit(resources_.ScreenQuad, resources_.BrightnessFilter); Ref bright_pixels = result->GetColorAttachment(0); Ref down_up_samepled = BloomDownAndUpSample(bright_pixels, radius, depth); @@ -124,14 +125,14 @@ namespace DE { source->Bind(1); down_up_samepled->Bind(2); - m_Resources.bloom->Bind(); - m_Resources.bloom->SetInt("u_Texture", 1); - m_Resources.bloom->SetInt("u_BrighnessTexture", 2); - m_Resources.bloom->SetFloat("u_Strength", strength); + resources_.Bloom->Bind(); + resources_.Bloom->SetInt("u_Texture", 1); + resources_.Bloom->SetInt("u_BrighnessTexture", 2); + resources_.Bloom->SetFloat("u_Strength", strength); result->Bind(); Renderer::SetViewport(texture->GetWidth(), texture->GetHeight()); Renderer::Clear(); - Renderer::Submit(m_Resources.screen_quad, m_Resources.bloom); + Renderer::Submit(resources_.ScreenQuad, resources_.Bloom); return Unit(); } S_METHOD_IMPL(Ref, BloomDownAndUpSample, (Ref texture, float radius, U32 depth), (texture, radius, depth)) { @@ -146,21 +147,21 @@ namespace DE { width /= level_divisor; } if (layers.empty()) { - LOG_WARNING("Failed to gen layers for bloom because depth < 1 or texture is smaller then 2x2"); + LOG_WARNING("Failed to gen layers for Bloom because depth < 1 or texture is smaller then 2x2"); return texture; } Ref current = texture; height = texture->GetHeight(); width = texture->GetWidth(); for (U32 i = 0; i < layers.size(); ++i) { - m_Resources.bloom_downsample->Bind(); - m_Resources.bloom_downsample->SetInt("u_Texture", 1); + resources_.BloomDownsample->Bind(); + resources_.BloomDownsample->SetInt("u_Texture", 1); current->Bind(1); buffer->SetColorAttachment(layers[i], 0); buffer->Bind(); Renderer::SetViewport(width / level_divisor, height / level_divisor); Renderer::Clear(); - Renderer::Submit(m_Resources.screen_quad, m_Resources.bloom_downsample); + Renderer::Submit(resources_.ScreenQuad, resources_.BloomDownsample); current = layers[i]; height /= level_divisor; @@ -172,25 +173,25 @@ namespace DE { for (S32 i = layers.size() - 1; i > 0; --i) { Ref small = layers[i]; Ref big = layers[i - 1]; - m_Resources.bloom_upsample->Bind(); - m_Resources.bloom_upsample->SetInt("u_Texture", 1); - m_Resources.bloom_upsample->SetFloat("u_Radius", radius); + resources_.BloomUpsample->Bind(); + resources_.BloomUpsample->SetInt("u_Texture", 1); + resources_.BloomUpsample->SetFloat("u_Radius", radius); buffer->SetColorAttachment(big, 0); buffer->Bind(); Renderer::SetViewport(big->GetWidth(), big->GetHeight()); - Renderer::Submit(m_Resources.screen_quad, m_Resources.bloom_upsample); + Renderer::Submit(resources_.ScreenQuad, resources_.BloomUpsample); } glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // Ref result = Texture::Create(texture->GetWidth(), texture->GetHeight(), texture->GetChannels(), texture->GetFormat()); // buffer->SetColorAttachment(result, 0); // buffer->Bind(); - // m_Resources.textured_quad->Bind(); - // m_Resources.textured_quad->SetInt("u_Texture", 1); + // resources_.textured_quad->Bind(); + // resources_.textured_quad->SetInt("u_Texture", 1); // layers.front()->Bind(1); // Renderer::SetViewport(texture->GetWidth(), texture->GetHeight()); // Renderer::Clear(); - // Renderer::Submit(m_Resources.screen_quad, m_Resources.textured_quad); + // Renderer::Submit(resources_.ScreenQuad, resources_.textured_quad); return layers.front(); } @@ -199,14 +200,14 @@ namespace DE { result->AddColorAttachment(texture->GetFormat(), texture->GetChannels()); result->Bind(); - m_Resources.gamma_hdr->Bind(); - m_Resources.gamma_hdr->SetInt("u_Texture", 1); - m_Resources.gamma_hdr->SetFloat("u_Exposure", exposure); - m_Resources.gamma_hdr->SetFloat("u_Gamma", gamma); + resources_.GammaHDR->Bind(); + resources_.GammaHDR->SetInt("u_Texture", 1); + resources_.GammaHDR->SetFloat("u_Exposure", exposure); + resources_.GammaHDR->SetFloat("u_Gamma", gamma); texture->Bind(1); SetViewport(texture->GetWidth(), texture->GetHeight()); Clear(); - Submit(m_Resources.screen_quad, m_Resources.gamma_hdr); + Submit(resources_.ScreenQuad, resources_.GammaHDR); texture->Copy(result, 0); @@ -218,64 +219,64 @@ namespace DE { result->Bind(); texture->Bind(1); - m_Resources.gaussian_blur->Bind(); - m_Resources.gaussian_blur->SetInt("u_Texture", 1); - m_Resources.gaussian_blur->SetInt("u_Horizontal", 1); + resources_.GaussianBlur->Bind(); + resources_.GaussianBlur->SetInt("u_Texture", 1); + resources_.GaussianBlur->SetInt("u_Horizontal", 1); SetViewport(texture->GetWidth(), texture->GetHeight()); Clear(); - Submit(m_Resources.screen_quad, m_Resources.gaussian_blur); + Submit(resources_.ScreenQuad, resources_.GaussianBlur); Ref horizontal = result->GetColorAttachment(0); result->SetColorAttachment(texture, 0); - m_Resources.gaussian_blur->Bind(); - m_Resources.gaussian_blur->SetInt("u_Texture", 1); - m_Resources.gaussian_blur->SetInt("u_Horizontal", 0); + resources_.GaussianBlur->Bind(); + resources_.GaussianBlur->SetInt("u_Texture", 1); + resources_.GaussianBlur->SetInt("u_Horizontal", 0); horizontal->Bind(1); result->Bind(); SetViewport(texture->GetWidth(), texture->GetHeight()); Clear(); - Submit(m_Resources.screen_quad, m_Resources.gaussian_blur); + Submit(resources_.ScreenQuad, resources_.GaussianBlur); return Unit(); } S_METHOD_IMPL(Unit, Enable, (RenderSetting setting), (setting)) { - m_RenderAPI->Enable(setting); + render_api_->Enable(setting); return Unit(); } S_METHOD_IMPL(Unit, Disable, (RenderSetting setting), (setting)) { - m_RenderAPI->Disable(setting); + render_api_->Disable(setting); return Unit(); } S_METHOD_IMPL(Unit, SetClearColor, (Vec4 color), (color)) { - m_RenderAPI->SetClearColor(color); + render_api_->SetClearColor(color); return Unit(); } S_METHOD_IMPL(Unit, SetClearColor, (float r, float g, float b, float a), (r, g, b, a)) { - m_RenderAPI->SetClearColor(Vec4(r, g, b, a)); + render_api_->SetClearColor(Vec4(r, g, b, a)); return Unit(); } S_METHOD_IMPL(Unit, SetDefaultFrameBuffer, (), ()) { - m_RenderAPI->SetDefaultFrameBuffer(); + render_api_->SetDefaultFrameBuffer(); return Unit(); } S_METHOD_IMPL(Ref, GetShader, (Shaders shader), (shader)) { switch (shader) { - case Shaders::EquirectangularToCubeMap: return m_Resources.equirectangular_to_cubemap; - case Shaders::Skybox: return m_Resources.skybox; - case Shaders::Convolution: return m_Resources.convolution; - case Shaders::PreFileterConvolution: return m_Resources.pre_filter_convolution; - case Shaders::BRDFConvolution: return m_Resources.brdf_convolution; - case Shaders::BrightnessFilter: return m_Resources.brightness_filter; - case Shaders::TexturedQuad: return m_Resources.textured_quad; - case Shaders::GaussianBlur: return m_Resources.gaussian_blur; - case Shaders::Bloom: return m_Resources.bloom; - case Shaders::GammaHDR: return m_Resources.gamma_hdr; - case Shaders::BloomUpsample: return m_Resources.bloom_upsample; - case Shaders::BloomDownsample: return m_Resources.bloom_downsample; - case Shaders::DirectionalShadowMap: return m_Resources.directional_shadow_map; - case Shaders::OmnidirectionalShadowMap: return m_Resources.omnidirectional_shadow_map; + case Shaders::EquirectangularToCubeMap: return resources_.EquirectangularToCubemap; + case Shaders::Skybox: return resources_.Skybox; + case Shaders::Convolution: return resources_.Convolution; + case Shaders::PreFileterConvolution: return resources_.PreFilterConvolution; + case Shaders::BRDFConvolution: return resources_.BRDFConvolution; + case Shaders::BrightnessFilter: return resources_.BrightnessFilter; + case Shaders::TexturedQuad: return resources_.TexturedQuad; + case Shaders::GaussianBlur: return resources_.GaussianBlur; + case Shaders::Bloom: return resources_.Bloom; + case Shaders::GammaHDR: return resources_.GammaHDR; + case Shaders::BloomUpsample: return resources_.BloomUpsample; + case Shaders::BloomDownsample: return resources_.BloomDownsample; + case Shaders::DirectionalShadowMap: return resources_.DirectionalShadowMap; + case Shaders::OmnidirectionalShadowMap: return resources_.OmnidirectionalShadowMap; case Shaders::Last: case Shaders::None: return nullptr; default: DE_ASSERT(false, "Wrong Renderer shader requested"); break; @@ -284,9 +285,9 @@ namespace DE { } S_METHOD_IMPL(Ref, GetTexture, (Textures texture), (texture)) { switch (texture) { - case Textures::White: return m_Resources.white; - case Textures::Normal: return m_Resources.normal; - case Textures::BRDF: return m_Resources.brdf; + case Textures::White: return resources_.White; + case Textures::Normal: return resources_.Normal; + case Textures::BRDF: return resources_.BRDF; case Textures::Last: case Textures::None: return nullptr; default: DE_ASSERT(false, "Wrong Renderer texture requested"); break; @@ -295,8 +296,8 @@ namespace DE { } S_METHOD_IMPL(Ref, GetVertexArray, (VertexArrays vao), (vao)) { switch (vao) { - case VertexArrays::Cube: return m_Resources.cube; - case VertexArrays::ScreenQuad: return m_Resources.screen_quad; + case VertexArrays::Cube: return resources_.Cube; + case VertexArrays::ScreenQuad: return resources_.ScreenQuad; case VertexArrays::Last: case VertexArrays::None: return nullptr; default: DE_ASSERT(false, "Wrong Renderer vertex array requested"); break; @@ -305,13 +306,13 @@ namespace DE { } S_METHOD_IMPL(API, CurrentAPI, (), ()) { - return m_RenderAPI->GetAPI(); + return render_api_->GetAPI(); } S_METHOD_IMPL(Renderer::Statistics, GetStatistics, (), ()) { - return m_FrameStatistics; + return frame_statistics_; } S_METHOD_IMPL(RenderAPI&, GetRenderAPI, (), ()) { - return *m_RenderAPI; + return *render_api_; } void Renderer::GenResources() { @@ -324,7 +325,7 @@ namespace DE { std::vector data(4, 255); TextureData tex_data(&data[0], width, height, format); - m_Resources.white = Texture::Create(tex_data); + resources_.White = Texture::Create(tex_data); } //*Normal { @@ -334,7 +335,7 @@ namespace DE { std::vector data = {128, 128, 255, 255}; TextureData tex_data(&data[0], width, height, format); - m_Resources.normal = Texture::Create(tex_data); + resources_.Normal = Texture::Create(tex_data); } //*___VertexArrays_____________________________________________________________________________________________________________________________________________________________________________ @@ -375,9 +376,9 @@ namespace DE { auto ib = IndexBuffer::Create(indices, 36); auto vb = VertexBuffer::Create({{BufferElementType::Float3}, 0}, 8, vertices); - m_Resources.cube = VertexArray::Create(); - m_Resources.cube->SetIndexBuffer(ib); - m_Resources.cube->AddVertexBuffer(vb); + resources_.Cube = VertexArray::Create(); + resources_.Cube->SetIndexBuffer(ib); + resources_.Cube->AddVertexBuffer(vb); } //*ScreenQuad { @@ -414,13 +415,13 @@ namespace DE { auto vb = VertexBuffer::Create({BufferElementType::Float2, BufferElementType::Float2}, 4, vertices); auto ib = IndexBuffer::Create(indices, 6); - m_Resources.screen_quad = VertexArray::Create(); - m_Resources.screen_quad->SetIndexBuffer(ib); - m_Resources.screen_quad->AddVertexBuffer(vb); + resources_.ScreenQuad = VertexArray::Create(); + resources_.ScreenQuad->SetIndexBuffer(ib); + resources_.ScreenQuad->AddVertexBuffer(vb); } //*___Shaders_____________________________________________________________________________________________________________________________________________________________________________ - Path shaders = Config::GetPath(DE_CFG_EXECUTABLE_PATH) / "../DummyEngine/Core/Rendering/Shaders"; + Path shaders = Config::Get().ExecutablePath / "../DummyEngine/Core/Rendering/Shaders"; //*EquirectangularToCubeMap { std::vector parts = { @@ -428,7 +429,7 @@ namespace DE { {ShaderPartType::Fragment, shaders / "Fragment/EquirectangularToCubeMap.fs"}, }; - m_Resources.equirectangular_to_cubemap = Shader::Create(parts); + resources_.EquirectangularToCubemap = Shader::Create(parts); } { std::vector parts = { @@ -436,7 +437,7 @@ namespace DE { {ShaderPartType::Fragment, shaders / "Fragment/CubeMapSample.fs"}, }; - m_Resources.skybox = Shader::Create(parts); + resources_.Skybox = Shader::Create(parts); } { std::vector parts = { @@ -444,7 +445,7 @@ namespace DE { {ShaderPartType::Fragment, shaders / "Fragment/CubeMapConvolution.fs"}, }; - m_Resources.convolution = Shader::Create(parts); + resources_.Convolution = Shader::Create(parts); } { std::vector parts = { @@ -452,7 +453,7 @@ namespace DE { {ShaderPartType::Fragment, shaders / "Fragment/CubeMapPrefilter.fs"}, }; - m_Resources.pre_filter_convolution = Shader::Create(parts); + resources_.PreFilterConvolution = Shader::Create(parts); } { std::vector parts = { @@ -460,7 +461,7 @@ namespace DE { {ShaderPartType::Fragment, shaders / "Fragment/BRDFConvolution.fs"}, }; - m_Resources.brdf_convolution = Shader::Create(parts); + resources_.BRDFConvolution = Shader::Create(parts); } { std::vector parts = { @@ -468,7 +469,7 @@ namespace DE { {ShaderPartType::Fragment, shaders / "Fragment/BrightnessFilter.fs"} }; - m_Resources.brightness_filter = Shader::Create(parts); + resources_.BrightnessFilter = Shader::Create(parts); } { std::vector parts = { @@ -476,7 +477,7 @@ namespace DE { {ShaderPartType::Fragment, shaders / "Fragment/TexturedQuad.fs"} }; - m_Resources.textured_quad = Shader::Create(parts); + resources_.TexturedQuad = Shader::Create(parts); } { std::vector parts = { @@ -484,7 +485,7 @@ namespace DE { {ShaderPartType::Fragment, shaders / "Fragment/GaussianBlur.fs"} }; - m_Resources.gaussian_blur = Shader::Create(parts); + resources_.GaussianBlur = Shader::Create(parts); } { std::vector parts = { @@ -492,7 +493,7 @@ namespace DE { {ShaderPartType::Fragment, shaders / "Fragment/Bloom.fs"} }; - m_Resources.bloom = Shader::Create(parts); + resources_.Bloom = Shader::Create(parts); } { std::vector parts = { @@ -500,7 +501,7 @@ namespace DE { {ShaderPartType::Fragment, shaders / "Fragment/GammaHDR.fs"} }; - m_Resources.gamma_hdr = Shader::Create(parts); + resources_.GammaHDR = Shader::Create(parts); } { std::vector parts = { @@ -508,7 +509,7 @@ namespace DE { {ShaderPartType::Fragment, shaders / "Fragment/BloomUpsample.fs"} }; - m_Resources.bloom_upsample = Shader::Create(parts); + resources_.BloomUpsample = Shader::Create(parts); } { std::vector parts = { @@ -516,7 +517,7 @@ namespace DE { {ShaderPartType::Fragment, shaders / "Fragment/BloomDownsample.fs"} }; - m_Resources.bloom_downsample = Shader::Create(parts); + resources_.BloomDownsample = Shader::Create(parts); } { std::vector parts = { @@ -524,7 +525,7 @@ namespace DE { {ShaderPartType::Fragment, shaders / "Fragment/DirectionalShadowMap.fs"} }; - m_Resources.directional_shadow_map = Shader::Create(parts); + resources_.DirectionalShadowMap = Shader::Create(parts); } { std::vector parts = { @@ -533,7 +534,7 @@ namespace DE { {ShaderPartType::Geometry, shaders / "Geometry/OmnidirectionalShadowMap.gs"} }; - m_Resources.omnidirectional_shadow_map = Shader::Create(parts); + resources_.OmnidirectionalShadowMap = Shader::Create(parts); } { const size_t sz = 1024; @@ -543,13 +544,13 @@ namespace DE { buffer->AddColorAttachment(Texture::Format::U8, Texture::Channels::RG); SetViewport(sz, sz); Clear(); - Submit(m_Resources.screen_quad, m_Resources.brdf_convolution); - m_Resources.brdf = buffer->GetColorAttachment(0); + Submit(resources_.ScreenQuad, resources_.BRDFConvolution); + resources_.BRDF = buffer->GetColorAttachment(0); } } void Renderer::Statistics::Reset() { - m_DrawCallsAmount = 0; - m_DrawnInstances = 0; + DrawCallsAmount = 0; + DrawnInstances = 0; } -} // namespace DE \ No newline at end of file +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Rendering/Renderer/Renderer.h b/DummyEngine/Core/Rendering/Renderer/Renderer.h index d7ee77e..089b54b 100644 --- a/DummyEngine/Core/Rendering/Renderer/Renderer.h +++ b/DummyEngine/Core/Rendering/Renderer/Renderer.h @@ -1,19 +1,20 @@ #pragma once -#include "DummyEngine/Core/Objects/Cameras/FPSCamera.h" -#include "DummyEngine/Core/Rendering/Renderer/CubeMap.h" -#include "DummyEngine/Core/Rendering/Renderer/FrameBuffer.h" #include "DummyEngine/Core/Rendering/Renderer/RenderAPI.h" -#include "DummyEngine/Core/Rendering/Renderer/RenderStructs.h" -#include "DummyEngine/Core/Rendering/Renderer/Shader.h" -#include "DummyEngine/Core/Rendering/Renderer/Texture.h" -#include "DummyEngine/Core/Rendering/Renderer/VertexArray.h" -#include "DummyEngine/Utils/Base.h" -namespace DE { +#include "DummyEngine/Utils/Debug/Logger.h" +#include "DummyEngine/Utils/Helpers/Singleton.h" + +namespace DummyEngine { + + class RenderMesh; + class CubeMap; + class Shader; + class Texture; + class FPSCamera; class Renderer : public Singleton { - LOGGER_AUTHOR(Renderer) + LOG_AUTHOR(Renderer) SINGLETON(Renderer) public: enum class Shaders { @@ -51,8 +52,8 @@ namespace DE { Last, }; struct Statistics { - U32 m_DrawCallsAmount; - U32 m_DrawnInstances; + U32 DrawCallsAmount; + U32 DrawnInstances; void Reset(); }; @@ -89,32 +90,32 @@ namespace DE { void GenResources(); struct Resources { - Ref white; - Ref normal; - Ref brdf; - - Ref screen_quad; - Ref cube; - - Ref equirectangular_to_cubemap; - Ref skybox; - Ref convolution; - Ref pre_filter_convolution; - Ref brdf_convolution; - Ref brightness_filter; - Ref gaussian_blur; - Ref textured_quad; - Ref bloom; - Ref gamma_hdr; - Ref bloom_upsample; - Ref bloom_downsample; - Ref directional_shadow_map; - Ref omnidirectional_shadow_map; + Ref White; + Ref Normal; + Ref BRDF; + + Ref ScreenQuad; + Ref Cube; + + Ref EquirectangularToCubemap; + Ref Skybox; + Ref Convolution; + Ref PreFilterConvolution; + Ref BRDFConvolution; + Ref BrightnessFilter; + Ref GaussianBlur; + Ref TexturedQuad; + Ref Bloom; + Ref GammaHDR; + Ref BloomUpsample; + Ref BloomDownsample; + Ref DirectionalShadowMap; + Ref OmnidirectionalShadowMap; }; - Scope m_RenderAPI; - Statistics m_FrameStatistics; - Resources m_Resources; + Scope render_api_; + Statistics frame_statistics_; + Resources resources_; }; -} // namespace DE +} // namespace DummyEngine diff --git a/DummyEngine/Core/Rendering/Renderer/Shader.cpp b/DummyEngine/Core/Rendering/Renderer/Shader.cpp index ae322f9..9e40efc 100644 --- a/DummyEngine/Core/Rendering/Renderer/Shader.cpp +++ b/DummyEngine/Core/Rendering/Renderer/Shader.cpp @@ -1,9 +1,10 @@ -#include "DummyEngine/Core/Rendering/Renderer/Shader.h" +#include "Shader.h" #include "DummyEngine/Core/Rendering/Renderer/Renderer.h" #include "DummyEngine/Core/Rendering/RendererOpenGL/GLShader.h" -namespace DE { +namespace DummyEngine { + Ref Shader::Create(const std::vector& initializers) { switch (Renderer::CurrentAPI()) { case API::OpenGL: return CreateRef(initializers); @@ -21,4 +22,4 @@ namespace DE { return nullptr; } -} // namespace DE \ No newline at end of file +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Rendering/Renderer/Shader.h b/DummyEngine/Core/Rendering/Renderer/Shader.h index d65317d..270537e 100644 --- a/DummyEngine/Core/Rendering/Renderer/Shader.h +++ b/DummyEngine/Core/Rendering/Renderer/Shader.h @@ -1,9 +1,8 @@ #pragma once #include "DummyEngine/Core/ResourceManaging/RawData.h" -#include "DummyEngine/Utils/Base.h" -namespace DE { +namespace DummyEngine { class Shader { public: @@ -28,4 +27,5 @@ namespace DE { static Ref Create(const std::vector& initializers); }; -} // namespace DE \ No newline at end of file + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Rendering/Renderer/SkyBox.cpp b/DummyEngine/Core/Rendering/Renderer/SkyBox.cpp index a30c350..3c885de 100644 --- a/DummyEngine/Core/Rendering/Renderer/SkyBox.cpp +++ b/DummyEngine/Core/Rendering/Renderer/SkyBox.cpp @@ -1,45 +1,47 @@ -#include "DummyEngine/Core/Rendering/Renderer/SkyBox.h" +#include "SkyBox.h" +#include "DummyEngine/Core/Rendering/Renderer/CubeMap.h" #include "DummyEngine/Core/Rendering/Renderer/FrameBuffer.h" #include "DummyEngine/Core/Rendering/Renderer/Renderer.h" +#include "DummyEngine/Core/Rendering/Renderer/Shader.h" -namespace DE { - const U32 SKYBOX_SIZE = 2048; - const U32 IRRADIANCE_TEXTURE_UNIT = 7; - const U32 PREFILTER_TEXTURE_UNIT = 8; - const U32 BRDF_TEXTURE_UNIT = 9; - const U32 MAX_LEVELS = 10; +namespace DummyEngine { + constexpr U32 kSkyboxSize = 2048; + constexpr U32 kIrradianceTextureUnit = 7; + constexpr U32 kPrefilterTextureUnit = 8; + constexpr U32 kBRDFTextureUnit = 9; + constexpr U32 kMaxLevels = 10; SkyBox::SkyBox(Ref texture) { - m_Raw = GenRawCubeMap(texture); + raw_ = GenRawCubeMap(texture); BakeIBL(); } SkyBox::SkyBox(Ref cubemap) { - m_Raw = cubemap; + raw_ = cubemap; BakeIBL(); } Ref SkyBox::GetMap() { - return m_Raw; + return raw_; } void SkyBox::ApplyIBL(Ref shader) { - if (!m_Irradiance) { + if (!irradiance_) { return; } - if (!m_Prefilter) { + if (!prefilter_) { return; } - m_Irradiance->Bind(IRRADIANCE_TEXTURE_UNIT); - m_Prefilter->Bind(PREFILTER_TEXTURE_UNIT); - Renderer::GetTexture(Renderer::Textures::BRDF)->Bind(BRDF_TEXTURE_UNIT); - shader->SetInt("u_IrradianceMap", IRRADIANCE_TEXTURE_UNIT); - shader->SetInt("u_PrefilterMap", PREFILTER_TEXTURE_UNIT); - shader->SetInt("u_BRDF", BRDF_TEXTURE_UNIT); + irradiance_->Bind(kIrradianceTextureUnit); + prefilter_->Bind(kPrefilterTextureUnit); + Renderer::GetTexture(Renderer::Textures::BRDF)->Bind(kBRDFTextureUnit); + shader->SetInt("u_IrradianceMap", kIrradianceTextureUnit); + shader->SetInt("u_PrefilterMap", kPrefilterTextureUnit); + shader->SetInt("u_BRDF", kBRDFTextureUnit); } Ref SkyBox::GenRawCubeMap(Ref texture) { Ref tex = Texture::Create(*texture); - Ref res = CubeMap::Create(SKYBOX_SIZE, Texture::DataFormat(texture->Format()), Texture::DataChannels(texture->Channels())); + Ref res = CubeMap::Create(kSkyboxSize, Texture::DataFormat(texture->Format()), Texture::DataChannels(texture->Channels())); Ref shader = Renderer::GetShader(Renderer::Shaders::EquirectangularToCubeMap); Ref cube = Renderer::GetVertexArray(Renderer::VertexArrays::Cube); @@ -56,11 +58,11 @@ namespace DE { shader->SetMat4("u_Projection", projection); for (U32 i = 0; i < 6; ++i) { shader->SetMat4("u_View", views[i]); - Ref buf = FrameBuffer::Create({SKYBOX_SIZE, SKYBOX_SIZE}); + Ref buf = FrameBuffer::Create({kSkyboxSize, kSkyboxSize}); buf->Bind(); buf->SetDepthAttachment(Texture::Format::F32); buf->AddColorAttachment(res, i); - Renderer::SetViewport(SKYBOX_SIZE, SKYBOX_SIZE); + Renderer::SetViewport(kSkyboxSize, kSkyboxSize); Renderer::Clear(); tex->Bind(1); Renderer::Submit(cube, shader); @@ -68,7 +70,7 @@ namespace DE { return res; } void SkyBox::BakeIBL() { - m_Irradiance = CubeMap::Create(SKYBOX_SIZE, Texture::Format::U8, Texture::Channels::RGB); + irradiance_ = CubeMap::Create(kSkyboxSize, Texture::Format::U8, Texture::Channels::RGB); Ref shader = Renderer::GetShader(Renderer::Shaders::Convolution); Ref cube = Renderer::GetVertexArray(Renderer::VertexArrays::Cube); @@ -85,33 +87,33 @@ namespace DE { shader->SetMat4("u_Projection", projection); for (U32 i = 0; i < 6; ++i) { shader->SetMat4("u_View", views[i]); - Ref buf = FrameBuffer::Create({SKYBOX_SIZE, SKYBOX_SIZE}); + Ref buf = FrameBuffer::Create({kSkyboxSize, kSkyboxSize}); buf->Bind(); buf->SetDepthAttachment(Texture::Format::F32); - buf->AddColorAttachment(m_Irradiance, i); - Renderer::SetViewport(SKYBOX_SIZE, SKYBOX_SIZE); + buf->AddColorAttachment(irradiance_, i); + Renderer::SetViewport(kSkyboxSize, kSkyboxSize); Renderer::Clear(); - m_Raw->Bind(1); + raw_->Bind(1); Renderer::Submit(cube, shader); } - U32 curr_size = SKYBOX_SIZE; - m_Prefilter = CubeMap::Create(curr_size, Texture::Format::U8, Texture::Channels::RGB, true); + U32 curr_size = kSkyboxSize; + prefilter_ = CubeMap::Create(curr_size, Texture::Format::U8, Texture::Channels::RGB, true); Ref s_prefilter = Renderer::GetShader(Renderer::Shaders::PreFileterConvolution); s_prefilter->Bind(); s_prefilter->SetInt("u_CubeMap", 1); s_prefilter->SetMat4("u_Projection", projection); s_prefilter->SetMat4("u_Transform", Mat4(1.0)); - for (U32 lod = 0; lod < MAX_LEVELS; ++lod) { - float roughness = (float)lod / (MAX_LEVELS - 1); + for (U32 lod = 0; lod < kMaxLevels; ++lod) { + float roughness = (float)lod / (kMaxLevels - 1); s_prefilter->SetFloat("u_Roughness", roughness); for (U32 i = 0; i < 6; ++i) { s_prefilter->SetMat4("u_View", views[i]); Ref buf = FrameBuffer::Create({curr_size, curr_size}); buf->Bind(); buf->SetDepthAttachment(Texture::Format::F32); - buf->AddColorAttachment(m_Prefilter, i, lod); - m_Raw->Bind(1); + buf->AddColorAttachment(prefilter_, i, lod); + raw_->Bind(1); Renderer::SetViewport(curr_size, curr_size); Renderer::Clear(); Renderer::Submit(cube, s_prefilter); @@ -119,4 +121,5 @@ namespace DE { curr_size /= 2; } } -} // namespace DE \ No newline at end of file + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Rendering/Renderer/SkyBox.h b/DummyEngine/Core/Rendering/Renderer/SkyBox.h index 9a9b9ef..0ed101a 100644 --- a/DummyEngine/Core/Rendering/Renderer/SkyBox.h +++ b/DummyEngine/Core/Rendering/Renderer/SkyBox.h @@ -1,16 +1,18 @@ #pragma once -#include "DummyEngine/Core/Rendering/Renderer/CubeMap.h" -#include "DummyEngine/Core/Rendering/Renderer/Shader.h" -#include "DummyEngine/Core/Rendering/Renderer/Texture.h" -#include "DummyEngine/Utils/Base.h" +#include "DummyEngine/Utils/Types/Types.h" + +namespace DummyEngine { + + class TextureData; + class CubeMap; + class Shader; -namespace DE { class SkyBox { public: SkyBox() = default; - SkyBox(Ref texture); - SkyBox(Ref cubemap); + explicit SkyBox(Ref texture); + explicit SkyBox(Ref cubemap); Ref GetMap(); void ApplyIBL(Ref shader); @@ -19,8 +21,9 @@ namespace DE { Ref GenRawCubeMap(Ref texture); void BakeIBL(); - Ref m_Raw; - Ref m_Irradiance; - Ref m_Prefilter; + Ref raw_; + Ref irradiance_; + Ref prefilter_; }; -} // namespace DE \ No newline at end of file + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Rendering/Renderer/Texture.cpp b/DummyEngine/Core/Rendering/Renderer/Texture.cpp index a89ed6e..decb7f3 100644 --- a/DummyEngine/Core/Rendering/Renderer/Texture.cpp +++ b/DummyEngine/Core/Rendering/Renderer/Texture.cpp @@ -1,9 +1,10 @@ -#include "DummyEngine/Core/Rendering/Renderer/Texture.h" +#include "Texture.h" #include "DummyEngine/Core/Rendering/Renderer/Renderer.h" #include "DummyEngine/Core/Rendering/RendererOpenGL/GLTexture.h" -namespace DE { +namespace DummyEngine { + std::string Texture::FormatToStr(Format format) { switch (format) { case Format::F16: return "F16"; @@ -95,4 +96,5 @@ namespace DE { } return Texture::Channels::None; } -} // namespace DE \ No newline at end of file + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Rendering/Renderer/Texture.h b/DummyEngine/Core/Rendering/Renderer/Texture.h index 92cb7f0..2eb481c 100644 --- a/DummyEngine/Core/Rendering/Renderer/Texture.h +++ b/DummyEngine/Core/Rendering/Renderer/Texture.h @@ -1,9 +1,9 @@ #pragma once #include "DummyEngine/Core/ResourceManaging/RawData.h" -#include "DummyEngine/Utils/Base.h" -namespace DE { +namespace DummyEngine { + class FrameBuffer; class Texture { public: @@ -33,4 +33,5 @@ namespace DE { static Ref Create(U32 width, U32 height, Channels channels = Channels::RGBA, Format format = Format::U8, bool depth_buffer = false); static Ref Create(const TextureData& texture_data); }; -} // namespace DE \ No newline at end of file + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Rendering/Renderer/UniformBuffer.cpp b/DummyEngine/Core/Rendering/Renderer/UniformBuffer.cpp index 988c695..62251d4 100644 --- a/DummyEngine/Core/Rendering/Renderer/UniformBuffer.cpp +++ b/DummyEngine/Core/Rendering/Renderer/UniformBuffer.cpp @@ -1,9 +1,10 @@ -#include "DummyEngine/Core/Rendering/Renderer/UniformBuffer.h" +#include "UniformBuffer.h" #include "DummyEngine/Core/Rendering/Renderer/Renderer.h" #include "DummyEngine/Core/Rendering/RendererOpenGL/GLUniformBuffer.h" -namespace DE { +namespace DummyEngine { + Ref UniformBuffer::Create(const BufferLayout& layout, U32 size) { switch (Renderer::CurrentAPI()) { case API::OpenGL: return CreateRef(layout, size); @@ -21,4 +22,5 @@ namespace DE { return nullptr; } -} // namespace DE \ No newline at end of file + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Rendering/Renderer/UniformBuffer.h b/DummyEngine/Core/Rendering/Renderer/UniformBuffer.h index db39cf4..f7dd69d 100644 --- a/DummyEngine/Core/Rendering/Renderer/UniformBuffer.h +++ b/DummyEngine/Core/Rendering/Renderer/UniformBuffer.h @@ -2,20 +2,20 @@ #include "DummyEngine/Core/Rendering/Renderer/BufferLayout.h" #include "DummyEngine/Core/Rendering/Renderer/LocalBuffer.h" -#include "DummyEngine/Utils/Base.h" -namespace DE { +namespace DummyEngine { class UniformBuffer { public: virtual ~UniformBuffer() = default; virtual void Bind(U32 index) const = 0; - virtual LocalBufferNode at(U32 index) = 0; + virtual LocalBufferNode At(U32 index) = 0; virtual void PushData() const = 0; virtual const BufferLayout& GetLayout() const = 0; static Ref Create(const BufferLayout& layout, U32 size); }; -} // namespace DE + +} // namespace DummyEngine diff --git a/DummyEngine/Core/Rendering/Renderer/VertexArray.cpp b/DummyEngine/Core/Rendering/Renderer/VertexArray.cpp index bd10499..4fe8232 100644 --- a/DummyEngine/Core/Rendering/Renderer/VertexArray.cpp +++ b/DummyEngine/Core/Rendering/Renderer/VertexArray.cpp @@ -1,9 +1,9 @@ -#include "DummyEngine/Core/Rendering/Renderer/VertexArray.h" +#include "VertexArray.h" #include "DummyEngine/Core/Rendering/Renderer/Renderer.h" #include "DummyEngine/Core/Rendering/RendererOpenGL/GLVertexArray.h" -namespace DE { +namespace DummyEngine { Ref VertexArray::Copy() const { Ref result = VertexArray::Create(); @@ -29,4 +29,4 @@ namespace DE { } return nullptr; } -} // namespace DE \ No newline at end of file +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Rendering/Renderer/VertexArray.h b/DummyEngine/Core/Rendering/Renderer/VertexArray.h index c7810e8..59b19dd 100644 --- a/DummyEngine/Core/Rendering/Renderer/VertexArray.h +++ b/DummyEngine/Core/Rendering/Renderer/VertexArray.h @@ -1,9 +1,8 @@ #pragma once #include "DummyEngine/Core/Rendering/Renderer/VertexBuffer.h" -#include "DummyEngine/Utils/Base.h" -namespace DE { +namespace DummyEngine { class VertexArray { public: @@ -12,9 +11,8 @@ namespace DE { virtual void Bind() const = 0; virtual void UnBind() const = 0; - virtual void AddVertexBuffer(const Ref& vertexBuffer) = 0; - - virtual void SetIndexBuffer(const Ref& indexBuffer) = 0; + virtual void AddVertexBuffer(const Ref& vertex_buffer) = 0; + virtual void SetIndexBuffer(const Ref& index_buffer) = 0; virtual const std::vector>& GetVertexBuffers() const = 0; virtual const Ref& GetIndexBuffer() const = 0; @@ -22,4 +20,5 @@ namespace DE { Ref Copy() const; static Ref Create(); }; -} // namespace DE \ No newline at end of file + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Rendering/Renderer/VertexBuffer.cpp b/DummyEngine/Core/Rendering/Renderer/VertexBuffer.cpp index e5bf0f0..848b344 100644 --- a/DummyEngine/Core/Rendering/Renderer/VertexBuffer.cpp +++ b/DummyEngine/Core/Rendering/Renderer/VertexBuffer.cpp @@ -1,9 +1,11 @@ -#include "DummyEngine/Core/Rendering/Renderer/VertexBuffer.h" +#include "VertexBuffer.h" #include "DummyEngine/Core/Rendering/Renderer/Renderer.h" #include "DummyEngine/Core/Rendering/RendererOpenGL/GLVertexBuffer.h" +#include "DummyEngine/Utils/Debug/Assert.h" + +namespace DummyEngine { -namespace DE { Ref VertexBuffer::Create(const BufferLayout& layout, U32 size, BufferUsage usage) { switch (Renderer::CurrentAPI()) { case API::OpenGL: return CreateRef(layout, size, usage); @@ -55,4 +57,4 @@ namespace DE { return nullptr; } -} // namespace DE \ No newline at end of file +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Rendering/Renderer/VertexBuffer.h b/DummyEngine/Core/Rendering/Renderer/VertexBuffer.h index 6a71de3..50d268a 100644 --- a/DummyEngine/Core/Rendering/Renderer/VertexBuffer.h +++ b/DummyEngine/Core/Rendering/Renderer/VertexBuffer.h @@ -1,9 +1,9 @@ #pragma once +#include "DummyEngine/Core/Rendering/Renderer/BufferLayout.h" #include "DummyEngine/Core/Rendering/Renderer/LocalBuffer.h" -#include "DummyEngine/Utils/Base.h" -namespace DE { +namespace DummyEngine { class VertexBuffer { public: @@ -12,7 +12,7 @@ namespace DE { virtual void Bind() const = 0; virtual void UnBind() const = 0; - virtual LocalBufferNode at(U32 index) = 0; + virtual LocalBufferNode At(U32 index) = 0; virtual void SetData(const void* data, U32 size) = 0; virtual void PushData() = 0; @@ -36,4 +36,4 @@ namespace DE { static Ref Create(const U32* indices, U32 count); }; -} // namespace DE +} // namespace DummyEngine diff --git a/DummyEngine/Core/Rendering/RendererOpenGL/GLContext.cpp b/DummyEngine/Core/Rendering/RendererOpenGL/GLContext.cpp index 0b7e41e..9bee6c3 100644 --- a/DummyEngine/Core/Rendering/RendererOpenGL/GLContext.cpp +++ b/DummyEngine/Core/Rendering/RendererOpenGL/GLContext.cpp @@ -1,20 +1,21 @@ -#include "DummyEngine/Core/Rendering/RendererOpenGL/GLContext.h" +#include "GLContext.h" #include "DummyEngine/Core/Rendering/RendererOpenGL/GLUtils.h" +#include "DummyEngine/Utils/Debug/Profiler.h" // clang-format off #include #include // clang-format on -namespace DE { +namespace DummyEngine { - GLContext::GLContext(GLFWwindow* window) : m_Window(window) { + GLContext::GLContext(GLFWwindow* window) : window_(window) { DE_ASSERT(window, "Wrong window handle"); } void GLContext::Load() { - glfwMakeContextCurrent(m_Window); + glfwMakeContextCurrent(window_); int status = gladLoadGLLoader((GLADloadproc)glfwGetProcAddress); DE_ASSERT(status, "Failed to initialize GLAD"); @@ -25,7 +26,7 @@ namespace DE { void GLContext::SwapBuffers() { DE_PROFILE_SCOPE("Context SwapBuffers"); - glfwSwapBuffers(m_Window); + glfwSwapBuffers(window_); } -} // namespace DE +} // namespace DummyEngine diff --git a/DummyEngine/Core/Rendering/RendererOpenGL/GLContext.h b/DummyEngine/Core/Rendering/RendererOpenGL/GLContext.h index 004627d..e9338ac 100644 --- a/DummyEngine/Core/Rendering/RendererOpenGL/GLContext.h +++ b/DummyEngine/Core/Rendering/RendererOpenGL/GLContext.h @@ -1,19 +1,20 @@ #pragma once #include "DummyEngine/Core/Rendering/Renderer/Context.h" +#include "DummyEngine/Utils/Debug/Logger.h" -namespace DE { +namespace DummyEngine { class GLContext : public Context { - LOGGER_AUTHOR(GLContext) + LOG_AUTHOR(GLContext) public: - GLContext(GLFWwindow* window); + explicit GLContext(GLFWwindow* window); virtual void Load() override; virtual void SwapBuffers() override; private: - GLFWwindow* m_Window; + GLFWwindow* window_; }; -} // namespace DE \ No newline at end of file +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Rendering/RendererOpenGL/GLCubeMap.cpp b/DummyEngine/Core/Rendering/RendererOpenGL/GLCubeMap.cpp index 61deaca..a7f674b 100644 --- a/DummyEngine/Core/Rendering/RendererOpenGL/GLCubeMap.cpp +++ b/DummyEngine/Core/Rendering/RendererOpenGL/GLCubeMap.cpp @@ -1,13 +1,14 @@ -#include "DummyEngine/Core/Rendering/RendererOpenGL/GLCubeMap.h" +#include "GLCubeMap.h" #include "DummyEngine/Core/Rendering/Renderer/Texture.h" #include "DummyEngine/Core/Rendering/RendererOpenGL/GLUtils.h" #include "DummyEngine/ToolBox/Editors/TextureEditor.h" -namespace DE { +namespace DummyEngine { + GLCubeMap::GLCubeMap(const Ref data) { - glGenTextures(1, &m_MapId); - glBindTexture(GL_TEXTURE_CUBE_MAP, m_MapId); + glGenTextures(1, &map_id_); + glBindTexture(GL_TEXTURE_CUBE_MAP, map_id_); // TODO: move somewhere else... glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR); @@ -45,8 +46,8 @@ namespace DE { glCheckError(); } GLCubeMap::GLCubeMap(U32 size, Texture::Format format, Texture::Channels channels, bool gen_mipmap, bool depth_map) { - glGenTextures(1, &m_MapId); - glBindTexture(GL_TEXTURE_CUBE_MAP, m_MapId); + glGenTextures(1, &map_id_); + glBindTexture(GL_TEXTURE_CUBE_MAP, map_id_); // TODO: move somewhere else... if (!depth_map) { @@ -77,14 +78,15 @@ namespace DE { glCheckError(); } GLCubeMap::~GLCubeMap() { - glDeleteTextures(1, &m_MapId); + glDeleteTextures(1, &map_id_); } float& GLCubeMap::GetLOD() { - return m_LOD; + return lod_; } void GLCubeMap::Bind(U32 slot) const { glActiveTexture(GL_TEXTURE0 + slot); - glBindTexture(GL_TEXTURE_CUBE_MAP, m_MapId); + glBindTexture(GL_TEXTURE_CUBE_MAP, map_id_); } -} // namespace DE \ No newline at end of file + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Rendering/RendererOpenGL/GLCubeMap.h b/DummyEngine/Core/Rendering/RendererOpenGL/GLCubeMap.h index 54b8f38..438f59c 100644 --- a/DummyEngine/Core/Rendering/RendererOpenGL/GLCubeMap.h +++ b/DummyEngine/Core/Rendering/RendererOpenGL/GLCubeMap.h @@ -3,14 +3,16 @@ #include #include "DummyEngine/Core/Rendering/Renderer/CubeMap.h" +#include "DummyEngine/Utils/Debug/Logger.h" -namespace DE { +namespace DummyEngine { class GLCubeMap : public CubeMap { - LOGGER_AUTHOR(GLCubeMap) + LOG_AUTHOR(GLCubeMap) public: - GLCubeMap(const Ref data); + explicit GLCubeMap(const Ref data); GLCubeMap(U32 size, Texture::Format format, Texture::Channels channels, bool gen_mipmap, bool depth_map); virtual ~GLCubeMap(); + virtual void Bind(U32 slot) const override; virtual float& GetLOD() override; @@ -22,7 +24,7 @@ namespace DE { private: friend class GLFrameBuffer; - float m_LOD = 0; - GLuint m_MapId; + float lod_ = 0; + GLuint map_id_; }; -} // namespace DE \ No newline at end of file +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Rendering/RendererOpenGL/GLDebug.cpp b/DummyEngine/Core/Rendering/RendererOpenGL/GLDebug.cpp index 89d4018..ff979fb 100644 --- a/DummyEngine/Core/Rendering/RendererOpenGL/GLDebug.cpp +++ b/DummyEngine/Core/Rendering/RendererOpenGL/GLDebug.cpp @@ -1,13 +1,17 @@ -#include "DummyEngine/Core/Rendering/RendererOpenGL/GLDebug.h" +#include "GLDebug.h" #include -namespace DE { - void glCheckError_(const char* file, int line) { - GLenum errorCode; - while ((errorCode = glGetError()) != GL_NO_ERROR) { +#include +#include + +namespace DummyEngine { + + void GlCheckError(const char* file, int line) { + GLenum error_code; + while ((error_code = glGetError()) != GL_NO_ERROR) { std::string error; - switch (errorCode) { + switch (error_code) { case GL_INVALID_ENUM: error = "INVALID_ENUM"; break; case GL_INVALID_VALUE: error = "INVALID_VALUE"; break; case GL_INVALID_OPERATION: error = "INVALID_OPERATION"; break; @@ -16,6 +20,5 @@ namespace DE { } std::cout << error << " | " << file << " (" << line << ")" << std::endl; } - return; } -} // namespace DE \ No newline at end of file +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Rendering/RendererOpenGL/GLDebug.h b/DummyEngine/Core/Rendering/RendererOpenGL/GLDebug.h index 62bb734..ed47750 100644 --- a/DummyEngine/Core/Rendering/RendererOpenGL/GLDebug.h +++ b/DummyEngine/Core/Rendering/RendererOpenGL/GLDebug.h @@ -1,8 +1,6 @@ #pragma once -#include "DummyEngine/Utils/Base.h" - -namespace DE { - void glCheckError_(const char* file, int line); -#define glCheckError() glCheckError_(__FILE__, __LINE__) -} // namespace DE +namespace DummyEngine { + void GlCheckError(const char* file, int line); +#define glCheckError() GlCheckError(__FILE__, __LINE__) +} // namespace DummyEngine diff --git a/DummyEngine/Core/Rendering/RendererOpenGL/GLFrameBuffer.cpp b/DummyEngine/Core/Rendering/RendererOpenGL/GLFrameBuffer.cpp index 5cf589a..adc70fa 100644 --- a/DummyEngine/Core/Rendering/RendererOpenGL/GLFrameBuffer.cpp +++ b/DummyEngine/Core/Rendering/RendererOpenGL/GLFrameBuffer.cpp @@ -1,9 +1,10 @@ -#include "DummyEngine/Core/Rendering/RendererOpenGL/GLFrameBuffer.h" +#include "GLFrameBuffer.h" #include "DummyEngine/Core/Rendering/RendererOpenGL/GLCubeMap.h" #include "DummyEngine/Core/Rendering/RendererOpenGL/GLTexture.h" -namespace DE { +namespace DummyEngine { + bool IsColorFormat(Texture::Channels channels) { switch (channels) { case Texture::Channels::R: return true; @@ -21,22 +22,22 @@ namespace DE { } void GLFrameBuffer::Rebuild() { - for (size_t i = 0; i < m_ColorAttachments.size(); ++i) { - auto& attachment = m_ColorAttachments[i]; - attachment.m_Texture->Resize(m_Properties.width, m_Properties.height); + for (size_t i = 0; i < color_attachments_.size(); ++i) { + auto& attachment = color_attachments_[i]; + attachment.Texture->Resize(properties_.Width, properties_.Height); } - m_DepthAttachment.m_Texture->Resize(m_Properties.width, m_Properties.height); + depth_attachment_.Texture->Resize(properties_.Width, properties_.Height); } - GLFrameBuffer::GLFrameBuffer(const FrameBufferProperties& properties) : m_BufferId(0), m_Properties(properties) { - glGenFramebuffers(1, &m_BufferId); + GLFrameBuffer::GLFrameBuffer(const FrameBufferProperties& properties) : buffer_id_(0), properties_(properties) { + glGenFramebuffers(1, &buffer_id_); } GLFrameBuffer::~GLFrameBuffer() { - glDeleteFramebuffers(1, &m_BufferId); + glDeleteFramebuffers(1, &buffer_id_); } void GLFrameBuffer::Bind() { - glBindFramebuffer(GL_FRAMEBUFFER, m_BufferId); + glBindFramebuffer(GL_FRAMEBUFFER, buffer_id_); } void GLFrameBuffer::UnBind() { glBindFramebuffer(GL_FRAMEBUFFER, 0); @@ -45,74 +46,74 @@ namespace DE { void GLFrameBuffer::AddColorAttachment(Texture::Format format, Texture::Channels channels) { // TODO: Switch 8 to GPU capabilities. DE_ASSERT(IsColorFormat(channels), "Wrong channels for color attachment"); - DE_ASSERT(m_ColorAttachments.size() <= 8, "No available color attachment slot"); - glBindFramebuffer(GL_FRAMEBUFFER, m_BufferId); - m_ColorAttachments.push_back({nullptr}); - m_ColorAttachments.back().m_Texture = Texture::Create(m_Properties.width, m_Properties.height, channels, format); + DE_ASSERT(color_attachments_.size() <= 8, "No available color attachment slot"); + glBindFramebuffer(GL_FRAMEBUFFER, buffer_id_); + color_attachments_.push_back({nullptr}); + color_attachments_.back().Texture = Texture::Create(properties_.Width, properties_.Height, channels, format); glFramebufferTexture2D(GL_FRAMEBUFFER, - GL_COLOR_ATTACHMENT0 + m_ColorAttachments.size() - 1, + GL_COLOR_ATTACHMENT0 + color_attachments_.size() - 1, GL_TEXTURE_2D, - std::dynamic_pointer_cast(m_ColorAttachments.back().m_Texture)->m_TextureId, + std::dynamic_pointer_cast(color_attachments_.back().Texture)->texture_id_, 0); } void GLFrameBuffer::AddColorAttachment(Ref map, U32 side, U32 lod) { // TODO: Rework - glBindFramebuffer(GL_FRAMEBUFFER, m_BufferId); - m_ColorAttachments.push_back({nullptr}); + glBindFramebuffer(GL_FRAMEBUFFER, buffer_id_); + color_attachments_.push_back({nullptr}); glFramebufferTexture2D(GL_FRAMEBUFFER, - GL_COLOR_ATTACHMENT0 + m_ColorAttachments.size() - 1, + GL_COLOR_ATTACHMENT0 + color_attachments_.size() - 1, GL_TEXTURE_CUBE_MAP_POSITIVE_X + side, - std::dynamic_pointer_cast(map)->m_MapId, + std::dynamic_pointer_cast(map)->map_id_, lod); } void GLFrameBuffer::SetDepthAttachment(Texture::Format format) { - glBindFramebuffer(GL_FRAMEBUFFER, m_BufferId); - m_DepthAttachment.m_Texture = Texture::Create(m_Properties.width, m_Properties.height, Texture::Channels::Depth, format, true); + glBindFramebuffer(GL_FRAMEBUFFER, buffer_id_); + depth_attachment_.Texture = Texture::Create(properties_.Width, properties_.Height, Texture::Channels::Depth, format, true); glFramebufferTexture2D( - GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, std::dynamic_pointer_cast(m_DepthAttachment.m_Texture)->m_TextureId, 0); + GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, std::dynamic_pointer_cast(depth_attachment_.Texture)->texture_id_, 0); } void GLFrameBuffer::SetColorAttachment(Ref texture, U32 id) { - if (m_ColorAttachments.size() <= id) { - m_ColorAttachments.resize(id + 1); + if (color_attachments_.size() <= id) { + color_attachments_.resize(id + 1); } - m_ColorAttachments[id].m_Texture = texture; - glBindFramebuffer(GL_FRAMEBUFFER, m_BufferId); + color_attachments_[id].Texture = texture; + glBindFramebuffer(GL_FRAMEBUFFER, buffer_id_); glFramebufferTexture2D( - GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + id, GL_TEXTURE_2D, std::dynamic_pointer_cast(texture)->m_TextureId, 0); + GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + id, GL_TEXTURE_2D, std::dynamic_pointer_cast(texture)->texture_id_, 0); } void GLFrameBuffer::SetDepthAttachment(Ref map) { - glBindFramebuffer(GL_FRAMEBUFFER, m_BufferId); - glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, std::dynamic_pointer_cast(map)->m_MapId, 0); + glBindFramebuffer(GL_FRAMEBUFFER, buffer_id_); + glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, std::dynamic_pointer_cast(map)->map_id_, 0); } bool GLFrameBuffer::Valid() const { - glBindFramebuffer(GL_FRAMEBUFFER, m_BufferId); + glBindFramebuffer(GL_FRAMEBUFFER, buffer_id_); GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); return status == GL_FRAMEBUFFER_COMPLETE; } void GLFrameBuffer::Resize(U32 width, U32 height) { - if ((m_Properties.width != width || m_Properties.height != height) && 0 < width && 0 < height) { - m_Properties.width = width; - m_Properties.height = height; + if ((properties_.Width != width || properties_.Height != height) && 0 < width && 0 < height) { + properties_.Width = width; + properties_.Height = height; Rebuild(); } } U32 GLFrameBuffer::GetWidth() const { - return m_Properties.width; + return properties_.Width; } U32 GLFrameBuffer::GetHeight() const { - return m_Properties.height; + return properties_.Height; } Ref GLFrameBuffer::GetColorAttachment(U32 attachment_id = 0) { - DE_ASSERT(0 <= attachment_id && attachment_id < m_ColorAttachments.size(), "Color attachment with index {} does not exist", attachment_id); - return m_ColorAttachments[attachment_id].m_Texture; + DE_ASSERT(0 <= attachment_id && attachment_id < color_attachments_.size(), "Color attachment with index {} does not exist", attachment_id); + return color_attachments_[attachment_id].Texture; } Ref GLFrameBuffer::GetDepthAttachment() { - return m_DepthAttachment.m_Texture; + return depth_attachment_.Texture; } const FrameBufferProperties& GLFrameBuffer::GetProperties() const { - return m_Properties; + return properties_; } -} // namespace DE \ No newline at end of file +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Rendering/RendererOpenGL/GLFrameBuffer.h b/DummyEngine/Core/Rendering/RendererOpenGL/GLFrameBuffer.h index bb87be5..84854e8 100644 --- a/DummyEngine/Core/Rendering/RendererOpenGL/GLFrameBuffer.h +++ b/DummyEngine/Core/Rendering/RendererOpenGL/GLFrameBuffer.h @@ -1,14 +1,14 @@ #pragma once +#include "DummyEngine/Core/Rendering/Renderer/FrameBuffer.h" + #include -#include "DummyEngine/Core/Rendering/Renderer/FrameBuffer.h" -#include "DummyEngine/Utils/Base.h" +namespace DummyEngine { -namespace DE { class GLFrameBuffer : public FrameBuffer { public: - GLFrameBuffer(const FrameBufferProperties& properties); + explicit GLFrameBuffer(const FrameBufferProperties& properties); virtual ~GLFrameBuffer(); GLFrameBuffer() = delete; @@ -38,10 +38,11 @@ namespace DE { virtual const FrameBufferProperties& GetProperties() const override; private: - GLuint m_BufferId; - FrameBufferProperties m_Properties; + GLuint buffer_id_; + FrameBufferProperties properties_; - FrameBufferAttchment m_DepthAttachment; - std::vector m_ColorAttachments; + FrameBufferAttchment depth_attachment_; + std::vector color_attachments_; }; -} // namespace DE \ No newline at end of file + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Rendering/RendererOpenGL/GLRenderAPI.cpp b/DummyEngine/Core/Rendering/RendererOpenGL/GLRenderAPI.cpp index 53efab1..9125509 100644 --- a/DummyEngine/Core/Rendering/RendererOpenGL/GLRenderAPI.cpp +++ b/DummyEngine/Core/Rendering/RendererOpenGL/GLRenderAPI.cpp @@ -1,19 +1,15 @@ -#include "DummyEngine/Core/Rendering/RendererOpenGL/GLRenderAPI.h" - -#include +#include "GLRenderAPI.h" #include "DummyEngine/Core/Rendering/RendererOpenGL/GLUtils.h" -namespace DE { +#include + +namespace DummyEngine { void GLRenderAPI::SetDefaultState() { glEnable(GL_DEPTH_TEST); glEnable(GL_MULTISAMPLE); - // glEnable(GL_CULL_FACE); glCullFace(GL_FRONT); - // glFrontFace(GL_CW); - // glDepthMask(GL_TRUE); - // glDepthFunc(GL_LEQUAL); glEnable(GL_BLEND); glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS); @@ -76,4 +72,5 @@ namespace DE { API GLRenderAPI::GetAPI() { return API::OpenGL; } -} // namespace DE \ No newline at end of file + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Rendering/RendererOpenGL/GLRenderAPI.h b/DummyEngine/Core/Rendering/RendererOpenGL/GLRenderAPI.h index ff1c750..681ea9b 100644 --- a/DummyEngine/Core/Rendering/RendererOpenGL/GLRenderAPI.h +++ b/DummyEngine/Core/Rendering/RendererOpenGL/GLRenderAPI.h @@ -2,7 +2,8 @@ #include "DummyEngine/Core/Rendering/Renderer/RenderAPI.h" -namespace DE { +namespace DummyEngine { + class GLRenderAPI : public RenderAPI { public: GLRenderAPI() = default; @@ -28,4 +29,5 @@ namespace DE { virtual API GetAPI() override; }; -} // namespace DE \ No newline at end of file + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Rendering/RendererOpenGL/GLShader.cpp b/DummyEngine/Core/Rendering/RendererOpenGL/GLShader.cpp index 642f3dc..ac046fa 100644 --- a/DummyEngine/Core/Rendering/RendererOpenGL/GLShader.cpp +++ b/DummyEngine/Core/Rendering/RendererOpenGL/GLShader.cpp @@ -1,10 +1,11 @@ -#include "DummyEngine/Core/Rendering/RendererOpenGL/GLShader.h" +#include "GLShader.h" #include "DummyEngine/Core/Application/Config.h" -#include "DummyEngine/Core/Rendering/Renderer/Renderer.h" #include "DummyEngine/Core/Rendering/RendererOpenGL/GLDebug.h" -namespace DE { +#include + +namespace DummyEngine { GLenum ShaderPartTypeToGLShaderPartType(ShaderPartType type) { switch (type) { case ShaderPartType::Vertex: return GL_VERTEX_SHADER; @@ -15,90 +16,90 @@ namespace DE { } GLShader::GLShader(const std::vector& shader_parts) { - m_ShaderId = glCreateProgram(); + shader_id_ = glCreateProgram(); for (const auto& part : shader_parts) { AddPart(part); } - glLinkProgram(m_ShaderId); + glLinkProgram(shader_id_); int success; std::string info_log; - info_log.resize(Config::GetI(DE_CFG_MAX_COMPILE_ERROR_LEN)); - glGetProgramiv(m_ShaderId, GL_LINK_STATUS, &success); + info_log.resize(Config::Get().MaxShaderCompileErrorLen); + glGetProgramiv(shader_id_, GL_LINK_STATUS, &success); int len = 0; - if (!success) { - glGetProgramInfoLog(m_ShaderId, info_log.size(), &len, info_log.data()); + if (success == GL_FALSE) { + glGetProgramInfoLog(shader_id_, info_log.size(), &len, info_log.data()); info_log.resize(len); - LOG_ERROR("Failed to link shader program {} due:\n{}", std::to_string(m_ShaderId), info_log); + LOG_ERROR("Failed to link shader program {} due:\n{}", std::to_string(shader_id_), info_log); throw std::runtime_error("Failed to compile shader."); } - LOG_INFO("GLShader program {} linked successfully", std::to_string(m_ShaderId)); + LOG_INFO("GLShader program {} linked successfully", std::to_string(shader_id_)); } GLShader::~GLShader() { - glDeleteProgram(m_ShaderId); - for (const auto& part : m_Parts) { + glDeleteProgram(shader_id_); + for (const auto& part : parts_) { glDeleteShader(part); } } void GLShader::Bind() const { - glUseProgram(m_ShaderId); + glUseProgram(shader_id_); } void GLShader::UnBind() const { glUseProgram(0); } void GLShader::SetFloat(const std::string& uniform_name, float x) const { - GLint pos = glGetUniformLocation(m_ShaderId, uniform_name.c_str()); + GLint pos = glGetUniformLocation(shader_id_, uniform_name.c_str()); glUniform1f(pos, x); } void GLShader::SetFloat2(const std::string& uniform_name, float x, float y) const { - GLint pos = glGetUniformLocation(m_ShaderId, uniform_name.c_str()); + GLint pos = glGetUniformLocation(shader_id_, uniform_name.c_str()); glUniform2f(pos, x, y); } void GLShader::SetFloat3(const std::string& uniform_name, float x, float y, float z) const { - GLint pos = glGetUniformLocation(m_ShaderId, uniform_name.c_str()); + GLint pos = glGetUniformLocation(shader_id_, uniform_name.c_str()); glUniform3f(pos, x, y, z); } void GLShader::SetFloat4(const std::string& uniform_name, float x, float y, float z, float w) const { - GLint pos = glGetUniformLocation(m_ShaderId, uniform_name.c_str()); + GLint pos = glGetUniformLocation(shader_id_, uniform_name.c_str()); glUniform4f(pos, x, y, z, w); } void GLShader::SetFloat2(const std::string& uniform_name, Vec2 value) const { - GLint pos = glGetUniformLocation(m_ShaderId, uniform_name.c_str()); + GLint pos = glGetUniformLocation(shader_id_, uniform_name.c_str()); glUniform2f(pos, value.x, value.y); } void GLShader::SetFloat3(const std::string& uniform_name, Vec3 value) const { - GLint pos = glGetUniformLocation(m_ShaderId, uniform_name.c_str()); + GLint pos = glGetUniformLocation(shader_id_, uniform_name.c_str()); glUniform3f(pos, value.x, value.y, value.z); } void GLShader::SetFloat4(const std::string& uniform_name, Vec4 value) const { - GLint pos = glGetUniformLocation(m_ShaderId, uniform_name.c_str()); + GLint pos = glGetUniformLocation(shader_id_, uniform_name.c_str()); glUniform4f(pos, value.x, value.y, value.z, value.w); } void GLShader::SetInt(const std::string& uniform_name, int x) const { - GLint pos = glGetUniformLocation(m_ShaderId, uniform_name.c_str()); + GLint pos = glGetUniformLocation(shader_id_, uniform_name.c_str()); glUniform1i(pos, x); } void GLShader::SetInt2(const std::string& uniform_name, int x, int y) const { - GLint pos = glGetUniformLocation(m_ShaderId, uniform_name.c_str()); + GLint pos = glGetUniformLocation(shader_id_, uniform_name.c_str()); glUniform2i(pos, x, y); } void GLShader::SetInt3(const std::string& uniform_name, int x, int y, int z) const { - GLint pos = glGetUniformLocation(m_ShaderId, uniform_name.c_str()); + GLint pos = glGetUniformLocation(shader_id_, uniform_name.c_str()); glUniform3i(pos, x, y, z); } void GLShader::SetInt4(const std::string& uniform_name, int x, int y, int z, int w) const { - GLint pos = glGetUniformLocation(m_ShaderId, uniform_name.c_str()); + GLint pos = glGetUniformLocation(shader_id_, uniform_name.c_str()); glUniform4i(pos, x, y, z, w); } void GLShader::SetMat4(const std::string& uniform_name, Mat4 value) const { - GLint pos = glGetUniformLocation(m_ShaderId, uniform_name.c_str()); + GLint pos = glGetUniformLocation(shader_id_, uniform_name.c_str()); glUniformMatrix4fv(pos, 1, GL_FALSE, glm::value_ptr(value)); } void GLShader::SetUnifromBlock(const std::string& uniform_name, U32 id) const { - GLint pos = glGetUniformBlockIndex(m_ShaderId, uniform_name.c_str()); - glUniformBlockBinding(m_ShaderId, pos, id); + GLint pos = glGetUniformBlockIndex(shader_id_, uniform_name.c_str()); + glUniformBlockBinding(shader_id_, pos, id); glCheckError(); } @@ -108,7 +109,7 @@ namespace DE { std::ifstream fin(path_to_file); if (!fin.is_open()) { - LOG_ERROR("Can't open shader source file {}", RelativeToExecutable(path_to_file)); + LOG_ERROR("Can't open shader source file {}", Config::RelativeToExecutable(path_to_file)); return source_string; } try { @@ -116,33 +117,33 @@ namespace DE { source_string.append(line + "\n"); } } catch (...) { - LOG_ERROR("Failed to read shader source file {}", RelativeToExecutable(path_to_file)); + LOG_ERROR("Failed to read shader source file {}", Config::RelativeToExecutable(path_to_file)); return source_string; } return source_string; } void GLShader::AddPart(ShaderPart part) { - std::string source = ReadPartFromFile(part.path); + std::string source = ReadPartFromFile(part.Path); const char* source_c_str = source.c_str(); - GLuint shader_part = glCreateShader(ShaderPartTypeToGLShaderPartType(part.type)); - glShaderSource(shader_part, 1, &source_c_str, NULL); + GLuint shader_part = glCreateShader(ShaderPartTypeToGLShaderPartType(part.Type)); + glShaderSource(shader_part, 1, &source_c_str, nullptr); glCompileShader(shader_part); - m_Parts.push_back(shader_part); + parts_.push_back(shader_part); int success = 1; std::string info_log; - info_log.resize(Config::GetI(DE_CFG_MAX_COMPILE_ERROR_LEN)); + info_log.resize(Config::Get().MaxShaderCompileErrorLen); int len = 0; glGetShaderiv(shader_part, GL_COMPILE_STATUS, &success); - if (!success) { + if (success == GL_FALSE) { glGetShaderInfoLog(shader_part, info_log.size(), &len, info_log.data()); info_log.resize(len); - LOG_ERROR("Failed to compile shader {} due:\n{}", part.path, info_log); + LOG_ERROR("Failed to compile shader {} due:\n{}", part.Path, info_log); return; } - LOG_INFO("File {} compiled", RelativeToExecutable(part.path)); + LOG_INFO("File {} compiled", Config::RelativeToExecutable(part.Path)); - glAttachShader(m_ShaderId, shader_part); + glAttachShader(shader_id_, shader_part); } -} // namespace DE \ No newline at end of file +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Rendering/RendererOpenGL/GLShader.h b/DummyEngine/Core/Rendering/RendererOpenGL/GLShader.h index 2994918..27385db 100644 --- a/DummyEngine/Core/Rendering/RendererOpenGL/GLShader.h +++ b/DummyEngine/Core/Rendering/RendererOpenGL/GLShader.h @@ -2,15 +2,14 @@ #include -#include "DummyEngine/Core/Rendering/Renderer/RenderStructs.h" #include "DummyEngine/Core/Rendering/Renderer/Shader.h" -#include "DummyEngine/Utils/Base.h" +#include "DummyEngine/Utils/Debug/Logger.h" -namespace DE { +namespace DummyEngine { namespace fs = std::filesystem; class GLShader : public Shader { - LOGGER_AUTHOR(GLShader) + LOG_AUTHOR(GLShader) public: GLShader() = delete; GLShader(const Shader& other) = delete; @@ -18,7 +17,7 @@ namespace DE { GLShader& operator=(Shader&& other) = delete; GLShader& operator=(const Shader& other) = delete; - GLShader(const std::vector& shader_parts); + explicit GLShader(const std::vector& shader_parts); virtual ~GLShader(); virtual void Bind() const override; @@ -43,7 +42,7 @@ namespace DE { void AddPart(ShaderPart part); - std::vector m_Parts; - GLuint m_ShaderId; + std::vector parts_; + GLuint shader_id_; }; -} // namespace DE \ No newline at end of file +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Rendering/RendererOpenGL/GLTexture.cpp b/DummyEngine/Core/Rendering/RendererOpenGL/GLTexture.cpp index b3f8d92..92a06d9 100644 --- a/DummyEngine/Core/Rendering/RendererOpenGL/GLTexture.cpp +++ b/DummyEngine/Core/Rendering/RendererOpenGL/GLTexture.cpp @@ -1,15 +1,16 @@ -#include "DummyEngine/Core/Rendering/RendererOpenGL/GLTexture.h" +#include "GLTexture.h" -#include "DummyEngine/Core/Rendering/RendererOpenGL/GLFrameBuffer.h" +#include "DummyEngine/Core/Rendering/Renderer/FrameBuffer.h" #include "DummyEngine/Core/Rendering/RendererOpenGL/GLUtils.h" +#include "DummyEngine/Utils/Debug/Assert.h" -namespace DE { +namespace DummyEngine { GLTexture::GLTexture(uint32_t width, uint32_t height, Texture::Channels channels, Texture::Format format, bool depth_buffer) : - m_Width(0), m_Height(0), m_Format(format), m_Channels(channels) { - glGenTextures(1, &m_TextureId); + width_(0), height_(0), format_(format), channels_(channels) { + glGenTextures(1, &texture_id_); glActiveTexture(GL_TEXTURE0); - glBindTexture(GL_TEXTURE_2D, m_TextureId); + glBindTexture(GL_TEXTURE_2D, texture_id_); // TODO: Move tex parameters somewhere else... if (!depth_buffer) { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); @@ -18,21 +19,21 @@ namespace DE { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); } else { - glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, width, height, 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL); + glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, width, height, 0, GL_DEPTH_COMPONENT, GL_FLOAT, nullptr); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER); - float borderColor[] = {1.0f, 1.0f, 1.0f, 1.0f}; - glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, borderColor); + float border_color[] = {1.0f, 1.0f, 1.0f, 1.0f}; + glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, border_color); } Resize(width, height); } - GLTexture::GLTexture(Texture::Channels channels, Texture::Format format) : m_Width(0), m_Height(0), m_Format(format), m_Channels(channels) { - glGenTextures(1, &m_TextureId); + GLTexture::GLTexture(Texture::Channels channels, Texture::Format format) : width_(0), height_(0), format_(format), channels_(channels) { + glGenTextures(1, &texture_id_); glActiveTexture(GL_TEXTURE0); - glBindTexture(GL_TEXTURE_2D, m_TextureId); + glBindTexture(GL_TEXTURE_2D, texture_id_); // TODO: Move tex parameters somewhere else... glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); @@ -41,13 +42,10 @@ namespace DE { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); } GLTexture::GLTexture(const TextureData& data) : - m_Width(data.Width()), - m_Height(data.Height()), - m_Format(Texture::DataFormat(data.Format())), - m_Channels(Texture::DataChannels(data.Channels())) { - glGenTextures(1, &m_TextureId); + width_(data.Width()), height_(data.Height()), format_(Texture::DataFormat(data.Format())), channels_(Texture::DataChannels(data.Channels())) { + glGenTextures(1, &texture_id_); glActiveTexture(GL_TEXTURE0); - glBindTexture(GL_TEXTURE_2D, m_TextureId); + glBindTexture(GL_TEXTURE_2D, texture_id_); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); @@ -59,78 +57,71 @@ namespace DE { } GLTexture::~GLTexture() { - glDeleteTextures(1, &m_TextureId); + glDeleteTextures(1, &texture_id_); } U32 GLTexture::GetWidth() const { - return m_Width; + return width_; } U32 GLTexture::GetHeight() const { - return m_Height; + return height_; } U32 GLTexture::GetRendererId() const { - return m_TextureId; + return texture_id_; } Texture::Format GLTexture::GetFormat() const { - return m_Format; + return format_; } Texture::Channels GLTexture::GetChannels() const { - return m_Channels; + return channels_; } void GLTexture::Copy(Ref buffer, U32 attachment_id) { GLTexture* source = reinterpret_cast(buffer->GetColorAttachment(attachment_id).get()); - m_Height = source->m_Height; - m_Width = source->m_Width; - m_Format = source->m_Format; - m_Channels = source->m_Channels; + height_ = source->height_; + width_ = source->width_; + format_ = source->format_; + channels_ = source->channels_; Invalidate(); buffer->Bind(); glReadBuffer(GL_COLOR_ATTACHMENT0 + attachment_id); glActiveTexture(GL_TEXTURE0); - glBindTexture(GL_TEXTURE_2D, m_TextureId); - glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, m_Width, m_Height); + glBindTexture(GL_TEXTURE_2D, texture_id_); + glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, width_, height_); } void GLTexture::SetFormat(Format format) { - if (m_Format != format) { - m_Format = format; + if (format_ != format) { + format_ = format; Invalidate(); } } void GLTexture::SetChannels(Channels channels) { - if (m_Channels != channels) { - m_Channels = channels; + if (channels_ != channels) { + channels_ = channels; Invalidate(); } } void GLTexture::Resize(U32 width, U32 height) { DE_ASSERT(width * height > 0, "Cannot resize texture to size 0"); - if (m_Width != width || m_Height != height) { - m_Width = width; - m_Height = height; + if (width_ != width || height_ != height) { + width_ = width; + height_ = height; Invalidate(); } } void GLTexture::Bind(U32 unit_id) const { DE_ASSERT(unit_id > 0, "Cannot bind to texture slot 0, because it's reserved by engine"); glActiveTexture(GL_TEXTURE0 + unit_id); - glBindTexture(GL_TEXTURE_2D, m_TextureId); + glBindTexture(GL_TEXTURE_2D, texture_id_); } void GLTexture::Invalidate(GLenum data_type, const void* data) { glActiveTexture(GL_TEXTURE0); - glBindTexture(GL_TEXTURE_2D, m_TextureId); - glTexImage2D(GL_TEXTURE_2D, - 0, - GLTextureFormatInternal(m_Format, m_Channels), - m_Width, - m_Height, - 0, - GLTextureFormatExternal(m_Channels), - data_type, - data); + glBindTexture(GL_TEXTURE_2D, texture_id_); + glTexImage2D( + GL_TEXTURE_2D, 0, GLTextureFormatInternal(format_, channels_), width_, height_, 0, GLTextureFormatExternal(channels_), data_type, data); // glGenerateMipmap(GL_TEXTURE_2D); } -} // namespace DE +} // namespace DummyEngine diff --git a/DummyEngine/Core/Rendering/RendererOpenGL/GLTexture.h b/DummyEngine/Core/Rendering/RendererOpenGL/GLTexture.h index b426fd5..42c15e1 100644 --- a/DummyEngine/Core/Rendering/RendererOpenGL/GLTexture.h +++ b/DummyEngine/Core/Rendering/RendererOpenGL/GLTexture.h @@ -3,9 +3,8 @@ #include #include "DummyEngine/Core/Rendering/Renderer/Texture.h" -#include "DummyEngine/Utils/Base.h" -namespace DE { +namespace DummyEngine { class GLTexture : public Texture { public: @@ -17,7 +16,7 @@ namespace DE { GLTexture(U32 width, U32 height, Channels channels, Format format, bool depth_buffer); GLTexture(Texture::Channels channels, Format format); - GLTexture(const TextureData& data); + explicit GLTexture(const TextureData& data); virtual ~GLTexture(); @@ -38,56 +37,11 @@ namespace DE { friend class GLFrameBuffer; - GLuint m_TextureId; - U32 m_Width; - U32 m_Height; - Format m_Format; - Channels m_Channels; + GLuint texture_id_; + U32 width_; + U32 height_; + Format format_; + Channels channels_; }; - // class GLTexture - // { - // public: - // void SetData(const Texture2DData& data); - // void BindToUnit(unsigned int unit_id) const; - - // GLTexture(); - // GLTexture(const GLTexture& other); - // GLTexture(GLTexture&& other); - // GLTexture& operator=(const GLTexture& other); - // GLTexture& operator=(GLTexture&& other); - // ~GLTexture(); - - // private: - // friend class Initializer; - - // class Texture2DManager - // { - // private: - // bool _initialized; - // std::unordered_map _reference_count; - - // Texture2DManager(); - - // unsigned int ICreateTexture2D(); - // unsigned int ICreateInstance(unsigned int texture_id); - // void IDestroyInstance(unsigned int texture_id); - // void IDestroyTexture2D(unsigned int texture_id); - - // static Texture2DManager& Get(); - - // public: - // static void Initialize(); - // static void Terminate(); - - // static unsigned int CreateTexture2D(); - // static unsigned int CreateInstance(unsigned int texture_id); - // static void DestroyInstance(unsigned int texture_id); - // static void DestroyTexture2D(unsigned int texture_id); - // }; - - // GLint Texture2DFormatToGLenum(Texture2DFormat format) const; - - // unsigned int m_TextureId; - // }; -} // namespace DE \ No newline at end of file +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Rendering/RendererOpenGL/GLUniformBuffer.cpp b/DummyEngine/Core/Rendering/RendererOpenGL/GLUniformBuffer.cpp index 8608146..e3dfcca 100644 --- a/DummyEngine/Core/Rendering/RendererOpenGL/GLUniformBuffer.cpp +++ b/DummyEngine/Core/Rendering/RendererOpenGL/GLUniformBuffer.cpp @@ -1,32 +1,33 @@ -#include "DummyEngine/Core/Rendering/RendererOpenGL/GLUniformBuffer.h" +#include "GLUniformBuffer.h" -namespace DE { - GLUniformBuffer::GLUniformBuffer(const BufferLayout& layout, U32 size) : m_Layout(layout) { - m_Layout.SetLayoutType(BufferLayoutType::Uniform); - m_Size = size * m_Layout.GetStride(); +namespace DummyEngine { - m_LocalBuffer.Allocate(m_Layout, size); + GLUniformBuffer::GLUniformBuffer(const BufferLayout& layout, U32 size) : layout_(layout) { + layout_.SetLayoutType(BufferLayoutType::Uniform); + size_ = size * layout_.GetStride(); - glGenBuffers(1, &m_BufferId); - glBindBuffer(GL_UNIFORM_BUFFER, m_BufferId); - glBufferData(GL_UNIFORM_BUFFER, m_Size, nullptr, GL_DYNAMIC_DRAW); + local_buffer_.Allocate(layout_, size); + + glGenBuffers(1, &buffer_id_); + glBindBuffer(GL_UNIFORM_BUFFER, buffer_id_); + glBufferData(GL_UNIFORM_BUFFER, size_, nullptr, GL_DYNAMIC_DRAW); } GLUniformBuffer::~GLUniformBuffer() { - glDeleteBuffers(1, &m_BufferId); + glDeleteBuffers(1, &buffer_id_); } void GLUniformBuffer::Bind(uint32_t index) const { - glBindBufferBase(GL_UNIFORM_BUFFER, index, m_BufferId); + glBindBufferBase(GL_UNIFORM_BUFFER, index, buffer_id_); } - LocalBufferNode GLUniformBuffer::at(uint32_t index) { - return m_LocalBuffer.at(index); + LocalBufferNode GLUniformBuffer::At(uint32_t index) { + return local_buffer_.At(index); } void GLUniformBuffer::PushData() const { - glBindBuffer(GL_UNIFORM_BUFFER, m_BufferId); - glBufferSubData(GL_UNIFORM_BUFFER, 0, m_Size, m_LocalBuffer.m_Data); + glBindBuffer(GL_UNIFORM_BUFFER, buffer_id_); + glBufferSubData(GL_UNIFORM_BUFFER, 0, size_, local_buffer_.data_); } const BufferLayout& GLUniformBuffer::GetLayout() const { - return m_Layout; + return layout_; } -} // namespace DE \ No newline at end of file +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Rendering/RendererOpenGL/GLUniformBuffer.h b/DummyEngine/Core/Rendering/RendererOpenGL/GLUniformBuffer.h index fa8fac6..b8f526e 100644 --- a/DummyEngine/Core/Rendering/RendererOpenGL/GLUniformBuffer.h +++ b/DummyEngine/Core/Rendering/RendererOpenGL/GLUniformBuffer.h @@ -1,10 +1,10 @@ #pragma once -#include - #include "DummyEngine/Core/Rendering/Renderer/UniformBuffer.h" -namespace DE { +#include + +namespace DummyEngine { class GLUniformBuffer : public UniformBuffer { public: GLUniformBuffer(const BufferLayout& layout, U32 size); @@ -16,15 +16,15 @@ namespace DE { GLUniformBuffer& operator=(const GLUniformBuffer& other) = delete; GLUniformBuffer& operator=(GLUniformBuffer&& other) = delete; - virtual void Bind(U32 index) const; - virtual LocalBufferNode at(U32 index); - virtual void PushData() const; - virtual const BufferLayout& GetLayout() const; + virtual void Bind(U32 index) const override; + virtual LocalBufferNode At(U32 index) override; + virtual void PushData() const override; + virtual const BufferLayout& GetLayout() const override; private: - GLuint m_BufferId; - LocalBuffer m_LocalBuffer; - BufferLayout m_Layout; - U32 m_Size; + GLuint buffer_id_; + LocalBuffer local_buffer_; + BufferLayout layout_; + U32 size_; }; -} // namespace DE \ No newline at end of file +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Rendering/RendererOpenGL/GLUtils.cpp b/DummyEngine/Core/Rendering/RendererOpenGL/GLUtils.cpp index c1ccd52..6fc2e5a 100644 --- a/DummyEngine/Core/Rendering/RendererOpenGL/GLUtils.cpp +++ b/DummyEngine/Core/Rendering/RendererOpenGL/GLUtils.cpp @@ -1,8 +1,10 @@ -#include "DummyEngine/Core/Rendering/RendererOpenGL/GLUtils.h" +#include "GLUtils.h" #include "DummyEngine/Core/Rendering/Renderer/RenderAPI.h" +#include "DummyEngine/Utils/Debug/Assert.h" + +namespace DummyEngine { -namespace DE { GLenum GLTextureFormatInternal(Texture::Format format, Texture::Channels channels) { if (format == Texture::Format::U8 && channels == Texture::Channels::R) return GL_R8; if (format == Texture::Format::U8 && channels == Texture::Channels::RG) return GL_RG8; @@ -59,4 +61,5 @@ namespace DE { } return 0; } -} // namespace DE \ No newline at end of file + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Rendering/RendererOpenGL/GLUtils.h b/DummyEngine/Core/Rendering/RendererOpenGL/GLUtils.h index 5421e5c..765f313 100644 --- a/DummyEngine/Core/Rendering/RendererOpenGL/GLUtils.h +++ b/DummyEngine/Core/Rendering/RendererOpenGL/GLUtils.h @@ -1,18 +1,20 @@ #pragma once -#include - #include "DummyEngine/Core/Rendering/Renderer/Texture.h" -#include "DummyEngine/Core/Rendering/RendererOpenGL/GLDebug.h" +#include "DummyEngine/Core/Rendering/RendererOpenGL/GLDebug.h" // IWYU pragma: export #include "DummyEngine/Core/ResourceManaging/RawData.h" -namespace DE { +#include + #define GL_STRING(name) reinterpret_cast(glGetString(name)) +namespace DummyEngine { + enum class RenderPrimitive; GLenum GLTextureFormatInternal(Texture::Format format, Texture::Channels channels); GLenum GLTextureFormatExternal(Texture::Channels format); GLenum GLDataType(TextureFormat format); GLenum RenderPrimitiveToGL(RenderPrimitive primitive); -} // namespace DE \ No newline at end of file + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Rendering/RendererOpenGL/GLVertexArray.cpp b/DummyEngine/Core/Rendering/RendererOpenGL/GLVertexArray.cpp index 9d20590..03b166a 100644 --- a/DummyEngine/Core/Rendering/RendererOpenGL/GLVertexArray.cpp +++ b/DummyEngine/Core/Rendering/RendererOpenGL/GLVertexArray.cpp @@ -1,41 +1,41 @@ -#include "DummyEngine/Core/Rendering/RendererOpenGL/GLVertexArray.h" +#include "GLVertexArray.h" -namespace DE { +namespace DummyEngine { - GLVertexArray::GLVertexArray() : m_CurrentAtributeId(0) { - glGenVertexArrays(1, &m_ArrayId); + GLVertexArray::GLVertexArray() : current_attribute_id_(0) { + glGenVertexArrays(1, &array_id_); } GLVertexArray::~GLVertexArray() { - glDeleteVertexArrays(1, &m_ArrayId); + glDeleteVertexArrays(1, &array_id_); } void GLVertexArray::Bind() const { - glBindVertexArray(m_ArrayId); + glBindVertexArray(array_id_); } void GLVertexArray::UnBind() const { glBindVertexArray(0); } void GLVertexArray::AddVertexBuffer(const Ref& vertex_buffer) { - glBindVertexArray(m_ArrayId); + glBindVertexArray(array_id_); vertex_buffer->Bind(); const auto& layout = vertex_buffer->GetLayout(); for (const auto& element : layout) { - switch (element.type) { + switch (element.Type) { case BufferElementType::Float: case BufferElementType::Float2: case BufferElementType::Float3: case BufferElementType::Float4: { - glEnableVertexAttribArray(m_CurrentAtributeId); - glVertexAttribPointer(m_CurrentAtributeId, + glEnableVertexAttribArray(current_attribute_id_); + glVertexAttribPointer(current_attribute_id_, element.ComponentCount(), GL_FLOAT, - element.normalized ? GL_TRUE : GL_FALSE, + element.Normalized ? GL_TRUE : GL_FALSE, layout.GetStride(), - (void*)element.offset); - glVertexAttribDivisor(m_CurrentAtributeId, layout.GetDivisor()); - ++m_CurrentAtributeId; + (void*)element.Offset); + glVertexAttribDivisor(current_attribute_id_, layout.GetDivisor()); + ++current_attribute_id_; break; } @@ -43,44 +43,44 @@ namespace DE { case BufferElementType::Int2: case BufferElementType::Int3: case BufferElementType::Int4: { - glEnableVertexAttribArray(m_CurrentAtributeId); - glVertexAttribIPointer(m_CurrentAtributeId, element.ComponentCount(), GL_INT, layout.GetStride(), (void*)element.offset); - glVertexAttribDivisor(m_CurrentAtributeId, layout.GetDivisor()); - ++m_CurrentAtributeId; + glEnableVertexAttribArray(current_attribute_id_); + glVertexAttribIPointer(current_attribute_id_, element.ComponentCount(), GL_INT, layout.GetStride(), (void*)element.Offset); + glVertexAttribDivisor(current_attribute_id_, layout.GetDivisor()); + ++current_attribute_id_; break; } case BufferElementType::Mat4: { U32 count = element.ComponentCount(); for (U8 i = 0; i < count; ++i) { - glEnableVertexAttribArray(m_CurrentAtributeId); - glVertexAttribPointer(m_CurrentAtributeId, + glEnableVertexAttribArray(current_attribute_id_); + glVertexAttribPointer(current_attribute_id_, count, GL_FLOAT, - element.normalized ? GL_TRUE : GL_FALSE, + element.Normalized ? GL_TRUE : GL_FALSE, layout.GetStride(), - (void*)(element.offset + sizeof(float) * count * i)); - glVertexAttribDivisor(m_CurrentAtributeId, layout.GetDivisor()); - ++m_CurrentAtributeId; + (void*)(element.Offset + sizeof(float) * count * i)); + glVertexAttribDivisor(current_attribute_id_, layout.GetDivisor()); + ++current_attribute_id_; } break; } default: break; } } - m_VertexBuffers.push_back(vertex_buffer); + vertex_buffers_.push_back(vertex_buffer); } void GLVertexArray::SetIndexBuffer(const Ref& index_buffer) { - glBindVertexArray(m_ArrayId); + glBindVertexArray(array_id_); index_buffer->Bind(); - m_IndexBuffer = index_buffer; + index_buffer_ = index_buffer; } const std::vector>& GLVertexArray::GetVertexBuffers() const { - return m_VertexBuffers; + return vertex_buffers_; } const Ref& GLVertexArray::GetIndexBuffer() const { - return m_IndexBuffer; + return index_buffer_; } -} // namespace DE \ No newline at end of file +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Rendering/RendererOpenGL/GLVertexArray.h b/DummyEngine/Core/Rendering/RendererOpenGL/GLVertexArray.h index d5cefb2..cda3dff 100644 --- a/DummyEngine/Core/Rendering/RendererOpenGL/GLVertexArray.h +++ b/DummyEngine/Core/Rendering/RendererOpenGL/GLVertexArray.h @@ -1,10 +1,11 @@ #pragma once -#include #include "DummyEngine/Core/Rendering/Renderer/VertexArray.h" -#include "DummyEngine/Utils/Base.h" -namespace DE { +#include + +namespace DummyEngine { + class GLVertexArray : public VertexArray { public: GLVertexArray(); @@ -21,10 +22,11 @@ namespace DE { virtual const Ref& GetIndexBuffer() const override; private: - std::vector> m_VertexBuffers; - Ref m_IndexBuffer; + std::vector> vertex_buffers_; + Ref index_buffer_; - GLuint m_ArrayId; - U32 m_CurrentAtributeId; + GLuint array_id_; + U32 current_attribute_id_; }; -} // namespace DE \ No newline at end of file + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Rendering/RendererOpenGL/GLVertexBuffer.cpp b/DummyEngine/Core/Rendering/RendererOpenGL/GLVertexBuffer.cpp index 47c8416..70402fe 100644 --- a/DummyEngine/Core/Rendering/RendererOpenGL/GLVertexBuffer.cpp +++ b/DummyEngine/Core/Rendering/RendererOpenGL/GLVertexBuffer.cpp @@ -1,8 +1,11 @@ -#include "DummyEngine/Core/Rendering/RendererOpenGL/GLVertexBuffer.h" +#include "GLVertexBuffer.h" + +#include "DummyEngine/Utils/Debug/Assert.h" + +namespace DummyEngine { -namespace DE { void GLVertexBuffer::Bind() const { - glBindBuffer(GL_ARRAY_BUFFER, m_BufferId); + glBindBuffer(GL_ARRAY_BUFFER, buffer_id_); } void GLVertexBuffer::UnBind() const { glBindBuffer(GL_ARRAY_BUFFER, 0); @@ -10,57 +13,57 @@ namespace DE { // TODO: Think about not creating LocalBuffer if BufferUsage is Static. - GLVertexBuffer::GLVertexBuffer(const BufferLayout& layout, U32 size, BufferUsage usage) : m_Usage(usage), m_Layout(layout) { - m_Layout.SetLayoutType(BufferLayoutType::Vertex); - m_Size = (size * m_Layout.GetStride()); + GLVertexBuffer::GLVertexBuffer(const BufferLayout& layout, U32 size, BufferUsage usage) : usage_(usage), layout_(layout) { + layout_.SetLayoutType(BufferLayoutType::Vertex); + size_ = (size * layout_.GetStride()); - if (m_Usage == BufferUsage::Dynamic) { - m_LocalBuffer.Allocate(m_Layout, size); + if (usage_ == BufferUsage::Dynamic) { + local_buffer_.Allocate(layout_, size); } - glGenBuffers(1, &m_BufferId); - glBindBuffer(GL_ARRAY_BUFFER, m_BufferId); - glBufferData(GL_ARRAY_BUFFER, m_Size, nullptr, BufferUsafeToGLBufferUsage(usage)); + glGenBuffers(1, &buffer_id_); + glBindBuffer(GL_ARRAY_BUFFER, buffer_id_); + glBufferData(GL_ARRAY_BUFFER, size_, nullptr, BufferUsafeToGLBufferUsage(usage)); } - GLVertexBuffer::GLVertexBuffer(const BufferLayout& layout, U32 size, const void* data, BufferUsage usage) : m_Usage(usage), m_Layout(layout) { - m_Layout.SetLayoutType(BufferLayoutType::Vertex); - m_Size = (size * m_Layout.GetStride()); + GLVertexBuffer::GLVertexBuffer(const BufferLayout& layout, U32 size, const void* data, BufferUsage usage) : usage_(usage), layout_(layout) { + layout_.SetLayoutType(BufferLayoutType::Vertex); + size_ = (size * layout_.GetStride()); - if (m_Usage == BufferUsage::Dynamic) { - m_LocalBuffer.Allocate(m_Layout, size); - m_LocalBuffer.SetData(data, m_Size); + if (usage_ == BufferUsage::Dynamic) { + local_buffer_.Allocate(layout_, size); + local_buffer_.SetData(data, size_); } - glGenBuffers(1, &m_BufferId); - glBindBuffer(GL_ARRAY_BUFFER, m_BufferId); - glBufferData(GL_ARRAY_BUFFER, m_Size, data, BufferUsafeToGLBufferUsage(usage)); + glGenBuffers(1, &buffer_id_); + glBindBuffer(GL_ARRAY_BUFFER, buffer_id_); + glBufferData(GL_ARRAY_BUFFER, size_, data, BufferUsafeToGLBufferUsage(usage)); } GLVertexBuffer::~GLVertexBuffer() { - glDeleteBuffers(1, &m_BufferId); + glDeleteBuffers(1, &buffer_id_); } const BufferLayout& GLVertexBuffer::GetLayout() const { - return m_Layout; + return layout_; } - LocalBufferNode GLVertexBuffer::at(U32 index) { - DE_ASSERT(m_Usage == BufferUsage::Dynamic, "Using at function on non-dynamic-usage vertex_buffer"); - return m_LocalBuffer.at(index); + LocalBufferNode GLVertexBuffer::At(U32 index) { + DE_ASSERT(usage_ == BufferUsage::Dynamic, "Using at function on non-dynamic-usage vertex_buffer"); + return local_buffer_.At(index); } void GLVertexBuffer::SetData(const void* data, U32 size) { - if (m_Usage == BufferUsage::Dynamic) { - m_LocalBuffer.SetData(data, size); + if (usage_ == BufferUsage::Dynamic) { + local_buffer_.SetData(data, size); } else { - DE_ASSERT(m_Size == size, "Invalid data size {} expected {}", size, m_Size); + DE_ASSERT(size_ == size, "Invalid data size {} expected {}", size, size_); - glBindBuffer(GL_ARRAY_BUFFER, m_BufferId); + glBindBuffer(GL_ARRAY_BUFFER, buffer_id_); glBufferSubData(GL_ARRAY_BUFFER, 0, size, data); } } void GLVertexBuffer::PushData() { - DE_ASSERT(m_Usage == BufferUsage::Dynamic, "Using PushData function on non-dynamic-usage vertex_buffer. Use SetData instead"); + DE_ASSERT(usage_ == BufferUsage::Dynamic, "Using PushData function on non-dynamic-usage vertex_buffer. Use SetData instead"); - glBindBuffer(GL_ARRAY_BUFFER, m_BufferId); - glBufferSubData(GL_ARRAY_BUFFER, 0, m_LocalBuffer.m_Size, m_LocalBuffer.m_Data); + glBindBuffer(GL_ARRAY_BUFFER, buffer_id_); + glBufferSubData(GL_ARRAY_BUFFER, 0, local_buffer_.size_, local_buffer_.data_); } GLenum GLVertexBuffer::BufferUsafeToGLBufferUsage(BufferUsage usage) { @@ -71,29 +74,29 @@ namespace DE { } } U32 GLVertexBuffer::Size() const { - return m_Size / m_Layout.GetStride(); + return size_ / layout_.GetStride(); } //*---------------------------------------------------------------------------------- - GLIndexBuffer::GLIndexBuffer(const U32* indices, U32 indices_amount) : _indices_amount(indices_amount) { - glGenBuffers(1, &m_BufferId); - glBindBuffer(GL_ARRAY_BUFFER, m_BufferId); + GLIndexBuffer::GLIndexBuffer(const U32* indices, U32 indices_amount) : indices_amount_(indices_amount) { + glGenBuffers(1, &buffer_id_); + glBindBuffer(GL_ARRAY_BUFFER, buffer_id_); glBufferData(GL_ARRAY_BUFFER, indices_amount * sizeof(U32), indices, GL_STATIC_DRAW); } GLIndexBuffer::~GLIndexBuffer() { - glDeleteBuffers(1, &m_BufferId); + glDeleteBuffers(1, &buffer_id_); } void GLIndexBuffer::Bind() const { - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_BufferId); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffer_id_); } void GLIndexBuffer::UnBind() const { glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); } U32 GLIndexBuffer::IndicesAmount() const { - return _indices_amount; + return indices_amount_; } -} // namespace DE \ No newline at end of file +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Rendering/RendererOpenGL/GLVertexBuffer.h b/DummyEngine/Core/Rendering/RendererOpenGL/GLVertexBuffer.h index 5542a15..55ae61a 100644 --- a/DummyEngine/Core/Rendering/RendererOpenGL/GLVertexBuffer.h +++ b/DummyEngine/Core/Rendering/RendererOpenGL/GLVertexBuffer.h @@ -1,11 +1,10 @@ #pragma once -#include - #include "DummyEngine/Core/Rendering/Renderer/VertexBuffer.h" -#include "DummyEngine/Utils/Base.h" -namespace DE { +#include + +namespace DummyEngine { class GLVertexBuffer : public VertexBuffer { public: @@ -23,7 +22,7 @@ namespace DE { virtual void Bind() const override; virtual void UnBind() const override; - virtual LocalBufferNode at(U32 index) override; + virtual LocalBufferNode At(U32 index) override; virtual void SetData(const void* data, U32 size) override; virtual void PushData() override; @@ -34,11 +33,11 @@ namespace DE { private: static GLenum BufferUsafeToGLBufferUsage(BufferUsage usage); - BufferUsage m_Usage; - LocalBuffer m_LocalBuffer; - BufferLayout m_Layout; - GLuint m_BufferId; - U32 m_Size; + BufferUsage usage_; + LocalBuffer local_buffer_; + BufferLayout layout_; + GLuint buffer_id_; + U32 size_; }; class GLIndexBuffer : public IndexBuffer { @@ -58,7 +57,7 @@ namespace DE { virtual U32 IndicesAmount() const override; private: - GLuint m_BufferId; - U32 _indices_amount; + GLuint buffer_id_; + U32 indices_amount_; }; -} // namespace DE \ No newline at end of file +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/ResourceManaging/AssetManager.cpp b/DummyEngine/Core/ResourceManaging/AssetManager.cpp index dac8d50..96e2ef7 100644 --- a/DummyEngine/Core/ResourceManaging/AssetManager.cpp +++ b/DummyEngine/Core/ResourceManaging/AssetManager.cpp @@ -1,6 +1,7 @@ #include "DummyEngine/Core/ResourceManaging/AssetManager.h" -namespace DE { +namespace DummyEngine { + SINGLETON_BASE(AssetManager); S_INITIALIZE() { return Unit(); @@ -10,90 +11,90 @@ namespace DE { } S_METHOD_IMPL(bool, AddScriptAsset, (const ScriptAsset& asset), (asset)) { - if (m_Scripts.contains(asset.id)) { + if (scripts_.contains(asset.ID)) { return false; } - m_Scripts[asset.id] = asset; - LOG_INFO("Added ScriptAsset({}|{})", asset.name, asset.id); + scripts_[asset.ID] = asset; + LOG_INFO("Added ScriptAsset({}|{})", asset.Name, asset.ID); return true; } S_METHOD_IMPL(bool, AddTextureAsset, (const TextureAsset& asset), (asset)) { - if (m_Textures.contains(asset.id)) { + if (textures_.contains(asset.ID)) { return false; } - m_Textures[asset.id] = asset; - LOG_INFO("Added TextureAsset({}|{})", asset.name, asset.id); + textures_[asset.ID] = asset; + LOG_INFO("Added TextureAsset({}|{})", asset.Name, asset.ID); return true; } S_METHOD_IMPL(bool, AddShaderAsset, (const ShaderAsset& asset), (asset)) { - if (m_Shaders.contains(asset.id)) { + if (shaders_.contains(asset.ID)) { return false; } - m_Shaders[asset.id] = asset; - LOG_INFO("Added ShaderAsset({}|{})", asset.name, asset.id); + shaders_[asset.ID] = asset; + LOG_INFO("Added ShaderAsset({}|{})", asset.Name, asset.ID); return true; } S_METHOD_IMPL(bool, AddRenderMeshAsset, (const RenderMeshAsset& asset), (asset)) { - if (m_RenderMeshes.contains(asset.id)) { + if (render_meshes_.contains(asset.ID)) { return false; } - m_RenderMeshes[asset.id] = asset; - LOG_INFO("Added RenderMeshAsset({}|{})", asset.name, asset.id); + render_meshes_[asset.ID] = asset; + LOG_INFO("Added RenderMeshAsset({}|{})", asset.Name, asset.ID); return true; } S_METHOD_IMPL(std::optional, GetScriptAsset, (UUID id), (id)) { - if (!m_Scripts.contains(id)) { + if (!scripts_.contains(id)) { return {}; } - return m_Scripts[id]; + return scripts_[id]; } S_METHOD_IMPL(std::optional, GetTextureAsset, (UUID id), (id)) { - if (!m_Textures.contains(id)) { + if (!textures_.contains(id)) { return {}; } - return m_Textures[id]; + return textures_[id]; } S_METHOD_IMPL(std::optional, GetShaderAsset, (UUID id), (id)) { - if (!m_Shaders.contains(id)) { + if (!shaders_.contains(id)) { return {}; } - return m_Shaders[id]; + return shaders_[id]; } S_METHOD_IMPL(std::optional, GetRenderMeshAsset, (UUID id), (id)) { - if (!m_RenderMeshes.contains(id)) { + if (!render_meshes_.contains(id)) { return {}; } - return m_RenderMeshes[id]; + return render_meshes_[id]; } S_METHOD_IMPL(bool, RemoveScriptAsset, (UUID id), (id)) { - if (m_Scripts.contains(id)) { - m_Scripts.erase(id); + if (scripts_.contains(id)) { + scripts_.erase(id); LOG_INFO("Remove ScriptAsset({})", id); return true; } return false; } S_METHOD_IMPL(bool, RemoveTextureAsset, (UUID id), (id)) { - if (m_Textures.contains(id)) { - m_Textures.erase(id); + if (textures_.contains(id)) { + textures_.erase(id); LOG_INFO("Remove TextureAsset({})", id); return true; } return false; } S_METHOD_IMPL(bool, RemoveShaderAsset, (UUID id), (id)) { - if (m_Shaders.contains(id)) { - m_Shaders.erase(id); + if (shaders_.contains(id)) { + shaders_.erase(id); LOG_INFO("Remove ShaderAsset({})", id); return true; } return false; } S_METHOD_IMPL(bool, RemoveRenderMeshAsset, (UUID id), (id)) { - if (m_RenderMeshes.contains(id)) { - m_RenderMeshes.erase(id); + if (render_meshes_.contains(id)) { + render_meshes_.erase(id); LOG_INFO("Remove RenderMeshAsset({})", id); return true; } @@ -101,11 +102,11 @@ namespace DE { } S_METHOD_IMPL(Unit, Clear, (), ()) { - m_RenderMeshes.clear(); - m_Textures.clear(); - m_Shaders.clear(); - m_Scripts.clear(); + render_meshes_.clear(); + textures_.clear(); + shaders_.clear(); + scripts_.clear(); return Unit(); } -} // namespace DE \ No newline at end of file +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/ResourceManaging/AssetManager.h b/DummyEngine/Core/ResourceManaging/AssetManager.h index ba59731..7ad9f23 100644 --- a/DummyEngine/Core/ResourceManaging/AssetManager.h +++ b/DummyEngine/Core/ResourceManaging/AssetManager.h @@ -1,11 +1,13 @@ #pragma once #include "DummyEngine/Core/ResourceManaging/Assets.h" -#include "DummyEngine/Utils/Base.h" +#include "DummyEngine/Utils/Debug/Logger.h" +#include "DummyEngine/Utils/Helpers/Singleton.h" + +namespace DummyEngine { -namespace DE { class AssetManager : public Singleton { - LOGGER_AUTHOR(AssetManager) + LOG_AUTHOR(AssetManager) SINGLETON(AssetManager) public: S_METHOD_DEF(bool, AddScriptAsset, (const ScriptAsset& asset)); @@ -26,9 +28,10 @@ namespace DE { S_METHOD_DEF(Unit, Clear, ()); private: - std::unordered_map m_RenderMeshes; - std::unordered_map m_Textures; - std::unordered_map m_Shaders; - std::unordered_map m_Scripts; + std::unordered_map render_meshes_; + std::unordered_map textures_; + std::unordered_map shaders_; + std::unordered_map scripts_; }; -} // namespace DE \ No newline at end of file + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/ResourceManaging/Assets.h b/DummyEngine/Core/ResourceManaging/Assets.h index 5b59d4a..f405b75 100644 --- a/DummyEngine/Core/ResourceManaging/Assets.h +++ b/DummyEngine/Core/ResourceManaging/Assets.h @@ -1,37 +1,40 @@ #pragma once #include "DummyEngine/Core/ResourceManaging/RawData.h" -#include "DummyEngine/Utils/Base.h" +#include "DummyEngine/Utils/Types/UUID.h" + +namespace DummyEngine { -namespace DE { struct TextureAsset { struct LoadingProperties { - Path path; - bool flip_uvs = true; - TextureFormat format = TextureFormat::U8; + Path Path; + bool FlipUV = true; + TextureFormat Format = TextureFormat::U8; }; - UUID id; - std::string name; - LoadingProperties loading_props; + + UUID ID; + std::string Name; + LoadingProperties LoadingProps; }; struct RenderMeshAsset { struct LoadingProperties { - Path path; - bool flip_uvs; - bool compress; + Path Path; + bool FlipUV; + bool Compress; }; - LoadingProperties loading_props; - UUID id; - std::string name; + LoadingProperties LoadingProps; + UUID ID; + std::string Name; }; struct ShaderAsset { - UUID id; - std::string name; - std::vector parts; + UUID ID; + std::string Name; + std::vector Parts; }; struct ScriptAsset { - UUID id; - std::string name; - Path path; + UUID ID; + std::string Name; + Path Path; }; -} // namespace DE \ No newline at end of file + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/ResourceManaging/HandleManager.h b/DummyEngine/Core/ResourceManaging/HandleManager.h deleted file mode 100644 index 84d19d0..0000000 --- a/DummyEngine/Core/ResourceManaging/HandleManager.h +++ /dev/null @@ -1,174 +0,0 @@ -#pragma once - -#include "DummyEngine/Utils/Base.h" - -namespace DE { - template class HandleManager; - template class Handle { - public: - T& operator*(); - const T& operator*() const; - T* operator->(); - const T* operator->() const; - bool Valid() const; - void Destroy(); - //! Temporary - U32 GetId() const { return m_ID; } - - private: - friend class HandleManager; - HandleManager* m_Manager = nullptr; - U32 m_ID = 0; - U32 m_Gen = 0; - }; - - template class HandleManager { - public: - class Iterator { - public: - bool operator==(const Iterator& other) const; - bool operator!=(const Iterator& other) const; - - Iterator& operator++(); - Iterator operator++(int); - Iterator& operator--(); - Iterator operator--(int); - T& operator*(); - T* operator->(); - U32 ID() const; - - private: - friend class HandleManager; - Iterator(HandleManager* manager, U32 id); - - HandleManager* m_Manager = nullptr; - U32 m_ID = 0; - }; - - Iterator begin(); - Iterator end(); - - Handle CreateHandle(); - void Destroy(U32 id); - void Clear(); - - private: - friend class Handle; - void GenId(); - - struct Instance { - T instance; - U32 gen = 0; - bool valid = false; - }; - - std::deque m_AvailableIds; - std::vector m_Instances; - }; - - template bool HandleManager::Iterator::operator==(const Iterator& other) const { - return m_Manager == other.m_Manager && m_ID == other.m_ID; - } - template bool HandleManager::Iterator::operator!=(const Iterator& other) const { - return m_Manager != other.m_Manager || m_ID != other.m_ID; - } - - template typename HandleManager::Iterator& HandleManager::Iterator::operator++() { - do { - ++m_ID; - } while (m_ID < m_Manager->m_Instances.size() && !m_Manager->m_Instances[m_ID].valid); - return *this; - } - template typename HandleManager::Iterator HandleManager::Iterator::operator++(int) { - Iterator res = *this; - do { - ++m_ID; - } while (m_ID < m_Manager->m_Instances.size() && !m_Manager->m_Instances[m_ID].valid); - return res; - } - template typename HandleManager::Iterator& HandleManager::Iterator::operator--() { - do { - --m_ID; - } while (m_ID > 0 && !m_Manager->m_Instances[m_ID].valid); - return *this; - } - template typename HandleManager::Iterator HandleManager::Iterator::operator--(int) { - Iterator res = *this; - do { - --m_ID; - } while (m_ID > 0 && !m_Manager->m_Instances[m_ID].valid); - return res; - } - template T& HandleManager::Iterator::operator*() { - return m_Manager->m_Instances[m_ID].instance; - } - template T* HandleManager::Iterator::operator->() { - return &(m_Manager->m_Instances[m_ID].instance); - } - template U32 HandleManager::Iterator::ID() const { - return m_ID; - } - - template HandleManager::Iterator::Iterator(HandleManager* manager, U32 id) : m_Manager(manager), m_ID(id) {} - - template typename HandleManager::Iterator HandleManager::begin() { - for (size_t i = 0; i < m_Instances.size(); ++i) { - if (m_Instances[i].valid) { - return Iterator(this, i); - } - } - return Iterator(this, m_Instances.size()); - } - template typename HandleManager::Iterator HandleManager::end() { - return Iterator(this, m_Instances.size()); - } - - template Handle HandleManager::CreateHandle() { - if (m_AvailableIds.empty()) { - GenId(); - } - Handle res; - res.m_Manager = this; - res.m_ID = m_AvailableIds.front(); - res.m_Gen = ++m_Instances[res.m_ID].gen; - m_Instances[res.m_ID].valid = true; - m_AvailableIds.pop_front(); - return res; - } - template void HandleManager::Destroy(U32 id) { - if (m_Instances[id].valid) { - m_Instances[id].valid = false; - m_Instances[id].instance = T(); - m_AvailableIds.push_back(id); - } - } - template void HandleManager::Clear() { - for (U32 i = 0; i < m_Instances.size(); ++i) { - Destroy(i); - } - } - template void HandleManager::GenId() { - m_AvailableIds.push_back(m_Instances.size()); - m_Instances.push_back(Instance()); - } - - template T& Handle::operator*() { - return m_Manager->m_Instances[m_ID].instance; - } - template const T& Handle::operator*() const { - return m_Manager->m_Instances[m_ID].instance; - } - template T* Handle::operator->() { - return &(m_Manager->m_Instances[m_ID].instance); - } - template const T* Handle::operator->() const { - return &(m_Manager->m_Instances[m_ID].instance); - } - template bool Handle::Valid() const { - return m_Manager && m_Manager->m_Instances[m_ID].valid && m_Manager->m_Instances[m_ID].gen == m_Gen; - } - template void Handle::Destroy() { - m_Manager->m_AvailableIds.push_back(m_ID); - m_Manager->m_Instances[m_ID].valid = false; - } -} // namespace DE diff --git a/DummyEngine/Core/ResourceManaging/RawData.cpp b/DummyEngine/Core/ResourceManaging/RawData.cpp index ec059ec..77f67cd 100644 --- a/DummyEngine/Core/ResourceManaging/RawData.cpp +++ b/DummyEngine/Core/ResourceManaging/RawData.cpp @@ -1,6 +1,9 @@ -#include "DummyEngine/Core/ResourceManaging/RawData.h" +#include "RawData.h" + +#include "DummyEngine/Utils/Debug/Assert.h" + +namespace DummyEngine { -namespace DE { std::string MaterialTypeToStr(MaterialType type) { switch (type) { case MaterialType::PBR: return "PBR"; @@ -53,49 +56,49 @@ namespace DE { return ShaderPartType::None; } - TextureData::TextureData() : m_Data(nullptr), m_Width(0), m_Height(0), m_Channels(TextureChannels::None), m_Format(TextureFormat::None) {} + TextureData::TextureData() : data_(nullptr), width_(0), height_(0), channels_(TextureChannels::None), format_(TextureFormat::None) {} - TextureData::TextureData(const void* data, U32 width, U32 height, TextureChannels channels, TextureFormat format) : m_Data(nullptr) { + TextureData::TextureData(const void* data, U32 width, U32 height, TextureChannels channels, TextureFormat format) : data_(nullptr) { SetData(data, width, height, channels, format); } TextureData::~TextureData() { - free(m_Data); + free(data_); } void TextureData::SetData(const void* data, U32 width, U32 height, TextureChannels channels, TextureFormat format) { - if (m_Data) { - free(m_Data); + if (data_ != nullptr) { + free(data_); } size_t size = width * height * ChannelAmount(channels) * FormatSize(format); DE_ASSERT(size > 0, "Wrong texture data size"); - m_Data = malloc(size); - std::memcpy(m_Data, data, size); - m_Width = width; - m_Height = height; - m_Channels = channels; - m_Format = format; + data_ = malloc(size); + std::memcpy(data_, data, size); + width_ = width; + height_ = height; + channels_ = channels; + format_ = format; } U32 TextureData::PixelSize() const { - return ChannelAmount(m_Channels) * FormatSize(m_Format); + return ChannelAmount(channels_) * FormatSize(format_); } RenderSubMeshData& RenderSubMeshData::operator+=(const RenderSubMeshData& other) { - size_t sz = vertices.size(); - for (size_t i = 0; i < other.vertices.size(); ++i) { - vertices.push_back(other.vertices[i]); + size_t sz = Vertices.size(); + for (size_t i = 0; i < other.Vertices.size(); ++i) { + Vertices.push_back(other.Vertices[i]); } - for (size_t i = 0; i < other.indices.size(); ++i) { - indices.push_back(other.indices[i] + sz); + for (size_t i = 0; i < other.Indices.size(); ++i) { + Indices.push_back(other.Indices[i] + sz); } return *this; } void RenderMeshData::Compress() { std::vector new_vec(1); - new_vec.back() = meshes.front(); - for (size_t i = 1; i < meshes.size(); ++i) { - new_vec.back() += meshes[i]; + new_vec.back() = Meshes.front(); + for (size_t i = 1; i < Meshes.size(); ++i) { + new_vec.back() += Meshes[i]; } - meshes = new_vec; + Meshes = new_vec; } -} // namespace DE \ No newline at end of file +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/ResourceManaging/RawData.h b/DummyEngine/Core/ResourceManaging/RawData.h index f1d7967..e3183d9 100644 --- a/DummyEngine/Core/ResourceManaging/RawData.h +++ b/DummyEngine/Core/ResourceManaging/RawData.h @@ -1,22 +1,28 @@ #pragma once + #include "DummyEngine/Core/Animations/Animation.h" -#include "DummyEngine/Utils/Base.h" -namespace DE { +#include + +namespace DummyEngine { + enum class MaterialType { None = 0, Phong, PBR, }; - std::string MaterialTypeToStr(MaterialType type); - MaterialType MaterialTypeFromStr(const std::string& str); - enum class TextureChannels { None = 0, RED, RG, RGB, RGBA }; + enum class TextureChannels { + None = 0, + RED, + RG, + RGB, + RGBA, + }; enum class TextureFormat { None = 0, U8, Float, }; - enum CubeSide { Right = 0, Left = 1, @@ -25,12 +31,15 @@ namespace DE { Back = 5, Front = 4, }; - U32 ChannelAmount(TextureChannels format); - U32 FormatSize(TextureFormat format); + + std::string MaterialTypeToStr(MaterialType type); + MaterialType MaterialTypeFromStr(const std::string& str); + U32 ChannelAmount(TextureChannels format); + U32 FormatSize(TextureFormat format); struct ShaderPart { - ShaderPartType type; - Path path; + ShaderPartType Type; + Path Path; }; std::string ShaderPartTypeToString(ShaderPartType type); @@ -41,55 +50,55 @@ namespace DE { TextureData(); TextureData(const void* data, U32 width, U32 height, TextureChannels channels, TextureFormat format = TextureFormat::U8); ~TextureData(); + void SetData(const void* data, U32 width, U32 height, TextureChannels channels, TextureFormat format = TextureFormat::U8); U32 PixelSize() const; - U32 Width() const { return m_Width; } - U32 Height() const { return m_Height; } - TextureChannels Channels() const { return m_Channels; } - TextureFormat Format() const { return m_Format; } - // U32 Channels() const { return PixelSize(m_Format); } - void* Data() { return m_Data; } - const void* Data() const { return m_Data; } + U32 Width() const { return width_; } + U32 Height() const { return height_; } + TextureChannels Channels() const { return channels_; } + TextureFormat Format() const { return format_; } + void* Data() { return data_; } + const void* Data() const { return data_; } private: - void* m_Data; - U32 m_Width; - U32 m_Height; - TextureChannels m_Channels; - TextureFormat m_Format; + void* data_; + U32 width_; + U32 height_; + TextureChannels channels_; + TextureFormat format_; }; struct MaterialData { - MaterialType type = MaterialType::PBR; - float shininess; - - Vec3 albedo = Vec3(1.0f); - Vec3 diffuse = Vec3(1.0f); - Vec3 specular = Vec3(1.0f); - Vec3 orm = Vec3(1.0f); - Vec3 ambient = Vec3(1.0f); - Vec3 emission = Vec3(1.0f); - - Ref albedo_map; - Ref diffuse_map; - Ref specular_map; - Ref normal_map; - Ref orm_map; - Ref emission_map; + MaterialType Type = MaterialType::PBR; + float Shininess; + + Vec3 Albedo = Vec3(1.0f); + Vec3 Diffuse = Vec3(1.0f); + Vec3 Specular = Vec3(1.0f); + Vec3 ORM = Vec3(1.0f); + Vec3 Ambient = Vec3(1.0f); + Vec3 Emission = Vec3(1.0f); + + Ref AlbedoMap; + Ref DiffuseMap; + Ref SpecularMap; + Ref NormalMap; + Ref ORMMap; + Ref EmissionMap; }; struct RenderSubMeshData { - std::vector vertices; - std::vector indices; - MaterialData material; + std::vector Vertices; + std::vector Indices; + MaterialData Material; RenderSubMeshData& operator+=(const RenderSubMeshData& other); }; struct RenderMeshData { - Ref animation; - std::vector meshes; + Ref Animation; + std::vector Meshes; void Compress(); }; -} // namespace DE \ No newline at end of file +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/ResourceManaging/ResourceManager.cpp b/DummyEngine/Core/ResourceManaging/ResourceManager.cpp index dc2c454..5bc2b5f 100644 --- a/DummyEngine/Core/ResourceManaging/ResourceManager.cpp +++ b/DummyEngine/Core/ResourceManaging/ResourceManager.cpp @@ -1,10 +1,11 @@ -#include "DummyEngine/Core/ResourceManaging/ResourceManager.h" +#include "ResourceManager.h" #include "DummyEngine/Core/ResourceManaging/AssetManager.h" #include "DummyEngine/ToolBox/Loaders/ModelLoader.h" #include "DummyEngine/ToolBox/Loaders/TextureLoader.h" -namespace DE { +namespace DummyEngine { + SINGLETON_BASE(ResourceManager); S_INITIALIZE() { return Unit(); @@ -14,7 +15,7 @@ namespace DE { } S_METHOD_IMPL(bool, LoadShader, (UUID id), (id)) { - if (m_Shaders.contains(id)) { + if (shaders_.contains(id)) { LOG_WARNING("Shader {} was not loaded because already loaded", id); return false; } @@ -23,12 +24,12 @@ namespace DE { LOG_WARNING("Shader {} was not loaded because does not exist in AssetManager", id); return false; } - m_Shaders[id] = Shader::Create(asset.value().parts); + shaders_[id] = Shader::Create(asset.value().Parts); LOG_INFO("Shader {} was added", id); return true; } S_METHOD_IMPL(bool, LoadRenderMesh, (UUID id), (id)) { - if (m_RenderMeshes.contains(id)) { + if (render_meshes_.contains(id)) { LOG_WARNING("RenderMesh {} was not loaded because already loaded", id); return false; } @@ -37,16 +38,16 @@ namespace DE { LOG_WARNING("RenderMesh {} was not loaded because does not exist in AssetManager", id); return false; } - auto model = ModelLoader::Load(asset.value().loading_props); + auto model = ModelLoader::Load(asset.value().LoadingProps); if (model == nullptr) { return false; } - m_RenderMeshes[id] = CreateRef(model); + render_meshes_[id] = CreateRef(model); LOG_INFO("RenderMesh {} was added", id); return true; } S_METHOD_IMPL(bool, LoadHitBox, (UUID id), (id)) { - if (m_HitBoxes.contains(id)) { + if (hit_boxes_.contains(id)) { LOG_WARNING("HitBox {} was not loaded because already loaded", id); return false; } @@ -55,23 +56,23 @@ namespace DE { LOG_WARNING("Hitbox {} was not loaded because does not exist in AssetManager", id); return false; } - auto mesh = ModelLoader::Load(asset.value().loading_props); + auto mesh = ModelLoader::Load(asset.value().LoadingProps); if (mesh == nullptr) { return false; } std::vector vertices; - for (const auto& submesh : mesh->meshes) { - for (const auto& vert : submesh.vertices) { - vertices.push_back(vert.position); + for (const auto& submesh : mesh->Meshes) { + for (const auto& vert : submesh.Vertices) { + vertices.push_back(vert.Position); } } - m_HitBoxes.insert({id, CreateRef()}); - m_HitBoxes[id]->Build(vertices); + hit_boxes_.insert({id, CreateRef()}); + hit_boxes_[id]->Build(vertices); LOG_INFO("Hitbox {} was added", id); return true; } S_METHOD_IMPL(bool, LoadCubeMap, (UUID id), (id)) { - if (m_CubeMaps.contains(id)) { + if (cube_maps_.contains(id)) { LOG_WARNING("CubeMap {} was not loaded because already loaded", id); return false; } @@ -80,12 +81,12 @@ namespace DE { LOG_WARNING("CubeMap {} was not loaded because does not exist in AssetManager", id); return false; } - m_CubeMaps[id] = CubeMap::Create(TextureLoader::Load(asset.value().loading_props)); + cube_maps_[id] = CubeMap::Create(TextureLoader::Load(asset.value().LoadingProps)); LOG_INFO("CubeMap {} was added", id); return true; } S_METHOD_IMPL(bool, LoadTexture, (UUID id), (id)) { - if (m_Textures.contains(id)) { + if (textures_.contains(id)) { LOG_WARNING("Texture {} was not loaded because already loaded", id); return false; } @@ -94,105 +95,106 @@ namespace DE { LOG_WARNING("Texture {} was not loaded because does not exist in AssetManager", id); return false; } - m_Textures[id] = Texture::Create(*TextureLoader::Load(asset.value().loading_props)); + textures_[id] = Texture::Create(*TextureLoader::Load(asset.value().LoadingProps)); LOG_INFO("Texture {} was added", id); return true; } S_METHOD_IMPL(std::optional>, GetShader, (UUID id), (id)) { - if (m_Shaders.contains(id)) { - return m_Shaders[id]; + if (shaders_.contains(id)) { + return shaders_[id]; } return {}; } S_METHOD_IMPL(std::optional>, GetRenderMesh, (UUID id), (id)) { - if (m_RenderMeshes.contains(id)) { - return m_RenderMeshes[id]; + if (render_meshes_.contains(id)) { + return render_meshes_[id]; } return {}; } S_METHOD_IMPL(std::optional>, GetCubeMap, (UUID id), (id)) { - if (m_CubeMaps.contains(id)) { - return m_CubeMaps[id]; + if (cube_maps_.contains(id)) { + return cube_maps_[id]; } return {}; } S_METHOD_IMPL(std::optional>, GetTexture, (UUID id), (id)) { - if (m_Textures.contains(id)) { - return m_Textures[id]; + if (textures_.contains(id)) { + return textures_[id]; } return {}; } S_METHOD_IMPL(std::optional>, GetHitBox, (UUID id), (id)) { - if (m_HitBoxes.contains(id)) { - return m_HitBoxes[id]; + if (hit_boxes_.contains(id)) { + return hit_boxes_[id]; } return {}; } S_METHOD_IMPL(bool, HasShader, (UUID id), (id)) { - return m_Shaders.contains(id); + return shaders_.contains(id); } S_METHOD_IMPL(bool, HasRenderMesh, (UUID id), (id)) { - return m_RenderMeshes.contains(id); + return render_meshes_.contains(id); } S_METHOD_IMPL(bool, HasCubeMap, (UUID id), (id)) { - return m_CubeMaps.contains(id); + return cube_maps_.contains(id); } S_METHOD_IMPL(bool, HasTexture, (UUID id), (id)) { - return m_Textures.contains(id); + return textures_.contains(id); } S_METHOD_IMPL(bool, HasHitBox, (UUID id), (id)) { - return m_HitBoxes.contains(id); + return hit_boxes_.contains(id); } S_METHOD_IMPL(bool, DeleteShader, (UUID id), (id)) { - if (m_Shaders.contains(id)) { - m_Shaders.erase(id); + if (shaders_.contains(id)) { + shaders_.erase(id); LOG_INFO("Shader {} was deleted", id); return true; } return false; } S_METHOD_IMPL(bool, DeleteRenderMesh, (UUID id), (id)) { - if (m_RenderMeshes.contains(id)) { - m_RenderMeshes.erase(id); + if (render_meshes_.contains(id)) { + render_meshes_.erase(id); LOG_INFO("RenderMesh {} was deleted", id); return true; } return false; } S_METHOD_IMPL(bool, DeleteCubeMap, (UUID id), (id)) { - if (m_CubeMaps.contains(id)) { - m_CubeMaps.erase(id); + if (cube_maps_.contains(id)) { + cube_maps_.erase(id); LOG_INFO("CubeMap {} was deleted", id); return true; } return false; } S_METHOD_IMPL(bool, DeleteHitBox, (UUID id), (id)) { - if (m_HitBoxes.contains(id)) { - m_HitBoxes.erase(id); + if (hit_boxes_.contains(id)) { + hit_boxes_.erase(id); LOG_INFO("Hitbox {} was deleted", id); return true; } return false; } S_METHOD_IMPL(bool, DeleteTexture, (UUID id), (id)) { - if (m_Textures.contains(id)) { - m_Textures.erase(id); + if (textures_.contains(id)) { + textures_.erase(id); LOG_INFO("Texture {} was deleted", id); return true; } return false; } S_METHOD_IMPL(Unit, Clear, (), ()) { - m_Shaders.clear(); - m_RenderMeshes.clear(); - m_CubeMaps.clear(); - m_HitBoxes.clear(); - m_Textures.clear(); + shaders_.clear(); + render_meshes_.clear(); + cube_maps_.clear(); + hit_boxes_.clear(); + textures_.clear(); LOG_INFO("Cleared all resources"); return Unit(); } -} // namespace DE \ No newline at end of file + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/ResourceManaging/ResourceManager.h b/DummyEngine/Core/ResourceManaging/ResourceManager.h index 3d4fb19..5f390a0 100644 --- a/DummyEngine/Core/ResourceManaging/ResourceManager.h +++ b/DummyEngine/Core/ResourceManaging/ResourceManager.h @@ -4,12 +4,11 @@ #include "DummyEngine/Core/Rendering/Renderer/CubeMap.h" #include "DummyEngine/Core/Rendering/Renderer/RenderStructs.h" #include "DummyEngine/Core/Rendering/Renderer/Shader.h" -#include "DummyEngine/Core/ResourceManaging/Assets.h" -#include "DummyEngine/Utils/Base.h" -namespace DE { +namespace DummyEngine { + class ResourceManager : public Singleton { - LOGGER_AUTHOR(ResourceManager) + LOG_AUTHOR(ResourceManager) SINGLETON(ResourceManager) public: S_METHOD_DEF(bool, LoadShader, (UUID id)); @@ -39,10 +38,11 @@ namespace DE { S_METHOD_DEF(Unit, Clear, ()); private: - std::unordered_map> m_Shaders; - std::unordered_map> m_RenderMeshes; - std::unordered_map> m_CubeMaps; - std::unordered_map> m_Textures; - std::unordered_map> m_HitBoxes; + std::unordered_map> shaders_; + std::unordered_map> render_meshes_; + std::unordered_map> cube_maps_; + std::unordered_map> textures_; + std::unordered_map> hit_boxes_; }; -} // namespace DE \ No newline at end of file + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Scene/Components.cpp b/DummyEngine/Core/Scene/Components.cpp index 2e3623b..68756f3 100644 --- a/DummyEngine/Core/Scene/Components.cpp +++ b/DummyEngine/Core/Scene/Components.cpp @@ -1,18 +1,19 @@ -#include "DummyEngine/Core/Scene/Components.h" +#include "Components.h" -namespace DE { +namespace DummyEngine { Mat4 TransformComponent::GetTransform() const { - return glm::translate(glm::mat4(1.0f), translation + translation_offset) * glm::toMat4(glm::quat(glm::radians(rotation + rotation_offet))) * - glm::scale(glm::mat4(1.0f), scale * scale_offset); + return glm::translate(glm::mat4(1.0f), Translation + TranslationOffset) * glm::toMat4(glm::quat(glm::radians(Rotation + RotationOffet))) * + glm::scale(glm::mat4(1.0f), Scale * ScaleOffset); } Mat4 TransformComponent::GetTranslation() const { - return glm::translate(glm::mat4(1.0f), translation + translation_offset); + return glm::translate(glm::mat4(1.0f), Translation + TranslationOffset); } Mat4 TransformComponent::GetRotation() const { - return glm::toMat4(glm::quat(glm::radians(rotation + rotation_offet))); + return glm::toMat4(glm::quat(glm::radians(Rotation + RotationOffet))); } Mat4 TransformComponent::GetScale() const { - return glm::scale(glm::mat4(1.0f), scale * scale_offset); + return glm::scale(glm::mat4(1.0f), Scale * ScaleOffset); } -} // namespace DE \ No newline at end of file + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Scene/Components.h b/DummyEngine/Core/Scene/Components.h index 3c8df29..d4a7ca5 100644 --- a/DummyEngine/Core/Scene/Components.h +++ b/DummyEngine/Core/Scene/Components.h @@ -1,44 +1,45 @@ #pragma once -#include "DummyEngine/Core/Rendering/Renderer/CubeMap.h" #include "DummyEngine/Core/Rendering/Renderer/RenderStructs.h" #include "DummyEngine/Core/Rendering/Renderer/Shader.h" #include "DummyEngine/Core/Rendering/Renderer/SkyBox.h" -#include "DummyEngine/Utils/Base.h" +#include "DummyEngine/Utils/Types/UUID.h" -namespace DE { +namespace DummyEngine { class IDComponent { public: IDComponent() = default; - IDComponent(UUID uuid) : m_ID(uuid) {} + IDComponent(UUID uuid) : id_(uuid) {} // NOLINT + operator UUID() const { return id_; } // NOLINT - UUID Get() const { return m_ID; } - std::string Hex() const { return m_ID; } - - operator UUID() const { return m_ID; } + UUID Get() const { return id_; } + std::string Hex() const { return id_; } private: - UUID m_ID; + UUID id_; }; struct TagComponent { TagComponent() = default; - TagComponent(const std::string& tag) : tag(tag) {} - operator std::string() const { return tag; } + TagComponent(const std::string& tag) : Tag(tag) {} // NOLINT + operator std::string() const { return Tag; } // NOLINT - bool operator==(const TagComponent& other) const { return tag == other.tag; } - bool operator!=(const TagComponent& other) const { return tag != other.tag; } - bool operator<(const TagComponent& other) const { return tag < other.tag; } - bool operator>(const TagComponent& other) const { return tag > other.tag; } + bool operator==(const TagComponent& other) const { return Tag == other.Tag; } + bool operator!=(const TagComponent& other) const { return Tag != other.Tag; } + bool operator<(const TagComponent& other) const { return Tag < other.Tag; } + bool operator>(const TagComponent& other) const { return Tag > other.Tag; } - std::string tag; + std::string Tag; }; struct TransformComponent { - Vec3 scale = Vec3(1.0), scale_offset = Vec3(1.0); - Vec3 translation = Vec3(0.0), translation_offset = Vec3(0.0); - Vec3 rotation = Vec3(0.0), rotation_offet = Vec3(0.0); + Vec3 Scale = Vec3(1.0); + Vec3 ScaleOffset = Vec3(1.0); + Vec3 Translation = Vec3(0.0); + Vec3 TranslationOffset = Vec3(0.0); + Vec3 Rotation = Vec3(0.0); + Vec3 RotationOffet = Vec3(0.0); TransformComponent() = default; @@ -47,17 +48,19 @@ namespace DE { Mat4 GetRotation() const; Mat4 GetScale() const; }; + struct ShaderComponent { - UUID id; + UUID ID; + Ref Shader; - Ref shader; - Shader* operator->() { return shader.get(); } + class Shader* operator->() { return Shader.get(); } }; + struct RenderMeshComponent { - UUID id; + UUID ID; + Ref Mesh = nullptr; - Ref mesh = nullptr; - RenderMesh* operator->() { return mesh.get(); } + RenderMesh* operator->() { return Mesh.get(); } }; struct SkyBoxComponent { @@ -65,16 +68,20 @@ namespace DE { CubeMap = 0, Equirectangular, }; - TexType type; - UUID id; - Ref map; - SkyBox* operator->() { return map.get(); } + TexType Type; + UUID ID; + Ref SkyBox; + + class SkyBox* operator->() { return SkyBox.get(); } }; - template struct hash; - template <> struct hash { - std::size_t operator()(const DE::TagComponent& tag) const { return std::hash()(tag); } +} // namespace DummyEngine + +namespace std { + + template <> struct hash { + std::size_t operator()(const DummyEngine::TagComponent& tag) const { return std::hash()(tag); } }; -} // namespace DE \ No newline at end of file +} // namespace std \ No newline at end of file diff --git a/DummyEngine/Core/Scene/Scene.cpp b/DummyEngine/Core/Scene/Scene.cpp index 6088df7..8b1499c 100644 --- a/DummyEngine/Core/Scene/Scene.cpp +++ b/DummyEngine/Core/Scene/Scene.cpp @@ -1,184 +1,140 @@ -#include "DummyEngine/Core/Scene/Scene.h" +#include "Scene.h" -#include "DummyEngine/Core/ECS/Entity.hpp" -#include "DummyEngine/Core/Objects/LightSources/LightSource.h" -#include "DummyEngine/Core/Rendering/Renderer/Renderer.h" -#include "DummyEngine/Core/ResourceManaging/ResourceManager.h" +#include "DummyEngine/Core/Physics/Solver.hpp" #include "DummyEngine/Core/Scene/Components.h" #include "DummyEngine/Core/Scene/SceneHierarchy.h" #include "DummyEngine/Core/Scene/SceneRenderer.h" #include "DummyEngine/Core/Scripting/Script.h" #include "DummyEngine/Core/Scripting/ScriptEngine.h" +#include "DummyEngine/Utils/Debug/Profiler.h" -namespace DE { +#include + +namespace DummyEngine { void Scene::OnRuntimeStart() { - // for (auto e : View()) { - // auto& audio = e.Get(); - // if (audio.sound) { - // audio.sound->start_streaming(); - // } - // } - for (auto e : m_Storage->View()) { + for (auto e : storage_->View()) { auto& component = e.Get(); if (component.Valid()) { component->OnRuntimeStart(); } } std::unordered_set> meshes; - for (auto e : m_Storage->View()) { - auto mesh = e.Get().mesh; - if (mesh->p_Animator && !meshes.contains(mesh)) { + for (auto e : storage_->View()) { + auto mesh = e.Get().Mesh; + if (mesh->Animator && !meshes.contains(mesh)) { meshes.insert(mesh); - mesh->p_Animator->SetTime(0); + mesh->Animator->SetTime(0); } } } - void Scene::OnRuntimePause() { - // for (auto e : View()) { - // auto& audio = e.Get(); - // if (audio.sound) { - // audio.sound->pause_streaming(); - // } - // } - } + void Scene::OnRuntimePause() {} - void Scene::OnRuntimeResume() { - // for (auto e : View()) { - // auto& audio = e.Get(); - // if (audio.sound) { - // audio.sound->resume_streaming(); - // } - // } - } + void Scene::OnRuntimeResume() {} void Scene::OnRuntimeStop() { - // for (auto e : View()) { - // auto& audio = e.Get(); - // if (audio.sound) { - // audio.sound->stop_streaming(); - // } - // } - for (auto e : m_Storage->View()) { + for (auto e : storage_->View()) { auto& component = e.Get(); if (component.Valid()) { component->OnRuntimeStop(); } } std::unordered_set> meshes; - for (auto e : m_Storage->View()) { - auto mesh = e.Get().mesh; - if (mesh->p_Animator && !meshes.contains(mesh)) { + for (auto e : storage_->View()) { + auto mesh = e.Get().Mesh; + if (mesh->Animator && !meshes.contains(mesh)) { meshes.insert(mesh); - mesh->p_Animator->SetTime(0); + mesh->Animator->SetTime(0); } } } void Scene::OnUpdate(float dt) { DE_PROFILE_SCOPE("Scene OnUpdate"); - if (m_PhysicsSolver) { + if (physics_solver_) { DE_PROFILE_SCOPE("Physics"); - m_PhysicsSolver->OnUpdate(dt * 2); + physics_solver_->OnUpdate(dt * 2); } - for (auto e : m_Storage->View()) { + for (auto e : storage_->View()) { auto& component = e.Get(); if (component.Valid()) { component->OnUpdate(dt); } } - // for (auto e : m_Storage->View()) { - // auto& component = e.Get(); - // if (component.sound) { - // Vec3 pos(0.0f); - // if (e.Has()) { - // pos = e.Get().translation; - // } - // component.sound->setPosition({pos.x, pos.y, pos.z}); - // component.sound->play_streaming(); - // } - // } std::unordered_set> meshes; - for (auto e : m_Storage->View()) { - auto mesh = e.Get().mesh; - if (mesh->p_Animator && !meshes.contains(mesh)) { + for (auto e : storage_->View()) { + auto mesh = e.Get().Mesh; + if (mesh->Animator && !meshes.contains(mesh)) { meshes.insert(mesh); - mesh->p_Animator->UpdateAnimation(dt); + mesh->Animator->UpdateAnimation(dt); } } - m_Storage->UpdateSystems(dt); + storage_->UpdateSystems(dt); } void Scene::OnRender(Entity camera) { if (!camera.Valid()) { - camera = m_Camera; + camera = camera_; } if (!camera.Has()) { LOG_WARNING("Specified camera entity has no camera component"); return; } - m_Renderer->Render(camera); + renderer_->Render(camera); } void Scene::OnViewPortResize(U32 x, U32 y) { double aspect = double(x) / double(y); - auto cameras = m_Storage->View(); + auto cameras = storage_->View(); for (auto e : cameras) { e.Get().SetAspect(aspect); } - m_Renderer->OnViewPortResize(x, y); + renderer_->OnViewPortResize(x, y); } - Scene::Scene() : m_Storage(CreateRef()), m_Renderer(CreateRef(this)), m_Hierarchy("Scene") { - m_Storage->SetAddHandler([this](Entity entity) { + Scene::Scene() : storage_(CreateRef()), renderer_(CreateRef(this)), hierarchy_("Scene") { + storage_->SetAddHandler([this](Entity entity) { auto id = entity.Get(); - DE_ASSERT(m_EntityByID.find(id) == m_EntityByID.end(), "UUID collision occured {}", id.Get()); - m_EntityByID[id] = entity; + DE_ASSERT(entity_by_id_.find(id) == entity_by_id_.end(), "UUID collision occured {}", id.Get()); + entity_by_id_[id] = entity; }); - m_PhysicsSolver = CreateRef(); - m_Storage->SetRemoveHandler([this](Entity entity) { m_EntityByID.erase(entity.Get()); }); - // m_Storage->SetRemoveHandler([this](Entity entity) { - // auto& sound = entity.Get().sound; - // if (sound) { - // sound->stop_streaming(); - // } - // }); + physics_solver_ = CreateRef(); + storage_->SetRemoveHandler([this](Entity entity) { entity_by_id_.erase(entity.Get()); }); } Scene::~Scene() { - m_Storage->Destruct(); - m_Storage = nullptr; + storage_->Destruct(); + storage_ = nullptr; } Entity Scene::CreateEmptyEntity() { - return m_Storage->CreateEntity(); + return storage_->CreateEntity(); } Entity Scene::CreateEntity(const std::string& name, bool visisble) { - Entity new_entity = m_Storage->CreateEntity(); + Entity new_entity = storage_->CreateEntity(); new_entity.AddComponent(TagComponent(name)); new_entity.AddComponent(IDComponent(UUID::Generate())); if (visisble) { - m_Hierarchy.AddEntity(new_entity); + hierarchy_.AddEntity(new_entity); } return new_entity; } Entity Scene::CloneEntity(Entity) { - // DE_ASSERT(false, "Clone of entity not implemented yet."); return CreateEntity("Entity", false); } Entity Scene::GetByID(UUID uuid) { - return (m_EntityByID.contains(uuid) ? m_EntityByID.at(uuid) : Entity()); + return (entity_by_id_.contains(uuid) ? entity_by_id_.at(uuid) : Entity()); } SceneHierarchy::Node Scene::GetHierarchyRoot() { - return m_Hierarchy.GetRoot(); + return hierarchy_.GetRoot(); } void Scene::SetCamera(Entity entity) { DE_ASSERT(entity.Has(), "SetCamera on entity withour camera"); - m_Camera = entity; + camera_ = entity; } bool Scene::HasCamera() { - return m_Camera.Valid(); + return camera_.Valid(); } void Scene::LoadPhysics(Ref& scene) { - m_PhysicsSolver->LoadScene(scene); + physics_solver_->LoadScene(scene); } -} // namespace DE \ No newline at end of file +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Scene/Scene.h b/DummyEngine/Core/Scene/Scene.h index 6ec9368..f6525e7 100644 --- a/DummyEngine/Core/Scene/Scene.h +++ b/DummyEngine/Core/Scene/Scene.h @@ -1,21 +1,21 @@ #pragma once #include "DummyEngine/Core/ECS/ECS.h" -#include "DummyEngine/Core/Objects/Cameras/FPSCamera.h" -#include "DummyEngine/Core/Physics/Solver.hpp" -#include "DummyEngine/Core/Scene/Components.h" #include "DummyEngine/Core/Scene/SceneHierarchy.h" +#include "DummyEngine/Utils/Debug/Logger.h" + +namespace DummyEngine { -namespace DE { class Entity; class SceneRenderer; class ScripyEngine; + namespace Physics { class Solver; } class Scene { - LOGGER_AUTHOR(Scene) + LOG_AUTHOR(Scene) public: Scene(); ~Scene(); @@ -37,27 +37,28 @@ namespace DE { void LoadPhysics(Ref& scene); - Ref GetRenderer() { return m_Renderer; } + Ref GetRenderer() { return renderer_; } SceneHierarchy::Node GetHierarchyRoot(); template Ref AttachSystem(Ref system = nullptr) { if (!system) { system = CreateRef(); } - m_Storage->AttachSystem(system); + storage_->AttachSystem(system); return system; } - template StorageView View() { return m_Storage->View(); } + template StorageView View() { return storage_->View(); } private: friend class ScriptEngine; friend class SceneRenderer; - Entity m_Camera; - Ref m_Storage; - Ref m_Renderer; - SceneHierarchy m_Hierarchy; - std::unordered_map m_EntityByID; - Ref m_PhysicsSolver; + Entity camera_; + Ref storage_; + Ref renderer_; + Ref physics_solver_; + SceneHierarchy hierarchy_; + std::unordered_map entity_by_id_; }; -} // namespace DE \ No newline at end of file + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Scene/SceneHierarchy.cpp b/DummyEngine/Core/Scene/SceneHierarchy.cpp index 0ae5203..9faf82a 100644 --- a/DummyEngine/Core/Scene/SceneHierarchy.cpp +++ b/DummyEngine/Core/Scene/SceneHierarchy.cpp @@ -1,83 +1,82 @@ -#include "DummyEngine/Core/Scene/SceneHierarchy.h" +#include "SceneHierarchy.h" -#include "DummyEngine/Core/Scene/Components.h" +namespace DummyEngine { -namespace DE { bool SceneHierarchy::Node::Valid() const { - return m_ID != UINT32_MAX && m_Owner && !std::holds_alternative(m_Owner->m_Nodes[m_ID].node); + return id_ != UINT32_MAX && owner_ != nullptr && !std::holds_alternative(owner_->nodes_[id_].Node); } bool SceneHierarchy::Node::IsEntity() const { - return m_ID != UINT32_MAX && m_Owner && std::holds_alternative(m_Owner->m_Nodes[m_ID].node); + return id_ != UINT32_MAX && owner_ != nullptr && std::holds_alternative(owner_->nodes_[id_].Node); } bool SceneHierarchy::Node::IsFolder() const { - return m_ID != UINT32_MAX && m_Owner && std::holds_alternative(m_Owner->m_Nodes[m_ID].node); + return id_ != UINT32_MAX && owner_ != nullptr && std::holds_alternative(owner_->nodes_[id_].Node); } bool SceneHierarchy::Node::IsAnsestorOf(const Node& child) const { - if (!Valid() || !child.Valid() || m_Owner != child.m_Owner) { + if (!Valid() || !child.Valid() || owner_ != child.owner_) { return false; } - return m_Owner->IsAnsestor(m_ID, child.m_ID); + return owner_->IsAnsestor(id_, child.id_); } U32 SceneHierarchy::Node::GetID() const { - return m_ID; + return id_; } SceneHierarchy::Node SceneHierarchy::Node::GetParent() const { - DE_ASSERT(m_ID != UINT32_MAX && m_Owner, "Use of GetParent on invalid SceneHierarchy::Node"); - return Node(m_Owner, m_Owner->m_Nodes[m_ID].parent); + DE_ASSERT(id_ == UINT32_MAX && owner_ != nullptr, "Use of GetParent on invalid SceneHierarchy::Node"); + return Node(owner_, owner_->nodes_[id_].Parent); } bool SceneHierarchy::Node::Attach(Node other) { - DE_ASSERT(m_ID != UINT32_MAX && m_Owner, "Use of Attach on invalid SceneHierarchy::Node"); - return m_Owner->Attach(*this, other); + DE_ASSERT(id_ != UINT32_MAX && owner_ != nullptr, "Use of Attach on invalid SceneHierarchy::Node"); + return owner_->Attach(*this, other); } SceneHierarchy::Node SceneHierarchy::Node::AddEntity(Entity entity) { DE_ASSERT(IsFolder(), "Use of AddEntity on invalid SceneHierarchy::Node"); - auto ent = m_Owner->AddEntity(entity); - m_Owner->Attach(*this, ent); + auto ent = owner_->AddEntity(entity); + owner_->Attach(*this, ent); return ent; } SceneHierarchy::Node SceneHierarchy::Node::AddFolder(const std::string& name) { DE_ASSERT(IsFolder(), "Use of AddFolder on invalid SceneHierarchy::Node"); - auto folder = m_Owner->AddFolder(name); - m_Owner->Attach(*this, folder); + auto folder = owner_->AddFolder(name); + owner_->Attach(*this, folder); return folder; } void SceneHierarchy::Node::Delete() { - DE_ASSERT(m_ID != UINT32_MAX && m_Owner, "Use of Delete on invalid SceneHierarchy::Node"); - m_Owner->DeleteNode(*this); + DE_ASSERT(id_ != UINT32_MAX && owner_, "Use of Delete on invalid SceneHierarchy::Node"); + owner_->DeleteNode(*this); *this = Node(); } Entity SceneHierarchy::Node::GetEntity() const { - DE_ASSERT(IsEntity(), "Use of GetEntity on non entity node"); - auto& entity = std::get(m_Owner->m_Nodes[m_ID].node); - return entity.entity; + DE_ASSERT(IsEntity(), "Use of GetEntity on non entity Node"); + auto& entity = std::get(owner_->nodes_[id_].Node); + return entity.Entity; } std::vector SceneHierarchy::Node::GetChilds() const { - DE_ASSERT(IsFolder(), "Use of GetChilds on non folder node"); + DE_ASSERT(IsFolder(), "Use of GetChilds on non folder Node"); std::vector res; - auto& folder = std::get(m_Owner->m_Nodes[m_ID].node); - for (auto child : folder.childs) { - res.push_back(Node(m_Owner, child)); + auto& folder = std::get(owner_->nodes_[id_].Node); + for (auto child : folder.Childs) { + res.push_back(Node(owner_, child)); } return res; } std::string& SceneHierarchy::Node::GetName() { - DE_ASSERT(IsFolder(), "Use of GetName on non folder node"); - auto& folder = std::get(m_Owner->m_Nodes[m_ID].node); - return folder.name; + DE_ASSERT(IsFolder(), "Use of GetName on non folder Node"); + auto& folder = std::get(owner_->nodes_[id_].Node); + return folder.Name; } bool SceneHierarchy::Node::operator==(const Node& other) const { - return m_ID == other.m_ID && m_Owner == other.m_Owner; + return id_ == other.id_ && owner_ == other.owner_; } bool SceneHierarchy::Node::operator!=(const Node& other) const { - return m_ID != other.m_ID || m_Owner != other.m_Owner; + return id_ != other.id_ || owner_ != other.owner_; } - SceneHierarchy::Node::Node(SceneHierarchy* owner, U32 id) : m_Owner(owner), m_ID(id) {} + SceneHierarchy::Node::Node(SceneHierarchy* owner, U32 id) : owner_(owner), id_(id) {} SceneHierarchy::SceneHierarchy(const std::string& name) { - m_Nodes.emplace_back(name); + nodes_.emplace_back(name); } SceneHierarchy::Node SceneHierarchy::GetRoot() { @@ -85,77 +84,78 @@ namespace DE { } SceneHierarchy::Node SceneHierarchy::AddFolder(const std::string& name) { U32 id; - if (m_AvailableNodes.empty()) { - id = m_Nodes.size(); - m_Nodes.emplace_back(name, 0); + if (available_nodes_.empty()) { + id = nodes_.size(); + nodes_.emplace_back(name, 0); } else { - id = m_AvailableNodes.front(); - m_AvailableNodes.pop(); - m_Nodes[id] = NodeData(name, 0); + id = available_nodes_.front(); + available_nodes_.pop(); + nodes_[id] = NodeData(name, 0); } - std::get(m_Nodes[0].node).childs.push_back(id); + std::get(nodes_[0].Node).Childs.push_back(id); return Node(this, id); } SceneHierarchy::Node SceneHierarchy::AddEntity(Entity entity) { U32 id; - if (m_AvailableNodes.empty()) { - id = m_Nodes.size(); - m_Nodes.emplace_back(entity, 0); + if (available_nodes_.empty()) { + id = nodes_.size(); + nodes_.emplace_back(entity, 0); } else { - id = m_AvailableNodes.front(); - m_AvailableNodes.pop(); - m_Nodes[id] = NodeData(entity, 0); + id = available_nodes_.front(); + available_nodes_.pop(); + nodes_[id] = NodeData(entity, 0); } - std::get(m_Nodes[0].node).childs.push_back(id); + std::get(nodes_[0].Node).Childs.push_back(id); return Node(this, id); } void SceneHierarchy::DeleteNode(Node node) { - DE_ASSERT(node.m_ID < m_Nodes.size(), "Use of DeleteNode on invalid SceneHierarchy::Node"); - DE_ASSERT(node.m_ID != 0, "Use of DeleteNode on root SceneHierarchy::Node"); - auto& parent = std::get(m_Nodes[m_Nodes[node.m_ID].parent].node); - for (auto it = parent.childs.begin(); it != parent.childs.end(); ++it) { - if (*it == node.m_ID) { - parent.childs.erase(it); + DE_ASSERT(node.id_ < nodes_.size(), "Use of DeleteNode on invalid SceneHierarchy::Node"); + DE_ASSERT(node.id_ != 0, "Use of DeleteNode on root SceneHierarchy::Node"); + auto& parent = std::get(nodes_[nodes_[node.id_].Parent].Node); + for (auto it = parent.Childs.begin(); it != parent.Childs.end(); ++it) { + if (*it == node.id_) { + parent.Childs.erase(it); break; } } - m_Nodes[node.m_ID] = NodeData(); - m_AvailableNodes.push(node.m_ID); + nodes_[node.id_] = NodeData(); + available_nodes_.push(node.id_); } bool SceneHierarchy::Attach(Node parent, Node child) { - DE_ASSERT(child.m_ID < m_Nodes.size(), "Use of Attach on invalid child SceneHierarchy::Node"); - DE_ASSERT(parent.m_ID < m_Nodes.size(), "Use of Attach on invalid parent SceneHierarchy::Node"); - U32 new_parent_id = parent.m_ID; - U32 old_parent_id = m_Nodes[child.m_ID].parent; - U32 child_id = child.m_ID; + DE_ASSERT(child.id_ < nodes_.size(), "Use of Attach on invalid child SceneHierarchy::Node"); + DE_ASSERT(parent.id_ < nodes_.size(), "Use of Attach on invalid Parent SceneHierarchy::Node"); + U32 new_parent_id = parent.id_; + U32 old_parent_id = nodes_[child.id_].Parent; + U32 child_id = child.id_; if (new_parent_id == old_parent_id || !parent.IsFolder() || IsAnsestor(child_id, new_parent_id)) { return false; } - auto& old_parent = std::get(m_Nodes[old_parent_id].node); - auto& new_parent = std::get(m_Nodes[new_parent_id].node); - for (auto it = old_parent.childs.begin(); it != old_parent.childs.end(); ++it) { - if (*it == child.m_ID) { - old_parent.childs.erase(it); + auto& old_parent = std::get(nodes_[old_parent_id].Node); + auto& new_parent = std::get(nodes_[new_parent_id].Node); + for (auto it = old_parent.Childs.begin(); it != old_parent.Childs.end(); ++it) { + if (*it == child.id_) { + old_parent.Childs.erase(it); break; } } - m_Nodes[child_id].parent = new_parent_id; - new_parent.childs.push_back(child_id); + nodes_[child_id].Parent = new_parent_id; + new_parent.Childs.push_back(child_id); return true; } bool SceneHierarchy::IsAnsestor(U32 parent, U32 child) const { do { - if (m_Nodes[child].parent == parent) { + if (nodes_[child].Parent == parent) { return true; } - child = m_Nodes[child].parent; + child = nodes_[child].Parent; } while (child != UINT32_MAX); return false; } - SceneHierarchy::NodeData::NodeData(Entity entity, U32 parent) : node(EntityNode(entity)), parent(parent) {} - SceneHierarchy::NodeData::NodeData(const std::string& name, U32 parent) : node(FolderNode(name)), parent(parent) {} - SceneHierarchy::NodeData::EntityNode::EntityNode(Entity ent) : entity(ent) {} - SceneHierarchy::NodeData::FolderNode::FolderNode(const std::string& name) : name(name) {} -} // namespace DE \ No newline at end of file + SceneHierarchy::NodeData::NodeData(Entity entity, U32 parent) : Node(EntityNode(entity)), Parent(parent) {} + SceneHierarchy::NodeData::NodeData(const std::string& name, U32 parent) : Node(FolderNode(name)), Parent(parent) {} + SceneHierarchy::NodeData::EntityNode::EntityNode(class Entity ent) : Entity(ent) {} + SceneHierarchy::NodeData::FolderNode::FolderNode(const std::string& name) : Name(name) {} + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Scene/SceneHierarchy.h b/DummyEngine/Core/Scene/SceneHierarchy.h index aa50377..2898a67 100644 --- a/DummyEngine/Core/Scene/SceneHierarchy.h +++ b/DummyEngine/Core/Scene/SceneHierarchy.h @@ -1,10 +1,24 @@ #pragma once #include "DummyEngine/Core/ECS/ECS.h" -#include "DummyEngine/Utils/Base.h" -namespace DE { +namespace DummyEngine { + class SceneHierarchy { + public: + class Node; + + explicit SceneHierarchy(const std::string& name); + + Node GetRoot(); + Node AddFolder(const std::string& name); + Node AddEntity(Entity entity); + void DeleteNode(Node node); + bool Attach(Node parent, Node child); + + private: + bool IsAnsestor(U32 parent, U32 child) const; + public: class Node { public: @@ -34,41 +48,38 @@ namespace DE { friend class SceneHierarchy; Node(SceneHierarchy* owner, U32 id); - SceneHierarchy* m_Owner = nullptr; - U32 m_ID = UINT32_MAX; + SceneHierarchy* owner_ = nullptr; + U32 id_ = UINT32_MAX; }; - SceneHierarchy(const std::string& name); - - Node GetRoot(); - Node AddFolder(const std::string& name); - Node AddEntity(Entity entity); - void DeleteNode(Node node); - bool Attach(Node parent, Node child); - private: - bool IsAnsestor(U32 parent, U32 child) const; - struct NodeData { + public: NodeData() = default; - NodeData(Entity entity, U32 parent = -1); - NodeData(const std::string& name, U32 parent = -1); + explicit NodeData(Entity entity, U32 parent = -1); + explicit NodeData(const std::string& name, U32 parent = -1); + public: struct FolderNode { - std::string name; - std::vector childs; - FolderNode(const std::string& name); + std::string Name; + std::vector Childs; + + explicit FolderNode(const std::string& name); }; struct EntityNode { - Entity entity; - EntityNode(Entity ent); + Entity Entity; + + explicit EntityNode(class Entity entity); }; - std::variant node; - U32 parent; + public: + std::variant Node; + U32 Parent; }; - std::vector m_Nodes; - std::queue m_AvailableNodes; + + private: + std::vector nodes_; + std::queue available_nodes_; }; -} // namespace DE \ No newline at end of file +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Scene/SceneRenderer.cpp b/DummyEngine/Core/Scene/SceneRenderer.cpp index 2b4ec80..089c897 100644 --- a/DummyEngine/Core/Scene/SceneRenderer.cpp +++ b/DummyEngine/Core/Scene/SceneRenderer.cpp @@ -1,21 +1,22 @@ -#include "DummyEngine/Core/Scene/SceneRenderer.h" +#include "SceneRenderer.h" #include "DummyEngine/Core/Console/Console.hpp" -#include "DummyEngine/Core/ECS/ECS.h" #include "DummyEngine/Core/Objects/LightSources/LightSource.h" +#include "DummyEngine/Core/Rendering/Renderer/FrameBuffer.h" #include "DummyEngine/Core/Rendering/Renderer/Renderer.h" -#include "DummyEngine/Core/Rendering/RendererOpenGL/GLDebug.h" +#include "DummyEngine/Core/Rendering/Renderer/UniformBuffer.h" #include "DummyEngine/Core/ResourceManaging/ResourceManager.h" #include "DummyEngine/Core/Scene/Components.h" #include "DummyEngine/Core/Scripting/ScriptEngine.h" +#include "DummyEngine/Utils/Debug/Profiler.h" -namespace DE { - const U32 MAX_LIGHTS_IN_SCENE = 1000; +namespace DummyEngine { - const U32 LIGHT_UB_ID = 1; + constexpr U32 kMaxLightsInScene = 1000; + constexpr U32 kLightUniformBufferID = 1; - SceneRenderer::SceneRenderer(Scene* scene) : m_Scene(scene) { - m_Lights = UniformBuffer::Create( + SceneRenderer::SceneRenderer(Scene* scene) : scene_(scene) { + lights_ = UniformBuffer::Create( { BufferElementType::Float3, BufferElementType::Float3, @@ -25,114 +26,114 @@ namespace DE { BufferElementType::Float3, BufferElementType::Float3, }, - MAX_LIGHTS_IN_SCENE); - m_FrameBuffer = FrameBuffer::Create({1920, 1080}); - m_FrameBuffer->AddColorAttachment(Texture::Format::F32, Texture::Channels::RGBA); - m_FrameBuffer->SetDepthAttachment(Texture::Format::F32); + kMaxLightsInScene); + frame_buffer_ = FrameBuffer::Create({1920, 1080}); + frame_buffer_->AddColorAttachment(Texture::Format::F32, Texture::Channels::RGBA); + frame_buffer_->SetDepthAttachment(Texture::Format::F32); - if (settings.use_directional_shadow_map) { - initializeShadowMap(); + if (Settings.UseDirectionalShadowMap) { + InitializeShadowMap(); } } void SceneRenderer::OnViewPortResize(U32 x, U32 y) { - m_FrameBuffer->Resize(x, y); + frame_buffer_->Resize(x, y); } void SceneRenderer::Render(Entity cam) { DE_PROFILE_SCOPE("Scene Render"); Entity skybox; - auto& camera = cam.Get(); - FPSCamera lightCamera = FPSCamera(Vec3{0, 100, 0}, Vec3{0, -1, 0}); - if (settings.use_directional_shadow_map) { + auto& camera = cam.Get(); + FPSCamera light_camera(Vec3{0, 100, 0}, Vec3{0, -1, 0}); + if (Settings.UseDirectionalShadowMap) { DE_PROFILE_SCOPE("Directional ShadowMap Rendering"); - if (!m_ShadowMap) { - initializeShadowMap(); + if (!shadow_map_) { + InitializeShadowMap(); } - m_ShadowMap->Bind(); + shadow_map_->Bind(); Renderer::Enable(RenderSetting::FaceCulling); - Renderer::SetViewport(m_ShadowMap->GetWidth(), m_ShadowMap->GetHeight()); + Renderer::SetViewport(shadow_map_->GetWidth(), shadow_map_->GetHeight()); Renderer::Clear(); auto shader = Renderer::GetShader(Renderer::Shaders::DirectionalShadowMap); shader->Bind(); - for (auto entity : m_Scene->m_Storage->View()) { - if (entity.Get().type == LightSourceType::Direction) { - lightCamera.SetPos(entity.Get().translation); - lightCamera.SetDir(entity.Get().direction); + for (auto entity : scene_->storage_->View()) { + if (entity.Get().Type == LightSourceType::Direction) { + light_camera.SetPos(entity.Get().Translation); + light_camera.SetDir(entity.Get().Direction); } } - shader->SetMat4("u_Camera.view", lightCamera.GetViewMatrix()); - shader->SetMat4("u_Camera.projection", lightCamera.GetOrthoProjectionMatrix()); - for (auto e : m_Scene->View()) { - auto mesh = e.Get().mesh; - int res = (mesh->p_Animator ? 1 : 0); + shader->SetMat4("u_Camera.view", light_camera.GetViewMatrix()); + shader->SetMat4("u_Camera.projection", light_camera.GetOrthoProjectionMatrix()); + for (auto e : scene_->View()) { + auto mesh = e.Get().Mesh; + int res = (mesh->Animator ? 1 : 0); shader->SetInt("u_Animated", res); - if (mesh->p_Animator) { - mesh->p_Animator->SetMatricies(shader); + if (mesh->Animator) { + mesh->Animator->SetMatricies(shader); } Mat4 transform(1.0f); if (e.Has()) { transform = e.Get().GetTransform(); } for (const auto& submesh : mesh->GetSubMeshes()) { - Renderer::Submit(submesh.vertex_array, shader, transform); + Renderer::Submit(submesh.VertexArray, shader, transform); } } Renderer::Disable(RenderSetting::FaceCulling); - m_ShadowMap->UnBind(); + shadow_map_->UnBind(); } - if (settings.use_point_shadows) { + if (Settings.UsePointShadows) { DE_PROFILE_SCOPE("PointShadowMap Rendering"); auto shader = Renderer::GetShader(Renderer::Shaders::OmnidirectionalShadowMap); shader->Bind(); - U32 size = Console::GetInt("r_psm_size"); - glm::mat4 shadowProj = glm::perspective(glm::radians(90.f), 1.f, Console::GetFloat("r_psm_near"), Console::GetFloat("r_psm_far")); - for (auto entity : m_Scene->m_Storage->View()) { - auto id = entity.Get().Get(); - auto& lightSource = entity.Get(); - if (lightSource.type != LightSourceType::Point) { + U32 size = Console::GetInt("r_psm_size"); + glm::mat4 shadow_proj = glm::perspective(glm::radians(90.f), 1.f, Console::GetFloat("r_psm_near"), Console::GetFloat("r_psm_far")); + for (auto entity : scene_->storage_->View()) { + auto id = entity.Get().Get(); + auto& light_source = entity.Get(); + if (light_source.Type != LightSourceType::Point) { continue; } Ref fbo; - if (m_PointShadowCubemaps.find(id) == m_PointShadowCubemaps.end()) { + if (point_shadow_cubemaps_.find(id) == point_shadow_cubemaps_.end()) { auto map = CubeMap::Create(size, Texture::Format::F32, Texture::Channels::Depth, false, true); fbo = FrameBuffer::Create({size, size}); fbo->SetDepthAttachment(map); - m_PointShadowCubemaps[id] = map; - m_PointShadowFrameBuffers[id] = fbo; + point_shadow_cubemaps_[id] = map; + point_shadow_map_[id] = fbo; } else { - fbo = m_PointShadowFrameBuffers[id]; + fbo = point_shadow_map_[id]; } fbo->Bind(); Renderer::Enable(RenderSetting::FaceCulling); Renderer::SetViewport(size, size); Renderer::Clear(); - auto pos = lightSource.position; - std::vector shadowMatrices(6); - shadowMatrices[0] = shadowProj * glm::lookAt(pos, pos + glm::vec3(1., 0., 0.), glm::vec3(0., -1., 0.)); - shadowMatrices[1] = shadowProj * glm::lookAt(pos, pos + glm::vec3(-1., 0., 0.), glm::vec3(0., -1., 0.)); - shadowMatrices[2] = shadowProj * glm::lookAt(pos, pos + glm::vec3(0., 1., 0.), glm::vec3(0., 0., 1.)); - shadowMatrices[3] = shadowProj * glm::lookAt(pos, pos + glm::vec3(0., -1., 0.), glm::vec3(0., 0., -1.)); - shadowMatrices[4] = shadowProj * glm::lookAt(pos, pos + glm::vec3(0., 0., 1.), glm::vec3(0., -1., 0.)); - shadowMatrices[5] = shadowProj * glm::lookAt(pos, pos + glm::vec3(0., 0., -1.), glm::vec3(0., -1., 0.)); + auto pos = light_source.Position; + std::vector shadow_matrices(6); + shadow_matrices[0] = shadow_proj * glm::lookAt(pos, pos + glm::vec3(1., 0., 0.), glm::vec3(0., -1., 0.)); + shadow_matrices[1] = shadow_proj * glm::lookAt(pos, pos + glm::vec3(-1., 0., 0.), glm::vec3(0., -1., 0.)); + shadow_matrices[2] = shadow_proj * glm::lookAt(pos, pos + glm::vec3(0., 1., 0.), glm::vec3(0., 0., 1.)); + shadow_matrices[3] = shadow_proj * glm::lookAt(pos, pos + glm::vec3(0., -1., 0.), glm::vec3(0., 0., -1.)); + shadow_matrices[4] = shadow_proj * glm::lookAt(pos, pos + glm::vec3(0., 0., 1.), glm::vec3(0., -1., 0.)); + shadow_matrices[5] = shadow_proj * glm::lookAt(pos, pos + glm::vec3(0., 0., -1.), glm::vec3(0., -1., 0.)); for (size_t i = 0; i < 6; i++) { - shader->SetMat4(std::format("shadowMatrices[{}]", i), shadowMatrices[i]); + shader->SetMat4(std::format("shadowMatrices[{}]", i), shadow_matrices[i]); } shader->SetFloat("far_plane", Console::GetFloat("r_psm_far")); shader->SetFloat3("lightPos", pos); - for (auto e : m_Scene->View()) { - auto mesh = e.Get().mesh; - int res = (mesh->p_Animator ? 1 : 0); + for (auto e : scene_->View()) { + auto mesh = e.Get().Mesh; + int res = (mesh->Animator ? 1 : 0); shader->SetInt("u_Animated", res); - if (mesh->p_Animator) { - mesh->p_Animator->SetMatricies(shader); + if (mesh->Animator) { + mesh->Animator->SetMatricies(shader); } Mat4 transform(1.0f); if (e.Has()) { transform = e.Get().GetTransform(); } for (const auto& submesh : mesh->GetSubMeshes()) { - Renderer::Submit(submesh.vertex_array, shader, transform); + Renderer::Submit(submesh.VertexArray, shader, transform); } } Renderer::Disable(RenderSetting::FaceCulling); @@ -141,30 +142,30 @@ namespace DE { } { DE_PROFILE_SCOPE("Shader Update"); - auto skyboxes = m_Scene->m_Storage->View(); + auto skyboxes = scene_->storage_->View(); if (!skyboxes.Empty()) { skybox = *skyboxes.begin(); } - UpdateShaders(camera, skybox, lightCamera); + UpdateShaders(camera, skybox, light_camera); } { DE_PROFILE_SCOPE("Mesh Rendering"); - m_FrameBuffer->Bind(); - m_Lights->Bind(LIGHT_UB_ID); - if (settings.use_directional_shadow_map) { - m_ShadowMap->GetDepthAttachment()->Bind(12); + frame_buffer_->Bind(); + lights_->Bind(kLightUniformBufferID); + if (Settings.UseDirectionalShadowMap) { + shadow_map_->GetDepthAttachment()->Bind(12); } - if (settings.use_point_shadows) { + if (Settings.UsePointShadows) { int idx = 0; - for (auto entity : m_Scene->m_Storage->View()) { - if (entity.Get().type == LightSourceType::Point) { + for (auto entity : scene_->storage_->View()) { + if (entity.Get().Type == LightSourceType::Point) { auto id = entity.Get().Get(); - m_PointShadowCubemaps[id]->Bind(15 + idx); + point_shadow_cubemaps_[id]->Bind(15 + idx); idx++; } } } - Renderer::SetViewport(m_FrameBuffer->GetWidth(), m_FrameBuffer->GetHeight()); + Renderer::SetViewport(frame_buffer_->GetWidth(), frame_buffer_->GetHeight()); Renderer::Clear(); if (skybox.Valid()) { Mat4 transform = Mat4(1.0); @@ -173,35 +174,35 @@ namespace DE { } Renderer::Submit(skybox.Get()->GetMap(), camera, transform); } - for (auto e : m_Scene->View()) { + for (auto e : scene_->View()) { auto& component = e.Get(); if (component.Valid()) { component->OnRender(); } } - for (auto e : m_Scene->View()) { - auto shader = e.Get().shader; - auto mesh = e.Get().mesh; - int res = (mesh->p_Animator ? 1 : 0); + for (auto e : scene_->View()) { + auto shader = e.Get().Shader; + auto mesh = e.Get().Mesh; + int res = (mesh->Animator ? 1 : 0); shader->Bind(); shader->SetInt("u_Animated", res); - if (mesh->p_Animator) { - mesh->p_Animator->SetMatricies(shader); + if (mesh->Animator) { + mesh->Animator->SetMatricies(shader); } Mat4 transform(1.0f); if (e.Has()) { transform = e.Get().GetTransform(); } - if (settings.use_directional_shadow_map) { + if (Settings.UseDirectionalShadowMap) { shader->SetInt("u_UseShadowMap", 1); shader->SetInt("u_ShadowMap", 12); } - if (settings.use_point_shadows) { + if (Settings.UsePointShadows) { shader->SetInt("u_UsePointShadowMap", 1); shader->SetFloat("u_ShadowFarPlane", Console::GetFloat("r_psm_far")); int idx = 0; - for (auto entity : m_Scene->m_Storage->View()) { - if (entity.Get().type == LightSourceType::Point) { + for (auto entity : scene_->storage_->View()) { + if (entity.Get().Type == LightSourceType::Point) { shader->SetInt(std::format("u_PointShadowMap[{}]", idx), 15 + idx); idx++; } @@ -211,50 +212,50 @@ namespace DE { } Renderer::Submit(mesh, shader, transform); } - m_FrameBuffer->UnBind(); + frame_buffer_->UnBind(); } { DE_PROFILE_SCOPE("Post-Processing"); - if (settings.bloom) { + if (Settings.Bloom) { DE_PROFILE_SCOPE("Bloom"); - Renderer::Bloom(m_FrameBuffer->GetColorAttachment(0), - settings.bloom_threshold, - settings.bloom_soft_threshold, - settings.bloom_radius, - settings.bloom_depth, - settings.bloom_strength); + Renderer::Bloom(frame_buffer_->GetColorAttachment(0), + Settings.BloomThreshold, + Settings.BloomSoftThreshold, + Settings.BloomRadius, + Settings.BloomDepth, + Settings.BloomStrength); } - if (settings.gamma_tone_mapping) { + if (Settings.GammaToneMapping) { DE_PROFILE_SCOPE("Gamma & HDR"); - Renderer::GammeHDRCorrecion(m_FrameBuffer->GetColorAttachment(0), settings.exposure, settings.gamma); + Renderer::GammeHDRCorrecion(frame_buffer_->GetColorAttachment(0), Settings.Exposure, Settings.Gamma); } } } - void SceneRenderer::UpdateShaders(const FPSCamera& camera, Entity skybox, const FPSCamera& lightCamera) { + void SceneRenderer::UpdateShaders(const FPSCamera& camera, Entity skybox, const FPSCamera& light_camera) { DE_PROFILE_SCOPE("UpdateShaders"); int cnt_light_sources = 0; - for (auto enitity : m_Scene->m_Storage->View()) { - auto& light_source = enitity.Get(); - m_Lights->at(cnt_light_sources).Get(0) = light_source.ambient; - m_Lights->at(cnt_light_sources).Get(1) = light_source.diffuse; - m_Lights->at(cnt_light_sources).Get(2) = light_source.specular; - m_Lights->at(cnt_light_sources).Get(3) = light_source.direction; - m_Lights->at(cnt_light_sources).Get(4) = light_source.position; - m_Lights->at(cnt_light_sources).Get(5) = light_source.clq; - m_Lights->at(cnt_light_sources).Get(6) = - Vec3(light_source.outer_cone_cos, light_source.inner_cone_cos, LightSourceTypeToId(light_source.type)); + for (auto enitity : scene_->storage_->View()) { + auto& light_source = enitity.Get(); + lights_->At(cnt_light_sources).Get(0) = light_source.Ambient; + lights_->At(cnt_light_sources).Get(1) = light_source.Diffuse; + lights_->At(cnt_light_sources).Get(2) = light_source.Specular; + lights_->At(cnt_light_sources).Get(3) = light_source.Direction; + lights_->At(cnt_light_sources).Get(4) = light_source.Position; + lights_->At(cnt_light_sources).Get(5) = light_source.CLQ; + lights_->At(cnt_light_sources).Get(6) = + Vec3(light_source.OuterConeCosinus, light_source.InnerConeCosinus, LightSourceTypeToId(light_source.Type)); cnt_light_sources++; } - m_Lights->PushData(); - for (auto [id, shader] : m_Shaders) { + lights_->PushData(); + for (auto [id, shader] : shaders_) { shader->Bind(); if (skybox.Valid() && skybox.Has()) { skybox.Get()->ApplyIBL(shader); if (skybox.Has()) { auto& transform = skybox.Get(); - Vec3 rotation = -(transform.rotation + transform.rotation_offet); + Vec3 rotation = -(transform.Rotation + transform.RotationOffet); Mat4 mt_rotation = glm::toMat4(glm::quat(glm::radians(rotation))); shader->SetMat4("u_EnvRotation", mt_rotation); } @@ -262,40 +263,40 @@ namespace DE { shader->SetInt("u_LightAmount", cnt_light_sources); shader->SetMat4("u_Camera.view", camera.GetViewMatrix()); shader->SetMat4("u_Camera.projection", camera.GetProjectionMatrix()); - if (settings.use_directional_shadow_map) { - shader->SetMat4("u_DirectionalShadowMapCamera.view", lightCamera.GetViewMatrix()); - shader->SetMat4("u_DirectionalShadowMapCamera.projection", lightCamera.GetOrthoProjectionMatrix()); + if (Settings.UseDirectionalShadowMap) { + shader->SetMat4("u_DirectionalShadowMapCamera.view", light_camera.GetViewMatrix()); + shader->SetMat4("u_DirectionalShadowMapCamera.projection", light_camera.GetOrthoProjectionMatrix()); shader->SetInt("u_DirectionalShadowMap", 1); } } } Ref SceneRenderer::GetFrameBuffer() { - return m_FrameBuffer; + return frame_buffer_; } Ref SceneRenderer::GetShadowMap() { - return m_ShadowMap; + return shadow_map_; } void SceneRenderer::RequestShader(UUID shader_id) { - if (!m_Shaders.contains(shader_id)) { + if (!shaders_.contains(shader_id)) { auto shader = ResourceManager::GetShader(shader_id); if (shader) { - m_Shaders[shader_id] = shader.value(); - m_Shaders[shader_id]->SetUnifromBlock("ub_Lights", LIGHT_UB_ID); + shaders_[shader_id] = shader.value(); + shaders_[shader_id]->SetUnifromBlock("ub_Lights", kLightUniformBufferID); } else { LOG_WARNING("Shader {} not found in ResourceManager", shader_id); } } } - void SceneRenderer::initializeShadowMap() { - m_ShadowMap = + void SceneRenderer::InitializeShadowMap() { + shadow_map_ = FrameBuffer::Create({static_cast(Console::GetInt("r_shadowmap_width")), static_cast(Console::GetInt("r_shadowmap_height"))}); - m_ShadowMap->SetDepthAttachment(Texture::Format::F32); + shadow_map_->SetDepthAttachment(Texture::Format::F32); Console::OnCommand("r_shadowmap_resize", [&]() { LOG_INFO("ShadowMap resize"); - m_ShadowMap->Resize(static_cast(Console::GetInt("r_shadowmap_width")), static_cast(Console::GetInt("r_shadowmap_height"))); + shadow_map_->Resize(static_cast(Console::GetInt("r_shadowmap_width")), static_cast(Console::GetInt("r_shadowmap_height"))); }); } -} // namespace DE \ No newline at end of file +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Scene/SceneRenderer.h b/DummyEngine/Core/Scene/SceneRenderer.h index f1e13a6..cd98c95 100644 --- a/DummyEngine/Core/Scene/SceneRenderer.h +++ b/DummyEngine/Core/Scene/SceneRenderer.h @@ -1,52 +1,60 @@ #pragma once #include "DummyEngine/Core/ECS/ECS.h" -#include "DummyEngine/Core/Rendering/Renderer/FrameBuffer.h" -#include "DummyEngine/Core/Rendering/Renderer/Shader.h" -#include "DummyEngine/Core/Rendering/Renderer/UniformBuffer.h" +#include "DummyEngine/Core/Objects/Cameras/FPSCamera.h" #include "DummyEngine/Core/Scene/Scene.h" -#include "DummyEngine/Utils/Base.h" -namespace DE { +namespace DummyEngine { + + class Shader; + class UniformBuffer; + class FrameBuffer; + class CubeMap; + class SceneRenderer { - LOGGER_AUTHOR(SceneRenderer) + LOG_AUTHOR(SceneRenderer) public: - struct Settings { - bool bloom = false; - float bloom_threshold = 1; - float bloom_soft_threshold = 0; - float bloom_radius = 0.005; - float bloom_strength = 0.04; - U32 bloom_depth = 5; - - bool gamma_tone_mapping = false; - float exposure = 1; - float gamma = 1; - - bool use_directional_shadow_map = false; - bool use_point_shadows = false; - }; - Settings settings; - SceneRenderer(Scene* scene); + explicit SceneRenderer(Scene* scene); void Render(Entity camera); void OnViewPortResize(U32 x, U32 y); Ref GetFrameBuffer(); Ref GetShadowMap(); - void initializeShadowMap(); - + void InitializeShadowMap(); void RequestShader(UUID shader_id); + public: + struct GraphicsSettings { + bool Bloom = false; + float BloomThreshold = 1; + float BloomSoftThreshold = 0; + float BloomRadius = 0.005; + float BloomStrength = 0.04; + U32 BloomDepth = 5; + + bool GammaToneMapping = false; + float Exposure = 1; + float Gamma = 1; + + bool UseDirectionalShadowMap = false; + bool UsePointShadows = false; + }; + + public: + GraphicsSettings Settings; + private: - void UpdateShaders(const FPSCamera& camera, Entity skybox, const FPSCamera& lightCamera); - - Scene* m_Scene; - Ref m_Lights; - Ref m_FrameBuffer; - Ref m_ShadowMap; - std::unordered_map> m_PointShadowFrameBuffers; - std::unordered_map> m_PointShadowCubemaps; - std::unordered_map> m_Shaders; + void UpdateShaders(const FPSCamera& camera, Entity skybox, const FPSCamera& light_camera); + + private: + Scene* scene_; + Ref lights_; + Ref frame_buffer_; + Ref shadow_map_; + std::unordered_map> point_shadow_map_; + std::unordered_map> point_shadow_cubemaps_; + std::unordered_map> shaders_; }; -} // namespace DE \ No newline at end of file + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Scripting/Script.cpp b/DummyEngine/Core/Scripting/Script.cpp index 5b82866..4446392 100644 --- a/DummyEngine/Core/Scripting/Script.cpp +++ b/DummyEngine/Core/Scripting/Script.cpp @@ -1,6 +1,6 @@ -#include "DummyEngine/Core/Scripting/Script.h" +#include "Script.h" -namespace DE { +namespace DummyEngine { std::string ScriptFieldTypeToString(ScriptFieldType type) { switch (type) { @@ -73,25 +73,25 @@ namespace DE { } bool Script::FieldIterator::operator==(const FieldIterator& other) const { - return m_Script == other.m_Script && m_Iterator == other.m_Iterator; + return script_ == other.script_ && iterator_ == other.iterator_; } bool Script::FieldIterator::operator!=(const FieldIterator& other) const { - return m_Script != other.m_Script || m_Iterator != other.m_Iterator; + return script_ != other.script_ || iterator_ != other.iterator_; } Script::FieldIterator& Script::FieldIterator::operator++() { - ++m_Iterator; + ++iterator_; return *this; } Script::FieldIterator Script::FieldIterator::operator++(int) { FieldIterator result = *this; - ++m_Iterator; + ++iterator_; return result; } std::pair, Script::Field> Script::FieldIterator::operator*() const { - return {std::cref(m_Iterator->first), Field(m_Iterator->second.type, (char*)m_Script + m_Iterator->second.offset)}; + return {std::cref(iterator_->first), Field(iterator_->second.Type, (char*)script_ + iterator_->second.Offset)}; } - Script::FieldIterator::FieldIterator(Script* owner, Iterator it) : m_Iterator(it), m_Script(owner) {} + Script::FieldIterator::FieldIterator(Script* owner, Iterator it) : iterator_(it), script_(owner) {} Script::FieldIterator Script::begin() { return FieldIterator(this, GetClassFields().begin()); @@ -99,7 +99,7 @@ namespace DE { Script::FieldIterator Script::end() { return FieldIterator(this, GetClassFields().end()); } - Script::Field::Field(ScriptFieldType type, void* ptr) : m_Type(type), m_Data(ptr) {} + Script::Field::Field(ScriptFieldType type, void* ptr) : type_(type), data_(ptr) {} void Script::AttachToScene(WeakRef scene, Entity entity) { m_Scene = scene; @@ -109,7 +109,7 @@ namespace DE { ScriptFieldType Script::GetFieldType(const std::string& name) const { if (GetClassFields().contains(name)) { - return GetClassFields().at(name).type; + return GetClassFields().at(name).Type; } return ScriptFieldType::None; } @@ -122,4 +122,4 @@ namespace DE { Ref Script::GetScene() const { return m_Scene.lock(); } -} // namespace DE +} // namespace DummyEngine diff --git a/DummyEngine/Core/Scripting/Script.h b/DummyEngine/Core/Scripting/Script.h index 5d559e1..a3f9d17 100644 --- a/DummyEngine/Core/Scripting/Script.h +++ b/DummyEngine/Core/Scripting/Script.h @@ -2,9 +2,9 @@ #include "DummyEngine/Core/ECS/ECS.h" #include "DummyEngine/Core/Scene/Scene.h" -#include "DummyEngine/Utils/Base.h" +#include "DummyEngine/Utils/Helpers/CompilerSpecific.h" -namespace DE { +namespace DummyEngine { enum class ScriptFieldType { None = 0, @@ -26,8 +26,8 @@ namespace DE { Entity, }; struct ScriptClassField { - ScriptFieldType type; - U32 offset; + ScriptFieldType Type; + U32 Offset; }; class Script { @@ -41,12 +41,12 @@ namespace DE { Field(ScriptFieldType type, void* ptr); template T& Get(); template const T& Get() const; - ScriptFieldType GetType() const { return m_Type; } - void* Get() const { return m_Data; } + ScriptFieldType GetType() const { return type_; } + void* Get() const { return data_; } private: - ScriptFieldType m_Type; - void* m_Data; + ScriptFieldType type_; + void* data_; }; class FieldIterator { public: @@ -60,8 +60,8 @@ namespace DE { friend class Script; FieldIterator(Script* owner, Iterator it); - Iterator m_Iterator; - Script* m_Script; + Iterator iterator_; + Script* script_; }; Script() = default; @@ -78,8 +78,8 @@ namespace DE { virtual void OnRuntimeStop() {} virtual void OnDetach() {} - FieldIterator begin(); - FieldIterator end(); + FieldIterator begin(); // NOLINT + FieldIterator end(); // NOLINT template T& GetField(const std::string& name); ScriptFieldType GetFieldType(const std::string& name) const; @@ -109,26 +109,26 @@ namespace DE { // clang-format on template T& Script::Field::Get() { - DE_ASSERT(m_Type == TypeToScriptFieldType(), + DE_ASSERT(type_ == TypeToScriptFieldType(), "Wrong field type {} expected {}", ScriptFieldTypeToString(TypeToScriptFieldType()), - ScriptFieldTypeToString(m_Type)); - return *(T*)m_Data; + ScriptFieldTypeToString(type_)); + return *(T*)data_; } template const T& Script::Field::Get() const { - DE_ASSERT(m_Type == TypeToScriptFieldType(), + DE_ASSERT(type_ == TypeToScriptFieldType(), "Wrong field type {} expected {}", ScriptFieldTypeToString(TypeToScriptFieldType()), - ScriptFieldTypeToString(m_Type)); - return *(T*)m_Data; + ScriptFieldTypeToString(type_)); + return *(T*)data_; } template T& Script::GetField(const std::string& name) { DE_ASSERT(GetClassFields().contains(name), "Wrong field name(", name, ")"); - DE_ASSERT(GetClassFields().at(name).type == TypeToScriptFieldType(), + DE_ASSERT(GetClassFields().at(name).Type == TypeToScriptFieldType(), "Wrong field type {} expected {}", ScriptFieldTypeToString(TypeToScriptFieldType()), - ScriptFieldTypeToString(GetClassFields().at(name).type)); - return *(T*)((char*)this + GetClassFields().at(name).offset); + ScriptFieldTypeToString(GetClassFields().at(name).Type)); + return *(T*)((char*)this + GetClassFields().at(name).Offset); } template T& Script::Add(const T& t) { DE_ASSERT(m_Entity.Valid(), "Using invalid entity in script"); @@ -172,4 +172,4 @@ protected: delete script; \ } -} // namespace DE +} // namespace DummyEngine diff --git a/DummyEngine/Core/Scripting/ScriptClass.cpp b/DummyEngine/Core/Scripting/ScriptClass.cpp index 0632351..e1c3cfa 100644 --- a/DummyEngine/Core/Scripting/ScriptClass.cpp +++ b/DummyEngine/Core/Scripting/ScriptClass.cpp @@ -1,25 +1,27 @@ -#include "DummyEngine/Core/Scripting/ScriptClass.h" +#include "ScriptClass.h" -namespace DE { - ScriptClass::ScriptClass(const std::string& name) : m_Name(name) {} +namespace DummyEngine { + + ScriptClass::ScriptClass(const std::string& name) : name_(name) {} bool ScriptClass::Load(Ref library) { if (!library->Valid()) { return false; } - m_Library = library; + library_ = library; - f_create = reinterpret_cast(library->GetFunction(m_Name + "Create")); - f_delete = reinterpret_cast(library->GetFunction(m_Name + "Delete")); + f_create_ = reinterpret_cast(library->GetFunction(name_ + "Create")); + f_delete_ = reinterpret_cast(library->GetFunction(name_ + "Delete")); return Valid(); } bool ScriptClass::Valid() { - auto ptr = m_Library.lock(); + auto ptr = library_.lock(); if (!ptr) { return false; } - return ptr->Valid() && f_create && f_delete; + return ptr->Valid() && f_create_ != nullptr && f_delete_ != nullptr; } const std::string& ScriptClass::GetName() const { - return m_Name; + return name_; } -} // namespace DE \ No newline at end of file + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Scripting/ScriptClass.h b/DummyEngine/Core/Scripting/ScriptClass.h index e88e2ce..5dd19ca 100644 --- a/DummyEngine/Core/Scripting/ScriptClass.h +++ b/DummyEngine/Core/Scripting/ScriptClass.h @@ -2,9 +2,8 @@ #include "DummyEngine/Core/Scripting/Script.h" #include "DummyEngine/Core/Scripting/SharedObject.h" -#include "DummyEngine/Utils/Base.h" -namespace DE { +namespace DummyEngine { class ScriptClass { public: @@ -12,20 +11,20 @@ namespace DE { using FDelete = void (*)(Script*); ScriptClass() = default; - ScriptClass(const std::string& name); + explicit ScriptClass(const std::string& name); bool Load(Ref library); bool Valid(); const std::string& GetName() const; - inline Script* Create() { return f_create(); } - inline void Delete(Script* ptr) { f_delete(ptr); } + inline Script* Create() { return f_create_(); } + inline void Delete(Script* ptr) { f_delete_(ptr); } private: - std::string m_Name; - WeakRef m_Library; + std::string name_; + WeakRef library_; - FCreate f_create = nullptr; - FDelete f_delete = nullptr; + FCreate f_create_ = nullptr; + FDelete f_delete_ = nullptr; }; -} // namespace DE +} // namespace DummyEngine diff --git a/DummyEngine/Core/Scripting/ScriptEngine.cpp b/DummyEngine/Core/Scripting/ScriptEngine.cpp index 76de3da..b4e328b 100644 --- a/DummyEngine/Core/Scripting/ScriptEngine.cpp +++ b/DummyEngine/Core/Scripting/ScriptEngine.cpp @@ -1,76 +1,75 @@ -#include "DummyEngine/Core/Scripting/ScriptEngine.h" +#include "ScriptEngine.h" #include "DummyEngine/Core/ResourceManaging/AssetManager.h" -#include "DummyEngine/Core/Scene/Components.h" #include "DummyEngine/Core/Scene/Scene.h" -namespace DE { +namespace DummyEngine { SINGLETON_BASE(ScriptEngine); - ScriptComponent::ScriptComponent(U32 id) : m_ID(id) { - ScriptEngine::IncreaseRefCount(m_ID); + ScriptComponent::ScriptComponent(U32 id) : id_(id) { + ScriptEngine::IncreaseRefCount(id_); } ScriptComponent::ScriptComponent(const ScriptComponent& other) { - m_ID = other.m_ID; - if (other.m_ID != UINT32_MAX) { - ScriptEngine::IncreaseRefCount(m_ID); + id_ = other.id_; + if (other.id_ != UINT32_MAX) { + ScriptEngine::IncreaseRefCount(id_); } } ScriptComponent::ScriptComponent(ScriptComponent&& other) { - m_ID = other.m_ID; - other.m_ID = UINT32_MAX; + id_ = other.id_; + other.id_ = UINT32_MAX; } ScriptComponent& ScriptComponent::operator=(const ScriptComponent& other) { if (&other != this) { - if (m_ID != UINT32_MAX) { - ScriptEngine::DecreaseRefCount(m_ID); + if (id_ != UINT32_MAX) { + ScriptEngine::DecreaseRefCount(id_); } - m_ID = other.m_ID; - if (other.m_ID != UINT32_MAX) { - ScriptEngine::IncreaseRefCount(m_ID); + id_ = other.id_; + if (other.id_ != UINT32_MAX) { + ScriptEngine::IncreaseRefCount(id_); } } return *this; } ScriptComponent& ScriptComponent::operator=(ScriptComponent&& other) { if (&other != this) { - if (m_ID != UINT32_MAX) { - ScriptEngine::DecreaseRefCount(m_ID); + if (id_ != UINT32_MAX) { + ScriptEngine::DecreaseRefCount(id_); } - m_ID = other.m_ID; - other.m_ID = UINT32_MAX; + id_ = other.id_; + other.id_ = UINT32_MAX; } return *this; } ScriptComponent::~ScriptComponent() { - if (m_ID != UINT32_MAX) { - ScriptEngine::DecreaseRefCount(m_ID); + if (id_ != UINT32_MAX) { + ScriptEngine::DecreaseRefCount(id_); } } UUID ScriptComponent::ID() const { - return ScriptEngine::Get().m_ProxyManager.GetProxy(m_ID).m_ScriptID; + return ScriptEngine::GetInstance().proxy_manager_.GetProxy(id_).ScriptID; } bool ScriptComponent::Valid() const { - return m_ID != UINT32_MAX && ScriptEngine::Get().m_ProxyManager.GetProxy(m_ID).m_Script; + return id_ != UINT32_MAX && ScriptEngine::GetInstance().proxy_manager_.GetProxy(id_).Script != nullptr; } Script& ScriptComponent::operator*() { - return *ScriptEngine::Get().m_ProxyManager.GetProxy(m_ID).m_Script; + return *ScriptEngine::GetInstance().proxy_manager_.GetProxy(id_).Script; } Script* ScriptComponent::operator->() { - return ScriptEngine::Get().m_ProxyManager.GetProxy(m_ID).m_Script; + return ScriptEngine::GetInstance().proxy_manager_.GetProxy(id_).Script; } bool ScriptProxyManager::Iterator::operator==(const Iterator& other) const { - return m_Manager == other.m_Manager && m_ID == other.m_ID; + return manager_ == other.manager_ && id_ == other.id_; } bool ScriptProxyManager::Iterator::operator!=(const Iterator& other) const { - return m_ID != other.m_ID || m_Manager != other.m_Manager; + return id_ != other.id_ || manager_ != other.manager_; } ScriptProxyManager::Iterator& ScriptProxyManager::Iterator::operator++() { do { - ++m_ID; - } while (m_ID < m_Manager->m_States.size() && !m_Manager->m_States[m_ID]); + ++id_; + } while (id_ < manager_->states_.size() && !manager_->states_[id_]); return *this; } ScriptProxyManager::Iterator ScriptProxyManager::Iterator::operator++(int) { @@ -79,56 +78,56 @@ namespace DE { return res; } ScriptProxy& ScriptProxyManager::Iterator::operator*() { - return m_Manager->m_Proxys[m_ID]; + return manager_->proxys_[id_]; } ScriptProxy* ScriptProxyManager::Iterator::operator->() { - return &(m_Manager->m_Proxys[m_ID]); + return &(manager_->proxys_[id_]); } - ScriptProxyManager::Iterator::Iterator(ScriptProxyManager* manager, U32 id) : m_Manager(manager), m_ID(id) {} + ScriptProxyManager::Iterator::Iterator(ScriptProxyManager* manager, U32 id) : manager_(manager), id_(id) {} ScriptProxyManager::Iterator ScriptProxyManager::begin() { U32 id = 0; - while (id < m_States.size() && !m_States[id]) { + while (id < states_.size() && !states_[id]) { ++id; } return Iterator(this, id); } ScriptProxyManager::Iterator ScriptProxyManager::end() { - return Iterator(this, m_States.size()); + return Iterator(this, states_.size()); } void ScriptProxyManager::Clear() { - m_States.clear(); - m_Proxys.clear(); - m_States.clear(); + states_.clear(); + proxys_.clear(); + states_.clear(); } void ScriptProxyManager::Destroy(U32 id) { - m_AvailableIds.push_back(id); - m_States[id] = false; + available_ids_.push_back(id); + states_[id] = false; } void ScriptProxyManager::Destroy(Iterator it) { - Destroy(it.m_ID); + Destroy(it.id_); } ScriptProxy& ScriptProxyManager::GetProxy(U32 id) { - return m_Proxys[id]; + return proxys_[id]; } U32 ScriptProxyManager::CreateProxy() { ExtendIfRequired(); - U32 id = m_AvailableIds.front(); - m_AvailableIds.pop_front(); - m_States[id] = true; - m_Proxys[id].m_ScriptID = UUID(); - m_Proxys[id].m_Script = nullptr; + U32 id = available_ids_.front(); + available_ids_.pop_front(); + states_[id] = true; + proxys_[id].ScriptID = UUID(); + proxys_[id].Script = nullptr; return id; } void ScriptProxyManager::ExtendIfRequired() { - if (m_AvailableIds.empty()) { - m_AvailableIds.push_back(m_Proxys.size()); - m_Proxys.push_back({nullptr, 0, UUID()}); - m_States.push_back(false); + if (available_ids_.empty()) { + available_ids_.push_back(proxys_.size()); + proxys_.push_back({nullptr, 0, UUID()}); + states_.push_back(false); } } @@ -148,20 +147,20 @@ namespace DE { LOG_WARNING("ScriptAsset {} was not found in AssetManager", id); return false; } - const auto& name = asset.value().name; + const auto& name = asset.value().Name; - if (m_ScriptClasses.contains(id)) { + if (script_classes_.contains(id)) { LOG_WARNING("Script {} wasn't added because already exists", id); return false; } - m_ScriptClasses[id] = ScriptClass(name); - for (auto lib : m_Libraries) { - m_ScriptClasses[id].Load(lib); - if (m_ScriptClasses[id].Valid()) { + script_classes_[id] = ScriptClass(name); + for (auto lib : libraries_) { + script_classes_[id].Load(lib); + if (script_classes_[id].Valid()) { LOG_INFO("Script ({}|{}) found in library {}", name, id, lib->GetName()); - for (auto& instance : m_ProxyManager) { - if (instance.m_ScriptID == id) { - instance.m_Script = m_ScriptClasses[id].Create(); + for (auto& instance : proxy_manager_) { + if (instance.ScriptID == id) { + instance.Script = script_classes_[id].Create(); LOG_INFO("Created instance of ({}|{})", name, id); } } @@ -172,49 +171,49 @@ namespace DE { return false; } S_METHOD_IMPL(bool, DeleteScript, (UUID id), (id)) { - if (!m_ScriptClasses.contains(id)) { + if (!script_classes_.contains(id)) { LOG_WARNING("Script {} was not deleted because does not exists", id); return false; } - if (m_ScriptClasses[id].Valid()) { - for (auto& instance : m_ProxyManager) { - if (instance.m_ScriptID == id) { - m_ScriptClasses[id].Delete(instance.m_Script); - instance.m_Script = nullptr; - LOG_INFO("Deleted instance of ({}|{})", m_ScriptClasses[id].GetName(), id); + if (script_classes_[id].Valid()) { + for (auto& instance : proxy_manager_) { + if (instance.ScriptID == id) { + script_classes_[id].Delete(instance.Script); + instance.Script = nullptr; + LOG_INFO("Deleted instance of ({}|{})", script_classes_[id].GetName(), id); } } } - m_ScriptClasses.erase(id); + script_classes_.erase(id); LOG_INFO("Script {} was deleted", id); return true; } S_METHOD_IMPL(bool, ValidScript, (UUID id), (id)) { - return m_ScriptClasses.contains(id) && m_ScriptClasses[id].Valid(); + return script_classes_.contains(id) && script_classes_[id].Valid(); } S_METHOD_IMPL(Unit, ClearScripts, (), ()) { - for (auto& instance : m_ProxyManager) { - if (instance.m_Script) { - DE_ASSERT(m_ScriptClasses.contains(instance.m_ScriptID), "Internal state broken"); - m_ScriptClasses[instance.m_ScriptID].Delete(instance.m_Script); - instance.m_Script = nullptr; - LOG_INFO("Deleted instance of ({}|{})", m_ScriptClasses[instance.m_ScriptID].GetName(), instance.m_ScriptID); + for (auto& instance : proxy_manager_) { + if (instance.Script != nullptr) { + DE_ASSERT(script_classes_.contains(instance.ScriptID), "Internal state broken"); + script_classes_[instance.ScriptID].Delete(instance.Script); + instance.Script = nullptr; + LOG_INFO("Deleted instance of ({}|{})", script_classes_[instance.ScriptID].GetName(), instance.ScriptID); } } - m_ScriptClasses.clear(); + script_classes_.clear(); LOG_INFO("Cleared all scripts"); return Unit(); } S_METHOD_IMPL(Unit, AddLibrary, (Ref library), (library)) { - for (size_t i = 0; i < m_Libraries.size(); ++i) { - if (m_Libraries[i]->GetName() == library->GetName()) { - DeleteLibrary(m_Libraries[i]->GetName()); + for (size_t i = 0; i < libraries_.size(); ++i) { + if (libraries_[i]->GetName() == library->GetName()) { + DeleteLibrary(libraries_[i]->GetName()); LOG_WARNING("Deleted library {} because already loaded", library->GetName()); break; } } - m_Libraries.push_back(library); + libraries_.push_back(library); UpdateScriptClasses(library); LOG_INFO("Library {} was added", library->GetName()); return Unit(); @@ -223,8 +222,8 @@ namespace DE { S32 id = -1; //*Find library { - for (size_t i = 0; i < m_Libraries.size(); ++i) { - if (m_Libraries[i]->GetName() == name) { + for (size_t i = 0; i < libraries_.size(); ++i) { + if (libraries_[i]->GetName() == name) { id = i; break; } @@ -235,27 +234,27 @@ namespace DE { } } - m_Libraries[id]->Invalidate(); + libraries_[id]->Invalidate(); //*Invalidate Instances { - for (auto& instance : m_ProxyManager) { - if (m_ScriptClasses.contains(instance.m_ScriptID) && !m_ScriptClasses[instance.m_ScriptID].Valid()) { - if (instance.m_Script) { - m_ScriptClasses[instance.m_ScriptID].Delete(instance.m_Script); - instance.m_Script = nullptr; - LOG_INFO("Deleted instance of ({}|{})", m_ScriptClasses[instance.m_ScriptID].GetName(), instance.m_ScriptID); + for (auto& instance : proxy_manager_) { + if (script_classes_.contains(instance.ScriptID) && !script_classes_[instance.ScriptID].Valid()) { + if (instance.Script != nullptr) { + script_classes_[instance.ScriptID].Delete(instance.Script); + instance.Script = nullptr; + LOG_INFO("Deleted instance of ({}|{})", script_classes_[instance.ScriptID].GetName(), instance.ScriptID); } } } } - m_Libraries.erase(m_Libraries.begin() + id); + libraries_.erase(libraries_.begin() + id); LOG_INFO("Library {} was deleted", name); return Unit(); } S_METHOD_IMPL(bool, LibraryLoaded, (const std::string& name), (name)) { - for (auto lib : m_Libraries) { + for (auto lib : libraries_) { if (lib->GetName() == name) { return true; } @@ -263,33 +262,33 @@ namespace DE { return false; } S_METHOD_IMPL(Unit, ClearLibraries, (), ()) { - for (auto lib : m_Libraries) { + for (auto lib : libraries_) { lib->Invalidate(); } - for (auto& instance : m_ProxyManager) { - if (instance.m_Script) { - DE_ASSERT(m_ScriptClasses.contains(instance.m_ScriptID), "Internal state broken"); - m_ScriptClasses[instance.m_ScriptID].Delete(instance.m_Script); - instance.m_Script = nullptr; - LOG_INFO("Deleted instance of ({}|{})", m_ScriptClasses[instance.m_ScriptID].GetName(), instance.m_ScriptID); + for (auto& instance : proxy_manager_) { + if (instance.Script != nullptr) { + DE_ASSERT(script_classes_.contains(instance.ScriptID), "Internal state broken"); + script_classes_[instance.ScriptID].Delete(instance.Script); + instance.Script = nullptr; + LOG_INFO("Deleted instance of ({}|{})", script_classes_[instance.ScriptID].GetName(), instance.ScriptID); } } - m_Libraries.clear(); + libraries_.clear(); LOG_INFO("Cleared all libraries"); return Unit(); } S_METHOD_IMPL(ScriptComponent, CreateScript, (UUID id), (id)) { - auto p_id = m_ProxyManager.CreateProxy(); - auto& proxy = m_ProxyManager.GetProxy(p_id); + auto p_id = proxy_manager_.CreateProxy(); + auto& proxy = proxy_manager_.GetProxy(p_id); ScriptComponent res(p_id); - proxy.m_ScriptID = id; - if (!m_ScriptClasses.contains(id)) { + proxy.ScriptID = id; + if (!script_classes_.contains(id)) { LOG_WARNING("Creating ScriptComponent of unknown ScriptClass {}", id); } else { - if (m_ScriptClasses[id].Valid()) { - proxy.m_Script = m_ScriptClasses[id].Create(); - LOG_INFO("Created instance of ({}|{})", m_ScriptClasses[id].GetName(), id); + if (script_classes_[id].Valid()) { + proxy.Script = script_classes_[id].Create(); + LOG_INFO("Created instance of ({}|{})", script_classes_[id].GetName(), id); } else { LOG_WARNING("Creating ScriptComponent of not yet loaded ScriptClass {}", id); } @@ -297,44 +296,44 @@ namespace DE { return res; } S_METHOD_IMPL(Unit, IncreaseRefCount, (U32 id), (id)) { - auto& proxy = m_ProxyManager.GetProxy(id); - ++proxy.m_RefCount; + auto& proxy = proxy_manager_.GetProxy(id); + ++proxy.RefCount; return Unit(); } S_METHOD_IMPL(Unit, DecreaseRefCount, (U32 id), (id)) { - auto& proxy = m_ProxyManager.GetProxy(id); - DE_ASSERT(proxy.m_RefCount != 0, "Ref Counter error"); - --proxy.m_RefCount; - if (proxy.m_RefCount == 0) { + auto& proxy = proxy_manager_.GetProxy(id); + DE_ASSERT(proxy.RefCount != 0, "Ref Counter error"); + --proxy.RefCount; + if (proxy.RefCount == 0) { Destroy(id); } return Unit(); } void ScriptEngine::Destroy(U32 id) { - ScriptProxy& proxy = m_ProxyManager.GetProxy(id); - if (proxy.m_Script) { - DE_ASSERT(m_ScriptClasses.contains(proxy.m_ScriptID), "Internal state broken"); - m_ScriptClasses[proxy.m_ScriptID].Delete(proxy.m_Script); - proxy.m_Script = nullptr; - LOG_INFO("Deleted instance of ({}|{})", m_ScriptClasses[proxy.m_ScriptID].GetName(), proxy.m_ScriptID); + ScriptProxy& proxy = proxy_manager_.GetProxy(id); + if (proxy.Script != nullptr) { + DE_ASSERT(script_classes_.contains(proxy.ScriptID), "Internal state broken"); + script_classes_[proxy.ScriptID].Delete(proxy.Script); + proxy.Script = nullptr; + LOG_INFO("Deleted instance of ({}|{})", script_classes_[proxy.ScriptID].GetName(), proxy.ScriptID); } - m_ProxyManager.Destroy(id); + proxy_manager_.Destroy(id); } void ScriptEngine::UpdateScriptClasses(Ref library) { - for (auto& [id, script_class] : m_ScriptClasses) { + for (auto& [id, script_class] : script_classes_) { if (!script_class.Valid()) { if (script_class.Load(library)) { LOG_INFO("ScriptClass {} was found in library {}", script_class.GetName(), library->GetName()); } } } - for (auto& instance : m_ProxyManager) { - if (!instance.m_Script && m_ScriptClasses.contains(instance.m_ScriptID) && m_ScriptClasses[instance.m_ScriptID].Valid()) { - instance.m_Script = m_ScriptClasses[instance.m_ScriptID].Create(); - LOG_INFO("Created instance of ({}|{})", m_ScriptClasses[instance.m_ScriptID].GetName(), instance.m_ScriptID); + for (auto& instance : proxy_manager_) { + if (instance.Script == nullptr && script_classes_.contains(instance.ScriptID) && script_classes_[instance.ScriptID].Valid()) { + instance.Script = script_classes_[instance.ScriptID].Create(); + LOG_INFO("Created instance of ({}|{})", script_classes_[instance.ScriptID].GetName(), instance.ScriptID); } } } -} // namespace DE \ No newline at end of file +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Scripting/ScriptEngine.h b/DummyEngine/Core/Scripting/ScriptEngine.h index 9fd97bf..db9915d 100644 --- a/DummyEngine/Core/Scripting/ScriptEngine.h +++ b/DummyEngine/Core/Scripting/ScriptEngine.h @@ -1,13 +1,11 @@ #pragma once -#include "DummyEngine/Core/ResourceManaging/Assets.h" -#include "DummyEngine/Core/ResourceManaging/HandleManager.h" #include "DummyEngine/Core/Scripting/Script.h" #include "DummyEngine/Core/Scripting/ScriptClass.h" #include "DummyEngine/Core/Scripting/SharedObject.h" -#include "DummyEngine/Utils/Base.h" -namespace DE { +namespace DummyEngine { + class ScriptComponent { public: ScriptComponent() = default; @@ -23,16 +21,16 @@ namespace DE { Script* operator->(); private: - ScriptComponent(U32 id); + explicit ScriptComponent(U32 id); friend class ScriptEngine; - U32 m_ID = UINT32_MAX; + U32 id_ = UINT32_MAX; }; struct ScriptProxy { - Script* m_Script = nullptr; - U32 m_RefCount = 0; - UUID m_ScriptID; + Script* Script = nullptr; + U32 RefCount = 0; + UUID ScriptID; }; class ScriptProxyManager { @@ -51,12 +49,12 @@ namespace DE { friend class ScriptProxyManager; Iterator(ScriptProxyManager* manager, U32 id); - ScriptProxyManager* m_Manager = nullptr; - U32 m_ID = 0; + ScriptProxyManager* manager_ = nullptr; + U32 id_ = 0; }; - Iterator begin(); - Iterator end(); + Iterator begin(); // NOLINT + Iterator end(); // NOLINT void Clear(); void Destroy(U32 id); @@ -68,13 +66,13 @@ namespace DE { private: void ExtendIfRequired(); - std::vector m_Proxys; - std::deque m_AvailableIds; - std::vector m_States; + std::vector proxys_; + std::deque available_ids_; + std::vector states_; }; class ScriptEngine : public Singleton { - LOGGER_AUTHOR(ScriptEngine) + LOG_AUTHOR(ScriptEngine) SINGLETON(ScriptEngine) public: S_METHOD_DEF(bool, AddScript, (UUID id)); @@ -98,8 +96,9 @@ namespace DE { void UpdateScriptClasses(Ref library); - std::vector> m_Libraries; - std::unordered_map m_ScriptClasses; - ScriptProxyManager m_ProxyManager; + std::vector> libraries_; + std::unordered_map script_classes_; + ScriptProxyManager proxy_manager_; }; -} // namespace DE \ No newline at end of file + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Scripting/SharedObject.h b/DummyEngine/Core/Scripting/SharedObject.h index 02721ad..3f35072 100644 --- a/DummyEngine/Core/Scripting/SharedObject.h +++ b/DummyEngine/Core/Scripting/SharedObject.h @@ -1,8 +1,8 @@ #pragma once -#include "DummyEngine/Utils/Base.h" +#include "DummyEngine/Utils/Types/Types.h" -namespace DE { +namespace DummyEngine { class SharedObjectImpl; @@ -10,6 +10,7 @@ namespace DE { public: SharedObject(); ~SharedObject(); + bool Load(const Path& directory, const std::string& name); void Invalidate(); @@ -19,6 +20,7 @@ namespace DE { const std::string& GetName() const; private: - Scope m_Impl; + Scope impl_; }; -} // namespace DE \ No newline at end of file + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/DummyEngine.h b/DummyEngine/DummyEngine.h index 43a5229..1791e92 100644 --- a/DummyEngine/DummyEngine.h +++ b/DummyEngine/DummyEngine.h @@ -1,25 +1,24 @@ #pragma once -#include "DummyEngine/Core/Application/Application.h" -#include "DummyEngine/Core/Application/Config.h" -#include "DummyEngine/Core/Application/FileSystem.h" -#include "DummyEngine/Core/ECS/ECS.h" -#include "DummyEngine/Core/Objects/Cameras/FPSCamera.h" -#include "DummyEngine/Core/Objects/LightSources/LightSource.h" -#include "DummyEngine/Core/Physics/PhysicsComponent.h" -#include "DummyEngine/Core/Rendering/Renderer/FrameBuffer.h" -#include "DummyEngine/Core/Rendering/Renderer/LocalBuffer.h" -#include "DummyEngine/Core/Rendering/Renderer/Renderer.h" -#include "DummyEngine/Core/Rendering/Renderer/Texture.h" -#include "DummyEngine/Core/ResourceManaging/AssetManager.h" -#include "DummyEngine/Core/ResourceManaging/ResourceManager.h" -#include "DummyEngine/Core/Scene/Components.h" -#include "DummyEngine/Core/Scene/Scene.h" -#include "DummyEngine/Core/Scene/SceneHierarchy.h" -#include "DummyEngine/Core/Scene/SceneRenderer.h" -#include "DummyEngine/Core/Scripting/ScriptEngine.h" -#include "DummyEngine/ToolBox/Editors/TextureEditor.h" -#include "DummyEngine/ToolBox/Loaders/ModelLoader.h" -#include "DummyEngine/ToolBox/Loaders/SceneLoader.h" -#include "DummyEngine/ToolBox/Loaders/TextureLoader.h" -#include "DummyEngine/Utils/Base.h" +#include "DummyEngine/Core/Application/Application.h" // IWYU pragma: export +#include "DummyEngine/Core/Application/Config.h" // IWYU pragma: export +#include "DummyEngine/Core/Application/FileSystem.h" // IWYU pragma: export +#include "DummyEngine/Core/Application/Input.h" // IWYU pragma: export +#include "DummyEngine/Core/ECS/ECS.h" // IWYU pragma: export +#include "DummyEngine/Core/Objects/Cameras/FPSCamera.h" // IWYU pragma: export +#include "DummyEngine/Core/Objects/LightSources/LightSource.h" // IWYU pragma: export +#include "DummyEngine/Core/Physics/PhysicsComponent.h" // IWYU pragma: export +#include "DummyEngine/Core/Rendering/Renderer/FrameBuffer.h" // IWYU pragma: export +#include "DummyEngine/Core/Rendering/Renderer/LocalBuffer.h" // IWYU pragma: export +#include "DummyEngine/Core/Rendering/Renderer/Renderer.h" // IWYU pragma: export +#include "DummyEngine/Core/Rendering/Renderer/Texture.h" // IWYU pragma: export +#include "DummyEngine/Core/ResourceManaging/AssetManager.h" // IWYU pragma: export +#include "DummyEngine/Core/ResourceManaging/ResourceManager.h" // IWYU pragma: export +#include "DummyEngine/Core/Scene/Components.h" // IWYU pragma: export +#include "DummyEngine/Core/Scene/Scene.h" // IWYU pragma: export +#include "DummyEngine/Core/Scene/SceneHierarchy.h" // IWYU pragma: export +#include "DummyEngine/Core/Scene/SceneRenderer.h" // IWYU pragma: export +#include "DummyEngine/Core/Scripting/ScriptEngine.h" // IWYU pragma: export +#include "DummyEngine/Utils/Debug/Profiler.h" // IWYU pragma: export +#include "DummyEngine/Utils/Helpers/Random.h" // IWYU pragma: export +#include "DummyEngine/Utils/PCH/GLMIncludes.h" // IWYU pragma: export diff --git a/DummyEngine/Platform/Linux/Core/Scripting/SharedObject.cpp b/DummyEngine/Platform/Linux/Core/Scripting/SharedObject.cpp index 6b9f3f1..84ef441 100644 --- a/DummyEngine/Platform/Linux/Core/Scripting/SharedObject.cpp +++ b/DummyEngine/Platform/Linux/Core/Scripting/SharedObject.cpp @@ -1,12 +1,13 @@ #include "DummyEngine/Core/Scripting/SharedObject.h" -#include - #include "DummyEngine/Core/Application/Config.h" +#include "DummyEngine/Utils/Debug/Logger.h" + +#include -namespace DE { +namespace DummyEngine { class SharedObjectImpl { - LOGGER_AUTHOR(SharedObject) + LOG_AUTHOR(SharedObject) public: SharedObjectImpl() {} ~SharedObjectImpl() { @@ -43,7 +44,7 @@ namespace DE { m_Directory = directory; m_Name = name; m_Valid = true; - LOG_INFO("Loaded library {}", RelativeToExecutable(directory / (name + ".dll"))); + LOG_INFO("Loaded library {}", Config::RelativeToExecutable(directory / (name + ".dll"))); return true; } void Invalidate() { m_Valid = false; } @@ -89,4 +90,4 @@ namespace DE { return m_Impl->GetName(); } -} // namespace DE \ No newline at end of file +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Platform/Linux/Utils/Debug/Demangler.cpp b/DummyEngine/Platform/Linux/Utils/Debug/Demangler.cpp index 3db1d43..e91aa8a 100644 --- a/DummyEngine/Platform/Linux/Utils/Debug/Demangler.cpp +++ b/DummyEngine/Platform/Linux/Utils/Debug/Demangler.cpp @@ -1,6 +1,7 @@ #include "DummyEngine/Platform/Linux/Utils/Debug/Demangler.h" -namespace DE { +namespace DummyEngine { + std::string DemangledName(const std::string& name) { std::string res; int status; @@ -11,4 +12,5 @@ namespace DE { free(realname); return res; } -} // namespace DE \ No newline at end of file + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Platform/Linux/Utils/Debug/Demangler.h b/DummyEngine/Platform/Linux/Utils/Debug/Demangler.h index ac3afe6..e0aabd7 100644 --- a/DummyEngine/Platform/Linux/Utils/Debug/Demangler.h +++ b/DummyEngine/Platform/Linux/Utils/Debug/Demangler.h @@ -1,10 +1,10 @@ #pragma once #include - #include -namespace DE { +namespace DummyEngine { + template std::string DemangledName() { std::string res; int status; @@ -17,4 +17,5 @@ namespace DE { return res; } std::string DemangledName(const std::string& name); -} // namespace DE \ No newline at end of file + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Platform/Linux/Utils/Debug/StackTrace.cpp b/DummyEngine/Platform/Linux/Utils/Debug/StackTrace.cpp index bc59004..9a006b3 100644 --- a/DummyEngine/Platform/Linux/Utils/Debug/StackTrace.cpp +++ b/DummyEngine/Platform/Linux/Utils/Debug/StackTrace.cpp @@ -1,13 +1,10 @@ #include "DummyEngine/Utils/Debug/StackTrace.h" -#include "DummyEngine/Utils/Debug/Demangler.h" +namespace DummyEngine { -// clang-format off -// clang-format on - -namespace DE { std::string StackTrace() { return "StackTrace not impemented\n"; } -} // namespace DE \ No newline at end of file + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Platform/Macos/Core/Scripting/SharedObject.cpp b/DummyEngine/Platform/Macos/Core/Scripting/SharedObject.cpp index facf844..ad3e0f5 100644 --- a/DummyEngine/Platform/Macos/Core/Scripting/SharedObject.cpp +++ b/DummyEngine/Platform/Macos/Core/Scripting/SharedObject.cpp @@ -5,9 +5,9 @@ #include "DummyEngine/Core/Application/Config.h" -namespace DE { +namespace DummyEngine { class SharedObjectImpl { - LOGGER_AUTHOR(SharedObject) + LOG_AUTHOR(SharedObject) public: SharedObjectImpl() {} ~SharedObjectImpl() { @@ -43,7 +43,7 @@ namespace DE { m_Directory = directory; m_Name = name; m_Valid = true; - LOG_INFO("Loaded library {}", RelativeToExecutable(directory / (name + ".dylib"))); + LOG_INFO("Loaded library {}", Config::RelativeToExecutable(directory / (name + ".dylib"))); return true; } void Invalidate() { m_Valid = false; } @@ -88,4 +88,4 @@ namespace DE { return m_Impl->Valid(); } -} // namespace DE \ No newline at end of file +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Platform/Macos/Utils/Debug/Demangler.cpp b/DummyEngine/Platform/Macos/Utils/Debug/Demangler.cpp index 445e2b5..1276367 100644 --- a/DummyEngine/Platform/Macos/Utils/Debug/Demangler.cpp +++ b/DummyEngine/Platform/Macos/Utils/Debug/Demangler.cpp @@ -1,7 +1,7 @@ #include "DummyEngine/Platform/Windows/Utils/Debug/Demangler.h" -namespace DE { +namespace DummyEngine { std::string DemangledName(const std::string& name) { return "Demangler not impemented\n"; } -} // namespace DE \ No newline at end of file +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Platform/Macos/Utils/Debug/Demangler.h b/DummyEngine/Platform/Macos/Utils/Debug/Demangler.h index ab34e2a..a19efb8 100644 --- a/DummyEngine/Platform/Macos/Utils/Debug/Demangler.h +++ b/DummyEngine/Platform/Macos/Utils/Debug/Demangler.h @@ -2,9 +2,9 @@ #include -namespace DE { +namespace DummyEngine { template std::string DemangledName() { return "Demangler not impemented\n"; } std::string DemangledName(const std::string& name); -} // namespace DE \ No newline at end of file +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Platform/Macos/Utils/Debug/StackTrace.cpp b/DummyEngine/Platform/Macos/Utils/Debug/StackTrace.cpp index 74ea969..cfc4590 100644 --- a/DummyEngine/Platform/Macos/Utils/Debug/StackTrace.cpp +++ b/DummyEngine/Platform/Macos/Utils/Debug/StackTrace.cpp @@ -3,9 +3,9 @@ #include "DummyEngine/Utils/Debug/Demangler.h" -namespace DE { +namespace DummyEngine { std::string StackTrace() { return "StackTrace not impemented\n"; } -} // namespace DE \ No newline at end of file +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Platform/Windows/Core/Scripting/SharedObject.cpp b/DummyEngine/Platform/Windows/Core/Scripting/SharedObject.cpp index 471ea2f..24963ad 100644 --- a/DummyEngine/Platform/Windows/Core/Scripting/SharedObject.cpp +++ b/DummyEngine/Platform/Windows/Core/Scripting/SharedObject.cpp @@ -1,17 +1,18 @@ #include "DummyEngine/Core/Scripting/SharedObject.h" -#include - #include "DummyEngine/Core/Application/Config.h" +#include "DummyEngine/Utils/Debug/Logger.h" + +#include -namespace DE { +namespace DummyEngine { class SharedObjectImpl { - LOGGER_AUTHOR(SharedObject) + LOG_AUTHOR(SharedObject) public: SharedObjectImpl() {} ~SharedObjectImpl() { - if (m_Handle) { - FreeLibrary(m_Handle); + if (handle_ != nullptr) { + FreeLibrary(handle_); } } @@ -21,7 +22,7 @@ namespace DE { SharedObjectImpl& operator=(SharedObjectImpl&&) = delete; bool Load(const Path& directory, const std::string& name) { - if (m_Handle && m_Valid) { + if (handle_ != nullptr && valid_) { LOG_WARNING("Library {} already loaded", name); return false; } @@ -31,62 +32,62 @@ namespace DE { return false; } HMODULE new_handle = LoadLibrary(path_to_dll.string().c_str()); - if (!new_handle) { + if (new_handle == nullptr) { LOG_WARNING("Failed to load library {}", path_to_dll); return false; } - if (m_Handle) { - FreeLibrary(m_Handle); + if (handle_ != nullptr) { + FreeLibrary(handle_); } - m_Handle = new_handle; - m_Directory = directory; - m_Name = name; - m_Valid = true; - LOG_INFO("Loaded library {}", RelativeToExecutable(path_to_dll)); + handle_ = new_handle; + directory_ = directory; + name_ = name; + valid_ = true; + LOG_INFO("Loaded library {}", Config::RelativeToExecutable(path_to_dll)); return true; } - void Invalidate() { m_Valid = false; } + void Invalidate() { valid_ = false; } - bool Valid() const { return m_Valid && m_Handle; } + bool Valid() const { return valid_ && handle_ != nullptr; } VoidFPtr GetFunction(const std::string& function_name) const { - if (!m_Handle) { + if (handle_ == nullptr) { return nullptr; } - return (VoidFPtr)GetProcAddress(m_Handle, function_name.c_str()); + return (VoidFPtr)GetProcAddress(handle_, function_name.c_str()); } - const Path& GetDirectory() const { return m_Directory; } - const std::string& GetName() const { return m_Name; } + const Path& GetDirectory() const { return directory_; } + const std::string& GetName() const { return name_; } private: - Path m_Directory; - std::string m_Name; - HMODULE m_Handle = NULL; - bool m_Valid = false; + Path directory_; + std::string name_; + HMODULE handle_ = nullptr; + bool valid_ = false; }; SharedObject::SharedObject() { - m_Impl = CreateScope(); + impl_ = CreateScope(); } SharedObject::~SharedObject() {} bool SharedObject::Load(const Path& directory, const std::string& name) { - return m_Impl->Load(directory, name); + return impl_->Load(directory, name); } void SharedObject::Invalidate() { - m_Impl->Invalidate(); + impl_->Invalidate(); } bool SharedObject::Valid() const { - return m_Impl->Valid(); + return impl_->Valid(); } VoidFPtr SharedObject::GetFunction(const std::string& function_name) const { - return m_Impl->GetFunction(function_name); + return impl_->GetFunction(function_name); } const Path& SharedObject::GetDirectory() const { - return m_Impl->GetDirectory(); + return impl_->GetDirectory(); } const std::string& SharedObject::GetName() const { - return m_Impl->GetName(); + return impl_->GetName(); } -} // namespace DE \ No newline at end of file +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Platform/Windows/Utils/Debug/Demangler.cpp b/DummyEngine/Platform/Windows/Utils/Debug/Demangler.cpp index f375dd2..e30ac97 100644 --- a/DummyEngine/Platform/Windows/Utils/Debug/Demangler.cpp +++ b/DummyEngine/Platform/Windows/Utils/Debug/Demangler.cpp @@ -1,14 +1,16 @@ #include "DummyEngine/Platform/Windows/Utils/Debug/Demangler.h" -namespace DE { +namespace DummyEngine { + std::string DemangledName(const std::string& name) { std::string res; int status; char* realname; - realname = abi::__cxa_demangle(name.c_str(), 0, 0, &status); + realname = abi::__cxa_demangle(name.c_str(), nullptr, nullptr, &status); res = realname; free(realname); return res; } -} // namespace DE \ No newline at end of file + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Platform/Windows/Utils/Debug/Demangler.h b/DummyEngine/Platform/Windows/Utils/Debug/Demangler.h index c1966f6..e0aabd7 100644 --- a/DummyEngine/Platform/Windows/Utils/Debug/Demangler.h +++ b/DummyEngine/Platform/Windows/Utils/Debug/Demangler.h @@ -1,10 +1,10 @@ #pragma once #include +#include -#include "DummyEngine/Utils/Base.h" +namespace DummyEngine { -namespace DE { template std::string DemangledName() { std::string res; int status; @@ -17,4 +17,5 @@ namespace DE { return res; } std::string DemangledName(const std::string& name); -} // namespace DE \ No newline at end of file + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Platform/Windows/Utils/Debug/StackTrace.cpp b/DummyEngine/Platform/Windows/Utils/Debug/StackTrace.cpp index 35a6715..5584fb1 100644 --- a/DummyEngine/Platform/Windows/Utils/Debug/StackTrace.cpp +++ b/DummyEngine/Platform/Windows/Utils/Debug/StackTrace.cpp @@ -1,117 +1,15 @@ #include "DummyEngine/Utils/Debug/StackTrace.h" -#include "DummyEngine/Utils/Debug/Demangler.h" - // clang-format off #include #include // clang-format on -namespace DE { - struct StackFrame { - DWORD64 address; - std::string name; - std::string module; - unsigned int line; - std::string file; - }; - - std::string basename(const std::string& file) { - size_t i = file.find_last_of("\\/"); - if (i == std::string::npos) { - return file; - } else { - return file.substr(i + 1); - } - } +namespace DummyEngine { std::string StackTrace() { -#if 1 return "StackTrace not impemented\n"; -#else - std::stringstream ss; - DWORD machine = IMAGE_FILE_MACHINE_AMD64; - HANDLE process = GetCurrentProcess(); - HANDLE thread = GetCurrentThread(); - - if (SymInitialize(process, NULL, TRUE) == FALSE) { - ss << "Failed to get stack trace\n"; - return ss.str(); - } - SymSetOptions(SYMOPT_LOAD_LINES); - - CONTEXT context = {}; - context.ContextFlags = CONTEXT_FULL; - RtlCaptureContext(&context); - - STACKFRAME frame = {}; - frame.AddrPC.Offset = context.Rip; - frame.AddrPC.Mode = AddrModeFlat; - frame.AddrFrame.Offset = context.Rbp; - frame.AddrFrame.Mode = AddrModeFlat; - frame.AddrStack.Offset = context.Rsp; - frame.AddrStack.Mode = AddrModeFlat; - bool first = true; - - std::vector frames; - while (StackWalk(machine, process, thread, &frame, &context, NULL, SymFunctionTableAccess, SymGetModuleBase, NULL)) { - StackFrame f = {}; - f.address = frame.AddrPC.Offset; - DWORD64 moduleBase = 0; - - moduleBase = SymGetModuleBase(process, frame.AddrPC.Offset); - - char moduelBuff[MAX_PATH]; - if (moduleBase && GetModuleFileNameA((HINSTANCE)moduleBase, moduelBuff, MAX_PATH)) { - f.module = basename(moduelBuff); - } else { - f.module = "Unknown Module"; - } - - DWORD64 offset = 0; - - char symbolBuffer[sizeof(IMAGEHLP_SYMBOL) + 255]; - PIMAGEHLP_SYMBOL symbol = (PIMAGEHLP_SYMBOL)symbolBuffer; - symbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL) + 255; - symbol->MaxNameLength = 254; - - if (SymGetSymFromAddr(process, frame.AddrPC.Offset, &offset, symbol)) { - f.name = symbol->Name; - int status; - std::string demangled = DemangledName(f.name); - if (demangled.empty()) { - f.name = symbol->Name; - } else { - f.name = demangled; - } - } else { - f.name = "Unknown Function"; - } - - IMAGEHLP_LINE line; - line.SizeOfStruct = sizeof(IMAGEHLP_LINE); - - DWORD offset_ln = 0; - if (SymGetLineFromAddr(process, frame.AddrPC.Offset, &offset_ln, &line)) { - f.file = line.FileName; - f.line = line.LineNumber; - } else { - f.line = 0; - } - - if (!first) { - frames.push_back(f); - } - first = false; - } - SymCleanup(process); - - for (const auto& frame : frames) { - ss << frame.name << " in " << frame.module << "\n"; - } - - return ss.str(); -#endif } -} // namespace DE \ No newline at end of file + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Sources.cmake b/DummyEngine/Sources.cmake index b125d25..ff50f31 100644 --- a/DummyEngine/Sources.cmake +++ b/DummyEngine/Sources.cmake @@ -63,8 +63,6 @@ Core/Rendering/RendererOpenGL/GLUniformBuffer.cpp Core/Rendering/RendererOpenGL/GLRenderAPI.cpp Core/Rendering/RendererOpenGL/GLDebug.cpp -Core/Physics/SceneConstants.cpp -Core/Physics/ForceQueue.cpp Core/Physics/Solver.cpp Core/Physics/ConvexCollider.cpp Core/Physics/Utils.cpp @@ -83,7 +81,7 @@ ToolBox/Loaders/SceneLoader.cpp ToolBox/Editors/TextureEditor.cpp ) -set(ENGINE_PRECOMPILED_HEADERS Utils/Base.h) +set(ENGINE_PRECOMPILED_HEADERS Utils/PCH/PCH.h) if("${CMAKE_PLATFORM}" STREQUAL "WINDOWS") set(PLATFORM_SOURCES diff --git a/DummyEngine/ToolBox/Editors/TextureEditor.cpp b/DummyEngine/ToolBox/Editors/TextureEditor.cpp index cf32643..c459846 100644 --- a/DummyEngine/ToolBox/Editors/TextureEditor.cpp +++ b/DummyEngine/ToolBox/Editors/TextureEditor.cpp @@ -1,6 +1,7 @@ #include "DummyEngine/ToolBox/Editors/TextureEditor.h" -namespace DE { +namespace DummyEngine { + Ref TextureEditor::GetTexturePart(const Ref data, U32 width, U32 height, U32 x_pos, U32 y_pos) { Ref res = CreateRef(); res->SetData(data->Data(), width, height, data->Channels(), data->Format()); @@ -28,4 +29,5 @@ namespace DE { default: return nullptr; } } -} // namespace DE \ No newline at end of file + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/ToolBox/Editors/TextureEditor.h b/DummyEngine/ToolBox/Editors/TextureEditor.h index 74bcb34..b8a5063 100644 --- a/DummyEngine/ToolBox/Editors/TextureEditor.h +++ b/DummyEngine/ToolBox/Editors/TextureEditor.h @@ -1,13 +1,13 @@ #pragma once #include "DummyEngine/Core/ResourceManaging/RawData.h" -#include "DummyEngine/Utils/Base.h" -namespace DE { +namespace DummyEngine { + class TextureEditor { public: static Ref GetTexturePart(const Ref data, U32 width, U32 height, U32 x_pos, U32 y_pos); - static Ref GetSkyBoxSide(const Ref data, CubeSide side); }; -} // namespace DE \ No newline at end of file + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/ToolBox/Loaders/ModelLoader.cpp b/DummyEngine/ToolBox/Loaders/ModelLoader.cpp index ceafa7e..a5ab056 100644 --- a/DummyEngine/ToolBox/Loaders/ModelLoader.cpp +++ b/DummyEngine/ToolBox/Loaders/ModelLoader.cpp @@ -1,11 +1,11 @@ -#include "DummyEngine/ToolBox/Loaders/ModelLoader.h" - -#include +#include "ModelLoader.h" #include "DummyEngine/Core/Application/Config.h" #include "DummyEngine/ToolBox/Loaders/TextureLoader.h" -namespace DE { +#include + +namespace DummyEngine { Mat4 AssimpToGLM(const aiMatrix4x4& from) { Mat4 to; to[0][0] = from.a1; @@ -32,34 +32,34 @@ namespace DE { auto pos = node->mPositionKeys[i].mValue; float time_stamp = node->mPositionKeys[i].mTime; KeyPosition data; - data.position.x = pos.x; - data.position.y = pos.y; - data.position.z = pos.z; - data.time_stamp = time_stamp; - bone.m_Positions.push_back(data); + data.Position.x = pos.x; + data.Position.y = pos.y; + data.Position.z = pos.z; + data.TimeStamp = time_stamp; + bone.positions_.push_back(data); } for (U32 i = 0; i < node->mNumRotationKeys; ++i) { auto rot = node->mRotationKeys[i].mValue; float time_stamp = node->mRotationKeys[i].mTime; KeyRotation data; - data.orientation.x = rot.x; - data.orientation.y = rot.y; - data.orientation.z = rot.z; - data.orientation.w = rot.w; - data.time_stamp = time_stamp; - bone.m_Rotations.push_back(data); + data.Orientation.x = rot.x; + data.Orientation.y = rot.y; + data.Orientation.z = rot.z; + data.Orientation.w = rot.w; + data.TimeStamp = time_stamp; + bone.rotations_.push_back(data); } for (U32 i = 0; i < node->mNumScalingKeys; ++i) { aiVector3D scale = node->mScalingKeys[i].mValue; float time_stamp = node->mScalingKeys[i].mTime; KeyScale data; - data.scale.x = scale.x; - data.scale.y = scale.y; - data.scale.z = scale.z; - data.time_stamp = time_stamp; - bone.m_Scales.push_back(data); + data.Scale.x = scale.x; + data.Scale.y = scale.y; + data.Scale.z = scale.z; + data.TimeStamp = time_stamp; + bone.scales_.push_back(data); } // LOG_INFO("Loaded bone ({}|{}), with positions ({}), rotations ({}) and scales ({})", // bone.GetBoneName(), @@ -70,27 +70,27 @@ namespace DE { } void ModelLoader::ReadWeights(aiMesh* mesh) { - auto& model = *m_State.m_CurrentData; - auto& current_mesh = model.meshes[m_State.m_CurrentMeshId]; - if (!model.animation) { + auto& model = *gState.CurrentData; + auto& current_mesh = model.Meshes[gState.CurrentMeshID]; + if (!model.Animation) { return; } - auto& animation = *model.animation; + auto& animation = *model.Animation; for (U32 i = 0; i < mesh->mNumBones; ++i) { int bone_id = -1; std::string bone_name = mesh->mBones[i]->mName.C_Str(); - if (!animation.m_BoneNameToID.contains(bone_name)) { - bone_id = animation.m_Bones.size(); - animation.m_BoneNameToID[bone_name] = bone_id; + if (!animation.bone_name_to_id_.contains(bone_name)) { + bone_id = animation.bones_.size(); + animation.bone_name_to_id_[bone_name] = bone_id; BoneInfo bone_info; - bone_info.bone = Bone(bone_name, bone_id); - bone_info.offset = AssimpToGLM(mesh->mBones[i]->mOffsetMatrix); - animation.m_Bones.push_back(bone_info); + bone_info.Bone = Bone(bone_name, bone_id); + bone_info.Offset = AssimpToGLM(mesh->mBones[i]->mOffsetMatrix); + animation.bones_.push_back(bone_info); // printf("Added bone (%s) with id (%d)\n", bone_name.c_str(), bone_id); } else { - bone_id = animation.m_BoneNameToID[bone_name]; + bone_id = animation.bone_name_to_id_[bone_name]; } if (bone_id == -1) { LOG_WARNING("Wrong bone id"); @@ -103,11 +103,11 @@ namespace DE { U32 v_id = weights[j].mVertexId; float weight = weights[j].mWeight; - if (v_id >= current_mesh.vertices.size()) { + if (v_id >= current_mesh.Vertices.size()) { LOG_WARNING("Wrong vertex id"); return; } - current_mesh.vertices[v_id].AddBone(bone_id, weight); + current_mesh.Vertices[v_id].AddBone(bone_id, weight); } } } @@ -115,93 +115,93 @@ namespace DE { for (U32 i = 0; i < anim->mNumChannels; ++i) { auto channel = anim->mChannels[i]; auto bone_info = animation.GetBone(channel->mNodeName.data); - if (!bone_info) { + if (bone_info == nullptr) { BoneInfo info; - info.offset = glm::mat4(1.0); - animation.m_BoneNameToID[channel->mNodeName.data] = animation.m_Bones.size(); - animation.m_Bones.push_back(info); - bone_info = &animation.m_Bones.back(); + info.Offset = glm::mat4(1.0); + animation.bone_name_to_id_[channel->mNodeName.data] = animation.bones_.size(); + animation.bones_.push_back(info); + bone_info = &animation.bones_.back(); LOG_WARNING("Added unknown bone"); } - LoadBone(bone_info->bone, channel); + LoadBone(bone_info->Bone, channel); } } void ModelLoader::ReadAnimationNode(Animation::Node& node, const aiNode* src) { - node.name = src->mName.data; - node.transformation = AssimpToGLM(src->mTransformation); - node.childrens.resize(src->mNumChildren); + node.Name = src->mName.data; + node.Transformation = AssimpToGLM(src->mTransformation); + node.Childrens.resize(src->mNumChildren); for (U32 i = 0; i < src->mNumChildren; i++) { - Animation::Node& data = node.childrens[i]; + Animation::Node& data = node.Childrens[i]; ReadAnimationNode(data, src->mChildren[i]); } } void ModelLoader::ReadAnimation(Animation& animation, const aiScene* scene) { - auto anim = scene->mAnimations[0]; - animation.m_Duration = anim->mDuration; - animation.m_TicksPerSecond = anim->mTicksPerSecond; - ReadAnimationNode(animation.m_RootNode, scene->mRootNode); + auto anim = scene->mAnimations[0]; + animation.duration_ = anim->mDuration; + animation.ticks_per_second_ = anim->mTicksPerSecond; + ReadAnimationNode(animation.root_node_, scene->mRootNode); ReadBones(animation, anim); } - ModelLoader::LoaderState ModelLoader::m_State; + ModelLoader::LoaderState ModelLoader::gState; MaterialData ModelLoader::LoadMaterial(aiMaterial* mat) { MaterialData material; - material.diffuse = GetColor(mat, ColorType::Diffuse); - material.specular = GetColor(mat, ColorType::Specular); - material.ambient = GetColor(mat, ColorType::Ambient); - material.albedo = GetColor(mat, ColorType::Albedo); - material.orm = GetColor(mat, ColorType::ORM); - material.orm = GetColor(mat, ColorType::Emission); - aiGetMaterialFloat(mat, AI_MATKEY_SHININESS, &material.shininess); + material.Diffuse = GetColor(mat, ColorType::Diffuse); + material.Specular = GetColor(mat, ColorType::Specular); + material.Ambient = GetColor(mat, ColorType::Ambient); + material.Albedo = GetColor(mat, ColorType::Albedo); + material.ORM = GetColor(mat, ColorType::ORM); + material.Emission = GetColor(mat, ColorType::Emission); + aiGetMaterialFloat(mat, AI_MATKEY_SHININESS, &material.Shininess); - material.albedo_map = GetTexture(mat, aiTextureType_DIFFUSE); - material.normal_map = GetTexture(mat, aiTextureType_NORMALS); - material.orm_map = GetTexture(mat, aiTextureType_METALNESS); - material.diffuse_map = GetTexture(mat, aiTextureType_DIFFUSE); - material.specular_map = GetTexture(mat, aiTextureType_SPECULAR); - material.emission_map = GetTexture(mat, aiTextureType_EMISSIVE); + material.AlbedoMap = GetTexture(mat, aiTextureType_DIFFUSE); + material.NormalMap = GetTexture(mat, aiTextureType_NORMALS); + material.ORMMap = GetTexture(mat, aiTextureType_METALNESS); + material.DiffuseMap = GetTexture(mat, aiTextureType_DIFFUSE); + material.SpecularMap = GetTexture(mat, aiTextureType_SPECULAR); + material.EmissionMap = GetTexture(mat, aiTextureType_EMISSIVE); return material; } Ref ModelLoader::Load(const RenderMeshAsset::LoadingProperties& properties) { - m_State.m_Props = properties; + gState.Props = properties; unsigned int flags = aiProcess_Triangulate | aiProcess_CalcTangentSpace; - if (properties.flip_uvs) { + if (properties.FlipUV) { flags |= aiProcess_FlipUVs; } - const aiScene* scene = m_State.m_Importer.ReadFile(properties.path.string(), flags); + const aiScene* scene = gState.Importer.ReadFile(properties.Path.string(), flags); - if (!scene || scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode) { - LOG_ERROR("Failed to load model {} due: {}", RelativeToExecutable(properties.path), m_State.m_Importer.GetErrorString()); + if (scene == nullptr || (scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE) != 0 || scene->mRootNode == nullptr) { + LOG_ERROR("Failed to load model {} due: {}", Config::RelativeToExecutable(properties.Path), gState.Importer.GetErrorString()); return nullptr; } - m_State.m_CurrentData = CreateRef(); + gState.CurrentData = CreateRef(); if (scene->mNumAnimations > 0) { - m_State.m_CurrentData->animation = CreateRef(); + gState.CurrentData->Animation = CreateRef(); } - m_State.m_CurrentMeshId = 0; - m_State.m_MeshesAmount = 0; - m_State.m_NodesAmount = 0; - m_State.m_VerticesAmount = 0; - m_State.m_CurrentDirectory = properties.path.parent_path(); + gState.CurrentMeshID = 0; + gState.MeshesAmount = 0; + gState.NodesAmount = 0; + gState.VerticesAmount = 0; + gState.CurrentDirectory = properties.Path.parent_path(); ReadModelProperties(scene->mRootNode, scene); - m_State.m_CurrentData->meshes.resize(m_State.m_MeshesAmount); + gState.CurrentData->Meshes.resize(gState.MeshesAmount); ProcessNode(scene->mRootNode, scene); - if (m_State.m_CurrentData->animation) { - ReadAnimation(*m_State.m_CurrentData->animation, scene); + if (gState.CurrentData->Animation) { + ReadAnimation(*gState.CurrentData->Animation, scene); } - if (properties.compress) { - m_State.m_CurrentData->Compress(); + if (properties.Compress) { + gState.CurrentData->Compress(); } LOG_INFO("Model {} loaded with {} meshes and {} verticies", - RelativeToExecutable(properties.path), - m_State.m_MeshesAmount, - m_State.m_VerticesAmount); - return m_State.m_CurrentData; + Config::RelativeToExecutable(properties.Path), + gState.MeshesAmount, + gState.VerticesAmount); + return gState.CurrentData; } void ModelLoader::ProcessNode(aiNode* node, const aiScene* scene) { @@ -214,43 +214,43 @@ namespace DE { } } void ModelLoader::ProcessMesh(aiMesh* mesh, const aiScene* scene) { - RenderMeshData& model = *m_State.m_CurrentData; - RenderSubMeshData& current_mesh = model.meshes[m_State.m_CurrentMeshId]; + RenderMeshData& model = *gState.CurrentData; + RenderSubMeshData& current_mesh = model.Meshes[gState.CurrentMeshID]; for (size_t i = 0; i < mesh->mNumVertices; ++i) { Vertex3D vertex; - vertex.position.x = mesh->mVertices[i].x; - vertex.position.y = mesh->mVertices[i].y; - vertex.position.z = mesh->mVertices[i].z; + vertex.Position.x = mesh->mVertices[i].x; + vertex.Position.y = mesh->mVertices[i].y; + vertex.Position.z = mesh->mVertices[i].z; - if (mesh->mNormals) { - vertex.normal.x = mesh->mNormals[i].x; - vertex.normal.y = mesh->mNormals[i].y; - vertex.normal.z = mesh->mNormals[i].z; + if (mesh->mNormals != nullptr) { + vertex.Normal.x = mesh->mNormals[i].x; + vertex.Normal.y = mesh->mNormals[i].y; + vertex.Normal.z = mesh->mNormals[i].z; } - if (mesh->mTangents) { - vertex.tangent.x = mesh->mTangents[i].x; - vertex.tangent.y = mesh->mTangents[i].y; - vertex.tangent.z = mesh->mTangents[i].z; + if (mesh->mTangents != nullptr) { + vertex.Tangent.x = mesh->mTangents[i].x; + vertex.Tangent.y = mesh->mTangents[i].y; + vertex.Tangent.z = mesh->mTangents[i].z; } - if (mesh->mTextureCoords[0]) { - vertex.tex_coords.x = mesh->mTextureCoords[0][i].x; - vertex.tex_coords.y = mesh->mTextureCoords[0][i].y; + if (mesh->mTextureCoords[0] != nullptr) { + vertex.TexCoords.x = mesh->mTextureCoords[0][i].x; + vertex.TexCoords.y = mesh->mTextureCoords[0][i].y; } - current_mesh.vertices.push_back(vertex); + current_mesh.Vertices.push_back(vertex); } ReadWeights(mesh); for (size_t i = 0; i < mesh->mNumFaces; ++i) { aiFace face = mesh->mFaces[i]; for (size_t j = 0; j < face.mNumIndices; ++j) { - current_mesh.indices.push_back(face.mIndices[j]); + current_mesh.Indices.push_back(face.mIndices[j]); } } if (mesh->mMaterialIndex >= 0) { aiMaterial* material = scene->mMaterials[mesh->mMaterialIndex]; - current_mesh.material = LoadMaterial(material); + current_mesh.Material = LoadMaterial(material); } - ++m_State.m_CurrentMeshId; + ++gState.CurrentMeshID; } Vec3 ModelLoader::GetColor(aiMaterial* mat, ColorType type) { aiColor3D color(1.f, 1.f, 1.f); @@ -278,20 +278,20 @@ namespace DE { } mat->GetTexture(type, 0, &file_name); - if (!m_State.m_ModelTextures.contains(m_State.m_CurrentDirectory / file_name.C_Str())) { - m_State.m_ModelTextures[m_State.m_CurrentDirectory / file_name.C_Str()] = - TextureLoader::Load({m_State.m_CurrentDirectory / file_name.C_Str(), false}); + if (!gState.ModelTextures.contains(gState.CurrentDirectory / file_name.C_Str())) { + gState.ModelTextures[gState.CurrentDirectory / file_name.C_Str()] = + TextureLoader::Load({gState.CurrentDirectory / file_name.C_Str(), false}); } - return m_State.m_ModelTextures[m_State.m_CurrentDirectory / file_name.C_Str()]; + return gState.ModelTextures[gState.CurrentDirectory / file_name.C_Str()]; } void ModelLoader::ReadModelProperties(aiNode* node, const aiScene* scene) { - ++m_State.m_NodesAmount; - m_State.m_MeshesAmount += node->mNumMeshes; + ++gState.NodesAmount; + gState.MeshesAmount += node->mNumMeshes; for (size_t i = 0; i < node->mNumMeshes; ++i) { - m_State.m_VerticesAmount += scene->mMeshes[node->mMeshes[i]]->mNumVertices; + gState.VerticesAmount += scene->mMeshes[node->mMeshes[i]]->mNumVertices; } for (size_t i = 0; i < node->mNumChildren; ++i) { ReadModelProperties(node->mChildren[i], scene); } } -} // namespace DE \ No newline at end of file +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/ToolBox/Loaders/ModelLoader.h b/DummyEngine/ToolBox/Loaders/ModelLoader.h index 9276d40..6a824cc 100644 --- a/DummyEngine/ToolBox/Loaders/ModelLoader.h +++ b/DummyEngine/ToolBox/Loaders/ModelLoader.h @@ -1,36 +1,44 @@ #pragma once -#include +#include "DummyEngine/Core/ResourceManaging/Assets.h" +#include "DummyEngine/Utils/Debug/Logger.h" +#include #include -#include "DummyEngine/Core/ResourceManaging/Assets.h" - -namespace DE { +namespace DummyEngine { namespace fs = std::filesystem; class ModelLoader { - LOGGER_AUTHOR(ModelLoader) + LOG_AUTHOR(ModelLoader) public: static Ref Load(const RenderMeshAsset::LoadingProperties& props); private: - enum ColorType { None = 0, Albedo, Diffuse, Specular, Ambient, ORM, Emission }; + enum ColorType { + None = 0, + Albedo, + Diffuse, + Specular, + Ambient, + ORM, + Emission, + }; struct LoaderState { - size_t m_VerticesAmount; - size_t m_NodesAmount; - size_t m_CurrentMeshId; - size_t m_MeshesAmount; - Path m_CurrentDirectory; - RenderMeshAsset::LoadingProperties m_Props; - - Ref m_CurrentData; - std::unordered_map> m_ModelTextures; - Assimp::Importer m_Importer; + size_t VerticesAmount; + size_t NodesAmount; + size_t CurrentMeshID; + size_t MeshesAmount; + Path CurrentDirectory; + RenderMeshAsset::LoadingProperties Props; + + Ref CurrentData; + std::unordered_map> ModelTextures; + Assimp::Importer Importer; }; - static LoaderState m_State; + static LoaderState gState; static void LoadBone(Bone& bone, aiNodeAnim* node); static void ReadWeights(aiMesh* mesh); @@ -45,5 +53,5 @@ namespace DE { static Ref GetTexture(aiMaterial* mat, aiTextureType type); static void ReadModelProperties(aiNode* node, const aiScene* scene); - }; // namespace DE -} // namespace DE \ No newline at end of file + }; // namespace DummyEngine +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/ToolBox/Loaders/SceneLoader.cpp b/DummyEngine/ToolBox/Loaders/SceneLoader.cpp index 9204336..35e9db0 100644 --- a/DummyEngine/ToolBox/Loaders/SceneLoader.cpp +++ b/DummyEngine/ToolBox/Loaders/SceneLoader.cpp @@ -6,14 +6,13 @@ #include "DummyEngine/Core/Physics/PhysicsComponent.h" #include "DummyEngine/Core/ResourceManaging/AssetManager.h" #include "DummyEngine/Core/ResourceManaging/ResourceManager.h" +#include "DummyEngine/Core/Scene/Components.h" #include "DummyEngine/Core/Scene/SceneHierarchy.h" #include "DummyEngine/Core/Scene/SceneRenderer.h" #include "DummyEngine/Core/Scripting/ScriptEngine.h" -#include "DummyEngine/ToolBox/Loaders/ModelLoader.h" #include "DummyEngine/ToolBox/Loaders/TextureLoader.h" -#include "DummyEngine/Utils/Base.h" -namespace DE { +namespace DummyEngine { //*~~~Saving~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -73,112 +72,112 @@ namespace DE { // TODO: Different names for different unknown components... DE_ASSERT(false, "Trying to save unknown component"); } - template <> void SaveComponent(YAML::Node& n_Entity, Entity entity) { + template <> void SaveComponent(YAML::Node& n_entity, Entity entity) { if (entity.Has()) { - n_Entity["Tag"] = entity.Get().tag; + n_entity["Tag"] = entity.Get().Tag; } } - template <> void SaveComponent(YAML::Node& n_Entity, Entity entity) { + template <> void SaveComponent(YAML::Node& n_entity, Entity entity) { if (entity.Has()) { - n_Entity["UUID"] = entity.Get().Hex(); + n_entity["UUID"] = entity.Get().Hex(); } } - template <> void SaveComponent(YAML::Node& n_Entity, Entity entity) { + template <> void SaveComponent(YAML::Node& n_entity, Entity entity) { if (entity.Has()) { - n_Entity["Transformation"]["Translation"] = NodeVec3(entity.Get().translation); - n_Entity["Transformation"]["TranslationOffset"] = NodeVec3(entity.Get().translation_offset); - n_Entity["Transformation"]["Rotation"] = NodeVec3(entity.Get().rotation); - n_Entity["Transformation"]["RotationOffset"] = NodeVec3(entity.Get().rotation_offet); - n_Entity["Transformation"]["Scale"] = NodeVec3(entity.Get().scale); - n_Entity["Transformation"]["ScaleOffset"] = NodeVec3(entity.Get().scale_offset); + n_entity["Transformation"]["Translation"] = NodeVec3(entity.Get().Translation); + n_entity["Transformation"]["TranslationOffset"] = NodeVec3(entity.Get().TranslationOffset); + n_entity["Transformation"]["Rotation"] = NodeVec3(entity.Get().Rotation); + n_entity["Transformation"]["RotationOffset"] = NodeVec3(entity.Get().RotationOffet); + n_entity["Transformation"]["Scale"] = NodeVec3(entity.Get().Scale); + n_entity["Transformation"]["ScaleOffset"] = NodeVec3(entity.Get().ScaleOffset); } } - template <> void SaveComponent(YAML::Node& n_Entity, Entity entity) { + template <> void SaveComponent(YAML::Node& n_entity, Entity entity) { if (entity.Has()) { - n_Entity["RenderModel"]["UUID"] = entity.Get().id.Hex(); - auto materials = n_Entity["RenderModel"]["Materials"]; + n_entity["RenderModel"]["UUID"] = entity.Get().ID.Hex(); + auto materials = n_entity["RenderModel"]["Materials"]; U32 cnt = 0; for (const auto& mesh : entity.Get()->GetSubMeshes()) { YAML::Node mat; - mat["Type"] = MaterialTypeToStr(mesh.material.type); - mat["Albedo"] = NodeVec3(mesh.material.albedo); - mat["Ambient"] = NodeVec3(mesh.material.ambient); - mat["ORM"] = NodeVec3(mesh.material.orm); - mat["Diffuse"] = NodeVec3(mesh.material.diffuse); - mat["Specular"] = NodeVec3(mesh.material.specular); - mat["Emission"] = NodeVec3(mesh.material.emission); - mat["Shininess"] = mesh.material.shininess; - mat["EmissionStrength"] = mesh.material.emission_strength; + mat["Type"] = MaterialTypeToStr(mesh.Material.Type); + mat["Albedo"] = NodeVec3(mesh.Material.Albedo); + mat["Ambient"] = NodeVec3(mesh.Material.Ambient); + mat["ORM"] = NodeVec3(mesh.Material.ORM); + mat["Diffuse"] = NodeVec3(mesh.Material.Diffuse); + mat["Specular"] = NodeVec3(mesh.Material.Specular); + mat["Emission"] = NodeVec3(mesh.Material.Emission); + mat["Shininess"] = mesh.Material.Shininess; + mat["EmissionStrength"] = mesh.Material.EmissionStrength; mat["MeshID"] = cnt++; materials.push_back(mat); } } } - template <> void SaveComponent(YAML::Node& n_Entity, Entity entity) { + template <> void SaveComponent(YAML::Node& n_entity, Entity entity) { if (entity.Has()) { - n_Entity["Shader"] = entity.Get().id.Hex(); + n_entity["Shader"] = entity.Get().ID.Hex(); } } - template <> void SaveComponent(YAML::Node& n_Entity, Entity entity) { + template <> void SaveComponent(YAML::Node& n_entity, Entity entity) { if (entity.Has()) { - n_Entity["FPSCamera"]["FOV"] = entity.Get().m_FOV; - n_Entity["FPSCamera"]["Aspect"] = entity.Get().m_Aspect; - n_Entity["FPSCamera"]["NearPlane"] = entity.Get().m_NearPlane; - n_Entity["FPSCamera"]["FarPlane"] = entity.Get().m_FarPlane; - n_Entity["FPSCamera"]["Position"] = NodeVec3(entity.Get().m_Position); - n_Entity["FPSCamera"]["Direction"] = NodeVec3(entity.Get().m_Direction); + n_entity["FPSCamera"]["FOV"] = entity.Get().FOV; + n_entity["FPSCamera"]["Aspect"] = entity.Get().Aspect; + n_entity["FPSCamera"]["NearPlane"] = entity.Get().NearPlane; + n_entity["FPSCamera"]["FarPlane"] = entity.Get().FarPlane; + n_entity["FPSCamera"]["Position"] = NodeVec3(entity.Get().Position); + n_entity["FPSCamera"]["Direction"] = NodeVec3(entity.Get().Direction); } } - template <> void SaveComponent(YAML::Node& n_Entity, Entity entity) { + template <> void SaveComponent(YAML::Node& n_entity, Entity entity) { if (entity.Has()) { - n_Entity["LightSource"]["Type"] = LightSourceTypeToString(entity.Get().type); - n_Entity["LightSource"]["Ambient"] = NodeVec3(entity.Get().ambient); - n_Entity["LightSource"]["Diffuse"] = NodeVec3(entity.Get().diffuse); - n_Entity["LightSource"]["Specular"] = NodeVec3(entity.Get().specular); - n_Entity["LightSource"]["Direction"] = NodeVec3(entity.Get().direction); - n_Entity["LightSource"]["Position"] = NodeVec3(entity.Get().position); - n_Entity["LightSource"]["CLQ"] = NodeVec3(entity.Get().clq); - n_Entity["LightSource"]["InnerCone"] = entity.Get().inner_cone_cos; - n_Entity["LightSource"]["OuterCone"] = entity.Get().outer_cone_cos; - } - } - template <> void SaveComponent(YAML::Node& n_Entity, Entity entity) { + n_entity["LightSource"]["Type"] = LightSourceTypeToString(entity.Get().Type); + n_entity["LightSource"]["Ambient"] = NodeVec3(entity.Get().Ambient); + n_entity["LightSource"]["Diffuse"] = NodeVec3(entity.Get().Diffuse); + n_entity["LightSource"]["Specular"] = NodeVec3(entity.Get().Specular); + n_entity["LightSource"]["Direction"] = NodeVec3(entity.Get().Direction); + n_entity["LightSource"]["Position"] = NodeVec3(entity.Get().Position); + n_entity["LightSource"]["CLQ"] = NodeVec3(entity.Get().CLQ); + n_entity["LightSource"]["InnerCone"] = entity.Get().InnerConeCosinus; + n_entity["LightSource"]["OuterCone"] = entity.Get().OuterConeCosinus; + } + } + template <> void SaveComponent(YAML::Node& n_entity, Entity entity) { if (entity.Has()) { auto skybox = entity.Get(); - n_Entity["SkyBox"]["Type"] = (skybox.type == SkyBoxComponent::TexType::CubeMap ? "CubeMap" : "Equirectangular"); - n_Entity["SkyBox"]["UUID"] = skybox.id.Hex(); + n_entity["SkyBox"]["Type"] = (skybox.Type == SkyBoxComponent::TexType::CubeMap ? "CubeMap" : "Equirectangular"); + n_entity["SkyBox"]["UUID"] = skybox.ID.Hex(); } } - template <> void SaveComponent(YAML::Node& n_Entity, Entity entity) { + template <> void SaveComponent(YAML::Node& n_entity, Entity entity) { if (entity.Has() && entity.Get().Valid()) { auto& script_instance = entity.Get(); - n_Entity["Script"]["UUID"] = script_instance.ID().Hex(); + n_entity["Script"]["UUID"] = script_instance.ID().Hex(); for (auto [name, field] : *script_instance) { - n_Entity["Script"]["Fields"][name.get()] = NodeScriptField(field); + n_entity["Script"]["Fields"][name.get()] = NodeScriptField(field); } } } - template <> void SaveComponent(YAML::Node& n_Entity, Entity entity) { + template <> void SaveComponent(YAML::Node& n_entity, Entity entity) { if (entity.Has()) { const auto& phys = entity.Get(); - n_Entity["Physics"]["InvMass"] = phys.inv_mass; - n_Entity["Physics"]["InvInertia"] = phys.inv_inertia; - n_Entity["Physics"]["Collidable"] = phys.collidable; - n_Entity["Physics"]["Gravity"] = phys.gravity; + n_entity["Physics"]["InvMass"] = phys.InvertedMass; + n_entity["Physics"]["InvInertia"] = phys.InvertedInertia; + n_entity["Physics"]["Collidable"] = phys.Collidable; + n_entity["Physics"]["Gravity"] = phys.Gravity; } } - void SaveEntity(YAML::Node& n_Entity, Entity entity) { - SaveComponent(n_Entity, entity); - SaveComponent(n_Entity, entity); - SaveComponent(n_Entity, entity); - SaveComponent(n_Entity, entity); - SaveComponent(n_Entity, entity); - SaveComponent(n_Entity, entity); - SaveComponent(n_Entity, entity); - SaveComponent(n_Entity, entity); - SaveComponent(n_Entity, entity); - SaveComponent(n_Entity, entity); + void SaveEntity(YAML::Node& n_entity, Entity entity) { + SaveComponent(n_entity, entity); + SaveComponent(n_entity, entity); + SaveComponent(n_entity, entity); + SaveComponent(n_entity, entity); + SaveComponent(n_entity, entity); + SaveComponent(n_entity, entity); + SaveComponent(n_entity, entity); + SaveComponent(n_entity, entity); + SaveComponent(n_entity, entity); + SaveComponent(n_entity, entity); } YAML::Node SaveNode(SceneHierarchy::Node node) { YAML::Node res; @@ -201,66 +200,66 @@ namespace DE { return res; } - YAML::Node SaveRendererSettings(const SceneRenderer::Settings& settings) { + YAML::Node SaveRendererSettings(const SceneRenderer::GraphicsSettings& settings) { YAML::Node set; - set["Bloom"] = settings.bloom; - set["BloomThreshold"] = settings.bloom_threshold; - set["BloomSoftTreshold"] = settings.bloom_soft_threshold; - set["BloomDepth"] = settings.bloom_depth; - set["BloomRadius"] = settings.bloom_radius; - set["BloomStrength"] = settings.bloom_strength; - set["GammaToneMapping"] = settings.gamma_tone_mapping; - set["Exposure"] = settings.exposure; - set["Gamma"] = settings.gamma; - set["UseDirectionalShadowMap"] = settings.use_directional_shadow_map; - set["UsePointShadows"] = settings.use_directional_shadow_map; + set["Bloom"] = settings.Bloom; + set["BloomThreshold"] = settings.BloomThreshold; + set["BloomSoftTreshold"] = settings.BloomSoftThreshold; + set["BloomDepth"] = settings.BloomDepth; + set["BloomRadius"] = settings.BloomRadius; + set["BloomStrength"] = settings.BloomStrength; + set["GammaToneMapping"] = settings.GammaToneMapping; + set["Exposure"] = settings.Exposure; + set["Gamma"] = settings.Gamma; + set["UseDirectionalShadowMap"] = settings.UseDirectionalShadowMap; + set["UsePointShadows"] = settings.UsePointShadows; return set; } YAML::Node SaveTextures(const SceneAssets& assets) { - YAML::Node n_Textures; - for (const auto& texture : assets.textures) { - YAML::Node n_Texture; - n_Textures[texture.name] = n_Texture; - n_Texture["Path"] = RelativeToExecutable(texture.loading_props.path).generic_string(); - n_Texture["FlipUV"] = texture.loading_props.flip_uvs; - n_Texture["UUID"] = texture.id.Hex(); + YAML::Node n_textures; + for (const auto& texture : assets.Textures) { + YAML::Node n_texture; + n_textures[texture.Name] = n_texture; + n_texture["Path"] = Config::RelativeToExecutable(texture.LoadingProps.Path).generic_string(); + n_texture["FlipUV"] = texture.LoadingProps.FlipUV; + n_texture["UUID"] = texture.ID.Hex(); } - return n_Textures; + return n_textures; } YAML::Node SaveModels(const SceneAssets& assets) { - YAML::Node n_Models; - for (const auto& model : assets.render_meshes) { - YAML::Node n_Model; + YAML::Node n_models; + for (const auto& model : assets.RenderMeshes) { + YAML::Node n_model; - n_Models[model.name] = n_Model; - n_Model["Path"] = RelativeToExecutable(model.loading_props.path).generic_string(); - n_Model["Compress"] = model.loading_props.compress; - n_Model["FlipUV"] = model.loading_props.flip_uvs; - n_Model["UUID"] = model.id.Hex(); + n_models[model.Name] = n_model; + n_model["Path"] = Config::RelativeToExecutable(model.LoadingProps.Path).generic_string(); + n_model["Compress"] = model.LoadingProps.Compress; + n_model["FlipUV"] = model.LoadingProps.FlipUV; + n_model["UUID"] = model.ID.Hex(); } - return n_Models; + return n_models; } YAML::Node SaveScripts(const SceneAssets& assets) { - YAML::Node n_Scripts; - for (const auto& script : assets.scripts) { - YAML::Node n_Script; - n_Scripts[script.name] = n_Script; - n_Script["Path"] = RelativeToExecutable(script.path).generic_string(); - n_Script["UUID"] = script.id.Hex(); + YAML::Node n_scripts; + for (const auto& script : assets.Scripts) { + YAML::Node n_script; + n_scripts[script.Name] = n_script; + n_script["Path"] = Config::RelativeToExecutable(script.Path).generic_string(); + n_script["UUID"] = script.ID.Hex(); } - return n_Scripts; + return n_scripts; } YAML::Node SaveShaders(const SceneAssets& assets) { - YAML::Node n_Shaders; - for (const auto& shader : assets.shaders) { - YAML::Node n_Shader; - n_Shaders[shader.name] = n_Shader; - n_Shader["UUID"] = shader.id.Hex(); - for (const auto& part : shader.parts) { - n_Shader[ShaderPartTypeToString(part.type)] = RelativeToExecutable(part.path).generic_string(); + YAML::Node n_shaders; + for (const auto& shader : assets.Shaders) { + YAML::Node n_shader; + n_shaders[shader.Name] = n_shader; + n_shader["UUID"] = shader.ID.Hex(); + for (const auto& part : shader.Parts) { + n_shader[ShaderPartTypeToString(part.Type)] = Config::RelativeToExecutable(part.Path).generic_string(); } } - return n_Shaders; + return n_shaders; } YAML::Node SaveAssets(const SceneAssets& assets) { YAML::Node res; @@ -321,51 +320,51 @@ namespace DE { template void LoadComponent(Ref, YAML::Node, Entity&) { LOG_WARNING("Load function of {} undefined", DemangledName()); } - template <> void LoadComponent(Ref, YAML::Node n_Component, Entity& entity) { - entity.AddComponent(n_Component.as()); + template <> void LoadComponent(Ref, YAML::Node n_component, Entity& entity) { + entity.AddComponent(n_component.as()); } - template <> void LoadComponent(Ref, YAML::Node n_Component, Entity& entity) { - auto s = n_Component.as(); - entity.AddComponent(IDComponent(UUID(n_Component.as()))); + template <> void LoadComponent(Ref, YAML::Node n_component, Entity& entity) { + auto s = n_component.as(); + entity.AddComponent(IDComponent(UUID(n_component.as()))); } - template <> void LoadComponent(Ref, YAML::Node n_Component, Entity& entity) { + template <> void LoadComponent(Ref, YAML::Node n_component, Entity& entity) { TransformComponent transformation; - transformation.translation = GetVec3(n_Component["Translation"]); - transformation.translation_offset = GetVec3(n_Component["TranslationOffset"]); - transformation.rotation = GetVec3(n_Component["Rotation"]); - transformation.rotation_offet = GetVec3(n_Component["RotationOffset"]); - transformation.scale = GetVec3(n_Component["Scale"]); - transformation.scale_offset = GetVec3(n_Component["ScaleOffset"]); + transformation.Translation = GetVec3(n_component["Translation"]); + transformation.TranslationOffset = GetVec3(n_component["TranslationOffset"]); + transformation.Rotation = GetVec3(n_component["Rotation"]); + transformation.RotationOffet = GetVec3(n_component["RotationOffset"]); + transformation.Scale = GetVec3(n_component["Scale"]); + transformation.ScaleOffset = GetVec3(n_component["ScaleOffset"]); entity.AddComponent(transformation); } - template <> void LoadComponent(Ref, YAML::Node n_Component, Entity& entity) { - UUID id = n_Component["UUID"].as(); + template <> void LoadComponent(Ref, YAML::Node n_component, Entity& entity) { + UUID id = n_component["UUID"].as(); if (!ResourceManager::HasRenderMesh(id) && !ResourceManager::LoadRenderMesh(id)) { LOG_WARNING("RenderMesh {} not found in ResourceManager", id); } if (!ResourceManager::HasHitBox(id) && !ResourceManager::LoadHitBox(id)) { LOG_WARNING("Failed to load HitBox {}", id); } - auto& meshes = entity.AddComponent({id, ResourceManager::GetRenderMesh(id).value()->Copy()})->mesh->GetSubMeshes(); + auto& meshes = entity.AddComponent({id, ResourceManager::GetRenderMesh(id).value()->Copy()})->Mesh->GetSubMeshes(); - for (const auto& mat : n_Component["Materials"]) { - U32 mesh_id = mat["MeshID"].as(); - auto& material = meshes[mesh_id].material; - material.albedo = GetVec3(mat["Albedo"]); - material.ambient = GetVec3(mat["Ambient"]); - material.diffuse = GetVec3(mat["Diffuse"]); - material.specular = GetVec3(mat["Specular"]); - material.emission = GetVec3(mat["Emission"]); - material.orm = GetVec3(mat["ORM"]); - material.shininess = mat["Shininess"].as(); - material.emission_strength = mat["EmissionStrength"].as(); - material.type = MaterialTypeFromStr(mat["Type"].as()); + for (const auto& mat : n_component["Materials"]) { + U32 mesh_id = mat["MeshID"].as(); + auto& material = meshes[mesh_id].Material; + material.Albedo = GetVec3(mat["Albedo"]); + material.Ambient = GetVec3(mat["Ambient"]); + material.Diffuse = GetVec3(mat["Diffuse"]); + material.Specular = GetVec3(mat["Specular"]); + material.Emission = GetVec3(mat["Emission"]); + material.ORM = GetVec3(mat["ORM"]); + material.Shininess = mat["Shininess"].as(); + material.EmissionStrength = mat["EmissionStrength"].as(); + material.Type = MaterialTypeFromStr(mat["Type"].as()); } } - template <> void LoadComponent(Ref scene, YAML::Node n_Component, Entity& entity) { - UUID id = n_Component.as(); + template <> void LoadComponent(Ref scene, YAML::Node n_component, Entity& entity) { + UUID id = n_component.as(); if (!ResourceManager::HasShader(id) && !ResourceManager::LoadShader(id)) { LOG_WARNING("Shader {} not found in ResourceManager", id); } else { @@ -373,37 +372,37 @@ namespace DE { scene->GetRenderer()->RequestShader(id); } } - template <> void LoadComponent(Ref, YAML::Node n_Component, Entity& entity) { + template <> void LoadComponent(Ref, YAML::Node n_component, Entity& entity) { FPSCamera fps_camera; - fps_camera.SetFov(n_Component["FOV"].as()); - fps_camera.SetAspect(n_Component["Aspect"].as()); - fps_camera.SetNearPlane(n_Component["NearPlane"].as()); - fps_camera.SetFarPlane(n_Component["FarPlane"].as()); - fps_camera.SetPos(GetVec3(n_Component["Position"])); - fps_camera.SetDir(GetVec3(n_Component["Direction"])); + fps_camera.SetFov(n_component["FOV"].as()); + fps_camera.SetAspect(n_component["Aspect"].as()); + fps_camera.SetNearPlane(n_component["NearPlane"].as()); + fps_camera.SetFarPlane(n_component["FarPlane"].as()); + fps_camera.SetPos(GetVec3(n_component["Position"])); + fps_camera.SetDir(GetVec3(n_component["Direction"])); entity.AddComponent(fps_camera); } - template <> void LoadComponent(Ref, YAML::Node n_Component, Entity& entity) { + template <> void LoadComponent(Ref, YAML::Node n_component, Entity& entity) { LightSource light_source; - light_source.type = StringToLightSourceType(n_Component["Type"].as()); - light_source.ambient = GetVec3(n_Component["Ambient"]); - light_source.diffuse = GetVec3(n_Component["Diffuse"]); - light_source.specular = GetVec3(n_Component["Specular"]); - light_source.direction = GetVec3(n_Component["Direction"]); - light_source.position = GetVec3(n_Component["Position"]); - light_source.clq = GetVec3(n_Component["CLQ"]); - light_source.inner_cone_cos = n_Component["InnerCone"].as(); - light_source.outer_cone_cos = n_Component["OuterCone"].as(); + light_source.Type = StringToLightSourceType(n_component["Type"].as()); + light_source.Ambient = GetVec3(n_component["Ambient"]); + light_source.Diffuse = GetVec3(n_component["Diffuse"]); + light_source.Specular = GetVec3(n_component["Specular"]); + light_source.Direction = GetVec3(n_component["Direction"]); + light_source.Position = GetVec3(n_component["Position"]); + light_source.CLQ = GetVec3(n_component["CLQ"]); + light_source.InnerConeCosinus = n_component["InnerCone"].as(); + light_source.OuterConeCosinus = n_component["OuterCone"].as(); entity.AddComponent(light_source); } - template <> void LoadComponent(Ref, YAML::Node n_Component, Entity& entity) { - UUID id = n_Component["UUID"].as(); + template <> void LoadComponent(Ref, YAML::Node n_component, Entity& entity) { + UUID id = n_component["UUID"].as(); SkyBoxComponent::TexType type = - (n_Component["Type"].as() == "CubeMap" ? SkyBoxComponent::TexType::CubeMap : SkyBoxComponent::TexType::Equirectangular); + (n_component["Type"].as() == "CubeMap" ? SkyBoxComponent::TexType::CubeMap : SkyBoxComponent::TexType::Equirectangular); if (type == SkyBoxComponent::TexType::CubeMap) { if (!ResourceManager::HasCubeMap(id) && !ResourceManager::LoadCubeMap(id)) { LOG_WARNING("CubeMap {} not found in ResourceManager", id); @@ -417,53 +416,53 @@ namespace DE { LOG_WARNING("CubeMap {} not found in ResourceManager", id); } else { auto asset = AssetManager::GetTextureAsset(id); - Ref skybox = CreateRef(TextureLoader::Load(asset.value().loading_props)); + Ref skybox = CreateRef(TextureLoader::Load(asset.value().LoadingProps)); entity.AddComponent({type, id, skybox}); } } } - template <> void LoadComponent(Ref, YAML::Node n_Component, Entity& entity) { - ScriptComponent script = ScriptEngine::CreateScript(n_Component["UUID"].as()); + template <> void LoadComponent(Ref, YAML::Node n_component, Entity& entity) { + ScriptComponent script = ScriptEngine::CreateScript(n_component["UUID"].as()); entity.AddComponent(script); if (script.Valid()) { for (auto [name, field] : *script) { - if (n_Component["Fields"][name.get()]) { - GetField(n_Component["Fields"][name.get()], field); + if (n_component["Fields"][name.get()]) { + GetField(n_component["Fields"][name.get()], field); } } } else { LOG_INFO("Failed to create valid script: {}", script.ID()); } } - template <> void LoadComponent(Ref, YAML::Node n_Component, Entity& entity) { + template <> void LoadComponent(Ref, YAML::Node n_component, Entity& entity) { Physics::PhysicsComponent component{Vec3(0, 0, 0), Vec3(0, 0, 0), - n_Component["InvMass"].as(), - n_Component["InvInertia"].as(), - n_Component["Collidable"].as(), - n_Component["Gravity"].as(), + n_component["InvMass"].as(), + n_component["InvInertia"].as(), + n_component["Collidable"].as(), + n_component["Gravity"].as(), Vec3(0, 0, 0), Vec3(0, 0, 0)}; entity.AddComponent(component); } - Entity LoadEntity(Ref scene, YAML::Node n_Entity) { + Entity LoadEntity(Ref scene, YAML::Node n_entity) { Entity entity = scene->CreateEmptyEntity(); - if (n_Entity["Tag"]) LoadComponent(scene, n_Entity["Tag"], entity); - if (n_Entity["UUID"]) LoadComponent(scene, n_Entity["UUID"], entity); - if (n_Entity["Transformation"]) LoadComponent(scene, n_Entity["Transformation"], entity); - if (n_Entity["RenderModel"]) LoadComponent(scene, n_Entity["RenderModel"], entity); - if (n_Entity["Shader"]) LoadComponent(scene, n_Entity["Shader"], entity); - if (n_Entity["FPSCamera"]) LoadComponent(scene, n_Entity["FPSCamera"], entity); - if (n_Entity["LightSource"]) LoadComponent(scene, n_Entity["LightSource"], entity); - if (n_Entity["SkyBox"]) LoadComponent(scene, n_Entity["SkyBox"], entity); - if (n_Entity["Script"]) LoadComponent(scene, n_Entity["Script"], entity); - if (n_Entity["Physics"]) LoadComponent(scene, n_Entity["Physics"], entity); + if (n_entity["Tag"]) LoadComponent(scene, n_entity["Tag"], entity); + if (n_entity["UUID"]) LoadComponent(scene, n_entity["UUID"], entity); + if (n_entity["Transformation"]) LoadComponent(scene, n_entity["Transformation"], entity); + if (n_entity["RenderModel"]) LoadComponent(scene, n_entity["RenderModel"], entity); + if (n_entity["Shader"]) LoadComponent(scene, n_entity["Shader"], entity); + if (n_entity["FPSCamera"]) LoadComponent(scene, n_entity["FPSCamera"], entity); + if (n_entity["LightSource"]) LoadComponent(scene, n_entity["LightSource"], entity); + if (n_entity["SkyBox"]) LoadComponent(scene, n_entity["SkyBox"], entity); + if (n_entity["Script"]) LoadComponent(scene, n_entity["Script"], entity); + if (n_entity["Physics"]) LoadComponent(scene, n_entity["Physics"], entity); return entity; } - void LoadHierarchyNode(Ref scene, YAML::Node n_Array, SceneHierarchy::Node load_to) { - for (const auto& node : n_Array) { + void LoadHierarchyNode(Ref scene, YAML::Node n_array, SceneHierarchy::Node load_to) { + for (const auto& node : n_array) { if (node["Entity"]) { Entity entity = LoadEntity(scene, node["Entity"]); load_to.AddEntity(entity); @@ -479,66 +478,66 @@ namespace DE { { for (const auto& node : assets["Scripts"]) { ScriptAsset asset; - asset.id = node.second["UUID"].as(); - asset.name = node.first.as(); - asset.path = Config::GetPath(DE_CFG_EXECUTABLE_PATH) / node.second["Path"].as(); - data.scripts.emplace_back(std::move(asset)); + asset.ID = node.second["UUID"].as(); + asset.Name = node.first.as(); + asset.Path = Config::Get().ExecutablePath / node.second["Path"].as(); + data.Scripts.emplace_back(std::move(asset)); } } //*RenderMeshAssets { for (const auto& node : assets["Models"]) { RenderMeshAsset asset; - asset.name = node.first.as(); - asset.id = node.second["UUID"].as(); - asset.loading_props.compress = node.second["Compress"].as(); - asset.loading_props.flip_uvs = node.second["FlipUV"].as(); - std::string type = (node.second["MatType"] ? node.second["MatType"].as() : ""); - asset.loading_props.path = Config::GetPath(DE_CFG_EXECUTABLE_PATH) / node.second["Path"].as(); - data.render_meshes.emplace_back(std::move(asset)); + asset.Name = node.first.as(); + asset.ID = node.second["UUID"].as(); + asset.LoadingProps.Compress = node.second["Compress"].as(); + asset.LoadingProps.FlipUV = node.second["FlipUV"].as(); + std::string type = (node.second["MatType"] ? node.second["MatType"].as() : ""); + asset.LoadingProps.Path = Config::Get().ExecutablePath / node.second["Path"].as(); + data.RenderMeshes.emplace_back(std::move(asset)); } } //*TextureAssets { for (const auto& node : assets["Textures"]) { TextureAsset asset; - asset.id = node.second["UUID"].as(); - asset.name = node.first.as(); - asset.loading_props.flip_uvs = node.second["FlipUV"].as(); - asset.loading_props.path = Config::GetPath(DE_CFG_EXECUTABLE_PATH) / node.second["Path"].as(); - data.textures.emplace_back(std::move(asset)); + asset.ID = node.second["UUID"].as(); + asset.Name = node.first.as(); + asset.LoadingProps.FlipUV = node.second["FlipUV"].as(); + asset.LoadingProps.Path = Config::Get().ExecutablePath / node.second["Path"].as(); + data.Textures.emplace_back(std::move(asset)); } } //*ShaderAssets { - for (const auto& n_Shader : assets["Shaders"]) { + for (const auto& n_shader : assets["Shaders"]) { ShaderAsset asset; - asset.id = n_Shader.second["UUID"].as(); - asset.name = n_Shader.first.as(); - for (const auto& n_Part : n_Shader.second) { - if (n_Part.first.as() != "UUID") { + asset.ID = n_shader.second["UUID"].as(); + asset.Name = n_shader.first.as(); + for (const auto& n_part : n_shader.second) { + if (n_part.first.as() != "UUID") { ShaderPart shader_part; - shader_part.type = StringToShaderPartType(n_Part.first.as()); - shader_part.path = fs::canonical(Config::GetPath(DE_CFG_EXECUTABLE_PATH) / n_Part.second.as()); - asset.parts.push_back(shader_part); + shader_part.Type = StringToShaderPartType(n_part.first.as()); + shader_part.Path = fs::canonical(Config::Get().ExecutablePath / n_part.second.as()); + asset.Parts.push_back(shader_part); } } - data.shaders.emplace_back(std::move(asset)); + data.Shaders.emplace_back(std::move(asset)); } } } - void LoadRendererSettings(SceneRenderer::Settings& settings, YAML::Node node) { - settings.bloom = node["Bloom"].as(); - settings.bloom_threshold = node["BloomThreshold"].as(); - settings.bloom_soft_threshold = node["BloomSoftTreshold"].as(); - settings.bloom_depth = node["BloomDepth"].as(); - settings.bloom_radius = node["BloomRadius"].as(); - settings.bloom_strength = node["BloomStrength"].as(); - settings.gamma_tone_mapping = node["GammaToneMapping"].as(); - settings.exposure = node["Exposure"].as(); - settings.gamma = node["Gamma"].as(); + void LoadRendererSettings(SceneRenderer::GraphicsSettings& settings, YAML::Node node) { + settings.Bloom = node["Bloom"].as(); + settings.BloomThreshold = node["BloomThreshold"].as(); + settings.BloomSoftThreshold = node["BloomSoftTreshold"].as(); + settings.BloomDepth = node["BloomDepth"].as(); + settings.BloomRadius = node["BloomRadius"].as(); + settings.BloomStrength = node["BloomStrength"].as(); + settings.GammaToneMapping = node["GammaToneMapping"].as(); + settings.Exposure = node["Exposure"].as(); + settings.Gamma = node["Gamma"].as(); if (node["UseDirectionalShadowMap"].IsDefined()) { - settings.use_directional_shadow_map = node["UseDirectionalShadowMap"].as(); + settings.UseDirectionalShadowMap = node["UseDirectionalShadowMap"].as(); } } @@ -547,12 +546,12 @@ namespace DE { std::optional SceneLoader::LoadScene(const Path& path) { try { SceneFileData result; - YAML::Node n_Scene = YAML::LoadFile(path.string())["Scene"]; - LoadAssets(result.assets, n_Scene["Assets"]); - LoadRendererSettings(result.settings, n_Scene["RendererSettings"]); - result.hierarchy = n_Scene["Hierarchy"]; - result.name = n_Scene["Name"].as(); - LOG_INFO("Loaded SceneData for {}", RelativeToExecutable(path)); + YAML::Node n_scene = YAML::LoadFile(path.string())["Scene"]; + LoadAssets(result.Assets, n_scene["Assets"]); + LoadRendererSettings(result.Settings, n_scene["RendererSettings"]); + result.Hierarchy = n_scene["Hierarchy"]; + result.Name = n_scene["Name"].as(); + LOG_INFO("Loaded SceneData for {}", Config::RelativeToExecutable(path)); return result; } catch (const std::exception& e) { LOG_ERROR("Failed to load SceneData for {} due to exception: {}", path.string(), e.what()); @@ -577,27 +576,27 @@ namespace DE { } bool SceneLoader::SaveScene(const SceneFileData& data, const Path& path) { try { - YAML::Node n_Root, n_Scene; + YAML::Node n_root, n_scene; std::ofstream output_file; output_file.open(path); if (!output_file.is_open()) { - LOG_ERROR("Failed to open file {} to save scene", RelativeToExecutable(path)); + LOG_ERROR("Failed to open file {} to save scene", Config::RelativeToExecutable(path)); return false; } - n_Root["Scene"] = n_Scene; - n_Scene["Name"] = data.name; - n_Scene["Assets"] = SaveAssets(data.assets); - n_Scene["Hierarchy"] = data.hierarchy; - n_Scene["RendererSettings"] = SaveRendererSettings(data.settings); - output_file << n_Root; - LOG_INFO("Saved scene {} to file {}", data.name, RelativeToExecutable(path)); + n_root["Scene"] = n_scene; + n_scene["Name"] = data.Name; + n_scene["Assets"] = SaveAssets(data.Assets); + n_scene["Hierarchy"] = data.Hierarchy; + n_scene["RendererSettings"] = SaveRendererSettings(data.Settings); + output_file << n_root; + LOG_INFO("Saved scene {} to file {}", data.Name, Config::RelativeToExecutable(path)); return true; } catch (...) { - LOG_ERROR("Failed to open file {} to save scene", RelativeToExecutable(path)); + LOG_ERROR("Failed to open file {} to save scene", Config::RelativeToExecutable(path)); return false; } } -} // namespace DE \ No newline at end of file +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/ToolBox/Loaders/SceneLoader.h b/DummyEngine/ToolBox/Loaders/SceneLoader.h index c4a36c2..c1d58c2 100644 --- a/DummyEngine/ToolBox/Loaders/SceneLoader.h +++ b/DummyEngine/ToolBox/Loaders/SceneLoader.h @@ -1,31 +1,29 @@ #pragma once -// clang-format off -#include "DummyEngine/Utils/Base.h" #include "DummyEngine/Core/ResourceManaging/Assets.h" #include "DummyEngine/Core/Scene/Scene.h" #include "DummyEngine/Core/Scene/SceneRenderer.h" #include -// clang-format on -namespace DE { +namespace DummyEngine { + struct SceneAssets { - std::vector scripts; - std::vector render_meshes; - std::vector textures; - std::vector shaders; + std::vector Scripts; + std::vector RenderMeshes; + std::vector Textures; + std::vector Shaders; }; struct SceneFileData { - SceneRenderer::Settings settings; - SceneAssets assets; - YAML::Node hierarchy; - std::string name; + SceneRenderer::GraphicsSettings Settings; + SceneAssets Assets; + YAML::Node Hierarchy; + std::string Name; }; class SceneLoader { - LOGGER_AUTHOR(SceneLoader) + LOG_AUTHOR(SceneLoader) public: static std::optional LoadScene(const Path& path); static bool SaveScene(const SceneFileData& data, const Path& path); @@ -33,4 +31,4 @@ namespace DE { static YAML::Node Deserialize(Ref scene); }; -} // namespace DE \ No newline at end of file +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/ToolBox/Loaders/TextureLoader.cpp b/DummyEngine/ToolBox/Loaders/TextureLoader.cpp index d4402c1..3f00b44 100644 --- a/DummyEngine/ToolBox/Loaders/TextureLoader.cpp +++ b/DummyEngine/ToolBox/Loaders/TextureLoader.cpp @@ -1,41 +1,42 @@ -#include "DummyEngine/ToolBox/Loaders/TextureLoader.h" +#include "TextureLoader.h" + +#include "DummyEngine/Core/Application/Config.h" #include #include -#include "DummyEngine/Core/Application/Config.h" +namespace DummyEngine { -namespace DE { Ref TextureLoader::Load(const TextureAsset::LoadingProperties& props) { void* stb_data; - int width, height, nrChannels; + int width, height, nr_channels; TextureChannels channels; std::string channels_s; std::string format_s; auto res = CreateRef(); - stbi_set_flip_vertically_on_load(props.flip_uvs ? true : false); + stbi_set_flip_vertically_on_load(int(props.FlipUV)); - switch (props.format) { + switch (props.Format) { case TextureFormat::U8: - stb_data = stbi_load(props.path.string().c_str(), &width, &height, &nrChannels, 0); + stb_data = stbi_load(props.Path.string().c_str(), &width, &height, &nr_channels, 0); format_s = "U8"; break; case TextureFormat::Float: - stb_data = stbi_loadf(props.path.string().c_str(), &width, &height, &nrChannels, 0); + stb_data = stbi_loadf(props.Path.string().c_str(), &width, &height, &nr_channels, 0); format_s = "Float"; break; case TextureFormat::None: LOG_WARNING("Texture was not loaded because of unspecified format"); return res; default: DE_ASSERT(false, "Unsupported texture format"); break; } - if (!stb_data) { - LOG_ERROR("Failed to load texture {}", RelativeToExecutable(props.path)); + if (stb_data == nullptr) { + LOG_ERROR("Failed to load texture {}", Config::RelativeToExecutable(props.Path)); return nullptr; } - switch (nrChannels) { + switch (nr_channels) { case 1: channels_s = "RED"; channels = TextureChannels::RED; @@ -58,20 +59,11 @@ namespace DE { break; } - res->SetData(stb_data, width, height, channels, props.format); + res->SetData(stb_data, width, height, channels, props.Format); stbi_image_free(stb_data); - LOG_INFO("Texture {} loaded, channels ({}), format ({})", RelativeToExecutable(props.path), channels_s, format_s); + LOG_INFO("Texture {} loaded, channels ({}), format ({})", Config::RelativeToExecutable(props.Path), channels_s, format_s); return res; } - // void TextureLoader::Save(const Path& path, const Ref data) { - // switch (data->Format()) { - // case TextureChannels::RGBA: { - // stbi_write_png( - // path.string().c_str(), data->Width(), data->Height(), data->Channels(), data->Data(), data->Width() * data->Channels()); - // break; - // } - // default: break; - // } - // } -} // namespace DE \ No newline at end of file + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/ToolBox/Loaders/TextureLoader.h b/DummyEngine/ToolBox/Loaders/TextureLoader.h index c4fd18c..b6fea55 100644 --- a/DummyEngine/ToolBox/Loaders/TextureLoader.h +++ b/DummyEngine/ToolBox/Loaders/TextureLoader.h @@ -2,15 +2,14 @@ #include "DummyEngine/Core/ResourceManaging/Assets.h" #include "DummyEngine/Core/ResourceManaging/RawData.h" -#include "DummyEngine/Utils/Base.h" +#include "DummyEngine/Utils/Debug/Logger.h" -namespace DE { - namespace fs = std::filesystem; +namespace DummyEngine { class TextureLoader { - LOGGER_AUTHOR(TextureLoader) + LOG_AUTHOR(TextureLoader) public: static Ref Load(const TextureAsset::LoadingProperties& props); - // static void Save(const Path& path, const Ref data); }; -} // namespace DE \ No newline at end of file + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Utils/Base.h b/DummyEngine/Utils/Base.h deleted file mode 100644 index d986faf..0000000 --- a/DummyEngine/Utils/Base.h +++ /dev/null @@ -1,18 +0,0 @@ -#pragma once - -#include "DummyEngine/Utils/Base/CompilerSpecific.h" -#include "DummyEngine/Utils/Base/Constants.h" -#include "DummyEngine/Utils/Base/GLMIncludes.h" -#include "DummyEngine/Utils/Base/STDIncludes.h" -#include "DummyEngine/Utils/Debug/Assert.h" -#include "DummyEngine/Utils/Debug/Demangler.h" -#include "DummyEngine/Utils/Debug/Logger.h" -#include "DummyEngine/Utils/Debug/Profiler.h" -#include "DummyEngine/Utils/Debug/StackTrace.h" -#include "DummyEngine/Utils/Helpers/Conversions.h" -#include "DummyEngine/Utils/Helpers/Random.h" -#include "DummyEngine/Utils/Helpers/Singleton.h" -#include "DummyEngine/Utils/Helpers/StringOperations.h" -#include "DummyEngine/Utils/Helpers/Timer.h" -#include "DummyEngine/Utils/Types/STDAdapters.h" -#include "DummyEngine/Utils/Types/UUID.h" diff --git a/DummyEngine/Utils/Base/Constants.h b/DummyEngine/Utils/Base/Constants.h deleted file mode 100644 index a469e4a..0000000 --- a/DummyEngine/Utils/Base/Constants.h +++ /dev/null @@ -1,12 +0,0 @@ -#pragma once - -#include "DummyEngine/Utils/Types/Types.h" - -namespace DE { - namespace Constants { - const float DefaultCameraFOV = 90.0f; - const float DefaultCameraAspect = 16.0f / 9.0f; - const float DefaultCameraNearPlane = 0.1f; - const float DefaultCameraFarPlane = 2'000'000.0f; - } // namespace Constants -} // namespace DE \ No newline at end of file diff --git a/DummyEngine/Utils/Base/GLMIncludes.h b/DummyEngine/Utils/Base/GLMIncludes.h deleted file mode 100644 index bfcae2d..0000000 --- a/DummyEngine/Utils/Base/GLMIncludes.h +++ /dev/null @@ -1,9 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include -#include diff --git a/DummyEngine/Utils/Base/STDIncludes.h b/DummyEngine/Utils/Base/STDIncludes.h deleted file mode 100644 index b309a18..0000000 --- a/DummyEngine/Utils/Base/STDIncludes.h +++ /dev/null @@ -1,29 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include diff --git a/DummyEngine/Utils/DS/Trie.cpp b/DummyEngine/Utils/DS/Trie.cpp index 4efb077..306e451 100644 --- a/DummyEngine/Utils/DS/Trie.cpp +++ b/DummyEngine/Utils/DS/Trie.cpp @@ -1,21 +1,24 @@ #include "Trie.hpp" -namespace DE { - Ref Trie::getSuffixLink(Ref v) { +#include + +namespace DummyEngine { + + Ref Trie::GetSuffixLink(Ref v) { if (!v) { return v; } if (!v->suffix_link) { - if (v == m_root || v->parent == m_root) { - v->suffix_link = m_root; + if (v == root_ || v->parent == root_) { + v->suffix_link = root_; } else { - v->suffix_link = getNext(getSuffixLink(v->parent), v->char_to_parent); + v->suffix_link = GetNext(GetSuffixLink(v->parent), v->char_to_parent); } } return v->suffix_link; } - Ref Trie::getNext(Ref v, char c) { + Ref Trie::GetNext(Ref v, char c) { if (!v) { return v; } @@ -23,40 +26,40 @@ namespace DE { return v->next[c]; } else if (v->sons.contains(c)) { v->next[c] = v->sons[c]; - } else if (v == m_root) { - v->next[c] = m_root; + } else if (v == root_) { + v->next[c] = root_; } else { - v->next[c] = getNext(getSuffixLink(v), c); + v->next[c] = GetNext(GetSuffixLink(v), c); } return v->next[c]; } - Ref Trie::getUp(Ref v) { + Ref Trie::GetUp(Ref v) { if (!v) { return v; } if (!v->super_suffix_link) { - if (!getSuffixLink(v)->terminal_idx.empty()) { // leaf - v->super_suffix_link = getSuffixLink(v); - } else if (getSuffixLink(v) == m_root) { - v->super_suffix_link = m_root; + if (!GetSuffixLink(v)->terminal_idx.empty()) { // leaf + v->super_suffix_link = GetSuffixLink(v); + } else if (GetSuffixLink(v) == root_) { + v->super_suffix_link = root_; } else { - v->super_suffix_link = getUp(getSuffixLink(v)); + v->super_suffix_link = GetUp(GetSuffixLink(v)); } } return v->super_suffix_link; } void Trie::AddWord(std::string& str) { - Ref current = m_root; + Ref current = root_; for (const char c : str) { if (!current->sons.contains(c)) { current->sons[c] = CreateRef(current, c); } current = current->sons[c]; } - current->terminal_idx.push_back(m_words.size()); - m_words.push_back(CreateRef(str)); + current->terminal_idx.push_back(words_.size()); + words_.push_back(CreateRef(str)); } void Trie::Build(std::vector& dict) { @@ -68,22 +71,22 @@ namespace DE { std::vector> Trie::Search(std::string needle) { std::vector> result; std::set idx_found; - Ref current = m_root; + Ref current = root_; for (char c : needle) { - current = getNext(current, c); + current = GetNext(current, c); auto& ptr = current; - while (ptr != m_root) { + while (ptr != root_) { for (const auto& idx : ptr->terminal_idx) { if (idx_found.contains(idx)) { continue; } idx_found.insert(idx); - result.push_back(m_words[idx]); + result.push_back(words_[idx]); } - ptr = getUp(ptr); + ptr = GetUp(ptr); } } return result; } -} // namespace DE +} // namespace DummyEngine diff --git a/DummyEngine/Utils/DS/Trie.hpp b/DummyEngine/Utils/DS/Trie.hpp index 1ffbbf3..cc9dd00 100644 --- a/DummyEngine/Utils/DS/Trie.hpp +++ b/DummyEngine/Utils/DS/Trie.hpp @@ -1,8 +1,9 @@ #pragma once -#include "../Types/Types.h" +#include "DummyEngine/Utils/Types/Types.h" + +namespace DummyEngine { -namespace DE { class Trie { struct Node { Node(Ref& p, char prev) { @@ -21,9 +22,9 @@ namespace DE { Ref super_suffix_link; }; - Ref getSuffixLink(Ref v); - Ref getNext(Ref v, char c); - Ref getUp(Ref v); + Ref GetSuffixLink(Ref v); + Ref GetNext(Ref v, char c); + Ref GetUp(Ref v); public: void Build(std::vector& dict); @@ -31,7 +32,8 @@ namespace DE { std::vector> Search(std::string needle); private: - Ref m_root; - std::vector> m_words; + Ref root_; + std::vector> words_; }; -} // namespace DE \ No newline at end of file + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Utils/Debug/Assert.cpp b/DummyEngine/Utils/Debug/Assert.cpp index f10050e..da2dd0c 100644 --- a/DummyEngine/Utils/Debug/Assert.cpp +++ b/DummyEngine/Utils/Debug/Assert.cpp @@ -1,12 +1,14 @@ -#include "DummyEngine/Utils/Debug/Assert.h" +#include "Assert.h" -#include "DummyEngine/Utils/Base/STDIncludes.h" #include "DummyEngine/Utils/Debug/Logger.h" #include "DummyEngine/Utils/Debug/StackTrace.h" -namespace DE { +#include +#include - extern bool g_EnteredInMain; +namespace DummyEngine { + + extern bool gEnteredInMain; void FailAssert(const char* expr_str, const char* file, int line, const std::string& msg) { std::stringstream ss; @@ -20,7 +22,7 @@ namespace DE { if (Logger::Initialized()) { LOG_FATAL_AS("Assertion", "{}", ss.str()); } - exit(1); + abort(); } -} // namespace DE \ No newline at end of file +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Utils/Debug/Assert.h b/DummyEngine/Utils/Debug/Assert.h index 867595c..72fbe17 100644 --- a/DummyEngine/Utils/Debug/Assert.h +++ b/DummyEngine/Utils/Debug/Assert.h @@ -1,18 +1,20 @@ #pragma once -#include +#include // IWYU pragma: export + +namespace DummyEngine { -namespace DE { void FailAssert(const char* expr_str, const char* file, int line, const std::string& msg); +} // namespace DummyEngine + #if DE_ENABLE_ASSERTS -#define DE_ASSERT(Expr, ...) \ - do { \ - if (!(Expr)) { \ - FailAssert(#Expr, __FILE__, __LINE__, std::format(__VA_ARGS__)); \ - } \ +#define DE_ASSERT(Expr, ...) \ + do { \ + if (!(Expr)) { \ + ::DummyEngine::FailAssert(#Expr, __FILE__, __LINE__, std::format(__VA_ARGS__)); \ + } \ } while (false) #else #define DE_ASSERT(Expr, Msg) -#endif -} // namespace DE +#endif \ No newline at end of file diff --git a/DummyEngine/Utils/Debug/Demangler.h b/DummyEngine/Utils/Debug/Demangler.h index 483e010..6148bc4 100644 --- a/DummyEngine/Utils/Debug/Demangler.h +++ b/DummyEngine/Utils/Debug/Demangler.h @@ -8,4 +8,4 @@ #endif #ifdef DE_PLATFORM_MACOS #include "DummyEngine/Platform/Macos/Utils/Debug/Demangler.h" -#endif \ No newline at end of file +#endif diff --git a/DummyEngine/Utils/Debug/Logger.cpp b/DummyEngine/Utils/Debug/Logger.cpp index b611c32..01a670f 100644 --- a/DummyEngine/Utils/Debug/Logger.cpp +++ b/DummyEngine/Utils/Debug/Logger.cpp @@ -1,111 +1,116 @@ -#include "DummyEngine/Utils/Debug/Logger.h" +#include "Logger.h" #include "DummyEngine/Core/Application/Config.h" #include "DummyEngine/Core/Application/FileSystem.h" #include "DummyEngine/Core/Console/Console.hpp" #include "DummyEngine/Utils/Debug/Assert.h" -namespace DE { - std::string Logger::Record::LogRecordTypeToStr(Type type) { +#include // IWYU pragma: keep +#include +#include + +namespace DummyEngine { + + std::string Logger::Record::LogRecordTypeToStr(RecordType type) { switch (type) { - case Type::Debug: return "Debug"; - case Type::Info: return "Info"; - case Type::Warning: return "Warning"; - case Type::Error: return "Error"; - case Type::Fatal: return "Fatal"; + case RecordType::Debug: return "Debug"; + case RecordType::Info: return "Info"; + case RecordType::Warning: return "Warning"; + case RecordType::Error: return "Error"; + case RecordType::Fatal: return "Fatal"; default: return "None"; } } std::string Logger::Record::ToString() const { - auto type_str = std::format("[{}]", LogRecordTypeToStr(type)); - auto author_str = author.empty() ? author : std::format("[{}]", author); - return std::format("[{}] {: >9} {: <20} {}\n", timestamp, type_str, author_str, message); + auto type_str = std::format("[{}]", LogRecordTypeToStr(Type)); + auto author_str = Author.empty() ? Author : std::format("[{}]", Author); + return std::format("[{}] {: >9} {: <20} {}\n", Timestamp, type_str, author_str, Message); } SINGLETON_BASE(Logger); S_INITIALIZE() { - FileSystem::CreateDirectory(Config::GetPath(DE_CFG_LOG_PATH)); - auto& log = m_Streams.emplace(kDefaultLog, LogStream()).first->second; - auto path = Config::GetPath(DE_CFG_LOG_PATH) / kDefaultLogFileName; - log.stream.open(path); - DE_ASSERT(log.stream.is_open(), "Failed to open default log: {}", path.string()); + FileSystem::CreateDirectory(Config::Get().LogPath); + auto& log = streams_.emplace(kDefaultLog, LogStream()).first->second; + auto path = Config::Get().LogPath / kDefaultLogFileName; + log.Stream.open(path); + DE_ASSERT(log.Stream.is_open(), "Failed to open default log: {}", path.string()); return Unit(); } S_TERMINATE() { - for (auto& [name, stream] : m_Streams) { - stream.stream.close(); + for (auto& [name, stream] : streams_) { + stream.Stream.close(); } - m_Streams.clear(); + streams_.clear(); return Unit(); } S_METHOD_IMPL(bool, Open, (const std::string& log_name), (log_name)) { - auto [it, emplaced] = m_Streams.emplace(log_name, LogStream()); + auto [it, emplaced] = streams_.emplace(log_name, LogStream()); if (!emplaced) { return false; } auto& log = it->second; - FileSystem::CreateDirectory(Config::GetPath(DE_CFG_LOG_PATH)); - log.stream.open(Config::GetPath(DE_CFG_LOG_PATH) / (log_name + ".txt")); - if (!log.stream.is_open()) { - m_Streams.erase(it); + FileSystem::CreateDirectory(Config::Get().LogPath); + log.Stream.open(Config::Get().LogPath / (log_name + ".txt")); + if (!log.Stream.is_open()) { + streams_.erase(it); return false; } return true; } S_METHOD_IMPL(Unit, Close, (const std::string& log_name), (log_name)) { - m_Streams.erase(log_name); + streams_.erase(log_name); return Unit(); } S_METHOD_IMPL(Unit, Log, (const std::string& log, Record&& record), (log, std::move(record))) { - auto it = m_Streams.find(log); - if (it == m_Streams.end()) { + auto it = streams_.find(log); + if (it == streams_.end()) { return Unit(); } auto& stream = it->second; - stream.records.push_back(std::move(record)); - if (stream.records.size() > stream.depth) { - stream.records.pop_front(); + stream.Records.push_back(std::move(record)); + if (stream.Records.size() > stream.Depth) { + stream.Records.pop_front(); } - auto log_string = stream.records.back().ToString(); + auto log_string = stream.Records.back().ToString(); Console::PushLog(log_string); std::cout << log_string; - stream.stream << log_string; - stream.stream.flush(); - if (stream.records.back().type == Record::Type::Fatal) { + stream.Stream << log_string; + stream.Stream.flush(); + if (stream.Records.back().Type == RecordType::Fatal) { ITerminate(); } return Unit(); } S_METHOD_IMPL(const std::deque&, GetRecords, (const std::string& log), (log)) { - if (!m_Streams.contains(log)) { - return m_Empty; + if (!streams_.contains(log)) { + return empty_; } - return m_Streams[log].records; + return streams_[log].Records; } S_METHOD_IMPL(Unit, SetLogDepth, (U32 depth, const std::string& log), (depth, log)) { - if (!m_Streams.contains(log)) { + if (!streams_.contains(log)) { return Unit(); } - m_Streams[log].depth = depth; + streams_[log].Depth = depth; return Unit(); } - void LogWithAuthor(const std::string& log, Logger::Record::Type type, const std::string& author, std::string&& message) { + void LogWithAuthor(const std::string& log, Logger::RecordType type, const std::string& author, std::string&& message) { Logger::Record record; - record.author = author; - record.timestamp = Logger::Record::Clock::now(); - record.type = type; - record.message = std::move(message); + record.Author = author; + record.Timestamp = Logger::Record::Clock::now(); + record.Type = type; + record.Message = std::move(message); Logger::Log(log, std::move(record)); } - void Log(const std::string& log, Logger::Record::Type type, std::string&& message) { + void Log(const std::string& log, Logger::RecordType type, std::string&& message) { LogWithAuthor(log, type, Logger::kDefaultAuthor, std::move(message)); } -} // namespace DE \ No newline at end of file +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Utils/Debug/Logger.h b/DummyEngine/Utils/Debug/Logger.h index c2f9bb3..2710087 100644 --- a/DummyEngine/Utils/Debug/Logger.h +++ b/DummyEngine/Utils/Debug/Logger.h @@ -1,35 +1,38 @@ #pragma once -#include "DummyEngine/Utils/Base/STDIncludes.h" +#include "DummyEngine/Utils/Helpers/STDAdapters.h" // IWYU pragma: export #include "DummyEngine/Utils/Helpers/Singleton.h" #include "DummyEngine/Utils/Types/Types.h" -namespace DE { +#include + +namespace DummyEngine { class Logger : public Singleton { public: + enum class RecordType { + None = 0, + Debug, + Info, + Warning, + Error, + Fatal, + }; + struct Record { public: - enum class Type { - None = 0, - Debug, - Info, - Warning, - Error, - Fatal, - }; using Clock = std::chrono::system_clock; using TimeStamp = std::chrono::time_point; public: - static std::string LogRecordTypeToStr(Type type); + static std::string LogRecordTypeToStr(RecordType type); std::string ToString() const; public: - TimeStamp timestamp; - Type type; - std::string author; - std::string message; + TimeStamp Timestamp; + RecordType Type; + std::string Author; + std::string Message; }; public: @@ -49,37 +52,43 @@ namespace DE { private: struct LogStream { - std::deque records; - std::ofstream stream; - U32 depth = 32; + std::deque Records; + std::ofstream Stream; + U32 Depth = 32; }; - std::deque m_Empty; - std::unordered_map m_Streams; + std::deque empty_; + std::unordered_map streams_; }; - void LogWithAuthor(const std::string& log, Logger::Record::Type type, const std::string& author, std::string&& message); - void Log(const std::string& log, Logger::Record::Type type, std::string&& message); + void LogWithAuthor(const std::string& log, Logger::RecordType type, const std::string& author, std::string&& message); + void Log(const std::string& log, Logger::RecordType type, std::string&& message); -} // namespace DE +} // namespace DummyEngine #if DE_ENABLE_LOGGING == 1 -#define LOGGER_AUTHOR(author) \ -private: \ - static void Log(const std::string& log, Logger::Record::Type type, std::string&& message) { \ - LogWithAuthor(log, type, #author, std::move(message)); \ +#define LOG_AUTHOR(author) \ +private: \ + static void Log(const std::string& log, Logger::RecordType type, std::string&& message) { \ + LogWithAuthor(log, type, #author, std::move(message)); \ } -#define LOG_DEBUG(...) Log(::DE::Logger::kDefaultLog, ::DE::Logger::Record::Type::Debug, std::format(__VA_ARGS__)) -#define LOG_INFO(...) Log(::DE::Logger::kDefaultLog, ::DE::Logger::Record::Type::Info, std::format(__VA_ARGS__)) -#define LOG_WARNING(...) Log(::DE::Logger::kDefaultLog, ::DE::Logger::Record::Type::Warning, std::format(__VA_ARGS__)) -#define LOG_ERROR(...) Log(::DE::Logger::kDefaultLog, ::DE::Logger::Record::Type::Error, std::format(__VA_ARGS__)) -#define LOG_FATAL(...) Log(::DE::Logger::kDefaultLog, ::DE::Logger::Record::Type::Fatal, std::format(__VA_ARGS__)) -#define LOG_DEBUG_AS(author, ...) LogWithAuthor(::DE::Logger::kDefaultLog, ::DE::Logger::Record::Type::Debug, author, std::format(__VA_ARGS__)) -#define LOG_INFO_AS(author, ...) LogWithAuthor(::DE::Logger::kDefaultLog, ::DE::Logger::Record::Type::Info, author, std::format(__VA_ARGS__)) -#define LOG_WARNING_AS(author, ...) LogWithAuthor(::DE::Logger::kDefaultLog, ::DE::Logger::Record::Type::Warning, author, std::format(__VA_ARGS__)) -#define LOG_ERROR_AS(author, ...) LogWithAuthor(::DE::Logger::kDefaultLog, ::DE::Logger::Record::Type::Error, author, std::format(__VA_ARGS__)) -#define LOG_FATAL_AS(author, ...) LogWithAuthor(::DE::Logger::kDefaultLog, ::DE::Logger::Record::Type::Fatal, author, std::format(__VA_ARGS__)) +#define LOG_DEBUG(...) Log(::DummyEngine::Logger::kDefaultLog, ::DummyEngine::Logger::RecordType::Debug, std::format(__VA_ARGS__)) +#define LOG_INFO(...) Log(::DummyEngine::Logger::kDefaultLog, ::DummyEngine::Logger::RecordType::Info, std::format(__VA_ARGS__)) +#define LOG_WARNING(...) Log(::DummyEngine::Logger::kDefaultLog, ::DummyEngine::Logger::RecordType::Warning, std::format(__VA_ARGS__)) +#define LOG_ERROR(...) Log(::DummyEngine::Logger::kDefaultLog, ::DummyEngine::Logger::RecordType::Error, std::format(__VA_ARGS__)) +#define LOG_FATAL(...) Log(::DummyEngine::Logger::kDefaultLog, ::DummyEngine::Logger::RecordType::Fatal, std::format(__VA_ARGS__)) + +#define LOG_DEBUG_AS(author, ...) \ + LogWithAuthor(::DummyEngine::Logger::kDefaultLog, ::DummyEngine::Logger::RecordType::Debug, author, std::format(__VA_ARGS__)) +#define LOG_INFO_AS(author, ...) \ + LogWithAuthor(::DummyEngine::Logger::kDefaultLog, ::DummyEngine::Logger::RecordType::Info, author, std::format(__VA_ARGS__)) +#define LOG_WARNING_AS(author, ...) \ + LogWithAuthor(::DummyEngine::Logger::kDefaultLog, ::DummyEngine::Logger::RecordType::Warning, author, std::format(__VA_ARGS__)) +#define LOG_ERROR_AS(author, ...) \ + LogWithAuthor(::DummyEngine::Logger::kDefaultLog, ::DummyEngine::Logger::RecordType::Error, author, std::format(__VA_ARGS__)) +#define LOG_FATAL_AS(author, ...) \ + LogWithAuthor(::DummyEngine::Logger::kDefaultLog, ::DummyEngine::Logger::RecordType::Fatal, author, std::format(__VA_ARGS__)) #else -#define LOGGER_AUTHOR(author) +#define LOG_AUTHOR(author) #define LOG_DEBUG(...) #define LOG_INFO(...) #define LOG_WARNING(...) diff --git a/DummyEngine/Utils/Debug/Profiler.cpp b/DummyEngine/Utils/Debug/Profiler.cpp index a3226e0..92f9198 100644 --- a/DummyEngine/Utils/Debug/Profiler.cpp +++ b/DummyEngine/Utils/Debug/Profiler.cpp @@ -1,8 +1,9 @@ -#include "DummyEngine/Utils/Debug/Profiler.h" +#include "Profiler.h" + +namespace DummyEngine { -namespace DE { ProfilerFrame::ProfilerFrame(U32 predicted_lapse_amount) { - m_TimeLapses.reserve(predicted_lapse_amount); + Timelapses.reserve(predicted_lapse_amount); } SINGLETON_BASE(Profiler); @@ -16,39 +17,39 @@ namespace DE { } S_METHOD_IMPL(const ProfilerFrame&, GetOldestFrame, (), ()) { - return Get().m_Frames.front(); + return frames_.front(); } S_METHOD_IMPL(Unit, BeginFrame, (), ()) { - if (!m_Frames.empty()) { + if (!frames_.empty()) { IPopTimeLapse(); } - m_Frames.push(ProfilerFrame(m_PrevFrameTimeLapseAmount)); - m_PrevFrameTimeLapseAmount = 0; + frames_.push(ProfilerFrame(prev_frame_timelapse_amount_)); + prev_frame_timelapse_amount_ = 0; // TODO: Move somewhere frame storage size. - if (m_Frames.size() > 2) { - m_Frames.pop(); + if (frames_.size() > 2) { + frames_.pop(); } IPushTimeLapse("Frame"); return Unit(); } S_METHOD_IMPL(Unit, PushTimeLapse, (const std::string& name), (name)) { - ++m_PrevFrameTimeLapseAmount; - U32 index = m_Frames.back().m_TimeLapses.size(); - m_Frames.back().m_TimeLapses.push_back(TimeLapse(name)); - m_Frames.back().m_TimeLapses.back().m_Start = std::chrono::high_resolution_clock::now(); - if (!m_TimeLapseStack.empty()) { - m_Frames.back().m_TimeLapses[m_TimeLapseStack.top()].m_Childs.push_back(index); + ++prev_frame_timelapse_amount_; + U32 index = frames_.back().Timelapses.size(); + frames_.back().Timelapses.push_back(TimeLapse(name)); + frames_.back().Timelapses.back().Start = std::chrono::high_resolution_clock::now(); + if (!timelapse_stack_.empty()) { + frames_.back().Timelapses[timelapse_stack_.top()].Childs.push_back(index); } - m_TimeLapseStack.push(index); + timelapse_stack_.push(index); return Unit(); } S_METHOD_IMPL(Unit, PopTimeLapse, (), ()) { - DE_ASSERT(!m_TimeLapseStack.empty(), "Attempt to pop empty timelapse stack."); + DE_ASSERT(!timelapse_stack_.empty(), "Attempt to pop empty timelapse stack."); - m_Frames.back().m_TimeLapses[m_TimeLapseStack.top()].m_End = std::chrono::high_resolution_clock::now(); - m_TimeLapseStack.pop(); + frames_.back().Timelapses[timelapse_stack_.top()].End = std::chrono::high_resolution_clock::now(); + timelapse_stack_.pop(); return Unit(); } @@ -59,4 +60,4 @@ namespace DE { Profiler::PopTimeLapse(); } -} // namespace DE \ No newline at end of file +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Utils/Debug/Profiler.h b/DummyEngine/Utils/Debug/Profiler.h index eba14cb..77fb75c 100644 --- a/DummyEngine/Utils/Debug/Profiler.h +++ b/DummyEngine/Utils/Debug/Profiler.h @@ -1,5 +1,8 @@ #pragma once +#include "DummyEngine/Utils/Helpers/Singleton.h" +#include "DummyEngine/Utils/Types/Types.h" + #include #include #include @@ -7,25 +10,23 @@ #include #include -#include "DummyEngine/Utils/Helpers/Singleton.h" -#include "DummyEngine/Utils/Types/Types.h" +namespace DummyEngine { -namespace DE { struct TimeLapse { - std::chrono::time_point m_Start; - std::chrono::time_point m_End; - std::vector m_Childs; - std::string m_Name; + std::chrono::time_point Start; + std::chrono::time_point End; + std::vector Childs; + std::string Name; - float Duration() const { return (m_End - m_Start).count() * 0.001 * 0.001; } - std::string StrDuration() const { return std::to_string((m_End - m_Start).count() * 0.001 * 0.001) + "ms"; } + float Duration() const { return (End - Start).count() * 0.001 * 0.001; } + std::string StrDuration() const { return std::to_string((End - Start).count() * 0.001 * 0.001) + "ms"; } - TimeLapse(const std::string& name) : m_Name(name) {} + explicit TimeLapse(const std::string& name) : Name(name) {} }; struct ProfilerFrame { - std::vector m_TimeLapses; + std::vector Timelapses; - ProfilerFrame(U32 predicted_lapse_amount); + explicit ProfilerFrame(U32 predicted_lapse_amount); }; class Profiler : public Singleton { @@ -39,17 +40,19 @@ namespace DE { private: friend class ProfilerScopeObject; - std::queue m_Frames; - std::stack m_TimeLapseStack; - U32 m_PrevFrameTimeLapseAmount = 0; + std::queue frames_; + std::stack timelapse_stack_; + U32 prev_frame_timelapse_amount_ = 0; }; class ProfilerScopeObject { public: - ProfilerScopeObject(const std::string& name); + explicit ProfilerScopeObject(const std::string& name); ~ProfilerScopeObject(); }; +} // namespace DummyEngine + #if DE_ENABLE_PROFILER #define DE_PROFILE_SCOPE(name) \ ProfilerScopeObject profiler_scope_object(name); \ @@ -64,5 +67,3 @@ namespace DE { #define DE_PROFILE_SCOPE(name) #define DE_PROFILER_BEGIN_FRAME() #endif - -} // namespace DE \ No newline at end of file diff --git a/DummyEngine/Utils/Debug/StackTrace.h b/DummyEngine/Utils/Debug/StackTrace.h index 8895272..51716f0 100644 --- a/DummyEngine/Utils/Debug/StackTrace.h +++ b/DummyEngine/Utils/Debug/StackTrace.h @@ -1,7 +1,9 @@ #pragma once -#include "DummyEngine/Utils/Base/STDIncludes.h" +#include + +namespace DummyEngine { -namespace DE { std::string StackTrace(); + } \ No newline at end of file diff --git a/DummyEngine/Utils/Base/CompilerSpecific.h b/DummyEngine/Utils/Helpers/CompilerSpecific.h similarity index 78% rename from DummyEngine/Utils/Base/CompilerSpecific.h rename to DummyEngine/Utils/Helpers/CompilerSpecific.h index 89dca6d..689e624 100644 --- a/DummyEngine/Utils/Base/CompilerSpecific.h +++ b/DummyEngine/Utils/Helpers/CompilerSpecific.h @@ -1,5 +1,6 @@ #pragma once -#include "DummyEngine/Utils/Types/Types.h" + +#include "DummyEngine/Utils/Types/Types.h" // IWYU pragma: keep #ifdef __GNUC__ #define DE_COMPILER_GCC_VERSION_MAJOR __GNUC__ @@ -21,7 +22,6 @@ #endif #if DE_PLATFORM_WINDOWS -#define YAML_CPP_STATIC_DEFINE #define DE_SCRIPT_API extern "C" __declspec(dllexport) #endif @@ -34,10 +34,10 @@ #undef DE_COMPILER_PATH_HASH #endif -namespace std { +namespace std { // NOLINT #ifndef DE_COMPILER_PATH_HASH - template <> struct hash { - std::size_t operator()(const DE::Path& path) const { return hash_value(path); } + template <> struct hash { + std::size_t operator()(const DummyEngine::Path& path) const { return hash_value(path); } }; #endif } // namespace std diff --git a/DummyEngine/Utils/Helpers/Conversions.cpp b/DummyEngine/Utils/Helpers/Conversions.cpp index d874b86..2bc3cfa 100644 --- a/DummyEngine/Utils/Helpers/Conversions.cpp +++ b/DummyEngine/Utils/Helpers/Conversions.cpp @@ -1,6 +1,7 @@ -#include "DummyEngine/Utils/Helpers/Conversions.h" +#include "Conversions.h" + +namespace DummyEngine { -namespace DE { std::ostream& operator<<(std::ostream& os, const Vec2& vec) { os << "(" << vec.x << " " << vec.y << ")"; return os; @@ -20,4 +21,5 @@ namespace DE { << " " << mat[1][3] << " " << mat[2][3] << " " << mat[3][3] << "))"; return os; } -} // namespace DE \ No newline at end of file + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Utils/Helpers/Conversions.h b/DummyEngine/Utils/Helpers/Conversions.h index ecfe91a..4ac91f7 100644 --- a/DummyEngine/Utils/Helpers/Conversions.h +++ b/DummyEngine/Utils/Helpers/Conversions.h @@ -1,11 +1,14 @@ #pragma once -#include "DummyEngine/Utils/Base/STDIncludes.h" #include "DummyEngine/Utils/Types/Types.h" -namespace DE { +#include + +namespace DummyEngine { + std::ostream& operator<<(std::ostream& os, const Vec2& vec); std::ostream& operator<<(std::ostream& os, const Vec3& vec); std::ostream& operator<<(std::ostream& os, const Vec4& vec); std::ostream& operator<<(std::ostream& os, const Mat4& vec); -} // namespace DE \ No newline at end of file + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Utils/Helpers/Random.cpp b/DummyEngine/Utils/Helpers/Random.cpp index 35c5e98..143622e 100644 --- a/DummyEngine/Utils/Helpers/Random.cpp +++ b/DummyEngine/Utils/Helpers/Random.cpp @@ -1,16 +1,17 @@ -#include "DummyEngine/Utils/Helpers/Random.h" +#include "Random.h" -#include "DummyEngine/Utils/Types/Types.h" +#include -namespace DE { +namespace DummyEngine { - std::mt19937 s_Generator(time(0)); + static thread_local std::mt19937 gGenerator(time(nullptr)); float Random::Float(float range_begin, float range_end) { - float tmp = ((float)s_Generator() / (float)std::numeric_limits::max()); + float tmp = ((float)gGenerator() / (float)std::numeric_limits::max()); return tmp * range_end + (1 - tmp) * range_begin; } S32 Random::Int(S32 range_begin, S32 range_end) { return Float(range_begin, range_end); } -} // namespace DE \ No newline at end of file + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Utils/Helpers/Random.h b/DummyEngine/Utils/Helpers/Random.h index 7f4a313..3a63f1c 100644 --- a/DummyEngine/Utils/Helpers/Random.h +++ b/DummyEngine/Utils/Helpers/Random.h @@ -2,10 +2,12 @@ #include "DummyEngine/Utils/Types/Types.h" -namespace DE { +namespace DummyEngine { + class Random { public: static float Float(float range_begin = 0.0f, float range_end = 1.0f); static S32 Int(S32 range_begin = 0, S32 rang_end = 1024); }; -} // namespace DE \ No newline at end of file + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Utils/Helpers/STDAdapters.h b/DummyEngine/Utils/Helpers/STDAdapters.h new file mode 100644 index 0000000..1302fa1 --- /dev/null +++ b/DummyEngine/Utils/Helpers/STDAdapters.h @@ -0,0 +1,27 @@ +#pragma once + +#include "DummyEngine/Utils/Types/Types.h" +#include "DummyEngine/Utils/Types/UUID.h" + +#include + +namespace std { + template <> struct formatter : formatter { + auto format(const DummyEngine::Vec3& vec, format_context& ctx) const { + return formatter::format(std::format("({}, {}, {})", vec.x, vec.y, vec.z), ctx); + } + }; + template <> struct formatter : formatter { + auto format(const DummyEngine::Vec4& vec, format_context& ctx) const { + return formatter::format(std::format("({}, {}, {}, {})", vec.x, vec.y, vec.z, vec.w), ctx); + } + }; + + template <> struct formatter : formatter { + auto format(const DummyEngine::Path& path, format_context& ctx) const { return formatter::format(path.string(), ctx); } + }; + + template <> struct formatter : formatter { + auto format(const DummyEngine::UUID& uuid, format_context& ctx) const { return formatter::format(uuid.Hex(), ctx); } + }; +} // namespace std \ No newline at end of file diff --git a/DummyEngine/Utils/Helpers/Singleton.h b/DummyEngine/Utils/Helpers/Singleton.h index 6248506..479595c 100644 --- a/DummyEngine/Utils/Helpers/Singleton.h +++ b/DummyEngine/Utils/Helpers/Singleton.h @@ -2,8 +2,6 @@ #include "DummyEngine/Utils/Debug/Assert.h" -struct Unit {}; - #define SINGLETON(type) \ private: \ friend class Singleton; \ @@ -19,16 +17,16 @@ public: \ S_METHOD_DEF(Unit, Initialize, ()); \ S_METHOD_DEF(Unit, Terminate, ()); -#define SINGLETON_BASE(type) \ - static const std::string CurrentSingletonName = #type; \ - template <> type* Singleton::s_Instance = nullptr; \ - template <> type& Singleton::Get() { \ - DE_ASSERT(s_Instance, "Using {} before initialization", CurrentSingletonName); \ - return *s_Instance; \ - } \ - bool type::Initialized() { \ - return s_Instance != nullptr; \ - } \ +#define SINGLETON_BASE(type) \ + static const std::string CurrentSingletonName = #type; \ + template <> type* Singleton::gInstance = nullptr; \ + template <> type& Singleton::GetInstance() { \ + DE_ASSERT(gInstance, "Using {} before initialization", CurrentSingletonName); \ + return *gInstance; \ + } \ + bool type::Initialized() { \ + return gInstance != nullptr; \ + } \ using CurrentSingleton = type #define DEL_BRACKETS(a) SECOND(FIRST a) @@ -39,7 +37,7 @@ public: \ #define S_METHOD(return_type, name, signature, variables) \ static DEL_BRACKETS(return_type) name(DEL_BRACKETS(signature)) { \ - return Get().I##name(DEL_BRACKETS(variables)); \ + return GetInstance().I##name(DEL_BRACKETS(variables)); \ } \ DEL_BRACKETS(return_type) I##name(DEL_BRACKETS(signature)) @@ -47,32 +45,35 @@ public: \ static DEL_BRACKETS(return_type) name(DEL_BRACKETS(signature)); \ DEL_BRACKETS(return_type) I##name(DEL_BRACKETS(signature)); -#define S_METHOD_IMPL(return_type, name, signature, variables) \ - DEL_BRACKETS(return_type) CurrentSingleton::name(DEL_BRACKETS(signature)) { \ - return CurrentSingleton::Get().I##name(DEL_BRACKETS(variables)); \ - } \ +#define S_METHOD_IMPL(return_type, name, signature, variables) \ + DEL_BRACKETS(return_type) CurrentSingleton::name(DEL_BRACKETS(signature)) { \ + return CurrentSingleton::GetInstance().I##name(DEL_BRACKETS(variables)); \ + } \ DEL_BRACKETS(return_type) CurrentSingleton::I##name(DEL_BRACKETS(signature)) -#define S_INITIALIZE() \ - Unit CurrentSingleton::Initialize() { \ - DE_ASSERT(!s_Instance, "Double initialization of {}", CurrentSingletonName); \ - s_Instance = new CurrentSingleton(); \ - DE_ASSERT(s_Instance, "Failed to allocate memory for {}", CurrentSingletonName); \ - s_Instance->IInitialize(); \ - return Unit(); \ - } \ +#define S_INITIALIZE() \ + Unit CurrentSingleton::Initialize() { \ + DE_ASSERT(!gInstance, "Double initialization of {}", CurrentSingletonName); \ + gInstance = new CurrentSingleton(); \ + DE_ASSERT(gInstance, "Failed to allocate memory for {}", CurrentSingletonName); \ + gInstance->IInitialize(); \ + return Unit(); \ + } \ Unit CurrentSingleton::IInitialize() -#define S_TERMINATE() \ - Unit CurrentSingleton::Terminate() { \ - DE_ASSERT(s_Instance, "Terminating before initialization of {}", CurrentSingletonName); \ - s_Instance->ITerminate(); \ - delete s_Instance; \ - s_Instance = nullptr; \ - return Unit(); \ - } \ +#define S_TERMINATE() \ + Unit CurrentSingleton::Terminate() { \ + DE_ASSERT(gInstance, "Terminating before initialization of {}", CurrentSingletonName); \ + gInstance->ITerminate(); \ + delete gInstance; \ + gInstance = nullptr; \ + return Unit(); \ + } \ Unit CurrentSingleton::ITerminate() -namespace DE { +namespace DummyEngine { + + struct Unit {}; + template class Singleton { public: Singleton(const Singleton&) = delete; @@ -81,10 +82,11 @@ namespace DE { Singleton& operator=(Singleton&&) = delete; protected: - static T& Get(); + static T& GetInstance(); Singleton() = default; virtual ~Singleton() = default; - static T* s_Instance; + static T* gInstance; }; -} // namespace DE + +} // namespace DummyEngine diff --git a/DummyEngine/Utils/Helpers/StringOperations.cpp b/DummyEngine/Utils/Helpers/StringOperations.cpp index 18ced2e..a007404 100644 --- a/DummyEngine/Utils/Helpers/StringOperations.cpp +++ b/DummyEngine/Utils/Helpers/StringOperations.cpp @@ -1,9 +1,8 @@ -#include "DummyEngine/Utils/Helpers/StringOperations.h" +#include "StringOperations.h" -#include "DummyEngine/Utils/Base/STDIncludes.h" -#include "DummyEngine/Utils/Types/UUID.h" +#include -namespace DE { +namespace DummyEngine { U32 HexCharToInt(char a) { if (a >= 'a') { @@ -27,4 +26,4 @@ namespace DE { res << std::setfill('0') << std::setw(16) << std::hex << a; return res.str(); } -} // namespace DE +} // namespace DummyEngine diff --git a/DummyEngine/Utils/Helpers/StringOperations.h b/DummyEngine/Utils/Helpers/StringOperations.h index 6875ec6..0fbf78b 100644 --- a/DummyEngine/Utils/Helpers/StringOperations.h +++ b/DummyEngine/Utils/Helpers/StringOperations.h @@ -1,11 +1,13 @@ #pragma once -#include "DummyEngine/Utils/Base/STDIncludes.h" + #include "DummyEngine/Utils/Types/Types.h" -namespace DE { +#include + +namespace DummyEngine { U32 HexCharToInt(char a); U64 StrToHex(std::string_view string); std::string HexToStr(U64 a); -} // namespace DE +} // namespace DummyEngine diff --git a/DummyEngine/Utils/Helpers/Timer.cpp b/DummyEngine/Utils/Helpers/Timer.cpp index 2017d3f..d4477ce 100644 --- a/DummyEngine/Utils/Helpers/Timer.cpp +++ b/DummyEngine/Utils/Helpers/Timer.cpp @@ -1,19 +1,21 @@ -#include "DummyEngine/Utils/Helpers/Timer.h" +#include "Timer.h" + +namespace DummyEngine { -namespace DE { Timer::Timer() { - m_StartTime = std::chrono::system_clock::now(); + start_time_ = std::chrono::system_clock::now(); } float Timer::Time() const { - return (std::chrono::system_clock::now() - m_StartTime).count(); + return (std::chrono::system_clock::now() - start_time_).count(); } float Timer::TimeM() const { - return (std::chrono::system_clock::now() - m_StartTime).count() * 1000; + return (std::chrono::system_clock::now() - start_time_).count() * 1000; } float Timer::Reset() { - float res = (std::chrono::system_clock::now() - m_StartTime).count(); - m_StartTime = std::chrono::system_clock::now(); + float res = (std::chrono::system_clock::now() - start_time_).count(); + start_time_ = std::chrono::system_clock::now(); return res; } -} // namespace DE \ No newline at end of file + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Utils/Helpers/Timer.h b/DummyEngine/Utils/Helpers/Timer.h index c6f4401..dfff5d9 100644 --- a/DummyEngine/Utils/Helpers/Timer.h +++ b/DummyEngine/Utils/Helpers/Timer.h @@ -1,8 +1,9 @@ #pragma once -#include "DummyEngine/Utils/Base/STDIncludes.h" +#include + +namespace DummyEngine { -namespace DE { class Timer { public: Timer(); @@ -12,6 +13,7 @@ namespace DE { float Reset(); private: - std::chrono::system_clock::time_point m_StartTime; + std::chrono::system_clock::time_point start_time_; }; -} // namespace DE \ No newline at end of file + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Utils/PCH/GLMIncludes.h b/DummyEngine/Utils/PCH/GLMIncludes.h new file mode 100644 index 0000000..0e9d919 --- /dev/null +++ b/DummyEngine/Utils/PCH/GLMIncludes.h @@ -0,0 +1,9 @@ +#pragma once + +#include // IWYU pragma: export +#include // IWYU pragma: export +#include // IWYU pragma: export +#include // IWYU pragma: export +#include // IWYU pragma: export +#include // IWYU pragma: export +#include // IWYU pragma: export diff --git a/DummyEngine/Utils/PCH/PCH.h b/DummyEngine/Utils/PCH/PCH.h new file mode 100644 index 0000000..e89cab3 --- /dev/null +++ b/DummyEngine/Utils/PCH/PCH.h @@ -0,0 +1,22 @@ +#pragma once + +#include "DummyEngine/Utils/PCH/GLMIncludes.h" // IWYU pragma: export +#include "DummyEngine/Utils/PCH/STDIncludes.h" // IWYU pragma: export + +#include "DummyEngine/Utils/Debug/Assert.h" // IWYU pragma: export +#include "DummyEngine/Utils/Debug/Demangler.h" // IWYU pragma: export +#include "DummyEngine/Utils/Debug/Logger.h" // IWYU pragma: export +#include "DummyEngine/Utils/Debug/Profiler.h" // IWYU pragma: export +#include "DummyEngine/Utils/Debug/StackTrace.h" // IWYU pragma: export + +#include "DummyEngine/Utils/Helpers/CompilerSpecific.h" // IWYU pragma: export +#include "DummyEngine/Utils/Helpers/Conversions.h" // IWYU pragma: export +#include "DummyEngine/Utils/Helpers/Random.h" // IWYU pragma: export +#include "DummyEngine/Utils/Helpers/STDAdapters.h" // IWYU pragma: export +#include "DummyEngine/Utils/Helpers/Singleton.h" // IWYU pragma: export +#include "DummyEngine/Utils/Helpers/StringOperations.h" // IWYU pragma: export +#include "DummyEngine/Utils/Helpers/Timer.h" // IWYU pragma: export + +#include "DummyEngine/Utils/Types/Constants.h" // IWYU pragma: export +#include "DummyEngine/Utils/Types/Types.h" // IWYU pragma: export +#include "DummyEngine/Utils/Types/UUID.h" // IWYU pragma: export diff --git a/DummyEngine/Utils/PCH/STDIncludes.h b/DummyEngine/Utils/PCH/STDIncludes.h new file mode 100644 index 0000000..4069990 --- /dev/null +++ b/DummyEngine/Utils/PCH/STDIncludes.h @@ -0,0 +1,29 @@ +#pragma once + +#include // IWYU pragma: export +#include // IWYU pragma: export +#include // IWYU pragma: export +#include // IWYU pragma: export +#include // IWYU pragma: export +#include // IWYU pragma: export +#include // IWYU pragma: export +#include // IWYU pragma: export +#include // IWYU pragma: export +#include // IWYU pragma: export +#include // IWYU pragma: export +#include // IWYU pragma: export +#include // IWYU pragma: export +#include // IWYU pragma: export +#include // IWYU pragma: export +#include // IWYU pragma: export +#include // IWYU pragma: export +#include // IWYU pragma: export +#include // IWYU pragma: export +#include // IWYU pragma: export +#include // IWYU pragma: export +#include // IWYU pragma: export +#include // IWYU pragma: export +#include // IWYU pragma: export +#include // IWYU pragma: export +#include // IWYU pragma: export +#include // IWYU pragma: export diff --git a/DummyEngine/Utils/ScriptIncludes.h b/DummyEngine/Utils/ScriptIncludes.h deleted file mode 100644 index 215e416..0000000 --- a/DummyEngine/Utils/ScriptIncludes.h +++ /dev/null @@ -1,12 +0,0 @@ -#pragma once - -#include "DummyEngine/Core/Application/Config.h" -#include "DummyEngine/Core/Application/Input.h" -#include "DummyEngine/Core/ECS/ECS.h" -#include "DummyEngine/Core/Objects/Cameras/FPSCamera.h" -#include "DummyEngine/Core/Objects/LightSources/LightSource.h" -#include "DummyEngine/Core/Rendering/Renderer/Renderer.h" -#include "DummyEngine/Core/Scene/Components.h" -#include "DummyEngine/Core/Scene/Scene.h" -#include "DummyEngine/Core/Scripting/Script.h" -#include "DummyEngine/Utils/Base.h" diff --git a/DummyEngine/Utils/Types/Constants.h b/DummyEngine/Utils/Types/Constants.h new file mode 100644 index 0000000..80d2cd7 --- /dev/null +++ b/DummyEngine/Utils/Types/Constants.h @@ -0,0 +1,10 @@ +#pragma once + +namespace DummyEngine { + namespace Constants { + constexpr float kDefaultCameraFOV = 90.0f; + constexpr float kDefaultCameraAspect = 16.0f / 9.0f; + constexpr float kDefaultCameraNearPlane = 0.1f; + constexpr float kDefaultCameraFarPlane = 2'000'000.0f; + } // namespace Constants +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Utils/Types/STDAdapters.h b/DummyEngine/Utils/Types/STDAdapters.h deleted file mode 100644 index 7e8e29b..0000000 --- a/DummyEngine/Utils/Types/STDAdapters.h +++ /dev/null @@ -1,25 +0,0 @@ -#pragma once - -#include "DummyEngine/Utils/Types/Types.h" -#include "DummyEngine/Utils/Types/UUID.h" - -namespace std { - template <> struct formatter : formatter { - auto format(const DE::Vec3& vec, format_context& ctx) const { - return formatter::format(std::format("({}, {}, {})", vec.x, vec.y, vec.z), ctx); - } - }; - template <> struct formatter : formatter { - auto format(const DE::Vec4& vec, format_context& ctx) const { - return formatter::format(std::format("({}, {}, {}, {})", vec.x, vec.y, vec.z, vec.w), ctx); - } - }; - - template <> struct formatter : formatter { - auto format(const DE::Path& path, format_context& ctx) const { return formatter::format(path.string(), ctx); } - }; - - template <> struct formatter : formatter { - auto format(const DE::UUID& uuid, format_context& ctx) const { return formatter::format(uuid.Hex(), ctx); } - }; -} // namespace std \ No newline at end of file diff --git a/DummyEngine/Utils/Types/Types.cpp b/DummyEngine/Utils/Types/Types.cpp index f2483d6..8057864 100644 --- a/DummyEngine/Utils/Types/Types.cpp +++ b/DummyEngine/Utils/Types/Types.cpp @@ -1,15 +1,15 @@ -#include "DummyEngine/Utils/Types/Types.h" +#include "Types.h" -#include "DummyEngine/Utils/Debug/Logger.h" +namespace DummyEngine { -namespace DE { void Vertex3D::AddBone(S32 id, float weight) { for (size_t i = 0; i < MAX_BONE_INFLUENCE; ++i) { - if (bones[i] == -1) { - bones[i] = id; - weights[i] = weight; + if (Bones[i] == -1) { + Bones[i] = id; + Weights[i] = weight; return; } } } -} // namespace DE + +} // namespace DummyEngine diff --git a/DummyEngine/Utils/Types/Types.h b/DummyEngine/Utils/Types/Types.h index 300124f..97dedc4 100644 --- a/DummyEngine/Utils/Types/Types.h +++ b/DummyEngine/Utils/Types/Types.h @@ -1,7 +1,10 @@ #pragma once -#include "DummyEngine/Utils/Base/GLMIncludes.h" -#include "DummyEngine/Utils/Base/STDIncludes.h" +#include +#include + +#include +#include #define MAX_BONE_INFLUENCE 8 #define MAX_BONES 128 @@ -15,7 +18,7 @@ using S16 = int16_t; using S32 = int32_t; using S64 = int64_t; -namespace DE { +namespace DummyEngine { namespace fs = std::filesystem; using VoidFPtr = void (*)(); @@ -39,12 +42,12 @@ namespace DE { enum class BufferUsage { None = 0, Static, Dynamic }; struct Vertex3D { - Vec3 position = Vec3(0); - Vec3 normal = Vec3(0); - Vec3 tangent = Vec3(0); - Vec2 tex_coords = Vec2(0); - S32 bones[MAX_BONE_INFLUENCE] = {-1, -1, -1, -1, -1, -1, -1, -1}; - float weights[MAX_BONE_INFLUENCE] = {0, 0, 0, 0, 0, 0, 0, 0}; + Vec3 Position = Vec3(0); + Vec3 Normal = Vec3(0); + Vec3 Tangent = Vec3(0); + Vec2 TexCoords = Vec2(0); + S32 Bones[MAX_BONE_INFLUENCE] = {-1, -1, -1, -1, -1, -1, -1, -1}; + float Weights[MAX_BONE_INFLUENCE] = {0, 0, 0, 0, 0, 0, 0, 0}; void AddBone(S32 id, float weight); }; @@ -68,4 +71,4 @@ namespace DE { return h1 ^ h2; } }; -} // namespace DE +} // namespace DummyEngine diff --git a/DummyEngine/Utils/Types/UUID.cpp b/DummyEngine/Utils/Types/UUID.cpp index 52c80ac..2dee695 100644 --- a/DummyEngine/Utils/Types/UUID.cpp +++ b/DummyEngine/Utils/Types/UUID.cpp @@ -1,12 +1,14 @@ -#include "DummyEngine/Utils/Types/UUID.h" +#include "UUID.h" #include "DummyEngine/Utils/Debug/Assert.h" #include "DummyEngine/Utils/Helpers/StringOperations.h" -namespace DE { - static std::random_device s_RandomDevice; - static std::mt19937_64 s_Engine(s_RandomDevice()); - static std::uniform_int_distribution s_UniformDistribution; +#include + +namespace DummyEngine { + static thread_local std::random_device gRandomDevice; + static thread_local std::mt19937_64 gEngine(gRandomDevice()); + static thread_local std::uniform_int_distribution gUniformDistribution; UUID::UUID(const std::string& str) { DE_ASSERT(str.size() == 32, "Wrong str size {}", str.size()); @@ -14,33 +16,33 @@ namespace DE { std::string_view second(str); first.remove_suffix(16); second.remove_prefix(16); - m_First = StrToHex(first); - m_Second = StrToHex(second); + first_ = StrToHex(first); + second_ = StrToHex(second); } UUID::operator std::string() const { - return std::format("{:032x}{:032x}", m_First, m_Second); + return std::format("{:032x}{:032x}", first_, second_); } std::string UUID::Hex() const { - return std::format("{:032x}{:032x}", m_First, m_Second); + return std::format("{:032x}{:032x}", first_, second_); } bool UUID::operator==(const UUID& other) const { - return m_First == other.m_First && m_Second == other.m_Second; + return first_ == other.first_ && second_ == other.second_; } bool UUID::operator!=(const UUID& other) const { - return m_First != other.m_First || m_Second != other.m_Second; + return first_ != other.first_ || second_ != other.second_; } bool UUID::operator<(const UUID& other) const { - return (m_First == other.m_First ? m_Second < other.m_Second : m_First < other.m_First); + return (first_ == other.first_ ? second_ < other.second_ : first_ < other.first_); } bool UUID::operator>(const UUID& other) const { - return (m_First == other.m_First ? m_Second > other.m_Second : m_First > other.m_First); + return (first_ == other.first_ ? second_ > other.second_ : first_ > other.first_); } UUID UUID::Generate() { UUID res; - res.m_First = s_UniformDistribution(s_Engine); - res.m_Second = s_UniformDistribution(s_Engine); + res.first_ = gUniformDistribution(gEngine); + res.second_ = gUniformDistribution(gEngine); return res; } -} // namespace DE +} // namespace DummyEngine diff --git a/DummyEngine/Utils/Types/UUID.h b/DummyEngine/Utils/Types/UUID.h index 9c271fc..936945e 100644 --- a/DummyEngine/Utils/Types/UUID.h +++ b/DummyEngine/Utils/Types/UUID.h @@ -1,17 +1,17 @@ #pragma once -#include "DummyEngine/Utils/Base/STDIncludes.h" #include "DummyEngine/Utils/Types/Types.h" -namespace DE { +#include + +namespace DummyEngine { class UUID { public: static UUID Generate(); - UUID() = default; - UUID(const std::string& str); - - operator std::string() const; + UUID() = default; + UUID(const std::string& str); // NOLINT + operator std::string() const; // NOLINT bool operator==(const UUID& other) const; bool operator!=(const UUID& other) const; @@ -23,15 +23,15 @@ namespace DE { private: template friend struct std::hash; - U64 m_First = 0; - U64 m_Second = 0; + U64 first_ = 0; + U64 second_ = 0; }; -} // namespace DE +} // namespace DummyEngine namespace std { - template <> struct hash { - std::size_t operator()(const DE::UUID& uuid) const { return uuid.m_First ^ uuid.m_Second; } + template <> struct hash { + std::size_t operator()(const DummyEngine::UUID& uuid) const { return uuid.first_ ^ uuid.second_; } }; } // namespace std \ No newline at end of file diff --git a/Examples/EmptyApplication.cpp b/Examples/EmptyApplication.cpp index 7a615c4..8f66eb0 100644 --- a/Examples/EmptyApplication.cpp +++ b/Examples/EmptyApplication.cpp @@ -1,13 +1,13 @@ #include "DummyEngine/Core/Application/EntryPoint.h" #include "DummyEngine/DummyEngine.h" -class MyLayer : public DE::Layer { +class MyLayer : public DummyEngine::Layer { public: - MyLayer() : DE::Layer("MyLayer") {} + MyLayer() : DummyEngine::Layer("MyLayer") {} }; -namespace DE { +namespace DummyEngine { void SetupApplication() { Application::PushLayer(new MyLayer()); } -} // namespace DE +} // namespace DummyEngine diff --git a/Examples/Test.cpp b/Examples/Test.cpp index 5a155c2..d6e965e 100644 --- a/Examples/Test.cpp +++ b/Examples/Test.cpp @@ -1,6 +1,6 @@ #include "DummyEngine/DummyEngine.h" -using namespace DE; +using namespace DummyEngine; int main() { freopen("output.txt", "w", stdout); diff --git a/Sandbox/Assets/Scripts/BasicScripts/SquareMovement.cpp b/Sandbox/Assets/Scripts/BasicScripts/SquareMovement.cpp index 23ccc5b..a688edc 100644 --- a/Sandbox/Assets/Scripts/BasicScripts/SquareMovement.cpp +++ b/Sandbox/Assets/Scripts/BasicScripts/SquareMovement.cpp @@ -1,34 +1,34 @@ -#include "DummyEngine/Utils/ScriptIncludes.h" +#include "DummyEngine/DummyEngine.h" -using namespace DE; +using namespace DummyEngine; class SquareMovement : public Script { SCRIPT(SquareMovement) public: virtual void OnUpdate(float dt) override { - current_time += dt; - float persent = ((current_time + offset) - cycle_time * (int)((current_time + offset) / cycle_time)) / cycle_time; - auto& position = Get().translation; + current_time_ += dt; + float persent = ((current_time_ + offset_) - cycle_time_ * (int)((current_time_ + offset_) / cycle_time_)) / cycle_time_; + auto& position = Get().Translation; if (persent <= 0.25f) { - position = Vec3(left_back.x, height, left_back.y) + Smouth(4.0f * (persent - 0.0f)) * Vec3(right_front.x - left_back.x, 0, 0); + position = Vec3(left_back_.x, height_, left_back_.y) + Smouth(4.0f * (persent - 0.0f)) * Vec3(right_front_.x - left_back_.x, 0, 0); } else if (persent <= 0.5f) { - position = Vec3(right_front.x, height, left_back.y) + Smouth(4.0f * (persent - 0.25f)) * Vec3(0, 0, right_front.y - left_back.y); + position = Vec3(right_front_.x, height_, left_back_.y) + Smouth(4.0f * (persent - 0.25f)) * Vec3(0, 0, right_front_.y - left_back_.y); } else if (persent <= 0.75f) { - position = Vec3(right_front.x, height, right_front.y) + Smouth(4.0f * (persent - 0.5f)) * Vec3(left_back.x - right_front.x, 0, 0); + position = Vec3(right_front_.x, height_, right_front_.y) + Smouth(4.0f * (persent - 0.5f)) * Vec3(left_back_.x - right_front_.x, 0, 0); } else if (persent <= 1.0f) { - position = Vec3(left_back.x, height, right_front.y) + Smouth(4.0f * (persent - 0.75f)) * Vec3(0, 0, left_back.y - right_front.y); + position = Vec3(left_back_.x, height_, right_front_.y) + Smouth(4.0f * (persent - 0.75f)) * Vec3(0, 0, left_back_.y - right_front_.y); } } private: float Smouth(float delta) const { return (std::sin((delta * 2 - 1) * 3.1415926 / 2) + 1) / 2; } - float cycle_time = 1; - float current_time = 0; - float height = 10; - float offset = 0; - Vec2 left_back = {10, 10}; - Vec2 right_front = {0.0, 0.0}; + float cycle_time_ = 1; + float current_time_ = 0; + float height_ = 10; + float offset_ = 0; + Vec2 left_back_ = {10, 10}; + Vec2 right_front_ = {0.0, 0.0}; }; -SCRIPT_BASE(SquareMovement, FIELD(cycle_time), FIELD(height), FIELD(offset), FIELD(left_back), FIELD(right_front)) +SCRIPT_BASE(SquareMovement, FIELD(cycle_time_), FIELD(height_), FIELD(offset_), FIELD(left_back_), FIELD(right_front_)) diff --git a/Sandbox/Assets/Scripts/Gate/GateController.cpp b/Sandbox/Assets/Scripts/Gate/GateController.cpp index cc5b4ae..755d81b 100644 --- a/Sandbox/Assets/Scripts/Gate/GateController.cpp +++ b/Sandbox/Assets/Scripts/Gate/GateController.cpp @@ -1,19 +1,19 @@ -#include "DummyEngine/Utils/ScriptIncludes.h" +#include "DummyEngine/DummyEngine.h" -using namespace DE; +using namespace DummyEngine; class GateController : public Script { SCRIPT(GateController) public: - virtual void OnUpdate(float dt) override { + virtual void OnUpdate(float) override { DE_PROFILE_SCOPE("GateContoller"); - m_Open = false; - if (Controller.Valid()) { - if (Controller.Has()) { - const auto& controller_pos = Controller.Get().translation; - const auto& my_pos = Get().translation; + open_ = false; + if (controller_.Valid()) { + if (controller_.Has()) { + const auto& controller_pos = controller_.Get().Translation; + const auto& my_pos = Get().Translation; float dist = glm::length(Vec2(my_pos.x - controller_pos.x, my_pos.z - controller_pos.z)); - m_Open = (dist < Distance); + open_ = (dist < distance_); } } Move(); @@ -21,31 +21,31 @@ class GateController : public Script { private: void Move() { - if (m_Open) { - if (current_height + Speed < OpenHeight) { - current_height += Speed; + if (open_) { + if (current_height_ + speed_ < open_height_) { + current_height_ += speed_; } else { - current_height = OpenHeight; + current_height_ = open_height_; } } else { - if (current_height - Speed > CloseHeight) { - current_height -= Speed; + if (current_height_ - speed_ > close_height_) { + current_height_ -= speed_; } else { - current_height = CloseHeight; + current_height_ = close_height_; } } auto& my_pos = Get(); - my_pos.translation.y = current_height; - my_pos.scale.y = (OpenHeight - current_height) / (OpenHeight - CloseHeight) * 3 + 1; + my_pos.Translation.y = current_height_; + my_pos.Scale.y = (open_height_ - current_height_) / (open_height_ - close_height_) * 3 + 1; } - bool m_Open = false; - float Speed = 1.0; - float Distance = 1.0; - float current_height = 0.0; - float OpenHeight = 0; - float CloseHeight = 0; - Entity Controller; + bool open_ = false; + float speed_ = 1.0; + float distance_ = 1.0; + float current_height_ = 0.0; + float open_height_ = 0; + float close_height_ = 0; + Entity controller_; }; -SCRIPT_BASE(GateController, FIELD(Speed), FIELD(Distance), FIELD(OpenHeight), FIELD(CloseHeight), FIELD(Controller)) +SCRIPT_BASE(GateController, FIELD(speed_), FIELD(distance_), FIELD(open_height_), FIELD(close_height_), FIELD(controller_)) diff --git a/Sandbox/Assets/Scripts/Gate/SinMovement.cpp b/Sandbox/Assets/Scripts/Gate/SinMovement.cpp index f20324a..b02108c 100644 --- a/Sandbox/Assets/Scripts/Gate/SinMovement.cpp +++ b/Sandbox/Assets/Scripts/Gate/SinMovement.cpp @@ -1,24 +1,24 @@ -#include "DummyEngine/Utils/ScriptIncludes.h" +#include "DummyEngine/DummyEngine.h" -using namespace DE; +using namespace DummyEngine; class SinMovement : public Script { SCRIPT(SinMovement) public: virtual void OnUpdate(float dt) override { DE_PROFILE_SCOPE("SinMovement"); - current_time += dt * Speed; - auto& pos = Get().translation; - float d = (sin(current_time) + 1) / 2; - pos = d * PosA + (1 - d) * PosB; + current_time_ += dt * speed_; + auto& pos = Get().Translation; + float d = (sin(current_time_) + 1) / 2; + pos = d * pos_a_ + (1 - d) * pos_b_; // pos = d * PosA + (1 - d) * PosB + Vec3(0, 20, 0)* float(cos(current_time)) ; } private: - Vec3 PosA = Vec3(0, 0, 0); - Vec3 PosB = Vec3(0, 0, 0); - float Speed = 1; - float current_time = 0; + Vec3 pos_a_ = Vec3(0, 0, 0); + Vec3 pos_b_ = Vec3(0, 0, 0); + float speed_ = 1; + float current_time_ = 0; }; -SCRIPT_BASE(SinMovement, FIELD(PosA), FIELD(PosB), FIELD(Speed)) +SCRIPT_BASE(SinMovement, FIELD(pos_a_), FIELD(pos_b_), FIELD(speed_)) diff --git a/Sandbox/Assets/Scripts/Grass/Grass.cpp b/Sandbox/Assets/Scripts/Grass/Grass.cpp index 62612c2..7b2eb77 100644 --- a/Sandbox/Assets/Scripts/Grass/Grass.cpp +++ b/Sandbox/Assets/Scripts/Grass/Grass.cpp @@ -1,6 +1,6 @@ -#include "DummyEngine/Utils/ScriptIncludes.h" +#include "DummyEngine/DummyEngine.h" -using namespace DE; +using namespace DummyEngine; class Grass : public Script { SCRIPT(Grass) @@ -19,38 +19,38 @@ class Grass : public Script { data[3 * i + 2] = glm::rotate(Vec3(1.0, 0, 0), Random::Float(0, 3.1415926 * 2), Vec3(0, 1, 0)); } - grass = VertexArray::Create(); + grass_ = VertexArray::Create(); auto bf = VertexBuffer::Create({BufferElementType::Float3, BufferElementType::Float3, BufferElementType::Float3}, y_amount * x_amount, &data[0]); - grass->AddVertexBuffer(bf); + grass_->AddVertexBuffer(bf); - auto shaders = Config::GetPath(DE_CFG_SHADER_PATH); + auto shaders = Config::Get().ShaderPath; std::vector parts = { { ShaderPartType::Vertex, shaders / "Grass/Grass.vs"}, {ShaderPartType::Geometry, shaders / "Grass/Grass.gs"}, {ShaderPartType::Fragment, shaders / "Grass/Grass.fs"} }; - shader = Shader::Create(parts); + shader_ = Shader::Create(parts); } - virtual void OnUpdate(float dt) override { time += dt * Speed; } + virtual void OnUpdate(float dt) override { time_ += dt * speed_; } virtual void OnRender() override { - shader->Bind(); - shader->SetFloat("u_Time", time); - if (Camera.Has()) { - auto& cam = Camera.Get(); - shader->SetMat4("u_Camera.view", cam.GetViewMatrix()); - shader->SetMat4("u_Camera.projection", cam.GetProjectionMatrix()); + shader_->Bind(); + shader_->SetFloat("u_Time", time_); + if (camera_.Has()) { + auto& cam = camera_.Get(); + shader_->SetMat4("u_Camera.view", cam.GetViewMatrix()); + shader_->SetMat4("u_Camera.projection", cam.GetProjectionMatrix()); } - Renderer::GetRenderAPI().DrawArrays(grass, RenderPrimitive::Point); + Renderer::GetRenderAPI().DrawArrays(grass_, RenderPrimitive::Point); } private: - float time; - float Speed; - Entity Camera; - Ref grass; - Ref shader; + float time_; + float speed_; + Entity camera_; + Ref grass_; + Ref shader_; }; -SCRIPT_BASE(Grass, FIELD(Camera), FIELD(Speed)) +SCRIPT_BASE(Grass, FIELD(camera_), FIELD(speed_)) diff --git a/Sandbox/Assets/Scripts/Sky/SkyController.cpp b/Sandbox/Assets/Scripts/Sky/SkyController.cpp index 40295b1..45d3ff1 100644 --- a/Sandbox/Assets/Scripts/Sky/SkyController.cpp +++ b/Sandbox/Assets/Scripts/Sky/SkyController.cpp @@ -1,21 +1,21 @@ -#include "DummyEngine/Utils/ScriptIncludes.h" +#include "DummyEngine/DummyEngine.h" -using namespace DE; +using namespace DummyEngine; class SkyContoller : public Script { SCRIPT(SkyContoller) public: virtual void OnRuntimeStop() override { - auto& pos = Get().rotation; + auto& pos = Get().Rotation; pos = {0.0, 0.0, 0.0}; } virtual void OnUpdate(float dt) override { DE_PROFILE_SCOPE("SkyController"); - current_time += dt; - auto& pos = Get().rotation; - pos.x += dt * RotationSpeed.x; - pos.y += dt * RotationSpeed.y; - pos.z += dt * RotationSpeed.z; + current_time_ += dt; + auto& pos = Get().Rotation; + pos.x += dt * rotation_speed_.x; + pos.y += dt * rotation_speed_.y; + pos.z += dt * rotation_speed_.z; ClampRoundValue(pos, 0, 360); } @@ -28,8 +28,8 @@ class SkyContoller : public Script { if (vec.z < min) vec.z = max; if (vec.z > max) vec.z = min; } - Vec3 RotationSpeed = {0.1, 0.1, 0.1}; - float current_time = 0; + Vec3 rotation_speed_ = {0.1, 0.1, 0.1}; + float current_time_ = 0; }; -SCRIPT_BASE(SkyContoller, FIELD(RotationSpeed)) +SCRIPT_BASE(SkyContoller, FIELD(rotation_speed_)) diff --git a/Sandbox/Assets/Scripts/SphereSpawner.cpp b/Sandbox/Assets/Scripts/SphereSpawner.cpp deleted file mode 100644 index 2f6f2f0..0000000 --- a/Sandbox/Assets/Scripts/SphereSpawner.cpp +++ /dev/null @@ -1,17 +0,0 @@ -#include "DummyEngine/Utils/ScriptIncludes.h" - -using namespace DE; - -class SphereSpawner : public Script { - SCRIPT(SphereSpawner) -public: - virtual void OnRuntimeStart(float dt) override {} - virtual void OnRuntimeEnd(float dt) override {} - -private: - U32 Width; - U32 Height; - std::vector spheres; -}; - -SCRIPT_BASE(GateController, FIELD(Width), FIELD(Height)) From 6e635cfc0dfbf63ea672ee50807bcc906c5f0e5c Mon Sep 17 00:00:00 2001 From: Mag1str0 Date: Fri, 22 Nov 2024 02:41:15 +0300 Subject: [PATCH 08/15] Fixed linux build --- .github/workflows/main.yml | 2 +- .../Platform/Linux/Scripting/Compiler.cpp | 26 ++++----- .../Linux/Core/Scripting/SharedObject.cpp | 54 +++++++++---------- .../Platform/Linux/Utils/Debug/Demangler.cpp | 2 +- 4 files changed, 43 insertions(+), 41 deletions(-) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 12d99ae..2390286 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -107,7 +107,7 @@ jobs: files-changed-only: false database: '${{ github.workspace }}/build' repo-root: '${{ github.workspace }}' - ignore: 'build/**|Examples/**|Sandbox/**' + ignore: 'build/**|Examples/**|Sandbox/**|DummyEngine/Core/ECS**' step-summary: true - name: Check Linter Results if: steps.linter.outputs.checks-failed > 0 diff --git a/DummyEditor/Platform/Linux/Scripting/Compiler.cpp b/DummyEditor/Platform/Linux/Scripting/Compiler.cpp index 3bda5fd..4937829 100644 --- a/DummyEditor/Platform/Linux/Scripting/Compiler.cpp +++ b/DummyEditor/Platform/Linux/Scripting/Compiler.cpp @@ -1,5 +1,7 @@ #include "DummyEditor/Scripting/Compiler.h" +#include "DummyEngine/Core/Application/FileSystem.h" + namespace DummyEngine { class LinuxCompilerImpl : public CompilerImpl { LOG_AUTHOR(Compiler) @@ -53,12 +55,12 @@ namespace DummyEngine { int res = system(link_command.c_str()); return res == 0; } - virtual void AddIncludeDir(const Path& dir) { m_IncludeDirs.insert(dir); } - virtual void DeleteIncludeDir(const Path& dir) { m_IncludeDirs.erase(dir); } - virtual void AddLinkLibrary(const Path& library) { m_Libraries.insert(library); } - virtual void DeleteLinkLibrary(const Path& library) { m_Libraries.erase(library); } - virtual void AddDefine(const std::string& define) { m_Defines.insert(define); } - virtual void DeleteDefine(const std::string& define) { m_Defines.erase(define); } + virtual void AddIncludeDir(const Path& dir) { include_dirs_.insert(dir); } + virtual void DeleteIncludeDir(const Path& dir) { include_dirs_.erase(dir); } + virtual void AddLinkLibrary(const Path& library) { libraries_.insert(library); } + virtual void DeleteLinkLibrary(const Path& library) { libraries_.erase(library); } + virtual void AddDefine(const std::string& define) { defines_.insert(define); } + virtual void DeleteDefine(const std::string& define) { defines_.erase(define); } private: std::string GetCompiler() { @@ -69,7 +71,7 @@ namespace DummyEngine { std::string AddIncludeDirArguments() { std::string res; - for (const auto& dir : m_IncludeDirs) { + for (const auto& dir : include_dirs_) { res.append(" -I "); res.append(dir.string()); } @@ -88,7 +90,7 @@ namespace DummyEngine { } std::string AddLinkArgs() { std::string res; - for (auto lib : m_Libraries) { + for (auto lib : libraries_) { std::string name = lib.stem().string(); lib.remove_filename(); if (lib.empty()) { @@ -103,7 +105,7 @@ namespace DummyEngine { } std::string AddDefines() { std::string res; - for (const auto& def : m_Defines) { + for (const auto& def : defines_) { res.append(" -D"); res.append(def); } @@ -113,9 +115,9 @@ namespace DummyEngine { return " -o " + destination.string() + "/" + library_name + ".so"; } - std::unordered_set m_IncludeDirs; - std::unordered_set m_Libraries; - std::unordered_set m_Defines; + std::unordered_set include_dirs_; + std::unordered_set libraries_; + std::unordered_set defines_; }; Scope Compiler::CreateCompilerImpl() { diff --git a/DummyEngine/Platform/Linux/Core/Scripting/SharedObject.cpp b/DummyEngine/Platform/Linux/Core/Scripting/SharedObject.cpp index 84ef441..8e6516b 100644 --- a/DummyEngine/Platform/Linux/Core/Scripting/SharedObject.cpp +++ b/DummyEngine/Platform/Linux/Core/Scripting/SharedObject.cpp @@ -11,8 +11,8 @@ namespace DummyEngine { public: SharedObjectImpl() {} ~SharedObjectImpl() { - if (m_Handle) { - dlclose(m_Handle); + if (handle_ != nullptr) { + dlclose(handle_); } } @@ -22,7 +22,7 @@ namespace DummyEngine { SharedObjectImpl& operator=(SharedObjectImpl&&) = delete; bool Load(const Path& directory, const std::string& name) { - if (m_Handle && m_Valid) { + if (handle_ != nullptr && valid_) { LOG_WARNING("Library {} already loaded", name); return false; } @@ -32,62 +32,62 @@ namespace DummyEngine { return false; } void* new_handle = dlopen(path_to_dll.string().c_str(), RTLD_LAZY); - if (!new_handle) { + if (new_handle == nullptr) { LOG_WARNING("Failed to load library {}", path_to_dll); return false; } - if (m_Handle) { - dlclose(m_Handle); + if (handle_ != nullptr) { + dlclose(handle_); } - m_Handle = new_handle; - m_Directory = directory; - m_Name = name; - m_Valid = true; + handle_ = new_handle; + directory_ = directory; + name_ = name; + valid_ = true; LOG_INFO("Loaded library {}", Config::RelativeToExecutable(directory / (name + ".dll"))); return true; } - void Invalidate() { m_Valid = false; } + void Invalidate() { valid_ = false; } - bool Valid() const { return m_Valid && m_Handle; } + bool Valid() const { return valid_ && handle_ != nullptr; } VoidFPtr GetFunction(const std::string& function_name) const { - if (!m_Handle) { + if (handle_ == nullptr) { return nullptr; } - return (VoidFPtr)dlsym(m_Handle, function_name.c_str()); + return (VoidFPtr)dlsym(handle_, function_name.c_str()); } - const Path& GetDirectory() const { return m_Directory; } - const std::string& GetName() const { return m_Name; } + const Path& GetDirectory() const { return directory_; } + const std::string& GetName() const { return name_; } private: - Path m_Directory; - std::string m_Name; - void* m_Handle = nullptr; - bool m_Valid = false; + Path directory_; + std::string name_; + void* handle_ = nullptr; + bool valid_ = false; }; SharedObject::SharedObject() { - m_Impl = CreateScope(); + impl_ = CreateScope(); } SharedObject::~SharedObject() {} bool SharedObject::Load(const Path& directory, const std::string& name) { - return m_Impl->Load(directory, name); + return impl_->Load(directory, name); } void SharedObject::Invalidate() { - m_Impl->Invalidate(); + impl_->Invalidate(); } bool SharedObject::Valid() const { - return m_Impl->Valid(); + return impl_->Valid(); } VoidFPtr SharedObject::GetFunction(const std::string& function_name) const { - return m_Impl->GetFunction(function_name); + return impl_->GetFunction(function_name); } const Path& SharedObject::GetDirectory() const { - return m_Impl->GetDirectory(); + return impl_->GetDirectory(); } const std::string& SharedObject::GetName() const { - return m_Impl->GetName(); + return impl_->GetName(); } } // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Platform/Linux/Utils/Debug/Demangler.cpp b/DummyEngine/Platform/Linux/Utils/Debug/Demangler.cpp index e91aa8a..136e548 100644 --- a/DummyEngine/Platform/Linux/Utils/Debug/Demangler.cpp +++ b/DummyEngine/Platform/Linux/Utils/Debug/Demangler.cpp @@ -7,7 +7,7 @@ namespace DummyEngine { int status; char* realname; - realname = abi::__cxa_demangle(name.c_str(), 0, 0, &status); + realname = abi::__cxa_demangle(name.c_str(), nullptr, nullptr, &status); res = realname; free(realname); return res; From e8e751a68c28f4274359cca9778b1b7182e83317 Mon Sep 17 00:00:00 2001 From: Mag1str0 Date: Fri, 22 Nov 2024 02:56:28 +0300 Subject: [PATCH 09/15] Fix more clang tidy errors --- .github/workflows/main.yml | 6 +-- CMake/Compiler.cmake | 4 +- .../Platform/Linux/Scripting/Compiler.cpp | 4 ++ DummyEngine/Core/Application/Input.cpp | 54 +++++++++---------- DummyEngine/Core/Application/Input.h | 16 +++--- .../Platform/Linux/Utils/Debug/Demangler.h | 2 +- DummyEngine/Utils/DS/Trie.cpp | 46 ++++++++-------- DummyEngine/Utils/DS/Trie.hpp | 18 +++---- 8 files changed, 77 insertions(+), 73 deletions(-) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 2390286..5698117 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -39,7 +39,7 @@ jobs: cxx-compiler: clang++ c-compiler: clang build-args: --target DummyEditor --parallel 16 --config ${{ matrix.build_type }} - options: CMAKE_BUILD_TYPE=${{ matrix.build_type }} + options: CMAKE_BUILD_TYPE=${{ matrix.build_type }} DE_FORCE_NO_PCH=ON BuildUbuntu: runs-on: ubuntu-latest name: Build Ubuntu @@ -70,7 +70,7 @@ jobs: cxx-compiler: ${{ matrix.cpp_compiler }} c-compiler: ${{ matrix.c_compiler }} build-args: --target DummyEditor --parallel 16 --config ${{ matrix.build_type }} - options: CMAKE_BUILD_TYPE=${{ matrix.build_type }} + options: CMAKE_BUILD_TYPE=${{ matrix.build_type }} DE_FORCE_NO_PCH=ON Linter: runs-on: ubuntu-latest name: Clang Tidy @@ -107,7 +107,7 @@ jobs: files-changed-only: false database: '${{ github.workspace }}/build' repo-root: '${{ github.workspace }}' - ignore: 'build/**|Examples/**|Sandbox/**|DummyEngine/Core/ECS**' + ignore: 'build/**|Examples/**|Sandbox/**|DummyEngine/Core/ECS**|DummyEngine/Platform/Macos/**|DummyEditor/Platform/Macos/**' step-summary: true - name: Check Linter Results if: steps.linter.outputs.checks-failed > 0 diff --git a/CMake/Compiler.cmake b/CMake/Compiler.cmake index 3576c7a..a4bfe9b 100644 --- a/CMake/Compiler.cmake +++ b/CMake/Compiler.cmake @@ -16,10 +16,10 @@ endif() if(${DE_ENABLE_CLANG_TIDY_ON_COMPILATION}) find_program(CLANG_TIDY_EXE NAMES "clang-tidy" "clang-tidy-17" "clang-tidy-18" "clang-tidy-19" REQUIRED) set(CLANG_TIDY_COMMAND "${CLANG_TIDY_EXE}" "-p" "${CMAKE_CURRENT_SOURCE_DIR}/build") - message(STATUS "TIDY COMMAND: [${CLANG_TIDY_COMMAND}]") if (${DE_CLANG_TIDY_WARNINGS_AS_ERRORS}) - set(CLANG_TIDY_COMMAND ${CLANG_TIDY_COMMAND} "--warnings-as-errors=*") + set(CLANG_TIDY_COMMAND ${CLANG_TIDY_COMMAND} "--warnings-as-errors='*'") endif() + message(STATUS "CLANG_TIDY_COMMAND: [${CLANG_TIDY_COMMAND}]") endif() diff --git a/DummyEditor/Platform/Linux/Scripting/Compiler.cpp b/DummyEditor/Platform/Linux/Scripting/Compiler.cpp index 4937829..ea206b5 100644 --- a/DummyEditor/Platform/Linux/Scripting/Compiler.cpp +++ b/DummyEditor/Platform/Linux/Scripting/Compiler.cpp @@ -1,8 +1,12 @@ #include "DummyEditor/Scripting/Compiler.h" #include "DummyEngine/Core/Application/FileSystem.h" +#include "DummyEngine/Utils/Debug/Logger.h" + +#include namespace DummyEngine { + class LinuxCompilerImpl : public CompilerImpl { LOG_AUTHOR(Compiler) public: diff --git a/DummyEngine/Core/Application/Input.cpp b/DummyEngine/Core/Application/Input.cpp index ec58e4a..094f95d 100644 --- a/DummyEngine/Core/Application/Input.cpp +++ b/DummyEngine/Core/Application/Input.cpp @@ -5,29 +5,29 @@ namespace DummyEngine { InputFrame::InputFrame() { - key_states.resize((size_t)Key::Last); + KeyStates.resize((size_t)Key::Last); } SINGLETON_BASE(Input); S_INITIALIZE() { - m_MaxFrameAmount = Config::Get().MaxInputFrameAmount; - m_EventDispatcher.AddEventListener([this](KeyPressedEvent& event) { - DE_ASSERT(m_CurrentFrame.key_states.size() > event.GetKey(), "Bad key code: {}", event.GetKey()); - m_CurrentFrame.key_states[event.GetKey()] = true; + max_frame_amount_ = Config::Get().MaxInputFrameAmount; + event_dispatcher_.AddEventListener([this](KeyPressedEvent& event) { + DE_ASSERT(current_frame_.KeyStates.size() > event.GetKey(), "Bad key code: {}", event.GetKey()); + current_frame_.KeyStates[event.GetKey()] = true; }); - m_EventDispatcher.AddEventListener([this](KeyReleasedEvent& event) { - DE_ASSERT(m_CurrentFrame.key_states.size() > event.GetKey(), "Bad key code: {}", event.GetKey()); - m_CurrentFrame.key_states[event.GetKey()] = false; + event_dispatcher_.AddEventListener([this](KeyReleasedEvent& event) { + DE_ASSERT(current_frame_.KeyStates.size() > event.GetKey(), "Bad key code: {}", event.GetKey()); + current_frame_.KeyStates[event.GetKey()] = false; }); - m_EventDispatcher.AddEventListener([this](SetMouseLockEvent&) { m_CurrentFrame.mouse_locked = true; }); - m_EventDispatcher.AddEventListener([this](SetMouseUnlockEvent&) { m_CurrentFrame.mouse_locked = false; }); - m_EventDispatcher.AddEventListener( - [this](SetMouseLockToggleEvent&) { m_CurrentFrame.mouse_locked = !m_CurrentFrame.mouse_locked; }); + event_dispatcher_.AddEventListener([this](SetMouseLockEvent&) { current_frame_.MouseLocked = true; }); + event_dispatcher_.AddEventListener([this](SetMouseUnlockEvent&) { current_frame_.MouseLocked = false; }); + event_dispatcher_.AddEventListener( + [this](SetMouseLockToggleEvent&) { current_frame_.MouseLocked = !current_frame_.MouseLocked; }); - m_EventDispatcher.AddEventListener([this](MouseMovedCallback& event) { - m_CurrentFrame.x_pos = event.GetXPos(); - m_CurrentFrame.y_pos = event.GetYPos(); + event_dispatcher_.AddEventListener([this](MouseMovedCallback& event) { + current_frame_.PosX = event.GetXPos(); + current_frame_.PosY = event.GetYPos(); }); INewFrame(); @@ -38,44 +38,44 @@ namespace DummyEngine { } S_METHOD_IMPL(Unit, OnEvent, (Event & event), (event)) { - m_EventDispatcher.Dispatch(event); + event_dispatcher_.Dispatch(event); return Unit(); } S_METHOD_IMPL(Unit, NewFrame, (), ()) { DE_PROFILE_SCOPE("Imput Frame Begin"); - m_Frames.push_front(m_CurrentFrame); - if (m_Frames.size() > m_MaxFrameAmount) { - m_Frames.pop_back(); + frames_.push_front(current_frame_); + if (frames_.size() > max_frame_amount_) { + frames_.pop_back(); } return Unit(); } S_METHOD_IMPL(Unit, SetFrameAmount, (size_t n), (n)) { - m_MaxFrameAmount = n; + max_frame_amount_ = n; return Unit(); } S_METHOD_IMPL(double, CursorXOffset, (), ()) { - return m_Frames[0].x_pos - m_Frames[1].x_pos; + return frames_[0].PosX - frames_[1].PosX; } S_METHOD_IMPL(double, CursorYOffset, (), ()) { - return m_Frames[0].y_pos - m_Frames[1].y_pos; + return frames_[0].PosY - frames_[1].PosY; } S_METHOD_IMPL(bool, MouseLocked, (), ()) { - return m_Frames[0].mouse_locked; + return frames_[0].MouseLocked; } S_METHOD_IMPL(bool, KeyReleased, (Key key), (key)) { - return !m_Frames[0].key_states.at((size_t)key) && m_Frames[1].key_states.at((size_t)key); + return !frames_[0].KeyStates.at((size_t)key) && frames_[1].KeyStates.at((size_t)key); } S_METHOD_IMPL(bool, KeyPressed, (Key key), (key)) { - return m_Frames[0].key_states.at((size_t)key) && !m_Frames[1].key_states.at((size_t)key); + return frames_[0].KeyStates.at((size_t)key) && !frames_[1].KeyStates.at((size_t)key); } S_METHOD_IMPL(bool, KeyDown, (Key key), (key)) { - return m_Frames[0].key_states.at((size_t)key); + return frames_[0].KeyStates.at((size_t)key); } S_METHOD_IMPL(bool, KeyUp, (Key key), (key)) { - return !m_Frames[0].key_states.at((size_t)key); + return !frames_[0].KeyStates.at((size_t)key); } } // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/Application/Input.h b/DummyEngine/Core/Application/Input.h index 8c8d6b7..a85ebab 100644 --- a/DummyEngine/Core/Application/Input.h +++ b/DummyEngine/Core/Application/Input.h @@ -7,10 +7,10 @@ namespace DummyEngine { struct InputFrame { - bool mouse_locked = false; - double x_pos; - double y_pos; - std::vector key_states; + bool MouseLocked = false; + double PosX; + double PosY; + std::vector KeyStates; InputFrame(); }; @@ -32,10 +32,10 @@ namespace DummyEngine { S_METHOD_DEF(bool, KeyUp, (Key key)); private: - InputFrame m_CurrentFrame; - EventDispatcher m_EventDispatcher; - std::deque m_Frames; - size_t m_MaxFrameAmount; + InputFrame current_frame_; + EventDispatcher event_dispatcher_; + std::deque frames_; + size_t max_frame_amount_; }; } // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Platform/Linux/Utils/Debug/Demangler.h b/DummyEngine/Platform/Linux/Utils/Debug/Demangler.h index e0aabd7..dc99bd0 100644 --- a/DummyEngine/Platform/Linux/Utils/Debug/Demangler.h +++ b/DummyEngine/Platform/Linux/Utils/Debug/Demangler.h @@ -11,7 +11,7 @@ namespace DummyEngine { char* realname; const std::type_info& ti = typeid(T); - realname = abi::__cxa_demangle(ti.name(), 0, 0, &status); + realname = abi::__cxa_demangle(ti.name(), nullptr, nullptr, &status); res = realname; free(realname); return res; diff --git a/DummyEngine/Utils/DS/Trie.cpp b/DummyEngine/Utils/DS/Trie.cpp index 306e451..155951b 100644 --- a/DummyEngine/Utils/DS/Trie.cpp +++ b/DummyEngine/Utils/DS/Trie.cpp @@ -8,57 +8,57 @@ namespace DummyEngine { if (!v) { return v; } - if (!v->suffix_link) { - if (v == root_ || v->parent == root_) { - v->suffix_link = root_; + if (!v->SuffixLink) { + if (v == root_ || v->Parent == root_) { + v->SuffixLink = root_; } else { - v->suffix_link = GetNext(GetSuffixLink(v->parent), v->char_to_parent); + v->SuffixLink = GetNext(GetSuffixLink(v->Parent), v->CharToParent); } } - return v->suffix_link; + return v->SuffixLink; } Ref Trie::GetNext(Ref v, char c) { if (!v) { return v; } - if (v->next.contains(c)) { - return v->next[c]; - } else if (v->sons.contains(c)) { - v->next[c] = v->sons[c]; + if (v->Next.contains(c)) { + return v->Next[c]; + } else if (v->Sons.contains(c)) { + v->Next[c] = v->Sons[c]; } else if (v == root_) { - v->next[c] = root_; + v->Next[c] = root_; } else { - v->next[c] = GetNext(GetSuffixLink(v), c); + v->Next[c] = GetNext(GetSuffixLink(v), c); } - return v->next[c]; + return v->Next[c]; } Ref Trie::GetUp(Ref v) { if (!v) { return v; } - if (!v->super_suffix_link) { - if (!GetSuffixLink(v)->terminal_idx.empty()) { // leaf - v->super_suffix_link = GetSuffixLink(v); + if (!v->SuperSuffixLink) { + if (!GetSuffixLink(v)->TerminalIdx.empty()) { // leaf + v->SuperSuffixLink = GetSuffixLink(v); } else if (GetSuffixLink(v) == root_) { - v->super_suffix_link = root_; + v->SuperSuffixLink = root_; } else { - v->super_suffix_link = GetUp(GetSuffixLink(v)); + v->SuperSuffixLink = GetUp(GetSuffixLink(v)); } } - return v->super_suffix_link; + return v->SuperSuffixLink; } void Trie::AddWord(std::string& str) { Ref current = root_; for (const char c : str) { - if (!current->sons.contains(c)) { - current->sons[c] = CreateRef(current, c); + if (!current->Sons.contains(c)) { + current->Sons[c] = CreateRef(current, c); } - current = current->sons[c]; + current = current->Sons[c]; } - current->terminal_idx.push_back(words_.size()); + current->TerminalIdx.push_back(words_.size()); words_.push_back(CreateRef(str)); } @@ -76,7 +76,7 @@ namespace DummyEngine { current = GetNext(current, c); auto& ptr = current; while (ptr != root_) { - for (const auto& idx : ptr->terminal_idx) { + for (const auto& idx : ptr->TerminalIdx) { if (idx_found.contains(idx)) { continue; } diff --git a/DummyEngine/Utils/DS/Trie.hpp b/DummyEngine/Utils/DS/Trie.hpp index cc9dd00..352974b 100644 --- a/DummyEngine/Utils/DS/Trie.hpp +++ b/DummyEngine/Utils/DS/Trie.hpp @@ -7,19 +7,19 @@ namespace DummyEngine { class Trie { struct Node { Node(Ref& p, char prev) { - parent = p; - char_to_parent = prev; + Parent = p; + CharToParent = prev; } - std::vector terminal_idx; + std::vector TerminalIdx; - Ref parent; - char char_to_parent; + Ref Parent; + char CharToParent; - std::unordered_map> next; - std::unordered_map> sons; - Ref suffix_link; - Ref super_suffix_link; + std::unordered_map> Next; + std::unordered_map> Sons; + Ref SuffixLink; + Ref SuperSuffixLink; }; Ref GetSuffixLink(Ref v); From d9620038694ae9522d71c9686567365d025c8d4d Mon Sep 17 00:00:00 2001 From: Mag1str02 Date: Fri, 22 Nov 2024 12:32:01 +0300 Subject: [PATCH 10/15] Fixed tidy errors --- .github/workflows/main.yml | 2 +- CMake/Compiler.cmake | 2 +- DummyEditor/CMakeLists.txt | 3 +++ DummyEditor/ImGuiUtils/ImGuiManager.cpp | 2 +- DummyEditor/Panels/ViewportPanel.cpp | 15 ++++++++------- DummyEditor/Panels/ViewportPanel.h | 12 ++++++------ DummyEngine/Utils/DS/Trie.hpp | 2 +- 7 files changed, 21 insertions(+), 17 deletions(-) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 5698117..4d903ca 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -107,7 +107,7 @@ jobs: files-changed-only: false database: '${{ github.workspace }}/build' repo-root: '${{ github.workspace }}' - ignore: 'build/**|Examples/**|Sandbox/**|DummyEngine/Core/ECS**|DummyEngine/Platform/Macos/**|DummyEditor/Platform/Macos/**' + ignore: 'build/**|Examples/**|Sandbox/**|DummyEngine/Core/ECS**|DummyEngine/Platform/**|DummyEditor/Platform/**' step-summary: true - name: Check Linter Results if: steps.linter.outputs.checks-failed > 0 diff --git a/CMake/Compiler.cmake b/CMake/Compiler.cmake index a4bfe9b..49f858f 100644 --- a/CMake/Compiler.cmake +++ b/CMake/Compiler.cmake @@ -17,7 +17,7 @@ if(${DE_ENABLE_CLANG_TIDY_ON_COMPILATION}) find_program(CLANG_TIDY_EXE NAMES "clang-tidy" "clang-tidy-17" "clang-tidy-18" "clang-tidy-19" REQUIRED) set(CLANG_TIDY_COMMAND "${CLANG_TIDY_EXE}" "-p" "${CMAKE_CURRENT_SOURCE_DIR}/build") if (${DE_CLANG_TIDY_WARNINGS_AS_ERRORS}) - set(CLANG_TIDY_COMMAND ${CLANG_TIDY_COMMAND} "--warnings-as-errors='*'") + set(CLANG_TIDY_COMMAND ${CLANG_TIDY_COMMAND} "--warnings-as-errors=*") endif() message(STATUS "CLANG_TIDY_COMMAND: [${CLANG_TIDY_COMMAND}]") endif() diff --git a/DummyEditor/CMakeLists.txt b/DummyEditor/CMakeLists.txt index 720cb78..b2a40d1 100644 --- a/DummyEditor/CMakeLists.txt +++ b/DummyEditor/CMakeLists.txt @@ -15,4 +15,7 @@ add_dependencies(DummyEditor DummyEditorScripts) if (${ENABLE_PRECOMPILED_HEADERS}) target_precompile_headers(DummyEditor REUSE_FROM DummyEngineLib) +endif() +if (${DE_ENABLE_CLANG_TIDY_ON_COMPILATION}) + set_target_properties(DummyEditor PROPERTIES CXX_CLANG_TIDY "${CLANG_TIDY_COMMAND}") endif() \ No newline at end of file diff --git a/DummyEditor/ImGuiUtils/ImGuiManager.cpp b/DummyEditor/ImGuiUtils/ImGuiManager.cpp index 6e394ce..fd3d09e 100644 --- a/DummyEditor/ImGuiUtils/ImGuiManager.cpp +++ b/DummyEditor/ImGuiUtils/ImGuiManager.cpp @@ -52,7 +52,7 @@ namespace DummyEngine { ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f)); ImGui::Begin("DockSpace", - NULL, + nullptr, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus | ImGuiWindowFlags_MenuBar | ImGuiWindowFlags_NoDocking); diff --git a/DummyEditor/Panels/ViewportPanel.cpp b/DummyEditor/Panels/ViewportPanel.cpp index 64d4971..f3b131b 100644 --- a/DummyEditor/Panels/ViewportPanel.cpp +++ b/DummyEditor/Panels/ViewportPanel.cpp @@ -12,13 +12,14 @@ namespace DummyEngine { if (m_Controller) { ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f)); if (ImGui::Begin((ICON_MD_TV + m_Name).c_str())) { - m_ViewportSize = ImGui::GetContentRegionAvail(); - auto buffer = m_FrameBuffer.lock(); + viewport_size_ = ImGui::GetContentRegionAvail(); + auto buffer = frame_buffer_.lock(); if (buffer) { - if (m_UseDepthAttachment) { - ImGui::Image(buffer->GetDepthAttachment()->GetRendererId(), m_ViewportSize, {0, 1}, {1, 0}); + if (use_depth_attachment_) { + ImGui::Image(buffer->GetDepthAttachment()->GetRendererId(), viewport_size_, {0, 1}, {1, 0}); } else { - ImGui::Image(buffer->GetColorAttachment(0)->GetRendererId(), m_ViewportSize, {0, 1}, {1, 0}); + ImGui::Image(buffer->GetColorAttachment(0)->GetRendererId(), viewport_size_, {0, 1}, {1, 0}); + ToolPanel(); } } @@ -69,7 +70,7 @@ namespace DummyEngine { ++button_amount; build_and_run = true; } - ImVec2 cursor_pos{m_ViewportSize.x * 0.5f - (button_amount * button_size.x + (button_amount - 1) * button_padding.x) / 2, button_padding.y}; + ImVec2 cursor_pos{viewport_size_.x * 0.5f - (button_amount * button_size.x + (button_amount - 1) * button_padding.x) / 2, button_padding.y}; if (play) { ImGui::SetCursorPos(cursor_pos); @@ -119,6 +120,6 @@ namespace DummyEngine { } } void ViewportPanel::SetFrameBuffer(Ref buffer) { - m_FrameBuffer = buffer; + frame_buffer_ = buffer; } } // namespace DummyEngine \ No newline at end of file diff --git a/DummyEditor/Panels/ViewportPanel.h b/DummyEditor/Panels/ViewportPanel.h index 5a089ec..76a0758 100644 --- a/DummyEditor/Panels/ViewportPanel.h +++ b/DummyEditor/Panels/ViewportPanel.h @@ -18,14 +18,14 @@ namespace DummyEngine { void ToolPanel(); void SetFrameBuffer(Ref buffer); - U32 GetWidth() const { return m_ViewportSize.x; } - U32 GetHeight() const { return m_ViewportSize.y; } - void UseDepthAttachment(bool f) { m_UseDepthAttachment = f; } + U32 GetWidth() const { return viewport_size_.x; } + U32 GetHeight() const { return viewport_size_.y; } + void UseDepthAttachment(bool f) { use_depth_attachment_ = f; } private: - bool m_UseDepthAttachment = false; - ImVec2 m_ViewportSize; - WeakRef m_FrameBuffer; + bool use_depth_attachment_ = false; + ImVec2 viewport_size_; + WeakRef frame_buffer_; }; } // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Utils/DS/Trie.hpp b/DummyEngine/Utils/DS/Trie.hpp index 352974b..47c6af3 100644 --- a/DummyEngine/Utils/DS/Trie.hpp +++ b/DummyEngine/Utils/DS/Trie.hpp @@ -7,7 +7,7 @@ namespace DummyEngine { class Trie { struct Node { Node(Ref& p, char prev) { - Parent = p; + Parent = p; CharToParent = prev; } From c63ac7faf6ae784960a80d4e64df6bc54fe3d069 Mon Sep 17 00:00:00 2001 From: Mag1str02 Date: Fri, 22 Nov 2024 13:48:20 +0300 Subject: [PATCH 11/15] Restructured ECS headers for better tooling --- .github/workflows/main.yml | 2 +- DummyEngine/Core/ECS/ComponentArray.h | 29 ++ DummyEngine/Core/ECS/ComponentManager.h | 41 +++ DummyEngine/Core/ECS/ECS.h | 271 +----------------- DummyEngine/Core/ECS/Entity.h | 39 +++ DummyEngine/Core/ECS/EntityManager.h | 26 ++ DummyEngine/Core/ECS/Forward.h | 21 ++ .../{ => Implementation}/ComponentArray.hpp | 2 + .../{ => Implementation}/ComponentManager.hpp | 72 ++--- .../Core/ECS/{ => Implementation}/ECS.cpp | 0 .../Core/ECS/{ => Implementation}/Entity.hpp | 3 + .../{ => Implementation}/EntityManager.hpp | 4 + .../Core/ECS/Implementation/Signature.hpp | 46 +++ .../Core/ECS/{ => Implementation}/Storage.hpp | 6 +- .../ECS/{ => Implementation}/StorageView.hpp | 5 + .../Core/ECS/{ => Implementation}/System.hpp | 6 + .../{ => Implementation}/SystemManager.hpp | 11 +- DummyEngine/Core/ECS/Signature.h | 18 ++ DummyEngine/Core/ECS/Storage.h | 49 ++++ DummyEngine/Core/ECS/StorageView.h | 37 +++ DummyEngine/Core/ECS/System.h | 23 ++ DummyEngine/Core/ECS/SystemManager.h | 21 ++ DummyEngine/Sources.cmake | 2 +- 23 files changed, 421 insertions(+), 313 deletions(-) create mode 100644 DummyEngine/Core/ECS/ComponentArray.h create mode 100644 DummyEngine/Core/ECS/ComponentManager.h create mode 100644 DummyEngine/Core/ECS/Entity.h create mode 100644 DummyEngine/Core/ECS/EntityManager.h create mode 100644 DummyEngine/Core/ECS/Forward.h rename DummyEngine/Core/ECS/{ => Implementation}/ComponentArray.hpp (96%) rename DummyEngine/Core/ECS/{ => Implementation}/ComponentManager.hpp (59%) rename DummyEngine/Core/ECS/{ => Implementation}/ECS.cpp (100%) rename DummyEngine/Core/ECS/{ => Implementation}/Entity.hpp (97%) rename DummyEngine/Core/ECS/{ => Implementation}/EntityManager.hpp (96%) create mode 100644 DummyEngine/Core/ECS/Implementation/Signature.hpp rename DummyEngine/Core/ECS/{ => Implementation}/Storage.hpp (96%) rename DummyEngine/Core/ECS/{ => Implementation}/StorageView.hpp (94%) rename DummyEngine/Core/ECS/{ => Implementation}/System.hpp (78%) rename DummyEngine/Core/ECS/{ => Implementation}/SystemManager.hpp (65%) create mode 100644 DummyEngine/Core/ECS/Signature.h create mode 100644 DummyEngine/Core/ECS/Storage.h create mode 100644 DummyEngine/Core/ECS/StorageView.h create mode 100644 DummyEngine/Core/ECS/System.h create mode 100644 DummyEngine/Core/ECS/SystemManager.h diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 4d903ca..1091a29 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -107,7 +107,7 @@ jobs: files-changed-only: false database: '${{ github.workspace }}/build' repo-root: '${{ github.workspace }}' - ignore: 'build/**|Examples/**|Sandbox/**|DummyEngine/Core/ECS**|DummyEngine/Platform/**|DummyEditor/Platform/**' + ignore: 'build/**|Examples/**|Sandbox/**|DummyEngine/Platform/**|DummyEditor/Platform/**' step-summary: true - name: Check Linter Results if: steps.linter.outputs.checks-failed > 0 diff --git a/DummyEngine/Core/ECS/ComponentArray.h b/DummyEngine/Core/ECS/ComponentArray.h new file mode 100644 index 0000000..8e796dd --- /dev/null +++ b/DummyEngine/Core/ECS/ComponentArray.h @@ -0,0 +1,29 @@ +#pragma once + +#include "Forward.h" + +namespace DummyEngine { + + class IComponentArray { + public: + virtual ~IComponentArray() = default; + virtual void* AddComponent(U32 id, void* component) = 0; + virtual void* GetComponent(U32 id) = 0; + virtual bool HasComponent(U32 id) = 0; + virtual void RemoveComponent(U32 id) = 0; + }; + template class ComponentArray : public IComponentArray { + public: + ComponentArray() = default; + virtual void* AddComponent(U32 id, void* component); + virtual void* GetComponent(U32 id); + virtual bool HasComponent(U32 id); + virtual void RemoveComponent(U32 id); + + private: + std::unordered_map entity_to_index_; + std::vector index_to_entity_; + std::vector component_array_; + }; + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/ECS/ComponentManager.h b/DummyEngine/Core/ECS/ComponentManager.h new file mode 100644 index 0000000..5af52cc --- /dev/null +++ b/DummyEngine/Core/ECS/ComponentManager.h @@ -0,0 +1,41 @@ +#pragma once + +#include "Forward.h" + +namespace DummyEngine { + + class ComponentManager { + public: + explicit ComponentManager(Storage* storage); + + template ComponentType* AddComponent(U32 entity_id, const ComponentType& component); + template ComponentType* GetComponent(U32 entity_id); + template void RemoveComponent(U32 entity_id); + template bool HasComponent(U32 entity_id) const; + void Destroy(U32 entity_id); + + template void SetAddHandler(std::function func); + template void SetRemoveHandler(std::function func); + + template Signature BuildSignature(); + bool Matches(U32 id, const Signature& signature) const; + + private: + template typename std::enable_if::type ValidateComponents() const; + template bool ValidateComponents() const; + + template typename std::enable_if::type GetSignature() const; + template Signature GetSignature() const; + + void ValidateSignature(U32 entity_id); + template void RegisterComponent(); + + std::unordered_map> component_arrays_; + std::unordered_map component_id_; + std::unordered_map> add_handlers_; + std::unordered_map> remove_handlers_; + std::vector signatures_; + Storage* storage_; + }; + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/ECS/ECS.h b/DummyEngine/Core/ECS/ECS.h index e7d687a..1231c72 100644 --- a/DummyEngine/Core/ECS/ECS.h +++ b/DummyEngine/Core/ECS/ECS.h @@ -1,264 +1,11 @@ #pragma once -#include "DummyEngine/Utils/Debug/Assert.h" // IWYU pragma: export -#include "DummyEngine/Utils/Types/Types.h" - -#include - -#define INDEX(type) std::type_index(typeid(type)) - -namespace DummyEngine { - - //*___CLASS_DECLARATIONS___________________________________________________________________________________________________________________________________________________________________________________________________ - class Entity; - class Storage; - class System; - class IComponentArray; - class ComponentManager; - class EntityManager; - class SystemManager; - template class StorageView; - template class ComponentArray; - - //*___COMPONENT_MANAGER___________________________________________________________________________________________________________________________________________________________________________________________ - - class IComponentArray { - public: - virtual ~IComponentArray() = default; - virtual void* AddComponent(U32 id, void* component) = 0; - virtual void* GetComponent(U32 id) = 0; - virtual bool HasComponent(U32 id) = 0; - virtual void RemoveComponent(U32 id) = 0; - }; - template class ComponentArray : public IComponentArray { - public: - ComponentArray() = default; - virtual void* AddComponent(U32 id, void* component); - virtual void* GetComponent(U32 id); - virtual bool HasComponent(U32 id); - virtual void RemoveComponent(U32 id); - - private: - std::unordered_map entity_to_index_; - std::vector index_to_entity_; - std::vector component_array_; - }; - - class Signature { - public: - bool Get(U64 id) const; - void Set(U64 id, bool value); - bool Matches(const Signature& required) const; - size_t Size() const { - size_t size = 0; - for (size_t i = 0; i < 64 * data_.size(); ++i) { - if (Get(i)) { - ++size; - } - } - return size; - } - - private: - std::vector data_; - }; - class ComponentManager { - public: - explicit ComponentManager(Storage* storage); - - template ComponentType* AddComponent(U32 entity_id, const ComponentType& component); - template ComponentType* GetComponent(U32 entity_id); - template void RemoveComponent(U32 entity_id); - template bool HasComponent(U32 entity_id) const; - void Destroy(U32 entity_id); - - template void SetAddHandler(std::function func); - template void SetRemoveHandler(std::function func); - - template Signature BuildSignature(); - bool Matches(U32 id, const Signature& signature) const; - - private: - template typename std::enable_if::type ValidateComponents() const; - template bool ValidateComponents() const; - - template typename std::enable_if::type GetSignature() const; - template Signature GetSignature() const; - - void ValidateSignature(U32 entity_id); - template void RegisterComponent(); - - std::unordered_map> component_arrays_; - std::unordered_map component_id_; - std::unordered_map> add_handlers_; - std::unordered_map> remove_handlers_; - std::vector signatures_; - Storage* storage_; - }; - - //*___ENTITY_MANAGER___________________________________________________________________________________________________________________________________________________________________________________________ - - class EntityManager { - public: - EntityManager() = default; - - std::pair CreateEntity(); - void Destroy(U32 id); - bool Valid(U32 id, U32 gen) const; - - U32 Generation(U32 id) const; - U32 NextEntity(U32 id) const; - U32 BeginEntity() const; - U32 EndEntity() const; - - private: - std::vector generations_; - std::vector states_; - std::queue available_entities_; - }; - - //*___SYSTEM_MANAGER___________________________________________________________________________________________________________________________________________________________________________________________ - - class System { - public: - virtual ~System() = default; - virtual void Update(float dt) = 0; - virtual std::string GetName() const = 0; - - protected: - template StorageView View(); - - private: - friend class SystemManager; - void Bind(Storage* storage); - - Storage* storage_; - }; - class SystemManager { - public: - explicit SystemManager(Storage* storage); - void Update(float dt); - template void AddDependency(); - template void AttachSystem(std::shared_ptr system); - - private: - std::vector> systems_; - std::unordered_map system_ids_; - std::vector> dependency_graph_; - Storage* storage_; - }; - - //*___ENTITY____________________________________________________________________________________________________________________________________________________________________________________________________ - - class Entity { - public: - Entity(); - ~Entity() = default; - Entity(const Entity&) = default; - Entity(Entity&&) = default; - Entity& operator=(const Entity&) = default; - Entity& operator=(Entity&&) = default; - - bool Valid() const; - void Destroy(); - - template ComponentType* AddComponent(ComponentType component = ComponentType()); - template ComponentType* GetComponent(); - template ComponentType& Add(ComponentType component = ComponentType()); - template ComponentType& Get(); - template bool Has() const; - template void Remove(); - - bool operator==(const Entity& other) const; - bool operator!=(const Entity& other) const; - - private: - template friend class StorageView; - friend struct std::hash; - friend class Storage; - - U32 id_; - U32 gen_; - WeakRef storage_; - }; - - //*___STORAGE___________________________________________________________________________________________________________________________________________________________________________________________ - - class Storage : public std::enable_shared_from_this { - public: - Storage(); - // If any of remove callbacks use functions of passed entity, Destruct should be called before destructor - void Destruct(); - ~Storage() = default; - Storage(const Storage&) = delete; - Storage(Storage&&) = delete; - Storage& operator=(const Storage&) = delete; - Storage& operator=(Storage&&) = delete; - - Entity CreateEntity(); - template StorageView View(); - - template void SetAddHandler(std::function func); - template void SetRemoveHandler(std::function func); - - template void AttachSystem(std::shared_ptr system); - void UpdateSystems(float dt); - - private: - template friend class StorageView; - friend class Entity; - friend class ComponentManager; - friend struct StorageDeleter; - - Entity GetEntity(U32 id); - bool Valid(U32 id, U32 gen) const; - void Destroy(U32 id, U32 gen); - - template ComponentType* AddComponent(U32 id, U32 gen, const ComponentType& component); - template ComponentType* GetComponent(U32 id, U32 gen); - template bool HasComponent(U32 id, U32 gen) const; - template void RemoveComponent(U32 id, U32 gen); - - EntityManager entity_manager_; - ComponentManager component_manager_; - SystemManager system_manager_; - }; - template class StorageView { - public: - class Iterator { - public: - Iterator(U32 id, StorageView* v); - - bool operator==(const Iterator& other) const; - bool operator!=(const Iterator& other) const; - Iterator& operator++(); - Iterator operator++(int); - Entity operator*(); - - private: - friend class StorageView; - U32 id_; - StorageView* view_; - }; - Iterator begin(); // NOLINT - Iterator end(); // NOLINT - bool Empty(); - - private: - friend class Storage; - explicit StorageView(Storage* storage); - - Signature signature_; - Storage* storage_; - }; - -} // namespace DummyEngine - -#include "DummyEngine/Core/ECS/ComponentArray.hpp" // IWYU pragma: export -#include "DummyEngine/Core/ECS/ComponentManager.hpp" // IWYU pragma: export -#include "DummyEngine/Core/ECS/Entity.hpp" // IWYU pragma: export -#include "DummyEngine/Core/ECS/EntityManager.hpp" // IWYU pragma: export -#include "DummyEngine/Core/ECS/Storage.hpp" // IWYU pragma: export -#include "DummyEngine/Core/ECS/StorageView.hpp" // IWYU pragma: export -#include "DummyEngine/Core/ECS/System.hpp" // IWYU pragma: export -#include "DummyEngine/Core/ECS/SystemManager.hpp" // IWYU pragma: export \ No newline at end of file +#include "DummyEngine/Core/ECS/Implementation/ComponentArray.hpp" // IWYU pragma: export +#include "DummyEngine/Core/ECS/Implementation/ComponentManager.hpp" // IWYU pragma: export +#include "DummyEngine/Core/ECS/Implementation/Entity.hpp" // IWYU pragma: export +#include "DummyEngine/Core/ECS/Implementation/EntityManager.hpp" // IWYU pragma: export +#include "DummyEngine/Core/ECS/Implementation/Signature.hpp" // IWYU pragma: export +#include "DummyEngine/Core/ECS/Implementation/Storage.hpp" // IWYU pragma: export +#include "DummyEngine/Core/ECS/Implementation/StorageView.hpp" // IWYU pragma: export +#include "DummyEngine/Core/ECS/Implementation/System.hpp" // IWYU pragma: export +#include "DummyEngine/Core/ECS/Implementation/SystemManager.hpp" // IWYU pragma: export diff --git a/DummyEngine/Core/ECS/Entity.h b/DummyEngine/Core/ECS/Entity.h new file mode 100644 index 0000000..8a8e7e4 --- /dev/null +++ b/DummyEngine/Core/ECS/Entity.h @@ -0,0 +1,39 @@ +#pragma once + +#include "Forward.h" + +namespace DummyEngine { + + class Entity { + public: + Entity(); + ~Entity() = default; + Entity(const Entity&) = default; + Entity(Entity&&) = default; + Entity& operator=(const Entity&) = default; + Entity& operator=(Entity&&) = default; + + bool Valid() const; + void Destroy(); + + template ComponentType* AddComponent(ComponentType component = ComponentType()); + template ComponentType* GetComponent(); + template ComponentType& Add(ComponentType component = ComponentType()); + template ComponentType& Get(); + template bool Has() const; + template void Remove(); + + bool operator==(const Entity& other) const; + bool operator!=(const Entity& other) const; + + private: + template friend class StorageView; + friend struct std::hash; + friend class Storage; + + U32 id_; + U32 gen_; + WeakRef storage_; + }; + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/ECS/EntityManager.h b/DummyEngine/Core/ECS/EntityManager.h new file mode 100644 index 0000000..59d69a0 --- /dev/null +++ b/DummyEngine/Core/ECS/EntityManager.h @@ -0,0 +1,26 @@ +#pragma once + +#include "DummyEngine/Utils/Types/Types.h" + +namespace DummyEngine { + + class EntityManager { + public: + EntityManager() = default; + + std::pair CreateEntity(); + void Destroy(U32 id); + bool Valid(U32 id, U32 gen) const; + + U32 Generation(U32 id) const; + U32 NextEntity(U32 id) const; + U32 BeginEntity() const; + U32 EndEntity() const; + + private: + std::vector generations_; + std::vector states_; + std::queue available_entities_; + }; + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/ECS/Forward.h b/DummyEngine/Core/ECS/Forward.h new file mode 100644 index 0000000..de1f6be --- /dev/null +++ b/DummyEngine/Core/ECS/Forward.h @@ -0,0 +1,21 @@ +#pragma once + +#include "DummyEngine/Utils/Debug/Assert.h" // IWYU pragma: export +#include "DummyEngine/Utils/Types/Types.h" // IWYU pragma: export + +#include // IWYU pragma: export + +namespace DummyEngine { + + class Signature; + class Entity; + class Storage; + class System; + class IComponentArray; + class ComponentManager; + class EntityManager; + class SystemManager; + template class StorageView; + template class ComponentArray; + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/ECS/ComponentArray.hpp b/DummyEngine/Core/ECS/Implementation/ComponentArray.hpp similarity index 96% rename from DummyEngine/Core/ECS/ComponentArray.hpp rename to DummyEngine/Core/ECS/Implementation/ComponentArray.hpp index a924c81..3d624ab 100644 --- a/DummyEngine/Core/ECS/ComponentArray.hpp +++ b/DummyEngine/Core/ECS/Implementation/ComponentArray.hpp @@ -1,5 +1,7 @@ #pragma once +#include "DummyEngine/Core/ECS/ComponentArray.h" + namespace DummyEngine { template void* ComponentArray::AddComponent(U32 id, void* component) { DE_ASSERT(!entity_to_index_.contains(id), "Adding component which already exists to entity {}", id); diff --git a/DummyEngine/Core/ECS/ComponentManager.hpp b/DummyEngine/Core/ECS/Implementation/ComponentManager.hpp similarity index 59% rename from DummyEngine/Core/ECS/ComponentManager.hpp rename to DummyEngine/Core/ECS/Implementation/ComponentManager.hpp index 8aa77d4..eba982d 100644 --- a/DummyEngine/Core/ECS/ComponentManager.hpp +++ b/DummyEngine/Core/ECS/Implementation/ComponentManager.hpp @@ -1,33 +1,14 @@ #pragma once +#include "DummyEngine/Core/ECS/ComponentArray.h" +#include "DummyEngine/Core/ECS/ComponentManager.h" +#include "DummyEngine/Core/ECS/Entity.h" +#include "DummyEngine/Core/ECS/Signature.h" +#include "DummyEngine/Core/ECS/Storage.h" + namespace DummyEngine { -#ifdef ECS_IMPLEMENTATION - bool Signature::Get(U64 id) const { - return (data_.size() <= (id >> 6) ? false : (data_[id >> 6] >> (id & 63)) & 1); - } - void Signature::Set(U64 id, bool value) { - if (data_.size() <= id >> 6) { - data_.resize((id >> 6) + 1); - } - data_[id >> 6] &= ~(1 << (id & 63)); - data_[id >> 6] |= ((U64)value << (id & 63)); - } - bool Signature::Matches(const Signature& required) const { - size_t i; - size_t mn = std::min(required.data_.size(), data_.size()); - for (i = 0; i < mn; ++i) { - if ((data_[i] & required.data_[i]) != required.data_[i]) { - return false; - } - } - while (i < required.data_.size()) { - if (required.data_[i++]) { - return false; - } - } - return true; - } +#ifdef ECS_IMPLEMENTATION ComponentManager::ComponentManager(Storage* storage) : storage_(storage) {} void ComponentManager::Destroy(U32 entity_id) { Entity e = storage_->GetEntity(entity_id); @@ -55,20 +36,20 @@ namespace DummyEngine { template void ComponentManager::SetAddHandler(std::function func) { RegisterComponent(); - add_handlers_[INDEX(ComponentType)] = func; + add_handlers_[std::type_index(typeid(ComponentType))] = func; } template void ComponentManager::SetRemoveHandler(std::function func) { RegisterComponent(); - remove_handlers_[INDEX(ComponentType)] = func; + remove_handlers_[std::type_index(typeid(ComponentType))] = func; } template ComponentType* ComponentManager::AddComponent(U32 entity_id, const ComponentType& component) { RegisterComponent(); ValidateSignature(entity_id); - signatures_[entity_id].Set(component_id_[INDEX(ComponentType)], true); + signatures_[entity_id].Set(component_id_[std::type_index(typeid(ComponentType))], true); auto* c = reinterpret_cast( - component_arrays_[INDEX(ComponentType)]->AddComponent(entity_id, const_cast(&component))); - add_handlers_[INDEX(ComponentType)](storage_->GetEntity(entity_id)); + component_arrays_[std::type_index(typeid(ComponentType))]->AddComponent(entity_id, const_cast(&component))); + add_handlers_[std::type_index(typeid(ComponentType))](storage_->GetEntity(entity_id)); return c; } template ComponentType* ComponentManager::GetComponent(U32 entity_id) { @@ -76,22 +57,22 @@ namespace DummyEngine { if (!HasComponent(entity_id)) { return nullptr; } - return reinterpret_cast(component_arrays_[INDEX(ComponentType)]->GetComponent(entity_id)); + return reinterpret_cast(component_arrays_[std::type_index(typeid(ComponentType))]->GetComponent(entity_id)); } template void ComponentManager::RemoveComponent(U32 entity_id) { ValidateSignature(entity_id); if (HasComponent(entity_id)) { - remove_handlers_[INDEX(ComponentType)](storage_->GetEntity(entity_id)); - signatures_[entity_id].Set(component_id_[INDEX(ComponentType)], false); - component_arrays_[INDEX(ComponentType)]->RemoveComponent(entity_id); + remove_handlers_[std::type_index(typeid(ComponentType))](storage_->GetEntity(entity_id)); + signatures_[entity_id].Set(component_id_[std::type_index(typeid(ComponentType))], false); + component_arrays_[std::type_index(typeid(ComponentType))]->RemoveComponent(entity_id); } } template bool ComponentManager::HasComponent(U32 entity_id) const { - if (signatures_.size() < entity_id + 1 || component_id_.find(INDEX(ComponentType)) == component_id_.end()) { + if (signatures_.size() < entity_id + 1 || component_id_.find(std::type_index(typeid(ComponentType))) == component_id_.end()) { return false; } - return signatures_.at(entity_id).Get(component_id_.at(INDEX(ComponentType))); + return signatures_.at(entity_id).Get(component_id_.at(std::type_index(typeid(ComponentType)))); } template Signature ComponentManager::BuildSignature() { @@ -107,7 +88,7 @@ namespace DummyEngine { return true; } template bool ComponentManager::ValidateComponents() const { - if (component_id_.find(INDEX(T)) == component_id_.end()) { + if (component_id_.find(std::type_index(typeid(T))) == component_id_.end()) { return false; } return ValidateComponents(); @@ -118,17 +99,18 @@ namespace DummyEngine { } template Signature ComponentManager::GetSignature() const { Signature res = GetSignature(); - res.Set(component_id_.at(INDEX(T)), true); + res.Set(component_id_.at(std::type_index(typeid(T))), true); return res; } template void ComponentManager::RegisterComponent() { - if (component_id_.find(INDEX(ComponentType)) == component_id_.end()) { - auto default_handler = [](Entity) {}; - component_id_[INDEX(ComponentType)] = component_id_.size(); - component_arrays_[INDEX(ComponentType)] = std::make_shared>(ComponentArray()); - add_handlers_[INDEX(ComponentType)] = default_handler; - remove_handlers_[INDEX(ComponentType)] = default_handler; + if (component_id_.find(std::type_index(typeid(ComponentType))) == component_id_.end()) { + auto default_handler = [](Entity) {}; + component_id_[std::type_index(typeid(ComponentType))] = component_id_.size(); + component_arrays_[std::type_index(typeid(ComponentType))] = + std::make_shared>(ComponentArray()); + add_handlers_[std::type_index(typeid(ComponentType))] = default_handler; + remove_handlers_[std::type_index(typeid(ComponentType))] = default_handler; } } } // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/ECS/ECS.cpp b/DummyEngine/Core/ECS/Implementation/ECS.cpp similarity index 100% rename from DummyEngine/Core/ECS/ECS.cpp rename to DummyEngine/Core/ECS/Implementation/ECS.cpp diff --git a/DummyEngine/Core/ECS/Entity.hpp b/DummyEngine/Core/ECS/Implementation/Entity.hpp similarity index 97% rename from DummyEngine/Core/ECS/Entity.hpp rename to DummyEngine/Core/ECS/Implementation/Entity.hpp index 688ed1e..f214534 100644 --- a/DummyEngine/Core/ECS/Entity.hpp +++ b/DummyEngine/Core/ECS/Implementation/Entity.hpp @@ -1,5 +1,8 @@ #pragma once +#include "DummyEngine/Core/ECS/Entity.h" +#include "DummyEngine/Core/ECS/Storage.h" + namespace DummyEngine { #ifdef ECS_IMPLEMENTATION Entity::Entity() : id_(0), gen_(0) {} diff --git a/DummyEngine/Core/ECS/EntityManager.hpp b/DummyEngine/Core/ECS/Implementation/EntityManager.hpp similarity index 96% rename from DummyEngine/Core/ECS/EntityManager.hpp rename to DummyEngine/Core/ECS/Implementation/EntityManager.hpp index 60b9f06..e440b01 100644 --- a/DummyEngine/Core/ECS/EntityManager.hpp +++ b/DummyEngine/Core/ECS/Implementation/EntityManager.hpp @@ -1,6 +1,9 @@ #pragma once +#include "DummyEngine/Core/ECS/EntityManager.h" + namespace DummyEngine { + #ifdef ECS_IMPLEMENTATION std::pair EntityManager::CreateEntity() { if (available_entities_.empty()) { @@ -45,4 +48,5 @@ namespace DummyEngine { return states_.size(); } #endif + } // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/ECS/Implementation/Signature.hpp b/DummyEngine/Core/ECS/Implementation/Signature.hpp new file mode 100644 index 0000000..715055c --- /dev/null +++ b/DummyEngine/Core/ECS/Implementation/Signature.hpp @@ -0,0 +1,46 @@ +#include "DummyEngine/Core/ECS/Signature.h" + +namespace DummyEngine { + +#ifdef ECS_IMPLEMENTATION + size_t Signature::Size() const { + size_t size = 0; + for (size_t i = 0; i < 64 * data_.size(); ++i) { + if (Get(i)) { + ++size; + } + } + return size; + } + bool Signature::Get(U64 id) const { + if (data_.size() <= (id >> 6)) { + return false; + } + return ((data_[id >> 6] >> (id & 63)) & 1) != 0; + } + void Signature::Set(U64 id, bool value) { + if (data_.size() <= id >> 6) { + data_.resize((id >> 6) + 1); + } + data_[id >> 6] &= ~(1 << (id & 63)); + data_[id >> 6] |= ((U64)value << (id & 63)); + } + bool Signature::Matches(const Signature& required) const { + size_t i; + size_t mn = std::min(required.data_.size(), data_.size()); + for (i = 0; i < mn; ++i) { + if ((data_[i] & required.data_[i]) != required.data_[i]) { + return false; + } + } + while (i < required.data_.size()) { + if (required.data_[i++] != 0) { + return false; + } + } + return true; + } + +#endif + +} // namespace DummyEngine diff --git a/DummyEngine/Core/ECS/Storage.hpp b/DummyEngine/Core/ECS/Implementation/Storage.hpp similarity index 96% rename from DummyEngine/Core/ECS/Storage.hpp rename to DummyEngine/Core/ECS/Implementation/Storage.hpp index 02d5e51..336740e 100644 --- a/DummyEngine/Core/ECS/Storage.hpp +++ b/DummyEngine/Core/ECS/Implementation/Storage.hpp @@ -1,8 +1,11 @@ #pragma once +#include "DummyEngine/Core/ECS/EntityManager.h" +#include "DummyEngine/Core/ECS/Storage.h" + namespace DummyEngine { -#ifdef ECS_IMPLEMENTATION +#ifdef ECS_IMPLEMENTATION Storage::Storage() : component_manager_(this), system_manager_(this) {} void Storage::Destruct() { for (U32 id = entity_manager_.BeginEntity(); id != entity_manager_.EndEntity(); id = entity_manager_.NextEntity(id)) { @@ -38,6 +41,7 @@ namespace DummyEngine { } } #endif + template StorageView Storage::View() { return StorageView(this); } diff --git a/DummyEngine/Core/ECS/StorageView.hpp b/DummyEngine/Core/ECS/Implementation/StorageView.hpp similarity index 94% rename from DummyEngine/Core/ECS/StorageView.hpp rename to DummyEngine/Core/ECS/Implementation/StorageView.hpp index 5cb3789..7ffc500 100644 --- a/DummyEngine/Core/ECS/StorageView.hpp +++ b/DummyEngine/Core/ECS/Implementation/StorageView.hpp @@ -1,5 +1,10 @@ #pragma once +#include "Storage.hpp" // IWYU pragma: keep + +#include "DummyEngine/Core/ECS/Entity.h" +#include "DummyEngine/Core/ECS/StorageView.h" + namespace DummyEngine { template StorageView::Iterator::Iterator(U32 id, StorageView* v) : id_(id), view_(v) {} diff --git a/DummyEngine/Core/ECS/System.hpp b/DummyEngine/Core/ECS/Implementation/System.hpp similarity index 78% rename from DummyEngine/Core/ECS/System.hpp rename to DummyEngine/Core/ECS/Implementation/System.hpp index a9ec375..fd27330 100644 --- a/DummyEngine/Core/ECS/System.hpp +++ b/DummyEngine/Core/ECS/Implementation/System.hpp @@ -1,12 +1,18 @@ #pragma once +#include "DummyEngine/Core/ECS/Storage.h" +#include "DummyEngine/Core/ECS/System.h" + namespace DummyEngine { + #ifdef ECS_IMPLEMENTATION void System::Bind(Storage* storage) { storage_ = storage; } #endif + template StorageView System::View() { return storage_->View(); } + } // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/ECS/SystemManager.hpp b/DummyEngine/Core/ECS/Implementation/SystemManager.hpp similarity index 65% rename from DummyEngine/Core/ECS/SystemManager.hpp rename to DummyEngine/Core/ECS/Implementation/SystemManager.hpp index 4bfc013..ae0b9f2 100644 --- a/DummyEngine/Core/ECS/SystemManager.hpp +++ b/DummyEngine/Core/ECS/Implementation/SystemManager.hpp @@ -1,6 +1,10 @@ #pragma once +#include "DummyEngine/Core/ECS/System.h" +#include "DummyEngine/Core/ECS/SystemManager.h" + namespace DummyEngine { + #ifdef ECS_IMPLEMENTATION SystemManager::SystemManager(Storage* storage) { storage_ = storage; @@ -13,11 +17,12 @@ namespace DummyEngine { #endif template void SystemManager::AddDependency() {} template void SystemManager::AttachSystem(std::shared_ptr system) { - if (system_ids_.find(INDEX(SystemType)) == system_ids_.end()) { - size_t sz = system_ids_.size(); - system_ids_[INDEX(SystemType)] = sz; + if (system_ids_.find(std::type_index(typeid(SystemType))) == system_ids_.end()) { + size_t sz = system_ids_.size(); + system_ids_[std::type_index(typeid(SystemType))] = sz; systems_.push_back(system); systems_.back()->Bind(storage_); } } + } // namespace DummyEngine diff --git a/DummyEngine/Core/ECS/Signature.h b/DummyEngine/Core/ECS/Signature.h new file mode 100644 index 0000000..ec9be48 --- /dev/null +++ b/DummyEngine/Core/ECS/Signature.h @@ -0,0 +1,18 @@ +#pragma once + +#include "Forward.h" + +namespace DummyEngine { + + class Signature { + public: + bool Get(U64 id) const; + void Set(U64 id, bool value); + bool Matches(const Signature& required) const; + size_t Size() const; + + private: + std::vector data_; + }; + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/ECS/Storage.h b/DummyEngine/Core/ECS/Storage.h new file mode 100644 index 0000000..ca9338d --- /dev/null +++ b/DummyEngine/Core/ECS/Storage.h @@ -0,0 +1,49 @@ +#pragma once + +#include "ComponentManager.h" +#include "EntityManager.h" +#include "SystemManager.h" + +namespace DummyEngine { + + class Storage : public std::enable_shared_from_this { + public: + Storage(); + // If any of remove callbacks use functions of passed entity, Destruct should be called before destructor + void Destruct(); + ~Storage() = default; + Storage(const Storage&) = delete; + Storage(Storage&&) = delete; + Storage& operator=(const Storage&) = delete; + Storage& operator=(Storage&&) = delete; + + Entity CreateEntity(); + template StorageView View(); + + template void SetAddHandler(std::function func); + template void SetRemoveHandler(std::function func); + + template void AttachSystem(std::shared_ptr system); + void UpdateSystems(float dt); + + private: + template friend class StorageView; + friend class Entity; + friend class ComponentManager; + friend struct StorageDeleter; + + Entity GetEntity(U32 id); + bool Valid(U32 id, U32 gen) const; + void Destroy(U32 id, U32 gen); + + template ComponentType* AddComponent(U32 id, U32 gen, const ComponentType& component); + template ComponentType* GetComponent(U32 id, U32 gen); + template bool HasComponent(U32 id, U32 gen) const; + template void RemoveComponent(U32 id, U32 gen); + + EntityManager entity_manager_; + ComponentManager component_manager_; + SystemManager system_manager_; + }; + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/ECS/StorageView.h b/DummyEngine/Core/ECS/StorageView.h new file mode 100644 index 0000000..d3a030c --- /dev/null +++ b/DummyEngine/Core/ECS/StorageView.h @@ -0,0 +1,37 @@ +#pragma once + +#include "Forward.h" +#include "Signature.h" + +namespace DummyEngine { + + template class StorageView { + public: + class Iterator { + public: + Iterator(U32 id, StorageView* v); + + bool operator==(const Iterator& other) const; + bool operator!=(const Iterator& other) const; + Iterator& operator++(); + Iterator operator++(int); + Entity operator*(); + + private: + friend class StorageView; + U32 id_; + StorageView* view_; + }; + Iterator begin(); // NOLINT + Iterator end(); // NOLINT + bool Empty(); + + private: + friend class Storage; + explicit StorageView(Storage* storage); + + Signature signature_; + Storage* storage_; + }; + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/ECS/System.h b/DummyEngine/Core/ECS/System.h new file mode 100644 index 0000000..11943c0 --- /dev/null +++ b/DummyEngine/Core/ECS/System.h @@ -0,0 +1,23 @@ +#pragma once + +#include "Forward.h" + +namespace DummyEngine { + + class System { + public: + virtual ~System() = default; + virtual void Update(float dt) = 0; + virtual std::string GetName() const = 0; + + protected: + template StorageView View(); + + private: + friend class SystemManager; + void Bind(Storage* storage); + + Storage* storage_; + }; + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Core/ECS/SystemManager.h b/DummyEngine/Core/ECS/SystemManager.h new file mode 100644 index 0000000..67b92ad --- /dev/null +++ b/DummyEngine/Core/ECS/SystemManager.h @@ -0,0 +1,21 @@ +#pragma once + +#include "Forward.h" + +namespace DummyEngine { + + class SystemManager { + public: + explicit SystemManager(Storage* storage); + void Update(float dt); + template void AddDependency(); + template void AttachSystem(std::shared_ptr system); + + private: + std::vector> systems_; + std::unordered_map system_ids_; + std::vector> dependency_graph_; + Storage* storage_; + }; + +} // namespace DummyEngine \ No newline at end of file diff --git a/DummyEngine/Sources.cmake b/DummyEngine/Sources.cmake index ff50f31..31d1416 100644 --- a/DummyEngine/Sources.cmake +++ b/DummyEngine/Sources.cmake @@ -27,7 +27,7 @@ Core/Application/FileSystem.cpp Core/Console/ConsoleLayer.cpp Core/Console/Console.cpp -Core/ECS/ECS.cpp +Core/ECS/Implementation/ECS.cpp Core/Scene/Components.cpp Core/Scene/Scene.cpp From e18ea9e39c20ab92593f3ebfdfd0c32bacee2ab0 Mon Sep 17 00:00:00 2001 From: Mag1str02 Date: Fri, 22 Nov 2024 15:14:41 +0300 Subject: [PATCH 12/15] Added sanitizers options --- CMake/Compiler.cmake | 31 ++++++++++++++++++++++++++----- CMake/Options.cmake | 4 +++- CMake/Platform.cmake | 6 +++--- DummyEditor/Sources.cmake | 6 +++--- DummyEngine/CMakeLists.txt | 2 +- DummyEngine/Sources.cmake | 6 +++--- Examples/Test.cpp | 10 +++++----- 7 files changed, 44 insertions(+), 21 deletions(-) diff --git a/CMake/Compiler.cmake b/CMake/Compiler.cmake index 49f858f..3ed7ef2 100644 --- a/CMake/Compiler.cmake +++ b/CMake/Compiler.cmake @@ -5,6 +5,7 @@ set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fPIC -fno-omit-frame-pointer") set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/../Sandbox) set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/../Sandbox) +# Precompiled headers and libc++ set(ENABLE_PRECOMPILED_HEADERS OFF) if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -stdlib=libc++") @@ -13,21 +14,41 @@ endif() if (${DE_FORCE_NO_PCH}) set(ENABLE_PRECOMPILED_HEADERS OFF) endif() -if(${DE_ENABLE_CLANG_TIDY_ON_COMPILATION}) + +# Clang Tidy +if(DE_ENABLE_CLANG_TIDY_ON_COMPILATION) find_program(CLANG_TIDY_EXE NAMES "clang-tidy" "clang-tidy-17" "clang-tidy-18" "clang-tidy-19" REQUIRED) set(CLANG_TIDY_COMMAND "${CLANG_TIDY_EXE}" "-p" "${CMAKE_CURRENT_SOURCE_DIR}/build") - if (${DE_CLANG_TIDY_WARNINGS_AS_ERRORS}) + if (DE_CLANG_TIDY_WARNINGS_AS_ERRORS) set(CLANG_TIDY_COMMAND ${CLANG_TIDY_COMMAND} "--warnings-as-errors=*") endif() message(STATUS "CLANG_TIDY_COMMAND: [${CLANG_TIDY_COMMAND}]") endif() +# Sanitizers https://clang.llvm.org/docs/UsersManual.html#controlling-code-generation +if (DE_ENABLE_ASAN AND DE_ENABLE_TSAN) + message(FATAL_ERROR "ASAN and TSAN cannot be used simultaneously") +endif() +if (DE_ENABLE_UBSAN) + add_compile_options(-fsanitize=undefined) + add_link_options(-fsanitize=undefined) +endif() +if (DE_ENABLE_ASAN) + add_compile_options(-fsanitize=address) + add_link_options(-fsanitize=address) +endif() +if (DE_ENABLE_TSAN) + if (DE_PLATFORM STREQUAL "WINDOWS") + message(FATAL_ERROR "Cannot use TSAN on Windows") + endif() + add_compile_options(-fsanitize=thread) + add_link_options(-fsanitize=thread) +endif() -message(STATUS "Precompiled headers: ${ENABLE_PRECOMPILED_HEADERS}") - +# Warnings function(add_warnings TARGET) target_compile_options(${TARGET} PUBLIC -Wall -Wextra -Wpedantic -Wno-extra-semi -Wno-missing-field-initializers -Werror) - if (${ENABLE_PRECOMPILED_HEADERS}) + if (ENABLE_PRECOMPILED_HEADERS) target_compile_options(${TARGET} PUBLIC -Winvalid-pch) endif() endfunction(add_warnings) \ No newline at end of file diff --git a/CMake/Options.cmake b/CMake/Options.cmake index 9765784..b70adb2 100644 --- a/CMake/Options.cmake +++ b/CMake/Options.cmake @@ -10,4 +10,6 @@ endmacro() set_option(DE_ENABLE_CLANG_TIDY_ON_COMPILATION "Run clang tidy during compilation" OFF) set_option(DE_CLANG_TIDY_WARNINGS_AS_ERRORS "Set clang warnings as errors" OFF) set_option(DE_FORCE_NO_PCH "Prevent PCH" OFF) - +set_option(DE_ENABLE_UBSAN "Enable UBSAN" OFF) +set_option(DE_ENABLE_ASAN "Enable ASAN" OFF) +set_option(DE_ENABLE_TSAN "Enable TSAN" OFF) diff --git a/CMake/Platform.cmake b/CMake/Platform.cmake index a2e232d..200b624 100644 --- a/CMake/Platform.cmake +++ b/CMake/Platform.cmake @@ -1,16 +1,16 @@ if(WIN32) message(STATUS "Platform WINDOWS") - set(CMAKE_PLATFORM "WINDOWS") + set(DE_PLATFORM "WINDOWS") add_compile_definitions(DE_PLATFORM_WINDOWS) endif() if(UNIX AND NOT APPLE) message(STATUS "Platform LINUX") - set(CMAKE_PLATFORM "LINUX") + set(DE_PLATFORM "LINUX") add_compile_definitions(DE_PLATFORM_LINUX) endif() if(APPLE) message(STATUS "Platform MACOS") - set(CMAKE_PLATFORM "MACOS") + set(DE_PLATFORM "MACOS") add_compile_definitions(DE_PLATFORM_MACOS) set(CMAKE_OSX_DEPLOYMENT_TARGET "12.0" CACHE STRING "Minimum OS X deployment version") endif() diff --git a/DummyEditor/Sources.cmake b/DummyEditor/Sources.cmake index 8e8ae43..4187b87 100644 --- a/DummyEditor/Sources.cmake +++ b/DummyEditor/Sources.cmake @@ -17,17 +17,17 @@ set(EDITOR_SOURCES Scripting/ScriptManager.cpp Scripting/Compiler.cpp ) -if("${CMAKE_PLATFORM}" STREQUAL "WINDOWS") +if(DE_PLATFORM STREQUAL "WINDOWS") set(PLATFORM_SOURCES Platform/Windows/Scripting/Compiler.cpp ) endif() -if("${CMAKE_PLATFORM}" STREQUAL "LINUX") +if(DE_PLATFORM STREQUAL "LINUX") set(PLATFORM_SOURCES Platform/Linux/Scripting/Compiler.cpp ) endif() -if("${CMAKE_PLATFORM}" STREQUAL "MACOS") +if(DE_PLATFORM STREQUAL "MACOS") set(PLATFORM_SOURCES Platform/Macos/Scripting/Compiler.cpp ) diff --git a/DummyEngine/CMakeLists.txt b/DummyEngine/CMakeLists.txt index bade05b..48f9674 100644 --- a/DummyEngine/CMakeLists.txt +++ b/DummyEngine/CMakeLists.txt @@ -24,6 +24,6 @@ if (${DE_ENABLE_CLANG_TIDY_ON_COMPILATION}) set_target_properties(DummyEngineLib PROPERTIES CXX_CLANG_TIDY "${CLANG_TIDY_COMMAND}") endif() -if ("${CMAKE_PLATFORM}" STREQUAL "WINDOWS") +if (DE_PLATFORM STREQUAL "WINDOWS") target_compile_definitions(DummyEngineLib PUBLIC YAML_CPP_STATIC_DEFINE) endif() \ No newline at end of file diff --git a/DummyEngine/Sources.cmake b/DummyEngine/Sources.cmake index 31d1416..4fa3302 100644 --- a/DummyEngine/Sources.cmake +++ b/DummyEngine/Sources.cmake @@ -83,21 +83,21 @@ ToolBox/Editors/TextureEditor.cpp set(ENGINE_PRECOMPILED_HEADERS Utils/PCH/PCH.h) -if("${CMAKE_PLATFORM}" STREQUAL "WINDOWS") +if(DE_PLATFORM STREQUAL "WINDOWS") set(PLATFORM_SOURCES Platform/Windows/Utils/Debug/StackTrace.cpp Platform/Windows/Utils/Debug/Demangler.cpp Platform/Windows/Core/Scripting/SharedObject.cpp ) endif() -if("${CMAKE_PLATFORM}" STREQUAL "LINUX") +if(DE_PLATFORM STREQUAL "LINUX") set(PLATFORM_SOURCES Platform/Linux/Utils/Debug/StackTrace.cpp Platform/Linux/Utils/Debug/Demangler.cpp Platform/Linux/Core/Scripting/SharedObject.cpp ) endif() -if("${CMAKE_PLATFORM}" STREQUAL "MACOS") +if(DE_PLATFORM STREQUAL "MACOS") set(PLATFORM_SOURCES Platform/Macos/Utils/Debug/StackTrace.cpp Platform/Macos/Utils/Debug/Demangler.cpp diff --git a/Examples/Test.cpp b/Examples/Test.cpp index d6e965e..d0cec7d 100644 --- a/Examples/Test.cpp +++ b/Examples/Test.cpp @@ -1,10 +1,10 @@ -#include "DummyEngine/DummyEngine.h" - -using namespace DummyEngine; +#include int main() { - freopen("output.txt", "w", stdout); for (size_t i = 0; i < 100; ++i) { - std::cout << (std::string)UUID::Generate() << std::endl; + int* a = new int(); + *a = 1; + delete a; + std::cout << *a << std::endl; } } \ No newline at end of file From d3a43f6a8150faae1333edf9e694a5b8d1827a88 Mon Sep 17 00:00:00 2001 From: Mag1str0 Date: Fri, 22 Nov 2024 15:48:05 +0300 Subject: [PATCH 13/15] Added memory sanitizer and examples for sanitizers --- .gitignore | 4 + CMake/Compiler.cmake | 13 ++ CMake/Options.cmake | 1 + Examples/CMakeLists.txt | 12 +- Examples/EmptyApplication.cpp | 13 -- Examples/HelloTriangle.cpp | 199 ---------------------------- Examples/ImGuiTest.cpp | 165 ----------------------- Examples/TestASAN.cpp | 10 ++ Examples/{Test.cpp => TestLSAN.cpp} | 1 - Examples/TestMSAN.cpp | 8 ++ Examples/TestTSAN.cpp | 27 ++++ 11 files changed, 67 insertions(+), 386 deletions(-) delete mode 100644 Examples/EmptyApplication.cpp delete mode 100644 Examples/HelloTriangle.cpp delete mode 100644 Examples/ImGuiTest.cpp create mode 100644 Examples/TestASAN.cpp rename Examples/{Test.cpp => TestLSAN.cpp} (90%) create mode 100644 Examples/TestMSAN.cpp create mode 100644 Examples/TestTSAN.cpp diff --git a/.gitignore b/.gitignore index 673c034..b6c975d 100644 --- a/.gitignore +++ b/.gitignore @@ -12,6 +12,10 @@ DummyEngine/Presets Sandbox/imgui.ini Sandbox/DummyEditor +Sandbox/TestASAN +Sandbox/TestLSAN +Sandbox/TestMSAN +Sandbox/TestTSAN Sandbox/Logs/** Sandbox/Cache/** Sandbox/**.dll diff --git a/CMake/Compiler.cmake b/CMake/Compiler.cmake index 3ed7ef2..a34ff8f 100644 --- a/CMake/Compiler.cmake +++ b/CMake/Compiler.cmake @@ -29,6 +29,12 @@ endif() if (DE_ENABLE_ASAN AND DE_ENABLE_TSAN) message(FATAL_ERROR "ASAN and TSAN cannot be used simultaneously") endif() +if (DE_ENABLE_ASAN AND DE_ENABLE_MSAN) + message(FATAL_ERROR "ASAN and MSAN cannot be used simultaneously") +endif() +if (DE_ENABLE_TSAN AND DE_ENABLE_MSAN) + message(FATAL_ERROR "TSAN and MSAN cannot be used simultaneously") +endif() if (DE_ENABLE_UBSAN) add_compile_options(-fsanitize=undefined) add_link_options(-fsanitize=undefined) @@ -44,6 +50,13 @@ if (DE_ENABLE_TSAN) add_compile_options(-fsanitize=thread) add_link_options(-fsanitize=thread) endif() +if (DE_ENABLE_MSAN) + if (DE_PLATFORM STREQUAL "WINDOWS") + message(FATAL_ERROR "Cannot use MSAN on Windows") + endif() + add_compile_options(-fsanitize=memory) + add_link_options(-fsanitize=memory) +endif() # Warnings function(add_warnings TARGET) diff --git a/CMake/Options.cmake b/CMake/Options.cmake index b70adb2..b85b1bc 100644 --- a/CMake/Options.cmake +++ b/CMake/Options.cmake @@ -13,3 +13,4 @@ set_option(DE_FORCE_NO_PCH "Prevent PCH" OFF) set_option(DE_ENABLE_UBSAN "Enable UBSAN" OFF) set_option(DE_ENABLE_ASAN "Enable ASAN" OFF) set_option(DE_ENABLE_TSAN "Enable TSAN" OFF) +set_option(DE_ENABLE_MSAN "Enable MSAN" OFF) diff --git a/Examples/CMakeLists.txt b/Examples/CMakeLists.txt index 3db1029..62e5989 100644 --- a/Examples/CMakeLists.txt +++ b/Examples/CMakeLists.txt @@ -1,9 +1,5 @@ -add_executable(EmptyApplication EmptyApplication.cpp) -add_executable(ImguiTest ImGuiTest.cpp) -add_executable(HelloTriangle HelloTriangle.cpp) -add_executable(Test Test.cpp) -target_link_libraries(EmptyApplication PUBLIC DummyEngineLib) -target_link_libraries(ImguiTest PUBLIC DummyEngineLib) -target_link_libraries(HelloTriangle PUBLIC DummyEngineLib) -target_link_libraries(Test PUBLIC DummyEngineLib) +add_executable(TestASAN TestASAN.cpp) +add_executable(TestTSAN TestTSAN.cpp) +add_executable(TestMSAN TestMSAN.cpp) +add_executable(TestLSAN TestLSAN.cpp) \ No newline at end of file diff --git a/Examples/EmptyApplication.cpp b/Examples/EmptyApplication.cpp deleted file mode 100644 index 8f66eb0..0000000 --- a/Examples/EmptyApplication.cpp +++ /dev/null @@ -1,13 +0,0 @@ -#include "DummyEngine/Core/Application/EntryPoint.h" -#include "DummyEngine/DummyEngine.h" - -class MyLayer : public DummyEngine::Layer { -public: - MyLayer() : DummyEngine::Layer("MyLayer") {} -}; -namespace DummyEngine { - - void SetupApplication() { - Application::PushLayer(new MyLayer()); - } -} // namespace DummyEngine diff --git a/Examples/HelloTriangle.cpp b/Examples/HelloTriangle.cpp deleted file mode 100644 index a19b614..0000000 --- a/Examples/HelloTriangle.cpp +++ /dev/null @@ -1,199 +0,0 @@ -#include "DummyEngine/DummyEngine.h" - -void framebuffer_size_callback(GLFWwindow* window, int width, int height); -void processInput(GLFWwindow* window); - -// settings -const unsigned int SCR_WIDTH = 800; -const unsigned int SCR_HEIGHT = 600; - -const char* vertexShaderSource = - "#version 330 core\n" - "layout (location = 0) in vec3 aPos;\n" - "void main()\n" - "{\n" - " gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0);\n" - "}\0"; -const char* fragmentShaderSource = - "#version 330 core\n" - "out vec4 FragColor;\n" - "void main()\n" - "{\n" - " FragColor = vec4(1.0f, 0.5f, 0.2f, 1.0f);\n" - "}\n\0"; - -int main() { - // glfw: initialize and configure - // ------------------------------ - glfwInit(); - glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); - glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 5); - glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); - -#ifdef __APPLE__ - glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); -#endif - - // glfw window creation - // -------------------- - GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", NULL, NULL); - if (window == NULL) { - std::cout << "Failed to create GLFW window" << std::endl; - glfwTerminate(); - return -1; - } - glfwMakeContextCurrent(window); - glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); - - // glad: load all OpenGL function pointers - // --------------------------------------- - if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { - std::cout << "Failed to initialize GLAD" << std::endl; - return -1; - } - - // build and compile our shader program - // ------------------------------------ - // vertex shader - unsigned int vertexShader = glCreateShader(GL_VERTEX_SHADER); - glShaderSource(vertexShader, 1, &vertexShaderSource, NULL); - glCompileShader(vertexShader); - // check for shader compile errors - int success; - char infoLog[512]; - glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success); - if (!success) { - glGetShaderInfoLog(vertexShader, 512, NULL, infoLog); - std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << std::endl; - } - // fragment shader - unsigned int fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); - glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL); - glCompileShader(fragmentShader); - // check for shader compile errors - glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success); - if (!success) { - glGetShaderInfoLog(fragmentShader, 512, NULL, infoLog); - std::cout << "ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n" << infoLog << std::endl; - } - // link shaders - unsigned int shaderProgram = glCreateProgram(); - glAttachShader(shaderProgram, vertexShader); - glAttachShader(shaderProgram, fragmentShader); - glLinkProgram(shaderProgram); - // check for linking errors - glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success); - if (!success) { - glGetProgramInfoLog(shaderProgram, 512, NULL, infoLog); - std::cout << "ERROR::SHADER::PROGRAM::LINKING_FAILED\n" << infoLog << std::endl; - } - glDeleteShader(vertexShader); - glDeleteShader(fragmentShader); - - // set up vertex data (and buffer(s)) and configure vertex attributes - // ------------------------------------------------------------------ - float vertices[] = { - 0.5f, - 0.5f, - 0.0f, // top right - 0.5f, - -0.5f, - 0.0f, // bottom right - -0.5f, - -0.5f, - 0.0f, // bottom left - -0.5f, - 0.5f, - 0.0f // top left - }; - unsigned int indices[] = { - // note that we start from 0! - 0, - 1, - 3, // first Triangle - 1, - 2, - 3 // second Triangle - }; - unsigned int VBO, VAO, EBO; - glGenVertexArrays(1, &VAO); - glGenBuffers(1, &VBO); - glGenBuffers(1, &EBO); - // bind the Vertex Array Object first, then bind and set vertex buffer(s), and then configure vertex attributes(s). - glBindVertexArray(VAO); - - glBindBuffer(GL_ARRAY_BUFFER, VBO); - glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); - - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); - glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW); - - glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0); - glEnableVertexAttribArray(0); - - // note that this is allowed, the call to glVertexAttribPointer registered VBO as the vertex attribute's bound vertex buffer object so afterwards - // we can safely unbind - glBindBuffer(GL_ARRAY_BUFFER, 0); - - // remember: do NOT unbind the EBO while a VAO is active as the bound element buffer object IS stored in the VAO; keep the EBO bound. - // glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); - - // You can unbind the VAO afterwards so other VAO calls won't accidentally modify this VAO, but this rarely happens. Modifying other - // VAOs requires a call to glBindVertexArray anyways so we generally don't unbind VAOs (nor VBOs) when it's not directly necessary. - glBindVertexArray(0); - - // uncomment this call to draw in wireframe polygons. - // glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); - - // render loop - // ----------- - while (!glfwWindowShouldClose(window)) { - // input - // ----- - processInput(window); - - // render - // ------ - glClearColor(0.0, 0.0, 0.0, 1.0f); - glClear(GL_COLOR_BUFFER_BIT); - - // draw our first triangle - glUseProgram(shaderProgram); - glBindVertexArray( - VAO); // seeing as we only have a single VAO there's no need to bind it every time, but we'll do so to keep things a bit more organized - // glDrawArrays(GL_TRIANGLES, 0, 6); - glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0); - // glBindVertexArray(0); // no need to unbind it every time - - // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.) - // ------------------------------------------------------------------------------- - glfwSwapBuffers(window); - glfwPollEvents(); - } - - // optional: de-allocate all resources once they've outlived their purpose: - // ------------------------------------------------------------------------ - glDeleteVertexArrays(1, &VAO); - glDeleteBuffers(1, &VBO); - glDeleteBuffers(1, &EBO); - glDeleteProgram(shaderProgram); - - // glfw: terminate, clearing all previously allocated GLFW resources. - // ------------------------------------------------------------------ - glfwTerminate(); - return 0; -} - -// process all input: query GLFW whether relevant keys are pressed/released this frame and react accordingly -// --------------------------------------------------------------------------------------------------------- -void processInput(GLFWwindow* window) { - if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) glfwSetWindowShouldClose(window, true); -} - -// glfw: whenever the window size changed (by OS or user resize) this callback function executes -// --------------------------------------------------------------------------------------------- -void framebuffer_size_callback(GLFWwindow* window, int width, int height) { - // make sure the viewport matches the new window dimensions; note that width and - // height will be significantly larger than specified on retina displays. - glViewport(0, 0, width, height); -} \ No newline at end of file diff --git a/Examples/ImGuiTest.cpp b/Examples/ImGuiTest.cpp deleted file mode 100644 index c0b2bcc..0000000 --- a/Examples/ImGuiTest.cpp +++ /dev/null @@ -1,165 +0,0 @@ -// Dear ImGui: standalone example application for GLFW + OpenGL 3, using programmable pipeline -// (GLFW is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan/Metal graphics context creation, etc.) -// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. -// Read online: https://github.com/ocornut/imgui/tree/master/docs - -// clang-format off -#include -#include "imgui.h" -#include "imgui_impl_glfw.h" -#include "imgui_impl_opengl3.h" -#include -#include -#include -// clang-format on - -static void glfw_error_callback(int error, const char* description) { - fprintf(stderr, "Glfw Error %d: %s\n", error, description); -} - -int main(int, char**) { - IM_ASSERT(false); - // Setup window - glfwSetErrorCallback(glfw_error_callback); - if (!glfwInit()) return 1; - - // GL 3.0 + GLSL 130 - const char* glsl_version = "#version 460"; - glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); - glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 6); - glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // 3.2+ only - - // Create window with graphics context - GLFWwindow* window = glfwCreateWindow(1280, 720, "Dear ImGui GLFW+OpenGL3 example", NULL, NULL); - if (window == NULL) return 1; - glfwMakeContextCurrent(window); - glfwSwapInterval(0); // Enable vsync - - if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { - std::cout << "Failed to load GL" << std::endl; - } else { - std::cout << "GL loaded" << std::endl; - } - - // Setup Dear ImGui context - IMGUI_CHECKVERSION(); - ImGui::CreateContext(); - ImGuiIO& io = ImGui::GetIO(); - (void)io; - io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; - io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable; - // io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls - // io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls - - // Setup Dear ImGui style - ImGui::StyleColorsDark(); - // ImGui::StyleColorsLight(); - - // Setup Platform/Renderer backends - std::cout << ImGui_ImplGlfw_InitForOpenGL(window, true) << std::endl; - std::cout << ImGui_ImplOpenGL3_Init(glsl_version) << std::endl; - - // Load Fonts - // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select - // them. - // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. - // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or - // display an error and quit). - // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling - // ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. - // - Read 'docs/FONTS.md' for more instructions and details. - // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! - // io.Fonts->AddFontDefault(); - // io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); - // io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); - // io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); - // io.Fonts->AddFontFromFileTTF("../../misc/fonts/ProggyTiny.ttf", 10.0f); - // ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese()); - // IM_ASSERT(font != NULL); - - // Our state - bool show_demo_window = true; - bool show_another_window = false; - ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f); - glClearColor(clear_color.x, clear_color.y, clear_color.z, clear_color.w); - - // Main loop - while (!glfwWindowShouldClose(window)) { - // Poll and handle events (inputs, window resize, etc.) - // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs. - // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse - // data. - // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the - // keyboard data. Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. - glfwPollEvents(); - - // Start the Dear ImGui frame - ImGui_ImplOpenGL3_NewFrame(); - ImGui_ImplGlfw_NewFrame(); - ImGui::NewFrame(); - - // ImGui::DockSpaceOverViewport(ImGui::GetMainViewport()); - // 1. Show the big demo window (Most of the sample code is in ImGui::ShowDemoWindow()! You can browse its code to learn more about Dear - // ImGui!). - if (show_demo_window) ImGui::ShowDemoWindow(&show_demo_window); - - // 2. Show a simple window that we create ourselves. We use a Begin/End pair to created a named window. - { - static float f = 0.0f; - static int counter = 0; - - ImGui::Begin("Hello, world!"); // Create a window called "Hello, world!" and append into it. - - ImGui::Text("This is some useful text."); // Display some text (you can use a format strings too) - ImGui::Checkbox("Demo Window", &show_demo_window); // Edit bools storing our window open/close state - ImGui::Checkbox("Another Window", &show_another_window); - - ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f - ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color - - if (ImGui::Button("Button")) // Buttons return true when clicked (most widgets return true whenedited/activated) - counter++; - ImGui::SameLine(); - ImGui::Text("counter = %d", counter); - - ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); - ImGui::End(); - } - - // 3. Show another simple window. - if (show_another_window) { - ImGui::Begin("Another Window", &show_another_window); // Pass a pointer to our bool variable (the window will have a closing buttonthat - // will clear the bool when clicked) - ImGui::Text("Hello from another window!"); - if (ImGui::Button("Close Me")) show_another_window = false; - ImGui::End(); - } - - // Rendering - ImGui::Render(); - int display_w, display_h; - glfwGetFramebufferSize(window, &display_w, &display_h); - glViewport(0, 0, display_w, display_h); - glClearColor(clear_color.x * clear_color.w, clear_color.y * clear_color.w, clear_color.z * clear_color.w, clear_color.w); - glClear(GL_COLOR_BUFFER_BIT); - ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); - if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) { - GLFWwindow* backup_current_context = glfwGetCurrentContext(); - ImGui::UpdatePlatformWindows(); - ImGui::RenderPlatformWindowsDefault(); - glfwMakeContextCurrent(backup_current_context); - } - - glfwSwapBuffers(window); - } - - // Cleanup - ImGui_ImplOpenGL3_Shutdown(); - ImGui_ImplGlfw_Shutdown(); - ImGui::DestroyContext(); - - glfwDestroyWindow(window); - glfwTerminate(); - - return 0; -} diff --git a/Examples/TestASAN.cpp b/Examples/TestASAN.cpp new file mode 100644 index 0000000..e91c3a8 --- /dev/null +++ b/Examples/TestASAN.cpp @@ -0,0 +1,10 @@ +#include + +int main() { + for (size_t i = 0; i < 10; ++i) { + int* a = new int(); + *a = 1; + delete a; + std::cout << *a << std::endl; + } +} \ No newline at end of file diff --git a/Examples/Test.cpp b/Examples/TestLSAN.cpp similarity index 90% rename from Examples/Test.cpp rename to Examples/TestLSAN.cpp index d0cec7d..5964c8c 100644 --- a/Examples/Test.cpp +++ b/Examples/TestLSAN.cpp @@ -4,7 +4,6 @@ int main() { for (size_t i = 0; i < 100; ++i) { int* a = new int(); *a = 1; - delete a; std::cout << *a << std::endl; } } \ No newline at end of file diff --git a/Examples/TestMSAN.cpp b/Examples/TestMSAN.cpp new file mode 100644 index 0000000..13bd882 --- /dev/null +++ b/Examples/TestMSAN.cpp @@ -0,0 +1,8 @@ +#include + +int main() { + int a[10]; + for (size_t i = 0; i < 10; ++i) { + std::cout << a[i] << std::endl; + } +} \ No newline at end of file diff --git a/Examples/TestTSAN.cpp b/Examples/TestTSAN.cpp new file mode 100644 index 0000000..2398f5f --- /dev/null +++ b/Examples/TestTSAN.cpp @@ -0,0 +1,27 @@ +#include +#include + +int main() { + using namespace std::literals::chrono_literals; + + std::atomic stop = false; + int a = 0; + std::thread t1([&]() { + do { + for (size_t i = 0; i < 100000; ++i) { + a = i; + } + } while (!stop.load()); + }); + std::thread t2([&]() { + do { + for (size_t i = 0; i < 100000; ++i) { + a = i; + } + } while (!stop.load()); + }); + std::this_thread::sleep_for(5s); + stop.store(true); + t1.join(); + t2.join(); +} \ No newline at end of file From 939902b0e6cb55053da343aa113858f04ff1c1fa Mon Sep 17 00:00:00 2001 From: Mag1str0 Date: Fri, 22 Nov 2024 18:18:27 +0300 Subject: [PATCH 14/15] Added cmake-variants --- CMake/Compiler.cmake | 2 +- CMake/Options.cmake | 6 +- DummyEditor/CMakeLists.txt | 3 +- .../Platform/Linux/Scripting/Compiler.cpp | 2 +- DummyEngine/CMakeLists.txt | 8 +- .../Core/Rendering/Renderer/LocalBuffer.cpp | 2 +- cmake-variants.yaml | 81 +++++++++++++++++++ 7 files changed, 96 insertions(+), 8 deletions(-) create mode 100644 cmake-variants.yaml diff --git a/CMake/Compiler.cmake b/CMake/Compiler.cmake index a34ff8f..ab97595 100644 --- a/CMake/Compiler.cmake +++ b/CMake/Compiler.cmake @@ -16,7 +16,7 @@ if (${DE_FORCE_NO_PCH}) endif() # Clang Tidy -if(DE_ENABLE_CLANG_TIDY_ON_COMPILATION) +if(DE_CLANG_TIDY_RUN_ON_COMPILATION) find_program(CLANG_TIDY_EXE NAMES "clang-tidy" "clang-tidy-17" "clang-tidy-18" "clang-tidy-19" REQUIRED) set(CLANG_TIDY_COMMAND "${CLANG_TIDY_EXE}" "-p" "${CMAKE_CURRENT_SOURCE_DIR}/build") if (DE_CLANG_TIDY_WARNINGS_AS_ERRORS) diff --git a/CMake/Options.cmake b/CMake/Options.cmake index b85b1bc..e13d639 100644 --- a/CMake/Options.cmake +++ b/CMake/Options.cmake @@ -7,10 +7,14 @@ macro(set_option option help value) endif() endmacro() -set_option(DE_ENABLE_CLANG_TIDY_ON_COMPILATION "Run clang tidy during compilation" OFF) + +message(STATUS "---Confiring-Project-Options-----------------------------------------------------------------") +set_option(DE_FORMAT_BEFORE_BUILD "Runs clang-format on DummyEngine and DummyEditor before build" OFF) +set_option(DE_CLANG_TIDY_RUN_ON_COMPILATION "Run clang tidy during compilation" OFF) set_option(DE_CLANG_TIDY_WARNINGS_AS_ERRORS "Set clang warnings as errors" OFF) set_option(DE_FORCE_NO_PCH "Prevent PCH" OFF) set_option(DE_ENABLE_UBSAN "Enable UBSAN" OFF) set_option(DE_ENABLE_ASAN "Enable ASAN" OFF) set_option(DE_ENABLE_TSAN "Enable TSAN" OFF) set_option(DE_ENABLE_MSAN "Enable MSAN" OFF) +message(STATUS "---Confired-Project-Options------------------------------------------------------------------") diff --git a/DummyEditor/CMakeLists.txt b/DummyEditor/CMakeLists.txt index b2a40d1..70d131c 100644 --- a/DummyEditor/CMakeLists.txt +++ b/DummyEditor/CMakeLists.txt @@ -15,7 +15,8 @@ add_dependencies(DummyEditor DummyEditorScripts) if (${ENABLE_PRECOMPILED_HEADERS}) target_precompile_headers(DummyEditor REUSE_FROM DummyEngineLib) + target_precompile_headers(DummyEditorScripts REUSE_FROM DummyEngineLib) endif() -if (${DE_ENABLE_CLANG_TIDY_ON_COMPILATION}) +if (${DE_CLANG_TIDY_RUN_ON_COMPILATION}) set_target_properties(DummyEditor PROPERTIES CXX_CLANG_TIDY "${CLANG_TIDY_COMMAND}") endif() \ No newline at end of file diff --git a/DummyEditor/Platform/Linux/Scripting/Compiler.cpp b/DummyEditor/Platform/Linux/Scripting/Compiler.cpp index ea206b5..e0f6bdf 100644 --- a/DummyEditor/Platform/Linux/Scripting/Compiler.cpp +++ b/DummyEditor/Platform/Linux/Scripting/Compiler.cpp @@ -23,7 +23,7 @@ namespace DummyEngine { std::string compile_command; compile_command.append(GetCompiler()); - compile_command.append(" -c -std=c++20"); + compile_command.append(" -c -std=c++20 -stdlib=libc++"); compile_command.append(" -fPIC "); compile_command.append(AddDefines()); compile_command.append(AddIncludeDirArguments()); diff --git a/DummyEngine/CMakeLists.txt b/DummyEngine/CMakeLists.txt index 48f9674..c124b34 100644 --- a/DummyEngine/CMakeLists.txt +++ b/DummyEngine/CMakeLists.txt @@ -17,13 +17,15 @@ target_compile_definitions(DummyEngineLib PUBLIC target_include_directories(DummyEngineLib PUBLIC ../.) add_warnings(DummyEngineLib) -if (${ENABLE_PRECOMPILED_HEADERS}) +if (ENABLE_PRECOMPILED_HEADERS) target_precompile_headers(DummyEngineLib PUBLIC ${ENGINE_PRECOMPILED_HEADERS}) endif() -if (${DE_ENABLE_CLANG_TIDY_ON_COMPILATION}) +if (DE_CLANG_TIDY_RUN_ON_COMPILATION) set_target_properties(DummyEngineLib PROPERTIES CXX_CLANG_TIDY "${CLANG_TIDY_COMMAND}") endif() - if (DE_PLATFORM STREQUAL "WINDOWS") target_compile_definitions(DummyEngineLib PUBLIC YAML_CPP_STATIC_DEFINE) +endif() +if (DE_FORMAT_BEFORE_BUILD) + add_dependencies(DummyEngineLib FormatAll) endif() \ No newline at end of file diff --git a/DummyEngine/Core/Rendering/Renderer/LocalBuffer.cpp b/DummyEngine/Core/Rendering/Renderer/LocalBuffer.cpp index 07fee3a..655faed 100644 --- a/DummyEngine/Core/Rendering/Renderer/LocalBuffer.cpp +++ b/DummyEngine/Core/Rendering/Renderer/LocalBuffer.cpp @@ -34,7 +34,7 @@ namespace DummyEngine { } void LocalBuffer::Allocate(U32 size) { if (data_ != nullptr) { - delete[] data_; + free(data_); } data_ = (U8*)malloc(size); size_ = size; diff --git a/cmake-variants.yaml b/cmake-variants.yaml new file mode 100644 index 0000000..062be55 --- /dev/null +++ b/cmake-variants.yaml @@ -0,0 +1,81 @@ +buildType: + default: Release + choices: + Release: + short: Release + long: Main development build type with optimized code and debug info + buildType: ReleaseWithDebInfo + settings: + DE_FORMAT_BEFORE_BUILD: OFF + DE_CLANG_TIDY_RUN_ON_COMPILATION: OFF + DE_CLANG_TIDY_WARNINGS_AS_ERRORS: OFF + DE_FORCE_NO_PCH: OFF + DE_ENABLE_UBSAN: OFF + DE_ENABLE_ASAN: OFF + DE_ENABLE_MSAN: OFF + DE_ENABLE_TSAN: OFF + Debug: + short: Debug + long: Debug build type + buildType: Debug + settings: + DE_FORMAT_BEFORE_BUILD: OFF + DE_CLANG_TIDY_RUN_ON_COMPILATION: OFF + DE_CLANG_TIDY_WARNINGS_AS_ERRORS: OFF + DE_FORCE_NO_PCH: OFF + DE_ENABLE_UBSAN: OFF + DE_ENABLE_ASAN: OFF + DE_ENABLE_MSAN: OFF + DE_ENABLE_TSAN: OFF + ReleaseTSAN: + short: ReleaseTSAN + long: Optimized code with TSAN + buildType: ReleaseWithDebInfo + settings: + DE_FORMAT_BEFORE_BUILD: OFF + DE_CLANG_TIDY_RUN_ON_COMPILATION: OFF + DE_CLANG_TIDY_WARNINGS_AS_ERRORS: OFF + DE_FORCE_NO_PCH: OFF + DE_ENABLE_UBSAN: ON + DE_ENABLE_ASAN: OFF + DE_ENABLE_MSAN: OFF + DE_ENABLE_TSAN: ON + ReleaseASAN: + short: ReleaseASAN + long: Optimized code with ASAN + buildType: ReleaseWithDebInfo + settings: + DE_FORMAT_BEFORE_BUILD: OFF + DE_CLANG_TIDY_RUN_ON_COMPILATION: OFF + DE_CLANG_TIDY_WARNINGS_AS_ERRORS: OFF + DE_FORCE_NO_PCH: OFF + DE_ENABLE_UBSAN: ON + DE_ENABLE_ASAN: ON + DE_ENABLE_MSAN: OFF + DE_ENABLE_TSAN: OFF + ReleaseMSAN: + short: ReleaseMSAN + long: Optimized code with MSAN + buildType: ReleaseWithDebInfo + settings: + DE_FORMAT_BEFORE_BUILD: OFF + DE_CLANG_TIDY_RUN_ON_COMPILATION: OFF + DE_CLANG_TIDY_WARNINGS_AS_ERRORS: OFF + DE_FORCE_NO_PCH: OFF + DE_ENABLE_UBSAN: ON + DE_ENABLE_ASAN: OFF + DE_ENABLE_MSAN: ON + DE_ENABLE_TSAN: OFF + ReleaseTidy: + short: ReleaseTidy + long: Runs clang-format before build, forces no PCH and runs clang-tidy checks + buildType: ReleaseWithDebInfo + settings: + DE_FORMAT_BEFORE_BUILD: ON + DE_CLANG_TIDY_RUN_ON_COMPILATION: ON + DE_CLANG_TIDY_WARNINGS_AS_ERRORS: ON + DE_FORCE_NO_PCH: ON + DE_ENABLE_UBSAN: OFF + DE_ENABLE_ASAN: OFF + DE_ENABLE_MSAN: OFF + DE_ENABLE_TSAN: OFF From 8417c8fac941525f6768ccb67224a1faa83900b6 Mon Sep 17 00:00:00 2001 From: Mag1str02 Date: Fri, 22 Nov 2024 18:37:58 +0300 Subject: [PATCH 15/15] Restored old script field names --- DummyEditor/EditorLayer.cpp | 2 +- DummyEditor/Scripts/EditorCameraController.cpp | 2 +- DummyEngine/Core/Scripting/Script.h | 4 ++-- Sandbox/Assets/Scripts/BasicScripts/SquareMovement.cpp | 7 ++++++- Sandbox/Assets/Scripts/Gate/GateController.cpp | 7 ++++++- Sandbox/Assets/Scripts/Gate/SinMovement.cpp | 2 +- Sandbox/Assets/Scripts/Grass/Grass.cpp | 2 +- Sandbox/Assets/Scripts/Sky/SkyController.cpp | 2 +- 8 files changed, 19 insertions(+), 9 deletions(-) diff --git a/DummyEditor/EditorLayer.cpp b/DummyEditor/EditorLayer.cpp index d8d5d23..3ffe718 100644 --- a/DummyEditor/EditorLayer.cpp +++ b/DummyEditor/EditorLayer.cpp @@ -340,7 +340,7 @@ namespace DummyEngine { } } if (editor_camera_.Valid()) { - bool& active = editor_camera_.Get()->GetField("active_"); + bool& active = editor_camera_.Get()->GetField("Active"); if (input_state_ == InputState::ViewPort) { active = true; } else { diff --git a/DummyEditor/Scripts/EditorCameraController.cpp b/DummyEditor/Scripts/EditorCameraController.cpp index a4e25dc..d471f8b 100644 --- a/DummyEditor/Scripts/EditorCameraController.cpp +++ b/DummyEditor/Scripts/EditorCameraController.cpp @@ -46,4 +46,4 @@ class EditorCameraController : public Script { bool active_ = false; }; -SCRIPT_BASE(EditorCameraController, FIELD(active_)) +SCRIPT_BASE(EditorCameraController, FIELD("Active", active_)) diff --git a/DummyEngine/Core/Scripting/Script.h b/DummyEngine/Core/Scripting/Script.h index a3f9d17..76dd24e 100644 --- a/DummyEngine/Core/Scripting/Script.h +++ b/DummyEngine/Core/Scripting/Script.h @@ -147,9 +147,9 @@ namespace DummyEngine { m_Entity.Remove(); } -#define FIELD(field) \ +#define FIELD(field_name, field) \ { \ - #field, { \ + field_name, { \ TypeToScriptFieldType(), OffsetOf(&CurrentScriptType::field) \ } \ } diff --git a/Sandbox/Assets/Scripts/BasicScripts/SquareMovement.cpp b/Sandbox/Assets/Scripts/BasicScripts/SquareMovement.cpp index a688edc..11e1031 100644 --- a/Sandbox/Assets/Scripts/BasicScripts/SquareMovement.cpp +++ b/Sandbox/Assets/Scripts/BasicScripts/SquareMovement.cpp @@ -31,4 +31,9 @@ class SquareMovement : public Script { Vec2 right_front_ = {0.0, 0.0}; }; -SCRIPT_BASE(SquareMovement, FIELD(cycle_time_), FIELD(height_), FIELD(offset_), FIELD(left_back_), FIELD(right_front_)) +SCRIPT_BASE(SquareMovement, + FIELD("CycleTime", cycle_time_), + FIELD("Height", height_), + FIELD("Offset", offset_), + FIELD("LeftBack", left_back_), + FIELD("RightFront", right_front_)) diff --git a/Sandbox/Assets/Scripts/Gate/GateController.cpp b/Sandbox/Assets/Scripts/Gate/GateController.cpp index 755d81b..b04b299 100644 --- a/Sandbox/Assets/Scripts/Gate/GateController.cpp +++ b/Sandbox/Assets/Scripts/Gate/GateController.cpp @@ -48,4 +48,9 @@ class GateController : public Script { Entity controller_; }; -SCRIPT_BASE(GateController, FIELD(speed_), FIELD(distance_), FIELD(open_height_), FIELD(close_height_), FIELD(controller_)) +SCRIPT_BASE(GateController, + FIELD("Speed", speed_), + FIELD("Distance", distance_), + FIELD("OpenHeight", open_height_), + FIELD("CloseHeight", close_height_), + FIELD("Controller", controller_)) diff --git a/Sandbox/Assets/Scripts/Gate/SinMovement.cpp b/Sandbox/Assets/Scripts/Gate/SinMovement.cpp index b02108c..a56dddf 100644 --- a/Sandbox/Assets/Scripts/Gate/SinMovement.cpp +++ b/Sandbox/Assets/Scripts/Gate/SinMovement.cpp @@ -21,4 +21,4 @@ class SinMovement : public Script { float current_time_ = 0; }; -SCRIPT_BASE(SinMovement, FIELD(pos_a_), FIELD(pos_b_), FIELD(speed_)) +SCRIPT_BASE(SinMovement, FIELD("PosA", pos_a_), FIELD("PosB", pos_b_), FIELD("Speed", speed_)) diff --git a/Sandbox/Assets/Scripts/Grass/Grass.cpp b/Sandbox/Assets/Scripts/Grass/Grass.cpp index 7b2eb77..d9a51e3 100644 --- a/Sandbox/Assets/Scripts/Grass/Grass.cpp +++ b/Sandbox/Assets/Scripts/Grass/Grass.cpp @@ -53,4 +53,4 @@ class Grass : public Script { Ref shader_; }; -SCRIPT_BASE(Grass, FIELD(camera_), FIELD(speed_)) +SCRIPT_BASE(Grass, FIELD("Camera", camera_), FIELD("Speed", speed_)) diff --git a/Sandbox/Assets/Scripts/Sky/SkyController.cpp b/Sandbox/Assets/Scripts/Sky/SkyController.cpp index 45d3ff1..4bdd998 100644 --- a/Sandbox/Assets/Scripts/Sky/SkyController.cpp +++ b/Sandbox/Assets/Scripts/Sky/SkyController.cpp @@ -32,4 +32,4 @@ class SkyContoller : public Script { float current_time_ = 0; }; -SCRIPT_BASE(SkyContoller, FIELD(rotation_speed_)) +SCRIPT_BASE(SkyContoller, FIELD("RotationSpeed", rotation_speed_))