diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 2d31cf9e7..8b11197f0 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -31,6 +31,17 @@ env: RUN_TESTS: true jobs: + feature-index: + runs-on: ubuntu-24.04 + name: Check feature index + + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Check that wiki/Features.md lists all features + run: python3 wiki/check_features.py + windows-build: runs-on: windows-2022 name: Build on Windows @@ -62,7 +73,7 @@ jobs: uses: friendlyanon/setup-vcpkg@v1 # Committish: The commit sha of the vcpkg repo, same as in vcpkg.json with: - committish: d3a1e8c161275780ebf2eebd8c6b70d9fabc0a19 + committish: d186940b2f0c4e8e5b4ff804af57d2a26fbfa091 cache: ${{ env.USE_CACHE }} # This doesn't work when the Visual Studio C++ CLI was set up first (maybe needs a setup with 2019 version) @@ -138,7 +149,7 @@ jobs: cc: "cl" cxx: "cl" configure-options: -DCMAKE_TOOLCHAIN_FILE='${{ github.workspace }}/vcpkg/scripts/buildsystems/vcpkg.cmake' - -DATLAS_TESTS=ON -DATLAS_BINDLESS=OFF -DATLAS_EDITOR=OFF -DATLAS_HEADLESS=ON -G Ninja + -DATLAS_TESTS=ON -DATLAS_EDITOR=OFF -DATLAS_HEADLESS=ON -G Ninja parallel: 16 build-type: ${{ matrix.build-type }} @@ -206,7 +217,7 @@ jobs: uses: friendlyanon/setup-vcpkg@v1 # Committish: The commit sha of the vcpkg repo, same as in vcpkg.json with: - committish: d3a1e8c161275780ebf2eebd8c6b70d9fabc0a19 + committish: d186940b2f0c4e8e5b4ff804af57d2a26fbfa091 cache: ${{ env.USE_CACHE }} - name: Setup Ninja @@ -274,7 +285,7 @@ jobs: cc: "gcc" cxx: "g++" configure-options: -DCMAKE_TOOLCHAIN_FILE='${{ github.workspace }}/vcpkg/scripts/buildsystems/vcpkg.cmake' - -DATLAS_TESTS=ON -DATLAS_BINDLESS=OFF -DATLAS_EDITOR=OFF -DATLAS_HEADLESS=ON -G Ninja + -DATLAS_TESTS=ON -DATLAS_EDITOR=OFF -DATLAS_HEADLESS=ON -G Ninja parallel: 16 build-type: ${{ matrix.build-type }} @@ -339,7 +350,7 @@ jobs: uses: friendlyanon/setup-vcpkg@v1 # Committish: The commit sha of the vcpkg repo, same as in vcpkg.json with: - committish: d3a1e8c161275780ebf2eebd8c6b70d9fabc0a19 + committish: d186940b2f0c4e8e5b4ff804af57d2a26fbfa091 cache: ${{ env.USE_CACHE }} - name: Setup Ninja @@ -429,7 +440,7 @@ jobs: cc: "clang" cxx: "clang++" configure-options: -DCMAKE_TOOLCHAIN_FILE='${{ github.workspace }}/vcpkg/scripts/buildsystems/vcpkg.cmake' - -DATLAS_TESTS=ON -DATLAS_BINDLESS=OFF -DATLAS_EDITOR=OFF -DATLAS_BUNDLE=ON -DATLAS_HEADLESS=ON -G Ninja + -DATLAS_TESTS=ON -DATLAS_EDITOR=OFF -DATLAS_BUNDLE=ON -DATLAS_HEADLESS=ON -G Ninja parallel: 16 build-type: ${{ matrix.build-type }} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index cd80630eb..9f083e352 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -31,7 +31,7 @@ jobs: uses: friendlyanon/setup-vcpkg@v1 # Committish: The commit sha of the vcpkg repo, same as in vcpkg.json with: - committish: d3a1e8c161275780ebf2eebd8c6b70d9fabc0a19 + committish: d186940b2f0c4e8e5b4ff804af57d2a26fbfa091 - name: Delete MSVC tool version shell: pwsh @@ -110,7 +110,7 @@ jobs: uses: friendlyanon/setup-vcpkg@v1 # Committish: The commit sha of the vcpkg repo, same as in vcpkg.json with: - committish: d3a1e8c161275780ebf2eebd8c6b70d9fabc0a19 + committish: d186940b2f0c4e8e5b4ff804af57d2a26fbfa091 - name: Setup Ninja uses: ashutoshvarma/setup-ninja@master @@ -178,7 +178,7 @@ jobs: uses: friendlyanon/setup-vcpkg@v1 # Committish: The commit sha of the vcpkg repo, same as in vcpkg.json with: - committish: d3a1e8c161275780ebf2eebd8c6b70d9fabc0a19 + committish: d186940b2f0c4e8e5b4ff804af57d2a26fbfa091 cache: ${{ env.USE_CACHE }} - name: Setup Ninja diff --git a/.gitignore b/.gitignore index e6080f1e6..de231aef0 100644 --- a/.gitignore +++ b/.gitignore @@ -6,6 +6,8 @@ # Project files !/.gitattributes !/.gitignore +!/.mcp.json +!/AtlasEngine.aeproject !/CMakeLists.txt !/Doxyfile !/LICENSE.md @@ -18,8 +20,12 @@ !/.github/ !/libs/ !/src/ +!/templates/ !/wiki/ +# Vendor SDKs of the optional upscalers are downloaded separately (see libs/upscalers/README.md) +/libs/upscalers/*/sdk/ + # data/: engine assets only. The large sample asset folders are downloaded separately (see data/README.md) !/data/ /data/* @@ -33,6 +39,16 @@ !/data/shader/ !/data/sponza/ +# Import output stays local, only these default assets are tracked +/data/materials/* +!/data/materials/CapsuleMaterial.aematerial +!/data/materials/Chrome.aematerial +!/data/materials/Material.001.aematerial +/data/meshes/* +!/data/meshes/capsule.aemesh +!/data/meshes/chromesphere.aemesh +!/data/meshes/metallicwall.aemesh + !/data/README.md !/data/capsule.gltf !/data/chromesphere.bin @@ -71,3 +87,4 @@ __pycache__/ local.properties CMakeSettings.json CMakeUserPresets.json +src/bridge/examples diff --git a/.mcp.json b/.mcp.json new file mode 100644 index 000000000..e1afdf714 --- /dev/null +++ b/.mcp.json @@ -0,0 +1,8 @@ +{ + "mcpServers": { + "atlas": { + "type": "http", + "url": "http://127.0.0.1:7777/mcp" + } + } +} diff --git a/AtlasEngine.aeproject b/AtlasEngine.aeproject new file mode 100644 index 000000000..f41ac5565 --- /dev/null +++ b/AtlasEngine.aeproject @@ -0,0 +1,6 @@ +{ + "name": "Atlas Engine", + "assetDirectory": "data", + "mainScript": "", + "startScene": "scenes/sponza.aescene" +} diff --git a/CMakeLists.txt b/CMakeLists.txt index 2a25207ea..8f2096dc1 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -14,6 +14,8 @@ endif(COMMAND cmake_policy) cmake_minimum_required(VERSION 3.25) project(AtlasEngine VERSION 0.2.1) +# The engine library has its own project() call, which clears PROJECT_VERSION +set(ATLAS_ENGINE_VERSION ${PROJECT_VERSION}) # Only 64 bit is supported ################################################################### @@ -27,11 +29,13 @@ option(ATLAS_EXPORT_MAIN "Add main file in root of directory tree. Add ${ATLAS_E option(ATLAS_NO_APP "Disables the engines main function" OFF) option(ATLAS_DEMO "Build demo executable" OFF) option(ATLAS_EDITOR "Build editor executable" ON) +option(ATLAS_BRIDGE "Build the Atlas Bridge executable, the scene capture and inspection tool" OFF) +option(ATLAS_BRIDGE_LIBRARY "Build only the bridge library, for game hosts that run bridge jobs" OFF) option(ATLAS_IMGUI "Activate ImGui integration" OFF) option(ATLAS_ASSIMP "Activate Assimp integration" ON) option(ATLAS_HEADLESS "Activate support for running the engine in headless mode" OFF) -option(ATLAS_BINDLESS "Activate support for running the engine with bindless resources turned on" ON) option(ATLAS_BUNDLE "Allows the applications to be bundled and installed on MacOS" OFF) +option(ATLAS_LUA_SAFETIES "Check the arguments of Lua binding calls, wrong ones raise Lua errors instead of crashing" ON) option(ATLAS_MSVC_HOT_RELOAD "Configures all targets to be hot-reloadable" OFF) if(${CMAKE_CURRENT_SOURCE_DIR} STREQUAL ${CMAKE_BINARY_DIR}) @@ -72,23 +76,24 @@ endif() if (ATLAS_DEMO) set(ATLAS_EXPORT_MAIN ON CACHE BOOL "Override engine settings" FORCE) endif() +if (ATLAS_BRIDGE) +set(ATLAS_EXPORT_MAIN ON CACHE BOOL "Override engine settings" FORCE) +endif() # Set dependencies location ####################################################################### set (ATLAS_LOCATION ${CMAKE_CURRENT_SOURCE_DIR}/src/engine) set (DEMO_LOCATION ${CMAKE_CURRENT_SOURCE_DIR}/src/demo) set (TESTS_LOCATION ${CMAKE_CURRENT_SOURCE_DIR}/src/tests) set (EDITOR_LOCATION ${CMAKE_CURRENT_SOURCE_DIR}/src/editor) +set (BRIDGE_LOCATION ${CMAKE_CURRENT_SOURCE_DIR}/src/bridge) set (IMGUI_EXTENSION_LOCATION ${CMAKE_CURRENT_SOURCE_DIR}/libs/ImguiExtension) # Add dependencies ################################################################################ -find_package(SDL2 CONFIG REQUIRED) +find_package(SDL3 CONFIG REQUIRED) if(ATLAS_ASSIMP) find_package(assimp CONFIG REQUIRED) endif() -if (ANDROID) - add_subdirectory(${HIDAPI_LOCATION}) -endif() find_package(unofficial-spirv-reflect CONFIG REQUIRED) find_package(Vulkan REQUIRED) @@ -100,6 +105,9 @@ find_package(SPIRV-Tools-opt CONFIG REQUIRED) find_package(nlohmann_json CONFIG REQUIRED) find_package(Jolt CONFIG REQUIRED) find_package(Lua REQUIRED) +find_package(Ktx CONFIG REQUIRED) +find_package(recastnavigation CONFIG REQUIRED) +find_package(meshoptimizer CONFIG REQUIRED) if (ATLAS_TESTS) find_package(GTest CONFIG REQUIRED) @@ -121,6 +129,11 @@ if (ATLAS_EDITOR) add_subdirectory(${EDITOR_LOCATION}) endif() +# The editor runs the commands of the bridge in the open scene +if (ATLAS_BRIDGE OR ATLAS_BRIDGE_LIBRARY OR ATLAS_EDITOR) + add_subdirectory(${BRIDGE_LOCATION}) +endif() + if (ATLAS_TESTS) add_subdirectory(${TESTS_LOCATION}) endif() diff --git a/README.md b/README.md index e5cdcbaaf..04f8422aa 100644 --- a/README.md +++ b/README.md @@ -55,11 +55,11 @@ initialize the engine yourself - **ATLAS_IMGUI** Enables the [ImGui](https://github.com/ocornut/imgui) integration. Is enabled by default if the demo project is build. - **ATLAS_ASSIMP** Enables the [Assimp](https://github.com/assimp/assimp) integration. Is enabled by default. - **ATLAS_HEADLESS** Enables the headless support, which means no window needs to be created. Is disabled by default. -- **ATLAS_BINDLESS** Enables support for bindless resources. Might be problematic on MacOS. Enabled by default. - **ATLAS_TESTS** Generates the testing project and allows to target it. - **ATLAS_BUNDLE** Allows the applications to be bundled and installed on MacOS. Disabled by default ## Documentation If you want more information have a look into the [Documentation](https://tippesi.github.io/Atlas-Engine-Doc/index.html). +To let an agent (Claude Code, Codex, ChatGPT, ...) work in the scene open in the editor, see [Atlas Bridge](wiki/AtlasBridge.md). ## License The source code is licensed under the MIT license. The copyright notices of the dependencies can be found in the LICENSE.md file in the dependency directory. diff --git a/THIRDPARTY.md b/THIRDPARTY.md index 0964aa752..52c9d66ae 100644 --- a/THIRDPARTY.md +++ b/THIRDPARTY.md @@ -322,6 +322,25 @@ JoltPhysics THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +KTX-Software +-------------------------------------------------------------------------------- + Copyright 2013-2020 Mark Callow and The Khronos Group Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Includes the Basis Universal transcoder (Copyright 2019-2021 Binomial LLC, Apache-2.0) + and links zstd (Copyright (c) Meta Platforms, Inc. and affiliates, BSD-3-Clause). + spirv-reflect -------------------------------------------------------------------------------- Apache License diff --git a/data/editor/icons/cancel.png b/data/editor/icons/cancel.png new file mode 100644 index 000000000..40216068f Binary files /dev/null and b/data/editor/icons/cancel.png differ diff --git a/data/editor/icons/cancel.svg b/data/editor/icons/cancel.svg new file mode 100644 index 000000000..8504fbfda --- /dev/null +++ b/data/editor/icons/cancel.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/data/editor/icons/cancel_light.png b/data/editor/icons/cancel_light.png new file mode 100644 index 000000000..15d6db4c8 Binary files /dev/null and b/data/editor/icons/cancel_light.png differ diff --git a/data/editor/icons/clouds.png b/data/editor/icons/clouds.png new file mode 100644 index 000000000..a2f8cdbb3 Binary files /dev/null and b/data/editor/icons/clouds.png differ diff --git a/data/editor/icons/clouds.svg b/data/editor/icons/clouds.svg new file mode 100644 index 000000000..a36bddda9 --- /dev/null +++ b/data/editor/icons/clouds.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/data/editor/icons/clouds_light.png b/data/editor/icons/clouds_light.png new file mode 100644 index 000000000..a86f413e5 Binary files /dev/null and b/data/editor/icons/clouds_light.png differ diff --git a/data/editor/icons/error.png b/data/editor/icons/error.png new file mode 100644 index 000000000..3f2270083 Binary files /dev/null and b/data/editor/icons/error.png differ diff --git a/data/editor/icons/error.svg b/data/editor/icons/error.svg new file mode 100644 index 000000000..9a83c9306 --- /dev/null +++ b/data/editor/icons/error.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/data/editor/icons/error_light.png b/data/editor/icons/error_light.png new file mode 100644 index 000000000..36ab386b6 Binary files /dev/null and b/data/editor/icons/error_light.png differ diff --git a/data/editor/icons/fog.png b/data/editor/icons/fog.png new file mode 100644 index 000000000..794a098ef Binary files /dev/null and b/data/editor/icons/fog.png differ diff --git a/data/editor/icons/fog.svg b/data/editor/icons/fog.svg new file mode 100644 index 000000000..428ea0add --- /dev/null +++ b/data/editor/icons/fog.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/data/editor/icons/fog_light.png b/data/editor/icons/fog_light.png new file mode 100644 index 000000000..2e2c8d3ea Binary files /dev/null and b/data/editor/icons/fog_light.png differ diff --git a/data/editor/icons/globalIllumination.png b/data/editor/icons/globalIllumination.png new file mode 100644 index 000000000..7ee7b2ebc Binary files /dev/null and b/data/editor/icons/globalIllumination.png differ diff --git a/data/editor/icons/globalIllumination.svg b/data/editor/icons/globalIllumination.svg new file mode 100644 index 000000000..78e442622 --- /dev/null +++ b/data/editor/icons/globalIllumination.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/data/editor/icons/globalIllumination_light.png b/data/editor/icons/globalIllumination_light.png new file mode 100644 index 000000000..8dae6a821 Binary files /dev/null and b/data/editor/icons/globalIllumination_light.png differ diff --git a/data/editor/icons/irradianceVolume.png b/data/editor/icons/irradianceVolume.png new file mode 100644 index 000000000..2ef9b0d6e Binary files /dev/null and b/data/editor/icons/irradianceVolume.png differ diff --git a/data/editor/icons/irradianceVolume.svg b/data/editor/icons/irradianceVolume.svg new file mode 100644 index 000000000..9fbbea5ed --- /dev/null +++ b/data/editor/icons/irradianceVolume.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/data/editor/icons/irradianceVolume_light.png b/data/editor/icons/irradianceVolume_light.png new file mode 100644 index 000000000..a22c5bac4 Binary files /dev/null and b/data/editor/icons/irradianceVolume_light.png differ diff --git a/data/editor/icons/log.png b/data/editor/icons/log.png new file mode 100644 index 000000000..e59b73264 Binary files /dev/null and b/data/editor/icons/log.png differ diff --git a/data/editor/icons/log.svg b/data/editor/icons/log.svg new file mode 100644 index 000000000..53b09a6bd --- /dev/null +++ b/data/editor/icons/log.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/data/editor/icons/log_light.png b/data/editor/icons/log_light.png new file mode 100644 index 000000000..d34812040 Binary files /dev/null and b/data/editor/icons/log_light.png differ diff --git a/data/editor/icons/materialGraph.png b/data/editor/icons/materialGraph.png new file mode 100644 index 000000000..118cce659 Binary files /dev/null and b/data/editor/icons/materialGraph.png differ diff --git a/data/editor/icons/materialGraph.svg b/data/editor/icons/materialGraph.svg new file mode 100644 index 000000000..0f5425584 --- /dev/null +++ b/data/editor/icons/materialGraph.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/data/editor/icons/materialGraph_light.png b/data/editor/icons/materialGraph_light.png new file mode 100644 index 000000000..8c31ee3d6 Binary files /dev/null and b/data/editor/icons/materialGraph_light.png differ diff --git a/data/editor/icons/navigation.png b/data/editor/icons/navigation.png new file mode 100644 index 000000000..1098b6337 Binary files /dev/null and b/data/editor/icons/navigation.png differ diff --git a/data/editor/icons/navigation.svg b/data/editor/icons/navigation.svg new file mode 100644 index 000000000..eff7d6127 --- /dev/null +++ b/data/editor/icons/navigation.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/data/editor/icons/navigation_light.png b/data/editor/icons/navigation_light.png new file mode 100644 index 000000000..f74440b4b Binary files /dev/null and b/data/editor/icons/navigation_light.png differ diff --git a/data/editor/icons/notifications.png b/data/editor/icons/notifications.png new file mode 100644 index 000000000..ee217ed20 Binary files /dev/null and b/data/editor/icons/notifications.png differ diff --git a/data/editor/icons/notifications.svg b/data/editor/icons/notifications.svg new file mode 100644 index 000000000..dbfe0e040 --- /dev/null +++ b/data/editor/icons/notifications.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/data/editor/icons/notifications_light.png b/data/editor/icons/notifications_light.png new file mode 100644 index 000000000..ff24d3cb6 Binary files /dev/null and b/data/editor/icons/notifications_light.png differ diff --git a/data/editor/icons/ocean.png b/data/editor/icons/ocean.png new file mode 100644 index 000000000..548572661 Binary files /dev/null and b/data/editor/icons/ocean.png differ diff --git a/data/editor/icons/ocean.svg b/data/editor/icons/ocean.svg new file mode 100644 index 000000000..b6857326d --- /dev/null +++ b/data/editor/icons/ocean.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/data/editor/icons/ocean_light.png b/data/editor/icons/ocean_light.png new file mode 100644 index 000000000..16ce5fb94 Binary files /dev/null and b/data/editor/icons/ocean_light.png differ diff --git a/data/editor/icons/openInNew.png b/data/editor/icons/openInNew.png new file mode 100644 index 000000000..5fb94c3bc Binary files /dev/null and b/data/editor/icons/openInNew.png differ diff --git a/data/editor/icons/openInNew.svg b/data/editor/icons/openInNew.svg new file mode 100644 index 000000000..ef3fe201a --- /dev/null +++ b/data/editor/icons/openInNew.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/data/editor/icons/openInNew_light.png b/data/editor/icons/openInNew_light.png new file mode 100644 index 000000000..314551c04 Binary files /dev/null and b/data/editor/icons/openInNew_light.png differ diff --git a/data/editor/icons/pause.png b/data/editor/icons/pause.png new file mode 100644 index 000000000..01b8e5293 Binary files /dev/null and b/data/editor/icons/pause.png differ diff --git a/data/editor/icons/pause.svg b/data/editor/icons/pause.svg new file mode 100644 index 000000000..95bc792fc --- /dev/null +++ b/data/editor/icons/pause.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/data/editor/icons/pause_light.png b/data/editor/icons/pause_light.png new file mode 100644 index 000000000..61fdadb44 Binary files /dev/null and b/data/editor/icons/pause_light.png differ diff --git a/data/editor/icons/pin.png b/data/editor/icons/pin.png new file mode 100644 index 000000000..e7333c9b7 Binary files /dev/null and b/data/editor/icons/pin.png differ diff --git a/data/editor/icons/pin.svg b/data/editor/icons/pin.svg new file mode 100644 index 000000000..9f3538e70 --- /dev/null +++ b/data/editor/icons/pin.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/data/editor/icons/pinFilled.png b/data/editor/icons/pinFilled.png new file mode 100644 index 000000000..3439438ca Binary files /dev/null and b/data/editor/icons/pinFilled.png differ diff --git a/data/editor/icons/pinFilled.svg b/data/editor/icons/pinFilled.svg new file mode 100644 index 000000000..c2f8ef72f --- /dev/null +++ b/data/editor/icons/pinFilled.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/data/editor/icons/pinFilled_light.png b/data/editor/icons/pinFilled_light.png new file mode 100644 index 000000000..77c4aba1b Binary files /dev/null and b/data/editor/icons/pinFilled_light.png differ diff --git a/data/editor/icons/pin_light.png b/data/editor/icons/pin_light.png new file mode 100644 index 000000000..08f6adf49 Binary files /dev/null and b/data/editor/icons/pin_light.png differ diff --git a/data/editor/icons/postProcessing.png b/data/editor/icons/postProcessing.png new file mode 100644 index 000000000..90f327d6f Binary files /dev/null and b/data/editor/icons/postProcessing.png differ diff --git a/data/editor/icons/postProcessing.svg b/data/editor/icons/postProcessing.svg new file mode 100644 index 000000000..887f8bd49 --- /dev/null +++ b/data/editor/icons/postProcessing.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/data/editor/icons/postProcessing_light.png b/data/editor/icons/postProcessing_light.png new file mode 100644 index 000000000..0b14a2336 Binary files /dev/null and b/data/editor/icons/postProcessing_light.png differ diff --git a/data/editor/icons/profiler.png b/data/editor/icons/profiler.png new file mode 100644 index 000000000..821a59c17 Binary files /dev/null and b/data/editor/icons/profiler.png differ diff --git a/data/editor/icons/profiler.svg b/data/editor/icons/profiler.svg new file mode 100644 index 000000000..cf94f4936 --- /dev/null +++ b/data/editor/icons/profiler.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/data/editor/icons/profiler_light.png b/data/editor/icons/profiler_light.png new file mode 100644 index 000000000..e62da384b Binary files /dev/null and b/data/editor/icons/profiler_light.png differ diff --git a/data/editor/icons/redo.png b/data/editor/icons/redo.png new file mode 100644 index 000000000..0c77c238f Binary files /dev/null and b/data/editor/icons/redo.png differ diff --git a/data/editor/icons/redo.svg b/data/editor/icons/redo.svg new file mode 100644 index 000000000..94d65b4c8 --- /dev/null +++ b/data/editor/icons/redo.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/data/editor/icons/redo_light.png b/data/editor/icons/redo_light.png new file mode 100644 index 000000000..3c87cdb97 Binary files /dev/null and b/data/editor/icons/redo_light.png differ diff --git a/data/editor/icons/reflection.png b/data/editor/icons/reflection.png new file mode 100644 index 000000000..622fdd042 Binary files /dev/null and b/data/editor/icons/reflection.png differ diff --git a/data/editor/icons/reflection.svg b/data/editor/icons/reflection.svg new file mode 100644 index 000000000..844fc7a08 --- /dev/null +++ b/data/editor/icons/reflection.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/data/editor/icons/reflection_light.png b/data/editor/icons/reflection_light.png new file mode 100644 index 000000000..131f94295 Binary files /dev/null and b/data/editor/icons/reflection_light.png differ diff --git a/data/editor/icons/reset.png b/data/editor/icons/reset.png new file mode 100644 index 000000000..0e3508cf7 Binary files /dev/null and b/data/editor/icons/reset.png differ diff --git a/data/editor/icons/reset.svg b/data/editor/icons/reset.svg new file mode 100644 index 000000000..8fa96d44b --- /dev/null +++ b/data/editor/icons/reset.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/data/editor/icons/reset_light.png b/data/editor/icons/reset_light.png new file mode 100644 index 000000000..19165a5aa Binary files /dev/null and b/data/editor/icons/reset_light.png differ diff --git a/data/editor/icons/save.png b/data/editor/icons/save.png new file mode 100644 index 000000000..a9743387e Binary files /dev/null and b/data/editor/icons/save.png differ diff --git a/data/editor/icons/save.svg b/data/editor/icons/save.svg new file mode 100644 index 000000000..03da450db --- /dev/null +++ b/data/editor/icons/save.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/data/editor/icons/save_light.png b/data/editor/icons/save_light.png new file mode 100644 index 000000000..795d8428b Binary files /dev/null and b/data/editor/icons/save_light.png differ diff --git a/data/editor/icons/scaleInverse.png b/data/editor/icons/scaleInverse.png new file mode 100644 index 000000000..8b3b31670 Binary files /dev/null and b/data/editor/icons/scaleInverse.png differ diff --git a/data/editor/icons/scaleInverse.svg b/data/editor/icons/scaleInverse.svg new file mode 100644 index 000000000..2e33ce508 --- /dev/null +++ b/data/editor/icons/scaleInverse.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/data/editor/icons/scaleInverse_light.png b/data/editor/icons/scaleInverse_light.png new file mode 100644 index 000000000..04c84afe2 Binary files /dev/null and b/data/editor/icons/scaleInverse_light.png differ diff --git a/data/editor/icons/search.png b/data/editor/icons/search.png new file mode 100644 index 000000000..384f7331f Binary files /dev/null and b/data/editor/icons/search.png differ diff --git a/data/editor/icons/search.svg b/data/editor/icons/search.svg new file mode 100644 index 000000000..ef0d0521e --- /dev/null +++ b/data/editor/icons/search.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/data/editor/icons/search_light.png b/data/editor/icons/search_light.png new file mode 100644 index 000000000..cbd55e094 Binary files /dev/null and b/data/editor/icons/search_light.png differ diff --git a/data/editor/icons/shadow.png b/data/editor/icons/shadow.png new file mode 100644 index 000000000..3c7cc6741 Binary files /dev/null and b/data/editor/icons/shadow.png differ diff --git a/data/editor/icons/shadow.svg b/data/editor/icons/shadow.svg new file mode 100644 index 000000000..c37b321f4 --- /dev/null +++ b/data/editor/icons/shadow.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/data/editor/icons/shadow_light.png b/data/editor/icons/shadow_light.png new file mode 100644 index 000000000..53fd70f83 Binary files /dev/null and b/data/editor/icons/shadow_light.png differ diff --git a/data/editor/icons/sky.png b/data/editor/icons/sky.png new file mode 100644 index 000000000..c0276b9b3 Binary files /dev/null and b/data/editor/icons/sky.png differ diff --git a/data/editor/icons/sky.svg b/data/editor/icons/sky.svg new file mode 100644 index 000000000..8e4e9d0d9 --- /dev/null +++ b/data/editor/icons/sky.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/data/editor/icons/sky_light.png b/data/editor/icons/sky_light.png new file mode 100644 index 000000000..6a8770880 Binary files /dev/null and b/data/editor/icons/sky_light.png differ diff --git a/data/editor/icons/undo.png b/data/editor/icons/undo.png new file mode 100644 index 000000000..66d1ff32e Binary files /dev/null and b/data/editor/icons/undo.png differ diff --git a/data/editor/icons/undo.svg b/data/editor/icons/undo.svg new file mode 100644 index 000000000..c451e1adc --- /dev/null +++ b/data/editor/icons/undo.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/data/editor/icons/undo_light.png b/data/editor/icons/undo_light.png new file mode 100644 index 000000000..fc8c6340a Binary files /dev/null and b/data/editor/icons/undo_light.png differ diff --git a/data/editor/icons/viewGrid.png b/data/editor/icons/viewGrid.png new file mode 100644 index 000000000..c9904ebe2 Binary files /dev/null and b/data/editor/icons/viewGrid.png differ diff --git a/data/editor/icons/viewGrid.svg b/data/editor/icons/viewGrid.svg new file mode 100644 index 000000000..962298238 --- /dev/null +++ b/data/editor/icons/viewGrid.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/data/editor/icons/viewGrid_light.png b/data/editor/icons/viewGrid_light.png new file mode 100644 index 000000000..76f6dbd53 Binary files /dev/null and b/data/editor/icons/viewGrid_light.png differ diff --git a/data/editor/icons/viewList.png b/data/editor/icons/viewList.png new file mode 100644 index 000000000..676f1c174 Binary files /dev/null and b/data/editor/icons/viewList.png differ diff --git a/data/editor/icons/viewList.svg b/data/editor/icons/viewList.svg new file mode 100644 index 000000000..8bff278f9 --- /dev/null +++ b/data/editor/icons/viewList.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/data/editor/icons/viewList_light.png b/data/editor/icons/viewList_light.png new file mode 100644 index 000000000..85e0c726f Binary files /dev/null and b/data/editor/icons/viewList_light.png differ diff --git a/data/editor/icons/warning.png b/data/editor/icons/warning.png new file mode 100644 index 000000000..2d4ff221d Binary files /dev/null and b/data/editor/icons/warning.png differ diff --git a/data/editor/icons/warning.svg b/data/editor/icons/warning.svg new file mode 100644 index 000000000..7fe972ff2 --- /dev/null +++ b/data/editor/icons/warning.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/data/editor/icons/warning_light.png b/data/editor/icons/warning_light.png new file mode 100644 index 000000000..1b5befc47 Binary files /dev/null and b/data/editor/icons/warning_light.png differ diff --git a/data/editor/icons/wind.png b/data/editor/icons/wind.png new file mode 100644 index 000000000..4bad7a7f0 Binary files /dev/null and b/data/editor/icons/wind.png differ diff --git a/data/editor/icons/wind.svg b/data/editor/icons/wind.svg new file mode 100644 index 000000000..5a41f9dbf --- /dev/null +++ b/data/editor/icons/wind.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/data/editor/icons/wind_light.png b/data/editor/icons/wind_light.png new file mode 100644 index 000000000..d168c5bbd Binary files /dev/null and b/data/editor/icons/wind_light.png differ diff --git a/data/font/LICENSE b/data/font/LICENSE index c660ed35c..cad0ee0ee 100644 --- a/data/font/LICENSE +++ b/data/font/LICENSE @@ -1,3 +1,5 @@ +Roboto (roboto.ttf) +-------------------------------------------------------------------------------- Copyright 2024 Google @@ -11,4 +13,101 @@ distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and - limitations under the License. \ No newline at end of file + limitations under the License. + +Roboto Mono (robotomono.ttf) +-------------------------------------------------------------------------------- + +Copyright 2015 The Roboto Mono Project Authors (https://github.com/googlefonts/robotomono) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://openfontlicense.org + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/data/font/robotomono.ttf b/data/font/robotomono.ttf new file mode 100644 index 000000000..eb1fde544 Binary files /dev/null and b/data/font/robotomono.ttf differ diff --git a/data/scenes/sponza.aescene b/data/scenes/sponza.aescene index ebb6d0873..adf21663e 100644 Binary files a/data/scenes/sponza.aescene and b/data/scenes/sponza.aescene differ diff --git a/data/shader/atmosphere/atmosphere.csh b/data/shader/atmosphere/atmosphere.csh index 1716f759e..ed4dd92cb 100644 --- a/data/shader/atmosphere/atmosphere.csh +++ b/data/shader/atmosphere/atmosphere.csh @@ -27,6 +27,7 @@ layout(set = 3, binding = 3, std140) uniform UniformBuffer { float surfaceHeightOffset; float planetRadius; float atmosphereRadius; + float sunAngularRadius; } uniforms; #ifndef ENVIRONMENT_PROBE @@ -116,9 +117,9 @@ void main() { vec3 GetSunDisk(vec3 viewDirection, AtmosphereParameters atmosphere) { - float viewSunCosAngle = dot(viewDirection, uniforms.sunDirection.xyz); - float sunDisk = smoothstep(cos(atmosphereSunAngularRadius * 1.25), cos(atmosphereSunAngularRadius), - viewSunCosAngle); + // The chord length stays precise for small sun disks, unlike the cosine of the angle + float viewSunDistance = distance(viewDirection, uniforms.sunDirection.xyz); + float sunDisk = 1.0 - smoothstep(uniforms.sunAngularRadius, uniforms.sunAngularRadius * 1.25, viewSunDistance); vec3 cameraUp = normalize(uniforms.cameraLocation.xyz - uniforms.planetCenter.xyz); float cameraRadius = length(uniforms.cameraLocation.xyz - uniforms.planetCenter.xyz); diff --git a/data/shader/atmosphere/common.hsh b/data/shader/atmosphere/common.hsh index 424bbcffa..6da4fafb4 100644 --- a/data/shader/atmosphere/common.hsh +++ b/data/shader/atmosphere/common.hsh @@ -222,6 +222,7 @@ void GetRadiusMuFromMultipleScatteringTextureUv(vec2 uv, AtmosphereParameters at } +// Multiple scattering for a unit sun radiance vec3 GetMultipleScattering(sampler2D multipleScatteringTexture, float radius, float muS, AtmosphereParameters atmosphere) { @@ -263,7 +264,7 @@ vec3 GetGroundRadiance(sampler2D transmittanceTexture, sampler2D multipleScatter vec3 transmittanceToSun = GetTransmittanceToSun(transmittanceTexture, groundRadius, sunZenithCosAngle, atmosphere); vec3 directIrradiance = sunRadiance * transmittanceToSun * saturate(sunZenithCosAngle); - vec3 indirectIrradiance = GetMultipleScattering(multipleScatteringTexture, groundRadius, + vec3 indirectIrradiance = sunRadiance * GetMultipleScattering(multipleScatteringTexture, groundRadius, sunZenithCosAngle, atmosphere) * PI * atmosphereGroundIndirectFactor; return atmosphere.groundAlbedo * (directIrradiance + indirectIrradiance) / PI; @@ -365,7 +366,7 @@ vec3 IntegrateAtmosphereScattering(sampler2D transmittanceTexture, sampler2D mul vec3 transmittanceToSun = GetTransmittanceToSun(transmittanceTexture, sampleRadius, muS, atmosphere); vec3 phaseScattering = GetAtmospherePhaseScattering(densities, cosTheta, atmosphere); - vec3 multipleScattering = GetMultipleScattering(multipleScatteringTexture, sampleRadius, + vec3 multipleScattering = sunRadiance * GetMultipleScattering(multipleScatteringTexture, sampleRadius, muS, atmosphere); float shadowVisibility = max3(transmittanceToSun); float multipleScatteringVisibility = shadowVisibility * diff --git a/data/shader/atmosphere/multipleScattering.csh b/data/shader/atmosphere/multipleScattering.csh index 60430b156..e5d2c7e59 100644 --- a/data/shader/atmosphere/multipleScattering.csh +++ b/data/shader/atmosphere/multipleScattering.csh @@ -1,12 +1,12 @@ #include -layout (local_size_x = 8, local_size_y = 8) in; +// One work group per texel, each invocation integrates one direction +layout (local_size_x = 64) in; layout(set = 3, binding = 0, rgba16f) writeonly uniform image2D multipleScatteringImage; layout(set = 3, binding = 1) uniform sampler2D transmittanceTexture; layout(set = 3, binding = 2, std140) uniform UniformBuffer { - vec4 sunRadiance; vec4 rayleighScatteringCoeff; vec4 groundAlbedo; float mieScatteringCoeff; @@ -20,16 +20,17 @@ layout(set = 3, binding = 2, std140) uniform UniformBuffer { const int multipleScatteringDirectionSampleCount = 64; const int multipleScatteringRaySampleCount = 20; +shared vec3 sharedLuminance[multipleScatteringDirectionSampleCount]; +shared vec3 sharedMultiScatteringFactor[multipleScatteringDirectionSampleCount]; + AtmosphereParameters GetAtmosphereParameters(); vec3 GetSphericalFibonacciDirection(int index, int count); void main() { - ivec2 pixel = ivec2(gl_GlobalInvocationID.xy); + ivec2 pixel = ivec2(gl_WorkGroupID.xy); ivec2 resolution = imageSize(multipleScatteringImage); - - if (pixel.x >= resolution.x || pixel.y >= resolution.y) - return; + int index = int(gl_LocalInvocationIndex); vec2 uv = (vec2(pixel) + 0.5) / vec2(resolution); @@ -40,25 +41,36 @@ void main() { vec3 samplePosition = vec3(0.0, 0.0, radius); vec3 sunDirection = vec3(sqrt(max(1.0 - muS * muS, 0.0)), 0.0, muS); + vec3 rayDirection = GetSphericalFibonacciDirection(index, multipleScatteringDirectionSampleCount); - vec3 inScatteredLuminance = vec3(0.0); - vec3 multiScatteringFactor = vec3(0.0); + vec3 rayLuminance; + vec3 rayMultiScatteringFactor; + // Computed for a unit sun radiance, the sun is applied where the table is sampled + IntegrateAtmosphereMultiScattering(transmittanceTexture, samplePosition, rayDirection, sunDirection, + vec3(0.0), atmosphere, vec3(1.0), multipleScatteringRaySampleCount, 1.4, + rayLuminance, rayMultiScatteringFactor); - float sampleWeight = 4.0 * PI / float(multipleScatteringDirectionSampleCount); + sharedLuminance[index] = rayLuminance; + sharedMultiScatteringFactor[index] = rayMultiScatteringFactor; - for (int i = 0; i < multipleScatteringDirectionSampleCount; i++) { - vec3 rayDirection = GetSphericalFibonacciDirection(i, multipleScatteringDirectionSampleCount); + barrier(); - vec3 rayLuminance; - vec3 rayMultiScatteringFactor; - IntegrateAtmosphereMultiScattering(transmittanceTexture, samplePosition, rayDirection, sunDirection, - vec3(0.0), atmosphere, uniforms.sunRadiance.rgb, multipleScatteringRaySampleCount, 1.4, - rayLuminance, rayMultiScatteringFactor); + for (int stride = multipleScatteringDirectionSampleCount / 2; stride > 0; stride /= 2) { + if (index < stride) { + sharedLuminance[index] += sharedLuminance[index + stride]; + sharedMultiScatteringFactor[index] += sharedMultiScatteringFactor[index + stride]; + } - inScatteredLuminance += rayLuminance * sampleWeight * atmosphereIsotropicPhase; - multiScatteringFactor += rayMultiScatteringFactor * sampleWeight; + barrier(); } + if (index > 0) + return; + + float sampleWeight = 4.0 * PI / float(multipleScatteringDirectionSampleCount); + vec3 inScatteredLuminance = sharedLuminance[0] * sampleWeight * atmosphereIsotropicPhase; + vec3 multiScatteringFactor = sharedMultiScatteringFactor[0] * sampleWeight; + vec3 clampedFactor = min(multiScatteringFactor, vec3(0.999)); vec3 multipleScattering = inScatteredLuminance / max(vec3(1.0) - clampedFactor, vec3(0.01)); diff --git a/data/shader/bloom/bloom.hsh b/data/shader/bloom/bloom.hsh deleted file mode 100644 index e69de29bb..000000000 diff --git a/data/shader/bloom/bloomDownsample.csh b/data/shader/bloom/bloomDownsample.csh index eb6b0a988..5b25a4f39 100644 --- a/data/shader/bloom/bloomDownsample.csh +++ b/data/shader/bloom/bloomDownsample.csh @@ -2,7 +2,6 @@ layout (local_size_x = 16, local_size_y = 16) in; #include <../common/utility.hsh> #include <../common/types.hsh> -#include <../common/flatten.hsh> layout (set = 3, binding = 0, rgba16f) writeonly uniform image2D textureOut; layout (set = 3, binding = 1) uniform sampler2D textureIn; @@ -12,19 +11,6 @@ layout(push_constant) uniform constants { float threshold; } pushConstants; -const uint supportSize = 2; -const uint sharedDataSize = (2u * gl_WorkGroupSize.x + 2u * supportSize) * (2u * gl_WorkGroupSize.y + 2u * supportSize); -const ivec2 unflattenedSharedDataSize = 2 * ivec2(gl_WorkGroupSize) + 2 * int(supportSize); - -shared vec3 sharedMemory[sharedDataSize]; - -const ivec2 pixelOffsets[4] = ivec2[4]( - ivec2(0, 0), - ivec2(1, 0), - ivec2(0, 1), - ivec2(1, 1) -); - AeF16 Luma(AeF16x3 color) { const AeF16x3 luma = AeF16x3(0.299, 0.587, 0.114); diff --git a/data/shader/bloom/bloomUpsample.csh b/data/shader/bloom/bloomUpsample.csh index d533c1d9e..edd1f8c48 100644 --- a/data/shader/bloom/bloomUpsample.csh +++ b/data/shader/bloom/bloomUpsample.csh @@ -2,7 +2,8 @@ layout (local_size_x = 8, local_size_y = 8) in; -layout (set = 3, binding = 0, rgba16f) writeonly uniform image2D textureOut; +// Holds the downsampled mip, the upsampled lower mip is added to it +layout (set = 3, binding = 0, rgba16f) uniform image2D textureOut; layout (set = 3, binding = 1) uniform sampler2D textureIn; layout(push_constant) uniform constants { @@ -27,10 +28,8 @@ void main() { // Lower mip tex coord vec2 texCoord = (coord + 0.5) / size; - // Upper mip texel size - vec2 texelSize = 1.0 / textureSize(textureIn, pushConstants.mipLevel); - vec2 filterSize = vec2(pushConstants.filterSize); - texelSize = max(filterSize, filterSize); + // Filter size in texture coordinates + vec2 texelSize = vec2(pushConstants.filterSize); // We always sample at pixel border, not centers AeF16x3 filter00 = Sample(texCoord + vec2(-texelSize.x, -texelSize.y)); @@ -53,7 +52,7 @@ void main() { filtered /= AeF16(16.0); if (pushConstants.additive > 0) { - imageStore(textureOut, coord, vec4(filtered + filter11, 1.0)); + imageStore(textureOut, coord, vec4(vec3(filtered) + imageLoad(textureOut, coord).rgb, 1.0)); } else { imageStore(textureOut, coord, vec4(filtered, 1.0)); diff --git a/data/shader/brdf/filterProbe.csh b/data/shader/brdf/filterProbe.csh index 43a7153ec..3d6e2342e 100644 --- a/data/shader/brdf/filterProbe.csh +++ b/data/shader/brdf/filterProbe.csh @@ -35,8 +35,8 @@ vec3 CubeCoordToWorld(ivec3 cubeCoord, vec2 cubemapSize) { void main() { ivec2 pixel = ivec2(gl_GlobalInvocationID); - if (pixel.x > imageSize(filteredCubeMap).x || - pixel.y > imageSize(filteredCubeMap).y) + if (pixel.x >= imageSize(filteredCubeMap).x || + pixel.y >= imageSize(filteredCubeMap).y) return; vec3 worldDirection = CubeCoordToWorld(ivec3(gl_GlobalInvocationID), @@ -73,7 +73,7 @@ vec3 FilterDiffuse(vec3 worldDirection, ivec2 cubeMapSize) { NdotL = saturate(NdotL); if (NdotL > 0.0) { - color.xyz += min(textureLod(cubeMap, L, 5.0).rgb, 5.0); + color.xyz += min(textureLod(cubeMap, L, 5.0).rgb * globalData.skyCubemapExposure, 5.0); color.w += 1.0; } @@ -121,7 +121,7 @@ vec3 FilterSpecular(vec3 worldDirection, ivec2 cubeMapSize) { lod = pushConstants.mipLevel == 0u ? 0.0 : lod; - color.xyz += clamp(textureLod(cubeMap, L, lod).rgb, vec3(0.0), vec3(5.0)) * NdotL; + color.xyz += clamp(textureLod(cubeMap, L, lod).rgb * globalData.skyCubemapExposure, vec3(0.0), vec3(5.0)) * NdotL; color.w += NdotL; } diff --git a/data/shader/clouds/clouds.hsh b/data/shader/clouds/clouds.hsh index a9800249c..409c466bb 100644 --- a/data/shader/clouds/clouds.hsh +++ b/data/shader/clouds/clouds.hsh @@ -58,7 +58,7 @@ const float cloudTypeVariation = 0.55; const float bottomTypeVariation = 0.12; const float windSkew = 0.12; -const float multiScatteringIntensity = 0.28; +const float multiScatteringIntensity = 0.45; const float multiScatteringAttenuation = 0.65; const float multiScatteringContribution = 0.50; const float multiScatteringEccentricityAttenuation = 0.60; @@ -68,6 +68,15 @@ const float edgeAlbedo = 0.68; const float edgeAlbedoCurve = 2.0; const float ambientAlbedoMix = 0.35; +// Cloud tops see the bright sky, bottoms are occluded by the cloud above and mostly see the ground +const float ambientTopStrength = 0.6; +const float ambientBottomStrength = 0.18; +const float ambientGroundMix = 0.5; + +// Powder effect: surfaces which only received light close to the surface scatter less light back. +// It darkens the creases of billowing clouds when the sun is behind the viewer. +const float powderStrength = 0.65; + vec3 cloudPlanetCenter = cloudUniforms.planetCenter.xyz; #define MULTISCATTER_OCTAVES 4 diff --git a/data/shader/clouds/integrate.csh b/data/shader/clouds/integrate.csh index 355883aee..fdc57902d 100644 --- a/data/shader/clouds/integrate.csh +++ b/data/shader/clouds/integrate.csh @@ -27,8 +27,8 @@ vec4 ComputeVolumetricClouds(vec3 fragPos, float depth); void main() { ivec2 pixel = ivec2(gl_GlobalInvocationID); - if (pixel.x > imageSize(volumetricCloudImage).x || - pixel.y > imageSize(volumetricCloudImage).y) + if (pixel.x >= imageSize(volumetricCloudImage).x || + pixel.y >= imageSize(volumetricCloudImage).y) return; vec2 texCoord = (vec2(pixel) + 0.5) / vec2(imageSize(volumetricCloudImage)); @@ -77,9 +77,7 @@ vec4 ComputeVolumetricClouds(vec3 fragPos, float depth) { if (length(fragPos) < inDist && depth != 1.0) return vec4(0.0, 0.0, 0.0, 1.0); - float rayLength = cloudUniforms.distanceLimit; - rayLength = outDist - inDist; - rayLength = depth < 1.0 ? min(length(fragPos) - inDist, outDist - inDist) : outDist - inDist; + float rayLength = depth < 1.0 ? min(length(fragPos) - inDist, outDist - inDist) : outDist - inDist; return IntegrateVolumetricClouds(globalData.cameraLocation.xyz, rayDirection, inDist, rayLength, blueNoiseVec); diff --git a/data/shader/clouds/integrate.hsh b/data/shader/clouds/integrate.hsh index 12517fd0b..ea90967e7 100644 --- a/data/shader/clouds/integrate.hsh +++ b/data/shader/clouds/integrate.hsh @@ -27,24 +27,6 @@ void CalculateTexCoords(vec3 pos, out vec3 shapeTexCoords, out vec3 detailTexCoo void CalculateRayLength(vec3 rayOrigin, vec3 rayDirection, out float minDist, out float maxDist) { - /* - // This is an option for the future to make the clouds wrap down at the distance limit into the horizon - float radiusDiff = cloudUniforms.outerRadius - cloudUniforms.innerRadius; - - float outerRadius = cloudUniforms.distanceLimit; - float innerRadius = cloudUniforms.distanceLimit - radiusDiff; - - float innerHeight = cloudUniforms.innerRadius - cloudUniforms.planetRadius; - - vec3 planetCenterDir = normalize(rayOrigin - cloudPlanetCenter); - vec3 surfacePos = cloudPlanetCenter + planetCenterDir * cloudUniforms.planetRadius; - - vec3 spherePos = surfacePos - (innerRadius - innerHeight) * planetCenterDir; - vec2 planetDist = IntersectSphere(rayOrigin, rayDirection, globalData.planetCenter.xyz, cloudUniforms.planetRadius); - vec2 inDist = IntersectSphere(rayOrigin, rayDirection, spherePos, innerRadius); - vec2 outDist = IntersectSphere(rayOrigin, rayDirection, spherePos, outerRadius); - */ - vec3 spherePos = cloudPlanetCenter; vec2 planetDist = IntersectSphere(rayOrigin, rayDirection, cloudUniforms.planetCenter.xyz, cloudUniforms.planetRadius); vec2 inDist = IntersectSphere(rayOrigin, rayDirection, spherePos, cloudUniforms.innerRadius); @@ -136,11 +118,27 @@ vec3 ComputeAmbientColor(vec3 pos, float extinction) { float distFromCenter = distance(pos, cloudPlanetCenter); vec3 isotropicLightTop = textureLod(diffuseProbe, vec3(0.0, 1.0, 0.0), 0.0).rgb; + vec3 isotropicLightBottom = textureLod(diffuseProbe, vec3(0.0, -1.0, 0.0), 0.0).rgb; + + float heightFraction = saturate((distFromCenter - cloudUniforms.innerRadius) / + (cloudUniforms.outerRadius - cloudUniforms.innerRadius)); + + // The sky lights the tops, the bases only get light reflected from the ground below + vec3 topAmbient = ambientTopStrength * isotropicLightTop; + vec3 bottomAmbient = ambientBottomStrength * mix(isotropicLightTop, isotropicLightBottom, ambientGroundMix); + return mix(bottomAmbient, topAmbient, sqrt(heightFraction)); + +} + +float ComputePowder(vec3 lightExtinction, float lightDotView) { + + // Powder term 1 - exp(-2 * depth) with the optical depth -log(lightExtinction) towards the light + float extinctionToLight = dot(lightExtinction, vec3(0.3333)); + float powder = 1.0 - extinctionToLight * extinctionToLight; - float heightFraction = (distFromCenter - cloudUniforms.innerRadius) / - (cloudUniforms.outerRadius - cloudUniforms.innerRadius); - float ambientContribution = saturate(0.5); - return 0.5 * isotropicLightTop * ambientContribution; + // Only applied when looking away from the sun, forward scattering is unaffected + float viewWeight = saturate(0.5 - lightDotView * 0.5); + return mix(1.0, mix(1.0 - powderStrength, 1.0, powder), viewWeight); } @@ -245,7 +243,8 @@ vec4 IntegrateVolumetricClouds(vec3 rayOrigin, vec3 rayDirection, float rayStart vec4 clampedExtinction = max(extinctionCoefficient, 0.0000001); vec4 stepExtinction = exp(-extinctionCoefficient * smallStepLength); - float lightDotView = dot(cloudUniforms.light.direction.xyz, rayDirection); + // Cosine between the view ray and the direction to the sun, positive eccentricities scatter forward + float lightDotView = dot(-cloudUniforms.light.direction.xyz, rayDirection); vec3 lightColor = cloudUniforms.light.color.rgb * cloudUniforms.light.intensity; vec4 lightExtinction = GetExtinctionToLight(rayPos, i % 4, noiseVector); @@ -253,7 +252,8 @@ vec4 IntegrateVolumetricClouds(vec3 rayOrigin, vec3 rayDirection, float rayStart cloudUniforms.eccentricitySecondPhase, cloudUniforms.phaseAlpha, lightDotView); vec3 multipleScattering = ApproximateMultipleScattering(lightExtinction.rgb, lightDotView); - vec3 directLighting = directAlbedo * phaseFunction * lightColor * lightExtinction.rgb; + vec3 directLighting = directAlbedo * phaseFunction * lightColor * lightExtinction.rgb * + ComputePowder(lightExtinction.rgb, lightDotView); vec3 multiScatterLighting = directAlbedo * multiScatteringIntensity * lightColor * multipleScattering; vec3 ambientLighting = ambientAlbedo * ComputeAmbientColor(rayPos, extinction.a); diff --git a/data/shader/clouds/shadow.csh b/data/shader/clouds/shadow.csh index 834cc876b..02d8e025e 100644 --- a/data/shader/clouds/shadow.csh +++ b/data/shader/clouds/shadow.csh @@ -27,8 +27,8 @@ vec2 ComputeVolumetricClouds(vec3 minDepthPos, vec3 maxDepthPos); void main() { ivec2 pixel = ivec2(gl_GlobalInvocationID); - if (pixel.x > imageSize(volumetricCloudShadowImage).x || - pixel.y > imageSize(volumetricCloudShadowImage).y) + if (pixel.x >= imageSize(volumetricCloudShadowImage).x || + pixel.y >= imageSize(volumetricCloudShadowImage).y) return; vec2 texCoord = (vec2(pixel) + 0.5) / vec2(imageSize(volumetricCloudShadowImage)); diff --git a/data/shader/clouds/temporal.csh b/data/shader/clouds/temporal.csh index a9c518928..bd105013d 100644 --- a/data/shader/clouds/temporal.csh +++ b/data/shader/clouds/temporal.csh @@ -277,8 +277,8 @@ void main() { LoadGroupSharedData(); ivec2 pixel = ivec2(gl_GlobalInvocationID); - if (pixel.x > imageSize(resolveImage).x || - pixel.y > imageSize(resolveImage).y) + if (pixel.x >= imageSize(resolveImage).x || + pixel.y >= imageSize(resolveImage).y) return; vec4 localNeighbourhoodMin, localNeighbourhoodMax; @@ -302,7 +302,7 @@ void main() { history = success && valid ? catmullRomHistory : history; } - vec4 historyValue = history; + vec4 historyValue = vec4(history.rgb * globalData.preExposure / globalData.lastPreExposure, history.a); vec4 currentValue = texelFetch(currentTexture, pixel, 0); float currentDepth = texelFetch(depthTexture, pixel, 0).r; diff --git a/data/shader/common/denoiser.hsh b/data/shader/common/denoiser.hsh new file mode 100644 index 000000000..58bc2ed4a --- /dev/null +++ b/data/shader/common/denoiser.hsh @@ -0,0 +1,123 @@ +#include <../globals.hsh> +#include +#include + +// Hit distances are stored as h / (h + 1 m): bounded with misses as one and independent of the camera +float EncodeHitDistance(float hitDistance) { + + return hitDistance / (hitDistance + 1.0); + +} + +float DecodeHitDistance(float encodedHitDistance) { + + return encodedHitDistance / max(1.0 - encodedHitDistance, 1e-3); + +} + +// The motion of the surface itself in pixels, without the part that the camera causes +vec2 GetObjectMotion(sampler2D velocityTexture, ivec2 texel, float depth, vec2 resolution) { + + vec2 texCoord = (vec2(texel) + 0.5) / resolution; + vec4 lastPosition = globalData.pvMatrixLast * vec4(ConvertDepth(depth, texCoord, globalData.ipvMatrixCurrent), 1.0); + vec2 cameraVelocity = (lastPosition.xy / lastPosition.w * 0.5 + 0.5) - texCoord; + return depth < 1.0 ? (texelFetch(velocityTexture, texel, 0).rg - cameraVelocity) * resolution : vec2(0.0); + +} + +// Squared motion of a neighbor relative to the center, only neighbors around the same depth count +float GetNearbyMotionSquared(vec2 sampleMotion, vec2 centerMotion, float linearDepth, float sampleLinearDepth) { + + if (abs(linearDepth - sampleLinearDepth) >= 0.5 + 0.1 * abs(linearDepth)) + return 0.0; + + vec2 relativeMotion = sampleMotion - centerMotion; + return dot(relativeMotion, relativeMotion); + +} + +// Moving neighbors change what the rays see without the reprojection noticing, below half a pixel it's swaying vegetation +float LimitHistoryByNearbyMotion(float historyLength, float nearbyMotion) { + + return mix(historyLength, min(historyLength, 4.0), saturate((nearbyMotion - 0.5) / 2.0)); + +} + +bool IsOffscreen(vec2 uv) { + + return uv.x < 0.0 || uv.y < 0.0 || uv.x > 1.0 || uv.y > 1.0; + +} + +// Catmull-Rom with five bilinear taps, the corners of the 4x4 footprint are left out +vec4 SampleCatmullRom(sampler2D historyTexture, vec2 uv, vec2 resolution) { + + vec2 invResolution = 1.0 / resolution; + vec2 samplePixel = uv * resolution; + + vec2 center = floor(samplePixel - 0.5) + 0.5; + vec2 f = samplePixel - center; + + vec2 w0 = f * (-0.5 + f * (1.0 - 0.5 * f)); + vec2 w1 = 1.0 + f * f * (-2.5 + 1.5 * f); + vec2 w2 = f * (0.5 + f * (2.0 - 1.5 * f)); + vec2 w3 = f * f * (-0.5 + 0.5 * f); + + vec2 w12 = w1 + w2; + vec2 uv0 = (center - 1.0) * invResolution; + vec2 uv12 = (center + w2 / w12) * invResolution; + vec2 uv3 = (center + 2.0) * invResolution; + + vec4 history = textureLod(historyTexture, vec2(uv12.x, uv0.y), 0.0) * (w12.x * w0.y) + + textureLod(historyTexture, vec2(uv0.x, uv12.y), 0.0) * (w0.x * w12.y) + + textureLod(historyTexture, uv12, 0.0) * (w12.x * w12.y) + + textureLod(historyTexture, vec2(uv3.x, uv12.y), 0.0) * (w3.x * w12.y) + + textureLod(historyTexture, vec2(uv12.x, uv3.y), 0.0) * (w12.x * w3.y); + float totalWeight = w12.x * w0.y + w0.x * w12.y + w12.x * w12.y + w3.x * w12.y + w12.x * w3.y; + + return history / totalWeight; + +} + +// Effective number of accumulated frames, blending reduces the noise variance to (1 - factor)^2 + factor^2 / historyLength +float GetAccumulatedFrames(float factor, float historyLength) { + + return 1.0 / (sqr(1.0 - factor) + sqr(factor) / max(historyLength, 1e-6)); + +} + +// View space direction through a pixel with a view space depth of one, it is affine in the texture coordinates +vec3 GetViewRay(vec2 texCoord) { + + vec3 position = ConvertDepthToViewSpace(0.5, texCoord); + return position / position.z; + +} + +float Luma(vec3 color) { + + const vec3 luma = vec3(0.299, 0.587, 0.114); + return dot(color, luma); + +} + +// The distance along the line from the history to the current color where it leaves the box +float ClipBoundingBox(vec3 boxMin, vec3 boxMax, vec3 history, vec3 current) { + + vec3 origin = history; + vec3 dir = current - history; + + // Make sure dir isn't zero + dir.x = abs(dir.x) < (1.0 / 32767.0) ? (1.0 / 32767.0) : dir.x; + dir.y = abs(dir.y) < (1.0 / 32767.0) ? (1.0 / 32767.0) : dir.y; + dir.z = abs(dir.z) < (1.0 / 32767.0) ? (1.0 / 32767.0) : dir.z; + + vec3 invDir = 1.0 / dir; + + vec3 t0 = (boxMin - origin) * invDir; + vec3 t1 = (boxMax - origin) * invDir; + + vec3 intersect = min(t0, t1); + return max(intersect.x, max(intersect.y, intersect.z)); + +} diff --git a/data/shader/common/light.hsh b/data/shader/common/light.hsh index 886cf6d4d..a3ac44e9b 100644 --- a/data/shader/common/light.hsh +++ b/data/shader/common/light.hsh @@ -4,10 +4,4 @@ float GetDistanceAttenuation(float dist, float radius) { return saturate(1.0 - pow(dist / radius, 4.0)) / (dist * dist); -} - -float GetAngleAttenuation() { - - - } \ No newline at end of file diff --git a/data/shader/common/material.hsh b/data/shader/common/material.hsh index 3c864e1a1..71363570f 100644 --- a/data/shader/common/material.hsh +++ b/data/shader/common/material.hsh @@ -42,8 +42,19 @@ struct Material { bool transmissive; bool vertexColors; bool terrain; + + // Only set for the hits of rays + uint blendMode; + // Of the side the ray enters relative to the one it comes from + float refractiveIndex; }; +// Has to match MaterialBlendMode +const uint blendModeNone = 0u; +const uint blendModeAlpha = 1u; +const uint blendModeAdditive = 2u; +const uint blendModeMultiply = 3u; + struct PackedMaterial { vec4 data0; vec4 data1; diff --git a/data/shader/common/opacity.hsh b/data/shader/common/opacity.hsh new file mode 100644 index 000000000..387c775c8 --- /dev/null +++ b/data/shader/common/opacity.hsh @@ -0,0 +1,2 @@ +// Surfaces with a lower opacity are cut out, the same in all passes +const float opacityCutoff = 0.2; diff --git a/data/shader/common/rotation.hsh b/data/shader/common/rotation.hsh new file mode 100644 index 000000000..1c3739cef --- /dev/null +++ b/data/shader/common/rotation.hsh @@ -0,0 +1,11 @@ +// Rotates v like the rotation which turns the unit vector from into the unit vector to +vec3 RotateLike(vec3 v, vec3 from, vec3 to) { + + vec3 axis = cross(from, to); + float cosine = dot(from, to); + // Opposite vectors have no shortest rotation, the mirror image works for vectors orthogonal to them + if (cosine < -0.999) + return v - 2.0 * dot(v, from) * from; + return v * cosine + cross(axis, v) + axis * (dot(axis, v) / (1.0 + cosine)); + +} \ No newline at end of file diff --git a/data/shader/common/stencil.hsh b/data/shader/common/stencil.hsh index 2b27900a2..a01ba14f0 100644 --- a/data/shader/common/stencil.hsh +++ b/data/shader/common/stencil.hsh @@ -2,6 +2,7 @@ struct StencilFeatures { bool responsivePixel; bool waterPixel; bool underWaterPixel; + bool noTemporalAccumulation; }; StencilFeatures CreateStencilFeatures() { @@ -11,6 +12,7 @@ StencilFeatures CreateStencilFeatures() { features.responsivePixel = false; features.waterPixel = false; features.underWaterPixel = false; + features.noTemporalAccumulation = false; return features; @@ -21,12 +23,14 @@ uint EncodeStencilFeatures(StencilFeatures features) { const uint responsivePixel = (1 << 0); const uint waterPixel = (1 << 1); const uint underWaterPixel = (1 << 2); + const uint noTemporalAccumulation = (1 << 3); uint data = 0u; data |= features.responsivePixel ? responsivePixel : 0u; data |= features.waterPixel ? waterPixel : 0u; data |= features.underWaterPixel ? underWaterPixel : 0u; + data |= features.noTemporalAccumulation ? noTemporalAccumulation : 0u; return data; @@ -37,12 +41,14 @@ StencilFeatures DecodeStencilFeatures(uint data) { const uint responsivePixel = (1 << 0); const uint waterPixel = (1 << 1); const uint underWaterPixel = (1 << 2); + const uint noTemporalAccumulation = (1 << 3); StencilFeatures features; features.responsivePixel = (data & responsivePixel) > 0u; features.waterPixel = (data & waterPixel) > 0u; features.underWaterPixel = (data & underWaterPixel) > 0u; + features.noTemporalAccumulation = (data & noTemporalAccumulation) > 0u; return features; diff --git a/data/shader/common/texCoord.hsh b/data/shader/common/texCoord.hsh new file mode 100644 index 000000000..2577c9593 --- /dev/null +++ b/data/shader/common/texCoord.hsh @@ -0,0 +1,9 @@ +#include <../globals.hsh> + +// Texture coordinates of a mesh as all passes use them: flipped for meshes with inverted UVs, animated and tiled by the material +vec2 TransformTexCoord(vec2 texCoord, bool invertUVs, vec2 uvAnimation, float uvTiling) { + + texCoord = invertUVs ? vec2(texCoord.x, 1.0 - texCoord.y) : texCoord; + return (texCoord + uvAnimation * globalData.time) * uvTiling; + +} diff --git a/data/shader/common/traceScreenSpace.hsh b/data/shader/common/traceScreenSpace.hsh index ea2979952..5e43cf1b4 100644 --- a/data/shader/common/traceScreenSpace.hsh +++ b/data/shader/common/traceScreenSpace.hsh @@ -11,282 +11,79 @@ #define point2 vec2 #define point3 vec3 -float distanceSquared(vec2 a, vec2 b) { a -= b; return dot(a, a); } +// Returns true if the ray hit something, the hierarchical depth buffer is generated by the HiZRenderer +bool traceScreenSpaceHiZ(point3 csOrig, vec3 csDir, sampler2D hiZTexture, int hiZLevelCount, vec2 depthBufferSize, + int maxIterations, float maxDistance, bool stopBehindGeometry, out point2 hitPixel, out point3 hitPoint) { -bool intersectsDepthBuffer(float z, float minZ, float maxZ, float thickness, float strideCutoff) { - /* - * Based on how far away from the camera the depth is, - * adding a bit of extra thickness can help improve some - * artifacts. Driving this value up too high can cause - * artifacts of its own. - */ - float depthScale = min(1.0, -z * strideCutoff); - thickness *= mix(0.0, 4.0, depthScale); - return (maxZ >= z - thickness) && (minZ < z); -} - -bool validPixel(vec2 hitPixel, vec2 resolution) { - - return hitPixel.x >= 0 && hitPixel.y >= 0 && hitPixel.x < resolution.x && hitPixel.y < resolution.y; - -} - -// Returns true if the ray hit something -bool traceScreenSpace( - // Camera-space ray origin, which must be within the view volume - point3 csOrig, - - // Unit length camera-space ray direction - vec3 csDir, - - // The camera-space Z buffer (all negative values) - sampler2D csZBuffer, - - // Camera space thickness to ascribe to each pixel in the depth buffer - float zThickness, - - // Step in horizontal or vertical pixels between samples. This is a float - // because integer math is slow on GPUs, but should be set to an integer >= 1 - float stride, - - // Number between 0 and 1 for how far to bump the ray in stride units - // to conceal banding artifacts - float jitter, - - // Maximum number of iterations. Higher gives better images but may be slow - const float maxSteps, - - // Maximum camera-space distance to trace before returning a miss - float maxDistance, - - bool stopBehindGeometry, - - // Pixel coordinates of the first intersection with the scene - out point2 hitPixel, - - // Camera space location of the ray hit - out point3 hitPoint, - - out point3 minPoint, - - out point3 maxPoint) { - - mat4 ipMatrix = globalData.ipMatrix; + hitPixel = vec2(0.0); + hitPoint = vec3(0.0); - // Clip to the near plane + // Clip to the near plane float rayLength = ((csOrig.z + csDir.z * maxDistance) > -globalData.cameraNearPlane) ? (-globalData.cameraNearPlane - csOrig.z) / csDir.z : maxDistance; point3 csEndPoint = csOrig + csDir * rayLength; - vec2 csZBufferSize = vec2(textureSize(csZBuffer, 0)); - - // Project into homogeneous clip space vec4 H0 = globalData.pMatrix * vec4(csOrig, 1.0); vec4 H1 = globalData.pMatrix * vec4(csEndPoint, 1.0); - float k0 = 1.0 / H0.w, k1 = 1.0 / H1.w; - - // The interpolated homogeneous version of the camera-space points - point3 Q0 = csOrig * k0; - point3 Q1 = csEndPoint * k1; - - // Screen-space endpoints - point2 P0 = (H0.xy * k0) * 0.5 + 0.5; - point2 P1 = 0.5 * (H1.xy * k1) + 0.5; - P0 *= csZBufferSize; - P1 *= csZBufferSize; - - // If the line is degenerate, make it cover at least one pixel - // to avoid handling zero-pixel extent as a special case later - P1 += vec2((distanceSquared(P0, P1) < 0.0001) ? 0.01 : 0.0); - vec2 delta = P1 - P0; + vec3 S0 = vec3((H0.xy / H0.w * 0.5 + 0.5) * depthBufferSize, H0.z / H0.w); + vec3 S1 = vec3((H1.xy / H1.w * 0.5 + 0.5) * depthBufferSize, H1.z / H1.w); + vec3 D = S1 - S0; - // Permute so that the primary iteration is in x to collapse - // all quadrant-specific DDA cases later - bool permute = false; - if (abs(delta.x) < abs(delta.y)) { - // This is a more-vertical line - permute = true; delta = delta.yx; P0 = P0.yx; P1 = P1.yx; - } - - float stepDir = sign(delta.x); - float invdx = stepDir / delta.x; + vec2 safeD = mix(D.xy, vec2(1e-12), lessThan(abs(D.xy), vec2(1e-12))); + vec2 invD = 1.0 / safeD; - // Track the derivatives of Q and k - vec3 dQ = (Q1 - Q0) * invdx; - float dk = (k1 - k0) * invdx; - vec2 dP = vec2(stepDir, delta.y * invdx); + vec2 tBorder = (mix(vec2(0.0), depthBufferSize, greaterThan(D.xy, vec2(0.0))) - S0.xy) * invD; + float tEnd = min(1.0, min(tBorder.x, tBorder.y)); - // Scale derivatives by the desired pixel stride and then - // offset the starting values by the jitter fraction + float pixelLength = max(abs(D.x), abs(D.y)); + float tEpsilon = 0.01 / max(pixelLength, 1.0); - const float strideOffset = 0.002; - float strideScale = 1.0 - min(1.0, abs(csOrig.z) * strideOffset); - stride = 1.0 + strideScale * stride; + vec2 stepDirection = vec2(greaterThan(D.xy, vec2(0.0))); - P0 += dP; - Q0 += dQ; - k0 += dk; + // Skipping more than the origin pixel might miss surfaces next to the origin + vec2 tOriginExit = ((floor(S0.xy) + stepDirection) - S0.xy) * invD; + float t = min(min(tOriginExit.x, tOriginExit.y) + tEpsilon, 1.0); - dP *= stride; - dQ *= stride; - dk *= stride; + int level = 0; + for (int i = 0; i < maxIterations && t < tEnd; i++) { + point2 P = S0.xy + D.xy * t; + float cellSize = float(1 << level); + vec2 cell = floor(P / cellSize); + vec2 minMaxDepth = texelFetch(hiZTexture, ivec2(cell), level).rg; - P0 += dP * jitter; - Q0 += dQ * jitter; - k0 += dk * jitter; + vec2 tBoundary = ((cell + stepDirection) * cellSize - S0.xy) * invD; + float tExit = min(min(tBoundary.x, tBoundary.y), tEnd); + float rayDepth0 = S0.z + D.z * t; + float rayDepth1 = S0.z + D.z * tExit; + float rayDepthMin = min(rayDepth0, rayDepth1); + float rayDepthMax = max(rayDepth0, rayDepth1); - // Slide P from P0 to P1, (now-homogeneous) Q from Q0 to Q1, k from k0 to k1 - point3 Q = Q0; + bool inFront = rayDepthMax < minMaxDepth.x; + bool behind = rayDepthMin > minMaxDepth.y; - // Adjust end condition for iteration direction - float end = P1.x * stepDir; + if (stopBehindGeometry && behind) + return false; - float k = k0, stepCount = 0.0, prevZMaxEstimate = csOrig.z; - float rayZMin = prevZMaxEstimate, rayZMax = prevZMaxEstimate; - float sceneZMax = rayZMax + maxDistance; - float sceneDepthMax = 0.0; - point2 P = P0; - for (; - ((P.x * stepDir) <= end) && (stepCount < maxSteps) && - !intersectsDepthBuffer(sceneZMax, rayZMin, rayZMax, zThickness, strideOffset) && - (sceneZMax != 0); - P += dP, Q.z += dQ.z, k += dk, ++stepCount) { - - rayZMin = prevZMaxEstimate; - rayZMax = (dQ.z * 0.5 + Q.z) / (dk * 0.5 + k); - prevZMaxEstimate = rayZMax; - if (rayZMin > rayZMax) { - float t = rayZMin; rayZMin = rayZMax; rayZMax = t; + if (inFront || behind) { + t = tExit + tEpsilon; + level = min(level + 1, hiZLevelCount - 1); + } + else if (level > 0) { + level--; + } + else { + if (minMaxDepth.x >= 1.0) { + t = tExit + tEpsilon; + continue; + } + + hitPixel = cell; + vec2 texCoord = (cell + 0.5) / depthBufferSize; + hitPoint = ConvertDepthToViewSpace(rayDepth0, texCoord); + return true; } - - hitPixel = permute ? P.yx : P; - // You may need hitPixel.y = csZBufferSize.y - hitPixel.y; here if your vertical axis - // is different than ours in screen space - sceneDepthMax = texelFetch(csZBuffer, ivec2(hitPixel), 0).r; - sceneZMax = ConvertDepthToViewSpaceDepth(sceneDepthMax, ipMatrix); - - // If we have a raytracing fallback we want to reject rays that go behind the depth buffer in - // certain phases in the screen space trace. - if (stopBehindGeometry && sceneZMax > rayZMax) - return false; } - minPoint = Q0 + dQ * (stepCount - 2.0); - maxPoint = Q0 + dQ * (stepCount - 1.0); + return false; - minPoint /= (k - 2.0 * dk); - maxPoint /= (k - 1.0 * dk); - - // Advance Q based on the number of steps - Q.xy += dQ.xy * stepCount; - hitPoint = Q * (1.0 / k); - - return (intersectsDepthBuffer(sceneZMax, rayZMin, rayZMax, zThickness, strideOffset)) - && validPixel(hitPixel, csZBufferSize) && sceneDepthMax < 1.0; } - -bool traceScreenSpace( - // Camera-space ray origin, which must be within the view volume - point3 csOrig, - - // Unit length camera-space ray direction - vec3 csDir, - - // The camera-space Z buffer (all negative values) - sampler2D csZBuffer, - - // Camera space thickness to ascribe to each pixel in the depth buffer - float zThickness, - - // Step in horizontal or vertical pixels between samples. This is a float - // because integer math is slow on GPUs, but should be set to an integer >= 1 - float stride, - - // Number between 0 and 1 for how far to bump the ray in stride units - // to conceal banding artifacts - float jitter, - - // Maximum number of iterations. Higher gives better images but may be slow - const float maxSteps, - - // Maximum camera-space distance to trace before returning a miss - float maxDistance, - - // Pixel coordinates of the first intersection with the scene - out point2 hitPixel, - - // Camera space location of the ray hit - out point3 hitPoint) { - - point3 minPoint, maxPoint; - return traceScreenSpace(csOrig, csDir, csZBuffer, zThickness, stride, jitter, maxSteps, maxDistance, false, hitPixel, hitPoint, minPoint, maxPoint); - -} - -bool traceScreenSpaceAdvanced( - // Camera-space ray origin, which must be within the view volume - point3 csOrig, - - // Unit length camera-space ray direction - vec3 csDir, - - // The camera-space Z buffer (all negative values) - sampler2D csZBuffer, - - // Camera space thickness to ascribe to each pixel in the depth buffer - float zThickness, - - // Step in horizontal or vertical pixels between samples. This is a float - // because integer math is slow on GPUs, but should be set to an integer >= 1 - float stride, - - // Number between 0 and 1 for how far to bump the ray in stride units - // to conceal banding artifacts - float jitter, - - // Maximum number of iterations. Higher gives better images but may be slow - float maxSteps, - - // Maximum camera-space distance to trace before returning a miss - float maxDistance, - - bool allowFallback, - - bool stopBehindGeometry, - - // Pixel coordinates of the first intersection with the scene - out point2 hitPixel, - - // Camera space location of the ray hit - out point3 hitPoint) { - - bool hit = false; - - point3 minPoint, maxPoint; - if(traceScreenSpace(csOrig, csDir, csZBuffer, zThickness, stride, jitter, maxSteps, maxDistance, stopBehindGeometry, hitPixel, hitPoint, minPoint, maxPoint)) { - hit = true; - } - - if (!hit && !allowFallback) - return false; - - hit = false; - // maxSteps /= 2.0; - - csOrig = minPoint; - csDir = normalize(maxPoint - minPoint); - stride = max(1.0, stride / maxSteps); - //zThickness /= (1.0 * maxSteps); - //maxDistance = min(maxDistance, 20.0 * distance(maxPoint, minPoint)); - - vec2 newHitPixel; - vec3 newHitPoint; - if (traceScreenSpace(csOrig, csDir, csZBuffer, zThickness, stride, jitter, maxSteps, maxDistance, false, newHitPixel, newHitPoint, minPoint, maxPoint)) { - hitPixel = newHitPixel; - hitPoint = newHitPoint; - hit = true; - } - - return hit; - -} \ No newline at end of file diff --git a/data/shader/common/upsample.hsh b/data/shader/common/upsample.hsh new file mode 100644 index 000000000..dc3fae9c1 --- /dev/null +++ b/data/shader/common/upsample.hsh @@ -0,0 +1,55 @@ +#include + +// Upsampling of half resolution data: a work group loads the low resolution texels it covers into shared memory, +// with a border of one texel +const uint depthDataSize = (gl_WorkGroupSize.x / 2 + 2) * (gl_WorkGroupSize.y / 2 + 2); +const ivec2 unflattenedDepthDataSize = ivec2(gl_WorkGroupSize) / 2 + 2; + +// The low resolution texel the invocation loads, invocations beyond the tile return false +bool GetUpsampleTileTexel(ivec2 lowResSize, out ivec2 texel) { + + texel = ivec2(0); + if (gl_LocalInvocationIndex >= depthDataSize) + return false; + + ivec2 workGroupOffset = ivec2(gl_WorkGroupID) * ivec2(gl_WorkGroupSize) / 2 - ivec2(1); + texel = clamp(Unflatten2D(int(gl_LocalInvocationIndex), unflattenedDepthDataSize) + workGroupOffset, + ivec2(0), lowResSize - 1); + return true; + +} + +const ivec2 offsets[9] = ivec2[9]( + ivec2(-1, -1), + ivec2(0, -1), + ivec2(1, -1), + ivec2(-1, 0), + ivec2(0, 0), + ivec2(1, 0), + ivec2(-1, 1), + ivec2(0, 1), + ivec2(1, 1) +); + +const ivec2 pixelOffsets[4] = ivec2[4]( + ivec2(0, 0), + ivec2(1, 0), + ivec2(0, 1), + ivec2(1, 1) +); + +// The index of the depth closest to the reference, the center wins ties +int NearestDepth(float referenceDepth, float[9] depthVec) { + + int idx = 4; + float nearest = distance(referenceDepth, depthVec[4]); + for (int i = 0; i < 9; i++) { + float dist = distance(referenceDepth, depthVec[i]); + if (dist < nearest) { + nearest = dist; + idx = i; + } + } + return idx; + +} diff --git a/data/shader/common/utility.hsh b/data/shader/common/utility.hsh index 5594ccf52..05b635280 100644 --- a/data/shader/common/utility.hsh +++ b/data/shader/common/utility.hsh @@ -130,6 +130,15 @@ float min4(vec4 value) { } +// 1 inside the screen, going to 0 at its edges over the fade distance in normalized device coordinates +float EdgeFadeOut(vec2 screenPos, float fadeDist) { + + screenPos = abs(screenPos * 2.0 - 1.0); + vec2 fadeOut = (screenPos - 1.0 + fadeDist) / fadeDist; + return saturate(1.0 - max(fadeOut.x, fadeOut.y)); + +} + vec3 Cartesian(vec2 spherical) { float sinTheta = sin(spherical.x); return normalize(vec3( diff --git a/data/shader/culling/common.hsh b/data/shader/culling/common.hsh new file mode 100644 index 000000000..b72d9edbf --- /dev/null +++ b/data/shader/culling/common.hsh @@ -0,0 +1,97 @@ +// Has to match the structures in scene/GPUScene.h + +#define INSTANCE_VISIBLE 1u +#define INSTANCE_DONT_CULL 2u +#define INSTANCE_REVERSED_WINDING 4u + +#define INVALID_HISTORY_IDX 0xFFFFFFFFu + +#define MESH_DRAWABLE 1u +#define MESH_CAST_SHADOW 2u +#define MESH_IMPOSTOR 4u +#define MESH_GEOMETRY 8u +#define MESH_DRAW_EARLY 16u + +// Has to match MeshData::maxLodCount +#define MAX_LOD_COUNT 5u + +#define DRAW_DEFAULT_WINDING 0u +#define DRAW_REVERSED_WINDING 1u +#define DRAW_IMPOSTOR 2u + +// Each view has a counter per winding and level of detail of a mesh, the one of the impostors comes after them +#define IMPOSTOR_COUNTER (2u * MAX_LOD_COUNT) +#define MESH_COUNTER_COUNT (2u * MAX_LOD_COUNT + 1u) + +// The culling result of an instance has a bit per view below its level of detail, GPUScene::maxCullViewCount views +#define RESULT_LOD_SHIFT 24u + +struct Instance { + // Rows of the global matrix + mat3x4 matrix; + uint meshIdx; + uint flags; + uint historyIdx; + // Whether the main view saw the instance in its last occlusion test + uint visibleLastFrame; +}; + +struct CullMesh { + // The w components are the distance culling of the main and the shadow passes + vec4 aabbMin; + vec4 aabbMax; + float impostorDistance; + float impostorShadowDistance; + uint flags; + // Instances with a smaller bounding sphere in pixels are culled + float minScreenSize; + // The region of the indices of the mesh in each view, shared by its levels of detail, windings and impostors + uint regionOffset; + uint regionCapacity; + uint padding0; + uint lodCount; + // Errors of the levels from 1 on divided by their pixel error, an instance uses a level while the error times its + // scale and the focal length stays below its distance + vec4 lodErrors; +}; + +uint SelectLod(CullMesh mesh, float distance, float scale, float focalLength) { + + uint lod = 0u; + float projection = scale * focalLength; + for (uint i = 1u; i < mesh.lodCount; i++) { + if (mesh.lodErrors[i - 1u] * projection > distance) + break; + lod = i; + } + return lod; + +} + +float GetMaxScale(mat3x4 matrix) { + + return max(length(vec3(matrix[0].x, matrix[1].x, matrix[2].x)), + max(length(vec3(matrix[0].y, matrix[1].y, matrix[2].y)), length(vec3(matrix[0].z, matrix[1].z, matrix[2].z)))); + +} + +struct CullView { + vec4 planes[6]; + uint shadow; + uint indexOffset; + uint padding0; + uint counterOffset; +}; + +// The counter of the draw an instance is part of in a view +uint GetDrawCounter(bool impostor, uint lod, bool reversedWinding) { + + return impostor ? IMPOSTOR_COUNTER : 2u * lod + (reversedWinding ? DRAW_REVERSED_WINDING : DRAW_DEFAULT_WINDING); + +} + +vec3 GetInstancePosition(mat3x4 matrix) { + + return vec3(matrix[0].w, matrix[1].w, matrix[2].w); + +} diff --git a/data/shader/culling/cull.csh b/data/shader/culling/cull.csh new file mode 100644 index 000000000..5915d716d --- /dev/null +++ b/data/shader/culling/cull.csh @@ -0,0 +1,299 @@ +#include + +// Counts the visible instances of all views per draw and keeps in which views an instance is visible, +// culling/indices.csh writes the indices once the counts are turned into offsets +// The main view draws the instances visible in the last frame first, OCCLUSION then tests the others against that +// depth, counts them in their own view and remembers the visibility for the next frame + +#ifdef OCCLUSION +#include <../globals.hsh> +#endif + +layout (local_size_x = 64) in; + +#ifdef OCCLUSION +layout(std430, set = 3, binding = 0) buffer Instances { +#else +layout(std430, set = 3, binding = 0) readonly buffer Instances { +#endif + Instance instances[]; +}; + +layout(std430, set = 3, binding = 1) readonly buffer Meshes { + CullMesh meshes[]; +}; + +layout(std430, set = 3, binding = 2) readonly buffer Views { + CullView views[]; +}; + +layout(std430, set = 3, binding = 3) buffer Counters { + uint counters[]; +}; + +#ifndef RAY_TRACING_INSTANCES +// Per instance the views it is visible in (x) and drawn as an impostor in (y), with its level of detail in the high bits of y +layout(std430, set = 3, binding = 4) buffer Results { + uvec2 results[]; +}; +#endif + +layout(push_constant) uniform constants { + vec4 cameraLocation; + uint instanceCount; + uint viewCount; + uint maxRayTracingInstanceCount; + uint includeObjectHistory; + // Viewport height in pixels divided by 2 * tan(fov / 2) + float focalLength; + // This view only gets the instances which were visible in the last frame + uint occlusionView; + uint firstView; + uint padding0; + ivec2 depthResolution; + int hiZLevelCount; + uint padding1; +} PushConstants; + +#ifndef RAY_TRACING_INSTANCES +// The instances of the occluded view within its frustum, starts with the indirect dispatch of the occlusion test +layout(std430, set = 3, binding = 14) buffer OcclusionInstances { + uint occlusionGroupCountX; + uint occlusionGroupCountY; + uint occlusionGroupCountZ; + uint occlusionInstanceCount; + uint occlusionInstances[]; +}; +#endif + +#ifdef OCCLUSION +// Hierarchical depth with the farthest depth in g +layout(set = 3, binding = 13) uniform sampler2D hiZTexture; + +bool IsOccluded(vec3 aabbMin, vec3 aabbMax) { + + vec2 ndcMin = vec2(1.0); + vec2 ndcMax = vec2(-1.0); + float closestDepth = 1.0; + + for (int i = 0; i < 8; i++) { + vec3 corner = vec3((i & 1) != 0 ? aabbMax.x : aabbMin.x, (i & 2) != 0 ? aabbMax.y : aabbMin.y, + (i & 4) != 0 ? aabbMax.z : aabbMin.z); + vec4 clip = globalData.pvMatrixCurrent * vec4(corner, 1.0); + // Bounds crossing the near plane can't be projected + if (clip.w <= 0.0 || clip.z <= 0.0) + return false; + + vec3 ndc = clip.xyz / clip.w; + ndcMin = min(ndcMin, ndc.xy); + ndcMax = max(ndcMax, ndc.xy); + closestDepth = min(closestDepth, ndc.z); + } + + // One pixel more, the pixels at the border of the bounds are only partly covered + ivec2 maxPixel = PushConstants.depthResolution - 1; + ivec2 pixelMin = clamp(ivec2((ndcMin * 0.5 + 0.5) * vec2(PushConstants.depthResolution)) - 1, ivec2(0), maxPixel); + ivec2 pixelMax = clamp(ivec2((ndcMax * 0.5 + 0.5) * vec2(PushConstants.depthResolution)) + 1, ivec2(0), maxPixel); + + // The bounds cover at most three texels per axis in this level + ivec2 size = pixelMax - pixelMin; + int level = findMSB(max(max(size.x, size.y), 1)); + if (level >= PushConstants.hiZLevelCount) + return false; + + ivec2 texelMin = pixelMin >> level; + ivec2 texelMax = pixelMax >> level; + for (int y = texelMin.y; y <= texelMax.y; y++) { + for (int x = texelMin.x; x <= texelMax.x; x++) { + if (closestDepth <= texelFetch(hiZTexture, ivec2(x, y), level).g) + return false; + } + } + + return true; + +} +#endif + +#ifdef RAY_TRACING_INSTANCES +#include +#elif !defined(OCCLUSION) +// Closest distances (float bits) per mesh for the streaming: drawn instances to their bounds divided by their scale +// for the textures, all instances to their positions or centers for the meshes +layout(std430, set = 3, binding = 12) buffer MeshDistances { + uint meshDistances[]; +}; + +void WriteMeshDistance(uint idx, float distance) { + + uint distanceBits = floatBitsToUint(distance); + // Most instances are further away than the closest one, reading first skips their atomics + if (distanceBits < meshDistances[idx]) + atomicMin(meshDistances[idx], distanceBits); + +} +#endif + +bool Intersects(vec3 aabbMin, vec3 aabbMax, CullView view) { + + for (int i = 0; i < 6; i++) { + vec4 plane = view.planes[i]; + vec3 s = mix(aabbMin, aabbMax, greaterThanEqual(plane.xyz, vec3(0.0))); + if (plane.w + dot(plane.xyz, s) < 0.0) + return false; + } + + return true; + +} + +float DistanceSqr(vec3 a, vec3 b) { + + vec3 diff = a - b; + return dot(diff, diff); + +} + +void main() { + +#ifdef OCCLUSION + if (gl_GlobalInvocationID.x >= occlusionInstanceCount) + return; + uint idx = occlusionInstances[gl_GlobalInvocationID.x]; +#else + uint idx = gl_GlobalInvocationID.x; + if (idx >= PushConstants.instanceCount) + return; +#ifndef RAY_TRACING_INSTANCES + // Instances which return early aren't visible in any view + results[idx] = uvec2(0u); +#endif +#endif + + Instance instance = instances[idx]; + bool dontCull = (instance.flags & INSTANCE_DONT_CULL) != 0u; + if ((instance.flags & INSTANCE_VISIBLE) == 0u && !dontCull) + return; + + CullMesh mesh = meshes[instance.meshIdx]; + + vec3 localCenter = 0.5 * (mesh.aabbMin.xyz + mesh.aabbMax.xyz); + vec3 localExtent = 0.5 * (mesh.aabbMax.xyz - mesh.aabbMin.xyz); + + mat3x4 matrix = instance.matrix; + vec3 center = vec4(localCenter, 1.0) * matrix; + vec3 extent = vec3(dot(abs(matrix[0].xyz), localExtent), dot(abs(matrix[1].xyz), localExtent), + dot(abs(matrix[2].xyz), localExtent)); + + vec3 cameraLocation = PushConstants.cameraLocation.xyz; + float centerDistanceSqr = DistanceSqr(center, cameraLocation); + float positionDistanceSqr = DistanceSqr(GetInstancePosition(matrix), cameraLocation); + float boundsDistance = length(max(abs(cameraLocation - center) - extent, vec3(0.0))); + float maxScale = GetMaxScale(matrix); + + bool geometry = (mesh.flags & MESH_GEOMETRY) != 0u; + + // Instances smaller than the minimum screen size are culled, from the ray traced scene as well + float screenSizeSqr = 4.0 * dot(extent, extent) * PushConstants.focalLength * PushConstants.focalLength; + float minScreenSizeSqr = mesh.minScreenSize * mesh.minScreenSize * centerDistanceSqr; + bool largeEnough = dontCull || screenSizeSqr >= minScreenSizeSqr; + +#ifndef RAY_TRACING_INSTANCES +#ifndef OCCLUSION + // The streaming hears of instances from half the minimum screen size on, so their meshes are resident once they + // get big enough + bool requested = dontCull || 4.0 * screenSizeSqr >= minScreenSizeSqr; + + // Meshes which aren't drawable need the distances as well, to be loaded again. Instances that are never culled + // need their geometry at any distance + if (requested) + WriteMeshDistance(2u * instance.meshIdx + 1u, dontCull ? 0.0 : sqrt(min(positionDistanceSqr, centerDistanceSqr))); + + bool withinCullingDistance = dontCull || centerDistanceSqr <= mesh.aabbMin.w * mesh.aabbMin.w; + + // Instances drawn as impostors or culled by distance don't need the textures of the mesh + bool impostorOnly = (mesh.flags & MESH_IMPOSTOR) != 0u && + (!geometry || positionDistanceSqr >= mesh.impostorDistance * mesh.impostorDistance); + if (geometry && largeEnough && !impostorOnly && withinCullingDistance) + WriteMeshDistance(2u * instance.meshIdx, boundsDistance / maxScale); +#endif +#endif + + if ((mesh.flags & MESH_DRAWABLE) == 0u || !largeEnough) + return; + + // All views and the ray traced instance use the same level of detail, shadows of another level would fall onto it. + // The occlusion test keeps the one of the first culling, the indices are written with it +#ifdef OCCLUSION + uvec2 result = results[idx]; + uint lod = result.y >> RESULT_LOD_SHIFT; +#else + uint lod = mesh.lodCount > 1u ? SelectLod(mesh, boundsDistance, maxScale, PushConstants.focalLength) : 0u; +#endif + +#ifdef RAY_TRACING_INSTANCES + if ((instance.flags & INSTANCE_VISIBLE) != 0u) + WriteRayTracingInstance(instance, lod, positionDistanceSqr, PushConstants.maxRayTracingInstanceCount, + PushConstants.includeObjectHistory > 0u); + return; +#endif + + bool reversedWinding = (instance.flags & INSTANCE_REVERSED_WINDING) != 0u; +#ifndef OCCLUSION + uvec2 result = uvec2(0u, lod << RESULT_LOD_SHIFT); +#endif + + bool visibleLastFrame = instance.visibleLastFrame > 0u; + bool drawnEarly = (mesh.flags & MESH_DRAW_EARLY) != 0u && (visibleLastFrame || dontCull); + for (uint i = PushConstants.firstView; i < PushConstants.firstView + PushConstants.viewCount; i++) { + CullView view = views[i]; + bool shadow = view.shadow > 0u; + if (shadow && (mesh.flags & MESH_CAST_SHADOW) == 0u) + continue; + + if (!dontCull) { + float cullingDistance = shadow ? mesh.aabbMax.w : mesh.aabbMin.w; + if (centerDistanceSqr > cullingDistance * cullingDistance) + continue; + if (!Intersects(center - extent, center + extent, view)) + continue; + } + +#ifdef OCCLUSION + bool visible = dontCull || !IsOccluded(center - extent, center + extent); + if (visible != visibleLastFrame) + instances[idx].visibleLastFrame = visible ? 1u : 0u; + if (!visible || drawnEarly) + continue; +#elif !defined(RAY_TRACING_INSTANCES) + if (i == PushConstants.occlusionView) { + uint occlusionIdx = atomicAdd(occlusionInstanceCount, 1u); + occlusionInstances[occlusionIdx] = idx; + if (occlusionIdx % 64u == 0u) { + atomicAdd(occlusionGroupCountX, 1u); + occlusionGroupCountY = 1u; + occlusionGroupCountZ = 1u; + } + + if (!drawnEarly) + continue; + } +#endif + + float impostorDistance = shadow ? mesh.impostorShadowDistance : mesh.impostorDistance; + // Meshes without resident geometry are drawn as impostors only + bool impostor = (mesh.flags & MESH_IMPOSTOR) != 0u && + (!geometry || positionDistanceSqr >= impostorDistance * impostorDistance); + + uint counterIdx = view.counterOffset + instance.meshIdx * MESH_COUNTER_COUNT; + atomicAdd(counters[counterIdx + GetDrawCounter(impostor, lod, reversedWinding)], 1u); + result.x |= 1u << i; + if (impostor) + result.y |= 1u << i; + } + +#ifndef RAY_TRACING_INSTANCES + results[idx] = result; +#endif + +} diff --git a/data/shader/culling/draws.csh b/data/shader/culling/draws.csh new file mode 100644 index 000000000..232b50e27 --- /dev/null +++ b/data/shader/culling/draws.csh @@ -0,0 +1,84 @@ +#include + +// Writes the indirect draw commands of the culled instances, impostors are drawn without indices + +layout (local_size_x = 64) in; + +struct DrawRequest { + uint meshIdx; + uint view; + uint type; + uint indexCount; + uint firstIndex; + uint lod; + int vertexOffset; + uint padding0; +}; + +layout(std430, set = 3, binding = 0) readonly buffer Meshes { + CullMesh meshes[]; +}; + +layout(std430, set = 3, binding = 1) readonly buffer Views { + CullView views[]; +}; + +layout(std430, set = 3, binding = 2) readonly buffer Counters { + uint counters[]; +}; + +layout(std430, set = 3, binding = 3) readonly buffer Requests { + DrawRequest requests[]; +}; + +layout(std430, set = 3, binding = 4) writeonly buffer Commands { + uint commands[]; +}; + +// The end of the indices of each draw +layout(std430, set = 3, binding = 5) readonly buffer Offsets { + uint offsets[]; +}; + +layout(push_constant) uniform constants { + uint firstRequest; + uint requestCount; +} PushConstants; + +void main() { + + if (gl_GlobalInvocationID.x >= PushConstants.requestCount) + return; + + uint idx = PushConstants.firstRequest + gl_GlobalInvocationID.x; + DrawRequest request = requests[idx]; + CullMesh mesh = meshes[request.meshIdx]; + CullView view = views[request.view]; + + uint counterIdx = view.counterOffset + request.meshIdx * MESH_COUNTER_COUNT + + GetDrawCounter(request.type == DRAW_IMPOSTOR, request.lod, request.type == DRAW_REVERSED_WINDING); + uint instanceCount = counters[counterIdx]; + uint firstInstance = offsets[counterIdx] - instanceCount; + + // Indices beyond the region weren't written + uint regionEnd = view.indexOffset + mesh.regionOffset + mesh.regionCapacity; + instanceCount = min(instanceCount, regionEnd - min(firstInstance, regionEnd)); + + uint offset = idx * 5u; + if (request.type == DRAW_IMPOSTOR) { + // A quad per impostor + commands[offset + 0u] = 4u; + commands[offset + 1u] = instanceCount; + commands[offset + 2u] = 0u; + commands[offset + 3u] = firstInstance; + commands[offset + 4u] = 0u; + } + else { + commands[offset + 0u] = request.indexCount; + commands[offset + 1u] = instanceCount; + commands[offset + 2u] = request.firstIndex; + commands[offset + 3u] = uint(request.vertexOffset); + commands[offset + 4u] = firstInstance; + } + +} diff --git a/data/shader/culling/indices.csh b/data/shader/culling/indices.csh new file mode 100644 index 000000000..9ef85532e --- /dev/null +++ b/data/shader/culling/indices.csh @@ -0,0 +1,83 @@ +#include + +// Writes the indices of the visible instances at the offsets of their draws, each offset ends up behind its draw +// OCCLUSION writes the instances the occlusion test counted + +layout (local_size_x = 64) in; + +layout(std430, set = 3, binding = 0) readonly buffer Instances { + Instance instances[]; +}; + +layout(std430, set = 3, binding = 1) readonly buffer Meshes { + CullMesh meshes[]; +}; + +layout(std430, set = 3, binding = 2) readonly buffer Views { + CullView views[]; +}; + +layout(std430, set = 3, binding = 3) readonly buffer Results { + uvec2 results[]; +}; + +layout(std430, set = 3, binding = 4) buffer Offsets { + uint offsets[]; +}; + +layout(std430, set = 3, binding = 5) writeonly buffer Indices { + uint indices[]; +}; + +#ifdef OCCLUSION +layout(std430, set = 3, binding = 6) readonly buffer OcclusionInstances { + uint occlusionGroupCountX; + uint occlusionGroupCountY; + uint occlusionGroupCountZ; + uint occlusionInstanceCount; + uint occlusionInstances[]; +}; +#endif + +layout(push_constant) uniform constants { + uint firstView; + uint viewCount; + uint meshCount; + uint instanceCount; +} PushConstants; + +void main() { + +#ifdef OCCLUSION + if (gl_GlobalInvocationID.x >= occlusionInstanceCount) + return; + uint idx = occlusionInstances[gl_GlobalInvocationID.x]; +#else + uint idx = gl_GlobalInvocationID.x; + if (idx >= PushConstants.instanceCount) + return; +#endif + + uvec2 result = results[idx]; + uint viewMask = ((1u << PushConstants.viewCount) - 1u) << PushConstants.firstView; + if ((result.x & viewMask) == 0u) + return; + + Instance instance = instances[idx]; + CullMesh mesh = meshes[instance.meshIdx]; + uint lod = result.y >> RESULT_LOD_SHIFT; + bool reversedWinding = (instance.flags & INSTANCE_REVERSED_WINDING) != 0u; + + for (uint i = PushConstants.firstView; i < PushConstants.firstView + PushConstants.viewCount; i++) { + if ((result.x & (1u << i)) == 0u) + continue; + + CullView view = views[i]; + bool impostor = (result.y & (1u << i)) != 0u; + uint counterIdx = view.counterOffset + instance.meshIdx * MESH_COUNTER_COUNT + GetDrawCounter(impostor, lod, reversedWinding); + uint position = atomicAdd(offsets[counterIdx], 1u); + if (position < view.indexOffset + mesh.regionOffset + mesh.regionCapacity) + indices[position] = idx; + } + +} diff --git a/data/shader/culling/instances.hsh b/data/shader/culling/instances.hsh new file mode 100644 index 000000000..a1fa8f709 --- /dev/null +++ b/data/shader/culling/instances.hsh @@ -0,0 +1,31 @@ +#include + +layout(std430, set = 1, binding = 20) readonly buffer Instances { + Instance instances[]; +}; + +// Matrices of the last frame of the instances which moved +layout(std430, set = 1, binding = 21) readonly buffer InstanceHistory { + mat3x4 instanceHistory[]; +}; + +layout(std430, set = 1, binding = 22) readonly buffer InstanceIndices { + uint instanceIndices[]; +}; + +layout(std430, set = 1, binding = 23) readonly buffer ImpostorInstanceIndices { + uint impostorInstanceIndices[]; +}; + +mat4 GetInstanceMatrix(uint idx) { + + return mat4(transpose(instances[idx].matrix)); + +} + +mat4 GetLastInstanceMatrix(uint idx) { + + uint historyIdx = instances[idx].historyIdx; + return historyIdx != INVALID_HISTORY_IDX ? mat4(transpose(instanceHistory[historyIdx])) : GetInstanceMatrix(idx); + +} diff --git a/data/shader/culling/offsets.csh b/data/shader/culling/offsets.csh new file mode 100644 index 000000000..69f425b5c --- /dev/null +++ b/data/shader/culling/offsets.csh @@ -0,0 +1,46 @@ +#include + +// Turns the counts of the draws of each mesh and view into offsets in the region of the mesh + +layout (local_size_x = 64) in; + +layout(std430, set = 3, binding = 0) readonly buffer Meshes { + CullMesh meshes[]; +}; + +layout(std430, set = 3, binding = 1) readonly buffer Views { + CullView views[]; +}; + +layout(std430, set = 3, binding = 2) readonly buffer Counters { + uint counters[]; +}; + +layout(std430, set = 3, binding = 3) writeonly buffer Offsets { + uint offsets[]; +}; + +layout(push_constant) uniform constants { + uint firstView; + uint viewCount; + uint meshCount; + uint instanceCount; +} PushConstants; + +void main() { + + uint idx = gl_GlobalInvocationID.x; + if (idx >= PushConstants.viewCount * PushConstants.meshCount) + return; + + uint meshIdx = idx % PushConstants.meshCount; + CullView view = views[PushConstants.firstView + idx / PushConstants.meshCount]; + + uint counterIdx = view.counterOffset + meshIdx * MESH_COUNTER_COUNT; + uint offset = view.indexOffset + meshes[meshIdx].regionOffset; + for (uint i = 0u; i < MESH_COUNTER_COUNT; i++) { + offsets[counterIdx + i] = offset; + offset += counters[counterIdx + i]; + } + +} diff --git a/data/shader/culling/rtinstances.hsh b/data/shader/culling/rtinstances.hsh new file mode 100644 index 000000000..e2a918017 --- /dev/null +++ b/data/shader/culling/rtinstances.hsh @@ -0,0 +1,120 @@ +// Writes the hardware ray tracing instances of the scene instances within the ray tracing distance of their meshes. +// The instances written on the host (terrain and animated meshes) come first. RTMesh has to match GPURTMesh in +// RayTracingWorld.h, TLASInstance VkAccelerationStructureInstanceKHR and BVHInstance GPUBVHInstance in RTStructures.h + +#define RT_MESH_USABLE 1u +#define RT_MESH_FORCE_OPAQUE 2u + +struct RTMesh { + uint blasOffset; + int materialOffset; + uint mask; + uint flags; + float cullingDistanceSqr; + // Nearer instances are deformed and written on the host + float deformDistanceSqr; + uvec2 blasAddress; + // First record of the mesh in the hit region of ray tracing pipelines + uint hitRecordOffset; + // The levels of detail from 1 on follow each other from this mesh on, lodCount includes level 0 + uint lodOffset; + uint lodCount; + uint padding0; +}; + +struct TLASInstance { + vec4 transform[3]; + uint customIndexAndMask; + uint bindingOffsetAndFlags; + uvec2 blasAddress; +}; + +struct BVHInstance { + mat3x4 inverseMatrix; + int meshOffset; + int materialOffset; + int nextInstance; + uint mask; + uvec2 deformedVertices; + uvec2 meshIndices; +}; + +layout(std430, set = 3, binding = 6) readonly buffer InstanceHistory { + mat3x4 instanceHistory[]; +}; + +layout(std430, set = 3, binding = 7) readonly buffer RTMeshes { + RTMesh rtMeshes[]; +}; + +layout(std430, set = 3, binding = 8) buffer RTInstanceCounter { + uint rtInstanceCounter; +}; + +layout(std430, set = 3, binding = 9) writeonly buffer TLASInstances { + TLASInstance tlasInstances[]; +}; + +layout(std430, set = 3, binding = 10) writeonly buffer BVHInstances { + BVHInstance bvhInstances[]; +}; + +layout(std430, set = 3, binding = 11) writeonly buffer LastMatrices { + mat3x4 lastMatrices[]; +}; + +// VK_GEOMETRY_INSTANCE_TRIANGLE_FACING_CULL_DISABLE_BIT_KHR and VK_GEOMETRY_INSTANCE_FORCE_OPAQUE_BIT_KHR +const uint cullDisableFlag = 1u; +const uint forceOpaqueFlag = 4u; + +void WriteRayTracingInstance(Instance instance, uint lod, float distanceSqr, uint maxInstanceCount, bool includeObjectHistory) { + + RTMesh mesh = rtMeshes[instance.meshIdx]; + if ((mesh.flags & RT_MESH_USABLE) == 0u || distanceSqr > mesh.cullingDistanceSqr || distanceSqr < mesh.deformDistanceSqr) + return; + + // Levels whose BLAS isn't usable yet fall back to the finest one that is + lod = min(lod, mesh.lodCount - 1u); + if (lod > 0u) + mesh = rtMeshes[mesh.lodOffset + lod - 1u]; + + uint instanceIdx = atomicAdd(rtInstanceCounter, 1u); + if (instanceIdx >= maxInstanceCount) + return; + + mat3x4 matrix = instance.matrix; + + TLASInstance tlasInstance; + tlasInstance.transform[0] = matrix[0]; + tlasInstance.transform[1] = matrix[1]; + tlasInstance.transform[2] = matrix[2]; + tlasInstance.customIndexAndMask = (mesh.blasOffset & 0xFFFFFFu) | (mesh.mask << 24u); + uint flags = cullDisableFlag | ((mesh.flags & RT_MESH_FORCE_OPAQUE) != 0u ? forceOpaqueFlag : 0u); + tlasInstance.bindingOffsetAndFlags = (mesh.hitRecordOffset & 0xFFFFFFu) | (flags << 24u); + tlasInstance.blasAddress = mesh.blasAddress; + tlasInstances[instanceIdx] = tlasInstance; + + vec3 position = GetInstancePosition(matrix); + mat3 rotationScale = transpose(mat3(matrix[0].xyz, matrix[1].xyz, matrix[2].xyz)); + mat3 inverseRotationScale = inverse(rotationScale); + vec3 inverseTranslation = -(inverseRotationScale * position); + mat3 inverseRows = transpose(inverseRotationScale); + + BVHInstance bvhInstance; + bvhInstance.inverseMatrix = mat3x4(vec4(inverseRows[0], inverseTranslation.x), + vec4(inverseRows[1], inverseTranslation.y), vec4(inverseRows[2], inverseTranslation.z)); + bvhInstance.meshOffset = int(mesh.blasOffset); + bvhInstance.materialOffset = mesh.materialOffset; + bvhInstance.nextInstance = 0; + bvhInstance.mask = mesh.mask; + // Deformed instances are written on the host + bvhInstance.deformedVertices = uvec2(0u); + bvhInstance.meshIndices = uvec2(0u); + bvhInstances[instanceIdx] = bvhInstance; + + if (includeObjectHistory) { + lastMatrices[instanceIdx] = instance.historyIdx != INVALID_HISTORY_IDX ? + instanceHistory[instance.historyIdx] : matrix; + } + +} diff --git a/data/shader/culling/scatter.csh b/data/shader/culling/scatter.csh new file mode 100644 index 000000000..3eb18090f --- /dev/null +++ b/data/shader/culling/scatter.csh @@ -0,0 +1,34 @@ +#include + +layout (local_size_x = 64) in; + +layout(std430, set = 3, binding = 0) buffer Instances { + Instance instances[]; +}; + +layout(std430, set = 3, binding = 1) readonly buffer Updates { + Instance updates[]; +}; + +layout(std430, set = 3, binding = 2) readonly buffer UpdateIndices { + uint updateIndices[]; +}; + +layout(push_constant) uniform constants { + uint updateCount; +} PushConstants; + +void main() { + + uint idx = gl_GlobalInvocationID.x; + if (idx >= PushConstants.updateCount) + return; + + uint instanceIdx = updateIndices[idx]; + Instance update = updates[idx]; + // Has to match GPUScene::keepVisibleLastFrame + if (update.visibleLastFrame == 2u) + update.visibleLastFrame = instances[instanceIdx].visibleLastFrame; + instances[instanceIdx] = update; + +} diff --git a/data/shader/ddgi/copyEdge.csh b/data/shader/ddgi/copyEdge.csh deleted file mode 100644 index 113e02b2a..000000000 --- a/data/shader/ddgi/copyEdge.csh +++ /dev/null @@ -1,69 +0,0 @@ -layout (local_size_x = 8, local_size_y = 8) in; - -#if defined(IRRADIANCE) -layout (set = 3, binding = 0, rgb10_a2) uniform image2DArray image; -#elif defined(RADIANCE) -layout (set = 3, binding = 0, rgb10_a2) uniform image2DArray image; -#else -layout (set = 3, binding = 0, rg16f) uniform image2DArray image; -#endif - -layout(push_constant) uniform constants { - int probeRes; -} PushConstants; - -ivec2 OctMapStitch(ivec2 pix, bool leftBorder, bool rightBorder, - bool upBorder, bool downBorder) { - // Check if we're in one of the corners - if (leftBorder && upBorder) { - return ivec2(PushConstants.probeRes, PushConstants.probeRes); - } - else if (rightBorder && upBorder) { - return ivec2(1, PushConstants.probeRes); - } - else if (leftBorder && downBorder) { - return ivec2(PushConstants.probeRes, 1); - } - else if (rightBorder && downBorder) { - return ivec2(1, 1); - } - // Check on which side we are - if (upBorder) { - return ivec2(PushConstants.probeRes - pix.x + 1, 1); - } - if (downBorder) { - return ivec2(PushConstants.probeRes - pix.x + 1, PushConstants.probeRes); - } - if (leftBorder) { - return ivec2(1, PushConstants.probeRes - pix.y + 1); - } - if (rightBorder) { - return ivec2(PushConstants.probeRes, PushConstants.probeRes - pix.y + 1); - } -} - -void main() { - - ivec2 pixel = ivec2(gl_GlobalInvocationID); - if (pixel.x > imageSize(image).x || - pixel.y > imageSize(image).y) - return; - - int probeResWithBorder = PushConstants.probeRes + 2; - ivec2 pix = pixel % ivec2(probeResWithBorder); - - bool leftBorder = pix.x == 0; - bool rightBorder = pix.x == probeResWithBorder - 1; - - bool upBorder = pix.y == 0; - bool downBorder = pix.y == probeResWithBorder - 1; - - if (leftBorder || rightBorder || upBorder || downBorder) { - ivec2 offset = OctMapStitch(pix, leftBorder, rightBorder, upBorder, downBorder); - ivec2 base = (pixel / ivec2(probeResWithBorder)) * probeResWithBorder; - - vec4 color = imageLoad(image, ivec3(base + offset, int(gl_GlobalInvocationID.z))); - imageStore(image, ivec3(pixel, int(gl_GlobalInvocationID.z)), color); - } - -} \ No newline at end of file diff --git a/data/shader/ddgi/ddgi.hsh b/data/shader/ddgi/ddgi.hsh index a1788a9d7..8da2fbbd7 100644 --- a/data/shader/ddgi/ddgi.hsh +++ b/data/shader/ddgi/ddgi.hsh @@ -60,6 +60,10 @@ layout(std140, set = 2, binding = 27) uniform DDGIBuffer { int volumeEnabled; float volumeStorageScale; + + // Bring the gamma encoded history and the stored probes to the current pre-exposure + float historyExposureScale; + float volumeExposureScale; } ddgiData; struct RayHit { @@ -303,7 +307,7 @@ vec4 GetLocalIrradianceFromCascade(vec3 P, vec3 V, vec3 N, vec3 geometryNormal, : vec4(sqr(sumIrradianceIgnoredState / sumWeightIgnoredState), 0.0); // Due to the texture format we loose a bit of energy - irradiance *= 1.0989 / ddgiData.volumeStorageScale; + irradiance *= 1.0989 * ddgiData.volumeExposureScale / ddgiData.volumeStorageScale; return irradiance; @@ -461,7 +465,7 @@ vec4 GetLocalRadianceFromCascade(vec3 P, vec3 V, vec3 N, vec3 geometryNormal, in : vec4(sqr(sumIrradianceIgnoredState / sumWeightIgnoredState), 0.0); // Due to the texture format we loose a bit of energy - irradiance *= 1.0989 / ddgiData.volumeStorageScale; + irradiance *= 1.0989 * ddgiData.volumeExposureScale / ddgiData.volumeStorageScale; return irradiance; @@ -609,19 +613,24 @@ void GetLocalProbeLightingFromCascade(vec3 P, vec3 V, vec3 N, vec3 L, vec3 geome vec3 irrCoord = GetProbeCoord(gridCell, cascadeIndex, irrOctCoord, irrRes, irrTexelSize, ddgiData.volumeIrradianceRes); irradiance.rgb = pow(textureLod(irradianceVolume, irrCoord, 0).rgb, vec3(0.5 * ddgiData.volumeGamma)); +#ifdef RADIANCE_VOLUME vec3 radCoord = GetProbeCoord(gridCell, cascadeIndex, radOctCoord, radRes, radTexelSize, ddgiData.volumeRadianceRes); radiance.rgb = pow(textureLod(radianceVolume, radCoord, 0).rgb, vec3(0.5 * ddgiData.volumeGamma)); +#endif float weightIgnoredState = weight; weight = probeState != PROBE_STATE_INACTIVE ? weight : 0.0; sumIrradiance += weight * irradiance.rgb; - sumRadiance += weight * radiance.rgb; sumWeight += weight; sumIrradianceIgnoredState += weightIgnoredState * irradiance.rgb; - sumRadianceIgnoredState += weightIgnoredState * radiance.rgb; sumWeightIgnoredState += weightIgnoredState; + +#ifdef RADIANCE_VOLUME + sumRadiance += weight * radiance.rgb; + sumRadianceIgnoredState += weightIgnoredState * radiance.rgb; +#endif } if (sumWeight == 0.0 && sumWeightIgnoredState == 0.0) return; @@ -630,13 +639,13 @@ void GetLocalProbeLightingFromCascade(vec3 P, vec3 V, vec3 N, vec3 L, vec3 geome irradiance = sumWeight > 0.0 ? vec4(sqr(sumIrradiance / sumWeight), 0.0) : vec4(sqr(sumIrradianceIgnoredState / sumWeightIgnoredState), 0.0); // Due to the texture format we loose a bit of energy - irradiance *= 1.0989 / ddgiData.volumeStorageScale; + irradiance *= 1.0989 * ddgiData.volumeExposureScale / ddgiData.volumeStorageScale; #ifdef RADIANCE_VOLUME // If no probes are activated for the given geometry, at least use the information available radiance = sumWeight > 0.0 ? vec4(sqr(sumRadiance / sumWeight), 0.0) : vec4(sqr(sumRadianceIgnoredState / sumWeightIgnoredState), 0.0); - radiance *= 1.0989 / ddgiData.volumeStorageScale; + radiance *= 1.0989 * ddgiData.volumeExposureScale / ddgiData.volumeStorageScale; #else radiance = irradiance; #endif diff --git a/data/shader/ddgi/probeUpdate.csh b/data/shader/ddgi/probeUpdate.csh index a43d2a4b5..d7df52200 100644 --- a/data/shader/ddgi/probeUpdate.csh +++ b/data/shader/ddgi/probeUpdate.csh @@ -24,7 +24,7 @@ layout (local_size_x = 6, local_size_y = 6) in; #ifdef LOWER_RES_RADIANCE layout (local_size_x = 14, local_size_y = 14) in; #else -layout (local_size_x = 30, local_size_y = 30) in; +layout (local_size_x = 30, local_size_y = 10) in; #endif #else #ifdef LOWER_RES_MOMENTS @@ -34,12 +34,10 @@ layout (local_size_x = 14, local_size_y = 14) in; #endif #endif -#if defined(IRRADIANCE) -layout (set = 3, binding = 0, rgb10_a2) writeonly uniform image2DArray irradiance; -#elif defined(RADIANCE) -layout (set = 3, binding = 0, rgb10_a2) writeonly uniform image2DArray radiance; +#if defined(IRRADIANCE) || defined(RADIANCE) +layout (set = 3, binding = 0, rgb10_a2) writeonly uniform image2DArray probeImage; #else -layout (set = 3, binding = 0, rg16f) writeonly uniform image2DArray moment; +layout (set = 3, binding = 0, rg16f) writeonly uniform image2DArray probeImage; #endif layout(std430, set = 3, binding = 1) buffer RayHits { @@ -56,6 +54,13 @@ layout(std430, set = 3, binding = 3) buffer HistoryProbeOffsets { const uint sharedSize = 128; +#if defined(RADIANCE) && !defined(LOWER_RES_RADIANCE) +// Large probes are split into slices of rows, one work group each, such that several groups fit on a compute unit +const int probeSliceCount = 3; +#else +const int probeSliceCount = 1; +#endif + #if defined(IRRADIANCE) || defined(RADIANCE) struct RayData { // This seems to be a better layout than two vec3's @@ -76,12 +81,86 @@ struct RayData { shared RayData rayData[sharedSize]; -vec4 GetHistoryFromHigherCascade(ivec2 pixel, int cascadeIndex) { +#ifdef RADIANCE +// Each ray is linked into the lists of the texels within its weight cone, such that a texel only iterates its own rays +#ifdef LOWER_RES_RADIANCE +const int rayTexelReach = 1; +#else +const int rayTexelReach = 2; +#endif +const int rayTexelWidth = 2 * rayTexelReach + 1; +const uint texelsPerRay = uint(rayTexelWidth * rayTexelWidth); +const uint invalidRayNode = 0xFFFFFFFFu; +// Only rays within ~7 degrees pass the weight threshold +const float radianceCosThreshold = 0.992; + +shared AeF16x4 texelDirections[gl_WorkGroupSize.x * gl_WorkGroupSize.y]; +shared uint texelRayHeads[gl_WorkGroupSize.x * gl_WorkGroupSize.y]; +shared ivec2 rayTexels[sharedSize]; +shared uint rayNodeNext[sharedSize * texelsPerRay]; + +// Maps a texel outside of the octahedral map to the adjacent texel across the fold +ivec2 WrapOctahedronTexel(ivec2 texel, ivec2 res) { + + if (texel.x < 0 || texel.x >= res.x) { + texel.x = texel.x < 0 ? -texel.x - 1 : 2 * res.x - 1 - texel.x; + texel.y = res.y - 1 - texel.y; + } + if (texel.y < 0 || texel.y >= res.y) { + texel.y = texel.y < 0 ? -texel.y - 1 : 2 * res.y - 1 - texel.y; + texel.x = res.x - 1 - texel.x; + } + + return texel; + +} + +// Each node is a pair of a ray and a texel in the neighborhood of the ray's texel +void LinkRayNode(uint node, ivec2 res, int sliceOffset) { + + uint rayIdx = node / texelsPerRay; + uint neighbor = node % texelsPerRay; + + ivec2 rayTexel = rayTexels[rayIdx]; + ivec2 texel = rayTexel + ivec2(neighbor % uint(rayTexelWidth), neighbor / uint(rayTexelWidth)) - ivec2(rayTexelReach); + ivec2 wrappedTexel = WrapOctahedronTexel(texel, res); + // Near the middle of an edge the fold maps back into the neighborhood, link these texels once + if (wrappedTexel != texel && all(lessThanEqual(abs(wrappedTexel - rayTexel), ivec2(rayTexelReach)))) + return; - ivec3 workGroup = ivec3(gl_WorkGroupID.xyz); - workGroup.y %= ddgiData.volumeProbeCount.y; + ivec2 sliceTexel = wrappedTexel - ivec2(0, sliceOffset); + if (sliceTexel.y < 0 || sliceTexel.y >= int(gl_WorkGroupSize.y)) + return; - vec3 probePosition = vec3(workGroup) * ddgiData.cascades[cascadeIndex].cellSize.xyz + ddgiData.cascades[cascadeIndex].volumeMin.xyz; + uint texelIdx = uint(sliceTexel.y * res.x + sliceTexel.x); + if (dot(texelDirections[texelIdx].rgb, rayData[rayIdx].direction.rgb) < AeF16(radianceCosThreshold)) + return; + + rayNodeNext[node] = atomicExchange(texelRayHeads[texelIdx], node); + +} + +void AccumulateRadiance(uint rayIdx, AeF16x3 N, bool reset, inout AeF16x4 result) { + + AeF16 cosTheta = dot(N, rayData[rayIdx].direction.rgb); + if (!reset && cosTheta < AeF16(radianceCosThreshold)) + return; + + AeF16 weight = pow(max(AeF16(0.0), cosTheta), AeF16(256.0)); + + AeF16x3 radiance = rayData[rayIdx].radiance.xyz; + + if (reset || weight > 0.15) + result += AeF16x4(radiance, AeF16(1.0)) * weight; + +} +#endif + +vec4 GetHistoryFromHigherCascade(ivec2 pixel, ivec3 probeGroup, int cascadeIndex) { + + probeGroup.y %= ddgiData.volumeProbeCount.y; + + vec3 probePosition = vec3(probeGroup) * ddgiData.cascades[cascadeIndex].cellSize.xyz + ddgiData.cascades[cascadeIndex].volumeMin.xyz; // Note: Cascades are orderd from biggest (index 0) to smallest (index cascadeCount - 1) cascadeIndex = max(cascadeIndex - 1, 0); @@ -119,16 +198,47 @@ vec4 GetHistoryFromHigherCascade(ivec2 pixel, int cascadeIndex) { } +// Border texels repeat the mirrored interior texels of the same edge, such that bilinear filtering wraps around the octahedron +void StoreProbeTexel(ivec2 pix, ivec2 res, ivec2 resOffset, int layer, vec4 value) { + + ivec2 tileOffset = resOffset - ivec2(1); + ivec2 texel = pix + ivec2(1); + ivec2 mirrored = res + ivec2(1) - texel; + + imageStore(probeImage, ivec3(tileOffset + texel, layer), value); + + if (texel.y == 1) + imageStore(probeImage, ivec3(tileOffset + ivec2(mirrored.x, 0), layer), value); + if (texel.y == res.y) + imageStore(probeImage, ivec3(tileOffset + ivec2(mirrored.x, res.y + 1), layer), value); + if (texel.x == 1) + imageStore(probeImage, ivec3(tileOffset + ivec2(0, mirrored.y), layer), value); + if (texel.x == res.x) + imageStore(probeImage, ivec3(tileOffset + ivec2(res.x + 1, mirrored.y), layer), value); + + bool cornerX = texel.x == 1 || texel.x == res.x; + bool cornerY = texel.y == 1 || texel.y == res.y; + if (cornerX && cornerY) { + ivec2 corner = mix(ivec2(0), res + ivec2(1), equal(texel, ivec2(1))); + imageStore(probeImage, ivec3(tileOffset + corner, layer), value); + } + +} + void main() { - uint baseIdx = Flatten3D(ivec3(gl_WorkGroupID.xzy), ivec3(gl_NumWorkGroups.xzy)); + ivec3 probeGroup = ivec3(int(gl_WorkGroupID.x) / probeSliceCount, gl_WorkGroupID.yz); + ivec3 probeGroupCount = ivec3(int(gl_NumWorkGroups.x) / probeSliceCount, gl_NumWorkGroups.yz); + int sliceOffset = (int(gl_WorkGroupID.x) % probeSliceCount) * int(gl_WorkGroupSize.y); + + uint baseIdx = Flatten3D(probeGroup.xzy, probeGroupCount.xzy); int cascadeIndex = GetProbeCascadeIndex(baseIdx); bool reset; ivec3 historyProbeCoord; - GetProbeHistoryInfo(ivec3(gl_WorkGroupID.xyz), cascadeIndex, historyProbeCoord, reset); + GetProbeHistoryInfo(probeGroup, cascadeIndex, historyProbeCoord, reset); - uint historyBaseIdx = Flatten3D(ivec3(historyProbeCoord.xzy), ivec3(gl_NumWorkGroups.xzy)); + uint historyBaseIdx = Flatten3D(ivec3(historyProbeCoord.xzy), probeGroupCount.xzy); uint probeState = floatBitsToUint(historyProbeStates[historyBaseIdx].x); float probeAge = probeStates[baseIdx].w; @@ -147,13 +257,16 @@ void main() { ivec2 res = ivec2(ddgiData.volumeMomentsRes); #endif - ivec2 pix = ivec2(gl_LocalInvocationID); + ivec2 pix = ivec2(gl_LocalInvocationID) + ivec2(0, sliceOffset); vec2 coord = (vec2(pix) + vec2(0.5)) / vec2(res); AeF16x3 N = AeF16x3(OctahedronToUnitVector(coord)); +#ifdef RADIANCE + texelDirections[gl_LocalInvocationIndex] = AeF16x4(N, 0.0); +#endif - ivec2 resOffset = (res + ivec2(2)) * ivec2(gl_WorkGroupID.xz) + ivec2(1); - ivec3 volumeCoord = ivec3(resOffset + pix, int(gl_WorkGroupID.y)); + ivec2 resOffset = (res + ivec2(2)) * probeGroup.xz + ivec2(1); + ivec3 volumeCoord = ivec3(resOffset + pix, probeGroup.y); AeF16 cellLength = AeF16(length(ddgiData.cascades[cascadeIndex].cellSize.xyz)); AeF16 maxDepth = cellLength * AeF16(0.75); @@ -166,6 +279,10 @@ void main() { // We might not have a multiple of shared size in terms of rays uint loadRayCount = min(sharedSize, probeRayCount - i); +#ifdef RADIANCE + texelRayHeads[gl_LocalInvocationIndex] = invalidRayNode; +#endif + // Load rays cooperatively for (uint j = gl_LocalInvocationIndex; j < loadRayCount; j += groupSize) { RayHit hit = UnpackRayHit(hits[rayBaseIdx + i + j]); @@ -173,6 +290,9 @@ void main() { #if defined(IRRADIANCE) || defined(RADIANCE) rayData[j].radiance.rgb = hit.radiance.rgb; rayData[j].direction.a = hit.radiance.a; +#ifdef RADIANCE + rayTexels[j] = min(ivec2(UnitVectorToOctahedron(vec3(hit.direction.xyz)) * vec2(res)), res - ivec2(1)); +#endif #else #ifndef AE_HALF_FLOAT float dist = hit.radiance.a; @@ -191,9 +311,27 @@ void main() { barrier(); +#ifdef RADIANCE + if (!reset) { + for (uint node = gl_LocalInvocationIndex; node < loadRayCount * texelsPerRay; node += groupSize) + LinkRayNode(node, res, sliceOffset); + barrier(); + } +#endif + float maxWeight = 0.0; // Iterate over all rays in the shared memory +#ifdef RADIANCE + if (!reset) { + for (uint node = texelRayHeads[gl_LocalInvocationIndex]; node != invalidRayNode; node = rayNodeNext[node]) + AccumulateRadiance(node / texelsPerRay, N, reset, result); + } + else { + for (uint j = 0; j < loadRayCount; j++) + AccumulateRadiance(j, N, reset, result); + } +#else for (uint j = 0; j < loadRayCount; j++) { #if defined(IRRADIANCE) @@ -223,14 +361,6 @@ void main() { newProbeOffset -= rayData[j].direction.xyz * (probeOffsetDistance - dist) * 0.001 * probeOffset.w / probeOffsetDistance; } } -#elif defined(RADIANCE) - AeF16 weight = max(AeF16(0.0), dot(N, rayData[j].direction.rgb)); - weight = pow(weight, AeF16(256.0)); - - AeF16x3 radiance = rayData[j].radiance.xyz; - - if (reset ||weight > 0.15) - result += AeF16x4(radiance, AeF16(1.0)) * weight; #else AeF16 weight = max(AeF16(0.0), dot(N, rayData[j].direction.xyz)); @@ -242,6 +372,7 @@ void main() { } #endif } +#endif barrier(); @@ -256,8 +387,9 @@ void main() { #if defined(IRRADIANCE) vec3 lastResult = texelFetch(irradianceVolume, historyVolumeCoord, 0).rgb; if (probeState == PROBE_STATE_NEW || reset) { - lastResult = GetHistoryFromHigherCascade(pix, cascadeIndex).rgb; + lastResult = GetHistoryFromHigherCascade(pix, probeGroup, cascadeIndex).rgb; } + lastResult *= ddgiData.historyExposureScale; vec3 resultOut = lastResult; if (result.w > 0.0) { vec4 fullResult = vec4(result); @@ -271,7 +403,7 @@ void main() { resultOut = mix(fullResult.xyz, lastResult, hysteresis); } } - imageStore(irradiance, volumeCoord, vec4(resultOut, 0.0)); + StoreProbeTexel(pix, res, resOffset, volumeCoord.z, vec4(resultOut, 0.0)); if (gl_LocalInvocationIndex == 0) { vec3 maxOffset = ddgiData.cascades[cascadeIndex].cellSize.xyz * 0.5; @@ -282,8 +414,9 @@ void main() { #elif defined(RADIANCE) vec3 lastResult = texelFetch(radianceVolume, historyVolumeCoord, 0).rgb; if (probeState == PROBE_STATE_NEW || reset) { - lastResult = GetHistoryFromHigherCascade(pix, cascadeIndex).rgb; + lastResult = GetHistoryFromHigherCascade(pix, probeGroup, cascadeIndex).rgb; } + lastResult *= ddgiData.historyExposureScale; vec3 resultOut = lastResult; if (result.w > 0.0) { vec4 fullResult = vec4(result); @@ -297,11 +430,11 @@ void main() { resultOut = mix(fullResult.xyz, lastResult, hysteresis); } } - imageStore(radiance, volumeCoord, vec4(resultOut, 0.0)); + StoreProbeTexel(pix, res, resOffset, volumeCoord.z, vec4(resultOut, 0.0)); #else vec2 lastResult = texelFetch(momentsVolume, historyVolumeCoord, 0).rg; if (probeState == PROBE_STATE_NEW || reset) { - lastResult = GetHistoryFromHigherCascade(pix, cascadeIndex).rg; + lastResult = GetHistoryFromHigherCascade(pix, probeGroup, cascadeIndex).rg; } vec2 resultOut = lastResult; if (result.w > 0.0) { @@ -315,7 +448,7 @@ void main() { } } - imageStore(moment, volumeCoord, vec4(resultOut, 0.0, 0.0)); + StoreProbeTexel(pix, res, resOffset, volumeCoord.z, vec4(resultOut, 0.0, 0.0)); #endif } \ No newline at end of file diff --git a/data/shader/ddgi/rayHit.csh b/data/shader/ddgi/rayHit.csh index 934513bb0..b98a00fc7 100644 --- a/data/shader/ddgi/rayHit.csh +++ b/data/shader/ddgi/rayHit.csh @@ -3,9 +3,7 @@ // Journal of Computer Graphics Techniques Vol 8.2 (2019). // Majercik, Zander, et al. "Scaling Probe-Based Real-Time Dynamic Global Illumination for Production." // arXiv preprint arXiv:2009.10796 (2020). -#ifdef USE_SHADOW_MAP -#define SHADOW_FILTER_1x1 -#endif +#define LOCAL_STACK #include <../raytracer/lights.hsh> #include <../raytracer/tracing.hsh> @@ -21,14 +19,14 @@ #include <../brdf/importanceSample.hsh> #include <../brdf/surface.hsh> -#include <../shadow.hsh> #include <../clouds/shadow.hsh> #include #include +#include +#ifndef RAY_TRACING_PIPELINE layout (local_size_x = 32) in; - -layout(set = 3, binding = 0) uniform sampler2DArrayShadow cascadeMaps; +#endif #ifdef CLOUD_SHADOWS layout(set = 3, binding = 1) uniform sampler2D cloudMap; @@ -39,15 +37,27 @@ layout(std430, set = 3, binding = 2) buffer RayHits { PackedRayHit hits[]; }; +#ifdef DEFERRED_SHADOW_RAYS +layout(std430, set = 3, binding = 4) buffer ShadowRays { + PackedShadowRay shadowRays[]; +}; + +layout(std430, set = 3, binding = 5) buffer ShadowRayCount { + uint shadowRayCount; +}; +#endif + layout(std140, set = 3, binding = 3) uniform UniformBuffer { float seed; - Shadow shadow; } Uniforms; vec3 EvaluateHit(inout Ray ray); vec3 EvaluateDirectLight(inout Surface surface); bool CheckVisibility(Surface surface, float lightDistance); +bool hasShadowRay = false; +PackedShadowRay shadowRay; + void main() { if (IsRayInvocationValid()) { @@ -55,10 +65,20 @@ void main() { vec3 radiance = vec3(0.0); if (ray.ID >= 0) { + TraceBufferedRay(ray); radiance = EvaluateHit(ray); // Probes store the lighting scaled, the lookup restores it radiance *= ddgiData.volumeStorageScale; + +#ifdef DEFERRED_SHADOW_RAYS + if (hasShadowRay) { + uint shadowRayIdx = atomicAdd(shadowRayCount, 1u); + shadowRays[shadowRayIdx].origin = shadowRay.origin; + shadowRays[shadowRayIdx].direction = shadowRay.direction; + shadowRays[shadowRayIdx].radiance = vec4(shadowRay.radiance.rgb * ddgiData.volumeStorageScale, uintBitsToFloat(uint(ray.ID))); + } +#endif RayHit hit; #ifndef AE_HALF_FLOAT @@ -86,12 +106,8 @@ vec3 EvaluateHit(inout Ray ray) { return SampleEnvironmentMap(ray.direction, 4).rgb; } - // Unpack the compressed triangle and extract surface parameters - Instance instance = GetInstance(ray); - Triangle tri = GetTriangle(ray, instance); - bool backfaceHit; - Surface surface = GetSurfaceParameters(instance, tri, ray, false, backfaceHit, 4); + Surface surface = GetHitSurface(ray, false, backfaceHit, 4); // Indicates backface hit if (backfaceHit) { @@ -102,8 +118,14 @@ vec3 EvaluateHit(inout Ray ray) { radiance += surface.material.emissiveColor; // Evaluate direct light - radiance += EvaluateDirectLight(surface); - + vec3 direct = EvaluateDirectLight(surface); + if (hasShadowRay) + shadowRay.radiance = vec4(direct, 0.0); + else + radiance += direct; + + // Without RADIANCE_VOLUME the probe radiance falls back to the irradiance, the large radiance + // probes are too expensive to sample at incoherent hits for the small specular part of the bounce vec4 probeIrradiance, probeRadiance; GetLocalProbeLighting(surface.P, surface.V, surface.N, surface.N, surface.geometryNormal, probeIrradiance, probeRadiance); @@ -129,7 +151,7 @@ vec3 EvaluateDirectLight(inout Surface surface) { return vec3(0.0); float curSeed = Uniforms.seed; - float raySeed = float(gl_GlobalInvocationID.x); + float raySeed = float(INVOCATION_ID.x); float lightPdf; Light light = GetLight(surface, raySeed, curSeed, lightPdf); @@ -149,27 +171,17 @@ vec3 EvaluateDirectLight(inout Surface surface) { // Check for visibilty. This is important to get an // estimate of the solid angle of the light from point P // on the surface. - if (light.type == uint(DIRECTIONAL_LIGHT)) { -#ifdef USE_SHADOW_MAP - float shadowFactor = CalculateShadowWorldSpace(Uniforms.shadow, cascadeMaps, surface.P, - lightSurface.geometryNormal, saturate(dot(lightSurface.L, lightSurface.geometryNormal))); - radiance *= shadowFactor; -#else - if (light.castShadow) - radiance *= CheckVisibility(lightSurface, lightDistance) ? 1.0 : 0.0; + if (light.castShadow) + radiance *= CheckVisibility(lightSurface, lightDistance) ? 1.0 : 0.0; #ifdef CLOUD_SHADOWS + if (light.type == uint(DIRECTIONAL_LIGHT)) { vec3 P = vec3(globalData.vMatrix * vec4(surface.P, 1.0)); float cloudShadowFactor = CalculateCloudShadow(P, cloudShadowUniforms.cloudShadow, cloudMap); radiance *= cloudShadowFactor; -#endif -#endif - } - else { - if (light.castShadow) - radiance *= CheckVisibility(lightSurface, lightDistance) ? 1.0 : 0.0; } +#endif return reflectance * radiance * lightSurface.NdotL / lightPdf; @@ -182,7 +194,14 @@ bool CheckVisibility(Surface surface, float lightDistance) { ray.direction = surface.L; float side = dot(surface.L, surface.geometryNormal) < 0.0 ? -1.0 : 1.0; ray.origin = surface.P + surface.geometryNormal * (side * EPSILON); +#ifdef DEFERRED_SHADOW_RAYS + hasShadowRay = true; + shadowRay.origin = vec4(ray.origin, lightDistance - 2.0 * EPSILON); + shadowRay.direction = vec4(ray.direction, 0.0); + return true; +#else return HitAny(ray, INSTANCE_MASK_SHADOW, 0.0, lightDistance - 2.0 * EPSILON) == false; +#endif } else { return false; diff --git a/data/shader/ddgi/rayHit.rgen b/data/shader/ddgi/rayHit.rgen new file mode 100644 index 000000000..109e29376 --- /dev/null +++ b/data/shader/ddgi/rayHit.rgen @@ -0,0 +1,7 @@ +// Traces and shades the probe rays as the ray generation stage of a ray tracing pipeline, see bvh.hsh for the tracing +#extension GL_EXT_ray_tracing : require +#extension GL_EXT_shader_invocation_reorder : require + +#define RAY_TRACING_PIPELINE + +#include diff --git a/data/shader/ddgi/rayShadow.csh b/data/shader/ddgi/rayShadow.csh new file mode 100644 index 000000000..96ec38be2 --- /dev/null +++ b/data/shader/ddgi/rayShadow.csh @@ -0,0 +1,38 @@ +#define LOCAL_STACK + +#include <../raytracer/tracing.hsh> +#include +#include + +layout (local_size_x = 32) in; + +layout(std430, set = 3, binding = 2) buffer RayHits { + PackedRayHit hits[]; +}; + +layout(std430, set = 3, binding = 4) buffer ShadowRays { + PackedShadowRay shadowRays[]; +}; + +layout(std430, set = 3, binding = 5) buffer ShadowRayCount { + uint shadowRayCount; +}; + +void main() { + + uint idx = gl_GlobalInvocationID.x; + if (idx >= shadowRayCount) + return; + + Ray ray; + ray.origin = shadowRays[idx].origin.xyz; + ray.direction = shadowRays[idx].direction.xyz; + + if (!HitAny(ray, INSTANCE_MASK_SHADOW, 0.0, shadowRays[idx].origin.w)) { + uint hitIdx = floatBitsToUint(shadowRays[idx].radiance.w); + RayHit hit = UnpackRayHit(hits[hitIdx]); + hit.radiance.rgb = AeF16x3(vec3(hit.radiance.rgb) + shadowRays[idx].radiance.rgb); + hits[hitIdx] = PackRayHit(hit); + } + +} diff --git a/data/shader/ddgi/shadowRay.hsh b/data/shader/ddgi/shadowRay.hsh new file mode 100644 index 000000000..e1836fb0f --- /dev/null +++ b/data/shader/ddgi/shadowRay.hsh @@ -0,0 +1,7 @@ +struct PackedShadowRay { + // xyz: origin, w: maximum distance + vec4 origin; + vec4 direction; + // rgb: direct light if the light is visible, w: index of the ray hit + vec4 radiance; +}; diff --git a/data/shader/deferred/direct.csh b/data/shader/deferred/direct.csh index 7685cd2eb..d5e9c02ab 100644 --- a/data/shader/deferred/direct.csh +++ b/data/shader/deferred/direct.csh @@ -14,6 +14,7 @@ layout (local_size_x = 16, local_size_y = 16) in; #include <../common/convert.hsh> #include <../common/utility.hsh> +#include <../common/light.hsh> #include <../brdf/brdfEval.hsh> #include <../common/octahedron.hsh> #include <../clouds/shadow.hsh> @@ -29,13 +30,12 @@ layout(set = 3, binding = 2) uniform sampler2D cloudMap; layout(set = 3, binding = 4) uniform sampler shadowSampler; +#include + layout(std430, set = 3, binding = 6) buffer LightBucketsBuffer { int lightBuckets[]; }; -layout(set = 3, binding = 7) uniform texture2DArray cascadeMaps[8]; -layout(set = 3, binding = 15) uniform textureCube cubeMaps[8]; - layout(push_constant) uniform constants { int lightCount; int lightBucketCount; @@ -45,9 +45,6 @@ layout(push_constant) uniform constants { shared uint sharedLightBuckets[lightBucketCount]; -vec3 EvaluateLight(Light light, Surface surface, vec3 geometryNormal, bool isMain); -float GetShadowFactor(Light light, Surface surface, uint lightType, vec3 geometryNormal, bool isMain); - void LoadGroupSharedData() { int lightBucketOffset = GetLightBucketsGroupOffset(); @@ -102,17 +99,14 @@ void main() { Light light = lights[offsetIdx + j]; -#ifndef AE_BINDLESS - light.shadow.mapIdx = int(offsetIdx + j); -#endif bool isMain = i + j == 0u ? true : false; - direct += EvaluateLight(light, surface, geometryNormal, isMain); + direct += EvaluateLight(light, surface, geometryNormal, isMain, pixel, texCoord); } } if (dot(surface.material.emissiveColor, vec3(1.0)) > 0.01) { - direct += surface.material.emissiveColor; + direct += surface.material.emissiveColor * globalData.preExposure; } } @@ -120,137 +114,3 @@ void main() { imageStore(image, pixel, vec4(direct, 1.0)); } - -uint GetLightType(Light light) { - - return floatBitsToUint(light.color.a); - -} - -vec3 EvaluateLight(Light light, Surface surface, vec3 geometryNormal, bool isMain) { - - uint lightType = GetLightType(light); - - float attenuation = 1.0; - float radius = light.direction.w; - - if (lightType == DIRECTIONAL_LIGHT) { - surface.L = normalize(-light.direction.xyz); - } - else if (lightType == POINT_LIGHT) { - vec3 pointToLight = light.location.xyz - surface.P; - float sqrDistance = dot(pointToLight, pointToLight); - float dist = sqrt(sqrDistance); - - attenuation = saturate(1.0 - pow(dist / radius, 4.0)) / sqrDistance; - - surface.L = pointToLight / dist; - } - else if (lightType == SPOT_LIGHT) { - vec3 pointToLight = light.location.xyz - surface.P; - float sqrDistance = dot(pointToLight, pointToLight); - float dist = sqrt(sqrDistance); - - surface.L = pointToLight / dist; - - float strength = dot(surface.L, normalize(-light.direction.xyz)); - float angleAttenuation = saturate(strength * light.specific0 + light.specific1); - float distAttenuation = saturate(1.0 - pow(dist / radius, 4.0)) / sqrDistance; - attenuation = distAttenuation * sqr(angleAttenuation); - } - - if (attenuation == 0.0) - return vec3(0.0); - - float shadowFactor = GetShadowFactor(light, surface, lightType, geometryNormal, isMain); - - UpdateSurface(surface); - - // Direct diffuse + specular BRDF - vec3 directDiffuse = EvaluateDiffuseBRDF(surface); - vec3 directSpecular = EvaluateSpecularBRDF(surface); - - vec3 direct = directDiffuse + directSpecular; - - vec3 radiance = light.color.rgb * light.intensity * attenuation; - direct = direct * radiance * surface.NdotL * shadowFactor; - - if (surface.material.transmissive) { - Surface backSurface = CreateSurface(surface.V, -surface.N, surface.L, surface.material); - - float viewDependency = saturate(dot(-surface.V, surface.L)); - // viewDependency = sqr(viewDependency); - - // Direct diffuse BRDF backside - directDiffuse = viewDependency * surface.material.transmissiveColor * EvaluateDiffuseBRDF(backSurface); - // Need to change this back - // direct += directDiffuse * radiance * backSurface.NdotL * shadowFactorTransmissive; - direct += directDiffuse * radiance * backSurface.NdotL * shadowFactor; - } - - return direct; - -} - -float GetShadowFactor(Light light, Surface surface, uint lightType, vec3 geometryNormal, bool isMain) { - - if (light.shadow.mapIdx < 0) - return 1.0; - - ivec2 pixel = ivec2(gl_GlobalInvocationID); - - float shadowFactor = 1.0; - - vec3 shadowNormal = surface.material.transmissive ? dot(surface.L, geometryNormal) < 0.0 ? - -geometryNormal : geometryNormal : geometryNormal; - - if (lightType == DIRECTIONAL_LIGHT) { -#ifdef AE_BINDLESS - shadowFactor = CalculateCascadedShadow(light.shadow, bindlessTextureArrays[nonuniformEXT(light.shadow.mapIdx)], - shadowSampler, surface.P, vec3(vec2(pixel) + 0.5, 0.0), - shadowNormal, saturate(dot(-light.direction.xyz, shadowNormal))); -#else - shadowFactor = CalculateCascadedShadow(light.shadow, cascadeMaps[nonuniformEXT(light.shadow.mapIdx)], - shadowSampler, surface.P, vec3(vec2(pixel) + 0.5, 0.0), - shadowNormal, saturate(dot(-light.direction.xyz, shadowNormal))); -#endif - } - else if (lightType == POINT_LIGHT) { -#ifdef AE_BINDLESS - shadowFactor = CalculatePointShadow(light.shadow, bindlessCubemaps[nonuniformEXT(light.shadow.mapIdx)], - shadowSampler, surface.P, shadowNormal, saturate(dot(-light.direction.xyz, shadowNormal))); -#else - shadowFactor = CalculatePointShadow(light.shadow, cubeMaps[nonuniformEXT(light.shadow.mapIdx)], - shadowSampler, surface.P, shadowNormal, saturate(dot(-light.direction.xyz, shadowNormal))); -#endif - } - else if (lightType == SPOT_LIGHT) { -#ifdef AE_BINDLESS - shadowFactor = CalculateSpotShadow(light.shadow, bindlessTextureArrays[nonuniformEXT(light.shadow.mapIdx)], - shadowSampler, surface.P, vec3(vec2(pixel) + 0.5, 0.0), - shadowNormal, saturate(dot(-light.direction.xyz, shadowNormal))); -#else - shadowFactor = CalculateSpotShadow(light.shadow, cascadeMaps[nonuniformEXT(light.shadow.mapIdx)], - shadowSampler, surface.P, vec3(vec2(pixel) + 0.5, 0.0), - shadowNormal, saturate(dot(-light.direction.xyz, shadowNormal))); -#endif - } - - if (isMain) { -#ifdef CLOUD_SHADOWS - float cloudShadowFactor = CalculateCloudShadow(surface.P, cloudShadowUniforms.cloudShadow, cloudMap); - - shadowFactor *= cloudShadowFactor; -#endif - float shadowFactorTransmissive = shadowFactor; -#ifdef SCREEN_SPACE_SHADOWS - ivec2 resolution = imageSize(image); - vec2 texCoord = (vec2(pixel) + 0.5) / vec2(resolution); - float sssFactor = textureLod(sssTexture, texCoord, 0).r; - shadowFactor = min(sssFactor, shadowFactor); -#endif - } - - return shadowFactor; - -} \ No newline at end of file diff --git a/data/shader/deferred/directLight.hsh b/data/shader/deferred/directLight.hsh new file mode 100644 index 000000000..3f684d822 --- /dev/null +++ b/data/shader/deferred/directLight.hsh @@ -0,0 +1,119 @@ +// The light of a light source on a surface. The includer declares shadowSampler, cloudMap with CLOUD_SHADOWS and +// sssTexture with SCREEN_SPACE_SHADOWS, the pixel selects the shadow filter noise + +float GetShadowFactor(Light light, Surface surface, uint lightType, vec3 geometryNormal, bool isMain, ivec2 pixel, vec2 texCoord); + +uint GetLightType(Light light) { + + return floatBitsToUint(light.color.a); + +} + +vec3 EvaluateLight(Light light, Surface surface, vec3 geometryNormal, bool isMain, ivec2 pixel, vec2 texCoord) { + + uint lightType = GetLightType(light); + + float attenuation = 1.0; + float radius = light.direction.w; + + if (lightType == DIRECTIONAL_LIGHT) { + surface.L = normalize(-light.direction.xyz); + } + else if (lightType == POINT_LIGHT) { + vec3 pointToLight = light.location.xyz - surface.P; + float dist = length(pointToLight); + + attenuation = GetDistanceAttenuation(dist, radius); + + surface.L = pointToLight / dist; + } + else if (lightType == SPOT_LIGHT) { + vec3 pointToLight = light.location.xyz - surface.P; + float dist = length(pointToLight); + + surface.L = pointToLight / dist; + + float strength = dot(surface.L, normalize(-light.direction.xyz)); + float angleAttenuation = saturate(strength * light.specific0 + light.specific1); + float distAttenuation = GetDistanceAttenuation(dist, radius); + attenuation = distAttenuation * sqr(angleAttenuation); + } + + if (attenuation == 0.0) + return vec3(0.0); + + if (dot(surface.N, surface.L) <= 0.0 && !surface.material.transmissive) + return vec3(0.0); + + float shadowFactor = GetShadowFactor(light, surface, lightType, geometryNormal, isMain, pixel, texCoord); + + UpdateSurface(surface); + + // Direct diffuse + specular BRDF + vec3 directDiffuse = EvaluateDiffuseBRDF(surface); + vec3 directSpecular = EvaluateSpecularBRDF(surface); +#ifdef TRANSLUCENT_PASS + // Translucent surfaces scatter light by their opacity, glass reflects it regardless of the opacity + directDiffuse *= surface.material.opacity; +#endif + + vec3 direct = directDiffuse + directSpecular; + + vec3 radiance = light.color.rgb * light.intensity * attenuation; + direct = direct * radiance * surface.NdotL * shadowFactor; + + if (surface.material.transmissive) { + Surface backSurface = CreateSurface(surface.V, -surface.N, surface.L, surface.material); + + float viewDependency = saturate(dot(-surface.V, surface.L)); + // viewDependency = sqr(viewDependency); + + // Direct diffuse BRDF backside + directDiffuse = viewDependency * surface.material.transmissiveColor * EvaluateDiffuseBRDF(backSurface); + direct += directDiffuse * radiance * backSurface.NdotL * shadowFactor; + } + + return direct; + +} + +float GetShadowFactor(Light light, Surface surface, uint lightType, vec3 geometryNormal, bool isMain, ivec2 pixel, vec2 texCoord) { + + if (light.shadow.mapIdx < 0) + return 1.0; + + float shadowFactor = 1.0; + + vec3 shadowNormal = surface.material.transmissive ? dot(surface.L, geometryNormal) < 0.0 ? + -geometryNormal : geometryNormal : geometryNormal; + + if (lightType == DIRECTIONAL_LIGHT) { + shadowFactor = CalculateCascadedShadow(light.shadow, bindlessTextureArrays[nonuniformEXT(light.shadow.mapIdx)], + shadowSampler, surface.P, vec3(vec2(pixel) + 0.5, 0.0), + shadowNormal, saturate(dot(-light.direction.xyz, shadowNormal))); + } + else if (lightType == POINT_LIGHT) { + shadowFactor = CalculatePointShadow(light.shadow, bindlessCubemaps[nonuniformEXT(light.shadow.mapIdx)], + shadowSampler, surface.P, shadowNormal, saturate(dot(-light.direction.xyz, shadowNormal))); + } + else if (lightType == SPOT_LIGHT) { + shadowFactor = CalculateSpotShadow(light.shadow, bindlessTextureArrays[nonuniformEXT(light.shadow.mapIdx)], + shadowSampler, surface.P, vec3(vec2(pixel) + 0.5, 0.0), + shadowNormal, saturate(dot(-light.direction.xyz, shadowNormal))); + } + + if (isMain) { +#ifdef CLOUD_SHADOWS + float cloudShadowFactor = CalculateCloudShadow(surface.P, cloudShadowUniforms.cloudShadow, cloudMap); + + shadowFactor *= cloudShadowFactor; +#endif +#ifdef SCREEN_SPACE_SHADOWS + float sssFactor = textureLod(sssTexture, texCoord, 0).r; + shadowFactor = min(sssFactor, shadowFactor); +#endif + } + + return shadowFactor; + +} \ No newline at end of file diff --git a/data/shader/deferred/geometry.fsh b/data/shader/deferred/geometry.fsh index daa70129d..e35bcc6c2 100644 --- a/data/shader/deferred/geometry.fsh +++ b/data/shader/deferred/geometry.fsh @@ -1,8 +1,47 @@ #include <../common/random.hsh> #include <../common/normalencode.hsh> #include <../globals.hsh> +#include <../common/opacity.hsh> +#include <../common/material.hsh> #include +#include +#if defined(TRANSLUCENT) +#include <../translucent/translucent.hsh> + +layout (location = 0) out vec4 colorFS; +layout (location = 1) out vec4 coverageFS; +layout (location = 2) out vec4 blendedVelocityFS; + +vec3 baseColorFS; +vec2 normalFS; +vec2 geometryNormalFS; +vec3 roughnessMetalnessAoFS; +vec3 emissiveFS; +uint materialIdxFS; +vec2 velocityFS; +#elif defined(FRONT_LAYER) +// The channels of the G-buffer which the reflections read +layout (location = 0) out vec2 normalFS; +layout (location = 1) out vec2 geometryNormalFS; +layout (location = 2) out vec3 roughnessMetalnessAoFS; +layout (location = 3) out uint materialIdxFS; +layout (location = 4) out vec2 velocityFS; + +vec3 baseColorFS; +vec3 emissiveFS; +#elif defined(REFRACTION_BACK_FACES) +// The normal pointing out of the surface where refracted rays leave it, the depth is written as well +layout (location = 0) out vec2 backNormalFS; + +vec3 baseColorFS; +vec2 normalFS; +vec2 geometryNormalFS; +vec3 roughnessMetalnessAoFS; +vec3 emissiveFS; +uint materialIdxFS; +vec2 velocityFS; +#else layout (location = 0) out vec3 baseColorFS; layout (location = 1) out vec2 normalFS; layout (location = 2) out vec2 geometryNormalFS; @@ -10,6 +49,7 @@ layout (location = 3) out vec3 roughnessMetalnessAoFS; layout (location = 4) out vec3 emissiveFS; layout (location = 5) out uint materialIdxFS; layout (location = 6) out vec2 velocityFS; +#endif layout(location=0) in vec3 positionVS; layout(location=1) in vec3 normalVS; @@ -28,29 +68,16 @@ layout(location=5) in vec4 vertexColorsVS; layout(location=7) in mat3 TBN; #endif -layout(push_constant) uniform constants { - uint vegetation; - uint invertUVs; - uint twoSided; - uint staticMesh; - uint materialIdx; - float normalScale; - float displacementScale; - float windTextureLod; - float windBendScale; - float windWiggleScale; - float uvAnimationX; - float uvAnimationY; - float uvTiling; - uint baseColorTextureIdx; - uint opacityTextureIdx; - uint normalTextureIdx; - uint roughnessTextureIdx; - uint metalnessTextureIdx; - uint aoTextureIdx; - uint heightTextureIdx; - uint emissiveTextureIdx; -} PushConstants; +#ifdef MATERIAL_GRAPH_SURFACE +layout(location=10) in vec3 objectPositionVS; +layout(location=11) in vec3 instancePositionVS; +layout(location=12) in vec3 objectNormalVS; +#endif + +layout(location=13) flat in uint lodVS; +#ifdef DRAW_DATA +layout(location=14) flat in uint drawIdxVS; +#endif vec2 ParallaxMapping(vec2 texCoords, vec3 viewDir) { #ifdef HEIGHT_MAP @@ -63,20 +90,20 @@ vec2 ParallaxMapping(vec2 texCoords, vec3 viewDir) { // depth of current layer float currentLayerDepth = 0.0; // the amount to shift the texture coordinates per layer (from vector P) - vec2 P = viewDir.xy / viewDir.z * PushConstants.displacementScale; + vec2 P = viewDir.xy / viewDir.z * DrawValue(displacementScale); vec2 deltaTexCoords = P / numLayers; vec2 currentTexCoords = texCoords; vec2 ddx = dFdx(texCoords); vec2 ddy = dFdy(texCoords); - float currentDepthMapValue = 1.0 - SampleHeight(currentTexCoords, PushConstants.heightTextureIdx, ddx, ddy).r; + float currentDepthMapValue = 1.0 - SampleHeight(currentTexCoords, DrawValue(heightTextureIdx), ddx, ddy).r; while(currentLayerDepth < currentDepthMapValue) { // shift texture coordinates along direction of P currentTexCoords -= deltaTexCoords; // get depthmap value at current texture coordinates - currentDepthMapValue = 1.0 - SampleHeight(currentTexCoords, PushConstants.heightTextureIdx, ddx, ddy).r; + currentDepthMapValue = 1.0 - SampleHeight(currentTexCoords, DrawValue(heightTextureIdx), ddx, ddy).r; // get depth of next layer currentLayerDepth += layerDepth; } @@ -85,7 +112,7 @@ vec2 ParallaxMapping(vec2 texCoords, vec3 viewDir) { // get depth after and before collision for linear interpolation float afterDepth = currentDepthMapValue - currentLayerDepth; - float beforeDepth = 1.0 - SampleHeight(prevTexCoords, PushConstants.heightTextureIdx, ddx, ddy).r - currentLayerDepth + layerDepth; + float beforeDepth = 1.0 - SampleHeight(prevTexCoords, DrawValue(heightTextureIdx), ddx, ddy).r - currentLayerDepth + layerDepth; // interpolation of texture coordinates float weight = afterDepth / (afterDepth - beforeDepth); @@ -100,10 +127,64 @@ vec2 ParallaxMapping(vec2 texCoords, vec3 viewDir) { void main() { +#ifdef DRAW_DATA + drawIdx = drawIdxVS; +#endif + + // The coverage of translucent surfaces, the others are cut out by it + float opacity = 1.0; + +#ifdef MATERIAL_GRAPH_SURFACE + vec2 graphTexCoord = vec2(0.0); + vec4 graphColor = vec4(1.0); +#ifdef TEX_COORDS + graphTexCoord = texCoordVS; +#endif +#ifdef VERTEX_COLORS + graphColor = vertexColorsVS; +#endif + + float graphFrontFacing = gl_FrontFacing ? 1.0 : -1.0; + vec3 graphGeometryNormal = normalize(normalVS) * (DrawValue(twoSided) > 0 ? graphFrontFacing : 1.0); + mat3 graphTangentFrame = mat3(1.0); +#if defined(MATERIAL_GRAPH_WRITES_NORMAL) || defined(MATERIAL_GRAPH_USES_TANGENTS) +#ifdef NORMAL_MAP + graphTangentFrame = TBN; +#else + graphTangentFrame = MaterialGraphCotangentFrame(graphGeometryNormal, positionVS, graphTexCoord); +#endif +#endif + + MaterialSurfaceInput surfaceInput = CreateMaterialSurfaceInput(objectPositionVS, normalize(objectNormalVS), + vec3(globalData.ivMatrix * vec4(positionVS, 1.0)), normalize(mat3(globalData.ivMatrix) * graphGeometryNormal), + instancePositionVS, graphTangentFrame, graphTexCoord, 0.5 * ndcCurrentVS.xy / ndcCurrentVS.z + 0.5, + graphColor, graphFrontFacing, PushConstants.materialGraphOffset); + MaterialSurfaceOutput surface = EvaluateMaterialSurface(surfaceInput); + +#if defined(MATERIAL_GRAPH_HAS_OPACITY) && defined(TRANSLUCENT_PASS) + opacity = surface.opacity; +#elif defined(MATERIAL_GRAPH_OPACITY) + if (surface.opacity < opacityCutoff) + discard; +#endif + + baseColorFS = surface.baseColor; + emissiveFS = surface.emissive; + roughnessMetalnessAoFS = vec3(surface.roughness, surface.metalness, surface.ao); + geometryNormalFS = EncodeNormal(graphGeometryNormal); + +#ifdef MATERIAL_GRAPH_WRITES_NORMAL + vec3 graphNormal = normalize(graphTangentFrame * surface.normal); + graphNormal *= dot(graphGeometryNormal, graphNormal) < 0.0 ? -1.0 : 1.0; + normalFS = EncodeNormal(graphNormal); +#else + normalFS = geometryNormalFS; +#endif +#else #ifdef TEX_COORDS vec2 texCoords = texCoordVS; #endif - + // Check if usage is valid (otherwise texCoords won't be used) #if defined(HEIGHT_MAP) && (defined(BASE_COLOR_MAP) || defined(NORMAL_MAP) || defined(ROUGHNESS_MAP) || defined(METALNESS_MAP) || defined(AO_MAP) || defined(EMISSIVE_MAP)) vec3 viewDir = normalize(transpose(TBN) * -positionVS); @@ -113,24 +194,25 @@ void main() { baseColorFS = vec3(1.0); #if (defined(OPACITY_MAP) || defined(VERTEX_COLORS)) - float opacity = 1.0; #ifdef OPACITY_MAP - opacity *= SampleOpacity(texCoords, PushConstants.opacityTextureIdx, globalData.mipLodBias); + opacity *= SampleOpacity(texCoords, DrawValue(opacityTextureIdx), globalData.mipLodBias); #endif #ifdef VERTEX_COLORS // opacity *= vertexColorsVS.a; #endif - if (opacity < 0.2) +#ifndef TRANSLUCENT_PASS + if (opacity < opacityCutoff) discard; #endif +#endif #ifdef BASE_COLOR_MAP - vec3 textureColor = SampleBaseColor(texCoords, PushConstants.baseColorTextureIdx, globalData.mipLodBias); + vec3 textureColor = SampleBaseColor(texCoords, DrawValue(baseColorTextureIdx), globalData.mipLodBias); baseColorFS *= textureColor.rgb; #endif #ifdef EMISSIVE_MAP - vec3 emissiveColor = SampleEmissive(texCoords, PushConstants.emissiveTextureIdx, globalData.mipLodBias); + vec3 emissiveColor = SampleEmissive(texCoords, DrawValue(emissiveTextureIdx), globalData.mipLodBias); emissiveFS = emissiveColor.rgb; #endif @@ -141,16 +223,16 @@ void main() { vec3 geometryNormal = normalize(normalVS); #ifdef NORMAL_MAP - vec3 normalColor = SampleNormal(texCoords, PushConstants.normalTextureIdx, globalData.mipLodBias); - vec3 normal = mix(geometryNormal, normalize(TBN * normalColor), PushConstants.normalScale); + vec3 normalColor = SampleNormal(texCoords, DrawValue(normalTextureIdx), globalData.mipLodBias); + vec3 normal = mix(geometryNormal, normalize(TBN * normalColor), DrawValue(normalScale)); // We want the normal always to face the camera for two sided materials - geometryNormal *= PushConstants.twoSided > 0 ? gl_FrontFacing ? 1.0 : -1.0 : 1.0; + geometryNormal *= DrawValue(twoSided) > 0 ? gl_FrontFacing ? 1.0 : -1.0 : 1.0; normal *= dot(geometryNormal, normal) < 0.0 ? -1.0 : 1.0; normalFS = EncodeNormal(normal); #else // We want the normal always to face the camera for two sided materials - geometryNormal *= PushConstants.twoSided > 0 ? gl_FrontFacing ? 1.0 : -1.0 : 1.0; + geometryNormal *= DrawValue(twoSided) > 0 ? gl_FrontFacing ? 1.0 : -1.0 : 1.0; #endif @@ -165,16 +247,17 @@ void main() { float aoFactor = 1.0; #ifdef ROUGHNESS_MAP - roughnessFactor *= SampleRoughness(texCoords, PushConstants.roughnessTextureIdx, globalData.mipLodBias); + roughnessFactor *= SampleRoughness(texCoords, DrawValue(roughnessTextureIdx), globalData.mipLodBias); roughnessMetalnessAoFS.r = roughnessFactor; #endif #ifdef METALNESS_MAP - metalnessFactor *= SampleMetalness(texCoords, PushConstants.metalnessTextureIdx, globalData.mipLodBias); + metalnessFactor *= SampleMetalness(texCoords, DrawValue(metalnessTextureIdx), globalData.mipLodBias); roughnessMetalnessAoFS.g = metalnessFactor; #endif #ifdef AO_MAP - aoFactor *= SampleAo(texCoords, PushConstants.aoTextureIdx, globalData.mipLodBias); + aoFactor *= SampleAo(texCoords, DrawValue(aoTextureIdx), globalData.mipLodBias); roughnessMetalnessAoFS.b = aoFactor; +#endif #endif // Calculate velocity @@ -186,6 +269,59 @@ void main() { velocityFS = (ndcL - ndcC) * 0.5; - materialIdxFS = PushConstants.materialIdx; - + materialIdxFS = DrawValue(materialIdx); + + if (globalData.debugMeshLods > 0u) { + const vec3 lodColors[5] = vec3[](vec3(1.0), vec3(0.1, 0.9, 0.1), vec3(0.1, 0.4, 1.0), vec3(1.0, 0.8, 0.1), + vec3(1.0, 0.1, 0.1)); + baseColorFS = lodColors[min(lodVS, 4u)] * (0.5 + 0.5 * dot(baseColorFS, vec3(0.333))); + } + +#ifdef TRANSLUCENT_PASS + // The material holds the factors of the maps like in the deferred passes, see deferred/deferred.hsh + Material material = UnpackMaterial(materialIdxFS); + opacity *= material.opacity; +#endif + +#if defined(FRONT_LAYER) || defined(REFRACTION_BACK_FACES) + // Only surfaces with some coverage reflect, refracting ones are clear glass without it like in the path tracer + if (opacity <= 0.0 && PushConstants.refractiveIndex == 1.0) + discard; +#endif + +#ifdef REFRACTION_BACK_FACES + vec3 backNormal = DecodeNormal(normalFS); + backNormalFS = EncodeNormal(dot(backNormal, positionVS) < 0.0 ? -backNormal : backNormal); +#endif + +#ifdef TRANSLUCENT + if (material.baseColorMap || material.vertexColors) + material.baseColor *= baseColorFS; + if (material.roughnessMap) + material.roughness *= roughnessMetalnessAoFS.r; + if (material.metalnessMap) + material.metalness *= roughnessMetalnessAoFS.g; + if (material.aoMap) + material.ao *= roughnessMetalnessAoFS.b; + if (material.emissiveMap) + material.emissiveColor *= emissiveFS; + + vec3 shadingGeometryNormal = DecodeNormal(geometryNormalFS); + vec3 shadingNormal = material.normalMap ? DecodeNormal(normalFS) : shadingGeometryNormal; + + float coverage; + colorFS = ShadeTranslucent(material, shadingNormal, shadingGeometryNormal, positionVS, saturate(opacity), + PushConstants.refractiveIndex, PushConstants.thickness, coverage); + coverageFS = vec4(coverage, 0.0, 0.0, coverage); + // The upscaler reprojects by the surface as much as it covers the background, light added or multiplied keeps + // the motion of the background +#if defined(BLEND_ALPHA) + blendedVelocityFS = vec4(velocityFS * coverage, 0.0, coverage); +#elif defined(BLEND_ADDITIVE) + blendedVelocityFS = vec4(0.0); +#else + blendedVelocityFS = vec4(1.0); +#endif +#endif + } diff --git a/data/shader/deferred/geometry.hsh b/data/shader/deferred/geometry.hsh new file mode 100644 index 000000000..302c4d587 --- /dev/null +++ b/data/shader/deferred/geometry.hsh @@ -0,0 +1,59 @@ +// Translucent surfaces are blended (TRANSLUCENT), write the closest one for the reflections (FRONT_LAYER) or the back +// faces where refracted rays leave them (REFRACTION_BACK_FACES) instead of being cut out +#if defined(TRANSLUCENT) || defined(FRONT_LAYER) || defined(REFRACTION_BACK_FACES) +#define TRANSLUCENT_PASS +#endif + +// Has to match OpaqueRenderer::DrawData, multi draws read it from a buffer instead of the push constants +struct GeometryDraw { + uint invertUVs; + uint twoSided; + uint staticMesh; + uint materialIdx; + float normalScale; + float displacementScale; + float windTextureLod; + float windBendScale; + float windWiggleScale; + float uvAnimationX; + float uvAnimationY; + float uvTiling; + uint baseColorTextureIdx; + uint opacityTextureIdx; + uint normalTextureIdx; + uint roughnessTextureIdx; + uint metalnessTextureIdx; + uint aoTextureIdx; + uint heightTextureIdx; + uint emissiveTextureIdx; + // Level of detail of host culled draws, the commands of a GPU culled draw add their level + uint lod; +}; + +layout(push_constant) uniform constants { + GeometryDraw draw; + uint deformOffset; + uint jointCount; + uint instanceOffset; + // With DRAW_DATA the data of a draw is at firstDraw + gl_DrawID, the draws of a multi draw follow each other + uint firstDraw; +#ifdef TRANSLUCENT_PASS + // See TranslucentRenderer::PushConstants, 1 without refraction + float refractiveIndex; + float thickness; +#endif +#ifdef MATERIAL_GRAPH + uint materialGraphOffset; +#endif +} PushConstants; + +#ifdef DRAW_DATA +layout(std430, set = 3, binding = 10) readonly buffer GeometryDraws { + GeometryDraw geometryDraws[]; +}; + +uint drawIdx; +#define DrawValue(name) geometryDraws[drawIdx].name +#else +#define DrawValue(name) PushConstants.draw.name +#endif diff --git a/data/shader/deferred/geometry.vsh b/data/shader/deferred/geometry.vsh index fe7dcd91e..fce7e8748 100644 --- a/data/shader/deferred/geometry.vsh +++ b/data/shader/deferred/geometry.vsh @@ -1,5 +1,10 @@ #include <../wind.hsh> #include <../globals.hsh> +#include <../common/packing.hsh> +#include <../common/rotation.hsh> +#include <../common/texCoord.hsh> +#include <../common/opacity.hsh> +#include // New naming convention: // Vertex attributes v[Name] @@ -25,6 +30,18 @@ layout(location=3) in vec4 vTangent; layout(location=4) in vec4 vVertexColors; #endif +#ifdef SKINNED +layout(location=5) in uvec4 vJoints; +layout(location=6) in vec4 vWeights; +#endif + +#ifdef TEX_COORDS_1 +layout(location=7) in vec2 vTexCoord1; +#endif + +#ifdef INSTANCE_BUFFER +#include <../culling/instances.hsh> +#else layout(std430, set = 1, binding = 1) readonly buffer CurrentMatrices { mat3x4 currentMatrices[]; }; @@ -32,6 +49,32 @@ layout(std430, set = 1, binding = 1) readonly buffer CurrentMatrices { layout(std430, set = 1, binding = 2) readonly buffer LastMatrices { mat3x4 lastMatrices[]; }; +#endif + +#ifdef SKINNED +layout(std430, set = 1, binding = 4) readonly buffer CurrentJointMatrices { + mat3x4 currentJointMatrices[]; +}; + +layout(std430, set = 1, binding = 5) readonly buffer LastJointMatrices { + mat3x4 lastJointMatrices[]; +}; +#endif + +#ifdef SOFT_BODY +// Positions with the packed normal in w, each instance has the offset of its vertices +layout(std430, set = 1, binding = 24) readonly buffer CurrentSoftBodyVertices { + vec4 currentSoftBodyVertices[]; +}; + +layout(std430, set = 1, binding = 25) readonly buffer LastSoftBodyVertices { + vec4 lastSoftBodyVertices[]; +}; + +layout(std430, set = 1, binding = 26) readonly buffer SoftBodyVertexOffsets { + uint softBodyVertexOffsets[]; +}; +#endif // Vertex out parameters layout(location=0) out vec3 positionVS; @@ -51,61 +94,151 @@ layout(location=5) out vec4 vertexColorsVS; layout(location=7) out mat3 TBN; #endif -layout(set = 3, binding = 8) uniform sampler2D windNoiseMap; +#ifdef MATERIAL_GRAPH_SURFACE +layout(location=10) out vec3 objectPositionVS; +layout(location=11) out vec3 instancePositionVS; +layout(location=12) out vec3 objectNormalVS; +#endif -layout(push_constant) uniform constants { - uint vegetation; - uint invertUVs; - uint twoSided; - uint staticMesh; - uint materialIdx; - float normalScale; - float displacementScale; - float windTextureLod; - float windBendScale; - float windWiggleScale; - float uvAnimationX; - float uvAnimationY; - float uvTiling; - uint baseColorTextureIdx; - uint opacityTextureIdx; - uint normalTextureIdx; - uint roughnessTextureIdx; - uint metalnessTextureIdx; - uint aoTextureIdx; - uint heightTextureIdx; - uint emissiveTextureIdx; -} PushConstants; +layout(location=13) flat out uint lodVS; +#ifdef DRAW_DATA +layout(location=14) flat out uint drawIdxVS; +#endif + +layout(set = 3, binding = 8) uniform sampler2D windNoiseMap; // Functions void main() { +#ifdef DRAW_DATA + drawIdx = PushConstants.firstDraw + uint(gl_DrawID); + drawIdxVS = drawIdx; + lodVS = PushConstants.draw.lod + DrawValue(lod); +#else + lodVS = PushConstants.draw.lod + uint(gl_DrawID); +#endif + +#ifdef INSTANCE_BUFFER + uint instanceIdx = instanceIndices[gl_InstanceIndex]; + mat4 mMatrix = GetInstanceMatrix(instanceIdx); + mat4 mMatrixLast = DrawValue(staticMesh) > 0 ? mMatrix : GetLastInstanceMatrix(instanceIdx); +#else mat4 mMatrix = mat4(transpose(currentMatrices[gl_InstanceIndex])); - mat4 mMatrixLast = PushConstants.staticMesh > 0 ? mMatrix : mat4(transpose(lastMatrices[gl_InstanceIndex])); + mat4 mMatrixLast = DrawValue(staticMesh) > 0 ? mMatrix : mat4(transpose(lastMatrices[gl_InstanceIndex])); +#endif #ifdef TEX_COORDS - texCoordVS = PushConstants.invertUVs > 0 ? vec2(vTexCoord.x, 1.0 - vTexCoord.y) : vTexCoord; - texCoordVS += vec2(PushConstants.uvAnimationX, PushConstants.uvAnimationY) * globalData.time; - texCoordVS *= PushConstants.uvTiling; + texCoordVS = TransformTexCoord(vTexCoord, DrawValue(invertUVs) > 0, + vec2(DrawValue(uvAnimationX), DrawValue(uvAnimationY)), DrawValue(uvTiling)); #endif mat4 mvMatrix = globalData.vMatrix * mMatrix; vec3 position = vPosition; vec3 lastPosition = vPosition; + vec3 normal = vNormal.xyz; +#if defined(NORMAL_MAP) || defined(HEIGHT_MAP) + vec3 tangent = vTangent.xyz; +#endif - if (PushConstants.vegetation > 0) { +#ifdef SKINNED + uint jointOffset = PushConstants.deformOffset + (gl_InstanceIndex - PushConstants.instanceOffset) * PushConstants.jointCount; + vec4 weights = vWeights / dot(vWeights, vec4(1.0)); - // This is not well optimized and could use some work - vec3 windPosition = vec3(mMatrix * vec4(position, 1.0)); - vec2 windDir = normalize((inverse(mMatrix) * vec4(globalData.windDir.x, 0.0, globalData.windDir.y, 0.0)).xz); - position = WindAnimation(windNoiseMap, vPosition, windDir, PushConstants.windBendScale, - PushConstants.windWiggleScale, PushConstants.windTextureLod, globalData.time, windPosition); - lastPosition = WindAnimation(windNoiseMap, vPosition, windDir, PushConstants.windBendScale, - PushConstants.windWiggleScale, PushConstants.windTextureLod, - globalData.time - globalData.deltaTime, windPosition); + mat3x4 skinMatrix = weights.x * currentJointMatrices[jointOffset + vJoints.x] + + weights.y * currentJointMatrices[jointOffset + vJoints.y] + + weights.z * currentJointMatrices[jointOffset + vJoints.z] + + weights.w * currentJointMatrices[jointOffset + vJoints.w]; + mat3x4 lastSkinMatrix = weights.x * lastJointMatrices[jointOffset + vJoints.x] + + weights.y * lastJointMatrices[jointOffset + vJoints.y] + + weights.z * lastJointMatrices[jointOffset + vJoints.z] + + weights.w * lastJointMatrices[jointOffset + vJoints.w]; + position = vec4(vPosition, 1.0) * skinMatrix; + lastPosition = vec4(vPosition, 1.0) * lastSkinMatrix; + normal = vec4(normal, 0.0) * skinMatrix; +#if defined(NORMAL_MAP) || defined(HEIGHT_MAP) + tangent = vec4(tangent, 0.0) * skinMatrix; +#endif +#endif + +#ifdef SOFT_BODY + uint softBodyVertex = softBodyVertexOffsets[PushConstants.deformOffset + gl_InstanceIndex - + PushConstants.instanceOffset] + gl_VertexIndex; + vec4 softBodyCurrent = currentSoftBodyVertices[softBodyVertex]; + position = softBodyCurrent.xyz; + lastPosition = lastSoftBodyVertices[softBodyVertex].xyz; + normal = unpackUnitVector(floatBitsToInt(softBodyCurrent.w)).xyz; +#if defined(NORMAL_MAP) || defined(HEIGHT_MAP) + // Turned like the normal, so it stays along the surface while the cloth turns + tangent = RotateLike(tangent, normalize(vNormal.xyz), normal); +#endif +#endif + +#ifdef MATERIAL_GRAPH + vec2 graphTexCoord = vec2(0.0); + vec2 graphTexCoord1 = vec2(0.0); + vec3 graphTangent = vec3(1.0, 0.0, 0.0); + vec4 graphColor = vec4(1.0); +#ifdef TEX_COORDS + graphTexCoord = texCoordVS; +#endif +#ifdef TEX_COORDS_1 + graphTexCoord1 = DrawValue(invertUVs) > 0 ? vec2(vTexCoord1.x, 1.0 - vTexCoord1.y) : vTexCoord1; +#endif +#ifdef TANGENTS + graphTangent = vTangent.xyz; +#endif +#ifdef VERTEX_COLORS + graphColor = vVertexColors; +#endif + + MaterialVertexInput graphInput = CreateMaterialVertexInput(vPosition, position, normal, graphTangent, graphTexCoord, graphTexCoord1, + graphColor, mMatrix, globalData.time, PushConstants.materialGraphOffset); + +#ifdef MATERIAL_GRAPH_VERTEX_OPACITY + // The opacity is the same for the whole draw, moving all vertices outside the view keeps fragments free of discards +#ifdef TRANSLUCENT_PASS + if (EvaluateMaterialOpacity(graphInput) <= 0.0) { +#else + if (EvaluateMaterialOpacity(graphInput) < opacityCutoff) { +#endif + gl_Position = vec4(2.0, 2.0, 2.0, 1.0); + return; } +#endif + + WriteMaterialVaryings(graphInput); + +#ifdef MATERIAL_GRAPH_SURFACE + // Patterns stay on the surface when it moves + objectPositionVS = vPosition; + instancePositionVS = vec3(mMatrix[3]); +#endif + +#ifdef MATERIAL_GRAPH_VERTEX_OFFSET + normal = EvaluateMaterialVertexNormal(graphInput); + position += EvaluateMaterialVertexOffset(graphInput); + + graphInput = CreateMaterialVertexInput(vPosition, lastPosition, graphInput.normal, graphTangent, graphTexCoord, graphTexCoord1, + graphColor, mMatrixLast, globalData.time - globalData.deltaTime, PushConstants.materialGraphOffset); + lastPosition += EvaluateMaterialVertexOffset(graphInput); +#endif + +#ifdef MATERIAL_GRAPH_SURFACE + objectNormalVS = normal; +#endif +#endif + +#ifdef VEGETATION + vec3 windPosition = vec3(mMatrix * vec4(position, 1.0)); + vec2 windDir = GetWindDirection(mMatrix); + position = WindAnimation(windNoiseMap, position, windDir, DrawValue(windBendScale), + DrawValue(windWiggleScale), DrawValue(windTextureLod), globalData.time, windPosition); + lastPosition = WindAnimation(windNoiseMap, lastPosition, windDir, DrawValue(windBendScale), + DrawValue(windWiggleScale), DrawValue(windTextureLod), + globalData.time - globalData.deltaTime, windPosition); +#endif vec4 positionToCamera = mvMatrix * vec4(position, 1.0); positionVS = positionToCamera.xyz; @@ -127,18 +260,18 @@ void main() { mat3 cofactorMatrix = mat3(cross(modelView[1], modelView[2]), cross(modelView[2], modelView[0]), cross(modelView[0], modelView[1])); float orientation = dot(modelView[0], cofactorMatrix[0]) < 0.0 ? -1.0 : 1.0; - normalVS = orientation * (cofactorMatrix * vNormal.xyz); + normalVS = orientation * (cofactorMatrix * normal); #if defined(NORMAL_MAP) || defined(HEIGHT_MAP) - vec3 normal = normalize(normalVS); - float correctionFactor = orientation * vTangent.w * (PushConstants.invertUVs > 0 ? 1.0 : -1.0); - vec3 tangent = mat3(mvMatrix) * vTangent.xyz; - tangent = normalize(tangent - normal * dot(tangent, normal)); + vec3 normalView = normalize(normalVS); + float correctionFactor = orientation * vTangent.w * (DrawValue(invertUVs) > 0 ? 1.0 : -1.0); + vec3 tangentView = mat3(mvMatrix) * tangent; + tangentView = normalize(tangentView - normalView * dot(tangentView, normalView)); vec3 bitangent = normalize(correctionFactor * - cross(tangent, normal)); + cross(tangentView, normalView)); - TBN = mat3(tangent, bitangent, normal); + TBN = mat3(tangentView, bitangent, normalView); #endif #ifdef VERTEX_COLORS diff --git a/data/shader/deferred/indirectDiffuse.csh b/data/shader/deferred/indirectDiffuse.csh index c213b793c..f659f2efc 100644 --- a/data/shader/deferred/indirectDiffuse.csh +++ b/data/shader/deferred/indirectDiffuse.csh @@ -10,6 +10,9 @@ layout (local_size_x = 8, local_size_y = 8) in; +// Needs the work group size +#include <../common/upsample.hsh> + layout(set = 3, binding = 0, rgba16f) uniform image2D image; layout(set = 3, binding = 1) uniform sampler2D giTexture; layout(set = 3, binding = 2) uniform sampler2D lowResDepthTexture; @@ -31,18 +34,10 @@ shared float depths[36]; shared vec3 normals[36]; shared vec4 gi[36]; -const uint depthDataSize = (gl_WorkGroupSize.x / 2 + 2) * (gl_WorkGroupSize.y / 2 + 2); -const ivec2 unflattenedDepthDataSize = ivec2(gl_WorkGroupSize) / 2 + 2; - void LoadGroupSharedData() { - ivec2 workGroupOffset = ivec2(gl_WorkGroupID) * ivec2(gl_WorkGroupSize) / 2 - ivec2(1); - - // We assume data size is smaller than gl_WorkGroupSize.x + gl_WorkGroupSize.y - if (gl_LocalInvocationIndex < depthDataSize) { - ivec2 offset = Unflatten2D(int(gl_LocalInvocationIndex), unflattenedDepthDataSize); - offset += workGroupOffset; - offset = clamp(offset, ivec2(0), textureSize(lowResDepthTexture, 0)); + ivec2 offset; + if (GetUpsampleTileTexel(textureSize(lowResDepthTexture, 0), offset)) { depths[gl_LocalInvocationIndex] = ConvertDepthToViewSpaceDepth(texelFetch(lowResDepthTexture, offset, 0).r); vec3 normal = DecodeNormal(texelFetch(lowResNormalTexture, offset, 0).rg); @@ -57,40 +52,6 @@ void LoadGroupSharedData() { } -const ivec2 offsets[9] = ivec2[9]( - ivec2(-1, -1), - ivec2(0, -1), - ivec2(1, -1), - ivec2(-1, 0), - ivec2(0, 0), - ivec2(1, 0), - ivec2(-1, 1), - ivec2(0, 1), - ivec2(1, 1) -); - -const ivec2 pixelOffsets[4] = ivec2[4]( - ivec2(0, 0), - ivec2(1, 0), - ivec2(0, 1), - ivec2(1, 1) -); - -int NearestDepth(float referenceDepth, float[9] depthVec) { - - int idx = 0; - float nearest = distance(referenceDepth, depthVec[0]); - for (int i = 1; i < 9; i++) { - float dist = distance(referenceDepth, depthVec[i]); - if (dist < nearest) { - nearest = dist; - idx = i; - } - } - return idx; - -} - float GetPixelEdgeWeight(int sharedMemoryOffset, float referenceDepth, vec3 referenceNormal) { float depth = depths[sharedMemoryOffset]; @@ -163,8 +124,8 @@ void main() { if (Uniforms.giDownsampled2x > 0 || Uniforms.reflectionDownsampled2x > 0) LoadGroupSharedData(); - if (gl_GlobalInvocationID.x > imageSize(image).x || - gl_GlobalInvocationID.y > imageSize(image).y) + if (gl_GlobalInvocationID.x >= imageSize(image).x || + gl_GlobalInvocationID.y >= imageSize(image).y) return; ivec2 resolution = imageSize(image); diff --git a/data/shader/deferred/indirectSpecular.csh b/data/shader/deferred/indirectSpecular.csh index 3389a3810..5d972e5f7 100644 --- a/data/shader/deferred/indirectSpecular.csh +++ b/data/shader/deferred/indirectSpecular.csh @@ -2,6 +2,7 @@ #include <../brdf/brdfEval.hsh> #include <../common/flatten.hsh> +#include <../common/stencil.hsh> #ifdef DDGI #include <../ddgi/ddgi.hsh> @@ -9,11 +10,18 @@ layout (local_size_x = 8, local_size_y = 8) in; +// Needs the work group size +#include <../common/upsample.hsh> + layout(set = 3, binding = 0, rgba16f) uniform image2D image; layout(set = 3, binding = 1) uniform sampler2D reflectionTexture; layout(set = 3, binding = 2) uniform sampler2D giTexture; layout(set = 3, binding = 3) uniform sampler2D lowResDepthTexture; layout(set = 3, binding = 4) uniform sampler2D lowResNormalTexture; +#ifdef SEPARATE_REFLECTION +// Where the reflections start, the ocean or a translucent surface in front of the G-buffer +layout(set = 3, binding = 6) uniform sampler2D reflectionDepthTexture; +#endif layout(set = 3, binding = 5) uniform UniformBuffer { int reflectionDownsampled2x; @@ -33,18 +41,10 @@ shared vec3 normals[36]; shared float aos[36]; shared vec3 reflections[36]; -const uint depthDataSize = (gl_WorkGroupSize.x / 2 + 2) * (gl_WorkGroupSize.y / 2 + 2); -const ivec2 unflattenedDepthDataSize = ivec2(gl_WorkGroupSize) / 2 + 2; - void LoadGroupSharedData() { - ivec2 workGroupOffset = ivec2(gl_WorkGroupID) * ivec2(gl_WorkGroupSize) / 2 - ivec2(1); - - // We assume data size is smaller than gl_WorkGroupSize.x + gl_WorkGroupSize.y - if (gl_LocalInvocationIndex < depthDataSize) { - ivec2 offset = Unflatten2D(int(gl_LocalInvocationIndex), unflattenedDepthDataSize); - offset += workGroupOffset; - offset = clamp(offset, ivec2(0), textureSize(lowResDepthTexture, 0)); + ivec2 offset; + if (GetUpsampleTileTexel(textureSize(lowResDepthTexture, 0), offset)) { depths[gl_LocalInvocationIndex] = ConvertDepthToViewSpaceDepth(texelFetch(lowResDepthTexture, offset, 0).r); vec3 normal = DecodeNormal(texelFetch(lowResNormalTexture, offset, 0).rg); @@ -63,40 +63,6 @@ void LoadGroupSharedData() { } -const ivec2 offsets[9] = ivec2[9]( - ivec2(-1, -1), - ivec2(0, -1), - ivec2(1, -1), - ivec2(-1, 0), - ivec2(0, 0), - ivec2(1, 0), - ivec2(-1, 1), - ivec2(0, 1), - ivec2(1, 1) -); - -const ivec2 pixelOffsets[4] = ivec2[4]( - ivec2(0, 0), - ivec2(1, 0), - ivec2(0, 1), - ivec2(1, 1) -); - -int NearestDepth(float referenceDepth, float[9] depthVec) { - - int idx = 0; - float nearest = distance(referenceDepth, depthVec[0]); - for (int i = 1; i < 9; i++) { - float dist = distance(referenceDepth, depthVec[i]); - if (dist < nearest) { - nearest = dist; - idx = i; - } - } - return idx; - -} - float UpsampleAo2x(float referenceDepth) { ivec2 pixel = ivec2(gl_LocalInvocationID) / 2 + ivec2(1); @@ -128,7 +94,7 @@ float GetPixelEdgeWeight(int sharedMemoryOffset, float referenceDepth, vec3 refe return depthWeight * normalWeight; } -UpsampleResult Upsample(float referenceDepth, vec3 referenceNormal, float referenceRoughness, vec2 highResPixel) { +UpsampleResult Upsample(float referenceDepth, vec3 referenceNormal, vec2 highResPixel) { UpsampleResult result; @@ -167,7 +133,7 @@ UpsampleResult Upsample(float referenceDepth, vec3 referenceNormal, float refere result.ao /= totalWeight; float maxWeight = 0.0; - int maxMemoryIdx = 0; + int maxMemoryIdx = Flatten2D(pixel, unflattenedDepthDataSize); for (uint i = 0; i < 9; i++) { int sharedMemoryOffset = Flatten2D(pixel + offsets[i], unflattenedDepthDataSize); @@ -178,7 +144,8 @@ UpsampleResult Upsample(float referenceDepth, vec3 referenceNormal, float refere } } - if (totalWeight < maxWeight && referenceRoughness > 0.01) { + // Only fall back to the most similar neighbor when the bilinear footprint is rejected + if (totalWeight <= 0.05 * maxWeight) { result.ao = aos[maxMemoryIdx]; result.reflection = reflections[maxMemoryIdx]; } @@ -194,8 +161,8 @@ void main() { if (Uniforms.giDownsampled2x > 0 || Uniforms.reflectionDownsampled2x > 0) LoadGroupSharedData(); - if (gl_GlobalInvocationID.x > imageSize(image).x || - gl_GlobalInvocationID.y > imageSize(image).y) + if (gl_GlobalInvocationID.x >= imageSize(image).x || + gl_GlobalInvocationID.y >= imageSize(image).y) return; ivec2 resolution = imageSize(image); @@ -219,7 +186,7 @@ void main() { vec3 worldNormal = normalize(vec3(globalData.ivMatrix * vec4(surface.N, 0.0))); vec3 geometryWorldNormal = normalize(vec3(globalData.ivMatrix * vec4(geometryNormal, 0.0))); - upsampleResult = Upsample(depth, surface.N, surface.material.roughness, vec2(pixel)); + upsampleResult = Upsample(depth, surface.N, vec2(pixel)); // Indirect specular BRDF vec3 R = normalize(mat3(globalData.ivMatrix) * reflect(-surface.V, surface.N)); @@ -231,6 +198,11 @@ void main() { #ifdef REFLECTION vec3 indirectSpecular = Uniforms.reflectionDownsampled2x > 0 ? upsampleResult.reflection : textureLod(reflectionTexture, texCoord, 0.0).rgb; +#ifdef SEPARATE_REFLECTION + // Behind the surface the reflections were traced from, the probe reflects + if (texelFetch(reflectionDepthTexture, pixel, 0).r < depth) + indirectSpecular = prefilteredSpecular; +#endif #else #ifdef DDGI vec3 indirectSpecular = IsInsideVolume(worldPosition) ? vec3(0.0) : prefilteredSpecular; @@ -245,7 +217,7 @@ void main() { // This normally only accounts for diffuse occlusion, we need seperate terms // for diffuse and specular. #ifdef SSGI - float ao = Uniforms.giDownsampled2x > 0 ? upsampleResult.ao : texelFetch(giTexture, pixel, 0).r; + float ao = Uniforms.giDownsampled2x > 0 ? upsampleResult.ao : texelFetch(giTexture, pixel, 0).a; indirect *= vec3(pow(ao, Uniforms.aoStrength)); #endif diff --git a/data/shader/deferred/lightCulling.csh b/data/shader/deferred/lightCulling.csh index 24193c19a..0c31c07ca 100644 --- a/data/shader/deferred/lightCulling.csh +++ b/data/shader/deferred/lightCulling.csh @@ -36,8 +36,13 @@ void main() { float depth = texelFetch(depthTexture, pixel, 0).r; float viewDepth = ConvertDepthToViewSpaceDepth(depth); + // Translucent surfaces are in front of the opaque ones, their tiles reach from the near plane if (gl_LocalInvocationIndex == 0u) { +#ifdef FROM_NEAR_PLANE + sharedDepthMin = floatBitsToUint(0.0); +#else sharedDepthMin = floatBitsToUint(depth); +#endif sharedDepthMax = floatBitsToUint(depth); depthMask = 0; } @@ -115,10 +120,14 @@ void main() { } int shiftCount = 31 - endBin + startBin; - int downShift = (0xFFFFFFFF >> shiftCount); + int downShift = int(0xFFFFFFFFu >> uint(shiftCount)); int lightMask = downShift << startBin; +#ifdef FROM_NEAR_PLANE + if (visible) { +#else if (visible && (lightMask & depthMask) != 0) { +#endif atomicOr(sharedLightBuckets[lightBucketIdx], 1 << lightBuckedBit); } } diff --git a/data/shader/deferred/sss.csh b/data/shader/deferred/sss.csh index 081a28885..0b0a6411f 100644 --- a/data/shader/deferred/sss.csh +++ b/data/shader/deferred/sss.csh @@ -24,14 +24,6 @@ layout(push_constant) uniform constants { int jitter; } pushConstants; -float EdgeFadeOut(vec2 screenPos, float fadeDist) { - - screenPos = abs(screenPos * 2.0 - 1.0); - vec2 fadeOut = (screenPos - 1.0 + fadeDist) / fadeDist; - return saturate(1.0 - max(fadeOut.x, fadeOut.y)); - -} - vec2 PosToUV(vec3 pos) { vec4 clipSpace = globalData.pMatrix * vec4(pos, 1.0); @@ -45,11 +37,17 @@ void main() { ivec2 pixel = ivec2(gl_GlobalInvocationID); ivec2 resolution = imageSize(image); - if (pixel.x > resolution.x || - pixel.y > resolution.y) + if (pixel.x >= resolution.x || + pixel.y >= resolution.y) return; float depth = texelFetch(depthTexture, pixel, 0).r; + // Sky pixels don't read the shadows + if (depth == 1.0) { + imageStore(image, pixel, vec4(1.0)); + return; + } + vec3 normal = DecodeNormal(texelFetch(normalTexture, pixel, 0).rg); vec2 texCoord = (vec2(pixel) + 0.5) / vec2(resolution); diff --git a/data/shader/deferred/texture.hsh b/data/shader/deferred/texture.hsh index c225188af..54d44f9c6 100644 --- a/data/shader/deferred/texture.hsh +++ b/data/shader/deferred/texture.hsh @@ -1,40 +1,9 @@ #include <../globals.hsh> -#ifndef BINDLESS_TEXTURES -#ifdef BASE_COLOR_MAP -layout(set = 3, binding = 0) uniform sampler2D baseColorMap; -#endif -#ifdef OPACITY_MAP -layout(set = 3, binding = 1) uniform sampler2D opacityMap; -#endif -#ifdef NORMAL_MAP -layout(set = 3, binding = 2) uniform sampler2D normalMap; -#endif -#ifdef ROUGHNESS_MAP -layout(set = 3, binding = 3) uniform sampler2D roughnessMap; -#endif -#ifdef METALNESS_MAP -layout(set = 3, binding = 4) uniform sampler2D metalnessMap; -#endif -#ifdef AO_MAP -layout(set = 3, binding = 5) uniform sampler2D aoMap; -#endif -#ifdef HEIGHT_MAP -layout(set = 3, binding = 6) uniform sampler2D heightMap; -#endif -#ifdef EMISSIVE_MAP -layout(set = 3, binding = 7) uniform sampler2D emissiveMap; -#endif -#endif - vec3 SampleBaseColor(vec2 texCoords, uint textureID, float bias) { #ifdef BASE_COLOR_MAP -#ifdef BINDLESS_TEXTURES return texture(sampler2D(bindlessTextures[textureID], bindlessSampler), texCoords, bias).rgb; -#else - return texture(baseColorMap, texCoords, bias).rgb; -#endif #else return vec3(1.0); #endif @@ -44,11 +13,7 @@ vec3 SampleBaseColor(vec2 texCoords, uint textureID, float bias) { float SampleOpacity(vec2 texCoords, uint textureID, float bias) { #ifdef OPACITY_MAP -#ifdef BINDLESS_TEXTURES return texture(sampler2D(bindlessTextures[textureID], bindlessSampler), texCoords, bias).r; -#else - return texture(opacityMap, texCoords, bias).r; -#endif #else return 1.0; #endif @@ -58,11 +23,7 @@ float SampleOpacity(vec2 texCoords, uint textureID, float bias) { vec3 SampleNormal(vec2 texCoords, uint textureID, float bias) { #ifdef NORMAL_MAP -#ifdef BINDLESS_TEXTURES return 2.0 * texture(sampler2D(bindlessTextures[textureID], bindlessSampler), texCoords, bias).rgb - 1.0; -#else - return 2.0 * texture(normalMap, texCoords, bias).rgb - 1.0; -#endif #else return vec3(0.0); #endif @@ -72,11 +33,7 @@ vec3 SampleNormal(vec2 texCoords, uint textureID, float bias) { float SampleRoughness(vec2 texCoords, uint textureID, float bias) { #ifdef ROUGHNESS_MAP -#ifdef BINDLESS_TEXTURES return texture(sampler2D(bindlessTextures[textureID], bindlessSampler), texCoords, bias).r; -#else - return texture(roughnessMap, texCoords, bias).r; -#endif #else return 1.0; #endif @@ -86,11 +43,7 @@ float SampleRoughness(vec2 texCoords, uint textureID, float bias) { float SampleMetalness(vec2 texCoords, uint textureID, float bias) { #ifdef METALNESS_MAP -#ifdef BINDLESS_TEXTURES return texture(sampler2D(bindlessTextures[textureID], bindlessSampler), texCoords, bias).r; -#else - return texture(metalnessMap, texCoords, bias).r; -#endif #else return 0.0; #endif @@ -100,11 +53,7 @@ float SampleMetalness(vec2 texCoords, uint textureID, float bias) { float SampleAo(vec2 texCoords, uint textureID, float bias) { #ifdef AO_MAP -#ifdef BINDLESS_TEXTURES return texture(sampler2D(bindlessTextures[textureID], bindlessSampler), texCoords, bias).r; -#else - return texture(aoMap, texCoords, bias).r; -#endif #else return 1.0; #endif @@ -114,11 +63,7 @@ float SampleAo(vec2 texCoords, uint textureID, float bias) { float SampleHeight(vec2 texCoords, uint textureID, vec2 ddx, vec2 ddy) { #ifdef HEIGHT_MAP -#ifdef BINDLESS_TEXTURES return textureGrad(sampler2D(bindlessTextures[textureID], bindlessSampler), texCoords, ddx, ddy).r; -#else - return textureGrad(heightMap, texCoords, ddx, ddy).r; -#endif #else return 0.0; #endif @@ -128,11 +73,7 @@ float SampleHeight(vec2 texCoords, uint textureID, vec2 ddx, vec2 ddy) { vec3 SampleEmissive(vec2 texCoords, uint textureID, float bias) { #ifdef EMISSIVE_MAP -#ifdef BINDLESS_TEXTURES return texture(sampler2D(bindlessTextures[textureID], bindlessSampler), texCoords, bias).rgb; -#else - return texture(emissiveMap, texCoords, bias).rgb; -#endif #else return vec3(0.0); #endif diff --git a/data/shader/example/compute.csh b/data/shader/example/compute.csh index 8d8f745a2..64bc852a7 100644 --- a/data/shader/example/compute.csh +++ b/data/shader/example/compute.csh @@ -14,8 +14,8 @@ const float noiseScale = 0.1; void main() { ivec2 pixel = ivec2(gl_GlobalInvocationID); - if (pixel.x > imageSize(image).x || - pixel.y > imageSize(image).y) + if (pixel.x >= imageSize(image).x || + pixel.y >= imageSize(image).y) return; // Load the color from the image diff --git a/data/shader/exposure/histogram.csh b/data/shader/exposure/histogram.csh index a02b931d8..ad138f017 100644 --- a/data/shader/exposure/histogram.csh +++ b/data/shader/exposure/histogram.csh @@ -32,7 +32,7 @@ void main() { barrier(); - ivec2 pixel = ivec2(gl_GlobalInvocationID); + ivec2 pixel = 2 * ivec2(gl_GlobalInvocationID); if (pixel.x < textureSize(hdrTexture, 0).x && pixel.y < textureSize(hdrTexture, 0).y) { diff --git a/data/shader/fsr2/ffx_fsr2_callbacks_glsl.h b/data/shader/fsr2/ffx_fsr2_callbacks_glsl.h index 790219b44..b964ca275 100644 --- a/data/shader/fsr2/ffx_fsr2_callbacks_glsl.h +++ b/data/shader/fsr2/ffx_fsr2_callbacks_glsl.h @@ -238,7 +238,7 @@ layout (set = 0, binding = 1) uniform sampler s_LinearClamp; layout (set = 1, binding = FSR2_BIND_UAV_DILATED_MOTION_VECTORS, rg16f) writeonly uniform image2D rw_dilated_motion_vectors; #endif #if defined FSR2_BIND_UAV_DILATED_DEPTH - layout (set = 1, binding = FSR2_BIND_UAV_DILATED_DEPTH, r16f) writeonly uniform image2D rw_dilatedDepth; + layout (set = 1, binding = FSR2_BIND_UAV_DILATED_DEPTH, r32f) writeonly uniform image2D rw_dilatedDepth; #endif #if defined FSR2_BIND_UAV_INTERNAL_UPSCALED layout (set = 1, binding = FSR2_BIND_UAV_INTERNAL_UPSCALED, rgba16f) writeonly uniform image2D rw_internal_upscaled_color; @@ -253,7 +253,7 @@ layout (set = 0, binding = 1) uniform sampler s_LinearClamp; layout(set = 1, binding = FSR2_BIND_UAV_NEW_LOCKS, r8) uniform image2D rw_new_locks; #endif #if defined FSR2_BIND_UAV_PREPARED_INPUT_COLOR - layout (set = 1, binding = FSR2_BIND_UAV_PREPARED_INPUT_COLOR, rgba16) writeonly uniform image2D rw_prepared_input_color; + layout (set = 1, binding = FSR2_BIND_UAV_PREPARED_INPUT_COLOR, rgba16f) writeonly uniform image2D rw_prepared_input_color; #endif #if defined FSR2_BIND_UAV_LUMA_HISTORY layout (set = 1, binding = FSR2_BIND_UAV_LUMA_HISTORY, rgba8) uniform image2D rw_luma_history; @@ -281,10 +281,10 @@ layout (set = 0, binding = 1) uniform sampler s_LinearClamp; #endif #if defined FSR2_BIND_UAV_AUTOREACTIVE - layout(set = 1, binding = FSR2_BIND_UAV_AUTOREACTIVE, r32f) uniform image2D rw_output_autoreactive; + layout(set = 1, binding = FSR2_BIND_UAV_AUTOREACTIVE, r8) uniform image2D rw_output_autoreactive; #endif #if defined FSR2_BIND_UAV_AUTOCOMPOSITION - layout(set = 1, binding = FSR2_BIND_UAV_AUTOCOMPOSITION, r32f) uniform image2D rw_output_autocomposition; + layout(set = 1, binding = FSR2_BIND_UAV_AUTOCOMPOSITION, r8) uniform image2D rw_output_autocomposition; #endif #if defined FSR2_BIND_UAV_PREV_PRE_ALPHA_COLOR layout(set = 1, binding = FSR2_BIND_UAV_PREV_PRE_ALPHA_COLOR, r11f_g11f_b10f) uniform image2D rw_output_prev_color_pre_alpha; diff --git a/data/shader/fsr2/ffx_spd.h b/data/shader/fsr2/ffx_spd.h index 5ce24ec87..630fa0b28 100644 --- a/data/shader/fsr2/ffx_spd.h +++ b/data/shader/fsr2/ffx_spd.h @@ -332,6 +332,8 @@ void SpdDownsampleMip_2(FfxUInt32 x, FfxUInt32 y, FfxUInt32x2 workGroupID, FfxUI #else FfxFloat32x4 v = SpdLoadIntermediate(x, y); v = SpdReduceQuad(v); + // The other quads have to read their values before the results overwrite them + SpdWorkgroupShuffleBarrier(); // quad index 0 stores result if (localInvocationIndex % 4 == 0) { @@ -367,16 +369,19 @@ void SpdDownsampleMip_3(FfxUInt32 x, FfxUInt32 y, FfxUInt32x2 workGroupID, FfxUI SpdStoreIntermediate(x * 4 + y, y * 4, v); } #else + FfxFloat32x4 v = FfxFloat32x4(0); if (localInvocationIndex < 64) { - FfxFloat32x4 v = SpdLoadIntermediate(x * 2 + y % 2, y * 2); - v = SpdReduceQuad(v); - // quad index 0 stores result - if (localInvocationIndex % 4 == 0) - { - SpdStore(FfxInt32x2(workGroupID.xy * 4) + FfxInt32x2(x / 2, y / 2), v, mip, slice); - SpdStoreIntermediate(x * 2 + y / 2, y * 2, v); - } + v = SpdLoadIntermediate(x * 2 + y % 2, y * 2); + v = SpdReduceQuad(v); + } + // The other quads have to read their values before the results overwrite them + SpdWorkgroupShuffleBarrier(); + // quad index 0 stores result + if (localInvocationIndex < 64 && localInvocationIndex % 4 == 0) + { + SpdStore(FfxInt32x2(workGroupID.xy * 4) + FfxInt32x2(x / 2, y / 2), v, mip, slice); + SpdStoreIntermediate(x * 2 + y / 2, y * 2, v); } #endif } @@ -400,16 +405,19 @@ void SpdDownsampleMip_4(FfxUInt32 x, FfxUInt32 y, FfxUInt32x2 workGroupID, FfxUI SpdStoreIntermediate(x + y * 2, 0, v); } #else + FfxFloat32x4 v = FfxFloat32x4(0); if (localInvocationIndex < 16) { - FfxFloat32x4 v = SpdLoadIntermediate(x * 4 + y, y * 4); - v = SpdReduceQuad(v); - // quad index 0 stores result - if (localInvocationIndex % 4 == 0) - { - SpdStore(FfxInt32x2(workGroupID.xy * 2) + FfxInt32x2(x / 2, y / 2), v, mip, slice); - SpdStoreIntermediate(x / 2 + y, 0, v); - } + v = SpdLoadIntermediate(x * 4 + y, y * 4); + v = SpdReduceQuad(v); + } + // The other quads have to read their values before the results overwrite them + SpdWorkgroupShuffleBarrier(); + // quad index 0 stores result + if (localInvocationIndex < 16 && localInvocationIndex % 4 == 0) + { + SpdStore(FfxInt32x2(workGroupID.xy * 2) + FfxInt32x2(x / 2, y / 2), v, mip, slice); + SpdStoreIntermediate(x / 2 + y, 0, v); } #endif } @@ -743,6 +751,8 @@ void SpdDownsampleMip_2H(FfxUInt32 x, FfxUInt32 y, FfxUInt32x2 workGroupID, FfxU #else FfxFloat16x4 v = SpdLoadIntermediateH(x, y); v = SpdReduceQuadH(v); + // The other quads have to read their values before the results overwrite them + SpdWorkgroupShuffleBarrier(); // quad index 0 stores result if (localInvocationIndex % 4 == 0) { @@ -778,16 +788,19 @@ void SpdDownsampleMip_3H(FfxUInt32 x, FfxUInt32 y, FfxUInt32x2 workGroupID, FfxU SpdStoreIntermediateH(x * 4 + y, y * 4, v); } #else + FfxFloat16x4 v = FfxFloat16x4(0); if (localInvocationIndex < 64) { - FfxFloat16x4 v = SpdLoadIntermediateH(x * 2 + y % 2, y * 2); - v = SpdReduceQuadH(v); - // quad index 0 stores result - if (localInvocationIndex % 4 == 0) - { - SpdStoreH(FfxInt32x2(workGroupID.xy * 4) + FfxInt32x2(x / 2, y / 2), v, mip, slice); - SpdStoreIntermediateH(x * 2 + y / 2, y * 2, v); - } + v = SpdLoadIntermediateH(x * 2 + y % 2, y * 2); + v = SpdReduceQuadH(v); + } + // The other quads have to read their values before the results overwrite them + SpdWorkgroupShuffleBarrier(); + // quad index 0 stores result + if (localInvocationIndex < 64 && localInvocationIndex % 4 == 0) + { + SpdStoreH(FfxInt32x2(workGroupID.xy * 4) + FfxInt32x2(x / 2, y / 2), v, mip, slice); + SpdStoreIntermediateH(x * 2 + y / 2, y * 2, v); } #endif } @@ -811,16 +824,19 @@ void SpdDownsampleMip_4H(FfxUInt32 x, FfxUInt32 y, FfxUInt32x2 workGroupID, FfxU SpdStoreIntermediateH(x + y * 2, 0, v); } #else + FfxFloat16x4 v = FfxFloat16x4(0); if (localInvocationIndex < 16) { - FfxFloat16x4 v = SpdLoadIntermediateH(x * 4 + y, y * 4); - v = SpdReduceQuadH(v); - // quad index 0 stores result - if (localInvocationIndex % 4 == 0) - { - SpdStoreH(FfxInt32x2(workGroupID.xy * 2) + FfxInt32x2(x / 2, y / 2), v, mip, slice); - SpdStoreIntermediateH(x / 2 + y, 0, v); - } + v = SpdLoadIntermediateH(x * 4 + y, y * 4); + v = SpdReduceQuadH(v); + } + // The other quads have to read their values before the results overwrite them + SpdWorkgroupShuffleBarrier(); + // quad index 0 stores result + if (localInvocationIndex < 16 && localInvocationIndex % 4 == 0) + { + SpdStoreH(FfxInt32x2(workGroupID.xy * 2) + FfxInt32x2(x / 2, y / 2), v, mip, slice); + SpdStoreIntermediateH(x / 2 + y, 0, v); } #endif } diff --git a/data/shader/gbuffer/downsampleGBuffer2x.csh b/data/shader/gbuffer/downsampleGBuffer2x.csh index 505fd7a09..84e29306b 100644 --- a/data/shader/gbuffer/downsampleGBuffer2x.csh +++ b/data/shader/gbuffer/downsampleGBuffer2x.csh @@ -13,8 +13,8 @@ layout (set = 3, binding = 4) uniform sampler2D velocityIn; layout (set = 3, binding = 5) uniform usampler2D materialIdxIn; layout (set = 3, binding = 6, r32f) writeonly uniform image2D depthOut; -layout (set = 3, binding = 7, rgba16f) writeonly uniform image2D normalOut; -layout (set = 3, binding = 8, rgba16f) writeonly uniform image2D geometryNormalOut; +layout (set = 3, binding = 7, rg16f) writeonly uniform image2D normalOut; +layout (set = 3, binding = 8, rg16f) writeonly uniform image2D geometryNormalOut; layout (set = 3, binding = 9, rgba8) writeonly uniform image2D roughnessMetallicAoOut; layout (set = 3, binding = 10, rg16f) writeonly uniform image2D velocityOut; layout (set = 3, binding = 11, r16ui) writeonly uniform uimage2D materialIdxOut; @@ -105,23 +105,23 @@ void main() { imageStore(depthOut, coord, vec4(depth, 0.0, 0.0, 1.0)); #ifndef DEPTH_ONLY - vec3 normal00 = texelFetch(normalIn, coord * 2 + ivec2(0, 0), 0).rgb; - vec3 normal10 = texelFetch(normalIn, coord * 2 + ivec2(1, 0), 0).rgb; - vec3 normal01 = texelFetch(normalIn, coord * 2 + ivec2(0, 1), 0).rgb; - vec3 normal11 = texelFetch(normalIn, coord * 2 + ivec2(1, 1), 0).rgb; + vec2 normal00 = texelFetch(normalIn, coord * 2 + ivec2(0, 0), 0).rg; + vec2 normal10 = texelFetch(normalIn, coord * 2 + ivec2(1, 0), 0).rg; + vec2 normal01 = texelFetch(normalIn, coord * 2 + ivec2(0, 1), 0).rg; + vec2 normal11 = texelFetch(normalIn, coord * 2 + ivec2(1, 1), 0).rg; - vec3 normal = depthIdx < 2 ? (depthIdx < 1 ? normal00 : normal10) : + vec2 normal = depthIdx < 2 ? (depthIdx < 1 ? normal00 : normal10) : (depthIdx < 3 ? normal01 : normal11); - imageStore(normalOut, coord, vec4(normal, 1.0)); + imageStore(normalOut, coord, vec4(normal, 0.0, 0.0)); - vec3 geometryNormal00 = texelFetch(geometryNormalIn, coord * 2 + ivec2(0, 0), 0).rgb; - vec3 geometryNormal10 = texelFetch(geometryNormalIn, coord * 2 + ivec2(1, 0), 0).rgb; - vec3 geometryNormal01 = texelFetch(geometryNormalIn, coord * 2 + ivec2(0, 1), 0).rgb; - vec3 geometryNormal11 = texelFetch(geometryNormalIn, coord * 2 + ivec2(1, 1), 0).rgb; + vec2 geometryNormal00 = texelFetch(geometryNormalIn, coord * 2 + ivec2(0, 0), 0).rg; + vec2 geometryNormal10 = texelFetch(geometryNormalIn, coord * 2 + ivec2(1, 0), 0).rg; + vec2 geometryNormal01 = texelFetch(geometryNormalIn, coord * 2 + ivec2(0, 1), 0).rg; + vec2 geometryNormal11 = texelFetch(geometryNormalIn, coord * 2 + ivec2(1, 1), 0).rg; - vec3 geometryNormal = depthIdx < 2 ? (depthIdx < 1 ? geometryNormal00 : geometryNormal10) : + vec2 geometryNormal = depthIdx < 2 ? (depthIdx < 1 ? geometryNormal00 : geometryNormal10) : (depthIdx < 3 ? geometryNormal01 : geometryNormal11); - imageStore(geometryNormalOut, coord, vec4(geometryNormal, 1.0)); + imageStore(geometryNormalOut, coord, vec4(geometryNormal, 0.0, 0.0)); vec3 roughnessMetallicAo00 = texelFetch(roughnessMetallicAoIn, coord * 2 + ivec2(0, 0), 0).rgb; vec3 roughnessMetallicAo10 = texelFetch(roughnessMetallicAoIn, coord * 2 + ivec2(1, 0), 0).rgb; diff --git a/data/shader/gbuffer/generateReactiveMask.csh b/data/shader/gbuffer/generateReactiveMask.csh index 237539962..d7a4ddf36 100644 --- a/data/shader/gbuffer/generateReactiveMask.csh +++ b/data/shader/gbuffer/generateReactiveMask.csh @@ -5,6 +5,15 @@ layout (local_size_x = 8, local_size_y = 8) in; layout (set = 3, binding = 0, r8) uniform image2D reactiveMaskImage; layout (set = 3, binding = 1) uniform usampler2D stencilTexture; layout (set = 3, binding = 2) uniform sampler2D roughnessMetalnessAoTexture; +layout (set = 3, binding = 3) uniform usampler2D lastStencilTexture; +layout (set = 3, binding = 4) uniform sampler2D velocityTexture; +#ifdef TRANSLUCENCY +layout (set = 3, binding = 5) uniform sampler2D translucencyTexture; +#endif + +layout(push_constant) uniform constants { + int hasHistory; +} pushConstants; void main() { @@ -22,6 +31,20 @@ void main() { vec3 roughnessMetallicAo = texelFetch(roughnessMetalnessAoTexture, pixel, 0).rgb; float reflectiveReactivity = min(1.0, 5.0 * roughnessMetallicAo.r); reactivity = max(reactivity, mix(0.5, 0.0, reflectiveReactivity)); +#ifdef TRANSLUCENCY + // Blended surfaces don't move with the velocity of what is behind them + reactivity = max(reactivity, 0.9 * texelFetch(translucencyTexture, pixel, 0).r); +#endif + + bool rejectHistory = features.noTemporalAccumulation; + if (pushConstants.hasHistory > 0) { + vec2 uv = (vec2(pixel) + 0.5) / vec2(size) + texelFetch(velocityTexture, pixel, 0).rg; + ivec2 historyPixel = clamp(ivec2(uv * vec2(size)), ivec2(0), size - 1); + StencilFeatures historyFeatures = DecodeStencilFeatures(texelFetch(lastStencilTexture, historyPixel, 0).r); + StencilFeatures previousFeatures = DecodeStencilFeatures(texelFetch(lastStencilTexture, pixel, 0).r); + rejectHistory = rejectHistory || historyFeatures.noTemporalAccumulation || previousFeatures.noTemporalAccumulation; + } + reactivity = rejectHistory ? 1.0 : reactivity; imageStore(reactiveMaskImage, pixel, vec4(reactivity, 0.0, 0.0, 0.0)); diff --git a/data/shader/gbuffer/hiz.csh b/data/shader/gbuffer/hiz.csh new file mode 100644 index 000000000..4a6d3535d --- /dev/null +++ b/data/shader/gbuffer/hiz.csh @@ -0,0 +1,111 @@ +// Hierarchical depth with the closest depth in r and the farthest depth plus the thickness in g. +// Each work group reduces a 32x32 block of the input and writes up to six levels. + +#include <../globals.hsh> + +layout (local_size_x = 16, local_size_y = 16) in; + +layout(set = 3, binding = 0) uniform sampler2D depthIn; +layout(set = 3, binding = 1, rg32f) readonly uniform image2D levelIn; + +layout(set = 3, binding = 2, rg32f) writeonly uniform image2D levelOut0; +layout(set = 3, binding = 3, rg32f) writeonly uniform image2D levelOut1; +layout(set = 3, binding = 4, rg32f) writeonly uniform image2D levelOut2; +layout(set = 3, binding = 5, rg32f) writeonly uniform image2D levelOut3; +layout(set = 3, binding = 6, rg32f) writeonly uniform image2D levelOut4; +layout(set = 3, binding = 7, rg32f) writeonly uniform image2D levelOut5; + +layout(push_constant) uniform constants { + ivec2 inputSize; + int fromDepth; + int levelCount; + float distanceThickness; +} pushConstants; + +shared vec2 sharedMinMax[16][16]; + +vec2 FetchTexel(ivec2 texel) { + + if (any(greaterThanEqual(texel, pushConstants.inputSize))) + return vec2(1.0); + + if (pushConstants.fromDepth > 0) { + float depth = texelFetch(depthIn, texel, 0).r; + if (depth >= 1.0 || pushConstants.distanceThickness <= 0.0) + return vec2(depth); + + vec2 viewSpace = (globalData.ipMatrix * vec4(0.0, 0.0, depth, 1.0)).zw; + float viewZ = viewSpace.x / viewSpace.y; + viewZ -= pushConstants.distanceThickness * min(-viewZ, 500.0); + vec4 clipSpace = globalData.pMatrix * vec4(0.0, 0.0, viewZ, 1.0); + return vec2(depth, clipSpace.z / clipSpace.w); + } + + return imageLoad(levelIn, texel).rg; + +} + +vec2 Combine(vec2 a, vec2 b) { + + return vec2(min(a.x, b.x), max(a.y, b.y)); + +} + +void Store(int level, ivec2 texel, vec2 value) { + + if (level >= pushConstants.levelCount) + return; + + if (level == 0) imageStore(levelOut0, texel, vec4(value, 0.0, 0.0)); + else if (level == 1) imageStore(levelOut1, texel, vec4(value, 0.0, 0.0)); + else if (level == 2) imageStore(levelOut2, texel, vec4(value, 0.0, 0.0)); + else if (level == 3) imageStore(levelOut3, texel, vec4(value, 0.0, 0.0)); + else if (level == 4) imageStore(levelOut4, texel, vec4(value, 0.0, 0.0)); + else if (level == 5) imageStore(levelOut5, texel, vec4(value, 0.0, 0.0)); + +} + +void main() { + + ivec2 pixel = ivec2(gl_LocalInvocationID); + ivec2 workGroupOffset = ivec2(gl_WorkGroupID) * ivec2(gl_WorkGroupSize) * 2; + + // When reading the depth texture, the input is level 0 + ivec2 coord = workGroupOffset + 2 * pixel; + vec2 depth00 = FetchTexel(coord); + vec2 depth10 = FetchTexel(coord + ivec2(1, 0)); + vec2 depth01 = FetchTexel(coord + ivec2(0, 1)); + vec2 depth11 = FetchTexel(coord + ivec2(1, 1)); + + int level = 0; + if (pushConstants.fromDepth > 0) { + Store(0, coord, depth00); + Store(0, coord + ivec2(1, 0), depth10); + Store(0, coord + ivec2(0, 1), depth01); + Store(0, coord + ivec2(1, 1), depth11); + level = 1; + } + + vec2 value = Combine(Combine(depth00, depth10), Combine(depth01, depth11)); + Store(level, ivec2(gl_WorkGroupID.xy) * 16 + pixel, value); + sharedMinMax[pixel.y][pixel.x] = value; + + int size = 16; + for (int i = 1; i < 5; i++) { + barrier(); + + size /= 2; + if (all(lessThan(pixel, ivec2(size)))) { + ivec2 texel = 2 * pixel; + value = Combine(Combine(sharedMinMax[texel.y][texel.x], sharedMinMax[texel.y][texel.x + 1]), + Combine(sharedMinMax[texel.y + 1][texel.x], sharedMinMax[texel.y + 1][texel.x + 1])); + Store(level + i, ivec2(gl_WorkGroupID.xy) * size + pixel, value); + } + + barrier(); + + if (all(lessThan(pixel, ivec2(size)))) + sharedMinMax[pixel.y][pixel.x] = value; + } + +} diff --git a/data/shader/gbuffer/patchGBuffer.csh b/data/shader/gbuffer/patchGBuffer.csh index 86d7174d5..62a0501cd 100644 --- a/data/shader/gbuffer/patchGBuffer.csh +++ b/data/shader/gbuffer/patchGBuffer.csh @@ -3,7 +3,7 @@ layout (local_size_x = 8, local_size_y = 8) in; layout (set = 3, binding = 0, rg16f) uniform image2D normalImage; -layout (set = 3, binding = 1, rgba16f) uniform image2D roughnessMetalnessAoImage; +layout (set = 3, binding = 1, rgba8) uniform image2D roughnessMetalnessAoImage; layout (set = 3, binding = 2) uniform sampler2D geometryNormalTexture; layout (set = 3, binding = 3) uniform usampler2D materialIdxTexture; diff --git a/data/shader/globals.hsh b/data/shader/globals.hsh index 7fab7c58c..5edd8506e 100644 --- a/data/shader/globals.hsh +++ b/data/shader/globals.hsh @@ -1,12 +1,7 @@ -#ifdef AE_BINDLESS +// Has to match the counts in graphics/Common.h #define TEXTURE_COUNT 16384 #define CUBEMAP_COUNT 1024 #define TEXTURE_ARRAY_COUNT 128 -#else -#define TEXTURE_COUNT 1 -#define CUBEMAP_COUNT 1 -#define TEXTURE_ARRAY_COUNT 1 -#endif layout(set = 1, binding = 31, std140) uniform GlobalBuffer { vec4 frustumPlanes[6]; @@ -36,6 +31,13 @@ layout(set = 1, binding = 31, std140) uniform GlobalBuffer { float mipLodBias; float cameraNearPlane; float cameraFarPlane; + // Exposure the lighting buffers are stored with, keeps strong physical lights within the limits of the GI + float preExposure; + float lastPreExposure; + // A loaded sky cubemap doesn't carry the pre-exposure, a generated one does + float skyCubemapExposure; + // Colors meshes by their level of detail + uint debugMeshLods; } globalData; layout(set = 0, binding = 3) uniform texture2D bindlessTextures[TEXTURE_COUNT]; diff --git a/data/shader/impostor/depthOffset.hsh b/data/shader/impostor/depthOffset.hsh new file mode 100644 index 000000000..6db00c781 --- /dev/null +++ b/data/shader/impostor/depthOffset.hsh @@ -0,0 +1,7 @@ +// The bake stores the distance in front of the billboard plane plus one, texels without geometry stay zero. Filtered +// texels at the silhouette mix both, divided by their coverage (the alpha of the base color) they are restored +float ImpostorDepthOffset(float depth, float alpha) { + + return depth / max(alpha, 1e-3) - 1.0; + +} diff --git a/data/shader/impostor/generate.fsh b/data/shader/impostor/generate.fsh index ffe7d8754..d7ebf258f 100644 --- a/data/shader/impostor/generate.fsh +++ b/data/shader/impostor/generate.fsh @@ -1,4 +1,5 @@ #include <../common/random.hsh> +#include <../common/opacity.hsh> layout (location = 0) out vec4 baseColorFS; layout (location = 1) out vec3 normalFS; @@ -112,7 +113,7 @@ void main() { #ifdef OPACITY_MAP float opacity = texture(opacityMap, texCoords).r; - if (opacity < 0.2) + if (opacity < opacityCutoff) discard; #endif @@ -123,21 +124,18 @@ void main() { baseColorFS *= PushConstants.baseColor; - vec3 geometryNormalFS = normalize(normalVS); + vec3 geometryNormal = normalize(normalVS); + // We want the normal always to face the camera for two sided materials + vec3 facingGeometryNormal = geometryNormal * (PushConstants.twoSided > 0 && dot(normalVS, positionVS) > 0.0 ? -1.0 : 1.0); #ifdef NORMAL_MAP vec3 normalColor = texture(normalMap, texCoords).rgb; - normalFS = mix(geometryNormalFS, normalize(TBN * (2.0 * normalColor - 1.0)), PushConstants.normalScale); - // We want the normal always to face the camera for two sided materials - geometryNormalFS *= PushConstants.twoSided > 0 ? dot(normalVS, positionVS) > 0.0 ? -1.0 : 1.0 : 1.0; - normalFS = 0.5 * normalFS + 0.5; + vec3 normal = normalize(mix(geometryNormal, normalize(TBN * (2.0 * normalColor - 1.0)), PushConstants.normalScale)); + normal *= dot(facingGeometryNormal, normal) < 0.0 ? -1.0 : 1.0; + normalFS = 0.5 * normal + 0.5; #else - // We want the normal always to face the camera for two sided materials - geometryNormalFS *= PushConstants.twoSided > 0 ? dot(normalVS, positionVS) > 0.0 ? -1.0 : 1.0 : 1.0; + normalFS = 0.5 * facingGeometryNormal + 0.5; #endif - - geometryNormalFS = 0.5 * geometryNormalFS + 0.5; - normalFS = geometryNormalFS; float roughnessFactor = PushConstants.roughness; float metalnessFactor = PushConstants.metalness; diff --git a/data/shader/impostor/impostor.fsh b/data/shader/impostor/impostor.fsh index b399840b1..fcec389e1 100644 --- a/data/shader/impostor/impostor.fsh +++ b/data/shader/impostor/impostor.fsh @@ -1,5 +1,6 @@ #include <../globals.hsh> #include <../common/normalencode.hsh> +#include layout (location = 0) out vec4 baseColorFS; layout (location = 1) out vec2 normalFS; @@ -28,7 +29,7 @@ layout(location=4) flat in int indexVS; #ifdef PIXEL_DEPTH_OFFSET layout(location=10) in vec3 modelPositionVS; -layout(location=11) flat in vec3 instanceScale; +layout(location=11) in float depthScale; #endif layout(location=12) flat in mat3 rotationMatrix; @@ -37,10 +38,6 @@ layout(set = 3, binding = 1) uniform sampler2DArray roughnessMetalnessAoMap; layout(set = 3, binding = 2) uniform sampler2DArray normalMap; layout(set = 3, binding = 3) uniform sampler2DArray depthMap; -layout(std430, set = 1, binding = 2) buffer Matrices { - mat4 matrices[]; -}; - layout(set = 3, binding = 5, std140) uniform UniformBuffer{ vec4 center; @@ -127,13 +124,14 @@ void main() { float depth1 = texture(depthMap, vec3(texCoordVS, float(index1VS)), uniforms.mipBias + globalData.mipLodBias).r; float depth2 = texture(depthMap, vec3(texCoordVS, float(index2VS)), uniforms.mipBias + globalData.mipLodBias).r; - float depthOffset = weight0VS * depth0 + - weight1VS * depth1 + - weight2VS * depth2; + // Decoded together, views without the surface at this texel would push the depth back + float depthOffset = ImpostorDepthOffset(weight0VS * depth0 + weight1VS * depth1 + weight2VS * depth2, baseColor.a); #else - float depthOffset = texture(depthMap, vec3(texCoordVS, float(indexVS)), uniforms.mipBias + globalData.mipLodBias).r; + float depthOffset = ImpostorDepthOffset(texture(depthMap, vec3(texCoordVS, float(indexVS)), uniforms.mipBias + globalData.mipLodBias).r, + baseColor.a); #endif - vec3 modelPosition = modelPositionVS + depthOffset * -globalData.cameraDirection.xyz * instanceScale; + vec3 toCamera = normalize(globalData.cameraLocation.xyz - modelPositionVS); + vec3 modelPosition = modelPositionVS + depthOffset * toCamera * depthScale; vec4 modelPositionFS = globalData.pMatrix * globalData.vMatrix * vec4(modelPosition.xyz, 1.0); float modelDepth = modelPositionFS.z / modelPositionFS.w; gl_FragDepth = modelDepth; diff --git a/data/shader/impostor/impostor.vsh b/data/shader/impostor/impostor.vsh index 6a8c1dbb9..da3971cbf 100644 --- a/data/shader/impostor/impostor.vsh +++ b/data/shader/impostor/impostor.vsh @@ -10,9 +10,7 @@ struct ViewPlane { vec4 up; }; -layout(std430, set = 1, binding = 3) readonly buffer Matrices { - mat3x4 matrices[]; -}; +#include <../culling/instances.hsh> layout (std430, set = 3, binding = 4) readonly buffer ViewPlanes { ViewPlane viewPlanes[]; @@ -37,7 +35,7 @@ layout(location=4) flat out int indexVS; #ifdef PIXEL_DEPTH_OFFSET layout(location=10) out vec3 modelPositionVS; -layout(location=11) flat out vec3 instanceScale; +layout(location=11) out float depthScale; #endif layout(location=12) flat out mat3 rotationMatrix; @@ -75,13 +73,12 @@ vec4 InterpolateTriangle(vec2 coord) { void main() { - mat4 mMatrix = mat4(transpose(matrices[gl_InstanceIndex])); + mat4 mMatrix = GetInstanceMatrix(impostorInstanceIndices[gl_InstanceIndex]); texCoordVS = 0.5 * vPosition + 0.5; - vec3 translation = vec3(mMatrix[3]); - - vec3 pos = translation + uniforms.center.xyz; - vec3 dir = normalize(vec3(inverse(mMatrix) * vec4(globalData.cameraLocation.xyz - pos, 0.0))); + mat4 inverseMatrix = inverse(mMatrix); + vec3 pos = vec3(mMatrix * vec4(uniforms.center.xyz, 1.0)); + vec3 dir = normalize(vec3(inverseMatrix * vec4(globalData.cameraLocation.xyz - pos, 0.0))); float frames = float(uniforms.views); @@ -150,11 +147,8 @@ void main() { rotationMatrix = mat3(mMatrix); #ifdef PIXEL_DEPTH_OFFSET modelPositionVS = vec3(modelPosition); - instanceScale = vec3( - length(mMatrix[0]), - length(mMatrix[1]), - length(mMatrix[2]) - ); + // The depth is baked along the view direction in model space, this is its length in world space + depthScale = 1.0 / length(mat3(inverseMatrix) * normalize(globalData.cameraLocation.xyz - modelPositionVS)); #endif gl_Position = globalData.pMatrix * vec4(positionVS, 1.0); diff --git a/data/shader/impostor/impostorShadow.fsh b/data/shader/impostor/impostorShadow.fsh index f9604bfdc..022f6eabc 100644 --- a/data/shader/impostor/impostorShadow.fsh +++ b/data/shader/impostor/impostorShadow.fsh @@ -1,4 +1,5 @@ #include <../globals.hsh> +#include layout(location = 0) in vec2 texCoordVS; #ifdef INTERPOLATION @@ -14,7 +15,7 @@ layout(location=1) flat in int indexVS; #endif #ifdef PIXEL_DEPTH_OFFSET layout(location=7) in vec3 modelPositionVS; -layout(location=8) flat in vec3 instanceScale; +layout(location=8) in float depthScale; #endif layout(set = 3, binding = 0) uniform sampler2DArray baseColorMap; @@ -22,10 +23,6 @@ layout(set = 3, binding = 0) uniform sampler2DArray baseColorMap; layout(set = 3, binding = 1) uniform sampler2DArray depthMap; #endif -layout(std430, set = 1, binding = 3) buffer Matrices { - mat4 matrices[]; -}; - layout(set = 3, binding = 3, std140) uniform UniformBuffer{ vec4 center; @@ -40,8 +37,6 @@ layout(push_constant) uniform constants { mat4 lightSpaceMatrix; vec4 lightLocation; - vec4 lightUp; - vec4 lightRight; } pushConstants; void main() { @@ -69,13 +64,14 @@ void main() { float depth1 = texture(depthMap, vec3(texCoordVS, float(index1VS)), uniforms.mipBias).r; float depth2 = texture(depthMap, vec3(texCoordVS, float(index2VS)), uniforms.mipBias).r; - float depthOffset = weight0VS * depth0 + - weight1VS * depth1 + - weight2VS * depth2; + // Decoded together, views without the surface at this texel would push the depth back + float depthOffset = ImpostorDepthOffset(weight0VS * depth0 + weight1VS * depth1 + weight2VS * depth2, alpha); #else - float depthOffset = texture(depthMap, vec3(texCoordVS, float(indexVS)), uniforms.mipBias).r; + float depthOffset = ImpostorDepthOffset(texture(depthMap, vec3(texCoordVS, float(indexVS)), uniforms.mipBias).r, alpha); #endif - vec3 modelPosition = modelPositionVS + depthOffset * normalize(pushConstants.lightLocation.xyz) * instanceScale; + // Towards a point light or along the directional light (its location lies far away against the direction) + vec3 toLight = normalize(pushConstants.lightLocation.xyz - modelPositionVS); + vec3 modelPosition = modelPositionVS + depthOffset * toLight * depthScale; vec4 modelPositionFS = pushConstants.lightSpaceMatrix * vec4(modelPosition.xyz, 1.0); float modelDepth = modelPositionFS.z / modelPositionFS.w; gl_FragDepth = modelDepth; diff --git a/data/shader/impostor/impostorShadow.vsh b/data/shader/impostor/impostorShadow.vsh index 107edab4d..71ef62880 100644 --- a/data/shader/impostor/impostorShadow.vsh +++ b/data/shader/impostor/impostorShadow.vsh @@ -18,7 +18,7 @@ layout(location=1) flat out int indexVS; #endif #ifdef PIXEL_DEPTH_OFFSET layout(location=7) out vec3 modelPositionVS; -layout(location=8) flat out vec3 instanceScale; +layout(location=8) out float depthScale; #endif struct ViewPlane { @@ -26,9 +26,7 @@ struct ViewPlane { vec4 up; }; -layout(std430, set = 1, binding = 3) readonly buffer Matrices { - mat3x4 matrices[]; -}; +#include <../culling/instances.hsh> layout (std430, set = 3, binding = 2) readonly buffer ViewPlanes { ViewPlane viewPlanes[]; @@ -48,8 +46,6 @@ layout(push_constant) uniform constants { mat4 lightSpaceMatrix; vec4 lightLocation; - vec4 lightUp; - vec4 lightRight; } pushConstants; vec4 InterpolateTriangle(vec2 coord) { @@ -70,14 +66,13 @@ vec4 InterpolateTriangle(vec2 coord) { void main() { - mat4 mMatrix = mat4(transpose(matrices[gl_InstanceIndex])); + mat4 mMatrix = GetInstanceMatrix(impostorInstanceIndices[gl_InstanceIndex]); texCoordVS = 0.5 * vPosition + 0.5; - vec3 translation = vec3(mMatrix[3]); - - vec3 pos = translation + uniforms.center.xyz; - vec3 dir = normalize(vec3(inverse(mMatrix) * vec4(pushConstants.lightLocation.xyz - pos, 0.0))); + mat4 inverseMatrix = inverse(mMatrix); + vec3 pos = vec3(mMatrix * vec4(uniforms.center.xyz, 1.0)); + vec3 dir = normalize(vec3(inverseMatrix * vec4(pushConstants.lightLocation.xyz - pos, 0.0))); float frames = float(uniforms.views); vec2 octahedron = UnitVectorToHemiOctahedron(normalize(dir)); @@ -135,12 +130,9 @@ void main() { + normalize(right.xyz) * position.x) + uniforms.center.xyz, 1.0); #ifdef PIXEL_DEPTH_OFFSET - instanceScale = vec3( - length(mMatrix[0]), - length(mMatrix[1]), - length(mMatrix[2]) - ); modelPositionVS = vec3(modelPosition); + // The depth is baked along the view direction in model space, this is its length in world space + depthScale = 1.0 / length(mat3(inverseMatrix) * normalize(pushConstants.lightLocation.xyz - modelPositionVS)); #endif gl_Position = pushConstants.lightSpaceMatrix * modelPosition; diff --git a/data/shader/materialGraph/common.hsh b/data/shader/materialGraph/common.hsh new file mode 100644 index 000000000..a88084125 --- /dev/null +++ b/data/shader/materialGraph/common.hsh @@ -0,0 +1,617 @@ +#extension GL_EXT_nonuniform_qualifier : require + +// Interface between the geometry and shadow shaders and the code generated from material graphs +// Only shaders generated from a graph include this file, see materialgraph/Compiler + +#include <../globals.hsh> +#include <../common/opacity.hsh> + +#if (defined(MATERIAL_GRAPH_WRITES_NORMAL) || defined(MATERIAL_GRAPH_USES_TANGENTS)) && defined(TANGENTS) && defined(TEX_COORDS) && !defined(NORMAL_MAP) +#define NORMAL_MAP +#endif + +// Parameter values and bindless texture indices of all graph materials, indexed by the offset of the material +// Ray tracing passes use binding 9 of set 3 for other resources +#ifdef MATERIAL_GRAPH_STAGE_HIT +layout(std430, set = 3, binding = 24) readonly buffer MaterialGraphParameters { +#else +layout(std430, set = 3, binding = 9) readonly buffer MaterialGraphParameters { +#endif + uint materialGraphParameters[]; +}; + +struct MaterialVertexInput { + vec3 position; + vec3 normal; + vec3 tangent; + vec3 worldPosition; + vec3 worldNormal; + vec3 instancePosition; + vec3 viewDirection; + vec2 texCoord; + // Second texture coordinate set, zero for meshes without one + vec2 texCoord1; + vec4 color; + float time; + uint parameterOffset; + mat4 modelMatrix; +}; + +struct MaterialSurfaceInput { + vec3 position; + vec3 normal; + vec3 worldPosition; + vec3 worldNormal; + vec3 viewPosition; + vec3 viewNormal; + vec3 instancePosition; + vec3 viewDirection; + // Tangent to view space + mat3 tangentFrame; + vec2 texCoord; + // Only the vertex stage has the second set, evaluations and ray hits read zero + vec2 texCoord1; + vec2 screenCoord; + vec4 color; + float time; + float frontFacing; + uint parameterOffset; +#ifdef MATERIAL_GRAPH_STAGE_EVALUATE + // Nodes of the vertex stage are calculated per fragment in an evaluation + vec3 tangent; + mat4 modelMatrix; +#endif +}; + +struct MaterialSurfaceOutput { + vec3 baseColor; + // In tangent space + vec3 normal; + vec3 emissive; + float roughness; + float metalness; + float ao; + float opacity; +}; + +MaterialSurfaceOutput CreateMaterialSurfaceOutput() { + + MaterialSurfaceOutput surface; + + surface.baseColor = vec3(1.0); + surface.normal = vec3(0.0, 0.0, 1.0); + surface.emissive = vec3(0.0); + surface.roughness = 1.0; + surface.metalness = 0.0; + surface.ao = 1.0; + surface.opacity = 1.0; + + return surface; + +} + +// The object position is the one of the mesh file, on skinned meshes it stays the same while they are animated +MaterialVertexInput CreateMaterialVertexInput(vec3 objectPosition, vec3 position, vec3 normal, vec3 tangent, vec2 texCoord, vec2 texCoord1, + vec4 color, mat4 modelMatrix, float time, uint parameterOffset) { + + MaterialVertexInput vertexIn; + + vertexIn.position = objectPosition; + vertexIn.normal = normal; + vertexIn.tangent = tangent; + vertexIn.worldPosition = vec3(modelMatrix * vec4(position, 1.0)); + vertexIn.worldNormal = normalize(mat3(modelMatrix) * normal); + vertexIn.instancePosition = vec3(modelMatrix[3]); + vertexIn.viewDirection = normalize(globalData.cameraLocation.xyz - vertexIn.worldPosition); + vertexIn.texCoord = texCoord; + vertexIn.texCoord1 = texCoord1; + vertexIn.color = color; + vertexIn.time = time; + vertexIn.parameterOffset = parameterOffset; + vertexIn.modelMatrix = modelMatrix; + + return vertexIn; + +} + +// The same vertex at another position, e.g. to find the normal of the displaced surface +MaterialVertexInput MoveMaterialVertexInput(MaterialVertexInput vertexIn, vec3 offset) { + + vertexIn.position += offset; + vertexIn.worldPosition += mat3(vertexIn.modelMatrix) * offset; + vertexIn.viewDirection = normalize(globalData.cameraLocation.xyz - vertexIn.worldPosition); + + return vertexIn; + +} + +MaterialSurfaceInput CreateMaterialSurfaceInput(vec3 position, vec3 normal, vec3 worldPosition, vec3 worldNormal, + vec3 instancePosition, mat3 tangentFrame, vec2 texCoord, vec2 screenCoord, vec4 color, float frontFacing, + uint parameterOffset) { + + MaterialSurfaceInput surfaceIn; + + surfaceIn.position = position; + surfaceIn.normal = normal; + surfaceIn.worldPosition = worldPosition; + surfaceIn.worldNormal = worldNormal; + surfaceIn.viewPosition = vec3(globalData.vMatrix * vec4(worldPosition, 1.0)); + surfaceIn.viewNormal = mat3(globalData.vMatrix) * worldNormal; + surfaceIn.instancePosition = instancePosition; + surfaceIn.viewDirection = normalize(globalData.cameraLocation.xyz - worldPosition); + surfaceIn.tangentFrame = tangentFrame; + surfaceIn.texCoord = texCoord; + surfaceIn.texCoord1 = vec2(0.0); + surfaceIn.screenCoord = screenCoord; + surfaceIn.color = color; + surfaceIn.time = globalData.time; + surfaceIn.frontFacing = frontFacing; + surfaceIn.parameterOffset = parameterOffset; + + return surfaceIn; + +} + +float MaterialGraphReadFloat(uint offset) { + + return uintBitsToFloat(materialGraphParameters[offset]); + +} + +vec2 MaterialGraphReadVec2(uint offset) { + + return vec2(MaterialGraphReadFloat(offset), MaterialGraphReadFloat(offset + 1u)); + +} + +vec3 MaterialGraphReadVec3(uint offset) { + + return vec3(MaterialGraphReadFloat(offset), MaterialGraphReadFloat(offset + 1u), MaterialGraphReadFloat(offset + 2u)); + +} + +vec4 MaterialGraphReadVec4(uint offset) { + + return vec4(MaterialGraphReadFloat(offset), MaterialGraphReadFloat(offset + 1u), MaterialGraphReadFloat(offset + 2u), MaterialGraphReadFloat(offset + 3u)); + +} + +#ifdef MATERIAL_GRAPH_STAGE_HIT +// Hits have no derivatives, the level comes from the ray tracing pass +float materialGraphHitTextureLevel = 0.0; +#endif + +// The vertex stage has no derivatives, it always samples the most detailed level +vec4 MaterialGraphSampleTexture(uint textureIdx, vec2 texCoord) { + +#if defined(MATERIAL_GRAPH_STAGE_HIT) + return textureLod(sampler2D(bindlessTextures[nonuniformEXT(textureIdx)], bindlessSampler), texCoord, materialGraphHitTextureLevel); +#elif defined(MATERIAL_GRAPH_STAGE_SURFACE) + return texture(sampler2D(bindlessTextures[nonuniformEXT(textureIdx)], bindlessSampler), texCoord, globalData.mipLodBias); +#else + return textureLod(sampler2D(bindlessTextures[nonuniformEXT(textureIdx)], bindlessSampler), texCoord, 0.0); +#endif + +} + +vec4 MaterialGraphSampleTextureLod(uint textureIdx, vec2 texCoord, float lod) { + + return textureLod(sampler2D(bindlessTextures[nonuniformEXT(textureIdx)], bindlessSampler), texCoord, lod); + +} + +vec3 MaterialGraphSampleNormal(uint textureIdx, vec2 texCoord, float strength) { + + vec3 normal = 2.0 * MaterialGraphSampleTexture(textureIdx, texCoord).rgb - 1.0; + normal.xy *= strength; + return normalize(normal); + +} + +vec4 MaterialGraphSampleTriplanar(uint textureIdx, vec3 position, vec3 normal, float scale, float sharpness) { + + vec3 weights = pow(abs(normal), vec3(sharpness)); + weights /= max(weights.x + weights.y + weights.z, 0.0001); + + return MaterialGraphSampleTexture(textureIdx, position.zy * scale) * weights.x + + MaterialGraphSampleTexture(textureIdx, position.xz * scale) * weights.y + + MaterialGraphSampleTexture(textureIdx, position.xy * scale) * weights.z; + +} + +vec3 MaterialGraphSampleTriplanarNormal(uint textureIdx, vec3 position, vec3 normal, float scale, float sharpness, float strength) { + + vec3 weights = pow(abs(normal), vec3(sharpness)); + weights /= max(weights.x + weights.y + weights.z, 0.0001); + + vec3 normalX = 2.0 * MaterialGraphSampleTexture(textureIdx, position.zy * scale).rgb - 1.0; + vec3 normalY = 2.0 * MaterialGraphSampleTexture(textureIdx, position.xz * scale).rgb - 1.0; + vec3 normalZ = 2.0 * MaterialGraphSampleTexture(textureIdx, position.xy * scale).rgb - 1.0; + + normalX = vec3(normalX.xy * strength + normal.zy, abs(normalX.z) * normal.x); + normalY = vec3(normalY.xy * strength + normal.xz, abs(normalY.z) * normal.y); + normalZ = vec3(normalZ.xy * strength + normal.xy, abs(normalZ.z) * normal.z); + + return normalize(normalX.zyx * weights.x + normalY.xzy * weights.y + normalZ * weights.z); + +} + +vec2 MaterialGraphTextureSize(uint textureIdx) { + + return vec2(textureSize(sampler2D(bindlessTextures[nonuniformEXT(textureIdx)], bindlessSampler), 0)); + +} + +vec3 MaterialGraphMod289(vec3 x) { + + return x - floor(x * (1.0 / 289.0)) * 289.0; + +} + +vec4 MaterialGraphMod289(vec4 x) { + + return x - floor(x * (1.0 / 289.0)) * 289.0; + +} + +vec4 MaterialGraphPermute(vec4 x) { + + return MaterialGraphMod289(((x * 34.0) + 10.0) * x); + +} + +// Simplex noise in the range of -1 to 1 +float MaterialGraphSimplex(vec3 v) { + + const vec2 C = vec2(1.0 / 6.0, 1.0 / 3.0); + const vec4 D = vec4(0.0, 0.5, 1.0, 2.0); + + vec3 i = floor(v + dot(v, C.yyy)); + vec3 x0 = v - i + dot(i, C.xxx); + + vec3 g = step(x0.yzx, x0.xyz); + vec3 l = 1.0 - g; + vec3 i1 = min(g.xyz, l.zxy); + vec3 i2 = max(g.xyz, l.zxy); + + vec3 x1 = x0 - i1 + C.xxx; + vec3 x2 = x0 - i2 + C.yyy; + vec3 x3 = x0 - D.yyy; + + i = MaterialGraphMod289(i); + vec4 p = MaterialGraphPermute(MaterialGraphPermute(MaterialGraphPermute( + i.z + vec4(0.0, i1.z, i2.z, 1.0)) + + i.y + vec4(0.0, i1.y, i2.y, 1.0)) + + i.x + vec4(0.0, i1.x, i2.x, 1.0)); + + float n_ = 0.142857142857; + vec3 ns = n_ * D.wyz - D.xzx; + + vec4 j = p - 49.0 * floor(p * ns.z * ns.z); + + vec4 x_ = floor(j * ns.z); + vec4 y_ = floor(j - 7.0 * x_); + + vec4 x = x_ * ns.x + ns.yyyy; + vec4 y = y_ * ns.x + ns.yyyy; + vec4 h = 1.0 - abs(x) - abs(y); + + vec4 b0 = vec4(x.xy, y.xy); + vec4 b1 = vec4(x.zw, y.zw); + + vec4 s0 = floor(b0) * 2.0 + 1.0; + vec4 s1 = floor(b1) * 2.0 + 1.0; + vec4 sh = -step(h, vec4(0.0)); + + vec4 a0 = b0.xzyw + s0.xzyw * sh.xxyy; + vec4 a1 = b1.xzyw + s1.xzyw * sh.zzww; + + vec3 p0 = vec3(a0.xy, h.x); + vec3 p1 = vec3(a0.zw, h.y); + vec3 p2 = vec3(a1.xy, h.z); + vec3 p3 = vec3(a1.zw, h.w); + + vec4 norm = 1.79284291400159 - 0.85373472095314 * vec4(dot(p0, p0), dot(p1, p1), dot(p2, p2), dot(p3, p3)); + p0 *= norm.x; + p1 *= norm.y; + p2 *= norm.z; + p3 *= norm.w; + + vec4 m = max(0.5 - vec4(dot(x0, x0), dot(x1, x1), dot(x2, x2), dot(x3, x3)), 0.0); + m = m * m; + return 105.0 * dot(m * m, vec4(dot(p0, x0), dot(p1, x1), dot(p2, x2), dot(p3, x3))); + +} + +float MaterialGraphFractalNoise(vec3 position, float octaves, float lacunarity, float gain) { + + float value = 0.0; + float amplitude = 1.0; + float amplitudeSum = 0.0; + + int count = clamp(int(octaves), 1, 8); + for (int i = 0; i < count; i++) { + value += amplitude * MaterialGraphSimplex(position); + amplitudeSum += amplitude; + amplitude *= gain; + position = position * lacunarity + vec3(17.3, -9.1, 4.7); + } + + return value / amplitudeSum; + +} + +// Absolute noise folded into sharp ridges, in the range of 0 to 1 +float MaterialGraphRidgedNoise(vec3 position, float octaves, float lacunarity, float gain) { + + float value = 0.0; + float amplitude = 1.0; + float amplitudeSum = 0.0; + + int count = clamp(int(octaves), 1, 8); + for (int i = 0; i < count; i++) { + float ridge = 1.0 - abs(MaterialGraphSimplex(position)); + value += amplitude * ridge * ridge; + amplitudeSum += amplitude; + amplitude *= gain; + position = position * lacunarity + vec3(17.3, -9.1, 4.7); + } + + return value / amplitudeSum; + +} + +vec3 MaterialGraphHash3(vec3 p) { + + p = vec3(dot(p, vec3(127.1, 311.7, 74.7)), dot(p, vec3(269.5, 183.3, 246.1)), dot(p, vec3(113.5, 271.9, 124.6))); + return fract(sin(p) * 43758.5453123); + +} + +// Distance to the closest feature point in x, to the second closest in y and a random value of the cell in z +vec3 MaterialGraphVoronoi(vec3 position, float jitter) { + + vec3 cell = floor(position); + vec3 local = fract(position); + + float first = 8.0; + float second = 8.0; + float id = 0.0; + + for (int z = -1; z <= 1; z++) { + for (int y = -1; y <= 1; y++) { + for (int x = -1; x <= 1; x++) { + vec3 offset = vec3(float(x), float(y), float(z)); + vec3 random = MaterialGraphHash3(cell + offset); + vec3 delta = offset + random * jitter - local; + float dist = dot(delta, delta); + if (dist < first) { + second = first; + first = dist; + id = random.x; + } + else if (dist < second) { + second = dist; + } + } + } + } + + return vec3(sqrt(first), sqrt(second), id); + +} + +float MaterialGraphChecker(vec3 position) { + + vec3 cell = floor(position); + return mod(cell.x + cell.y + cell.z, 2.0); + +} + +vec3 MaterialGraphHueShift(vec3 color, float shift) { + + const vec3 axis = vec3(0.57735); + float cosAngle = cos(shift); + return color * cosAngle + cross(axis, color) * sin(shift) + axis * dot(axis, color) * (1.0 - cosAngle); + +} + +vec3 MaterialGraphRotateAxis(vec3 position, vec3 axis, float angle) { + + axis = normalize(axis); + float sinAngle = sin(angle); + float cosAngle = cos(angle); + return position * cosAngle + cross(axis, position) * sinAngle + axis * dot(axis, position) * (1.0 - cosAngle); + +} + +vec2 MaterialGraphRotateCoord(vec2 coord, vec2 center, float angle) { + + float sinAngle = sin(angle); + float cosAngle = cos(angle); + coord -= center; + return vec2(coord.x * cosAngle - coord.y * sinAngle, coord.x * sinAngle + coord.y * cosAngle) + center; + +} + +vec2 MaterialGraphPolar(vec2 coord, vec2 center, float radialScale, float angleScale) { + + vec2 delta = coord - center; + return vec2(length(delta) * radialScale, (atan(delta.y, delta.x) / 6.28318530718 + 0.5) * angleScale); + +} + +vec2 MaterialGraphFlipbook(vec2 coord, float columns, float rows, float frame) { + + float index = mod(floor(frame), columns * rows); + return (fract(coord) + vec2(mod(index, columns), floor(index / columns))) / vec2(columns, rows); + +} + +vec2 MaterialGraphTwirl(vec2 coord, vec2 center, float strength) { + + return MaterialGraphRotateCoord(coord, center, length(coord - center) * strength); + +} + +vec2 MaterialGraphDistort(vec2 coord, float scale, float strength, float seed) { + + vec3 position = vec3(coord * scale, seed); + return coord + vec2(MaterialGraphSimplex(position), MaterialGraphSimplex(position + vec3(31.7, 11.3, 5.9))) * strength; + +} + +float MaterialGraphRemap(float value, float fromMin, float fromMax, float toMin, float toMax) { + + return toMin + (value - fromMin) / (fromMax - fromMin) * (toMax - toMin); + +} + +vec3 MaterialGraphRamp(float position, vec3 color0, vec3 color1, vec3 color2, float center) { + + return position < center ? mix(color0, color1, clamp(position / max(center, 0.0001), 0.0, 1.0)) : + mix(color1, color2, clamp((position - center) / max(1.0 - center, 0.0001), 0.0, 1.0)); + +} + +vec3 MaterialGraphBlendNormals(vec3 a, vec3 b) { + + return normalize(vec3(a.xy + b.xy, a.z * b.z)); + +} + +vec3 MaterialGraphNormalize(vec3 value) { + + float len = length(value); + return len > 0.0 ? value / len : value; + +} + +#if defined(MATERIAL_GRAPH_STAGE_SURFACE) && !defined(MATERIAL_GRAPH_STAGE_HIT) +// Tangent space normal of a height, which works for procedural values without a tangent frame of the mesh +vec3 MaterialGraphNormalFromHeight(float height, float strength, vec3 viewPosition, vec3 viewNormal, mat3 tangentFrame) { + + vec3 dpdx = dFdx(viewPosition); + vec3 dpdy = dFdy(viewPosition); + float dhdx = dFdx(height) * strength; + float dhdy = dFdy(height) * strength; + + vec3 normal = normalize(viewNormal); + vec3 r1 = cross(dpdy, normal); + vec3 r2 = cross(normal, dpdx); + float determinant = dot(dpdx, r1); + + // Degenerate triangles, e.g. at the poles of spheres, have no direction + if (determinant == 0.0) + return vec3(0.0, 0.0, 1.0); + + vec3 gradient = sign(determinant) * (dhdx * r1 + dhdy * r2); + vec3 perturbed = normalize(abs(determinant) * normal - gradient); + + return normalize(transpose(tangentFrame) * perturbed); + +} + +// Each corner of a tile has its own offset, the mip level stays the one of the continuous coordinates +vec4 MaterialGraphSampleWithoutTiling(uint textureIdx, vec2 coord, float blend) { + + vec2 tile = floor(coord); + vec2 weights = smoothstep(vec2(0.5 - 0.5 * blend), vec2(0.5 + 0.5 * blend), fract(coord)); + + vec2 ddx = dFdx(coord); + vec2 ddy = dFdy(coord); + + vec4 values[4]; + for (int y = 0; y < 2; y++) { + for (int x = 0; x < 2; x++) { + vec2 offset = MaterialGraphHash3(vec3(tile + vec2(float(x), float(y)), 3.0)).xy; + values[y * 2 + x] = textureGrad(sampler2D(bindlessTextures[nonuniformEXT(textureIdx)], bindlessSampler), coord + offset, ddx, ddy); + } + } + + return mix(mix(values[0], values[1], weights.x), mix(values[2], values[3], weights.x), weights.y); + +} + +vec2 MaterialGraphParallax(uint textureIdx, vec2 coord, vec3 viewDirection, float scale, float steps) { + + vec2 ddx = dFdx(coord); + vec2 ddy = dFdy(coord); + + int count = clamp(int(steps), 1, 64); + float layerDepth = 1.0 / float(count); + vec2 delta = viewDirection.xy / max(viewDirection.z, 0.05) * scale * layerDepth; + + vec2 current = coord; + float depth = 0.0; + float height = 1.0 - textureGrad(sampler2D(bindlessTextures[nonuniformEXT(textureIdx)], bindlessSampler), current, ddx, ddy).r; + float previousHeight = height; + + for (int i = 0; i < count && depth < height; i++) { + previousHeight = height; + current -= delta; + depth += layerDepth; + height = 1.0 - textureGrad(sampler2D(bindlessTextures[nonuniformEXT(textureIdx)], bindlessSampler), current, ddx, ddy).r; + } + + float after = height - depth; + float before = previousHeight - depth + layerDepth; + return mix(current, current + delta, clamp(after / min(after - before, -0.0001), 0.0, 1.0)); + +} + +// Tangent frame from the derivatives, for meshes without tangents +mat3 MaterialGraphCotangentFrame(vec3 normal, vec3 viewPosition, vec2 texCoord) { + + vec3 dp1 = dFdx(viewPosition); + vec3 dp2 = dFdy(viewPosition); + vec2 duv1 = dFdx(texCoord); + vec2 duv2 = dFdy(texCoord); + + vec3 dp2perp = cross(dp2, normal); + vec3 dp1perp = cross(normal, dp1); + vec3 tangent = dp2perp * duv1.x + dp1perp * duv2.x; + vec3 bitangent = dp2perp * duv1.y + dp1perp * duv2.y; + + float scale = max(dot(tangent, tangent), dot(bitangent, bitangent)); + if (scale <= 0.0) { + vec3 up = abs(normal.y) < 0.99 ? vec3(0.0, 1.0, 0.0) : vec3(1.0, 0.0, 0.0); + tangent = normalize(cross(up, normal)); + return mat3(tangent, cross(normal, tangent), normal); + } + + float invScale = inversesqrt(scale); + return mat3(tangent * invScale, bitangent * invScale, normal); + +} +#elif defined(MATERIAL_GRAPH_STAGE_HIT) +// Without derivatives heights keep the surface flat +vec3 MaterialGraphNormalFromHeight(float height, float strength, vec3 viewPosition, vec3 viewNormal, mat3 tangentFrame) { + + return vec3(0.0, 0.0, 1.0); + +} + +vec4 MaterialGraphSampleWithoutTiling(uint textureIdx, vec2 coord, float blend) { + + vec2 tile = floor(coord); + vec2 weights = smoothstep(vec2(0.5 - 0.5 * blend), vec2(0.5 + 0.5 * blend), fract(coord)); + + vec4 values[4]; + for (int y = 0; y < 2; y++) { + for (int x = 0; x < 2; x++) { + vec2 offset = MaterialGraphHash3(vec3(tile + vec2(float(x), float(y)), 3.0)).xy; + values[y * 2 + x] = MaterialGraphSampleTexture(textureIdx, coord + offset); + } + } + + return mix(mix(values[0], values[1], weights.x), mix(values[2], values[3], weights.x), weights.y); + +} + +vec2 MaterialGraphParallax(uint textureIdx, vec2 coord, vec3 viewDirection, float scale, float steps) { + + return coord; + +} +#endif diff --git a/data/shader/materialGraph/evaluate.fsh b/data/shader/materialGraph/evaluate.fsh new file mode 100644 index 000000000..4f22626f1 --- /dev/null +++ b/data/shader/materialGraph/evaluate.fsh @@ -0,0 +1,102 @@ +// Included by the shaders generated for evaluating a part of a graph, see materialgraph/Compiler + +layout(location=0) in vec3 positionVS; +layout(location=1) in vec3 normalVS; +layout(location=2) in vec2 texCoordVS; +layout(location=3) in vec4 colorVS; +layout(location=4) in vec4 tangentVS; +#ifdef EVALUATE_IMPOSTOR +layout(location=5) in float depthVS; +#endif + +#ifdef EVALUATE_PREVIEW +layout(location=0) out vec4 colorFS; +#elif defined(EVALUATE_IMPOSTOR) +// The layout of the impostor maps, see impostor/generate.fsh +layout(location=0) out vec4 baseColorFS; +layout(location=1) out vec3 normalFS; +layout(location=2) out vec3 roughnessMetalnessAoFS; +layout(location=3) out float depthFS; +#else +layout(location=0) out vec4 baseColorFS; +layout(location=1) out vec4 normalFS; +layout(location=2) out vec4 roughnessMetalnessAoFS; +layout(location=3) out vec4 emissiveFS; +layout(location=4) out vec4 opacityFS; +#endif + +layout(push_constant) uniform constants { +#ifdef EVALUATE_IMPOSTOR + mat4 vMatrix; +#endif + float time; + uint invertUVs; +#ifdef EVALUATE_IMPOSTOR + float distanceToPlaneCenter; + uint twoSided; +#endif +} PushConstants; + +void main() { + + vec3 normal = normalize(normalVS); + float frontFacing = 1.0; +#ifdef EVALUATE_IMPOSTOR + frontFacing = gl_FrontFacing ? 1.0 : -1.0; + normal *= PushConstants.twoSided > 0 ? frontFacing : 1.0; +#endif + + // The same frame the geometry pass builds + mat3 tangentFrame; + if (dot(tangentVS.xyz, tangentVS.xyz) > 0.0) { + vec3 tangent = normalize(tangentVS.xyz - normal * dot(tangentVS.xyz, normal)); + float correctionFactor = tangentVS.w * (PushConstants.invertUVs > 0 ? 1.0 : -1.0); + tangentFrame = mat3(tangent, normalize(correctionFactor * cross(tangent, normal)), normal); + } + else { + tangentFrame = MaterialGraphCotangentFrame(normal, positionVS, texCoordVS); + } + + MaterialSurfaceInput surfaceIn = CreateMaterialSurfaceInput(positionVS, normal, positionVS, normal, vec3(0.0), + tangentFrame, texCoordVS, texCoordVS, colorVS, frontFacing, 0u); + + surfaceIn.time = PushConstants.time; +#ifdef EVALUATE_IMPOSTOR + vec3 cameraLocation = -transpose(mat3(PushConstants.vMatrix)) * PushConstants.vMatrix[3].xyz; + surfaceIn.viewDirection = normalize(cameraLocation - positionVS); +#else + // Maps are the same from all directions, so they are made looking straight at the surface + surfaceIn.viewDirection = normal; +#endif + surfaceIn.tangent = tangentFrame[0]; + surfaceIn.modelMatrix = mat4(1.0); + +#ifdef EVALUATE_PREVIEW + vec4 value = EvaluateMaterialPreview(surfaceIn); + colorFS = vec4(pow(clamp(value.rgb, vec3(0.0), vec3(1.0)), vec3(1.0 / 2.2)), 1.0); +#elif defined(EVALUATE_IMPOSTOR) + MaterialSurfaceOutput surface = EvaluateMaterialSurface(surfaceIn); + if (surface.opacity < opacityCutoff) + discard; + + // Impostors store the normal in the space of the mesh, like the geometry pass writes it + vec3 surfaceNormal = normalize(tangentFrame * surface.normal); + surfaceNormal = any(isnan(surfaceNormal)) ? normal : surfaceNormal * (dot(normal, surfaceNormal) < 0.0 ? -1.0 : 1.0); + + baseColorFS = vec4(surface.baseColor, 1.0); + normalFS = 0.5 * surfaceNormal + 0.5; + roughnessMetalnessAoFS = vec3(surface.roughness, surface.metalness, surface.ao); + depthFS = depthVS; +#else + MaterialSurfaceOutput surface = EvaluateMaterialSurface(surfaceIn); + + // The alpha channels mark the texels the mesh covers + baseColorFS = vec4(surface.baseColor, 1.0); + // Texels of degenerate triangles have no direction + normalFS = vec4(any(isnan(surface.normal)) ? vec3(0.0, 0.0, 1.0) : surface.normal, 1.0); + roughnessMetalnessAoFS = vec4(surface.roughness, surface.metalness, surface.ao, 1.0); + emissiveFS = vec4(surface.emissive, 1.0); + opacityFS = vec4(surface.opacity, 0.0, 0.0, 1.0); +#endif + +} diff --git a/data/shader/materialGraph/evaluate.vsh b/data/shader/materialGraph/evaluate.vsh new file mode 100644 index 000000000..4d899231a --- /dev/null +++ b/data/shader/materialGraph/evaluate.vsh @@ -0,0 +1,86 @@ +// Evaluates a part of a graph outside of the regular passes, see materialgraph/Evaluator. Either on a plane for the +// previews of nodes, on a mesh, which is laid out by its texture coordinates to fill maps of it, or on a mesh seen +// from the views of an impostor + +layout(location=0) out vec3 positionVS; +layout(location=1) out vec3 normalVS; +layout(location=2) out vec2 texCoordVS; +layout(location=3) out vec4 colorVS; +layout(location=4) out vec4 tangentVS; +#ifdef EVALUATE_IMPOSTOR +layout(location=5) out float depthVS; +#endif + +#ifdef EVALUATE_MESH +layout(location=0) in vec3 vPosition; +layout(location=1) in vec4 vNormal; +#ifdef TEX_COORDS +layout(location=2) in vec2 vTexCoord; +#endif +#ifdef TANGENTS +layout(location=3) in vec4 vTangent; +#endif +#ifdef VERTEX_COLORS +layout(location=4) in vec4 vVertexColors; +#endif +#else +layout(location=0) in vec2 vPosition; +#endif + +layout(push_constant) uniform constants { +#ifdef EVALUATE_IMPOSTOR + mat4 vMatrix; +#endif + float time; + uint invertUVs; +#ifdef EVALUATE_IMPOSTOR + float distanceToPlaneCenter; + uint twoSided; +#endif +} PushConstants; + +#ifdef EVALUATE_IMPOSTOR +layout(set = 3, binding = 7, std140) uniform UniformBuffer { + mat4 pMatrix; +} Uniforms; +#endif + +void main() { + + colorVS = vec4(1.0); + tangentVS = vec4(0.0); + +#ifdef EVALUATE_MESH + positionVS = vPosition; + normalVS = vNormal.xyz; + texCoordVS = vec2(0.0); +#ifdef TEX_COORDS + texCoordVS = PushConstants.invertUVs > 0 ? vec2(vTexCoord.x, 1.0 - vTexCoord.y) : vTexCoord; +#endif + +#ifdef TANGENTS + tangentVS = vTangent; +#endif +#ifdef VERTEX_COLORS + colorVS = vVertexColors; +#endif + +#ifdef EVALUATE_IMPOSTOR + vec4 positionToCamera = PushConstants.vMatrix * vec4(vPosition, 1.0); + depthVS = positionToCamera.z + PushConstants.distanceToPlaneCenter; + gl_Position = Uniforms.pMatrix * positionToCamera; +#else + // The map is sampled with the coordinates the renderers use, which is what it gets filled with + gl_Position = vec4(2.0 * texCoordVS - 1.0, 0.0, 1.0); +#endif +#else + // A slightly bulged plane, nodes which depend on the normal show something + positionVS = vec3(vPosition.x, -vPosition.y, 0.0); + normalVS = vec3(0.7 * positionVS.xy, 1.0); + texCoordVS = 0.5 * vPosition + 0.5; + tangentVS = vec4(1.0, 0.0, 0.0, 1.0); + + gl_Position = vec4(vPosition, 0.0, 1.0); +#endif + +} diff --git a/data/shader/normalreconstruction.csh b/data/shader/normalreconstruction.csh index 6726b3412..dd8782c8d 100644 --- a/data/shader/normalreconstruction.csh +++ b/data/shader/normalreconstruction.csh @@ -47,8 +47,8 @@ void main() { LoadGroupSharedData(); ivec2 pixel = ivec2(gl_GlobalInvocationID); - if (pixel.x > imageSize(normalImage).x || - pixel.y > imageSize(normalImage).y) + if (pixel.x >= imageSize(normalImage).x || + pixel.y >= imageSize(normalImage).y) return; vec2 texCoord = (vec2(pixel) + 0.5) / vec2(imageSize(normalImage)); diff --git a/data/shader/ocean/butterfly.csh b/data/shader/ocean/butterfly.csh deleted file mode 100644 index cabcb3ab4..000000000 --- a/data/shader/ocean/butterfly.csh +++ /dev/null @@ -1,77 +0,0 @@ -#include <../common/PI.hsh> -#include <../common/complex.hsh> - -layout (local_size_x = 8, local_size_y = 8, local_size_z = 1) in; - -layout (set = 3, binding = 0, rg32f) readonly uniform image2D twiddleIndicesTexture; - -layout (set = 3, binding = 1, rgba32f) readonly uniform image2DArray pingpong0; -layout (set = 3, binding = 2, rgba32f) writeonly uniform image2DArray pingpong1; - -layout(push_constant) uniform constants { - int stage; - int pingpong; - int N; - float preTwiddle; -} PushConstants; - -void horizontal(); -void vertical(); - -void main() { - -#ifdef HORIZONTAL - horizontal(); -#endif -#ifdef VERTICAL - vertical(); -#endif - -} - -void horizontal() { - - int spectrumIdx = int(gl_GlobalInvocationID.z); - ivec2 coord = ivec2(gl_GlobalInvocationID.xy); - - float k = mod(float(coord.x) * PushConstants.preTwiddle, float(PushConstants.N)); - float twiddleArgument = 2.0 * PI * k / float(PushConstants.N); - vec2 twiddleFactor = vec2(cos(twiddleArgument), sin(twiddleArgument)); - - vec2 twiddle = imageLoad(twiddleIndicesTexture, ivec2(PushConstants.stage, coord.x)).rg; - - vec4 s1 = imageLoad(pingpong0, ivec3(twiddle.x, coord.y, spectrumIdx)); - vec4 t1 = imageLoad(pingpong0, ivec3(twiddle.y, coord.y, spectrumIdx)); - - vec4 u1 = vec4(twiddleFactor.x, twiddleFactor.y, - twiddleFactor.x, twiddleFactor.y); - - vec4 H1 = s1 + mul(u1, t1); - - imageStore(pingpong1, ivec3(gl_GlobalInvocationID.xyz), H1); - -} - -void vertical() { - - int spectrumIdx = int(gl_GlobalInvocationID.z); - ivec2 coord = ivec2(gl_GlobalInvocationID.xy); - - float k = mod(float(coord.y) * PushConstants.preTwiddle, float(PushConstants.N)); - float twiddleArgument = 2.0 * PI * k / float(PushConstants.N); - vec2 twiddleFactor = vec2(cos(twiddleArgument), sin(twiddleArgument)); - - vec2 twiddle = imageLoad(twiddleIndicesTexture, ivec2(PushConstants.stage, coord.y)).rg; - - vec4 s1 = imageLoad(pingpong0, ivec3(coord.x, twiddle.x, spectrumIdx)); - vec4 t1 = imageLoad(pingpong0, ivec3(coord.x, twiddle.y, spectrumIdx)); - - vec4 u1 = vec4(twiddleFactor.x, twiddleFactor.y, - twiddleFactor.x, twiddleFactor.y); - - vec4 H1 = s1 + mul(u1, t1); - - imageStore(pingpong1, ivec3(gl_GlobalInvocationID.xyz), H1); - - -} \ No newline at end of file diff --git a/data/shader/ocean/caustics.csh b/data/shader/ocean/caustics.csh index 5c813050a..b413d294c 100644 --- a/data/shader/ocean/caustics.csh +++ b/data/shader/ocean/caustics.csh @@ -39,8 +39,8 @@ const float fadeoutFalloff = 0.2; void main() { ivec2 pixel = ivec2(gl_GlobalInvocationID); - if (pixel.x > imageSize(refractionImage).x || - pixel.y > imageSize(refractionImage).y) + if (pixel.x >= imageSize(refractionImage).x || + pixel.y >= imageSize(refractionImage).y) return; Light light = LightUniforms.light; diff --git a/data/shader/ocean/common.hsh b/data/shader/ocean/common.hsh index 0f62430d3..b95322ffd 100644 --- a/data/shader/ocean/common.hsh +++ b/data/shader/ocean/common.hsh @@ -42,24 +42,23 @@ vec3 GetOceanDisplacement(vec3 position, float dist, out float perlinScale, vec4 fade = saturate((fadeoutDistances - vec4(dist)) / fadeDistances); if (Uniforms.spectrumCount > 0 && fade[0] > 0.0) { - displacement0 = textureLod(displacementMap, vec3(texCoord / tilingFactors[0], 0.0), 0.0).grb * spectrumScaling.x; + displacement0 = textureLod(displacementMap, vec3(texCoord / tilingFactors[0], 0.0), 0.0).rgb * spectrumScaling.x; displacement0 *= fade[0]; } if (Uniforms.spectrumCount > 1 && fade[1] > 0.0) { - displacement1 = textureLod(displacementMap, vec3(texCoord / tilingFactors[1] + vec2(0.25), 1.0), 0.0).grb * spectrumScaling.y; + displacement1 = textureLod(displacementMap, vec3(texCoord / tilingFactors[1] + vec2(0.25), 1.0), 0.0).rgb * spectrumScaling.y; displacement1 *= fade[1]; } if (Uniforms.spectrumCount > 2 && fade[2] > 0.0) { - displacement2 = textureLod(displacementMap, vec3(texCoord / tilingFactors[2] + vec2(0.5), 2.0), 0.0).grb * spectrumScaling.z; + displacement2 = textureLod(displacementMap, vec3(texCoord / tilingFactors[2] + vec2(0.5), 2.0), 0.0).rgb * spectrumScaling.z; displacement2 *= fade[2]; } if (Uniforms.spectrumCount > 3 && fade[3] > 0.0) { - displacement3 = textureLod(displacementMap, vec3(texCoord / tilingFactors[3] + vec2(0.75), 3.0), 0.0).grb * spectrumScaling.w; + displacement3 = textureLod(displacementMap, vec3(texCoord / tilingFactors[3] + vec2(0.75), 3.0), 0.0).rgb * spectrumScaling.w; displacement3 *= fade[3]; } - float weightSum = dot(vec4(1.0), spectrumScaling); - vec3 displacement = (displacement0 + displacement1 + displacement2 + displacement3) / weightSum; + vec3 displacement = displacement0 + displacement1 + displacement2 + displacement3; displacement.y *= Uniforms.displacementScale * shoreScale; displacement.x *= Uniforms.choppyScale * shoreScale; displacement.z *= Uniforms.choppyScale * shoreScale; @@ -81,43 +80,3 @@ vec3 GetOceanDisplacement(vec3 position, float dist, out float perlinScale, return displacement; } - -void GetOceanGradientAndFold(vec2 texCoord, float dist, out float fold, out vec2 gradient) { - - texCoord /= Uniforms.tiling; - - vec4 tilingFactors = Uniforms.spectrumTilingFactors; - vec4 fadeoutDistances = Uniforms.spectrumFadeoutDistances; - - vec4 data0 = vec4(0.0), data1 = vec4(0.0), data2 = vec4(0.0), data3 = vec4(0.0); - - vec4 fade = saturate((fadeoutDistances - vec4(dist)) / fadeDistances); - if (Uniforms.spectrumCount > 0 && fade[0] > 0.0) { - data0 = texture(normalMap, vec3(texCoord / tilingFactors[0], 0.0)); - data0 *= fade[0]; - } - if (Uniforms.spectrumCount > 1 && fade[1] > 0.0) { - data1 = texture(normalMap, vec3(texCoord / tilingFactors[1] + vec2(0.25), 1.0)); - data1 *= fade[1]; - } - if (Uniforms.spectrumCount > 2 && fade[2] > 0.0) { - data2 = texture(normalMap, vec3(texCoord / tilingFactors[2] + vec2(0.5), 2.0)); - data2 *= fade[2]; - } - if (Uniforms.spectrumCount > 3 && fade[3] > 0.0) { - data3 = texture(normalMap, vec3(texCoord / tilingFactors[3] + vec2(0.75), 3.0)); - data3 *= fade[3]; - } - - float perlin = textureLod(perlinNoiseMap, texCoord * 0.125 * 0.125, 0.0).r; - float perlinScale = sqr(clamp(perlin, 0.0, 1.0)); - - float weightSum = dot(vec4(1.0), spectrumScaling); - fold = saturate(10.0 * ((data0.a + data1.a + data2.a + data3.a) / weightSum)); - gradient = ((data0.rg) + (data1.rg) - + (data2.rg) + (data3.rg)); - - //fold *= perlinScale; - //gradient *= perlinScale; - -} \ No newline at end of file diff --git a/data/shader/ocean/depth.fsh b/data/shader/ocean/depth.fsh index bc62a6e90..b089e3764 100644 --- a/data/shader/ocean/depth.fsh +++ b/data/shader/ocean/depth.fsh @@ -2,7 +2,20 @@ #include <../common/stencil.hsh> #include <../globals.hsh> +#include +#include + +layout (location = 0) in vec3 fOriginalCoord; +layout (location = 1) in float shoreScaling; +#ifdef TERRAIN +layout (location = 2) in vec3 normalShoreWave; +#endif + +layout (set = 3, binding = 5) uniform sampler2D depthTexture; + layout (location = 0) out uint stencil; +// Encoded view space normal, the ray origins for the reflections +layout (location = 1) out vec2 normal; void main() { @@ -23,6 +36,23 @@ void main() { features.waterPixel = true; + // Only the visible surface needs a normal, the depth is still needed below the scene + normal = vec2(0.0); + if (gl_FragCoord.z <= texelFetch(depthTexture, ivec2(gl_FragCoord.xy), 0).r) { + float fold, jacobian, slopeVariance; + vec2 gradient; + float viewDistance = distance(fOriginalCoord, globalData.cameraLocation.xyz); + GetOceanGradientAndFold(fOriginalCoord.xz, viewDistance, fold, gradient, jacobian, slopeVariance); + + // The reflections treat the water surface as a perfect mirror + vec3 worldNormal = normalize(vec3(gradient.x, 1.0, gradient.y)); +#ifdef TERRAIN + worldNormal = mix(normalShoreWave, worldNormal, shoreScaling); +#endif + worldNormal = GetOceanRippleNormal(worldNormal, fOriginalCoord.xz, shoreScaling); + normal = EncodeNormal(normalize(vec3(globalData.vMatrix * vec4(worldNormal, 0.0)))); + } + // Remember that the ocean stencil has only 8 bits, need to be careful about the features // and their bit order. stencil = EncodeStencilFeatures(features); diff --git a/data/shader/ocean/depth.vsh b/data/shader/ocean/depth.vsh index efc2f1259..5605432e5 100644 --- a/data/shader/ocean/depth.vsh +++ b/data/shader/ocean/depth.vsh @@ -7,6 +7,12 @@ layout(location=0) in vec3 vPosition; +layout(location=0) out vec3 fOriginalCoord; +layout(location=1) out float shoreScaling; +#ifdef TERRAIN +layout(location=2) out vec3 normalShoreWave; +#endif + vec3 stitch(vec3 position) { // Note: This only works because our grid has a constant size @@ -42,10 +48,13 @@ void main() { vec3(PushConstants.nodeLocation.x, 0.0, PushConstants.nodeLocation.y) + Uniforms.translation.xyz; + fOriginalCoord = fPosition; float distanceToCamera = distance(fPosition.xyz, globalData.cameraLocation.xyz); - float perlinScale, shoreScaling; +#ifndef TERRAIN vec3 normalShoreWave; +#endif + float perlinScale; fPosition += GetOceanDisplacement(fPosition, distanceToCamera, perlinScale, shoreScaling, normalShoreWave); vec3 position = vec3(globalData.vMatrix * vec4(fPosition, 1.0)); diff --git a/data/shader/ocean/fft.csh b/data/shader/ocean/fft.csh new file mode 100644 index 000000000..78f4c1da4 --- /dev/null +++ b/data/shader/ocean/fft.csh @@ -0,0 +1,193 @@ +#include <../common/PI.hsh> +#include <../common/complex.hsh> + +layout (local_size_x = FFT_SIZE / 2, local_size_y = 1, local_size_z = 1) in; + +#ifdef HORIZONTAL +layout (set = 3, binding = 0, rgba32f) writeonly uniform image2DArray hTD; +layout (set = 3, binding = 1, rg32f) readonly uniform image2DArray h0K; +#ifdef NORMALS +layout (set = 3, binding = 2, rgba32f) writeonly uniform image2DArray hTDSlopes; +#endif +#endif +#ifdef VERTICAL +layout (set = 3, binding = 0, rgba16f) writeonly uniform image2DArray displacementMap; +layout (set = 3, binding = 1, rgba32f) readonly uniform image2DArray hTD; +#ifdef NORMALS +layout (set = 3, binding = 2, rgba16f) writeonly uniform image2DArray normalMap; +layout (set = 3, binding = 3, rgba32f) readonly uniform image2DArray hTDSlopes; +#endif +#endif + +layout(push_constant) uniform constants { + vec4 L; + vec4 spectrumScaling; + float time; + float choppyScale; + float displacementScale; +} PushConstants; + +const float g = 9.81; + +shared vec4 sharedData[FFT_SIZE]; +#ifdef NORMALS +shared vec4 sharedSlopes[FFT_SIZE]; +#endif + +int ReverseBits(int idx) { + + return int(bitfieldReverse(uint(idx)) >> uint(32 - findMSB(FFT_SIZE))); + +} + +#ifdef HORIZONTAL +vec2 MulI(vec2 c) { + + return vec2(-c.y, c.x); + +} + +vec4 ComputeSpectrum(ivec3 coord, out vec4 slopes) { + + vec2 waveCoord = vec2(coord.xy) - float(FFT_SIZE) / 2.0; + vec2 waveVector = 2.0 * PI / PushConstants.L[coord.z] * waveCoord; + + float k = length(waveVector); + float w = sqrt(g * k); + + ivec2 inverseCoords = (FFT_SIZE - coord.xy) % FFT_SIZE; + vec2 h0_k = imageLoad(h0K, coord).rg; + vec2 h0_mk = imageLoad(h0K, ivec3(inverseCoords, coord.z)).rg; + + float cos_wt = cos(w * PushConstants.time); + float sin_wt = sin(w * PushConstants.time); + + // Calculate h(t) + vec2 ht; + ht.x = cos_wt * (h0_k.x + h0_mk.x) - sin_wt * (h0_k.y + h0_mk.y); + ht.y = sin_wt * (h0_k.x - h0_mk.x) + cos_wt * (h0_k.y - h0_mk.y); + + // From h(t) calculate dx(t) and dy(t) as i * k / |k| * h(t), which moves the points towards the crests + float kt2 = dot(waveCoord, waveCoord); + vec2 nkt = vec2(0.0); + + if (kt2 > 1e-12) + nkt = normalize(waveCoord); + + vec2 dt_x = vec2(-ht.y * nkt.x, ht.x * nkt.x); + vec2 idt_z = vec2(-ht.x * nkt.y, -ht.y * nkt.y); + +#ifdef NORMALS + // Real results are packed in pairs: h + i * dDx/dz, dh/dx + i * dh/dz and dDx/dx + i * dDz/dz + vec2 slopeX = MulI(ht) * waveVector.x; + vec2 slopeZ = MulI(ht) * waveVector.y; + vec2 dxx = -ht * waveVector.x * nkt.x; + vec2 dzz = -ht * waveVector.y * nkt.y; + vec2 dxz = -ht * waveVector.x * nkt.y; + + slopes = vec4(slopeX + MulI(slopeZ), dxx + MulI(dzz)); + ht += MulI(dxz); +#else + slopes = vec4(0.0); +#endif + + return vec4(ht, dt_x + idt_z); + +} +#endif + +void FFT() { + + int idx = int(gl_LocalInvocationIndex); + + for (int span = 1; span < FFT_SIZE; span *= 2) { + int pos = idx % span; + int top = (idx / span) * span * 2 + pos; + int bottom = top + span; + + float twiddleArgument = PI * float(pos) / float(span); + vec2 twiddleFactor = vec2(cos(twiddleArgument), sin(twiddleArgument)); + + vec4 s = sharedData[top]; + vec4 t = mul(vec4(twiddleFactor, twiddleFactor), sharedData[bottom]); + + sharedData[top] = s + t; + sharedData[bottom] = s - t; + +#ifdef NORMALS + s = sharedSlopes[top]; + t = mul(vec4(twiddleFactor, twiddleFactor), sharedSlopes[bottom]); + + sharedSlopes[top] = s + t; + sharedSlopes[bottom] = s - t; +#endif + + barrier(); + } + +} + +void main() { + + int idx = int(gl_LocalInvocationIndex); + int spectrumIdx = int(gl_WorkGroupID.z); + +#ifdef HORIZONTAL + int row = int(gl_WorkGroupID.y); + + for (int i = idx; i < FFT_SIZE; i += FFT_SIZE / 2) { + vec4 slopes; + sharedData[ReverseBits(i)] = ComputeSpectrum(ivec3(i, row, spectrumIdx), slopes); +#ifdef NORMALS + sharedSlopes[ReverseBits(i)] = slopes; +#endif + } + + barrier(); + + FFT(); + + for (int i = idx; i < FFT_SIZE; i += FFT_SIZE / 2) { + imageStore(hTD, ivec3(i, row, spectrumIdx), sharedData[i]); +#ifdef NORMALS + imageStore(hTDSlopes, ivec3(i, row, spectrumIdx), sharedSlopes[i]); +#endif + } +#endif + +#ifdef VERTICAL + int column = int(gl_WorkGroupID.x); + + for (int i = idx; i < FFT_SIZE; i += FFT_SIZE / 2) { + sharedData[ReverseBits(i)] = imageLoad(hTD, ivec3(column, i, spectrumIdx)); +#ifdef NORMALS + sharedSlopes[ReverseBits(i)] = imageLoad(hTDSlopes, ivec3(column, i, spectrumIdx)); +#endif + } + + barrier(); + + FFT(); + + for (int i = idx; i < FFT_SIZE; i += FFT_SIZE / 2) { + vec4 data = sharedData[i]; + float perm = bool((column + i) & 1) ? -1.0 : 1.0; + imageStore(displacementMap, ivec3(column, i, spectrumIdx), vec4(perm * data.bra, 1.0)); + +#ifdef NORMALS + vec4 slopes = perm * sharedSlopes[i]; + float scale = PushConstants.spectrumScaling[spectrumIdx]; + float choppyScale = PushConstants.choppyScale * scale; + + // Same as the normal shader, but without the error of finite differences + vec2 slope = slopes.xy * PushConstants.displacementScale * scale; + vec3 derivatives = vec3(slopes.zw, perm * data.g) * choppyScale; + float J = (1.0 + derivatives.x) * (1.0 + derivatives.y) - derivatives.z * derivatives.z; + + vec2 gradient = slope / max(vec2(1.0) + derivatives.xy, vec2(0.01)); + imageStore(normalMap, ivec3(column, i, spectrumIdx), vec4(-gradient, dot(gradient, gradient), 1.0 - J)); +#endif + } +#endif + +} diff --git a/data/shader/ocean/h0.csh b/data/shader/ocean/h0.csh index 950ed6b9a..bc9dc77b9 100644 --- a/data/shader/ocean/h0.csh +++ b/data/shader/ocean/h0.csh @@ -10,9 +10,10 @@ layout(set = 3, binding = 4) uniform sampler2D noise2; layout(set = 3, binding = 5) uniform sampler2D noise3; layout(push_constant) uniform constants { - ivec4 L; + vec4 L; vec2 w; int N; + int C; float A; float windspeed; float windDependency; @@ -21,13 +22,17 @@ layout(push_constant) uniform constants { const float g = 9.81; +// Each cascade keeps the waves between a fraction of its size and that of the next smaller cascade +const float bandWavelengthFraction = 0.25; + // Box-Muller transform: https://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform vec2 gaussrnd() { - vec2 coord = vec2(gl_GlobalInvocationID.xy) / float(PushConstants.N); - - float U00 = clamp(texture(noise0, coord).r + 0.00001, 0.0, 1.0); - float U01 = clamp(texture(noise1, coord).r + 0.00001, 0.0, 1.0); + // The cascades use the same wave vector indices, with the same random numbers they would repeat each other + ivec2 pixel = (ivec2(gl_GlobalInvocationID.xy) + int(gl_GlobalInvocationID.z) * ivec2(131, 241)) % PushConstants.N; + + float U00 = clamp(texelFetch(noise0, pixel, 0).r + 0.00001, 0.0, 1.0); + float U01 = clamp(texelFetch(noise1, pixel, 0).r + 0.00001, 0.0, 1.0); float R0 = sqrt(-2.0 * log(U00)); float T0 = 2.0 * PI * U01; @@ -58,16 +63,30 @@ void main() { vec2 coord = vec2(gl_GlobalInvocationID.xy) - float(PushConstants.N) / 2.0; - vec2 waveVector = 2.0 * PI / float(PushConstants.L[spectrumIdx]) * coord; + vec2 waveVector = 2.0 * PI / PushConstants.L[spectrumIdx] * coord; float l = (PushConstants.windspeed * PushConstants.windspeed) / g; - float h0k = sqrt(phillips(waveVector, PushConstants.A, l, PushConstants.w)) / sqrt(2.0); + // Scaled by the frequency step, such that the wave heights don't depend on the cascade size + float dk = 2.0 * PI / PushConstants.L[spectrumIdx]; + float h0k = sqrt(phillips(waveVector, PushConstants.A, l, PushConstants.w)) / sqrt(2.0) * dk; vec2 rnd = gaussrnd(); - if (waveVector.x == 0.0 && - waveVector.y == 0.0) { + float L = PushConstants.L[spectrumIdx]; + float smallerL = 0.0; + bool hasLarger = false; + for (int i = 0; i < PushConstants.C; i++) { + if (PushConstants.L[i] < L) + smallerL = max(smallerL, PushConstants.L[i]); + hasLarger = hasLarger || PushConstants.L[i] > L; + } + + float k = length(waveVector); + float kMin = hasLarger ? 2.0 * PI / (bandWavelengthFraction * L) : 0.0; + float kMax = smallerL > 0.0 ? 2.0 * PI / (bandWavelengthFraction * smallerL) : 1e20; + + if (k == 0.0 || k < kMin || k >= kMax) { h0k = 0.0; } diff --git a/data/shader/ocean/ht.csh b/data/shader/ocean/ht.csh deleted file mode 100644 index 5aa24c44f..000000000 --- a/data/shader/ocean/ht.csh +++ /dev/null @@ -1,52 +0,0 @@ -#include <../common/PI.hsh> -#include <../common/complex.hsh> - -layout (local_size_x = 16, local_size_y = 16, local_size_z = 1) in; - -layout (set = 3, binding = 0, rgba32f) writeonly uniform image2DArray hTD; -layout (set = 3, binding = 1, rg32f) readonly uniform image2DArray h0K; - -layout(push_constant) uniform constants { - ivec4 L; - int N; - float time; -} PushConstants; - -const float g = 9.81; - -void main() { - - int spectrumIdx = int(gl_GlobalInvocationID.z); - vec2 coord = vec2(gl_GlobalInvocationID.xy) - float(PushConstants.N) / 2.0; - - vec2 waveVector = 2.0 * PI / float(PushConstants.L[spectrumIdx]) * coord; - - float k = length(waveVector); - float w = sqrt(g * k); - - ivec2 inverseCoords = (ivec2(imageSize(h0K))) - ivec2(gl_GlobalInvocationID); - vec2 h0_k = imageLoad(h0K, ivec3(gl_GlobalInvocationID.xy, spectrumIdx)).rg; - vec2 h0_mk = imageLoad(h0K, ivec3(inverseCoords, spectrumIdx)).rg; - - float cos_wt = cos(w * PushConstants.time); - float sin_wt = sin(w * PushConstants.time); - - // Calculate h(t) - vec2 ht; - ht.x = cos_wt * (h0_k.x + h0_mk.x) - sin_wt * (h0_k.y + h0_mk.y); - ht.y = sin_wt * (h0_k.x - h0_mk.x) + cos_wt * (h0_k.y - h0_mk.y); - - // From h(t) calculate dx(t) and dy(t) - vec2 kt = coord; - float kt2 = dot(kt, kt); - vec2 nkt = vec2(0.0); - - if (kt2 > 1e-12) - nkt = normalize(kt); - - vec2 dt_x = vec2(ht.y * nkt.x, -ht.x * nkt.x); - vec2 idt_z = vec2(ht.x * nkt.y, ht.y * nkt.y); - - imageStore(hTD, ivec3(gl_GlobalInvocationID.xyz), vec4(ht, dt_x + idt_z)); - -} \ No newline at end of file diff --git a/data/shader/ocean/inversion.csh b/data/shader/ocean/inversion.csh deleted file mode 100644 index 8145e4207..000000000 --- a/data/shader/ocean/inversion.csh +++ /dev/null @@ -1,23 +0,0 @@ -layout (local_size_x = 16, local_size_y = 16, local_size_z = 1) in; - -layout (set = 3, binding = 0, rgba16f) writeonly uniform image2DArray displacementMap; -layout (set = 3, binding = 1, rgba32f) readonly uniform image2DArray pingpongMap; - -void main() { - - ivec3 coord = ivec3(gl_GlobalInvocationID.xyz); - - float perm = bool((coord.x + coord.y) & 1) ? -1.0 : 1.0; - - vec3 displacement; - - float x = imageLoad(pingpongMap, coord).b; - float y = imageLoad(pingpongMap, coord).r; - float z = imageLoad(pingpongMap, coord).a; - - displacement = perm * vec3(x, y, z); - - imageStore(displacementMap, coord, - vec4(displacement, 1.0)); - -} \ No newline at end of file diff --git a/data/shader/ocean/normal.csh b/data/shader/ocean/normal.csh index da2547748..37d5d3a7b 100644 --- a/data/shader/ocean/normal.csh +++ b/data/shader/ocean/normal.csh @@ -7,7 +7,6 @@ layout (set = 3, binding = 1, rgba16f) writeonly uniform image2DArray normalMap; // layout (set = 3, binding = 2, rgba16f) readonly uniform image2D historyMap; layout(push_constant) uniform constants { - ivec4 L; vec4 tilingFactor; vec4 spectrumScaling; int N; @@ -17,8 +16,6 @@ layout(push_constant) uniform constants { float temporalWeight; float temporalThreshold; - - float foamOffset; } PushConstants; vec3 AdjustScale(vec3 point) { @@ -40,11 +37,11 @@ void main() { float tileSize = (tilingFactor * PushConstants.tiling) / float(PushConstants.N); float invTileSize = 1.0 / tileSize; - vec3 center = imageLoad(displacementMap, coord).grb; - vec3 left = imageLoad(displacementMap, ivec3(mod(fCoord.x - 1.0, fN), coord.y, coord.z)).grb; - vec3 right = imageLoad(displacementMap, ivec3(mod(fCoord.x + 1.0, fN), coord.y, coord.z)).grb; - vec3 top = imageLoad(displacementMap, ivec3(coord.x, mod(fCoord.y + 1.0, fN), coord.z)).grb; - vec3 bottom = imageLoad(displacementMap, ivec3(coord.x, mod(fCoord.y - 1.0, fN), coord.z)).grb; + vec3 center = imageLoad(displacementMap, coord).rgb; + vec3 left = imageLoad(displacementMap, ivec3(mod(fCoord.x - 1.0, fN), coord.y, coord.z)).rgb; + vec3 right = imageLoad(displacementMap, ivec3(mod(fCoord.x + 1.0, fN), coord.y, coord.z)).rgb; + vec3 top = imageLoad(displacementMap, ivec3(coord.x, mod(fCoord.y + 1.0, fN), coord.z)).rgb; + vec3 bottom = imageLoad(displacementMap, ivec3(coord.x, mod(fCoord.y - 1.0, fN), coord.z)).rgb; center = AdjustScale(center); left = AdjustScale(left); @@ -54,22 +51,19 @@ void main() { // float history = imageLoad(historyMap, coord).a; - // Calculate jacobian - vec2 Dx = 2.0 * (right.xz - left.xz); - vec2 Dy = 2.0 * (top.xz - bottom.xz); - float J = (tileSize + Dx.x) * (tileSize + Dy.y) - Dx.y * Dy.x; - - float fold = max(0.0, -clamp(J, -1.0, 1.0) + PushConstants.foamOffset); + // Calculate jacobian, it's 1 for undisturbed water and negative where the waves fold over + vec2 Dx = 0.5 * invTileSize * (right.xz - left.xz); + vec2 Dy = 0.5 * invTileSize * (top.xz - bottom.xz); + float J = (1.0 + Dx.x) * (1.0 + Dy.y) - Dx.y * Dy.x; - /* - float blend = fold > PushConstants.temporalThreshold ? 0.0 : 0.0; - fold = mix(fold, history, blend); - */ + // The cascades are combined into an approximate jacobian of the whole surface when rendering + float jacobianDeficit = 1.0 - J; float width = right.x - center.x; float height = top.z - center.z; vec2 gradient = vec2(right.y - center.y, top.y - center.y) / max(tileSize + vec2(width, height), tileSize * 0.01); - imageStore(normalMap, coord, vec4(-gradient, 0.0, fold)); + // The squared slope is averaged by the mip maps, the rendering derives the roughness from it + imageStore(normalMap, coord, vec4(-gradient, dot(gradient, gradient), jacobianDeficit)); } \ No newline at end of file diff --git a/data/shader/ocean/ocean.fsh b/data/shader/ocean/ocean.fsh index 12012460c..91b2a8d06 100644 --- a/data/shader/ocean/ocean.fsh +++ b/data/shader/ocean/ocean.fsh @@ -1,6 +1,7 @@ #define SHADOW_FILTER_VOGEL #include +#include #include <../common/convert.hsh> #include <../common/utility.hsh> #include <../common/stencil.hsh> @@ -9,8 +10,18 @@ #include <../clouds/shadow.hsh> #include <../volumetric/volumetric.hsh> #include <../structures.hsh> +#include <../brdf/brdf.hsh> #include +#include + +#ifdef DDGI +#include <../ddgi/ddgi.hsh> +#endif + +// From deferred.hsh +layout(set = 1, binding = 11) uniform samplerCube specularProbe; +layout(set = 1, binding = 12) uniform samplerCube diffuseProbe; // Lighting based on Island Demo (NVIDIA SDK 11) @@ -19,12 +30,13 @@ layout (location = 1) out vec2 velocity; layout (location = 2) out uint stencil; layout (set = 3, binding = 2) uniform sampler2D foamTexture; -layout (set = 3, binding = 3) uniform samplerCube skyEnvProbe; +#ifdef REFLECTION +layout (set = 3, binding = 3) uniform sampler2D reflectionTexture; +#endif layout (set = 3, binding = 4) uniform sampler2D refractionTexture; layout (set = 3, binding = 5) uniform sampler2D depthTexture; layout (set = 3, binding = 7) uniform sampler2D volumetricTexture; layout (set = 3, binding = 8) uniform sampler2DArrayShadow cascadeMaps; -layout (set = 3, binding = 10) uniform sampler2D rippleTexture; layout(set = 3, binding = 15) uniform sampler2D cloudShadowMap; layout(set = 3, binding = 16) uniform sampler2D volumetricCloudTexture; layout(set = 3, binding = 20) uniform sampler2D oceanDepthTexture; @@ -41,17 +53,18 @@ layout(location=8) in vec3 ndcLast; layout(location=9) in vec3 normalShoreWave; #endif -// Control water scattering at crests -const float scatterIntensity = 1.5; -const float scatterCrestScale = 0.2; -const float scatterCrestOffset = 0.0; +// Sun light scattered through the thin wave crests, the jacobian tells how thin they are +const float scatterIntensity = 2.5; +const float scatterThinnessScale = 4.0; +const float scatterCrestHeight = 1.0; -// Specular properties -const float specularPower = 500.0; -const float specularIntensity = 350.0; +// From right below, the surface stays partly transparent near the camera +const float nearSurfaceTransmission = 0.6; +const float nearSurfaceCameraDepth = 1.5; +const float nearSurfaceDistance = 15.0; // Shore softness (lower is softer) -const float shoreSoftness = 70.5; +const float shoreSoftness = 7.5; const float fadeoutDistance = 100.0; const float fadeoutFalloff = 0.2; @@ -68,12 +81,10 @@ void main() { Light light = LightUniforms.light; - vec2 fTexCoord = fOriginalCoord.xz / Uniforms.tiling; - - float fold; + float fold, jacobian, slopeVariance; vec2 gradientDisplacement; - GetOceanGradientAndFold(fOriginalCoord.xz, distance(fOriginalCoord.xyz, globalData.cameraLocation.xyz), - fold, gradientDisplacement); + float viewDistance = distance(fOriginalCoord.xyz, globalData.cameraLocation.xyz); + GetOceanGradientAndFold(fOriginalCoord.xz, viewDistance, fold, gradientDisplacement, jacobian, slopeVariance); /* // This stuff calculates the geometry normals from the depth buffer @@ -95,10 +106,10 @@ void main() { vec3 depthPos = ConvertDepthToViewSpace(clipDepth, ndcCoord); //vec3 fNormal = normal; - vec3 fNormal = normalize(vec3(gradientDisplacement.x, 2.0, gradientDisplacement.y)); + vec3 fNormal = normalize(vec3(gradientDisplacement.x, 1.0, gradientDisplacement.y)); - float shadowFactor = max(CalculateCascadedShadow(light.shadow, cascadeMaps, fPosition, - vec3(gl_FragCoord.xy, 0.0), fNormal, 0.0), 1.0); + float shadowFactor = CalculateCascadedShadow(light.shadow, cascadeMaps, fPosition, + vec3(gl_FragCoord.xy, 0.0), fNormal, 0.0); #ifdef CLOUD_SHADOWS @@ -112,58 +123,40 @@ void main() { fNormal = mix(normalShoreWave, fNormal, shoreScaling); #endif - // Create TBN matrix for normal mapping - vec3 norm = fNormal; - vec3 tang = vec3(1.0, 0.0, 0.0); - tang.y = -((norm.x*tang.x) / norm.y) - ((norm.z*tang.z) / norm.y); - tang = normalize(tang); - vec3 bitang = normalize(cross(tang, norm)); - mat3 tbn = mat3(tang, bitang, norm); - - // Normal mapping normal (offsets actual normal) - vec3 rippleNormal = vec3(0.0, 1.0, 0.0); - -#ifdef RIPPLE_TEXTURE - rippleNormal = normalize(2.0 * texture(rippleTexture, 20.0 * fTexCoord - vec2(globalData.time * 0.2), globalData.mipLodBias).rgb - 1.0); - rippleNormal += normalize(2.0 * texture(rippleTexture, 20.0 * fTexCoord * 0.5 + vec2(globalData.time * 0.05), globalData.mipLodBias).rgb - 1.0); - // Won't work with rippleNormal = vec3(0.0, 1.0, 0.0). Might be worth an investigation - norm = normalize(tbn * rippleNormal); -#endif - - // Scale ripples based on actual (not view) depth of water - float rippleScaling = clamp(1.0 - shoreScaling, 0.05, 0.1); - norm = normalize(mix(fNormal, norm, rippleScaling)); + vec3 norm = GetOceanRippleNormal(fNormal, fOriginalCoord.xz, shoreScaling); vec3 eyeDir = normalize(fModelCoord - globalData.cameraLocation.xyz); + vec3 lightDir = -light.direction.xyz; - float nDotL = dot(norm, -light.direction.xyz); + float nDotL = dot(norm, lightDir); float nDotE = saturate(dot(norm, -eyeDir)); // Calculate fresnel factor - float fresnel = 0.02 + (1.0 - 0.02) * pow(1.0 - nDotE, 5.0); - - // Calculate reflection vector + float fresnel = FresnelSchlick(vec3(0.02), 1.0, nDotE).r; + + // Reflections below the horizon would show the ground of the sky probe vec3 reflectionVec = normalize(reflect(eyeDir, norm)); - //reflectionVec.y = max(0.0, reflectionVec.y); - + reflectionVec.y = max(0.0, reflectionVec.y); + reflectionVec = normalize(reflectionVec); + // Calculate sun spot - float specularFactor = shadowFactor * fresnel * pow(max(dot(normalize(reflectionVec), - -normalize(light.direction.xyz)), 0.0), specularPower); + float alpha = GetOceanAlpha(slopeVariance); + float surfaceRoughness = sqrt(alpha); + // The sun is a disk, the half vectors which reflect parts of it spread by half its angular radius + float sunAlpha = sqrt(sqr(alpha) + sqr(tan(0.5 * Uniforms.sunAngularRadius))); + vec3 halfway = normalize(lightDir - eyeDir); + float specularFactor = shadowFactor * saturate(nDotL) * DistributionGGX(saturate(dot(norm, halfway)), sunAlpha) * + VisibilitySmithGGXCorrelated(saturate(nDotL), max(nDotE, 0.0001), sunAlpha) * + FresnelSchlick(vec3(0.02), 1.0, saturate(dot(-eyeDir, halfway))).r; // Scattering equations float waveHeight = fModelCoord.y - Uniforms.translation.y; - float scatterFactor = scatterIntensity * max(0.0, waveHeight - * scatterCrestScale + scatterCrestOffset); - - scatterFactor *= shadowFactor * pow(max(0.0, dot(-light.direction.xyz, eyeDir)), 8.0); - - scatterFactor *= pow(clamp(1.0 - nDotL, 0.0, 1.1), 16.0); - - /* - scatterFactor += shadowFactor * Uniforms.waterColorIntensity.y - * max(0.0, waveHeight) * max(0.0, nDotE) * - max(0.0, 1.0 + eyeDir.y) * dot(-light.direction.xyz, -eyeDir); - */ + float crestThinness = saturate((1.0 - jacobian) * scatterThinnessScale) * + smoothstep(0.0, scatterCrestHeight, waveHeight); + // Only visible when looking towards the sun through the wave side which faces away from it + float scatterFactor = scatterIntensity * crestThinness * pow(saturate(dot(lightDir, eyeDir)), 4.0) * + pow(saturate(0.5 - 0.5 * dot(lightDir, norm)), 3.0); + scatterFactor *= shadowFactor * saturate(lightDir.y + 0.2); // Calculate water depth based on the viewer (ray from camera to ground) float waterViewDepth = max(0.0, fPosition.z - depthPos.z); @@ -175,23 +168,47 @@ void main() { // Retrieve colors from textures vec3 refractionColor = textureLod(refractionTexture, ndcCoord + refractionDisturbance, 0).rgb; - vec3 reflectionColor = textureLod(skyEnvProbe, reflectionVec, 0).rgb; +#ifdef REFLECTION + // Traced and filtered from the ocean surface together with the reflections of the scene + vec3 reflectionColor = textureLod(reflectionTexture, ndcCoord, 0.0).rgb; +#else + float reflectionMipLevel = surfaceRoughness * float(textureQueryLevels(specularProbe) - 1); + vec3 reflectionColor = textureLod(specularProbe, reflectionVec, reflectionMipLevel).rgb; +#endif - // Calculate water color - vec3 depthFog = mix(Uniforms.deepWaterBodyColor.rgb, Uniforms.waterBodyColor.rgb, min(1.0 , exp(-waterViewDepth / 10.0))); - float diffuseFactor = Uniforms.waterColorIntensity.x + Uniforms.waterColorIntensity.y * - max(0.0, nDotL) * shadowFactor; - vec3 waterColor = diffuseFactor * light.intensity * light.color.rgb * depthFog; + // The light which enters the water body from above, like the indirect diffuse lighting of the scene + vec3 indirectLight = textureLod(diffuseProbe, norm, 0.0).rgb; +#ifdef DDGI +#ifdef DDGI_SCROLL + vec4 indirectLightLocal = ddgiData.volumeEnabled > 0 ? + GetLocalIrradiance(fModelCoord, eyeDir, norm, norm, indirectLight) : vec4(0.0, 0.0, 0.0, 1.0); +#else + vec4 indirectLightLocal = ddgiData.volumeEnabled > 0 ? + GetLocalIrradiance(fModelCoord, eyeDir, norm, norm) : vec4(0.0, 0.0, 0.0, 1.0); +#endif + indirectLightLocal = IsInsideVolume(fModelCoord) ? indirectLightLocal : vec4(0.0, 0.0, 0.0, 1.0); + indirectLight = (indirectLightLocal.rgb + indirectLight * indirectLightLocal.a) * ddgiData.volumeStrength; +#endif + + // Light scattered by the water body along the refracted view ray, like seen from under water + vec3 extinction = GetWaterExtinction(); + float waterRayLength = distance(fPosition, depthPos); + vec3 sunScattering, ambientScattering; + GetWaterScattering(extinction, refract(eyeDir, norm, 1.0 / waterRefractiveIndex), 0.0, waterRayLength, + light, indirectLight, sunScattering, ambientScattering); + vec3 waterColor = shadowFactor * sunScattering + ambientScattering; // Water edges at shore sould be soft fresnel *= min(1.0, waterViewDepth * shoreSoftness); - // Update refraction color based on water depth (exponential falloff) - refractionColor = mix(waterColor, refractionColor, min(1.0 , exp(-waterViewDepth / 2.0))); + // The ground was lit with the light above the water, it lost energy on the way down + vec3 groundPos = vec3(globalData.ivMatrix * vec4(depthPos, 1.0)); + refractionColor *= GetWaterDownwellingTransmittance(light, max(Uniforms.translation.y - groundPos.y, 0.0)); + refractionColor = refractionColor * exp(-extinction * waterRayLength) + waterColor; vec2 shoreInteraction = vec2(0.0); #ifdef TERRAIN - shoreInteraction = CalculateShoreInteraction(fModelCoord); + shoreInteraction = CalculateShoreInteraction(fOriginalCoord); #endif // Calculate foam based on folding of wave and fade it out near shores @@ -204,30 +221,66 @@ void main() { // Mix relection and refraction and add sun spot color = mix(refractionColor, reflectionColor, fresnel); - color += specularIntensity * fresnel * specularFactor * light.color.rgb; - color += Uniforms.scatterColor.rgb * scatterFactor; + color += specularFactor * light.intensity * light.color.rgb; + color += (1.0 - fresnel) * scatterFactor * light.intensity * light.color.rgb * Uniforms.scatterColor.rgb; - vec3 foamShadowFactor = mix(vec3(0.1), - vec3(0.5) * max(0.0, nDotL) * shadowFactor, 0.7); + // Foam is a bright diffuse surface lit by the sun and the sky + const float foamAlbedo = 0.9; + vec3 foamLight = max(0.0, nDotL) * shadowFactor * light.intensity * light.color.rgb * INV_PI + indirectLight; - vec3 foamColor = vec3(1.0); + // Without a foam texture the foam is broken up by noise #ifdef FOAM_TEXTURE - foamColor = foamShadowFactor * light.intensity * light.color.rgb; + float foamPattern = texture(foamTexture, fOriginalCoord.xz / (2.0 * Uniforms.foamSize), globalData.mipLodBias).r; +#else + float foamNoise = 0.6 * texture(perlinNoiseMap, fOriginalCoord.xz / (3.0 * Uniforms.foamSize), globalData.mipLodBias).r + + 0.4 * texture(perlinNoiseMap, fOriginalCoord.xz / Uniforms.foamSize, globalData.mipLodBias).r; + float foamPattern = saturate((foamNoise - 0.2) / 0.6); #endif - color = mix(color, foamColor, foam * texture(foamTexture, fOriginalCoord.xz / 8.0, globalData.mipLodBias).r); + // The pattern shapes the foam edges and gives the foam its structure + vec3 foamColor = foamAlbedo * mix(0.35, 1.0, foamPattern) * foamLight; + float foamEdge = max(fwidth(foamPattern), 0.1); + float foamCoverage = smoothstep(1.0 - foam - foamEdge, 1.0 - foam + foamEdge, foamPattern) * step(0.001, foam); + color = mix(color, foamColor, foamCoverage); - vec3 breakingColor = foamShadowFactor * light.intensity * light.color.rgb; + vec3 breakingColor = foamAlbedo * foamLight; color = mix(color, breakingColor, shoreInteraction.y); StencilFeatures features = CreateStencilFeatures(); if (!gl_FrontFacing) { - fresnel = 0.02 + (1.0 - 0.02) * pow(1.0 - saturate(dot(fNormal, eyeDir)), 5.0); disturbance = (mat3(globalData.vMatrix) * -vec3(norm.x, 0.0, norm.z)).xz; refractionDisturbance = vec2(disturbance.x, -disturbance.y) * 0.1; refractionDisturbance *= min(2.0, waterViewDepth); - color = textureLod(refractionTexture, ndcCoord + refractionDisturbance, 0).rgb * (1.0 - fresnel); + vec3 transmittedColor = textureLod(refractionTexture, ndcCoord + refractionDisturbance, 0).rgb; + + // Light from above only gets through inside of Snell's window, outside of it the water body is reflected + // The waves only bend the edge of the window slightly, it stays a circle + vec3 windowNormal = normalize(mix(vec3(0.0, 1.0, 0.0), norm, 0.3)); + vec3 transmittedDir = refract(eyeDir, -windowNormal, waterRefractiveIndex); + float windowTransmission = dot(transmittedDir, transmittedDir) > 0.0 ? + 1.0 - FresnelSchlick(vec3(0.02), 1.0, saturate(dot(transmittedDir, windowNormal))).r : 0.0; + + // The whole sky is squeezed into the window, what isn't on screen comes from the sky probe + vec4 windowClip = globalData.pMatrix * globalData.vMatrix * vec4(transmittedDir, 0.0); + vec2 windowCoord = 0.5 * windowClip.xy / max(windowClip.w, 1e-4) + 0.5; + vec2 windowEdge = saturate(min(windowCoord, 1.0 - windowCoord) * 10.0); + float windowOnScreen = windowClip.w > 0.0 ? windowEdge.x * windowEdge.y : 0.0; + vec3 windowColor = mix(textureLod(specularProbe, transmittedDir, 0.0).rgb, + textureLod(refractionTexture, windowCoord, 0.0).rgb, windowOnScreen); + + vec3 skyRadiance = textureLod(diffuseProbe, vec3(0.0, 1.0, 0.0), 0.0).rgb; + vec3 sunScattering, ambientScattering; + GetWaterScattering(GetWaterExtinction(), reflect(eyeDir, -norm), 0.0, 1000.0, light, skyRadiance, + sunScattering, ambientScattering); + + color = mix(sunScattering + ambientScattering, windowColor, windowTransmission); + + // Right below the surface the outside stays visible through the waves + float cameraDepth = Uniforms.translation.y - globalData.cameraLocation.y; + float nearTransmission = nearSurfaceTransmission * (1.0 - smoothstep(0.0, nearSurfaceCameraDepth, cameraDepth)) * + (1.0 - smoothstep(0.0, nearSurfaceDistance, length(fPosition))); + color = mix(color, transmittedColor, nearTransmission * (1.0 - windowTransmission)); features.underWaterPixel = true; } else { @@ -241,7 +294,7 @@ void main() { #ifdef CLOUDS volumetricClouds = textureLod(volumetricCloudTexture, ndcCoord, 0.0); #endif - color = ApplyVolumetrics(Uniforms.fog, color, volumetricFog, volumetricClouds, + color = ApplyVolumetrics(color, volumetricFog, volumetricClouds, eyeDir, globalData.planetCenter.xyz, Uniforms.innerCloudRadius); } diff --git a/data/shader/ocean/queries.csh b/data/shader/ocean/queries.csh new file mode 100644 index 000000000..517858559 --- /dev/null +++ b/data/shader/ocean/queries.csh @@ -0,0 +1,48 @@ +layout (local_size_x = 64) in; + +#include +#include + +layout(std430, set = 3, binding = 14) readonly buffer Positions { + vec4 positions[]; +}; + +layout(std430, set = 3, binding = 18) writeonly buffer Results { + vec4 results[]; +}; + +layout (set = 3, binding = 17, std140) uniform QueryUniformBuffer { + int count; +} QueryUniforms; + +vec3 GetDisplacedPosition(vec3 position) { + + float perlinScale, shoreScale; + vec3 normalShoreWave; + // The physics shouldn't depend on the camera, so the waves don't fade out with the distance to it + return position + GetOceanDisplacement(position, 0.0, perlinScale, shoreScale, normalShoreWave); + +} + +void main() { + + int idx = int(gl_GlobalInvocationID.x); + if (idx >= QueryUniforms.count) + return; + + vec2 position = positions[idx].xz; + + // The waves move the surface sideways as well, search the undisplaced position that ends up here + vec3 originalPosition = vec3(position.x, Uniforms.translation.y, position.y); + for (int i = 0; i < 4; i++) { + vec3 displacedPosition = GetDisplacedPosition(originalPosition); + originalPosition.xz += position - displacedPosition.xz; + } + + vec3 displacedPosition = GetDisplacedPosition(originalPosition); + vec3 tangent = GetDisplacedPosition(originalPosition + vec3(0.1, 0.0, 0.0)) - displacedPosition; + vec3 bitangent = GetDisplacedPosition(originalPosition + vec3(0.0, 0.0, 0.1)) - displacedPosition; + + results[idx] = vec4(normalize(cross(bitangent, tangent)), displacedPosition.y); + +} diff --git a/data/shader/ocean/sharedUniforms.hsh b/data/shader/ocean/sharedUniforms.hsh index f70ffedec..77fb71ddf 100644 --- a/data/shader/ocean/sharedUniforms.hsh +++ b/data/shader/ocean/sharedUniforms.hsh @@ -6,7 +6,6 @@ layout (set = 3, binding = 11, std140) uniform UniformBuffer { Fog fog; vec4 waterBodyColor; - vec4 deepWaterBodyColor; vec4 scatterColor; vec4 translation; @@ -37,6 +36,11 @@ layout (set = 3, binding = 11, std140) uniform UniformBuffer { int N; int spectrumCount; float innerCloudRadius; + + float foamOffset; + float foamScale; + float foamSize; + float sunAngularRadius; } Uniforms; layout (set = 3, binding = 12, std140) uniform LightUniformBuffer { diff --git a/data/shader/ocean/shoreInteraction.hsh b/data/shader/ocean/shoreInteraction.hsh index 95a5f1c42..81eb18de7 100644 --- a/data/shader/ocean/shoreInteraction.hsh +++ b/data/shader/ocean/shoreInteraction.hsh @@ -1,33 +1,63 @@ #include #include <../common/utility.hsh> +#include <../common/random.hsh> layout(set = 3, binding = 9) uniform sampler2D terrainHeight; -vec3 CalculateGerstner(vec3 position) { +float ShoreValueNoise(vec2 position) { + + ivec2 cell = ivec2(floor(position)); + vec2 weight = fract(position); + weight = weight * weight * (3.0 - 2.0 * weight); + + float a = floatConstruct(hash(uvec2(cell))); + float b = floatConstruct(hash(uvec2(cell + ivec2(1, 0)))); + float c = floatConstruct(hash(uvec2(cell + ivec2(0, 1)))); + float d = floatConstruct(hash(uvec2(cell + ivec2(1, 1)))); + return mix(mix(a, b, weight.x), mix(c, d, weight.x), weight.y); + +} + +// Breaks the shore waves into irregular stretches that drift slowly, independent of the world axes +float ShoreModulation(vec3 position) { + + vec2 drift = vec2(0.031, 0.017) * globalData.time; + float noise = 0.65 * ShoreValueNoise(position.xz / 28.0 + drift) + 0.35 * ShoreValueNoise(position.xz / 9.0 - 1.7 * drift); + return smoothstep(0.45, 0.75, noise); + +} + +// Scale fades the shore wave out on the shore and in deep water +float GetShoreWavePhase(vec3 position, out float scale, out vec2 shoreGradient) { - vec2 terrainTex = (vec2(position.xz) - vec2(Uniforms.terrainTranslation.xz)) - / Uniforms.terrainSideLength; + vec2 terrainTex = (position.xz - Uniforms.terrainTranslation.xz) / Uniforms.terrainSideLength; + vec4 shore = textureLod(terrainHeight, terrainTex, 0.0); - float shoreDistance = textureLod(terrainHeight, terrainTex, 0.0).g; - vec2 shoreGradient = normalize(2.0 * textureLod(terrainHeight, terrainTex, 0.0).ba - 1.0); + float shoreDistance = shore.g; + shoreGradient = normalize(2.0 * shore.ba - 1.0); // Avoid scaling by water depth. Resolution artifacts become obvious. - float scale = clamp(1.0 - shoreDistance, 0.0, 1.0); - scale *= clamp(shoreDistance * 10.0, 0.0, 1.0); + scale = saturate(1.0 - shoreDistance) * saturate(shoreDistance * 10.0); - // Should be uniforms float waveLength = Uniforms.shoreWaveLength / 100.0; float speed = Uniforms.shoreWaveSpeed / 100.0; + return (shoreDistance + speed * globalData.time) / waveLength; - float w = 1.0 / waveLength; - float phi = speed * w; - float rad = w * shoreDistance + phi * globalData.time; +} + +vec3 CalculateGerstner(vec3 position) { + + float scale; + vec2 shoreGradient; + float rad = GetShoreWavePhase(position, scale, shoreGradient); - float modulation = saturate(sin(position.x / 20.0) + cos(position.z / 10.0)); - float distanceScale = saturate(1.0 - (distance(globalData.cameraLocation.xyz, position) - Uniforms.shoreWaveDistanceOffset) / Uniforms.shoreWaveDistanceScale); + if (scale * distanceScale <= 0.0) + return vec3(0.0); + + float modulation = ShoreModulation(position); float amplitude = 1.0 * Uniforms.shoreWaveAmplitude * scale * modulation * distanceScale; float steepness = 1.0 * Uniforms.shoreWaveSteepness * scale * modulation * distanceScale; @@ -44,22 +74,13 @@ vec3 CalculateGerstner(vec3 position) { vec2 CalculateShoreInteraction(vec3 position) { - vec2 terrainTex = (vec2(position.xz) - vec2(Uniforms.terrainTranslation.xz)) - / Uniforms.terrainSideLength; - float shoreDistance = textureLod(terrainHeight, terrainTex, 0.0).g; - - float scale = clamp(1.0 - shoreDistance, 0.0, 1.0); - scale *= clamp(shoreDistance * 10.0, 0.0, 1.0); - - // Should be uniforms - float waveLength = Uniforms.shoreWaveLength / 100.0; - float speed = Uniforms.shoreWaveSpeed / 100.0; - - float w = 1.0 / waveLength; - float phi = speed * w; - float rad = w * shoreDistance + phi * globalData.time; + float scale; + vec2 shoreGradient; + float rad = GetShoreWavePhase(position, scale, shoreGradient); + if (scale <= 0.3) + return vec2(0.0); - float modulation = saturate(sin(position.x / 20.0) + cos(position.z / 10.0)); + float modulation = ShoreModulation(position); // Move these calculations to the fragment shader float foamShoreWave = max(-cos(rad), 0.0) * 1.0 * max(scale - 0.3, 0.0) * modulation; diff --git a/data/shader/ocean/surface.hsh b/data/shader/ocean/surface.hsh new file mode 100644 index 000000000..08daa1092 --- /dev/null +++ b/data/shader/ocean/surface.hsh @@ -0,0 +1,71 @@ +// Surface detail which can only be evaluated in fragment shaders, used by the surface and the depth pass + +layout (set = 3, binding = 10) uniform sampler2D rippleTexture; + +// Roughness of the waves which are too small for the simulation, the larger ones add their slope variance +const float roughness = 0.07; +// Only part of the unresolved slopes is turned into roughness, which keeps some of the sparkle of the sun reflection +const float slopeVarianceScale = 0.25; + +void GetOceanGradientAndFold(vec2 texCoord, float dist, out float fold, out vec2 gradient, + out float jacobian, out float slopeVariance) { + + texCoord /= Uniforms.tiling; + + vec4 tilingFactors = Uniforms.spectrumTilingFactors; + vec4 fadeoutDistances = Uniforms.spectrumFadeoutDistances; + + vec4 fade = saturate((fadeoutDistances - vec4(dist)) / fadeDistances); + + // Each cascade contains a different band of waves, so they are added up + gradient = vec2(0.0); + jacobian = 1.0; + slopeVariance = 0.0; + + for (int i = 0; i < Uniforms.spectrumCount; i++) { + vec3 coord = vec3(texCoord / tilingFactors[i] + vec2(0.25 * float(i)), float(i)); + if (fade[i] > 0.0) { + vec4 data = texture(normalMap, coord); + gradient += fade[i] * data.rg; + jacobian -= fade[i] * data.a; + // Unresolved slopes roughen the surface, under magnification the filtering only adds grid artifacts + float mipLevel = textureQueryLod(normalMap, coord.xy).y; + float filteredVariance = max(0.0, data.b - dot(data.rg, data.rg)) * saturate(mipLevel); + slopeVariance += filteredVariance + (1.0 - sqr(fade[i])) * dot(data.rg, data.rg); + } + else { + // The smallest mip level is the average squared slope of the whole cascade + slopeVariance += textureLod(normalMap, coord, float(textureQueryLevels(normalMap) - 1)).b; + } + } + + fold = saturate((Uniforms.foamOffset - jacobian) * Uniforms.foamScale); + +} + +// Small ripples from the normal map on top of the simulated waves, they fade out at the shore +vec3 GetOceanRippleNormal(vec3 normal, vec2 position, float shoreScaling) { + +#ifdef RIPPLE_TEXTURE + vec3 tangent = normalize(vec3(1.0, -normal.x / normal.y, 0.0)); + vec3 bitangent = normalize(cross(tangent, normal)); + mat3 tbn = mat3(tangent, bitangent, normal); + + vec2 texCoord = 20.0 * position / Uniforms.tiling; + vec3 rippleNormal = normalize(2.0 * texture(rippleTexture, texCoord - vec2(globalData.time * 0.2), globalData.mipLodBias).rgb - 1.0); + rippleNormal += normalize(2.0 * texture(rippleTexture, texCoord * 0.5 + vec2(globalData.time * 0.05), globalData.mipLodBias).rgb - 1.0); + + float rippleScaling = clamp(1.0 - shoreScaling, 0.05, 0.1); + return normalize(mix(normal, normalize(tbn * rippleNormal), rippleScaling)); +#else + return normal; +#endif + +} + +float GetOceanAlpha(float slopeVariance) { + + // The slope variance of a surface roughly is the squared alpha of its microfacet distribution + return sqrt(sqr(sqr(roughness)) + slopeVarianceScale * slopeVariance); + +} diff --git a/data/shader/ocean/twiddleIndices.csh b/data/shader/ocean/twiddleIndices.csh deleted file mode 100644 index a69d72378..000000000 --- a/data/shader/ocean/twiddleIndices.csh +++ /dev/null @@ -1,44 +0,0 @@ -#include <../common/PI.hsh> -#include <../common/complex.hsh> - -layout (local_size_x = 1, local_size_y = 16) in; - -layout (set = 3, binding = 0, rg32f) writeonly uniform image2D twiddleIndicesTexture; - -// The first butterfly stage we use bit-reversed indices computed -// on the CPU. -layout (set = 3, binding = 1, std430) buffer indices { - int index[]; -} bitrevIndices; - -// Remember that this is executed into x direction just log_2(N) times. -void main() { - - vec2 coord = vec2(gl_GlobalInvocationID.xy); - - // Span of the butterfly operation at a given horizontal point - float span = floor(pow(2.0, coord.x)); - - bool topWing = mod(coord.y, pow(2.0, coord.x + 1.0)) < pow(2.0, coord.x); - - vec4 twiddleIndices; - - // For the first stage use the shader storage buffer - if (coord.x == 0.0) { - if (topWing) - twiddleIndices = vec4(bitrevIndices.index[int(coord.y)], - bitrevIndices.index[int(coord.y + 1.0)], 0.0, 0.0); - else - twiddleIndices = vec4(bitrevIndices.index[int(coord.y - 1.0)], - bitrevIndices.index[int(coord.y)], 0.0, 0.0); - } - else { - if (topWing) - twiddleIndices = vec4(coord.y, coord.y + span, 0.0, 0.0); - else - twiddleIndices = vec4(coord.y - span, coord.y, 0.0, 0.0); - } - - imageStore(twiddleIndicesTexture, ivec2(coord), twiddleIndices); - -} \ No newline at end of file diff --git a/data/shader/ocean/underwater.csh b/data/shader/ocean/underwater.csh index c414e48cc..a963b2f77 100644 --- a/data/shader/ocean/underwater.csh +++ b/data/shader/ocean/underwater.csh @@ -1,6 +1,6 @@ layout (local_size_x = 8, local_size_y = 8) in; -#define SHADOW_FILTER_VOGEL +#define SHADOW_FILTER_1x1 #include #include @@ -12,6 +12,11 @@ layout (local_size_x = 8, local_size_y = 8) in; #include <../common/utility.hsh> #include <../common/stencil.hsh> #include <../common/normalencode.hsh> +#include <../common/ign.hsh> + +#include + +layout(set = 1, binding = 12) uniform samplerCube diffuseProbe; layout (set = 3, binding = 4) uniform sampler2D refractionTexture; layout(set = 3, binding = 16) uniform sampler2D depthTexture; @@ -20,12 +25,61 @@ layout(set = 3, binding = 18) uniform sampler2D oceanDepthTexture; layout(set = 3, binding = 8) uniform sampler2DArrayShadow cascadeMaps; layout(set = 3, binding = 20, rgba16f) uniform image2D outputImage; +const int shaftSampleCount = 8; +const float shaftDistance = 40.0; + +// Caustic pattern at the surface, normalized to an average of one +float GetShaftPattern(vec2 position) { + + mat3 m = mat3(-2,-1,2, 3,-2,1, 1,2,2); + vec3 a = vec3(position * 0.25, globalData.time / 4.0) * m; + vec3 b = a * m * 0.4; + vec3 c = b * m * 0.3; + float pattern = min(min(length(0.5 - fract(a)), length(0.5 - fract(b))), length(0.5 - fract(c))); + return pattern * pattern * pattern / 0.06; + +} + +// Average visibility of the sun along the view ray: shadows and the light focused by the waves +float GetShaftVisibility(Light light, vec3 rayOrigin, vec3 rayDirection, vec3 viewRayDirection, float rayLength, + float waterHeight, vec3 lightDirection, float extinction, float downwellingAttenuation, float noise) { + + float marchLength = min(rayLength, shaftDistance); + float stepLength = marchLength / float(shaftSampleCount); + + float visibility = 0.0; + float weightSum = 0.0; + for (int i = 0; i < shaftSampleCount; i++) { + float t = (float(i) + noise) * stepLength; + vec3 position = rayOrigin + rayDirection * t; + float depth = max(waterHeight - position.y, 0.0); + + vec2 surfacePosition = position.xz - lightDirection.xz * depth / -lightDirection.y; + + // The shadow map follows the unrefracted light, so the shadow is taken where the refracted light enters + vec3 surfaceViewPosition = vec3(globalData.vMatrix * vec4(surfacePosition.x, waterHeight, surfacePosition.y, 1.0)); + float shadow = CalculateCascadedShadow(light.shadow, cascadeMaps, surfaceViewPosition, + vec3(0.0), vec3(0.0), 1.0); + + // Shafts build up below the surface and blur out deeper down + float shaftStrength = saturate(depth / 3.0) * exp(-depth / 20.0); + float shaft = mix(1.0, GetShaftPattern(surfacePosition), shaftStrength); + + // Samples which contribute more light count more + float weight = exp(-extinction * t - downwellingAttenuation * depth / -lightDirection.y); + visibility += weight * shadow * shaft; + weightSum += weight; + } + + return weightSum > 0.0 ? visibility / weightSum : 1.0; + +} void main() { ivec2 pixel = ivec2(gl_GlobalInvocationID); - if (pixel.x > imageSize(outputImage).x || - pixel.y > imageSize(outputImage).y) + if (pixel.x >= imageSize(outputImage).x || + pixel.y >= imageSize(outputImage).y) return; Light light = LightUniforms.light; @@ -35,17 +89,10 @@ void main() { float depth = textureLod(depthTexture, texCoord, 0.0).r; float oceanDepth = textureLod(oceanDepthTexture, texCoord, 0.0).r; - if (depth == 1.0 && oceanDepth == 1.0) - return; - vec3 viewSpacePos = ConvertDepthToViewSpace(depth, texCoord); - vec3 viewSpaceOceanPos = ConvertDepthToViewSpace(oceanDepth, texCoord); vec3 pixelPos = vec3(globalData.ivMatrix * vec4(viewSpacePos, 1.0)); - vec3 oceanPos = vec3(globalData.ivMatrix * vec4(viewSpaceOceanPos, 1.0)); vec3 nearPos = vec3(globalData.ivMatrix * vec4(ConvertDepthToViewSpace(0.0, texCoord), 1.0)); - float distanceToCamera = length(viewSpacePos); - int pixelsUnderWater = 0; int waterPixels = 0; for (int x = -1; x <= 1; x++) { @@ -66,41 +113,53 @@ void main() { vec3 normalShoreWave; vec3 displacement = GetOceanDisplacement(nearPos, 0.0, perlinScale, shoreScaling, normalShoreWave); - vec3 viewVector = pixelPos - nearPos; - - float waterDepth = Uniforms.translation.y - nearPos.y + displacement.y; - if (waterDepth < 0.0 && depth < oceanDepth && oceanDepth < 1.0 || + float waterHeight = Uniforms.translation.y + displacement.y; + float waterDepth = waterHeight - nearPos.y; + // With the camera under water every pixel is seen through water, also far surface pixels voted to be seen from above + if (waterDepth < 0.0 && (depth == 1.0 && oceanDepth == 1.0 || + depth < oceanDepth && oceanDepth < 1.0 || oceanDepth == 1.0 && pixelPos.y > Uniforms.translation.y || - (!underWaterPixel && features.waterPixel)) { + (!underWaterPixel && features.waterPixel))) { return; } - texCoord = (texCoord + vec2(0.05)) * 0.9; - - texCoord.x += sin(texCoord.y * 2.0 * PI * 5.0 + 5.0 * globalData.time) * 0.001 / depth; - texCoord.y += cos(texCoord.x * 2.0 * PI * 2.0 + 2.0 * globalData.time) * 0.001 / depth; + // Slight wobble of the image like seen through moving water + vec2 wobble = vec2(sin(texCoord.y * 2.0 * PI * 5.0 + 5.0 * globalData.time), + cos(texCoord.x * 2.0 * PI * 2.0 + 2.0 * globalData.time)) * 0.001; + texCoord = clamp(texCoord + wobble, vec2(0.0), vec2(1.0)); depth = textureLod(depthTexture, texCoord, 0.0).r; viewSpacePos = ConvertDepthToViewSpace(depth, texCoord); pixelPos = vec3(globalData.ivMatrix * vec4(viewSpacePos, 1.0)); - vec3 refractionColor = textureLod(refractionTexture, texCoord, 0.0).rgb; + vec3 surfaceColor = textureLod(refractionTexture, texCoord, 0.0).rgb; + + vec3 rayOrigin = globalData.cameraLocation.xyz; + vec3 rayDirection = normalize(pixelPos - rayOrigin); + float rayLength = depth < 1.0 ? distance(pixelPos, rayOrigin) : 1000.0; + // The water ends at the surface + if (rayDirection.y > 0.0) + rayLength = min(rayLength, max(waterHeight - rayOrigin.y, 0.0) / rayDirection.y + 1.0); - float NDotL = dot(-light.direction.xyz, vec3(0.0, 1.0, 0.0)); + float cameraDepth = max(waterHeight - rayOrigin.y, 0.0); + float pixelDepth = max(Uniforms.translation.y - pixelPos.y, 0.0); - viewVector = normalize(viewVector); + vec3 extinction = GetWaterExtinction(); + vec3 lightDirection = GetUnderwaterLightDirection(light.direction.xyz); - float waterOffset = max(0.0, (nearPos.y - Uniforms.translation.y) / max(viewVector.y, 0.0001)); - float waterViewDepth = distance(pixelPos, nearPos); + vec3 skyRadiance = textureLod(diffuseProbe, vec3(0.0, 1.0, 0.0), 0.0).rgb; + vec3 sunScattering, ambientScattering; + GetWaterScattering(extinction, rayDirection, cameraDepth, rayLength, light, skyRadiance, + sunScattering, ambientScattering); - // Calculate water color - vec3 depthFog = mix(Uniforms.deepWaterBodyColor.rgb, Uniforms.waterBodyColor.rgb, min(1.0 , exp(-waterViewDepth / 20.0))); - float diffuseFactor = Uniforms.waterColorIntensity.x + Uniforms.waterColorIntensity.y * max(0.0, NDotL); - vec3 waterColor = diffuseFactor * light.intensity * light.color.rgb * depthFog; + float noise = GetInterleavedGradientNoise(vec2(pixel)); + sunScattering *= GetShaftVisibility(light, rayOrigin, rayDirection, normalize(viewSpacePos), rayLength, + waterHeight, lightDirection, extinction.g, GetWaterDownwellingAttenuation().g, noise); - // Update refraction color based on water depth (exponential falloff) - refractionColor = mix(waterColor, refractionColor, min(1.0 , exp(-waterViewDepth / 5.0))); + // Surfaces were lit with the light above the water, it lost energy on the way down + surfaceColor *= GetWaterDownwellingTransmittance(light, pixelDepth); + vec3 color = surfaceColor * exp(-extinction * rayLength) + sunScattering + ambientScattering; - imageStore(outputImage, pixel, vec4(refractionColor, 0.0)); + imageStore(outputImage, pixel, vec4(color, 0.0)); -} \ No newline at end of file +} diff --git a/data/shader/ocean/waterBody.hsh b/data/shader/ocean/waterBody.hsh new file mode 100644 index 000000000..ae525ec4a --- /dev/null +++ b/data/shader/ocean/waterBody.hsh @@ -0,0 +1,93 @@ +#include <../common/PI.hsh> + +// Light inside the water body, seen from above and below the surface +// The absorption follows the water body color, red is gone after a few meters +const float waterAbsorptionScale = 0.12; +// Water scatters short wavelengths more +const vec3 waterScattering = vec3(0.03, 0.05, 0.1); +const float waterRefractiveIndex = 1.33; +// Skylight enters from all directions and travels a longer way down than the sun light +const float ambientDownwellingCosine = 0.75; +const float waterPhaseG = 0.6; + +vec3 GetWaterAbsorption() { + + return -log(clamp(Uniforms.waterBodyColor.rgb, vec3(0.01), vec3(1.0))) * waterAbsorptionScale; + +} + +vec3 GetWaterExtinction() { + + return GetWaterAbsorption() + waterScattering; + +} + +// Most light is scattered forward and keeps going down, only the light scattered back is lost on the way +vec3 GetWaterDownwellingAttenuation() { + + return GetWaterAbsorption() + 0.25 * waterScattering; + +} + +// Direction of the sun light after entering the water +vec3 GetUnderwaterLightDirection(vec3 lightDirection) { + + vec3 direction = refract(normalize(lightDirection), vec3(0.0, 1.0, 0.0), 1.0 / waterRefractiveIndex); + return dot(direction, direction) > 0.0 ? direction : vec3(0.0, -1.0, 0.0); + +} + +float GetUnderwaterLightCosine(vec3 lightDirection) { + + return max(-GetUnderwaterLightDirection(lightDirection).y, 0.05); + +} + +// Surfaces under water are lit with the light above the water, this is what is left of it at a depth +vec3 GetWaterDownwellingTransmittance(Light light, float depth) { + + return exp(-GetWaterDownwellingAttenuation() * depth / GetUnderwaterLightCosine(light.direction.xyz)); + +} + +float WaterPhase(float cosTheta) { + + float g = waterPhaseG; + float henyeyGreenstein = (1.0 - g * g) / (4.0 * PI * pow(1.0 + g * g - 2.0 * g * cosTheta, 1.5)); + return mix(1.0 / (4.0 * PI), henyeyGreenstein, 0.7); + +} + +// Integral of the light scattered towards the viewer along a ray starting at a depth below the surface, +// where the light coming from above is attenuated by the way down with the given cosine +vec3 IntegrateWaterScattering(vec3 extinction, float startDepth, float rayDirectionY, float lightCosine, float rayLength) { + + vec3 attenuation = GetWaterDownwellingAttenuation() / lightCosine; + vec3 rate = extinction - attenuation * rayDirectionY; + vec3 integral = mix(vec3(rayLength), (1.0 - exp(-rate * rayLength)) / rate, greaterThan(abs(rate), vec3(1e-4))); + return exp(-attenuation * startDepth) * integral; + +} + +// Light scattered towards the viewer, without sun shadows +void GetWaterScattering(vec3 extinction, vec3 rayDirection, float startDepth, float rayLength, Light light, + vec3 skyRadiance, out vec3 sunScattering, out vec3 ambientScattering) { + + vec3 lightDirection = GetUnderwaterLightDirection(light.direction.xyz); + float lightCosine = GetUnderwaterLightCosine(light.direction.xyz); + // Fades out the sun below the horizon, then only the sky lights the water + float sunVisibility = saturate(-light.direction.y * 10.0); + + // Light scattered several times, approximated for an infinite medium + vec3 absorption = extinction - waterScattering; + vec3 scattering = waterScattering / max(absorption / extinction, vec3(0.2)); + + vec3 sunLight = sunVisibility * light.intensity * light.color.rgb * WaterPhase(dot(rayDirection, -lightDirection)); + sunScattering = Uniforms.waterColorIntensity.y * scattering * sunLight * + IntegrateWaterScattering(extinction, startDepth, rayDirection.y, lightCosine, rayLength); + + // Only the upper hemisphere is lit by the sky + ambientScattering = Uniforms.waterColorIntensity.x * scattering * 0.5 * skyRadiance * + IntegrateWaterScattering(extinction, startDepth, rayDirection.y, ambientDownwellingCosine, rayLength); + +} diff --git a/data/shader/pathtracer/atrous.csh b/data/shader/pathtracer/atrous.csh new file mode 100644 index 000000000..2fe4d44cb --- /dev/null +++ b/data/shader/pathtracer/atrous.csh @@ -0,0 +1,245 @@ +#include <../common/utility.hsh> +#include <../common/convert.hsh> +#include <../common/flatten.hsh> +#include <../common/normalencode.hsh> + +#include <../common/denoiser.hsh> + +layout (local_size_x = 16, local_size_y = 16) in; + +layout(set = 3, binding = 0, rgba16f) writeonly uniform image2D outputImage; +layout(set = 3, binding = 1) uniform sampler2D inputTexture; +layout(set = 3, binding = 2) uniform sampler2D depthTexture; +layout(set = 3, binding = 3) uniform sampler2D normalTexture; +layout(set = 3, binding = 4) uniform usampler2D materialIdxTexture; +#ifdef REMODULATE +layout(set = 3, binding = 5) uniform sampler2D albedoTexture; +layout(set = 3, binding = 6) uniform sampler2D emissionTexture; +#endif + +#ifdef STEP_SIZE1 +const int kernelRadius = 2; +#endif +#ifdef STEP_SIZE2 +const int kernelRadius = 4; +#endif +#ifdef STEP_SIZE4 +const int kernelRadius = 8; +#endif + +const int stepSize = kernelRadius / 2; + +const uint sharedDataSize = (gl_WorkGroupSize.x + 2 * kernelRadius) * (gl_WorkGroupSize.y + 2 * kernelRadius); +const ivec2 unflattenedSharedDataSize = ivec2(gl_WorkGroupSize) + 2 * kernelRadius; + +struct PixelData { + vec4 color; + vec3 normal; + uint materialIdx; + float depth; +}; + +struct PackedPixelData { + // Contains 16 bit color, variance and normal + uvec4 data; +}; + +// Separate arrays, a struct with them would be padded to 32 bytes and exceed 32 KB of shared memory on some devices +shared PackedPixelData pixelData[sharedDataSize]; +shared uint pixelMaterialIdx[sharedDataSize]; +shared float pixelDepth[sharedDataSize]; + +layout(push_constant) uniform constants { + float strength; +} pushConstants; + +const float kernelWeights[3] = { 1.0, 2.0 / 3.0, 1.0 / 6.0 }; + +PackedPixelData PackPixelData(PixelData data) { + PackedPixelData compressed; + + compressed.data.x = packHalf2x16(data.color.rg); + compressed.data.y = packHalf2x16(data.color.ba); + compressed.data.z = packHalf2x16(data.normal.xy); + compressed.data.w = packHalf2x16(vec2(data.normal.z, 0.0)); + + return compressed; +} + +PixelData UnpackPixelData(PackedPixelData compressed) { + PixelData data; + + data.color.rg = unpackHalf2x16(compressed.data.x); + data.color.ba = unpackHalf2x16(compressed.data.y); + data.normal.xy = unpackHalf2x16(compressed.data.z); + vec2 temp = unpackHalf2x16(compressed.data.w); + data.normal.z = temp.x; + + return data; +} + +void LoadGroupSharedData() { + + ivec2 resolution = imageSize(outputImage); + ivec2 workGroupOffset = ivec2(gl_WorkGroupID) * ivec2(gl_WorkGroupSize) - ivec2(kernelRadius); + + uint workGroupSize = gl_WorkGroupSize.x * gl_WorkGroupSize.y; + for(uint i = gl_LocalInvocationIndex; i < sharedDataSize; i += workGroupSize) { + ivec2 localOffset = Unflatten2D(int(i), unflattenedSharedDataSize); + ivec2 texel = localOffset + workGroupOffset; + + texel = clamp(texel, ivec2(0), ivec2(resolution) - ivec2(1)); + + PixelData data; + + data.color = texelFetch(inputTexture, texel, 0); + + // Linear depth, zero marks the sky + float depth = texelFetch(depthTexture, texel, 0).r; + data.depth = depth >= 1.0 ? 0.0 : ConvertDepthToViewSpaceDepth(depth); + + data.materialIdx = texelFetch(materialIdxTexture, texel, 0).r; + + // The path tracer writes world space normals + data.normal = DecodeNormal(texelFetch(normalTexture, texel, 0).rg); + + pixelData[i] = PackPixelData(data); + pixelMaterialIdx[i] = data.materialIdx; + pixelDepth[i] = data.depth; + } + + barrier(); + +} + +PixelData GetPixel(ivec2 pixelOffset) { + + ivec2 pixel = ivec2(gl_LocalInvocationID) + ivec2(kernelRadius); + int sharedMemoryIdx = Flatten2D(pixel + pixelOffset, unflattenedSharedDataSize); + PixelData data = UnpackPixelData(pixelData[sharedMemoryIdx]); + data.materialIdx = pixelMaterialIdx[sharedMemoryIdx]; + data.depth = pixelDepth[sharedMemoryIdx]; + return data; + +} + +float GetFilteredVariance() { + + float variance = 0.0; + const float weights[2][2] = + { + { 1.0 / 4.0, 1.0 / 8.0 }, + { 1.0 / 8.0, 1.0 / 16.0 } + }; + + const int radius = 1; + for (int x = -radius; x <= radius; x++) { + for (int y = -radius; y <= radius; y++) { + PixelData samplePixelData = GetPixel(ivec2(x, y)); + + float weight = weights[abs(x)][abs(y)]; + float sampleVariance = samplePixelData.color.a; + variance += weight * sampleVariance; + } + } + + return variance; + +} + +vec4 Filter(ivec2 pixel, ivec2 resolution, PixelData centerPixelData) { + + vec2 texCoord = (vec2(pixel) + 0.5) / vec2(resolution); + vec2 texelSize = 1.0 / vec2(resolution); + + vec4 centerColor = centerPixelData.color; + vec3 centerNormal = centerPixelData.normal; + uint centerMaterialIdx = centerPixelData.materialIdx; + + vec3 viewRay = GetViewRay(texCoord); + vec3 viewRayDx = GetViewRay(texCoord + vec2(texelSize.x, 0.0)) - viewRay; + vec3 viewRayDy = GetViewRay(texCoord + vec2(0.0, texelSize.y)) - viewRay; + vec3 centerPosition = viewRay * centerPixelData.depth; + vec3 centerViewNormal = normalize(mat3(globalData.vMatrix) * centerNormal); + + float centerLuminance = Luma(centerColor.rgb); + + vec4 outputColor = centerColor; + float totalWeight = 1.0; + + float variance = GetFilteredVariance(); + float stdDeviation = sqrt(max(0.0, variance)); + + vec3 viewDir = normalize(centerPosition); + float NdotV = abs(dot(viewDir, centerViewNormal)); + float depthPhi = max(32.0, NdotV * 128.0); + + // All weights of a tap go into one exponent, the terms that don't depend on the tap are computed once. + // The distance to the surface plane is affine in the offset since the view ray is + const float log2e = 1.442695; + float planeRay = dot(viewRay, centerViewNormal); + float planeRayDx = dot(viewRayDx, centerViewNormal); + float planeRayDy = dot(viewRayDy, centerViewNormal); + float planeOffset = dot(centerPosition, centerViewNormal); + float planeScale = depthPhi * log2e / abs(centerPosition.z); + float luminanceScale = log2e / (stdDeviation * pushConstants.strength + 1e-10); + const float normalPhi = 128.0; + + const int radius = 2; + for (int x = -radius; x <= radius; x++) { + for (int y = -radius; y <= radius; y++) { + ivec2 offset = ivec2(x, y) * stepSize; + ivec2 samplePixel = pixel + offset; + + if (samplePixel.x >= resolution.x || samplePixel.y >= resolution.y || + samplePixel.x < 0 || samplePixel.y < 0 + || (x == 0 && y == 0)) + continue; + + PixelData samplePixelData = GetPixel(offset); + + if (samplePixelData.depth == 0.0 || samplePixelData.materialIdx != centerMaterialIdx) + continue; + + vec4 sampleColor = samplePixelData.color; + + // The distance to the surface plane stays stable at grazing angles, unlike the depth + float planeDistance = samplePixelData.depth * (planeRay + float(offset.x) * planeRayDx + + float(offset.y) * planeRayDy) - planeOffset; + float normalDot = max(dot(centerNormal, samplePixelData.normal), 1e-6); + + float exponent = abs(centerLuminance - Luma(sampleColor.rgb)) * luminanceScale + + abs(planeDistance) * planeScale - normalPhi * log2(normalDot); + float weight = kernelWeights[abs(x)] * kernelWeights[abs(y)] * exp2(-exponent); + + totalWeight += weight; + outputColor += vec4(vec3(weight), weight * weight) * sampleColor; + } + } + + return outputColor / vec4(vec3(totalWeight), totalWeight * totalWeight); + +} + +void main() { + + LoadGroupSharedData(); + + ivec2 pixel = ivec2(gl_GlobalInvocationID); + ivec2 resolution = imageSize(outputImage); + if (pixel.x >= resolution.x || pixel.y >= resolution.y) + return; + + PixelData centerPixelData = GetPixel(ivec2(0)); + vec4 outputColor = centerPixelData.depth == 0.0 ? texelFetch(inputTexture, pixel, 0) : + Filter(pixel, resolution, centerPixelData); + +#ifdef REMODULATE + vec3 albedo = texelFetch(albedoTexture, pixel, 0).rgb; + vec3 emission = texelFetch(emissionTexture, pixel, 0).rgb; + outputColor = vec4(min(outputColor.rgb * albedo + emission, vec3(65000.0)), 1.0); +#endif + + imageStore(outputImage, pixel, outputColor); + +} diff --git a/data/shader/pathtracer/rayHit.csh b/data/shader/pathtracer/rayHit.csh index 28f182454..19ad55fd8 100644 --- a/data/shader/pathtracer/rayHit.csh +++ b/data/shader/pathtracer/rayHit.csh @@ -13,8 +13,11 @@ #include <../brdf/brdfSample.hsh> #include <../brdf/importanceSample.hsh> #include <../brdf/surface.hsh> +#include <../clouds/shadow.hsh> +#ifndef RAY_TRACING_PIPELINE layout (local_size_x = 32) in; +#endif #ifdef REALTIME layout (set = 3, binding = 1, r32ui) uniform uimage2DArray frameAccumImage; @@ -23,10 +26,15 @@ layout (set = 3, binding = 6, r32f) writeonly uniform image2D depthImage; layout (set = 3, binding = 7, rg16f) writeonly uniform image2D normalImage; layout (set = 3, binding = 8, r16ui) writeonly uniform uimage2D materialIdxImage; layout (set = 3, binding = 9, rgba8) writeonly uniform image2D albedoImage; +layout (set = 3, binding = 10, rgba16f) writeonly uniform image2D emissionImage; #else layout (set = 3, binding = 1, rgba8) writeonly uniform image2D outputImage; #endif +#ifdef CLOUD_SHADOWS +layout(set = 3, binding = 11) uniform sampler2D cloudMap; +#endif + /* Except for image variables qualified with the format qualifiers r32f, r32i, and r32ui, image variables must specify either memory qualifier readonly or the memory qualifier writeonly. @@ -41,22 +49,25 @@ layout(set = 3, binding = 4) uniform UniformBuffer { int sampleCount; int bounceCount; float seed; - float exposure; int samplesPerFrame; float maxRadiance; } Uniforms; const float gamma = 1.0 / 2.2; +const float minAlbedo = 0.02; Surface EvaluateBounce(inout Ray ray, inout RayPayload payload); vec3 EvaluateDirectLight(inout Surface surface); void EvaluateIndirectLight(inout Surface surface, inout Ray ray, inout RayPayload payload); +vec3 RefractThrough(Surface surface, vec3 direction, float raySeed, inout float seed); float CheckVisibility(Surface surface, float lightDistance); +vec3 GetDemodulationAlbedo(Surface surface); void main() { if (IsRayInvocationValid()) { Ray ray = ReadRay(); + TraceBufferedRay(ray); RayPayload payload; payload.radiance = vec3(0.0); @@ -82,6 +93,8 @@ void main() { vec3 position; uint materialId; vec3 geometryNormal; + vec3 albedo; + vec3 emission; if (ray.hitID >= 0) { instance = bvhInstances[nonuniformEXT(ray.hitInstanceID)]; lastMatrix = mat4(transpose(instanceLastMatrices[nonuniformEXT(ray.hitInstanceID)])); @@ -89,6 +102,9 @@ void main() { position = surface.P; materialId = surface.material.ID; geometryNormal = surface.geometryNormal; + albedo = GetDemodulationAlbedo(surface); + emission = surface.material.blendMode == blendModeMultiply ? vec3(0.0) : surface.material.emissiveColor * + (surface.material.blendMode == blendModeAdditive ? surface.material.opacity : 1.0); } else { instance.inverseMatrix = mat3x4(1.0); @@ -96,6 +112,8 @@ void main() { position = ray.origin + ray.direction * 100.0; materialId = 65535; geometryNormal = vec3(1.0, 0.0, 0.0); + albedo = vec3(1.0); + emission = vec3(0.0); } // As a reminder: The current inverse matrix is also transposed @@ -114,7 +132,9 @@ void main() { imageStore(depthImage, pixel, vec4(ray.hitID >= 0 ? projPositionCurrent.z / projPositionCurrent.w : INF, 0.0, 0.0, 0.0)); imageStore(materialIdxImage, pixel, uvec4(materialId, 0.0, 0.0, 0.0)); - imageStore(normalImage, pixel, vec4(EncodeNormal(geometryNormal), 0.0, 0.0)); + imageStore(normalImage, pixel, vec4(EncodeNormal(geometryNormal), 0.0, 0.0)); + imageStore(albedoImage, pixel, vec4(albedo, 1.0)); + imageStore(emissionImage, pixel, vec4(min(emission, vec3(65000.0)), 1.0)); } #endif @@ -126,7 +146,8 @@ void main() { accumColor += vec4(payload.radiance, 1.0); imageStore(outAccumImage, pixel, accumColor); - vec3 color = accumColor.rgb * Uniforms.exposure / float(Uniforms.sampleCount + 1); + // The pre-exposure of the radiance is the exposure + vec3 color = accumColor.rgb / float(Uniforms.sampleCount + 1); color = vec3(1.0) - exp(-color); //color = color / (vec3(1.0) + color); @@ -176,10 +197,35 @@ Surface EvaluateBounce(inout Ray ray, inout RayPayload payload) { int lod = int(ray.hitDistance / 30.0); lod = 0; - // Unpack the compressed triangle and extract surface parameters - Instance instance = GetInstance(ray); - Triangle tri = GetTriangle(ray, instance); - surface = GetSurfaceParameters(instance, tri, ray, true, lod); + bool backfaceHit; + surface = GetHitSurface(ray, true, backfaceHit, lod); + + // Additive surfaces add their light, multiplied ones tint the light behind them, the ray continues unchanged + if (surface.material.blendMode == blendModeAdditive || surface.material.blendMode == blendModeMultiply) { + if (surface.material.blendMode == blendModeAdditive) { + vec3 emission = surface.material.emissiveColor * surface.material.opacity; +#ifdef REALTIME + // The primary emission is added after the denoiser + emission = Uniforms.bounceCount > 0 ? emission : vec3(0.0); +#endif + payload.radiance += payload.throughput * (emission + EvaluateDirectLight(surface)); + } + else { + payload.throughput *= mix(vec3(1.0), surface.material.baseColor, surface.material.opacity); + } + ray.origin = surface.P + ray.direction * EPSILON; + return surface; + } + + // Alpha blended surfaces which aren't two sided cover the light behind them once like in the rasterizer, their back + // faces are only where the rays leave them + if (backfaceHit && surface.material.blendMode == blendModeAlpha) { + surface.material.opacity = 0.0; + float curSeed = Uniforms.seed; + ray.direction = RefractThrough(surface, ray.direction, float(ray.ID), curSeed); + ray.origin = surface.P + ray.direction * EPSILON; + return surface; + } // If we hit an emissive surface we need to terminate the ray #ifndef REALTIME @@ -188,12 +234,13 @@ Surface EvaluateBounce(inout Ray ray, inout RayPayload payload) { payload.radiance += surface.material.emissiveColor; } #else - payload.radiance += payload.throughput * surface.material.emissiveColor; + // The primary emission is added after the denoiser + if (Uniforms.bounceCount > 0) + payload.radiance += payload.throughput * surface.material.emissiveColor; #endif - // Evaluate direct and indirect light - vec3 radiance = payload.throughput * saturate(surface.material.opacity) - * EvaluateDirectLight(surface); + // Evaluate direct and indirect light, the direct light is weighted by the opacity + vec3 radiance = payload.throughput * EvaluateDirectLight(surface); // Clamp indirect radiance // This has to be used cautiously and might be the reason @@ -215,13 +262,27 @@ Surface EvaluateBounce(inout Ray ray, inout RayPayload payload) { } +vec3 GetDemodulationAlbedo(Surface surface) { + + // Additive and multiplied surfaces only change the light behind them + if (surface.material.blendMode == blendModeAdditive || surface.material.blendMode == blendModeMultiply) + return vec3(1.0); + + vec3 diffuse = (1.0 - surface.material.metalness) * surface.material.baseColor; + vec3 specular = EvaluateIndirectSpecularBRDF(surface); + vec3 albedo = mix(vec3(1.0), diffuse + specular, saturate(surface.material.opacity)); + // Quantized like the albedo image + return round(max(saturate(albedo), vec3(minAlbedo)) * 255.0) / 255.0; + +} + vec3 EvaluateDirectLight(inout Surface surface) { if (GetLightCount() == 0) return vec3(0.0); float curSeed = Uniforms.seed; - float raySeed = float(gl_GlobalInvocationID.x); + float raySeed = float(INVOCATION_ID.x); float lightPdf; Light light = GetLight(surface, raySeed, curSeed, lightPdf); @@ -232,10 +293,17 @@ vec3 EvaluateDirectLight(inout Surface surface) { if (lightPdf <= 0.0) return vec3(0.0); vec3 transmissionColor = GetTransmissionColor(surface.material); - // Front side reflection, transmission is evaluated separately below - vec3 reflectance = EvaluateDiffuseBRDF(surface) + EvaluateSpecularBRDF(surface); - reflectance *= surface.material.opacity; + // Front side reflection, transmission is evaluated separately below. Alpha blended surfaces like glass reflect + // regardless of their opacity + float specularOpacity = surface.material.blendMode == blendModeAlpha ? 1.0 : surface.material.opacity; + vec3 reflectance = EvaluateDiffuseBRDF(surface) * surface.material.opacity + + EvaluateSpecularBRDF(surface) * specularOpacity; vec3 radiance = light.radiance * solidAngle; +#ifdef CLOUD_SHADOWS + if (light.type == uint(DIRECTIONAL_LIGHT)) + radiance *= CalculateCloudShadow(vec3(globalData.vMatrix * vec4(surface.P, 1.0)), cloudShadowUniforms.cloudShadow, + cloudMap); +#endif float visibility = light.castShadow ? CheckVisibility(surface, lightDistance) : 1.0; vec3 direct = reflectance * radiance * surface.NdotL * visibility / lightPdf; @@ -282,7 +350,8 @@ void EvaluateIndirectLight(inout Surface surface, inout Ray ray, inout RayPayloa if (rnd < specChance) { brdfSample = SampleSpecularBRDF(surface, vec2(u0, u1)); - brdfSample.reflectance *= opacity; + // Alpha blended surfaces like glass reflect regardless of their opacity + brdfSample.reflectance *= mat.blendMode == blendModeAlpha ? 1.0 : opacity; brdfSample.pdf *= specChance; cosine = surface.NdotL; } @@ -310,7 +379,7 @@ void EvaluateIndirectLight(inout Surface surface, inout Ray ray, inout RayPayloa brdfSample.pdf *= (1.0 - passThroughChance); } else { - brdfSample.L = ray.direction; + brdfSample.L = RefractThrough(surface, ray.direction, raySeed, curSeed); brdfSample.pdf = passThroughChance; brdfSample.reflectance = vec3(1.0 - opacity); transmitted = true; @@ -332,9 +401,10 @@ void EvaluateIndirectLight(inout Surface surface, inout Ray ray, inout RayPayloa payload.throughput = vec3(0.0); return; } - // Offset the origin to the side the ray continues on + // Offset the origin to the side the ray continues on, rays passing through may also leave a surface or be reflected + float passedSide = dot(ray.direction, surface.geometryNormal) > 0.0 ? 1.0 : -1.0; ray.origin = transmitted && !passedThrough ? surface.P - surface.geometryNormal * EPSILON : - passedThrough ? surface.P - surface.N * EPSILON : surface.P + surface.V * EPSILON; + passedThrough ? surface.P + surface.geometryNormal * (passedSide * EPSILON) : surface.P + surface.V * EPSILON; payload.throughput *= mat.ao; // Russain roulette, terminate rays with a chance of one percent @@ -359,10 +429,28 @@ float CheckVisibility(Surface surface, float lightDistance) { ray.direction = surface.L; // For transmitted light N is already flipped to the back side ray.origin = surface.P + surface.N * EPSILON; - return HitAnyTransparency(ray, INSTANCE_MASK_SHADOW, 0.0, lightDistance - 2.0 * EPSILON); + return HitAnyTransparency(ray, INSTANCE_MASK_SHADOW_TRANSPARENCY, 0.0, lightDistance - 2.0 * EPSILON); } else { return 0.0; } } + +// Refracting surfaces bend the ray where it enters and leaves them, it's reflected beyond the critical angle. Rough ones +// refract it through a normal of their microfacets +vec3 RefractThrough(Surface surface, vec3 direction, float raySeed, inout float seed) { + + if (surface.material.refractiveIndex == 1.0) + return direction; + + vec3 facingNormal = dot(direction, surface.N) < 0.0 ? surface.N : -surface.N; + if (surface.material.roughness > 0.0) { + vec2 u = vec2(random(raySeed, seed), random(raySeed, seed)); + vec3 microfacetNormal = ImportanceSampleGGX(u, facingNormal, sqr(surface.material.roughness)); + facingNormal = dot(microfacetNormal, direction) < 0.0 ? microfacetNormal : facingNormal; + } + vec3 refracted = refract(direction, facingNormal, 1.0 / surface.material.refractiveIndex); + return dot(refracted, refracted) > 0.0 ? refracted : reflect(direction, facingNormal); + +} diff --git a/data/shader/pathtracer/rayHit.rgen b/data/shader/pathtracer/rayHit.rgen new file mode 100644 index 000000000..6ceb692e2 --- /dev/null +++ b/data/shader/pathtracer/rayHit.rgen @@ -0,0 +1,7 @@ +// Traces and shades a bounce of the path tracer as the ray generation stage of a ray tracing pipeline, see bvh.hsh +#extension GL_EXT_ray_tracing : require +#extension GL_EXT_shader_invocation_reorder : require + +#define RAY_TRACING_PIPELINE + +#include diff --git a/data/shader/pathtracer/temporal.csh b/data/shader/pathtracer/temporal.csh index 560f9fcc6..a7bc77b80 100644 --- a/data/shader/pathtracer/temporal.csh +++ b/data/shader/pathtracer/temporal.csh @@ -8,6 +8,7 @@ #include <../common/random.hsh> #include <../common/normalencode.hsh> #include <../common/edgePreserving.hsh> +#include <../common/denoiser.hsh> layout (local_size_x = 16, local_size_y = 16) in; @@ -20,18 +21,21 @@ layout (set = 3, binding = 4) uniform sampler2D velocityTexture; layout (set = 3, binding = 5) uniform sampler2D depthTexture; layout (set = 3, binding = 6) uniform sampler2D normalTexture; layout (set = 3, binding = 7) uniform usampler2D materialIdxTexture; +layout (set = 3, binding = 8) uniform sampler2D albedoTexture; layout(set = 3, binding = 9) uniform sampler2D historyDepthTexture; layout(set = 3, binding = 10) uniform sampler2D historyNormalTexture; layout(set = 3, binding = 11) uniform usampler2D historyMaterialIdxTexture; +layout(set = 3, binding = 12, rg32f) writeonly uniform image2D momentsImage; +layout(set = 3, binding = 13) uniform sampler2D historyMomentsTexture; layout(push_constant) uniform constants { float historyClipMax; float currentClipFactor; float maxHistoryLength; - float exposure; int samplesPerFrame; float maxRadiance; + int resetHistory; } pushConstants; vec2 invResolution = 1.0 / vec2(imageSize(outAccumImage)); @@ -63,13 +67,6 @@ const ivec2 pixelOffsets[4] = ivec2[4]( ivec2(1, 1) ); -float Luma(vec3 color) { - - const vec3 luma = vec3(0.299, 0.587, 0.114); - return dot(color, luma); - -} - vec3 FetchTexel(ivec2 texel) { vec3 color; @@ -90,7 +87,7 @@ vec3 FetchTexel(ivec2 texel) { float(pushConstants.samplesPerFrame) * pushConstants.maxRadiance; } - return max(color, 0.0); + return max(color, 0.0) / texelFetch(albedoTexture, texel, 0).rgb; } @@ -151,26 +148,6 @@ ivec2 FindNearest3x3(ivec2 pixel) { } -float ClipBoundingBox(vec3 boxMin, vec3 boxMax, vec3 history, vec3 current) { - - vec3 origin = history; - vec3 dir = current - history; - - // Make sure dir isn't zero - dir.x = abs(dir.x) < (1.0 / 32767.0) ? (1.0 / 32767.0) : dir.x; - dir.y = abs(dir.y) < (1.0 / 32767.0) ? (1.0 / 32767.0) : dir.y; - dir.z = abs(dir.z) < (1.0 / 32767.0) ? (1.0 / 32767.0) : dir.z; - - vec3 invDir = 1.0 / dir; - - vec3 t0 = (boxMin - origin) * invDir; - vec3 t1 = (boxMax - origin) * invDir; - - vec3 intersect = min(t0, t1); - return max(intersect.x, max(intersect.y, intersect.z)); - -} - float IsHistoryPixelValid(ivec2 pixel, float linearDepth, uint materialIdx, vec3 normal) { float confidence = 1.0; @@ -217,13 +194,13 @@ bool SampleHistory(ivec2 pixel, vec2 historyPixel, vec2 velocity, out vec4 histo if (IsHistoryPixelValid(offsetPixel, linearDepth, materialIdx, normal) > 0.0) { totalWeight += weights[i]; history += texelFetch(inAccumImage, offsetPixel, 0) * weights[i]; - //historyMoments += texelFetch(historyMomentsTexture, offsetPixel, 0) * weights[i]; + historyMoments += texelFetch(historyMomentsTexture, offsetPixel, 0) * weights[i]; } } if (totalWeight > 0.0) { history /= totalWeight; - //historyMoments /= totalWeight; + historyMoments /= totalWeight; return true; } @@ -239,7 +216,7 @@ bool SampleHistory(ivec2 pixel, vec2 historyPixel, vec2 velocity, out vec4 histo if (IsHistoryPixelValid(offsetPixel, linearDepth, materialIdx, normal) > 0.0) { totalWeight += 1.0; history += texelFetch(inAccumImage, offsetPixel, 0); - //historyMoments += texelFetch(historyMomentsTexture, offsetPixel, 0) * weights[i]; + historyMoments += texelFetch(historyMomentsTexture, offsetPixel, 0); } } @@ -369,8 +346,8 @@ void main() { LoadGroupSharedData(); ivec2 pixel = ivec2(gl_GlobalInvocationID); - if (pixel.x > imageSize(outAccumImage).x || - pixel.y > imageSize(outAccumImage).y) + if (pixel.x >= imageSize(outAccumImage).x || + pixel.y >= imageSize(outAccumImage).y) return; uint materialIdx = texelFetch(materialIdxTexture, pixel, 0).r; @@ -381,6 +358,7 @@ void main() { ComputeVarianceMinMax(mean, std); vec3 currentRadiance = FetchTexel(pixel); + float currentLuma = Luma(currentRadiance); vec2 velocity = texelFetch(velocityTexture, pixel, 0).rg; @@ -421,11 +399,11 @@ void main() { currentRadiance = YCoCgToRGB(currentRadiance); float temporalWeight = (pushConstants.maxHistoryLength - 1.0) / pushConstants.maxHistoryLength; - float factor = mix(0.0, temporalWeight - maxVelocity, 1.0 - adjClipBlend); + float factor = mix(0.0, temporalWeight, 1.0 - adjClipBlend); factor = (historyUV.x < 0.0 || historyUV.y < 0.0 || historyUV.x > 1.0 || historyUV.y > 1.0) ? 0.0 : factor; - if (factor < 0.1 || !valid) { + if (factor < 0.1 || !valid || pushConstants.resetHistory > 0) { historyLength = 0.0; } @@ -444,8 +422,17 @@ void main() { vec3 resolve = mix(currentRadiance, historyRadiance, factor); + vec2 momentsResolve = mix(vec2(currentLuma, sqr(currentLuma)), historyMoments.rg, factor); + float accumulatedFrames = GetAccumulatedFrames(factor, historyLength); + + // Short histories use the variance of the neighbourhood, the resolve has the variance of the mean + float variance = max(momentsResolve.g - sqr(momentsResolve.r), 0.0); + variance = accumulatedFrames < 4.0 ? max(variance, sqr(std.x)) : variance; + variance /= accumulatedFrames; + imageStore(outAccumImage, pixel, vec4(resolve, historyLength + 1.0)); - imageStore(outputImage, pixel, vec4(resolve, 1.0)); + imageStore(momentsImage, pixel, vec4(momentsResolve, 0.0, 0.0)); + imageStore(outputImage, pixel, vec4(min(resolve, vec3(65000.0)), min(variance, 65000.0))); //imageStore(outAccumImage, pixel, vec4(vec3(valid ? 1.0 : 0.0), historyLength + 1.0)); //imageStore(outAccumImage, pixel, vec4(vec3(historyLength / 10.0), historyLength + 1.0)); diff --git a/data/shader/postprocessing.fsh b/data/shader/postprocessing.fsh index 43bf15ae6..bfe713f58 100644 --- a/data/shader/postprocessing.fsh +++ b/data/shader/postprocessing.fsh @@ -18,8 +18,6 @@ layout(set = 3, binding = 5) uniform sampler2D autoExposureTexture; #endif layout(set = 3, binding = 4) uniform UniformBuffer { - float exposure; - float autoExposureMipLevel; float paperWhiteLuminance; float maxScreenLuminance; float saturation; @@ -32,8 +30,10 @@ layout(set = 3, binding = 4) uniform UniformBuffer { float vignetteOffset; float vignettePower; float vignetteStrength; - float padding0; + float autoExposureScale; float padding1; + float padding2; + float padding3; vec4 vignetteColor; vec4 tintColor; } Uniforms; @@ -42,13 +42,6 @@ const float gamma = 1.0 / 2.2; float screenMaxNits = Uniforms.maxScreenLuminance; float paperWhiteNits = Uniforms.paperWhiteLuminance; -float Luma(vec3 color) { - - const vec3 luma = vec3(0.299, 0.587, 0.114); - return dot(color, luma); - -} - vec3 ACESToneMap(vec3 hdrColor) { float a = 2.51; float b = 0.03; @@ -74,33 +67,12 @@ vec3 ToneMap(vec3 hdrColor) { } -float ToneMap(float luminance) { - - return 1.0 - exp(-luminance); - -} - vec3 saturate(vec3 color, float factor) { const vec3 luma = vec3(0.299, 0.587, 0.114); vec3 pixelLuminance = max(vec3(dot(color, luma)), vec3(0.0)); return mix(pixelLuminance, color, factor); } -const mat3 RGBToYCoCgMatrix = mat3(0.25, 0.5, -0.25, 0.5, 0.0, 0.5, 0.25, -0.5, -0.25); -const mat3 YCoCgToRGBMatrix = mat3(1.0, 1.0, 1.0, 1.0, 0.0, -1.0, -1.0, 1.0, -1.0); - -vec3 RGBToYCoCg(vec3 RGB) { - - return RGBToYCoCgMatrix * RGB; - -} - -vec3 YCoCgToRGB(vec3 YCoCg) { - - return YCoCgToRGBMatrix * YCoCg; - -} - void main() { vec2 texCoord = 0.5 * positionVS + 0.5; @@ -136,12 +108,12 @@ void main() { bloom = Uniforms.bloomDirtStrength * textureLod(bloomDirtTexture, texCoord, 0.0).r * bloom + bloom; #endif - color += bloom; + color = color * Uniforms.tintColor.rgb + bloom; - color *= Uniforms.exposure; + // The camera exposure is already applied as the pre-exposure of the lighting #ifdef AUTO_EXPOSURE float exposureBrightness = texelFetch(autoExposureTexture, ivec2(0.0), 0).r; - color /= (9.6 * exposureBrightness); + color *= Uniforms.autoExposureScale / (9.6 * exposureBrightness); #endif #ifdef FILM_GRAIN @@ -187,8 +159,6 @@ void main() { #endif #endif - color = color * Uniforms.tintColor.rgb; - color = clamp(saturate(color, Uniforms.saturation), vec3(0.0), vec3(1.0)); color = ((color - 0.5) * max(Uniforms.contrast, 0.0)) + 0.5; diff --git a/data/shader/raytracer/binning.csh b/data/shader/raytracer/binning.csh deleted file mode 100644 index eb5d93bfb..000000000 --- a/data/shader/raytracer/binning.csh +++ /dev/null @@ -1,27 +0,0 @@ -#include -#include -#include - -layout (local_size_x = 32) in; - -void main() { - - if (IsRayInvocationValid()) { - uint idx = (1u - rayBufferOffset) * rayBufferSize + gl_GlobalInvocationID.x; - PackedRay packedRay = rays[idx]; - Ray ray = UnpackRay(packedRay); - - idx = (1u - rayPayloadBufferOffset) * rayBufferSize + gl_GlobalInvocationID.x; - PackedRayPayload packedPayload = rayPayloads[idx]; - - uint bin = uint(ray.hitID); - idx = atomicAdd(rayBinCounters[bin], 1u) + rayBinOffsets[bin]; - - uint offset = rayBufferOffset * rayBufferSize; - rays[offset + idx] = packedRay; - - offset = rayPayloadBufferOffset * rayBufferSize; - rayPayloads[offset + idx] = packedPayload; - } - -} \ No newline at end of file diff --git a/data/shader/raytracer/binningOffset.csh b/data/shader/raytracer/binningOffset.csh deleted file mode 100644 index 7ab63111f..000000000 --- a/data/shader/raytracer/binningOffset.csh +++ /dev/null @@ -1,24 +0,0 @@ -#include - -layout (local_size_x = 64) in; - -shared uint counts[64]; - -void main() { - - uint idx = gl_LocalInvocationIndex; - - counts[idx] = rayBinCounters[idx]; - - barrier(); - - uint totalOffset = 0; - for (uint i = 0; i < idx; i++) { - totalOffset += counts[i]; - } - - // Also want to reset the counters - rayBinCounters[idx] = 0; - rayBinOffsets[idx] = totalOffset; - -} \ No newline at end of file diff --git a/data/shader/raytracer/buffers.hsh b/data/shader/raytracer/buffers.hsh index 7ec24f9a7..2730a8027 100644 --- a/data/shader/raytracer/buffers.hsh +++ b/data/shader/raytracer/buffers.hsh @@ -1,10 +1,6 @@ #include -#ifdef AE_BINDLESS #define MESH_COUNT 8192 -#else -#define MESH_COUNT 1 -#endif layout(std430, set = 2, binding = 13) buffer ReadAtomic { uint readAtomic[]; @@ -26,14 +22,6 @@ layout (std430, set = 2, binding = 7) buffer Materials { RaytraceMaterial materials[]; }; -layout(std430, set = 2, binding = 17) buffer RayBinCounters { - uint rayBinCounters[]; -}; - -layout(std430, set = 2, binding = 18) buffer RayBinOffsets { - uint rayBinOffsets[]; -}; - layout(std430, set = 2, binding = 21) buffer Instances { Instance bvhInstances[]; }; diff --git a/data/shader/raytracer/bvh.hsh b/data/shader/raytracer/bvh.hsh index 3599b44a2..1e1f37fe2 100644 --- a/data/shader/raytracer/bvh.hsh +++ b/data/shader/raytracer/bvh.hsh @@ -3,16 +3,29 @@ #ifdef AE_HARDWARE_RAYTRACING #extension GL_EXT_ray_tracing : enable #extension GL_EXT_ray_query : enable +#extension GL_EXT_ray_tracing_position_fetch : enable layout(set = 2, binding = 23) uniform accelerationStructureEXT topLevelAS; #endif #include #include +#include <../common/opacity.hsh> #include #include #include +#ifdef AE_HARDWARE_RAYTRACING +// Object space normal of a triangle, the hit code transforms it with the instance +vec3 GetTriangleNormal(vec3 v0, vec3 v1, vec3 v2) { + + vec3 normal = cross(v0 - v1, v0 - v2); + float len = length(normal); + return len > 0.0 ? normal / len : vec3(0.0, 1.0, 0.0); + +} +#endif + #define STACK_SIZE 32 #define TLAS_INVALID (STACK_SIZE + 2) @@ -36,9 +49,15 @@ BVHNode UnpackNode(PackedBVHNode compressed) { return node; } -// Use local stack if there isn't much register pressure +// Use local stack if there isn't much register pressure. Note that the local stack is dynamically +// indexed and therefore might end up in (cached) device memory instead of registers. +// The shared stack is laid out with the thread index as the fastest changing index, such +// that all threads accessing the same stack depth hit different memory banks. #ifndef LOCAL_STACK -shared int stack[32][STACK_SIZE]; +shared int stack[STACK_SIZE][32]; +#define STACK_ENTRY(idx) stack[idx][threadID] +#else +#define STACK_ENTRY(idx) stack[idx] #endif void CheckLeafClosest(inout Ray ray, int meshPtr, int nodePtr, float tmin, float tmax) { @@ -124,8 +143,8 @@ int nodePtr, float tmin, float tmax) { #endif bool intersect = IntersectTriangle(ray, v0, v1, v2, sol); if (intersect && sol.x > tmin && sol.x < tmax && d <= 0.0 && sol.x < ray.hitDistance) { - float opacity = tri.opacity < 0.0 ? GetOpacity(tri, sol.yz, materialOffset, 0) : tri.opacity; - if (opacity > 0.0) { + // Triangles without an opacity map have a positive opacity + if (tri.opacity >= 0.0 || GetCutoutOpacity(tri, sol.yz, materialOffset, 0) >= opacityCutoff) { ray.hitDistance = sol.x; ray.hitID = triPtr; ray.hitInstanceID = ray.currentInstanceID; @@ -174,6 +193,10 @@ bool CheckInstance(inout Ray ray, inout uint cullMask, inout int meshPtr, inout int instancePtr = ~nodePtr; Instance instance = bvhInstances[instancePtr]; + // Rejected instances must not transform the ray, the TLAS traversal continues with it + if ((instance.mask & cullMask) == 0) + return false; + // We don't normalize the direction in case there is a scale in the // matrix. In that case the normalization leads to wrong scales in closest hit distance ray.origin = vec4(ray.origin, 1.0) * instance.inverseMatrix; @@ -184,7 +207,7 @@ bool CheckInstance(inout Ray ray, inout uint cullMask, inout int meshPtr, inout materialOffset = instance.materialOffset; nodePtr = 0; - return (instance.mask & cullMask) > 0; + return true; } @@ -205,64 +228,54 @@ void HitClosest(inout Ray ray, uint cullMask, float tMin, float tMax) { return; #ifdef LOCAL_STACK - int stack[1][STACK_SIZE]; - threadID = 0; + int stack[STACK_SIZE]; #endif uint tlasIndex = TLAS_INVALID; + // TLAS and BLAS nodes share one code path, only the node fetch differs. Lanes of a SIMD group + // are often in different levels, separate paths would then be executed one after another. while (stackPtr != 0u) { - if (stackPtr < tlasIndex) { + bool isTlas = stackPtr < tlasIndex; + if (isTlas && tlasIndex != TLAS_INVALID) { ray.origin = originalRayOrigin; ray.direction = originalRayDirection; tlasIndex = TLAS_INVALID; - if (nodePtr < 0) { + } + + if (nodePtr < 0) { + if (isTlas) { if (CheckInstance(ray, cullMask, meshPtr, materialOffset, nodePtr)) tlasIndex = stackPtr; else - nodePtr = stack[threadID][--stackPtr]; + nodePtr = STACK_ENTRY(--stackPtr); } else { - BVHNode node = UnpackNode(tlasNodes[nodePtr]); - - float hitL = 0.0, hitR = 0.0; - bool intersectL = IntersectAABB(ray, - node.leftAABB, tMin, ray.hitDistance, hitL); - bool intersectR = IntersectAABB(ray, - node.rightAABB, tMin, ray.hitDistance, hitR); - - bool noIntersection = !intersectL && !intersectR; - nodePtr = hitL <= hitR ? node.leftPtr : node.rightPtr; - nodePtr = noIntersection ? stack[threadID][--stackPtr] : nodePtr; - - if (intersectR && intersectL) { - int stackIdx = hitL <= hitR ? node.rightPtr : node.leftPtr; - stack[threadID][stackPtr++] = stackIdx; - } + CheckLeafClosest(ray, meshPtr, nodePtr, tMin, ray.hitDistance); + nodePtr = STACK_ENTRY(--stackPtr); } } else { - if(nodePtr < 0) { - CheckLeafClosest(ray, meshPtr, nodePtr, tMin, ray.hitDistance); - nodePtr = stack[threadID][--stackPtr]; - } - else { - BVHNode node = UnpackNode(blasNodes[nonuniformEXT(meshPtr)].data[nodePtr]); - - float hitL = 0.0, hitR = 0.0; - bool intersectL = IntersectAABB(ray, + PackedBVHNode packedNode; + if (isTlas) + packedNode = tlasNodes[nodePtr]; + else + packedNode = blasNodes[nonuniformEXT(meshPtr)].data[nodePtr]; + BVHNode node = UnpackNode(packedNode); + + float hitL = 0.0, hitR = 0.0; + bool intersectL = IntersectAABB(ray, node.leftAABB, tMin, ray.hitDistance, hitL); - bool intersectR = IntersectAABB(ray, + bool intersectR = IntersectAABB(ray, node.rightAABB, tMin, ray.hitDistance, hitR); - bool noIntersection = !intersectL && !intersectR; - nodePtr = hitL <= hitR ? node.leftPtr : node.rightPtr; - nodePtr = noIntersection ? stack[threadID][--stackPtr] : nodePtr; + bool noIntersection = !intersectL && !intersectR; + nodePtr = hitL <= hitR ? node.leftPtr : node.rightPtr; + nodePtr = noIntersection ? STACK_ENTRY(--stackPtr) : nodePtr; - if (intersectR && intersectL) { - int stackIdx = hitL <= hitR ? node.rightPtr : node.leftPtr; - stack[threadID][stackPtr++] = stackIdx; - } + if (intersectR && intersectL) { + int stackIdx = hitL <= hitR ? node.rightPtr : node.leftPtr; + STACK_ENTRY(stackPtr++) = stackIdx; } } } @@ -289,64 +302,53 @@ void HitClosestTransparency(inout Ray ray, uint cullMask, float tMin, float tMax return; #ifdef LOCAL_STACK - int stack[1][STACK_SIZE]; - threadID = 0; + int stack[STACK_SIZE]; #endif uint tlasIndex = TLAS_INVALID; + // See HitClosest for why TLAS and BLAS nodes share one code path while (stackPtr != 0u) { - if (stackPtr < tlasIndex) { + bool isTlas = stackPtr < tlasIndex; + if (isTlas && tlasIndex != TLAS_INVALID) { ray.origin = originalRayOrigin; ray.direction = originalRayDirection; tlasIndex = TLAS_INVALID; - if (nodePtr < 0) { + } + + if (nodePtr < 0) { + if (isTlas) { if (CheckInstance(ray, cullMask, meshPtr, materialOffset, nodePtr)) tlasIndex = stackPtr; else - nodePtr = stack[threadID][--stackPtr]; + nodePtr = STACK_ENTRY(--stackPtr); } else { - BVHNode node = UnpackNode(tlasNodes[nodePtr]); - - float hitL = 0.0, hitR = 0.0; - bool intersectL = IntersectAABB(ray, - node.leftAABB, tMin, ray.hitDistance, hitL); - bool intersectR = IntersectAABB(ray, - node.rightAABB, tMin, ray.hitDistance, hitR); - - bool noIntersection = !intersectL && !intersectR; - nodePtr = hitL <= hitR ? node.leftPtr : node.rightPtr; - nodePtr = noIntersection ? stack[threadID][--stackPtr] : nodePtr; - - if (intersectR && intersectL) { - int stackIdx = hitL <= hitR ? node.rightPtr : node.leftPtr; - stack[threadID][stackPtr++] = stackIdx; - } + CheckLeafClosestTransparency(ray, meshPtr, materialOffset, nodePtr, tMin, ray.hitDistance); + nodePtr = STACK_ENTRY(--stackPtr); } } else { - if(nodePtr < 0) { - CheckLeafClosestTransparency(ray, meshPtr, materialOffset, nodePtr, tMin, ray.hitDistance); - nodePtr = stack[threadID][--stackPtr]; - } - else { - BVHNode node = UnpackNode(blasNodes[nonuniformEXT(meshPtr)].data[nodePtr]); - - float hitL = 0.0, hitR = 0.0; - bool intersectL = IntersectAABB(ray, + PackedBVHNode packedNode; + if (isTlas) + packedNode = tlasNodes[nodePtr]; + else + packedNode = blasNodes[nonuniformEXT(meshPtr)].data[nodePtr]; + BVHNode node = UnpackNode(packedNode); + + float hitL = 0.0, hitR = 0.0; + bool intersectL = IntersectAABB(ray, node.leftAABB, tMin, ray.hitDistance, hitL); - bool intersectR = IntersectAABB(ray, + bool intersectR = IntersectAABB(ray, node.rightAABB, tMin, ray.hitDistance, hitR); - bool noIntersection = !intersectL && !intersectR; - nodePtr = hitL <= hitR ? node.leftPtr : node.rightPtr; - nodePtr = noIntersection ? stack[threadID][--stackPtr] : nodePtr; + bool noIntersection = !intersectL && !intersectR; + nodePtr = hitL <= hitR ? node.leftPtr : node.rightPtr; + nodePtr = noIntersection ? STACK_ENTRY(--stackPtr) : nodePtr; - if (intersectR && intersectL) { - int stackIdx = hitL <= hitR ? node.rightPtr : node.leftPtr; - stack[threadID][stackPtr++] = stackIdx; - } + if (intersectR && intersectL) { + int stackIdx = hitL <= hitR ? node.rightPtr : node.leftPtr; + STACK_ENTRY(stackPtr++) = stackIdx; } } } @@ -373,62 +375,52 @@ bool HitAny(inout Ray ray, uint cullMask, float tMin, float tMax) { vec3 originalRayDirection = ray.direction; #ifdef LOCAL_STACK - int stack[1][STACK_SIZE]; - threadID = 0; + int stack[STACK_SIZE]; #endif uint tlasIndex = TLAS_INVALID; + // See HitClosest for why TLAS and BLAS nodes share one code path while (stackPtr != 0u && !hit) { - if (stackPtr < tlasIndex) { - if (tlasIndex != TLAS_INVALID) { - ray.origin = originalRayOrigin; - ray.direction = originalRayDirection; - } + bool isTlas = stackPtr < tlasIndex; + if (isTlas && tlasIndex != TLAS_INVALID) { + ray.origin = originalRayOrigin; + ray.direction = originalRayDirection; tlasIndex = TLAS_INVALID; - if (nodePtr < 0) { + } + + if (nodePtr < 0) { + if (isTlas) { if (CheckInstance(ray, cullMask, meshPtr, materialOffset, nodePtr)) tlasIndex = stackPtr; else - nodePtr = stack[threadID][--stackPtr]; + nodePtr = STACK_ENTRY(--stackPtr); } else { - BVHNode node = UnpackNode(tlasNodes[nodePtr]); - - bool intersectL = IntersectAABB(ray, - node.leftAABB, tMin, tMax); - bool intersectR = IntersectAABB(ray, - node.rightAABB, tMin, tMax); - - nodePtr = intersectL ? node.leftPtr : node.rightPtr; - nodePtr = !intersectR && !intersectL ? stack[threadID][--stackPtr] : nodePtr; - - if (intersectR && intersectL) { - stack[threadID][stackPtr++] = node.rightPtr; - } - } - } - else { - if(nodePtr < 0) { if (CheckLeaf(ray, meshPtr, nodePtr, tMin, tMax)) { hit = true; } - nodePtr = stack[threadID][--stackPtr]; + nodePtr = STACK_ENTRY(--stackPtr); } - else { - BVHNode node = UnpackNode(blasNodes[nonuniformEXT(meshPtr)].data[nodePtr]); - - bool intersectL = IntersectAABB(ray, + } + else { + PackedBVHNode packedNode; + if (isTlas) + packedNode = tlasNodes[nodePtr]; + else + packedNode = blasNodes[nonuniformEXT(meshPtr)].data[nodePtr]; + BVHNode node = UnpackNode(packedNode); + + bool intersectL = IntersectAABB(ray, node.leftAABB, tMin, tMax); - bool intersectR = IntersectAABB(ray, + bool intersectR = IntersectAABB(ray, node.rightAABB, tMin, tMax); - nodePtr = intersectL ? node.leftPtr : node.rightPtr; - nodePtr = !intersectR && !intersectL ? stack[threadID][--stackPtr] : nodePtr; + nodePtr = intersectL ? node.leftPtr : node.rightPtr; + nodePtr = !intersectR && !intersectL ? STACK_ENTRY(--stackPtr) : nodePtr; - if (intersectR && intersectL) { - stack[threadID][stackPtr++] = node.rightPtr; - } + if (intersectR && intersectL) { + STACK_ENTRY(stackPtr++) = node.rightPtr; } } } @@ -457,61 +449,53 @@ float HitAnyTransparency(inout Ray ray, uint cullMask, float tMin, float tMax) { vec3 originalRayDirection = ray.direction; #ifdef LOCAL_STACK - int stack[1][STACK_SIZE]; - threadID = 0; + int stack[STACK_SIZE]; #endif uint tlasIndex = TLAS_INVALID; + // See HitClosest for why TLAS and BLAS nodes share one code path while (stackPtr != 0u && transparency > 0.0) { - if (stackPtr < tlasIndex) { + bool isTlas = stackPtr < tlasIndex; + if (isTlas && tlasIndex != TLAS_INVALID) { ray.origin = originalRayOrigin; ray.direction = originalRayDirection; tlasIndex = TLAS_INVALID; - if (nodePtr < 0) { + } + + if (nodePtr < 0) { + if (isTlas) { if (CheckInstance(ray, cullMask, meshPtr, materialOffset, nodePtr)) tlasIndex = stackPtr; else - nodePtr = stack[threadID][--stackPtr]; + nodePtr = STACK_ENTRY(--stackPtr); } else { - BVHNode node = UnpackNode(tlasNodes[nodePtr]); - - bool intersectL = IntersectAABB(ray, - node.leftAABB, tMin, tMax); - bool intersectR = IntersectAABB(ray, - node.rightAABB, tMin, tMax); - - nodePtr = intersectL ? node.leftPtr : node.rightPtr; - nodePtr = !intersectR && !intersectL ? stack[threadID][--stackPtr] : nodePtr; - - if (intersectR && intersectL) { - stack[threadID][stackPtr++] = node.rightPtr; - } - } - } - else { - if(nodePtr < 0) { - transparency *= CheckLeafTransparency(ray, meshPtr, materialOffset, nodePtr, tMin, tMax, transparency); + transparency = CheckLeafTransparency(ray, meshPtr, materialOffset, nodePtr, tMin, tMax, transparency); if (transparency < 0.000001) { transparency = 0.0; } - nodePtr = stack[threadID][--stackPtr]; + nodePtr = STACK_ENTRY(--stackPtr); } - else { - BVHNode node = UnpackNode(blasNodes[nonuniformEXT(meshPtr)].data[nodePtr]); - - bool intersectL = IntersectAABB(ray, + } + else { + PackedBVHNode packedNode; + if (isTlas) + packedNode = tlasNodes[nodePtr]; + else + packedNode = blasNodes[nonuniformEXT(meshPtr)].data[nodePtr]; + BVHNode node = UnpackNode(packedNode); + + bool intersectL = IntersectAABB(ray, node.leftAABB, tMin, tMax); - bool intersectR = IntersectAABB(ray, + bool intersectR = IntersectAABB(ray, node.rightAABB, tMin, tMax); - nodePtr = intersectL ? node.leftPtr : node.rightPtr; - nodePtr = !intersectR && !intersectL ? stack[threadID][--stackPtr] : nodePtr; + nodePtr = intersectL ? node.leftPtr : node.rightPtr; + nodePtr = !intersectR && !intersectL ? STACK_ENTRY(--stackPtr) : nodePtr; - if (intersectR && intersectL) { - stack[threadID][stackPtr++] = node.rightPtr; - } + if (intersectR && intersectL) { + STACK_ENTRY(stackPtr++) = node.rightPtr; } } } @@ -525,12 +509,78 @@ float HitAnyTransparency(inout Ray ray, uint cullMask, float tMin, float tMax) { #else +#ifdef RAY_TRACING_PIPELINE +// The hit object only identifies the hit, the ray generation stage shades it after the threads are reordered +layout(location = 0) rayPayloadEXT uvec2 unusedPayload; +layout(location = 0) hitObjectAttributeEXT vec2 hitObjectBarycentrics; + +void TraceClosest(inout Ray ray, uint rayFlags, uint cullMask, float tMin, float tMax) { + + ray.hitDistance = tMax; + + // One hit record per geometry, the records of meshes with material graphs select their hit groups + // (RayTracingWorld::hitRecords), reordering groups the threads by hit group first + hitObjectTraceRayEXT(closestHitObject, topLevelAS, rayFlags, cullMask, 0, 1, 0, + ray.origin, tMin, ray.direction, tMax, 0); + +#ifdef SHADER_EXECUTION_REORDER + // Hits on the same mesh share materials and textures, misses all sample the sky + uint coherenceHint = hitObjectIsHitEXT(closestHitObject) ? uint(hitObjectGetInstanceCustomIndexEXT(closestHitObject)) + 1u : 0u; + reorderThreadEXT(closestHitObject, coherenceHint, 16); +#endif + + if (hitObjectIsHitEXT(closestHitObject)) { + hitObjectGetAttributesEXT(closestHitObject, 0); + ray.hitBarycentrics = hitObjectBarycentrics; +#ifdef AE_POSITION_FETCH + vec3 positions[3]; + hitObjectGetIntersectionTriangleVertexPositionsEXT(closestHitObject, positions); + ray.hitGeometryNormal = GetTriangleNormal(positions[0], positions[1], positions[2]); +#endif + + ray.hitDistance = hitObjectGetRayTMaxEXT(closestHitObject); + ray.hitInstanceID = hitObjectGetInstanceIdEXT(closestHitObject); + + int geometryOffset = hitObjectGetGeometryIndexEXT(closestHitObject); + int meshIdx = hitObjectGetInstanceCustomIndexEXT(closestHitObject); + + int triangleOffset = int(geometryTriangleOffsets[nonuniformEXT(meshIdx)].data[nonuniformEXT(geometryOffset)]); + ray.hitID = hitObjectGetPrimitiveIndexEXT(closestHitObject) + triangleOffset; + } + +} + +void HitClosest(inout Ray ray, uint cullMask, float tMin, float tMax) { + + TraceClosest(ray, gl_RayFlagsOpaqueEXT, cullMask, tMin, tMax); + +} + +// Transparent geometry is resolved by the any hit stage +void HitClosestTransparency(inout Ray ray, uint cullMask, float tMin, float tMax) { + + TraceClosest(ray, gl_RayFlagsNoneEXT, cullMask, tMin, tMax); + +} +#else +void SetCommittedHitGeometry(inout Ray ray, rayQueryEXT rayQuery) { + + ray.hitBarycentrics = rayQueryGetIntersectionBarycentricsEXT(rayQuery, true); +#ifdef AE_POSITION_FETCH + vec3 positions[3]; + rayQueryGetIntersectionTriangleVertexPositionsEXT(rayQuery, true, positions); + ray.hitGeometryNormal = GetTriangleNormal(positions[0], positions[1], positions[2]); +#endif + +} + void HitClosest(inout Ray ray, uint cullMask, float tMin, float tMax) { ray.hitDistance = tMax; rayQueryEXT rayQuery; - rayQueryInitializeEXT(rayQuery, topLevelAS, gl_RayFlagsNoneEXT, cullMask, + // Every candidate would be confirmed anyway, opaque rays keep the traversal in hardware + rayQueryInitializeEXT(rayQuery, topLevelAS, gl_RayFlagsOpaqueEXT, cullMask, ray.origin, tMin, ray.direction, tMax); // Start traversal: return false if traversal is complete @@ -545,20 +595,24 @@ void HitClosest(inout Ray ray, uint cullMask, float tMin, float tMax) { ray.hitDistance = rayQueryGetIntersectionTEXT(rayQuery, true); ray.hitInstanceID = rayQueryGetIntersectionInstanceIdEXT(rayQuery, true); - int geometryOffset = rayQueryGetIntersectionGeometryIndexEXT(rayQuery, false); - int meshIdx = rayQueryGetIntersectionInstanceCustomIndexEXT(rayQuery, false); + int geometryOffset = rayQueryGetIntersectionGeometryIndexEXT(rayQuery, true); + int meshIdx = rayQueryGetIntersectionInstanceCustomIndexEXT(rayQuery, true); int triangleOffset = int(geometryTriangleOffsets[nonuniformEXT(meshIdx)].data[nonuniformEXT(geometryOffset)]); ray.hitID = rayQueryGetIntersectionPrimitiveIndexEXT(rayQuery, true) + triangleOffset; + + SetCommittedHitGeometry(ray, rayQuery); } } +#endif + bool HitAny(inout Ray ray, uint cullMask, float tMin, float tMax) { ray.hitDistance = tMax; rayQueryEXT rayQuery; - rayQueryInitializeEXT(rayQuery, topLevelAS, gl_RayFlagsTerminateOnFirstHitEXT, cullMask, + rayQueryInitializeEXT(rayQuery, topLevelAS, gl_RayFlagsTerminateOnFirstHitEXT | gl_RayFlagsOpaqueEXT, cullMask, ray.origin, tMin, ray.direction, tMax); // Start traversal: return false if traversal is complete @@ -577,6 +631,7 @@ bool HitAny(inout Ray ray, uint cullMask, float tMin, float tMax) { } +#ifndef RAY_TRACING_PIPELINE void HitClosestTransparency(inout Ray ray, uint cullMask, float tMin, float tMax) { ray.hitDistance = tMax; @@ -603,7 +658,7 @@ void HitClosestTransparency(inout Ray ray, uint cullMask, float tMin, float tMax Triangle tri = UnpackTriangle(triangles[nonuniformEXT(meshIdx)].data[nonuniformEXT(hitID)]); - if (GetOpacity(tri, barrycentric, materialOffset, 0) > 0.001) { + if (GetCutoutOpacity(tri, barrycentric, materialOffset, 0) >= opacityCutoff) { rayQueryConfirmIntersectionEXT(rayQuery); } @@ -620,10 +675,14 @@ void HitClosestTransparency(inout Ray ray, uint cullMask, float tMin, float tMax int triangleOffset = int(geometryTriangleOffsets[nonuniformEXT(meshIdx)].data[nonuniformEXT(geometryOffset)]); ray.hitID = rayQueryGetIntersectionPrimitiveIndexEXT(rayQuery, true) + triangleOffset; + + SetCommittedHitGeometry(ray, rayQuery); } } +#endif + float HitAnyTransparency(inout Ray ray, uint cullMask, float tMin, float tMax) { float transparency = 1.0; @@ -667,4 +726,27 @@ float HitAnyTransparency(inout Ray ray, uint cullMask, float tMin, float tMax) { return transparency; } -#endif \ No newline at end of file +#endif + +// Non-opaque geometry is alpha tested with OPACITY_CHECK +void HitClosestOpacityCheck(inout Ray ray, uint cullMask, float tMin, float tMax) { + +#ifdef OPACITY_CHECK + HitClosestTransparency(ray, cullMask, tMin, tMax); +#else + HitClosest(ray, cullMask, tMin, tMax); +#endif + +} + +// Rays of the ray buffer are traced in a separate pass by compute pipelines, ray tracing pipelines trace them here +void TraceBufferedRay(inout Ray ray) { + +#ifdef RAY_TRACING_PIPELINE + ray.hitID = -1; + ray.hitDistance = 0.0; + if (ray.ID >= 0) + HitClosestOpacityCheck(ray, INSTANCE_MASK_CLOSEST, 0.0, INF); +#endif + +} diff --git a/data/shader/raytracer/common.hsh b/data/shader/raytracer/common.hsh index 3cfdb5b6e..faa9765fa 100644 --- a/data/shader/raytracer/common.hsh +++ b/data/shader/raytracer/common.hsh @@ -1,4 +1,5 @@ #include +#include <../globals.hsh> #include <../common/random.hsh> #include <../common/PI.hsh> #include <../common/packing.hsh> @@ -15,6 +16,17 @@ #define INSTANCE_MASK_ALL (1 << 7) #define INSTANCE_MASK_SHADOW (1 << 6) +// Meshes with only translucent materials, rays without TRANSLUCENT_HITS would see them as opaque without an opacity check +#define INSTANCE_MASK_TRANSLUCENT (1 << 5) +#define INSTANCE_MASK_TRANSLUCENT_SHADOW (1 << 4) + +// The instances of closest hits, and of shadow rays which pass translucent surfaces by their opacity +#ifdef TRANSLUCENT_HITS +#define INSTANCE_MASK_CLOSEST (INSTANCE_MASK_ALL | INSTANCE_MASK_TRANSLUCENT) +#else +#define INSTANCE_MASK_CLOSEST INSTANCE_MASK_ALL +#endif +#define INSTANCE_MASK_SHADOW_TRANSPARENCY (INSTANCE_MASK_SHADOW | INSTANCE_MASK_TRANSLUCENT_SHADOW) Triangle UnpackTriangle(PackedTriangle triangle) { Triangle tri; @@ -56,6 +68,9 @@ Ray UnpackRay(PackedRay compressed) { ray.hitDistance = compressed.hit.x; ray.hitInstanceID = floatBitsToInt(compressed.hit.z); + ray.hitBarycentrics = unpackUnorm2x16(floatBitsToUint(compressed.direction.w)); + ray.hitGeometryNormal = unpackUnitVector(floatBitsToInt(compressed.hit.w)).xyz; + return ray; } @@ -70,6 +85,9 @@ PackedRay PackRay(Ray ray) { compressed.hit.y = intBitsToFloat(ray.hitID); compressed.hit.z = intBitsToFloat(ray.hitInstanceID); + compressed.direction.w = uintBitsToFloat(packUnorm2x16(ray.hitBarycentrics)); + compressed.hit.w = intBitsToFloat(packUnitVector(ray.hitGeometryNormal)); + return compressed; } @@ -106,7 +124,8 @@ Light UnpackLight(PackedLight compressed) { light.P = compressed.P.xyz; light.N = normalize(compressed.N.xyz); - light.radiance = compressed.color.rgb; + // The lights of ray tracing are built once, the pre-exposure follows the camera + light.radiance = compressed.color.rgb * globalData.preExposure; uint data0 = floatBitsToUint(compressed.data.x); uint data1 = floatBitsToUint(compressed.P.w); diff --git a/data/shader/raytracer/deferredShadow.hsh b/data/shader/raytracer/deferredShadow.hsh new file mode 100644 index 000000000..c7de03bd5 --- /dev/null +++ b/data/shader/raytracer/deferredShadow.hsh @@ -0,0 +1,32 @@ +// The radiance of each sample is clamped, so the result can only be put together after the shadow rays are traced + +struct DeferredSample { + // w: 1.0 if the sample is valid, -1.0 in the first sample of a pixel which isn't ray traced + vec4 radiance; + // w: radiance limit + vec4 lobeWeight; +}; + +struct DeferredShadowRay { + // xyz: origin, w: maximum distance + vec4 origin; + // w: index of the light + vec4 direction; +}; + +layout(std430, set = 3, binding = 12) buffer DeferredSamples { + DeferredSample deferredSamples[]; +}; + +// rgb: direct light, w: transparency along the shadow ray +layout(std430, set = 3, binding = 13) buffer DeferredLights { + vec4 deferredLights[]; +}; + +layout(std430, set = 3, binding = 14) buffer DeferredShadowRays { + DeferredShadowRay deferredShadowRays[]; +}; + +layout(std430, set = 3, binding = 15) buffer DeferredShadowRayCount { + uint deferredShadowRayCount; +}; diff --git a/data/shader/raytracer/deform.csh b/data/shader/raytracer/deform.csh new file mode 100644 index 000000000..942b05c1b --- /dev/null +++ b/data/shader/raytracer/deform.csh @@ -0,0 +1,167 @@ +// Deforms vertices for hardware ray tracing like deferred/geometry.vsh (skinning, graph vertex offset, wind) into the +// positions of the instance BLAS and the normals the hits read. Material graphs include it after their vertex functions +#extension GL_EXT_buffer_reference : require +#extension GL_EXT_buffer_reference_uvec2 : require + +#include <../globals.hsh> +#include <../wind.hsh> +#include <../common/packing.hsh> +#include <../common/rotation.hsh> +#include <../common/texCoord.hsh> + +// Has to match the group size of the deformation pass in RayTracingWorld +layout (local_size_x = 64) in; + +// Has to match GPUDeformVertex in RTStructures.h +struct DeformVertex { + // Position and the packed normal in w + vec4 position; + // Packed tangent with the handedness in w + uint tangent; + uint texCoord; + uint color; + uint weights; + uint joints01; + uint joints23; + uint texCoord1; + uint padding0; +}; + +// One deformed vertex range of an instance, has to match GPUDeformJob in RTStructures.h +struct DeformJob { + mat3x4 matrix; + uvec2 sourceVertices; + uvec2 positions; + uvec2 normals; + uint firstGroup; + uint vertexOffset; + uint vertexCount; + uint deformOffset; + float windBendScale; + float windWiggleScale; + float windTextureLod; + uint materialGraphOffset; + uint invertUVs; + float uvTiling; + vec2 uvAnimation; + uint hasTexCoords1; + uint padding0; +}; + +layout(buffer_reference, std430, buffer_reference_align = 16) readonly buffer DeformVertexBuffer { + DeformVertex vertices[]; +}; + +layout(buffer_reference, std430, buffer_reference_align = 4) writeonly buffer PositionBuffer { + float positions[]; +}; + +layout(buffer_reference, std430, buffer_reference_align = 8) writeonly buffer NormalBuffer { + uvec2 normals[]; +}; + +layout(std430, set = 3, binding = 0) readonly buffer DeformJobs { + DeformJob deformJobs[]; +}; + +layout(std430, set = 3, binding = 1) readonly buffer JointMatrices { + mat3x4 jointMatrices[]; +}; + +layout(std430, set = 3, binding = 2) readonly buffer GroupJobs { + uint groupJobs[]; +}; + +#ifdef WIND +layout(set = 3, binding = 3) uniform sampler2D windNoiseMap; +#endif + +#ifdef SOFT_BODY +// Positions with the packed normal in w +layout(std430, set = 3, binding = 4) readonly buffer SoftBodyVertices { + vec4 softBodyVertices[]; +}; +#endif + +layout(push_constant) uniform constants { + uint groupOffset; + uint groupCount; +} PushConstants; + +void main() { + + uint group = gl_WorkGroupID.y * gl_NumWorkGroups.x + gl_WorkGroupID.x; + if (group >= PushConstants.groupCount) + return; + + DeformJob job = deformJobs[groupJobs[PushConstants.groupOffset + group]]; + uint idx = (group - job.firstGroup) * gl_WorkGroupSize.x + gl_LocalInvocationIndex; + if (idx >= job.vertexCount) + return; + + uint vertexIdx = job.vertexOffset + idx; + DeformVertex vertex = DeformVertexBuffer(job.sourceVertices).vertices[vertexIdx]; + + vec3 position = vertex.position.xyz; + vec3 normal = unpackUnitVector(floatBitsToInt(vertex.position.w)).xyz; + vec4 tangent = unpackUnitVector(int(vertex.tangent)); + + mat4 mMatrix = mat4(transpose(job.matrix)); + +#ifdef SKINNED + uvec4 joints = uvec4(vertex.joints01 & 0xFFFFu, vertex.joints01 >> 16u, vertex.joints23 & 0xFFFFu, vertex.joints23 >> 16u); + vec4 weights = unpackUnorm4x8(vertex.weights); + weights /= dot(weights, vec4(1.0)); + + mat3x4 skinMatrix = weights.x * jointMatrices[job.deformOffset + joints.x] + + weights.y * jointMatrices[job.deformOffset + joints.y] + + weights.z * jointMatrices[job.deformOffset + joints.z] + + weights.w * jointMatrices[job.deformOffset + joints.w]; + + position = vec4(position, 1.0) * skinMatrix; + normal = vec4(normal, 0.0) * skinMatrix; + tangent.xyz = vec4(tangent.xyz, 0.0) * skinMatrix; +#endif + +#ifdef SOFT_BODY + // The vertices of the body start at the joint offset + vec4 softBodyVertex = softBodyVertices[job.deformOffset + vertexIdx]; + vec3 restNormal = normal; + position = softBodyVertex.xyz; + normal = unpackUnitVector(floatBitsToInt(softBodyVertex.w)).xyz; + tangent.xyz = RotateLike(tangent.xyz, normalize(restNormal), normal); +#endif + +#ifdef MATERIAL_GRAPH_VERTEX_OFFSET + vec2 texCoord = unpackHalf2x16(vertex.texCoord); + texCoord = TransformTexCoord(texCoord, job.invertUVs > 0u, job.uvAnimation, job.uvTiling); + + // Meshes without tangents use the same default as the rasterizer + vec3 graphTangent = dot(tangent.xyz, tangent.xyz) > 0.01 ? tangent.xyz : vec3(1.0, 0.0, 0.0); + + // Zero without a second set, like the rasterizer + vec2 texCoord1 = unpackHalf2x16(vertex.texCoord1); + texCoord1 = job.invertUVs > 0u && job.hasTexCoords1 > 0u ? vec2(texCoord1.x, 1.0 - texCoord1.y) : texCoord1; + + MaterialVertexInput graphInput = CreateMaterialVertexInput(vertex.position.xyz, position, normal, graphTangent, + texCoord, texCoord1, unpackUnorm4x8(vertex.color), mMatrix, globalData.time, job.materialGraphOffset); + normal = EvaluateMaterialVertexNormal(graphInput); + position += EvaluateMaterialVertexOffset(graphInput); +#endif + +#ifdef WIND + vec3 windPosition = vec3(mMatrix * vec4(position, 1.0)); + position = WindAnimation(windNoiseMap, position, GetWindDirection(mMatrix), job.windBendScale, + job.windWiggleScale, job.windTextureLod, globalData.time, windPosition); +#endif + + PositionBuffer positions = PositionBuffer(job.positions); + positions.positions[vertexIdx * 3u + 0u] = position.x; + positions.positions[vertexIdx * 3u + 1u] = position.y; + positions.positions[vertexIdx * 3u + 2u] = position.z; + + float tangentLength = length(tangent.xyz); + tangent.xyz = tangentLength > 0.0 ? tangent.xyz / tangentLength : vec3(0.0); + NormalBuffer(job.normals).normals[vertexIdx] = uvec2(packUnitVector(normalize(normal)), packUnitVector(tangent)); + +} diff --git a/data/shader/raytracer/deformTriangles.csh b/data/shader/raytracer/deformTriangles.csh new file mode 100644 index 000000000..729142443 --- /dev/null +++ b/data/shader/raytracer/deformTriangles.csh @@ -0,0 +1,113 @@ +// Gathers the vertices deformed by deform.csh into the triangles of a software BLAS, hardware ray tracing builds +// its BLAS from the deformed positions directly +#extension GL_EXT_buffer_reference : require +#extension GL_EXT_buffer_reference_uvec2 : require + +#include +#include <../common/packing.hsh> + +// Has to match the group size of the triangle pass in RayTracingWorld +layout (local_size_x = 64) in; + +// Has to match GPUDeformTriangleJob in RTStructures.h +struct DeformTriangleJob { + uvec2 triangleVertices; + uvec2 positions; + uvec2 normals; + uvec2 triangles; + uvec2 bvhTriangles; + uint firstGroup; + uint triangleCount; +}; + +layout(buffer_reference, std430, buffer_reference_align = 16) readonly buffer TriangleVertexBuffer { + uvec4 triangleVertices[]; +}; + +layout(buffer_reference, std430, buffer_reference_align = 4) readonly buffer PositionBuffer { + float positions[]; +}; + +layout(buffer_reference, std430, buffer_reference_align = 8) readonly buffer NormalBuffer { + uvec2 normals[]; +}; + +layout(buffer_reference, std430, buffer_reference_align = 16) buffer TriangleBuffer { + PackedTriangle triangles[]; +}; + +layout(buffer_reference, std430, buffer_reference_align = 16) buffer BVHTriangleBuffer { + PackedBVHTriangle bvhTriangles[]; +}; + +layout(std430, set = 3, binding = 0) readonly buffer TriangleJobs { + DeformTriangleJob triangleJobs[]; +}; + +layout(std430, set = 3, binding = 2) readonly buffer GroupJobs { + uint groupJobs[]; +}; + +layout(push_constant) uniform constants { + uint groupOffset; + uint groupCount; +} PushConstants; + +void main() { + + uint group = gl_WorkGroupID.y * gl_NumWorkGroups.x + gl_WorkGroupID.x; + if (group >= PushConstants.groupCount) + return; + + DeformTriangleJob job = triangleJobs[groupJobs[PushConstants.groupOffset + group]]; + uint idx = (group - job.firstGroup) * gl_WorkGroupSize.x + gl_LocalInvocationIndex; + if (idx >= job.triangleCount) + return; + + PositionBuffer deformedPositions = PositionBuffer(job.positions); + NormalBuffer deformedNormals = NormalBuffer(job.normals); + uvec4 vertexIndices = TriangleVertexBuffer(job.triangleVertices).triangleVertices[idx]; + + vec3 positions[3]; + vec3 normals[3]; + for (int i = 0; i < 3; i++) { + uint vertexIdx = vertexIndices[i]; + positions[i] = vec3(deformedPositions.positions[vertexIdx * 3u], deformedPositions.positions[vertexIdx * 3u + 1u], + deformedPositions.positions[vertexIdx * 3u + 2u]); + normals[i] = unpackUnitVector(int(deformedNormals.normals[vertexIdx].x)).xyz; + } + + TriangleBuffer triangles = TriangleBuffer(job.triangles); + vec4 texCoords = triangles.triangles[idx].d0; + vec2 uv0 = unpackHalf2x16(floatBitsToUint(texCoords.x)); + vec2 uv1 = unpackHalf2x16(floatBitsToUint(texCoords.y)); + vec2 uv2 = unpackHalf2x16(floatBitsToUint(texCoords.z)); + + // Same tangent frame as the triangles built on the CPU + vec3 v0v1 = positions[1] - positions[0]; + vec3 v0v2 = positions[2] - positions[0]; + vec2 uv0uv1 = uv1 - uv0; + vec2 uv0uv2 = uv2 - uv0; + + float r = 1.0 / (uv0uv1.x * uv0uv2.y - uv0uv2.x * uv0uv1.y); + + vec3 s = (uv0uv2.y * v0v1 - uv0uv1.y * v0v2) * r; + vec3 t = (uv0uv1.x * v0v2 - uv0uv2.x * v0v1) * r; + + vec3 normal = normalize(normals[0] + normals[1] + normals[2]); + + vec3 tangent = normalize(s - normal * dot(normal, s)); + float handedness = dot(cross(tangent, normal), t) < 0.0 ? 1.0 : -1.0; + vec3 bitangent = handedness * normalize(cross(tangent, normal)); + + triangles.triangles[idx].v0 = vec4(positions[0], intBitsToFloat(packUnitVector(normals[0]))); + triangles.triangles[idx].v1 = vec4(positions[1], intBitsToFloat(packUnitVector(normals[1]))); + triangles.triangles[idx].v2 = vec4(positions[2], intBitsToFloat(packUnitVector(normals[2]))); + triangles.triangles[idx].d1.xy = vec2(intBitsToFloat(packUnitVector(tangent)), intBitsToFloat(packUnitVector(bitangent))); + + BVHTriangleBuffer bvhTriangles = BVHTriangleBuffer(job.bvhTriangles); + bvhTriangles.bvhTriangles[idx].v0.xyz = positions[0]; + bvhTriangles.bvhTriangles[idx].v1.xyz = positions[1]; + bvhTriangles.bvhTriangles[idx].v2.xyz = positions[2]; + +} diff --git a/data/shader/raytracer/direct.hsh b/data/shader/raytracer/direct.hsh index 22d190681..3fb5eee54 100644 --- a/data/shader/raytracer/direct.hsh +++ b/data/shader/raytracer/direct.hsh @@ -4,6 +4,7 @@ #include #include #include <../common/random.hsh> +#include <../common/light.hsh> int GetLightCount() { return PushConstants.lightCount; @@ -33,21 +34,18 @@ Light GetLight(Surface surface, float seed0, float seed1, out float lightPdf) { weight = light.brightness; } else if (light.type == uint(POINT_LIGHT)) { - vec3 pointToLight = light.P - surface.P; - float sqrDistance = dot(pointToLight, pointToLight); - float lightDistance = sqrt(sqrDistance); + float lightDistance = distance(light.P, surface.P); - weight = light.brightness * light.radius / sqrDistance; + weight = light.brightness * GetDistanceAttenuation(lightDistance, light.radius); } else if (light.type == uint(SPOT_LIGHT)) { vec3 pointToLight = light.P - surface.P; - float sqrDistance = dot(pointToLight, pointToLight); - float lightDistance = sqrt(sqrDistance); + float lightDistance = length(pointToLight); vec3 L = pointToLight / lightDistance; - float NdotL = max(dot(light.N, -L), 0.0); + float angleAttenuation = saturate(dot(light.N, -L) * light.angleScale + light.angleOffset); - weight = light.brightness * NdotL / sqrDistance; + weight = light.brightness * sqr(angleAttenuation) * GetDistanceAttenuation(lightDistance, light.radius); } weight = clamp(weight, 0.0000001, 1000000000000.0); @@ -103,24 +101,21 @@ void SampleLight(Light light, inout Surface surface, float seed0, float seed1, } else if (light.type == uint(POINT_LIGHT)) { vec3 pointToLight = light.P - surface.P; - float sqrDistance = dot(pointToLight, pointToLight); - dist = sqrt(sqrDistance); + dist = length(pointToLight); - float attenuation = saturate(1.0 - pow(dist / light.radius, 4.0)); - solidAngle = attenuation / sqrDistance; + solidAngle = GetDistanceAttenuation(dist, light.radius); surface.L = pointToLight / dist; UpdateSurface(surface); } else if (light.type == uint(SPOT_LIGHT)) { vec3 pointToLight = light.P - surface.P; - float sqrDistance = dot(pointToLight, pointToLight); - dist = sqrt(sqrDistance); + dist = length(pointToLight); surface.L = pointToLight / dist; float strength = dot(surface.L, -light.N); - float attenuation = saturate(strength * light.angleScale + light.angleOffset); - solidAngle = sqr(attenuation) / sqrDistance; + float angleAttenuation = saturate(strength * light.angleScale + light.angleOffset); + solidAngle = sqr(angleAttenuation) * GetDistanceAttenuation(dist, light.radius); UpdateSurface(surface); } diff --git a/data/shader/raytracer/graphHit.hsh b/data/shader/raytracer/graphHit.hsh new file mode 100644 index 000000000..44eea2b6b --- /dev/null +++ b/data/shader/raytracer/graphHit.hsh @@ -0,0 +1,20 @@ +// Data exchanged between the surface of hits and the hit shader of a material graph, see graphHit.rchit + +struct MaterialGraphHit { + // Tangent, bitangent and normal in world space, the hit shader gets positions and transforms from the hit object + mat3 tangentFrame; + // Vertex color packed as unorm 4x8 + uint color; + vec2 texCoord; + float frontFacing; + float textureLevel; + uint parameterOffset; + + vec3 baseColor; + // In tangent space + vec3 normal; + vec3 emissive; + float roughness; + float metalness; + float ao; +}; diff --git a/data/shader/raytracer/graphHit.rchit b/data/shader/raytracer/graphHit.rchit new file mode 100644 index 000000000..21dc28433 --- /dev/null +++ b/data/shader/raytracer/graphHit.rchit @@ -0,0 +1,39 @@ +// Evaluates the surface of a material graph for a hit of a ray tracing pipeline, the ray generation stage executes it +// with the hit object of the ray. The shaders generated from graphs include this file after their surface function, +// see materialgraph/Compiler +#extension GL_EXT_ray_tracing : require + +#include + +layout(location = 1) rayPayloadInEXT MaterialGraphHit graphHit; + +void main() { + + materialGraphHitTextureLevel = graphHit.textureLevel; + + mat4 modelMatrix = mat4(gl_ObjectToWorldEXT); + mat3 tangentFrame = graphHit.tangentFrame; + + vec3 worldPosition = gl_WorldRayOriginEXT + gl_HitTEXT * gl_WorldRayDirectionEXT; + vec3 objectPosition = gl_ObjectRayOriginEXT + gl_HitTEXT * gl_ObjectRayDirectionEXT; + vec3 objectNormal = normalize(tangentFrame[2] * mat3(modelMatrix)); + + MaterialSurfaceInput surfaceIn = CreateMaterialSurfaceInput(objectPosition, objectNormal, worldPosition, + tangentFrame[2], vec3(modelMatrix[3]), mat3(globalData.vMatrix) * tangentFrame, graphHit.texCoord, vec2(0.5), + unpackUnorm4x8(graphHit.color), graphHit.frontFacing, graphHit.parameterOffset); + + // Rays see the surface from their origin, not from the camera + surfaceIn.viewDirection = -gl_WorldRayDirectionEXT; + surfaceIn.tangent = normalize(transpose(mat3(modelMatrix)) * tangentFrame[0]); + surfaceIn.modelMatrix = modelMatrix; + + MaterialSurfaceOutput surface = EvaluateMaterialSurface(surfaceIn); + + graphHit.baseColor = surface.baseColor; + graphHit.normal = surface.normal; + graphHit.emissive = surface.emissive; + graphHit.roughness = surface.roughness; + graphHit.metalness = surface.metalness; + graphHit.ao = surface.ao; + +} diff --git a/data/shader/raytracer/graphOpacity.rahit b/data/shader/raytracer/graphOpacity.rahit new file mode 100644 index 000000000..2f524089c --- /dev/null +++ b/data/shader/raytracer/graphOpacity.rahit @@ -0,0 +1,67 @@ +// Alpha tests the candidate hits of a material graph with an opacity like opacity.rahit does for other materials. The +// shaders generated from graphs include this file after their surface function, see materialgraph/Compiler +#extension GL_EXT_ray_tracing : require +#extension GL_EXT_nonuniform_qualifier : require + +#include +#include <../common/random.hsh> + +hitAttributeEXT vec2 barycentrics; + +void main() { + + int meshIdx = gl_InstanceCustomIndexEXT; + int triangleOffset = int(geometryTriangleOffsets[nonuniformEXT(meshIdx)].data[nonuniformEXT(gl_GeometryIndexEXT)]); + int hitID = gl_PrimitiveID + triangleOffset; + + Instance instance = bvhInstances[nonuniformEXT(gl_InstanceID)]; + Triangle tri = UnpackTriangle(triangles[nonuniformEXT(meshIdx)].data[nonuniformEXT(hitID)]); + RaytraceMaterial rayMat = materials[nonuniformEXT(tri.materialIndex + instance.materialOffset)]; +#ifndef TRANSLUCENT_HITS + // Rays pass through translucent surfaces + if (rayMat.blendMode != blendModeNone) + ignoreIntersectionEXT; +#endif + + float s = barycentrics.x; + float t = barycentrics.y; + float r = 1.0 - s - t; + + vec2 texCoord = r * tri.uv0 + s * tri.uv1 + t * tri.uv2; + texCoord = TransformTexCoord(texCoord, rayMat.invertUVs > 0, vec2(rayMat.uvAnimationX, rayMat.uvAnimationY), rayMat.tiling); + vec4 color = r * tri.color0 + s * tri.color1 + t * tri.color2; + + mat4 modelMatrix = mat4(gl_ObjectToWorldEXT); + vec3 objectNormal = normalize(r * tri.n0 + s * tri.n1 + t * tri.n2); + vec3 worldNormal = normalize(transpose(mat3(gl_WorldToObjectEXT)) * objectNormal); + vec3 worldPosition = gl_WorldRayOriginEXT + gl_HitTEXT * gl_WorldRayDirectionEXT; + vec3 objectPosition = gl_ObjectRayOriginEXT + gl_HitTEXT * gl_ObjectRayDirectionEXT; + + vec3 bitangent = rayMat.invertUVs > 0 ? tri.bt : -tri.bt; + mat3 tangentFrame = mat3(normalize(mat3(modelMatrix) * tri.t), normalize(mat3(modelMatrix) * bitangent), worldNormal); + float frontFacing = gl_HitKindEXT == gl_HitKindFrontFacingTriangleEXT ? 1.0 : -1.0; + + materialGraphHitTextureLevel = 0.0; + MaterialSurfaceInput surfaceIn = CreateMaterialSurfaceInput(objectPosition, objectNormal, worldPosition, worldNormal, + vec3(modelMatrix[3]), mat3(globalData.vMatrix) * tangentFrame, texCoord, vec2(0.5), color, frontFacing, + rayMat.graphParameterOffset); + + // Rays see the surface from their origin, not from the camera + surfaceIn.viewDirection = -gl_WorldRayDirectionEXT; + surfaceIn.tangent = normalize(tri.t); + surfaceIn.modelMatrix = modelMatrix; + + float opacity = EvaluateMaterialSurface(surfaceIn).opacity; +#ifdef TRANSLUCENT_HITS + // The path tracer blends the opacity of translucent materials itself, the one of the graph decides which hits it sees + if (rayMat.blendMode != blendModeNone) { + uint seed = hash(uvec4(gl_LaunchIDEXT.xy, floatBitsToUint(gl_HitTEXT), uint(globalData.frameCount))); + if (opacity <= floatConstruct(seed)) + ignoreIntersectionEXT; + return; + } +#endif + if (opacity < opacityCutoff) + ignoreIntersectionEXT; + +} diff --git a/data/shader/raytracer/lighting.hsh b/data/shader/raytracer/lighting.hsh new file mode 100644 index 000000000..a2c4dca78 --- /dev/null +++ b/data/shader/raytracer/lighting.hsh @@ -0,0 +1,96 @@ +// Direct light at the hits of RTGI and reflections. With DEFERRED_SHADOW_RAYS the shadow rays are written out and +// traced in a separate pass. Needs the cloud map with CLOUD_SHADOWS +#ifdef DEFERRED_SHADOW_RAYS +#include + +bool hasDeferredShadowRay = false; +DeferredShadowRay deferredShadowRay; +int deferredLightBase = 0; +#endif + +float CheckVisibility(Surface surface, float lightDistance) { + + if (surface.NdotL > 0.0) { + Ray ray; + ray.direction = surface.L; + float side = dot(surface.L, surface.geometryNormal) < 0.0 ? -1.0 : 1.0; + ray.origin = surface.P + surface.geometryNormal * (side * EPSILON); +#ifdef DEFERRED_SHADOW_RAYS + hasDeferredShadowRay = true; + deferredShadowRay.origin = vec4(ray.origin, lightDistance - 2.0 * EPSILON); + deferredShadowRay.direction = vec4(ray.direction, 0.0); + return 1.0; +#else + return HitAnyTransparency(ray, INSTANCE_MASK_SHADOW_TRANSPARENCY, 0.0, lightDistance - 2.0 * EPSILON); +#endif + } + else { + return 0.0; + } + +} + +vec3 EvaluateDirectLight(inout Surface surface, float raySeed, float seed) { + + if (GetLightCount() == 0) + return vec3(0.0); + + float lightPdf; + Light light = GetLight(surface, raySeed, seed, lightPdf); + + float solidAngle, lightDistance; + SampleLight(light, surface, raySeed, seed, solidAngle, lightDistance); + + bool transmittedLight = IsTransmittedLight(surface); + Surface lightSurface = transmittedLight ? GetTransmissionSurface(surface) : surface; + + // Evaluate the BRDF + vec3 reflectance = transmittedLight ? GetTransmissionColor(surface.material) * EvaluateDiffuseBRDF(lightSurface) : + EvaluateDiffuseBRDF(surface) + EvaluateSpecularBRDF(surface); + reflectance *= surface.material.opacity; + vec3 radiance = light.radiance * solidAngle; + + // The visibility is needed to estimate the solid angle of the light from the surface + if (light.castShadow) + radiance *= CheckVisibility(lightSurface, lightDistance); + +#ifdef CLOUD_SHADOWS + if (light.type == uint(DIRECTIONAL_LIGHT)) { + vec3 P = vec3(globalData.vMatrix * vec4(surface.P, 1.0)); + float cloudShadowFactor = CalculateCloudShadow(P, cloudShadowUniforms.cloudShadow, cloudMap); + + radiance *= cloudShadowFactor; + } +#endif + + return reflectance * radiance * lightSurface.NdotL / lightPdf; + +} + +// The average of several light samples, deferred shadow rays store their sample instead +vec3 EvaluateDirectLights(inout Surface surface, float raySeed, float seed, int lightSampleCount) { + + vec3 radiance = vec3(0.0); + for (int i = 0; i < lightSampleCount; i++) { +#ifdef DEFERRED_SHADOW_RAYS + hasDeferredShadowRay = false; + vec3 direct = EvaluateDirectLight(surface, raySeed, seed) / float(lightSampleCount); + if (hasDeferredShadowRay) { + uint lightIdx = uint(deferredLightBase + i); + deferredLights[lightIdx] = vec4(direct, 1.0); + uint shadowRayIdx = atomicAdd(deferredShadowRayCount, 1u); + deferredShadowRays[shadowRayIdx].origin = deferredShadowRay.origin; + deferredShadowRays[shadowRayIdx].direction = vec4(deferredShadowRay.direction.xyz, uintBitsToFloat(lightIdx)); + } + else { + radiance += direct; + } +#else + radiance += EvaluateDirectLight(surface, raySeed, seed) / float(lightSampleCount); +#endif + seed += 1.0 / float(lightSampleCount); + } + + return radiance; + +} diff --git a/data/shader/raytracer/miss.rmiss b/data/shader/raytracer/miss.rmiss new file mode 100644 index 000000000..869c9cd53 --- /dev/null +++ b/data/shader/raytracer/miss.rmiss @@ -0,0 +1,8 @@ +// Hit objects don't invoke miss shaders, the pipeline just needs one +#extension GL_EXT_ray_tracing : require + +layout(location = 0) rayPayloadInEXT uvec2 unusedPayload; + +void main() { + +} diff --git a/data/shader/raytracer/opacity.rahit b/data/shader/raytracer/opacity.rahit new file mode 100644 index 000000000..d9721fc4b --- /dev/null +++ b/data/shader/raytracer/opacity.rahit @@ -0,0 +1,22 @@ +// Alpha tests the candidate hits of non-opaque geometry like HitClosestTransparency in bvh.hsh +#extension GL_EXT_ray_tracing : require +#extension GL_EXT_nonuniform_qualifier : require + +#include +#include <../common/opacity.hsh> + +hitAttributeEXT vec2 barycentrics; + +void main() { + + int meshIdx = gl_InstanceCustomIndexEXT; + int triangleOffset = int(geometryTriangleOffsets[nonuniformEXT(meshIdx)].data[nonuniformEXT(gl_GeometryIndexEXT)]); + int hitID = gl_PrimitiveID + triangleOffset; + + int materialOffset = bvhInstances[nonuniformEXT(gl_InstanceID)].materialOffset; + Triangle tri = UnpackTriangle(triangles[nonuniformEXT(meshIdx)].data[nonuniformEXT(hitID)]); + + if (GetCutoutOpacity(tri, barycentrics, materialOffset, 0) < opacityCutoff) + ignoreIntersectionEXT; + +} diff --git a/data/shader/raytracer/refitBVH.csh b/data/shader/raytracer/refitBVH.csh new file mode 100644 index 000000000..4632126d4 --- /dev/null +++ b/data/shader/raytracer/refitBVH.csh @@ -0,0 +1,78 @@ +#include + +// Updates the bounds of a BVH with a fixed topology. Each dispatch updates the nodes of one tree level, +// starting with the deepest level, such that the bounds of the child nodes are always up to date. + +layout (local_size_x = 64) in; + +layout(std430, set = 3, binding = 0) buffer Nodes { + PackedBVHNode nodes[]; +}; + +layout(std430, set = 3, binding = 1) readonly buffer BVHTriangles { + PackedBVHTriangle bvhTriangles[]; +}; + +layout(std430, set = 3, binding = 2) readonly buffer LevelNodes { + int levelNodes[]; +}; + +// Bounds of each node (min, max) for its parent +layout(std430, set = 3, binding = 3) buffer NodeBounds { + vec4 nodeBounds[]; +}; + +layout(push_constant) uniform constants { + uint nodeOffset; + uint nodeCount; +} PushConstants; + +void GetChildBounds(int nodePtr, out vec3 boundsMin, out vec3 boundsMax) { + + if (nodePtr >= 0) { + boundsMin = nodeBounds[2 * nodePtr].xyz; + boundsMax = nodeBounds[2 * nodePtr + 1].xyz; + return; + } + + boundsMin = vec3(1e30); + boundsMax = vec3(-1e30); + + int triPtr = ~nodePtr; + bool endOfNode = false; + while (!endOfNode) { + vec3 v0 = bvhTriangles[triPtr].v0.xyz; + vec3 v1 = bvhTriangles[triPtr].v1.xyz; + vec3 v2 = bvhTriangles[triPtr].v2.xyz; + endOfNode = bvhTriangles[triPtr].v0.w > 0.0; + + boundsMin = min(boundsMin, min(v0, min(v1, v2))); + boundsMax = max(boundsMax, max(v0, max(v1, v2))); + triPtr++; + } + +} + +void main() { + + uint idx = gl_GlobalInvocationID.x; + if (idx >= PushConstants.nodeCount) + return; + + int nodeIdx = levelNodes[PushConstants.nodeOffset + idx]; + + int leftPtr = floatBitsToInt(nodes[nodeIdx].data3.x); + int rightPtr = floatBitsToInt(nodes[nodeIdx].data3.y); + + vec3 leftMin, leftMax, rightMin, rightMax; + GetChildBounds(leftPtr, leftMin, leftMax); + GetChildBounds(rightPtr, rightMin, rightMax); + + nodes[nodeIdx].data0 = vec4(leftMin, leftMax.x); + nodes[nodeIdx].data1 = vec4(leftMax.yz, rightMin.xy); + nodes[nodeIdx].data2 = vec4(rightMin.z, rightMax); + + nodeBounds[2 * nodeIdx] = vec4(min(leftMin, rightMin), 0.0); + nodeBounds[2 * nodeIdx + 1] = vec4(max(leftMax, rightMax), 0.0); + +} diff --git a/data/shader/raytracer/structures.hsh b/data/shader/raytracer/structures.hsh index 01ee80a09..4f9789cd5 100644 --- a/data/shader/raytracer/structures.hsh +++ b/data/shader/raytracer/structures.hsh @@ -27,6 +27,10 @@ struct Ray { int hitInstanceID; int currentInstanceID; + + // Hardware ray tracing returns the hit point on the triangle and its object space normal + vec2 hitBarycentrics; + vec3 hitGeometryNormal; }; struct RayPayload { @@ -142,6 +146,21 @@ struct RaytraceMaterial { uint transmissionColor; + // Hit group of a material graph in ray tracing pipelines, 0 without one + uint graphHitGroup; + uint graphParameterOffset; + float uvAnimationX; + float uvAnimationY; + + // A blend mode of common/material.hsh, rays pass through translucent surfaces except with TRANSLUCENT_HITS, shadow + // rays are dimmed by their opacity + uint blendMode; + // Of the inside of refracting surfaces, 1 for the others + float refractiveIndex; + + uint padding0; + uint padding1; + }; struct PackedLight { @@ -186,6 +205,10 @@ struct Instance { int nextInstance; int mask; + + // Device addresses of the normals of a deformed instance and the indices of its mesh, see GetTriangle + uvec2 deformedVertices; + uvec2 meshIndices; }; struct PackedBVHNode { @@ -207,14 +230,3 @@ struct PackedBVHTriangle { vec4 v1; vec4 v2; }; - -layout(push_constant) uniform constants { - int lightCount; - uint rayBufferOffset; - uint rayPayloadBufferOffset; - uint rayBufferSize; - int useRayBinning; - int padding0; - int padding1; - int padding2; -} PushConstants; diff --git a/data/shader/raytracer/surface.hsh b/data/shader/raytracer/surface.hsh index 0db76aec2..81f18af30 100644 --- a/data/shader/raytracer/surface.hsh +++ b/data/shader/raytracer/surface.hsh @@ -1,4 +1,8 @@ #extension GL_EXT_nonuniform_qualifier : require +#ifdef AE_HARDWARE_RAYTRACING +#extension GL_EXT_buffer_reference : require +#extension GL_EXT_buffer_reference_uvec2 : require +#endif #include #include @@ -6,6 +10,20 @@ #include #include <../brdf/surface.hsh> +#include <../common/texCoord.hsh> +#include <../common/opacity.hsh> + +#ifdef RAY_TRACING_PIPELINE +// The hit of the last ray of TraceClosest, hit objects can't be assigned or passed as out parameters +hitObjectEXT closestHitObject; +#endif + +#if defined(MATERIAL_GRAPH_HITS) && defined(RAY_TRACING_PIPELINE) +#include + +// The hit groups of material graphs are executed with the hit object of the ray +layout(location = 1) rayPayloadEXT MaterialGraphHit graphHit; +#endif Instance GetInstance(Ray ray) { @@ -13,9 +31,60 @@ Instance GetInstance(Ray ray) { } +#ifdef AE_HARDWARE_RAYTRACING +// Packed normal and tangent per vertex, written by the deformation pass +layout(buffer_reference, std430, buffer_reference_align = 8) readonly buffer DeformedVertexBuffer { + uvec2 data[]; +}; + +layout(buffer_reference, std430, buffer_reference_align = 4) readonly buffer MeshIndexBuffer { + uint data[]; +}; + +uint GetMeshIndex(uvec2 address, uint position) { + + // The lowest bit of the address marks 16 bit indices + MeshIndexBuffer indices = MeshIndexBuffer(uvec2(address.x & ~1u, address.y)); + if ((address.x & 1u) == 0u) + return indices.data[position]; + + uint word = indices.data[position >> 1u]; + return (position & 1u) > 0u ? word >> 16u : word & 0xFFFFu; + +} +#endif + +// The triangle of the mesh with the normals of a deformed instance, hardware ray tracing gets the hit positions from +// the acceleration structure Triangle GetTriangle(Ray ray, Instance instance) { - return UnpackTriangle(triangles[nonuniformEXT(instance.meshOffset)].data[nonuniformEXT(ray.hitID)]); + Triangle tri = UnpackTriangle(triangles[nonuniformEXT(instance.meshOffset)].data[nonuniformEXT(ray.hitID)]); + +#ifdef AE_HARDWARE_RAYTRACING + if (instance.deformedVertices != uvec2(0u)) { + DeformedVertexBuffer vertices = DeformedVertexBuffer(instance.deformedVertices); + uint firstIndex = uint(ray.hitID) * 3u; + uvec2 v0 = vertices.data[GetMeshIndex(instance.meshIndices, firstIndex)]; + uvec2 v1 = vertices.data[GetMeshIndex(instance.meshIndices, firstIndex + 1u)]; + uvec2 v2 = vertices.data[GetMeshIndex(instance.meshIndices, firstIndex + 2u)]; + + // The bitangent keeps the handedness of the undeformed triangle + float handedness = dot(cross(tri.n0 + tri.n1 + tri.n2, tri.t), tri.bt) < 0.0 ? -1.0 : 1.0; + + tri.n0 = unpackUnitVector(int(v0.x)).xyz; + tri.n1 = unpackUnitVector(int(v1.x)).xyz; + tri.n2 = unpackUnitVector(int(v2.x)).xyz; + + vec3 tangent = unpackUnitVector(int(v0.y)).xyz + unpackUnitVector(int(v1.y)).xyz + unpackUnitVector(int(v2.y)).xyz; + // Meshes without tangents have zero tangents, which unpack to almost zero + if (dot(tangent, tangent) > 0.01) { + tri.t = normalize(tangent); + tri.bt = handedness * normalize(cross(tri.n0 + tri.n1 + tri.n2, tri.t)); + } + } +#endif + + return tri; } @@ -26,7 +95,7 @@ Material GetTriangleMaterial(Triangle tri, int materialOffset, out RaytraceMater mat.ID = rayMat.ID; mat.baseColor = vec3(rayMat.baseR, rayMat.baseG, rayMat.baseB); - mat.emissiveColor = vec3(rayMat.emissR, rayMat.emissG, rayMat.emissB); + mat.emissiveColor = vec3(rayMat.emissR, rayMat.emissG, rayMat.emissB) * globalData.preExposure; mat.transmissiveColor = unpackColorVector(int(rayMat.transmissionColor)).rgb; mat.transmissive = any(greaterThan(mat.transmissiveColor, vec3(0.0))); @@ -41,6 +110,9 @@ Material GetTriangleMaterial(Triangle tri, int materialOffset, out RaytraceMater mat.normalScale = rayMat.normalScale; mat.displacementScale = 0.0; + mat.blendMode = rayMat.blendMode; + mat.refractiveIndex = rayMat.refractiveIndex; + return mat; } @@ -48,9 +120,11 @@ void TransformTriangle(inout Triangle tri, Instance instance) { mat4 matrix = inverse(mat4(transpose(instance.inverseMatrix))); +#ifndef AE_HARDWARE_RAYTRACING tri.v0 = vec3(matrix * vec4(tri.v0, 1.0)); tri.v1 = vec3(matrix * vec4(tri.v1, 1.0)); tri.v2 = vec3(matrix * vec4(tri.v2, 1.0)); +#endif mat3 normalMatrix = transpose(mat3(transpose(instance.inverseMatrix))); tri.n0 = normalize(normalMatrix * tri.n0); @@ -71,13 +145,17 @@ Surface GetSurfaceParameters(Instance instance, Triangle tri, Ray ray, RaytraceMaterial rayMat; Material mat = GetTriangleMaterial(tri, instance.materialOffset, rayMat); - // The ray doesn't provide us with the barrycentric coordinates - // so we intersect again. +#ifdef AE_HARDWARE_RAYTRACING + float dist = ray.hitDistance; + vec2 barrycentric = ray.hitBarycentrics; +#else + // The software traversal doesn't provide the barycentric coordinates, so we intersect again vec3 sol; IntersectTriangle(ray, tri.v0, tri.v1, tri.v2, sol); float dist = sol.x; vec2 barrycentric = sol.yz; +#endif float s = barrycentric.x; float t = barrycentric.y; @@ -89,16 +167,29 @@ Surface GetSurfaceParameters(Instance instance, Triangle tri, Ray ray, vec3 normal = normalize(r * tri.n0 + s * tri.n1 + t * tri.n2); vec4 vertexColor = r * tri.color0 + s * tri.color1 + t * tri.color2; +#ifdef AE_HARDWARE_RAYTRACING + // The normal matrix keeps the front face of transforms with reversed winding + mat3 normalMatrix = transpose(mat3(transpose(instance.inverseMatrix))); +#ifdef AE_POSITION_FETCH + vec3 triangleNormal = normalize(normalMatrix * ray.hitGeometryNormal); +#else + // The undeformed triangle of the mesh, deformed instances only use it to find the front face + vec3 triangleNormal = normalize(normalMatrix * cross(tri.v0 - tri.v1, tri.v0 - tri.v2)); +#endif +#else // Produces some problems in the bottom left corner of the Sponza scene, // but fixes the cube. Should work in theory. vec3 triangleNormal = normalize(cross(tri.v0 - tri.v1, tri.v0 - tri.v2)); // Transforms with reversed winding need the same front-face correction as in the rasterizer float orientation = determinant(mat3(transpose(instance.inverseMatrix))) < 0.0 ? -1.0 : 1.0; triangleNormal *= orientation; +#endif bool flipNormal = dot(triangleNormal, ray.direction) > 0.0; bool twoSided = rayMat.twoSided > 0 || mat.transmissive; backfaceHit = twoSided || rayMat.cullBackFaces == 0 ? false : flipNormal; triangleNormal *= flipNormal && twoSided ? -1.0 : 1.0; + // Rays leave refracting surfaces through their back faces + mat.refractiveIndex = flipNormal ? 1.0 / mat.refractiveIndex : mat.refractiveIndex; vec3 geometryNormal = triangleNormal; @@ -109,33 +200,59 @@ Surface GetSurfaceParameters(Instance instance, Triangle tri, Ray ray, normal = normalize(2.0 * SampleTerrainNormalBilinear(rayMat.terrainNormalTexture, 0.0, terrainTexCoord) - 1.0); } - texCoord = rayMat.invertUVs > 0 ? vec2(texCoord.x, 1.0 - texCoord.y) : texCoord; - texCoord *= rayMat.tiling; + texCoord = TransformTexCoord(texCoord, rayMat.invertUVs > 0, vec2(rayMat.uvAnimationX, rayMat.uvAnimationY), rayMat.tiling); int level = textureLevel; - //mat.opacity *= vertexColor.a; - mat.baseColor *= rayMat.useVertexColors > 0 ? vertexColor.rgb : vec3(1.0); - mat.baseColor *= SampleBaseColorBilinear(rayMat.baseColorTexture, float(level), texCoord); - mat.opacity *= SampleOpacityBilinear(rayMat.opacityTexture, float(level), texCoord); - - mat.roughness *= SampleRoughnessBilinear(rayMat.roughnessTexture, float(level), texCoord); - mat.metalness *= SampleMetalnessBilinear(rayMat.metalnessTexture, float(level), texCoord); - mat.ao *= SampleAoBilinear(rayMat.aoTexture, float(level), texCoord); - // Need to have the texture level to go to near zero, otherwise we will have light leaks - mat.emissiveColor *= SampleEmissiveBilinear(rayMat.emissiveTexture, max(0.0, float(level - 3.0)), texCoord); // Account for changing texture coord direction vec3 bitangent = rayMat.invertUVs > 0 ? tri.bt : -tri.bt; mat3 TBN = mat3(tri.t, bitangent, normal); - // Sample normal map - if (rayMat.normalTexture >= 0 && useNormalMaps) { - vec3 texNormal = 2.0 * SampleNormalBilinear(rayMat.normalTexture, float(level), texCoord) - 1.0; - texNormal = TBN * texNormal; - // Make sure we don't divide by zero - // The normalize function crashes the program in case of vec3(0.0) - texNormal /= max(length(texNormal), 0.00001); - normal = mix(normal, texNormal, saturate(mat.normalScale)); +#if defined(MATERIAL_GRAPH_HITS) && defined(RAY_TRACING_PIPELINE) + if (rayMat.graphHitGroup > 0u) { + graphHit.tangentFrame = TBN; + graphHit.color = packUnorm4x8(vertexColor); + graphHit.texCoord = texCoord; + graphHit.frontFacing = flipNormal ? -1.0 : 1.0; + graphHit.textureLevel = float(level); + graphHit.parameterOffset = rayMat.graphParameterOffset; + + hitObjectExecuteShaderEXT(closestHitObject, 1); + + // The G-buffer limits these values, an albedo above one would amplify itself in the bounces of the DDGI + mat.baseColor = saturate(graphHit.baseColor); + mat.roughness = saturate(graphHit.roughness); + mat.metalness = saturate(graphHit.metalness); + mat.ao = saturate(graphHit.ao); + mat.emissiveColor = graphHit.emissive * globalData.preExposure; + + vec3 graphNormal = TBN * graphHit.normal; + if (useNormalMaps && dot(graphNormal, graphNormal) > 0.0) + normal = normalize(graphNormal); + } + else +#endif + { + //mat.opacity *= vertexColor.a; + mat.baseColor *= rayMat.useVertexColors > 0 ? vertexColor.rgb : vec3(1.0); + mat.baseColor *= SampleBaseColorBilinear(rayMat.baseColorTexture, float(level), texCoord); + mat.opacity *= SampleOpacityBilinear(rayMat.opacityTexture, float(level), texCoord); + + mat.roughness *= SampleRoughnessBilinear(rayMat.roughnessTexture, float(level), texCoord); + mat.metalness *= SampleMetalnessBilinear(rayMat.metalnessTexture, float(level), texCoord); + mat.ao *= SampleAoBilinear(rayMat.aoTexture, float(level), texCoord); + // Need to have the texture level to go to near zero, otherwise we will have light leaks + mat.emissiveColor *= SampleEmissiveBilinear(rayMat.emissiveTexture, max(0.0, float(level - 3.0)), texCoord); + + // Sample normal map + if (rayMat.normalTexture >= 0 && useNormalMaps) { + vec3 texNormal = 2.0 * SampleNormalBilinear(rayMat.normalTexture, float(level), texCoord) - 1.0; + texNormal = TBN * texNormal; + // Make sure we don't divide by zero + // The normalize function crashes the program in case of vec3(0.0) + texNormal /= max(length(texNormal), 0.00001); + normal = mix(normal, texNormal, saturate(mat.normalScale)); + } } normal = dot(normal, triangleNormal) < 0.0 && rayMat.twoSided > 0 ? -normal : normal; @@ -161,22 +278,49 @@ Surface GetSurfaceParameters(Instance instance, Triangle tri, Ray ray, } +// The surface of the closest hit of a ray +Surface GetHitSurface(Ray ray, bool useNormalMaps, out bool backfaceHit, int textureLevel) { + + Instance instance = GetInstance(ray); + Triangle tri = GetTriangle(ray, instance); + return GetSurfaceParameters(instance, tri, ray, useNormalMaps, backfaceHit, textureLevel); + +} + Surface GetSurfaceParameters(Instance instance, Triangle tri, Ray ray, bool useNormalMaps, int textureLevel) { bool normalFlipped; return GetSurfaceParameters(instance, tri, ray, useNormalMaps, normalFlipped, textureLevel); } -float GetOpacity(Triangle tri, vec2 barrycentric, int materialOffset, int textureLevel) { +float SampleMaterialOpacity(RaytraceMaterial rayMat, Triangle tri, vec2 barrycentric, int textureLevel) { float s = barrycentric.x; float t = barrycentric.y; float r = 1.0 - s - t; - RaytraceMaterial rayMat = materials[tri.materialIndex + materialOffset]; - - float vertexAlpha = r * tri.color0.a + s * tri.color1.a + t * tri.color2.a; vec2 texCoord = r * tri.uv0 + s * tri.uv1 + t * tri.uv2; - texCoord = rayMat.invertUVs > 0 ? vec2(texCoord.x, 1.0 - texCoord.y) : texCoord; + texCoord = TransformTexCoord(texCoord, rayMat.invertUVs > 0, vec2(rayMat.uvAnimationX, rayMat.uvAnimationY), rayMat.tiling); - return SampleOpacityBilinear(rayMat.opacityTexture, float(textureLevel), texCoord * rayMat.tiling) - * rayMat.opacity; + return SampleOpacityBilinear(rayMat.opacityTexture, float(textureLevel), texCoord); +} + +// Surfaces are cut out by their opacity map only, like in the raster passes. Rays pass through translucent ones, +// the path tracer blends them itself (TRANSLUCENT_HITS) +float GetCutoutOpacity(Triangle tri, vec2 barrycentric, int materialOffset, int textureLevel) { + RaytraceMaterial rayMat = materials[tri.materialIndex + materialOffset]; +#ifdef TRANSLUCENT_HITS + if (rayMat.blendMode != blendModeNone) + return 1.0; +#else + if (rayMat.blendMode != blendModeNone) + return 0.0; +#endif + return SampleMaterialOpacity(rayMat, tri, barrycentric, textureLevel); +} + +// The share of the light a surface blocks, translucent ones block it by their opacity, additive ones not at all +float GetOpacity(Triangle tri, vec2 barrycentric, int materialOffset, int textureLevel) { + RaytraceMaterial rayMat = materials[tri.materialIndex + materialOffset]; + if (rayMat.blendMode == blendModeAdditive) + return 0.0; + return SampleMaterialOpacity(rayMat, tri, barrycentric, textureLevel) * rayMat.opacity; } diff --git a/data/shader/raytracer/texture.hsh b/data/shader/raytracer/texture.hsh index 591c858ea..85953151c 100644 --- a/data/shader/raytracer/texture.hsh +++ b/data/shader/raytracer/texture.hsh @@ -81,12 +81,12 @@ vec3 SampleTerrainNormalBilinear(int textureId, float mip, vec2 texCoord) { vec4 SampleEnvironmentMap(vec3 v) { - return textureLod(environmentMap, v, 0); + return textureLod(environmentMap, v, 0) * globalData.skyCubemapExposure; } vec4 SampleEnvironmentMap(vec3 v, float lod) { - return textureLod(environmentMap, v, lod); + return textureLod(environmentMap, v, lod) * globalData.skyCubemapExposure; } \ No newline at end of file diff --git a/data/shader/raytracer/traceClosest.csh b/data/shader/raytracer/traceClosest.csh index d1d00cc2a..aa1827c2c 100644 --- a/data/shader/raytracer/traceClosest.csh +++ b/data/shader/raytracer/traceClosest.csh @@ -22,12 +22,7 @@ void main() { ray.hitID = -1; ray.hitDistance = 0.0; if (ray.ID >= 0) { - // Find any triangle in the BVH -#ifdef OPACITY_CHECK - HitClosestTransparency(ray, INSTANCE_MASK_ALL, offset, INF); -#else - HitClosest(ray, INSTANCE_MASK_ALL, offset, INF); -#endif + HitClosestOpacityCheck(ray, INSTANCE_MASK_CLOSEST, offset, INF); } uint writeOffset = PushConstants.rayBufferOffset * PushConstants.rayBufferSize; diff --git a/data/shader/raytracer/traceDispatch.csh b/data/shader/raytracer/traceDispatch.csh index 142de4a8f..7c94bfc71 100644 --- a/data/shader/raytracer/traceDispatch.csh +++ b/data/shader/raytracer/traceDispatch.csh @@ -22,6 +22,14 @@ void main() { dispatch.numGroupsZ = uint(1); indirectCommands[0] = dispatch; + + // Ray generation stages of ray tracing pipelines are launched per ray + DispatchIndirectCommand traceRays; + traceRays.numGroupsX = max(rayCount, uint(1)); + traceRays.numGroupsY = uint(1); + traceRays.numGroupsZ = uint(1); + + indirectCommands[1] = traceRays; writeAtomic[0] = uint(0); diff --git a/data/shader/raytracer/traceShadow.csh b/data/shader/raytracer/traceShadow.csh new file mode 100644 index 000000000..00795aad1 --- /dev/null +++ b/data/shader/raytracer/traceShadow.csh @@ -0,0 +1,21 @@ +#define LOCAL_STACK + +#include +#include + +layout (local_size_x = 32) in; + +void main() { + + uint idx = gl_GlobalInvocationID.x; + if (idx >= deferredShadowRayCount) + return; + + Ray ray; + ray.origin = deferredShadowRays[idx].origin.xyz; + ray.direction = deferredShadowRays[idx].direction.xyz; + + uint lightIdx = floatBitsToUint(deferredShadowRays[idx].direction.w); + deferredLights[lightIdx].w = HitAnyTransparency(ray, INSTANCE_MASK_SHADOW_TRANSPARENCY, 0.0, deferredShadowRays[idx].origin.w); + +} diff --git a/data/shader/raytracer/tracing.hsh b/data/shader/raytracer/tracing.hsh index 708a7d240..bfd49b2c7 100644 --- a/data/shader/raytracer/tracing.hsh +++ b/data/shader/raytracer/tracing.hsh @@ -1,3 +1,10 @@ +// Ray generation stages of ray tracing pipelines launch one invocation per element like a compute dispatch +#ifdef RAY_TRACING_PIPELINE +#define INVOCATION_ID gl_LaunchIDEXT +#else +#define INVOCATION_ID gl_GlobalInvocationID +#endif + #include #include #include @@ -9,31 +16,25 @@ #include <../common/octahedron.hsh> #include <../common/flatten.hsh> +layout(push_constant) uniform constants { + int lightCount; + uint rayBufferOffset; + uint rayPayloadBufferOffset; + uint rayBufferSize; +} PushConstants; + // We use double buffering for the ray and payload buffers, // which means the buffer has an actual size of rayBufferSize * 2 // Also note that the payload offset is different from the ray offset // as rays are written two times per bounce or execution, while payloads // are just written by the shader of the user -uint DetermineRayBin(Ray ray) { - ivec2 coord = ivec2(UnitVectorToOctahedron(ray.direction) * 8.0); - return Flatten2D(coord, ivec2(8)); -} - -Ray AddRayToBin(Ray ray) { - if (PushConstants.useRayBinning == 0) return ray; - uint bin = DetermineRayBin(ray); - atomicAdd(rayBinCounters[bin], 1u); - ray.hitID = int(bin); - return ray; -} - bool IsRayInvocationValid() { - return gl_GlobalInvocationID.x < readAtomic[0]; + return INVOCATION_ID.x < readAtomic[0]; } uint GetRayInvocation() { - return gl_GlobalInvocationID.x; + return INVOCATION_ID.x; } bool IsRayIndexValid(uint idx) { @@ -41,12 +42,12 @@ bool IsRayIndexValid(uint idx) { } Ray ReadRay() { - uint idx = (1u - PushConstants.rayBufferOffset) * PushConstants.rayBufferSize + gl_GlobalInvocationID.x; + uint idx = (1u - PushConstants.rayBufferOffset) * PushConstants.rayBufferSize + INVOCATION_ID.x; return UnpackRay(rays[idx]); } RayPayload ReadRayPayload() { - uint idx = (1u - PushConstants.rayPayloadBufferOffset) * PushConstants.rayBufferSize + gl_GlobalInvocationID.x; + uint idx = (1u - PushConstants.rayPayloadBufferOffset) * PushConstants.rayBufferSize + INVOCATION_ID.x; return UnpackRayPayload(rayPayloads[idx]); } @@ -61,14 +62,12 @@ RayPayload ReadRayPayload(uint idx) { } void WriteRay(Ray ray) { - ray = AddRayToBin(ray); uint offset = PushConstants.rayBufferOffset * PushConstants.rayBufferSize; uint idx = atomicAdd(writeAtomic[0], uint(1)) + offset; rays[idx] = PackRay(ray); } void WriteRay(Ray ray, RayPayload payload) { - ray = AddRayToBin(ray); uint rayOffset = PushConstants.rayBufferOffset * PushConstants.rayBufferSize; uint payloadOffset = PushConstants.rayPayloadBufferOffset * PushConstants.rayBufferSize; uint idx = atomicAdd(writeAtomic[0], uint(1)); @@ -77,14 +76,12 @@ void WriteRay(Ray ray, RayPayload payload) { } void WriteRay(Ray ray, uint idx) { - ray = AddRayToBin(ray); idx += PushConstants.rayBufferOffset * PushConstants.rayBufferSize; atomicAdd(writeAtomic[0], uint(1)); rays[idx] = PackRay(ray); } void WriteRay(Ray ray, RayPayload payload, uint idx) { - ray = AddRayToBin(ray); uint rayOffset = PushConstants.rayBufferOffset * PushConstants.rayBufferSize; uint payloadOffset = PushConstants.rayPayloadBufferOffset * PushConstants.rayBufferSize; atomicAdd(writeAtomic[0], uint(1)); diff --git a/data/shader/reflection/atrous.csh b/data/shader/reflection/atrous.csh index dfc7d130b..5261ce28c 100644 --- a/data/shader/reflection/atrous.csh +++ b/data/shader/reflection/atrous.csh @@ -7,6 +7,8 @@ #include <../common/material.hsh> #include <../common/normalencode.hsh> +#include <../common/denoiser.hsh> + layout (local_size_x = 16, local_size_y = 16) in; layout(set = 3, binding = 0, rgba16f) writeonly uniform image2D outputImage; @@ -15,6 +17,7 @@ layout(set = 3, binding = 2) uniform sampler2D depthTexture; layout(set = 3, binding = 3) uniform sampler2D normalTexture; layout(set = 3, binding = 4) uniform sampler2D roughnessTexture; layout(set = 3, binding = 5) uniform usampler2D materialIdxTexture; +layout(set = 3, binding = 6) uniform sampler2D historyLengthTexture; #ifdef STEP_SIZE1 const int kernelRadius = 2; @@ -26,6 +29,8 @@ const int kernelRadius = 4; const int kernelRadius = 8; #endif +const int stepSize = kernelRadius / 2; + const uint sharedDataSize = (gl_WorkGroupSize.x + 2 * kernelRadius) * (gl_WorkGroupSize.y + 2 * kernelRadius); const ivec2 unflattenedSharedDataSize = ivec2(gl_WorkGroupSize) + 2 * kernelRadius; @@ -44,19 +49,24 @@ struct PackedPixelData { #else uvec4 data; #endif - float depth; }; +// Separate arrays, a struct with the depth would be padded to 32 bytes and exceed 32 KB of shared memory on some devices shared PackedPixelData pixelData[sharedDataSize]; +shared float pixelDepth[sharedDataSize]; +shared uint groupFilters; layout(push_constant) uniform constants { - int stepSize; float strength; float roughnessCutoff; } pushConstants; const float kernelWeights[3] = { 1.0, 2.0 / 3.0, 1.0 / 6.0 }; +// In pixels, the three passes together reach 14 pixels +const float maxBlurRadius = 16.0; +const float minBlurRadius = 1.5; + PackedPixelData PackPixelData(PixelData data) { PackedPixelData compressed; @@ -71,8 +81,6 @@ PackedPixelData PackPixelData(PixelData data) { compressed.data.w = packHalf2x16(vec2(data.normal.z, data.roughness)); #endif - compressed.depth = data.depth; - return compressed; } @@ -91,7 +99,6 @@ PixelData UnpackPixelData(PackedPixelData compressed) { data.normal.z = temp.x; data.roughness = temp.y; #endif - data.depth = compressed.depth; return data; } @@ -112,12 +119,15 @@ void LoadGroupSharedData() { data.color = texelFetch(inputTexture, texel, 0); - data.depth = texelFetch(depthTexture, texel, 0).r; + // Linear depth, zero marks the sky + float depth = texelFetch(depthTexture, texel, 0).r; + data.depth = depth == 1.0 ? 0.0 : ConvertDepthToViewSpaceDepth(depth); data.roughness = texelFetch(roughnessTexture, texel, 0).r; data.normal = DecodeNormal(texelFetch(normalTexture, texel, 0).rg); pixelData[i] = PackPixelData(data); + pixelDepth[i] = data.depth; } barrier(); @@ -128,39 +138,9 @@ PixelData GetPixel(ivec2 pixelOffset) { ivec2 pixel = ivec2(gl_LocalInvocationID) + ivec2(kernelRadius); int sharedMemoryIdx = Flatten2D(pixel + pixelOffset, unflattenedSharedDataSize); - return UnpackPixelData(pixelData[sharedMemoryIdx]); - -} - -float Luma(vec3 color) { - - const vec3 luma = vec3(0.299, 0.587, 0.114); - return dot(color, luma); - -} - -float ComputeEdgeStoppingWeight(float centerLuminance, float sampleLuminance, - vec3 centerNormal, vec3 sampleNormal, - float centerDepth, float sampleDepth, - float centerRoughness, float sampleRoughness, - float luminancePhi, float normalPhi, - float depthPhi, float roughnessPhi) { - - const float epsilon = 1e-10; - - float luminanceDiff = abs(centerLuminance - sampleLuminance); - float luminanceWeight = min(exp(-luminanceDiff / (luminancePhi + epsilon)), 1.0); - - float normalDiff = saturate(dot(centerNormal, sampleNormal)); - float normalWeight = min(pow(normalDiff, normalPhi), 1.0); - - float depthDiff = abs(centerDepth - sampleDepth); - float depthWeight = min(exp(-depthDiff * depthPhi), 1.0); - - float roughnessDiff = abs(centerRoughness - sampleRoughness); - float roughnessWeight = min(exp(-roughnessDiff / (roughnessPhi + epsilon)), 1.0); - - return luminanceWeight * normalWeight * depthWeight * roughnessWeight; + PixelData data = UnpackPixelData(pixelData[sharedMemoryIdx]); + data.depth = pixelDepth[sharedMemoryIdx]; + return data; } @@ -190,82 +170,117 @@ float GetFilteredVariance(ivec2 pixel) { void main() { - LoadGroupSharedData(); - ivec2 pixel = ivec2(gl_GlobalInvocationID); ivec2 resolution = imageSize(outputImage); + bool insideImage = pixel.x < resolution.x && pixel.y < resolution.y; + + float depth = insideImage ? texelFetch(depthTexture, pixel, 0).r : 1.0; + float roughness = insideImage ? texelFetch(roughnessTexture, pixel, 0).r : 1.0; + vec4 moments = insideImage ? texelFetch(historyLengthTexture, pixel, 0) : vec4(0.0); + float historyLength = moments.b; - if (pixel.x >= resolution.x || pixel.y >= resolution.y) + // The projection flips y, its scale is negative + float pixelWorldSize = 2.0 * abs(ConvertDepthToViewSpaceDepth(depth)) / (abs(globalData.pMatrix[1][1]) * float(resolution.y)); + // The blur radius follows the reflection lobe (roughness squared times hit distance), short histories get more + float lobeRadius = sqr(roughness) * DecodeHitDistance(moments.a) / pixelWorldSize; + lobeRadius = max(lobeRadius, maxBlurRadius / max(historyLength, 1.0)); + + float blurRadius = clamp(lobeRadius, minBlurRadius, maxBlurRadius); + + // Below half the step size the taps of this pass have no weight left + bool filterPixel = insideImage && depth < 1.0 && roughness < pushConstants.roughnessCutoff && + blurRadius >= 0.5 * float(stepSize); + + if (gl_LocalInvocationIndex == 0) + groupFilters = 0u; + barrier(); + if (filterPixel) + atomicOr(groupFilters, 1u); + barrier(); + + if (groupFilters != 0u) + LoadGroupSharedData(); + + if (!insideImage || depth == 1.0) return; + if (!filterPixel) { + imageStore(outputImage, pixel, texelFetch(inputTexture, pixel, 0)); + return; + } + vec2 texCoord = (vec2(pixel) + 0.5) / vec2(resolution); + vec2 texelSize = 1.0 / vec2(resolution); + + vec3 viewRay = GetViewRay(texCoord); + vec3 viewRayDx = GetViewRay(texCoord + vec2(texelSize.x, 0.0)) - viewRay; + vec3 viewRayDy = GetViewRay(texCoord + vec2(0.0, texelSize.y)) - viewRay; PixelData centerPixelData = GetPixel(ivec2(0)); - + vec4 centerColor = centerPixelData.color; - float centerDepth = centerPixelData.depth; vec3 centerNormal = centerPixelData.normal; float centerRoughness = centerPixelData.roughness; - if (centerDepth == 1.0) - return; - float centerLuminance = Luma(centerColor.rgb); - float centerLinearDepth = ConvertDepthToViewSpaceDepth(centerDepth); - + vec3 centerPosition = viewRay * centerPixelData.depth; + vec4 outputColor = centerColor; float totalWeight = 1.0; float variance = GetFilteredVariance(pixel); float stdDeviation = sqrt(max(0.0, variance)); - vec3 viewDir = normalize(ConvertDepthToViewSpace(centerDepth, texCoord)); - float NdotV = abs(dot(viewDir, centerNormal)); - float depthPhi = max(32.0, NdotV * 256.0 / max(1.0, abs(centerLinearDepth))); - - if (centerRoughness < pushConstants.roughnessCutoff) { - const int radius = 2; - for (int x = -radius; x <= radius; x++) { - for (int y = -radius; y <= radius; y++) { - ivec2 samplePixel = pixel + ivec2(x, y) * pushConstants.stepSize; - - if (samplePixel.x >= resolution.x || samplePixel.y >= resolution.y - || (x == 0 && y == 0)) - continue; + // All weights of a tap go into one exponent, the terms that don't depend on the tap are computed once. + // The distance to the surface plane is affine in the offset since the view ray is + const float log2e = 1.442695; + const float normalPhi = 256.0; + const float depthPhi = 128.0; + const float roughnessPhi = 0.05; + float planeRay = dot(viewRay, centerNormal); + float planeRayDx = dot(viewRayDx, centerNormal); + float planeRayDy = dot(viewRayDy, centerNormal); + float planeOffset = dot(centerPosition, centerNormal); + float planeScale = depthPhi * log2e / abs(centerPosition.z); + float luminanceScale = log2e / (stdDeviation * pushConstants.strength + 1e-10); + float roughnessScale = log2e / roughnessPhi; + float distanceScale = log2e * float(stepSize * stepSize) / sqr(blurRadius); + + const int radius = 2; + for (int x = -radius; x <= radius; x++) { + for (int y = -radius; y <= radius; y++) { + ivec2 offset = ivec2(x, y) * stepSize; + ivec2 samplePixel = pixel + offset; - PixelData samplePixelData = GetPixel(ivec2(x, y) * pushConstants.stepSize); + if (samplePixel.x >= resolution.x || samplePixel.y >= resolution.y || + samplePixel.x < 0 || samplePixel.y < 0 + || (x == 0 && y == 0)) + continue; - if (samplePixelData.depth == 1.0) - continue; + PixelData samplePixelData = GetPixel(offset); - vec4 sampleColor = samplePixelData.color; - vec3 sampleNormal = samplePixelData.normal; + if (samplePixelData.depth == 0.0) + continue; - float sampleDepth = samplePixelData.depth; - float sampleLuminance = Luma(sampleColor.rgb); + vec4 sampleColor = samplePixelData.color; - float sampleRoughness = samplePixelData.roughness; + // The distance to the surface plane stays stable at grazing angles, unlike the depth + float planeDistance = samplePixelData.depth * (planeRay + float(offset.x) * planeRayDx + + float(offset.y) * planeRayDy) - planeOffset; + float normalDot = max(dot(centerNormal, samplePixelData.normal), 1e-6); - float kernelWeight = kernelWeights[abs(x)] * kernelWeights[abs(y)]; - float edgeStoppingWeight = ComputeEdgeStoppingWeight( - centerLuminance, sampleLuminance, - centerNormal, sampleNormal, - centerDepth, sampleDepth, - centerRoughness, sampleRoughness, - stdDeviation * pushConstants.strength, - 256.0, 128.0, 0.05); + float exponent = abs(centerLuminance - Luma(sampleColor.rgb)) * luminanceScale + + abs(planeDistance) * planeScale + abs(centerRoughness - samplePixelData.roughness) * roughnessScale + + float(x * x + y * y) * distanceScale - normalPhi * log2(normalDot); + float weight = kernelWeights[abs(x)] * kernelWeights[abs(y)] * exp2(-exponent); - float weight = kernelWeight * edgeStoppingWeight; - - totalWeight += weight; - outputColor += vec4(vec3(weight), weight * weight) * sampleColor; - } + totalWeight += weight; + outputColor += vec4(vec3(weight), weight * weight) * sampleColor; } - - outputColor = outputColor / vec4(vec3(totalWeight), totalWeight * totalWeight); } + outputColor = outputColor / vec4(vec3(totalWeight), totalWeight * totalWeight); + imageStore(outputImage, pixel, outputColor); - //imageStore(outputImage, pixel, vec4(centerColor.a)); } \ No newline at end of file diff --git a/data/shader/reflection/reflectionData.csh b/data/shader/reflection/reflectionData.csh new file mode 100644 index 000000000..eb5d9cf55 --- /dev/null +++ b/data/shader/reflection/reflectionData.csh @@ -0,0 +1,128 @@ +#include <../globals.hsh> +#include <../common/convert.hsh> +#include <../common/stencil.hsh> + +// The G-buffer, but the reflections start on the closest surface: the visible ocean (OCEAN) or the closest alpha blended +// surface (FRONT_LAYER) if they are in front of it + +layout (local_size_x = 8, local_size_y = 8) in; + +layout (set = 3, binding = 0) uniform sampler2D depthIn; +layout (set = 3, binding = 1) uniform sampler2D normalIn; +layout (set = 3, binding = 2) uniform sampler2D geometryNormalIn; +layout (set = 3, binding = 3) uniform sampler2D roughnessMetallicAoIn; +layout (set = 3, binding = 4) uniform sampler2D velocityIn; +layout (set = 3, binding = 5) uniform usampler2D materialIdxIn; + +#ifdef OCEAN +layout (set = 3, binding = 6) uniform sampler2D oceanDepthIn; +layout (set = 3, binding = 7) uniform sampler2D oceanNormalIn; +layout (set = 3, binding = 8) uniform usampler2D oceanStencilIn; +#endif +#ifdef FRONT_LAYER +layout (set = 3, binding = 22) uniform sampler2D frontLayerDepthIn; +layout (set = 3, binding = 23) uniform sampler2D frontLayerNormalIn; +layout (set = 3, binding = 24) uniform sampler2D frontLayerGeometryNormalIn; +layout (set = 3, binding = 25) uniform sampler2D frontLayerRoughnessMetallicAoIn; +layout (set = 3, binding = 26) uniform sampler2D frontLayerVelocityIn; +layout (set = 3, binding = 27) uniform usampler2D frontLayerMaterialIdxIn; +#endif + +layout (set = 3, binding = 9, r32f) writeonly uniform image2D depthOut; +layout (set = 3, binding = 10, rg16f) writeonly uniform image2D normalOut; +layout (set = 3, binding = 11, rg16f) writeonly uniform image2D geometryNormalOut; +layout (set = 3, binding = 12, rgba8) writeonly uniform image2D roughnessMetallicAoOut; +layout (set = 3, binding = 13, rg16f) writeonly uniform image2D velocityOut; +layout (set = 3, binding = 14, r16ui) writeonly uniform uimage2D materialIdxOut; + +// Like the G-buffer downscale, the half resolution data is the top left pixel of each 2x2 block +layout (set = 3, binding = 15, r32f) writeonly uniform image2D halfResDepthOut; +layout (set = 3, binding = 16, rg16f) writeonly uniform image2D halfResNormalOut; +layout (set = 3, binding = 17, rg16f) writeonly uniform image2D halfResGeometryNormalOut; +layout (set = 3, binding = 18, rgba8) writeonly uniform image2D halfResRoughnessMetallicAoOut; +layout (set = 3, binding = 19, rg16f) writeonly uniform image2D halfResVelocityOut; +layout (set = 3, binding = 20, r16ui) writeonly uniform uimage2D halfResMaterialIdxOut; +layout (set = 3, binding = 21, r8i) writeonly uniform iimage2D halfResOffsetOut; + +layout(push_constant) uniform constants { + uint oceanMaterialIdx; +} PushConstants; + +void Store(ivec2 pixel, float depth, vec2 normal, vec2 geometryNormal, vec4 roughnessMetallicAo, + vec2 velocity, uint materialIdx) { + + imageStore(depthOut, pixel, vec4(depth)); + imageStore(normalOut, pixel, vec4(normal, 0.0, 0.0)); + imageStore(geometryNormalOut, pixel, vec4(geometryNormal, 0.0, 0.0)); + imageStore(roughnessMetallicAoOut, pixel, roughnessMetallicAo); + imageStore(velocityOut, pixel, vec4(velocity, 0.0, 0.0)); + imageStore(materialIdxOut, pixel, uvec4(materialIdx)); + + ivec2 halfResPixel = pixel / 2; + if (pixel.x % 2 != 0 || pixel.y % 2 != 0 || any(greaterThanEqual(halfResPixel, imageSize(halfResDepthOut)))) + return; + + imageStore(halfResDepthOut, halfResPixel, vec4(depth)); + imageStore(halfResNormalOut, halfResPixel, vec4(normal, 0.0, 0.0)); + imageStore(halfResGeometryNormalOut, halfResPixel, vec4(geometryNormal, 0.0, 0.0)); + imageStore(halfResRoughnessMetallicAoOut, halfResPixel, roughnessMetallicAo); + imageStore(halfResVelocityOut, halfResPixel, vec4(velocity, 0.0, 0.0)); + imageStore(halfResMaterialIdxOut, halfResPixel, uvec4(materialIdx)); + imageStore(halfResOffsetOut, halfResPixel, ivec4(0)); + +} + +void main() { + + ivec2 resolution = imageSize(depthOut); + ivec2 pixel = ivec2(gl_GlobalInvocationID.xy); + if (pixel.x >= resolution.x || pixel.y >= resolution.y) + return; + + float depth = texelFetch(depthIn, pixel, 0).r; + +#ifdef FRONT_LAYER + // Starts out as a copy of the depth, the surfaces only write where they are in front + float frontLayerDepth = texelFetch(frontLayerDepthIn, pixel, 0).r; +#else + float frontLayerDepth = 1.0; +#endif + +#ifdef OCEAN + float oceanDepth = texelFetch(oceanDepthIn, pixel, 0).r; + StencilFeatures features = DecodeStencilFeatures(texelFetch(oceanStencilIn, pixel, 0).r); + bool oceanVisible = oceanDepth < 1.0 && oceanDepth <= depth && !features.underWaterPixel; + + if (oceanVisible && oceanDepth <= frontLayerDepth) { + vec2 texCoord = (vec2(pixel) + 0.5) / vec2(resolution); + vec3 viewPos = ConvertDepthToViewSpace(oceanDepth, texCoord); + vec3 worldPos = vec3(globalData.ivMatrix * vec4(viewPos, 1.0)); + + vec2 normal = texelFetch(oceanNormalIn, pixel, 0).rg; + + // Same velocity as the ocean surface pass, which only accounts for the camera movement + vec4 last = globalData.pvMatrixLast * vec4(worldPos, 1.0); + vec4 current = globalData.pMatrix * vec4(viewPos, 1.0); + vec2 ndcLast = last.xy / last.w - globalData.jitterLast; + vec2 ndcCurrent = current.xy / current.w - globalData.jitterCurrent; + + Store(pixel, oceanDepth, normal, normal, vec4(0.0, 0.0, 1.0, 0.0), (ndcLast - ndcCurrent) * 0.5, + PushConstants.oceanMaterialIdx); + return; + } +#endif + +#ifdef FRONT_LAYER + if (frontLayerDepth < depth) { + Store(pixel, frontLayerDepth, texelFetch(frontLayerNormalIn, pixel, 0).rg, + texelFetch(frontLayerGeometryNormalIn, pixel, 0).rg, texelFetch(frontLayerRoughnessMetallicAoIn, pixel, 0), + texelFetch(frontLayerVelocityIn, pixel, 0).rg, texelFetch(frontLayerMaterialIdxIn, pixel, 0).r); + return; + } +#endif + + Store(pixel, depth, texelFetch(normalIn, pixel, 0).rg, texelFetch(geometryNormalIn, pixel, 0).rg, + texelFetch(roughnessMetallicAoIn, pixel, 0), texelFetch(velocityIn, pixel, 0).rg, + texelFetch(materialIdxIn, pixel, 0).r); + +} diff --git a/data/shader/reflection/rtreflection.csh b/data/shader/reflection/rtreflection.csh index a32159c58..182c59578 100644 --- a/data/shader/reflection/rtreflection.csh +++ b/data/shader/reflection/rtreflection.csh @@ -1,5 +1,3 @@ -#define SHADOW_FILTER_1x1 - #include <../globals.hsh> #include <../raytracer/lights.hsh> #include <../raytracer/tracing.hsh> @@ -21,10 +19,13 @@ #include <../ddgi/ddgi.hsh> #include <../ddgi/transmission.hsh> -#include <../shadow.hsh> #include <../clouds/shadow.hsh> +#include <../common/denoiser.hsh> + +#ifndef RAY_TRACING_PIPELINE layout (local_size_x = 8, local_size_y = 4) in; +#endif layout (set = 3, binding = 0, rgba16f) uniform image2D rtrImage; @@ -33,7 +34,6 @@ layout(set = 3, binding = 2) uniform sampler2D depthTexture; layout(set = 3, binding = 3) uniform sampler2D roughnessMetallicAoTexture; layout(set = 3, binding = 4) uniform isampler2D offsetTexture; layout(set = 3, binding = 5) uniform usampler2D materialIdxTexture; -layout(set = 3, binding = 6) uniform sampler2DArrayShadow cascadeMaps; layout(set = 3, binding = 7) uniform sampler2D scramblingRankingTexture; layout(set = 3, binding = 8) uniform sampler2D sobolSequenceTexture; @@ -80,29 +80,34 @@ layout(std140, set = 3, binding = 10) uniform UniformBuffer { ivec2 resolution; uint frameCount; int padding1; - Shadow shadow; } uniforms; +#include <../raytracer/lighting.hsh> + vec3 EvaluateHit(inout Ray ray, float rand); -vec3 EvaluateDirectLight(inout Surface surface, inout float seed); -float CheckVisibility(Surface surface, float lightDistance); void main() { ivec2 resolution = uniforms.resolution; - if (int(gl_GlobalInvocationID.x) < resolution.x && - int(gl_GlobalInvocationID.y) < resolution.y) { + if (int(INVOCATION_ID.x) < resolution.x && + int(INVOCATION_ID.y) < resolution.y) { - ivec2 pixel = ivec2(gl_GlobalInvocationID.xy); + ivec2 pixel = ivec2(INVOCATION_ID.xy); #ifdef SSR vec4 reflection = imageLoad(rtrImage, pixel); + // Pixels SSR resolved keep its result, the resolve skips them by the marker + if (reflection.a != 0.0) { +#ifdef DEFERRED_SHADOW_RAYS + deferredSamples[(pixel.y * resolution.x + pixel.x) * uniforms.sampleCount].radiance.w = -1.0; +#endif + return; + } #else vec4 reflection = vec4(0.0); #endif - // No need, there is no offset right now int offsetIdx = texelFetch(offsetTexture, pixel, 0).r; #ifdef UPSCALE ivec2 offset = pixelOffsets[globalData.frameCount % 4]; @@ -117,7 +122,8 @@ void main() { recontructTexCoord = (2.0 * (vec2(pixel)) + offset + 0.5) / (2.0 * vec2(resolution)); highResPixel = 2 * pixel + offset; #else - recontructTexCoord = (vec2(pixel) + 0.5) / vec2(resolution); + // The downsampled data belongs to one pixel of the 2x2 block + recontructTexCoord = (2.0 * vec2(pixel) + pixelOffsets[offsetIdx] + 0.5) / (2.0 * vec2(resolution)); highResPixel = pixel; #endif } @@ -140,7 +146,13 @@ void main() { float roughness = texelFetch(roughnessMetallicAoTexture, highResPixel, 0).r; material.roughness *= material.roughnessMap || material.terrain ? roughness : 1.0; - float hitDistance = reflection.a; +#ifdef DEFERRED_SHADOW_RAYS + int pixelIdx = pixel.y * resolution.x + pixel.x; +#endif + + // Mean of the encoded hit distances, misses and probe samples count as one + float hitDistanceSum = 0.0; + int hitDistanceCount = 0; if (material.roughness <= 1.0 && depth < 1.0 && reflection.a == 0.0) { @@ -153,11 +165,28 @@ void main() { const int sampleCount = uniforms.sampleCount; + // Values per pixel are computed once before the loop + float roughness = material.roughness; + float alpha = sqr(max(0.0, roughness)); + float viewOffset = max(1.0, 2.0 * length(viewPos)); +#ifdef AUTO_EXPOSURE + float radianceLimit = 9.6 * uniforms.radianceLimit * texelFetch(exposureTexture, ivec2(0), 0).r * globalData.preExposure; +#else + float radianceLimit = uniforms.radianceLimit; +#endif + for (int i = 0; i < sampleCount; i++) { #ifdef UPSCALE int sampleIdx = int(uniforms.frameSeed / 4) * sampleCount + i; #else int sampleIdx = int(uniforms.frameSeed) * sampleCount + i; +#endif +#ifdef DEFERRED_SHADOW_RAYS + int deferredSampleIdx = pixelIdx * sampleCount + i; + deferredSamples[deferredSampleIdx].radiance.w = 0.0; + deferredLightBase = deferredSampleIdx * uniforms.lightSampleCount; + for (int j = 0; j < uniforms.lightSampleCount; j++) + deferredLights[deferredLightBase + j] = vec4(0.0, 0.0, 0.0, 1.0); #endif vec3 blueNoiseVec = vec3( SampleBlueNoise(highResPixel, sampleIdx, 0, scramblingRankingTexture, sobolSequenceTexture), @@ -165,15 +194,13 @@ void main() { SampleBlueNoise(highResPixel, sampleIdx, 2, scramblingRankingTexture, sobolSequenceTexture) ); - float alpha = sqr(max(0.0, material.roughness)); - Ray ray; ray.ID = i; blueNoiseVec.y *= (1.0 - uniforms.bias); float pdf = 1.0; BRDFSample brdfSample; - if (material.roughness >= 0.0) { + if (roughness >= 0.0) { ImportanceSampleGGXVNDF(blueNoiseVec.xy, N, V, alpha, ray.direction, pdf); } @@ -181,28 +208,22 @@ void main() { ray.direction = R; } - Surface surface = CreateSurface(V, N, ray.direction, material); - bool isRayValid = !isnan3(ray.direction) && !isinf3(ray.direction) && dot(N, ray.direction) >= 0.0; if (isRayValid) { // Scale offset by depth since the depth buffer inaccuracies increase at a distance and might not match the ray traced geometry anymore - float viewOffset = max(1.0, 2.0 * length(viewPos)); ray.origin = worldPos + ray.direction * EPSILON * viewOffset + worldNorm * EPSILON * viewOffset; ray.hitID = -1; ray.hitDistance = 0.0; vec3 radiance = vec3(0.0); + float encodedHitDistance = 1.0; - if (material.roughness <= uniforms.roughnessCutoff) { -#ifdef OPACITY_CHECK - HitClosestTransparency(ray, INSTANCE_MASK_ALL, 0.0, INF); -#else - HitClosest(ray, INSTANCE_MASK_ALL, 0.0, INF); -#endif - hitDistance = ray.hitDistance; + if (roughness <= uniforms.roughnessCutoff) { + HitClosestOpacityCheck(ray, INSTANCE_MASK_ALL, 0.0, INF); + encodedHitDistance = ray.hitID != -1 ? EncodeHitDistance(ray.hitDistance) : 1.0; radiance = EvaluateHit(ray, blueNoiseVec.z); } else { @@ -214,13 +235,15 @@ void main() { #elif defined(IRRADIANCE_VOLUME) radiance = IsInsideVolume(worldPos) ? probeIrradiance.rgb : vec3(0.0); #endif - hitDistance = 1.0; } -#ifdef AUTO_EXPOSURE - float radianceLimit = 9.6 * uniforms.radianceLimit * texelFetch(exposureTexture, ivec2(0), 0).r; -#else - float radianceLimit = uniforms.radianceLimit; + hitDistanceSum += encodedHitDistance; + hitDistanceCount++; + +#ifdef DEFERRED_SHADOW_RAYS + deferredSamples[deferredSampleIdx].radiance = vec4(radiance, 1.0); + deferredSamples[deferredSampleIdx].lobeWeight = vec4(1.0, 1.0, 1.0, radianceLimit); + continue; #endif float radianceMax = max(max(max(radiance.r, @@ -229,10 +252,20 @@ void main() { } } +#ifndef DEFERRED_SHADOW_RAYS reflection.rgb /= float(sampleCount); +#endif } +#ifdef DEFERRED_SHADOW_RAYS + else { + deferredSamples[pixelIdx * uniforms.sampleCount].radiance.w = -1.0; + } +#endif + // Misses store zero, an infinite distance breaks the virtual reprojection of the temporal pass + float meanHitDistance = hitDistanceCount > 0 ? hitDistanceSum / float(hitDistanceCount) : 1.0; + float hitDistance = meanHitDistance < 1.0 ? DecodeHitDistance(meanHitDistance) : 0.0; imageStore(rtrImage, pixel, vec4(reflection.rgb, hitDistance)); } @@ -248,12 +281,8 @@ vec3 EvaluateHit(inout Ray ray, float rand) { return SampleEnvironmentMap(ray.direction).rgb; } - // Unpack the compressed triangle and extract surface parameters - Instance instance = GetInstance(ray); - Triangle tri = GetTriangle(ray, instance); - bool backfaceHit; - Surface surface = GetSurfaceParameters(instance, tri, ray, false, backfaceHit, uniforms.textureLevel); + Surface surface = GetHitSurface(ray, false, backfaceHit, uniforms.textureLevel); // Evaluate indirect lighting #ifdef IRRADIANCE_VOLUME @@ -275,73 +304,9 @@ vec3 EvaluateHit(inout Ray ray, float rand) { radiance += surface.material.emissiveColor; float curSeed = float(uniforms.frameSeed) / 255.0 + float(ray.ID) * float(uniforms.sampleCount); - // Evaluate direct light - for (int i = 0; i < uniforms.lightSampleCount; i++) { - radiance += (EvaluateDirectLight(surface, curSeed) / float(uniforms.lightSampleCount)); - curSeed += 1.0 / float(uniforms.lightSampleCount); - } + float raySeed = float(INVOCATION_ID.x * uniforms.resolution.y + INVOCATION_ID.y); + radiance += EvaluateDirectLights(surface, raySeed, curSeed, uniforms.lightSampleCount); return radiance; } - -vec3 EvaluateDirectLight(inout Surface surface, inout float seed) { - - if (GetLightCount() == 0) - return vec3(0.0); - - float raySeed = float(gl_GlobalInvocationID.x * uniforms.resolution.y + gl_GlobalInvocationID.y); - - float lightPdf; - Light light = GetLight(surface, raySeed, seed, lightPdf); - - float solidAngle, lightDistance; - SampleLight(light, surface, raySeed, seed, solidAngle, lightDistance); - - bool transmittedLight = IsTransmittedLight(surface); - Surface lightSurface = transmittedLight ? GetTransmissionSurface(surface) : surface; - - // Evaluate the BRDF - vec3 reflectance = transmittedLight ? GetTransmissionColor(surface.material) * EvaluateDiffuseBRDF(lightSurface) : - EvaluateDiffuseBRDF(surface) + EvaluateSpecularBRDF(surface); - reflectance *= surface.material.opacity; - vec3 radiance = light.radiance * solidAngle; - - // Check for visibilty. This is important to get an - // estimate of the solid angle of the light from point P - // on the surface. -#ifdef USE_SHADOW_MAP - radiance *= CalculateShadowWorldSpace(uniforms.shadow, cascadeMaps, surface.P, - lightSurface.geometryNormal, saturate(dot(lightSurface.L, lightSurface.geometryNormal))); -#else - if (light.castShadow) - radiance *= CheckVisibility(lightSurface, lightDistance); -#endif - -#ifdef CLOUD_SHADOWS - if (light.type == uint(DIRECTIONAL_LIGHT)) { - vec3 P = vec3(globalData.vMatrix * vec4(surface.P, 1.0)); - float cloudShadowFactor = CalculateCloudShadow(P, cloudShadowUniforms.cloudShadow, cloudMap); - - radiance *= cloudShadowFactor; - } -#endif - - return reflectance * radiance * lightSurface.NdotL / lightPdf; - -} - -float CheckVisibility(Surface surface, float lightDistance) { - - if (surface.NdotL > 0.0) { - Ray ray; - ray.direction = surface.L; - float side = dot(surface.L, surface.geometryNormal) < 0.0 ? -1.0 : 1.0; - ray.origin = surface.P + surface.geometryNormal * (side * EPSILON); - return HitAnyTransparency(ray, INSTANCE_MASK_SHADOW, 0.0, lightDistance - 2.0 * EPSILON); - } - else { - return 0.0; - } - -} diff --git a/data/shader/reflection/rtreflection.rgen b/data/shader/reflection/rtreflection.rgen new file mode 100644 index 000000000..11c17c85c --- /dev/null +++ b/data/shader/reflection/rtreflection.rgen @@ -0,0 +1,7 @@ +// Ray traced reflections as the ray generation stage of a ray tracing pipeline, see bvh.hsh for the tracing +#extension GL_EXT_ray_tracing : require +#extension GL_EXT_shader_invocation_reorder : require + +#define RAY_TRACING_PIPELINE + +#include diff --git a/data/shader/reflection/rtreflectionResolve.csh b/data/shader/reflection/rtreflectionResolve.csh new file mode 100644 index 000000000..9358f0094 --- /dev/null +++ b/data/shader/reflection/rtreflectionResolve.csh @@ -0,0 +1,47 @@ +#include <../raytracer/deferredShadow.hsh> + +layout (local_size_x = 8, local_size_y = 4) in; + +layout (set = 3, binding = 0, rgba16f) uniform image2D rtrImage; + +layout(push_constant) uniform constants { + ivec2 resolution; + int sampleCount; + int lightSampleCount; +} pushConstants; + +void main() { + + ivec2 resolution = pushConstants.resolution; + if (int(gl_GlobalInvocationID.x) >= resolution.x || int(gl_GlobalInvocationID.y) >= resolution.y) + return; + + ivec2 pixel = ivec2(gl_GlobalInvocationID.xy); + int pixelIdx = pixel.y * resolution.x + pixel.x; + + // Pixels which weren't ray traced, e.g. because of an SSR hit, keep their reflection + if (deferredSamples[pixelIdx * pushConstants.sampleCount].radiance.w < 0.0) + return; + + vec4 reflection = imageLoad(rtrImage, pixel); + for (int i = 0; i < pushConstants.sampleCount; i++) { + int sampleIdx = pixelIdx * pushConstants.sampleCount + i; + if (deferredSamples[sampleIdx].radiance.w == 0.0) + continue; + + vec3 radiance = deferredSamples[sampleIdx].radiance.rgb; + for (int j = 0; j < pushConstants.lightSampleCount; j++) { + vec4 light = deferredLights[sampleIdx * pushConstants.lightSampleCount + j]; + radiance += light.rgb * light.w; + } + + float radianceLimit = deferredSamples[sampleIdx].lobeWeight.w; + float radianceMax = max(max(max(radiance.r, + max(radiance.g, radiance.b)), radianceLimit), 1e-12); + reflection.rgb += radiance * (radianceLimit / radianceMax); + } + + reflection.rgb /= float(pushConstants.sampleCount); + imageStore(rtrImage, pixel, reflection); + +} diff --git a/data/shader/reflection/ssr.csh b/data/shader/reflection/ssr.csh index 5e15dfc84..0c9e8c8d4 100644 --- a/data/shader/reflection/ssr.csh +++ b/data/shader/reflection/ssr.csh @@ -17,7 +17,6 @@ #include <../brdf/surface.hsh> #include <../ddgi/ddgi.hsh> -#include <../shadow.hsh> layout (local_size_x = 8, local_size_y = 4) in; @@ -28,12 +27,14 @@ layout(set = 3, binding = 2) uniform sampler2D depthTexture; layout(set = 3, binding = 3) uniform sampler2D roughnessMetallicAoTexture; layout(set = 3, binding = 4) uniform isampler2D offsetTexture; layout(set = 3, binding = 5) uniform usampler2D materialIdxTexture; -layout(set = 3, binding = 6) uniform sampler2DArrayShadow cascadeMaps; layout(set = 3, binding = 7) uniform sampler2D scramblingRankingTexture; layout(set = 3, binding = 8) uniform sampler2D sobolSequenceTexture; layout(set = 3, binding = 9) uniform sampler2D lightingTexture; +layout(set = 3, binding = 12) uniform sampler2D hiZTexture; +// Depth at the resolution of the hierarchical depth buffer, which is the one of the rays +layout(set = 3, binding = 13) uniform sampler2D hiZDepthTexture; #ifdef AUTO_EXPOSURE layout(set = 3, binding = 11) uniform sampler2D exposureTexture; #endif @@ -59,8 +60,7 @@ layout(std140, set = 3, binding = 10) uniform UniformBuffer { int halfRes; ivec2 resolution; uint frameCount; - int padding1; - Shadow shadow; + int hiZLevelCount; } uniforms; vec4 SampleCatmullRom(vec2 uv) { @@ -117,7 +117,6 @@ vec4 SampleCatmullRom(vec2 uv) { } shared int maxSteps; -shared int stepSize; void main() { @@ -125,7 +124,6 @@ void main() { if (gl_LocalInvocationIndex == 0u) { maxSteps = 0; - stepSize = 0; } barrier(); @@ -169,12 +167,10 @@ void main() { material.roughness *= material.roughnessMap || material.terrain ? roughness : 1.0; if (material.roughness < 0.1) { - atomicMax(maxSteps, 128); - atomicMax(stepSize, 8); + atomicMax(maxSteps, 64); } else { - atomicMax(maxSteps, 64); - atomicMax(stepSize, 16); + atomicMax(maxSteps, 32); } barrier(); @@ -232,19 +228,14 @@ void main() { vec2 hitPixel; vec3 hitPoint; -#ifdef UPSCALE - float jitter = GetInterleavedGradientNoise(vec2(highResPixel), 32u) / float(sampleCount) + i / float(sampleCount); -#else - float jitter = GetInterleavedGradientNoise(vec2(highResPixel), 32u) / float(sampleCount) + i / float(sampleCount); -#endif #ifdef RT bool stopBehindGeometry = true; #else bool stopBehindGeometry = false; #endif - if (traceScreenSpaceAdvanced(viewRayOrigin, viewDir, depthTexture, 1.0, stepSize, 0.9, maxSteps, - rayLength, false, stopBehindGeometry, hitPixel, hitPoint)) { - vec2 hitTexCoord = vec2(hitPixel + 0.5) / vec2(textureSize(lightingTexture, 0)); + if (traceScreenSpaceHiZ(viewRayOrigin, viewDir, hiZTexture, uniforms.hiZLevelCount, vec2(textureSize(hiZDepthTexture, 0)), + maxSteps, rayLength, stopBehindGeometry, hitPixel, hitPoint)) { + vec2 hitTexCoord = vec2(hitPixel + 0.5) / vec2(textureSize(hiZDepthTexture, 0)); //radiance = SampleCatmullRom(hitTexCoord).rgb; radiance = textureLod(lightingTexture, hitTexCoord, 0.0).rgb; @@ -258,7 +249,7 @@ void main() { } #ifdef AUTO_EXPOSURE - float radianceLimit = 9.6 * uniforms.radianceLimit * texelFetch(exposureTexture, ivec2(0), 0).r; + float radianceLimit = 9.6 * uniforms.radianceLimit * texelFetch(exposureTexture, ivec2(0), 0).r * globalData.preExposure; #else float radianceLimit = uniforms.radianceLimit; #endif diff --git a/data/shader/reflection/temporal.csh b/data/shader/reflection/temporal.csh index 477c2641a..39e5ff1fa 100644 --- a/data/shader/reflection/temporal.csh +++ b/data/shader/reflection/temporal.csh @@ -11,6 +11,7 @@ #include <../common/material.hsh> #include <../common/random.hsh> #include <../common/normalencode.hsh> +#include <../common/denoiser.hsh> layout (local_size_x = 16, local_size_y = 16) in; @@ -34,21 +35,20 @@ layout(set = 3, binding = 13) uniform sampler2D historyRoughnessMetallicAoTextur vec2 invResolution = 1.0 / vec2(imageSize(resolveImage)); vec2 resolution = vec2(imageSize(resolveImage)); -const int kernelRadius = 5; +const int kernelRadius = 3; const uint sharedDataSize = (gl_WorkGroupSize.x + 2 * kernelRadius) * (gl_WorkGroupSize.y + 2 * kernelRadius); const ivec2 unflattenedSharedDataSize = ivec2(gl_WorkGroupSize) + 2 * kernelRadius; shared vec4 sharedRadianceDepth[sharedDataSize]; +shared vec2 sharedObjectMotion[sharedDataSize]; layout(push_constant) uniform constants { - vec4 cameraLocationLast; float temporalWeight; float historyClipMax; float currentClipFactor; float roughnessCutoff; int resetHistory; - uint frameCount; } pushConstants; const ivec2 offsets[9] = ivec2[9]( @@ -70,13 +70,6 @@ const ivec2 pixelOffsets[4] = ivec2[4]( ivec2(1, 1) ); -float Luma(vec3 color) { - - const vec3 luma = vec3(0.299, 0.587, 0.114); - return dot(color, luma); - -} - vec4 FetchTexel(ivec2 texel) { vec4 color = texelFetch(currentTexture, texel, 0); @@ -97,8 +90,10 @@ void LoadGroupSharedData() { texel = clamp(texel, ivec2(0), ivec2(resolution) - ivec2(1)); vec4 radianceRayLength = FetchTexel(texel); + float depth = texelFetch(depthTexture, texel, 0).r; sharedRadianceDepth[i].rgb = RGBToYCoCg(radianceRayLength.rgb); - sharedRadianceDepth[i].a = ConvertDepthToViewSpaceDepth(texelFetch(depthTexture, texel, 0).r); + sharedRadianceDepth[i].a = ConvertDepthToViewSpaceDepth(depth); + sharedObjectMotion[i] = GetObjectMotion(velocityTexture, texel, depth, resolution); } barrier(); @@ -143,31 +138,27 @@ ivec2 FindNearest3x3(ivec2 pixel) { } -float ClipBoundingBox(vec3 boxMin, vec3 boxMax, vec3 history, vec3 current) { - - vec3 origin = history; - vec3 dir = current - history; - - // Make sure dir isn't zero - dir.x = abs(dir.x) < (1.0 / 32767.0) ? (1.0 / 32767.0) : dir.x; - dir.y = abs(dir.y) < (1.0 / 32767.0) ? (1.0 / 32767.0) : dir.y; - dir.z = abs(dir.z) < (1.0 / 32767.0) ? (1.0 / 32767.0) : dir.z; - - vec3 invDir = 1.0 / dir; +vec3 GetHistoryWorldPosition(ivec2 historyPixel) { - vec3 t0 = (boxMin - origin) * invDir; - vec3 t1 = (boxMax - origin) * invDir; - - vec3 intersect = min(t0, t1); - return max(intersect.x, max(intersect.y, intersect.z)); + float historyDepth = texelFetch(historyDepthTexture, historyPixel, 0).r; + vec2 ndc = (vec2(historyPixel) + 0.5) * invResolution * 2.0 - 1.0; + vec4 position = globalData.ipvMatrixLast * vec4(ndc, historyDepth, 1.0); + return position.xyz / position.w; } -bool SampleHistory(ivec2 pixel, vec2 historyPixel, float normalPhi, out vec4 history, out vec4 historyMoments) { - +// The bilinear footprint is complete when all four history texels are valid, their range limits a bicubic filter. +// The confidence is the valid part of the footprint, it shortens the history of partly valid reprojections +bool SampleHistory(ivec2 pixel, vec2 historyPixel, float normalPhi, out vec4 history, out vec4 historyMoments, + out bool completeFootprint, out vec4 historyMin, out vec4 historyMax, out float footprintConfidence) { + + footprintConfidence = 0.0; history = vec4(0.0); historyMoments = vec4(0.0); + historyMin = vec4(1e30); + historyMax = vec4(-1e30); + int validCount = 0; float totalWeight = 0.0; float x = fract(historyPixel.x); float y = fract(historyPixel.y); @@ -177,8 +168,11 @@ bool SampleHistory(ivec2 pixel, vec2 historyPixel, float normalPhi, out vec4 his vec3 normal = DecodeNormal(texelFetch(normalTexture, pixel, 0).rg); float depth = texelFetch(depthTexture, pixel, 0).r; - float linearDepth = ConvertDepthToViewSpaceDepth(depth); - float depthPhi = normalPhi / abs(linearDepth); + vec3 viewPosition = ConvertDepthToViewSpace(depth, (vec2(pixel) + 0.5) * invResolution); + vec3 position = vec3(globalData.ivMatrix * vec4(viewPosition, 1.0)); + vec3 worldNormal = normalize(mat3(globalData.ivMatrix) * normal); + // The distance to the surface plane stays stable at grazing angles, unlike the depth + float depthPhi = normalPhi / abs(viewPosition.z); float roughness = texelFetch(roughnessMetallicAoTexture, pixel, 0).r; uint materialIdx = texelFetch(materialIdxTexture, pixel, 0).r; @@ -193,22 +187,28 @@ bool SampleHistory(ivec2 pixel, vec2 historyPixel, float normalPhi, out vec4 his vec3 historyNormal = DecodeNormal(texelFetch(historyNormalTexture, offsetPixel, 0).rg); confidence *= pow(max(dot(historyNormal, normal), 0.0), normalPhi); - float historyDepth = texelFetch(historyDepthTexture, offsetPixel, 0).r; - float historyLinearDepth = historyDepth; - - confidence *= min(1.0 , exp(-abs(linearDepth - historyLinearDepth) * depthPhi)); + float planeDistance = abs(dot(GetHistoryWorldPosition(offsetPixel) - position, worldNormal)); + confidence *= min(1.0 , exp(-planeDistance * depthPhi)); uint historyMaterialIdx = texelFetch(historyMaterialIdxTexture, offsetPixel, 0).r; confidence *= historyMaterialIdx == materialIdx ? 1.0 : 0.0; if (confidence > 0.2) { + vec4 historyTexel = texelFetch(historyTexture, offsetPixel, 0); + historyMin = min(historyMin, historyTexel); + historyMax = max(historyMax, historyTexel); + validCount++; + totalWeight += weights[i]; - history += texelFetch(historyTexture, offsetPixel, 0) * weights[i]; + history += historyTexel * weights[i]; historyMoments += texelFetch(historyMomentsTexture, offsetPixel, 0) * weights[i]; } } + completeFootprint = validCount == 4; + if (totalWeight > 0.0) { + footprintConfidence = totalWeight; history /= totalWeight; historyMoments /= totalWeight; return true; @@ -223,9 +223,8 @@ bool SampleHistory(ivec2 pixel, vec2 historyPixel, float normalPhi, out vec4 his vec3 historyNormal = DecodeNormal(texelFetch(historyNormalTexture, offsetPixel, 0).rg); confidence *= pow(max(dot(historyNormal, normal), 0.0), normalPhi); - float historyDepth = texelFetch(historyDepthTexture, offsetPixel, 0).r; - float historyLinearDepth = ConvertDepthToViewSpaceDepth(historyDepth); - confidence *= min(1.0 , exp(-abs(linearDepth - historyLinearDepth) * depthPhi)); + float planeDistance = abs(dot(GetHistoryWorldPosition(offsetPixel) - position, worldNormal)); + confidence *= min(1.0 , exp(-planeDistance * depthPhi)); uint historyMaterialIdx = texelFetch(historyMaterialIdxTexture, offsetPixel, 0).r; confidence *= historyMaterialIdx == materialIdx ? 1.0 : 0.0; @@ -238,6 +237,8 @@ bool SampleHistory(ivec2 pixel, vec2 historyPixel, float normalPhi, out vec4 his } if (totalWeight > 0.0) { + // None of the footprint texels matched, the neighbors around it are less trustworthy + footprintConfidence = totalWeight / 9.0; history /= totalWeight; historyMoments /= totalWeight; return true; @@ -250,85 +251,13 @@ bool SampleHistory(ivec2 pixel, vec2 historyPixel, float normalPhi, out vec4 his } -float IsHistoryPixelValid(ivec2 pixel, float linearDepth, vec3 normal) { - - float confidence = 1.0; - - vec3 historyNormal = DecodeNormal(texelFetch(historyNormalTexture, pixel, 0).rg); - confidence *= pow(max(dot(historyNormal, normal), 0.0), 16.0); - - float depthPhi = 128.0 / abs(linearDepth); - float historyDepth = texelFetch(historyDepthTexture, pixel, 0).r; - float historyLinearDepth = historyDepth; - confidence *= min(1.0 , exp(-abs(linearDepth - historyLinearDepth) * depthPhi)); - - return confidence > 0.1 ? 1.0 : 0.0; - -} - -vec4 GetCatmullRomSample(ivec2 pixel, inout float weight, float linearDepth, vec3 normal) { - - pixel = clamp(pixel, ivec2(0), ivec2(imageSize(resolveImage) - 1)); - - weight *= IsHistoryPixelValid(pixel, linearDepth, normal); - - return texelFetch(historyTexture, pixel, 0) * weight; - -} - -bool SampleCatmullRom(ivec2 pixel, vec2 uv, out vec4 history) { - - vec3 normal = DecodeNormal(texelFetch(normalTexture, pixel, 0).rg); - float depth = texelFetch(depthTexture, pixel, 0).r; - - vec2 position = uv * resolution; - - vec2 center = floor(position - 0.5) + 0.5; - vec2 f = position - center; - vec2 f2 = f * f; - vec2 f3 = f2 * f; - - vec2 w0 = f2 - 0.5 * (f3 + f); - vec2 w1 = 1.5 * f3 - 2.5 * f2 + 1.0; - vec2 w3 = 0.5 * (f3 - f2); - vec2 w2 = 1.0 - w0 - w1 - w3; - - ivec2 uv0 = ivec2(center - 1.0); - ivec2 uv1 = ivec2(center); - ivec2 uv2 = ivec2(center + 1.0); - ivec2 uv3 = ivec2(center + 2.0); - - ivec2 uvs[4] = { uv0, uv1, uv2, uv3 }; - vec2 weights[4] = { w0, w1, w2, w3 }; - - history = vec4(0.0); - - float totalWeight = 0.0; - - for (int x = 0; x <= 3; x++) { - for (int y = 0; y <= 3; y++) { - float weight = weights[x].x * weights[y].y; - ivec2 uv = ivec2(uvs[x].x, uvs[y].y); - - history += GetCatmullRomSample(uv, weight, depth, normal); - totalWeight += weight; - } - } - - if (totalWeight > 0.5) { - history /= totalWeight; - history = max(history, 0.0); - - return true; - } - - return false; -} - -void ComputeVarianceMinMax(float roughness, int radius, out vec3 mean, out vec3 std) { +// The sample count is the effective one of the weighted neighborhood, (sum of weights)^2 / sum of squared weights. +// The nearby motion is the fastest movement of a neighbor around the same depth relative to the pixel in pixels +void ComputeVarianceMinMax(int radius, out vec3 mean, out vec3 std, out float sampleCount, out float nearbyMotion) { vec3 m1 = vec3(0.0); vec3 m2 = vec3(0.0); + float squaredWeight = 0.0; // This could be varied using the temporal variance estimation // By using a wide neighborhood for variance estimation (8x8) we introduce block artifacts // These are similiar to video compression artifacts, the spatial filter mostly clears them up @@ -339,40 +268,36 @@ void ComputeVarianceMinMax(float roughness, int radius, out vec3 mean, out vec3 float linearDepth = ConvertDepthToViewSpaceDepth(depth); float depthPhi = max(1.0, abs(0.025 * linearDepth)); - uint materialIdx = texelFetch(materialIdxTexture, pixel, 0).r; - float totalWeight = 0.0; + vec2 centerObjectMotion = sharedObjectMotion[GetSharedMemoryIndex(ivec2(0))]; + float nearbyMotionSquared = 0.0; + float depthScale = 1.442695 / depthPhi; + for (int i = -radius; i <= radius; i++) { for (int j = -radius; j <= radius; j++) { int sharedMemoryIdx = GetSharedMemoryIndex(ivec2(i, j)); vec3 sampleRadiance = FetchCurrentRadiance(sharedMemoryIdx); float sampleLinearDepth = FetchDepth(sharedMemoryIdx); - - float weight = min(1.0 , exp(-abs(linearDepth - sampleLinearDepth) / depthPhi)); - + + float weight = exp2(-abs(linearDepth - sampleLinearDepth) * depthScale); + m1 += sampleRadiance * weight; m2 += sampleRadiance * sampleRadiance * weight; totalWeight += weight; + squaredWeight += weight * weight; + + nearbyMotionSquared = max(nearbyMotionSquared, GetNearbyMotionSquared(sharedObjectMotion[sharedMemoryIdx], + centerObjectMotion, linearDepth, sampleLinearDepth)); } } mean = m1 / totalWeight; std = sqrt(max((m2 / totalWeight) - (mean * mean), 0.0)); -} - -float ComputeParallax(vec3 position, vec3 historyPosition) { - - vec3 cameraDelta = pushConstants.cameraLocationLast.xyz - globalData.cameraLocation.xyz; - - vec3 V = normalize(position); - vec3 historyV = normalize(historyPosition - cameraDelta); - - float cosTheta = saturate(dot(V, historyV)); - return sqrt(1.0 - cosTheta * cosTheta) / max(cosTheta, 1e-6) * 60.0; - + sampleCount = sqr(totalWeight) / squaredWeight; + nearbyMotion = sqrt(nearbyMotionSquared); } float GetSpecularDominantFactor(float NdotV, float roughness) { @@ -384,30 +309,26 @@ float GetSpecularDominantFactor(float NdotV, float roughness) { } -float GetAccumulationSpeed(float NdotV, float roughness, float parallax) { +float GetFilteredRayLength(ivec2 pixel) { - const float accumCurve = 0.5; - const float accumBasePower = 0.5; + float centerDepth = FetchDepth(GetSharedMemoryIndex(ivec2(0))); + float depthPhi = 32.0 / abs(centerDepth); - float acossqr = 1.0 - NdotV; - float rsqr = sqr(roughness); - - float a = pow(saturate(acossqr), accumCurve); - float b = 1.1 + rsqr; - - float parallaxSensitivity = (b + a) / (b - a); - float powerScale = 1.0 + parallax * parallaxSensitivity; - - float f = 1.0 - exp2(-200.0 * rsqr); - f *= pow(saturate(roughness), accumBasePower * powerScale); - - return min(f, pushConstants.temporalWeight); + float rayLength = 0.0; + float totalWeight = 0.0; -} + // Misses have a ray length of zero and are excluded + for (int i = 0; i < 9; i++) { + ivec2 samplePixel = clamp(pixel + offsets[i], ivec2(0), ivec2(resolution) - ivec2(1)); + float sampleRayLength = abs(texelFetch(currentTexture, samplePixel, 0).a); + float sampleDepth = FetchDepth(GetSharedMemoryIndex(offsets[i])); -vec2 SurfacePointReprojection(vec2 pixel, vec2 velocity) { + float weight = sampleRayLength > 0.0 ? min(1.0, exp(-abs(centerDepth - sampleDepth) * depthPhi)) : 0.0; + rayLength += sampleRayLength * weight; + totalWeight += weight; + } - return pixel + velocity * resolution; + return totalWeight > 0.0 ? rayLength / totalWeight : 0.0; } @@ -437,8 +358,8 @@ void main() { LoadGroupSharedData(); ivec2 pixel = ivec2(gl_GlobalInvocationID); - if (pixel.x > imageSize(resolveImage).x || - pixel.y > imageSize(resolveImage).y) + if (pixel.x >= imageSize(resolveImage).x || + pixel.y >= imageSize(resolveImage).y) return; vec2 uv = (vec2(pixel) + 0.5) * invResolution; @@ -447,157 +368,157 @@ void main() { float roughness = textureLod(roughnessMetallicAoTexture, uv, .0).r; vec3 normal = normalize(DecodeNormal(texelFetch(normalTexture, pixel, 0).rg)); - vec2 surfaceHistoryPixel = SurfacePointReprojection(vec2(pixel), velocity); - vec2 surfaceHistoryUV = (surfaceHistoryPixel + 0.5) * invResolution; - float depth = texelFetch(depthTexture, pixel, 0).r; - float depthHistory = texelFetch(depthTexture, ivec2(surfaceHistoryPixel), 0).r; - - //vec3 position = vec3(globalData.ivMatrix * vec4(ConvertDepthToViewSpace(depth, uv), 1.0)); - //vec3 positionHistory = vec3(inverse(globalData.vMatrixLast) * vec4(ConvertDepthToViewSpace(depthHistory, surfaceHistoryUV), 1.0)); - vec3 position = ConvertDepthToViewSpace(depth, uv); - vec3 positionHistory = ConvertDepthToViewSpace(depthHistory, uv); - float parallax = ComputeParallax(position, positionHistory); float NdotV = abs(dot(normalize(-position), normal)); float dominantFactor = GetSpecularDominantFactor(NdotV, sqrt(roughness)); vec3 mean, std; + float sampleCount, nearbyMotion; #ifdef UPSCALE const int radius = int(mix(3.0, float(kernelRadius), min(1.0, roughness * 4.0))); #else const int radius = int(mix(2.0, float(kernelRadius), min(1.0, roughness * 4.0))); #endif - if (roughness < pushConstants.roughnessCutoff) { - ComputeVarianceMinMax(roughness, radius, mean, std); - } - else { - // Don't need much denoising here (except for roughness = 1. looks noisy for metallic surfaces) - ComputeVarianceMinMax(roughness, 3, mean, std); - } - - ivec2 velocityPixel = pixel; + // Above the cutoff the probes don't need much denoising (except for roughness = 1. looks noisy for metallic surfaces) + ComputeVarianceMinMax(roughness < pushConstants.roughnessCutoff ? radius : 3, + mean, std, sampleCount, nearbyMotion); - uv = (vec2(pixel) + vec2(0.5)) * invResolution + velocity; vec2 historyPixel = vec2(pixel) + velocity * resolution; - uv = (historyPixel + 0.5) * invResolution; + vec2 historyUv = (historyPixel + 0.5) * invResolution; - bool valid = true; - vec4 history = vec4(0.0); - vec4 historyMoments = vec4(0.0); - valid = SampleHistory(pixel, historyPixel, 16.0, - history, historyMoments); + vec4 history; + vec4 historyMoments; + bool completeFootprint; + vec4 historyMin, historyMax; + float footprintConfidence; + bool valid = SampleHistory(pixel, historyPixel, 16.0, + history, historyMoments, completeFootprint, historyMin, historyMax, footprintConfidence) && !IsOffscreen(historyUv); #ifdef BICUBIC_FILTER - // This should be implemented more efficiently, see - if (roughness < pushConstants.roughnessCutoff) { - vec4 catmullRomHistory; - bool success = SampleCatmullRom(pixel, uv, catmullRomHistory); - history = success && valid ? catmullRomHistory : history; - } + // The clamp removes ringing and texels outside the footprint that belong to other surfaces + if (roughness < pushConstants.roughnessCutoff && completeFootprint) + history = clamp(SampleCatmullRom(historyTexture, historyUv, resolution), historyMin, historyMax); #endif + // The history was stored with the pre-exposure of the last frame, the moments hold luma and its square + float exposureScale = globalData.preExposure / globalData.lastPreExposure; + vec2 momentsExposureScale = vec2(exposureScale, exposureScale * exposureScale); + history.rgb *= exposureScale; + historyMoments.rg *= momentsExposureScale; + vec3 currentColor = RGBToYCoCg(texelFetch(currentTexture, pixel, 0).rgb); + // Misses have a ray length of zero. Mirrors use their own ray length, it has no noise and averaging it across + // the edges of reflected objects would mix their distances + const float virtualCutoff = 0.2; float rayLength = texelFetch(currentTexture, pixel, 0).a; + float filteredRayLength = mix(abs(rayLength), GetFilteredRayLength(pixel), saturate(roughness / virtualCutoff)); if (rayLength != 0 && roughness < pushConstants.roughnessCutoff) { - vec2 virtualHistoryPixel = VirtualPointReprojection(pixel, imageSize(resolveImage), abs(rayLength)); - - bool validRepojection = true; - vec4 historyVirtualRepojection = vec4(0.0); - vec4 historyMomentsVirtualRepojection = vec4(0.0); - validRepojection = SampleHistory(pixel, virtualHistoryPixel, 32.0, - historyVirtualRepojection, historyMomentsVirtualRepojection); + vec2 virtualHistoryPixel = VirtualPointReprojection(pixel, imageSize(resolveImage), filteredRayLength); + vec2 virtualHistoryUv = (virtualHistoryPixel + 0.5) * invResolution; + + vec4 historyVirtualRepojection; + vec4 historyMomentsVirtualRepojection; + bool completeVirtualFootprint; + vec4 virtualHistoryMin, virtualHistoryMax; + float virtualFootprintConfidence; + bool validRepojection = SampleHistory(pixel, virtualHistoryPixel, 32.0, + historyVirtualRepojection, historyMomentsVirtualRepojection, + completeVirtualFootprint, virtualHistoryMin, virtualHistoryMax, virtualFootprintConfidence) && + !IsOffscreen(virtualHistoryUv); #ifdef BICUBIC_FILTER - // This should be implemented more efficiently, see - if (validRepojection) { - vec4 catmullRomHistory; - uv = (virtualHistoryPixel + 0.5) * invResolution; - bool success = SampleCatmullRom(pixel, uv, catmullRomHistory); - historyVirtualRepojection = success ? catmullRomHistory : historyVirtualRepojection; - } + if (validRepojection && completeVirtualFootprint) + historyVirtualRepojection = clamp(SampleCatmullRom(historyTexture, virtualHistoryUv, resolution), + virtualHistoryMin, virtualHistoryMax); #endif + historyVirtualRepojection.rgb *= exposureScale; + historyMomentsVirtualRepojection.rg *= momentsExposureScale; - vec3 virtualNormal = normalize(DecodeNormal(texelFetch(historyNormalTexture, ivec2(virtualHistoryPixel), 0).rg)); - float virtualRoughness = texelFetch(historyRoughnessMetallicAoTexture, ivec2(virtualHistoryPixel), 0).r; + ivec2 virtualHistoryTexel = clamp(ivec2(virtualHistoryPixel), ivec2(0), ivec2(resolution) - ivec2(1)); + vec3 virtualNormal = normalize(DecodeNormal(texelFetch(historyNormalTexture, virtualHistoryTexel, 0).rg)); + float virtualRoughness = texelFetch(historyRoughnessMetallicAoTexture, virtualHistoryTexel, 0).r; - const float virtualCutoff = 0.2; float virtualConfidence = dominantFactor * sqr(max((virtualCutoff - roughness) / virtualCutoff, 0.0)); virtualConfidence *= pow(max(dot(virtualNormal, normal), 0.0), 512.0); virtualConfidence *= pow(1.0 - abs(virtualRoughness - roughness), 32.0); - valid = valid || validRepojection; - history = (historyVirtualRepojection * virtualConfidence + - (1.0 - virtualConfidence) * history); + // Only valid reprojections contribute, below the virtual cutoff the virtual one replaces an invalid surface one + float virtualWeight = validRepojection ? (valid ? virtualConfidence : (roughness < virtualCutoff ? 1.0 : 0.0)) : 0.0; + valid = valid || virtualWeight > 0.0; + history = mix(history, historyVirtualRepojection, virtualWeight); + historyMoments = mix(historyMoments, historyMomentsVirtualRepojection, virtualWeight); + footprintConfidence = mix(footprintConfidence, virtualFootprintConfidence, virtualWeight); } vec2 currentMoments; currentMoments.r = currentColor.r; currentMoments.g = currentMoments.r * currentMoments.r; - vec3 historyNeighbourhoodMin = mean - std; - vec3 historyNeighbourhoodMax = mean + std; + // Two standard deviations, a narrower box shortens converged histories at highlights and reflected edges + vec3 historyNeighbourhoodMin = mean - 2.0 * std; + vec3 historyNeighbourhoodMax = mean + 2.0 * std; vec3 currentNeighbourhoodMin = mean - pushConstants.currentClipFactor * std; vec3 currentNeighbourhoodMax = mean + pushConstants.currentClipFactor * std; currentColor = clamp(currentColor, currentNeighbourhoodMin, currentNeighbourhoodMax); vec3 historyColor = RGBToYCoCg(history.rgb); - float clipBlend = ClipBoundingBox(historyNeighbourhoodMin, historyNeighbourhoodMax, - historyColor, currentColor); - - // In case of clipping we might also reject the sample. TODO: Investigate - clipBlend = ClipBoundingBox(historyNeighbourhoodMin, historyNeighbourhoodMax, - historyColor, currentColor); - float adjClipBlend = clamp(clipBlend, 0.0, pushConstants.historyClipMax); - currentColor = valid ? currentColor : mean; - - historyColor = YCoCgToRGB(historyColor); - currentColor = YCoCgToRGB(currentColor); + float historyLength = historyMoments.b * footprintConfidence; - float temporalWeight = mix(pushConstants.temporalWeight, 0.0, adjClipBlend); - -#ifdef UPSCALE - float roughnessMinTemporalWeight = 0.75; -#else - float roughnessMinTemporalWeight = temporalWeight; -#endif - float factor = clamp(32.0 * log(roughness + 1.0), roughnessMinTemporalWeight, temporalWeight); - //factor = GetAccumulationSpeed(NdotV, roughness, parallax); - valid = (uv.x < 0.0 || uv.y < 0.0 || uv.x > 1.0 - || uv.y > 1.0) ? false : valid; + // Histories outside the neighborhood shorten, small neighborhoods (thin objects, edges) fully from ten samples on + float clipBlend = ClipBoundingBox(historyNeighbourhoodMin, historyNeighbourhoodMax, + historyColor, currentColor); + float adjClipBlend = clamp(clipBlend, 0.0, pushConstants.historyClipMax); + historyLength *= 1.0 - adjClipBlend * saturate((sampleCount - 2.0) / 8.0); - factor = pushConstants.resetHistory > 0 ? 0.0 : factor; + historyLength = LimitHistoryByNearbyMotion(historyLength, nearbyMotion); - float historyLength = historyMoments.b; - if (factor <= 0.1 * roughness || !valid) { + if (pushConstants.resetHistory > 0 || !valid) { + valid = false; historyLength = 0.0; currentMoments.g = 1.0; currentMoments.r = 0.0; } - factor = max(0.75, factor - 20.0 * max(abs(velocity.x), abs(velocity.y))); - factor = min(factor, historyLength / (historyLength + 1.0)); + // New and short histories (disocclusions) start from the neighborhood mean instead of single noisy samples. + // Mirrors keep their sample, it has no noise and the mean would mix different reflected content + currentColor = mix(mean, currentColor, max(saturate(historyLength / 4.0), 1.0 - saturate(roughness / virtualCutoff))); + + historyColor = YCoCgToRGB(historyColor); + currentColor = YCoCgToRGB(currentColor); + + float factor = min(pushConstants.temporalWeight, historyLength / (historyLength + 1.0)); #ifdef UPSCALE - factor = rayLength > 0.0 ? factor : (valid ? mix(1.0, 0.0, adjClipBlend) : factor); + // Misses have a ray length of zero, so the upsampling marks pixels it filled in by their position + bool traced = pixel % 2 == pixelOffsets[globalData.frameCount % 4]; + factor = traced ? factor : (valid ? min(1.0 - adjClipBlend, historyLength / (historyLength + 1.0)) : factor); #endif vec3 resolve = factor <= 0.0 ? currentColor : mix(currentColor, historyColor, factor); vec2 momentsResolve = factor <= 0.0 ? currentMoments : mix(currentMoments, historyMoments.rg, factor); + // Accumulated for the spatial filter, which limits its radius by the lobe the reflection rays cover + // Pixels above the cutoff sample the probes and have no ray length + bool traceRay = roughness < pushConstants.roughnessCutoff && filteredRayLength > 0.0; + float currentHitDistance = traceRay ? EncodeHitDistance(filteredRayLength) : 1.0; + float hitDistance = factor <= 0.0 ? currentHitDistance : mix(currentHitDistance, historyMoments.a, factor); + + float accumulatedFrames = GetAccumulatedFrames(factor, historyLength); + // Boost variance when we have a small history length (we trade blur for noise) - float varianceBoost = max(1.0, 4.0 / (historyLength + 1.0)); + float varianceBoost = max(1.0, 4.0 / accumulatedFrames); float variance = max(0.0, momentsResolve.g - momentsResolve.r * momentsResolve.r); variance *= varianceBoost; variance = roughness <= 0.1 ? max(variance * roughness, roughness * 1e-6) : variance; - imageStore(momentsImage, pixel, vec4(momentsResolve, historyLength + 1.0, 0.0)); + imageStore(momentsImage, pixel, vec4(momentsResolve, accumulatedFrames, hitDistance)); imageStore(resolveImage, pixel, vec4(vec3(resolve), variance)); } \ No newline at end of file diff --git a/data/shader/reflection/upsample.csh b/data/shader/reflection/upsample.csh index 51f6ddeec..db9ad8bfd 100644 --- a/data/shader/reflection/upsample.csh +++ b/data/shader/reflection/upsample.csh @@ -9,6 +9,9 @@ layout (local_size_x = 8, local_size_y = 8) in; +// Needs the work group size +#include <../common/upsample.hsh> + layout(set = 3, binding = 0, rgba16f) writeonly uniform image2D image; layout(set = 3, binding = 1) uniform sampler2D lowResTexture; @@ -21,22 +24,14 @@ shared float depths[36]; shared vec3 normals[36]; shared vec4 data[36]; -const uint depthDataSize = (gl_WorkGroupSize.x / 2 + 2) * (gl_WorkGroupSize.y / 2 + 2); -const ivec2 unflattenedDepthDataSize = ivec2(gl_WorkGroupSize) / 2 + 2; - layout(push_constant) uniform constants { int frameCount; } pushConstants; void LoadGroupSharedData() { - ivec2 workGroupOffset = ivec2(gl_WorkGroupID) * ivec2(gl_WorkGroupSize) / 2 - ivec2(1); - - // We assume data size is smaller than gl_WorkGroupSize.x + gl_WorkGroupSize.y - if (gl_LocalInvocationIndex < depthDataSize) { - ivec2 offset = Unflatten2D(int(gl_LocalInvocationIndex), unflattenedDepthDataSize); - offset += workGroupOffset; - offset = clamp(offset, ivec2(0), textureSize(lowResDepthTexture, 0) - 1); + ivec2 offset; + if (GetUpsampleTileTexel(textureSize(lowResDepthTexture, 0), offset)) { depths[gl_LocalInvocationIndex] = ConvertDepthToViewSpaceDepth(texelFetch(lowResDepthTexture, offset, 0).r); vec3 normal = DecodeNormal(texelFetch(lowResNormalTexture, offset, 0).rg); @@ -49,25 +44,6 @@ void LoadGroupSharedData() { } -const ivec2 offsets[9] = ivec2[9]( - ivec2(-1, -1), - ivec2(0, -1), - ivec2(1, -1), - ivec2(-1, 0), - ivec2(0, 0), - ivec2(1, 0), - ivec2(-1, 1), - ivec2(0, 1), - ivec2(1, 1) -); - -const ivec2 pixelOffsets[4] = ivec2[4]( - ivec2(0, 0), - ivec2(1, 0), - ivec2(0, 1), - ivec2(1, 1) -); - vec4 Upsample(float referenceDepth, vec3 referenceNormal, vec2 highResPixel) { highResPixel /= 2.0; @@ -109,8 +85,8 @@ void main() { LoadGroupSharedData(); - if (gl_GlobalInvocationID.x > imageSize(image).x || - gl_GlobalInvocationID.y > imageSize(image).y) + if (gl_GlobalInvocationID.x >= imageSize(image).x || + gl_GlobalInvocationID.y >= imageSize(image).y) return; ivec2 resolution = imageSize(image); diff --git a/data/shader/rtgi/atrous.csh b/data/shader/rtgi/atrous.csh index 02b3c7205..b0bee5e6c 100644 --- a/data/shader/rtgi/atrous.csh +++ b/data/shader/rtgi/atrous.csh @@ -5,6 +5,8 @@ #include <../common/material.hsh> #include <../common/normalencode.hsh> +#include <../common/denoiser.hsh> + layout (local_size_x = 16, local_size_y = 16) in; layout(set = 3, binding = 0, rgba16f) writeonly uniform image2D outputImage; @@ -24,6 +26,8 @@ const int kernelRadius = 4; const int kernelRadius = 8; #endif +const int stepSize = kernelRadius / 2; + const uint sharedDataSize = (gl_WorkGroupSize.x + 2 * kernelRadius) * (gl_WorkGroupSize.y + 2 * kernelRadius); const ivec2 unflattenedSharedDataSize = ivec2(gl_WorkGroupSize) + 2 * kernelRadius; @@ -37,19 +41,24 @@ struct PixelData { struct PackedPixelData { // Contains 16 bit color, variance, normal and roughness uvec4 data; - uint materialIdx; - float depth; }; +// Separate arrays, a struct with them would be padded to 32 bytes and exceed 32 KB of shared memory on some devices shared PackedPixelData pixelData[sharedDataSize]; +shared uint pixelMaterialIdx[sharedDataSize]; +shared float pixelDepth[sharedDataSize]; +shared uint groupFilters; layout(push_constant) uniform constants { - int stepSize; float strength; } pushConstants; const float kernelWeights[3] = { 1.0, 2.0 / 3.0, 1.0 / 6.0 }; +// In pixels, the three passes together reach 14 pixels +const float maxBlurRadius = 16.0; +const float minBlurRadius = 1.5; + PackedPixelData PackPixelData(PixelData data) { PackedPixelData compressed; @@ -57,8 +66,6 @@ PackedPixelData PackPixelData(PixelData data) { compressed.data.y = packHalf2x16(data.color.ba); compressed.data.z = packHalf2x16(data.normal.xy); compressed.data.w = packHalf2x16(vec2(data.normal.z, 0.0)); - compressed.materialIdx = data.materialIdx; - compressed.depth = data.depth; return compressed; } @@ -71,8 +78,6 @@ PixelData UnpackPixelData(PackedPixelData compressed) { data.normal.xy = unpackHalf2x16(compressed.data.z); vec2 temp = unpackHalf2x16(compressed.data.w); data.normal.z = temp.x; - data.materialIdx = compressed.materialIdx; - data.depth = compressed.depth; return data; } @@ -93,13 +98,17 @@ void LoadGroupSharedData() { data.color = texelFetch(inputTexture, texel, 0); - data.depth = texelFetch(depthTexture, texel, 0).r; + // Linear depth, zero marks the sky + float depth = texelFetch(depthTexture, texel, 0).r; + data.depth = depth == 1.0 ? 0.0 : ConvertDepthToViewSpaceDepth(depth); data.materialIdx = texelFetch(materialIdxTexture, texel, 0).r; data.normal = DecodeNormal(texelFetch(normalTexture, texel, 0).rg); pixelData[i] = PackPixelData(data); + pixelMaterialIdx[i] = data.materialIdx; + pixelDepth[i] = data.depth; } barrier(); @@ -110,40 +119,10 @@ PixelData GetPixel(ivec2 pixelOffset) { ivec2 pixel = ivec2(gl_LocalInvocationID) + ivec2(kernelRadius); int sharedMemoryIdx = Flatten2D(pixel + pixelOffset, unflattenedSharedDataSize); - return UnpackPixelData(pixelData[sharedMemoryIdx]); - -} - -float Luma(vec3 color) { - - const vec3 luma = vec3(0.299, 0.587, 0.114); - return dot(color, luma); - -} - -float ComputeEdgeStoppingWeight(float centerLuminance, float sampleLuminance, - vec3 centerNormal, vec3 sampleNormal, - float centerDepth, float sampleDepth, - uint centerMaterialIdx, uint sampleMaterialIdx, - float luminancePhi, float normalPhi, - float depthPhi, bool noHistory) { - - const float epsilon = 1e-10; - - float luminanceDiff = abs(centerLuminance - sampleLuminance); - float luminanceWeight = min(exp(-luminanceDiff / (luminancePhi + epsilon)), 1.0); - - luminanceWeight = noHistory ? 1.0 : luminanceWeight; - - float normalDiff = saturate(dot(centerNormal, sampleNormal)); - float normalWeight = min(pow(normalDiff, normalPhi), 1.0); - - float depthDiff = abs(centerDepth - sampleDepth); - float depthWeight = min(exp(-depthDiff * depthPhi), 1.0); - - float materialWeight = centerMaterialIdx == sampleMaterialIdx ? 1.0 : 0.0; - - return luminanceWeight * normalWeight * depthWeight * materialWeight; + PixelData data = UnpackPixelData(pixelData[sharedMemoryIdx]); + data.materialIdx = pixelMaterialIdx[sharedMemoryIdx]; + data.depth = pixelDepth[sharedMemoryIdx]; + return data; } @@ -173,75 +152,114 @@ float GetFilteredVariance(ivec2 pixel) { void main() { - LoadGroupSharedData(); - ivec2 pixel = ivec2(gl_GlobalInvocationID); ivec2 resolution = imageSize(outputImage); + bool insideImage = pixel.x < resolution.x && pixel.y < resolution.y; + + vec2 texCoord = (vec2(pixel) + 0.5) / vec2(resolution); + vec2 texelSize = 1.0 / vec2(resolution); - if (pixel.x >= resolution.x || pixel.y >= resolution.y) + float depth = insideImage ? texelFetch(depthTexture, pixel, 0).r : 1.0; + vec4 moments = insideImage ? texelFetch(historyLengthTexture, pixel, 0) : vec4(0.0); + + vec3 viewRay = GetViewRay(texCoord); + vec3 centerPosition = viewRay * ConvertDepthToViewSpaceDepth(depth); + + float historyLength = moments.b; + bool noHistory = historyLength <= 1.0; + + // The blur radius shrinks with the effectively accumulated frames and is limited by the hit distance. + // Short histories need the blur more than the details, the limit only sets in while they grow + float historyRadius = maxBlurRadius / sqrt(max(historyLength, 1.0)); + + float hitDistance = DecodeHitDistance(moments.a); + // The projection flips y, its scale is negative + float pixelWorldSize = 2.0 * abs(centerPosition.z) / (abs(globalData.pMatrix[1][1]) * float(resolution.y)); + float hitRadius = max(hitDistance / pixelWorldSize, maxBlurRadius / max(historyLength, 1.0)); + + float blurRadius = max(minBlurRadius, min(historyRadius, hitRadius)); + + // Below half the step size the taps of this pass have no weight left + bool filterPixel = insideImage && depth < 1.0 && blurRadius >= 0.5 * float(stepSize); + + if (gl_LocalInvocationIndex == 0) + groupFilters = 0u; + barrier(); + if (filterPixel) + atomicOr(groupFilters, 1u); + barrier(); + + if (groupFilters != 0u) + LoadGroupSharedData(); + + if (!insideImage || depth == 1.0) return; - vec2 texCoord = (vec2(pixel) + 0.5) / vec2(resolution); + if (!filterPixel) { + imageStore(outputImage, pixel, texelFetch(inputTexture, pixel, 0)); + return; + } + + vec3 viewRayDx = GetViewRay(texCoord + vec2(texelSize.x, 0.0)) - viewRay; + vec3 viewRayDy = GetViewRay(texCoord + vec2(0.0, texelSize.y)) - viewRay; PixelData centerPixelData = GetPixel(ivec2(0)); - + vec4 centerColor = centerPixelData.color; - float centerDepth = centerPixelData.depth; vec3 centerNormal = centerPixelData.normal; uint centerMaterialIdx = centerPixelData.materialIdx; - if (centerDepth == 1.0) - return; - - float historyLength = texelFetch(historyLengthTexture, pixel, 0).b; - bool noHistory = historyLength <= 1.0; - float centerLuminance = Luma(centerColor.rgb); - float centerLinearDepth = ConvertDepthToViewSpaceDepth(centerDepth); - + vec4 outputColor = centerColor; float totalWeight = 1.0; float variance = GetFilteredVariance(pixel); float stdDeviation = sqrt(max(0.0, variance)); - vec3 viewDir = normalize(ConvertDepthToViewSpace(centerDepth, texCoord)); + vec3 viewDir = normalize(centerPosition); float NdotV = abs(dot(viewDir, centerNormal)); float depthPhi = max(32.0, NdotV * 128.0); + // All weights of a tap go into one exponent, the terms that don't depend on the tap are computed once. + // The distance to the surface plane is affine in the offset since the view ray is + const float log2e = 1.442695; + float planeRay = dot(viewRay, centerNormal); + float planeRayDx = dot(viewRayDx, centerNormal); + float planeRayDy = dot(viewRayDy, centerNormal); + float planeOffset = dot(centerPosition, centerNormal); + float planeScale = depthPhi * log2e / abs(centerPosition.z); + float luminanceScale = noHistory ? 0.0 : log2e / (stdDeviation * pushConstants.strength + 1e-10); + float normalPhi = noHistory ? 2.0 : NdotV * 128.0; + float distanceScale = log2e * float(stepSize * stepSize) / sqr(blurRadius); + const int radius = 2; for (int x = -radius; x <= radius; x++) { - for (int y = -radius; y <= radius; y++) { - ivec2 samplePixel = pixel + ivec2(x, y) * pushConstants.stepSize; + for (int y = -radius; y <= radius; y++) { + ivec2 offset = ivec2(x, y) * stepSize; + ivec2 samplePixel = pixel + offset; if (samplePixel.x >= resolution.x || samplePixel.y >= resolution.y || samplePixel.x < 0 || samplePixel.y < 0 || (x == 0 && y == 0)) continue; - PixelData samplePixelData = GetPixel(ivec2(x, y) * pushConstants.stepSize); + PixelData samplePixelData = GetPixel(offset); - if (samplePixelData.depth == 1.0) + if (samplePixelData.depth == 0.0 || samplePixelData.materialIdx != centerMaterialIdx) continue; vec4 sampleColor = samplePixelData.color; - vec3 sampleNormal = samplePixelData.normal; - - float sampleDepth = samplePixelData.depth; - float sampleLuminance = Luma(sampleColor.rgb); - - uint sampleMaterialIdx = samplePixelData.materialIdx; - float kernelWeight = kernelWeights[abs(x)] * kernelWeights[abs(y)]; - float edgeStoppingWeight = ComputeEdgeStoppingWeight( - centerLuminance, sampleLuminance, - centerNormal, sampleNormal, - centerDepth, sampleDepth, - centerMaterialIdx, sampleMaterialIdx, - stdDeviation * pushConstants.strength, - noHistory ? 2.0 : NdotV * 128.0, depthPhi, noHistory); + // The distance to the surface plane stays stable at grazing angles, unlike the depth + float planeDistance = samplePixelData.depth * (planeRay + float(offset.x) * planeRayDx + + float(offset.y) * planeRayDy) - planeOffset; + float normalDot = max(dot(centerNormal, samplePixelData.normal), 1e-6); - float weight = kernelWeight * edgeStoppingWeight; + float exponent = abs(centerLuminance - Luma(sampleColor.rgb)) * luminanceScale + + abs(planeDistance) * planeScale + float(x * x + y * y) * distanceScale - + normalPhi * log2(normalDot); + float weight = kernelWeights[abs(x)] * kernelWeights[abs(y)] * exp2(-exponent); totalWeight += weight; outputColor += vec4(vec3(weight), weight * weight) * sampleColor; diff --git a/data/shader/rtgi/rtgi.csh b/data/shader/rtgi/rtgi.csh index 4f3cca3aa..1e1e6bd7e 100644 --- a/data/shader/rtgi/rtgi.csh +++ b/data/shader/rtgi/rtgi.csh @@ -1,5 +1,3 @@ -#define SHADOW_FILTER_1x1 - #include <../globals.hsh> #include <../raytracer/lights.hsh> #include <../raytracer/tracing.hsh> @@ -22,9 +20,12 @@ #include <../ddgi/ddgi.hsh> #include <../ddgi/transmission.hsh> #include <../clouds/shadow.hsh> -#include <../shadow.hsh> +#include <../common/denoiser.hsh> + +#ifndef RAY_TRACING_PIPELINE layout (local_size_x = 8, local_size_y = 4) in; +#endif layout (set = 3, binding = 0, rgba16f) writeonly uniform image2D rtrImage; @@ -33,7 +34,6 @@ layout(set = 3, binding = 2) uniform sampler2D depthTexture; layout(set = 3, binding = 3) uniform sampler2D roughnessMetallicAoTexture; layout(set = 3, binding = 4) uniform isampler2D offsetTexture; layout(set = 3, binding = 5) uniform usampler2D materialIdxTexture; -layout(set = 3, binding = 6) uniform sampler2DArrayShadow cascadeMaps; layout(set = 3, binding = 7) uniform sampler2D scramblingRankingTexture; layout(set = 3, binding = 8) uniform sampler2D sobolSequenceTexture; @@ -65,24 +65,21 @@ layout(std140, set = 3, binding = 10) uniform UniformBuffer { int textureLevel; float roughnessCutoff; int halfRes; - int padding0; - int padding1; ivec2 resolution; - Shadow shadow; } uniforms; +#include <../raytracer/lighting.hsh> + vec3 EvaluateHit(inout Ray ray, vec3 cubemapSamplingDirection, float rand); -vec3 EvaluateDirectLight(inout Surface surface, inout float seed); -float CheckVisibility(Surface surface, float lightDistance); void main() { ivec2 resolution = uniforms.resolution; - if (int(gl_GlobalInvocationID.x) < resolution.x && - int(gl_GlobalInvocationID.y) < resolution.y) { + if (int(INVOCATION_ID.x) < resolution.x && + int(INVOCATION_ID.y) < resolution.y) { - ivec2 pixel = ivec2(gl_GlobalInvocationID.xy); + ivec2 pixel = ivec2(INVOCATION_ID.xy); vec2 texCoord = (vec2(pixel) + vec2(0.5)) / vec2(resolution); @@ -107,11 +104,18 @@ void main() { Material material = UnpackMaterial(materialIdx); vec3 reflection = vec3(0.0); +#ifdef DEFERRED_SHADOW_RAYS + int pixelIdx = pixel.y * resolution.x + pixel.x; +#endif + + // Mean of the encoded hit distances, misses count as one + float hitDistanceSum = 0.0; + int hitDistanceCount = 0; if (depth < 1.0) { #ifdef AUTO_EXPOSURE - float radianceLimit = 9.6 * uniforms.radianceLimit * texelFetch(exposureTexture, ivec2(0), 0).r; + float radianceLimit = 9.6 * uniforms.radianceLimit * texelFetch(exposureTexture, ivec2(0), 0).r * globalData.preExposure; #else float radianceLimit = uniforms.radianceLimit; #endif @@ -120,6 +124,13 @@ void main() { for (int i = 0; i < sampleCount; i++) { int sampleIdx = int(uniforms.frameSeed) * sampleCount + i; +#ifdef DEFERRED_SHADOW_RAYS + int deferredSampleIdx = pixelIdx * sampleCount + i; + deferredSamples[deferredSampleIdx].radiance.w = 0.0; + deferredLightBase = deferredSampleIdx * uniforms.lightSampleCount; + for (int j = 0; j < uniforms.lightSampleCount; j++) + deferredLights[deferredLightBase + j] = vec4(0.0, 0.0, 0.0, 1.0); +#endif vec3 blueNoiseVec = vec3( SampleBlueNoise(pixel, sampleIdx, 0, scramblingRankingTexture, sobolSequenceTexture), SampleBlueNoise(pixel, sampleIdx, 1, scramblingRankingTexture, sobolSequenceTexture), @@ -163,8 +174,8 @@ void main() { if (isRayValid) { // Scale offset by depth since the depth buffer inaccuracies increase at a distance and might not match the ray traced geometry anymore - float viewOffset = max(1.0, 4.0 * length(viewPos)); - ray.origin = worldPos + ray.direction * EPSILON * viewOffset + sampleNormal * EPSILON * viewOffset; + float viewOffset = max(1.0, 1.0 * length(viewPos)); + ray.origin = worldPos + sampleNormal * EPSILON * viewOffset; ray.hitID = -1; ray.hitDistance = 0.0; @@ -179,11 +190,10 @@ void main() { #endif vec3 radiance = vec3(0.0); -#ifdef OPACITY_CHECK - HitClosestTransparency(ray, INSTANCE_MASK_ALL, 0.0, rayLength); -#else - HitClosest(ray, INSTANCE_MASK_ALL, 0.0, rayLength); -#endif + HitClosestOpacityCheck(ray, INSTANCE_MASK_ALL, 0.0, rayLength); + + hitDistanceSum += ray.hitID != -1 ? EncodeHitDistance(ray.hitDistance) : 1.0; + hitDistanceCount++; #ifdef DDGI radiance = EvaluateHit(ray, sampleNormal, blueNoiseVec.z); @@ -197,6 +207,12 @@ void main() { radiance = EvaluateHit(ray, sampleNormal, blueNoiseVec.z); #endif +#ifdef DEFERRED_SHADOW_RAYS + deferredSamples[deferredSampleIdx].radiance = vec4(radiance, 1.0); + deferredSamples[deferredSampleIdx].lobeWeight = vec4(lobeWeight, radianceLimit); + continue; +#endif + if (isnan3(radiance) || isinf3(radiance)) radiance = vec3(0.0); @@ -212,8 +228,16 @@ void main() { reflection /= float(sampleCount); } +#ifdef DEFERRED_SHADOW_RAYS + else { + for (int i = 0; i < uniforms.sampleCount; i++) + deferredSamples[pixelIdx * uniforms.sampleCount + i].radiance.w = 0.0; + } +#endif - imageStore(rtrImage, pixel, vec4(reflection, 1.0)); + // With deferred shadow rays the resolve adds the radiance and keeps the hit distance + float hitDistance = hitDistanceCount > 0 ? hitDistanceSum / float(hitDistanceCount) : 1.0; + imageStore(rtrImage, pixel, vec4(reflection, hitDistance)); } } @@ -228,12 +252,8 @@ vec3 EvaluateHit(inout Ray ray, vec3 cubemapSamplingDirection, float rand) { return textureLod(specularProbe, ray.direction, 3.0).rgb; } - // Unpack the compressed triangle and extract surface parameters - Instance instance = GetInstance(ray); - Triangle tri = GetTriangle(ray, instance); - bool backfaceHit; - Surface surface = GetSurfaceParameters(instance, tri, ray, false, backfaceHit, uniforms.textureLevel); + Surface surface = GetHitSurface(ray, false, backfaceHit, uniforms.textureLevel); #ifdef DDGI // Trick: Offset on secondary bounce towards camera, avoids light leaking (introducing innacuracies ofc) @@ -255,75 +275,9 @@ vec3 EvaluateHit(inout Ray ray, vec3 cubemapSamplingDirection, float rand) { radiance += surface.material.emissiveColor; float curSeed = float(uniforms.frameSeed) / 255.0; - // Evaluate direct light - for (int i = 0; i < uniforms.lightSampleCount; i++) { - radiance += (EvaluateDirectLight(surface, curSeed) / float(uniforms.lightSampleCount)); - curSeed += 1.0 / float(uniforms.lightSampleCount); - } + float raySeed = float(INVOCATION_ID.x * uniforms.resolution.y + INVOCATION_ID.y); + radiance += EvaluateDirectLights(surface, raySeed, curSeed, uniforms.lightSampleCount); return radiance; } - -vec3 EvaluateDirectLight(inout Surface surface, inout float seed) { - - if (GetLightCount() == 0) - return vec3(0.0); - - float raySeed = float(gl_GlobalInvocationID.x * uniforms.resolution.y + gl_GlobalInvocationID.y); - - float lightPdf; - Light light = GetLight(surface, raySeed, seed, lightPdf); - - float solidAngle, lightDistance; - SampleLight(light, surface, raySeed, seed, solidAngle, lightDistance); - - bool transmittedLight = IsTransmittedLight(surface); - Surface lightSurface = transmittedLight ? GetTransmissionSurface(surface) : surface; - -#ifdef USE_SHADOW_MAP - float shadowFactor = CalculateShadowWorldSpace(uniforms.shadow, cascadeMaps, surface.P, - lightSurface.geometryNormal, saturate(dot(lightSurface.L, lightSurface.geometryNormal))); -#else - float shadowFactor = 1.0; - if (light.castShadow) - shadowFactor *= CheckVisibility(lightSurface, lightDistance); -#endif - - // Evaluate the BRDF - vec3 reflectance = transmittedLight ? GetTransmissionColor(surface.material) * EvaluateDiffuseBRDF(lightSurface) : - EvaluateDiffuseBRDF(surface) + EvaluateSpecularBRDF(surface); - reflectance *= surface.material.opacity; - vec3 radiance = light.radiance * solidAngle * shadowFactor; - - // Check for visibilty. This is important to get an - // estimate of the solid angle of the light from point P - // on the surface. - -#ifdef CLOUD_SHADOWS - if (light.type == uint(DIRECTIONAL_LIGHT)) { - vec3 P = vec3(globalData.vMatrix * vec4(surface.P, 1.0)); - float cloudShadowFactor = CalculateCloudShadow(P, cloudShadowUniforms.cloudShadow, cloudMap); - - radiance *= cloudShadowFactor; - } -#endif - - return reflectance * radiance * lightSurface.NdotL / lightPdf; - -} - -float CheckVisibility(Surface surface, float lightDistance) { - - if (surface.NdotL > 0.0) { - Ray ray; - ray.direction = surface.L; - float side = dot(surface.L, surface.geometryNormal) < 0.0 ? -1.0 : 1.0; - ray.origin = surface.P + surface.geometryNormal * (side * EPSILON); - return HitAnyTransparency(ray, INSTANCE_MASK_SHADOW, 0.0, lightDistance - 2.0 * EPSILON); - } - else { - return 0.0; - } - -} diff --git a/data/shader/rtgi/rtgi.rgen b/data/shader/rtgi/rtgi.rgen new file mode 100644 index 000000000..278f23a74 --- /dev/null +++ b/data/shader/rtgi/rtgi.rgen @@ -0,0 +1,7 @@ +// RTGI as the ray generation stage of a ray tracing pipeline, see bvh.hsh for the tracing +#extension GL_EXT_ray_tracing : require +#extension GL_EXT_shader_invocation_reorder : require + +#define RAY_TRACING_PIPELINE + +#include diff --git a/data/shader/rtgi/rtgiResolve.csh b/data/shader/rtgi/rtgiResolve.csh new file mode 100644 index 000000000..dc5a00f95 --- /dev/null +++ b/data/shader/rtgi/rtgiResolve.csh @@ -0,0 +1,52 @@ +#include <../common/utility.hsh> +#include <../raytracer/deferredShadow.hsh> + +layout (local_size_x = 8, local_size_y = 4) in; + +layout (set = 3, binding = 0, rgba16f) uniform image2D giImage; + +layout(push_constant) uniform constants { + ivec2 resolution; + int sampleCount; + int lightSampleCount; +} pushConstants; + +void main() { + + ivec2 resolution = pushConstants.resolution; + if (int(gl_GlobalInvocationID.x) >= resolution.x || int(gl_GlobalInvocationID.y) >= resolution.y) + return; + + ivec2 pixel = ivec2(gl_GlobalInvocationID.xy); + int pixelIdx = pixel.y * resolution.x + pixel.x; + + vec3 gi = vec3(0.0); + for (int i = 0; i < pushConstants.sampleCount; i++) { + int sampleIdx = pixelIdx * pushConstants.sampleCount + i; + if (deferredSamples[sampleIdx].radiance.w == 0.0) + continue; + + vec3 radiance = deferredSamples[sampleIdx].radiance.rgb; + for (int j = 0; j < pushConstants.lightSampleCount; j++) { + vec4 light = deferredLights[sampleIdx * pushConstants.lightSampleCount + j]; + radiance += light.rgb * light.w; + } + + if (isnan3(radiance) || isinf3(radiance)) + radiance = vec3(0.0); + + radiance = max(radiance, vec3(0.0)); + + float radianceLimit = deferredSamples[sampleIdx].lobeWeight.w; + float radianceMax = max(max(max(radiance.r, + max(radiance.g, radiance.b)), radianceLimit), 1e-12); + radiance *= radianceLimit / radianceMax; + + gi += radiance * deferredSamples[sampleIdx].lobeWeight.rgb; + } + + gi /= float(pushConstants.sampleCount); + float hitDistance = imageLoad(giImage, pixel).a; + imageStore(giImage, pixel, vec4(gi, hitDistance)); + +} diff --git a/data/shader/rtgi/temporal.csh b/data/shader/rtgi/temporal.csh index 4da3d6b35..61f9c410a 100644 --- a/data/shader/rtgi/temporal.csh +++ b/data/shader/rtgi/temporal.csh @@ -12,6 +12,7 @@ #include <../common/random.hsh> #include <../common/normalencode.hsh> #include <../common/edgePreserving.hsh> +#include <../common/denoiser.hsh> layout (local_size_x = 16, local_size_y = 16) in; @@ -34,13 +35,21 @@ layout(set = 3, binding = 12) uniform usampler2D historyMaterialIdxTexture; vec2 invResolution = 1.0 / vec2(imageSize(resolveImage)); vec2 resolution = vec2(imageSize(resolveImage)); -const int kernelRadius = 5; +const int kernelRadius = 3; const uint sharedDataSize = (gl_WorkGroupSize.x + 2 * kernelRadius) * (gl_WorkGroupSize.y + 2 * kernelRadius); const ivec2 unflattenedSharedDataSize = ivec2(gl_WorkGroupSize) + 2 * kernelRadius; shared vec4 sharedRadianceDepth[sharedDataSize]; shared uint sharedMaterialIdx[sharedDataSize]; +shared float sharedHitDistance[sharedDataSize]; +shared vec2 sharedObjectMotion[sharedDataSize]; + +// Neighborhood of the encoded hit distance that is accumulated and compared with its history +const int hitDistanceRadius = 2; +// Spread of a pixel's encoded hit distance assumed in addition to the measured one, +// a few neighbors or identical values (all misses) don't give a reliable estimate +const float hitDistancePriorSpread = 0.1; layout(push_constant) uniform constants { float temporalWeight; @@ -68,20 +77,6 @@ const ivec2 pixelOffsets[4] = ivec2[4]( ivec2(1, 1) ); -float Luma(vec3 color) { - - const vec3 luma = vec3(0.299, 0.587, 0.114); - return dot(color, luma); - -} - -vec3 FetchTexel(ivec2 texel) { - - vec3 color = max(texelFetch(currentTexture, texel, 0).rgb, 0); - return color; - -} - void LoadGroupSharedData() { ivec2 workGroupOffset = ivec2(gl_WorkGroupID) * ivec2(gl_WorkGroupSize) - ivec2(kernelRadius); @@ -93,9 +88,13 @@ void LoadGroupSharedData() { texel = clamp(texel, ivec2(0), ivec2(resolution) - ivec2(1)); - sharedRadianceDepth[i].rgb = RGBToYCoCg(FetchTexel(texel)); - sharedRadianceDepth[i].a = texelFetch(depthTexture, texel, 0).r; + vec4 current = texelFetch(currentTexture, texel, 0); + float depth = texelFetch(depthTexture, texel, 0).r; + sharedRadianceDepth[i].rgb = RGBToYCoCg(max(current.rgb, 0.0)); + sharedHitDistance[i] = current.a; + sharedRadianceDepth[i].a = ConvertDepthToViewSpaceDepth(depth); sharedMaterialIdx[i].r = texelFetch(materialIdxTexture, texel, 0).r; + sharedObjectMotion[i] = GetObjectMotion(velocityTexture, texel, depth, resolution); } barrier(); @@ -146,31 +145,18 @@ ivec2 FindNearest3x3(ivec2 pixel) { } -float ClipBoundingBox(vec3 boxMin, vec3 boxMax, vec3 history, vec3 current) { - - vec3 origin = history; - vec3 dir = current - history; - - // Make sure dir isn't zero - dir.x = abs(dir.x) < (1.0 / 32767.0) ? (1.0 / 32767.0) : dir.x; - dir.y = abs(dir.y) < (1.0 / 32767.0) ? (1.0 / 32767.0) : dir.y; - dir.z = abs(dir.z) < (1.0 / 32767.0) ? (1.0 / 32767.0) : dir.z; +// The bilinear footprint is complete when all four history texels are valid, their range limits a bicubic filter. +// The confidence is the valid part of the footprint, it shortens the history of partly valid reprojections +bool SampleHistory(ivec2 pixel, vec2 historyPixel, out vec4 history, out vec4 historyMoments, + out bool completeFootprint, out vec4 historyMin, out vec4 historyMax, out float footprintConfidence) { - vec3 invDir = 1.0 / dir; - - vec3 t0 = (boxMin - origin) * invDir; - vec3 t1 = (boxMax - origin) * invDir; - - vec3 intersect = min(t0, t1); - return max(intersect.x, max(intersect.y, intersect.z)); - -} - -bool SampleHistory(ivec2 pixel, vec2 historyPixel, out vec4 history, out vec4 historyMoments) { - + footprintConfidence = 0.0; history = vec4(0.0); historyMoments = vec4(0.0); + historyMin = vec4(1e30); + historyMax = vec4(-1e30); + int validCount = 0; float totalWeight = 0.0; float x = fract(historyPixel.x); float y = fract(historyPixel.y); @@ -187,7 +173,6 @@ bool SampleHistory(ivec2 pixel, vec2 historyPixel, out vec4 history, out vec4 hi vec3 viewDir = normalize(position - globalData.cameraLocation.xyz); float NdotV = abs(dot(viewDir, worldNormal)); - float linearDepth = depth; float depthPhi = max(1.0, NdotV * 32.0 * abs(ConvertDepthToViewSpaceDepth(depth))); // Calculate confidence over 2x2 bilinear neighborhood @@ -202,16 +187,27 @@ bool SampleHistory(ivec2 pixel, vec2 historyPixel, out vec4 history, out vec4 hi float historyDepth = texelFetch(historyDepthTexture, offsetPixel, 0).r; float depthWeight = min(1.0 , exp(-abs(depth - historyDepth) * depthPhi)); - float confidence = normalWeight * depthWeight; + uint historyMaterialIdx = texelFetch(historyMaterialIdxTexture, offsetPixel, 0).r; + float materialWeight = historyMaterialIdx == materialIdx ? 1.0 : 0.0; + + float confidence = normalWeight * depthWeight * materialWeight; + + if (confidence > 0.2) { + vec4 historyTexel = texelFetch(historyTexture, offsetPixel, 0); + historyMin = min(historyMin, historyTexel); + historyMax = max(historyMax, historyTexel); + validCount++; - if (confidence > 0.2) { totalWeight += weights[i]; - history += texelFetch(historyTexture, offsetPixel, 0) * weights[i]; + history += historyTexel * weights[i]; historyMoments += texelFetch(historyMomentsTexture, offsetPixel, 0) * weights[i]; } } + completeFootprint = validCount == 4; + if (totalWeight > 0.0) { + footprintConfidence = totalWeight; history /= totalWeight; historyMoments /= totalWeight; return true; @@ -228,7 +224,10 @@ bool SampleHistory(ivec2 pixel, vec2 historyPixel, out vec4 history, out vec4 hi float historyDepth = texelFetch(historyDepthTexture, offsetPixel, 0).r; float depthWeight = min(1.0 , exp(-abs(depth - historyDepth) * depthPhi)); - float confidence = normalWeight * depthWeight; + uint historyMaterialIdx = texelFetch(historyMaterialIdxTexture, offsetPixel, 0).r; + float materialWeight = historyMaterialIdx == materialIdx ? 1.0 : 0.0; + + float confidence = normalWeight * depthWeight * materialWeight; if (confidence > 0.5) { totalWeight += 1.0; @@ -238,6 +237,8 @@ bool SampleHistory(ivec2 pixel, vec2 historyPixel, out vec4 history, out vec4 hi } if (totalWeight > 0.0) { + // None of the footprint texels matched, the neighbors around it are less trustworthy + footprintConfidence = totalWeight / 9.0; history /= totalWeight; historyMoments /= totalWeight; return true; @@ -250,91 +251,20 @@ bool SampleHistory(ivec2 pixel, vec2 historyPixel, out vec4 history, out vec4 hi } -float IsHistoryPixelValid(ivec2 pixel, float linearDepth, vec3 normal, float depthPhi) { - - float confidence = 1.0; - - vec3 historyNormal = DecodeNormal(texelFetch(historyNormalTexture, pixel, 0).rg); - confidence *= GetEdgePreservingNormalWeight(normal, historyNormal, 1.0); - - float historyDepth = ConvertDepthToViewSpaceDepth(texelFetch(historyDepthTexture, pixel, 0).r); - confidence *= min(1.0 , exp(-abs(linearDepth - historyDepth))); - - return confidence > 0.1 ? 1.0 : 0.0; - -} - -vec4 GetCatmullRomSample(ivec2 pixel, inout float weight, float linearDepth, vec3 normal, float depthPhi) { - - pixel = clamp(pixel, ivec2(0), ivec2(imageSize(resolveImage) - 1)); - - weight *= IsHistoryPixelValid(pixel, linearDepth, normal, depthPhi); - - return texelFetch(historyTexture, pixel, 0) * weight; - -} - -bool SampleCatmullRom(ivec2 pixel, vec2 uv, out vec4 history) { - - vec3 normal = DecodeNormal(texelFetch(normalTexture, pixel, 0).rg); - float depth = texelFetch(depthTexture, pixel, 0).r; - vec2 texCoord = (vec2(pixel) + 0.5) / resolution; - vec3 position = ConvertDepth(depth, texCoord, globalData.ipvMatrixCurrent); - vec3 worldNormal = vec3(globalData.ivMatrix * vec4(normal, 0.0)); - - vec3 viewDir = normalize(position - globalData.cameraLocation.xyz); - float NdotV = abs(dot(viewDir, worldNormal)); - float linearDepth = ConvertDepthToViewSpaceDepth(depth); - float depthPhi = max(1.0, NdotV * 16.0 / max(1.0, abs(linearDepth))); - - vec2 samplePixel = uv * resolution; - - vec2 center = floor(samplePixel - 0.5) + 0.5; - vec2 f = samplePixel - center; - vec2 f2 = f * f; - vec2 f3 = f2 * f; - - vec2 w0 = f2 - 0.5 * (f3 + f); - vec2 w1 = 1.5 * f3 - 2.5 * f2 + 1.0; - vec2 w3 = 0.5 * (f3 - f2); - vec2 w2 = 1.0 - w0 - w1 - w3; - - ivec2 uv0 = ivec2(center - 1.0); - ivec2 uv1 = ivec2(center); - ivec2 uv2 = ivec2(center + 1.0); - ivec2 uv3 = ivec2(center + 2.0); - - ivec2 uvs[4] = { uv0, uv1, uv2, uv3 }; - vec2 weights[4] = { w0, w1, w2, w3 }; - - history = vec4(0.0); - - float totalWeight = 0.0; - - for (int x = 0; x <= 3; x++) { - for (int y = 0; y <= 3; y++) { - float weight = weights[x].x * weights[y].y; - ivec2 uv = ivec2(uvs[x].x, uvs[y].y); - - history += GetCatmullRomSample(uv, weight, linearDepth, normal, depthPhi); - totalWeight += weight; - } - } - - if (totalWeight > 0.5) { - history /= totalWeight; - history = max(history, 0.0); - - return true; - } - - return false; -} - -void ComputeVarianceMinMax(out vec3 mean, out vec3 std) { +// Sample counts are effective ones of the weighted neighborhoods, (sum of weights)^2 / sum of squared weights. +// The hit distance mean comes with its standard error, the noise expected for it without any change. +// The nearby motion is the fastest movement of a neighbor around the same depth relative to the pixel in pixels +void ComputeVarianceMinMax(out vec3 mean, out vec3 std, out float sampleCount, + out float hitDistanceMean, out float hitDistanceError, out float nearbyMotion) { vec3 m1 = vec3(0.0); vec3 m2 = vec3(0.0); + float squaredWeight = 0.0; + + float h1 = 0.0; + float h2 = 0.0; + float hitDistanceWeight = 0.0; + float hitDistanceSquaredWeight = 0.0; // This could be varied using the temporal variance estimation // By using a wide neighborhood for variance estimation (8x8) we introduce block artifacts @@ -356,33 +286,52 @@ void ComputeVarianceMinMax(out vec3 mean, out vec3 std) { float totalWeight = 0.0; + vec2 centerObjectMotion = sharedObjectMotion[GetSharedMemoryIndex(ivec2(0))]; + float nearbyMotionSquared = 0.0; + float depthScale = 1.442695 * depthPhi; + for (int i = -radius; i <= radius; i++) { for (int j = -radius; j <= radius; j++) { int sharedMemoryIdx = GetSharedMemoryIndex(ivec2(i, j)); vec3 sampleRadiance = FetchCurrentRadiance(sharedMemoryIdx); - float sampleDepth = FetchDepth(sharedMemoryIdx); + float sampleLinearDepth = FetchDepth(sharedMemoryIdx); uint sampleMaterialIdx = FetchMaterialIdx(sharedMemoryIdx); - ivec2 samplePixel = pixel + ivec2(i, j); - texCoord = (vec2(pixel) + 0.5) / resolution; - vec3 samplePosition = ConvertDepth(sampleDepth, texCoord, globalData.ipvMatrixCurrent); - - float sampleLinearDepth = ConvertDepthToViewSpaceDepth(sampleDepth); - float weight = min(1.0 , exp(-abs(linearDepth - sampleLinearDepth) * depthPhi)); + float weight = exp2(-abs(linearDepth - sampleLinearDepth) * depthScale); weight *= sampleMaterialIdx != materialIdx ? 0.0 : 1.0; m1 += sampleRadiance * weight; m2 += sampleRadiance * sampleRadiance * weight; - totalWeight += weight; + totalWeight += weight; + squaredWeight += weight * weight; + + nearbyMotionSquared = max(nearbyMotionSquared, GetNearbyMotionSquared(sharedObjectMotion[sharedMemoryIdx], + centerObjectMotion, linearDepth, sampleLinearDepth)); + + if (abs(i) <= hitDistanceRadius && abs(j) <= hitDistanceRadius) { + float sampleHitDistance = sharedHitDistance[sharedMemoryIdx]; + h1 += sampleHitDistance * weight; + h2 += sampleHitDistance * sampleHitDistance * weight; + hitDistanceWeight += weight; + hitDistanceSquaredWeight += weight * weight; + } } } mean = m1 / totalWeight; std = sqrt(max((m2 / totalWeight) - (mean * mean), 0.0)); + sampleCount = sqr(totalWeight) / squaredWeight; + nearbyMotion = sqrt(nearbyMotionSquared); + + hitDistanceMean = h1 / hitDistanceWeight; + float hitDistanceSampleCount = sqr(hitDistanceWeight) / hitDistanceSquaredWeight; + float hitDistanceVariance = max(h2 / hitDistanceWeight - hitDistanceMean * hitDistanceMean, 0.0) * + hitDistanceSampleCount / max(hitDistanceSampleCount - 1.0, 1.0); + hitDistanceError = sqrt((hitDistanceVariance + sqr(hitDistancePriorSpread)) / hitDistanceSampleCount); } void main() { @@ -390,12 +339,13 @@ void main() { LoadGroupSharedData(); ivec2 pixel = ivec2(gl_GlobalInvocationID); - if (pixel.x > imageSize(resolveImage).x || - pixel.y > imageSize(resolveImage).y) + if (pixel.x >= imageSize(resolveImage).x || + pixel.y >= imageSize(resolveImage).y) return; vec3 mean, std; - ComputeVarianceMinMax(mean, std); + float sampleCount, hitDistanceMean, hitDistanceError, nearbyMotion; + ComputeVarianceMinMax(mean, std, sampleCount, hitDistanceMean, hitDistanceError, nearbyMotion); ivec2 velocityPixel = pixel; vec2 velocity = texelFetch(velocityTexture, velocityPixel, 0).rg; @@ -403,18 +353,25 @@ void main() { vec2 uv = (vec2(pixel) + vec2(0.5)) * invResolution + velocity; vec2 historyPixel = vec2(pixel) + (velocity * resolution); - bool valid = true; vec4 history; vec4 historyMoments; - valid = SampleHistory(pixel, historyPixel, history, historyMoments); + bool completeFootprint; + vec4 historyMin, historyMax; + float footprintConfidence; + bool valid = SampleHistory(pixel, historyPixel, history, historyMoments, + completeFootprint, historyMin, historyMax, footprintConfidence); #ifdef BICUBIC_FILTER - // This should be implemented more efficiently, see - vec4 catmullRomHistory; - bool success = SampleCatmullRom(pixel, uv, catmullRomHistory); - history = success && valid ? catmullRomHistory : history; + // The clamp removes ringing and texels outside the footprint that belong to other surfaces + if (completeFootprint) + history = clamp(SampleCatmullRom(historyTexture, uv, resolution), historyMin, historyMax); #endif + // The history was stored with the pre-exposure of the last frame, the moments hold luma and its square + float exposureScale = globalData.preExposure / globalData.lastPreExposure; + history.rgb *= exposureScale; + historyMoments.rg *= vec2(exposureScale, exposureScale * exposureScale); + vec3 historyColor = RGBToYCoCg(history.rgb); vec3 currentColor = RGBToYCoCg(texelFetch(currentTexture, pixel, 0).rgb); @@ -422,52 +379,57 @@ void main() { currentMoments.r = currentColor.r; currentMoments.g = currentMoments.r * currentMoments.r; - float historyLength = historyMoments.b; + float historyLength = historyMoments.b * footprintConfidence; + + // A changed hit distance means the geometry the rays see changed, shorten above two standard errors, reset at six + float hitDistanceDeviation = abs(hitDistanceMean - historyMoments.a) / hitDistanceError; + historyLength *= saturate((6.0 - hitDistanceDeviation) / 4.0); + + historyLength = LimitHistoryByNearbyMotion(historyLength, nearbyMotion); - vec3 historyNeighbourhoodMin = mean - std; - vec3 historyNeighbourhoodMax = mean + std; + // Two standard deviations, a narrower box shortens converged histories at highlights and edges + vec3 historyNeighbourhoodMin = mean - 2.0 * std; + vec3 historyNeighbourhoodMax = mean + 2.0 * std; vec3 currentNeighbourhoodMin = mean - pushConstants.currentClipFactor * std; vec3 currentNeighbourhoodMax = mean + pushConstants.currentClipFactor * std; - // In case of clipping we might also reject the sample. TODO: Investigate + // Histories outside the neighborhood shorten, small neighborhoods (thin objects, edges) fully from ten samples on float clipBlend = ClipBoundingBox(historyNeighbourhoodMin, historyNeighbourhoodMax, historyColor, currentColor); float adjClipBlend = clamp(clipBlend, 0.0, pushConstants.historyClipMax); + historyLength *= 1.0 - adjClipBlend * saturate((sampleCount - 2.0) / 8.0); currentColor = clamp(currentColor, currentNeighbourhoodMin, currentNeighbourhoodMax); - currentColor.r = valid ? currentColor.r : mean.r; - - historyColor = YCoCgToRGB(historyColor); - currentColor = YCoCgToRGB(currentColor); - - //float factor = mix(0.0, pushConstants.temporalWeight, 1.0 - adjClipBlend); - float factor = mix(pushConstants.temporalWeight, 0.5, adjClipBlend); - factor = (uv.x < 0.0 || uv.y < 0.0 || uv.x > 1.0 - || uv.y > 1.0) ? 0.0 : factor; - - factor = pushConstants.resetHistory > 0 ? 0.0 : factor; - - if (factor == 0.0 || !valid) { + if (IsOffscreen(uv) || pushConstants.resetHistory > 0 || !valid) { historyLength = 0.0; currentMoments.g = 1.0; currentMoments.r = 0.0; } - factor = max(0.75, factor - 20.0 * max(abs(velocity.x), abs(velocity.y))); - factor = min(factor, historyLength / (historyLength + 1.0)); + // New and short histories (disocclusions) start from the neighborhood mean instead of single noisy samples + currentColor = mix(mean, currentColor, saturate(historyLength / 4.0)); + + historyColor = YCoCgToRGB(historyColor); + currentColor = YCoCgToRGB(currentColor); + + float factor = min(pushConstants.temporalWeight, historyLength / (historyLength + 1.0)); vec3 resolve = factor <= 0.0 ? currentColor : mix(currentColor, historyColor, factor); vec2 momentsResolve = factor <= 0.0 ? currentMoments : mix(currentMoments, historyMoments.rg, factor); + float hitDistance = factor <= 0.0 ? hitDistanceMean : mix(hitDistanceMean, historyMoments.a, factor); + + float accumulatedFrames = GetAccumulatedFrames(factor, historyLength); + // Boost variance when we have a small history length (we trade blur for noise) - float varianceBoost = max(1.0, 16.0 / (historyLength + 1.0)); + float varianceBoost = max(1.0, 16.0 / accumulatedFrames); float variance = max(0.0, momentsResolve.g - momentsResolve.r * momentsResolve.r); variance *= varianceBoost; variance = max(variance, 1e-5); - imageStore(momentsImage, pixel, vec4(momentsResolve, historyLength + 1.0, 0.0)); + imageStore(momentsImage, pixel, vec4(momentsResolve, accumulatedFrames, hitDistance)); imageStore(resolveImage, pixel, vec4(resolve, variance)); } \ No newline at end of file diff --git a/data/shader/shadow.hsh b/data/shader/shadow.hsh index ed48e3d58..1be96a883 100644 --- a/data/shader/shadow.hsh +++ b/data/shader/shadow.hsh @@ -282,7 +282,16 @@ float cascadeLookup(inout Shadow shadow, texture2DArray cascadeMaps, sampler sh visibility += offsetLookup(cascadeMaps, shadowSampler, shadowCoords.xy, 0.0, 0.0, float(cascadeIndex), resInv, shadowCoords.z, bias); #endif #ifdef SHADOW_FILTER_VOGEL + // Four taps spread over the disk decide whether the pixel is fully lit or fully shadowed + for (int i = 0; i < 16; i += 4) { + visibility += offsetLookup(cascadeMaps, shadowSampler, uv, float(cascadeIndex), shadow.edgeSoftness, texelSize, resInv, position, i, shadowCoords.z, bias); + } + if (visibility == 0.0 || visibility == 4.0) + return clamp(visibility * 0.25 + fadeout, 0.0, 1.0); + for (int i = 0; i < 16; i++) { + if (i % 4 == 0) + continue; visibility += offsetLookup(cascadeMaps, shadowSampler, uv, float(cascadeIndex), shadow.edgeSoftness, texelSize, resInv, position, i, shadowCoords.z, bias); } #endif @@ -406,7 +415,7 @@ float CalculateShadowWorldSpace(inout Shadow shadow, texture2DArray cascadeMaps, mat4(transpose(cascadeMatrix)), position, position, vec2(texelSize), 0.0, false); } -vec3 sampleOffsetDirections[20] = vec3[] ( +const vec3 sampleOffsetDirections[20] = vec3[] ( vec3( 1, 1, 1), vec3( 1, -1, 1), vec3(-1, -1, 1), vec3(-1, 1, 1), vec3( 1, 1, -1), vec3( 1, -1, -1), vec3(-1, -1, -1), vec3(-1, 1, -1), vec3( 1, 1, 0), vec3( 1, -1, 0), vec3(-1, -1, 0), vec3(-1, 1, 0), @@ -442,7 +451,7 @@ float CalculatePointShadow(inout Shadow shadow, textureCube cubeMap, sampler sha shadowFactor += clamp(texture(samplerCubeShadow(cubeMap, shadowSampler), vec4(shadowCoords.xyz + sampleOffsetDirections[i] * diskRadius, depth - 0.0001)), 0.0, 1.0); } - shadowFactor /= float(samples + 1); + shadowFactor /= float(samples); return shadowFactor; @@ -450,8 +459,6 @@ float CalculatePointShadow(inout Shadow shadow, textureCube cubeMap, sampler sha float CalculateSpotShadow(inout Shadow shadow, texture2DArray cascadeMaps, sampler shadowSampler, vec3 fragmentPosition, vec3 position, vec3 normal, float cosTheta) { - - float distance = -fragmentPosition.z; mat4 shadowMatrix; shadowMatrix[0] = shadow.cascades[0].cascadeSpace[0]; diff --git a/data/shader/shadowMapping.fsh b/data/shader/shadowMapping.fsh index 4140ce000..6982b80c0 100644 --- a/data/shader/shadowMapping.fsh +++ b/data/shader/shadowMapping.fsh @@ -1,25 +1,51 @@ #include +#include +#include +#include -#ifdef OPACITY_MAP +#if defined(OPACITY_MAP) || defined(MATERIAL_GRAPH_SURFACE) layout(location = 0) in vec2 texCoordVS; #endif -layout(push_constant) uniform constants { - mat4 lightSpaceMatrix; - uint vegetation; - uint invertUVs; - float windTextureLod; - float windBendScale; - float windWiggleScale; - uint textureID; -} PushConstants; +#ifdef TRANSLUCENT +layout(location = 13) flat in float opacityVS; +#endif + +#ifdef MATERIAL_GRAPH_SURFACE +layout(location = 1) in vec3 worldPositionVS; +layout(location = 2) in vec3 worldNormalVS; +layout(location = 3) in vec4 vertexColorsVS; +layout(location = 10) in vec3 objectPositionVS; +layout(location = 11) in vec3 instancePositionVS; +layout(location = 12) in vec3 objectNormalVS; +#endif void main() { - + + float opacity = 1.0; +#ifdef TRANSLUCENT + opacity = opacityVS; +#endif + #ifdef OPACITY_MAP - float opacity = SampleOpacity(texCoordVS, PushConstants.textureID, 0.0); - if(opacity < 0.2) + opacity *= SampleOpacity(texCoordVS, PushConstants.textureID, 0.0); +#endif + +#ifdef MATERIAL_GRAPH_SURFACE + MaterialSurfaceInput surfaceInput = CreateMaterialSurfaceInput(objectPositionVS, normalize(objectNormalVS), + worldPositionVS, normalize(worldNormalVS), instancePositionVS, mat3(1.0), texCoordVS, vec2(0.0), + vertexColorsVS, gl_FrontFacing ? 1.0 : -1.0, PushConstants.materialGraphOffset); + opacity *= EvaluateMaterialSurface(surfaceInput).opacity; +#endif + +#ifdef TRANSLUCENT + // A pattern changing every frame lets light through by the opacity, the filtering of the shadow maps and the temporal + // accumulation average it to a partial shadow. White noise leaves coarser blotches than interleaved gradient noise + if (opacity <= GetInterleavedGradientNoise(gl_FragCoord.xy, 16u)) + discard; +#else + if (opacity < opacityCutoff) discard; #endif - -} \ No newline at end of file + +} diff --git a/data/shader/shadowMapping.hsh b/data/shader/shadowMapping.hsh new file mode 100644 index 000000000..2fd97caea --- /dev/null +++ b/data/shader/shadowMapping.hsh @@ -0,0 +1,31 @@ +// Has to match ShadowRenderer::DrawData and ShadowRenderer::PushConstants + +// Only the wind and the opacity differ between the draws of a merged pipeline +struct ShadowDraw { + float windTextureLod; + float windBendScale; + float windWiggleScale; + float opacity; +}; + +layout(push_constant) uniform constants { + mat4 lightSpaceMatrix; + uint deformOffset; + uint jointCount; + uint instanceOffset; + // With DRAW_DATA the data of a draw is at firstDraw + gl_DrawID, the draws of a multi draw follow each other + uint firstDraw; + uint invertUVs; + uint textureID; + uint materialGraphOffset; + float uvAnimationX; + float uvAnimationY; + float uvTiling; + ShadowDraw draw; +} PushConstants; + +#ifdef DRAW_DATA +layout(std430, set = 3, binding = 10) readonly buffer ShadowDraws { + ShadowDraw shadowDraws[]; +}; +#endif diff --git a/data/shader/shadowMapping.vsh b/data/shader/shadowMapping.vsh index 87af352ce..820d7585c 100644 --- a/data/shader/shadowMapping.vsh +++ b/data/shader/shadowMapping.vsh @@ -1,51 +1,185 @@ #include #include +#include +#include +#include +#include layout(location=0) in vec3 vPosition; -#ifdef OPACITY_MAP +#ifdef MATERIAL_GRAPH +layout(location=1) in vec4 vNormal; +#ifdef TANGENTS +layout(location=3) in vec4 vTangent; +#endif +#ifdef VERTEX_COLORS +layout(location=4) in vec4 vVertexColors; +#endif +#endif +#if defined(OPACITY_MAP) || (defined(MATERIAL_GRAPH) && defined(TEX_COORDS)) layout(location=2) in vec2 vTexCoord; #endif +#ifdef SKINNED +layout(location=5) in uvec4 vJoints; +layout(location=6) in vec4 vWeights; +#endif +#if defined(MATERIAL_GRAPH) && defined(TEX_COORDS_1) +layout(location=7) in vec2 vTexCoord1; +#endif -#ifdef OPACITY_MAP +#if defined(OPACITY_MAP) || defined(MATERIAL_GRAPH_SURFACE) layout(location=0) out vec2 texCoordVS; #endif +#ifdef TRANSLUCENT +layout(location=13) flat out float opacityVS; +#endif + +#ifdef MATERIAL_GRAPH_SURFACE +layout(location=1) out vec3 worldPositionVS; +layout(location=2) out vec3 worldNormalVS; +layout(location=3) out vec4 vertexColorsVS; +layout(location=10) out vec3 objectPositionVS; +layout(location=11) out vec3 instancePositionVS; +layout(location=12) out vec3 objectNormalVS; +#endif + +#ifdef INSTANCE_BUFFER +#include +#else layout(std430, set = 1, binding = 1) readonly buffer Matrices { mat3x4 matrices[]; }; +#endif -layout(set = 3, binding = 0) uniform sampler2D windNoiseMap; +#ifdef SKINNED +layout(std430, set = 1, binding = 4) readonly buffer JointMatrices { + mat3x4 jointMatrices[]; +}; +#endif -layout(push_constant) uniform constants { - mat4 lightSpaceMatrix; - uint vegetation; - uint invertUVs; - float windTextureLod; - float windBendScale; - float windWiggleScale; - uint textureID; -} PushConstants; +#ifdef SOFT_BODY +// Positions with the packed normal in w, each instance has the offset of its vertices +layout(std430, set = 1, binding = 24) readonly buffer SoftBodyVertices { + vec4 softBodyVertices[]; +}; + +layout(std430, set = 1, binding = 26) readonly buffer SoftBodyVertexOffsets { + uint softBodyVertexOffsets[]; +}; +#endif + +layout(set = 3, binding = 0) uniform sampler2D windNoiseMap; void main() { +#ifdef INSTANCE_BUFFER + mat4 mMatrix = GetInstanceMatrix(instanceIndices[gl_InstanceIndex]); +#else mat4 mMatrix = mat4(transpose(matrices[gl_InstanceIndex])); - +#endif + +#ifdef DRAW_DATA + ShadowDraw draw = shadowDraws[PushConstants.firstDraw + uint(gl_DrawID)]; +#else + ShadowDraw draw = PushConstants.draw; +#endif +#ifdef TRANSLUCENT + opacityVS = draw.opacity; +#endif + #ifdef OPACITY_MAP - texCoordVS = PushConstants.invertUVs > 0 ? vec2(vTexCoord.x, 1.0 - vTexCoord.y) : vTexCoord; + texCoordVS = TransformTexCoord(vTexCoord, PushConstants.invertUVs > 0, + vec2(PushConstants.uvAnimationX, PushConstants.uvAnimationY), PushConstants.uvTiling); #endif mat4 matrix = mMatrix; vec3 position = vPosition; - if (PushConstants.vegetation > 0) { +#ifdef SKINNED + uint jointOffset = PushConstants.deformOffset + (gl_InstanceIndex - PushConstants.instanceOffset) * PushConstants.jointCount; + vec4 weights = vWeights / dot(vWeights, vec4(1.0)); + + mat3x4 skinMatrix = weights.x * jointMatrices[jointOffset + vJoints.x] + + weights.y * jointMatrices[jointOffset + vJoints.y] + + weights.z * jointMatrices[jointOffset + vJoints.z] + + weights.w * jointMatrices[jointOffset + vJoints.w]; + + position = vec4(vPosition, 1.0) * skinMatrix; +#endif + +#ifdef SOFT_BODY + vec4 softBodyVertex = softBodyVertices[softBodyVertexOffsets[PushConstants.deformOffset + gl_InstanceIndex - + PushConstants.instanceOffset] + gl_VertexIndex]; + position = softBodyVertex.xyz; +#endif + +#ifdef MATERIAL_GRAPH + vec3 graphNormal = vNormal.xyz; + vec2 graphTexCoord = vec2(0.0); + vec2 graphTexCoord1 = vec2(0.0); + vec3 graphTangent = vec3(1.0, 0.0, 0.0); + vec4 graphColor = vec4(1.0); +#ifdef SKINNED + graphNormal = vec4(graphNormal, 0.0) * skinMatrix; +#endif +#ifdef SOFT_BODY + graphNormal = unpackUnitVector(floatBitsToInt(softBodyVertex.w)).xyz; +#endif +#ifdef TEX_COORDS + graphTexCoord = TransformTexCoord(vTexCoord, PushConstants.invertUVs > 0, + vec2(PushConstants.uvAnimationX, PushConstants.uvAnimationY), PushConstants.uvTiling); +#endif +#ifdef TEX_COORDS_1 + graphTexCoord1 = PushConstants.invertUVs > 0 ? vec2(vTexCoord1.x, 1.0 - vTexCoord1.y) : vTexCoord1; +#endif +#ifdef TANGENTS + graphTangent = vTangent.xyz; +#endif +#ifdef VERTEX_COLORS + graphColor = vVertexColors; +#endif - // This is not well optimized and could use some work - vec3 windPosition = vec3(mMatrix * vec4(position, 1.0)); - vec2 windDir = normalize((inverse(mMatrix) * vec4(globalData.windDir.x, 0.0, globalData.windDir.y, 0.0)).xz); - position = WindAnimation(windNoiseMap, vPosition, windDir, PushConstants.windBendScale, - PushConstants.windWiggleScale, PushConstants.windTextureLod, globalData.time, windPosition); + MaterialVertexInput graphInput = CreateMaterialVertexInput(vPosition, position, graphNormal, graphTangent, graphTexCoord, graphTexCoord1, + graphColor, mMatrix, globalData.time, PushConstants.materialGraphOffset); +#ifdef MATERIAL_GRAPH_VERTEX_OPACITY +#ifdef TRANSLUCENT + opacityVS *= EvaluateMaterialOpacity(graphInput); + if (opacityVS <= 0.0) { +#else + if (EvaluateMaterialOpacity(graphInput) < opacityCutoff) { +#endif + gl_Position = vec4(2.0, 2.0, 2.0, 1.0); + return; } +#endif + + WriteMaterialVaryings(graphInput); + +#ifdef MATERIAL_GRAPH_SURFACE + texCoordVS = graphTexCoord; + objectPositionVS = vPosition; + objectNormalVS = graphNormal; + instancePositionVS = vec3(mMatrix[3]); + worldNormalVS = graphInput.worldNormal; + vertexColorsVS = graphColor; +#endif + +#ifdef MATERIAL_GRAPH_VERTEX_OFFSET + position += EvaluateMaterialVertexOffset(graphInput); +#endif + +#ifdef MATERIAL_GRAPH_SURFACE + worldPositionVS = vec3(mMatrix * vec4(position, 1.0)); +#endif +#endif + +#ifdef VEGETATION + vec3 windPosition = vec3(mMatrix * vec4(position, 1.0)); + vec2 windDir = GetWindDirection(mMatrix); + position = WindAnimation(windNoiseMap, position, windDir, draw.windBendScale, + draw.windWiggleScale, draw.windTextureLod, globalData.time, windPosition); +#endif gl_Position = PushConstants.lightSpaceMatrix * matrix * vec4(position, 1.0f); diff --git a/data/shader/skybox.csh b/data/shader/skybox.csh index 148ca41ce..a68bec0b2 100644 --- a/data/shader/skybox.csh +++ b/data/shader/skybox.csh @@ -18,8 +18,8 @@ vec2 resolution = vec2(imageSize(colorImage)); void main() { ivec2 pixel = ivec2(gl_GlobalInvocationID); - if (pixel.x > imageSize(colorImage).x || - pixel.y > imageSize(colorImage).y) + if (pixel.x >= imageSize(colorImage).x || + pixel.y >= imageSize(colorImage).y) return; float depth = texelFetch(depthTexture, pixel, 0).r; @@ -34,7 +34,7 @@ void main() { vec3 cubemapCoord = normalize(worldPos - globalData.cameraLocation.xyz); - vec3 color = textureLod(skyCubemap, cubemapCoord, 0).rgb; + vec3 color = textureLod(skyCubemap, cubemapCoord, 0).rgb * globalData.skyCubemapExposure; vec3 cameraLocationDiff = globalData.cameraLocation.xyz - pushConstants.cameraLocationLast.xyz; diff --git a/data/shader/ssgi/ssgi.csh b/data/shader/ssgi/ssgi.csh index 923166543..82973bdf0 100644 --- a/data/shader/ssgi/ssgi.csh +++ b/data/shader/ssgi/ssgi.csh @@ -34,6 +34,7 @@ layout(set = 3, binding = 6) uniform sampler2D directLightTexture; layout(set = 3, binding = 7) uniform sampler2D scramblingRankingTexture; layout(set = 3, binding = 8) uniform sampler2D sobolSequenceTexture; +layout(set = 3, binding = 14) uniform sampler2D hiZTexture; layout(set = 1, binding = 12) uniform samplerCube diffuseProbe; @@ -55,6 +56,7 @@ layout(std140, set = 3, binding = 9) uniform UniformBuffer { uint rayCount; uint sampleCount; int downsampled2x; + int hiZLevelCount; } uniforms; float Luma(vec3 color) { @@ -80,8 +82,10 @@ void main() { float depth = texelFetch(depthTexture, pixel, 0).r; - vec2 recontructTexCoord = (2.0 * vec2(pixel) + pixelOffset + vec2(0.5)) / (2.0 * vec2(resolution)); - vec3 viewPos = ConvertDepthToViewSpace(depth, texCoord); + // The downsampled data belongs to one pixel of the 2x2 block + vec2 recontructTexCoord = uniforms.downsampled2x > 0 ? + (2.0 * vec2(pixel) + pixelOffset + vec2(0.5)) / (2.0 * vec2(resolution)) : texCoord; + vec3 viewPos = ConvertDepthToViewSpace(depth, recontructTexCoord); vec3 worldPos = vec3(globalData.ivMatrix * vec4(viewPos, 1.0)); vec3 viewVec = vec3(globalData.ivMatrix * vec4(viewPos, 0.0)); vec3 viewNorm = normalize(DecodeNormal(textureLod(normalTexture, texCoord, 0).rg)); @@ -110,7 +114,7 @@ void main() { if (depth < 1.0) { #ifdef AUTO_EXPOSURE - float radianceLimit = 9.6 * uniforms.radianceLimit * texelFetch(exposureTexture, ivec2(0), 0).r; + float radianceLimit = 9.6 * uniforms.radianceLimit * texelFetch(exposureTexture, ivec2(0), 0).r * globalData.preExposure; #else float radianceLimit = uniforms.radianceLimit; #endif @@ -148,17 +152,19 @@ void main() { vec2 hitPixel; vec3 hitPoint; - float jitter = GetInterleavedGradientNoise(vec2(pixel)) / float(uniforms.rayCount) + j / float(uniforms.rayCount); - if (traceScreenSpaceAdvanced(viewRayOrigin, viewDir, depthTexture, 4.0, 16.0, jitter, 64.0, 1000.0, false, false, hitPixel, hitPoint)) { + if (traceScreenSpaceHiZ(viewRayOrigin, viewDir, hiZTexture, uniforms.hiZLevelCount, vec2(textureSize(depthTexture, 0)), + 32, rayLength, false, hitPixel, hitPoint)) { vec2 hitTexCoord = vec2(hitPixel + 0.5) / vec2(textureSize(depthTexture, 0)); vec3 stepViewNorm = normalize(DecodeNormal(texelFetch(normalTexture, ivec2(hitPixel), 0).rg)); float depth = texelFetch(depthTexture, ivec2(hitPixel), 0).r; hitPoint = ConvertDepthToViewSpace(depth, hitTexCoord); float NdotV = saturate(dot(-viewDir, stepViewNorm)); - NdotL = saturate(dot(viewNorm, hitPoint)); if (NdotV > 0.0) { - irradiance += textureLod(directLightTexture, hitTexCoord, 0).rgb; + vec3 radiance = textureLod(directLightTexture, hitTexCoord, 0).rgb; + float radianceMax = max(max(max(radiance.r, + max(radiance.g, radiance.b)), radianceLimit), 1e-12); + irradiance += radiance * (radianceLimit / radianceMax); } else { aoHits += 1.0; @@ -167,10 +173,6 @@ void main() { } } - float irradianceMax = max(max(max(irradiance.r, - max(irradiance.g, irradiance.b)), radianceLimit), 1e-12); - irradiance *= (radianceLimit / irradianceMax); - // Supplement misses with the probe irradiance irradiance += float(uniforms.rayCount - hits) * probeIrradiance; irradiance /= (float(uniforms.rayCount)); diff --git a/data/shader/ssgi/temporal.csh b/data/shader/ssgi/temporal.csh index ad56de661..257da1d02 100644 --- a/data/shader/ssgi/temporal.csh +++ b/data/shader/ssgi/temporal.csh @@ -5,6 +5,7 @@ #include <../common/flatten.hsh> #include <../common/random.hsh> #include <../common/normalencode.hsh> +#include <../globals.hsh> layout (local_size_x = 8, local_size_y = 8) in; @@ -248,21 +249,13 @@ bool SampleHistory(ivec2 pixel, vec2 historyPixel, out vec4 history, out float h } -float EdgeFadeOut(vec2 screenPos, float fadeDist) { - - screenPos = abs(screenPos * 2.0 - 1.0); - vec2 fadeOut = (screenPos - 1.0 + fadeDist) / fadeDist; - return saturate(1.0 - max(fadeOut.x, fadeOut.y)); - -} - void main() { LoadGroupSharedData(); ivec2 pixel = ivec2(gl_GlobalInvocationID); - if (pixel.x > imageSize(resolveImage).x || - pixel.y > imageSize(resolveImage).y) + if (pixel.x >= imageSize(resolveImage).x || + pixel.y >= imageSize(resolveImage).y) return; vec4 mean, std; @@ -288,6 +281,8 @@ void main() { vec4 history; float historyLength; valid = SampleHistory(pixel, historyPixel, history, historyLength); + // The history was stored with the pre-exposure of the last frame + history.rgb *= globalData.preExposure / globalData.lastPreExposure; vec4 historyValue = history; vec4 currentValue = texelFetch(currentTexture, pixel, 0); @@ -299,14 +294,10 @@ void main() { // At the edge we have invalid information we want to get rid of historyLength = mix(min(historyLength, 8.0), historyLength, EdgeFadeOut(uv, 0.05)); - float factor = 31.0 / 32.0; - factor = (uv.x < 0.0 || uv.y < 0.0 || uv.x > 1.0 - || uv.y > 1.0) ? 0.0 : factor; - - factor = pushConstants.resetHistory > 0 ? 0.0 : factor; - factor = max(0.75, factor - 20.0 * max(abs(velocity.x), abs(velocity.y))); + float factor = max(0.75, 31.0 / 32.0 - 20.0 * max(abs(velocity.x), abs(velocity.y))); - if (factor == 0.0 || !valid) { + bool offscreen = uv.x < 0.0 || uv.y < 0.0 || uv.x > 1.0 || uv.y > 1.0; + if (offscreen || pushConstants.resetHistory > 0 || !valid) { historyLength = 0.0; } diff --git a/data/shader/taa.csh b/data/shader/taa.csh index 202985be9..e572f285d 100644 --- a/data/shader/taa.csh +++ b/data/shader/taa.csh @@ -2,6 +2,7 @@ #include #include #include +#include layout (local_size_x = 8, local_size_y = 8) in; @@ -13,9 +14,8 @@ layout(set = 3, binding = 3) uniform sampler2D velocityTexture; layout(set = 3, binding = 4) uniform sampler2D depthTexture; layout(set = 3, binding = 5) uniform sampler2D lastVelocityTexture; -#ifndef PATHTRACE layout(set = 3, binding = 6) uniform usampler2D stencilTexture; -#endif +layout(set = 3, binding = 7) uniform usampler2D lastStencilTexture; layout(push_constant) uniform constants { vec2 resolution; @@ -33,10 +33,6 @@ const float maxVelocityBlend = 0.2; #define TAA_CLIP //#define TAA_DENOISE -#ifdef PATHTRACE -#define TAA_CLIP -#endif - const ivec2 offsets[9] = ivec2[9]( ivec2(-1, -1), ivec2(0, -1), @@ -243,6 +239,8 @@ vec4 SampleHistory(vec2 texCoord) { #else historyColor = texture(historyTexture, texCoord); #endif + // The history was stored with the pre-exposure of the last frame + historyColor.rgb *= globalData.preExposure / globalData.lastPreExposure; #ifdef TAA_TONE historyColor.rgb = Tonemap(historyColor.rgb); @@ -313,8 +311,8 @@ void main() { LoadGroupSharedData(); ivec2 pixel = ivec2(gl_GlobalInvocationID); - if (pixel.x > imageSize(resolveImage).x || - pixel.y > imageSize(resolveImage).y) + if (pixel.x >= imageSize(resolveImage).x || + pixel.y >= imageSize(resolveImage).y) return; LoadLocalData(); @@ -357,6 +355,19 @@ void main() { vec2 uv = (vec2(pixel) + vec2(0.5)) * PushConstants.invResolution + velocity; + StencilFeatures features = DecodeStencilFeatures(texelFetch(stencilTexture, pixel, 0).r); + bool rejectHistory = features.noTemporalAccumulation; + if (PushConstants.resetHistory == 0) { + ivec2 historyPixel = clamp(ivec2(uv * PushConstants.resolution), ivec2(0), ivec2(PushConstants.resolution) - 1); + StencilFeatures historyFeatures = DecodeStencilFeatures(texelFetch(lastStencilTexture, historyPixel, 0).r); + StencilFeatures previousFeatures = DecodeStencilFeatures(texelFetch(lastStencilTexture, pixel, 0).r); + rejectHistory = rejectHistory || historyFeatures.noTemporalAccumulation || previousFeatures.noTemporalAccumulation; + } + if (rejectHistory) { + imageStore(resolveImage, pixel, vec4(texelFetch(currentTexture, pixel, 0).rgb, 0.0)); + return; + } + // Maybe we might want to filter the current input pixel vec4 history = SampleHistory(uv); @@ -370,12 +381,10 @@ void main() { float range = 1.4; float localAntiFlicker = mix(0.6, 5.0, 1.0 - velocityBlend); -#ifndef PATHTRACE #ifdef TAA_DENOISE range += localAntiFlicker; #else range += mix(0.0, localAntiFlicker, historyContrast); -#endif #endif localNeighbourhoodMin = average - range * (average - localNeighbourhoodMin); @@ -391,11 +400,7 @@ void main() { historyColor = clamp(historyColor, localNeighbourhoodMin, localNeighbourhoodMax); #endif -#ifndef PATHTRACE float blendFactor = mix(minVelocityBlend, maxVelocityBlend, velocityBlend); -#else - float blendFactor = mix(minVelocityBlend, maxVelocityBlend, velocityBlend); -#endif #ifdef TAA_YCOCG historyColor = YCoCgToRGB(historyColor); @@ -407,10 +412,7 @@ void main() { currentColor.rgb = InverseTonemap(currentColor.rgb); #endif -#ifndef PATHTRACE - StencilFeatures features = DecodeStencilFeatures(texelFetch(stencilTexture, pixel, 0).r); blendFactor = features.responsivePixel ? 0.5 : blendFactor; -#endif // Check if we sampled outside the viewport area blendFactor = (uv.x < 0.0 || uv.y < 0.0 || uv.x > 1.0 diff --git a/data/shader/terrain/shadowmapping.fsh b/data/shader/terrain/shadowmapping.fsh deleted file mode 100644 index 48f3365be..000000000 --- a/data/shader/terrain/shadowmapping.fsh +++ /dev/null @@ -1,5 +0,0 @@ -void main() { - - - -} \ No newline at end of file diff --git a/data/shader/terrain/shadowmapping.vsh b/data/shader/terrain/shadowmapping.vsh index ff316028a..14f33db4b 100644 --- a/data/shader/terrain/shadowmapping.vsh +++ b/data/shader/terrain/shadowmapping.vsh @@ -2,6 +2,8 @@ layout (location = 0) in vec3 vPosition; layout (set = 3, binding = 0) uniform usampler2D heightField; +out float gl_ClipDistance[1]; + layout(push_constant) uniform constants { mat4 lightSpaceMatrix; vec4 translation; @@ -56,14 +58,13 @@ void main() { vec2 texCoords = localPosition; texCoords /= PushConstants.nodeSideLength; - float heightDiscretized = texture(heightField, texCoords).r; - // The middle of the texel should match the vertex position - float height = float(heightDiscretized) / 65535.0 * PushConstants.heightScale; + uint heightDiscretized = texture(heightField, texCoords).r; + // The middle of the texel should match the vertex position, 65535 marks holes + float height = float(heightDiscretized) / 65534.0 * PushConstants.heightScale; gl_Position = PushConstants.lightSpaceMatrix * vec4(vec3(position.x, height, position.y) + PushConstants.translation.xyz, 1.0); - if (heightDiscretized == 65535u) { - gl_Position = vec4(0.0, 0.0, 0.0, intBitsToFloat(int(0xFFC00000u))); - } + // The triangles around holes are clipped, see terrain.vsh + gl_ClipDistance[0] = heightDiscretized == 65535u ? -1e20 : 1.0; } \ No newline at end of file diff --git a/data/shader/terrain/terrain.fsh b/data/shader/terrain/terrain.fsh index 1697f13bd..9ffc0c976 100644 --- a/data/shader/terrain/terrain.fsh +++ b/data/shader/terrain/terrain.fsh @@ -16,10 +16,6 @@ layout (location = 6) out vec2 velocityFS; layout (set = 3, binding = 1) uniform sampler2D normalMap; layout (set = 3, binding = 2) uniform usampler2D splatMap; -layout (set = 3, binding = 3) uniform sampler2DArray baseColorMaps; -layout (set = 3, binding = 4) uniform sampler2DArray roughnessMaps; -layout (set = 3, binding = 5) uniform sampler2DArray aoMaps; -layout (set = 3, binding = 6) uniform sampler2DArray normalMaps; layout (set = 3, binding = 10) uniform sampler2D noiseMap; @@ -64,19 +60,18 @@ vec3 hueShift(vec3 color, float hue) { return vec3(color * cosAngle + cross(k, color) * sin(hue) + k * dot(k, color) * (1.0 - cosAngle)); } -vec4 sampleTexture(sampler2DArray texArray, vec2 coords, vec2 origCoords, uint index) { +vec4 SampleTexture(uint textureIdx, vec2 coords, vec2 ddx, vec2 ddy) { - float lod = textureQueryLod(texArray, origCoords).x; - return textureLod(texArray, vec3(coords, nonuniformEXT(float(index))), lod + globalData.mipLodBias); + return textureGrad(sampler2D(bindlessTextures[nonuniformEXT(textureIdx)], bindlessSampler), coords, ddx, ddy); } -vec3 SampleBaseColor(vec2 off, uvec4 indices, vec4 tiling, vec2 coords, vec2 origCoords) { +vec3 SampleBaseColor(vec2 off, uvec4 indices, vec4 tiling, vec2 coords, vec2 ddx, vec2 ddy) { - vec3 q00 = nonuniformEXT(sampleTexture(baseColorMaps, coords * tiling.x, origCoords * tiling.x, indices.x).rgb); - vec3 q10 = nonuniformEXT(indices.y != indices.x ? sampleTexture(baseColorMaps, coords * tiling.y, origCoords * tiling.y, indices.y).rgb : q00); - vec3 q01 = nonuniformEXT(indices.z != indices.x ? sampleTexture(baseColorMaps, coords * tiling.z, origCoords * tiling.z, indices.z).rgb : q00); - vec3 q11 = nonuniformEXT(indices.w != indices.x ? sampleTexture(baseColorMaps, coords * tiling.w, origCoords * tiling.w, indices.w).rgb : q00); + vec3 q00 = SampleTexture(Materials.materials[nonuniformEXT(indices.x)].baseColorTextureIdx, coords * tiling.x, ddx * tiling.x, ddy * tiling.x).rgb; + vec3 q10 = indices.y != indices.x ? SampleTexture(Materials.materials[nonuniformEXT(indices.y)].baseColorTextureIdx, coords * tiling.y, ddx * tiling.y, ddy * tiling.y).rgb : q00; + vec3 q01 = indices.z != indices.x ? SampleTexture(Materials.materials[nonuniformEXT(indices.z)].baseColorTextureIdx, coords * tiling.z, ddx * tiling.z, ddy * tiling.z).rgb : q00; + vec3 q11 = indices.w != indices.x ? SampleTexture(Materials.materials[nonuniformEXT(indices.w)].baseColorTextureIdx, coords * tiling.w, ddx * tiling.w, ddy * tiling.w).rgb : q00; // Interpolate samples horizontally vec3 h0 = mix(q00, q10, off.x); @@ -87,12 +82,12 @@ vec3 SampleBaseColor(vec2 off, uvec4 indices, vec4 tiling, vec2 coords, vec2 ori } -float SampleRoughness(vec2 off, uvec4 indices, vec4 tiling, vec2 coords, vec2 origCoords) { +float SampleRoughness(vec2 off, uvec4 indices, vec4 tiling, vec2 coords, vec2 ddx, vec2 ddy) { - float q00 = nonuniformEXT(sampleTexture(roughnessMaps, coords * tiling.x, origCoords * tiling.x, indices.x).r); - float q10 = nonuniformEXT(indices.y != indices.x ? sampleTexture(roughnessMaps, coords * tiling.y, origCoords * tiling.y, indices.y).r : q00); - float q01 = nonuniformEXT(indices.z != indices.x ? sampleTexture(roughnessMaps, coords * tiling.z, origCoords * tiling.z, indices.z).r : q00); - float q11 = nonuniformEXT(indices.w != indices.x ? sampleTexture(roughnessMaps, coords * tiling.w, origCoords * tiling.w, indices.w).r : q00); + float q00 = SampleTexture(Materials.materials[nonuniformEXT(indices.x)].roughnessTextureIdx, coords * tiling.x, ddx * tiling.x, ddy * tiling.x).r; + float q10 = indices.y != indices.x ? SampleTexture(Materials.materials[nonuniformEXT(indices.y)].roughnessTextureIdx, coords * tiling.y, ddx * tiling.y, ddy * tiling.y).r : q00; + float q01 = indices.z != indices.x ? SampleTexture(Materials.materials[nonuniformEXT(indices.z)].roughnessTextureIdx, coords * tiling.z, ddx * tiling.z, ddy * tiling.z).r : q00; + float q11 = indices.w != indices.x ? SampleTexture(Materials.materials[nonuniformEXT(indices.w)].roughnessTextureIdx, coords * tiling.w, ddx * tiling.w, ddy * tiling.w).r : q00; // Interpolate samples horizontally float h0 = mix(q00, q10, off.x); @@ -103,12 +98,12 @@ float SampleRoughness(vec2 off, uvec4 indices, vec4 tiling, vec2 coords, vec2 or } -float SampleAo(vec2 off, uvec4 indices, vec4 tiling, vec2 coords, vec2 origCoords) { +float SampleAo(vec2 off, uvec4 indices, vec4 tiling, vec2 coords, vec2 ddx, vec2 ddy) { - float q00 = nonuniformEXT(sampleTexture(aoMaps, coords * tiling.x, origCoords * tiling.x, indices.x).r); - float q10 = nonuniformEXT(indices.y != indices.x ? sampleTexture(aoMaps, coords * tiling.y, origCoords * tiling.y, indices.y).r : q00); - float q01 = nonuniformEXT(indices.z != indices.x ? sampleTexture(aoMaps, coords * tiling.z, origCoords * tiling.z, indices.z).r : q00); - float q11 = nonuniformEXT(indices.w != indices.x ? sampleTexture(aoMaps, coords * tiling.w, origCoords * tiling.w, indices.w).r : q00); + float q00 = SampleTexture(Materials.materials[nonuniformEXT(indices.x)].aoTextureIdx, coords * tiling.x, ddx * tiling.x, ddy * tiling.x).r; + float q10 = indices.y != indices.x ? SampleTexture(Materials.materials[nonuniformEXT(indices.y)].aoTextureIdx, coords * tiling.y, ddx * tiling.y, ddy * tiling.y).r : q00; + float q01 = indices.z != indices.x ? SampleTexture(Materials.materials[nonuniformEXT(indices.z)].aoTextureIdx, coords * tiling.z, ddx * tiling.z, ddy * tiling.z).r : q00; + float q11 = indices.w != indices.x ? SampleTexture(Materials.materials[nonuniformEXT(indices.w)].aoTextureIdx, coords * tiling.w, ddx * tiling.w, ddy * tiling.w).r : q00; // Interpolate samples horizontally float h0 = mix(q00, q10, off.x); @@ -119,12 +114,12 @@ float SampleAo(vec2 off, uvec4 indices, vec4 tiling, vec2 coords, vec2 origCoord } -vec3 SampleNormal(vec2 off, uvec4 indices, vec4 tiling, vec2 coords, vec2 origCoords) { +vec3 SampleNormal(vec2 off, uvec4 indices, vec4 tiling, vec2 coords, vec2 ddx, vec2 ddy) { - vec3 q00 = nonuniformEXT(sampleTexture(normalMaps, coords * tiling.x, origCoords * tiling.x, indices.x).rgb); - vec3 q10 = nonuniformEXT(indices.y != indices.x ? sampleTexture(normalMaps, coords * tiling.y, origCoords * tiling.y, indices.y).rgb : q00); - vec3 q01 = nonuniformEXT(indices.z != indices.x ? sampleTexture(normalMaps, coords * tiling.z, origCoords * tiling.z, indices.z).rgb : q00); - vec3 q11 = nonuniformEXT(indices.w != indices.x ? sampleTexture(normalMaps, coords * tiling.w, origCoords * tiling.w, indices.w).rgb : q00); + vec3 q00 = SampleTexture(Materials.materials[nonuniformEXT(indices.x)].normalTextureIdx, coords * tiling.x, ddx * tiling.x, ddy * tiling.x).rgb; + vec3 q10 = indices.y != indices.x ? SampleTexture(Materials.materials[nonuniformEXT(indices.y)].normalTextureIdx, coords * tiling.y, ddx * tiling.y, ddy * tiling.y).rgb : q00; + vec3 q01 = indices.z != indices.x ? SampleTexture(Materials.materials[nonuniformEXT(indices.z)].normalTextureIdx, coords * tiling.z, ddx * tiling.z, ddy * tiling.z).rgb : q00; + vec3 q11 = indices.w != indices.x ? SampleTexture(Materials.materials[nonuniformEXT(indices.w)].normalTextureIdx, coords * tiling.w, ddx * tiling.w, ddy * tiling.w).rgb : q00; // Interpolate samples horizontally vec3 h0 = mix(q00, q10, off.x); @@ -192,7 +187,11 @@ void main() { vec2 flooredCoords = floor(position + vec2(noiseX, noiseY)); float rand = random(flooredCoords); vec2 rotTexCoords = rotateUV(position, rand); - //rotTexCoords = materialTexCoords; + + // Gradients of the rotated coordinates without the jumps between the randomly rotated cells + float gradientScale = exp2(globalData.mipLodBias); + vec2 ddx = rotateUV(dFdx(materialTexCoords) * gradientScale + vec2(0.5), rand) - vec2(0.5); + vec2 ddy = rotateUV(dFdy(materialTexCoords) * gradientScale + vec2(0.5), rand) - vec2(0.5); vec4 tiling = vec4( Materials.materials[nonuniformEXT(indices.x)].tiling, @@ -209,7 +208,7 @@ void main() { off ); - baseColorFS *= SampleBaseColor(off, indices, tiling, rotTexCoords, materialTexCoords); + baseColorFS *= SampleBaseColor(off, indices, tiling, rotTexCoords, ddx, ddy); baseColorFS = hueShift(baseColorFS, noiseZ - 0.5); baseColorFS = baseColorFS * (noiseW * 0.5 + 0.5); @@ -256,7 +255,7 @@ void main() { Materials.materials[nonuniformEXT(indices.w)].normalScale, off ); - vec3 normal = SampleNormal(off, indices, tiling, rotTexCoords, materialTexCoords); + vec3 normal = SampleNormal(off, indices, tiling, rotTexCoords, ddx, ddy); vec3 tang = vec3(1.0, 0.0, 0.0); tang.y = -((norm.x*tang.x) / norm.y) - ((norm.z*tang.z) / norm.y); tang = normalize(tang); @@ -264,8 +263,8 @@ void main() { mat3 tbn = mat3(tang, bitang, norm); normal = normalize(tbn * (2.0 * normal - 1.0)); normal = mix(norm, normal, normalScale); - //ao *= SampleAo(off, indices, tiling, rotTexCoords, materialTexCoords); - //roughness *= SampleRoughness(off, indices, tiling, rotTexCoords, materialTexCoords); + //ao *= SampleAo(off, indices, tiling, rotTexCoords, ddx, ddy); + //roughness *= SampleRoughness(off, indices, tiling, rotTexCoords, ddx, ddy); #else vec3 normal = norm; #endif diff --git a/data/shader/terrain/terrain.tcsh b/data/shader/terrain/terrain.tcsh index 6dedb4ad7..3beda76b1 100644 --- a/data/shader/terrain/terrain.tcsh +++ b/data/shader/terrain/terrain.tcsh @@ -85,7 +85,7 @@ void main() { maxVec += dir; minVec -= dir; - if (IsTileVisible(minVec, maxVec)) { + if (!hole && IsTileVisible(minVec, maxVec)) { #ifndef DISTANCE vec3 midAB = vec3(gl_in[0].gl_Position + gl_in[1].gl_Position) / 2.0; diff --git a/data/shader/terrain/terrain.tesh b/data/shader/terrain/terrain.tesh index 584487215..b8df018de 100644 --- a/data/shader/terrain/terrain.tesh +++ b/data/shader/terrain/terrain.tesh @@ -10,7 +10,6 @@ layout(quads, equal_spacing, cw) in; layout (set = 3, binding = 1) uniform sampler2D normalMap; layout (set = 3, binding = 2) uniform usampler2D splatMap; -layout (set = 3, binding = 7) uniform sampler2DArray displacementMaps; layout (set = 3, binding = 10) uniform sampler2D noiseMap; layout (set = 3, binding = 8, std140) uniform UBO { @@ -49,6 +48,12 @@ layout(location=1) out vec2 texCoords; layout(location=2) out vec3 ndcCurrent; layout(location=3) out vec3 ndcLast; +float SampleDisplacementTexture(uint textureIdx, vec2 coords) { + + return textureLod(sampler2D(bindlessTextures[nonuniformEXT(textureIdx)], bindlessSampler), coords, 0.0).r; + +} + float SampleDisplacement(vec2 off, vec2 coords, uvec4 indices) { vec2 position = materialTexCoords + PushConstants.nodeLocation; @@ -63,12 +68,12 @@ float SampleDisplacement(vec2 off, vec2 coords, uvec4 indices) { if (indices.x == indices.y && indices.x == indices.z && indices.x == indices.w) - return texture(displacementMaps, vec3(rotTexCoords, float(indices.x))).r; + return SampleDisplacementTexture(Materials.materials[indices.x].displacementTextureIdx, rotTexCoords); - float q00 = texture(displacementMaps, vec3(rotTexCoords, float(indices.x))).r; - float q10 = texture(displacementMaps, vec3(rotTexCoords, float(indices.y))).r; - float q01 = texture(displacementMaps, vec3(rotTexCoords, float(indices.z))).r; - float q11 = texture(displacementMaps, vec3(rotTexCoords, float(indices.w))).r; + float q00 = SampleDisplacementTexture(Materials.materials[indices.x].displacementTextureIdx, rotTexCoords); + float q10 = SampleDisplacementTexture(Materials.materials[indices.y].displacementTextureIdx, rotTexCoords); + float q01 = SampleDisplacementTexture(Materials.materials[indices.z].displacementTextureIdx, rotTexCoords); + float q11 = SampleDisplacementTexture(Materials.materials[indices.w].displacementTextureIdx, rotTexCoords); // Interpolate samples horizontally float h0 = mix(q00, q10, off.x); @@ -95,9 +100,6 @@ void main(){ float u = gl_TessCoord.x; float v = gl_TessCoord.y; - bool hole = gl_in[3].gl_Position.w < 0.0 || gl_in[2].gl_Position.w < 0.0 || - gl_in[1].gl_Position.w < 0.0 || gl_in[0].gl_Position.w < 0.0; - // world position vec4 position = ((1.0 - u) * (1.0 - v) * gl_in[3].gl_Position + @@ -138,7 +140,8 @@ void main(){ Materials.materials[indices.w].displacementScale, off ); - float displacement = SampleDisplacement(off, materialTexCoords, indices) + // Around the surface instead of above it, so objects placed on the physical ground don't look sunk in + float displacement = (SampleDisplacement(off, materialTexCoords, indices) - 0.5) * displacementScale * weight; position.xyz += norm * displacement; @@ -151,10 +154,5 @@ void main(){ vec4 last = globalData.pvMatrixLast * position; ndcLast = vec3(last.xy, last.w); - - if (hole) { - gl_Position = vec4(0.0, 0.0, 0.0, -1.0); - ndcLast = ndcCurrent; - } } \ No newline at end of file diff --git a/data/shader/terrain/terrain.vsh b/data/shader/terrain/terrain.vsh index 42b3be624..d484e3020 100644 --- a/data/shader/terrain/terrain.vsh +++ b/data/shader/terrain/terrain.vsh @@ -10,6 +10,7 @@ layout(set = 3, binding = 0) uniform usampler2D heightField; layout(set = 3, binding = 2) uniform usampler2D splatMap; #ifdef DISTANCE +out float gl_ClipDistance[1]; layout(location=0) out vec2 materialTexCoords; layout(location=1) out vec2 texCoords; layout(location=2) out vec3 ndcCurrent; @@ -108,12 +109,14 @@ void main() { ndcLast = vec3(last.xy, last.w); #endif - // Produce NaNs here - if (heightDiscretized == 65535u) { - gl_Position = vec4(0.0, 0.0, 0.0, intBitsToFloat(int(0xFFC00000u))); -#ifdef DISTANCE - ndcLast = ndcCurrent; + // Holes leave out the patches around the vertex, the control shader culls them. Without tessellation the + // triangles around it are clipped, the large distance leaves at most sub-pixel slivers of them + bool hole = heightDiscretized == 65535u; +#ifndef DISTANCE + if (hole) + gl_Position.w = -1.0; +#else + gl_ClipDistance[0] = hole ? -1e20 : 1.0; #endif - } } \ No newline at end of file diff --git a/data/shader/terrain/terrainMaterial.hsh b/data/shader/terrain/terrainMaterial.hsh index a76204fc9..28a079510 100644 --- a/data/shader/terrain/terrainMaterial.hsh +++ b/data/shader/terrain/terrainMaterial.hsh @@ -17,7 +17,11 @@ struct TerrainMaterial { float tiling; - int padding; + uint baseColorTextureIdx; + uint roughnessTextureIdx; + uint aoTextureIdx; + uint normalTextureIdx; + uint displacementTextureIdx; }; diff --git a/data/shader/text.fsh b/data/shader/text.fsh index 8629d60b0..b66f4e4d5 100644 --- a/data/shader/text.fsh +++ b/data/shader/text.fsh @@ -1,9 +1,11 @@ #include +#include layout (location=0) out vec4 colorFS; #ifdef TEXT_3D layout (location=1) out vec2 velocityFS; +layout (location=2) out uint stencilFS; #endif layout(location=0) in vec3 texCoordVS; @@ -72,11 +74,15 @@ void main() { if (colorFS.a < 0.5) discard; + StencilFeatures features = CreateStencilFeatures(); + features.noTemporalAccumulation = true; + stencilFS = EncodeStencilFeatures(features); + vec2 ndcL = ndcLastVS.xy / ndcLastVS.z; vec2 ndcC = ndcCurrentVS.xy / ndcCurrentVS.z; + // The current position is unjittered already (see text.vsh), the last one used the jittered matrix ndcL -= globalData.jitterLast; - ndcC -= globalData.jitterCurrent; velocityFS = (ndcL - ndcC) * 0.5; #endif diff --git a/data/shader/text.vsh b/data/shader/text.vsh index ec84c473f..06059b40d 100644 --- a/data/shader/text.vsh +++ b/data/shader/text.vsh @@ -83,7 +83,8 @@ void main() { vec3 worldPosition = right * screenPositionVS.x + down * screenPositionVS.y; worldPosition = worldPosition + pushConstants.position.xyz - right * halfSize.x - down * halfSize.y; - gl_Position = globalData.pMatrix * globalData.vMatrix * vec4(worldPosition, 1.0); + // Text isn't accumulated temporally (see text.fsh), the jitter would only make it shake + gl_Position = globalData.pMatrixUnjitterd * globalData.vMatrix * vec4(worldPosition, 1.0); ndcCurrentVS = vec3(gl_Position.xy, gl_Position.w); // For moving objects we need the last frames matrix diff --git a/data/shader/translucent/translucent.hsh b/data/shader/translucent/translucent.hsh new file mode 100644 index 000000000..ab59cb1a5 --- /dev/null +++ b/data/shader/translucent/translucent.hsh @@ -0,0 +1,369 @@ +// Forward shading of translucent surfaces, included by the geometry fragment shader with TRANSLUCENT. One blend mode +// macro is set: BLEND_ALPHA (premultiplied), BLEND_ADDITIVE or BLEND_MULTIPLY + +#define SHADOW_FILTER_VOGEL + +#include <../deferred/deferred.hsh> +#include <../structures.hsh> +#include <../shadow.hsh> +#include <../common/light.hsh> +#include <../brdf/brdfEval.hsh> +#include <../clouds/shadow.hsh> +#include <../volumetric/froxelSlices.hsh> + +#ifdef DDGI +#include <../ddgi/ddgi.hsh> +#endif + +layout(set = 3, binding = 11) uniform sampler shadowSampler; +#ifdef CLOUD_SHADOWS +layout(set = 3, binding = 12) uniform sampler2D cloudMap; +#endif + +#include <../deferred/directLight.hsh> + +// Light tiles which reach from the near plane to the opaque surfaces, with the buckets of deferred/lightCulling.hsh +const int lightBucketCount = 128; + +layout(std430, set = 3, binding = 13) readonly buffer TranslucentLightBuckets { + int lightBuckets[]; +}; + +layout(set = 3, binding = 14) uniform sampler2D refractionTexture; +layout(set = 3, binding = 15) uniform sampler2D refractionDepthTexture; +// The closest back faces of refracting surfaces with their normals pointing out of them +layout(set = 3, binding = 20) uniform sampler2D refractionBackDepthTexture; +layout(set = 3, binding = 21) uniform sampler2D refractionBackNormalTexture; +#ifdef REFLECTION +// Traced from the closest alpha blended surface, see the front layer of the translucent renderer +layout(set = 3, binding = 16) uniform sampler2D reflectionTexture; +layout(set = 3, binding = 17) uniform sampler2D reflectionDepthTexture; +#endif +#ifdef FOG +layout(set = 3, binding = 18) uniform sampler3D integratedFroxelTexture; +#endif + +layout(std140, set = 3, binding = 19) uniform TranslucentUniformBuffer { + vec2 resolution; + // Maps the unjittered screen coordinates to the froxel columns + vec2 froxelGridScale; + int lightBucketCount; + int lightTileCountX; + int specularProbeMipLevels; + int refractionMipLevels; + float froxelNear; + float froxelFar; + float froxelExtendedFar; + int froxelSliceCount; + float froxelDistributionExponent; +} translucentUniforms; + +vec3 GetTranslucentDirectLight(Surface surface, vec3 geometryNormal, ivec2 pixel, vec2 texCoord) { + + ivec2 tile = pixel / ivec2(16); + int bucketOffset = (tile.x + tile.y * translucentUniforms.lightTileCountX) * lightBucketCount; + + vec3 direct = vec3(0.0); + for (int i = 0; i < translucentUniforms.lightBucketCount; i++) { + uint lightBucket = uint(lightBuckets[bucketOffset + i]); + if (lightBucket == 0u) + continue; + + uint bucketBitCount = findMSB(lightBucket) + 1u; + for (uint j = 0u; j < bucketBitCount; j++) { + if ((lightBucket & (1u << j)) == 0u) + continue; + + uint lightIdx = uint(i) * 32u + j; + direct += EvaluateLight(lights[lightIdx], surface, geometryNormal, lightIdx == 0u, pixel, texCoord); + } + } + return direct; + +} + +vec3 GetTranslucentIndirectDiffuse(Surface surface, vec3 geometryNormal) { + + vec3 worldView = -normalize(vec3(globalData.ivMatrix * vec4(surface.P, 0.0))); + vec3 worldPosition = vec3(globalData.ivMatrix * vec4(surface.P, 1.0)); + vec3 worldNormal = normalize(vec3(globalData.ivMatrix * vec4(surface.N, 0.0))); + vec3 geometryWorldNormal = normalize(vec3(globalData.ivMatrix * vec4(geometryNormal, 0.0))); + + vec3 prefilteredDiffuse = textureLod(diffuseProbe, worldNormal, 0).rgb; +#ifdef DDGI +#ifdef DDGI_SCROLL + vec4 prefilteredDiffuseLocal = ddgiData.volumeEnabled > 0 ? + GetLocalIrradiance(worldPosition, worldView, worldNormal, geometryWorldNormal, prefilteredDiffuse) : vec4(0.0, 0.0, 0.0, 1.0); +#else + vec4 prefilteredDiffuseLocal = ddgiData.volumeEnabled > 0 ? + GetLocalIrradiance(worldPosition, worldView, worldNormal, geometryWorldNormal) : vec4(0.0, 0.0, 0.0, 1.0); +#endif + prefilteredDiffuseLocal = IsInsideVolume(worldPosition) ? prefilteredDiffuseLocal : vec4(0.0, 0.0, 0.0, 1.0); + prefilteredDiffuse = (prefilteredDiffuseLocal.rgb + prefilteredDiffuse * prefilteredDiffuseLocal.a) * ddgiData.volumeStrength; +#endif + return prefilteredDiffuse * EvaluateIndirectDiffuseBRDF(surface) * surface.material.ao; + +} + +vec3 GetTranslucentIndirectSpecular(Surface surface, vec2 texCoord) { + + vec3 R = normalize(mat3(globalData.ivMatrix) * reflect(-surface.V, surface.N)); + float mipLevel = surface.material.roughness * float(translucentUniforms.specularProbeMipLevels - 1); + vec3 indirectSpecular = textureLod(specularProbe, R, mipLevel).rgb; + +#ifdef REFLECTION + // Only the closest alpha blended surface has traced reflections, the ones behind it use the probe + float reflectionDepth = textureLod(reflectionDepthTexture, texCoord, 0.0).r; + float reflectionViewDepth = ConvertDepthToViewSpace(reflectionDepth, texCoord).z; + if (abs(reflectionViewDepth - surface.P.z) < 0.01 * abs(surface.P.z)) + indirectSpecular = textureLod(reflectionTexture, texCoord, 0.0).rgb; +#endif + + return indirectSpecular * EvaluateIndirectSpecularBRDF(surface) * surface.material.ao; + +} + +// The in-scattered light (rgb) and transmittance (a) between the camera and the surface +vec4 GetTranslucentFog(vec3 viewPosition, vec2 texCoord) { + +#ifdef FOG + FroxelSlices slices = FroxelSlices(translucentUniforms.froxelNear, translucentUniforms.froxelFar, + translucentUniforms.froxelExtendedFar, translucentUniforms.froxelSliceCount, translucentUniforms.froxelDistributionExponent); + + // Each slice stores the integral up to its far end, inside the first slice it is interpolated from the camera + float slice = GetFroxelSlice(slices, -viewPosition.z); + vec2 unjitteredTexCoord = texCoord - 0.5 * globalData.jitterCurrent; + vec2 gridTexCoord = unjitteredTexCoord * translucentUniforms.froxelGridScale; + float sliceTexCoord = (max(slice - 1.0, 0.0) + 0.5) / float(translucentUniforms.froxelSliceCount); + vec4 integrated = textureLod(integratedFroxelTexture, vec3(gridTexCoord, sliceTexCoord), 0.0); + return mix(vec4(0.0, 0.0, 0.0, 1.0), integrated, clamp(slice, 0.0, 1.0)); +#else + return vec4(0.0, 0.0, 0.0, 1.0); +#endif + +} + +vec2 ProjectToTexCoord(vec3 viewPosition) { + + vec4 projected = globalData.pMatrix * vec4(viewPosition, 1.0); + return projected.xy / projected.w * 0.5 + 0.5; + +} + +bool IsOnScreen(vec2 texCoord) { + + return all(greaterThanEqual(texCoord, vec2(0.0))) && all(lessThanEqual(texCoord, vec2(1.0))); + +} + +// Results of TraceBackground: the ray hit the background, left the screen or the distance without a hit (the image goes on +// there like at its edge), was lost behind the camera, or ran behind a surface in front of the refracting one, which +// hides the background there +const int traceHit = 0; +const int traceLeft = 1; +const int traceLost = 2; +const int traceOccluded = 3; + +// Marches the ray through the depth of the background copy with steps growing with the distance. The texture coordinate +// is where the ray hit or left the screen, or where it ended. Surfaces closer than the refracting one at surfaceDepth +// (view space) are in front of it, the ray is never behind them +int TraceBackground(vec3 origin, vec3 direction, float maxDistance, float surfaceDepth, out vec2 hitTexCoord) { + + const int stepCount = 24; + hitTexCoord = ProjectToTexCoord(origin); + float lastDistance = 0.0; + for (int i = 1; i <= stepCount; i++) { + float distance = maxDistance * sqr(float(i) / float(stepCount)); + vec3 position = origin + direction * distance; + if (position.z >= 0.0) + return traceLost; + + vec2 texCoord = ProjectToTexCoord(position); + if (!IsOnScreen(texCoord)) { + // Where the ray crosses the edge of the screen, the neighbors which still hit continue there + float near = lastDistance, far = distance; + for (int j = 0; j < 5; j++) { + float middle = 0.5 * (near + far); + vec2 middleTexCoord = ProjectToTexCoord(origin + direction * middle); + if (IsOnScreen(middleTexCoord)) { + near = middle; + hitTexCoord = middleTexCoord; + } + else { + far = middle; + } + } + return traceLeft; + } + + float backgroundViewDepth = ConvertDepthToViewSpaceDepth(textureLod(refractionDepthTexture, texCoord, 0.0).r); + if (backgroundViewDepth > surfaceDepth) + return traceOccluded; + + hitTexCoord = texCoord; + if (backgroundViewDepth > position.z) { + // Refine between the last two steps. Surfaces are taken as thick, a ray which passes behind one ends on it, what + // it would hit behind isn't on the screen + float near = lastDistance, far = distance; + for (int j = 0; j < 4; j++) { + float middle = 0.5 * (near + far); + vec3 middlePosition = origin + direction * middle; + vec2 middleTexCoord = ProjectToTexCoord(middlePosition); + float middleViewDepth = ConvertDepthToViewSpaceDepth(textureLod(refractionDepthTexture, middleTexCoord, 0.0).r); + if (middleViewDepth > middlePosition.z && middleViewDepth <= surfaceDepth) { + far = middle; + hitTexCoord = middleTexCoord; + } + else { + near = middle; + } + } + return traceHit; + } + lastDistance = distance; + } + + return traceLeft; + +} + +// The angle of the cone rough surfaces scatter refracted rays into. A microfacet tilted by an angle only turns the ray by +// the fraction 1 - 1 / n of it, at both sides of the surface +float GetRefractionSpread(float roughness, float refractiveIndex) { + + return 2.0 * sqr(roughness) * abs(1.0 - 1.0 / refractiveIndex); + +} + +// The mip of the background which blurs it like the cone of the refracted rays where they hit it, far from the surface +// the blur is larger +float GetRefractionMipLevel(float spread, vec3 surfacePosition, vec2 hitTexCoord) { + + vec3 hitPosition = ConvertDepthToViewSpace(textureLod(refractionDepthTexture, hitTexCoord, 0.0).r, hitTexCoord); + float radius = spread * distance(hitPosition, surfacePosition); + float pixels = radius * abs(globalData.pMatrix[1][1]) * float(textureSize(refractionTexture, 0).y) / max(-hitPosition.z, 0.001); + return clamp(log2(max(pixels, 1.0)), 0.0, float(translucentUniforms.refractionMipLevels - 1)); + +} + +// The background seen through the surface. With SCREEN_SPACE_REFRACTION the ray is refracted where it enters, leaves +// closed surfaces through their back faces and open ones after the thickness, where it's refracted again. Otherwise the +// background is only displaced by the normal like behind thin glass. Rough surfaces blur the background +vec3 GetRefractedBackground(Surface surface, vec2 texCoord, float refractiveIndex, float thickness) { + + // Toward the edges of the screen the refraction fades out, the background behind the surface continues to the edge + refractiveIndex = mix(1.0, refractiveIndex, EdgeFadeOut(texCoord, 0.1)); + float spread = GetRefractionSpread(surface.material.roughness, refractiveIndex); +#ifdef SCREEN_SPACE_REFRACTION + vec3 incident = normalize(surface.P); + vec3 normal = dot(surface.N, incident) < 0.0 ? surface.N : -surface.N; + vec3 inside = refract(incident, normal, 1.0 / refractiveIndex); + + vec3 exitPosition = surface.P + inside * thickness; + vec3 exitDirection = refract(inside, normal, refractiveIndex); + float backDepth = textureLod(refractionBackDepthTexture, texCoord, 0.0).r; + float backViewDepth = ConvertDepthToViewSpaceDepth(backDepth); + bool closed = backDepth < 1.0 && backViewDepth < surface.P.z; + if (closed) { + // The distance to the back face along the refracted ray, found in a few fixed point steps + float distance = length(ConvertDepthToViewSpace(backDepth, texCoord) - surface.P); + vec2 exitTexCoord = texCoord; + for (int i = 0; i < 3; i++) { + vec2 stepTexCoord = ProjectToTexCoord(surface.P + inside * distance); + float stepDepth = IsOnScreen(stepTexCoord) ? textureLod(refractionBackDepthTexture, stepTexCoord, 0.0).r : 1.0; + if (stepDepth >= 1.0) + break; + exitTexCoord = stepTexCoord; + distance = length(ConvertDepthToViewSpace(stepDepth, stepTexCoord) - surface.P); + } + + vec3 backNormal = DecodeNormal(textureLod(refractionBackNormalTexture, exitTexCoord, 0.0).rg); + exitPosition = surface.P + inside * distance; + exitDirection = refract(inside, -backNormal, refractiveIndex); + // Total internal reflection keeps the ray inside, it's approximated by the reflected direction + if (dot(exitDirection, exitDirection) == 0.0) + exitDirection = reflect(inside, -backNormal); + } + + // Open surfaces like water planes are a slab of the thickness, the background inside it is seen directly + vec2 backgroundTexCoord; + int result = closed ? traceLost : TraceBackground(surface.P, inside, thickness, surface.P.z, backgroundTexCoord); + if (result != traceHit && result != traceOccluded) + result = TraceBackground(exitPosition, exitDirection, 64.0, surface.P.z, backgroundTexCoord); + // Where surfaces in front of this one hide the refracted background, the one straight behind is seen + if (result == traceOccluded) + backgroundTexCoord = texCoord; + bool seesBackground = result != traceLost; + + // Lenses magnify the background and its blur by how fast the hit moves between neighboring pixels, which is measured + // in the pixel quad. The smaller direction ignores jumps at the outlines of what is hit + vec2 hitPixel = backgroundTexCoord * translucentUniforms.resolution; + float magnification = clamp(min(length(dFdx(hitPixel)), length(dFdy(hitPixel))), 1.0, 16.0); + if (seesBackground) + return textureLod(refractionTexture, backgroundTexCoord, + GetRefractionMipLevel(spread * magnification, surface.P, backgroundTexCoord)).rgb; + + // Rays behind the camera see the probe, its mips are filtered for the roughness of reflections + vec3 worldDirection = normalize(mat3(globalData.ivMatrix) * exitDirection); + float probeMipLevel = sqrt(spread) * float(translucentUniforms.specularProbeMipLevels - 1); + return textureLod(specularProbe, worldDirection, probeMipLevel).rgb; +#else + vec3 offsetPosition = surface.P - vec3(surface.N.xy * (refractiveIndex - 1.0) * thickness, 0.0); + // Off screen the image goes on like at its edge + vec2 offsetTexCoord = clamp(ProjectToTexCoord(offsetPosition), vec2(0.0), vec2(1.0)); + // Surfaces in front of this one stay in front, they would bleed into it + float backgroundViewDepth = ConvertDepthToViewSpaceDepth(textureLod(refractionDepthTexture, offsetTexCoord, 0.0).r); + vec2 refractedTexCoord = backgroundViewDepth < surface.P.z ? offsetTexCoord : texCoord; + return textureLod(refractionTexture, refractedTexCoord, GetRefractionMipLevel(spread, surface.P, refractedTexCoord)).rgb; +#endif + +} + +// The color to blend for the material at the view space position with the opacity as coverage. The blend state of the +// mode combines it with the background, the coverage is written for the reactive mask +vec4 ShadeTranslucent(Material material, vec3 normal, vec3 geometryNormal, vec3 viewPosition, float opacity, + float refractiveIndex, float thickness, out float coverage) { + + ivec2 pixel = ivec2(gl_FragCoord.xy); + vec2 texCoord = gl_FragCoord.xy / translucentUniforms.resolution; + vec4 fog = GetTranslucentFog(viewPosition, texCoord); + +#ifdef BLEND_MULTIPLY + // Darkens the background by the color, the fog in front of the surface isn't darkened + coverage = 1.0; + vec3 factor = mix(vec3(1.0), material.baseColor, opacity); + return vec4(mix(vec3(1.0), factor, fog.a), 1.0); +#else + Surface surface = CreateSurface(normalize(-viewPosition), normal, vec3(0.0, -1.0, 0.0), material); + surface.P = viewPosition; +#ifdef BLEND_ADDITIVE + surface.material.opacity = 1.0; +#else + // The direct light weights the diffuse part by it + surface.material.opacity = opacity; +#endif + + vec3 direct = GetTranslucentDirectLight(surface, geometryNormal, pixel, texCoord); + vec3 indirectDiffuse = GetTranslucentIndirectDiffuse(surface, geometryNormal); + vec3 specular = GetTranslucentIndirectSpecular(surface, texCoord); + vec3 emissive = material.emissiveColor * globalData.preExposure; + + coverage = opacity; +#ifdef BLEND_ADDITIVE + // Adds light only, the fog in front of the surface is already in the background + vec3 color = (direct + indirectDiffuse + specular + emissive) * opacity; + return vec4(color * fog.a, 0.0); +#else + // Reflections and emission keep their strength on clear surfaces + vec3 color = direct + indirectDiffuse * opacity + specular + emissive; + color = color * fog.a + fog.rgb * opacity; + if (refractiveIndex == 1.0) + return vec4(color, opacity); + + // The refracted background replaces the one behind the surface + vec3 background = GetRefractedBackground(surface, texCoord, refractiveIndex, thickness); + return vec4(color + background * (1.0 - opacity), 1.0); +#endif +#endif + +} diff --git a/data/shader/upsampleSpatial.csh b/data/shader/upsampleSpatial.csh index 08e53fc29..009059e03 100644 --- a/data/shader/upsampleSpatial.csh +++ b/data/shader/upsampleSpatial.csh @@ -61,8 +61,8 @@ vec4 SampleCatmullRom(vec2 uv) { void main() { ivec2 pixel = ivec2(gl_GlobalInvocationID); - if (pixel.x > imageSize(textureOut).x || - pixel.y > imageSize(textureOut).y) + if (pixel.x >= imageSize(textureOut).x || + pixel.y >= imageSize(textureOut).y) return; vec2 uv = (vec2(pixel)) / vec2(imageSize(textureOut)); diff --git a/data/shader/vegetation/depth.fsh b/data/shader/vegetation/depth.fsh deleted file mode 100644 index 7ea44cedc..000000000 --- a/data/shader/vegetation/depth.fsh +++ /dev/null @@ -1,16 +0,0 @@ -#ifdef OPACITY_MAP -layout(binding = 1) uniform sampler2D opacityMap; -#endif - -in vec3 positionVS; -in vec2 texCoordVS; - -void main() { - -#ifdef OPACITY_MAP - float opacity = texture(opacityMap, texCoordVS).r; - if (opacity < 0.2) - discard; -#endif - -} \ No newline at end of file diff --git a/data/shader/vegetation/depth.vsh b/data/shader/vegetation/depth.vsh deleted file mode 100644 index 41a386733..000000000 --- a/data/shader/vegetation/depth.vsh +++ /dev/null @@ -1,37 +0,0 @@ -#include <../wind.hsh> -#include - -// Per vertex attributes -layout(location=0) in vec3 vPosition; -layout(location=2) in vec2 vTexCoord; - -// Vertex out parameters -out vec3 positionVS; -out vec2 texCoordVS; - -// Uniforms -uniform mat4 pMatrix; -uniform mat4 vMatrix; - -uniform float time; -uniform float deltaTime; - -uniform bool invertUVs; - -// Functions -void main() { - - Instance instance = instanceData[gl_InstanceID + gl_BaseInstance]; - texCoordVS = invertUVs ? vec2(vTexCoord.x, 1.0 - vTexCoord.y) : vTexCoord; - - mat4 mvMatrix = vMatrix; - - vec3 position = instance.position.xyz + vPosition; - position = instance.position.xyz + WindAnimation(vPosition, time, instance.position.xyz); - - vec4 positionToCamera = mvMatrix * vec4(position, 1.0); - positionVS = positionToCamera.xyz; - - gl_Position = pMatrix * positionToCamera; - -} \ No newline at end of file diff --git a/data/shader/vegetation/vegetation.fsh b/data/shader/vegetation/vegetation.fsh index 94a033287..a3dc6fa10 100644 --- a/data/shader/vegetation/vegetation.fsh +++ b/data/shader/vegetation/vegetation.fsh @@ -1,4 +1,5 @@ #include <../globals.hsh> +#include <../common/opacity.hsh> #include <../common/random.hsh> #include <../common/normalencode.hsh> @@ -74,7 +75,7 @@ void main() { #ifdef VERTEX_COLORS opacity *= vertexColorsVS.a; #endif - if (opacity < 0.2) + if (opacity < opacityCutoff) discard; #endif diff --git a/data/shader/volumetric/fog.hsh b/data/shader/volumetric/fog.hsh index e7d87370d..cb65b3534 100644 --- a/data/shader/volumetric/fog.hsh +++ b/data/shader/volumetric/fog.hsh @@ -1,37 +1,47 @@ struct Fog { - vec4 extinctionCoefficients; + vec4 albedo; float density; float heightFalloff; float height; float scatteringAnisotropy; - float scatteringFactor; - float extinctionFactor; float ambientFactor; }; -// https://developer.amd.com/wordpress/media/2012/10/Wenzel-Real-time_Atmospheric_Effects_in_Games.pdf -float ComputeVolumetricFog(Fog fog, vec3 viewPos, vec3 worldPos) { - viewPos.y -= fog.height; +// The fog has one medium: the density is its extinction, constant below the fog height and falling off exponentially +// above it. The scattering is the albedo times the extinction, the froxels and the rays to the lights use the same extinction + +float GetVolumetricFogDensity(Fog fog, vec3 worldPos) { + worldPos.y -= fog.height; - vec3 viewToWorldPos = worldPos - viewPos; + return clamp(exp(-fog.heightFalloff * worldPos.y), 0.0, 1.0); + +} - float fogIntegration = length(viewToWorldPos) * - exp(-fog.heightFalloff * viewPos.y); +// Integral of the density profile over the height relative to the fog height +float IntegrateVolumetricFogDensity(Fog fog, float height) { - float t = fog.heightFalloff * viewToWorldPos.y; - if (abs(t) > 0.0001) { - fogIntegration *= (1.0 - exp(-t)) / t; - } + if (height <= 0.0 || fog.heightFalloff <= 0.0) + return height; + return (1.0 - exp(-fog.heightFalloff * height)) / fog.heightFalloff; - return max(exp(-fog.density * fogIntegration), 0.0); } -float GetVolumetricFogDensity(Fog fog, vec3 worldPos) { +// Transmittance between two points +float ComputeVolumetricFog(Fog fog, vec3 viewPos, vec3 worldPos) { - worldPos.y -= fog.height; + float startHeight = viewPos.y - fog.height; + float endHeight = worldPos.y - fog.height; + float heightDifference = endHeight - startHeight; - return clamp(exp(-fog.heightFalloff * worldPos.y), 0.0, 1.0); + // The mean density along the ray, the integral over the height divided by the height difference. Below a centimeter + // the difference of the integrals loses its precision, the density hardly changes there + float meanDensity = abs(heightDifference) > 0.01 ? + (IntegrateVolumetricFogDensity(fog, endHeight) - IntegrateVolumetricFogDensity(fog, startHeight)) / heightDifference : + GetVolumetricFogDensity(fog, viewPos); + + float opticalDepth = fog.density * meanDensity * distance(viewPos, worldPos); + return exp(-opticalDepth); } diff --git a/data/shader/volumetric/fogVolumes.hsh b/data/shader/volumetric/fogVolumes.hsh new file mode 100644 index 000000000..94f3497fd --- /dev/null +++ b/data/shader/volumetric/fogVolumes.hsh @@ -0,0 +1,52 @@ +#ifdef FOG_VOLUMES + +#define FOG_VOLUME_BOX 0 +#define FOG_VOLUME_ELLIPSOID 1 + +struct FogVolume { + vec4 worldToUnit0; + vec4 worldToUnit1; + vec4 worldToUnit2; + + vec4 scatteringAndDensity; + vec4 emissiveAndEdgeFade; + vec4 noiseOffsetAndFrequency; + + float noiseAmount; + float noiseCoverage; + float noiseSharpness; + int noiseOctaves; + + float heightFalloff; + float ambientFactor; + int shape; + float selfShadowing; + + float scatteringAnisotropy; + float padding0; + float padding1; + float padding2; +}; + +layout(std430, set = 3, binding = 11) buffer FogVolumes { + FogVolume fogVolumes[]; +}; + +layout(std430, set = 3, binding = 13) buffer FogVolumeMasks { + uint fogVolumeMasks[]; +}; + +uint GetFogVolumeClusterIndex() { + + return gl_WorkGroupID.x + (gl_WorkGroupID.y + gl_WorkGroupID.z * gl_NumWorkGroups.y) * gl_NumWorkGroups.x; + +} + +vec3 GetFogVolumeUnitPosition(FogVolume volume, vec3 worldPosition) { + + vec4 position = vec4(worldPosition, 1.0); + return vec3(dot(volume.worldToUnit0, position), dot(volume.worldToUnit1, position), dot(volume.worldToUnit2, position)); + +} + +#endif diff --git a/data/shader/volumetric/froxel.hsh b/data/shader/volumetric/froxel.hsh new file mode 100644 index 000000000..493aa7fb6 --- /dev/null +++ b/data/shader/volumetric/froxel.hsh @@ -0,0 +1,67 @@ +#include <../globals.hsh> +#include <../common/convert.hsh> +#include + +#define FROXEL_CLUSTER_SIZE 4 +// Thin fog is far below the normal range of the half floats of the froxels +#define FROXEL_DATA_SCALE 256.0 + +layout(push_constant) uniform constants { + ivec2 columnCount; + ivec2 resolution; + int sliceCount; + int tileSize; + float near; + float far; + int lightCount; + int resetHistory; + int fogVolumeCount; + vec4 jitter; + float extendedFar; + float distributionExponent; + float padding1; + float padding2; +} pushConstants; + +FroxelSlices GetFroxelSlices() { + + return FroxelSlices(pushConstants.near, pushConstants.far, pushConstants.extendedFar, pushConstants.sliceCount, + pushConstants.distributionExponent); + +} + +float GetFroxelSliceDepth(float slice) { + + return GetFroxelSliceDepth(GetFroxelSlices(), slice); + +} + +float GetFroxelSlice(float viewDepth) { + + return GetFroxelSlice(GetFroxelSlices(), viewDepth); + +} + +// The grid is fixed to the unjittered projection, a jittered grid shows up as pulsing of small lights +vec2 UnjitteredToJitteredTexCoord(vec2 texCoord) { + + return texCoord + 0.5 * globalData.jitterCurrent; + +} + +vec2 GetFroxelColumnTexCoord(ivec2 column, vec2 volumetricResolution) { + + return UnjitteredToJitteredTexCoord((vec2(column) + 0.5) * float(pushConstants.tileSize) / volumetricResolution); + +} + +vec3 GetFroxelPosition(ivec3 froxel, vec3 offset, vec2 volumetricResolution) { + + vec2 texCoord = (vec2(froxel.xy) + offset.xy) * float(pushConstants.tileSize) / volumetricResolution; + + float viewDepth = GetFroxelSliceDepth(float(froxel.z) + offset.z); + + vec3 rayDirection = normalize(ConvertDepthToViewSpace(1.0, UnjitteredToJitteredTexCoord(texCoord))); + return rayDirection * (viewDepth / max(-rayDirection.z, 1e-3)); + +} diff --git a/data/shader/volumetric/froxelApply.csh b/data/shader/volumetric/froxelApply.csh new file mode 100644 index 000000000..46e298331 --- /dev/null +++ b/data/shader/volumetric/froxelApply.csh @@ -0,0 +1,78 @@ +layout (local_size_x = 8, local_size_y = 8) in; + +#include <../globals.hsh> +#include <../common/convert.hsh> +#include <../common/stencil.hsh> + +#include + +layout(set = 3, binding = 0, rgba16f) writeonly uniform image2D volumetricImage; +layout(set = 3, binding = 1) uniform sampler2D depthTexture; +layout(set = 3, binding = 3) uniform sampler2D oceanDepthTexture; +layout(set = 3, binding = 4) uniform usampler2D oceanStencilTexture; +layout(set = 3, binding = 20) uniform sampler3D integratedFroxelTexture; + +// Cubic B-spline in x and y from four linear samples, see "Fast Third-Order Texture Filtering", Sigg and Hadwiger 2005 +vec4 SampleIntegratedFroxels(vec3 texCoord) { + + vec2 size = vec2(pushConstants.columnCount); + vec2 coord = texCoord.xy * size - 0.5; + vec2 index = floor(coord); + vec2 fraction = coord - index; + vec2 oneMinusFraction = 1.0 - fraction; + + vec2 w0 = oneMinusFraction * oneMinusFraction * oneMinusFraction / 6.0; + vec2 w1 = (4.0 - 6.0 * fraction * fraction + 3.0 * fraction * fraction * fraction) / 6.0; + vec2 w3 = fraction * fraction * fraction / 6.0; + vec2 w2 = 1.0 - w0 - w1 - w3; + + vec2 g0 = w0 + w1; + vec2 g1 = w2 + w3; + vec2 coord0 = (index - 0.5 + w1 / g0) / size; + vec2 coord1 = (index + 1.5 + w3 / g1) / size; + + vec4 sample00 = textureLod(integratedFroxelTexture, vec3(coord0.x, coord0.y, texCoord.z), 0.0); + vec4 sample10 = textureLod(integratedFroxelTexture, vec3(coord1.x, coord0.y, texCoord.z), 0.0); + vec4 sample01 = textureLod(integratedFroxelTexture, vec3(coord0.x, coord1.y, texCoord.z), 0.0); + vec4 sample11 = textureLod(integratedFroxelTexture, vec3(coord1.x, coord1.y, texCoord.z), 0.0); + + return g0.y * (g0.x * sample00 + g1.x * sample10) + g1.y * (g0.x * sample01 + g1.x * sample11); + +} + +void main() { + + ivec2 pixel = ivec2(gl_GlobalInvocationID.xy); + ivec2 resolution = imageSize(volumetricImage); + if (any(greaterThanEqual(pixel, resolution))) + return; + + vec2 texCoord = (vec2(pixel) + 0.5) / vec2(resolution); + + float depth = textureLod(depthTexture, texCoord, 0.0).r; + vec3 endPos = ConvertDepthToViewSpace(depth, texCoord); + +#ifdef OCEAN + StencilFeatures features = DecodeStencilFeatures(textureLod(oceanStencilTexture, texCoord, 0.0).r); + + float oceanDepth = textureLod(oceanDepthTexture, texCoord, 0.0).r; + vec3 oceanPos = ConvertDepthToViewSpace(oceanDepth, texCoord); + + if (oceanDepth < depth && !features.underWaterPixel) { + endPos = oceanPos; + } +#endif + + // Each slice stores the integral up to its far end, inside the first slice it is interpolated from the camera + float slice = GetFroxelSlice(-endPos.z); + vec2 unjitteredTexCoord = texCoord - 0.5 * globalData.jitterCurrent; + vec2 gridTexCoord = unjitteredTexCoord * vec2(resolution) / vec2(pushConstants.columnCount * pushConstants.tileSize); + float sliceTexCoord = (max(slice - 1.0, 0.0) + 0.5) / float(pushConstants.sliceCount); + vec4 integrated = SampleIntegratedFroxels(vec3(gridTexCoord, sliceTexCoord)); + + float firstSliceWeight = clamp(slice, 0.0, 1.0); + integrated = mix(vec4(0.0, 0.0, 0.0, 1.0), integrated, firstSliceWeight); + + imageStore(volumetricImage, pixel, integrated); + +} diff --git a/data/shader/volumetric/froxelCulling.csh b/data/shader/volumetric/froxelCulling.csh new file mode 100644 index 000000000..c5c3b8788 --- /dev/null +++ b/data/shader/volumetric/froxelCulling.csh @@ -0,0 +1,122 @@ +// One light list per froxel cluster + +layout (local_size_x = 64) in; + +#include <../deferred/lightCulling.hsh> +#include <../structures.hsh> +#include <../globals.hsh> +#include <../common/convert.hsh> + +#include +#include + +layout (std430, set = 3, binding = 8) buffer VolumetricLights { + VolumetricLight volumetricLights[]; +}; + +layout(std430, set = 3, binding = 10) buffer LightIndicesBuffer { + int lightIndices[]; +}; + +const int lightCountPerCluster = 63; + +shared int sharedLightIndices[lightCountPerCluster]; +shared int sharedLightCount; +#ifdef FOG_VOLUMES +shared uint sharedFogVolumeMask; +#endif + +void main() { + + ivec3 cluster = ivec3(gl_WorkGroupID); + ivec3 firstFroxel = cluster * FROXEL_CLUSTER_SIZE; + ivec3 lastFroxel = min(firstFroxel + FROXEL_CLUSTER_SIZE, ivec3(pushConstants.columnCount, pushConstants.sliceCount)); + + vec2 volumetricResolution = vec2(pushConstants.resolution); + + vec3 corners[8]; + for (int i = 0; i < 8; i++) { + ivec3 froxel = ivec3((i & 1) > 0 ? lastFroxel.x : firstFroxel.x, (i & 2) > 0 ? lastFroxel.y : firstFroxel.y, + (i & 4) > 0 ? lastFroxel.z - 1 : firstFroxel.z); + vec3 offset = vec3(0.0, 0.0, (i & 4) > 0 ? 1.0 : 0.0); + corners[i] = GetFroxelPosition(froxel, offset, volumetricResolution); + } + + Plane planes[4]; + GetFrustumPlanes(planes, corners); + AABB aabb = CalculateAABB(corners); + + if (gl_LocalInvocationIndex == 0u) { + sharedLightCount = 0; +#ifdef FOG_VOLUMES + sharedFogVolumeMask = 0u; +#endif + } + + barrier(); + + for (int i = int(gl_LocalInvocationIndex); i < pushConstants.lightCount; i += int(gl_WorkGroupSize.x)) { + VolumetricLight light = volumetricLights[i]; + float radius = light.direction.w; + uint lightType = floatBitsToUint(light.color.a); + + Sphere sphere; + if (lightType == POINT_LIGHT) { + sphere.center = light.location.xyz; + sphere.radius = radius; + } + else if (lightType == SPOT_LIGHT) { + sphere = CalculateSphereFromSpotLight(light.location, light.direction, radius); + } + else { + continue; + } + + if (SphereAABBIntersection(sphere, aabb) && SphereFrustumIntersection(sphere, planes)) { + int lightIdx = atomicAdd(sharedLightCount, 1); + if (lightIdx < lightCountPerCluster) + sharedLightIndices[lightIdx] = i; + } + } + +#ifdef FOG_VOLUMES + vec3 clusterCenter = vec3(0.0); + for (int i = 0; i < 8; i++) + clusterCenter += corners[i] / 8.0; + + float clusterRadius = 0.0; + for (int i = 0; i < 8; i++) + clusterRadius = max(clusterRadius, distance(corners[i], clusterCenter)); + + vec3 worldClusterCenter = vec3(globalData.ivMatrix * vec4(clusterCenter, 1.0)); + + for (int i = int(gl_LocalInvocationIndex); i < pushConstants.fogVolumeCount; i += int(gl_WorkGroupSize.x)) { + FogVolume volume = fogVolumes[i]; + + // Each row is the gradient of a unit axis, this also keeps flat and long volumes tight + vec3 unitCenter = GetFogVolumeUnitPosition(volume, worldClusterCenter); + vec3 unitRadius = clusterRadius * vec3(length(volume.worldToUnit0.xyz), + length(volume.worldToUnit1.xyz), length(volume.worldToUnit2.xyz)); + + if (all(lessThanEqual(abs(unitCenter), vec3(1.0) + unitRadius))) + atomicOr(sharedFogVolumeMask, 1u << uint(i)); + } +#endif + + barrier(); + + int lightCount = min(lightCountPerCluster, sharedLightCount); + int clusterOffset = int(cluster.x + (cluster.y + cluster.z * gl_NumWorkGroups.y) * gl_NumWorkGroups.x) * + (lightCountPerCluster + 1); + for (int i = int(gl_LocalInvocationIndex); i < lightCount; i += int(gl_WorkGroupSize.x)) { + lightIndices[clusterOffset + i + 1] = sharedLightIndices[i]; + } + + if (gl_LocalInvocationIndex == 0u) { + lightIndices[clusterOffset] = lightCount; +#ifdef FOG_VOLUMES + fogVolumeMasks[GetFogVolumeClusterIndex()] = sharedFogVolumeMask; +#endif + } + +} diff --git a/data/shader/volumetric/froxelFilter.csh b/data/shader/volumetric/froxelFilter.csh new file mode 100644 index 000000000..d1874025e --- /dev/null +++ b/data/shader/volumetric/froxelFilter.csh @@ -0,0 +1,34 @@ +layout (local_size_x = 4, local_size_y = 4, local_size_z = 4) in; + +#include <../globals.hsh> +#include <../common/convert.hsh> + +#include + +layout(set = 3, binding = 0, rgba16f) writeonly uniform image3D froxelImage; +layout(set = 3, binding = 1) uniform sampler3D froxelTexture; + +const float weights[7] = float[](0.071303, 0.131514, 0.189879, 0.214607, 0.189879, 0.131514, 0.071303); + +void main() { + + ivec3 froxel = ivec3(gl_GlobalInvocationID); + ivec3 froxelCount = ivec3(pushConstants.columnCount, pushConstants.sliceCount); + if (any(greaterThanEqual(froxel, froxelCount))) + return; + +#ifdef HORIZONTAL + ivec3 offset = ivec3(1, 0, 0); +#else + ivec3 offset = ivec3(0, 1, 0); +#endif + + vec4 result = vec4(0.0); + for (int i = -3; i <= 3; i++) { + ivec3 coord = clamp(froxel + i * offset, ivec3(0), froxelCount - 1); + result += weights[i + 3] * texelFetch(froxelTexture, coord, 0); + } + + imageStore(froxelImage, froxel, result); + +} diff --git a/data/shader/volumetric/froxelInject.csh b/data/shader/volumetric/froxelInject.csh new file mode 100644 index 000000000..75efa86c8 --- /dev/null +++ b/data/shader/volumetric/froxelInject.csh @@ -0,0 +1,346 @@ +#extension GL_EXT_nonuniform_qualifier : require + +#include + +// volumetricLights.hsh reads gl_WorkGroupSize, which has to be declared before +layout (local_size_x = FROXEL_CLUSTER_SIZE, local_size_y = FROXEL_CLUSTER_SIZE, local_size_z = FROXEL_CLUSTER_SIZE) in; + +#include +#include +#include <../common/random.hsh> + +layout(set = 3, binding = 0, rgba16f) writeonly uniform image3D froxelImage; +layout(set = 3, binding = 1) uniform sampler3D historyFroxelTexture; + +#ifdef SKY_PROBE +layout(set = 1, binding = 12) uniform samplerCube diffuseProbe; +#endif + +// Punctual lights only contribute to the first 100 units of a view ray +const float punctualLightDistance = 100.0; + +// Integrates the inverse square falloff along the part of the view ray inside the froxel, such that the energy doesn't +// depend on the jitter. The shadow is sampled where the falloff has most of its energy. The fog volumes have their own +// phase function, their light is returned in volumeScattering where hasVolumes is set +vec3 ComputePunctualLightScattering(uint lightType, vec3 rayDirection, float rayStart, float rayEnd, float sampleOffset, + float angularRadius, bool hasVolumes, float volumeAnisotropy, out vec3 volumeScattering) { + + vec3 lightScattering = vec3(0.0); + volumeScattering = vec3(0.0); + + for (int j = 0; j < sharedLightIndicesCount; j++) { + VolumetricLight light = sharedLights[j]; + + float radius = light.direction.w; + + float closestDistance = dot(light.location.xyz, rayDirection); + float sqrRayDistance = max(dot(light.location.xyz, light.location.xyz) - closestDistance * closestDistance, 0.0); + if (sqrRayDistance >= radius * radius) + continue; + + // The ray stands for a whole froxel column, a light inside of it is spread over the footprint of the column + float footprint = angularRadius * max(closestDistance, 0.0); + float offset = sqrt(sqrRayDistance + footprint * footprint + 0.1); + + vec3 position = rayDirection * clamp(closestDistance, rayStart, rayEnd); + vec3 pointToLight = light.location.xyz - position; + float sqrDistance = dot(pointToLight, pointToLight); + + float attenuation = saturate(1.0 - pow(sqrDistance / (radius * radius), 2.0)); + if (attenuation == 0.0) + continue; + + float angleStart = atan((rayStart - closestDistance) / offset); + float angleEnd = atan((rayEnd - closestDistance) / offset); + float falloff = (angleEnd - angleStart) / (offset * (rayEnd - rayStart)); + + vec3 shadowPosition = rayDirection * (closestDistance + offset * tan(mix(angleStart, angleEnd, sampleOffset))); + + if (lightType == SPOT_LIGHT) { + vec3 L = normalize(light.location.xyz - shadowPosition); + float strength = dot(L, normalize(-light.direction.xyz)); + float angleAttenuation = saturate(strength * light.specific0 + light.specific1); + if (angleAttenuation == 0.0) + continue; + + attenuation *= sqr(angleAttenuation); + } + + float NdotL = dot(-pointToLight / max(sqrt(sqrDistance), 0.001), rayDirection); + float shadowValue = GetShadowFactorPunctualLight(j, lightType, shadowPosition); + + vec3 incomingLight = shadowValue * light.color.rgb * attenuation * light.intensity * falloff; + lightScattering += ComputeScattering(uniforms.fog.scatteringAnisotropy, NdotL) * incomingLight; + if (hasVolumes) + volumeScattering += ComputeScattering(volumeAnisotropy, NdotL) * incomingLight; + } + + return lightScattering; + +} + +vec3 ComputePunctualLightSample(uint lightType, ivec3 froxel, vec3 offset, vec2 volumetricResolution, + bool hasVolumes, float volumeAnisotropy, out vec3 volumeScattering) { + + volumeScattering = vec3(0.0); + + vec3 columnStart = normalize(GetFroxelPosition(froxel, vec3(0.0, 0.5, 1.0), volumetricResolution)); + vec3 columnEnd = normalize(GetFroxelPosition(froxel, vec3(1.0, 0.5, 1.0), volumetricResolution)); + float angularRadius = 0.5 * distance(columnStart, columnEnd); + + vec3 segmentStart = GetFroxelPosition(froxel, vec3(offset.xy, 0.0), volumetricResolution); + vec3 segmentEnd = GetFroxelPosition(froxel, vec3(offset.xy, 1.0), volumetricResolution); + + float rayStart = length(segmentStart); + float rayLength = length(segmentEnd); + float rayEnd = min(rayLength, punctualLightDistance); + + return rayStart < rayEnd ? ComputePunctualLightScattering(lightType, segmentEnd / rayLength, rayStart, rayEnd, offset.z, + angularRadius, hasVolumes, volumeAnisotropy, volumeScattering) : vec3(0.0); + +} + +vec4 GetHistory(vec3 position, vec2 volumetricResolution, out bool valid) { + + vec3 worldPosition = vec3(globalData.ivMatrix * vec4(position, 1.0)); + + vec4 lastClipSpace = globalData.pvMatrixLast * vec4(worldPosition, 1.0); + vec2 lastTexCoord = (lastClipSpace.xy / lastClipSpace.w - globalData.jitterLast) * 0.5 + 0.5; + float lastViewDepth = -(globalData.vMatrixLast * vec4(worldPosition, 1.0)).z; + + vec2 gridScale = volumetricResolution / vec2(pushConstants.columnCount * pushConstants.tileSize); + vec3 historyTexCoord = vec3(lastTexCoord * gridScale, GetFroxelSlice(lastViewDepth) / float(pushConstants.sliceCount)); + + valid = pushConstants.resetHistory == 0 && lastClipSpace.w > 0.0 && + all(greaterThanEqual(historyTexCoord, vec3(0.0))) && all(lessThanEqual(historyTexCoord, vec3(1.0))); + return textureLod(historyFroxelTexture, historyTexCoord, 0.0); + +} + +vec3 GetSkyAmbient() { + +#ifdef SKY_PROBE + return 0.5 * (textureLod(diffuseProbe, vec3(0.0, 1.0, 0.0), 0.0).rgb + textureLod(diffuseProbe, vec3(0.0, -1.0, 0.0), 0.0).rgb); +#else + return vec3(1.0); +#endif + +} + +#ifdef FOG_VOLUMES +float GetValueNoise(vec3 position) { + + ivec3 cell = ivec3(floor(position)); + vec3 weight = fract(position); + weight = weight * weight * (3.0 - 2.0 * weight); + + float values[8]; + for (int i = 0; i < 8; i++) { + uvec3 corner = uvec3(cell + ivec3(i & 1, (i >> 1) & 1, (i >> 2) & 1)); + // The hash is symmetric in its last components + values[i] = floatConstruct(hash(corner + uvec3(0u, 0x3C6EF372u, 0x9E3779B9u))); + } + + float bottom = mix(mix(values[0], values[1], weight.x), mix(values[2], values[3], weight.x), weight.y); + float top = mix(mix(values[4], values[5], weight.x), mix(values[6], values[7], weight.x), weight.y); + return mix(bottom, top, weight.z); + +} + +// Coverage is the part of the volume which keeps its fog, the rest is cut out as gaps +float GetFogVolumeNoise(FogVolume volume, vec3 worldPosition) { + + vec3 position = (worldPosition - volume.noiseOffsetAndFrequency.xyz) * volume.noiseOffsetAndFrequency.w; + + float noise = 0.0; + float weight = 1.0; + float totalWeight = 0.0; + for (int i = 0; i < volume.noiseOctaves; i++) { + noise += weight * GetValueNoise(position + 17.0 * float(i)); + totalWeight += weight; + weight *= 0.5; + position *= 2.03; + } + noise /= totalWeight; + + // Layered value noise rarely leaves this range + float threshold = mix(0.8, 0.2, volume.noiseCoverage); + float softness = mix(0.3, 0.01, volume.noiseSharpness); + return smoothstep(threshold - softness, threshold + softness, noise); + +} + +float GetFogVolumeDensity(FogVolume volume, vec3 worldPosition) { + + vec3 unitPosition = GetFogVolumeUnitPosition(volume, worldPosition); + + vec3 absPosition = abs(unitPosition); + float edgeDistance = 1.0 - (volume.shape == FOG_VOLUME_BOX ? + max(absPosition.x, max(absPosition.y, absPosition.z)) : length(unitPosition)); + if (edgeDistance <= 0.0) + return 0.0; + + float density = volume.scatteringAndDensity.a * smoothstep(0.0, max(volume.emissiveAndEdgeFade.a, 0.001), edgeDistance); + density *= exp(-volume.heightFalloff * (unitPosition.y * 0.5 + 0.5)); + + if (volume.noiseAmount > 0.0) + density *= mix(1.0, GetFogVolumeNoise(volume, worldPosition), volume.noiseAmount); + + return density; + +} + +// Ignores the noise, the falloff and the fade at the edges +float GetFogVolumeTransmittanceToLight(FogVolume volume, vec3 worldPosition, vec3 worldToLight) { + + vec3 unitPosition = GetFogVolumeUnitPosition(volume, worldPosition); + vec3 unitDirection = vec3(dot(volume.worldToUnit0.xyz, worldToLight), dot(volume.worldToUnit1.xyz, worldToLight), + dot(volume.worldToUnit2.xyz, worldToLight)); + + float exitDistance; + if (volume.shape == FOG_VOLUME_BOX) { + vec3 axisDistance = (vec3(1.0) - unitPosition * sign(unitDirection)) / max(abs(unitDirection), vec3(1e-6)); + exitDistance = min(axisDistance.x, min(axisDistance.y, axisDistance.z)); + } + else { + float a = dot(unitDirection, unitDirection); + float b = dot(unitPosition, unitDirection); + float c = dot(unitPosition, unitPosition) - 1.0; + exitDistance = (-b + sqrt(max(b * b - a * c, 0.0))) / a; + } + + // The second term stands in for light which reaches the point after scattering several times + float opticalDepth = volume.selfShadowing * volume.scatteringAndDensity.a * max(exitDistance, 0.0); + return max(exp(-opticalDepth), 0.3 * exp(-0.25 * opticalDepth)); + +} +#endif + +void main() { + + // No early return, all invocations have to reach the barriers when loading the lights + ivec3 froxel = ivec3(gl_GlobalInvocationID); + bool validFroxel = all(lessThan(froxel.xy, pushConstants.columnCount)) && froxel.z < pushConstants.sliceCount; + + vec2 volumetricResolution = vec2(pushConstants.resolution); + + vec3 jitter = pushConstants.jitter.xyz; + // The last slice reaches up to the camera far plane, a jittered depth makes the distance flicker + if (froxel.z == pushConstants.sliceCount - 1) + jitter.z = 0.5; + vec3 position = GetFroxelPosition(froxel, jitter, volumetricResolution); + vec3 rayDirection = normalize(position); + vec3 worldPosition = vec3(globalData.ivMatrix * vec4(position, 1.0)); + + float heightDensity = GetVolumetricFogDensity(uniforms.fog, worldPosition); + float density = uniforms.fog.density * heightDensity; + + // Weights of the lighting in the volumes, known before the lighting is computed + vec3 volumeDirectional = vec3(0.0); + vec3 volumeLocal = vec3(0.0); + vec3 volumeAmbient = vec3(0.0); + vec3 volumeEmissive = vec3(0.0); + float volumeExtinction = 0.0; + + // Overlapping volumes share one phase function, their anisotropies are blended by the light they scatter. A single + // volume keeps its own exactly + float volumeAnisotropyWeighted = 0.0; + float volumeAnisotropyWeight = 0.0; + +#ifdef FOG_VOLUMES + vec3 worldToLight = -normalize(mat3(globalData.ivMatrix) * volumetricLights[0].direction.xyz); + uint fogVolumeMask = fogVolumeMasks[GetFogVolumeClusterIndex()]; + while (fogVolumeMask != 0u) { + FogVolume volume = fogVolumes[findLSB(fogVolumeMask)]; + fogVolumeMask &= fogVolumeMask - 1u; + + float volumeDensity = GetFogVolumeDensity(volume, worldPosition); + if (volumeDensity <= 0.0) + continue; + + float transmittance = uniforms.directionalLightCount > 0 ? + GetFogVolumeTransmittanceToLight(volume, worldPosition, worldToLight) : 1.0; + + vec3 volumeScattering = volumeDensity * volume.scatteringAndDensity.rgb; + float scatteringWeight = dot(volumeScattering, vec3(0.2126, 0.7152, 0.0722)); + volumeAnisotropyWeighted += scatteringWeight * volume.scatteringAnisotropy; + volumeAnisotropyWeight += scatteringWeight; + + volumeDirectional += transmittance * volumeScattering; + volumeLocal += volumeScattering; + volumeAmbient += volume.ambientFactor * volumeScattering; + volumeEmissive += volumeDensity * volume.emissiveAndEdgeFade.rgb; + volumeExtinction += volumeDensity; + } +#endif + + // Without a volume at the froxel the second phase function is skipped + bool hasVolumes = volumeAnisotropyWeight > 0.0; + float volumeAnisotropy = hasVolumes ? volumeAnisotropyWeighted / volumeAnisotropyWeight : 0.0; + + // The lighting is multiplied by the density, shadows are expensive and don't matter without fog + bool hasFog = validFroxel && ((density > 0.0 && heightDensity > 0.001) || volumeExtinction > 0.0); + + vec3 directionalScattering = vec3(0.0); + vec3 volumeDirectionalScattering = vec3(0.0); + for (int j = 0; hasFog && j < uniforms.directionalLightCount; j++) { + VolumetricLight light = volumetricLights[j]; + + uint lightType = floatBitsToUint(light.color.a); + + bool isMain = j == 0 ? true : false; + float shadowValue = GetShadowFactorDirectionalLight(j, light.shadowIdx, lightType, isMain, position); + + vec3 lightPosition = position - 100000.0 * light.direction.xyz; + lightPosition = vec3(globalData.ivMatrix * vec4(lightPosition, 1.0)); + float extinctionToLight = ComputeVolumetricFog(uniforms.fog, worldPosition, lightPosition); + float NdotL = dot(rayDirection, normalize(light.direction.xyz)); + + vec3 incomingLight = shadowValue * light.color.rgb * light.intensity * extinctionToLight; + directionalScattering += ComputeScattering(uniforms.fog.scatteringAnisotropy, NdotL) * incomingLight; + if (hasVolumes) + volumeDirectionalScattering += ComputeScattering(volumeAnisotropy, NdotL) * incomingLight; + } + + vec3 center = GetFroxelPosition(froxel, vec3(0.5), volumetricResolution); + + vec3 localScattering = vec3(0.0); + vec3 volumeLocalScattering = vec3(0.0); +#ifdef LOCAL_LIGHTS + vec3 volumeLightScattering; + LoadLightTypeData(POINT_LIGHT); + if (hasFog && sharedLightIndicesCount > 0) { + localScattering += ComputePunctualLightSample(POINT_LIGHT, froxel, pushConstants.jitter.xyz, volumetricResolution, + hasVolumes, volumeAnisotropy, volumeLightScattering); + volumeLocalScattering += volumeLightScattering; + } + LoadLightTypeData(SPOT_LIGHT); + if (hasFog && sharedLightIndicesCount > 0) { + localScattering += ComputePunctualLightSample(SPOT_LIGHT, froxel, pushConstants.jitter.xyz, volumetricResolution, + hasVolumes, volumeAnisotropy, volumeLightScattering); + volumeLocalScattering += volumeLightScattering; + } +#endif + + vec3 skyAmbient = hasFog ? GetSkyAmbient() : vec3(0.0); + + vec3 scattering = uniforms.fog.albedo.rgb * density * + (directionalScattering + localScattering + uniforms.fog.ambientFactor * skyAmbient); + scattering += volumeDirectional * volumeDirectionalScattering + volumeLocal * volumeLocalScattering + + volumeAmbient * skyAmbient + volumeEmissive; + // Fog volumes have their own extinction, the global fog doesn't change it + float extinction = density + volumeExtinction; + + vec4 current = vec4(scattering, extinction) * FROXEL_DATA_SCALE; + + bool validHistory; + vec4 history = GetHistory(center, volumetricResolution, validHistory); + // A single invalid value would stay in the history forever + validHistory = validHistory && !any(isnan(history)) && !any(isinf(history)); + history.rgb *= globalData.preExposure / globalData.lastPreExposure; + vec4 result = validHistory ? mix(history, current, 0.1) : current; + + if (validFroxel) + imageStore(froxelImage, froxel, result); + +} diff --git a/data/shader/volumetric/froxelIntegrate.csh b/data/shader/volumetric/froxelIntegrate.csh new file mode 100644 index 000000000..31e0f9ab6 --- /dev/null +++ b/data/shader/volumetric/froxelIntegrate.csh @@ -0,0 +1,88 @@ +layout (local_size_x = 8, local_size_y = 8) in; + +#include <../globals.hsh> +#include <../common/convert.hsh> +#include <../clouds/shadow.hsh> + +#include +#include + +layout(set = 3, binding = 0, rgba16f) writeonly uniform image3D integratedFroxelImage; +layout(set = 3, binding = 1) uniform sampler3D froxelTexture; +layout(set = 3, binding = 5) uniform sampler2D volumetricCloudTexture; + +layout(std140, set = 3, binding = 7) uniform UniformBuffer { + float intensity; + int directionalLightCount; + int padding0; + int padding1; + vec4 planetCenterAndRadius; + Fog fog; + CloudShadow cloudShadow; +} uniforms; + +void main() { + + ivec2 column = ivec2(gl_GlobalInvocationID.xy); + if (any(greaterThanEqual(column, pushConstants.columnCount))) + return; + + vec2 volumetricResolution = vec2(pushConstants.resolution); + vec2 texCoord = GetFroxelColumnTexCoord(column, volumetricResolution); + + vec3 viewDirection = normalize(ConvertDepthToViewSpace(1.0, texCoord)); + float distancePerDepth = 1.0 / max(-viewDirection.z, 1e-3); + vec3 worldDirection = vec3(globalData.ivMatrix * vec4(viewDirection, 0.0)); + + vec3 foginess = vec3(0.0); + vec4 extinction = vec4(1.0); + vec4 extinctionWithClouds = vec4(1.0); + +#ifdef CLOUDS + bool receivedCloudExtinction = false; + float cloudExtinction = min(textureLod(volumetricCloudTexture, texCoord, 0.0).a, 1.0); + vec3 planetCenter = uniforms.planetCenterAndRadius.xyz; + float cloudInnerRadius = uniforms.planetCenterAndRadius.w; +#endif + + float sliceStart = 0.0; + for (int i = 0; i < pushConstants.sliceCount; i++) { + float sliceEnd = GetFroxelSliceDepth(float(i + 1)); + float stepLength = (sliceEnd - sliceStart) * distancePerDepth; + + vec4 froxel = texelFetch(froxelTexture, ivec3(column, i), 0) / FROXEL_DATA_SCALE; + + // Extinction of the global fog and the fog volumes, grey for all channels + vec4 extinctionCoefficient = vec4(froxel.a); + + vec4 clampedExtinction = max(extinctionCoefficient, 0.0000001); + vec4 stepExtinction = exp(-extinctionCoefficient * stepLength); + + vec3 stepScattering = froxel.rgb; + vec3 luminanceIntegral = (stepScattering - stepScattering * stepExtinction.rgb) / clampedExtinction.rgb; + +#ifdef CLOUDS + foginess += luminanceIntegral * extinctionWithClouds.rgb; + + vec3 worldPosition = globalData.cameraLocation.xyz + + worldDirection * (0.5 * (sliceStart + sliceEnd) * distancePerDepth); + float distToPlanetCenter = distance(worldPosition, planetCenter); + if (distToPlanetCenter > cloudInnerRadius && !receivedCloudExtinction) { + extinctionWithClouds *= stepExtinction * cloudExtinction; + receivedCloudExtinction = true; + } + else { + extinctionWithClouds *= stepExtinction; + } +#else + foginess += luminanceIntegral * extinction.rgb; +#endif + + extinction *= stepExtinction; + + imageStore(integratedFroxelImage, ivec3(column, i), vec4(foginess * uniforms.intensity, extinction.a)); + + sliceStart = sliceEnd; + } + +} diff --git a/data/shader/volumetric/froxelSlices.hsh b/data/shader/volumetric/froxelSlices.hsh new file mode 100644 index 000000000..b4bfac26a --- /dev/null +++ b/data/shader/volumetric/froxelSlices.hsh @@ -0,0 +1,41 @@ +// The depths of the slices of the froxel grid, which is shared by the froxel passes and the translucent surfaces + +struct FroxelSlices { + float near; + float far; + float extendedFar; + int sliceCount; + float distributionExponent; +}; + +float GetRegularFroxelSliceDepth(FroxelSlices slices, float slice) { + + float t = pow(clamp(slice / float(slices.sliceCount), 0.0, 1.0), slices.distributionExponent); + return slices.near * pow(slices.far / slices.near, t); + +} + +float GetFroxelSliceDepth(FroxelSlices slices, float slice) { + + float lastSlice = float(slices.sliceCount - 1); + if (slice <= lastSlice) + return GetRegularFroxelSliceDepth(slices, slice); + + float lastSliceStart = GetRegularFroxelSliceDepth(slices, lastSlice); + return mix(lastSliceStart, max(slices.extendedFar, slices.far), slice - lastSlice); + +} + +float GetFroxelSlice(FroxelSlices slices, float viewDepth) { + + float lastSlice = float(slices.sliceCount - 1); + float lastSliceStart = GetRegularFroxelSliceDepth(slices, lastSlice); + if (viewDepth >= lastSliceStart) { + float lastSliceEnd = max(slices.extendedFar, slices.far); + return lastSlice + clamp((viewDepth - lastSliceStart) / max(lastSliceEnd - lastSliceStart, 1e-6), 0.0, 1.0); + } + + float t = log(max(viewDepth, slices.near) / slices.near) / log(slices.far / slices.near); + return pow(t, 1.0 / slices.distributionExponent) * float(slices.sliceCount); + +} diff --git a/data/shader/volumetric/lightCulling.csh b/data/shader/volumetric/lightCulling.csh deleted file mode 100644 index e2928118f..000000000 --- a/data/shader/volumetric/lightCulling.csh +++ /dev/null @@ -1,120 +0,0 @@ -layout (local_size_x = 16, local_size_y = 16) in; - -#include <../deferred/lightCulling.hsh> - -#include <../structures.hsh> -#include <../shadow.hsh> -#include <../globals.hsh> - -#include <../common/convert.hsh> -#include <../common/utility.hsh> - -layout(set = 3, binding = 1) uniform sampler2D depthTexture; - -layout (std430, set = 3, binding = 8) buffer VolumetricLights { - VolumetricLight volumetricLights[]; -}; - -layout(std430, set = 3, binding = 10) buffer LightIndicesBuffer { - int lightIndices[]; -}; - -layout(push_constant) uniform constants { - int lightCount; -} pushConstants; - -const int lightCountPerTile = 63; -const int groupSize = int(gl_WorkGroupSize.x * gl_WorkGroupSize.y); - -// Results in 32 * 128 = 4096 possible lights in the tile -shared int sharedLightIndices[lightCountPerTile]; -shared int sharedLightCount; -shared uint sharedDepthMax; - -int GetLightIndicesOffset() { - - int groupOffset = int(gl_WorkGroupID.x + gl_WorkGroupID.y * gl_NumWorkGroups.x); - return groupOffset * (lightCountPerTile + 1); - -} - -void main() { - - ivec2 resolution = textureSize(depthTexture, 0); - ivec2 pixel = ivec2(gl_GlobalInvocationID.xy); - - vec2 texCoord = (vec2(pixel) + 0.5) / vec2(resolution); - - float depth = texelFetch(depthTexture, pixel, 0).r; - float viewDepth = ConvertDepthToViewSpaceDepth(depth); - - if (gl_LocalInvocationIndex == 0u) { - sharedDepthMax = floatBitsToUint(depth); - sharedLightCount = 0; - } - - barrier(); - - atomicMax(sharedDepthMax, floatBitsToUint(depth)); - - barrier(); - - float depthMin = 0.0; - float depthMax = ConvertDepthToViewSpaceDepth(uintBitsToFloat(sharedDepthMax)); - - vec3 frustumCorners[8]; - GetFrustumCorners(frustumCorners, resolution, 0.0, uintBitsToFloat(sharedDepthMax)); - - Plane frustumPlanes[4]; - GetFrustumPlanes(frustumPlanes, frustumCorners); - - AABB frustumAABB = CalculateAABB(frustumCorners); - - vec3 viewPos = ConvertDepthToViewSpace(depth, texCoord); - - int localOffset = int(gl_LocalInvocationIndex); - int lightIdx = 0; - for (int i = localOffset; i < pushConstants.lightCount && lightIdx < lightCountPerTile; i += groupSize) { - bool visible = true; - - VolumetricLight light = volumetricLights[i]; - float radius = light.direction.w; - - uint lightType = floatBitsToUint(light.color.a); - Sphere sphere; - - // Remember: Forward is in -z direction - if (lightType == POINT_LIGHT) { - sphere.center = light.location.xyz; - sphere.radius = radius; - } - else if (lightType == SPOT_LIGHT) { - sphere = CalculateSphereFromSpotLight(light.location, light.direction, radius); - } - - visible = visible && SphereAABBIntersection(sphere, frustumAABB); - if (visible) { - visible = SphereFrustumIntersection(sphere, frustumPlanes); - } - - if (visible) { - lightIdx = atomicAdd(sharedLightCount, 1); - - if (lightIdx < lightCountPerTile) - sharedLightIndices[lightIdx] = i; - } - } - - barrier(); - - int lightCount = min(lightCountPerTile, sharedLightCount); - int lightIndicesOffset = GetLightIndicesOffset(); - for (int i = localOffset; i < lightCount; i += groupSize) { - lightIndices[i + lightIndicesOffset + 1] = sharedLightIndices[i]; - } - - if (gl_LocalInvocationIndex == 0u) { - lightIndices[lightIndicesOffset] = lightCount; - } - -} \ No newline at end of file diff --git a/data/shader/volumetric/volumetric.csh b/data/shader/volumetric/volumetric.csh deleted file mode 100644 index dc39ed199..000000000 --- a/data/shader/volumetric/volumetric.csh +++ /dev/null @@ -1,522 +0,0 @@ -#extension GL_EXT_nonuniform_qualifier : require - -layout (local_size_x = 16, local_size_y = 16) in; - -#include <../globals.hsh> -#include <../structures.hsh> -#include <../common/ign.hsh> -#include <../common/convert.hsh> -#include <../common/stencil.hsh> -#include <../common/utility.hsh> -#include <../common/random.hsh> -#include <../clouds/shadow.hsh> -#include <../common/bluenoise.hsh> - -#include - -layout(set = 3, binding = 0, rgba16f) writeonly uniform image2D volumetricImage; -layout(set = 3, binding = 1) uniform sampler2D depthTexture; -layout(set = 3, binding = 2) uniform sampler2D cloudMap; -layout(set = 3, binding = 3) uniform sampler2D oceanDepthTexture; -layout(set = 3, binding = 4) uniform usampler2D oceanStencilTexture; -layout(set = 3, binding = 5) uniform sampler2D volumetricCloudTexture; -layout(set = 3, binding = 6) uniform sampler shadowSampler; - -layout(std140, set = 3, binding = 7) uniform UniformBuffer { - int sampleCount; - float intensity; - int fogEnabled; - float oceanHeight; - int lightCount; - int offsetX; - int offsetY; - int directionalLightCount; - vec4 planetCenterAndRadius; - Fog fog; - CloudShadow cloudShadow; -} uniforms; - -layout (std430, set = 3, binding = 8) buffer VolumetricLights { - VolumetricLight volumetricLights[]; -}; - -layout (std430, set = 3, binding = 9) buffer VolumetricShadows { - Shadow volumetricShadows[]; -}; - -layout(std430, set = 3, binding = 10) buffer LightIndicesBuffer { - int lightIndices[]; -}; - -layout(set = 3, binding = 11) uniform texture2DArray cascadeMaps[8]; -layout(set = 3, binding = 19) uniform textureCube cubeMaps[8]; - -const int lightCountPerTile = 63; - -shared uint sharedLightIndices[64]; -shared int sharedLightIndicesCount; - -vec4 ComputeVolumetricDirectionalLights(vec3 fragPos, float startDepth, vec2 texCoords); -vec4 ComputeVolumetricPunctualLights(uint lightType, vec3 fragPos, float startDepth, vec2 texCoords); -float GetShadowFactorDirectionalLight(int lightIdx, int shadowIdx, uint lightType, bool isMain, vec3 currentPosition); -float GetShadowFactorPunctualLight(int lightIdx, int shadowIdx, uint lightType, bool isMain, vec3 currentPosition); - -int GetLightIndicesOffset() { - - int groupOffset = int(gl_WorkGroupID.x + gl_WorkGroupID.y * gl_NumWorkGroups.x); - return groupOffset * (lightCountPerTile + 1); - -} - -void LoadLightTypeData(uint requestedLightType) { - - barrier(); - - int groupSize = int(gl_WorkGroupSize.x * gl_WorkGroupSize.y); - int localOffset = int(gl_LocalInvocationIndex); - - if (localOffset == 0) { - sharedLightIndicesCount = 0; - } - - barrier(); - - int groupOffset = GetLightIndicesOffset(); - int lightCount = min(lightCountPerTile, lightIndices[groupOffset]); - - int lastIdx = 0; - for (int i = localOffset; i < lightCount; i += groupSize) { - uint lightIdx = lightIndices[groupOffset + i + 1]; - uint lightType = floatBitsToUint(volumetricLights[lightIdx].color.a); - if (requestedLightType != lightType) - continue; - - int idx = atomicAdd(sharedLightIndicesCount, 1); - if (idx < lightCountPerTile) - sharedLightIndices[idx] = lightIdx; - } - - barrier(); - - if (localOffset == 0) { - sharedLightIndicesCount = min(lightCount, sharedLightIndicesCount); - } - - barrier(); - -} - -void main() { - - ivec2 pixel = ivec2(gl_GlobalInvocationID); - if (pixel.x > imageSize(volumetricImage).x || - pixel.y > imageSize(volumetricImage).y) - return; - - vec2 texCoord = (vec2(pixel) + 0.5) / vec2(imageSize(volumetricImage)); - - float depth = textureLod(depthTexture, texCoord, 0.0).r; - vec3 pixelPos = ConvertDepthToViewSpace(depth, texCoord); - - vec3 endPos = pixelPos; - - float startDepth = 0.0; -#ifdef OCEAN - StencilFeatures features = DecodeStencilFeatures(textureLod(oceanStencilTexture, texCoord, 0.0).r); - - float oceanDepth = textureLod(oceanDepthTexture, texCoord, 0.0).r; - vec3 oceanPos = ConvertDepthToViewSpace(oceanDepth, texCoord); - - // We could use stencil features here, but they are unrealiable. Next option is to just apply - // simpl fog to the refraction texture when under water - if (oceanDepth < depth && !features.underWaterPixel) { - endPos = oceanPos; - } -#endif - - bool validPixel = pixel.x < imageSize(volumetricImage).x && - pixel.y < imageSize(volumetricImage).y; - - vec4 radiance = vec4(0.0); - radiance = ComputeVolumetricDirectionalLights(endPos, startDepth, texCoord); - -#ifdef LOCAL_LIGHTS - LoadLightTypeData(POINT_LIGHT); - if (sharedLightIndicesCount > 0) - radiance.rgb += ComputeVolumetricPunctualLights(POINT_LIGHT, endPos, startDepth, texCoord).rgb; - - LoadLightTypeData(SPOT_LIGHT); - if (sharedLightIndicesCount > 0) - radiance.rgb += ComputeVolumetricPunctualLights(SPOT_LIGHT, endPos, startDepth, texCoord).rgb; -#endif - - if (validPixel) - imageStore(volumetricImage, pixel, radiance); - -} - -vec4 ComputeVolumetricDirectionalLights(vec3 fragPos, float startDepth, vec2 texCoords) { - - vec2 resolution = vec2(imageSize(volumetricImage)); - vec3 viewPosition = vec3(globalData.ivMatrix * vec4(fragPos, 1.0)); - - // We compute this in view space - vec3 rayVector = fragPos; - float rayLength = max(length(rayVector) - startDepth, 0.0); - vec3 rayDirection = rayVector / rayLength; - float stepLength = rayLength / float(uniforms.sampleCount); - vec3 stepVector = rayDirection * stepLength; - - vec3 foginess = vec3(0.0); - vec4 extinction = vec4(1.0); - vec4 extinctionWithClouds = vec4(1.0); - - vec2 interleavedTexCoords = (0.5 * texCoords + 0.5) * resolution; - - float noiseOffset = GetInterleavedGradientNoise(interleavedTexCoords); - vec3 currentPosition = stepVector * (noiseOffset + startDepth); - -#ifdef CLOUDS - bool receivedCloudExtinction = false; - float cloudExtinction = min(textureLod(volumetricCloudTexture, texCoords, 0.0).a, 1.0); -#endif - - for (int i = 0; i < uniforms.sampleCount; i++) { - - float t0 = float(i) / float(uniforms.sampleCount); - float t1 = float(i + 1) / float(uniforms.sampleCount); - - t0 = t0 * t0; - t1 = t1 * t1; - - float delta = t1 - t0; - float t = t0 + delta * noiseOffset; - - currentPosition = rayDirection * t * rayLength + startDepth; - stepLength = delta * rayLength; - - vec3 worldPosition = vec3(globalData.ivMatrix * vec4(currentPosition, 1.0)); - - vec3 lightScattering = vec3(0.0); - vec3 lightAmbient = vec3(1.0); - - // First all directional lights - for(int j = 0; j < uniforms.directionalLightCount; j++) { - VolumetricLight light = volumetricLights[j]; - - uint lightType = floatBitsToUint(light.color.a); - - bool isMain = j == 0 ? true : false; - float shadowValue = GetShadowFactorDirectionalLight(j, light.shadowIdx, lightType, isMain, currentPosition); - - vec3 lightPosition = currentPosition - 100000.0 * light.direction.xyz; - lightPosition = vec3(globalData.ivMatrix * vec4(lightPosition, 1.0)); - float extinctionToLight = ComputeVolumetricFog(uniforms.fog, worldPosition, lightPosition); - float NdotL = dot(normalize(rayDirection), normalize(light.direction.xyz)); - - float phaseFunction = uniforms.fogEnabled > 0 ? - ComputeScattering(uniforms.fog.scatteringAnisotropy, NdotL) : 1.0; - - lightScattering += shadowValue * phaseFunction * light.color.rgb * light.intensity * extinctionToLight; - } - -#ifdef CLOUDS - vec3 planetCenter = uniforms.planetCenterAndRadius.xyz; - float cloudInnerRadius = uniforms.planetCenterAndRadius.w; - - float distToPlanetCenter = distance(worldPosition, planetCenter); -#endif - - float density = uniforms.fog.density * GetVolumetricFogDensity(uniforms.fog, worldPosition); - - vec3 scatteringCoefficient = uniforms.fog.scatteringFactor * - uniforms.fog.extinctionCoefficients.rgb * density; - vec4 extinctionCoefficient = uniforms.fog.extinctionFactor * - uniforms.fog.extinctionCoefficients * density; - - vec4 clampedExtinction = max(extinctionCoefficient, 0.0000001); - vec4 stepExtinction = exp(-extinctionCoefficient * stepLength); - - vec3 stepScattering = scatteringCoefficient * (lightScattering + vec3(uniforms.fog.ambientFactor) * lightAmbient); - - vec3 luminanceIntegral = (stepScattering - stepScattering * stepExtinction.rgb) / clampedExtinction.rgb; -#ifdef CLOUDS - foginess += luminanceIntegral * extinctionWithClouds.rgb; - - if (distToPlanetCenter > cloudInnerRadius && !receivedCloudExtinction) { - extinctionWithClouds *= uniforms.fogEnabled > 0 ? stepExtinction * cloudExtinction : vec4(1.0); - receivedCloudExtinction = true; - } - else { - extinctionWithClouds *= uniforms.fogEnabled > 0 ? stepExtinction : vec4(1.0); - } -#else - foginess += luminanceIntegral * extinction.rgb; -#endif - - extinction *= uniforms.fogEnabled > 0 ? stepExtinction : vec4(1.0); - - currentPosition += stepVector; - - } - - return vec4(foginess * uniforms.intensity, extinction.a); - -} - -vec4 ComputeVolumetricPunctualLights(uint lightType, vec3 fragPos, float startDepth, vec2 texCoords) { - - vec2 resolution = vec2(imageSize(volumetricImage)); - vec3 viewPosition = vec3(globalData.ivMatrix * vec4(fragPos, 1.0)); - - // We compute this in view space - vec3 rayVector = fragPos; - float rayLength = clamp(length(rayVector) - startDepth, 0.0, 100.0); - vec3 rayDirection = normalize(rayVector); - float stepLength = rayLength / float(uniforms.sampleCount); - vec3 stepVector = rayDirection * stepLength; - - vec3 foginess = vec3(0.0); - vec4 extinction = vec4(1.0); - vec4 extinctionWithClouds = vec4(1.0); - - vec2 interleavedTexCoords = (0.5 * texCoords + 0.5) * resolution; - - float noiseOffset = GetInterleavedGradientNoise(interleavedTexCoords); - vec3 currentPosition = stepVector * (noiseOffset + startDepth); - -#ifdef CLOUDS - bool receivedCloudExtinction = false; - float cloudExtinction = min(textureLod(volumetricCloudTexture, texCoords, 0.0).a, 1.0); -#endif - - for (int i = 0; i < uniforms.sampleCount; i++) { - - float t0 = float(i) / float(uniforms.sampleCount); - float t1 = float(i + 1) / float(uniforms.sampleCount); - - t0 = t0 * t0; - t1 = t1 * t1; - - float delta = t1 - t0; - float t = t0 + delta * noiseOffset; - - //currentPosition = rayDirection * t * rayLength + startDepth; - //stepLength = delta * rayLength; - - vec3 worldPosition = vec3(globalData.ivMatrix * vec4(currentPosition, 1.0)); - - vec3 lightScattering = vec3(0.0); - - // Then all punctual lights - for(int j = 0; j < sharedLightIndicesCount; j++) { - int lightIdx = int(sharedLightIndices[j]); - VolumetricLight light = volumetricLights[lightIdx]; - - float NdotL = 1.0; - float attenuation = 1.0; - float sqrDistance = 1.0; - - float shadowValue = 1.0; - - float radius = light.direction.w; - if (lightType == POINT_LIGHT) { - vec3 pointToLight = light.location.xyz - currentPosition; - sqrDistance = max(0.0, dot(pointToLight, pointToLight)); - - attenuation = saturate(1.0 - pow(sqrDistance / (radius * radius), 4.0)); - if (attenuation == 0.0) - continue; - - NdotL = dot(-normalize(light.location.xyz), rayDirection); - shadowValue = GetShadowFactorPunctualLight(lightIdx, light.shadowIdx, POINT_LIGHT, false, currentPosition); - } - else if (lightType == SPOT_LIGHT) { - vec3 pointToLight = light.location.xyz - currentPosition; - sqrDistance = dot(pointToLight, pointToLight); - - vec3 L = pointToLight / sqrt(sqrDistance); - - float strength = dot(L, normalize(-light.direction.xyz)); - float angleAttenuation = saturate(strength * light.specific0 + light.specific1); - float distAttenuation = saturate(1.0 - pow(sqrDistance / (radius * radius), 4.0)); - if (angleAttenuation == 0.0 || distAttenuation == 0.0) - continue; - - NdotL = dot(-normalize(light.location.xyz), rayDirection); - attenuation = min(distAttenuation * sqr(angleAttenuation), 1.0); - shadowValue = GetShadowFactorPunctualLight(lightIdx, light.shadowIdx, SPOT_LIGHT, false, currentPosition); - } - - // No shadows for now - //shadowValue = 1.0; - - float phaseFunction = uniforms.fogEnabled > 0 ? - ComputeScattering(uniforms.fog.scatteringAnisotropy, NdotL) : 1.0; - - lightScattering += phaseFunction * shadowValue * light.color.rgb * attenuation * light.intensity / max(sqrDistance, 0.1); - } - -#ifdef CLOUDS - vec3 planetCenter = uniforms.planetCenterAndRadius.xyz; - float cloudInnerRadius = uniforms.planetCenterAndRadius.w; - - float distToPlanetCenter = distance(worldPosition, planetCenter); -#endif - - float density = uniforms.fog.density * GetVolumetricFogDensity(uniforms.fog, worldPosition); - - vec3 scatteringCoefficient = uniforms.fog.scatteringFactor * - uniforms.fog.extinctionCoefficients.rgb * density; - vec4 extinctionCoefficient = uniforms.fog.extinctionFactor * - uniforms.fog.extinctionCoefficients * density; - - vec4 clampedExtinction = max(extinctionCoefficient, 0.0000001); - vec4 stepExtinction = exp(-extinctionCoefficient * stepLength); - - vec3 stepScattering = scatteringCoefficient * lightScattering; - - vec3 luminanceIntegral = (stepScattering - stepScattering * stepExtinction.rgb) / clampedExtinction.rgb; -#ifdef CLOUDS - foginess += luminanceIntegral * extinctionWithClouds.rgb; - - if (distToPlanetCenter > cloudInnerRadius && !receivedCloudExtinction) { - extinctionWithClouds *= uniforms.fogEnabled > 0 ? stepExtinction * cloudExtinction : vec4(1.0); - receivedCloudExtinction = true; - } - else { - extinctionWithClouds *= uniforms.fogEnabled > 0 ? stepExtinction : vec4(1.0); - } -#else - foginess += luminanceIntegral * extinction.rgb; -#endif - - extinction *= uniforms.fogEnabled > 0 ? stepExtinction : vec4(1.0); - - currentPosition += stepVector; - - } - - return vec4(foginess * uniforms.intensity, extinction.a); - -} - -float GetShadowFactorDirectionalLight(int lightIdx, int shadowIdx, uint lightType, bool isMain, vec3 currentPosition) { - - float dist = -currentPosition.z; - -#ifndef AE_BINDLESS - int mapIdx = lightIdx; -#else - int mapIdx = volumetricShadows[shadowIdx].mapIdx; -#endif - - if (shadowIdx < 0 || dist > volumetricShadows[shadowIdx].distance || mapIdx < 0) - return 1.0; - - float shadowValue = 1.0; - - - int cascadeIndex = 0; - cascadeIndex = dist >= volumetricShadows[shadowIdx].cascades[0].distance ? 1 : cascadeIndex; - cascadeIndex = dist >= volumetricShadows[shadowIdx].cascades[1].distance ? 2 : cascadeIndex; - cascadeIndex = dist >= volumetricShadows[shadowIdx].cascades[2].distance ? 3 : cascadeIndex; - cascadeIndex = dist >= volumetricShadows[shadowIdx].cascades[3].distance ? 4 : cascadeIndex; - cascadeIndex = dist >= volumetricShadows[shadowIdx].cascades[4].distance ? 5 : cascadeIndex; - - cascadeIndex = min(volumetricShadows[shadowIdx].cascadeCount - 1, cascadeIndex); - - mat3x4 cascadeMatrix = volumetricShadows[shadowIdx].cascades[0].cascadeSpace; - cascadeMatrix = cascadeIndex > 0 ? volumetricShadows[shadowIdx].cascades[1].cascadeSpace : cascadeMatrix; - cascadeMatrix = cascadeIndex > 1 ? volumetricShadows[shadowIdx].cascades[2].cascadeSpace : cascadeMatrix; - cascadeMatrix = cascadeIndex > 2 ? volumetricShadows[shadowIdx].cascades[3].cascadeSpace : cascadeMatrix; - cascadeMatrix = cascadeIndex > 3 ? volumetricShadows[shadowIdx].cascades[4].cascadeSpace : cascadeMatrix; - cascadeMatrix = cascadeIndex > 4 ? volumetricShadows[shadowIdx].cascades[5].cascadeSpace : cascadeMatrix; - - float positionLength = dist; - float positionRatio = positionLength / volumetricShadows[shadowIdx].distance; - vec3 shadowPosition = positionRatio <= 1.0 ? currentPosition : currentPosition / positionRatio; - vec4 cascadeSpace = mat4(transpose(cascadeMatrix)) * vec4(currentPosition, 1.0); - cascadeSpace.xyz /= cascadeSpace.w; - - cascadeSpace.xy = cascadeSpace.xy * 0.5 + 0.5; - -#ifdef AE_BINDLESS - shadowValue = texture(sampler2DArrayShadow(bindlessTextureArrays[nonuniformEXT(mapIdx)], shadowSampler), - vec4(cascadeSpace.xy, cascadeIndex, cascadeSpace.z)); -#else - shadowValue = texture(sampler2DArrayShadow(cascadeMaps[nonuniformEXT(mapIdx)], shadowSampler), - vec4(cascadeSpace.xy, cascadeIndex, cascadeSpace.z)); -#endif - - vec3 worldPosition = vec3(globalData.ivMatrix * vec4(currentPosition, 1.0)); - -#ifdef CLOUD_SHADOWS - if (isMain) { - vec3 planetCenter = uniforms.planetCenterAndRadius.xyz; - float cloudInnerRadius = uniforms.planetCenterAndRadius.w; - float distToPlanetCenter = distance(worldPosition, planetCenter); - float cloudShadowValue = CalculateCloudShadow(currentPosition, uniforms.cloudShadow, cloudMap); - cloudShadowValue = distToPlanetCenter < cloudInnerRadius ? cloudShadowValue : 1.0; - shadowValue = min(shadowValue, cloudShadowValue); - } -#endif - - return min(shadowValue, 1.0); - -} - -float GetShadowFactorPunctualLight(int lightIdx, int shadowIdx, uint lightType, bool isMain, vec3 currentPosition) { - - float dist = -currentPosition.z; - -#ifndef AE_BINDLESS - int mapIdx = lightIdx; -#else - int mapIdx = volumetricShadows[shadowIdx].mapIdx; -#endif - - if (shadowIdx < 0 || dist > volumetricShadows[shadowIdx].distance || mapIdx < 0) - return 1.0; - - float shadowValue = 1.0; - if (lightType == POINT_LIGHT) { -#ifdef AE_BINDLESS - mat4 projectionMatrix; - projectionMatrix[0] = volumetricShadows[shadowIdx].cascades[1].cascadeSpace[0]; - projectionMatrix[1] = volumetricShadows[shadowIdx].cascades[1].cascadeSpace[1]; - projectionMatrix[2] = volumetricShadows[shadowIdx].cascades[1].cascadeSpace[2]; - projectionMatrix[3] = volumetricShadows[shadowIdx].cascades[2].cascadeSpace[0]; - - vec4 shadowCoords = mat4(transpose(volumetricShadows[shadowIdx].cascades[0].cascadeSpace)) * vec4(currentPosition, 1.0); - shadowCoords.y *= -1.0; - vec4 absPosition = abs(shadowCoords); - float depth = -max(absPosition.x, max(absPosition.y, absPosition.z)); - vec4 clip = projectionMatrix * vec4(0.0, 0.0, depth, 1.0); - depth = clip.z / clip.w; - - shadowValue = clamp(texture(samplerCubeShadow(bindlessCubemaps[nonuniformEXT(mapIdx)], shadowSampler), - vec4(shadowCoords.xyz , depth - 0.0001)), 0.0, 1.0); -#endif - } - else if (lightType == SPOT_LIGHT) { -#ifdef AE_BINDLESS - mat4 shadowMatrix; - shadowMatrix[0] = volumetricShadows[shadowIdx].cascades[0].cascadeSpace[0]; - shadowMatrix[1] = volumetricShadows[shadowIdx].cascades[0].cascadeSpace[1]; - shadowMatrix[2] = volumetricShadows[shadowIdx].cascades[0].cascadeSpace[2]; - shadowMatrix[3] = volumetricShadows[shadowIdx].cascades[1].cascadeSpace[0]; - - vec4 cascadeSpace = shadowMatrix * vec4(currentPosition, 1.0); - cascadeSpace.xyz /= cascadeSpace.w; - - cascadeSpace.xy = cascadeSpace.xy * 0.5 + 0.5; - - shadowValue = texture(sampler2DArrayShadow(bindlessTextureArrays[nonuniformEXT(mapIdx)], shadowSampler), - vec4(cascadeSpace.xy, 0.0, cascadeSpace.z)); -#endif - } - - return min(shadowValue, 1.0); - -} \ No newline at end of file diff --git a/data/shader/volumetric/volumetric.hsh b/data/shader/volumetric/volumetric.hsh index 8aec38c03..b29e50a7b 100644 --- a/data/shader/volumetric/volumetric.hsh +++ b/data/shader/volumetric/volumetric.hsh @@ -1,4 +1,3 @@ -#include #include <../globals.hsh> vec2 IntersectSphere(vec3 origin, vec3 direction, vec3 pos, float radius) { @@ -24,7 +23,7 @@ vec2 IntersectSphere(vec3 origin, vec3 direction, vec3 pos, float radius) { return vec2(minDist, maxDist); } -vec3 ApplyVolumetrics(Fog fog, vec3 inputColor, vec4 volumetricFog, vec4 volumetricClouds, +vec3 ApplyVolumetrics(vec3 inputColor, vec4 volumetricFog, vec4 volumetricClouds, vec3 worldViewDirection, vec3 planetCenter, float innerCloudRadius) { vec2 intersectDists = IntersectSphere(globalData.cameraLocation.xyz, worldViewDirection, @@ -39,7 +38,7 @@ vec3 ApplyVolumetrics(Fog fog, vec3 inputColor, vec4 volumetricFog, vec4 volumet #endif #ifdef FOG - vec3 outputColor = fog.density > 0.0 ? inputColor * fogExtinction + volumetricFog.rgb : inputColor; + vec3 outputColor = inputColor * fogExtinction + volumetricFog.rgb; #else vec3 outputColor = inputColor; #endif diff --git a/data/shader/volumetric/volumetricLights.hsh b/data/shader/volumetric/volumetricLights.hsh new file mode 100644 index 000000000..d513bf0d4 --- /dev/null +++ b/data/shader/volumetric/volumetricLights.hsh @@ -0,0 +1,241 @@ +#include <../globals.hsh> +#include <../structures.hsh> +#include <../common/convert.hsh> +#include <../common/utility.hsh> +#include <../clouds/shadow.hsh> + +#include + +layout(set = 3, binding = 2) uniform sampler2D cloudMap; +layout(set = 3, binding = 5) uniform sampler2D volumetricCloudTexture; +layout(set = 3, binding = 6) uniform sampler shadowSampler; +layout(set = 3, binding = 12) uniform sampler shadowDepthSampler; + +layout(std140, set = 3, binding = 7) uniform UniformBuffer { + float intensity; + int directionalLightCount; + int padding0; + int padding1; + vec4 planetCenterAndRadius; + Fog fog; + CloudShadow cloudShadow; +} uniforms; + +layout (std430, set = 3, binding = 8) buffer VolumetricLights { + VolumetricLight volumetricLights[]; +}; + +layout (std430, set = 3, binding = 9) buffer VolumetricShadows { + Shadow volumetricShadows[]; +}; + +layout(std430, set = 3, binding = 10) buffer LightIndicesBuffer { + int lightIndices[]; +}; + +const int lightCountPerTile = 63; + +shared uint sharedLightIndices[64]; +shared int sharedLightIndicesCount; + +shared VolumetricLight sharedLights[64]; +shared int sharedShadowMapIdx[64]; +shared float sharedShadowDistance[64]; +shared mat4 sharedShadowMatrix[64]; +shared vec4 sharedShadowProjection[64]; + +// Distance in world units over which the shadow fades in behind an occluder +const float shadowFadeDistance = 0.1; + +float GetShadowFactorDirectionalLight(int lightIdx, int shadowIdx, uint lightType, bool isMain, vec3 currentPosition); +float GetShadowFactorPunctualLight(int sharedIdx, uint lightType, vec3 currentPosition); + +// Exponential depth test of a gathered 2x2 footprint, filtered bilinearly to avoid hard shadow edges in the fog +float GetSoftShadow(vec4 occluderDistances, float receiverDistance, vec2 texelPosition) { + + vec4 shadows = exp(min(occluderDistances - receiverDistance, 0.0) / shadowFadeDistance); + + vec2 weight = fract(texelPosition - 0.5); + float top = mix(shadows.w, shadows.z, weight.x); + float bottom = mix(shadows.x, shadows.y, weight.x); + return mix(top, bottom, weight.y); + +} + +int GetLightIndicesOffset() { + + int groupOffset = int(gl_WorkGroupID.x + (gl_WorkGroupID.y + gl_WorkGroupID.z * gl_NumWorkGroups.y) * gl_NumWorkGroups.x); + return groupOffset * (lightCountPerTile + 1); + +} + +void LoadLightTypeData(uint requestedLightType) { + + barrier(); + + int groupSize = int(gl_WorkGroupSize.x * gl_WorkGroupSize.y * gl_WorkGroupSize.z); + int localOffset = int(gl_LocalInvocationIndex); + + if (localOffset == 0) { + sharedLightIndicesCount = 0; + } + + barrier(); + + int groupOffset = GetLightIndicesOffset(); + int lightCount = min(lightCountPerTile, lightIndices[groupOffset]); + + for (int i = localOffset; i < lightCount; i += groupSize) { + uint lightIdx = lightIndices[groupOffset + i + 1]; + uint lightType = floatBitsToUint(volumetricLights[lightIdx].color.a); + if (requestedLightType != lightType) + continue; + + int idx = atomicAdd(sharedLightIndicesCount, 1); + if (idx < lightCountPerTile) + sharedLightIndices[idx] = lightIdx; + } + + barrier(); + + if (localOffset == 0) { + sharedLightIndicesCount = min(lightCount, sharedLightIndicesCount); + } + + barrier(); + + for (int i = localOffset; i < sharedLightIndicesCount; i += groupSize) { + int lightIdx = int(sharedLightIndices[i]); + VolumetricLight light = volumetricLights[lightIdx]; + sharedLights[i] = light; + + int shadowIdx = light.shadowIdx; + int mapIdx = -1; + if (shadowIdx >= 0) { + mapIdx = volumetricShadows[shadowIdx].mapIdx; + sharedShadowDistance[i] = volumetricShadows[shadowIdx].distance; + } + sharedShadowMapIdx[i] = mapIdx; + + if (mapIdx < 0) + continue; + + if (requestedLightType == POINT_LIGHT) { + sharedShadowMatrix[i] = mat4(transpose(volumetricShadows[shadowIdx].cascades[0].cascadeSpace)); + vec4 projection2 = volumetricShadows[shadowIdx].cascades[1].cascadeSpace[2]; + vec4 projection3 = volumetricShadows[shadowIdx].cascades[2].cascadeSpace[0]; + sharedShadowProjection[i] = vec4(projection2.z, projection3.z, projection2.w, projection3.w); + } + else if (requestedLightType == SPOT_LIGHT) { + mat4 shadowMatrix; + shadowMatrix[0] = volumetricShadows[shadowIdx].cascades[0].cascadeSpace[0]; + shadowMatrix[1] = volumetricShadows[shadowIdx].cascades[0].cascadeSpace[1]; + shadowMatrix[2] = volumetricShadows[shadowIdx].cascades[0].cascadeSpace[2]; + shadowMatrix[3] = volumetricShadows[shadowIdx].cascades[1].cascadeSpace[0]; + sharedShadowMatrix[i] = shadowMatrix; + + // Linearizes the shadow map depth: distance = b / (depth + a) + mat4 shadowRows = transpose(shadowMatrix); + float a = -dot(shadowRows[2].xyz, shadowRows[3].xyz) / dot(shadowRows[3].xyz, shadowRows[3].xyz); + float b = shadowRows[2].w + a * shadowRows[3].w; + sharedShadowProjection[i] = vec4(a, b, 0.0, 0.0); + } + } + + barrier(); + +} + +float GetShadowFactorDirectionalLight(int lightIdx, int shadowIdx, uint lightType, bool isMain, vec3 currentPosition) { + + float dist = -currentPosition.z; + + if (shadowIdx < 0) + return 1.0; + + int mapIdx = volumetricShadows[shadowIdx].mapIdx; + + if (dist > volumetricShadows[shadowIdx].distance || mapIdx < 0) + return 1.0; + + float shadowValue = 1.0; + + int cascadeIndex = 0; + cascadeIndex = dist >= volumetricShadows[shadowIdx].cascades[0].distance ? 1 : cascadeIndex; + cascadeIndex = dist >= volumetricShadows[shadowIdx].cascades[1].distance ? 2 : cascadeIndex; + cascadeIndex = dist >= volumetricShadows[shadowIdx].cascades[2].distance ? 3 : cascadeIndex; + cascadeIndex = dist >= volumetricShadows[shadowIdx].cascades[3].distance ? 4 : cascadeIndex; + cascadeIndex = dist >= volumetricShadows[shadowIdx].cascades[4].distance ? 5 : cascadeIndex; + + cascadeIndex = min(volumetricShadows[shadowIdx].cascadeCount - 1, cascadeIndex); + + mat3x4 cascadeMatrix = volumetricShadows[shadowIdx].cascades[max(cascadeIndex, 0)].cascadeSpace; + + vec4 cascadeSpace = mat4(transpose(cascadeMatrix)) * vec4(currentPosition, 1.0); + cascadeSpace.xyz /= cascadeSpace.w; + + cascadeSpace.xy = cascadeSpace.xy * 0.5 + 0.5; + + vec2 texelPosition = cascadeSpace.xy * vec2(textureSize(sampler2DArray(bindlessTextureArrays[nonuniformEXT(mapIdx)], shadowDepthSampler), 0).xy); + vec4 depths = textureGather(sampler2DArray(bindlessTextureArrays[nonuniformEXT(mapIdx)], shadowDepthSampler), + vec3(cascadeSpace.xy, cascadeIndex), 0); + + // The cascades are orthographic, the depth is linear + float depthToDistance = 1.0 / length(cascadeMatrix[2].xyz); + shadowValue = GetSoftShadow(depths * depthToDistance, cascadeSpace.z * depthToDistance, texelPosition); + + vec3 worldPosition = vec3(globalData.ivMatrix * vec4(currentPosition, 1.0)); + +#ifdef CLOUD_SHADOWS + if (isMain) { + vec3 planetCenter = uniforms.planetCenterAndRadius.xyz; + float cloudInnerRadius = uniforms.planetCenterAndRadius.w; + float distToPlanetCenter = distance(worldPosition, planetCenter); + float cloudShadowValue = CalculateCloudShadow(currentPosition, uniforms.cloudShadow, cloudMap); + cloudShadowValue = distToPlanetCenter < cloudInnerRadius ? cloudShadowValue : 1.0; + shadowValue = min(shadowValue, cloudShadowValue); + } +#endif + + return min(shadowValue, 1.0); + +} + +float GetShadowFactorPunctualLight(int sharedIdx, uint lightType, vec3 currentPosition) { + + float dist = -currentPosition.z; + + int mapIdx = sharedShadowMapIdx[sharedIdx]; + if (mapIdx < 0 || dist > sharedShadowDistance[sharedIdx]) + return 1.0; + + float shadowValue = 1.0; + if (lightType == POINT_LIGHT) { + vec4 shadowCoords = sharedShadowMatrix[sharedIdx] * vec4(currentPosition, 1.0); + shadowCoords.y *= -1.0; + vec4 absPosition = abs(shadowCoords); + float depth = -max(absPosition.x, max(absPosition.y, absPosition.z)); + vec4 projection = sharedShadowProjection[sharedIdx]; + depth = (projection.x * depth + projection.y) / (projection.z * depth + projection.w); + + shadowValue = clamp(texture(samplerCubeShadow(bindlessCubemaps[nonuniformEXT(mapIdx)], shadowSampler), + vec4(shadowCoords.xyz , depth - 0.0001)), 0.0, 1.0); + } + else if (lightType == SPOT_LIGHT) { + vec4 cascadeSpace = sharedShadowMatrix[sharedIdx] * vec4(currentPosition, 1.0); + float receiverDistance = cascadeSpace.w; + cascadeSpace.xyz /= cascadeSpace.w; + + cascadeSpace.xy = cascadeSpace.xy * 0.5 + 0.5; + + vec2 texelPosition = cascadeSpace.xy * vec2(textureSize(sampler2DArray(bindlessTextureArrays[nonuniformEXT(mapIdx)], shadowDepthSampler), 0).xy); + vec4 depths = textureGather(sampler2DArray(bindlessTextureArrays[nonuniformEXT(mapIdx)], shadowDepthSampler), + vec3(cascadeSpace.xy, 0.0), 0); + + vec4 projection = sharedShadowProjection[sharedIdx]; + shadowValue = GetSoftShadow(projection.y / (depths + projection.x), receiverDistance, texelPosition); + } + + return min(shadowValue, 1.0); + +} diff --git a/data/shader/volumetric/volumetricResolve.csh b/data/shader/volumetric/volumetricResolve.csh index e2b174a3f..4d0603109 100644 --- a/data/shader/volumetric/volumetricResolve.csh +++ b/data/shader/volumetric/volumetricResolve.csh @@ -3,11 +3,13 @@ #include <../common/utility.hsh> #include <../common/flatten.hsh> -#include #include layout (local_size_x = 8, local_size_y = 8) in; +// Needs the work group size +#include <../common/upsample.hsh> + layout(set = 3, binding = 0, rgba16f) uniform image2D resolveImage; layout(set = 3, binding = 1) uniform sampler2D lowResVolumetricTexture; layout(set = 3, binding = 2) uniform sampler2D lowResDepthTexture; @@ -18,13 +20,9 @@ layout(set = 3, binding = 3) uniform sampler2D lowResVolumetricCloudsTexture; #endif layout(set = 3, binding = 5) uniform UniformBuffer { - Fog fog; vec4 planetCenter; - vec4 mainLightColor; - vec4 mainLightDirection; int downsampled2x; int cloudsEnabled; - int fogEnabled; float innerCloudRadius; float planetRadius; float cloudDistanceLimit; @@ -35,20 +33,12 @@ shared float depths[36]; shared vec4 volumetrics[36]; shared vec4 clouds[36]; -const uint depthDataSize = (gl_WorkGroupSize.x / 2 + 2) * (gl_WorkGroupSize.y / 2 + 2); -const ivec2 unflattenedDepthDataSize = ivec2(gl_WorkGroupSize) / 2 + 2; - vec3 planetCenter = uniforms.planetCenter.xyz; void LoadGroupSharedData() { - ivec2 workGroupOffset = ivec2(gl_WorkGroupID) * ivec2(gl_WorkGroupSize) / 2 - ivec2(1); - - // We assume data size is smaller than gl_WorkGroupSize.x + gl_WorkGroupSize.y - if (gl_LocalInvocationIndex < depthDataSize) { - ivec2 offset = Unflatten2D(int(gl_LocalInvocationIndex), unflattenedDepthDataSize); - offset += workGroupOffset; - offset = clamp(offset, ivec2(0), textureSize(lowResDepthTexture, 0) - ivec2(1)); + ivec2 offset; + if (GetUpsampleTileTexel(textureSize(lowResDepthTexture, 0), offset)) { depths[gl_LocalInvocationIndex] = texelFetch(lowResDepthTexture, offset, 0).r; volumetrics[gl_LocalInvocationIndex] = texelFetch(lowResVolumetricTexture, offset, 0); #ifdef CLOUDS @@ -60,40 +50,6 @@ void LoadGroupSharedData() { } -const ivec2 offsets[9] = ivec2[9]( - ivec2(-1, -1), - ivec2(0, -1), - ivec2(1, -1), - ivec2(-1, 0), - ivec2(0, 0), - ivec2(1, 0), - ivec2(-1, 1), - ivec2(0, 1), - ivec2(1, 1) -); - -const ivec2 pixelOffsets[4] = ivec2[4]( - ivec2(0, 0), - ivec2(1, 0), - ivec2(0, 1), - ivec2(1, 1) -); - -int NearestDepth(float referenceDepth, float[9] depthVec) { - - int idx = 4; - float nearest = distance(referenceDepth, depthVec[4]); - for (int i = 0; i < 9; i++) { - float dist = distance(referenceDepth, depthVec[i]); - if (dist < nearest) { - nearest = dist; - idx = i; - } - } - return idx; - -} - void Upsample2x(float referenceDepth, vec2 texCoord, out vec4 volumetric, out vec4 volumetricClouds) { ivec2 pixel = ivec2(gl_LocalInvocationID) / 2 + ivec2(1); @@ -162,8 +118,8 @@ void main() { if (uniforms.downsampled2x > 0) LoadGroupSharedData(); ivec2 pixel = ivec2(gl_GlobalInvocationID); - if (pixel.x > imageSize(resolveImage).x || - pixel.y > imageSize(resolveImage).y) + if (pixel.x >= imageSize(resolveImage).x || + pixel.y >= imageSize(resolveImage).y) return; vec2 texCoord = (vec2(pixel) + 0.5) / vec2(imageSize(resolveImage)); @@ -188,28 +144,7 @@ void main() { vec3 resolve = imageLoad(resolveImage, pixel).rgb; -#ifndef RAYMARCHED_FOG - float LdotV = dot(worldDirection, normalize(uniforms.mainLightDirection.xyz)); - float phaseFunction = ComputeScattering(uniforms.fog.scatteringAnisotropy, LdotV); - - vec3 worldPosition = vec3(globalData.ivMatrix * vec4(viewPosition, 1.0)); - volumetricFog.a = ComputeVolumetricFog(uniforms.fog, globalData.cameraLocation.xyz, worldPosition); - - vec3 lightPosition = worldPosition - 10000.0 * normalize(uniforms.mainLightDirection.xyz); - lightPosition = vec3(globalData.ivMatrix * vec4(lightPosition, 1.0)); - float extinctionToLight = ComputeVolumetricFog(uniforms.fog, worldPosition, lightPosition); - - vec3 scatteringCoefficient = uniforms.fog.scatteringFactor * - uniforms.fog.extinctionCoefficients.rgb; - - vec3 lightScattering = phaseFunction * uniforms.mainLightColor.rgb; - - vec3 scattering = scatteringCoefficient * (lightScattering + vec3(uniforms.fog.ambientFactor)); - - volumetricFog.rgb = scattering * clamp(1.0 - volumetricFog.a, 0.0, 1.0); -#endif - - resolve = ApplyVolumetrics(uniforms.fog, resolve, volumetricFog, volumetricClouds, + resolve = ApplyVolumetrics(resolve, volumetricFog, volumetricClouds, worldDirection, planetCenter, uniforms.innerCloudRadius); imageStore(resolveImage, pixel, vec4(resolve, 1.0)); diff --git a/data/shader/wind.hsh b/data/shader/wind.hsh index a2afbd986..f3e15e74c 100644 --- a/data/shader/wind.hsh +++ b/data/shader/wind.hsh @@ -10,12 +10,21 @@ vec4 SmoothCurve( vec4 x ) { return x * x *( 3.0 - 2.0 * x ); } vec4 TriangleWave( vec4 x ) { return abs( fract( x + 0.5 ) * 2.0 - 1.0 ); } vec4 SmoothTriangleWave( vec4 x ) { return SmoothCurve( TriangleWave( x ) ); } +// The scene wind in the object space of a vegetation instance +vec2 GetWindDirection(mat4 modelMatrix) { + + return normalize((inverse(mat3(modelMatrix)) * vec3(globalData.windDir.x, 0.0, globalData.windDir.y)).xz); + +} + vec3 WindAnimation(sampler2D noiseTexture, vec3 position, vec2 windDir, float bendFactor, float wiggleFactor, float lod, float animTime, vec3 location) { vec3 originalPos = position; float windSpeed = globalData.windSpeed; + // Above a breeze the bending grows linearly with the speed, so strong wind and storms visibly bend vegetation + float windAmplitude = max(sqrt(windSpeed), windSpeed * 0.5); float centerDistance = length(position.xz); float height = max(0.0, position.y * bendFactor * 0.5); @@ -28,10 +37,10 @@ vec3 WindAnimation(sampler2D noiseTexture, vec3 position, vec2 windDir, mainBending *= mainBending; mainBending = mainBending * mainBending - mainBending; - position.xz += windDir * mainBending * sqrt(windSpeed); + position.xz += windDir * mainBending * windAmplitude; position.xyz = normalize(position - vec3(originalPos.x, 0.0, originalPos.z)) * abs(originalPos.y) + vec3(originalPos.x, 0.0, originalPos.z); - float branchAmp = .25 * sqrt(windSpeed); + float branchAmp = .25 * windAmplitude; float detailAmp = 0.02; float edgeAtten = 0.5; float speed = 0.2; diff --git a/libs/ImguiExtension/CMakeLists.txt b/libs/ImguiExtension/CMakeLists.txt index d792b3a74..6b8415aca 100644 --- a/libs/ImguiExtension/CMakeLists.txt +++ b/libs/ImguiExtension/CMakeLists.txt @@ -29,5 +29,5 @@ find_package(implot CONFIG REQUIRED) # We cam do this here, since the ImguiExtension dependency uses the engine and therefore is always included # after the engine is added add_library(${PROJECT_NAME} STATIC ${IMGUI_SOURCE_FILES}) -target_compile_definitions(${PROJECT_NAME} PUBLIC ${ATLAS_ENGINE_COMPILE_DEFINITIONS}) -target_link_libraries(${PROJECT_NAME} imgui::imgui implot::implot volk::volk volk::volk_headers SDL2::SDL2 GPUOpen::VulkanMemoryAllocator Jolt::Jolt) \ No newline at end of file +target_compile_definitions(${PROJECT_NAME} PUBLIC $) +target_link_libraries(${PROJECT_NAME} imgui::imgui implot::implot volk::volk volk::volk_headers SDL3::SDL3 GPUOpen::VulkanMemoryAllocator Jolt::Jolt) \ No newline at end of file diff --git a/libs/ImguiExtension/ImguiWrapper.cpp b/libs/ImguiExtension/ImguiWrapper.cpp index e76c876b7..66b102f02 100644 --- a/libs/ImguiExtension/ImguiWrapper.cpp +++ b/libs/ImguiExtension/ImguiWrapper.cpp @@ -1,18 +1,23 @@ -// Based on SDL2 Imgui backend: https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_sdl2.cpp +// Based on SDL3 Imgui backend: https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_sdl3.cpp #include "ImguiWrapper.h" #ifndef AE_OS_APPLE_MOBILE #define VK_NO_PROTOTYPES #endif -#include +#include +#include #include +#include #include +#include + namespace Atlas::ImguiExtension { void ImguiWrapper::Load(Atlas::Window *window) { + this->window = window; ImPlot::CreateContext(); // Setup back-end capabilities flags @@ -21,20 +26,27 @@ namespace Atlas::ImguiExtension { io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used) io.BackendPlatformName = "imgui_impl_atlas"; - /* - io.SetClipboardTextFn = ImGui_ImplSDL2_SetClipboardText; - io.GetClipboardTextFn = ImGui_ImplSDL2_GetClipboardText; - io.ClipboardUserData = NULL; - */ - - mouseCursors[ImGuiMouseCursor_Arrow] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_ARROW); - mouseCursors[ImGuiMouseCursor_TextInput] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_IBEAM); - mouseCursors[ImGuiMouseCursor_ResizeAll] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZEALL); - mouseCursors[ImGuiMouseCursor_ResizeNS] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZENS); - mouseCursors[ImGuiMouseCursor_ResizeEW] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZEWE); - mouseCursors[ImGuiMouseCursor_ResizeNESW] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZENESW); - mouseCursors[ImGuiMouseCursor_ResizeNWSE] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZENWSE); - mouseCursors[ImGuiMouseCursor_Hand] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_HAND); + ImGuiPlatformIO &platformIO = ImGui::GetPlatformIO(); + platformIO.Platform_ClipboardUserData = this; + platformIO.Platform_SetClipboardTextFn = [](ImGuiContext*, const char* text) { + SDL_SetClipboardText(text); + }; + platformIO.Platform_GetClipboardTextFn = [](ImGuiContext*) -> const char* { + auto wrapper = static_cast(ImGui::GetPlatformIO().Platform_ClipboardUserData); + // SDL hands out a copy that has to stay valid until ImGui asks again + SDL_free(wrapper->clipboardText); + wrapper->clipboardText = SDL_GetClipboardText(); + return wrapper->clipboardText; + }; + + mouseCursors[ImGuiMouseCursor_Arrow] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_DEFAULT); + mouseCursors[ImGuiMouseCursor_TextInput] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_TEXT); + mouseCursors[ImGuiMouseCursor_ResizeAll] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_MOVE); + mouseCursors[ImGuiMouseCursor_ResizeNS] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_NS_RESIZE); + mouseCursors[ImGuiMouseCursor_ResizeEW] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_EW_RESIZE); + mouseCursors[ImGuiMouseCursor_ResizeNESW] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_NESW_RESIZE); + mouseCursors[ImGuiMouseCursor_ResizeNWSE] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_NWSE_RESIZE); + mouseCursors[ImGuiMouseCursor_Hand] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_POINTER); // Subscribe to events auto windowEventHandler = std::bind(&ImguiWrapper::WindowHandler, this, std::placeholders::_1); @@ -55,7 +67,9 @@ namespace Atlas::ImguiExtension { auto textInputEventHandler = std::bind(&ImguiWrapper::TextInputHandler, this, std::placeholders::_1); textInputID = Atlas::Events::EventManager::TextInputEventDelegate.Subscribe(textInputEventHandler); - RecreateImGuiResources(); + // The resources might have been created already, e.g. for the fonts of the application + if (!initialized) + RecreateImGuiResources(); } @@ -66,13 +80,34 @@ namespace Atlas::ImguiExtension { device->WaitForIdle(); - // Unsubscribe from all events ImGui_ImplVulkan_Shutdown(); + if (window) { + window->windowEventDelegate.Unsubscribe(windowID); + window->mouseButtonEventDelegate.Unsubscribe(mouseButtonID); + window->mouseMotionEventDelegate.Unsubscribe(mouseMotionID); + window->mouseWheelEventDelegate.Unsubscribe(mouseWheelID); + window = nullptr; + } + Atlas::Events::EventManager::KeyboardEventDelegate.Unsubscribe(keyboardID); + Atlas::Events::EventManager::TextInputEventDelegate.Unsubscribe(textInputID); + for (auto& cursor : mouseCursors) { + SDL_DestroyCursor(cursor); + cursor = nullptr; + } + ImPlot::DestroyContext(); pool.reset(); + for (auto list : drawListCopies) + IM_DELETE(list); + drawListCopies.clear(); + drawDataCopy.Clear(); + + SDL_free(clipboardText); + clipboardText = nullptr; + initialized = false; } @@ -83,9 +118,9 @@ namespace Atlas::ImguiExtension { io.DeltaTime = deltaTime; - auto w = (float) window->GetWidth(); - auto h = (float) window->GetHeight(); - auto size = glm::vec2(window->GetDrawableSize()); + auto w = (float) window->GetWidth() / scale; + auto h = (float) window->GetHeight() / scale; + auto size = vec2(window->GetDrawableSize()); io.DisplaySize = ImVec2(w, h); if (w > 0.0f && h > 0.0f) io.DisplayFramebufferScale = ImVec2(size.x / w, size.y / h); @@ -117,6 +152,8 @@ namespace Atlas::ImguiExtension { void ImguiWrapper::Render(bool clearSwapChain) { + Atlas::CPUProfiler::Scope profilerScope("ImGui"); + ImGuiIO &io = ImGui::GetIO(); ImGui_ImplVulkan_NewFrame(); @@ -131,15 +168,15 @@ namespace Atlas::ImguiExtension { commandList->BeginCommands(); - Atlas::Graphics::Profiler::BeginThread("ImGui thread", commandList); - Atlas::Graphics::Profiler::BeginQuery("ImGui"); + Atlas::GPUProfiler::BeginThread("ImGui thread", commandList); + Atlas::GPUProfiler::BeginQuery("ImGui"); commandList->BeginRenderPass(swapChain, clearSwapChain); - ImGui_ImplVulkan_RenderDrawData(ImGui::GetDrawData(), commandList->commandBuffer); + ImGui_ImplVulkan_RenderDrawData(hasDrawDataCopy ? &drawDataCopy : ImGui::GetDrawData(), commandList->commandBuffer); commandList->EndRenderPass(); - Atlas::Graphics::Profiler::EndQuery(); - Atlas::Graphics::Profiler::EndThread(); + Atlas::GPUProfiler::EndQuery(); + Atlas::GPUProfiler::EndThread(); commandList->EndCommands(); @@ -147,15 +184,56 @@ namespace Atlas::ImguiExtension { } - void ImguiWrapper::RecreateImGuiResources() { + void ImguiWrapper::CopyDrawData() { - if (initialized) { - ImGui_ImplVulkan_Shutdown(); + auto copyVector = [](auto& destination, const auto& source) { + destination.resize(source.Size); + if (source.Size) + std::memcpy(destination.Data, source.Data, source.size_in_bytes()); + }; + + drawDataCopy.Clear(); + hasDrawDataCopy = true; + + auto drawData = ImGui::GetDrawData(); + if (!drawData) + return; + + drawDataCopy.Valid = drawData->Valid; + drawDataCopy.CmdListsCount = drawData->CmdListsCount; + drawDataCopy.TotalIdxCount = drawData->TotalIdxCount; + drawDataCopy.TotalVtxCount = drawData->TotalVtxCount; + drawDataCopy.DisplayPos = drawData->DisplayPos; + drawDataCopy.DisplaySize = drawData->DisplaySize; + drawDataCopy.FramebufferScale = drawData->FramebufferScale; + drawDataCopy.OwnerViewport = drawData->OwnerViewport; + + for (int32_t i = 0; i < drawData->CmdLists.Size; i++) { + auto source = drawData->CmdLists[i]; + if (i >= drawListCopies.Size) + drawListCopies.push_back(IM_NEW(ImDrawList)(source->_Data)); + + auto copy = drawListCopies[i]; + copyVector(copy->CmdBuffer, source->CmdBuffer); + copyVector(copy->IdxBuffer, source->IdxBuffer); + copyVector(copy->VtxBuffer, source->VtxBuffer); + copy->Flags = source->Flags; + drawDataCopy.CmdLists.push_back(copy); } + } + + void ImguiWrapper::RecreateImGuiResources() { + auto instance = Atlas::Graphics::Instance::DefaultInstance; auto device = instance->GetGraphicsDevice(); + // Frames in flight still use the old font texture + if (initialized) { + device->WaitForIdle(); + ImGui_ImplVulkan_Shutdown(); + } + auto desc = Atlas::Graphics::DescriptorPoolDesc{ .freeDescriptorSets = true }; @@ -185,12 +263,27 @@ namespace Atlas::ImguiExtension { //clear font textures from cpu data ImGui_ImplVulkan_DestroyFontUploadObjects(); + // The backend only keeps the handle, a queue left locked blocks the render thread forever + queue.Unlock(); + imageViewToDescriptorSetMap.clear(); initialized = true; } + void ImguiWrapper::SetScale(float scale) { + + this->scale = scale; + + } + + float ImguiWrapper::GetScale() const { + + return scale; + + } + ImTextureID ImguiWrapper::GetTextureId(const Atlas::Texture::Texture* texture, VkImageLayout layout) { @@ -238,7 +331,7 @@ namespace Atlas::ImguiExtension { ImGuiIO &io = ImGui::GetIO(); - io.MousePos = ImVec2((float) event.x, (float) event.y); + io.MousePos = ImVec2(event.x / scale, event.y / scale); } @@ -246,10 +339,8 @@ namespace Atlas::ImguiExtension { ImGuiIO &io = ImGui::GetIO(); - if (event.x > 0) io.MouseWheelH += 1; - if (event.x < 0) io.MouseWheelH -= 1; - if (event.y > 0) io.MouseWheel += 1; - if (event.y < 0) io.MouseWheel -= 1; + io.MouseWheelH += event.x; + io.MouseWheel += event.y; } @@ -280,12 +371,12 @@ namespace Atlas::ImguiExtension { ImGuiMouseCursor imgui_cursor = ImGui::GetMouseCursor(); if (io.MouseDrawCursor || imgui_cursor == ImGuiMouseCursor_None) { // Hide OS mouse cursor if imgui is drawing it or if it wants no cursor - SDL_ShowCursor(SDL_FALSE); + SDL_HideCursor(); } else { // Show OS mouse cursor SDL_SetCursor( mouseCursors[imgui_cursor] ? mouseCursors[imgui_cursor] : mouseCursors[ImGuiMouseCursor_Arrow]); - SDL_ShowCursor(SDL_TRUE); + SDL_ShowCursor(); } } @@ -323,7 +414,7 @@ namespace Atlas::ImguiExtension { return ImGuiKey_Enter; case SDLK_ESCAPE: return ImGuiKey_Escape; - case SDLK_QUOTE: + case SDLK_APOSTROPHE: return ImGuiKey_Apostrophe; case SDLK_COMMA: return ImGuiKey_Comma; @@ -343,7 +434,7 @@ namespace Atlas::ImguiExtension { return ImGuiKey_Backslash; case SDLK_RIGHTBRACKET: return ImGuiKey_RightBracket; - case SDLK_BACKQUOTE: + case SDLK_GRAVE: return ImGuiKey_GraveAccent; case SDLK_CAPSLOCK: return ImGuiKey_CapsLock; @@ -427,57 +518,57 @@ namespace Atlas::ImguiExtension { return ImGuiKey_8; case SDLK_9: return ImGuiKey_9; - case SDLK_a: + case SDLK_A: return ImGuiKey_A; - case SDLK_b: + case SDLK_B: return ImGuiKey_B; - case SDLK_c: + case SDLK_C: return ImGuiKey_C; - case SDLK_d: + case SDLK_D: return ImGuiKey_D; - case SDLK_e: + case SDLK_E: return ImGuiKey_E; - case SDLK_f: + case SDLK_F: return ImGuiKey_F; - case SDLK_g: + case SDLK_G: return ImGuiKey_G; - case SDLK_h: + case SDLK_H: return ImGuiKey_H; - case SDLK_i: + case SDLK_I: return ImGuiKey_I; - case SDLK_j: + case SDLK_J: return ImGuiKey_J; - case SDLK_k: + case SDLK_K: return ImGuiKey_K; - case SDLK_l: + case SDLK_L: return ImGuiKey_L; - case SDLK_m: + case SDLK_M: return ImGuiKey_M; - case SDLK_n: + case SDLK_N: return ImGuiKey_N; - case SDLK_o: + case SDLK_O: return ImGuiKey_O; - case SDLK_p: + case SDLK_P: return ImGuiKey_P; - case SDLK_q: + case SDLK_Q: return ImGuiKey_Q; - case SDLK_r: + case SDLK_R: return ImGuiKey_R; - case SDLK_s: + case SDLK_S: return ImGuiKey_S; - case SDLK_t: + case SDLK_T: return ImGuiKey_T; - case SDLK_u: + case SDLK_U: return ImGuiKey_U; - case SDLK_v: + case SDLK_V: return ImGuiKey_V; - case SDLK_w: + case SDLK_W: return ImGuiKey_W; - case SDLK_x: + case SDLK_X: return ImGuiKey_X; - case SDLK_y: + case SDLK_Y: return ImGuiKey_Y; - case SDLK_z: + case SDLK_Z: return ImGuiKey_Z; case SDLK_F1: return ImGuiKey_F1; @@ -512,10 +603,10 @@ namespace Atlas::ImguiExtension { void ImguiWrapper::UpdateKeyModifiers(uint16_t keyModifier) { ImGuiIO &io = ImGui::GetIO(); - io.AddKeyEvent(ImGuiMod_Ctrl, (keyModifier & KMOD_CTRL) != 0); - io.AddKeyEvent(ImGuiMod_Shift, (keyModifier & KMOD_SHIFT) != 0); - io.AddKeyEvent(ImGuiMod_Alt, (keyModifier & KMOD_ALT) != 0); - io.AddKeyEvent(ImGuiMod_Super, (keyModifier & KMOD_GUI) != 0); + io.AddKeyEvent(ImGuiMod_Ctrl, (keyModifier & SDL_KMOD_CTRL) != 0); + io.AddKeyEvent(ImGuiMod_Shift, (keyModifier & SDL_KMOD_SHIFT) != 0); + io.AddKeyEvent(ImGuiMod_Alt, (keyModifier & SDL_KMOD_ALT) != 0); + io.AddKeyEvent(ImGuiMod_Super, (keyModifier & SDL_KMOD_GUI) != 0); } diff --git a/libs/ImguiExtension/ImguiWrapper.h b/libs/ImguiExtension/ImguiWrapper.h index a654a3c98..797b595de 100644 --- a/libs/ImguiExtension/ImguiWrapper.h +++ b/libs/ImguiExtension/ImguiWrapper.h @@ -26,8 +26,17 @@ namespace Atlas::ImguiExtension { void Render(bool clearSwapChain = false); + // Copies the draw data after ImGui::Render(), Render() then draws the copy. A render thread can draw it + // while the next frame is built, but must not render while it is copied + void CopyDrawData(); + void RecreateImGuiResources(); + // Scales the whole interface, ImGui works with a smaller display and a larger framebuffer scale + void SetScale(float scale); + + float GetScale() const; + ImTextureID GetTextureId(const Atlas::Texture::Texture* texture, VkImageLayout layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); @@ -56,6 +65,7 @@ namespace Atlas::ImguiExtension { void UpdateMouseCursor(); SDL_Cursor *mouseCursors[ImGuiMouseCursor_COUNT]; + char *clipboardText = nullptr; int32_t windowID = 0; int32_t mouseMotionID = 0; @@ -65,10 +75,16 @@ namespace Atlas::ImguiExtension { int32_t textInputID = 0; Atlas::Window *window = nullptr; + float scale = 1.0f; Atlas::Ref pool = nullptr; std::unordered_map imageViewToDescriptorSetMap; + ImDrawData drawDataCopy; + // Reused by the copies, such that their buffers aren't allocated every frame + ImVector drawListCopies; + bool hasDrawDataCopy = false; + bool initialized = false; }; diff --git a/libs/ImguiExtension/Panels.h b/libs/ImguiExtension/Panels.h index 27ec06544..7cbca9ac9 100644 --- a/libs/ImguiExtension/Panels.h +++ b/libs/ImguiExtension/Panels.h @@ -10,6 +10,7 @@ #include "panels/RTGIPanel.h" #include "panels/MaterialPanel.h" #include "panels/MaterialsPanel.h" -#include "panels/GPUProfilerPanel.h" +#include "panels/ProfilerPanel.h" #include "panels/WindPanel.h" #include "panels/SkyPanel.h" +#include "panels/OceanPanel.h" diff --git a/libs/ImguiExtension/UiElements.cpp b/libs/ImguiExtension/UiElements.cpp index da6132ffd..1cb3516be 100644 --- a/libs/ImguiExtension/UiElements.cpp +++ b/libs/ImguiExtension/UiElements.cpp @@ -1,7 +1,15 @@ #include "UiElements.h" +#include +#include + +#include +#include + namespace Atlas::ImguiExtension { + UIElements::PropertySearch UIElements::propertySearch; + void UIElements::TexturePreview(Ref& wrapper, const Texture::Texture* texture) { auto lineHeight = ImGui::GetTextLineHeightWithSpacing(); @@ -53,4 +61,469 @@ namespace Atlas::ImguiExtension { } + bool UIElements::BeginProperties(const char* id) { + + // Content hidden by a search still shows the matching rows of its tables + auto window = ImGui::GetCurrentWindow(); + if (IsContentHidden(window)) + window->SkipItems = false; + + auto start = ImGui::GetCursorScreenPos(); + if (!ImGui::BeginTable(id, 2, ImGuiTableFlags_SizingStretchProp | ImGuiTableFlags_NoSavedSettings)) { + UpdateContentVisibility(); + return false; + } + + SetupPropertyLabelColumn("Label"); + ImGui::TableSetupColumn("Value", ImGuiTableColumnFlags_WidthStretch); + if (propertySearch.active) + propertySearch.tables.push_back({ .start = start }); + return true; + + } + + void UIElements::PropertyLabel(const char* label, const char* tooltip) { + + auto labelEnd = ImGui::FindRenderedTextEnd(label); + auto highlight = false; + if (propertySearch.active) { + auto& search = propertySearch; + const auto& scope = search.scopes[search.depth - 1]; + if (!scope.matches && !scope.sectionMatches) { + if (!MatchesSearchWords(std::string_view(label, labelEnd), tooltip ? tooltip : std::string_view())) { + // Like ImGui between rows, the value and everything up to the next row is skipped + HideItems(ImGui::GetCurrentWindow()); + return; + } + highlight = true; + } + CountPropertyMatch(); + if (!search.tables.empty()) + search.tables.back().shownRows++; + } + + ImGui::TableNextRow(); + ImGui::TableSetColumnIndex(0); + + // Muted and centered on the value, long labels are cut off with an ellipsis and shown in full in the tooltip + auto width = ImGui::GetContentRegionAvail().x; + auto pos = ImGui::GetCursorScreenPos(); + auto textSize = ImGui::CalcTextSize(label, nullptr, true); + MeasurePropertyLabel(textSize.x); + ImGui::Dummy(ImVec2(width, ImGui::GetFrameHeight())); + auto textPos = ImVec2(pos.x, pos.y + ImGui::GetStyle().FramePadding.y); + auto textEnd = ImVec2(pos.x + width, textPos.y + ImGui::GetTextLineHeight()); + // Matches of a search stand out + ImGui::PushStyleColor(ImGuiCol_Text, ImGui::GetStyleColorVec4(highlight ? ImGuiCol_Text : ImGuiCol_TextDisabled)); + ImGui::RenderTextEllipsis(ImGui::GetWindowDrawList(), textPos, textEnd, textEnd.x, textEnd.x, label, + labelEnd, &textSize); + ImGui::PopStyleColor(); + if (tooltip) + ImGui::SetItemTooltip("%s", tooltip); + else if (textSize.x > width) + ImGui::SetItemTooltip("%s", label); + + ImGui::TableSetColumnIndex(1); + ImGui::SetNextItemWidth(-FLT_MIN); + + } + + void UIElements::EndProperties() { + + ImGui::EndTable(); + + auto& search = propertySearch; + if (!search.active || search.tables.empty()) + return; + + auto table = search.tables.back(); + search.tables.pop_back(); + if (table.shownRows == 0) + ImGui::SetCursorScreenPos(table.start); + UpdateContentVisibility(); + + } + + void UIElements::SetupPropertyLabelColumn(const char* name) { + + // At most 40% of the width, which is also the width before the labels of the window were measured + auto labelWidth = UpdatePropertyLabelWidth(0.0f); + auto maxWidth = 0.4f * ImGui::GetContentRegionAvail().x; + auto width = labelWidth > 0.0f ? std::min(labelWidth + 2.0f * ImGui::GetStyle().ItemSpacing.x, maxWidth) : maxWidth; + + ImGui::TableSetupColumn(name, ImGuiTableColumnFlags_WidthFixed, width); + // A new table has no maximum width yet, which would clamp the width, the initial width applies instead + auto table = ImGui::GetCurrentTable(); + if (!table->IsInitializing) + ImGui::TableSetColumnWidth(table->DeclColumnsCount - 1, width); + + } + + void UIElements::MeasurePropertyLabel(float labelWidth) { + + UpdatePropertyLabelWidth(labelWidth); + + } + + void UIElements::PropertySection(const char* label) { + + auto& search = propertySearch; + if (!search.active) { + ImGui::SeparatorText(label); + return; + } + + auto& scope = search.scopes[search.depth - 1]; + auto labelEnd = ImGui::FindRenderedTextEnd(label); + scope.section.clear(); + scope.sectionMatches = MatchesSearchWords(std::string_view(label, labelEnd)); + scope.section.assign(label, labelEnd); + if (scope.sectionMatches) + CountPropertyMatch(); + UpdateContentVisibility(); + + } + + void UIElements::BeginPropertySearch(const std::string& text, uint32_t scope) { + + auto& search = propertySearch; + AE_ASSERT(!search.active && "Property searches can't be nested"); + + if (text != search.text) { + search.text = text; + search.words = SplitWords(text); + } + if (search.words.empty()) + return; + + search.active = true; + search.anyMatch = false; + search.depth = 0; + search.blockDepth = 0; + search.tables.clear(); + // Never 0, the value of groups which weren't counted yet + search.key = ImHashData(&scope, sizeof(scope), ImHashStr(text.c_str())) | 1u; + PushPropertyScope(0, {}, false); + + } + + bool UIElements::EndPropertySearch() { + + auto& search = propertySearch; + if (!search.active) + return true; + + AE_ASSERT(search.depth == 1 && search.blockDepth == 0 && search.tables.empty() && + "Property groups, blocks and tables have to end before the search"); + + search.active = false; + search.depth = 0; + return search.anyMatch; + + } + + bool UIElements::PropertySearchBar(const char* id, std::string& text, bool focus) { + + if (focus) + ImGui::SetKeyboardFocusHere(); + ImGui::SetNextItemWidth(-FLT_MIN); + return ImGui::InputTextWithHint(id, "Search properties...", &text, ImGuiInputTextFlags_EscapeClearsAll); + + } + + bool UIElements::BeginPropertyGroup(const char* name) { + + auto& search = propertySearch; + if (!search.active) + return true; + + // Nothing is counted in hidden windows or rows + auto window = ImGui::GetCurrentWindow(); + auto contentHidden = IsContentHidden(window); + if (window->SkipItems && !contentHidden) + return false; + + const auto& parent = search.scopes[search.depth - 1]; + auto id = ImGui::GetID(name); + auto nameView = std::string_view(name, ImGui::FindRenderedTextEnd(name)); + auto nameMatches = MatchesSearchWords(nameView); + auto matches = nameMatches || parent.matches || parent.sectionMatches; + + // The matches of the last time the group was drawn with this search + auto recount = false; + auto& storage = window->StateStorage; + if (!matches && storage.GetInt(ImHashStr("Search key", 0, id)) == int32_t(search.key) && + storage.GetInt(ImHashStr("Search matches", 0, id)) == 0) { + if (ImGui::GetFrameCount() - storage.GetInt(ImHashStr("Search frame", 0, id)) < recountInterval) + return false; + recount = true; + } + + auto& scope = PushPropertyScope(id, nameView, matches); + if (nameMatches) + CountPropertyMatch(); + + // The header is shown in hidden content + if (contentHidden) + window->SkipItems = false; + + // Content can change without a change of the search, e.g. when a resource is loaded. The group is drawn + // invisibly then and takes no space without matches + if (recount) { + scope.recount = true; + scope.start = ImGui::GetCursorScreenPos(); + scope.maxPos = window->DC.CursorMaxPos; + ImGui::PushClipRect(scope.start, scope.start, true); + } + + return true; + + } + + void UIElements::EndPropertyGroup() { + + auto& search = propertySearch; + if (!search.active) + return; + + AE_ASSERT(search.depth > 1 && "EndPropertyGroup without a group"); + + auto& scope = search.scopes[search.depth - 1]; + if (scope.contentWindow) + EndPropertyContent(); + + auto window = ImGui::GetCurrentWindow(); + if (scope.recount) { + ImGui::PopClipRect(); + if (scope.matchCount == 0) { + ImGui::SetCursorScreenPos(scope.start); + window->DC.CursorMaxPos = scope.maxPos; + } + } + + if (scope.counted) { + auto& storage = window->StateStorage; + storage.SetInt(ImHashStr("Search key", 0, scope.id), int32_t(search.key)); + storage.SetInt(ImHashStr("Search matches", 0, scope.id), scope.matchCount); + storage.SetInt(ImHashStr("Search frame", 0, scope.id), ImGui::GetFrameCount()); + } + + search.depth--; + UpdateContentVisibility(); + + } + + ImGuiTreeNodeFlags UIElements::PropertyGroupHeaderFlags() { + + // Leaf nodes are always open and keep the open state of the node + return propertySearch.active ? ImGuiTreeNodeFlags_Leaf : ImGuiTreeNodeFlags_None; + + } + + void UIElements::BeginPropertyContent() { + + auto& search = propertySearch; + if (!search.active) + return; + + auto& scope = search.scopes[search.depth - 1]; + AE_ASSERT(search.depth > 1 && !scope.contentWindow && "Property content needs a group and can't be nested"); + + scope.contentWindow = ImGui::GetCurrentWindow(); + scope.contentSkipItems = scope.contentWindow->SkipItems; + if (scope.contentSkipItems) + scope.counted = false; + UpdateContentVisibility(); + + } + + void UIElements::EndPropertyContent() { + + auto& search = propertySearch; + if (!search.active) + return; + + auto& scope = search.scopes[search.depth - 1]; + AE_ASSERT(scope.contentWindow && "EndPropertyContent without BeginPropertyContent"); + + scope.contentWindow->SkipItems = scope.contentSkipItems; + scope.contentWindow = nullptr; + + } + + bool UIElements::BeginPropertyBlock(const char* label) { + + auto& search = propertySearch; + if (!search.active) + return true; + + // Blocks in hidden rows stay hidden + auto window = ImGui::GetCurrentWindow(); + auto contentHidden = IsContentHidden(window); + if (window->SkipItems && !contentHidden) + return false; + + const auto& scope = search.scopes[search.depth - 1]; + if (!scope.matches && !scope.sectionMatches && + !MatchesSearchWords(std::string_view(label, ImGui::FindRenderedTextEnd(label)))) + return false; + + CountPropertyMatch(); + if (contentHidden) + window->SkipItems = false; + search.blockDepth++; + return true; + + } + + void UIElements::EndPropertyBlock() { + + auto& search = propertySearch; + if (!search.active) + return; + + search.blockDepth--; + UpdateContentVisibility(); + + } + + bool UIElements::MatchesSearch(std::string_view text, std::string_view search) { + + size_t start = 0; + while (start < search.size()) { + auto end = search.find_first_of(" \t", start); + if (end == std::string_view::npos) + end = search.size(); + if (end > start && !ContainsIgnoreCase(text, search.substr(start, end - start))) + return false; + start = end + 1; + } + return true; + + } + + UIElements::PropertyScope& UIElements::PushPropertyScope(ImGuiID id, std::string_view name, bool matches) { + + auto& search = propertySearch; + if (search.depth == search.scopes.size()) + search.scopes.emplace_back(); + + auto& scope = search.scopes[search.depth++]; + scope.id = id; + scope.name.assign(name); + scope.matches = matches; + scope.matchCount = 0; + scope.counted = true; + scope.recount = false; + scope.section.clear(); + scope.sectionMatches = false; + scope.contentWindow = nullptr; + scope.contentSkipItems = false; + return scope; + + } + + bool UIElements::MatchesSearchWords(std::string_view label, std::string_view tooltip) { + + const auto& search = propertySearch; + for (const auto& word : search.words) { + auto found = ContainsIgnoreCase(label, word) || ContainsIgnoreCase(tooltip, word); + for (size_t i = 0; i < search.depth && !found; i++) + found = ContainsIgnoreCase(search.scopes[i].name, word) || ContainsIgnoreCase(search.scopes[i].section, word); + if (!found) + return false; + } + return true; + + } + + bool UIElements::ContainsIgnoreCase(std::string_view text, std::string_view word) { + + auto iter = std::search(text.begin(), text.end(), word.begin(), word.end(), [](char character0, char character1) { + return std::tolower(static_cast(character0)) == std::tolower(static_cast(character1)); + }); + return iter != text.end() || word.empty(); + + } + + std::vector UIElements::SplitWords(std::string_view text) { + + std::vector words; + size_t start = 0; + while (start < text.size()) { + auto end = text.find_first_of(" \t", start); + if (end == std::string_view::npos) + end = text.size(); + if (end > start) + words.emplace_back(text.substr(start, end - start)); + start = end + 1; + } + return words; + + } + + void UIElements::CountPropertyMatch() { + + auto& search = propertySearch; + search.anyMatch = true; + for (size_t i = 0; i < search.depth; i++) + search.scopes[i].matchCount++; + + } + + bool UIElements::IsContentHidden(ImGuiWindow* window) { + + const auto& search = propertySearch; + if (!search.active || !search.tables.empty() || search.blockDepth > 0) + return false; + + const auto& scope = search.scopes[search.depth - 1]; + return scope.contentWindow == window && !scope.contentSkipItems; + + } + + void UIElements::HideItems(ImGuiWindow* window) { + + // Item queries like IsItemHovered would otherwise refer to the last shown item + window->SkipItems = true; + ImGui::SetLastItemData(0, ImGuiItemFlags_None, ImGuiItemStatusFlags_None, ImRect()); + + } + + void UIElements::UpdateContentVisibility() { + + const auto& search = propertySearch; + if (!search.active || !search.tables.empty() || search.blockDepth > 0) + return; + + const auto& scope = search.scopes[search.depth - 1]; + if (!scope.contentWindow) + return; + + if (scope.contentSkipItems || (!scope.matches && !scope.sectionMatches)) + HideItems(scope.contentWindow); + else + scope.contentWindow->SkipItems = false; + + } + + float UIElements::UpdatePropertyLabelWidth(float labelWidth) { + + // The longest label of this frame is collected while the labels are drawn + auto window = ImGui::GetCurrentWindow(); + auto& storage = window->StateStorage; + auto lastWidthKey = ImHashStr("Property label width", 0, window->ID); + auto widthKey = ImHashStr("Property label width of this frame", 0, window->ID); + auto frameKey = ImHashStr("Property label frame", 0, window->ID); + auto frame = ImGui::GetFrameCount(); + if (storage.GetInt(frameKey) != frame) { + storage.SetFloat(lastWidthKey, storage.GetFloat(widthKey)); + storage.SetFloat(widthKey, 0.0f); + storage.SetInt(frameKey, frame); + } + storage.SetFloat(widthKey, std::max(storage.GetFloat(widthKey), labelWidth)); + return storage.GetFloat(lastWidthKey); + + } + } \ No newline at end of file diff --git a/libs/ImguiExtension/UiElements.h b/libs/ImguiExtension/UiElements.h index 0676b5470..ad5e63bae 100644 --- a/libs/ImguiExtension/UiElements.h +++ b/libs/ImguiExtension/UiElements.h @@ -1,12 +1,17 @@ #pragma once #include +#include +#include +#include #include #include "System.h" #include "ImguiWrapper.h" #include "texture/Texture2D.h" +struct ImGuiWindow; + namespace Atlas::ImguiExtension { class UIElements { @@ -18,6 +23,129 @@ namespace Atlas::ImguiExtension { static void Tooltip(const char* text, float size = 35.0f); + // Properties with a muted label on the left and the value filling the rest of the row. Call PropertyLabel + // before each value, then EndProperties. Same layout as the property tables of the editor + static bool BeginProperties(const char* id); + + // Starts a row, the next item is the value and fills its column + static void PropertyLabel(const char* label, const char* tooltip = nullptr); + + static void EndProperties(); + + // All label columns of a window are as wide as its longest label. Tables with their own columns set it up + // with this and report each of their labels with MeasurePropertyLabel + static void SetupPropertyLabelColumn(const char* name); + + static void MeasurePropertyLabel(float labelWidth); + + // Heading of the following properties, hidden while searching + static void PropertySection(const char* label); + + // Filters the property rows drawn until EndPropertySearch. Rows are shown when every word of the text is in + // their label, tooltip, or the name of a section or group they are in. Panels mark their parts with groups, + // sections and blocks, everything else in the content of a group is hidden while searching. Tables in the + // content have to be property tables. The scope changes when the searched content does, e.g. with the + // selected entity. Does nothing for an empty text + static void BeginPropertySearch(const std::string& text, uint32_t scope = 0); + + // Returns whether anything matched + static bool EndPropertySearch(); + + // Input for the text of a property search, Escape clears it + static bool PropertySearchBar(const char* id, std::string& text, bool focus = false); + + // A group of properties below a header, e.g. a component or an element of a list. Groups can be nested. While + // searching a group is hidden without matches, then it returns false and EndPropertyGroup isn't called. + // Matches are counted while the group is drawn, hidden groups are drawn invisibly from time to time to find + // matches in changed content + static bool BeginPropertyGroup(const char* name); + + static void EndPropertyGroup(); + + // Flags for the tree node or collapsing header of a group, which keep it open while searching + static ImGuiTreeNodeFlags PropertyGroupHeaderFlags(); + + // The content of a group below its header. While searching, everything in it that isn't a matching property + // row, block, nested group or part of a matching section or group is hidden, e.g. buttons and lists + static void BeginPropertyContent(); + + static void EndPropertyContent(); + + // Content outside of property rows, e.g. a button or a list, which is shown when the label matches the + // search. Returns false when it's hidden, then EndPropertyBlock isn't called + static bool BeginPropertyBlock(const char* label); + + static void EndPropertyBlock(); + + // Case-insensitive, every word of the search has to be in the text + static bool MatchesSearch(std::string_view text, std::string_view search); + + private: + struct PropertyScope { + ImGuiID id = 0; + std::string name; + bool matches = false; + int32_t matchCount = 0; + + // Counts are only stored when the whole content was drawn + bool counted = true; + bool recount = false; + ImVec2 start; + ImVec2 maxPos; + + std::string section; + bool sectionMatches = false; + + ImGuiWindow* contentWindow = nullptr; + bool contentSkipItems = false; + }; + + struct PropertySearch { + bool active = false; + std::string text; + std::vector words; + uint32_t key = 0; + bool anyMatch = false; + + // The first scope is the search itself, scopes are kept to reuse their strings + std::vector scopes; + size_t depth = 0; + int32_t blockDepth = 0; + + // Property tables of the search, tables without a shown row take no space + struct Table { + ImVec2 start; + int32_t shownRows = 0; + }; + std::vector tables; + }; + + // Returns the longest label of the current window in the last frame + static float UpdatePropertyLabelWidth(float labelWidth); + + static PropertyScope& PushPropertyScope(ImGuiID id, std::string_view name, bool matches); + + // Every word of the search is in the label, the tooltip or the names and sections of the current scopes + static bool MatchesSearchWords(std::string_view label, std::string_view tooltip = {}); + + static bool ContainsIgnoreCase(std::string_view text, std::string_view word); + + static std::vector SplitWords(std::string_view text); + + static void CountPropertyMatch(); + + // Whether the window skips items only because the content of the current scope is hidden + static bool IsContentHidden(ImGuiWindow* window); + + static void HideItems(ImGuiWindow* window); + + // Hides the content outside of property tables and blocks unless the section or the group matches + static void UpdateContentVisibility(); + + static constexpr int32_t recountInterval = 30; + + static PropertySearch propertySearch; + }; } \ No newline at end of file diff --git a/libs/ImguiExtension/panels/FogPanel.cpp b/libs/ImguiExtension/panels/FogPanel.cpp index 9407ab056..29ef49869 100644 --- a/libs/ImguiExtension/panels/FogPanel.cpp +++ b/libs/ImguiExtension/panels/FogPanel.cpp @@ -6,28 +6,49 @@ namespace Atlas::ImguiExtension { ImGui::PushID(GetNameID()); - ImGui::Checkbox("Enable", &fog->enable); - ImGui::SetItemTooltip("Resoltion settings are shared between fog and volumetric clouds"); - - ImGui::ColorEdit3("Extinction coefficients", &fog->extinctionCoefficients[0]); - ImGui::DragFloat("Extinction factor", &fog->extinctionFactor, 0.002f, 0.0001f, 4.0f); - ImGui::DragFloat("Scattering factor", &fog->scatteringFactor, 0.002f, 0.0001f, 4.0f); - ImGui::DragFloat("Ambient factor", &fog->ambientFactor, 0.001f, 0.0001f, 1.0f); - - ImGui::SliderFloat("Density", &fog->density, 0.0f, 0.5f, "%.4f", ImGuiSliderFlags_Logarithmic); - ImGui::SliderFloat("Height", &fog->height, -10000.0f, 10000.0f, "%.3f", ImGuiSliderFlags_Logarithmic); - ImGui::SliderFloat("Height falloff", &fog->heightFalloff, 0.0f, 0.5f, - "%.4f", ImGuiSliderFlags_Logarithmic); - ImGui::SliderFloat("Scattering anisotropy", &fog->scatteringAnisotropy, -1.0f, 1.0f, - "%.3f", ImGuiSliderFlags_Logarithmic); - ImGui::SeparatorText("Volumetric"); - ImGui::Checkbox("Raymarching", &fog->rayMarching); - ImGui::Checkbox("Local lights", &fog->localLights); - ImGui::DragInt("Raymarch step count", &fog->rayMarchStepCount, 1, 128); - ImGui::SliderFloat("Intensity", &fog->volumetricIntensity, 0.0f, 1.0f); + if (UIElements::BeginProperties("FogGeneral")) { + UIElements::PropertyLabel("Enable", "Resolution settings are shared between fog and volumetric clouds"); + ImGui::Checkbox("##Enable", &fog->enable); + + UIElements::PropertyLabel("Albedo", "Share of the light the fog removes which it scatters, the rest is absorbed"); + ImGui::ColorEdit3("##Albedo", &fog->albedo[0]); + UIElements::PropertyLabel("Ambient factor"); + ImGui::DragFloat("##Ambient factor", &fog->ambientFactor, 0.001f, 0.0001f, 1.0f); + + UIElements::PropertyLabel("Density", "Extinction per world unit below the fog height"); + ImGui::DragFloat("##Density", &fog->density, 0.0001f, 0.0f, 0.5f, "%.5f", ImGuiSliderFlags_Logarithmic); + UIElements::PropertyLabel("Height"); + ImGui::DragFloat("##Height", &fog->height, 1.0f, -10000.0f, 10000.0f, "%.3f", ImGuiSliderFlags_Logarithmic); + UIElements::PropertyLabel("Height falloff"); + ImGui::DragFloat("##Height falloff", &fog->heightFalloff, 0.0005f, 0.0f, 0.5f, + "%.4f", ImGuiSliderFlags_Logarithmic); + UIElements::PropertyLabel("Scattering anisotropy"); + ImGui::DragFloat("##Scattering anisotropy", &fog->scatteringAnisotropy, 0.005f, -1.0f, 1.0f, + "%.3f", ImGuiSliderFlags_Logarithmic); + UIElements::EndProperties(); + } + + UIElements::PropertySection("Volumetric"); + if (UIElements::BeginProperties("FogVolumetric")) { + UIElements::PropertyLabel("Local lights"); + ImGui::Checkbox("##Local lights", &fog->localLights); + UIElements::PropertyLabel("Froxel tile size"); + ImGui::DragInt("##Froxel tile size", &fog->froxelTileSize, 0.1f, 4, 32); + UIElements::PropertyLabel("Froxel slice count"); + ImGui::DragInt("##Froxel slice count", &fog->froxelSliceCount, 0.1f, 16, 256); + UIElements::PropertyLabel("Froxel filter"); + ImGui::Checkbox("##Froxel filter", &fog->froxelFilter); + UIElements::PropertyLabel("Froxel far distance (0 = camera far)"); + ImGui::DragFloat("##Froxel far distance (0 = camera far)", &fog->froxelFarDistance, 1.0f, 0.0f, 5000.0f); + UIElements::PropertyLabel("Froxel distribution exponent"); + ImGui::DragFloat("##Froxel distribution exponent", &fog->froxelDistributionExponent, 0.01f, 0.25f, 4.0f); + UIElements::PropertyLabel("Intensity"); + ImGui::DragFloat("##Intensity", &fog->volumetricIntensity, 0.005f, 0.0f, 1.0f); + UIElements::EndProperties(); + } ImGui::PopID(); } -} \ No newline at end of file +} diff --git a/libs/ImguiExtension/panels/GPUProfilerPanel.cpp b/libs/ImguiExtension/panels/GPUProfilerPanel.cpp deleted file mode 100644 index 52ff79692..000000000 --- a/libs/ImguiExtension/panels/GPUProfilerPanel.cpp +++ /dev/null @@ -1,131 +0,0 @@ -#include "GPUProfilerPanel.h" -#include "common/MathHelper.h" - -#include "graphics/Profiler.h" -#include "Clock.h" - -namespace Atlas::ImguiExtension { - - void GPUProfilerPanel::Render() { - - ImGui::PushID(GetNameID()); - - // All controls in one row - bool enabled = Graphics::Profiler::enable; - ImGui::Checkbox("Enable##Profiler", &enabled); - Graphics::Profiler::enable = enabled; - - ImGui::SameLine(); - ImGui::Checkbox("Show graph##Profiler", &showGraph); - - if (!showGraph) { - const char* items[] = { "Chronologically", "Max time", "Min time" }; - ImGui::SameLine(); - ImGui::SetNextItemWidth(std::min(ImGui::GetContentRegionAvail().x * 0.5f, ImGui::GetFontSize() * 10.0f)); - ImGui::Combo("Sort##Performance", &sortItem, items, IM_ARRAYSIZE(items)); - } - - if (!enabled) - ImGui::TextDisabled("The profiler is disabled, enable it to collect GPU timings"); - else if (showGraph) - perfGraphPanel.Render(); - else - RenderTable(); - - ImGui::PopID(); - - } - - void GPUProfilerPanel::RenderTable() { - - Graphics::Profiler::OrderBy order; - switch (sortItem) { - case 1: order = Graphics::Profiler::OrderBy::MAX_TIME; break; - case 2: order = Graphics::Profiler::OrderBy::MIN_TIME; break; - default: order = Graphics::Profiler::OrderBy::CHRONO; break; - } - - // Fraction of the thread time is drawn as a bar behind the time, such that expensive passes stand out - auto barColor = ImGui::GetStyleColorVec4(ImGuiCol_PlotHistogram); - barColor.w *= 0.35f; - auto barColorU32 = ImGui::GetColorU32(barColor); - - auto renderTime = [&](double elapsedNs, double totalNs) { - auto ms = elapsedNs / 1000000.0; - auto fraction = totalNs > 0.0 ? float(Helper::Math::Saturate(elapsedNs / totalNs)) : 0.0f; - - auto cellMin = ImGui::GetCursorScreenPos(); - auto cellWidth = ImGui::GetContentRegionAvail().x; - auto lineHeight = ImGui::GetTextLineHeight(); - ImGui::GetWindowDrawList()->AddRectFilled(ImVec2(cellMin.x, cellMin.y + lineHeight - 3.0f), - ImVec2(cellMin.x + cellWidth * fraction, cellMin.y + lineHeight), barColorU32, 1.5f); - - char text[32]; - std::snprintf(text, sizeof(text), "%.3f", ms); - auto textWidth = ImGui::CalcTextSize(text).x; - ImGui::SetCursorPosX(ImGui::GetCursorPosX() + cellWidth - textWidth); - ImGui::TextUnformatted(text); - }; - - std::function displayQuery; - displayQuery = [&](Graphics::Profiler::Query& query, double totalNs) { - ImGui::TableNextRow(); - ImGui::TableNextColumn(); - - ImGuiTreeNodeFlags expandable = 0; - if (!query.children.size()) expandable = ImGuiTreeNodeFlags_NoTreePushOnOpen | - ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_Bullet; - - bool open = ImGui::TreeNodeEx(query.name.c_str(), expandable | ImGuiTreeNodeFlags_SpanFullWidth); - ImGui::TableNextColumn(); - renderTime(double(query.timer.elapsedTime), totalNs); - - if (open && query.children.size()) { - for (auto& child : query.children) - displayQuery(child, totalNs); - ImGui::TreePop(); - } - - }; - - ImGuiTableFlags flags = ImGuiTableFlags_BordersV | ImGuiTableFlags_BordersOuterH | - ImGuiTableFlags_Resizable | ImGuiTableFlags_RowBg | ImGuiTableFlags_NoBordersInBody | - ImGuiTableFlags_ScrollY; - - if (ImGui::BeginTable("PerfTable", 2, flags)) { - ImGui::TableSetupScrollFreeze(0, 1); - ImGui::TableSetupColumn("Name", ImGuiTableColumnFlags_NoHide | ImGuiTableColumnFlags_WidthStretch); - ImGui::TableSetupColumn("Time (ms)", ImGuiTableColumnFlags_NoHide | ImGuiTableColumnFlags_WidthFixed, - ImGui::GetFontSize() * 14.0f); - ImGui::TableHeadersRow(); - - auto threadData = Graphics::Profiler::GetQueriesAverage(64, order); - for (auto& thread : threadData) { - double threadTime = 0.0; - for (const auto& query : thread.queries) - threadTime += double(query.timer.elapsedTime); - - ImGui::TableNextRow(); - ImGui::TableNextColumn(); - - ImGuiTreeNodeFlags expandable = ImGuiTreeNodeFlags_DefaultOpen; - if (!thread.queries.size()) expandable = ImGuiTreeNodeFlags_NoTreePushOnOpen | - ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_Bullet; - - bool open = ImGui::TreeNodeEx(thread.name.c_str(), expandable | ImGuiTreeNodeFlags_SpanFullWidth); - ImGui::TableNextColumn(); - renderTime(threadTime, 0.0); - - if (open && thread.queries.size()) { - for (auto &query: thread.queries) - displayQuery(query, threadTime); - ImGui::TreePop(); - } - } - - ImGui::EndTable(); - } - - } - -} diff --git a/libs/ImguiExtension/panels/GPUProfilerPanel.h b/libs/ImguiExtension/panels/GPUProfilerPanel.h deleted file mode 100644 index 4e0e911a5..000000000 --- a/libs/ImguiExtension/panels/GPUProfilerPanel.h +++ /dev/null @@ -1,29 +0,0 @@ -#pragma once - -#include "Panel.h" -#include "PerformanceGraphPanel.h" - -#include -#include -#include - -namespace Atlas::ImguiExtension { - - class GPUProfilerPanel : public Panel { - - public: - GPUProfilerPanel() : Panel("GPU profiler hierarchy") {} - - void Render(); - - void RenderTable(); - - bool showGraph = false; - - int32_t sortItem = 0; - - PerformanceGraphPanel perfGraphPanel; - - }; - -} \ No newline at end of file diff --git a/libs/ImguiExtension/panels/IrradianceVolumePanel.cpp b/libs/ImguiExtension/panels/IrradianceVolumePanel.cpp index 4a9369edd..1cdbb9f4c 100644 --- a/libs/ImguiExtension/panels/IrradianceVolumePanel.cpp +++ b/libs/ImguiExtension/panels/IrradianceVolumePanel.cpp @@ -2,6 +2,7 @@ #include "StringHelper.h" #include +#include namespace Atlas::ImguiExtension { @@ -10,130 +11,179 @@ namespace Atlas::ImguiExtension { ImGui::PushID(GetNameID()); // Read-only information - ImGui::TextDisabled("Probe count"); - ImGui::SameLine(); - ImGui::TextUnformatted(VecToString(volume->probeCount).c_str()); - ImGui::TextDisabled("Cell size"); - ImGui::SameLine(); - ImGui::TextUnformatted(VecToString(volume->cascades[0].cellSize).c_str()); - - ImGui::SeparatorText("General"); - ImGui::Checkbox("Enable volume", &volume->enable); - ImGui::Checkbox("Update volume", &volume->update); - ImGui::Checkbox("Visualize probes", &volume->debug); - - ImGui::SeparatorText("Sampling"); - ImGui::Checkbox("Sample emissives", &volume->sampleEmissives); - ImGui::Checkbox("Use shadow map", &volume->useShadowMap); - if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) { - ImGui::SetTooltip("Uses the shadow map to calculate shadows in the GI. " - "This is only possible when cascaded shadow maps are not used."); + if (UIElements::BeginProperties("IrradianceVolumeInfo")) { + UIElements::PropertyLabel("Probe count"); + ImGui::AlignTextToFramePadding(); + ImGui::TextUnformatted(VecToString(volume->probeCount).c_str()); + UIElements::PropertyLabel("Cell size"); + ImGui::AlignTextToFramePadding(); + ImGui::TextUnformatted(VecToString(volume->cascades[0].cellSize).c_str()); + UIElements::EndProperties(); } - ImGui::Checkbox("Calculate visibility", &volume->visibility); - ImGui::Checkbox("Calculate radiance", &volume->radiance); - bool prevMomentRes = volume->lowerResMoments; - ImGui::Checkbox("Lower resolution visibility", &volume->lowerResMoments); - if (prevMomentRes != volume->lowerResMoments) { - volume->SetMomentsResolution(volume->lowerResMoments); + UIElements::PropertySection("General"); + if (UIElements::BeginProperties("IrradianceVolumeGeneral")) { + UIElements::PropertyLabel("Enable volume"); + ImGui::Checkbox("##Enable volume", &volume->enable); + UIElements::PropertyLabel("Update volume"); + ImGui::Checkbox("##Update volume", &volume->update); + UIElements::PropertyLabel("Visualize probes"); + ImGui::Checkbox("##Visualize probes", &volume->debug); + UIElements::EndProperties(); } - bool prevRadianceRes = volume->lowerResRadiance; - ImGui::Checkbox("Lower resolution radiance", &volume->lowerResRadiance); - if (prevRadianceRes != volume->lowerResRadiance) { - volume->SetRadianceResolution(volume->lowerResRadiance); - } + UIElements::PropertySection("Sampling"); + if (UIElements::BeginProperties("IrradianceVolumeSampling")) { + UIElements::PropertyLabel("Calculate visibility"); + ImGui::Checkbox("##Calculate visibility", &volume->visibility); + UIElements::PropertyLabel("Calculate radiance"); + ImGui::Checkbox("##Calculate radiance", &volume->radiance); + + bool prevMomentRes = volume->lowerResMoments; + UIElements::PropertyLabel("Lower resolution visibility"); + ImGui::Checkbox("##Lower resolution visibility", &volume->lowerResMoments); + if (prevMomentRes != volume->lowerResMoments) { + volume->SetMomentsResolution(volume->lowerResMoments); + } - ImGui::Checkbox("Opacity check", &volume->opacityCheck); - - ImGui::SeparatorText("Probe grid"); - auto prevCascadeCount = volume->cascadeCount; - ImGui::SliderInt("Cascades count", &volume->cascadeCount, 1, MAX_IRRADIANCE_VOLUME_CASCADES); - - const char* gridResItems [] = { "11x11x11", "15x15x15", "21x21x21", "31x31x31" }; - int currentItem = 0; - if (volume->probeCount == glm::ivec3(11)) currentItem = 0; - if (volume->probeCount == glm::ivec3(15)) currentItem = 1; - if (volume->probeCount == glm::ivec3(21)) currentItem = 2; - if (volume->probeCount == glm::ivec3(31)) currentItem = 3; - auto prevItem = currentItem; - ImGui::Combo("Resolution", ¤tItem, gridResItems, IM_ARRAYSIZE(gridResItems)); - - if (currentItem != prevItem || prevCascadeCount != volume->cascadeCount) { - switch (currentItem) { - case 0: volume->SetProbeCount(glm::ivec3(11), volume->cascadeCount); break; - case 1: volume->SetProbeCount(glm::ivec3(15), volume->cascadeCount); break; - case 2: volume->SetProbeCount(glm::ivec3(21), volume->cascadeCount); break; - case 3: volume->SetProbeCount(glm::ivec3(31), volume->cascadeCount); break; + bool prevRadianceRes = volume->lowerResRadiance; + UIElements::PropertyLabel("Lower resolution radiance"); + ImGui::Checkbox("##Lower resolution radiance", &volume->lowerResRadiance); + if (prevRadianceRes != volume->lowerResRadiance) { + volume->SetRadianceResolution(volume->lowerResRadiance); } - } - const char* rayCountItems[] = { "32", "64", "96", "128", "256", "512" }; - currentItem = 0; - if (volume->rayCount == 32) currentItem = 0; - if (volume->rayCount == 64) currentItem = 1; - if (volume->rayCount == 96) currentItem = 2; - if (volume->rayCount == 128) currentItem = 3; - if (volume->rayCount == 256) currentItem = 4; - if (volume->rayCount == 512) currentItem = 5; - prevItem = currentItem; - ImGui::Combo("Ray count", ¤tItem, rayCountItems, IM_ARRAYSIZE(rayCountItems)); - - if (currentItem != prevItem) { - switch (currentItem) { - case 0: volume->SetRayCount(32, 16); break; - case 1: volume->SetRayCount(64, 16); break; - case 2: volume->SetRayCount(96, 16); break; - case 3: volume->SetRayCount(128, 16); break; - case 4: volume->SetRayCount(256, 16); break; - case 5: volume->SetRayCount(512, 16); break; + UIElements::PropertyLabel("Opacity check"); + ImGui::Checkbox("##Opacity check", &volume->opacityCheck); + auto reorderSupported = Graphics::GraphicsDevice::DefaultDevice->support.shaderExecutionReordering; + UIElements::PropertyLabel("Shader execution reordering"); + ImGui::BeginDisabled(!reorderSupported); + ImGui::Checkbox("##Shader execution reordering", &volume->shaderExecutionReordering); + if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) { + ImGui::SetTooltip("Sorts the rays by the mesh they hit before shading. Helps with many different meshes, " + "costs with few. Needs hit objects, which the device %s.", reorderSupported ? "supports" : "doesn't support"); } + ImGui::EndDisabled(); + UIElements::EndProperties(); } - ImGui::SliderFloat("Strength", &volume->strength, 0.0f, 5.0f); - if (ImGui::SliderFloat("Probe storage scale", &volume->storageScale, 0.000001f, 1.0f, - "%.6f", ImGuiSliderFlags_Logarithmic)) { - volume->ClearProbes(); - } - if (ImGui::IsItemHovered()) { - ImGui::SetTooltip("Smaller values increase lighting range at the cost of precision.\n" - "0.1 gives 10x range; lighting brightness is restored when sampled.\n" - "Changing this clears probe history."); - } + UIElements::PropertySection("Probe grid"); + if (UIElements::BeginProperties("IrradianceVolumeProbeGrid")) { + auto prevCascadeCount = volume->cascadeCount; + UIElements::PropertyLabel("Cascades count"); + ImGui::SliderInt("##Cascades count", &volume->cascadeCount, 1, MAX_IRRADIANCE_VOLUME_CASCADES); + + const char* gridResItems [] = { "11x11x11", "15x15x15", "21x21x21", "31x31x31" }; + int currentItem = 0; + if (volume->probeCount == ivec3(11)) currentItem = 0; + if (volume->probeCount == ivec3(15)) currentItem = 1; + if (volume->probeCount == ivec3(21)) currentItem = 2; + if (volume->probeCount == ivec3(31)) currentItem = 3; + auto prevItem = currentItem; + UIElements::PropertyLabel("Resolution"); + ImGui::Combo("##Resolution", ¤tItem, gridResItems, IM_ARRAYSIZE(gridResItems)); + + if (currentItem != prevItem || prevCascadeCount != volume->cascadeCount) { + switch (currentItem) { + case 0: volume->SetProbeCount(ivec3(11), volume->cascadeCount); break; + case 1: volume->SetProbeCount(ivec3(15), volume->cascadeCount); break; + case 2: volume->SetProbeCount(ivec3(21), volume->cascadeCount); break; + case 3: volume->SetProbeCount(ivec3(31), volume->cascadeCount); break; + } + } + + const char* rayCountItems[] = { "32", "64", "96", "128", "256", "512" }; + currentItem = 0; + if (volume->rayCount == 32) currentItem = 0; + if (volume->rayCount == 64) currentItem = 1; + if (volume->rayCount == 96) currentItem = 2; + if (volume->rayCount == 128) currentItem = 3; + if (volume->rayCount == 256) currentItem = 4; + if (volume->rayCount == 512) currentItem = 5; + prevItem = currentItem; + UIElements::PropertyLabel("Ray count"); + ImGui::Combo("##Ray count", ¤tItem, rayCountItems, IM_ARRAYSIZE(rayCountItems)); + + if (currentItem != prevItem) { + switch (currentItem) { + case 0: volume->SetRayCount(32, 16); break; + case 1: volume->SetRayCount(64, 16); break; + case 2: volume->SetRayCount(96, 16); break; + case 3: volume->SetRayCount(128, 16); break; + case 4: volume->SetRayCount(256, 16); break; + case 5: volume->SetRayCount(512, 16); break; + } + } - ImGui::SeparatorText("Volume bounds"); - ImGui::Checkbox("Scrolling", &volume->scroll); - if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) { - ImGui::SetTooltip("Scrolls the volume based on a set position (by default the camera). " - "This should be used for large scenes where the volume can't cover the whole scene"); + UIElements::PropertyLabel("Strength"); + ImGui::SliderFloat("##Strength", &volume->strength, 0.0f, 5.0f); + UIElements::PropertyLabel("Probe storage scale"); + if (ImGui::SliderFloat("##Probe storage scale", &volume->storageScale, 0.000001f, 1.0f, + "%.6f", ImGuiSliderFlags_Logarithmic)) { + volume->ClearProbes(); + } + if (ImGui::IsItemHovered()) { + ImGui::SetTooltip("Smaller values increase lighting range at the cost of precision.\n" + "0.1 gives 10x range; lighting brightness is restored when sampled.\n" + "Changing this clears probe history."); + } + UIElements::EndProperties(); } - if (volume->scroll) { - auto volumeSize = volume->aabb.GetSize(); - ImGui::DragFloat3("Size", (float*)&volumeSize, 0.5f, 1.0f, 2000.0f); - volume->aabb = volume->aabb.Scale(volumeSize / volume->aabb.GetSize()); + UIElements::PropertySection("Volume bounds"); + if (UIElements::BeginProperties("IrradianceVolumeBounds")) { + UIElements::PropertyLabel("Scrolling"); + ImGui::Checkbox("##Scrolling", &volume->scroll); + if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) { + ImGui::SetTooltip("Scrolls the volume based on a set position (by default the camera). " + "This should be used for large scenes where the volume can't cover the whole scene"); + } + + if (volume->scroll) { + auto volumeSize = volume->aabb.GetSize(); + UIElements::PropertyLabel("Size"); + ImGui::DragFloat3("##Size", (float*)&volumeSize, 0.5f, 1.0f, 2000.0f); + volume->aabb = volume->aabb.Scale(volumeSize / volume->aabb.GetSize()); + } + else { + UIElements::PropertyLabel("Min"); + ImGui::DragFloat3("##Min", (float*)&volume->aabb.min, 0.5f, -2000.0f, 2000.0f); + UIElements::PropertyLabel("Max"); + ImGui::DragFloat3("##Max", (float*)&volume->aabb.max, 0.5f, -2000.0f, 2000.0f); + } + UIElements::EndProperties(); } - else { - ImGui::DragFloat3("Min", (float*)&volume->aabb.min, 0.5f, -2000.0f, 2000.0f); - ImGui::DragFloat3("Max", (float*)&volume->aabb.max, 0.5f, -2000.0f, 2000.0f); + if (!volume->scroll) { if (ImGui::Button("Adjust to scene size", ImVec2(-FLT_MIN, 0.0f))) { volume->aabb = CalculateSceneSize(scene); } } volume->SetAABB(volume->aabb); - ImGui::SeparatorText("Filtering"); - ImGui::SliderFloat("Hysteresis", &volume->hysteresis, 0.0f, 1.0f, "%.3f"); - ImGui::SliderFloat("Sharpness", &volume->sharpness, 0.01f, 200.0f, "%.3f", ImGuiSliderFlags_Logarithmic); - ImGui::SliderFloat("Bias", &volume->bias, 0.0f, 1.0f); - auto prevGamma = volume->gamma; - ImGui::SliderFloat("Gamma exponent", &volume->gamma, 0.0f, 10.0f, "%.3f", ImGuiSliderFlags_Logarithmic); - if (prevGamma != volume->gamma) volume->ClearProbes(); - ImGui::DragFloat("Split correction", &volume->splitCorrection, 0.01f, 1.0f, 10.0f); - - ImGui::SeparatorText("Probe optimization"); - ImGui::Checkbox("Optimize probes", &volume->optimizeProbes); + UIElements::PropertySection("Filtering"); + if (UIElements::BeginProperties("IrradianceVolumeFiltering")) { + UIElements::PropertyLabel("Hysteresis"); + ImGui::SliderFloat("##Hysteresis", &volume->hysteresis, 0.0f, 1.0f, "%.3f"); + UIElements::PropertyLabel("Sharpness"); + ImGui::SliderFloat("##Sharpness", &volume->sharpness, 0.01f, 200.0f, "%.3f", ImGuiSliderFlags_Logarithmic); + UIElements::PropertyLabel("Bias"); + ImGui::SliderFloat("##Bias", &volume->bias, 0.0f, 1.0f); + auto prevGamma = volume->gamma; + UIElements::PropertyLabel("Gamma exponent"); + ImGui::SliderFloat("##Gamma exponent", &volume->gamma, 0.0f, 10.0f, "%.3f", ImGuiSliderFlags_Logarithmic); + if (prevGamma != volume->gamma) volume->ClearProbes(); + UIElements::PropertyLabel("Split correction"); + ImGui::DragFloat("##Split correction", &volume->splitCorrection, 0.01f, 1.0f, 10.0f); + UIElements::EndProperties(); + } + + UIElements::PropertySection("Probe optimization"); + if (UIElements::BeginProperties("IrradianceVolumeProbeOptimization")) { + UIElements::PropertyLabel("Optimize probes"); + ImGui::Checkbox("##Optimize probes", &volume->optimizeProbes); + UIElements::EndProperties(); + } if (ImGui::Button("Reset probe offsets", ImVec2(-FLT_MIN, 0.0f))) { volume->ResetProbeOffsets(); } @@ -144,8 +194,8 @@ namespace Atlas::ImguiExtension { Volume::AABB IrradianceVolumePanel::CalculateSceneSize(Ref& scene) const { - auto min = glm::vec3(std::numeric_limits::max()); - auto max = glm::vec3(-std::numeric_limits::max()); + auto min = vec3(std::numeric_limits::max()); + auto max = vec3(-std::numeric_limits::max()); Volume::AABB aabb(min, max); auto meshSubset = scene->GetSubset(); diff --git a/libs/ImguiExtension/panels/MaterialPanel.cpp b/libs/ImguiExtension/panels/MaterialPanel.cpp index a56d761fe..c0f5c4341 100644 --- a/libs/ImguiExtension/panels/MaterialPanel.cpp +++ b/libs/ImguiExtension/panels/MaterialPanel.cpp @@ -6,87 +6,120 @@ namespace Atlas::ImguiExtension { ImGui::PushID(GetNameID()); - auto availableWidth = ImGui::GetContentRegionAvail().x; - auto padding = 8.0f; - auto widthAfterImage = availableWidth - padding - ImGui::GetTextLineHeight(); - - auto renderWithImagePreview = [&](ResourceHandle& texture, std::function element) { + auto renderWithImagePreview = [&](ResourceHandle& texture, const char* propertiesId, + std::function element) { // If this will not be loaded it will return 0, so we can still use it ImGui::PushID(texture.GetID()); - if (texture.IsLoaded()) { + // The selector shows its own preview + if (textureSelector.has_value()) { + texture = textureSelector.value()(texture); + } + else if (texture.IsLoaded()) { UIElements::TexturePreview(wrapper, &texture); - ImGui::SameLine(); - // Calculate next item width and push a width with the image elements width substracted from it - auto width = ImGui::CalcItemWidth(); - ImGui::PushItemWidth(width - padding - ImGui::GetTextLineHeightWithSpacing()); - if (textureSelector.has_value()) { - texture = textureSelector.value()(texture); - ImGui::PopItemWidth(); - } } - else { - if (textureSelector.has_value()) - texture = textureSelector.value()(texture); + if (UIElements::BeginProperties(propertiesId)) { + element(); + UIElements::EndProperties(); } - element(); - if (texture.IsLoaded() && !textureSelector.has_value()) - ImGui::PopItemWidth(); ImGui::PopID(); }; - ImGui::SeparatorText("Base color"); - renderWithImagePreview(material->baseColorMap, [&]() { - ImGui::ColorEdit3("Base color", glm::value_ptr(material->baseColor)); + UIElements::PropertySection("Base color"); + renderWithImagePreview(material->baseColorMap, "MaterialBaseColor", [&]() { + UIElements::PropertyLabel("Base color"); + ImGui::ColorEdit3("##Base color", glm::value_ptr(material->baseColor)); }); - ImGui::SeparatorText("Emission"); - renderWithImagePreview(material->emissiveMap, [&]() { - ImGui::ColorEdit3("Emissive color", glm::value_ptr(material->emissiveColor)); - ImGui::DragFloat("Emissive intensity", &material->emissiveIntensity, 0.1f, 0.0f, 10000.0f, "%.2f"); + UIElements::PropertySection("Emission"); + renderWithImagePreview(material->emissiveMap, "MaterialEmission", [&]() { + UIElements::PropertyLabel("Emissive color"); + ImGui::ColorEdit3("##Emissive color", glm::value_ptr(material->emissiveColor)); + UIElements::PropertyLabel("Emissive intensity"); + ImGui::DragFloat("##Emissive intensity", &material->emissiveIntensity, 0.1f, 0.0f, 10000.0f, "%.2f"); }); - ImGui::SeparatorText("Opacity"); - renderWithImagePreview(material->opacityMap, [&]() { - ImGui::SliderFloat("Opacity factor", &material->opacity, 0.0f, 1.0f, "%.3f", ImGuiSliderFlags_AlwaysClamp); + UIElements::PropertySection("Opacity"); + renderWithImagePreview(material->opacityMap, "MaterialOpacity", [&]() { + UIElements::PropertyLabel("Opacity factor"); + ImGui::SliderFloat("##Opacity factor", &material->opacity, 0.0f, 1.0f, "%.3f", ImGuiSliderFlags_AlwaysClamp); }); - ImGui::SeparatorText("Normals"); - renderWithImagePreview(material->normalMap, [&]() { - ImGui::SliderFloat("Normal factor", &material->normalScale, 0.0f, 1.0f); + UIElements::PropertySection("Normals"); + renderWithImagePreview(material->normalMap, "MaterialNormals", [&]() { + UIElements::PropertyLabel("Normal factor"); + ImGui::SliderFloat("##Normal factor", &material->normalScale, 0.0f, 1.0f); }); - ImGui::SeparatorText("Roughness"); - renderWithImagePreview(material->roughnessMap, [&]() { - ImGui::SliderFloat("Roughness factor", &material->roughness, 0.0f, 1.0f, "%.3f", ImGuiSliderFlags_AlwaysClamp); + UIElements::PropertySection("Roughness"); + renderWithImagePreview(material->roughnessMap, "MaterialRoughness", [&]() { + UIElements::PropertyLabel("Roughness factor"); + ImGui::SliderFloat("##Roughness factor", &material->roughness, 0.0f, 1.0f, "%.3f", ImGuiSliderFlags_AlwaysClamp); }); - ImGui::SeparatorText("Metallic"); - renderWithImagePreview(material->metalnessMap, [&]() { - ImGui::SliderFloat("Metallic factor", &material->metalness, 0.0f, 1.0f, "%.3f", ImGuiSliderFlags_AlwaysClamp); + UIElements::PropertySection("Metallic"); + renderWithImagePreview(material->metalnessMap, "MaterialMetallic", [&]() { + UIElements::PropertyLabel("Metallic factor"); + ImGui::SliderFloat("##Metallic factor", &material->metalness, 0.0f, 1.0f, "%.3f", ImGuiSliderFlags_AlwaysClamp); }); - ImGui::SeparatorText("Ambient occlusion"); - renderWithImagePreview(material->aoMap, [&]() { - ImGui::SliderFloat("Ao factor", &material->ao, 0.0f, 1.0f, "%.3f", ImGuiSliderFlags_AlwaysClamp); + UIElements::PropertySection("Ambient occlusion"); + renderWithImagePreview(material->aoMap, "MaterialAmbientOcclusion", [&]() { + UIElements::PropertyLabel("Ao factor"); + ImGui::SliderFloat("##Ao factor", &material->ao, 0.0f, 1.0f, "%.3f", ImGuiSliderFlags_AlwaysClamp); }); - ImGui::SeparatorText("Displacement"); - renderWithImagePreview(material->displacementMap, [&]() { - ImGui::SliderFloat("Displacement scale", &material->displacementScale, 0.0f, 1.0f); + UIElements::PropertySection("Displacement"); + renderWithImagePreview(material->displacementMap, "MaterialDisplacement", [&]() { + UIElements::PropertyLabel("Displacement scale"); + ImGui::SliderFloat("##Displacement scale", &material->displacementScale, 0.0f, 1.0f); }); - ImGui::SeparatorText("Surface"); - ImGui::SliderFloat("Reflectance", &material->reflectance, 0.0f, 1.0f, "%.3f", ImGuiSliderFlags_AlwaysClamp); - - ImGui::ColorEdit3("Transmissive color", glm::value_ptr(material->transmissiveColor)); - - ImGui::Checkbox("Two sided", &material->twoSided); - - ImGui::SeparatorText("UV"); - ImGui::DragFloat2("UV animation", glm::value_ptr(material->uvAnimation), 0.01f, -1.0f, 1.0f); - ImGui::DragFloat("UV tiling", &material->tiling, 0.01f, 0.01f, 100.0f); + UIElements::PropertySection("Surface"); + if (UIElements::BeginProperties("MaterialSurface")) { + UIElements::PropertyLabel("Reflectance"); + ImGui::SliderFloat("##Reflectance", &material->reflectance, 0.0f, 1.0f, "%.3f", ImGuiSliderFlags_AlwaysClamp); + + UIElements::PropertyLabel("Two sided"); + ImGui::Checkbox("##Two sided", &material->twoSided); + UIElements::EndProperties(); + } + + UIElements::PropertySection("Transmission"); + if (UIElements::BeginProperties("MaterialTransmission")) { + UIElements::PropertyLabel("Transmitted color", "Light shining through thin surfaces like leaves or cloth, lit from " + "the back side and tinted by this color. Black lets no light through"); + ImGui::ColorEdit3("##Transmitted color", glm::value_ptr(material->transmissiveColor)); + UIElements::EndProperties(); + } + + UIElements::PropertySection("Translucency"); + if (UIElements::BeginProperties("MaterialTranslucency")) { + const char* blendModes[] = { "None", "Alpha", "Additive", "Multiply" }; + auto blendMode = int32_t(material->blendMode); + UIElements::PropertyLabel("Blend mode"); + if (ImGui::Combo("##Blend mode", &blendMode, blendModes, IM_ARRAYSIZE(blendModes))) + material->blendMode = MaterialBlendMode(blendMode); + + if (material->blendMode == MaterialBlendMode::Alpha) { + UIElements::PropertyLabel("Refractive index"); + ImGui::SliderFloat("##Refractive index", &material->refractiveIndex, 1.0f, 2.5f, "%.3f", ImGuiSliderFlags_AlwaysClamp); + UIElements::PropertyLabel("Thickness", "Above zero the surface refracts. Closed meshes refract where the rays " + "leave them through their back faces, the thickness only applies to open meshes like water planes"); + ImGui::DragFloat("##Thickness", &material->thickness, 0.001f, 0.0f, 1.0f, "%.3f m", ImGuiSliderFlags_AlwaysClamp); + } + UIElements::EndProperties(); + } + + UIElements::PropertySection("UV"); + if (UIElements::BeginProperties("MaterialUV")) { + UIElements::PropertyLabel("UV animation"); + ImGui::DragFloat2("##UV animation", glm::value_ptr(material->uvAnimation), 0.01f, -1.0f, 1.0f); + UIElements::PropertyLabel("UV tiling"); + ImGui::DragFloat("##UV tiling", &material->tiling, 0.01f, 0.01f, 100.0f); + UIElements::EndProperties(); + } ImGui::PopID(); diff --git a/libs/ImguiExtension/panels/MaterialsPanel.cpp b/libs/ImguiExtension/panels/MaterialsPanel.cpp index e7a4b8483..7d793345d 100644 --- a/libs/ImguiExtension/panels/MaterialsPanel.cpp +++ b/libs/ImguiExtension/panels/MaterialsPanel.cpp @@ -8,11 +8,13 @@ namespace Atlas::ImguiExtension { void MaterialsPanel::Render(Ref& wrapper, std::vector>& materials, - MaterialSelector materialSelector, MaterialPanel::TextureSelector textureSelector) { + MaterialSelector materialSelector, MaterialPanel::TextureSelector textureSelector, + GraphMaterialRenderer graphMaterialRenderer) { ImGui::PushID(GetNameID()); - ImGui::InputTextWithHint("Search", "Type to search material", &materialSearch); + ImGui::SetNextItemWidth(-FLT_MIN); + ImGui::InputTextWithHint("##Search", "Search materials...", &materialSearch); auto matches = materials | std::views::filter( [&](const ResourceHandle& material) { @@ -41,18 +43,25 @@ namespace Atlas::ImguiExtension { auto nodeID = GetNameID() + std::to_string(counter); materialName += "###" + nodeID; - if (ImGui::TreeNode(materialName.c_str())) { - if (materialSelector.has_value()) { - material = materialSelector.value()(material); - ImGui::Separator(); + if (UIElements::BeginPropertyGroup(materialName.c_str())) { + if (ImGui::TreeNodeEx(materialName.c_str(), UIElements::PropertyGroupHeaderFlags())) { + UIElements::BeginPropertyContent(); + if (materialSelector.has_value()) { + material = materialSelector.value()(material); + ImGui::Separator(); + } + // Might be deleted above + if (material.IsLoaded() && material->HasGraph() && graphMaterialRenderer.has_value()) { + graphMaterialRenderer.value()(material.Get()); + } + else if (material.IsLoaded()) { + materialPanel.Render(wrapper, material.Get(), textureSelector); + } + UIElements::EndPropertyContent(); + + ImGui::TreePop(); } - // Might be deleted above - if (material.IsLoaded()) { - materialPanel.Render(wrapper, material.Get(), textureSelector); - } - - ImGui::TreePop(); - + UIElements::EndPropertyGroup(); } ImGui::PopID(); @@ -68,7 +77,8 @@ namespace Atlas::ImguiExtension { ImGui::PushID(GetNameID()); - ImGui::InputTextWithHint("Search", "Type to search material", &materialSearch); + ImGui::SetNextItemWidth(-FLT_MIN); + ImGui::InputTextWithHint("##Search", "Search materials...", &materialSearch); auto matches = materials | std::views::filter( [&](const Ref& material) { @@ -85,12 +95,15 @@ namespace Atlas::ImguiExtension { auto nodeID = GetNameID() + std::to_string(counter); materialName += "###" + nodeID; - if (ImGui::TreeNode(materialName.c_str())) { - - materialPanel.Render(wrapper, material, textureSelector); - - ImGui::TreePop(); + if (UIElements::BeginPropertyGroup(materialName.c_str())) { + if (ImGui::TreeNodeEx(materialName.c_str(), UIElements::PropertyGroupHeaderFlags())) { + UIElements::BeginPropertyContent(); + materialPanel.Render(wrapper, material, textureSelector); + UIElements::EndPropertyContent(); + ImGui::TreePop(); + } + UIElements::EndPropertyGroup(); } ImGui::PopID(); diff --git a/libs/ImguiExtension/panels/MaterialsPanel.h b/libs/ImguiExtension/panels/MaterialsPanel.h index f6c259175..a70f5178c 100644 --- a/libs/ImguiExtension/panels/MaterialsPanel.h +++ b/libs/ImguiExtension/panels/MaterialsPanel.h @@ -12,12 +12,15 @@ namespace Atlas::ImguiExtension { class MaterialsPanel : public Panel { using MaterialSelector = std::optional(ResourceHandle)>>; + // Renders a material with a graph instead of the properties, e.g. with the parameters of the graph + using GraphMaterialRenderer = std::optional&)>>; public: MaterialsPanel() : Panel("Materials properties") {} void Render(Ref& wrapper, std::vector>& materials, - MaterialSelector materialSelector = {}, MaterialPanel::TextureSelector textureSelector = {}); + MaterialSelector materialSelector = {}, MaterialPanel::TextureSelector textureSelector = {}, + GraphMaterialRenderer graphMaterialRenderer = {}); void Render(Ref& wrapper, std::vector>& materials, MaterialPanel::TextureSelector textureSelector = {}); diff --git a/libs/ImguiExtension/panels/OceanPanel.cpp b/libs/ImguiExtension/panels/OceanPanel.cpp new file mode 100644 index 000000000..ebc99ca7a --- /dev/null +++ b/libs/ImguiExtension/panels/OceanPanel.cpp @@ -0,0 +1,165 @@ +#include "OceanPanel.h" + +#include "ocean/OceanSerializer.h" + +namespace Atlas::ImguiExtension { + + void OceanPanel::Render(Ref& ocean, TextureSelector textureSelector) { + + ImGui::PushID(GetNameID()); + + auto& simulation = ocean->simulation; + + if (UIElements::BeginProperties("OceanGeneral")) { + UIElements::PropertyLabel("Enable"); + ImGui::Checkbox("##Enable", &ocean->enable); + UIElements::PropertyLabel("Underwater shader"); + ImGui::Checkbox("##Underwater shader", &ocean->underwaterShader); + UIElements::PropertyLabel("Wireframe"); + ImGui::Checkbox("##Wireframe", &ocean->wireframe); + UIElements::PropertyLabel("Translation"); + ImGui::DragFloat3("##Translation", glm::value_ptr(ocean->translation), 0.1f); + UIElements::EndProperties(); + } + + // Changing these recreates the ocean, the other settings are kept + UIElements::PropertySection("Resolution"); + int32_t LoDCount = ocean->GetLoDCount(); + float size = ocean->sideLength; + int32_t N = simulation.N; + + bool recreate = false; + if (UIElements::BeginProperties("OceanResolution")) { + const char* resolutions[] = { "128", "256", "512", "1024" }; + int32_t resolutionIdx = glm::clamp(int32_t(log2f(float(N))) - 7, 0, 3); + UIElements::PropertyLabel("Simulation resolution"); + if (ImGui::Combo("##Simulation resolution", &resolutionIdx, resolutions, IM_ARRAYSIZE(resolutions))) { + N = 128 << resolutionIdx; + recreate = true; + } + UIElements::PropertyLabel("Size"); + recreate |= ImGui::DragFloat("##Size", &size, 16.0f, 64.0f, 65536.0f, "%.0f m"); + UIElements::PropertyLabel("LoD count"); + recreate |= ImGui::DragInt("##LoD count", &LoDCount, 0.1f, 1, 12); + UIElements::EndProperties(); + } + + if (recreate) { + json j = *ocean; + j["LoDCount"] = LoDCount; + j["size"] = size; + j["N"] = N; + ocean = CreateRef(j.get()); + } + + UIElements::PropertySection("Waves"); + if (UIElements::BeginProperties("OceanWaves")) { + bool spectrumChanged = false; + UIElements::PropertyLabel("Wave amplitude"); + spectrumChanged |= ImGui::DragFloat("##Wave amplitude", &simulation.waveAmplitude, 0.00001f, + 0.0f, 0.01f, "%.6f"); + UIElements::PropertyLabel("Small wave surpression"); + spectrumChanged |= ImGui::DragFloat("##Small wave surpression", &simulation.waveSurpression, 0.0001f, + 0.0f, 1.0f, "%.4f"); + UIElements::PropertyLabel("Wind direction"); + spectrumChanged |= ImGui::DragFloat2("##Wind direction", glm::value_ptr(simulation.windDirection), + 0.01f, -1.0f, 1.0f); + UIElements::PropertyLabel("Wind speed"); + spectrumChanged |= ImGui::DragFloat("##Wind speed", &simulation.windSpeed, 0.1f, 0.5f, 40.0f, "%.1f m/s"); + UIElements::PropertyLabel("Wind dependency", "Strength of the waves running against the wind"); + spectrumChanged |= ImGui::SliderFloat("##Wind dependency", &simulation.windDependency, 0.0f, 1.0f); + if (spectrumChanged) + simulation.UpdateSpectrum(); + + UIElements::PropertyLabel("Displacement scale"); + ImGui::DragFloat("##Displacement scale", &ocean->displacementScale, 0.01f, 0.0f, 4.0f); + UIElements::PropertyLabel("Choppyness scale"); + ImGui::DragFloat("##Choppyness scale", &ocean->choppynessScale, 0.01f, 0.0f, 2.0f); + UIElements::PropertyLabel("Patch size", "Size of the smallest cascade, the others are scaled by their tiling factors"); + ImGui::DragFloat("##Patch size", &ocean->tiling, 0.1f, 1.0f, 1024.0f, "%.1f m"); + UIElements::PropertyLabel("Simulation speed"); + ImGui::DragFloat("##Simulation speed", &simulation.simulationSpeed, 0.01f, 0.0f, 10.0f); + UIElements::PropertyLabel("Update simulation"); + ImGui::Checkbox("##Update simulation", &simulation.update); + UIElements::PropertyLabel("Normals from FFT"); + ImGui::Checkbox("##Normals from FFT", &simulation.fftNormals); + UIElements::EndProperties(); + } + + UIElements::PropertySection("Spectrum cascades"); + if (UIElements::BeginProperties("OceanSpectrumCascades")) { + UIElements::PropertyLabel("Tiling factors"); + ImGui::DragFloat4("##Tiling factors", glm::value_ptr(simulation.spectrumTilingFactors), 0.1f, 0.1f, 100.0f); + UIElements::PropertyLabel("Weights"); + ImGui::DragFloat4("##Weights", glm::value_ptr(simulation.spectrumWeights), 0.01f, 0.0f, 1.0f); + UIElements::PropertyLabel("Fadeout distances"); + ImGui::DragFloat4("##Fadeout distances", glm::value_ptr(simulation.spectrumFadeoutDistances), + 10.0f, 0.0f, 100000.0f, "%.0f"); + UIElements::EndProperties(); + } + + if (textureSelector.has_value()) { + UIElements::PropertySection("Ripple normal map"); + ImGui::PushID("Ripple"); + ocean->rippleTexture = textureSelector.value()(ocean->rippleTexture); + ImGui::PopID(); + } + + UIElements::PropertySection("Foam"); + if (textureSelector.has_value()) { + ImGui::PushID("Foam"); + ocean->foamTexture = textureSelector.value()(ocean->foamTexture); + ImGui::PopID(); + } + if (UIElements::BeginProperties("OceanFoam")) { + UIElements::PropertyLabel("Foam offset"); + ImGui::DragFloat("##Foam offset", &simulation.foamOffset, 0.01f, -1.0f, 1.0f); + UIElements::PropertyLabel("Foam scale"); + ImGui::DragFloat("##Foam scale", &simulation.foamScale, 0.01f, 0.0f, 10.0f); + UIElements::PropertyLabel("Foam size"); + ImGui::DragFloat("##Foam size", &simulation.foamSize, 0.01f, 0.0f, 20.0f); + UIElements::EndProperties(); + } + + UIElements::PropertySection("Water color"); + if (UIElements::BeginProperties("OceanWaterColor")) { + UIElements::PropertyLabel("Water body color"); + ImGui::ColorEdit3("##Water body color", glm::value_ptr(ocean->waterBodyColor)); + UIElements::PropertyLabel("Scatter color"); + ImGui::ColorEdit3("##Scatter color", glm::value_ptr(ocean->scatterColor)); + UIElements::PropertyLabel("Water color intensity"); + ImGui::DragFloat2("##Water color intensity", glm::value_ptr(ocean->waterColorIntensity), 0.01f, 0.0f, 10.0f); + UIElements::EndProperties(); + } + + UIElements::PropertySection("Shore waves"); + if (UIElements::BeginProperties("OceanShoreWaves")) { + UIElements::PropertyLabel("Distance offset"); + ImGui::DragFloat("##Distance offset", &ocean->shoreWaveDistanceOffset, 0.5f, 0.0f, 1000.0f); + UIElements::PropertyLabel("Distance scale"); + ImGui::DragFloat("##Distance scale", &ocean->shoreWaveDistanceScale, 0.5f, 0.0f, 1000.0f); + UIElements::PropertyLabel("Amplitude"); + ImGui::DragFloat("##Amplitude", &ocean->shoreWaveAmplitude, 0.01f, 0.0f, 10.0f); + UIElements::PropertyLabel("Steepness"); + ImGui::DragFloat("##Steepness", &ocean->shoreWaveSteepness, 0.01f, 0.0f, 10.0f); + UIElements::PropertyLabel("Power"); + ImGui::DragFloat("##Power", &ocean->shoreWavePower, 0.01f, 0.0f, 10.0f); + UIElements::PropertyLabel("Speed"); + ImGui::DragFloat("##Speed", &ocean->shoreWaveSpeed, 0.01f, 0.0f, 50.0f); + UIElements::PropertyLabel("Length"); + ImGui::DragFloat("##Length", &ocean->shoreWaveLength, 0.01f, 0.0f, 50.0f); + UIElements::EndProperties(); + } + + UIElements::PropertySection("Physics"); + if (UIElements::BeginProperties("OceanPhysics")) { + UIElements::PropertyLabel("Enable physics", "Bodies with buoyancy float on the waves and scripts can query the surface"); + ImGui::Checkbox("##Enable physics", &ocean->physics); + UIElements::EndProperties(); + } + + ImGui::PopID(); + + } + +} diff --git a/libs/ImguiExtension/panels/OceanPanel.h b/libs/ImguiExtension/panels/OceanPanel.h new file mode 100644 index 000000000..abbbc0ff1 --- /dev/null +++ b/libs/ImguiExtension/panels/OceanPanel.h @@ -0,0 +1,23 @@ +#pragma once + +#include "Panel.h" + +#include "ocean/Ocean.h" + +#include +#include + +namespace Atlas::ImguiExtension { + + class OceanPanel : public Panel { + + public: + OceanPanel() : Panel("Ocean properties") {} + + using TextureSelector = std::optional(ResourceHandle)>>; + + void Render(Ref& ocean, TextureSelector textureSelector = {}); + + }; + +} diff --git a/libs/ImguiExtension/panels/PerformanceGraphPanel.cpp b/libs/ImguiExtension/panels/PerformanceGraphPanel.cpp index 5353b058e..b8e306698 100644 --- a/libs/ImguiExtension/panels/PerformanceGraphPanel.cpp +++ b/libs/ImguiExtension/panels/PerformanceGraphPanel.cpp @@ -1,6 +1,6 @@ #include "PerformanceGraphPanel.h" -#include "graphics/Profiler.h" +#include "profiler/GPUProfiler.h" #include "Clock.h" namespace Atlas::ImguiExtension { @@ -57,14 +57,14 @@ namespace Atlas::ImguiExtension { void PerformanceGraphPanel::UpdateGraphData() { - auto gpuProfilerData = Graphics::Profiler::GetQueries(Graphics::Profiler::OrderBy::MAX_TIME); + auto gpuProfilerData = GPUProfiler::GetQueries(GPUProfiler::OrderBy::MAX_TIME); double slowestTime = 0.0; for (int32_t i = 0; i < int32_t(gpuProfilerData.size()); i++) { const auto& threadData = gpuProfilerData[i]; double threadTime = 0.0; for (const auto& query : threadData.queries) { - threadTime += query.timer.elapsedTime; + threadTime += query.elapsedTime; } if (threadTime > slowestTime) { slowestTime = threadTime; diff --git a/libs/ImguiExtension/panels/PostProcessingPanel.cpp b/libs/ImguiExtension/panels/PostProcessingPanel.cpp index e538cbdfa..acc61d1be 100644 --- a/libs/ImguiExtension/panels/PostProcessingPanel.cpp +++ b/libs/ImguiExtension/panels/PostProcessingPanel.cpp @@ -7,75 +7,148 @@ namespace Atlas::ImguiExtension { ImGui::PushID(GetNameID()); // Settings of disabled effects are shown, but greyed out - ImGui::SeparatorText("Anti-aliasing and upscaling"); - ImGui::Checkbox("Temporal anti-aliasing##TAA", &postProcessing.taa.enable); - ImGui::BeginDisabled(!postProcessing.taa.enable); - ImGui::SliderFloat("Jitter range", &postProcessing.taa.jitterRange, 0.001f, 0.999f); - ImGui::EndDisabled(); - ImGui::Checkbox("FSR2##FSR2", &postProcessing.fsr2); + UIElements::PropertySection("Anti-aliasing and upscaling"); + if (UIElements::BeginProperties("PostProcessingUpscaling")) { + if (showUpscaler) + RenderUpscalerSelection(postProcessing.upscaler, isUpscalerSupported, true); + ImGui::BeginDisabled(postProcessing.upscaler == PostProcessing::Upscaler::None); + UIElements::PropertyLabel("Jitter range"); + ImGui::SliderFloat("##Jitter range", &postProcessing.taa.jitterRange, 0.001f, 0.999f); + ImGui::EndDisabled(); + UIElements::EndProperties(); + } - ImGui::SeparatorText("Sharpen filter"); - ImGui::Checkbox("Enable##Sharpen", &postProcessing.sharpen.enable); - ImGui::BeginDisabled(!postProcessing.sharpen.enable); - ImGui::SliderFloat("Sharpness", &postProcessing.sharpen.factor, 0.0f, 1.0f); - ImGui::EndDisabled(); + UIElements::PropertySection("Sharpen filter"); + if (UIElements::BeginProperties("PostProcessingSharpen")) { + UIElements::PropertyLabel("Enable"); + ImGui::Checkbox("##Enable", &postProcessing.sharpen.enable); + ImGui::BeginDisabled(!postProcessing.sharpen.enable); + UIElements::PropertyLabel("Sharpness"); + ImGui::SliderFloat("##Sharpness", &postProcessing.sharpen.factor, 0.0f, 1.0f); + ImGui::EndDisabled(); + UIElements::EndProperties(); + } - ImGui::SeparatorText("Image effects"); - ImGui::SliderFloat("Exposure compensation (EV)", &postProcessing.exposureCompensation, -10.0f, 10.0f); - ImGui::Checkbox("Filmic tonemapping", &postProcessing.filmicTonemapping); - ImGui::ColorEdit3("Tint", glm::value_ptr(postProcessing.tint)); - ImGui::SliderFloat("Saturation", &postProcessing.saturation, 0.0f, 2.0f); - ImGui::SliderFloat("Contrast", &postProcessing.contrast, 0.0f, 2.0f); - ImGui::SliderFloat("Paper white luminance", &postProcessing.paperWhiteLuminance, 0.0f, 300.0f); - ImGui::SliderFloat("Maximum screen luminance", &postProcessing.screenMaxLuminance, 0.0f, 2000.0f); - - ImGui::SeparatorText("Chromatic aberration"); - ImGui::Checkbox("Enable##Chromatic aberration", &postProcessing.chromaticAberration.enable); - ImGui::BeginDisabled(!postProcessing.chromaticAberration.enable); - ImGui::Checkbox("Colors reversed", &postProcessing.chromaticAberration.colorsReversed); - ImGui::SliderFloat("Strength##Chromatic abberation", &postProcessing.chromaticAberration.strength, 0.0f, 4.0f); - ImGui::EndDisabled(); + UIElements::PropertySection("Image effects"); + if (UIElements::BeginProperties("PostProcessingImageEffects")) { + UIElements::PropertyLabel("Exposure compensation (EV)"); + ImGui::SliderFloat("##Exposure compensation (EV)", &postProcessing.exposureCompensation, -10.0f, 10.0f); + UIElements::PropertyLabel("Filmic tonemapping"); + ImGui::Checkbox("##Filmic tonemapping", &postProcessing.filmicTonemapping); + UIElements::PropertyLabel("Tint", "Multiplies the linear colors before tone mapping, bright surfaces stay white"); + ImGui::ColorEdit3("##Tint", glm::value_ptr(postProcessing.tint)); + UIElements::PropertyLabel("Saturation"); + ImGui::SliderFloat("##Saturation", &postProcessing.saturation, 0.0f, 2.0f); + UIElements::PropertyLabel("Contrast"); + ImGui::SliderFloat("##Contrast", &postProcessing.contrast, 0.0f, 2.0f); + UIElements::PropertyLabel("Paper white luminance"); + ImGui::SliderFloat("##Paper white luminance", &postProcessing.paperWhiteLuminance, 0.0f, 300.0f); + UIElements::PropertyLabel("Maximum screen luminance"); + ImGui::SliderFloat("##Maximum screen luminance", &postProcessing.screenMaxLuminance, 0.0f, 2000.0f); + UIElements::EndProperties(); + } - ImGui::SeparatorText("Film grain"); - ImGui::Checkbox("Enable##Film grain", &postProcessing.filmGrain.enable); - ImGui::BeginDisabled(!postProcessing.filmGrain.enable); - ImGui::SliderFloat("Strength##Film grain", &postProcessing.filmGrain.strength, 0.0f, 1.0f); - ImGui::EndDisabled(); + UIElements::PropertySection("Chromatic aberration"); + if (UIElements::BeginProperties("PostProcessingChromaticAberration")) { + UIElements::PropertyLabel("Enable"); + ImGui::Checkbox("##Enable", &postProcessing.chromaticAberration.enable); + ImGui::BeginDisabled(!postProcessing.chromaticAberration.enable); + UIElements::PropertyLabel("Colors reversed"); + ImGui::Checkbox("##Colors reversed", &postProcessing.chromaticAberration.colorsReversed); + UIElements::PropertyLabel("Strength"); + ImGui::SliderFloat("##Strength", &postProcessing.chromaticAberration.strength, 0.0f, 4.0f); + ImGui::EndDisabled(); + UIElements::EndProperties(); + } - ImGui::SeparatorText("Vignette"); - ImGui::Checkbox("Enable##Vignette", &postProcessing.vignette.enable); - ImGui::BeginDisabled(!postProcessing.vignette.enable); - ImGui::ColorEdit3("Color##Vignette", glm::value_ptr(postProcessing.vignette.color)); - ImGui::SliderFloat("Strength##Vignette", &postProcessing.vignette.strength, 0.0f, 1.0f); - ImGui::SliderFloat("Power##Vignette", &postProcessing.vignette.power, 0.0f, 10.0f); - ImGui::SliderFloat("Offset##Vignette", &postProcessing.vignette.offset, -1.0f, 1.0f); - ImGui::EndDisabled(); + UIElements::PropertySection("Film grain"); + if (UIElements::BeginProperties("PostProcessingFilmGrain")) { + UIElements::PropertyLabel("Enable"); + ImGui::Checkbox("##Enable", &postProcessing.filmGrain.enable); + ImGui::BeginDisabled(!postProcessing.filmGrain.enable); + UIElements::PropertyLabel("Strength"); + ImGui::SliderFloat("##Strength", &postProcessing.filmGrain.strength, 0.0f, 1.0f); + ImGui::EndDisabled(); + UIElements::EndProperties(); + } + + UIElements::PropertySection("Vignette"); + if (UIElements::BeginProperties("PostProcessingVignette")) { + UIElements::PropertyLabel("Enable"); + ImGui::Checkbox("##Enable", &postProcessing.vignette.enable); + ImGui::BeginDisabled(!postProcessing.vignette.enable); + UIElements::PropertyLabel("Color"); + ImGui::ColorEdit3("##Color", glm::value_ptr(postProcessing.vignette.color)); + UIElements::PropertyLabel("Strength"); + ImGui::SliderFloat("##Strength", &postProcessing.vignette.strength, 0.0f, 1.0f); + UIElements::PropertyLabel("Power"); + ImGui::SliderFloat("##Power", &postProcessing.vignette.power, 0.0f, 10.0f); + UIElements::PropertyLabel("Offset"); + ImGui::SliderFloat("##Offset", &postProcessing.vignette.offset, -1.0f, 1.0f); + ImGui::EndDisabled(); + UIElements::EndProperties(); + } - ImGui::SeparatorText("Bloom"); - ImGui::Checkbox("Enable##Bloom", &postProcessing.bloom.enable); + UIElements::PropertySection("Bloom"); + if (UIElements::BeginProperties("PostProcessingBloomEnable")) { + UIElements::PropertyLabel("Enable"); + ImGui::Checkbox("##Enable", &postProcessing.bloom.enable); + UIElements::EndProperties(); + } ImGui::BeginDisabled(!postProcessing.bloom.enable); if (textureSelector.has_value()) postProcessing.bloom.dirtMap = textureSelector.value()(postProcessing.bloom.dirtMap); - ImGui::DragFloat("Strength##Bloom", &postProcessing.bloom.strength, 0.001f, 0.0f, 1.0f); - ImGui::DragFloat("Dirt strength##Bloom", &postProcessing.bloom.dirtStrength, 0.01f, 0.0f, 10.0f); - ImGui::DragFloat("Threshold##Bloom", &postProcessing.bloom.threshold, 0.01f, 0.0f, 10.0f); - ImGui::DragFloat("Filter size##Bloom", &postProcessing.bloom.filterSize, 0.001f, 0.0f, 1.0f); - auto mipLevels = int32_t(postProcessing.bloom.mipLevels); - ImGui::DragInt("Mip levels##Bloom", &mipLevels, 1, 2, 12); - postProcessing.bloom.mipLevels = mipLevels; + if (UIElements::BeginProperties("PostProcessingBloom")) { + UIElements::PropertyLabel("Strength"); + ImGui::DragFloat("##Strength", &postProcessing.bloom.strength, 0.001f, 0.0f, 1.0f); + UIElements::PropertyLabel("Dirt strength"); + ImGui::DragFloat("##Dirt strength", &postProcessing.bloom.dirtStrength, 0.01f, 0.0f, 10.0f); + UIElements::PropertyLabel("Threshold"); + ImGui::DragFloat("##Threshold", &postProcessing.bloom.threshold, 0.01f, 0.0f, 10.0f); + UIElements::PropertyLabel("Filter size"); + ImGui::DragFloat("##Filter size", &postProcessing.bloom.filterSize, 0.001f, 0.0f, 1.0f); + auto mipLevels = int32_t(postProcessing.bloom.mipLevels); + UIElements::PropertyLabel("Mip levels"); + ImGui::DragInt("##Mip levels", &mipLevels, 1, 2, 12); + postProcessing.bloom.mipLevels = mipLevels; + UIElements::EndProperties(); + } ImGui::EndDisabled(); - ImGui::SeparatorText("Auto-exposure"); - ImGui::Checkbox("Enable##Exposure", &postProcessing.autoExposure.enable); - ImGui::BeginDisabled(!postProcessing.autoExposure.enable); - ImGui::DragFloat("Min luminance##Exposure", &postProcessing.autoExposure.luminanceMin, 0.0005f, 0.00001f, 1000.0f, "%.4f"); - ImGui::DragFloat("Max luminance##Exposure", &postProcessing.autoExposure.luminanceMax, 0.1f, 0.0f, 1000.0f, "%.4f"); - ImGui::DragFloat("Black level##Exposure", &postProcessing.autoExposure.blackLevel, 0.000001f, 0.0f, 1.0f, "%.6f"); - ImGui::DragFloat("Time coefficient##Exposure", &postProcessing.autoExposure.timeCoefficient, 0.01f, 0.0f, 10.0f); - ImGui::EndDisabled(); + UIElements::PropertySection("Auto-exposure"); + if (UIElements::BeginProperties("PostProcessingAutoExposure")) { + UIElements::PropertyLabel("Enable"); + ImGui::Checkbox("##Enable", &postProcessing.autoExposure.enable); + ImGui::BeginDisabled(!postProcessing.autoExposure.enable); + UIElements::PropertyLabel("Min luminance"); + ImGui::DragFloat("##Min luminance", &postProcessing.autoExposure.luminanceMin, 0.0005f, 0.00001f, 1000.0f, "%.4f"); + UIElements::PropertyLabel("Max luminance"); + ImGui::DragFloat("##Max luminance", &postProcessing.autoExposure.luminanceMax, 10.0f, + postProcessing.autoExposure.luminanceMin, 1000000.0f, "%.1f", ImGuiSliderFlags_Logarithmic); + UIElements::PropertyLabel("Black level"); + ImGui::DragFloat("##Black level", &postProcessing.autoExposure.blackLevel, 0.000001f, 0.0f, 1.0f, "%.6f"); + UIElements::PropertyLabel("Time coefficient"); + ImGui::DragFloat("##Time coefficient", &postProcessing.autoExposure.timeCoefficient, 0.01f, 0.0f, 10.0f); + ImGui::EndDisabled(); + UIElements::EndProperties(); + } ImGui::PopID(); } + void PostProcessingPanel::RenderUpscalerSelection(PostProcessing::Upscaler& upscaler, + const std::function& isSupported, bool inProperties) { + + const auto& names = PostProcessing::PostProcessing::upscalerNames; + auto selected = static_cast(upscaler); + if (inProperties) + UIElements::PropertyLabel("Upscaler"); + if (ImGui::Combo(inProperties ? "##Upscaler" : "Upscaler", &selected, names, IM_ARRAYSIZE(names))) + upscaler = static_cast(selected); + if (isSupported && !isSupported(upscaler)) + ImGui::TextDisabled("Not available on this device, FSR 2 is used instead"); + + } + } diff --git a/libs/ImguiExtension/panels/PostProcessingPanel.h b/libs/ImguiExtension/panels/PostProcessingPanel.h index 1da21855a..099c860d6 100644 --- a/libs/ImguiExtension/panels/PostProcessingPanel.h +++ b/libs/ImguiExtension/panels/PostProcessingPanel.h @@ -15,6 +15,15 @@ namespace Atlas::ImguiExtension { void Render(PostProcessing::PostProcessing& postProcessing, TextureSelector textureSelector = {}); + // Unsupported upscalers fall back to FSR2, the selection tells this when isSupported is set. Inside a properties + // table the label goes into its own column, otherwise ImGui draws it to the right + static void RenderUpscalerSelection(PostProcessing::Upscaler& upscaler, + const std::function& isSupported, bool inProperties); + + std::function isUpscalerSupported; + // Hosts with the upscaler in other settings, e.g. the project settings of the editor, hide it here + bool showUpscaler = true; + }; } \ No newline at end of file diff --git a/libs/ImguiExtension/panels/ProfilerPanel.cpp b/libs/ImguiExtension/panels/ProfilerPanel.cpp new file mode 100644 index 000000000..f7cf51d68 --- /dev/null +++ b/libs/ImguiExtension/panels/ProfilerPanel.cpp @@ -0,0 +1,476 @@ +#include "ProfilerPanel.h" +#include "common/MathHelper.h" + +#include "profiler/CPUProfiler.h" +#include "profiler/GPUProfiler.h" +#include "Clock.h" + +#include +#include +#include + +namespace Atlas::ImguiExtension { + + void ProfilerPanel::Refresh() { + + auto order = GetOrder(); + if (Clock::Get() - lastRefreshTime < 0.25f && order == refreshedOrder && lastRefreshTime >= 0.0f) + return; + lastRefreshTime = Clock::Get(); + refreshedOrder = order; + + // The main and the render thread come first and are open, the workers are listed collapsed + cpuThreads = CPUProfiler::enable ? CPUProfiler::GetQueriesAverage(64, order) : std::vector(); + std::stable_partition(cpuThreads.begin(), cpuThreads.end(), [](const auto& thread) { + return thread.name == "Main" || thread.name == "Render"; + }); + gpuThreads = GPUProfiler::enable ? GPUProfiler::GetQueriesAverage(64, order) : std::vector(); + + } + + void ProfilerPanel::Render() { + + Refresh(); + ImGui::PushID(GetNameID()); + + if (ImGui::BeginTabBar("Profilers")) { + if (ImGui::BeginTabItem("CPU")) { + if (RenderControls(CPUProfiler::enable, false)) + RenderTable(cpuThreads, false); + ImGui::EndTabItem(); + } + if (ImGui::BeginTabItem("GPU")) { + if (RenderControls(GPUProfiler::enable, true)) { + if (showGraph) + perfGraphPanel.Render(); + else + RenderTable(gpuThreads, true); + } + ImGui::EndTabItem(); + } + if (ImGui::BeginTabItem("Hitches")) { + RenderHitches(); + ImGui::EndTabItem(); + } + ImGui::EndTabBar(); + } + + ImGui::PopID(); + + } + + bool ProfilerPanel::RenderControls(std::atomic_bool& enable, bool graph) { + + bool enabled = enable; + ImGui::Checkbox("Enable##Profiler", &enabled); + enable = enabled; + + if (graph) { + ImGui::SameLine(); + ImGui::Checkbox("Show graph##Profiler", &showGraph); + } + + if (!graph || !showGraph) { + const char* items[] = { "Chronologically", "Max time", "Min time", "Alphabetically" }; + ImGui::SameLine(); + ImGui::SetNextItemWidth(std::min(ImGui::GetContentRegionAvail().x * 0.5f, ImGui::GetFontSize() * 10.0f)); + ImGui::Combo("Sort##Profiler", &sortItem, items, IM_ARRAYSIZE(items)); + } + + if (!enabled) + ImGui::TextDisabled("The profiler is disabled, enable it to collect timings"); + + return enabled; + + } + + void ProfilerPanel::RenderHitches() { + + auto settings = HitchRecorder::GetSettings(); + auto settingsChanged = false; + + // The revision is read first, a hitch recorded meanwhile is copied in the next frame + auto revision = HitchRecorder::GetRevision(); + if (revision != hitchRevision) { + hitchRevision = revision; + hitches = HitchRecorder::GetHitches(); + hitchSummary = HitchRecorder::Evaluate(hitches); + } + + settingsChanged |= ImGui::Checkbox("Record##Hitches", &settings.enable); + ImGui::SameLine(); + if (ImGui::Button("Clear##Hitches")) + HitchRecorder::Clear(); + ImGui::SameLine(); + settingsChanged |= ImGui::Checkbox("Log##Hitches", &settings.log); + ImGui::SameLine(); + ImGui::TextDisabled("%d hitches", int32_t(hitches.size())); + + // Wide panels show the hitches and their causes next to the profile of the selected hitch + auto sideBySide = ImGui::GetContentRegionAvail().x >= ImGui::GetFontSize() * 50.0f; + + if (ImGui::CollapsingHeader("Detection##Hitches")) + settingsChanged |= RenderHitchSettings(settings, sideBySide); + + if (settingsChanged) + HitchRecorder::SetSettings(settings); + + if (!sideBySide) { + if (ImGui::CollapsingHeader("Causes##Hitches", ImGuiTreeNodeFlags_DefaultOpen)) + RenderHitchSummary(0.0f); + RenderHitchList(0.0f, settings.enable); + RenderHitchDetails(); + return; + } + + ImGuiTableFlags flags = ImGuiTableFlags_Resizable | ImGuiTableFlags_BordersInnerV | ImGuiTableFlags_SizingStretchProp; + if (ImGui::BeginTable("HitchLayout", 2, flags, ImVec2(0.0f, ImGui::GetContentRegionAvail().y))) { + ImGui::TableSetupColumn("Hitches", ImGuiTableColumnFlags_WidthStretch, 1.0f); + ImGui::TableSetupColumn("Profile", ImGuiTableColumnFlags_WidthStretch, 1.0f); + ImGui::TableNextRow(); + + ImGui::TableNextColumn(); + auto height = ImGui::GetContentRegionAvail().y; + ImGui::BeginChild("Hitches", ImVec2(0.0f, height)); + auto listHeight = std::floor(ImGui::GetContentRegionAvail().y * 0.55f); + RenderHitchList(listHeight, settings.enable); + ImGui::SeparatorText("Causes"); + RenderHitchSummary(ImGui::GetContentRegionAvail().y); + ImGui::EndChild(); + + ImGui::TableNextColumn(); + ImGui::BeginChild("Profile", ImVec2(0.0f, height)); + RenderHitchDetails(); + ImGui::EndChild(); + + ImGui::EndTable(); + } + + } + + bool ProfilerPanel::RenderHitchSettings(HitchRecorder::Settings& settings, bool sideBySide) { + + auto changed = false; + // The render thread metric needs a render thread + auto hasRenderThread = CPUProfiler::GetThreadTime("Render") > 0.0f; + + const char* triggers[] = { "Above minimum", "Above average", "Above minimum and average" }; + + auto renderDetector = [&](const char* label, HitchRecorder::Detector& detector, bool gpu) { + ImGui::PushID(label); + ImGui::SeparatorText(label); + + changed |= ImGui::Checkbox("Detect", &detector.enable); + + // The CPU detector measures the CPU metrics, the GPU detector the GPU ones + auto firstMetric = gpu ? int32_t(HitchRecorder::Metric::GPU_BUSY) : int32_t(HitchRecorder::Metric::FRAME_TIME); + auto metricCount = gpu ? 2 : 3; + auto metricIdx = std::clamp(int32_t(detector.metric) - firstMetric, 0, metricCount - 1); + if (ImGui::BeginCombo("Metric", HitchRecorder::GetMetricName(HitchRecorder::Metric(firstMetric + metricIdx)))) { + for (int32_t i = 0; i < metricCount; i++) { + auto metric = HitchRecorder::Metric(firstMetric + i); + auto selectableFlags = metric == HitchRecorder::Metric::RENDER_THREAD && !hasRenderThread ? + ImGuiSelectableFlags_Disabled : ImGuiSelectableFlags_None; + if (ImGui::Selectable(HitchRecorder::GetMetricName(metric), i == metricIdx, selectableFlags)) { + detector.metric = metric; + changed = true; + } + } + ImGui::EndCombo(); + } + + auto triggerIdx = int32_t(detector.trigger); + if (ImGui::Combo("Trigger", &triggerIdx, triggers, IM_ARRAYSIZE(triggers))) { + detector.trigger = HitchRecorder::Trigger(triggerIdx); + changed = true; + } + + if (detector.trigger != HitchRecorder::Trigger::RELATIVE) + changed |= ImGui::DragFloat("Minimum time", &detector.minimumTime, 0.1f, 0.1f, 1000.0f, "%.1f ms", + ImGuiSliderFlags_AlwaysClamp); + if (detector.trigger != HitchRecorder::Trigger::ABSOLUTE) + changed |= ImGui::DragFloat("Relative to average", &detector.relativeThreshold, 0.01f, 1.1f, 20.0f, "%.2fx", + ImGuiSliderFlags_AlwaysClamp); + if (detector.metric == HitchRecorder::Metric::RENDER_THREAD && !hasRenderThread) + ImGui::TextDisabled("There is no render thread"); + + auto profilerEnabled = gpu ? GPUProfiler::enable.load() : CPUProfiler::enable.load(); + if (detector.enable && !profilerEnabled) { + if (gpu || detector.metric != HitchRecorder::Metric::FRAME_TIME) + ImGui::TextDisabled("Needs the %s profiler, which is disabled", gpu ? "GPU" : "CPU"); + else + ImGui::TextDisabled("The CPU profiler is disabled, hitches are recorded without a profile"); + } + + ImGui::PopID(); + }; + + // The labels are on the right of the widgets and keep their room + if (sideBySide && ImGui::BeginTable("HitchDetectors", 2, ImGuiTableFlags_SizingStretchSame)) { + ImGui::TableNextRow(); + ImGui::TableNextColumn(); + ImGui::PushItemWidth(-ImGui::GetFontSize() * 9.0f); + renderDetector("CPU", settings.cpu, false); + ImGui::PopItemWidth(); + ImGui::TableNextColumn(); + ImGui::PushItemWidth(-ImGui::GetFontSize() * 9.0f); + renderDetector("GPU", settings.gpu, true); + ImGui::PopItemWidth(); + ImGui::EndTable(); + } + else { + renderDetector("CPU", settings.cpu, false); + renderDetector("GPU", settings.gpu, true); + } + + ImGui::Separator(); + uint32_t minHitches = 1, maxHitches = 4096; + changed |= ImGui::DragScalar("Kept hitches", ImGuiDataType_U32, &settings.maxHitches, 1.0f, &minHitches, &maxHitches, + nullptr, ImGuiSliderFlags_AlwaysClamp); + + return changed; + + } + + void ProfilerPanel::RenderHitchSummary(float height) { + + if (hitchSummary.empty()) { + ImGui::TextWrapped("No causes yet, a cause is a query which took much longer than on average"); + return; + } + + if (height <= 0.0f) { + auto rows = std::min(int32_t(hitchSummary.size()), 8) + 1; + height = ImGui::GetTextLineHeightWithSpacing() * float(rows) + ImGui::GetStyle().CellPadding.y * 2.0f * float(rows); + } + + ImGuiTableFlags flags = ImGuiTableFlags_BordersV | ImGuiTableFlags_BordersOuterH | ImGuiTableFlags_Resizable | + ImGuiTableFlags_RowBg | ImGuiTableFlags_ScrollY; + if (ImGui::BeginTable("HitchCauses", 5, flags, ImVec2(0.0f, height))) { + ImGui::TableSetupScrollFreeze(0, 1); + ImGui::TableSetupColumn("Thread", ImGuiTableColumnFlags_WidthFixed, ImGui::GetFontSize() * 8.0f); + ImGui::TableSetupColumn("Query", ImGuiTableColumnFlags_WidthStretch); + ImGui::TableSetupColumn("Hitches", ImGuiTableColumnFlags_WidthFixed, ImGui::GetFontSize() * 4.0f); + ImGui::TableSetupColumn("Excess (ms)", ImGuiTableColumnFlags_WidthFixed, ImGui::GetFontSize() * 6.0f); + ImGui::TableSetupColumn("Max (ms)", ImGuiTableColumnFlags_WidthFixed, ImGui::GetFontSize() * 5.0f); + ImGui::TableHeadersRow(); + + for (const auto& summary : hitchSummary) { + ImGui::TableNextRow(); + ImGui::TableNextColumn(); + ImGui::TextUnformatted(summary.thread.c_str()); + ImGui::TableNextColumn(); + ImGui::TextUnformatted(summary.path.c_str()); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", summary.path.c_str()); + ImGui::TableNextColumn(); + ImGui::Text("%d", int32_t(summary.hitches)); + ImGui::TableNextColumn(); + ImGui::Text("%.1f", summary.totalExcess); + ImGui::TableNextColumn(); + ImGui::Text("%.1f", summary.maxExcess); + } + + ImGui::EndTable(); + } + + } + + void ProfilerPanel::RenderHitchList(float height, bool recording) { + + if (hitches.empty()) { + ImGui::TextDisabled(recording ? "No hitches recorded" : "Recording is disabled"); + return; + } + + auto selected = GetSelectedHitch(); + + if (height <= 0.0f) { + auto rows = std::min(int32_t(hitches.size()), 8) + 1; + height = ImGui::GetTextLineHeightWithSpacing() * float(rows) + ImGui::GetStyle().CellPadding.y * 2.0f * float(rows); + } + + ImGuiTableFlags flags = ImGuiTableFlags_BordersV | ImGuiTableFlags_BordersOuterH | ImGuiTableFlags_Resizable | + ImGuiTableFlags_RowBg | ImGuiTableFlags_ScrollY; + if (ImGui::BeginTable("HitchList", 6, flags, ImVec2(0.0f, height))) { + ImGui::TableSetupScrollFreeze(0, 1); + ImGui::TableSetupColumn("Time (s)", ImGuiTableColumnFlags_WidthFixed, ImGui::GetFontSize() * 5.0f); + ImGui::TableSetupColumn("Metric", ImGuiTableColumnFlags_WidthFixed, ImGui::GetFontSize() * 9.0f); + ImGui::TableSetupColumn("ms", ImGuiTableColumnFlags_WidthFixed, ImGui::GetFontSize() * 4.0f); + ImGui::TableSetupColumn("Average", ImGuiTableColumnFlags_WidthFixed, ImGui::GetFontSize() * 4.0f); + ImGui::TableSetupColumn("Factor", ImGuiTableColumnFlags_WidthFixed, ImGui::GetFontSize() * 4.0f); + ImGui::TableSetupColumn("Main cause", ImGuiTableColumnFlags_WidthStretch); + ImGui::TableHeadersRow(); + + // The latest first, only the visible rows are drawn + ImGuiListClipper clipper; + clipper.Begin(int32_t(hitches.size())); + while (clipper.Step()) { + for (auto row = clipper.DisplayStart; row < clipper.DisplayEnd; row++) { + const auto& hitch = *hitches[hitches.size() - 1 - size_t(row)]; + + ImGui::TableNextRow(); + ImGui::TableNextColumn(); + char label[48]; + std::snprintf(label, sizeof(label), "%.1f##%llu", hitch.time, static_cast(hitch.id)); + if (ImGui::Selectable(label, hitch.id == selected->id, ImGuiSelectableFlags_SpanAllColumns)) + selectedHitchId = hitch.id; + ImGui::TableNextColumn(); + ImGui::Text("%s %s", hitch.source == HitchRecorder::Source::GPU ? "GPU" : "CPU", + HitchRecorder::GetMetricName(hitch.metric)); + ImGui::TableNextColumn(); + ImGui::Text("%.1f", hitch.frameTime); + ImGui::TableNextColumn(); + ImGui::Text("%.1f", hitch.averageFrameTime); + ImGui::TableNextColumn(); + if (hitch.averageFrameTime > 0.0f) + ImGui::Text("%.1fx", hitch.frameTime / hitch.averageFrameTime); + ImGui::TableNextColumn(); + if (!hitch.causes.empty()) + ImGui::Text("%s: %s", hitch.causes.front().thread.c_str(), hitch.causes.front().path.c_str()); + else + ImGui::TextDisabled("-"); + } + } + + ImGui::EndTable(); + } + + } + + void ProfilerPanel::RenderHitchDetails() { + + auto selected = GetSelectedHitch(); + if (!selected) + return; + + const auto& hitch = *selected; + auto sourceName = hitch.source == HitchRecorder::Source::GPU ? "GPU" : "CPU"; + ImGui::TextWrapped("%s hitch at %.1f s: %.1f ms %s, average %.1f ms", sourceName, hitch.time, hitch.frameTime, + HitchRecorder::GetMetricName(hitch.metric), hitch.averageFrameTime); + for (const auto& cause : hitch.causes) + ImGui::BulletText("%s: %s %.1f ms (average %.1f ms)", cause.thread.c_str(), cause.path.c_str(), + cause.time, cause.averageTime); + + if (hitch.threads.empty()) + ImGui::TextDisabled("No profile, the %s profiler was disabled", sourceName); + else + RenderTable(hitch.threads, hitch.source == HitchRecorder::Source::GPU); + + } + + const HitchRecorder::Hitch* ProfilerPanel::GetSelectedHitch() const { + + if (hitches.empty()) + return nullptr; + + // Shows the latest hitch until another one is selected + auto selected = std::find_if(hitches.begin(), hitches.end(), + [&](const Ref& hitch) { return hitch->id == selectedHitchId; }); + return selected != hitches.end() ? selected->get() : hitches.back().get(); + + } + + void ProfilerPanel::RenderTable(const std::vector& threadData, bool openAllThreads) { + + // Fraction of the thread time is drawn as a bar behind the time, such that expensive queries stand out + auto barColor = ImGui::GetStyleColorVec4(ImGuiCol_PlotHistogram); + barColor.w *= 0.35f; + auto barColorU32 = ImGui::GetColorU32(barColor); + + auto renderRightAligned = [](const char* text) { + ImGui::SetCursorPosX(ImGui::GetCursorPosX() + ImGui::GetContentRegionAvail().x - ImGui::CalcTextSize(text).x); + ImGui::TextUnformatted(text); + }; + + auto renderTime = [&](double elapsedNs, double totalNs) { + auto fraction = totalNs > 0.0 ? float(Helper::Math::Saturate(elapsedNs / totalNs)) : 0.0f; + + auto cellMin = ImGui::GetCursorScreenPos(); + auto cellWidth = ImGui::GetContentRegionAvail().x; + auto lineHeight = ImGui::GetTextLineHeight(); + ImGui::GetWindowDrawList()->AddRectFilled(ImVec2(cellMin.x, cellMin.y + lineHeight - 3.0f), + ImVec2(cellMin.x + cellWidth * fraction, cellMin.y + lineHeight), barColorU32, 1.5f); + + char text[32]; + std::snprintf(text, sizeof(text), "%.3f", elapsedNs / 1000000.0); + renderRightAligned(text); + }; + + std::function displayQuery; + displayQuery = [&](const Profiler::Query& query, double totalNs) { + ImGui::TableNextRow(); + ImGui::TableNextColumn(); + + ImGuiTreeNodeFlags expandable = 0; + if (!query.children.size()) expandable = ImGuiTreeNodeFlags_NoTreePushOnOpen | + ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_Bullet; + + bool open = ImGui::TreeNodeEx(query.name.c_str(), expandable | ImGuiTreeNodeFlags_SpanFullWidth); + ImGui::TableNextColumn(); + renderRightAligned(std::to_string(query.calls).c_str()); + ImGui::TableNextColumn(); + renderTime(double(query.elapsedTime), totalNs); + + if (open && query.children.size()) { + for (const auto& child : query.children) + displayQuery(child, totalNs); + ImGui::TreePop(); + } + }; + + ImGuiTableFlags flags = ImGuiTableFlags_BordersV | ImGuiTableFlags_BordersOuterH | + ImGuiTableFlags_Resizable | ImGuiTableFlags_RowBg | ImGuiTableFlags_NoBordersInBody | + ImGuiTableFlags_ScrollY; + + if (ImGui::BeginTable("PerfTable", 3, flags)) { + ImGui::TableSetupScrollFreeze(0, 1); + ImGui::TableSetupColumn("Name", ImGuiTableColumnFlags_NoHide | ImGuiTableColumnFlags_WidthStretch); + ImGui::TableSetupColumn("Calls", ImGuiTableColumnFlags_NoHide | ImGuiTableColumnFlags_WidthFixed, + ImGui::GetFontSize() * 4.0f); + ImGui::TableSetupColumn("Time (ms)", ImGuiTableColumnFlags_NoHide | ImGuiTableColumnFlags_WidthFixed, + ImGui::GetFontSize() * 10.0f); + ImGui::TableHeadersRow(); + + for (const auto& thread : threadData) { + double threadTime = 0.0; + for (const auto& query : thread.queries) + threadTime += double(query.elapsedTime); + + ImGui::TableNextRow(); + ImGui::TableNextColumn(); + + auto open = openAllThreads || thread.name == "Main" || thread.name == "Render"; + ImGuiTreeNodeFlags expandable = open ? ImGuiTreeNodeFlags_DefaultOpen : 0; + if (!thread.queries.size()) expandable = ImGuiTreeNodeFlags_NoTreePushOnOpen | + ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_Bullet; + + bool isOpen = ImGui::TreeNodeEx(thread.name.c_str(), expandable | ImGuiTreeNodeFlags_SpanFullWidth); + ImGui::TableNextColumn(); + ImGui::TableNextColumn(); + renderTime(threadTime, 0.0); + + if (isOpen && thread.queries.size()) { + for (const auto& query : thread.queries) + displayQuery(query, threadTime); + ImGui::TreePop(); + } + } + + ImGui::EndTable(); + } + + } + + Profiler::OrderBy ProfilerPanel::GetOrder() const { + + switch (sortItem) { + case 1: return Profiler::OrderBy::MAX_TIME; + case 2: return Profiler::OrderBy::MIN_TIME; + case 3: return Profiler::OrderBy::NAME; + default: return Profiler::OrderBy::CHRONO; + } + + } + +} diff --git a/libs/ImguiExtension/panels/ProfilerPanel.h b/libs/ImguiExtension/panels/ProfilerPanel.h new file mode 100644 index 000000000..1a36555e9 --- /dev/null +++ b/libs/ImguiExtension/panels/ProfilerPanel.h @@ -0,0 +1,67 @@ +#pragma once + +#include "Panel.h" +#include "PerformanceGraphPanel.h" + +#include "profiler/Profiler.h" +#include "profiler/HitchRecorder.h" + +#include +#include + +namespace Atlas::ImguiExtension { + + class ProfilerPanel : public Panel { + + public: + ProfilerPanel() : Panel("Profiler") {} + + void Render(); + + // Averages of the queries over the history, refreshed a few times per second: merging the history of all + // threads every frame costs more than most of the work it measures + void Refresh(); + + std::vector cpuThreads; + std::vector gpuThreads; + + bool showGraph = false; + + int32_t sortItem = 0; + + PerformanceGraphPanel perfGraphPanel; + + private: + bool RenderControls(std::atomic_bool& enable, bool graph); + + void RenderHitches(); + + // Returns whether the settings changed + bool RenderHitchSettings(HitchRecorder::Settings& settings, bool sideBySide); + + // A height of 0 fits the table to its rows, at most a few + void RenderHitchSummary(float height); + + void RenderHitchList(float height, bool recording); + + void RenderHitchDetails(); + + // The selected hitch or the latest one + const HitchRecorder::Hitch* GetSelectedHitch() const; + + void RenderTable(const std::vector& threadData, bool openAllThreads); + + Profiler::OrderBy GetOrder() const; + + // The recorded hitches, updated when the recorder changes + std::vector> hitches; + std::vector hitchSummary; + uint64_t hitchRevision = std::numeric_limits::max(); + uint64_t selectedHitchId = std::numeric_limits::max(); + + float lastRefreshTime = -1.0f; + Profiler::OrderBy refreshedOrder = Profiler::OrderBy::MAX_TIME; + + }; + +} diff --git a/libs/ImguiExtension/panels/RTGIPanel.cpp b/libs/ImguiExtension/panels/RTGIPanel.cpp index 5c82be13d..afc1d7708 100644 --- a/libs/ImguiExtension/panels/RTGIPanel.cpp +++ b/libs/ImguiExtension/panels/RTGIPanel.cpp @@ -1,42 +1,69 @@ #include "RTGIPanel.h" +#include "graphics/GraphicsDevice.h" + namespace Atlas::ImguiExtension { void RTGIPanel::Render(Ref& rtgi, Ref& target) { ImGui::PushID(GetNameID()); - ImGui::Checkbox("Enable", &rtgi->enable); - ImGui::Checkbox("Half resolution", &rtgi->halfResolution); + if (UIElements::BeginProperties("RTGIGeneral")) { + UIElements::PropertyLabel("Enable"); + ImGui::Checkbox("##Enable", &rtgi->enable); + UIElements::PropertyLabel("Half resolution"); + ImGui::Checkbox("##Half resolution", &rtgi->halfResolution); - ImGui::Checkbox("Use shadow map", &rtgi->useShadowMap); - if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) { - ImGui::SetTooltip("Uses the shadow map to calculate shadows in GI. " - "This is only possible when cascaded shadow maps are not used."); - } - ImGui::Checkbox("Use normal maps", &rtgi->useNormalMaps); - if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) { - ImGui::SetTooltip("Uses the normal maps to cast GI rays."); + UIElements::PropertyLabel("Use normal maps"); + ImGui::Checkbox("##Use normal maps", &rtgi->useNormalMaps); + if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) { + ImGui::SetTooltip("Uses the normal maps to cast GI rays."); + } + UIElements::PropertyLabel("Use DDGI as secondary bounce"); + ImGui::Checkbox("##Use DDGI as secondary bounce", &rtgi->ddgi); + UIElements::PropertyLabel("Opacity check"); + ImGui::Checkbox("##Opacity check", &rtgi->opacityCheck); + auto reorderSupported = Graphics::GraphicsDevice::DefaultDevice->support.shaderExecutionReordering; + UIElements::PropertyLabel("Shader execution reordering"); + ImGui::BeginDisabled(!reorderSupported); + ImGui::Checkbox("##Shader execution reordering", &rtgi->shaderExecutionReordering); + if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) { + ImGui::SetTooltip("Sorts the rays by the mesh they hit before shading. Helps with many different meshes, " + "costs with few. Needs hit objects, which the device %s.", reorderSupported ? "supports" : "doesn't support"); + } + ImGui::EndDisabled(); + // ImGui::SliderInt("Sample count", &reflection->sampleCount, 1, 32); + UIElements::PropertyLabel("Radiance limit"); + ImGui::DragFloat("##Radiance limit", &rtgi->radianceLimit, 0.1f, 0.0f, 1000.0f); + if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) { + ImGui::SetTooltip("Limits the amount of incoming radiance. Is internally scale by the camera exposure."); + } + UIElements::PropertyLabel("Bias"); + ImGui::SliderFloat("##Bias", &rtgi->bias, 0.0f, 1.0f); + UIElements::PropertyLabel("Texture level"); + ImGui::SliderInt("##Texture level", &rtgi->textureLevel, 0, 10); + UIElements::PropertyLabel("Sample count"); + ImGui::SliderInt("##Sample count", &rtgi->sampleCount, 1, 10); + UIElements::PropertyLabel("Light sample count"); + ImGui::SliderInt("##Light sample count", &rtgi->lightSampleCount, 1, 10); + UIElements::EndProperties(); } - ImGui::Checkbox("Use DDGI as secondary bounce", &rtgi->ddgi); - ImGui::Checkbox("Opacity check", &rtgi->opacityCheck); - // ImGui::SliderInt("Sample count", &reflection->sampleCount, 1, 32); - ImGui::DragFloat("Radiance limit", &rtgi->radianceLimit, 0.1f, 0.0f, 1000.0f); - if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) { - ImGui::SetTooltip("Limits the amount of incoming radiance. Is internally scale by the camera exposure."); + + UIElements::PropertySection("Denoiser"); + if (UIElements::BeginProperties("RTGIDenoiser")) { + UIElements::PropertyLabel("Spatial filter strength"); + ImGui::SliderFloat("##Spatial filter strength", &rtgi->spatialFilterStrength, 0.0f, 10.0f); + UIElements::PropertyLabel("Temporal weight"); + ImGui::SliderFloat("##Temporal weight", &rtgi->temporalWeight, 0.0f, 1.0f); + UIElements::PropertyLabel("Maximum history clip factor"); + ImGui::SliderFloat("##Maximum history clip factor", &rtgi->historyClipMax, 0.0f, 1.0f); + UIElements::PropertyLabel("Current clip factor"); + ImGui::SliderFloat("##Current clip factor", &rtgi->currentClipFactor, 0.0f, 10.0f); + UIElements::EndProperties(); } - ImGui::SliderFloat("Bias", &rtgi->bias, 0.0f, 1.0f); - ImGui::SliderInt("Texture level##RTGI", &rtgi->textureLevel, 0, 10); - ImGui::SliderInt("Sample count##RTGI", &rtgi->sampleCount, 1, 10); - ImGui::SliderInt("Light sample count##RTGI", &rtgi->lightSampleCount, 1, 10); - ImGui::SeparatorText("Denoiser"); - ImGui::SliderFloat("Spatial filter strength", &rtgi->spatialFilterStrength, 0.0f, 10.0f); - ImGui::SliderFloat("Temporal weight", &rtgi->temporalWeight, 0.0f, 1.0f); - ImGui::SliderFloat("Maximum history clip factor", &rtgi->historyClipMax, 0.0f, 1.0f); - ImGui::SliderFloat("Current clip factor", &rtgi->currentClipFactor, 0.0f, 10.0f); ImGui::PopID(); } -} \ No newline at end of file +} diff --git a/libs/ImguiExtension/panels/ReflectionPanel.cpp b/libs/ImguiExtension/panels/ReflectionPanel.cpp index 3737eeddb..732c36bb5 100644 --- a/libs/ImguiExtension/panels/ReflectionPanel.cpp +++ b/libs/ImguiExtension/panels/ReflectionPanel.cpp @@ -1,44 +1,75 @@ #include "ReflectionPanel.h" +#include "graphics/GraphicsDevice.h" + namespace Atlas::ImguiExtension { void ReflectionPanel::Render(Ref &reflection, Ref& target) { ImGui::PushID(GetNameID()); - ImGui::Checkbox("Enable", &reflection->enable); - ImGui::Checkbox("Enable RT", &reflection->rt); - ImGui::Checkbox("Enable SSR", &reflection->ssr); - ImGui::Checkbox("Half resolution", &reflection->halfResolution); - ImGui::Checkbox("Upsample before filtering", &reflection->upsampleBeforeFiltering); - - //ImGui::Checkbox("Enable raytracing##Reflection", &reflection->rt); - ImGui::Checkbox("Use shadow map", &reflection->useShadowMap); - if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) { - ImGui::SetTooltip("Uses the shadow map to calculate shadows in reflections. " - "This is only possible when cascaded shadow maps are not used."); + if (UIElements::BeginProperties("ReflectionGeneral")) { + UIElements::PropertyLabel("Enable"); + ImGui::Checkbox("##Enable", &reflection->enable); + UIElements::PropertyLabel("Enable RT"); + ImGui::Checkbox("##Enable RT", &reflection->rt); + UIElements::PropertyLabel("Enable SSR"); + ImGui::Checkbox("##Enable SSR", &reflection->ssr); + UIElements::PropertyLabel("Half resolution"); + ImGui::Checkbox("##Half resolution", &reflection->halfResolution); + UIElements::PropertyLabel("Upsample before filtering"); + ImGui::Checkbox("##Upsample before filtering", &reflection->upsampleBeforeFiltering); + + //ImGui::Checkbox("Enable raytracing##Reflection", &reflection->rt); + UIElements::PropertyLabel("Use normal maps"); + ImGui::Checkbox("##Use normal maps", &reflection->useNormalMaps); + if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) { + ImGui::SetTooltip("Uses the normal maps to cast reflection rays."); + } + UIElements::PropertyLabel("Use DDGI in reflection"); + ImGui::Checkbox("##Use DDGI in reflection", &reflection->ddgi); + UIElements::PropertyLabel("Opacity check"); + ImGui::Checkbox("##Opacity check", &reflection->opacityCheck); + auto reorderSupported = Graphics::GraphicsDevice::DefaultDevice->support.shaderExecutionReordering; + UIElements::PropertyLabel("Shader execution reordering"); + ImGui::BeginDisabled(!reorderSupported); + ImGui::Checkbox("##Shader execution reordering", &reflection->shaderExecutionReordering); + if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) { + ImGui::SetTooltip("Sorts the rays by the mesh they hit before shading. Helps with many different meshes, " + "costs with few. Needs hit objects, which the device %s.", reorderSupported ? "supports" : "doesn't support"); + } + ImGui::EndDisabled(); + // ImGui::SliderInt("Sample count", &reflection->sampleCount, 1, 32); + UIElements::PropertyLabel("Radiance limit"); + ImGui::DragFloat("##Radiance limit", &reflection->radianceLimit, 0.1f, 0.0f, 1000.0f); + UIElements::PropertyLabel("Bias"); + ImGui::SliderFloat("##Bias", &reflection->bias, 0.0f, 1.0f); + UIElements::PropertyLabel("Roughness cuttoff"); + ImGui::SliderFloat("##Roughness cuttoff", &reflection->roughnessCutoff, 0.0f, 1.0f); + UIElements::PropertyLabel("Texture level"); + ImGui::SliderInt("##Texture level", &reflection->textureLevel, 0, 10); + UIElements::PropertyLabel("Sample count"); + ImGui::SliderInt("##Sample count", &reflection->sampleCount, 1, 10); + UIElements::PropertyLabel("Light sample count"); + ImGui::SliderInt("##Light sample count", &reflection->lightSampleCount, 1, 10); + UIElements::EndProperties(); } - ImGui::Checkbox("Use normal maps", &reflection->useNormalMaps); - if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) { - ImGui::SetTooltip("Uses the normal maps to cast reflection rays."); + + UIElements::PropertySection("Denoiser"); + if (UIElements::BeginProperties("ReflectionDenoiser")) { + UIElements::PropertyLabel("Spatial filter strength"); + ImGui::SliderFloat("##Spatial filter strength", &reflection->spatialFilterStrength, 0.0f, 10.0f); + UIElements::PropertyLabel("Temporal weight"); + ImGui::SliderFloat("##Temporal weight", &reflection->temporalWeight, 0.0f, 1.0f); + UIElements::PropertyLabel("Maximum history clip factor"); + ImGui::SliderFloat("##Maximum history clip factor", &reflection->historyClipMax, 0.0f, 1.0f); + UIElements::PropertyLabel("Current clip factor"); + ImGui::SliderFloat("##Current clip factor", &reflection->currentClipFactor, 0.0f, 10.0f); + UIElements::EndProperties(); } - ImGui::Checkbox("Use DDGI in reflection", &reflection->ddgi); - ImGui::Checkbox("Opacity check", &reflection->opacityCheck); - // ImGui::SliderInt("Sample count", &reflection->sampleCount, 1, 32); - ImGui::DragFloat("Radiance limit", &reflection->radianceLimit, 0.1f, 0.0f, 1000.0f); - ImGui::SliderFloat("Bias", &reflection->bias, 0.0f, 1.0f); - ImGui::SliderFloat("Roughness cuttoff", &reflection->roughnessCutoff, 0.0f, 1.0f); - ImGui::SliderInt("Texture level##Reflection", &reflection->textureLevel, 0, 10); - ImGui::SliderInt("Sample count##Reflection", &reflection->sampleCount, 1, 10); - ImGui::SliderInt("Light sample count##Reflection", &reflection->lightSampleCount, 1, 10); - ImGui::SeparatorText("Denoiser"); - ImGui::SliderFloat("Spatial filter strength", &reflection->spatialFilterStrength, 0.0f, 10.0f); - ImGui::SliderFloat("Temporal weight", &reflection->temporalWeight, 0.0f, 1.0f); - ImGui::SliderFloat("Maximum history clip factor", &reflection->historyClipMax, 0.0f, 1.0f); - ImGui::SliderFloat("Current clip factor", &reflection->currentClipFactor, 0.0f, 10.0f); ImGui::PopID(); } -} \ No newline at end of file +} diff --git a/libs/ImguiExtension/panels/SSGIPanel.cpp b/libs/ImguiExtension/panels/SSGIPanel.cpp index 6a13c8014..314a69a62 100644 --- a/libs/ImguiExtension/panels/SSGIPanel.cpp +++ b/libs/ImguiExtension/panels/SSGIPanel.cpp @@ -6,18 +6,31 @@ namespace Atlas::ImguiExtension { ImGui::PushID(GetNameID()); - ImGui::Checkbox("Enable", &ssgi->enable); - ImGui::Checkbox("Half resolution", &ssgi->halfResolution); - - ImGui::Checkbox("Enable ambient occlusion", &ssgi->enableAo); - ImGui::SliderInt("Ray count", &ssgi->rayCount, 1, 8); - ImGui::SliderInt("Sample count", &ssgi->sampleCount, 1, 16); - ImGui::SliderFloat("Radius", &ssgi->radius, 0.0f, 10.0f); - ImGui::SliderFloat("Ao strength", &ssgi->aoStrength, 0.0f, 10.0f); - ImGui::DragFloat("Irradiance limit", &ssgi->irradianceLimit, 0.1f, 0.0f, 1000.0f); + if (UIElements::BeginProperties("SSGIGeneral")) { + UIElements::PropertyLabel("Enable"); + ImGui::Checkbox("##Enable", &ssgi->enable); + UIElements::PropertyLabel("Half resolution"); + ImGui::Checkbox("##Half resolution", &ssgi->halfResolution); + + UIElements::PropertyLabel("Enable ambient occlusion"); + ImGui::Checkbox("##Enable ambient occlusion", &ssgi->enableAo); + UIElements::PropertyLabel("Ray count"); + ImGui::DragInt("##Ray count", &ssgi->rayCount, 0.1f, 1, 8); + UIElements::PropertyLabel("Sample count"); + ImGui::DragInt("##Sample count", &ssgi->sampleCount, 0.1f, 1, 16); + UIElements::PropertyLabel("Radius"); + ImGui::DragFloat("##Radius", &ssgi->radius, 1.0f, 0.0f, 2000.0f); + UIElements::PropertyLabel("Thickness"); + ImGui::DragFloat("##Thickness", &ssgi->thickness, 0.001f, 0.0f, 0.2f, "%.3f"); + UIElements::PropertyLabel("Ao strength"); + ImGui::DragFloat("##Ao strength", &ssgi->aoStrength, 0.01f, 0.0f, 10.0f); + UIElements::PropertyLabel("Irradiance limit"); + ImGui::DragFloat("##Irradiance limit", &ssgi->irradianceLimit, 0.1f, 0.0f, 1000.0f); + UIElements::EndProperties(); + } ImGui::PopID(); } -} \ No newline at end of file +} diff --git a/libs/ImguiExtension/panels/SSSPanel.cpp b/libs/ImguiExtension/panels/SSSPanel.cpp index 5454b21b6..522b22601 100644 --- a/libs/ImguiExtension/panels/SSSPanel.cpp +++ b/libs/ImguiExtension/panels/SSSPanel.cpp @@ -6,15 +6,24 @@ namespace Atlas::ImguiExtension { ImGui::PushID(GetNameID()); - ImGui::Checkbox("Enable", &sss->enable); - ImGui::Checkbox("Trace in world space", &sss->traceWorldSpace); - ImGui::DragInt("Sample count", &sss->sampleCount, 1.f, 2, 64); - ImGui::SliderFloat("Max length", &sss->maxLength, 0.01f, 1.0f); - ImGui::SliderFloat("Min length world space", &sss->minLengthWorldSpace, 0.01f, 1.0f); - ImGui::SliderFloat("Thickness", &sss->thickness, 0.001f, 1.0f, "%.3f", ImGuiSliderFlags_Logarithmic); + if (UIElements::BeginProperties("SSSGeneral")) { + UIElements::PropertyLabel("Enable"); + ImGui::Checkbox("##Enable", &sss->enable); + UIElements::PropertyLabel("Trace in world space"); + ImGui::Checkbox("##Trace in world space", &sss->traceWorldSpace); + UIElements::PropertyLabel("Sample count"); + ImGui::DragInt("##Sample count", &sss->sampleCount, 1.f, 2, 64); + UIElements::PropertyLabel("Max length"); + ImGui::SliderFloat("##Max length", &sss->maxLength, 0.01f, 1.0f); + UIElements::PropertyLabel("Min length world space"); + ImGui::SliderFloat("##Min length world space", &sss->minLengthWorldSpace, 0.01f, 1.0f); + UIElements::PropertyLabel("Thickness"); + ImGui::SliderFloat("##Thickness", &sss->thickness, 0.001f, 1.0f, "%.3f", ImGuiSliderFlags_Logarithmic); + UIElements::EndProperties(); + } ImGui::PopID(); } -} \ No newline at end of file +} diff --git a/libs/ImguiExtension/panels/SkyPanel.cpp b/libs/ImguiExtension/panels/SkyPanel.cpp index f381e7b0c..3326f0cf8 100644 --- a/libs/ImguiExtension/panels/SkyPanel.cpp +++ b/libs/ImguiExtension/panels/SkyPanel.cpp @@ -10,11 +10,11 @@ namespace Atlas::ImguiExtension { if (sky.probe) cubemap = sky.probe->cubemap; - ImGui::SeparatorText("Environment map"); + UIElements::PropertySection("Environment map"); if (cubemapSelector.has_value()) { cubemap = cubemapSelector.value()(cubemap); } - + if (cubemap.IsValid() && !sky.probe) sky.probe = CreateRef(cubemap); else if (!cubemap.IsValid() && sky.probe) @@ -26,14 +26,28 @@ namespace Atlas::ImguiExtension { atmosphere->rayleighScatteringCoeff *= 1e6f; atmosphere->mieScatteringCoeff *= 1e6f; - ImGui::SeparatorText("Atmosphere"); - bool atmosphereChanged = false; - atmosphereChanged |= ImGui::DragFloat3("Rayleigh scattering coefficient", glm::value_ptr(atmosphere->rayleighScatteringCoeff), 0.1f, 0.0f, 10e10f); - atmosphereChanged |= ImGui::ColorEdit3("Ground albedo", glm::value_ptr(atmosphere->groundAlbedo)); - atmosphereChanged |= ImGui::DragFloat("Mie scattering coefficient", &atmosphere->mieScatteringCoeff, 1.0f, 0.0f, 10e10f); - atmosphereChanged |= ImGui::DragFloat("Rayleigh height scale", &atmosphere->rayleighHeightScale, 100.0f, 0.0f, 10e10f); - atmosphereChanged |= ImGui::DragFloat("Mie height scale", &atmosphere->mieHeightScale, 100.0f, 0.0f, 10e10f); - atmosphere->needsUpdate |= atmosphereChanged; + UIElements::PropertySection("Atmosphere"); + if (UIElements::BeginProperties("SkyAtmosphere")) { + bool atmosphereChanged = false; + UIElements::PropertyLabel("Rayleigh scattering coefficient"); + atmosphereChanged |= ImGui::DragFloat3("##Rayleigh scattering coefficient", glm::value_ptr(atmosphere->rayleighScatteringCoeff), 0.1f, 0.0f, 10e10f); + UIElements::PropertyLabel("Ground albedo"); + atmosphereChanged |= ImGui::ColorEdit3("##Ground albedo", glm::value_ptr(atmosphere->groundAlbedo)); + UIElements::PropertyLabel("Mie scattering coefficient"); + atmosphereChanged |= ImGui::DragFloat("##Mie scattering coefficient", &atmosphere->mieScatteringCoeff, 1.0f, 0.0f, 10e10f); + UIElements::PropertyLabel("Rayleigh height scale"); + atmosphereChanged |= ImGui::DragFloat("##Rayleigh height scale", &atmosphere->rayleighHeightScale, 100.0f, 0.0f, 10e10f); + UIElements::PropertyLabel("Mie height scale"); + atmosphereChanged |= ImGui::DragFloat("##Mie height scale", &atmosphere->mieHeightScale, 100.0f, 0.0f, 10e10f); + atmosphere->needsUpdate |= atmosphereChanged; + UIElements::PropertyLabel("Sun disk size", "Angular diameter of the sun, the real sun has about 0.53 degrees"); + ImGui::DragFloat("##Sun disk size", &atmosphere->sunDiskSize, 0.01f, 0.01f, 20.0f, "%.2f deg"); + UIElements::PropertyLabel("Direct light", "How much the air colors and dims the sun's light, red and weak near the horizon at 1"); + ImGui::SliderFloat("##Direct light", &atmosphere->directLight, 0.0f, 1.0f); + UIElements::PropertyLabel("Indirect light", "How much the sky lights the scene: ambient light, global illumination and sky reflections"); + ImGui::SliderFloat("##Indirect light", &atmosphere->indirectLight, 0.0f, 2.0f); + UIElements::EndProperties(); + } atmosphere->rayleighScatteringCoeff /= 1e6f; atmosphere->mieScatteringCoeff /= 1e6f; diff --git a/libs/ImguiExtension/panels/VolumetricCloudsPanel.cpp b/libs/ImguiExtension/panels/VolumetricCloudsPanel.cpp index 7c3fde73e..f0c81cf4c 100644 --- a/libs/ImguiExtension/panels/VolumetricCloudsPanel.cpp +++ b/libs/ImguiExtension/panels/VolumetricCloudsPanel.cpp @@ -6,33 +6,89 @@ namespace Atlas::ImguiExtension { ImGui::PushID(GetNameID()); - ImGui::Checkbox("Enable", &clouds->enable); + if (UIElements::BeginProperties("CloudsGeneral")) { + UIElements::PropertyLabel("Enable"); + ImGui::Checkbox("##Enable", &clouds->enable); + UIElements::EndProperties(); + } // Settings of disabled clouds are shown, but greyed out ImGui::BeginDisabled(!clouds->enable); - ImGui::Checkbox("Cast shadow", &clouds->castShadow); - - ImGui::SeparatorText("Shape"); - ImGui::SliderFloat("Coverage", &clouds->coverage, 0.0f, 1.0f); - ImGui::SliderFloat("Cloud type", &clouds->cloudType, 0.0f, 1.0f); - ImGui::SetItemTooltip("Continuous blend: stratus (0), stratocumulus (0.5), cumulus (1)"); - ImGui::SliderFloat("Cloud size", &clouds->cloudSize, 100.0f, 10000.0f, "%.0f m", ImGuiSliderFlags_Logarithmic); - ImGui::SliderFloat("Vertical development", &clouds->verticalDevelopment, 0.0f, 1.0f); - ImGui::SetItemTooltip("Controls billow proportions and height variation within the cloud layer"); - ImGui::SliderFloat("Detail", &clouds->detail, 0.0f, 1.0f); - ImGui::SliderFloat("Density", &clouds->densityMultiplier, 0.0f, 2.0f); - - ImGui::SeparatorText("Layer"); - ImGui::DragFloat("Base altitude", &clouds->baseAltitude, 10.0f, 0.0f, 20000.0f, "%.0f m"); - ImGui::DragFloat("Layer thickness", &clouds->layerThickness, 10.0f, 1.0f, 10000.0f, "%.0f m"); - ImGui::SliderFloat("Distance limit", &clouds->distanceLimit, 1000.0f, 40000.0f, "%.0f m"); - if (ImGui::SliderFloat("Variation seed", &clouds->variationSeed, 0.0f, 100.0f)) - clouds->needsNoiseUpdate = true; - - ImGui::SeparatorText("Quality"); - ImGui::Combo("Quality", &clouds->quality, "Low\0Medium\0High\0Ultra\0"); - ImGui::SetItemTooltip("Controls ray samples, lighting samples and volumetric resolution (shared with fog)"); - ImGui::Checkbox("Debug", &debug); + if (UIElements::BeginProperties("CloudsShadow")) { + UIElements::PropertyLabel("Cast shadow"); + ImGui::Checkbox("##Cast shadow", &clouds->castShadow); + UIElements::EndProperties(); + } + + UIElements::PropertySection("Shape"); + if (UIElements::BeginProperties("CloudsShape")) { + UIElements::PropertyLabel("Coverage"); + ImGui::SliderFloat("##Coverage", &clouds->coverage, 0.0f, 1.0f); + UIElements::PropertyLabel("Cloud type", "Continuous blend: stratus (0), stratocumulus (0.5), cumulus (1)"); + ImGui::SliderFloat("##Cloud type", &clouds->cloudType, 0.0f, 1.0f); + UIElements::PropertyLabel("Cloud size"); + ImGui::SliderFloat("##Cloud size", &clouds->cloudSize, 100.0f, 10000.0f, "%.0f m", ImGuiSliderFlags_Logarithmic); + UIElements::PropertyLabel("Vertical development", "Controls billow proportions and height variation within the cloud layer"); + ImGui::SliderFloat("##Vertical development", &clouds->verticalDevelopment, 0.0f, 1.0f); + UIElements::PropertyLabel("Detail"); + ImGui::SliderFloat("##Detail", &clouds->detail, 0.0f, 1.0f); + UIElements::PropertyLabel("Density"); + ImGui::SliderFloat("##Density", &clouds->densityMultiplier, 0.0f, 2.0f); + UIElements::EndProperties(); + } + + UIElements::PropertySection("Layer"); + if (UIElements::BeginProperties("CloudsLayer")) { + UIElements::PropertyLabel("Base altitude"); + ImGui::DragFloat("##Base altitude", &clouds->baseAltitude, 10.0f, 0.0f, 20000.0f, "%.0f m"); + UIElements::PropertyLabel("Layer thickness"); + ImGui::DragFloat("##Layer thickness", &clouds->layerThickness, 10.0f, 1.0f, 10000.0f, "%.0f m"); + UIElements::PropertyLabel("Distance limit"); + ImGui::SliderFloat("##Distance limit", &clouds->distanceLimit, 1000.0f, 40000.0f, "%.0f m"); + UIElements::PropertyLabel("Variation seed"); + if (ImGui::SliderFloat("##Variation seed", &clouds->variationSeed, 0.0f, 100.0f)) + clouds->needsNoiseUpdate = true; + UIElements::EndProperties(); + } + + UIElements::PropertySection("Scattering"); + auto& scattering = clouds->scattering; + if (UIElements::BeginProperties("CloudsScattering")) { + UIElements::PropertyLabel("Extinction", "How much light the cloud medium absorbs and scatters per density, higher values make clouds more opaque"); + ImGui::DragFloat("##Extinction", &scattering.extinctionFactor, 0.001f, 0.0f, 10.0f); + UIElements::PropertyLabel("Extinction color", "Relative extinction per channel, lower values let more of that color pass through"); + ImGui::ColorEdit3("##Extinction color", &scattering.extinctionCoefficients[0]); + UIElements::PropertyLabel("Scattering", "Brightness of the light scattered towards the viewer"); + ImGui::DragFloat("##Scattering", &scattering.scatteringFactor, 0.001f, 0.0f, 10.0f); + UIElements::PropertyLabel("Eccentricity first phase"); + ImGui::SliderFloat("##Eccentricity first phase", &scattering.eccentricityFirstPhase, -0.99f, 0.99f); + UIElements::PropertyLabel("Eccentricity second phase", "Positive values scatter forward (silver lining towards the sun), negative values backward"); + ImGui::SliderFloat("##Eccentricity second phase", &scattering.eccentricitySecondPhase, -0.99f, 0.99f); + UIElements::PropertyLabel("Phase blend", "Blend from the first (0) to the second (1) phase function"); + ImGui::SliderFloat("##Phase blend", &scattering.phaseAlpha, 0.0f, 1.0f); + UIElements::EndProperties(); + } + + UIElements::PropertySection("Quality"); + if (UIElements::BeginProperties("CloudsQuality")) { + UIElements::PropertyLabel("Quality", "Controls ray samples, lighting samples and volumetric resolution (shared with fog)"); + ImGui::Combo("##Quality", &clouds->quality, "Low\0Medium\0High\0Ultra\0"); + + const int32_t shadowResolutions[] = { 512, 1024, 2048, 4096 }; + auto shadowResolutionItem = 0; + for (int32_t i = 0; i < IM_ARRAYSIZE(shadowResolutions); i++) + if (clouds->shadowTexture.width == shadowResolutions[i]) + shadowResolutionItem = i; + ImGui::BeginDisabled(!clouds->castShadow); + UIElements::PropertyLabel("Shadow resolution"); + if (ImGui::Combo("##Shadow resolution", &shadowResolutionItem, "512x512\0" "1024x1024\0" "2048x2048\0" "4096x4096\0")) + clouds->SetShadowResolution(shadowResolutions[shadowResolutionItem]); + ImGui::EndDisabled(); + + UIElements::PropertyLabel("Debug"); + ImGui::Checkbox("##Debug", &debug); + UIElements::EndProperties(); + } ImGui::EndDisabled(); diff --git a/libs/ImguiExtension/panels/WindPanel.cpp b/libs/ImguiExtension/panels/WindPanel.cpp index 63b760de9..187dbbd02 100644 --- a/libs/ImguiExtension/panels/WindPanel.cpp +++ b/libs/ImguiExtension/panels/WindPanel.cpp @@ -6,17 +6,22 @@ namespace Atlas::ImguiExtension { ImGui::PushID(GetNameID()); - ImGui::SeparatorText("Noise texture"); + UIElements::PropertySection("Noise texture"); UIElements::TextureView(wrapper, &wind.noiseMap, 255.0f); ImGui::Separator(); - ImGui::DragFloat2("Wind direction", glm::value_ptr(wind.direction), 0.01f, -1.0f, 1.0f); - ImGui::DragFloat("Wind speed", &wind.speed, 0.5f, 0.0f, 100.0f); + if (UIElements::BeginProperties("WindGeneral")) { + UIElements::PropertyLabel("Wind direction"); + ImGui::DragFloat2("##Wind direction", glm::value_ptr(wind.direction), 0.01f, -1.0f, 1.0f); + UIElements::PropertyLabel("Wind speed"); + ImGui::DragFloat("##Wind speed", &wind.speed, 0.5f, 0.0f, 100.0f); + UIElements::EndProperties(); + } ImGui::PopID(); } -} \ No newline at end of file +} diff --git a/libs/upscalers/README.md b/libs/upscalers/README.md new file mode 100644 index 000000000..4dc1c0bf5 --- /dev/null +++ b/libs/upscalers/README.md @@ -0,0 +1,40 @@ +# Vendor upscalers + +Optional upscalers selected with `PostProcessing::upscaler`. Each one lives in its own folder and is compiled +into the engine only when its SDK is found. Without the SDK, or on a GPU it doesn't support, the engine uses +FSR2 instead (`MainRenderer::IsUpscalerSupported`). The SDKs aren't part of the repository. + +| Upscaler | SDK folder | Platforms | Runtime library | +|----------|------------|-----------|-----------------| +| DLSS | `dlss/sdk` or `ATLAS_DLSS_SDK` | Windows, Linux | `nvngx_dlss.dll` / `libnvidia-ngx-dlss.so.*` | +| FSR 4 | `fsr4/sdk` or `ATLAS_FSR4_SDK` | Windows | `amd_fidelityfx_upscaler_vk.dll` | + +Set `ATLAS_DLSS=OFF` or `ATLAS_FSR4=OFF` to build without an SDK that is present. + +## DLSS + +From the [DLSS SDK](https://github.com/NVIDIA/DLSS) copy into `dlss/sdk`: + +- `include/` +- `lib/Windows_x86_64/x64/` (`nvsdk_ngx_d.lib`, `nvsdk_ngx_d_dbg.lib`) and `lib/Windows_x86_64/rel/nvngx_dlss.dll` +- `lib/Linux_x86_64/libnvsdk_ngx.a` and `lib/Linux_x86_64/rel/libnvidia-ngx-dlss.so.*` +- `LICENSE.txt` + +`lib/Windows_x86_64/dev` contains a DLSS library with debug overlays and hotkeys for checking jitter, motion +vectors and exposure. NGX needs an NVIDIA RTX GPU and loads the DLSS library from the executable folder or the SDK. + +## FSR 4 + +From the [AMD FSR SDK](https://github.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK) (2.4 or newer) copy into `fsr4/sdk`: + +- `Kits/FidelityFX/api/include/` to `api/include/` +- `Kits/FidelityFX/upscalers/include/` to `upscalers/include/` +- `Kits/FidelityFX/signedbin/amd_fidelityfx_upscaler_vk.dll` to `bin/` +- `Kits/FidelityFX/docs/license.md` + +The signed library selects the upscaler version for the GPU: the machine learning FSR 4 on supported AMD GPUs with a +recent driver, FSR 3 otherwise. The log names the version in use. + +## Packaging + +Ship the runtime library next to the executable together with the SDK license. diff --git a/libs/upscalers/Upscalers.cmake b/libs/upscalers/Upscalers.cmake new file mode 100644 index 000000000..ab6b30913 --- /dev/null +++ b/libs/upscalers/Upscalers.cmake @@ -0,0 +1,5 @@ +# Optional upscalers of vendor SDKs, compiled into the AtlasEngine target. An upscaler is only built when its SDK +# was found, without it or on GPUs it doesn't support the engine falls back to FSR2 (see README.md) +get_filename_component(ATLAS_UPSCALER_ADDONS_SOURCE ${CMAKE_CURRENT_LIST_DIR}/../../src/engine/renderer/UpscalerAddons.cpp ABSOLUTE) +include(${CMAKE_CURRENT_LIST_DIR}/dlss/DLSS.cmake) +include(${CMAKE_CURRENT_LIST_DIR}/fsr4/FSR4.cmake) diff --git a/libs/upscalers/dlss/DLSS.cmake b/libs/upscalers/dlss/DLSS.cmake new file mode 100644 index 000000000..f1cefbb65 --- /dev/null +++ b/libs/upscalers/dlss/DLSS.cmake @@ -0,0 +1,23 @@ +option(ATLAS_DLSS "Build the DLSS upscaler when its SDK is found" ON) +set(ATLAS_DLSS_SDK "${CMAKE_CURRENT_LIST_DIR}/sdk" CACHE PATH "DLSS SDK with the include and lib folders of github.com/NVIDIA/DLSS") + +if (ATLAS_DLSS AND EXISTS "${ATLAS_DLSS_SDK}/include/nvsdk_ngx_vk.h" AND (WIN32 OR (UNIX AND NOT APPLE AND NOT ANDROID))) + message(STATUS "Building the DLSS upscaler with ${ATLAS_DLSS_SDK}") + + target_sources(AtlasEngine PRIVATE ${CMAKE_CURRENT_LIST_DIR}/DLSSRenderer.cpp ${CMAKE_CURRENT_LIST_DIR}/DLSSRenderer.h) + target_include_directories(AtlasEngine PRIVATE ${ATLAS_DLSS_SDK}/include) + + # NGX loads the DLSS library from the executable folder, other than in release builds also from this one + if (WIN32) + target_link_libraries(AtlasEngine LINK_PRIVATE + "${ATLAS_DLSS_SDK}/lib/Windows_x86_64/x64/nvsdk_ngx_d$<$:_dbg>.lib") + set(ATLAS_DLSS_RUNTIME_DIR "${ATLAS_DLSS_SDK}/lib/Windows_x86_64/rel") + else() + target_link_libraries(AtlasEngine LINK_PRIVATE "${ATLAS_DLSS_SDK}/lib/Linux_x86_64/libnvsdk_ngx.a" dl) + set(ATLAS_DLSS_RUNTIME_DIR "${ATLAS_DLSS_SDK}/lib/Linux_x86_64/rel") + endif() + + # Only for the files which use it, the precompiled header of the engine is shared with the applications + set_property(SOURCE ${CMAKE_CURRENT_LIST_DIR}/DLSSRenderer.cpp ${ATLAS_UPSCALER_ADDONS_SOURCE} APPEND PROPERTY + COMPILE_DEFINITIONS AE_UPSCALER_DLSS "$<$>:AE_DLSS_RUNTIME_DIR=\"${ATLAS_DLSS_RUNTIME_DIR}\">") +endif() diff --git a/libs/upscalers/dlss/DLSSRenderer.cpp b/libs/upscalers/dlss/DLSSRenderer.cpp new file mode 100644 index 000000000..a28f45504 --- /dev/null +++ b/libs/upscalers/dlss/DLSSRenderer.cpp @@ -0,0 +1,237 @@ +#include "DLSSRenderer.h" +#include "graphics/Instance.h" + +#include + +#include + +namespace Atlas::Renderer { + + struct DLSSRenderer::Helpers { + static constexpr const char* projectId = "e71a5590-902c-44c5-a774-a3323a389902"; + static constexpr const char* engineVersion = "0.2.1"; + + static const wchar_t* GetDataPath() { + + // NGX writes its logs there + static const std::wstring path = std::filesystem::temp_directory_path().wstring(); + return path.c_str(); + + } + + static const NVSDK_NGX_FeatureCommonInfo* GetFeatureInfo() { + + // The DLSS library is searched next to the executable first, other than in release builds then in the SDK +#ifdef AE_DLSS_RUNTIME_DIR + static const std::wstring runtimeDir = std::filesystem::path(AE_DLSS_RUNTIME_DIR).wstring(); + static const wchar_t* paths[] = { runtimeDir.c_str() }; + static NVSDK_NGX_FeatureCommonInfo info = { .PathListInfo = { .Path = paths, .Length = 1 } }; +#else + static NVSDK_NGX_FeatureCommonInfo info = {}; +#endif + return &info; + + } + + static NVSDK_NGX_FeatureDiscoveryInfo GetDiscoveryInfo() { + + NVSDK_NGX_FeatureDiscoveryInfo info = {}; + info.SDKVersion = NVSDK_NGX_Version_API; + info.FeatureID = NVSDK_NGX_Feature_SuperSampling; + info.Identifier.IdentifierType = NVSDK_NGX_Application_Identifier_Type_Project_Id; + info.Identifier.v.ProjectDesc = { projectId, NVSDK_NGX_ENGINE_TYPE_CUSTOM, engineVersion }; + info.ApplicationDataPath = GetDataPath(); + info.FeatureInfo = GetFeatureInfo(); + return info; + + } + + static std::vector GetExtensionNames(NVSDK_NGX_Result result, uint32_t count, const VkExtensionProperties* properties) { + + std::vector names; + if (NVSDK_NGX_FAILED(result)) + return names; + + for (uint32_t i = 0; i < count; i++) + names.emplace_back(properties[i].extensionName); + return names; + + } + + static NVSDK_NGX_PerfQuality_Value GetPerfQuality(float scale) { + + // Only selects the default preset, the render size comes from the render target + if (scale >= 0.99f) return NVSDK_NGX_PerfQuality_Value_DLAA; + if (scale >= 0.62f) return NVSDK_NGX_PerfQuality_Value_MaxQuality; + if (scale >= 0.54f) return NVSDK_NGX_PerfQuality_Value_Balanced; + if (scale >= 0.42f) return NVSDK_NGX_PerfQuality_Value_MaxPerf; + return NVSDK_NGX_PerfQuality_Value_UltraPerformance; + + } + }; + + DLSSRenderer::DLSSRenderer(Graphics::GraphicsDevice* device) { + + this->device = device; + + auto result = NVSDK_NGX_VULKAN_Init_with_ProjectID(Helpers::projectId, NVSDK_NGX_ENGINE_TYPE_CUSTOM, Helpers::engineVersion, + Helpers::GetDataPath(), device->instance->GetNativeInstance(), device->physicalDevice, device->device, + vkGetInstanceProcAddr, vkGetDeviceProcAddr, Helpers::GetFeatureInfo()); + if (NVSDK_NGX_FAILED(result)) { + Log::Message("DLSS isn't available on this device (NGX result " + std::to_string(int32_t(result)) + ")"); + return; + } + initialized = true; + + int32_t available = 0, needsUpdatedDriver = 0; + result = NVSDK_NGX_VULKAN_GetCapabilityParameters(¶meters); + if (NVSDK_NGX_SUCCEED(result)) { + NVSDK_NGX_Parameter_GetI(parameters, NVSDK_NGX_Parameter_SuperSampling_Available, &available); + NVSDK_NGX_Parameter_GetI(parameters, NVSDK_NGX_Parameter_SuperSampling_NeedsUpdatedDriver, &needsUpdatedDriver); + } + + supported = available != 0; + if (supported) + Log::Message("DLSS is available"); + else if (needsUpdatedDriver) + Log::Warning("DLSS needs a newer driver"); + else + Log::Message("DLSS isn't available on this device"); + + } + + DLSSRenderer::~DLSSRenderer() { + + if (!initialized) + return; + + DLSSRenderer::DestroyContext(); + if (parameters) + NVSDK_NGX_VULKAN_DestroyParameters(parameters); + NVSDK_NGX_VULKAN_Shutdown1(device->device); + + } + + void DLSSRenderer::Render(const Ref& target, const Ref& scene, Graphics::CommandList* commandList) { + + GPUProfiler::Scope gpuScope("DLSS"); + + auto renderSize = ivec2(target->GetScaledWidth(), target->GetScaledHeight()); + + auto& camera = scene->renderState.camera; + auto targetData = target->GetData(FULL_RES); + + auto colorImage = target->lightingTexture.image; + auto depthImage = targetData->depthTexture->image; + auto velocityImage = target->GetVelocity()->image; + auto outputImage = target->hdrTexture.image; + + // NGX writes the output with compute and transfer commands (it clears it on a reset) + Graphics::ImageBarrier imageBarriers[] = { + {colorImage, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_ACCESS_SHADER_READ_BIT}, + {depthImage, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_ACCESS_SHADER_READ_BIT}, + {velocityImage, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_ACCESS_SHADER_READ_BIT}, + {outputImage, VK_IMAGE_LAYOUT_GENERAL, VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT}, + }; + commandList->PipelineBarrier(imageBarriers, {}, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); + + auto getResource = [](const Ref& image, bool readWrite) { + VkImageSubresourceRange range = { image->aspectFlags, 0, 1, 0, 1 }; + return NVSDK_NGX_Create_ImageView_Resource_VK(image->view, image->image, range, image->format, + image->width, image->height, readWrite); + }; + + auto color = getResource(colorImage, false); + auto depth = getResource(depthImage, false); + auto velocity = getResource(velocityImage, false); + auto output = getResource(outputImage, true); + + NVSDK_NGX_VK_DLSS_Eval_Params evalParams = {}; + evalParams.Feature.pInColor = &color; + evalParams.Feature.pInOutput = &output; + evalParams.pInDepth = &depth; + evalParams.pInMotionVectors = &velocity; + // Same conventions as for FSR2: jitter in render pixels, motion vectors in UV space towards the last frame + evalParams.InJitterOffsetX = camera.GetJitter().x * float(renderSize.x) * 0.5f; + evalParams.InJitterOffsetY = camera.GetJitter().y * float(renderSize.y) * 0.5f; + evalParams.InMVScaleX = float(renderSize.x); + evalParams.InMVScaleY = float(renderSize.y); + evalParams.InRenderSubrectDimensions = { uint32_t(renderSize.x), uint32_t(renderSize.y) }; + evalParams.InReset = target->HasHistory() ? 0 : 1; + evalParams.InFrameTimeDeltaInMsec = scene->renderState.deltaTime * 1000.0f; + evalParams.InPreExposure = scene->renderState.preExposure; + + auto result = NGX_VULKAN_EVALUATE_DLSS_EXT(commandList->commandBuffer, feature, parameters, &evalParams); + commandList->InvalidateBoundState(); + if (NVSDK_NGX_FAILED(result)) { + Log::Warning("DLSS evaluation failed (NGX result " + std::to_string(int32_t(result)) + "), using FSR 2 instead"); + MarkContextFailed(); + } + + commandList->ImageMemoryBarrier(outputImage, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, + VK_ACCESS_SHADER_READ_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, + VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT); + + } + + std::vector DLSSRenderer::GetInstanceExtensions() { + + auto discoveryInfo = Helpers::GetDiscoveryInfo(); + uint32_t count = 0; + VkExtensionProperties* properties = nullptr; + auto result = NVSDK_NGX_VULKAN_GetFeatureInstanceExtensionRequirements(&discoveryInfo, &count, &properties); + return Helpers::GetExtensionNames(result, count, properties); + + } + + std::vector DLSSRenderer::GetDeviceExtensions(VkInstance instance, VkPhysicalDevice physicalDevice) { + + auto discoveryInfo = Helpers::GetDiscoveryInfo(); + uint32_t count = 0; + VkExtensionProperties* properties = nullptr; + auto result = NVSDK_NGX_VULKAN_GetFeatureDeviceExtensionRequirements(instance, physicalDevice, + &discoveryInfo, &count, &properties); + return Helpers::GetExtensionNames(result, count, properties); + + } + + bool DLSSRenderer::CreateContext(ivec2 renderSize, ivec2 displaySize, Graphics::CommandList* commandList) { + + NVSDK_NGX_DLSS_Create_Params createParams = {}; + createParams.Feature.InWidth = uint32_t(renderSize.x); + createParams.Feature.InHeight = uint32_t(renderSize.y); + createParams.Feature.InTargetWidth = uint32_t(displaySize.x); + createParams.Feature.InTargetHeight = uint32_t(displaySize.y); + createParams.Feature.InPerfQualityValue = Helpers::GetPerfQuality(float(renderSize.x) / float(displaySize.x)); + // The lighting is linear HDR, the exposure is only known after the upscaling + createParams.InFeatureCreateFlags = NVSDK_NGX_DLSS_Feature_Flags_IsHDR | NVSDK_NGX_DLSS_Feature_Flags_MVLowRes | + NVSDK_NGX_DLSS_Feature_Flags_AutoExposure; + + auto result = NGX_VULKAN_CREATE_DLSS_EXT1(device->device, commandList->commandBuffer, 1, 1, + &feature, parameters, &createParams); + commandList->InvalidateBoundState(); + + if (NVSDK_NGX_FAILED(result)) { + Log::Warning("Couldn't create the DLSS feature for " + std::to_string(renderSize.x) + "x" + std::to_string(renderSize.y) + + " (NGX result " + std::to_string(int32_t(result)) + "), using FSR 2 instead"); + feature = nullptr; + return false; + } + + return true; + + } + + void DLSSRenderer::DestroyContext() { + + if (!feature) + return; + + // The feature may still be used by command lists in flight + device->WaitForIdle(); + NVSDK_NGX_VULKAN_ReleaseFeature(feature); + feature = nullptr; + + } + +} diff --git a/libs/upscalers/dlss/DLSSRenderer.h b/libs/upscalers/dlss/DLSSRenderer.h new file mode 100644 index 000000000..a322797be --- /dev/null +++ b/libs/upscalers/dlss/DLSSRenderer.h @@ -0,0 +1,45 @@ +#pragma once + +#include "renderer/UpscalingRenderer.h" + +struct NVSDK_NGX_Handle; +struct NVSDK_NGX_Parameter; + +namespace Atlas::Renderer { + + // NVIDIA DLSS super resolution through NGX, which loads the DLSS library of the SDK + class DLSSRenderer : public VendorUpscalingRenderer { + + public: + explicit DLSSRenderer(Graphics::GraphicsDevice* device); + + ~DLSSRenderer(); + + bool IsSupported() const override { return supported; } + + void Render(const Ref& target, const Ref& scene, Graphics::CommandList* commandList) override; + + static std::vector GetInstanceExtensions(); + + static std::vector GetDeviceExtensions(VkInstance instance, VkPhysicalDevice physicalDevice); + + protected: + bool HasContext() const override { return feature != nullptr; } + + bool CreateContext(ivec2 renderSize, ivec2 displaySize, Graphics::CommandList* commandList) override; + + void DestroyContext() override; + + private: + // Defined with the source file, their types stay out of this header + struct Helpers; + + bool initialized = false; + bool supported = false; + + NVSDK_NGX_Parameter* parameters = nullptr; + NVSDK_NGX_Handle* feature = nullptr; + + }; + +} diff --git a/libs/upscalers/fsr4/FSR4.cmake b/libs/upscalers/fsr4/FSR4.cmake new file mode 100644 index 000000000..274c0527e --- /dev/null +++ b/libs/upscalers/fsr4/FSR4.cmake @@ -0,0 +1,14 @@ +option(ATLAS_FSR4 "Build the FSR 4 upscaler when its SDK is found" ON) +set(ATLAS_FSR4_SDK "${CMAKE_CURRENT_LIST_DIR}/sdk" CACHE PATH "Headers and the signed Vulkan upscaler library of the AMD FSR SDK") + +# The SDK only has signed libraries for Windows +if (ATLAS_FSR4 AND EXISTS "${ATLAS_FSR4_SDK}/upscalers/include/ffx_upscale.h" AND WIN32) + message(STATUS "Building the FSR 4 upscaler with ${ATLAS_FSR4_SDK}") + + target_sources(AtlasEngine PRIVATE ${CMAKE_CURRENT_LIST_DIR}/FSR4Renderer.cpp ${CMAKE_CURRENT_LIST_DIR}/FSR4Renderer.h) + target_include_directories(AtlasEngine PRIVATE ${ATLAS_FSR4_SDK}) + + # The upscaler library is loaded at runtime from the executable folder, other than in release builds also from this one + set_property(SOURCE ${CMAKE_CURRENT_LIST_DIR}/FSR4Renderer.cpp ${ATLAS_UPSCALER_ADDONS_SOURCE} APPEND PROPERTY + COMPILE_DEFINITIONS AE_UPSCALER_FSR4 "$<$>:AE_FSR4_RUNTIME_DIR=\"${ATLAS_FSR4_SDK}/bin\">") +endif() diff --git a/libs/upscalers/fsr4/FSR4Renderer.cpp b/libs/upscalers/fsr4/FSR4Renderer.cpp new file mode 100644 index 000000000..b51d184c5 --- /dev/null +++ b/libs/upscalers/fsr4/FSR4Renderer.cpp @@ -0,0 +1,237 @@ +#include "FSR4Renderer.h" + +#include +#include + +#include + +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include + +namespace Atlas::Renderer { + + struct FSR4Renderer::Functions { + PfnFfxCreateContext createContext = nullptr; + PfnFfxDestroyContext destroyContext = nullptr; + PfnFfxQuery query = nullptr; + PfnFfxDispatch dispatch = nullptr; + }; + + struct FSR4Renderer::Helpers { + static constexpr const wchar_t* libraryName = L"amd_fidelityfx_upscaler_vk.dll"; + + static HMODULE LoadUpscalerLibrary() { + + // The library is searched next to the executable first, other than in release builds then in the SDK + wchar_t executablePath[MAX_PATH]; + GetModuleFileNameW(nullptr, executablePath, MAX_PATH); + auto path = std::filesystem::path(executablePath).parent_path() / libraryName; +#ifdef AE_FSR4_RUNTIME_DIR + if (!std::filesystem::exists(path)) + path = std::filesystem::path(AE_FSR4_RUNTIME_DIR) / libraryName; +#endif + + return LoadLibraryW(path.c_str()); + + } + + static void LogMessage(uint32_t type, const wchar_t* message) { + + auto text = "FSR: " + std::filesystem::path(message).string(); + if (type == FFX_API_MESSAGE_TYPE_ERROR) + Log::Error(text); + else + Log::Warning(text); + + } + + static FfxApiResource GetResource(const Ref& image, uint32_t usage, uint32_t state) { + + FfxApiResourceDescription description = {}; + description.type = FFX_API_RESOURCE_TYPE_TEXTURE2D; + description.format = ffxApiGetSurfaceFormatVK(image->format); + description.width = image->width; + description.height = image->height; + description.depth = 1; + description.mipCount = 1; + description.usage = usage; + + return ffxApiGetResourceVK(reinterpret_cast(image->image), description, state); + + } + }; + + FSR4Renderer::FSR4Renderer(Graphics::GraphicsDevice* device) : functions(std::make_unique()) { + + this->device = device; + + auto module = Helpers::LoadUpscalerLibrary(); + if (!module) { + Log::Message("FSR 4 isn't available, " + std::filesystem::path(Helpers::libraryName).string() + " wasn't found"); + return; + } + library = module; + + functions->createContext = reinterpret_cast(GetProcAddress(module, "ffxCreateContext")); + functions->destroyContext = reinterpret_cast(GetProcAddress(module, "ffxDestroyContext")); + functions->query = reinterpret_cast(GetProcAddress(module, "ffxQuery")); + functions->dispatch = reinterpret_cast(GetProcAddress(module, "ffxDispatch")); + + VkDeviceContext deviceContext = { device->device, device->physicalDevice, vkGetDeviceProcAddr }; + + uint64_t versionCount = 0; + ffxQueryDescGetVersions versionQuery = {}; + versionQuery.header.type = FFX_API_QUERY_DESC_TYPE_GET_VERSIONS; + versionQuery.createDescType = FFX_API_CREATE_CONTEXT_DESC_TYPE_UPSCALE; + versionQuery.device = &deviceContext; + versionQuery.outputCount = &versionCount; + functions->query(nullptr, &versionQuery.header); + + std::vector versionNames(versionCount); + versionQuery.versionNames = versionNames.data(); + functions->query(nullptr, &versionQuery.header); + + std::string versions; + for (auto name : versionNames) + versions += (versions.empty() ? "" : ", ") + std::string(name); + + supported = versionCount > 0; + if (supported) + Log::Message("FSR upscaler versions available on this device: " + versions); + else + Log::Message("The FSR upscaler isn't available on this device"); + + } + + FSR4Renderer::~FSR4Renderer() { + + FSR4Renderer::DestroyContext(); + if (library) + FreeLibrary(static_cast(library)); + + } + + void FSR4Renderer::Render(const Ref& target, const Ref& scene, Graphics::CommandList* commandList) { + + GPUProfiler::Scope gpuScope("FSR4"); + + auto renderSize = ivec2(target->GetScaledWidth(), target->GetScaledHeight()); + auto displaySize = ivec2(target->GetWidth(), target->GetHeight()); + + auto& postProcessing = scene->renderState.postProcessing; + auto& camera = scene->renderState.camera; + auto targetData = target->GetData(FULL_RES); + + auto colorImage = target->lightingTexture.image; + auto depthImage = targetData->depthTexture->image; + auto velocityImage = target->GetVelocity()->image; + auto reactiveMaskImage = target->reactiveMaskTexture.image; + auto outputImage = target->hdrTexture.image; + + bool reactiveMask = !target->IsUsedForPathTracing(); + + std::vector imageBarriers = { + {colorImage, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_ACCESS_SHADER_READ_BIT}, + {depthImage, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_ACCESS_SHADER_READ_BIT}, + {velocityImage, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_ACCESS_SHADER_READ_BIT}, + {outputImage, VK_IMAGE_LAYOUT_GENERAL, VK_ACCESS_SHADER_WRITE_BIT}, + }; + if (reactiveMask) + imageBarriers.push_back({reactiveMaskImage, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_ACCESS_SHADER_READ_BIT}); + commandList->PipelineBarrier(imageBarriers, {}, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT); + + ffxDispatchDescUpscale dispatch = {}; + dispatch.header.type = FFX_API_DISPATCH_DESC_TYPE_UPSCALE; + dispatch.commandList = commandList->commandBuffer; + dispatch.color = Helpers::GetResource(colorImage, FFX_API_RESOURCE_USAGE_READ_ONLY, FFX_API_RESOURCE_STATE_COMPUTE_READ); + dispatch.depth = Helpers::GetResource(depthImage, FFX_API_RESOURCE_USAGE_DEPTHTARGET, FFX_API_RESOURCE_STATE_COMPUTE_READ); + dispatch.motionVectors = Helpers::GetResource(velocityImage, FFX_API_RESOURCE_USAGE_READ_ONLY, FFX_API_RESOURCE_STATE_COMPUTE_READ); + if (reactiveMask) + dispatch.reactive = Helpers::GetResource(reactiveMaskImage, FFX_API_RESOURCE_USAGE_READ_ONLY, FFX_API_RESOURCE_STATE_COMPUTE_READ); + dispatch.output = Helpers::GetResource(outputImage, FFX_API_RESOURCE_USAGE_UAV, FFX_API_RESOURCE_STATE_UNORDERED_ACCESS); + // Same conventions as for FSR2: jitter in render pixels, motion vectors in UV space towards the last frame + dispatch.jitterOffset = { camera.GetJitter().x * float(renderSize.x) * 0.5f, camera.GetJitter().y * float(renderSize.y) * 0.5f }; + dispatch.motionVectorScale = { float(renderSize.x), float(renderSize.y) }; + dispatch.renderSize = { uint32_t(renderSize.x), uint32_t(renderSize.y) }; + dispatch.upscaleSize = { uint32_t(displaySize.x), uint32_t(displaySize.y) }; + dispatch.enableSharpening = postProcessing.sharpen.enable; + dispatch.sharpness = postProcessing.sharpen.factor; + dispatch.frameTimeDelta = scene->renderState.deltaTime * 1000.0f; + dispatch.preExposure = scene->renderState.preExposure; + dispatch.reset = !target->HasHistory(); + dispatch.cameraNear = camera.nearPlane; + dispatch.cameraFar = camera.farPlane; + dispatch.cameraFovAngleVertical = glm::radians(camera.fieldOfView); + dispatch.viewSpaceToMetersFactor = 1.0f; + + auto result = functions->dispatch(&context, &dispatch.header); + commandList->InvalidateBoundState(); + if (result != FFX_API_RETURN_OK) { + Log::Warning("The FSR dispatch failed (result " + std::to_string(result) + "), using FSR 2 instead"); + MarkContextFailed(); + } + + commandList->ImageMemoryBarrier(outputImage, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, + VK_ACCESS_SHADER_READ_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, + VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT); + + } + + std::vector FSR4Renderer::GetDeviceExtensions() { + + // The machine learning upscaler runs with cooperative matrices, on RDNA 4 with 8 bit floats + return { VK_KHR_COOPERATIVE_MATRIX_EXTENSION_NAME, VK_EXT_SHADER_FLOAT8_EXTENSION_NAME }; + + } + + bool FSR4Renderer::CreateContext(ivec2 renderSize, ivec2 displaySize, Graphics::CommandList* commandList) { + + ffxCreateBackendVKDesc backendDesc = {}; + backendDesc.header.type = FFX_API_CREATE_CONTEXT_DESC_TYPE_BACKEND_VK; + backendDesc.deviceContext = { device->device, device->physicalDevice, vkGetDeviceProcAddr }; + + ffxCreateContextDescUpscale createDesc = {}; + createDesc.header.type = FFX_API_CREATE_CONTEXT_DESC_TYPE_UPSCALE; + createDesc.header.pNext = &backendDesc.header; + // The lighting is linear HDR, the exposure is only known after the upscaling + createDesc.flags = FFX_UPSCALE_ENABLE_HIGH_DYNAMIC_RANGE | FFX_UPSCALE_ENABLE_AUTO_EXPOSURE; + createDesc.maxRenderSize = { uint32_t(renderSize.x), uint32_t(renderSize.y) }; + createDesc.maxUpscaleSize = { uint32_t(displaySize.x), uint32_t(displaySize.y) }; + createDesc.fpMessage = Helpers::LogMessage; + + auto result = functions->createContext(&context, &createDesc.header, nullptr); + if (result != FFX_API_RETURN_OK) { + Log::Warning("Couldn't create the FSR upscaler context for " + std::to_string(renderSize.x) + "x" + std::to_string(renderSize.y) + + " (result " + std::to_string(result) + "), using FSR 2 instead"); + context = nullptr; + return false; + } + + ffxQueryGetProviderVersion versionQuery = {}; + versionQuery.header.type = FFX_API_QUERY_DESC_TYPE_GET_PROVIDER_VERSION; + functions->query(&context, &versionQuery.header); + if (versionQuery.versionName) + Log::Message("Upscaling with FSR " + std::string(versionQuery.versionName)); + + return true; + + } + + void FSR4Renderer::DestroyContext() { + + if (!context) + return; + + // The context may still be used by command lists in flight + device->WaitForIdle(); + functions->destroyContext(&context, nullptr); + context = nullptr; + + } + +} diff --git a/libs/upscalers/fsr4/FSR4Renderer.h b/libs/upscalers/fsr4/FSR4Renderer.h new file mode 100644 index 000000000..d1d105ebd --- /dev/null +++ b/libs/upscalers/fsr4/FSR4Renderer.h @@ -0,0 +1,45 @@ +#pragma once + +#include "renderer/UpscalingRenderer.h" + +namespace Atlas::Renderer { + + // AMD FSR upscaler of the FSR SDK, whose signed library selects FSR 4 on supported GPUs and FSR 3 otherwise + class FSR4Renderer : public VendorUpscalingRenderer { + + public: + explicit FSR4Renderer(Graphics::GraphicsDevice* device); + + ~FSR4Renderer(); + + bool IsSupported() const override { return supported; } + + bool UsesReactiveMask() const override { return true; } + + bool Sharpens() const override { return true; } + + void Render(const Ref& target, const Ref& scene, Graphics::CommandList* commandList) override; + + static std::vector GetDeviceExtensions(); + + protected: + bool HasContext() const override { return context != nullptr; } + + bool CreateContext(ivec2 renderSize, ivec2 displaySize, Graphics::CommandList* commandList) override; + + void DestroyContext() override; + + private: + struct Functions; + // Defined with the source file, their types stay out of this header + struct Helpers; + + void* library = nullptr; + std::unique_ptr functions; + void* context = nullptr; + + bool supported = false; + + }; + +} diff --git a/src/bridge/App.cpp b/src/bridge/App.cpp new file mode 100644 index 000000000..285fdb862 --- /dev/null +++ b/src/bridge/App.cpp @@ -0,0 +1,2084 @@ +#include "App.h" +#include "TerrainTools.h" +#include "SceneEditor.h" +#include "Check.h" +#include "Summary.h" +#include "Tools.h" +#include "InstanceRegistry.h" +#include "Processes.h" + +#include "Serializer.h" +#include "loader/ImageLoader.h" +#include "resource/ResourceManager.h" +#include "scripting/Script.h" +#include "scene/components/LuaScriptComponent.h" +#include "graphics/GraphicsDevice.h" +#include "profiler/CPUProfiler.h" +#include "profiler/GPUProfiler.h" +#include "profiler/HitchRecorder.h" +#include "streaming/StreamingManager.h" +#include "materialgraph/PipelineCache.h" +#include "Clock.h" +#include "audio/AudioManager.h" + +#include + +#include +#include + +const Atlas::EngineConfig Atlas::EngineInstance::engineConfig = { + .assetDirectory = "../../data", + .shaderDirectory = "shader", + .commandLineTool = [](const std::vector& args) { return Atlas::Bridge::RunCommandLineTool(args, "../../data"); } +}; + +namespace Atlas::Bridge { + + using namespace Scene::Components; + + struct ViewAngles { + + float azimuth; + float elevation; + + }; + + static ViewAngles GetViewAngles(const std::string& view) { + + // Azimuth 0 places the camera on the +Z side looking towards -Z + static const std::map views = { + { "front", { 0.0f, 15.0f } }, + { "right", { 90.0f, 15.0f } }, + { "back", { 180.0f, 15.0f } }, + { "left", { 270.0f, 15.0f } }, + { "top", { 0.0f, 89.0f } }, + { "iso", { 45.0f, 35.0f } }, + // Almost at ground level, best to see whether something floats + { "low", { 0.0f, 2.0f } }, + { "lowSide", { 90.0f, 2.0f } }, + }; + + auto it = views.find(view); + if (it == views.end()) + throw std::runtime_error("Unknown view '" + view + "' (front, right, back, left, top, iso, low, lowSide)"); + + return it->second; + + } + + // Keep scripts active with a minimal time step while waiting for real-time playback + static constexpr float freezeDeltaTime = 1e-5f; + + void App::LoadContent() { + + startTime = std::chrono::steady_clock::now(); + report.InstallCrashHandlers(); + InstanceRegistry::Register(args); + + // Pictures never show the fallback of a material graph + MaterialGraph::PipelineCache::asynchronous = false; + + // Jobs edit, save and bake resources and take pictures right away, --streaming measures the streaming instead. + // A pipeline without shots never takes pictures: it streams, so a world build doesn't fill the GPU memory + auto hasArg = [&](const char* arg) { return std::find(args.begin(), args.end(), arg) != args.end(); }; + if (hasArg("--pipeline") && hasArg("--no-shots")) { + // Edits need little of the GPU: what the pipeline window shows stays small, impostors are baked at full size + Streaming::StreamingManager::settings.textures.budget = 512; + Streaming::StreamingManager::settings.impostors.budget = 512; + Streaming::StreamingManager::settings.meshes.budget = 1024; + } + else if (!hasArg("--streaming")) { + Streaming::StreamingManager::settings.textures.enable = false; + Streaming::StreamingManager::settings.impostors.enable = false; + Streaming::StreamingManager::settings.meshes.enable = false; + } + + // A server or a pipeline runs several jobs, the other options of the command line apply to each of them + std::string serve, pipelineFile, from; + bool force = false; + for (size_t i = 1; i < args.size(); i++) { + if (args[i] == "--serve" && i + 1 < args.size()) + serve = args[++i]; + else if (args[i] == "--pipeline" && i + 1 < args.size()) + pipelineFile = args[++i]; + else if (args[i] == "--from" && i + 1 < args.size()) + from = args[++i]; + else if (args[i] == "--force") + force = true; + else + jobArguments.push_back(args[i]); + } + + // Muted until a job asks for the sound + Audio::AudioManager::Mute(); + + try { + if (!serve.empty()) { + mode = Mode::Server; + std::vector serverOptions; + for (const auto& option : { "--streaming", "--validation" }) + if (std::find(args.begin(), args.end(), option) != args.end()) + serverOptions.push_back(option); + server.emplace(ResolveUserPath(serve), serverOptions); + + // Scenes can be loaded before the first job, which sets up the renderer for its resolution + captureRenderer.Init(mainRenderer, job.resolution); + defaultRenderScale = captureRenderer.GetRenderScale(); + rendererInitialized = true; + overlay = std::make_unique(); + + if (std::find(jobArguments.begin(), jobArguments.end(), "--hidden") == jobArguments.end()) { + font = CreateRef("font/roboto.ttf", 16.0f, 5); + auto panelHeight = CaptureRenderer::GetPanelHeight(font, outputLineCount + 1); + window.SetSize(job.resolution.x, job.resolution.y + int32_t(panelHeight)); + ShowWindow(std::find(jobArguments.begin(), jobArguments.end(), "--foreground") != jobArguments.end()); + } + + report.Print("Serving commands from " + server->directory.string()); + SetIdle(); + return; + } + if (!pipelineFile.empty()) { + mode = Mode::Pipeline; + pipeline = Pipeline::Load(ResolveUserPath(pipelineFile), from, force); + report.Print("Pipeline '" + pipeline->name + "' with " + std::to_string(pipeline->steps.size()) + " steps, snapshots in " + + pipeline->snapshotDirectory.string()); + pipeline->Prepare([&](const std::string& message) { report.Print(message); }); + StartPipelineStep(); + return; + } + job = ParseCommandLine(args); + } + catch (const std::exception& e) { + std::string message = e.what(); + std::printf("%s\n", message.c_str()); + phase = Phase::Done; + Exit(message.starts_with("Usage:") ? 0 : 2); + return; + } + + StartJob(job); + + } + + Job App::ParseJobFile(const fs::path& path, const std::vector& extraArguments) const { + + // Options before the job file are kept, the job file can't override them + std::vector jobArgs = { args.front() }; + jobArgs.insert(jobArgs.end(), jobArguments.begin(), jobArguments.end()); + jobArgs.insert(jobArgs.end(), extraArguments.begin(), extraArguments.end()); + jobArgs.push_back(path.string()); + return ParseCommandLine(jobArgs); + + } + + void App::ResetJobState() { + + fatal = false; + activeCamera.reset(); + captureRequests.clear(); + pendingReadbacks.clear(); + sheets.clear(); + sheetOrder.clear(); + jobSheetImages.clear(); + jobSheetLabels.clear(); + shotState = {}; + stillState = {}; + baseSettings = json(); + editFrames = 0; + RevertUnsavedEdits(editState); + editState = EditState(); + UpdatePipelinesOfMaterials(ReloadMaterials(settingsMaterials)); + settingsMaterials.clear(); + variantCaptures.clear(); + stripCameras.clear(); + + player.Reset(job); + nextCheckTime = 0.0f; + nextTrackTime = 0.0f; + + queryResults = json::array(); + checkRunner.reset(); + tracker.reset(); + + report.Reset(job); + + frameCount = 0; + readyFrame = -1; + rtWaitFrames = 0; + loadSeconds = 0.0f; + phaseBeforeFinish = Phase::Prepare; + + } + + void App::StartJob(const Job& nextJob) { + + job = nextJob; + ResetJobState(); + startTime = std::chrono::steady_clock::now(); + + if (auto error = report.Begin(); !error.empty()) { + report.Error(error); + report.Print("Status: error (" + error + ")"); + report.exitCode = 2; + report.data = { { "job", job.name }, { "status", "error" }, { "exitCode", 2 }, { "reason", error } }; + FinishJob(); + return; + } + + if (job.showWindow) { + if (!font) + font = CreateRef("font/roboto.ttf", 16.0f, 5); + + // The frame keeps its aspect ratio above the output panel, large captures are shown smaller + auto panelHeight = CaptureRenderer::GetPanelHeight(font, outputLineCount + 1); + auto scale = std::min({ 1.0f, 1600.0f / float(job.resolution.x), 900.0f / float(job.resolution.y) }); + window.SetSize(int32_t(float(job.resolution.x) * scale), int32_t(float(job.resolution.y) * scale + panelHeight)); + ShowWindow(job.foreground); + } + else if (mode != Mode::Job) { + window.Hide(); + } + + // The profilers are disabled by default in release builds, hitches need the CPU profile. The GPU queries write the + // checkpoints of the crash diagnostics + CPUProfiler::enable = job.profileFrames > 0 || job.hitches.has_value(); + GPUProfiler::enable = job.profileFrames > 0 || (job.hitches && job.hitches->gpu) || + Graphics::GraphicsDevice::DefaultDevice->support.diagnosticCheckpoints; + outputFrame = false; + if (job.hitches) { + auto hitchSettings = HitchRecorder::GetSettings(); + hitchSettings.cpu.minimumTime = job.hitches->minimumFrameTime; + hitchSettings.cpu.relativeThreshold = job.hitches->relativeThreshold; + hitchSettings.gpu.enable = job.hitches->gpu; + HitchRecorder::SetSettings(hitchSettings); + } + + if (job.sound) + Audio::AudioManager::Unmute(); + else + Audio::AudioManager::Mute(); + + report.Print("Job '" + job.name + "' with scene " + job.scene + " (run " + report.runId + ")" + + (report.previousSeconds > 0.0f ? ", the previous run took " + FormatFloat(report.previousSeconds, 0) + " s" : "")); + SetBusyActivity(); + if (server) + server->WriteStatus("running", job.scene, job.name); + + if (job.validation && !report.EnableValidation()) { + Fail("Validation layers aren't available, they are part of the Vulkan SDK"); + return; + } + report.Print("Output directory: " + job.outputDirectory.string()); + + // A direct run was checked before the engine started, servers and pipelines check their jobs here without the preflight + if (mode != Mode::Job) { + for (const auto& issue : CheckJob(job, false)) { + if (issue.starts_with("ERROR")) { + Fail(issue.substr(7)); + return; + } + report.Print(issue); + } + } + + if (!rendererInitialized) { + captureRenderer.Init(mainRenderer, job.resolution); + defaultRenderScale = captureRenderer.GetRenderScale(); + rendererInitialized = true; + } + else if (captureRenderer.resolution != job.resolution) { + // Resources of the previous resolution may still be in use by frames in flight + graphicsDevice->WaitForIdle(); + captureRenderer.Resize(job.resolution); + } + captureRenderer.SetRenderScale(job.renderScale.value_or(defaultRenderScale)); + baseRenderScale = captureRenderer.GetRenderScale(); + overlay = std::make_unique(); + + // The mouse over a shown window must not turn the players of a running job + playerInput.useMouse = false; + + checkRunner = std::make_unique(job.checks); + if (job.track) + tracker = std::make_unique(*job.track); + + // Load with the camera of the first shot such that streaming and probes start in the right area. Entities an + // edit adds don't exist yet, such shots are framed once the edit is done + if (!job.shots.empty() && !(job.edit && job.shots.front().camera.mode == "focus")) + activeCamera = job.shots.front().camera; + else if (job.edit && !job.shots.empty()) + activeCamera = CameraSpec { .mode = "overview" }; + else + activeCamera = job.observer.value_or(CameraSpec {}); + + // Capture errors that happen while loading + report.SkipLog(); + + if (scene && scenePath == job.scene && !sceneDirty) { + // The scene starts each job with the settings it was loaded with, out of play mode + ApplySettings(*scene, sceneSettings, settingsMaterials); + scene->physicsWorld->pauseSimulation = true; + scene->paused = false; + captureRenderer.InvalidateHistory(); + report.Print("Using the loaded scene"); + phase = Phase::Prepare; + return; + } + if (scene && mode == Mode::Server) { + // A played or edited scene is loaded again, its meshes with their materials and textures stay loaded + if (scenePath == job.scene) { + retainedMeshes = scene->GetMeshes(); + report.Print("Loading the scene again, the last job played or edited it"); + } + UnloadScene(); + } + else if (scene) { + Fail("The job uses " + job.scene + ", but " + scenePath + " is loaded, unload it first"); + return; + } + + keepScene = false; + LoadScene(job.scene); + + } + + void App::LoadScene(const std::string& path) { + + scenePath = path; + if (!job.waitGpu) { + SetBusyActivity(); + BeginLoading(); + return; + } + + // Scenes of other engine applications fill the GPU memory, a second one on top of them runs out of it + phase = Phase::WaitingForGpu; + gpuWaitStart = std::chrono::steady_clock::now(); + nextGpuCheck = gpuWaitStart; + nextGpuWaitPrint = gpuWaitStart; + gpuWaitReason.clear(); + InstanceRegistry::QueueForGpu("waiting for the GPU to load " + path); + if (server) + server->WriteStatus("waiting for the GPU", path, job.name); + + } + + void App::UpdateGpuWait() { + + auto now = std::chrono::steady_clock::now(); + if (now < nextGpuCheck) + return; + nextGpuCheck = now + std::chrono::milliseconds(500); + + std::vector ahead; + auto seconds = SecondsSince(gpuWaitStart); + if (InstanceRegistry::PollGpu(ahead)) { + // The wait doesn't count into the duration of the job, the next run expects its end from that + startTime += now - gpuWaitStart; + report.data["gpuWaitSeconds"] = Round(seconds, 1); + if (!gpuWaitReason.empty()) + report.Print("The GPU is free after " + FormatFloat(seconds, 0) + " s, loading " + scenePath); + if (server) + server->WriteStatus(loadingForCommand ? "loading" : "running", scenePath, loadingForCommand ? "" : job.name); + SetBusyActivity(); + BeginLoading(); + return; + } + + if (seconds > job.gpuWaitTimeout) { + Fail("The GPU is still busy after " + FormatFloat(seconds, 0) + " s (gpuWaitTimeout), waiting for " + gpuWaitReason); + return; + } + + // Nobody ahead: this process claimed the GPU and gets it in the next step + if (ahead.empty()) + return; + + auto reason = InstanceRegistry::Describe(ahead); + if (reason != gpuWaitReason || now >= nextGpuWaitPrint) { + report.Print("Waiting for the GPU before loading " + scenePath + " (" + FormatFloat(seconds, 0) + " s): " + reason); + nextGpuWaitPrint = now + std::chrono::seconds(60); + } + gpuWaitReason = reason; + + } + + void App::BeginLoading() { + + loadStartTime = std::chrono::steady_clock::now(); + frameCount = 0; + rtWaitFrames = 0; + phase = Phase::Loading; + const auto& path = scenePath; + + try { + auto binary = fs::path(path).extension() != ".json"; + scene = Serializer::DeserializeScene(path, binary); + } + catch (const std::exception& e) { + scene.reset(); + Fail("Couldn't load scene " + path + ": " + e.what()); + return; + } + + if (!scene) { + Fail("Couldn't load scene " + path); + return; + } + + CreateCaptureCamera(); + + } + + void App::UnloadScene() { + + if (!scene) + return; + + graphicsDevice->WaitForIdle(); + // The Lua environment of the player references the script state of the scene + player.Stop(); + scene.reset(); + scenePath.clear(); + sceneSettings = json(); + captureCameraEntity = Scene::Entity(); + keepScene = false; + sceneDirty = false; + + } + + void App::UnloadContent() { + + if (phase != Phase::Done && phase != Phase::Idle) { + // A lost device ends the main loop like a closed window, e.g. when the scene exceeds the GPU memory + Fail(graphicsDevice->isDeviceLost ? "The GPU device was lost before the job finished (out of GPU memory?)" : + "The window was closed before the job finished"); + Finish(); + } + report.End(); + + graphicsDevice->WaitForIdle(); + report.DestroyValidation(); + player.Stop(); + scene.reset(); + InstanceRegistry::Unregister(); + + } + + void App::Update(float deltaTime) { + + if (phase == Phase::Done) + return; + + if (outputFrame) { + // The profiler dropped the frame which wrote the images, its frame time arrives now + outputFrame = false; + CPUProfiler::enable = true; + } + else { + report.BeginFrame(job.profileFrames); + } + { + CPUProfiler::Scope profilerScope("Wait for previous frame"); + graphicsDevice->WaitForPreviousFrameSubmission(); + } + + auto waiting = phase == Phase::Idle || phase == Phase::WaitingForGpu; + if (vsync != waiting) { + vsync = waiting; + graphicsDevice->CreateSwapChain(vsync ? VK_PRESENT_MODE_FIFO_KHR : VK_PRESENT_MODE_IMMEDIATE_KHR, + graphicsDevice->swapChain->colorSpace); + // A new swap chain and its first presents can bring the window to the front + if (job.showWindow && !job.foreground && !window.IsFocused()) + backgroundUntil = Clock::Get() + 3.0f; + } + + if (backgroundUntil > Clock::Get()) { + if (window.IsFocused()) + backgroundUntil = 0.0f; + else + MoveWindowToBack(window.GetSDLWindow()); + } + + try { + // Writing the images takes much longer than a frame + if (job.profileFrames > 0 && !pendingReadbacks.empty()) { + CPUProfiler::enable = false; + outputFrame = true; + } + + CPUProfiler::Scope sectionScope("Readback"); + ProcessReadback(); + sectionScope.Next("Collect log"); + CollectLog(); + + frameCount++; + + if (server && phase != Phase::Idle && phase != Phase::Done && phase != Phase::Finish && server->IsCancelled()) + Fail("Cancelled by the client"); + + switch (phase) { + case Phase::Idle: + sectionScope.Next("Commands"); + ProcessNextCommand(); + break; + case Phase::WaitingForGpu: + sectionScope.Next("Wait for the GPU"); + UpdateGpuWait(); + // Leaves the GPU to the others, also without vsync in a hidden window + std::this_thread::sleep_for(std::chrono::milliseconds(50)); + break; + case Phase::Loading: { + sectionScope.Next("Loading"); + UpdateSceneWithCaptureCamera(*activeCamera); + auto elapsed = std::chrono::duration(std::chrono::steady_clock::now() - loadStartTime).count(); + if (IsSceneReady()) { + for (const auto& mesh : scene->GetMeshes()) + if (mesh.IsValid() && !mesh.IsLoaded()) + report.Warn("Mesh " + mesh.GetResource()->path + " failed to load"); + + loadSeconds = elapsed; + sceneSettings = ExportSettings(*scene); + report.Print("Scene ready after " + FormatFloat(loadSeconds, 1) + "s (" + std::to_string(frameCount) + + " frames, " + std::to_string(scene->GetEntityCount() - 1) + " entities)"); + retainedMeshes.clear(); + if (loadingForCommand) { + loadingForCommand = false; + SetIdle(); + CompleteCommand({ { "status", "ok" }, { "loadSeconds", loadSeconds }, + { "entities", scene->GetEntityCount() - 1 }, { "warnings", report.warnings } }); + } + else { + phase = Phase::Prepare; + } + } + else if (elapsed > job.loadTimeout) { + Fail("Scene didn't finish loading within " + FormatFloat(job.loadTimeout, 0) + "s"); + } + break; + } + case Phase::Prepare: + sectionScope.Next("Prepare"); + Prepare(); + break; + case Phase::EditSave: + sectionScope.Next("Edit save"); + FinishEdit(); + break; + case Phase::Shots: + sectionScope.Next("Shots"); + UpdateShots(); + break; + case Phase::Play: + sectionScope.Next("Play"); + UpdatePlay(); + break; + case Phase::Finish: + sectionScope.Next("Finish"); + // The scene isn't updated anymore, captures of a frame which wasn't rendered (e.g. an event threw) never will be + captureRequests.clear(); + if (!HasPendingCaptures()) + Finish(); + break; + default: + break; + } + } + catch (const std::exception& e) { + Fail(e.what()); + } + + } + + void App::Render(float deltaTime) { + + // Only a scene updated in this frame is rendered, e.g. not while finishing, waiting for commands or in the frame a + // job starts on a loaded scene. The renderer would use the per frame data of an older update, like an + // acceleration structure that was never built because its frame wasn't rendered + auto updated = sceneUpdated; + sceneUpdated = false; + if (!scene || !updated) { + // Scene updates can enqueue GPU work even when no scene frame is rendered + if (scene) + scene->WaitForAsyncWorkCompletion(); + PresentWindow(); + return; + } + + std::vector passes; + for (const auto& request : captureRequests) + for (const auto& pass : request.passes) + if (std::find(passes.begin(), passes.end(), pass) == passes.end()) + passes.push_back(pass); + + try { + CPUProfiler::Scope profilerScope("Capture render"); + BuildOverlay(); + // Loading frames aren't captured, path tracing them stalled the GPU for more than 30 s + captureRenderer.Render(scene, passes, overlay->GetBatches(), job.pathTrace && phase != Phase::Loading); + } + catch (const std::exception& e) { + // E.g. validation errors, which the engine throws in non-release builds + Fail(std::string("Rendering failed: ") + e.what()); + captureRequests.clear(); + PresentWindow(); + return; + } + + pendingReadbacks = std::move(captureRequests); + captureRequests.clear(); + + PresentWindow(); + + } + + void App::PresentWindow() { + + if (!job.showWindow || !font) { + captureRenderer.Present(); + return; + } + + std::vector lines = { { GetStatusLine(), vec4(0.55f, 0.8f, 1.0f, 1.0f) } }; + const auto& outputLines = report.outputLines; + auto first = outputLines.size() > outputLineCount ? outputLines.size() - outputLineCount : 0; + lines.insert(lines.end(), outputLines.begin() + first, outputLines.end()); + + captureRenderer.Present(font, lines); + + } + + std::string App::GetStatusLine() const { + + if (phase == Phase::Idle) + return "waiting for commands | " + (scene ? scenePath + " loaded" : std::string("no scene loaded")); + + std::string line = job.name + " | "; + switch (phase) { + case Phase::Idle: + break; + case Phase::WaitingForGpu: + line += "waiting for the GPU" + (gpuWaitReason.empty() ? std::string() : ": " + gpuWaitReason); + break; + case Phase::Loading: + line += "loading " + job.scene; + break; + case Phase::Prepare: + case Phase::EditSave: + line += "preparing"; + break; + case Phase::Shots: + line += "shots"; + break; + case Phase::Play: + line += "playing " + FormatFloat(player.timeline.time, 2) + " / " + FormatFloat(job.duration, 2) + " s"; + if (scene && scene->paused) + line += " (paused)"; + break; + case Phase::Finish: + line += "writing outputs"; + break; + case Phase::Done: + line += report.exitCode == 0 ? "passed" : report.exitCode == 1 ? "failed" : "error"; + break; + } + + return line + " | frame " + std::to_string(frameCount); + + } + + void App::Fail(const std::string& message) { + + report.Error(message); + fatal = true; + + // A scene loaded by a command has no job and no report + if (loadingForCommand) { + loadingForCommand = false; + retainedMeshes.clear(); + UnloadScene(); + SetIdle(); + CompleteCommand({ { "status", "error" }, { "reason", message } }); + return; + } + + if (phase != Phase::Done && phase != Phase::Finish) { + phaseBeforeFinish = phase; + phase = Phase::Finish; + } + + } + + void App::RunJobLua(const LuaEvent& lua, const std::string& name) { + + // Pixel picking uses the same camera setup as shots + EditHooks hooks; + hooks.pickRay = [this](const json& cameraJson, vec2 pixel) { + // The scene update computes the camera matrices, the simulation is paused at this point + UpdateSceneWithCaptureCamera(ParseCamera(cameraJson)); + const auto& camera = captureCameraEntity.GetComponent(); + return Volume::Ray(captureRenderer.GetViewport(), camera, pixel + vec2(0.5f)); + }; + + auto start = std::chrono::steady_clock::now(); + LuaJob luaJob; + luaJob.Start(scene->GetLuaState(), scene.get(), report, [start]() { return SecondsSince(start); }, hooks, &editState); + // Stopped also when the Lua fails + std::unique_ptr stop(&luaJob, [](LuaJob* job) { job->Stop(); }); + luaJob.Run(lua.code, lua.file.empty() ? name : lua.file); + + } + + void App::CollectLog() { + + for (const auto& entry : report.CollectLog()) { + player.timeline.MatchLog(entry.message); + if (entry.type != Log::TYPE_ERROR || !checkRunner || !job.checks.logErrors || MatchAnyPattern(job.checks.logIgnore, entry.message)) + continue; + + checkRunner->AddFailure({ "log", entry.message.substr(0, 160), player.timeline.time, entry.message }); + // Nothing after the first error is worth the wait, e.g. a script that would have logged the condition of an event + if (job.checks.failFast && phase != Phase::Finish && phase != Phase::Done && phase != Phase::Idle) { + report.Print("Stopping at the first error, checks.failFast = false runs to the end"); + phaseBeforeFinish = phase; + phase = Phase::Finish; + } + } + + } + + bool App::IsSceneReady() { + + // A few frames are needed to kick off the asynchronous work + if (frameCount < 3) + return false; + + // Meshes that failed to load count as loaded, they're reported once the scene is ready + if (!scene->IsFullyLoaded()) + return false; + + // Ray tracing structures are built asynchronously, but not every device/scene builds them + if (scene->IsRtDataNeeded() && !scene->IsRtDataValid() && rtWaitFrames++ < 300) + return false; + + return true; + + } + + void App::Prepare() { + + // The settings come first, the scene update extracts what the next frame renders + if (!job.settings.empty()) + ApplySettings(*scene, job.settings, settingsMaterials); + baseSettings = ExportSettings(*scene); + if (job.settings.contains("materials")) + baseSettings["materials"] = job.settings["materials"]; + + // The renderer expects a scene update in every frame + UpdateSceneWithCaptureCamera(*activeCamera); + report.Print("Rendering at " + std::to_string(job.resolution.x) + "x" + std::to_string(job.resolution.y) + GetRenderDescription()); + + EntitySet excluded = { captureCameraEntity }; + + if (job.inspect) { + auto inspection = InspectScene(*scene, job.inspect->filter, job.inspect->detail, excluded); + report.WriteJson(job.inspect->file, inspection); + report.Print("Inspection: " + std::to_string(inspection["entities"].size()) + " entities written to " + job.inspect->file); + } + + if (!job.queries.empty()) { + auto results = RunQueries(*scene, job.queries, job.outputDirectory); + report.WriteJson("queries.json", results); + queryResults = results; + for (const auto& result : results) { + auto text = result.contains("error") ? "error: " + result["error"].get() : result["result"].dump(); + if (text.size() > 400) + text = text.substr(0, 400) + "... (see queries.json)"; + report.Print("Query " + result["query"].dump() + " -> " + text); + } + } + + if (job.lua && !job.edit) + RunJobLua(*job.lua, "lua"); + + if (job.edit) { + auto inspectStart = std::chrono::steady_clock::now(); + editBefore = CaptureSceneState(*scene, excluded); + report.data["edit"]["seconds"]["inspectBefore"] = SecondsSince(inspectStart); + editState.loadedTerrain = scene->terrain.IsValid() ? scene->terrain.GetResource()->path : ""; + editState.dryRun = job.edit->dryRun; + editState.textureFormat = job.edit->textureFormat == "ktx2" ? Loader::ImportTextureFormat::KTX2 : + Loader::ImportTextureFormat::Original; + // After the snapshot, changes of the Lua are part of the edit + if (job.lua) + RunJobLua(*job.lua, "lua"); + scene->WaitForAsyncWorkCompletion(); + auto operationsStart = std::chrono::steady_clock::now(); + report.data["edit"]["operations"] = ApplyEditOperations(scene, job.edit->operations, editState); + report.data["edit"]["seconds"]["operations"] = SecondsSince(operationsStart); + report.Print("Applied " + std::to_string(job.edit->operations.size()) + " edit operations in " + + FormatFloat(report.data["edit"]["seconds"]["operations"].get(), 1) + "s"); + // Waiting cleared the render list of this frame's update, rendering it would draw host culled shadow + // instances without their meshes + sceneUpdated = false; + phase = Phase::EditSave; + return; + } + + // Checks of a static scene run once, while playing they run continuously + if (!job.play) + checkRunner->Run(*scene, 0.0f); + + // Hitches of loading and editing aren't reported, only those of frames from here on + hitchesStartTime = Clock::Get(); + + if (!job.shots.empty()) + phase = Phase::Shots; + else if (job.play) + StartPlay(); + else + phase = Phase::Finish; + + } + + void App::FinishEdit() { + + // Propagate transforms and bounds before inspection + UpdateSceneWithCaptureCamera(*activeCamera); + if (++editFrames < 3) + return; + + EntitySet excluded = { captureCameraEntity }; + auto& edit = report.data["edit"]; + + auto& seconds = edit["seconds"]; + // Its changes are part of the diff and saved with the scene + if (job.edit->lua) { + RunJobLua(*job.edit->lua, "edit.lua"); + scene->UpdateTransforms(); + } + auto phaseStart = std::chrono::steady_clock::now(); + auto after = CaptureSceneState(*scene, excluded); + seconds["inspectAfter"] = SecondsSince(phaseStart); + phaseStart = std::chrono::steady_clock::now(); + auto diff = DiffSceneStates(editBefore, after); + editBefore.clear(); + for (const auto& list : { "changed", "added", "removed" }) + diff[list] = CapList(diff[list], 2000); + report.WriteJson("edit_diff.json", diff); + seconds["diff"] = SecondsSince(phaseStart); + edit["diff"] = diff["summary"]; + report.Print("Edit diff: " + diff["summary"].get() + " (see edit_diff.json)"); + + // Queries of the edited scene, e.g. to verify placements + if (!job.edit->queries.empty()) { + auto results = RunQueries(*scene, job.edit->queries, job.outputDirectory); + report.WriteJson("edit_queries.json", results); + for (const auto& result : results) { + auto text = result.contains("error") ? "error: " + result["error"].get() : result["result"].dump(); + if (text.size() > 400) + text = text.substr(0, 400) + "... (see edit_queries.json)"; + report.Print("Edit query " + result["query"].value("type", "") + " -> " + text); + } + } + phaseStart = std::chrono::steady_clock::now(); + checkRunner->Run(*scene, 0.0f); + seconds["checks"] = SecondsSince(phaseStart); + if (checkRunner->HasFailures()) { + edit["saved"] = false; + Fail("Checks failed after the edit, neither the scene nor materials were saved"); + return; + } + + if (job.edit->dryRun) { + edit["saved"] = false; + report.Print("Dry run, neither the scene nor materials are saved"); + phase = job.shots.empty() ? Phase::Finish : Phase::Shots; + return; + } + + // Edits which only changed materials leave the scene untouched, no need to rewrite it + bool sceneChanged = !diff["changed"].empty() || !diff["added"].empty() || !diff["removed"].empty() || job.edit->saveUnchanged || + editState.terrainChanged; + + auto output = job.edit->output; + if (output.empty()) { + auto scenePath = fs::path(job.scene); + auto fileName = scenePath.stem().string() + ".edit" + scenePath.extension().string(); + output = (scenePath.parent_path() / fileName).generic_string(); + } + + // Validate the output first, materials are only written together with the scene + auto absoluteOutput = GetAssetDirectory() / output; + if (sceneChanged && output == job.scene && !job.edit->overwrite) { + Fail("Refusing to overwrite the input scene " + output + ", set edit.overwrite = true or choose another output"); + return; + } + if (sceneChanged && fs::exists(absoluteOutput) && output != job.scene && !job.edit->overwrite) { + Fail("Output scene " + output + " already exists, set edit.overwrite = true to replace it"); + return; + } + // The patches of the settings are for the running scene only, saving would write them into the file + for (const auto& path : editState.changedMaterials) { + if (settingsMaterials.contains(path)) { + Fail("Material " + path + " is patched by the settings and edited, edit it in a job without the patch"); + return; + } + } + + if (!editState.graphEdits.changed.empty()) { + edit["graphs"] = SaveMaterialGraphs(editState.graphEdits); + report.Print("Saved " + std::to_string(edit["graphs"].size()) + " edited material graphs"); + } + if (!editState.changedMaterials.empty()) { + edit["materials"] = SaveMaterials(editState.changedMaterials); + report.Print("Saved " + std::to_string(editState.changedMaterials.size()) + " edited materials"); + editState.changedMaterials.clear(); + } + + if (!sceneChanged) { + edit["saved"] = false; + report.Print("The scene itself didn't change, it is not saved"); + phase = job.shots.empty() ? Phase::Finish : Phase::Shots; + return; + } + + // The snapshots of a pipeline keep the previous states + if (fs::exists(absoluteOutput) && mode != Mode::Pipeline) { + auto timestamp = std::chrono::system_clock::now().time_since_epoch() / std::chrono::seconds(1); + auto backup = absoluteOutput; + backup += ".backup-" + std::to_string(timestamp); + fs::copy_file(absoluteOutput, backup); + edit["backup"] = backup.string(); + report.Print("Backup of the previous scene: " + backup.string()); + } + + // The capture camera must not end up in the scene, the editor does the same with its camera + auto entityCount = scene->GetEntityCount() - 1; + scene->DestroyEntity(captureCameraEntity); + + if (editState.terrainChanged) { + SaveSceneTerrain(*scene); + edit["terrain"] = scene->terrain.GetResource()->path; + report.Print("Saved terrain to data/" + scene->terrain.GetResource()->path); + } + + auto binary = fs::path(output).extension() != ".json"; + phaseStart = std::chrono::steady_clock::now(); + Serializer::SerializeScene(scene, output, false, binary); + seconds["save"] = SecondsSince(phaseStart); + + CreateCaptureCamera(); + + // A pipeline step that continues with the scene saves it again, only the last saved state is loaded again + if (mode != Mode::Pipeline || !StepReadsScene(pipeline->currentStep + 1, output)) { + phaseStart = std::chrono::steady_clock::now(); + try { + auto reloaded = Serializer::DeserializeScene(output, binary); + auto reloadedCount = reloaded->GetEntityCount(); + edit["verified"] = reloadedCount == entityCount; + if (reloadedCount != entityCount) + Fail("Saved scene has " + std::to_string(reloadedCount) + " entities, expected " + std::to_string(entityCount)); + seconds["verify"] = SecondsSince(phaseStart); + } + catch (const std::exception& e) { + Fail("Saved scene " + output + " couldn't be loaded again: " + e.what()); + return; + } + } + + edit["saved"] = true; + edit["output"] = output; + report.Print("Saved edited scene to data/" + output); + + // A scene that stays loaded starts the next job with the settings it was saved with + sceneSettings = ExportSettings(*scene); + + if (phase == Phase::Finish) + return; + + phase = job.shots.empty() ? Phase::Finish : Phase::Shots; + + } + + void App::UpdateShots() { + + auto variantCount = std::max(job.variants.size(), size_t(1)); + const auto& shot = job.shots[shotState.shot]; + auto views = shot.views.empty() ? std::vector { "" } : shot.views; + const auto& view = views[shotState.view]; + + bool firstFrameOfShot = shotState.settledFrames == 0 && !shotState.requested; + if (firstFrameOfShot && !job.variants.empty() && shotState.shot == 0 && shotState.view == 0) { + const auto& variant = job.variants[shotState.variant]; + ApplyBaseSettings(); + ApplySettings(*scene, variant.settings, settingsMaterials); + captureRenderer.SetRenderScale(variant.renderScale.value_or(baseRenderScale)); + report.Print("Variant '" + variant.name + "'" + GetRenderDescription()); + } + + auto camera = shot.camera; + if (!view.empty()) { + camera.view = view; + camera.azimuth.reset(); + camera.elevation.reset(); + if (camera.mode == "scene" || camera.mode == "manual") + throw std::runtime_error("Shot '" + shot.name + "' has views, which require a focus or overview camera"); + } + activeCamera = camera; + + UpdateSceneWithCaptureCamera(camera); + + auto settleFrames = shot.settleFrames >= 0 ? shot.settleFrames : job.settleFrames; + if (!shotState.requested) { + if (shotState.settledFrames++ < settleFrames) + return; + + auto variantName = job.variants.empty() ? std::string() : job.variants[shotState.variant].name; + auto prefix = job.variants.empty() ? std::string() : SanitizeFileName(variantName) + "/"; + auto baseName = SanitizeFileName(shot.name) + (view.empty() ? "" : "_" + view); + + CaptureRequest request; + request.path = job.outputDirectory / (prefix + baseName + ".png"); + request.passes = shot.passes; + request.label = view.empty() ? shot.name : view; + request.crop = GetCropRectangle(shot.crop); + + if (views.size() > 1) { + request.group = prefix + SanitizeFileName(shot.name) + "_views"; + if (!sheets.contains(request.group)) { + auto title = shot.name + (job.variants.empty() ? "" : " (" + variantName + ")"); + sheets[request.group] = { .title = title, .path = job.outputDirectory / (request.group + ".png") }; + sheetOrder.push_back(request.group); + } + } + + RequestCapture(request); + + // Variants of the same shot/view are compared in an additional sheet + if (!job.variants.empty()) { + auto group = baseName + "_variants"; + if (!sheets.contains(group)) { + sheets[group] = { .title = baseName + " variants", .path = job.outputDirectory / (group + ".png") }; + sheetOrder.push_back(group); + } + variantCaptures[request.path.string()] = { group, variantName }; + } + + shotState.requested = true; + return; + } + + if (HasPendingCaptures()) + return; + + shotState.requested = false; + shotState.settledFrames = 0; + + if (++shotState.view < views.size()) + return; + shotState.view = 0; + + if (++shotState.shot < job.shots.size()) + return; + shotState.shot = 0; + + if (++shotState.variant < variantCount) + return; + + if (job.play) { + if (!job.variants.empty()) + ApplyBaseSettings(); + StartPlay(); + } + else { + phase = Phase::Finish; + } + + } + + void App::ApplyBaseSettings() { + + // Material patches aren't part of the exported settings, the files restore them + UpdatePipelinesOfMaterials(ReloadMaterials(settingsMaterials)); + settingsMaterials.clear(); + ApplySettings(*scene, baseSettings, settingsMaterials); + captureRenderer.SetRenderScale(baseRenderScale); + + } + + void App::StartPlay() { + + // The scripts get new entities, the asynchronous work of the last scene update (e.g. the ray tracing world) + // still reads the entity storage. Waiting clears the render list of the update, so its frame isn't rendered + scene->WaitForAsyncWorkCompletion(); + sceneUpdated = false; + + playStartTime = std::chrono::steady_clock::now(); + auto events = job.timeline; + + // Strips are expanded into capture events + for (const auto& strip : job.strips) { + auto group = SanitizeFileName(strip.name); + sheets[group] = { .title = strip.name, .columns = strip.columns, .path = job.outputDirectory / (group + ".png") }; + sheetOrder.push_back(group); + + if (strip.hasCamera) + stripCameras[group] = strip.camera; + + // Integer steps avoid accumulating floating point errors + auto count = int32_t(std::floor((strip.to - strip.from) / strip.every + 1e-3f)); + for (int32_t i = 0; i <= count; i++) { + auto time = strip.from + float(i) * strip.every; + + CaptureEvent capture; + capture.file = group + "/" + FormatFloat(time, 2) + "s.png"; + capture.group = group; + capture.stripCamera = strip.hasCamera; + events.push_back({ .time = time, .type = "capture", .action = capture }); + } + } + + activeCamera = job.observer.value_or(CameraSpec {}); + + // Focus cameras are framed once, re-framing a moving object every frame makes the camera jump + if ((activeCamera->mode == "focus" || activeCamera->mode == "overview") && !activeCamera->dynamic) { + ApplyCameraSpec(*activeCamera); + const auto& camera = captureCameraEntity.GetComponent(); + + CameraSpec fixed = *activeCamera; + fixed.mode = "manual"; + fixed.position = camera.location; + fixed.lookAt.reset(); + fixed.yaw = glm::degrees(camera.rotation.x); + fixed.pitch = glm::degrees(camera.rotation.y); + fixed.farPlane = camera.farPlane; + activeCamera = fixed; + } + + player.Start(job, *scene, std::move(events), report, nullptr, SDL_GetWindowID(window.GetSDLWindow())); + + // Enable play mode; scene.paused controls pauses and resetScripts temporarily leaves play mode + scene->physicsWorld->pauseSimulation = false; + phase = Phase::Play; + + report.Print("Playing for " + FormatFloat(job.duration, 2) + "s with " + std::to_string(player.timeline.GetTimedEventCount()) + + " timeline events and " + std::to_string(player.timeline.GetTriggerCount()) + " conditional events"); + + } + + void App::UpdatePlay() { + + if (stillState.active) { + UpdateStill(); + return; + } + + auto& timeline = player.timeline; + + // A shown window plays in real time, the simulation still advances in fixed steps + auto realPlayTime = std::chrono::duration(std::chrono::steady_clock::now() - playStartTime).count(); + if (job.showWindow && job.realTime && timeline.time > realPlayTime) { + UpdateSceneFrozen(*activeCamera); + return; + } + + bool liveCapture = false; + if (!player.Update([&](const EventSpec& event) { return RunEvent(event, liveCapture); })) { + UpdateStill(); + return; + } + + // A live capture shows the regular step of this frame, which also gives correct motion vectors + // The job only finishes once it was rendered + if (!liveCapture && timeline.IsFinished(job.duration)) { + player.ReportMissedEvents(*checkRunner); + checkRunner->Run(*scene, timeline.time); + if (tracker) + tracker->Record(*scene, timeline.time); + phase = Phase::Finish; + return; + } + + // The observer is the main camera during the update, culling, shadows and terrain LODs + // are computed for the main camera. Scripts access their camera through their entity + playerInput.Update(*scene, job.fixedDeltaTime); + UpdateSceneWithCaptureCamera(*activeCamera); + timeline.time += job.fixedDeltaTime; + + if (timeline.IsDue(nextCheckTime)) { + checkRunner->Run(*scene, timeline.time); + nextCheckTime += job.checks.interval; + } + if (tracker && timeline.IsDue(nextTrackTime)) { + tracker->Record(*scene, timeline.time); + nextTrackTime += tracker->spec.interval; + } + + } + + Player::EventResult App::RunEvent(const EventSpec& event, bool& liveCapture) { + + auto& timeline = player.timeline; + if (std::holds_alternative(event.action)) { + // Leaving play mode discards non-permanent script environments; scene.paused keeps their state + scene->physicsWorld->pauseSimulation = true; + UpdateSceneWithCaptureCamera(*activeCamera, freezeDeltaTime); + scene->physicsWorld->pauseSimulation = false; + report.Print(FormatTime(timeline.time) + " reset the state of all scripts"); + return Player::EventResult::Done; + } + + const auto& capture = std::get(event.action); + CameraSpec camera = activeCamera.value_or(CameraSpec {}); + bool ownCamera = false; + if (capture.camera) { + camera = *capture.camera; + ownCamera = true; + } + else if (capture.stripCamera) { + camera = stripCameras[capture.group]; + ownCamera = true; + } + + CaptureRequest request; + auto defaultFile = SanitizeFileName(capture.name) + "_" + FormatFloat(timeline.time, 2) + "s.png"; + request.path = job.outputDirectory / capture.file.value_or(defaultFile); + request.group = capture.group; + request.label = capture.label.value_or(FormatTime(event.time)); + request.time = event.time; + request.passes = capture.passes; + request.crop = GetCropRectangle(capture.crop); + + // A different camera than the observer needs frozen frames to let temporal effects settle + if (ownCamera || capture.still) { + // Pending live captures are taken first, the still starts in the next frame + if (liveCapture) + return Player::EventResult::Defer; + + stillState = StillState { + .active = true, + .camera = camera, + .request = request, + .settleFrames = capture.settleFrames.value_or(job.settleFrames) + }; + // The paused scene doesn't advance the exposure adaptation, it starts over for the new view + captureRenderer.InvalidateHistory(); + return Player::EventResult::Suspend; + } + + RequestCapture(request); + liveCapture = true; + return Player::EventResult::Done; + + } + + void App::UpdateStill() { + + UpdateSceneFrozen(stillState.camera); + + if (!stillState.requested) { + if (stillState.settledFrames++ < stillState.settleFrames) + return; + + RequestCapture(stillState.request); + stillState.requested = true; + return; + } + + if (HasPendingCaptures()) + return; + + captureRenderer.InvalidateHistory(); + stillState = StillState {}; + + } + + void App::UpdateSceneFrozen(const CameraSpec& spec) { + + auto wasPaused = scene->paused; + scene->paused = true; + UpdateSceneWithCaptureCamera(spec, freezeDeltaTime); + scene->paused = wasPaused; + + } + + void App::Finish() { + + for (const auto& group : sheetOrder) { + auto& sheet = sheets[group]; + if (sheet.images.empty()) + continue; + + auto image = ComposeSheet(sheet.images, sheet.labels, sheet.columns, sheet.title); + if (WritePng(image, sheet.path)) + report.AddOutput(fs::relative(sheet.path, job.outputDirectory).generic_string()); + } + + // All captures of the job in one picture that is cheap to look at + if (!jobSheetImages.empty()) { + auto columns = int32_t(std::ceil(std::sqrt(float(jobSheetImages.size())))); + auto cellWidth = std::max((1536 - 4 * (columns + 1)) / columns, 64); + auto sheet = ComposeSheet(jobSheetImages, jobSheetLabels, columns, job.name, cellWidth); + if (WriteImage(sheet, job.outputDirectory / "sheet.jpg")) + report.AddOutput("sheet.jpg"); + } + if (job.compare) + CompareImages(); + + if (tracker) + report.WriteJson("trace.json", tracker->GetTrace()); + + if (job.profileFrames > 0) + report.WriteProfile(job.profileFrames); + if (job.hitches) { + // A hitch is recorded at the end of its frame + auto hitches = HitchRecorder::GetHitches(); + std::erase_if(hitches, [&](const auto& hitch) { return hitch->time - hitch->frameTime / 1000.0f < hitchesStartTime; }); + report.WriteHitches(hitches); + } + + if (report.IsValidationEnabled()) + report.WriteValidation(); + + auto failedExpectations = std::count_if(report.expectations.begin(), report.expectations.end(), [](const json& expectation) { + + return !expectation["passed"].get(); + + }); + + if (fatal) + report.exitCode = 2; + else if ((checkRunner && checkRunner->HasFailures()) || failedExpectations > 0) + report.exitCode = 1; + else + report.exitCode = 0; + + std::string reason; + if (fatal) { + reason = report.errors.empty() ? "unknown error" : report.errors.front(); + } + else if (report.exitCode == 1) { + auto failedChecks = checkRunner ? checkRunner->GetSummary().size() : size_t(0); + reason = std::to_string(failedChecks) + " failed checks, " + std::to_string(failedExpectations) + " failed expectations"; + } + + std::string status = report.exitCode == 0 ? "passed" : (report.exitCode == 1 ? "failed" : "error"); + json result = { + { "job", job.name }, { "runId", report.runId }, { "scene", job.scene }, { "status", status }, + { "exitCode", report.exitCode }, { "renderScale", baseRenderScale }, { "loadSeconds", loadSeconds }, + { "frames", frameCount }, { "errors", report.errors }, { "warnings", report.warnings }, + { "totalSeconds", std::chrono::duration(std::chrono::steady_clock::now() - startTime).count() }, + { "engineLogErrors", report.logErrorCount } + }; + if (!reason.empty()) + result["reason"] = reason; + if (checkRunner) + result["checks"] = checkRunner->GetReport(); + if (!report.expectations.empty()) + result["expectations"] = report.expectations; + if (!report.results.empty()) + result["results"] = report.results; + if (job.play) + result["playedSeconds"] = player.timeline.time; + if (auto triggers = player.timeline.GetTriggerReport(); !triggers.is_null()) + result["conditionalEvents"] = triggers; + report.Write(result); + + report.Print("---------------------------------------------"); + report.Print("Status: " + status + (reason.empty() ? "" : " (" + reason + ")")); + for (const auto& line : FormatSummary(report.data, job.outputDirectory)) + report.Print(line); + + FinishJob(); + + } + + void App::FinishJob() { + + report.End(); + + if (mode == Mode::Job) { + phase = Phase::Done; + Exit(report.exitCode); + return; + } + + if (mode == Mode::Server) { + // The scene stays loaded for the next job, which loads it again if this one played or edited it. A scene that + // didn't finish loading is unloaded + if (scene && phaseBeforeFinish == Phase::Loading) + UnloadScene(); + sceneDirty = scene && (job.play || job.edit); + SetIdle(); + CompleteCommand({ { "status", report.data.value("status", "error") }, { "exitCode", report.exitCode }, + { "reason", report.data.value("reason", "") }, { "outputDirectory", job.outputDirectory.string() }, + { "report", (job.outputDirectory / "report.json").string() } }); + return; + } + + if (report.exitCode != 0) + pipeline->FailStep(report.exitCode); + else + pipeline->CompleteStep(report.data); + + const auto& edit = report.data.value("edit", json::object()); + auto savedScene = edit.value("saved", false) ? edit["output"].get() : ""; + if (!savedScene.empty() && !job.play && StepReadsScene(pipeline->currentStep, savedScene)) { + scenePath = savedScene; + keepScene = true; + } + else { + UnloadScene(); + } + + StartPipelineStep(); + + } + + bool App::StepReadsScene(size_t step, const std::string& scene) { + + // Skipped steps leave the scene in memory for the step after them + while (step < pipeline->steps.size() && pipeline->Skips(step)) + step++; + if (step >= pipeline->steps.size()) + return false; + + try { + return ParseJobFile(pipeline->steps[step].jobFile).scene == scene; + } + catch (const std::exception&) { + // Reported when the step starts + return false; + } + + } + + void App::StartPipelineStep() { + + if (pipeline->IsFinished()) { + auto summaryPath = pipeline->WriteSummary(); + + report.Print("---------------------------------------------"); + for (const auto& step : pipeline->GetSummary()) + report.Print("Step " + step["step"].get() + ": " + step["result"].get()); + report.Print(std::string("Pipeline ") + (pipeline->exitCode == 0 ? "passed" : "failed") + ", summary in " + summaryPath.string()); + + UnloadScene(); + phase = Phase::Done; + Exit(pipeline->exitCode); + return; + } + + const auto& step = pipeline->steps[pipeline->currentStep]; + if (pipeline->Skips(pipeline->currentStep)) { + report.Print("Pipeline step " + std::to_string(pipeline->currentStep + 1) + " / " + std::to_string(pipeline->steps.size()) + ": " + + step.name + " is independent and unchanged, skipped"); + pipeline->SkipStep(); + StartPipelineStep(); + return; + } + report.Print("Pipeline step " + std::to_string(pipeline->currentStep + 1) + " / " + std::to_string(pipeline->steps.size()) + ": " + step.name); + + Job stepJob; + try { + stepJob = ParseJobFile(step.jobFile); + } + catch (const std::exception& e) { + report.Print(std::string("ERROR: ") + e.what()); + pipeline->FailStep(2); + StartPipelineStep(); + return; + } + + StartJob(stepJob); + + } + + void App::ProcessNextCommand() { + + auto command = server->Poll(); + if (!command) + return; + + if (command->is_discarded() || !command->is_object()) { + CompleteCommand({ { "status", "error" }, { "reason", "The command isn't a JSON object" } }); + return; + } + + static const std::map commands = { + { "loadScene", &App::LoadSceneCommand }, + { "reloadScene", &App::ReloadSceneCommand }, + { "run", &App::RunCommand }, + { "stop", &App::StopCommand } + }; + + try { + auto type = command->value("command", std::string(command->contains("job") ? "run" : "")); + report.Print("Command '" + server->commandName + "': " + type); + + auto handler = commands.find(type); + if (handler == commands.end()) { + std::string known; + for (const auto& [name, _] : commands) + known += (known.empty() ? "" : ", ") + name; + throw std::runtime_error("Unknown command '" + type + "' (" + known + ")"); + } + (this->*handler->second)(*command); + } + catch (const std::exception& e) { + report.Print(std::string("ERROR: ") + e.what()); + CompleteCommand({ { "status", "error" }, { "reason", e.what() } }); + } + + } + + void App::LoadSceneCommand(const json& command) { + + LoadSceneForCommand(ToAssetPath(command.at("scene").get()), command); + + } + + void App::ReloadSceneCommand(const json& command) { + + if (scenePath.empty()) + throw std::runtime_error("No scene is loaded"); + + // The meshes with their materials and textures stay loaded until the scene is ready again + if (scene) + retainedMeshes = scene->GetMeshes(); + LoadSceneForCommand(scenePath, command); + + } + + void App::LoadSceneForCommand(std::string path, const json& command) { + + UnloadScene(); + + // A minimal job, its timeout and resolution apply while loading + job = Job(); + job.name = server->commandName; + job.scene = path; + job.loadTimeout = command.value("timeout", job.loadTimeout); + job.waitGpu = command.value("waitGpu", std::find(jobArguments.begin(), jobArguments.end(), "--no-wait-gpu") == jobArguments.end()); + job.gpuWaitTimeout = command.value("gpuWaitTimeout", job.gpuWaitTimeout); + ResetJobState(); + activeCamera = command.contains("camera") ? ParseCamera(command["camera"]) : CameraSpec {}; + report.SkipLog(); + + keepScene = true; + loadingForCommand = true; + report.Print("Loading " + path); + server->WriteStatus("loading", path); + LoadScene(path); + + } + + void App::RunCommand(const json& command) { + + fs::path jobFile; + const auto& jobJson = command.at("job"); + if (jobJson.is_string()) { + jobFile = ResolveUserPath(jobJson.get()); + } + else { + // Inline jobs are written next to the processed command + auto inlineJob = jobJson; + if (!inlineJob.contains("name")) + inlineJob["name"] = server->commandName; + if (!inlineJob.contains("scene") && scene) + inlineJob["scene"] = scenePath; + jobFile = server->directory / "done" / (server->commandName + ".job.json"); + std::ofstream stream(jobFile); + stream << inlineJob.dump(2); + } + StartJob(ParseJobFile(jobFile, command.value("args", std::vector()))); + + } + + void App::StopCommand(const json&) { + + CompleteCommand({ { "status", "ok" } }); + server->Close(); + UnloadScene(); + phase = Phase::Done; + Exit(0); + + } + + void App::ShowWindow(bool foreground) { + + // Only a window which isn't shown yet goes behind the others, one the user brought to the front stays there + auto sdlWindow = window.GetSDLWindow(); + auto wasHidden = (SDL_GetWindowFlags(sdlWindow) & SDL_WINDOW_HIDDEN) != 0; + SDL_SetHint(SDL_HINT_WINDOW_ACTIVATE_WHEN_SHOWN, foreground ? "1" : "0"); + window.Show(); + + if (foreground) { + backgroundUntil = 0.0f; + SDL_RaiseWindow(sdlWindow); + } + else if (wasHidden) { + backgroundUntil = Clock::Get() + 3.0f; + MoveWindowToBack(sdlWindow); + } + + } + + void App::SetBusyActivity() { + + if (loadingForCommand) { + InstanceRegistry::SetActivity("loading " + scenePath, true); + return; + } + + auto now = std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count(); + InstanceRegistry::SetActivity("job " + job.name, true, + report.previousSeconds > 0.0f ? std::optional(now + int64_t(report.previousSeconds)) : std::nullopt); + + } + + void App::SetIdle() { + + phase = Phase::Idle; + server->WriteStatus("idle", scene ? scenePath : ""); + InstanceRegistry::SetActivity("server idle" + (scene ? ", " + scenePath + " loaded" : std::string()), false); + + } + + void App::CompleteCommand(const json& result) { + + server->Complete(result, scene ? scenePath : ""); + report.Print("Command '" + server->commandName + "' done: " + result.value("status", "")); + + } + + std::string App::GetRenderDescription() const { + + using PostProcessing::Upscaler; + auto upscaler = std::string(PostProcessing::PostProcessing::GetUpscalerName(scene->postProcessing.upscaler)); + if (!mainRenderer->IsUpscalerSupported(scene->postProcessing.upscaler)) + upscaler += std::string(" not available, ") + PostProcessing::PostProcessing::GetUpscalerName(Upscaler::FSR2); + return ", render scale " + FormatFloat(captureRenderer.GetRenderScale(), 2) + " (" + upscaler + ")"; + + } + + void App::CreateCaptureCamera() { + + captureCameraEntity = scene->CreateEntity(); + auto& camera = captureCameraEntity.AddComponent(60.0f, float(job.resolution.x) / float(job.resolution.y), 0.1f, 2000.0f); + camera.isMain = false; + + } + + void App::UpdateSceneWithCaptureCamera(const CameraSpec& spec, float deltaTime) { + + bool useCaptureCamera = UsesCaptureCamera(spec); + if (useCaptureCamera) + ApplyCameraSpec(spec); + + // Path tracing needs the ray tracing data, which the scene only builds when an effect uses it + if (scene->rayTracingWorld) + scene->rayTracingWorld->includeObjectHistory = job.pathTrace; + + scene->Update(deltaTime < 0.0f ? job.fixedDeltaTime : deltaTime, useCaptureCamera ? captureCameraEntity : Scene::Entity()); + sceneUpdated = true; + + } + + bool App::UsesCaptureCamera(const CameraSpec& spec) const { + + if (spec.mode != "scene") + return true; + + // Scenes without a main camera of their own are shown from an overview + auto cameraSubset = scene->GetSubset(); + for (auto entity : cameraSubset) + if (entity != ECS::Entity(captureCameraEntity) && cameraSubset.Get(entity).isMain) + return false; + + return true; + + } + + void App::ApplyCameraSpec(const CameraSpec& spec) { + + auto& camera = captureCameraEntity.GetComponent(); + camera.aspectRatio = float(job.resolution.x) / float(job.resolution.y); + camera.fieldOfView = spec.fieldOfView; + camera.nearPlane = spec.nearPlane; + camera.farPlane = spec.farPlane; + + vec3 position = camera.location; + std::optional target; + float yaw = glm::radians(spec.yaw), pitch = glm::radians(spec.pitch); + + auto mode = spec.mode == "scene" ? std::string("overview") : spec.mode; + + if (mode == "manual") { + position = spec.position; + target = spec.lookAt; + if (spec.groundRelative) { + auto top = GetSceneBounds(*scene).max.y + 10.0f; + auto groundHeight = [&](vec3 point) { + + auto ground = GroundBelow(*scene, vec3(point.x, top, point.z), { captureCameraEntity }); + return ground.valid ? ground.position.y : 0.0f; + + }; + position.y += groundHeight(position); + if (target) + target->y += groundHeight(*target); + } + } + else if (mode == "focus" || mode == "overview") { + Volume::AABB bounds; + float entityYaw = 0.0f; + EntitySet focused; + if (mode == "focus") { + auto entities = FindTopmostEntities(*scene, spec.entity); + if (entities.empty()) { + // Entities created by scripts might not exist yet while loading or playing + if (phase == Phase::Play || phase == Phase::Loading) + return; + throw std::runtime_error("Camera focus: no entity matches '" + spec.entity + "'"); + } + bounds = GetBounds(entities); + entityYaw = glm::degrees(GetEntityYaw(entities.front())); + for (auto entity : entities) + CollectHierarchy(entity, focused); + } + else { + bounds = GetSceneBounds(*scene); + } + + auto angles = GetViewAngles(spec.view.empty() ? (mode == "overview" ? "iso" : "front") : spec.view); + auto azimuth = spec.azimuth.value_or(angles.azimuth) + (spec.local ? entityYaw : 0.0f); + auto elevation = spec.elevation.value_or(angles.elevation); + + auto direction = GetDirection(azimuth, elevation); + + auto center = bounds.GetCenter(); + auto radius = std::max(glm::length(bounds.GetSize()) * 0.5f, 0.25f); + + // Fit the bounding sphere into the smaller of the two field of view angles + auto halfFov = glm::radians(spec.fieldOfView) * 0.5f; + auto halfFovHorizontal = std::atan(std::tan(halfFov) * camera.aspectRatio); + auto distance = spec.distance > 0.0f ? spec.distance : radius * spec.padding / std::sin(std::min(halfFov, halfFovHorizontal)); + + // Prefer nearby unobstructed angles before reducing the camera distance + if (mode == "focus" && spec.avoidOcclusion) { + static const vec2 angleOffsets[] = { { 0.0f, 0.0f }, { 0.0f, 15.0f }, { 20.0f, 10.0f }, { -20.0f, 10.0f }, + { 0.0f, 30.0f }, { 40.0f, 20.0f }, { -40.0f, 20.0f }, { 0.0f, 50.0f }, { 0.0f, -10.0f } }; + + // Sample corners as well as the center to account for partial occlusion + std::vector samples = { center }; + for (auto corner : bounds.GetCorners()) + samples.push_back(glm::mix(corner, center, 0.1f)); + + auto countVisible = [&](vec3 cameraPosition) { + + int32_t visible = 0; + for (auto sample : samples) { + auto toSample = sample - cameraPosition; + auto length = glm::length(toSample); + if (length < 1e-4f || !Raycast(*scene, cameraPosition, toSample / length, length, focused).valid) + visible++; + } + return visible; + + }; + + auto bestDirection = direction; + auto bestVisible = 0; + for (auto offset : angleOffsets) { + auto candidate = GetDirection(azimuth + offset.x, glm::clamp(elevation + offset.y, -80.0f, 89.0f)); + + auto visible = countVisible(center + candidate * distance); + if (visible > bestVisible) { + bestVisible = visible; + bestDirection = candidate; + } + if (visible == int32_t(samples.size())) + break; + } + + if (bestVisible > 0) { + direction = bestDirection; + } + else { + // Moving closer only helps if the camera stays outside of the focused bounds, + // otherwise the requested view is kept even though it's occluded + auto hit = Raycast(*scene, center, direction, distance, focused); + if (hit.valid && hit.distance - 0.25f > radius) + distance = hit.distance - 0.25f; + } + } + + position = center + direction * distance; + target = center; + camera.farPlane = std::max(spec.farPlane, distance + radius * 4.0f); + } + else if (mode == "follow") { + auto entities = FindTopmostEntities(*scene, spec.entity); + if (entities.empty()) + return; + + auto bounds = GetEntityBounds(entities.front()); + auto center = bounds.GetCenter(); + auto offset = spec.offset; + if (spec.local) + offset = vec3(glm::rotate(GetEntityYaw(entities.front()), vec3(0.0f, 1.0f, 0.0f)) * vec4(offset, 0.0f)); + + position = center + offset; + target = center; + } + + if (target && glm::distance(*target, position) > 1e-4f) { + auto direction = glm::normalize(*target - position); + yaw = std::atan2(direction.x, direction.z); + pitch = std::asin(glm::clamp(direction.y, -1.0f, 1.0f)); + } + + camera.location = position; + camera.rotation = vec2(yaw, pitch); + + } + + void App::RequestCapture(const CaptureRequest& request) { + + captureRequests.push_back(request); + + } + + bool App::HasPendingCaptures() const { + + return !captureRequests.empty() || !pendingReadbacks.empty(); + + } + + void App::ProcessReadback() { + + if (pendingReadbacks.empty()) + return; + + auto requests = std::move(pendingReadbacks); + pendingReadbacks.clear(); + + // All requests of a frame were rendered into the same image + auto image = captureRenderer.ReadOutput(); + std::map> passImages; + + for (const auto& request : requests) { + if (!WritePng(image, request.path)) { + Fail("Couldn't write " + request.path.string()); + continue; + } + + auto relative = fs::relative(request.path, job.outputDirectory).generic_string(); + report.AddOutput(relative); + report.Print("Captured " + relative + (phase == Phase::Play ? " at " + FormatTime(request.time) : "")); + + if (!request.group.empty()) + AddToSheet(request.group, image, request.label); + jobSheetImages.push_back(Downscale(image, 640)); + jobSheetLabels.push_back(fs::path(relative).replace_extension().generic_string()); + + if (request.crop) { + auto crop = CropImage(image, *request.crop); + auto cropPath = request.path.parent_path() / (request.path.stem().string() + "_crop.png"); + if (WritePng(crop, cropPath)) { + auto cropRelative = fs::relative(cropPath, job.outputDirectory).generic_string(); + report.AddOutput(cropRelative); + jobSheetImages.push_back(Downscale(crop, 640)); + jobSheetLabels.push_back(fs::path(cropRelative).replace_extension().generic_string()); + } + } + + if (auto it = variantCaptures.find(request.path.string()); it != variantCaptures.end()) + AddToSheet(it->second.first, image, it->second.second); + + if (request.passes.empty()) + continue; + + auto stem = request.path.parent_path() / request.path.stem(); + auto group = fs::relative(stem, job.outputDirectory).generic_string() + "_passes"; + sheets[group] = { .title = relative + " passes", .path = job.outputDirectory / (group + ".png") }; + sheetOrder.push_back(group); + AddToSheet(group, image, "lit"); + + for (const auto& pass : request.passes) { + if (!passImages.contains(pass)) + passImages[pass] = captureRenderer.ReadPass(pass); + + auto passPath = fs::path(stem.string() + "_" + pass + ".png"); + if (WritePng(passImages[pass], passPath)) + report.AddOutput(fs::relative(passPath, job.outputDirectory).generic_string()); + AddToSheet(group, passImages[pass], pass); + } + } + + } + + std::optional App::GetCropRectangle(const json& crop) { + + if (crop.is_null()) + return std::nullopt; + if (crop.is_array() && crop.size() == 4) + return ivec4(crop[0].get(), crop[1].get(), crop[2].get(), crop[3].get()); + if (!crop.is_object() || !crop.contains("entity")) + throw std::runtime_error("A crop is [x, y, width, height] or { \"entity\": pattern, \"padding\": 0.15 }: " + crop.dump()); + + auto pattern = crop["entity"].get(); + auto entities = FindTopmostEntities(*scene, pattern); + if (entities.empty()) { + report.Warn("Crop: no entity matches '" + pattern + "', the image isn't cropped"); + return std::nullopt; + } + + // The camera that rendered the frame, the capture camera unless the scene camera is shown + auto cameraEntity = UsesCaptureCamera(activeCamera.value_or(CameraSpec {})) ? captureCameraEntity : Scene::Entity(); + const auto& camera = cameraEntity.IsValid() ? cameraEntity.GetComponent() : scene->GetMainCamera(); + vec2 min(std::numeric_limits::max()), max(-std::numeric_limits::max()); + for (auto corner : GetBounds(entities).GetCorners()) { + auto pixel = vec2(captureRenderer.GetViewport()->Project(corner, camera)); + min = glm::min(min, pixel); + max = glm::max(max, pixel); + } + + auto padding = (max - min) * crop.value("padding", 0.15f); + min -= padding; + max += padding; + auto size = glm::max(max - min, vec2(32.0f)); + return ivec4(int32_t(min.x), int32_t(min.y), int32_t(size.x), int32_t(size.y)); + + } + + void App::CompareImages() { + + const auto& spec = *job.compare; + json comparisons = json::array(); + std::error_code error; + for (const auto& output : report.GetOutputs()) { + auto relative = output.get(); + auto extension = fs::path(relative).extension().string(); + if ((extension != ".png" && extension != ".jpg") || relative == "sheet.jpg") + continue; + + auto reference = spec.reference / relative; + if (spec.update) { + fs::create_directories(reference.parent_path(), error); + fs::copy_file(job.outputDirectory / relative, reference, fs::copy_options::overwrite_existing, error); + continue; + } + + auto current = LoadImageFile(job.outputDirectory / relative); + auto expected = LoadImageFile(reference); + if (!expected) { + comparisons.push_back({ { "image", relative }, { "status", "no reference" } }); + checkRunner->AddFailure({ "compare", relative, 0.0f, "no reference image " + reference.string() }); + continue; + } + + auto difference = Bridge::CompareImages(*current, *expected, spec.threshold); + auto differs = difference.sizeMismatch || difference.percent > spec.maxPercent; + comparisons.push_back({ { "image", relative }, { "status", differs ? "differs" : "same" }, { "percent", Round(difference.percent, 3) }, + { "mean", Round(difference.mean, 3) }, { "max", difference.max } }); + if (differs) + checkRunner->AddFailure({ "compare", relative, 0.0f, difference.sizeMismatch ? "the size differs from the reference" : + FormatFloat(difference.percent, 2) + "% of the pixels differ from the reference (mean " + FormatFloat(difference.mean, 2) + ")" }); + } + + if (spec.update) + report.Print("Wrote the images as the reference to " + spec.reference.string()); + else + report.data["comparisons"] = comparisons; + + } + + void App::AddToSheet(const std::string& group, const Ref& image, const std::string& label) { + + auto& sheet = sheets[group]; + // Only the downscaled version is needed for the sheet + sheet.images.push_back(Downscale(image, 640)); + sheet.labels.push_back(label); + + } + + void App::BuildOverlay() { + + overlay->Clear(); + if (!job.overlay) + return; + + const auto& spec = *job.overlay; + overlay->depthTest = spec.depthTest; + auto& batch = overlay->GetBatch(); + auto line = [&](vec3 from, vec3 to, vec3 color) { batch->AddLine(from, to, color, color); }; + + for (auto entity : FindTopmostEntities(*scene, spec.bounds)) + batch->AddLineAABB(GetEntityBounds(entity), vec3(1.0f, 0.85f, 0.1f)); + + if (spec.players) { + auto playerSubset = scene->GetSubset(); + for (auto entity : playerSubset) + batch->AddLineCylinder(GetEntityPosition(entity), 1.8f, 0.35f, vec3(0.1f, 0.9f, 1.0f)); + } + + if (spec.trails && tracker) { + for (const auto& [label, samples] : tracker->GetSamples()) + for (size_t i = 1; i < samples.size(); i++) + line(samples[i - 1].position, samples[i].position, vec3(1.0f, 0.2f, 0.9f)); + } + + if (spec.queries) { + for (const auto& result : queryResults) { + const auto& query = result["query"]; + if (!result.contains("result")) + continue; + const auto& hit = result["result"]; + auto type = query.value("type", std::string()); + + if (!hit.is_object()) + continue; + + if (type == "path") { + const auto& samples = hit["samples"]; + for (size_t i = 1; i < samples.size(); i++) + line(ToVec3(samples[i - 1]["position"]) + vec3(0.0f, 0.05f, 0.0f), + ToVec3(samples[i]["position"]) + vec3(0.0f, 0.05f, 0.0f), vec3(0.2f, 1.0f, 0.2f)); + for (const auto& issue : hit["issues"]) + batch->AddLineCross(ToVec3(issue["at"]), 0.4f, vec3(1.0f, 0.15f, 0.15f)); + } + else if (type == "route") { + const auto& points = hit["points"]; + for (size_t i = 1; i < points.size(); i++) + line(ToVec3(points[i - 1]) + vec3(0.0f, 0.3f, 0.0f), ToVec3(points[i]) + vec3(0.0f, 0.3f, 0.0f), + vec3(1.0f, 0.85f, 0.1f)); + } + } + } + + if (spec.physics && scene->physicsWorld && scene->HasMainCamera()) { + Physics::DebugDrawSettings settings; + settings.center = scene->GetMainCamera().GetLocation(); + scene->physicsWorld->DebugDraw(batch.get(), settings); + } + + for (const auto& marker : spec.markers) + batch->AddLineCross(ToVec3(marker.at("position")), marker.value("size", 0.5f), + ToVec3(marker.value("color", json()), vec3(1.0f, 0.3f, 0.1f))); + + for (const auto& axes : spec.axes) + batch->AddLineAxes(axes, 2.0f); + + } + +} + +Atlas::EngineInstance* GetEngineInstance() { + + return new Atlas::Bridge::App(); + +} diff --git a/src/bridge/App.h b/src/bridge/App.h new file mode 100644 index 000000000..c132b8689 --- /dev/null +++ b/src/bridge/App.h @@ -0,0 +1,320 @@ +#pragma once + +#include "Job.h" +#include "CaptureRenderer.h" +#include "Checks.h" +#include "SceneTools.h" +#include "Overlay.h" +#include "Pipeline.h" +#include "Report.h" +#include "SceneEditor.h" +#include "Server.h" +#include "Player.h" + +#include "EngineInstance.h" +#include "input/PlayerInput.h" + +#include +#include +#include + +namespace Atlas::Bridge { + + class App : public EngineInstance { + + public: + App() : EngineInstance("Atlas Bridge", 1280, 720, AE_WINDOW_HIDDEN) {} + + void LoadContent() final; + + void UnloadContent() final; + + void Update(float deltaTime) final; + + void Render(float deltaTime) final; + + private: + enum class Phase { + // Server mode: waiting for the next command + Idle, + // Other engine applications keep the GPU busy, the scene loads once they are done + WaitingForGpu, + Loading, + Prepare, + EditSave, + Shots, + Play, + Finish, + Done + }; + + struct CaptureRequest { + + std::string group; + std::string label; + fs::path path; + std::vector passes; + float time = 0.0f; + std::optional crop; + + }; + + struct SheetGroup { + + std::string title; + int32_t columns = 0; + fs::path path; + std::vector> images; + std::vector labels; + + }; + + struct ShotState { + + size_t variant = 0; + size_t shot = 0; + size_t view = 0; + int32_t settledFrames = 0; + bool requested = false; + + }; + + struct StillState { + + bool active = false; + CameraSpec camera; + CaptureRequest request; + int32_t settleFrames = 0; + int32_t settledFrames = 0; + bool requested = false; + + }; + + // A single job (the default), a server that processes commands or a pipeline of edit jobs + enum class Mode { + Job, + Server, + Pipeline + }; + + // Sets up a job, it uses the loaded scene if it is the scene of the job + void StartJob(const Job& nextJob); + + // Parses a job file with the options of the command line that apply to every job + Job ParseJobFile(const fs::path& path, const std::vector& extraArguments = {}) const; + + // Resets everything that belongs to a single job + void ResetJobState(); + + void LoadScene(const std::string& path); + + void UnloadScene(); + + // Server mode: reads the next command file, runs commands that don't need frames immediately + void ProcessNextCommand(); + + void LoadSceneCommand(const json& command); + + void ReloadSceneCommand(const json& command); + + // Loads a scene without a job, it stays loaded for the following jobs. The path is a copy, it can be the + // path of the loaded scene, which is unloaded first + void LoadSceneForCommand(std::string path, const json& command); + + void RunCommand(const json& command); + + // The lua of a job or its edit, Bridge.Result values become results of the job + void RunJobLua(const LuaEvent& lua, const std::string& name); + + void StopCommand(const json& command); + + // Server mode: writes .result.json, the result of the current command + void CompleteCommand(const json& result); + + // Server mode: waits for the next command + void SetIdle(); + + // What this process does for the other engine applications, see InstanceRegistry + void SetBusyActivity(); + + // Loads the scene of scenePath, LoadScene waits for the GPU first + void BeginLoading(); + + // One step of waiting for the GPU, loads the scene once it's this process' turn + void UpdateGpuWait(); + + // Shows the window behind the other windows without the focus, or in front of them + void ShowWindow(bool foreground); + + // Called once the report of a job is written: exits, continues the pipeline or waits for the next command + void FinishJob(); + + void StartPipelineStep(); + + // A pipeline step continues with the scene in memory if it reads the scene the step before saved + bool StepReadsScene(size_t step, const std::string& scene); + + void Fail(const std::string& message); + + // Engine log entries can fail the checks and meet the log conditions of the timeline + void CollectLog(); + + bool IsSceneReady(); + + void Prepare(); + + void FinishEdit(); + + void UpdateShots(); + + // The settings of the job without a variant, also the materials patched by them + void ApplyBaseSettings(); + + void StartPlay(); + + void UpdatePlay(); + + void UpdateStill(); + + // Renders the scene without advancing time, scripts and physics + void UpdateSceneFrozen(const CameraSpec& spec); + + void Finish(); + + void CreateCaptureCamera(); + + // Updates the scene while the capture camera is the main camera. A negative delta + // time uses the fixed delta time of the job + void UpdateSceneWithCaptureCamera(const CameraSpec& spec, float deltaTime = -1.0f); + + void ApplyCameraSpec(const CameraSpec& spec); + + bool UsesCaptureCamera(const CameraSpec& spec) const; + + void RequestCapture(const CaptureRequest& request); + + bool HasPendingCaptures() const; + + void ProcessReadback(); + + void AddToSheet(const std::string& group, const Ref& image, const std::string& label); + + // The pixels of a crop of the next capture, from a rectangle or the bounds of entities seen by the current camera + std::optional GetCropRectangle(const json& crop); + + // Compares the images of the job with the reference directory of the job + void CompareImages(); + + // The timeline events the player leaves to the app: captures and resetScripts + Player::EventResult RunEvent(const EventSpec& event, bool& liveCapture); + + void BuildOverlay(); + + // Presents the frame, in a shown window with a status line and the latest output below it + void PresentWindow(); + + std::string GetStatusLine() const; + + // Render scale and upscaler, e.g. ", render scale 0.75 (FSR2)" + std::string GetRenderDescription() const; + + Mode mode = Mode::Job; + // Options of the command line which are passed on to every job of a server or pipeline + std::vector jobArguments; + + Job job; + Phase phase = Phase::Loading; + // The phase a failure ended, e.g. to unload a scene that didn't finish loading + Phase phaseBeforeFinish = Phase::Loading; + bool fatal = false; + // Jobs present without vsync, an idle or waiting process with vsync + bool vsync = false; + + Ref scene; + // Asset path of the loaded scene and its settings right after loading, restored for each job + std::string scenePath; + json sceneSettings; + // Materials patched in memory by the settings of a job or a variant, they go back to their files afterwards + std::set settingsMaterials; + // A scene loaded by a command or kept between pipeline steps stays loaded after the job + bool keepScene = false; + // Server mode: the last job played or edited the scene, the next one loads it again + bool sceneDirty = false; + // Set while a loadScene command waits for the scene to finish loading + bool loadingForCommand = false; + // The meshes of a reloaded scene, with their materials and textures, stay loaded until it is ready again + std::vector> retainedMeshes; + Scene::Entity captureCameraEntity; + // Set by a scene update, the next render uses it + bool sceneUpdated = false; + std::chrono::steady_clock::time_point loadStartTime; + + std::optional server; + std::optional pipeline; + + bool rendererInitialized = false; + float defaultRenderScale = 1.0f; + + CaptureRenderer captureRenderer; + + std::optional activeCamera; + + // All requests of a frame share the same rendered image + std::vector captureRequests; + std::vector pendingReadbacks; + // The frame which writes the captured images is left out of the profile + bool outputFrame = false; + std::map sheets; + std::vector sheetOrder; + // Every capture of the job for sheet.jpg + std::vector> jobSheetImages; + std::vector jobSheetLabels; + + ShotState shotState; + StillState stillState; + json baseSettings; + float baseRenderScale = 1.0f; + int32_t editFrames = 0; + // Until then a window shown in the background is kept behind the others, in seconds of the clock + float backgroundUntil = 0.0f; + std::chrono::steady_clock::time_point gpuWaitStart; + std::chrono::steady_clock::time_point nextGpuCheck; + std::chrono::steady_clock::time_point nextGpuWaitPrint; + // Whom this process waits for, for the status line + std::string gpuWaitReason; + EditState editState; + SceneState editBefore; + + // Capture path -> (sheet group, label) for the comparison of variants + std::map> variantCaptures; + std::map stripCameras; + + Player player; + float nextCheckTime = 0.0f; + float nextTrackTime = 0.0f; + + Input::PlayerInput playerInput; + std::unique_ptr overlay; + json queryResults = json::array(); + + std::unique_ptr checkRunner; + std::unique_ptr tracker; + + Report report; + + int32_t frameCount = 0; + int32_t readyFrame = -1; + int32_t rtWaitFrames = 0; + std::chrono::steady_clock::time_point startTime; + float loadSeconds = 0.0f; + + // Shown window: output panel and playback in real time + static constexpr size_t outputLineCount = 12; + Ref font; + std::chrono::steady_clock::time_point playStartTime; + // Clock time from which on hitches are reported + float hitchesStartTime = 0.0f; + + }; + +} diff --git a/src/bridge/Bench.cpp b/src/bridge/Bench.cpp new file mode 100644 index 000000000..06b736c59 --- /dev/null +++ b/src/bridge/Bench.cpp @@ -0,0 +1,295 @@ +#include "Bench.h" +#include "Client.h" +#include "Image.h" +#include "Processes.h" + +#include "InstanceRegistry.h" + +#include +#include +#include +#include +#include + +namespace Atlas::Bridge { + + struct Variant { + + std::string name; + fs::path executable; + // Relative to the data directory, empty for the default shaders + std::string shaderDirectory; + // Shaders that differ between the variants, touched before a run so the SPIR-V cache doesn't serve the other one + std::vector changedShaders; + + }; + + struct Statistics { + + double mean = 0.0; + double min = 0.0; + double max = 0.0; + double variance = 0.0; + + }; + + static Statistics GetStatistics(const std::vector& values) { + + Statistics statistics; + if (values.empty()) + return statistics; + statistics.min = *std::min_element(values.begin(), values.end()); + statistics.max = *std::max_element(values.begin(), values.end()); + for (auto value : values) + statistics.mean += value; + statistics.mean /= double(values.size()); + for (auto value : values) + statistics.variance += (value - statistics.mean) * (value - statistics.mean); + statistics.variance /= double(std::max(values.size(), size_t(2)) - 1); + return statistics; + + } + + // GPU passes of the profile up to the second level by their path, e.g. "Render scene / Opaque" + static std::map ReadProfile(const fs::path& path) { + + std::map passes; + std::ifstream stream(path); + auto profile = json::parse(stream, nullptr, false); + if (!profile.is_object()) + return passes; + + for (const auto& thread : profile.value("threads", json::array())) + for (const auto& query : thread.value("queries", json::array())) + if (query.value("depth", 0) <= 1) + passes[query.value("query", std::string())] += query.value("ms", 0.0); + if (profile.contains("cpu")) + passes["CPU frame"] = profile["cpu"].value("frameMs", 0.0); + return passes; + + } + + static fs::path FirstImage(const fs::path& directory) { + + std::vector images; + std::error_code error; + for (const auto& entry : fs::directory_iterator(directory, error)) + if (entry.path().extension() == ".png") + images.push_back(entry.path()); + std::sort(images.begin(), images.end()); + return images.empty() ? fs::path() : images.front(); + + } + + static std::vector GetVariants(const json& bench, const fs::path& benchDirectory) { + + auto resolve = [&](const std::string& path) { + + fs::path value(path); + if (value.is_absolute()) + return value; + auto inBench = (benchDirectory / value).lexically_normal(); + return fs::exists(inBench) ? inBench : ResolveUserPath(path); + + }; + + std::vector variants; + if (bench.contains("builds")) { + for (const auto& [name, executable] : bench["builds"].items()) + variants.push_back({ name, resolve(executable.get()) }); + for (const auto& variant : variants) + if (!fs::exists(variant.executable)) + throw std::runtime_error("The build " + variant.name + " doesn't exist: " + variant.executable.string()); + return variants; + } + if (!bench.contains("shaders")) + throw std::runtime_error("A bench needs builds or shaders"); + + // Shader directories are given to the engine relative to the data directory + auto data = GetAssetDirectory(); + std::vector directories; + for (const auto& [name, directory] : bench["shaders"].items()) { + fs::path path(directory.get()); + auto absolute = path.is_absolute() ? path : fs::exists(data / path) ? data / path : resolve(path.string()); + if (!fs::is_directory(absolute)) + throw std::runtime_error("The shader directory " + name + " doesn't exist: " + absolute.string()); + directories.push_back(fs::weakly_canonical(absolute)); + variants.push_back({ name, GetExecutablePath(), fs::relative(directories.back(), data).generic_string() }); + } + + // Only the files that differ are touched, the shaders of other applications are reloaded when they change + auto readFile = [](const fs::path& path) { + + std::ifstream stream(path, std::ios::binary); + return std::string(std::istreambuf_iterator(stream), {}); + + }; + std::error_code error; + for (const auto& entry : fs::recursive_directory_iterator(directories.front(), error)) { + if (!entry.is_regular_file()) + continue; + auto relative = fs::relative(entry.path(), directories.front()); + auto content = readFile(entry.path()); + bool differs = false; + for (size_t i = 1; i < directories.size(); i++) + differs |= readFile(directories[i] / relative) != content; + if (!differs) + continue; + for (size_t i = 0; i < directories.size(); i++) + if (fs::exists(directories[i] / relative)) + variants[i].changedShaders.push_back(directories[i] / relative); + } + Print(std::to_string(variants.front().changedShaders.size()) + " shader files differ between the directories"); + return variants; + + } + + int32_t RunBench(const std::vector& args) { + + if (args.size() < 3) + throw std::runtime_error("bench expects a bench file"); + + auto benchFile = ResolveUserPath(args[2]); + std::ifstream stream(benchFile); + auto bench = json::parse(stream, nullptr, false, true); + if (!bench.is_object()) + throw std::runtime_error("Couldn't parse " + benchFile.string()); + + auto variants = GetVariants(bench, benchFile.parent_path()); + if (variants.size() < 2) + throw std::runtime_error("A bench needs at least two builds or shader directories"); + + auto rounds = std::max(bench.value("rounds", 2), 2); + auto maxRounds = std::max(bench.value("maxRounds", 5), rounds); + auto frames = bench.value("frames", 240); + auto passFilter = bench.value("passes", std::vector()); + auto extraArgs = bench.value("args", std::vector()); + auto output = (GetExecutablePath().parent_path() / ".." / "bridge" / "bench" / benchFile.stem()).lexically_normal(); + std::error_code error; + fs::remove_all(output, error); + + for (const auto& instance : InstanceRegistry::GetInstances()) + if (instance.pid != CurrentProcessId()) + Print("Note: " + instance.executable + " (process " + std::to_string(instance.pid) + ") runs, " + instance.activity + + ". Its GPU work shifts the timings"); + + json result = json::object(); + int32_t exitCode = 0; + for (const auto& jobEntry : bench.at("jobs")) { + auto jobFile = fs::path(jobEntry.get()); + if (!jobFile.is_absolute()) + jobFile = (benchFile.parent_path() / jobFile).lexically_normal(); + auto jobName = jobFile.stem().string(); + + std::map>> measurements; + std::map> runDirectories; + int32_t round = 0; + bool decided = false; + while (round < maxRounds && !decided) { + round++; + // Alternating the order cancels a drift over the rounds, e.g. a GPU that heats up + auto order = variants; + if (round % 2 == 0) + std::reverse(order.begin(), order.end()); + + for (const auto& variant : order) { + for (const auto& shader : variant.changedShaders) + fs::last_write_time(shader, fs::file_time_type::clock::now(), error); + WaitForGpu(600.0f); + + auto directory = output / jobName / (variant.name + "_" + std::to_string(round)); + std::vector command = { variant.executable.string(), jobFile.string(), "--out", directory.string(), + "--resolution", "1920x1080", "--profile", "64", "--settle", std::to_string(frames), + "--set", "postProcessing.autoExposure.enable=false", "--pause", "--no-wait-gpu" }; + if (!variant.shaderDirectory.empty()) + command.insert(command.end(), { "--shader-dir", variant.shaderDirectory }); + command.insert(command.end(), extraArgs.begin(), extraArgs.end()); + + fs::create_directories(directory, error); + auto start = std::chrono::steady_clock::now(); + auto code = RunProcess(command, variant.executable.parent_path(), directory / "bench_run.log", 900.0f); + auto passes = ReadProfile(directory / "profile.json"); + if (code != 0 || passes.empty()) { + Print(jobName + " " + variant.name + " round " + std::to_string(round) + " failed with exit code " + + std::to_string(code) + ", see " + (directory / "bench_run.log").string()); + return 2; + } + for (const auto& [pass, milliseconds] : passes) + measurements[variant.name][pass].push_back(milliseconds); + runDirectories[variant.name].push_back(directory); + Print(jobName + " " + variant.name + " round " + std::to_string(round) + ": Render scene " + + FormatFloat(float(passes["Render scene"]), 3) + " ms (" + FormatFloat(SecondsSince(start), 0) + " s)"); + } + + if (round < rounds) + continue; + + // More rounds only help while the difference of the frame is within its uncertainty and above 1 % + auto base = GetStatistics(measurements[variants[0].name]["Render scene"]); + auto change = GetStatistics(measurements[variants[1].name]["Render scene"]); + auto standardError = std::sqrt(base.variance / double(round) + change.variance / double(round)); + auto delta = std::abs(change.mean - base.mean); + decided = delta > 2.0 * standardError || 2.0 * standardError < 0.01 * base.mean; + } + + // Passes of the frame total and the largest ones unless the bench names them + std::vector passes = passFilter; + if (passes.empty()) { + std::vector> sorted; + for (const auto& [pass, values] : measurements[variants[0].name]) + sorted.emplace_back(GetStatistics(values).mean, pass); + std::sort(sorted.rbegin(), sorted.rend()); + for (size_t i = 0; i < std::min(sorted.size(), size_t(14)); i++) + passes.push_back(sorted[i].second); + } + + Print(""); + Print(jobName + ", " + std::to_string(round) + " rounds, ms as mean (min - max):"); + json jobResult = json::object(); + for (const auto& pass : passes) { + std::string line = " " + pass + ":"; + json passResult = json::object(); + std::vector statistics; + for (const auto& variant : variants) { + auto values = measurements[variant.name][pass]; + statistics.push_back(GetStatistics(values)); + const auto& s = statistics.back(); + line += " " + variant.name + " " + FormatFloat(float(s.mean), 3) + " (" + FormatFloat(float(s.min), 3) + " - " + + FormatFloat(float(s.max), 3) + ")"; + passResult[variant.name] = { { "mean", s.mean }, { "min", s.min }, { "max", s.max }, { "values", values } }; + } + auto standardError = std::sqrt(statistics[0].variance / double(round) + statistics[1].variance / double(round)); + auto delta = statistics[1].mean - statistics[0].mean; + auto verdict = std::abs(delta) > 2.0 * standardError ? (delta < 0.0 ? "faster" : "slower") : "inconclusive"; + line += ", " + std::string(delta >= 0.0 ? "+" : "") + FormatFloat(float(delta), 3) + " ms " + verdict; + passResult["delta"] = delta; + passResult["verdict"] = verdict; + jobResult[pass] = passResult; + Print(line); + } + + // Pixel differences between the builds next to those between two runs of one build + auto noiseA = FirstImage(runDirectories[variants[0].name][0]), noiseB = FirstImage(runDirectories[variants[0].name][1]); + auto changed = FirstImage(runDirectories[variants[1].name][0]); + if (!noiseA.empty() && !noiseB.empty() && !changed.empty()) { + auto a = LoadImageFile(noiseA), b = LoadImageFile(noiseB), c = LoadImageFile(changed); + if (a && b && c) { + auto noise = CompareImages(*a, *b, 8); + auto difference = CompareImages(*a, *c, 8); + Print(" pixels: " + variants[0].name + " to " + variants[1].name + " " + FormatFloat(difference.percent, 2) + "% differ (mean " + + FormatFloat(difference.mean, 2) + "), two runs of " + variants[0].name + " " + FormatFloat(noise.percent, 2) + + "% (mean " + FormatFloat(noise.mean, 2) + ")"); + jobResult["pixels"] = { { "builds", difference.percent }, { "noise", noise.percent } }; + } + } + jobResult["rounds"] = round; + result[jobName] = jobResult; + } + + WriteFileAtomic(output / "bench.json", result.dump(2)); + Print("Results in " + (output / "bench.json").string()); + return exitCode; + + } + +} diff --git a/src/bridge/Bench.h b/src/bridge/Bench.h new file mode 100644 index 000000000..3ea7d6503 --- /dev/null +++ b/src/bridge/Bench.h @@ -0,0 +1,16 @@ +#pragma once + +#include "Common.h" + +namespace Atlas::Bridge { + + // bench : runs jobs with two or more builds (executables) or shader directories in interleaved rounds with + // the deterministic settings of the performance rules (1920x1080, 240 frames, the last 64 profiled, auto exposure off, + // the scene paused right away) and reports the frame total and the passes as mean and spread per build. Rounds are added while a + // difference is smaller than the spread. The images of two builds are compared with the noise of one build + // { "jobs": ["sponza.json"], "builds": { "base": "bin/RelWithDebInfo/AtlasBridge_base.exe", "change": "..." }, + // "rounds": 2, "maxRounds": 5, "passes": ["Render scene"] } + // or "shaders": { "base": "", "change": "shader" } instead of builds, run with this executable + int32_t RunBench(const std::vector& args); + +} diff --git a/src/bridge/CMakeLists.txt b/src/bridge/CMakeLists.txt new file mode 100644 index 000000000..15afeade0 --- /dev/null +++ b/src/bridge/CMakeLists.txt @@ -0,0 +1,53 @@ +cmake_minimum_required(VERSION 3.25) + +project(AtlasBridge VERSION 0.2.1) + +# The bridge is a library: game hosts link AtlasBridgeLibrary to run jobs with their own interface +# (HostedJob.h). The executable adds the standalone app with its own renderer (App.cpp), for it the root +# CMakeLists.txt turns the ATLAS_EXPORT_MAIN option on. Neither needs ImGui. +set(ATLAS_BRIDGE_OUTPUT_NAME "AtlasBridge" CACHE STRING "File name of the bridge executable") + +file(GLOB_RECURSE BRIDGE_SOURCE_FILES "*.cpp" "*.h") +set(BRIDGE_APP_FILES ${CMAKE_CURRENT_SOURCE_DIR}/App.cpp ${CMAKE_CURRENT_SOURCE_DIR}/App.h) +list(REMOVE_ITEM BRIDGE_SOURCE_FILES ${BRIDGE_APP_FILES}) + +foreach(SOURCE_FILE IN ITEMS ${BRIDGE_SOURCE_FILES} ${BRIDGE_APP_FILES}) + file(RELATIVE_PATH SOURCE_FILE_REL "${CMAKE_CURRENT_SOURCE_DIR}" "${SOURCE_FILE}") + get_filename_component(SOURCE_PATH "${SOURCE_FILE_REL}" PATH) + string(REPLACE "/" "\\" SOURCE_PATH_CONVERTED "${SOURCE_PATH}") + source_group("${SOURCE_PATH_CONVERTED}" FILES "${SOURCE_FILE}") +endforeach() + +add_library(AtlasBridgeLibrary STATIC ${BRIDGE_SOURCE_FILES}) +target_include_directories(AtlasBridgeLibrary PUBLIC ${CMAKE_CURRENT_SOURCE_DIR} ../engine ../../libs) +target_compile_definitions(AtlasBridgeLibrary PUBLIC ${ATLAS_ENGINE_COMPILE_DEFINITIONS}) +target_link_libraries(AtlasBridgeLibrary PUBLIC AtlasEngine) + +# Every program linking the library can offer the MCP server +find_package(httplib CONFIG REQUIRED) +target_link_libraries(AtlasBridgeLibrary PRIVATE httplib::httplib) +# Winsock has to come before windows.h, which the precompiled header of the engine can't promise +set_source_files_properties(${CMAKE_CURRENT_SOURCE_DIR}/McpServer.cpp PROPERTIES SKIP_PRECOMPILE_HEADERS ON) + +if (NOT ATLAS_BRIDGE) + return() +endif() + +# We want to make sure that the linker searches for local libraries first +if (UNIX AND NOT APPLE AND NOT ANDROID) +set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,-rpath='$ORIGIN'") +endif() +# Need to reference the vulkan SDK for MacOS to search at runtime +if (APPLE) +set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,-rpath,'/usr/local/lib'") +endif() + +add_executable(${PROJECT_NAME} ${BRIDGE_APP_FILES} ${ATLAS_ENGINE_MAIN_FILE}) +target_link_libraries(${PROJECT_NAME} AtlasBridgeLibrary) +set_target_properties(${PROJECT_NAME} PROPERTIES OUTPUT_NAME ${ATLAS_BRIDGE_OUTPUT_NAME}) + +# A running bridge can't be overwritten (LNK1168), but Windows lets it be renamed +if (WIN32) + add_custom_command(TARGET ${PROJECT_NAME} PRE_LINK + COMMAND ${CMAKE_COMMAND} -DEXECUTABLE=$ -P ${CMAKE_CURRENT_SOURCE_DIR}/MoveRunningExecutable.cmake) +endif() diff --git a/src/bridge/CaptureRenderer.cpp b/src/bridge/CaptureRenderer.cpp new file mode 100644 index 000000000..84a0e891b --- /dev/null +++ b/src/bridge/CaptureRenderer.cpp @@ -0,0 +1,244 @@ +#include "CaptureRenderer.h" + +#include "graphics/GraphicsDevice.h" + +#include + +namespace Atlas::Bridge { + + void CaptureRenderer::Init(Ref mainRenderer, ivec2 resolution) { + + this->mainRenderer = mainRenderer; + this->resolution = resolution; + + renderTarget = CreateRef(resolution.x, resolution.y); + viewport = CreateRef(0, 0, resolution.x, resolution.y); + + // Post-processing output is already tone mapped and gamma corrected + outputTexture = CreateRef(resolution.x, resolution.y, VK_FORMAT_R16G16B16A16_SFLOAT); + + } + + void CaptureRenderer::Resize(ivec2 resolution) { + + this->resolution = resolution; + renderTarget->Resize(resolution.x, resolution.y); + viewport->Set(0, 0, resolution.x, resolution.y); + outputTexture = CreateRef(resolution.x, resolution.y, VK_FORMAT_R16G16B16A16_SFLOAT); + // Recreated with the new resolution on their next use + passTargets.clear(); + + } + + void CaptureRenderer::Render(const Ref& scene, const std::vector& passes, + std::span> primitiveBatches, bool pathTrace) { + + if (pathTrace) + mainRenderer->PathTraceScene(viewport, renderTarget, scene, outputTexture.get(), primitiveBatches); + else + mainRenderer->RenderScene(viewport, renderTarget, scene, primitiveBatches, outputTexture.get()); + hasFrame = true; + + float exposure = scene->HasMainCamera() ? scene->GetMainCamera().exposure : 1.0f; + for (const auto& pass : passes) + RenderPass(pass, exposure); + + } + + void CaptureRenderer::Present(const Ref& font, const std::vector& lines) { + + auto device = Graphics::GraphicsDevice::DefaultDevice; + // A minimized window has no swap chain images + if (!device->swapChain->isComplete) + return; + + auto commandList = device->GetCommandList(); + + commandList->BeginCommands(); + device->swapChain->colorClearValue.color = { 0.0f, 0.0f, 0.0f, 1.0f }; + commandList->BeginRenderPass(device->swapChain, true); + + auto extent = device->swapChain->extent; + auto windowViewport = CreateRef(0, 0, int32_t(extent.width), int32_t(extent.height)); + auto panelHeight = font && !lines.empty() ? GetPanelHeight(font, lines.size()) : 0.0f; + + if (hasFrame && outputTexture->image->layout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) { + // Keep the aspect ratio of the capture in the area above the panel + auto areaWidth = float(extent.width); + auto areaHeight = std::max(float(extent.height) - panelHeight, 1.0f); + auto scale = std::min(areaWidth / float(outputTexture->width), areaHeight / float(outputTexture->height)); + auto width = float(outputTexture->width) * scale; + auto height = float(outputTexture->height) * scale; + // The texture renderer places the image from the bottom and needs to flip it + mainRenderer->textureRenderer.RenderTexture2D(commandList, windowViewport, outputTexture.get(), + (areaWidth - width) * 0.5f, panelHeight + (areaHeight - height) * 0.5f, width, height, 0.0f, 1.0f, + false, true); + } + + if (panelHeight > 0.0f) { + auto y = float(extent.height) - panelHeight + panelPadding; + for (const auto& line : lines) { + mainRenderer->textRenderer.Render(commandList, windowViewport, font, line.text, panelPadding, y, line.color); + y += font->lineHeight; + } + } + + commandList->EndRenderPass(); + commandList->EndCommands(); + + device->SubmitCommandList(commandList); + + } + + float CaptureRenderer::GetPanelHeight(const Ref& font, size_t lineCount) { + + return float(lineCount) * font->lineHeight + 2.0f * panelPadding; + + } + + void CaptureRenderer::SetRenderScale(float renderScale) { + + if (renderTarget->GetScalingFactor() != renderScale) + renderTarget->SetScalingFactor(renderScale); + + } + + float CaptureRenderer::GetRenderScale() const { + + return renderTarget->GetScalingFactor(); + + } + + Ref CaptureRenderer::ReadOutput() { + + auto image = outputTexture->GetImage(); + + // The alpha channel isn't meaningful, write opaque images + auto& data = image->GetData(); + for (size_t i = 3; i < data.size(); i += 4) + data[i] = 255; + + return image; + + } + + Ref CaptureRenderer::ReadPass(const std::string& pass) { + + auto& target = GetPassTarget(pass); + auto floatImage = target.texture->GetImage(); + auto& floatData = floatImage->GetData(); + + for (size_t i = 0; i < floatData.size(); i += 4) { + // Signed screen space motion, no motion is gray + if (pass == "velocity") { + floatData[i] = 0.5f + 0.5f * floatData[i]; + floatData[i + 1] = 0.5f + 0.5f * floatData[i + 1]; + floatData[i + 2] = 0.5f; + } + floatData[i + 3] = 1.0f; + } + + auto image = CreateImage(target.texture->width, target.texture->height); + image->SetData(floatImage->ConvertData()); + + return image; + + } + + const std::vector& CaptureRenderer::GetPassNames() { + + static const std::vector names = { "albedo", "normal", "geometryNormal", "roughness", "emissive", + "depth", "velocity", "stencil", "materialIdx", "reflection", "volumetric", "clouds", "sss", "gi" }; + return names; + + } + + void CaptureRenderer::RenderPass(const std::string& pass, float exposure) { + + auto device = Graphics::GraphicsDevice::DefaultDevice; + auto& target = GetPassTarget(pass); + auto rtData = renderTarget->GetData(Renderer::RenderResolution::FULL_RES); + + Texture::Texture2D* texture = nullptr; + float scale = 1.0f; + if (pass == "albedo") + texture = rtData->baseColorTexture.get(); + else if (pass == "normal") + texture = rtData->normalTexture.get(); + else if (pass == "geometryNormal") + texture = rtData->geometryNormalTexture.get(); + else if (pass == "roughness") + texture = rtData->roughnessMetallicAoTexture.get(); + else if (pass == "emissive") + texture = rtData->emissiveTexture.get(); + else if (pass == "depth") + texture = rtData->depthTexture.get(); + else if (pass == "velocity") { + texture = rtData->velocityTexture.get(); + scale = 100.0f; + } + else if (pass == "stencil") { + texture = rtData->stencilTexture.get(); + scale = 1.0f / 255.0f; + } + else if (pass == "materialIdx") { + texture = rtData->materialIdxTexture.get(); + scale = 1.0f / 10000.0f; + } + else if (pass == "reflection") { + texture = &renderTarget->reflectionTexture; + scale = exposure; + } + else if (pass == "volumetric") { + texture = &renderTarget->volumetricTexture; + scale = exposure; + } + else if (pass == "clouds") { + texture = &renderTarget->volumetricCloudsTexture; + scale = exposure; + } + else if (pass == "sss") + texture = &renderTarget->sssTexture; + else if (pass == "gi") { + texture = &renderTarget->giTexture; + scale = exposure; + } + + if (!texture) + return; + + auto commandList = device->GetCommandList(Graphics::GraphicsQueue); + commandList->BeginCommands(); + commandList->BeginRendering(Graphics::RenderingDesc { .colorAttachments = { { + .image = target.texture->image, + .loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR + } } }); + + mainRenderer->textureRenderer.RenderTexture2D(commandList, viewport, texture, 0.0f, 0.0f, + float(viewport->width), float(viewport->height), 0.0f, scale, false, true); + + commandList->EndRendering(); + commandList->EndCommands(); + + device->SubmitCommandList(commandList); + + } + + CaptureRenderer::PassTarget& CaptureRenderer::GetPassTarget(const std::string& pass) { + + if (std::find(GetPassNames().begin(), GetPassNames().end(), pass) == GetPassNames().end()) + throw std::runtime_error("Unknown pass '" + pass + "'"); + + auto it = passTargets.find(pass); + if (it != passTargets.end()) + return it->second; + + // Passes keep negative values, e.g. of the velocity + PassTarget target; + target.texture = CreateRef(resolution.x, resolution.y, VK_FORMAT_R16G16B16A16_SFLOAT); + + return passTargets[pass] = target; + + } + +} diff --git a/src/bridge/CaptureRenderer.h b/src/bridge/CaptureRenderer.h new file mode 100644 index 000000000..b400e32ee --- /dev/null +++ b/src/bridge/CaptureRenderer.h @@ -0,0 +1,88 @@ +#pragma once + +#include "Common.h" +#include "Image.h" + +#include "Viewport.h" +#include "Font.h" +#include "renderer/MainRenderer.h" +#include "texture/Texture2D.h" +#include "graphics/Rendering.h" + +#include + +namespace Atlas::Bridge { + + // Renders a scene into an offscreen texture like the editor viewport does, + // optionally renders debug views of intermediate passes and reads everything back + class CaptureRenderer { + + public: + struct TextLine { + + std::string text; + vec4 color = vec4(1.0f); + + }; + + void Init(Ref mainRenderer, ivec2 resolution); + + // Changes the resolution of an initialized renderer, the render target is resized such that + // renderers which keep state per target (e.g. FSR2) adapt to it + void Resize(ivec2 resolution); + + void Render(const Ref& scene, const std::vector& passes, + std::span> primitiveBatches = {}, bool pathTrace = false); + + // Shows the last rendered frame in the (possibly hidden) window. This also keeps + // the swap chain acquire/present cycle going. Text lines are shown in a panel below the frame + void Present(const Ref& font = nullptr, const std::vector& lines = {}); + + // Height of the text panel for a number of lines + static float GetPanelHeight(const Ref& font, size_t lineCount); + + // Only valid after the frame that rendered the content has finished on the GPU + Ref ReadOutput(); + + Ref ReadPass(const std::string& pass); + + static const std::vector& GetPassNames(); + + const Ref& GetViewport() const { return viewport; } + + // Scaling factor of the render target, the output keeps the resolution + void SetRenderScale(float renderScale); + + float GetRenderScale() const; + + // Temporal effects start over, e.g. when switching to another camera while the scene is paused + void InvalidateHistory() { renderTarget->InvalidateHistory(); } + + ivec2 resolution = ivec2(0); + + private: + struct PassTarget { + + Ref texture; + + }; + + void RenderPass(const std::string& pass, float exposure); + + PassTarget& GetPassTarget(const std::string& pass); + + Ref mainRenderer; + Ref renderTarget; + Ref viewport; + + Ref outputTexture; + + std::map passTargets; + + bool hasFrame = false; + + static constexpr float panelPadding = 8.0f; + + }; + +} diff --git a/src/bridge/Check.cpp b/src/bridge/Check.cpp new file mode 100644 index 000000000..befa17645 --- /dev/null +++ b/src/bridge/Check.cpp @@ -0,0 +1,201 @@ +#include "Check.h" +#include "LuaJob.h" +#include "MaterialGraphTools.h" +#include "Processes.h" +#include "SceneFile.h" + +#include + +namespace Atlas::Bridge { + + struct EntityReference { + + std::string pattern; + std::string where; + // Entities that have to be in the scene file, others may be created by scripts or edits + bool required = false; + + }; + + static std::vector CollectReferences(const Job& job) { + + std::vector references; + auto add = [&](const std::string& pattern, const std::string& where, bool required = false) { + + if (!pattern.empty() && pattern != "*" && !pattern.starts_with("#")) + references.push_back({ pattern, where, required }); + + }; + auto addCamera = [&](const CameraSpec& camera, const std::string& where, bool required = false) { + + if (camera.mode == "focus" || camera.mode == "follow") + add(camera.entity, where, required); + + }; + + for (const auto& shot : job.shots) + addCamera(shot.camera, "shot " + shot.name, !job.edit); + if (job.observer) + addCamera(*job.observer, "observer"); + for (const auto& strip : job.strips) + if (strip.hasCamera) + addCamera(strip.camera, "strip " + strip.name); + for (const auto& script : job.scripts) + add(script.entity, "script " + script.path); + + for (const auto& event : job.timeline) { + auto where = event.type + " at t=" + FormatFloat(event.time, 2); + std::visit([&](const auto& action) { + + using Action = std::decay_t; + if constexpr (std::is_same_v || std::is_same_v || + std::is_same_v) + add(action.entity, where); + if constexpr (std::is_same_v) + if (action.camera) + addCamera(*action.camera, where); + if constexpr (std::is_same_v) + if (action.expectation.contains("entity")) + add(action.expectation["entity"].template get(), where); + + }, event.action); + if (event.when && event.when->contains("entity")) + add((*event.when)["entity"].get(), "condition of " + where); + } + + if (job.checks.grounded) + for (const auto& pattern : job.checks.grounded->entities) + add(pattern, "checks.grounded"); + if (job.checks.penetration) + for (const auto& pattern : job.checks.penetration->entities) + add(pattern, "checks.penetration"); + if (job.track) + for (const auto& pattern : job.track->entities) + add(pattern, "track"); + + return references; + + } + + static void CheckLua(const Job& job, std::vector& issues) { + + auto check = [&](const std::string& code, const std::string& where, bool expression) { + + auto error = LuaJob::Compile(code, where, expression); + if (!error.empty()) + issues.push_back("ERROR: Lua of the " + where + " doesn't compile: " + error); + + }; + + for (const auto& event : job.timeline) { + auto where = event.type + " event at t=" + FormatFloat(event.time, 2); + if (auto lua = std::get_if(&event.action)) + check(lua->code, lua->file.empty() ? where : lua->file, !lua->result.empty()); + if (auto expect = std::get_if(&event.action); expect && expect->expectation.contains("lua")) + check(expect->expectation["lua"].get(), where, true); + if (event.when && event.when->contains("lua")) + check((*event.when)["lua"].get(), "condition of the " + where, true); + } + + if (job.lua) + check(job.lua->code, job.lua->file.empty() ? "lua of the job" : job.lua->file, false); + if (job.edit && job.edit->lua) + check(job.edit->lua->code, job.edit->lua->file.empty() ? "lua of the edit" : job.edit->lua->file, false); + + for (const auto& script : job.scripts) { + fs::path path(script.path); + std::ifstream stream(path.is_absolute() ? path : GetAssetDirectory() / path); + if (stream.is_open()) + check(std::string(std::istreambuf_iterator(stream), {}), "script " + script.path, false); + } + + } + + static void RunPreflight(const Job& job, std::vector& issues) { + + if (job.preflight.empty() || !job.play) + return; + + auto log = GetExecutablePath().parent_path() / ".cache" / "bridge-preflight.log"; + std::error_code error; + fs::create_directories(log.parent_path(), error); + auto start = std::chrono::steady_clock::now(); + auto exitCode = RunProcess(job.preflight, job.preflightDirectory, log, 120.0f); + if (exitCode == 0) + return; + + std::string command; + for (const auto& arg : job.preflight) + command += (command.empty() ? "" : " ") + arg; + std::ifstream stream(log); + std::vector lines; + for (std::string line; std::getline(stream, line);) + if (!line.empty()) + lines.push_back(line); + std::string output; + for (size_t i = lines.size() > 12 ? lines.size() - 12 : 0; i < lines.size(); i++) + output += "\n " + lines[i]; + issues.push_back("ERROR: The preflight of the project (" + command + ") failed with exit code " + std::to_string(exitCode) + + " after " + FormatFloat(SecondsSince(start), 1) + " s:" + output); + + } + + std::vector CheckJob(const Job& job, bool preflight) { + + std::vector issues; + CheckLua(job, issues); + if (job.edit) + CheckMaterialGraphOperations(job.edit->operations, issues); + + auto references = CollectReferences(job); + auto scenePath = fs::path(job.scene).is_absolute() ? fs::path(job.scene) : GetAssetDirectory() / job.scene; + if (!references.empty() && fs::exists(scenePath)) { + std::vector names; + try { + names = ReadEntityNames(scenePath); + } + catch (const std::exception& e) { + issues.push_back("NOTE: The entities of " + job.scene + " couldn't be read: " + e.what()); + } + + for (const auto& reference : references) { + if (names.empty() || std::any_of(names.begin(), names.end(), [&](const std::string& name) { + return Helper::String::MatchWildcard(reference.pattern, name); })) + continue; + + std::string closest; + for (const auto& name : FindClosestNames(names, reference.pattern)) + closest += (closest.empty() ? "" : ", ") + std::string("'") + name + "'"; + auto message = "no entity of " + job.scene + " matches '" + reference.pattern + "' (" + reference.where + "), closest: " + + closest; + issues.push_back(reference.required ? "ERROR: " + message : "NOTE: " + message + ". Scripts or edits may create it"); + } + } + else if (!fs::exists(scenePath)) { + issues.push_back("NOTE: The scene " + job.scene + " doesn't exist yet"); + } + + if (preflight) + RunPreflight(job, issues); + + std::stable_partition(issues.begin(), issues.end(), [](const std::string& issue) { return issue.starts_with("ERROR"); }); + return issues; + + } + + std::vector CheckJobFile(const fs::path& path, const std::vector& options) { + + std::vector args = { "AtlasBridge" }; + args.insert(args.end(), options.begin(), options.end()); + args.push_back(path.string()); + + try { + return CheckJob(ParseCommandLine(args)); + } + catch (const std::exception& e) { + return { std::string("ERROR: ") + e.what() }; + } + + } + +} diff --git a/src/bridge/Check.h b/src/bridge/Check.h new file mode 100644 index 000000000..afefdfaa0 --- /dev/null +++ b/src/bridge/Check.h @@ -0,0 +1,15 @@ +#pragma once + +#include "Job.h" + +namespace Atlas::Bridge { + + // Finds mistakes in a job before its scene is loaded: Lua that doesn't compile, entity patterns that match no entity + // of the scene file (with the closest names) and the preflight command of the project (bridge.project.json) for + // jobs that play. Issues start with ERROR (the job can't run) or NOTE (e.g. an entity a script may still create) + std::vector CheckJob(const Job& job, bool preflight = true); + + // Parses the job file with the options before it, a parse error is the only issue then + std::vector CheckJobFile(const fs::path& path, const std::vector& options); + +} diff --git a/src/bridge/Checks.cpp b/src/bridge/Checks.cpp new file mode 100644 index 000000000..53b4f735f --- /dev/null +++ b/src/bridge/Checks.cpp @@ -0,0 +1,380 @@ +#include "Checks.h" + +#include + +namespace Atlas::Bridge { + + using namespace Scene::Components; + + // Counts the triangles of a mesh that intersect the given world space box + static int32_t CountIntrudingTriangles(const MeshComponent& meshComponent, const TransformComponent& transform, + const Volume::AABB& box) { + + if (!meshComponent.mesh.IsLoaded()) + return 0; + + auto& data = meshComponent.mesh->data; + auto& vertices = data.vertices.Get(); + auto& indices = data.indices.Get(); + + // Cheap rejection in local space with the conservatively transformed box + auto localBox = box.Transform(glm::inverse(transform.globalMatrix)); + + int32_t count = 0; + for (size_t i = 0; i + 2 < indices.size(); i += 3) { + const auto& a = vertices[indices[i]]; + const auto& b = vertices[indices[i + 1]]; + const auto& c = vertices[indices[i + 2]]; + + auto min = glm::min(a, glm::min(b, c)), max = glm::max(a, glm::max(b, c)); + if (glm::any(glm::lessThan(max, localBox.min)) || glm::any(glm::greaterThan(min, localBox.max))) + continue; + + auto worldA = vec3(transform.globalMatrix * vec4(a, 1.0f)); + auto worldB = vec3(transform.globalMatrix * vec4(b, 1.0f)); + auto worldC = vec3(transform.globalMatrix * vec4(c, 1.0f)); + if (box.IntersectsTriangle(worldA, worldB, worldC)) + count++; + } + + return count; + + } + + static bool MatchesSelfOrAncestor(Scene::Scene& scene, Scene::Entity entity, + const std::vector& patterns) { + + while (entity.IsValid()) { + if (MatchAnyPattern(patterns, GetEntityName(entity))) + return true; + entity = scene.GetParentEntity(entity); + } + + return false; + + } + + static bool Compare(float actual, const std::string& op, float expected, float tolerance) { + + if (op == ">") + return actual > expected; + if (op == ">=") + return actual >= expected; + if (op == "<") + return actual < expected; + if (op == "<=") + return actual <= expected; + if (op == "==") + return std::abs(actual - expected) <= tolerance; + if (op == "!=") + return std::abs(actual - expected) > tolerance; + throw std::runtime_error("Unknown comparison operator '" + op + "'"); + + } + + void CheckRunner::Run(Scene::Scene& scene, float time) { + + if (spec.grounded) + CheckGrounded(scene, time); + if (spec.penetration) + CheckPenetration(scene, time); + if (spec.invalidTransforms) + CheckInvalidTransforms(scene, time); + + } + + void CheckRunner::AddFailure(const Failure& failure) { + + auto key = failure.check + "|" + failure.entity; + if (failureCounts[key]++ == 0) + failures.push_back(failure); + + } + + void CheckRunner::CheckGrounded(Scene::Scene& scene, float time) { + + auto entities = spec.grounded->entities.empty() ? std::vector() : FindTopmostEntities(scene, spec.grounded->entities); + auto meshInstances = FindMeshInstances(scene, spec.grounded->meshes); + entities.insert(entities.end(), meshInstances.begin(), meshInstances.end()); + runCounts["grounded"] += int32_t(entities.size()); + + if (!groundedIgnored) + groundedIgnored = spec.grounded->ignore.empty() ? EntitySet() : CollectHierarchies(scene, spec.grounded->ignore); + + for (auto entity : entities) { + // Skip entities whose hierarchy has no loaded mesh bounds + auto [bounds, hasMesh, ground] = GroundBelowEntity(scene, entity, 0.5f, *groundedIgnored); + if (!hasMesh) + continue; + + if (!ground.valid) { + AddFailure({ "grounded", GetEntityLabel(entity), time, + "no ground below the entity at " + FormatVec3(bounds.GetCenter()) }); + continue; + } + + // Standing on a prop (e.g. walking over hay bales) counts as a failure if surfaces are given + const auto& surfaces = spec.grounded->surfaces; + if (!surfaces.empty() && ground.entity.IsValid() && !MatchesSelfOrAncestor(scene, ground.entity, surfaces)) { + AddFailure({ "grounded", GetEntityLabel(entity), time, + "stands on " + GetEntityLabel(ground.entity) + ", which doesn't match the allowed surfaces" }); + continue; + } + + auto heights = " (bottom y " + FormatFloat(bounds.min.y) + ", ground y " + FormatFloat(ground.position.y) + ")"; + auto gap = bounds.min.y - ground.position.y; + if (gap > spec.grounded->maxGap) { + AddFailure({ "grounded", GetEntityLabel(entity), time, + "floats " + FormatFloat(gap) + " m above " + GetHitLabel(ground) + heights }); + continue; + } + if (gap < -spec.grounded->maxSink) { + AddFailure({ "grounded", GetEntityLabel(entity), time, + "sinks " + FormatFloat(-gap) + " m into " + GetHitLabel(ground) + heights }); + continue; + } + + // The edges of wide meshes on a slope can hang in the air while the center sits on the ground + if (spec.grounded->footprint > 1) { + auto footprint = MeasureFootprint(scene, entity, bounds, spec.grounded->footprint, spec.grounded->baseHeight, *groundedIgnored); + if (footprint.samples > 0 && footprint.maxGap > spec.grounded->maxGap) + AddFailure({ "grounded", GetEntityLabel(entity), time, "its underside floats " + FormatFloat(footprint.maxGap) + " m at " + + FormatVec3(footprint.worst, 2) + " (worst of " + std::to_string(footprint.samples) + " footprint points)" }); + } + } + + } + + void CheckRunner::CheckPenetration(Scene::Scene& scene, float time) { + + auto& penetration = *spec.penetration; + auto entities = FindTopmostEntities(scene, penetration.entities); + runCounts["penetration"] += int32_t(entities.size()); + + for (auto entity : entities) { + EntitySet hierarchy; + CollectHierarchy(entity, hierarchy); + + bool hasMesh = false; + auto bounds = GetEntityBounds(entity, &hasMesh); + if (!hasMesh) + continue; + + // Shrink the bounds such that touching neighbors (e.g. resting on the floor) don't count + auto margin = glm::min(vec3(penetration.margin), bounds.GetSize() * 0.45f); + auto box = Volume::AABB(bounds.min + margin, bounds.max - margin); + + for (auto other : scene.QueryAABB(box)) { + if (hierarchy.contains(other)) + continue; + if (!MatchesSelfOrAncestor(scene, other, penetration.against)) + continue; + + auto meshComponent = other.TryGetComponent(); + auto transform = other.TryGetComponent(); + if (!meshComponent || !transform || !meshComponent->visible) + continue; + + auto intruding = CountIntrudingTriangles(*meshComponent, *transform, box); + + // Count only additional intersections relative to the first observation + auto key = std::make_pair(ECS::Entity(entity), ECS::Entity(other)); + auto [it, inserted] = baselineIntrusions.try_emplace(key, intruding); + auto increase = intruding - it->second; + + if (increase >= penetration.minTriangles) + AddFailure({ "penetration", GetEntityLabel(entity), time, + std::to_string(increase) + " more triangles of " + GetEntityLabel(other) + + " intrude into its bounds than at the start (" + std::to_string(intruding) + " vs " + + std::to_string(it->second) + ", bounds " + FormatVec3(bounds.min) + " - " + FormatVec3(bounds.max) + ")" }); + } + } + + } + + void CheckRunner::CheckInvalidTransforms(Scene::Scene& scene, float time) { + + auto transformSubset = scene.GetSubset(); + for (auto entity : transformSubset) { + const auto& transform = transformSubset.Get(entity); + + const float* values = glm::value_ptr(transform.globalMatrix); + bool valid = true; + for (int32_t i = 0; i < 16; i++) + valid &= std::isfinite(values[i]); + + if (!valid) + AddFailure({ "invalidTransforms", GetEntityLabel({ entity, &scene.entityManager }), time, + "transform contains NaN or infinite values" }); + } + + } + + json CheckRunner::GetReport() const { + + json j; + j["passed"] = failures.empty(); + + auto getRunCount = [&](const std::string& check) { + + return runCounts.contains(check) ? runCounts.at(check) : 0; + + }; + + json checks = json::object(); + if (spec.grounded) + checks["grounded"] = { { "evaluations", getRunCount("grounded") } }; + if (spec.penetration) + checks["penetration"] = { { "evaluations", getRunCount("penetration") } }; + j["checks"] = checks; + + json failureList = json::array(); + for (const auto& failure : failures) { + auto key = failure.check + "|" + failure.entity; + failureList.push_back({ { "check", failure.check }, { "entity", failure.entity }, { "firstTime", failure.time }, + { "message", failure.message }, { "occurrences", failureCounts.at(key) } }); + } + j["failures"] = failureList; + + return j; + + } + + std::vector CheckRunner::GetSummary() const { + + std::vector lines; + for (const auto& failure : failures) { + auto key = failure.check + "|" + failure.entity; + lines.push_back("[" + failure.check + "] t=" + FormatFloat(failure.time, 2) + "s " + failure.entity + ": " + + failure.message + " (" + std::to_string(failureCounts.at(key)) + "x)"); + } + + return lines; + + } + + void Tracker::Record(Scene::Scene& scene, float time) { + + for (auto entity : FindTopmostEntities(scene, spec.entities)) { + auto bounds = GetEntityBounds(entity); + samples[GetEntityLabel(entity)].push_back({ time, GetEntityPosition(entity), glm::degrees(GetEntityYaw(entity)), bounds.min.y }); + } + + } + + json Tracker::GetTrace() const { + + json j; + j["interval"] = spec.interval; + + json summary = json::object(); + json entities = json::object(); + for (const auto& [label, list] : samples) { + json entitySamples = json::array(); + float travelled = 0.0f; + float minY = std::numeric_limits::max(), maxY = -std::numeric_limits::max(); + for (size_t i = 0; i < list.size(); i++) { + const auto& sample = list[i]; + entitySamples.push_back({ { "t", Round(sample.time) }, { "position", FromVec3(sample.position) }, + { "yaw", Round(sample.yaw, 1) }, { "bottomY", Round(sample.minY) } }); + if (i > 0) + travelled += glm::distance(sample.position, list[i - 1].position); + minY = std::min(minY, sample.position.y); + maxY = std::max(maxY, sample.position.y); + } + entities[label] = entitySamples; + + if (!list.empty()) + summary[label] = { { "start", FromVec3(list.front().position) }, { "end", FromVec3(list.back().position) }, + { "distanceTravelled", travelled }, { "minY", minY }, { "maxY", maxY }, + { "firstSeen", list.front().time }, { "lastSeen", list.back().time } }; + } + + j["summary"] = summary; + j["entities"] = entities; + + return j; + + } + + json EvaluateExpectation(Scene::Scene& scene, const json& expectation, bool& passed) { + + json result; + result["expect"] = expectation; + passed = false; + + auto entityPattern = expectation.at("entity").get(); + auto property = expectation.at("property").get(); + auto entities = FindTopmostEntities(scene, entityPattern); + + if (property == "count") { + auto op = expectation.value("op", std::string("==")); + auto expected = expectation.at("value").get(); + passed = Compare(float(entities.size()), op, expected, 0.5f); + result["actual"] = entities.size(); + return result; + } + + if (property == "exists") { + auto expected = expectation.value("value", true); + passed = entities.empty() != expected; + result["actual"] = !entities.empty(); + return result; + } + + if (entities.empty()) { + result["error"] = "No entity matches '" + entityPattern + "'"; + return result; + } + + auto op = expectation.value("op", std::string(">")); + auto expected = expectation.at("value").get(); + auto tolerance = expectation.value("tolerance", 0.01f); + + // All matching entities have to fulfill the expectation + passed = true; + json actualValues = json::object(); + for (auto entity : entities) { + auto position = GetEntityPosition(entity); + bool hasMesh = false; + auto bounds = GetEntityBounds(entity, &hasMesh); + + // Like the grounded check, skip entities whose hierarchy has no loaded mesh bounds + if (property == "gapToGround" && !hasMesh) + continue; + + float actual = 0.0f; + if (property == "position.x") + actual = position.x; + else if (property == "position.y") + actual = position.y; + else if (property == "position.z") + actual = position.z; + else if (property == "bottom.y") + actual = bounds.min.y; + else if (property == "top.y") + actual = bounds.max.y; + else if (property == "yaw") + actual = glm::degrees(GetEntityYaw(entity)); + else if (property == "distanceTo") { + actual = glm::distance(position, ToVec3(expectation.at("point"))); + } + else if (property == "gapToGround") { + auto ground = GroundBelowEntity(scene, entity).ground; + actual = ground.valid ? bounds.min.y - ground.position.y : std::numeric_limits::infinity(); + } + else { + throw std::runtime_error("Unknown expectation property '" + property + + "' (count, exists, position.x/y/z, bottom.y, top.y, yaw, distanceTo, gapToGround)"); + } + + actualValues[GetEntityLabel(entity)] = actual; + passed &= Compare(actual, op, expected, tolerance); + } + + result["actual"] = actualValues; + return result; + + } + +} diff --git a/src/bridge/Checks.h b/src/bridge/Checks.h new file mode 100644 index 000000000..70eb89967 --- /dev/null +++ b/src/bridge/Checks.h @@ -0,0 +1,87 @@ +#pragma once + +#include "Job.h" +#include "SceneTools.h" + +#include +#include + +namespace Atlas::Bridge { + + struct Failure { + + std::string check; + std::string entity; + float time = 0.0f; + std::string message; + + }; + + // Runs the plausibility checks of a job, either once (static) or repeatedly while playing + class CheckRunner { + + public: + explicit CheckRunner(const ChecksSpec& spec) : spec(spec) {} + + void Run(Scene::Scene& scene, float time); + + void AddFailure(const Failure& failure); + + bool HasFailures() const { return !failures.empty(); } + + json GetReport() const; + + std::vector GetSummary() const; + + const ChecksSpec spec; + + private: + void CheckGrounded(Scene::Scene& scene, float time); + + void CheckPenetration(Scene::Scene& scene, float time); + + void CheckInvalidTransforms(Scene::Scene& scene, float time); + + std::vector failures; + // Only the first failure per check and entity is kept in detail, the rest is counted + std::map failureCounts; + std::map runCounts; + + std::map, int32_t> baselineIntrusions; + + std::optional groundedIgnored; + + }; + + // Records positions of entities over time + class Tracker { + + public: + explicit Tracker(const TrackSpec& spec) : spec(spec) {} + + void Record(Scene::Scene& scene, float time); + + json GetTrace() const; + + struct Sample { + + float time; + vec3 position; + float yaw; + float minY; + + }; + + const std::map>& GetSamples() const { return samples; } + + const TrackSpec spec; + + private: + std::map> samples; + + }; + + // Evaluates a timeline expectation, e.g. { "entity": "Crate", "property": "position.y", "op": ">", "value": 0 } + json EvaluateExpectation(Scene::Scene& scene, const json& expectation, bool& passed); + +} diff --git a/src/bridge/Client.cpp b/src/bridge/Client.cpp new file mode 100644 index 000000000..dba29084a --- /dev/null +++ b/src/bridge/Client.cpp @@ -0,0 +1,495 @@ +#include "Client.h" +#include "Check.h" +#include "LuaJob.h" +#include "Processes.h" +#include "Summary.h" + +#include "InstanceRegistry.h" + +#include +#include +#include + +namespace Atlas::Bridge { + + struct ClientOptions { + + fs::path server; + bool detach = false; + float timeout = 540.0f; + bool waitGpu = true; + // Options of the server process itself, a server started with others is restarted + std::vector serverOptions; + // The command and its arguments, job options are passed on to the job + std::vector arguments; + + }; + + static void Sleep(int32_t milliseconds) { + + std::this_thread::sleep_for(std::chrono::milliseconds(milliseconds)); + + } + + static int64_t Now() { + + return std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count(); + + } + + static json ReadJson(const fs::path& path) { + + std::ifstream stream(path); + if (!stream.is_open()) + return json(); + auto j = json::parse(stream, nullptr, false, true); + return j.is_discarded() ? json() : j; + + } + + static fs::path GetDefaultServerDirectory() { + + auto executable = GetExecutablePath(); + return (executable.parent_path() / ".." / "bridge-server" / executable.stem()).lexically_normal(); + + } + + static std::string GetLogTail(const fs::path& path, size_t lines) { + + std::ifstream stream(path); + std::vector all; + for (std::string line; std::getline(stream, line);) + all.push_back(line); + + std::string tail; + for (size_t i = all.size() > lines ? all.size() - lines : 0; i < all.size(); i++) + tail += "\n " + all[i]; + return tail; + + } + + // server.json of a server whose process still runs + static std::optional ReadServer(const fs::path& directory) { + + auto status = ReadJson(directory / "server.json"); + if (!status.is_object() || !IsProcessRunning(status.value("pid", uint32_t(0)))) + return std::nullopt; + return status; + + } + + static bool IsCurrentServer(const json& status, const ClientOptions& options) { + + std::error_code error; + auto executable = GetExecutablePath(); + auto build = fs::last_write_time(executable, error).time_since_epoch().count(); + return fs::path(status.value("executable", std::string())) == executable && status.value("build", int64_t(0)) == build && + status.value("options", std::vector()) == options.serverOptions; + + } + + static std::string WriteCommand(const fs::path& directory, const json& command, const std::string& name) { + + auto milliseconds = std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count(); + auto file = std::to_string(milliseconds) + "_" + std::to_string(CurrentProcessId()) + "_" + SanitizeFileName(name); + WriteFileAtomic(directory / (file + ".json"), command.dump(2)); + return file; + + } + + static bool WaitForExit(uint32_t processId, float timeoutSeconds) { + + auto start = std::chrono::steady_clock::now(); + while (IsProcessRunning(processId)) { + if (SecondsSince(start) > timeoutSeconds) + return false; + Sleep(200); + } + return true; + + } + + static void StopServer(const fs::path& directory, const json& status) { + + auto processId = status.value("pid", uint32_t(0)); + if (status.value("state", std::string()) != "idle") + WriteFileAtomic(directory / "cancel", ""); + WriteCommand(directory, { { "command", "stop" } }, "stop"); + if (!WaitForExit(processId, 60.0f)) { + Print("The server didn't stop within 60 s, ending it"); + KillProcessTree(processId); + } + + } + + // Starts a server or uses the running one, which has to be of this build and have the same options + static std::optional GetServer(const ClientOptions& options) { + + const auto& directory = options.server; + auto status = ReadServer(directory); + if (status && !IsCurrentServer(*status, options)) { + auto start = std::chrono::steady_clock::now(); + if (status->value("state", std::string()) != "idle") + Print("The server of " + directory.string() + " runs another build or other options and is busy with " + + status->value("job", std::string("a command")) + ", waiting for it"); + while (status && status->value("state", std::string()) != "idle" && SecondsSince(start) < options.timeout) { + Sleep(500); + status = ReadServer(directory); + } + if (status && status->value("state", std::string()) != "idle") { + Print("The server is still busy, try again later or stop it with: AtlasBridge stop"); + return std::nullopt; + } + if (status) { + Print("Restarting the server, it runs another build or other options"); + StopServer(directory, *status); + } + status.reset(); + } + if (status) + return status; + + std::error_code error; + fs::create_directories(directory, error); + fs::remove(directory / "server.json", error); + auto log = directory / "server.log"; + if (fs::exists(log, error)) + fs::rename(log, directory / "server.previous.log", error); + + std::vector serverArgs = { "--serve", directory.string() }; + serverArgs.insert(serverArgs.end(), options.serverOptions.begin(), options.serverOptions.end()); + auto executable = GetExecutablePath(); + auto processId = StartDetachedProcess(executable, serverArgs, executable.parent_path(), log); + if (processId == 0) { + Print("Couldn't start a server with " + executable.string()); + return std::nullopt; + } + + auto start = std::chrono::steady_clock::now(); + while (true) { + status = ReadServer(directory); + if (status && status->value("pid", uint32_t(0)) == processId) + break; + if (!IsProcessRunning(processId) || SecondsSince(start) > 120.0f) { + Print("The server didn't start, its log:" + GetLogTail(log, 15)); + return std::nullopt; + } + Sleep(200); + } + Print("Started a server (process " + std::to_string(processId) + ") in " + directory.string()); + return status; + + } + + static int32_t PrintResult(const json& result, bool valuesOnly) { + + if (!result.contains("report")) { + Print(result.value("command", std::string("command")) + ": " + result.value("status", std::string("error")) + + (result.contains("reason") && !result["reason"].get().empty() ? ": " + result["reason"].get() : "")); + return result.value("status", std::string()) == "ok" ? 0 : 2; + } + + auto report = ReadJson(result["report"].get()); + if (!report.is_object()) { + Print("The report " + result["report"].get() + " is missing: " + result.value("reason", std::string())); + return 2; + } + + auto exitCode = report.value("exitCode", 2); + if (valuesOnly && exitCode == 0 && report.contains("results")) { + for (const auto& [key, value] : report["results"].items()) + Print(key == "value" ? value.dump() : key + " = " + value.dump()); + return 0; + } + + for (const auto& line : FormatSummary(report, fs::path(result.value("outputDirectory", std::string())))) + Print(line); + return exitCode; + + } + + static int32_t WaitForCommand(const ClientOptions& options, const std::string& command, bool valuesOnly) { + + auto path = options.server / (command + ".result.json"); + auto start = std::chrono::steady_clock::now(); + bool printedGpuWait = false; + while (!fs::exists(path)) { + auto status = ReadServer(options.server); + if (!status && !fs::exists(path)) { + Print("The server ended before " + command + " was done, its log:" + GetLogTail(options.server / "server.log", 20)); + return 3; + } + if (status && !printedGpuWait && status->value("state", std::string()) == "waiting for the GPU" && + status->value("command", std::string()) == command) { + Print("The server waits for the GPU before it loads " + status->value("scene", std::string()) + ", status shows for whom"); + printedGpuWait = true; + } + if (options.timeout > 0.0f && SecondsSince(start) > options.timeout) { + Print(command + " still runs after " + FormatFloat(options.timeout, 0) + " s, wait for it with: AtlasBridge wait " + + command + (options.server == GetDefaultServerDirectory() ? "" : " --server " + options.server.string())); + return 4; + } + Sleep(200); + } + + // The result is written atomically + return PrintResult(ReadJson(path), valuesOnly); + + } + + static int32_t SendCommand(const ClientOptions& options, const json& command, const std::string& name, bool valuesOnly = false) { + + auto server = GetServer(options); + if (!server) + return 2; + + // The server waits for the GPU itself before it loads a scene + auto serverProcess = server->value("pid", uint32_t(0)); + if (!options.waitGpu) { + for (const auto& instance : InstanceRegistry::GetInstances()) + if (instance.busy && instance.pid != serverProcess && instance.pid != CurrentProcessId()) + Print("Note: " + instance.executable + " (process " + std::to_string(instance.pid) + ") is busy: " + instance.activity); + } + + auto file = WriteCommand(options.server, command, name); + if (options.detach) { + Print("Sent " + file + ", wait for it with: AtlasBridge wait " + file); + return 0; + } + + return WaitForCommand(options, file, valuesOnly); + + } + + static int32_t Run(ClientOptions& options) { + + if (options.arguments.size() < 2) + throw std::runtime_error("run expects a job file or an inline job"); + + const auto& jobArgument = options.arguments[1]; + std::vector jobOptions(options.arguments.begin() + 2, options.arguments.end()); + if (!options.waitGpu) + jobOptions.push_back("--no-wait-gpu"); + + json command = { { "command", "run" }, { "args", jobOptions } }; + std::string name; + if (jobArgument.starts_with("{")) { + auto inlineJob = json::parse(jobArgument, nullptr, false, true); + if (!inlineJob.is_object()) + throw std::runtime_error("The inline job isn't a JSON object"); + command["job"] = inlineJob; + name = inlineJob.value("name", std::string("inline")); + } + else { + auto path = ResolveUserPath(jobArgument); + // Mistakes in the job are found without the server + auto issues = CheckJobFile(path, jobOptions); + if (!issues.empty() && issues.front().starts_with("ERROR")) { + for (const auto& issue : issues) + Print(issue); + return 2; + } + for (const auto& issue : issues) + Print(issue); + command["job"] = path.generic_string(); + name = path.stem().string(); + } + + return SendCommand(options, command, name); + + } + + static int32_t Eval(ClientOptions& options) { + + if (options.arguments.size() < 2) + throw std::runtime_error("eval expects Lua code"); + + float play = 0.05f; + std::string scene; + auto& arguments = options.arguments; + for (size_t i = 2; i < arguments.size(); i++) { + if (arguments[i] == "--play" && i + 1 < arguments.size()) + play = std::max(std::stof(arguments[++i]), 0.05f); + else if (arguments[i] == "--scene" && i + 1 < arguments.size()) + scene = arguments[++i]; + else + throw std::runtime_error("Unknown eval option '" + arguments[i] + "' (--play , --scene )"); + } + + auto error = LuaJob::Compile(arguments[1], "eval", true); + if (!error.empty()) { + Print("ERROR: " + error); + return 2; + } + + json job = { + { "name", "eval" }, { "play", true }, { "duration", play }, { "shots", json::array() }, { "realTime", false }, + { "timeline", json::array({ { { "t", play }, { "lua", arguments[1] }, { "result", "value" } } }) } + }; + if (!scene.empty()) + job["scene"] = scene; + if (!options.waitGpu) + job["waitGpu"] = false; + + return SendCommand(options, { { "command", "run" }, { "job", job } }, "eval", true); + + } + + static int32_t Status(const ClientOptions& options) { + + auto status = ReadServer(options.server); + if (!status) { + Print("No server runs in " + options.server.string()); + } + else { + auto since = Now() - status->value("since", Now()); + auto state = status->value("state", std::string()); + Print("Server (process " + std::to_string(status->value("pid", 0)) + ") in " + options.server.string() + ": " + state + + (state == "running" ? " " + status->value("job", std::string()) : "") + " for " + std::to_string(since) + " s" + + (status->value("scene", std::string()).empty() ? "" : ", scene " + status->value("scene", std::string())) + + (IsCurrentServer(*status, options) ? "" : ", another build")); + } + PrintInstances(); + return 0; + + } + + std::optional RunClient(const std::vector& args) { + + static const std::vector commands = { "run", "eval", "wait", "status", "cancel", "stop" }; + if (args.size() < 2 || std::find(commands.begin(), commands.end(), args[1]) == commands.end()) + return std::nullopt; + + ClientOptions options; + options.server = GetDefaultServerDirectory(); + for (size_t i = 1; i < args.size(); i++) { + const auto& arg = args[i]; + if (arg == "--server" && i + 1 < args.size()) + options.server = ResolveUserPath(args[++i]); + else if (arg == "--detach") + options.detach = true; + else if (arg == "--timeout" && i + 1 < args.size()) + options.timeout = std::stof(args[++i]); + else if (arg == "--no-wait-gpu") + options.waitGpu = false; + else if (arg == "--wait-gpu") { + // The default, accepted for older command lines + } + else if (arg == "--streaming" || arg == "--validation") + options.serverOptions.push_back(arg); + else + options.arguments.push_back(arg); + } + + const auto& command = options.arguments.front(); + try { + if (command == "run") + return Run(options); + if (command == "eval") + return Eval(options); + if (command == "status") + return Status(options); + if (command == "wait") { + if (options.arguments.size() < 2) + throw std::runtime_error("wait expects the name of a command"); + return WaitForCommand(options, options.arguments[1], false); + } + + auto status = ReadServer(options.server); + if (!status) { + Print("No server runs in " + options.server.string()); + return 0; + } + if (command == "cancel") { + WriteFileAtomic(options.server / "cancel", ""); + Print("Asked the server to cancel " + status->value("job", std::string("its job"))); + return 0; + } + StopServer(options.server, *status); + Print("Stopped the server"); + return 0; + } + catch (const std::exception& e) { + Print(std::string("ERROR: ") + e.what()); + return 2; + } + + } + + void PrintInstances() { + + auto all = InstanceRegistry::GetInstances(); + auto instances = all; + std::erase_if(instances, [](const auto& instance) { return instance.pid == CurrentProcessId(); }); + if (instances.empty()) { + Print("No other engine application runs"); + return; + } + + auto now = Now(); + Print("Engine applications:"); + for (const auto& instance : instances) { + std::string arguments; + for (const auto& arg : instance.args) + arguments += " " + arg; + if (arguments.size() > 100) + arguments = arguments.substr(0, 97) + "..."; + std::string waitsFor; + if (instance.waitingSince) + for (const auto& other : InstanceRegistry::GetInstancesAhead(instance, all)) + waitsFor += (waitsFor.empty() ? ", waits for " : ", ") + std::to_string(other.pid); + Print(" " + std::to_string(instance.pid) + " " + instance.executable + (instance.busy ? " [busy] " : " ") + instance.activity + + waitsFor + ", running " + std::to_string((now - instance.started) / 60) + " min" + + (instance.expectedEnd ? ", expected end in " + std::to_string(std::max(*instance.expectedEnd - now, int64_t(0))) + " s" : "") + + " |" + arguments); + } + + } + + bool WaitForGpu(float timeoutSeconds) { + + auto start = std::chrono::steady_clock::now(); + bool printed = false; + while (true) { + auto busy = InstanceRegistry::GetBusyInstances(); + if (busy.empty()) + return true; + + if (!printed) { + for (const auto& instance : busy) + Print("Waiting for " + instance.executable + " (process " + std::to_string(instance.pid) + "): " + instance.activity); + printed = true; + } + if (timeoutSeconds > 0.0f && SecondsSince(start) > timeoutSeconds) { + Print("The GPU is still busy after " + FormatFloat(timeoutSeconds, 0) + " s"); + return false; + } + Sleep(1000); + } + + } + + int32_t Kill(const std::string& target) { + + std::vector processes; + if (target == "captures") { + for (const auto& instance : InstanceRegistry::GetInstances()) + if (instance.pid != CurrentProcessId() && instance.executable.starts_with("AtlasBridge")) + processes.push_back(instance.pid); + } + else { + processes.push_back(uint32_t(std::stoul(target))); + } + + for (auto processId : processes) { + auto killed = KillProcessTree(processId); + Print("Ended process " + std::to_string(processId) + (killed.size() > 1 ? " and " + std::to_string(killed.size() - 1) + + " processes it started" : killed.empty() ? " (it didn't run)" : "")); + } + if (processes.empty()) + Print("No other bridge runs"); + return 0; + + } + +} diff --git a/src/bridge/Client.h b/src/bridge/Client.h new file mode 100644 index 000000000..7a131d049 --- /dev/null +++ b/src/bridge/Client.h @@ -0,0 +1,27 @@ +#pragma once + +#include "Common.h" + +#include + +namespace Atlas::Bridge { + + // The client of the server mode: starts a server or uses the running one, keeps its scene loaded between runs, + // sends a command, waits for it and prints the summary of the job. + // run [job options] eval [--play ] [--scene ] + // wait status cancel stop + // Common options: --server (default bin/bridge-server/), --detach (return right away), + // --timeout (stop waiting, default 540), --no-wait-gpu (the server loads without waiting for the GPU) + std::optional RunClient(const std::vector& args); + + // Prints the engine applications that run on this machine, what they do and whom they wait for, see InstanceRegistry + void PrintInstances(); + + // Waits until no other engine application keeps the GPU busy, without a place in the queue of InstanceRegistry. + // Returns false after the timeout + bool WaitForGpu(float timeoutSeconds); + + // Ends a process with its children, "captures" ends all other bridges + int32_t Kill(const std::string& target); + +} diff --git a/src/bridge/Common.cpp b/src/bridge/Common.cpp new file mode 100644 index 000000000..5fb513026 --- /dev/null +++ b/src/bridge/Common.cpp @@ -0,0 +1,233 @@ +#include "Common.h" + +#include "loader/AssetLoader.h" + +#include +#include +#include +#include +#include + +namespace Atlas::Bridge { + + // Runs before main(), which changes the working directory to the executable directory + static const fs::path launchDirectory = fs::current_path(); + + const fs::path& GetLaunchDirectory() { + + return launchDirectory; + + } + + fs::path GetAssetDirectory() { + + return fs::weakly_canonical(Loader::AssetLoader::GetDataDirectory()); + + } + + fs::path ResolveUserPath(const std::string& path) { + + fs::path userPath(path); + if (userPath.is_absolute()) + return userPath.lexically_normal(); + + return (launchDirectory / userPath).lexically_normal(); + + } + + std::string ToAssetPath(const std::string& path) { + + auto assetDirectory = GetAssetDirectory(); + + // Prefer paths that exist relative to the launch directory (e.g. data/scenes/x.aescene) + auto userPath = ResolveUserPath(path); + if (fs::exists(userPath)) { + auto relative = fs::weakly_canonical(userPath).lexically_relative(assetDirectory); + if (!relative.empty() && relative.native()[0] != '.') + return relative.generic_string(); + // Outside of the asset directory, the engine accepts absolute paths + return fs::weakly_canonical(userPath).generic_string(); + } + + auto generic = fs::path(path).generic_string(); + if (generic.starts_with("data/")) + generic = generic.substr(5); + + return generic; + + } + + bool MatchAnyPattern(const std::vector& patterns, const std::string& text) { + + for (const auto& pattern : patterns) + if (Helper::String::MatchWildcard(pattern, text)) + return true; + + return false; + + } + + vec3 ToVec3(const json& j, vec3 defaultValue) { + + if (j.is_array() && j.size() == 3) + return vec3(j[0].get(), j[1].get(), j[2].get()); + if (j.is_number()) + return vec3(j.get()); + + return defaultValue; + + } + + vec2 ToVec2(const json& j) { + + return vec2(j.at(0).get(), j.at(j.size() == 3 ? 2 : 1).get()); + + } + + json FromVec3(vec3 v) { + + return json::array({ Round(v.x, 4), Round(v.y, 4), Round(v.z, 4) }); + + } + + double Round(double value, int32_t decimals) { + + auto scale = std::pow(10.0, double(decimals)); + return std::round(value * scale) / scale; + + } + + vec3 GetDirection(float azimuth, float elevation) { + + auto az = glm::radians(azimuth), el = glm::radians(elevation); + return vec3(std::cos(el) * std::sin(az), std::sin(el), std::cos(el) * std::cos(az)); + + } + + std::string FormatFloat(float value, int32_t precision) { + + std::ostringstream stream; + stream << std::fixed << std::setprecision(precision) << value; + return stream.str(); + + } + + float SecondsSince(std::chrono::steady_clock::time_point start) { + + return std::chrono::duration(std::chrono::steady_clock::now() - start).count(); + + } + + std::string FormatVec3(vec3 v, int32_t precision) { + + return "(" + FormatFloat(v.x, precision) + ", " + FormatFloat(v.y, precision) + ", " + + FormatFloat(v.z, precision) + ")"; + + } + + std::string FormatTime(float time) { + + return "t=" + FormatFloat(time, 2) + "s"; + + } + + std::string SanitizeFileName(const std::string& name) { + + std::string result; + for (auto c : name) { + if (std::isalnum(uint8_t(c)) || c == '-' || c == '_' || c == '.') + result.push_back(c); + else + result.push_back('_'); + } + + return result.empty() ? "unnamed" : result; + + } + + bool IsLocalHost(std::string authority) { + + if (authority.starts_with("[")) + authority = authority.substr(1, authority.find(']') - 1); + else + authority = authority.substr(0, authority.find(':')); + return authority == "localhost" || authority == "127.0.0.1" || authority == "::1"; + + } + + bool IsLocalOrigin(const std::string& origin) { + + auto scheme = origin.find("://"); + return origin.empty() || (scheme != std::string::npos && IsLocalHost(origin.substr(scheme + 3))); + + } + + bool WriteFileAtomic(const fs::path& path, const std::string& content) { + + auto temporary = path; + temporary += ".tmp"; + { + std::ofstream stream(temporary, std::ios::binary); + if (!stream.is_open()) + return false; + stream << content; + } + + std::error_code error; + fs::rename(temporary, path, error); + return !error; + + } + + void Print(const std::string& line) { + + std::printf("%s\n", line.c_str()); + std::fflush(stdout); + + } + + void CheckKeys(const json& j, const std::set& allowed, const std::string& context) { + + if (!j.is_object()) + throw std::runtime_error(context + " must be a JSON object"); + + for (auto& [key, value] : j.items()) { + if (allowed.contains(key)) + continue; + std::string names; + for (const auto& name : allowed) + names += (names.empty() ? "" : ", ") + name; + throw std::runtime_error("Unknown key '" + key + "' in " + context + " (" + names + ")"); + } + + } + + std::vector ToAssetPatterns(const json& j) { + + std::vector patterns; + for (const auto& pattern : j.is_array() ? j : json::array({ j })) + patterns.push_back(ToAssetPath(pattern.get())); + return patterns; + + } + + std::vector FindAssetFiles(const json& patterns, const std::string& extension) { + + std::vector paths; + for (const auto& pattern : ToAssetPatterns(patterns)) { + auto directory = fs::path(pattern).parent_path(); + if (!fs::is_directory(GetAssetDirectory() / directory)) + throw std::runtime_error("No directory " + directory.generic_string() + " for " + pattern); + for (const auto& file : fs::directory_iterator(GetAssetDirectory() / directory)) { + auto path = (directory / file.path().filename()).generic_string(); + if (file.is_regular_file() && file.path().extension() == extension && Helper::String::MatchWildcard(pattern, path)) + paths.push_back(path); + } + } + std::sort(paths.begin(), paths.end()); + paths.erase(std::unique(paths.begin(), paths.end()), paths.end()); + return paths; + + } + +} diff --git a/src/bridge/Common.h b/src/bridge/Common.h new file mode 100644 index 000000000..6732d9869 --- /dev/null +++ b/src/bridge/Common.h @@ -0,0 +1,83 @@ +#pragma once + +#include "System.h" +#include "common/SerializationHelper.h" +#include "common/StringHelper.h" + +#include +#include +#include +#include +#include + +namespace Atlas::Bridge { + + namespace fs = std::filesystem; + + using glm::u8vec4; + using glm::uvec4; + + // Directory the tool was launched from. The engine main changes the working directory + // to the executable directory, so this is captured during static initialization + const fs::path& GetLaunchDirectory(); + + // Absolute path of the engine's filesystem data directory + fs::path GetAssetDirectory(); + + // Resolves a user supplied path relative to the launch directory + fs::path ResolveUserPath(const std::string& path); + + // Converts a user supplied scene path into a path relative to the asset directory, + // e.g. "data/scenes/Kingdom.aescene" or "scenes/Kingdom.aescene" -> "scenes/Kingdom.aescene" + std::string ToAssetPath(const std::string& path); + + // Wildcard match against any of the patterns, see Helper::String::MatchWildcard + bool MatchAnyPattern(const std::vector& patterns, const std::string& text); + + vec3 ToVec3(const json& j, vec3 defaultValue = vec3(0.0f)); + + // Horizontal position from [x, z] or [x, y, z] + vec2 ToVec2(const json& j); + + json FromVec3(vec3 v); + + // Rounds to a number of decimals to keep the JSON output readable + double Round(double value, int32_t decimals = 3); + + // Unit vector for angles in degrees, azimuth 0 points towards +Z and 90 towards +X + vec3 GetDirection(float azimuth, float elevation); + + std::string FormatFloat(float value, int32_t precision = 3); + + float SecondsSince(std::chrono::steady_clock::time_point start); + + std::string FormatVec3(vec3 v, int32_t precision = 3); + + // Time of a timeline, e.g. "t=1.50s" + std::string FormatTime(float time); + + std::string SanitizeFileName(const std::string& name); + + // Writes next to the target, then renames, a failed rename leaves the target unchanged + bool WriteFileAtomic(const fs::path& path, const std::string& content); + + // A line on the console, flushed so clients and logs see it right away + void Print(const std::string& line); + + // Whether the host of a Host header ("localhost:7777", "[::1]:80") is this machine + bool IsLocalHost(std::string authority); + + // Web pages send an Origin, local servers only take requests without one or from local pages + bool IsLocalOrigin(const std::string& origin); + + // Typos in job files would otherwise be silently ignored + void CheckKeys(const json& j, const std::set& allowed, const std::string& context); + + // A pattern or a list of patterns of asset paths + std::vector ToAssetPatterns(const json& j); + + // Files with the extension matching the patterns, e.g. "models/animations/Horse_*.aeanimation", sorted and unique. + // Wildcards are only allowed in the file names + std::vector FindAssetFiles(const json& patterns, const std::string& extension); + +} diff --git a/src/bridge/HostedJob.cpp b/src/bridge/HostedJob.cpp new file mode 100644 index 000000000..4b0906e55 --- /dev/null +++ b/src/bridge/HostedJob.cpp @@ -0,0 +1,364 @@ +#include "HostedJob.h" +#include "SceneTools.h" +#include "Summary.h" +#include "Processes.h" + +#include "InstanceRegistry.h" + +#include + +#include +#include + +namespace Atlas::Bridge { + + std::unique_ptr HostedJob::FromArguments(const std::vector& args, const std::string& scenePath) { + + auto option = std::find(args.begin(), args.end(), "--bridge"); + if (option == args.end() || option + 1 == args.end()) + return nullptr; + + // The scene is the one of the game, the other options of the game aren't options of the job besides the GPU wait + std::vector jobArgs = { args.front(), "--scene", scenePath }; + for (size_t i = 1; i < args.size(); i++) { + if (args[i] == "--no-wait-gpu") + jobArgs.push_back(args[i]); + else if (args[i] == "--gpu-wait-timeout" && i + 1 < args.size()) + jobArgs.insert(jobArgs.end(), { args[i], args[i + 1] }); + } + jobArgs.push_back(*(option + 1)); + + auto hosted = std::make_unique(); + auto& job = hosted->job; + job = ParseCommandLine(jobArgs); + + auto unsupported = [](const std::string& what) { + + throw std::runtime_error(what + " needs the renderer of the bridge, a job in a game plays the game with its camera"); + + }; + if (!job.play) + throw std::runtime_error("A job in a game plays it: set play and duration"); + if (job.edit) + unsupported("edit"); + if (!job.shots.empty()) + unsupported("shots"); + if (!job.variants.empty()) + unsupported("variants"); + if (job.observer) + unsupported("observer"); + if (job.inspect) + unsupported("inspect"); + for (const auto& strip : job.strips) + if (strip.hasCamera) + unsupported("A strip with a camera"); + for (const auto& event : job.timeline) { + if (auto capture = std::get_if(&event.action); capture && (capture->camera || capture->still || !capture->crop.is_null())) + unsupported("A capture with a camera, still or crop"); + if (std::holds_alternative(event.action)) + unsupported("resetScripts"); + } + + auto& report = hosted->report; + report.Reset(job); + report.showWindow = false; + if (auto error = report.Begin(); !error.empty()) + throw std::runtime_error(error); + hosted->startTime = std::chrono::steady_clock::now(); + + // Jobs in a window without vsync never start the game like a player does, each build has to pass one that does. + // The report of a refused job replaces the outputs of its previous run + if (!job.playerDisplay) { + std::ifstream record(GetPlayerDisplayRecordPath()); + int64_t passed = 0; + auto build = GetBuildStamp(); + std::string error; + if (build == 0) + error = "The build time of the game can't be read, so jobs in a window can't run"; + else if (!(record >> passed) || passed != build) + error = "This build of the game hasn't passed a job with \"playerDisplay\": true yet. It starts the game " + "with the display settings of a player (fullscreen, vsync); run one before the other jobs"; + if (!error.empty()) { + hosted->fatal = true; + report.Error(error); + hosted->Finish(); + throw std::runtime_error(error); + } + } + + report.Print("Job '" + job.name + "' in the game, it starts with the game" + (report.previousSeconds > 0.0f ? + ", the previous run took " + FormatFloat(report.previousSeconds, 0) + " s" : "")); + // The game loads its world after this, scenes of other engine applications would leave too little GPU memory. + // Its window exists already and has to handle its messages meanwhile + if (job.waitGpu) { + InstanceRegistry::QueueForGpu("waiting for the GPU to start job " + job.name); + auto waitStart = std::chrono::steady_clock::now(); + auto nextPrint = waitStart; + std::string waitingFor; + std::vector ahead; + while (!InstanceRegistry::PollGpu(ahead)) { + auto seconds = SecondsSince(waitStart); + auto reason = InstanceRegistry::Describe(ahead); + if (!reason.empty() && (reason != waitingFor || std::chrono::steady_clock::now() >= nextPrint)) { + report.Print("Waiting for the GPU (" + FormatFloat(seconds, 0) + " s): " + reason); + nextPrint = std::chrono::steady_clock::now() + std::chrono::seconds(60); + waitingFor = reason; + } + if (seconds > job.gpuWaitTimeout) { + auto error = "The GPU is still busy after " + FormatFloat(seconds, 0) + " s (gpuWaitTimeout), waiting for " + waitingFor; + hosted->fatal = true; + report.Error(error); + hosted->Finish(); + throw std::runtime_error(error); + } + for (int32_t i = 0; i < 10; i++) { + SDL_PumpEvents(); + std::this_thread::sleep_for(std::chrono::milliseconds(50)); + } + } + // The wait doesn't count into the duration of the job + hosted->startTime += std::chrono::steady_clock::now() - waitStart; + } + InstanceRegistry::SetActivity("job " + job.name, true); + return hosted; + + } + + void HostedJob::Start(Scene::Scene& playedScene, sol::state* luaState, uint32_t windowId) { + + scene = &playedScene; + try { + if (!job.settings.empty()) + ApplySettings(*scene, job.settings, patchedMaterials); + + if (!job.queries.empty()) { + auto results = RunQueries(*scene, job.queries, job.outputDirectory); + report.WriteJson("queries.json", results); + for (const auto& result : results) + report.Print("Query " + result["query"].value("type", "") + " -> " + + (result.contains("error") ? result["error"].dump() : result["result"].dump()).substr(0, 300)); + } + if (job.lua) { + LuaJob lua; + lua.Start(luaState ? *luaState : scene->GetLuaState(), scene, report, []() { return 0.0f; }); + // Stopped also when the Lua fails + std::unique_ptr stop(&lua, [](LuaJob* job) { job->Stop(); }); + lua.Run(job.lua->code, job.lua->file.empty() ? "lua" : job.lua->file); + } + + checks = std::make_unique(job.checks); + if (job.track) + tracker = std::make_unique(*job.track); + + // Strips are live captures of the window + auto events = job.timeline; + for (const auto& strip : job.strips) { + auto group = SanitizeFileName(strip.name); + groups.emplace_back(group, strip.name); + auto count = int32_t(std::floor((strip.to - strip.from) / strip.every + 1e-3f)); + for (int32_t i = 0; i <= count; i++) { + auto time = strip.from + float(i) * strip.every; + CaptureEvent capture; + capture.file = group + "/" + FormatFloat(time, 2) + "s.png"; + capture.group = group; + events.push_back({ .time = time, .type = "capture", .action = capture }); + } + } + + player.Reset(job); + player.Start(job, *scene, std::move(events), report, luaState, windowId); + report.Print("Playing for " + FormatFloat(job.duration, 2) + "s in the game"); + } + catch (const std::exception& e) { + report.Error(e.what()); + fatal = true; + } + + } + + float HostedJob::BeginFrame(float deltaTime) { + + if (finished || !scene) + return deltaTime; + + try { + CollectLog(); + + // A capture is done once its file stopped growing + if (pending) { + std::error_code error; + auto size = fs::exists(pending->path, error) ? fs::file_size(pending->path, error) : 0; + if (size > 0 && size == pending->size) { + auto relative = fs::relative(pending->path, job.outputDirectory).generic_string(); + report.AddOutput(relative); + report.Print("Captured " + relative + " at " + FormatTime(player.timeline.time)); + if (auto image = LoadImageFile(pending->path)) { + auto small = Downscale(image, 640); + sheetImages.push_back(small); + sheetLabels.push_back(fs::path(relative).replace_extension().generic_string()); + if (!pending->group.empty()) { + groupImages[pending->group].first.push_back(small); + groupImages[pending->group].second.push_back(pending->label); + } + } + pending.reset(); + } + else if (pending) { + pending->size = size; + } + } + + if (!fatal && !stopping) { + player.Update([&](const EventSpec& event) { + + const auto& capture = std::get(event.action); + auto file = capture.file.value_or(SanitizeFileName(capture.name) + "_" + FormatFloat(player.timeline.time, 2) + "s.png"); + requested.push_back({ job.outputDirectory / file, capture.group, capture.label.value_or(FormatTime(event.time)) }); + fs::create_directories(requested.back().path.parent_path()); + return Player::EventResult::Done; + + }); + } + + auto done = fatal || stopping || player.timeline.IsFinished(job.duration); + if (done && requested.empty() && !pending) { + if (!fatal && !stopping) { + player.ReportMissedEvents(*checks); + checks->Run(*scene, player.timeline.time); + if (tracker) + tracker->Record(*scene, player.timeline.time); + } + Finish(); + return deltaTime; + } + } + catch (const std::exception& e) { + report.Error(e.what()); + fatal = true; + } + + return job.fixedDeltaTime; + + } + + void HostedJob::EndFrame() { + + if (finished || !scene || fatal || stopping) + return; + + auto& timeline = player.timeline; + timeline.time += job.fixedDeltaTime; + if (timeline.IsDue(nextCheckTime)) { + checks->Run(*scene, timeline.time); + nextCheckTime += job.checks.interval; + } + if (tracker && timeline.IsDue(nextTrackTime)) { + tracker->Record(*scene, timeline.time); + nextTrackTime += tracker->spec.interval; + } + + } + + std::optional HostedJob::TakeCapture() { + + if (finished || pending || requested.empty()) + return std::nullopt; + + pending = requested.front(); + requested.erase(requested.begin()); + return pending->path; + + } + + void HostedJob::CollectLog() { + + for (const auto& entry : report.CollectLog()) { + player.timeline.MatchLog(entry.message); + if (entry.type != Log::TYPE_ERROR || !checks || !job.checks.logErrors || MatchAnyPattern(job.checks.logIgnore, entry.message)) + continue; + + checks->AddFailure({ "log", entry.message.substr(0, 160), player.timeline.time, entry.message }); + if (job.checks.failFast && !stopping) { + report.Print("Stopping at the first error, checks.failFast = false runs to the end"); + stopping = true; + } + } + + } + + void HostedJob::Finish() { + + UpdatePipelinesOfMaterials(ReloadMaterials(patchedMaterials)); + patchedMaterials.clear(); + + for (const auto& [group, title] : groups) { + const auto& [images, labels] = groupImages[group]; + if (!images.empty() && WriteImage(ComposeSheet(images, labels, 0, title), job.outputDirectory / (group + ".png"))) + report.AddOutput(group + ".png"); + } + if (!sheetImages.empty()) { + auto columns = int32_t(std::ceil(std::sqrt(float(sheetImages.size())))); + auto cellWidth = std::max((1536 - 4 * (columns + 1)) / columns, 64); + if (WriteImage(ComposeSheet(sheetImages, sheetLabels, columns, job.name, cellWidth), job.outputDirectory / "sheet.jpg")) + report.AddOutput("sheet.jpg"); + } + if (tracker) + report.WriteJson("trace.json", tracker->GetTrace()); + + auto failedExpectations = std::count_if(report.expectations.begin(), report.expectations.end(), + [](const json& expectation) { return !expectation["passed"].get(); }); + report.exitCode = fatal ? 2 : (checks && checks->HasFailures()) || failedExpectations > 0 ? 1 : 0; + + if (auto build = GetBuildStamp(); job.playerDisplay && report.exitCode == 0 && build != 0) { + auto recordPath = GetPlayerDisplayRecordPath(); + std::error_code error; + fs::create_directories(recordPath.parent_path(), error); + std::ofstream(recordPath) << build; + } + + std::string status = report.exitCode == 0 ? "passed" : report.exitCode == 1 ? "failed" : "error"; + json result = { + { "job", job.name }, { "runId", report.runId }, { "scene", job.scene }, { "status", status }, { "exitCode", report.exitCode }, + { "host", true }, { "errors", report.errors }, { "warnings", report.warnings }, { "engineLogErrors", report.logErrorCount }, + { "totalSeconds", SecondsSince(startTime) }, { "playedSeconds", player.timeline.time } + }; + if (fatal) + result["reason"] = report.errors.empty() ? "unknown error" : report.errors.front(); + else if (report.exitCode == 1) + result["reason"] = std::to_string(checks ? checks->GetSummary().size() : 0) + " failed checks, " + + std::to_string(failedExpectations) + " failed expectations"; + if (checks) + result["checks"] = checks->GetReport(); + if (!report.expectations.empty()) + result["expectations"] = report.expectations; + if (!report.results.empty()) + result["results"] = report.results; + if (auto triggers = player.timeline.GetTriggerReport(); !triggers.is_null()) + result["conditionalEvents"] = triggers; + report.Write(result); + + for (const auto& line : FormatSummary(report.data, job.outputDirectory)) + report.Print(line); + report.End(); + player.Stop(); + finished = true; + + } + + fs::path HostedJob::GetPlayerDisplayRecordPath() { + + auto executable = GetExecutablePath(); + return executable.parent_path() / ".cache" / ("bridge-player-display-" + executable.stem().string() + ".txt"); + + } + + int64_t HostedJob::GetBuildStamp() { + + // 0 if the time can't be read, the error value would be the same for every build + std::error_code error; + auto time = fs::last_write_time(GetExecutablePath(), error); + return error ? 0 : int64_t(time.time_since_epoch().count()); + + } + +} diff --git a/src/bridge/HostedJob.h b/src/bridge/HostedJob.h new file mode 100644 index 000000000..251b08f7f --- /dev/null +++ b/src/bridge/HostedJob.h @@ -0,0 +1,93 @@ +#pragma once + +#include "Job.h" +#include "Player.h" +#include "Report.h" +#include "Checks.h" +#include "Image.h" + +#include +#include + +namespace Atlas::Bridge { + + // Runs a bridge job inside a game host: the game loads, updates and renders its scene with its interface, the job + // plays its timeline on it (keys, controller, mouse, Lua, expectations, conditions), runs its checks and captures the + // window with the interface. Jobs without shots, edits, variants and capture cameras run, see README.md. A host: + // job = HostedJob::FromArguments(args, scenePath) --bridge on the command line, nullptr without + // if (!job->KeepsPlayerDisplay()) before the window and swap chain are set up: keep the window + // and present without vsync, otherwise start like for a player + // job->Start(*scene, &luaState, windowId) once the game runs, e.g. after its script started + // deltaTime = job->BeginFrame(deltaTime) before the game update, returns the fixed time step of the job + // job->EndFrame() after the scene update + // if (auto path = job->TakeCapture()) save the window to the path, the job waits until the file is there + // if (job->IsFinished()) Exit(job->GetExitCode()) + class HostedJob { + + public: + // Throws std::runtime_error for jobs that need the renderer of the bridge, and for jobs with the test display + // until a job with the display of the player passed on this build of the game + static std::unique_ptr FromArguments(const std::vector& args, const std::string& scenePath); + + bool KeepsPlayerDisplay() const { return job.playerDisplay; } + + void Start(Scene::Scene& scene, sol::state* luaState, uint32_t windowId); + + bool IsStarted() const { return scene != nullptr; } + + float BeginFrame(float deltaTime); + + void EndFrame(); + + std::optional TakeCapture(); + + bool IsFinished() const { return finished; } + + int32_t GetExitCode() const { return report.exitCode; } + + private: + struct Capture { + + fs::path path; + std::string group; + std::string label; + uintmax_t size = 0; + + }; + + void CollectLog(); + + void Finish(); + + // Records the build of the game a job with the display of the player passed on + static fs::path GetPlayerDisplayRecordPath(); + + static int64_t GetBuildStamp(); + + Job job; + Report report; + Player player; + std::unique_ptr checks; + std::unique_ptr tracker; + Scene::Scene* scene = nullptr; + // Materials the settings patched in memory, they go back to their files when the job finishes + std::set patchedMaterials; + + std::vector requested; + std::optional pending; + std::vector> groups; + std::vector> sheetImages; + std::vector sheetLabels; + std::map>, std::vector>> groupImages; + + float nextCheckTime = 0.0f; + float nextTrackTime = 0.0f; + bool fatal = false; + // The first error ended the job, it finishes once its captures are written + bool stopping = false; + bool finished = false; + std::chrono::steady_clock::time_point startTime; + + }; + +} diff --git a/src/bridge/Image.cpp b/src/bridge/Image.cpp new file mode 100644 index 000000000..fcc31dca3 --- /dev/null +++ b/src/bridge/Image.cpp @@ -0,0 +1,247 @@ +#include "Image.h" + +#include "loader/ImageLoader.h" + +#include + +#include +#include +#include + +namespace Atlas::Bridge { + + struct FontData { + + std::vector data; + stbtt_fontinfo info; + bool valid = false; + + }; + + static FontData& GetFont() { + + static FontData font; + static std::once_flag flag; + + std::call_once(flag, [&]() { + + std::ifstream stream(GetAssetDirectory() / "font" / "roboto.ttf", std::ios::binary); + if (!stream.is_open()) + return; + + font.data = std::vector(std::istreambuf_iterator(stream), {}); + font.valid = stbtt_InitFont(&font.info, font.data.data(), 0) != 0; + + }); + + return font; + + } + + Ref CreateImage(int32_t width, int32_t height, u8vec4 color) { + + auto image = CreateRef(width, height, 4); + image->FillRect(0, 0, width, height, vec4(color)); + + return image; + + } + + bool WritePng(const Ref& image, const fs::path& path) { + + image->fileFormat = Common::ImageFormat::PNG; + auto mutableImage = image; + Loader::ImageLoader::SaveImage(mutableImage, path.string()); + + return fs::exists(path); + + } + + bool WriteImage(const Ref& image, const fs::path& path) { + + auto extension = path.extension().string(); + if (extension != ".jpg" && extension != ".jpeg") + return WritePng(image, path); + + image->fileFormat = Common::ImageFormat::JPG; + auto mutableImage = image; + Loader::ImageLoader::SaveImage(mutableImage, path.string()); + + return fs::exists(path); + + } + + Ref LoadImageFile(const fs::path& path) { + + std::error_code error; + if (!fs::exists(path, error)) + return nullptr; + auto image = Loader::ImageLoader::LoadImage(path.string(), false, 4); + return image && image->HasData() ? image : nullptr; + + } + + Ref CropImage(const Ref& image, ivec4 rectangle) { + + auto x0 = std::clamp(rectangle.x, 0, image->width - 1), y0 = std::clamp(rectangle.y, 0, image->height - 1); + auto x1 = std::clamp(rectangle.x + rectangle.z, x0 + 1, image->width), y1 = std::clamp(rectangle.y + rectangle.w, y0 + 1, image->height); + + auto crop = CreateRef(x1 - x0, y1 - y0, 4); + const auto& source = image->GetData(); + auto& target = crop->GetData(); + for (int32_t y = y0; y < y1; y++) + std::copy_n(source.begin() + (size_t(y) * size_t(image->width) + size_t(x0)) * 4, size_t(x1 - x0) * 4, + target.begin() + size_t(y - y0) * size_t(x1 - x0) * 4); + return crop; + + } + + ImageDifference CompareImages(const Image& a, const Image& b, int32_t threshold, Ref* heatMap) { + + ImageDifference difference; + if (a.width != b.width || a.height != b.height) { + difference.sizeMismatch = true; + return difference; + } + + const auto& dataA = a.GetData(); + const auto& dataB = b.GetData(); + if (heatMap) + *heatMap = CreateRef(a.width, a.height, 4); + + double sum = 0.0; + size_t differing = 0; + auto pixels = size_t(a.width) * size_t(a.height); + for (size_t i = 0; i < pixels; i++) { + int32_t pixelMax = 0; + for (size_t c = 0; c < 3; c++) { + auto delta = std::abs(int32_t(dataA[i * 4 + c]) - int32_t(dataB[i * 4 + c])); + sum += double(delta); + pixelMax = std::max(pixelMax, delta); + } + difference.max = std::max(difference.max, float(pixelMax)); + if (pixelMax > threshold) + differing++; + + if (heatMap) { + auto gray = uint8_t((int32_t(dataA[i * 4]) + int32_t(dataA[i * 4 + 1]) + int32_t(dataA[i * 4 + 2])) / 6); + auto& heat = (*heatMap)->GetData(); + auto red = pixelMax > threshold ? uint8_t(std::min(128 + pixelMax * 2, 255)) : gray; + heat[i * 4] = red; + heat[i * 4 + 1] = pixelMax > threshold ? uint8_t(0) : gray; + heat[i * 4 + 2] = pixelMax > threshold ? uint8_t(0) : gray; + heat[i * 4 + 3] = 255; + } + } + + difference.mean = float(sum / double(pixels * 3)); + difference.percent = 100.0f * float(differing) / float(pixels); + return difference; + + } + + Ref Downscale(const Ref& image, int32_t maxWidth) { + + if (image->width <= maxWidth) + return image; + + auto scale = float(maxWidth) / float(image->width); + auto copy = CreateRef(image->width, image->height, image->channels); + copy->SetData(image->GetData()); + copy->Resize(maxWidth, std::max(int32_t(float(image->height) * scale), 1)); + + return copy; + + } + + int32_t DrawText(Image& image, int32_t x, int32_t y, const std::string& text, float pixelHeight, u8vec4 color) { + + auto& font = GetFont(); + if (!font.valid) + return 0; + + auto scale = stbtt_ScaleForPixelHeight(&font.info, pixelHeight); + + int32_t ascent, descent, lineGap; + stbtt_GetFontVMetrics(&font.info, &ascent, &descent, &lineGap); + auto baseline = y + int32_t(float(ascent) * scale); + + float cursor = float(x); + for (size_t i = 0; i < text.size(); i++) { + auto codepoint = int32_t(uint8_t(text[i])); + + int32_t advance, leftBearing; + stbtt_GetCodepointHMetrics(&font.info, codepoint, &advance, &leftBearing); + + int32_t x0, y0, x1, y1; + stbtt_GetCodepointBitmapBox(&font.info, codepoint, scale, scale, &x0, &y0, &x1, &y1); + + auto glyphWidth = x1 - x0, glyphHeight = y1 - y0; + if (glyphWidth > 0 && glyphHeight > 0) { + std::vector bitmap(size_t(glyphWidth) * size_t(glyphHeight)); + stbtt_MakeCodepointBitmap(&font.info, bitmap.data(), glyphWidth, glyphHeight, glyphWidth, scale, scale, codepoint); + + for (int32_t gy = 0; gy < glyphHeight; gy++) { + for (int32_t gx = 0; gx < glyphWidth; gx++) { + auto alpha = float(bitmap[size_t(gy) * size_t(glyphWidth) + size_t(gx)]) / 255.0f; + image.BlendPixel(int32_t(cursor) + x0 + gx, baseline + y0 + gy, vec4(color), alpha); + } + } + } + + cursor += float(advance) * scale; + if (i + 1 < text.size()) + cursor += scale * float(stbtt_GetCodepointKernAdvance(&font.info, codepoint, int32_t(uint8_t(text[i + 1])))); + } + + return int32_t(cursor) - x; + + } + + Ref ComposeSheet(const std::vector>& images, const std::vector& labels, + int32_t columns, const std::string& title, int32_t cellWidth) { + + if (images.empty()) + return CreateImage(1, 1); + + const int32_t labelHeight = 26; + const int32_t titleHeight = title.empty() ? 0 : 34; + const int32_t spacing = 4; + + if (columns <= 0) + columns = int32_t(std::ceil(std::sqrt(float(images.size())))); + columns = std::min(columns, int32_t(images.size())); + auto rows = (int32_t(images.size()) + columns - 1) / columns; + + std::vector> cells; + int32_t cellHeight = 0; + for (const auto& image : images) { + cells.push_back(Downscale(image, cellWidth)); + cellHeight = std::max(cellHeight, cells.back()->height); + } + cellWidth = std::min(cellWidth, cells.front()->width); + + auto width = columns * (cellWidth + spacing) + spacing; + auto height = titleHeight + rows * (cellHeight + labelHeight + spacing) + spacing; + auto sheet = CreateImage(width, height, u8vec4(24, 24, 24, 255)); + + if (!title.empty()) + DrawText(*sheet, spacing + 4, 6, title, 22.0f); + + for (size_t i = 0; i < cells.size(); i++) { + auto column = int32_t(i) % columns, row = int32_t(i) / columns; + auto x = spacing + column * (cellWidth + spacing); + auto y = titleHeight + spacing + row * (cellHeight + labelHeight + spacing); + + sheet->FillRect(x, y, cellWidth, labelHeight, vec4(48, 48, 48, 255)); + if (i < labels.size()) + DrawText(*sheet, x + 6, y + 4, labels[i], 17.0f); + + sheet->Blit(*cells[i], x, y + labelHeight); + } + + return sheet; + + } + +} diff --git a/src/bridge/Image.h b/src/bridge/Image.h new file mode 100644 index 000000000..e79e826cb --- /dev/null +++ b/src/bridge/Image.h @@ -0,0 +1,51 @@ +#pragma once + +#include "Common.h" + +#include "common/Image.h" + +namespace Atlas::Bridge { + + // Captures are stored in engine images with 4 channels (RGBA8) + using Image = Common::Image; + + Ref CreateImage(int32_t width, int32_t height, u8vec4 color = u8vec4(0, 0, 0, 255)); + + // Saved with the engine image loader + bool WritePng(const Ref& image, const fs::path& path); + + // A PNG or a JPG by the extension of the path + bool WriteImage(const Ref& image, const fs::path& path); + + // nullptr if the file can't be read + Ref LoadImageFile(const fs::path& path); + + // The part of the image inside the rectangle (x, y, width, height), clamped to the image + Ref CropImage(const Ref& image, ivec4 rectangle); + + struct ImageDifference { + + // Of the color channels on a scale of 0 to 255 + float mean = 0.0f; + float max = 0.0f; + // Pixels with a channel that differs by more than the threshold + float percent = 0.0f; + bool sizeMismatch = false; + + }; + + // Optionally writes a heat map: the first image in gray, differences above the threshold in red + ImageDifference CompareImages(const Image& a, const Image& b, int32_t threshold, Ref* heatMap = nullptr); + + // Returns the input if it fits maxWidth, otherwise a copy resized with the engine image resampling + Ref Downscale(const Ref& image, int32_t maxWidth); + + // Draws byte-wise text with font/roboto.ttf from the asset directory and returns its width + // The engine font stores glyph textures on the GPU; CPU bitmaps are rasterized here with stb_truetype + int32_t DrawText(Image& image, int32_t x, int32_t y, const std::string& text, float pixelHeight, u8vec4 color = u8vec4(255)); + + // Grid of labeled images with an optional title + Ref ComposeSheet(const std::vector>& images, const std::vector& labels, + int32_t columns, const std::string& title, int32_t cellWidth = 640); + +} diff --git a/src/bridge/Inspect.cpp b/src/bridge/Inspect.cpp new file mode 100644 index 000000000..a1c55ed65 --- /dev/null +++ b/src/bridge/Inspect.cpp @@ -0,0 +1,345 @@ +#include "Inspect.h" +#include "MaterialGraphTools.h" +#include "SceneFile.h" + +#include +#include +#include + +#include +#include +#include +#include + +namespace Atlas::Bridge { + + static std::string FormatSize(const Volume::AABB& bounds) { + + auto size = bounds.max - bounds.min; + return FormatFloat(size.x, 2) + " x " + FormatFloat(size.y, 2) + " x " + FormatFloat(size.z, 2); + + } + + // Where the origin lies in the bounds, e.g. "x center, y bottom, z center" + static std::string DescribeOrigin(const Volume::AABB& bounds) { + + auto describe = [](float min, float max, const char* low, const char* high) -> std::string { + + if (max - min < 1e-5f) + return "flat"; + auto t = -min / (max - min); + if (std::abs(t) < 0.05f) + return low; + if (std::abs(t - 1.0f) < 0.05f) + return high; + if (std::abs(t - 0.5f) < 0.05f) + return "center"; + return FormatFloat(t * 100.0f, 0) + "%"; + + }; + + return "x " + describe(bounds.min.x, bounds.max.x, "min", "max") + ", y " + describe(bounds.min.y, bounds.max.y, "bottom", "top") + + ", z " + describe(bounds.min.z, bounds.max.z, "min", "max"); + + } + + static std::string DescribePlacement(const mat4& matrix) { + + auto position = vec3(matrix[3]); + auto scale = vec3(glm::length(vec3(matrix[0])), glm::length(vec3(matrix[1])), glm::length(vec3(matrix[2]))); + auto forward = vec3(matrix[2]) / std::max(scale.z, 1e-6f); + auto yaw = glm::degrees(std::atan2(forward.x, forward.z)); + + auto text = FormatVec3(position, 2); + if (std::abs(yaw) > 0.05f) + text += ", yaw " + FormatFloat(yaw, 1); + if (glm::length(scale - vec3(1.0f)) > 1e-3f) + text += std::abs(scale.x - scale.y) < 1e-3f && std::abs(scale.y - scale.z) < 1e-3f ? ", scale " + FormatFloat(scale.x, 3) : + ", scale " + FormatVec3(scale, 3); + return text; + + } + + struct InspectOptions { + + fs::path file; + std::vector filters; + std::string assembly; + size_t limit = 40; + fs::path output; + // Material graphs: the generated shader code + bool code = false; + + }; + + static int32_t InspectMesh(const InspectOptions& options) { + + auto info = ReadMeshFile(options.file); + json result = { + { "name", info.name }, { "bounds", { { "min", FromVec3(info.bounds.min) }, { "max", FromVec3(info.bounds.max) } } }, + { "origin", DescribeOrigin(info.bounds) }, { "vertices", info.vertexCount }, { "triangles", info.indexCount / 3 }, + { "materials", info.materials }, { "impostor", info.impostor }, { "settings", info.settings }, + { "lodTriangles", info.lodTriangles } + }; + + Print(info.name + ": " + FormatSize(info.bounds) + " m, origin " + DescribeOrigin(info.bounds) + ", bounds " + + FormatVec3(info.bounds.min, 2) + " to " + FormatVec3(info.bounds.max, 2)); + Print(" " + std::to_string(info.vertexCount) + " vertices, " + std::to_string(info.indexCount / 3) + " triangles, " + + std::to_string(info.subData.size()) + " submeshes" + (info.impostor.empty() ? ", no impostor" : ", impostor " + info.impostor)); + if (!info.lodTriangles.empty()) { + std::string lods; + for (auto triangles : info.lodTriangles) + lods += (lods.empty() ? "" : ", ") + std::to_string(triangles); + Print(" levels of detail: " + lods + " triangles"); + } + for (size_t i = 0; i < info.materials.size(); i++) { + std::string submeshes; + for (const auto& [name, index] : info.subData) + if (index == int32_t(i)) + submeshes += (submeshes.empty() ? "" : ", ") + name; + Print(" material " + std::to_string(i) + ": " + info.materials[i] + (submeshes.empty() ? "" : " (" + submeshes + ")")); + } + std::string settings; + for (const auto& key : { "mobility", "castShadow", "rayTrace", "cullBackFaces", "vegetation", "distanceCulling", + "impostorDistance", "minScreenSize", "lodPixelError", "invertUVs" }) + if (info.settings.contains(key)) + settings += std::string(settings.empty() ? "" : ", ") + key + " " + info.settings[key].dump(); + Print(" " + settings); + + if (!options.output.empty()) + WriteFileAtomic(options.output, result.dump(2)); + return 0; + + } + + static int32_t InspectModel(const InspectOptions& options) { + + Assimp::Importer importer; + auto scene = importer.ReadFile(options.file.string(), aiProcess_Triangulate | aiProcess_GenBoundingBoxes); + if (!scene) { + Print("Couldn't read " + options.file.string() + ": " + importer.GetErrorString()); + return 2; + } + + auto toMatrix = [](const aiMatrix4x4& m) { + + return glm::transpose(glm::make_mat4(&m.a1)); + + }; + + Volume::AABB bounds(vec3(std::numeric_limits::max()), vec3(-std::numeric_limits::max())); + int64_t vertices = 0, triangles = 0; + std::vector nodeLines; + std::function visit = [&](const aiNode* node, const mat4& parent, int32_t depth) { + + auto global = parent * toMatrix(node->mTransformation); + for (uint32_t i = 0; i < node->mNumMeshes; i++) { + const auto mesh = scene->mMeshes[node->mMeshes[i]]; + vertices += mesh->mNumVertices; + triangles += mesh->mNumFaces; + const auto& box = mesh->mAABB; + for (int32_t corner = 0; corner < 8; corner++) { + vec3 point((corner & 1) ? box.mMax.x : box.mMin.x, (corner & 2) ? box.mMax.y : box.mMin.y, (corner & 4) ? box.mMax.z : box.mMin.z); + auto transformed = vec3(global * vec4(point, 1.0f)); + bounds.min = glm::min(bounds.min, transformed); + bounds.max = glm::max(bounds.max, transformed); + } + } + if (depth <= 3 && nodeLines.size() < options.limit) + nodeLines.push_back(std::string(size_t(depth) * 2 + 2, ' ') + node->mName.C_Str() + ": " + DescribePlacement(toMatrix(node->mTransformation)) + + (node->mNumMeshes ? ", " + std::to_string(node->mNumMeshes) + " meshes" : "") + + (node->mNumChildren ? ", " + std::to_string(node->mNumChildren) + " children" : "")); + for (uint32_t i = 0; i < node->mNumChildren; i++) + visit(node->mChildren[i], global, depth + 1); + + }; + visit(scene->mRootNode, mat4(1.0f), 0); + + double unitScale = 0.0; + if (scene->mMetaData) + scene->mMetaData->Get("UnitScaleFactor", unitScale); + + Print(options.file.filename().string() + ": " + std::to_string(scene->mNumMeshes) + " meshes, " + std::to_string(vertices) + + " vertices, " + std::to_string(triangles) + " triangles, bounds " + FormatSize(bounds) + " (" + FormatVec3(bounds.min, 2) + + " to " + FormatVec3(bounds.max, 2) + "), origin " + DescribeOrigin(bounds) + (unitScale > 0.0 ? ", unit scale " + + FormatFloat(float(unitScale), 2) : "")); + for (uint32_t i = 0; i < scene->mNumMaterials && i < options.limit; i++) { + auto material = scene->mMaterials[i]; + aiString texture; + std::string line = " material " + std::string(material->GetName().C_Str()); + if (material->GetTexture(aiTextureType_DIFFUSE, 0, &texture) == AI_SUCCESS || material->GetTexture(aiTextureType_BASE_COLOR, 0, &texture) == AI_SUCCESS) + line += ": " + std::string(texture.C_Str()); + Print(line); + } + for (uint32_t i = 0; i < scene->mNumAnimations; i++) { + auto animation = scene->mAnimations[i]; + auto ticks = animation->mTicksPerSecond > 0.0 ? animation->mTicksPerSecond : 25.0; + Print(" animation " + std::string(animation->mName.C_Str()) + ": " + FormatFloat(float(animation->mDuration / ticks), 2) + " s, " + + std::to_string(animation->mNumChannels) + " channels"); + } + Print(" nodes:"); + for (const auto& line : nodeLines) + Print(line); + return 0; + + } + + static int32_t InspectScene(const InspectOptions& options) { + + auto entities = ReadFileEntities(options.file); + + std::map components, meshes; + for (const auto& entity : entities) { + for (const auto& component : entity.components) + components[component]++; + if (!entity.mesh.empty()) + meshes[entity.mesh]++; + } + + std::string componentText; + for (const auto& [name, count] : components) + componentText += (componentText.empty() ? "" : ", ") + name + " " + std::to_string(count); + Print(options.file.filename().string() + ": " + std::to_string(entities.size()) + " entities, " + std::to_string(meshes.size()) + + " meshes; components: " + componentText); + + std::vector> meshList; + for (const auto& [path, count] : meshes) + meshList.emplace_back(count, path); + std::sort(meshList.rbegin(), meshList.rend()); + Print(" most used meshes:"); + for (size_t i = 0; i < std::min(meshList.size(), size_t(12)); i++) + Print(" " + std::to_string(meshList[i].first) + "x " + meshList[i].second); + + json result = { { "entities", entities.size() }, { "components", components }, { "meshes", meshes } }; + + if (!options.filters.empty()) { + json matches = json::array(); + size_t count = 0; + Print(" entities matching the filter:"); + for (const auto& entity : entities) { + if (!MatchAnyPattern(options.filters, entity.name)) + continue; + count++; + std::string parent = entity.parent >= 0 ? entities[entity.parent].name : ""; + matches.push_back({ { "name", entity.name }, { "position", FromVec3(vec3(entity.global[3])) }, { "mesh", entity.mesh }, + { "parent", parent }, { "components", entity.components } }); + if (count <= options.limit) + Print(" " + entity.name + " at " + DescribePlacement(entity.global) + (entity.mesh.empty() ? "" : ", " + entity.mesh) + + (parent.empty() ? "" : ", in " + parent)); + } + if (count > options.limit) + Print(" ... " + std::to_string(count - options.limit) + " more (--limit, --out)"); + Print(" " + std::to_string(count) + " entities match"); + result["matches"] = matches; + } + + if (!options.assembly.empty()) { + auto root = std::find_if(entities.begin(), entities.end(), [&](const FileEntity& entity) { + return Helper::String::MatchWildcard(options.assembly, entity.name); }); + if (root == entities.end()) { + std::vector names; + for (const auto& entity : entities) + names.push_back(entity.name); + std::string closest; + for (const auto& name : FindClosestNames(names, options.assembly)) + closest += (closest.empty() ? "'" : ", '") + name + "'"; + Print("No entity matches '" + options.assembly + "', closest: " + closest); + return 2; + } + + // Mesh bounds are read once per mesh file, paths in packages are relative to the scene + std::map> meshBounds; + auto getBounds = [&](const std::string& mesh) -> std::optional { + + if (auto it = meshBounds.find(mesh); it != meshBounds.end()) + return it->second; + auto path = mesh.starts_with(".") ? options.file.parent_path() / mesh : GetAssetDirectory() / mesh; + std::optional bounds; + try { + bounds = ReadMeshFile(path.lexically_normal()).bounds; + } + catch (const std::exception&) {} + return meshBounds[mesh] = bounds; + + }; + + auto rootIndex = int32_t(root - entities.begin()); + auto inverse = glm::inverse(root->global); + json parts = json::array(); + Print(" assembly " + root->name + " at " + DescribePlacement(root->global) + ", parts relative to it:"); + std::vector depths(entities.size(), -1); + depths[rootIndex] = 0; + size_t printed = 0; + for (size_t i = size_t(rootIndex) + 1; i < entities.size(); i++) { + const auto& entity = entities[i]; + if (entity.parent < 0 || depths[entity.parent] < 0) + continue; + depths[i] = depths[entity.parent] + 1; + auto relative = inverse * entity.global; + std::string boundsText; + json part = { { "name", entity.name }, { "offset", FromVec3(vec3(relative[3])) }, { "mesh", entity.mesh } }; + if (!entity.mesh.empty()) { + if (auto bounds = getBounds(entity.mesh)) { + auto transformed = bounds->Transform(relative); + boundsText = ", bounds " + FormatVec3(transformed.min, 2) + " to " + FormatVec3(transformed.max, 2); + part["bounds"] = { { "min", FromVec3(transformed.min) }, { "max", FromVec3(transformed.max) } }; + } + } + parts.push_back(part); + if (printed++ < options.limit) + Print(std::string(size_t(depths[i]) * 2 + 2, ' ') + entity.name + ": " + DescribePlacement(relative) + + (entity.mesh.empty() ? "" : ", " + fs::path(entity.mesh).filename().string()) + boundsText); + } + if (printed > options.limit) + Print(" ... " + std::to_string(printed - options.limit) + " more parts (--limit, --out)"); + result["assembly"] = { { "root", root->name }, { "parts", parts } }; + } + + if (!options.output.empty()) { + WriteFileAtomic(options.output, result.dump(2)); + Print(" written to " + options.output.string()); + } + return 0; + + } + + int32_t Inspect(const std::vector& args) { + + if (args.size() < 3) + throw std::runtime_error("inspect expects a scene, prefab, mesh, model or material graph file, or nodes"); + + InspectOptions options; + auto file = ResolveUserPath(args[2]); + std::error_code error; + options.file = fs::exists(file, error) ? file : GetAssetDirectory() / args[2]; + for (size_t i = 3; i < args.size(); i++) { + if (args[i] == "--code") + options.code = true; + else if (args[i] == "--filter" && i + 1 < args.size()) + options.filters.push_back(args[++i]); + else if (args[i] == "--assembly" && i + 1 < args.size()) + options.assembly = args[++i]; + else if (args[i] == "--limit" && i + 1 < args.size()) + options.limit = size_t(std::stoul(args[++i])); + else if (args[i] == "--out" && i + 1 < args.size()) + options.output = ResolveUserPath(args[++i]); + else + throw std::runtime_error("Unknown inspect option '" + args[i] + "' (--filter, --assembly, --limit, --out, --code)"); + } + if (args[2] == "nodes") + return InspectMaterialGraphNodes(options.filters); + if (!fs::exists(options.file, error)) + throw std::runtime_error("No file " + args[2] + " in the launch or the data directory"); + + auto extension = options.file.extension().string(); + if (extension == ".aemesh") + return InspectMesh(options); + if (extension == ".aematgraph") + return InspectMaterialGraph(options.file, options.filters, options.code, options.output); + if (extension == ".aescene" || extension == ".aeprefab" || extension == ".json") + return InspectScene(options); + return InspectModel(options); + + } + +} diff --git a/src/bridge/Inspect.h b/src/bridge/Inspect.h new file mode 100644 index 000000000..01dbabf73 --- /dev/null +++ b/src/bridge/Inspect.h @@ -0,0 +1,15 @@ +#pragma once + +#include "Common.h" + +namespace Atlas::Bridge { + + // inspect [--filter ] [--assembly ] [--limit ] [--out ] + // Reads files without loading them. Scenes and prefabs: entity and component counts, the most used meshes, entities + // matching the filters with their position, and with --assembly the parts of an entity relative to it. Meshes + // (.aemesh): bounds, where the origin lies, counts, materials, impostor and settings. Models (glTF, FBX, OBJ, ...): + // nodes, meshes, bounds, materials, animations and the unit scale. Material graphs (.aematgraph): compile result, + // parameters, nodes with their links and stages, --code the generated shaders. "nodes": the node library + int32_t Inspect(const std::vector& args); + +} diff --git a/src/bridge/InstanceRegistry.cpp b/src/bridge/InstanceRegistry.cpp new file mode 100644 index 000000000..ebc7cdaed --- /dev/null +++ b/src/bridge/InstanceRegistry.cpp @@ -0,0 +1,244 @@ +#include "InstanceRegistry.h" +#include "Processes.h" +#include "common/SerializationHelper.h" + +#include +#include +#include +#include +#include + +#ifdef AE_OS_WINDOWS +#define NOMINMAX +#define WIN32_LEAN_AND_MEAN +#include +#else +#include +#include +#endif + +namespace Atlas::Bridge { + + // The registered instance of this process with the identity of its process, which tells it apart from a later + // process with the same id + static std::optional self; + static uint64_t selfProcessStart = 0; + + static fs::path GetDirectory() { + +#ifdef AE_OS_WINDOWS + auto base = std::getenv("LOCALAPPDATA"); + return fs::path(base ? base : ".") / "AtlasEngine" / "instances"; +#else + auto base = std::getenv("XDG_RUNTIME_DIR"); + return fs::path(base ? base : "/tmp") / "atlas-engine-instances"; +#endif + + } + + static uint64_t GetProcessStart(uint32_t pid) { + +#ifdef AE_OS_WINDOWS + auto process = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid); + if (!process) + return 0; + + DWORD exitCode = 0; + FILETIME creation, exit, kernel, user; + uint64_t start = 0; + if (GetExitCodeProcess(process, &exitCode) && exitCode == STILL_ACTIVE && + GetProcessTimes(process, &creation, &exit, &kernel, &user)) + start = (uint64_t(creation.dwHighDateTime) << 32) | creation.dwLowDateTime; + CloseHandle(process); + return start; +#else + // The id is enough here, kill(0) only checks whether the process exists + return kill(pid_t(pid), 0) == 0 || errno == EPERM ? 1 : 0; +#endif + + } + + static void Write() { + + if (!self) + return; + + json j = { + { "pid", self->pid }, { "processStart", selfProcessStart }, { "executable", self->executable }, + { "args", self->args }, { "started", self->started }, { "activity", self->activity }, { "busy", self->busy }, + { "expectedEnd", self->expectedEnd ? json(*self->expectedEnd) : json() }, + { "waitingSince", self->waitingSince ? json(*self->waitingSince) : json() } + }; + + std::error_code error; + auto directory = GetDirectory(); + fs::create_directories(directory, error); + auto path = directory / (std::to_string(self->pid) + ".json"); + auto temporary = path; + temporary += ".tmp"; + { + std::ofstream stream(temporary); + stream << j.dump(); + } + // Fails on Windows while another process reads the file, the order of the GPU queue relies on the write + for (int32_t attempt = 0; attempt < 20; attempt++) { + fs::rename(temporary, path, error); + if (!error) + break; + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + } + + } + + void InstanceRegistry::Register(const std::vector& args) { + + self = Instance { + .pid = CurrentProcessId(), + .executable = args.empty() ? std::string() : fs::path(args.front()).filename().string(), + .args = args.size() > 1 ? std::vector(args.begin() + 1, args.end()) : std::vector(), + .started = std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count(), + .activity = "running" + }; + selfProcessStart = GetProcessStart(self->pid); + Write(); + + } + + void InstanceRegistry::Unregister() { + + if (!self) + return; + + std::error_code error; + fs::remove(GetDirectory() / (std::to_string(self->pid) + ".json"), error); + self.reset(); + + } + + void InstanceRegistry::SetActivity(const std::string& activity, bool busy, std::optional expectedEnd) { + + if (!self) + return; + + self->activity = activity; + self->busy = busy; + self->expectedEnd = expectedEnd; + self->waitingSince.reset(); + Write(); + + } + + std::vector InstanceRegistry::GetInstances() { + + std::vector instances; + std::error_code error; + for (const auto& entry : fs::directory_iterator(GetDirectory(), error)) { + if (entry.path().extension() != ".json") + continue; + + json j; + { + std::ifstream stream(entry.path()); + j = json::parse(stream, nullptr, false); + } + if (j.is_discarded() || !j.contains("pid")) + continue; + + Instance instance; + instance.pid = j["pid"].get(); + auto start = GetProcessStart(instance.pid); + if (start == 0 || start != j.value("processStart", start)) { + fs::remove(entry.path(), error); + continue; + } + + instance.executable = j.value("executable", std::string()); + instance.args = j.value("args", std::vector()); + instance.started = j.value("started", int64_t(0)); + instance.activity = j.value("activity", std::string()); + instance.busy = j.value("busy", true); + if (j.contains("expectedEnd") && j["expectedEnd"].is_number()) + instance.expectedEnd = j["expectedEnd"].get(); + if (j.contains("waitingSince") && j["waitingSince"].is_number()) + instance.waitingSince = j["waitingSince"].get(); + instances.push_back(instance); + } + + return instances; + + } + + std::vector InstanceRegistry::GetBusyInstances() { + + auto instances = GetInstances(); + std::erase_if(instances, [](const Instance& instance) { return !instance.busy || instance.pid == CurrentProcessId(); }); + return instances; + + } + + std::vector InstanceRegistry::GetInstancesAhead(const Instance& waiter, const std::vector& instances) { + + std::vector ahead; + for (const auto& instance : instances) { + if (instance.pid == waiter.pid) + continue; + // A later waiter which claimed the GPU before it saw this one backs off in its next step + auto isAhead = instance.waitingSince && waiter.waitingSince ? + std::pair(*instance.waitingSince, instance.pid) < std::pair(*waiter.waitingSince, waiter.pid) : instance.busy; + if (isAhead) + ahead.push_back(instance); + } + return ahead; + + } + + void InstanceRegistry::QueueForGpu(const std::string& activity) { + + if (!self) + return; + + self->activity = activity; + self->busy = false; + self->expectedEnd.reset(); + self->waitingSince = std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch()).count(); + Write(); + + } + + bool InstanceRegistry::PollGpu(std::vector& ahead) { + + if (!self) { + ahead = GetBusyInstances(); + return ahead.empty(); + } + + ahead = GetInstancesAhead(*self, GetInstances()); + if (!ahead.empty()) { + if (self->busy) { + self->busy = false; + Write(); + } + return false; + } + + if (self->busy) + return true; + + self->busy = true; + Write(); + return false; + + } + + std::string InstanceRegistry::Describe(const std::vector& instances) { + + std::string description; + for (const auto& instance : instances) + description += (description.empty() ? "" : ", ") + instance.executable + " (process " + std::to_string(instance.pid) + + "): " + instance.activity; + return description; + + } + +} diff --git a/src/bridge/InstanceRegistry.h b/src/bridge/InstanceRegistry.h new file mode 100644 index 000000000..e860e6c4b --- /dev/null +++ b/src/bridge/InstanceRegistry.h @@ -0,0 +1,63 @@ +#pragma once + +#include "System.h" + +#include +#include +#include + +namespace Atlas::Bridge { + + // The engine applications running on this machine (bridge, games linking the bridge library), so that tools + // see who uses the GPU. Each one is a file in a directory of the user, an application adds it in LoadContent and + // removes it in UnloadContent + class InstanceRegistry { + + public: + struct Instance { + + uint32_t pid = 0; + std::string executable; + std::vector args; + // Seconds since the epoch + int64_t started = 0; + // What the application does, e.g. "job hours", and whether it keeps the GPU under load + std::string activity; + bool busy = true; + std::optional expectedEnd; + // Milliseconds since the epoch, while it waits for the GPU. A waiting instance which is busy claimed the GPU + std::optional waitingSince; + + }; + + static void Register(const std::vector& args); + + static void Unregister(); + + // Ends waiting for the GPU + static void SetActivity(const std::string& activity, bool busy, std::optional expectedEnd = std::nullopt); + + // The instances whose process still runs, files of ended processes are removed + static std::vector GetInstances(); + + // The other instances which keep the GPU busy + static std::vector GetBusyInstances(); + + // The instances a waiting instance waits for: busy ones and the ones which wait longer, the smaller process id + // first on a tie. Without waiting it's the busy ones + static std::vector GetInstancesAhead(const Instance& waiter, const std::vector& instances); + + // Queues this process for the GPU, it isn't busy while it waits + static void QueueForGpu(const std::string& activity); + + // One step of waiting, at most every few hundred milliseconds: with nobody ahead this process claims the GPU and + // gets it when the next step still finds nobody ahead, two processes claiming at once see each other then. + // Returns true once the caller may load, ahead lists whom it still waits for + static bool PollGpu(std::vector& ahead); + + // E.g. "AtlasBridge.exe (process 1234): job hours, ..." + static std::string Describe(const std::vector& instances); + + }; + +} diff --git a/src/bridge/Job.cpp b/src/bridge/Job.cpp new file mode 100644 index 000000000..7b66b8df3 --- /dev/null +++ b/src/bridge/Job.cpp @@ -0,0 +1,902 @@ +#include "Job.h" + +#include +#include +#include +#include +#include + +namespace Atlas::Bridge { + + static std::vector ToStringList(const json& j) { + + std::vector list; + if (j.is_string()) + list.push_back(j.get()); + else if (j.is_array()) + for (const auto& item : j) + list.push_back(item.get()); + + return list; + + } + + static std::vector SplitList(const std::string& text, char separator = ',') { + + std::vector list; + size_t start = 0; + while (start <= text.size()) { + auto end = text.find(separator, start); + if (end == std::string::npos) + end = text.size(); + auto item = text.substr(start, end - start); + if (!item.empty()) + list.push_back(item); + start = end + 1; + } + + return list; + + } + + static json ParseVec3Argument(const std::string& text, const std::string& option) { + + auto parts = SplitList(text); + if (parts.size() != 3) + throw std::runtime_error(option + " expects x,y,z but got '" + text + "'"); + + return json::array({ std::stof(parts[0]), std::stof(parts[1]), std::stof(parts[2]) }); + + } + + static float ParseRenderScale(const json& j) { + + auto renderScale = j.get(); + if (renderScale <= 0.0f || renderScale > 1.0f) + throw std::runtime_error("renderScale must be in (0, 1]"); + + return renderScale; + + } + + static ShotSpec ParseShot(const json& j, size_t index) { + + CheckKeys(j, { "name", "camera", "views", "passes", "settleFrames", "crop" }, "shot"); + + ShotSpec shot; + shot.name = j.value("name", "shot" + std::to_string(index)); + if (j.contains("camera")) + shot.camera = ParseCamera(j["camera"]); + if (j.contains("views")) + shot.views = ToStringList(j["views"]); + if (j.contains("passes")) + shot.passes = ToStringList(j["passes"]); + shot.settleFrames = j.value("settleFrames", -1); + shot.crop = j.value("crop", json()); + + return shot; + + } + + static GroundedCheckSpec ParseGrounded(const json& j) { + + CheckKeys(j, { "entities", "meshes", "maxGap", "maxSink", "surfaces", "ignore", "footprint", "baseHeight" }, "checks.grounded"); + if (!j.contains("entities") && !j.contains("meshes")) + throw std::runtime_error("checks.grounded needs 'entities' or 'meshes'"); + + GroundedCheckSpec spec; + if (j.contains("entities")) + spec.entities = ToStringList(j["entities"]); + if (j.contains("meshes")) + spec.meshes = ToStringList(j["meshes"]); + spec.maxGap = j.value("maxGap", spec.maxGap); + spec.maxSink = j.value("maxSink", spec.maxSink); + if (j.contains("surfaces")) + spec.surfaces = ToStringList(j["surfaces"]); + if (j.contains("ignore")) + spec.ignore = ToStringList(j["ignore"]); + spec.footprint = j.value("footprint", spec.footprint); + spec.baseHeight = j.value("baseHeight", spec.baseHeight); + return spec; + + } + + static PenetrationCheckSpec ParsePenetration(const json& j) { + + CheckKeys(j, { "entities", "against", "margin", "minTriangles" }, "checks.penetration"); + + PenetrationCheckSpec spec; + spec.entities = ToStringList(j.at("entities")); + spec.against = j.contains("against") ? ToStringList(j["against"]) : std::vector { "*" }; + spec.margin = j.value("margin", spec.margin); + spec.minTriangles = j.value("minTriangles", spec.minTriangles); + return spec; + + } + + // The type of a timeline event is the key of its action, e.g. { "t": 1.0, "key": "E" } + static std::string GetEventType(const json& event) { + + static const std::vector types = { "capture", "key", "controller", "mouse", "look", "teleport", "log", "expect", + "lua", "resetScripts", "pause", "end", "animation" }; + + std::string type; + for (const auto& candidate : types) { + if (!event.contains(candidate)) + continue; + if (!type.empty()) + throw std::runtime_error("A timeline event can only have one type: " + event.dump()); + type = candidate; + } + if (type.empty()) + throw std::runtime_error("Timeline event without a known type (capture, key, controller, mouse, look, teleport, log, expect, " + "lua, resetScripts, pause, end, animation): " + event.dump()); + + return type; + + } + + static vec2 ToPixel(const json& j, const std::string& context) { + + if (!j.is_array() || j.size() != 2) + throw std::runtime_error(context + " expects window pixels [x, y]"); + return vec2(j[0].get(), j[1].get()); + + } + + // Inline code or { "file" } relative to the job + static LuaEvent ParseLua(const json& value, const fs::path& baseDirectory, const std::string& result) { + + if (value.is_string()) + return LuaEvent { value.get(), "", result }; + CheckKeys(value, { "file" }, "lua"); + auto path = (baseDirectory / value.at("file").get()).lexically_normal(); + std::ifstream stream(path); + if (!stream.is_open()) + throw std::runtime_error("Couldn't open the Lua file " + path.string()); + return LuaEvent { std::string(std::istreambuf_iterator(stream), {}), path.string(), result }; + + } + + static EventAction ParseEventAction(const json& event, const std::string& type, float fixedDeltaTime, const fs::path& baseDirectory) { + + const auto& value = event[type]; + // A press lasts two frames unless it has a duration + auto pressDuration = fixedDeltaTime * 2.0f; + + if (type == "capture") { + CaptureEvent capture; + capture.name = value.value("name", capture.name); + if (value.contains("file")) + capture.file = value["file"].get(); + capture.group = value.value("group", capture.group); + if (value.contains("label")) + capture.label = value["label"].get(); + if (value.contains("camera")) + capture.camera = ParseCamera(value["camera"]); + capture.stripCamera = value.value("stripCamera", capture.stripCamera); + capture.still = value.value("still", capture.still); + if (value.contains("settleFrames")) + capture.settleFrames = value["settleFrames"].get(); + if (value.contains("passes")) + capture.passes = ToStringList(value["passes"]); + capture.crop = value.value("crop", json()); + return capture; + } + if (type == "key") { + InputEvent input = { .device = InputEvent::Device::Key, .duration = pressDuration }; + if (value.is_string()) { + input.name = value.get(); + return input; + } + input.name = value.at("key").get(); + input.action = value.value("action", input.action); + input.duration = value.value("duration", input.duration); + return input; + } + if (type == "controller") { + CheckKeys(value, { "button", "action", "duration", "axis", "value" }, "controller"); + if (value.contains("axis")) + return InputEvent { .device = InputEvent::Device::Axis, .name = value["axis"].get(), + .value = value.at("value").get() }; + if (!value.contains("button")) + throw std::runtime_error("A controller event needs a button or an axis: " + event.dump()); + return InputEvent { .device = InputEvent::Device::Button, .name = value["button"].get(), + .action = value.value("action", std::string("press")), .duration = value.value("duration", pressDuration) }; + } + if (type == "mouse") { + CheckKeys(value, { "move", "click", "down", "up", "button", "duration", "wheel" }, "mouse"); + InputEvent input = { .device = InputEvent::Device::Mouse, .name = value.value("button", std::string("left")), + .duration = value.value("duration", pressDuration) }; + if (value.contains("move")) { + input.action = "move"; + input.position = ToPixel(value["move"], "mouse.move"); + } + else if (value.contains("click")) { + input.position = ToPixel(value["click"], "mouse.click"); + } + else if (value.contains("down") || value.contains("up")) { + input.action = value.contains("down") ? "down" : "up"; + input.name = value[input.action].get(); + } + else if (value.contains("wheel")) { + input.action = "wheel"; + input.value = value["wheel"].get(); + } + else { + throw std::runtime_error("A mouse event needs move, click, down, up or wheel: " + event.dump()); + } + if (input.name != "left" && input.name != "right" && input.name != "middle") + throw std::runtime_error("Unknown mouse button '" + input.name + "' (left, right, middle)"); + return input; + } + if (type == "lua") + return ParseLua(value, baseDirectory, event.value("result", std::string())); + if (type == "look" || type == "teleport") { + std::optional yaw, pitch; + if (value.contains("yaw")) + yaw = value["yaw"].get(); + if (value.contains("pitch")) + pitch = value["pitch"].get(); + auto entity = value.at("entity").get(); + if (type == "look") + return LookEvent { entity, yaw, pitch }; + return TeleportEvent { entity, ToVec3(value.at("position")), yaw, pitch }; + } + if (type == "animation") + return AnimationEvent { value.at("entity").get(), value.at("animation").get(), + value.value("model", std::string()), value.value("blendTime", 0.0f) }; + if (type == "log") + return LogEvent { value.get() }; + if (type == "expect") + return ExpectEvent { value }; + if (type == "pause") { + if (!value.is_boolean()) + throw std::runtime_error("A pause event needs true or false: " + event.dump()); + return PauseEvent { value.get() }; + } + if (type == "end") { + if (value != true) + throw std::runtime_error("An end event needs true: " + event.dump()); + return EndEvent {}; + } + return ResetScriptsEvent {}; + + } + + CameraSpec ParseCamera(const json& j) { + + CameraSpec camera; + + if (j.is_string()) { + camera.mode = j.get(); + return camera; + } + + CheckKeys(j, + { "mode", "position", "lookAt", "yaw", "pitch", "entity", "view", "azimuth", "elevation", "local", + "distance", "padding", "avoidOcclusion", "dynamic", "offset", "fov", "near", "far", "groundRelative" }, + "camera"); + + // Infer the mode from the given keys if it isn't specified + if (j.contains("mode")) + camera.mode = j["mode"].get(); + else if (j.contains("entity") && j.contains("offset")) + camera.mode = "follow"; + else if (j.contains("entity")) + camera.mode = "focus"; + else if (j.contains("position")) + camera.mode = "manual"; + + static const std::set modes = { "scene", "manual", "focus", "follow", "overview" }; + if (!modes.contains(camera.mode)) + throw std::runtime_error("Unknown camera mode '" + camera.mode + "'"); + + camera.position = ToVec3(j.value("position", json()), camera.position); + if (j.contains("lookAt")) + camera.lookAt = ToVec3(j["lookAt"]); + camera.yaw = j.value("yaw", camera.yaw); + camera.pitch = j.value("pitch", camera.pitch); + camera.entity = j.value("entity", camera.entity); + camera.view = j.value("view", camera.view); + if (j.contains("azimuth")) + camera.azimuth = j["azimuth"].get(); + if (j.contains("elevation")) + camera.elevation = j["elevation"].get(); + camera.local = j.value("local", camera.local); + camera.distance = j.value("distance", camera.distance); + camera.padding = j.value("padding", camera.padding); + camera.avoidOcclusion = j.value("avoidOcclusion", camera.avoidOcclusion); + camera.dynamic = j.value("dynamic", camera.dynamic); + camera.offset = ToVec3(j.value("offset", json()), camera.offset); + camera.fieldOfView = j.value("fov", camera.fieldOfView); + camera.nearPlane = j.value("near", camera.nearPlane); + camera.farPlane = j.value("far", camera.farPlane); + camera.groundRelative = j.value("groundRelative", camera.groundRelative); + + if ((camera.mode == "focus" || camera.mode == "follow") && camera.entity.empty()) + throw std::runtime_error("Camera mode '" + camera.mode + "' requires an entity pattern"); + + return camera; + + } + + Job ParseJob(const json& j, const fs::path& baseDirectory) { + + CheckKeys(j, + { "name", "scene", "out", "resolution", "renderScale", "settleFrames", "loadTimeout", "fixedDt", "showWindow", "foreground", + "waitGpu", "gpuWaitTimeout", "realTime", "pathTrace", "playerDisplay", "settings", "variants", "inspect", "queries", "lua", "edit", + "shots", "play", "duration", "timeline", "strips", "observer", "scripts", "track", "overlay", "checks", "profile", "hitches", + "compare", "$schema", "description" }, + "job"); + + Job job; + + if (!j.contains("scene")) + throw std::runtime_error("The job doesn't specify a scene"); + + job.scene = ToAssetPath(j["scene"].get()); + job.name = j.value("name", fs::path(job.scene).stem().string()); + + if (j.contains("out")) { + fs::path out(j["out"].get()); + job.outputDirectory = out.is_absolute() ? out : (baseDirectory / out).lexically_normal(); + } + else { + // bin//../capture/, the bin directory is ignored by git + job.outputDirectory = (fs::current_path() / ".." / "bridge" / SanitizeFileName(job.name)).lexically_normal(); + } + + if (j.contains("resolution")) { + auto& resolution = j["resolution"]; + job.resolution = ivec2(resolution.at(0).get(), resolution.at(1).get()); + if (job.resolution.x <= 0 || job.resolution.y <= 0) + throw std::runtime_error("Invalid resolution"); + } + + if (j.contains("renderScale")) + job.renderScale = ParseRenderScale(j["renderScale"]); + + job.settleFrames = j.value("settleFrames", job.settleFrames); + job.loadTimeout = j.value("loadTimeout", job.loadTimeout); + job.fixedDeltaTime = j.value("fixedDt", job.fixedDeltaTime); + job.showWindow = j.value("showWindow", job.showWindow); + job.foreground = j.value("foreground", job.foreground); + job.waitGpu = j.value("waitGpu", job.waitGpu); + job.gpuWaitTimeout = j.value("gpuWaitTimeout", job.gpuWaitTimeout); + job.pathTrace = j.value("pathTrace", job.pathTrace); + job.realTime = j.value("realTime", job.realTime); + job.playerDisplay = j.value("playerDisplay", job.playerDisplay); + + if (job.fixedDeltaTime <= 0.0f) + throw std::runtime_error("fixedDt must be positive"); + + if (j.contains("settings")) + job.settings = j["settings"]; + + if (j.contains("variants")) { + for (const auto& variant : j["variants"]) { + CheckKeys(variant, { "name", "settings", "renderScale" }, "variant"); + VariantSpec spec; + spec.name = variant.at("name").get(); + spec.settings = variant.value("settings", json::object()); + if (variant.contains("renderScale")) + spec.renderScale = ParseRenderScale(variant["renderScale"]); + job.variants.push_back(spec); + } + } + + if (j.contains("inspect")) { + auto& inspect = j["inspect"]; + InspectSpec spec; + if (inspect.is_string()) { + spec.file = inspect.get(); + } + else if (inspect.is_object()) { + CheckKeys(inspect, { "file", "filter", "detail" }, "inspect"); + spec.file = inspect.value("file", spec.file); + if (inspect.contains("filter")) + spec.filter = ToStringList(inspect["filter"]); + if (inspect.contains("detail")) + spec.detail = ToStringList(inspect["detail"]); + } + if (!inspect.is_boolean() || inspect.get()) + job.inspect = spec; + } + + if (j.contains("queries")) + job.queries = j["queries"]; + if (j.contains("lua")) + job.lua = ParseLua(j["lua"], baseDirectory, ""); + + if (j.contains("edit")) { + auto& edit = j["edit"]; + CheckKeys(edit, { "operations", "output", "overwrite", "saveUnchanged", "dryRun", "queries", "lua", "textureFormat" }, "edit"); + EditSpec spec; + spec.operations = edit.value("operations", json::array()); + spec.output = edit.contains("output") ? ToAssetPath(edit["output"].get()) : ""; + spec.overwrite = edit.value("overwrite", false); + spec.saveUnchanged = edit.value("saveUnchanged", false); + spec.dryRun = edit.value("dryRun", false); + spec.textureFormat = edit.value("textureFormat", spec.textureFormat); + if (spec.textureFormat != "original" && spec.textureFormat != "ktx2") + throw std::runtime_error("edit.textureFormat has to be \"original\" or \"ktx2\""); + spec.queries = edit.value("queries", json::array()); + if (edit.contains("lua")) + spec.lua = ParseLua(edit["lua"], baseDirectory, ""); + job.edit = spec; + } + + if (j.contains("shots")) { + size_t index = 0; + for (const auto& shot : j["shots"]) + job.shots.push_back(ParseShot(shot, index++)); + } + + job.play = j.value("play", false); + job.duration = j.value("duration", 0.0f); + + if (j.contains("timeline")) { + for (const auto& event : j["timeline"]) { + EventSpec spec; + spec.time = event.value("t", 0.0f); + spec.type = GetEventType(event); + spec.action = ParseEventAction(event, spec.type, job.fixedDeltaTime, baseDirectory); + spec.data = event; + + if (event.contains("when")) { + const auto& when = event["when"]; + bool isLog = when.is_object() && when.contains("log") && when["log"].is_string(); + bool isLua = when.is_object() && when.contains("lua") && when["lua"].is_string(); + bool isProperty = when.is_object() && when.contains("entity") && when.contains("property"); + if (!isLog && !isLua && !isProperty) + throw std::runtime_error("A when condition needs a log text, a lua expression or entity, property, op and value like an " + "expectation: " + event.dump()); + spec.when = when; + spec.delay = event.value("delay", 0.0f); + spec.optional = event.value("optional", false); + } + + job.timeline.push_back(spec); + } + } + + if (j.contains("strips")) { + for (const auto& strip : j["strips"]) { + CheckKeys(strip, { "name", "from", "to", "every", "camera", "columns" }, "strip"); + StripSpec spec; + spec.name = strip.value("name", "strip" + std::to_string(job.strips.size())); + spec.from = strip.value("from", 0.0f); + spec.to = strip.value("to", job.duration); + spec.every = strip.value("every", spec.every); + spec.columns = strip.value("columns", 0); + if (strip.contains("camera")) { + spec.camera = ParseCamera(strip["camera"]); + spec.hasCamera = true; + } + if (spec.every <= 0.0f) + throw std::runtime_error("strip.every must be positive"); + job.strips.push_back(spec); + } + } + + if (j.contains("observer")) + job.observer = ParseCamera(j["observer"]); + + if (j.contains("scripts")) { + for (const auto& script : j["scripts"]) { + ScriptSpec spec; + if (script.is_string()) { + spec.path = script.get(); + } + else { + CheckKeys(script, { "script", "entity" }, "scripts"); + spec.path = script.at("script").get(); + spec.entity = script.value("entity", std::string()); + } + + // Scripts inside data/ are referenced like any other asset, others by their absolute path + fs::path path(spec.path); + auto resolved = path.is_absolute() ? path : (baseDirectory / path).lexically_normal(); + if (fs::exists(resolved)) { + auto assetPath = ToAssetPath(resolved.string()); + spec.path = fs::path(assetPath).is_absolute() ? resolved.generic_string() : assetPath; + } + else if (!fs::exists(GetAssetDirectory() / path)) { + throw std::runtime_error("Script " + spec.path + " doesn't exist"); + } + + job.scripts.push_back(spec); + } + } + + if (j.contains("track")) { + auto& track = j["track"]; + TrackSpec spec; + if (track.is_object()) { + CheckKeys(track, { "entities", "interval" }, "track"); + spec.entities = ToStringList(track.at("entities")); + spec.interval = track.value("interval", spec.interval); + } + else { + spec.entities = ToStringList(track); + } + job.track = spec; + } + + if (j.contains("compare")) { + const auto& compare = j["compare"]; + CheckKeys(compare, { "reference", "threshold", "maxPercent", "update" }, "compare"); + fs::path reference(compare.at("reference").get()); + job.compare = CompareSpec { + .reference = reference.is_absolute() ? reference : (baseDirectory / reference).lexically_normal(), + .threshold = compare.value("threshold", 8), + .maxPercent = compare.value("maxPercent", 0.5f), + .update = compare.value("update", false) + }; + } + + if (j.contains("profile")) { + auto& profile = j["profile"]; + if (profile.is_object()) { + CheckKeys(profile, { "frames" }, "profile"); + job.profileFrames = std::max(profile.value("frames", 32), 1); + } + else { + job.profileFrames = profile.get() ? 32 : 0; + } + } + + if (j.contains("hitches")) { + auto& hitches = j["hitches"]; + if (hitches.is_object()) { + CheckKeys(hitches, { "minimumMs", "relativeThreshold", "gpu" }, "hitches"); + job.hitches = HitchesSpec { + .minimumFrameTime = hitches.value("minimumMs", 40.0f), + .relativeThreshold = hitches.value("relativeThreshold", 2.0f), + .gpu = hitches.value("gpu", false) + }; + } + else if (hitches.get()) { + job.hitches = HitchesSpec(); + } + } + + if (j.contains("overlay")) { + auto& overlay = j["overlay"]; + OverlaySpec spec; + if (overlay.is_object()) { + CheckKeys(overlay, { "bounds", "markers", "axes", "players", "trails", "queries", "physics", "depthTest" }, "overlay"); + if (overlay.contains("bounds")) + spec.bounds = ToStringList(overlay["bounds"]); + spec.markers = overlay.value("markers", json::array()); + for (const auto& axes : overlay.value("axes", json::array())) + spec.axes.push_back(ToVec3(axes)); + spec.players = overlay.value("players", spec.players); + spec.trails = overlay.value("trails", spec.trails); + spec.queries = overlay.value("queries", spec.queries); + spec.physics = overlay.value("physics", spec.physics); + spec.depthTest = overlay.value("depthTest", spec.depthTest); + } + if (!overlay.is_boolean() || overlay.get()) + job.overlay = spec; + } + + if (j.contains("checks")) { + auto& checks = j["checks"]; + CheckKeys(checks, { "grounded", "penetration", "logErrors", "invalidTransforms", "failFast", "interval" }, "checks"); + if (checks.contains("grounded")) + job.checks.grounded = ParseGrounded(checks["grounded"]); + if (checks.contains("penetration")) + job.checks.penetration = ParsePenetration(checks["penetration"]); + if (checks.contains("logErrors") && checks["logErrors"].is_object()) { + CheckKeys(checks["logErrors"], { "ignore" }, "checks.logErrors"); + job.checks.logIgnore = ToStringList(checks["logErrors"].value("ignore", json::array())); + } + else { + job.checks.logErrors = checks.value("logErrors", job.checks.logErrors); + } + job.checks.invalidTransforms = checks.value("invalidTransforms", job.checks.invalidTransforms); + job.checks.failFast = checks.value("failFast", job.checks.failFast); + job.checks.interval = checks.value("interval", job.checks.interval); + } + + if (job.play && job.duration <= 0.0f) + throw std::runtime_error("A job with play = true needs a positive duration"); + if (!job.play && (!job.timeline.empty() || !job.strips.empty() || !job.scripts.empty())) + throw std::runtime_error("timeline, strips and scripts require play = true"); + if (job.play && job.edit) + throw std::runtime_error("edit and play can't be combined, scripts would create runtime entities that end up in the saved scene. " + "Run a second job on the edited scene instead"); + + // Without any explicit work, take a picture with the scene camera + if (job.shots.empty() && !job.play && !job.inspect && job.queries.empty() && !job.edit) + job.shots.push_back(ShotSpec { .name = "frame" }); + + return job; + + } + + // bridge.project.json in the directory of a job or above it: defaults for every job of a project and its preflight + static std::optional FindProjectFile(fs::path directory) { + + std::error_code error; + while (!directory.empty()) { + auto file = directory / "bridge.project.json"; + if (fs::exists(file, error)) + return file; + if (directory == directory.parent_path()) + break; + directory = directory.parent_path(); + } + return std::nullopt; + + } + + Job ParseCommandLine(const std::vector& args) { + + json j = json::object(); + fs::path baseDirectory = GetLaunchDirectory(); + std::optional projectFile; + + json cliShot = json::object(); + json cliCamera = json::object(); + bool validation = false; + bool sound = false; + bool pauseAtStart = false; + + // Skip the executable path + for (size_t i = 1; i < args.size(); i++) { + const auto& arg = args[i]; + + auto next = [&]() -> std::string { + + if (i + 1 >= args.size()) + throw std::runtime_error(arg + " expects a value"); + return args[++i]; + + }; + auto hasValue = [&]() { + + return i + 1 < args.size() && !args[i + 1].starts_with("--"); + + }; + + if (arg == "--help" || arg == "-h") + throw std::runtime_error(GetUsage()); + else if (arg == "--job" || (!arg.starts_with("--") && arg.ends_with(".json"))) { + auto path = ResolveUserPath(arg == "--job" ? next() : arg); + std::ifstream stream(path); + if (!stream.is_open()) + throw std::runtime_error("Couldn't open job file " + path.string()); + + json fileJob; + try { + fileJob = json::parse(stream, nullptr, true, true); + } + catch (const json::exception& e) { + throw std::runtime_error("Couldn't parse job file " + path.string() + ": " + e.what()); + } + + // Defaults of the project come first, the job replaces them, values given on the command line before the job + // file are kept + projectFile = FindProjectFile(path.parent_path()); + if (projectFile) { + std::ifstream projectStream(*projectFile); + auto project = json::parse(projectStream, nullptr, false, true); + if (!project.is_object()) + throw std::runtime_error("Couldn't parse " + projectFile->string()); + CheckKeys(project, { "defaults", "preflight", "description" }, projectFile->string()); + auto defaults = project.value("defaults", json::object()); + defaults.merge_patch(fileJob); + fileJob = defaults; + } + + fileJob.merge_patch(j); + j = fileJob; + if (!j.contains("name")) + j["name"] = path.stem().string(); + baseDirectory = path.parent_path(); + } + else if (arg == "--scene") + j["scene"] = next(); + else if (arg == "--out") + j["out"] = ResolveUserPath(next()).string(); + else if (arg == "--name") + j["name"] = next(); + else if (arg == "--resolution") { + auto value = next(); + auto parts = SplitList(value, 'x'); + if (parts.size() != 2) + throw std::runtime_error("--resolution expects WIDTHxHEIGHT"); + j["resolution"] = json::array({ std::stoi(parts[0]), std::stoi(parts[1]) }); + } + else if (arg == "--render-scale") + j["renderScale"] = std::stof(next()); + else if (arg == "--settle") + j["settleFrames"] = std::stoi(next()); + else if (arg == "--timeout") + j["loadTimeout"] = std::stof(next()); + else if (arg == "--show") + j["showWindow"] = true; + else if (arg == "--hidden") + j["showWindow"] = false; + else if (arg == "--foreground") + j["foreground"] = true; + else if (arg == "--no-wait-gpu") + j["waitGpu"] = false; + else if (arg == "--gpu-wait-timeout") + j["gpuWaitTimeout"] = std::stof(next()); + else if (arg == "--no-shots") + j["shots"] = json::array(); + else if (arg == "--fast") + j["realTime"] = false; + else if (arg == "--overlay") + j["overlay"] = true; + else if (arg == "--validation") + validation = true; + else if (arg == "--hitches") + // Only a number is the minimum, a job file can follow as well + j["hitches"] = hasValue() && std::isdigit(static_cast(args[i + 1][0])) ? + json { { "minimumMs", std::stof(next()) } } : json(true); + else if (arg == "--sound") + sound = true; + else if (arg == "--streaming" || arg == "--verbose") { + // Read before any job, streaming has to be set up before the scene loads + } + else if (arg == "--wait-gpu") { + // The default, accepted for older command lines + } + else if (arg == "--shader-dir") + // Read by the engine before it starts + next(); + else if (arg == "--profile") + j["profile"] = { { "frames", std::stoi(next()) } }; + else if (arg == "--pause") + pauseAtStart = true; + else if (arg == "--inspect") + j["inspect"] = hasValue() ? json(next()) : json(true); + else if (arg == "--play") { + j["play"] = true; + j["duration"] = std::stof(next()); + } + else if (arg == "--camera") + cliCamera["position"] = ParseVec3Argument(next(), arg); + else if (arg == "--look-at") + cliCamera["lookAt"] = ParseVec3Argument(next(), arg); + else if (arg == "--yaw") + cliCamera["yaw"] = std::stof(next()); + else if (arg == "--pitch") + cliCamera["pitch"] = std::stof(next()); + else if (arg == "--fov") + cliCamera["fov"] = std::stof(next()); + else if (arg == "--focus") + cliCamera["entity"] = next(); + else if (arg == "--distance") + cliCamera["distance"] = std::stof(next()); + else if (arg == "--overview") + cliCamera["mode"] = "overview"; + else if (arg == "--views") + cliShot["views"] = SplitList(next()); + else if (arg == "--passes") + cliShot["passes"] = SplitList(next()); + else if (arg == "--shot") + cliShot["name"] = next(); + else if (arg == "--set") { + // --set fog.density=0.02, the value is parsed as JSON if possible + auto assignment = next(); + auto equals = assignment.find('='); + if (equals == std::string::npos) + throw std::runtime_error("--set expects path=value"); + + auto path = assignment.substr(0, equals); + auto valueText = assignment.substr(equals + 1); + json value; + try { + value = json::parse(valueText); + } + catch (const json::exception&) { + value = valueText; + } + + json* node = &j["settings"]; + for (const auto& key : SplitList(path, '.')) + node = &(*node)[key]; + *node = value; + } + else { + throw std::runtime_error("Unknown argument '" + arg + "'\n\n" + GetUsage()); + } + } + + if (!cliCamera.empty()) + cliShot["camera"] = cliCamera; + if (!cliShot.empty()) { + if (!j.contains("shots")) + j["shots"] = json::array(); + j["shots"].push_back(cliShot); + } + + if (!j.contains("scene")) + throw std::runtime_error("No scene given\n\n" + GetUsage()); + + // The scene stands still from the start, e.g. for measurements that have to repeat + if (pauseAtStart && j.value("play", false)) { + auto timeline = j.value("timeline", json::array()); + timeline.insert(timeline.begin(), json { { "t", 0.0f }, { "pause", true } }); + j["timeline"] = timeline; + } + + auto job = ParseJob(j, baseDirectory); + job.validation = validation; + job.sound = sound; + if (projectFile) { + std::ifstream projectStream(*projectFile); + auto project = json::parse(projectStream, nullptr, false, true); + job.preflight = ToStringList(project.value("preflight", json::array())); + job.preflightDirectory = projectFile->parent_path(); + } + return job; + + } + + std::string GetUsage() { + + return R"(Usage: + AtlasBridge [options] + AtlasBridge --scene [options] + AtlasBridge --compose [--title ] [--columns ]
"; + auto table = object.as(); + auto length = table.size(); + if (length > 0) { + json array = json::array(); + for (size_t i = 1; i <= length; i++) + array.push_back(ToJson(table[i], depth + 1)); + return array; + } + json map = json::object(); + for (const auto& [key, value] : table) + map[key.is() ? key.as() : ToJson(key).dump()] = ToJson(value, depth + 1); + return map; + } + case sol::type::userdata: + if (object.is()) { + auto v = object.as(); + return json::array({ v.x, v.y }); + } + if (object.is()) + return FromVec3(object.as()); + if (object.is()) { + auto v = object.as(); + return json::array({ v.x, v.y, v.z, v.w }); + } + break; + default: + break; + } + + // Anything else as Lua would print it + auto lua = object.lua_state(); + object.push(lua); + size_t length = 0; + auto text = luaL_tolstring(lua, -1, &length); + std::string result(text, length); + lua_pop(lua, 2); + return result; + + } + +} diff --git a/src/bridge/LuaJob.h b/src/bridge/LuaJob.h new file mode 100644 index 000000000..537fb72e9 --- /dev/null +++ b/src/bridge/LuaJob.h @@ -0,0 +1,60 @@ +#pragma once + +#include "Common.h" + +#include "LuaEdit.h" +#include "SceneEditor.h" +#include "scene/Scene.h" + +#include + +#include +#include + +namespace Atlas::Bridge { + + class Report; + + // The Lua of a job: lua events, conditions and expectations. Snippets run in one environment over the globals of a + // script state (the scene's or the one of a game host), so they see what the game scripts put there and share their + // variables. The environment has scene (GetThisScene()) and the table Bridge of LuaEdit.h: Result(key, value) stores + // a value in report.json, Time() is the time of the job, Fail(message) fails it + class LuaJob { + + public: + // Bridge.Edit uses the edit state of the job, without one its own + void Start(sol::state& state, Scene::Scene* scene, Report& report, const std::function& time, + const EditHooks& hooks = {}, EditState* jobEditState = nullptr); + + // Empties the table Bridge, its functions refer to this object and the edit state + void Stop(); + + bool IsStarted() const { return environment.has_value(); } + + // Runs a chunk, Lua errors throw with the name of the snippet + json Run(const std::string& code, const std::string& name); + + // Evaluates an expression, or a chunk that returns a value + json Evaluate(const std::string& code, const std::string& name); + + // A lua expectation or condition: { "lua": "...", "op": ">=", "value": 3 }, without op the value has to be true + json Expect(const json& expectation, bool& passed); + + // Only nil and false are false, like in Lua + static bool IsTrue(const json& value); + + // Compiles the code like Evaluate would without running it, returns the error or an empty string + static std::string Compile(const std::string& code, const std::string& name, bool expression); + + static json ToJson(const sol::object& object, int32_t depth = 0); + + private: + sol::state* state = nullptr; + std::optional environment; + sol::table bridgeTable; + // Edit operations of Bridge.Edit + EditState editState; + + }; + +} diff --git a/src/bridge/MaterialGraphTools.cpp b/src/bridge/MaterialGraphTools.cpp new file mode 100644 index 000000000..b95c046e1 --- /dev/null +++ b/src/bridge/MaterialGraphTools.cpp @@ -0,0 +1,959 @@ +#include "MaterialGraphTools.h" +#include "SceneFile.h" + +#include "loader/AssetLoader.h" +#include "loader/AssetReferences.h" +#include "materialgraph/MaterialGraphSerializer.h" +#include "materialgraph/NodeLibrary.h" +#include "resource/ResourceManager.h" +#include "streaming/TextureStreaming.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace Atlas::Bridge { + + using namespace MaterialGraph; + using Loader::AssetReferences; + + // Without trailing zeros, e.g. 8 or 0.25 + static std::string FormatNumber(float value) { + + auto text = FormatFloat(value, 3); + text.erase(text.find_last_not_of('0') + 1); + if (text.ends_with('.')) + text.pop_back(); + return text == "-0" ? "0" : text; + + } + + static std::string GetTypeName(ValueType type, bool isColor = false) { + + return isColor ? "color" : NodeLibrary::GetTypeName(type); + + } + + // Components a value of the type uses, generic values use all of them + static int32_t GetComponentCount(ValueType type) { + + if (type == ValueType::Texture) + return 1; + return type == ValueType::Generic ? 4 : int32_t(type) + 1; + + } + + static std::string FormatValue(vec4 value, int32_t components) { + + if (components == 1) + return FormatNumber(value.x); + + std::string text = "("; + for (int32_t i = 0; i < components; i++) + text += (i > 0 ? ", " : "") + FormatNumber(value[i]); + return text + ")"; + + } + + static json ToJson(vec4 value, int32_t components) { + + if (components == 1) + return Round(value.x, 4); + + json array = json::array(); + for (int32_t i = 0; i < components; i++) + array.push_back(Round(value[i], 4)); + return array; + + } + + // A number sets all components (only the first one without splat), an array the first ones, objects use the keys of + // the files ({ "x", "y", "z", "w" }). Components which aren't given keep their current value + static vec4 ToVec4(const json& value, vec4 current, bool splat, int32_t components, const std::string& what) { + + if (value.is_array() && value.size() > size_t(components)) + throw std::runtime_error(what + ": " + std::to_string(value.size()) + " components for a value with " + std::to_string(components)); + + if (value.is_number()) + return splat ? vec4(value.get()) : vec4(value.get(), current.y, current.z, current.w); + + if (value.is_array() && !value.empty() && value.size() <= 4 && + std::all_of(value.begin(), value.end(), [](const json& component) { return component.is_number(); })) { + for (size_t i = 0; i < value.size(); i++) + current[int32_t(i)] = value[i].get(); + return current; + } + + if (value.is_object()) { + const std::string names[] = { "x", "y", "z", "w" }; + for (const auto& [key, component] : value.items()) { + auto index = int32_t(std::find(std::begin(names), std::end(names), key) - std::begin(names)); + if (index >= components || !component.is_number()) + throw std::runtime_error(what + ": '" + key + "' isn't a number for a component of a value with " + + std::to_string(components) + " components"); + current[index] = component.get(); + } + return current; + } + + throw std::runtime_error(what + ": expected a number or an array of up to 4 numbers, got " + value.dump()); + + } + + static vec2 ToVec2Array(const json& value, const std::string& what) { + + if (!value.is_array() || value.size() != 2 || !value[0].is_number() || !value[1].is_number()) + throw std::runtime_error(what + ": expected [x, y], got " + value.dump()); + return vec2(value[0].get(), value[1].get()); + + } + + static std::string Join(const std::vector& names) { + + std::string text; + for (const auto& name : names) + text += (text.empty() ? "'" : ", '") + name + "'"; + return text.empty() ? "none" : text; + + } + + static std::string GetLabel(const Node& node) { + + return "#" + std::to_string(node.id) + " " + node.type + (node.name.empty() ? "" : " '" + node.name + "'"); + + } + + // Comments and frames keep their text in the name, it doesn't name the node + static bool IsNote(const Node& node) { + + auto definition = NodeLibrary::Find(node); + return definition && (definition->kind == NodeKind::Comment || definition->kind == NodeKind::Frame); + + } + + static std::vector GetPinNames(const NodeDefinition& definition, bool inputs) { + + std::vector names; + if (inputs) { + for (const auto& input : definition.inputs) + names.push_back(input.name); + } + else { + for (const auto& output : definition.outputs) + names.push_back(output.name); + } + return names; + + } + + static GraphDocument ReadDocument(const std::string& path) { + + std::ifstream stream(GetAssetDirectory() / path); + if (!stream.is_open()) + throw std::runtime_error("couldn't open the graph " + path); + + auto j = json::parse(stream); + AssetReferences::ResolveReferences(j, AssetReferences::Type::MaterialGraph, path); + + GraphDocument document; + for (auto& node : j.at("nodes")) { + if (!node.contains("texturePath")) + continue; + document.texturePaths[node.at("id").get()] = node["texturePath"].get(); + node.erase("texturePath"); + } + + document.graph = CreateRef(); + from_json(j, *document.graph); + return document; + + } + + static GraphDocument& GetDocument(const std::string& path, std::map& documents) { + + auto iter = documents.find(path); + if (iter == documents.end()) + iter = documents.emplace(path, ReadDocument(path)).first; + return iter->second; + + } + + static json SerializeDocument(const GraphDocument& document, const std::string& path) { + + json j; + to_json(j, *document.graph); + for (auto& node : j["nodes"]) { + auto iter = document.texturePaths.find(node["id"].get()); + if (iter != document.texturePaths.end()) + node["texturePath"] = iter->second; + } + + AssetReferences::MakeReferences(j, AssetReferences::Type::MaterialGraph, path); + return j; + + } + + // A #id, a key of the operation, a parameter name or a node type which occurs once + static Node* FindNode(Graph& graph, const std::map& keys, const std::string& reference, std::string& error) { + + if (reference.starts_with("#")) { + uint32_t id = 0; + auto result = std::from_chars(reference.data() + 1, reference.data() + reference.size(), id); + auto node = result.ec == std::errc() ? graph.GetNode(id) : nullptr; + if (!node) + error = "no node " + reference; + return node; + } + + if (auto iter = keys.find(reference); iter != keys.end()) { + auto node = graph.GetNode(iter->second); + if (!node) + error = "the node '" + reference + "' was removed"; + return node; + } + + std::vector matches; + for (auto& node : graph.nodes) + if (node.name == reference && !IsNote(node)) + matches.push_back(&node); + if (matches.empty()) { + for (auto& node : graph.nodes) + if (node.type == reference) + matches.push_back(&node); + } + + if (matches.size() == 1) + return matches.front(); + + if (matches.size() > 1) { + std::vector labels; + for (auto node : matches) + labels.push_back(GetLabel(*node)); + error = "'" + reference + "' matches " + std::to_string(matches.size()) + " nodes (" + Join(labels) + "), use a #id or a key"; + return nullptr; + } + + std::vector candidates; + for (const auto& [key, _] : keys) + candidates.push_back(key); + for (const auto& node : graph.nodes) { + if (!node.name.empty() && !IsNote(node)) + candidates.push_back(node.name); + candidates.push_back(node.type); + } + error = "no node '" + reference + "' (a #id, a key of the operation, a parameter name or a node type which occurs once), closest: " + + Join(FindClosestNames(candidates, reference)); + return nullptr; + + } + + static Node& GetNode(Graph& graph, const std::map& keys, const std::string& reference) { + + std::string error; + auto node = FindNode(graph, keys, reference, error); + if (!node) + throw std::runtime_error(error); + return *node; + + } + + // "reference" for nodes with one output or "reference.Pin" + static std::pair FindOutput(Graph& graph, const std::map& keys, const std::string& text) { + + std::string error; + auto node = FindNode(graph, keys, text, error); + std::string pin; + if (!node) { + auto dot = text.rfind('.'); + if (dot == std::string::npos) + throw std::runtime_error(error); + node = &GetNode(graph, keys, text.substr(0, dot)); + pin = text.substr(dot + 1); + } + + auto definition = NodeLibrary::Find(*node); + if (!definition) + throw std::runtime_error(GetLabel(*node) + " has an unknown type"); + auto outputs = GetPinNames(*definition, false); + + if (pin.empty()) { + if (outputs.size() != 1) + throw std::runtime_error(GetLabel(*node) + " has the outputs " + Join(outputs) + ", name one, e.g. '" + text + "." + + (outputs.empty() ? "" : outputs.front()) + "'"); + pin = outputs.front(); + } + else if (!definition->FindOutput(pin)) { + throw std::runtime_error(GetLabel(*node) + " has no output '" + pin + "', its outputs: " + Join(outputs)); + } + + return { node->id, pin }; + + } + + static void ApplyNodeEntry(Graph& graph, GraphDocument& document, const std::map& keys, uint32_t id, const json& entry) { + + static const std::set known = { "key", "type", "node", "remove", "name", "value", "position", "size", "range", "group", + "order", "texture", "inputs", "code", "codeInputs", "codeOutputType" }; + CheckKeys(entry, known, "materialGraph node " + entry.dump()); + + auto node = graph.GetNode(id); + auto definition = NodeLibrary::Find(*node); + auto label = GetLabel(*node); + + if (entry.contains("name")) + node->name = entry["name"].get(); + if (entry.contains("value")) { + // Texture parameters keep their coordinate scale in x and the fallback in y, the vertex output its settings + auto isValue = definition && (definition->kind == NodeKind::Constant || definition->kind == NodeKind::Parameter); + auto splat = isValue && definition->valueType != ValueType::Texture; + auto components = 4; + if (isValue) + components = definition->valueType == ValueType::Texture ? 2 : GetComponentCount(definition->valueType); + node->value = ToVec4(entry["value"], node->value, splat, components, label + " value"); + } + if (entry.contains("position")) + node->position = ToVec2Array(entry["position"], label + " position"); + if (entry.contains("size")) + node->size = ToVec2Array(entry["size"], label + " size"); + if (entry.contains("range")) + node->range = ToVec2Array(entry["range"], label + " range"); + if (entry.contains("group")) + node->group = entry["group"].get(); + if (entry.contains("order")) + node->order = entry["order"].get(); + + if (entry.contains("code") || entry.contains("codeInputs") || entry.contains("codeOutputType")) { + if (node->type != NodeLibrary::codeType) + throw std::runtime_error(label + " isn't a code node, only those have code"); + + auto checkType = [&](ValueType type, const std::string& what) { + if (type == ValueType::Texture || type == ValueType::Generic) + throw std::runtime_error(label + ": " + what + " needs one of the types float, vec2, vec3, vec4"); + }; + + if (entry.contains("code")) + node->code = entry["code"].get(); + if (entry.contains("codeOutputType")) { + node->codeOutputType = NodeLibrary::FindType(entry["codeOutputType"].get()); + checkType(node->codeOutputType, "the result"); + } + if (entry.contains("codeInputs")) { + // The format of graph files, [["name", "vec3"], ...] in the order of the arguments + node->codeInputs = entry["codeInputs"].get>(); + for (const auto& input : node->codeInputs) + checkType(input.type, "the input " + input.name); + } + NodeLibrary::UpdateCodeDefinition(*node); + definition = NodeLibrary::Find(*node); + } + + if (entry.contains("texture")) { + if (!definition || definition->valueType != ValueType::Texture) + throw std::runtime_error(label + " has no texture, only texture parameters have one"); + if (entry["texture"].is_null()) { + document.texturePaths.erase(id); + } + else { + auto path = ToAssetPath(entry["texture"].get()); + if (!fs::exists(GetAssetDirectory() / path)) + throw std::runtime_error(label + ": no texture file " + path); + document.texturePaths[id] = path; + } + } + + if (!entry.contains("inputs")) + return; + + for (const auto& [pin, value] : entry["inputs"].items()) { + node = graph.GetNode(id); + auto input = definition ? definition->FindInput(pin) : nullptr; + if (!input) + throw std::runtime_error(label + " has no input '" + pin + "', its inputs: " + + (definition ? Join(GetPinNames(*definition, true)) : "unknown")); + + if (value.is_string()) { + auto [fromId, fromPin] = FindOutput(graph, keys, value.get()); + auto from = graph.GetNode(fromId); + if (!graph.Connect(fromId, fromPin, id, pin)) { + auto output = NodeLibrary::Find(*from)->FindOutput(fromPin); + auto reason = fromId == id ? "a node can't use its own output" : (output->type == ValueType::Texture) != (input->type == ValueType::Texture) ? + "textures only connect to textures" : "the link isn't valid"; + throw std::runtime_error("can't connect " + GetLabel(*from) + "." + fromPin + " to " + label + "." + pin + ": " + reason); + } + continue; + } + + graph.Disconnect(id, pin); + if (value.is_null()) { + node->inputValues.erase(pin); + continue; + } + if (input->type == ValueType::Texture) + throw std::runtime_error(label + "." + pin + " is a texture input, it only takes a link"); + auto current = node->inputValues.contains(pin) ? node->inputValues[pin] : input->defaultValue; + node->inputValues[pin] = ToVec4(value, current, true, GetComponentCount(input->type), label + "." + pin); + } + + } + + // New nodes without a position go into the column of their way to the outputs (like Arrange in the editor), below + // the nodes already there + static void PlaceNodes(Graph& graph, const std::vector& unplaced) { + + std::set pending(unplaced.begin(), unplaced.end()); + if (pending.empty()) + return; + + std::unordered_map depths; + for (const auto& node : graph.nodes) + depths[node.id] = 0; + for (size_t i = 0; i < graph.nodes.size(); i++) { + auto changed = false; + for (const auto& link : graph.links) { + auto depth = depths[link.toNode] + 1; + if (depth > depths[link.fromNode]) { + depths[link.fromNode] = depth; + changed = true; + } + } + if (!changed) + break; + } + + auto right = 0.0f; + auto hasPlaced = false; + for (const auto& node : graph.nodes) { + if (pending.contains(node.id) || IsNote(node)) + continue; + right = hasPlaced ? std::max(right, node.position.x) : node.position.x; + hasPlaced = true; + } + + const float columnSpacing = 310.0f; + const float nodeHeight = 240.0f; + for (auto id : unplaced) { + auto node = graph.GetNode(id); + if (!node) + continue; + + auto x = right - float(depths[id]) * columnSpacing; + auto y = 0.0f; + auto hasNeighbour = false; + for (const auto& other : graph.nodes) { + if (pending.contains(other.id) || IsNote(other) || std::abs(other.position.x - x) >= 0.5f * columnSpacing) + continue; + y = hasNeighbour ? std::max(y, other.position.y + nodeHeight) : other.position.y + nodeHeight; + hasNeighbour = true; + } + node->position = vec2(x, y); + pending.erase(id); + } + + } + + static json DescribeParameters(const CompiledGraph& compiled) { + + json parameters = json::array(); + for (const auto& parameter : compiled.parameters) { + json description = { { "name", parameter.name }, { "type", GetTypeName(parameter.type, parameter.isColor) } }; + if (parameter.type != ValueType::Texture) + description["default"] = ToJson(parameter.defaultValue, GetComponentCount(parameter.type)); + if (parameter.HasRange()) + description["range"] = { parameter.range.x, parameter.range.y }; + if (!parameter.group.empty()) + description["group"] = parameter.group; + parameters.push_back(description); + } + return parameters; + + } + + static json DescribeCompiled(const CompiledGraph& compiled) { + + return { { "vertexOffset", compiled.hasVertexOffset }, { "surface", compiled.hasSurface }, { "opacity", compiled.hasOpacity }, + { "uniformOpacity", compiled.hasUniformOpacity }, { "writesNormal", compiled.writesNormal }, { "shadowPipeline", compiled.UsesShadowPipeline() } }; + + } + + static std::string FormatErrors(const Graph& graph, const CompiledGraph& compiled) { + + std::string text; + for (const auto& error : compiled.errors) { + auto node = graph.GetNode(error.nodeId); + text += "\n " + (node ? GetLabel(*node) + ": " : std::string()) + error.message; + } + return text; + + } + + json EditMaterialGraph(const json& operation, MaterialGraphEdits& edits) { + + CheckKeys(operation, { "op", "graph", "create", "from", "overwrite", "name", "maxDisplacement", "nodes" }, "materialGraph"); + + auto path = ToAssetPath(operation.at("graph").get()); + if (fs::path(path).extension() != ".aematgraph") + throw std::runtime_error(path + " isn't a .aematgraph file"); + + auto& documents = edits.documents; + auto create = operation.value("create", false) || operation.contains("from"); + auto exists = documents.contains(path) || fs::exists(GetAssetDirectory() / path); + if (create && exists && !operation.value("overwrite", false)) + throw std::runtime_error(path + " already exists, set \"overwrite\": true or leave out \"create\""); + if (!create && !exists) + throw std::runtime_error(path + " doesn't exist, set \"create\": true"); + + // Edits a copy, a failing operation leaves the document as it was + GraphDocument document; + if (operation.contains("from")) { + document = GetDocument(ToAssetPath(operation["from"].get()), documents); + document.graph = CreateRef(*document.graph); + document.graph->name = fs::path(path).stem().string(); + } + else if (create) { + document.graph = Graph::CreateDefault(); + document.graph->name = fs::path(path).stem().string(); + } + else { + document = GetDocument(path, documents); + document.graph = CreateRef(*document.graph); + } + + auto& graph = *document.graph; + if (operation.contains("name")) + graph.name = operation["name"].get(); + if (operation.contains("maxDisplacement")) + graph.maxDisplacement = operation["maxDisplacement"].get(); + + // Nodes are added and found first, links may point to nodes of later entries + auto entries = operation.value("nodes", json::array()); + std::map keys; + std::vector entryNodes, added, unplaced; + for (const auto& entry : entries) { + if (entry.contains("type") == entry.contains("node")) + throw std::runtime_error("a node entry has either \"type\" (adds a node) or \"node\" (changes one): " + entry.dump()); + + uint32_t id = 0; + if (entry.contains("type")) { + auto type = entry["type"].get(); + if (!NodeLibrary::Find(type)) { + std::vector types; + for (const auto& definition : NodeLibrary::GetDefinitions()) + types.push_back(definition.type); + throw std::runtime_error("unknown node type '" + type + "', closest: " + Join(FindClosestNames(types, type)) + + ". 'inspect nodes' lists all of them"); + } + id = graph.AddNode(type).id; + added.push_back(id); + if (!entry.contains("position")) + unplaced.push_back(id); + } + else { + id = GetNode(graph, keys, entry["node"].get()).id; + } + + if (entry.contains("key")) { + auto key = entry["key"].get(); + if (!keys.emplace(key, id).second) + throw std::runtime_error("the key '" + key + "' is used twice"); + } + entryNodes.push_back(id); + } + + int32_t removed = 0; + for (size_t i = 0; i < entries.size(); i++) { + auto id = entryNodes[i]; + if (!graph.GetNode(id)) + throw std::runtime_error("the node of " + entries[i].dump() + " was removed by an earlier entry"); + + if (entries[i].value("remove", false)) { + graph.RemoveNode(id); + document.texturePaths.erase(id); + removed++; + continue; + } + ApplyNodeEntry(graph, document, keys, id, entries[i]); + } + PlaceNodes(graph, unplaced); + + auto compiled = graph.Compile(); + if (!compiled->errors.empty()) + throw std::runtime_error(path + " doesn't compile:" + FormatErrors(graph, *compiled)); + + documents[path] = document; + edits.changed.insert(path); + + json nodes = json::object(); + for (const auto& [key, id] : keys) + nodes[key] = id; + + return { { "graph", path }, { "created", create }, { "nodes", nodes }, { "added", added.size() }, { "removed", removed }, + { "parameters", DescribeParameters(*compiled) }, { "compiled", DescribeCompiled(*compiled) } }; + + } + + json SaveMaterialGraphs(MaterialGraphEdits& edits) { + + json saved = json::array(); + for (const auto& path : edits.changed) { + auto file = GetAssetDirectory() / path; + json entry = { { "graph", path } }; + if (fs::exists(file)) { + auto backup = file; + backup += ".backup"; + if (!fs::exists(backup)) + fs::copy_file(file, backup); + entry["backup"] = backup.string(); + } + + auto document = SerializeDocument(edits.documents.at(path), path); + if (!Loader::AssetLoader::WriteJson(file.string(), document, Loader::JsonFormat::Indented)) + throw std::runtime_error("Couldn't write the material graph " + path); + saved.push_back(entry); + } + edits.changed.clear(); + + return saved; + + } + + Ref CreateGraph(const GraphDocument& document) { + + // Parameters take their default textures from the nodes, so the graph is compiled with them + auto graph = CreateRef(*document.graph); + for (const auto& [id, path] : document.texturePaths) { + if (auto node = graph->GetNode(id)) + node->texture = ResourceManager::GetOrLoadResourceWithLoaderAsync(path, + Streaming::TextureStreaming::LoadTexture, false, Texture::Wrapping::Repeat, Texture::Filtering::Anisotropic); + } + graph->Compile(); + + return graph; + + } + + std::vector FindMaterialFiles(const json& patterns) { + + auto paths = FindAssetFiles(patterns, ".aematerial"); + if (paths.empty()) + throw std::runtime_error("no material matches " + patterns.dump()); + return paths; + + } + + void CheckAssignMaterialGraph(const json& operation) { + + CheckKeys(operation, { "op", "materials", "graph", "values", "textures", "reset" }, "assignMaterialGraph"); + if (operation.contains("graph") && operation["graph"].is_null() && (operation.contains("values") || operation.contains("textures"))) + throw std::runtime_error("values and textures need a graph, \"graph\" is null"); + + } + + static Ref GetCompiledGraph(const std::string& path, MaterialGraphEdits& edits) { + + auto& document = GetDocument(path, edits.documents); + auto compiled = document.graph->GetCompiled(); + return compiled ? compiled : document.graph->Compile(); + + } + + json ToParameterJson(const Parameter& parameter, vec4 value) { + + return ToJson(value, GetComponentCount(parameter.type)); + + } + + const Parameter* FindParameter(const CompiledGraph& compiled, const std::string& name) { + + auto iter = std::find_if(compiled.parameters.begin(), compiled.parameters.end(), [&](const Parameter& parameter) { + return parameter.name == name; }); + return iter != compiled.parameters.end() ? &*iter : nullptr; + + } + + vec4 ToParameterValue(const Parameter& parameter, const json& value, vec4 current) { + + if (parameter.type == ValueType::Texture) + throw std::runtime_error("'" + parameter.name + "' is a texture parameter, set it with \"textures\""); + return ToVec4(value, current, true, GetComponentCount(parameter.type), "the value of '" + parameter.name + "'"); + + } + + void CheckGraphValues(const json& operation, const CompiledGraph& compiled, const std::string& graphPath) { + + auto find = [&](const std::string& name) -> const Parameter& { + + auto parameter = FindParameter(compiled, name); + if (!parameter) { + std::vector names; + for (const auto& candidate : compiled.parameters) + names.push_back(candidate.name); + throw std::runtime_error("the graph " + graphPath + " has no parameter '" + name + "', its parameters: " + Join(names)); + } + return *parameter; + + }; + + for (const auto& [name, value] : operation.value("values", json::object()).items()) { + const auto& parameter = find(name); + ToParameterValue(parameter, value, parameter.defaultValue); + } + + for (const auto& [name, value] : operation.value("textures", json::object()).items()) { + const auto& parameter = find(name); + if (parameter.type != ValueType::Texture) + throw std::runtime_error("'" + name + "' isn't a texture parameter, set it with \"values\""); + if (!value.is_null() && !fs::exists(GetAssetDirectory() / ToAssetPath(value.get()))) + throw std::runtime_error("no texture file " + value.get() + " for '" + name + "'"); + } + + auto reset = operation.value("reset", json()); + if (reset.is_array()) { + for (const auto& name : reset) + find(name.get()); + } + + } + + void CheckMaterialGraphOperations(const json& operations, std::vector& issues) { + + MaterialGraphEdits edits; + for (size_t i = 0; i < operations.size(); i++) { + const auto& operation = operations[i]; + auto type = operation.value("op", std::string()); + if (type != "materialGraph" && type != "assignMaterialGraph") + continue; + + auto where = "edit operation " + std::to_string(i + 1) + " (" + type + ")"; + try { + if (type == "materialGraph") { + EditMaterialGraph(operation, edits); + continue; + } + + CheckAssignMaterialGraph(operation); + auto patterns = ToAssetPatterns(operation.at("materials")); + auto missingDirectory = std::any_of(patterns.begin(), patterns.end(), [](const std::string& pattern) { + return !fs::is_directory(GetAssetDirectory() / fs::path(pattern).parent_path()); }); + auto materials = missingDirectory ? std::vector() : FindAssetFiles(patterns, ".aematerial"); + if (materials.empty()) { + issues.push_back("NOTE: " + where + ": no material matches " + operation["materials"].dump() + ", earlier operations may create it"); + continue; + } + + std::map assigned; + for (const auto& material : materials) { + std::string graphPath; + if (operation.contains("graph")) { + graphPath = operation["graph"].is_null() ? std::string() : ToAssetPath(operation["graph"].get()); + assigned[material] = graphPath; + } + else if (edits.assigned.contains(material)) { + graphPath = edits.assigned[material]; + } + else { + std::ifstream stream(GetAssetDirectory() / material); + auto j = json::parse(stream); + AssetReferences::ResolveReferences(j, AssetReferences::Type::Material, material); + graphPath = j.value("graphPath", std::string()); + } + + if (graphPath.empty()) { + if (operation.contains("values") || operation.contains("textures")) + throw std::runtime_error(material + " has no graph, set \"graph\""); + continue; + } + + auto compiled = GetCompiledGraph(graphPath, edits); + if (!compiled->errors.empty()) + throw std::runtime_error("the graph " + graphPath + " doesn't compile"); + CheckGraphValues(operation, *compiled, graphPath); + } + // A failing operation ends the edit, only valid ones assign their graph for the next ones + for (const auto& [material, graphPath] : assigned) + edits.assigned[material] = graphPath; + } + catch (const std::exception& e) { + issues.push_back("ERROR: " + where + ": " + e.what()); + } + } + + } + + static std::string DescribeStages(const CompiledGraph& compiled, uint32_t nodeId) { + + auto iter = compiled.nodeStages.find(nodeId); + if (iter == compiled.nodeStages.end() || iter->second == 0) + return "unused"; + if (iter->second == AllStages) + return "vertex + surface"; + return iter->second == VertexStage ? "vertex" : "surface"; + + } + + int32_t InspectMaterialGraph(const fs::path& file, const std::vector& filters, bool printCode, const fs::path& output) { + + // References in packages are relative to the file, which needs its path below the data directory + auto relative = file.lexically_normal().lexically_relative(GetAssetDirectory()); + auto path = !relative.empty() && relative.native()[0] != '.' ? relative.generic_string() : file.generic_string(); + + auto document = ReadDocument(path); + auto& graph = *document.graph; + auto compiled = graph.Compile(); + + Print(path + ": '" + graph.name + "', " + std::to_string(graph.nodes.size()) + " nodes, " + std::to_string(graph.links.size()) + + " links, largest displacement " + FormatNumber(graph.maxDisplacement)); + + if (!compiled->errors.empty()) { + Print(" doesn't compile:" + FormatErrors(graph, *compiled)); + } + else { + std::vector parts; + if (compiled->hasVertexOffset) + parts.push_back("moves vertices"); + if (compiled->hasSurface) + parts.push_back(compiled->writesNormal ? "surface with normals" : "surface"); + if (compiled->hasOpacity) + parts.push_back(compiled->hasUniformOpacity ? "opacity per draw" : "cutout opacity"); + if (parts.empty()) + parts.push_back("nothing, the material renders like a regular one"); + std::string text; + for (const auto& part : parts) + text += (text.empty() ? "" : ", ") + part; + Print(" compiles: " + text); + } + + if (!compiled->parameters.empty()) + Print(" parameters:"); + for (const auto& parameter : compiled->parameters) { + auto line = " " + parameter.name + ": " + GetTypeName(parameter.type, parameter.isColor); + if (parameter.type == ValueType::Texture) { + auto texture = document.texturePaths.find(parameter.nodeId); + const char* fallbacks[] = { "white", "black", "normal" }; + line += texture != document.texturePaths.end() ? " " + texture->second : std::string(" ") + fallbacks[int32_t(parameter.fallback)]; + } + else { + line += " " + FormatValue(parameter.defaultValue, GetComponentCount(parameter.type)); + } + if (parameter.HasRange()) + line += " [" + FormatNumber(parameter.range.x) + ", " + FormatNumber(parameter.range.y) + "]"; + if (!parameter.group.empty()) + line += ", group " + parameter.group; + Print(line); + } + + Print(" nodes (stages they run in):"); + for (const auto& node : graph.nodes) { + if (!filters.empty() && !MatchAnyPattern(filters, node.type) && !MatchAnyPattern(filters, node.name) && + !MatchAnyPattern(filters, "#" + std::to_string(node.id))) + continue; + + auto definition = NodeLibrary::Find(node); + auto line = " " + GetLabel(node); + if (definition && (definition->kind == NodeKind::Constant || (definition->kind == NodeKind::Parameter && definition->valueType != ValueType::Texture))) + line += " = " + FormatValue(node.value, GetComponentCount(definition->valueType)); + if (auto texture = document.texturePaths.find(node.id); texture != document.texturePaths.end()) + line += " " + texture->second; + if (definition && !IsNote(node)) + line += " (" + DescribeStages(*compiled, node.id) + ")"; + Print(line); + + if (!definition) + continue; + for (const auto& input : definition->inputs) { + if (auto link = graph.GetInputLink(node.id, input.name)) { + auto from = graph.GetNode(link->fromNode); + Print(" " + input.name + " <- " + (from ? GetLabel(*from) : "#" + std::to_string(link->fromNode)) + "." + link->fromPin); + } + else if (auto value = node.inputValues.find(input.name); value != node.inputValues.end()) { + Print(" " + input.name + " = " + FormatValue(value->second, GetComponentCount(input.type))); + } + } + } + + std::vector> code = { + { "main vertex", compiled->mainVertexCode }, { "main fragment", compiled->mainFragmentCode }, + { "shadow vertex", compiled->shadowVertexCode }, { "shadow fragment", compiled->shadowFragmentCode } }; + if (printCode) { + for (const auto& [stage, text] : code) + if (!text.empty()) + Print(" // " + stage + "\n" + text); + } + + if (!output.empty()) { + json errors = json::array(); + for (const auto& error : compiled->errors) + errors.push_back({ { "node", error.nodeId }, { "message", error.message } }); + json result = { { "graph", SerializeDocument(document, path) }, { "errors", errors }, + { "parameters", DescribeParameters(*compiled) }, { "compiled", DescribeCompiled(*compiled) } }; + json stages = json::object(); + for (const auto& node : graph.nodes) + stages[std::to_string(node.id)] = DescribeStages(*compiled, node.id); + result["stages"] = stages; + if (printCode) { + for (const auto& [stage, text] : code) + result["code"][stage] = text; + } + if (!WriteFileAtomic(output, result.dump(2))) + throw std::runtime_error("Couldn't write " + output.string()); + Print(" written to " + output.string()); + } + + return compiled->errors.empty() ? 0 : 1; + + } + + int32_t InspectMaterialGraphNodes(const std::vector& filters) { + + const char* stageNames[] = { "", "vertex only", "surface only", "" }; + + // Unconnected inputs with an expression read what an input node gives, e.g. the object position + std::unordered_map expressionNames; + for (const auto& definition : NodeLibrary::GetDefinitions()) + if (definition.inputs.empty() && definition.outputs.size() == 1 && !definition.outputs.front().expression.empty()) + expressionNames.emplace(definition.outputs.front().expression, definition.type); + + std::string category; + for (const auto& definition : NodeLibrary::GetDefinitions()) { + if (!filters.empty() && !MatchAnyPattern(filters, definition.type) && !MatchAnyPattern(filters, definition.category)) + continue; + + if (definition.category != category) { + category = definition.category; + Print(category + ":"); + } + + std::string inputs; + for (const auto& input : definition.inputs) { + auto text = input.name + " " + GetTypeName(input.type); + if (!input.defaultExpression.empty()) + text += " = " + (expressionNames.contains(input.defaultExpression) ? expressionNames[input.defaultExpression] : input.defaultExpression); + else if (input.type != ValueType::Texture) + text += " = " + FormatValue(input.defaultValue, GetComponentCount(input.type)); + inputs += (inputs.empty() ? "" : ", ") + text; + } + + std::string outputs; + for (const auto& output : definition.outputs) + outputs += (outputs.empty() ? "" : ", ") + output.name + " " + GetTypeName(output.type); + + auto line = " " + definition.type; + if (definition.kind == NodeKind::Constant || definition.kind == NodeKind::Parameter) + line += " (value " + GetTypeName(definition.valueType, definition.isColor) + " " + + FormatValue(definition.defaultValue, definition.valueType == ValueType::Texture ? 2 : GetComponentCount(definition.valueType)) + ")"; + if (definition.stages != AllStages) + line += std::string(" [") + stageNames[definition.stages & AllStages] + "]"; + line += ": " + (inputs.empty() ? std::string("-") : inputs) + " -> " + (outputs.empty() ? std::string("-") : outputs); + Print(line); + if (!filters.empty() && !definition.tooltip.empty()) + Print(" " + definition.tooltip); + } + + return 0; + + } + +} diff --git a/src/bridge/MaterialGraphTools.h b/src/bridge/MaterialGraphTools.h new file mode 100644 index 000000000..fea6ab269 --- /dev/null +++ b/src/bridge/MaterialGraphTools.h @@ -0,0 +1,66 @@ +#pragma once + +#include "Common.h" + +#include "materialgraph/MaterialGraph.h" + +#include +#include + +namespace Atlas::Bridge { + + // A graph file as the operations of a job edit it. Textures aren't loaded, the nodes keep their paths + struct GraphDocument { + + Ref graph; + std::map texturePaths; + + }; + + // The graphs of the operations of a job by their asset path. Nothing is written before the checks of the edit passed + struct MaterialGraphEdits { + + std::map documents; + // Documents to write, the files still have the state from before the job + std::set changed; + // Graphs earlier assignMaterialGraph operations put on materials, empty if they removed it (only check uses it) + std::map assigned; + + }; + + // The materialGraph edit operation: creates or changes a graph document and compiles it, compile errors fail it + json EditMaterialGraph(const json& operation, MaterialGraphEdits& edits); + + // Writes the changed graphs, a .backup of an existing file is kept + json SaveMaterialGraphs(MaterialGraphEdits& edits); + + // The graph of a document as the engine uses it, with its textures + Ref CreateGraph(const GraphDocument& document); + + // Material files of a path or a list of paths, wildcards are allowed in the file names. Fails if nothing matches + std::vector FindMaterialFiles(const json& patterns); + + // The keys of an assignMaterialGraph operation and values without a graph + void CheckAssignMaterialGraph(const json& operation); + + // Validates the values, textures and resets of an assignMaterialGraph operation against the parameters of a graph + void CheckGraphValues(const json& operation, const MaterialGraph::CompiledGraph& compiled, const std::string& graphPath); + + // The value of a parameter from a number (all components) or an array (the first components, the others are kept) + vec4 ToParameterValue(const MaterialGraph::Parameter& parameter, const json& value, vec4 current); + + // The components of the parameter type, rounded for reports + json ToParameterJson(const MaterialGraph::Parameter& parameter, vec4 value); + + const MaterialGraph::Parameter* FindParameter(const MaterialGraph::CompiledGraph& compiled, const std::string& name); + + // Applies the materialGraph and assignMaterialGraph operations of a job without the engine, issues start with ERROR + void CheckMaterialGraphOperations(const json& operations, std::vector& issues); + + // inspect of a .aematgraph file: nodes, links, parameters and the result of compiling it + int32_t InspectMaterialGraph(const fs::path& file, const std::vector& filters, bool printCode, const fs::path& output); + + // inspect nodes: the node library with the pins of every node + int32_t InspectMaterialGraphNodes(const std::vector& filters); + +} diff --git a/src/bridge/Mcp.cpp b/src/bridge/Mcp.cpp new file mode 100644 index 000000000..563e5c938 --- /dev/null +++ b/src/bridge/Mcp.cpp @@ -0,0 +1,63 @@ +#include "Mcp.h" +#include "McpTools.h" +#include "Processes.h" + +namespace Atlas::Bridge { + + int32_t RunMcpServer(const std::vector& args) { + + auto port = McpServer::defaultPort; + std::string token; + if (auto environment = std::getenv("ATLAS_BRIDGE_TOKEN")) + token = environment; + + for (size_t i = 2; i < args.size(); i++) { + auto hasValue = i + 1 < args.size(); + if (args[i] == "--port" && hasValue) + port = std::stoi(args[++i]); + else if (args[i] == "--token" && hasValue) + token = args[++i]; + else + throw std::runtime_error("Usage: mcp [--port 7777] [--token ]"); + } + + auto executable = GetExecutablePath(); + auto base = GetLaunchDirectory(); + + McpServer server("atlas-bridge", McpTools::GetInstructions("bridge, which runs jobs on scene files with the real GPU")); + McpTools::AddJobTools(server, executable, base); + + server.AddTool({ .name = "lua", + .description = "Runs Lua in the scene the bridge server has loaded, after playing it for play seconds. " + McpTools::GetLuaHelp(), + .inputSchema = McpTools::ObjectSchema({ + { "code", { { "type", "string" } } }, + { "scene", { { "type", "string" }, { "description", "Scene to load, default the loaded one" } } }, + { "play", { { "type", "number" } } } }, { "code" }), + .call = [executable, base](const json& arguments, const McpServer::Reply& reply) { + std::vector command = { "eval", arguments.at("code").get() }; + if (arguments.contains("scene")) + command.insert(command.end(), { "--scene", arguments["scene"].get() }); + if (arguments.contains("play")) + command.insert(command.end(), { "--play", std::to_string(arguments["play"].get()) }); + reply(McpTools::RunBridge(executable, base, command)); + }, + .onRequestThread = true }); + + server.AddTool({ .name = "status", .description = "Which program serves the tools (the bridge) and what its server does", + .call = [executable, base](const json&, const McpServer::Reply& reply) { + reply(McpTools::RunBridge(executable, base, { "status" }, 60.0f)); + }, + .onRequestThread = true }); + + std::string error; + if (!server.Start(port, error, token)) { + Print("ERROR: " + error); + return 2; + } + Print("Atlas Bridge MCP server on http://127.0.0.1:" + std::to_string(port) + "/mcp"); + server.Wait(); + return 0; + + } + +} diff --git a/src/bridge/Mcp.h b/src/bridge/Mcp.h new file mode 100644 index 000000000..325e1021a --- /dev/null +++ b/src/bridge/Mcp.h @@ -0,0 +1,11 @@ +#pragma once + +#include "Common.h" + +namespace Atlas::Bridge { + + // `AtlasBridge mcp`: the MCP server of the bridge (McpServer.h) with the job tools and Lua in the scene of the bridge + // server, until the process ends + int32_t RunMcpServer(const std::vector& args); + +} diff --git a/src/bridge/McpServer.cpp b/src/bridge/McpServer.cpp new file mode 100644 index 000000000..2cdf72fec --- /dev/null +++ b/src/bridge/McpServer.cpp @@ -0,0 +1,271 @@ +// Winsock has to come before any windows.h, so this file is compiled without the precompiled header, and windows.h +// mustn't leave its macros to the engine headers +#define NOMINMAX +#define WIN32_LEAN_AND_MEAN +#include +#undef near +#undef far + +#include "McpServer.h" +#include "Image.h" + +#include "Engine.h" + +#include +#include + +namespace Atlas::Bridge { + + struct McpServer::Http { + httplib::Server server; + }; + + McpServer::McpServer(const std::string& name, const std::string& instructions) + : name(name), instructions(instructions), http(std::make_unique()) { + + } + + McpServer::~McpServer() { + + // Calls still waiting get an answer first, stopping waits for their requests. Later calls are answered right away + std::deque pending; + { + std::scoped_lock lock(mutex); + closing = true; + pending = std::exchange(calls, {}); + } + for (auto& call : pending) + call.result->set_value(TextContent("The " + name + " was closed", true)); + + http->server.stop(); + if (thread.joinable()) + thread.join(); + + } + + void McpServer::AddTool(Tool tool) { + + tools.push_back(std::move(tool)); + + } + + bool McpServer::Start(int32_t port, std::string& error, const std::string& token) { + + auto& server = http->server; + // The first program keeps the port, SO_REUSEADDR would let a second one bind it on Windows + server.set_socket_options([](socket_t socket) { + int enable = 1; +#ifdef _WIN32 + setsockopt(socket, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, reinterpret_cast(&enable), sizeof(enable)); +#else + setsockopt(socket, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable)); +#endif + }); + // Jobs run for minutes, the answer is written when they end + server.set_read_timeout(60, 0); + server.set_write_timeout(1800, 0); + + // Web pages must not reach the server: their requests carry an Origin, and with DNS rebinding a host name of the + // attacker. A JSON content type can't be sent without a preflight, which isn't answered. Clients of agents send + // no Origin, the host only matters without a token (a tunnel forwards other host names) + auto authorized = [this, token](const httplib::Request& request, httplib::Response& response) { + auto origin = request.get_header_value("Origin"); + auto knownOrigin = origin == "https://chatgpt.com" || origin == "https://claude.ai"; + auto hostAllowed = !token.empty() || IsLocalHost(request.get_header_value("Host")); + if ((!IsLocalOrigin(origin) && !knownOrigin) || !hostAllowed) { + response.status = 403; + return false; + } + if (!token.empty() && request.get_header_value("Authorization") != "Bearer " + token) { + response.status = 401; + response.set_header("WWW-Authenticate", "Bearer"); + return false; + } + return true; + }; + + server.Post("/mcp", [this, authorized](const httplib::Request& request, httplib::Response& response) { + if (!authorized(request, response)) + return; + if (!request.get_header_value("Content-Type").starts_with("application/json")) { + response.status = 415; + return; + } + + auto message = json::parse(request.body, nullptr, false); + if (message.is_discarded()) { + response.status = 400; + response.set_content(json({ { "jsonrpc", "2.0" }, { "id", nullptr }, + { "error", { { "code", -32700 }, { "message", "Parse error" } } } }).dump(), "application/json"); + return; + } + + auto answer = HandleMessage(message); + if (!answer) { + response.status = 202; + return; + } + // Every request stands on its own, the session id is only for clients which expect one + if (message.value("method", "") == "initialize") + response.set_header("Mcp-Session-Id", std::to_string(std::random_device()()) + std::to_string(std::random_device()())); + response.set_content(answer->dump(), "application/json"); + }); + // No stream of messages from the server + server.Get("/mcp", [authorized](const httplib::Request& request, httplib::Response& response) { + if (authorized(request, response)) + response.status = 405; + }); + server.Delete("/mcp", [authorized](const httplib::Request& request, httplib::Response& response) { + if (authorized(request, response)) + response.status = 200; + }); + + if (!server.bind_to_port("127.0.0.1", port)) { + // The program which has the port says its name when asked like a client would + httplib::Client client("127.0.0.1", port); + client.set_connection_timeout(1, 0); + client.set_read_timeout(2, 0); + auto other = client.Post("/mcp", json({ { "jsonrpc", "2.0" }, { "id", 1 }, { "method", "initialize" }, + { "params", json::object() } }).dump(), "application/json"); + auto answer = other && other->status == 200 ? json::parse(other->body, nullptr, false) : json(); + auto owner = answer.is_object() ? answer["result"]["serverInfo"].value("name", "") : ""; + error = "Port " + std::to_string(port) + (owner.empty() ? " is used by another program" : " is used by " + owner); + return false; + } + + this->port = port; + thread = std::thread([this]() { http->server.listen_after_bind(); }); + return true; + + } + + void McpServer::Update() { + + std::deque pending; + { + std::scoped_lock lock(mutex); + pending = std::exchange(calls, {}); + } + for (const auto& call : pending) + Run(call); + + } + + void McpServer::Wait() { + + if (thread.joinable()) + thread.join(); + + } + + json McpServer::TextContent(const std::string& text, bool isError) { + + return { { "content", json::array({ { { "type", "text" }, { "text", text } } }) }, { "isError", isError } }; + + } + + json McpServer::ImageContent(fs::path path) { + + // Large windows would be megabytes of base64 in the answer + if (auto image = LoadImageFile(path); image && image->width > 1536) { + auto preview = path; + preview.replace_extension(".preview.jpg"); + if (WriteImage(Downscale(image, 1536), preview)) + path = preview; + } + + std::ifstream stream(path, std::ios::binary); + if (!stream.is_open()) + return TextContent("Can't read " + path.string(), true); + std::string data((std::istreambuf_iterator(stream)), std::istreambuf_iterator()); + + auto extension = path.extension().string(); + auto mime = extension == ".jpg" || extension == ".jpeg" ? "image/jpeg" : "image/png"; + return { { "content", json::array({ + { { "type", "image" }, { "data", httplib::detail::base64_encode(data) }, { "mimeType", mime } }, + { { "type", "text" }, { "text", path.string() } } }) }, { "isError", false } }; + + } + + std::optional McpServer::HandleMessage(const json& message) { + + if (!message.is_object()) + return json { { "jsonrpc", "2.0" }, { "id", nullptr }, { "error", { { "code", -32600 }, { "message", "Invalid request" } } } }; + // Notifications and answers of the client get no answer + if (!message.contains("id") || !message.contains("method")) + return std::nullopt; + + auto method = message.value("method", ""); + auto params = message.value("params", json::object()); + json response = { { "jsonrpc", "2.0" }, { "id", message["id"] } }; + + if (method == "initialize") { + response["result"] = { + { "protocolVersion", params.value("protocolVersion", "2025-06-18") }, + { "capabilities", { { "tools", json::object() } } }, + { "serverInfo", { { "name", name }, { "version", Engine::GetVersion() } } }, + { "instructions", instructions } + }; + } + else if (method == "tools/list") { + json list = json::array(); + for (const auto& tool : tools) + list.push_back({ { "name", tool.name }, { "description", tool.description }, { "inputSchema", tool.inputSchema } }); + response["result"] = { { "tools", list } }; + } + else if (method == "tools/call") { + response["result"] = CallTool(params.value("name", ""), params.value("arguments", json::object())); + } + else if (method == "ping") { + response["result"] = json::object(); + } + else { + response["error"] = { { "code", -32601 }, { "message", "Method not found: " + method } }; + } + + return response; + + } + + json McpServer::CallTool(const std::string& toolName, const json& arguments) { + + auto tool = std::find_if(tools.begin(), tools.end(), [&](const Tool& tool) { return tool.name == toolName; }); + if (tool == tools.end()) + return TextContent("Unknown tool " + toolName + " of the " + name, true); + + Call call = { &*tool, arguments, std::make_shared>() }; + auto result = call.result->get_future(); + if (tool->onRequestThread) { + Run(call); + } + else { + std::scoped_lock lock(mutex); + if (closing) + return TextContent("The " + name + " was closed", true); + calls.push_back(call); + } + + // The program can be busy, e.g. loading a scene or starting to play + if (result.wait_for(std::chrono::minutes(10)) != std::future_status::ready) + return TextContent("The " + name + " didn't run the call within 10 minutes", true); + return result.get(); + + } + + void McpServer::Run(const Call& call) { + + auto replied = std::make_shared(false); + auto reply = [call, replied](json result) { + if (!std::exchange(*replied, true)) + call.result->set_value(std::move(result)); + }; + try { + call.tool->call(call.arguments, reply); + } + catch (const std::exception& e) { + reply(TextContent(std::string("ERROR: ") + e.what(), true)); + } + + } + +} diff --git a/src/bridge/McpServer.h b/src/bridge/McpServer.h new file mode 100644 index 000000000..cc22a0402 --- /dev/null +++ b/src/bridge/McpServer.h @@ -0,0 +1,88 @@ +#pragma once + +#include "Common.h" + +#include +#include +#include +#include +#include +#include + +namespace Atlas::Bridge { + + // Model Context Protocol server over Streamable HTTP on 127.0.0.1 (POST /mcp, answered with JSON). Every program + // linking the bridge library can offer one: the editor, AtlasBridge.exe, a game. Only one gets the port, the first, + // the others are told who has it. Clients see the program in serverInfo and its tools in tools/list. Requests + // arrive on a thread of the server, tool calls run on the main thread of the program in Update() unless the tool + // runs on the request thread + class McpServer { + + public: + using Reply = std::function; + + struct Tool { + std::string name; + std::string description; + json inputSchema = json::object({ { "type", "object" } }); + // Calls reply once with the result (TextContent, ImageContent), also in a later frame + std::function call; + // Long calls which don't touch the program, e.g. starting a job, don't wait for its frames + bool onRequestThread = false; + }; + + McpServer(const std::string& name, const std::string& instructions); + + ~McpServer(); + + // Before Start + void AddTool(Tool tool); + + // False if the port is taken, the error says by which program. With a token, requests need it as bearer token + bool Start(int32_t port, std::string& error, const std::string& token = ""); + + // Runs the calls which arrived since the last frame, on the main thread + void Update(); + + // Blocks while the server runs, for programs without frames + void Wait(); + + int32_t GetPort() const { return port; } + + static json TextContent(const std::string& text, bool isError = false); + + // Images wider than a sheet are sent at 1536 px + static json ImageContent(fs::path path); + + static constexpr int32_t defaultPort = 7777; + + private: + struct Call { + const Tool* tool; + json arguments; + std::shared_ptr> result; + }; + + struct Http; + + std::optional HandleMessage(const json& message); + + json CallTool(const std::string& name, const json& arguments); + + static void Run(const Call& call); + + std::string name; + std::string instructions; + std::vector tools; + + std::unique_ptr http; + std::thread thread; + int32_t port = 0; + + std::mutex mutex; + std::deque calls; + bool closing = false; + + }; + +} diff --git a/src/bridge/McpTools.cpp b/src/bridge/McpTools.cpp new file mode 100644 index 000000000..e05dc9950 --- /dev/null +++ b/src/bridge/McpTools.cpp @@ -0,0 +1,220 @@ +#include "McpTools.h" +#include "Processes.h" +#include "LuaEdit.h" + +#include "project/Project.h" +#include "scripting/BindingRegistry.h" +#include "scripting/LuaHost.h" + +#include +#include +#include + +namespace Atlas::Bridge { + + static std::atomic callCount = 0; + + static const char* runDescription = R"(Runs a bridge job with the real GPU on the bridge server (keeps the scene loaded between jobs) and returns +the summary: status, failed checks and expectations, results, outputs. A job is a JSON object or the path of a job +file: { "scene": "scenes/x.aescene", "queries": [], "edit": {}, "shots": [], "play": true, "duration": 5, +"timeline": [], "checks": {} }; docs("Jobs") has every key. Edits write scene files (only after their checks pass), +persistent scene changes go through "edit", never by rewriting .aescene files. Pass "--streaming" for large scenes. +Exit codes: 0 passed, 1 a check failed, 2 error, 3 crash, 4 still waiting (job_status, the job keeps running).)"; + + std::string McpTools::GetLuaHelp() { + + return R"(The code sees the engine bindings (Atlas, Glm, scene, the globals of the scene scripts) and the table Bridge: + Find(pattern), FindMeshes(pattern) entities by name pattern (* ?) or #id, by loaded mesh path + Query(query) one query of the job format, e.g. { type = "path", points = {...} }; + docs("Queries") lists them, rays and heights are scene:CastRay + SampleTerrain(x, z) { height, slope, normal, material, hole } of the terrain, nil outside + PickRay(camera, x, y) the ray through a pixel of a shot camera (jobs that render) + Result(key, value), Fail(message) returned with the result, a returned value comes back as "value" + Time() seconds of the job or the call + Selection(), Camera() selected entities and camera { location, direction } of the editor + Touch(entity) call before changing components of an entity directly (undo) + SetPosition(entity, Glm.Vec3(x,y,z)) world position, keeps the rotation; SetMatrix(entity, mat4) the local matrix + Create(name, parent?), Destroy(entity) + Edit(operation) one edit operation of the job format, e.g. { op = "snapToGround", entity = "Barrel" } +Scene settings are part of the step too, e.g. scene.sky.atmosphere = Atlas.Atmosphere.new(), scene.sky.probe = nil, +scene.sky.probe = Atlas.EnvironmentProbe.new("environment.hdr"), scene.sky.clouds = Atlas.VolumetricClouds.new(). +Material graphs: Atlas.ResourceManager.GetOrLoadMaterialGraph(path):Get() or material.graph:Get(), then graph:FindNodes, +AddNode(type), Connect(from, pin, to, pin), SetInput/SetValue/SetName/SetCode(id, ...), Compile() (returns the errors), +Atlas.MaterialGraph.GetNodeTypes(). Atlas.Log.GetLatest(count) returns the newest log entries.)"; + + } + + std::string McpTools::GetInstructions(const std::string& program) { + + return "This is the " + program + " of the Atlas Engine (serverInfo says which program, status what it has open). " + R"(Measure before placing anything (scene:CastRay, Bridge.SampleTerrain, queries of jobs), never guess coordinates or +heights. Test time is the user's time: check a job first, run one targeted job with the shortest duration, look at +sheet.jpg (view_image) instead of single images. docs returns sections of the full reference.)"; + + } + + json McpTools::ObjectSchema(const json& properties, const std::vector& required) { + + return { { "type", "object" }, { "properties", properties }, { "required", required } }; + + } + + json McpTools::RunBridge(const fs::path& bridgeExecutable, const fs::path& baseDirectory, std::vector arguments, + float timeoutSeconds) { + + auto directory = fs::temp_directory_path() / "AtlasBridge"; + fs::create_directories(directory); + auto log = directory / ("mcp-" + std::to_string(CurrentProcessId()) + "-" + std::to_string(callCount++) + ".log"); + + arguments.insert(arguments.begin(), bridgeExecutable.string()); + auto exitCode = RunProcess(arguments, baseDirectory, log, timeoutSeconds); + + std::ifstream stream(log, std::ios::binary); + std::string output((std::istreambuf_iterator(stream)), std::istreambuf_iterator()); + output += "\n(exit code " + std::to_string(exitCode) + ")"; + return McpServer::TextContent(output, exitCode < 0 || (exitCode >= 2 && exitCode != 4)); + + } + + void McpTools::AddJobTools(McpServer& server, const fs::path& bridgeExecutable, const fs::path& baseDirectory) { + + auto resolve = [baseDirectory](const std::string& path) { + fs::path userPath(path); + return userPath.is_absolute() ? userPath : (baseDirectory / userPath).lexically_normal(); + }; + auto writeJob = [resolve](const json& job) { + if (job.is_string()) + return resolve(job.get()); + + auto directory = fs::temp_directory_path() / "AtlasBridge"; + fs::create_directories(directory); + auto path = directory / ("mcp-job-" + std::to_string(CurrentProcessId()) + "-" + std::to_string(callCount++) + ".json"); + auto inlineJob = job; + if (!inlineJob.contains("name")) + inlineJob["name"] = "mcp"; + WriteFileAtomic(path, inlineJob.dump(2)); + return path; + }; + auto run = [bridgeExecutable, baseDirectory](std::vector arguments, float timeout = 0.0f) { + return RunBridge(bridgeExecutable, baseDirectory, std::move(arguments), timeout); + }; + json jobArgument = { { "description", "Job object or path of a job file" } }; + + server.AddTool({ .name = "run", .description = runDescription, + .inputSchema = ObjectSchema({ { "job", jobArgument }, + { "args", { { "type", "array" }, { "items", { { "type", "string" } } }, + { "description", "Job options, e.g. --streaming, --play 3, --views front,low, --no-shots, --timeout 540" } } } }, { "job" }), + .call = [run, writeJob](const json& arguments, const McpServer::Reply& reply) { + std::vector command = { "run", writeJob(arguments.at("job")).string() }; + for (const auto& arg : arguments.value("args", std::vector())) + command.push_back(arg); + reply(run(command)); + }, + .onRequestThread = true }); + + server.AddTool({ .name = "check", + .description = "Finds mistakes in a job without loading anything (entity names, Lua that doesn't compile, keys), milliseconds", + .inputSchema = ObjectSchema({ { "job", jobArgument } }, { "job" }), + .call = [run, writeJob](const json& arguments, const McpServer::Reply& reply) { + reply(run({ "check", writeJob(arguments.at("job")).string() }, 120.0f)); + }, + .onRequestThread = true }); + + server.AddTool({ .name = "inspect", + .description = "Entities, meshes, materials and graph nodes of a scene, prefab, mesh, model or material graph file without loading it", + .inputSchema = ObjectSchema({ + { "target", { { "type", "string" }, { "description", "File, or 'nodes' for the node types of material graphs" } } }, + { "filter", { { "type", "string" }, { "description", "Name pattern" } } }, + { "limit", { { "type", "integer" } } } }, { "target" }), + .call = [run](const json& arguments, const McpServer::Reply& reply) { + std::vector command = { "inspect", arguments.at("target").get() }; + if (arguments.contains("filter")) + command.insert(command.end(), { "--filter", arguments["filter"].get() }); + if (arguments.contains("limit")) + command.insert(command.end(), { "--limit", std::to_string(arguments["limit"].get()) }); + reply(run(command, 300.0f)); + }, + .onRequestThread = true }); + + server.AddTool({ .name = "job_status", + .description = "What the bridge server and the engine applications on the machine do, whom a waiting run waits for", + .call = [run](const json&, const McpServer::Reply& reply) { reply(run({ "status" }, 60.0f)); }, + .onRequestThread = true }); + + server.AddTool({ .name = "cancel", .description = "Stops the running job of the bridge server", + .call = [run](const json&, const McpServer::Reply& reply) { reply(run({ "cancel" }, 60.0f)); }, + .onRequestThread = true }); + + server.AddTool({ .name = "view_image", .description = "An image file as an image, e.g. sheet.jpg of a job", + .inputSchema = ObjectSchema({ { "path", { { "type", "string" } } } }, { "path" }), + .call = [resolve](const json& arguments, const McpServer::Reply& reply) { + reply(McpServer::ImageContent(resolve(arguments.at("path").get()))); + }, + .onRequestThread = true }); + + server.AddTool({ .name = "bindings", + .description = "The Lua bindings: types with their fields, methods and constructors, the tables (Atlas, Glm, Host, " + "Project, Bridge) and the globals of scripts, with Lua types. Search with filter (a type, table or member name, " + "e.g. Sky, probe, SetPosition), or format lua for annotations of the Lua language server", + .inputSchema = ObjectSchema({ { "filter", { { "type", "string" } } }, + { "format", { { "type", "string" }, { "enum", { "json", "lua" } } } } }), + .call = [](const json& arguments, const McpServer::Reply& reply) { + // A program only knows the bindings of the Lua states it created, all of them are created once here + static std::once_flag recorded; + std::call_once(recorded, []() { + Scripting::LuaHost host; + if (!Project::active) + Scripting::Binder(host.GetState().globals(), "_G").set("Project", CreateRef()); + EditState state; + Scripting::Binder bridge(host.GetState().create_table(), "Bridge"); + LuaEdit::AddFunctions(bridge, nullptr, state, {}, [](const std::string&, json) {}, []() { return 0.0f; }); + }); + + if (arguments.value("format", "json") == "lua") { + reply(McpServer::TextContent(Scripting::BindingRegistry::ToLuaAnnotations())); + return; + } + auto result = Scripting::BindingRegistry::ToJson(arguments.value("filter", "")); + reply(McpServer::TextContent(result.empty() ? "Nothing matches the filter" : result.dump(1), result.empty())); + }, + .onRequestThread = true }); + + auto readme = bridgeExecutable.parent_path() / ".." / ".." / "src" / "bridge" / "README.md"; + server.AddTool({ .name = "docs", + .description = "A section of the bridge reference (README.md) by its heading, e.g. Jobs, Playing, Checks, Queries, Editing, Pipelines; without a section the list of headings", + .inputSchema = ObjectSchema({ { "section", { { "type", "string" } } } }), + .call = [readme](const json& arguments, const McpServer::Reply& reply) { + std::ifstream stream(readme); + if (!stream.is_open()) { + reply(McpServer::TextContent("README.md of the bridge not found next to the build", true)); + return; + } + + std::vector> sections; + std::string line; + while (std::getline(stream, line)) { + if (!line.empty() && line.back() == '\r') + line.pop_back(); + if (line.starts_with("#")) + sections.push_back({ line.substr(line.find_first_not_of("# ")), "" }); + else if (!sections.empty()) + sections.back().second += line + "\n"; + } + + auto section = arguments.value("section", ""); + std::string headings; + for (const auto& [heading, text] : sections) { + if (!section.empty() && heading == section) { + reply(McpServer::TextContent("# " + heading + "\n" + text)); + return; + } + headings += heading + "\n"; + } + reply(McpServer::TextContent((section.empty() ? "" : "No section '" + section + "', the sections:\n") + headings, + !section.empty())); + }, + .onRequestThread = true }); + + } + +} diff --git a/src/bridge/McpTools.h b/src/bridge/McpTools.h new file mode 100644 index 000000000..379580b1a --- /dev/null +++ b/src/bridge/McpTools.h @@ -0,0 +1,28 @@ +#pragma once + +#include "McpServer.h" + +namespace Atlas::Bridge { + + // Tools of the MCP server which every program can offer: jobs on scene files run by AtlasBridge.exe (run, check, + // inspect, job_status, cancel), images and the reference. The descriptions carry the rules of README.md + class McpTools { + + public: + // Relative paths of jobs and images are relative to the base directory, e.g. the project + static void AddJobTools(McpServer& server, const fs::path& bridgeExecutable, const fs::path& baseDirectory); + + // The table Bridge of LuaEdit.h, for the descriptions of lua tools + static std::string GetLuaHelp(); + + static std::string GetInstructions(const std::string& program); + + static json ObjectSchema(const json& properties, const std::vector& required = {}); + + // Runs a command of AtlasBridge.exe and returns its output + static json RunBridge(const fs::path& bridgeExecutable, const fs::path& baseDirectory, std::vector arguments, + float timeoutSeconds = 0.0f); + + }; + +} diff --git a/src/bridge/MoveRunningExecutable.cmake b/src/bridge/MoveRunningExecutable.cmake new file mode 100644 index 000000000..7e2ad390e --- /dev/null +++ b/src/bridge/MoveRunningExecutable.cmake @@ -0,0 +1,11 @@ +# Moves the executable aside before it is linked: a running program keeps running from the renamed file and the +# new one can be written. Renamed files of earlier builds are removed once they don't run anymore +file(GLOB previous "${EXECUTABLE}.old-*") +foreach(file IN LISTS previous) + execute_process(COMMAND ${CMAKE_COMMAND} -E rm -f "${file}" RESULT_VARIABLE ignored ERROR_QUIET) +endforeach() + +if (EXISTS "${EXECUTABLE}") + string(TIMESTAMP stamp "%Y%m%d%H%M%S") + file(RENAME "${EXECUTABLE}" "${EXECUTABLE}.old-${stamp}" RESULT renamed) +endif() diff --git a/src/bridge/Overlay.cpp b/src/bridge/Overlay.cpp new file mode 100644 index 000000000..9e389c261 --- /dev/null +++ b/src/bridge/Overlay.cpp @@ -0,0 +1,37 @@ +#include "Overlay.h" + +#include "graphics/GraphicsDevice.h" + +namespace Atlas::Bridge { + + Overlay::Overlay() { + + auto device = Graphics::GraphicsDevice::DefaultDevice; + for (size_t i = 0; i < batches.size(); i++) { + batches[i] = CreateRef(); + batches[i]->testDepth = i == 0; + batches[i]->SetLineWidth(device->support.wideLines ? 2.0f : 1.0f); + } + + } + + void Overlay::Clear() { + + for (auto& batch : batches) + batch->Clear(); + + } + + std::span> Overlay::GetBatches() { + + return batches; + + } + + Ref& Overlay::GetBatch() { + + return depthTest ? batches[0] : batches[1]; + + } + +} diff --git a/src/bridge/Overlay.h b/src/bridge/Overlay.h new file mode 100644 index 000000000..34108eea3 --- /dev/null +++ b/src/bridge/Overlay.h @@ -0,0 +1,32 @@ +#pragma once + +#include "Common.h" + +#include "renderer/PrimitiveBatch.h" + +#include + +namespace Atlas::Bridge { + + // Debug lines drawn into the captured images through the engine primitive batches, + // e.g. bounds of entities, invisible entities like players, trails and query results + class Overlay { + + public: + Overlay(); + + void Clear(); + + // The batch for new lines, depending on depthTest + Ref& GetBatch(); + + std::span> GetBatches(); + + bool depthTest = false; + + private: + std::array, 2> batches; + + }; + +} diff --git a/src/bridge/Pipeline.cpp b/src/bridge/Pipeline.cpp new file mode 100644 index 000000000..f2e6307cf --- /dev/null +++ b/src/bridge/Pipeline.cpp @@ -0,0 +1,322 @@ +#include "Pipeline.h" + +#include +#include +#include + +namespace Atlas::Bridge { + + static constexpr uint64_t fnvOffset = 14695981039346656037ull; + static constexpr uint64_t fnvPrime = 1099511628211ull; + + static uint64_t HashBytes(uint64_t hash, const char* data, size_t size) { + + for (size_t i = 0; i < size; i++) { + hash ^= uint8_t(data[i]); + hash *= fnvPrime; + } + return hash; + + } + + static uint64_t HashFile(uint64_t hash, const fs::path& path) { + + std::ifstream stream(path, std::ios::binary); + if (!stream.is_open()) + throw std::runtime_error("Couldn't read " + path.string()); + + std::vector buffer(1 << 20); + while (stream) { + stream.read(buffer.data(), std::streamsize(buffer.size())); + hash = HashBytes(hash, buffer.data(), size_t(stream.gcount())); + } + return hash; + + } + + static std::string ToHex(uint64_t value) { + + char text[17]; + std::snprintf(text, sizeof(text), "%016llx", static_cast(value)); + return text; + + } + + // Empty for files that don't exist + static std::string HashAsset(const std::string& assetPath) { + + auto path = GetAssetDirectory() / assetPath; + return fs::exists(path) ? ToHex(HashFile(fnvOffset, path)) : std::string(); + + } + + Pipeline Pipeline::Load(const fs::path& file, const std::string& from, bool force) { + + std::ifstream stream(file); + if (!stream.is_open()) + throw std::runtime_error("Couldn't open pipeline file " + file.string()); + + json j; + try { + j = json::parse(stream, nullptr, true, true); + } + catch (const json::exception& e) { + throw std::runtime_error("Couldn't parse pipeline file " + file.string() + ": " + e.what()); + } + + Pipeline pipeline; + pipeline.name = j.value("name", file.stem().string()); + pipeline.from = from; + pipeline.force = force; + + auto baseDirectory = file.parent_path(); + for (const auto& path : j.value("files", std::vector())) + pipeline.stateFiles.push_back(ToAssetPath(path)); + + if (!j.contains("steps") || j["steps"].empty()) + throw std::runtime_error("The pipeline " + file.string() + " has no steps"); + + for (const auto& stepJson : j["steps"]) { + // A step is a job file or { "job": ..., "name": ..., "inputs": [...] } + Step step; + auto jobPath = stepJson.is_string() ? stepJson.get() : stepJson.at("job").get(); + step.jobFile = (baseDirectory / jobPath).lexically_normal(); + step.name = stepJson.is_object() ? stepJson.value("name", step.jobFile.stem().string()) : step.jobFile.stem().string(); + if (stepJson.is_object()) { + for (const auto& input : stepJson.value("inputs", std::vector())) + step.inputs.push_back((baseDirectory / input).lexically_normal()); + step.independent = stepJson.value("independent", false); + } + pipeline.steps.push_back(step); + } + + if (!from.empty() && std::none_of(pipeline.steps.begin(), pipeline.steps.end(), [&](const Step& step) { return step.name == from; })) + throw std::runtime_error("--from: the pipeline has no step named '" + from + "'"); + + if (j.contains("snapshots")) { + fs::path snapshots(j["snapshots"].get()); + pipeline.snapshotDirectory = snapshots.is_absolute() ? snapshots : (baseDirectory / snapshots).lexically_normal(); + } + else { + // Next to the job outputs, the bin directory is ignored by git + pipeline.snapshotDirectory = + (fs::current_path() / ".." / "bridge" / SanitizeFileName(pipeline.name) / "snapshots").lexically_normal(); + } + + // Each key covers the steps before it, a change invalidates all following steps. The key of an independent + // step covers only its own files, they still go into the keys of the steps after it + uint64_t key = fnvOffset; + for (auto& step : pipeline.steps) { + auto own = HashFile(fnvOffset, step.jobFile); + key = HashFile(key, step.jobFile); + for (const auto& input : step.inputs) { + own = HashFile(own, input); + key = HashFile(key, input); + } + step.key = ToHex(step.independent ? own : key); + } + + pipeline.results.resize(pipeline.steps.size(), "pending"); + return pipeline; + + } + + void Pipeline::Prepare(const std::function& print) { + + size_t first = 0; + for (; first < steps.size(); first++) { + if (force || steps[first].name == from) + break; + auto snapshot = ReadSnapshot(first); + if (!snapshot || snapshot->key != steps[first].key) + break; + results[first] = "up to date"; + } + + if (first > 0) { + // Also when everything is up to date, the files may have been changed since the last run + auto snapshot = ReadSnapshot(first - 1); + Restore(*snapshot, print); + stateFiles.clear(); + for (const auto& [path, hash] : snapshot->files) + stateFiles.push_back(path); + } + + for (size_t i = first; i < steps.size(); i++) { + auto snapshot = steps[i].independent ? ReadSnapshot(i) : std::nullopt; + if (snapshot) + steps[i].previousKey = snapshot->key; + } + + Invalidate(first); + currentStep = first; + + } + + bool Pipeline::Skips(size_t index) const { + + const auto& step = steps[index]; + return step.independent && !force && step.name != from && !step.previousKey.empty() && step.previousKey == step.key; + + } + + void Pipeline::SkipStep() { + + Complete(currentStep, json::object()); + results[currentStep] = "unchanged"; + currentStep++; + + } + + void Pipeline::Complete(size_t index, const json& report) { + + if (report.contains("edit")) { + const auto& edit = report["edit"]; + auto add = [&](const std::string& path) { + + if (std::find(stateFiles.begin(), stateFiles.end(), path) == stateFiles.end()) + stateFiles.push_back(path); + + }; + if (edit.value("saved", false)) + add(edit["output"].get()); + if (edit.contains("terrain")) + add(edit["terrain"].get()); + for (const auto& material : edit.value("materials", json::array())) + add(material["material"].get()); + for (const auto& graph : edit.value("graphs", json::array())) + add(graph["graph"].get()); + } + + json manifest = { { "step", steps[index].name }, { "job", steps[index].jobFile.string() }, { "key", steps[index].key }, + { "files", json::object() } }; + auto start = std::chrono::steady_clock::now(); + for (const auto& path : stateFiles) + manifest["files"][path] = StoreFile(path); + manifest["storeSeconds"] = SecondsSince(start); + + fs::create_directories(snapshotDirectory); + std::ofstream stream(GetManifestPath(index)); + stream << manifest.dump(2); + results[index] = "ran"; + + } + + void Pipeline::Fail(size_t index) { + + results[index] = "failed"; + Invalidate(index); + + } + + void Pipeline::Invalidate(size_t index) { + + std::error_code error; + for (size_t i = index; i < steps.size(); i++) + fs::remove(GetManifestPath(i), error); + + } + + void Pipeline::CompleteStep(const json& report) { + + Complete(currentStep, report); + currentStep++; + + } + + void Pipeline::FailStep(int32_t stepExitCode) { + + Fail(currentStep); + exitCode = stepExitCode; + currentStep = steps.size(); + + } + + bool Pipeline::IsFinished() const { + + return currentStep >= steps.size(); + + } + + fs::path Pipeline::WriteSummary() const { + + auto path = snapshotDirectory.parent_path() / "pipeline.json"; + fs::create_directories(path.parent_path()); + WriteFileAtomic(path, json({ { "pipeline", name }, { "exitCode", exitCode }, { "steps", GetSummary() } }).dump(2)); + return path; + + } + + json Pipeline::GetSummary() const { + + json summary = json::array(); + for (size_t i = 0; i < steps.size(); i++) + summary.push_back({ { "step", steps[i].name }, { "job", steps[i].jobFile.string() }, { "result", results[i] } }); + return summary; + + } + + fs::path Pipeline::GetManifestPath(size_t index) const { + + return snapshotDirectory / (std::to_string(index + 1) + "_" + SanitizeFileName(steps[index].name) + ".json"); + + } + + std::optional Pipeline::ReadSnapshot(size_t index) const { + + std::ifstream stream(GetManifestPath(index)); + if (!stream.is_open()) + return std::nullopt; + + auto manifest = json::parse(stream, nullptr, false); + if (manifest.is_discarded()) + return std::nullopt; + + Snapshot snapshot; + snapshot.key = manifest.value("key", std::string()); + for (const auto& [path, hash] : manifest.value("files", json::object()).items()) { + // A snapshot whose stored files were removed can't be restored + if (!hash.get().empty() && !fs::exists(snapshotDirectory / "files" / hash.get())) + return std::nullopt; + snapshot.files[path] = hash.get(); + } + return snapshot; + + } + + void Pipeline::Restore(const Snapshot& snapshot, const std::function& print) { + + for (const auto& [path, hash] : snapshot.files) { + if (HashAsset(path) == hash) + continue; + + auto target = GetAssetDirectory() / path; + if (hash.empty()) { + fs::remove(target); + print("Restored " + path + " (removed, it didn't exist at this step)"); + continue; + } + fs::create_directories(target.parent_path()); + fs::copy_file(snapshotDirectory / "files" / hash, target, fs::copy_options::overwrite_existing); + print("Restored " + path); + } + + } + + std::string Pipeline::StoreFile(const std::string& assetPath) { + + auto hash = HashAsset(assetPath); + if (hash.empty()) + return hash; + + // Content addressed, steps that didn't change a file share its copy + auto stored = snapshotDirectory / "files" / hash; + if (!fs::exists(stored)) { + fs::create_directories(stored.parent_path()); + fs::copy_file(GetAssetDirectory() / assetPath, stored); + } + return hash; + + } + +} diff --git a/src/bridge/Pipeline.h b/src/bridge/Pipeline.h new file mode 100644 index 000000000..abb0da6b3 --- /dev/null +++ b/src/bridge/Pipeline.h @@ -0,0 +1,99 @@ +#pragma once + +#include "Common.h" + +#include +#include +#include + +namespace Atlas::Bridge { + + // A sequence of edit jobs that builds a scene step by step. After each step the files of the + // state (the saved scenes, edited materials and the files listed by the pipeline) are stored + // as a snapshot. A step whose job and inputs didn't change since its snapshot is skipped, the + // first changed step starts from the snapshot of the step before it. See README.md + class Pipeline { + + public: + struct Step { + + std::string name; + fs::path jobFile; + // Additional files the result depends on, e.g. scripts or prefabs used by the job + std::vector inputs; + // Hash of the job, its inputs and the key of the previous step. An independent step doesn't use the state + // of the steps before it (e.g. it imports assets), its key covers only its job and inputs + std::string key; + bool independent = false; + // The key of an independent step in the last run, it is skipped while its key is the same + std::string previousKey; + + }; + + // Parses the pipeline file, --from and --force are options of the command line + static Pipeline Load(const fs::path& file, const std::string& from, bool force); + + // Determines the first step to run and restores the state it starts from. All steps are finished + // if all snapshots are up to date + void Prepare(const std::function& print); + + // Stores the state after the current step finished successfully and continues with the next one. Scenes and + // terrains saved by the job and materials it changed become part of the state of this and all following steps + void CompleteStep(const json& report); + + // A failed step and all following ones have no valid snapshot anymore, the pipeline stops with the exit code + void FailStep(int32_t exitCode); + + bool IsFinished() const; + + // An independent step whose job and inputs didn't change since the last run, SkipStep passes it + bool Skips(size_t index) const; + + void SkipStep(); + + // Writes pipeline.json with the result of each step next to the snapshots and returns its path + fs::path WriteSummary() const; + + json GetSummary() const; + + std::string name; + std::vector steps; + fs::path snapshotDirectory; + + size_t currentStep = 0; + int32_t exitCode = 0; + + private: + struct Snapshot { + + std::string key; + // Asset path -> hash of the stored content, empty if the file didn't exist + std::map files; + + }; + + fs::path GetManifestPath(size_t index) const; + + std::optional ReadSnapshot(size_t index) const; + + // Copies the stored files of a snapshot back into the data directory + void Restore(const Snapshot& snapshot, const std::function& print); + + std::string StoreFile(const std::string& assetPath); + + void Complete(size_t index, const json& report); + + void Fail(size_t index); + + void Invalidate(size_t index); + + // Asset paths that make up the state, the files listed by the pipeline come first + std::vector stateFiles; + std::string from; + bool force = false; + + std::vector results; + + }; + +} diff --git a/src/bridge/Player.cpp b/src/bridge/Player.cpp new file mode 100644 index 000000000..9e076eb36 --- /dev/null +++ b/src/bridge/Player.cpp @@ -0,0 +1,268 @@ +#include "Player.h" +#include "SceneEditor.h" + +#include "resource/ResourceManager.h" +#include "scripting/Script.h" +#include "scene/components/LuaScriptComponent.h" + +namespace Atlas::Bridge { + + using namespace Scene::Components; + + void Player::Reset(const Job& job) { + + Stop(); + timeline.Reset(job.timeline); + + } + + void Player::Start(const Job& job, Scene::Scene& playedScene, std::vector events, Report& jobReport, + sol::state* luaState, uint32_t windowId) { + + scene = &playedScene; + report = &jobReport; + timeline.windowId = windowId; + + if (auto dropped = timeline.Start(std::move(events), job.duration)) + report->Warn(std::to_string(dropped) + " timeline events after the duration of " + FormatFloat(job.duration, 2) + "s are ignored"); + + for (const auto& spec : job.scripts) { + auto script = ResourceManager::GetOrLoadResource(spec.path); + if (!script.IsLoaded()) + throw std::runtime_error("Couldn't load script " + spec.path); + + std::vector entities; + if (spec.entity.empty()) { + auto entity = scene->CreateEntity(); + entity.AddComponent("Capture script " + fs::path(spec.path).stem().string()); + entity.AddComponent(mat4(1.0f), false); + entities.push_back(entity); + } + else { + entities = FindTopmostEntities(*scene, spec.entity); + if (entities.empty()) + throw std::runtime_error("Script " + spec.path + ": no entity matches '" + spec.entity + "'"); + } + + for (auto entity : entities) { + if (entity.HasComponent()) + throw std::runtime_error(GetEntityLabel(entity) + " already has a script, attach to a new entity instead"); + entity.AddComponent(script); + report->Print("Attached script " + spec.path + " to " + GetEntityLabel(entity)); + } + } + + lua.Start(luaState ? *luaState : scene->GetLuaState(), scene, *report, [this]() { return timeline.time; }); + + } + + void Player::Stop() { + + lua.Stop(); + scene = nullptr; + + } + + bool Player::Update(const OwnerEvent& ownerEvent) { + + timeline.Update([&](const json& condition) { + + bool passed = false; + Expect(condition, passed); + return passed; + + }, [&](const std::string& message) { report->Print(message); }); + + while (auto due = timeline.GetDueEvent()) { + const auto& event = *due; + + auto result = EventResult::Done; + std::visit([&](const auto& action) { + + using Action = std::decay_t; + if constexpr (std::is_same_v || std::is_same_v) + result = ownerEvent(event); + else + Run(action); + + }, event.action); + + if (result == EventResult::Defer) + break; + timeline.PopEvent(); + if (result == EventResult::Suspend) + return false; + } + + return true; + + } + + void Player::ReportMissedEvents(CheckRunner& checks) { + + for (const auto& event : timeline.GetMissedEvents()) { + auto message = "Conditional event never happened: " + event.data.dump(); + if (event.optional) + report->Warn(message); + else + checks.AddFailure({ "timeline", event.type, timeline.time, message }); + } + + } + + json Player::Expect(const json& expectation, bool& passed) { + + if (expectation.contains("lua")) + return lua.Expect(expectation, passed); + return EvaluateExpectation(*scene, expectation, passed); + + } + + void Player::Run(const InputEvent& input) { + + timeline.Fire(input); + auto time = FormatTime(timeline.time); + if (input.device == InputEvent::Device::Axis) + report->Print(time + " controller " + input.name + " " + FormatFloat(input.value, 2)); + else if (input.device == InputEvent::Device::Mouse) + report->Print(time + " mouse " + input.action + (input.action == "move" || input.action == "wheel" ? "" : " " + input.name) + + (input.position ? " at " + FormatFloat(input.position->x, 0) + ", " + FormatFloat(input.position->y, 0) : "") + + (input.action == "wheel" ? " " + FormatFloat(input.value, 1) : "")); + else + report->Print(time + (input.device == InputEvent::Device::Key ? " key " : " controller ") + input.name + " " + input.action); + + } + + void Player::Run(const LookEvent& look) { + + auto entities = FindTopmostEntities(*scene, look.entity); + if (entities.empty()) + report->Warn(FormatTime(timeline.time) + " look: no entity matches '" + look.entity + "'"); + for (auto entity : entities) + SetLookDirection(entity, look.yaw, look.pitch); + + } + + void Player::Run(const TeleportEvent& teleport) { + + auto entities = FindTopmostEntities(*scene, teleport.entity); + if (entities.empty()) + report->Warn(FormatTime(timeline.time) + " teleport: no entity matches '" + teleport.entity + "'"); + + for (auto entity : entities) { + if (auto player = entity.TryGetComponent(); player && player->IsValid()) + player->SetPosition(teleport.position); + SetWorldPosition(entity, teleport.position); + if (teleport.yaw || teleport.pitch) + SetLookDirection(entity, teleport.yaw, teleport.pitch); + report->Print(FormatTime(timeline.time) + " teleported " + GetEntityLabel(entity) + " to " + FormatVec3(teleport.position)); + } + + } + + void Player::Run(const AnimationEvent& spec) { + + auto entities = FindTopmostEntities(*scene, spec.entity); + if (entities.empty()) + report->Warn(FormatTime(timeline.time) + " animation: no entity matches '" + spec.entity + "'"); + + ResourceHandle animation; + try { + animation = LoadAnimationForScene(spec.animation, spec.model); + } + catch (const std::exception& e) { + report->Warn(FormatTime(timeline.time) + " animation: " + e.what()); + return; + } + + for (auto entity : entities) { + auto animationComponent = entity.TryGetComponent(); + if (!animationComponent) { + report->Warn(FormatTime(timeline.time) + " animation: " + GetEntityLabel(entity) + " has no animation component"); + continue; + } + animationComponent->Play(animation, spec.blendTime); + report->Print(FormatTime(timeline.time) + " playing " + animation.GetResource()->path + " on " + GetEntityLabel(entity)); + } + + } + + void Player::Run(const LogEvent& log) { + + report->Print(FormatTime(timeline.time) + " " + log.text); + + } + + void Player::Run(const ExpectEvent& expect) { + + bool passed = false; + auto result = Expect(expect.expectation, passed); + result["t"] = timeline.time; + result["passed"] = passed; + report->expectations.push_back(result); + + report->Print(FormatTime(timeline.time) + " expectation " + (passed ? "passed: " : "FAILED: ") + result.dump()); + + } + + void Player::Run(const PauseEvent& pause) { + + // The job time continues, e.g. to check that nothing moves and scripts keep their state + scene->paused = pause.pause; + report->Print(FormatTime(timeline.time) + (scene->paused ? " paused the scene" : " resumed the scene")); + + } + + void Player::Run(const EndEvent&) { + + // The remaining timed events are skipped, conditional events that didn't happen yet still fail + report->Print(FormatTime(timeline.time) + " ended the job"); + timeline.End(); + + } + + void Player::Run(const LuaEvent& event) { + + auto name = (event.file.empty() ? "event" : fs::path(event.file).filename().string()) + " at " + FormatTime(timeline.time); + if (!event.result.empty()) { + report->results[event.result] = lua.Evaluate(event.code, name); + report->Print(FormatTime(timeline.time) + " result " + event.result + " = " + report->results[event.result].dump()); + return; + } + + auto result = lua.Run(event.code, name); + if (!result.is_null()) + report->Print(FormatTime(timeline.time) + " lua returned " + result.dump()); + + } + + void Player::SetLookDirection(Scene::Entity entity, std::optional yaw, std::optional pitch) { + + auto camera = entity.TryGetComponent(); + if (!camera) { + // Entities without a camera (e.g. driven by a script) are turned around the world Y axis instead + auto transform = entity.TryGetComponent(); + if (!transform || !yaw) { + report->Warn(GetEntityLabel(entity) + " has no camera, only the yaw of its transform can be set"); + return; + } + + auto global = glm::translate(vec3(transform->globalMatrix[3])) * glm::rotate(glm::radians(*yaw), vec3(0.0f, 1.0f, 0.0f)); + transform->SetGlobal(global, scene->GetParentEntity(entity)); + report->Print(FormatTime(timeline.time) + " " + GetEntityLabel(entity) + " turned to yaw " + FormatFloat(*yaw, 1)); + return; + } + + // Yaw 0 looks towards +Z, 90 towards +X + if (yaw) + camera->rotation.x = glm::radians(*yaw); + if (pitch) + camera->rotation.y = glm::radians(*pitch); + + report->Print(FormatTime(timeline.time) + " " + GetEntityLabel(entity) + " looks at yaw " + + FormatFloat(glm::degrees(camera->rotation.x), 1) + ", pitch " + + FormatFloat(glm::degrees(camera->rotation.y), 1)); + + } + +} diff --git a/src/bridge/Player.h b/src/bridge/Player.h new file mode 100644 index 000000000..1385e494e --- /dev/null +++ b/src/bridge/Player.h @@ -0,0 +1,77 @@ +#pragma once + +#include "Timeline.h" +#include "LuaJob.h" +#include "Checks.h" +#include "Report.h" + +#include + +namespace Atlas::Bridge { + + // Plays the timeline of a job on a scene: input, mouse, Lua, look, teleport, animations, logs, expectations, pauses + // and the conditions of events. The bridge app and HostedJob use it, captures and resetScripts are left to them + class Player { + + public: + enum class EventResult { + // The next event runs + Done, + // The event runs again in the next frame, the remaining events of this frame wait for it + Defer, + // The event is done, the owner ends the frame without running more events + Suspend + }; + + using OwnerEvent = std::function; + + // Prepares the timeline, see Timeline::Reset + void Reset(const Job& job); + + // Attaches the scripts of the job, prepares its Lua in the state (the scene's by default) and starts the + // timeline. The window receives the mouse events + void Start(const Job& job, Scene::Scene& scene, std::vector events, Report& report, + sol::state* luaState, uint32_t windowId); + + void Stop(); + + // Releases input, checks the conditions and runs the due events of this frame. Returns false if an event of + // the owner suspended the frame + bool Update(const OwnerEvent& ownerEvent); + + // Conditional events that never happened are failures unless they are optional + void ReportMissedEvents(CheckRunner& checks); + + // Evaluates a condition or an expectation, Lua ones need a started player + json Expect(const json& expectation, bool& passed); + + Timeline timeline; + LuaJob lua; + + private: + void Run(const InputEvent& input); + + void Run(const LookEvent& look); + + void Run(const TeleportEvent& teleport); + + void Run(const AnimationEvent& animation); + + void Run(const LogEvent& log); + + void Run(const ExpectEvent& expect); + + void Run(const PauseEvent& pause); + + void Run(const EndEvent&); + + void Run(const LuaEvent& lua); + + void SetLookDirection(Scene::Entity entity, std::optional yaw, std::optional pitch); + + Scene::Scene* scene = nullptr; + Report* report = nullptr; + + }; + +} diff --git a/src/bridge/Processes.cpp b/src/bridge/Processes.cpp new file mode 100644 index 000000000..d5590cd2b --- /dev/null +++ b/src/bridge/Processes.cpp @@ -0,0 +1,293 @@ +#include "Processes.h" + +#include +#include +#include + +#include + +#ifdef AE_OS_WINDOWS +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#include +#else +#include +#include +#include +#include +#include +extern char** environ; +#endif + +namespace Atlas::Bridge { + + uint32_t CurrentProcessId() { + +#ifdef AE_OS_WINDOWS + return uint32_t(::GetCurrentProcessId()); +#else + return uint32_t(getpid()); +#endif + + } + + bool IsProcessRunning(uint32_t processId) { + +#ifdef AE_OS_WINDOWS + auto process = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, processId); + if (!process) + return false; + DWORD code = 0; + bool running = GetExitCodeProcess(process, &code) && code == STILL_ACTIVE; + CloseHandle(process); + return running; +#else + return kill(pid_t(processId), 0) == 0; +#endif + + } + + fs::path GetExecutablePath() { + +#ifdef AE_OS_WINDOWS + std::wstring path(MAX_PATH, L'\0'); + auto length = GetModuleFileNameW(nullptr, path.data(), DWORD(path.size())); + path.resize(length); + return fs::path(path); +#else + std::error_code error; + return fs::read_symlink("/proc/self/exe", error); +#endif + + } + +#ifdef AE_OS_WINDOWS + // Quotes an argument like the C runtime parses it + static std::wstring QuoteArgument(const std::string& arg) { + + auto wide = fs::path(arg).wstring(); + if (!wide.empty() && wide.find_first_of(L" \t\"") == std::wstring::npos) + return wide; + + std::wstring quoted = L"\""; + size_t backslashes = 0; + for (auto c : wide) { + if (c == L'\\') { + backslashes++; + continue; + } + quoted.append(c == L'"' ? backslashes * 2 + 1 : backslashes, L'\\'); + backslashes = 0; + quoted.push_back(c); + } + quoted.append(backslashes * 2, L'\\'); + quoted.push_back(L'"'); + return quoted; + + } + + static HANDLE OpenLog(const fs::path& log) { + + SECURITY_ATTRIBUTES attributes = { sizeof(SECURITY_ATTRIBUTES), nullptr, TRUE }; + return CreateFileW(log.wstring().c_str(), GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, &attributes, CREATE_ALWAYS, + FILE_ATTRIBUTE_NORMAL, nullptr); + + } + + static HANDLE Start(const std::vector& command, const fs::path& workingDirectory, const fs::path& log, DWORD flags, + uint32_t& processId) { + + std::wstring commandLine; + for (const auto& arg : command) + commandLine += (commandLine.empty() ? L"" : L" ") + QuoteArgument(arg); + + // Only the log is inherited: a child holding the output pipe of the caller would keep e.g. "| tail" waiting + auto output = OpenLog(log); + SECURITY_ATTRIBUTES attributes = { sizeof(SECURITY_ATTRIBUTES), nullptr, TRUE }; + auto input = CreateFileW(L"NUL", GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, &attributes, OPEN_EXISTING, 0, nullptr); + HANDLE inherited[] = { output, input }; + + SIZE_T size = 0; + InitializeProcThreadAttributeList(nullptr, 1, 0, &size); + std::vector attributeList(size); + auto list = reinterpret_cast(attributeList.data()); + InitializeProcThreadAttributeList(list, 1, 0, &size); + UpdateProcThreadAttribute(list, 0, PROC_THREAD_ATTRIBUTE_HANDLE_LIST, inherited, sizeof(inherited), nullptr, nullptr); + + STARTUPINFOEXW startup = {}; + startup.StartupInfo.cb = sizeof(STARTUPINFOEXW); + startup.StartupInfo.dwFlags = STARTF_USESTDHANDLES; + startup.StartupInfo.hStdInput = input; + startup.StartupInfo.hStdOutput = output; + startup.StartupInfo.hStdError = output; + startup.lpAttributeList = list; + + PROCESS_INFORMATION process = {}; + auto directory = workingDirectory.wstring(); + auto create = [&](DWORD creationFlags) { + + return CreateProcessW(nullptr, commandLine.data(), nullptr, nullptr, TRUE, creationFlags | EXTENDED_STARTUPINFO_PRESENT, nullptr, + directory.empty() ? nullptr : directory.c_str(), &startup.StartupInfo, &process); + + }; + auto created = create(flags); + // A job object of the calling shell may not allow processes to leave it + if (!created && (flags & CREATE_BREAKAWAY_FROM_JOB)) + created = create(flags & ~CREATE_BREAKAWAY_FROM_JOB); + DeleteProcThreadAttributeList(list); + CloseHandle(output); + CloseHandle(input); + if (!created) + return nullptr; + + CloseHandle(process.hThread); + processId = uint32_t(process.dwProcessId); + return process.hProcess; + + } +#endif + + uint32_t StartDetachedProcess(const fs::path& executable, const std::vector& args, const fs::path& workingDirectory, + const fs::path& log) { + + std::vector command = { executable.string() }; + command.insert(command.end(), args.begin(), args.end()); + +#ifdef AE_OS_WINDOWS + uint32_t processId = 0; + auto process = Start(command, workingDirectory, log, DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP | CREATE_BREAKAWAY_FROM_JOB, + processId); + if (!process) + return 0; + CloseHandle(process); + return processId; +#else + auto child = fork(); + if (child != 0) + return child > 0 ? uint32_t(child) : 0; + + setsid(); + auto output = open(log.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644); + dup2(output, 1); + dup2(output, 2); + if (!workingDirectory.empty() && chdir(workingDirectory.c_str()) != 0) + _exit(127); + std::vector argv; + for (auto& arg : command) + argv.push_back(arg.data()); + argv.push_back(nullptr); + execv(argv[0], argv.data()); + _exit(127); +#endif + + } + + int32_t RunProcess(const std::vector& command, const fs::path& workingDirectory, const fs::path& log, + float timeoutSeconds) { + +#ifdef AE_OS_WINDOWS + uint32_t processId = 0; + auto process = Start(command, workingDirectory, log, CREATE_NO_WINDOW, processId); + if (!process) + return -1; + + auto wait = WaitForSingleObject(process, timeoutSeconds > 0.0f ? DWORD(timeoutSeconds * 1000.0f) : INFINITE); + if (wait == WAIT_TIMEOUT) { + CloseHandle(process); + KillProcessTree(processId); + return -2; + } + + DWORD code = 0; + GetExitCodeProcess(process, &code); + CloseHandle(process); + return int32_t(code); +#else + posix_spawn_file_actions_t actions; + posix_spawn_file_actions_init(&actions); + posix_spawn_file_actions_addopen(&actions, 1, log.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644); + posix_spawn_file_actions_adddup2(&actions, 1, 2); + + std::vector arguments = command; + std::vector argv; + for (auto& arg : arguments) + argv.push_back(arg.data()); + argv.push_back(nullptr); + + auto previous = fs::current_path(); + if (!workingDirectory.empty()) + fs::current_path(workingDirectory); + pid_t child = 0; + auto spawned = posix_spawnp(&child, argv[0], &actions, nullptr, argv.data(), environ); + fs::current_path(previous); + posix_spawn_file_actions_destroy(&actions); + if (spawned != 0) + return -1; + + auto start = std::chrono::steady_clock::now(); + int status = 0; + while (waitpid(child, &status, WNOHANG) == 0) { + if (timeoutSeconds > 0.0f && SecondsSince(start) > timeoutSeconds) { + KillProcessTree(uint32_t(child)); + waitpid(child, &status, 0); + return -2; + } + std::this_thread::sleep_for(std::chrono::milliseconds(50)); + } + return WIFEXITED(status) ? WEXITSTATUS(status) : -1; +#endif + + } + + std::vector KillProcessTree(uint32_t processId) { + + std::vector killed; + +#ifdef AE_OS_WINDOWS + // Children first, a parent like a script would otherwise start new ones + std::vector> processes; + auto snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); + if (snapshot != INVALID_HANDLE_VALUE) { + PROCESSENTRY32W entry = { sizeof(PROCESSENTRY32W) }; + for (auto valid = Process32FirstW(snapshot, &entry); valid; valid = Process32NextW(snapshot, &entry)) + processes.emplace_back(uint32_t(entry.th32ProcessID), uint32_t(entry.th32ParentProcessID)); + CloseHandle(snapshot); + } + + std::vector tree = { processId }; + for (size_t i = 0; i < tree.size(); i++) + for (const auto& [child, parent] : processes) + if (parent == tree[i] && child != processId && std::find(tree.begin(), tree.end(), child) == tree.end()) + tree.push_back(child); + + for (auto it = tree.rbegin(); it != tree.rend(); ++it) { + auto process = OpenProcess(PROCESS_TERMINATE, FALSE, *it); + if (!process) + continue; + if (TerminateProcess(process, 1)) + killed.push_back(*it); + CloseHandle(process); + } +#else + if (kill(pid_t(processId), SIGKILL) == 0) + killed.push_back(processId); +#endif + + return killed; + + } + + void MoveWindowToBack(SDL_Window* window) { + +#ifdef AE_OS_WINDOWS + auto handle = static_cast(SDL_GetPointerProperty(SDL_GetWindowProperties(window), SDL_PROP_WINDOW_WIN32_HWND_POINTER, nullptr)); + // A window without one below it is at the bottom already + if (handle && GetWindow(handle, GW_HWNDNEXT)) + SetWindowPos(handle, HWND_BOTTOM, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); +#endif + + } + +} diff --git a/src/bridge/Processes.h b/src/bridge/Processes.h new file mode 100644 index 000000000..07a06340c --- /dev/null +++ b/src/bridge/Processes.h @@ -0,0 +1,31 @@ +#pragma once + +#include "Common.h" + +struct SDL_Window; + +namespace Atlas::Bridge { + + uint32_t CurrentProcessId(); + + bool IsProcessRunning(uint32_t processId); + + fs::path GetExecutablePath(); + + // Starts a process that keeps running after this one ended, its output goes into the log file. Returns its id, 0 if + // it couldn't be started + uint32_t StartDetachedProcess(const fs::path& executable, const std::vector& args, const fs::path& workingDirectory, + const fs::path& log); + + // Runs a command line (the program first) and waits for it, its output is written into the log file. Returns the exit + // code, -1 if it couldn't be started and -2 if it was ended after the timeout + int32_t RunProcess(const std::vector& command, const fs::path& workingDirectory, const fs::path& log, + float timeoutSeconds = 0.0f); + + // Ends a process and every process it started, returns the ids of the ended processes + std::vector KillProcessTree(uint32_t processId); + + // Puts a window behind all other windows without activating it, only on Windows + void MoveWindowToBack(SDL_Window* window); + +} diff --git a/src/bridge/README.md b/src/bridge/README.md new file mode 100644 index 000000000..87d7b83ee --- /dev/null +++ b/src/bridge/README.md @@ -0,0 +1,416 @@ +# Atlas Bridge + +Renders, plays, measures, checks and edits scenes from JSON jobs with the real GPU (the editor's `MainRenderer`), and +runs the same jobs inside a game with its interface. Every run writes images, `report.json`, `log.txt` and an exit code: +`0` passed, `1` a check or expectation failed, `2` error, `3` crash, `4` the client stopped waiting. + +Build: `-DATLAS_BRIDGE=ON` (executable, `ATLAS_BRIDGE_OUTPUT_NAME` names it) or `-DATLAS_BRIDGE_LIBRARY=ON` (only the +library, for game hosts). A running bridge is renamed aside when it is linked again, a build never fails on it. + +## Rules for runs + +- Use the client (`run`, `eval`): the server keeps the scene loaded, the world loads once instead of 25 s per run. +- `check` a job before the first run, it finds wrong entity names, Lua that doesn't compile and the preflight errors in + milliseconds. Every run checks its job before loading anyway. +- Run only what answers the question: one targeted job, the shortest `duration`, `end` once the result is known. A job + prints how long its previous run took; anything above a few minutes needs a reason, a suite of jobs needs the user. +- Look at `sheet.jpg` (all captures of a job, at most 1536 px wide) instead of single images; let `diff` or `compare` + decide whether something changed before looking at all. +- Measure with queries and `eval` instead of probe scripts that log values. Never guess coordinates or heights. +- Scenes load once no other engine application keeps the GPU busy and no earlier run waits for it, their scenes would + fill its memory (`--no-wait-gpu` or `"waitGpu": false` loads right away, the job fails after `gpuWaitTimeout`, + 1800 s); `status` shows whom a waiting run waits for. The window opens behind the other windows without taking the + focus, `--foreground` brings it to the front. +- Games: each build passes a short job with `"playerDisplay": true` first, the start a player gets (see Jobs in a game). +- Stopping a background shell leaves its children running: `kill ` ends a process with the processes it started, + `stop` ends the server. A killed run leaves `bin/bridge//bridge.lock`: check that the pid is gone, then delete it. + +## Commands + +```powershell +AtlasBridge [options] # direct run in this process +AtlasBridge --scene [options] # quick shot or inspection without a job file +AtlasBridge run [job options] # on the server of this executable, prints the summary +AtlasBridge eval "" [--play 3] [--scene ] # the value of Lua in the loaded scene after playing +AtlasBridge wait | status | cancel | stop # --server --detach --timeout --no-wait-gpu +AtlasBridge check ... # mistakes in jobs without loading anything +AtlasBridge inspect [--filter ] [--assembly ] [--limit n] [--out f] +AtlasBridge inspect [--filter ] [--code] [--out f] | inspect nodes [--filter ] +AtlasBridge diff [--threshold 8] [--out sheet.jpg] # images or directories, numbers per image +AtlasBridge compose [--width 1536] [--columns n] [--title t] ... +AtlasBridge bench # A/B timings of builds or shader directories +AtlasBridge kill # ends a process with the processes it started +AtlasBridge --serve | --pipeline [--from ] [--force] +``` + +The commands without a scene start in milliseconds, they don't create a window or a GPU device. Job options (also after +the job file, they override it): `--out`, `--name`, `--resolution WxH`, `--render-scale`, `--settle `, +`--timeout `, `--foreground` (the window opens in front with the focus instead of behind the other windows), +`--hidden` (no window, as fast as possible; runs stay visible by default), `--fast` (shown, as fast as +possible), `--no-shots`, `--overlay`, `--play `, `--set path=value` (settings), `--profile `, `--pause` +(pause at the start of playing), `--hitches [ms]`, `--inspect [file]`, `--sound`, `--no-wait-gpu`, +`--gpu-wait-timeout `, and before the engine starts: `--validation`, `--streaming` (on for a `--pipeline` with +`--no-shots`, which takes no pictures and so keeps the GPU memory of a world build small), `--shader-dir ` (relative +to `data/`), `--verbose` (the whole engine log, otherwise only its errors). Shot options: +`--focus `, `--views front,low`, `--camera x,y,z`, `--look-at x,y,z`, `--yaw`, `--pitch`, `--fov`, +`--distance`, `--overview`, `--passes albedo,normal`, `--shot `. Outputs: `bin/bridge//` or `--out`. + +### Client and server + +`run`, `eval`, `wait`, `status`, `cancel` and `stop` talk to `bin/bridge-server//` (`--server `). The +client starts a server when none runs and replaces one of another build or with other `--streaming`/`--validation` +options once it is idle. Commands queue in file name order, several clients share a server. The server keeps the last +scene loaded; a job for another scene, or after a job that played or edited, loads it again and keeps the meshes, +materials and textures meanwhile. While waiting for commands or for the GPU it presents with vsync, jobs run without. +The client waits up to `--timeout` (540 s), also while the server waits for the GPU, then prints the command to `wait` +for and exits with 4; `--detach` returns right away. `cancel` stops the running job, `stop` the server. + +The summary: status, duration (load, played), errors and failed checks grouped with counts, failed expectations with +their values, conditions that never happened, `results`, warnings and the outputs. Everything else is in `report.json` +and `log.txt` of the output directory. + +Server protocol, for other clients: JSON files in the directory, `{ "command": "run", "job": "" | {inline}, +"args": [...] }`, `loadScene` (`scene`, `timeout`, `camera`, `waitGpu`, `gpuWaitTimeout`), `reloadScene`, +`stop`; results in `.result.json` (`status`, `exitCode`, `reason`, `report`, `outputDirectory`), processed +commands in `done/`. `server.json` names the process, its build and its state (idle, waiting for the GPU, loading, +running), a file named `cancel` stops the job. + +### Engine applications on the machine + +The bridge and games linking `AtlasBridgeLibrary` register themselves in `LoadContent` (`InstanceRegistry`, +one file per process in `%LOCALAPPDATA%/AtlasEngine/instances`) with what they do and whether they are busy. The +editor and the demo don't, the engine doesn't know the registry. `status` lists them and whom a waiting one waits for. +Every scene load queues for the GPU: direct runs, pipelines and servers (also for commands of other programs) right +before each scene they load, games before a job starts them (they pass `--no-wait-gpu` and `--gpu-wait-timeout ` of +their command line to the job). A waiting process isn't busy. It loads once nothing is busy and nobody waits longer, +after claiming the GPU for one more check, so two processes starting together don't load at once. Games register as +busy while they run, a run waits for a game until `gpuWaitTimeout`. + +## Jobs + +```jsonc +{ + "scene": "scenes/Kingdom.aescene", // relative to data/ or the job; the only required key + "name": "kingdom", "out": "...", // defaults: file name, bin/bridge/ + "resolution": [1280, 720], "renderScale": 0.75, "settleFrames": 60, "loadTimeout": 300, "fixedDt": 0.016667, + "showWindow": true, "foreground": false, "realTime": true, "pathTrace": false, "waitGpu": true, "gpuWaitTimeout": 1800, + "settings": { "fog": { "density": 0.02 } }, "variants": [ { "name": "noFog", "settings": { "fog": { "enable": false } } } ], + "inspect": { "file": "scene.json", "filter": ["*Gate*"], "detail": ["Player"] }, + "queries": [], "edit": {}, "shots": [], + "play": true, "duration": 5.0, "observer": { /* camera */ }, "scripts": ["test.lua", { "script": "x.lua", "entity": "Player" }], + "timeline": [], "strips": [], "track": { "entities": ["Guard*"], "interval": 0.25 }, + "checks": {}, "compare": { "reference": "reference/", "maxPercent": 0.5, "threshold": 8, "update": false }, + "profile": { "frames": 64 }, "hitches": { "minimumMs": 40, "relativeThreshold": 2 } +} +``` + +Unknown keys are errors. Entities are name patterns with `*` and `?` (or `#id`); a match of a parent and its children +uses the topmost. A run: check, load (all meshes, terrain and ray tracing data), `settings`, `inspect`, `queries`, `edit`, +`shots` (each after `settleFrames`), `play` with the timeline in steps of `fixedDt`, checks (once, or every +`checks.interval` while playing). The scene file only changes with `edit`. + +`bridge.project.json` in the job's directory or above: `{ "defaults": { /* job keys, the job replaces them */ }, +"preflight": ["python", "tools/lua_check.py"] }`. The preflight runs in its directory before a job that plays, with the +direct run and the client, and fails it with its output. + +`settings` patches the feature settings of the scene with merge semantics (`sky` with `clouds` and `atmosphere`, +`postProcessing`, `wind`, `occlusionCulling`, `fog`, `irradianceVolume`, `reflection`, `rtgi`, `ssgi`, `sss`, `ocean`, +an `--inspect` lists them), plus `sun` (`elevation`, `azimuth` 0 = +Z side, or `direction`; `color`, `intensity`, +`shadow: { "cascades": 3, "longRange": true }`) and `materials` (`{ "": { /* .aematerial keys */ } }`, +the running scene only, they go back to their files after the variant and the job). Patching `ocean` adds one, `null` +removes an optional feature (`fog`, `ocean`, `rtgi`, ...). `postProcessing.upscaler`: 0 none, 1 TAA, 2 FSR2, 3 FSR4, +4 DLSS (falls back to FSR2). `variants` render all shots again (`settings`, `renderScale`) with a `_variants.png` +sheet, `play` runs with the settings of the job. + +**Cameras**: `"scene"`, `"overview"`, `{ "position", "lookAt" | "yaw"/"pitch", "groundRelative" }`, focus +`{ "entity", "view", "azimuth", "elevation", "distance", "padding": 1.25, "local", "avoidOcclusion": true }`, follow +`{ "entity", "offset": [0, 2, -6], "local" }`; all `fov`, `near`, `far`. Views: `front` (+Z side), `right`, `back`, +`left`, `top`, `iso`, `low`, `lowSide` (ground level, best to see floating). + +**Shots**: `{ "name", "camera", "views": [...], "passes": [...], "settleFrames", "crop": [x, y, w, h] | { "entity", "padding": 0.15 } }`. +Views write `_.png` and `_views.png`, passes `_.png` and `_passes.png`: `albedo`, +`normal`, `geometryNormal`, `roughness`, `emissive`, `depth`, `velocity`, `stencil`, `materialIdx`, `reflection`, +`volumetric`, `clouds`, `sss`, `gi`. A crop writes `_crop.png` at full resolution. `sheet.jpg` has every capture. + +`compare` compares every image with the one of the same path in `reference`: more than `maxPercent` pixels differing by +more than `threshold` fail the job, `update` writes this run as the reference. `report.json` has `comparisons`. + +### Playing + +The `observer` (default: the scene camera) is the main camera while playing; a focus observer is framed once unless +`dynamic`. Keys move players like the editor's play mode (`W A S D`, `Left Shift`, `Space`), the mouse isn't used for +looking, `look` turns them. + +```jsonc +{ "t": 0.0, "teleport": { "entity": "Player", "position": [x, y, z], "yaw": -90 } } +{ "t": 0.0, "look": { "entity": "Player", "yaw": -90, "pitch": 0 } } // yaw 0 looks along +Z +{ "t": 0.5, "key": "E" } // or { "key": "W", "action": "down|up|press", "duration": 1 } +{ "t": 0.5, "controller": { "button": "a" } } // or { "axis": "lefty", "value": -1 }, held until changed +{ "t": 0.5, "mouse": { "click": [640, 360], "button": "left" } } // window pixels; "move": [x, y], "down"/"up": "left", "wheel": 1 +{ "t": 1.0, "lua": "OdysseyGame.context.daycycle.SetHour(21.5)" } // or { "file": "probe.lua" } +{ "t": 2.0, "lua": "OdysseyGame.context.quests.stage", "result": "stage" } // the value goes into results +{ "t": 1.0, "capture": { "name": "now" } } // live; with "camera" or "still": a still +{ "t": 2.0, "expect": { "entity": "Crate", "property": "bottom.y", "op": "<", "value": 0.1 } } +{ "t": 2.0, "expect": { "lua": "#OdysseyGame.context.ships.list", "op": ">=", "value": 3 } } +{ "t": 2.0, "log": "message" } +{ "t": 2.5, "animation": { "entity": "Fox", "animation": "Walk", "model": "skinning/Fox/Fox.gltf", "blendTime": 0.4 } } +{ "t": 3.0, "pause": true } // scripts, physics and players stand still +{ "t": 5.0, "resetScripts": true } // discards non-permanent script environments +{ "when": { "log": "*done*" }, "end": true } // ends the job, duration is only the limit +``` + +Conditions (`when`, `t` is the earliest check, `delay`, `optional`): `{ "log": "text" }` (contains, or a pattern), +`{ "lua": "expression" }` (true when not nil or false) or a property like an expectation. A condition that never +happens fails the job unless `optional`. Expectation properties: `exists`, `count`, `position.x/y/z`, `bottom.y`, +`top.y`, `yaw`, `distanceTo` (`point`), `gapToGround`; operators `< <= > >= == !=` (`tolerance`); every matching entity +has to pass. Lua expectations compare the value with `op`/`value`, without them it has to be true. + +**Lua** (`lua` events, conditions, expectations) runs in one environment over the globals of the scene's script state, +so it sees what the game scripts put there (e.g. `OdysseyGame`) and keeps its variables between events. It has `scene` +(also `GetThisScene()`) and `Bridge`, the same table as in edits (`lua` operation): `Result(key, value)` (into +`results`), `Time()`, `Fail(message)` and the functions which find, query and change entities. Lua errors end +the job. Key names are SDL names (`E`, `Space`, `Left Shift`), controller events attach a virtual game controller +(`a`, `x`, `leftshoulder`, `dpup`, `start`, `leftx`, `lefty`, `rightx`, `righty`, `lefttrigger`; sticks -1 to 1, right +and down positive). + +Live captures show the running frame; captures with their own camera are stills on a paused scene. `strips` +(`name`, `from`, `to`, `every`, `columns`, optional `camera`) write `.png` sheets of a movement. `scripts` are +attached for the run (relative to the job or `data/`). `track` writes `trace.json`. + +### Checks + +```jsonc +"checks": { + "grounded": { "entities": ["Guard*"], "meshes": ["*/SM_Env_Tree_*.aemesh"], "maxGap": 0.15, "maxSink": 0.3, + "surfaces": ["*Ground*"], "ignore": ["*Bush*"], "footprint": 3, "baseHeight": 0.3 }, + "penetration": { "entities": ["*Portcullis*"], "against": ["*"], "margin": 0.05, "minTriangles": 1 }, + "logErrors": true, // or { "ignore": ["*music.wav*"] } + "failFast": true, "invalidTransforms": true, "interval": 0.1 +} +``` + +`grounded` compares the bottom of the bounds with the ground below their center (skipping the own hierarchy and +`ignore`), `surfaces` restricts what it may stand on. `footprint` adds a grid of n x n points: where the underside of +the mesh is within `baseHeight` of its bottom, the gap to the ground must not exceed `maxGap` either, e.g. the downhill +edge of a field. `penetration` counts additional intruding triangles of other meshes. `logErrors` fails on engine and +script errors; with `failFast` the job ends at the first one (it would fail anyway) instead of running to its end. + +### Queries + +Run after loading (`queries.json`) or after an edit (`edit.queries`, `edit_queries.json`). They hit what characters +collide with (bodies by their shapes, meshes without body, terrain). + +```jsonc +{ "type": "around", "position": [...], "radius": 5 } +{ "type": "path", "points": [[x, y, z], ...], "maxStep": 0.3, "radius": 0.4, "spacing": 0.5, "snap": false } +{ "type": "route", "from": [x, z], "to": [x, z], "via": [], "cell": 2, "margin": 60, "maxSlope": 30, "maxStep": 0.6, + "clearance": 1, "avoidMaterials": [], "avoid": [], "walkOn": ["*Bridge*"], "ignore": [], "map": "route.png" } +{ "type": "route", "from": [x, z], "to": [x, y, z], "navigation": true } // on the navigation mesh like the game +{ "type": "terrain" } { "type": "buried", "entity": "Dungeon", "margin": 1 } +{ "type": "terrainMap", "file": "map.png", "min": [x, z], "max": [x, z], "size": 2048, "grid": 100, "contour": 5, + "highlight": [], "markers": [{ "position": [x, z], "radius": 10, "label": "hole" }], "paths": [] } +{ "type": "materialGraphShaders", "directory": "x/graphs", "library": true, "spirvDirectory": "out" } +``` + +- `path` checks steps and obstacles at knee and chest height; `route` is A* over a grid around the stops (holes, slopes, + avoided materials, objects; `map` shows why cells are blocked) or Detour with `navigation`; `terrainMap` draws a top + down map; `buried` lists meshes above the terrain or below holes; + terrain queries keep all cells loaded. + +### Lua measurements + +Ground heights, rays, entities, terrain samples and pixel picks are Lua: `"lua"` of a job runs after loading (after the +queries), `"edit": { "lua" }` on the edited scene; both are code or `{ "file" }` relative to the job, `Bridge.Result` +values go into `results` of `report.json`. + +```lua +local hit = scene:CastRay(Atlas.Ray(Glm.Vec3(x, 130, z), Glm.Vec3(0, -1, 0)), Atlas.SceneQueryComponents.All) +Bridge.Result("floor", { y = hit.position.y, entity = hit.entity:GetNameComponent().name, material = hit.material }) +Bridge.Result("terrain", Bridge.SampleTerrain(x, z)) -- height, slope, normal, material, hole; nil outside +local ray = Bridge.PickRay({ position = { 0, 5, 10 }, lookAt = { 0, 1, 0 } }, 640, 360) -- camera like shots +``` + +`scene:CastRay(ray, components, skip)` passes through entities for which `skip(entity)` returns true, the overload +with an entity skips it and its children. `scene:GetHierarchyBounds(entity)` gives the bounds of a hierarchy. + +### Editing + +`edit`: `operations`, `output` (default `.edit.aescene`), `overwrite`, `saveUnchanged`, `dryRun`, `queries`, +`textureFormat` (`ktx2` for imported models). Transforms, names and copies of entities are Lua (`lua` operation with +`Bridge.SetPosition`, `Bridge.SetMatrix`, `Bridge.Create` and the entity bindings). The edit writes `edit_diff.json`, runs the checks and only saves when they +pass, then loads the saved scene again to verify it. Materials and graphs an edit changed without saving them (dry +runs, failed checks) go back to their files before the server runs the next job. An overwritten scene is backed up +(`.backup-", "change": "shader" }`, the differing files are touched + before each run so the SPIR-V cache doesn't serve the other one) run interleaved in alternating order at 1920x1080, + `frames` (240) rendered and the last 64 profiled, auto exposure off and the scene paused; `rounds` (2) and up to `maxRounds` (5) while the frame + total is within twice its standard error and above 1 %. It prints every pass (or `passes`) as mean (min - max) per + build with the verdict faster, slower or inconclusive, and the pixel difference of the builds next to that of two + runs of one build. Results in `bin/bridge/bench//bench.json`. + +## Output files + +`report.json` (status, reason, errors, warnings, checks, expectations, results, comparisons, conditional events, +timings, outputs, GPU memory), `log.txt`, `sheet.jpg`, captures and sheets (`*_views.png`, `*_passes.png`, +`*_variants.png`, strips, `*_crop.png`), `scene.json`, `queries.json`, `edit_queries.json`, `edit_diff.json`, +`trace.json`, `profile.json`, `hitches.json`, `validation.json`. A run removes the outputs of the previous run listed in +its `report.json` and marks the directory with `bridge.lock` (a second run on it fails with the owner). Every run has a +`runId`. + +## Changing the bridge + +The bridge stays general: nothing specific to one game or scene goes in there, that belongs into the job files of the +project. It's built on engine functions (`Common::Image`, `Scene::CastRay`, `Renderer::PrimitiveBatch`, engine +`to_json`/`from_json`), so search `src/engine` before writing a helper, and fix a broken engine function instead of +working around it. Unlike the engine, it reports invalid jobs and edits with exceptions. + +## Source layout + +- `App`: the executable: direct runs, `--serve`, `--pipeline` and the phases of a job (load, prepare, edit, shots, play, + finish) with its renderer (`CaptureRenderer`, `Overlay`). +- `Player`, `Timeline`, `LuaJob`: the timeline of a playing job, its input, conditions and Lua, shared with `HostedJob`. +- `Job`, `Check`: job files, the command line and the project file; checks before loading. +- `Report`, `Summary`, `Checks`: the outputs, the printed summary, checks and expectations. +- `Tools`, `Client`, `Server`, `Processes`, `InstanceRegistry`: commands without the GPU, the client and server, processes, + the running engine applications. +- `SceneEditor`, `SceneTools`, `TerrainTools`, `Scatter`: edit operations, queries and brushes, each a function in a + table by its name. `SceneFile`, `Inspect`: reading scene, prefab and mesh files without loading them. +- `LuaEdit`: the `lua` operation and Lua of editor commands. `McpServer`, `McpTools`, `Mcp`: the MCP server, its job tools and `mcp`. + `WindowShot`: the window with the interface as an image. +- `Pipeline`, `Bench`, `Image`: pipelines, benchmarks, images, sheets and differences. + +Engine notes that used to be here are in `wiki/EngineNotes.md`. diff --git a/src/bridge/Report.cpp b/src/bridge/Report.cpp new file mode 100644 index 000000000..6de4573cd --- /dev/null +++ b/src/bridge/Report.cpp @@ -0,0 +1,653 @@ +#include "Report.h" +#include "Processes.h" + +#include "graphics/GraphicsDevice.h" +#include "graphics/Instance.h" +#include "graphics/MemoryManager.h" +#include "profiler/GPUProfiler.h" +#include "profiler/CPUProfiler.h" +#include "resource/ResourceManager.h" +#include "texture/Texture2D.h" +#include "Clock.h" + +#include +#include +#include +#include +#if __has_include() +#include +#endif + +#ifdef AE_OS_WINDOWS +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#else +#include +#endif + +namespace Atlas::Bridge { + + // The report the crash handlers write into + static Report* crashReport = nullptr; + + // Remove only outputs listed in the previous report + static void RemovePreviousOutputs(const fs::path& directory) { + + std::ifstream stream(directory / "report.json"); + if (!stream.is_open()) + return; + + auto previousReport = json::parse(stream, nullptr, false); + stream.close(); + if (previousReport.is_discarded() || !previousReport.contains("outputs")) + return; + + std::error_code error; + for (const auto& output : previousReport["outputs"]) { + auto path = (directory / output.get()).lexically_normal(); + if (path.lexically_relative(directory).string().starts_with("..")) + continue; + + fs::remove(path, error); + // Directories of strips and variants + auto parent = path.parent_path(); + if (parent != directory && fs::is_empty(parent, error)) + fs::remove(parent, error); + } + + } + + // Device memory of the images and buffers alive at the end of a job: textures (images with mip maps, by their + // resource path), other images (render targets, maps) and buffers by usage, plus the budget of the device heaps + static json GpuMemoryReport() { + + auto device = Graphics::GraphicsDevice::DefaultDevice; + auto allocator = device->memoryManager->allocator; + constexpr double megabyte = 1024.0 * 1024.0; + + auto allocationSize = [&](VmaAllocation allocation) -> VkDeviceSize { + if (allocation == VK_NULL_HANDLE) + return 0; + VmaAllocationInfo info; + vmaGetAllocationInfo(allocator, allocation, &info); + return info.size; + }; + + std::unordered_map texturePaths; + for (const auto& texture : ResourceManager::GetResources()) + if (texture.IsLoaded() && texture->image) + texturePaths[texture->image.get()] = texture.GetResource()->path; + + struct Entry { std::string name; VkDeviceSize size; }; + std::vector textures, images, buffers; + std::map bufferUsage; + VkDeviceSize textureBytes = 0, imageBytes = 0, bufferBytes = 0; + { + std::lock_guard lock(device->images.mutex); + for (const auto& image : device->images.data) { + auto size = allocationSize(image->allocation); + auto description = std::to_string(image->width) + "x" + std::to_string(image->height) + + (image->layers > 1 ? "x" + std::to_string(image->layers) : "") + " format " + std::to_string(int32_t(image->format)) + + ", " + std::to_string(image->mipLevels) + " mips"; + auto path = texturePaths.find(image.get()); + if (path != texturePaths.end()) { + textures.push_back({ path->second + " (" + description + ")", size }); + textureBytes += size; + } + else { + images.push_back({ description, size }); + imageBytes += size; + } + } + } + { + std::lock_guard lock(device->buffers.mutex); + for (const auto& buffer : device->buffers.data) { + auto size = allocationSize(buffer->allocation); + std::string usage = buffer->usageFlags & VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_STORAGE_BIT_KHR ? "accelerationStructure" : + buffer->usageFlags & VK_BUFFER_USAGE_VERTEX_BUFFER_BIT ? "vertex" : + buffer->usageFlags & VK_BUFFER_USAGE_INDEX_BUFFER_BIT ? "index" : + buffer->usageFlags & VK_BUFFER_USAGE_STORAGE_BUFFER_BIT ? "storage" : + buffer->usageFlags & VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT ? "uniform" : "other"; + bufferUsage[usage] += size; + buffers.push_back({ usage + " " + std::to_string(buffer->size) + " bytes", size }); + bufferBytes += size; + } + } + + auto largest = [&](std::vector& entries) { + std::sort(entries.begin(), entries.end(), [](const Entry& a, const Entry& b) { return a.size > b.size; }); + json list = json::array(); + for (size_t i = 0; i < std::min(entries.size(), size_t(25)); i++) + list.push_back({ { "name", entries[i].name }, { "megabytes", double(entries[i].size) / megabyte } }); + return list; + }; + + json usage = json::object(); + for (const auto& [name, size] : bufferUsage) + usage[name] = double(size) / megabyte; + + VmaBudget budgets[VK_MAX_MEMORY_HEAPS]; + vmaGetHeapBudgets(allocator, budgets); + const VkPhysicalDeviceMemoryProperties* properties; + vmaGetMemoryProperties(allocator, &properties); + json heaps = json::array(); + for (uint32_t i = 0; i < properties->memoryHeapCount; i++) { + if (!(properties->memoryHeaps[i].flags & VK_MEMORY_HEAP_DEVICE_LOCAL_BIT)) + continue; + heaps.push_back({ { "blockMegabytes", double(budgets[i].statistics.blockBytes) / megabyte }, + { "allocationMegabytes", double(budgets[i].statistics.allocationBytes) / megabyte }, + { "processUsageMegabytes", double(budgets[i].usage) / megabyte }, + { "budgetMegabytes", double(budgets[i].budget) / megabyte } }); + } + + return { + { "textureMegabytes", double(textureBytes) / megabyte }, { "textureCount", textures.size() }, + { "otherImageMegabytes", double(imageBytes) / megabyte }, { "otherImageCount", images.size() }, + { "bufferMegabytes", double(bufferBytes) / megabyte }, { "bufferCount", buffers.size() }, + { "bufferMegabytesByUsage", usage }, { "deviceHeaps", heaps }, + { "largestTextures", largest(textures) }, { "largestOtherImages", largest(images) }, { "largestBuffers", largest(buffers) } + }; + + } + + void Report::InstallCrashHandlers() { + + crashReport = this; + + std::set_terminate([]() { + + std::string reason = "std::terminate"; + if (auto exception = std::current_exception()) { + try { + std::rethrow_exception(exception); + } + catch (const std::exception& e) { + reason += " with uncaught exception: " + std::string(e.what()); + } + catch (...) { + reason += " with an unknown exception"; + } + } + crashReport->WriteCrash(reason); + std::_Exit(crashReport->written ? crashReport->exitCode : 3); + + }); + + std::signal(SIGABRT, [](int32_t) { + + crashReport->WriteCrash("abort"); + std::_Exit(crashReport->written ? crashReport->exitCode : 3); + + }); + +#ifdef AE_OS_WINDOWS + SetUnhandledExceptionFilter([](EXCEPTION_POINTERS* info) -> LONG { + + char code[32]; + std::snprintf(code, sizeof(code), "0x%08lX", info->ExceptionRecord->ExceptionCode); + crashReport->WriteCrash(std::string("unhandled exception ") + code); + std::_Exit(crashReport->written ? crashReport->exitCode : 3); + + }); +#endif + + } + + void Report::Reset(const Job& job) { + + jobName = job.name; + outputDirectory = job.outputDirectory; + showWindow = job.showWindow; + + data = json(); + errors.clear(); + warnings.clear(); + expectations = json::array(); + results = json::object(); + outputs = json::array(); + logErrorCount = 0; + exitCode = 0; + written = false; + reportPath.clear(); + frameTimes.clear(); + + std::lock_guard lock(validationMutex); + validationMessages.clear(); + + } + + std::string Report::Begin() { + + fs::create_directories(outputDirectory); + runId = std::to_string(std::chrono::system_clock::now().time_since_epoch() / std::chrono::seconds(1)) + "-" + + std::to_string(CurrentProcessId()); + + // Prevent concurrent runs from mixing outputs + auto path = outputDirectory / "bridge.lock"; + bool locked = false; + for (int32_t attempt = 0; attempt < 2 && !locked; attempt++) { + // Exclusive creation, only one process can succeed + if (auto file = std::fopen(path.string().c_str(), "wx")) { + auto content = json { { "pid", CurrentProcessId() }, { "job", jobName }, { "runId", runId } }.dump(); + std::fputs(content.c_str(), file); + std::fclose(file); + lockPath = path; + locked = true; + break; + } + + std::ifstream stream(path); + auto lock = json::parse(stream, nullptr, false); + stream.close(); + auto processId = lock.is_object() ? lock.value("pid", uint32_t(0)) : uint32_t(0); + if (processId != 0 && IsProcessRunning(processId)) + return "The output directory " + outputDirectory.string() + " is used by capture process " + + std::to_string(processId) + " (job '" + lock.value("job", std::string()) + "', run " + + lock.value("runId", std::string()) + "). Wait for it or choose another directory with --out"; + + // Left behind by a process that crashed or was killed + std::error_code error; + fs::remove(path, error); + } + if (!locked) + return "Couldn't create the lock file " + path.string(); + + // The duration of the previous run tells how long this one takes + { + std::ifstream stream(outputDirectory / "report.json"); + auto previous = json::parse(stream, nullptr, false); + previousSeconds = previous.is_object() && previous.contains("totalSeconds") ? previous["totalSeconds"].get() : 0.0f; + } + + // Clear stale outputs before recording the running state + RemovePreviousOutputs(outputDirectory); + reportPath = outputDirectory / "report.json"; + json running = { { "job", jobName }, { "runId", runId }, { "status", "running" }, { "pid", CurrentProcessId() } }; + WriteFileAtomic(reportPath, running.dump(2)); + logFile.open(outputDirectory / "log.txt"); + + return {}; + + } + + void Report::End() { + + ReleaseLock(); + logFile.close(); + + } + + void Report::Write(const json& result) { + + data.update(result); + data["outputs"] = outputs; + data["gpuMemory"] = GpuMemoryReport(); + + WriteJson("report.json", data); + written = true; + + } + + void Report::Print(const std::string& message) { + + std::printf("[bridge] %s\n", message.c_str()); + std::fflush(stdout); + + if (showWindow) { + auto color = vec4(0.85f, 0.85f, 0.85f, 1.0f); + if (message.starts_with("ERROR") || message.starts_with("FAILED")) + color = vec4(1.0f, 0.4f, 0.35f, 1.0f); + else if (message.starts_with("WARNING")) + color = vec4(1.0f, 0.8f, 0.3f, 1.0f); + else if (message.starts_with("Status: passed")) + color = vec4(0.45f, 0.9f, 0.45f, 1.0f); + outputLines.push_back({ message, color }); + if (outputLines.size() > 200) + outputLines.pop_front(); + } + + if (logFile.is_open()) + logFile << "[bridge] " << message << "\n"; + + } + + void Report::Warn(const std::string& message) { + + warnings.push_back(message); + Print("WARNING: " + message); + + } + + void Report::Error(const std::string& message) { + + errors.push_back(message); + Print("ERROR: " + message); + + } + + void Report::WriteJson(const std::string& fileName, const json& j) { + + auto path = outputDirectory / fileName; + fs::create_directories(path.parent_path()); + + if (!WriteFileAtomic(path, j.dump(2))) + Warn("Couldn't write " + path.string()); + + outputs.push_back(fileName); + + } + + void Report::AddOutput(const std::string& path) { + + outputs.push_back(path); + + } + + const json& Report::GetOutputs() const { + + return outputs; + + } + + std::vector Report::CollectLog() { + + auto entries = Log::GetEntriesSince(logIndex); + logIndex += entries.size(); + + for (const auto& entry : entries) { + std::string type = entry.type == Log::TYPE_ERROR ? "ERROR" : (entry.type == Log::TYPE_WARNING ? "WARNING" : "INFO"); + if (logFile.is_open()) + logFile << "[" << FormatFloat(entry.time, 2) << "] " << type << ": " << entry.message << "\n"; + + if (entry.type == Log::TYPE_ERROR) { + logErrorCount++; + std::printf("[engine] ERROR: %s\n", entry.message.c_str()); + } + } + + if (logFile.is_open()) + logFile.flush(); + + return entries; + + } + + void Report::SkipLog() { + + logIndex = Log::GetEntryCount(); + + } + + void Report::BeginFrame(int32_t profileFrames) { + + if (profileFrames <= 0) + return; + + frameTimes.push_back(Clock::GetDelta() * 1000.0f); + if (frameTimes.size() > size_t(profileFrames)) + frameTimes.pop_front(); + + } + + bool Report::EnableValidation() { + + if (validationMessenger != VK_NULL_HANDLE) + return true; + + auto instance = Graphics::Instance::DefaultInstance; + if (!instance->extendedValidationEnabled) + return false; + + VkDebugUtilsMessengerCreateInfoEXT createInfo = {}; + createInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT; + createInfo.messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT; + createInfo.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT; + createInfo.pfnUserCallback = ValidationCallback; + createInfo.pUserData = this; + VK_CHECK(vkCreateDebugUtilsMessengerEXT(instance->GetNativeInstance(), &createInfo, nullptr, &validationMessenger)) + + Print("Validation: GPU assisted, synchronization and best practices validation enabled"); + return true; + + } + + bool Report::IsValidationEnabled() const { + + return validationMessenger != VK_NULL_HANDLE; + + } + + void Report::DestroyValidation() { + + if (validationMessenger != VK_NULL_HANDLE) + vkDestroyDebugUtilsMessengerEXT(Graphics::Instance::DefaultInstance->GetNativeInstance(), validationMessenger, nullptr); + validationMessenger = VK_NULL_HANDLE; + + } + + void Report::WriteProfile(int32_t frames) { + + // The queries of a thread with their total, printed as well if requested + auto addThread = [&](const Profiler::ThreadData& thread, const std::string& label, bool print) { + + double total = 0.0; + auto threadJson = ThreadToJson(thread, 0.0, total); + + if (print) { + Print(label + " " + thread.name + ": " + FormatFloat(float(total), 3) + " ms per frame"); + for (const auto& query : threadJson["queries"]) + if (query["depth"].get() <= 1 && query["ms"].get() >= 0.05) + Print(" " + FormatFloat(query["ms"].get(), 3) + " ms " + query["query"].get()); + } + + return threadJson; + + }; + + json profile; + profile["frames"] = frames; + for (const auto& thread : GPUProfiler::GetQueriesAverage(uint32_t(frames))) + profile["threads"].push_back(addThread(thread, "GPU", true)); + + auto cpuThreads = CPUProfiler::GetQueriesAverage(uint32_t(frames)); + + // The frame times come from the engine clock, the parts of the main thread from the CPU profiler + if (!frameTimes.empty()) { + double frameSum = 0.0; + float maxFrame = 0.0f; + for (auto frameTime : frameTimes) { + frameSum += frameTime; + maxFrame = std::max(maxFrame, frameTime); + } + + std::function&, const std::string&)> findMilliseconds = + [&](const std::vector& queries, const std::string& name) { + double milliseconds = 0.0; + for (const auto& query : queries) + milliseconds += query.name == name ? double(query.elapsedTime) / 1000000.0 : findMilliseconds(query.children, name); + return milliseconds; + }; + auto mainThread = std::find_if(cpuThreads.begin(), cpuThreads.end(), [](const auto& thread) { return thread.name == "Main"; }); + auto mainMilliseconds = [&](const std::string& name) { + return mainThread != cpuThreads.end() ? Round(findMilliseconds(mainThread->queries, name), 4) : 0.0; + }; + + profile["cpu"] = { { "frames", frameTimes.size() }, { "frameMs", Round(frameSum / double(frameTimes.size()), 4) }, + { "maxFrameMs", Round(maxFrame, 4) }, { "waitForGpuMs", mainMilliseconds("Wait for previous frame") }, + { "sceneUpdateMs", mainMilliseconds("Scene update") }, { "renderMs", mainMilliseconds("Capture render") } }; + Print("CPU frame " + FormatFloat(float(profile["cpu"]["frameMs"].get()), 3) + " ms: scene update " + + FormatFloat(float(profile["cpu"]["sceneUpdateMs"].get()), 3) + " ms, render " + + FormatFloat(float(profile["cpu"]["renderMs"].get()), 3) + " ms, waiting for the GPU " + + FormatFloat(float(profile["cpu"]["waitForGpuMs"].get()), 3) + " ms"); + } + + // The workers are only in the file + for (const auto& thread : cpuThreads) + profile["cpuThreads"].push_back(addThread(thread, "CPU", thread.name == "Main" || thread.name == "Render")); + + WriteJson("profile.json", profile); + + } + + void Report::WriteHitches(const std::vector>& hitches) { + + json hitchesJson = json::array(); + for (const auto& hitchRef : hitches) { + const auto& hitch = *hitchRef; + // Only the scopes that took a noticeable part of the frame + auto minimumMilliseconds = double(hitch.frameTime) * 0.05; + + json threads = json::array(); + std::string summary; + for (const auto& thread : hitch.threads) { + double total = 0.0; + auto threadJson = ThreadToJson(thread, minimumMilliseconds, total); + if (total < minimumMilliseconds) + continue; + + threads.push_back(threadJson); + if (thread.name == "Main" || thread.name == "Render") + for (const auto& query : threadJson["queries"]) + if (query["depth"].get() <= 2) + summary += "\n " + thread.name + ": " + FormatFloat(query["ms"].get(), 1) + " ms " + + query["query"].get(); + } + + json causes = json::array(); + for (const auto& cause : hitch.causes) + causes.push_back({ { "thread", cause.thread }, { "query", cause.path }, { "ms", Round(cause.time, 2) }, + { "averageMs", Round(cause.averageTime, 2) } }); + + hitchesJson.push_back({ { "time", Round(hitch.time, 3) }, + { "source", hitch.source == HitchRecorder::Source::GPU ? "gpu" : "cpu" }, + { "metric", HitchRecorder::GetMetricId(hitch.metric) }, { "frameMs", Round(hitch.frameTime, 2) }, + { "averageMs", Round(hitch.averageFrameTime, 2) }, { "causes", causes }, { "threads", threads } }); + Print(" Hitch " + FormatFloat(hitch.frameTime, 1) + " ms (average " + FormatFloat(hitch.averageFrameTime, 1) + + " ms) at " + FormatFloat(hitch.time, 1) + " s" + summary); + } + + Print("Hitches: " + std::to_string(hitches.size()) + (hitches.empty() ? "" : ", see hitches.json")); + WriteJson("hitches.json", { { "hitches", hitchesJson } }); + + } + + json Report::ThreadToJson(const Profiler::ThreadData& thread, double minimumMilliseconds, double& totalMilliseconds) const { + + json queries = json::array(); + std::function addQuery = + [&](const Profiler::Query& query, const std::string& parent, int32_t depth) { + + auto milliseconds = double(query.elapsedTime) / 1000000.0; + if (milliseconds < minimumMilliseconds) + return; + + auto path = parent.empty() ? query.name : parent + " / " + query.name; + queries.push_back({ { "query", path }, { "depth", depth }, { "calls", query.calls }, { "ms", Round(milliseconds, 4) } }); + for (const auto& child : query.children) + addQuery(child, path, depth + 1); + + }; + + totalMilliseconds = 0.0; + for (const auto& query : thread.queries) { + totalMilliseconds += double(query.elapsedTime) / 1000000.0; + addQuery(query, "", 0); + } + + return json { { "thread", thread.name }, { "ms", Round(totalMilliseconds, 4) }, { "queries", queries } }; + + } + + void Report::WriteValidation() { + + std::lock_guard lock(validationMutex); + + // Errors first, then the most frequent messages + std::vector> sorted(validationMessages.begin(), validationMessages.end()); + std::sort(sorted.begin(), sorted.end(), [](const auto& a, const auto& b) { + + bool aError = a.second.severity == "error", bError = b.second.severity == "error"; + if (aError != bError) + return aError; + return a.second.count > b.second.count; + + }); + + json messages = json::array(); + std::map counts = { { "error", 0 }, { "warning", 0 }, { "performance", 0 } }; + for (const auto& [id, message] : sorted) { + messages.push_back({ { "id", id }, { "severity", message.severity }, { "count", message.count }, + { "message", message.message } }); + counts[message.severity]++; + } + + json summary = { { "errors", counts["error"] }, { "warnings", counts["warning"] }, + { "performance", counts["performance"] } }; + WriteJson("validation.json", { { "summary", summary }, { "messages", messages } }); + data["validation"] = summary; + + Print("Validation: " + std::to_string(counts["error"]) + " errors, " + std::to_string(counts["warning"]) + + " warnings, " + std::to_string(counts["performance"]) + " performance warnings (distinct ids)"); + for (const auto& [id, message] : sorted) { + if (message.severity == "error") + Print("VALIDATION " + id + " (" + std::to_string(message.count) + "x)"); + } + + } + + VkBool32 Report::ValidationCallback(VkDebugUtilsMessageSeverityFlagBitsEXT severity, + VkDebugUtilsMessageTypeFlagsEXT type, const VkDebugUtilsMessengerCallbackDataEXT* data, void* userData) { + + auto report = static_cast(userData); + auto id = data->pMessageIdName ? std::string(data->pMessageIdName) : std::to_string(data->messageIdNumber); + + std::lock_guard lock(report->validationMutex); + auto& message = report->validationMessages[id]; + if (message.count++ == 0) { + if (severity == VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT) + message.severity = "error"; + else + message.severity = type & VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT ? "performance" : "warning"; + // Contains the involved objects with their debug names + message.message = data->pMessage; + } + + return VK_FALSE; + + } + + void Report::ReleaseLock() { + + if (lockPath.empty()) + return; + std::error_code error; + fs::remove(lockPath, error); + lockPath.clear(); + + } + + void Report::WriteCrash(const std::string& reason) { + + auto message = "[bridge] CRASH: " + reason; +#if defined(__cpp_lib_stacktrace) && __cpp_lib_stacktrace >= 202011L + message += "\nStack trace:\n" + std::to_string(std::stacktrace::current()); +#endif + std::fprintf(stderr, "%s\n", message.c_str()); + std::fprintf(stdout, "%s\n", message.c_str()); + std::fflush(stderr); + std::fflush(stdout); + + // The result of a job that finished is kept, e.g. when the shutdown crashes + if (!written && !reportPath.empty()) { + json report = { { "job", jobName }, { "runId", runId }, { "status", "crashed" }, { "exitCode", 3 }, + { "reason", reason } }; + WriteFileAtomic(reportPath, report.dump(2)); + } + ReleaseLock(); + + } + +} diff --git a/src/bridge/Report.h b/src/bridge/Report.h new file mode 100644 index 000000000..274c95670 --- /dev/null +++ b/src/bridge/Report.h @@ -0,0 +1,137 @@ +#pragma once + +#include "Job.h" +#include "CaptureRenderer.h" + +#include "Log.h" +#include "graphics/Common.h" +#include "profiler/HitchRecorder.h" + +#include +#include +#include +#include +#include + +namespace Atlas::Bridge { + + // The results of a job in its output directory: report.json, log.txt and the other JSON outputs, the + // printed output, the profile and the validation messages. Writes a report for crashes as well + class Report { + + public: + // Crashes write a report with the status "crashed" and exit with code 3 + void InstallCrashHandlers(); + + // Clears the report for a job, it is written to the output directory of the job + void Reset(const Job& job); + + // Starts the report in the output directory: takes the lock of the directory, removes the outputs of the + // previous run, writes the running state and opens log.txt. Returns an error if another process uses the directory + std::string Begin(); + + // Releases the lock of the output directory and closes log.txt + void End(); + + // Writes report.json with the result, the outputs and the GPU memory. The result can't change anymore, + // even if the shutdown crashes + void Write(const json& result); + + void Print(const std::string& message); + + void Warn(const std::string& message); + + void Error(const std::string& message); + + // Written to the output directory and listed as an output + void WriteJson(const std::string& fileName, const json& j); + + // A path relative to the output directory + void AddOutput(const std::string& path); + + const json& GetOutputs() const; + + // Engine log entries since the last call, written to log.txt + std::vector CollectLog(); + + // Engine log entries before this are not reported + void SkipLog(); + + // Keeps the frame times of the last frames for the profile, the other CPU times come from the CPU profiler + void BeginFrame(int32_t profileFrames); + + // Returns false if the validation layers aren't available + bool EnableValidation(); + + // Writes the GPU timings averaged over the last frames and the CPU times to profile.json + void WriteProfile(int32_t frames); + + // Writes the hitches of the job with their CPU profile to hitches.json and prints them + void WriteHitches(const std::vector>& hitches); + + // Writes the validation messages grouped by their id to validation.json + void WriteValidation(); + + bool IsValidationEnabled() const; + + void DestroyValidation(); + + // Fields of report.json besides the result, e.g. the edit + json data; + + std::vector errors; + std::vector warnings; + json expectations = json::array(); + // Values of Bridge.Result(key, value) + json results = json::object(); + int32_t logErrorCount = 0; + + int32_t exitCode = 0; + std::string runId; + // Duration of the previous run in the output directory, 0 if unknown + float previousSeconds = 0.0f; + + // Lines of the output panel of a shown window + std::deque outputLines; + bool showWindow = true; + + private: + struct ValidationMessage { + + std::string severity; + std::string message; + int32_t count = 0; + + }; + + static VKAPI_ATTR VkBool32 VKAPI_CALL ValidationCallback(VkDebugUtilsMessageSeverityFlagBitsEXT severity, + VkDebugUtilsMessageTypeFlagsEXT type, const VkDebugUtilsMessengerCallbackDataEXT* data, void* userData); + + void ReleaseLock(); + + void WriteCrash(const std::string& reason); + + // The queries of a thread as a flat list with paths, queries below the minimum time are left out + json ThreadToJson(const Profiler::ThreadData& thread, double minimumMilliseconds, double& totalMilliseconds) const; + + std::string jobName; + fs::path outputDirectory; + fs::path lockPath; + // Set once the report of a job began, the crash handlers write into it + fs::path reportPath; + json outputs = json::array(); + bool written = false; + + std::ofstream logFile; + size_t logIndex = 0; + + std::deque frameTimes; + + // Message id -> message, the validation layers call back from any thread + VkDebugUtilsMessengerEXT validationMessenger = VK_NULL_HANDLE; + std::map validationMessages; + std::mutex validationMutex; + + }; + +} diff --git a/src/bridge/Scatter.cpp b/src/bridge/Scatter.cpp new file mode 100644 index 000000000..273f4a788 --- /dev/null +++ b/src/bridge/Scatter.cpp @@ -0,0 +1,683 @@ +#include "Scatter.h" +#include "SceneEditor.h" +#include "TerrainTools.h" + +#include "common/MathHelper.h" +#include "common/MatrixDecomposition.h" +#include "jobsystem/JobSystem.h" +#include "physics/ShapesManager.h" +#include "scene/prefabs/MeshInstance.h" + +#include +#include +#include + +#include +#include + +#include +#include +#include +#include + +namespace Atlas::Bridge { + + using namespace Scene::Components; + + // Circle (optionally a ring), rectangle, polygon or a corridor along a polyline + struct Area { + + enum class Type { Circle, Rect, Polygon, Corridor } type = Type::Circle; + vec2 center = vec2(0.0f); + float radius = 0.0f; + float innerRadius = 0.0f; + vec2 min = vec2(0.0f), max = vec2(0.0f); + std::vector points; + float halfWidth = 0.0f; + + bool Contains(vec2 point) const { + + switch (type) { + case Type::Circle: { + auto distance = glm::distance(point, center); + return distance <= radius && distance >= innerRadius; + } + case Type::Rect: + return glm::all(glm::greaterThanEqual(point, min)) && glm::all(glm::lessThanEqual(point, max)); + case Type::Polygon: + return Helper::Math::IsInsidePolygon(point, points); + case Type::Corridor: + for (size_t i = 1; i < points.size(); i++) + if (Helper::Math::DistanceToSegment(point, points[i - 1], points[i]) <= halfWidth) + return true; + return false; + } + return false; + + } + + void GetBounds(vec2& boundsMin, vec2& boundsMax) const { + + switch (type) { + case Type::Circle: + boundsMin = center - vec2(radius); + boundsMax = center + vec2(radius); + break; + case Type::Rect: + boundsMin = min; + boundsMax = max; + break; + default: + boundsMin = vec2(FLT_MAX); + boundsMax = vec2(-FLT_MAX); + for (auto point : points) { + boundsMin = glm::min(boundsMin, point - vec2(halfWidth)); + boundsMax = glm::max(boundsMax, point + vec2(halfWidth)); + } + } + + } + + }; + + static Area ParseArea(const json& j) { + + Area area; + if (j.contains("radius")) { + area.type = Area::Type::Circle; + area.center = ToVec2(j.at("center")); + area.radius = j["radius"].get(); + area.innerRadius = j.value("innerRadius", 0.0f); + } + else if (j.contains("min")) { + area.type = Area::Type::Rect; + area.min = ToVec2(j["min"]); + area.max = ToVec2(j.at("max")); + } + else if (j.contains("polygon")) { + area.type = Area::Type::Polygon; + for (const auto& point : j["polygon"]) + area.points.push_back(ToVec2(point)); + if (area.points.size() < 3) + throw std::runtime_error("scatter: a polygon needs at least 3 points"); + } + else if (j.contains("path")) { + area.type = Area::Type::Corridor; + for (const auto& point : j["path"]) + area.points.push_back(ToVec2(point)); + area.halfWidth = j.at("width").get() * 0.5f; + if (area.points.size() < 2) + throw std::runtime_error("scatter: a path needs at least 2 points"); + } + else { + throw std::runtime_error("scatter: an area needs center/radius, min/max, polygon or path/width: " + j.dump()); + } + return area; + + } + + std::function MakeAreaTest(const json& area, vec2& boundsMin, vec2& boundsMax) { + + auto parsed = ParseArea(area); + parsed.GetBounds(boundsMin, boundsMax); + return [parsed](vec2 point) { return parsed.Contains(point); }; + + } + + struct Item { + + ResourceHandle mesh; + std::string name; + float weight = 1.0f; + vec2 scale = vec2(1.0f); + // Factor on the height, e.g. for wide flat patches of grass + float scaleY = 1.0f; + // Largest height difference between the ground below the footprint and the plane of the instance, 0 for any + float flatness = 0.0f; + vec2 yaw = vec2(0.0f, 360.0f); + float tilt = 0.0f; + // Fixed rotation around the local x axis after the yaw, e.g. for fallen objects + float pitch = 0.0f; + float align = 0.0f; + float sink = 0.0f; + // Height of the lowest point of the pitched mesh relative to its pivot, at scale 1 + float bottom = 0.0f; + // Footprint radius at scale 1 + float radius = 0.5f; + float height = 1.0f; + // Empty, "mesh" or "capsule" + std::string body; + float bodyRadius = 0.3f; + float bodyHeight = 2.0f; + // Instance name instead of " ", the index is appended if several are placed + std::string instanceName; + json light; + int32_t placed = 0; + + }; + + // Uniform grid over x/z for quick neighborhood tests + template + struct SpatialGrid { + + float cellSize = 16.0f; + std::unordered_map> cells; + + static int64_t Key(int32_t x, int32_t y) { + + return (int64_t(x) << 32) ^ int64_t(uint32_t(y)); + + } + + void Insert(vec2 min, vec2 max, const T& value) { + + auto cellMin = ivec2(glm::floor(min / cellSize)); + auto cellMax = ivec2(glm::floor(max / cellSize)); + for (auto y = cellMin.y; y <= cellMax.y; y++) + for (auto x = cellMin.x; x <= cellMax.x; x++) + cells[Key(x, y)].push_back(value); + + } + + template + bool Any(vec2 min, vec2 max, Func func) const { + + auto cellMin = ivec2(glm::floor(min / cellSize)); + auto cellMax = ivec2(glm::floor(max / cellSize)); + for (auto y = cellMin.y; y <= cellMax.y; y++) { + for (auto x = cellMin.x; x <= cellMax.x; x++) { + auto it = cells.find(Key(x, y)); + if (it == cells.end()) + continue; + for (const auto& value : it->second) + if (func(value)) + return true; + } + } + return false; + + } + + }; + + struct Blocker { + + Volume::AABB aabb; + ECS::Entity entity; + + }; + + struct Placed { + + vec2 position; + float radius; + + }; + + json Scatter(Scene::Scene& scene, const json& spec) { + + // Scenes without a terrain are scattered on the first visible surface below castFrom (default: above the scene) + Ref terrain; + if (scene.terrain.IsLoaded()) + terrain = GetCompleteTerrain(scene); + auto sceneBounds = terrain ? Volume::AABB() : GetSceneBounds(scene); + auto castFrom = spec.value("castFrom", sceneBounds.max.y + 1.0f); + + // With append, instances are added to an existing group of the same name + auto groupName = spec.at("group").get(); + auto existingGroup = scene.GetEntityByName(groupName); + auto append = spec.value("append", false); + if (existingGroup.IsValid() && !append) + throw std::runtime_error("scatter: an entity named '" + groupName + "' already exists, set \"append\": true"); + + auto area = ParseArea(spec.at("area")); + std::vector excluded; + for (const auto& exclude : spec.value("exclude", json::array())) + excluded.push_back(ParseArea(exclude)); + + // Large scatters test millions of points against hundreds of exclusions, they are looked up by their bounds + // and corridors by those of their segments + struct ExcludedPart { + const Area* area; + size_t segment; + }; + SpatialGrid excludedGrid; + excludedGrid.cellSize = 32.0f; + for (const auto& exclude : excluded) { + if (exclude.type == Area::Type::Corridor) { + for (size_t i = 1; i < exclude.points.size(); i++) + excludedGrid.Insert(glm::min(exclude.points[i - 1], exclude.points[i]) - vec2(exclude.halfWidth), + glm::max(exclude.points[i - 1], exclude.points[i]) + vec2(exclude.halfWidth), { &exclude, i }); + continue; + } + vec2 excludedMin, excludedMax; + exclude.GetBounds(excludedMin, excludedMax); + excludedGrid.Insert(excludedMin, excludedMax, { &exclude, 0 }); + } + + std::vector items; + float weightSum = 0.0f; + for (const auto& itemSpec : spec.at("items")) { + Item item; + item.mesh = LoadMeshForScene(itemSpec.at("mesh").get()); + item.name = item.mesh->name; + item.weight = itemSpec.value("weight", 1.0f); + if (itemSpec.contains("scale")) { + const auto& scale = itemSpec["scale"]; + item.scale = scale.is_array() ? vec2(scale.at(0).get(), scale.at(1).get()) : + vec2(scale.get()); + } + item.scaleY = itemSpec.value("scaleY", 1.0f); + item.flatness = itemSpec.value("flatness", 0.0f); + if (itemSpec.contains("yaw")) + item.yaw = vec2(itemSpec["yaw"].at(0).get(), itemSpec["yaw"].at(1).get()); + item.tilt = itemSpec.value("tilt", 0.0f); + item.pitch = itemSpec.value("pitch", 0.0f); + item.align = itemSpec.value("align", 0.0f); + item.sink = itemSpec.value("sink", 0.0f); + + // The lowest point of the mesh is put on the ground unless the pivot is (e.g. meshes modelled on their base) + if (!itemSpec.value("pivotOnGround", false)) { + const auto& aabb = item.mesh->data.aabb; + auto pitch = glm::rotate(glm::radians(item.pitch), vec3(1.0f, 0.0f, 0.0f)); + item.bottom = FLT_MAX; + for (int32_t corner = 0; corner < 8; corner++) { + auto point = vec3(corner & 1 ? aabb.max.x : aabb.min.x, corner & 2 ? aabb.max.y : aabb.min.y, + corner & 4 ? aabb.max.z : aabb.min.z); + item.bottom = std::min(item.bottom, vec3(pitch * vec4(point, 1.0f)).y); + } + } + + auto size = item.mesh->data.aabb.max - item.mesh->data.aabb.min; + item.radius = itemSpec.value("radius", 0.35f * std::max(size.x, size.z)); + item.height = size.y; + + auto body = itemSpec.value("body", json(false)); + item.body = body.is_boolean() ? (body.get() ? "mesh" : "") : body.get(); + if (!item.body.empty() && item.body != "mesh" && item.body != "capsule") + throw std::runtime_error("scatter: body must be false, true/\"mesh\" or \"capsule\""); + item.bodyRadius = itemSpec.value("bodyRadius", 0.15f * std::max(size.x, size.z)); + item.bodyHeight = itemSpec.value("bodyHeight", size.y * 0.6f); + + item.instanceName = itemSpec.value("name", std::string()); + item.light = itemSpec.value("light", json()); + + weightSum += item.weight; + items.push_back(item); + } + if (items.empty() || weightSum <= 0.0f) + throw std::runtime_error("scatter: no items"); + + auto count = spec.at("count").get(); + auto attempts = spec.value("attempts", count * 40); + auto seed = spec.value("seed", 1u); + auto spacing = spec.value("spacing", 0.0f); + auto clearance = spec.value("clearance", 0.5f); + auto onMeshes = spec.value("onMeshes", false); + auto slopeRange = spec.contains("slope") ? vec2(spec["slope"].at(0).get(), spec["slope"].at(1).get()) : + vec2(0.0f, 35.0f); + auto heightRange = spec.contains("height") ? vec2(spec["height"].at(0).get(), spec["height"].at(1).get()) : + vec2(-FLT_MAX, FLT_MAX); + std::vector materials; + if (spec.contains("materials")) + materials = spec["materials"].get>(); + if (!terrain && !materials.empty()) + throw std::runtime_error("scatter: materials are terrain material slots, the scene has no terrain"); + // Without a terrain every ground is a mesh + if (!terrain) + onMeshes = true; + + // Simplex noise mask for clusters and clearings: kept where the noise is above the threshold, + // with a linear probability ramp of the given softness + bool useNoise = spec.contains("noise"); + auto noiseScale = useNoise ? spec["noise"].value("scale", 60.0f) : 1.0f; + auto noiseThreshold = useNoise ? spec["noise"].value("threshold", 0.0f) : 0.0f; + auto noiseSoftness = useNoise ? spec["noise"].value("softness", 0.2f) : 0.0f; + auto noiseOffset = vec2(float(seed % 1000) * 17.31f, float(seed % 1000) * 9.73f); + + // Existing meshes block placement, except ignored entities (e.g. grass) and huge meshes like merged + // terrain pieces, which the ground raycast handles + auto ignorePatterns = spec.value("ignore", std::vector()); + auto maxBlockerSize = spec.value("maxBlockerSize", 120.0f); + + auto isIgnored = [&](const Scene::Entity& entity) { return IsInHierarchies(scene, entity, ignorePatterns); }; + + vec2 boundsMin, boundsMax; + area.GetBounds(boundsMin, boundsMax); + + // Only meshes within reach of the area can block an instance, small scatters in a large world check a few + SpatialGrid blockers; + if (clearance >= 0.0f) { + auto reach = 0.0f; + for (const auto& item : items) + reach = std::max(reach, item.radius * std::max(item.scale.x, item.scale.y)); + reach += clearance + 1.0f; + auto reachMin = boundsMin - vec2(reach), reachMax = boundsMax + vec2(reach); + + auto meshSubset = scene.GetSubset(); + for (auto entity : meshSubset) { + const auto& mesh = meshSubset.Get(entity); + if (!mesh.visible || mesh.aabb.max.x < reachMin.x || mesh.aabb.min.x > reachMax.x || + mesh.aabb.max.z < reachMin.y || mesh.aabb.min.z > reachMax.y || !mesh.mesh.IsLoaded()) + continue; + auto size = mesh.aabb.max - mesh.aabb.min; + if (size.x > maxBlockerSize || size.z > maxBlockerSize || isIgnored({ entity, &scene.entityManager })) + continue; + blockers.Insert(vec2(mesh.aabb.min.x, mesh.aabb.min.z), vec2(mesh.aabb.max.x, mesh.aabb.max.z), { mesh.aabb, entity }); + } + } + + SpatialGrid placedGrid; + placedGrid.cellSize = 8.0f; + + // Instances of earlier scatters this one keeps its spacing to as well, e.g. grass patches of other groups + for (auto entity : FindEntities(scene, spec.value("spacingWith", std::vector()))) { + auto position = GetEntityPosition(entity); + auto point = vec2(position.x, position.z); + placedGrid.Insert(point, point, { point, 0.0f }); + } + + std::mt19937 random(seed); + std::uniform_real_distribution unit(0.0f, 1.0f); + + std::map rejected; + std::vector created; + + auto tooClose = [&](vec2 point, float radius) { + + auto searchRadius = std::max(spacing, radius * 2.0f) + 1.0f; + return placedGrid.Any(point - vec2(searchRadius), point + vec2(searchRadius), [&](const Placed& other) { + + return glm::distance(other.position, point) < (spacing > 0.0f ? spacing : radius + other.radius); + + }); + + }; + + // What the instance stands on doesn't block it, e.g. a building that is a single mesh + auto blocked = [&](vec2 point, float reach, const RaycastHit& ground, float top) { + + return blockers.Any(point - vec2(reach), point + vec2(reach), [&](const Blocker& blocker) { + + const auto& aabb = blocker.aabb; + if (blocker.entity == ECS::Entity(ground.entity) || aabb.max.y < ground.position.y - 0.25f || aabb.min.y > top) + return false; + auto closest = glm::clamp(point, vec2(aabb.min.x, aabb.min.z), vec2(aabb.max.x, aabb.max.z)); + return glm::distance(closest, point) < reach; + + }); + + }; + + // The tests of an attempt only read the scene, except the spacing to earlier instances. They run in parallel in + // batches, the spacing test and the creation follow in the order of the attempts. Instances reach the ray casts + // only with the next scene update, so the result is the same as testing one attempt after the other + struct Draw { + vec2 point; + float item, scale, yaw, tilt, tiltDirection, noise; + }; + struct Candidate { + // Rejections by the tests before and after the spacing test + const char* rejectedBefore = nullptr; + const char* rejectedAfter = nullptr; + vec2 point = vec2(0.0f); + size_t item = 0; + float scale = 1.0f; + float radius = 0.0f; + mat4 matrix = mat4(1.0f); + }; + + auto evaluate = [&](const Draw& draw, Candidate& candidate) { + + auto point = draw.point; + candidate.point = point; + if (!area.Contains(point)) { + candidate.rejectedBefore = "outside"; + return; + } + auto isExcluded = excludedGrid.Any(point, point, [&](const ExcludedPart& part) { + if (part.area->type != Area::Type::Corridor) + return part.area->Contains(point); + const auto& points = part.area->points; + return Helper::Math::DistanceToSegment(point, points[part.segment - 1], points[part.segment]) <= part.area->halfWidth; + }); + if (isExcluded) { + candidate.rejectedBefore = "excluded"; + return; + } + if (useNoise) { + auto noise = glm::simplex((point + noiseOffset) / noiseScale); + auto probability = noiseSoftness > 0.0f ? + glm::clamp((noise - noiseThreshold) / noiseSoftness, 0.0f, 1.0f) : (noise >= noiseThreshold ? 1.0f : 0.0f); + if (draw.noise >= probability) { + candidate.rejectedBefore = "noise"; + return; + } + } + + TerrainSample sample; + if (terrain) { + sample = SampleTerrain(terrain, point); + } + else { + auto surface = Raycast(scene, vec3(point.x, castFrom, point.y), vec3(0.0f, -1.0f, 0.0f), + castFrom - sceneBounds.min.y + 1.0f, isIgnored); + sample.valid = surface.valid; + sample.height = surface.position.y; + sample.normal = surface.normal; + sample.slopeDegrees = glm::degrees(std::acos(Helper::Math::Saturate(surface.normal.y))); + } + if (!sample.valid || sample.hole) { + candidate.rejectedBefore = terrain ? "noTerrain" : "noGround"; + return; + } + if (sample.slopeDegrees < slopeRange.x || sample.slopeDegrees > slopeRange.y) { + candidate.rejectedBefore = "slope"; + return; + } + if (sample.height < heightRange.x || sample.height > heightRange.y) { + candidate.rejectedBefore = "height"; + return; + } + if (!materials.empty() && std::find(materials.begin(), materials.end(), sample.material) == materials.end()) { + candidate.rejectedBefore = "material"; + return; + } + + size_t itemIndex = 0; + for (float weight = items[0].weight; weight < draw.item && itemIndex + 1 < items.size();) + weight += items[++itemIndex].weight; + const auto& item = items[itemIndex]; + + auto scale = glm::mix(item.scale.x, item.scale.y, draw.scale); + auto radius = item.radius * scale; + candidate.item = itemIndex; + candidate.scale = scale; + candidate.radius = radius; + + // Wide flat items lift off convex ground and dig into hollows, up to the edge of the footprint + if (terrain && item.flatness > 0.0f) { + auto uneven = false; + for (int32_t k = 0; k < 16 && !uneven; k++) { + auto angle = float(k) * glm::quarter_pi(); + auto offset = vec2(std::cos(angle), std::sin(angle)) * radius * (k < 8 ? 0.7f : 1.4f); + auto edge = SampleTerrain(terrain, point + offset); + auto plane = sample.height - (sample.normal.x * offset.x + sample.normal.z * offset.y) / sample.normal.y; + uneven = !edge.valid || edge.hole || std::abs(edge.height - plane) > item.flatness; + } + if (uneven) { + candidate.rejectedAfter = "uneven"; + return; + } + } + + // On a terrain the ground has to be the terrain itself, something lying on it (a road, a house) is a mesh hit + auto ground = Raycast(scene, vec3(point.x, sample.height + 3.0f, point.y), vec3(0.0f, -1.0f, 0.0f), 8.0f, isIgnored); + if (!ground.valid) { + candidate.rejectedAfter = "noGround"; + return; + } + if (ground.kind != "terrain" && !onMeshes) { + candidate.rejectedAfter = "onMesh"; + return; + } + + if (clearance >= 0.0f && blocked(point, radius + clearance, ground, ground.position.y + item.height * scale * item.scaleY)) { + candidate.rejectedAfter = "blocked"; + return; + } + + // Align the up axis partially to the ground normal, then tilt randomly + auto normal = ground.kind == "terrain" ? sample.normal : ground.normal; + auto up = glm::normalize(glm::mix(vec3(0.0f, 1.0f, 0.0f), normal, item.align)); + auto tiltAngle = glm::radians(item.tilt * draw.tilt); + auto tiltAxis = vec3(std::cos(draw.tiltDirection * glm::two_pi()), 0.0f, std::sin(draw.tiltDirection * glm::two_pi())); + up = glm::normalize(glm::rotate(glm::angleAxis(tiltAngle, tiltAxis), up)); + auto alignment = glm::rotation(vec3(0.0f, 1.0f, 0.0f), up); + auto yaw = glm::radians(glm::mix(item.yaw.x, item.yaw.y, draw.yaw)); + + auto position = ground.position - up * ((item.sink + item.bottom) * scale * item.scaleY); + candidate.matrix = glm::translate(position) * glm::mat4_cast(alignment) * + glm::rotate(yaw, vec3(0.0f, 1.0f, 0.0f)) * glm::rotate(glm::radians(item.pitch), vec3(1.0f, 0.0f, 0.0f)) * + glm::scale(vec3(scale, scale * item.scaleY, scale)); + + }; + + // Large scatters take minutes while the window doesn't update + auto progressStep = std::max(attempts / 10, 1); + const int32_t batchSize = 16384; + std::vector draws; + std::vector candidates; + JobGroup jobGroup{ "Scatter", JobPriority::High }; + for (int32_t batchStart = 0; batchStart < attempts && int32_t(created.size()) < count; batchStart += batchSize) { + auto batchCount = std::min(batchSize, attempts - batchStart); + + // The random numbers are drawn in the same order as one attempt after the other + draws.resize(batchCount); + for (auto& draw : draws) { + auto point = glm::mix(boundsMin, boundsMax, vec2(unit(random), unit(random))); + // Draw all random numbers of an attempt up front, such that rejections don't shift the sequence + auto itemChoice = unit(random) * weightSum; + auto scaleChoice = unit(random), yawChoice = unit(random), tiltChoice = unit(random), + tiltDirection = unit(random), noiseChoice = unit(random); + draw = { point, itemChoice, scaleChoice, yawChoice, tiltChoice, tiltDirection, noiseChoice }; + } + + candidates.assign(batchCount, Candidate()); + JobSystem::ParallelFor(jobGroup, batchCount, std::max(batchCount / 64, 1), [&](JobData&, int32_t i) { + evaluate(draws[i], candidates[i]); + }); + JobSystem::Wait(jobGroup); + + for (int32_t i = 0; i < batchCount && int32_t(created.size()) < count; i++) { + auto attempt = batchStart + i; + if (attempts >= 1000000 && attempt > 0 && attempt % progressStep == 0) { + std::printf("[bridge] scatter %s: %d%% of the attempts, %zu placed\n", groupName.c_str(), + attempt / progressStep * 10, created.size()); + std::fflush(stdout); + } + + const auto& candidate = candidates[i]; + if (candidate.rejectedBefore) { + rejected[candidate.rejectedBefore]++; + continue; + } + auto point = candidate.point; + auto radius = candidate.radius; + if (tooClose(point, radius)) { + rejected["spacing"]++; + continue; + } + if (candidate.rejectedAfter) { + rejected[candidate.rejectedAfter]++; + continue; + } + + auto& item = items[candidate.item]; + auto scale = candidate.scale; + const auto& matrix = candidate.matrix; + auto name = item.instanceName.empty() ? groupName + " " + item.name + " " + std::to_string(created.size()) : + (count == 1 ? item.instanceName : item.instanceName + " " + std::to_string(item.placed + 1)); + auto entity = scene.CreatePrefab(item.mesh, matrix, true); + entity.AddComponent(name); + entity.GetComponent().globalMatrix = matrix; + + // A light on a child entity, offset in the space of the instance (e.g. the flame of a lantern) + if (!item.light.is_null()) { + auto offset = ToVec3(item.light.value("offset", json())); + auto lightEntity = scene.CreateEntity(); + lightEntity.AddComponent(name + " Light"); + auto& lightTransform = lightEntity.AddComponent(glm::translate(offset), true); + lightTransform.globalMatrix = matrix * glm::translate(offset); + AddLight(lightEntity, item.light); + lightEntity.SetParent(entity); + } + + if (item.body == "mesh") { + AddMeshBody(entity, item.mesh, vec3(scale)); + } + else if (item.body == "capsule") { + // Trunks and posts: a feet aligned capsule, the crown stays passable + Physics::CapsuleShapeSettings settings; + settings.radius = item.bodyRadius * scale; + settings.height = std::max(item.bodyHeight * scale - 2.0f * settings.radius, 0.01f); + entity.AddComponent(Physics::BodyCreationSettings { + .objectLayer = Physics::Layers::Static, .shape = Physics::ShapesManager::CreateShape(settings) }); + } + + placedGrid.Insert(point - vec2(radius), point + vec2(radius), { point, radius }); + created.push_back(entity); + item.placed++; + } + } + + // Children are added once all instances exist, creating components can invalidate component references. + // The group is created below the parent (or the root, scenes without one get a top level group) + Scene::Entity parent; + if (spec.contains("parent")) { + auto parents = FindEntities(scene, spec["parent"].get()); + if (parents.empty()) + throw std::runtime_error("scatter: no parent matches " + spec["parent"].dump()); + parent = parents.front(); + } + else { + parent = scene.GetRootEntity(); + } + + auto group = existingGroup; + if (!group.IsValid()) { + group = scene.CreateEntity(); + group.AddComponent(groupName); + // Without a transform the group is in the space of its parent, the scene only updates it in the next frame + group.AddComponent().globalMatrix = scene.GetGlobalMatrix(parent); + group.SetParent(parent); + } + for (auto entity : created) { + entity.SetParent(group); + // The instances were placed in world space, groups (or their parents) may have a transform + auto& transform = entity.GetComponent(); + transform.SetGlobal(transform.globalMatrix, group); + } + + json placedItems = json::object(); + for (const auto& item : items) + placedItems[item.name] = item.placed; + + json result = { + { "group", GetEntityLabel(group) }, + { "placed", created.size() }, + { "requested", count }, + { "items", placedItems }, + { "rejected", rejected } + }; + if (created.empty() && spec.value("required", false)) + throw std::runtime_error("scatter: nothing of '" + groupName + "' (" + items.front().name + ") could be placed, rejections: " + + json(rejected).dump()); + if (int32_t(created.size()) < count) + result["warning"] = "Only " + std::to_string(created.size()) + " of " + std::to_string(count) + + " instances placed, the area is too small or too restricted"; + return result; + + } + +} diff --git a/src/bridge/Scatter.h b/src/bridge/Scatter.h new file mode 100644 index 000000000..560b37c2d --- /dev/null +++ b/src/bridge/Scatter.h @@ -0,0 +1,16 @@ +#pragma once + +#include "SceneTools.h" + +#include + +namespace Atlas::Bridge { + + // Scatters mesh instances over the terrain into a new group entity, see the "scatter" edit operation + // in README.md. Placement is deterministic for a given seed. Returns placement statistics + json Scatter(Scene::Scene& scene, const json& spec); + + // Point test for a scatter area (circle or ring, rectangle, polygon or path corridor) in x/z and its bounds + std::function MakeAreaTest(const json& area, vec2& boundsMin, vec2& boundsMax); + +} diff --git a/src/bridge/SceneEditor.cpp b/src/bridge/SceneEditor.cpp new file mode 100644 index 000000000..1bf411818 --- /dev/null +++ b/src/bridge/SceneEditor.cpp @@ -0,0 +1,2103 @@ +#include "SceneEditor.h" +#include "Checks.h" +#include "MaterialGraphTools.h" +#include "Scatter.h" +#include "LuaEdit.h" +#include "TerrainTools.h" + +#include "common/MatrixDecomposition.h" +#include "common/Path.h" +#include "loader/AssetReferences.h" +#include "loader/MaterialGraphLoader.h" +#include "loader/MaterialLoader.h" +#include "loader/MeshLoader.h" +#include "loader/AnimationLoader.h" +#include "loader/ImageLoader.h" +#include "loader/KtxLoader.h" +#include "loader/ImpostorLoader.h" +#include "jobsystem/JobSystem.h" +#include "loader/ModelImporter.h" +#include "mesh/MeshSerializer.h" +#include "mesh/MeshSimplifier.h" +#include "physics/ShapesManager.h" +#include "resource/ResourceManager.h" +#include "scene/SceneSerializer.h" +#include "scene/components/ComponentSerializer.h" +#include "scene/components/LuaScriptComponent.h" +#include "scripting/Script.h" +#include "streaming/TextureStreaming.h" +#include "materialgraph/Baker.h" +#include "tools/ImpostorTool.h" +#include "Serializer.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Atlas::Bridge { + + using namespace Scene::Components; + + // Set by the edit for the models it imports (EditState::textureFormat) + static Loader::ImportTextureFormat importTextureFormat = Loader::ImportTextureFormat::Original; + + static std::vector SelectEntities(Scene::Scene& scene, const json& operation) { + + auto pattern = operation.at("entity").get(); + auto entities = FindTopmostEntities(scene, pattern); + auto all = operation.value("all", false); + + if (entities.empty()) + throw std::runtime_error("No entity matches '" + pattern + "' in " + operation.dump()); + if (!all && entities.size() > 1) { + std::string names; + for (size_t i = 0; i < entities.size() && i < 10; i++) + names += "\n " + GetEntityLabel(entities[i]); + throw std::runtime_error("'" + pattern + "' matches " + std::to_string(entities.size()) + + " entities, set \"all\": true or use a more specific pattern / #id:" + names); + } + + return entities; + + } + + static TransformComponent& GetTransform(Scene::Entity entity) { + + auto transform = entity.TryGetComponent(); + if (!transform) + throw std::runtime_error(GetEntityLabel(entity) + " has no transform component"); + + return *transform; + + } + + static void TranslateWorld(Scene::Entity entity, vec3 delta) { + + auto& transform = GetTransform(entity); + transform.SetGlobal(glm::translate(delta) * transform.globalMatrix, entity.GetScene()->GetParentEntity(entity)); + + } + + // The parent given by an operation or the root + static Scene::Entity GetParent(Scene::Scene& scene, const json& operation) { + + return operation.contains("parent") ? SelectEntities(scene, json { { "entity", operation["parent"] } }).front() : scene.GetRootEntity(); + + } + + // Added entities need unique names, such that later operations can select them + static void CheckNewName(Scene::Scene& scene, const std::string& name) { + + if (scene.GetEntityByName(name).IsValid()) + throw std::runtime_error("An entity named '" + name + "' already exists"); + + } + + static void SetName(Scene::Entity entity, const std::string& name) { + + if (auto nameComponent = entity.TryGetComponent()) + nameComponent->name = name; + else + entity.AddComponent(name); + + } + + // position is in world space, localPosition (with rotation and scale) in the space of the parent + static mat4 GetPlacement(Scene::Scene& scene, const json& operation, Scene::Entity parent) { + + Common::MatrixDecomposition decomposition; + decomposition.translation = ToVec3(operation.value("position", json())); + decomposition.rotation = glm::radians(ToVec3(operation.value("rotation", json()))); + decomposition.scale = ToVec3(operation.value("scale", json()), vec3(1.0f)); + if (!operation.contains("localPosition")) + return decomposition.Compose(); + + decomposition.translation = ToVec3(operation["localPosition"]); + auto parentMatrix = scene.GetGlobalMatrix(parent); + auto animationComponent = parent.IsValid() ? parent.TryGetComponent() : nullptr; + if (animationComponent && operation.contains("parentJoint")) + parentMatrix = parentMatrix * animationComponent->GetJointMatrix(operation["parentJoint"].get()); + return parentMatrix * decomposition.Compose(); + + } + + mat4 HierarchyMatrix(Scene::Scene& scene, Scene::Entity entity) { + + mat4 matrix(1.0f); + for (auto current = entity; current.IsValid(); current = scene.GetParentEntity(current)) + if (auto transform = current.TryGetComponent()) + matrix = transform->matrix * matrix; + return matrix; + + } + + static void Place(Scene::Entity entity, Scene::Entity parent, const mat4& global) { + + GetTransform(entity).SetGlobal(global, parent); + entity.SetParent(parent); + + } + + void AddMeshBody(Scene::Entity entity, const ResourceHandle& mesh, vec3 scale) { + + Physics::MeshShapeSettings settings = { .mesh = mesh, .scale = scale }; + entity.AddComponent(Physics::BodyCreationSettings { + .objectLayer = Physics::Layers::Static, .shape = Physics::ShapesManager::CreateShape(settings) }); + + } + + // The bounding box, convex hull or boxes of a mesh instance at its scale + static Ref CreateBodyShape(Scene::Entity entity, const json& operation) { + + auto& mesh = entity.GetComponent().mesh; + auto scale = GetTransform(entity).DecomposeGlobal().scale; + auto density = operation.value("density", 500.0f); + + Ref shape; + auto type = operation.value("shape", std::string("box")); + if (type == "box") { + Physics::BoundingBoxShapeSettings settings = { .aabb = mesh->data.aabb, .density = density, .scale = scale }; + shape = Physics::ShapesManager::CreateShape(settings); + } + else if (type == "convex") { + Physics::ConvexHullShapeSettings settings = { .mesh = mesh, .density = density, .scale = scale }; + shape = Physics::ShapesManager::CreateShape(settings); + } + else if (type == "boxes") { + // Boxes in mesh space [minX, minY, minZ, maxX, maxY, maxZ], e.g. a hull up to its deck and the rails + Physics::CompoundShapeSettings settings = { .scale = scale }; + for (const auto& box : operation.at("boxes")) { + Physics::BoundingBoxShapeSettings boxSettings = { .aabb = Volume::AABB(vec3(box[0], box[1], box[2]), + vec3(box[3], box[4], box[5])), .density = density }; + settings.children.push_back({ .shape = Physics::ShapesManager::CreateShape(boxSettings) }); + } + shape = Physics::ShapesManager::CreateShape(settings); + } + else { + throw std::runtime_error("meshBodies: shape has to be box, convex or boxes"); + } + + return shape; + + } + + // A simulated body around a mesh instance + static void AddMovableBody(Scene::Entity entity, const json& operation, bool inOcean) { + + auto shape = CreateBodyShape(entity, operation); + entity.AddComponent(Physics::BodyCreationSettings { + .objectLayer = Physics::Layers::Movable, + .friction = operation.value("friction", 0.8f), + .restitution = operation.value("restitution", 0.1f), + .buoyancy = inOcean ? operation.value("buoyancy", 0.0f) : 0.0f, + .fluidLinearDrag = operation.value("fluidLinearDrag", 0.5f), + .fluidAngularDrag = operation.value("fluidAngularDrag", 0.01f), + .startAsleep = operation.value("asleep", true), + .shape = shape }); + GetTransform(entity).isStatic = false; + + } + + void AddLight(Scene::Entity entity, const json& spec) { + + auto type = spec.value("type", std::string("point")); + if (type != "point" && type != "spot") + throw std::runtime_error("light.type must be point or spot"); + + auto& light = entity.AddComponent( + type == "point" ? LightType::PointLight : LightType::SpotLight, LightMobility::StationaryLight); + light.color = ToVec3(spec.value("color", json()), vec3(1.0f)); + light.intensity = spec.value("intensity", 1.0f); + light.volumetric = spec.value("volumetric", false); + auto radius = spec.value("radius", 20.0f); + auto shadow = spec.value("shadow", false); + auto shadowResolution = spec.value("shadowResolution", 1024); + if (type == "point") { + light.properties.point.radius = radius; + if (shadow) + light.AddPointShadow(0.25f, shadowResolution); + } + else { + // The direction is in entity space + light.properties.spot.radius = radius; + light.properties.spot.direction = + glm::normalize(ToVec3(spec.value("direction", json()), vec3(0.0f, -1.0f, 0.0f))); + light.properties.spot.innerConeAngle = glm::radians(spec.value("innerAngle", 25.0f)); + light.properties.spot.outerConeAngle = glm::radians(spec.value("outerAngle", 40.0f)); + if (shadow) + light.AddSpotShadow(2.0f, shadowResolution); + } + + } + + ResourceHandle LoadMeshForScene(const std::string& path) { + + auto meshPath = ToAssetPath(path); + if (Common::Path::GetFileType(meshPath) != "aemesh") { + auto imported = Loader::ModelImporter::ImportMesh(meshPath, true, 4096, importTextureFormat); + if (!imported) + throw std::runtime_error("Couldn't import " + meshPath); + auto directory = Common::Path::GetDirectory(meshPath); + meshPath = (directory.empty() ? "" : directory + "/") + "meshes/" + imported->name + ".aemesh"; + } + + auto mesh = ResourceManager::GetOrLoadResourceWithLoader( + meshPath, ResourceOrigin::User, Loader::MeshLoader::LoadMesh, true); + if (!mesh.IsLoaded()) + throw std::runtime_error("Couldn't load mesh " + meshPath); + + return mesh; + + } + + ResourceHandle LoadAnimationForScene(const std::string& animation, const std::string& modelPath) { + + auto animationPath = ToAssetPath(animation); + if (Common::Path::GetFileType(animationPath) != "aeanimation") { + auto path = ToAssetPath(modelPath); + auto imported = Loader::ModelImporter::ImportAnimations(path, true); + + auto match = std::find_if(imported.begin(), imported.end(), + [&](const auto& item) { return item->name == animation; }); + if (match == imported.end()) { + std::string names; + for (const auto& item : imported) + names += (names.empty() ? "" : ", ") + item->name; + throw std::runtime_error("No animation " + animation + " in " + path + " (" + names + ")"); + } + + animationPath = Loader::ModelImporter::GetAnimationFilename(path, (*match)->name); + } + + auto handle = ResourceManager::GetOrLoadResourceWithLoader( + animationPath, ResourceOrigin::User, Loader::AnimationLoader::LoadAnimation, true); + if (!handle.IsLoaded()) + throw std::runtime_error("Couldn't load animation " + animationPath); + + return handle; + + } + + static std::vector GetAnimationFiles(const Mesh::Mesh& mesh) { + + std::vector paths; + for (const auto& animation : mesh.data.animations) + paths.push_back(animation.GetResource()->path); + return paths; + + } + + // "lods": a level count or { "count", "reduction", "regenerate" } + static Mesh::MeshLodSettings GetLodSettings(const json& lods) { + + Mesh::MeshLodSettings settings; + if (!lods.is_object()) { + settings.maxLodCount = lods.get(); + return settings; + } + settings.maxLodCount = lods.value("count", settings.maxLodCount); + settings.reduction = lods.value("reduction", settings.reduction); + return settings; + + } + + // Levels of detail generated with the same settings stay, "regenerate" in an object replaces them anyway + static bool HasRequestedLods(const Mesh::Mesh& mesh, const json& lods) { + + auto settings = GetLodSettings(lods); + if (settings.maxLodCount <= 1) + return mesh.data.GetLodCount() == 1; + + const auto& generated = mesh.data.lodSettings; + return mesh.data.GetLodCount() > 1 && generated.maxLodCount == settings.maxLodCount && + generated.reduction == settings.reduction && !(lods.is_object() && lods.value("regenerate", false)); + + } + + // Waits for the levels of detail which ApplyMeshSettings started, edits save the meshes right away + static void TakeGeneratedLods(const std::vector>& meshes) { + + for (const auto& mesh : meshes) + mesh->WaitForLods(); + Mesh::Mesh::ApplyGeneratedLods(true); + + } + + // Settings of the meshCopy and meshSettings operations + static void ApplyMeshSettings(Mesh::Mesh& mesh, const json& settings) { + + mesh.invertUVs = settings.value("invertUVs", mesh.invertUVs); + mesh.cullBackFaces = settings.value("cullBackFaces", mesh.cullBackFaces); + mesh.vegetation = settings.value("vegetation", mesh.vegetation); + mesh.castShadow = settings.value("castShadow", mesh.castShadow); + mesh.rayTrace = settings.value("rayTrace", mesh.rayTrace); + mesh.minScreenSize = settings.value("minScreenSize", mesh.minScreenSize); + mesh.distanceCulling = settings.value("distanceCulling", mesh.distanceCulling); + mesh.lodPixelError = settings.value("lodPixelError", mesh.lodPixelError); + // Generated in the background, TakeGeneratedLods waits for them + if (settings.contains("lods") && !HasRequestedLods(mesh, settings["lods"])) + mesh.GenerateLods(GetLodSettings(settings["lods"])); + mesh.animationLodDistance = settings.value("animationLodDistance", mesh.animationLodDistance); + mesh.animationMaxInterval = settings.value("animationMaxInterval", mesh.animationMaxInterval); + // Fields of the soft body settings, e.g. { "maxSimulatedVertices": 300 } + if (settings.contains("softBody")) { + json softBody = mesh.softBody; + softBody.merge_patch(settings["softBody"]); + softBody.get_to(mesh.softBody); + mesh.ResetSoftBodySimulationMesh(); + } + if (settings.contains("animations")) { + mesh.data.animations.clear(); + for (const auto& path : FindAssetFiles(settings["animations"], ".aeanimation")) { + mesh.data.animations.push_back(ResourceManager::GetOrLoadResourceWithLoader( + path, ResourceOrigin::User, Loader::AnimationLoader::LoadAnimation, true)); + } + } + // Instances moved by the physics need the motion of the last frame + if (settings.contains("movable")) + mesh.mobility = settings["movable"].get() ? Mesh::MeshMobility::Movable : Mesh::MeshMobility::Stationary; + mesh.UpdatePipelines(); + + } + + // A distant impostor of views x views renderings, saved next to the mesh by SaveMesh + static void GenerateMeshImpostor(ResourceHandle& mesh, const json& spec) { + + // A pending load must finish before replacing the same resource + mesh->impostor.WaitForLoad(); + + // Copies of a mesh (meshCopy) still reference the impostor of the original + auto impostorPath = mesh.GetResource()->path + ".aeimpostor"; + if (!mesh->impostor.IsLoaded() || mesh->impostor.GetResource()->path != impostorPath) { + // A new impostor is compressed like the textures the edit imports + auto impostor = CreateRef(); + impostor->compressTextures = importTextureFormat == Loader::ImportTextureFormat::KTX2; + mesh->impostor = ResourceManager::AddResource(impostorPath, impostor); + // A referenced impostor whose file is missing stays as a resource that failed to load, it takes the new one + if (!mesh->impostor.IsLoaded()) + mesh->impostor.GetResource()->Swap(impostor); + } + + // Settings the spec leaves out stay those of the impostor that is replaced, like in the editor + auto interpolation = spec.value("interpolation", mesh->impostor->interpolation); + auto pixelDepthOffset = spec.value("pixelDepthOffset", mesh->impostor->pixelDepthOffset); + auto textureFormat = spec.value("textureFormat", std::string(mesh->impostor->compressTextures ? "ktx2" : "original")); + if (textureFormat != "original" && textureFormat != "ktx2") + throw std::runtime_error("impostor.textureFormat has to be \"original\" or \"ktx2\""); + + auto impostor = Tools::ImpostorTool::GenerateImpostor(mesh, spec.value("views", 12), spec.value("resolution", 256)); + mesh->impostor.GetResource()->Swap(impostor); + mesh->impostor->interpolation = interpolation; + mesh->impostor->pixelDepthOffset = pixelDepthOffset; + mesh->impostor->compressTextures = textureFormat == "ktx2"; + mesh->impostorDistance = spec.value("distance", mesh->impostorDistance); + mesh->impostorShadowDistance = spec.value("shadowDistance", mesh->impostorShadowDistance); + + } + + // Whether the saved impostor of a mesh was baked with these settings after the last change of the mesh, its + // materials and their textures, then baking it again would give the same result + static bool IsImpostorCurrent(ResourceHandle& mesh, const fs::path& meshFile, const json& spec) { + + mesh->impostor.WaitForLoad(); + auto impostorFile = fs::path(meshFile).concat(".aeimpostor"); + if (!mesh->impostor.IsLoaded() || mesh->impostor.GetResource()->path != mesh.GetResource()->path + ".aeimpostor" || + !fs::exists(impostorFile)) + return false; + + const auto& impostor = mesh->impostor; + auto textureFormat = spec.value("textureFormat", std::string(impostor->compressTextures ? "ktx2" : "original")); + if (impostor->views != spec.value("views", 12) || impostor->resolution != spec.value("resolution", 256) || + impostor->interpolation != spec.value("interpolation", impostor->interpolation) || + impostor->pixelDepthOffset != spec.value("pixelDepthOffset", impostor->pixelDepthOffset) || + impostor->compressTextures != (textureFormat == "ktx2") || + mesh->impostorDistance != spec.value("distance", mesh->impostorDistance) || + mesh->impostorShadowDistance != spec.value("shadowDistance", mesh->impostorShadowDistance)) + return false; + + auto baked = fs::last_write_time(impostorFile); + auto newer = [&](const std::string& path) { + auto file = fs::path(Loader::AssetLoader::GetFullPath(path)); + return fs::exists(file) && fs::last_write_time(file) > baked; + }; + if (fs::last_write_time(meshFile) > baked) + return false; + auto newerMap = [&](const ResourceHandle& map) { + return map.IsValid() && newer(map.GetResource()->path); + }; + for (const auto& material : mesh->data.materials) { + if (!material.IsLoaded()) + continue; + if (newer(material.GetResource()->path) || newerMap(material->baseColorMap) || newerMap(material->opacityMap) || + newerMap(material->normalMap) || newerMap(material->roughnessMap) || newerMap(material->metalnessMap) || + newerMap(material->aoMap) || newerMap(material->displacementMap) || newerMap(material->emissiveMap)) + return false; + } + return true; + + } + + // Turns the root of a scene file into a prefab: excluded entities (name patterns), directional lights, + // players, cameras and optionally scripts are left out, such that the prefab can be placed into another scene + static json MakePrefabFromScene(const json& operation, std::map& sceneSources) { + + auto scenePath = ToAssetPath(operation.at("scene").get()); + auto output = ToAssetPath(operation.at("output").get()); + auto outputFile = GetAssetDirectory() / output; + if (fs::exists(outputFile) && !operation.value("overwrite", false)) + throw std::runtime_error("makePrefab: " + output + " already exists, set \"overwrite\": true"); + + json imported; + const json* source = nullptr; + if (Common::Path::GetFileType(scenePath) != "aescene") { + // Model scenes (glTF, FBX, ...) are imported like in the editor, meshes and materials are saved next to the source + auto importedScene = Loader::ModelImporter::ImportScene(scenePath, vec3(-2048.0f), vec3(2048.0f), 6, true, false, + operation.value("invertUVs", false), operation.value("maxTextureResolution", 4096), importTextureFormat); + if (!importedScene) + throw std::runtime_error("makePrefab: couldn't import " + scenePath); + Scene::SceneToJson(imported, importedScene.get()); + Serializer::NestSceneEntities(imported); + source = &imported; + } + else { + // Many prefabs are cut from the same scene, it is only read once per edit + auto& cached = sceneSources[scenePath]; + if (cached.is_null()) { + std::ifstream input(GetAssetDirectory() / scenePath, std::ios::binary); + if (!input.is_open()) + throw std::runtime_error("makePrefab: couldn't open " + scenePath); + std::vector data((std::istreambuf_iterator(input)), {}); + // Scenes are stored as MessagePack or as plain JSON + auto j = !data.empty() && data[0] == '{' ? json::parse(data) : json::from_msgpack(data); + Loader::AssetReferences::ResolveReferences(j, Loader::AssetReferences::Type::Scene, scenePath); + + // Prefabs nest their entities and are readable json, binary scenes reference resources by index + // and store raw matrices. Nesting first turns binary columns into json values + Serializer::NestSceneEntities(j); + Loader::AssetReferences::InlineResourceTable(j); + std::function makeReadable = [&](json& entity) { + if (entity.contains("transform") && entity["transform"]["matrix"].is_binary()) + entity["transform"]["matrix"] = entity["transform"]["matrix"].get(); + if (entity.contains("entities")) + for (auto& child : entity["entities"]) + makeReadable(child); + }; + for (auto& entity : j["entities"]) + makeReadable(entity); + + cached = std::move(j); + } + source = &cached; + } + + const json* root = nullptr; + for (const auto& entity : source->at("entities")) + if (entity.value("root", false)) + root = &entity; + if (!root) + throw std::runtime_error("makePrefab: " + scenePath + " has no root entity"); + + auto excluded = operation.value("exclude", std::vector()); + auto keepScripts = operation.value("scripts", true); + // Plants and other small dressing shouldn't block the player + auto withoutBodies = operation.value("withoutBodies", std::vector()); + auto stripBody = [&](json& entity) { + if (entity.contains("rigidBody") && entity.contains("mesh") && + MatchAnyPattern(withoutBodies, entity["mesh"].value("resourcePath", std::string()))) + entity.erase("rigidBody"); + }; + int32_t removed = 0, kept = 0; + + auto getName = [](const json& entity) { + return entity.contains("name") ? entity["name"].value("name", std::string()) : std::string(); + }; + auto isLeftOut = [&](const json& entity) { + auto directional = entity.contains("light") && + entity["light"].value("type", -1) == int32_t(LightType::DirectionalLight); + return entity.contains("player") || directional || MatchAnyPattern(excluded, getName(entity)); + }; + + std::function filter = [&](json& entity) { + + if (!keepScripts) + entity.erase("script"); + entity.erase("camera"); + stripBody(entity); + if (!entity.contains("entities")) + return; + + json children = json::array(); + for (auto& child : entity["entities"]) { + if (isLeftOut(child)) { + removed++; + continue; + } + filter(child); + children.push_back(std::move(child)); + kept++; + } + entity["entities"] = std::move(children); + + }; + + // With an entity only its subtree becomes the prefab, e.g. one of several places built in a scene + const json* selected = root; + mat4 parentMatrix(1.0f); + if (operation.contains("entity")) { + auto pattern = operation["entity"].get(); + const json* found = nullptr; + std::function find = [&](const json& entity, const mat4& matrix) { + if (!entity.contains("entities")) + return; + for (const auto& child : entity.at("entities")) { + if (found) + return; + if (isLeftOut(child)) + continue; + if (MatchAnyPattern({ pattern }, getName(child))) { + found = &child; + parentMatrix = matrix; + return; + } + find(child, child.contains("transform") ? matrix * child["transform"].at("matrix").get() : matrix); + } + }; + find(*root, mat4(1.0f)); + if (!found) + throw std::runtime_error("makePrefab: no entity " + pattern + " in " + scenePath); + selected = found; + } + + json prefab = *selected; + filter(prefab); + + // An area collects the meshes in world space with the parent matrix, the entity included + if (operation.contains("entity") && !operation.contains("area")) { + // The children keep their hierarchy, relative to the origin + auto local = prefab.contains("transform") ? prefab["transform"].at("matrix").get() : mat4(1.0f); + auto origin = glm::translate(-ToVec3(operation.value("origin", json::array({ 0.0f, 0.0f, 0.0f })))); + for (auto& child : prefab["entities"]) { + auto childMatrix = child.contains("transform") ? child["transform"].at("matrix").get() : mat4(1.0f); + // Groups without a transform are in the space of their parent, they get one + if (!child.contains("transform")) + child["transform"]["isStatic"] = false; + child["transform"]["matrix"] = origin * parentMatrix * local * childMatrix; + } + } + + // With an area only the mesh and light entities around its center are kept, flattened and relative to the center + if (operation.contains("area")) { + auto center = ToVec3(operation["area"].at("center")); + auto radius = operation["area"].at("radius").get(); + auto excludedMeshes = operation.value("excludeMeshes", std::vector()); + auto includedMeshes = operation.value("includeMeshes", std::vector{ "*" }); + + json children = json::array(); + std::function collect = [&](const json& entity, const mat4& parentMatrix) { + + auto global = parentMatrix; + if (entity.contains("transform")) + global = parentMatrix * entity["transform"].at("matrix").get(); + + auto meshPath = entity.contains("mesh") ? entity["mesh"].value("resourcePath", std::string()) : std::string(); + auto inside = glm::distance(vec3(global[3]), center) <= radius; + if (inside && (entity.contains("light") || (!meshPath.empty() && MatchAnyPattern(includedMeshes, meshPath) && + !MatchAnyPattern(excludedMeshes, meshPath)))) { + json child = entity; + child.erase("entities"); + stripBody(child); + child["transform"]["matrix"] = glm::translate(-center) * global; + children.push_back(child); + } + for (const auto& child : entity.value("entities", json::array())) + collect(child, global); + + }; + collect(prefab, parentMatrix); + + kept = int32_t(children.size()); + if (children.empty()) + throw std::runtime_error("makePrefab: no meshes or lights in the area of " + scenePath); + prefab["entities"] = children; + } + + prefab["root"] = false; + prefab["name"] = NameComponent(operation.value("name", fs::path(output).stem().string())); + prefab["transform"] = TransformComponent(); + + Loader::AssetReferences::MakeReferences(prefab, Loader::AssetReferences::Type::Entity, output); + if (!Loader::AssetLoader::WriteJson(outputFile.string(), prefab, Loader::JsonFormat::Compact)) + throw std::runtime_error("makePrefab: couldn't write " + output); + + return { { "prefab", output }, { "entities", kept }, { "removed", removed } }; + + } + + struct EditContext { + + const Ref& sceneRef; + Scene::Scene& scene; + EditState& state; + // Many prefabs are cut from the same scene, it is only read once per edit + std::map prefabSources; + // Impostors encoded and written while meshSettings renders the next ones + JobGroup impostorWrites{ "Impostor writes" }; + // Runs of add operations share the names of the scene and the parents found by an exact name, the names of + // added entities are new. Other operations may rename or remove entities, they clear both + std::unordered_set names; + bool namesCollected = false; + // The first add of a run compares the names without collecting them + bool addedWithoutNames = false; + std::unordered_map parents; + + ~EditContext() { + + JobSystem::Wait(impostorWrites); + + } + + }; + + static json EditSnapToGround(EditContext& context, const json& operation) { + + auto& scene = context.scene; + json affected = json::array(); + + auto offset = operation.value("offset", 0.0f); + for (auto entity : SelectEntities(scene, operation)) { + auto [bounds, hasMesh, ground] = GroundBelowEntity(scene, entity, operation.value("searchAbove", 0.5f)); + if (!ground.valid) + throw std::runtime_error("No ground below " + GetEntityLabel(entity)); + + auto delta = ground.position.y + offset - bounds.min.y; + TranslateWorld(entity, vec3(0.0f, delta, 0.0f)); + affected.push_back({ { "entity", GetEntityLabel(entity) }, { "deltaY", delta }, { "ground", GetHitLabel(ground) } }); + } + + return affected; + + } + + static json EditSetVisible(EditContext& context, const json& operation) { + + auto& scene = context.scene; + json affected = json::array(); + + for (auto entity : SelectEntities(scene, operation)) { + EntitySet hierarchy; + CollectHierarchy(entity, hierarchy); + for (auto member : hierarchy) { + Scene::Entity memberEntity = { member, &scene.entityManager }; + if (auto mesh = memberEntity.TryGetComponent()) + mesh->SetVisible(operation.at("visible").get()); + } + affected.push_back(GetEntityLabel(entity)); + } + + return affected; + + } + + static json EditMaterial(EditContext& context, const json& operation) { + + auto& state = context.state; + json affected = json::array(); + + // The file is written by SaveMaterials once the checks passed + auto materialPath = ToAssetPath(operation.at("material").get()); + auto material = ResourceManager::GetOrLoadResourceWithLoader( + materialPath, ResourceOrigin::User, Loader::MaterialLoader::LoadMaterial, false); + if (!material.IsLoaded()) + throw std::runtime_error("Couldn't load material " + materialPath); + + auto changes = operation.at("set"); + json before = *material.Get(); + PatchMaterial(*material.Get(), changes); + json after = *material.Get(); + state.changedMaterials.insert(materialPath); + + json changed = json::object(); + for (auto& [key, value] : changes.items()) + changed[key] = { { "before", before.value(key, json()) }, { "after", after.value(key, json()) } }; + affected.push_back({ { "material", materialPath }, { "changes", changed } }); + + return affected; + + } + + static json EditDelete(EditContext& context, const json& operation) { + + auto& scene = context.scene; + json affected = json::array(); + + for (auto entity : SelectEntities(scene, operation)) { + affected.push_back(GetEntityLabel(entity)); + scene.DestroyEntity(entity); + } + + return affected; + + } + + static json EditAdd(EditContext& context, const json& operation) { + + auto& scene = context.scene; + json affected = json::array(); + + auto name = operation.at("name").get(); + // A single add (e.g. Bridge.Edit from Lua) compares the names once, a run of adds collects them into a set + auto nameSubset = scene.GetSubset(); + if (!context.namesCollected && !context.addedWithoutNames) { + for (auto entity : nameSubset) + if (nameSubset.Get(entity).name == name) + throw std::runtime_error("An entity named '" + name + "' already exists"); + context.names.insert(name); + context.addedWithoutNames = true; + } + else { + if (!context.namesCollected) { + for (auto entity : nameSubset) + context.names.insert(nameSubset.Get(entity).name); + context.namesCollected = true; + } + if (!context.names.insert(name).second) + throw std::runtime_error("An entity named '" + name + "' already exists"); + } + + Scene::Entity parent; + auto parentName = operation.contains("parent") ? operation["parent"].get() : std::string(); + auto exactParent = !parentName.empty() && parentName.find_first_of("*?") == std::string::npos && !parentName.starts_with('#'); + if (auto cached = context.parents.find(parentName); exactParent && cached != context.parents.end()) { + parent = cached->second; + } + else { + parent = GetParent(scene, operation); + if (exactParent) + context.parents[parentName] = parent; + } + auto global = GetPlacement(scene, operation, parent); + + ResourceHandle mesh; + if (operation.contains("mesh")) + mesh = LoadMeshForScene(operation["mesh"].get()); + + auto hasScript = operation.contains("script"); + Scene::Entity entity; + if (mesh.IsValid()) { + entity = scene.CreatePrefab(mesh, global, !hasScript); + } + else { + entity = scene.CreateEntity(); + entity.AddComponent(global, !hasScript); + } + entity.AddComponent(name); + // Follows a joint of the animated parent, the position is then relative to the joint + GetTransform(entity).parentJoint = operation.value("parentJoint", -1); + Place(entity, parent, global); + + json added = { { "entity", GetEntityLabel(entity) } }; + if (mesh.IsValid()) { + added["mesh"] = mesh.GetResource()->path; + // Hidden meshes can be shown by scripts, e.g. a lit and an unlit variant + entity.GetComponent().SetVisible(operation.value("visible", true)); + + // Use the world scale for the collision mesh + if (operation.value("body", false)) + AddMeshBody(entity, mesh, GetTransform(entity).DecomposeGlobal().scale); + } + else if (operation.contains("body")) { + throw std::runtime_error("add: a body requires a mesh"); + } + + if (operation.contains("animation")) { + if (!mesh.IsValid()) + throw std::runtime_error("add: an animation requires a mesh"); + auto animation = LoadAnimationForScene(operation["animation"].get(), + operation["mesh"].get()); + auto& animationComponent = entity.AddComponent(animation); + animationComponent.speed = operation.value("animationSpeed", 1.0f); + animationComponent.time = operation.value("animationTime", 0.0f); + added["animation"] = animation.GetResource()->path; + } + + // Main camera looking along +Z, the editor needs one to start playing + if (operation.contains("camera")) { + const auto& spec = operation["camera"]; + auto& camera = entity.AddComponent( + spec.value("fov", 70.0f), 16.0f / 9.0f, spec.value("near", 0.1f), spec.value("far", 2000.0f)); + camera.isMain = spec.value("main", true); + added["camera"] = camera.isMain ? "main" : "secondary"; + } + + if (operation.contains("light")) { + AddLight(entity, operation["light"]); + added["light"] = operation["light"].value("type", std::string("point")); + } + + // The scale of the entity is the half size of the volume + if (operation.contains("fogVolume")) { + FogVolumeComponent fogVolume = operation["fogVolume"]; + entity.AddComponent(fogVolume); + added["fogVolume"] = true; + } + + if (hasScript) { + auto scriptPath = ToAssetPath(operation["script"].get()); + auto script = ResourceManager::GetOrLoadResource(scriptPath, ResourceOrigin::User); + if (!script.IsLoaded()) + throw std::runtime_error("Couldn't load script " + scriptPath); + entity.AddComponent(script); + added["script"] = scriptPath; + } + + affected.push_back(added); + + return affected; + + } + + static json EditTerrainCopy(EditContext& context, const json& operation) { + + auto& scene = context.scene; + auto& state = context.state; + json affected = json::array(); + + CopySceneTerrain(scene, operation.at("path").get(), operation.value("overwrite", false)); + state.terrainChanged = true; + affected.push_back({ { "terrain", scene.terrain.GetResource()->path } }); + + return affected; + + } + + static json EditTerrainCreate(EditContext& context, const json& operation) { + + auto& scene = context.scene; + auto& state = context.state; + json affected = json::array(); + + affected.push_back(CreateSceneTerrain(scene, operation)); + state.terrainChanged = true; + + return affected; + + } + + static json EditTerrain(EditContext& context, const json& operation) { + + auto& scene = context.scene; + auto& state = context.state; + + // Terrain files can be shared by several scenes, edit a copy unless overwriting is explicitly allowed + if (scene.terrain.IsValid() && scene.terrain.GetResource()->path == state.loadedTerrain && + !operation.value("overwriteTerrain", false)) + throw std::runtime_error("terrain: edit a copy (terrainCopy) or set \"overwriteTerrain\": true to change " + + state.loadedTerrain); + auto affected = ApplyTerrainBrushes(scene, operation.at("brushes")); + state.terrainChanged = true; + + return affected; + + } + + static json EditShoreLine(EditContext& context, const json& operation) { + + auto& scene = context.scene; + auto& state = context.state; + json affected = json::array(); + + affected.push_back(BakeShoreLine(scene, operation)); + state.terrainChanged = true; + + return affected; + + } + + static json EditScatter(EditContext& context, const json& operation) { + + auto& scene = context.scene; + + return json::array({ Scatter(scene, operation) }); + + } + + static json EditClearArea(EditContext& context, const json& operation) { + + auto& scene = context.scene; + json affected = json::array(); + + // Removes the descendants of the selected entities (e.g. a grass group) inside a scatter area. With "under" only + // those that stand inside the footprint (x/z bounds plus "margin") of a mesh of those entities, e.g. the plants + // under a place that was put into the scene after its nature was scattered + vec2 boundsMin, boundsMax; + auto areaTest = MakeAreaTest(operation.at("area"), boundsMin, boundsMax); + std::vector footprints; + if (operation.contains("under")) { + auto margin = vec3(operation.value("margin", 0.0f), 0.0f, operation.value("margin", 0.0f)); + for (auto owner : FindEntities(scene, operation.at("under").get>())) { + EntitySet members; + CollectHierarchy(owner, members); + for (auto member : members) { + Scene::Entity entity = { member, &scene.entityManager }; + if (!entity.HasComponent() || !entity.GetComponent().mesh.IsLoaded()) + continue; + auto aabb = entity.GetComponent().mesh->data.aabb.Transform(HierarchyMatrix(scene, entity)); + footprints.push_back(Volume::AABB(aabb.min - margin, aabb.max + margin)); + } + } + } + auto inside = [&](vec3 position) { + if (!areaTest(vec2(position.x, position.z))) + return false; + if (!operation.contains("under")) + return true; + return std::any_of(footprints.begin(), footprints.end(), [&](const Volume::AABB& box) { + return position.x >= box.min.x && position.x <= box.max.x && position.z >= box.min.z && position.z <= box.max.z; }); + }; + + // The meshes in the area are checked for an ancestor of the selected entities, collecting the hierarchies of + // large groups would take longer than the whole area + auto patterns = operation.at("entities").get>(); + std::vector removed; + auto subset = scene.GetSubset(); + for (auto entity : subset) { + auto position = vec3(subset.Get(entity).globalMatrix[3]); + if (position.x < boundsMin.x || position.x > boundsMax.x || position.z < boundsMin.y || position.z > boundsMax.y || + !inside(position)) + continue; + Scene::Entity candidate = { entity, &scene.entityManager }; + if (IsInHierarchies(scene, scene.GetParentEntity(candidate), patterns)) + removed.push_back(candidate); + } + for (auto entity : removed) + scene.DestroyEntity(entity); + affected.push_back({ { "removed", removed.size() }, { "footprints", footprints.size() } }); + + return affected; + + } + + static json EditMeshSettings(EditContext& context, const json& operation) { + + json affected = json::array(); + + // Changes mesh files matching a pattern, e.g. "dungeon/meshes/*.aemesh", after backing them up once + auto pattern = ToAssetPath(operation.at("meshes").get()); + auto excluded = operation.value("exclude", std::vector()); + const auto& settings = operation.at("set"); + auto directory = GetAssetDirectory() / fs::path(pattern).parent_path(); + if (!fs::is_directory(directory)) + throw std::runtime_error("meshSettings: no directory " + directory.string()); + + struct ChangedMesh { + std::string path; + fs::path file; + ResourceHandle mesh; + bool bake; + }; + std::vector changedMeshes; + for (const auto& file : fs::directory_iterator(directory)) { + auto path = (fs::path(pattern).parent_path() / file.path().filename()).generic_string(); + if (!file.is_regular_file() || file.path().extension() != ".aemesh" || !Helper::String::MatchWildcard(pattern, path)) + continue; + if (std::ranges::any_of(excluded, [&](const auto& exclude) { return Helper::String::MatchWildcard(exclude, path); })) + continue; + + auto backup = file.path(); + backup += ".backup"; + if (!fs::exists(backup)) + fs::copy_file(file.path(), backup); + + auto mesh = LoadMeshForScene(path); + // Meshes that already have these settings and a current impostor are left as they are + auto unchanged = settings.value("invertUVs", mesh->invertUVs) == mesh->invertUVs && + settings.value("cullBackFaces", mesh->cullBackFaces) == mesh->cullBackFaces && + settings.value("vegetation", mesh->vegetation) == mesh->vegetation && + settings.value("castShadow", mesh->castShadow) == mesh->castShadow && + settings.value("rayTrace", mesh->rayTrace) == mesh->rayTrace && + settings.value("minScreenSize", mesh->minScreenSize) == mesh->minScreenSize && + settings.value("distanceCulling", mesh->distanceCulling) == mesh->distanceCulling && + settings.value("lodPixelError", mesh->lodPixelError) == mesh->lodPixelError && + (!settings.contains("lods") || HasRequestedLods(*mesh.Get(), settings["lods"])) && + settings.value("animationLodDistance", mesh->animationLodDistance) == mesh->animationLodDistance && + settings.value("animationMaxInterval", mesh->animationMaxInterval) == mesh->animationMaxInterval && + (!settings.contains("softBody") || [&]() { + json softBody = mesh->softBody, patched = softBody; + patched.merge_patch(settings["softBody"]); + return patched == softBody; + }()) && + (!settings.contains("animations") || FindAssetFiles(settings["animations"], ".aeanimation") == GetAnimationFiles(*mesh.Get())) && + settings.value("movable", mesh->mobility == Mesh::MeshMobility::Movable) == (mesh->mobility == Mesh::MeshMobility::Movable); + auto bake = settings.contains("impostor") && (!unchanged || !IsImpostorCurrent(mesh, file.path(), settings["impostor"])); + if (unchanged && !bake) + continue; + + // The levels of detail of all meshes are generated at the same time + ApplyMeshSettings(*mesh.Get(), settings); + changedMeshes.push_back({ path, file.path(), mesh, bake }); + } + + std::vector> meshes; + for (const auto& changedMesh : changedMeshes) + meshes.push_back(changedMesh.mesh); + TakeGeneratedLods(meshes); + + json changed = json::array(); + for (auto& [path, file, mesh, bake] : changedMeshes) { + changed.push_back(path); + if (!bake) { + // Levels of detail and other settings that don't change the look keep an impostor current + const std::string_view keepLook[] = { "lods", "lodPixelError", "minScreenSize", "distanceCulling", "rayTrace", "castShadow", "movable", + "animationLodDistance", "animationMaxInterval", "softBody" }; + auto lookUnchanged = std::ranges::all_of(settings.items(), [&](const auto& item) { + return std::ranges::find(keepLook, std::string_view(item.key())) != std::end(keepLook); + }); + auto impostorFile = fs::path(file).concat(".aeimpostor"); + auto current = lookUnchanged && fs::exists(impostorFile) && fs::last_write_time(impostorFile) >= fs::last_write_time(file); + Loader::MeshLoader::SaveMesh(mesh.Get(), path, true); + if (current) + fs::last_write_time(impostorFile, fs::file_time_type::clock::now()); + continue; + } + + // Impostors are rendered one at a time, jobs encode and write them meanwhile. Rendering waits while + // the jobs are behind, every pending impostor keeps its renderings in memory + GenerateMeshImpostor(mesh, settings["impostor"]); + Loader::MeshLoader::SaveMesh(mesh.Get(), path, true, false, false); + auto data = Loader::ImpostorLoader::ReadImpostor(mesh->impostor.Get(), mesh->impostor.GetResource()->path); + auto& writes = context.impostorWrites; + auto maxPending = std::max(2, 2 * JobSystem::GetWorkerCount(writes.priority)); + if (writes.counter.load() >= maxPending) + JobSystem::Wait(writes); + JobSystem::Execute(writes, [data](JobData&) { Loader::ImpostorLoader::WriteImpostor(data); }); + + // The renderings of an impostor are only released at the end of a frame, which doesn't come during an + // edit: without this many impostors in one edit run out of GPU memory + Graphics::GraphicsDevice::DefaultDevice->WaitForIdle(); + Graphics::GraphicsDevice::DefaultDevice->ForceMemoryCleanup(); + } + affected.push_back({ { "meshes", changed.size() }, { "set", settings } }); + + return affected; + + } + + // The mesh instances an operation is for: all instances of "meshes" or the entities named like "entity" (with all) + static std::vector SelectMeshInstances(Scene::Scene& scene, const json& operation) { + + if (!operation.contains("entity")) + return FindMeshInstances(scene, ToAssetPatterns(operation.at("meshes"))); + + std::vector instances; + for (auto entity : SelectEntities(scene, operation)) + if (entity.HasComponent()) + instances.push_back(entity); + return instances; + + } + + static json EditSoftBodies(EditContext& context, const json& operation) { + + auto& scene = context.scene; + + // Cloth for every instance of the matching meshes ("meshes", "exclude"): the soft body settings come from "set" + // (the fields of the component). Pins are found per connected part of the mesh: "pin": "top" pins the highest + // pinShare of each part's height, e.g. a banner on its beam or each sail on its yard, "topBottom" also the + // lowest (sails tied to the yard below), "none" leaves it free, "set" keeps the pinBounds of "set". Parts smaller + // than fixedSize (rings, hooks) are pinned completely. With "remove" the instances lose their soft bodies + auto remove = operation.value("remove", false); + auto pin = operation.value("pin", std::string("top")); + auto pinShare = operation.value("pinShare", 0.06f); + auto fixedSize = operation.value("fixedSize", 0.3f); + if (pin != "top" && pin != "topBottom" && pin != "none" && pin != "set") + throw std::runtime_error("softBodies: pin has to be top, topBottom, none or set"); + + // Bounds of the connected parts of the first LOD, render vertices at the same position are joined + auto partBounds = [](const Mesh::MeshData& data) { + auto vertexCount = size_t(data.GetVertexCount() - data.lodVertexCount); + std::span vertices(data.vertices.data.data(), vertexCount); + auto welded = Mesh::MeshSimplifier::GeneratePositionRemap(vertices); + + std::vector parents(vertexCount); + std::iota(parents.begin(), parents.end(), 0u); + auto find = [&](uint32_t i) { + while (parents[i] != i) + i = parents[i] = parents[parents[i]]; + return i; + }; + for (const auto& subData : data.subData) { + auto range = subData.GetLod(0); + for (uint32_t i = 0; i + 2 < range.indicesCount; i += 3) { + auto offset = range.indicesOffset + i; + auto root = find(welded[data.indices[offset]]); + parents[find(welded[data.indices[offset + 1]])] = root; + parents[find(welded[data.indices[offset + 2]])] = root; + } + } + + std::unordered_map parts; + for (size_t i = 0; i < vertexCount; i++) { + auto [item, inserted] = parts.try_emplace(find(welded[i]), data.vertices[i], data.vertices[i]); + if (!inserted) + item->second.Grow(data.vertices[i]); + } + return parts; + }; + + SoftBodyComponent defaults; + if (operation.contains("set")) + from_json(operation["set"], defaults); + + size_t count = 0; + for (auto entity : FindMeshInstances(scene, ToAssetPatterns(operation.at("meshes")), ToAssetPatterns(operation.value("exclude", json::array())))) { + if (entity.HasComponent()) + entity.RemoveComponent(); + if (remove) { + count++; + continue; + } + + auto& mesh = entity.GetComponent().mesh; + mesh.WaitForLoad(); + if (!mesh.IsLoaded()) + continue; + + // The cloth would collide with a rigid body of its own mesh + if (entity.HasComponent()) + entity.RemoveComponent(); + + auto settings = defaults.settings; + settings.pinned = pin != "none"; + if (pin != "set") + settings.pinBounds.clear(); + if (settings.pinned && pin != "set") { + const auto margin = vec3(0.01f); + for (const auto& [root, part] : partBounds(mesh->data)) { + auto size = part.max - part.min; + if (glm::max(size.x, glm::max(size.y, size.z)) < fixedSize) { + settings.pinBounds.emplace_back(part.min - margin, part.max + margin); + continue; + } + settings.pinBounds.emplace_back(vec3(part.min.x, part.max.y - pinShare * size.y, part.min.z) - margin, part.max + margin); + if (pin == "topBottom") + settings.pinBounds.emplace_back(part.min - margin, vec3(part.max.x, part.min.y + pinShare * size.y, part.max.z) + margin); + } + } + entity.AddComponent(settings); + count++; + } + + return json::array({ { { "softBodies", count }, { "removed", remove } } }); + + } + + static json EditMeshBodies(EditContext& context, const json& operation) { + + auto& scene = context.scene; + json affected = json::array(); + + // Static mesh shapes for every instance of the matching meshes, e.g. trees of prefabs and scatter groups, + // or with "shape" box, convex or boxes simpler static shapes. With remove the instances lose their bodies + // instead, e.g. grass the player walks through. "motion": "dynamic" makes them simulated bodies (shape box or convex, density, friction, restitution, asleep, buoyancy), + // with "supported": true only those resting on a body, the terrain or the ocean, the others stay as they are + auto replace = operation.value("replace", false); + auto remove = operation.value("remove", false); + auto motion = operation.value("motion", std::string("static")); + if (motion != "static" && motion != "dynamic") + throw std::runtime_error("meshBodies: motion has to be static or dynamic"); + + std::vector matches; + for (auto entity : SelectMeshInstances(scene, operation)) + if (remove ? entity.HasComponent() : replace || !entity.HasComponent()) + matches.push_back(entity); + + // Something with a body or the terrain right below the bottom of an instance: a pot on a table without + // collision would fall through it once touched. Floating instances are carried by the ocean they reach + size_t unsupported = 0; + auto floats = operation.value("buoyancy", 0.0f) > 0.0f && scene.ocean && scene.ocean->enable && scene.ocean->physics; + // Only instances in the ocean float, sunken ones, e.g. the cargo of a wreck on the sea floor, stay down there + auto isInOcean = [&](Scene::Entity entity) { + auto aabb = entity.GetComponent().mesh->data.aabb.Transform(GetTransform(entity).globalMatrix); + return floats && aabb.min.y < scene.ocean->translation.y && aabb.max.y > scene.ocean->translation.y - 2.0f; + }; + auto isSupported = [&](Scene::Entity entity) { + if (isInOcean(entity)) + return true; + auto aabb = entity.GetComponent().mesh->data.aabb.Transform(GetTransform(entity).globalMatrix); + Volume::Ray ray(vec3(aabb.GetCenter().x, aabb.min.y + 0.15f, aabb.GetCenter().z), vec3(0.0f, -1.0f, 0.0f), 0.0f, 0.4f); + auto hit = scene.CastRay(ray, Scene::RigidBodyComponentBit | Scene::TerrainComponentBit, + [&](const Scene::Entity& other) { return other == entity; }); + return hit.valid; + }; + // Only the instances that float in the ocean, e.g. the boats on the water and not those pulled up on a beach + if (operation.value("inOcean", false)) { + if (!floats) + throw std::runtime_error("meshBodies: inOcean needs buoyancy and an ocean with physics"); + std::erase_if(matches, [&](Scene::Entity entity) { return !isInOcean(entity); }); + } + if (motion == "dynamic" && operation.value("supported", false)) { + std::erase_if(matches, [&](Scene::Entity entity) { + auto supported = isSupported(entity); + unsupported += supported ? 0 : 1; + return !supported; + }); + } + + // Components are changed once all matches are known, adding them invalidates the subset + for (auto entity : matches) { + if (entity.HasComponent()) + entity.RemoveComponent(); + if (remove) + continue; + if (motion == "dynamic") + AddMovableBody(entity, operation, isInOcean(entity)); + else if (operation.value("shape", std::string("mesh")) == "mesh") + AddMeshBody(entity, entity.GetComponent().mesh, GetTransform(entity).DecomposeGlobal().scale); + else + entity.AddComponent(Physics::BodyCreationSettings { + .objectLayer = Physics::Layers::Static, .shape = CreateBodyShape(entity, operation) }); + } + affected.push_back({ { remove ? "removed" : "bodies", matches.size() } }); + if (unsupported) + affected.push_back({ { "unsupported", unsupported } }); + + return affected; + + } + + // A zone that reports the hero and simulated bodies entering and leaving it (contact events with isTrigger), e.g. + // a place the hero discovers: a sphere (radius), a box (halfSize) or an upright cylinder (radius, height) + static json EditTrigger(EditContext& context, const json& operation) { + + auto& scene = context.scene; + + auto name = operation.at("name").get(); + CheckNewName(scene, name); + auto parent = GetParent(scene, operation); + auto global = GetPlacement(scene, operation, parent); + + Ref shape; + auto type = operation.value("shape", std::string("sphere")); + if (type == "sphere") { + Physics::SphereShapeSettings settings = { .radius = operation.at("radius").get() }; + shape = Physics::ShapesManager::CreateShape(settings); + } + else if (type == "box") { + auto halfSize = ToVec3(operation.at("halfSize")); + Physics::BoundingBoxShapeSettings settings = { .aabb = Volume::AABB(-halfSize, halfSize) }; + shape = Physics::ShapesManager::CreateShape(settings); + } + else if (type == "cylinder") { + Physics::CylinderShapeSettings settings = { .height = operation.at("height").get(), + .radius = operation.at("radius").get() }; + shape = Physics::ShapesManager::CreateShape(settings); + } + else { + throw std::runtime_error("trigger: shape has to be sphere, box or cylinder"); + } + + auto entity = scene.CreateEntity(); + entity.AddComponent(global, true); + entity.AddComponent(name); + Place(entity, parent, global); + entity.AddComponent(Physics::BodyCreationSettings { + .objectLayer = Physics::Layers::Static, .isTrigger = true, .shape = shape }); + + return json::array({ { { "entity", GetEntityLabel(entity) }, { "shape", type } } }); + + } + + // Hangs the simulated instances of matching meshes on the world or connects them to an entity: a point, hinge, + // cone, distance, slider or fixed constraint at an anchor in the mesh ("top", "bottom" or a position in mesh + // space), to the anchor where the instance is or to a fixed worldPoint + static json EditConstraint(EditContext& context, const json& operation) { + + auto& scene = context.scene; + + static const std::unordered_map types = { + { "fixed", Physics::ConstraintType::Fixed }, { "point", Physics::ConstraintType::Point }, + { "hinge", Physics::ConstraintType::Hinge }, { "slider", Physics::ConstraintType::Slider }, + { "distance", Physics::ConstraintType::Distance }, { "cone", Physics::ConstraintType::Cone } }; + auto type = types.find(operation.value("type", std::string("point"))); + if (type == types.end()) + throw std::runtime_error("constraint: unknown type"); + + Scene::Entity connected; + if (operation.contains("connect")) { + connected = scene.GetEntityByName(operation["connect"].get()); + if (!connected.IsValid() || !connected.HasComponent()) + throw std::runtime_error("constraint: connect needs an entity with a body"); + } + + // Instances that already hang on a constraint keep it, e.g. the boats tied to a bollard among those anchored + std::vector matches; + for (auto entity : SelectMeshInstances(scene, operation)) + if (auto body = entity.TryGetComponent(); body && body->layer == Physics::Layers::Movable && + entity != connected && !entity.HasComponent()) + matches.push_back(entity); + + for (auto entity : matches) { + const auto& aabb = entity.GetComponent().mesh->data.aabb; + auto center = aabb.GetCenter(); + vec3 anchor; + auto spec = operation.value("anchor", json("top")); + if (spec == "top") + anchor = vec3(center.x, aabb.max.y, center.z); + else if (spec == "bottom") + anchor = vec3(center.x, aabb.min.y, center.z); + else + anchor = ToVec3(spec); + + // The body has the position and rotation of the instance, its shape carries the scale + auto& transform = GetTransform(entity); + auto decomposition = transform.DecomposeGlobal(); + Physics::ConstraintCreationSettings settings = { + .type = type->second, + .point = anchor * decomposition.scale, + .otherPoint = vec3(transform.globalMatrix * vec4(anchor, 1.0f)), + .axis = ToVec3(operation.value("axis", json()), vec3(0.0f, 1.0f, 0.0f)), + .enableLimits = operation.contains("limits"), + .limitsMin = operation.contains("limits") ? operation["limits"][0].get() : 0.0f, + .limitsMax = operation.contains("limits") ? operation["limits"][1].get() : 0.0f, + .halfConeAngle = glm::radians(operation.value("halfConeAngle", 30.0f)), + .breakForce = operation.value("breakForce", 0.0f) }; + // The other end at a fixed point of the world, e.g. the bollard a boat is tied to, or at an offset in the + // world from where the anchor is now, e.g. the stone a boat is anchored to on the sea floor + if (operation.contains("worldPoint")) + settings.otherPoint = ToVec3(operation["worldPoint"]); + if (operation.contains("worldOffset")) + settings.otherPoint += ToVec3(operation["worldOffset"]); + if (connected.IsValid()) { + auto other = GetTransform(connected).DecomposeGlobal(); + other.scale = vec3(1.0f); + auto body = other.Compose(); + settings.otherPoint = vec3(glm::inverse(body) * vec4(settings.otherPoint, 1.0f)); + } + entity.AddComponent(settings, connected); + } + + return json::array({ { { "constraints", matches.size() } } }); + + } + + static json EditMaterialCopy(EditContext& context, const json& operation) { + + json affected = json::array(); + + // Copies a material file and changes its properties, e.g. to fix imported foliage materials + auto sourcePath = ToAssetPath(operation.at("material").get()); + auto outputPath = ToAssetPath(operation.at("output").get()); + auto outputFile = GetAssetDirectory() / outputPath; + if (fs::exists(outputFile) && !operation.value("overwrite", false)) + throw std::runtime_error("materialCopy: " + outputPath + " already exists, set \"overwrite\": true"); + + std::ifstream input(GetAssetDirectory() / sourcePath); + if (!input.is_open()) + throw std::runtime_error("materialCopy: couldn't open " + sourcePath); + auto material = json::parse(input); + input.close(); + + // References in packages are relative to the material file, the copy gets its own + Loader::AssetReferences::ResolveReferences(material, Loader::AssetReferences::Type::Material, sourcePath); + for (const auto& [key, value] : operation.value("set", json::object()).items()) { + // Colors are given as [r, g, b] + if (value.is_array() && value.size() == 3) + material[key] = { { "x", value[0] }, { "y", value[1] }, { "z", value[2] } }; + else + material[key] = value; + } + for (const auto& key : operation.value("remove", std::vector())) + material.erase(key); + material["name"] = fs::path(outputPath).stem().string(); + Loader::AssetReferences::MakeReferences(material, Loader::AssetReferences::Type::Material, outputPath); + + if (!Loader::AssetLoader::WriteJson(outputFile.string(), material, Loader::JsonFormat::Compact)) + throw std::runtime_error("materialCopy: couldn't write " + outputPath); + affected.push_back(outputPath); + + return affected; + + } + + static json EditCompressTextures(EditContext& context, const json& operation) { + + auto& state = context.state; + json affected = json::array(); + + // Converts the textures of all materials and material graphs below the directories into compressed KTX2 files + // next to the sources and points the files to them, a .backup of each changed file is kept + std::map conversions; + std::vector> materials; + for (const auto& directory : operation.at("directories")) { + auto root = GetAssetDirectory() / ToAssetPath(directory.get()); + if (!fs::is_directory(root)) + throw std::runtime_error("compressTextures: " + directory.get() + " isn't a directory"); + for (const auto& file : fs::recursive_directory_iterator(root, fs::directory_options::follow_directory_symlink)) { + auto extension = file.path().extension(); + if (!file.is_regular_file() || (extension != ".aematerial" && extension != ".aematgraph")) + continue; + std::ifstream input(file.path()); + auto material = json::parse(input); + auto materialDirectory = fs::relative(file.path().parent_path(), GetAssetDirectory()); + bool changed = false; + auto convert = [&](json& value) { + if (!value.is_string() || Loader::KtxLoader::IsKtxFile(value.get())) + return; + // References inside packages are relative to the file + auto reference = value.get(); + auto source = reference.starts_with("./") || reference.starts_with("../") ? + (materialDirectory / reference).lexically_normal().generic_string() : reference; + auto target = fs::path(source).replace_extension(".ktx2").generic_string(); + conversions[source] = target; + value = fs::path(reference).replace_extension(".ktx2").generic_string(); + changed = true; + }; + for (auto& [key, value] : material.items()) { + if (key.ends_with("MapPath")) + convert(value); + } + if (material.contains("graphTextures")) { + for (auto& [_, value] : material["graphTextures"].items()) + convert(value); + } + if (material.contains("nodes")) { + for (auto& node : material["nodes"]) { + if (node.contains("texturePath")) + convert(node["texturePath"]); + } + } + if (changed) + materials.emplace_back(file.path(), material); + } + } + + // The files are rewritten and loaded again, which would drop the changes of earlier operations + for (const auto& [path, _] : materials) { + auto assetPath = fs::relative(path, GetAssetDirectory()).generic_string(); + if (state.changedMaterials.contains(assetPath) || state.graphEdits.changed.contains(assetPath)) + throw std::runtime_error("compressTextures: " + assetPath + " was changed by an earlier operation, " + "compress the textures in an edit of their own first"); + } + + std::vector> pending; + for (const auto& conversion : conversions) + if (!fs::exists(GetAssetDirectory() / conversion.second)) + pending.push_back(conversion); + + // A dry run only reports what would be converted + if (state.dryRun) { + affected.push_back({ { "materials", materials.size() }, { "textures", conversions.size() }, + { "converted", 0 }, { "pending", pending.size() } }); + return affected; + } + + // The encoder runs single threaded per image + std::vector failed(pending.size()); + JobGroup group{ "Compress textures", JobPriority::High }; + JobSystem::ParallelFor(group, int32_t(pending.size()), int32_t(pending.size()), [&](JobData&, int32_t idx) { + const auto& [source, target] = pending[idx]; + if (!fs::exists(GetAssetDirectory() / source)) { + failed[idx] = source + " doesn't exist"; + return; + } + auto image = Loader::ImageLoader::LoadImage(source); + auto fileData = Loader::KtxLoader::EncodeImage({ image }, true); + if (fileData.empty()) { + failed[idx] = "couldn't encode " + source; + return; + } + auto fileStream = Loader::AssetLoader::WriteFile(target, std::ios::out | std::ios::binary); + if (!fileStream.is_open()) { + failed[idx] = "couldn't write " + target; + return; + } + fileStream.write(fileData.data(), std::streamsize(fileData.size())); + }); + JobSystem::Wait(group); + + json errors = json::array(); + for (const auto& error : failed) + if (!error.empty()) + errors.push_back(error); + if (!errors.empty()) + throw std::runtime_error("compressTextures: " + errors.dump()); + + uintmax_t sourceBytes = 0, targetBytes = 0; + for (const auto& [source, target] : conversions) { + sourceBytes += fs::file_size(GetAssetDirectory() / source); + targetBytes += fs::file_size(GetAssetDirectory() / target); + } + + std::set written; + for (auto& [path, material] : materials) { + auto backup = path; + backup += ".backup"; + if (!fs::exists(backup)) + fs::copy_file(path, backup); + if (!Loader::AssetLoader::WriteJson(path.string(), material, Loader::JsonFormat::Compact)) + throw std::runtime_error("compressTextures: couldn't write " + path.string()); + written.insert(fs::relative(path, GetAssetDirectory()).generic_string()); + } + + // Loaded materials and graphs take the new textures, otherwise later saves write the old ones back + UpdatePipelinesOfMaterials(ReloadMaterials(written)); + + affected.push_back({ { "materials", materials.size() }, { "textures", conversions.size() }, + { "converted", pending.size() }, { "sourceMB", double(sourceBytes) / 1048576.0 }, + { "ktx2MB", double(targetBytes) / 1048576.0 } }); + + return affected; + + } + + static json EditBakeMaterial(EditContext& context, const json& operation) { + + auto path = ToAssetPath(operation.at("material").get()); + auto material = ResourceManager::GetOrLoadResourceWithLoader(path, ResourceOrigin::User, Loader::MaterialLoader::LoadMaterial, false); + if (!material.IsLoaded()) + throw std::runtime_error("bakeMaterial: couldn't load " + path); + + auto meshPath = operation.at("mesh").get(); + auto mesh = LoadMeshForScene(meshPath); + + auto& settings = material->graphBake; + settings.mode = operation.value("mode", std::string("textures")) == "average" ? MaterialGraph::BakeMode::Average : MaterialGraph::BakeMode::Textures; + settings.resolution = operation.value("resolution", 1024); + settings.time = operation.value("time", 0.0f); + settings.meshPath = ToAssetPath(meshPath); + + // Pipelines of the graph don't change, the compiled state decides whether a bake is up to date + if (material->HasGraph() && !material->graph->GetCompiled()) + material->graph->Compile(); + + auto result = MaterialGraph::Baker::Bake(material, mesh); + if (!result.success) + throw std::runtime_error("bakeMaterial: " + result.error); + + Loader::MaterialLoader::SaveMaterial(material.Get(), material.GetResource()->path); + + return { { "material", path }, { "maps", result.maps }, { "baseColor", { material->baseColor.x, material->baseColor.y, material->baseColor.z } }, + { "roughness", material->roughness }, { "metalness", material->metalness }, { "emissiveIntensity", material->emissiveIntensity } }; + + } + + static json EditMaterialGraphFile(EditContext& context, const json& operation) { + + // The file is written once the checks passed, graphs the engine already loaded follow the edit right away + auto& edits = context.state.graphEdits; + auto result = EditMaterialGraph(operation, edits); + auto path = result["graph"].get(); + auto graph = ResourceManager::GetResource(path); + if (graph.IsLoaded()) { + *graph.Get() = *CreateGraph(edits.documents.at(path)); + + std::set materials; + for (const auto& material : ResourceManager::GetResources()) + if (material.IsLoaded() && material->graph.GetResource() == graph.GetResource()) + materials.insert(material.Get().get()); + UpdatePipelinesOfMaterials(materials); + } + + return json::array({ result }); + + } + + // Graphs changed by the job come from their documents, the files still have the old state + static ResourceHandle GetGraphOfEdit(EditContext& context, const std::string& path) { + + auto graph = ResourceManager::GetResource(path); + const auto& edits = context.state.graphEdits; + if (edits.changed.contains(path)) + return graph.IsLoaded() ? graph : ResourceManager::AddResource(path, ResourceOrigin::User, + CreateGraph(edits.documents.at(path))); + + // A graph created by a dry run stays loaded without a file + if (!fs::exists(GetAssetDirectory() / path)) + throw std::runtime_error("no graph " + path); + if (graph.IsLoaded()) + return graph; + + graph = ResourceManager::GetOrLoadResourceWithLoader(path, ResourceOrigin::User, Loader::MaterialGraphLoader::LoadGraph); + if (!graph.IsLoaded()) + throw std::runtime_error("couldn't load the graph " + path); + return graph; + + } + + static json EditAssignMaterialGraph(EditContext& context, const json& operation) { + + CheckAssignMaterialGraph(operation); + + ResourceHandle assignedGraph; + if (operation.contains("graph") && !operation["graph"].is_null()) + assignedGraph = GetGraphOfEdit(context, ToAssetPath(operation["graph"].get())); + + json affected = json::array(); + std::set graphChanged; + for (const auto& path : FindMaterialFiles(operation.at("materials"))) { + auto material = ResourceManager::GetOrLoadResourceWithLoader(path, ResourceOrigin::User, Loader::MaterialLoader::LoadMaterial, false); + if (!material.IsLoaded()) + throw std::runtime_error("couldn't load " + path); + + auto graph = operation.contains("graph") ? assignedGraph : material->graph; + auto compiled = graph.IsLoaded() ? graph->GetCompiled() : nullptr; + if (compiled) { + auto graphPath = graph.GetResource()->path; + if (!compiled->errors.empty()) + throw std::runtime_error("the graph " + graphPath + " doesn't compile"); + CheckGraphValues(operation, *compiled, graphPath); + } + else if (operation.contains("values") || operation.contains("textures")) { + throw std::runtime_error(path + " has no graph, set \"graph\""); + } + + // Validated, from here on the material changes. The file is written by SaveMaterials once the checks passed + context.state.changedMaterials.insert(path); + if (graph.GetResource() != material->graph.GetResource()) { + material->graph = graph; + graphChanged.insert(material.Get().get()); + } + + // Values of parameters the graph doesn't have, or values of textures and the other way round, don't apply + auto reset = operation.value("reset", json()); + std::erase_if(material->graphValues, [&](const auto& entry) { + auto parameter = compiled ? FindParameter(*compiled, entry.first) : nullptr; + return reset == true || !parameter || parameter->type == MaterialGraph::ValueType::Texture; }); + std::erase_if(material->graphTextures, [&](const auto& entry) { + auto parameter = compiled ? FindParameter(*compiled, entry.first) : nullptr; + return reset == true || !parameter || parameter->type != MaterialGraph::ValueType::Texture; }); + material->graphParameterVersion++; + if (reset.is_array()) { + for (const auto& name : reset) + material->ResetGraphParameter(name.get()); + } + + for (const auto& [name, value] : operation.value("values", json::object()).items()) { + auto parameter = FindParameter(*compiled, name); + material->SetGraphParameter(name, ToParameterValue(*parameter, value, material->GetGraphValue(*parameter))); + } + for (const auto& [name, value] : operation.value("textures", json::object()).items()) { + if (value.is_null()) { + material->graphTextures.erase(name); + material->graphParameterVersion++; + continue; + } + material->SetGraphTexture(name, ResourceManager::GetOrLoadResourceWithLoaderAsync( + ToAssetPath(value.get()), Streaming::TextureStreaming::LoadTexture, false, Texture::Wrapping::Repeat, + Texture::Filtering::Anisotropic)); + } + + json values = json::object(); + for (const auto& [name, value] : material->graphValues) + values[name] = ToParameterJson(*FindParameter(*compiled, name), value); + json textures = json::object(); + for (const auto& [name, texture] : material->graphTextures) + textures[name] = texture.IsValid() ? texture.GetResource()->path : std::string(); + affected.push_back({ { "material", path }, { "graph", graph.IsLoaded() ? graph.GetResource()->path : std::string() }, + { "values", values }, { "textures", textures } }); + } + UpdatePipelinesOfMaterials(graphChanged); + + return affected; + + } + + static json EditMeshMaterials(EditContext& context, const json& operation) { + + json affected = json::array(); + + // Replaces materials of mesh files, e.g. of copies made by meshCopy + auto replace = operation.value("replace", json::object()); + auto replacementForAll = operation.value("all", std::string()); + for (const auto& meshPath : operation.at("meshes")) { + auto mesh = LoadMeshForScene(meshPath.get()); + int32_t replaced = 0; + for (auto& material : mesh->data.materials) { + auto path = material.GetResource()->path; + if (replacementForAll.empty() && !replace.contains(path)) + continue; + auto newPath = ToAssetPath(replacementForAll.empty() ? replace[path].get() : replacementForAll); + auto newMaterial = ResourceManager::GetOrLoadResourceWithLoader(newPath, + ResourceOrigin::User, Loader::MaterialLoader::LoadMaterial, false); + if (!newMaterial.IsLoaded()) + throw std::runtime_error("meshMaterials: couldn't load " + newPath); + for (auto& subData : mesh->data.subData) + if (subData.material.GetResource() == material.GetResource()) + subData.material = newMaterial; + material = newMaterial; + replaced++; + } + mesh->UpdatePipelines(); + Loader::MeshLoader::SaveMesh(mesh.Get(), mesh.GetResource()->path, true); + affected.push_back({ { "mesh", mesh.GetResource()->path }, { "replaced", replaced } }); + } + + return affected; + + } + + static json EditMeshCopy(EditContext& context, const json& operation) { + + auto& scene = context.scene; + json affected = json::array(); + + // Shared mesh files stay untouched: the copy is changed and assigned to the selected hierarchies + auto sourcePath = ToAssetPath(operation.at("mesh").get()); + auto outputPath = ToAssetPath(operation.at("output").get()); + auto outputFile = GetAssetDirectory() / outputPath; + if (fs::exists(outputFile) && !operation.value("overwrite", false)) + throw std::runtime_error("meshCopy: " + outputPath + " already exists, set \"overwrite\": true"); + fs::create_directories(outputFile.parent_path()); + + // Model files (OBJ, glTF, ...) are imported, the import is saved as the copy + ResourceHandle mesh; + if (Common::Path::GetFileType(sourcePath) != "aemesh") { + mesh = LoadMeshForScene(sourcePath); + } + else { + // An earlier copy can already be loaded (e.g. by the scene or a meshSettings operation), the + // changes below have to start from the source again, otherwise normals are inverted twice + auto cached = ResourceManager::GetResource(outputPath); + fs::copy_file(GetAssetDirectory() / sourcePath, outputFile, fs::copy_options::overwrite_existing); + mesh = LoadMeshForScene(outputPath); + if (cached.IsLoaded()) { + json fresh = *Loader::MeshLoader::LoadMesh(outputPath, true); + from_json(fresh, *mesh.Get()); + mesh->UpdatePipelines(); + } + } + if (operation.value("invertNormals", false)) { + for (auto& normal : mesh->data.normals.Get()) + normal = vec4(-vec3(normal), normal.w); + mesh->UpdateData(); + } + // Mesh settings, e.g. to configure foliage like the other meshes of its asset pack + if (operation.contains("set")) { + ApplyMeshSettings(*mesh.Get(), operation["set"]); + TakeGeneratedLods({ mesh }); + } + Loader::MeshLoader::SaveMesh(mesh.Get(), outputPath, true); + + int32_t assigned = 0; + if (operation.contains("assign")) { + for (auto member : CollectHierarchies(scene, operation["assign"].get>())) { + Scene::Entity entity = { member, &scene.entityManager }; + auto meshComponent = entity.TryGetComponent(); + if (meshComponent && meshComponent->mesh.IsValid() && + meshComponent->mesh.GetResource()->path == sourcePath) { + meshComponent->ChangeResource(mesh); + assigned++; + } + } + } + affected.push_back({ { "mesh", outputPath }, { "assigned", assigned } }); + + return affected; + + } + + static json EditMakePrefab(EditContext& context, const json& operation) { + + return json::array({ MakePrefabFromScene(operation, context.prefabSources) }); + + } + + static json EditPrefab(EditContext& context, const json& operation) { + + auto& scene = context.scene; + json affected = json::array(); + + auto name = operation.at("name").get(); + CheckNewName(scene, name); + + auto parent = GetParent(scene, operation); + auto global = GetPlacement(scene, operation, parent); + + auto prefabPath = ToAssetPath(operation.at("prefab").get()); + auto entity = Serializer::DeserializePrefab(context.sceneRef, prefabPath); + SetName(entity, name); + + if (!entity.HasComponent()) + entity.AddComponent(mat4(1.0f), true); + Place(entity, parent, global); + + EntitySet members; + CollectHierarchy(entity, members); + affected.push_back({ { "entity", GetEntityLabel(entity) }, { "prefab", prefabPath }, { "entities", members.size() } }); + + return affected; + + } + + static json EditReplaceMesh(EditContext& context, const json& operation) { + + auto& scene = context.scene; + json affected = json::array(); + + // Every instance of the matching meshes gets one of the meshes in "with", chosen by the instance so the + // choices mix evenly. The bottom of the new mesh stays where the old one was, pivots differ between packs + std::vector> replacements; + for (const auto& path : operation.at("with")) + replacements.push_back(LoadMeshForScene(path.get())); + if (replacements.empty()) + throw std::runtime_error("replaceMesh: no meshes in 'with'"); + auto matchHeight = operation.value("matchHeight", true); + auto seed = operation.value("seed", 0u); + auto inCircle = [&](const char* key, Scene::Entity entity) { + const auto& circle = operation.at(key); + auto center = circle.at("center").get>(); + auto position = vec3(GetTransform(entity).globalMatrix[3]); + return glm::distance(vec2(position.x, position.z), vec2(center[0], center[1])) < circle.at("radius").get(); + }; + + std::vector found; + for (auto entity : FindMeshInstances(scene, ToAssetPatterns(operation.at("meshes")), + ToAssetPatterns(operation.value("exclude", json::array())))) { + if ((operation.contains("within") && !inCircle("within", entity)) || (operation.contains("beyond") && inCircle("beyond", entity))) + continue; + found.push_back(entity); + } + + for (auto entity : found) { + auto& meshComponent = entity.GetComponent(); + auto id = static_cast(static_cast(entity)); + const auto& replacement = replacements[(id * 2654435761u + seed) % replacements.size()]; + auto& transform = GetTransform(entity); + const auto& oldAabb = meshComponent.mesh->data.aabb; + const auto& newAabb = replacement->data.aabb; + auto factor = 1.0f; + if (matchHeight && oldAabb.max.y > oldAabb.min.y && newAabb.max.y > newAabb.min.y) + factor = (oldAabb.max.y - oldAabb.min.y) / (newAabb.max.y - newAabb.min.y); + auto adjust = glm::translate(vec3(0.0f, oldAabb.min.y - newAabb.min.y * factor, 0.0f)) * glm::scale(vec3(factor)); + transform.Set(transform.matrix * adjust); + meshComponent.ChangeResource(replacement); + if (entity.HasComponent()) + entity.RemoveComponent(); + } + affected.push_back({ { "replaced", found.size() }, { "with", operation.at("with") } }); + + return affected; + + } + + static json EditReplaceWithPrefab(EditContext& context, const json& operation) { + + auto& scene = context.scene; + json affected = json::array(); + + // Every instance of the matching meshes becomes an instance of the prefab with the same transform and + // parent. The bottom of the prefab stays where the bottom of the mesh was + auto replaced = FindMeshInstances(scene, ToAssetPatterns(operation.at("meshes")), + ToAssetPatterns(operation.value("exclude", json::array()))); + auto nearby = FindMeshInstances(scene, ToAssetPatterns(operation.value("removeNear", json::array()))); + + auto prefabPath = ToAssetPath(operation.at("prefab").get()); + auto name = operation.value("name", std::string("Prefab")); + // The lowest point of the meshes of a prefab instance in its own space + std::function bottom = [&](Scene::Entity entity, const mat4& parentMatrix) { + auto matrix = parentMatrix; + if (auto transform = entity.TryGetComponent()) + matrix = parentMatrix * transform->matrix; + auto lowest = std::numeric_limits::max(); + // Prefab meshes load asynchronously + if (auto meshComponent = entity.TryGetComponent(); meshComponent && meshComponent->mesh.IsValid()) { + meshComponent->mesh.WaitForLoad(); + if (meshComponent->mesh.IsLoaded()) + lowest = meshComponent->mesh->data.aabb.Transform(matrix).min.y; + } + if (auto hierarchy = entity.TryGetComponent()) + for (auto child : hierarchy->GetChildren()) + lowest = std::min(lowest, bottom(child, matrix)); + return lowest; + }; + EntitySet removed; + for (size_t index = 0; index < replaced.size(); index++) { + auto original = replaced[index]; + auto global = HierarchyMatrix(scene, original); + auto parent = scene.GetParentEntity(original); + if (!parent.IsValid()) + parent = scene.GetRootEntity(); + + auto entity = Serializer::DeserializePrefab(context.sceneRef, prefabPath); + SetName(entity, name + " " + std::to_string(index + 1)); + if (!entity.HasComponent()) + entity.AddComponent(mat4(1.0f), true); + auto prefabBottom = bottom(entity, glm::inverse(GetTransform(entity).matrix)); + auto meshBottom = original.GetComponent().mesh->data.aabb.min.y; + if (prefabBottom == std::numeric_limits::max()) + throw std::runtime_error("replaceWithPrefab: " + prefabPath + " has no loaded mesh to place its bottom"); + global = global * glm::translate(vec3(0.0f, meshBottom - prefabBottom, 0.0f)); + GetTransform(entity).Set(glm::inverse(HierarchyMatrix(scene, parent)) * global); + entity.SetParent(parent); + + auto position = vec3(global[3]); + for (auto other : nearby) { + if (!removed.contains(other) && glm::distance(vec3(HierarchyMatrix(scene, other)[3]), position) < 1.5f) + removed.insert(other); + } + removed.insert(original); + } + for (auto entity : removed) + scene.DestroyEntity(Scene::Entity(entity, &scene.entityManager)); + affected.push_back({ { "replaced", replaced.size() }, { "removed", removed.size() - replaced.size() }, { "prefab", prefabPath } }); + + return affected; + + } + + // Lua with the table Bridge (LuaEdit.h), from "code" or a "file" relative to data/ + static json EditLua(EditContext& context, const json& operation) { + + auto name = operation.value("file", std::string("lua")); + auto code = operation.value("code", std::string()); + if (operation.contains("file")) { + std::ifstream stream(GetAssetDirectory() / name, std::ios::binary); + if (!stream.is_open()) + throw std::runtime_error("lua: can't read " + name); + code.assign(std::istreambuf_iterator(stream), std::istreambuf_iterator()); + } + if (code.empty()) + throw std::runtime_error("lua: needs \"code\" or \"file\""); + + LuaEdit edit(context.sceneRef, context.state); + return edit.Run(code, name); + + } + + static const std::map editOperations = { + { "snapToGround", EditSnapToGround }, + { "setVisible", EditSetVisible }, + { "material", EditMaterial }, + { "delete", EditDelete }, + { "add", EditAdd }, + { "terrainCopy", EditTerrainCopy }, + { "terrainCreate", EditTerrainCreate }, + { "terrain", EditTerrain }, + { "shoreLine", EditShoreLine }, + { "scatter", EditScatter }, + { "clearArea", EditClearArea }, + { "meshSettings", EditMeshSettings }, + { "meshBodies", EditMeshBodies }, + { "softBodies", EditSoftBodies }, + { "trigger", EditTrigger }, + { "constraint", EditConstraint }, + { "materialCopy", EditMaterialCopy }, + { "compressTextures", EditCompressTextures }, + { "bakeMaterial", EditBakeMaterial }, + { "materialGraph", EditMaterialGraphFile }, + { "assignMaterialGraph", EditAssignMaterialGraph }, + { "meshMaterials", EditMeshMaterials }, + { "meshCopy", EditMeshCopy }, + { "makePrefab", EditMakePrefab }, + { "prefab", EditPrefab }, + { "replaceMesh", EditReplaceMesh }, + { "replaceWithPrefab", EditReplaceWithPrefab }, + { "lua", EditLua } + }; + + json CapList(const json& list, size_t count) { + + if (!list.is_array() || list.size() <= count) + return list; + return { { "count", list.size() }, { "first", json(list.begin(), list.begin() + count) } }; + + } + + json ApplyEditOperations(const Ref& sceneRef, const json& operations, EditState& state) { + + EditContext context = { sceneRef, *sceneRef, state }; + importTextureFormat = state.textureFormat; + + json log = json::array(); + for (const auto& operation : operations) { + auto type = operation.at("op").get(); + auto handler = editOperations.find(type); + if (handler == editOperations.end()) { + std::string known; + for (const auto& [name, _] : editOperations) + known += (known.empty() ? "" : ", ") + name; + throw std::runtime_error("Unknown edit operation '" + type + "' (" + known + ")"); + } + + // Other operations may read the impostor files + if (type != "meshSettings") + JobSystem::Wait(context.impostorWrites); + if (type != "add") { + context.names.clear(); + context.namesCollected = false; + context.addedWithoutNames = false; + context.parents.clear(); + } + + auto start = std::chrono::steady_clock::now(); + json affected; + try { + affected = handler->second(context, operation); + // The next operation reads global matrices, bounds and ray casts of the changed entities + context.scene.UpdateTransforms(); + } + catch (const std::exception& e) { + // Most operations name themselves in their errors already + std::string message = e.what(); + if (message.starts_with(type + ": ")) + message = message.substr(type.size() + 2); + throw std::runtime_error("Edit operation " + std::to_string(log.size() + 1) + " (" + type + "): " + message); + } + auto seconds = SecondsSince(start); + // Long edits don't update the window, the log shows that they progress + if (seconds > 2.0f) { + auto label = operation.value("group", operation.value("name", std::string())); + std::printf("[bridge] edit operation %zu (%s%s%s): %.1f s\n", log.size() + 1, type.c_str(), label.empty() ? "" : " ", + label.c_str(), seconds); + std::fflush(stdout); + } + log.push_back({ { "operation", CapList(operation) }, { "affected", CapList(affected) }, { "seconds", seconds } }); + } + JobSystem::Wait(context.impostorWrites); + + return log; + + } + + void SetWorldPosition(Scene::Entity entity, vec3 position) { + + auto& transform = GetTransform(entity); + TranslateWorld(entity, position - vec3(transform.globalMatrix[3])); + + } + + json SaveMaterials(const std::set& paths) { + + json saved = json::array(); + for (const auto& path : paths) { + auto backup = GetAssetDirectory() / path; + backup += ".backup"; + if (!fs::exists(backup)) + fs::copy_file(GetAssetDirectory() / path, backup); + + // The loader converts the resource paths into references from the material file + auto material = ResourceManager::GetResource(path); + Loader::MaterialLoader::SaveMaterial(material.Get(), path); + saved.push_back({ { "material", path }, { "backup", backup.string() } }); + } + + return saved; + + } + + void RevertUnsavedEdits(EditState& state) { + + auto paths = state.changedMaterials; + paths.insert(state.graphEdits.changed.begin(), state.graphEdits.changed.end()); + UpdatePipelinesOfMaterials(ReloadMaterials(paths)); + state.graphEdits.changed.clear(); + state.changedMaterials.clear(); + + } + +} diff --git a/src/bridge/SceneEditor.h b/src/bridge/SceneEditor.h new file mode 100644 index 000000000..1ac7b4f7a --- /dev/null +++ b/src/bridge/SceneEditor.h @@ -0,0 +1,64 @@ +#pragma once + +#include "Job.h" +#include "MaterialGraphTools.h" +#include "SceneTools.h" + +#include "loader/ModelImporter.h" + +#include + +namespace Atlas::Bridge { + + // Applies edit operations to a loaded scene. Operations selecting existing entities use name patterns or #ids + // and by default require exactly one match to avoid accidental mass edits ("all": true allows more) + // Throws std::runtime_error on invalid operations, the scene must not be saved in that case + struct EditState { + + // Patched materials are only changed in memory, they are saved once the checks passed + std::set changedMaterials; + // Material graphs of the operations, saved together with the materials + MaterialGraphEdits graphEdits; + // Terrain of the scene as it was loaded, it is only edited after a terrainCopy (or with "overwriteTerrain") + std::string loadedTerrain; + bool terrainChanged = false; + // Operations which only make sense for inspection (detachTerrain) require a dry run + bool dryRun = false; + // Format of the textures of imported models + Loader::ImportTextureFormat textureFormat = Loader::ImportTextureFormat::Original; + + }; + + json ApplyEditOperations(const Ref& scene, const json& operations, EditState& state); + + // The global matrix from the local ones up the hierarchy, for entities changed earlier in the same operation + mat4 HierarchyMatrix(Scene::Scene& scene, Scene::Entity entity); + + // Model files (glTF, FBX, ...) are imported next to the source into meshes/ and materials/ first, + // scenes can only reference .aemesh files + ResourceHandle LoadMeshForScene(const std::string& path); + + // An animation file or the name of an animation of the model file + ResourceHandle LoadAnimationForScene(const std::string& animation, const std::string& modelPath); + + // Writes the materials to their files, a .backup of the original file is kept + json SaveMaterials(const std::set& paths); + + // Loaded materials and graphs an edit changed without saving them (dry runs, failed checks) go back to their files, + // the server keeps them loaded for the next jobs + void RevertUnsavedEdits(EditState& state); + + // Moves an entity to a world position, keeping its rotation (the parent transform is taken into account) + void SetWorldPosition(Scene::Entity entity, vec3 position); + + // Static body with the mesh as its collision shape + void AddMeshBody(Scene::Entity entity, const ResourceHandle& mesh, vec3 scale); + + // Point or spot light at the entity origin, the light of the add and scatter operations + void AddLight(Scene::Entity entity, const json& spec); + + // Lists of more than count entries are reduced to their length and the first entries, large edits of a pipeline + // otherwise write reports of hundreds of megabytes + json CapList(const json& list, size_t count = 200); + +} diff --git a/src/bridge/SceneFile.cpp b/src/bridge/SceneFile.cpp new file mode 100644 index 000000000..4b905dfa4 --- /dev/null +++ b/src/bridge/SceneFile.cpp @@ -0,0 +1,503 @@ +#include "SceneFile.h" +#include "Processes.h" + +#include "Log.h" + +#include +#include +#include + +namespace Atlas::Bridge { + + static std::vector ReadBytes(const fs::path& path) { + + std::ifstream stream(path, std::ios::binary); + if (!stream.is_open()) + throw std::runtime_error("Couldn't open " + path.string()); + return std::vector(std::istreambuf_iterator(stream), {}); + + } + + static bool IsJsonFile(const fs::path& path) { + + return path.extension() == ".json"; + + } + + // Collects the entities while the parser walks the file, without building the document + class EntityReader : public nlohmann::json_sax { + + public: + EntityReader(std::vector& entities, bool rootIsEntity, bool namesOnly) + : entities(entities), rootIsEntity(rootIsEntity), namesOnly(namesOnly) {} + + bool null() override { return true; } + bool boolean(bool) override { return true; } + bool number_integer(number_integer_t value) override { return Integer(int64_t(value)); } + bool number_unsigned(number_unsigned_t value) override { return Integer(int64_t(value)); } + bool number_float(number_float_t value, const string_t&) override { return Number(float(value)); } + + bool binary(binary_t& value) override { + + // Binary scenes store matrices as raw floats + const auto& frame = frames.back(); + if (frame.role == Role::Transform && frame.key == "matrix" && value.size() == sizeof(mat4)) { + auto& values = matrices[frame.entity]; + values.resize(16); + std::memcpy(values.data(), value.data(), sizeof(mat4)); + } + // Scenes with binary columns store the index lists and the columns as raw values + else if (frame.role == Role::EntityTable && frame.key == "parent") { + parents = Decode(value); + } + else if (frame.role == Role::Section && frame.key == "entity") { + for (auto entity : Decode(value)) + AddSectionEntity(entity); + } + else if (frame.role == Role::Columns) { + // The columns come before the entities of their section + columns[frame.key] = std::move(static_cast&>(value)); + } + return true; + + } + + bool string(string_t& value) override { + + auto& frame = frames.back(); + if (frame.role == Role::Name && frame.key == "name") + entities[frame.entity].name = value; + else if (frame.role == Role::Mesh && frame.key == "resourcePath") + entities[frame.entity].mesh = value; + else if (frame.role == Role::Resources) + resources.push_back(value); + return true; + + } + + bool start_object(std::size_t) override { + + if (frames.empty()) { + frames.push_back({ rootIsEntity ? Role::Entity : Role::Root, {}, rootIsEntity ? AddEntity(-1) : -1 }); + return true; + } + + const auto parent = frames.back(); + auto role = Role::Ignored; + auto entity = parent.entity; + if (parent.role == Role::Entities) { + role = Role::Entity; + entity = AddEntity(parent.entity); + } + else if (parent.role == Role::Entity) { + if (parent.key == "name") + role = Role::Name; + else if (parent.key == "transform" && !namesOnly) + role = Role::Transform; + else if (parent.key == "mesh" && !namesOnly) + role = Role::Mesh; + } + else if (parent.role == Role::Matrix) { + // Older files store a matrix as one object per column + role = Role::Matrix; + } + else if (parent.role == Role::Root && parent.key == "entities") { + role = Role::EntityTable; + } + else if (parent.role == Role::Root && parent.key == "components") { + role = Role::Components; + } + else if (parent.role == Role::Components) { + role = Role::Section; + section = parent.key; + sectionEntities.clear(); + sectionValue = 0; + columns.clear(); + } + else if (parent.role == Role::Section && parent.key == "columns") { + role = Role::Columns; + } + else if (parent.role == Role::SectionValues) { + // The entities of a section come before its values + entity = int32_t(sectionEntities.at(sectionValue++)); + if (section == "name") + role = Role::Name; + else if (section == "transform" && !namesOnly) + role = Role::Transform; + else if (section == "mesh" && !namesOnly) + role = Role::Mesh; + } + frames.push_back({ role, {}, entity }); + return true; + + } + + bool key(string_t& value) override { + + auto& frame = frames.back(); + frame.key = value; + if (frame.role == Role::Entity && !namesOnly && value != "id" && value != "entities" && value != "root" && value != "name" && + value != "transform") + entities[frame.entity].components.push_back(value); + return true; + + } + + bool end_object() override { + + if (frames.back().role == Role::Section && !columns.empty()) + ApplyColumns(); + frames.pop_back(); + return true; + + } + + bool start_array(std::size_t) override { + + if (frames.empty()) { + frames.push_back({ Role::Ignored, {}, -1 }); + return true; + } + + const auto& parent = frames.back(); + auto role = Role::Ignored; + if ((parent.role == Role::Root || parent.role == Role::Entity) && parent.key == "entities") + role = Role::Entities; + else if ((parent.role == Role::Transform && parent.key == "matrix") || parent.role == Role::Matrix) + role = Role::Matrix; + else if (parent.role == Role::Root && parent.key == "resources") + role = Role::Resources; + else if (parent.role == Role::EntityTable && parent.key == "parent") + role = Role::Parents; + else if (parent.role == Role::Section && parent.key == "entity") + role = Role::SectionEntities; + else if (parent.role == Role::Section && parent.key == "values") + role = Role::SectionValues; + frames.push_back({ role, {}, parent.entity }); + return true; + + } + + bool end_array() override { + + frames.pop_back(); + return true; + + } + + bool parse_error(std::size_t position, const std::string&, const nlohmann::detail::exception& exception) override { + + throw std::runtime_error("Invalid file at byte " + std::to_string(position) + ": " + exception.what()); + + } + + std::vector> matrices; + + // Binary scenes reference meshes by their index in the resource table + std::vector resources; + std::unordered_map meshIndices; + + // Scenes store the parents in their entity table, the components in a section per component type + std::vector parents; + + private: + enum class Role { + Root, + Entities, + Entity, + Name, + Transform, + Matrix, + Mesh, + Resources, + EntityTable, + Parents, + Components, + Section, + SectionEntities, + SectionValues, + Columns, + Ignored + }; + + struct Frame { + + Role role; + std::string key; + int32_t entity; + + }; + + int32_t AddEntity(int32_t parent) { + + entities.push_back({ .parent = parent }); + if (!namesOnly) + matrices.emplace_back(); + return int32_t(entities.size()) - 1; + + } + + bool Number(float value) { + + const auto& frame = frames.back(); + if (frame.role == Role::Matrix) + matrices[frame.entity].push_back(value); + return true; + + } + + bool Integer(int64_t value) { + + const auto& frame = frames.back(); + if (frame.role == Role::Mesh && frame.key == "resourcePath") + meshIndices[frame.entity] = size_t(value); + else if (frame.role == Role::Parents) + parents.push_back(int32_t(value)); + else if (frame.role == Role::SectionEntities) + AddSectionEntity(size_t(value)); + return Number(float(value)); + + } + + template + static std::vector Decode(const std::vector& data) { + + std::vector values(data.size() / sizeof(T)); + std::memcpy(values.data(), data.data(), values.size() * sizeof(T)); + return values; + + } + + void ApplyColumns() { + + // Files that don't match their entity list are reported, they would otherwise be read out of bounds + auto count = sectionEntities.size(); + auto hasCount = [&](const char* name, size_t elementSize, size_t expected) { + if (columns[name].size() == expected * elementSize) + return true; + Log::Error("Scene column " + section + "." + name + " doesn't match its entities"); + return false; + }; + + if (section == "name" && hasCount("offset", sizeof(uint32_t), count + 1)) { + auto offsets = Decode(columns["offset"]); + const auto& text = columns["text"]; + if (offsets.back() > text.size() || !std::is_sorted(offsets.begin(), offsets.end())) { + Log::Error("Scene name column has invalid offsets"); + columns.clear(); + return; + } + for (size_t i = 0; i < sectionEntities.size(); i++) + entities[sectionEntities[i]].name.assign(reinterpret_cast(text.data()) + offsets[i], + offsets[i + 1] - offsets[i]); + } + else if (section == "transform" && !namesOnly && hasCount("matrix", sizeof(mat4), count)) { + auto values = Decode(columns["matrix"]); + for (size_t i = 0; i < sectionEntities.size(); i++) + matrices[sectionEntities[i]].assign(values.begin() + i * 16, values.begin() + (i + 1) * 16); + } + else if (section == "mesh" && !namesOnly && hasCount("resource", sizeof(uint32_t), count)) { + auto indices = Decode(columns["resource"]); + for (size_t i = 0; i < sectionEntities.size(); i++) + if (indices[i] != UINT32_MAX) + meshIndices[int32_t(sectionEntities[i])] = indices[i]; + } + columns.clear(); + + } + + void AddSectionEntity(size_t entity) { + + // Sections can come before the entity table + if (entity >= entities.size()) { + entities.resize(entity + 1); + if (!namesOnly) + matrices.resize(entity + 1); + } + sectionEntities.push_back(entity); + if (!namesOnly && section != "name" && section != "transform" && section != "hierarchy") + entities[entity].components.push_back(section); + + } + + std::vector& entities; + std::vector frames; + bool rootIsEntity; + bool namesOnly; + + std::string section; + std::vector sectionEntities; + size_t sectionValue = 0; + std::unordered_map> columns; + + }; + + static std::vector ReadEntities(const fs::path& path, bool namesOnly) { + + auto bytes = ReadBytes(path); + std::vector entities; + EntityReader reader(entities, path.extension() == ".aeprefab", namesOnly); + if (IsJsonFile(path)) + json::sax_parse(bytes.begin(), bytes.end(), &reader, json::input_format_t::json, true, true); + else + json::sax_parse(bytes.begin(), bytes.end(), &reader, json::input_format_t::msgpack); + + for (const auto& [entity, index] : reader.meshIndices) + entities[entity].mesh = reader.resources.at(index); + + // Parents come before their children in the entity table + if (entities.size() < reader.parents.size()) { + entities.resize(reader.parents.size()); + reader.matrices.resize(namesOnly ? 0 : entities.size()); + } + for (size_t i = 0; i < reader.parents.size(); i++) + entities[i].parent = reader.parents[i]; + + if (namesOnly) + return entities; + + for (size_t i = 0; i < entities.size(); i++) { + auto& entity = entities[i]; + const auto& values = reader.matrices[i]; + if (values.size() == 16) + entity.local = glm::make_mat4(values.data()); + entity.global = entity.parent >= 0 ? entities[entity.parent].global * entity.local : entity.local; + } + return entities; + + } + + std::vector ReadFileEntities(const fs::path& path) { + + return ReadEntities(path, false); + + } + + std::vector ReadEntityNames(const fs::path& path) { + + std::error_code error; + auto size = fs::file_size(path, error); + // The count is a 128 bit integer on macOS, which std::to_string doesn't take + auto time = static_cast(fs::last_write_time(path, error).time_since_epoch().count()); + auto key = std::hash()(fs::absolute(path).generic_string() + "|" + std::to_string(size) + "|" + std::to_string(time)); + auto cache = GetExecutablePath().parent_path() / ".cache" / "bridge-names" / (path.stem().string() + "-" + std::to_string(key) + ".txt"); + + std::vector names; + if (std::ifstream stream(cache); stream.is_open()) { + for (std::string line; std::getline(stream, line);) + names.push_back(line); + return names; + } + + for (auto& entity : ReadEntities(path, true)) + names.push_back(std::move(entity.name)); + + fs::create_directories(cache.parent_path(), error); + // Older caches of the same file are of no use anymore + for (const auto& entry : fs::directory_iterator(cache.parent_path(), error)) + if (entry.path().filename().string().starts_with(path.stem().string() + "-")) + fs::remove(entry.path(), error); + std::string content; + for (const auto& name : names) + content += name + "\n"; + WriteFileAtomic(cache, content); + return names; + + } + + static vec3 ToVector(const json& j) { + + if (j.is_array() && j.size() >= 3) + return vec3(j[0].get(), j[1].get(), j[2].get()); + if (j.is_object()) + return vec3(j.value("x", 0.0f), j.value("y", 0.0f), j.value("z", 0.0f)); + return vec3(0.0f); + + } + + MeshFileInfo ReadMeshFile(const fs::path& path) { + + auto bytes = ReadBytes(path); + json j; + try { + j = json::from_msgpack(bytes); + } + catch (const json::exception&) { + j = json::parse(bytes.begin(), bytes.end()); + } + + MeshFileInfo info; + info.name = j.value("name", path.stem().string()); + info.impostor = j.value("impostor", std::string()); + + const auto& data = j.value("data", json::object()); + if (data.contains("aabb")) + info.bounds = Volume::AABB(ToVector(data["aabb"]["min"]), ToVector(data["aabb"]["max"])); + info.vertexCount = data.value("vertexCount", int64_t(0)); + info.indexCount = data.value("indexCount", int64_t(0)); + for (const auto& material : data.value("materials", json::array())) + info.materials.push_back(material.is_string() ? material.get() : material.dump()); + for (const auto& sub : data.value("subData", json::array())) { + info.subData.emplace_back(sub.value("name", std::string()), sub.value("materialIdx", 0)); + const auto& lods = sub.value("lods", json::array()); + info.lodTriangles.resize(std::max(info.lodTriangles.size(), lods.size())); + for (size_t i = 0; i < lods.size(); i++) + info.lodTriangles[i] += lods[i][1].get() / 3; + } + + for (const auto& [key, value] : j.items()) + if (key != "data" && key != "impostor" && key != "name" && !value.is_object() && !value.is_array()) + info.settings[key] = value; + + return info; + + } + + static size_t EditDistance(const std::string& a, const std::string& b) { + + std::vector row(b.size() + 1); + for (size_t j = 0; j <= b.size(); j++) + row[j] = j; + + for (size_t i = 1; i <= a.size(); i++) { + size_t diagonal = row[0]; + row[0] = i; + for (size_t j = 1; j <= b.size(); j++) { + auto above = row[j]; + auto same = std::tolower(static_cast(a[i - 1])) == std::tolower(static_cast(b[j - 1])); + row[j] = std::min({ row[j] + 1, row[j - 1] + 1, diagonal + (same ? 0 : 1) }); + diagonal = above; + } + } + return row[b.size()]; + + } + + std::vector FindClosestNames(const std::vector& names, const std::string& text, size_t count) { + + // Wildcards don't count as differences + std::string pattern; + std::copy_if(text.begin(), text.end(), std::back_inserter(pattern), [](char c) { return c != '*' && c != '?'; }); + + std::vector> scored; + std::vector unique = names; + std::sort(unique.begin(), unique.end()); + unique.erase(std::unique(unique.begin(), unique.end()), unique.end()); + for (const auto& name : unique) { + // A name that contains the text is as close as it gets + auto lowerName = name, lowerPattern = pattern; + std::transform(lowerName.begin(), lowerName.end(), lowerName.begin(), [](unsigned char c) { return char(std::tolower(c)); }); + std::transform(lowerPattern.begin(), lowerPattern.end(), lowerPattern.begin(), [](unsigned char c) { return char(std::tolower(c)); }); + auto distance = lowerName.find(lowerPattern) != std::string::npos ? 0 : EditDistance(lowerName, lowerPattern); + scored.emplace_back(distance, name); + } + std::partial_sort(scored.begin(), scored.begin() + std::min(count, scored.size()), scored.end()); + + std::vector closest; + for (size_t i = 0; i < std::min(count, scored.size()); i++) + closest.push_back(scored[i].second); + return closest; + + } + +} diff --git a/src/bridge/SceneFile.h b/src/bridge/SceneFile.h new file mode 100644 index 000000000..79278afeb --- /dev/null +++ b/src/bridge/SceneFile.h @@ -0,0 +1,51 @@ +#pragma once + +#include "Common.h" + +#include "volume/AABB.h" + +namespace Atlas::Bridge { + + // An entity of a scene or prefab file read without loading it + struct FileEntity { + + std::string name; + int32_t parent = -1; + mat4 local = mat4(1.0f); + mat4 global = mat4(1.0f); + std::string mesh; + // The components by their key in the file, e.g. mesh, rigidBody, script + std::vector components; + + }; + + // Reads the entity tree of a scene (.aescene, .json) or prefab (.aeprefab) with a SAX parser, which takes a few + // seconds for the world scene of a million entities. Parents come before their children + std::vector ReadFileEntities(const fs::path& path); + + // The entity names of a scene or prefab file, cached next to the executable by path, size and write time + std::vector ReadEntityNames(const fs::path& path); + + struct MeshFileInfo { + + std::string name; + Volume::AABB bounds; + int64_t vertexCount = 0; + int64_t indexCount = 0; + std::vector materials; + // Submeshes with their material index + std::vector> subData; + // Triangles of the levels of detail from 1 on + std::vector lodTriangles; + std::string impostor; + json settings = json::object(); + + }; + + // Reads an .aemesh file without loading it + MeshFileInfo ReadMeshFile(const fs::path& path); + + // Names that differ least from the text, ignoring case, for "did you mean" hints + std::vector FindClosestNames(const std::vector& names, const std::string& text, size_t count = 3); + +} diff --git a/src/bridge/SceneTools.cpp b/src/bridge/SceneTools.cpp new file mode 100644 index 000000000..5c7f925e5 --- /dev/null +++ b/src/bridge/SceneTools.cpp @@ -0,0 +1,1253 @@ +#include "SceneTools.h" +#include "Image.h" +#include "TerrainTools.h" + +#include "scene/SceneSerializer.h" +#include "scene/components/ComponentSerializer.h" +#include "scene/components/LuaScriptComponent.h" +#include "lighting/LightingSerializer.h" +#include "postprocessing/PostProcessingSerializer.h" +#include "mesh/MeshSerializer.h" +#include "resource/ResourceManager.h" +#include "common/MathHelper.h" +#include "graphics/ShaderCompiler.h" +#include "jobsystem/JobSystem.h" +#include "loader/AssetLoader.h" +#include "loader/MaterialGraphLoader.h" +#include "loader/MaterialLoader.h" +#include "loader/ShaderLoader.h" +#include "materialgraph/Compiler.h" +#include "common/MatrixDecomposition.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Atlas::Bridge { + + using namespace Scene::Components; + + static json BoundsToJson(const Volume::AABB& aabb) { + + return json{ { "min", FromVec3(aabb.min) }, { "max", FromVec3(aabb.max) }, { "size", FromVec3(aabb.GetSize()) } }; + + } + + static EntitySet GetIgnoredEntities(Scene::Scene& scene, const json& query) { + + return CollectHierarchies(scene, query.value("ignore", std::vector())); + + } + + // The bits of Scene::GetComponentMask, the hierarchy isn't a serialized component + static constexpr uint32_t hierarchyBit = 1u << 31; + + static uint32_t GetComponentBit(const char* key) { + + const auto& types = Scene::GetComponentTypes(); + for (size_t i = 0; i < types.size(); i++) + if (std::string_view(types[i].key) == key) + return 1u << uint32_t(i); + AE_ASSERT(false && "Unknown component key, the scene serializer renamed it"); + return 0u; + + } + + static const uint32_t meshBit = GetComponentBit("mesh"), scriptBit = GetComponentBit("script"); + + static uint32_t GetEntityComponentMask(Scene::Entity entity) { + + return Scene::GetComponentMask(entity) | (entity.HasComponent() ? hierarchyBit : 0u); + + } + + static std::vector GetComponentNames(uint32_t mask) { + + std::vector names; + const auto& types = Scene::GetComponentTypes(); + for (size_t i = 0; i < types.size(); i++) + if (mask & (1u << uint32_t(i))) + names.push_back(types[i].key); + if (mask & hierarchyBit) + names.push_back("hierarchy"); + return names; + + } + + static std::vector GetComponentNames(Scene::Entity entity) { + + return GetComponentNames(GetEntityComponentMask(entity)); + + } + + static json ComponentDetails(Scene::Entity entity) { + + json j; + if (auto comp = entity.TryGetComponent()) + j["transform"] = *comp; + if (auto comp = entity.TryGetComponent()) + j["mesh"] = *comp; + if (auto comp = entity.TryGetComponent()) + j["camera"] = *comp; + if (auto comp = entity.TryGetComponent()) + j["light"] = *comp; + if (auto comp = entity.TryGetComponent()) + j["rigidBody"] = *comp; + if (auto comp = entity.TryGetComponent()) + j["player"] = *comp; + if (auto comp = entity.TryGetComponent()) + j["luaScript"] = *comp; + if (auto comp = entity.TryGetComponent()) + j["audio"] = *comp; + if (auto comp = entity.TryGetComponent()) + j["audioVolume"] = *comp; + if (auto comp = entity.TryGetComponent()) + j["fogVolume"] = *comp; + if (auto comp = entity.TryGetComponent()) + j["text"] = *comp; + if (auto comp = entity.TryGetComponent()) + j["spline"] = *comp; + return j; + + } + + std::string GetHitMaterial(const RaycastHit& hit) { + + if (hit.triangle < 0 || !hit.entity.IsValid()) + return ""; + + auto meshComponent = hit.entity.TryGetComponent(); + if (!meshComponent || !meshComponent->mesh.IsLoaded()) + return ""; + + auto subData = meshComponent->mesh->data.GetSubDataOfTriangle(int32_t(hit.triangle)); + if (!subData) + return ""; + + return subData->material.IsValid() ? subData->material.GetResource()->path : subData->name; + + } + + std::string GetHitLabel(const RaycastHit& hit) { + + return hit.entity.IsValid() ? GetEntityLabel(hit.entity) : hit.kind; + + } + + std::string GetEntityName(Scene::Entity entity) { + + if (!entity.IsValid()) + return ""; + + auto nameComponent = entity.TryGetComponent(); + return nameComponent ? nameComponent->name : ""; + + } + + std::string GetEntityLabel(Scene::Entity entity) { + + auto name = GetEntityName(entity); + return (name.empty() ? "" : name) + " (#" + std::to_string(entity.GetID()) + ")"; + + } + + std::vector FindEntities(Scene::Scene& scene, const std::vector& patterns) { + + std::vector entities; + if (patterns.empty()) + return entities; + + auto nameSubset = scene.GetSubset(); + for (auto entity : nameSubset) { + const auto& nameComponent = nameSubset.Get(entity); + if (MatchAnyPattern(patterns, nameComponent.name)) + entities.push_back({ entity, &scene.entityManager }); + } + + // Allow to address entities by id as well, e.g. "#123" + for (const auto& pattern : patterns) { + if (pattern.size() > 1 && pattern[0] == '#') { + auto id = ECS::Entity(std::stoull(pattern.substr(1))); + Scene::Entity entity = { id, &scene.entityManager }; + if (entity.IsValid()) + entities.push_back(entity); + } + } + + return entities; + + } + + std::vector FindEntities(Scene::Scene& scene, const std::string& pattern) { + + return FindEntities(scene, std::vector { pattern }); + + } + + std::vector FindTopmostEntities(Scene::Scene& scene, const std::vector& patterns) { + + auto entities = FindEntities(scene, patterns); + EntitySet contained(entities.begin(), entities.end()); + + std::vector result; + for (auto entity : entities) { + bool ancestorContained = false; + auto parent = scene.GetParentEntity(entity); + while (parent.IsValid() && !ancestorContained) { + ancestorContained = contained.contains(parent); + parent = scene.GetParentEntity(parent); + } + + if (!ancestorContained) + result.push_back(entity); + } + + return result; + + } + + std::vector FindTopmostEntities(Scene::Scene& scene, const std::string& pattern) { + + return FindTopmostEntities(scene, std::vector { pattern }); + + } + + std::vector FindMeshInstances(Scene::Scene& scene, const std::vector& patterns, + const std::vector& excluded) { + + std::vector entities; + auto meshSubset = scene.GetSubset(); + for (auto entity : meshSubset) { + const auto& mesh = meshSubset.Get(entity).mesh; + if (!mesh.IsLoaded()) + continue; + const auto& path = mesh.GetResource()->path; + if (MatchAnyPattern(patterns, path) && !MatchAnyPattern(excluded, path)) + entities.push_back({ entity, &scene.entityManager }); + } + + return entities; + + } + + void CollectHierarchy(Scene::Entity entity, EntitySet& set) { + + if (!entity.IsValid() || set.contains(entity)) + return; + + set.insert(entity); + + auto hierarchyComponent = entity.TryGetComponent(); + if (!hierarchyComponent) + return; + + for (auto child : hierarchyComponent->GetChildren()) + CollectHierarchy(child, set); + + } + + EntitySet CollectHierarchies(Scene::Scene& scene, const std::vector& patterns) { + + EntitySet set; + for (auto entity : FindEntities(scene, patterns)) + CollectHierarchy(entity, set); + + return set; + + } + + bool IsInHierarchies(Scene::Scene& scene, Scene::Entity entity, const std::vector& patterns) { + + if (patterns.empty()) + return false; + + for (; entity.IsValid(); entity = scene.GetParentEntity(entity)) { + auto nameComponent = entity.TryGetComponent(); + if (nameComponent && MatchAnyPattern(patterns, nameComponent->name)) + return true; + + for (const auto& pattern : patterns) + if (pattern.size() > 1 && pattern[0] == '#' && ECS::Entity(std::stoull(pattern.substr(1))) == ECS::Entity(entity)) + return true; + } + + return false; + + } + + Volume::AABB GetEntityBounds(Scene::Entity entity, bool* hasMesh) { + + auto bounds = entity.GetScene()->GetHierarchyBounds(entity); + if (hasMesh) + *hasMesh = bounds.has_value(); + if (bounds) + return *bounds; + + auto position = GetEntityPosition(entity); + return Volume::AABB(position - vec3(0.05f), position + vec3(0.05f)); + + } + + Volume::AABB GetBounds(const std::vector& entities) { + + Volume::AABB bounds(vec3(std::numeric_limits::max()), vec3(-std::numeric_limits::max())); + for (auto entity : entities) + bounds.Grow(GetEntityBounds(entity)); + + return bounds; + + } + + Volume::AABB GetSceneBounds(Scene::Scene& scene) { + + Volume::AABB bounds(vec3(std::numeric_limits::max()), vec3(-std::numeric_limits::max())); + bool found = false; + + auto meshSubset = scene.GetSubset(); + for (auto entity : meshSubset) { + const auto& meshComponent = meshSubset.Get(entity); + if (!meshComponent.mesh.IsLoaded()) + continue; + + bounds.Grow(meshComponent.aabb); + found = true; + } + + if (scene.terrain.IsLoaded()) { + auto& terrain = scene.terrain; + bounds.Grow(terrain->translation); + bounds.Grow(terrain->translation + vec3(terrain->sideLength, terrain->heightScale, terrain->sideLength)); + found = true; + } + + if (!found) + bounds = Volume::AABB(vec3(-10.0f), vec3(10.0f)); + + return bounds; + + } + + vec3 GetEntityPosition(Scene::Entity entity) { + + auto transformComponent = entity.TryGetComponent(); + if (!transformComponent) + return vec3(0.0f); + + return vec3(transformComponent->globalMatrix[3]); + + } + + float GetEntityYaw(Scene::Entity entity) { + + auto transformComponent = entity.TryGetComponent(); + if (!transformComponent) + return 0.0f; + + auto forward = vec3(transformComponent->globalMatrix * vec4(0.0f, 0.0f, 1.0f, 0.0f)); + return std::atan2(forward.x, forward.z); + + } + + RaycastHit Raycast(Scene::Scene& scene, vec3 origin, vec3 direction, float maxDistance, const EntitySet& ignored, + Scene::SceneQueryComponents components) { + + return Raycast(scene, origin, direction, maxDistance, [&](const Scene::Entity& entity) { + return ignored.contains(entity); + }, components); + + } + + RaycastHit Raycast(Scene::Scene& scene, vec3 origin, vec3 direction, float maxDistance, + const std::function& isIgnored, Scene::SceneQueryComponents components) { + + RaycastHit hit; + direction = Helper::Math::NormalizeOrZero(direction); + if (direction == vec3(0.0f)) + return hit; + + // Skip invisible meshes and players for visual and ground queries + auto ray = Volume::Ray(origin, direction, 0.0f, maxDistance); + auto result = scene.CastRay(ray, components, [&](const Scene::Entity& entity) { + + if (isIgnored(entity) || entity.HasComponent()) + return true; + auto meshComponent = entity.TryGetComponent(); + return meshComponent && !meshComponent->visible; + + }); + + if (!result.valid) + return hit; + + hit.valid = true; + hit.distance = result.hitDistance; + hit.position = ray.Get(result.hitDistance); + hit.normal = result.normal; + hit.entity = result.data; + hit.triangle = result.triangleIndex; + if (result.triangleIndex >= 0) + hit.kind = "mesh"; + else if (!result.data.IsValid()) + hit.kind = "terrain"; + else + hit.kind = result.data.HasComponent() ? "text" : "body"; + + return hit; + + } + + RaycastHit GroundBelow(Scene::Scene& scene, vec3 position, const EntitySet& ignored) { + + return Raycast(scene, position, vec3(0.0f, -1.0f, 0.0f), 4096.0f, ignored, CollisionComponents); + + } + + EntityGround GroundBelowEntity(Scene::Scene& scene, Scene::Entity entity, float searchAbove, const EntitySet& alsoIgnored) { + + EntityGround result; + result.bounds = GetEntityBounds(entity, &result.hasMesh); + + auto ignored = alsoIgnored; + CollectHierarchy(entity, ignored); + auto center = result.bounds.GetCenter(); + result.ground = GroundBelow(scene, vec3(center.x, result.bounds.max.y + searchAbove, center.z), ignored); + + return result; + + } + + FootprintGap MeasureFootprint(Scene::Scene& scene, Scene::Entity entity, const Volume::AABB& bounds, int32_t grid, float baseHeight, + const EntitySet& alsoIgnored) { + + EntitySet hierarchy; + CollectHierarchy(entity, hierarchy); + auto ignored = alsoIgnored; + ignored.insert(hierarchy.begin(), hierarchy.end()); + auto outsideHierarchy = [&](const Scene::Entity& hit) { return !hierarchy.contains(hit); }; + + FootprintGap result; + result.maxGap = -std::numeric_limits::infinity(); + auto inset = bounds.GetSize() * 0.05f; + auto min = bounds.min + inset, max = bounds.max - inset; + grid = std::max(grid, 2); + for (int32_t a = 0; a < grid; a++) { + for (int32_t b = 0; b < grid; b++) { + auto x = glm::mix(min.x, max.x, float(a) / float(grid - 1)), z = glm::mix(min.z, max.z, float(b) / float(grid - 1)); + + // The underside of the entity from below, then the ground with the entity left out + auto underside = Raycast(scene, vec3(x, bounds.min.y - 1.0f, z), vec3(0.0f, 1.0f, 0.0f), bounds.GetSize().y + 2.0f, + outsideHierarchy, VisualComponents); + if (!underside.valid || underside.position.y > bounds.min.y + baseHeight) + continue; + + auto ground = GroundBelow(scene, vec3(x, bounds.max.y + 0.5f, z), ignored); + if (!ground.valid) + continue; + + result.samples++; + auto gap = underside.position.y - ground.position.y; + if (gap > result.maxGap) { + result.maxGap = gap; + result.worst = vec3(x, underside.position.y, z); + } + } + } + return result; + + } + + json InspectScene(Scene::Scene& scene, const std::vector& filter, + const std::vector& detail, const EntitySet& excluded) { + + json j; + j["name"] = scene.name; + j["entityCount"] = scene.GetEntityCount() - excluded.size(); + j["bounds"] = BoundsToJson(GetSceneBounds(scene)); + j["hasMainCamera"] = scene.HasMainCamera(); + j["hasTerrain"] = scene.terrain.IsValid(); + j["hasOcean"] = scene.ocean != nullptr; + j["settings"] = ExportSettings(scene); + + json entities = json::array(); + for (auto entity : scene) { + if (excluded.contains(entity)) + continue; + + auto name = GetEntityName(entity); + if (!filter.empty() && !MatchAnyPattern(filter, name)) + continue; + + json e; + e["id"] = entity.GetID(); + e["name"] = name; + e["components"] = GetComponentNames(entity); + + auto parent = scene.GetParentEntity(entity); + if (parent.IsValid()) + e["parent"] = GetEntityLabel(parent); + + if (auto hierarchy = entity.TryGetComponent()) + e["childCount"] = hierarchy->GetChildren().size(); + + if (auto transform = entity.TryGetComponent()) { + auto local = transform->Decompose(); + e["position"] = FromVec3(vec3(transform->globalMatrix[3])); + e["localPosition"] = FromVec3(local.translation); + e["localRotationDegrees"] = FromVec3(glm::degrees(local.rotation)); + e["localScale"] = FromVec3(local.scale); + e["worldYawDegrees"] = Round(glm::degrees(GetEntityYaw(entity)), 2); + e["static"] = transform->IsStatic(); + } + + bool hasMesh = false; + auto bounds = GetEntityBounds(entity, &hasMesh); + if (hasMesh) + e["bounds"] = BoundsToJson(bounds); + + if (auto mesh = entity.TryGetComponent()) { + e["mesh"] = mesh->mesh.IsValid() ? mesh->mesh.GetResource()->path : ""; + e["visible"] = mesh->visible; + } + if (auto camera = entity.TryGetComponent()) + e["camera"] = { { "isMain", camera->isMain }, { "fov", camera->fieldOfView }, + { "location", FromVec3(camera->GetLocation()) } }; + if (auto light = entity.TryGetComponent()) + e["light"] = { { "type", int32_t(light->type) }, { "isMain", light->isMain } }; + if (auto script = entity.TryGetComponent()) + e["script"] = script->script.IsValid() ? script->script.GetResource()->path : ""; + + if (!detail.empty() && MatchAnyPattern(detail, name)) + e["detail"] = ComponentDetails(entity); + + entities.push_back(e); + } + j["entities"] = entities; + + return j; + + } + + SceneState CaptureSceneState(Scene::Scene& scene, const EntitySet& excluded) { + + SceneState state; + state.reserve(scene.GetEntityCount()); + for (auto entity : scene) { + if (excluded.contains(entity)) + continue; + + auto& e = state[entity.GetID()]; + e.name = GetEntityName(entity); + auto parent = scene.GetParentEntity(entity); + e.parent = parent.IsValid() ? parent.GetID() : ECS::EntityConfig::InvalidEntity; + e.components = GetEntityComponentMask(entity); + if (auto transform = entity.TryGetComponent()) { + e.hasTransform = true; + e.local = transform->matrix; + e.global = transform->globalMatrix; + } + if (auto mesh = entity.TryGetComponent()) { + e.mesh = mesh->mesh.IsValid() ? mesh->mesh.GetResource()->path : ""; + e.visible = mesh->visible; + } + if (auto script = entity.TryGetComponent()) + e.script = script->script.IsValid() ? script->script.GetResource()->path : ""; + } + return state; + + } + + json DiffSceneStates(const SceneState& before, const SceneState& after) { + + // The inspection rounds to 4 decimals, smaller differences don't count as changes + auto same = [](const mat4& a, const mat4& b) { + for (int32_t c = 0; c < 4; c++) + for (int32_t r = 0; r < 4; r++) + if (std::abs(a[c][r] - b[c][r]) > 1e-4f) + return false; + return true; + }; + auto parentLabel = [](const SceneState& state, uint64_t parent) -> json { + if (parent == ECS::EntityConfig::InvalidEntity) + return json(); + auto it = state.find(parent); + auto name = it != state.end() ? it->second.name : std::string(); + return (name.empty() ? "" : name) + " (#" + std::to_string(parent) + ")"; + }; + auto decompose = [](const EntityState& e) -> std::array { + if (!e.hasTransform) + return { json(), json(), json() }; + Common::MatrixDecomposition local(e.local); + return { FromVec3(local.translation), FromVec3(glm::degrees(local.rotation)), FromVec3(local.scale) }; + }; + auto meshField = [](const EntityState& e, json value) { return e.components & meshBit ? value : json(); }; + + // Sorted by id like the inspections, so the lists don't depend on the hashing + std::vector ids; + ids.reserve(before.size()); + for (const auto& [id, _] : before) + ids.push_back(id); + std::sort(ids.begin(), ids.end()); + + json changed = json::array(), added = json::array(), removed = json::array(); + for (auto id : ids) { + const auto& b = before.at(id); + auto it = after.find(id); + if (it == after.end()) { + removed.push_back({ { "id", id }, { "name", b.name } }); + continue; + } + const auto& a = it->second; + + json changes = json::object(); + auto change = [&](const char* field, const json& beforeValue, const json& afterValue) { + if (beforeValue != afterValue) + changes[field] = { { "before", beforeValue }, { "after", afterValue } }; + }; + change("name", b.name, a.name); + if (b.parent != a.parent) + change("parent", parentLabel(before, b.parent), parentLabel(after, a.parent)); + if (b.components != a.components) + change("components", GetComponentNames(b.components), GetComponentNames(a.components)); + if (b.hasTransform != a.hasTransform || !same(b.global, a.global)) + change("position", b.hasTransform ? FromVec3(vec3(b.global[3])) : json(), a.hasTransform ? FromVec3(vec3(a.global[3])) : json()); + if (b.hasTransform != a.hasTransform || !same(b.local, a.local)) { + auto beforeLocal = decompose(b), afterLocal = decompose(a); + change("localPosition", beforeLocal[0], afterLocal[0]); + change("localRotationDegrees", beforeLocal[1], afterLocal[1]); + change("localScale", beforeLocal[2], afterLocal[2]); + } + change("mesh", meshField(b, b.mesh), meshField(a, a.mesh)); + change("visible", meshField(b, b.visible), meshField(a, a.visible)); + change("script", b.components & scriptBit ? json(b.script) : json(), a.components & scriptBit ? json(a.script) : json()); + + if (!changes.empty()) + changed.push_back({ { "id", id }, { "name", a.name }, { "changes", changes } }); + } + + ids.clear(); + for (const auto& [id, _] : after) + if (!before.contains(id)) + ids.push_back(id); + std::sort(ids.begin(), ids.end()); + for (auto id : ids) { + const auto& a = after.at(id); + added.push_back({ { "id", id }, { "name", a.name }, { "position", a.hasTransform ? FromVec3(vec3(a.global[3])) : json() } }); + } + + json diff; + diff["changed"] = changed; + diff["added"] = added; + diff["removed"] = removed; + diff["summary"] = std::to_string(changed.size()) + " changed, " + std::to_string(added.size()) + " added, " + + std::to_string(removed.size()) + " removed"; + return diff; + + } + + json ExportSettings(Scene::Scene& scene) { + + json j; + Scene::SceneSettingsToJson(j, &scene); + + // Restoring the settings removes the features a patch added + for (auto key : { "fog", "irradianceVolume", "reflection", "rtgi", "sss", "ssgi", "ocean", "navigation" }) + if (!j.contains(key)) + j[key] = nullptr; + + // Variants restore these settings, so the sun has to be part of them + if (scene.HasMainLight()) { + const auto& light = scene.GetMainLight(); + j["sun"] = { { "direction", FromVec3(light.properties.directional.direction) }, + { "color", FromVec3(light.color) }, { "intensity", light.intensity } }; + if (light.shadow) + j["sun"]["shadow"] = { { "cascades", light.shadow->viewCount - (light.shadow->longRange ? 1 : 0) }, + { "longRange", light.shadow->longRange }, { "longRangeDistance", light.shadow->longRangeDistance } }; + } + return j; + + } + + void ApplySettings(Scene::Scene& scene, const json& settings, std::set& patchedMaterials) { + + json features = json::object(); + + for (auto& [key, patch] : settings.items()) { + if (key == "materials") { + ApplyMaterialPatches(patch, patchedMaterials); + } + else if (key == "sun") { + if (!scene.HasMainLight()) + throw std::runtime_error("The scene has no main directional light for the sun settings"); + + auto& light = scene.GetMainLight(); + if (patch.contains("direction")) + light.properties.directional.direction = glm::normalize(ToVec3(patch["direction"])); + // Light direction points from the sun towards the scene + if (patch.contains("elevation") || patch.contains("azimuth")) + light.properties.directional.direction = + -GetDirection(patch.value("azimuth", 0.0f), patch.value("elevation", 45.0f)); + if (patch.contains("color")) + light.color = ToVec3(patch["color"]); + if (patch.contains("intensity")) + light.intensity = patch["intensity"].get(); + if (patch.contains("shadow")) { + if (!light.shadow) + throw std::runtime_error("The main light has no shadow for the sun shadow settings"); + + // The shadow is created anew for its cascades, the long range view is one more after the near ones + auto previous = light.shadow; + const auto& shadow = patch["shadow"]; + auto longRange = shadow.value("longRange", previous->longRange); + auto longRangeDistance = shadow.value("longRangeDistance", previous->longRangeDistance); + auto cascades = shadow.value("cascades", previous->viewCount - (previous->longRange ? 1 : 0)); + light.AddDirectionalShadow(previous->distance, previous->bias, previous->resolution, previous->edgeSoftness, + cascades + (longRange ? 1 : 0), previous->splitCorrection, longRange, longRangeDistance); + light.shadow->allowTerrain = previous->allowTerrain; + light.shadow->allowDynamicEntities = previous->allowDynamicEntities; + light.shadow->cascadeBlendDistance = previous->cascadeBlendDistance; + } + } + else { + // A default constructed ocean has no valid simulation to patch, so it starts with the editor defaults + if (key == "ocean" && !scene.ocean && !patch.is_null()) + scene.ocean = CreateRef(9, 4096.0f); + + features[key] = patch; + } + } + + Scene::PatchSceneSettings(features, &scene); + + json applied; + Scene::SceneSettingsToJson(applied, &scene); + for (auto& [key, patch] : features.items()) { + // A null patch removes a feature, which then isn't exported anymore + if (!applied.contains(key) && !patch.is_null()) + throw std::runtime_error("Unknown settings key '" + key + "'. Known keys: the scene settings " + "(sky, postProcessing, wind, fog, ...), materials and sun"); + } + + } + + void PatchMaterial(Material& material, const json& patch) { + + // Round trip through the engine serializer, so the keys are the ones of the material files + json j = material; + j.merge_patch(patch); + from_json(j, material); + + // Added or removed maps change the shader variants + UpdatePipelinesOfMaterials({ &material }); + + } + + void UpdatePipelinesOfMaterials(const std::set& changed) { + + if (changed.empty()) + return; + + for (auto& mesh : ResourceManager::GetResources()) { + if (!mesh.IsLoaded()) + continue; + + const auto& materials = mesh->data.materials; + if (std::any_of(materials.begin(), materials.end(), [&](const auto& handle) { return changed.contains(handle.Get().get()); })) + mesh->UpdatePipelines(); + } + + } + + int32_t ApplyMaterialPatches(const json& patches, std::set& patchedPaths) { + + int32_t count = 0; + for (auto& material : ResourceManager::GetResources()) { + if (!material.IsLoaded()) + continue; + + const auto& path = material.GetResource()->path; + for (auto& [pattern, patch] : patches.items()) { + if (!Helper::String::MatchWildcard(pattern, path)) + continue; + + PatchMaterial(*material.Get(), patch); + patchedPaths.insert(path); + count++; + } + } + + if (count == 0) + throw std::runtime_error("No loaded material matches the material patches " + patches.dump()); + + return count; + + } + + std::set ReloadMaterials(const std::set& paths) { + + std::set reloaded; + for (const auto& path : paths) { + // Graphs created in memory have no file to go back to + if (!fs::exists(GetAssetDirectory() / path)) + continue; + + if (fs::path(path).extension() == ".aematgraph") { + auto graph = ResourceManager::GetResource(path); + if (!graph.IsLoaded()) + continue; + + *graph.Get() = *Loader::MaterialGraphLoader::LoadGraph(path); + for (const auto& material : ResourceManager::GetResources()) + if (material.IsLoaded() && material->graph.GetResource() == graph.GetResource()) + reloaded.insert(material.Get().get()); + continue; + } + + auto material = ResourceManager::GetResource(path); + if (!material.IsLoaded()) + continue; + + // Materials can't be copied, the state of the file goes through the serializer + json j = *Loader::MaterialLoader::LoadMaterial(path, false); + from_json(j, *material.Get()); + reloaded.insert(material.Get().get()); + } + + return reloaded; + + } + + struct QueryContext { + + Scene::Scene& scene; + const fs::path& outputDirectory; + + }; + + // Compiles shaders of material graphs for all the meshes they can be used with. Without a graph directory it + // only checks each node of the library, in each stage and with each input type + static json QueryMaterialGraphShaders(const QueryContext& context, const json& query) { + + using namespace MaterialGraph; + namespace fs = std::filesystem; + + std::vector> graphs; + std::vector names; + + if (query.contains("directory")) { + auto directory = Loader::AssetLoader::GetFullPath(query["directory"].get()); + for (const auto& file : fs::directory_iterator(directory)) { + if (file.path().extension() != ".aematgraph") + continue; + auto path = query["directory"].get() + "/" + file.path().filename().string(); + graphs.push_back(Loader::MaterialGraphLoader::LoadGraph(path)); + names.push_back(file.path().filename().string()); + } + } + + // Every node with the types of its generic inputs, connected to the output of every stage it can be used in + if (query.value("library", true)) { + const std::vector sources = { "Float", "Vector 2", "Vector 3", "Vector 4" }; + for (const auto& definition : NodeLibrary::GetDefinitions()) { + if (definition.kind == NodeKind::VertexOutput || definition.kind == NodeKind::SurfaceOutput || + definition.kind == NodeKind::Comment) + continue; + + auto isGeneric = std::any_of(definition.inputs.begin(), definition.inputs.end(), + [](const auto& input) { return input.type == ValueType::Generic; }); + + for (const auto& source : sources) { + if (!isGeneric && source != sources.front()) + break; + + for (const auto& output : definition.outputs) { + for (auto stage : { VertexStage, SurfaceStage }) { + if (!(definition.stages & stage) || output.type == ValueType::Texture) + continue; + + auto graph = CreateRef(); + auto vertexOutput = graph->AddNode(NodeLibrary::vertexOutputType).id; + auto surfaceOutput = graph->AddNode(NodeLibrary::surfaceOutputType).id; + + auto nodeId = graph->AddNode(definition.type).id; + graph->GetNode(nodeId)->name = "Value"; + + for (const auto& input : definition.inputs) { + if (input.type == ValueType::Texture) { + auto textureId = graph->AddNode("Texture parameter").id; + graph->GetNode(textureId)->name = "Texture"; + graph->Connect(textureId, "Value", nodeId, input.name); + } + else if (input.type == ValueType::Generic) { + auto sourceId = graph->AddNode(source).id; + graph->Connect(sourceId, "Value", nodeId, input.name); + } + } + + if (stage == VertexStage) + graph->Connect(nodeId, output.name, vertexOutput, NodeLibrary::positionOffsetPin); + else + graph->Connect(nodeId, output.name, surfaceOutput, NodeLibrary::emissivePin); + + graph->Compile(); + graphs.push_back(graph); + names.push_back(definition.type + " / " + output.name + " / " + source + + (stage == VertexStage ? " / vertex" : " / surface")); + } + } + } + } + } + + // The macros the renderers can set, a mesh has or doesn't have each of the attributes + std::vector> meshMacros; + for (int32_t texCoords = 0; texCoords < 2; texCoords++) { + for (int32_t tangents = 0; tangents < 2; tangents++) { + for (int32_t colors = 0; colors < 2; colors++) { + for (int32_t texCoords1 = 0; texCoords1 < 2; texCoords1++) { + for (int32_t skinned = 0; skinned < 2; skinned++) { + std::vector macros; + if (texCoords) macros.push_back("TEX_COORDS"); + if (tangents) macros.push_back("TANGENTS"); + if (colors) macros.push_back("VERTEX_COLORS"); + if (texCoords1) macros.push_back("TEX_COORDS_1"); + macros.push_back(skinned ? "SKINNED" : "INSTANCE_BUFFER"); + meshMacros.push_back(macros); + } + } + } + } + } + + struct Compilation { + std::string name; + std::string file; + VkShaderStageFlagBits stage; + std::vector macros; + bool success = false; + }; + + std::vector compilations; + auto add = [&](const std::string& name, const std::string& file, VkShaderStageFlagBits stage, const std::vector& macros) { + if (!file.empty()) + compilations.push_back({ name, file, stage, macros }); + }; + + int32_t graphErrors = 0; + json failedGraphs = json::array(); + + auto allMeshMacros = query.value("allMeshes", true); + for (size_t i = 0; i < graphs.size(); i++) { + auto compiled = graphs[i]->GetCompiled(); + if (!compiled || !compiled->valid) { + graphErrors++; + failedGraphs.push_back({ { "graph", names[i] }, { "error", compiled && !compiled->errors.empty() ? compiled->errors.front().message : "" } }); + continue; + } + + // Checking the library once is enough, the macros only matter for the code around the nodes + for (const auto& macros : meshMacros) { + add(names[i], compiled->mainVertexFile, VK_SHADER_STAGE_VERTEX_BIT, macros); + add(names[i], compiled->mainFragmentFile, VK_SHADER_STAGE_FRAGMENT_BIT, macros); + add(names[i], compiled->shadowVertexFile, VK_SHADER_STAGE_VERTEX_BIT, macros); + add(names[i], compiled->CutsOutFragments() ? compiled->shadowFragmentFile : std::string(), VK_SHADER_STAGE_FRAGMENT_BIT, macros); + + // Without a surface of the graph the regular maps of a material are used + if (!compiled->hasSurface) { + auto withMaps = macros; + for (auto map : { "BASE_COLOR_MAP", "OPACITY_MAP", "ROUGHNESS_MAP", "METALNESS_MAP", "AO_MAP", "EMISSIVE_MAP" }) + withMaps.push_back(map); + if (std::find(macros.begin(), macros.end(), "TANGENTS") != macros.end()) { + withMaps.push_back("NORMAL_MAP"); + withMaps.push_back("HEIGHT_MAP"); + } + if (std::find(macros.begin(), macros.end(), "TEX_COORDS") != macros.end()) { + add(names[i], compiled->mainVertexFile, VK_SHADER_STAGE_VERTEX_BIT, withMaps); + add(names[i], compiled->mainFragmentFile, VK_SHADER_STAGE_FRAGMENT_BIT, withMaps); + auto shadowMacros = macros; + shadowMacros.push_back("OPACITY_MAP"); + add(names[i], compiled->shadowVertexFile, VK_SHADER_STAGE_VERTEX_BIT, shadowMacros); + add(names[i], compiled->shadowFragmentFile, VK_SHADER_STAGE_FRAGMENT_BIT, shadowMacros); + } + } + + if (!allMeshMacros) + break; + } + } + + auto spirvDirectory = query.value("spirvDirectory", std::string()); + if (!spirvDirectory.empty()) + fs::create_directories(spirvDirectory); + + JobGroup group{ "Material graph shaders", JobPriority::Medium }; + JobSystem::ExecuteMultiple(group, int32_t(compilations.size()), [&](JobData& data) { + auto& compilation = compilations[data.idx]; + auto stageFile = Loader::ShaderLoader::LoadFile(compilation.file, compilation.stage); + auto binary = Graphics::ShaderCompiler::Compile(stageFile, compilation.macros, false, compilation.success); + + if (compilation.success && !spirvDirectory.empty()) { + auto suffix = compilation.stage == VK_SHADER_STAGE_VERTEX_BIT ? ".vert.spv" : ".frag.spv"; + std::ofstream file(spirvDirectory + "/" + std::to_string(data.idx) + suffix, std::ios::binary); + file.write(reinterpret_cast(binary.data()), binary.size() * sizeof(uint32_t)); + } + }); + JobSystem::Wait(group); + + json failed = json::array(); + int32_t succeeded = 0; + for (const auto& compilation : compilations) { + if (compilation.success) { + succeeded++; + continue; + } + std::string macros; + for (const auto& macro : compilation.macros) + macros += macro + " "; + if (failed.size() < 40) + failed.push_back({ { "graph", compilation.name }, { "file", compilation.file }, { "macros", macros } }); + } + + return { { "graphs", graphs.size() }, { "invalidGraphs", graphErrors }, { "failedGraphs", failedGraphs }, + { "compilations", compilations.size() }, { "succeeded", succeeded }, { "failed", failed } }; + + } + + static json QueryAround(const QueryContext& context, const json& query) { + + auto& scene = context.scene; + + auto position = ToVec3(query.at("position")); + auto radius = query.at("radius").get(); + auto aabb = Volume::AABB(position - vec3(radius), position + vec3(radius)); + + json matches = json::array(); + for (auto entity : scene.QueryAABB(aabb)) { + auto meshComponent = entity.TryGetComponent(); + if (!meshComponent) + continue; + matches.push_back({ { "entity", GetEntityLabel(entity) }, + { "distance", meshComponent->aabb.GetDistance(position) }, + { "bounds", BoundsToJson(meshComponent->aabb) } }); + } + std::sort(matches.begin(), matches.end(), [](const json& a, const json& b) { + + return a["distance"].get() < b["distance"].get(); + + }); + return matches; + + } + + static json QueryPath(const QueryContext& context, const json& query) { + + auto& scene = context.scene; + + // Sample ground height and obstacles along the polyline + auto spacing = std::max(query.value("spacing", 0.5f), 0.05f); + auto maxStep = query.value("maxStep", 0.3f); + auto radius = query.value("radius", 0.4f); + // Points given as x/z start at the terrain height with "snap": true + auto snap = query.value("snap", false); + std::vector points; + for (const auto& point : query.at("points")) + points.push_back(point.size() == 2 ? vec3(point[0].get(), 0.0f, point[1].get()) : ToVec3(point)); + if (points.size() < 2) + throw std::runtime_error("A path needs at least two points"); + + auto ignored = GetIgnoredEntities(scene, query); + + json issues = json::array(); + json samples = json::array(); + std::optional last; + float length = 0.0f; + + for (size_t i = 0; i + 1 < points.size(); i++) { + auto segment = points[i + 1] - points[i]; + auto count = std::max(int32_t(std::ceil(glm::length(vec2(segment.x, segment.z)) / spacing)), 1); + for (int32_t k = (i == 0 ? 0 : 1); k <= count; k++) { + auto guess = points[i] + segment * (float(k) / float(count)); + if (snap) { + auto sample = SampleTerrain(GetCompleteTerrain(scene), vec2(guess.x, guess.z)); + if (sample.valid && !sample.hole) + guess.y = sample.height; + } + auto ground = Raycast(scene, guess + vec3(0.0f, 1.5f, 0.0f), vec3(0.0f, -1.0f, 0.0f), 4.0f, ignored, CollisionComponents); + if (!ground.valid) { + issues.push_back({ { "at", FromVec3(guess) }, + { "issue", "no ground within 1.5 m above and 2.5 m below" } }); + continue; + } + + auto position = ground.position; + samples.push_back({ { "position", FromVec3(position) }, { "on", GetHitLabel(ground) } }); + + if (last) { + auto step = position.y - last->y; + if (std::abs(step) > maxStep) + issues.push_back({ { "at", FromVec3(position) }, + { "issue", "step of " + FormatFloat(step, 2) + " m onto " + GetHitLabel(ground) } }); + + // Obstacles between the previous and this sample, at knee and chest height and at the sides + auto direction = position - *last; + direction.y = 0.0f; + auto distance = glm::length(direction); + if (distance > 1e-4f) { + direction /= distance; + auto side = vec3(-direction.z, 0.0f, direction.x) * radius; + for (auto height : { 0.5f, 1.3f }) { + for (auto offset : { vec3(0.0f), side, -side }) { + auto origin = *last + vec3(0.0f, height, 0.0f) + offset; + auto hit = Raycast(scene, origin, direction, distance, ignored, CollisionComponents); + if (hit.valid) + issues.push_back({ { "at", FromVec3(hit.position) }, + { "issue", "blocked by " + GetHitLabel(hit) + " (" + hit.kind + ")" } }); + } + } + } + length += glm::distance(position, *last); + } + last = position; + } + } + + // Neighboring samples often report the same obstacle, keep the first occurrence per description + json uniqueIssues = json::array(); + std::set seen; + for (const auto& issue : issues) + if (seen.insert(issue["issue"].get()).second) + uniqueIssues.push_back(issue); + + return { { "walkable", uniqueIssues.empty() }, { "length", length }, + { "issues", uniqueIssues }, { "samples", samples } }; + + } + + static json QueryTerrain(const QueryContext& context, const json& query) { + + auto& scene = context.scene; + + return DescribeTerrain(GetCompleteTerrain(scene)); + + } + + static json QueryTerrainMap(const QueryContext& context, const json& query) { + + auto& scene = context.scene; + + if (context.outputDirectory.empty()) + throw std::runtime_error("terrainMap needs an output directory"); + auto file = query.value("file", std::string("terrain_map.png")); + auto image = RenderTerrainMap(scene, query); + WritePng(image, context.outputDirectory / file); + return { { "file", file }, { "width", image->width }, { "height", image->height } }; + + } + + static json QueryRoute(const QueryContext& context, const json& query) { + + auto& scene = context.scene; + + return FindRoute(scene, query, context.outputDirectory); + + } + + static json QueryBuried(const QueryContext& context, const json& query) { + + auto& scene = context.scene; + + // Meshes of a hierarchy which reach above the terrain (or lie below a hole), e.g. to check + // that a level placed under the terrain only shows at its entrance + const auto& terrain = GetCompleteTerrain(scene); + auto margin = query.value("margin", 0.0f); + auto members = CollectHierarchies(scene, { query.at("entity").get() }); + + json exposed = json::array(); + int32_t meshCount = 0; + for (auto member : members) { + Scene::Entity entity = { member, &scene.entityManager }; + auto mesh = entity.TryGetComponent(); + if (!mesh || !mesh->visible || !mesh->mesh.IsLoaded()) + continue; + meshCount++; + + const auto& aabb = mesh->aabb; + float lowest = FLT_MAX, worst = -FLT_MAX; + bool underHole = false; + for (auto fraction : { vec2(0.5f), vec2(0.1f), vec2(0.9f), vec2(0.1f, 0.9f), vec2(0.9f, 0.1f) }) { + auto point = glm::mix(vec2(aabb.min.x, aabb.min.z), vec2(aabb.max.x, aabb.max.z), fraction); + auto sample = SampleTerrain(terrain, point); + if (!sample.valid) + continue; + if (sample.hole) { + underHole = true; + continue; + } + lowest = std::min(lowest, sample.height); + worst = std::max(worst, aabb.max.y - sample.height); + } + if (underHole || worst > -margin) + exposed.push_back({ { "entity", GetEntityLabel(entity) }, { "above", worst }, { "underHole", underHole }, + { "top", aabb.max.y }, { "terrain", lowest }, { "center", FromVec3(aabb.GetCenter()) } }); + } + + std::sort(exposed.begin(), exposed.end(), [](const json& a, const json& b) { + + return a["above"].get() > b["above"].get(); + + }); + auto exposedCount = exposed.size(); + if (exposed.size() > 200) + exposed.erase(exposed.begin() + 200, exposed.end()); + return { { "meshes", meshCount }, { "exposedCount", exposedCount }, { "exposed", exposed } }; + + } + + static const std::map queryTypes = { + { "around", QueryAround }, + { "materialGraphShaders", QueryMaterialGraphShaders }, + { "path", QueryPath }, + { "terrain", QueryTerrain }, + { "terrainMap", QueryTerrainMap }, + { "route", QueryRoute }, + { "buried", QueryBuried } + }; + + json RunQueries(Scene::Scene& scene, const json& queries, const fs::path& outputDirectory) { + + QueryContext context = { scene, outputDirectory }; + + json results = json::array(); + for (const auto& query : queries) { + json result; + result["query"] = query; + + try { + auto type = query.at("type").get(); + auto handler = queryTypes.find(type); + if (handler == queryTypes.end()) { + std::string known; + for (const auto& [name, _] : queryTypes) + known += (known.empty() ? "" : ", ") + name; + throw std::runtime_error("Unknown query type '" + type + "' (" + known + "), measurements like rays, " + "ground heights and terrain samples are Lua (scene:CastRay, Bridge.SampleTerrain, Bridge.PickRay)"); + } + result["result"] = handler->second(context, query); + } + catch (const std::exception& e) { + result["error"] = e.what(); + } + + results.push_back(result); + } + + return results; + + } + +} diff --git a/src/bridge/SceneTools.h b/src/bridge/SceneTools.h new file mode 100644 index 000000000..2211de333 --- /dev/null +++ b/src/bridge/SceneTools.h @@ -0,0 +1,166 @@ +#pragma once + +#include "Common.h" + +#include "scene/Scene.h" + +#include +#include +#include + +namespace Atlas::Bridge { + + using EntitySet = std::unordered_set; + + // Physics shapes can differ from visible meshes and terrain + constexpr Scene::SceneQueryComponents VisualComponents = Scene::MeshComponentBit | Scene::TerrainComponentBit; + + // Ground, clearance and paths: what characters collide with. Bodies are hit with their collision shapes, + // meshes without a mesh shape body (e.g. grass) directly, so scenes without physics still work + constexpr Scene::SceneQueryComponents CollisionComponents = VisualComponents | Scene::RigidBodyComponentBit; + + struct RaycastHit { + + bool valid = false; + float distance = 0.0f; + vec3 position = vec3(0.0f); + vec3 normal = vec3(0.0f); + Scene::Entity entity; + // terrain, mesh, body, text + std::string kind; + // Index of the hit triangle for mesh hits + int64_t triangle = -1; + + }; + + // Material path of the hit triangle, or the submesh name if it has no material; empty if unknown + std::string GetHitMaterial(const RaycastHit& hit); + + // Label of the hit entity, or the kind of the hit if no entity was hit (e.g. terrain) + std::string GetHitLabel(const RaycastHit& hit); + + // Converts a pixel of a camera described by a job camera spec into a world space ray (origin, direction) + + std::string GetEntityName(Scene::Entity entity); + + // Unique label used in reports, e.g. "Gate (#123)" + std::string GetEntityLabel(Scene::Entity entity); + + std::vector FindEntities(Scene::Scene& scene, const std::vector& patterns); + + std::vector FindEntities(Scene::Scene& scene, const std::string& pattern); + + // Matching entities without those whose ancestor matches as well + std::vector FindTopmostEntities(Scene::Scene& scene, const std::vector& patterns); + + std::vector FindTopmostEntities(Scene::Scene& scene, const std::string& pattern); + + // Entities whose loaded mesh path matches one of the patterns and none of the excluded ones + std::vector FindMeshInstances(Scene::Scene& scene, const std::vector& patterns, + const std::vector& excluded = {}); + + // Adds the entity and all of its descendants to the set + void CollectHierarchy(Scene::Entity entity, EntitySet& set); + + // The hierarchies of all matching entities, e.g. to ignore them in raycasts + EntitySet CollectHierarchies(Scene::Scene& scene, const std::vector& patterns); + + // Whether the entity is in one of the hierarchies CollectHierarchies would collect, without visiting the whole scene + bool IsInHierarchies(Scene::Scene& scene, Scene::Entity entity, const std::vector& patterns); + + // Union of the loaded mesh bounds of the entity and its descendants. Entities without + // loaded meshes get a small box around their position + Volume::AABB GetEntityBounds(Scene::Entity entity, bool* hasMesh = nullptr); + + Volume::AABB GetBounds(const std::vector& entities); + + Volume::AABB GetSceneBounds(Scene::Scene& scene); + + vec3 GetEntityPosition(Scene::Entity entity); + + // Yaw of the entity's world rotation in radians (rotation around +Y, 0 means facing +Z) + float GetEntityYaw(Scene::Entity entity); + + // Scene::CastRay with triangle precision, filtering ignored entities, players and invisible meshes + RaycastHit Raycast(Scene::Scene& scene, vec3 origin, vec3 direction, float maxDistance, + const EntitySet& ignored = {}, Scene::SceneQueryComponents components = VisualComponents); + + RaycastHit Raycast(Scene::Scene& scene, vec3 origin, vec3 direction, float maxDistance, + const std::function& isIgnored, Scene::SceneQueryComponents components = VisualComponents); + + // Casts downwards from the given height + RaycastHit GroundBelow(Scene::Scene& scene, vec3 position, const EntitySet& ignored = {}); + + struct EntityGround { + + Volume::AABB bounds; + bool hasMesh = false; + RaycastHit ground; + + }; + + // Ground below the center of the entity bounds, ignoring its own hierarchy and the ignored entities. The ray + // starts searchAbove over the top of the bounds, such that roofs or arches above the entity are not hit + EntityGround GroundBelowEntity(Scene::Scene& scene, Scene::Entity entity, float searchAbove = 0.5f, + const EntitySet& ignored = {}); + + struct FootprintGap { + + int32_t samples = 0; + float maxGap = 0.0f; + vec3 worst = vec3(0.0f); + + }; + + // The largest gap between the underside of an entity and the ground on a grid of points over its bounds. Only points + // where the underside is within baseHeight of the bottom count, e.g. not those below the canopy of a tree + FootprintGap MeasureFootprint(Scene::Scene& scene, Scene::Entity entity, const Volume::AABB& bounds, int32_t grid, float baseHeight, + const EntitySet& ignored = {}); + + json InspectScene(Scene::Scene& scene, const std::vector& filter, + const std::vector& detail, const EntitySet& excluded = {}); + + // What the diff of an edit compares of an entity, collected without building JSON: the world scene of a pipeline + // has a million entities + struct EntityState { + std::string name; + uint64_t parent = ECS::EntityConfig::InvalidEntity; + uint32_t components = 0; + bool hasTransform = false; + mat4 local = mat4(1.0f); + mat4 global = mat4(1.0f); + std::string mesh; + bool visible = false; + std::string script; + }; + + using SceneState = std::unordered_map; + + SceneState CaptureSceneState(Scene::Scene& scene, const EntitySet& excluded = {}); + + // Changed, added and removed entities, the changed fields with the values before and after as an inspection + // lists them + json DiffSceneStates(const SceneState& before, const SceneState& after); + + json ExportSettings(Scene::Scene& scene); + + // Materials the settings patched in memory are added to patchedMaterials, ReloadMaterials restores them + void ApplySettings(Scene::Scene& scene, const json& settings, std::set& patchedMaterials); + + // Merge patch with the fields of the .aematerial files, null removes a map + void PatchMaterial(Material& material, const json& patch); + + // The meshes cache shader variants per sub data, meshes with changed maps or graphs need new ones + void UpdatePipelinesOfMaterials(const std::set& changed); + + // Patches all loaded materials whose path matches a pattern, e.g. { "kingdom/*_01_A*": { "metalness": 0.2 } } + // The fields are the ones of the .aematerial files. Returns the number of patched materials + int32_t ApplyMaterialPatches(const json& patches, std::set& patchedPaths); + + // Loads materials and material graphs from their files again, returns the materials for UpdatePipelinesOfMaterials + std::set ReloadMaterials(const std::set& paths); + + // Runs a list of spatial queries, maps and routes are written into the output directory + json RunQueries(Scene::Scene& scene, const json& queries, const fs::path& outputDirectory = {}); + +} diff --git a/src/bridge/Server.cpp b/src/bridge/Server.cpp new file mode 100644 index 000000000..81a45811e --- /dev/null +++ b/src/bridge/Server.cpp @@ -0,0 +1,101 @@ +#include "Server.h" +#include "Processes.h" + +#include +#include + +namespace Atlas::Bridge { + + Server::Server(const fs::path& directory, const std::vector& options) : directory(directory), options(options) { + + fs::create_directories(directory / "done"); + std::error_code error; + fs::remove(directory / "cancel", error); + build = fs::last_write_time(GetExecutablePath(), error).time_since_epoch().count(); + + } + + std::optional Server::Poll() { + + auto now = std::chrono::steady_clock::now(); + if (now < nextPollTime) + return std::nullopt; + nextPollTime = now + std::chrono::milliseconds(200); + + std::vector files; + std::error_code error; + for (const auto& entry : fs::directory_iterator(directory, error)) { + auto name = entry.path().filename().string(); + if (entry.is_regular_file() && name.ends_with(".json") && !name.ends_with(".result.json") && name != "server.json") + files.push_back(entry.path()); + } + if (files.empty()) + return std::nullopt; + std::sort(files.begin(), files.end()); + + auto file = files.front(); + commandName = file.stem().string(); + commandStartTime = now; + + json command; + { + std::ifstream stream(file); + command = json::parse(stream, nullptr, false, true); + } + // Processed commands are moved away, their results are written next to the queue + auto processed = directory / "done" / file.filename(); + fs::rename(file, processed, error); + if (error) { + fs::copy_file(file, processed, fs::copy_options::overwrite_existing, error); + fs::remove(file, error); + } + + return command; + + } + + void Server::Complete(const json& result, const std::string& scenePath) { + + auto complete = result; + complete["command"] = commandName; + complete["seconds"] = std::chrono::duration(std::chrono::steady_clock::now() - commandStartTime).count(); + complete["scene"] = scenePath.empty() ? json() : json(scenePath); + WriteFileAtomic(directory / (commandName + ".result.json"), complete.dump(2)); + + } + + void Server::WriteStatus(const std::string& state, const std::string& scenePath, const std::string& job) { + + json status = { + { "pid", CurrentProcessId() }, { "executable", GetExecutablePath().string() }, { "build", build }, { "options", options }, + { "state", state }, + { "scene", scenePath }, { "command", state == "idle" ? "" : commandName }, { "job", job }, + { "since", std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count() } + }; + WriteFileAtomic(directory / "server.json", status.dump(2)); + + } + + bool Server::IsCancelled() { + + auto now = std::chrono::steady_clock::now(); + if (now < nextCancelCheck) + return false; + nextCancelCheck = now + std::chrono::milliseconds(200); + + std::error_code error; + if (!fs::exists(directory / "cancel", error)) + return false; + fs::remove(directory / "cancel", error); + return true; + + } + + void Server::Close() { + + std::error_code error; + fs::remove(directory / "server.json", error); + + } + +} diff --git a/src/bridge/Server.h b/src/bridge/Server.h new file mode 100644 index 000000000..fcfe9f0bd --- /dev/null +++ b/src/bridge/Server.h @@ -0,0 +1,51 @@ +#pragma once + +#include "Common.h" + +#include +#include + +namespace Atlas::Bridge { + + // The command queue of the server mode: JSON files in a directory, processed in the order of their file names. + // A processed command is moved to done/, its result is written to .result.json. server.json tells + // clients which process serves the directory, its build and what it does; a file named cancel stops the running + // job. The client mode of the executable writes the commands (Client.h) + class Server { + + public: + // The options are the server wide options of the command line, e.g. --streaming + Server(const fs::path& directory, const std::vector& options); + + // The next command, the directory is read at most every 200 ms. Files with invalid JSON are returned as + // a discarded value + std::optional Poll(); + + // Writes the result of the current command, with its duration and the loaded scene + void Complete(const json& result, const std::string& scenePath); + + // Writes server.json: idle, loading or running, the loaded scene and the job + void WriteStatus(const std::string& state, const std::string& scenePath, const std::string& job = ""); + + // Whether a client asked to stop the running job, checked at most every 200 ms + bool IsCancelled(); + + // Removes server.json when the server ends + void Close(); + + fs::path directory; + // File name of the current command without its extension + std::string commandName; + + private: + std::vector options; + // Write time of the executable when the server started, a client restarts a server of an older build + int64_t build = 0; + + std::chrono::steady_clock::time_point commandStartTime; + std::chrono::steady_clock::time_point nextPollTime; + std::chrono::steady_clock::time_point nextCancelCheck; + + }; + +} diff --git a/src/bridge/Summary.cpp b/src/bridge/Summary.cpp new file mode 100644 index 000000000..06e516f66 --- /dev/null +++ b/src/bridge/Summary.cpp @@ -0,0 +1,167 @@ +#include "Summary.h" + +#include + +namespace Atlas::Bridge { + + // The first line, e.g. of a Lua error without its stack traceback + static std::string Shorten(const std::string& text, size_t length = 160) { + + auto line = text.substr(0, text.find('\n')); + if (line.size() > length) + return line.substr(0, length - 3) + "..."; + return line.size() < text.size() ? line + " ..." : line; + + } + + // Equal messages once with their count, in the order they first appeared + static std::vector CountDuplicates(const json& messages) { + + std::vector order; + std::map counts; + for (const auto& message : messages) { + auto text = message.is_string() ? message.get() : message.dump(); + if (counts[text]++ == 0) + order.push_back(text); + } + + std::vector lines; + for (const auto& text : order) + lines.push_back(Shorten(text) + (counts[text] > 1 ? " (" + std::to_string(counts[text]) + "x)" : "")); + return lines; + + } + + std::vector FormatSummary(const json& report, const fs::path& outputDirectory) { + + std::vector lines; + auto add = [&](const std::string& line) { lines.push_back(line); }; + + auto status = report.value("status", std::string("unknown")); + std::string head = report.value("job", std::string("job")) + ": " + status; + if (report.contains("totalSeconds")) + head += " in " + FormatFloat(report["totalSeconds"].get(), 1) + " s"; + std::vector parts; + if (report.value("loadSeconds", 0.0f) > 0.05f) + parts.push_back("load " + FormatFloat(report["loadSeconds"].get(), 1) + " s"); + if (report.contains("playedSeconds")) + parts.push_back("played " + FormatFloat(report["playedSeconds"].get(), 1) + " s"); + if (!parts.empty()) { + head += " ("; + for (size_t i = 0; i < parts.size(); i++) + head += (i ? ", " : "") + parts[i]; + head += ")"; + } + if (report.contains("reason")) + head += ": " + report["reason"].get(); + add(head); + + constexpr size_t maxItems = 6; + auto list = [&](const std::string& title, const std::vector& items) { + + if (items.empty()) + return; + add(" " + title + ":"); + for (size_t i = 0; i < std::min(items.size(), maxItems); i++) + add(" " + items[i]); + if (items.size() > maxItems) + add(" ... " + std::to_string(items.size() - maxItems) + " more in report.json"); + + }; + + list("errors", CountDuplicates(report.value("errors", json::array()))); + + // Failures of a check are listed by their message, entities with the same failure are counted + if (report.contains("checks")) { + std::vector failures; + for (const auto& failure : report["checks"].value("failures", json::array())) { + // Log failures are named by their message + auto check = failure.value("check", std::string()); + auto entity = check == "log" ? std::string() : failure.value("entity", std::string()) + ": "; + failures.push_back("[" + check + "] " + entity + Shorten(failure.value("message", std::string()), 140) + " (t=" + + FormatFloat(failure.value("firstTime", 0.0f), 2) + "s, " + std::to_string(failure.value("occurrences", 1)) + "x)"); + } + list("failed checks", failures); + } + + if (report.contains("expectations")) { + std::vector failed; + int32_t passed = 0; + for (const auto& expectation : report["expectations"]) { + if (expectation.value("passed", false)) { + passed++; + continue; + } + auto expect = expectation.value("expect", json()); + auto what = expect.contains("lua") ? expect["lua"].get() : expect.dump(); + if (expect.contains("op")) + what += " " + expect["op"].get() + " " + expect.value("value", json()).dump(); + failed.push_back("t=" + FormatFloat(expectation.value("t", 0.0f), 2) + "s " + Shorten(what, 100) + ", actual " + + Shorten(expectation.contains("error") ? expectation["error"].dump() : expectation.value("actual", json()).dump(), 100)); + } + add(" expectations: " + std::to_string(passed) + " passed" + (failed.empty() ? "" : ", " + std::to_string(failed.size()) + " failed")); + list("failed expectations", failed); + } + + if (report.contains("comparisons")) { + std::vector differing; + size_t same = 0; + for (const auto& comparison : report["comparisons"]) { + if (comparison.value("status", std::string()) == "same") + same++; + else + differing.push_back(comparison.value("image", std::string()) + ": " + comparison.value("status", std::string()) + + (comparison.contains("percent") ? " (" + FormatFloat(comparison["percent"].get(), 2) + "% of the pixels)" : "")); + } + add(" reference images: " + std::to_string(same) + " same" + (differing.empty() ? "" : ", " + std::to_string(differing.size()) + " differ")); + list("differing images", differing); + } + + if (report.contains("conditionalEvents")) { + std::vector missed; + for (const auto& trigger : report["conditionalEvents"]) + if (!trigger.value("fired", false)) + missed.push_back(Shorten(trigger.value("event", json()).dump(), 140)); + list("conditions that never happened", missed); + } + + if (report.contains("results") && !report["results"].empty()) { + std::vector results; + for (const auto& [key, value] : report["results"].items()) + results.push_back(key + " = " + Shorten(value.dump(), 200)); + add(" results:"); + for (const auto& result : results) + add(" " + result); + } + + auto warnings = CountDuplicates(report.value("warnings", json::array())); + if (!warnings.empty()) + add(" warnings: " + std::to_string(warnings.size()) + ", first: " + warnings.front()); + if (report.value("engineLogErrors", 0) > 0) + add(" engine log errors: " + std::to_string(report["engineLogErrors"].get()) + " (log.txt)"); + + // Images by count, the sheet first, other files by name + int32_t images = 0; + std::vector files; + for (const auto& output : report.value("outputs", json::array())) { + auto path = output.get(); + auto extension = fs::path(path).extension().string(); + if (path == "sheet.jpg") + files.insert(files.begin(), path); + else if (extension == ".png" || extension == ".jpg") + images++; + else + files.push_back(path); + } + std::string outputs = " outputs in " + outputDirectory.string() + ":"; + for (const auto& file : files) + outputs += " " + file; + if (images > 0) + outputs += " +" + std::to_string(images) + " images"; + add(outputs); + + return lines; + + } + +} diff --git a/src/bridge/Summary.h b/src/bridge/Summary.h new file mode 100644 index 000000000..3e34963bb --- /dev/null +++ b/src/bridge/Summary.h @@ -0,0 +1,11 @@ +#pragma once + +#include "Common.h" + +namespace Atlas::Bridge { + + // The result of a job in a few lines, from its report.json: status, failed checks and expectations grouped with + // counts, conditions that never happened, results, errors and outputs. Printed at the end of a job and by the client + std::vector FormatSummary(const json& report, const fs::path& outputDirectory); + +} diff --git a/src/bridge/TerrainTools.cpp b/src/bridge/TerrainTools.cpp new file mode 100644 index 000000000..4e7eaccc1 --- /dev/null +++ b/src/bridge/TerrainTools.cpp @@ -0,0 +1,1230 @@ +#include "TerrainTools.h" + +#include "Filter.h" +#include "common/MathHelper.h" +#include "loader/ImageLoader.h" +#include "loader/MaterialLoader.h" +#include "loader/TerrainLoader.h" +#include "physics/ShapesManager.h" +#include "resource/ResourceManager.h" +#include "tools/TerrainTool.h" +#include "navigation/NavigationMesh.h" + +#include +#include +#include +#include +#include +#include + +namespace Atlas::Bridge { + + using namespace Scene::Components; + + // Texels of the highest LoD, which cover the terrain without overlap (the last row/column of a cell is + // the first of the next one) + struct TexelGrid { + + Terrain::Terrain* terrain = nullptr; + int32_t LoD = 0; + int32_t cellsPerSide = 0; + int32_t texelsPerCell = 0; + int32_t texelsPerSide = 0; + float texelSize = 0.0f; + + Terrain::TerrainStorageCell* GetCell(ivec2 texel, int32_t& index) const { + + if (texel.x < 0 || texel.y < 0 || texel.x >= texelsPerSide || texel.y >= texelsPerSide) + return nullptr; + + auto cell = terrain->storage->GetCell(texel.x / texelsPerCell, texel.y / texelsPerCell, LoD); + if (!cell || !cell->IsLoaded()) + return nullptr; + + auto local = texel % texelsPerCell; + index = local.y * cell->heightField->width + local.x; + return cell; + + } + + bool IsHole(ivec2 texel) const { + + int32_t index; + auto cell = GetCell(texel, index); + return cell && cell->heightData[index] == FLT_MAX; + + } + + // World space height, FLT_MAX for holes and texels outside of the terrain + float GetHeight(ivec2 texel) const { + + int32_t index; + auto cell = GetCell(texel, index); + if (!cell || cell->heightData[index] == FLT_MAX) + return FLT_MAX; + return terrain->translation.y + cell->heightData[index] * terrain->heightScale; + + } + + int32_t GetMaterial(ivec2 texel) const { + + int32_t index; + auto cell = GetCell(texel, index); + if (!cell || cell->materialIdxData.empty()) + return -1; + return cell->materialIdxData[index]; + + } + + ivec2 ToTexel(vec2 world) const { + + auto relative = (world - vec2(terrain->translation.x, terrain->translation.z)) / texelSize; + return ivec2(glm::floor(relative + 0.5f)); + + } + + vec2 ToWorld(ivec2 texel) const { + + return vec2(terrain->translation.x, terrain->translation.z) + vec2(texel) * texelSize; + + } + + }; + + static TexelGrid GetTexelGrid(const Ref& terrain) { + + TexelGrid grid; + grid.terrain = terrain.get(); + grid.LoD = terrain->LoDCount - 1; + grid.cellsPerSide = int32_t(std::round(std::sqrt(float(terrain->storage->GetCellCount(grid.LoD))))); + grid.texelsPerCell = 8 * terrain->patchSizeFactor; + grid.texelsPerSide = grid.cellsPerSide * grid.texelsPerCell; + grid.texelSize = terrain->sideLength / float(grid.texelsPerSide); + return grid; + + } + + const Ref& GetCompleteTerrain(Scene::Scene& scene) { + + if (!scene.terrain.IsLoaded()) + throw std::runtime_error("The scene has no loaded terrain"); + + auto& terrain = scene.terrain.Get(); + if (!terrain->storage->inEditing) { + Tools::TerrainTool::LoadMissingCells(terrain, scene.terrain.GetResource()->path); + terrain->storage->inEditing = true; + } + + return terrain; + + } + + TerrainSample SampleTerrain(const Ref& terrain, vec2 position) { + + TerrainSample sample; + auto grid = GetTexelGrid(terrain); + auto texel = grid.ToTexel(position); + + int32_t index; + if (!grid.GetCell(texel, index)) + return sample; + + sample.valid = true; + sample.material = grid.GetMaterial(texel); + if (grid.IsHole(texel)) { + sample.hole = true; + return sample; + } + + // Next to holes the interpolated height is invalid, the texel height is used there + auto center = grid.GetHeight(texel); + sample.height = terrain->GetHeight(position.x, position.y); + if (sample.height < terrain->translation.y) + sample.height = center; + + // Terrain::GetHeight derives its normal with unit texel spacing, use the actual spacing + auto heightAt = [&](ivec2 offset) { + + auto height = grid.GetHeight(texel + offset); + return height == FLT_MAX ? center : height; + + }; + auto dx = (heightAt(ivec2(1, 0)) - heightAt(ivec2(-1, 0))) / (2.0f * grid.texelSize); + auto dz = (heightAt(ivec2(0, 1)) - heightAt(ivec2(0, -1))) / (2.0f * grid.texelSize); + sample.normal = glm::normalize(vec3(-dx, 1.0f, -dz)); + sample.slopeDegrees = glm::degrees(std::acos(glm::clamp(sample.normal.y, -1.0f, 1.0f))); + return sample; + + } + + json DescribeTerrain(const Ref& terrain) { + + auto grid = GetTexelGrid(terrain); + + json description; + description["translation"] = FromVec3(terrain->translation); + description["sideLength"] = terrain->sideLength; + description["min"] = { terrain->translation.x, terrain->translation.z }; + description["max"] = { terrain->translation.x + terrain->sideLength, terrain->translation.z + terrain->sideLength }; + description["resolution"] = terrain->resolution; + description["heightScale"] = terrain->heightScale; + description["LoDCount"] = terrain->LoDCount; + description["cellsPerSide"] = grid.cellsPerSide; + description["texelSize"] = grid.texelSize; + + json materials = json::array(); + for (size_t slot = 0; slot < terrain->storage->materials.size(); slot++) { + const auto& material = terrain->storage->materials[slot]; + if (material.IsValid()) + materials.push_back({ { "slot", slot }, { "material", material.GetResource()->path } }); + } + description["materials"] = materials; + + // Connected hole regions with 8-neighborhood + std::vector visited(size_t(grid.texelsPerSide) * size_t(grid.texelsPerSide), 0); + json holes = json::array(); + float minHeight = FLT_MAX, maxHeight = -FLT_MAX; + std::vector materialCounts(terrain->storage->materials.size() + 1, 0); + + for (int32_t y = 0; y < grid.texelsPerSide; y++) { + for (int32_t x = 0; x < grid.texelsPerSide; x++) { + ivec2 texel(x, y); + auto material = grid.GetMaterial(texel); + if (material >= 0 && material < int32_t(materialCounts.size())) + materialCounts[material]++; + + auto height = grid.GetHeight(texel); + if (height != FLT_MAX) { + minHeight = std::min(minHeight, height); + maxHeight = std::max(maxHeight, height); + } + + auto start = size_t(y) * grid.texelsPerSide + x; + if (visited[start] || !grid.IsHole(texel)) + continue; + + std::vector stack = { texel }; + visited[start] = 1; + ivec2 min(x, y), max(x, y); + int64_t count = 0; + vec2 sum(0.0f); + float rimMin = FLT_MAX, rimMax = -FLT_MAX, rimSum = 0.0f; + int32_t rimCount = 0; + + while (!stack.empty()) { + auto current = stack.back(); + stack.pop_back(); + count++; + sum += vec2(current); + min = glm::min(min, current); + max = glm::max(max, current); + + for (int32_t j = -1; j <= 1; j++) { + for (int32_t i = -1; i <= 1; i++) { + auto neighbor = current + ivec2(i, j); + int32_t index; + if ((i == 0 && j == 0) || !grid.GetCell(neighbor, index)) + continue; + auto neighborIndex = size_t(neighbor.y) * grid.texelsPerSide + neighbor.x; + if (grid.IsHole(neighbor)) { + if (!visited[neighborIndex]) { + visited[neighborIndex] = 1; + stack.push_back(neighbor); + } + continue; + } + + auto rimHeight = grid.GetHeight(neighbor); + rimMin = std::min(rimMin, rimHeight); + rimMax = std::max(rimMax, rimHeight); + rimSum += rimHeight; + rimCount++; + } + } + } + + auto worldMin = grid.ToWorld(min); + auto worldMax = grid.ToWorld(max); + auto center = grid.ToWorld(ivec2(0)) + sum / float(count) * grid.texelSize; + json hole = { + { "texels", count }, + { "area", float(count) * grid.texelSize * grid.texelSize }, + { "center", { center.x, center.y } }, + { "min", { worldMin.x, worldMin.y } }, + { "max", { worldMax.x, worldMax.y } }, + { "size", { worldMax.x - worldMin.x + grid.texelSize, worldMax.y - worldMin.y + grid.texelSize } } + }; + if (rimCount > 0) + hole["rimHeight"] = { { "min", rimMin }, { "max", rimMax }, { "average", rimSum / float(rimCount) } }; + holes.push_back(hole); + } + } + + std::sort(holes.begin(), holes.end(), [](const json& a, const json& b) { + + return a["texels"].get() > b["texels"].get(); + + }); + + json usage = json::array(); + for (size_t slot = 0; slot < materialCounts.size(); slot++) + if (materialCounts[slot] > 0) + usage.push_back({ { "slot", slot }, + { "share", float(materialCounts[slot]) / float(grid.texelsPerSide * grid.texelsPerSide) } }); + + description["materialUsage"] = usage; + description["heightRange"] = { minHeight, maxHeight }; + description["holes"] = holes; + return description; + + } + + static u8vec4 MaterialColor(int32_t slot) { + + static const std::vector colors = { + { 92, 138, 58, 255 }, { 214, 190, 128, 255 }, { 240, 244, 250, 255 }, { 120, 116, 110, 255 }, + { 196, 204, 214, 255 }, { 138, 104, 70, 255 }, { 180, 160, 120, 255 }, { 70, 110, 140, 255 }, + { 150, 90, 150, 255 }, { 60, 90, 40, 255 } }; + + if (slot < 0) + return { 0, 0, 0, 255 }; + return colors[size_t(slot) % colors.size()]; + + } + + static void DrawLine(Image& image, vec2 a, vec2 b, u8vec4 color, float alpha = 1.0f) { + + auto steps = int32_t(std::max(std::abs(b.x - a.x), std::abs(b.y - a.y))) + 1; + for (int32_t i = 0; i <= steps; i++) { + auto point = glm::mix(a, b, float(i) / float(steps)); + image.BlendPixel(int32_t(point.x), int32_t(point.y), vec4(color), alpha); + } + + } + + Ref RenderTerrainMap(Scene::Scene& scene, const json& spec) { + + const auto& terrain = GetCompleteTerrain(scene); + auto grid = GetTexelGrid(terrain); + + vec2 regionMin(terrain->translation.x, terrain->translation.z); + vec2 regionMax = regionMin + vec2(terrain->sideLength); + if (spec.contains("min")) + regionMin = vec2(spec["min"].at(0).get(), spec["min"].at(1).get()); + if (spec.contains("max")) + regionMax = vec2(spec["max"].at(0).get(), spec["max"].at(1).get()); + if (spec.contains("center") && spec.contains("radius")) { + auto center = vec2(spec["center"].at(0).get(), spec["center"].at(1).get()); + auto radius = spec["radius"].get(); + regionMin = center - vec2(radius); + regionMax = center + vec2(radius); + } + + auto extent = regionMax - regionMin; + if (extent.x <= 0.0f || extent.y <= 0.0f) + throw std::runtime_error("terrainMap: max has to be larger than min"); + + auto size = spec.value("size", 2048); + auto metersPerPixel = std::max(extent.x, extent.y) / float(size); + auto width = int32_t(std::ceil(extent.x / metersPerPixel)); + auto height = int32_t(std::ceil(extent.y / metersPerPixel)); + auto contour = spec.value("contour", 5.0f); + + // +X to the right, +Z down + auto toPixel = [&](vec2 world) { return (world - regionMin) / metersPerPixel; }; + auto toWorld = [&](float x, float y) { return regionMin + vec2(x + 0.5f, y + 0.5f) * metersPerPixel; }; + + auto image = CreateImage(width, height, u8vec4(20, 20, 30, 255)); + auto& data = image->GetData(); + auto sunDirection = glm::normalize(vec3(-1.0f, 1.4f, -0.8f)); + + for (int32_t y = 0; y < height; y++) { + for (int32_t x = 0; x < width; x++) { + auto world = toWorld(float(x), float(y)); + auto texel = grid.ToTexel(world); + int32_t index; + if (!grid.GetCell(texel, index)) + continue; + + auto offset = (size_t(y) * width + x) * 4; + if (grid.IsHole(texel)) { + data[offset] = 255, data[offset + 1] = 0, data[offset + 2] = 255; + continue; + } + + auto center = grid.GetHeight(texel); + auto step = std::max(1, int32_t(metersPerPixel / grid.texelSize)); + auto right = grid.GetHeight(texel + ivec2(step, 0)); + auto down = grid.GetHeight(texel + ivec2(0, step)); + right = right == FLT_MAX ? center : right; + down = down == FLT_MAX ? center : down; + auto distance = float(step) * grid.texelSize; + auto normal = glm::normalize(vec3(center - right, distance, center - down)); + auto shade = 0.45f + 0.75f * std::max(0.0f, glm::dot(normal, sunDirection)); + + auto color = vec3(MaterialColor(grid.GetMaterial(texel))) * shade; + // Contour lines where the height crosses a multiple of the contour spacing + if (contour > 0.0f && std::floor(center / contour) != std::floor(std::min(right, down) / contour)) + color *= 0.6f; + + color = glm::clamp(color, vec3(0.0f), vec3(255.0f)); + data[offset] = uint8_t(color.r), data[offset + 1] = uint8_t(color.g), data[offset + 2] = uint8_t(color.b); + } + } + + // Footprints of mesh entities. Grass and other small vegetation would hide the terrain + // Highlighted hierarchies are drawn on top in cyan, e.g. to see the footprint of a placed prefab + auto highlighted = CollectHierarchies(scene, spec.value("highlight", std::vector())); + + if (spec.value("meshes", true) || !highlighted.empty()) { + auto smallMeshes = spec.value("smallMeshes", false); + auto meshSubset = scene.GetSubset(); + for (auto entityId : meshSubset) { + const auto& mesh = meshSubset.Get(entityId); + if (!mesh.visible || !mesh.mesh.IsLoaded()) + continue; + + auto min = toPixel(vec2(mesh.aabb.min.x, mesh.aabb.min.z)); + auto max = toPixel(vec2(mesh.aabb.max.x, mesh.aabb.max.z)); + if (highlighted.contains(entityId)) { + for (auto py = int32_t(min.y); py <= int32_t(max.y); py++) + for (auto px = int32_t(min.x); px <= int32_t(max.x); px++) + image->BlendPixel(px, py, vec4(0, 230, 255, 255), 0.25f); + continue; + } + if (!spec.value("meshes", true)) + continue; + + // Colored by the naming conventions of common asset packs + Scene::Entity entity = { entityId, &scene.entityManager }; + auto name = GetEntityName(entity); + auto meshSize = mesh.aabb.max - mesh.aabb.min; + if (meshSize.x > 400.0f || meshSize.z > 400.0f) + continue; + if (!smallMeshes && meshSize.x < 1.0f && meshSize.z < 1.0f) + continue; + + u8vec4 color(40, 40, 40, 255); + float alpha = 0.55f; + if (name.find("Grass") != std::string::npos || name.find("Flower") != std::string::npos) { + if (!smallMeshes) + continue; + color = u8vec4(170, 230, 90, 255); + alpha = 0.35f; + } + else if (name.find("Tree") != std::string::npos || name.find("Bush") != std::string::npos || + name.find("Fern") != std::string::npos) { + color = u8vec4(20, 70, 20, 255); + alpha = 0.7f; + } + else if (name.find("SM_Bld") != std::string::npos || name.find("Wall") != std::string::npos) { + color = u8vec4(120, 30, 30, 255); + alpha = 0.6f; + } + else if (name.find("Rock") != std::string::npos || name.find("Cliff") != std::string::npos) { + color = u8vec4(70, 70, 80, 255); + } + + for (auto py = int32_t(min.y); py <= int32_t(max.y); py++) + for (auto px = int32_t(min.x); px <= int32_t(max.x); px++) + image->BlendPixel(px, py, vec4(color), alpha); + } + } + + auto gridSpacing = spec.value("grid", 100.0f); + if (gridSpacing > 0.0f) { + auto labelHeight = std::max(12.0f, float(width) / 110.0f); + for (auto value = std::ceil(regionMin.x / gridSpacing) * gridSpacing; value <= regionMax.x; value += gridSpacing) { + auto px = toPixel(vec2(value, 0.0f)).x; + DrawLine(*image, vec2(px, 0.0f), vec2(px, float(height - 1)), u8vec4(255), 0.35f); + DrawText(*image, int32_t(px) + 3, 2, "x " + FormatFloat(value, 0), labelHeight, u8vec4(255, 255, 160, 255)); + } + for (auto value = std::ceil(regionMin.y / gridSpacing) * gridSpacing; value <= regionMax.y; value += gridSpacing) { + auto py = toPixel(vec2(0.0f, value)).y; + DrawLine(*image, vec2(0.0f, py), vec2(float(width - 1), py), u8vec4(255), 0.35f); + DrawText(*image, 3, int32_t(py) + 2, "z " + FormatFloat(value, 0), labelHeight, u8vec4(255, 255, 160, 255)); + } + } + + if (spec.contains("markers")) { + for (const auto& marker : spec["markers"]) { + const auto& position = marker.at("position"); + auto pixel = toPixel(ToVec2(position)); + auto color = u8vec4(vec3(ToVec3(marker.value("color", json()), vec3(1.0f, 0.1f, 0.1f))) * 255.0f, 255.0f); + auto radius = std::max(2.0f, marker.value("radius", 0.0f) / metersPerPixel); + for (int32_t i = 0; i < 64; i++) { + auto a = float(i) / 64.0f * 6.2831853f, b = float(i + 1) / 64.0f * 6.2831853f; + DrawLine(*image, pixel + radius * vec2(std::cos(a), std::sin(a)), + pixel + radius * vec2(std::cos(b), std::sin(b)), color); + } + if (marker.contains("label")) + DrawText(*image, int32_t(pixel.x + radius + 3.0f), int32_t(pixel.y - 6.0f), + marker["label"].get(), std::max(14.0f, float(width) / 90.0f), color); + } + } + + if (spec.contains("paths")) { + for (const auto& path : spec["paths"]) { + auto color = u8vec4(vec3(ToVec3(path.value("color", json()), vec3(1.0f, 0.9f, 0.1f))) * 255.0f, 255.0f); + const auto& points = path.at("points"); + for (size_t i = 1; i < points.size(); i++) + DrawLine(*image, toPixel(ToVec2(points[i - 1])), toPixel(ToVec2(points[i])), color); + } + } + + return image; + + } + + // Brush sizes are in texels and have to stay below two cell edges (the brushes work on 3x3 cells) + static int32_t GetBrushSize(const TexelGrid& grid, float radius) { + + auto size = 2 * int32_t(std::round(radius / grid.texelSize)) + 1; + if (size >= 2 * grid.texelsPerCell) + throw std::runtime_error("Terrain brush radius " + FormatFloat(radius, 1) + " is too large, the maximum is " + + FormatFloat(float(grid.texelsPerCell - 1) * grid.texelSize, 1) + " m. Split it into several brushes"); + return std::max(size, 1); + + } + + // Stamps along a polyline in steps of the spacing + static std::vector SamplePolyline(const json& points, float spacing) { + + std::vector samples; + for (size_t i = 1; i < points.size(); i++) { + auto a = ToVec2(points[i - 1]); + auto b = ToVec2(points[i]); + auto length = glm::distance(a, b); + auto steps = std::max(1, int32_t(std::ceil(length / spacing))); + for (int32_t step = i == 1 ? 0 : 1; step <= steps; step++) + samples.push_back(glm::mix(a, b, float(step) / float(steps))); + } + if (points.size() == 1) + samples.push_back(ToVec2(points[0])); + return samples; + + } + + // Why a route cell is blocked: no ground (holes, outside of the terrain), steep slopes, avoided surfaces (e.g. water), + // objects lying on the ground (rocks, houses) unless they match walkOn, and obstacles at knee and chest height + enum class BlockReason : uint8_t { + None, + Ground, + Slope, + Avoided, + Object, + Obstacle + }; + + struct RouteCell { + + BlockReason reason = BlockReason::None; + float height = 0.0f; + float slope = 0.0f; + + bool IsBlocked() const { return reason != BlockReason::None; } + + }; + + // The route on a navigation mesh like the game builds it, with the settings of the scene's navigation. The mesh + // is built leg by leg around the stops, which are placed on the terrain or given with their height + static json FindNavigationRoute(Scene::Scene& scene, const json& query) { + + std::vector stops; + auto addStop = [&](const json& stop) { + if (stop.size() == 3) { + stops.push_back(ToVec3(stop)); + return; + } + auto position = ToVec2(stop); + if (!scene.terrain.IsLoaded()) + throw std::runtime_error("route: stops need a height in a scene without terrain"); + auto sample = SampleTerrain(GetCompleteTerrain(scene), position); + stops.push_back(vec3(position.x, sample.valid ? sample.height : 0.0f, position.y)); + }; + addStop(query.at("from")); + for (const auto& via : query.value("via", json::array())) + addStop(via); + addStop(query.at("to")); + + auto settings = scene.navigation ? scene.navigation->settings : Navigation::NavigationSettings(); + Navigation::NavigationMesh mesh(settings); + mesh.searchExtents = vec3(2.0f, 4.0f, 2.0f); + + auto margin = query.value("margin", 60.0f); + auto timeout = query.value("timeout", 120.0f); + + auto formatStop = [](vec3 stop) { return FormatFloat(stop.x, 1) + ", " + FormatFloat(stop.z, 1); }; + + json points = json::array(); + auto totalLength = 0.0f; + for (size_t leg = 0; leg + 1 < stops.size(); leg++) { + auto from = stops[leg], to = stops[leg + 1]; + auto center = (from + to) * 0.5f; + auto radius = glm::distance(vec2(from.x, from.z), vec2(to.x, to.z)) * 0.5f + margin; + + auto start = std::chrono::steady_clock::now(); + while (true) { + mesh.Update(&scene, center, radius); + if (!mesh.GetPendingTileCount()) + break; + if (std::chrono::duration(std::chrono::steady_clock::now() - start).count() > timeout) + throw std::runtime_error("route: the navigation tiles around " + formatStop(center) + " weren't built within " + + FormatFloat(timeout, 0) + " s"); + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } + + auto path = mesh.FindPath(from, to); + if (path.empty()) + throw std::runtime_error("route: no path on the navigation mesh from " + formatStop(from) + " to " + formatStop(to) + + " (" + std::to_string(mesh.GetTileCount()) + " tiles with polygons)"); + + for (size_t i = leg == 0 ? 0 : 1; i < path.size(); i++) { + if (!points.empty()) { + const auto& last = points.back(); + totalLength += glm::distance(vec3(last[0].get(), last[1].get(), last[2].get()), path[i]); + } + points.push_back({ path[i].x, path[i].y, path[i].z }); + } + } + + return { { "points", points }, { "length", totalLength }, { "navigation", true } }; + + } + + json FindRoute(Scene::Scene& scene, const json& query, const fs::path& outputDirectory) { + + if (query.value("navigation", false)) + return FindNavigationRoute(scene, query); + + const auto& terrain = GetCompleteTerrain(scene); + + std::vector stops = { ToVec2(query.at("from")) }; + for (const auto& via : query.value("via", json::array())) + stops.push_back(ToVec2(via)); + stops.push_back(ToVec2(query.at("to"))); + + auto cellSize = query.value("cell", 2.0f); + auto margin = query.value("margin", 60.0f); + auto maxSlope = query.value("maxSlope", 30.0f); + auto maxStep = query.value("maxStep", 0.6f); + auto clearance = query.value("clearance", 1); + auto avoidMaterials = query.value("avoidMaterials", std::vector()); + auto avoidEntities = query.value("avoid", std::vector()); + auto walkOn = query.value("walkOn", std::vector()); + auto slopeWeight = query.value("slopeWeight", 2.0f); + + auto ignored = CollectHierarchies(scene, query.value("ignore", std::vector())); + // The terrain is sampled directly, its height field body would count as an obstacle on slopes + auto rigidBodySubset = scene.GetSubset(); + for (auto entity : rigidBodySubset) { + auto& rigidBody = rigidBodySubset.Get(entity); + if (rigidBody.IsValid() && rigidBody.GetShape()->type == Physics::ShapeType::HeightField) + ignored.insert(entity); + } + + vec2 regionMin(FLT_MAX), regionMax(-FLT_MAX); + for (auto stop : stops) { + regionMin = glm::min(regionMin, stop - vec2(margin)); + regionMax = glm::max(regionMax, stop + vec2(margin)); + } + auto size = ivec2(glm::ceil((regionMax - regionMin) / cellSize)) + 1; + if (size.x * size.y > 400000) + throw std::runtime_error("route: the region has too many cells, increase cell or reduce margin"); + + auto toWorld = [&](ivec2 cell) { return regionMin + vec2(cell) * cellSize; }; + auto toCell = [&](vec2 world) { + return glm::clamp(ivec2(glm::round((world - regionMin) / cellSize)), ivec2(0), size - 1); + }; + auto index = [&](ivec2 cell) { return size_t(cell.y) * size.x + cell.x; }; + + auto nameMatches = [&](Scene::Entity entity, const std::vector& patterns) { + + for (; entity.IsValid(); entity = scene.GetParentEntity(entity)) + if (MatchAnyPattern(patterns, GetEntityName(entity))) + return true; + return false; + + }; + + std::vector cells(size_t(size.x) * size.y); + std::map blockers; + auto countBlocker = [&](Scene::Entity entity) { + + // Counted by the name without the instance number, e.g. "Rocks SM_Env_Rock_01 17" as "Rocks SM_Env_Rock_01" + auto name = GetEntityName(entity); + auto end = name.find_last_not_of("0123456789"); + if (end != std::string::npos && end + 1 < name.size() && (name[end] == '_' || name[end] == ' ')) + name = name.substr(0, end); + blockers[name]++; + + }; + for (int32_t y = 0; y < size.y; y++) { + for (int32_t x = 0; x < size.x; x++) { + auto& cell = cells[index({ x, y })]; + auto world = toWorld({ x, y }); + auto sample = SampleTerrain(terrain, world); + if (!sample.valid || sample.hole) { + cell.reason = BlockReason::Ground; + continue; + } + + auto hit = Raycast(scene, vec3(world.x, sample.height + 3.0f, world.y), vec3(0.0f, -1.0f, 0.0f), 6.0f, + ignored, CollisionComponents); + if (!hit.valid) { + cell.reason = BlockReason::Ground; + continue; + } + cell.height = hit.position.y; + cell.slope = hit.kind == "terrain" ? sample.slopeDegrees : + glm::degrees(std::acos(glm::clamp(std::abs(hit.normal.y), 0.0f, 1.0f))); + + if (hit.kind != "terrain") { + auto onTop = hit.position.y - sample.height > 0.35f; + if (MatchAnyPattern(avoidMaterials, GetHitMaterial(hit)) || nameMatches(hit.entity, avoidEntities)) { + cell.reason = BlockReason::Avoided; + continue; + } + if (onTop && !nameMatches(hit.entity, walkOn)) { + cell.reason = BlockReason::Object; + countBlocker(hit.entity); + continue; + } + } + if (cell.slope > maxSlope) { + cell.reason = BlockReason::Slope; + continue; + } + + // Obstacles standing in the cell + for (auto height : { 0.5f, 1.3f }) { + for (auto direction : { vec3(1.0f, 0.0f, 0.0f), vec3(0.0f, 0.0f, 1.0f) }) { + auto origin = vec3(world.x, cell.height + height, world.y) - direction * (cellSize * 0.5f); + auto obstacle = Raycast(scene, origin, direction, cellSize, ignored, CollisionComponents); + if (obstacle.valid && obstacle.kind != "terrain" && !nameMatches(obstacle.entity, walkOn)) { + cell.reason = BlockReason::Obstacle; + countBlocker(obstacle.entity); + } + } + } + } + } + + // Keep a distance to blocked cells, except at the stops themselves + std::vector blocked(cells.size(), 0); + int32_t blockedCount = 0; + for (int32_t y = 0; y < size.y; y++) { + for (int32_t x = 0; x < size.x; x++) { + if (!cells[index({ x, y })].IsBlocked()) + continue; + blockedCount++; + for (int32_t j = -clearance; j <= clearance; j++) { + for (int32_t i = -clearance; i <= clearance; i++) { + auto neighbor = ivec2(x + i, y + j); + if (glm::all(glm::greaterThanEqual(neighbor, ivec2(0))) && glm::all(glm::lessThan(neighbor, size))) + blocked[index(neighbor)] = 1; + } + } + } + } + for (auto stop : stops) { + auto cell = toCell(stop); + if (!cells[index(cell)].IsBlocked()) + blocked[index(cell)] = 0; + } + + // Diagnostic image: free cells shaded by height, blocked cells colored by their reason, the route in yellow + Ref map; + if (query.contains("map") && !outputDirectory.empty()) { + static const u8vec4 reasonColors[] = { { 120, 120, 120, 255 }, { 0, 0, 0, 255 }, { 230, 140, 30, 255 }, + { 40, 90, 230, 255 }, { 150, 150, 160, 255 }, { 220, 30, 30, 255 } }; + map = CreateImage(size.x, size.y); + for (int32_t y = 0; y < size.y; y++) { + for (int32_t x = 0; x < size.x; x++) { + const auto& cell = cells[index({ x, y })]; + auto color = cell.IsBlocked() ? reasonColors[size_t(cell.reason)] : + (blocked[index({ x, y })] ? u8vec4(90, 140, 70, 255) : u8vec4(120, 200, 100, 255)); + map->SetData(x, y, ivec4(color)); + } + } + } + auto writeMap = [&]() { + + if (map) + WritePng(map, outputDirectory / query["map"].get()); + + }; + + auto passable = [&](ivec2 a, ivec2 b) { + + if (blocked[index(b)]) + return false; + return std::abs(cells[index(a)].height - cells[index(b)].height) <= maxStep * glm::length(vec2(b - a)); + + }; + + // Line of sight over passable cells, used to simplify the grid path + auto visible = [&](ivec2 a, ivec2 b) { + + auto steps = std::max(std::abs(b.x - a.x), std::abs(b.y - a.y)); + auto last = a; + for (int32_t step = 1; step <= steps; step++) { + auto cell = ivec2(glm::round(glm::mix(vec2(a), vec2(b), float(step) / float(steps)))); + if (cell != last && !passable(last, cell)) + return false; + last = cell; + } + return true; + + }; + + json points = json::array(); + float totalLength = 0.0f; + auto maxSegmentCells = size_t(query.value("maxSegment", 30.0f) / cellSize); + + for (size_t leg = 0; leg + 1 < stops.size(); leg++) { + auto start = toCell(stops[leg]), goal = toCell(stops[leg + 1]); + std::vector cost(cells.size(), FLT_MAX); + std::vector previous(cells.size(), -1); + using Node = std::pair; + std::priority_queue, std::greater> open; + cost[index(start)] = 0.0f; + open.push({ 0.0f, int64_t(index(start)) }); + + while (!open.empty()) { + auto current = open.top().second; + open.pop(); + if (current == int64_t(index(goal))) + break; + auto cell = ivec2(int32_t(current % size.x), int32_t(current / size.x)); + for (int32_t j = -1; j <= 1; j++) { + for (int32_t i = -1; i <= 1; i++) { + auto next = cell + ivec2(i, j); + if ((i == 0 && j == 0) || glm::any(glm::lessThan(next, ivec2(0))) || + glm::any(glm::greaterThanEqual(next, size)) || !passable(cell, next)) + continue; + auto distance = glm::length(vec2(i, j)) * cellSize; + auto slope = cells[index(next)].slope / std::max(maxSlope, 1.0f); + auto newCost = cost[current] + distance * (1.0f + slopeWeight * slope * slope); + if (newCost < cost[index(next)]) { + cost[index(next)] = newCost; + previous[index(next)] = current; + auto heuristic = glm::distance(vec2(next), vec2(goal)) * cellSize; + open.push({ newCost + heuristic, int64_t(index(next)) }); + } + } + } + } + + if (previous[index(goal)] < 0 && goal != start) { + writeMap(); + std::vector> sorted; + for (const auto& [name, count] : blockers) + sorted.push_back({ count, name }); + std::sort(sorted.rbegin(), sorted.rend()); + std::string top; + for (size_t i = 0; i < sorted.size() && i < 12; i++) + top += (i ? ", " : "") + sorted[i].second + " " + std::to_string(sorted[i].first); + throw std::runtime_error("route: no walkable route from " + FormatFloat(stops[leg].x, 1) + ", " + + FormatFloat(stops[leg].y, 1) + " to " + FormatFloat(stops[leg + 1].x, 1) + ", " + FormatFloat(stops[leg + 1].y, 1) + + " (" + std::to_string(blockedCount) + " of " + std::to_string(cells.size()) + " cells blocked, most by " + top + ")"); + } + + std::vector path; + for (auto current = int64_t(index(goal)); current >= 0; current = previous[current]) + path.push_back(ivec2(int32_t(current % size.x), int32_t(current / size.x))); + std::reverse(path.begin(), path.end()); + if (map) + for (auto cell : path) + map->SetData(cell.x, cell.y, ivec4(255, 230, 0, 255)); + + std::vector simplified = { path.front() }; + size_t anchor = 0; + for (size_t i = 2; i < path.size(); i++) { + if (!visible(path[anchor], path[i]) || i - anchor > maxSegmentCells) { + anchor = i - 1; + simplified.push_back(path[anchor]); + } + } + if (path.size() > 1) + simplified.push_back(path.back()); + + for (size_t i = leg == 0 ? 0 : 1; i < simplified.size(); i++) { + auto world = toWorld(simplified[i]); + auto height = cells[index(simplified[i])].height; + if (!points.empty()) { + const auto& last = points.back(); + totalLength += glm::distance( + vec3(last[0].get(), last[1].get(), last[2].get()), vec3(world.x, height, world.y)); + } + points.push_back({ world.x, height, world.y }); + } + } + + writeMap(); + return { { "points", points }, { "length", totalLength }, { "cells", cells.size() }, { "blockedCells", blockedCount } }; + + } + + // Each brush changes the terrain and returns what it did, besides its type + using TerrainBrush = json(*)(const Ref& terrain, const TexelGrid& grid, const json& brush); + + static json BrushFlatten(const Ref& terrain, const TexelGrid& grid, const json& brush) { + + // The falloff blends towards the target height with a smooth curve outside of the radius + auto position = ToVec2(brush.at("position")); + auto radius = brush.at("radius").get(); + auto targetHeight = brush.at("height").get(); + auto strength = brush.value("strength", 1.0f); + auto falloff = brush.value("falloff", 0.0f); + auto before = SampleTerrain(terrain, position); + + Tools::TerrainTool::FlattenHeight(terrain, GetBrushSize(grid, radius), strength, position, targetHeight, true, + int32_t(std::ceil(falloff / grid.texelSize))); + return { { "heightBefore", before.height }, { "heightAfter", SampleTerrain(terrain, position).height } }; + + } + + static json BrushRaise(const Ref& terrain, const TexelGrid& grid, const json& brush) { + + // Gaussian mound (or dip with a negative amount) of the given height in meters at its center + auto position = ToVec2(brush.at("position")); + auto radius = brush.at("radius").get(); + auto amount = brush.at("amount").get(); + auto halfSize = (GetBrushSize(grid, radius) - 1) / 2; + + Filter filter; + filter.CalculateGaussianFilter(float(halfSize) / 2.5f, uint32_t(halfSize)); + std::vector> weights; + std::vector> offsets; + filter.Get(&weights, &offsets); + auto centerWeight = weights[halfSize][halfSize]; + + auto before = SampleTerrain(terrain, position); + Tools::TerrainTool::BrushHeight(terrain, &filter, amount / centerWeight, position); + return { { "heightBefore", before.height }, { "heightAfter", SampleTerrain(terrain, position).height } }; + + } + + static json BrushSmooth(const Ref& terrain, const TexelGrid& grid, const json& brush) { + + auto radius = brush.at("radius").get(); + auto size = GetBrushSize(grid, radius); + auto points = brush.contains("points") ? SamplePolyline(brush["points"], radius * 0.5f) : + std::vector { ToVec2(brush.at("position")) }; + auto iterations = brush.value("iterations", 1); + for (int32_t i = 0; i < iterations; i++) + for (auto point : points) + Tools::TerrainTool::SmoothHeight(terrain, size, brush.value("contributing", 2), + brush.value("strength", 0.5f), point); + return { { "stamps", points.size() * iterations } }; + + } + + static json BrushHole(const Ref& terrain, const TexelGrid& grid, const json& brush) { + + auto position = ToVec2(brush.at("position")); + Tools::TerrainTool::BrushHole(terrain, position, GetBrushSize(grid, brush.at("radius").get())); + return json::object(); + + } + + static json BrushFill(const Ref& terrain, const TexelGrid& grid, const json& brush) { + + // Closes holes again, at a position or at each of a list of points + auto size = GetBrushSize(grid, brush.at("radius").get()); + auto points = brush.contains("points") ? std::vector() : std::vector { ToVec2(brush.at("position")) }; + for (const auto& point : brush.value("points", json::array())) + points.push_back(ToVec2(point)); + for (auto point : points) + Tools::TerrainTool::FillHoles(terrain, point, size); + return { { "stamps", points.size() } }; + + } + + // Paints a material at a position or, as a path, along a polyline whose ground can be leveled with a smoothing pass + static json PaintMaterial(const Ref& terrain, const TexelGrid& grid, const json& brush, bool path) { + + auto radius = path ? brush.at("width").get() * 0.5f : brush.at("radius").get(); + auto slot = brush.at("slot").get(); + if (slot < 0 || slot >= int32_t(terrain->storage->materials.size()) || + !terrain->storage->materials[slot].IsValid()) + throw std::runtime_error("Terrain material slot " + std::to_string(slot) + " is empty"); + + auto points = path ? SamplePolyline(brush.at("points"), brush.value("spacing", radius * 0.5f)) : + std::vector { ToVec2(brush.at("position")) }; + auto size = GetBrushSize(grid, radius); + auto smooth = brush.value("smooth", 0.0f); + for (auto point : points) { + if (smooth > 0.0f) + Tools::TerrainTool::SmoothHeight(terrain, size, 3, smooth, point); + Tools::TerrainTool::BrushMaterial(terrain, point, size, slot); + } + return { { "stamps", points.size() } }; + + } + + static const std::map terrainBrushes = { + { "flatten", BrushFlatten }, + { "raise", BrushRaise }, + { "smooth", BrushSmooth }, + { "hole", BrushHole }, + { "fill", BrushFill }, + { "material", [](const Ref& terrain, const TexelGrid& grid, const json& brush) { + return PaintMaterial(terrain, grid, brush, false); } }, + { "path", [](const Ref& terrain, const TexelGrid& grid, const json& brush) { + return PaintMaterial(terrain, grid, brush, true); } } + }; + + json ApplyTerrainBrushes(Scene::Scene& scene, const json& brushes) { + + const auto& terrain = GetCompleteTerrain(scene); + auto grid = GetTexelGrid(terrain); + json log = json::array(); + + for (const auto& brush : brushes) { + auto type = brush.at("type").get(); + auto handler = terrainBrushes.find(type); + if (handler == terrainBrushes.end()) { + std::string known; + for (const auto& [name, _] : terrainBrushes) + known += (known.empty() ? "" : ", ") + name; + throw std::runtime_error("Unknown terrain brush '" + type + "' (" + known + ")"); + } + + json entry = { { "type", type } }; + entry.update(handler->second(terrain, grid, brush)); + log.push_back(entry); + } + + RebuildTerrainBody(scene); + return log; + + } + + void RebuildTerrainBody(Scene::Scene& scene) { + + const auto& terrain = GetCompleteTerrain(scene); + auto heightImage = terrain->GetHeightField(terrain->LoDCount - 1); + + Physics::HeightFieldShapeSettings shapeSettings { + .heightData = heightImage.GetData(), + .translation = terrain->translation, + .scale = vec3(terrain->resolution, terrain->heightScale, terrain->resolution) + }; + auto shape = Physics::ShapesManager::CreateShape(shapeSettings); + + Scene::Entity bodyEntity; + auto rigidBodySubset = scene.GetSubset(); + for (auto entity : rigidBodySubset) { + auto& rigidBody = rigidBodySubset.Get(entity); + if (rigidBody.IsValid() && rigidBody.GetShape()->type == Physics::ShapeType::HeightField) { + bodyEntity = { entity, &scene.entityManager }; + break; + } + } + // Scenes without physics for their terrain have nothing to update + if (!bodyEntity.IsValid()) + return; + + bodyEntity.RemoveComponent(); + bodyEntity.AddComponent(Physics::BodyCreationSettings { .shape = shape }); + + } + + void CopySceneTerrain(Scene::Scene& scene, const std::string& path, bool overwrite) { + + if (!scene.terrain.IsLoaded()) + throw std::runtime_error("The scene has no loaded terrain"); + + auto sourcePath = scene.terrain.GetResource()->path; + auto targetPath = ToAssetPath(path); + if (targetPath == sourcePath) + throw std::runtime_error("terrainCopy: the target is the current terrain " + targetPath); + + auto source = GetAssetDirectory() / sourcePath; + auto target = GetAssetDirectory() / targetPath; + if (fs::exists(target) && !overwrite) + throw std::runtime_error("terrainCopy: " + targetPath + " already exists, set \"overwrite\": true"); + + fs::create_directories(target.parent_path()); + fs::copy_file(source, target, fs::copy_options::overwrite_existing); + + auto copy = ResourceManager::GetOrLoadResourceWithLoader( + targetPath, ResourceOrigin::User, Loader::TerrainLoader::LoadTerrain, false); + copy.WaitForLoad(); + if (!copy.IsLoaded()) + throw std::runtime_error("terrainCopy: couldn't load " + targetPath); + + scene.terrain = copy; + GetCompleteTerrain(scene); + + } + + json CreateSceneTerrain(Scene::Scene& scene, const json& spec) { + + auto path = ToAssetPath(spec.at("path").get()); + auto target = GetAssetDirectory() / path; + if (fs::exists(target) && !spec.value("overwrite", false)) + throw std::runtime_error("terrainCreate: " + path + " already exists, set \"overwrite\": true"); + + auto heightMapPath = ToAssetPath(spec.at("heightMap").get()); + auto heightImage = Loader::ImageLoader::LoadImage(heightMapPath, false, 1); + if (!heightImage || heightImage->width == 0) + throw std::runtime_error("terrainCreate: couldn't load the height map " + heightMapPath); + + Ref> splatImage; + if (spec.contains("splatMap")) { + auto splatMapPath = ToAssetPath(spec["splatMap"].get()); + splatImage = Loader::ImageLoader::LoadImage(splatMapPath, false, 1); + if (!splatImage || splatImage->width == 0) + throw std::runtime_error("terrainCreate: couldn't load the splat map " + splatMapPath); + } + else { + splatImage = CreateRef>(heightImage->width, heightImage->height, 1); + } + + std::vector> materials; + for (const auto& materialPath : spec.at("materials").get>()) { + auto material = ResourceManager::GetOrLoadResourceWithLoader(ToAssetPath(materialPath), + ResourceOrigin::User, Loader::MaterialLoader::LoadMaterial, false); + material.WaitForLoad(); + if (!material.IsLoaded()) + throw std::runtime_error("terrainCreate: couldn't load the material " + materialPath); + materials.push_back(material); + } + if (materials.empty()) + throw std::runtime_error("terrainCreate: at least one material is needed"); + + auto LoDCount = spec.value("LoDCount", 6); + auto patchSize = spec.value("patchSize", 16); + auto resolution = spec.value("resolution", 1.0f); + auto height = spec.at("height").get(); + + auto terrain = Tools::TerrainTool::GenerateTerrain(*heightImage, *splatImage, 1, LoDCount, patchSize, + resolution, height, materials); + if (!terrain) + throw std::runtime_error("terrainCreate: couldn't generate the terrain, the height map has to be square"); + + // Centered on the origin unless placed explicitly + terrain->translation = vec3(-terrain->sideLength * 0.5f, 0.0f, -terrain->sideLength * 0.5f); + if (spec.contains("translation")) + terrain->translation = ToVec3(spec["translation"]); + terrain->filename = fs::path(path).stem().string(); + if (spec.contains("displacementDistance")) + terrain->SetDisplacementDistance(spec["displacementDistance"].get()); + if (spec.contains("tessellation")) { + const auto& tessellation = spec["tessellation"]; + terrain->SetTessellationFunction(tessellation.value("factor", terrain->tessellationFactor), + tessellation.value("slope", terrain->tessellationSlope), tessellation.value("shift", terrain->tessellationShift), + tessellation.value("maxLevel", terrain->maxTessellationLevel)); + } + // Generated cells have no file to stream them from until the terrain is saved + terrain->storage->inEditing = true; + Tools::TerrainTool::BakeTerrain(terrain); + + // Streaming would read the file of a loaded terrain while it is overwritten + auto existing = ResourceManager::GetResource(path); + if (existing.IsValid()) + throw std::runtime_error("terrainCreate: " + path + " is already loaded, use another path"); + + fs::create_directories(target.parent_path()); + Loader::TerrainLoader::SaveTerrain(terrain, path); + scene.terrain = ResourceManager::AddResource(path, terrain); + + // A height field body like the editor creates it, replacing the body of a previous terrain + auto heightField = terrain->GetHeightField(LoDCount - 1); + Physics::HeightFieldShapeSettings shapeSettings { + .heightData = heightField.GetData(), + .translation = terrain->translation, + .scale = vec3(terrain->resolution, terrain->heightScale, terrain->resolution) + }; + auto shape = Physics::ShapesManager::CreateShape(shapeSettings); + + Scene::Entity bodyEntity; + auto rigidBodySubset = scene.GetSubset(); + for (auto entity : rigidBodySubset) { + auto& rigidBody = rigidBodySubset.Get(entity); + if (rigidBody.IsValid() && rigidBody.GetShape()->type == Physics::ShapeType::HeightField) { + bodyEntity = { entity, &scene.entityManager }; + break; + } + } + if (bodyEntity.IsValid()) { + bodyEntity.RemoveComponent(); + } + else { + bodyEntity = scene.CreateEntity(); + bodyEntity.AddComponent(terrain->filename); + // Bodies only enter the physics world together with a transform + bodyEntity.AddComponent(mat4(1.0f), true); + bodyEntity.SetParent(scene.GetRootEntity()); + } + bodyEntity.AddComponent(Physics::BodyCreationSettings { .shape = shape }); + + return { { "terrain", path }, { "sideLength", terrain->sideLength }, { "height", height }, + { "translation", FromVec3(terrain->translation) }, { "materials", materials.size() }, + { "body", GetEntityLabel(bodyEntity) } }; + + } + + json BakeShoreLine(Scene::Scene& scene, const json& spec) { + + const auto& terrain = GetCompleteTerrain(scene); + const auto& terrainPath = scene.terrain.GetResource()->path; + + auto oceanHeight = spec.value("oceanHeight", scene.ocean ? scene.ocean->translation.y : 0.0f); + auto resolution = spec.value("resolution", 2048); + auto path = (fs::path(terrainPath).parent_path() / (fs::path(terrainPath).stem().string() + "_shoreline.png")) + .generic_string(); + + // The map compares the water level with the terrain heights, which start at the terrain translation + auto image = Tools::TerrainTool::GenerateTerrainOceanMap(terrain, terrainPath, oceanHeight - terrain->translation.y, resolution); + // Calm water (harbor basins): the shore waves fade out over "falloff" m towards the inside of each area, the + // shore distance reads as open water there + auto& data = image->GetData(); + for (const auto& calm : spec.value("calm", json::array())) { + auto center = vec2(calm["center"][0].get(), calm["center"][1].get()); + auto radius = calm.value("radius", 50.0f); + auto falloff = calm.value("falloff", 20.0f); + + // Only the pixels within the radius + auto origin = vec2(terrain->translation.x, terrain->translation.z); + auto size = ivec2(image->width, image->height); + auto pixelsPerUnit = vec2(size) / terrain->sideLength; + auto minPixel = glm::clamp(ivec2(glm::floor((center - radius - origin) * pixelsPerUnit)), ivec2(0), size); + auto maxPixel = glm::clamp(ivec2(glm::ceil((center + radius - origin) * pixelsPerUnit)), ivec2(0), size); + for (int32_t y = minPixel.y; y < maxPixel.y; y++) { + for (int32_t x = minPixel.x; x < maxPixel.x; x++) { + auto world = origin + (vec2(x, y) + 0.5f) / pixelsPerUnit; + auto calmness = Helper::Math::Saturate((radius - glm::distance(world, center)) / falloff); + if (calmness <= 0.0f) + continue; + auto& distance = data[(y * image->width + x) * image->channels + 1]; + distance = uint8_t(glm::mix(float(distance), 255.0f, calmness)); + } + } + } + Loader::ImageLoader::SaveImage(image, path); + + terrain->shoreLinePath = path; + terrain->shoreLine = Texture::Texture2D(resolution, resolution, VK_FORMAT_R8G8B8A8_UNORM, + Texture::Wrapping::ClampToEdge, Texture::Filtering::Linear); + terrain->shoreLine.SetData(image->GetData()); + + return { { "shoreLine", path }, { "oceanHeight", oceanHeight }, { "resolution", resolution } }; + + } + + void SaveSceneTerrain(Scene::Scene& scene) { + + const auto& terrain = GetCompleteTerrain(scene); + const auto& path = scene.terrain.GetResource()->path; + + Tools::TerrainTool::LoadMissingCells(terrain, path); + Tools::TerrainTool::BakeTerrain(terrain); + Loader::TerrainLoader::SaveTerrain(terrain, path); + + } + +} diff --git a/src/bridge/TerrainTools.h b/src/bridge/TerrainTools.h new file mode 100644 index 000000000..1992fceba --- /dev/null +++ b/src/bridge/TerrainTools.h @@ -0,0 +1,58 @@ +#pragma once + +#include "Image.h" +#include "SceneTools.h" + +#include "terrain/Terrain.h" + +namespace Atlas::Bridge { + + struct TerrainSample { + + bool valid = false; + bool hole = false; + float height = 0.0f; + vec3 normal = vec3(0.0f, 1.0f, 0.0f); + float slopeDegrees = 0.0f; + // Material slot of the nearest texel + int32_t material = -1; + + }; + + // Cells are streamed around the camera. Measurements and edits need all of them, and edited cells + // must not be unloaded again, so the storage stays in editing mode + const Ref& GetCompleteTerrain(Scene::Scene& scene); + + // Samples the highest LoD storage cells at a world space x/z position + TerrainSample SampleTerrain(const Ref& terrain, vec2 position); + + // Extents, parameters, material slots and connected hole regions of the highest LoD + json DescribeTerrain(const Ref& terrain); + + // Top down map: material colors with hill shading and contour lines, holes, mesh entity footprints, + // a labeled grid and optional markers. Region defaults to the whole terrain + Ref RenderTerrainMap(Scene::Scene& scene, const json& spec); + + // Walkable route between two points (and optional via points): A* over a ground grid, see the "route" query + json FindRoute(Scene::Scene& scene, const json& query, const fs::path& outputDirectory = {}); + + // Brushes of the "terrain" edit operation, see README.md. Returns a log entry per brush + json ApplyTerrainBrushes(Scene::Scene& scene, const json& brushes); + + // Recreates the height field body of the terrain after its heights changed (like the editor terrain panel) + void RebuildTerrainBody(Scene::Scene& scene); + + // Copies the terrain file of the scene to a new path and loads the copy as the scene terrain + void CopySceneTerrain(Scene::Scene& scene, const std::string& path, bool overwrite); + + // Generates a terrain from a height map (16 bit) and an optional splat map image, writes it to its file and + // makes it the scene terrain with a height field body, see the "terrainCreate" edit operation in README.md + json CreateSceneTerrain(Scene::Scene& scene, const json& spec); + + // Bakes the shore line map of the ocean waves next to the terrain file, see the "shoreLine" edit operation in README.md + json BakeShoreLine(Scene::Scene& scene, const json& spec); + + // Bakes the lower LoDs and writes the terrain back to its file + void SaveSceneTerrain(Scene::Scene& scene); + +} diff --git a/src/bridge/Timeline.cpp b/src/bridge/Timeline.cpp new file mode 100644 index 000000000..239ee9c62 --- /dev/null +++ b/src/bridge/Timeline.cpp @@ -0,0 +1,313 @@ +#include "Timeline.h" + +#include "events/EventManager.h" + +#include + +#include + +namespace Atlas::Bridge { + + // Accumulated fixed time steps don't exactly hit the times of the timeline + static constexpr float timeTolerance = 1e-4f; + + void Timeline::Reset(const std::vector& jobEvents) { + + time = 0.0f; + events.clear(); + nextEvent = 0; + ended = false; + triggers.clear(); + pendingReleases.clear(); + DetachController(); + + auto usesController = [](const EventSpec& event) { + auto input = std::get_if(&event.action); + return input && (input->device == InputEvent::Device::Button || input->device == InputEvent::Device::Axis); + }; + if (std::any_of(jobEvents.begin(), jobEvents.end(), usesController)) + AttachController(); + + } + + size_t Timeline::Start(std::vector timedEvents, float duration) { + + time = 0.0f; + nextEvent = 0; + ended = false; + + events.clear(); + triggers.clear(); + for (auto& event : timedEvents) { + if (event.when) + triggers.push_back({ .event = event }); + else + events.push_back(event); + } + + std::stable_sort(events.begin(), events.end(), [](const EventSpec& a, const EventSpec& b) { + + return a.time < b.time; + + }); + + auto beyond = std::remove_if(events.begin(), events.end(), [&](const EventSpec& event) { + + return event.time > duration + timeTolerance; + + }); + auto dropped = size_t(std::distance(beyond, events.end())); + events.erase(beyond, events.end()); + return dropped; + + } + + bool Timeline::IsDue(float eventTime) const { + + return eventTime <= time + timeTolerance; + + } + + void Timeline::Update(const std::function& isMet, const std::function& print) { + + for (auto it = pendingReleases.begin(); it != pendingReleases.end();) { + if (IsDue(it->first)) { + SetInput(it->second, false); + it = pendingReleases.erase(it); + } + else { + ++it; + } + } + + std::vector due; + for (auto& trigger : triggers) { + const auto& when = *trigger.event.when; + if (!trigger.metTime && IsDue(trigger.event.time)) { + if (when.contains("log") ? trigger.logMatched : isMet(when)) { + trigger.metTime = time; + print(FormatTime(time) + " condition met: " + when.dump()); + } + } + + if (trigger.metTime && !trigger.fired && IsDue(*trigger.metTime + trigger.event.delay)) { + trigger.fired = true; + auto event = trigger.event; + event.time = time; + due.push_back(event); + } + } + + // Due events run in this frame before the timed events of the frame + events.insert(events.begin() + nextEvent, due.begin(), due.end()); + + } + + void Timeline::MatchLog(const std::string& message) { + + for (auto& trigger : triggers) { + if (trigger.logMatched || !IsDue(trigger.event.time) || !trigger.event.when->contains("log")) + continue; + auto pattern = (*trigger.event.when)["log"].get(); + if (pattern.find_first_of("*?") == std::string::npos) + pattern = "*" + pattern + "*"; + trigger.logMatched = Helper::String::MatchWildcard(pattern, message); + } + + } + + const EventSpec* Timeline::GetDueEvent() const { + + if (nextEvent >= events.size() || !IsDue(events[nextEvent].time)) + return nullptr; + + return &events[nextEvent]; + + } + + void Timeline::PopEvent() { + + nextEvent = std::min(nextEvent + 1, events.size()); + + } + + void Timeline::End() { + + ended = true; + nextEvent = events.size(); + + } + + bool Timeline::IsEnded() const { + + return ended; + + } + + bool Timeline::IsFinished(float duration) const { + + return (ended || IsDue(duration)) && nextEvent >= events.size(); + + } + + void Timeline::Fire(const InputEvent& input) { + + if (input.device == InputEvent::Device::Axis || (input.device == InputEvent::Device::Mouse && + (input.action == "move" || input.action == "wheel"))) { + SetInput(input, true); + return; + } + + if (input.action == "down" || input.action == "press") + SetInput(input, true); + if (input.action == "up") + SetInput(input, false); + if (input.action == "press") + pendingReleases.emplace_back(time + input.duration, input); + + } + + std::vector Timeline::GetMissedEvents() const { + + std::vector missed; + for (const auto& trigger : triggers) + if (!trigger.fired) + missed.push_back(trigger.event); + + return missed; + + } + + json Timeline::GetTriggerReport() const { + + if (triggers.empty()) + return json(); + + json report = json::array(); + for (const auto& trigger : triggers) + report.push_back({ { "event", trigger.event.data }, { "fired", trigger.fired }, + { "conditionMetAt", trigger.metTime ? json(*trigger.metTime) : json() } }); + + return report; + + } + + size_t Timeline::GetTimedEventCount() const { + + return events.size(); + + } + + size_t Timeline::GetTriggerCount() const { + + return triggers.size(); + + } + + void Timeline::SetInput(const InputEvent& input, bool down) { + + if (input.device == InputEvent::Device::Key) { + auto keyCode = SDL_GetKeyFromName(input.name.c_str()); + if (keyCode == SDLK_UNKNOWN) + throw std::runtime_error("Unknown key '" + input.name + "', use SDL key names like E, Space, Left Shift, Up"); + + SDL_KeyboardEvent event = {}; + event.type = down ? SDL_EVENT_KEY_DOWN : SDL_EVENT_KEY_UP; + event.down = down; + event.repeat = false; + event.key = keyCode; + event.scancode = SDL_GetScancodeFromKey(keyCode, nullptr); + + Events::EventManager::KeyboardEventDelegate.Fire(Events::KeyboardEvent(event)); + return; + } + + if (input.device == InputEvent::Device::Mouse) { + // Pushed into the SDL queue, the engine dispatches them to the window and the interface like real input + SDL_Event event = {}; + if (input.position && down) { + auto delta = *input.position - mousePosition; + mousePosition = *input.position; + event.type = SDL_EVENT_MOUSE_MOTION; + event.motion.windowID = windowId; + event.motion.x = mousePosition.x; + event.motion.y = mousePosition.y; + event.motion.xrel = delta.x; + event.motion.yrel = delta.y; + SDL_PushEvent(&event); + } + if (input.action == "move") + return; + + event = {}; + if (input.action == "wheel") { + event.type = SDL_EVENT_MOUSE_WHEEL; + event.wheel.windowID = windowId; + event.wheel.y = input.value; + event.wheel.integer_y = int32_t(input.value); + event.wheel.direction = SDL_MOUSEWHEEL_NORMAL; + event.wheel.mouse_x = mousePosition.x; + event.wheel.mouse_y = mousePosition.y; + SDL_PushEvent(&event); + return; + } + + auto button = input.name == "right" ? SDL_BUTTON_RIGHT : input.name == "middle" ? SDL_BUTTON_MIDDLE : SDL_BUTTON_LEFT; + event.type = down ? SDL_EVENT_MOUSE_BUTTON_DOWN : SDL_EVENT_MOUSE_BUTTON_UP; + event.button.windowID = windowId; + event.button.button = Uint8(button); + event.button.down = down; + event.button.clicks = 1; + event.button.x = mousePosition.x; + event.button.y = mousePosition.y; + SDL_PushEvent(&event); + return; + } + + AttachController(); + if (input.device == InputEvent::Device::Button) { + auto index = SDL_GetGamepadButtonFromString(input.name.c_str()); + if (index == SDL_GAMEPAD_BUTTON_INVALID) + throw std::runtime_error("Unknown controller button '" + input.name + "', use SDL names like a, b, x, y, leftshoulder, dpup, start"); + SDL_SetJoystickVirtualButton(controller, index, down); + return; + } + + auto index = SDL_GetGamepadAxisFromString(input.name.c_str()); + if (index == SDL_GAMEPAD_AXIS_INVALID) + throw std::runtime_error("Unknown controller axis '" + input.name + "', use leftx, lefty, rightx, righty, lefttrigger or righttrigger"); + SDL_SetJoystickVirtualAxis(controller, index, Sint16(glm::clamp(input.value, -1.0f, 1.0f) * 32767.0f)); + + } + + void Timeline::AttachController() { + + if (controller) + return; + + // SDL reports the virtual controller like a connected one, the engine receives its events + SDL_VirtualJoystickDesc desc; + SDL_INIT_INTERFACE(&desc); + desc.type = SDL_JOYSTICK_TYPE_GAMEPAD; + desc.naxes = SDL_GAMEPAD_AXIS_COUNT; + desc.nbuttons = SDL_GAMEPAD_BUTTON_COUNT; + desc.name = "Capture controller"; + controller = SDL_OpenJoystick(SDL_AttachVirtualJoystick(&desc)); + if (!controller) + throw std::runtime_error("Couldn't attach a virtual controller: " + std::string(SDL_GetError())); + + } + + void Timeline::DetachController() { + + if (!controller) + return; + + auto instance = SDL_GetJoystickID(controller); + SDL_CloseJoystick(controller); + controller = nullptr; + SDL_DetachVirtualJoystick(instance); + + } + +} diff --git a/src/bridge/Timeline.h b/src/bridge/Timeline.h new file mode 100644 index 000000000..f6aa96098 --- /dev/null +++ b/src/bridge/Timeline.h @@ -0,0 +1,94 @@ +#pragma once + +#include "Job.h" + +#include "scene/Scene.h" + +#include + +#include + +namespace Atlas::Bridge { + + // The events of a playing job: timed events in the order of their time, conditional events that wait + // for their condition and the input the events simulate + class Timeline { + + public: + struct Trigger { + + EventSpec event; + bool logMatched = false; + std::optional metTime; + bool fired = false; + + }; + + // Prepares the timeline of a job. A virtual controller is attached right away, SDL reports it a few + // frames later and earlier events would be lost + void Reset(const std::vector& jobEvents); + + // Starts playing at time 0, events with a condition become triggers. Returns the number of + // events after the duration, which are dropped + size_t Start(std::vector timedEvents, float duration); + + // Whether a time is reached, tolerates the rounding of the fixed time steps + bool IsDue(float time) const; + + // Releases the keys and buttons whose press is over and queues the events whose condition is met. Log + // conditions are matched by MatchLog, isMet evaluates the others + void Update(const std::function& isMet, const std::function& print); + + // Log conditions: a text without wildcards matches when the message contains it + void MatchLog(const std::string& message); + + // The next event that is due in this frame, nullptr if there is none + const EventSpec* GetDueEvent() const; + + void PopEvent(); + + // Skips the remaining timed events, conditional events that didn't happen yet still count as missed + void End(); + + bool IsEnded() const; + + // All events ran and the duration (or an end event) is reached + bool IsFinished(float duration) const; + + // Keys and buttons go down, up or are pressed and released after the duration, axes get their value + void Fire(const InputEvent& input); + + // Conditional events that never fired + std::vector GetMissedEvents() const; + + // When the conditions were met and whether their events fired, null without conditional events + json GetTriggerReport() const; + + size_t GetTimedEventCount() const; + + size_t GetTriggerCount() const; + + float time = 0.0f; + // Window that receives the mouse events + uint32_t windowId = 0; + + private: + void SetInput(const InputEvent& input, bool down); + + void AttachController(); + + void DetachController(); + + std::vector events; + size_t nextEvent = 0; + bool ended = false; + std::vector triggers; + + // Pressed keys and buttons with the time they are released + std::vector> pendingReleases; + SDL_Joystick* controller = nullptr; + vec2 mousePosition = vec2(0.0f); + + }; + +} diff --git a/src/bridge/Tools.cpp b/src/bridge/Tools.cpp new file mode 100644 index 000000000..fd6bfb742 --- /dev/null +++ b/src/bridge/Tools.cpp @@ -0,0 +1,320 @@ +#include "Tools.h" +#include "Mcp.h" +#include "Bench.h" +#include "Check.h" +#include "Client.h" +#include "Image.h" +#include "Inspect.h" +#include "Processes.h" + +#include "InstanceRegistry.h" + +#include "Log.h" +#include "loader/AssetLoader.h" + +#include +#include +#include + +namespace Atlas::Bridge { + + static bool IsImage(const fs::path& path) { + + auto extension = path.extension().string(); + return extension == ".png" || extension == ".jpg" || extension == ".jpeg"; + + } + + // A file, a directory (its images) or a pattern with * and ? in the file name, sorted by name + static std::vector ExpandImages(const std::string& item) { + + auto path = ResolveUserPath(item); + std::error_code error; + std::vector paths; + if (fs::is_directory(path, error)) { + for (const auto& entry : fs::directory_iterator(path, error)) + if (entry.is_regular_file() && IsImage(entry.path())) + paths.push_back(entry.path()); + } + else if (path.filename().string().find_first_of("*?") != std::string::npos) { + auto pattern = path.filename().string(); + for (const auto& entry : fs::directory_iterator(path.parent_path(), error)) + if (entry.is_regular_file() && Helper::String::MatchWildcard(pattern, entry.path().filename().string())) + paths.push_back(entry.path()); + } + else { + paths.push_back(path); + } + std::sort(paths.begin(), paths.end()); + return paths; + + } + + // compose [--title ] [--columns ] [--width ] ... + static int32_t Compose(const std::vector& args) { + + if (args.size() < 4) + throw std::runtime_error("compose expects an output file and images"); + + auto output = ResolveUserPath(args[2]); + std::string title; + int32_t columns = 0; + int32_t width = 1536; + std::vector> images; + std::vector labels; + + for (size_t i = 3; i < args.size(); i++) { + if (args[i] == "--title" && i + 1 < args.size()) { + title = args[++i]; + continue; + } + if (args[i] == "--columns" && i + 1 < args.size()) { + columns = std::stoi(args[++i]); + continue; + } + if (args[i] == "--width" && i + 1 < args.size()) { + width = std::stoi(args[++i]); + continue; + } + + auto separator = args[i].find('='); + auto label = separator == std::string::npos ? std::string() : args[i].substr(0, separator); + for (const auto& path : ExpandImages(separator == std::string::npos ? args[i] : args[i].substr(separator + 1))) { + auto image = LoadImageFile(path); + if (!image) { + Print("Couldn't load " + path.string()); + return 2; + } + images.push_back(image); + labels.push_back(label.empty() ? path.stem().string() : label); + } + } + if (images.empty()) { + Print("No images to compose"); + return 2; + } + + auto columnCount = columns > 0 ? columns : int32_t(std::ceil(std::sqrt(float(images.size())))); + columnCount = std::min(columnCount, int32_t(images.size())); + auto cellWidth = std::max((width - 4 * (columnCount + 1)) / columnCount, 32); + auto sheet = ComposeSheet(images, labels, columnCount, title, cellWidth); + if (!WriteImage(sheet, output)) + return 2; + Print("Composed " + std::to_string(images.size()) + " images into " + output.string() + " (" + std::to_string(sheet->width) + "x" + + std::to_string(sheet->height) + ")"); + return 0; + + } + + // diff [--threshold <0-255>] [--out ]: two images or two directories with images of the same names + static int32_t Diff(const std::vector& args) { + + if (args.size() < 4) + throw std::runtime_error("diff expects two images or two directories"); + + int32_t threshold = 8; + fs::path output; + for (size_t i = 4; i < args.size(); i++) { + if (args[i] == "--threshold" && i + 1 < args.size()) + threshold = std::stoi(args[++i]); + else if (args[i] == "--out" && i + 1 < args.size()) + output = ResolveUserPath(args[++i]); + else + throw std::runtime_error("Unknown diff option '" + args[i] + "' (--threshold <0-255>, --out )"); + } + + auto a = ResolveUserPath(args[2]), b = ResolveUserPath(args[3]); + std::vector>> pairs; + std::vector unmatched; + std::error_code error; + if (fs::is_directory(a, error) && fs::is_directory(b, error)) { + std::map inB; + for (const auto& entry : fs::recursive_directory_iterator(b, error)) + if (entry.is_regular_file() && IsImage(entry.path())) + inB[fs::relative(entry.path(), b).generic_string()] = entry.path(); + for (const auto& entry : fs::recursive_directory_iterator(a, error)) { + if (!entry.is_regular_file() || !IsImage(entry.path())) + continue; + auto relative = fs::relative(entry.path(), a).generic_string(); + if (auto it = inB.find(relative); it != inB.end()) { + pairs.push_back({ relative, { entry.path(), it->second } }); + inB.erase(it); + } + else { + unmatched.push_back(relative + ": only in the first"); + } + } + for (const auto& [relative, path] : inB) + unmatched.push_back(relative + ": only in the second"); + } + else { + pairs.push_back({ a.filename().string(), { a, b } }); + } + + struct Result { + + std::string name; + ImageDifference difference; + Ref a, b, heat; + + }; + std::vector results; + for (const auto& [name, paths] : pairs) { + auto imageA = LoadImageFile(paths.first), imageB = LoadImageFile(paths.second); + if (!imageA || !imageB) { + unmatched.push_back(name + ": couldn't be read"); + continue; + } + Result result = { name, {}, imageA, imageB, nullptr }; + result.difference = CompareImages(*imageA, *imageB, threshold, output.empty() ? nullptr : &result.heat); + results.push_back(result); + } + std::sort(results.begin(), results.end(), [](const Result& x, const Result& y) { return x.difference.percent > y.difference.percent; }); + + size_t differing = 0; + for (const auto& result : results) { + const auto& difference = result.difference; + if (difference.sizeMismatch) { + differing++; + Print(" " + result.name + ": sizes differ (" + std::to_string(result.a->width) + "x" + std::to_string(result.a->height) + + ", " + std::to_string(result.b->width) + "x" + std::to_string(result.b->height) + ")"); + continue; + } + if (difference.percent > 0.0f) + differing++; + Print(" " + result.name + ": " + FormatFloat(difference.percent, 2) + "% of the pixels differ by more than " + + std::to_string(threshold) + ", mean " + FormatFloat(difference.mean, 2) + ", max " + FormatFloat(difference.max, 0)); + } + for (const auto& line : unmatched) + Print(" " + line); + Print(std::to_string(results.size()) + " images compared, " + std::to_string(differing) + " differ" + + (unmatched.empty() ? "" : ", " + std::to_string(unmatched.size()) + " without a partner")); + + if (!output.empty()) { + std::vector> images; + std::vector labels; + for (const auto& result : results) { + if (result.difference.percent <= 0.0f || result.difference.sizeMismatch || images.size() >= 24) + continue; + images.insert(images.end(), { result.a, result.b, result.heat }); + labels.insert(labels.end(), { result.name, "second", FormatFloat(result.difference.percent, 2) + "% differ" }); + } + if (!images.empty()) { + auto sheet = ComposeSheet(images, labels, 3, "", 504); + if (WriteImage(sheet, output)) + Print("Differences in " + output.string()); + } + } + + return differing > 0 || !unmatched.empty() ? 1 : 0; + + } + + static int32_t Check(const std::vector& args) { + + if (args.size() < 3) + throw std::runtime_error("check expects job files"); + + bool failed = false; + for (size_t i = 2; i < args.size(); i++) { + auto path = ResolveUserPath(args[i]); + auto issues = CheckJobFile(path, {}); + auto errors = std::count_if(issues.begin(), issues.end(), [](const std::string& issue) { return issue.starts_with("ERROR"); }); + failed |= errors > 0; + Print(path.filename().string() + ": " + (errors > 0 ? std::to_string(errors) + " errors" : std::string("ok"))); + for (const auto& issue : issues) + Print(" " + issue); + } + return failed ? 2 : 0; + + } + + static std::string GetToolUsage() { + + return R"(Commands without the GPU: + run [job options] Run a job on the server of this executable and print its summary + eval [--play ] [--scene ] Evaluate Lua in the loaded scene, after playing it for a while + wait | status | cancel | stop The server: wait for a command, show what runs, cancel the job, stop it + --server --detach --timeout --no-wait-gpu --streaming --validation + check ... Find mistakes in jobs without loading their scenes + kill End a process and the processes it started + compose [--title t] [--columns n] [--width px] ... + diff [--threshold 0-255] [--out sheet.jpg] Compare two images or directories of images + inspect [--filter pattern] [--assembly pattern] [--limit n] [--code] + bench Compare builds or shader directories in interleaved rounds + mcp Model Context Protocol server on stdin/stdout for agents +)"; + + } + + std::optional RunCommandLineTool(const std::vector& args, const std::string& assetDirectory) { + + // Jobs and scenes are found relative to the data directory of the engine + Loader::AssetLoader::SetAssetDirectory(assetDirectory); + // The engine log goes into log.txt and its errors are printed, --verbose prints all of it + Log::printToConsole = std::find(args.begin(), args.end(), "--verbose") != args.end(); + + if (args.size() < 2) + return std::nullopt; + + const auto& command = args[1]; + try { + if (command == "mcp") + return RunMcpServer(args); + if (auto exitCode = RunClient(args)) + return exitCode; + if (command == "check") + return Check(args); + if (command == "kill") { + if (args.size() < 3) + throw std::runtime_error("kill expects a process id or captures"); + return Kill(args[2]); + } + if (command == "compose" || command == "--compose") + return Compose(args); + if (command == "diff") + return Diff(args); + if (command == "inspect") + return Inspect(args); + if (command == "bench") + return RunBench(args); + if (command == "help" || command == "--help" || command == "-h") { + Print(GetUsage() + "\n" + GetToolUsage()); + return 0; + } + } + catch (const std::exception& e) { + Print(std::string("ERROR: ") + e.what()); + return 2; + } + + // A direct run of a job is checked before the engine starts, servers and pipelines check their jobs themselves + auto isRendering = std::any_of(args.begin(), args.end(), [](const std::string& arg) { return arg == "--serve" || arg == "--pipeline"; }); + auto jobFile = std::find_if(args.begin() + 1, args.end(), [](const std::string& arg) { return !arg.starts_with("--") && arg.ends_with(".json"); }); + if (!isRendering && jobFile != args.end()) { + std::vector issues; + try { + issues = CheckJob(ParseCommandLine(args)); + } + catch (const std::exception& e) { + std::string message = e.what(); + Print(message.starts_with("Usage:") ? message + "\n" + GetToolUsage() : "ERROR: " + message); + return message.starts_with("Usage:") ? 0 : 2; + } + for (const auto& issue : issues) + Print(issue); + if (!issues.empty() && issues.front().starts_with("ERROR")) + return 2; + } + + // Runs wait for the GPU in the queue of InstanceRegistry before each scene they load, see App::LoadScene + if (std::find(args.begin(), args.end(), "--no-wait-gpu") != args.end() && std::find(args.begin(), args.end(), "--serve") == args.end()) { + for (const auto& instance : InstanceRegistry::GetBusyInstances()) + Print("Note: " + instance.executable + " (process " + std::to_string(instance.pid) + ") is busy: " + instance.activity); + } + + return std::nullopt; + + } + +} diff --git a/src/bridge/Tools.h b/src/bridge/Tools.h new file mode 100644 index 000000000..a248f0a45 --- /dev/null +++ b/src/bridge/Tools.h @@ -0,0 +1,14 @@ +#pragma once + +#include "Common.h" + +#include + +namespace Atlas::Bridge { + + // The modes of the executable that need neither a window nor the GPU, they run before the engine starts: the client of + // a server, check, kill, compose, diff, inspect and bench. A direct run of a job is checked here before the engine + // starts, returns no exit code for every mode that renders + std::optional RunCommandLineTool(const std::vector& args, const std::string& assetDirectory); + +} diff --git a/src/bridge/WindowShot.cpp b/src/bridge/WindowShot.cpp new file mode 100644 index 000000000..9f1c44715 --- /dev/null +++ b/src/bridge/WindowShot.cpp @@ -0,0 +1,89 @@ +#include "WindowShot.h" + +#include "graphics/GraphicsDevice.h" +#include "loader/ImageLoader.h" +#include "common/Image.h" + +namespace Atlas::Bridge { + + bool WindowShot::Copy(const std::string& path) { + + auto device = Graphics::GraphicsDevice::DefaultDevice; + auto swapChain = device->swapChain; + auto format = swapChain->surfaceFormat.format; + bgra = format == VK_FORMAT_B8G8R8A8_UNORM || format == VK_FORMAT_B8G8R8A8_SRGB; + auto rgba = format == VK_FORMAT_R8G8B8A8_UNORM || format == VK_FORMAT_R8G8B8A8_SRGB; + if (!swapChain->isComplete || !swapChain->readable || !(bgra || rgba)) + return false; + + extent = swapChain->extent; + Graphics::BufferDesc desc = { + .usageFlags = VK_BUFFER_USAGE_TRANSFER_DST_BIT, + .domain = Graphics::BufferDomain::Host, + .hostAccess = Graphics::BufferHostAccess::Random, + .size = size_t(extent.width) * size_t(extent.height) * 4, + }; + buffer = device->CreateBuffer(desc); + this->path = path; + + auto image = swapChain->images[swapChain->aquiredImageIndex]; + VkImageMemoryBarrier barrier = {}; + barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; + barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + barrier.image = image; + barrier.subresourceRange = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 }; + barrier.oldLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; + barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; + barrier.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; + barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; + + auto commandList = device->GetCommandList(); + commandList->BeginCommands(); + vkCmdPipelineBarrier(commandList->commandBuffer, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, + VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &barrier); + VkBufferImageCopy copy = {}; + copy.imageSubresource = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1 }; + copy.imageExtent = { extent.width, extent.height, 1 }; + vkCmdCopyImageToBuffer(commandList->commandBuffer, image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, buffer->buffer, 1, ©); + barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; + barrier.newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; + barrier.srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT; + barrier.dstAccessMask = 0; + vkCmdPipelineBarrier(commandList->commandBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, + VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, 0, nullptr, 0, nullptr, 1, &barrier); + commandList->EndCommands(); + device->SubmitCommandList(commandList); + + return true; + + } + + bool WindowShot::Save() { + + if (!buffer) + return false; + + // Waiting for the previous submission isn't enough, parts of the buffer still held the last picture + Graphics::GraphicsDevice::DefaultDevice->WaitForIdle(); + + auto width = int32_t(extent.width), height = int32_t(extent.height); + auto image = CreateRef>(width, height, 4); + auto& pixels = image->GetData(); + auto source = static_cast(buffer->Map()); + for (size_t i = 0; i < pixels.size(); i += 4) { + pixels[i] = source[i + (bgra ? 2 : 0)]; + pixels[i + 1] = source[i + 1]; + pixels[i + 2] = source[i + (bgra ? 0 : 2)]; + pixels[i + 3] = 255; + } + buffer->Unmap(); + image->fileFormat = Common::ImageFormat::PNG; + Loader::ImageLoader::SaveImage(image, path); + buffer.reset(); + + return true; + + } + +} diff --git a/src/bridge/WindowShot.h b/src/bridge/WindowShot.h new file mode 100644 index 000000000..43828c3b2 --- /dev/null +++ b/src/bridge/WindowShot.h @@ -0,0 +1,31 @@ +#pragma once + +#include "Common.h" + +#include "graphics/Buffer.h" + +#include + +namespace Atlas::Bridge { + + // The window as the user sees it, the interface included: Copy() after the interface was rendered copies the swap + // chain image into a buffer with the commands of the frame, Save() writes it once the frame is done. Unlike a + // picture of the window taken from outside it works while the window is covered + class WindowShot { + + public: + // False if the swap chain can't be read + bool Copy(const std::string& path); + + // False while no copy is waiting, call it in a later frame + bool Save(); + + private: + Ref buffer; + VkExtent2D extent = {}; + bool bgra = false; + std::string path; + + }; + +} diff --git a/src/demo/App.cpp b/src/demo/App.cpp index afd785b17..a127f1542 100644 --- a/src/demo/App.cpp +++ b/src/demo/App.cpp @@ -18,6 +18,12 @@ using namespace Atlas::Scene::Components; using namespace Atlas::Scene::Prefabs; using namespace Atlas::ImguiExtension; +using Atlas::vec2; +using Atlas::vec3; +using Atlas::vec4; +using Atlas::ivec3; +using Atlas::mat4; + void App::LoadContent() { renderTarget = Atlas::CreateRef(1920, 1080); @@ -31,11 +37,11 @@ void App::LoadContent() { font = Atlas::CreateRef("font/roboto.ttf", 22.0f, 5); - scene = Atlas::CreateRef("demoScene", glm::vec3(-2048.0f), glm::vec3(2048.0f)); + scene = Atlas::CreateRef("demoScene", vec3(-2048.0f), vec3(2048.0f)); cameraEntity = scene->CreateEntity(); auto& camera = cameraEntity.AddComponent(47.0f, 2.0f, 1.0f, 400.0f, - glm::vec3(30.0f, 25.0f, 0.0f), glm::vec2(-3.14f / 2.0f, 0.0f)); + vec3(30.0f, 25.0f, 0.0f), vec2(-3.14f / 2.0f, 0.0f)); mouseHandler = Atlas::Input::MouseHandler(1.5f, 8.0f); keyboardHandler = Atlas::Input::KeyboardHandler(7.0f, 5.0f); @@ -69,14 +75,12 @@ void App::LoadContent() { directionalLightEntity = scene->CreateEntity(); auto& directionalLight = directionalLightEntity.AddComponent(LightType::DirectionalLight); - directionalLight.properties.directional.direction = glm::vec3(0.0f, -1.0f, 1.0f); - directionalLight.color = glm::vec3(255, 236, 209) / 255.0f; - directionalLight.AddDirectionalShadow(200.0f, 3.0f, 4096, 0.125f, - glm::vec3(0.0f), glm::vec4(-100.0f, 100.0f, -70.0f, 120.0f)); + directionalLight.properties.directional.direction = vec3(0.0f, -1.0f, 1.0f); + directionalLight.color = vec3(255, 236, 209) / 255.0f; + directionalLight.AddDirectionalShadow(200.0f, 3.0f, 4096, 0.125f, 4, 0.9f); directionalLight.isMain = true; scene->reflection = Atlas::CreateRef(); - scene->reflection->useShadowMap = true; scene->fog = Atlas::CreateRef(); scene->fog->enable = true; @@ -95,7 +99,6 @@ void App::LoadContent() { scene->ssgi = Atlas::CreateRef(); scene->rtgi = Atlas::CreateRef(); scene->rtgi->enable = graphicsDevice->support.hardwareRayTracing; - scene->rtgi->useShadowMap = true; scene->physicsWorld = Atlas::CreateRef(); scene->rayTracingWorld = Atlas::CreateRef(); @@ -173,13 +176,13 @@ void App::Update(float deltaTime) { if (meshComponent.mesh->name == "chromesphere") { float height = (sinf(Atlas::Clock::Get() / 5.0f) + 1.0f) * 20.0f; - auto matrix = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, height, .0f)); + auto matrix = glm::translate(mat4(1.0f), vec3(0.0f, height, .0f)); transformComponent.Set(matrix); } else if (meshComponent.mesh->name == "metallicwall") { - auto matrix = glm::translate(glm::mat4(1.0f), glm::vec3(-50.0f, 0.0f, -2.0f)); - matrix = glm::rotate(matrix, Atlas::Clock::Get() / 2.0f, glm::vec3(0.0f, 1.0f, 0.0f)); + auto matrix = glm::translate(mat4(1.0f), vec3(-50.0f, 0.0f, -2.0f)); + matrix = glm::rotate(matrix, Atlas::Clock::Get() / 2.0f, vec3(0.0f, 1.0f, 0.0f)); transformComponent.Set(matrix); } @@ -195,14 +198,14 @@ void App::Update(float deltaTime) { auto x = (2.0f * Atlas::Common::Random::SampleFastUniformFloat() - 1.0f) * 20.0f; auto z = (2.0f * Atlas::Common::Random::SampleFastUniformFloat() - 1.0f) * 20.0f; - auto matrix = glm::translate(glm::mat4(1.0f), glm::vec3(x, 100.0f, z)); + auto matrix = glm::translate(mat4(1.0f), vec3(x, 100.0f, z)); auto entity = scene->CreatePrefab(meshes.back(), matrix, false); auto shapeSettings = Atlas::Physics::SphereShapeSettings{ .radius = meshes.back()->data.radius, .density = sphereDensity, - .scale = glm::vec3(sphereScale), + .scale = vec3(sphereScale), }; auto shape = Atlas::Physics::ShapesManager::CreateShape(shapeSettings); @@ -241,11 +244,11 @@ void App::Update(float deltaTime) { auto shapeSettings = Atlas::Physics::SphereShapeSettings{ .radius = meshes.back()->data.radius, .density = sphereDensity, - .scale = glm::vec3(sphereScale), + .scale = vec3(sphereScale), }; auto shape = Atlas::Physics::ShapesManager::CreateShape(shapeSettings); - auto matrix = glm::translate(glm::mat4(1.0f), glm::vec3(camera.GetLocation() + + auto matrix = glm::translate(mat4(1.0f), vec3(camera.GetLocation() + camera.direction * meshes.back()->data.radius * 2.0f)); auto entity = scene->CreatePrefab(meshes.back(), matrix, false); @@ -300,8 +303,7 @@ void App::Render(float deltaTime) { graphicsDevice->WaitForPreviousFrameSubmission(); #ifndef AE_HEADLESS - auto windowFlags = window.GetFlags(); - if (windowFlags & AE_WINDOW_HIDDEN || windowFlags & AE_WINDOW_MINIMIZED || !(windowFlags & AE_WINDOW_SHOWN)) { + if (window.IsOccluded()) { // If we take the early way out we need to make sure that stuff is completed (usually main renderer takes care of that) scene->WaitForAsyncWorkCompletion(); return; @@ -317,7 +319,7 @@ void App::Render(float deltaTime) { auto& directionalLight = directionalLightEntity.GetComponent(); if (animateLight) directionalLight.properties.directional.direction - = glm::vec3(0.0f, -1.0f, sin(Atlas::Clock::Get() / 10.0f)); + = vec3(0.0f, -1.0f, sin(Atlas::Clock::Get() / 10.0f)); viewport->Set(0, 0, renderTarget->GetWidth(), renderTarget->GetHeight()); @@ -502,7 +504,6 @@ void App::Render(float deltaTime) { bool pathTraceEnabled = pathTrace; ImGui::Checkbox("Enable##Pathtrace", &pathTrace); ImGui::SliderInt("Bounces##Pathtrace", &mainRenderer->pathTracingRenderer.bounces, 0, 100); - ImGui::Checkbox("Sample emissives##Pathtrace", &mainRenderer->pathTracingRenderer.sampleEmissives); ImGui::Text("Realtime"); ImGui::Checkbox("Realtime##Pathtrace", &mainRenderer->pathTracingRenderer.realTime); ImGui::SliderInt("Samples per frame##Pathtrace", &mainRenderer->pathTracingRenderer.realTimeSamplesPerFrame, 1, 100); @@ -510,6 +511,7 @@ void App::Render(float deltaTime) { ImGui::SliderInt("Max accumulated frames##Pathtrace", &mainRenderer->pathTracingRenderer.historyLengthMax, 1, 256); ImGui::SliderFloat("Current clip##Pathtrace", &mainRenderer->pathTracingRenderer.currentClipFactor, 0.1f, 4.0f); ImGui::SliderFloat("Max history clip##Pathtrace", &mainRenderer->pathTracingRenderer.historyClipMax, 0.0f, 1.0f); + ImGui::SliderFloat("Spatial filter strength##Pathtrace", &mainRenderer->pathTracingRenderer.spatialFilterStrength, 0.0f, 16.0f); scene->rayTracingWorld->includeObjectHistory = pathTrace; } @@ -621,7 +623,7 @@ void App::Render(float deltaTime) { ImGui::Text("Use F11 to hide/unhide the UI"); } if (ImGui::CollapsingHeader("Profiler")) { - gpuProfilerPanel.Render(); + profilerPanel.Render(); } } @@ -695,7 +697,7 @@ void App::DisplayLoadingScreen(float deltaTime) { viewport->Set(0, 0, windowSize.x, windowSize.y); mainRenderer->textRenderer.Render(commandList, viewport, font, - "Loading...", x, y, glm::vec4(1.0f, 1.0f, 1.0f, 1.0f), 2.0f); + "Loading...", x, y, vec4(1.0f, 1.0f, 1.0f, 1.0f), 2.0f); commandList->EndRenderPass(); commandList->EndCommands(); @@ -733,7 +735,7 @@ bool App::LoadScene() { Atlas::ResourceHandle sky; auto& directionalLight = directionalLightEntity.GetComponent(); - directionalLight.properties.directional.direction = glm::vec3(0.0f, -1.0f, 1.0f); + directionalLight.properties.directional.direction = vec3(0.0f, -1.0f, 1.0f); auto& camera = cameraEntity.GetComponent(); @@ -748,20 +750,20 @@ bool App::LoadScene() { using namespace Atlas::Loader; - std::vector transforms; + std::vector transforms; if (sceneSelection == CORNELL) { auto mesh = Atlas::ResourceManager::GetOrLoadResourceWithLoaderAsync( "cornell/CornellBox-Original.obj", ModelImporter::ImportMesh, false, 2048 ); meshes.push_back(mesh); - transforms.push_back(glm::scale(glm::mat4(1.0f), glm::vec3(10.0f))); + transforms.push_back(glm::scale(mat4(1.0f), vec3(10.0f))); // Other scene related settings apart from the mesh directionalLight.intensity = 0.0f; // Setup camera - camera.location = glm::vec3(0.0f, 14.0f, 40.0f); - camera.rotation = glm::vec2(-3.14f, -0.1f); + camera.location = vec3(0.0f, 14.0f, 40.0f); + camera.rotation = vec2(-3.14f, -0.1f); scene->fog->enable = false; scene->fog->volumetricIntensity = 0.0f; @@ -771,7 +773,7 @@ bool App::LoadScene() { "sponza/sponza.obj", ModelImporter::ImportMesh, false, 2048 ); meshes.push_back(mesh); - transforms.push_back(glm::scale(glm::mat4(1.0f), glm::vec3(.05f))); + transforms.push_back(glm::scale(mat4(1.0f), vec3(.05f))); mesh = Atlas::ResourceManager::GetOrLoadResourceWithLoaderAsync( "metallicwall.gltf", ModelImporter::ImportMesh, Atlas::Mesh::MeshMobility::Movable, false, 2048 @@ -780,12 +782,12 @@ bool App::LoadScene() { transforms.emplace_back(1.0f); // Other scene related settings apart from the mesh - directionalLight.properties.directional.direction = glm::vec3(0.0f, -1.0f, 0.33f); + directionalLight.properties.directional.direction = vec3(0.0f, -1.0f, 0.33f); directionalLight.intensity = 100.0f; // Setup camera - camera.location = glm::vec3(30.0f, 25.0f, 0.0f); - camera.rotation = glm::vec2(-3.14f / 2.0f, 0.0f); + camera.location = vec3(30.0f, 25.0f, 0.0f); + camera.rotation = vec2(-3.14f / 2.0f, 0.0f); camera.exposure = 0.125f; scene->fog->enable = true; @@ -796,14 +798,14 @@ bool App::LoadScene() { "bistro/mesh/exterior.obj", ModelImporter::ImportMesh, false, 2048 ); meshes.push_back(mesh); - transforms.push_back(glm::scale(glm::mat4(1.0f), glm::vec3(.015f))); + transforms.push_back(glm::scale(mat4(1.0f), vec3(.015f))); // Other scene related settings apart from the mesh directionalLight.intensity = 100.0f; // Setup camera - camera.location = glm::vec3(-21.0f, 8.0f, 1.0f); - camera.rotation = glm::vec2(3.14f / 2.0f, 0.0f); + camera.location = vec3(-21.0f, 8.0f, 1.0f); + camera.rotation = vec2(3.14f / 2.0f, 0.0f); camera.exposure = 0.125f; scene->fog->enable = true; @@ -814,15 +816,15 @@ bool App::LoadScene() { "sanmiguel/san-miguel-low-poly.obj", ModelImporter::ImportMesh, false, 2048 ); meshes.push_back(mesh); - transforms.push_back(glm::scale(glm::mat4(1.0f), glm::vec3(2.0f))); + transforms.push_back(glm::scale(mat4(1.0f), vec3(2.0f))); // Other scene related settings apart from the mesh directionalLight.intensity = 100.0f; - directionalLight.properties.directional.direction = glm::vec3(0.0f, -1.0f, -1.0f); + directionalLight.properties.directional.direction = vec3(0.0f, -1.0f, -1.0f); // Setup camera - camera.location = glm::vec3(45.0f, 26.0f, 17.0f); - camera.rotation = glm::vec2(-4.14f / 2.0f, -.6f); + camera.location = vec3(45.0f, 26.0f, 17.0f); + camera.rotation = vec2(-4.14f / 2.0f, -.6f); camera.exposure = 2.5f; scene->fog->enable = true; @@ -844,8 +846,8 @@ bool App::LoadScene() { directionalLight.intensity = 10.0f; // Setup camera - camera.location = glm::vec3(30.0f, 25.0f, 0.0f); - camera.rotation = glm::vec2(-3.14f / 2.0f, 0.0f); + camera.location = vec3(30.0f, 25.0f, 0.0f); + camera.rotation = vec2(-3.14f / 2.0f, 0.0f); scene->fog->enable = true; scene->fog->volumetricIntensity = 0.08f; @@ -855,14 +857,14 @@ bool App::LoadScene() { "pica pica/mesh/scene.gltf", ModelImporter::ImportMesh, false, 2048 ); meshes.push_back(mesh); - transforms.push_back(glm::rotate(glm::mat4(1.0f), -3.14f / 2.0f, glm::vec3(1.0f, 0.0f, 0.0f))); + transforms.push_back(glm::rotate(mat4(1.0f), -3.14f / 2.0f, vec3(1.0f, 0.0f, 0.0f))); // Other scene related settings apart from the mesh directionalLight.intensity = 10.0f; // Setup camera - camera.location = glm::vec3(30.0f, 25.0f, 0.0f); - camera.rotation = glm::vec2(-3.14f / 2.0f, 0.0f); + camera.location = vec3(30.0f, 25.0f, 0.0f); + camera.rotation = vec2(-3.14f / 2.0f, 0.0f); camera.exposure = 1.0f; scene->fog->enable = true; @@ -879,8 +881,8 @@ bool App::LoadScene() { directionalLight.intensity = 10.0f; // Setup camera - camera.location = glm::vec3(30.0f, 25.0f, 0.0f); - camera.rotation = glm::vec2(-3.14f / 2.0f, 0.0f); + camera.location = vec3(30.0f, 25.0f, 0.0f); + camera.rotation = vec2(-3.14f / 2.0f, 0.0f); camera.exposure = 1.0f; scene->fog->enable = false; @@ -891,7 +893,7 @@ bool App::LoadScene() { "material demo/materials.obj", ModelImporter::ImportMesh, false, 2048 ); meshes.push_back(mesh); - transforms.push_back(glm::scale(glm::vec3(8.0f))); + transforms.push_back(glm::scale(vec3(8.0f))); sky = Atlas::ResourceManager::GetOrLoadResourceAsync("environment.hdr"); probe = Atlas::Lighting::EnvironmentProbe(sky); @@ -901,8 +903,8 @@ bool App::LoadScene() { directionalLight.intensity = 10.0f; // Setup camera - camera.location = glm::vec3(30.0f, 25.0f, 0.0f); - camera.rotation = glm::vec2(-3.14f / 2.0f, 0.0f); + camera.location = vec3(30.0f, 25.0f, 0.0f); + camera.rotation = vec2(-3.14f / 2.0f, 0.0f); camera.exposure = 1.0f; scene->fog->enable = false; @@ -911,7 +913,7 @@ bool App::LoadScene() { scene->fog->volumetricIntensity = 0.0f; } else if (sceneSelection == FOREST) { - auto otherScene = Atlas::Loader::ModelImporter::ImportScene("forest/forest.gltf", -glm::vec3(2048.0f), glm::vec3(2048.0f), 5, false, false, false, 2048); + auto otherScene = Atlas::Loader::ModelImporter::ImportScene("forest/forest.gltf", -vec3(2048.0f), vec3(2048.0f), 6, false, false, false, 2048); otherScene->Update(1.0f); CopyActors(otherScene); @@ -920,15 +922,15 @@ bool App::LoadScene() { directionalLight.intensity = 50.0f; // Setup camera - camera.location = glm::vec3(30.0f, 25.0f, 0.0f); - camera.rotation = glm::vec2(-3.14f / 2.0f, 0.0f); + camera.location = vec3(30.0f, 25.0f, 0.0f); + camera.rotation = vec2(-3.14f / 2.0f, 0.0f); camera.exposure = 1.0f; scene->fog->enable = false; scene->fog->volumetricIntensity = 0.08f; } else if (sceneSelection == EMERALDSQUARE) { - auto otherScene = Atlas::Loader::ModelImporter::ImportScene("emeraldsquare/square.gltf", -glm::vec3(2048.0f), glm::vec3(2048.0f), 5, false, false, false, 2048); + auto otherScene = Atlas::Loader::ModelImporter::ImportScene("emeraldsquare/square.gltf", -vec3(2048.0f), vec3(2048.0f), 6, false, false, false, 2048); otherScene->Update(1.0f); CopyActors(otherScene); @@ -937,8 +939,8 @@ bool App::LoadScene() { directionalLight.intensity = 10.0f; // Setup camera - camera.location = glm::vec3(30.0f, 25.0f, 0.0f); - camera.rotation = glm::vec2(-3.14f / 2.0f, 0.0f); + camera.location = vec3(30.0f, 25.0f, 0.0f); + camera.rotation = vec2(-3.14f / 2.0f, 0.0f); camera.exposure = 1.0f; scene->fog->enable = false; @@ -949,7 +951,7 @@ bool App::LoadScene() { "flying world/scene.gltf", ModelImporter::ImportMesh, false, 2048 ); meshes.push_back(mesh); - transforms.emplace_back(glm::scale(glm::vec3(0.01f))); + transforms.emplace_back(glm::scale(vec3(0.01f))); // Metalness is set to 0.9f //for (auto& material : mesh.data.materials) material.metalness = 0.0f; @@ -958,8 +960,8 @@ bool App::LoadScene() { directionalLight.intensity = 50.0f; // Setup camera - camera.location = glm::vec3(30.0f, 25.0f, 0.0f); - camera.rotation = glm::vec2(-3.14f / 2.0f, 0.0f); + camera.location = vec3(30.0f, 25.0f, 0.0f); + camera.rotation = vec2(-3.14f / 2.0f, 0.0f); camera.exposure = 1.0f; scene->sky.clouds->baseAltitude = 700.0f; @@ -974,30 +976,30 @@ bool App::LoadScene() { "newsponza/main/NewSponza_Main_Blender_glTF.gltf", ModelImporter::ImportMesh, false, 2048 ); meshes.push_back(mesh); - transforms.emplace_back(glm::scale(glm::vec3(4.0f))); + transforms.emplace_back(glm::scale(vec3(4.0f))); mesh = Atlas::ResourceManager::GetOrLoadResourceWithLoaderAsync( "newsponza/candles/NewSponza_100sOfCandles_glTF_OmniLights.gltf", ModelImporter::ImportMesh, false, 2048 ); meshes.push_back(mesh); - transforms.emplace_back(glm::scale(glm::vec3(4.0f))); + transforms.emplace_back(glm::scale(vec3(4.0f))); mesh = Atlas::ResourceManager::GetOrLoadResourceWithLoaderAsync( "newsponza/curtains/NewSponza_Curtains_glTF.gltf", ModelImporter::ImportMesh, false, 2048 ); meshes.push_back(mesh); - transforms.emplace_back(glm::scale(glm::vec3(4.0f))); + transforms.emplace_back(glm::scale(vec3(4.0f))); mesh = Atlas::ResourceManager::GetOrLoadResourceWithLoaderAsync( "newsponza/ivy/NewSponza_IvyGrowth_glTF.gltf", ModelImporter::ImportMesh, false, 2048 ); meshes.push_back(mesh); - transforms.emplace_back(glm::scale(glm::vec3(4.0f))); + transforms.emplace_back(glm::scale(vec3(4.0f))); // Other scene related settings apart from the mesh - directionalLight.properties.directional.direction = glm::vec3(0.0f, -1.0f, 0.33f); + directionalLight.properties.directional.direction = vec3(0.0f, -1.0f, 0.33f); directionalLight.intensity = 100.0f; // Setup camera - camera.location = glm::vec3(30.0f, 25.0f, 0.0f); - camera.rotation = glm::vec2(-3.14f / 2.0f, 0.0f); + camera.location = vec3(30.0f, 25.0f, 0.0f); + camera.rotation = vec2(-3.14f / 2.0f, 0.0f); scene->fog->enable = true; scene->fog->volumetricIntensity = 0.28f; @@ -1030,8 +1032,8 @@ bool App::LoadScene() { auto y = (2.0f * Atlas::Common::Random::SampleFastUniformFloat() - 1.0f) * 100.0f; auto z = (2.0f * Atlas::Common::Random::SampleFastUniformFloat() - 1.0f) * 100.0f; - auto entity = scene->CreatePrefab(mesh, glm::translate(glm::mat4(1.0f), - glm::vec3(x, y, z))); + auto entity = scene->CreatePrefab(mesh, glm::translate(mat4(1.0f), + vec3(x, y, z))); entities.push_back(entity); } } @@ -1089,8 +1091,8 @@ void App::CheckLoadScene() { graphicsDevice->WaitForPreviousFrameSubmission(); - auto sceneAABB = Atlas::Volume::AABB(glm::vec3(std::numeric_limits::max()), - glm::vec3(-std::numeric_limits::max())); + auto sceneAABB = Atlas::Volume::AABB(vec3(std::numeric_limits::max()), + vec3(-std::numeric_limits::max())); auto transformEntities = scene->GetSubset(); for (auto entity : transformEntities) { @@ -1106,71 +1108,69 @@ void App::CheckLoadScene() { if (sceneSelection == CORNELL) { scene->irradianceVolume = std::make_shared( - sceneAABB.Scale(1.10f), glm::ivec3(20)); - scene->irradianceVolume->sampleEmissives = true; + sceneAABB.Scale(1.10f), ivec3(20)); scene->irradianceVolume->SetRayCount(512, 32); } else if (sceneSelection == SPONZA) { scene->irradianceVolume = std::make_shared( - sceneAABB.Scale(1.1f), glm::ivec3(20)); + sceneAABB.Scale(1.1f), ivec3(20)); scene->irradianceVolume->SetRayCount(128, 32); scene->irradianceVolume->strength = 1.5f; } else if (sceneSelection == BISTRO) { scene->irradianceVolume = std::make_shared( - sceneAABB.Scale(0.9f), glm::ivec3(20)); + sceneAABB.Scale(0.9f), ivec3(20)); scene->irradianceVolume->SetRayCount(32, 32); scene->irradianceVolume->strength = 1.5f; } else if (sceneSelection == SANMIGUEL) { scene->irradianceVolume = std::make_shared( - sceneAABB.Scale(1.0f), glm::ivec3(20)); + sceneAABB.Scale(1.0f), ivec3(20)); scene->irradianceVolume->SetRayCount(128, 32); } else if (sceneSelection == MEDIEVAL) { scene->irradianceVolume = std::make_shared( - sceneAABB.Scale(1.0f), glm::ivec3(20)); + sceneAABB.Scale(1.0f), ivec3(20)); scene->irradianceVolume->SetRayCount(128, 32); } else if (sceneSelection == PICAPICA) { for (auto& material : meshes.front()->data.materials) material->twoSided = false; scene->irradianceVolume = std::make_shared( - sceneAABB.Scale(1.0f), glm::ivec3(20)); + sceneAABB.Scale(1.0f), ivec3(20)); scene->irradianceVolume->SetRayCount(128, 32); } else if (sceneSelection == SUBWAY) { scene->irradianceVolume = std::make_shared( - sceneAABB.Scale(1.05f), glm::ivec3(20)); + sceneAABB.Scale(1.05f), ivec3(20)); scene->irradianceVolume->SetRayCount(128, 32); } else if (sceneSelection == MATERIALS) { scene->irradianceVolume = std::make_shared( - sceneAABB.Scale(1.05f), glm::ivec3(20)); + sceneAABB.Scale(1.05f), ivec3(20)); scene->irradianceVolume->SetRayCount(128, 32); } else if (sceneSelection == FOREST) { scene->irradianceVolume = std::make_shared( - sceneAABB.Scale(1.05f), glm::ivec3(20)); + sceneAABB.Scale(1.05f), ivec3(20)); scene->irradianceVolume->SetRayCount(32, 32); } else if (sceneSelection == NEWSPONZA) { scene->irradianceVolume = std::make_shared( - sceneAABB.Scale(1.05f), glm::ivec3(20)); + sceneAABB.Scale(1.05f), ivec3(20)); scene->irradianceVolume->SetRayCount(128, 32); } else if (sceneSelection == EMERALDSQUARE) { scene->irradianceVolume = std::make_shared( - sceneAABB.Scale(1.05f), glm::ivec3(20)); + sceneAABB.Scale(1.05f), ivec3(20)); scene->irradianceVolume->SetRayCount(128, 32); } else if (sceneSelection == FLYINGWORLD) { scene->irradianceVolume = std::make_shared( - sceneAABB.Scale(1.05f), glm::ivec3(20)); + sceneAABB.Scale(1.05f), ivec3(20)); scene->irradianceVolume->SetRayCount(128, 32); } - scene->irradianceVolume->useShadowMap = true; scene->irradianceVolume->visibility = false; // Add rigid body components to entities (we need to wait for loading to complete to get valid mesh bounds) diff --git a/src/demo/App.h b/src/demo/App.h index 6e90c012d..3c88e371a 100644 --- a/src/demo/App.h +++ b/src/demo/App.h @@ -88,7 +88,7 @@ class App : public Atlas::EngineInstance { Atlas::ImguiExtension::ReflectionPanel reflectionPanel; Atlas::ImguiExtension::SSSPanel sssPanel; Atlas::ImguiExtension::PostProcessingPanel postProcessingPanel; - Atlas::ImguiExtension::GPUProfilerPanel gpuProfilerPanel; + Atlas::ImguiExtension::ProfilerPanel profilerPanel; Atlas::ImguiExtension::MaterialsPanel materialsPanel; Atlas::ImguiExtension::WindPanel windPanel; diff --git a/src/editor/App.cpp b/src/editor/App.cpp index 961dea012..82a5a3ac6 100644 --- a/src/editor/App.cpp +++ b/src/editor/App.cpp @@ -5,12 +5,23 @@ #include "Notifications.h" #include "ContentDiscovery.h" #include "Theme.h" +#include "DataCreator.h" +#include "RecentProjects.h" + +#include #include "ui/panels/PopupPanels.h" #include "tools/FileSystemHelper.h" #include +#include +#include +#include +#include +#include #include +#include #include +#include #include #include @@ -30,52 +41,349 @@ namespace Atlas::Editor { void App::LoadContent() { + // Scenes don't wait behind the meshes and textures which are already loading + ResourceManager::loadPriority = JobPriority::Medium; + + // Meshes and impostors are saved and baked here, they stay resident unless the engine settings enable it + Streaming::StreamingManager::settings.impostors.enable = false; + Streaming::StreamingManager::settings.meshes.enable = false; + + if (engineDataDirectory.empty()) + engineDataDirectory = Loader::AssetLoader::GetDataDirectory(); + LoadProject(); + ContentDiscovery::Update(); + // The ImGui wrapper creates the ImPlot context ImGui::CreateContext(); - ImPlot::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; + // Each project keeps its own layout + if (Singletons::project) { + imguiIniPath = Singletons::project->GetDirectory() + "/.atlas/imgui.ini"; + io.IniFilename = imguiIniPath.c_str(); + } - SetDefaultWindowResolution(); + if (!switchingProject) + SetDefaultWindowResolution(); auto icon = Atlas::Texture::Texture2D("icon.png"); window.SetIcon(&icon); - // Add font with enlarged size and scale it down again - // This means we can use scaled text up to 2x the size - io.Fonts->AddFontFromFileTTF( - Loader::AssetLoader::GetFullPath("font/roboto.ttf").c_str(), - 32.0f - )->Scale = 0.5f; - SubscribeToResourceEvents(); Singletons::imguiWrapper = CreateRef(); - Singletons::imguiWrapper->Load(&window); Singletons::config = CreateRef(); Serialization::DeserializeConfig(); + + // --log-hitches [ms] logs frames that take much longer than the ones before with their CPU profile, it + // overrides the hitch settings of the config for this run + for (size_t i = 0; i < args.size(); i++) { + if (args[i] != "--log-hitches") + continue; + auto hitchSettings = HitchRecorder::GetSettings(); + configHitchSettings = hitchSettings; + hitchSettings.enable = true; + hitchSettings.cpu.enable = true; + hitchSettings.log = true; + if (i + 1 < args.size() && std::isdigit(static_cast(args[i + 1][0]))) + hitchSettings.cpu.minimumTime = std::stof(args[i + 1]); + HitchRecorder::SetSettings(hitchSettings); + } + + contentBrowserWindow.currentDirectory = Loader::AssetLoader::GetDataDirectory(); Serialization::DeserializeContentBrowserWindow(contentBrowserWindow); + Serialization::DeserializeDrawerWindow(logWindow); + Serialization::DeserializeDrawerWindow(profilerWindow); + restoringScenes = false; + + // A hand edited config may name a drawer twice or one which doesn't exist + auto& statusBarDrawers = Singletons::config->statusBarDrawers; + std::vector knownDrawers; + for (const auto& name : statusBarDrawers) + if (FindDrawer(name) && std::find(knownDrawers.begin(), knownDrawers.end(), name) == knownDrawers.end()) + knownDrawers.push_back(name); + statusBarDrawers = knownDrawers; + + // The font depends on the scale from the config, its resources are created only once + UpdateUiScale(); + Singletons::imguiWrapper->Load(&window); + // Everything that needs the config comes afterwards Singletons::icons = CreateRef(); Singletons::blockingOperation = CreateRef(); - Singletons::renderTarget = CreateRef(1280, 720); + Singletons::contentPreviews = CreateRef(); Singletons::mainRenderer = mainRenderer; mouseHandler = Input::MouseHandler(1.5f, 8.0f); keyboardHandler = Input::KeyboardHandler(7.0f, 5.0f); - Theme::Apply(Singletons::config->darkMode); + ApplyTheme(); RegisterCommands(); + projectHub = std::make_unique(engineDataDirectory, + (std::filesystem::path(engineDataDirectory).parent_path() / "templates").generic_string()); + + if (Singletons::project) { + projectSettingsWindow.onChange = [this](const Project&) { ApplyProjectSettings(); }; + ApplyProjectSettings(); + OpenStartScene(); + // --mcp-port if another program uses the default port + auto port = Bridge::McpServer::defaultPort; + for (size_t i = 0; i + 1 < args.size(); i++) { + if (args[i] == "--mcp-port") + port = std::stoi(args[i + 1]); + } + bridge = std::make_unique(Singletons::project, port, [this]() { return GetActiveSceneWindow(); }); + bridge->addEditorFunctions = [this](Scripting::Binder& editor) { AddEditorFunctions(editor); }; + // Recorded for the bindings and completions before the first script runs + sol::state recorder; + Scripting::Binder editorTable(recorder.create_table(), "Editor"); + AddEditorFunctions(editorTable); + // Lua of the agent changes the project like the settings window: applied, undoable there and saved by the user + bridge->onProjectChange = [this](const Project& before) { + projectSettingsWindow.RecordChange(Singletons::project, before, "project (Lua)"); + }; + } + + } + + void App::LoadProject() { + + std::string path; + for (size_t i = 0; i + 1 < args.size(); i++) { + if (args[i] == "--project") + path = args[i + 1]; + } + + // main() changes into the directory of the executable + auto project = path.empty() ? nullptr : Project::Load(Bridge::ResolveUserPath(path).string()); + if (!project) { + // The hub works with the data of the engine, e.g. after closing a project + Project::Activate(nullptr); + Loader::AssetLoader::SetAssetDirectory(engineDataDirectory); + // The project hub only keeps settings like the interface scale, it opens no scenes + auto prefPath = SDL_GetPrefPath("AtlasEngine", "Editor"); + if (prefPath) + Serialization::SetConfigDirectory(prefPath); + SDL_free(prefPath); + return; + } + + Project::Activate(project); + + // Asset directories which were used without a project kept the editor state in .config + auto stateDirectory = std::filesystem::path(project->GetDirectory()) / ".atlas"; + auto legacyDirectory = std::filesystem::path(project->GetAssetDirectory()) / ".config"; + std::error_code error; + if (!std::filesystem::exists(stateDirectory, error) && std::filesystem::is_directory(legacyDirectory, error)) + std::filesystem::copy(legacyDirectory, stateDirectory, std::filesystem::copy_options::recursive, error); + Serialization::SetConfigDirectory(stateDirectory.generic_string()); + + RecentProjects::Add(*project); + window.SetTitle("Atlas Engine Editor - " + project->name); + Singletons::project = project; + + } + + void App::ApplyProjectSettings() { + + auto& project = Singletons::project; + project->ApplySettings(); + // Meshes and impostors are saved and baked here, they stay resident whatever the project sets + Streaming::StreamingManager::settings.impostors.enable = false; + Streaming::StreamingManager::settings.meshes.enable = false; + + for (const auto& sceneWindow : sceneWindows) { + if (sceneWindow->scene.IsLoaded()) + project->ApplyTo(*sceneWindow->scene.Get()); + } + + } + + void App::ExportLuaAnnotations() { + + auto directory = std::filesystem::path(Singletons::project->GetDirectory()); + auto file = directory / ".atlas" / "lua" / "atlas.lua"; + std::filesystem::create_directories(file.parent_path()); + std::ofstream(file, std::ios::binary) << Scripting::BindingRegistry::ToLuaAnnotations(); + + auto luarc = directory / ".luarc.json"; + if (!std::filesystem::exists(luarc)) + std::ofstream(luarc, std::ios::binary) << json({ { "workspace.library", { ".atlas/lua" } } }).dump(2); + Notifications::Push({ .message = "Lua annotations written to " + file.generic_string() }); + + } + + void App::OpenStartScene() { + + auto& project = Singletons::project; + if (project->startScene.empty() || !Singletons::config->openedScenes.empty()) + return; + + if (!Loader::AssetLoader::FileExists(project->startScene)) { + auto scene = DataCreator::CreateScene(Common::Path::GetFileNameWithoutExtension(project->startScene), + vec3(-2048.0f), vec3(2048.0f), 8); + + // Playing needs a main camera + auto camera = scene->CreateEntity(); + camera.AddComponent("Camera"); + camera.AddComponent(glm::translate(mat4(1.0f), vec3(0.0f, 2.0f, 10.0f))); + auto& cameraComponent = camera.AddComponent(47.0f, 2.0f, 0.5f, 2000.0f); + cameraComponent.isMain = true; + scene->GetRootEntity().GetComponent().AddChild(camera); + + Serializer::SerializeScene(scene, project->startScene, false, true, false); + } + + FileImporter::ImportFile(project->startScene); + + } + + void App::OpenProject(const std::string& path) { + + // Unsaved changes are asked about first, like when the editor closes + nextProject = path; + if (AllowQuit()) + projectSwitchRequested = true; + + } + + void App::AddEditorFunctions(Scripting::Binder& editor) { + + // { name, kind, path, shown, focused, unsaved } of the tabs and drawers + editor.set_function("Windows", [this](sol::this_state state) { + sol::state_view lua(state); + sol::table windows = lua.create_table(); + auto add = [&](const UI::Window& window, const char* kind, const std::string& path) { + windows.add(lua.create_table_with("name", window.name, "kind", kind, "path", path, "shown", window.show, + "focused", window.inFocus, "unsaved", window.hasUnsavedChanges)); + }; + for (const auto& window : sceneWindows) + add(*window, "scene", UI::SceneWindow::GetScenePath(window->scene)); + for (const auto& window : assetEditorWindows) + add(*window, "asset", window->GetAssetPath()); + for (const auto& window : codeEditorWindows) + add(*window, "code", window->GetPath()); + add(projectSettingsWindow, "project settings", Singletons::project ? Singletons::project->path : ""); + add(contentBrowserWindow, "content browser", contentBrowserWindow.currentDirectory); + add(logWindow, "log", ""); + add(profilerWindow, "profiler", ""); + return windows; + }); + // Opens a file like a double click in the content browser: scenes, assets, scripts and shaders + editor.set_function("Open", [this](const std::string& path) { + if (!std::filesystem::exists(Loader::AssetLoader::GetFullPath(path))) + throw std::runtime_error(path + " doesn't exist in the asset directory"); + auto error = OpenInAssetEditor(path); + if (!error.empty()) + throw std::runtime_error(error); + }); + // Shows a window and gives it the focus, found by its name or path + editor.set_function("Focus", [this](const std::string& nameOrPath) { + std::vector> windows; + for (const auto& window : sceneWindows) + windows.emplace_back(window.get(), UI::SceneWindow::GetScenePath(window->scene)); + for (const auto& window : assetEditorWindows) + windows.emplace_back(window.get(), window->GetAssetPath()); + for (const auto& window : codeEditorWindows) + windows.emplace_back(window.get(), window->GetPath()); + windows.emplace_back(&projectSettingsWindow, ""); + windows.emplace_back(&contentBrowserWindow, ""); + windows.emplace_back(&logWindow, ""); + windows.emplace_back(&profilerWindow, ""); + for (auto& [window, path] : windows) { + if (window->name != nameOrPath && path != nameOrPath) + continue; + window->show = true; + window->requestFocus = true; + return; + } + throw std::runtime_error("There is no window " + nameOrPath + ", Editor.Windows() lists them"); + }); + // The text of an open code window, also while it isn't saved + editor.set_function("GetText", [this](const std::string& path) -> std::string { + for (const auto& window : codeEditorWindows) + if (window->GetPath() == path) + return window->GetText(); + throw std::runtime_error(path + " isn't open in a code window, Editor.Open(path) opens it"); + }); + // Replaces the text of a code window, opened if needed, as one undo step there. The user saves it + editor.set_function("SetText", [this](const std::string& path, const std::string& text) { + auto find = [&]() { + return std::find_if(codeEditorWindows.begin(), codeEditorWindows.end(), + [&](const auto& window) { return window->GetPath() == path; }); + }; + if (find() == codeEditorWindows.end()) + OpenInAssetEditor(path); + auto window = find(); + if (window == codeEditorWindows.end()) + throw std::runtime_error(path + " can't be opened in a code window"); + (*window)->SetText(text); + }); + + } + + void App::SwitchProject() { + + WaitForRender(); + auto path = *nextProject; + UnloadContent(); + + sceneWindows.clear(); + assetEditorWindows.clear(); + codeEditorWindows.clear(); + activeAssetEditorWindow.reset(); + waitToLoadScenes.clear(); + userOpenedScenes.clear(); + unsavedWindows.clear(); + activeCodeEditorWindow.reset(); + emptyStateScenes.clear(); + quitAfterUnsavedChanges = false; + quitConfirmed = false; + activeSceneIdx = 0; + drawerDockNodeID = 0; + systemUiScale = 0.0f; + fontRasterSize = 0.0f; + emptyStateVisible = false; + resetDockspaceLayout = false; + dockLoadingScenes = false; + restoringScenes = true; + playingMaximized = false; + projectHub.reset(); + projectSettingsWindow.history.Clear(); + projectSettingsWindow.hasUnsavedChanges = false; + projectSettingsWindow.show = false; + commandPalette = UI::CommandPalette(); + nextProject.reset(); + projectSwitchRequested = false; + + // The project replaces the one the editor started with, without one the project hub opens + for (size_t i = 0; i < args.size(); i++) { + if (args[i] == "--project" && i + 1 < args.size()) { + args.erase(args.begin() + i, args.begin() + i + 2); + break; + } + } + if (!path.empty()) { + args.push_back("--project"); + args.push_back(path); + } + + switchingProject = true; + LoadContent(); + switchingProject = false; + } void App::UnloadContent() { + Loader::ModelImporter::WaitForBackgroundImports(); + Singletons::imguiWrapper->Unload(); CopyPasteHelper::Clear(); @@ -83,50 +391,152 @@ namespace Atlas::Editor { for (const auto& sceneWindow : sceneWindows) { if (sceneWindow->isPlaying) sceneWindow->StopPlaying(); - Serialization::SerializeSceneWindow(sceneWindow); + // There is no update anymore which would run the queued operations + Singletons::blockingOperation->Finish(); + if (!sceneWindow->IsPrefab()) + Serialization::SerializeSceneWindow(sceneWindow); } Serialization::SerializeContentBrowserWindow(contentBrowserWindow); + Serialization::SerializeDrawerWindow(logWindow); + Serialization::SerializeDrawerWindow(profilerWindow); + if (configHitchSettings) + HitchRecorder::SetSettings(*configHitchSettings); Serialization::SerializeConfig(); ContentDiscovery::Shutdown(); + bridge.reset(); Singletons::Destruct(); - ImPlot::DestroyContext(); + ResourceManager::Unsubscribe(ResourceTopic::ResourceCreate, sceneCreateSubscription); + Events::EventManager::DropEventDelegate.Unsubscribe(dropSubscription); + + ImGui::DestroyContext(); } void App::Update(float deltaTime) { + if (projectSwitchRequested) + SwitchProject(); + const ImGuiIO& io = ImGui::GetIO(); + CPUProfiler::Scope sectionScope("Content discovery"); // Will lead to frame time spikes, don't do it if content can't be seen if (!playingMaximized) ContentDiscovery::Update(); + sectionScope.Next("ImGui update"); + UpdateUiScale(); Singletons::imguiWrapper->Update(&window, deltaTime); Singletons::blockingOperation->Update(); + // Commands wait while playing starts or stops + if (bridge && !Singletons::blockingOperation->block) { + sectionScope.Next("Bridge commands"); + bridge->Update(); + } + if (Singletons::blockingOperation->block) return; + Loader::ModelImporter::ApplyBackgroundImports(); + + sectionScope.Next("Content previews update"); + // Also while no previews are shown, they release what they don't need anymore + Singletons::contentPreviews->ReleaseUnused(); + + sectionScope.Next("Content browser update"); contentBrowserWindow.Update(); + logWindow.Update(); + + // Requests to show a file also have to work while the drawer is closed + if (!UI::ContentBrowserWindow::contentToShowPath.empty()) + contentBrowserWindow.show = true; + + if (!UI::ContentBrowserWindow::contentToEditPath.empty()) { + OpenInAssetEditor(UI::ContentBrowserWindow::contentToEditPath); + UI::ContentBrowserWindow::contentToEditPath.clear(); + } + + // Windows with unsaved changes stay open until the user decided about them + for (const auto& assetEditorWindow : assetEditorWindows) { + if (!assetEditorWindow->show && assetEditorWindow->hasUnsavedChanges) { + assetEditorWindow->show = true; + AddUnsavedWindow(assetEditorWindow); + } + } + std::erase_if(assetEditorWindows, [](const auto& window) { return !window->show; }); + if (activeAssetEditorWindow && !activeAssetEditorWindow->show) + activeAssetEditorWindow = nullptr; + for (const auto& assetEditorWindow : assetEditorWindows) + if (assetEditorWindow->inFocus) { + activeAssetEditorWindow = assetEditorWindow; + activeCodeEditorWindow = nullptr; + } + // Drags outside of viewports, e.g. on a slider, must not turn the next camera that gets the focus + auto mouseMovedCamera = false; + for (const auto& assetEditorWindow : assetEditorWindows) { + if (!assetEditorWindow->viewportPanel.isFocused || !assetEditorWindow->cameraEntity.IsValid() || ImGuizmo::IsUsing()) + continue; + auto& camera = assetEditorWindow->cameraEntity.GetComponent(); + keyboardHandler.speed = assetEditorWindow->cameraMovementSpeed; + mouseHandler.Update(camera, deltaTime); + keyboardHandler.Update(camera, deltaTime); + mouseMovedCamera = true; + } + + sectionScope.Next("Scene windows update"); // Create new windows for fully loaded scenes for (size_t i = 0; i < waitToLoadScenes.size(); i++) { if (waitToLoadScenes[i].IsLoaded()) { std::swap(waitToLoadScenes[i], waitToLoadScenes.back()); + // Projects saved before they had the scene settings take them from their first scene + auto& project = Singletons::project; + if (project->AdoptSceneSettings(*waitToLoadScenes.back().Get())) + project->Save(); + project->ApplyTo(*waitToLoadScenes.back().Get()); + // After the scene is loaded we can retrieve the window configuration and deserialize it sceneWindows.emplace_back(Serialization::DeserializeSceneWindow(waitToLoadScenes.back())); + // Scenes opened by the user and the ones opened for the first time join the others, restored + // ones stay where they were left and after a layout reset nobody has a place anymore + auto settings = ImGui::FindWindowSettingsByID(ImHashStr(sceneWindows.back()->GetNameID())); + sceneWindows.back()->requestDocking = !settings || dockLoadingScenes; + // Large scenes take a while, it's worth to say when they are there + if (std::erase(userOpenedScenes, waitToLoadScenes.back())) { + OpenAsTab(*sceneWindows.back()); + Notifications::Push({ .message = "Opened scene " + waitToLoadScenes.back()->name }); + } waitToLoadScenes.pop_back(); i--; } } + // Failed scenes are forgotten, such that they can be opened again once the problem is fixed + std::erase_if(waitToLoadScenes, [&](const auto& handle) { + if (!handle.GetResource()->errorOnLoad) + return false; + std::erase(Singletons::config->openedScenes, handle); + std::erase(userOpenedScenes, handle); + Notifications::Push({ .message = "Couldn't load scene " + handle.GetResource()->GetFileName() + ": " + + handle.GetResource()->errorMessageOnLoad, .type = NotificationType::Error }); + return true; + }); + + if (waitToLoadScenes.empty()) + dockLoadingScenes = false; + // Quick quit - if (sceneWindows.empty()) + if (sceneWindows.empty()) { + if (!mouseMovedCamera) + mouseHandler.Reset(); + ImGuizmo::Enable(true); return; + } auto& config = Singletons::config; @@ -136,24 +546,34 @@ namespace Atlas::Editor { size_t sceneCounter = 0; for (const auto& sceneWindow : sceneWindows) { - // Delete windows not opened in the config (don't know when this does happen) - if (std::find(config->openedScenes.begin(), config->openedScenes.end(), + // Delete windows not opened in the config (don't know when this does happen), prefabs aren't part of it + if (!sceneWindow->IsPrefab() && std::find(config->openedScenes.begin(), config->openedScenes.end(), sceneWindow->scene) == config->openedScenes.end()) { toBeDeletedSceneWindows.push_back(sceneCounter++); continue; } + // Windows with unsaved changes stay open until the user decided about them + if (!sceneWindow->show && sceneWindow->hasUnsavedChanges) { + sceneWindow->show = true; + AddUnsavedWindow(sceneWindow); + } + // Delete closed windows if (!sceneWindow->show) { auto iter = std::find(config->openedScenes.begin(), config->openedScenes.end(), sceneWindow->scene); - config->openedScenes.erase(iter); + if (iter != config->openedScenes.end()) + config->openedScenes.erase(iter); toBeDeletedSceneWindows.push_back(sceneCounter++); continue; } - if (sceneWindow->inFocus) + if (sceneWindow->inFocus) { activeSceneIdx = sceneCounter; + activeAssetEditorWindow = nullptr; + activeCodeEditorWindow = nullptr; + } sceneCounter++; } @@ -164,7 +584,10 @@ namespace Atlas::Editor { // Serialize window before erasing it if (sceneWindows[sceneWindowIdx]->isPlaying) sceneWindows[sceneWindowIdx]->StopPlaying(); - Serialization::SerializeSceneWindow(sceneWindows[sceneWindowIdx]); + // Queued operations reference the window + Singletons::blockingOperation->Finish(); + if (!sceneWindows[sceneWindowIdx]->IsPrefab()) + Serialization::SerializeSceneWindow(sceneWindows[sceneWindowIdx]); sceneWindows.erase(sceneWindows.begin() + sceneWindowIdx); } @@ -188,25 +611,21 @@ namespace Atlas::Editor { mouseHandler.Update(camera, deltaTime); keyboardHandler.Update(camera, deltaTime); + mouseMovedCamera = true; } - if (activeSceneWindow->isPlaying) { - auto playerSubset = activeSceneWindow->scene->GetSubset(); - for (auto entity : playerSubset) { - auto camera = entity.TryGetComponent(); - if (!camera) - continue; - - auto& player = entity.GetComponent(); + if (!mouseMovedCamera) + mouseHandler.Reset(); - mouseHandler.Update(*camera, deltaTime); - keyboardHandler.Update(*camera, player, deltaTime); - } + if (activeSceneWindow->isPlaying && !activeSceneWindow->scene->paused) { + playerInput.mouseHandler.sensibility = activeSceneWindow->cameraRotationSpeed; + playerInput.Update(*activeSceneWindow->scene.Get(), deltaTime); } // Update all scenes after input was applied for (auto& sceneWindow : sceneWindows) { - if (sceneWindow == activeSceneWindow) + // Only the last focused scene uses the camera input and the gizmo + if (sceneWindow == activeSceneWindow && !activeAssetEditorWindow) sceneWindow->isActiveWindow = true; else sceneWindow->isActiveWindow = false; @@ -215,7 +634,8 @@ namespace Atlas::Editor { sceneWindow->Update(deltaTime); } - ImGuizmo::Enable(activeSceneWindow->guizmo.needEnabled); + // Asset editors have their own gizmos, e.g. for the pins of soft bodies + ImGuizmo::Enable(activeAssetEditorWindow || activeSceneWindow->guizmo.needEnabled); } @@ -223,10 +643,27 @@ namespace Atlas::Editor { graphicsDevice->WaitForPreviousFrameSubmission(); - auto windowFlags = window.GetFlags(); - if (windowFlags & AE_WINDOW_HIDDEN || windowFlags & AE_WINDOW_MINIMIZED || !(windowFlags & AE_WINDOW_SHOWN)) { + auto waitForSceneUpdates = [&]() { + + for (const auto& sceneWindow : sceneWindows) { + if (sceneWindow->scene.IsLoaded()) + sceneWindow->scene->WaitForAsyncWorkCompletion(); + } + + // The preview scenes of asset editors are updated even if their viewport isn't rendered + for (const auto& assetEditorWindow : assetEditorWindows) { + if (assetEditorWindow->scene) + assetEditorWindow->scene->WaitForAsyncWorkCompletion(); + } + + }; + + // Playing scenes were updated in Update(), the panels below change what their jobs read + waitForSceneUpdates(); + + if (window.IsOccluded()) return; - } + auto& config = Singletons::config; @@ -236,9 +673,24 @@ namespace Atlas::Editor { else graphicsDevice->CreateSwapChain(VK_PRESENT_MODE_IMMEDIATE_KHR, Atlas::Graphics::SRGB_NONLINEAR); } + + + + + + CPUProfiler::Scope sectionScope("ImGui new frame"); ImGui::NewFrame(); ImGuizmo::BeginFrame(); + if (!Singletons::project) { + if (auto path = projectHub->Render(window.GetSDLWindow())) + OpenProject(*path); + Notifications::Display(); + ImGui::Render(); + Singletons::imguiWrapper->Render(true); + return; + } + // ImGui::ShowDemoWindow(); // ImPlot::ShowDemoWindow(); @@ -256,7 +708,9 @@ namespace Atlas::Editor { ImGui::GetColorU32(Theme::Base())); // Status bar first, it reduces the work area of the viewport + sectionScope.Next("Status bar"); RenderStatusBar(); + sectionScope.Next("Dockspace"); // The host covers the work area, which excludes the main menu bar and the status bar ImGui::SetNextWindowPos(viewport->WorkPos); @@ -278,13 +732,22 @@ namespace Atlas::Editor { if (!ImGui::DockBuilderGetNode(mainDsId) || resetDockspaceLayout) { SetupMainDockspace(mainDsId); } + PrepareDrawerDocking(mainDsId); - ImGuiDockNodeFlags dockspace_flags = ImGuiDockNodeFlags_PassthruCentralNode; + // The tabs have close buttons, a second one at the end of the tab bar would just be confusing + ImGuiDockNodeFlags dockspace_flags = ImGuiDockNodeFlags_PassthruCentralNode | ImGuiDockNodeFlags_NoCloseButton; ImGui::DockSpace(mainDsId, ImVec2(0.0f, 0.0f), dockspace_flags); + // Layouts saved before the drawers existed have no central node to dock into + if (!ImGui::DockBuilderGetCentralNode(mainDsId)) + resetDockspaceLayout = true; + if (sceneWindows.empty()) RenderEmptyState(mainDsId); + else + emptyStateVisible = false; + sectionScope.Next("Main menu bar"); if (ImGui::BeginMainMenuBar()) { static bool newScene = false; bool saveScene = false, exitEditor = false; @@ -294,11 +757,15 @@ namespace Atlas::Editor { const char* saveShortcut = "Ctrl+S"; #endif if (ImGui::BeginMenu("File")) { - /* - ImGui::MenuItem("Open project", nullptr, &openProject); - ImGui::MenuItem("Save project", nullptr, &saveProject); + if (ImGui::MenuItem("New project...")) + projectHub->OpenNewProjectPopup(); + if (ImGui::MenuItem("Open project...")) + OpenProject(""); + ImGui::SetItemTooltip("Closes the project and shows the project hub"); + ImGui::MenuItem("Project settings", nullptr, &projectSettingsWindow.show); + if (ImGui::MenuItem("Save project", nullptr, false, projectSettingsWindow.hasUnsavedChanges)) + projectSettingsWindow.Save(Singletons::project); ImGui::Separator(); - */ ImGui::MenuItem("New scene...", nullptr, &newScene); RenderRecentScenesMenu(); ImGui::MenuItem("Save scene", saveShortcut, &saveScene, activeSceneWindow != nullptr); @@ -311,16 +778,39 @@ namespace Atlas::Editor { ImGui::EndMenu(); } + if (ImGui::BeginMenu("Edit")) { + auto history = GetActiveHistory(); + auto undoName = history ? history->GetUndoName() : std::string(); + auto redoName = history ? history->GetRedoName() : std::string(); + if (ImGui::MenuItem(undoName.empty() ? "Undo" : ("Undo " + undoName).c_str(), "Ctrl+Z", false, CanUndo())) + Undo(); + if (ImGui::MenuItem(redoName.empty() ? "Redo" : ("Redo " + redoName).c_str(), "Ctrl+Shift+Z", false, CanRedo())) + Redo(); + ImGui::EndMenu(); + } + if (ImGui::BeginMenu("View")) { ImGui::SeparatorText("Windows"); - ImGui::MenuItem("Content browser", nullptr, &contentBrowserWindow.show); - ImGui::MenuItem("Log", nullptr, &logWindow.show); + ImGui::MenuItem("Content browser", "Ctrl+B", &contentBrowserWindow.show); + ImGui::MenuItem("Log", "Ctrl+J", &logWindow.show); ImGui::MenuItem("Profiler", nullptr, &profilerWindow.show); ImGui::MenuItem("Geometry brush", nullptr, &geometryBrushWindow.show); ImGui::SeparatorText("Appearance"); if (ImGui::MenuItem("Dark mode", nullptr, &config->darkMode)) { - Theme::Apply(config->darkMode); + ApplyTheme(); + } + if (ImGui::BeginMenu("Interface scale")) { + auto percent = [](float scale) { return std::to_string(int32_t(std::round(scale * 100.0f))) + "%"; }; + auto systemLabel = "System (" + percent(window.GetContentScale()) + ")"; + if (ImGui::MenuItem(systemLabel.c_str(), nullptr, config->uiScale <= 0.0f)) + config->uiScale = 0.0f; + ImGui::Separator(); + for (auto scale : { 0.75f, 0.9f, 1.0f, 1.1f, 1.25f, 1.5f, 1.75f, 2.0f }) { + if (ImGui::MenuItem(percent(scale).c_str(), nullptr, config->uiScale == scale)) + config->uiScale = scale; + } + ImGui::EndMenu(); } ImGui::MenuItem("Reset layout", nullptr, &resetDockspaceLayout); ImGui::EndMenu(); @@ -354,22 +844,64 @@ namespace Atlas::Editor { ImGui::EndMainMenuBar(); } + sectionScope.Next("Scene windows"); for (auto& sceneWindow : sceneWindows) { + DockAsTab(*sceneWindow); sceneWindow->Render(); } + sectionScope.Next("Asset editor windows"); + for (auto& codeEditorWindow : codeEditorWindows) { + DockAsTab(*codeEditorWindow); + codeEditorWindow->Render(); + } + for (auto& codeEditorWindow : codeEditorWindows) { + if (!codeEditorWindow->show && codeEditorWindow->hasUnsavedChanges) { + codeEditorWindow->show = true; + AddUnsavedWindow(codeEditorWindow); + } + if (codeEditorWindow->inFocus) { + activeCodeEditorWindow = codeEditorWindow; + activeAssetEditorWindow = nullptr; + } + } + std::erase_if(codeEditorWindows, [](const auto& window) { return !window->show; }); + if (activeCodeEditorWindow && !activeCodeEditorWindow->show) + activeCodeEditorWindow = nullptr; + + for (auto& assetEditorWindow : assetEditorWindows) { + DockAsTab(*assetEditorWindow); + assetEditorWindow->Render(); + } + // This does active changes to the scene, render after scene windows + sectionScope.Next("Geometry brush window"); + DockAsTab(geometryBrushWindow); geometryBrushWindow.Render(activeSceneWindow); + UpdateDrawers(); + + sectionScope.Next("Content browser"); + DockPinnedDrawer(contentBrowserWindow); contentBrowserWindow.Render(); + sectionScope.Next("Log window"); + DockPinnedDrawer(logWindow); logWindow.Render(); + sectionScope.Next("Profiler window"); + DockPinnedDrawer(profilerWindow); profilerWindow.Render(); + sectionScope.Next("Settings window"); + sectionScope.Next("Project settings window"); + DockAsTab(projectSettingsWindow); + projectSettingsWindow.Render(Singletons::project); ImGui::End(); } else { + sectionScope.Next("Maximized scene"); RenderSceneMaximized(); } + sectionScope.Next("Popups and notifications"); // Global shortcut for the command palette #ifdef AE_OS_MACOS @@ -379,17 +911,35 @@ namespace Atlas::Editor { #endif if (commandDown && ImGui::IsKeyPressed(ImGuiKey_P, false) && !Singletons::blockingOperation->block) commandPalette.Open(); + if (commandDown && ImGui::IsKeyPressed(ImGuiKey_B, false) && !playingMaximized) + contentBrowserWindow.show = !contentBrowserWindow.show; + if (commandDown && ImGui::IsKeyPressed(ImGuiKey_J, false) && !playingMaximized) + logWindow.show = !logWindow.show; if (!playingMaximized) RenderShortcutsWindow(); Notifications::Display(); UI::PopupPanels::Render(); + if (auto created = projectHub->RenderNewProjectPopup(window.GetSDLWindow())) + OpenProject(*created); + RenderUnsavedChangesPopup(); commandPalette.Render(); + // Generates the previews which everything rendered in this frame requested + sectionScope.Next("Content previews"); + Singletons::contentPreviews->Update(); + + // Inactive viewports can still have scene jobs that enqueue GPU work + sectionScope.Next("Wait for scene updates"); + waitForSceneUpdates(); + sectionScope.Next("ImGui render"); ImGui::Render(); Singletons::imguiWrapper->Render(true); + if (bridge) + bridge->AfterRender(); + } void App::RenderSceneMaximized() { @@ -410,12 +960,12 @@ namespace Atlas::Editor { auto renderArea = ImGui::GetContentRegionAvail(); activeSceneWindow->viewportPanel.RenderScene(activeSceneWindow->scene.Get(), - ivec2(0), ivec2(int32_t(renderArea.x), int32_t(renderArea.y)), true); + ivec2(0), ivec2(int32_t(renderArea.x), int32_t(renderArea.y))); auto set = Singletons::imguiWrapper->GetTextureId(&activeSceneWindow->viewportPanel.viewportTexture); ImGui::Image(set, renderArea); if (activeSceneWindow->perfOverlayMaximized) { - auto gpuProfilerData = Graphics::Profiler::GetQueriesAverage(32, Graphics::Profiler::OrderBy::MAX_TIME); + auto gpuProfilerData = GPUProfiler::GetQueriesAverage(32, GPUProfiler::OrderBy::MAX_TIME); std::string perfString; double slowestTime = 0.0; @@ -423,14 +973,14 @@ namespace Atlas::Editor { const auto& threadData = gpuProfilerData[i]; double threadTime = 0.0; for (const auto& query : threadData.queries) { - threadTime += query.timer.elapsedTime; + threadTime += query.elapsedTime; } if (threadTime > slowestTime) { slowestTime = threadTime; } } - auto target = Singletons::renderTarget; + auto target = activeSceneWindow->viewportPanel.renderTarget; // Put the overlay on a translucent panel, such that it stays readable on bright scenes ImGui::SetCursorPos(ImVec2(12.0f, 12.0f)); @@ -471,31 +1021,205 @@ namespace Atlas::Editor { void App::RenderEmptyState(ImGuiID dsID) { - // The central node is transparent when nothing is docked, draw a hint behind all windows auto centralNode = ImGui::DockBuilderGetCentralNode(dsID); if (!centralNode || centralNode->Size.x <= 0.0f || centralNode->Size.y <= 0.0f) return; - bool loading = !waitToLoadScenes.empty(); - const char* title = loading ? "Loading scene..." : "No scene open"; - const char* subtitle = loading ? "" : - "Double-click a scene in the content browser or create one with File > New scene"; + auto& config = Singletons::config; - auto drawList = ImGui::GetBackgroundDrawList(ImGui::GetMainViewport()); - auto font = ImGui::GetFont(); - auto fontSize = ImGui::GetFontSize(); - auto titleSize = fontSize * 1.5f; + ImGui::SetNextWindowPos(ImVec2(centralNode->Pos.x + centralNode->Size.x * 0.5f, + centralNode->Pos.y + centralNode->Size.y * 0.5f), ImGuiCond_Always, ImVec2(0.5f, 0.5f)); + + // Stays behind everything else, e.g. the drawers + auto flags = ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoDocking | ImGuiWindowFlags_NoSavedSettings | + ImGuiWindowFlags_NoBackground | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_AlwaysAutoResize | + ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoFocusOnAppearing; + ImGui::Begin("##Empty state", nullptr, flags); + + if (!waitToLoadScenes.empty()) { + auto heading = "Loading " + std::to_string(waitToLoadScenes.size()) + " scenes..."; + if (waitToLoadScenes.size() <= 3) { + std::string names; + for (const auto& handle : waitToLoadScenes) + names += (names.empty() ? "" : ", ") + Common::Path::GetFileNameWithoutExtension(handle.GetResource()->path); + heading = "Loading " + names + "..."; + } + + // The spinner is centered above the heading, the window sizes itself to the heading + auto textWidth = ImGui::CalcTextSize(heading.c_str()).x * UI::Widgets::headingScale; + ImGui::SetCursorPosX(ImGui::GetCursorPosX() + std::max(0.0f, (textWidth - ImGui::GetTextLineHeight() * 2.0f) * 0.5f)); + UI::Widgets::Spinner(2.0f); + UI::Widgets::Heading(heading.c_str()); + ImGui::End(); + return; + } + + ImGui::SetWindowFontScale(1.5f); + ImGui::TextUnformatted("No scene open"); + ImGui::SetWindowFontScale(1.0f); + ImGui::TextDisabled("Create a new scene or open one from the content browser"); + + ImGui::Dummy(ImVec2(0.0f, 4.0f)); + + Theme::PushPrimaryButton(); + if (ImGui::Button("New scene...")) + UI::PopupPanels::isNewScenePopupVisible = true; + Theme::PopPrimaryButton(); + ImGui::SameLine(); + if (ImGui::Button("Content browser")) + contentBrowserWindow.show = true; + + // Scenes might have been moved or deleted in the meantime, which is checked once when the state shows up + if (!emptyStateVisible) { + emptyStateScenes.clear(); + for (const auto& path : config->recentScenes) { + if (emptyStateScenes.size() < 5 && std::filesystem::exists(Loader::AssetLoader::GetFullPath(path))) + emptyStateScenes.push_back(path); + } + } + emptyStateVisible = true; + + if (!emptyStateScenes.empty()) { + ImGui::Dummy(ImVec2(0.0f, 4.0f)); + ImGui::SeparatorText("Recent scenes"); + } + + std::string openPath; + for (const auto& path : emptyStateScenes) { + auto name = Common::Path::GetFileNameWithoutExtension(path); + if (ImGui::Selectable((name + "##" + path).c_str())) + openPath = path; + ImGui::SetItemTooltip("%s", path.c_str()); + } + + ImGui::End(); + + if (!openPath.empty()) + FileImporter::ImportFile(openPath); + + } - auto center = ImVec2(centralNode->Pos.x + centralNode->Size.x * 0.5f, - centralNode->Pos.y + centralNode->Size.y * 0.5f); + void App::ApplyTheme() { - auto titleWidth = font->CalcTextSizeA(titleSize, FLT_MAX, 0.0f, title).x; - auto subtitleWidth = font->CalcTextSizeA(fontSize, FLT_MAX, 0.0f, subtitle).x; + Theme::Apply(Singletons::config->darkMode); - drawList->AddText(font, titleSize, ImVec2(center.x - titleWidth * 0.5f, center.y - titleSize), - ImGui::GetColorU32(ImGuiCol_Text), title); - drawList->AddText(font, fontSize, ImVec2(center.x - subtitleWidth * 0.5f, center.y + fontSize * 0.5f), - ImGui::GetColorU32(Theme::TextMuted()), subtitle); + auto base = Theme::Base(); + window.SetTitleBarColor(vec3(base.x, base.y, base.z), Singletons::config->darkMode); + + } + + void App::UpdateUiScale() { + + auto systemScale = window.GetContentScale(); + auto scale = glm::clamp(Singletons::config->uiScale > 0.0f ? Singletons::config->uiScale : systemScale, 0.5f, 3.0f); + + // The window was moved to a display with another scale + if (Singletons::config->uiScale <= 0.0f && systemUiScale > 0.0f && systemScale != systemUiScale) + Notifications::Push({ .message = "Scaled the interface to " + std::to_string(int32_t(std::round(scale * 100.0f))) + + "% for this display" }); + systemUiScale = systemScale; + + Singletons::imguiWrapper->SetScale(scale); + + // Minimized windows can have no size at all, the font is kept for when they come back + auto drawableSize = window.GetDrawableSize(); + if (drawableSize.x <= 0 || window.GetWidth() <= 0) + return; + + // Text is rasterized for the pixels it covers, but at least at twice its size such that larger text stays sharp + auto pixelDensity = float(drawableSize.x) / float(window.GetWidth()); + auto rasterSize = std::round(16.0f * std::max(2.0f, pixelDensity * scale)); + if (rasterSize == fontRasterSize) + return; + fontRasterSize = rasterSize; + + auto& io = ImGui::GetIO(); + io.Fonts->Clear(); + io.Fonts->AddFontFromFileTTF(Loader::AssetLoader::GetFullPath("font/roboto.ttf").c_str(), rasterSize)->Scale = 16.0f / rasterSize; + // Code is shown with the regular font if this one is missing + Theme::codeFont = io.Fonts->AddFontFromFileTTF(Loader::AssetLoader::GetFullPath("font/robotomono.ttf").c_str(), rasterSize); + if (Theme::codeFont) + Theme::codeFont->Scale = 15.0f / rasterSize; + Singletons::imguiWrapper->RecreateImGuiResources(); + + } + + void App::Undo() { + + if (activeCodeEditorWindow) { + activeCodeEditorWindow->Undo(); + return; + } + + if (projectSettingsWindow.inFocus) { + projectSettingsWindow.history.Undo(); + return; + } + + if (activeAssetEditorWindow) { + activeAssetEditorWindow->Undo(); + return; + } + + auto sceneWindow = GetActiveSceneWindow(); + if (sceneWindow && !sceneWindow->isPlaying) + sceneWindow->Undo(); + + } + + void App::Redo() { + + if (activeCodeEditorWindow) { + activeCodeEditorWindow->Redo(); + return; + } + + if (projectSettingsWindow.inFocus) { + projectSettingsWindow.history.Redo(); + return; + } + + if (activeAssetEditorWindow) { + activeAssetEditorWindow->Redo(); + return; + } + + auto sceneWindow = GetActiveSceneWindow(); + if (sceneWindow && !sceneWindow->isPlaying) + sceneWindow->Redo(); + + } + + bool App::CanUndo() const { + + if (activeCodeEditorWindow) + return activeCodeEditorWindow->CanUndo(); + auto history = GetActiveHistory(); + return history && history->CanUndo(); + + } + + bool App::CanRedo() const { + + if (activeCodeEditorWindow) + return activeCodeEditorWindow->CanRedo(); + auto history = GetActiveHistory(); + return history && history->CanRedo(); + + } + + const UndoHistory* App::GetActiveHistory() const { + + if (projectSettingsWindow.inFocus) + return &projectSettingsWindow.history; + + if (activeAssetEditorWindow) + return &activeAssetEditorWindow->history; + + auto sceneWindow = GetActiveSceneWindow(); + if (!sceneWindow || sceneWindow->isPlaying) + return nullptr; + return &sceneWindow->history.history; } @@ -521,26 +1245,44 @@ namespace Atlas::Editor { }; // File + commandPalette.Register({ .category = "File", .name = "New project...", + .action = [this]() { projectHub->OpenNewProjectPopup(); } }); + commandPalette.Register({ .category = "File", .name = "Open project...", + .action = [this]() { OpenProject(""); } }); + commandPalette.Register({ .category = "File", .name = "Export Lua annotations", + .action = [this]() { ExportLuaAnnotations(); } }); commandPalette.Register({ .category = "File", .name = "New scene...", .action = []() { UI::PopupPanels::isNewScenePopupVisible = true; } }); + commandPalette.Register({ .category = "File", .name = "Save project", + .action = [this]() { projectSettingsWindow.Save(Singletons::project); }, + .isEnabled = [this]() { return projectSettingsWindow.hasUnsavedChanges; } }); commandPalette.Register({ .category = "File", .name = "Save scene", .shortcut = "Ctrl+S", .action = [this]() { GetActiveSceneWindow()->SaveScene(); }, .isEnabled = canEdit }); // Windows - auto registerWindow = [&](const char* name, bool* show) { - commandPalette.Register({ .category = "Window", .name = std::string("Toggle ") + name, + auto registerWindow = [&](const char* name, bool* show, const char* shortcut = "") { + commandPalette.Register({ .category = "Window", .name = std::string("Toggle ") + name, .shortcut = shortcut, .action = [show]() { *show = !*show; }, .isChecked = [show]() { return *show; } }); }; - registerWindow("content browser", &contentBrowserWindow.show); - registerWindow("log", &logWindow.show); + registerWindow("content browser", &contentBrowserWindow.show, "Ctrl+B"); + registerWindow("log", &logWindow.show, "Ctrl+J"); + auto registerPin = [&](const char* name, UI::DrawerWindow* drawer) { + commandPalette.Register({ .category = "Window", .name = std::string("Dock ") + name + " in layout", + .action = [drawer]() { drawer->SetPinned(!drawer->pinned); }, + .isChecked = [drawer]() { return drawer->pinned; } }); + }; + registerPin("content browser", &contentBrowserWindow); + registerPin("log", &logWindow); registerWindow("profiler", &profilerWindow.show); + registerPin("profiler", &profilerWindow); + registerWindow("project settings", &projectSettingsWindow.show); registerWindow("geometry brush", &geometryBrushWindow.show); commandPalette.Register({ .category = "Window", .name = "Reset layout", .action = [this]() { resetDockspaceLayout = true; } }); // Appearance and renderer commandPalette.Register({ .category = "View", .name = "Toggle dark mode", - .action = [&config]() { config->darkMode = !config->darkMode; Theme::Apply(config->darkMode); }, + .action = [this, &config]() { config->darkMode = !config->darkMode; ApplyTheme(); }, .isChecked = [&config]() { return config->darkMode; } }); commandPalette.Register({ .category = "Renderer", .name = "Toggle VSync", .action = [&config]() { config->vsync = !config->vsync; }, @@ -562,10 +1304,42 @@ namespace Atlas::Editor { commandPalette.Register({ .category = "Viewport", .name = "Focus selection", .shortcut = "F", .action = [this]() { GetActiveSceneWindow()->FocusSelection(); }, .isEnabled = canEdit }); + commandPalette.Register({ .category = "Viewport", .name = "Drop selection to ground", .shortcut = "End", + .action = [this]() { GetActiveSceneWindow()->DropSelectionToGround(); }, .isEnabled = canEdit }); + commandPalette.Register({ .category = "Properties", .name = "Search entity properties", .shortcut = "Ctrl+F", + .action = [this]() { + auto& panel = GetActiveSceneWindow()->scenePropertiesPanel; + panel.entityPropertiesPanel.focusSearch = true; + ImGui::SetWindowFocus(panel.GetNameID()); + }, + .isEnabled = [this, hasScene]() { return hasScene() && GetActiveSceneWindow()->sceneHierarchyPanel.selectedEntity.IsValid(); } }); + auto isViewingCamera = [this, canEdit]() { + return canEdit() && GetActiveSceneWindow()->viewedCameraEntity.IsValid(); + }; + commandPalette.Register({ .category = "Viewport", .name = "View through selected camera", + .action = [this]() { auto window = GetActiveSceneWindow(); window->ViewThroughCamera(window->sceneHierarchyPanel.selectedEntity); }, + .isEnabled = [this, canEdit]() { + if (!canEdit()) + return false; + auto entity = GetActiveSceneWindow()->sceneHierarchyPanel.selectedEntity; + return entity.IsValid() && entity.HasComponent(); + } }); + commandPalette.Register({ .category = "Viewport", .name = "Apply view to camera", + .action = [this]() { GetActiveSceneWindow()->ApplyViewToCamera(); }, .isEnabled = isViewingCamera }); + commandPalette.Register({ .category = "Viewport", .name = "Back to editor camera", + .action = [this]() { GetActiveSceneWindow()->ReturnToEditorCamera(); }, .isEnabled = isViewingCamera }); commandPalette.Register({ .category = "Viewport", .name = "Toggle grid", .shortcut = "G", .action = [this]() { auto window = GetActiveSceneWindow(); window->showGrid = !window->showGrid; }, .isEnabled = canEdit, .isChecked = [this]() { auto window = GetActiveSceneWindow(); return window && window->showGrid; } }); + commandPalette.Register({ .category = "Viewport", .name = "Toggle physics", + .action = [this]() { auto window = GetActiveSceneWindow(); window->showPhysics = !window->showPhysics; }, + .isEnabled = hasScene, + .isChecked = [this]() { auto window = GetActiveSceneWindow(); return window && window->showPhysics; } }); + commandPalette.Register({ .category = "Viewport", .name = "Toggle navigation mesh", + .action = [this]() { auto& panel = GetActiveSceneWindow()->scenePropertiesPanel.navigationPanel; panel.showMesh = !panel.showMesh; }, + .isEnabled = hasScene, + .isChecked = [this]() { auto window = GetActiveSceneWindow(); return window && window->scenePropertiesPanel.navigationPanel.showMesh; } }); commandPalette.Register({ .category = "Viewport", .name = "Toggle gizmo snapping", .action = [this]() { auto& guizmo = GetActiveSceneWindow()->guizmo; guizmo.snappingEnabled = !guizmo.snappingEnabled; }, .isEnabled = canEdit, @@ -606,14 +1380,94 @@ namespace Atlas::Editor { registerCreate("Camera", UI::SceneHierarchyPanel::EntityTemplate::Camera); registerCreate("Audio source", UI::SceneHierarchyPanel::EntityTemplate::AudioSource); registerCreate("Text", UI::SceneHierarchyPanel::EntityTemplate::Text); + registerCreate("Fog volume", UI::SceneHierarchyPanel::EntityTemplate::FogVolume); // Scene commandPalette.Register({ .category = "Scene", .name = "Play", .action = [this]() { GetActiveSceneWindow()->StartPlaying(); }, .isEnabled = canEdit }); + commandPalette.Register({ .category = "Scene", .name = "Pause or resume playing", + .action = [this]() { GetActiveSceneWindow()->TogglePause(); }, + .isEnabled = [this, hasScene]() { return hasScene() && GetActiveSceneWindow()->isPlaying; } }); commandPalette.Register({ .category = "Scene", .name = "Stop playing", .shortcut = "Ctrl+Q", .action = [this]() { GetActiveSceneWindow()->StopPlaying(); }, .isEnabled = [this, hasScene]() { return hasScene() && GetActiveSceneWindow()->isPlaying; } }); + // Undo of the asset editor or scene in front + commandPalette.Register({ .category = "Edit", .name = "Undo", .shortcut = "Ctrl+Z", + .action = [this]() { Undo(); }, + .isEnabled = [this]() { return CanUndo(); } }); + commandPalette.Register({ .category = "Edit", .name = "Redo", .shortcut = "Ctrl+Shift+Z", + .action = [this]() { Redo(); }, + .isEnabled = [this]() { return CanRedo(); } }); + + // Material graph of the material editor in front + auto materialEditor = [this]() { + return std::dynamic_pointer_cast(activeAssetEditorWindow); + }; + auto hasMaterialGraph = [materialEditor]() { + auto window = materialEditor(); + return window && window->material.IsLoaded() && window->material->HasGraph(); + }; + commandPalette.Register({ .category = "Material graph", .name = "Add node", .shortcut = "Space", + .action = [materialEditor]() { materialEditor()->graphPanel.OpenAddMenu(); }, .isEnabled = hasMaterialGraph }); + commandPalette.Register({ .category = "Material graph", .name = "Frame all nodes", .shortcut = "F", + .action = [materialEditor]() { materialEditor()->graphPanel.FrameAll(); }, .isEnabled = hasMaterialGraph }); + commandPalette.Register({ .category = "Material graph", .name = "Arrange nodes", + .action = [materialEditor]() { auto window = materialEditor(); window->graphPanel.Arrange(*window->material->graph.Get()); }, + .isEnabled = hasMaterialGraph }); + commandPalette.Register({ .category = "Material graph", .name = "Show generated code", + .action = [materialEditor]() { materialEditor()->graphPanel.ShowGeneratedCode(); }, .isEnabled = hasMaterialGraph }); + commandPalette.Register({ .category = "Material graph", .name = "Select all nodes", .shortcut = "Ctrl+A", + .action = [materialEditor]() { auto window = materialEditor(); window->graphPanel.SelectAll(*window->material->graph.Get()); }, + .isEnabled = hasMaterialGraph }); + commandPalette.Register({ .category = "Material graph", .name = "Delete selected nodes", .shortcut = "Del", + .action = [materialEditor]() { auto window = materialEditor(); window->graphPanel.DeleteSelection(*window->material->graph.Get()); }, + .isEnabled = hasMaterialGraph }); + commandPalette.Register({ .category = "Material graph", .name = "Copy selected nodes", .shortcut = "Ctrl+C", + .action = [materialEditor]() { auto window = materialEditor(); window->graphPanel.CopySelection(*window->material->graph.Get()); }, + .isEnabled = hasMaterialGraph }); + commandPalette.Register({ .category = "Material graph", .name = "Paste nodes", .shortcut = "Ctrl+V", + .action = [materialEditor]() { auto window = materialEditor(); window->graphPanel.Paste(*window->material->graph.Get()); }, + .isEnabled = hasMaterialGraph }); + commandPalette.Register({ .category = "Material graph", .name = "Duplicate selected nodes", .shortcut = "Ctrl+D", + .action = [materialEditor]() { auto window = materialEditor(); window->graphPanel.DuplicateSelection(*window->material->graph.Get()); }, + .isEnabled = hasMaterialGraph }); + commandPalette.Register({ .category = "Material graph", .name = "Frame selected nodes", .shortcut = "Ctrl+G", + .action = [materialEditor]() { auto window = materialEditor(); window->graphPanel.FrameSelection(*window->material->graph.Get()); }, + .isEnabled = hasMaterialGraph }); + commandPalette.Register({ .category = "Material graph", .name = "Toggle maximized", .shortcut = "F11", + .action = [materialEditor]() { materialEditor()->graphPanel.ToggleMaximized(); }, .isEnabled = hasMaterialGraph }); + + // Code window in front + auto hasCodeWindow = [this]() { return activeCodeEditorWindow != nullptr; }; + commandPalette.Register({ .category = "Code", .name = "Save file", .shortcut = "Ctrl+S", + .action = [this]() { activeCodeEditorWindow->Save(); }, .isEnabled = hasCodeWindow }); + commandPalette.Register({ .category = "Code", .name = "Find in file", .shortcut = "Ctrl+F", + .action = [this]() { activeCodeEditorWindow->OpenSearch(false); }, .isEnabled = hasCodeWindow }); + commandPalette.Register({ .category = "Code", .name = "Replace in file", .shortcut = "Ctrl+H", + .action = [this]() { activeCodeEditorWindow->OpenSearch(true); }, .isEnabled = hasCodeWindow }); + + // Asset editor in front + auto hasAssetEditor = [this]() { return activeAssetEditorWindow != nullptr; }; + commandPalette.Register({ .category = "Asset editor", .name = "Save asset", .shortcut = "Ctrl+S", + .action = [this]() { activeAssetEditorWindow->Save(); activeAssetEditorWindow->hasUnsavedChanges = false; }, + .isEnabled = hasAssetEditor }); + commandPalette.Register({ .category = "Asset editor", .name = "Focus asset", .shortcut = "F", + .action = [this]() { activeAssetEditorWindow->FocusAsset(); }, .isEnabled = hasAssetEditor }); + commandPalette.Register({ .category = "Asset editor", .name = "Toggle grid", .shortcut = "G", + .action = [this]() { activeAssetEditorWindow->showGrid = !activeAssetEditorWindow->showGrid; }, .isEnabled = hasAssetEditor }); + + // Animation timeline of the mesh editor in front + auto meshEditor = [this]() { + return std::dynamic_pointer_cast(activeAssetEditorWindow); + }; + commandPalette.Register({ .category = "Animation timeline", .name = "Save animation", + .action = [meshEditor]() { meshEditor()->timelinePanel.saveRequested = true; }, + .isEnabled = [meshEditor]() { return meshEditor() != nullptr; } }); + commandPalette.Register({ .category = "Animation timeline", .name = "Delete selected key", .shortcut = "Del", + .action = [meshEditor]() { meshEditor()->timelinePanel.deleteKeyRequested = true; }, + .isEnabled = [meshEditor]() { auto window = meshEditor(); return window && window->timelinePanel.HasSelectedKey(); } }); + // Help commandPalette.Register({ .category = "Help", .name = "Keyboard shortcuts", .action = [this]() { showShortcutsWindow = true; } }); @@ -645,7 +1499,7 @@ namespace Atlas::Editor { if (!exists) ImGui::SetItemTooltip("File doesn't exist anymore"); else if (loadFailed) - ImGui::SetItemTooltip("Loading failed: %s", openedIter->GetResource()->exceptionOnLoad.what()); + ImGui::SetItemTooltip("Loading failed: %s", openedIter->GetResource()->errorMessageOnLoad.c_str()); else ImGui::SetItemTooltip("%s", path.c_str()); } @@ -666,65 +1520,153 @@ namespace Atlas::Editor { auto viewport = ImGui::GetMainViewport(); auto flags = ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_MenuBar; - auto divider = []() { - ImGui::SameLine(); - ImGui::SeparatorEx(ImGuiSeparatorFlags_Vertical); - ImGui::SameLine(); + auto gap = [](float width) { + ImGui::SameLine(0.0f, width); + }; + + // Plain text shares the vertical center with the labels of the chips + auto text = [&](const char* str, ImGuiCol color) { + auto pos = ImGui::GetCursorScreenPos(); + auto height = ImGui::GetFrameHeight(); + ImGui::Dummy(ImVec2(ImGui::CalcTextSize(str).x, height)); + ImGui::GetWindowDrawList()->AddText(ImVec2(pos.x, GetCapCenteredTextY(pos.y + height * 0.5f)), + ImGui::GetColorU32(color), str); }; ImGui::PushStyleColor(ImGuiCol_MenuBarBg, Theme::Base()); - if (ImGui::BeginViewportSideBar("##Status bar", viewport, ImGuiDir_Down, ImGui::GetFrameHeight(), flags)) { + if (ImGui::BeginViewportSideBar("##Status bar", viewport, ImGuiDir_Down, ImGui::GetFrameHeight() + 4.0f, flags)) { if (ImGui::BeginMenuBar()) { + auto window = ImGui::GetCurrentWindow(); + window->DrawList->AddLine(window->Pos, ImVec2(window->Pos.x + window->Size.x, window->Pos.y), + ImGui::GetColorU32(ImGuiCol_Border)); + + auto warningCount = logWindow.GetUnseenWarningCount(); + auto errorCount = logWindow.GetUnseenErrorCount(); + + // The drawers chosen for the status bar, a right click on it changes them + auto contentBrowserHovered = false; + auto firstDrawer = true; + for (const auto& name : Singletons::config->statusBarDrawers) { + auto drawer = FindDrawer(name); + if (!drawer) + continue; + if (!firstDrawer) + gap(4.0f); + firstDrawer = false; + + auto isLog = drawer->window == &logWindow; + auto hovered = RenderDrawerButton(*drawer->window, drawer->icon, drawer->name, drawer->shortcut, + isLog ? errorCount : 0, isLog ? warningCount : 0); + if (drawer->window == &contentBrowserWindow) + contentBrowserHovered = hovered; + } + + // Dragging something onto the button opens the content browser as a drop target + auto isDragging = ImGui::IsDragDropActive(); + drawerSpringTime = isDragging && contentBrowserHovered ? drawerSpringTime + ImGui::GetIO().DeltaTime : 0.0f; + if (drawerSpringTime > 0.35f) + contentBrowserWindow.show = true; + + RenderStatusBarMenu(); + + gap(16.0f); + + // Context is plain information, it stays quiet next to the things that can be clicked auto sceneWindow = GetActiveSceneWindow(); + std::string guizmoText; if (sceneWindow && sceneWindow->scene.IsLoaded()) { - if (sceneWindow->isPlaying) - ImGui::TextColored(Theme::Success(), "Playing"); - else - ImGui::TextDisabled("Editing"); + if (sceneWindow->isPlaying) { + RenderStatusChip("##Playing", IconType::Play, "Playing", Theme::Success(), Theme::Success(0.16f), Theme::Success(0.16f)); + gap(8.0f); + } - divider(); - ImGui::TextUnformatted(sceneWindow->scene->name.c_str()); + auto sceneLabel = sceneWindow->IsPrefab() ? Common::Path::GetFileName(sceneWindow->prefabPath) : + UI::SceneWindow::GetSceneLabel(sceneWindow->scene); + text(sceneLabel.c_str(), ImGuiCol_Text); - divider(); const auto& selection = sceneWindow->sceneHierarchyPanel.selectedEntities; auto selectedEntity = sceneWindow->sceneHierarchyPanel.selectedEntity; - if (selection.empty()) { - ImGui::TextDisabled("Nothing selected"); - } - else if (selection.size() == 1 && selectedEntity.IsValid()) { - auto nameComponent = selectedEntity.TryGetComponent(); - auto name = nameComponent ? nameComponent->name : "Entity " + std::to_string(selectedEntity); - ImGui::TextDisabled("Selected"); - ImGui::SameLine(); - ImGui::TextUnformatted(name.c_str()); - } - else { - ImGui::Text("%d entities selected", int32_t(selection.size())); + if (!selection.empty()) { + gap(6.0f); + text("/", ImGuiCol_TextDisabled); + gap(6.0f); + if (selection.size() == 1 && selectedEntity.IsValid()) { + auto nameComponent = selectedEntity.TryGetComponent(); + auto name = nameComponent ? nameComponent->name : "Entity " + std::to_string(selectedEntity); + text(name.c_str(), ImGuiCol_Text); + } + else { + text((std::to_string(selection.size()) + " entities").c_str(), ImGuiCol_Text); + } } - divider(); const auto& guizmo = sceneWindow->guizmo; - const char* modeName = guizmo.mode == ImGuizmo::OPERATION::ROTATE ? "Rotate" : + guizmoText = guizmo.mode == ImGuizmo::OPERATION::ROTATE ? "Rotate" : guizmo.mode == ImGuizmo::OPERATION::SCALE ? "Scale" : "Translate"; - ImGui::TextDisabled("%s, %s%s", modeName, guizmo.objectSpace ? "local" : "world", - guizmo.snappingEnabled ? ", snapping" : ""); + guizmoText += guizmo.objectSpace ? " \xC2\xB7 Local" : " \xC2\xB7 World"; + if (guizmo.snappingEnabled) + guizmoText += " \xC2\xB7 Snapping"; } else { - ImGui::TextDisabled("No scene open"); + text("No scene open", ImGuiCol_TextDisabled); } - // Performance on the right side + // Jobs come in bursts, the peak of the last half second avoids a flickering count. Short work isn't mentioned + auto deltaTime = ImGui::GetIO().DeltaTime; + auto backgroundJobs = JobSystem::GetPendingJobCount(JobPriority::Medium) + + JobSystem::GetPendingJobCount(JobPriority::Low); + backgroundJobPeak = std::max(backgroundJobPeak, backgroundJobs); + + backgroundJobRefreshTime += deltaTime; + if (backgroundJobRefreshTime > 0.5f || backgroundJobShown == 0) { + backgroundJobShown = backgroundJobPeak; + backgroundJobPeak = backgroundJobs; + backgroundJobRefreshTime = 0.0f; + } + backgroundJobTime = backgroundJobShown > 0 ? backgroundJobTime + deltaTime : 0.0f; + + if (backgroundJobTime > 0.5f && backgroundJobShown > 0) { + gap(16.0f); + const char* dots[] = { ".", "..", "..." }; + char jobText[64]; + std::snprintf(jobText, sizeof(jobText), "%d background %s%s", backgroundJobShown, backgroundJobShown == 1 ? "job" : "jobs", + dots[int32_t(ImGui::GetTime() * 2.0) % 3]); + text(jobText, ImGuiCol_TextDisabled); + } + + // Gizmo mode, performance and the notifications on the right side auto frameTime = Clock::GetAverage() * 1000.0f; - char rightText[64]; - std::snprintf(rightText, sizeof(rightText), "%.1f ms %.0f fps", - frameTime, frameTime > 0.0f ? 1000.0f / frameTime : 0.0f); - auto rightWidth = ImGui::CalcTextSize(rightText).x + ImGui::GetStyle().ItemSpacing.x; + char rightText[128]; + std::snprintf(rightText, sizeof(rightText), "%s%s%.1f ms \xC2\xB7 %.0f fps", guizmoText.c_str(), + guizmoText.empty() ? "" : " ", frameTime, frameTime > 0.0f ? 1000.0f / frameTime : 0.0f); + auto notificationWidth = GetStatusChipWidth("", GetNotificationBadgeWidth(Notifications::GetUnreadCount())); + auto rightWidth = ImGui::CalcTextSize(rightText).x + ImGui::GetStyle().ItemSpacing.x + notificationWidth; auto rightPos = ImGui::GetWindowContentRegionMax().x - rightWidth; + + // The problem nobody has seen yet takes the room in between and opens the log + if (warningCount + errorCount > 0 && !logWindow.GetLastProblem().empty()) { + gap(16.0f); + auto maxWidth = rightPos - ImGui::GetCursorPosX() - 16.0f; + auto isError = logWindow.IsLastProblemError(); + auto color = isError ? Theme::Error() : Theme::Warning(); + auto background = isError ? Theme::Error(0.1f) : Theme::Warning(0.1f); + auto backgroundHovered = isError ? Theme::Error(0.22f) : Theme::Warning(0.22f); + if (maxWidth > 80.0f) { + if (RenderStatusChip("##Last problem", isError ? IconType::Error : IconType::Warning, + logWindow.GetLastProblem().c_str(), color, background, backgroundHovered, maxWidth)) + logWindow.show = true; + ImGui::SetItemTooltip("%s\nClick to open the log", logWindow.GetLastProblem().c_str()); + } + } + if (rightPos > ImGui::GetCursorPosX()) { ImGui::SameLine(rightPos); - ImGui::TextDisabled("%s", rightText); + text(rightText, ImGuiCol_TextDisabled); } + ImGui::SameLine(ImGui::GetWindowContentRegionMax().x - notificationWidth); + RenderNotificationButton(); + ImGui::EndMenuBar(); } } @@ -734,6 +1676,516 @@ namespace Atlas::Editor { } + bool App::RenderStatusChip(const char* id, IconType icon, const char* text, ImVec4 color, + ImVec4 background, ImVec4 backgroundHovered, float maxWidth, float trailingWidth) { + + const float padding = 8.0f; + // Chips without text only show their icon + const float iconGap = text[0] ? 5.0f : 0.0f; + + auto fontSize = ImGui::GetFontSize(); + auto iconSize = fontSize; + auto textSize = ImGui::CalcTextSize(text); + auto width = std::min(GetStatusChipWidth(text, trailingWidth), maxWidth); + auto height = ImGui::GetFrameHeight(); + + // Pressing on click, since a drawer that is open closes itself when the mouse goes down outside of it + auto pos = ImGui::GetCursorScreenPos(); + auto pressed = ImGui::InvisibleButton(id, ImVec2(width, height), ImGuiButtonFlags_PressedOnClick); + auto hovered = ImGui::IsItemHovered(); + + auto drawList = ImGui::GetWindowDrawList(); + auto min = ImVec2(pos.x, pos.y + 2.0f); + auto max = ImVec2(pos.x + width, pos.y + height - 2.0f); + drawList->AddRectFilled(min, max, ImGui::GetColorU32(hovered ? backgroundHovered : background), 5.0f); + + auto centerY = (min.y + max.y) * 0.5f; + auto iconMin = ImVec2(min.x + padding, centerY - iconSize * 0.5f); + auto set = Singletons::imguiWrapper->GetTextureId(&Singletons::icons->GetTintable(icon)); + drawList->AddImage(set, iconMin, ImVec2(iconMin.x + iconSize, iconMin.y + iconSize), + ImVec2(0.1f, 0.1f), ImVec2(0.9f, 0.9f), ImGui::GetColorU32(color)); + + auto textMin = ImVec2(iconMin.x + iconSize + iconGap, GetCapCenteredTextY(centerY)); + auto textMaxX = max.x - padding - trailingWidth; + ImGui::PushStyleColor(ImGuiCol_Text, color); + ImGui::RenderTextEllipsis(drawList, textMin, ImVec2(textMaxX, max.y), textMaxX, textMaxX, text, nullptr, &textSize); + ImGui::PopStyleColor(); + + return pressed; + + } + + float App::GetStatusChipWidth(const char* text, float trailingWidth) { + + // Padding, icon, the gap to the text and the text, chips without text only show their icon + auto iconGap = text[0] ? 5.0f : 0.0f; + return 8.0f + ImGui::GetFontSize() + iconGap + ImGui::CalcTextSize(text).x + trailingWidth + 8.0f; + + } + + float App::GetNotificationBadgeWidth(int32_t unreadCount) { + + // Gap to the icon and the padded count + return unreadCount > 0 ? 6.0f + ImGui::CalcTextSize(std::to_string(unreadCount).c_str()).x + 10.0f : 0.0f; + + } + + void App::RenderNotificationButton() { + + auto unreadCount = Notifications::GetUnreadCount(); + auto hasError = unreadCount > 0 && Notifications::HasUnreadError(); + auto countText = std::to_string(unreadCount); + auto badgeWidth = GetNotificationBadgeWidth(unreadCount); + + auto active = notificationsOpen || unreadCount > 0; + auto color = active ? ImGui::GetStyleColorVec4(ImGuiCol_Text) : Theme::TextMuted(); + auto background = notificationsOpen ? Theme::Accent(0.35f) : Theme::TextMuted(0.12f); + auto backgroundHovered = notificationsOpen ? Theme::Accent(0.45f) : Theme::TextMuted(0.22f); + + // The popup closes itself when the mouse goes down outside of it, a click on the button shouldn't open it again + auto wasOpen = notificationsOpen; + if (RenderStatusChip("##Notifications", IconType::Notifications, "", color, background, backgroundHovered, + FLT_MAX, badgeWidth) && !wasOpen) + ImGui::OpenPopup("##Notification center"); + if (unreadCount > 0) + ImGui::SetItemTooltip("%d new %s", unreadCount, unreadCount == 1 ? "notification" : "notifications"); + else + ImGui::SetItemTooltip("Notifications"); + + auto itemMin = ImGui::GetItemRectMin(); + auto itemMax = ImGui::GetItemRectMax(); + if (unreadCount > 0) { + auto badgeColor = hasError ? Theme::Error() : Theme::Accent(); + auto min = ImVec2(itemMax.x - 8.0f - badgeWidth + 6.0f, itemMin.y + 5.0f); + auto max = ImVec2(itemMax.x - 8.0f, itemMax.y - 5.0f); + auto drawList = ImGui::GetWindowDrawList(); + drawList->AddRectFilled(min, max, ImGui::GetColorU32(badgeColor), (max.y - min.y) * 0.5f); + drawList->AddText(ImVec2(min.x + 5.0f, GetCapCenteredTextY((min.y + max.y) * 0.5f)), + ImGui::GetColorU32(ImVec4(1.0f, 1.0f, 1.0f, 1.0f)), countText.c_str()); + } + + ImGui::SetNextWindowPos(ImVec2(itemMax.x, itemMin.y - 6.0f), ImGuiCond_Always, ImVec2(1.0f, 1.0f)); + notificationsOpen = ImGui::BeginPopup("##Notification center"); + if (notificationsOpen) { + // Everything that is visible while it is open counts as read + Notifications::MarkAsRead(); + Notifications::DisplayHistory(); + if (ImGui::IsKeyPressed(ImGuiKey_Escape)) + ImGui::CloseCurrentPopup(); + ImGui::EndPopup(); + } + + } + + float App::GetCapCenteredTextY(float centerY) { + + // The line height includes room for descenders, labels look centered when their capitals are + auto font = ImGui::GetFont(); + auto scale = ImGui::GetFontSize() / font->FontSize; + auto glyph = font->FindGlyph('H'); + return centerY - (glyph->Y0 + glyph->Y1) * 0.5f * scale; + + } + + bool App::RenderDrawerButton(UI::DrawerWindow& drawer, IconType icon, const char* label, const char* shortcut, + int32_t errorCount, int32_t warningCount) { + + const float badgeGap = 6.0f; + const float badgePadding = 5.0f; + const float badgeIconGap = 3.0f; + + auto color = drawer.show ? ImGui::GetStyleColorVec4(ImGuiCol_Text) : Theme::TextMuted(); + auto background = drawer.show ? Theme::Accent(0.35f) : Theme::TextMuted(0.12f); + auto backgroundHovered = drawer.show ? Theme::Accent(0.45f) : Theme::TextMuted(0.22f); + + // New warnings and errors are shown as badges inside of the button + struct Badge { + IconType icon; + ImVec4 color; + int32_t count; + const char* name; + char text[16]; + float width; + }; + Badge badges[] = { + { IconType::Error, Theme::Error(), errorCount, "errors" }, + { IconType::Warning, Theme::Warning(), warningCount, "warnings" } + }; + + auto badgeIconSize = ImGui::GetFontSize() * 0.9f; + auto trailingWidth = 0.0f; + for (auto& badge : badges) { + if (badge.count <= 0) + continue; + std::snprintf(badge.text, sizeof(badge.text), "%d", badge.count); + badge.width = badgePadding + badgeIconSize + badgeIconGap + ImGui::CalcTextSize(badge.text).x + badgePadding; + trailingWidth += badgeGap + badge.width; + } + + if (RenderStatusChip(label, icon, label, color, background, backgroundHovered, FLT_MAX, trailingWidth)) + drawer.show = !drawer.show; + auto hovered = ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem); + + auto drawList = ImGui::GetWindowDrawList(); + auto itemMin = ImGui::GetItemRectMin(); + auto itemMax = ImGui::GetItemRectMax(); + auto fontSize = ImGui::GetFontSize(); + auto x = itemMax.x - 8.0f - trailingWidth; + const Badge* hoveredBadge = nullptr; + for (const auto& badge : badges) { + if (badge.count <= 0) + continue; + x += badgeGap; + auto min = ImVec2(x, itemMin.y + 5.0f); + auto max = ImVec2(x + badge.width, itemMax.y - 5.0f); + drawList->AddRectFilled(min, max, ImGui::GetColorU32(ImVec4(badge.color.x, badge.color.y, badge.color.z, 0.2f)), 4.0f); + + auto iconMin = ImVec2(min.x + badgePadding, (itemMin.y + itemMax.y - badgeIconSize) * 0.5f); + auto set = Singletons::imguiWrapper->GetTextureId(&Singletons::icons->GetTintable(badge.icon)); + drawList->AddImage(set, iconMin, ImVec2(iconMin.x + badgeIconSize, iconMin.y + badgeIconSize), + ImVec2(0.1f, 0.1f), ImVec2(0.9f, 0.9f), ImGui::GetColorU32(badge.color)); + drawList->AddText(ImVec2(iconMin.x + badgeIconSize + badgeIconGap, GetCapCenteredTextY((itemMin.y + itemMax.y) * 0.5f)), + ImGui::GetColorU32(badge.color), badge.text); + + if (hovered && ImGui::IsMouseHoveringRect(min, max)) + hoveredBadge = &badge; + x += badge.width; + } + + if (hoveredBadge) + ImGui::SetItemTooltip("%d new %s", hoveredBadge->count, hoveredBadge->name); + else if (*shortcut) + ImGui::SetItemTooltip("Toggle %s (%s)", label, shortcut); + else + ImGui::SetItemTooltip("Toggle %s", label); + + return hovered; + + } + + void App::UpdateDrawers() { + + // Only one drawer is open at a time, the last one opened replaces the other one + for (auto& opening : drawers) { + if (!opening.window->IsOpening()) + continue; + for (auto& other : drawers) { + if (other.window != opening.window && other.window->show && !other.window->pinned) + opening.window->TakeOver(*other.window); + } + break; + } + + // The source item of a drag isn't rendered anymore after the drawer closed + auto payload = ImGui::GetDragDropPayload(); + if (payload && payload->IsDataType("ContentBrowserResource") && !contentBrowserWindow.IsVisible() && + ImGui::BeginDragDropSource(ImGuiDragDropFlags_SourceExtern)) { + ImGui::TextUnformatted(Common::Path::GetFileName(static_cast(payload->Data)).c_str()); + ImGui::TextDisabled("Drop on a matching resource slot"); + ImGui::EndDragDropSource(); + } + + } + + void App::PrepareDrawerDocking(ImGuiID dsID) { + + // Pinned drawers without a place in the saved layout are docked again + auto requestDockingIfLost = [](UI::DrawerWindow& drawer) { + if (!drawer.pinned || drawer.requestDocking || ImGui::FindWindowByName(drawer.GetNameID())) + return; + auto settings = ImGui::FindWindowSettingsByID(ImHashStr(drawer.GetNameID())); + drawer.requestDocking = !settings || !settings->DockId; + }; + for (auto& drawer : drawers) + requestDockingIfLost(*drawer.window); + + drawerDockNodeID = 0; + if (std::none_of(drawers.begin(), drawers.end(), [](const Drawer& drawer) { return drawer.window->requestDocking; })) + return; + + // A drawer that is docked already shares its node with the new one + auto getDockID = [](const UI::DrawerWindow& drawer) -> ImGuiID { + auto window = ImGui::FindWindowByName(drawer.GetNameID()); + return drawer.pinned && !drawer.requestDocking && window ? window->DockId : 0; + }; + for (const auto& drawer : drawers) { + drawerDockNodeID = getDockID(*drawer.window); + if (drawerDockNodeID) + return; + } + + auto centralNode = ImGui::DockBuilderGetCentralNode(dsID); + if (!centralNode) + return; + + ImGuiID dockIdUp; + ImGui::DockBuilderSplitNode(centralNode->ID, ImGuiDir_Down, 0.3f, &drawerDockNodeID, &dockIdUp); + ImGui::DockBuilderFinish(dsID); + + } + + void App::DockPinnedDrawer(UI::DrawerWindow& drawer) { + + // A new layout has its central node only after the first update, the request waits until then + if (!drawer.requestDocking || !drawerDockNodeID) + return; + drawer.requestDocking = false; + + ImGui::SetNextWindowDockID(drawerDockNodeID, ImGuiCond_Always); + + } + + void App::RenderStatusBarMenu() { + + if (!ImGui::BeginPopupContextWindow("Status bar menu")) + return; + + auto& shownDrawers = Singletons::config->statusBarDrawers; + + ImGui::TextDisabled("Drawers in the status bar, drag to reorder"); + ImGui::Separator(); + + int32_t removedDrawer = -1, draggedDrawer = -1; + std::vector rowTops; + for (int32_t i = 0; i < int32_t(shownDrawers.size()); i++) { + // The id follows the entry, such that it stays active while it moves past others + ImGui::PushID(shownDrawers[i].c_str()); + auto shown = true; + if (ImGui::Checkbox("##Shown", &shown)) + removedDrawer = i; + ImGui::SameLine(); + ImGui::Selectable(shownDrawers[i].c_str(), false, ImGuiSelectableFlags_NoAutoClosePopups); + rowTops.push_back(ImGui::GetItemRectMin().y); + if (ImGui::IsItemActive() && ImGui::IsMouseDragging(ImGuiMouseButton_Left)) + draggedDrawer = i; + ImGui::PopID(); + } + // A dragged entry moves to the row below the mouse + if (draggedDrawer >= 0 && removedDrawer < 0) { + int32_t targetDrawer = 0; + for (int32_t i = 1; i < int32_t(rowTops.size()); i++) + if (ImGui::GetIO().MousePos.y >= rowTops[i]) + targetDrawer = i; + if (targetDrawer != draggedDrawer) { + auto name = shownDrawers[draggedDrawer]; + shownDrawers.erase(shownDrawers.begin() + draggedDrawer); + shownDrawers.insert(shownDrawers.begin() + targetDrawer, name); + } + } + if (removedDrawer >= 0) + shownDrawers.erase(shownDrawers.begin() + removedDrawer); + + // Drawers which aren't shown are added at the end + for (const auto& drawer : drawers) { + if (std::find(shownDrawers.begin(), shownDrawers.end(), drawer.name) != shownDrawers.end()) + continue; + ImGui::PushID(drawer.name); + auto shown = false; + if (ImGui::Checkbox("##Shown", &shown)) + shownDrawers.push_back(drawer.name); + ImGui::SameLine(); + ImGui::TextDisabled("%s", drawer.name); + ImGui::PopID(); + } + + ImGui::EndPopup(); + + } + + App::Drawer* App::FindDrawer(const std::string& name) { + + auto iter = std::find_if(drawers.begin(), drawers.end(), [&](const Drawer& drawer) { return name == drawer.name; }); + return iter != drawers.end() ? &*iter : nullptr; + + } + + bool App::AllowQuit() { + + if (quitConfirmed) + return true; + + for (const auto& window : sceneWindows) + if (window->hasUnsavedChanges) + AddUnsavedWindow(window); + for (const auto& window : assetEditorWindows) + if (window->hasUnsavedChanges) + AddUnsavedWindow(window); + for (const auto& window : codeEditorWindows) + if (window->hasUnsavedChanges) + AddUnsavedWindow(window); + + auto unsavedProject = Singletons::project && projectSettingsWindow.hasUnsavedChanges; + quitAfterUnsavedChanges = !unsavedWindows.empty() || unsavedProject; + return !quitAfterUnsavedChanges; + + } + + void App::AddUnsavedWindow(const Ref& window) { + + if (std::find(unsavedWindows.begin(), unsavedWindows.end(), window) == unsavedWindows.end()) + unsavedWindows.push_back(window); + + } + + bool App::IsWindowOpen(const Ref& window) const { + + auto contains = [&](const auto& windows) { + return std::any_of(windows.begin(), windows.end(), [&](const auto& open) { return open == window; }); + }; + return contains(sceneWindows) || contains(assetEditorWindows) || contains(codeEditorWindows); + + } + + void App::SaveWindow(const Ref& window) { + + if (auto sceneWindow = std::dynamic_pointer_cast(window)) { + // The scene of a playing window is the state of the game + if (sceneWindow->isPlaying) + sceneWindow->StopPlaying(); + sceneWindow->SaveScene(); + } + else if (auto assetEditorWindow = std::dynamic_pointer_cast(window)) { + assetEditorWindow->Save(); + } + else if (auto codeEditorWindow = std::dynamic_pointer_cast(window)) { + codeEditorWindow->Save(); + } + + } + + std::pair App::GetWindowFile(const Ref& window) const { + + if (auto sceneWindow = std::dynamic_pointer_cast(window)) { + auto path = UI::SceneWindow::GetScenePath(sceneWindow->scene); + return { Common::Path::GetFileNameWithoutExtension(path), path }; + } + if (auto assetEditorWindow = std::dynamic_pointer_cast(window)) + return { window->name, assetEditorWindow->GetAssetPath() }; + if (auto codeEditorWindow = std::dynamic_pointer_cast(window)) + return { window->name, codeEditorWindow->GetPath() }; + return { window->name, "" }; + + } + + void App::RenderUnsavedChangesPopup() { + + // Windows can close in other ways in the meantime, e.g. after a save + std::erase_if(unsavedWindows, [&](const auto& window) { return !window->hasUnsavedChanges || !IsWindowOpen(window); }); + // The project is only asked about when the editor closes + auto unsavedProject = quitAfterUnsavedChanges && Singletons::project && projectSettingsWindow.hasUnsavedChanges; + if (unsavedWindows.empty() && !unsavedProject) { + if (quitAfterUnsavedChanges && nextProject) { + quitAfterUnsavedChanges = false; + projectSwitchRequested = true; + } + else if (quitAfterUnsavedChanges) { + quitConfirmed = true; + Exit(); + } + return; + } + + // A running save shows its own popup, both would take turns opening + if (Singletons::blockingOperation->block) + return; + + const char* popupName = "Unsaved changes"; + if (!ImGui::IsPopupOpen(popupName)) + ImGui::OpenPopup(popupName); + + // Laid out like the other dialogs: centered with a fixed width, the question first and the actions at the bottom + auto viewport = ImGui::GetMainViewport(); + auto width = std::clamp(viewport->Size.x * 0.3f, 420.0f, 560.0f); + ImGui::SetNextWindowPos(viewport->GetCenter(), ImGuiCond_Appearing, ImVec2(0.5f, 0.5f)); + ImGui::SetNextWindowSizeConstraints(ImVec2(width, 0.0f), ImVec2(width, FLT_MAX)); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(20.0f, 16.0f)); + auto open = ImGui::BeginPopupModal(popupName, nullptr, ImGuiWindowFlags_AlwaysAutoResize | + ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoTitleBar); + ImGui::PopStyleVar(); + if (!open) + return; + + // The scenes, assets, code and the project with their files + std::vector> unsaved; + for (const auto& window : unsavedWindows) + unsaved.push_back(GetWindowFile(window)); + if (unsavedProject) + unsaved.emplace_back("the project " + Singletons::project->name, Singletons::project->path); + auto files = std::to_string(unsavedWindows.size()) + (unsavedWindows.size() == 1 ? " file" : " files"); + auto heading = unsaved.size() == 1 ? "Save the changes to " + unsaved.front().first + "?" : + "Save the changes to " + files + (unsavedProject ? " and the project?" : "?"); + ImGui::SetWindowFontScale(1.25f); + ImGui::TextWrapped("%s", heading.c_str()); + ImGui::SetWindowFontScale(1.0f); + ImGui::Spacing(); + auto consequence = !quitAfterUnsavedChanges ? "The window closes afterwards." : + nextProject ? "The editor opens the other project afterwards." : "The editor closes afterwards."; + ImGui::PushStyleColor(ImGuiCol_Text, Theme::TextMuted()); + ImGui::TextWrapped("%s Changes which aren't saved are lost.", consequence); + ImGui::PopStyleColor(); + + // A single one is named in the question already + if (unsaved.size() > 1) { + ImGui::Spacing(); + for (const auto& [label, file] : unsaved) { + ImGui::Bullet(); + ImGui::TextUnformatted(label.c_str()); + ImGui::SameLine(); + ImGui::TextColored(Theme::TextMuted(), "%s", file.c_str()); + } + } + + ImGui::Spacing(); + ImGui::Spacing(); + ImGui::Separator(); + ImGui::Spacing(); + + // The destructive action stands apart on the left, saving is the rightmost and the default with Enter + auto& style = ImGui::GetStyle(); + auto buttonWidth = std::max({ ImGui::CalcTextSize("Save").x, ImGui::CalcTextSize("Cancel").x, + ImGui::CalcTextSize("Don't save").x }) + 4.0f * style.FramePadding.x; + Theme::PushDangerButton(); + bool discard = ImGui::Button("Don't save", ImVec2(buttonWidth, 0.0f)); + Theme::PopDangerButton(); + ImGui::SameLine(ImGui::GetContentRegionMax().x - 2.0f * buttonWidth - style.ItemSpacing.x); + bool cancel = ImGui::Button("Cancel", ImVec2(buttonWidth, 0.0f)) || ImGui::IsKeyPressed(ImGuiKey_Escape, false); + ImGui::SameLine(); + Theme::PushPrimaryButton(); + bool save = ImGui::Button("Save", ImVec2(buttonWidth, 0.0f)) || ImGui::IsKeyPressed(ImGuiKey_Enter, false); + Theme::PopPrimaryButton(); + + if (save || discard) { + for (const auto& window : unsavedWindows) { + if (save) + SaveWindow(window); + // Saves of scenes run as blocking operations, which finish before the window is deleted. Quitting + // keeps the windows, such that they open again with the next start + window->hasUnsavedChanges = false; + if (!quitAfterUnsavedChanges) + window->show = false; + } + } + + if (unsavedProject && save) + projectSettingsWindow.Save(Singletons::project); + // The changes of a discarded project are lost with the editor + if (unsavedProject && discard) + projectSettingsWindow.hasUnsavedChanges = false; + + if (save || discard || cancel) { + unsavedWindows.clear(); + // A cancelled quit doesn't switch the project either + if (cancel) { + quitAfterUnsavedChanges = false; + nextProject.reset(); + } + ImGui::CloseCurrentPopup(); + } + + ImGui::EndPopup(); + + } + void App::RenderShortcutsWindow() { if (!showShortcutsWindow) @@ -764,7 +2216,12 @@ namespace Atlas::Editor { section("General", { { "Ctrl+P", "Open the command palette" }, + { "Ctrl+B", "Toggle the content browser" }, + { "Ctrl+J", "Toggle the log" }, + { "Esc", "Close the open drawer" }, { "Ctrl+S", "Save the active scene" }, + { "Ctrl+Z", "Undo in the scene or asset editor in front" }, + { "Ctrl+Shift+Z / Y", "Redo" }, { "Ctrl+Q", "Stop playing" }, }); section("Viewport", { @@ -793,6 +2250,16 @@ namespace Atlas::Editor { section("Terrain editing", { { "Hold right mouse", "Paint with the active brush" }, }); + section("Material graph", { + { "Space or right click", "Add a node, dropping a link on the canvas connects it" }, + { "Middle or right mouse drag", "Move the canvas" }, + { "Mouse wheel", "Zoom" }, + { "Drag a pin", "Connect, drag an input to move its link" }, + { "Alt+Click on a link", "Remove the link" }, + { "Ctrl+C / V / D", "Copy, paste or duplicate the selection" }, + { "F", "Show all nodes" }, + { "Delete", "Delete the selection" }, + }); } ImGui::End(); @@ -804,54 +2271,198 @@ namespace Atlas::Editor { ImGui::SetWindowPos(ImVec2(640.0f, 55.0f)); ImGui::DockBuilderRemoveNode(dsID); - ImGui::DockBuilderAddNode(dsID); - - ImGuiID dsIdUp, dsIdDown; - ImGui::DockBuilderSplitNode(dsID, ImGuiDir_Up, 0.7f, &dsIdUp, &dsIdDown); + ImGui::DockBuilderAddNode(dsID, ImGuiDockNodeFlags_DockSpace); + ImGui::DockBuilderSetNodeSize(dsID, ImGui::GetMainViewport()->WorkSize); for (auto& sceneWindow : sceneWindows) { - ImGui::DockBuilderDockWindow(sceneWindow->GetNameID(), dsIdUp); - } - upperDockNodeID = dsIdUp; - - { - auto dsIdCopy = dsIdDown; - auto dsIdLeft = ImGui::DockBuilderSplitNode(dsIdCopy, ImGuiDir_Left, 0.5f, NULL, &dsIdCopy); - auto dsIdRight = ImGui::DockBuilderSplitNode(dsIdCopy, ImGuiDir_Right, 0.0f, NULL, &dsIdCopy); - - ImGui::DockBuilderDockWindow(contentBrowserWindow.GetNameID(), dsIdLeft); - ImGui::DockBuilderDockWindow(logWindow.GetNameID(), dsIdRight); + ImGui::DockBuilderDockWindow(sceneWindow->GetNameID(), dsID); } ImGui::DockBuilderFinish(dsID); - profilerWindow.show = false; - contentBrowserWindow.show = true; - logWindow.show = true; + projectSettingsWindow.show = false; + // Pinned drawers keep their place in the new layout + for (auto& drawer : drawers) + drawer.window->show = drawer.window->requestDocking = drawer.window->pinned; - contentBrowserWindow.resetDockingLayout = true; - logWindow.resetDockingLayout = true; for (const auto& sceneWindow : sceneWindows) { sceneWindow->resetDockingLayout = true; sceneWindow->show = true; } resetDockspaceLayout = false; + dockLoadingScenes = true; + + } + + std::string App::OpenInAssetEditor(const std::string& path) { + + auto noEditor = "There is no editor for " + Common::Path::GetFileName(path); + auto mapping = Content::contentTypeMapping.find(Common::Path::GetFileType(path)); + if (mapping == Content::contentTypeMapping.end()) { + Notifications::Push({ .message = noEditor, .type = NotificationType::Warning }); + return noEditor; + } + auto type = mapping->second; + if (type == ContentType::Animation) { + // Animations play in the mesh editor focused last + Ref assetEditorWindow; + for (const auto& window : assetEditorWindows) { + auto candidate = std::dynamic_pointer_cast(window); + if (candidate && (!assetEditorWindow || candidate->lastFocusTime > assetEditorWindow->lastFocusTime)) + assetEditorWindow = candidate; + } + auto animation = FileImporter::ImportFile(path); + if (!assetEditorWindow || !assetEditorWindow->Play(animation)) { + std::string error = "Open a skinned mesh to play the animation on"; + Notifications::Push({ .message = error, .type = NotificationType::Error }); + return error; + } + return {}; + } + + if (type == ContentType::Prefab) { + for (const auto& sceneWindow : sceneWindows) { + if (sceneWindow->prefabPath == path) + return {}; + } + + auto scene = DataCreator::CreateScene(Common::Path::GetFileName(path), vec3(-2048.0f), vec3(2048.0f), 8); + Singletons::project->ApplyTo(*scene); + auto sceneWindow = CreateRef(ResourceHandle(scene), true); + sceneWindow->OpenPrefab(path); + OpenAsTab(*sceneWindow); + sceneWindows.push_back(sceneWindow); + return {}; + } + + if (type == ContentType::Script || type == ContentType::Shader) { + auto opened = std::find_if(codeEditorWindows.begin(), codeEditorWindows.end(), + [&](const auto& window) { return window->GetPath() == path; }); + if (opened != codeEditorWindows.end()) { + (*opened)->requestFocus = true; + return {}; + } + codeEditorWindows.push_back(CreateRef(path)); + OpenAsTab(*codeEditorWindows.back()); + return {}; + } + + // Scenes open as a scene tab, like a double click in the content browser + if (type == ContentType::Scene) { + FileImporter::ImportFile(path); + return {}; + } + + if (type != ContentType::Material && type != ContentType::MaterialGraph && type != ContentType::Mesh) { + Notifications::Push({ .message = noEditor, .type = NotificationType::Warning }); + return noEditor; + } + + auto iter = std::find_if(assetEditorWindows.begin(), assetEditorWindows.end(), + [&](const auto& window) { return window->GetAssetPath() == path; }); + if (iter != assetEditorWindows.end()) { + (*iter)->requestFocus = true; + activeAssetEditorWindow = *iter; + return {}; + } + + if (type == ContentType::Material) + assetEditorWindows.push_back(CreateRef(FileImporter::ImportFile(path), true)); + else if (type == ContentType::MaterialGraph) + assetEditorWindows.push_back(CreateRef(FileImporter::ImportFile(path), true)); + else + assetEditorWindows.push_back(CreateRef(FileImporter::ImportFile(path), true)); + // Docks next to the window which is still the active one + OpenAsTab(*assetEditorWindows.back()); + activeAssetEditorWindow = assetEditorWindows.back(); + return {}; + + } + + void App::DockAsTab(UI::Window& window) { + + if (window.show && !window.wasShown) { + // The first frame shows the windows of the saved layout, they are docked there already or floating + auto restored = ImGui::GetFrameCount() <= 1; + auto imguiWindow = ImGui::FindWindowByName(window.GetNameID()); + auto settings = ImGui::FindWindowSettingsByID(ImHashStr(window.GetNameID())); + auto dockId = imguiWindow ? imguiWindow->DockId : settings ? settings->DockId : 0; + if (!restored || !dockId) { + window.requestDocking = true; + if (!window.dockNodeID) + window.dockNodeID = GetActiveDockNodeID(); + } + if (!restored) + window.requestFocus = true; + } + window.wasShown = window.show; + DockNextToScenes(window); + + } + + void App::DockNextToScenes(UI::Window& window) { + + if (!window.requestDocking) + return; + window.requestDocking = false; + + if (window.dockNodeID && ImGui::DockBuilderGetNode(window.dockNodeID)) { + ImGui::SetNextWindowDockID(window.dockNodeID, ImGuiCond_Always); + window.dockNodeID = 0; + return; + } + window.dockNodeID = 0; + + for (const auto& sceneWindow : sceneWindows) { + auto imguiWindow = ImGui::FindWindowByName(sceneWindow->GetNameID()); + if (sceneWindow.get() != &window && imguiWindow && imguiWindow->DockId) { + ImGui::SetNextWindowDockID(imguiWindow->DockId, ImGuiCond_Always); + return; + } + } + + // Nothing to join, so the window takes the free space of the layout + auto centralNode = ImGui::DockBuilderGetCentralNode(ImGui::GetID("MainDS")); + if (centralNode) + ImGui::SetNextWindowDockID(centralNode->ID, ImGuiCond_Always); + + } + + ImGuiID App::GetActiveDockNodeID() const { + + const UI::Window* window = activeAssetEditorWindow.get(); + if (!window && !sceneWindows.empty()) + window = sceneWindows[std::min(activeSceneIdx, sceneWindows.size() - 1)].get(); + + auto imguiWindow = window ? ImGui::FindWindowByName(window->GetNameID()) : nullptr; + return imguiWindow ? imguiWindow->DockId : 0; + + } + + void App::OpenAsTab(UI::Window& window) const { + + window.requestDocking = true; + window.dockNodeID = GetActiveDockNodeID(); + window.requestFocus = true; } void App::SubscribeToResourceEvents() { - ResourceManager::Subscribe(ResourceTopic::ResourceCreate, + sceneCreateSubscription = ResourceManager::Subscribe(ResourceTopic::ResourceCreate, [&](Ref>& scene) { waitToLoadScenes.push_back(ResourceHandle(scene)); + if (!restoringScenes) + userOpenedScenes.push_back(ResourceHandle(scene)); Singletons::config->openedScenes.push_back(ResourceHandle(scene)); Singletons::config->AddRecentScene(scene->path); }); // Also kind of a resource event - Events::EventManager::DropEventDelegate.Subscribe([&](Events::DropEvent event) { - if (!event.file.empty() && contentBrowserWindow.show) { + dropSubscription = Events::EventManager::DropEventDelegate.Subscribe([&](Events::DropEvent event) { + if (!event.file.empty()) { + contentBrowserWindow.show = true; auto destinationDirectory = Common::Path::GetAbsolute(contentBrowserWindow.currentDirectory); FileSystemHelper::Copy(event.file, destinationDirectory); diff --git a/src/editor/App.h b/src/editor/App.h index aa5453e6d..c40aea1b7 100644 --- a/src/editor/App.h +++ b/src/editor/App.h @@ -3,19 +3,30 @@ #include #include #include +#include #include #include #include #include +#include #include #include "ui/windows/ContentBrowserWindow.h" #include "ui/windows/SceneWindow.h" +#include "ui/windows/MeshEditorWindow.h" +#include "ui/windows/MaterialEditorWindow.h" #include "ui/windows/LogWindow.h" #include "ui/windows/ProfilerWindow.h" #include "ui/windows/GeometryBrushWindow.h" +#include "ui/windows/ProjectHubWindow.h" +#include "ui/windows/ProjectSettingsWindow.h" +#include "ui/windows/CodeEditorWindow.h" #include "ui/popups/CommandPalette.h" +#include "EditorBridge.h" + +#include +#include #define WINDOW_FLAGS AE_WINDOW_RESIZABLE | AE_WINDOW_HIGH_DPI @@ -34,50 +45,210 @@ namespace Atlas::Editor { virtual void Render(float deltaTime) final; + bool AllowQuit() final; + private: + struct Drawer { + UI::DrawerWindow* window; + IconType icon; + const char* name; + const char* shortcut; + }; + + // Activates the project of --project, the asset directory and the editor state are the ones of the project + void LoadProject(); + + // Opens the start scene of a project without opened scenes, a missing start scene is created + void OpenStartScene(); + + // Streaming limits for the engine, scene settings for the open scenes + void ApplyProjectSettings(); + + // Writes the recorded Lua bindings for the Lua language server into .atlas/lua of the project, a .luarc.json + // which doesn't exist yet points other editors there + void ExportLuaAnnotations(); + + // The editor starts again with the project, an empty path shows the project hub. Resources, shaders and the + // editor state of the old asset directory don't carry over this way + void OpenProject(const std::string& path); + void RenderSceneMaximized(); - + void SetupMainDockspace(ImGuiID dsID); void RenderEmptyState(ImGuiID dsID); + void ApplyTheme(); + + // Follows the scale of the display unless the user chose one, the font is rasterized for it + void UpdateUiScale(); + + float GetStatusChipWidth(const char* text, float trailingWidth = 0.0f); + + float GetNotificationBadgeWidth(int32_t unreadCount); + + void RenderNotificationButton(); + void RenderStatusBar(); + // Undo and redo act on the asset editor or scene in front + void Undo(); + + void Redo(); + + bool CanUndo() const; + + bool CanRedo() const; + + const UndoHistory* GetActiveHistory() const; + + bool RenderDrawerButton(UI::DrawerWindow& drawer, IconType icon, const char* label, const char* shortcut, + int32_t errorCount = 0, int32_t warningCount = 0); + + // Chooses and orders the drawers of the status bar, opened by a right click on it + void RenderStatusBarMenu(); + + // Clickable items of the status bar carry a background, such that they stand out from plain information + bool RenderStatusChip(const char* id, IconType icon, const char* text, ImVec4 color, + ImVec4 background, ImVec4 backgroundHovered, float maxWidth = FLT_MAX, float trailingWidth = 0.0f); + + float GetCapCenteredTextY(float centerY); + + void UpdateDrawers(); + + // Pinned drawers share one area at the bottom of the layout, which is split off before the dockspace is updated + void PrepareDrawerDocking(ImGuiID dsID); + + void DockPinnedDrawer(UI::DrawerWindow& drawer); + + Drawer* FindDrawer(const std::string& name); + void RenderRecentScenesMenu(); void RenderShortcutsWindow(); + // Asks whether the scenes closed by the user or by quitting are saved or their changes discarded + void RenderUnsavedChangesPopup(); + + // Saves a scene, asset or code window + void SaveWindow(const Ref& window); + + // The name and file of a window for the unsaved changes dialog + std::pair GetWindowFile(const Ref& window) const; + + bool IsWindowOpen(const Ref& window) const; + + void AddUnsavedWindow(const Ref& window); + void RegisterCommands(); + // Opens meshes and materials in their editors and prefabs in a scene window, animations play in the last + // focused mesh editor + // Returns why the file can't be opened, empty if it was + std::string OpenInAssetEditor(const std::string& path); + + // Windows opened by the user join the selected window as a tab, others the scenes + void DockNextToScenes(UI::Window& window); + + // Dock node of the asset editor or scene window that was focused last + ImGuiID GetActiveDockNodeID() const; + + void OpenAsTab(UI::Window& window) const; + + // Called before a window is rendered: an opened window becomes a focused tab next to the active window, windows + // of the restored layout keep their place unless they float + void DockAsTab(UI::Window& window); + Ref GetActiveSceneWindow() const; void SubscribeToResourceEvents(); + // Unloads the open project and loads nextProject + void SwitchProject(); + + // The table Editor of the Lua of the MCP server: windows, focus, opening files and the text of code windows + void AddEditorFunctions(Scripting::Binder& editor); + void SetDefaultWindowResolution(); Input::MouseHandler mouseHandler; Input::KeyboardHandler keyboardHandler; + Input::PlayerInput playerInput; - UI::LogWindow logWindow = UI::LogWindow(true); - UI::ContentBrowserWindow contentBrowserWindow = UI::ContentBrowserWindow(true); + UI::LogWindow logWindow = UI::LogWindow(false); + UI::ContentBrowserWindow contentBrowserWindow = UI::ContentBrowserWindow(false); UI::ProfilerWindow profilerWindow = UI::ProfilerWindow(false); UI::GeometryBrushWindow geometryBrushWindow = UI::GeometryBrushWindow(false); + // The config decides which of them the status bar shows + std::vector drawers = { + { &contentBrowserWindow, IconType::Folder, "Content browser", "Ctrl+B" }, + { &logWindow, IconType::Log, "Log", "Ctrl+J" }, + { &profilerWindow, IconType::Profiler, "Profiler", "" } + }; + ImguiExtension::PerformanceGraphPanel performanceGraphPanel; UI::CommandPalette commandPalette; bool showShortcutsWindow = false; std::vector> waitToLoadScenes; + // Scenes opened by the user and not restored from the config + std::vector> userOpenedScenes; std::vector> sceneWindows; + std::vector> assetEditorWindows; + std::vector> codeEditorWindows; + Ref activeAssetEditorWindow; + // The code window in front, its undo and search are those of the edit menu and the command palette + Ref activeCodeEditorWindow; + + // Scenes, assets and code with unsaved changes the user wants to close, all of them before quitting + std::vector> unsavedWindows; + bool quitAfterUnsavedChanges = false; + bool quitConfirmed = false; size_t activeSceneIdx = 0; - ImGuiID upperDockNodeID; + ImGuiID drawerDockNodeID = 0; + + float drawerSpringTime = 0.0f; + // Background job count shown in the status bar, updated twice a second + float backgroundJobTime = 0.0f; + float backgroundJobRefreshTime = 0.0f; + int32_t backgroundJobPeak = 0; + int32_t backgroundJobShown = 0; + + float systemUiScale = 0.0f; + float fontRasterSize = 0.0f; + bool notificationsOpen = false; + + std::vector emptyStateScenes; + bool emptyStateVisible = false; bool resetDockspaceLayout = false; + bool dockLoadingScenes = false; + bool restoringScenes = true; bool playingMaximized = false; + // Hitch settings of the config while --log-hitches overrides them, these are saved instead + std::optional configHitchSettings; + + // New projects copy their standard data and templates from the asset directory the editor started with + std::string engineDataDirectory; + std::unique_ptr projectHub; + UI::ProjectSettingsWindow projectSettingsWindow = UI::ProjectSettingsWindow(false); + // Opened once the unsaved changes are saved or discarded, empty for the project hub. The editor switches in + // the same process, the window and the debugger stay + std::optional nextProject; + bool projectSwitchRequested = false; + bool switchingProject = false; + int32_t sceneCreateSubscription = 0; + uint32_t dropSubscription = 0; + // ImGui keeps the pointer to the file name + std::string imguiIniPath; + // Atlas Bridge commands for the open scene, only with a project + std::unique_ptr bridge; + }; } \ No newline at end of file diff --git a/src/editor/BlockingOperation.h b/src/editor/BlockingOperation.h index 2225c9aff..e943eed2a 100644 --- a/src/editor/BlockingOperation.h +++ b/src/editor/BlockingOperation.h @@ -3,7 +3,8 @@ #include "jobsystem/JobSystem.h" #include -#include +#include +#include namespace Atlas::Editor { @@ -13,27 +14,36 @@ namespace Atlas::Editor { ~BlockingOperation() { JobSystem::Wait(job); } void Block(const std::string& text, std::function blocker) { - this->blocker = blocker; + blockers.push_back(blocker); blockText = text; } void Update() { - if (!blocker.has_value()) + if (blockers.empty() || !job.HasFinished()) return; - + block = true; - JobSystem::Execute(job, [blocker = blocker, &block = block](JobData&) { - blocker.value()(); + JobSystem::Execute(job, [blockers = std::move(blockers), &block = block](JobData&) { + for (const auto& blocker : blockers) + blocker(); block = false; }); - blocker = {}; + blockers.clear(); + } + + // For callers which destroy what the operations reference before the next update + void Finish() { + JobSystem::Wait(job); + for (const auto& blocker : blockers) + blocker(); + blockers.clear(); } JobGroup job { "Blocking operation" }; - std::optional> blocker; + std::vector> blockers; std::string blockText; - bool block = false; + std::atomic_bool block = false; }; -} \ No newline at end of file +} diff --git a/src/editor/CMakeLists.txt b/src/editor/CMakeLists.txt index b5f4d9451..e84ed7e30 100644 --- a/src/editor/CMakeLists.txt +++ b/src/editor/CMakeLists.txt @@ -47,9 +47,15 @@ endif() target_precompile_headers(${PROJECT_NAME} REUSE_FROM AtlasEngine) +# A running editor can't be overwritten (LNK1168), it keeps running from a renamed file +if (WIN32) + add_custom_command(TARGET ${PROJECT_NAME} PRE_LINK + COMMAND ${CMAKE_COMMAND} -DEXECUTABLE=$ -P ${CMAKE_CURRENT_SOURCE_DIR}/../bridge/MoveRunningExecutable.cmake) +endif() + # We want to use both ImGui and the AtlasEngine. For ImGui, the ATLAS_IMGUI option # needs to be turned on. -target_link_libraries (${PROJECT_NAME} AtlasEngine ImguiExtension +target_link_libraries (${PROJECT_NAME} AtlasEngine ImguiExtension AtlasBridgeLibrary imguizmo::imguizmo Jolt::Jolt) if (APPLE AND ATLAS_BUNDLE) diff --git a/src/editor/Config.h b/src/editor/Config.h index 7bd85d908..286b53f08 100644 --- a/src/editor/Config.h +++ b/src/editor/Config.h @@ -10,9 +10,14 @@ namespace Atlas::Editor { bool darkMode = true; bool pathTrace = false; bool vsync = true; + // Zero follows the scale of the display set in the system settings + float uiScale = 0.0f; std::vector> openedScenes; + // Names of the drawers in the status bar, in their order + std::vector statusBarDrawers = { "Content browser", "Log" }; + // Most recently opened scene paths, newest first std::vector recentScenes; diff --git a/src/editor/Content.cpp b/src/editor/Content.cpp index 117693214..6b647d2e2 100644 --- a/src/editor/Content.cpp +++ b/src/editor/Content.cpp @@ -12,14 +12,34 @@ namespace Atlas::Editor { { "usd", ContentType::MeshSource }, { "usda", ContentType::MeshSource }, { "aematerial", ContentType::Material }, + { "aematgraph", ContentType::MaterialGraph }, { "aeterrain", ContentType::Terrain }, { "aescene", ContentType::Scene }, { "lua", ContentType::Script }, + { "glsl", ContentType::Shader }, + { "hsh", ContentType::Shader }, + { "vsh", ContentType::Shader }, + { "fsh", ContentType::Shader }, + { "gsh", ContentType::Shader }, + { "csh", ContentType::Shader }, + { "tcsh", ContentType::Shader }, + { "tesh", ContentType::Shader }, + { "rgen", ContentType::Shader }, + { "rchit", ContentType::Shader }, + { "rahit", ContentType::Shader }, + { "rmiss", ContentType::Shader }, { "ttf", ContentType::Font }, { "aeprefab", ContentType::Prefab }, { "jpg", ContentType::Texture }, + { "jpeg", ContentType::Texture }, { "png", ContentType::Texture }, + { "tga", ContentType::Texture }, + { "bmp", ContentType::Texture }, + { "gif", ContentType::Texture }, + { "psd", ContentType::Texture }, + { "ktx2", ContentType::Texture }, { "hdr", ContentType::EnvironmentTexture }, + { "aeanimation", ContentType::Animation }, }; } \ No newline at end of file diff --git a/src/editor/Content.h b/src/editor/Content.h index f54dbe27d..692b4e94c 100644 --- a/src/editor/Content.h +++ b/src/editor/Content.h @@ -18,6 +18,9 @@ namespace Atlas::Editor { Prefab, Texture, EnvironmentTexture, + Animation, + MaterialGraph, + Shader, None }; @@ -30,6 +33,9 @@ namespace Atlas::Editor { std::string assetPath; ContentType type = ContentType::None; + uintmax_t size = 0; + // Ticks of the last modification, changes e.g. renew the preview of the content + int64_t lastWriteTime = 0; static const std::map contentTypeMapping; }; diff --git a/src/editor/ContentDiscovery.cpp b/src/editor/ContentDiscovery.cpp index bf6cae97c..88e4c7803 100644 --- a/src/editor/ContentDiscovery.cpp +++ b/src/editor/ContentDiscovery.cpp @@ -104,7 +104,7 @@ namespace Atlas::Editor { auto dataDirectory = Loader::AssetLoader::GetDataDirectory(); - for (const auto& dirEntry : std::filesystem::directory_iterator(directory->path)) { + for (const auto& dirEntry : std::filesystem::directory_iterator(directory->path, std::filesystem::directory_options::skip_permission_denied)) { auto path = Common::Path::Normalize(dirEntry.path().string()); auto assetPath = Common::Path::GetRelative(dataDirectory, path); if (assetPath.starts_with('/')) @@ -137,11 +137,19 @@ namespace Atlas::Editor { continue; auto contentType = Content::contentTypeMapping.at(fileType); + std::error_code errorCode; + auto fileSize = dirEntry.file_size(errorCode); + if (errorCode) + fileSize = 0; + auto writeTime = dirEntry.last_write_time(errorCode); + auto lastWriteTime = errorCode ? int64_t(0) : int64_t(writeTime.time_since_epoch().count()); directory->files.emplace_back(Content { .name = filename, .path = path, .assetPath = assetPath, .type = contentType, + .size = fileSize, + .lastWriteTime = lastWriteTime, }); result->contentTypeToContentMap[contentType].push_back(directory->files.back()); diff --git a/src/editor/ContentDiscovery.h b/src/editor/ContentDiscovery.h index 83ca699b3..4b4f2f282 100644 --- a/src/editor/ContentDiscovery.h +++ b/src/editor/ContentDiscovery.h @@ -22,7 +22,8 @@ namespace Atlas::Editor { class ContentDiscovery { public: - static void Shutdown() { JobSystem::Wait(contentDiscoveryJob); } + // The content is discovered again afterwards, e.g. in the directory of another project + static void Shutdown() { JobSystem::Wait(contentDiscoveryJob); content.reset(); nextContent.reset(); } static void Execute(); diff --git a/src/editor/ContentPreviews.cpp b/src/editor/ContentPreviews.cpp new file mode 100644 index 000000000..28f9f12ba --- /dev/null +++ b/src/editor/ContentPreviews.cpp @@ -0,0 +1,1449 @@ +#include "ContentPreviews.h" +#include "ContentDiscovery.h" +#include "DataCreator.h" +#include "FileImporter.h" +#include "Singletons.h" +#include "Theme.h" + +#include "Clock.h" +#include "Serializer.h" +#include "common/Path.h" +#include "graphics/GraphicsDevice.h" +#include "loader/AssetLoader.h" +#include "loader/KtxLoader.h" +#include "loader/MaterialGraphLoader.h" +#include "loader/MaterialLoader.h" +#include "physics/PhysicsWorld.h" +#include "profiler/CPUProfiler.h" +#include "scene/components/AnimationComponent.h" +#include "scene/components/AudioComponent.h" +#include "scene/components/AudioVolumeComponent.h" +#include "scene/components/LuaScriptComponent.h" +#include "scene/prefabs/Group.h" +#include "scene/prefabs/MeshInstance.h" + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Atlas::Editor { + + using namespace Scene::Components; + + // Changes of how previews look have to be part of the cache key + static constexpr int32_t previewFormatVersion = 3; + + static float SrgbToLinear(float value) { + + value = glm::clamp(value, 0.0f, 1.0f); + return value <= 0.04045f ? value / 12.92f : std::pow((value + 0.055f) / 1.055f, 2.4f); + + } + + static const std::array& GetSrgbToLinearTable() { + + static const auto table = []() { + std::array values; + for (int32_t i = 0; i < 256; i++) + values[i] = SrgbToLinear(float(i) / 255.0f); + return values; + }(); + return table; + + } + + static uint8_t LinearToSrgb(float value) { + + // A table instead of a power per channel, the encoding runs for every pixel of every mip level + static const auto table = []() { + std::array values; + for (size_t i = 0; i < values.size(); i++) { + auto linear = float(i) / float(values.size() - 1); + auto encoded = linear <= 0.0031308f ? linear * 12.92f : 1.055f * std::pow(linear, 1.0f / 2.4f) - 0.055f; + values[i] = uint8_t(encoded * 255.0f + 0.5f); + } + return values; + }(); + + auto idx = size_t(glm::clamp(value, 0.0f, 1.0f) * float(table.size() - 1) + 0.5f); + return table[idx]; + + } + + static int64_t GetLastWriteTime(const std::string& assetPath) { + + std::error_code error; + auto writeTime = std::filesystem::last_write_time(Loader::AssetLoader::GetFullPath(assetPath), error); + return error ? int64_t(0) : int64_t(writeTime.time_since_epoch().count()); + + } + + // Fits large images into a slot, small ones are scaled up by whole factors such that pixel art stays sharp + static ivec2 GetPreviewSize(int32_t width, int32_t height, int32_t maxSize) { + + auto largest = glm::max(width, height); + if (largest <= maxSize) { + auto factor = maxSize / largest; + return ivec2(width, height) * factor; + } + + auto scale = float(maxSize) / float(largest); + return glm::max(ivec2(glm::round(vec2(width, height) * scale)), ivec2(1)); + + } + + // Linear colors with premultiplied alpha from fetch(x, y), averaged over the area of each target pixel + template + static std::vector Resample(int32_t width, int32_t height, ivec2 size, Fetch fetch) { + + std::vector pixels(size_t(size.x) * size_t(size.y), vec4(0.0f)); + + if (size.x >= width && size.y >= height) { + for (int32_t y = 0; y < size.y; y++) + for (int32_t x = 0; x < size.x; x++) + pixels[size_t(y) * size.x + x] = fetch(int32_t(int64_t(x) * width / size.x), int32_t(int64_t(y) * height / size.y)); + return pixels; + } + + std::vector counts(pixels.size(), 0.0f); + for (int32_t y = 0; y < height; y++) { + auto targetY = int32_t(int64_t(y) * size.y / height); + for (int32_t x = 0; x < width; x++) { + auto idx = size_t(targetY) * size.x + size_t(int64_t(x) * size.x / width); + pixels[idx] += fetch(x, y); + counts[idx] += 1.0f; + } + } + + for (size_t i = 0; i < pixels.size(); i++) + pixels[i] /= glm::max(counts[i], 1.0f); + + return pixels; + + } + + // Linear colors with premultiplied alpha to sRGB encoded colors with straight alpha + static void Encode(const std::vector& pixels, std::vector& data) { + + data.resize(pixels.size() * 4); + for (size_t i = 0; i < pixels.size(); i++) { + auto pixel = pixels[i]; + auto color = pixel.a > 0.0f ? vec3(pixel) / pixel.a : vec3(0.0f); + data[i * 4 + 0] = LinearToSrgb(color.r); + data[i * 4 + 1] = LinearToSrgb(color.g); + data[i * 4 + 2] = LinearToSrgb(color.b); + data[i * 4 + 3] = uint8_t(glm::clamp(pixel.a, 0.0f, 1.0f) * 255.0f + 0.5f); + } + + } + + static vec4 Decode(const uint8_t* pixel) { + + const auto& table = GetSrgbToLinearTable(); + auto alpha = float(pixel[3]) / 255.0f; + return vec4(table[pixel[0]] * alpha, table[pixel[1]] * alpha, table[pixel[2]] * alpha, alpha); + + } + + ContentPreviews::PreviewAtlas::PreviewAtlas(int32_t size, uint32_t mipLevels) { + + // The interface is drawn without color conversion, the atlas holds the colors as they are shown + format = VK_FORMAT_R8G8B8A8_UNORM; + + Reallocate(Graphics::ImageType::Image2D, size, size, 1, ::Atlas::Texture::Filtering::MipMapLinear, + ::Atlas::Texture::Wrapping::ClampToEdge, false, false, mipLevels); + RecreateSampler(::Atlas::Texture::Filtering::MipMapLinear, ::Atlas::Texture::Wrapping::ClampToEdge); + + } + + ContentPreviews::~ContentPreviews() { + + JobSystem::Wait(jobGroup); + renderJob.reset(); + + } + + bool ContentPreviews::IsSupported(ContentType type) { + + switch (type) { + case ContentType::Texture: + case ContentType::EnvironmentTexture: + case ContentType::Font: + case ContentType::Audio: + case ContentType::Mesh: + case ContentType::Material: + case ContentType::MaterialGraph: + case ContentType::Prefab: return true; + default: return false; + } + + } + + bool ContentPreviews::IsRendered(ContentType type) { + + return type == ContentType::Mesh || type == ContentType::Material || + type == ContentType::MaterialGraph || type == ContentType::Prefab; + + } + + bool ContentPreviews::Get(const std::string& assetPath, ContentType type, uintmax_t size, int64_t lastWriteTime, Preview& preview) { + + if (!IsSupported(type)) + return false; + + Hash version = 0; + HashCombine(version, assetPath); + HashCombine(version, int32_t(type)); + HashCombine(version, uint64_t(size)); + HashCombine(version, lastWriteTime); + HashCombine(version, slotSize); + HashCombine(version, previewFormatVersion); + + lastRequestTime = Clock::Get(); + requestedThisFrame = true; + + auto [iter, inserted] = entries.try_emplace(assetPath); + auto& entry = iter->second; + + // A changed file keeps showing its last preview until the new one is there + if (inserted || entry.version != version) { + entry.version = version; + entry.type = type; + entry.state = State::Queued; + entry.retryTime = 0.0f; + } + + if (entry.state == State::Failed && entry.retryTime > 0.0f && Clock::Get() >= entry.retryTime) { + entry.state = State::Queued; + entry.retryTime = 0.0f; + } + + if (entry.state == State::Queued && entry.lastRequestFrame != frame) + requested.push_back(assetPath); + entry.lastRequestFrame = frame; + + if (!entry.hasImage || !atlas) + return false; + + auto atlasSize = vec2(float(atlas->width), float(atlas->height)); + auto position = vec2(GetSlotPosition(entry.slot)); + // Half a texel inside, such that the neighboring slots don't shine through at the edges + auto uvMin = (position + 0.5f) / atlasSize; + auto uvMax = (position + vec2(entry.size) - 0.5f) / atlasSize; + + preview.texture = Singletons::imguiWrapper->GetTextureId(atlas.get()); + preview.uvMin = ImVec2(uvMin.x, uvMin.y); + preview.uvMax = ImVec2(uvMax.x, uvMax.y); + preview.size = ImVec2(float(entry.size.x), float(entry.size.y)); + preview.tintable = type == ContentType::Font || type == ContentType::Audio; + preview.transparent = IsRendered(type); + preview.alpha = glm::clamp((Clock::Get() - entry.readyTime) / fadeTime, 0.0f, 1.0f); + + return true; + + } + + bool ContentPreviews::Get(const std::string& assetPath, Preview& preview) { + + // The file as the content discovery found it, such that the content browser requests the same version + auto normalizedPath = Common::Path::Normalize(assetPath); + auto directoryPath = Common::Path::GetDirectory(normalizedPath); + auto dataDirectory = Loader::AssetLoader::GetDataDirectory(); + auto directory = ContentDiscovery::GetDirectory(directoryPath.empty() ? dataDirectory : dataDirectory + "/" + directoryPath); + if (!directory) + return false; + + for (const auto& file : directory->files) { + if (file.assetPath == normalizedPath) + return Get(file.assetPath, file.type, file.size, file.lastWriteTime, preview); + } + + return false; + + } + + void ContentPreviews::Render(const std::string& assetPath, ImVec2 size) { + + auto min = ImGui::GetCursorScreenPos(); + auto max = ImVec2(min.x + size.x, min.y + size.y); + ImGui::Dummy(size); + if (!ImGui::IsItemVisible()) + return; + + auto fileType = Common::Path::GetFileType(assetPath); + std::transform(fileType.begin(), fileType.end(), fileType.begin(), ::tolower); + auto typeIter = Content::contentTypeMapping.find(fileType); + auto type = typeIter != Content::contentTypeMapping.end() ? typeIter->second : ContentType::None; + auto iconTexture = Singletons::imguiWrapper->GetTextureId(&GetIcon(type)); + + auto drawList = ImGui::GetWindowDrawList(); + auto rounding = std::clamp(std::min(size.x, size.y) * 0.12f, 2.0f, Theme::overlayRounding); + drawList->AddRectFilled(min, max, ImGui::GetColorU32(Theme::PreviewBackground()), rounding); + + Preview preview; + if (Get(assetPath, preview)) { + Draw(drawList, preview, type, min, max, iconTexture, false, rounding); + } + else { + auto inset = iconInset * std::min(size.x, size.y); + drawList->AddImage(iconTexture, ImVec2(min.x + inset, min.y + inset), + ImVec2(max.x - inset, max.y - inset), ImVec2(0.0f, 0.0f), ImVec2(1.0f, 1.0f), + ImGui::GetColorU32(Theme::ContentIcon(type, iconAlpha))); + } + + } + + void ContentPreviews::Draw(ImDrawList* drawList, const Preview& preview, ContentType contentType, ImVec2 min, ImVec2 max, + ImTextureID iconTexture, bool framed, float rounding) { + + auto size = ImVec2(max.x - min.x, max.y - min.y); + + // The icon is replaced smoothly once the preview is generated + if (preview.alpha < 1.0f) { + auto inset = iconInset * std::min(size.x, size.y); + drawList->AddImage(iconTexture, ImVec2(min.x + inset, min.y + inset), ImVec2(max.x - inset, max.y - inset), + ImVec2(0.0f, 0.0f), ImVec2(1.0f, 1.0f), ImGui::GetColorU32(Theme::ContentIcon(contentType, iconAlpha * (1.0f - preview.alpha)))); + } + + // Fonts and audio are only a shape, they get some room around them + if (preview.tintable) { + auto inset = 0.12f * std::min(size.x, size.y); + min = ImVec2(min.x + inset, min.y + inset); + max = ImVec2(max.x - inset, max.y - inset); + size = ImVec2(max.x - min.x, max.y - min.y); + } + + // Fitted into the area with the aspect ratio of the content + auto scale = std::min(size.x / std::max(preview.size.x, 1.0f), size.y / std::max(preview.size.y, 1.0f)); + auto fitted = ImVec2(std::floor(preview.size.x * scale), std::floor(preview.size.y * scale)); + auto previewMin = ImVec2(std::floor(min.x + 0.5f * (size.x - fitted.x)), std::floor(min.y + 0.5f * (size.y - fitted.y))); + auto previewMax = ImVec2(previewMin.x + fitted.x, previewMin.y + fitted.y); + + if (preview.tintable) { + drawList->AddImage(preview.texture, previewMin, previewMax, preview.uvMin, preview.uvMax, + ImGui::GetColorU32(Theme::ContentIcon(contentType, 0.85f * preview.alpha))); + } + else if (preview.transparent) { + drawList->AddImage(preview.texture, previewMin, previewMax, preview.uvMin, preview.uvMax, + ImGui::GetColorU32(ImVec4(1.0f, 1.0f, 1.0f, preview.alpha))); + } + else { + if (framed) + rounding = std::clamp(std::min(fitted.x, fitted.y) * 0.06f, 1.0f, Theme::overlayRounding); + drawList->AddImageRounded(preview.texture, previewMin, previewMax, preview.uvMin, preview.uvMax, + ImGui::GetColorU32(ImVec4(1.0f, 1.0f, 1.0f, preview.alpha)), rounding); + // Dark images stand out from the background + if (framed) + drawList->AddRect(previewMin, previewMax, ImGui::GetColorU32(ImGuiCol_Border, 0.6f * preview.alpha), rounding); + } + + } + + Texture::Texture2D& ContentPreviews::GetIcon(ContentType contentType) { + + auto& icons = Singletons::icons; + + switch (contentType) { + case ContentType::Audio: return icons->GetTintable(IconType::Audio); + case ContentType::Mesh: return icons->GetTintable(IconType::Mesh); + case ContentType::MeshSource: return icons->GetTintable(IconType::MeshSource); + case ContentType::Material: return icons->GetTintable(IconType::Material); + case ContentType::MaterialGraph: return icons->GetTintable(IconType::MaterialGraph); + case ContentType::Scene: return icons->GetTintable(IconType::Scene); + case ContentType::Font: return icons->GetTintable(IconType::Font); + case ContentType::Prefab: return icons->GetTintable(IconType::Prefab); + case ContentType::Texture: return icons->GetTintable(IconType::Image); + case ContentType::EnvironmentTexture: return icons->GetTintable(IconType::EnvironmentImage); + case ContentType::Terrain: return icons->GetTintable(IconType::Terrain); + default: return icons->GetTintable(IconType::Document); + } + + } + + void ContentPreviews::Update() { + + if (!atlas && !requested.empty()) + Init(); + + if (atlas) { + ProcessResults(); + StartJobs(); + UpdateRendering(); + if (requestedThisFrame) + Evict(); + } + + requested.clear(); + // Only frames which show previews count, such that they aren't forgotten while nothing shows them + if (requestedThisFrame) + frame++; + requestedThisFrame = false; + + } + + void ContentPreviews::ReleaseUnused() { + + auto now = Clock::Get(); + + // Nothing is rendered for previews which aren't shown, the content is rendered again once it is visible + if (renderJob && now - lastRequestTime > hiddenTime) + CancelRender(); + + } + + void ContentPreviews::Init() { + + atlas = CreateRef(slotSize * slotsPerRow, mipLevels); + + } + + void ContentPreviews::StartJobs() { + + for (const auto& assetPath : requested) { + if (runningJobs >= maxRunningJobs) + break; + + auto iter = entries.find(assetPath); + if (iter == entries.end() || iter->second.state != State::Queued) + continue; + + auto& entry = iter->second; + // The slot is reserved before anything is generated, the content shows its icon without one + if (entry.slot < 0) + entry.slot = AllocateSlot(); + if (entry.slot < 0) + break; + + entry.state = State::Loading; + runningJobs++; + + JobSystem::Execute(jobGroup, [this, assetPath, type = entry.type, version = entry.version](JobData&) { + auto result = Generate(assetPath, type, version); + { + std::scoped_lock lock(resultMutex); + results.push_back(std::move(result)); + } + runningJobs--; + }); + } + + } + + void ContentPreviews::ProcessResults() { + + std::vector finished; + { + std::scoped_lock lock(resultMutex); + finished.swap(results); + } + + std::vector> uploads; + for (const auto& result : finished) { + auto iter = entries.find(result.assetPath); + if (iter == entries.end() || iter->second.version != result.version || iter->second.slot < 0) + continue; + + auto& entry = iter->second; + if (result.failed) { + entry.state = State::Failed; + } + else if (result.needsRender) { + entry.state = State::Rendering; + renderQueue.push_back(result.assetPath); + } + else { + uploads.emplace_back(&entry, &result); + } + } + + Upload(uploads); + + } + + std::vector ContentPreviews::BuildSlotLevels(const Image& image) { + + std::vector levels; + + // The whole slot is written, the parts next to the preview are transparent + std::vector level(size_t(slotSize) * slotSize, vec4(0.0f)); + for (int32_t y = 0; y < image.height; y++) + for (int32_t x = 0; x < image.width; x++) + level[size_t(y) * slotSize + x] = Decode(&image.data[(size_t(y) * image.width + x) * 4]); + + auto levelSize = slotSize; + std::vector data; + for (uint32_t mipLevel = 0; mipLevel < mipLevels; mipLevel++) { + if (mipLevel > 0) { + auto previousSize = levelSize; + levelSize /= 2; + std::vector next(size_t(levelSize) * levelSize); + for (int32_t y = 0; y < levelSize; y++) { + for (int32_t x = 0; x < levelSize; x++) { + auto idx = size_t(2 * y) * previousSize + size_t(2 * x); + next[size_t(y) * levelSize + x] = 0.25f * (level[idx] + level[idx + 1] + + level[idx + previousSize] + level[idx + previousSize + 1]); + } + } + level = std::move(next); + } + + Encode(level, data); + levels.insert(levels.end(), data.begin(), data.end()); + } + + return levels; + + } + + void ContentPreviews::Upload(const std::vector>& uploads) { + + if (uploads.empty()) + return; + + std::vector buffer; + std::vector regions; + + for (const auto& [entry, result] : uploads) { + auto position = GetSlotPosition(entry->slot); + size_t levelOffset = 0; + for (uint32_t mipLevel = 0; mipLevel < mipLevels; mipLevel++) { + auto levelSize = slotSize >> mipLevel; + auto levelBytes = size_t(levelSize) * size_t(levelSize) * 4; + + VkBufferImageCopy region = {}; + region.bufferOffset = buffer.size() + levelOffset; + region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + region.imageSubresource.mipLevel = mipLevel; + region.imageSubresource.baseArrayLayer = 0; + region.imageSubresource.layerCount = 1; + region.imageOffset = { position.x >> mipLevel, position.y >> mipLevel, 0 }; + region.imageExtent = { uint32_t(levelSize), uint32_t(levelSize), 1 }; + regions.push_back(region); + + levelOffset += levelBytes; + } + buffer.insert(buffer.end(), result->slotLevels.begin(), result->slotLevels.end()); + + // Only new previews fade in, not the ones of changed content + if (!entry->hasImage) + entry->readyTime = Clock::Get(); + entry->size = ivec2(result->image.width, result->image.height); + entry->hasImage = true; + entry->state = State::Ready; + } + + // Recorded with the other work of the frame instead of waiting for the device, the device keeps the + // staging buffer until the frame is done + auto device = Graphics::GraphicsDevice::DefaultDevice; + auto stagingBuffer = device->CreateBuffer({ + .usageFlags = VK_BUFFER_USAGE_TRANSFER_SRC_BIT, + .domain = Graphics::BufferDomain::Host, + .data = buffer.data(), + .size = buffer.size() + }); + + auto commandList = device->GetCommandList(Graphics::GraphicsQueue); + commandList->BeginCommands(); + commandList->ImageMemoryBarrier(atlas->image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_ACCESS_TRANSFER_WRITE_BIT, + VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT); + vkCmdCopyBufferToImage(commandList->commandBuffer, stagingBuffer->buffer, atlas->image->image, + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, uint32_t(regions.size()), regions.data()); + commandList->ImageMemoryBarrier(atlas->image, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_ACCESS_SHADER_READ_BIT, + VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); + commandList->EndCommands(); + device->SubmitCommandList(commandList); + + } + + int32_t ContentPreviews::AllocateSlot() { + + if (!freeSlots.empty()) { + auto slot = freeSlots.back(); + freeSlots.pop_back(); + return slot; + } + + if (nextSlot < slotsPerRow * slotsPerRow) + return nextSlot++; + + // The preview which wasn't shown for the longest time makes room, visible ones are kept + Entry* leastRecent = nullptr; + for (auto& [_, entry] : entries) { + if (entry.slot < 0 || entry.state == State::Loading || entry.state == State::Rendering || + entry.lastRequestFrame >= frame - 1) + continue; + if (!leastRecent || entry.lastRequestFrame < leastRecent->lastRequestFrame) + leastRecent = &entry; + } + + if (!leastRecent) + return -1; + + auto slot = leastRecent->slot; + leastRecent->slot = -1; + leastRecent->hasImage = false; + // Generated again once it is visible, the disk cache makes this fast + leastRecent->state = State::Queued; + + return slot; + + } + + void ContentPreviews::Evict() { + + // Content which wasn't visible for a while is forgotten, e.g. after the user browsed through a large project + const int64_t forgetAfterFrames = 3600; + + for (auto iter = entries.begin(); iter != entries.end();) { + auto& entry = iter->second; + auto inFlight = entry.state == State::Loading || entry.state == State::Rendering; + if (!inFlight && frame - entry.lastRequestFrame > forgetAfterFrames) { + if (entry.slot >= 0) + freeSlots.push_back(entry.slot); + iter = entries.erase(iter); + } + else { + iter++; + } + } + + } + + ivec2 ContentPreviews::GetSlotPosition(int32_t slot) const { + + return ivec2(slot % slotsPerRow, slot / slotsPerRow) * slotSize; + + } + + void ContentPreviews::UpdateRendering() { + + while (!renderJob && !renderQueue.empty()) { + auto assetPath = renderQueue.front(); + renderQueue.erase(renderQueue.begin()); + + auto iter = entries.find(assetPath); + if (iter == entries.end() || iter->second.state != State::Rendering) + continue; + + // Content which was scrolled out of view is queued again once it is visible + auto& entry = iter->second; + if (entry.lastRequestFrame < frame - 1) { + entry.state = State::Queued; + continue; + } + + renderJob = std::make_unique(); + renderJob->assetPath = assetPath; + renderJob->version = entry.version; + renderJob->type = entry.type; + + if (!StartRender(*renderJob)) + FinishRender(true); + } + + if (!renderJob) + return; + + // Waiting for the editor doesn't count towards the timeout + if (Singletons::blockingOperation->block) + return; + + auto& job = *renderJob; + job.activeTime += Clock::GetDelta(); + + // The copy of the last frame is read once the device finished that frame, nothing waits for it + if (job.readbackFrame >= 0) { + auto device = Graphics::GraphicsDevice::DefaultDevice; + if (device->GetFrameIndex() - job.readbackFrame > FRAME_DATA_COUNT) { + CPUProfiler::Scope scope("Read preview"); + FinishRender(false); + } + return; + } + + auto timedOut = job.activeTime > renderTimeout; + auto failedToLoad = [](const auto& handle) { + return handle.IsValid() && handle.GetResource()->errorOnLoad; + }; + + if (failedToLoad(job.mesh) || failedToLoad(job.material) || failedToLoad(job.graph)) { + FinishRender(true); + return; + } + + if (!job.root.IsValid()) { + auto isLoaded = [](const auto& handle) { + return !handle.IsValid() || handle.IsLoaded(); + }; + if (!isLoaded(job.mesh) || !isLoaded(job.material) || !isLoaded(job.graph)) { + if (timedOut) + FinishRender(true); + return; + } + + CPUProfiler::Scope scope("Add preview content"); + if (!renderer) + InitRendering(); + AddContent(job); + if (!job.root.IsValid()) { + FinishRender(true); + return; + } + } + + // Textures of the materials are loaded in the background + if (!renderScene->IsFullyLoaded()) { + if (!timedOut) + return; + job.complete = false; + } + + RenderFrame(job); + + } + + bool ContentPreviews::StartRender(RenderJob& job) { + + // Everything is loaded in the background, the job waits for it + switch (job.type) { + case ContentType::Mesh: + job.mesh = FileImporter::ImportFile(job.assetPath); + return job.mesh.IsValid(); + case ContentType::Material: + job.material = ResourceManager::GetOrLoadResourceWithLoaderAsync(job.assetPath, + ResourceOrigin::User, Loader::MaterialLoader::LoadMaterial, false); + return job.material.IsValid(); + case ContentType::MaterialGraph: + job.graph = ResourceManager::GetOrLoadResourceWithLoaderAsync(job.assetPath, + ResourceOrigin::User, Loader::MaterialGraphLoader::LoadGraph); + return job.graph.IsValid(); + case ContentType::Prefab: + return true; + default: + return false; + } + + } + + void ContentPreviews::InitRendering() { + + auto device = Graphics::GraphicsDevice::DefaultDevice; + + auto renderSize = slotSize * renderScale; + renderer = CreateRef(); + renderer->Init(device); + renderTarget = CreateRef(renderSize, renderSize); + renderViewport = CreateRef(0, 0, renderSize, renderSize); + renderTexture = Texture::Texture2D(renderSize, renderSize, VK_FORMAT_R16G16B16A16_SFLOAT); + + auto readbackDesc = Graphics::BufferDesc{ + .usageFlags = VK_BUFFER_USAGE_TRANSFER_DST_BIT, + .domain = Graphics::BufferDomain::Host, + .hostAccess = Graphics::BufferHostAccess::Random, + .size = size_t(renderSize) * size_t(renderSize) * sizeof(float16) * 4 + }; + colorReadback = device->CreateBuffer(readbackDesc); + + // The depth has the scaled resolution of the render target + auto depthTexture = renderTarget->GetData(Renderer::FULL_RES)->depthTexture; + depthSize = ivec2(depthTexture->width, depthTexture->height); + readbackDesc.size = size_t(depthSize.x) * size_t(depthSize.y) * sizeof(float); + depthReadback = device->CreateBuffer(readbackDesc); + + renderScene = CreateRef("Content preview"); + // Like the scenes of the editor, prefabs with rigid bodies or scripts expect one. It never runs + renderScene->physicsWorld = CreateRef(); + renderScene->physicsWorld->pauseSimulation = true; + + auto rootGroup = renderScene->CreatePrefab("Root"); + rootGroup.GetComponent().root = true; + + renderCamera = renderScene->CreateEntity(); + auto& camera = renderCamera.AddComponent(40.0f, 1.0f, 0.01f, 100.0f, + vec3(0.0f), vec2(glm::pi() + 0.6f, -0.55f)); + camera.isMain = true; + + renderLight = renderScene->CreateEntity(); + + } + + void ContentPreviews::AddContent(RenderJob& job) { + + Scene::Entity entity; + if (job.type == ContentType::Mesh) { + entity = renderScene->CreatePrefab(job.mesh, false); + // Skinned meshes need an animation component to be shown + if (job.mesh->data.IsSkinned()) + entity.AddComponent(); + } + else if (job.type == ContentType::Material || job.type == ContentType::MaterialGraph) { + // Graphs are shown with a material which only exists for the preview + if (job.type == ContentType::MaterialGraph) { + job.material = ResourceHandle(CreateRef()); + job.material->graph = job.graph; + } + // Fewer vertices than the sphere of the material editor, a small preview doesn't show displacement in detail + auto sphere = ResourceHandle(DataCreator::CreateSphere(job.material, 64, 96)); + job.mesh = sphere; + entity = renderScene->CreatePrefab(sphere, false); + } + else if (job.type == ContentType::Prefab) { + try { + entity = Serializer::DeserializePrefab(renderScene, job.assetPath); + } + catch (const std::exception&) { + entity = Scene::Entity(); + } + if (!entity.IsValid()) + return; + + // A preview only shows the prefab, scripts aren't executed and sounds aren't played + auto removeAll = [&]() { + std::vector entities; + for (auto componentEntity : renderScene->entityManager.GetSubset()) + entities.push_back(componentEntity); + for (auto componentEntity : entities) + renderScene->entityManager.Erase(componentEntity); + }; + removeAll.template operator()(); + removeAll.template operator()(); + removeAll.template operator()(); + } + + job.root = entity; + + } + + void ContentPreviews::RemoveContent(RenderJob& job) { + + if (job.root.IsValid()) + renderScene->DestroyEntity(job.root, true); + job.root = Scene::Entity(); + + } + + void ContentPreviews::RenderFrame(RenderJob& job) { + + // A frame which the renderer skips, e.g. while the window is minimized, doesn't count + auto device = Graphics::GraphicsDevice::DefaultDevice; + if (!device->swapChain->isComplete) + return; + + const float deltaTime = 1.0f / 60.0f; + + CPUProfiler::Scope scope("Update preview scene"); + if (job.renderedFrames == 0) { + // The camera direction and the bounds of prefabs are known after an update + renderScene->Update(deltaTime, renderCamera); + + Volume::AABB bounds(vec3(-1.0f), vec3(1.0f)); + if (job.type == ContentType::Prefab) + bounds = renderScene->GetHierarchyBounds(job.root).value_or(bounds); + else if (job.mesh.IsLoaded()) + bounds = job.mesh->data.aabb; + + // The sphere of materials fills the preview, other content fits in with its bounding sphere + auto center = 0.5f * (bounds.min + bounds.max); + auto radius = glm::max(0.5f * glm::length(bounds.max - bounds.min), 0.01f); + if (job.type == ContentType::Material || job.type == ContentType::MaterialGraph) + radius = 1.05f; + + auto& camera = renderCamera.GetComponent(); + auto distance = radius / std::sin(glm::radians(camera.fieldOfView) * 0.5f); + camera.location = center - camera.direction * distance; + camera.nearPlane = 0.01f * distance; + camera.farPlane = 4.0f * (distance + radius); + + // Prefabs might bring their own light, the light of the preview is only there without one + auto hasOwnLight = false; + for (auto lightEntity : renderScene->GetSubset()) + hasOwnLight |= lightEntity != renderLight; + + auto hasLight = renderLight.HasComponent(); + if (hasOwnLight && hasLight) { + renderLight.RemoveComponent(); + } + else if (!hasOwnLight && !hasLight) { + auto& light = renderLight.AddComponent(LightType::DirectionalLight); + light.properties.directional.direction = vec3(-0.5f, -1.0f, -1.0f); + light.color = vec3(255, 236, 209) / 255.0f; + light.intensity = 10.0f; + light.AddDirectionalShadow(distance + 2.0f * radius, 3.0f, 1024, 0.05f, 1, 0.9f); + light.isMain = true; + } + if (!hasOwnLight) + renderLight.GetComponent().shadow->distance = distance + 2.0f * radius; + } + + renderScene->Update(deltaTime, renderCamera); + + scope.Next("Render preview scene"); + renderer->Update(); + renderer->RenderScene(renderViewport, renderTarget, renderScene, {}, &renderTexture); + job.renderedFrames++; + + // Graphs compile their pipelines in the background, the frames only count once they are used + auto graphPending = false; + for (const auto& mesh : renderScene->GetMeshes()) { + if (!mesh.IsLoaded()) + continue; + for (const auto& subData : mesh->data.subData) + graphPending |= subData.mainPipelines.graphPending; + } + if (graphPending) { + if (job.activeTime <= renderTimeout) + job.renderedFrames = 1; + else + job.complete = false; + } + + if (job.renderedFrames >= renderFrames) { + scope.Next("Copy preview"); + CopyForReadback(); + job.readbackFrame = device->GetFrameIndex(); + } + + } + + void ContentPreviews::CopyForReadback() { + + auto device = Graphics::GraphicsDevice::DefaultDevice; + + // The swap of the render target moved the depth of the last frame into the history + auto depthImage = renderTarget->GetHistoryData(Renderer::FULL_RES)->depthTexture->image; + auto colorImage = renderTexture.image; + + auto commandList = device->GetCommandList(Graphics::QueueType::GraphicsQueue); + commandList->BeginCommands(); + + auto colorLayout = colorImage->layout; + auto colorAccess = colorImage->accessMask; + auto depthLayout = depthImage->layout; + auto depthAccess = depthImage->accessMask; + + Graphics::ImageBarrier transferBarriers[] = { + { colorImage, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_ACCESS_TRANSFER_READ_BIT }, + { depthImage, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_ACCESS_TRANSFER_READ_BIT }, + }; + commandList->PipelineBarrier(transferBarriers, {}, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT); + + commandList->CopyImageToBuffer(colorImage, colorReadback); + commandList->CopyImageToBuffer(depthImage, depthReadback); + + Graphics::ImageBarrier restoreBarriers[] = { + { colorImage, colorLayout, colorAccess }, + { depthImage, depthLayout, depthAccess }, + }; + commandList->PipelineBarrier(restoreBarriers, {}, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); + commandList->MemoryBarrier(VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_HOST_READ_BIT, + VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT); + + commandList->EndCommands(); + device->SubmitCommandList(commandList); + + } + + ContentPreviews::Image ContentPreviews::ProcessCapture(const std::vector& colors, const std::vector& depth, + ivec2 depthSize) { + + Image image; + + auto width = slotSize * renderScale; + auto getDepth = [&](int32_t x, int32_t y) { + return depth[size_t(y * depthSize.y / width) * depthSize.x + size_t(x * depthSize.x / width)]; + }; + + // The content fits into the view, so a corner shows the background + auto background = getDepth(0, 0); + + // The post processing already encoded the colors for the display, they are averaged as linear colors + auto size = ivec2(slotSize); + std::vector pixels(size_t(size.x) * size_t(size.y), vec4(0.0f)); + for (int32_t y = 0; y < size.y; y++) { + for (int32_t x = 0; x < size.x; x++) { + vec4 sum(0.0f); + for (int32_t sampleY = 0; sampleY < renderScale; sampleY++) { + for (int32_t sampleX = 0; sampleX < renderScale; sampleX++) { + auto pixelX = x * renderScale + sampleX; + auto pixelY = y * renderScale + sampleY; + if (getDepth(pixelX, pixelY) == background) + continue; + auto pixel = size_t(pixelY) * width + size_t(pixelX); + auto color = [&](size_t channel) { + return SrgbToLinear(glm::detail::toFloat32(colors[pixel * 4 + channel])); + }; + sum += vec4(color(0), color(1), color(2), 1.0f); + } + } + pixels[size_t(y) * size.x + x] = sum / float(renderScale * renderScale); + } + } + + // Nothing in view, e.g. an empty prefab + auto empty = std::all_of(pixels.begin(), pixels.end(), [](const vec4& pixel) { return pixel.a == 0.0f; }); + if (empty) + return image; + + image.width = size.x; + image.height = size.y; + Encode(pixels, image.data); + + return image; + + } + + void ContentPreviews::FinishRender(bool failed) { + + auto& job = *renderJob; + + auto iter = entries.find(job.assetPath); + if (iter != entries.end() && iter->second.version == job.version) { + if (failed) { + // Loading or rendering might work later, e.g. after a long import + iter->second.state = State::Failed; + iter->second.retryTime = Clock::Get() + retryDelay; + } + else { + std::vector colors(colorReadback->size / sizeof(float16)); + std::vector depth(depthReadback->size / sizeof(float)); + colorReadback->Invalidate(); + std::memcpy(colors.data(), colorReadback->Map(), colorReadback->size); + colorReadback->Unmap(); + depthReadback->Invalidate(); + std::memcpy(depth.data(), depthReadback->Map(), depthReadback->size); + depthReadback->Unmap(); + + // Incomplete previews are shown, but not cached + auto dependencies = job.complete ? GetDependencies() : std::vector(); + JobSystem::Execute(jobGroup, [this, assetPath = job.assetPath, version = job.version, complete = job.complete, + dependencies, colors = std::move(colors), depth = std::move(depth), depthSize = depthSize](JobData&) { + auto image = ProcessCapture(colors, depth, depthSize); + auto result = Result{ .assetPath = assetPath, .version = version, .failed = image.data.empty() }; + if (!result.failed) { + if (complete) + WriteCache(version, image, dependencies); + result.slotLevels = BuildSlotLevels(image); + result.image = std::move(image); + } + std::scoped_lock lock(resultMutex); + results.push_back(std::move(result)); + }); + } + } + + RemoveContent(job); + renderJob.reset(); + + } + + void ContentPreviews::CancelRender() { + + auto iter = entries.find(renderJob->assetPath); + if (iter != entries.end() && iter->second.version == renderJob->version) + iter->second.state = State::Queued; + + RemoveContent(*renderJob); + renderJob.reset(); + + } + + std::vector ContentPreviews::GetDependencies() { + + std::set paths; + auto add = [&](const auto& handle) { + if (handle.IsValid() && !handle.IsGenerated()) + paths.insert(handle.GetResource()->path); + }; + + for (const auto& mesh : renderScene->GetMeshes()) + add(mesh); + + for (const auto& material : renderScene->GetMaterials()) { + add(material); + add(material->graph); + for (const auto& map : material->GetMaps()) + add(map); + for (const auto& map : material->GetGraphTextures()) + add(map); + } + + // The file of the preview itself is part of the version + paths.erase(renderJob->assetPath); + + return std::vector(paths.begin(), paths.end()); + + } + + ContentPreviews::Result ContentPreviews::Generate(const std::string& assetPath, ContentType type, Hash version) { + + Result result = { .assetPath = assetPath, .version = version }; + + try { + if (!ReadCache(version, IsRendered(type), result.image)) { + if (IsRendered(type)) { + result.needsRender = true; + return result; + } + + switch (type) { + case ContentType::Texture: result.image = LoadTexture(assetPath); break; + case ContentType::EnvironmentTexture: result.image = LoadEnvironmentTexture(assetPath); break; + case ContentType::Font: result.image = LoadFont(assetPath); break; + case ContentType::Audio: result.image = LoadAudio(assetPath); break; + default: break; + } + + if (!result.image.data.empty()) + WriteCache(version, result.image, {}); + } + } + catch (const std::exception&) { + result.image = Image(); + } + + result.failed = result.image.data.empty(); + if (!result.failed) + result.slotLevels = BuildSlotLevels(result.image); + + return result; + + } + + std::string ContentPreviews::GetCachePath(Hash version) { + + // Not an image extension, the content discovery would find the previews otherwise + return ".cache/previews/" + std::to_string(version) + ".preview"; + + } + + void ContentPreviews::WriteCache(Hash version, const Image& image, const std::vector& dependencies) { + + std::vector fileData; + auto write = [](void* context, void* data, int size) { + auto fileData = static_cast*>(context); + fileData->insert(fileData->end(), static_cast(data), static_cast(data) + size); + }; + if (!stbi_write_png_to_func(write, &fileData, image.width, image.height, 4, image.data.data(), image.width * 4)) + return; + + // The files the preview depends on with their time of modification, a change of one renders it again + std::string dependencyData; + for (const auto& dependency : dependencies) + dependencyData += dependency + "\n" + std::to_string(GetLastWriteTime(dependency)) + "\n"; + + // Written aside and renamed, a preview is never read while it is written + auto writeFile = [](const std::string& path, const char* data, size_t size) { + auto tempPath = path + "." + std::to_string(std::random_device()()); + auto stream = Loader::AssetLoader::WriteFile(tempPath, std::ios::out | std::ios::binary); + if (!stream.is_open()) + return; + + stream.write(data, std::streamsize(size)); + stream.close(); + + std::error_code error; + if (!stream.fail()) + std::filesystem::rename(Loader::AssetLoader::GetFullPath(tempPath), Loader::AssetLoader::GetFullPath(path), error); + if (stream.fail() || error) + Loader::AssetLoader::RemoveFile(tempPath); + }; + + auto cachePath = GetCachePath(version); + writeFile(cachePath + ".dependencies", dependencyData.data(), dependencyData.size()); + writeFile(cachePath, fileData.data(), fileData.size()); + + } + + bool ContentPreviews::ReadCache(Hash version, bool checkDependencies, Image& image) { + + auto cachePath = GetCachePath(version); + if (!Loader::AssetLoader::FileExists(cachePath)) + return false; + + if (checkDependencies) { + auto dependencyPath = cachePath + ".dependencies"; + if (!Loader::AssetLoader::FileExists(dependencyPath)) + return false; + + auto stream = Loader::AssetLoader::ReadFile(dependencyPath, std::ios::in); + std::string path, writeTime; + while (std::getline(stream, path) && std::getline(stream, writeTime)) { + if (std::to_string(GetLastWriteTime(path)) != writeTime) + return false; + } + } + + auto stream = Loader::AssetLoader::ReadFile(cachePath, std::ios::in | std::ios::binary); + if (!stream.is_open()) + return false; + + auto buffer = Loader::AssetLoader::GetFileContent(stream); + int32_t width, height, channels; + auto pixels = stbi_load_from_memory(reinterpret_cast(buffer.data()), int32_t(buffer.size()), + &width, &height, &channels, 4); + if (!pixels) + return false; + + auto fits = width > 0 && height > 0 && width <= slotSize && height <= slotSize; + if (fits) { + image.width = width; + image.height = height; + image.data.assign(pixels, pixels + size_t(width) * size_t(height) * 4); + } + stbi_image_free(pixels); + + return fits; + + } + + ContentPreviews::Image ContentPreviews::LoadTexture(const std::string& assetPath) { + + Image image; + + int32_t width = 0, height = 0; + Ref> ktxImage; + stbi_uc* stbiData = nullptr; + + if (Loader::KtxLoader::IsKtxFile(assetPath)) { + // Only the levels up to the preview size are read and the one closest to it is decoded + ktxImage = Loader::KtxLoader::DecodeImage(assetPath, slotSize); + if (!ktxImage) + return image; + width = ktxImage->width; + height = ktxImage->height; + } + else { + // Streamed from the file, only the decoded image is in memory + int32_t channels; + stbiData = stbi_load(Loader::AssetLoader::GetFullPath(assetPath).c_str(), &width, &height, &channels, 4); + if (!stbiData) + return image; + } + + const uint8_t* pixels = ktxImage ? ktxImage->GetData().data() : stbiData; + auto size = GetPreviewSize(width, height, slotSize); + auto resampled = Resample(width, height, size, [&](int32_t x, int32_t y) { + return Decode(&pixels[(size_t(y) * width + x) * 4]); + }); + + if (stbiData) + stbi_image_free(stbiData); + + image.width = size.x; + image.height = size.y; + Encode(resampled, image.data); + + return image; + + } + + ContentPreviews::Image ContentPreviews::LoadEnvironmentTexture(const std::string& assetPath) { + + Image image; + + // Streamed from the file, only the decoded image is in memory + int32_t width, height, channels; + auto data = stbi_loadf(Loader::AssetLoader::GetFullPath(assetPath).c_str(), &width, &height, &channels, 3); + if (!data) + return image; + + auto size = GetPreviewSize(width, height, slotSize); + auto resampled = Resample(width, height, size, [&](int32_t x, int32_t y) { + auto pixel = data + (size_t(y) * width + x) * 3; + return vec4(pixel[0], pixel[1], pixel[2], 1.0f); + }); + stbi_image_free(data); + + // The exposure adapts to the average brightness, environments have very different ranges + double logLuminance = 0.0; + for (const auto& pixel : resampled) + logLuminance += std::log(1e-4 + double(glm::dot(vec3(pixel), vec3(0.2126f, 0.7152f, 0.0722f)))); + auto averageLuminance = float(std::exp(logLuminance / double(glm::max(resampled.size(), size_t(1))))); + auto exposure = glm::clamp(0.18f / averageLuminance, 1e-4f, 1e4f); + + for (auto& pixel : resampled) { + // Fitted ACES curve + auto color = vec3(pixel) * exposure * 0.6f; + color = glm::clamp((color * (2.51f * color + 0.03f)) / (color * (2.43f * color + 0.59f) + 0.14f), 0.0f, 1.0f); + pixel = vec4(color, 1.0f); + } + + image.width = size.x; + image.height = size.y; + Encode(resampled, image.data); + + return image; + + } + + ContentPreviews::Image ContentPreviews::LoadFont(const std::string& assetPath) { + + Image image; + + auto stream = Loader::AssetLoader::ReadFile(assetPath, std::ios::in | std::ios::binary); + if (!stream.is_open()) + return image; + auto buffer = Loader::AssetLoader::GetFileContent(stream); + stream.close(); + + auto fontData = reinterpret_cast(buffer.data()); + auto offset = stbtt_GetFontOffsetForIndex(fontData, 0); + stbtt_fontinfo font; + if (offset < 0 || !stbtt_InitFont(&font, fontData, offset)) + return image; + + const int32_t codepoints[] = { 'A', 'a' }; + + // Calls the function with the position of each glyph on the line + auto forEachGlyph = [&](float scale, auto function) { + float pen = 0.0f; + for (size_t i = 0; i < std::size(codepoints); i++) { + function(codepoints[i], int32_t(pen)); + + int32_t advance, leftBearing; + stbtt_GetCodepointHMetrics(&font, codepoints[i], &advance, &leftBearing); + pen += float(advance) * scale; + if (i + 1 < std::size(codepoints)) + pen += float(stbtt_GetCodepointKernAdvance(&font, codepoints[i], codepoints[i + 1])) * scale; + } + }; + + // The bounds of the text at a reference size, the text is then scaled to fill the preview + auto measure = [&](float scale, ivec2& min, ivec2& max) { + min = ivec2(std::numeric_limits::max()); + max = ivec2(std::numeric_limits::min()); + forEachGlyph(scale, [&](int32_t codepoint, int32_t pen) { + int32_t x0, y0, x1, y1; + stbtt_GetCodepointBitmapBox(&font, codepoint, scale, scale, &x0, &y0, &x1, &y1); + min = glm::min(min, ivec2(pen + x0, y0)); + max = glm::max(max, ivec2(pen + x1, y1)); + }); + }; + + ivec2 min, max; + auto referenceScale = stbtt_ScaleForPixelHeight(&font, 100.0f); + measure(referenceScale, min, max); + auto referenceSize = vec2(max - min); + if (referenceSize.x <= 0.0f || referenceSize.y <= 0.0f) + return image; + + auto fit = glm::min(0.72f * float(slotSize) / referenceSize.x, 0.6f * float(slotSize) / referenceSize.y); + auto scale = referenceScale * fit; + measure(scale, min, max); + + image.width = slotSize; + image.height = slotSize; + image.data.assign(size_t(slotSize) * slotSize * 4, 0); + + auto origin = (ivec2(slotSize) - (max - min)) / 2 - min; + forEachGlyph(scale, [&](int32_t codepoint, int32_t pen) { + int32_t width, height, offsetX, offsetY; + auto bitmap = stbtt_GetCodepointBitmap(&font, scale, scale, codepoint, &width, &height, &offsetX, &offsetY); + if (!bitmap) + return; + + for (int32_t y = 0; y < height; y++) { + for (int32_t x = 0; x < width; x++) { + auto targetX = origin.x + pen + offsetX + x; + auto targetY = origin.y + offsetY + y; + if (targetX < 0 || targetY < 0 || targetX >= slotSize || targetY >= slotSize) + continue; + auto idx = (size_t(targetY) * slotSize + targetX) * 4; + image.data[idx + 0] = 255; + image.data[idx + 1] = 255; + image.data[idx + 2] = 255; + image.data[idx + 3] = std::max(image.data[idx + 3], bitmap[size_t(y) * width + x]); + } + } + stbtt_FreeBitmap(bitmap, nullptr); + }); + + return image; + + } + + ContentPreviews::Image ContentPreviews::LoadAudio(const std::string& assetPath) { + + Image image; + + // Streamed from the file, the file content isn't kept next to the samples + SDL_AudioSpec spec; + uint8_t* data = nullptr; + uint32_t length = 0; + if (!SDL_LoadWAV(Loader::AssetLoader::GetFullPath(assetPath).c_str(), &spec, &data, &length)) + return image; + + // One channel of floats is enough to draw the waveform + SDL_AudioSpec floatSpec = { .format = SDL_AUDIO_F32, .channels = 1, .freq = spec.freq }; + uint8_t* converted = nullptr; + int32_t convertedLength = 0; + auto success = SDL_ConvertAudioSamples(&spec, data, int32_t(length), &floatSpec, &converted, &convertedLength); + SDL_free(data); + if (!success) + return image; + + auto samples = reinterpret_cast(converted); + auto sampleCount = size_t(convertedLength) / sizeof(float); + + // Bars with the loudness of a part of the audio, the loudest one fills the height + const int32_t barWidth = 3; + const int32_t barSpacing = 2; + const int32_t barCount = (slotSize + barSpacing) / (barWidth + barSpacing); + std::vector loudness(barCount, 0.0f); + for (int32_t i = 0; i < barCount && sampleCount > 0; i++) { + auto start = sampleCount * size_t(i) / size_t(barCount); + auto end = glm::max(sampleCount * size_t(i + 1) / size_t(barCount), start + 1); + double sum = 0.0; + for (auto j = start; j < end; j++) + sum += double(samples[j]) * double(samples[j]); + loudness[i] = float(std::sqrt(sum / double(end - start))); + } + SDL_free(converted); + + auto maxLoudness = *std::max_element(loudness.begin(), loudness.end()); + + image.width = slotSize; + image.height = slotSize; + image.data.assign(size_t(slotSize) * slotSize * 4, 0); + + auto barsWidth = barCount * (barWidth + barSpacing) - barSpacing; + auto startX = (slotSize - barsWidth) / 2; + auto center = float(slotSize) * 0.5f; + auto maxHeight = float(slotSize) * 0.6f; + + for (int32_t i = 0; i < barCount; i++) { + auto value = maxLoudness > 0.0f ? loudness[i] / maxLoudness : 0.0f; + // Quiet parts stay visible as a line + auto halfHeight = glm::max(0.5f * maxHeight * value, 1.5f); + for (int32_t y = 0; y < slotSize; y++) { + // Covered part of the pixel, such that the ends of the bars are smooth + auto pixelMin = float(y); + auto coverage = glm::clamp(glm::min(pixelMin + 1.0f, center + halfHeight) - + glm::max(pixelMin, center - halfHeight), 0.0f, 1.0f); + if (coverage <= 0.0f) + continue; + for (int32_t x = 0; x < barWidth; x++) { + auto idx = (size_t(y) * slotSize + size_t(startX + i * (barWidth + barSpacing) + x)) * 4; + image.data[idx + 0] = 255; + image.data[idx + 1] = 255; + image.data[idx + 2] = 255; + image.data[idx + 3] = uint8_t(coverage * 255.0f + 0.5f); + } + } + } + + return image; + + } + +} diff --git a/src/editor/ContentPreviews.h b/src/editor/ContentPreviews.h new file mode 100644 index 000000000..3c7630384 --- /dev/null +++ b/src/editor/ContentPreviews.h @@ -0,0 +1,254 @@ +#pragma once + +#include "Content.h" + +#include "System.h" +#include "Viewport.h" +#include "Material.h" +#include "common/Hash.h" +#include "jobsystem/JobSystem.h" +#include "mesh/Mesh.h" +#include "materialgraph/MaterialGraph.h" +#include "resource/Resource.h" +#include "scene/Scene.h" +#include "texture/Texture2D.h" +#include "renderer/MainRenderer.h" +#include "renderer/target/RenderTarget.h" + +#include + +#include +#include +#include +#include +#include + +namespace Atlas::Editor { + + // Small pictures of content, e.g. of textures, meshes and materials. All previews share one texture of a fixed size, + // the ones which weren't shown for the longest time make room for new ones. Images are decoded in the background, + // meshes and materials are rendered one after another. Generated previews are cached on disk (.cache/previews/) + class ContentPreviews { + + public: + struct Preview { + ImTextureID texture = {}; + ImVec2 uvMin; + ImVec2 uvMax; + // In pixels of the preview, which has the aspect ratio of the content + ImVec2 size; + // Previews of fonts and audio only have an alpha channel and are tinted like icons + bool tintable = false; + // Rendered meshes and materials have no background + bool transparent = false; + // Previews fade in once they are generated + float alpha = 1.0f; + }; + + ContentPreviews() = default; + + ~ContentPreviews(); + + static bool IsSupported(ContentType type); + + // Requests the preview of content which is visible in this frame. False while there is no preview (yet) + bool Get(const std::string& assetPath, ContentType type, uintmax_t size, int64_t lastWriteTime, Preview& preview); + + // Same for content of which only the path is known, e.g. a resource + bool Get(const std::string& assetPath, Preview& preview); + + // Item with the preview of the content, or the icon of its type while there is none + void Render(const std::string& assetPath, ImVec2 size); + + // The preview fitted into the area, the icon fades out while the preview fades in. Framed previews are + // outlined, the others have the given rounding + void Draw(ImDrawList* drawList, const Preview& preview, ContentType type, ImVec2 min, ImVec2 max, + ImTextureID iconTexture, bool framed, float rounding = 0.0f); + + // Shown for content without a preview (yet) + Texture::Texture2D& GetIcon(ContentType type); + + // Generates, uploads and evicts previews, called once per frame after the previews were requested + void Update(); + + // Stops rendering once no previews were requested for a moment, e.g. after the content browser was closed + void ReleaseUnused(); + + static constexpr int32_t slotSize = 160; + // Icons of content without a preview (yet), relative to the size of the area + static constexpr float iconInset = 0.17f; + static constexpr float iconAlpha = 0.85f; + + private: + // The preview texture has a few mip levels, such that small icons don't flicker + class PreviewAtlas : public Texture::Texture2D { + public: + PreviewAtlas(int32_t size, uint32_t mipLevels); + }; + + enum class State { + Queued = 0, + Loading, + Rendering, + Ready, + Failed + }; + + struct Image { + int32_t width = 0; + int32_t height = 0; + // RGBA with sRGB encoded colors, as they are shown + std::vector data; + }; + + struct Entry { + Hash version = 0; + ContentType type = ContentType::None; + State state = State::Queued; + + int32_t slot = -1; + ivec2 size = ivec2(0); + bool hasImage = false; + + int64_t lastRequestFrame = -1; + float readyTime = 0.0f; + // Failures which might go away, e.g. a timeout while loading, are tried again after this time + float retryTime = 0.0f; + }; + + struct Result { + std::string assetPath; + Hash version = 0; + // Meshes and materials which aren't cached are rendered + bool needsRender = false; + bool failed = false; + Image image; + // All mip levels of the slot, ready to be uploaded + std::vector slotLevels; + }; + + struct RenderJob { + std::string assetPath; + Hash version = 0; + ContentType type = ContentType::None; + // Only counts while the job is worked on, e.g. not while the editor blocks rendering + float activeTime = 0.0f; + + ResourceHandle mesh; + ResourceHandle material; + ResourceHandle graph; + + // The content in the preview scene + Scene::Entity root; + + int32_t renderedFrames = 0; + // Rendered after a timeout, e.g. with textures which didn't load. Such previews aren't cached + bool complete = true; + // Frame of the device in which the last frame was copied, it's read once the device finished it + int32_t readbackFrame = -1; + }; + + void Init(); + + void StartJobs(); + + void ProcessResults(); + + void Upload(const std::vector>& uploads); + + int32_t AllocateSlot(); + + void UpdateRendering(); + + bool StartRender(RenderJob& job); + + void InitRendering(); + + void AddContent(RenderJob& job); + + void RemoveContent(RenderJob& job); + + void RenderFrame(RenderJob& job); + + void CopyForReadback(); + + void FinishRender(bool failed); + + void CancelRender(); + + void Evict(); + + ivec2 GetSlotPosition(int32_t slot) const; + + static Result Generate(const std::string& assetPath, ContentType type, Hash version); + + // Mip levels of the whole slot with the image in its corner, the rest of the slot is transparent + static std::vector BuildSlotLevels(const Image& image); + + // Files the rendered preview depends on, e.g. the textures of a material + std::vector GetDependencies(); + + static Image ProcessCapture(const std::vector& colors, const std::vector& depth, ivec2 depthSize); + + static std::string GetCachePath(Hash version); + + static void WriteCache(Hash version, const Image& image, const std::vector& dependencies); + + static bool ReadCache(Hash version, bool checkDependencies, Image& image); + + static Image LoadTexture(const std::string& assetPath); + + static Image LoadEnvironmentTexture(const std::string& assetPath); + + static Image LoadFont(const std::string& assetPath); + + static Image LoadAudio(const std::string& assetPath); + + static bool IsRendered(ContentType type); + + Ref atlas; + + std::unordered_map entries; + std::vector requested; + std::vector freeSlots; + int32_t nextSlot = 0; + int64_t frame = 0; + float lastRequestTime = 0.0f; + bool requestedThisFrame = false; + + JobGroup jobGroup{ "Content previews", JobPriority::Low }; + std::atomic_int32_t runningJobs = 0; + std::mutex resultMutex; + std::vector results; + + // Content which has to be rendered, one after another + std::vector renderQueue; + Scope renderJob; + + // Created once and kept, all rendered previews share the renderer and the scene, only the content changes + Ref renderer; + Ref renderTarget; + Ref renderViewport; + Texture::Texture2D renderTexture; + Ref renderScene; + Scene::Entity renderCamera; + Scene::Entity renderLight; + Ref colorReadback; + Ref depthReadback; + ivec2 depthSize = ivec2(0); + + static constexpr int32_t slotsPerRow = 24; + static constexpr uint32_t mipLevels = 6; + // Decoding large images needs a lot of memory, so only a few run at once + static constexpr int32_t maxRunningJobs = 2; + // Rendered at a higher resolution, the edges against the transparent background are smooth then + static constexpr int32_t renderScale = 2; + static constexpr int32_t renderFrames = 16; + static constexpr float renderTimeout = 20.0f; + static constexpr float retryDelay = 30.0f; + static constexpr float hiddenTime = 1.0f; + static constexpr float fadeTime = 0.15f; + + }; + +} diff --git a/src/editor/DataCreator.cpp b/src/editor/DataCreator.cpp index 98395e14e..1c9f60b2a 100644 --- a/src/editor/DataCreator.cpp +++ b/src/editor/DataCreator.cpp @@ -16,17 +16,7 @@ namespace Atlas::Editor { auto& mainHierarchy = mainGroup.GetComponent(); mainHierarchy.root = true; - auto directionalLightEntity = scene->CreateEntity(); - directionalLightEntity.AddComponent("Directional light"); - auto& directionalLight = directionalLightEntity.AddComponent(LightType::DirectionalLight); - - directionalLight.properties.directional.direction = glm::vec3(0.0f, -1.0f, 1.0f); - directionalLight.color = glm::vec3(255, 236, 209) / 255.0f; - directionalLight.intensity = 10.0f; - directionalLight.AddDirectionalShadow(200.0f, 3.0f, 2048, 0.05f, 3, 0.9f); - directionalLight.isMain = true; - - mainHierarchy.AddChild(directionalLightEntity); + AddDirectionalLight(scene, mainHierarchy, vec3(0.0f, -1.0f, 1.0f)); scene->reflection = CreateRef(); @@ -66,26 +56,52 @@ namespace Atlas::Editor { } + Ref DataCreator::CreatePreviewScene(const std::string& name, const Volume::AABB& bounds) { + + auto extent = std::max(glm::length(bounds.max - bounds.min), 1.0f); + auto scene = CreateRef(name, vec3(-4.0f * extent), vec3(4.0f * extent), 4); + + auto mainGroup = scene->CreatePrefab("Root"); + auto& mainHierarchy = mainGroup.GetComponent(); + mainHierarchy.root = true; + + // Lights the side the camera of the preview looks at first + AddDirectionalLight(scene, mainHierarchy, vec3(-0.5f, -1.0f, -1.0f)); + + // Only what lights the asset, e.g. no clouds or fog, such that a preview is created fast + scene->reflection = CreateRef(); + scene->sky.atmosphere = CreateRef(); + scene->sss = CreateRef(); + + scene->postProcessing.taa = PostProcessing::TAA(0.99f); + scene->postProcessing.sharpen.enable = true; + scene->postProcessing.sharpen.factor = 0.15f; + + // The probes only cover the asset + auto volumeMargin = vec3(0.1f * extent); + scene->irradianceVolume = CreateRef( + Volume::AABB(bounds.min - volumeMargin, bounds.max + volumeMargin), ivec3(8), 1); + scene->irradianceVolume->rayCount = 32; + + scene->physicsWorld = CreateRef(); + scene->physicsWorld->pauseSimulation = true; + + scene->rayTracingWorld = CreateRef(); + + return scene; + + } + Ref DataCreator::CreateSceneFromMesh(const std::string& filename, vec3 min, vec3 max, - int32_t depth, bool invertUVs, bool addRigidBodies, bool makeMeshesStatic) { + int32_t depth, bool invertUVs, bool addRigidBodies, bool makeMeshesStatic, Loader::ImportTextureFormat textureFormat) { auto scene = Loader::ModelImporter::ImportScene(filename, min, max, depth, - true, makeMeshesStatic, invertUVs, 2048); + true, makeMeshesStatic, invertUVs, 4096, textureFormat, true); - auto rootEntity = scene->GetEntityByName("Root"); + auto rootEntity = scene->GetRootEntity(); auto& mainHierarchy = rootEntity.GetComponent(); - auto directionalLightEntity = scene->CreateEntity(); - directionalLightEntity.AddComponent("Directional light"); - auto& directionalLight = directionalLightEntity.AddComponent(LightType::DirectionalLight); - - directionalLight.properties.directional.direction = glm::vec3(0.0f, -1.0f, 1.0f); - directionalLight.color = glm::vec3(255, 236, 209) / 255.0f; - directionalLight.intensity = 10.0f; - directionalLight.AddDirectionalShadow(200.0f, 3.0f, 2048, 0.05f, 3, 0.9f); - directionalLight.isMain = true; - - mainHierarchy.AddChild(directionalLightEntity); + AddDirectionalLight(scene, mainHierarchy, vec3(0.0f, -1.0f, 1.0f)); scene->reflection = CreateRef(); @@ -120,29 +136,20 @@ namespace Atlas::Editor { scene->physicsWorld->pauseSimulation = true; scene->rayTracingWorld = CreateRef(); - scene->postProcessing.fsr2 = true; - - scene->Update(1.0f); - - min = glm::vec3(std::numeric_limits::max()); - max = glm::vec3(-std::numeric_limits::max()); - - Volume::AABB aabb(min, max); - auto meshSubset = scene->GetSubset(); - for (auto entity : meshSubset) { - const auto& meshComponent = meshSubset.Get(entity); + scene->postProcessing.upscaler = PostProcessing::Upscaler::FSR2; - aabb.Grow(meshComponent.aabb); - } - - if (addRigidBodies) { - for (auto entity : meshSubset) { - const auto& meshComponent = meshSubset.Get(entity); + // This runs in a job while frames are running, only the main thread may update a scene. The global + // transforms don't exist yet, the bodies are created once their meshes are imported + std::function addBodies; + addBodies = [&](Scene::Entity entity, const mat4& parentMatrix) { + auto transformComponent = entity.TryGetComponent(); + auto globalMatrix = transformComponent ? parentMatrix * transformComponent->matrix : parentMatrix; - auto transformComponent = entity.GetComponent(); + auto meshComponent = entity.TryGetComponent(); + if (meshComponent && transformComponent) { Atlas::Physics::MeshShapeSettings settings = { - .mesh = meshComponent.mesh, - .scale = transformComponent.DecomposeGlobal().scale + .mesh = meshComponent->mesh, + .scale = Common::MatrixDecomposition(globalMatrix).scale }; auto shape = Atlas::Physics::ShapesManager::CreateShape(settings); @@ -152,7 +159,16 @@ namespace Atlas::Editor { }; entity.AddComponent(bodySettings); } - } + + auto hierarchyComponent = entity.TryGetComponent(); + if (hierarchyComponent) { + for (auto child : hierarchyComponent->GetChildren()) + addBodies(child, globalMatrix); + } + }; + + if (addRigidBodies) + addBodies(rootEntity, mat4(1.0f)); scene->physicsWorld->OptimizeBroadphase(); @@ -160,4 +176,89 @@ namespace Atlas::Editor { } -} \ No newline at end of file + // A sphere with smooth normals and enough vertices to show the displacement of a graph + Ref DataCreator::CreateSphere(const ResourceHandle& material, int32_t rings, int32_t segments) { + + const float radius = 1.0f; + + Mesh::MeshData data; + data.indices.SetType(Mesh::ComponentFormat::UnsignedInt); + data.vertices.SetType(Mesh::ComponentFormat::Float); + data.normals.SetType(Mesh::ComponentFormat::PackedNormal); + data.texCoords.SetType(Mesh::ComponentFormat::HalfFloat); + data.tangents.SetType(Mesh::ComponentFormat::PackedNormal); + + auto vertexCount = (rings + 1) * (segments + 1); + auto indexCount = rings * segments * 6; + data.SetVertexCount(vertexCount); + data.SetIndexCount(indexCount); + data.vertices.SetElementCount(vertexCount); + data.normals.SetElementCount(vertexCount); + data.texCoords.SetElementCount(vertexCount); + data.tangents.SetElementCount(vertexCount); + data.indices.SetElementCount(indexCount); + + for (int32_t ring = 0; ring <= rings; ring++) { + for (int32_t segment = 0; segment <= segments; segment++) { + auto idx = ring * (segments + 1) + segment; + auto v = float(ring) / float(rings); + auto u = float(segment) / float(segments); + auto theta = v * glm::pi(); + auto phi = u * 2.0f * glm::pi(); + auto normal = vec3(glm::sin(theta) * glm::cos(phi), glm::cos(theta), glm::sin(theta) * glm::sin(phi)); + + data.vertices[idx] = normal * radius; + data.normals[idx] = vec4(normal, 0.0f); + data.texCoords[idx] = vec2(u * 2.0f, v); + data.tangents[idx] = vec4(-glm::sin(phi), 0.0f, glm::cos(phi), 1.0f); + } + } + + int32_t index = 0; + for (int32_t ring = 0; ring < rings; ring++) { + for (int32_t segment = 0; segment < segments; segment++) { + auto a = uint32_t(ring * (segments + 1) + segment); + auto b = uint32_t((ring + 1) * (segments + 1) + segment); + for (auto vertex : { a, a + 1, b, a + 1, b + 1, b }) + data.indices[index++] = vertex; + } + } + + data.aabb = Volume::AABB(vec3(-radius), vec3(radius)); + data.materials = { material }; + data.subData = { Mesh::MeshSubData { + .name = "Sphere", + .indicesOffset = 0, + .indicesCount = uint32_t(indexCount), + .material = material, + .materialIdx = 0, + .aabb = data.aabb, + .uvScale = radius * glm::pi() + } }; + + auto mesh = CreateRef(data); + // Only for looking at the material, the ray tracing data would take a moment to build + mesh->rayTrace = false; + mesh->name = "Detailed sphere"; + + return mesh; + + } + + void DataCreator::AddDirectionalLight(Ref& scene, HierarchyComponent& parent, vec3 direction) { + + auto directionalLightEntity = scene->CreateEntity(); + directionalLightEntity.AddComponent("Directional light"); + auto& directionalLight = directionalLightEntity.AddComponent(LightType::DirectionalLight); + + directionalLight.properties.directional.direction = direction; + directionalLight.color = vec3(255, 236, 209) / 255.0f; + directionalLight.intensity = 10.0f; + directionalLight.AddDirectionalShadow(200.0f, 3.0f, 2048, 0.05f, 3, 0.9f); + directionalLight.isMain = true; + + parent.AddChild(directionalLightEntity); + + } + +} diff --git a/src/editor/DataCreator.h b/src/editor/DataCreator.h index 4708860bb..69626a536 100644 --- a/src/editor/DataCreator.h +++ b/src/editor/DataCreator.h @@ -1,6 +1,7 @@ #pragma once #include "scene/Scene.h" +#include "loader/ModelImporter.h" namespace Atlas::Editor { @@ -9,8 +10,17 @@ namespace Atlas::Editor { public: static Ref CreateScene(const std::string& name, vec3 min, vec3 max, int32_t depth); + // Lights a single asset in an editor, e.g. a mesh or material. The probes only cover the bounds of the asset + static Ref CreatePreviewScene(const std::string& name, const Volume::AABB& bounds); + static Ref CreateSceneFromMesh(const std::string& filename,vec3 min, vec3 max, int32_t depth, - bool invertUVs, bool addRigidBodies, bool makeMeshesStatic); + bool invertUVs, bool addRigidBodies, bool makeMeshesStatic, Loader::ImportTextureFormat textureFormat); + + // A unit sphere with smooth normals, e.g. to look at a material. Enough rings and segments show the displacement of a graph + static Ref CreateSphere(const ResourceHandle& material, int32_t rings, int32_t segments); + + private: + static void AddDirectionalLight(Ref& scene, Scene::Components::HierarchyComponent& parent, vec3 direction); }; diff --git a/src/editor/EditorBridge.cpp b/src/editor/EditorBridge.cpp new file mode 100644 index 000000000..9dab72e7f --- /dev/null +++ b/src/editor/EditorBridge.cpp @@ -0,0 +1,260 @@ +#include "EditorBridge.h" +#include "Notifications.h" + +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace Atlas::Editor { + + EditorBridge::EditorBridge(const Ref& project, int32_t port, const std::function()>& getSceneWindow) + : getSceneWindow(getSceneWindow), directory(std::filesystem::path(project->GetDirectory()) / ".atlas" / "bridge"), + server("atlas-editor", Bridge::McpTools::GetInstructions("editor with the project " + project->name + + " open, changes show up while the user watches")) { + + // Jobs run in AtlasBridge next to the editor, paths of agents are relative to the project + auto executable = Bridge::GetExecutablePath(); + auto bridgeExecutable = executable.parent_path() / ("AtlasBridge" + executable.extension().string()); + Bridge::McpTools::AddJobTools(server, bridgeExecutable, project->GetDirectory()); + + server.AddTool({ .name = "lua", + .description = "Runs Lua in the scene open in the editor, the change is visible right away and one undo step (Ctrl+Z) " + "there. The scene isn't saved, the user saves it. While the scene plays, changes have no undo step and are " + "discarded when playing stops. Without an open scene (e.g. while it loads) there are only Atlas, Glm, Project " + "and Editor, the value of a return is the result. Functions which can't do what they are asked raise an " + "error, the call fails with it. Project is the open project (Project.settings, Project:ApplySettings(), " + "Project:Save()), changes of it are applied and one undo step in the project settings, the user saves them. " + "Editor has the windows: Editor.Windows(), Editor.Open(path), Editor.Focus(nameOrPath), Editor.GetText(path) " + "and Editor.SetText(path, text) of code windows (one undo step there, saved by the user). An open material " + "graph editor shows graph changes of the script with an undo step. " + Bridge::McpTools::GetLuaHelp() + "\nUse Bridge functions for bulk changes, " + "a loop over a million entities with SetPosition stays one cheap undo step.", + .inputSchema = Bridge::McpTools::ObjectSchema({ + { "code", { { "type", "string" }, { "description", "Lua code" } } }, + { "name", { { "type", "string" }, { "description", "Name of the undo step" } } } }, { "code" }), + .call = [this](const json& arguments, const Bridge::McpServer::Reply& reply) { + auto result = RunLua(arguments, this->getSceneWindow()); + reply(Bridge::McpServer::TextContent(result.dump(2), result.value("exitCode", 2) != 0)); + } }); + + server.AddTool({ .name = "screenshot", .description = "The editor window as the user sees it, as an image", + .call = [this](const json&, const Bridge::McpServer::Reply& reply) { + if (pendingShot) { + reply(Bridge::McpServer::TextContent("A screenshot is already being taken", true)); + return; + } + std::filesystem::create_directories(directory); + shotPath = (directory / ("screenshot-" + std::to_string(shotCount++ % 8) + ".png")).string(); + pendingShot = reply; + copyRequested = true; + } }); + + server.AddTool({ .name = "undo", + .description = "Undoes (or with redo: true redoes) the last step of the scene open in the editor, e.g. a lua call", + .inputSchema = Bridge::McpTools::ObjectSchema({ { "redo", { { "type", "boolean" } } } }), + .call = [this](const json& arguments, const Bridge::McpServer::Reply& reply) { + auto sceneWindow = this->getSceneWindow(); + if (!sceneWindow || sceneWindow->isPlaying) { + reply(Bridge::McpServer::TextContent("Undo needs an open scene which doesn't play", true)); + return; + } + auto redo = arguments.value("redo", false); + auto& history = sceneWindow->history.history; + auto step = redo ? history.GetRedoName() : history.GetUndoName(); + if (!(redo ? history.CanRedo() : history.CanUndo())) { + reply(Bridge::McpServer::TextContent(std::string("Nothing to ") + (redo ? "redo" : "undo"), true)); + return; + } + if (redo) + sceneWindow->Redo(); + else + sceneWindow->Undo(); + reply(Bridge::McpServer::TextContent((redo ? "Redone: " : "Undone: ") + step)); + } }); + + server.AddTool({ .name = "status", .description = "Which program serves the tools (the editor), its project, open scene and selected entities", + .call = [this, project](const json&, const Bridge::McpServer::Reply& reply) { + auto sceneWindow = this->getSceneWindow(); + auto hasScene = sceneWindow && sceneWindow->scene.IsValid(); + // The selected entities as "Name (#id)", Bridge.Find takes the #id + json selected = json::array(); + if (hasScene && sceneWindow->scene.IsLoaded()) { + for (auto ecsEntity : sceneWindow->sceneHierarchyPanel.selectedEntities) + selected.push_back(Bridge::GetEntityLabel(Scene::Entity(ecsEntity, &sceneWindow->scene->entityManager))); + } + json status = { { "program", "editor" }, { "project", project->name }, { "projectFile", project->path }, + { "scene", hasScene ? UI::SceneWindow::GetScenePath(sceneWindow->scene) : "" }, + { "loaded", hasScene && sceneWindow->scene.IsLoaded() }, { "playing", sceneWindow && sceneWindow->isPlaying }, + { "selected", selected } }; + reply(Bridge::McpServer::TextContent(status.dump(2))); + } }); + + std::string error; + if (server.Start(port, error)) + Log::Message("MCP server of the editor on http://127.0.0.1:" + std::to_string(port) + "/mcp"); + else + Notifications::Push({ .message = "No MCP server for agents: " + error, .type = NotificationType::Warning }); + + } + + EditorBridge::~EditorBridge() { + + // Closing the server waits for the requests, a screenshot of a later frame won't come anymore + if (pendingShot) + (*pendingShot)(Bridge::McpServer::TextContent("The editor closed before the screenshot", true)); + + } + + void EditorBridge::Update() { + + if (copied) { + copied = false; + auto reply = std::move(*pendingShot); + pendingShot.reset(); + reply(windowShot.Save() ? Bridge::McpServer::ImageContent(shotPath) : + Bridge::McpServer::TextContent("The window wasn't copied", true)); + } + + server.Update(); + + } + + void EditorBridge::AfterRender() { + + if (!copyRequested) + return; + copyRequested = false; + + if (windowShot.Copy(shotPath)) { + copied = true; + return; + } + (*pendingShot)(Bridge::McpServer::TextContent("The window can't be copied, the swap chain isn't readable", true)); + pendingShot.reset(); + + } + + json EditorBridge::RunLua(const json& arguments, const Ref& sceneWindow) { + + if (!sceneWindow || !sceneWindow->scene.IsLoaded()) + return RunLuaWithoutScene(arguments); + + auto scene = sceneWindow->scene.Get(); + auto code = arguments.value("code", ""); + auto name = arguments.value("name", "Bridge script"); + + // Changes while playing are discarded when playing stops, they don't need an undo step + auto& history = sceneWindow->history; + auto journal = !sceneWindow->isPlaying; + + Bridge::EditHooks hooks; + hooks.selection = [sceneWindow]() { + std::vector entities; + for (auto ecsEntity : sceneWindow->sceneHierarchyPanel.selectedEntities) + entities.emplace_back(ecsEntity, &sceneWindow->scene->entityManager); + return entities; + }; + hooks.camera = [sceneWindow]() -> json { + if (!sceneWindow->cameraEntity.IsValid()) + return nullptr; + const auto& camera = sceneWindow->cameraEntity.GetComponent(); + auto location = camera.GetLocation(); + return { { "location", { location.x, location.y, location.z } }, + { "direction", { camera.direction.x, camera.direction.y, camera.direction.z } } }; + }; + hooks.extendEnvironment = [this](sol::environment& environment) { + if (!addEditorFunctions) + return; + Scripting::Binder editor(sol::state_view(environment.lua_state()).create_table(), "Editor"); + addEditorFunctions(editor); + environment["Editor"] = editor.GetTable(); + }; + if (journal) { + hooks.beforeChange = [&history](Scene::Entity entity) { history.BeforeEntityChange(entity); }; + hooks.beforeTransformChange = [&history](Scene::Entity entity) { history.BeforeTransformChange(entity); }; + hooks.created = [&history](Scene::Entity entity) { history.EntityCreated(entity); }; + hooks.beforeDestroy = [&history](Scene::Entity entity) { history.BeforeEntityDestroy(entity); }; + // Edit operations don't report what they touch, the whole scene is saved before the first of them + hooks.beforeOperation = [&history]() { history.BeforeSceneChange(); }; + history.BeginScriptChange(scene); + } + + // The project is compared as it is saved, a change becomes an undo step of the project settings + auto projectBefore = Project::active ? std::optional(*Project::active) : std::nullopt; + + json result; + try { + // Materials the operations change stay loaded with the change, they are saved with the scene + Bridge::EditState state; + Bridge::LuaEdit edit(scene, state, hooks); + result = { { "status", "passed" }, { "exitCode", 0 }, { "results", edit.Run(code, name) } }; + } + catch (const std::exception& exception) { + result = { { "status", "error" }, { "exitCode", 2 }, { "reason", exception.what() } }; + } + + ReportProjectChange(projectBefore, result); + + if (journal) { + auto changed = history.EndScriptChange(name); + result["undoStep"] = changed > 0 ? json(name) : json(nullptr); + result["changedEntities"] = changed; + // The user decides when the scene is saved, closing the editor asks about the change + if (changed > 0) + sceneWindow->hasUnsavedChanges = true; + } + + return result; + + } + + json EditorBridge::RunLuaWithoutScene(const json& arguments) { + + auto code = arguments.value("code", ""); + auto name = arguments.value("name", "Bridge script"); + auto projectBefore = Project::active ? std::optional(*Project::active) : std::nullopt; + + Scripting::LuaHost host; + auto& lua = host.GetState(); + if (addEditorFunctions) { + Scripting::Binder editor(lua.create_table(), "Editor"); + addEditorFunctions(editor); + lua["Editor"] = editor.GetTable(); + } + + json result; + auto scriptResult = lua.safe_script(code, sol::script_pass_on_error, "=" + name); + if (scriptResult.valid()) { + json results = json::object(); + if (scriptResult.return_count() > 0) + results["value"] = Bridge::LuaJob::ToJson(scriptResult.get()); + result = { { "status", "passed" }, { "exitCode", 0 }, { "results", results } }; + } + else { + sol::error error = scriptResult; + result = { { "status", "error" }, { "exitCode", 2 }, { "reason", "Lua " + name + ": " + error.what() } }; + } + result["scene"] = nullptr; + + ReportProjectChange(projectBefore, result); + return result; + + } + + void EditorBridge::ReportProjectChange(const std::optional& before, json& result) { + + if (!before || json(*before) == json(*Project::active)) + return; + + result["projectChanged"] = true; + if (onProjectChange) + onProjectChange(*before); + + } + +} diff --git a/src/editor/EditorBridge.h b/src/editor/EditorBridge.h new file mode 100644 index 000000000..e2a90ceee --- /dev/null +++ b/src/editor/EditorBridge.h @@ -0,0 +1,58 @@ +#pragma once + +#include "ui/windows/SceneWindow.h" + +#include +#include +#include + +#include + +namespace Atlas::Editor { + + // The MCP server of the editor (Bridge::McpServer): Lua in the scene of the active scene window, one undo step per + // call, screenshots of the editor window, undo and the job tools of the bridge. Agents connect to + // http://127.0.0.1:/mcp, the first program which starts gets the port + class EditorBridge { + + public: + EditorBridge(const Ref& project, int32_t port, const std::function()>& getSceneWindow); + + ~EditorBridge(); + + // Called after Lua of the lua tool changed the project, with the project before + std::function onProjectChange; + + // Fills the table Editor of the lua tool + std::function addEditorFunctions; + + // Runs the tool calls which arrived since the last frame, on the main thread + void Update(); + + // After the interface is rendered, copies the window for a screenshot + void AfterRender(); + + private: + json RunLua(const json& arguments, const Ref& sceneWindow); + + // Without an open scene, e.g. while the start scene loads: the engine bindings, Project and Editor + json RunLuaWithoutScene(const json& arguments); + + void ReportProjectChange(const std::optional& before, json& result); + + std::function()> getSceneWindow; + std::filesystem::path directory; + + Bridge::McpServer server; + Bridge::WindowShot windowShot; + + // Screenshots finish a frame later, once the window was copied + std::optional pendingShot; + std::string shotPath; + int32_t shotCount = 0; + bool copyRequested = false; + bool copied = false; + + }; + +} diff --git a/src/editor/FileImporter.cpp b/src/editor/FileImporter.cpp index c67a759dd..9d04df19d 100644 --- a/src/editor/FileImporter.cpp +++ b/src/editor/FileImporter.cpp @@ -3,6 +3,7 @@ #include #include "common/Path.h" +#include "Notifications.h" namespace Atlas::Editor { @@ -20,6 +21,8 @@ namespace Atlas::Editor { if (!Content::contentTypeMapping.contains(fileType)) { Log::Warning("Incompatible file type " + fileType); + Notifications::Push({ .message = "Can't import " + Common::Path::GetFileName(filename) + ", ." + fileType + + " files aren't supported", .type = NotificationType::Warning }); return; } @@ -35,6 +38,7 @@ namespace Atlas::Editor { case ContentType::Script: ImportFile(filename); break; case ContentType::Font: ImportFile(filename); break; case ContentType::Terrain: ImportFile(filename); break; + case ContentType::Animation: ImportFile(filename); break; default: break; } diff --git a/src/editor/FileImporter.h b/src/editor/FileImporter.h index 6774630ff..334b33cc2 100644 --- a/src/editor/FileImporter.h +++ b/src/editor/FileImporter.h @@ -8,6 +8,7 @@ #include "resource/ResourceManager.h" #include "mesh/Mesh.h" +#include "animation/Animation.h" #include "scene/Scene.h" #include "audio/AudioData.h" #include "scripting/Script.h" @@ -15,8 +16,10 @@ #include "loader/ModelImporter.h" #include "loader/MaterialLoader.h" +#include "loader/MaterialGraphLoader.h" #include "loader/TerrainLoader.h" #include "loader/MeshLoader.h" +#include "loader/AnimationLoader.h" #include "Content.h" #include "Serializer.h" @@ -61,7 +64,11 @@ namespace Atlas::Editor { auto directoryPath = Common::Path::GetDirectory(filename) + "/meshes/"; resourcePath = directoryPath + resourcePath; auto loader = [filename](const std::string& resourcePath) -> auto { - return Loader::ModelImporter::ImportMesh(filename, true); + auto mesh = Loader::ModelImporter::ImportMesh(filename, true, 4096, Loader::ImportTextureFormat::KTX2); + // Animations are written next to the meshes and can then be assigned to animation components + if (mesh->data.IsSkinned()) + Loader::ModelImporter::ImportAnimations(filename, true); + return mesh; }; handle = ResourceManager::GetOrLoadResourceWithLoaderAsync(resourcePath, ResourceOrigin::User, std::function(loader)); @@ -76,6 +83,10 @@ namespace Atlas::Editor { handle = ResourceManager::GetOrLoadResourceWithLoader(filename, ResourceOrigin::User, Loader::MaterialLoader::LoadMaterial, false); } + else if constexpr (std::is_same_v) { + handle = ResourceManager::GetOrLoadResourceWithLoader(filename, + ResourceOrigin::User, Loader::MaterialGraphLoader::LoadGraph); + } else if constexpr (std::is_same_v) { handle = ResourceManager::GetOrLoadResourceWithLoaderAsync(filename, ResourceOrigin::User, Serializer::DeserializeScene, true); @@ -89,8 +100,7 @@ namespace Atlas::Editor { ResourceOrigin::User, 32.0f, 8, 127); } else if constexpr (std::is_same_v) { - // No support internally for async loading, load syncho. for now - handle = ResourceManager::GetOrLoadResource(filename, + handle = ResourceManager::GetOrLoadResourceAsync(filename, ResourceOrigin::User, true, Texture::Wrapping::Repeat, Texture::Filtering::Anisotropic, 0); } else if constexpr (std::is_same_v) { @@ -103,6 +113,10 @@ namespace Atlas::Editor { handle = ResourceManager::GetOrLoadResourceWithLoaderAsync(filename, ResourceOrigin::User, Loader::TerrainLoader::LoadTerrain, true); } + else if constexpr (std::is_same_v) { + handle = ResourceManager::GetOrLoadResourceWithLoaderAsync(filename, + ResourceOrigin::User, Loader::AnimationLoader::LoadAnimation, true); + } return handle; @@ -128,6 +142,9 @@ namespace Atlas::Editor { else if constexpr (std::is_same_v) { return type == ContentType::Material; } + else if constexpr (std::is_same_v) { + return type == ContentType::MaterialGraph; + } else if constexpr (std::is_same_v) { return type == ContentType::Scene; } @@ -149,6 +166,9 @@ namespace Atlas::Editor { else if constexpr (std::is_same_v) { return type == ContentType::Terrain; } + else if constexpr (std::is_same_v) { + return type == ContentType::Animation; + } else { return false; } diff --git a/src/editor/Icons.cpp b/src/editor/Icons.cpp index bcc2a2df2..6fefb6ead 100644 --- a/src/editor/Icons.cpp +++ b/src/editor/Icons.cpp @@ -9,6 +9,43 @@ namespace Atlas::Editor { } + Texture::Texture2D& Icons::GetTintable(IconType type) { + + // The dark mode icons are white already + if (Singletons::config->darkMode) + return Get(type); + + if (tintableIcons.empty()) { + tintableIcons = std::map{ + { IconType::Audio, Texture::Texture2D("editor/icons/audio.png") }, + { IconType::Document, Texture::Texture2D("editor/icons/document.png") }, + { IconType::Folder, Texture::Texture2D("editor/icons/folder.png") }, + { IconType::Image, Texture::Texture2D("editor/icons/image.png") }, + { IconType::Mesh, Texture::Texture2D("editor/icons/mesh.png") }, + { IconType::Scene, Texture::Texture2D("editor/icons/scene.png") }, + { IconType::Terrain, Texture::Texture2D("editor/icons/terrain.png") }, + { IconType::Font, Texture::Texture2D("editor/icons/font.png") }, + { IconType::Prefab, Texture::Texture2D("editor/icons/prefab.png") }, + { IconType::Material, Texture::Texture2D("editor/icons/material.png") }, + { IconType::MeshSource, Texture::Texture2D("editor/icons/meshSource.png") }, + { IconType::EnvironmentImage, Texture::Texture2D("editor/icons/environment.png") }, + { IconType::MaterialGraph, Texture::Texture2D("editor/icons/materialGraph.png") }, + { IconType::Log, Texture::Texture2D("editor/icons/log.png") }, + { IconType::Error, Texture::Texture2D("editor/icons/error.png") }, + { IconType::Warning, Texture::Texture2D("editor/icons/warning.png") }, + { IconType::Play, Texture::Texture2D("editor/icons/play.png") }, + { IconType::Notifications, Texture::Texture2D("editor/icons/notifications.png") }, + { IconType::Profiler, Texture::Texture2D("editor/icons/profiler.png") }, + }; + } + + if (!tintableIcons.contains(type)) + return tintableIcons[IconType::Document]; + + return tintableIcons[type]; + + } + Texture::Texture2D &Icons::Get(IconType type) { auto darkMode = Singletons::config->darkMode; @@ -37,6 +74,7 @@ namespace Atlas::Editor { { IconType::Mesh, Texture::Texture2D("editor/icons/mesh.png") }, { IconType::Play, Texture::Texture2D("editor/icons/play.png") }, { IconType::Stop, Texture::Texture2D("editor/icons/stop.png") }, + { IconType::Pause, Texture::Texture2D("editor/icons/pause.png") }, { IconType::Scene, Texture::Texture2D("editor/icons/scene.png") }, { IconType::Terrain, Texture::Texture2D("editor/icons/terrain.png") }, { IconType::Settings, Texture::Texture2D("editor/icons/settings.png") }, @@ -58,6 +96,35 @@ namespace Atlas::Editor { { IconType::EnvironmentImage, Texture::Texture2D("editor/icons/environment.png") }, { IconType::Trash, Texture::Texture2D("editor/icons/delete.png") }, { IconType::Filter, Texture::Texture2D("editor/icons/filter.png") }, + { IconType::OpenInNew, Texture::Texture2D("editor/icons/openInNew.png") }, + { IconType::Reset, Texture::Texture2D("editor/icons/reset.png") }, + { IconType::MaterialGraph, Texture::Texture2D("editor/icons/materialGraph.png") }, + { IconType::Ocean, Texture::Texture2D("editor/icons/ocean.png") }, + { IconType::Navigation, Texture::Texture2D("editor/icons/navigation.png") }, + { IconType::IrradianceVolume, Texture::Texture2D("editor/icons/irradianceVolume.png") }, + { IconType::GlobalIllumination, Texture::Texture2D("editor/icons/globalIllumination.png") }, + { IconType::Reflection, Texture::Texture2D("editor/icons/reflection.png") }, + { IconType::Shadow, Texture::Texture2D("editor/icons/shadow.png") }, + { IconType::Clouds, Texture::Texture2D("editor/icons/clouds.png") }, + { IconType::Fog, Texture::Texture2D("editor/icons/fog.png") }, + { IconType::Sky, Texture::Texture2D("editor/icons/sky.png") }, + { IconType::Wind, Texture::Texture2D("editor/icons/wind.png") }, + { IconType::PostProcessing, Texture::Texture2D("editor/icons/postProcessing.png") }, + { IconType::ViewList, Texture::Texture2D("editor/icons/viewList.png") }, + { IconType::ViewGrid, Texture::Texture2D("editor/icons/viewGrid.png") }, + { IconType::Log, Texture::Texture2D("editor/icons/log.png") }, + { IconType::Error, Texture::Texture2D("editor/icons/error.png") }, + { IconType::Warning, Texture::Texture2D("editor/icons/warning.png") }, + { IconType::Notifications, Texture::Texture2D("editor/icons/notifications.png") }, + { IconType::ScaleInverse, Texture::Texture2D("editor/icons/scaleInverse.png") }, + { IconType::Pin, Texture::Texture2D("editor/icons/pin.png") }, + { IconType::PinFilled, Texture::Texture2D("editor/icons/pinFilled.png") }, + { IconType::Profiler, Texture::Texture2D("editor/icons/profiler.png") }, + { IconType::Save, Texture::Texture2D("editor/icons/save.png") }, + { IconType::Undo, Texture::Texture2D("editor/icons/undo.png") }, + { IconType::Redo, Texture::Texture2D("editor/icons/redo.png") }, + { IconType::Search, Texture::Texture2D("editor/icons/search.png") }, + { IconType::Close, Texture::Texture2D("editor/icons/cancel.png") }, }; } else { @@ -70,6 +137,7 @@ namespace Atlas::Editor { { IconType::Mesh, Texture::Texture2D("editor/icons/mesh_light.png") }, { IconType::Play, Texture::Texture2D("editor/icons/play_light.png") }, { IconType::Stop, Texture::Texture2D("editor/icons/stop_light.png") }, + { IconType::Pause, Texture::Texture2D("editor/icons/pause_light.png") }, { IconType::Scene, Texture::Texture2D("editor/icons/scene_light.png") }, { IconType::Terrain, Texture::Texture2D("editor/icons/terrain_light.png") }, { IconType::Settings, Texture::Texture2D("editor/icons/settings_light.png") }, @@ -91,6 +159,35 @@ namespace Atlas::Editor { { IconType::EnvironmentImage, Texture::Texture2D("editor/icons/environment_light.png") }, { IconType::Trash, Texture::Texture2D("editor/icons/delete_light.png") }, { IconType::Filter, Texture::Texture2D("editor/icons/filter_light.png") }, + { IconType::OpenInNew, Texture::Texture2D("editor/icons/openInNew_light.png") }, + { IconType::Reset, Texture::Texture2D("editor/icons/reset_light.png") }, + { IconType::MaterialGraph, Texture::Texture2D("editor/icons/materialGraph_light.png") }, + { IconType::Ocean, Texture::Texture2D("editor/icons/ocean_light.png") }, + { IconType::Navigation, Texture::Texture2D("editor/icons/navigation_light.png") }, + { IconType::IrradianceVolume, Texture::Texture2D("editor/icons/irradianceVolume_light.png") }, + { IconType::GlobalIllumination, Texture::Texture2D("editor/icons/globalIllumination_light.png") }, + { IconType::Reflection, Texture::Texture2D("editor/icons/reflection_light.png") }, + { IconType::Shadow, Texture::Texture2D("editor/icons/shadow_light.png") }, + { IconType::Clouds, Texture::Texture2D("editor/icons/clouds_light.png") }, + { IconType::Fog, Texture::Texture2D("editor/icons/fog_light.png") }, + { IconType::Sky, Texture::Texture2D("editor/icons/sky_light.png") }, + { IconType::Wind, Texture::Texture2D("editor/icons/wind_light.png") }, + { IconType::PostProcessing, Texture::Texture2D("editor/icons/postProcessing_light.png") }, + { IconType::ViewList, Texture::Texture2D("editor/icons/viewList_light.png") }, + { IconType::ViewGrid, Texture::Texture2D("editor/icons/viewGrid_light.png") }, + { IconType::Log, Texture::Texture2D("editor/icons/log_light.png") }, + { IconType::Error, Texture::Texture2D("editor/icons/error_light.png") }, + { IconType::Warning, Texture::Texture2D("editor/icons/warning_light.png") }, + { IconType::Notifications, Texture::Texture2D("editor/icons/notifications_light.png") }, + { IconType::ScaleInverse, Texture::Texture2D("editor/icons/scaleInverse_light.png") }, + { IconType::Pin, Texture::Texture2D("editor/icons/pin_light.png") }, + { IconType::PinFilled, Texture::Texture2D("editor/icons/pinFilled_light.png") }, + { IconType::Profiler, Texture::Texture2D("editor/icons/profiler_light.png") }, + { IconType::Save, Texture::Texture2D("editor/icons/save_light.png") }, + { IconType::Undo, Texture::Texture2D("editor/icons/undo_light.png") }, + { IconType::Redo, Texture::Texture2D("editor/icons/redo_light.png") }, + { IconType::Search, Texture::Texture2D("editor/icons/search_light.png") }, + { IconType::Close, Texture::Texture2D("editor/icons/cancel_light.png") }, }; } diff --git a/src/editor/Icons.h b/src/editor/Icons.h index d7c499c0a..0ae8b3858 100644 --- a/src/editor/Icons.h +++ b/src/editor/Icons.h @@ -15,6 +15,7 @@ namespace Atlas::Editor { Mesh, Play, Stop, + Pause, Scene, Terrain, Font, @@ -35,7 +36,36 @@ namespace Atlas::Editor { MeshSource, EnvironmentImage, Trash, - Filter + Filter, + OpenInNew, + Reset, + MaterialGraph, + Ocean, + Navigation, + IrradianceVolume, + GlobalIllumination, + Reflection, + Shadow, + Clouds, + Fog, + Sky, + Wind, + PostProcessing, + ViewList, + ViewGrid, + Log, + Error, + Warning, + Notifications, + ScaleInverse, + Pin, + PinFilled, + Profiler, + Save, + Undo, + Redo, + Search, + Close }; class Icons { @@ -44,10 +74,14 @@ namespace Atlas::Editor { Texture::Texture2D& Get(IconType type); + // White in both modes, such that it can be tinted + Texture::Texture2D& GetTintable(IconType type); + private: void LoadIcons(); std::map icons; + std::map tintableIcons; bool darkModeIcons = true; diff --git a/src/editor/Notifications.cpp b/src/editor/Notifications.cpp index 04dda01c0..2b4a73d9a 100644 --- a/src/editor/Notifications.cpp +++ b/src/editor/Notifications.cpp @@ -7,6 +7,8 @@ #include "Log.h" #include + +#include #include namespace Atlas::Editor { @@ -19,6 +21,8 @@ namespace Atlas::Editor { } std::vector Notifications::notifications; + std::vector Notifications::history; + int32_t Notifications::unreadCount = 0; std::mutex Notifications::mutex; void Notifications::Push(const Notification& notification) { @@ -27,6 +31,99 @@ namespace Atlas::Editor { notifications.emplace_back(notification); + // Only the latest ones are kept, older ones are rarely of interest + history.emplace_back(notification); + if (history.size() > 100) + history.erase(history.begin()); + unreadCount++; + + } + + void Notifications::DisplayHistory() { + + const float width = 380.0f; + const float stripeWidth = 3.0f; + + std::scoped_lock lock(mutex); + + ImGui::TextUnformatted("Notifications"); + if (!history.empty()) { + ImGui::SameLine(width - ImGui::CalcTextSize("Clear all").x - 2.0f * ImGui::GetStyle().FramePadding.x); + if (ImGui::SmallButton("Clear all")) + history.clear(); + } + ImGui::Separator(); + + if (history.empty()) { + ImGui::Dummy(ImVec2(width, 0.0f)); + ImGui::TextDisabled("No notifications yet"); + return; + } + + // The list grows with the notifications until it scrolls + ImGui::SetNextWindowSizeConstraints(ImVec2(width, 0.0f), ImVec2(width, 420.0f)); + ImGui::BeginChild("Notification history", ImVec2(width, 0.0f), ImGuiChildFlags_AutoResizeY); + + auto time = Clock::Get(); + for (auto iter = history.rbegin(); iter != history.rend(); iter++) { + const auto& notification = *iter; + + auto isError = notification.type == NotificationType::Error; + auto isWarning = notification.type == NotificationType::Warning; + auto color = GetColor(notification); + + ImGui::PushID(¬ification); + auto start = ImGui::GetCursorScreenPos(); + ImGui::Indent(stripeWidth + 8.0f); + + ImGui::PushTextWrapPos(ImGui::GetCursorPosX() + width - stripeWidth - 16.0f); + ImGui::TextUnformatted(notification.message.c_str()); + ImGui::PopTextWrapPos(); + + // Older notifications show their age, the newest are just new + auto age = int32_t(time - notification.creationTime); + auto ageText = age < 10 ? std::string("Just now") : age < 60 ? std::to_string(age) + " s ago" : + age < 3600 ? std::to_string(age / 60) + " min ago" : std::to_string(age / 3600) + " h ago"; + ImGui::TextDisabled("%s%s", isError ? "Error \xC2\xB7 " : isWarning ? "Warning \xC2\xB7 " : "", ageText.c_str()); + + ImGui::Unindent(stripeWidth + 8.0f); + auto end = ImGui::GetItemRectMax(); + ImGui::GetWindowDrawList()->AddRectFilled(start, ImVec2(start.x + stripeWidth, end.y), + ImGui::GetColorU32(color), stripeWidth * 0.5f); + ImGui::PopID(); + + if (iter + 1 != history.rend()) + ImGui::Dummy(ImVec2(0.0f, 2.0f)); + } + + ImGui::EndChild(); + + } + + int32_t Notifications::GetUnreadCount() { + + std::scoped_lock lock(mutex); + + return std::min(unreadCount, int32_t(history.size())); + + } + + bool Notifications::HasUnreadError() { + + std::scoped_lock lock(mutex); + + auto count = std::min(unreadCount, int32_t(history.size())); + return std::any_of(history.end() - count, history.end(), + [](const Notification& notification) { return notification.type == NotificationType::Error; }); + + } + + void Notifications::MarkAsRead() { + + std::scoped_lock lock(mutex); + + unreadCount = 0; + } void Notifications::Display() { @@ -68,10 +165,7 @@ namespace Atlas::Editor { HashCombine(hash, notification.message); HashCombine(hash, notification.creationTime); - // White is the default color, which means "informational": use the accent then - bool isDefaultColor = notification.color == vec3(1.0f); - auto stripeColor = isDefaultColor ? Theme::Accent(alpha) : - ImVec4(notification.color.r, notification.color.g, notification.color.b, alpha); + auto stripeColor = GetColor(notification, alpha); ImGui::SetNextWindowBgAlpha(1.0f); ImGui::PushStyleColor(ImGuiCol_WindowBg, Fade(ImGui::GetStyleColorVec4(ImGuiCol_PopupBg), alpha)); @@ -115,4 +209,14 @@ namespace Atlas::Editor { } + ImVec4 Notifications::GetColor(const Notification& notification, float alpha) { + + switch (notification.type) { + case NotificationType::Error: return Theme::Error(alpha); + case NotificationType::Warning: return Theme::Warning(alpha); + default: return Theme::Accent(alpha); + } + + } + } \ No newline at end of file diff --git a/src/editor/Notifications.h b/src/editor/Notifications.h index fd221752f..39dafd09d 100644 --- a/src/editor/Notifications.h +++ b/src/editor/Notifications.h @@ -3,11 +3,19 @@ #include "System.h" #include "Clock.h" +#include + namespace Atlas::Editor { + enum class NotificationType { + Info = 0, + Warning, + Error + }; + struct Notification { std::string message; - vec3 color = vec3(1.0f); + NotificationType type = NotificationType::Info; float creationTime = Clock::Get(); float displayTime = 5.0f; @@ -21,8 +29,21 @@ namespace Atlas::Editor { static void Display(); + // The notifications of this session, newest first, e.g. for a popup + static void DisplayHistory(); + + static int32_t GetUnreadCount(); + + static bool HasUnreadError(); + + static void MarkAsRead(); + private: + static ImVec4 GetColor(const Notification& notification, float alpha = 1.0f); + static std::vector notifications; + static std::vector history; + static int32_t unreadCount; static std::mutex mutex; }; diff --git a/src/editor/RecentProjects.cpp b/src/editor/RecentProjects.cpp new file mode 100644 index 000000000..87f03f597 --- /dev/null +++ b/src/editor/RecentProjects.cpp @@ -0,0 +1,85 @@ +#include "RecentProjects.h" + +#include +#include + +#include + +#include +#include +#include + +namespace Atlas::Editor { + + std::vector RecentProjects::Load() { + + std::vector entries; + + std::ifstream stream(GetFilename(), std::ios::binary); + if (!stream.is_open()) + return entries; + + auto j = json::parse(stream, nullptr, false); + if (j.is_discarded() || !j.contains("projects")) + return entries; + + for (const auto& project : j["projects"]) { + Entry entry; + try_get_json(project, "path", entry.path); + try_get_json(project, "name", entry.name); + try_get_json(project, "lastOpened", entry.lastOpened); + entries.push_back(entry); + } + + return entries; + + } + + void RecentProjects::Add(const Project& project) { + + auto entries = Load(); + std::erase_if(entries, [&](const Entry& entry) { return entry.path == project.path; }); + + auto now = std::chrono::system_clock::now().time_since_epoch(); + entries.insert(entries.begin(), Entry { + .path = project.path, + .name = project.name, + .lastOpened = std::chrono::duration_cast(now).count() + }); + + Save(entries); + + } + + void RecentProjects::Remove(const std::string& path) { + + auto entries = Load(); + std::erase_if(entries, [&](const Entry& entry) { return entry.path == path; }); + Save(entries); + + } + + void RecentProjects::Save(const std::vector& entries) { + + json projects = json::array(); + for (const auto& entry : entries) + projects.push_back({ { "path", entry.path }, { "name", entry.name }, { "lastOpened", entry.lastOpened } }); + + json j = { { "projects", projects } }; + Loader::AssetLoader::WriteJson(GetFilename(), j, Loader::JsonFormat::Indented); + + } + + std::string RecentProjects::GetFilename() { + + static const std::string filename = []() { + auto prefPath = SDL_GetPrefPath("AtlasEngine", "Editor"); + std::string directory = prefPath ? prefPath : ""; + SDL_free(prefPath); + return directory + "projects.json"; + }(); + return filename; + + } + +} diff --git a/src/editor/RecentProjects.h b/src/editor/RecentProjects.h new file mode 100644 index 000000000..2f8167cbe --- /dev/null +++ b/src/editor/RecentProjects.h @@ -0,0 +1,34 @@ +#pragma once + +#include + +#include +#include + +namespace Atlas::Editor { + + // The projects the user opened, newest first. Stored per user and not with a project + class RecentProjects { + + public: + struct Entry { + std::string path; + std::string name; + // Seconds since the epoch + int64_t lastOpened = 0; + }; + + static std::vector Load(); + + static void Add(const Project& project); + + static void Remove(const std::string& path); + + private: + static void Save(const std::vector& entries); + + static std::string GetFilename(); + + }; + +} diff --git a/src/editor/SceneHistory.cpp b/src/editor/SceneHistory.cpp new file mode 100644 index 000000000..18b08cfb2 --- /dev/null +++ b/src/editor/SceneHistory.cpp @@ -0,0 +1,764 @@ +#include "SceneHistory.h" + +#include "scene/SceneSerializer.h" + +#include +#include +#include + +namespace Atlas::Editor { + + using namespace Scene::Components; + + void SceneHistory::Update(const Ref& scene, const std::unordered_set& selectedEntities) { + + this->scene = scene; + + auto interactionFinished = history.IsInteractionFinished(); + + if (interactionFinished && !settingsState.is_null()) { + auto settings = SaveSettings(); + if (!IsSameSettings(settingsState, settings)) { + auto before = settingsState; + history.Push({ + .name = "Edit scene settings", + .undo = [this, before]() { RestoreSettings(before); }, + .redo = [this, settings]() { RestoreSettings(settings); } + }); + settingsState = settings; + } + } + + if (settingsState.is_null()) + settingsState = SaveSettings(); + + // Entities which were deselected in the frame the interaction finished still need to be compared, + // e.g. a text field is confirmed by clicking on another entity + std::vector changes; + if (interactionFinished) { + for (auto& [ecsEntity, state] : entityStates) { + Scene::Entity entity(ecsEntity, &scene->entityManager); + if (!entity.IsValid()) + continue; + + // Even without a change the state is updated, such that rounding errors don't add up + auto current = SaveComponents(entity); + if (!IsSameEntity(state, current)) + changes.push_back({ ecsEntity, state, current }); + state = current; + } + std::erase_if(entityStates, [&](const auto& state) { return !selectedEntities.contains(state.first); }); + } + + for (auto ecsEntity : selectedEntities) { + Scene::Entity entity(ecsEntity, &scene->entityManager); + if (entity.IsValid() && !entityStates.contains(ecsEntity)) + entityStates[ecsEntity] = SaveComponents(entity); + } + + if (changes.empty()) + return; + + auto nameComponent = changes.size() == 1 ? Scene::Entity(changes.front().entity, &scene->entityManager) + .TryGetComponent() : nullptr; + auto name = changes.size() > 1 ? "Edit " + std::to_string(changes.size()) + " entities" : + nameComponent ? "Edit " + nameComponent->name : std::string("Edit entity"); + PushEntityChanges(name, changes); + + } + + void SceneHistory::BeginChange(const Ref& scene, const std::vector& roots) { + + this->scene = scene; + + hierarchiesBefore = SaveHierarchies(roots); + changeStarted = true; + + } + + void SceneHistory::EndChange(const std::string& name, const std::vector& roots) { + + if (!changeStarted) + return; + changeStarted = false; + + auto before = std::move(hierarchiesBefore); + auto after = SaveHierarchies(roots); + if (before.empty() && after.empty()) + return; + + history.Push({ + .name = name, + .undo = [this, before, after]() { + RemoveHierarchies(after); + RestoreHierarchies(before); + }, + .redo = [this, before, after]() { + RemoveHierarchies(before); + RestoreHierarchies(after); + } + }); + + // Edits of the changed entities start from their new state + ResetStates(); + + } + + void SceneHistory::BeginMove(const Ref& scene, const std::vector& entities) { + + this->scene = scene; + + std::vector ecsEntities(entities.begin(), entities.end()); + placementsBefore = SavePlacements(ecsEntities); + + } + + void SceneHistory::EndMove(const std::string& name) { + + auto before = std::move(placementsBefore); + std::vector entities; + for (const auto& placement : before) + entities.push_back(placement.entity); + auto after = SavePlacements(entities); + + auto moved = false; + for (size_t i = 0; i < before.size(); i++) + moved |= before[i].parent != after[i].parent || before[i].index != after[i].index; + if (!moved) + return; + + history.Push({ + .name = name, + .undo = [this, before]() { RestorePlacements(before); }, + .redo = [this, after]() { RestorePlacements(after); } + }); + + ResetStates(); + + } + + void SceneHistory::BeginEdit(const Ref& scene, const std::vector& entities) { + + this->scene = scene; + + editedEntities.clear(); + for (auto entity : entities) + if (entity.IsValid()) + editedEntities.push_back({ entity, SaveComponents(entity) }); + + } + + void SceneHistory::EndEdit(const std::string& name) { + + std::vector changes; + for (auto& change : editedEntities) { + Scene::Entity entity(change.entity, &scene->entityManager); + if (!entity.IsValid()) + continue; + change.after = SaveComponents(entity); + if (!IsSameEntity(change.before, change.after)) + changes.push_back(change); + } + editedEntities.clear(); + + if (changes.empty()) + return; + + PushEntityChanges(name, changes); + ResetStates(); + + } + + bool SceneHistory::Undo(const Ref& scene) { + + this->scene = scene; + + changedEntities.clear(); + auto undone = history.Undo(); + ResetStates(); + return undone; + + } + + bool SceneHistory::Redo(const Ref& scene) { + + this->scene = scene; + + changedEntities.clear(); + auto redone = history.Redo(); + ResetStates(); + return redone; + + } + + void SceneHistory::Clear() { + + history.Clear(); + ResetStates(); + remappedEntities.clear(); + changedEntities.clear(); + + } + + std::vector SceneHistory::GetChangedEntities() { + + std::vector entities; + std::unordered_set added; + for (auto ecsEntity : changedEntities) { + Scene::Entity entity(Resolve(ecsEntity), &scene->entityManager); + if (entity.IsValid() && added.insert(entity).second) + entities.push_back(entity); + } + return entities; + + } + + void SceneHistory::PushEntityChanges(const std::string& name, const std::vector& changes) { + + auto restore = [this, changes](bool undo) { + for (const auto& change : changes) { + Scene::Entity entity(Resolve(change.entity), &scene->entityManager); + if (!entity.IsValid()) + continue; + RestoreComponents(entity, undo ? change.before : change.after); + changedEntities.push_back(entity); + } + }; + + history.Push({ + .name = name, + .undo = [restore]() { restore(true); }, + .redo = [restore]() { restore(false); } + }); + + } + + void SceneHistory::BeginScriptChange(const Ref& scene) { + + this->scene = scene; + scriptChange = ScriptChange { .active = true, .settingsBefore = SaveSettings() }; + + } + + void SceneHistory::BeforeEntityChange(Scene::Entity entity) { + + if (!scriptChange.active || scriptChange.sceneSaved || !entity.IsValid() || scriptChange.entitiesBefore.contains(entity)) + return; + scriptChange.entitiesBefore[entity] = SaveComponents(entity); + + } + + void SceneHistory::BeforeTransformChange(Scene::Entity entity) { + + if (!scriptChange.active || scriptChange.sceneSaved || !entity.IsValid() || !scriptChange.transformEntities.insert(entity).second) + return; + auto transform = entity.TryGetComponent(); + if (!transform) + return; + + scriptChange.transforms.push_back({ entity, transform->matrix }); + + } + + void SceneHistory::EntityCreated(Scene::Entity entity) { + + if (scriptChange.active && !scriptChange.sceneSaved) + scriptChange.created.insert(entity); + + } + + void SceneHistory::BeforeEntityDestroy(Scene::Entity entity) { + + if (!scriptChange.active || scriptChange.sceneSaved || !entity.IsValid()) + return; + + // Entities created by the same command just disappear again + if (scriptChange.created.erase(entity)) + return; + + // Changes the script made before are taken back, the hierarchy is saved as it was before the command + auto restoreBefore = [&](auto&& self, Scene::Entity current) -> void { + if (auto before = scriptChange.entitiesBefore.find(current); before != scriptChange.entitiesBefore.end()) + RestoreComponents(current, before->second); + for (const auto& [transformEntity, matrix] : scriptChange.transforms) + if (transformEntity == current && current.HasComponent()) + current.GetComponent().Set(matrix); + if (auto hierarchy = current.TryGetComponent()) + for (auto child : hierarchy->GetChildren()) + self(self, child); + }; + restoreBefore(restoreBefore, entity); + auto destroyed = SaveHierarchies({ entity }); + scriptChange.destroyed.insert(scriptChange.destroyed.end(), destroyed.begin(), destroyed.end()); + + } + + void SceneHistory::BeforeSceneChange() { + + if (!scriptChange.active || scriptChange.sceneSaved) + return; + + // The root hierarchy as it was before the command: changes recorded so far are undone first, then the saved + // root replaces the one the script leaves behind + auto root = scene->GetRootEntity(); + if (!root.IsValid()) + return; + scriptChange.sceneBefore = SaveHierarchies({ root }); + scriptChange.sceneSaved = true; + + } + + size_t SceneHistory::EndScriptChange(const std::string& name) { + + if (!scriptChange.active) + return 0; + auto change = std::move(scriptChange); + scriptChange = ScriptChange(); + // Selected entities and settings are compared against their state after the script from now on + ResetStates(); + + auto step = CreateRef(); + for (auto& [ecsEntity, before] : change.entitiesBefore) { + Scene::Entity entity(ecsEntity, &scene->entityManager); + if (!entity.IsValid()) + continue; + auto after = SaveComponents(entity); + if (!IsSameEntity(before, after)) + step->entities.push_back({ ecsEntity, std::move(before), std::move(after) }); + } + + // Created entities are restored with their transform, those restored as a whole don't need their matrix + for (const auto& [ecsEntity, before] : change.transforms) { + Scene::Entity entity(ecsEntity, &scene->entityManager); + auto transform = entity.IsValid() ? entity.TryGetComponent() : nullptr; + if (!transform || transform->matrix == before || change.entitiesBefore.contains(ecsEntity) || + change.created.contains(ecsEntity)) + continue; + step->transformEntities.push_back(ecsEntity); + step->transformsBefore.push_back(before); + step->transformsAfter.push_back(transform->matrix); + } + + std::vector createdEntities; + createdEntities.reserve(change.created.size()); + for (auto ecsEntity : change.created) + createdEntities.emplace_back(ecsEntity, &scene->entityManager); + step->created = SaveHierarchies(createdEntities); + step->destroyed = std::move(change.destroyed); + + if (change.sceneSaved) { + step->sceneBefore = std::move(change.sceneBefore); + step->sceneAfter = SaveHierarchies({ scene->GetRootEntity() }); + } + + auto settingsAfter = SaveSettings(); + if (!IsSameSettings(change.settingsBefore, settingsAfter)) { + step->settingsBefore = std::move(change.settingsBefore); + step->settingsAfter = std::move(settingsAfter); + } + + auto count = step->entities.size() + step->transformEntities.size() + step->created.size() + step->destroyed.size() + + (change.sceneSaved ? size_t(1) : size_t(0)) + (step->settingsAfter.is_null() ? size_t(0) : size_t(1)); + if (count == 0) + return 0; + + std::shared_ptr data = step; + history.Push({ + .name = name, + .undo = [this, data]() { ApplyScriptStep(*data, true); }, + .redo = [this, data]() { ApplyScriptStep(*data, false); } + }); + + return count; + + } + + void SceneHistory::ApplyScriptStep(const ScriptStep& step, bool undo) { + + auto setTransforms = [&](const std::vector& matrices) { + for (size_t i = 0; i < step.transformEntities.size(); i++) { + Scene::Entity entity(Resolve(step.transformEntities[i]), &scene->entityManager); + if (!entity.IsValid()) + continue; + entity.GetComponent().Set(matrices[i]); + changedEntities.push_back(entity); + } + }; + auto setEntities = [&]() { + for (const auto& entityChange : step.entities) { + Scene::Entity entity(Resolve(entityChange.entity), &scene->entityManager); + if (!entity.IsValid()) + continue; + RestoreComponents(entity, undo ? entityChange.before : entityChange.after); + changedEntities.push_back(entity); + } + }; + + // The scene was saved after the changes recorded before it, which are undone afterwards and redone before it + if (undo) { + if (!step.sceneBefore.empty()) { + RemoveHierarchies(step.sceneAfter); + RestoreHierarchies(step.sceneBefore); + } + RemoveHierarchies(step.created); + RestoreHierarchies(step.destroyed); + setEntities(); + setTransforms(step.transformsBefore); + if (!step.settingsBefore.is_null()) + RestoreSettings(step.settingsBefore); + } + else { + if (!step.settingsAfter.is_null()) + RestoreSettings(step.settingsAfter); + setTransforms(step.transformsAfter); + setEntities(); + RemoveHierarchies(step.destroyed); + RestoreHierarchies(step.created); + if (!step.sceneAfter.empty()) { + RemoveHierarchies(step.sceneBefore); + RestoreHierarchies(step.sceneAfter); + } + } + + } + + std::vector SceneHistory::SaveHierarchies(const std::vector& roots) { + + // Scripts save thousands of roots at once, e.g. all entities they created under the same parent + std::unordered_set rootSet(roots.begin(), roots.end()); + std::unordered_map> childIndices; + + std::vector hierarchies; + for (auto root : roots) { + if (!root.IsValid()) + continue; + + // Descendants of other roots are part of their hierarchy already + auto hasRootAncestor = false; + for (auto parent = scene->GetParentEntity(root); parent.IsValid() && !hasRootAncestor; parent = scene->GetParentEntity(parent)) + hasRootAncestor = rootSet.contains(parent); + if (hasRootAncestor) + continue; + + auto& hierarchy = hierarchies.emplace_back(); + auto parent = scene->GetParentEntity(root); + hierarchy.parent = parent; + hierarchy.index = 0; + if (parent.IsValid()) { + auto [indices, inserted] = childIndices.try_emplace(parent); + if (inserted) { + const auto& children = parent.GetComponent().GetChildren(); + for (size_t i = 0; i < children.size(); i++) + indices->second[children[i]] = i; + } + hierarchy.index = indices->second[root]; + } + + std::set insertedEntities; + Scene::EntityToJson(hierarchy.entity, root, scene.get(), insertedEntities); + } + return hierarchies; + + } + + void SceneHistory::RemoveHierarchies(const std::vector& hierarchies) { + + for (const auto& hierarchy : hierarchies) { + Scene::Entity entity(Resolve(hierarchy.entity["id"]), &scene->entityManager); + if (entity.IsValid()) + scene->DestroyEntity(entity); + } + + } + + void SceneHistory::RestoreHierarchies(std::vector hierarchies) { + + // Siblings are inserted from the front, such that each one ends up at its index again + std::sort(hierarchies.begin(), hierarchies.end(), + [](const Hierarchy& a, const Hierarchy& b) { return a.index < b.index; }); + + for (const auto& hierarchy : hierarchies) { + auto entity = RestoreEntity(hierarchy.entity); + changedEntities.push_back(entity); + + PlaceEntity(entity, hierarchy.parent, hierarchy.index); + } + + } + + std::vector SceneHistory::SavePlacements(const std::vector& entities) { + + std::vector placements; + for (auto ecsEntity : entities) { + Scene::Entity entity(ecsEntity, &scene->entityManager); + auto parent = scene->GetParentEntity(entity); + size_t index = 0; + if (parent.IsValid()) { + const auto& children = parent.GetComponent().GetChildren(); + index = size_t(std::find(children.begin(), children.end(), entity) - children.begin()); + } + placements.push_back({ ecsEntity, parent, index }); + } + return placements; + + } + + void SceneHistory::RestorePlacements(std::vector placements) { + + // Siblings are inserted from the front, such that each one ends up at its index again + std::sort(placements.begin(), placements.end(), + [](const Placement& a, const Placement& b) { return a.index < b.index; }); + + for (const auto& placement : placements) { + Scene::Entity entity(Resolve(placement.entity), &scene->entityManager); + if (!entity.IsValid()) + continue; + + PlaceEntity(entity, placement.parent, placement.index); + changedEntities.push_back(entity); + } + + } + + void SceneHistory::PlaceEntity(Scene::Entity entity, ECS::Entity parent, size_t index) { + + Scene::Entity parentEntity(Resolve(parent), &scene->entityManager); + if (!parentEntity.IsValid()) + return; + + entity.SetParent(parentEntity); + auto& children = parentEntity.GetComponent().GetChildren(); + auto iter = std::find(children.begin(), children.end(), entity); + children.erase(iter); + children.insert(children.begin() + std::min(index, children.size()), entity); + + } + + Scene::Entity SceneHistory::RestoreEntity(const json& j) { + + auto id = Resolve(j["id"]); + auto ecsEntity = scene->entityManager.Create(id); + if (ecsEntity == ECS::EntityConfig::InvalidEntity) { + ecsEntity = scene->entityManager.Create(); + remappedEntities[id] = ecsEntity; + } + + Scene::Entity entity(ecsEntity, &scene->entityManager); + + auto components = j; + components.erase("id"); + components.erase("entities"); + Scene::EntityFromJson(components, entity, scene.get(), false); + + // Children need their components before the parent adds its hierarchy, see EntityFromJson + if (j.contains("entities")) { + std::vector children; + for (const auto& child : j["entities"]) + children.push_back(RestoreEntity(child)); + + auto& hierarchy = entity.AddComponent(); + hierarchy.root = j["root"]; + for (auto child : children) + hierarchy.AddChild(child); + } + + return entity; + + } + + json SceneHistory::SaveComponents(Scene::Entity entity) { + + json j; + Scene::ComponentsToJson(j, entity, scene.get()); + if (auto comp = entity.TryGetComponent()) + j["root"] = comp->root; + + return j; + + } + + void SceneHistory::RestoreComponents(Scene::Entity entity, const json& j) { + + auto current = SaveComponents(entity); + + for (const auto& [key, value] : current.items()) { + if (key == "root" || (j.contains(key) && IsSameComponent(key, j[key], value))) + continue; + + // The transform is set in place, removing it would detach e.g. the rigid body + if (key == "transform" && j.contains(key)) { + TransformComponent transform = j[key]; + auto& comp = entity.GetComponent(); + comp.isStatic = transform.isStatic; + comp.parentJoint = transform.parentJoint; + comp.Set(transform.matrix); + continue; + } + + Scene::RemoveComponent(entity, key); + } + + json added = json::object(); + for (const auto& [key, value] : j.items()) { + if (key == "root" || (key == "transform" && current.contains(key))) + continue; + if (!current.contains(key) || !IsSameComponent(key, current[key], value)) + added[key] = value; + } + Scene::EntityFromJson(added, entity, scene.get(), false); + + auto hierarchy = entity.TryGetComponent(); + if (hierarchy && j.contains("root")) + hierarchy->root = j["root"]; + + } + + bool SceneHistory::IsSameEntity(const json& a, const json& b) { + + if (a.size() != b.size()) + return false; + + for (const auto& [key, value] : a.items()) + if (!b.contains(key) || !IsSameComponent(key, value, b[key])) + return false; + + return true; + + } + + bool SceneHistory::IsSameComponent(const std::string& key, const json& a, const json& b) { + + // The local matrix is rebuilt from the global one, which changes it by rounding errors + if (key == "transform") { + TransformComponent transformA = a, transformB = b; + if (transformA.isStatic != transformB.isStatic || transformA.parentJoint != transformB.parentJoint) + return false; + for (int32_t i = 0; i < 4; i++) { + auto tolerance = 1e-6f * glm::max(vec4(1.0f), glm::abs(transformA.matrix[i])); + if (glm::any(glm::greaterThan(glm::abs(transformA.matrix[i] - transformB.matrix[i]), tolerance))) + return false; + } + return true; + } + + if (key != "animation" && key != "audio" && key != "rigidBody" && key != "light" && key != "camera") + return a == b; + + // Runtime state which isn't edited, e.g. the shadow cascades follow the camera + auto withoutRuntimeState = [&](json j) { + if (key == "animation") { + j.erase("time"); + if (j.contains("layers")) + for (auto& layer : j["layers"]) + layer.erase("time"); + } + if (key == "audio" && j.contains("stream")) + j["stream"].erase("time"); + if (key == "rigidBody") + j.erase("bodyIndex"); + if (key == "light" && j.contains("shadow")) { + j["shadow"].erase("views"); + j["shadow"].erase("center"); + } + if (key == "camera") + j.erase("aspectRatio"); + return j; + }; + return withoutRuntimeState(a) == withoutRuntimeState(b); + + } + + json SceneHistory::SaveSettings() { + + json j; + Scene::SceneSettingsToJson(j, scene.get()); + return j; + + } + + bool SceneHistory::IsSameSettings(const json& a, const json& b) { + + if (a.size() != b.size()) + return false; + + for (const auto& [key, value] : a.items()) + if (!b.contains(key) || !IsSameSetting(key, value, b[key])) + return false; + + return true; + + } + + bool SceneHistory::IsSameSetting(const std::string& key, const json& a, const json& b) { + + if (key != "irradianceVolume") + return a == b; + + // A scrolling volume follows the camera, only its size is a setting + auto withoutPosition = [](json j) { + if (!j.value("scroll", false) || !j.contains("aabb")) + return j; + const auto& aabb = j["aabb"]; + auto size = json::array(); + for (const auto* axis : { "x", "y", "z" }) + size.push_back(std::round((aabb["max"][axis].get() - aabb["min"][axis].get()) * 100.0f)); + j.erase("aabb"); + j["size"] = size; + return j; + }; + return withoutPosition(a) == withoutPosition(b); + + } + + void SceneHistory::RestoreSettings(const json& j) { + + // Only changed settings are restored, e.g. the irradiance volume would need to be rebuilt + auto current = SaveSettings(); + json changed = json::object(); + for (const auto& [key, value] : j.items()) + if (!current.contains(key) || !IsSameSetting(key, current[key], value)) + changed[key] = value; + + Scene::SceneSettingsFromJson(changed, scene.get()); + + // Features which didn't exist in the restored state are removed again + if (!j.contains("fog")) + scene->fog = nullptr; + if (!j.contains("irradianceVolume")) + scene->irradianceVolume = nullptr; + if (!j.contains("reflection")) + scene->reflection = nullptr; + if (!j.contains("rtgi")) + scene->rtgi = nullptr; + if (!j.contains("sss")) + scene->sss = nullptr; + if (!j.contains("ssgi")) + scene->ssgi = nullptr; + if (!j.contains("ocean")) + scene->ocean = nullptr; + if (!j.contains("navigation")) + scene->navigation = nullptr; + + } + + void SceneHistory::ResetStates() { + + entityStates.clear(); + settingsState = json(); + + } + + ECS::Entity SceneHistory::Resolve(ECS::Entity entity) { + + // Each restore with a new id adds a link, a chain can't be longer than the history + for (size_t i = 0; i <= history.maxSteps; i++) { + auto iter = remappedEntities.find(entity); + if (iter == remappedEntities.end()) + break; + entity = iter->second; + } + return entity; + + } + +} diff --git a/src/editor/SceneHistory.h b/src/editor/SceneHistory.h new file mode 100644 index 000000000..50bbd9652 --- /dev/null +++ b/src/editor/SceneHistory.h @@ -0,0 +1,169 @@ +#pragma once + +#include "UndoHistory.h" + +#include "scene/Scene.h" +#include "common/SerializationHelper.h" + +#include +#include + +namespace Atlas::Editor { + + // Undo steps of a scene. Restored entities keep their ids, unless another entity took the id in the meantime + class SceneHistory { + + public: + // Compares the selected entities and the scene settings with their last state once an interaction finished + void Update(const Ref& scene, const std::unordered_set& selectedEntities); + + // Structural changes save the hierarchies below the roots before and after the change + void BeginChange(const Ref& scene, const std::vector& roots); + + void EndChange(const std::string& name, const std::vector& roots); + + // Moves only save the parents and the order of the entities, not their hierarchies + void BeginMove(const Ref& scene, const std::vector& entities); + + void EndMove(const std::string& name); + + // Component edits of entities which aren't selected, e.g. renaming in the hierarchy + void BeginEdit(const Ref& scene, const std::vector& entities); + + void EndEdit(const std::string& name); + + // Changes made by code, e.g. a Lua command of the bridge, become one step. An entity is saved the first time it + // is about to change, of transforms only the matrices are kept, such that edits of many entities stay cheap + void BeginScriptChange(const Ref& scene); + + void BeforeEntityChange(Scene::Entity entity); + + void BeforeTransformChange(Scene::Entity entity); + + void EntityCreated(Scene::Entity entity); + + void BeforeEntityDestroy(Scene::Entity entity); + + // For changes which can't say what they touch: the root hierarchy is saved once, before the first of them, and + // after the command. Changes after it aren't recorded separately + void BeforeSceneChange(); + + // Pushes the step if something changed, returns the number of changed, created and destroyed entities + size_t EndScriptChange(const std::string& name); + + bool Undo(const Ref& scene); + + bool Redo(const Ref& scene); + + void Clear(); + + // The entities the last undo or redo changed + std::vector GetChangedEntities(); + + UndoHistory history; + + private: + struct Hierarchy { + ECS::Entity parent; + size_t index; + json entity; + }; + + struct Placement { + ECS::Entity entity; + ECS::Entity parent; + size_t index; + }; + + struct EntityChange { + ECS::Entity entity; + json before; + json after; + }; + + void PushEntityChanges(const std::string& name, const std::vector& changes); + + std::vector SaveHierarchies(const std::vector& roots); + + void RemoveHierarchies(const std::vector& hierarchies); + + void RestoreHierarchies(std::vector hierarchies); + + Scene::Entity RestoreEntity(const json& j); + + std::vector SavePlacements(const std::vector& entities); + + void RestorePlacements(std::vector placements); + + void PlaceEntity(Scene::Entity entity, ECS::Entity parent, size_t index); + + json SaveComponents(Scene::Entity entity); + + void RestoreComponents(Scene::Entity entity, const json& j); + + bool IsSameEntity(const json& a, const json& b); + + // Playback times, physics bodies and shadow cascades change while nothing is edited + bool IsSameComponent(const std::string& key, const json& a, const json& b); + + json SaveSettings(); + + bool IsSameSettings(const json& a, const json& b); + + bool IsSameSetting(const std::string& key, const json& a, const json& b); + + void RestoreSettings(const json& j); + + void ResetStates(); + + ECS::Entity Resolve(ECS::Entity entity); + + Ref scene; + + std::unordered_map entityStates; + json settingsState; + + std::vector hierarchiesBefore; + bool changeStarted = false; + + std::vector placementsBefore; + + std::vector editedEntities; + + // Entities which were restored with a new id, because the old one was taken + std::unordered_map remappedEntities; + + std::vector changedEntities; + + struct ScriptChange { + bool active = false; + bool sceneSaved = false; + std::unordered_map entitiesBefore; + std::unordered_set transformEntities; + std::vector> transforms; + std::unordered_set created; + std::vector destroyed; + std::vector sceneBefore; + // Sky, fog, post processing and the other settings of the scene + json settingsBefore; + } scriptChange; + + // Shared by the undo and redo of a step, such that large steps are kept once + struct ScriptStep { + std::vector entities; + std::vector transformEntities; + std::vector transformsBefore; + std::vector transformsAfter; + std::vector created; + std::vector destroyed; + std::vector sceneBefore; + std::vector sceneAfter; + json settingsBefore; + json settingsAfter; + }; + + void ApplyScriptStep(const ScriptStep& step, bool undo); + + }; + +} diff --git a/src/editor/Serialization.cpp b/src/editor/Serialization.cpp index d980bc566..4e386e1c2 100644 --- a/src/editor/Serialization.cpp +++ b/src/editor/Serialization.cpp @@ -1,19 +1,29 @@ #include "Serialization.h" #include "Singletons.h" #include "FileImporter.h" +#include "Notifications.h" #include "common/SerializationHelper.h" #include "tools/ToolSerializer.h" #include "scene/SceneSerializer.h" +#include "physics/PhysicsSerializer.h" #include "Log.h" +#include "profiler/HitchRecorder.h" + +#include +#include #include "loader/AssetLoader.h" namespace Atlas::Editor { - const std::string Serialization::configPath = ".config/"; - const std::string Serialization::configFilename = configPath + "config.json"; - const std::string Serialization::contentBrowserWindowFilename = configPath + "contentBrowserWindowConfig.json"; + std::string Serialization::configPath = ".config/"; + + void Serialization::SetConfigDirectory(const std::string& directory) { + + configPath = directory.ends_with('/') ? directory : directory + "/"; + + } void Serialization::SerializeConfig() { @@ -23,21 +33,42 @@ namespace Atlas::Editor { for (const auto& scene : config->openedScenes) scenePaths.push_back(scene.GetResource()->path); + auto detectorToJson = [](const HitchRecorder::Detector& detector) { + return json { + { "enable", detector.enable }, + { "metric", static_cast(detector.metric) }, + { "trigger", static_cast(detector.trigger) }, + { "minimumTime", detector.minimumTime }, + { "relativeThreshold", detector.relativeThreshold } + }; + }; + + auto hitchSettings = HitchRecorder::GetSettings(); + json hitches = { + { "enable", hitchSettings.enable }, + { "cpu", detectorToJson(hitchSettings.cpu) }, + { "gpu", detectorToJson(hitchSettings.gpu) }, + { "maxHitches", hitchSettings.maxHitches } + }; + json j = { { "darkMode", config->darkMode }, { "pathTrace", config->pathTrace }, { "vsync", config->vsync }, + { "uiScale", config->uiScale }, { "scenes", scenePaths }, - { "recentScenes", config->recentScenes } + { "recentScenes", config->recentScenes }, + { "statusBarDrawers", config->statusBarDrawers }, + { "hitches", hitches } }; - TryWriteToFile(configFilename, to_string(j)); + TryWriteToFile(configPath + "config.json", j); } void Serialization::DeserializeConfig() { - auto serialized = TryReadFromFile(configFilename); + auto serialized = TryReadFromFile(configPath + "config.json"); if (serialized.empty()) return; @@ -54,10 +85,38 @@ namespace Atlas::Editor { j.at("pathTrace").get_to(config->pathTrace); if (j.contains("vsync")) j.at("vsync").get_to(config->vsync); + if (j.contains("uiScale")) + j.at("uiScale").get_to(config->uiScale); if (j.contains("scenes")) j.at("scenes").get_to(scenePaths); if (j.contains("recentScenes")) j.at("recentScenes").get_to(config->recentScenes); + if (j.contains("statusBarDrawers")) + j.at("statusBarDrawers").get_to(config->statusBarDrawers); + + if (j.contains("hitches")) { + auto detectorFromJson = [](const json& j, HitchRecorder::Detector& detector) { + int32_t metric = static_cast(detector.metric); + int32_t trigger = static_cast(detector.trigger); + try_get_json(j, "enable", detector.enable); + try_get_json(j, "metric", metric); + try_get_json(j, "trigger", trigger); + try_get_json(j, "minimumTime", detector.minimumTime); + try_get_json(j, "relativeThreshold", detector.relativeThreshold); + detector.metric = static_cast(metric); + detector.trigger = static_cast(trigger); + }; + + const auto& hitches = j["hitches"]; + auto hitchSettings = HitchRecorder::GetSettings(); + try_get_json(hitches, "enable", hitchSettings.enable); + try_get_json(hitches, "maxHitches", hitchSettings.maxHitches); + if (hitches.contains("cpu")) + detectorFromJson(hitches["cpu"], hitchSettings.cpu); + if (hitches.contains("gpu")) + detectorFromJson(hitches["gpu"], hitchSettings.gpu); + HitchRecorder::SetSettings(hitchSettings); + } // No need to add it to the config, will be done through resource events for (const auto& scenePath : scenePaths) @@ -65,6 +124,16 @@ namespace Atlas::Editor { } + std::string Serialization::GetSceneWindowConfigFilename(const ResourceHandle& scene) { + + // The path without its extension, e.g. scenes_sponzaWindowConfig.json for scenes/sponza.aescene + auto key = UI::SceneWindow::GetScenePath(scene); + key = key.substr(0, key.rfind('.')); + std::replace_if(key.begin(), key.end(), [](char c) { return c == '/' || c == '\\' || c == ':'; }, '_'); + return configPath + key + "WindowConfig.json"; + + } + void Serialization::SerializeSceneWindow(const Ref& sceneWindow) { if (!sceneWindow->scene.IsLoaded()) @@ -84,17 +153,25 @@ namespace Atlas::Editor { { "showGrid", sceneWindow->showGrid }, { "cameraRotationSpeed", sceneWindow->cameraRotationSpeed }, { "depthTestBoundingVolumes", sceneWindow->depthTestBoundingVolumes }, + { "showPhysics", sceneWindow->showPhysics }, + { "depthTestPhysics", sceneWindow->depthTestPhysics }, + { "physicsDebugDrawSettings", sceneWindow->physicsDebugDrawSettings }, { "playMaximized", sceneWindow->playMaximized }, { "perfOverlayMaximized", sceneWindow->perfOverlayMaximized }, { "terrainGenerator", sceneWindow->scenePropertiesPanel.terrainPanel.terrainGenerator }, { "vegetationGenerator", sceneWindow->scenePropertiesPanel.terrainPanel.vegetationGeneratorPanel.vegetationGenerator }, - { "hierarchyFilter", sceneWindow->sceneHierarchyPanel.hierarchyFilter }, { "camera", camera } }; - auto filename = configPath + sceneWindow->scene->name + "WindowConfig.json"; + // Hidden components are saved by their key, new component types are shown + json hiddenComponents = json::array(); + const auto& componentTypes = Scene::GetComponentTypes(); + for (size_t i = 0; i < componentTypes.size(); i++) + if (!(sceneWindow->sceneHierarchyPanel.hierarchyFilter & (1u << uint32_t(i)))) + hiddenComponents.push_back(componentTypes[i].key); + j["hierarchyHiddenComponents"] = hiddenComponents; - TryWriteToFile(filename, to_string(j)); + TryWriteToFile(GetSceneWindowConfigFilename(sceneWindow->scene), j); } @@ -103,11 +180,12 @@ namespace Atlas::Editor { if (!handle.IsLoaded()) return nullptr; - auto filename = configPath + handle->name + "WindowConfig.json"; - auto sceneWindow = CreateRef(handle, true); - auto serialized = TryReadFromFile(filename); + // Configs written before they were named by the file are named by the scene, saving moves them over + auto serialized = TryReadFromFile(GetSceneWindowConfigFilename(handle)); + if (serialized.empty()) + serialized = TryReadFromFile(configPath + handle->name + "WindowConfig.json"); if (serialized.empty()) return sceneWindow; @@ -125,12 +203,20 @@ namespace Atlas::Editor { try_get_json(j, "showGrid", sceneWindow->showGrid); try_get_json(j, "cameraRotationSpeed", sceneWindow->cameraRotationSpeed); try_get_json(j, "depthTestBoundingVolumes", sceneWindow->depthTestBoundingVolumes); + try_get_json(j, "showPhysics", sceneWindow->showPhysics); + try_get_json(j, "depthTestPhysics", sceneWindow->depthTestPhysics); + try_get_json(j, "physicsDebugDrawSettings", sceneWindow->physicsDebugDrawSettings); try_get_json(j, "playMaximized", sceneWindow->playMaximized); try_get_json(j, "perfOverlayMaximized", sceneWindow->perfOverlayMaximized); try_get_json(j, "camera", camera); try_get_json(j, "terrainGenerator", sceneWindow->scenePropertiesPanel.terrainPanel.terrainGenerator); try_get_json(j, "vegetationGenerator", sceneWindow->scenePropertiesPanel.terrainPanel.vegetationGeneratorPanel.vegetationGenerator); - try_get_json(j, "hierarchyFilter", sceneWindow->sceneHierarchyPanel.hierarchyFilter); + std::vector hiddenComponents; + try_get_json(j, "hierarchyHiddenComponents", hiddenComponents); + const auto& componentTypes = Scene::GetComponentTypes(); + for (size_t i = 0; i < componentTypes.size(); i++) + if (std::find(hiddenComponents.begin(), hiddenComponents.end(), componentTypes[i].key) != hiddenComponents.end()) + sceneWindow->sceneHierarchyPanel.hierarchyFilter &= ~(1u << uint32_t(i)); sceneWindow->cameraEntity = sceneWindow->scene->CreateEntity(); Scene::EntityFromJson(camera, sceneWindow->cameraEntity, sceneWindow->scene.Get().get(), false); @@ -149,15 +235,20 @@ namespace Atlas::Editor { { "searchRecursively", contentBrowserWindow.searchRecursively }, { "contentFilter", contentBrowserWindow.contentFilter }, { "iconSize", contentBrowserWindow.iconSize }, + { "folderPanelWidth", contentBrowserWindow.folderPanelWidth }, + { "listView", contentBrowserWindow.listView }, + { "showPreviews", contentBrowserWindow.showPreviews }, + { "pinned", contentBrowserWindow.pinned }, + { "drawerHeight", contentBrowserWindow.height }, }; - TryWriteToFile(contentBrowserWindowFilename, to_string(j)); + TryWriteToFile(configPath + "contentBrowserWindowConfig.json", j); } void Serialization::DeserializeContentBrowserWindow(UI::ContentBrowserWindow& contentBrowserWindow) { - auto serialized = TryReadFromFile(contentBrowserWindowFilename); + auto serialized = TryReadFromFile(configPath + "contentBrowserWindowConfig.json"); if (serialized.empty()) return; @@ -170,22 +261,68 @@ namespace Atlas::Editor { j.at("searchRecursively").get_to(contentBrowserWindow.searchRecursively); if (j.contains("contentFilter")) j.at("contentFilter").get_to(contentBrowserWindow.contentFilter); + // A filter showing all types of an older version shows the types added since then too + auto filter = contentBrowserWindow.contentFilter; + if (filter == (1u << 11) - 1 || filter == (1u << 12) - 1 || filter == (1u << 13) - 1) + contentBrowserWindow.contentFilter = UI::ContentBrowserWindow::AllBit; if (j.contains("iconSize")) j.at("iconSize").get_to(contentBrowserWindow.iconSize); + if (j.contains("folderPanelWidth")) + j.at("folderPanelWidth").get_to(contentBrowserWindow.folderPanelWidth); + if (j.contains("listView")) + j.at("listView").get_to(contentBrowserWindow.listView); + if (j.contains("showPreviews")) + j.at("showPreviews").get_to(contentBrowserWindow.showPreviews); + if (j.contains("pinned")) + j.at("pinned").get_to(contentBrowserWindow.pinned); + if (j.contains("drawerHeight")) + j.at("drawerHeight").get_to(contentBrowserWindow.height); + contentBrowserWindow.show = contentBrowserWindow.pinned; } - void Serialization::TryWriteToFile(const std::string& filename, const std::string& content) { + void Serialization::SerializeDrawerWindow(const UI::DrawerWindow& drawerWindow) { - auto fileStream = Loader::AssetLoader::WriteFile(filename, std::ios::out | std::ios::binary); + json j = { + { "pinned", drawerWindow.pinned }, + { "drawerHeight", drawerWindow.height }, + }; - if (!fileStream.is_open()) { - Log::Error("Couldn't write config file"); + TryWriteToFile(GetDrawerWindowConfigFilename(drawerWindow), j); + + } + + void Serialization::DeserializeDrawerWindow(UI::DrawerWindow& drawerWindow) { + + auto serialized = TryReadFromFile(GetDrawerWindowConfigFilename(drawerWindow)); + + if (serialized.empty()) return; - } - fileStream << content; + json j = json::parse(serialized); + + if (j.contains("pinned")) + j.at("pinned").get_to(drawerWindow.pinned); + if (j.contains("drawerHeight")) + j.at("drawerHeight").get_to(drawerWindow.height); + drawerWindow.show = drawerWindow.pinned; - fileStream.close(); + } + + std::string Serialization::GetDrawerWindowConfigFilename(const UI::DrawerWindow& drawerWindow) { + + // E.g. logWindowConfig.json for the log + auto name = drawerWindow.name; + name[0] = char(std::tolower(name[0])); + return configPath + name + "WindowConfig.json"; + + } + + void Serialization::TryWriteToFile(const std::string& filename, json& j) { + + if (!Loader::AssetLoader::WriteJson(filename, j, Loader::JsonFormat::Compact)) { + Log::Error("Couldn't write config file"); + Notifications::Push({ .message = "Couldn't write the editor settings to " + filename, .type = NotificationType::Error }); + } } diff --git a/src/editor/Serialization.h b/src/editor/Serialization.h index ab8f19031..48d436ce3 100644 --- a/src/editor/Serialization.h +++ b/src/editor/Serialization.h @@ -3,6 +3,8 @@ #include #include "ui/windows/SceneWindow.h" +#include "ui/windows/ContentBrowserWindow.h" +#include "ui/windows/DrawerWindow.h" namespace Atlas::Editor { @@ -21,14 +23,25 @@ namespace Atlas::Editor { static void DeserializeContentBrowserWindow(UI::ContentBrowserWindow& contentBrowserWindow); + // Only the drawer state, the content browser has its own config + static void SerializeDrawerWindow(const UI::DrawerWindow& drawerWindow); + + static void DeserializeDrawerWindow(UI::DrawerWindow& drawerWindow); + + // The .atlas directory of a project, without a project .config in the asset directory + static void SetConfigDirectory(const std::string& directory); + private: - static void TryWriteToFile(const std::string& filename, const std::string& content); + // Scenes are identified by their file, the internal names of two scenes can be the same + static std::string GetSceneWindowConfigFilename(const ResourceHandle& scene); + + static std::string GetDrawerWindowConfigFilename(const UI::DrawerWindow& drawerWindow); + + static void TryWriteToFile(const std::string& filename, json& j); static std::string TryReadFromFile(const std::string& filename); - static const std::string configFilename; - static const std::string configPath; - static const std::string contentBrowserWindowFilename; + static std::string configPath; }; diff --git a/src/editor/Singletons.cpp b/src/editor/Singletons.cpp index 9612f4d84..c89cbaa85 100644 --- a/src/editor/Singletons.cpp +++ b/src/editor/Singletons.cpp @@ -1,22 +1,25 @@ #include "Singletons.h" +#include "ContentPreviews.h" namespace Atlas::Editor { Ref Singletons::imguiWrapper; - Ref Singletons::renderTarget; Ref Singletons::mainRenderer; Ref Singletons::icons; Ref Singletons::config; Ref Singletons::blockingOperation; + Ref Singletons::contentPreviews; + Ref Singletons::project; void Singletons::Destruct() { + contentPreviews.reset(); imguiWrapper.reset(); - renderTarget.reset(); mainRenderer.reset(); icons.reset(); config.reset(); blockingOperation.reset(); + project.reset(); } diff --git a/src/editor/Singletons.h b/src/editor/Singletons.h index 6500e3258..aa0b5ec52 100644 --- a/src/editor/Singletons.h +++ b/src/editor/Singletons.h @@ -7,19 +7,26 @@ #include "Config.h" #include "BlockingOperation.h" +#include "project/Project.h" + namespace Atlas::Editor { + class ContentPreviews; + class Singletons { public: static void Destruct(); static Ref imguiWrapper; - static Ref renderTarget; static Ref mainRenderer; static Ref icons; static Ref config; static Ref blockingOperation; + // Shared by everything which shows content, e.g. the content browser and resource selections + static Ref contentPreviews; + // Without a project the editor shows the project hub + static Ref project; }; diff --git a/src/editor/Theme.cpp b/src/editor/Theme.cpp index 68caf0e8c..a37b70390 100644 --- a/src/editor/Theme.cpp +++ b/src/editor/Theme.cpp @@ -5,6 +5,7 @@ namespace Atlas::Editor { bool Theme::dark = true; + ImFont* Theme::codeFont = nullptr; static ImVec4 Rgb(int r, int g, int b, float a = 1.0f) { @@ -259,6 +260,23 @@ namespace Atlas::Editor { } + void Theme::PushDangerButton() { + + // Tinted instead of filled, a destructive action shouldn't look like the main action of a group + ImGui::PushStyleColor(ImGuiCol_Button, Error(0.14f)); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, Error(0.28f)); + ImGui::PushStyleColor(ImGuiCol_ButtonActive, Error(0.4f)); + ImGui::PushStyleColor(ImGuiCol_Border, Error(0.45f)); + ImGui::PushStyleColor(ImGuiCol_Text, Error()); + + } + + void Theme::PopDangerButton() { + + ImGui::PopStyleColor(5); + + } + ImVec4 Theme::Base(float alpha) { return WithAlpha(GetPalette(dark).base, alpha); @@ -289,6 +307,76 @@ namespace Atlas::Editor { } + ImVec4 Theme::ContentIcon(ContentType type, float alpha) { + + // Only folders stand out, files keep the color of the text + if (type != ContentType::None) + return WithAlpha(GetPalette(dark).text, alpha); + + return dark ? Rgb(242, 199, 107, alpha) : Rgb(196, 140, 40, alpha); + + } + + ImVec4 Theme::ContentTypeColor(Editor::ContentType type, float alpha) { + + // Distinct hues per type, slightly darker in light mode such that the strips keep their contrast + ImVec4 color; + switch (type) { + case Editor::ContentType::Texture: color = Rgb(214, 86, 78); break; + case Editor::ContentType::EnvironmentTexture: color = Rgb(230, 146, 64); break; + case Editor::ContentType::Material: color = Rgb(102, 187, 92); break; + case Editor::ContentType::MaterialGraph: color = Rgb(56, 178, 150); break; + case Editor::ContentType::Mesh: color = Rgb(64, 172, 226); break; + case Editor::ContentType::MeshSource: color = Rgb(112, 146, 186); break; + case Editor::ContentType::Prefab: color = Rgb(92, 120, 240); break; + case Editor::ContentType::Scene: color = Rgb(238, 186, 64); break; + case Editor::ContentType::Audio: color = Rgb(170, 110, 226); break; + case Editor::ContentType::Font: color = Rgb(180, 180, 188); break; + case Editor::ContentType::Script: color = Rgb(218, 206, 84); break; + case Editor::ContentType::Shader: color = Rgb(196, 150, 98); break; + case Editor::ContentType::Terrain: color = Rgb(140, 160, 80); break; + case Editor::ContentType::Animation: color = Rgb(226, 104, 164); break; + default: color = GetPalette(dark).textMuted; break; + } + + if (!dark) + color = ImVec4(color.x * 0.85f, color.y * 0.85f, color.z * 0.85f, color.w); + + return WithAlpha(color, alpha); + + } + + ImVec4 Theme::AssetCard(float alpha) { + + return WithAlpha(GetPalette(dark).elevated, alpha); + + } + + ImVec4 Theme::AssetCardHovered(float alpha) { + + return WithAlpha(GetPalette(dark).control, alpha); + + } + + ImVec4 Theme::AssetThumbnail(float alpha) { + + // Darker than the card in dark mode, the previews of meshes and materials stand out on it + return dark ? Rgb(16, 17, 19, alpha) : WithAlpha(GetPalette(dark).base, alpha); + + } + + ImVec4 Theme::PreviewBackground(float alpha) { + + return dark ? Rgb(52, 60, 74, alpha) : Rgb(212, 220, 232, alpha); + + } + + ImVec4 Theme::Shadow(float alpha) { + + return ImVec4(0.0f, 0.0f, 0.0f, (dark ? 0.3f : 0.15f) * alpha); + + } + ImVec4 Theme::Axis(int32_t axis, float alpha) { switch (axis) { @@ -299,6 +387,80 @@ namespace Atlas::Editor { } + ImVec4 Theme::GraphBackground(float alpha) { + + return dark ? Rgb(24, 25, 28, alpha) : Rgb(236, 237, 240, alpha); + + } + + ImVec4 Theme::GraphGrid(float alpha) { + + return dark ? Rgb(255, 255, 255, 0.07f * alpha) : Rgb(0, 0, 0, 0.09f * alpha); + + } + + ImVec4 Theme::GraphNode(float alpha) { + + return dark ? Rgb(44, 46, 51, alpha) : Rgb(250, 250, 252, alpha); + + } + + ImVec4 Theme::GraphNodeBorder(float alpha) { + + return dark ? Rgb(255, 255, 255, 0.14f * alpha) : Rgb(0, 0, 0, 0.2f * alpha); + + } + + ImVec4 Theme::GraphNodeHeader(const char* category, float alpha) { + + const std::string name = category; + + vec3 color(0.45f, 0.47f, 0.52f); + if (name == "Input") color = vec3(0.68f, 0.28f, 0.33f); + else if (name == "Constant") color = vec3(0.32f, 0.42f, 0.55f); + else if (name == "Parameter") color = vec3(0.56f, 0.38f, 0.72f); + else if (name == "Texture") color = vec3(0.62f, 0.44f, 0.2f); + else if (name == "Math") color = vec3(0.24f, 0.46f, 0.6f); + else if (name == "Vector") color = vec3(0.22f, 0.52f, 0.5f); + else if (name == "Transform") color = vec3(0.3f, 0.5f, 0.4f); + else if (name == "Coordinates") color = vec3(0.42f, 0.5f, 0.28f); + else if (name == "Procedural") color = vec3(0.26f, 0.54f, 0.34f); + else if (name == "Normal") color = vec3(0.34f, 0.36f, 0.72f); + else if (name == "Logic") color = vec3(0.66f, 0.3f, 0.52f); + else if (name == "Output") color = vec3(0.72f, 0.42f, 0.14f); + + // The text on top stays readable in both modes + return ImVec4(color.x * (dark ? 0.8f : 1.1f), color.y * (dark ? 0.8f : 1.1f), color.z * (dark ? 0.8f : 1.1f), alpha); + + } + + ImVec4 Theme::GraphValue(int32_t type, float alpha) { + + switch (type) { + case 0: return Rgb(160, 200, 240, alpha); + case 1: return Rgb(110, 210, 160, alpha); + case 2: return Rgb(235, 200, 90, alpha); + case 3: return Rgb(235, 130, 160, alpha); + case 4: return Rgb(200, 140, 240, alpha); + default: return Rgb(200, 200, 200, alpha); + } + + } + + ImVec4 Theme::Code(int32_t type, float alpha) { + + switch (type) { + case 0: return dark ? Rgb(86, 156, 214, alpha) : Rgb(0, 92, 197, alpha); + case 1: return dark ? Rgb(78, 201, 176, alpha) : Rgb(38, 127, 153, alpha); + case 2: return dark ? Rgb(220, 220, 170, alpha) : Rgb(121, 94, 38, alpha); + case 3: return dark ? Rgb(181, 206, 168, alpha) : Rgb(9, 134, 88, alpha); + case 4: return dark ? Rgb(206, 145, 120, alpha) : Rgb(163, 21, 21, alpha); + case 5: return dark ? Rgb(106, 153, 85, alpha) : Rgb(0, 128, 0, alpha); + default: return dark ? Rgb(197, 134, 192, alpha) : Rgb(175, 0, 219, alpha); + } + + } + ImVec4 Theme::OverlayBackground(float alpha) { return WithAlpha(dark ? Rgb(20, 21, 24, 0.78f) : Rgb(250, 250, 252, 0.85f), alpha); diff --git a/src/editor/Theme.h b/src/editor/Theme.h index d784c3355..a777e550e 100644 --- a/src/editor/Theme.h +++ b/src/editor/Theme.h @@ -1,5 +1,7 @@ #pragma once +#include "Content.h" + #include #include @@ -23,6 +25,10 @@ namespace Atlas::Editor { static void PushPrimaryButton(); static void PopPrimaryButton(); + // Style for buttons that remove or delete something, pop with PopDangerButton() + static void PushDangerButton(); + static void PopDangerButton(); + // Darkest neutral (lightest in light mode), used behind and between panels static ImVec4 Base(float alpha = 1.0f); @@ -32,6 +38,23 @@ namespace Atlas::Editor { static ImVec4 TextMuted(float alpha = 1.0f); + // Tint of the content icons, only folders are colored + static ImVec4 ContentIcon(ContentType type, float alpha = 1.0f); + + // Color of each type of content, e.g. the strip below the thumbnails of the content browser + static ImVec4 ContentTypeColor(ContentType type, float alpha = 1.0f); + + // Cards of the content browser and the area of their thumbnails + static ImVec4 AssetCard(float alpha = 1.0f); + static ImVec4 AssetCardHovered(float alpha = 1.0f); + static ImVec4 AssetThumbnail(float alpha = 1.0f); + + // Blue-grey behind small previews, e.g. in resource selections, which sets them apart from the panel + static ImVec4 PreviewBackground(float alpha = 1.0f); + + // Shadow of windows which float above the layout, e.g. drawers + static ImVec4 Shadow(float alpha = 1.0f); + // X, Y and Z axis colors (index 0 to 2), matching the gizmo static ImVec4 Axis(int32_t axis, float alpha = 1.0f); @@ -39,8 +62,24 @@ namespace Atlas::Editor { static ImVec4 OverlayBackground(float alpha = 1.0f); static ImVec4 OverlayBorder(float alpha = 1.0f); + // Colors of the node editor + static ImVec4 GraphBackground(float alpha = 1.0f); + static ImVec4 GraphGrid(float alpha = 1.0f); + static ImVec4 GraphNode(float alpha = 1.0f); + static ImVec4 GraphNodeBorder(float alpha = 1.0f); + // The header shows the category of a node + static ImVec4 GraphNodeHeader(const char* category, float alpha = 1.0f); + // Pins and links show the type of their value, in the order of MaterialGraph::ValueType + static ImVec4 GraphValue(int32_t type, float alpha = 1.0f); + + // Syntax highlighting: keyword, type, builtin, number, string, comment and preprocessor + static ImVec4 Code(int32_t type, float alpha = 1.0f); + static constexpr float overlayRounding = 6.0f; + // Monospace font of code, null until the fonts are loaded + static ImFont* codeFont; + private: static bool dark; diff --git a/src/editor/UndoHistory.cpp b/src/editor/UndoHistory.cpp new file mode 100644 index 000000000..72afafeba --- /dev/null +++ b/src/editor/UndoHistory.cpp @@ -0,0 +1,133 @@ +#include "UndoHistory.h" + +#include +#include + +namespace Atlas::Editor { + + void UndoHistory::Push(Step step) { + + steps.resize(position); + steps.push_back(std::move(step)); + + if (steps.size() > maxSteps) + steps.erase(steps.begin()); + + position = steps.size(); + + } + + bool UndoHistory::Undo() { + + if (!CanUndo()) + return false; + + position--; + steps[position].undo(); + + return true; + + } + + bool UndoHistory::Redo() { + + if (!CanRedo()) + return false; + + steps[position].redo(); + position++; + + return true; + + } + + bool UndoHistory::CanUndo() const { + + return position > 0; + + } + + bool UndoHistory::CanRedo() const { + + return position < steps.size(); + + } + + std::string UndoHistory::GetUndoName() const { + + return CanUndo() ? steps[position - 1].name : std::string(); + + } + + std::string UndoHistory::GetRedoName() const { + + return CanRedo() ? steps[position].name : std::string(); + + } + + void UndoHistory::Clear() { + + steps.clear(); + position = 0; + + } + + bool UndoHistory::IsInteractionFinished() { + + auto interacting = ImGui::IsAnyItemActive() || ImGui::IsAnyMouseDown() || ImGuizmo::IsUsing(); + + // Shortcuts like dropping the selection to the ground edit without an active item + auto keyReleased = false; + for (auto key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = ImGuiKey(key + 1)) + keyReleased |= ImGui::IsKeyReleased(key); + + auto finished = !interacting && (wasInteracting || keyReleased); + wasInteracting = interacting; + + return finished; + + } + + bool UndoHistory::IsInteracting() const { + + return wasInteracting; + + } + + bool UndoHistory::HandleShortcuts() { + + auto direction = GetShortcutDirection(); + if (direction < 0) + return Undo(); + if (direction > 0) + return Redo(); + + return false; + + } + + int32_t UndoHistory::GetShortcutDirection() const { + + // Text fields have their own undo + if (ImGui::GetIO().WantTextInput) + return 0; + + bool controlDown; +#ifdef AE_OS_MACOS + controlDown = ImGui::IsKeyDown(ImGuiKey_LeftSuper) || ImGui::IsKeyDown(ImGuiKey_RightSuper); +#else + controlDown = ImGui::GetIO().KeyCtrl; +#endif + if (!controlDown) + return 0; + + if (ImGui::IsKeyPressed(ImGuiKey_Z) && !ImGui::GetIO().KeyShift) + return -1; + if ((ImGui::IsKeyPressed(ImGuiKey_Z) && ImGui::GetIO().KeyShift) || ImGui::IsKeyPressed(ImGuiKey_Y)) + return 1; + + return 0; + + } + +} diff --git a/src/editor/UndoHistory.h b/src/editor/UndoHistory.h new file mode 100644 index 000000000..f7b55079c --- /dev/null +++ b/src/editor/UndoHistory.h @@ -0,0 +1,58 @@ +#pragma once + +#include +#include +#include + +namespace Atlas::Editor { + + // Undo steps of one document, e.g. a scene or an asset editor + class UndoHistory { + + public: + struct Step { + std::string name; + std::function undo; + std::function redo; + }; + + // Removes the steps which were undone before + void Push(Step step); + + bool Undo(); + + bool Redo(); + + bool CanUndo() const; + + bool CanRedo() const; + + std::string GetUndoName() const; + + std::string GetRedoName() const; + + void Clear(); + + // Edits are compared once the user stops interacting, such that e.g. a drag is a single step + bool IsInteractionFinished(); + + // Whether an interaction was going on the last time it was checked + bool IsInteracting() const; + + // Handles the undo and redo shortcuts, returns true if a step was undone or redone + bool HandleShortcuts(); + + // -1 when the undo shortcut was pressed, 1 for the redo shortcut and 0 otherwise + int32_t GetShortcutDirection() const; + + size_t maxSteps = 256; + + private: + std::vector steps; + size_t position = 0; + + bool wasInteracting = false; + + }; + +} diff --git a/src/editor/tools/FileSystemHelper.cpp b/src/editor/tools/FileSystemHelper.cpp index ed55d887e..98850bfb7 100644 --- a/src/editor/tools/FileSystemHelper.cpp +++ b/src/editor/tools/FileSystemHelper.cpp @@ -32,7 +32,7 @@ namespace Atlas::Editor { catch (std::exception& e) { success = false; auto message = "Error copying " + path + " to asset directory: " + e.what(); - Notifications::Push({ message, vec3(1.0f, 0.0f, 0.0f) }); + Notifications::Push({ message, NotificationType::Error }); Log::Error(message); } } @@ -62,7 +62,7 @@ namespace Atlas::Editor { catch (std::exception& e) { success = false; auto message = "Error deleting " + path + ": " + e.what(); - Notifications::Push({ message, vec3(1.0f, 0.0f, 0.0f) }); + Notifications::Push({ message, NotificationType::Error }); Log::Error(message); } } @@ -97,7 +97,7 @@ namespace Atlas::Editor { } catch (std::exception& e) { auto message = "Error duplicating " + path + ": " + e.what(); - Notifications::Push({ message, vec3(1.0f, 0.0f, 0.0f) }); + Notifications::Push({ message, NotificationType::Error }); Log::Error(message); } }); diff --git a/src/editor/tools/Guizmo.h b/src/editor/tools/Guizmo.h index 6d2f4e826..800e1436c 100644 --- a/src/editor/tools/Guizmo.h +++ b/src/editor/tools/Guizmo.h @@ -26,6 +26,8 @@ namespace Atlas::Editor { // Imguizmo translate mode int32_t mode = 7; bool objectSpace = false; + // Surface snapping (Shift while translating) also turns the up axis of the selection to the surface normal + bool alignToSurface = false; bool needEnabled = false; diff --git a/src/editor/tools/PrimitiveBatchWrapper.cpp b/src/editor/tools/PrimitiveBatchWrapper.cpp index c766c29fb..f5f0006db 100644 --- a/src/editor/tools/PrimitiveBatchWrapper.cpp +++ b/src/editor/tools/PrimitiveBatchWrapper.cpp @@ -18,109 +18,9 @@ namespace Atlas::Editor { } - void PrimitiveBatchWrapper::RenderLine(vec3 p0, vec3 p1, vec3 color, bool depthTest) { + const Ref& PrimitiveBatchWrapper::GetBatch(bool depthTest) const { - auto& primitiveBatch = depthTest ? primitiveBatchDepthTest : primitiveBatchNoDepthTest; - - primitiveBatch->AddLine(p0, p1, color, color); - - } - - void PrimitiveBatchWrapper::RenderLineAABB(Volume::AABB aabb, glm::vec3 color, bool depthTest) { - - auto corners = aabb.GetCorners(); - - auto& primitiveBatch = depthTest ? primitiveBatchDepthTest : primitiveBatchNoDepthTest; - - primitiveBatch->AddLine(corners[0], corners[1], color, color); - primitiveBatch->AddLine(corners[1], corners[2], color, color); - primitiveBatch->AddLine(corners[2], corners[3], color, color); - primitiveBatch->AddLine(corners[3], corners[0], color, color); - primitiveBatch->AddLine(corners[4], corners[5], color, color); - primitiveBatch->AddLine(corners[5], corners[6], color, color); - primitiveBatch->AddLine(corners[6], corners[7], color, color); - primitiveBatch->AddLine(corners[7], corners[4], color, color); - primitiveBatch->AddLine(corners[0], corners[4], color, color); - primitiveBatch->AddLine(corners[1], corners[5], color, color); - primitiveBatch->AddLine(corners[2], corners[6], color, color); - primitiveBatch->AddLine(corners[3], corners[7], color, color); - - } - - void PrimitiveBatchWrapper::RenderLineFrustum(Volume::Frustum frustum, glm::vec3 color, bool depthTest) { - - auto corners = frustum.GetCorners(); - if (corners.empty()) - return; - - auto& primitiveBatch = depthTest ? primitiveBatchDepthTest : primitiveBatchNoDepthTest; - - primitiveBatch->AddLine(corners[0], corners[1], color, color); - primitiveBatch->AddLine(corners[2], corners[3], color, color); - primitiveBatch->AddLine(corners[0], corners[2], color, color); - primitiveBatch->AddLine(corners[1], corners[3], color, color); - primitiveBatch->AddLine(corners[4], corners[5], color, color); - primitiveBatch->AddLine(corners[6], corners[7], color, color); - primitiveBatch->AddLine(corners[4], corners[6], color, color); - primitiveBatch->AddLine(corners[5], corners[7], color, color); - primitiveBatch->AddLine(corners[0], corners[4], color, color); - primitiveBatch->AddLine(corners[1], corners[5], color, color); - primitiveBatch->AddLine(corners[2], corners[6], color, color); - primitiveBatch->AddLine(corners[3], corners[7], color, color); - - } - - void PrimitiveBatchWrapper::RenderLineSphere(vec3 position, float radius, vec3 color, bool depthTest) { - - const int32_t verticalSubdivs = 20; - const int32_t horizontalSubdivs = 20; - - auto& primitiveBatch = depthTest ? primitiveBatchDepthTest : primitiveBatchNoDepthTest; - - vec3 lastPoint; - - float alpha = 0.0f; - - for (int32_t i = 0; i < horizontalSubdivs; i++) { - - float ringRadius = sinf(alpha); - float ringHeight = cosf(alpha); - float beta = 0.0f; - - for (int32_t j = 0; j < verticalSubdivs; j++) { - - float x = sinf(beta) * ringRadius; - float z = cosf(beta) * ringRadius; - auto point = vec3(x, ringHeight, z) * radius + position; - - if (j > 0) { - primitiveBatch->AddLine(point, lastPoint, color, color); - } - - beta += 2.0f * glm::pi() / float(verticalSubdivs - 1); - - lastPoint = point; - - } - - alpha += glm::pi() / float(horizontalSubdivs); - - } - - } - - void PrimitiveBatchWrapper::RenderLineRectangle(const Volume::Rectangle& rect, vec3 color, bool depthTest) { - - auto point = rect.point; - auto right = rect.s0; - auto down = rect.s1; - - auto& primitiveBatch = depthTest ? primitiveBatchDepthTest : primitiveBatchNoDepthTest; - - primitiveBatch->AddLine(point, point + right, color, color); - primitiveBatch->AddLine(point, point + down, color, color); - primitiveBatch->AddLine(point + right, point + right + down, color, color); - primitiveBatch->AddLine(point + down, point + right + down, color, color); + return depthTest ? primitiveBatchDepthTest : primitiveBatchNoDepthTest; } diff --git a/src/editor/tools/PrimitiveBatchWrapper.h b/src/editor/tools/PrimitiveBatchWrapper.h index 43a99f090..48a133127 100644 --- a/src/editor/tools/PrimitiveBatchWrapper.h +++ b/src/editor/tools/PrimitiveBatchWrapper.h @@ -1,26 +1,16 @@ #pragma once #include "renderer/PrimitiveBatch.h" -#include "volume/AABB.h" -#include "volume/Frustum.h" -#include "volume/Rectangle.h" namespace Atlas::Editor { + // Debug lines of the viewport, drawn with and without depth test class PrimitiveBatchWrapper { public: PrimitiveBatchWrapper(); - void RenderLine(vec3 p0, vec3 p1, vec3 color, bool depthTest); - - void RenderLineAABB(Volume::AABB aabb, vec3 color, bool depthTest); - - void RenderLineFrustum(Volume::Frustum frustum, vec3 color, bool depthTest); - - void RenderLineSphere(vec3 point, float radius, vec3 color, bool depthTest); - - void RenderLineRectangle(const Volume::Rectangle& rect, vec3 color, bool depthTest); + const Ref& GetBatch(bool depthTest) const; void Clear(); diff --git a/src/editor/tools/TerrainGenerator.cpp b/src/editor/tools/TerrainGenerator.cpp index 967aab251..923a8f832 100644 --- a/src/editor/tools/TerrainGenerator.cpp +++ b/src/editor/tools/TerrainGenerator.cpp @@ -331,16 +331,16 @@ namespace Atlas::Editor { if (ImGui::Button("Generate", ImVec2(width, 0.0f))) { if (name.empty()) { - Notifications::Push({ "Terrain name is missing!", vec3(1.0f, 0.0f, 0.0f) }); + Notifications::Push({ "Terrain name is missing!", NotificationType::Error }); } else if (!materials.size() && advanced) { - Notifications::Push({ "At least one material is required!", vec3(1.0f, 0.0f, 0.0f) }); + Notifications::Push({ "At least one material is required!", NotificationType::Error }); } else if (!selectedMaterial.IsLoaded() && !advanced) { - Notifications::Push({ "At least one material is required!", vec3(1.0f, 0.0f, 0.0f) }); + Notifications::Push({ "At least one material is required!", NotificationType::Error }); } else if (heightMapSelection && (!heightMap.IsLoaded() || !heightMapImage->HasData())) { - Notifications::Push({ "No heightmap loaded!", vec3(1.0f, 0.0f, 0.0f) }); + Notifications::Push({ "No heightmap loaded!", NotificationType::Error }); } else { Singletons::blockingOperation->Block("Generating terrain. Please wait...", [&]() { @@ -434,7 +434,7 @@ namespace Atlas::Editor { float heightD = (float)heightImg.SampleBilinear(x, y - yTex).r * scale / 65535.0f; float heightU = (float)heightImg.SampleBilinear(x, y + yTex).r * scale / 65535.0f; - auto normal = glm::normalize(glm::vec3(heightL - heightR, 1.0f, + auto normal = glm::normalize(vec3(heightL - heightR, 1.0f, heightD - heightU)); height = (float)heightImg.SampleBilinear(x, y).r / 65535.0f; @@ -623,7 +623,9 @@ namespace Atlas::Editor { [previewHeightImg = *previewHeightImg, previewMoistureImg = *previewMoistureImg, previewBiomeImg = *previewBiomeImg, biomes = biomes, heightAmplitudes = heightAmplitudes, moistureAmplitudes = moistureAmplitudes, heightSeed = heightSeed, moistureSeed = moistureSeed, - heightExp = heightExp, heightMapImage = heightMapImage, heightMapSelection = heightMapSelection, this](JobData&) mutable { + heightExp = heightExp, heightMapImage = heightMapImage, heightMapSelection = heightMapSelection, + // The interface changes the members while the job runs + materials = materials, selectedMaterial = selectedMaterial, height = height, this](JobData&) mutable { if (heightMapSelection == 0 || !heightMapImage) { Common::NoiseGenerator::GeneratePerlinNoise2D(previewHeightImg, heightAmplitudes, @@ -636,8 +638,8 @@ namespace Atlas::Editor { for (int32_t x = 0; x < previewHeightImg.width; x++) { auto fx = float(x) / float(previewBiomeImg.width); auto fy = float(y) / float(previewBiomeImg.height); - auto height = heightMapImage->SampleBilinear(fx, fy).r; - previewHeightImg.SetData(x, y, 0, height); + auto sampledHeight = heightMapImage->SampleBilinear(fx, fy).r; + previewHeightImg.SetData(x, y, 0, sampledHeight); } } @@ -657,7 +659,7 @@ namespace Atlas::Editor { previewMoistureImg, height); std::pair, vec3> pair; - if (biome.materialIdx < 0) { + if (biome.materialIdx < 0 || biome.materialIdx >= int32_t(materials.size())) { // Try to use the default material for (auto mat : materials) { if (mat.first == selectedMaterial) { diff --git a/src/editor/tools/VegetationGenerator.cpp b/src/editor/tools/VegetationGenerator.cpp index 64d3f5d29..c56374f8a 100644 --- a/src/editor/tools/VegetationGenerator.cpp +++ b/src/editor/tools/VegetationGenerator.cpp @@ -74,16 +74,13 @@ namespace Atlas::Editor { type.entities.clear(); type.instances.clear(); - auto rootEntity = scene->GetEntityByName("Root"); + auto rootEntity = scene->GetRootEntity(); Scene::Entity parentEntity = scene->CreateEntity(); parentEntity.AddComponent(); parentEntity.AddComponent(type.name + " Generated"); - if (rootEntity.IsValid() && rootEntity.HasComponent()) { - auto& hierarchy = rootEntity.GetComponent(); - hierarchy.AddChild(parentEntity); - } + parentEntity.SetParent(rootEntity); type.parentEntity = parentEntity; @@ -97,7 +94,6 @@ namespace Atlas::Editor { Scene::Entity sourceEntity(type.entity, &scene->entityManager); Scene::Entity parentEntity(type.parentEntity, &scene->entityManager); - auto& hierachy = parentEntity.GetComponent(); const float alignmentLimit = glm::half_pi() - type.maxAlignmentAngle; @@ -125,8 +121,8 @@ namespace Atlas::Editor { N = glm::euclidean(vec2(spherical.x, spherical.y)); } - glm::vec3 up = glm::vec3(0.0f, 1.0f, 0.0f); - glm::quat rotation = glm::rotation(up, glm::normalize(N)); + vec3 up = vec3(0.0f, 1.0f, 0.0f); + quat rotation = glm::rotation(up, glm::normalize(N)); rot = glm::toMat4(rotation) * glm::rotate(instance.rotation, up); } @@ -144,7 +140,7 @@ namespace Atlas::Editor { type.entities.push_back(entity); - hierachy.AddChild(Scene::Entity(entity, &scene->entityManager)); + entity.SetParent(parentEntity); } @@ -202,7 +198,7 @@ namespace Atlas::Editor { instance.scale = glm::mix(type.scaleMin, type.scaleMax, GenerateUniformRandom(randGenerator)); if (type.excludeBasedOnCorners && mesh.IsLoaded()) { - glm::mat4 transform {1.0f}; + mat4 transform {1.0f}; transform = translate(transform, instance.position); transform *= glm::rotate(instance.rotation, vec3(0.0f, 1.0f, 0.0f)); transform = glm::scale(transform, instance.scale); diff --git a/src/editor/ui/CodeEditor.cpp b/src/editor/ui/CodeEditor.cpp new file mode 100644 index 000000000..317ad8bfd --- /dev/null +++ b/src/editor/ui/CodeEditor.cpp @@ -0,0 +1,1066 @@ +#include "CodeEditor.h" +#include "../Theme.h" +#include "../Singletons.h" +#include "Widgets.h" + +#include +#include +#include +#include +#include +#include + +namespace Atlas::Editor::UI { + + bool CodeEditor::Render(const char* id, std::string& text, ImVec2 size) { + + return RenderEditor(id, text, readOnly ? nullptr : &text, size); + + } + + void CodeEditor::Render(const char* id, const std::string& text, ImVec2 size) { + + RenderEditor(id, text, nullptr, size); + + } + + void CodeEditor::Reset(const std::string& text) { + + content = text; + cursor = 0; + anchor = 0; + undoStack.clear(); + redoStack.clear(); + Tokenize(); + + } + + bool CodeEditor::IsDeactivatedAfterEdit() const { + + return deactivatedAfterEdit; + + } + + std::vector CodeEditor::FindGlslFunctions(const std::string& code) { + + std::vector functions; + + // Definitions start at the beginning of a line, e.g. "float MaterialGraphRemap(float value, ...) {" + std::string comment; + size_t lineStart = 0; + while (lineStart < code.size()) { + auto lineEnd = code.find('\n', lineStart); + if (lineEnd == std::string::npos) + lineEnd = code.size(); + auto line = code.substr(lineStart, lineEnd - lineStart); + lineStart = lineEnd + 1; + if (!line.empty() && line.back() == '\r') + line.pop_back(); + + if (line.starts_with("// ")) { + comment += (comment.empty() ? "" : " ") + line.substr(3); + continue; + } + + auto argumentsStart = line.find('('); + auto nameStart = line.rfind(' ', argumentsStart); + if (!line.empty() && std::isalpha((unsigned char)line[0]) && argumentsStart != std::string::npos && + nameStart != std::string::npos && nameStart + 1 < argumentsStart && line.ends_with(") {")) { + auto name = line.substr(nameStart + 1, argumentsStart - nameStart - 1); + auto signature = line.substr(0, line.size() - 2); + auto iter = std::find_if(functions.begin(), functions.end(), + [&](const CodeCompletion& completion) { return completion.text == name; }); + if (iter == functions.end()) + functions.push_back({ name, "Function", signature, comment }); + else if (iter->signature.find(signature) == std::string::npos) + iter->signature += "\n" + signature; + } + comment.clear(); + } + return functions; + + } + + bool CodeEditor::RenderEditor(const char* id, const std::string& text, std::string* editedText, ImVec2 size) { + + changed = false; + deactivatedAfterEdit = false; + + // Another id is another text, e.g. of another node, the editor starts again. A text set before the first render + // keeps its undo steps + auto editorId = ImGui::GetID(id); + if (editorId != lastId) { + auto prepared = lastId == 0 && content == text; + lastId = editorId; + content = text; + if (!prepared) { + cursor = 0; + anchor = 0; + undoStack.clear(); + redoStack.clear(); + } + wasFocused = false; + editedWhileFocused = false; + completionOpen = false; + Tokenize(); + } + // Text changed outside, e.g. by the undo of the window + else if (text != content) { + content = text; + cursor = std::min(cursor, int32_t(content.size())); + while (cursor > 0 && cursor < int32_t(content.size()) && (content[cursor] & 0xC0) == 0x80) + cursor--; + anchor = cursor; + undoStack.clear(); + redoStack.clear(); + completionOpen = false; + Tokenize(); + } + else if (tokenizedLanguage != int32_t(language)) { + Tokenize(); + } + + interfaceFont = ImGui::GetFont(); + ImGui::PushFont(Theme::codeFont ? Theme::codeFont : interfaceFont); + // ImGui::CalcTextSize rounds up to whole pixels, the advance of the glyphs isn't rounded + characterWidth = ImGui::GetFont()->CalcTextSizeA(ImGui::GetFontSize(), FLT_MAX, 0.0f, "M").x; + lineHeight = std::round(ImGui::GetFontSize() * 1.3f); + + auto action = std::exchange(requestedAction, Action::None); + if (editedText && action == Action::Undo) + Restore(undoStack, redoStack); + if (editedText && action == Action::Redo) + Restore(redoStack, undoStack); + if (action == Action::Search || action == Action::Replace) { + searchOpen = true; + searchFocusRequested = true; + replaceOpen = action == Action::Replace && editedText; + } + + searchMatches = searchOpen ? FindMatches() : std::vector(); + if (searchOpen) + RenderSearch(editedText != nullptr); + + auto lineCount = int32_t(lineStarts.size()); + gutterWidth = float(std::max(int32_t(std::to_string(lineCount).size()), 2) + 2) * characterWidth; + + ImGui::PushStyleColor(ImGuiCol_ChildBg, ImGui::GetStyleColorVec4(ImGuiCol_FrameBg)); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f)); + if (ImGui::BeginChild(id, size, ImGuiChildFlags_Borders, ImGuiWindowFlags_HorizontalScrollbar)) { + auto window = ImGui::GetCurrentWindow(); + auto padding = ImGui::GetStyle().FramePadding.y; + auto origin = ImGui::GetCursorScreenPos(); + auto textOrigin = ImVec2(origin.x + gutterWidth + characterWidth, origin.y + padding); + const auto& inner = window->InnerRect; + + ImGui::Dummy(ImVec2(gutterWidth + float(maxColumns + 2) * characterWidth, float(lineCount) * lineHeight + 2.0f * padding)); + + // One item over the visible area owns the mouse, otherwise dragging a selection moves the window + auto itemId = window->GetID("##Text"); + bool hovered = false, held = false; + ImGui::ItemAdd(inner, itemId); + ImGui::ButtonBehavior(inner, itemId, &hovered, &held); + HandleMouse(textOrigin, hovered, held, inner.Contains(ImGui::GetIO().MousePos)); + + auto focused = ImGui::IsWindowFocused(); + if (focused) { + auto& io = ImGui::GetIO(); + if (editedText) { + ImGui::GetCurrentContext()->WantTextInputNextFrame = 1; + io.WantTextInput = true; + } + ImGui::SetNextFrameWantCaptureKeyboard(true); + io.WantCaptureKeyboard = true; + HandleKeyboard(editedText != nullptr, inner.GetHeight()); + } + if (wasFocused && !focused && editedWhileFocused) { + deactivatedAfterEdit = true; + editedWhileFocused = false; + } + wasFocused = focused; + + if (scrollToCursor) { + auto y = padding + float(GetLine(cursor)) * lineHeight; + if (y < ImGui::GetScrollY()) + ImGui::SetScrollY(y - padding); + else if (y + lineHeight > ImGui::GetScrollY() + inner.GetHeight()) + ImGui::SetScrollY(y + lineHeight + padding - inner.GetHeight()); + auto x = float(GetColumn(cursor)) * characterWidth; + auto textWidth = inner.GetWidth() - gutterWidth - 2.0f * characterWidth; + if (x < ImGui::GetScrollX()) + ImGui::SetScrollX(std::max(0.0f, x - 4.0f * characterWidth)); + else if (x > ImGui::GetScrollX() + textWidth) + ImGui::SetScrollX(x - textWidth + 4.0f * characterWidth); + scrollToCursor = false; + } + + auto firstLine = std::max(0, int32_t((ImGui::GetScrollY() - padding) / lineHeight)); + auto lastLine = std::min(lineCount - 1, int32_t((ImGui::GetScrollY() + inner.GetHeight()) / lineHeight) + 1); + DrawLines(textOrigin, inner.Min, inner.Max, firstLine, lastLine, focused); + + if (!focused) + completionOpen = false; + auto cursorPosition = ImVec2(textOrigin.x + float(GetColumn(cursor)) * characterWidth, + textOrigin.y + float(GetLine(cursor)) * lineHeight); + if (completionOpen && inner.Contains(cursorPosition)) + RenderCompletion(ImVec2(cursorPosition.x, cursorPosition.y + lineHeight), cursorPosition.y); + } + ImGui::EndChild(); + ImGui::PopStyleVar(); + ImGui::PopStyleColor(); + ImGui::PopFont(); + + if (changed && editedText) + *editedText = content; + + return changed; + + } + + void CodeEditor::HandleMouse(ImVec2 textOrigin, bool hovered, bool held, bool mouseInside) { + + const auto& io = ImGui::GetIO(); + + if (hovered) + ImGui::SetMouseCursor(ImGuiMouseCursor_TextInput); + if (hovered && ImGui::IsMouseClicked(ImGuiMouseButton_Left)) { + auto offset = GetOffsetAt(io.MousePos, textOrigin); + if (io.MouseClickedCount[ImGuiMouseButton_Left] == 2 && IsWordCharacter(offset)) { + for (anchor = offset; IsWordCharacter(anchor - 1); anchor--); + for (cursor = offset; IsWordCharacter(cursor); cursor++); + completionOpen = false; + } + else { + MoveCursor(offset, io.KeyShift); + selecting = true; + } + blinkStart = ImGui::GetTime(); + } + if (selecting && !held) + selecting = false; + if (selecting && ImGui::IsMouseDragging(ImGuiMouseButton_Left)) { + cursor = GetOffsetAt(io.MousePos, textOrigin); + scrollToCursor = !mouseInside; + } + + } + + void CodeEditor::DrawLines(ImVec2 textOrigin, ImVec2 visibleMin, ImVec2 visibleMax, int32_t firstLine, int32_t lastLine, bool focused) { + + auto drawList = ImGui::GetWindowDrawList(); + auto cursorLine = GetLine(cursor); + auto selectionStart = std::min(cursor, anchor); + auto selectionEnd = std::max(cursor, anchor); + auto textOffset = (lineHeight - ImGui::GetFontSize()) * 0.5f; + + for (auto line = firstLine; line <= lastLine; line++) { + auto lineStart = lineStarts[line]; + auto lineEnd = GetLineEnd(line); + auto y = textOrigin.y + float(line) * lineHeight; + + if (focused && line == cursorLine && selectionStart == selectionEnd) + drawList->AddRectFilled(ImVec2(visibleMin.x, y), ImVec2(visibleMax.x, y + lineHeight), + ImGui::GetColorU32(ImGuiCol_Text, 0.05f)); + + if (searchOpen && !searchText.empty()) { + auto first = std::lower_bound(searchMatches.begin(), searchMatches.end(), lineStart); + for (auto iter = first; iter != searchMatches.end() && *iter <= lineEnd; iter++) { + auto match = *iter; + auto x0 = float(GetColumn(match)) * characterWidth; + auto x1 = float(GetColumn(std::min(match + int32_t(searchText.size()), lineEnd))) * characterWidth; + drawList->AddRectFilled(ImVec2(textOrigin.x + x0, y), ImVec2(textOrigin.x + x1, y + lineHeight), + ImGui::GetColorU32(Theme::Accent(0.3f))); + } + } + + if (selectionStart < selectionEnd && selectionStart <= lineEnd && selectionEnd >= lineStart) { + auto x0 = float(GetColumn(std::max(selectionStart, lineStart))) * characterWidth; + auto x1 = float(GetColumn(std::min(selectionEnd, lineEnd))) * characterWidth; + if (selectionEnd > lineEnd) + x1 += characterWidth * 0.5f; + drawList->AddRectFilled(ImVec2(textOrigin.x + x0, y), ImVec2(textOrigin.x + x1, y + lineHeight), + ImGui::GetColorU32(ImGuiCol_TextSelectedBg)); + } + + // Tabs are expanded, so the text is drawn in runs between them + int32_t column = 0; + auto drawText = [&](int32_t start, int32_t end, ImU32 color) { + auto runStart = start; + auto runColumn = column; + for (auto i = start; i <= end; i++) { + if (i < end && content[i] != '\t') { + if ((content[i] & 0xC0) != 0x80) + column++; + continue; + } + if (i > runStart) + drawList->AddText(ImVec2(textOrigin.x + float(runColumn) * characterWidth, y + textOffset), + color, content.data() + runStart, content.data() + i); + if (i < end) + column = (column / tabSize + 1) * tabSize; + runStart = i + 1; + runColumn = column; + } + }; + + auto defaultColor = ImGui::GetColorU32(ImGuiCol_Text); + auto position = lineStart; + for (auto i = lineTokens[line]; i < lineTokens[line + 1]; i++) { + const auto& token = tokens[i]; + drawText(position, token.start, defaultColor); + drawText(token.start, token.end, ImGui::GetColorU32(Theme::Code(int32_t(token.type)))); + position = token.end; + } + drawText(position, lineEnd, defaultColor); + } + + auto blink = std::fmod(ImGui::GetTime() - blinkStart, 1.2) < 0.8; + if (focused && blink) { + auto x = textOrigin.x + float(GetColumn(cursor)) * characterWidth; + auto y = textOrigin.y + float(cursorLine) * lineHeight; + drawList->AddLine(ImVec2(x, y), ImVec2(x, y + lineHeight), ImGui::GetColorU32(ImGuiCol_Text), 1.5f); + } + + // The gutter covers the text that is scrolled to the left + drawList->AddRectFilled(visibleMin, ImVec2(visibleMin.x + gutterWidth, visibleMax.y), ImGui::GetColorU32(ImGuiCol_FrameBg)); + for (auto line = firstLine; line <= lastLine; line++) { + auto number = std::to_string(line + 1); + auto x = visibleMin.x + gutterWidth - float(number.size() + 1) * characterWidth; + auto color = line == cursorLine ? ImGui::GetColorU32(ImGuiCol_Text) : ImGui::GetColorU32(Theme::TextMuted(0.7f)); + drawList->AddText(ImVec2(x, textOrigin.y + float(line) * lineHeight + textOffset), color, number.c_str()); + } + + } + + void CodeEditor::Tokenize() { + + auto isGLSL = language == CodeLanguage::GLSL; + auto size = int32_t(content.size()); + + lineStarts = { 0 }; + maxColumns = 0; + for (int32_t i = 0; i < size; i++) { + if (content[i] == '\n') + lineStarts.push_back(i + 1); + } + for (int32_t line = 0; line < int32_t(lineStarts.size()); line++) + maxColumns = std::max(maxColumns, GetColumn(GetLineEnd(line))); + + tokens.clear(); + auto findEnd = [&](int32_t from, std::string_view end) { + auto position = content.find(end, from); + return position == std::string::npos ? size : int32_t(position + end.size()); + }; + auto lineEndFrom = [&](int32_t from) { + auto position = content.find('\n', from); + return position == std::string::npos ? size : int32_t(position); + }; + + auto lineBegin = true; + for (int32_t i = 0; i < size;) { + auto c = content[i]; + auto next = i + 1 < size ? content[i + 1] : '\0'; + if (c == '\n' || std::isspace(uint8_t(c))) { + lineBegin |= c == '\n'; + i++; + continue; + } + + auto start = i; + if (isGLSL && lineBegin && c == '#') { + i = lineEndFrom(i); + AddToken(start, i, TokenType::Preprocessor); + } + else if ((isGLSL && c == '/' && next == '/') || (!isGLSL && c == '-' && next == '-')) { + auto block = !isGLSL && content.compare(i + 2, 2, "[[") == 0; + i = block ? findEnd(i + 4, "]]") : lineEndFrom(i); + AddToken(start, i, TokenType::Comment); + } + else if (isGLSL && c == '/' && next == '*') { + i = findEnd(i + 2, "*/"); + AddToken(start, i, TokenType::Comment); + } + else if (c == '"' || (!isGLSL && c == '\'')) { + for (i++; i < size && content[i] != c && content[i] != '\n'; i++) + i += content[i] == '\\' ? 1 : 0; + i = std::min(i + 1, size); + AddToken(start, i, TokenType::String); + } + else if (!isGLSL && c == '[' && next == '[') { + i = findEnd(i + 2, "]]"); + AddToken(start, i, TokenType::String); + } + else if (std::isdigit(uint8_t(c)) || (c == '.' && std::isdigit(uint8_t(next)))) { + for (i++; i < size; i++) { + auto d = content[i]; + auto exponentSign = (d == '+' || d == '-') && (content[i - 1] == 'e' || content[i - 1] == 'E'); + if (!std::isalnum(uint8_t(d)) && d != '.' && !exponentSign) + break; + } + AddToken(start, i, TokenType::Number); + } + else if (std::isalpha(uint8_t(c)) || c == '_') { + while (i < size && (std::isalnum(uint8_t(content[i])) || content[i] == '_')) + i++; + auto word = std::string_view(content).substr(start, i - start); + auto contains = [&](const auto& words) { + return std::find(std::begin(words), std::end(words), word) != std::end(words); + }; + if (isGLSL ? contains(glslKeywords) : contains(luaKeywords)) + AddToken(start, i, TokenType::Keyword); + else if (isGLSL && contains(glslTypes)) + AddToken(start, i, TokenType::Type); + else if (isGLSL ? (contains(glslBuiltins) || word.starts_with("gl_")) : contains(luaBuiltins)) + AddToken(start, i, TokenType::Builtin); + } + else { + i++; + } + lineBegin = false; + } + + // Index of the first token of each line, the last entry ends the last line + auto lineCount = int32_t(lineStarts.size()); + lineTokens.resize(lineCount + 1); + int32_t token = 0; + for (int32_t line = 0; line < lineCount; line++) { + lineTokens[line] = token; + while (token < int32_t(tokens.size()) && tokens[token].start <= GetLineEnd(line)) + token++; + } + lineTokens[lineCount] = token; + + tokenizedLanguage = int32_t(language); + + } + + void CodeEditor::AddToken(int32_t start, int32_t end, TokenType type) { + + // Tokens never span lines, such that each line can be drawn on its own + while (start < end) { + auto lineEnd = std::min(GetLineEnd(GetLine(start)), end); + if (lineEnd > start) + tokens.push_back({ start, lineEnd, type }); + start = lineEnd + 1; + } + + } + + void CodeEditor::HandleKeyboard(bool canEdit, float visibleHeight) { + + auto& io = ImGui::GetIO(); + auto isOsx = io.ConfigMacOSXBehaviors; + auto wordMove = isOsx ? io.KeyAlt : io.KeyCtrl; + auto startEnd = isOsx && io.KeyCtrl && !io.KeyAlt; + auto shortcut = io.KeyCtrl && !io.KeyAlt; + auto shift = io.KeyShift; + + auto line = GetLine(cursor); + auto lineStart = lineStarts[line]; + auto selectionStart = std::min(cursor, anchor); + auto selectionEnd = std::max(cursor, anchor); + auto hasSelection = selectionStart != selectionEnd; + + if (completionOpen && (hasSelection || completionStart > cursor)) + completionOpen = false; + if (completionOpen && HandleCompletionKeys(canEdit)) + return; + // Edits keep the suggestions open, e.g. a deleted character only changes the filter + auto completionWasOpen = completionOpen; + + auto moveLines = [&](int32_t lines) { + auto column = preferredColumn >= 0 ? preferredColumn : GetColumn(cursor); + auto target = line + lines; + auto offset = target < 0 ? 0 : target >= int32_t(lineStarts.size()) ? int32_t(content.size()) : + GetOffset(target, column); + MoveCursor(offset, shift); + preferredColumn = column; + }; + + if (ImGui::IsKeyPressed(ImGuiKey_LeftArrow)) { + if (hasSelection && !shift) + MoveCursor(selectionStart, false); + else + MoveCursor(startEnd ? lineStart : wordMove ? GetWordBoundary(cursor, -1) : std::max(cursor - 1, 0), shift); + } + else if (ImGui::IsKeyPressed(ImGuiKey_RightArrow)) { + if (hasSelection && !shift) + MoveCursor(selectionEnd, false); + else + MoveCursor(startEnd ? GetLineEnd(line) : wordMove ? GetWordBoundary(cursor, 1) : + std::min(cursor + 1, int32_t(content.size())), shift); + } + else if (ImGui::IsKeyPressed(ImGuiKey_UpArrow)) + startEnd ? MoveCursor(0, shift) : moveLines(-1); + else if (ImGui::IsKeyPressed(ImGuiKey_DownArrow)) + startEnd ? MoveCursor(int32_t(content.size()), shift) : moveLines(1); + else if (ImGui::IsKeyPressed(ImGuiKey_PageUp)) + moveLines(-int32_t(visibleHeight / lineHeight)); + else if (ImGui::IsKeyPressed(ImGuiKey_PageDown)) + moveLines(int32_t(visibleHeight / lineHeight)); + else if (ImGui::IsKeyPressed(ImGuiKey_Home)) + MoveCursor(io.KeyCtrl ? 0 : lineStart, shift); + else if (ImGui::IsKeyPressed(ImGuiKey_End)) + MoveCursor(io.KeyCtrl ? int32_t(content.size()) : GetLineEnd(line), shift); + else if (ImGui::IsKeyPressed(ImGuiKey_Escape)) { + anchor = cursor; + searchOpen = false; + } + else if (shortcut && (ImGui::IsKeyPressed(ImGuiKey_F) || ImGui::IsKeyPressed(ImGuiKey_H))) { + // A selection within a line is searched for + if (hasSelection && content.find('\n', selectionStart) >= size_t(selectionEnd)) + searchText = content.substr(selectionStart, selectionEnd - selectionStart); + searchOpen = true; + searchFocusRequested = true; + replaceOpen = canEdit && ImGui::IsKeyPressed(ImGuiKey_H); + } + else if (ImGui::IsKeyPressed(ImGuiKey_F3) && !searchText.empty()) { + FindNext(!shift); + } + else if (shortcut && ImGui::IsKeyPressed(ImGuiKey_A)) { + anchor = 0; + cursor = int32_t(content.size()); + completionOpen = false; + } + else if (shortcut && hasSelection && (ImGui::IsKeyPressed(ImGuiKey_C) || ImGui::IsKeyPressed(ImGuiKey_X))) { + ImGui::SetClipboardText(content.substr(selectionStart, selectionEnd - selectionStart).c_str()); + if (canEdit && ImGui::IsKeyPressed(ImGuiKey_X)) + Replace(selectionStart, selectionEnd, "", false); + } + + if (!canEdit) + return; + + if (shortcut && ImGui::IsKeyPressed(ImGuiKey_V)) { + std::string value = ImGui::GetClipboardText() ? ImGui::GetClipboardText() : ""; + std::erase(value, '\r'); + Replace(selectionStart, selectionEnd, value, false); + } + else if (shortcut && ImGui::IsKeyPressed(ImGuiKey_Z)) + shift ? Restore(redoStack, undoStack) : Restore(undoStack, redoStack); + else if (shortcut && ImGui::IsKeyPressed(ImGuiKey_Y)) + Restore(redoStack, undoStack); + else if (ImGui::IsKeyPressed(ImGuiKey_Enter) || ImGui::IsKeyPressed(ImGuiKey_KeypadEnter)) { + // The new line keeps the indentation + auto indentation = lineStart; + while (indentation < selectionStart && (content[indentation] == ' ' || content[indentation] == '\t')) + indentation++; + Replace(selectionStart, selectionEnd, "\n" + content.substr(lineStart, indentation - lineStart), false); + } + else if (ImGui::IsKeyPressed(ImGuiKey_Tab)) { + auto spaces = tabSize - GetColumn(selectionStart) % tabSize; + Replace(selectionStart, selectionEnd, std::string(spaces, ' '), false); + } + else if (ImGui::IsKeyPressed(ImGuiKey_Backspace)) { + auto start = hasSelection ? selectionStart : startEnd ? lineStart : wordMove ? GetWordBoundary(cursor, -1) : cursor - 1; + while (!hasSelection && start > 0 && (content[start] & 0xC0) == 0x80) + start--; + if (start >= 0) + Replace(start, selectionEnd, "", !hasSelection); + } + else if (ImGui::IsKeyPressed(ImGuiKey_Delete)) { + auto end = hasSelection ? selectionEnd : wordMove ? GetWordBoundary(cursor, 1) : cursor + 1; + while (end < int32_t(content.size()) && (content[end] & 0xC0) == 0x80) + end++; + if (end <= int32_t(content.size())) + Replace(selectionStart, end, "", !hasSelection); + } + + auto ignoreCharacters = (io.KeyCtrl && !io.KeyAlt) || (isOsx && io.KeyCtrl); + auto completionRequested = shortcut && ImGui::IsKeyPressed(ImGuiKey_Space); + for (auto character : io.InputQueueCharacters) { + if (ignoreCharacters || character < 32 || character == 127) + continue; + char buffer[5] = {}; + ImTextCharToUtf8(buffer, character); + Replace(std::min(cursor, anchor), std::max(cursor, anchor), buffer, true); + // Words and members are completed while they are typed + completionRequested = character >= 128 || std::isalnum(int(character)) || character == '_' || character == '.' || character == ':'; + } + io.InputQueueCharacters.resize(0); + + if (completionRequested || (completionWasOpen && changed)) + UpdateCompletion(); + + } + + bool CodeEditor::HandleCompletionKeys(bool canEdit) { + + auto& io = ImGui::GetIO(); + if (!io.KeyShift && ImGui::IsKeyPressed(ImGuiKey_DownArrow)) { + completionIndex = (completionIndex + 1) % int32_t(completions.size()); + completionChosen = true; + return true; + } + if (!io.KeyShift && ImGui::IsKeyPressed(ImGuiKey_UpArrow)) { + completionIndex = (completionIndex + int32_t(completions.size()) - 1) % int32_t(completions.size()); + completionChosen = true; + return true; + } + if (ImGui::IsKeyPressed(ImGuiKey_Escape)) { + completionOpen = false; + return true; + } + // Enter at the end of a word is a new line, unless a suggestion was chosen with the arrows + auto enter = ImGui::IsKeyPressed(ImGuiKey_Enter) || ImGui::IsKeyPressed(ImGuiKey_KeypadEnter); + if (canEdit && ((enter && completionChosen) || ImGui::IsKeyPressed(ImGuiKey_Tab))) { + Replace(completionStart, cursor, completions[completionIndex].text, false); + completionOpen = false; + return true; + } + return false; + + } + + void CodeEditor::UpdateCompletion() { + + // The word in front of the cursor and, after a . or :, the expression it belongs to + CodeCompletionContext context; + completionStart = cursor; + while (IsWordCharacter(completionStart - 1)) + completionStart--; + context.prefix = content.substr(completionStart, cursor - completionStart); + if (completionStart > 0 && (content[completionStart - 1] == '.' || content[completionStart - 1] == ':')) { + context.separator = content[completionStart - 1]; + // The whole expression with calls and indices, e.g. scene:GetMainCamera() or children[i + 1] + auto qualifierStart = completionStart - 1; + while (qualifierStart > 0) { + auto c = content[qualifierStart - 1]; + if (c == ')' || c == ']') { + auto open = c == ')' ? '(' : '['; + auto depth = 0; + auto i = qualifierStart - 1; + for (; i >= 0; i--) { + depth += content[i] == c ? 1 : content[i] == open ? -1 : 0; + if (depth == 0) + break; + } + if (i < 0) + break; + qualifierStart = i; + continue; + } + if (!IsWordCharacter(qualifierStart - 1) && c != '.' && c != ':') + break; + qualifierStart--; + } + context.qualifier = content.substr(qualifierStart, completionStart - 1 - qualifierStart); + context.text = std::string_view(content).substr(0, qualifierStart); + } + + completions.clear(); + completionOpen = false; + if (context.prefix.empty() && !context.separator) + return; + + auto candidates = completionProvider ? completionProvider(context) : std::vector(); + if (!context.separator) { + auto addWords = [&](const auto& words, const char* kind) { + for (const auto& word : words) + candidates.push_back({ std::string(word), kind }); + }; + if (language == CodeLanguage::GLSL) { + addWords(glslKeywords, "Keyword"); + addWords(glslTypes, "Type"); + addWords(glslBuiltins, "Function"); + } + else { + addWords(luaKeywords, "Keyword"); + addWords(luaBuiltins, "Builtin"); + } + + // Names in the text, e.g. local variables, except the word being typed + std::unordered_set words; + for (int32_t i = 0; i < int32_t(content.size());) { + if (!IsWordCharacter(i) || std::isdigit((unsigned char)content[i])) { + i++; + continue; + } + auto start = i; + while (IsWordCharacter(i)) + i++; + if (start != completionStart && i - start > 1) + words.insert(std::string_view(content).substr(start, i - start)); + } + for (auto word : words) + candidates.push_back({ std::string(word), "Word" }); + } + + // Case doesn't matter while typing, an exactly typed word needs no suggestion + auto startsWith = [&](const std::string& text) { + return text.size() >= context.prefix.size() && std::equal(context.prefix.begin(), context.prefix.end(), text.begin(), + [](char a, char b) { return std::tolower((unsigned char)a) == std::tolower((unsigned char)b); }); + }; + for (auto& candidate : candidates) { + if (candidate.text != context.prefix && startsWith(candidate.text)) + completions.push_back(std::move(candidate)); + } + std::stable_sort(completions.begin(), completions.end(), + [](const CodeCompletion& a, const CodeCompletion& b) { return a.text < b.text; }); + completions.erase(std::unique(completions.begin(), completions.end(), + [](const CodeCompletion& a, const CodeCompletion& b) { return a.text == b.text; }), completions.end()); + + completionIndex = 0; + completionChosen = false; + completionOpen = !completions.empty(); + + } + + void CodeEditor::RenderCompletion(ImVec2 position, float lineTop) { + + const int32_t visibleCount = 8; + const float padding = 6.0f; + const float rowPadding = 3.0f; + + auto first = std::clamp(completionIndex - visibleCount / 2, 0, std::max(int32_t(completions.size()) - visibleCount, 0)); + auto last = std::min(first + visibleCount, int32_t(completions.size())); + + // As wide as the visible suggestions with their kinds, but not wider than a comfortable reading width + auto kindWidth = [&](const std::string& kind) { + ImGui::PushFont(interfaceFont); + auto width = ImGui::CalcTextSize(kind.c_str()).x; + ImGui::PopFont(); + return width; + }; + auto contentWidth = ImGui::GetFontSize() * 16.0f; + for (auto i = first; i < last; i++) + contentWidth = std::max(contentWidth, ImGui::CalcTextSize(completions[i].text.c_str()).x + + kindWidth(completions[i].kind) + 4.0f * padding); + contentWidth = std::min(contentWidth, ImGui::GetFontSize() * 28.0f); + + // Inside the window, above the line if there is no room below it + auto viewport = ImGui::GetMainViewport(); + auto width = contentWidth + 2.0f * padding; + position.x = std::max(viewport->WorkPos.x, std::min(position.x, viewport->WorkPos.x + viewport->WorkSize.x - width)); + auto rowHeight = ImGui::GetTextLineHeight() + 2.0f * rowPadding; + auto height = std::max(completionHeight, float(last - first) * rowHeight + 2.0f * padding); + if (position.y + height > viewport->WorkPos.y + viewport->WorkSize.y) + position.y = lineTop - height; + + // Looks like a tooltip but isn't one, other tooltips would be added to it or hide it + const auto flags = ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_AlwaysAutoResize | + ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoNav | + ImGuiWindowFlags_NoDocking; + const auto& style = ImGui::GetStyle(); + ImGui::SetNextWindowPos(position); + ImGui::PushStyleColor(ImGuiCol_WindowBg, style.Colors[ImGuiCol_PopupBg]); + ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, style.PopupRounding); + ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, style.PopupBorderSize); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(padding, padding)); + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0.0f, 0.0f)); + auto open = ImGui::Begin("##CodeCompletion", nullptr, flags); + ImGui::PopStyleVar(4); + ImGui::PopStyleColor(); + ImGui::BringWindowToDisplayFront(ImGui::GetCurrentWindow()); + if (!open) { + ImGui::End(); + return; + } + + auto drawList = ImGui::GetWindowDrawList(); + for (auto i = first; i < last; i++) { + const auto& completion = completions[i]; + auto min = ImGui::GetCursorScreenPos(); + auto max = ImVec2(min.x + contentWidth, min.y + rowHeight); + if (i == completionIndex) + drawList->AddRectFilled(min, max, ImGui::GetColorU32(Theme::Accent(0.35f)), 4.0f); + + auto kindX = max.x - padding - kindWidth(completion.kind); + drawList->PushClipRect(min, ImVec2(kindX - padding, max.y), true); + drawList->AddText(ImVec2(min.x + padding, min.y + rowPadding), ImGui::GetColorU32(ImGuiCol_Text), completion.text.c_str()); + drawList->PopClipRect(); + + ImGui::PushFont(interfaceFont); + auto kindY = min.y + (rowHeight - ImGui::GetFontSize()) * 0.5f; + drawList->AddText(ImVec2(kindX, kindY), ImGui::GetColorU32(Theme::TextMuted()), completion.kind.c_str()); + ImGui::PopFont(); + + ImGui::Dummy(ImVec2(contentWidth, rowHeight)); + } + + const auto& selected = completions[completionIndex]; + if (!selected.signature.empty() || !selected.description.empty()) { + ImGui::Dummy(ImVec2(0.0f, padding)); + ImGui::Separator(); + ImGui::Dummy(ImVec2(0.0f, padding)); + ImGui::PushTextWrapPos(ImGui::GetCursorPosX() + contentWidth); + if (!selected.signature.empty()) + ImGui::TextUnformatted(selected.signature.c_str()); + if (!selected.description.empty()) { + ImGui::PushFont(interfaceFont); + ImGui::TextColored(Theme::TextMuted(), "%s", selected.description.c_str()); + ImGui::PopFont(); + } + ImGui::PopTextWrapPos(); + } + + completionHeight = ImGui::GetWindowHeight(); + ImGui::End(); + + } + + void CodeEditor::Replace(int32_t start, int32_t end, const std::string& value, bool mergeUndo) { + + if (start == end && value.empty()) + return; + + // Typing within a second becomes one undo step + auto time = ImGui::GetTime(); + if (!mergeUndo || time - lastEditTime > 1.0 || undoStack.empty()) + undoStack.push_back({ content, cursor }); + if (undoStack.size() > 200) + undoStack.erase(undoStack.begin()); + redoStack.clear(); + lastEditTime = mergeUndo ? time : 0.0; + + content.replace(start, end - start, value); + Tokenize(); + MoveCursor(start + int32_t(value.size()), false); + changed = true; + editedWhileFocused = true; + + } + + void CodeEditor::Restore(std::vector& from, std::vector& to) { + + if (from.empty()) + return; + + to.push_back({ content, cursor }); + auto snapshot = from.back(); + from.pop_back(); + content = snapshot.text; + Tokenize(); + MoveCursor(std::min(snapshot.cursor, int32_t(content.size())), false); + lastEditTime = 0.0; + changed = true; + editedWhileFocused = true; + + } + + void CodeEditor::MoveCursor(int32_t offset, bool select) { + + // Never end up within a multi byte character + while (offset > 0 && offset < int32_t(content.size()) && (content[offset] & 0xC0) == 0x80) + offset += offset > cursor ? 1 : -1; + + cursor = offset; + if (!select) + anchor = offset; + preferredColumn = -1; + completionOpen = false; + scrollToCursor = true; + blinkStart = ImGui::GetTime(); + + } + + int32_t CodeEditor::GetLine(int32_t offset) const { + + return int32_t(std::upper_bound(lineStarts.begin(), lineStarts.end(), offset) - lineStarts.begin()) - 1; + + } + + int32_t CodeEditor::GetLineEnd(int32_t line) const { + + return line + 1 < int32_t(lineStarts.size()) ? lineStarts[line + 1] - 1 : int32_t(content.size()); + + } + + int32_t CodeEditor::GetColumn(int32_t offset) const { + + int32_t column = 0; + for (auto i = lineStarts[GetLine(offset)]; i < offset; i++) { + if (content[i] == '\t') + column = (column / tabSize + 1) * tabSize; + else if ((content[i] & 0xC0) != 0x80) + column++; + } + return column; + + } + + int32_t CodeEditor::GetOffset(int32_t line, int32_t column) const { + + auto end = GetLineEnd(line); + int32_t current = 0; + for (auto i = lineStarts[line]; i < end; i++) { + if ((content[i] & 0xC0) == 0x80) + continue; + auto next = content[i] == '\t' ? (current / tabSize + 1) * tabSize : current + 1; + if (column < next) + return 2 * (column - current) <= next - current ? i : i + 1; + current = next; + } + return end; + + } + + int32_t CodeEditor::GetOffsetAt(ImVec2 position, ImVec2 textOrigin) const { + + auto line = std::clamp(int32_t(std::floor((position.y - textOrigin.y) / lineHeight)), 0, int32_t(lineStarts.size()) - 1); + auto column = std::max(0, int32_t(std::round((position.x - textOrigin.x) / characterWidth))); + return GetOffset(line, column); + + } + + int32_t CodeEditor::GetWordBoundary(int32_t offset, int32_t direction) const { + + // Skips the spaces and symbols up to the next word and then the word + auto at = direction < 0 ? -1 : 0; + while (offset + at >= 0 && offset + at < int32_t(content.size()) && !IsWordCharacter(offset + at)) + offset += direction; + while (IsWordCharacter(offset + at)) + offset += direction; + return offset; + + } + + void CodeEditor::RenderSearch(bool canEdit) { + + auto& io = ImGui::GetIO(); + const auto& style = ImGui::GetStyle(); + auto matches = int32_t(searchMatches.size()); + auto countText = std::to_string(matches) + (matches == 1 ? " match" : " matches"); + + ImGui::PushFont(interfaceFont); + auto buttonWidth = [&](const char* label) { return ImGui::CalcTextSize(label).x + 2.0f * style.FramePadding.x; }; + auto iconWidth = ImGui::GetTextLineHeight() + 2.0f * style.FramePadding.x; + auto rightWidth = ImGui::CalcTextSize(countText.c_str()).x + 3.0f * iconWidth + (canEdit ? buttonWidth("Replace") : 0.0f) + + (canEdit ? 5.0f : 4.0f) * style.ItemSpacing.x; + + ImGui::SetNextItemWidth(-rightWidth); + if (searchFocusRequested) { + ImGui::SetKeyboardFocusHere(); + searchFocusRequested = false; + } + if (ImGui::InputTextWithHint("##Search", "Search...", &searchText, ImGuiInputTextFlags_EnterReturnsTrue)) { + FindNext(!io.KeyShift); + // Enter takes the focus from the field, the next match follows with the next Enter + ImGui::SetKeyboardFocusHere(-1); + } + if (ImGui::IsItemActive() && ImGui::IsKeyPressed(ImGuiKey_Escape)) + searchOpen = false; + + ImGui::SameLine(); + ImGui::AlignTextToFramePadding(); + ImGui::TextColored(Theme::TextMuted(), "%s", countText.c_str()); + ImGui::SameLine(); + if (Widgets::ToolbarIconButton("Previous match", Singletons::icons->Get(IconType::ArrowUp), "Previous match (Shift+F3)")) + FindNext(false); + ImGui::SameLine(); + if (Widgets::ToolbarIconButton("Next match", Singletons::icons->Get(IconType::ArrowDown), "Next match (F3)")) + FindNext(true); + if (canEdit) { + ImGui::SameLine(); + if (replaceOpen) + Theme::PushPrimaryButton(); + auto toggled = ImGui::Button("Replace"); + if (replaceOpen) + Theme::PopPrimaryButton(); + ImGui::SetItemTooltip("Replace (Ctrl+H)"); + if (toggled) + replaceOpen = !replaceOpen; + } + ImGui::SameLine(); + if (Widgets::ToolbarIconButton("Close search", Singletons::icons->Get(IconType::Close), "Close (Esc)")) + searchOpen = false; + + if (canEdit && replaceOpen) { + ImGui::SetNextItemWidth(-(buttonWidth("Replace") + buttonWidth("Replace all") + 2.0f * style.ItemSpacing.x)); + ImGui::InputTextWithHint("##Replace", "Replace with...", &replaceText); + ImGui::SameLine(); + ImGui::BeginDisabled(matches == 0); + if (ImGui::Button("Replace")) + ReplaceMatch(false); + ImGui::SameLine(); + if (ImGui::Button("Replace all")) + ReplaceMatch(true); + ImGui::EndDisabled(); + } + ImGui::PopFont(); + + } + + void CodeEditor::ReplaceMatch(bool all) { + + auto matches = FindMatches(); + if (matches.empty()) + return; + + auto length = int32_t(searchText.size()); + if (all) { + // One replacement of the whole text is one undo step + std::string replaced; + int32_t position = 0; + for (auto match : matches) { + replaced += content.substr(position, match - position) + replaceText; + position = match + length; + } + replaced += content.substr(position); + Replace(0, int32_t(content.size()), replaced, false); + MoveCursor(std::min(matches.front(), int32_t(content.size())), false); + return; + } + + // The selected match is replaced, otherwise the next one is selected first + auto selectionStart = std::min(cursor, anchor); + auto selected = std::max(cursor, anchor) - selectionStart == length && + std::find(matches.begin(), matches.end(), selectionStart) != matches.end(); + if (selected) + Replace(selectionStart, selectionStart + length, replaceText, false); + FindNext(true); + + } + + std::vector CodeEditor::FindMatches() const { + + std::vector matches; + if (searchText.empty()) + return matches; + auto equal = [](char a, char b) { return std::tolower((unsigned char)a) == std::tolower((unsigned char)b); }; + auto iter = content.begin(); + while ((iter = std::search(iter, content.end(), searchText.begin(), searchText.end(), equal)) != content.end()) { + matches.push_back(int32_t(iter - content.begin())); + iter += searchText.size(); + } + return matches; + + } + + void CodeEditor::FindNext(bool forward) { + + auto matches = FindMatches(); + if (matches.empty()) + return; + + auto selectionStart = std::min(cursor, anchor); + auto selectionEnd = std::max(cursor, anchor); + auto match = forward ? matches.front() : matches.back(); + if (forward) { + auto next = std::lower_bound(matches.begin(), matches.end(), selectionEnd); + if (next != matches.end()) + match = *next; + } + else { + auto previous = std::lower_bound(matches.begin(), matches.end(), selectionStart); + if (previous != matches.begin()) + match = *(previous - 1); + } + + anchor = match; + cursor = match + int32_t(searchText.size()); + scrollToCursor = true; + completionOpen = false; + + } + + bool CodeEditor::IsWordCharacter(int32_t offset) const { + + if (offset < 0 || offset >= int32_t(content.size())) + return false; + auto c = uint8_t(content[offset]); + return std::isalnum(c) || c == '_' || c >= 0x80; + + } + +} diff --git a/src/editor/ui/CodeEditor.h b/src/editor/ui/CodeEditor.h new file mode 100644 index 000000000..d534c9aa6 --- /dev/null +++ b/src/editor/ui/CodeEditor.h @@ -0,0 +1,225 @@ +#pragma once + +#include "System.h" + +#include + +#include +#include +#include +#include + +namespace Atlas::Editor::UI { + + enum class CodeLanguage { + GLSL = 0, + Lua + }; + + struct CodeCompletion { + std::string text; + std::string kind; + std::string signature; + std::string description; + }; + + // The word in front of the cursor and, after a . or :, what it belongs to, e.g. "entity" and ':' for "entity:Get". + // The qualifier keeps calls and indices ("scene:GetMainCamera()"), text is the code in front of it + struct CodeCompletionContext { + std::string prefix; + std::string qualifier; + char separator = 0; + std::string_view text; + }; + + // Text editor with syntax highlighting and line numbers. It keeps the cursor and undo history of the text + // with the id of the last call, another id starts again + class CodeEditor { + + public: + // Returns whether the text changed. A size of zero fills the available space on that axis + bool Render(const char* id, std::string& text, ImVec2 size = ImVec2(0.0f, 0.0f)); + + // Always read only, e.g. for generated code + void Render(const char* id, const std::string& text, ImVec2 size = ImVec2(0.0f, 0.0f)); + + // True for one frame when the editor lost the focus after the text was changed + bool IsDeactivatedAfterEdit() const; + + // Actions of a toolbar, they happen in the next Render + void Undo() { requestedAction = Action::Undo; } + + void Redo() { requestedAction = Action::Redo; } + + void OpenSearch(bool replace) { requestedAction = replace ? Action::Replace : Action::Search; } + + // Starts with a text before the editor is rendered, e.g. the file of a window, without undo steps + void Reset(const std::string& text); + + // Replaces the whole text as one undo step, the caller changes its own copy of the text too + void SetText(const std::string& text) { Replace(0, int32_t(content.size()), text, false); } + + bool CanUndo() const { return !undoStack.empty(); } + + bool CanRedo() const { return !redoStack.empty(); } + + CodeLanguage language = CodeLanguage::GLSL; + bool readOnly = false; + + // Suggestions for a context, the editor filters them by the prefix and adds the keywords and builtins of the language + std::function(const CodeCompletionContext& context)> completionProvider; + + // Functions defined in GLSL code with their signatures, the // comment lines above become the description. + // Overloads are one completion with a signature per line + static std::vector FindGlslFunctions(const std::string& code); + + private: + enum class Action { + None = 0, + Undo, + Redo, + Search, + Replace + }; + + void RenderSearch(bool canEdit); + + // Replaces the selected match and selects the next one, or replaces all matches as one undo step + void ReplaceMatch(bool all); + + // In the order of the code colors of the theme + enum class TokenType { + Keyword = 0, + Type, + Builtin, + Number, + String, + Comment, + Preprocessor + }; + + struct Token { + int32_t start; + int32_t end; + TokenType type; + }; + + struct Snapshot { + std::string text; + int32_t cursor; + }; + + bool RenderEditor(const char* id, const std::string& text, std::string* editedText, ImVec2 size); + + void Tokenize(); + + void AddToken(int32_t start, int32_t end, TokenType type); + + void HandleMouse(ImVec2 textOrigin, bool hovered, bool held, bool mouseInside); + + void HandleKeyboard(bool canEdit, float visibleHeight); + + void DrawLines(ImVec2 textOrigin, ImVec2 visibleMin, ImVec2 visibleMax, int32_t firstLine, int32_t lastLine, bool focused); + + bool HandleCompletionKeys(bool canEdit); + + void UpdateCompletion(); + + // Below the line of the cursor, or above it if there is no room below + void RenderCompletion(ImVec2 position, float lineTop); + + void Replace(int32_t start, int32_t end, const std::string& value, bool mergeUndo); + + void Restore(std::vector& from, std::vector& to); + + void MoveCursor(int32_t offset, bool select); + + int32_t GetLine(int32_t offset) const; + + int32_t GetLineEnd(int32_t line) const; + + int32_t GetColumn(int32_t offset) const; + + int32_t GetOffset(int32_t line, int32_t column) const; + + int32_t GetOffsetAt(ImVec2 position, ImVec2 textOrigin) const; + + int32_t GetWordBoundary(int32_t offset, int32_t direction) const; + + bool IsWordCharacter(int32_t offset) const; + + // Selects the next match of the search after the selection, or the one before it + void FindNext(bool forward); + + // Offsets of the matches of the search, ignoring case + std::vector FindMatches() const; + + std::string content; + std::vector lineStarts = { 0 }; + std::vector tokens; + std::vector lineTokens = { 0, 0 }; + int32_t maxColumns = 0; + int32_t tokenizedLanguage = -1; + ImGuiID lastId = 0; + + int32_t cursor = 0; + int32_t anchor = 0; + int32_t preferredColumn = -1; + + std::vector undoStack; + std::vector redoStack; + double lastEditTime = 0.0; + + float characterWidth = 0.0f; + float lineHeight = 0.0f; + float gutterWidth = 0.0f; + double blinkStart = 0.0; + + std::vector completions; + int32_t completionIndex = 0; + int32_t completionStart = 0; + bool completionOpen = false; + bool completionChosen = false; + float completionHeight = 0.0f; + // The font around the editor, descriptions are text and not code + ImFont* interfaceFont = nullptr; + + bool changed = false; + bool scrollToCursor = false; + bool selecting = false; + bool wasFocused = false; + bool editedWhileFocused = false; + bool deactivatedAfterEdit = false; + + // Ctrl+F opens the search above the text, Enter and F3 go to the next match, with Shift to the one before + bool searchOpen = false; + bool searchFocusRequested = false; + bool replaceOpen = false; + std::string searchText; + std::string replaceText; + // Offsets of the matches, found once per frame + std::vector searchMatches; + Action requestedAction = Action::None; + + const int32_t tabSize = 4; + + const std::vector glslKeywords = { "if", "else", "for", "while", "do", "return", "break", "continue", + "discard", "switch", "case", "default", "struct", "const", "in", "out", "inout", "uniform", "buffer", + "layout", "shared", "flat", "precision", "highp", "mediump", "lowp", "true", "false" }; + const std::vector glslTypes = { "void", "bool", "int", "uint", "float", "double", "vec2", "vec3", "vec4", + "ivec2", "ivec3", "ivec4", "uvec2", "uvec3", "uvec4", "bvec2", "bvec3", "bvec4", "mat2", "mat3", "mat4", + "mat3x4", "mat4x3", "sampler", "sampler2D", "sampler3D", "samplerCube", "sampler2DArray", "texture2D", + "texture2DArray", "image2D", "image3D" }; + const std::vector glslBuiltins = { "abs", "sign", "floor", "ceil", "round", "trunc", "fract", "mod", + "min", "max", "clamp", "mix", "step", "smoothstep", "sqrt", "inversesqrt", "pow", "exp", "exp2", "log", + "log2", "sin", "cos", "tan", "asin", "acos", "atan", "radians", "degrees", "length", "distance", "dot", + "cross", "normalize", "reflect", "refract", "transpose", "inverse", "determinant", "texture", "textureLod", + "texelFetch", "textureSize", "imageLoad", "imageStore", "dFdx", "dFdy", "fwidth", "any", "all", "saturate" }; + const std::vector luaKeywords = { "and", "break", "do", "else", "elseif", "end", "false", "for", + "function", "goto", "if", "in", "local", "nil", "not", "or", "repeat", "return", "then", "true", "until", "while" }; + const std::vector luaBuiltins = { "print", "pairs", "ipairs", "type", "tostring", "tonumber", "require", + "select", "next", "error", "assert", "pcall", "setmetatable", "getmetatable", "math", "string", "table", "self" }; + + }; + +} diff --git a/src/editor/ui/Widgets.cpp b/src/editor/ui/Widgets.cpp index 09d26cd70..6488f37aa 100644 --- a/src/editor/ui/Widgets.cpp +++ b/src/editor/ui/Widgets.cpp @@ -2,11 +2,22 @@ #include "../Singletons.h" #include "../Theme.h" +#include "ImguiExtension/UiElements.h" + +#include +#include +#include +#include + namespace Atlas::Editor::UI { bool Widgets::DragVec3(const char* label, vec3& value, float speed, float resetValue, float min, float max, const char* format) { + // Widgets drawing directly into the draw list return early like ImGui widgets, e.g. in rows hidden by a search + if (ImGui::GetCurrentWindow()->SkipItems) + return false; + const auto& style = ImGui::GetStyle(); const float stripeWidth = 3.0f; @@ -47,8 +58,11 @@ namespace Atlas::Editor::UI { ImGui::PopID(); } - ImGui::SameLine(0.0f, spacing); - ImGui::TextUnformatted(label); + // Labels starting with ## are hidden, e.g. in a property table which shows the label in its own column + if (std::strncmp(label, "##", 2) != 0) { + ImGui::SameLine(0.0f, spacing); + ImGui::TextUnformatted(label); + } ImGui::PopID(); @@ -58,6 +72,9 @@ namespace Atlas::Editor::UI { void Widgets::Callout(const char* text, ImVec4 color) { + if (ImGui::GetCurrentWindow()->SkipItems) + return; + const auto& style = ImGui::GetStyle(); const float padding = 8.0f; const float stripeWidth = 3.0f; @@ -100,6 +117,30 @@ namespace Atlas::Editor::UI { } + bool Widgets::RemovableSectionHeader(const char* label, ImGuiTreeNodeFlags flags, bool& remove, const char* tooltip) { + + bool open = SectionHeader(label, flags | ImGuiTreeNodeFlags_AllowOverlap); + + auto headerMin = ImGui::GetItemRectMin(); + auto headerMax = ImGui::GetItemRectMax(); + auto iconSize = ImGui::GetTextLineHeight(); + auto buttonExtent = iconSize + 2.0f; + auto cursorPos = ImGui::GetCursorPos(); + + ImGui::SameLine(); + ImGui::SetCursorScreenPos(ImVec2(headerMax.x - buttonExtent - ImGui::GetStyle().FramePadding.x, + headerMin.y + (headerMax.y - headerMin.y - buttonExtent) * 0.5f)); + + auto alpha = ImGui::IsMouseHoveringRect(headerMin, headerMax) ? 1.0f : 0.45f; + if (IconButton("Remove", Singletons::icons->Get(IconType::Trash), iconSize, tooltip, alpha)) + remove = true; + + ImGui::SetCursorPos(cursorPos); + + return open; + + } + bool Widgets::SegmentedControl(const char* label, int32_t& selection, const char* const items[], int32_t itemCount) { const auto& style = ImGui::GetStyle(); @@ -131,8 +172,11 @@ namespace Atlas::Editor::UI { Theme::PopPrimaryButton(); } - ImGui::SameLine(0.0f, style.ItemInnerSpacing.x); - ImGui::TextUnformatted(label); + // Labels starting with ## are hidden, e.g. in a property table which shows the label in its own column + if (std::strncmp(label, "##", 2) != 0) { + ImGui::SameLine(0.0f, style.ItemInnerSpacing.x); + ImGui::TextUnformatted(label); + } ImGui::PopID(); @@ -162,6 +206,9 @@ namespace Atlas::Editor::UI { void Widgets::ActiveIndicator() { + if (ImGui::GetCurrentWindow()->SkipItems) + return; + auto rectMin = ImGui::GetItemRectMin(); auto rectMax = ImGui::GetItemRectMax(); auto radius = std::max(2.5f, (rectMax.y - rectMin.y) * 0.12f); @@ -174,6 +221,183 @@ namespace Atlas::Editor::UI { } + bool Widgets::ToolbarIconButton(const char* id, const Texture::Texture2D& icon, const char* tooltip, bool selected) { + + auto set = Singletons::imguiWrapper->GetTextureId(&icon); + auto size = ImGui::GetTextLineHeight(); + + if (selected) + Theme::PushPrimaryButton(); + else + ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.0f, 0.0f, 0.0f, 0.0f)); + ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 0.0f); + + // The default frame padding makes it as high as text buttons and fields next to it + bool pressed = ImGui::ImageButton(id, set, ImVec2(size, size), ImVec2(0.1f, 0.1f), ImVec2(0.9f, 0.9f)); + + ImGui::PopStyleVar(); + if (selected) + Theme::PopPrimaryButton(); + else + ImGui::PopStyleColor(); + + if (tooltip) + ImGui::SetItemTooltip("%s", tooltip); + + return pressed; + + } + + bool Widgets::DangerButton(const char* label, ImVec2 size) { + + Theme::PushDangerButton(); + bool pressed = ImGui::Button(label, size); + Theme::PopDangerButton(); + return pressed; + + } + + void Widgets::Heading(const char* text) { + + ImGui::SetWindowFontScale(headingScale); + ImGui::TextUnformatted(text); + ImGui::SetWindowFontScale(1.0f); + + } + + bool Widgets::TextArea(const char* id, std::string& text, float lines, ImGuiInputTextFlags flags, bool* deactivatedAfterEdit) { + + // Child windows are created even when the parent skips its items + if (ImGui::GetCurrentWindow()->SkipItems) + return false; + + // The child keeps the height the user dragged it to, the text box fills it + auto height = lines * ImGui::GetTextLineHeight() + 2.0f * ImGui::GetStyle().FramePadding.y; + ImGui::BeginChild(id, ImVec2(-FLT_MIN, height), ImGuiChildFlags_ResizeY, ImGuiWindowFlags_NoScrollbar); + auto changed = ImGui::InputTextMultiline("##Text", &text, ImVec2(-FLT_MIN, -FLT_MIN), flags); + if (deactivatedAfterEdit) + *deactivatedAfterEdit = ImGui::IsItemDeactivatedAfterEdit(); + ImGui::EndChild(); + + return changed; + + } + + void Widgets::EmptyState(const char* text) { + + ImGui::PushTextWrapPos(); + ImGui::TextColored(Theme::TextMuted(), "%s", text); + ImGui::PopTextWrapPos(); + + } + + void Widgets::Spinner(float scale) { + + if (ImGui::GetCurrentWindow()->SkipItems) + return; + + auto size = ImGui::GetTextLineHeight() * scale; + auto pos = ImGui::GetCursorScreenPos(); + ImGui::Dummy(ImVec2(size, size)); + + auto drawList = ImGui::GetWindowDrawList(); + auto center = ImVec2(pos.x + size * 0.5f, pos.y + size * 0.5f); + auto radius = size * 0.5f - 2.0f; + auto thickness = std::max(2.0f, size * 0.12f); + + // A quarter of the ring turns around a faint full ring + auto start = float(ImGui::GetTime()) * 6.0f; + drawList->PathArcTo(center, radius, 0.0f, 2.0f * IM_PI, 32); + drawList->PathStroke(ImGui::GetColorU32(Theme::TextMuted(0.25f)), ImDrawFlags_None, thickness); + drawList->PathArcTo(center, radius, start, start + 0.5f * IM_PI, 12); + drawList->PathStroke(ImGui::GetColorU32(Theme::Accent()), ImDrawFlags_None, thickness); + + } + + void Widgets::LoadingState(const char* text) { + + auto region = ImGui::GetContentRegionAvail(); + auto start = ImGui::GetCursorPos(); + auto spinnerSize = ImGui::GetTextLineHeight() * 2.0f; + auto textSize = ImGui::CalcTextSize(text); + auto spacing = ImGui::GetStyle().ItemSpacing.y * 2.0f; + auto height = spinnerSize + spacing + textSize.y; + + auto top = start.y + std::max(0.0f, (region.y - height) * 0.5f); + ImGui::SetCursorPos(ImVec2(start.x + std::max(0.0f, (region.x - spinnerSize) * 0.5f), top)); + Spinner(2.0f); + ImGui::SetCursorPos(ImVec2(start.x + std::max(0.0f, (region.x - textSize.x) * 0.5f), top + spinnerSize + spacing)); + ImGui::TextColored(Theme::TextMuted(), "%s", text); + + } + + bool Widgets::BeginProperties(const char* id) { + + // The panels of ImguiExtension draw the same tables, the label color is the muted text of the theme + return ImguiExtension::UIElements::BeginProperties(id); + + } + + void Widgets::PropertyLabel(const char* label, const char* tooltip) { + + ImguiExtension::UIElements::PropertyLabel(label, tooltip); + + } + + void Widgets::EndProperties() { + + ImguiExtension::UIElements::EndProperties(); + + } + + void Widgets::PropertySection(const char* label) { + + ImguiExtension::UIElements::PropertySection(label); + + } + + bool Widgets::BeginPropertyGroup(const char* name) { + + return ImguiExtension::UIElements::BeginPropertyGroup(name); + + } + + void Widgets::EndPropertyGroup() { + + ImguiExtension::UIElements::EndPropertyGroup(); + + } + + ImGuiTreeNodeFlags Widgets::PropertyGroupHeaderFlags() { + + return ImguiExtension::UIElements::PropertyGroupHeaderFlags(); + + } + + void Widgets::BeginPropertyContent() { + + ImguiExtension::UIElements::BeginPropertyContent(); + + } + + void Widgets::EndPropertyContent() { + + ImguiExtension::UIElements::EndPropertyContent(); + + } + + bool Widgets::BeginPropertyBlock(const char* label) { + + return ImguiExtension::UIElements::BeginPropertyBlock(label); + + } + + void Widgets::EndPropertyBlock() { + + ImguiExtension::UIElements::EndPropertyBlock(); + + } + bool Widgets::IconButton(const char* id, const Texture::Texture2D& icon, float size, const char* tooltip, float alpha) { @@ -196,4 +420,21 @@ namespace Atlas::Editor::UI { } + bool Widgets::TextEllipsis(const char* text, const char* textEnd, float width) { + + if (ImGui::GetCurrentWindow()->SkipItems) + return false; + + auto textSize = ImGui::CalcTextSize(text, textEnd); + auto pos = ImGui::GetCursorScreenPos(); + auto lineHeight = ImGui::GetTextLineHeight(); + + ImGui::Dummy(ImVec2(std::min(textSize.x, width), lineHeight)); + ImGui::RenderTextEllipsis(ImGui::GetWindowDrawList(), pos, ImVec2(pos.x + width, pos.y + lineHeight), + pos.x + width, pos.x + width, text, textEnd, &textSize); + + return textSize.x > width; + + } + } diff --git a/src/editor/ui/Widgets.h b/src/editor/ui/Widgets.h index 07de67777..c6bf887ae 100644 --- a/src/editor/ui/Widgets.h +++ b/src/editor/ui/Widgets.h @@ -5,13 +5,16 @@ #include +#include + namespace Atlas::Editor::UI { // Small, editor specific widgets that are reused across panels class Widgets { public: - // Three drag fields marked with the X/Y/Z axis colors. Right-click on a field to reset it. + // Three drag fields marked with the X/Y/Z axis colors. Right-click on a field to reset it. A label starting + // with ## isn't shown, the fields then fill the width, e.g. after PropertyLabel static bool DragVec3(const char* label, vec3& value, float speed = 0.01f, float resetValue = 0.0f, float min = 0.0f, float max = 0.0f, const char* format = "%.3f"); @@ -22,6 +25,9 @@ namespace Atlas::Editor::UI { // Collapsing header with a neutral background, the accent color is reserved for selections static bool SectionHeader(const char* label, ImGuiTreeNodeFlags flags = 0); + // Section header with a trash can on its right side, which sets remove when clicked + static bool RemovableSectionHeader(const char* label, ImGuiTreeNodeFlags flags, bool& remove, const char* tooltip); + // Row of buttons where exactly one is selected, a more direct alternative to a combo with few items static bool SegmentedControl(const char* label, int32_t& selection, const char* const items[], int32_t itemCount); @@ -31,10 +37,64 @@ namespace Atlas::Editor::UI { // Small accent dot in the top right corner of the last item, e.g. to show that a filter is active static void ActiveIndicator(); + // Text that ends with an ellipsis if it is wider than width, returns whether it was shortened + static bool TextEllipsis(const char* text, const char* textEnd, float width); + // Image button without a background that only highlights on hover static bool IconButton(const char* id, const Texture::Texture2D& icon, float size, const char* tooltip = nullptr, float alpha = 1.0f); + // Icon button as high as the text buttons and fields of a row, for toolbars. Selected ones show the accent + static bool ToolbarIconButton(const char* id, const Texture::Texture2D& icon, const char* tooltip, bool selected = false); + + // Full width button for actions that remove or delete something + static bool DangerButton(const char* label, ImVec2 size = ImVec2(-FLT_MIN, 0.0f)); + + // Large text at the top of a panel or editor, other headings in it are section headers + static void Heading(const char* text); + + static constexpr float headingScale = 1.4f; + + // Full width text box for longer text such as comments, it scrolls and the lower edge can be dragged to resize it. + // Returns whether the text changed, deactivatedAfterEdit tells when an edit is final + static bool TextArea(const char* id, std::string& text, float lines, ImGuiInputTextFlags flags = 0, + bool* deactivatedAfterEdit = nullptr); + + // Muted, wrapped text where a list or section has nothing to show + static void EmptyState(const char* text); + + // Spinning ring with a text below, centered in the remaining region of the window + static void LoadingState(const char* text); + + // The spinning ring alone, as large as the text height times the scale + static void Spinner(float scale = 1.0f); + + // Properties with the label on the left and the value filling the rest of the row, like the parameters of + // materials. Call PropertyLabel before each value, then EndProperties + static bool BeginProperties(const char* id); + + // Starts a row, the next item is the value and fills its column + static void PropertyLabel(const char* label, const char* tooltip = nullptr); + + static void EndProperties(); + + // Searchable parts of the properties, see the property search of ImguiExtension::UIElements + static void PropertySection(const char* label); + + static bool BeginPropertyGroup(const char* name); + + static void EndPropertyGroup(); + + static ImGuiTreeNodeFlags PropertyGroupHeaderFlags(); + + static void BeginPropertyContent(); + + static void EndPropertyContent(); + + static bool BeginPropertyBlock(const char* label); + + static void EndPropertyBlock(); + }; } diff --git a/src/editor/ui/panels/AnimationTimelinePanel.cpp b/src/editor/ui/panels/AnimationTimelinePanel.cpp new file mode 100644 index 000000000..65bdb1b57 --- /dev/null +++ b/src/editor/ui/panels/AnimationTimelinePanel.cpp @@ -0,0 +1,469 @@ +#include "AnimationTimelinePanel.h" + +#include "../../Singletons.h" +#include "../../Notifications.h" +#include "../../Theme.h" +#include "../Widgets.h" + +#include "loader/AnimationLoader.h" + +#include + +namespace Atlas::Editor::UI { + + void AnimationTimelinePanel::Render(AnimationComponent& animationComponent, const Mesh::Skeleton& skeleton, + int32_t& selectedJoint) { + + // Without an animation on the component the first layer with one is shown + if (shownLayer >= animationComponent.GetLayerCount() || !GetTrack(animationComponent, shownLayer).animation->IsLoaded()) { + shownLayer = -1; + for (int32_t layer = -1; layer < animationComponent.GetLayerCount(); layer++) { + if (GetTrack(animationComponent, layer).animation->IsLoaded()) { + shownLayer = layer; + break; + } + } + } + + auto track = GetTrack(animationComponent, shownLayer); + if (!track.animation->IsLoaded()) { + Widgets::EmptyState("Play an animation to see its keys"); + saveRequested = deleteKeyRequested = false; + return; + } + + auto& animation = *track.animation->Get(); + if (shownAnimation != &animation) { + shownAnimation = &animation; + selectedKey = KeyRef(); + draggingKey = false; + } + modified = modifiedAnimations.contains(&animation); + + RenderToolbar(animationComponent, track); + + const auto& style = ImGui::GetStyle(); + auto lineHeight = ImGui::GetTextLineHeight(); + auto laneHeight = std::floor(0.5f * lineHeight) + 2.0f; + auto rowHeight = 3.0f * laneHeight + 4.0f; + auto rulerHeight = lineHeight + 8.0f; + auto keyRadius = 0.5f * laneHeight; + const float labelWidth = 12.0f * lineHeight; + + auto editorWidth = selectedKey.IsValid() ? 18.0f * lineHeight : 0.0f; + auto region = ImGui::GetContentRegionAvail(); + auto timelineWidth = std::max(animation.duration * zoom, region.x - editorWidth - labelWidth - 3.0f * style.ItemSpacing.x) + + 2.0f * keyRadius; + + auto mouse = ImGui::GetIO().MousePos; + float timelineOriginX = 0.0f; + + auto timeToX = [&](float time) { return timelineOriginX + time * zoom; }; + auto xToTime = [&](float x) { return glm::clamp((x - timelineOriginX) / zoom, 0.0f, animation.duration); }; + + auto tableFlags = ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY | ImGuiTableFlags_BordersInnerV | + ImGuiTableFlags_RowBg | ImGuiTableFlags_NoPadOuterX; + if (ImGui::BeginTable("Keys", 2, tableFlags, ImVec2(region.x - (editorWidth > 0.0f ? editorWidth + style.ItemSpacing.x : 0.0f), 0.0f))) { + // Scrolling tables have their own window to draw into + auto drawList = ImGui::GetWindowDrawList(); + ImGui::TableSetupScrollFreeze(1, 1); + ImGui::TableSetupColumn("Joint", ImGuiTableColumnFlags_WidthFixed, labelWidth); + ImGui::TableSetupColumn("Keys", ImGuiTableColumnFlags_WidthFixed, timelineWidth); + + // Ruler, dragging on it scrubs through the animation + ImGui::TableNextRow(ImGuiTableRowFlags_Headers, rulerHeight); + ImGui::TableNextColumn(); + ImGui::AlignTextToFramePadding(); + ImGui::TextDisabled("%d animated joints", int32_t(animation.channels.size())); + ImGui::TableNextColumn(); + + auto rulerMin = ImGui::GetCursorScreenPos(); + timelineOriginX = rulerMin.x + keyRadius; + ImGui::InvisibleButton("Ruler", ImVec2(timelineWidth, rulerHeight)); + if (ImGui::IsItemActive()) { + *track.time = xToTime(mouse.x); + *track.playing = false; + } + + // Labels at least 60 pixels apart + float steps[] = { 0.01f, 0.02f, 0.05f, 0.1f, 0.2f, 0.5f, 1.0f, 2.0f, 5.0f, 10.0f, 30.0f, 60.0f }; + float step = steps[IM_ARRAYSIZE(steps) - 1]; + for (auto candidate : steps) { + if (candidate * zoom >= 60.0f) { + step = candidate; + break; + } + } + + auto tickColor = ImGui::GetColorU32(ImGuiCol_TextDisabled); + for (int32_t i = 0; float(i) * step <= animation.duration + 0.0001f; i++) { + auto time = float(i) * step; + auto x = timeToX(time); + drawList->AddLine(ImVec2(x, rulerMin.y + rulerHeight - 6.0f), ImVec2(x, rulerMin.y + rulerHeight), tickColor); + char label[16]; + std::snprintf(label, sizeof(label), "%g", time); + drawList->AddText(ImVec2(x + 3.0f, rulerMin.y + 2.0f), tickColor, label); + } + + auto playheadColor = ImGui::GetColorU32(Theme::Accent()); + auto playheadX = timeToX(*track.time); + drawList->AddTriangleFilled(ImVec2(playheadX - 5.0f, rulerMin.y + rulerHeight - 8.0f), + ImVec2(playheadX + 5.0f, rulerMin.y + rulerHeight - 8.0f), ImVec2(playheadX, rulerMin.y + rulerHeight), playheadColor); + + ImU32 keyColors[] = { + ImGui::GetColorU32(Theme::Axis(0)), + ImGui::GetColorU32(Theme::Axis(1)), + ImGui::GetColorU32(Theme::Axis(2)) + }; + const char* laneNames[] = { "Position", "Rotation", "Scale" }; + + ImGuiListClipper clipper; + clipper.Begin(int32_t(animation.channels.size()), rowHeight); + while (clipper.Step()) { + for (int32_t channelIdx = clipper.DisplayStart; channelIdx < clipper.DisplayEnd; channelIdx++) { + auto& channel = animation.channels[channelIdx]; + auto jointIdx = skeleton.GetJointIndex(channel.jointName); + + ImGui::PushID(channelIdx); + ImGui::TableNextRow(0, rowHeight); + if (jointIdx >= 0 && jointIdx == selectedJoint) + ImGui::TableSetBgColor(ImGuiTableBgTarget_RowBg0, ImGui::GetColorU32(Theme::Accent(0.18f))); + + ImGui::TableNextColumn(); + if (ImGui::Selectable(channel.jointName.c_str(), false, 0, ImVec2(0.0f, rowHeight - style.CellPadding.y * 2.0f))) + selectedJoint = jointIdx; + if (jointIdx < 0) + ImGui::SetItemTooltip("The skeleton has no joint with this name"); + + ImGui::TableNextColumn(); + auto rowMin = ImGui::GetCursorScreenPos(); + ImGui::InvisibleButton("Lanes", ImVec2(timelineWidth, rowHeight - style.CellPadding.y * 2.0f)); + auto rowHovered = ImGui::IsItemHovered(); + auto hoveredLane = glm::clamp(int32_t((mouse.y - rowMin.y) / laneHeight), 0, 2); + + drawList->AddLine(ImVec2(playheadX, rowMin.y), ImVec2(playheadX, rowMin.y + rowHeight), playheadColor); + + KeyRef hoveredKey; + for (int32_t lane = 0; lane < 3; lane++) { + auto type = static_cast(lane); + const auto& times = GetTimes(channel, type); + auto y = rowMin.y + (float(lane) + 0.5f) * laneHeight; + + for (int32_t key = 0; key < int32_t(times.size()); key++) { + auto x = timeToX(times[key]); + auto ref = KeyRef { channelIdx, type, key }; + auto selected = ref == selectedKey; + auto hovered = rowHovered && lane == hoveredLane && std::abs(mouse.x - x) <= keyRadius + 1.0f; + if (hovered) + hoveredKey = ref; + + auto radius = selected || hovered ? keyRadius + 1.5f : keyRadius; + ImVec2 diamond[] = { ImVec2(x, y - radius), ImVec2(x + radius, y), ImVec2(x, y + radius), ImVec2(x - radius, y) }; + drawList->AddConvexPolyFilled(diamond, 4, keyColors[lane]); + if (selected) + drawList->AddPolyline(diamond, 4, ImGui::GetColorU32(ImGuiCol_Text), ImDrawFlags_Closed, 1.5f); + } + } + + if (rowHovered) { + if (hoveredKey.IsValid()) + ImGui::SetTooltip("%s %s at %.3f s", channel.jointName.c_str(), laneNames[int32_t(hoveredKey.type)], + GetTimes(channel, hoveredKey.type)[hoveredKey.key]); + + if (ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left) && !hoveredKey.IsValid()) { + auto type = static_cast(hoveredLane); + auto joint = jointIdx >= 0 ? &skeleton.joints[jointIdx] : nullptr; + selectedKey = { channelIdx, type, InsertKey(channel, type, xToTime(mouse.x), joint) }; + modified = true; + } + else if (ImGui::IsMouseClicked(ImGuiMouseButton_Left)) { + selectedKey = hoveredKey; + draggingKey = hoveredKey.IsValid(); + if (jointIdx >= 0) + selectedJoint = jointIdx; + } + } + + ImGui::PopID(); + } + } + + // Dragging the selected key moves it in time + if (draggingKey && selectedKey.IsValid()) { + if (ImGui::IsMouseDown(ImGuiMouseButton_Left)) { + auto& channel = animation.channels[selectedKey.channel]; + auto time = xToTime(mouse.x); + if (GetTimes(channel, selectedKey.type)[selectedKey.key] != time) { + selectedKey.key = MoveKey(channel, selectedKey.type, selectedKey.key, time); + modified = true; + } + } + else { + draggingKey = false; + } + } + + // Ctrl + mouse wheel zooms the timeline + const auto& io = ImGui::GetIO(); + if (ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows) && io.KeyCtrl && io.MouseWheel != 0.0f) + zoom = std::clamp(zoom * std::pow(1.25f, io.MouseWheel), 10.0f, 5000.0f); + + ImGui::EndTable(); + } + + auto deleteKeyPressed = ImGui::IsWindowFocused(ImGuiFocusedFlags_ChildWindows) && + !ImGui::GetIO().WantTextInput && ImGui::IsKeyPressed(ImGuiKey_Delete, false); + if (selectedKey.IsValid() && (deleteKeyRequested || deleteKeyPressed)) { + RemoveKey(animation.channels[selectedKey.channel], selectedKey.type, selectedKey.key); + selectedKey = KeyRef(); + modified = true; + } + deleteKeyRequested = false; + + if (selectedKey.IsValid()) { + ImGui::SameLine(); + ImGui::BeginChild("Key editor", ImVec2(0.0f, 0.0f), ImGuiChildFlags_Borders); + RenderKeyEditor(animation, skeleton); + ImGui::EndChild(); + } + + if (modified) + modifiedAnimations.insert(&animation); + else + modifiedAnimations.erase(&animation); + + } + + void AnimationTimelinePanel::SaveAnimation(ResourceHandle& animation) { + + if (!animation.IsLoaded()) + return; + + Loader::AnimationLoader::SaveAnimation(animation.Get(), animation.GetResource()->path, true); + Notifications::Push({ .message = "Saved animation " + animation.GetResource()->GetFileName() }); + modified = false; + + } + + AnimationTimelinePanel::Track AnimationTimelinePanel::GetTrack(AnimationComponent& animationComponent, int32_t layer) { + + Track track; + auto setTrack = [&](auto& playback) { + track.animation = std::addressof(playback.animation); + track.time = &playback.time; + track.speed = &playback.speed; + track.loop = &playback.loop; + track.playing = &playback.playing; + }; + + if (layer < 0) + setTrack(animationComponent); + else + setTrack(animationComponent.GetLayer(layer)); + + return track; + + } + + void AnimationTimelinePanel::RenderToolbar(AnimationComponent& animationComponent, Track& track) { + + auto& animation = *track.animation; + auto iconSize = ImGui::GetTextLineHeight(); + + auto& playIcon = Singletons::icons->Get(*track.playing ? IconType::Pause : IconType::Play); + ImGui::AlignTextToFramePadding(); + if (Widgets::IconButton("Play", playIcon, iconSize, *track.playing ? "Pause" : "Play")) + *track.playing = !*track.playing; + + // The base animation and the layers each have their own keys and playback + auto trackName = [&](int32_t layer) { + auto layerTrack = GetTrack(animationComponent, layer); + auto name = layerTrack.animation->IsLoaded() ? layerTrack.animation->Get()->name : std::string("No animation"); + return (layer < 0 ? std::string("Base: ") : "Layer " + std::to_string(layer) + ": ") + name; + }; + + ImGui::SameLine(); + ImGui::SetNextItemWidth(14.0f * iconSize); + if (ImGui::BeginCombo("##Track", trackName(shownLayer).c_str())) { + for (int32_t layer = -1; layer < animationComponent.GetLayerCount(); layer++) { + ImGui::BeginDisabled(!GetTrack(animationComponent, layer).animation->IsLoaded()); + if (ImGui::Selectable(trackName(layer).c_str(), layer == shownLayer)) + shownLayer = layer; + ImGui::EndDisabled(); + } + ImGui::EndCombo(); + } + ImGui::SetItemTooltip("Animation of the component or of one of its layers"); + if (modified) { + ImGui::SameLine(0.0f, 2.0f); + ImGui::TextColored(Theme::Warning(), "*"); + ImGui::SetItemTooltip("The keys changed since the animation was saved"); + } + + ImGui::SameLine(); + ImGui::SetNextItemWidth(6.0f * iconSize); + ImGui::DragFloat("##Time", track.time, 0.01f, 0.0f, animation->duration, "%.2f s"); + ImGui::SetItemTooltip("Time"); + ImGui::SameLine(); + ImGui::AlignTextToFramePadding(); + ImGui::TextDisabled("/"); + ImGui::SameLine(); + ImGui::SetNextItemWidth(6.0f * iconSize); + if (ImGui::DragFloat("##Duration", &animation->duration, 0.01f, 0.01f, 600.0f, "%.2f s")) + modified = true; + ImGui::SetItemTooltip("Duration"); + + ImGui::SameLine(); + ImGui::Checkbox("Loop", track.loop); + ImGui::SameLine(); + ImGui::SetNextItemWidth(5.0f * iconSize); + ImGui::DragFloat("##Speed", track.speed, 0.01f, -10.0f, 10.0f, "%.2fx"); + ImGui::SetItemTooltip("Playback speed"); + + // Save on the right, highlighted while there are changes + auto saveWidth = ImGui::GetTextLineHeight() + 2.0f * ImGui::GetStyle().FramePadding.x; + ImGui::SameLine(std::max(ImGui::GetCursorPosX(), ImGui::GetWindowContentRegionMax().x - saveWidth)); + auto saveTooltip = "Save the animation to " + animation.GetResource()->path; + if (Widgets::ToolbarIconButton("Save animation", Singletons::icons->Get(IconType::Save), saveTooltip.c_str(), modified) || + saveRequested) + SaveAnimation(animation); + saveRequested = false; + + ImGui::TextDisabled("Click a key to select it, drag to move it, Delete removes it, double click a lane adds one. " + "Ctrl + mouse wheel zooms"); + + } + + void AnimationTimelinePanel::RenderKeyEditor(Animation::Animation& animation, const Mesh::Skeleton& skeleton) { + + auto& channel = animation.channels[selectedKey.channel]; + auto& times = GetTimes(channel, selectedKey.type); + if (selectedKey.key >= int32_t(times.size())) { + selectedKey = KeyRef(); + return; + } + + const char* typeNames[] = { "Position", "Rotation", "Scale" }; + ImGui::SeparatorText((channel.jointName + " " + typeNames[int32_t(selectedKey.type)]).c_str()); + + if (Widgets::BeginProperties("Key")) { + auto time = times[selectedKey.key]; + Widgets::PropertyLabel("Time"); + if (ImGui::DragFloat("##Time", &time, 0.005f, 0.0f, animation.duration, "%.3f s")) { + selectedKey.key = MoveKey(channel, selectedKey.type, selectedKey.key, time); + modified = true; + } + + switch (selectedKey.type) { + case KeyType::Position: + Widgets::PropertyLabel("Position"); + modified |= Widgets::DragVec3("##Position", channel.positions[selectedKey.key], 0.001f); + break; + case KeyType::Rotation: { + auto& rotation = channel.rotations[selectedKey.key]; + auto euler = glm::degrees(glm::eulerAngles(rotation)); + Widgets::PropertyLabel("Rotation"); + if (Widgets::DragVec3("##Rotation", euler, 0.1f, 0.0f, 0.0f, 0.0f, "%.1f")) { + rotation = quat(glm::radians(euler)); + modified = true; + } + break; + } + case KeyType::Scale: + Widgets::PropertyLabel("Scale"); + modified |= Widgets::DragVec3("##Scale", channel.scales[selectedKey.key], 0.001f, 1.0f); + break; + } + + Widgets::EndProperties(); + } + + if (Widgets::DangerButton("Remove key")) { + RemoveKey(channel, selectedKey.type, selectedKey.key); + selectedKey = KeyRef(); + modified = true; + } + + } + + std::vector& AnimationTimelinePanel::GetTimes(Animation::Channel& channel, KeyType type) { + + switch (type) { + case KeyType::Rotation: return channel.rotationTimes; + case KeyType::Scale: return channel.scaleTimes; + default: return channel.positionTimes; + } + + } + + int32_t AnimationTimelinePanel::InsertKey(Animation::Channel& channel, KeyType type, float time, const Mesh::Joint* joint) { + + auto& times = GetTimes(channel, type); + auto it = std::lower_bound(times.begin(), times.end(), time); + auto key = int32_t(it - times.begin()); + + switch (type) { + case KeyType::Position: { + auto value = channel.SamplePosition(time, joint ? joint->position : vec3(0.0f)); + channel.positions.insert(channel.positions.begin() + key, value); + break; + } + case KeyType::Rotation: { + auto value = channel.SampleRotation(time, joint ? joint->rotation : quat(1.0f, 0.0f, 0.0f, 0.0f)); + channel.rotations.insert(channel.rotations.begin() + key, value); + break; + } + case KeyType::Scale: { + auto value = channel.SampleScale(time, joint ? joint->scale : vec3(1.0f)); + channel.scales.insert(channel.scales.begin() + key, value); + break; + } + } + + times.insert(times.begin() + key, time); + return key; + + } + + void AnimationTimelinePanel::RemoveKey(Animation::Channel& channel, KeyType type, int32_t key) { + + auto& times = GetTimes(channel, type); + times.erase(times.begin() + key); + + switch (type) { + case KeyType::Position: channel.positions.erase(channel.positions.begin() + key); break; + case KeyType::Rotation: channel.rotations.erase(channel.rotations.begin() + key); break; + case KeyType::Scale: channel.scales.erase(channel.scales.begin() + key); break; + } + + } + + int32_t AnimationTimelinePanel::MoveKey(Animation::Channel& channel, KeyType type, int32_t key, float time) { + + auto& times = GetTimes(channel, type); + + // Swap with the neighbours until the order is restored, the values move along + auto swapKeys = [&](int32_t a, int32_t b) { + std::swap(times[a], times[b]); + switch (type) { + case KeyType::Position: std::swap(channel.positions[a], channel.positions[b]); break; + case KeyType::Rotation: std::swap(channel.rotations[a], channel.rotations[b]); break; + case KeyType::Scale: std::swap(channel.scales[a], channel.scales[b]); break; + } + }; + + times[key] = time; + while (key > 0 && times[key - 1] > times[key]) { + swapKeys(key - 1, key); + key--; + } + while (key + 1 < int32_t(times.size()) && times[key + 1] < times[key]) { + swapKeys(key, key + 1); + key++; + } + + return key; + + } + +} diff --git a/src/editor/ui/panels/AnimationTimelinePanel.h b/src/editor/ui/panels/AnimationTimelinePanel.h new file mode 100644 index 000000000..c48ff684d --- /dev/null +++ b/src/editor/ui/panels/AnimationTimelinePanel.h @@ -0,0 +1,88 @@ +#pragma once + +#include "Panel.h" + +#include "scene/components/AnimationComponent.h" + +#include + +namespace Atlas::Editor::UI { + + // Keys of the animation of a component per joint, with playback, scrubbing and key editing + class AnimationTimelinePanel : public Panel { + + public: + AnimationTimelinePanel() : Panel("Timeline") {} + + /** + * Renders the panel into the current window + * @param selectedJoint The joint selected in the skeleton, clicking a row selects its joint + */ + void Render(AnimationComponent& animationComponent, const Mesh::Skeleton& skeleton, int32_t& selectedJoint); + + void SaveAnimation(ResourceHandle& animation); + + bool HasSelectedKey() const { return selectedKey.IsValid(); } + + // Whether keys of the shown animation changed since it was loaded or saved + bool modified = false; + + // Handled by the next render, the shown animation is only known there + bool saveRequested = false; + bool deleteKeyRequested = false; + + private: + // The animation of the component or of one of its layers, with its playback state + struct Track { + ResourceHandle* animation = nullptr; + float* time = nullptr; + float* speed = nullptr; + bool* loop = nullptr; + bool* playing = nullptr; + }; + + enum class KeyType { + Position = 0, + Rotation, + Scale + }; + + struct KeyRef { + int32_t channel = -1; + KeyType type = KeyType::Position; + int32_t key = -1; + + bool IsValid() const { return channel >= 0 && key >= 0; } + bool operator==(const KeyRef& that) const = default; + }; + + // The animation of the component with -1, otherwise the one of the layer + static Track GetTrack(AnimationComponent& animationComponent, int32_t layer); + + void RenderToolbar(AnimationComponent& animationComponent, Track& track); + + void RenderKeyEditor(Animation::Animation& animation, const Mesh::Skeleton& skeleton); + + static std::vector& GetTimes(Animation::Channel& channel, KeyType type); + + // Inserts a key with the value the channel has at the time + static int32_t InsertKey(Animation::Channel& channel, KeyType type, float time, const Mesh::Joint* joint); + + static void RemoveKey(Animation::Channel& channel, KeyType type, int32_t key); + + // Moves a key and keeps the keys sorted, returns the new index of the key + static int32_t MoveKey(Animation::Channel& channel, KeyType type, int32_t key, float time); + + const Animation::Animation* shownAnimation = nullptr; + std::unordered_set modifiedAnimations; + int32_t shownLayer = -1; + + KeyRef selectedKey; + bool draggingKey = false; + + // Pixels per second + float zoom = 200.0f; + + }; + +} diff --git a/src/editor/ui/panels/EntityPropertiesPanel.cpp b/src/editor/ui/panels/EntityPropertiesPanel.cpp index f824df7b2..75c80ca84 100644 --- a/src/editor/ui/panels/EntityPropertiesPanel.cpp +++ b/src/editor/ui/panels/EntityPropertiesPanel.cpp @@ -3,6 +3,7 @@ #include "Notifications.h" #include "Theme.h" +#include #include #include @@ -27,6 +28,14 @@ namespace Atlas::Editor::UI { std::string nodeName = nameComponent ? nameComponent->name : "Entity " + std::to_string(entity); bool rootNode = nodeName == "Root"; + ImguiExtension::UIElements::PropertySearchBar("##Property search", propertySearch, focusSearch); + // A hidden panel is shown in one of the next frames, the search bar gets the focus then + if (!ImGui::GetCurrentWindow()->SkipItems) + focusSearch = false; + ImGui::Spacing(); + + ImguiExtension::UIElements::BeginPropertySearch(propertySearch, uint32_t(entity)); + // General components { if (entity.HasComponent()) { @@ -35,12 +44,13 @@ namespace Atlas::Editor::UI { } if (entity.HasComponent()) { - // Create a copy here to be able to change the resource - auto comp = entity.GetComponent(); RenderComponentPanel("Mesh", scene, - entity, meshComponentPanel, comp); - entity.RemoveComponent(); - entity.AddComponent(comp); + entity, meshComponentPanel, entity.GetComponent()); + } + + if (entity.HasComponent()) { + RenderComponentPanel("Animation", scene, entity, + animationComponentPanel, entity.GetComponent()); } if (entity.HasComponent()) { @@ -60,6 +70,12 @@ namespace Atlas::Editor::UI { entity, audioVolumeComponentPanel, comp); } + if (entity.HasComponent()) { + auto& comp = entity.GetComponent(); + RenderComponentPanel("Fog volume", scene, + entity, fogVolumeComponentPanel, comp); + } + if (entity.HasComponent()) { auto& comp = entity.GetComponent(); RenderComponentPanel("Camera", scene, @@ -88,16 +104,37 @@ namespace Atlas::Editor::UI { } } + if (entity.HasComponent()) { + RenderComponentPanel("Soft body", scene, + entity, softBodyComponentPanel, entity.GetComponent()); + } + if (entity.HasComponent()) { auto comp = entity.GetComponent(); RenderComponentPanel("Player", scene, entity, playerComponentPanel, comp); - // Only change if we have new settings - entity.RemoveComponent(); - auto& newComp = entity.AddComponent(*comp.creationSettings); + // Recreating the player while playing would reset its state, e.g. crouching or touched triggers + if (scene->physicsWorld->pauseSimulation) { + entity.RemoveComponent(); + entity.AddComponent(*comp.creationSettings); + } + auto& newComp = entity.GetComponent(); newComp.slowVelocity = comp.slowVelocity; newComp.fastVelocity = comp.fastVelocity; newComp.jumpVelocity = comp.jumpVelocity; + newComp.acceleration = comp.acceleration; + newComp.deceleration = comp.deceleration; + newComp.allowInput = comp.allowInput; + newComp.stickToGroundDistance = comp.stickToGroundDistance; + newComp.walkStairStepUpDistance = comp.walkStairStepUpDistance; + newComp.crouchHeight = comp.crouchHeight; + newComp.crouchVelocity = comp.crouchVelocity; + } + + if (entity.HasComponent()) { + auto& comp = entity.GetComponent(); + RenderComponentPanel("Constraint", scene, + entity, constraintComponentPanel, comp); } if (entity.HasComponent()) { @@ -107,15 +144,17 @@ namespace Atlas::Editor::UI { } } + if (!ImguiExtension::UIElements::EndPropertySearch()) + Widgets::EmptyState("No properties match the search"); + // Add components { ImGui::Spacing(); - auto spacing = ImGui::GetStyle().ItemSpacing.x; - auto buttonWidth = (ImGui::GetContentRegionAvail().x - spacing) * 0.5f; - + // Components are removed with the trash can or the context menu of their header. The name has neither, every + // entity keeps it Theme::PushPrimaryButton(); - if (ImGui::Button("Add component", { buttonWidth, 0 })) + if (ImGui::Button("Add component", { -FLT_MIN, 0 })) ImGui::OpenPopup("AddComponent"); Theme::PopPrimaryButton(); @@ -130,10 +169,7 @@ namespace Atlas::Editor::UI { ImGui::Separator(); auto matches = [&](const char* name) { - std::string lowerName = name, lowerSearch = componentSearch; - std::transform(lowerName.begin(), lowerName.end(), lowerName.begin(), ::tolower); - std::transform(lowerSearch.begin(), lowerSearch.end(), lowerSearch.begin(), ::tolower); - return lowerName.find(lowerSearch) != std::string::npos; + return ImguiExtension::UIElements::MatchesSearch(name, componentSearch); }; if (!entity.HasComponent() && !rootNode && matches("Name") && ImGui::MenuItem("Name")) entity.AddComponent("Entity " + std::to_string(entity)); @@ -141,12 +177,16 @@ namespace Atlas::Editor::UI { entity.AddComponent(mat4(1.0f), false); if (!entity.HasComponent() && matches("Mesh") && ImGui::MenuItem("Mesh")) entity.AddComponent(); + if (!entity.HasComponent() && matches("Animation") && ImGui::MenuItem("Animation")) + entity.AddComponent(); if (!entity.HasComponent() && matches("Light") && ImGui::MenuItem("Light")) entity.AddComponent(LightType::PointLight); if (!entity.HasComponent() && matches("Audio") && ImGui::MenuItem("Audio")) entity.AddComponent(); if (!entity.HasComponent() && matches("Audio volume") && ImGui::MenuItem("Audio volume")) entity.AddComponent(); + if (!entity.HasComponent() && matches("Fog volume") && ImGui::MenuItem("Fog volume")) + entity.AddComponent(); if (!entity.HasComponent() && matches("Camera") && ImGui::MenuItem("Camera")) entity.AddComponent(); if (!entity.HasComponent() && matches("Text") && ImGui::MenuItem("Text")) @@ -184,39 +224,14 @@ namespace Atlas::Editor::UI { entity.AddComponent(bodySettings); } - ImGui::EndPopup(); - } + if (entity.HasComponent() && + !entity.HasComponent() && matches("Constraint") && ImGui::MenuItem("Constraint")) + entity.AddComponent(); - // Remove components - ImGui::SameLine(0.0f, spacing); - if (ImGui::Button("Remove component", { -FLT_MIN, 0 })) - ImGui::OpenPopup("RemoveComponent"); - - if (ImGui::BeginPopup("RemoveComponent")) { - if (entity.HasComponent() && !rootNode && ImGui::MenuItem("Name")) - entity.RemoveComponent(); - if (entity.HasComponent() && ImGui::MenuItem("Transform")) - entity.RemoveComponent(); - if (entity.HasComponent() && ImGui::MenuItem("Mesh")) - entity.RemoveComponent(); - if (entity.HasComponent() && ImGui::MenuItem("Light")) - entity.RemoveComponent(); - if (entity.HasComponent() && ImGui::MenuItem("Audio")) - entity.RemoveComponent(); - if (entity.HasComponent() && ImGui::MenuItem("Audio volume")) - entity.RemoveComponent(); - if (entity.HasComponent() && ImGui::MenuItem("Camera")) - entity.RemoveComponent(); - if (entity.HasComponent() && ImGui::MenuItem("Text")) - entity.RemoveComponent(); - if (entity.HasComponent() && ImGui::MenuItem("Lua script")) - entity.RemoveComponent(); - if (entity.HasComponent() && ImGui::MenuItem("Spline")) - entity.RemoveComponent(); - if (entity.HasComponent() && ImGui::MenuItem("Player")) - entity.RemoveComponent(); - if (entity.HasComponent() && ImGui::MenuItem("Rigid body")) - entity.RemoveComponent(); + // Soft bodies simulate the mesh of the entity + if (entity.HasComponent() && entity.HasComponent() && + !entity.HasComponent() && matches("Soft body") && ImGui::MenuItem("Soft body")) + entity.AddComponent(); ImGui::EndPopup(); } @@ -227,15 +242,19 @@ namespace Atlas::Editor::UI { if (ImGui::MenuItem("Paste")) { if (HandleComponentPaste(scene, entity)) {} else if (HandleComponentPaste(scene, entity)) {} + else if (HandleComponentPaste(scene, entity)) {} else if (HandleComponentPaste(scene, entity)) {} else if (HandleComponentPaste(scene, entity)) {} else if (HandleComponentPaste(scene, entity)) {} + else if (HandleComponentPaste(scene, entity)) {} else if (HandleComponentPaste(scene, entity)) {} else if (HandleComponentPaste(scene, entity)) {} else if (HandleComponentPaste(scene, entity)) {} else if (HandleComponentPaste(scene, entity)) {} else if (HandleComponentPaste(scene, entity)) {} else if (HandleComponentPaste(scene, entity)) {} + else if (HandleComponentPaste(scene, entity)) {} + else if (HandleComponentPaste(scene, entity)) {} else { Notifications::Push({"Invalid type to paste as a component."}); } diff --git a/src/editor/ui/panels/EntityPropertiesPanel.h b/src/editor/ui/panels/EntityPropertiesPanel.h index 67d2740b8..1dcc8af1e 100644 --- a/src/editor/ui/panels/EntityPropertiesPanel.h +++ b/src/editor/ui/panels/EntityPropertiesPanel.h @@ -6,15 +6,19 @@ #include "components/NameComponentPanel.h" #include "components/TransformComponentPanel.h" #include "components/MeshComponentPanel.h" +#include "components/AnimationComponentPanel.h" #include "components/LightComponentPanel.h" #include "components/AudioComponentPanel.h" #include "components/AudioVolumeComponentPanel.h" +#include "components/FogVolumeComponentPanel.h" #include "components/LuaScriptComponentPanel.h" #include "components/RigidBodyComponentPanel.h" +#include "components/SoftBodyComponentPanel.h" #include "components/PlayerComponentPanel.h" #include "components/CameraComponentPanel.h" #include "components/TextComponentPanel.h" #include "components/SplineComponentPanel.h" +#include "components/ConstraintComponentPanel.h" #include "components/HierarchyComponentPanel.h" #include "tools/CopyPasteHelper.h" @@ -40,18 +44,26 @@ namespace Atlas::Editor::UI { void Render(Ref& scene, EntityProperties entityProperties); + // Searches the properties of all components + std::string propertySearch; + bool focusSearch = false; + NameComponentPanel nameComponentPanel; TransformComponentPanel transformComponentPanel; MeshComponentPanel meshComponentPanel; + AnimationComponentPanel animationComponentPanel; LightComponentPanel lightComponentPanel; AudioComponentPanel audioComponentPanel; AudioVolumeComponentPanel audioVolumeComponentPanel; + FogVolumeComponentPanel fogVolumeComponentPanel; LuaScriptComponentPanel luaScriptComponentPanel; RigidBodyComponentPanel rigidBodyComponentPanel; + SoftBodyComponentPanel softBodyComponentPanel; PlayerComponentPanel playerComponentPanel; CameraComponentPanel cameraComponentPanel; TextComponentPanel textComponentPanel; SplineComponentPanel splineComponentPanel; + ConstraintComponentPanel constraintComponentPanel; HierarchyComponentPanel hierarchyComponentPanel; private: @@ -69,9 +81,12 @@ namespace Atlas::Editor::UI { Scene::Entity entity, S& panel, T& component) { bool resourceChanged = false; + if (!Widgets::BeginPropertyGroup(name.c_str())) + return false; + ImGuiTreeNodeFlags nodeFlags = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_DefaultOpen | ImGuiTreeNodeFlags_OpenOnDoubleClick | ImGuiTreeNodeFlags_SpanAvailWidth | ImGuiTreeNodeFlags_Framed | - ImGuiTreeNodeFlags_AllowOverlap; + ImGuiTreeNodeFlags_AllowOverlap | Widgets::PropertyGroupHeaderFlags(); // Component headers are neutral, the accent is reserved for selection ImGui::PushStyleColor(ImGuiCol_Header, ImGui::GetStyleColorVec4(ImGuiCol_Button)); @@ -105,15 +120,26 @@ namespace Atlas::Editor::UI { auto buttonExtent = iconSize + 2.0f; auto cursorPos = ImGui::GetCursorPos(); + auto buttonPos = ImVec2(headerMax.x - buttonExtent - ImGui::GetStyle().FramePadding.x, + headerMin.y + (headerMax.y - headerMin.y - buttonExtent) * 0.5f); + ImGui::SameLine(); - ImGui::SetCursorScreenPos(ImVec2(headerMax.x - buttonExtent - ImGui::GetStyle().FramePadding.x, - headerMin.y + (headerMax.y - headerMin.y - buttonExtent) * 0.5f)); + ImGui::SetCursorScreenPos(buttonPos); auto alpha = ImGui::IsMouseHoveringRect(headerMin, headerMax) ? 1.0f : 0.45f; ImGui::PushID(name.c_str()); if (Widgets::IconButton("Remove component", Singletons::icons->Get(IconType::Trash), iconSize, "Remove component", alpha)) removeComponent = true; + + if constexpr (std::is_same_v) { + if (component.mesh.IsValid()) { + ImGui::SetCursorScreenPos(ImVec2(buttonPos.x - buttonExtent - ImGui::GetStyle().ItemSpacing.x, buttonPos.y)); + if (Widgets::IconButton("Open in mesh editor", Singletons::icons->Get(IconType::OpenInNew), + iconSize, "Open in mesh editor", alpha)) + ContentBrowserWindow::contentToEditPath = component.mesh.GetResource()->path; + } + } ImGui::PopID(); ImGui::SetCursorPos(cursorPos); @@ -125,13 +151,17 @@ namespace Atlas::Editor::UI { pendingRemoval = [entity]() mutable { entity.RemoveComponent(); }; if (open) { + Widgets::BeginPropertyContent(); resourceChanged = panel.Render(scene, entity, component); + Widgets::EndPropertyContent(); ImGui::TreePop(); } ImGui::Spacing(); + Widgets::EndPropertyGroup(); + return resourceChanged; } @@ -143,7 +173,7 @@ namespace Atlas::Editor::UI { CopyPasteHelper::Paste(copy); if (copy.scene != scene.get()) { - Notifications::Push({ "Cannot copy component from one scene to another", vec3(1.0f, 0.0f, 0.0f) }); + Notifications::Push({ "Cannot copy component from one scene to another", NotificationType::Error }); return true; } diff --git a/src/editor/ui/panels/MaterialGraphPanel.cpp b/src/editor/ui/panels/MaterialGraphPanel.cpp new file mode 100644 index 000000000..81388f021 --- /dev/null +++ b/src/editor/ui/panels/MaterialGraphPanel.cpp @@ -0,0 +1,2497 @@ +#include "MaterialGraphPanel.h" + +#include "../../Theme.h" +#include "../../Notifications.h" +#include "../../Singletons.h" +#include "../Widgets.h" + +#include "loader/AssetLoader.h" +#include "materialgraph/MaterialGraphSerializer.h" + +#include +#include + +#include +#include +#include + +namespace Atlas::Editor::UI { + + using namespace MaterialGraph; + + std::string MaterialGraphPanel::clipboard; + + bool MaterialGraphPanel::Render(const ResourceHandle& graphHandle, const Material* material) { + + if (!graphHandle.IsLoaded()) + return false; + + auto& graph = *graphHandle.Get(); + auto compiled = graph.GetCompiled(); + currentGraph = &graph; + + ImGui::PushID(GetNameID()); + + DrawToolbar(graph, compiled.get()); + + auto inspectorSize = showInspector ? std::min(inspectorWidth, ImGui::GetContentRegionAvail().x * 0.4f) : 0.0f; + + canvasOrigin = ImGui::GetCursorScreenPos(); + canvasSize = ImGui::GetContentRegionAvail(); + // A narrow strip between canvas and inspector holds the arrow that shows and hides the inspector + const float toggleGap = 2.0f; + const float togglePadding = 3.0f; + auto toggleIconSize = std::floor(ImGui::GetTextLineHeight()); + auto toggleWidth = toggleIconSize + 2.0f * togglePadding; + canvasSize.x -= inspectorSize > 0.0f ? inspectorSize + toggleGap : 0.0f; + canvasSize.x -= toggleWidth + toggleGap; + if (canvasSize.x < 32.0f || canvasSize.y < 32.0f) { + ImGui::PopID(); + return false; + } + + ImGui::BeginChild("Canvas", canvasSize, ImGuiChildFlags_None, ImGuiWindowFlags_NoScrollbar | + ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoBackground); + + UpdateLayouts(graph); + + // New windows start tiny and the docking takes a few frames, framing during that would miss the final size + auto isCanvasStable = canvasSize.x == lastCanvasSize.x && canvasSize.y == lastCanvasSize.y; + stableCanvasFrames = isCanvasStable ? stableCanvasFrames + 1 : 0; + lastCanvasSize = canvasSize; + if (frameRequested && stableCanvasFrames >= 3) { + Frame(graph); + frameRequested = false; + UpdateLayouts(graph); + } + + auto drawList = ImGui::GetWindowDrawList(); + auto canvasMax = ImVec2(canvasOrigin.x + canvasSize.x, canvasOrigin.y + canvasSize.y); + + drawList->PushClipRect(canvasOrigin, canvasMax, true); + + DrawGrid(drawList, canvasOrigin, canvasMax); + DrawFrames(drawList, graph); + DrawLinks(drawList, graph); + DrawNodes(drawList, graph, compiled.get()); + + HandleInteractions(graph); + + // The selection box and the dragged link are on top of everything + if (interaction == Interaction::BoxSelection) { + auto mouse = ImGui::GetMousePos(); + drawList->AddRectFilled(boxStart, mouse, ImGui::ColorConvertFloat4ToU32(Theme::Accent(0.15f))); + drawList->AddRect(boxStart, mouse, ImGui::ColorConvertFloat4ToU32(Theme::Accent(0.8f))); + } + + DrawMinimap(drawList, graph, canvasOrigin, canvasMax); + + drawList->PopClipRect(); + + if (ImGui::IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows) && !ImGui::GetIO().WantTextInput) + HandleShortcuts(graphHandle); + + RenderNodeMenu(graph); + RenderAddMenu(graph); + + ImGui::EndChild(); + + ImGui::SameLine(0.0f, toggleGap); + ImGui::BeginChild("Inspector toggle", ImVec2(toggleWidth, canvasSize.y), ImGuiChildFlags_None, + ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_NoBackground); + { + auto buttonHeight = toggleIconSize + 2.0f * togglePadding; + ImGui::SetCursorPos(ImVec2(0.0f, std::max(0.0f, (canvasSize.y - buttonHeight) * 0.5f))); + + // The arrow points where the inspector goes + auto& arrow = Singletons::icons->Get(showInspector ? IconType::ArrowRight : IconType::ArrowLeft); + ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.0f, 0.0f, 0.0f, 0.0f)); + ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 0.0f); + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(togglePadding, togglePadding)); + if (ImGui::ImageButton("Toggle inspector", Singletons::imguiWrapper->GetTextureId(&arrow), + ImVec2(toggleIconSize, toggleIconSize), ImVec2(0.1f, 0.1f), ImVec2(0.9f, 0.9f))) + showInspector = !showInspector; + ImGui::PopStyleVar(2); + ImGui::PopStyleColor(); + ImGui::SetItemTooltip(showInspector ? "Hide the inspector" : "Show the inspector"); + } + ImGui::EndChild(); + + if (inspectorSize > 0.0f) { + ImGui::SameLine(0.0f, toggleGap); + ImGui::BeginChild("Inspector", ImVec2(inspectorSize, canvasSize.y), ImGuiChildFlags_Borders); + DrawInspector(graph); + ImGui::EndChild(); + } + + DrawCodeWindow(compiled.get()); + + // Edited code is compiled once the editor loses the focus or shows another node + if (editedCodeNode && (codeNodeEditor.IsDeactivatedAfterEdit() || shownCodeNode != editedCodeNode)) { + if (auto node = graph.GetNode(editedCodeNode)) + NodeLibrary::UpdateCodeDefinition(*node); + compileRequested = true; + editedCodeNode = 0; + } + shownCodeNode = 0; + + ImGui::PopID(); + + previews.Render(graph, material); + + if (colorEdited && !ImGui::IsMouseDown(ImGuiMouseButton_Left)) { + colorEdited = false; + compileRequested = true; + } + + if (compileRequested) { + graph.Compile(); + previews.Invalidate(); + compileRequested = false; + modified = true; + return true; + } + + return false; + + } + + namespace { + + // A rounded label in the color of what it stands for. Pills follow each other and wrap at the end of the line + void Pill(const char* text, ImVec4 color, const char* tooltip, bool& first) { + + const ImVec2 padding(8.0f, 3.0f); + auto textSize = ImGui::CalcTextSize(text); + auto size = ImVec2(textSize.x + 2.0f * padding.x, textSize.y + 2.0f * padding.y); + + if (!first) { + ImGui::SameLine(0.0f, 6.0f); + if (ImGui::GetCursorPosX() + size.x > ImGui::GetContentRegionMax().x) + ImGui::NewLine(); + } + first = false; + + auto position = ImGui::GetCursorScreenPos(); + ImGui::PushID(text); + ImGui::InvisibleButton("##Pill", size); + ImGui::PopID(); + ImGui::SetItemTooltip("%s", tooltip); + + auto drawList = ImGui::GetWindowDrawList(); + auto max = ImVec2(position.x + size.x, position.y + size.y); + auto rounding = size.y * 0.5f; + auto fill = color; + fill.w *= ImGui::IsItemHovered() ? 0.3f : 0.18f; + auto border = color; + border.w *= 0.6f; + drawList->AddRectFilled(position, max, ImGui::GetColorU32(fill), rounding); + drawList->AddRect(position, max, ImGui::GetColorU32(border), rounding); + drawList->AddText(ImVec2(position.x + padding.x, position.y + padding.y), ImGui::GetColorU32(color), text); + + } + + // Transparent icon button with the frame padding of the row, so it is as high as the text next to it + bool InspectorIconButton(const char* id, IconType iconType, const char* tooltip) { + + auto& icon = Singletons::icons->Get(iconType); + auto size = ImGui::GetTextLineHeight(); + ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.0f, 0.0f, 0.0f, 0.0f)); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(1.0f, 1.0f, 1.0f, 0.15f)); + ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(1.0f, 1.0f, 1.0f, 0.25f)); + ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 0.0f); + auto pressed = ImGui::ImageButton(id, Singletons::imguiWrapper->GetTextureId(&icon), ImVec2(size, size), + ImVec2(0.1f, 0.1f), ImVec2(0.9f, 0.9f)); + ImGui::PopStyleVar(); + ImGui::PopStyleColor(3); + ImGui::SetItemTooltip("%s", tooltip); + return pressed; + + } + + // The default of a parameter or the value of a constant in short, for the list of parameters + std::string FormatValue(const Node& node, const NodeDefinition& definition) { + + char buffer[96]; + switch (definition.valueType) { + case ValueType::Float: snprintf(buffer, sizeof(buffer), "%.3g", node.value.x); break; + case ValueType::Vec2: snprintf(buffer, sizeof(buffer), "%.3g, %.3g", node.value.x, node.value.y); break; + case ValueType::Vec3: snprintf(buffer, sizeof(buffer), "%.3g, %.3g, %.3g", node.value.x, node.value.y, node.value.z); break; + case ValueType::Vec4: snprintf(buffer, sizeof(buffer), "%.2g, %.2g, %.2g, %.2g", node.value.x, node.value.y, + node.value.z, node.value.w); break; + case ValueType::Texture: + return node.texture.IsValid() ? node.texture.GetResource()->GetFileName() : "No texture"; + default: buffer[0] = 0; break; + } + return buffer; + + } + + } + + void MaterialGraphPanel::DrawInspector(Graph& graph) { + + Node* selected = nullptr; + if (selection.size() == 1) + selected = graph.GetNode(*selection.begin()); + + if (!selected) { + DrawGraphOverview(graph); + return; + } + + auto definition = NodeLibrary::Find(*selected); + if (!definition) + return; + + // Header in the color of the node on the canvas: back to the overview, the name and the type of the node + auto isNamed = (definition->kind == NodeKind::Parameter || definition->kind == NodeKind::Frame) && !selected->name.empty(); + auto title = isNamed ? selected->name : selected->type; + auto subtitle = isNamed ? selected->type : definition->category; + { + auto drawList = ImGui::GetWindowDrawList(); + const float inset = 4.0f; + auto start = ImGui::GetCursorScreenPos(); + auto width = ImGui::GetContentRegionAvail().x; + auto height = ImGui::GetFrameHeight() + 2.0f * inset; + drawList->AddRectFilled(start, ImVec2(start.x + width, start.y + height), + ImGui::GetColorU32(Theme::GraphNodeHeader(definition->category.c_str())), 6.0f); + + ImGui::SetCursorScreenPos(ImVec2(start.x + inset, start.y + inset)); + if (InspectorIconButton("Back to overview", IconType::ArrowLeft, "Back to the overview of the graph")) { + selection.clear(); + return; + } + ImGui::SameLine(); + ImGui::AlignTextToFramePadding(); + ImGui::TextUnformatted(title.c_str()); + auto subtitleWidth = ImGui::CalcTextSize(subtitle.c_str()).x; + auto subtitleX = start.x + width - inset - ImGui::GetStyle().FramePadding.x - subtitleWidth; + if (subtitleX > ImGui::GetItemRectMax().x + 8.0f) { + ImGui::SameLine(); + ImGui::SetCursorScreenPos(ImVec2(subtitleX, ImGui::GetCursorScreenPos().y)); + ImGui::TextColored(ImVec4(1.0f, 1.0f, 1.0f, 0.65f), "%s", subtitle.c_str()); + } + ImGui::SetCursorScreenPos(ImVec2(start.x, start.y + height + ImGui::GetStyle().ItemSpacing.y)); + } + + ImGui::PushTextWrapPos(); + ImGui::TextColored(Theme::TextMuted(), "%s", definition->tooltip.c_str()); + ImGui::PopTextWrapPos(); + ImGui::Spacing(); + + if (definition->kind == NodeKind::Comment) { + auto edited = false; + Widgets::TextArea("Comment text", selected->name, 14.0f, 0, &edited); + if (edited) + modified = true; + return; + } + + if (!Widgets::BeginProperties("Node properties")) + return; + + if (definition->kind == NodeKind::Frame) { + Widgets::PropertyLabel("Title"); + ImGui::InputText("##Title", &selected->name); + if (ImGui::IsItemDeactivatedAfterEdit()) + modified = true; + } + + auto compiled = definition->kind != NodeKind::Frame ? graph.GetCompiled() : nullptr; + if (compiled) { + auto iter = compiled->nodeStages.find(selected->id); + auto stages = iter != compiled->nodeStages.end() ? iter->second : 0u; + Widgets::PropertyLabel("Stages", "The shaders this node ends up in"); + if (!stages) { + ImGui::AlignTextToFramePadding(); + ImGui::TextColored(Theme::TextMuted(), "Not used"); + ImGui::SetItemTooltip("The node doesn't lead to an output, it costs nothing"); + } + auto first = true; + if (stages & VertexStage) + Pill("Vertex", Theme::Success(), "Evaluated for every vertex", first); + if (stages & SurfaceStage) + Pill("Fragment", Theme::Accent(), "Evaluated for every fragment", first); + } + + if (definition->kind == NodeKind::Parameter) { + Widgets::PropertyLabel("Name", "Materials show the parameter with this name"); + ImGui::InputText("##Name", &selected->name); + if (ImGui::IsItemDeactivatedAfterEdit()) + compileRequested = true; + } + + // Defaults of parameters aren't part of the code and apply while dragging, constants compile once the value is final + auto hasValue = (definition->kind == NodeKind::Parameter || definition->kind == NodeKind::Constant) && + definition->valueType != ValueType::Texture; + if (hasValue) { + auto isParameter = definition->kind == NodeKind::Parameter; + Widgets::PropertyLabel(isParameter ? "Default" : "Value", isParameter ? "Materials use this value until they set their own" : + "Baked into the shaders, changing it compiles them again"); + int32_t components = definition->valueType == ValueType::Vec2 ? 2 : definition->valueType == ValueType::Vec3 ? 3 : + definition->valueType == ValueType::Vec4 ? 4 : 1; + auto changed = false; + if (definition->isColor) + changed = ImGui::ColorEdit3("##Value", &selected->value.x, ImGuiColorEditFlags_Float); + else if (selected->range.x < selected->range.y) + changed = ImGui::DragScalarN("##Value", ImGuiDataType_Float, &selected->value.x, components, 0.01f, + &selected->range.x, &selected->range.y, "%.3g", ImGuiSliderFlags_AlwaysClamp); + else + changed = ImGui::DragScalarN("##Value", ImGuiDataType_Float, &selected->value.x, components, 0.01f, + nullptr, nullptr, "%.3g"); + if (isParameter ? changed : ImGui::IsItemDeactivatedAfterEdit()) + compileRequested = true; + else + colorEdited |= definition->isColor && changed; + } + + if (definition->kind == NodeKind::StaticSwitch) { + auto isOn = selected->value.x > 0.0f; + Widgets::PropertyLabel("Selected", "Only the selected input is compiled. Changing it applies to all materials with the graph"); + if (ImGui::Checkbox("On##Switch", &isOn)) { + selected->value.x = isOn ? 1.0f : 0.0f; + compileRequested = true; + } + } + + if (definition->kind == NodeKind::Parameter) { + if (definition->valueType != ValueType::Texture && !definition->isColor) { + Widgets::PropertyLabel("Range", "Materials get a slider within these limits. Without a range the values are free"); + ImGui::DragFloatRange2("##Range", &selected->range.x, &selected->range.y, 0.01f, 0.0f, 0.0f, "Min %.3g", "Max %.3g"); + if (ImGui::IsItemDeactivatedAfterEdit()) + compileRequested = true; + } + + Widgets::PropertyLabel("Group", "Materials show parameters of the same group below a heading"); + ImGui::InputTextWithHint("##Group", "No group", &selected->group); + if (ImGui::IsItemDeactivatedAfterEdit()) + compileRequested = true; + + Widgets::PropertyLabel("Order", "Materials show smaller numbers first"); + ImGui::DragInt("##Order", &selected->order, 0.1f); + if (ImGui::IsItemDeactivatedAfterEdit()) + compileRequested = true; + } + + if (definition->kind == NodeKind::Parameter && definition->valueType == ValueType::Texture) { + Widgets::PropertyLabel("Default", "Materials use this texture until they select their own"); + auto textureChanged = false; + auto texture = textureSelectionPanel.Render(selected->texture, textureChanged); + textureSelectionPanel.Reset(); + if (textureChanged) { + selected->texture = texture; + compileRequested = true; + } + + const char* fallbacks[] = { "White", "Black", "Flat normal" }; + auto fallback = int32_t(selected->value.y); + Widgets::PropertyLabel("Fallback", "What the shaders read while neither the material nor the default has a texture"); + if (ImGui::Combo("##Fallback", &fallback, fallbacks, IM_ARRAYSIZE(fallbacks))) { + selected->value.y = float(fallback); + compileRequested = true; + } + + Widgets::PropertyLabel("Coordinate scale", "How much the graph scales the texture coordinates. The texture streaming " + "loads more detail for textures which repeat more often"); + ImGui::DragFloat("##Coordinate scale", &selected->value.x, 0.1f, 0.01f, 1000.0f); + if (ImGui::IsItemDeactivatedAfterEdit()) + compileRequested = true; + } + + if (definition->kind == NodeKind::VertexOutput) { + auto derive = selected->value.x > 0.0f; + Widgets::PropertyLabel("Derive normals", "Evaluates the displacement next to each vertex to find the normal of the moved " + "surface. This works for displacement from positions, not from texture coordinates"); + if (ImGui::Checkbox("##Derive normals", &derive)) { + selected->value.x = derive ? 1.0f : 0.0f; + compileRequested = true; + } + + Widgets::PropertyLabel("Sampling distance", "How far next to each vertex the displacement is evaluated for the normals"); + ImGui::BeginDisabled(!derive); + ImGui::DragFloat("##Sampling distance", &selected->value.y, 0.001f, 0.001f, 10.0f); + if (ImGui::IsItemDeactivatedAfterEdit()) + compileRequested = true; + ImGui::EndDisabled(); + } + + auto isCode = selected->type == NodeLibrary::codeType; + auto codeChanged = false; + if (isCode) { + const char* types[] = { "Float", "Vector 2", "Vector 3", "Vector 4" }; + auto outputType = int32_t(selected->codeOutputType); + Widgets::PropertyLabel("Result", "Type of the value the code returns"); + if (ImGui::Combo("##Result", &outputType, types, IM_ARRAYSIZE(types))) { + selected->codeOutputType = ValueType(outputType); + codeChanged = true; + } + + int32_t removedInput = -1; + for (size_t i = 0; i < selected->codeInputs.size(); i++) { + auto& input = selected->codeInputs[i]; + ImGui::PushID(int32_t(i)); + Widgets::PropertyLabel("Input", "An argument of the code with its name and type"); + auto buttonWidth = ImGui::GetFrameHeight(); + auto width = ImGui::GetContentRegionAvail().x - buttonWidth - 2.0f * ImGui::GetStyle().ItemSpacing.x; + ImGui::SetNextItemWidth(width * 0.55f); + ImGui::InputText("##Name", &input.name); + if (ImGui::IsItemActivated()) + renamedCodeInput = input.name; + if (ImGui::IsItemDeactivatedAfterEdit() && input.name != renamedCodeInput) { + // Links and values stay on the renamed input + for (auto& link : graph.links) { + if (link.toNode == selected->id && link.toPin == renamedCodeInput) + link.toPin = input.name; + } + if (selected->inputValues.contains(renamedCodeInput)) { + selected->inputValues[input.name] = selected->inputValues[renamedCodeInput]; + selected->inputValues.erase(renamedCodeInput); + } + codeChanged = true; + } + ImGui::SameLine(); + ImGui::SetNextItemWidth(width * 0.45f); + auto inputType = int32_t(input.type); + if (ImGui::Combo("##Type", &inputType, types, IM_ARRAYSIZE(types))) { + input.type = ValueType(inputType); + codeChanged = true; + } + ImGui::SameLine(); + if (InspectorIconButton("Remove input", IconType::Trash, "Removes the input and its link")) + removedInput = int32_t(i); + ImGui::PopID(); + } + + if (removedInput >= 0) { + const auto& name = selected->codeInputs[removedInput].name; + graph.Disconnect(selected->id, name); + selected->inputValues.erase(name); + selected->codeInputs.erase(selected->codeInputs.begin() + removedInput); + codeChanged = true; + } + + Widgets::PropertyLabel("##Add input"); + if (ImGui::Button("Add input")) + ImGui::OpenPopup("Add code input"); + + if (ImGui::BeginPopup("Add code input")) { + auto uniqueName = [&](const std::string& name, bool numbered) { + auto isUsed = [&](const std::string& candidate) { + return std::any_of(selected->codeInputs.begin(), selected->codeInputs.end(), + [&](const CodeInput& input) { return input.name == candidate; }); + }; + auto candidate = numbered ? name + "0" : name; + for (int32_t index = 1; isUsed(candidate); index++) + candidate = name + std::to_string(index); + return candidate; + }; + + if (ImGui::MenuItem("Empty input")) { + // Input alone is a reserved word in GLSL + selected->codeInputs.push_back({ uniqueName("input", true), ValueType::Float }); + codeChanged = true; + } + + // The code can't read scene data, an input node is connected to a new input instead + ImGui::SeparatorText("Connected to scene data"); + for (const auto& inputDefinition : NodeLibrary::GetDefinitions()) { + if (inputDefinition.category != "Input" || inputDefinition.outputs.empty()) + continue; + if (!ImGui::MenuItem(inputDefinition.type.c_str())) + continue; + + std::string name; + auto capitalize = false; + for (auto c : inputDefinition.type) { + if (c == ' ') { + capitalize = true; + continue; + } + name += capitalize ? char(std::toupper(c)) : char(std::tolower(c)); + capitalize = false; + } + name = uniqueName(name, false); + selected->codeInputs.push_back({ name, inputDefinition.outputs.front().type }); + + // The graph might move its nodes in memory when one is added + auto codeNodeId = selected->id; + auto position = selected->position - vec2(nodeWidth + 60.0f, -60.0f * float(selected->codeInputs.size() - 1)); + auto inputNodeId = graph.AddNode(inputDefinition.type, position).id; + selected = graph.GetNode(codeNodeId); + NodeLibrary::UpdateCodeDefinition(*selected); + graph.Connect(inputNodeId, inputDefinition.outputs.front().name, codeNodeId, name); + codeChanged = true; + } + ImGui::EndPopup(); + } + + auto signature = NodeLibrary::GetTypeName(selected->codeOutputType) + " Code(" + NodeLibrary::GetCodeParameters(*selected) + ")"; + Widgets::PropertyLabel("Signature", "The code is the body of this function and returns the result"); + ImGui::PushFont(Theme::codeFont ? Theme::codeFont : ImGui::GetFont()); + ImGui::PushTextWrapPos(); + ImGui::AlignTextToFramePadding(); + ImGui::TextUnformatted(signature.c_str()); + ImGui::PopTextWrapPos(); + ImGui::PopFont(); + } + + Widgets::EndProperties(); + + if (isCode) { + if (!codeFunctionCompletionsLoaded) + LoadCodeFunctionCompletions(); + // Only called within the render of the editor below, while the node is still valid + codeNodeEditor.completionProvider = [this, selected](const CodeCompletionContext& context) { + std::vector completions; + if (context.separator) + return completions; + for (const auto& input : selected->codeInputs) + completions.push_back({ input.name, "Input", NodeLibrary::GetTypeName(input.type) + " " + input.name, "An input of the code" }); + completions.insert(completions.end(), codeFunctionCompletions.begin(), codeFunctionCompletions.end()); + return completions; + }; + + // The lower edge can be dragged to resize the editor + ImGui::BeginChild("Code", ImVec2(-FLT_MIN, 16.0f * ImGui::GetTextLineHeightWithSpacing()), ImGuiChildFlags_ResizeY); + // Each node has its own id, the editor starts again for another node + if (codeNodeEditor.Render(("##Code" + std::to_string(selected->id)).c_str(), selected->code)) + editedCodeNode = selected->id; + ImGui::EndChild(); + shownCodeNode = selected->id; + } + + if (codeChanged) { + NodeLibrary::UpdateCodeDefinition(*selected); + compileRequested = true; + } + + } + + void MaterialGraphPanel::DrawGraphOverview(Graph& graph) { + + auto compiled = graph.GetCompiled(); + + if (selection.size() > 1) { + ImGui::TextColored(Theme::TextMuted(), "%d nodes selected", int32_t(selection.size())); + ImGui::Spacing(); + } + + // A click selects the node and moves it into the middle of the canvas, the zoom stays + auto showNode = [&](uint32_t nodeId) { + auto node = graph.GetNode(nodeId); + if (!node) + return; + selection.clear(); + selection.insert(nodeId); + auto center = node->position + GetNodeSize(*node) * 0.5f; + pan = vec2(canvasSize.x, canvasSize.y) * 0.5f / zoom - center; + }; + + // What the compiled graph does, the toolbar only names the kind of graph + if (Widgets::SectionHeader("Output", ImGuiTreeNodeFlags_DefaultOpen)) { + ImGui::PushTextWrapPos(); + if (!compiled) + ImGui::TextColored(Theme::TextMuted(), "Not compiled yet"); + else if (!compiled->valid) + ImGui::TextColored(Theme::Error(), "The graph has errors, materials use their regular properties"); + else if (!compiled->hasVertexOffset && !compiled->hasSurface) + ImGui::TextColored(Theme::TextMuted(), "No output is connected, materials use their regular properties"); + ImGui::PopTextWrapPos(); + + // Only what the graph does, aspects it doesn't change aren't shown + if (compiled && compiled->valid && (compiled->hasVertexOffset || compiled->hasSurface)) { + auto first = true; + if (compiled->hasVertexOffset) + Pill("Moves vertices", Theme::Success(), "The vertex output moves the vertices of the mesh. " + "Set the largest displacement, culling needs it", first); + if (compiled->hasSurface) + Pill("Surface", Theme::Accent(), "The surface output describes the surface. Ray tracing uses the regular " + "properties or a bake of the graph", first); + if (compiled->hasUniformOpacity) + Pill("Cutout per draw", Theme::Accent(), "Opacity only depends on parameters and constants: it is evaluated " + "per vertex and hides the whole draw, fragments stay as fast as opaque ones", first); + else if (compiled->hasOpacity) + Pill("Cutout per fragment", Theme::Warning(), "Opacity varies over the surface: fragments are cut out, which " + "turns off early depth tests and costs time even where nothing is cut out", first); + if (compiled->UsesShadowPipeline()) + Pill("Own shadows", Theme::Accent(), "Moved vertices or cut out fragments need their own shadow shaders, " + "otherwise shadows use the regular pipeline", first); + } + + // Only graphs moving vertices need it, a value from before stays editable to remove it + auto showDisplacement = (compiled && compiled->hasVertexOffset) || graph.maxDisplacement > 0.0f; + if (showDisplacement && Widgets::BeginProperties("Output")) { + Widgets::PropertyLabel("Displacement", "Largest distance a vertex moves in the space of the mesh. Culling adds this to " + "the bounds, otherwise moved vertices disappear at the edges of the screen"); + ImGui::DragFloat("##Largest displacement", &graph.maxDisplacement, 0.01f, 0.0f, 1000.0f, "%.3f"); + if (ImGui::IsItemDeactivatedAfterEdit()) + compileRequested = true; + Widgets::EndProperties(); + } + ImGui::Spacing(); + } + + if (compiled && !compiled->errors.empty()) { + auto errorsTitle = "Errors (" + std::to_string(compiled->errors.size()) + ")###Errors"; + if (Widgets::SectionHeader(errorsTitle.c_str(), ImGuiTreeNodeFlags_DefaultOpen)) { + ImGui::PushTextWrapPos(); + for (const auto& error : compiled->errors) { + ImGui::TextColored(Theme::Error(), "%s", error.message.c_str()); + // Errors of the whole graph have no node to show + if (error.nodeId == 0 || !graph.GetNode(error.nodeId)) + continue; + if (ImGui::IsItemHovered()) { + ImGui::SetMouseCursor(ImGuiMouseCursor_Hand); + ImGui::SetTooltip("Show the node"); + } + if (ImGui::IsItemClicked()) + showNode(error.nodeId); + } + ImGui::PopTextWrapPos(); + ImGui::Spacing(); + } + } + + // Parameters in the order materials show them: ungrouped first like in the material, then by group and order + std::vector parameters; + for (const auto& node : graph.nodes) { + auto definition = NodeLibrary::Find(node); + if (definition && definition->kind == NodeKind::Parameter) + parameters.push_back(&node); + } + std::stable_sort(parameters.begin(), parameters.end(), [](const Node* a, const Node* b) { + if (a->group != b->group) + return a->group < b->group; + return a->order < b->order; + }); + + auto parametersTitle = "Parameters (" + std::to_string(parameters.size()) + ")###Parameters"; + if (Widgets::SectionHeader(parametersTitle.c_str(), ImGuiTreeNodeFlags_DefaultOpen)) { + if (parameters.empty()) { + ImGui::PushTextWrapPos(); + ImGui::TextColored(Theme::TextMuted(), "No parameters, materials can't change anything without compiling"); + ImGui::PopTextWrapPos(); + } + + auto drawList = ImGui::GetWindowDrawList(); + auto rowHeight = ImGui::GetFrameHeight(); + for (size_t start = 0; start < parameters.size();) { + const auto& group = parameters[start]->group; + auto end = start; + while (end < parameters.size() && parameters[end]->group == group) + end++; + + auto isOpen = true; + if (!group.empty()) { + auto label = group + " (" + std::to_string(end - start) + ")###Group" + group; + isOpen = ImGui::TreeNodeEx(label.c_str(), ImGuiTreeNodeFlags_NoTreePushOnOpen | + ImGuiTreeNodeFlags_SpanAvailWidth | ImGuiTreeNodeFlags_DefaultOpen); + } + + // Rows of a group start below its title, tighter than the default spacing + auto indent = group.empty() ? 0.0f : ImGui::GetTreeNodeToLabelSpacing() - 12.0f; + if (isOpen && indent > 0.0f) + ImGui::Indent(indent); + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(ImGui::GetStyle().ItemSpacing.x, 1.0f)); + for (auto i = start; isOpen && i < end; i++) { + auto parameter = parameters[i]; + auto definition = NodeLibrary::Find(*parameter); + auto isUsed = !compiled || compiled->nodeStages.contains(parameter->id); + auto alpha = isUsed ? 1.0f : 0.45f; + + ImGui::PushID(int32_t(parameter->id)); + auto position = ImGui::GetCursorScreenPos(); + auto width = ImGui::GetContentRegionAvail().x; + if (ImGui::Selectable("##Parameter", false, ImGuiSelectableFlags_SpanAvailWidth, ImVec2(0.0f, rowHeight))) + showNode(parameter->id); + ImGui::SetItemTooltip(isUsed ? "Show the node" : "Not connected to an output, materials don't show it"); + ImGui::PopID(); + + // Type as a dot in the color of its pins, the name and the default on the right + auto centerY = position.y + rowHeight * 0.5f; + auto textY = centerY - ImGui::GetTextLineHeight() * 0.5f; + auto typeColor = GetValueColor(definition->valueType); + typeColor.w *= alpha; + drawList->AddCircleFilled(ImVec2(position.x + 10.0f, centerY), 4.0f, ImGui::GetColorU32(typeColor)); + auto name = parameter->name.empty() ? std::string("Unnamed") : parameter->name; + auto textColor = ImGui::GetStyleColorVec4(ImGuiCol_Text); + textColor.w *= alpha; + drawList->AddText(ImVec2(position.x + 22.0f, textY), ImGui::GetColorU32(textColor), name.c_str()); + + auto right = position.x + width - 6.0f; + if (definition->isColor) { + auto swatch = rowHeight - 10.0f; + auto color = ImVec4(parameter->value.x, parameter->value.y, parameter->value.z, alpha); + auto min = ImVec2(right - swatch * 1.6f, centerY - swatch * 0.5f); + auto max = ImVec2(right, centerY + swatch * 0.5f); + drawList->AddRectFilled(min, max, ImGui::GetColorU32(color), 3.0f); + drawList->AddRect(min, max, ImGui::GetColorU32(Theme::TextMuted(0.4f * alpha)), 3.0f); + } + else { + auto value = FormatValue(*parameter, *definition); + auto valueWidth = ImGui::CalcTextSize(value.c_str()).x; + drawList->AddText(ImVec2(right - valueWidth, textY), ImGui::GetColorU32(Theme::TextMuted(alpha)), value.c_str()); + } + } + + ImGui::PopStyleVar(); + if (isOpen && indent > 0.0f) + ImGui::Unindent(indent); + + start = end; + } + } + + ImGui::Spacing(); + ImGui::TextColored(Theme::TextMuted(0.7f), "Select a node to see its properties"); + + } + + bool MaterialGraphPanel::HasPreview(const NodeDefinition& definition) const { + + if (previewMode == PreviewMode::None || definition.kind == NodeKind::Comment || definition.kind == NodeKind::Frame || + definition.kind == NodeKind::Reroute) + return false; + + if (previewMode == PreviewMode::All) + return true; + + if (definition.kind == NodeKind::Parameter) + return definition.valueType == ValueType::Texture; + + return definition.kind == NodeKind::SurfaceOutput || definition.category == "Texture" || definition.category == "Procedural" || + definition.category == "Normal" || definition.category == "Coordinates" || definition.category == "Logic"; + + } + + void MaterialGraphPanel::Reset() { + + selection.clear(); + layouts.clear(); + movedWithFrames.clear(); + + interaction = Interaction::None; + draggedPin = PinRef(); + pendingPin = PinRef(); + resizedFrame = 0; + nodesMoved = false; + + compileRequested = false; + colorEdited = false; + modified = false; + + previews.Reset(); + + } + + void MaterialGraphPanel::FrameAll() { + + frameRequested = true; + + } + + void MaterialGraphPanel::OpenAddMenu() { + + openAddMenu = true; + pendingPin = PinRef(); + addPosition = ToCanvas(ImVec2(canvasOrigin.x + canvasSize.x * 0.5f, canvasOrigin.y + canvasSize.y * 0.5f)); + + } + + void MaterialGraphPanel::ShowGeneratedCode() { + + showCode = true; + + } + + void MaterialGraphPanel::OnGraphRestored(const Graph& graph) { + + std::erase_if(selection, [&](uint32_t id) { return graph.GetNode(id) == nullptr; }); + compileRequested = true; + modified = true; + + } + + ImVec2 MaterialGraphPanel::ToScreen(vec2 position) const { + + auto screen = (position + pan) * zoom; + return ImVec2(canvasOrigin.x + screen.x, canvasOrigin.y + screen.y); + + } + + vec2 MaterialGraphPanel::ToCanvas(ImVec2 position) const { + + return vec2(position.x - canvasOrigin.x, position.y - canvasOrigin.y) / zoom - pan; + + } + + void MaterialGraphPanel::UpdateLayouts(Graph& graph) { + + std::erase_if(layouts, [&](const auto& item) { return graph.GetNode(item.first) == nullptr; }); + + for (const auto& node : graph.nodes) { + auto definition = NodeLibrary::Find(node); + auto& layout = layouts[node.id]; + + layout.rows.clear(); + layout.outputPins.clear(); + layout.inputPins.clear(); + + if (definition && definition->kind == NodeKind::Frame) { + layout.min = ToScreen(node.position); + layout.max = ImVec2(layout.min.x + node.size.x * zoom, layout.min.y + node.size.y * zoom); + layout.headerHeight = frameHeaderHeight * zoom; + continue; + } + + if (definition && definition->kind == NodeKind::Reroute) { + layout.min = ToScreen(node.position); + layout.max = ImVec2(layout.min.x + rerouteSize * zoom, layout.min.y + rerouteSize * zoom); + layout.headerHeight = 0.0f; + auto centerY = 0.5f * (layout.min.y + layout.max.y); + layout.outputPins[definition->outputs.front().name + std::string()] = ImVec2(layout.max.x, centerY); + layout.inputPins[definition->inputs.front().name] = ImVec2(layout.min.x, centerY); + continue; + } + + auto scaledRow = rowHeight * zoom; + layout.headerHeight = scaledRow * (definition && definition->kind == NodeKind::Parameter ? 1.75f : 1.15f); + + if (definition) { + if (definition->kind == NodeKind::Comment) + layout.rows.push_back({ .kind = RowKind::Text, .height = scaledRow * 3.0f }); + if (definition->kind == NodeKind::Constant || definition->kind == NodeKind::Parameter) { + if (definition->valueType != ValueType::Texture) + layout.rows.push_back({ .kind = RowKind::Value, .height = scaledRow }); + } + if (definition->kind == NodeKind::StaticSwitch) + layout.rows.push_back({ .kind = RowKind::Value, .height = scaledRow }); + for (const auto& output : definition->outputs) + layout.rows.push_back({ .kind = RowKind::Output, .output = &output, .height = scaledRow }); + for (const auto& input : definition->inputs) { + auto hasWideWidget = (input.type == ValueType::Vec2 || input.type == ValueType::Vec3 || input.type == ValueType::Vec4) && + input.defaultExpression.empty() && !graph.GetInputLink(node.id, input.name); + layout.rows.push_back({ .kind = RowKind::Input, .input = &input, .height = scaledRow * (hasWideWidget ? 2.0f : 1.0f) }); + } + if (HasPreview(*definition)) + layout.rows.push_back({ .kind = RowKind::Preview, .height = previewHeight * zoom }); + } + + auto height = layout.headerHeight + 8.0f * zoom; + for (const auto& row : layout.rows) + height += row.height; + + layout.min = ToScreen(node.position); + layout.max = ImVec2(layout.min.x + nodeWidth * zoom, layout.min.y + height); + + auto y = layout.min.y + layout.headerHeight + 4.0f * zoom; + for (const auto& row : layout.rows) { + auto center = y + std::min(row.height, scaledRow) * 0.5f; + if (row.kind == RowKind::Output) + layout.outputPins[row.output->name] = ImVec2(layout.max.x, center); + else if (row.kind == RowKind::Input) + layout.inputPins[row.input->name] = ImVec2(layout.min.x, center); + y += row.height; + } + } + + } + + void MaterialGraphPanel::DrawGrid(ImDrawList* drawList, ImVec2 min, ImVec2 max) { + + drawList->AddRectFilled(min, max, ImGui::ColorConvertFloat4ToU32(Theme::GraphBackground())); + + // Coarser lines when zoomed out, otherwise they fill the whole canvas + auto baseStep = 32.0f; + while (baseStep * zoom < 16.0f) + baseStep *= 4.0f; + auto step = baseStep * zoom; + auto minor = ImGui::ColorConvertFloat4ToU32(Theme::GraphGrid(0.5f)); + auto major = ImGui::ColorConvertFloat4ToU32(Theme::GraphGrid(1.0f)); + + auto start = ToScreen(vec2(0.0f)); + auto firstX = std::fmod(start.x - min.x, step); + auto firstY = std::fmod(start.y - min.y, step); + + for (float x = firstX; x < max.x - min.x; x += step) { + auto index = int32_t(std::round((min.x + x - start.x) / step)); + drawList->AddLine(ImVec2(min.x + x, min.y), ImVec2(min.x + x, max.y), index % 4 == 0 ? major : minor); + } + for (float y = firstY; y < max.y - min.y; y += step) { + auto index = int32_t(std::round((min.y + y - start.y) / step)); + drawList->AddLine(ImVec2(min.x, min.y + y), ImVec2(max.x, min.y + y), index % 4 == 0 ? major : minor); + } + + } + + static void DrawCurve(ImDrawList* drawList, ImVec2 from, ImVec2 to, ImU32 color, float thickness, float zoom) { + + auto distance = std::max(std::abs(to.x - from.x) * 0.5f, 40.0f * zoom); + drawList->AddBezierCubic(from, ImVec2(from.x + distance, from.y), ImVec2(to.x - distance, to.y), to, color, thickness); + + } + + void MaterialGraphPanel::DrawFrames(ImDrawList* drawList, Graph& graph) { + + auto font = ImGui::GetFont(); + + for (const auto& node : graph.nodes) { + auto definition = NodeLibrary::Find(node); + if (!definition || definition->kind != NodeKind::Frame) + continue; + + const auto& layout = layouts[node.id]; + auto rounding = 8.0f * zoom; + auto isSelected = selection.contains(node.id); + + drawList->AddRectFilled(layout.min, layout.max, ImGui::ColorConvertFloat4ToU32(Theme::Accent(0.06f)), rounding); + drawList->AddRectFilled(layout.min, ImVec2(layout.max.x, layout.min.y + layout.headerHeight), + ImGui::ColorConvertFloat4ToU32(Theme::Accent(0.18f)), rounding, ImDrawFlags_RoundCornersTop); + drawList->AddRect(layout.min, layout.max, ImGui::ColorConvertFloat4ToU32(isSelected ? Theme::Accent() : Theme::Accent(0.35f)), rounding, 0, + isSelected ? 2.0f : 1.0f); + + // Titles stay readable when zoomed out, they are what is left to read then + auto fontSize = std::max(ImGui::GetFontSize() * 1.4f * zoom, 15.0f); + auto clip = ImVec4(layout.min.x, layout.min.y, layout.max.x, layout.max.y); + drawList->AddText(font, fontSize, ImVec2(layout.min.x + 8.0f * zoom, layout.min.y + 4.0f * zoom), + ImGui::ColorConvertFloat4ToU32(ImGui::GetStyleColorVec4(ImGuiCol_Text)), node.name.empty() ? "Frame" : node.name.c_str(), nullptr, 0.0f, &clip); + + auto corner = 12.0f * zoom; + drawList->AddTriangleFilled(ImVec2(layout.max.x, layout.max.y - corner), layout.max, ImVec2(layout.max.x - corner, layout.max.y), + ImGui::ColorConvertFloat4ToU32(Theme::Accent(0.5f))); + } + + } + + void MaterialGraphPanel::DrawLinks(ImDrawList* drawList, Graph& graph) { + + auto mouse = ImGui::GetMousePos(); + auto hoveredLink = interaction == Interaction::None && ImGui::IsWindowHovered() ? FindLink(graph, mouse) : nullptr; + + for (const auto& link : graph.links) { + auto from = layouts.find(link.fromNode); + auto to = layouts.find(link.toNode); + if (from == layouts.end() || to == layouts.end()) + continue; + + auto fromPin = from->second.outputPins.find(link.fromPin); + auto toPin = to->second.inputPins.find(link.toPin); + if (fromPin == from->second.outputPins.end() || toPin == to->second.inputPins.end()) + continue; + + auto fromNode = graph.GetNode(link.fromNode); + auto output = NodeLibrary::Find(*fromNode)->FindOutput(link.fromPin); + + auto highlight = &link == hoveredLink || selection.contains(link.fromNode) || selection.contains(link.toNode); + auto color = GetValueColor(output->type); + color.w = highlight ? 1.0f : 0.75f; + DrawCurve(drawList, fromPin->second, toPin->second, ImGui::ColorConvertFloat4ToU32(color), + (highlight ? 3.0f : 2.0f) * std::max(zoom, 0.6f), zoom); + } + + if (interaction == Interaction::DraggingLink && draggedPin.IsValid()) { + auto layout = layouts.find(draggedPin.node); + if (layout != layouts.end()) { + const auto& pins = draggedPin.isOutput ? layout->second.outputPins : layout->second.inputPins; + auto pin = pins.find(draggedPin.pin); + if (pin != pins.end()) { + auto color = ImGui::ColorConvertFloat4ToU32(Theme::Accent()); + if (draggedPin.isOutput) + DrawCurve(drawList, pin->second, mouse, color, 2.5f, zoom); + else + DrawCurve(drawList, mouse, pin->second, color, 2.5f, zoom); + } + } + } + + } + + void MaterialGraphPanel::DrawNodes(ImDrawList* drawList, Graph& graph, const CompiledGraph* compiled) { + + auto hoveredPin = FindPin(graph, ImGui::GetMousePos()); + + auto showDetails = zoom >= detailZoom; + + for (auto& node : graph.nodes) { + auto& layout = layouts[node.id]; + auto definition = NodeLibrary::Find(node); + + if (definition && definition->kind == NodeKind::Frame) + continue; + + // Nodes outside of the canvas don't need any draw calls or widgets + if (layout.max.x < canvasOrigin.x || layout.max.y < canvasOrigin.y || + layout.min.x > canvasOrigin.x + canvasSize.x || layout.min.y > canvasOrigin.y + canvasSize.y) + continue; + + if (definition && definition->kind == NodeKind::Reroute) { + auto center = ImVec2(0.5f * (layout.min.x + layout.max.x), 0.5f * (layout.min.y + layout.max.y)); + auto isSelected = selection.contains(node.id); + drawList->AddCircleFilled(center, 0.5f * rerouteSize * zoom, ImGui::ColorConvertFloat4ToU32(Theme::GraphNode())); + drawList->AddCircle(center, 0.5f * rerouteSize * zoom, ImGui::ColorConvertFloat4ToU32(isSelected ? Theme::Accent() : GetValueColor(ValueType::Generic)), + 0, 2.0f); + continue; + } + + auto rounding = 6.0f * zoom; + auto isSelected = selection.contains(node.id); + + const std::string* error = nullptr; + if (compiled) { + for (const auto& compileError : compiled->errors) { + if (compileError.nodeId == node.id) { + error = &compileError.message; + break; + } + } + } + + auto usedStages = 0u; + if (compiled) { + auto iter = compiled->nodeStages.find(node.id); + usedStages = iter != compiled->nodeStages.end() ? iter->second : 0u; + } + + // Nodes that don't contribute to anything are faded, their value isn't part of the shaders + auto isUsed = usedStages != 0u || (definition && (definition->kind == NodeKind::Comment || + definition->kind == NodeKind::VertexOutput || definition->kind == NodeKind::SurfaceOutput)); + auto alpha = isUsed ? 1.0f : 0.55f; + + drawList->AddRectFilled(layout.min, layout.max, ImGui::ColorConvertFloat4ToU32(Theme::GraphNode(alpha)), rounding); + + auto headerColor = Theme::GraphNodeHeader(definition ? definition->category.c_str() : "", alpha); + auto headerMax = ImVec2(layout.max.x, layout.min.y + layout.headerHeight); + drawList->AddRectFilled(layout.min, headerMax, ImGui::ColorConvertFloat4ToU32(headerColor), rounding, ImDrawFlags_RoundCornersTop); + + auto border = error ? Theme::Error() : isSelected ? Theme::Accent() : Theme::GraphNodeBorder(); + drawList->AddRect(layout.min, layout.max, ImGui::ColorConvertFloat4ToU32(border), rounding, 0, (isSelected || error ? 2.0f : 1.0f)); + + auto font = ImGui::GetFont(); + auto fontSize = ImGui::GetFontSize() * zoom; + auto textColor = ImGui::ColorConvertFloat4ToU32(ImGui::GetStyleColorVec4(ImGuiCol_Text)); + auto mutedColor = ImGui::ColorConvertFloat4ToU32(Theme::TextMuted()); + + auto textX = layout.min.x + 8.0f * zoom; + if (showDetails) { + drawList->AddText(font, fontSize, ImVec2(textX, layout.min.y + 3.0f * zoom), textColor, node.type.c_str()); + + if (definition && definition->kind == NodeKind::Parameter) + drawList->AddText(font, fontSize, ImVec2(textX, layout.min.y + rowHeight * 0.8f * zoom), mutedColor, node.name.c_str()); + } + else { + // Parameters are told apart by their name + auto clip = ImVec4(layout.min.x, layout.min.y, layout.max.x, layout.max.y); + const auto& title = definition && definition->kind == NodeKind::Parameter && !node.name.empty() ? node.name : node.type; + drawList->AddText(font, std::max(fontSize, 11.0f), ImVec2(layout.min.x + 3.0f, layout.min.y + 1.0f), textColor, title.c_str(), nullptr, 0.0f, &clip); + if (ImGui::IsMouseHoveringRect(layout.min, layout.max) && ImGui::IsWindowHovered()) + ImGui::SetTooltip("%s", title == node.type ? node.type.c_str() : (node.type + ": " + title).c_str()); + } + + // Which stage the node ends up in + auto chipX = layout.max.x - 8.0f * zoom; + auto drawChip = [&](const char* text, ImVec4 color) { + auto size = font->CalcTextSizeA(fontSize * 0.85f, FLT_MAX, 0.0f, text); + chipX -= size.x; + drawList->AddText(font, fontSize * 0.85f, ImVec2(chipX, layout.min.y + 4.0f * zoom), ImGui::ColorConvertFloat4ToU32(color), text); + chipX -= 5.0f * zoom; + }; + if (showDetails) { + if (usedStages & SurfaceStage) + drawChip("F", Theme::Warning()); + if (usedStages & VertexStage) + drawChip("V", Theme::Success()); + } + + auto y = layout.min.y + layout.headerHeight + 4.0f * zoom; + for (const auto& row : layout.rows) { + if (row.kind == RowKind::Output && showDetails) { + auto size = font->CalcTextSizeA(fontSize, FLT_MAX, 0.0f, row.output->name.c_str()); + drawList->AddText(font, fontSize, ImVec2(layout.max.x - size.x - 14.0f * zoom, y + 3.0f * zoom), textColor, row.output->name.c_str()); + } + else if (row.kind == RowKind::Input && showDetails) { + drawList->AddText(font, fontSize, ImVec2(layout.min.x + 14.0f * zoom, y + 3.0f * zoom), textColor, row.input->name.c_str()); + } + else if (row.kind == RowKind::Preview) { + previews.Request(node.id); + + // Square in the middle of the node + auto size = previewHeight * zoom - 6.0f * zoom; + auto centerX = 0.5f * (layout.min.x + layout.max.x); + auto imageMin = ImVec2(centerX - 0.5f * size, y + 3.0f * zoom); + auto imageMax = ImVec2(centerX + 0.5f * size, imageMin.y + size); + ImTextureID texture; + ImVec2 uvMin, uvMax; + if (previews.GetImage(node.id, texture, uvMin, uvMax)) + drawList->AddImage(texture, imageMin, imageMax, uvMin, uvMax); + else + drawList->AddRectFilled(imageMin, imageMax, ImGui::ColorConvertFloat4ToU32(Theme::GraphBackground())); + } + y += row.height; + } + + auto drawPin = [&](ImVec2 position, ValueType type, const std::string& pin, bool isOutput, bool isConnected) { + auto isHovered = hoveredPin.node == node.id && hoveredPin.pin == pin && hoveredPin.isOutput == isOutput; + auto radius = pinRadius * zoom * (isHovered ? 1.35f : 1.0f); + auto color = ImGui::ColorConvertFloat4ToU32(GetValueColor(type)); + if (isConnected) + drawList->AddCircleFilled(position, radius, color); + else + drawList->AddCircleFilled(position, radius, ImGui::ColorConvertFloat4ToU32(Theme::GraphNode())); + drawList->AddCircle(position, radius, color, 0, 2.0f * zoom); + if (isHovered) + ImGui::SetTooltip("%s: %s", pin.c_str(), GetValueName(type)); + }; + + if (definition) { + for (const auto& output : definition->outputs) { + auto isConnected = std::any_of(graph.links.begin(), graph.links.end(), + [&](const Link& link) { return link.fromNode == node.id && link.fromPin == output.name; }); + drawPin(layout.outputPins[output.name], output.type, output.name, true, isConnected); + } + for (const auto& input : definition->inputs) { + drawPin(layout.inputPins[input.name], input.type, input.name, false, graph.GetInputLink(node.id, input.name) != nullptr); + } + } + + ImGui::PushID(int32_t(node.id)); + if (DrawNodeWidgets(graph, node, layout)) + modified = true; + ImGui::PopID(); + + if (error && ImGui::IsMouseHoveringRect(layout.min, layout.max)) + ImGui::SetTooltip("%s", error->c_str()); + } + + } + + bool MaterialGraphPanel::DrawNodeWidgets(Graph& graph, Node& node, const NodeLayout& layout) { + + // Widgets get too small to be used before the text gets unreadable + if (zoom < detailZoom) + return false; + + auto definition = NodeLibrary::Find(node); + if (!definition) + return false; + + auto changed = false; + + ImGui::SetWindowFontScale(zoom); + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(3.0f * zoom, 1.0f * zoom)); + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(2.0f * zoom, 2.0f * zoom)); + + auto y = layout.min.y + layout.headerHeight + 4.0f * zoom; + auto padding = 8.0f * zoom; + for (const auto& row : layout.rows) { + if (row.kind == RowKind::Preview) { + } + else if (row.kind == RowKind::Value) { + changed |= DrawValueWidget(node, *definition, ImVec2(layout.min.x + padding, y + 1.0f * zoom), + layout.max.x - layout.min.x - 2.0f * padding); + } + else if (row.kind == RowKind::Text) { + ImGui::SetCursorScreenPos(ImVec2(layout.min.x + padding, y)); + changed |= ImGui::InputTextMultiline("##Comment", &node.name, + ImVec2(layout.max.x - layout.min.x - 2.0f * padding, row.height - 4.0f * zoom)); + } + else if (row.kind == RowKind::Input && !graph.GetInputLink(node.id, row.input->name)) { + auto textWidth = ImGui::CalcTextSize(row.input->name.c_str()).x; + auto isWide = row.height > rowHeight * zoom * 1.5f; + auto startX = isWide ? layout.min.x + 14.0f * zoom : layout.min.x + 14.0f * zoom + textWidth + 6.0f * zoom; + auto startY = isWide ? y + rowHeight * zoom : y + 1.0f * zoom; + auto width = layout.max.x - startX - padding; + if (width > 16.0f * zoom) + changed |= DrawInputWidget(node, *row.input, ImVec2(startX, startY), width); + } + y += row.height; + } + + ImGui::PopStyleVar(2); + ImGui::SetWindowFontScale(1.0f); + + return changed; + + } + + bool MaterialGraphPanel::DrawInputWidget(Node& node, const InputDefinition& input, ImVec2 position, float width) { + + ImGui::SetCursorScreenPos(position); + ImGui::PushID(input.name.c_str()); + + if (input.type == ValueType::Texture) { + ImGui::TextColored(Theme::Warning(), "connect a texture"); + ImGui::PopID(); + return false; + } + + if (!input.defaultExpression.empty()) { + ImGui::TextColored(Theme::TextMuted(), "of the mesh"); + ImGui::PopID(); + return false; + } + + auto value = input.defaultValue; + auto iter = node.inputValues.find(input.name); + if (iter != node.inputValues.end()) + value = iter->second; + + auto isColor = input.type == ValueType::Vec3 && (input.name.find("olor") != std::string::npos || + input.name == NodeLibrary::emissivePin); + + int32_t components = 1; + switch (input.type) { + case ValueType::Vec2: components = 2; break; + case ValueType::Vec3: components = 3; break; + case ValueType::Vec4: components = 4; break; + default: break; + } + + auto changed = false; + ImGui::SetNextItemWidth(width); + if (isColor) { + changed = ImGui::ColorEdit3("##Value", &value.x, ImGuiColorEditFlags_Float | ImGuiColorEditFlags_NoInputs | + ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_HDR); + } + else { + changed = ImGui::DragScalarN("##Value", ImGuiDataType_Float, &value.x, components, 0.01f, nullptr, nullptr, "%.3g"); + } + + if (changed) + node.inputValues[input.name] = value; + // Values are part of the generated code, so they wait until the value is final + if (ImGui::IsItemDeactivatedAfterEdit()) + compileRequested = true; + colorEdited |= isColor && changed; + + ImGui::PopID(); + + return changed; + + } + + bool MaterialGraphPanel::DrawValueWidget(Node& node, const NodeDefinition& definition, ImVec2 position, float width) { + + ImGui::SetCursorScreenPos(position); + + int32_t components = 1; + switch (definition.valueType) { + case ValueType::Vec2: components = 2; break; + case ValueType::Vec3: components = 3; break; + case ValueType::Vec4: components = 4; break; + default: break; + } + + if (definition.kind == NodeKind::StaticSwitch) { + auto isOn = node.value.x > 0.0f; + auto changed = ImGui::Checkbox("On##Value", &isOn); + if (changed) { + node.value.x = isOn ? 1.0f : 0.0f; + compileRequested = true; + } + return changed; + } + + auto changed = false; + ImGui::SetNextItemWidth(width); + if (definition.isColor) { + changed = ImGui::ColorEdit3("##Value", &node.value.x, ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoLabel); + } + else if (node.range.x < node.range.y) { + changed = ImGui::DragScalarN("##Value", ImGuiDataType_Float, &node.value.x, components, 0.01f, &node.range.x, &node.range.y, "%.3g", + ImGuiSliderFlags_AlwaysClamp); + } + else { + changed = ImGui::DragScalarN("##Value", ImGuiDataType_Float, &node.value.x, components, 0.01f, nullptr, nullptr, "%.3g"); + } + + // The default of a parameter isn't part of the code, so it can be applied while dragging + if (definition.kind == NodeKind::Parameter && changed) + compileRequested = true; + else if (ImGui::IsItemDeactivatedAfterEdit()) + compileRequested = true; + else + colorEdited |= definition.isColor && changed; + + return changed; + + } + + void MaterialGraphPanel::DrawToolbar(Graph& graph, const CompiledGraph* compiled) { + + if (ImGui::Button("Add node")) + OpenAddMenu(); + ImGui::SetItemTooltip("Adds a node (Space or right click on the canvas)"); + ImGui::SameLine(); + if (ImGui::Button("Frame")) + FrameAll(); + ImGui::SetItemTooltip("Shows all nodes (F)"); + ImGui::SameLine(); + if (ImGui::Button("Arrange")) + Arrange(graph); + ImGui::SetItemTooltip("Places all nodes next to the nodes they connect to"); + ImGui::SameLine(); + if (ImGui::Button("Generated code")) + showCode = true; + ImGui::SameLine(); + const char* previewModes[] = { "No previews", "Key previews", "All previews" }; + auto previewModeIdx = int32_t(previewMode); + ImGui::SetNextItemWidth(130.0f); + if (ImGui::Combo("##Previews", &previewModeIdx, previewModes, IM_ARRAYSIZE(previewModes))) + previewMode = PreviewMode(previewModeIdx); + ImGui::SetItemTooltip("Which nodes show a picture of their value. Pictures make nodes larger, Arrange takes that into account"); + ImGui::SameLine(); + // As high as the text buttons next to it: the icon is one line high with the same frame padding + auto& maximizeIcon = Singletons::icons->Get(maximized ? IconType::ScaleInverse : IconType::Scale); + auto lineHeight = ImGui::GetTextLineHeight(); + if (ImGui::ImageButton("Maximize", Singletons::imguiWrapper->GetTextureId(&maximizeIcon), ImVec2(lineHeight, lineHeight), + ImVec2(0.1f, 0.1f), ImVec2(0.9f, 0.9f))) { + maximized = !maximized; + frameRequested = true; + // The canvas gets its new size in the next frames + stableCanvasFrames = -2; + } + ImGui::SetItemTooltip(maximized ? "Shows the graph in the material editor again (F11)" : + "Shows the graph over the whole editor (F11)"); + ImGui::SameLine(); + if (modified) { + ImGui::TextColored(Theme::Warning(), "Unsaved"); + ImGui::SetItemTooltip("Saving the material saves the graph as well (Ctrl+S)"); + ImGui::SameLine(); + } + ImGui::TextDisabled("|"); + ImGui::SameLine(); + + if (!compiled) { + ImGui::TextDisabled("Not compiled"); + return; + } + + if (!compiled->valid) { + ImGui::TextColored(Theme::Error(), "%d %s", int32_t(compiled->errors.size()), compiled->errors.size() == 1 ? "error" : "errors"); + ImGui::SameLine(); + ImGui::TextColored(Theme::TextMuted(), "%s", compiled->errors.empty() ? "" : compiled->errors.front().message.c_str()); + return; + } + + if (!compiled->hasVertexOffset && !compiled->hasSurface) { + ImGui::TextColored(Theme::TextMuted(), "Connect an output to use the graph, until then the regular material properties are used"); + return; + } + + // The kind of graph only, the output section of the inspector explains what it does + auto kind = compiled->hasVertexOffset && compiled->hasSurface ? "Vertex and surface graph" : + compiled->hasVertexOffset ? "Vertex graph" : "Surface graph"; + auto textureCount = std::count_if(compiled->parameters.begin(), compiled->parameters.end(), + [](const Parameter& parameter) { return parameter.type == ValueType::Texture; }); + ImGui::TextUnformatted(kind); + ImGui::SetItemTooltip("The inspector shows what the graph does without a selected node"); + ImGui::SameLine(); + ImGui::TextColored(Theme::TextMuted(), "· %d parameters, %d textures", int32_t(compiled->parameters.size()), int32_t(textureCount)); + + } + + void MaterialGraphPanel::DrawMinimap(ImDrawList* drawList, Graph& graph, ImVec2 canvasMin, ImVec2 canvasMax) { + + if (graph.nodes.empty()) + return; + + vec2 boundsMin(FLT_MAX), boundsMax(-FLT_MAX); + for (const auto& node : graph.nodes) { + const auto& layout = layouts[node.id]; + boundsMin = glm::min(boundsMin, node.position); + boundsMax = glm::max(boundsMax, node.position + GetNodeSize(node)); + } + + auto viewMin = ToCanvas(canvasMin); + auto viewMax = ToCanvas(canvasMax); + boundsMin = glm::min(boundsMin, viewMin); + boundsMax = glm::max(boundsMax, viewMax); + + const auto maxMapSize = vec2(180.0f, 120.0f); + const auto margin = 8.0f; + auto extent = glm::max(boundsMax - boundsMin, vec2(1.0f)); + auto scale = glm::min(maxMapSize.x / extent.x, maxMapSize.y / extent.y); + + // The map only covers what it shows, a click anywhere on it stays near the graph + auto mapSize = extent * scale; + auto mapMax = ImVec2(canvasMax.x - margin, canvasMax.y - margin); + auto mapMin = ImVec2(mapMax.x - mapSize.x, mapMax.y - mapSize.y); + minimapMin = mapMin; + minimapMax = mapMax; + + auto toMap = [&](vec2 position) { + auto local = (position - boundsMin) * scale; + return ImVec2(mapMin.x + local.x, mapMin.y + local.y); + }; + + drawList->AddRectFilled(mapMin, mapMax, ImGui::ColorConvertFloat4ToU32(Theme::OverlayBackground()), 4.0f); + drawList->AddRect(mapMin, mapMax, ImGui::ColorConvertFloat4ToU32(Theme::OverlayBorder()), 4.0f); + + for (const auto& node : graph.nodes) { + auto definition = NodeLibrary::Find(node); + auto isFrame = definition && definition->kind == NodeKind::Frame; + auto color = selection.contains(node.id) ? Theme::Accent() : isFrame ? Theme::Accent(0.2f) : Theme::TextMuted(); + drawList->AddRectFilled(toMap(node.position), toMap(node.position + GetNodeSize(node)), + ImGui::ColorConvertFloat4ToU32(color)); + } + + drawList->AddRect(toMap(viewMin), toMap(viewMax), ImGui::ColorConvertFloat4ToU32(Theme::Accent())); + + // Clicking the map moves the view there + if (ImGui::IsWindowHovered() && ImGui::IsMouseHoveringRect(mapMin, mapMax) && ImGui::IsMouseDown(ImGuiMouseButton_Left) && + interaction == Interaction::None) { + auto mouse = ImGui::GetMousePos(); + auto target = boundsMin + vec2(mouse.x - mapMin.x, mouse.y - mapMin.y) / scale; + pan = vec2(canvasSize.x, canvasSize.y) * 0.5f / zoom - target; + } + + } + + void MaterialGraphPanel::DrawCodeWindow(const CompiledGraph* compiled) { + + if (!showCode) + return; + + ImGui::SetNextWindowSize(ImVec2(760.0f, 620.0f), ImGuiCond_FirstUseEver); + if (ImGui::Begin("Generated code##MaterialGraph", &showCode)) { + if (!compiled || !compiled->valid) { + ImGui::TextColored(Theme::Warning(), "The graph has errors, there is no code"); + } + else if (compiled->mainVertexCode.empty()) { + ImGui::TextDisabled("The graph doesn't generate any code yet"); + } + else { + // The selected tab has the color of the editor below and is attached to it + auto editorColor = ImGui::GetStyleColorVec4(ImGuiCol_FrameBg); + ImGui::PushStyleColor(ImGuiCol_Tab, ImVec4(0.0f, 0.0f, 0.0f, 0.0f)); + ImGui::PushStyleColor(ImGuiCol_TabDimmed, ImVec4(0.0f, 0.0f, 0.0f, 0.0f)); + ImGui::PushStyleColor(ImGuiCol_TabHovered, ImGui::GetStyleColorVec4(ImGuiCol_FrameBgHovered)); + ImGui::PushStyleColor(ImGuiCol_TabSelected, editorColor); + ImGui::PushStyleColor(ImGuiCol_TabDimmedSelected, editorColor); + ImGui::PushStyleVar(ImGuiStyleVar_TabBarBorderSize, 0.0f); + auto open = ImGui::BeginTabBar("Stages"); + auto barBottom = ImGui::GetCursorScreenPos().y - ImGui::GetStyle().ItemSpacing.y; + auto tab = [&](const char* name, const std::string& code, CodeEditor& editor) { + if (code.empty() || !ImGui::BeginTabItem(name)) + return; + ImGui::SetCursorScreenPos(ImVec2(ImGui::GetCursorScreenPos().x, barBottom)); + editor.Render(name, code); + ImGui::EndTabItem(); + }; + if (open) { + tab("Vertex", compiled->mainVertexCode, generatedCodeEditors[0]); + tab("Fragment", compiled->mainFragmentCode, generatedCodeEditors[1]); + tab("Shadow vertex", compiled->shadowVertexCode, generatedCodeEditors[2]); + tab("Shadow fragment", compiled->shadowFragmentCode, generatedCodeEditors[3]); + ImGui::EndTabBar(); + } + ImGui::PopStyleVar(); + ImGui::PopStyleColor(5); + } + } + ImGui::End(); + + } + + void MaterialGraphPanel::LoadCodeFunctionCompletions() { + + codeFunctionCompletionsLoaded = true; + + // Helpers of other helpers, not meant for code nodes + const std::vector internalFunctions = { "MaterialGraphReadFloat", "MaterialGraphReadVec2", + "MaterialGraphReadVec3", "MaterialGraphReadVec4", "MaterialGraphMod289", "MaterialGraphPermute", "MaterialGraphHash3" }; + + auto stream = Loader::AssetLoader::ReadFile("shader/materialGraph/common.hsh", std::ios::in); + if (!stream.is_open()) + return; + std::string code((std::istreambuf_iterator(stream)), std::istreambuf_iterator()); + + for (auto& function : CodeEditor::FindGlslFunctions(code)) { + if (function.text.starts_with("MaterialGraph") && + std::find(internalFunctions.begin(), internalFunctions.end(), function.text) == internalFunctions.end()) + codeFunctionCompletions.push_back(std::move(function)); + } + + } + + void MaterialGraphPanel::HandleInteractions(Graph& graph) { + + auto& io = ImGui::GetIO(); + auto mouse = ImGui::GetMousePos(); + auto isCanvasHovered = ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows) && + ImGui::IsMouseHoveringRect(canvasOrigin, ImVec2(canvasOrigin.x + canvasSize.x, canvasOrigin.y + canvasSize.y)); + + // A widget of a node has the mouse, e.g. a value that is dragged + auto isWidgetBusy = ImGui::IsAnyItemActive() || ImGui::IsAnyItemHovered(); + + // Only left clicks focus windows, the shortcuts should also work after using the canvas with the other buttons + if (isCanvasHovered && (ImGui::IsMouseClicked(ImGuiMouseButton_Right) || ImGui::IsMouseClicked(ImGuiMouseButton_Middle))) + ImGui::SetWindowFocus(); + + if (isCanvasHovered && io.MouseWheel != 0.0f) { + auto before = ToCanvas(mouse); + zoom = std::clamp(zoom * std::pow(1.15f, io.MouseWheel), minZoom, 2.5f); + auto after = ToCanvas(mouse); + pan += after - before; + } + + // Panning works from everywhere, also on top of nodes + if (isCanvasHovered && interaction == Interaction::None && ImGui::IsMouseClicked(ImGuiMouseButton_Middle)) + interaction = Interaction::Panning; + if (isCanvasHovered && interaction == Interaction::None && ImGui::IsMouseDragging(ImGuiMouseButton_Right, 4.0f)) + interaction = Interaction::Panning; + + if (interaction == Interaction::Panning) { + pan += vec2(io.MouseDelta.x, io.MouseDelta.y) / zoom; + if (!ImGui::IsMouseDown(ImGuiMouseButton_Middle) && !ImGui::IsMouseDown(ImGuiMouseButton_Right)) + interaction = Interaction::None; + return; + } + + if (interaction == Interaction::MovingNodes) { + if (io.MouseDelta.x != 0.0f || io.MouseDelta.y != 0.0f) { + nodesMoved = true; + for (auto id : selection) { + if (auto node = graph.GetNode(id)) + node->position += vec2(io.MouseDelta.x, io.MouseDelta.y) / zoom; + } + for (auto id : movedWithFrames) { + if (selection.contains(id)) + continue; + if (auto node = graph.GetNode(id)) + node->position += vec2(io.MouseDelta.x, io.MouseDelta.y) / zoom; + } + } + if (ImGui::IsMouseReleased(ImGuiMouseButton_Left)) { + interaction = Interaction::None; + modified |= nodesMoved; + } + return; + } + + if (interaction == Interaction::ResizingFrame) { + if (auto node = graph.GetNode(resizedFrame)) { + node->size = glm::max(node->size + vec2(io.MouseDelta.x, io.MouseDelta.y) / zoom, vec2(120.0f, 80.0f)); + } + if (ImGui::IsMouseReleased(ImGuiMouseButton_Left)) { + interaction = Interaction::None; + modified = true; + } + return; + } + + if (interaction == Interaction::BoxSelection) { + if (ImGui::IsMouseReleased(ImGuiMouseButton_Left)) { + auto boxMin = ImVec2(std::min(boxStart.x, mouse.x), std::min(boxStart.y, mouse.y)); + auto boxMax = ImVec2(std::max(boxStart.x, mouse.x), std::max(boxStart.y, mouse.y)); + if (!io.KeyShift && !io.KeyCtrl) + selection.clear(); + for (const auto& node : graph.nodes) { + const auto& layout = layouts[node.id]; + // A box inside of a frame selects the nodes in there, not the frame + auto definition = NodeLibrary::Find(node); + if (definition && definition->kind == NodeKind::Frame) { + if (layout.min.x >= boxMin.x && layout.max.x <= boxMax.x && layout.min.y >= boxMin.y && layout.max.y <= boxMax.y) + selection.insert(node.id); + continue; + } + if (layout.min.x < boxMax.x && layout.max.x > boxMin.x && layout.min.y < boxMax.y && layout.max.y > boxMin.y) + selection.insert(node.id); + } + interaction = Interaction::None; + } + return; + } + + if (interaction == Interaction::DraggingLink) { + if (ImGui::IsMouseReleased(ImGuiMouseButton_Left)) { + auto target = FindPin(graph, mouse); + interaction = Interaction::None; + + if (target.IsValid() && target.isOutput != draggedPin.isOutput) { + const auto& output = draggedPin.isOutput ? draggedPin : target; + const auto& input = draggedPin.isOutput ? target : draggedPin; + if (graph.Connect(output.node, output.pin, input.node, input.pin)) + compileRequested = true; + } + else if (!target.IsValid() && isCanvasHovered) { + // Dropped on the canvas: choose the node for the other end + pendingPin = draggedPin; + addPosition = ToCanvas(mouse); + openAddMenu = true; + } + draggedPin = PinRef(); + } + return; + } + + if (!isCanvasHovered) + return; + + if (ImGui::IsMouseReleased(ImGuiMouseButton_Right) && !isWidgetBusy) { + auto node = FindNode(graph, mouse); + if (node) { + if (!selection.contains(node)) { + selection.clear(); + selection.insert(node); + } + ImGui::OpenPopup("NodeMenu"); + } + else { + pendingPin = PinRef(); + addPosition = ToCanvas(mouse); + openAddMenu = true; + } + } + + if (!ImGui::IsMouseClicked(ImGuiMouseButton_Left)) + return; + + // The minimap handles the mouse on its own + if (ImGui::IsMouseHoveringRect(minimapMin, minimapMax)) + return; + + auto pin = FindPin(graph, mouse); + if (pin.IsValid()) { + // An input with a link gets picked up, the link can then be dropped somewhere else + if (!pin.isOutput) { + if (auto link = graph.GetInputLink(pin.node, pin.pin)) { + draggedPin = { link->fromNode, link->fromPin, true }; + graph.Disconnect(pin.node, pin.pin); + compileRequested = true; + interaction = Interaction::DraggingLink; + return; + } + } + draggedPin = pin; + interaction = Interaction::DraggingLink; + return; + } + + if (isWidgetBusy) + return; + + // A double click on a link adds a point to lead it around other nodes + if (ImGui::GetMouseClickedCount(ImGuiMouseButton_Left) == 2) { + if (auto link = FindLink(graph, mouse)) { + InsertReroute(graph, *link, ToCanvas(mouse) - vec2(rerouteSize * 0.5f)); + return; + } + } + + // Alt click removes a link + if (io.KeyAlt) { + if (auto link = FindLink(graph, mouse)) { + graph.Disconnect(link->toNode, link->toPin); + compileRequested = true; + return; + } + } + + auto node = FindNode(graph, mouse); + if (node) { + auto frameDefinition = NodeLibrary::Find(*graph.GetNode(node)); + auto isFrame = frameDefinition && frameDefinition->kind == NodeKind::Frame; + + if (isFrame) { + const auto& layout = layouts[node]; + auto corner = 14.0f; + if (mouse.x > layout.max.x - corner && mouse.y > layout.max.y - corner) { + resizedFrame = node; + interaction = Interaction::ResizingFrame; + return; + } + } + + if (io.KeyCtrl || io.KeyShift) { + if (selection.contains(node)) + selection.erase(node); + else + selection.insert(node); + } + else if (!selection.contains(node)) { + selection.clear(); + selection.insert(node); + } + nodesMoved = false; + interaction = Interaction::MovingNodes; + + movedWithFrames.clear(); + for (auto id : selection) { + auto selectedNode = graph.GetNode(id); + auto selectedDefinition = selectedNode ? NodeLibrary::Find(*selectedNode) : nullptr; + if (selectedDefinition && selectedDefinition->kind == NodeKind::Frame) { + for (auto inFrame : GetNodesInFrame(graph, *selectedNode)) + movedWithFrames.insert(inFrame); + } + } + + // The node ends up in front of the others + auto iter = std::find_if(graph.nodes.begin(), graph.nodes.end(), [&](const Node& item) { return item.id == node; }); + std::rotate(iter, iter + 1, graph.nodes.end()); + return; + } + + boxStart = mouse; + interaction = Interaction::BoxSelection; + + } + + void MaterialGraphPanel::HandleShortcuts(const ResourceHandle& graphHandle) { + + auto& graph = *graphHandle.Get(); + auto& io = ImGui::GetIO(); + +#ifdef AE_OS_MACOS + auto command = io.KeySuper; +#else + auto command = io.KeyCtrl; +#endif + + if (ImGui::IsKeyPressed(ImGuiKey_Delete, false) || ImGui::IsKeyPressed(ImGuiKey_Backspace, false)) + DeleteSelection(graph); + if (ImGui::IsKeyPressed(ImGuiKey_F, false) && !command) { + frameOnlySelection = !selection.empty(); + FrameAll(); + } + if (ImGui::IsKeyPressed(ImGuiKey_F11, false)) + ToggleMaximized(); + if (ImGui::IsKeyPressed(ImGuiKey_Space, false) && ImGui::IsWindowHovered()) { + pendingPin = PinRef(); + addPosition = ToCanvas(ImGui::GetMousePos()); + openAddMenu = true; + } + + if (!command) + return; + + if (ImGui::IsKeyPressed(ImGuiKey_A, false)) + SelectAll(graph); + if (ImGui::IsKeyPressed(ImGuiKey_C, false)) + CopySelection(graph); + if (ImGui::IsKeyPressed(ImGuiKey_V, false)) + Paste(graph); + if (ImGui::IsKeyPressed(ImGuiKey_D, false)) + DuplicateSelection(graph); + if (ImGui::IsKeyPressed(ImGuiKey_G, false)) + FrameSelection(graph); + + } + + void MaterialGraphPanel::RenderNodeMenu(Graph& graph) { + + if (!ImGui::BeginPopup("NodeMenu")) + return; + + if (ImGui::MenuItem("Duplicate", "Ctrl+D")) + DuplicateSelection(graph); + if (ImGui::MenuItem("Copy", "Ctrl+C")) + CopySelection(graph); + if (ImGui::MenuItem("Frame selection", "Ctrl+G")) + FrameSelection(graph); + if (ImGui::MenuItem("Disconnect")) { + std::erase_if(graph.links, [&](const Link& link) { + return selection.contains(link.fromNode) || selection.contains(link.toNode); + }); + compileRequested = true; + } + ImGui::Separator(); + if (ImGui::MenuItem("Delete", "Del")) + DeleteSelection(graph); + + ImGui::EndPopup(); + + } + + void MaterialGraphPanel::RenderAddMenu(Graph& graph) { + + if (openAddMenu) { + ImGui::OpenPopup("AddNodeMenu"); + addSearch.clear(); + addRow = 0; + focusAddSearch = true; + openAddMenu = false; + + // A dropped link leaves few nodes, they shouldn't hide in closed categories + openAddCategories.clear(); + if (pendingPin.IsValid()) { + for (const auto& definition : NodeLibrary::GetDefinitions()) + openAddCategories.insert(definition.category); + } + } + + ImGui::SetNextWindowSizeConstraints(ImVec2(280.0f, 0.0f), ImVec2(320.0f, 460.0f)); + if (!ImGui::BeginPopup("AddNodeMenu")) { + return; + } + + // A popup can only take the focus once it is shown + if (focusAddSearch) { + ImGui::SetKeyboardFocusHere(); + focusAddSearch = ImGui::IsWindowAppearing(); + } + ImGui::SetNextItemWidth(-1.0f); + if (ImGui::InputTextWithHint("##Search", "Search nodes...", &addSearch)) + addRow = 0; + + auto toLower = [](std::string text) { + std::transform(text.begin(), text.end(), text.begin(), [](unsigned char c) { return char(std::tolower(c)); }); + return text; + }; + auto search = toLower(addSearch); + + auto canAdd = [&](const NodeDefinition& definition) { + // The outputs exist in every graph, there can only be one of them + if (definition.kind == NodeKind::VertexOutput || definition.kind == NodeKind::SurfaceOutput) { + auto exists = std::any_of(graph.nodes.begin(), graph.nodes.end(), [&](const Node& node) { return node.type == definition.type; }); + if (exists) + return false; + } + // A dropped link only offers nodes the link can connect to + return !pendingPin.IsValid() || FindPendingPartner(graph, definition); + }; + + // Either a category or a node. Searching lists the nodes without categories + struct Row { + std::string category; + const NodeDefinition* definition = nullptr; + }; + + std::vector rows; + std::string category; + for (const auto& definition : NodeLibrary::GetDefinitions()) { + if (!canAdd(definition)) + continue; + + if (!search.empty()) { + if (toLower(definition.type).find(search) != std::string::npos || toLower(definition.tooltip).find(search) != std::string::npos) + rows.push_back({ definition.category, &definition }); + continue; + } + + if (definition.category != category) { + category = definition.category; + rows.push_back({ category }); + } + if (openAddCategories.contains(category)) + rows.push_back({ category, &definition }); + } + + const NodeDefinition* selected = nullptr; + auto rowMoved = false; + if (!rows.empty()) { + addRow = std::clamp(addRow, 0, int32_t(rows.size()) - 1); + + if (ImGui::IsKeyPressed(ImGuiKey_DownArrow) || ImGui::IsKeyPressed(ImGuiKey_UpArrow)) { + auto step = ImGui::IsKeyPressed(ImGuiKey_DownArrow) ? 1 : int32_t(rows.size()) - 1; + addRow = (addRow + step) % int32_t(rows.size()); + rowMoved = true; + } + + const auto& row = rows[addRow]; + auto isCategoryOpen = openAddCategories.contains(row.category); + if (ImGui::IsKeyPressed(ImGuiKey_Enter) || ImGui::IsKeyPressed(ImGuiKey_KeypadEnter)) { + if (row.definition) + selected = row.definition; + else if (isCategoryOpen) + openAddCategories.erase(row.category); + else + openAddCategories.insert(row.category); + } + + // The arrows move the cursor of the search text as long as there is one + if (search.empty() && ImGui::IsKeyPressed(ImGuiKey_RightArrow) && !row.definition) + openAddCategories.insert(row.category); + if (search.empty() && ImGui::IsKeyPressed(ImGuiKey_LeftArrow)) { + if (row.definition) { + while (rows[addRow].definition) + addRow--; + rowMoved = true; + } + else { + openAddCategories.erase(row.category); + } + } + } + + ImGui::BeginChild("Nodes", ImVec2(0.0f, 360.0f)); + + for (int32_t i = 0; i < int32_t(rows.size()); i++) { + const auto& row = rows[i]; + auto isCurrent = i == addRow; + + if (row.definition) { + if (search.empty()) + ImGui::Indent(); + if (ImGui::Selectable(row.definition->type.c_str(), isCurrent)) + selected = row.definition; + ImGui::SetItemTooltip("%s", row.definition->tooltip.c_str()); + if (search.empty()) + ImGui::Unindent(); + } + else { + auto isOpen = openAddCategories.contains(row.category); + ImGui::SetNextItemOpen(isOpen); + auto flags = ImGuiTreeNodeFlags_NoTreePushOnOpen | ImGuiTreeNodeFlags_SpanAvailWidth | (isCurrent ? ImGuiTreeNodeFlags_Selected : 0); + if (ImGui::TreeNodeEx(row.category.c_str(), flags) != isOpen) { + if (isOpen) + openAddCategories.erase(row.category); + else + openAddCategories.insert(row.category); + } + } + + if (isCurrent && rowMoved) + ImGui::SetScrollHereY(); + } + + ImGui::EndChild(); + + if (selected) { + AddNode(graph, *selected); + ImGui::CloseCurrentPopup(); + } + + ImGui::EndPopup(); + + } + + MaterialGraphPanel::PinRef MaterialGraphPanel::FindPin(const Graph& graph, ImVec2 position) const { + + auto radius = std::max(pinRadius * zoom * 1.6f, 7.0f); + auto isClose = [&](ImVec2 pin) { + auto dx = pin.x - position.x; + auto dy = pin.y - position.y; + return dx * dx + dy * dy <= radius * radius; + }; + + // From front to back, as nodes are drawn + for (auto node = graph.nodes.rbegin(); node != graph.nodes.rend(); node++) { + auto layout = layouts.find(node->id); + if (layout == layouts.end()) + continue; + for (const auto& [name, pin] : layout->second.outputPins) { + if (isClose(pin)) + return { node->id, name, true }; + } + for (const auto& [name, pin] : layout->second.inputPins) { + if (isClose(pin)) + return { node->id, name, false }; + } + } + + return {}; + + } + + uint32_t MaterialGraphPanel::FindNode(const Graph& graph, ImVec2 position) const { + + uint32_t frame = 0; + for (auto node = graph.nodes.rbegin(); node != graph.nodes.rend(); node++) { + auto layout = layouts.find(node->id); + if (layout == layouts.end()) + continue; + const auto& min = layout->second.min; + const auto& max = layout->second.max; + if (position.x < min.x || position.x > max.x || position.y < min.y || position.y > max.y) + continue; + + // Frames lie behind all nodes, inside of them only the header and the corner can be grabbed + auto definition = NodeLibrary::Find(*node); + if (definition && definition->kind == NodeKind::Frame) { + auto isCorner = position.x > max.x - 14.0f && position.y > max.y - 14.0f; + if (!frame && (position.y <= min.y + layout->second.headerHeight || isCorner)) + frame = node->id; + continue; + } + + return node->id; + } + + return frame; + + } + + const Link* MaterialGraphPanel::FindLink(const Graph& graph, ImVec2 position) const { + + if (FindNode(graph, position)) + return nullptr; + + for (const auto& link : graph.links) { + auto from = layouts.find(link.fromNode); + auto to = layouts.find(link.toNode); + if (from == layouts.end() || to == layouts.end()) + continue; + + auto fromPin = from->second.outputPins.find(link.fromPin); + auto toPin = to->second.inputPins.find(link.toPin); + if (fromPin == from->second.outputPins.end() || toPin == to->second.inputPins.end()) + continue; + + auto a = fromPin->second; + auto d = toPin->second; + auto distance = std::max(std::abs(d.x - a.x) * 0.5f, 40.0f * zoom); + auto b = ImVec2(a.x + distance, a.y); + auto c = ImVec2(d.x - distance, d.y); + + auto closest = ImBezierCubicClosestPointCasteljau(a, b, c, d, position, ImGui::GetStyle().CurveTessellationTol); + auto dx = closest.x - position.x; + auto dy = closest.y - position.y; + if (dx * dx + dy * dy < 36.0f) + return &link; + } + + return nullptr; + + } + + void MaterialGraphPanel::AddNode(Graph& graph, const NodeDefinition& definition) { + + auto& node = graph.AddNode(definition.type, addPosition); + auto nodeId = node.id; + + if (definition.kind == NodeKind::Frame) { + node.name = "Frame"; + node.size = vec2(520.0f, 360.0f); + } + + // Parameters need a name, which is unique for new nodes + if (definition.kind == NodeKind::Parameter) { + int32_t index = 1; + std::string name; + do { + name = "Parameter " + std::to_string(index++); + } while (std::any_of(graph.nodes.begin(), graph.nodes.end(), [&](const Node& other) { return other.name == name; })); + graph.GetNode(nodeId)->name = name; + } + + if (pendingPin.IsValid()) { + if (auto pin = FindPendingPartner(graph, definition)) { + if (pendingPin.isOutput) + graph.Connect(pendingPin.node, pendingPin.pin, nodeId, *pin); + else + graph.Connect(nodeId, *pin, pendingPin.node, pendingPin.pin); + } + pendingPin = PinRef(); + } + + selection.clear(); + selection.insert(nodeId); + + compileRequested = true; + + } + + const std::string* MaterialGraphPanel::FindPendingPartner(const Graph& graph, const NodeDefinition& definition) const { + + auto node = graph.GetNode(pendingPin.node); + auto pendingDefinition = node ? NodeLibrary::Find(*node) : nullptr; + if (!pendingDefinition) + return nullptr; + + // A varying reads in the vertex stage and hands the value to the surface stage + auto getStages = [](const NodeDefinition& nodeDefinition, bool isOutput) -> uint32_t { + switch (nodeDefinition.kind) { + case NodeKind::Varying: return isOutput ? SurfaceStage : VertexStage; + case NodeKind::VertexOutput: return VertexStage; + case NodeKind::SurfaceOutput: return SurfaceStage; + default: return nodeDefinition.stages; + } + }; + + if (!(getStages(*pendingDefinition, pendingPin.isOutput) & getStages(definition, !pendingPin.isOutput))) + return nullptr; + + auto pendingType = pendingPin.isOutput ? pendingDefinition->FindOutput(pendingPin.pin)->type : + pendingDefinition->FindInput(pendingPin.pin)->type; + + // Pins of the same type go first, other values would only convert + const std::string* partner = nullptr; + auto check = [&](const auto& pins) { + for (const auto& pin : pins) { + if ((pin.type == ValueType::Texture) != (pendingType == ValueType::Texture)) + continue; + if (pin.type == pendingType || pin.type == ValueType::Generic || pendingType == ValueType::Generic) + return &pin.name; + if (!partner) + partner = &pin.name; + } + return partner; + }; + + return pendingPin.isOutput ? check(definition.inputs) : check(definition.outputs); + + } + + void MaterialGraphPanel::SelectAll(const Graph& graph) { + + for (const auto& node : graph.nodes) + selection.insert(node.id); + + } + + void MaterialGraphPanel::ToggleMaximized() { + + maximized = !maximized; + frameRequested = true; + stableCanvasFrames = -2; + + } + + void MaterialGraphPanel::DeleteSelection(Graph& graph) { + + if (selection.empty()) + return; + + for (auto id : selection) { + auto node = graph.GetNode(id); + if (!node) + continue; + + // The outputs stay, otherwise there is nothing to connect the graph to + auto definition = NodeLibrary::Find(*node); + if (definition && (definition->kind == NodeKind::VertexOutput || definition->kind == NodeKind::SurfaceOutput)) { + std::erase_if(graph.links, [&](const Link& link) { return link.toNode == id; }); + continue; + } + + graph.RemoveNode(id); + } + + selection.clear(); + compileRequested = true; + + } + + void MaterialGraphPanel::DuplicateSelection(Graph& graph) { + + auto previousClipboard = clipboard; + CopySelection(graph); + Paste(graph); + clipboard = previousClipboard; + + } + + void MaterialGraphPanel::FrameSelection(Graph& graph) { + + if (selection.empty()) + return; + + vec2 boundsMin(FLT_MAX), boundsMax(-FLT_MAX); + for (auto id : selection) { + auto node = graph.GetNode(id); + if (!node) + continue; + boundsMin = glm::min(boundsMin, node->position); + boundsMax = glm::max(boundsMax, node->position + GetNodeSize(*node)); + } + + const float padding = 24.0f; + auto& frame = graph.AddNode("Frame", boundsMin - vec2(padding, padding + frameHeaderHeight)); + frame.name = "Frame"; + frame.size = boundsMax - boundsMin + vec2(2.0f * padding, 2.0f * padding + frameHeaderHeight); + + selection.clear(); + selection.insert(frame.id); + + modified = true; + + } + + void MaterialGraphPanel::InsertReroute(Graph& graph, Link link, vec2 position) { + + auto nodeId = graph.AddNode("Reroute", position).id; + + graph.Connect(link.fromNode, link.fromPin, nodeId, "Value"); + graph.Connect(nodeId, "Value", link.toNode, link.toPin); + + selection.clear(); + selection.insert(nodeId); + + compileRequested = true; + + } + + std::vector MaterialGraphPanel::GetNodesInFrame(const Graph& graph, const Node& frame) const { + + std::vector nodes; + for (const auto& node : graph.nodes) { + if (node.id == frame.id) + continue; + + auto center = node.position + 0.5f * GetNodeSize(node); + if (glm::all(glm::greaterThanEqual(center, frame.position)) && glm::all(glm::lessThanEqual(center, frame.position + frame.size))) + nodes.push_back(node.id); + } + + return nodes; + + } + + vec2 MaterialGraphPanel::GetNodeSize(const Node& node) const { + + auto layout = layouts.find(node.id); + if (layout == layouts.end() || zoom <= 0.0f) + return vec2(nodeWidth, 200.0f); + + return vec2(layout->second.max.x - layout->second.min.x, layout->second.max.y - layout->second.min.y) / zoom; + + } + + void MaterialGraphPanel::CopySelection(const Graph& graph) { + + std::unordered_set copied; + json nodes = json::array(); + for (const auto& node : graph.nodes) { + auto definition = NodeLibrary::Find(node); + if (!selection.contains(node.id) || (definition && (definition->kind == NodeKind::VertexOutput || definition->kind == NodeKind::SurfaceOutput))) + continue; + nodes.push_back(node); + copied.insert(node.id); + } + + json links = json::array(); + for (const auto& link : graph.links) { + if (copied.contains(link.fromNode) && copied.contains(link.toNode)) + links.push_back(link); + } + + clipboard = json{ {"nodes", nodes}, {"links", links} }.dump(); + + } + + void MaterialGraphPanel::Paste(Graph& graph) { + + if (clipboard.empty()) + return; + + auto j = json::parse(clipboard); + + std::vector nodes = j["nodes"]; + std::vector links = j["links"]; + + vec2 center(0.0f); + for (const auto& node : nodes) + center += node.position / float(std::max(nodes.size(), size_t(1))); + + // Near the mouse, a duplicate shouldn't hide the original + auto target = ImGui::IsWindowHovered() ? ToCanvas(ImGui::GetMousePos()) : center + vec2(40.0f); + + std::unordered_map idMap; + selection.clear(); + for (auto& node : nodes) { + auto oldId = node.id; + node.id = graph.nextNodeId++; + node.position += target - center; + idMap[oldId] = node.id; + selection.insert(node.id); + graph.nodes.push_back(node); + } + + for (auto link : links) { + link.fromNode = idMap[link.fromNode]; + link.toNode = idMap[link.toNode]; + graph.links.push_back(link); + } + + compileRequested = true; + + } + + void MaterialGraphPanel::Arrange(Graph& graph) { + + auto isFrame = [](const Node& node) { + auto definition = NodeLibrary::Find(node); + return definition && definition->kind == NodeKind::Frame; + }; + + // Frames keep the nodes they hold and are fitted around them afterwards + std::vector>> frames; + for (auto& node : graph.nodes) { + if (isFrame(node)) + frames.emplace_back(&node, GetNodesInFrame(graph, node)); + } + + // Columns by the longest way to an output, from right to left + std::unordered_map depths; + for (const auto& node : graph.nodes) + depths[node.id] = 0; + for (size_t i = 0; i < graph.nodes.size(); i++) { + auto changed = false; + for (const auto& link : graph.links) { + auto depth = depths[link.toNode] + 1; + if (depth > depths[link.fromNode]) { + depths[link.fromNode] = depth; + changed = true; + } + } + if (!changed) + break; + } + + std::map> columns; + for (auto& node : graph.nodes) { + if (!isFrame(node)) + columns[depths[node.id]].push_back(&node); + } + + const float columnSpacing = nodeWidth + 80.0f; + const float rowSpacing = 24.0f; + + auto getHeight = [&](const Node& node) { + return GetNodeSize(node).y; + }; + + std::unordered_map centers; + + // Nodes go where their links want them. Nodes in each other's way push each other apart evenly, pushing them + // only downwards would stack long chains into a staircase + auto placeColumn = [&](int32_t depth, std::vector& nodes, const std::unordered_map& wanted) { + std::stable_sort(nodes.begin(), nodes.end(), [&](const Node* a, const Node* b) { return wanted.at(a->id) < wanted.at(b->id); }); + + struct Block { + std::vector nodes; + float offsetSum = 0.0f; + float height = 0.0f; + float top = 0.0f; + }; + std::vector blocks; + for (auto node : nodes) { + auto height = getHeight(*node); + Block block = { .nodes = { node }, .offsetSum = wanted.at(node->id) - 0.5f * height, .height = height }; + block.top = block.offsetSum; + blocks.push_back(block); + + while (blocks.size() > 1) { + auto& upper = blocks[blocks.size() - 2]; + auto& lower = blocks.back(); + if (upper.top + upper.height + rowSpacing <= lower.top) + break; + + auto shift = upper.height + rowSpacing; + upper.offsetSum += lower.offsetSum - shift * float(lower.nodes.size()); + upper.nodes.insert(upper.nodes.end(), lower.nodes.begin(), lower.nodes.end()); + upper.height += rowSpacing + lower.height; + upper.top = upper.offsetSum / float(upper.nodes.size()); + blocks.pop_back(); + } + } + + for (const auto& block : blocks) { + auto top = block.top; + for (auto node : block.nodes) { + auto height = getHeight(*node); + node->position = vec2(-float(depth) * columnSpacing, top); + centers[node->id] = top + 0.5f * height; + top += height + rowSpacing; + } + } + }; + + // Follow the outputs first, then a few rounds from both sides settle the rest + auto sweep = [&](bool towardsInputs) { + auto apply = [&](int32_t depth, std::vector& nodes) { + std::unordered_map wanted; + float nextFree = 0.0f; + for (auto node : nodes) { + float sum = 0.0f, count = 0.0f; + for (const auto& link : graph.links) { + auto isTarget = towardsInputs ? link.toNode == node->id : link.fromNode == node->id; + auto other = towardsInputs ? link.fromNode : link.toNode; + if (isTarget && centers.contains(other)) { + sum += centers[other]; + count += 1.0f; + } + } + if (count > 0.0f) { + wanted[node->id] = sum / count; + } + else { + // Nothing to follow, the node stays where it is or below the others + wanted[node->id] = centers.contains(node->id) ? centers[node->id] : nextFree; + nextFree += getHeight(*node) + rowSpacing; + } + } + placeColumn(depth, nodes, wanted); + }; + + if (towardsInputs) { + for (auto iter = columns.rbegin(); iter != columns.rend(); iter++) + apply(iter->first, iter->second); + } + else { + for (auto iter = columns.begin(); iter != columns.end(); iter++) + apply(iter->first, iter->second); + } + }; + + sweep(false); + for (int32_t round = 0; round < 3; round++) { + sweep(true); + sweep(false); + } + + for (auto& [frame, nodes] : frames) { + vec2 boundsMin(FLT_MAX), boundsMax(-FLT_MAX); + for (auto id : nodes) { + auto node = graph.GetNode(id); + if (!node) + continue; + boundsMin = glm::min(boundsMin, node->position); + boundsMax = glm::max(boundsMax, node->position + GetNodeSize(*node)); + } + if (nodes.empty()) + continue; + + const float padding = 24.0f; + frame->position = boundsMin - vec2(padding, padding + frameHeaderHeight); + frame->size = boundsMax - boundsMin + vec2(2.0f * padding, 2.0f * padding + frameHeaderHeight); + } + + modified = true; + frameRequested = true; + + } + + void MaterialGraphPanel::Frame(const Graph& graph) { + + if (graph.nodes.empty() || canvasSize.x <= 0.0f || canvasSize.y <= 0.0f) + return; + + vec2 boundsMin(FLT_MAX), boundsMax(-FLT_MAX); + for (const auto& node : graph.nodes) { + if (frameOnlySelection && !selection.contains(node.id)) + continue; + boundsMin = glm::min(boundsMin, node.position); + boundsMax = glm::max(boundsMax, node.position + GetNodeSize(node)); + } + frameOnlySelection = false; + + const float margin = 40.0f; + auto extent = glm::max(boundsMax - boundsMin, vec2(1.0f)); + zoom = std::clamp(std::min((canvasSize.x - 2.0f * margin) / extent.x, (canvasSize.y - 2.0f * margin) / extent.y), minZoom, 1.25f); + pan = vec2(canvasSize.x, canvasSize.y) * 0.5f / zoom - (boundsMin + boundsMax) * 0.5f; + + } + + ImVec4 MaterialGraphPanel::GetValueColor(ValueType type) { + + return Theme::GraphValue(int32_t(type)); + + } + + const char* MaterialGraphPanel::GetValueName(ValueType type) { + + switch (type) { + case ValueType::Float: return "Number"; + case ValueType::Vec2: return "Vector 2"; + case ValueType::Vec3: return "Vector 3"; + case ValueType::Vec4: return "Vector 4"; + case ValueType::Texture: return "Texture"; + default: return "Any"; + } + + } + +} diff --git a/src/editor/ui/panels/MaterialGraphPanel.h b/src/editor/ui/panels/MaterialGraphPanel.h new file mode 100644 index 000000000..ff3238d3e --- /dev/null +++ b/src/editor/ui/panels/MaterialGraphPanel.h @@ -0,0 +1,260 @@ +#pragma once + +#include "Panel.h" +#include "MaterialGraphPreviews.h" +#include "ResourceSelectionPanel.h" +#include "ui/CodeEditor.h" + +#include "materialgraph/Compiler.h" +#include "materialgraph/MaterialGraph.h" +#include "materialgraph/NodeLibrary.h" +#include "resource/Resource.h" + +#include + +#include +#include +#include +#include +#include + +namespace Atlas::Editor::UI { + + // Canvas to edit the nodes and links of a material graph. Generates the shaders again after each change + class MaterialGraphPanel : public Panel { + + public: + MaterialGraphPanel() : Panel("Graph") {} + + // Renders the canvas into the current window, returns whether the graph was compiled. The previews of + // nodes show the values of the material, or the defaults of the graph without one + bool Render(const ResourceHandle& graph, const Material* material = nullptr); + + // Forgets everything about the last graph, needed when another graph is shown from now on + void Reset(); + + void FrameAll(); + + void Arrange(MaterialGraph::Graph& graph); + + void OpenAddMenu(); + + void ShowGeneratedCode(); + + // The graph got an earlier state, e.g. by an undo of the editor + void OnGraphRestored(const MaterialGraph::Graph& graph); + + void SelectAll(const MaterialGraph::Graph& graph); + + void DeleteSelection(MaterialGraph::Graph& graph); + + void DuplicateSelection(MaterialGraph::Graph& graph); + + // A frame around the selected nodes + void FrameSelection(MaterialGraph::Graph& graph); + + void CopySelection(const MaterialGraph::Graph& graph); + + void Paste(MaterialGraph::Graph& graph); + + void ToggleMaximized(); + + // Whether nodes changed since the last save + bool modified = false; + + // The canvas takes the whole editor, the window hosting the panel decides how + bool maximized = false; + + private: + struct PinRef { + uint32_t node = 0; + std::string pin; + bool isOutput = false; + + bool IsValid() const { return node != 0; } + }; + + enum class RowKind { + Output = 0, + Input, + Value, + Text, + Preview + }; + + struct Row { + RowKind kind = RowKind::Output; + const MaterialGraph::OutputDefinition* output = nullptr; + const MaterialGraph::InputDefinition* input = nullptr; + float height = 0.0f; + }; + + // Positions of a node on the screen, updated every frame + struct NodeLayout { + ImVec2 min; + ImVec2 max; + float headerHeight = 0.0f; + std::vector rows; + std::unordered_map outputPins; + std::unordered_map inputPins; + }; + + enum class Interaction { + None = 0, + Panning, + MovingNodes, + BoxSelection, + DraggingLink, + ResizingFrame + }; + + enum class PreviewMode { + None = 0, + // Nodes where a picture says more than the values + Key, + All + }; + + ImVec2 ToScreen(vec2 position) const; + + vec2 ToCanvas(ImVec2 position) const; + + void UpdateLayouts(MaterialGraph::Graph& graph); + + void DrawGrid(ImDrawList* drawList, ImVec2 min, ImVec2 max); + + void DrawFrames(ImDrawList* drawList, MaterialGraph::Graph& graph); + + void DrawLinks(ImDrawList* drawList, MaterialGraph::Graph& graph); + + void DrawNodes(ImDrawList* drawList, MaterialGraph::Graph& graph, const MaterialGraph::CompiledGraph* compiled); + + bool DrawNodeWidgets(MaterialGraph::Graph& graph, MaterialGraph::Node& node, const NodeLayout& layout); + + bool DrawInputWidget(MaterialGraph::Node& node, const MaterialGraph::InputDefinition& input, ImVec2 position, float width); + + bool DrawValueWidget(MaterialGraph::Node& node, const MaterialGraph::NodeDefinition& definition, ImVec2 position, float width); + + void DrawToolbar(MaterialGraph::Graph& graph, const MaterialGraph::CompiledGraph* compiled); + + void DrawMinimap(ImDrawList* drawList, MaterialGraph::Graph& graph, ImVec2 canvasMin, ImVec2 canvasMax); + + void DrawCodeWindow(const MaterialGraph::CompiledGraph* compiled); + + // The functions of the material graph shaders, suggested in the code of code nodes + void LoadCodeFunctionCompletions(); + + // The properties of the selected node and the settings of the graph + void DrawInspector(MaterialGraph::Graph& graph); + + // Without a single selected node: settings of the graph, errors and parameters, which select their node + void DrawGraphOverview(MaterialGraph::Graph& graph); + + bool HasPreview(const MaterialGraph::NodeDefinition& definition) const; + + void HandleInteractions(MaterialGraph::Graph& graph); + + void HandleShortcuts(const ResourceHandle& graph); + + void RenderNodeMenu(MaterialGraph::Graph& graph); + + void RenderAddMenu(MaterialGraph::Graph& graph); + + PinRef FindPin(const MaterialGraph::Graph& graph, ImVec2 position) const; + + uint32_t FindNode(const MaterialGraph::Graph& graph, ImVec2 position) const; + + const MaterialGraph::Link* FindLink(const MaterialGraph::Graph& graph, ImVec2 position) const; + + void AddNode(MaterialGraph::Graph& graph, const MaterialGraph::NodeDefinition& definition); + + // The pin of a new node the dropped link connects to, null if it can't connect to this kind of node + const std::string* FindPendingPartner(const MaterialGraph::Graph& graph, const MaterialGraph::NodeDefinition& definition) const; + + void InsertReroute(MaterialGraph::Graph& graph, MaterialGraph::Link link, vec2 position); + + std::vector GetNodesInFrame(const MaterialGraph::Graph& graph, const MaterialGraph::Node& frame) const; + + void Frame(const MaterialGraph::Graph& graph); + + vec2 GetNodeSize(const MaterialGraph::Node& node) const; + + static ImVec4 GetValueColor(MaterialGraph::ValueType type); + + static const char* GetValueName(MaterialGraph::ValueType type); + + // The graph while it renders + MaterialGraph::Graph* currentGraph = nullptr; + + vec2 pan = vec2(0.0f); + float zoom = 1.0f; + + ImVec2 canvasOrigin = ImVec2(0.0f, 0.0f); + ImVec2 canvasSize = ImVec2(0.0f, 0.0f); + ImVec2 lastCanvasSize = ImVec2(0.0f, 0.0f); + ImVec2 minimapMin = ImVec2(0.0f, 0.0f); + ImVec2 minimapMax = ImVec2(0.0f, 0.0f); + int32_t stableCanvasFrames = 0; + + std::unordered_map layouts; + std::unordered_set selection; + + Interaction interaction = Interaction::None; + PinRef draggedPin; + ImVec2 boxStart = ImVec2(0.0f, 0.0f); + bool nodesMoved = false; + + // A link dropped on the canvas connects to the node added from the menu + PinRef pendingPin; + vec2 addPosition = vec2(0.0f); + std::string addSearch; + bool focusAddSearch = false; + int32_t addRow = 0; + std::unordered_set openAddCategories; + + bool openAddMenu = false; + bool frameRequested = true; + bool frameOnlySelection = false; + bool showCode = false; + bool showInspector = true; + + PreviewMode previewMode = PreviewMode::Key; + MaterialGraphPreviews previews; + ResourceSelectionPanel textureSelectionPanel; + + uint32_t resizedFrame = 0; + // Nodes in moved frames move along with them + std::unordered_set movedWithFrames; + + // Generated code when a value changes, the mouse release decides for values baked into the shaders + bool compileRequested = false; + // The picker of a color is a popup, its item doesn't tell when the value is final + bool colorEdited = false; + // Name of the code input being renamed, its links move once the name is final + std::string renamedCodeInput; + + CodeEditor codeNodeEditor; + std::vector codeFunctionCompletions; + bool codeFunctionCompletionsLoaded = false; + // Code node which was edited but isn't compiled yet and the one the editor shows in this frame + uint32_t editedCodeNode = 0; + uint32_t shownCodeNode = 0; + // One for each stage of the generated code + CodeEditor generatedCodeEditors[4]; + + static std::string clipboard; + + static constexpr float minZoom = 0.02f; + static constexpr float nodeWidth = 230.0f; + static constexpr float rowHeight = 24.0f; + static constexpr float pinRadius = 6.0f; + static constexpr float rerouteSize = 22.0f; + static constexpr float previewHeight = 128.0f; + static constexpr float frameHeaderHeight = 34.0f; + static constexpr float inspectorWidth = 320.0f; + // Below this zoom only the titles and previews of nodes are shown + static constexpr float detailZoom = 0.45f; + + }; + +} diff --git a/src/editor/ui/panels/MaterialGraphParametersPanel.cpp b/src/editor/ui/panels/MaterialGraphParametersPanel.cpp new file mode 100644 index 000000000..797865b98 --- /dev/null +++ b/src/editor/ui/panels/MaterialGraphParametersPanel.cpp @@ -0,0 +1,194 @@ +#include "MaterialGraphParametersPanel.h" + +#include "../../Singletons.h" +#include "../../Theme.h" +#include "../Widgets.h" + +#include +#include +#include +#include +#include + +namespace Atlas::Editor::UI { + + void MaterialGraphParametersPanel::Render(Ref& material) { + + ImGui::PushID(GetNameID()); + textureSelectionPanel.Reset(); + + auto compiled = material->graph.IsLoaded() ? material->graph->GetCompiled() : nullptr; + if (compiled) { + for (const auto& error : compiled->errors) + Widgets::Callout(error.message.c_str(), Theme::Error()); + if (!compiled->parameters.empty()) + RenderParameters(*material, *compiled); + else + ImGui::TextDisabled("The graph has no parameters"); + } + + auto selectTexture = [&](ResourceHandle texture) { return textureSelectionPanel.Render(texture); }; + auto replacesSurface = compiled && compiled->valid && compiled->hasSurface; + if (!replacesSurface) { + materialPanel.Render(Singletons::imguiWrapper, material, selectTexture); + } + else if (ImGui::TreeNodeEx("Properties for ray tracing", ImGuiTreeNodeFlags_SpanAvailWidth)) { + Widgets::Callout("The graph describes the surface. Ray traced reflections, global illumination and shadows " + "don't run graphs, they use these values instead.", Theme::Accent()); + materialPanel.Render(Singletons::imguiWrapper, material, selectTexture); + ImGui::TreePop(); + } + + ImGui::PopID(); + + } + + void MaterialGraphParametersPanel::RenderParameters(Material& material, const MaterialGraph::CompiledGraph& compiled) { + + using namespace MaterialGraph; + + // Values come before textures, which are larger. Within that the graph decides + std::vector sorted; + for (const auto& parameter : compiled.parameters) + sorted.push_back(¶meter); + + std::map groupOrder; + for (auto parameter : sorted) { + auto [iter, inserted] = groupOrder.try_emplace(parameter->group, parameter->order); + if (!inserted) + iter->second = std::min(iter->second, parameter->order); + } + + auto getRank = [](const Parameter& parameter) { + return parameter.isColor ? 0 : parameter.type == ValueType::Texture ? 2 : 1; + }; + + std::stable_sort(sorted.begin(), sorted.end(), [&](const Parameter* a, const Parameter* b) { + // Parameters without a group are always on top + auto aKey = std::tuple(!a->group.empty(), groupOrder[a->group], a->group, a->order, getRank(*a), a->nodeId); + auto bKey = std::tuple(!b->group.empty(), groupOrder[b->group], b->group, b->order, getRank(*b), b->nodeId); + return aKey < bKey; + }); + + auto toLower = [](std::string text) { + std::transform(text.begin(), text.end(), text.begin(), [](unsigned char c) { return char(std::tolower(c)); }); + return text; + }; + + if (sorted.size() > maxParametersWithoutSearch) { + ImGui::SetNextItemWidth(-FLT_MIN); + ImGui::InputTextWithHint("##Search parameters", "Search parameters...", ¶meterSearch); + } + else { + parameterSearch.clear(); + } + + auto search = toLower(parameterSearch); + auto matches = [&](const Parameter& parameter) { + return toLower(parameter.name).find(search) != std::string::npos || toLower(parameter.group).find(search) != std::string::npos; + }; + + const auto iconColumnWidth = ImGui::GetTextLineHeight() + 2.0f * ImGui::GetStyle().FramePadding.x; + + for (size_t start = 0; start < sorted.size();) { + const auto& group = sorted[start]->group; + auto end = std::find_if(sorted.begin() + start, sorted.end(), [&](const Parameter* parameter) { return parameter->group != group; }); + auto count = std::count_if(sorted.begin() + start, end, [&](const Parameter* parameter) { return matches(*parameter); }); + + auto isOpen = count > 0; + if (count && !group.empty()) { + // A search shows all results, without changing which groups stay open afterwards + if (!search.empty()) { + ImGui::SeparatorText(group.c_str()); + } + else { + auto label = group + " (" + std::to_string(count) + ")###" + group; + auto flags = ImGuiTreeNodeFlags_NoTreePushOnOpen | ImGuiTreeNodeFlags_SpanAvailWidth | + (sorted.size() <= maxParametersWithoutSearch ? ImGuiTreeNodeFlags_DefaultOpen : 0); + isOpen = ImGui::TreeNodeEx(label.c_str(), flags); + } + } + + // The names line up with the labels of the properties below + if (isOpen && ImGui::BeginTable(("##Parameters" + group).c_str(), 3, + ImGuiTableFlags_SizingStretchProp | ImGuiTableFlags_NoSavedSettings)) { + ImguiExtension::UIElements::SetupPropertyLabelColumn("Name"); + ImGui::TableSetupColumn("Value", ImGuiTableColumnFlags_WidthStretch); + ImGui::TableSetupColumn("Reset", ImGuiTableColumnFlags_WidthFixed, iconColumnWidth); + + for (auto iter = sorted.begin() + start; iter != end; iter++) { + if (matches(**iter)) + RenderParameter(material, **iter); + } + + ImGui::EndTable(); + } + + start = size_t(end - sorted.begin()); + } + + } + + void MaterialGraphParametersPanel::RenderParameter(Material& material, const MaterialGraph::Parameter& parameter) { + + using namespace MaterialGraph; + + ImGui::PushID(parameter.name.c_str()); + ImGui::TableNextRow(); + + auto isTexture = parameter.type == ValueType::Texture; + auto isOverridden = isTexture ? material.graphTextures.contains(parameter.name) : material.graphValues.contains(parameter.name); + + // Names of parameters often are one word per capital letter + std::string name; + for (size_t i = 0; i < parameter.name.size(); i++) { + auto character = parameter.name[i]; + if (i > 0 && std::isupper(static_cast(character)) && std::islower(static_cast(parameter.name[i - 1]))) + name += ' '; + name += character; + } + + // Values of the graph are muted, the ones of this material stand out + ImGui::TableNextColumn(); + ImGui::AlignTextToFramePadding(); + ImguiExtension::UIElements::MeasurePropertyLabel(ImGui::CalcTextSize(name.c_str()).x); + if (isOverridden) + ImGui::TextUnformatted(name.c_str()); + else + ImGui::TextColored(Theme::TextMuted(), "%s", name.c_str()); + ImGui::SetItemTooltip("%s\n%s", parameter.name.c_str(), isOverridden ? "This material has its own value" : "Uses the default of the graph"); + + ImGui::TableNextColumn(); + if (isTexture) { + auto changed = false; + auto selected = textureSelectionPanel.Render(material.GetGraphTexture(parameter), changed); + if (changed) + material.SetGraphTexture(parameter.name, selected); + } + else { + auto value = material.GetGraphValue(parameter); + auto components = int32_t(parameter.type) + 1; + + auto changed = false; + ImGui::SetNextItemWidth(-FLT_MIN); + if (parameter.isColor) + changed = ImGui::ColorEdit3("##Value", &value.x); + else if (parameter.HasRange()) + changed = ImGui::SliderScalarN("##Value", ImGuiDataType_Float, &value.x, components, ¶meter.range.x, ¶meter.range.y); + else + changed = ImGui::DragScalarN("##Value", ImGuiDataType_Float, &value.x, components, 0.01f); + + if (changed) + material.SetGraphParameter(parameter.name, value); + } + + ImGui::TableNextColumn(); + if (isOverridden && Widgets::IconButton("Reset", Singletons::icons->Get(IconType::Reset), ImGui::GetTextLineHeight(), "Back to the default of the graph")) { + material.ResetGraphParameter(parameter.name); + } + + ImGui::PopID(); + + } + +} diff --git a/src/editor/ui/panels/MaterialGraphParametersPanel.h b/src/editor/ui/panels/MaterialGraphParametersPanel.h new file mode 100644 index 000000000..9df2ef1e1 --- /dev/null +++ b/src/editor/ui/panels/MaterialGraphParametersPanel.h @@ -0,0 +1,39 @@ +#pragma once + +#include "Panel.h" +#include "ResourceSelectionPanel.h" + +#include "Material.h" +#include "materialgraph/MaterialGraph.h" + +#include + +#include + +namespace Atlas::Editor::UI { + + // The parameters of the graph of a material with the values of the material, which overrides the defaults of the graph + class MaterialGraphParametersPanel : public Panel { + + public: + MaterialGraphParametersPanel() : Panel("Material graph parameters") {} + + // The parameters, followed by the properties of the material. Ray tracing uses them instead of a graph which + // describes the surface + void Render(Ref& material); + + void RenderParameters(Material& material, const MaterialGraph::CompiledGraph& compiled); + + private: + void RenderParameter(Material& material, const MaterialGraph::Parameter& parameter); + + std::string parameterSearch; + // Short lists stay open and don't need a search + static constexpr size_t maxParametersWithoutSearch = 12; + + ImguiExtension::MaterialPanel materialPanel; + ResourceSelectionPanel textureSelectionPanel; + + }; + +} diff --git a/src/editor/ui/panels/MaterialGraphPreviews.cpp b/src/editor/ui/panels/MaterialGraphPreviews.cpp new file mode 100644 index 000000000..4035799eb --- /dev/null +++ b/src/editor/ui/panels/MaterialGraphPreviews.cpp @@ -0,0 +1,188 @@ +#include "MaterialGraphPreviews.h" + +#include "../../Singletons.h" + +#include "Clock.h" +#include "graphics/GraphicsDevice.h" +#include "materialgraph/Compiler.h" +#include "materialgraph/PipelineCache.h" +#include "pipeline/PipelineManager.h" + +namespace Atlas::Editor::UI { + + using namespace MaterialGraph; + + void MaterialGraphPreviews::Invalidate() { + + revision++; + + } + + void MaterialGraphPreviews::Reset() { + + entries.clear(); + requested.clear(); + nextSlot = 0; + + } + + void MaterialGraphPreviews::Request(uint32_t nodeId) { + + requested.push_back(nodeId); + + } + + void MaterialGraphPreviews::Init() { + + evaluator = std::make_unique(); + + auto size = slotSize * slotsPerRow; + atlas = CreateRef(size, size, VK_FORMAT_R8G8B8A8_UNORM, Texture::Wrapping::ClampToEdge, + Texture::Filtering::Linear, false, true); + + rendering = Graphics::RenderingDesc{ .colorAttachments = { { .image = atlas->image } } }; + + } + + void MaterialGraphPreviews::Render(const Graph& graph, const Material* material) { + + + if (requested.empty()) + return; + + if (!evaluator) + Init(); + + frame++; + + auto generated = 0; + auto parameterShader = static_cast(nullptr); + + for (auto nodeId : requested) { + auto& entry = entries[nodeId]; + if (entry.slot < 0) { + if (nextSlot >= slotsPerRow * slotsPerRow) + continue; + entry.slot = nextSlot++; + } + + if (entry.revision != revision && generated < maxGeneratedPerFrame) { + generated++; + entry.revision = revision; + entry.shader = Compiler::CompilePreview(graph, nodeId); + entry.failed = !entry.shader.valid; + entry.rendered = false; + if (!entry.failed) + entry.config = evaluator->GetPipelineConfig(entry.shader, Graphics::AttachmentFormats(rendering), nullptr); + } + + if (entry.revision == revision && !entry.failed) + parameterShader = &entry.shader; + } + + if (!parameterShader) { + requested.clear(); + return; + } + + evaluator->UpdateParameters(parameterShader->parameters, parameterShader->parameterWords, material); + + // Values of the material changing render the previews again + Hash parameters = 0; + if (material) { + for (const auto& [name, value] : material->graphValues) { + HashCombine(parameters, name); + HashCombine(parameters, value.x); + HashCombine(parameters, value.y); + HashCombine(parameters, value.z); + } + for (const auto& [name, texture] : material->graphTextures) { + HashCombine(parameters, name); + HashCombine(parameters, texture.IsLoaded() ? texture->image.get() : nullptr); + } + } + // Textures finish loading in the background + for (const auto& parameter : parameterShader->parameters) + HashCombine(parameters, parameter.defaultTexture.IsLoaded() ? 1 : 0); + + auto parametersChanged = parameters != lastParameters; + lastParameters = parameters; + + auto isAnimationFrame = frame % animationInterval == 0; + + auto device = Graphics::GraphicsDevice::DefaultDevice; + Graphics::CommandList* commandList = nullptr; + + for (auto nodeId : requested) { + auto& entry = entries[nodeId]; + if (entry.slot < 0 || entry.revision != revision || entry.failed) + continue; + + if (entry.rendered && !parametersChanged && !(entry.shader.usesTime && isAnimationFrame)) + continue; + + if (PipelineCache::Request(entry.config, false) != PipelineCache::State::Ready) + continue; + + if (!commandList) { + commandList = device->GetCommandList(Graphics::GraphicsQueue); + commandList->BeginCommands(); + + if (!isAtlasPrepared) { + commandList->ImageMemoryBarrier(atlas->image, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_ACCESS_SHADER_READ_BIT, + VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); + isAtlasPrepared = true; + } + + commandList->BeginRendering(rendering); + } + + auto pipeline = PipelineManager::GetPipeline(entry.config); + commandList->BindPipeline(pipeline); + evaluator->planeVertexArray.Bind(commandList); + evaluator->Bind(commandList); + + auto x = (entry.slot % slotsPerRow) * slotSize; + auto y = (entry.slot / slotsPerRow) * slotSize; + commandList->SetViewport(x, y, slotSize, slotSize); + commandList->SetScissor(x, y, slotSize, slotSize); + + Evaluator::PushConstants constants = { .time = Clock::Get() }; + commandList->PushConstants("constants", &constants); + + commandList->Draw(4); + + entry.rendered = true; + } + + if (commandList) { + commandList->EndRendering(); + commandList->EndCommands(); + device->SubmitCommandList(commandList); + } + + requested.clear(); + + } + + bool MaterialGraphPreviews::GetImage(uint32_t nodeId, ImTextureID& texture, ImVec2& uvMin, ImVec2& uvMax) const { + + auto iter = entries.find(nodeId); + if (iter == entries.end() || iter->second.slot < 0 || !isAtlasPrepared) + return false; + + // A preview from before the last change is better than an empty node + if (!iter->second.rendered) + return false; + + const auto& slot = iter->second.slot; + auto scale = 1.0f / float(slotsPerRow); + uvMin = ImVec2(float(slot % slotsPerRow) * scale, float(slot / slotsPerRow) * scale); + uvMax = ImVec2(uvMin.x + scale, uvMin.y + scale); + texture = Singletons::imguiWrapper->GetTextureId(atlas.get()); + + return true; + + } + +} diff --git a/src/editor/ui/panels/MaterialGraphPreviews.h b/src/editor/ui/panels/MaterialGraphPreviews.h new file mode 100644 index 000000000..0c4e107dd --- /dev/null +++ b/src/editor/ui/panels/MaterialGraphPreviews.h @@ -0,0 +1,69 @@ +#pragma once + +#include "materialgraph/Evaluator.h" +#include "materialgraph/MaterialGraph.h" +#include "texture/Texture2D.h" + +#include + +#include +#include + +namespace Atlas::Editor::UI { + + // Small pictures of what nodes calculate, all in one texture. Shaders are compiled in the background for + // nodes in view, only nodes depending on the time render again regularly + class MaterialGraphPreviews { + + public: + // The graph changed, all previews need to be generated again + void Invalidate(); + + // Another graph is shown, its node ids mean something else + void Reset(); + + // Requests the preview of a node for this frame + void Request(uint32_t nodeId); + + void Render(const MaterialGraph::Graph& graph, const Material* material); + + // False while there is no picture of the node yet + bool GetImage(uint32_t nodeId, ImTextureID& texture, ImVec2& uvMin, ImVec2& uvMax) const; + + private: + struct Entry { + int32_t slot = -1; + int32_t revision = -1; + bool rendered = false; + bool failed = false; + MaterialGraph::EvaluationShader shader; + PipelineConfig config; + }; + + void Init(); + + ImVec2 GetSlotMin(int32_t slot) const; + + Scope evaluator; + + Ref atlas; + Graphics::RenderingDesc rendering; + bool isAtlasPrepared = false; + + std::unordered_map entries; + std::vector requested; + + int32_t revision = 0; + int32_t nextSlot = 0; + int32_t frame = 0; + Hash lastParameters = 0; + + static constexpr int32_t slotSize = 128; + static constexpr int32_t slotsPerRow = 16; + static constexpr int32_t maxGeneratedPerFrame = 6; + // Animated previews don't have to follow every frame + static constexpr int32_t animationInterval = 3; + + }; + +} diff --git a/src/editor/ui/panels/NavigationPanel.cpp b/src/editor/ui/panels/NavigationPanel.cpp new file mode 100644 index 000000000..9bc3bb455 --- /dev/null +++ b/src/editor/ui/panels/NavigationPanel.cpp @@ -0,0 +1,156 @@ +#include "NavigationPanel.h" +#include "../../Theme.h" +#include "../Widgets.h" +#include "../../Notifications.h" + +#include + +namespace Atlas::Editor::UI { + + void NavigationPanel::Update(const Ref& navigation) { + + // Building all tiles takes a while, the panel might not be looked at until it's done + if (!rebuilding || !navigation || !navigation->mesh || navigation->mesh->GetPendingTileCount() > 0) + return; + + Notifications::Push({ .message = "Rebuilt the navigation mesh with " + + std::to_string(navigation->mesh->GetTileCount()) + " tiles" }); + rebuilding = false; + + } + + void NavigationPanel::Render(Ref& navigation) { + + if (!navigation) { + Widgets::Callout("The scene has no navigation mesh. It is built around the camera from the static bodies and the terrain.", + Theme::TextMuted()); + Theme::PushPrimaryButton(); + if (ImGui::Button("Create navigation", ImVec2(-FLT_MIN, 0.0f))) + navigation = CreateRef(); + Theme::PopPrimaryButton(); + return; + } + + if (Widgets::SectionHeader("General", ImGuiTreeNodeFlags_DefaultOpen)) { + if (Widgets::BeginProperties("General")) { + Widgets::PropertyLabel("Enable", "Builds the navigation mesh around the camera while the scene updates"); + ImGui::Checkbox("##Enable", &navigation->enable); + auto maxRadius = navigation->mesh ? navigation->mesh->GetMaxRadius() : 500.0f; + char radiusTooltip[256]; + std::snprintf(radiusTooltip, sizeof(radiusTooltip), "Tiles are built within this distance around the camera, " + "tiles further away are removed.\nThe mesh holds 1024 tiles, which limits the radius to %.0f m with the " + "current tile size", maxRadius); + Widgets::PropertyLabel("Radius", radiusTooltip); + ImGui::DragFloat("##Radius", &navigation->radius, 1.0f, 16.0f, maxRadius, "%.0f m", ImGuiSliderFlags_AlwaysClamp); + Widgets::EndProperties(); + } + + if (navigation->mesh) { + ImGui::TextColored(Theme::TextMuted(), "%d tiles built, %d pending", navigation->mesh->GetTileCount(), + navigation->mesh->GetPendingTileCount()); + if (ImGui::Button("Rebuild", ImVec2(-FLT_MIN, 0.0f))) { + navigation->mesh->Invalidate(); + rebuilding = true; + } + ImGui::SetItemTooltip("Builds all tiles again. Tiles also rebuild by themselves where static bodies or terrain heights change"); + } + } + + if (!ImGui::IsAnyItemActive()) + editedSettings = navigation->settings; + auto& settings = editedSettings; + auto applySettings = [&]() { + if (ImGui::IsItemDeactivatedAfterEdit()) + navigation->settings = settings; + }; + + if (Widgets::SectionHeader("Agent") && Widgets::BeginProperties("Agent")) { + Widgets::PropertyLabel("Radius", "How far the mesh stays away from walls and edges, about the radius of a character"); + ImGui::SliderFloat("##Agent radius", &settings.agentRadius, 0.05f, 3.0f, "%.2f m"); + applySettings(); + Widgets::PropertyLabel("Height", "The free space a character needs above the floor, lower passages aren't walkable"); + ImGui::SliderFloat("##Height", &settings.agentHeight, 0.2f, 5.0f, "%.2f m"); + applySettings(); + Widgets::PropertyLabel("Max climb", "Steps up to this height are walked over, higher ledges separate the areas"); + ImGui::SliderFloat("##Max climb", &settings.agentMaxClimb, 0.0f, 2.0f, "%.2f m"); + applySettings(); + Widgets::PropertyLabel("Max slope", "Steeper ground isn't walkable"); + ImGui::SliderFloat("##Max slope", &settings.agentMaxSlope, 0.0f, 85.0f, "%.0f deg"); + applySettings(); + Widgets::EndProperties(); + } + + if (Widgets::SectionHeader("Voxelization")) { + if (Widgets::BeginProperties("Voxelization")) { + Widgets::PropertyLabel("Cell size", "Horizontal resolution of the voxels the mesh is built from. Smaller cells follow walls and\n" + "gaps more exactly, but take longer to build and produce more polygons"); + ImGui::SliderFloat("##Cell size", &settings.cellSize, 0.05f, 1.0f, "%.2f m"); + applySettings(); + Widgets::PropertyLabel("Cell height", "Vertical resolution of the voxels, steps and the agent height are rounded to it"); + ImGui::SliderFloat("##Cell height", &settings.cellHeight, 0.05f, 1.0f, "%.2f m"); + applySettings(); + Widgets::PropertyLabel("Tile size", "Side length of the tiles which are built and replaced on their own. Larger tiles allow a larger\n" + "radius, but take longer to rebuild and can exceed the 4096 polygons of a tile in dense areas\n" + "(the tile then stays empty and the log names it). It doesn't change the precision"); + ImGui::SliderFloat("##Tile size", &settings.tileSize, 8.0f, 128.0f, "%.0f m"); + applySettings(); + Widgets::EndProperties(); + } + ImGui::TextColored(Theme::TextMuted(), "Changing the agent or voxelization settings rebuilds the mesh"); + } + + if (Widgets::SectionHeader("Building") && Widgets::BeginProperties("Building")) { + Widgets::PropertyLabel("Tiles per frame", "Tiles whose geometry (static bodies and terrain) is collected on the main thread each frame.\n" + "Fewer keep the frame time steady, more fill a new area faster"); + ImGui::SliderInt("##Tiles per frame", &navigation->maxTileStartsPerUpdate, 1, 16, "%d", ImGuiSliderFlags_AlwaysClamp); + Widgets::PropertyLabel("Concurrent builds", "Tiles built in jobs at the same time. Each build takes one worker of the pool below"); + ImGui::SliderInt("##Concurrent builds", &navigation->maxConcurrentBuilds, 1, 32, "%d", ImGuiSliderFlags_AlwaysClamp); + + const char* priorities[] = { "High", "Medium", "Low" }; + auto priority = int32_t(navigation->buildPriority); + Widgets::PropertyLabel("Job priority", "The worker pool of the job system the tiles are built in. High shares the workers of the\n" + "frame (scene update, rendering), medium and low have their own workers with a lower thread priority"); + if (ImGui::Combo("##Job priority", &priority, priorities, IM_ARRAYSIZE(priorities))) + navigation->buildPriority = JobPriority(priority); + Widgets::EndProperties(); + } + + if (Widgets::SectionHeader("Debug", ImGuiTreeNodeFlags_DefaultOpen)) { + auto pathTestChanged = false; + if (Widgets::BeginProperties("Debug")) { + Widgets::PropertyLabel("Show mesh", "Draws the edges of the polygons of all built tiles"); + ImGui::Checkbox("##Show mesh", &showMesh); + Widgets::PropertyLabel("Path test", "Finds a path between two points in the viewport, like the characters of a game would"); + pathTestChanged = ImGui::Checkbox("##Path test", &pathTest); + Widgets::EndProperties(); + } + if (pathTestChanged && !pathTest) { + pathStart.reset(); + pathGoal.reset(); + path.clear(); + } + + if (pathTest) { + ImGui::TextColored(Theme::TextMuted(), "Right click sets the start, the next one the goal"); + if (pathStart && pathGoal) { + if (path.empty()) { + Widgets::Callout("No path between the points on the built tiles", Theme::Warning()); + } + else { + auto length = 0.0f; + for (size_t i = 1; i < path.size(); i++) + length += glm::distance(path[i - 1], path[i]); + ImGui::Text("%d corners, %.1f m", int32_t(path.size()), length); + } + } + } + } + + ImGui::Separator(); + if (Widgets::DangerButton("Remove navigation")) + navigation = nullptr; + ImGui::SetItemTooltip("Removes the navigation from the scene, scripts which use it don't find paths anymore"); + + } + +} diff --git a/src/editor/ui/panels/NavigationPanel.h b/src/editor/ui/panels/NavigationPanel.h new file mode 100644 index 000000000..175197064 --- /dev/null +++ b/src/editor/ui/panels/NavigationPanel.h @@ -0,0 +1,39 @@ +#pragma once + +#include "Panel.h" +#include "navigation/Navigation.h" + +#include + +namespace Atlas::Editor::UI { + + class NavigationPanel : public Panel { + + public: + NavigationPanel() : Panel("Navigation") {} + + // Tells when a rebuild finished, also while the panel isn't shown + void Update(const Ref& navigation); + + void Render(Ref& navigation); + + // Changes are applied when an edit ends, every change rebuilds the mesh + Navigation::NavigationSettings editedSettings; + + bool showMesh = false; + bool rebuilding = false; + + // The drawn edges, collected again when the mesh changes + std::vector meshEdges; + uint64_t meshEdgesRevision = 0; + const Navigation::NavigationMesh* meshEdgesMesh = nullptr; + + // Right clicks into the viewport set the start and the goal of a test path + bool pathTest = false; + std::optional pathStart; + std::optional pathGoal; + std::vector path; + + }; + +} diff --git a/src/editor/ui/panels/PopupPanels.cpp b/src/editor/ui/panels/PopupPanels.cpp index 18760d51a..ecd141b1f 100644 --- a/src/editor/ui/panels/PopupPanels.cpp +++ b/src/editor/ui/panels/PopupPanels.cpp @@ -8,7 +8,9 @@ #include "Singletons.h" #include "Notifications.h" #include "Theme.h" +#include "../Widgets.h" #include "loader/AssetLoader.h" +#include "scene/SpacePartitioning.h" #include #include @@ -34,9 +36,9 @@ namespace Atlas::Editor::UI { return; static std::string name; - static auto minSize = glm::vec3(-2048.0f); - static auto maxSize = glm::vec3(2048.0f); - static int32_t octreeDepth = 5; + static auto minSize = vec3(-2048.0f); + static auto maxSize = vec3(2048.0f); + static int32_t octreeDepth = 8; bool popupNew = false; @@ -51,14 +53,15 @@ namespace Atlas::Editor::UI { ImGui::SeparatorText("Scene"); - if (popupNew) - ImGui::SetKeyboardFocusHere(); - ImGui::InputTextWithHint("Name", "Type scene name here", &name); + if (Widgets::BeginProperties("Scene")) { + Widgets::PropertyLabel("Name"); + if (popupNew) + ImGui::SetKeyboardFocusHere(); + ImGui::InputTextWithHint("##Name", "Type scene name here", &name); + Widgets::EndProperties(); + } - ImGui::SeparatorText("Bounds"); - ImGui::DragFloat3("Min size", &minSize[0], 1.0f, -8192.0f, 8192.0f, "%.3f", ImGuiSliderFlags_Logarithmic); - ImGui::DragFloat3("Max size", &maxSize[0], 1.0f, -8192.0f, 8192.0f, "%.3f", ImGuiSliderFlags_Logarithmic); - ImGui::SliderInt("Octree depth", &octreeDepth, 1, 12); + RenderOctreeSettings(minSize, maxSize, octreeDepth); auto confirm = RenderDialogFooter("Create", ValidateSceneName(name)); @@ -70,6 +73,7 @@ namespace Atlas::Editor::UI { if (alreadyExisted) { Log::Warning("Scene couldn't be created due to scene with same name existing already"); + Notifications::Push({ .message = "A scene named " + name + " exists already", .type = NotificationType::Warning }); } } @@ -90,12 +94,13 @@ namespace Atlas::Editor::UI { return; static std::string name; - static auto minSize = glm::vec3(-2048.0f); - static auto maxSize = glm::vec3(2048.0f); - static int32_t octreeDepth = 5; + static auto minSize = vec3(-2048.0f); + static auto maxSize = vec3(2048.0f); + static int32_t octreeDepth = 8; static bool invertUVs = true; static bool addRigidBodies = true; static bool makeMeshesStatic = false; + static bool convertTexturesToKtx = true; bool popupNew = false; @@ -114,27 +119,38 @@ namespace Atlas::Editor::UI { ImGui::TextDisabled("Source: %s", filename.c_str()); ImGui::SeparatorText("Scene"); - if (popupNew) - ImGui::SetKeyboardFocusHere(); - ImGui::InputTextWithHint("Name", "Type scene name here", &name); + if (Widgets::BeginProperties("Scene")) { + Widgets::PropertyLabel("Name"); + if (popupNew) + ImGui::SetKeyboardFocusHere(); + ImGui::InputTextWithHint("##Name", "Type scene name here", &name); + Widgets::EndProperties(); + } - ImGui::SeparatorText("Bounds"); - ImGui::DragFloat3("Min size", &minSize[0], 1.0f, -8192.0f, 8192.0f, "%.3f", ImGuiSliderFlags_Logarithmic); - ImGui::DragFloat3("Max size", &maxSize[0], 1.0f, -8192.0f, 8192.0f, "%.3f", ImGuiSliderFlags_Logarithmic); - ImGui::SliderInt("Octree depth", &octreeDepth, 1, 12); + RenderOctreeSettings(minSize, maxSize, octreeDepth); ImGui::SeparatorText("Import"); - ImGui::Checkbox("Invert UVs", &invertUVs); - ImGui::Checkbox("Attach mesh rigid body components", &addRigidBodies); - ImGui::Checkbox("Make meshes static", &makeMeshesStatic); + if (Widgets::BeginProperties("Import")) { + Widgets::PropertyLabel("Invert UVs"); + ImGui::Checkbox("##Invert UVs", &invertUVs); + Widgets::PropertyLabel("Attach mesh rigid body components"); + ImGui::Checkbox("##Attach mesh rigid body components", &addRigidBodies); + Widgets::PropertyLabel("Make meshes static"); + ImGui::Checkbox("##Make meshes static", &makeMeshesStatic); + Widgets::PropertyLabel("Convert textures to KTX2"); + ImGui::Checkbox("##Convert textures to KTX2", &convertTexturesToKtx); + Widgets::EndProperties(); + } auto confirm = RenderDialogFooter("Import", ValidateSceneName(name)); if (confirm == DialogResult::Confirm) { Singletons::blockingOperation->Block("Importing scene. Please wait...", [&]() { + auto textureFormat = convertTexturesToKtx ? Loader::ImportTextureFormat::KTX2 : + Loader::ImportTextureFormat::Original; auto scene = DataCreator::CreateSceneFromMesh(filename, minSize, maxSize, - octreeDepth, invertUVs, addRigidBodies, makeMeshesStatic); + octreeDepth, invertUVs, addRigidBodies, makeMeshesStatic, textureFormat); scene->name = name; bool alreadyExisted; @@ -142,11 +158,12 @@ namespace Atlas::Editor::UI { if (alreadyExisted) { Log::Warning("Scene couldn't be created due to scene with same name existing already"); - Notifications::Push({ .message = "Error importing scene " + scene->name }); + Notifications::Push({ .message = "Couldn't import scene " + scene->name + ", a scene with this name exists already", + .type = NotificationType::Error }); return; } - Notifications::Push({ .message = "Imported scene " + scene->name }); + Notifications::Push({ .message = "The meshes and textures of " + scene->name + " import in the background" }); }); } @@ -161,6 +178,36 @@ namespace Atlas::Editor::UI { } + void PopupPanels::RenderOctreeSettings(vec3& min, vec3& max, int32_t& depth) { + + ImGui::SeparatorText("Octree"); + if (Widgets::BeginProperties("Octree")) { + Widgets::PropertyLabel("Min size"); + ImGui::DragFloat3("##Min size", &min[0], 1.0f, -8192.0f, 8192.0f, "%.3f", ImGuiSliderFlags_Logarithmic); + Widgets::PropertyLabel("Max size"); + ImGui::DragFloat3("##Max size", &max[0], 1.0f, -8192.0f, 8192.0f, "%.3f", ImGuiSliderFlags_Logarithmic); + max = glm::max(max, min + 1.0f); + + Widgets::PropertyLabel("Depth"); + ImGui::SliderInt("##Depth", &depth, 1, 12); + Widgets::EndProperties(); + } + + auto cellSize = Scene::SpacePartitioning::GetCellSize(min, max, depth); + ImGui::TextDisabled("Cells of %.1f x %.1f x %.1f m", cellSize.x, cellSize.y, cellSize.z); + + // Coarse cells make the queries of large worlds with many small meshes slow + auto suggestedDepth = Scene::SpacePartitioning::GetSuggestedDepth(min, max); + if (depth != suggestedDepth) { + ImGui::SameLine(); + auto label = "Use depth " + std::to_string(suggestedDepth) + " for " + + std::to_string(int32_t(Scene::SpacePartitioning::suggestedCellSize)) + " m cells"; + if (ImGui::SmallButton(label.c_str())) + depth = suggestedDepth; + } + + } + void PopupPanels::SetupDialog() { // Centered, fixed width and height fitting the content @@ -248,11 +295,17 @@ namespace Atlas::Editor::UI { ImGui::SetKeyboardFocusHere(); - // Center the text in the popup + // The spinning ring and the text next to it, centered together in the popup + const float spinnerScale = 1.5f; auto& blockText = Singletons::blockingOperation->blockText; auto textSize = ImGui::CalcTextSize(blockText.c_str()); + auto spinnerSize = ImGui::GetTextLineHeight() * spinnerScale; + auto spacing = ImGui::GetStyle().ItemSpacing.x * 2.0f; auto windowSize = ImGui::GetWindowSize(); - ImGui::SetCursorPos(ImVec2((windowSize.x - textSize.x) * 0.5f, (windowSize.y - textSize.y) * 0.5f)); + auto startX = (windowSize.x - (spinnerSize + spacing + textSize.x)) * 0.5f; + ImGui::SetCursorPos(ImVec2(startX, (windowSize.y - spinnerSize) * 0.5f)); + Widgets::Spinner(spinnerScale); + ImGui::SetCursorPos(ImVec2(startX + spinnerSize + spacing, (windowSize.y - textSize.y) * 0.5f)); ImGui::TextUnformatted(blockText.c_str()); if (!Singletons::blockingOperation->block) diff --git a/src/editor/ui/panels/PopupPanels.h b/src/editor/ui/panels/PopupPanels.h index 38ef5257a..d65b7ca2f 100644 --- a/src/editor/ui/panels/PopupPanels.h +++ b/src/editor/ui/panels/PopupPanels.h @@ -2,6 +2,7 @@ #include #include +#include namespace Atlas::Editor::UI { @@ -34,6 +35,9 @@ namespace Atlas::Editor::UI { static DialogResult RenderDialogFooter(const char* confirmLabel, const std::string& error); + // Bounds and depth of the octree of a new scene with the size of its cells + static void RenderOctreeSettings(vec3& min, vec3& max, int32_t& depth); + static void RenderNewScenePopup(); static void RenderImportScenePopup(); diff --git a/src/editor/ui/panels/ResourceSelectionPanel.h b/src/editor/ui/panels/ResourceSelectionPanel.h index df6680d9f..3103a89cb 100644 --- a/src/editor/ui/panels/ResourceSelectionPanel.h +++ b/src/editor/ui/panels/ResourceSelectionPanel.h @@ -2,12 +2,18 @@ #include "Panel.h" #include "Singletons.h" +#include "ContentPreviews.h" #include "Notifications.h" #include "Theme.h" +#include "ui/Widgets.h" #include "ui/popups/ResourceSelectionPopup.h" #include "tools/ResourcePayloadHelper.h" #include "ui/windows/ContentBrowserWindow.h" +#include +#include +#include + namespace Atlas::Editor::UI { template @@ -27,11 +33,35 @@ namespace Atlas::Editor::UI { const float padding = 8.0f; + if constexpr (std::is_same_v) { + if (resourceHandle.IsLoaded()) { + ImguiExtension::UIElements::TexturePreview(Singletons::imguiWrapper, &resourceHandle); + ImGui::SameLine(); + } + } + else if (resourceHandle.IsValid() && !resourceHandle.IsGenerated()) { + const auto& path = resourceHandle.GetResource()->path; + auto previewSize = ImGui::GetFrameHeight(); + Singletons::contentPreviews->Render(path, ImVec2(previewSize, previewSize)); + if (ImGui::BeginItemTooltip()) { + Singletons::contentPreviews->Render(path, ImVec2(8.0f * previewSize, 8.0f * previewSize)); + ImGui::EndTooltip(); + } + ImGui::SameLine(); + } + auto region = ImGui::GetContentRegionAvail(); auto lineHeight = ImGui::GetTextLineHeight(); auto deleteButtonSize = ImVec2(lineHeight, lineHeight); auto resourceButtonSize = region.x - (resourceHandle.IsValid() ? deleteButtonSize.x + 2.0f * padding : 0.0f); + // Materials and graphs open in their editor from here, like meshes do from their component + auto canOpen = false; + if constexpr (std::is_same_v || std::is_same_v) + canOpen = resourceHandle.IsValid() && !resourceHandle.IsGenerated(); + if (canOpen) + resourceButtonSize -= deleteButtonSize.x + 2.0f * padding; + resourceChanged = false; auto buttonName = resourceHandle.IsValid() ? resourceHandle.GetResource()->GetFileName() : "Drop resource here##" + std::to_string(counter++); @@ -86,20 +116,33 @@ namespace Atlas::Editor::UI { resourceChanged = true; } - if (resourceHandle.IsValid()) { - ImGui::SameLine(); - - auto& deleteIcon = Singletons::icons->Get(IconType::Trash); - auto set = Singletons::imguiWrapper->GetTextureId(&deleteIcon); + // Buttons next to the resource have the frame padding of the resource button, so they are as high as the row + auto rowIconButton = [&](const char* id, IconType iconType, const char* tooltip) { + auto& icon = Singletons::icons->Get(iconType); + auto set = Singletons::imguiWrapper->GetTextureId(&icon); ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.0f, 0.0f, 0.0f, 0.0f)); ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 0.0f); - if (ImGui::ImageButton("Resource delete button", set, deleteButtonSize, ImVec2(0.1f, 0.1f), ImVec2(0.9f, 0.9f))) { + auto pressed = ImGui::ImageButton(id, set, deleteButtonSize, ImVec2(0.1f, 0.1f), ImVec2(0.9f, 0.9f)); + ImGui::PopStyleVar(); + ImGui::PopStyleColor(); + + ImGui::SetItemTooltip("%s", tooltip); + return pressed; + }; + + if (canOpen) { + ImGui::SameLine(); + if (rowIconButton("Resource open button", IconType::OpenInNew, "Open in material editor")) + ContentBrowserWindow::contentToEditPath = resourceHandle.GetResource()->path; + } + + if (resourceHandle.IsValid()) { + ImGui::SameLine(); + if (rowIconButton("Resource delete button", IconType::Trash, "Remove")) { resourceHandle = ResourceHandle(); resourceChanged = true; } - ImGui::PopStyleVar(); - ImGui::PopStyleColor(); } /* diff --git a/src/editor/ui/panels/SceneHierarchyPanel.cpp b/src/editor/ui/panels/SceneHierarchyPanel.cpp index b65a55bcf..4254232a1 100644 --- a/src/editor/ui/panels/SceneHierarchyPanel.cpp +++ b/src/editor/ui/panels/SceneHierarchyPanel.cpp @@ -1,7 +1,10 @@ #include "SceneHierarchyPanel.h" +#include "scene/SceneSerializer.h" #include "../Widgets.h" +#include "Clock.h" + #include #include #include @@ -19,12 +22,37 @@ namespace Atlas::Editor::UI { if (!searchJobResultRetrieved) { std::swap(matchSet, newMatchSet); + matchAll = false; + openSearchMatches |= openSearchMatchesPending; + openSearchMatchesPending = false; searchJobResultRetrieved = true; } - if (entitySearch == lastEntitySearch && lastAliveEntityCount == scene->GetEntityCount() && !hierarchyFilterChanged) + bool searchChanged = entitySearch != lastEntitySearch; + + // Without a search or filter everything matches, large scenes don't need to go through all their entities + if (entitySearch.empty() && (hierarchyFilter & GetAllFilterBits()) == GetAllFilterBits()) { + if (!matchAll) { + matchAll = true; + std::unordered_set().swap(matchSet); + std::unordered_set().swap(newMatchSet); + } + openSearchMatches |= searchChanged; + lastEntitySearch = entitySearch; + hierarchyFilterChanged = false; return; + } + bool settingsChanged = searchChanged || hierarchyFilterChanged || matchAll; + if (!settingsChanged && lastAliveEntityCount == scene->GetEntityCount()) + return; + + // Entities created while playing shouldn't copy all the pools every frame + if (!settingsChanged && Clock::Get() - lastSearchTime < 1.0f) + return; + + openSearchMatchesPending |= searchChanged; + lastSearchTime = Clock::Get(); lastEntitySearch = entitySearch; lastAliveEntityCount = scene->GetEntityCount(); hierarchyFilterChanged = false; @@ -33,29 +61,19 @@ namespace Atlas::Editor::UI { EntityData data{ .hierarchyPool = scene->entityManager.GetPool(), .namePool = scene->entityManager.GetPool(), - .transformPool = scene->entityManager.GetPool(), - .meshPool = scene->entityManager.GetPool(), - .textPool = scene->entityManager.GetPool(), - .audioPool = scene->entityManager.GetPool(), - .audioVolumePool = scene->entityManager.GetPool(), - .playerPool = scene->entityManager.GetPool(), - .rigidBodyPool = scene->entityManager.GetPool(), - .cameraPool = scene->entityManager.GetPool(), - .scriptPool = scene->entityManager.GetPool(), - .lightPool = scene->entityManager.GetPool(), + .componentStorages = Scene::CopyComponentStorages(scene.get()), + .search = entitySearch, + .filter = hierarchyFilter, }; - auto root = scene->GetEntityByName("Root"); - // Aquire scene here such that it can't be freed and copy important pools - JobSystem::Execute(searchJob, [&, scene = scene, root = root, data = std::move(data)](JobData&) mutable { + // Search should be case-insensitive + std::transform(data.search.begin(), data.search.end(), data.search.begin(), ::tolower); - // Search should be case-insensitive - transformedEntitySearch = entitySearch; - std::transform(transformedEntitySearch.begin(), transformedEntitySearch.end(), - transformedEntitySearch.begin(), ::tolower); + auto root = scene->GetRootEntity(); + // Aquire scene here such that it can't be freed. The job only works on copies, the scene and UI can change meanwhile + JobSystem::Execute(searchJob, [&, scene = scene, root = root, data = std::move(data)](JobData&) mutable { newMatchSet.clear(); - newMatchSet.reserve(scene->entityManager.Alive()); std::string nodeName; SearchHierarchy(data, root, newMatchSet, nodeName, false); }); @@ -71,13 +89,22 @@ namespace Atlas::Editor::UI { if (ImGui::IsDragDropActive() && ImGui::IsWindowHovered() && !ImGui::IsWindowFocused()) ImGui::SetWindowFocus(); - isFocused = ImGui::IsWindowFocused(); + // The sticky rows are a child window + isFocused = ImGui::IsWindowFocused(ImGuiFocusedFlags_ChildWindows); if (scene != nullptr) { bool selectionChanged = false; - auto root = scene->GetEntityByName("Root"); + hierarchyPool = &scene->entityManager.GetPool(); + + // Finding the root goes through all hierarchies + Scene::Entity root(rootEntity, &scene->entityManager); + auto rootHierarchy = root.IsValid() ? hierarchyPool->TryGet(root) : nullptr; + if (!rootHierarchy || !rootHierarchy->root) { + root = scene->GetRootEntity(); + rootEntity = root; + } if (ImGui::BeginPopupContextWindow(nullptr, ImGuiPopupFlags_NoOpenOverItems | ImGuiPopupFlags_MouseButtonRight)) { // Unselect entity in this case, since this popup could only be opened by clicking on emtpy space @@ -89,8 +116,6 @@ namespace Atlas::Editor::UI { ImGui::EndPopup(); } - std::string prevEntitySearch = entitySearch; - auto region = ImGui::GetContentRegionAvail(); auto lineHeight = ImGui::GetTextLineHeight(); auto buttonSize = ImVec2(lineHeight, lineHeight); @@ -104,7 +129,6 @@ namespace Atlas::Editor::UI { ImGui::GetFrameHeight())); ImGui::SetNextItemWidth(-FLT_MIN); ImGui::InputTextWithHint("##Search", "Search entities...", &entitySearch); - bool searchChanged = entitySearch != prevEntitySearch; if (ImGui::IsItemClicked()) selectionChanged = true; ImGui::EndChild(); @@ -120,9 +144,24 @@ namespace Atlas::Editor::UI { RenderFilterPopup(); - TraverseHierarchy(scene, root, matchSet, inFocus, searchChanged, &selectionChanged); + // A hidden window doesn't submit anything + if (!ImGui::GetCurrentWindow()->SkipItems) { + openRows.clear(); + stickyRows.clear(); + stickyRowsFound = false; - RenderExtendedHierarchy(scene, &selectionChanged); + TraverseHierarchy(scene, root, &selectionChanged); + FlushSkippedRows(); + RenderStickyRows(scene, &selectionChanged); + + openSearchMatches = false; + // Entities hidden by the search can't be revealed + revealEntity = ECS::EntityConfig::InvalidEntity; + revealOpenSet.clear(); + } + + if (showSceneSettings) + RenderExtendedHierarchy(scene, &selectionChanged); const auto& io = ImGui::GetIO(); bool controlDown; @@ -190,6 +229,8 @@ namespace Atlas::Editor::UI { item("Camera", EntityTemplate::Camera); item("Audio source", EntityTemplate::AudioSource); item("Text", EntityTemplate::Text); + ImGui::Separator(); + item("Fog volume", EntityTemplate::FogVolume); return created; @@ -209,6 +250,15 @@ namespace Atlas::Editor::UI { } + void SceneHierarchyPanel::RevealEntity(const Ref& scene, Scene::Entity entity) { + + revealEntity = entity; + revealOpenSet.clear(); + for (auto parent = scene->GetParentEntity(entity); parent.IsValid(); parent = scene->GetParentEntity(parent)) + revealOpenSet.insert(parent); + + } + void SceneHierarchyPanel::ClearSelection() { selectedEntity = Scene::Entity(); @@ -218,8 +268,205 @@ namespace Atlas::Editor::UI { } - void SceneHierarchyPanel::TraverseHierarchy(Ref& scene, Scene::Entity entity, - std::unordered_set& matchSet, bool inFocus, bool searchChanged, bool* selectionChanged) { + void SceneHierarchyPanel::TraverseHierarchy(Ref& scene, Scene::Entity entity, bool* selectionChanged) { + + // If we have a search term and the name doesn't match, return + bool matches = matchAll || matchSet.contains(entity); + if (!entity.IsValid() || (entity != rootEntity && !matches)) + return; + + auto window = ImGui::GetCurrentWindow(); + auto hierarchyComponent = hierarchyPool->TryGet(entity); + + // Same id and state as the tree node of the entity + auto storage = ImGui::GetStateStorage(); + ImGuiID id = 0; + if (hierarchyComponent) { + id = window->GetID(reinterpret_cast(static_cast(entity))); + if (openSearchMatches) + storage->SetInt(id, !entitySearch.empty() && matches ? 1 : 0); + if (!revealOpenSet.empty() && revealOpenSet.contains(entity)) + storage->SetInt(id, 1); + } + + // Rows outside of the window only count for the size of the content. A few more than visible are + // submitted, such that keyboard navigation can leave the visible area + auto rowY = window->DC.CursorPos.y + float(skippedRows) * rowHeight; + auto margin = 2.0f * rowHeight; + bool isRowVisible = rowY + rowHeight >= window->ClipRect.Min.y - margin && rowY <= window->ClipRect.Max.y + margin; + + // The first row below the stack of scrolled out ancestors decides which of them stay at the top + if (!stickyRowsFound) { + auto top = window->ClipRect.Min.y; + // At most half of the window, the outermost ancestors stay + auto maxCount = size_t(std::max(1.0f, 0.5f * window->ClipRect.GetHeight() / rowHeight)); + size_t count = 0; + while (count < openRows.size() && count < maxCount && openRows[count].position.y < top + float(count) * rowHeight) + count++; + if (rowY >= top + float(count) * rowHeight) { + stickyRows.assign(openRows.begin(), openRows.begin() + count); + stickyRowsFound = true; + } + } + + if (!isRowVisible && entity != revealEntity) { + skippedRows++; + + if (hierarchyComponent && storage->GetInt(id, 0) != 0) { + openRows.push_back({ entity, id, ImVec2(window->DC.CursorPos.x, rowY) }); + ImGui::TreePushOverrideID(id); + TraverseChildren(scene, entity, selectionChanged); + ImGui::TreePop(); + openRows.pop_back(); + } + return; + } + + FlushSkippedRows(); + RenderEntityRow(scene, entity, selectionChanged); + + } + + void SceneHierarchyPanel::TraverseChildren(Ref& scene, Scene::Entity entity, bool* selectionChanged) { + + auto hierarchyComponent = hierarchyPool->TryGet(entity); + if (!hierarchyComponent) + return; + + auto children = &hierarchyComponent->GetChildren(); + for (size_t i = 0; i < children->size(); i++) { + auto lastRenderedRows = renderedRows; + + TraverseHierarchy(scene, (*children)[i], selectionChanged); + + // Only rendered rows can change the hierarchy, e.g. by deleting entities + if (renderedRows != lastRenderedRows) { + hierarchyComponent = hierarchyPool->TryGet(entity); + if (!hierarchyComponent) + return; + children = &hierarchyComponent->GetChildren(); + } + } + + } + + void SceneHierarchyPanel::FlushSkippedRows() { + + if (skippedRows > 0) + ImGui::Dummy(ImVec2(0.0f, std::max(float(skippedRows) * rowHeight - ImGui::GetStyle().ItemSpacing.y, 0.0f))); + skippedRows = 0; + + } + + void SceneHierarchyPanel::RenderStickyRows(Ref& scene, bool* selectionChanged) { + + if (stickyRows.empty()) + return; + + auto window = ImGui::GetCurrentWindow(); + auto storage = ImGui::GetStateStorage(); + auto cursor = ImGui::GetCursorScreenPos(); + auto top = window->ClipRect.Min.y; + auto height = float(stickyRows.size()) * rowHeight; + + // A child window on top of the tree, such that the rows below don't get its clicks + ImGui::SetCursorScreenPos(ImVec2(window->ClipRect.Min.x, top)); + ImGui::PushStyleColor(ImGuiCol_ChildBg, ImGui::GetStyleColorVec4(ImGuiCol_WindowBg)); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f)); + ImGui::BeginChild("Sticky rows", ImVec2(window->ClipRect.GetWidth(), height), ImGuiChildFlags_None, + ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse); + + for (size_t i = 0; i < stickyRows.size(); i++) { + const auto& row = stickyRows[i]; + auto y = top + float(i) * rowHeight; + // The rows of the tree might have deleted it + if (!row.entity.IsValid()) + continue; + auto nameComponent = row.entity.TryGetComponent(); + auto name = nameComponent ? nameComponent->name : "Entity " + std::to_string(row.entity); + + ImGui::SetCursorScreenPos(ImVec2(row.position.x, y)); + ImGui::SetNextItemOpen(true); + auto flags = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_SpanAvailWidth | ImGuiTreeNodeFlags_FramePadding | + ImGuiTreeNodeFlags_NoTreePushOnOpen; + flags |= selectedEntities.contains(row.entity) ? ImGuiTreeNodeFlags_Selected : 0; + bool open = ImGui::TreeNodeEx(reinterpret_cast(static_cast(row.entity)), flags, "%s", name.c_str()); + + if (!open) { + // Collapsing scrolls the tree such that the entity stays where its header was + storage->SetInt(row.id, 0); + ImGui::SetScrollY(window, window->Scroll.y + row.position.y - y); + } + else if (ImGui::IsItemClicked(ImGuiMouseButton_Left) && !ImGui::IsItemToggledOpen()) { + SelectEntity(row.entity, ImGui::IsKeyDown(ImGuiKey_LeftShift)); + if (ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left)) + focusRequested = true; + *selectionChanged = true; + } + + if (auto droppedEntity = AcceptEntityDrop(scene); droppedEntity.IsValid()) + MoveEntities(scene, row.entity, droppedEntity); + } + + ImGui::GetWindowDrawList()->AddLine(ImVec2(window->ClipRect.Min.x, top + height - 1.0f), + ImVec2(window->ClipRect.Max.x, top + height - 1.0f), ImGui::GetColorU32(ImGuiCol_Separator)); + + ImGui::EndChild(); + ImGui::PopStyleVar(); + ImGui::PopStyleColor(); + ImGui::SetCursorScreenPos(cursor); + + } + + Scene::Entity SceneHierarchyPanel::AcceptEntityDrop(const Ref& scene) { + + Scene::Entity droppedEntity; + if (!ImGui::BeginDragDropTarget()) + return droppedEntity; + + auto dropPayload = ImGui::GetDragDropPayload(); + if (dropPayload->IsDataType(typeid(Scene::Entity).name())) { + // Entities dragged from another scene window stay where they are + auto payload = ImGui::AcceptDragDropPayload(typeid(Scene::Entity).name()); + if (payload && static_cast(payload->Data)->GetScene() == scene.get()) + droppedEntity = *static_cast(payload->Data); + } + + ImGui::EndDragDropTarget(); + return droppedEntity; + + } + + void SceneHierarchyPanel::MoveEntities(Ref& scene, Scene::Entity parent, Scene::Entity droppedEntity) { + + // The selection moves when the dragged entity is part of it, ancestors of the target can't move below it + std::vector movedEntities; + if (selectedEntities.contains(droppedEntity)) { + for (auto ecsEntity : selectedEntities) + movedEntities.emplace_back(ecsEntity, &scene->entityManager); + } + else { + movedEntities.push_back(droppedEntity); + } + for (auto ancestor = parent; ancestor.IsValid(); ancestor = scene->GetParentEntity(ancestor)) + std::erase(movedEntities, ancestor); + + if (history) + history->BeginMove(scene, movedEntities); + for (auto movedEntity : movedEntities) { + movedEntity.SetParent(parent); + sceneChanged = true; + } + if (history) + history->EndMove("Move entities"); + + } + + void SceneHierarchyPanel::RenderEntityRow(Ref& scene, Scene::Entity entity, bool* selectionChanged) { + + renderedRows++; + auto rowStart = ImGui::GetCursorScreenPos(); + auto rowStartY = rowStart.y; ImGuiTreeNodeFlags baseFlags = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_AllowOverlap | ImGuiTreeNodeFlags_SpanAvailWidth | ImGuiTreeNodeFlags_FramePadding; @@ -233,25 +480,8 @@ namespace Atlas::Editor::UI { std::string nodeName = nameComponent ? nameComponent->name : "Entity " + std::to_string(entity); - // If the search term matches we want to display everything below this item in the hierarchy - bool validSearch = matchSet.contains(entity); - bool rootNode = nodeName == "Root"; - // If we have a search term and the name doesn't match, return - if (!rootNode && (!validSearch || !entity.IsValid())) - return; - - auto lineHeight = ImGui::GetTextLineHeightWithSpacing(); - auto rectWidth = ImGui::GetContentRegionAvail().x; - ImVec2 cursorPos = ImGui::GetCursorScreenPos(); - bool isItemVisible = ImGui::IsRectVisible(cursorPos, ImVec2(cursorPos.x + rectWidth, cursorPos.y + lineHeight)); - - if (matchSet.contains(entity) && !entitySearch.empty() && searchChanged) - ImGui::SetNextItemOpen(true, ImGuiCond_Always); - else if (entitySearch.empty() && searchChanged || !matchSet.contains(entity) && searchChanged) - ImGui::SetNextItemOpen(false, ImGuiCond_Always); - auto nodeFlags = baseFlags; nodeFlags |= selectedEntities.contains(entity) ? ImGuiTreeNodeFlags_Selected : 0; @@ -259,190 +489,194 @@ namespace Atlas::Editor::UI { bool createEntity = false; bool deleteEntity = false; bool duplicateEntity = false; - bool droppedEntities = false; - - // Don't waste precious CPU cycles here if not visible - if (isItemVisible) { - auto entityId = static_cast(entity); - - // The visibility button sits in a fixed column on the right side of the row. The name is - // clipped before it, such that long names don't run underneath the button - const float eyePadding = 2.0f; - auto eyeIconSize = ImGui::GetTextLineHeight(); - auto eyeExtent = eyeIconSize + 2.0f * eyePadding; - auto eyeMinX = ImGui::GetCursorScreenPos().x + ImGui::GetContentRegionAvail().x - eyeExtent; - - // Hidden entities are dimmed - bool isHidden = nodeInvisibleSet.contains(entity); - if (isHidden) - ImGui::PushStyleColor(ImGuiCol_Text, ImGui::GetStyleColorVec4(ImGuiCol_TextDisabled)); - bool isRenaming = renamingEntity == entity && nameComponent && !rootNode; - nodeOpen = ImGui::TreeNodeEx(reinterpret_cast(entityId), nodeFlags, ""); - - auto rowMin = ImGui::GetItemRectMin(); - auto rowMax = ImGui::GetItemRectMax(); - - bool nameTruncated = false; - if (!isRenaming) { - auto textPos = ImVec2(rowMin.x + ImGui::GetTreeNodeToLabelSpacing(), rowMin.y + ImGui::GetStyle().FramePadding.y); - auto textMaxX = eyeMinX - ImGui::GetStyle().ItemInnerSpacing.x; - nameTruncated = textPos.x + ImGui::CalcTextSize(nodeName.c_str()).x > textMaxX; - ImGui::RenderTextEllipsis(ImGui::GetWindowDrawList(), textPos, ImVec2(textMaxX, rowMax.y), - textMaxX, textMaxX, nodeName.c_str(), nullptr, nullptr); - } - if (isHidden) - ImGui::PopStyleColor(); + Scene::Entity droppedEntity; + + auto entityId = static_cast(entity); + + // The visibility button sits in a fixed column on the right side of the row. The name is + // clipped before it, such that long names don't run underneath the button + const float eyePadding = 2.0f; + auto eyeIconSize = ImGui::GetTextLineHeight(); + auto eyeExtent = eyeIconSize + 2.0f * eyePadding; + auto eyeMinX = ImGui::GetCursorScreenPos().x + ImGui::GetContentRegionAvail().x - eyeExtent; + + // Hidden entities are dimmed + bool isHidden = nodeInvisibleSet.contains(entity); + if (isHidden) + ImGui::PushStyleColor(ImGuiCol_Text, ImGui::GetStyleColorVec4(ImGuiCol_TextDisabled)); + bool isRenaming = renamingEntity == entity && nameComponent && !rootNode; + nodeOpen = ImGui::TreeNodeEx(reinterpret_cast(entityId), nodeFlags, ""); + + auto rowMin = ImGui::GetItemRectMin(); + auto rowMax = ImGui::GetItemRectMax(); + + bool nameTruncated = false; + if (!isRenaming) { + auto textPos = ImVec2(rowMin.x + ImGui::GetTreeNodeToLabelSpacing(), rowMin.y + ImGui::GetStyle().FramePadding.y); + auto textMaxX = eyeMinX - ImGui::GetStyle().ItemInnerSpacing.x; + nameTruncated = textPos.x + ImGui::CalcTextSize(nodeName.c_str()).x > textMaxX; + ImGui::RenderTextEllipsis(ImGui::GetWindowDrawList(), textPos, ImVec2(textMaxX, rowMax.y), + textMaxX, textMaxX, nodeName.c_str(), nullptr, nullptr); + } + if (isHidden) + ImGui::PopStyleColor(); - // Full name for clipped names - if (nameTruncated && !ImGui::IsDragDropActive()) - ImGui::SetItemTooltip("%s", nodeName.c_str()); + // Full name for clipped names + if (nameTruncated && !ImGui::IsDragDropActive()) + ImGui::SetItemTooltip("%s", nodeName.c_str()); - // Double click focuses the camera on the entity - if (!isRenaming && ImGui::IsItemHovered() && ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left) && - !ImGui::IsItemToggledOpen()) - focusRequested = true; + // Double click focuses the camera on the entity + if (!isRenaming && ImGui::IsItemHovered() && ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left) && + !ImGui::IsItemToggledOpen()) + focusRequested = true; - bool rowHovered = ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenOverlappedByItem); + bool rowHovered = ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenOverlappedByItem); - if (ImGui::IsItemToggledOpen()) - toggledOpenSet.insert(entity); + if (ImGui::IsItemToggledOpen()) + toggledOpenSet.insert(entity); - bool shiftPressed = ImGui::IsKeyDown(ImGuiKey_LeftShift); - if (!shiftPressed && (ImGui::IsItemHovered() && ImGui::IsMouseReleased(ImGuiMouseButton_Left) && !toggledOpenSet.contains(entity))) { - SelectEntity(entity); - } - if (shiftPressed && (ImGui::IsItemHovered() && ImGui::IsMouseReleased(ImGuiMouseButton_Left) && !toggledOpenSet.contains(entity))) { - SelectEntity(entity, true); - } - if (ImGui::IsItemClicked(ImGuiMouseButton_Right) && !toggledOpenSet.contains(entity) && !selectedEntities.contains(entity)) { - SelectEntity(entity); - } + bool shiftPressed = ImGui::IsKeyDown(ImGuiKey_LeftShift); + if (!shiftPressed && (ImGui::IsItemHovered() && ImGui::IsMouseReleased(ImGuiMouseButton_Left) && !toggledOpenSet.contains(entity))) { + SelectEntity(entity); + } + if (shiftPressed && (ImGui::IsItemHovered() && ImGui::IsMouseReleased(ImGuiMouseButton_Left) && !toggledOpenSet.contains(entity))) { + SelectEntity(entity, true); + } + if (ImGui::IsItemClicked(ImGuiMouseButton_Right) && !toggledOpenSet.contains(entity) && !selectedEntities.contains(entity)) { + SelectEntity(entity); + } - // In any case we need to notify that we clicked on an item - if ((ImGui::IsItemClicked(ImGuiMouseButton_Right) || ImGui::IsItemClicked(ImGuiMouseButton_Left)) && !ImGui::IsItemToggledOpen()) { - *selectionChanged = true; - } + // In any case we need to notify that we clicked on an item + if ((ImGui::IsItemClicked(ImGuiMouseButton_Right) || ImGui::IsItemClicked(ImGuiMouseButton_Left)) && !ImGui::IsItemToggledOpen()) { + *selectionChanged = true; + } - if (ImGui::BeginDragDropSource()) { - ImGui::SetDragDropPayload(typeid(Scene::Entity).name(), &entity, sizeof(Scene::Entity)); - // Show what is dragged, the hint is secondary - if (selectedEntities.size() > 1) - ImGui::Text("%d entities", int32_t(selectedEntities.size())); - else - ImGui::TextUnformatted(nodeName.c_str()); - ImGui::TextDisabled("Drop on an entity to reparent, or into the content browser to create a prefab"); + if (ImGui::BeginDragDropSource()) { + ImGui::SetDragDropPayload(typeid(Scene::Entity).name(), &entity, sizeof(Scene::Entity)); + // Show what is dragged, the hint is secondary + if (selectedEntities.size() > 1) + ImGui::Text("%d entities", int32_t(selectedEntities.size())); + else + ImGui::TextUnformatted(nodeName.c_str()); + ImGui::TextDisabled("Drop on an entity to reparent, or into the content browser to create a prefab"); - ImGui::EndDragDropSource(); - } + ImGui::EndDragDropSource(); + } - if (ImGui::BeginDragDropTarget()) { - auto dropPayload = ImGui::GetDragDropPayload(); - if (dropPayload->IsDataType(typeid(Scene::Entity).name())) { - droppedEntities = ImGui::AcceptDragDropPayload(typeid(Scene::Entity).name()); - } + droppedEntity = AcceptEntityDrop(scene); - ImGui::EndDragDropTarget(); - } + if (ImGui::BeginPopupContextItem()) { + if (ImGui::MenuItem("Focus", "F")) + focusRequested = true; - if (ImGui::BeginPopupContextItem()) { - if (ImGui::MenuItem("Focus", "F")) - focusRequested = true; + if (!rootNode && nameComponent && ImGui::MenuItem("Rename", "F2")) + StartRename(entity); - if (!rootNode && nameComponent && ImGui::MenuItem("Rename", "F2")) - StartRename(entity); + ImGui::Separator(); - ImGui::Separator(); + if (ImGui::BeginMenu("Create child")) { + createEntity = RenderCreateMenuItems(entity); + ImGui::EndMenu(); + } - if (ImGui::BeginMenu("Create child")) { - createEntity = RenderCreateMenuItems(entity); - ImGui::EndMenu(); - } + if (!rootNode && ImGui::MenuItem("Duplicate entity")) + duplicateEntity = true; - if (!rootNode && ImGui::MenuItem("Duplicate entity")) - duplicateEntity = true; + // We shouldn't allow the user to delete the root entity + if (!rootNode && ImGui::MenuItem("Delete entity")) + deleteEntity = true; - // We shouldn't allow the user to delete the root entity - if (!rootNode && ImGui::MenuItem("Delete entity")) - deleteEntity = true; + ImGui::EndPopup(); + } - ImGui::EndPopup(); + if (isRenaming) { + const auto& style = ImGui::GetStyle(); + ImGui::SameLine(); + ImGui::SetNextItemWidth(eyeMinX - ImGui::GetCursorScreenPos().x - style.ItemInnerSpacing.x); + if (renameFocusPending) { + ImGui::SetKeyboardFocusHere(); + renameFocusPending = false; } - if (isRenaming) { - const auto& style = ImGui::GetStyle(); - ImGui::SameLine(); - ImGui::SetNextItemWidth(eyeMinX - ImGui::GetCursorScreenPos().x - style.ItemInnerSpacing.x); - if (renameFocusPending) { - ImGui::SetKeyboardFocusHere(); - renameFocusPending = false; - } - - bool confirmed = ImGui::InputText("##Rename", &renameBuffer, - ImGuiInputTextFlags_EnterReturnsTrue | ImGuiInputTextFlags_AutoSelectAll); - bool cancelled = ImGui::IsKeyPressed(ImGuiKey_Escape, false); - // Clicking somewhere else confirms as well, escape cancels - bool finished = confirmed || ImGui::IsItemDeactivated() || - (!ImGui::IsItemActive() && renameFrameCount > 2); - renameFrameCount++; - - if (finished) { - if (!cancelled && !renameBuffer.empty()) - nameComponent->name = renameBuffer; - renamingEntity = Scene::Entity(); + bool confirmed = ImGui::InputText("##Rename", &renameBuffer, + ImGuiInputTextFlags_EnterReturnsTrue | ImGuiInputTextFlags_AutoSelectAll); + bool cancelled = ImGui::IsKeyPressed(ImGuiKey_Escape, false); + // Clicking somewhere else confirms as well, escape cancels + bool finished = confirmed || ImGui::IsItemDeactivated() || + (!ImGui::IsItemActive() && renameFrameCount > 2); + renameFrameCount++; + + if (finished) { + if (!cancelled && !renameBuffer.empty() && renameBuffer != nameComponent->name) { + if (history) + history->BeginEdit(scene, { entity }); + nameComponent->name = renameBuffer; + if (history) + history->EndEdit("Rename " + renameBuffer); + sceneChanged = true; } + renamingEntity = Scene::Entity(); } + } - ImGui::SameLine(); - - bool isNodeVisible = !isHidden; - auto& visibilityIcon = Singletons::icons->Get(isNodeVisible ? IconType::Visibility : IconType::VisibilityOff); - auto set = Singletons::imguiWrapper->GetTextureId(&visibilityIcon); + ImGui::SameLine(); - // Keep the eye subtle unless the row is hovered or the entity is hidden - auto iconAlpha = rowHovered || !isNodeVisible ? 1.0f : 0.4f; + bool isNodeVisible = !isHidden; + auto& visibilityIcon = Singletons::icons->Get(isNodeVisible ? IconType::Visibility : IconType::VisibilityOff); + auto set = Singletons::imguiWrapper->GetTextureId(&visibilityIcon); - ImGui::SetCursorScreenPos(ImVec2(eyeMinX, rowMin.y + (rowMax.y - rowMin.y - eyeExtent) * 0.5f)); + // Keep the eye subtle unless the row is hovered or the entity is hidden + auto iconAlpha = rowHovered || !isNodeVisible ? 1.0f : 0.4f; - ImGui::PushID(reinterpret_cast(entityId)); - ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0.0f, 0.0f)); - ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.0f, 0.0f, 0.0f, 0.0f)); - ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 0.0f); - ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(eyePadding, eyePadding)); + ImGui::SetCursorScreenPos(ImVec2(eyeMinX, rowMin.y + (rowMax.y - rowMin.y - eyeExtent) * 0.5f)); - if (ImGui::ImageButton("Visibility button", set, ImVec2(eyeIconSize, eyeIconSize), ImVec2(0.1f, 0.1f), ImVec2(0.9f, 0.9f), - ImVec4(0.0f, 0.0f, 0.0f, 0.0f), ImVec4(1.0f, 1.0f, 1.0f, iconAlpha))) { - isNodeVisible = !isNodeVisible; + ImGui::PushID(reinterpret_cast(entityId)); + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0.0f, 0.0f)); + ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.0f, 0.0f, 0.0f, 0.0f)); + ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 0.0f); + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(eyePadding, eyePadding)); + + if (ImGui::ImageButton("Visibility button", set, ImVec2(eyeIconSize, eyeIconSize), ImVec2(0.1f, 0.1f), ImVec2(0.9f, 0.9f), + ImVec4(0.0f, 0.0f, 0.0f, 0.0f), ImVec4(1.0f, 1.0f, 1.0f, iconAlpha))) { + isNodeVisible = !isNodeVisible; + + std::vector meshEntities; + CollectMeshEntities(entity, meshEntities); + if (history) + history->BeginEdit(scene, meshEntities); + ToggleHierarchyVisibility(entity, isNodeVisible); + if (history) + history->EndEdit(isNodeVisible ? "Show " + nodeName : "Hide " + nodeName); + sceneChanged = true; + + // We are checking the new state here + if (!isNodeVisible) + nodeInvisibleSet.insert(entity); + else + nodeInvisibleSet.erase(entity); + } - ToggleHierarchyVisibility(entity, isNodeVisible); + ImGui::SetItemTooltip(isNodeVisible ? "Hide" : "Show"); - // We are checking the new state here - if (!isNodeVisible) - nodeInvisibleSet.insert(entity); - else - nodeInvisibleSet.erase(entity); - } + ImGui::PopStyleVar(2); + ImGui::PopStyleColor(); + ImGui::PopStyleVar(); + ImGui::PopID(); - ImGui::SetItemTooltip(isNodeVisible ? "Hide" : "Show"); + // Skipped rows move by the same distance + rowHeight = ImGui::GetCurrentWindow()->DC.CursorPos.y - rowStartY; - ImGui::PopStyleVar(2); - ImGui::PopStyleColor(); - ImGui::PopStyleVar(); - ImGui::PopID(); - } - else { - // Still need to display something here - auto entityId = static_cast(entity); - nodeOpen = ImGui::TreeNodeEx(reinterpret_cast(entityId), nodeFlags, ""); + if (entity == revealEntity) { + ImGui::SetScrollHereY(0.5f); + revealEntity = ECS::EntityConfig::InvalidEntity; } if (nodeOpen && hierarchyComponent) { - auto children = hierarchyComponent->GetChildren(); - for (auto childEntity : children) { - - TraverseHierarchy(scene, childEntity, matchSet, inFocus, searchChanged, selectionChanged); - - } + // The open tree node pushed its id + openRows.push_back({ entity, ImGui::GetCurrentWindow()->IDStack.back(), rowStart }); + TraverseChildren(scene, entity, selectionChanged); + openRows.pop_back(); ImGui::TreePop(); @@ -463,30 +697,8 @@ namespace Atlas::Editor::UI { *selectionChanged |= createEntity | deleteEntity | duplicateEntity; - if (droppedEntities) { - // No hierarchy component, so create one - if (!hierarchyComponent) { - entity.AddComponent(); - hierarchyComponent = entity.TryGetComponent(); - } - - for (auto ecsEntity : selectedEntities) { - Scene::Entity dropEntity(ecsEntity, &scene->entityManager); - - if (entity == dropEntity) - continue; - - auto dropParentEntity = scene->GetParentEntity(dropEntity); - - if (dropParentEntity.IsValid()) { - auto& dropParentHierarchy = dropParentEntity.GetComponent(); - dropParentHierarchy.RemoveChild(dropEntity); - } - - hierarchyComponent->AddChild(dropEntity); - } - - } + if (droppedEntity.IsValid()) + MoveEntities(scene, entity, droppedEntity); // If the hierarchy is emtpy after movements or deletions, also remove the hierarchy hierarchyComponent = deleteEntity ? nullptr : entity.TryGetComponent(); @@ -501,34 +713,46 @@ namespace Atlas::Editor::UI { ImGui::Spacing(); ImGui::SeparatorText("Scene settings"); - RenderExtendedItem("Terrain", &selectedProperty.terrain, selectionChanged); + RenderExtendedItem("Terrain", IconType::Terrain, &selectedProperty.terrain, selectionChanged); + RenderExtendedItem("Ocean", IconType::Ocean, &selectedProperty.ocean, selectionChanged); + RenderExtendedItem("Navigation", IconType::Navigation, &selectedProperty.navigation, selectionChanged); if (scene->irradianceVolume) - RenderExtendedItem("Irradiance volume", &selectedProperty.irradianceVolume, selectionChanged); + RenderExtendedItem("Irradiance volume", IconType::IrradianceVolume, &selectedProperty.irradianceVolume, selectionChanged); if (scene->rtgi) - RenderExtendedItem("Raytraced global illumination", &selectedProperty.rtgi, selectionChanged); + RenderExtendedItem("Raytraced global illumination", IconType::GlobalIllumination, &selectedProperty.rtgi, selectionChanged); if (scene->ssgi) - RenderExtendedItem("Screen-space global illumination", &selectedProperty.ssgi, selectionChanged); + RenderExtendedItem("Screen-space global illumination", IconType::GlobalIllumination, &selectedProperty.ssgi, selectionChanged); if (scene->reflection) - RenderExtendedItem("Reflection", &selectedProperty.reflection, selectionChanged); + RenderExtendedItem("Reflection", IconType::Reflection, &selectedProperty.reflection, selectionChanged); if (scene->sss) - RenderExtendedItem("Screen-space shadows", &selectedProperty.sss, selectionChanged); + RenderExtendedItem("Screen-space shadows", IconType::Shadow, &selectedProperty.sss, selectionChanged); if (scene->sky.clouds) - RenderExtendedItem("Volumetric clouds", &selectedProperty.volumetricClouds, selectionChanged); + RenderExtendedItem("Volumetric clouds", IconType::Clouds, &selectedProperty.volumetricClouds, selectionChanged); if (scene->fog) - RenderExtendedItem("Fog", &selectedProperty.fog, selectionChanged); - RenderExtendedItem("Sky", &selectedProperty.sky, selectionChanged); - RenderExtendedItem("Wind", &selectedProperty.wind, selectionChanged); - RenderExtendedItem("Post processing", &selectedProperty.postProcessing, selectionChanged); + RenderExtendedItem("Fog", IconType::Fog, &selectedProperty.fog, selectionChanged); + RenderExtendedItem("Sky", IconType::Sky, &selectedProperty.sky, selectionChanged); + RenderExtendedItem("Wind", IconType::Wind, &selectedProperty.wind, selectionChanged); + RenderExtendedItem("Post processing", IconType::PostProcessing, &selectedProperty.postProcessing, selectionChanged); } - void SceneHierarchyPanel::RenderExtendedItem(const std::string& name, bool* selected, bool* selectionChanged) { + void SceneHierarchyPanel::RenderExtendedItem(const std::string& name, IconType iconType, bool* selected, bool* selectionChanged) { ImGuiTreeNodeFlags nodeFlags = ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_NoTreePushOnOpen | ImGuiTreeNodeFlags_SpanAvailWidth | ImGuiTreeNodeFlags_FramePadding; nodeFlags |= *selected ? ImGuiTreeNodeFlags_Selected : 0; ImGui::TreeNodeEx(name.c_str(), nodeFlags); + + // A leaf has no arrow, the icon takes its place + auto iconSize = ImGui::GetFontSize(); + auto iconPos = ImGui::GetItemRectMin(); + iconPos.x += ImGui::GetStyle().FramePadding.x; + iconPos.y += ImGui::GetStyle().FramePadding.y; + auto set = Singletons::imguiWrapper->GetTextureId(&Singletons::icons->Get(iconType)); + ImGui::GetWindowDrawList()->AddImage(set, iconPos, ImVec2(iconPos.x + iconSize, iconPos.y + iconSize), + ImVec2(0.0f, 0.0f), ImVec2(1.0f, 1.0f), ImGui::GetColorU32(ImVec4(1.0f, 1.0f, 1.0f, 0.75f))); + if (ImGui::IsItemClicked()) { ClearSelection(); *selected = true; @@ -537,65 +761,42 @@ namespace Atlas::Editor::UI { } - void SceneHierarchyPanel::RenderFilterPopup() { + uint32_t SceneHierarchyPanel::GetAllFilterBits() { - ImGui::SameLine(); - - auto region = ImGui::GetContentRegionAvail(); - auto lineHeight = ImGui::GetTextLineHeight(); - auto buttonSize = ImVec2(lineHeight, lineHeight); + return (1u << uint32_t(Scene::GetComponentTypes().size())) - 1u; - auto& filterIcon = Singletons::icons->Get(IconType::Filter); - auto set = Singletons::imguiWrapper->GetTextureId(&filterIcon); + } - auto uvMin = ImVec2(0.1f, 0.1f); - auto uvMax = ImVec2(0.9f, 0.9f); + void SceneHierarchyPanel::RenderFilterPopup() { - //ImGui::SetCursorPosX(ImVec2(region.x - (buttonSize.x + 2.0f * padding), ImGui::GetCursorPosY())); - ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.0f, 0.0f, 0.0f, 0.0f)); - ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 0.0f); - if (ImGui::ImageButton("Filter button", set, buttonSize, uvMin, uvMax)) { - ImGui::OpenPopup("Hierarchy filter settings"); - } - ImGui::PopStyleVar(); - ImGui::PopStyleColor(); + ImGui::SameLine(); // Mark the button while a filter hides entities - bool filterActive = (hierarchyFilter & HierarchyFilterBits::AllBit) != HierarchyFilterBits::AllBit; - ImGui::SetItemTooltip(filterActive ? "Filter entities (active)" : "Filter entities"); + bool filterActive = (hierarchyFilter & GetAllFilterBits()) != GetAllFilterBits(); + if (Widgets::ToolbarIconButton("Filter button", Singletons::icons->Get(IconType::Filter), + filterActive ? "Filter entities (active)" : "Filter entities")) + ImGui::OpenPopup("Hierarchy filter settings"); if (filterActive) Widgets::ActiveIndicator(); - // Filters can be combined, so they are checkboxes - auto renderSingleBitOption = [&](const char* name, HierarchyFilterBits bit) { - bool isSet = hierarchyFilter & bit; - if (ImGui::Checkbox(name, &isSet)) { - hierarchyFilter = isSet ? hierarchyFilter | bit : hierarchyFilter & ~bit; - } - }; - if (ImGui::BeginPopup("Hierarchy filter settings")) { ImGui::SeparatorText("Show entities with"); auto prevHierarchyFilter = hierarchyFilter; - HierarchyFilter filtered = hierarchyFilter & HierarchyFilterBits::AllBit; - bool isSet = filtered == HierarchyFilterBits::AllBit; + bool isSet = (hierarchyFilter & GetAllFilterBits()) == GetAllFilterBits(); if (ImGui::Checkbox("All", &isSet)) { - hierarchyFilter = isSet ? HierarchyFilterBits::AllBit : 0; + hierarchyFilter = isSet ? GetAllFilterBits() : 0; } ImGui::Separator(); - renderSingleBitOption("Name", HierarchyFilterBits::NameBit); - renderSingleBitOption("Transform", HierarchyFilterBits::TransformBit); - renderSingleBitOption("Mesh", HierarchyFilterBits::MeshBit); - renderSingleBitOption("Text", HierarchyFilterBits::TextBit); - renderSingleBitOption("Audio", HierarchyFilterBits::AudioBit); - renderSingleBitOption("Audio volume", HierarchyFilterBits::AudioVolumeBit); - renderSingleBitOption("Player", HierarchyFilterBits::PlayerBit); - renderSingleBitOption("Rigid body", HierarchyFilterBits::RigidBodyBit); - renderSingleBitOption("Camera", HierarchyFilterBits::CameraBit); - renderSingleBitOption("Script", HierarchyFilterBits::ScriptBit); - renderSingleBitOption("Light", HierarchyFilterBits::LightBit); + // Filters can be combined, so they are checkboxes + const auto& componentTypes = Scene::GetComponentTypes(); + for (size_t i = 0; i < componentTypes.size(); i++) { + auto bit = 1u << uint32_t(i); + bool isBitSet = hierarchyFilter & bit; + if (ImGui::Checkbox(componentTypes[i].name, &isBitSet)) + hierarchyFilter = isBitSet ? hierarchyFilter | bit : hierarchyFilter & ~bit; + } hierarchyFilterChanged = prevHierarchyFilter != hierarchyFilter; @@ -606,11 +807,24 @@ namespace Atlas::Editor::UI { void SceneHierarchyPanel::DeleteSelectedEntities(Ref& scene) { + sceneChanged |= !selectedEntities.empty(); + + // The root stays, e.g. when it is selected while pressing Delete + std::vector deletedEntities; for (auto ecsEntity : selectedEntities) { Scene::Entity entity(ecsEntity, &scene->entityManager); + if (entity.IsValid() && entity != scene->GetRootEntity()) + deletedEntities.push_back(entity); + } + + if (history) + history->BeginChange(scene, deletedEntities); + // Descendants of deleted entities are already gone + for (auto entity : deletedEntities) if (entity.IsValid()) scene->DestroyEntity(entity); - } + if (history) + history->EndChange(deletedEntities.size() == 1 ? "Delete entity" : "Delete entities", {}); ClearSelection(); @@ -618,39 +832,36 @@ namespace Atlas::Editor::UI { void SceneHierarchyPanel::DuplicateSelectedEntity(Ref& scene) { + sceneChanged |= !selectedEntities.empty(); + auto oldSelectedEntites = selectedEntities; ClearSelection(); + if (history) + history->BeginChange(scene, {}); + for (auto ecsEntity : oldSelectedEntites) { Scene::Entity entity(ecsEntity, &scene->entityManager); - if (!entity.IsValid()) + if (!entity.IsValid() || entity == scene->GetRootEntity()) continue; - auto parentEntity = scene->GetParentEntity(entity); - - // Create new hierarchy before retrieving other components since they might become - // invalid when internal ECS storage resizes auto newEntity = scene->DuplicateEntity(entity); - HierarchyComponent* component; - if (parentEntity.IsValid()) { - component = parentEntity.TryGetComponent(); - } - else { - auto root = scene->GetEntityByName("Root"); - component = root.TryGetComponent(); - } - - AE_ASSERT(component != nullptr); - - if (component != nullptr) { - component->AddChild(newEntity); - } + // The hierarchy only shows entities below the root + if (!scene->GetParentEntity(newEntity).IsValid()) + newEntity.SetParent(scene->GetRootEntity()); SelectEntity(newEntity, true); } + if (history) { + std::vector newEntities; + for (auto ecsEntity : selectedEntities) + newEntities.emplace_back(ecsEntity, &scene->entityManager); + history->EndChange(newEntities.size() == 1 ? "Duplicate entity" : "Duplicate entities", newEntities); + } + } bool SceneHierarchyPanel::SearchHierarchy(EntityData& data, ECS::Entity entity, @@ -660,39 +871,20 @@ namespace Atlas::Editor::UI { auto nameComponent = data.namePool.TryGet(entity); // Only allocate a new string when there is no name component - if (nameComponent) { - nodeName = nameComponent->name; - } - else { + if (!nameComponent) nodeName = "entity " + std::to_string(entity); - } + const auto& name = nameComponent ? nameComponent->name : nodeName; - auto it = std::search(nodeName.begin(), nodeName.end(), transformedEntitySearch.begin(), transformedEntitySearch.end(), + auto it = std::search(name.begin(), name.end(), data.search.begin(), data.search.end(), [](unsigned char nodeChar, unsigned char searchChar) { return std::tolower(nodeChar) == searchChar; }); - parentMatches |= it != nodeName.end(); - parentMatches |= transformedEntitySearch.empty(); - - if (hierarchyFilter != HierarchyFilterBits::AllBit) { - auto checkBit = [&](ECS::Pool&pool, HierarchyFilterBits bit) -> bool { - if (hierarchyFilter & bit) { - return pool.Contains(entity); - } - return false; - }; + parentMatches |= it != name.end(); + parentMatches |= data.search.empty(); + if ((data.filter & GetAllFilterBits()) != GetAllFilterBits()) { bool bitChecks = false; - bitChecks |= checkBit(data.namePool, HierarchyFilterBits::NameBit); - bitChecks |= checkBit(data.transformPool, HierarchyFilterBits::TransformBit); - bitChecks |= checkBit(data.meshPool, HierarchyFilterBits::MeshBit); - bitChecks |= checkBit(data.textPool, HierarchyFilterBits::TextBit); - bitChecks |= checkBit(data.audioPool, HierarchyFilterBits::AudioBit); - bitChecks |= checkBit(data.audioVolumePool, HierarchyFilterBits::AudioVolumeBit); - bitChecks |= checkBit(data.playerPool, HierarchyFilterBits::PlayerBit); - bitChecks |= checkBit(data.rigidBodyPool, HierarchyFilterBits::RigidBodyBit); - bitChecks |= checkBit(data.cameraPool, HierarchyFilterBits::CameraBit); - bitChecks |= checkBit(data.scriptPool, HierarchyFilterBits::ScriptBit); - bitChecks |= checkBit(data.lightPool, HierarchyFilterBits::LightBit); + for (size_t i = 0; i < data.componentStorages.size() && !bitChecks; i++) + bitChecks = (data.filter & (1u << uint32_t(i))) && data.componentStorages[i].Contains(entity); parentMatches &= bitChecks; } @@ -701,7 +893,7 @@ namespace Atlas::Editor::UI { if (hierarchyComponent) { - auto children = hierarchyComponent->GetChildren(); + const auto& children = hierarchyComponent->GetChildren(); for (auto childEntity : children) { matches |= SearchHierarchy(data, childEntity, matchSet, nodeName, parentMatches); @@ -717,11 +909,25 @@ namespace Atlas::Editor::UI { } + void SceneHierarchyPanel::CollectMeshEntities(Scene::Entity entity, std::vector& entities) { + + if (entity.HasComponent()) + entities.push_back(entity); + + auto hierarchyComponent = entity.TryGetComponent(); + if (!hierarchyComponent) + return; + + for (auto child : hierarchyComponent->GetChildren()) + CollectMeshEntities(child, entities); + + } + void SceneHierarchyPanel::ToggleHierarchyVisibility(Scene::Entity entity, bool visible) { auto meshComponent = entity.TryGetComponent(); if (meshComponent) { - meshComponent->visible = visible; + meshComponent->SetVisible(visible); } auto hierarchyComponent = entity.TryGetComponent(); diff --git a/src/editor/ui/panels/SceneHierarchyPanel.h b/src/editor/ui/panels/SceneHierarchyPanel.h index 17b12dbbe..04002d464 100644 --- a/src/editor/ui/panels/SceneHierarchyPanel.h +++ b/src/editor/ui/panels/SceneHierarchyPanel.h @@ -2,6 +2,7 @@ #include "Panel.h" #include "ScenePropertiesPanel.h" +#include "../../SceneHistory.h" #include "scene/Scene.h" namespace Atlas::Editor::UI { @@ -15,6 +16,8 @@ namespace Atlas::Editor::UI { bool rtgi = false; bool sss = false; bool irradianceVolume = false; + bool ocean = false; + bool navigation = false; bool wind = false; bool sky = false; bool postProcessing = false; @@ -28,23 +31,6 @@ namespace Atlas::Editor::UI { class SceneHierarchyPanel : public Panel { public: - typedef uint32_t HierarchyFilter; - - typedef enum HierarchyFilterBits { - NameBit = (1 << 0), - TransformBit = (1 << 1), - MeshBit = (1 << 2), - TextBit = (1 << 3), - AudioBit = (1 << 4), - AudioVolumeBit = (1 << 5), - PlayerBit = (1 << 6), - RigidBodyBit = (1 << 7), - CameraBit = (1 << 8), - ScriptBit = (1 << 9), - LightBit = (1 << 10), - AllBit = (1 << 11) - 1 - } HierarchyFilterBits; - SceneHierarchyPanel() : Panel("Scene hierarchy") {} ~SceneHierarchyPanel() { JobSystem::Wait(searchJob); } @@ -57,13 +43,26 @@ namespace Atlas::Editor::UI { void ClearSelection(); + // Opens the parents of the entity and scrolls to it in the next frame + void RevealEntity(const Ref& scene, Scene::Entity entity); + Scene::Entity selectedEntity; EntitySelectionType selectedType = EntitySelectionType::Entity; std::unordered_set selectedEntities; SelectedProperty selectedProperty; - HierarchyFilter hierarchyFilter = HierarchyFilterBits::AllBit; + // Prefabs have no scene settings of their own + bool showSceneSettings = true; + + // Bit i shows the entities with the component of Scene::GetComponentTypes()[i] + uint32_t hierarchyFilter = ~0u; + + // Set when the hierarchy changed the scene, e.g. by deleting or renaming entities + bool sceneChanged = false; + + // Records the changes of the hierarchy, set by the scene window + SceneHistory* history = nullptr; // Set when the user wants to focus the camera on the selection (double click, context menu) bool focusRequested = false; @@ -76,7 +75,8 @@ namespace Atlas::Editor::UI { DirectionalLight, Camera, AudioSource, - Text + Text, + FogVolume }; // Set by the create menus. The scene window creates the entity, since it knows the editor camera for the placement @@ -93,33 +93,49 @@ namespace Atlas::Editor::UI { private: void StartRename(Scene::Entity entity); + ECS::Entity revealEntity = ECS::EntityConfig::InvalidEntity; + std::unordered_set revealOpenSet; + // Inline renaming of an entity in the hierarchy Scene::Entity renamingEntity; std::string renameBuffer; bool renameFocusPending = false; int32_t renameFrameCount = 0; + // Copies for the search job. The filters only need to know which entities have a component, copies of + // components like scripts hold references into other systems, which would be released on the job thread struct EntityData { ECS::Pool hierarchyPool; ECS::Pool namePool; - ECS::Pool transformPool; - ECS::Pool meshPool; - ECS::Pool textPool; - ECS::Pool audioPool; - ECS::Pool audioVolumePool; - ECS::Pool playerPool; - ECS::Pool rigidBodyPool; - ECS::Pool cameraPool; - ECS::Pool scriptPool; - ECS::Pool lightPool; - }; - - void TraverseHierarchy(Ref& scene, Scene::Entity entity, - std::unordered_set& matchSet, bool inFocus, bool searchChanged, bool* selectionChanged); + std::vector componentStorages; + std::string search; + uint32_t filter; + }; + + static uint32_t GetAllFilterBits(); + + // Goes through the rows of the open tree, only the ones in the window are rendered + void TraverseHierarchy(Ref& scene, Scene::Entity entity, bool* selectionChanged); + + void TraverseChildren(Ref& scene, Scene::Entity entity, bool* selectionChanged); + + void RenderEntityRow(Ref& scene, Scene::Entity entity, bool* selectionChanged); + + // Advances the layout by the rows that weren't rendered + void FlushSkippedRows(); + + // Open entities whose rows were scrolled out stay visible at the top of the tree + void RenderStickyRows(Ref& scene, bool* selectionChanged); + + // The entity dropped on the last item, invalid without a drop + Scene::Entity AcceptEntityDrop(const Ref& scene); + + // Moves the dropped entity, or the selection if it's part of it, below the parent + void MoveEntities(Ref& scene, Scene::Entity parent, Scene::Entity droppedEntity); void RenderExtendedHierarchy(const Ref& scene, bool* selectionChanged); - void RenderExtendedItem(const std::string& name, bool* selected, bool* selectionChanged); + void RenderExtendedItem(const std::string& name, IconType iconType, bool* selected, bool* selectionChanged); void RenderFilterPopup(); @@ -132,15 +148,40 @@ namespace Atlas::Editor::UI { void ToggleHierarchyVisibility(Scene::Entity entity, bool visible); + void CollectMeshEntities(Scene::Entity entity, std::vector& entities); + JobGroup searchJob{ "Scene hierarchy search", JobPriority::Low }; std::string entitySearch; - std::string transformedEntitySearch; std::unordered_set matchSet; std::unordered_set newMatchSet; std::unordered_set nodeInvisibleSet; std::unordered_set toggledOpenSet; + // Without a search or filter there is no match set + bool matchAll = true; + // Opens the matches of a new search and closes everything when it's cleared + bool openSearchMatches = false; + bool openSearchMatchesPending = false; + float lastSearchTime = 0.0f; + + ECS::Pool* hierarchyPool = nullptr; + ECS::Entity rootEntity = ECS::EntityConfig::InvalidEntity; + + float rowHeight = 20.0f; + int32_t skippedRows = 0; + int32_t renderedRows = 0; + + struct OpenRow { + Scene::Entity entity; + ImGuiID id; + ImVec2 position; + }; + // The open ancestors of the current row and the ones shown at the top of the tree + std::vector openRows; + std::vector stickyRows; + bool stickyRowsFound = false; + int32_t lastAliveEntityCount = 0; std::string lastEntitySearch; bool hierarchyFilterChanged = false; diff --git a/src/editor/ui/panels/ScenePropertiesPanel.h b/src/editor/ui/panels/ScenePropertiesPanel.h index 04a5949c7..7efee4010 100644 --- a/src/editor/ui/panels/ScenePropertiesPanel.h +++ b/src/editor/ui/panels/ScenePropertiesPanel.h @@ -7,7 +7,9 @@ #include "EntityPropertiesPanel.h" #include "SceneStatisticsPanel.h" #include "ResourceSelectionPanel.h" +#include "../Widgets.h" #include "TerrainPanel.h" +#include "NavigationPanel.h" #include "ImguiExtension/Panels.h" #include @@ -29,6 +31,9 @@ namespace Atlas::Editor::UI { isFocused = ImGui::IsWindowFocused(); + // Labels are on the right side of the widgets, they get a fixed room to not be cut off in narrow panels + ImGui::PushItemWidth(-std::min(150.0f, ImGui::GetContentRegionAvail().x * 0.5f)); + if constexpr (std::is_same_v) { if (t.entity.IsValid()) { RenderHeading("Entity"); @@ -52,7 +57,7 @@ namespace Atlas::Editor::UI { irradianceVolumePanel.Render(t, scene); } else if constexpr (std::is_same_v>) { - RenderHeading("Raytraced global illumination"); + RenderHeading("Ray traced global illumination"); rtgiPanel.Render(t, target); } else if constexpr (std::is_same_v>) { @@ -67,6 +72,25 @@ namespace Atlas::Editor::UI { RenderHeading("Screen-space shadows"); sssPanel.Render(t); } + else if constexpr (std::is_same_v>) { + RenderHeading("Ocean"); + if (t) { + oceanPanel.Render(t, + [&](ResourceHandle handle) { + return textureSelectionPanel.Render(handle); + }); + ImGui::Separator(); + if (Widgets::DangerButton("Remove ocean")) + t = nullptr; + } + else if (ImGui::Button("Create ocean", ImVec2(-FLT_MIN, 0.0f))) { + t = CreateRef(9, 4096.0f); + } + } + else if constexpr (std::is_same_v>) { + RenderHeading("Navigation"); + navigationPanel.Render(t); + } else if constexpr (std::is_same_v) { RenderHeading("Wind"); windPanel.Render(Singletons::imguiWrapper, t); @@ -80,19 +104,28 @@ namespace Atlas::Editor::UI { } else if constexpr (std::is_same_v) { RenderHeading("Post processing"); - postProcessingPanel.Render(t, + // The upscaler is a project setting + postProcessingPanel.showUpscaler = false; + postProcessingPanel.isUpscalerSupported = [](PostProcessing::Upscaler upscaler) { + return Singletons::mainRenderer->IsUpscalerSupported(upscaler); + }; + postProcessingPanel.Render(t, [&](ResourceHandle handle) { return textureSelectionPanel.Render(handle); }); } else if constexpr (std::is_same_v>) { - RenderHeading("Scene statistics"); + // One heading for the scene, the statistics bring their own sections + RenderHeading("Scene"); + ImGui::TextDisabled("Occlusion culling, mesh LODs, the upscaler and the file format are project settings"); sceneStatisticsPanel.Render(t); } cubemapSelectionPanel.Reset(); textureSelectionPanel.Reset(); + ImGui::PopItemWidth(); + ImGui::End(); } @@ -104,6 +137,7 @@ namespace Atlas::Editor::UI { ResourceSelectionPanel textureSelectionPanel; TerrainPanel terrainPanel; + NavigationPanel navigationPanel; ImguiExtension::FogPanel fogPanel; ImguiExtension::VolumetricCloudsPanel volumetricCloudsPanel; ImguiExtension::IrradianceVolumePanel irradianceVolumePanel; @@ -111,6 +145,7 @@ namespace Atlas::Editor::UI { ImguiExtension::SSGIPanel ssgiPanel; ImguiExtension::RTGIPanel rtgiPanel; ImguiExtension::SSSPanel sssPanel; + ImguiExtension::OceanPanel oceanPanel; ImguiExtension::WindPanel windPanel; ImguiExtension::SkyPanel skyPanel; ImguiExtension::PostProcessingPanel postProcessingPanel; @@ -118,12 +153,7 @@ namespace Atlas::Editor::UI { private: void RenderHeading(const std::string& heading) { - ImGui::SetWindowFontScale(1.5f); - - ImGui::Text("%s", heading.c_str()); - - ImGui::SetWindowFontScale(1.0f); - + Widgets::Heading(heading.c_str()); ImGui::Separator(); } diff --git a/src/editor/ui/panels/SceneStatisticsPanel.cpp b/src/editor/ui/panels/SceneStatisticsPanel.cpp index b63ae549b..d2d8c8777 100644 --- a/src/editor/ui/panels/SceneStatisticsPanel.cpp +++ b/src/editor/ui/panels/SceneStatisticsPanel.cpp @@ -1,29 +1,12 @@ #include "SceneStatisticsPanel.h" +#include "profiler/CPUProfiler.h" namespace Atlas::Editor::UI { void SceneStatisticsPanel::Render(Ref scene) { - vec3 min = glm::vec3(std::numeric_limits::max()); - vec3 max = glm::vec3(-std::numeric_limits::max()); - - Volume::AABB aabb(min, max); - auto meshSubset = scene->GetSubset(); - for (auto entity : meshSubset) { - const auto& meshComponent = meshSubset.Get(entity); - - aabb.Grow(meshComponent.aabb); - } - - min = aabb.min; - max = aabb.max; - auto size = aabb.GetSize(); - - auto meshes = scene->GetMeshes(); - auto materials = scene->GetMaterials(); - - auto lightCount = scene->GetComponentCount(); - auto meshInstanceCount = scene->GetComponentCount(); + Collect(scene); + GrowBounds(scene); auto tableFlags = ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingStretchProp | ImGuiTableFlags_PadOuterX; @@ -46,24 +29,95 @@ namespace Atlas::Editor::UI { ImGui::SeparatorText("Dimensions"); if (ImGui::BeginTable("Dimensions table", 2, tableFlags)) { - row("Min", vecToString(min)); - row("Max", vecToString(max)); - row("Size", vecToString(size)); + row("Min", vecToString(bounds.min)); + row("Max", vecToString(bounds.max)); + row("Size", vecToString(bounds.GetSize())); ImGui::EndTable(); } ImGui::Spacing(); ImGui::SeparatorText("Content"); if (ImGui::BeginTable("Content table", 2, tableFlags)) { - row("Entities", std::to_string(scene->GetEntityCount())); - row("Meshes", std::to_string(meshes.size())); - row("Materials", std::to_string(materials.size())); + row("Entities", std::to_string(entityCount)); + row("Meshes", std::to_string(meshCount)); + row("Materials", std::to_string(materialCount)); row("Lights", std::to_string(lightCount)); row("Mesh instances", std::to_string(meshInstanceCount)); - row("Physics bodies", std::to_string(scene->physicsWorld->GetBodyCount())); ImGui::EndTable(); } + if (!physicsStatistics) + return; + + auto activeToString = [](uint32_t active, uint32_t count) { + return std::to_string(active) + " / " + std::to_string(count); + }; + + char updateTime[32]; + std::snprintf(updateTime, sizeof(updateTime), "%.2f ms", physicsStatistics->updateTime); + + ImGui::Spacing(); + ImGui::SeparatorText("Physics"); + if (ImGui::BeginTable("Physics table", 2, tableFlags)) { + row("Bodies", std::to_string(physicsStatistics->bodyCount)); + row("Static bodies", std::to_string(physicsStatistics->staticBodyCount)); + row("Active dynamic bodies", activeToString(physicsStatistics->activeDynamicBodyCount, physicsStatistics->dynamicBodyCount)); + row("Active kinematic bodies", activeToString(physicsStatistics->activeKinematicBodyCount, physicsStatistics->kinematicBodyCount)); + row("Constraints", std::to_string(physicsStatistics->constraintCount)); + row("Contacts", std::to_string(physicsStatistics->contactCount)); + row("Update time", updateTime); + ImGui::EndTable(); + } + + } + + void SceneStatisticsPanel::Collect(const Ref& scene) { + + CPUProfiler::Scope profilerScope("Collect scene statistics"); + + // A new scene starts from scratch + if (collectedScene.lock() != scene) { + collectedScene = scene; + bounds = Volume::AABB(vec3(0.0f), vec3(0.0f)); + boundsIndex = 0; + collectionStep = 0; + } + + switch (collectionStep) { + case 0: + entityCount = scene->GetEntityCount(); + lightCount = scene->GetComponentCount(); + meshInstanceCount = scene->GetComponentCount(); + break; + case 1: meshCount = scene->GetMeshes().size(); break; + case 2: materialCount = scene->GetMaterials().size(); break; + default: + physicsStatistics.reset(); + if (scene->physicsWorld) + physicsStatistics = scene->physicsWorld->GetStatistics(); + break; + } + collectionStep = (collectionStep + 1) % 4; + + } + + void SceneStatisticsPanel::GrowBounds(const Ref& scene) { + + // The pool is dense, iterating it directly avoids a lookup per entity. Components that are added or removed + // during a pass only show up in the next one + auto& meshPool = scene->entityManager.GetPool(); + if (!boundsIndex) + growingBounds = Volume::AABB(vec3(std::numeric_limits::max()), vec3(-std::numeric_limits::max())); + + auto end = std::min(boundsIndex + boundsComponentsPerFrame, meshPool.GetCount()); + for (; boundsIndex < end; boundsIndex++) + growingBounds.Grow(meshPool.GetByIndex(boundsIndex).aabb); + + if (boundsIndex >= meshPool.GetCount()) { + bounds = boundsIndex ? growingBounds : Volume::AABB(vec3(0.0f), vec3(0.0f)); + boundsIndex = 0; + } + } } \ No newline at end of file diff --git a/src/editor/ui/panels/SceneStatisticsPanel.h b/src/editor/ui/panels/SceneStatisticsPanel.h index e29c1d307..3e197dd81 100644 --- a/src/editor/ui/panels/SceneStatisticsPanel.h +++ b/src/editor/ui/panels/SceneStatisticsPanel.h @@ -3,6 +3,8 @@ #include "Panel.h" #include "scene/Scene.h" +#include + namespace Atlas::Editor::UI { class SceneStatisticsPanel : public Panel { @@ -13,6 +15,27 @@ namespace Atlas::Editor::UI { void Render(Ref scene); private: + void Collect(const Ref& scene); + + void GrowBounds(const Ref& scene); + + // Collecting everything takes milliseconds in large scenes. Each frame collects one of the values and a part + // of the bounds, such that the cost is the same in every frame + const size_t boundsComponentsPerFrame = 32768; + + // Doesn't keep a closed scene alive, a new scene at the same address is still a new one + std::weak_ptr collectedScene; + int32_t collectionStep = 0; + + Volume::AABB bounds; + Volume::AABB growingBounds; + size_t boundsIndex = 0; + size_t entityCount = 0; + size_t meshCount = 0; + size_t materialCount = 0; + size_t lightCount = 0; + size_t meshInstanceCount = 0; + std::optional physicsStatistics; }; diff --git a/src/editor/ui/panels/TerrainPanel.cpp b/src/editor/ui/panels/TerrainPanel.cpp index c3d6548bd..3c0ec75ff 100644 --- a/src/editor/ui/panels/TerrainPanel.cpp +++ b/src/editor/ui/panels/TerrainPanel.cpp @@ -68,33 +68,52 @@ namespace Atlas::Editor::UI { return; } - ImGui::Checkbox("Wireframe", &terrain->wireframe); - Widgets::DragVec3("Translation", terrain->translation, 1.0f, 0.0f, -10000.0f, 10000.0f); - ImGui::SliderFloat("Height", &terrain->heightScale, 1.0f, 2000.0f, "%.3f", ImGuiSliderFlags_Logarithmic); + if (Widgets::BeginProperties("General")) { + Widgets::PropertyLabel("Wireframe"); + ImGui::Checkbox("##Wireframe", &terrain->wireframe); + Widgets::PropertyLabel("Translation"); + Widgets::DragVec3("##Translation", terrain->translation, 1.0f, 0.0f, -10000.0f, 10000.0f); + Widgets::PropertyLabel("Height"); + ImGui::SliderFloat("##Height", &terrain->heightScale, 1.0f, 2000.0f, "%.3f", ImGuiSliderFlags_Logarithmic); + Widgets::EndProperties(); + } ImGui::SeparatorText("Tessellation"); - ImGui::SliderFloat("Factor", &terrain->tessellationFactor, 0.0f, - 16000.0f, "%.3f", 4.0f); - - ImGui::SliderFloat("Slope", &terrain->tessellationSlope, 0.0f, 10.0f); - ImGui::SliderFloat("Shift", &terrain->tessellationShift, 0.0f, 10.0f); - - ImGui::SliderFloat("Subdivisions", &terrain->maxTessellationLevel, 1.0f, - 64.0f); - ImGui::SliderFloat("Distance", &terrain->displacementDistance, 0.0f, 100.0f, - "%.3f", ImGuiSliderFlags_Logarithmic); + if (Widgets::BeginProperties("Tessellation")) { + Widgets::PropertyLabel("Factor"); + ImGui::SliderFloat("##Factor", &terrain->tessellationFactor, 0.0f, + 16000.0f, "%.3f", 4.0f); + + Widgets::PropertyLabel("Slope"); + ImGui::SliderFloat("##Slope", &terrain->tessellationSlope, 0.0f, 10.0f); + Widgets::PropertyLabel("Shift"); + ImGui::SliderFloat("##Shift", &terrain->tessellationShift, 0.0f, 10.0f); + + Widgets::PropertyLabel("Subdivisions"); + ImGui::SliderFloat("##Subdivisions", &terrain->maxTessellationLevel, 1.0f, + 64.0f); + Widgets::PropertyLabel("Distance"); + ImGui::SliderFloat("##Distance", &terrain->displacementDistance, 0.0f, 100.0f, + "%.3f", ImGuiSliderFlags_Logarithmic); + Widgets::EndProperties(); + } ImGui::SeparatorText("Lod distances"); if (editingMode) Widgets::Callout("Lods can't be changed in editing mode", Theme::Warning()); - for (size_t i = 0; i < terrain->LoDCount; i++) { - auto distance = terrain->GetLoDDistance((int32_t)i); - ImGui::SliderFloat(("LoD" + std::to_string(i)).c_str(), - &distance, 1.0f, 8192.0f, "%.3f", ImGuiSliderFlags_Logarithmic); - terrain->SetLoDDistance((int32_t)i, distance); + if (Widgets::BeginProperties("Lod distances")) { + for (size_t i = 0; i < terrain->LoDCount; i++) { + auto distance = terrain->GetLoDDistance((int32_t)i); + auto label = "LoD" + std::to_string(i); + Widgets::PropertyLabel(label.c_str()); + ImGui::SliderFloat(("##" + label).c_str(), + &distance, 1.0f, 8192.0f, "%.3f", ImGuiSliderFlags_Logarithmic); + terrain->SetLoDDistance((int32_t)i, distance); + } + Widgets::EndProperties(); } } @@ -106,35 +125,15 @@ namespace Atlas::Editor::UI { return; } - bool changed = false; materialsPanel.Render(Singletons::imguiWrapper, terrain->storage->materials, [&](ResourceHandle material) { bool materialChanged = false; - auto handle = materialSelectionPanel.Render(material, materialChanged); - changed |= materialChanged; - return handle; + return materialSelectionPanel.Render(material, materialChanged); }, [&](ResourceHandle texture) { - bool textureChanged = false; - auto handle = textureSelectionPanel.Render(texture); - changed |= textureChanged; - return handle; + return textureSelectionPanel.Render(texture); }); - if (changed) { - terrain->storage->BeginMaterialWrite(); - - for (int32_t i = 0; i < int32_t(terrain->storage->materials.size()); i++) { - auto material = terrain->storage->materials[i]; - if (!material.IsLoaded()) - continue; - - terrain->storage->WriteMaterial(i, material); - } - - terrain->storage->EndMaterialWrite(); - } - } void TerrainPanel::RenderEditingSettings(ResourceHandle& terrain, Ref scene) { @@ -146,7 +145,11 @@ namespace Atlas::Editor::UI { auto region = ImGui::GetContentRegionAvail(); - ImGui::Checkbox("Editing mode", &editingMode); + if (Widgets::BeginProperties("Editing")) { + Widgets::PropertyLabel("Editing mode", "Pushes LoD distances to 512 to enable editing without baking"); + ImGui::Checkbox("##Editing mode", &editingMode); + Widgets::EndProperties(); + } if (editingMode && !LoDDistances.size()) { // Can't really reset other than when the scene is finally saved (together with the new terrain) @@ -162,10 +165,6 @@ namespace Atlas::Editor::UI { } } - ImGui::SameLine(); - - UIElements::Tooltip("Pushes LoD distances to 512 to enable editing without baking"); - if (!editingMode) Widgets::Callout("Enable editing mode, then hold the right mouse button in the viewport to paint.", Theme::Accent()); @@ -173,62 +172,73 @@ namespace Atlas::Editor::UI { // Only one brush can be active, show the settings of the selected one ImGui::SeparatorText("Brush"); - const char* brushTypeItems[] = { "Height", "Material", "Hole" }; - int32_t brushTypeSelection = static_cast(brushType); - Widgets::SegmentedControl("Type", brushTypeSelection, brushTypeItems, IM_ARRAYSIZE(brushTypeItems)); - brushType = static_cast(brushTypeSelection); - - auto maxSize = 8.0f * terrain->patchSizeFactor - 1.0f; - ImGui::DragFloat("Brush size", &brushSize, 0.25f, 1.0f, maxSize); - - if (brushType == TerrainBrushType::Height) { - ImGui::PushID("Height"); - - const char* functionItems[] = { "Gauss", "Box", "Smooth", "Flatten" }; - int32_t heightBrushSelection = static_cast(brushFunction); - Widgets::SegmentedControl("Function", heightBrushSelection, functionItems, IM_ARRAYSIZE(functionItems)); - brushFunction = static_cast(heightBrushSelection); - - auto brushStrengthMin = -2000.0f; - auto brushStrengthMax = 2000.0f; + if (Widgets::BeginProperties("Brush")) { + const char* brushTypeItems[] = { "Height", "Material", "Hole" }; + int32_t brushTypeSelection = static_cast(brushType); + Widgets::PropertyLabel("Type"); + Widgets::SegmentedControl("##Type", brushTypeSelection, brushTypeItems, IM_ARRAYSIZE(brushTypeItems)); + brushType = static_cast(brushTypeSelection); + + auto maxSize = 8.0f * terrain->patchSizeFactor - 1.0f; + Widgets::PropertyLabel("Brush size"); + ImGui::DragFloat("##Brush size", &brushSize, 0.25f, 1.0f, maxSize); + + if (brushType == TerrainBrushType::Height) { + ImGui::PushID("Height"); + + const char* functionItems[] = { "Gauss", "Box", "Smooth", "Flatten" }; + int32_t heightBrushSelection = static_cast(brushFunction); + Widgets::PropertyLabel("Function"); + Widgets::SegmentedControl("##Function", heightBrushSelection, functionItems, IM_ARRAYSIZE(functionItems)); + brushFunction = static_cast(heightBrushSelection); + + auto brushStrengthMin = -2000.0f; + auto brushStrengthMax = 2000.0f; + + if (brushFunction == TerrainBrushFunction::Smooth || + brushFunction == TerrainBrushFunction::Flatten) { + brushStrengthMin = 0.0f; + brushStrengthMax = 1.0f; + brushStrength = glm::min(1.0f, brushStrength); + } + Widgets::PropertyLabel("Brush strength"); + ImGui::SliderFloat("##Brush strength", &brushStrength, brushStrengthMin, + brushStrengthMax, "%.3f", ImGuiSliderFlags_Logarithmic); + + // Need some extra setting here + if (brushFunction == TerrainBrushFunction::Flatten) { + Widgets::PropertyLabel("Query regular geometry"); + ImGui::Checkbox("##Query regular geometry", &brushFlattenQueryRegularGeometry); + } - if (brushFunction == TerrainBrushFunction::Smooth || - brushFunction == TerrainBrushFunction::Flatten) { - brushStrengthMin = 0.0f; - brushStrengthMax = 1.0f; - brushStrength = glm::min(1.0f, brushStrength); + ImGui::PopID(); } - ImGui::SliderFloat("Brush strength", &brushStrength, brushStrengthMin, - brushStrengthMax, "%.3f", ImGuiSliderFlags_Logarithmic); + else if (brushType == TerrainBrushType::Material) { + ImGui::PushID("Material"); - // Need some extra setting here - if (brushFunction == TerrainBrushFunction::Flatten) { - ImGui::Checkbox("Query regular geometry", &brushFlattenQueryRegularGeometry); - } + std::vector counter; + std::vector pointer; - ImGui::PopID(); - } - else if (brushType == TerrainBrushType::Material) { - ImGui::PushID("Material"); + for (size_t count = 0; count < terrain->storage->materials.size(); count++) { + auto& material = terrain->storage->materials[count]; + auto name = material.IsLoaded() ? material->name : std::string("Empty"); + counter.push_back(std::to_string(count) + ": " + name); + } + for (const auto& name : counter) { + pointer.push_back(name.c_str()); + } - std::vector counter; - std::vector pointer; + Widgets::PropertyLabel("Slot"); + ImGui::Combo("##Slot", &materialBrushSelection, + pointer.data(), pointer.size()); - for (size_t count = 0; count < terrain->storage->materials.size(); count++) { - auto& material = terrain->storage->materials[count]; - auto name = material.IsLoaded() ? material->name : std::string("Empty"); - counter.push_back(std::to_string(count) + ": " + name); + ImGui::PopID(); } - for (const auto& name : counter) { - pointer.push_back(name.c_str()); - } - - ImGui::Combo("Slot", &materialBrushSelection, - pointer.data(), pointer.size()); - ImGui::PopID(); + Widgets::EndProperties(); } - else if (brushType == TerrainBrushType::Hole) { + + if (brushType == TerrainBrushType::Hole) { ImGui::TextDisabled("Paints holes into the terrain"); } @@ -258,12 +268,19 @@ namespace Atlas::Editor::UI { terrain.WaitForLoad(); - auto heightImage = scene->terrain->GetHeightField(terrain->LoDCount - 1); + RebuildTerrainBody(scene); + + } + + void TerrainPanel::RebuildTerrainBody(Ref& scene) { + + auto& terrain = scene->terrain; + auto heightImage = terrain->GetHeightField(terrain->LoDCount - 1); Atlas::Physics::HeightFieldShapeSettings terrainShapeSettings{ .heightData = heightImage.GetData(), .translation = terrain->translation, - .scale = glm::vec3(terrain->resolution, terrain->heightScale, terrain->resolution) + .scale = vec3(terrain->resolution, terrain->heightScale, terrain->resolution) }; auto terrainShape = Atlas::Physics::ShapesManager::CreateShape(terrainShapeSettings); @@ -286,9 +303,7 @@ namespace Atlas::Editor::UI { terrainPhysicsEntity = scene->CreateEntity(); terrainPhysicsEntity.AddComponent(terrain->filename); - auto root = scene->GetEntityByName("Root"); - if (root.IsValid() && root.HasComponent()) - root.GetComponent().AddChild(terrainPhysicsEntity); + terrainPhysicsEntity.SetParent(scene->GetRootEntity()); } else { terrainPhysicsEntity.RemoveComponent(); @@ -298,7 +313,7 @@ namespace Atlas::Editor::UI { auto bodySettings = Atlas::Physics::BodyCreationSettings{ .shape = terrainShape }; terrainPhysicsEntity.AddComponent(bodySettings); - terrainPhysicsEntity.AddComponent(glm::mat4(1.0f)); + terrainPhysicsEntity.AddComponent(mat4(1.0f)); } diff --git a/src/editor/ui/panels/TerrainPanel.h b/src/editor/ui/panels/TerrainPanel.h index 490da8a49..778d60893 100644 --- a/src/editor/ui/panels/TerrainPanel.h +++ b/src/editor/ui/panels/TerrainPanel.h @@ -28,6 +28,9 @@ namespace Atlas::Editor::UI { void Render(ResourceHandle terrain, Ref scene); + // Collisions and navigation use the height field body, it has to follow edited heights + void RebuildTerrainBody(Ref& scene); + bool editingMode = false; float brushSize = 1.0f; float brushStrength = 1.0f; diff --git a/src/editor/ui/panels/VegetationGeneratorPanel.cpp b/src/editor/ui/panels/VegetationGeneratorPanel.cpp index cd6638633..e3f6e114b 100644 --- a/src/editor/ui/panels/VegetationGeneratorPanel.cpp +++ b/src/editor/ui/panels/VegetationGeneratorPanel.cpp @@ -28,7 +28,11 @@ namespace Atlas::Editor::UI { auto width = ImGui::GetContentRegionAvail().x; - ImGui::DragInt("Seed", &vegetationGenerator.seed, 1.0f, 1, 255); + if (Widgets::BeginProperties("Vegetation generator")) { + Widgets::PropertyLabel("Seed"); + ImGui::DragInt("##Seed", &vegetationGenerator.seed, 1.0f, 1, 255); + Widgets::EndProperties(); + } RenderBiomeVegetationTypes(scene, scene->terrain.Get(), terrainGenerator); @@ -53,42 +57,29 @@ namespace Atlas::Editor::UI { if (Singletons::blockingOperation->block) return; - const ImGuiTreeNodeFlags nodeFlags = ImGuiTreeNodeFlags_SpanAvailWidth | ImGuiTreeNodeFlags_FramePadding - | ImGuiTreeNodeFlags_AllowOverlap; - int32_t deleteIdx = -1; auto& types = vegetationGenerator.types; for (int32_t i = 0; i < int32_t(types.size()); i++) { auto& type = types[i]; - bool open = ImGui::TreeNodeEx(reinterpret_cast(type.id), nodeFlags, "%s", type.name.c_str()); - - auto deleteIcon = Singletons::icons->Get(IconType::Trash); - auto set = Singletons::imguiWrapper->GetTextureId(&deleteIcon); - - ImGui::SameLine(); - - float buttonSize = ImGui::GetTextLineHeight(); - auto width = ImGui::GetContentRegionAvail().x; - auto pos = ImGui::GetCursorPosX(); - ImGui::SetCursorPosX(pos + width - buttonSize); - - ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0.0f, 0.0f)); - ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 0.0f); - ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.0f, 0.0f, 0.0f, 0.0f)); - - if (ImGui::ImageButton("Vegetationtype delete button", set, ImVec2(buttonSize, buttonSize), ImVec2(0.1f, 0.1f), ImVec2(0.9f, 0.9f))) { + // The name can be edited below, the id keeps the header open while typing + ImGui::PushID(int32_t(type.id)); + bool remove = false; + bool open = Widgets::RemovableSectionHeader((type.name + "###Vegetation type").c_str(), 0, + remove, "Remove vegetation type"); + if (remove) deleteIdx = i; - } - ImGui::PopStyleColor(); - ImGui::PopStyleVar(2); - - // Here we can use the copy pase helper to copy over some settings to other biomes - if (!open) + if (!open) { + ImGui::PopID(); continue; + } - ImGui::InputText("Name", &type.name); + if (Widgets::BeginProperties("Vegetation type")) { + Widgets::PropertyLabel("Name"); + ImGui::InputText("##Name", &type.name); + Widgets::EndProperties(); + } ImGui::SeparatorText("Entity"); @@ -121,36 +112,67 @@ namespace Atlas::Editor::UI { type.initialDensity = std::max(0.001f, type.initialDensity); ImGui::SeparatorText("General"); - - ImGui::DragInt("Iterations", &type.iterations); - ImGui::DragInt("Seed", &type.seed); - ImGui::DragFloat("Initial density", &type.initialDensity, 0.01f, 0.0f, 1.0f); - ImGui::DragFloat("Offspring per iteration", &type.offspringPerIteration, 0.01f, 0.0f, 1.0f); - ImGui::DragFloat("Offspring spread radius", &type.offspringSpreadRadius, 0.1f, 0.1f, 100.0f); + if (Widgets::BeginProperties("General")) { + Widgets::PropertyLabel("Iterations"); + ImGui::DragInt("##Iterations", &type.iterations); + Widgets::PropertyLabel("Seed"); + ImGui::DragInt("##Seed", &type.seed); + Widgets::PropertyLabel("Initial density"); + ImGui::DragFloat("##Initial density", &type.initialDensity, 0.01f, 0.0f, 1.0f); + Widgets::PropertyLabel("Offspring per iteration"); + ImGui::DragFloat("##Offspring per iteration", &type.offspringPerIteration, 0.01f, 0.0f, 1.0f); + Widgets::PropertyLabel("Offspring spread radius"); + ImGui::DragFloat("##Offspring spread radius", &type.offspringSpreadRadius, 0.1f, 0.1f, 100.0f); + Widgets::EndProperties(); + } ImGui::SeparatorText("Placement"); - ImGui::DragFloat("Min height", &type.heightMin, 0.001f, 0.0f, 1.0f); - ImGui::DragFloat("Max height", &type.heightMax, 0.001f, 0.0f, 1.0f); - - ImGui::DragFloat("Min slope", &type.slopeMin, 0.001f, 0.0f, 1.0f); - ImGui::DragFloat("Max slope", &type.slopeMax, 0.001f, 0.0f, 1.0f); + if (Widgets::BeginProperties("Placement")) { + Widgets::PropertyLabel("Min height"); + ImGui::DragFloat("##Min height", &type.heightMin, 0.001f, 0.0f, 1.0f); + Widgets::PropertyLabel("Max height"); + ImGui::DragFloat("##Max height", &type.heightMax, 0.001f, 0.0f, 1.0f); + + Widgets::PropertyLabel("Min slope"); + ImGui::DragFloat("##Min slope", &type.slopeMin, 0.001f, 0.0f, 1.0f); + Widgets::PropertyLabel("Max slope"); + ImGui::DragFloat("##Max slope", &type.slopeMax, 0.001f, 0.0f, 1.0f); + Widgets::EndProperties(); + } ImGui::SeparatorText("Transform"); - Widgets::DragVec3("Offset", type.offset, 0.1f, 0.0f); - Widgets::DragVec3("Min scale", type.scaleMin, 0.1f, 1.0f); - Widgets::DragVec3("Max scale", type.scaleMax, 0.1f, 1.0f); - - ImGui::Checkbox("Align to surface", &type.alignToSurface); - ImGui::DragFloat("Max alignment angle", &type.maxAlignmentAngle, 0.01f, 0.0f, 3.14f / 2.0f); + if (Widgets::BeginProperties("Transform")) { + Widgets::PropertyLabel("Offset"); + Widgets::DragVec3("##Offset", type.offset, 0.1f, 0.0f); + Widgets::PropertyLabel("Min scale"); + Widgets::DragVec3("##Min scale", type.scaleMin, 0.1f, 1.0f); + Widgets::PropertyLabel("Max scale"); + Widgets::DragVec3("##Max scale", type.scaleMax, 0.1f, 1.0f); + + Widgets::PropertyLabel("Align to surface"); + ImGui::Checkbox("##Align to surface", &type.alignToSurface); + Widgets::PropertyLabel("Max alignment angle"); + ImGui::DragFloat("##Max alignment angle", &type.maxAlignmentAngle, 0.01f, 0.0f, 3.14f / 2.0f); + Widgets::EndProperties(); + } ImGui::SeparatorText("Growth"); - ImGui::DragFloat("Collision radius", &type.collisionRadius, 0.01f, 0.0f); - ImGui::DragFloat("Shade radius", &type.shadeRadius, 0.01f, 0.0f); - - ImGui::Checkbox("Can grow in shade", &type.canGrowInShade); - ImGui::DragInt("Max growth age", &type.growthMaxAge); - ImGui::DragFloat("Min growth scale", &type.growthMinScale, 0.01f); - ImGui::DragFloat("Max growth scale", &type.growthMaxScale, 0.01f); + if (Widgets::BeginProperties("Growth")) { + Widgets::PropertyLabel("Collision radius"); + ImGui::DragFloat("##Collision radius", &type.collisionRadius, 0.01f, 0.0f); + Widgets::PropertyLabel("Shade radius"); + ImGui::DragFloat("##Shade radius", &type.shadeRadius, 0.01f, 0.0f); + + Widgets::PropertyLabel("Can grow in shade"); + ImGui::Checkbox("##Can grow in shade", &type.canGrowInShade); + Widgets::PropertyLabel("Max growth age"); + ImGui::DragInt("##Max growth age", &type.growthMaxAge); + Widgets::PropertyLabel("Min growth scale"); + ImGui::DragFloat("##Min growth scale", &type.growthMinScale, 0.01f); + Widgets::PropertyLabel("Max growth scale"); + ImGui::DragFloat("##Max growth scale", &type.growthMaxScale, 0.01f); + Widgets::EndProperties(); + } // Create a child window with a scrollbar ImGui::SeparatorText("Exclude materials"); @@ -176,8 +198,7 @@ namespace Atlas::Editor::UI { ImGui::EndChild(); - if (open) - ImGui::TreePop(); + ImGui::PopID(); } if (deleteIdx >= 0) { diff --git a/src/editor/ui/panels/ViewportPanel.cpp b/src/editor/ui/panels/ViewportPanel.cpp index 5315044ea..25615d435 100644 --- a/src/editor/ui/panels/ViewportPanel.cpp +++ b/src/editor/ui/panels/ViewportPanel.cpp @@ -1,5 +1,6 @@ #include "ViewportPanel.h" #include "Singletons.h" +#include "Theme.h" #include @@ -8,9 +9,14 @@ namespace Atlas::Editor::UI { ViewportPanel::ViewportPanel() : Panel("Viewport") { viewport = CreateRef(); + renderViewport = CreateRef(); viewportTexture = Texture::Texture2D(1, 1, VK_FORMAT_R16G16B16A16_SFLOAT); + renderTarget = CreateRef(64, 64); - CreateRenderPass(); + mainRenderer = CreateRef(); + mainRenderer->Init(Graphics::GraphicsDevice::DefaultDevice); + + CreateRendering(); } @@ -27,9 +33,10 @@ namespace Atlas::Editor::UI { } - void ViewportPanel::Render(Ref &scene, bool isActiveWindow) { + void ViewportPanel::Render(Ref &scene) { - ImGui::Begin(GetNameID()); + // Viewports in hidden tabs aren't rendered + bool isVisible = ImGui::Begin(GetNameID()); bool isBlocked = Singletons::blockingOperation->block; @@ -52,7 +59,10 @@ namespace Atlas::Editor::UI { auto pos = ivec2(int32_t(windowPos.x), int32_t(windowPos.y)); auto size = ivec2(int32_t(region.x), int32_t(region.y)); - RenderScene(scene, pos, size, isActiveWindow); + if (isVisible) + RenderScene(scene, pos, size); + else + primitiveBatchWrapper.Clear(); if (viewportTexture.IsValid() && viewportTexture.image->layout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) { auto set = Singletons::imguiWrapper->GetTextureId(&viewportTexture); @@ -62,6 +72,11 @@ namespace Atlas::Editor::UI { if (drawOverlayFunc && !isBlocked) drawOverlayFunc(); + if (frameColor.w > 0.0f) { + ImGui::GetWindowDrawList()->AddRect(windowPos, ImVec2(windowPos.x + region.x, windowPos.y + region.y), + ImGui::GetColorU32(frameColor), 0.0f, 0, 3.0f); + } + ImGui::SetCursorPos(ImVec2(0.0f, 0.0f)); if (drawMenuBarFunc && !isBlocked) { @@ -76,20 +91,30 @@ namespace Atlas::Editor::UI { } - void ViewportPanel::RenderScene(Ref& scene, ivec2 pos, ivec2 size, bool isActive) { + void ViewportPanel::RenderScene(Ref& scene, ivec2 pos, ivec2 size) { bool validSize = size.x > 0 && size.y > 0; - if ((viewportTexture.width != size.x || - viewportTexture.height != size.y) && validSize) { + // The scene is rendered in window units as before, the interface scale doesn't lower its resolution + auto renderSize = ivec2(vec2(size) * Singletons::imguiWrapper->GetScale()); + if (validSize && (viewport->x != pos.x || viewport->y != pos.y || viewport->width != size.x || viewport->height != size.y)) viewport->Set(pos.x, pos.y, size.x, size.y); - viewportTexture.Resize(size.x, size.y); - CreateRenderPass(); + + // While a splitter or the window is dragged, the last image is stretched and the textures are only resized + // once the resize is done. The camera already uses the new aspect ratio, so the stretched image isn't distorted + auto resizing = ImGui::IsMouseDown(ImGuiMouseButton_Left) && viewportTexture.width > 1; + if ((viewportTexture.width != renderSize.x || + viewportTexture.height != renderSize.y) && validSize && !resizing) { + renderViewport->Set(0, 0, renderSize.x, renderSize.y); + viewportTexture.Resize(renderSize.x, renderSize.y); + CreateRendering(); } - if (scene != nullptr && validSize && isActive && !Singletons::blockingOperation->block) { + if (scene != nullptr && validSize && !Singletons::blockingOperation->block) { auto& config = Singletons::config; - auto& renderTarget = Singletons::renderTarget; + + // Advances the frame count of the renderer, e.g. for the jitter + mainRenderer->Update(); if (renderTarget->GetWidth() != viewportTexture.width || renderTarget->GetHeight() != viewportTexture.height) { @@ -101,12 +126,13 @@ namespace Atlas::Editor::UI { primitiveBatchWrapper.primitiveBatchNoDepthTest }; - if (config->pathTrace) { + // Scenes without ray tracing data (yet) are rasterized + if (config->pathTrace && allowPathTracing && scene->IsRtDataValid()) { // Overlays like the grid, bounding volumes and brushes are visible when path tracing as well - Singletons::mainRenderer->PathTraceScene(viewport, renderTarget, scene, &viewportTexture, primitiveBatches); + mainRenderer->PathTraceScene(renderViewport, renderTarget, scene, &viewportTexture, primitiveBatches); } else { - Singletons::mainRenderer->RenderScene(viewport, renderTarget, scene, + mainRenderer->RenderScene(renderViewport, renderTarget, scene, primitiveBatches, &viewportTexture); if (visualization != Lit) { @@ -117,117 +143,224 @@ namespace Atlas::Editor::UI { RenderVisualization(exposure); } } + } - primitiveBatchWrapper.Clear(); + // Lines of frames that weren't rendered are dropped, otherwise they would pile up + primitiveBatchWrapper.Clear(); + + } + + void ViewportPanel::RenderGrid(const Scene::Components::CameraComponent& camera) { + + auto location = camera.GetLocation(); + + // The spacing grows with the camera height (1, 10, 100, ...), such that the grid stays readable + auto height = std::max(std::abs(location.y), 1.0f); + auto spacing = std::pow(10.0f, std::floor(std::log10(height))); + + const int32_t halfLineCount = 50; + auto extent = spacing * float(halfLineCount); + auto center = glm::round(vec2(location.x, location.z) / spacing) * spacing; + + const auto minorColor = vec3(0.25f); + const auto majorColor = vec3(0.45f); + const auto xAxisColor = vec3(0.85f, 0.25f, 0.25f); + const auto zAxisColor = vec3(0.25f, 0.45f, 0.95f); + + auto& wrapper = primitiveBatchWrapper; + for (int32_t i = -halfLineCount; i <= halfLineCount; i++) { + auto offset = float(i) * spacing; + + // Line parallel to the z axis at this x position + auto x = center.x + offset; + auto xIndex = int64_t(std::round(x / spacing)); + auto xColor = std::abs(x) < 0.5f * spacing ? zAxisColor : (xIndex % 10 == 0 ? majorColor : minorColor); + wrapper.GetBatch(true)->AddLine(vec3(x, 0.0f, center.y - extent), vec3(x, 0.0f, center.y + extent), xColor, xColor); + + // Line parallel to the x axis at this z position + auto z = center.y + offset; + auto zIndex = int64_t(std::round(z / spacing)); + auto zColor = std::abs(z) < 0.5f * spacing ? xAxisColor : (zIndex % 10 == 0 ? majorColor : minorColor); + wrapper.GetBatch(true)->AddLine(vec3(center.x - extent, 0.0f, z), vec3(center.x + extent, 0.0f, z), zColor, zColor); + } + + } + + float ViewportPanel::GetToolbarGroupWidth(int32_t buttonCount) const { + + auto buttonExtent = ImGui::GetTextLineHeight() * 1.15f + 2.0f * toolbarFramePadding; + return float(buttonCount) * buttonExtent + float(buttonCount - 1) * toolbarButtonSpacing + 2.0f * toolbarGroupPadding; + + } + + void ViewportPanel::BeginToolbarGroup(float x, int32_t buttonCount) { + + auto groupHeight = ImGui::GetTextLineHeight() * 1.15f + 2.0f * toolbarFramePadding + 2.0f * toolbarGroupPadding; + + auto windowPos = ImGui::GetWindowPos(); + auto drawList = ImGui::GetWindowDrawList(); + auto min = ImVec2(windowPos.x + x, windowPos.y + toolbarMargin); + auto max = ImVec2(min.x + GetToolbarGroupWidth(buttonCount), min.y + groupHeight); + drawList->AddRectFilled(min, max, ImGui::GetColorU32(Theme::OverlayBackground()), Theme::overlayRounding); + drawList->AddRect(min, max, ImGui::GetColorU32(Theme::OverlayBorder()), Theme::overlayRounding); + ImGui::SetCursorPos(ImVec2(x + toolbarGroupPadding, toolbarMargin + toolbarGroupPadding)); + + } + + bool ViewportPanel::ToolbarButton(const char* id, IconType iconType, bool selected, bool enabled, + const char* tooltip, ImVec2 uvMin, ImVec2 uvMax) { + + auto iconSize = ImGui::GetTextLineHeight() * 1.15f; + auto& icon = Singletons::icons->Get(iconType); + auto set = Singletons::imguiWrapper->GetTextureId(&icon); + + // Light mode icons are dark, so they would vanish on a solid accent fill, use a tint there + bool darkMode = Singletons::config->darkMode; + auto selectedColor = darkMode ? Theme::AccentFill() : Theme::Accent(0.22f); + auto selectedHoverColor = darkMode ? Theme::AccentFillHovered() : Theme::Accent(0.32f); + + auto hoverColor = ImGui::GetStyleColorVec4(ImGuiCol_ButtonHovered); + ImGui::PushStyleColor(ImGuiCol_Button, selected ? selectedColor : ImVec4(0.0f, 0.0f, 0.0f, 0.0f)); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, selected ? selectedHoverColor : hoverColor); + ImGui::PushStyleColor(ImGuiCol_ButtonActive, selectedColor); + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(toolbarFramePadding, toolbarFramePadding)); + ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 0.0f); + + ImGui::BeginDisabled(!enabled); + bool pressed = ImGui::ImageButton(id, set, ImVec2(iconSize, iconSize), uvMin, uvMax); + ImGui::EndDisabled(); + + ImGui::PopStyleVar(2); + ImGui::PopStyleColor(3); + + ImGui::SetItemTooltip("%s", tooltip); + ImGui::SameLine(0.0f, toolbarButtonSpacing); + + return pressed && enabled; + + } + + void ViewportPanel::RenderVisualizationPopup() { + + if (!ImGui::BeginPopup("Visualization settings")) + return; + + auto menuItem = [&](const char* name, ViewportVisualization vis) { + bool selected = visualization == vis; + ImGui::MenuItem(name, nullptr, &selected); + if (selected) + visualization = vis; + }; + + ImGui::SeparatorText("Visualization"); + + menuItem("Lit", ViewportVisualization::Lit); + + if (ImGui::BeginMenu("GBuffer")) { + menuItem("Base color", ViewportVisualization::GBufferBaseColor); + menuItem("Roughness/Metalness/Ao", ViewportVisualization::GBufferRoughnessMetalnessAo); + menuItem("Emissive color", ViewportVisualization::GBufferEmissive); + menuItem("Depth", ViewportVisualization::GBufferDepth); + menuItem("Normals", ViewportVisualization::GBufferNormals); + menuItem("Geometry normals", ViewportVisualization::GBufferGeometryNormals); + menuItem("Velocity", ViewportVisualization::GBufferVelocity); + menuItem("Material index", ViewportVisualization::GBufferMaterialIdx); + menuItem("Stencil", ViewportVisualization::GBufferStencil); + ImGui::EndMenu(); } + menuItem("Volumetrics", ViewportVisualization::Volumetrics); + menuItem("Clouds", ViewportVisualization::Clouds); + menuItem("Reflections", ViewportVisualization::Reflections); + menuItem("SSS", ViewportVisualization::SSS); + menuItem("SSGI", ViewportVisualization::SSGI); + + ImGui::EndPopup(); + } void ViewportPanel::RenderVisualization(float exposure) { auto graphicsDevice = Graphics::GraphicsDevice::DefaultDevice; - auto& renderTarget = Singletons::renderTarget; - auto& mainRenderer = Singletons::mainRenderer; - auto rtData = renderTarget->GetData(Renderer::RenderResolution::FULL_RES); auto commandList = graphicsDevice->GetCommandList(Atlas::Graphics::GraphicsQueue); commandList->BeginCommands(); - commandList->BeginRenderPass(renderPass, frameBuffer, true); + commandList->BeginRendering(rendering); if (visualization == GBufferBaseColor) { - mainRenderer->textureRenderer.RenderTexture2D(commandList, viewport, rtData->baseColorTexture.get(), - 0.0f, 0.0f, float(viewport->width), float(viewport->height), 0.0, 1.0f, false, true); + mainRenderer->textureRenderer.RenderTexture2D(commandList, renderViewport, rtData->baseColorTexture.get(), + 0.0f, 0.0f, float(renderViewport->width), float(renderViewport->height), 0.0, 1.0f, false, true); } if (visualization == GBufferRoughnessMetalnessAo) { - mainRenderer->textureRenderer.RenderTexture2D(commandList, viewport, rtData->roughnessMetallicAoTexture.get(), - 0.0f, 0.0f, float(viewport->width), float(viewport->height), 0.0, 1.0f, false, true); + mainRenderer->textureRenderer.RenderTexture2D(commandList, renderViewport, rtData->roughnessMetallicAoTexture.get(), + 0.0f, 0.0f, float(renderViewport->width), float(renderViewport->height), 0.0, 1.0f, false, true); } if (visualization == GBufferEmissive) { - mainRenderer->textureRenderer.RenderTexture2D(commandList, viewport, rtData->emissiveTexture.get(), - 0.0f, 0.0f, float(viewport->width), float(viewport->height), 0.0, 1.0f, false, true); + mainRenderer->textureRenderer.RenderTexture2D(commandList, renderViewport, rtData->emissiveTexture.get(), + 0.0f, 0.0f, float(renderViewport->width), float(renderViewport->height), 0.0, 1.0f, false, true); } if (visualization == GBufferNormals) { - mainRenderer->textureRenderer.RenderTexture2D(commandList, viewport, rtData->normalTexture.get(), - 0.0f, 0.0f, float(viewport->width), float(viewport->height), 0.0, 1.0f, false, true); + mainRenderer->textureRenderer.RenderTexture2D(commandList, renderViewport, rtData->normalTexture.get(), + 0.0f, 0.0f, float(renderViewport->width), float(renderViewport->height), 0.0, 1.0f, false, true); } if (visualization == GBufferGeometryNormals) { - mainRenderer->textureRenderer.RenderTexture2D(commandList, viewport, rtData->geometryNormalTexture.get(), - 0.0f, 0.0f, float(viewport->width), float(viewport->height), 0.0, 1.0f, false, true); + mainRenderer->textureRenderer.RenderTexture2D(commandList, renderViewport, rtData->geometryNormalTexture.get(), + 0.0f, 0.0f, float(renderViewport->width), float(renderViewport->height), 0.0, 1.0f, false, true); } if (visualization == GBufferMaterialIdx) { - mainRenderer->textureRenderer.RenderTexture2D(commandList, viewport, rtData->materialIdxTexture.get(), - 0.0f, 0.0f, float(viewport->width), float(viewport->height), 0.0, 1.0f / 10000.0f, false, true); + mainRenderer->textureRenderer.RenderTexture2D(commandList, renderViewport, rtData->materialIdxTexture.get(), + 0.0f, 0.0f, float(renderViewport->width), float(renderViewport->height), 0.0, 1.0f / 10000.0f, false, true); } if (visualization == GBufferStencil) { - mainRenderer->textureRenderer.RenderTexture2D(commandList, viewport, rtData->stencilTexture.get(), - 0.0f, 0.0f, float(viewport->width), float(viewport->height), 0.0, 1.0f / 255.0f, false, true); + mainRenderer->textureRenderer.RenderTexture2D(commandList, renderViewport, rtData->stencilTexture.get(), + 0.0f, 0.0f, float(renderViewport->width), float(renderViewport->height), 0.0, 1.0f / 255.0f, false, true); } if (visualization == GBufferDepth) { - mainRenderer->textureRenderer.RenderTexture2D(commandList, viewport, rtData->depthTexture.get(), - 0.0f, 0.0f, float(viewport->width), float(viewport->height), 0.0, 1.0f, false, true); + mainRenderer->textureRenderer.RenderTexture2D(commandList, renderViewport, rtData->depthTexture.get(), + 0.0f, 0.0f, float(renderViewport->width), float(renderViewport->height), 0.0, 1.0f, false, true); } if (visualization == GBufferVelocity) { - mainRenderer->textureRenderer.RenderTexture2D(commandList, viewport, rtData->velocityTexture.get(), - 0.0f, 0.0f, float(viewport->width), float(viewport->height), 0.0, 100.0f, false, true); + mainRenderer->textureRenderer.RenderTexture2D(commandList, renderViewport, rtData->velocityTexture.get(), + 0.0f, 0.0f, float(renderViewport->width), float(renderViewport->height), 0.0, 100.0f, false, true); } else if (visualization == Reflections) { - mainRenderer->textureRenderer.RenderTexture2D(commandList, viewport, &renderTarget->reflectionTexture, - 0.0f, 0.0f, float(viewport->width), float(viewport->height), 0.0, exposure, false, true); + mainRenderer->textureRenderer.RenderTexture2D(commandList, renderViewport, &renderTarget->reflectionTexture, + 0.0f, 0.0f, float(renderViewport->width), float(renderViewport->height), 0.0, exposure, false, true); } else if (visualization == Volumetrics) { - mainRenderer->textureRenderer.RenderTexture2D(commandList, viewport, &renderTarget->volumetricTexture, - 0.0f, 0.0f, float(viewport->width), float(viewport->height), 0.0, exposure, false, true); + mainRenderer->textureRenderer.RenderTexture2D(commandList, renderViewport, &renderTarget->volumetricTexture, + 0.0f, 0.0f, float(renderViewport->width), float(renderViewport->height), 0.0, exposure, false, true); } else if (visualization == Clouds) { - mainRenderer->textureRenderer.RenderTexture2D(commandList, viewport, &renderTarget->volumetricCloudsTexture, - 0.0f, 0.0f, float(viewport->width), float(viewport->height), 0.0, exposure, false, true); + mainRenderer->textureRenderer.RenderTexture2D(commandList, renderViewport, &renderTarget->volumetricCloudsTexture, + 0.0f, 0.0f, float(renderViewport->width), float(renderViewport->height), 0.0, exposure, false, true); } else if (visualization == SSS) { - mainRenderer->textureRenderer.RenderTexture2D(commandList, viewport, &renderTarget->sssTexture, - 0.0f, 0.0f, float(viewport->width), float(viewport->height), 0.0, 1.0f, false, true); + mainRenderer->textureRenderer.RenderTexture2D(commandList, renderViewport, &renderTarget->sssTexture, + 0.0f, 0.0f, float(renderViewport->width), float(renderViewport->height), 0.0, 1.0f, false, true); } else if (visualization == SSGI) { - mainRenderer->textureRenderer.RenderTexture2D(commandList, viewport, &renderTarget->giTexture, - 0.0f, 0.0f, float(viewport->width), float(viewport->height), 0.0, exposure, false, true); + mainRenderer->textureRenderer.RenderTexture2D(commandList, renderViewport, &renderTarget->giTexture, + 0.0f, 0.0f, float(renderViewport->width), float(renderViewport->height), 0.0, exposure, false, true); } - commandList->EndRenderPass(); - - commandList->ImageMemoryBarrier(viewportTexture.image, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, - VK_ACCESS_SHADER_READ_BIT, VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT, VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT); + commandList->EndRendering(); commandList->EndCommands(); graphicsDevice->SubmitCommandList(commandList); } - void ViewportPanel::CreateRenderPass() { - - auto device = Graphics::GraphicsDevice::DefaultDevice; - - auto colorAttachment = Graphics::RenderPassColorAttachment{ - .imageFormat = viewportTexture.image->format, - .loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR, - .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED, - .outputLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, - }; - - auto renderPassDesc = Graphics::RenderPassDesc{ - .colorAttachments = { colorAttachment } - }; - - renderPass = device->CreateRenderPass(renderPassDesc); + void ViewportPanel::CreateRendering() { - auto frameBufferDesc = Graphics::FrameBufferDesc { - .renderPass = renderPass, - .colorAttachments = { - { viewportTexture.image, 0, true }, - }, - .extent = { uint32_t(viewportTexture.width), uint32_t(viewportTexture.height) } + rendering = Graphics::RenderingDesc{ + .colorAttachments = { { + .image = viewportTexture.image, + .loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR + } } }; - frameBuffer = device->CreateFrameBuffer(frameBufferDesc); } diff --git a/src/editor/ui/panels/ViewportPanel.h b/src/editor/ui/panels/ViewportPanel.h index cd8a84307..ec3ffc000 100644 --- a/src/editor/ui/panels/ViewportPanel.h +++ b/src/editor/ui/panels/ViewportPanel.h @@ -3,7 +3,10 @@ #include "Panel.h" #include "tools/PrimitiveBatchWrapper.h" #include "scene/Scene.h" +#include "renderer/target/RenderTarget.h" +#include "renderer/MainRenderer.h" #include "Viewport.h" +#include "Icons.h" namespace Atlas::Editor::UI { @@ -34,13 +37,41 @@ namespace Atlas::Editor::UI { void DrawOverlay(std::function func); - void Render(Ref& scene, bool isActiveWindow); + void Render(Ref& scene); - void RenderScene(Ref& scene, ivec2 pos, ivec2 size, bool isActive); + void RenderScene(Ref& scene, ivec2 pos, ivec2 size); + // Ground grid on the y = 0 plane around the camera + void RenderGrid(const Scene::Components::CameraComponent& camera); + + // Toolbars are drawn as floating, rounded button groups on top of the viewport from the menu bar function + float GetToolbarGroupWidth(int32_t buttonCount) const; + + void BeginToolbarGroup(float x, int32_t buttonCount); + + bool ToolbarButton(const char* id, IconType iconType, bool selected, bool enabled, const char* tooltip, + ImVec2 uvMin = ImVec2(0.15f, 0.15f), ImVec2 uvMax = ImVec2(0.85f, 0.85f)); + + // Contents of a "Visualization settings" popup, which selects the visualization + void RenderVisualizationPopup(); + + static constexpr float toolbarMargin = 8.0f; + static constexpr float toolbarGroupPadding = 3.0f; + static constexpr float toolbarButtonSpacing = 2.0f; + static constexpr float toolbarFramePadding = 5.0f; + + // In ImGui units for the interface, the scene is rendered with the render viewport Ref viewport; + Ref renderViewport; Texture::Texture2D viewportTexture; + // All visible viewports are rendered in the same frame, so uniform buffers, upscalers and history can't be shared + Ref renderTarget; + Ref mainRenderer; + + // Off for content the path tracer can't show, e.g. material graphs + bool allowPathTracing = true; + PrimitiveBatchWrapper primitiveBatchWrapper; ViewportVisualization visualization = Lit; @@ -48,15 +79,17 @@ namespace Atlas::Editor::UI { std::function drawMenuBarFunc; std::function drawOverlayFunc; + // Frame around the viewport, shows e.g. that the scene is playing. Invisible with an alpha of zero + ImVec4 frameColor = ImVec4(0.0f, 0.0f, 0.0f, 0.0f); + private: void RenderVisualization(float exposure); - void CreateRenderPass(); + void CreateRendering(); bool firstFrame = true; - Ref renderPass; - Ref frameBuffer; + Graphics::RenderingDesc rendering; }; diff --git a/src/editor/ui/panels/components/AnimationComponentPanel.cpp b/src/editor/ui/panels/components/AnimationComponentPanel.cpp new file mode 100644 index 000000000..367800532 --- /dev/null +++ b/src/editor/ui/panels/components/AnimationComponentPanel.cpp @@ -0,0 +1,251 @@ +#include "AnimationComponentPanel.h" + +#include "../../Widgets.h" +#include "../../../Theme.h" + +namespace Atlas::Editor::UI { + + bool AnimationComponentPanel::Render(Ref& scene, + Scene::Entity entity, AnimationComponent& animationComponent) { + + bool resourceChanged = false; + + auto animation = animationSelectionPanel.Render(animationComponent.animation, resourceChanged); + if (resourceChanged) + animationComponent.Play(animation, blendTime); + + auto meshComponent = entity.TryGetComponent(); + auto skinned = meshComponent && meshComponent->mesh.IsLoaded() && meshComponent->mesh->data.IsSkinned(); + if (!skinned) + ImGui::TextDisabled("The entity needs a skinned mesh"); + + Widgets::PropertySection("Playback"); + + if (Widgets::BeginProperties("Playback")) { + Widgets::PropertyLabel("Playing"); + ImGui::Checkbox("##Playing", &animationComponent.playing); + Widgets::PropertyLabel("Loop"); + ImGui::Checkbox("##Loop", &animationComponent.loop); + Widgets::PropertyLabel("Speed"); + ImGui::DragFloat("##Speed", &animationComponent.speed, 0.01f, -10.0f, 10.0f); + Widgets::PropertyLabel("Blend time", "Time to blend over when a new animation is selected"); + ImGui::DragFloat("##Blend time", &blendTime, 0.01f, 0.0f, 5.0f); + + auto duration = animationComponent.animation.IsLoaded() ? animationComponent.animation->duration : 0.0f; + Widgets::PropertyLabel("Time"); + ImGui::SliderFloat("##Time", &animationComponent.time, 0.0f, duration); + Widgets::EndProperties(); + } + + Widgets::PropertySection("Layers"); + + const Mesh::Skeleton* skeleton = skinned ? &meshComponent->mesh->data.skeleton : nullptr; + int32_t removedLayer = -1; + for (int32_t i = 0; i < animationComponent.GetLayerCount(); i++) { + ImGui::PushID(i); + bool remove = false; + auto name = "Layer " + std::to_string(i); + if (Widgets::BeginPropertyGroup(name.c_str())) { + if (Widgets::RemovableSectionHeader(name.c_str(), ImGuiTreeNodeFlags_DefaultOpen | Widgets::PropertyGroupHeaderFlags(), + remove, "Remove layer")) { + Widgets::BeginPropertyContent(); + resourceChanged |= RenderLayer(animationComponent.GetLayer(i), skeleton); + Widgets::EndPropertyContent(); + } + Widgets::EndPropertyGroup(); + } + if (remove) + removedLayer = i; + ImGui::PopID(); + } + + if (removedLayer >= 0) + animationComponent.layers.erase(animationComponent.layers.begin() + removedLayer); + + Theme::PushPrimaryButton(); + if (ImGui::Button("Add layer", ImVec2(-FLT_MIN, 0.0f))) + animationComponent.GetLayer(animationComponent.GetLayerCount()); + Theme::PopPrimaryButton(); + + Widgets::PropertySection("Inverse kinematics"); + + int32_t removedChain = -1; + for (int32_t i = 0; i < animationComponent.GetIKChainCount(); i++) { + ImGui::PushID(1000 + i); + bool remove = false; + auto name = "Chain " + std::to_string(i); + if (Widgets::BeginPropertyGroup(name.c_str())) { + if (Widgets::RemovableSectionHeader(name.c_str(), ImGuiTreeNodeFlags_DefaultOpen | Widgets::PropertyGroupHeaderFlags(), + remove, "Remove chain")) { + Widgets::BeginPropertyContent(); + RenderIKChain(animationComponent.GetIKChain(i), skeleton); + Widgets::EndPropertyContent(); + } + Widgets::EndPropertyGroup(); + } + if (remove) + removedChain = i; + ImGui::PopID(); + } + + if (removedChain >= 0) + animationComponent.ikChains.erase(animationComponent.ikChains.begin() + removedChain); + + Theme::PushPrimaryButton(); + if (ImGui::Button("Add chain", ImVec2(-FLT_MIN, 0.0f))) + animationComponent.GetIKChain(animationComponent.GetIKChainCount()); + Theme::PopPrimaryButton(); + + animationSelectionPanel.Reset(); + + return resourceChanged; + + } + + bool AnimationComponentPanel::RenderLayer(AnimationLayer& layer, const Mesh::Skeleton* skeleton) { + + bool resourceChanged = false; + + auto animation = animationSelectionPanel.Render(layer.animation, resourceChanged); + if (resourceChanged) + layer.Play(animation, blendTime); + + if (!Widgets::BeginProperties("Layer")) + return resourceChanged; + + const char* modes[] = { "Override", "Additive" }; + auto mode = static_cast(layer.mode); + Widgets::PropertyLabel("Mode"); + if (Widgets::SegmentedControl("##Mode", mode, modes, IM_ARRAYSIZE(modes))) + layer.mode = static_cast(mode); + + auto weight = layer.GetTargetWeight(); + Widgets::PropertyLabel("Weight"); + if (ImGui::SliderFloat("##Weight", &weight, 0.0f, 1.0f)) + layer.FadeTo(weight); + + // The mask starts at a joint of the skeleton, the whole skeleton without one + auto maskRoot = layer.GetMaskRoot(); + auto blendJoints = layer.GetMaskBlendJoints(); + auto maskChanged = false; + Widgets::PropertyLabel("Mask root"); + if (ImGui::BeginCombo("##Mask root", maskRoot.empty() ? "Whole skeleton" : maskRoot.c_str())) { + if (ImGui::Selectable("Whole skeleton", maskRoot.empty())) { + maskRoot.clear(); + maskChanged = true; + } + for (size_t i = 0; skeleton && i < skeleton->joints.size(); i++) { + const auto& name = skeleton->joints[i].name; + // Skeletons can have several joints with the same name + ImGui::PushID(int32_t(i)); + if (ImGui::Selectable(name.c_str(), name == maskRoot)) { + maskRoot = name; + maskChanged = true; + } + ImGui::PopID(); + } + ImGui::EndCombo(); + } + if (!maskRoot.empty()) { + Widgets::PropertyLabel("Blend joints", "Joints from the mask root down over which the layer fades in, e.g. along the spine"); + maskChanged |= ImGui::DragInt("##Blend joints", &blendJoints, 0.1f, 0, 16); + } + if (maskChanged) + layer.SetMask(maskRoot, blendJoints); + + Widgets::PropertyLabel("Playing"); + ImGui::Checkbox("##Playing", &layer.playing); + Widgets::PropertyLabel("Loop"); + ImGui::Checkbox("##Loop", &layer.loop); + Widgets::PropertyLabel("Speed"); + ImGui::DragFloat("##Speed", &layer.speed, 0.01f, -10.0f, 10.0f); + + auto duration = layer.animation.IsLoaded() ? layer.animation->duration : 0.0f; + Widgets::PropertyLabel("Time"); + ImGui::SliderFloat("##Time", &layer.time, 0.0f, duration); + + Widgets::EndProperties(); + + return resourceChanged; + + } + + void AnimationComponentPanel::RenderIKChain(AnimationIKChain& chain, const Mesh::Skeleton* skeleton) { + + std::string joints[] = { chain.GetUpperJoint(), chain.GetMiddleJoint(), chain.GetEndJoint() }; + const char* labels[] = { "Upper joint", "Middle joint", "End joint" }; + + if (!Widgets::BeginProperties("Chain")) + return; + + auto jointsChanged = false; + for (int32_t i = 0; i < 3; i++) { + Widgets::PropertyLabel(labels[i]); + ImGui::PushID(i); + if (!ImGui::BeginCombo("##Joint", joints[i].empty() ? "None" : joints[i].c_str())) { + ImGui::PopID(); + continue; + } + for (size_t j = 0; skeleton && j < skeleton->joints.size(); j++) { + const auto& name = skeleton->joints[j].name; + // Skeletons can have several joints with the same name + ImGui::PushID(int32_t(j)); + if (ImGui::Selectable(name.c_str(), name == joints[i])) { + joints[i] = name; + jointsChanged = true; + } + ImGui::PopID(); + } + ImGui::EndCombo(); + ImGui::PopID(); + } + if (jointsChanged) + chain.SetJoints(joints[0], joints[1], joints[2]); + + Widgets::EndProperties(); + + if (!chain.IsValid() && !joints[0].empty()) + ImGui::TextDisabled("Joints not found in the skeleton"); + + if (Widgets::BeginProperties("Chain target")) { + Widgets::PropertyLabel("Weight"); + ImGui::SliderFloat("##Weight", &chain.weight, 0.0f, 1.0f); + Widgets::PropertyLabel("Relative target", "The target is a world offset from where the animation puts the end joint"); + ImGui::Checkbox("##Relative target", &chain.relativeTarget); + Widgets::PropertyLabel("Target", chain.relativeTarget ? "World offset from the animated end joint" : "World position the end joint reaches for"); + Widgets::DragVec3("##Target", chain.target, 0.01f); + Widgets::PropertyLabel("Pole", "Direction in mesh space the middle joint bends to when the chain is straight"); + Widgets::DragVec3("##Pole", chain.pole, 0.01f, 0.0f, -1.0f, 1.0f); + Widgets::PropertyLabel("Normal"); + Widgets::DragVec3("##Normal", chain.normal, 0.01f, 0.0f, -1.0f, 1.0f); + Widgets::PropertyLabel("Normal weight"); + ImGui::SliderFloat("##Normal weight", &chain.normalWeight, 0.0f, 1.0f); + Widgets::EndProperties(); + } + + if (Widgets::BeginProperties("Foot lock")) { + Widgets::PropertyLabel("Foot lock", "A foot the animation sets down keeps its place until the animation lifts it"); + ImGui::Checkbox("##Foot lock", &chain.footLock); + Widgets::PropertyLabel("Lock speed", "Speed in chain lengths per second below which a lowered foot is planted"); + ImGui::DragFloat("##Lock speed", &chain.lockSpeed, 0.05f, 0.0f, 10.0f); + Widgets::PropertyLabel("Unlock speed", "Speed in chain lengths per second above which a planted foot lifts"); + ImGui::DragFloat("##Unlock speed", &chain.unlockSpeed, 0.05f, 0.0f, 20.0f); + Widgets::PropertyLabel("Speed ratio", "Fraction of the speed of the entity a foot may move and still count as planted"); + ImGui::DragFloat("##Speed ratio", &chain.lockSpeedRatio, 0.01f, 0.0f, 1.0f); + Widgets::PropertyLabel("Lock height", "Height in chain lengths over the lowest point of the steps"); + ImGui::DragFloat("##Lock height", &chain.lockHeight, 0.01f, 0.0f, 1.0f); + Widgets::PropertyLabel("Lock reach", "Distance in chain lengths from the animated foot at which a planted foot lets go"); + ImGui::DragFloat("##Lock reach", &chain.lockReach, 0.01f, 0.0f, 2.0f); + Widgets::PropertyLabel("Release time", "Seconds the foot takes to return to the animation"); + ImGui::DragFloat("##Release time", &chain.lockReleaseTime, 0.01f, 0.0f, 1.0f); + Widgets::EndProperties(); + if (chain.footLock) + ImGui::TextDisabled(chain.IsLocked() ? "Planted" : "Free"); + } + + if (ImGui::Button("Target from animation")) + chain.target = chain.relativeTarget ? vec3(0.0f) : chain.GetAnimatedEndPosition(); + + } + +} diff --git a/src/editor/ui/panels/components/AnimationComponentPanel.h b/src/editor/ui/panels/components/AnimationComponentPanel.h new file mode 100644 index 000000000..1edebf147 --- /dev/null +++ b/src/editor/ui/panels/components/AnimationComponentPanel.h @@ -0,0 +1,30 @@ +#pragma once + +#include "../Panel.h" + +#include "scene/Scene.h" +#include "scene/components/AnimationComponent.h" + +#include "../ResourceSelectionPanel.h" + +namespace Atlas::Editor::UI { + + class AnimationComponentPanel : public Panel { + + public: + AnimationComponentPanel() : Panel("Animation component") {} + + bool Render(Ref& scene, Scene::Entity entity, AnimationComponent& animationComponent); + + private: + bool RenderLayer(AnimationLayer& layer, const Mesh::Skeleton* skeleton); + + void RenderIKChain(AnimationIKChain& chain, const Mesh::Skeleton* skeleton); + + ResourceSelectionPanel animationSelectionPanel; + + float blendTime = 0.2f; + + }; + +} diff --git a/src/editor/ui/panels/components/AudioComponentPanel.cpp b/src/editor/ui/panels/components/AudioComponentPanel.cpp index b7ee5069f..f75f54765 100644 --- a/src/editor/ui/panels/components/AudioComponentPanel.cpp +++ b/src/editor/ui/panels/components/AudioComponentPanel.cpp @@ -1,4 +1,5 @@ #include "AudioComponentPanel.h" +#include "../../Widgets.h" #include "../../../tools/ResourcePayloadHelper.h" @@ -19,20 +20,32 @@ namespace Atlas::Editor::UI { audioComponent.ChangeResource(handle); } - ImGui::SeparatorText("Playback"); + Widgets::PropertySection("Playback"); - ImGui::SliderFloat("Volume", &audioComponent.volume, 0.0f, 1.0f); - ImGui::Checkbox("Play permanently", &audioComponent.permanentPlay); + if (Widgets::BeginProperties("AudioPlayback")) { + Widgets::PropertyLabel("Volume"); + ImGui::SliderFloat("##Volume", &audioComponent.volume, 0.0f, 1.0f); + Widgets::PropertyLabel("Play permanently"); + ImGui::Checkbox("##Play permanently", &audioComponent.permanentPlay); - if (audioComponent.stream && audioComponent.stream->IsValid()) { - ImGui::Checkbox("Loop stream", &audioComponent.stream->loop); + if (audioComponent.stream && audioComponent.stream->IsValid()) { + Widgets::PropertyLabel("Loop stream"); + ImGui::Checkbox("##Loop stream", &audioComponent.stream->loop); + } + Widgets::EndProperties(); } - ImGui::SeparatorText("Attenuation"); + Widgets::PropertySection("Attenuation"); - ImGui::DragFloat("Cutoff", &audioComponent.cutoff, 0.001f, 0.0001f, 0.2f); - ImGui::DragFloat("Falloff factor", &audioComponent.falloffFactor, 0.05f, 0.0f, 100.0f); - ImGui::DragFloat("Falloff power", &audioComponent.falloffPower, 1.0f, 0.0f, 100.0f); + if (Widgets::BeginProperties("AudioAttenuation")) { + Widgets::PropertyLabel("Cutoff"); + ImGui::DragFloat("##Cutoff", &audioComponent.cutoff, 0.001f, 0.0001f, 0.2f); + Widgets::PropertyLabel("Falloff factor"); + ImGui::DragFloat("##Falloff factor", &audioComponent.falloffFactor, 0.05f, 0.0f, 100.0f); + Widgets::PropertyLabel("Falloff power"); + ImGui::DragFloat("##Falloff power", &audioComponent.falloffPower, 1.0f, 0.0f, 100.0f); + Widgets::EndProperties(); + } audioSelectionPanel.Reset(); diff --git a/src/editor/ui/panels/components/AudioVolumeComponentPanel.cpp b/src/editor/ui/panels/components/AudioVolumeComponentPanel.cpp index 88e161033..86c4a6eb3 100644 --- a/src/editor/ui/panels/components/AudioVolumeComponentPanel.cpp +++ b/src/editor/ui/panels/components/AudioVolumeComponentPanel.cpp @@ -20,19 +20,29 @@ namespace Atlas::Editor::UI { audioVolumeComponent.ChangeResource(handle); } - ImGui::Text("AABB"); - Widgets::DragVec3("Min", audioVolumeComponent.aabb.min, 0.1f, 0.0f, -10000.0f, 10000.0f); - Widgets::DragVec3("Max", audioVolumeComponent.aabb.max, 0.1f, 0.0f, -10000.0f, 10000.0f); - - ImGui::DragFloat("Volume", &audioVolumeComponent.volume, 0.005f, 0.0f, 1.0f); - ImGui::DragFloat("Cutoff", &audioVolumeComponent.cutoff, 0.001f, 0.0001f, 0.2f); - ImGui::DragFloat("Falloff factor", &audioVolumeComponent.falloffFactor, 0.05f, 0.0f, 100.0f); - ImGui::DragFloat("Falloff power", &audioVolumeComponent.falloffPower, 1.0f, 0.0f, 100.0f); - - ImGui::Checkbox("Play permanently", &audioVolumeComponent.permanentPlay); - - if (audioVolumeComponent.stream && audioVolumeComponent.stream->IsValid()) { - ImGui::Checkbox("Loop stream", &audioVolumeComponent.stream->loop); + if (Widgets::BeginProperties("AudioVolume")) { + Widgets::PropertyLabel("AABB min"); + Widgets::DragVec3("##AABB min", audioVolumeComponent.aabb.min, 0.1f, 0.0f, -10000.0f, 10000.0f); + Widgets::PropertyLabel("AABB max"); + Widgets::DragVec3("##AABB max", audioVolumeComponent.aabb.max, 0.1f, 0.0f, -10000.0f, 10000.0f); + + Widgets::PropertyLabel("Volume"); + ImGui::DragFloat("##Volume", &audioVolumeComponent.volume, 0.005f, 0.0f, 1.0f); + Widgets::PropertyLabel("Cutoff"); + ImGui::DragFloat("##Cutoff", &audioVolumeComponent.cutoff, 0.001f, 0.0001f, 0.2f); + Widgets::PropertyLabel("Falloff factor"); + ImGui::DragFloat("##Falloff factor", &audioVolumeComponent.falloffFactor, 0.05f, 0.0f, 100.0f); + Widgets::PropertyLabel("Falloff power"); + ImGui::DragFloat("##Falloff power", &audioVolumeComponent.falloffPower, 1.0f, 0.0f, 100.0f); + + Widgets::PropertyLabel("Play permanently"); + ImGui::Checkbox("##Play permanently", &audioVolumeComponent.permanentPlay); + + if (audioVolumeComponent.stream && audioVolumeComponent.stream->IsValid()) { + Widgets::PropertyLabel("Loop stream"); + ImGui::Checkbox("##Loop stream", &audioVolumeComponent.stream->loop); + } + Widgets::EndProperties(); } audioSelectionPanel.Reset(); diff --git a/src/editor/ui/panels/components/CameraComponentPanel.cpp b/src/editor/ui/panels/components/CameraComponentPanel.cpp index 5f77a4cdc..e188d82bc 100644 --- a/src/editor/ui/panels/components/CameraComponentPanel.cpp +++ b/src/editor/ui/panels/components/CameraComponentPanel.cpp @@ -7,37 +7,60 @@ namespace Atlas::Editor::UI { ImGui::PushID(GetNameID()); - ImGui::Checkbox("Main camera", &cameraComponent.isMain); - ImGui::SetItemTooltip("The main camera renders the scene while playing"); - - ImGui::SeparatorText("Transform"); - - Widgets::DragVec3("Position", cameraComponent.location, 0.1f, 0.0f, -10000.0f, 10000.0f); - - // Rotation is stored in radians (pitch, yaw), but degrees are easier to work with - auto rotationDegrees = glm::degrees(cameraComponent.rotation); - if (ImGui::DragFloat2("Rotation", glm::value_ptr(rotationDegrees), 0.5f, -180.0f, 180.0f, "%.1f\xc2\xb0")) - cameraComponent.rotation = glm::radians(rotationDegrees); - - ImGui::Checkbox("Use entity translation", &cameraComponent.useEntityTranslation); - ImGui::Checkbox("Use entity rotation", &cameraComponent.useEntityRotation); - - ImGui::SeparatorText("Third person"); - - ImGui::Checkbox("Enabled", &cameraComponent.thirdPerson); - ImGui::BeginDisabled(!cameraComponent.thirdPerson); - ImGui::DragFloat("Distance", &cameraComponent.thirdPersonDistance, 0.1f, 0.0f, 100.0f); - ImGui::EndDisabled(); - - ImGui::SeparatorText("Lens"); - - ImGui::DragFloat("Field of view", &cameraComponent.fieldOfView, 0.1f, 1.0f, 180.0f); - ImGui::DragFloat("Aspect ratio", &cameraComponent.aspectRatio, 0.01f, 0.01f, 4.0f); - - ImGui::DragFloat("Near plane", &cameraComponent.nearPlane, 0.01f, 0.01f, 10.0f); - ImGui::DragFloat("Far plane", &cameraComponent.farPlane, 1.0f, 1.0f, 2000.0f); - - ImGui::DragFloat("Exposure", &cameraComponent.exposure, 0.01f, 0.01f, 100.0f); + if (Widgets::BeginProperties("CameraComponent")) { + Widgets::PropertyLabel("Main camera", "The main camera renders the scene while playing"); + ImGui::Checkbox("##Main camera", &cameraComponent.isMain); + Widgets::EndProperties(); + } + + Widgets::PropertySection("Transform"); + + if (Widgets::BeginProperties("CameraTransform")) { + Widgets::PropertyLabel("Position"); + Widgets::DragVec3("##Position", cameraComponent.location, 0.1f, 0.0f, -10000.0f, 10000.0f); + + // Rotation is stored in radians (pitch, yaw), but degrees are easier to work with + auto rotationDegrees = glm::degrees(cameraComponent.rotation); + Widgets::PropertyLabel("Rotation"); + if (ImGui::DragFloat2("##Rotation", glm::value_ptr(rotationDegrees), 0.5f, -180.0f, 180.0f, "%.1f\xc2\xb0")) + cameraComponent.rotation = glm::radians(rotationDegrees); + + Widgets::PropertyLabel("Use entity translation"); + ImGui::Checkbox("##Use entity translation", &cameraComponent.useEntityTranslation); + Widgets::PropertyLabel("Use entity rotation"); + ImGui::Checkbox("##Use entity rotation", &cameraComponent.useEntityRotation); + Widgets::EndProperties(); + } + + Widgets::PropertySection("Third person"); + + if (Widgets::BeginProperties("CameraThirdPerson")) { + Widgets::PropertyLabel("Enabled"); + ImGui::Checkbox("##Enabled", &cameraComponent.thirdPerson); + ImGui::BeginDisabled(!cameraComponent.thirdPerson); + Widgets::PropertyLabel("Distance"); + ImGui::DragFloat("##Distance", &cameraComponent.thirdPersonDistance, 0.1f, 0.0f, 100.0f); + ImGui::EndDisabled(); + Widgets::EndProperties(); + } + + Widgets::PropertySection("Lens"); + + if (Widgets::BeginProperties("CameraLens")) { + Widgets::PropertyLabel("Field of view"); + ImGui::DragFloat("##Field of view", &cameraComponent.fieldOfView, 0.1f, 1.0f, 180.0f); + Widgets::PropertyLabel("Aspect ratio"); + ImGui::DragFloat("##Aspect ratio", &cameraComponent.aspectRatio, 0.01f, 0.01f, 4.0f); + + Widgets::PropertyLabel("Near plane"); + ImGui::DragFloat("##Near plane", &cameraComponent.nearPlane, 0.01f, 0.01f, 10.0f); + Widgets::PropertyLabel("Far plane"); + ImGui::DragFloat("##Far plane", &cameraComponent.farPlane, 1.0f, 1.0f, 2000.0f); + + Widgets::PropertyLabel("Exposure"); + ImGui::DragFloat("##Exposure", &cameraComponent.exposure, 0.01f, 0.01f, 100.0f); + Widgets::EndProperties(); + } ImGui::PopID(); diff --git a/src/editor/ui/panels/components/ConstraintComponentPanel.cpp b/src/editor/ui/panels/components/ConstraintComponentPanel.cpp new file mode 100644 index 000000000..c151c9847 --- /dev/null +++ b/src/editor/ui/panels/components/ConstraintComponentPanel.cpp @@ -0,0 +1,139 @@ +#include "ConstraintComponentPanel.h" +#include "../../../Theme.h" +#include "../../Widgets.h" + +namespace Atlas::Editor::UI { + + using namespace Physics; + + bool ConstraintComponentPanel::Render(Ref& scene, Scene::Entity entity, + ConstraintComponent& constraintComponent) { + + ImGui::PushID(GetNameID()); + + if (!entity.HasComponent()) + Widgets::Callout("Constraint component needs a rigid body component to work properly", Theme::Warning()); + + if (constraintComponent.broken) + Widgets::Callout("The constraint broke, changing it creates it again", Theme::Warning()); + + Widgets::PropertySection("Connected entity"); + + bool changed = RenderConnectedEntity(entity, constraintComponent); + + Widgets::PropertySection("Constraint"); + + changed |= RenderConstraintSettings(constraintComponent.creationSettings); + + // Constraints are created while simulating, changes create the constraint again + if (changed) + constraintComponent.Reset(); + + ImGui::PopID(); + + return false; + + } + + bool ConstraintComponentPanel::RenderConnectedEntity(Scene::Entity entity, ConstraintComponent& constraintComponent) { + + auto connectedEntity = constraintComponent.GetConnectedEntity(); + + std::string buttonName = "Drop entity with rigid body component here (world)"; + if (connectedEntity.IsValid()) { + buttonName = "Entity " + std::to_string(connectedEntity.GetID()); + if (connectedEntity.HasComponent()) + buttonName = connectedEntity.GetComponent().name; + } + + Widgets::DropSlot(buttonName.c_str(), !connectedEntity.IsValid()); + + bool changed = false; + if (ImGui::BeginDragDropTarget()) { + auto dropPayload = ImGui::GetDragDropPayload(); + if (dropPayload->IsDataType(typeid(Scene::Entity).name())) { + Scene::Entity dropEntity; + std::memcpy(&dropEntity, dropPayload->Data, dropPayload->DataSize); + bool validEntity = dropEntity != entity && dropEntity.HasComponent(); + + if (validEntity && ImGui::AcceptDragDropPayload(typeid(Scene::Entity).name())) { + constraintComponent.SetConnectedEntity(dropEntity); + changed = true; + } + } + + ImGui::EndDragDropTarget(); + } + + if (connectedEntity.IsValid() && ImGui::Button("Connect to world", { -FLT_MIN, 0 })) { + constraintComponent.SetConnectedEntity(Scene::Entity()); + changed = true; + } + + return changed; + + } + + bool ConstraintComponentPanel::RenderConstraintSettings(Physics::ConstraintCreationSettings& settings) { + + bool changed = false; + + if (!Widgets::BeginProperties("Constraint")) + return false; + + const char* typeItems[] = { "Fixed", "Point", "Hinge", "Slider", "Distance", "Cone" }; + int currentItem = static_cast(settings.type); + Widgets::PropertyLabel("Type"); + changed |= ImGui::Combo("##Type", ¤tItem, typeItems, IM_ARRAYSIZE(typeItems)); + settings.type = static_cast(currentItem); + + auto type = settings.type; + + // Fixed and slider constraints keep the bodies where they are when the constraint is created + if (type != ConstraintType::Fixed && type != ConstraintType::Slider) { + Widgets::PropertyLabel("Point"); + changed |= Widgets::DragVec3("##Point", settings.point, 0.01f, 0.0f, -10000.0f, 10000.0f); + } + if (type == ConstraintType::Distance) { + Widgets::PropertyLabel("Other point"); + changed |= Widgets::DragVec3("##Other point", settings.otherPoint, 0.01f, 0.0f, -10000.0f, 10000.0f); + } + if (type == ConstraintType::Hinge || type == ConstraintType::Slider || type == ConstraintType::Cone) { + Widgets::PropertyLabel("Axis"); + changed |= Widgets::DragVec3("##Axis", settings.axis, 0.01f, 0.0f, -1.0f, 1.0f); + } + + if (type == ConstraintType::Hinge || type == ConstraintType::Slider || type == ConstraintType::Distance) { + Widgets::PropertyLabel("Enable limits"); + changed |= ImGui::Checkbox("##Enable limits", &settings.enableLimits); + if (settings.enableLimits) { + if (type == ConstraintType::Hinge) { + Widgets::PropertyLabel("Limits min"); + changed |= ImGui::SliderAngle("##Limits min", &settings.limitsMin, -180.0f, 0.0f); + Widgets::PropertyLabel("Limits max"); + changed |= ImGui::SliderAngle("##Limits max", &settings.limitsMax, 0.0f, 180.0f); + } + else { + Widgets::PropertyLabel("Limits min"); + changed |= ImGui::DragFloat("##Limits min", &settings.limitsMin, 0.01f, -10000.0f, 10000.0f); + Widgets::PropertyLabel("Limits max"); + changed |= ImGui::DragFloat("##Limits max", &settings.limitsMax, 0.01f, -10000.0f, 10000.0f); + } + } + } + + if (type == ConstraintType::Cone) { + Widgets::PropertyLabel("Half cone angle"); + changed |= ImGui::SliderAngle("##Half cone angle", &settings.halfConeAngle, 0.0f, 180.0f); + } + + Widgets::PropertyLabel("Break force", "Zero never breaks"); + changed |= ImGui::DragFloat("##Break force", &settings.breakForce, 10.0f, 0.0f, 1000000.0f); + + Widgets::EndProperties(); + + return changed; + + } + +} diff --git a/src/editor/ui/panels/components/ConstraintComponentPanel.h b/src/editor/ui/panels/components/ConstraintComponentPanel.h new file mode 100644 index 000000000..b5cd080bb --- /dev/null +++ b/src/editor/ui/panels/components/ConstraintComponentPanel.h @@ -0,0 +1,25 @@ +#pragma once + +#include "../Panel.h" + +#include "scene/Scene.h" +#include "scene/Entity.h" +#include "scene/components/ConstraintComponent.h" + +namespace Atlas::Editor::UI { + + class ConstraintComponentPanel : public Panel { + + public: + ConstraintComponentPanel() : Panel("Constraint component") {} + + bool Render(Ref& scene, Scene::Entity entity, ConstraintComponent& constraintComponent); + + private: + bool RenderConnectedEntity(Scene::Entity entity, ConstraintComponent& constraintComponent); + + bool RenderConstraintSettings(Physics::ConstraintCreationSettings& settings); + + }; + +} diff --git a/src/editor/ui/panels/components/FogVolumeComponentPanel.cpp b/src/editor/ui/panels/components/FogVolumeComponentPanel.cpp new file mode 100644 index 000000000..3a0f3deba --- /dev/null +++ b/src/editor/ui/panels/components/FogVolumeComponentPanel.cpp @@ -0,0 +1,70 @@ +#include "FogVolumeComponentPanel.h" +#include "../../Widgets.h" + +#include + +namespace Atlas::Editor::UI { + + bool FogVolumeComponentPanel::Render(Ref& scene, + Scene::Entity entity, FogVolumeComponent& fogVolumeComponent) { + + if (Widgets::BeginProperties("Fog volume")) { + Widgets::PropertyLabel("Enable"); + ImGui::Checkbox("##Enable", &fogVolumeComponent.enable); + + const char* shapes[] = { "Box", "Ellipsoid" }; + auto shape = static_cast(fogVolumeComponent.shape); + Widgets::PropertyLabel("Shape"); + if (ImGui::Combo("##Shape", &shape, shapes, IM_ARRAYSIZE(shapes))) + fogVolumeComponent.shape = static_cast(shape); + + Widgets::PropertyLabel("Density"); + ImGui::DragFloat("##Density", &fogVolumeComponent.density, 0.001f, 0.0f, 10.0f, "%.4f", ImGuiSliderFlags_Logarithmic); + Widgets::PropertyLabel("Albedo", "Share of the light the volume removes which it scatters, the rest is " + "absorbed. The density decides how much it hides"); + ImGui::ColorEdit3("##Albedo", &fogVolumeComponent.albedo[0]); + Widgets::PropertyLabel("Scattering anisotropy", "Negative values scatter towards the light: bright halos around " + "the sun and light shafts. Positive values scatter back to it, 0 evenly in all directions. Same as the " + "anisotropy of the scene fog"); + ImGui::SliderFloat("##Scattering anisotropy", &fogVolumeComponent.scatteringAnisotropy, -0.99f, 0.99f, "%.2f"); + Widgets::PropertyLabel("Emissive color"); + ImGui::ColorEdit3("##Emissive color", &fogVolumeComponent.emissiveColor[0], ImGuiColorEditFlags_HDR); + Widgets::PropertyLabel("Ambient factor"); + ImGui::DragFloat("##Ambient factor", &fogVolumeComponent.ambientFactor, 0.005f, 0.0f, 10.0f); + + Widgets::PropertyLabel("Self shadowing"); + ImGui::DragFloat("##Self shadowing", &fogVolumeComponent.selfShadowing, 0.005f, 0.0f, 4.0f); + + Widgets::PropertyLabel("Edge fade"); + ImGui::DragFloat("##Edge fade", &fogVolumeComponent.edgeFade, 0.005f, 0.0f, 1.0f); + Widgets::PropertyLabel("Height falloff"); + ImGui::DragFloat("##Height falloff", &fogVolumeComponent.heightFalloff, 0.01f, 0.0f, 20.0f); + + Widgets::PropertyLabel("Fade distance", "Zero doesn't fade the volume with distance"); + ImGui::DragFloat("##Fade distance", &fogVolumeComponent.fadeDistance, 1.0f, 0.0f, 10000.0f); + + Widgets::EndProperties(); + } + + Widgets::PropertySection("Noise"); + if (Widgets::BeginProperties("Fog volume noise")) { + Widgets::PropertyLabel("Amount"); + ImGui::DragFloat("##Amount", &fogVolumeComponent.noiseAmount, 0.005f, 0.0f, 1.0f); + Widgets::PropertyLabel("Scale"); + ImGui::DragFloat("##Scale", &fogVolumeComponent.noiseScale, 0.05f, 0.1f, 1000.0f); + Widgets::PropertyLabel("Coverage"); + ImGui::DragFloat("##Coverage", &fogVolumeComponent.noiseCoverage, 0.005f, 0.0f, 1.0f); + Widgets::PropertyLabel("Sharpness"); + ImGui::DragFloat("##Sharpness", &fogVolumeComponent.noiseSharpness, 0.005f, 0.0f, 1.0f); + Widgets::PropertyLabel("Octaves"); + ImGui::SliderInt("##Octaves", &fogVolumeComponent.noiseOctaves, 1, 5); + Widgets::PropertyLabel("Wind influence"); + ImGui::DragFloat("##Wind influence", &fogVolumeComponent.windInfluence, 0.005f, 0.0f, 2.0f); + Widgets::EndProperties(); + } + + return false; + + } + +} diff --git a/src/editor/ui/panels/components/FogVolumeComponentPanel.h b/src/editor/ui/panels/components/FogVolumeComponentPanel.h new file mode 100644 index 000000000..239834811 --- /dev/null +++ b/src/editor/ui/panels/components/FogVolumeComponentPanel.h @@ -0,0 +1,19 @@ +#pragma once + +#include "../Panel.h" + +#include "scene/Scene.h" +#include "scene/components/FogVolumeComponent.h" + +namespace Atlas::Editor::UI { + + class FogVolumeComponentPanel : public Panel { + + public: + FogVolumeComponentPanel() : Panel("Fog volume component") {} + + bool Render(Ref& scene, Scene::Entity entity, FogVolumeComponent& fogVolumeComponent); + + }; + +} diff --git a/src/editor/ui/panels/components/HierarchyComponentPanel.cpp b/src/editor/ui/panels/components/HierarchyComponentPanel.cpp index 8b0d20651..00095f26a 100644 --- a/src/editor/ui/panels/components/HierarchyComponentPanel.cpp +++ b/src/editor/ui/panels/components/HierarchyComponentPanel.cpp @@ -1,4 +1,5 @@ #include "HierarchyComponentPanel.h" +#include "../../Widgets.h" #include #include @@ -9,7 +10,12 @@ namespace Atlas::Editor::UI { Scene::Entity entity, HierarchyComponent& component) { auto childCount = int32_t(component.GetChildren().size()); - ImGui::TextDisabled("%d %s", childCount, childCount == 1 ? "child" : "children"); + if (Widgets::BeginProperties("HierarchyComponent")) { + Widgets::PropertyLabel("Children"); + ImGui::AlignTextToFramePadding(); + ImGui::Text("%d", childCount); + Widgets::EndProperties(); + } return false; diff --git a/src/editor/ui/panels/components/LightComponentPanel.cpp b/src/editor/ui/panels/components/LightComponentPanel.cpp index 6d02358df..59ea655e9 100644 --- a/src/editor/ui/panels/components/LightComponentPanel.cpp +++ b/src/editor/ui/panels/components/LightComponentPanel.cpp @@ -3,50 +3,75 @@ #include -#include - namespace Atlas::Editor::UI { bool LightComponentPanel::Render(Ref& scene, Scene::Entity entity, LightComponent &lightComponent) { - const char* typeItems[] = { "Directional", "Point", "Spot"}; - int typeItem = static_cast(lightComponent.type); - ImGui::Combo("Light type", &typeItem, typeItems, IM_ARRAYSIZE(typeItems)); - lightComponent.type = static_cast(typeItem); - - bool isStatic = lightComponent.mobility == LightMobility::StationaryLight; - ImGui::Checkbox("Static", &isStatic); - lightComponent.mobility = isStatic ? LightMobility::StationaryLight : LightMobility::MovableLight; + if (Widgets::BeginProperties("LightComponent")) { + const char* typeItems[] = { "Directional", "Point", "Spot"}; + int typeItem = static_cast(lightComponent.type); + Widgets::PropertyLabel("Light type"); + ImGui::Combo("##Light type", &typeItem, typeItems, IM_ARRAYSIZE(typeItems)); + lightComponent.type = static_cast(typeItem); + + bool isStatic = lightComponent.mobility == LightMobility::StationaryLight; + Widgets::PropertyLabel("Static"); + ImGui::Checkbox("##Static", &isStatic); + lightComponent.mobility = isStatic ? LightMobility::StationaryLight : LightMobility::MovableLight; + Widgets::EndProperties(); + } - ImGui::SeparatorText("Type properties"); + // The properties of the selected type of light + const char* typeSection = lightComponent.type == LightType::DirectionalLight ? "Directional" : + lightComponent.type == LightType::PointLight ? "Point" : "Spot"; + Widgets::PropertySection(typeSection); - if (lightComponent.type == LightType::DirectionalLight) { - ImGui::Checkbox("Main", &lightComponent.isMain); - auto& directional = lightComponent.properties.directional; - Widgets::DragVec3("Direction", directional.direction, 0.005f, 0.0f, -1.0f, 1.0f); - } - else if (lightComponent.type == LightType::PointLight) { - auto& point = lightComponent.properties.point; - Widgets::DragVec3("Position", point.position, 0.1f, 0.0f, -10000.0f, 10000.0f); - ImGui::DragFloat("Radius", &point.radius, 0.01f, 0.01f, 10000.0f); - } - else if (lightComponent.type == LightType::SpotLight) { - auto& spot = lightComponent.properties.spot; - Widgets::DragVec3("Position", spot.position, 0.1f, 0.0f, -10000.0f, 10000.0f); - Widgets::DragVec3("Direction", spot.direction, 0.01f, 0.0f, -1.0f, 1.0f); - ImGui::DragFloat("Radius", &spot.radius, 0.01f, 0.01f, 10000.0f); - ImGui::DragFloat("Inner cone angle", &spot.innerConeAngle, 0.01f, 0.01f, 2.0f); - ImGui::DragFloat("Outer cone angle", &spot.outerConeAngle, 0.01f, 0.01f, 2.0f); + if (Widgets::BeginProperties("LightType")) { + if (lightComponent.type == LightType::DirectionalLight) { + Widgets::PropertyLabel("Main"); + ImGui::Checkbox("##Main", &lightComponent.isMain); + auto& directional = lightComponent.properties.directional; + Widgets::PropertyLabel("Direction"); + Widgets::DragVec3("##Direction", directional.direction, 0.005f, 0.0f, -1.0f, 1.0f); + } + else if (lightComponent.type == LightType::PointLight) { + auto& point = lightComponent.properties.point; + Widgets::PropertyLabel("Position"); + Widgets::DragVec3("##Position", point.position, 0.1f, 0.0f, -10000.0f, 10000.0f); + Widgets::PropertyLabel("Radius"); + ImGui::DragFloat("##Radius", &point.radius, 0.01f, 0.01f, 10000.0f); + } + else if (lightComponent.type == LightType::SpotLight) { + auto& spot = lightComponent.properties.spot; + Widgets::PropertyLabel("Position"); + Widgets::DragVec3("##Position", spot.position, 0.1f, 0.0f, -10000.0f, 10000.0f); + Widgets::PropertyLabel("Direction"); + Widgets::DragVec3("##Direction", spot.direction, 0.01f, 0.0f, -1.0f, 1.0f); + Widgets::PropertyLabel("Radius"); + ImGui::DragFloat("##Radius", &spot.radius, 0.01f, 0.01f, 10000.0f); + Widgets::PropertyLabel("Inner cone angle"); + ImGui::DragFloat("##Inner cone angle", &spot.innerConeAngle, 0.01f, 0.01f, 2.0f); + Widgets::PropertyLabel("Outer cone angle"); + ImGui::DragFloat("##Outer cone angle", &spot.outerConeAngle, 0.01f, 0.01f, 2.0f); + } + Widgets::EndProperties(); } - ImGui::SeparatorText("General properties"); + Widgets::PropertySection("General"); bool castShadow = lightComponent.shadow != nullptr; - ImGui::Checkbox("Shadow", &castShadow); - ImGui::ColorEdit3("Color", &lightComponent.color[0]); - ImGui::DragFloat("Intensity", &lightComponent.intensity, 0.1f, 0.0f, 1000.0f); - ImGui::DragFloat("Volumetric intensity", &lightComponent.volumetricIntensity, 0.1f, 0.0f, 10.0f); + if (Widgets::BeginProperties("LightGeneral")) { + Widgets::PropertyLabel("Shadow"); + ImGui::Checkbox("##Shadow", &castShadow); + Widgets::PropertyLabel("Color"); + ImGui::ColorEdit3("##Color", &lightComponent.color[0]); + Widgets::PropertyLabel("Intensity"); + ImGui::DragFloat("##Intensity", &lightComponent.intensity, 0.1f, 0.0f, 1000.0f); + Widgets::PropertyLabel("Volumetric intensity"); + ImGui::DragFloat("##Volumetric intensity", &lightComponent.volumetricIntensity, 0.1f, 0.0f, 10.0f); + Widgets::EndProperties(); + } if (!lightComponent.shadow && castShadow) { if (lightComponent.type == LightType::DirectionalLight) { @@ -67,7 +92,7 @@ namespace Atlas::Editor::UI { auto& shadow = lightComponent.shadow; - ImGui::SeparatorText("Shadow"); + Widgets::PropertySection("Shadow"); const char* shadowResItems[] = { "512x512", "1024x1024", "2048x2048", "4096x4096", "8192x8192" }; int shadowResItem = 0; @@ -77,7 +102,18 @@ namespace Atlas::Editor::UI { if (shadow->resolution == 4096) shadowResItem = 3; if (shadow->resolution == 8192) shadowResItem = 4; auto prevItem = shadowResItem; - ImGui::Combo("Resolution", &shadowResItem, shadowResItems, IM_ARRAYSIZE(shadowResItems)); + + if (Widgets::BeginProperties("LightShadow")) { + Widgets::PropertyLabel("Resolution"); + ImGui::Combo("##Resolution", &shadowResItem, shadowResItems, IM_ARRAYSIZE(shadowResItems)); + Widgets::PropertyLabel("Bias"); + ImGui::DragFloat("##Bias", &shadow->bias, 0.05f, 0.0f, 10.0f); + Widgets::PropertyLabel("Distance"); + ImGui::DragFloat("##Distance", &shadow->distance, 1.0f, 0.0f, 10000.0f); + Widgets::PropertyLabel("Edge softness"); + ImGui::DragFloat("##Edge softness", &shadow->edgeSoftness, 0.005f, 0.0f, 1.0f); + Widgets::EndProperties(); + } if (shadowResItem != prevItem) { switch (shadowResItem) { @@ -89,55 +125,41 @@ namespace Atlas::Editor::UI { } } - ImGui::DragFloat("Bias", &shadow->bias, 0.05f, 0.0f, 10.0f); - ImGui::DragFloat("Distance", &shadow->distance, 1.0f, 0.0f, 10000.0f); - ImGui::DragFloat("Edge softness", &shadow->edgeSoftness, 0.005f, 0.0f, 1.0f); - - ImGui::Separator(); - if (lightComponent.type == LightType::DirectionalLight) { - ImGui::Checkbox("Is cascaded", &shadow->isCascaded); - - if (!shadow->isCascaded) { - ImGui::Checkbox("Follow main camera", &shadow->followMainCamera); - - if (!shadow->followMainCamera) { - Widgets::DragVec3("Center point", shadow->center, 0.5f, 0.0f, -10000.0f, 10000.0f); - } - - auto orthoSize = shadow->views.front().orthoSize; - if (orthoSize.x == 0.0f && orthoSize.y == 0.0f) - orthoSize = vec4(-100.0f, 100.0f, -100.0f, 100.0f); - - ImGui::Text("Width"); - ImGui::DragFloat("Min##Width", &orthoSize.x, 1.0f, -10000.0f, 10000.0f); - ImGui::DragFloat("Max##Width", &orthoSize.y, 1.0f, -10000.0f, 10000.0f); - - ImGui::Text("Height"); - ImGui::DragFloat("Min##Height", &orthoSize.z, 1.0f, -10000.0f, 10000.0f); - ImGui::DragFloat("Max##Height", &orthoSize.w, 1.0f, -10000.0f, 10000.0f); - - auto matrix = glm::ortho(-200.0f, 200.0f, -200.0f, 200.0f, -120.0f, 120.0f); - lightComponent.AddDirectionalShadow(shadow->distance, shadow->bias, shadow->resolution, - shadow->edgeSoftness, shadow->center, orthoSize); + Widgets::PropertySection("Cascades"); + + // The split correction and the long range distance are read every frame, a different number of cascades + // needs new maps. Long range takes one of the views + auto cascadeCount = shadow->viewCount - (shadow->longRange ? 1 : 0); + auto longRange = shadow->longRange; + if (Widgets::BeginProperties("LightShadowCascaded")) { + Widgets::PropertyLabel("Count", "Cascades split the shadow distance, more of them give sharper " + "shadows close to the camera"); + ImGui::SliderInt("##Cascade count", &cascadeCount, 1, MAX_SHADOW_VIEW_COUNT - (longRange ? 1 : 0)); + Widgets::PropertyLabel("Split correction", "0 splits the distance evenly, 1 gives the close cascades less of it"); + ImGui::DragFloat("##Split correction", &shadow->splitCorrection, 0.01f, 0.0f, 1.0f); + Widgets::PropertyLabel("Long range", "One more cascade with a coarse shadow far beyond the distance"); + ImGui::Checkbox("##Long range", &longRange); + ImGui::BeginDisabled(!longRange); + Widgets::PropertyLabel("Long range distance"); + if (ImGui::DragFloat("##Long range distance", &shadow->longRangeDistance, 10.0f, 10.0f, 10000.0f) && + shadow->longRange) + shadow->views.back().farDistance = shadow->longRangeDistance; + ImGui::EndDisabled(); + Widgets::EndProperties(); } - else { - ImGui::SliderInt("Cascade count", &shadow->viewCount, 1, 5); - ImGui::DragFloat("Split correction", &shadow->splitCorrection, 0.01f, 0.0f, 1.0f); - ImGui::Checkbox("Long range", &shadow->longRange); - ImGui::DragFloat("Long range distance", &shadow->longRangeDistance, 10.0f, 10.0f, 10000.0f); - - lightComponent.AddDirectionalShadow(shadow->distance, shadow->bias, shadow->resolution, shadow->edgeSoftness, - shadow->viewCount, shadow->splitCorrection, shadow->longRange, shadow->longRangeDistance); - } - } - else if (lightComponent.type == LightType::PointLight) { - + cascadeCount = std::min(cascadeCount, MAX_SHADOW_VIEW_COUNT - (longRange ? 1 : 0)); + if (cascadeCount != shadow->viewCount - (shadow->longRange ? 1 : 0) || longRange != shadow->longRange) { + auto previous = shadow; + lightComponent.AddDirectionalShadow(previous->distance, previous->bias, previous->resolution, previous->edgeSoftness, + cascadeCount + (longRange ? 1 : 0), previous->splitCorrection, longRange, previous->longRangeDistance); + shadow->longRangeDistance = previous->longRangeDistance; + shadow->allowTerrain = previous->allowTerrain; + shadow->allowDynamicEntities = previous->allowDynamicEntities; + shadow->cascadeBlendDistance = previous->cascadeBlendDistance; + } } - - - } return false; diff --git a/src/editor/ui/panels/components/LuaScriptComponentPanel.cpp b/src/editor/ui/panels/components/LuaScriptComponentPanel.cpp index dfbcfc72b..b960ac9b6 100644 --- a/src/editor/ui/panels/components/LuaScriptComponentPanel.cpp +++ b/src/editor/ui/panels/components/LuaScriptComponentPanel.cpp @@ -35,41 +35,50 @@ namespace Atlas::Editor::UI if (!luaScriptComponent.script.IsLoaded()) return false; - ImGui::Checkbox("Permanent execution", &luaScriptComponent.permanentExecution); + if (Widgets::BeginProperties("LuaScriptComponent")) { + Widgets::PropertyLabel("Permanent execution"); + ImGui::Checkbox("##Permanent execution", &luaScriptComponent.permanentExecution); + Widgets::EndProperties(); + } // The code is read-only here and can be long, so it is collapsed by default if (ImGui::TreeNodeEx("Source code", ImGuiTreeNodeFlags_SpanAvailWidth)) { - ImGui::InputTextMultiline("##Code", &luaScriptComponent.script->code, - ImVec2(-FLT_MIN, ImGui::GetTextLineHeight() * 12.0f), ImGuiInputTextFlags_ReadOnly); + Widgets::TextArea("Source code", luaScriptComponent.script->code, 18.0f, ImGuiInputTextFlags_ReadOnly); ImGui::TreePop(); } - ImGui::SeparatorText("Properties"); + Widgets::PropertySection("Properties"); if (luaScriptComponent.properties.empty()) - ImGui::TextDisabled("This script doesn't define any properties"); - for (auto& [name, property] : luaScriptComponent.properties) { - switch (property.type) { - case LuaScriptComponent::PropertyType::Boolean: - ImGui::Checkbox(name.c_str(), &property.booleanValue); - break; - case LuaScriptComponent::PropertyType::Integer: - ImGui::InputInt(name.c_str(), &property.integerValue); - break; - case LuaScriptComponent::PropertyType::Double: - ImGui::InputDouble(name.c_str(), &property.doubleValue); - break; - case LuaScriptComponent::PropertyType::String: - ImGui::InputText(name.c_str(), &property.stringValue); - break; - case LuaScriptComponent::PropertyType::Vec2: - ImGui::DragFloat2(name.c_str(), glm::value_ptr(property.vec2Value)); - break; - case LuaScriptComponent::PropertyType::Vec3: - Widgets::DragVec3(name.c_str(), property.vec3Value, 1.0f, 0.0f); - break; - case LuaScriptComponent::PropertyType::Undefined: - default: - break; + Widgets::EmptyState("No properties defined"); + else if (Widgets::BeginProperties("LuaScriptProperties")) { + for (auto& [name, property] : luaScriptComponent.properties) { + ImGui::PushID(name.c_str()); + Widgets::PropertyLabel(name.c_str()); + switch (property.type) { + case LuaScriptComponent::PropertyType::Boolean: + ImGui::Checkbox("##Value", &property.booleanValue); + break; + case LuaScriptComponent::PropertyType::Integer: + ImGui::InputInt("##Value", &property.integerValue); + break; + case LuaScriptComponent::PropertyType::Double: + ImGui::InputDouble("##Value", &property.doubleValue); + break; + case LuaScriptComponent::PropertyType::String: + ImGui::InputText("##Value", &property.stringValue); + break; + case LuaScriptComponent::PropertyType::Vec2: + ImGui::DragFloat2("##Value", glm::value_ptr(property.vec2Value)); + break; + case LuaScriptComponent::PropertyType::Vec3: + Widgets::DragVec3("##Value", property.vec3Value, 1.0f, 0.0f); + break; + case LuaScriptComponent::PropertyType::Undefined: + default: + break; + } + ImGui::PopID(); } + Widgets::EndProperties(); } return false; diff --git a/src/editor/ui/panels/components/MeshComponentPanel.cpp b/src/editor/ui/panels/components/MeshComponentPanel.cpp index 3f1d3e2d2..3670d70b8 100644 --- a/src/editor/ui/panels/components/MeshComponentPanel.cpp +++ b/src/editor/ui/panels/components/MeshComponentPanel.cpp @@ -1,7 +1,9 @@ #include "MeshComponentPanel.h" +#include "../../Widgets.h" #include "../../../Singletons.h" #include "../../../tools/ResourcePayloadHelper.h" +#include "../../../Notifications.h" #include #include @@ -12,92 +14,211 @@ namespace Atlas::Editor::UI { Scene::Entity entity, MeshComponent &meshComponent) { bool resourceChanged = false; - meshComponent.mesh = meshSelectionPanel.Render(meshComponent.mesh, resourceChanged); - - ImGui::Checkbox("Visible", &meshComponent.visible); - ImGui::Checkbox("Don't cull", &meshComponent.dontCull); + auto handle = meshSelectionPanel.Render(meshComponent.mesh, resourceChanged); + if (resourceChanged) + meshComponent.ChangeResource(handle); + + if (Widgets::BeginProperties("MeshComponentVisibility")) { + auto visible = meshComponent.visible; + Widgets::PropertyLabel("Visible"); + if (ImGui::Checkbox("##Visible", &visible)) + meshComponent.SetVisible(visible); + auto dontCull = meshComponent.dontCull; + Widgets::PropertyLabel("Don't cull"); + if (ImGui::Checkbox("##Don't cull", &dontCull)) + meshComponent.SetDontCull(dontCull); + Widgets::EndProperties(); + } if (meshComponent.mesh.IsLoaded()) { auto& mesh = meshComponent.mesh; { - ImGui::SeparatorText("Mesh settings"); + Widgets::PropertySection("Rendering"); + + if (Widgets::BeginProperties("MeshRendering")) { + const char* mobilityItems[] = { "Stationary", "Movable" }; + int mobilityItem = static_cast(mesh->mobility); + Widgets::PropertyLabel("Mobility"); + ImGui::Combo("##Mobility", &mobilityItem, mobilityItems, IM_ARRAYSIZE(mobilityItems)); + mesh->mobility = static_cast(mobilityItem); + + Widgets::PropertyLabel("Invert UVs"); + ImGui::Checkbox("##Invert UVs", &mesh->invertUVs); + Widgets::PropertyLabel("Cull backfaces"); + // Both are part of the pipelines + if (ImGui::Checkbox("##Cull backfaces", &mesh->cullBackFaces)) + mesh->UpdatePipelines(); + Widgets::PropertyLabel("Ray trace"); + ImGui::Checkbox("##Ray trace", &mesh->rayTrace); + Widgets::PropertyLabel("Is vegetation"); + if (ImGui::Checkbox("##Is vegetation", &mesh->vegetation)) + mesh->UpdatePipelines(); + + Widgets::PropertyLabel("Cast shadow"); + ImGui::Checkbox("##Cast shadow", &mesh->castShadow); + Widgets::PropertyLabel("Shadow cascades"); + ImGui::SliderInt("##Shadow cascades", &mesh->allowedShadowCascades, 1, 6); + Widgets::EndProperties(); + } - const char* mobilityItems[] = { "Stationary", "Movable" }; - int mobilityItem = static_cast(mesh->mobility); - ImGui::Combo("Mobility", &mobilityItem, mobilityItems, IM_ARRAYSIZE(mobilityItems)); - mesh->mobility = static_cast(mobilityItem); + if (Widgets::BeginPropertyBlock("Invert normals")) { + if (ImGui::Button("Invert normals", ImVec2(-FLT_MIN, 0.0f))) + mesh->InvertNormals(); + Widgets::EndPropertyBlock(); + } + } - ImGui::Checkbox("Invert UVs", &mesh->invertUVs); - ImGui::Checkbox("Cull backfaces", &mesh->cullBackFaces); - ImGui::Checkbox("Ray trace", &mesh->rayTrace); - ImGui::Checkbox("Is vegetation", &mesh->vegetation); + { + Widgets::PropertySection("Culling"); + if (Widgets::BeginProperties("MeshCulling")) { + Widgets::PropertyLabel("Distance culling"); + ImGui::DragFloat("##Distance culling", &mesh->distanceCulling, 1.0f); + Widgets::PropertyLabel("Shadow distance culling"); + ImGui::DragFloat("##Shadow distance culling", &mesh->shadowDistanceCulling, 1.0f); + Widgets::PropertyLabel("Ray trace distance culling"); + ImGui::DragFloat("##Ray trace distance culling", &mesh->rayTraceDistanceCulling, 1.0f); + Widgets::PropertyLabel("Minimum screen size (px)"); + ImGui::DragFloat("##Minimum screen size (px)", &mesh->minScreenSize, 0.1f, 0.0f, 64.0f); + Widgets::EndProperties(); + } + } - ImGui::Checkbox("Cast shadow", &mesh->castShadow); - ImGui::SliderInt("Shadow cascades", &mesh->allowedShadowCascades, 1, 6); + { + Widgets::PropertySection("Levels of detail"); + if (Widgets::BeginProperties("MeshLods")) { + Widgets::PropertyLabel("Pixel error", "Instances use the coarsest level whose error stays below this many pixels"); + ImGui::DragFloat("##Pixel error", &mesh->lodPixelError, 0.05f, 0.0f, 32.0f); + for (int32_t lod = 0; lod < mesh->data.GetLodCount(); lod++) { + size_t indexCount = 0; + for (const auto& subData : mesh->data.subData) + indexCount += subData.GetLod(lod).indicesCount; + auto label = "LOD " + std::to_string(lod); + Widgets::PropertyLabel(label.c_str()); + if (lod == 0) + ImGui::Text("%zu triangles", indexCount / 3); + else + ImGui::Text("%zu triangles, error %.4f", indexCount / 3, mesh->data.lodErrors[lod - 1]); + } + Widgets::PropertyLabel("Maximum levels", "Including the full detail level"); + ImGui::DragInt("##Maximum levels", &lodSettings.maxLodCount, 0.05f, 2, Mesh::MeshData::maxLodCount, "%d", + ImGuiSliderFlags_AlwaysClamp); + Widgets::PropertyLabel("Reduction", "Triangles of a level relative to the one before"); + ImGui::DragFloat("##Reduction", &lodSettings.reduction, 0.01f, 0.1f, 0.9f, "%.2f", ImGuiSliderFlags_AlwaysClamp); + Widgets::EndProperties(); + } - auto region = ImGui::GetContentRegionAvail(); - if (ImGui::Button("Invert normals", { region.x, 0.0 })) - mesh->InvertNormals(); + if (mesh->IsGeneratingLods()) { + ImGui::TextColored(Theme::TextMuted(), "Generating levels of detail..."); + } + else if (Widgets::BeginPropertyBlock("Generate or remove levels of detail")) { + if (ImGui::Button("Generate levels of detail", ImVec2(-FLT_MIN, 0.0f))) + mesh->GenerateLods(lodSettings); + if (mesh->data.GetLodCount() > 1 && Widgets::DangerButton("Remove levels of detail")) + mesh->ClearLods(); + Widgets::EndPropertyBlock(); + } } - { - ImGui::SeparatorText("Culling settings"); - ImGui::DragFloat("Distance culling", &mesh->distanceCulling, 1.0f); - ImGui::DragFloat("Shadow distance culling", &mesh->shadowDistanceCulling, 1.0f); - ImGui::DragFloat("Ray trace distance culling", &mesh->rayTraceDistanceCulling, 1.0f); + if (mesh->data.IsSkinned()) { + Widgets::PropertySection("Animation updates"); + if (Widgets::BeginProperties("MeshAnimation")) { + Widgets::PropertyLabel("Level of detail distance", "Beyond this distance the skeleton is updated less often"); + ImGui::DragFloat("##Level of detail distance", &mesh->animationLodDistance, 1.0f, 0.0f, 500.0f); + Widgets::PropertyLabel("Maximum frames between updates", "How many frames distant meshes skip at most"); + ImGui::SliderInt("##Maximum frames between updates", &mesh->animationMaxInterval, 1, 16); + Widgets::EndProperties(); + } } { - ImGui::SeparatorText("Impostor settings"); - - auto impostorFilename = mesh.GetResource()->path + ".aeimpostor"; - bool impostorEnabled = mesh->impostor.IsLoaded(); - ImGui::Checkbox("Enable", &impostorEnabled); - if (impostorEnabled && !mesh->impostor.IsLoaded()) { - - auto impostor = CreateRef(); - mesh->impostor = ResourceManager::AddResource(impostorFilename, impostor); - } - else if (!impostorEnabled && mesh->impostor.IsLoaded()) { - mesh->impostor = ResourceHandle(); + Widgets::PropertySection("Impostor"); + + if (Widgets::BeginProperties("MeshImpostor")) { + auto impostorFilename = mesh.GetResource()->path + ".aeimpostor"; + bool impostorEnabled = mesh->impostor.IsLoaded(); + Widgets::PropertyLabel("Enable"); + ImGui::Checkbox("##Enable", &impostorEnabled); + if (impostorEnabled && !mesh->impostor.IsLoaded()) { + + auto impostor = CreateRef(); + mesh->impostor = ResourceManager::AddResource(impostorFilename, impostor); + } + else if (!impostorEnabled && mesh->impostor.IsLoaded()) { + mesh->impostor = ResourceHandle(); + } + + if (mesh->impostor.IsLoaded()) { + auto& impostor = mesh->impostor; + + Widgets::PropertyLabel("Resolution"); + ImGui::SliderInt("##Resolution", &impostor->resolution, 64, 1024); + Widgets::PropertyLabel("Views"); + ImGui::SliderInt("##Views", &impostor->views, 2, 32); + Widgets::PropertyLabel("Distance"); + ImGui::DragFloat("##Distance", &mesh->impostorDistance, 1.0f, 1.0f, 2000.0f); + Widgets::PropertyLabel("Shadow distance"); + ImGui::DragFloat("##Shadow distance", &mesh->impostorShadowDistance, 1.0f, 1.0f, 2000.0f); + Widgets::PropertyLabel("Mip bias"); + ImGui::DragFloat("##Mip bias", &impostor->mipBias, 0.01f, 0.0f, 1.0f); + Widgets::PropertyLabel("Cutoff"); + ImGui::SliderFloat("##Cutoff", &impostor->cutoff, 0.0, 1.0f); + Widgets::PropertyLabel("Interpolation"); + ImGui::Checkbox("##Interpolation", &impostor->interpolation); + Widgets::PropertyLabel("Pixel-depth offset"); + ImGui::Checkbox("##Pixel-depth offset", &impostor->pixelDepthOffset); + Widgets::PropertyLabel("Compress textures"); + ImGui::Checkbox("##Compress textures", &impostor->compressTextures); + } + Widgets::EndProperties(); } if (mesh->impostor.IsLoaded()) { auto& impostor = mesh->impostor; - ImGui::SliderInt("Resolution", &impostor->resolution, 64, 1024); - ImGui::SliderInt("Views", &impostor->views, 2, 32); - ImGui::DragFloat("Distance", &mesh->impostorDistance, 1.0f, 1.0f, 2000.0f); - ImGui::DragFloat("Shadow distance", &mesh->impostorShadowDistance, 1.0f, 1.0f, 2000.0f); - ImGui::DragFloat("Mip bias", &impostor->mipBias, 0.01f, 0.0f, 1.0f); - ImGui::SliderFloat("Cutoff", &impostor->cutoff, 0.0, 1.0f); - ImGui::Checkbox("Interpolation", &impostor->interpolation); - ImGui::Checkbox("Pixel-depth offset", &impostor->pixelDepthOffset); - if (ImGui::Button("Generate", ImVec2(-FLT_MIN, 0.0f))) { auto newImpostor = Atlas::Tools::ImpostorTool::GenerateImpostor( mesh, impostor->views, impostor->resolution ); - impostor.GetResource()->Swap(newImpostor); + newImpostor->cutoff = impostor->cutoff; + newImpostor->mipBias = impostor->mipBias; + newImpostor->interpolation = impostor->interpolation; + newImpostor->pixelDepthOffset = impostor->pixelDepthOffset; + newImpostor->compressTextures = impostor->compressTextures; + impostor.GetResource()->Swap(newImpostor); + Notifications::Push({ .message = "Generated the impostor of " + mesh.GetResource()->GetFileName() }); } } } - + { - ImGui::SeparatorText("Wind settings"); - ImGui::DragFloat("Noise lod", &mesh->windNoiseTextureLod, 1.0f, 0.0f, 6.0f); - ImGui::DragFloat("Bend scale", &mesh->windBendScale, 0.05f, 0.0f, 5.0f); - ImGui::DragFloat("Wiggle scale", &mesh->windWiggleScale, 0.05f, 0.0f, 5.0f); + Widgets::PropertySection("Wind"); + if (Widgets::BeginProperties("MeshWind")) { + Widgets::PropertyLabel("Noise lod"); + ImGui::DragFloat("##Noise lod", &mesh->windNoiseTextureLod, 1.0f, 0.0f, 6.0f); + Widgets::PropertyLabel("Bend scale"); + ImGui::DragFloat("##Bend scale", &mesh->windBendScale, 0.05f, 0.0f, 5.0f); + Widgets::PropertyLabel("Wiggle scale"); + ImGui::DragFloat("##Wiggle scale", &mesh->windWiggleScale, 0.05f, 0.0f, 5.0f); + Widgets::EndProperties(); + } } - ImGui::SeparatorText("Materials"); + Widgets::PropertySection("Materials"); materialsPanel.Render(Singletons::imguiWrapper, mesh->data.materials, [&](ResourceHandle material) { - return materialSelectionPanel.Render(material); + auto selected = materialSelectionPanel.Render(material); + if (selected.IsLoaded() && selected->HasGraph()) { + ImGui::SameLine(); + ImGui::TextColored(Theme::TextMuted(), "Uses the graph %s", selected->graph.GetResource()->GetFileName().c_str()); + } + return selected; }, [&](ResourceHandle texture) { return textureSelectionPanel.Render(texture); + }, + [&](Ref& material) { + graphParametersPanel.Render(material); }); // Just update materials regardless of any change diff --git a/src/editor/ui/panels/components/MeshComponentPanel.h b/src/editor/ui/panels/components/MeshComponentPanel.h index 9c9a25427..a8544ea3a 100644 --- a/src/editor/ui/panels/components/MeshComponentPanel.h +++ b/src/editor/ui/panels/components/MeshComponentPanel.h @@ -7,6 +7,7 @@ #include "scene/components/MeshComponent.h" #include "../ResourceSelectionPanel.h" +#include "../MaterialGraphParametersPanel.h" #include "ImguiExtension/panels/MaterialsPanel.h" namespace Atlas::Editor::UI { @@ -20,6 +21,9 @@ namespace Atlas::Editor::UI { private: ImguiExtension::MaterialsPanel materialsPanel; + MaterialGraphParametersPanel graphParametersPanel; + + Mesh::MeshLodSettings lodSettings; ResourceSelectionPanel meshSelectionPanel; ResourceSelectionPanel materialSelectionPanel; diff --git a/src/editor/ui/panels/components/PlayerComponentPanel.cpp b/src/editor/ui/panels/components/PlayerComponentPanel.cpp index 78701408d..47db35461 100644 --- a/src/editor/ui/panels/components/PlayerComponentPanel.cpp +++ b/src/editor/ui/panels/components/PlayerComponentPanel.cpp @@ -14,11 +14,11 @@ namespace Atlas::Editor::UI { if (!entity.HasComponent()) Widgets::Callout("Player component needs a transform component to work properly", Theme::Warning()); - ImGui::SeparatorText("Shape"); + Widgets::PropertySection("Shape"); RenderShapeSettings(entity, playerComponent, *playerComponent.creationSettings); - ImGui::SeparatorText("Player"); + Widgets::PropertySection("Player"); RenderPlayerSettings(entity, playerComponent); @@ -40,16 +40,22 @@ namespace Atlas::Editor::UI { auto capsuleSettings = static_cast(shape->settings.get()); - ImGui::DragFloat("Radius", &capsuleSettings->radius, 0.1f, 0.01f, 100.0f); - ImGui::DragFloat("Height", &capsuleSettings->height, 0.1f, 0.01f, 100.0f); - if (transformComponent) capsuleSettings->scale = transformComponent->Decompose().scale; - Widgets::DragVec3("Scale", capsuleSettings->scale, 0.01f, 1.0f); + + if (Widgets::BeginProperties("PlayerShape")) { + Widgets::PropertyLabel("Radius"); + ImGui::DragFloat("##Radius", &capsuleSettings->radius, 0.1f, 0.01f, 100.0f); + Widgets::PropertyLabel("Height"); + ImGui::DragFloat("##Height", &capsuleSettings->height, 0.1f, 0.01f, 100.0f); + Widgets::PropertyLabel("Scale"); + Widgets::DragVec3("##Scale", capsuleSettings->scale, 0.01f, 1.0f); + Widgets::EndProperties(); + } if (ImGui::Button("Generate shape", { -FLT_MIN, 0 })) { if (!shape->TryCreate()) { - Notifications::Push({ .message = "Error creating player shape", .color = vec3(1.0f, 0.0f, 0.0f) }); + Notifications::Push({ .message = "Error creating player shape", .type = NotificationType::Error }); } else { playerComponent.SetShape(shape); @@ -60,20 +66,51 @@ namespace Atlas::Editor::UI { void PlayerComponentPanel::RenderPlayerSettings(Scene::Entity, PlayerComponent& player) { - ImGui::DragFloat("Mass", &player.creationSettings->mass, 0.5f, 1.0f, 1000.0f); - ImGui::DragFloat("Max strength", &player.creationSettings->maxStrength, 0.5f, 1.0f, 1000.0f); - - ImGui::SeparatorText("Movement"); + if (Widgets::BeginProperties("PlayerGeneral")) { + Widgets::PropertyLabel("Mass"); + ImGui::DragFloat("##Mass", &player.creationSettings->mass, 0.5f, 1.0f, 1000.0f); + Widgets::PropertyLabel("Max strength"); + ImGui::DragFloat("##Max strength", &player.creationSettings->maxStrength, 0.5f, 1.0f, 1000.0f); + Widgets::PropertyLabel("Can push bodies"); + ImGui::Checkbox("##Can push bodies", &player.creationSettings->canPushBodies); + Widgets::EndProperties(); + } - ImGui::DragFloat("Slow movement velocity", &player.slowVelocity, 0.1f, 0.0f, 100.0f); - ImGui::DragFloat("Fast movement velocity", &player.fastVelocity, 0.1f, 0.0f, 100.0f); - ImGui::DragFloat("Jump velocity", &player.jumpVelocity, 0.1f, 0.0f, 100.0f); + Widgets::PropertySection("Movement"); + + if (Widgets::BeginProperties("PlayerMovement")) { + Widgets::PropertyLabel("Slow movement velocity"); + ImGui::DragFloat("##Slow movement velocity", &player.slowVelocity, 0.1f, 0.0f, 100.0f); + Widgets::PropertyLabel("Fast movement velocity"); + ImGui::DragFloat("##Fast movement velocity", &player.fastVelocity, 0.1f, 0.0f, 100.0f); + Widgets::PropertyLabel("Jump velocity"); + ImGui::DragFloat("##Jump velocity", &player.jumpVelocity, 0.1f, 0.0f, 100.0f); + Widgets::PropertyLabel("Acceleration"); + ImGui::DragFloat("##Acceleration", &player.acceleration, 0.5f, 0.0f, 200.0f); + Widgets::PropertyLabel("Deceleration"); + ImGui::DragFloat("##Deceleration", &player.deceleration, 0.5f, 0.0f, 200.0f); + Widgets::EndProperties(); + } ImGui::Separator(); - ImGui::DragFloat("Stick to ground distance", &player.stickToGroundDistance, 0.01f, 0.0f, 10.0f); - ImGui::DragFloat("Step up distance", &player.walkStairStepUpDistance, 0.01f, 0.0f, 10.0f); + if (Widgets::BeginProperties("PlayerCrouch")) { + Widgets::PropertyLabel("Crouch height"); + ImGui::DragFloat("##Crouch height", &player.crouchHeight, 0.01f, 0.0f, 10.0f); + Widgets::PropertyLabel("Crouch velocity"); + ImGui::DragFloat("##Crouch velocity", &player.crouchVelocity, 0.1f, 0.0f, 100.0f); + Widgets::EndProperties(); + } - ImGui::Checkbox("Allow input", &player.allowInput); + ImGui::Separator(); + if (Widgets::BeginProperties("PlayerGround")) { + Widgets::PropertyLabel("Stick to ground distance"); + ImGui::DragFloat("##Stick to ground distance", &player.stickToGroundDistance, 0.01f, 0.0f, 10.0f); + Widgets::PropertyLabel("Step up distance"); + ImGui::DragFloat("##Step up distance", &player.walkStairStepUpDistance, 0.01f, 0.0f, 10.0f); + Widgets::PropertyLabel("Allow input"); + ImGui::Checkbox("##Allow input", &player.allowInput); + Widgets::EndProperties(); + } } diff --git a/src/editor/ui/panels/components/RigidBodyComponentPanel.cpp b/src/editor/ui/panels/components/RigidBodyComponentPanel.cpp index 0e111d37b..61908e52c 100644 --- a/src/editor/ui/panels/components/RigidBodyComponentPanel.cpp +++ b/src/editor/ui/panels/components/RigidBodyComponentPanel.cpp @@ -18,11 +18,11 @@ namespace Atlas::Editor::UI { return false; } - ImGui::SeparatorText("Shape"); + Widgets::PropertySection("Shape"); RenderShapeSettings(entity, creationSettings); - ImGui::SeparatorText("Body"); + Widgets::PropertySection("Body"); RenderBodySettings(entity, creationSettings); @@ -46,18 +46,31 @@ namespace Atlas::Editor::UI { return; } - const char* typeItems[] = { "Mesh", "Sphere", "Bounding box" }; - int currentItem = static_cast(shape->type); - int previousItem = currentItem; - ImGui::Combo("Shape type", ¤tItem, typeItems, IM_ARRAYSIZE(typeItems)); - shape->type = static_cast(currentItem); + std::vector types = { ShapeType::Mesh, ShapeType::ConvexHull, ShapeType::Sphere, + ShapeType::BoundingBox, ShapeType::Capsule, ShapeType::Cylinder, ShapeType::Compound }; + + auto previousType = shape->type; + if (Widgets::BeginProperties("Shape type")) { + Widgets::PropertyLabel("Shape type"); + if (ImGui::BeginCombo("##Shape type", GetShapeTypeName(shape->type))) { + for (auto type : types) { + auto isSelected = type == shape->type; + if (ImGui::Selectable(GetShapeTypeName(type), isSelected)) + shape->type = type; + if (isSelected) + ImGui::SetItemDefaultFocus(); + } + ImGui::EndCombo(); + } + Widgets::EndProperties(); + } - bool shapeTypeChanged = currentItem != previousItem; + bool shapeTypeChanged = shape->type != previousType; auto meshComponent = entity.TryGetComponent(); auto transformComponent = entity.TryGetComponent(); - glm::vec3* scale = nullptr; + vec3* scale = nullptr; float* density = nullptr; if (shape->type == ShapeType::Mesh) { @@ -81,7 +94,11 @@ namespace Atlas::Editor::UI { auto sphereSettings = static_cast(shape->settings.get()); - ImGui::DragFloat("Radius", &sphereSettings->radius, 0.1f, 0.0f); + if (Widgets::BeginProperties("Sphere")) { + Widgets::PropertyLabel("Radius"); + ImGui::DragFloat("##Radius", &sphereSettings->radius, 0.1f, 0.0f); + Widgets::EndProperties(); + } if (meshComponent && meshComponent->mesh.IsLoaded()) if (ImGui::Button("Take radius from mesh component")) sphereSettings->radius = meshComponent->mesh->data.radius; @@ -95,8 +112,13 @@ namespace Atlas::Editor::UI { auto boundingBoxSettings = static_cast(shape->settings.get()); - Widgets::DragVec3("Min", boundingBoxSettings->aabb.min, 0.1f, 0.0f, -10000.0f, 10000.0f); - Widgets::DragVec3("Max", boundingBoxSettings->aabb.max, 0.1f, 0.0f, -10000.0f, 10000.0f); + if (Widgets::BeginProperties("Bounding box")) { + Widgets::PropertyLabel("Min"); + Widgets::DragVec3("##Min", boundingBoxSettings->aabb.min, 0.1f, 0.0f, -10000.0f, 10000.0f); + Widgets::PropertyLabel("Max"); + Widgets::DragVec3("##Max", boundingBoxSettings->aabb.max, 0.1f, 0.0f, -10000.0f, 10000.0f); + Widgets::EndProperties(); + } if (meshComponent && meshComponent->mesh.IsLoaded()) if (ImGui::Button("Take bounding box from mesh component")) boundingBoxSettings->aabb = meshComponent->mesh->data.aabb; @@ -110,24 +132,81 @@ namespace Atlas::Editor::UI { auto capsuleSettings = static_cast(shape->settings.get()); - ImGui::DragFloat("Radius", &capsuleSettings->radius, 0.1f, 0.01f, 100.0f); - ImGui::DragFloat("Height", &capsuleSettings->height, 0.1f, 0.01f, 100.0f); + if (Widgets::BeginProperties("Capsule")) { + Widgets::PropertyLabel("Radius"); + ImGui::DragFloat("##Radius", &capsuleSettings->radius, 0.1f, 0.01f, 100.0f); + Widgets::PropertyLabel("Height"); + ImGui::DragFloat("##Height", &capsuleSettings->height, 0.1f, 0.01f, 100.0f); + Widgets::EndProperties(); + } density = &capsuleSettings->density; scale = &capsuleSettings->scale; } + else if (shape->type == ShapeType::ConvexHull) { + if (shapeTypeChanged) + shape->settings = CreateRef(); + + auto convexHullSettings = static_cast(shape->settings.get()); + + bool resourceChanged = false; + convexHullSettings->mesh = meshSelectionPanel.Render(convexHullSettings->mesh, resourceChanged); + + if (meshComponent) + if (ImGui::Button("Take resource from mesh component", ImVec2(-FLT_MIN, 0.0f))) + convexHullSettings->mesh = meshComponent->mesh; + + density = &convexHullSettings->density; + scale = &convexHullSettings->scale; + } + else if (shape->type == ShapeType::Cylinder) { + if (shapeTypeChanged) + shape->settings = CreateRef(); + + auto cylinderSettings = static_cast(shape->settings.get()); + + if (Widgets::BeginProperties("Cylinder")) { + Widgets::PropertyLabel("Radius"); + ImGui::DragFloat("##Radius", &cylinderSettings->radius, 0.1f, 0.01f, 100.0f); + Widgets::PropertyLabel("Height"); + ImGui::DragFloat("##Height", &cylinderSettings->height, 0.1f, 0.01f, 100.0f); + Widgets::EndProperties(); + } + + density = &cylinderSettings->density; + scale = &cylinderSettings->scale; + } + else if (shape->type == ShapeType::Compound) { + if (shapeTypeChanged) { + auto compoundSettings = CreateRef(); + compoundSettings->children.push_back({ ShapesManager::CreateShape(BoundingBoxShapeSettings {}) }); + shape->settings = compoundSettings; + } + + auto compoundSettings = static_cast(shape->settings.get()); + + RenderCompoundSettings(*compoundSettings); + + scale = &compoundSettings->scale; + } - if (density != nullptr) { - ImGui::DragFloat("Density", density, 0.01f, 0.001f); + if (scale != nullptr && transformComponent) { + auto& globalMatrix = transformComponent->globalMatrix; + // Need scale from global matrix decomposition + *scale = Common::MatrixDecomposition(globalMatrix).scale; } - if (scale != nullptr) { - if (transformComponent) { - auto& globalMatrix = transformComponent->globalMatrix; - // Need scale from global matrix decomposition - *scale = Common::MatrixDecomposition(globalMatrix).scale; + if ((density != nullptr || scale != nullptr) && Widgets::BeginProperties("Shape scale")) { + if (density != nullptr) { + Widgets::PropertyLabel("Density"); + ImGui::DragFloat("##Density", density, 0.01f, 0.001f); + } + + if (scale != nullptr) { + Widgets::PropertyLabel("Scale"); + Widgets::DragVec3("##Scale", *scale, 0.01f, 1.0f, -100.0f, 100.0f); } - Widgets::DragVec3("Scale", *scale, 0.01f, 1.0f, -100.0f, 100.0f); + Widgets::EndProperties(); } if (ImGui::Button("Generate shape", { -FLT_MIN, 0 }) || shapeTypeChanged) @@ -141,7 +220,8 @@ namespace Atlas::Editor::UI { Physics::BodyCreationSettings &settings) { // Mesh shapes can't be simulated, but they can be moved kinematically - std::vector layers = { Physics::Layers::Static, Physics::Layers::Kinematic }; + std::vector layers = { Physics::Layers::Static, Physics::Layers::Kinematic, + Physics::Layers::ClothCollider }; if (settings.shape->type != ShapeType::Mesh) layers.insert(layers.begin() + 1, Physics::Layers::Movable); @@ -149,6 +229,7 @@ namespace Atlas::Editor::UI { switch (layer) { case Physics::Layers::Movable: return "Movable"; case Physics::Layers::Kinematic: return "Kinematic"; + case Physics::Layers::ClothCollider: return "Cloth collider"; default: return "Static"; } }; @@ -156,7 +237,11 @@ namespace Atlas::Editor::UI { if (std::find(layers.begin(), layers.end(), settings.objectLayer) == layers.end()) settings.objectLayer = Physics::Layers::Static; - if (ImGui::BeginCombo("Object layer", layerName(settings.objectLayer))) { + if (!Widgets::BeginProperties("Body")) + return; + + Widgets::PropertyLabel("Object layer"); + if (ImGui::BeginCombo("##Object layer", layerName(settings.objectLayer))) { for (auto layer : layers) { auto isSelected = layer == settings.objectLayer; if (ImGui::Selectable(layerName(layer), isSelected)) @@ -169,19 +254,168 @@ namespace Atlas::Editor::UI { const char* motionQualityItems[] = { "Discrete", "Linear cast" }; int currentItem = static_cast(settings.motionQuality); - ImGui::Combo("Motion quality", ¤tItem, motionQualityItems, IM_ARRAYSIZE(motionQualityItems)); + Widgets::PropertyLabel("Motion quality"); + ImGui::Combo("##Motion quality", ¤tItem, motionQualityItems, IM_ARRAYSIZE(motionQualityItems)); settings.motionQuality = static_cast(currentItem); - Widgets::DragVec3("Linear velocity", settings.linearVelocity, 0.1f, 0.0f, -1000.0f, 1000.0f); - Widgets::DragVec3("Angular velocity", settings.angularVelocity, 0.1f, 0.0f, -1000.0f, 1000.0f); + Widgets::PropertyLabel("Linear velocity"); + Widgets::DragVec3("##Linear velocity", settings.linearVelocity, 0.1f, 0.0f, -1000.0f, 1000.0f); + Widgets::PropertyLabel("Angular velocity"); + Widgets::DragVec3("##Angular velocity", settings.angularVelocity, 0.1f, 0.0f, -1000.0f, 1000.0f); + + Widgets::PropertyLabel("Friction"); + ImGui::DragFloat("##Friction", &settings.friction, 0.01f, -0.0f, 1.0f); + Widgets::PropertyLabel("Restitution"); + ImGui::DragFloat("##Restitution", &settings.restitution, 0.01f, -0.0f, 1.0f); + + Widgets::PropertyLabel("Linear dampening"); + ImGui::DragFloat("##Linear dampening", &settings.linearDampening, 0.01f, -0.0f, 1.0f); + Widgets::PropertyLabel("Angular dampening"); + ImGui::DragFloat("##Angular dampening", &settings.angularDampening, 0.01f, -0.0f, 1.0f); + + Widgets::PropertyLabel("Gravity factor"); + ImGui::DragFloat("##Gravity factor", &settings.gravityFactor, 0.01f, -0.0f, 1.0f); + + Widgets::PropertyLabel("Trigger", "Reports contacts to scripts without colliding"); + ImGui::Checkbox("##Trigger", &settings.isTrigger); + + if (settings.isTrigger) { + Widgets::PropertyLabel("Fluid", "Bodies with buoyancy float below the top of the trigger"); + ImGui::Checkbox("##Fluid", &settings.isFluid); + } + + if (settings.objectLayer == Physics::Layers::Movable && !settings.isTrigger) { + Widgets::PropertyLabel("Buoyancy", "Floats in fluid triggers and the ocean, 1 is neutral, lower sinks, higher floats, zero disables it"); + ImGui::DragFloat("##Buoyancy", &settings.buoyancy, 0.01f, 0.0f, 2.0f); + if (settings.buoyancy > 0.0f) { + Widgets::PropertyLabel("Fluid linear drag"); + ImGui::DragFloat("##Fluid linear drag", &settings.fluidLinearDrag, 0.01f, 0.0f, 10.0f); + Widgets::PropertyLabel("Fluid angular drag"); + ImGui::DragFloat("##Fluid angular drag", &settings.fluidAngularDrag, 0.001f, 0.0f, 10.0f); + } + } + + Widgets::EndProperties(); + + } + + void RigidBodyComponentPanel::RenderCompoundSettings(Physics::CompoundShapeSettings& compoundSettings) { + + std::vector types = { ShapeType::Sphere, ShapeType::BoundingBox, ShapeType::Capsule, ShapeType::Cylinder }; + + auto& children = compoundSettings.children; + int32_t removeIdx = -1; + + for (size_t i = 0; i < children.size(); i++) { + auto& child = children[i]; + if (!child.shape) + continue; + + ImGui::PushID(int32_t(i)); + + bool remove = false; + auto name = "Child " + std::to_string(i); + auto groupShown = Widgets::BeginPropertyGroup(name.c_str()); + if (groupShown && Widgets::RemovableSectionHeader(name.c_str(), ImGuiTreeNodeFlags_DefaultOpen | + Widgets::PropertyGroupHeaderFlags(), remove, "Remove child") && Widgets::BeginProperties("Child")) { + auto previousType = child.shape->type; + Widgets::PropertyLabel("Shape type"); + if (ImGui::BeginCombo("##Shape type", GetShapeTypeName(child.shape->type))) { + for (auto type : types) { + auto isSelected = type == child.shape->type; + if (ImGui::Selectable(GetShapeTypeName(type), isSelected)) + child.shape->type = type; + if (isSelected) + ImGui::SetItemDefaultFocus(); + } + ImGui::EndCombo(); + } + + if (child.shape->type != previousType) { + if (child.shape->type == ShapeType::Sphere) + child.shape->settings = CreateRef(); + else if (child.shape->type == ShapeType::BoundingBox) + child.shape->settings = CreateRef(); + else if (child.shape->type == ShapeType::Capsule) + child.shape->settings = CreateRef(); + else if (child.shape->type == ShapeType::Cylinder) + child.shape->settings = CreateRef(); + } + + if (child.shape->type == ShapeType::Sphere) { + auto sphereSettings = static_cast(child.shape->settings.get()); + Widgets::PropertyLabel("Radius"); + ImGui::DragFloat("##Radius", &sphereSettings->radius, 0.1f, 0.01f, 100.0f); + Widgets::PropertyLabel("Density"); + ImGui::DragFloat("##Density", &sphereSettings->density, 0.01f, 0.001f); + } + else if (child.shape->type == ShapeType::BoundingBox) { + auto boundingBoxSettings = static_cast(child.shape->settings.get()); + Widgets::PropertyLabel("Min"); + Widgets::DragVec3("##Min", boundingBoxSettings->aabb.min, 0.1f, 0.0f, -10000.0f, 10000.0f); + Widgets::PropertyLabel("Max"); + Widgets::DragVec3("##Max", boundingBoxSettings->aabb.max, 0.1f, 0.0f, -10000.0f, 10000.0f); + Widgets::PropertyLabel("Density"); + ImGui::DragFloat("##Density", &boundingBoxSettings->density, 0.01f, 0.001f); + } + else if (child.shape->type == ShapeType::Capsule) { + auto capsuleSettings = static_cast(child.shape->settings.get()); + Widgets::PropertyLabel("Radius"); + ImGui::DragFloat("##Radius", &capsuleSettings->radius, 0.1f, 0.01f, 100.0f); + Widgets::PropertyLabel("Height"); + ImGui::DragFloat("##Height", &capsuleSettings->height, 0.1f, 0.01f, 100.0f); + Widgets::PropertyLabel("Density"); + ImGui::DragFloat("##Density", &capsuleSettings->density, 0.01f, 0.001f); + } + else if (child.shape->type == ShapeType::Cylinder) { + auto cylinderSettings = static_cast(child.shape->settings.get()); + Widgets::PropertyLabel("Radius"); + ImGui::DragFloat("##Radius", &cylinderSettings->radius, 0.1f, 0.01f, 100.0f); + Widgets::PropertyLabel("Height"); + ImGui::DragFloat("##Height", &cylinderSettings->height, 0.1f, 0.01f, 100.0f); + Widgets::PropertyLabel("Density"); + ImGui::DragFloat("##Density", &cylinderSettings->density, 0.01f, 0.001f); + } + + Widgets::PropertyLabel("Translation"); + Widgets::DragVec3("##Translation", child.translation, 0.01f, 0.0f, -10000.0f, 10000.0f); + + auto rotation = glm::degrees(glm::eulerAngles(child.rotation)); + Widgets::PropertyLabel("Rotation"); + if (Widgets::DragVec3("##Rotation", rotation, 0.5f, 0.0f, -360.0f, 360.0f)) + child.rotation = quat(glm::radians(rotation)); + + Widgets::EndProperties(); + } + if (groupShown) + Widgets::EndPropertyGroup(); + if (remove) + removeIdx = int32_t(i); + + ImGui::PopID(); + } - ImGui::DragFloat("Friction", &settings.friction, 0.01f, -0.0f, 1.0f); - ImGui::DragFloat("Restitution", &settings.restitution, 0.01f, -0.0f, 1.0f); + if (removeIdx >= 0 && children.size() > 1) + children.erase(children.begin() + removeIdx); - ImGui::DragFloat("Linear dampening", &settings.linearDampening, 0.01f, -0.0f, 1.0f); - ImGui::DragFloat("Angular dampening", &settings.angularDampening, 0.01f, -0.0f, 1.0f); + if (ImGui::Button("Add child", { -FLT_MIN, 0 })) + children.push_back({ ShapesManager::CreateShape(BoundingBoxShapeSettings {}) }); - ImGui::DragFloat("Gravity factor", &settings.gravityFactor, 0.01f, -0.0f, 1.0f); + } + + const char* RigidBodyComponentPanel::GetShapeTypeName(Physics::ShapeType type) const { + + switch (type) { + case ShapeType::Mesh: return "Mesh"; + case ShapeType::Sphere: return "Sphere"; + case ShapeType::BoundingBox: return "Bounding box"; + case ShapeType::Capsule: return "Capsule"; + case ShapeType::HeightField: return "Height field"; + case ShapeType::ConvexHull: return "Convex hull"; + case ShapeType::Cylinder: return "Cylinder"; + case ShapeType::Compound: return "Compound"; + default: return "Unknown"; + } } diff --git a/src/editor/ui/panels/components/RigidBodyComponentPanel.h b/src/editor/ui/panels/components/RigidBodyComponentPanel.h index b744f20c7..2a0fa5fa2 100644 --- a/src/editor/ui/panels/components/RigidBodyComponentPanel.h +++ b/src/editor/ui/panels/components/RigidBodyComponentPanel.h @@ -22,6 +22,10 @@ namespace Atlas::Editor::UI { void RenderBodySettings(Scene::Entity entity, Physics::BodyCreationSettings& creationSettings); + void RenderCompoundSettings(Physics::CompoundShapeSettings& compoundSettings); + + const char* GetShapeTypeName(Physics::ShapeType type) const; + ResourceSelectionPanel meshSelectionPanel; }; diff --git a/src/editor/ui/panels/components/SoftBodyComponentPanel.cpp b/src/editor/ui/panels/components/SoftBodyComponentPanel.cpp new file mode 100644 index 000000000..2b057347c --- /dev/null +++ b/src/editor/ui/panels/components/SoftBodyComponentPanel.cpp @@ -0,0 +1,259 @@ +#include "SoftBodyComponentPanel.h" +#include "../../../Theme.h" +#include "../../Widgets.h" +#include "../../windows/ContentBrowserWindow.h" + +#include +#include + +#include + +namespace Atlas::Editor::UI { + + bool SoftBodyComponentPanel::Render(const Ref& scene, + Scene::Entity entity, SoftBodyComponent& softBodyComponent) { + + if (!entity.HasComponent() || !entity.HasComponent()) + Widgets::Callout("Soft body component needs a mesh and a transform component", Theme::Warning()); + + auto& settings = softBodyComponent.settings; + bool changed = false; + + if (Widgets::BeginProperties("Soft body")) { + Widgets::PropertyLabel("Simulated vertices", "The resolution of the simulation mesh is set per mesh in the mesh editor"); + ImGui::Text("%zu", softBodyComponent.GetSimulatedVertexCount()); + + Widgets::PropertyLabel("Mass", "Spread over all vertices which aren't pinned"); + changed |= ImGui::DragFloat("##Mass", &settings.mass, 0.05f, 0.001f, 10000.0f); + + Widgets::PropertyLabel("Edge compliance", "Inverse stiffness of the edges, 0 is rigid"); + changed |= ImGui::DragFloat("##Edge compliance", &settings.edgeCompliance, 0.0001f, 0.0f, 1.0f, "%.5f"); + Widgets::PropertyLabel("Shear compliance"); + changed |= ImGui::DragFloat("##Shear compliance", &settings.shearCompliance, 0.0001f, 0.0f, 1.0f, "%.5f"); + Widgets::PropertyLabel("Bend compliance"); + changed |= ImGui::DragFloat("##Bend compliance", &settings.bendCompliance, 0.0001f, 0.0f, 1.0f, "%.5f"); + + const char* bendTypes[] = { "None", "Distance", "Dihedral" }; + auto bendType = int32_t(settings.bendType); + Widgets::PropertyLabel("Bend type", "Dihedral is the most expensive, but also bends non-planar triangles"); + if (ImGui::Combo("##Bend type", &bendType, bendTypes, IM_ARRAYSIZE(bendTypes))) { + settings.bendType = Physics::SoftBodyBendType(bendType); + changed = true; + } + + Widgets::PropertyLabel("Pressure", "Inflates closed meshes"); + changed |= ImGui::DragFloat("##Pressure", &settings.pressure, 1.0f, 0.0f, 100000.0f); + Widgets::PropertyLabel("Iterations"); + changed |= ImGui::DragInt("##Iterations", &settings.iterations, 0.1f, 1, 64); + Widgets::PropertyLabel("Linear damping"); + changed |= ImGui::DragFloat("##Linear damping", &settings.linearDamping, 0.01f, 0.0f, 10.0f); + Widgets::PropertyLabel("Friction"); + changed |= ImGui::DragFloat("##Friction", &settings.friction, 0.01f, 0.0f, 1.0f); + Widgets::PropertyLabel("Restitution"); + changed |= ImGui::DragFloat("##Restitution", &settings.restitution, 0.01f, 0.0f, 1.0f); + Widgets::PropertyLabel("Gravity factor"); + changed |= ImGui::DragFloat("##Gravity factor", &settings.gravityFactor, 0.01f, -10.0f, 10.0f); + Widgets::PropertyLabel("Vertex radius", "Keeps the vertices a little away from other bodies"); + changed |= ImGui::DragFloat("##Vertex radius", &settings.vertexRadius, 0.001f, 0.0f, 1.0f); + Widgets::PropertyLabel("Double sided"); + changed |= ImGui::Checkbox("##Double sided", &settings.doubleSided); + Widgets::PropertyLabel("Allow sleeping"); + changed |= ImGui::Checkbox("##Allow sleeping", &settings.allowSleeping); + Widgets::PropertyLabel("Wind factor", "Share of the difference to the scene wind velocity taken on per second"); + ImGui::DragFloat("##Wind factor", &settings.windFactor, 0.01f, 0.0f, 10.0f); + Widgets::PropertyLabel("Simulation distance", "Simulated within this distance of the camera only, 0 always"); + ImGui::DragFloat("##Simulation distance", &settings.simulationDistance, 1.0f, 0.0f, 10000.0f); + + auto layerName = settings.objectLayer == Physics::Layers::Cloth ? "Cloth" : "Movable"; + Widgets::PropertyLabel("Object layer", "Cloth hangs on the static world, kinematic bodies and cloth colliders, " + "it passes simulated bodies and other cloth"); + if (ImGui::BeginCombo("##Object layer", layerName)) { + for (auto layer : { Physics::Layers::Movable, Physics::Layers::Cloth }) { + auto isSelected = layer == settings.objectLayer; + if (ImGui::Selectable(layer == Physics::Layers::Cloth ? "Cloth" : "Movable", isSelected)) { + settings.objectLayer = layer; + changed = true; + } + if (isSelected) + ImGui::SetItemDefaultFocus(); + } + ImGui::EndCombo(); + } + + Widgets::PropertyLabel("Pinned", "Vertices within the pin bounds (mesh space) follow the entity"); + changed |= ImGui::Checkbox("##Pinned", &settings.pinned); + + Widgets::EndProperties(); + } + + if (ECS::Entity(entity) != selectedPinEntity) { + selectedPin = -1; + selectedPinEntity = entity; + } + + if (settings.pinned) { + Widgets::PropertySection("Pins"); + auto meshComponent = entity.TryGetComponent(); + auto simulationMesh = meshComponent && meshComponent->mesh.IsLoaded() ? + meshComponent->mesh->GetSoftBodySimulationMesh() : nullptr; + auto& pins = settings.pinBounds; + for (int32_t i = 0; i < int32_t(pins.size()); i++) { + ImGui::PushID(i); + auto vertexCount = simulationMesh ? simulationMesh->GetVertexCount(pins[i]) : size_t(0); + auto label = "Pin bounds " + std::to_string(i) + " (" + std::to_string(vertexCount) + " vertices)"; + if (ImGui::Selectable(label.c_str(), selectedPin == i)) + selectedPin = selectedPin == i ? -1 : i; + ImGui::SetItemTooltip("The gizmo in the viewport moves and resizes the selected bounds"); + if (simulationMesh && vertexCount == 0) + ImGui::TextColored(Theme::Warning(), "No simulated vertex inside, the closest one is pinned"); + if (selectedPin == i && Widgets::BeginProperties("Pin bounds")) { + Widgets::PropertyLabel("Min"); + changed |= Widgets::DragVec3("##Min", pins[i].min, 0.005f); + Widgets::PropertyLabel("Max"); + changed |= Widgets::DragVec3("##Max", pins[i].max, 0.005f); + Widgets::EndProperties(); + } + ImGui::PopID(); + } + + // New bounds cover the top of the mesh, where banners and curtains hang + if (ImGui::Button("Add pin bounds")) { + auto aabb = meshComponent && meshComponent->mesh.IsLoaded() ? meshComponent->mesh->data.aabb : + Volume::AABB(vec3(-0.5f), vec3(0.5f)); + auto margin = 0.01f * (aabb.max - aabb.min) + vec3(0.001f); + pins.emplace_back(vec3(aabb.min.x, aabb.max.y - 0.05f * (aabb.max.y - aabb.min.y), aabb.min.z) - margin, + aabb.max + margin); + selectedPin = int32_t(pins.size()) - 1; + changed = true; + } + if (selectedPin >= 0 && selectedPin < int32_t(pins.size())) { + ImGui::SameLine(); + if (Widgets::DangerButton("Remove pin bounds")) { + pins.erase(pins.begin() + selectedPin); + selectedPin = -1; + changed = true; + } + } + } + + ImGui::Checkbox("Show simulation mesh", &showSimulationMesh); + ImGui::SetItemTooltip("The simulated vertices and edges, pinned vertices and the pin bounds in the viewport"); + + // The body is built again from the rest pose with the new settings, once a dragged value is released + pendingReset |= changed; + auto reset = ImGui::Button("Reset simulation"); + auto meshComponent = entity.TryGetComponent(); + if (meshComponent && meshComponent->mesh.IsValid()) { + ImGui::SameLine(); + if (ImGui::Button("Edit simulation mesh")) + ContentBrowserWindow::contentToEditPath = meshComponent->mesh.GetResource()->path; + ImGui::SetItemTooltip("Opens the mesh editor, the resolution of the simulation mesh is set per mesh"); + } + if (reset || (pendingReset && !ImGui::IsAnyItemActive() && !ImGuizmo::IsUsing())) { + softBodyComponent.Reset(); + pendingReset = false; + } + + return false; + + } + + void SoftBodyComponentPanel::RenderOverlay(const Ref& scene, Scene::Entity entity, + PrimitiveBatchWrapper& wrapper) { + + auto softBodyComponent = entity.TryGetComponent(); + auto pinSelected = softBodyComponent && ECS::Entity(entity) == selectedPinEntity && selectedPin >= 0; + auto meshComponent = entity.TryGetComponent(); + if ((!showSimulationMesh && !pinSelected) || !meshComponent || !meshComponent->mesh.IsLoaded()) + return; + + const auto& mesh = meshComponent->mesh; + auto simulationMesh = mesh->GetSoftBodySimulationMesh(); + if (simulationMesh != drawnSimulationMesh) { + simulationMeshEdges.clear(); + const auto& indices = simulationMesh->indices; + for (size_t i = 0; i + 2 < indices.size(); i += 3) { + for (size_t j = 0; j < 3; j++) { + auto a = indices[i + j], b = indices[i + (j + 1) % 3]; + simulationMeshEdges.emplace_back(std::min(a, b), std::max(a, b)); + } + } + std::ranges::sort(simulationMeshEdges); + auto duplicates = std::ranges::unique(simulationMeshEdges); + simulationMeshEdges.erase(duplicates.begin(), duplicates.end()); + drawnSimulationMesh = simulationMesh; + } + + // A simulating body shows its current vertices + const auto* positions = &simulationMesh->positions; + if (softBodyComponent && softBodyComponent->IsValid() && !softBodyComponent->IsOutdated(*meshComponent) && + softBodyComponent->GetSimulatedPositions().size() == positions->size()) + positions = &softBodyComponent->GetSimulatedPositions(); + + auto globalMatrix = scene->GetGlobalMatrix(entity); + auto toWorld = [&](vec3 position) { return vec3(globalMatrix * vec4(position, 1.0f)); }; + auto& batch = wrapper.GetBatch(false); + + const auto edgeColor = vec3(0.2f, 0.8f, 1.0f); + for (const auto& [a, b] : simulationMeshEdges) + batch->AddLine(toWorld((*positions)[a]), toWorld((*positions)[b]), edgeColor, edgeColor); + + if (!softBodyComponent || !softBodyComponent->settings.pinned) + return; + + const auto& pins = softBodyComponent->settings.pinBounds; + auto extent = glm::length(mesh->data.aabb.max - mesh->data.aabb.min); + for (auto vertex : simulationMesh->GetPinnedVertices(pins)) + batch->AddLineCross(toWorld((*positions)[vertex]), 0.01f * extent, vec3(1.0f, 0.6f, 0.1f)); + + for (int32_t i = 0; i < int32_t(pins.size()); i++) { + auto color = pinSelected && i == selectedPin ? vec3(1.0f, 0.6f, 0.1f) : vec3(1.0f, 1.0f, 0.3f); + batch->AddLineAABB(pins[i].Transform(globalMatrix), color); + } + + } + + bool SoftBodyComponentPanel::RenderPinGizmo(const Ref& scene, Scene::Entity entity, + const Ref& viewport, const CameraComponent& camera) { + + auto softBodyComponent = entity.TryGetComponent(); + if (!softBodyComponent || ECS::Entity(entity) != selectedPinEntity || !softBodyComponent->settings.pinned) + return false; + + auto& pins = softBodyComponent->settings.pinBounds; + if (selectedPin < 0 || selectedPin >= int32_t(pins.size())) + return false; + + ImGuizmo::SetDrawlist(); + ImGuizmo::SetRect(float(viewport->x), float(viewport->y), float(viewport->width), float(viewport->height)); + + // ImGuizmo expects an OpenGL clip space + const mat4 clip = mat4(1.0f, 0.0f, 0.0f, 0.0f, + 0.0f, -1.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 0.5f, 0.0f, + 0.0f, 0.0f, 0.5f, 1.0f); + auto viewMatrix = camera.viewMatrix; + auto projectionMatrix = glm::inverse(clip) * camera.unjitterdProjection; + + // A unit cube scaled to the bounds, the gizmo moves it and its handles resize it + auto& bounds = pins[selectedPin]; + auto globalMatrix = scene->GetGlobalMatrix(entity); + auto center = 0.5f * (bounds.min + bounds.max); + auto size = glm::max(bounds.max - bounds.min, vec3(0.0001f)); + auto matrix = globalMatrix * glm::translate(mat4(1.0f), center) * glm::scale(mat4(1.0f), size); + const float localBounds[] = { -0.5f, -0.5f, -0.5f, 0.5f, 0.5f, 0.5f }; + + if (ImGuizmo::Manipulate(glm::value_ptr(viewMatrix), glm::value_ptr(projectionMatrix), + ImGuizmo::TRANSLATE | ImGuizmo::BOUNDS, ImGuizmo::LOCAL, glm::value_ptr(matrix), nullptr, nullptr, localBounds)) { + auto local = glm::inverse(globalMatrix) * matrix; + center = vec3(local[3]); + size = vec3(glm::length(vec3(local[0])), glm::length(vec3(local[1])), glm::length(vec3(local[2]))); + bounds = Volume::AABB(center - 0.5f * size, center + 0.5f * size); + pendingReset = true; + } + + return true; + + } + +} diff --git a/src/editor/ui/panels/components/SoftBodyComponentPanel.h b/src/editor/ui/panels/components/SoftBodyComponentPanel.h new file mode 100644 index 000000000..1d30dba88 --- /dev/null +++ b/src/editor/ui/panels/components/SoftBodyComponentPanel.h @@ -0,0 +1,41 @@ +#pragma once + +#include "../Panel.h" +#include "../../../tools/PrimitiveBatchWrapper.h" + +#include "scene/Scene.h" +#include "scene/Entity.h" +#include "scene/components/SoftBodyComponent.h" +#include "Viewport.h" + +namespace Atlas::Editor::UI { + + class SoftBodyComponentPanel : public Panel { + + public: + SoftBodyComponentPanel() : Panel("Soft body component") {} + + bool Render(const Ref& scene, Scene::Entity entity, SoftBodyComponent& softBodyComponent); + + // Edges and pinned vertices of the simulation mesh of the entity with the pin bounds of its soft body + void RenderOverlay(const Ref& scene, Scene::Entity entity, PrimitiveBatchWrapper& wrapper); + + // Inside of the viewport, moves and resizes the selected pin bounds. Returns false without a selected pin + bool RenderPinGizmo(const Ref& scene, Scene::Entity entity, const Ref& viewport, + const CameraComponent& camera); + + bool showSimulationMesh = false; + + private: + // Of the entity the panel was rendered for last + int32_t selectedPin = -1; + ECS::Entity selectedPinEntity = ECS::EntityConfig::InvalidEntity; + + bool pendingReset = false; + + Ref drawnSimulationMesh; + std::vector> simulationMeshEdges; + + }; + +} diff --git a/src/editor/ui/panels/components/SplineComponentPanel.cpp b/src/editor/ui/panels/components/SplineComponentPanel.cpp index 10de555ab..72740b20b 100644 --- a/src/editor/ui/panels/components/SplineComponentPanel.cpp +++ b/src/editor/ui/panels/components/SplineComponentPanel.cpp @@ -13,30 +13,38 @@ namespace Atlas::Editor::UI { ImGui::PushID(GetNameID()); - const char* typeItems[] = { "Linear", "Catmull Rom", "Hermite" }; - auto type = static_cast(splineComponent.type); - auto prevItem = type; - ImGui::Combo("Type", &type, typeItems, IM_ARRAYSIZE(typeItems)); - splineComponent.type = static_cast(type); - - const char* bakeItems[] = { "No bake", "Equal time bake", "Distance time bake" }; - auto bakeMode = static_cast(splineComponent.bakeMode); - prevItem = bakeMode; - ImGui::Combo("Bake mode", &bakeMode, bakeItems, IM_ARRAYSIZE(bakeItems)); - splineComponent.bakeMode = static_cast(bakeMode); + if (Widgets::BeginProperties("SplineComponent")) { + const char* typeItems[] = { "Linear", "Catmull Rom", "Hermite" }; + auto type = static_cast(splineComponent.type); + Widgets::PropertyLabel("Type"); + ImGui::Combo("##Type", &type, typeItems, IM_ARRAYSIZE(typeItems)); + splineComponent.type = static_cast(type); + + const char* bakeItems[] = { "No bake", "Equal time bake", "Distance time bake" }; + auto bakeMode = static_cast(splineComponent.bakeMode); + Widgets::PropertyLabel("Bake mode"); + ImGui::Combo("##Bake mode", &bakeMode, bakeItems, IM_ARRAYSIZE(bakeItems)); + splineComponent.bakeMode = static_cast(bakeMode); + Widgets::EndProperties(); + } auto& controlPoints = splineComponent.controlPoints; - ImGui::SeparatorText("Control points"); + Widgets::PropertySection("Control points"); if (controlPoints.empty()) - ImGui::TextDisabled("No control points yet"); + Widgets::EmptyState("No control points yet"); size_t counter = 0; size_t modifyIdx = 0; ControlPointAction action = ControlPointAction::None; for (auto& controlPoint : controlPoints) { ControlPointAction currentAction = ControlPointAction::None; - RenderControlPoint(controlPoint, counter++, controlPoints.size(), currentAction); + auto name = "Control point " + std::to_string(counter); + if (Widgets::BeginPropertyGroup(name.c_str())) { + RenderControlPoint(controlPoint, name, counter, controlPoints.size(), currentAction); + Widgets::EndPropertyGroup(); + } + counter++; if (currentAction != ControlPointAction::None) { action = currentAction; @@ -78,10 +86,11 @@ namespace Atlas::Editor::UI { } - void SplineComponentPanel::RenderControlPoint(SplineControlPoint& point, size_t idx, size_t count, ControlPointAction& action) { + void SplineComponentPanel::RenderControlPoint(SplineControlPoint& point, const std::string& name, size_t idx, size_t count, + ControlPointAction& action) { ImGuiTreeNodeFlags nodeFlags = ImGuiTreeNodeFlags_SpanAvailWidth | ImGuiTreeNodeFlags_FramePadding - | ImGuiTreeNodeFlags_AllowOverlap; + | ImGuiTreeNodeFlags_AllowOverlap | Widgets::PropertyGroupHeaderFlags(); // The point picked in the viewport is highlighted if (selectControlPointIdx == int32_t(idx)) nodeFlags |= ImGuiTreeNodeFlags_Selected; @@ -91,7 +100,7 @@ namespace Atlas::Editor::UI { auto buttonExtent = iconSize + 2.0f; auto buttonsMinX = ImGui::GetCursorScreenPos().x + ImGui::GetContentRegionAvail().x - 3.0f * buttonExtent; - bool open = ImGui::TreeNodeEx(reinterpret_cast(idx), nodeFlags, "Control point %d", int32_t(idx)); + bool open = ImGui::TreeNodeEx(reinterpret_cast(idx), nodeFlags, "%s", name.c_str()); auto rowMin = ImGui::GetItemRectMin(); auto rowMax = ImGui::GetItemRectMax(); @@ -113,7 +122,7 @@ namespace Atlas::Editor::UI { ImGui::EndDisabled(); ImGui::SameLine(); - if (Widgets::IconButton("Delete button", Singletons::icons->Get(IconType::Trash), iconSize, "Delete point")) + if (Widgets::IconButton("Remove button", Singletons::icons->Get(IconType::Trash), iconSize, "Remove point")) action = ControlPointAction::Delete; ImGui::PopStyleVar(); @@ -140,16 +149,23 @@ namespace Atlas::Editor::UI { vec3 localPosition = position, localRotation = rotation, localScale = scale; - Widgets::DragVec3("Position", position, 0.01f); + if (Widgets::BeginProperties("ControlPoint")) { + Widgets::PropertyLabel("Position"); + Widgets::DragVec3("##Position", position, 0.01f); - // Rotation is stored in radians, but degrees are easier to work with - auto rotationDegrees = glm::degrees(rotation); - if (Widgets::DragVec3("Rotation", rotationDegrees, 0.5f, 0.0f, 0.0f, 0.0f, "%.2f\xc2\xb0")) - rotation = glm::radians(rotationDegrees); + // Rotation is stored in radians, but degrees are easier to work with + auto rotationDegrees = glm::degrees(rotation); + Widgets::PropertyLabel("Rotation"); + if (Widgets::DragVec3("##Rotation", rotationDegrees, 0.5f, 0.0f, 0.0f, 0.0f, "%.2f\xc2\xb0")) + rotation = glm::radians(rotationDegrees); - Widgets::DragVec3("Scale", scale, 0.01f, 1.0f, -100.0f, 100.0f); + Widgets::PropertyLabel("Scale"); + Widgets::DragVec3("##Scale", scale, 0.01f, 1.0f, -100.0f, 100.0f); - ImGui::DragFloat("Time", &point.time, 0.001f, 0.0f, 1.0f); + Widgets::PropertyLabel("Time"); + ImGui::DragFloat("##Time", &point.time, 0.001f, 0.0f, 1.0f); + Widgets::EndProperties(); + } // Only recompose when a local change happened if (localPosition != position || localScale != scale || @@ -160,7 +176,7 @@ namespace Atlas::Editor::UI { composition.scale = scale; point.transform = composition.Compose(); - point.tangent = glm::normalize(glm::vec3(point.transform * glm::vec4(0.0f, 0.0f, 1.0f, 0.0f))); + point.tangent = glm::normalize(vec3(point.transform * vec4(0.0f, 0.0f, 1.0f, 0.0f))); } ImGui::TreePop(); diff --git a/src/editor/ui/panels/components/SplineComponentPanel.h b/src/editor/ui/panels/components/SplineComponentPanel.h index 553aaca48..c133ec517 100644 --- a/src/editor/ui/panels/components/SplineComponentPanel.h +++ b/src/editor/ui/panels/components/SplineComponentPanel.h @@ -25,7 +25,8 @@ namespace Atlas::Editor::UI { MoveDown }; - void RenderControlPoint(SplineControlPoint& point, size_t idx, size_t count, ControlPointAction& action); + void RenderControlPoint(SplineControlPoint& point, const std::string& name, size_t idx, size_t count, + ControlPointAction& action); }; diff --git a/src/editor/ui/panels/components/TextComponentPanel.cpp b/src/editor/ui/panels/components/TextComponentPanel.cpp index 4e7ba15ba..e036db5d3 100644 --- a/src/editor/ui/panels/components/TextComponentPanel.cpp +++ b/src/editor/ui/panels/components/TextComponentPanel.cpp @@ -21,20 +21,31 @@ namespace Atlas::Editor::UI { textComponent.ChangeResource(handle); } - ImGui::InputTextMultiline("##Text", &textComponent.text, - ImVec2(-FLT_MIN, ImGui::GetTextLineHeight() * 4.0f + ImGui::GetStyle().FramePadding.y * 2.0f)); + Widgets::TextArea("Text", textComponent.text, 7.0f); - ImGui::SeparatorText("Layout"); + Widgets::PropertySection("Layout"); - Widgets::DragVec3("Position", textComponent.position, 0.1f, 0.0f); - ImGui::DragFloat2("Half size", glm::value_ptr(textComponent.halfSize), 0.1f); - - ImGui::SeparatorText("Style"); + if (Widgets::BeginProperties("TextLayout")) { + Widgets::PropertyLabel("Position"); + Widgets::DragVec3("##Position", textComponent.position, 0.1f, 0.0f); + Widgets::PropertyLabel("Half size"); + ImGui::DragFloat2("##Half size", glm::value_ptr(textComponent.halfSize), 0.1f); + Widgets::EndProperties(); + } - ImGui::DragFloat("Scale", &textComponent.textScale, 0.01f, 0.0f, 100.0f); - ImGui::ColorEdit4("Color", glm::value_ptr(textComponent.textColor)); - ImGui::ColorEdit4("Outline color", glm::value_ptr(textComponent.outlineColor)); - ImGui::DragFloat("Outline factor", &textComponent.outlineFactor, 0.01f, 0.0f, 1.0f); + Widgets::PropertySection("Style"); + + if (Widgets::BeginProperties("TextStyle")) { + Widgets::PropertyLabel("Scale"); + ImGui::DragFloat("##Scale", &textComponent.textScale, 0.01f, 0.0f, 100.0f); + Widgets::PropertyLabel("Color"); + ImGui::ColorEdit4("##Color", glm::value_ptr(textComponent.textColor)); + Widgets::PropertyLabel("Outline color"); + ImGui::ColorEdit4("##Outline color", glm::value_ptr(textComponent.outlineColor)); + Widgets::PropertyLabel("Outline factor"); + ImGui::DragFloat("##Outline factor", &textComponent.outlineFactor, 0.01f, 0.0f, 1.0f); + Widgets::EndProperties(); + } ImGui::PopID(); diff --git a/src/editor/ui/panels/components/TransformComponentPanel.cpp b/src/editor/ui/panels/components/TransformComponentPanel.cpp index 62a4d8b7e..ea14a7e44 100644 --- a/src/editor/ui/panels/components/TransformComponentPanel.cpp +++ b/src/editor/ui/panels/components/TransformComponentPanel.cpp @@ -1,6 +1,9 @@ #include "TransformComponentPanel.h" #include "../../Widgets.h" +#include "scene/components/MeshComponent.h" +#include "scene/components/AnimationComponent.h" + #include #include @@ -12,9 +15,17 @@ namespace Atlas::Editor::UI { ImGui::PushID(GetNameID()); // Make sure the local matrix is updated from the global one - // This needs to happen when external system like physics just updated the globalMatrix + // This needs to happen when external system like physics just updated the globalMatrix. + // Otherwise the local matrix stays, rebuilding it each frame would add up rounding errors auto parentEntity = scene->GetParentEntity(entity); - transform.ReconstructLocalMatrix(parentEntity); + auto localMatrix = transform.GetReconstructedLocalMatrix(parentEntity); + for (int32_t i = 0; i < 4; i++) { + auto tolerance = 1e-5f * glm::max(vec4(1.0f), glm::abs(transform.matrix[i])); + if (glm::any(glm::greaterThan(glm::abs(localMatrix[i] - transform.matrix[i]), tolerance))) { + transform.Set(localMatrix); + break; + } + } // The matrix decomposition/composition code is a bit unstable and // we work with fixed information that is recomposed when changed, @@ -30,14 +41,47 @@ namespace Atlas::Editor::UI { vec3 localPosition = position, localRotation = rotation, localScale = scale; - Widgets::DragVec3("Position", position, 0.01f); + if (Widgets::BeginProperties("TransformComponent")) { + Widgets::PropertyLabel("Position"); + Widgets::DragVec3("##Position", position, 0.01f); + + // Rotation is stored in radians, but degrees are easier to work with + auto rotationDegrees = glm::degrees(rotation); + Widgets::PropertyLabel("Rotation"); + if (Widgets::DragVec3("##Rotation", rotationDegrees, 0.5f, 0.0f, 0.0f, 0.0f, "%.2f\xc2\xb0")) + rotation = glm::radians(rotationDegrees); - // Rotation is stored in radians, but degrees are easier to work with - auto rotationDegrees = glm::degrees(rotation); - if (Widgets::DragVec3("Rotation", rotationDegrees, 0.5f, 0.0f, 0.0f, 0.0f, "%.2f\xc2\xb0")) - rotation = glm::radians(rotationDegrees); + Widgets::PropertyLabel("Scale"); + Widgets::DragVec3("##Scale", scale, 0.01f, 1.0f, -100.0f, 100.0f); - Widgets::DragVec3("Scale", scale, 0.01f, 1.0f, -100.0f, 100.0f); + // Entities below an animated mesh can follow one of its joints, they keep their position when it changes + auto parentAnimationComponent = parentEntity.IsValid() ? parentEntity.TryGetComponent() : nullptr; + auto parentMeshComponent = parentEntity.IsValid() ? parentEntity.TryGetComponent() : nullptr; + if (parentAnimationComponent && parentMeshComponent && parentMeshComponent->mesh.IsLoaded() && + parentMeshComponent->mesh->data.IsSkinned()) { + const auto& joints = parentMeshComponent->mesh->data.skeleton.joints; + auto jointName = transform.parentJoint >= 0 && transform.parentJoint < int32_t(joints.size()) ? + joints[transform.parentJoint].name : std::string("None"); + + Widgets::PropertyLabel("Parent joint"); + if (ImGui::BeginCombo("##Parent joint", jointName.c_str())) { + if (ImGui::Selectable("None", transform.parentJoint < 0)) { + transform.parentJoint = -1; + transform.ReconstructLocalMatrix(parentEntity); + } + for (int32_t i = 0; i < int32_t(joints.size()); i++) { + ImGui::PushID(i); + if (ImGui::Selectable(joints[i].name.c_str(), transform.parentJoint == i)) { + transform.parentJoint = i; + transform.ReconstructLocalMatrix(parentEntity); + } + ImGui::PopID(); + } + ImGui::EndCombo(); + } + } + Widgets::EndProperties(); + } // Only recompose when a local change happened if (localPosition != position || localScale != scale || @@ -47,7 +91,6 @@ namespace Atlas::Editor::UI { composition.rotation = rotation; composition.scale = scale; transform.Set(composition.Compose()); - lastTransform = transform.matrix; } ImGui::PopID(); diff --git a/src/editor/ui/panels/components/TransformComponentPanel.h b/src/editor/ui/panels/components/TransformComponentPanel.h index 48af25341..f784e948b 100644 --- a/src/editor/ui/panels/components/TransformComponentPanel.h +++ b/src/editor/ui/panels/components/TransformComponentPanel.h @@ -15,15 +15,15 @@ namespace Atlas::Editor::UI { bool Render(Ref& scene, Scene::Entity entity, TransformComponent& transform); + // Decomposes the matrix again on the next render, e.g. after a tool moved the entity + void Refresh() { lastEntity = Scene::Entity(); } + private: Scene::Entity lastEntity; vec3 position; vec3 rotation; vec3 scale; - quat quaternion; - - glm::mat4 lastTransform; }; diff --git a/src/editor/ui/popups/ResourceSelectionPopup.h b/src/editor/ui/popups/ResourceSelectionPopup.h index 5742c32cf..ac3655cdc 100644 --- a/src/editor/ui/popups/ResourceSelectionPopup.h +++ b/src/editor/ui/popups/ResourceSelectionPopup.h @@ -1,6 +1,8 @@ #pragma once #include "Popup.h" +#include "ContentPreviews.h" +#include "Singletons.h" #include "resource/Resource.h" @@ -68,6 +70,9 @@ namespace Atlas::Editor::UI { auto itemName = resource->GetFileName(); ImGui::PushID(i); + auto previewSize = ImGui::GetTextLineHeight(); + Singletons::contentPreviews->Render(resource->path, ImVec2(previewSize, previewSize)); + ImGui::SameLine(); ImGui::Selectable(itemName.c_str(), &isSelected, ImGuiSelectableFlags_SpanAvailWidth); ImGui::SetItemTooltip("%s", resource->path.c_str()); ImGui::PopID(); diff --git a/src/editor/ui/windows/AssetEditorWindow.cpp b/src/editor/ui/windows/AssetEditorWindow.cpp new file mode 100644 index 000000000..eddab971e --- /dev/null +++ b/src/editor/ui/windows/AssetEditorWindow.cpp @@ -0,0 +1,321 @@ +#include "AssetEditorWindow.h" +#include "../Widgets.h" +#include "../../Singletons.h" + +#include "../../DataCreator.h" +#include "../../Singletons.h" +#include "../../Theme.h" + +#include "Clock.h" + +#include +#include + +namespace Atlas::Editor::UI { + + AssetEditorWindow::AssetEditorWindow(const std::string& name, bool show) : Window(name, show) { + + // Editors are opened and closed often, they always start with the default layout + resetDockingLayout = true; + + RegisterViewportOverlay(); + + } + + void AssetEditorWindow::Render() { + + // The asset identifies the window, the label gets room for the unsaved marker + auto assetPath = GetAssetPath(); + SetTitle(name, assetPath.empty() ? std::to_string(ID) : assetPath); + + ImGui::SetNextWindowSize(ImVec2(1280, 720), ImGuiCond_FirstUseEver); + if (!Begin()) + return; + + // The layout depends on the asset, e.g. skinned meshes have more panels + if (!IsReady()) { + auto loadingText = "Loading " + Common::Path::GetFileName(GetAssetPath()) + "..."; + Widgets::LoadingState(loadingText.c_str()); + End(); + return; + } + + ImGuiID dsID = ImGui::GetID(dockSpaceNameID.c_str()); + + if (!ImGui::DockBuilderGetNode(dsID) || resetDockingLayout) { + // New windows start tiny, the panels would keep that size + auto windowSize = ImGui::GetWindowSize(); + if (windowSize.x < 200.0f || windowSize.y < 200.0f) { + End(); + return; + } + + ImGui::DockBuilderRemoveNode(dsID); + ImGui::DockBuilderAddNode(dsID, ImGuiDockNodeFlags_DockSpace); + + ImGui::DockBuilderSetNodeSize(dsID, windowSize); + + ImGuiID dockIdSide = 0, dockIdBottom = 0, dockIdMiddle = dsID, dockIdRight; + if (HasSidePanel()) + ImGui::DockBuilderSplitNode(dockIdMiddle, ImGuiDir_Left, 0.18f, &dockIdSide, &dockIdMiddle); + ImGui::DockBuilderSplitNode(dockIdMiddle, ImGuiDir_Right, 0.3f, &dockIdRight, &dockIdMiddle); + if (HasBottomPanel()) + ImGui::DockBuilderSplitNode(dockIdMiddle, ImGuiDir_Down, GetBottomPanelSize(), &dockIdBottom, &dockIdMiddle); + + ImGui::DockBuilderDockWindow(viewportPanel.GetNameID(), dockIdMiddle); + ImGui::DockBuilderDockWindow(propertiesPanel.GetNameID(), dockIdRight); + DockPanels(dockIdSide, dockIdBottom); + ImGui::DockBuilderFinish(dsID); + + resetDockingLayout = false; + } + + // Panels which are alone in their node don't need a tab bar + ImGui::DockSpace(dsID, ImVec2(0.0f, 0.0f), ImGuiDockNodeFlags_AutoHideTabBar); + if (auto node = ImGui::DockBuilderGetNode(dsID)) { + dockSpacePos = node->Pos; + dockSpaceSize = node->Size; + } + dockSpaceViewport = ImGui::GetWindowViewport()->ID; + + inFocus = ImGui::IsWindowFocused() || propertiesPanel.isFocused || viewportPanel.isFocused || IsPanelFocused(); + if (inFocus) + lastFocusTime = Clock::Get(); + + if (!scene) + CreatePreview(); + + RenderPanels(); + + ImGui::Begin(propertiesPanel.GetNameID()); + + if (ImGui::IsDragDropActive() && ImGui::IsWindowHovered() && !ImGui::IsWindowFocused()) + ImGui::SetWindowFocus(); + + propertiesPanel.isFocused = ImGui::IsWindowFocused(); + + RenderProperties(); + + ImGui::End(); + + bool controlDown; +#ifdef AE_OS_MACOS + controlDown = ImGui::IsKeyDown(ImGuiKey_LeftSuper); +#else + controlDown = ImGui::IsKeyDown(ImGuiKey_LeftCtrl); +#endif + bool typing = ImGui::GetIO().WantTextInput; + if (inFocus && controlDown && ImGui::IsKeyPressed(ImGuiKey_S, false)) { + Save(); + hasUnsavedChanges = false; + } + if (inFocus && history.HandleShortcuts()) + lastState = SaveState(); + // Only the window the user works in has edits, an interaction which moved the focus away still has to finish + if (inFocus || history.IsInteracting() || lastState.is_null()) + UpdateHistory(); + auto viewportShortcuts = inFocus && !controlDown && !typing && AllowsViewportShortcuts(); + if (viewportShortcuts && ImGui::IsKeyPressed(ImGuiKey_F, false)) + FocusAsset(); + if (viewportShortcuts && ImGui::IsKeyPressed(ImGuiKey_G, false)) + showGrid = !showGrid; + + { + auto& camera = cameraEntity.GetComponent(); + camera.aspectRatio = float(viewportPanel.viewport->width) / std::max(float(viewportPanel.viewport->height), 1.0f); + + // Path tracing needs history while ray tracing + scene->rayTracingWorld->includeObjectHistory = Singletons::config->pathTrace; + scene->Update(Clock::GetDelta(), cameraEntity); + + // The camera direction is only known after the first update + if (focusRequested) { + FocusAsset(); + focusRequested = false; + } + + if (showGrid) + viewportPanel.RenderGrid(camera); + // The scene keeps the bounds of meshes up to date, e.g. with the pose of an animation + if (showBounds) { + auto bounds = scene->GetHierarchyBounds(entity).value_or(GetBounds()); + viewportPanel.primitiveBatchWrapper.GetBatch(true)->AddLineAABB(bounds, vec3(1.0f, 1.0f, 0.0f)); + } + + RenderOverlays(); + } + + viewportPanel.Render(scene); + AcceptViewportDrop(); + + End(); + + } + + void AssetEditorWindow::FocusAsset() { + + if (!scene) + return; + + auto& camera = cameraEntity.GetComponent(); + + // Keep the view direction and back off until the bounding sphere fits into the field of view + auto bounds = GetBounds(); + auto center = 0.5f * (bounds.min + bounds.max); + auto radius = std::max(0.5f * glm::length(bounds.max - bounds.min), 0.1f); + auto distance = radius / std::sin(glm::radians(camera.fieldOfView) * 0.5f); + + camera.location = center - camera.direction * distance; + + } + + void AssetEditorWindow::Undo() { + + if (history.Undo()) + lastState = SaveState(); + + } + + void AssetEditorWindow::Redo() { + + if (history.Redo()) + lastState = SaveState(); + + } + + void AssetEditorWindow::ResetHistory() { + + history.Clear(); + lastState = json(); + + } + + void AssetEditorWindow::UpdateHistory() { + + auto interactionFinished = history.IsInteractionFinished(); + + if (lastState.is_null()) { + lastState = SaveState(); + return; + } + + // A change from a script has no interaction of its own + if (!interactionFinished && !std::exchange(changedOutside, false)) + return; + + auto state = SaveState(); + if (state == lastState) + return; + + auto before = lastState; + hasUnsavedChanges = true; + history.Push({ + .name = "Edit " + Common::Path::GetFileName(GetAssetPath()), + .undo = [this, before]() { RestoreState(before); }, + .redo = [this, state]() { RestoreState(state); } + }); + lastState = state; + + } + + void AssetEditorWindow::RenderHeading(const char* saveTooltip) { + + auto& style = ImGui::GetStyle(); + auto path = GetAssetPath(); + + // Heading with the save button on the right + auto saveWidth = ImGui::GetTextLineHeight() + 2.0f * style.FramePadding.x; + auto headingStart = ImGui::GetCursorPos(); + + // The name is cut off before the save button + auto headingMin = ImGui::GetCursorScreenPos(); + ImGui::PushClipRect(headingMin, ImVec2(headingMin.x + ImGui::GetContentRegionAvail().x - saveWidth - style.ItemSpacing.x, + headingMin.y + 2.0f * ImGui::GetTextLineHeight()), true); + Widgets::Heading(Common::Path::GetFileName(path).c_str()); + ImGui::PopClipRect(); + ImGui::TextColored(Theme::TextMuted(), "%s", path.c_str()); + auto headingEnd = ImGui::GetCursorPos(); + + ImGui::SetCursorPos(ImVec2(ImGui::GetWindowContentRegionMax().x - saveWidth, headingStart.y)); + if (Widgets::ToolbarIconButton("Save", Singletons::icons->Get(IconType::Save), saveTooltip)) { + Save(); + hasUnsavedChanges = false; + } + ImGui::SetCursorPos(headingEnd); + + ImGui::Separator(); + + } + + void AssetEditorWindow::CreatePreview() { + + auto bounds = GetBounds(); + auto extent = std::max(glm::length(bounds.max - bounds.min), 1.0f); + scene = DataCreator::CreatePreviewScene(name, bounds); + + entity = CreatePreviewEntity(); + + cameraEntity = scene->CreateEntity(); + auto& camera = cameraEntity.AddComponent(47.0f, 2.0f, 0.01f * extent, 100.0f * extent, + vec3(0.0f), vec2(glm::pi() + 0.5f, -0.3f)); + camera.isMain = true; + + cameraMovementSpeed = extent; + focusRequested = true; + + } + + void AssetEditorWindow::RegisterViewportOverlay() { + + viewportPanel.DrawMenuBar([&]() { + + const float margin = ViewportPanel::toolbarMargin; + auto region = ImGui::GetContentRegionAvail(); + + // Mouse wheel over the viewport changes the camera speed, as in the scene window + const auto& io = ImGui::GetIO(); + if (ImGui::IsWindowHovered() && io.MouseWheel != 0.0f && !io.KeyCtrl) + cameraMovementSpeed = std::clamp(cameraMovementSpeed * std::pow(1.25f, io.MouseWheel), 0.01f, 500.0f); + + viewportPanel.BeginToolbarGroup(margin, 1); + if (viewportPanel.ToolbarButton("Focus button", IconType::Mesh, false, scene != nullptr, "Focus (F)")) + FocusAsset(); + + auto uvMin = ImVec2(0.1f, 0.1f); + auto uvMax = ImVec2(0.9f, 0.9f); + viewportPanel.BeginToolbarGroup(region.x - margin - viewportPanel.GetToolbarGroupWidth(2), 2); + if (viewportPanel.ToolbarButton("Viewport settings button", IconType::Settings, false, scene != nullptr, + "Viewport settings", uvMin, uvMax)) + ImGui::OpenPopup("Viewport settings"); + if (viewportPanel.ToolbarButton("Visualization settings button", IconType::Visibility, + viewportPanel.visualization != ViewportVisualization::Lit, scene != nullptr, "Visualization", uvMin, uvMax)) + ImGui::OpenPopup("Visualization settings"); + + if (ImGui::BeginPopup("Viewport settings")) { + ImGui::SeparatorText("Overlays"); + ImGui::Checkbox("Show grid (G)", &showGrid); + ImGui::Checkbox("Show bounds", &showBounds); + RenderViewportSettings(); + + ImGui::SeparatorText("Camera"); + ImGui::DragFloat("Movement speed", &cameraMovementSpeed, 0.01f, 0.01f, 500.0f); + ImGui::SetItemTooltip("The mouse wheel over the viewport changes the speed as well"); + if (cameraEntity.IsValid()) { + auto& camera = cameraEntity.GetComponent(); + ImGui::DragFloat("Exposure", &camera.exposure, 0.1f, 0.01f, 180.0f); + ImGui::DragFloat("Field of view", &camera.fieldOfView, 0.1f, 1.0f, 180.0f); + } + + ImGui::EndPopup(); + } + + viewportPanel.RenderVisualizationPopup(); + + // Don't leave the cursor on the toolbar line + ImGui::NewLine(); + + }); + + } + +} diff --git a/src/editor/ui/windows/AssetEditorWindow.h b/src/editor/ui/windows/AssetEditorWindow.h new file mode 100644 index 000000000..be3e438b2 --- /dev/null +++ b/src/editor/ui/windows/AssetEditorWindow.h @@ -0,0 +1,123 @@ +#pragma once + +#include "Window.h" + +#include "../panels/ViewportPanel.h" + +#include "scene/Scene.h" +#include "../../UndoHistory.h" +#include "common/SerializationHelper.h" + +namespace Atlas::Editor::UI { + + // Shows one asset in a preview scene with an editor camera, a viewport and a properties panel + class AssetEditorWindow : public Window { + + public: + AssetEditorWindow(const std::string& name, bool show); + + virtual ~AssetEditorWindow() = default; + + void Render(); + + virtual void Save() = 0; + + // Path of the edited asset, an asset is only opened once + virtual std::string GetAssetPath() const = 0; + + // Moves the camera such that the whole asset is in view + void FocusAsset(); + + void Undo(); + + void Redo(); + + Ref scene; + Scene::Entity entity; + Scene::Entity cameraEntity; + + ViewportPanel viewportPanel; + + // Clock time when the window was last focused, e.g. animations opened from the content browser play in the latest + float lastFocusTime = 0.0f; + + float cameraMovementSpeed = 1.0f; + + bool showGrid = true; + bool showBounds = false; + + UndoHistory history; + + protected: + // Whether the asset is loaded and the preview can be created + virtual bool IsReady() const = 0; + + // Creates the entity showing the asset in the preview scene + virtual Scene::Entity CreatePreviewEntity() = 0; + + virtual Volume::AABB GetBounds() const = 0; + + // Shown below the heading of the properties panel + virtual void RenderProperties() = 0; + + // Additional panels left of and below the viewport, docked by DockPanels + virtual void RenderPanels() {} + + virtual bool HasSidePanel() const { return false; } + + virtual bool HasBottomPanel() const { return false; } + + // Part of the height of the viewport area which the bottom panel takes + virtual float GetBottomPanelSize() const { return 0.35f; } + + // Panels with their own keyboard shortcuts keep the keys from the viewport while they are focused + virtual bool AllowsViewportShortcuts() const { return true; } + + virtual void DockPanels(ImGuiID side, ImGuiID bottom) {} + + virtual bool IsPanelFocused() const { return false; } + + // Additional entries of the viewport settings popup + virtual void RenderViewportSettings() {} + + // Lines drawn into the scene each frame + virtual void RenderOverlays() {} + + // Called after the viewport rendered, e.g. to accept resources dropped onto it + virtual void AcceptViewportDrop() {} + + // Heading with the asset name, its path and the save button + void RenderHeading(const char* saveTooltip); + + // State of the asset for the undo history, it is compared once an interaction finished + virtual json SaveState() const { return json(); } + + virtual void RestoreState(const json& j) {} + + // Starts a new history, e.g. after another asset was chosen in the same window + void ResetHistory(); + + // The asset was changed by something else than the window, e.g. a script, the next frame records it + bool changedOutside = false; + + Panel propertiesPanel = Panel("Properties"); + + // Area of the panels in this frame, e.g. for a panel maximized within the window + ImVec2 dockSpacePos = ImVec2(0.0f, 0.0f); + ImVec2 dockSpaceSize = ImVec2(0.0f, 0.0f); + ImGuiID dockSpaceViewport = 0; + + private: + void CreatePreview(); + + void RegisterViewportOverlay(); + + void UpdateHistory(); + + bool focusRequested = false; + + json lastState; + + }; + +} diff --git a/src/editor/ui/windows/CodeEditorWindow.cpp b/src/editor/ui/windows/CodeEditorWindow.cpp new file mode 100644 index 000000000..6ce9bf5e0 --- /dev/null +++ b/src/editor/ui/windows/CodeEditorWindow.cpp @@ -0,0 +1,609 @@ +#include "CodeEditorWindow.h" +#include "../../Notifications.h" +#include "../../Theme.h" +#include "../../Singletons.h" +#include "../Widgets.h" + +#include "common/Path.h" +#include "loader/AssetLoader.h" +#include "scripting/BindingRegistry.h" + +#include +#include +#include +#include +#include + +namespace Atlas::Editor::UI { + + CodeEditorWindow::CodeEditorWindow(const std::string& path) + : Window(Common::Path::GetFileName(path), true), path(path) { + + // The file identifies the window, two files can have the same name + SetTitle(name, path); + + auto stream = Loader::AssetLoader::ReadFile(path, std::ios::in | std::ios::binary); + if (stream.is_open()) + text.assign(std::istreambuf_iterator(stream), std::istreambuf_iterator()); + else + Notifications::Push({ .message = "Couldn't read " + path, .type = NotificationType::Error }); + windowsLineEndings = text.find("\r\n") != std::string::npos; + std::erase(text, '\r'); + codeEditor.Reset(text); + + if (Common::Path::GetFileType(path) == "lua") { + codeEditor.language = CodeLanguage::Lua; + codeEditor.completionProvider = &CodeEditorWindow::CompleteLua; + return; + } + + codeEditor.language = CodeLanguage::GLSL; + LoadIncludes(); + codeEditor.completionProvider = [this](const CodeCompletionContext& context) { return CompleteGlsl(context); }; + + } + + void CodeEditorWindow::Render() { + + SetTitle(name, path); + if (!Begin(ImGuiWindowFlags_NoScrollbar)) + return; + + inFocus = ImGui::IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows); + auto controlDown = ImGui::GetIO().KeyCtrl || ImGui::GetIO().KeySuper; + if (inFocus && controlDown && ImGui::IsKeyPressed(ImGuiKey_S, false)) + Save(); + + // A small toolbar, the shortcuts stand in the tooltips + const auto& icons = Singletons::icons; + ImGui::BeginDisabled(!hasUnsavedChanges); + if (Widgets::ToolbarIconButton("Save", icons->Get(IconType::Save), "Save (Ctrl+S)")) + Save(); + ImGui::EndDisabled(); + ImGui::SameLine(); + ImGui::BeginDisabled(!codeEditor.CanUndo()); + if (Widgets::ToolbarIconButton("Undo", icons->Get(IconType::Undo), "Undo (Ctrl+Z)")) + codeEditor.Undo(); + ImGui::EndDisabled(); + ImGui::SameLine(); + ImGui::BeginDisabled(!codeEditor.CanRedo()); + if (Widgets::ToolbarIconButton("Redo", icons->Get(IconType::Redo), "Redo (Ctrl+Y)")) + codeEditor.Redo(); + ImGui::EndDisabled(); + ImGui::SameLine(); + if (Widgets::ToolbarIconButton("Find", icons->Get(IconType::Search), "Find (Ctrl+F), replace (Ctrl+H)")) + codeEditor.OpenSearch(false); + ImGui::SameLine(); + ImGui::AlignTextToFramePadding(); + ImGui::TextColored(Theme::TextMuted(), "%s", path.c_str()); + + if (codeEditor.Render("##Code", text)) + hasUnsavedChanges = true; + + End(); + + } + + void CodeEditorWindow::SetText(const std::string& newText) { + + text = newText; + std::erase(text, '\r'); + codeEditor.SetText(text); + hasUnsavedChanges = true; + + } + + bool CodeEditorWindow::Save() { + + auto stream = Loader::AssetLoader::WriteFile(path, std::ios::out | std::ios::binary); + if (!stream.is_open()) { + Notifications::Push({ .message = "Couldn't write " + path, .type = NotificationType::Error }); + return false; + } + std::string file; + if (windowsLineEndings) { + file.reserve(text.size() + text.size() / 32); + for (auto c : text) + file += c == '\n' ? std::string("\r\n") : std::string(1, c); + } + const auto& content = windowsLineEndings ? file : text; + stream.write(content.data(), std::streamsize(content.size())); + hasUnsavedChanges = false; + + if (codeEditor.language == CodeLanguage::GLSL) + LoadIncludes(); + return true; + + } + + void CodeEditorWindow::LoadIncludes() { + + includedFunctions.clear(); + includedCode.clear(); + glslCache.reset(); + + // Includes are relative to the including file and read once, like the shader loader does + std::vector visited = { Common::Path::Normalize(path) }; + auto collect = [&](auto&& self, const std::string& file, const std::string& code) -> void { + auto directory = Common::Path::GetDirectory(file) + "/"; + size_t position = 0; + while ((position = code.find("#include ", position)) != std::string::npos) { + auto start = code.find_first_of("\"<", position) + 1; + auto end = code.find_first_of("\">", start); + position = end; + if (start == 0 || end == std::string::npos) + break; + + auto includePath = Common::Path::Normalize(directory + code.substr(start, end - start)); + if (std::find(visited.begin(), visited.end(), includePath) != visited.end()) + continue; + visited.push_back(includePath); + + auto stream = Loader::AssetLoader::ReadFile(includePath, std::ios::in | std::ios::binary); + if (!stream.is_open()) + continue; + std::string includeCode((std::istreambuf_iterator(stream)), std::istreambuf_iterator()); + includedCode += includeCode + "\n"; + auto functions = CodeEditor::FindGlslFunctions(includeCode); + includedFunctions.insert(includedFunctions.end(), functions.begin(), functions.end()); + self(self, includePath, includeCode); + } + }; + collect(collect, path, text); + + } + + using Owners = std::unordered_map; + + // A link of a Lua or GLSL expression like children[i + 1]:GetCameraComponent(), with its calls and indices + struct ExpressionSegment { + std::string name; + bool call = false; + int32_t indices = 0; + }; + + static std::vector SplitExpression(const std::string& expression) { + + std::vector segments; + size_t i = 0; + while (i < expression.size()) { + auto c = expression[i]; + if (std::isalnum((unsigned char)c) || c == '_') { + auto begin = i; + while (i < expression.size() && (std::isalnum((unsigned char)expression[i]) || expression[i] == '_')) + i++; + segments.push_back({ expression.substr(begin, i - begin) }); + continue; + } + if ((c == '(' || c == '[') && !segments.empty()) { + auto close = c == '(' ? ')' : ']'; + auto depth = 0; + for (; i < expression.size(); i++) { + depth += expression[i] == c ? 1 : expression[i] == close ? -1 : 0; + if (depth == 0) + break; + } + if (c == '(') + segments.back().call = true; + else + segments.back().indices++; + } + else if (c != '.' && c != ':') { + return {}; + } + i++; + } + return segments; + + } + + // The expression last assigned to a variable in the code, e.g. "scene:GetMainCamera()" for "local camera = ..." + static std::pair FindLuaAssignment(std::string_view text, const std::string& name) { + + auto isWord = [](char c) { return std::isalnum((unsigned char)c) || c == '_'; }; + auto position = text.size(); + while ((position = text.rfind(name, position == 0 ? 0 : position - 1)) != std::string_view::npos) { + auto end = position + name.size(); + if ((position == 0 || !isWord(text[position - 1])) && (end >= text.size() || !isWord(text[end]))) { + auto equals = end; + while (equals < text.size() && text[equals] == ' ') + equals++; + if (equals < text.size() && text[equals] == '=' && (equals + 1 >= text.size() || text[equals + 1] != '=')) { + auto begin = equals + 1; + while (begin < text.size() && text[begin] == ' ') + begin++; + // The expression ends where something else than names, calls and indices follows + auto i = begin; + while (i < text.size()) { + auto c = text[i]; + if (c == '(' || c == '[') { + auto close = c == '(' ? ')' : ']'; + auto depth = 0; + for (; i < text.size(); i++) { + depth += text[i] == c ? 1 : text[i] == close ? -1 : 0; + if (depth == 0) + break; + } + i++; + continue; + } + if (!isWord(c) && c != '.' && c != ':') + break; + i++; + } + return { std::string(text.substr(begin, i - begin)), position }; + } + } + if (position == 0) + break; + } + return { "", 0 }; + + } + + // "fun(number): Glm.Vec3, boolean | fun(): Glm.Vec3" -> "Glm.Vec3", the first value of the first overload + static std::string GetLuaReturnType(const std::string& type) { + + if (!type.starts_with("fun(")) + return ""; + auto depth = 0; + size_t i = 3; + for (; i < type.size(); i++) { + depth += type[i] == '(' ? 1 : type[i] == ')' ? -1 : 0; + if (depth == 0) + break; + } + if (type.compare(i + 1, 2, ": ") != 0) + return ""; + auto result = type.substr(i + 3); + return result.substr(0, std::min(result.find(", "), result.find(" | "))); + + } + + // Optional values and the component references of entities have the members of their type + static std::string NormalizeLuaType(std::string type, const Owners& owners) { + + if (type.ends_with("?")) + type.pop_back(); + if (type.ends_with("Ref")) { + auto base = type.substr(0, type.size() - 3); + auto reference = owners.find(type); + if (owners.contains(base) && (reference == owners.end() || reference->second->members.empty())) + type = base; + } + return type; + + } + + // The type of an expression: locals are followed to their assignment, calls give the return type, indices the + // element type. Empty if it isn't known + static std::string ResolveLuaType(const std::string& expression, std::string_view text, const Owners& owners, int32_t depth) { + + auto segments = SplitExpression(expression); + if (segments.empty() || depth > 8) + return ""; + + auto apply = [&](std::string type, const ExpressionSegment& segment) { + if (segment.call) + type = GetLuaReturnType(type); + type = NormalizeLuaType(type, owners); + for (int32_t i = 0; i < segment.indices && type.ends_with("[]"); i++) + type = type.substr(0, type.size() - 2); + return NormalizeLuaType(type, owners); + }; + + std::string type; + const auto& first = segments.front(); + auto [assigned, position] = FindLuaAssignment(text, first.name); + auto globals = owners.find("_G"); + if (!assigned.empty()) { + type = ResolveLuaType(assigned, text.substr(0, position), owners, depth + 1); + } + else if (globals != owners.end()) { + for (const auto& member : globals->second->members) + if (member.name == first.name) + type = member.type; + } + if (type.empty() && owners.contains(first.name)) + type = first.name; + type = apply(type, first); + + for (size_t i = 1; i < segments.size() && !type.empty(); i++) { + auto owner = owners.find(type); + std::string next; + if (owner != owners.end()) { + for (const auto& member : owner->second->members) + if (member.name == segments[i].name) + next = member.type; + } + // Tables contain types and tables, e.g. Atlas.Sky + if (next.empty() && owners.contains(type + "." + segments[i].name)) + next = type + "." + segments[i].name; + type = next.empty() ? "" : apply(next, segments[i]); + } + return type; + + } + + std::vector CodeEditorWindow::CompleteLua(const CodeCompletionContext& context) { + + auto lower = [](std::string text) { + std::transform(text.begin(), text.end(), text.begin(), [](unsigned char c) { return char(std::tolower(c)); }); + return text; + }; + auto lastSegment = [](const std::string& path) { return path.substr(path.rfind('.') + 1); }; + + // The bindings only change when new ones are recorded + static std::vector owners; + static Owners byPath; + static uint64_t ownersRevision = std::numeric_limits::max(); + if (ownersRevision != Scripting::BindingRegistry::GetRevision()) { + ownersRevision = Scripting::BindingRegistry::GetRevision(); + owners = Scripting::BindingRegistry::GetOwners(); + byPath.clear(); + for (const auto& owner : owners) + byPath[owner.path] = &owner; + } + + std::vector completions; + auto addMembers = [&](const Scripting::BindingRegistry::Owner& owner) { + for (const auto& member : owner.members) { + // Methods are called with :, fields and functions of tables with . + auto isMethod = member.kind == "method"; + if (context.separator && (context.separator == ':') != isMethod) + continue; + completions.push_back({ member.name, member.kind, member.type, member.description }); + } + }; + + if (!context.separator) { + // Globals: the functions of the script environment and the tables like Atlas, Glm or Host + std::vector roots; + for (const auto& owner : owners) { + if (owner.path == "_G") { + addMembers(owner); + continue; + } + auto root = owner.path.substr(0, owner.path.find('.')); + if (std::find(roots.begin(), roots.end(), root) == roots.end()) + roots.push_back(root); + } + for (const auto& root : roots) + completions.push_back({ root, "table", "", "" }); + return completions; + } + + std::vector types; + auto resolved = ResolveLuaType(context.qualifier, context.text, byPath, 0); + if (!resolved.empty()) { + types.push_back(resolved); + } + else { + // Without a known type, the qualifier is matched to a bound type or table by its name (scene, sky, Host) + // and by the fields of that name whose type is bound (scene.postProcessing) + auto qualifier = lower(context.qualifier); + for (const auto& owner : owners) { + if (lower(owner.path) == qualifier || lower(lastSegment(owner.path)) == qualifier) + types.push_back(owner.path); + for (const auto& member : owner.members) { + if (lower(member.name) == qualifier && member.kind != "method" && member.kind != "function") + types.push_back(NormalizeLuaType(member.type.substr(0, member.type.find('[')), byPath)); + } + } + } + + // Children of a table, e.g. Atlas. offers Sky, Scene and the other types + for (const auto& owner : owners) { + auto parent = owner.path.find('.') == std::string::npos ? "" : owner.path.substr(0, owner.path.rfind('.')); + if (std::find(types.begin(), types.end(), parent) != types.end()) + completions.push_back({ lastSegment(owner.path), owner.kind, "", owner.description }); + } + + for (const auto& owner : owners) { + if (std::find(types.begin(), types.end(), owner.path) != types.end()) + addMembers(owner); + } + + // Several types can match a name, each member is offered once + std::sort(completions.begin(), completions.end(), [](const auto& a, const auto& b) { return a.text < b.text; }); + completions.erase(std::unique(completions.begin(), completions.end(), + [](const auto& a, const auto& b) { return a.text == b.text; }), completions.end()); + return completions; + + } + + + // A declared GLSL type, e.g. "vec3", a struct or a block, and whether the declaration is an array + struct GlslType { + std::string name; + bool array = false; + }; + + struct GlslField { + GlslType type; + std::string name; + }; + + // Structs and blocks with their fields, and the instance names of blocks ("} uniforms;") + struct GlslScope { + std::unordered_map> structs; + std::unordered_map instances; + }; + + static const std::vector glslQualifiers = { "const", "in", "out", "inout", "uniform", "buffer", + "shared", "flat", "highp", "mediump", "lowp", "readonly", "writeonly", "coherent", "restrict", "volatile", "precise" }; + + static GlslScope FindGlslScope(const std::string& code) { + + GlslScope scope; + static const std::regex blockPattern(R"(\b(struct|uniform|buffer)\s+(\w+)\s*\{([^}]*)\}\s*(\w+)?(\s*\[)?)"); + static const std::regex namePattern(R"((\w+)\s*(\[[^\]]*\])?)"); + static const std::regex layoutPattern(R"(layout\s*\([^)]*\))"); + for (auto block = std::sregex_iterator(code.begin(), code.end(), blockPattern); block != std::sregex_iterator(); block++) { + auto& fields = scope.structs[(*block)[2]]; + auto body = std::regex_replace((*block)[3].str(), layoutPattern, ""); + size_t start = 0; + while (start < body.size()) { + auto end = std::min(body.find(';', start), body.size()); + auto statement = body.substr(start, end - start); + start = end + 1; + + // The first word which isn't a qualifier is the type, the others are the names + std::string type; + for (auto word = std::sregex_iterator(statement.begin(), statement.end(), namePattern); word != std::sregex_iterator(); word++) { + auto name = (*word)[1].str(); + if (std::isdigit((unsigned char)name[0])) + continue; + if (type.empty()) { + if (std::find(glslQualifiers.begin(), glslQualifiers.end(), name) == glslQualifiers.end()) + type = name; + continue; + } + fields.push_back({ { type, (*word)[2].matched }, name }); + } + } + if ((*block)[1] != "struct" && (*block)[4].matched) + scope.instances[(*block)[4]] = { (*block)[2], (*block)[5].matched }; + } + return scope; + + } + + // The type a variable is declared with last in the code: locals, parameters and globals + static GlslType FindGlslDeclaration(const std::string& code, const std::string& name) { + + static const std::vector notTypes = { "return", "else", "case", "discard", "break", "continue" }; + std::regex pattern(R"(\b([A-Za-z_]\w*)\s+)" + name + R"(\s*(\[[^\]]*\])?\s*[;=,)\[])"); + GlslType type; + for (auto match = std::sregex_iterator(code.begin(), code.end(), pattern); match != std::sregex_iterator(); match++) { + auto typeName = (*match)[1].str(); + if (std::find(notTypes.begin(), notTypes.end(), typeName) == notTypes.end()) + type = { typeName, (*match)[2].matched }; + } + return type; + + } + + // "vec3" -> 3 components of "float", matrices index to their columns + static int32_t GetGlslVectorSize(const std::string& type, std::string& scalar) { + + static const std::regex vectorPattern(R"(^(vec|ivec|uvec|bvec|dvec)([234])$)"); + std::smatch match; + if (!std::regex_match(type, match, vectorPattern)) + return 0; + static const std::unordered_map scalars = { { "vec", "float" }, { "ivec", "int" }, + { "uvec", "uint" }, { "bvec", "bool" }, { "dvec", "double" } }; + scalar = scalars.at(match[1]); + return match[2].str()[0] - '0'; + + } + + static GlslType IndexGlslType(GlslType type) { + + if (type.array) + return { type.name, false }; + + static const std::regex matrixPattern(R"(^mat([234])(?:x([234]))?$)"); + std::smatch match; + if (std::regex_match(type.name, match, matrixPattern)) + return { "vec" + (match[2].matched ? match[2].str() : match[1].str()) }; + + std::string scalar; + if (GetGlslVectorSize(type.name, scalar)) + return { scalar }; + return type; + + } + + struct CodeEditorWindow::GlslCache { + std::string text; + std::vector functions; + GlslScope scope; + }; + + std::vector CodeEditorWindow::CompleteGlsl(const CodeCompletionContext& context) const { + + // Structs and blocks can be anywhere in the file + if (!glslCache || glslCache->text != text) { + glslCache = std::make_shared(); + glslCache->text = text; + glslCache->functions = CodeEditor::FindGlslFunctions(text); + glslCache->functions.insert(glslCache->functions.end(), includedFunctions.begin(), includedFunctions.end()); + glslCache->scope = FindGlslScope(includedCode + "\n" + text); + } + const auto& functions = glslCache->functions; + const auto& scope = glslCache->scope; + if (!context.separator) + return functions; + if (context.separator != '.') + return {}; + + auto segments = SplitExpression(context.qualifier); + if (segments.empty()) + return {}; + + // Declarations of the includes come before the code + auto code = includedCode + "\n" + std::string(context.text); + + GlslType type; + const auto& first = segments.front(); + if (first.call) { + // The return type is in front of the name, e.g. "vec3 Rotate(vec3 v)" + for (const auto& function : functions) { + if (function.text != first.name) + continue; + auto declaration = function.signature.substr(0, function.signature.find(' ' + first.name + '(')); + type.name = declaration.substr(declaration.rfind(' ') + 1); + } + } + else if (auto instance = scope.instances.find(first.name); instance != scope.instances.end()) { + type = instance->second; + } + else { + type = FindGlslDeclaration(code, first.name); + } + + auto applyIndices = [&](const ExpressionSegment& segment) { + for (int32_t i = 0; i < segment.indices; i++) + type = IndexGlslType(type); + }; + applyIndices(first); + + for (size_t i = 1; i < segments.size() && !type.name.empty(); i++) { + std::string scalar; + if (GetGlslVectorSize(type.name, scalar)) { + // A swizzle of one component is a scalar, more are a vector of the same kind + auto length = segments[i].name.size(); + type = { length == 1 ? scalar : type.name.substr(0, type.name.size() - 1) + std::to_string(length) }; + } + else { + auto fields = scope.structs.find(type.name); + GlslType next; + if (fields != scope.structs.end()) { + for (const auto& field : fields->second) + if (field.name == segments[i].name) + next = field.type; + } + type = next; + } + applyIndices(segments[i]); + } + + std::vector completions; + if (type.array || type.name.empty()) + return completions; + std::string scalar; + if (auto size = GetGlslVectorSize(type.name, scalar)) { + for (const auto* components : { "xyzw", "rgba" }) + for (int32_t i = 0; i < size; i++) + completions.push_back({ std::string(1, components[i]), "Component", scalar }); + } + else if (auto fields = scope.structs.find(type.name); fields != scope.structs.end()) { + for (const auto& field : fields->second) + completions.push_back({ field.name, "Field", field.type.name + (field.type.array ? "[]" : "") + " " + field.name }); + } + return completions; + + } + +} diff --git a/src/editor/ui/windows/CodeEditorWindow.h b/src/editor/ui/windows/CodeEditorWindow.h new file mode 100644 index 000000000..ad462b2b5 --- /dev/null +++ b/src/editor/ui/windows/CodeEditorWindow.h @@ -0,0 +1,65 @@ +#pragma once + +#include "Window.h" +#include "../CodeEditor.h" + +#include +#include + +namespace Atlas::Editor::UI { + + // A Lua script or a shader file with syntax highlighting and completions, Ctrl+S saves it. Scripts complete the + // bindings the engine and the programs record (Scripting::BindingRegistry), shaders the functions of the file + // and its includes + class CodeEditorWindow : public Window { + + public: + explicit CodeEditorWindow(const std::string& path); + + void Render(); + + bool Save(); + + const std::string& GetPath() const { return path; } + + const std::string& GetText() const { return text; } + + // One undo step in the editor, the file is saved by the user + void SetText(const std::string& newText); + + void Undo() { codeEditor.Undo(); } + + void Redo() { codeEditor.Redo(); } + + bool CanUndo() const { return codeEditor.CanUndo(); } + + bool CanRedo() const { return codeEditor.CanRedo(); } + + void OpenSearch(bool replace) { codeEditor.OpenSearch(replace); } + + // Members of the bound types and tables for a context, e.g. after "sky." the fields of Atlas.Sky + static std::vector CompleteLua(const CodeCompletionContext& context); + + private: + // Functions, structs and blocks of the text and the includes, found again when the text changed + struct GlslCache; + + // Functions and code of the included files, collected when the file is opened or saved + void LoadIncludes(); + + // Functions, and after a . the fields of structs and blocks or the components of vectors + std::vector CompleteGlsl(const CodeCompletionContext& context) const; + + std::string path; + std::string text; + CodeEditor codeEditor; + // The file uses Windows line endings, the editor works without the \r and saves them again + bool windowsLineEndings = false; + + std::vector includedFunctions; + std::string includedCode; + mutable std::shared_ptr glslCache; + + }; + +} diff --git a/src/editor/ui/windows/ContentBrowserWindow.cpp b/src/editor/ui/windows/ContentBrowserWindow.cpp index 6c60fbae8..aa474f364 100644 --- a/src/editor/ui/windows/ContentBrowserWindow.cpp +++ b/src/editor/ui/windows/ContentBrowserWindow.cpp @@ -4,6 +4,7 @@ #include "Notifications.h" #include "ui/panels/PopupPanels.h" #include "ui/Widgets.h" +#include "Theme.h" #include "tools/CopyPasteHelper.h" #include "tools/FileSystemHelper.h" @@ -24,7 +25,7 @@ namespace Atlas::Editor::UI { - ContentBrowserWindow::ContentBrowserWindow(bool show) : Window("Content browser", show) { + ContentBrowserWindow::ContentBrowserWindow(bool show) : DrawerWindow("Content browser", show) { selectionStorage.AdapterIndexToStorageId = [](ImGuiSelectionBasicStorage* self, int idx) { (void)self; @@ -35,77 +36,98 @@ namespace Atlas::Editor::UI { void ContentBrowserWindow::Update() { - if (!show) + // A search runs on the medium pool next to long jobs (e.g. navigation tiles), the window doesn't wait for it. + // The next search starts once the last one has finished + if (!show || isEditing || !searchAndFilterJob.HasFinished()) return; - JobSystem::Execute(searchAndFilterJob, [&](JobData&) { - UpdateFilteredAndSortedDirEntries(); + auto contentDirectory = ContentDiscovery::GetDirectory(currentDirectory); + if (!contentDirectory) + return; + + // The job gets copies, the window changes the search while it runs + auto searchQuery = assetSearch; + std::transform(searchQuery.begin(), searchQuery.end(), searchQuery.begin(), ::tolower); + auto filter = contentFilter; + auto recursively = searchQuery.empty() ? filterRecursively && filter != ContentFilterBits::AllBit : searchRecursively; + auto listDirectories = searchQuery.empty() && !filterRecursively && filter == ContentFilterBits::AllBit; + + JobSystem::Execute(searchAndFilterJob, [this, contentDirectory, searchQuery, filter, recursively, listDirectories](JobData&) { + foundFiles.clear(); + SearchDirectory(contentDirectory, foundFiles, searchQuery, filter, recursively); + std::sort(foundFiles.begin(), foundFiles.end(), [](const auto& file0, const auto& file1) { + return file0.name < file1.name; + }); + + if (listDirectories) + foundDirectories = contentDirectory->directories; + else + foundDirectories.clear(); + hasFoundEntries = true; }); } void ContentBrowserWindow::Render() { + // A pinned browser can be behind another tab when a file should be shown + if (!contentToShowPath.empty()) + ImGui::SetNextWindowFocus(); + if (!Begin()) return; - ImGuiID dsID = ImGui::GetID(dockSpaceNameID.c_str()); - auto viewport = ImGui::GetWindowViewport(); - - if (!ImGui::DockBuilderGetNode(dsID) || resetDockingLayout) { - ImGui::DockBuilderRemoveNode(dsID); - ImGui::DockBuilderAddNode(dsID, ImGuiDockNodeFlags_DockSpace); + const float minPanelWidth = 120.0f; + auto panelWidth = std::clamp(folderPanelWidth, minPanelWidth, + std::max(ImGui::GetWindowWidth() - 2.0f * minPanelWidth, minPanelWidth)); - ImGui::DockBuilderSetNodeSize(dsID, viewport->Size); + ImGui::BeginChild("ResourceTypeSelection", ImVec2(panelWidth, 0.0f)); - uint32_t dockIdLeft, dockIdRight; - ImGui::DockBuilderSplitNode(dsID, ImGuiDir_Left, 0.05f, &dockIdLeft, &dockIdRight); - - ImGuiDockNode* leftNode = ImGui::DockBuilderGetNode(dockIdLeft); - ImGuiDockNode* rightNode = ImGui::DockBuilderGetNode(dockIdRight); - leftNode->LocalFlags |= ImGuiDockNodeFlags_NoTabBar | ImGuiDockNodeFlags_NoDockingOverMe; - rightNode->LocalFlags |= ImGuiDockNodeFlags_NoTabBar | ImGuiDockNodeFlags_NoDockingOverMe; + // Same height as the toolbar on the right side + ImGui::AlignTextToFramePadding(); + ImGui::TextDisabled("Folders"); - // we now dock our windows into the docking node we made above - ImGui::DockBuilderDockWindow("ResourceTypeSelection", dockIdLeft); - ImGui::DockBuilderDockWindow("ResourceTypeOverview", dockIdRight); - ImGui::DockBuilderFinish(dsID); + ImGui::Separator(); - resetDockingLayout = false; - } + RenderDirectoryControl(); - ImGui::DockSpace(dsID, ImVec2(0.0f, 0.0f), 0); + ImGui::EndChild(); - End(); + ImGui::SameLine(0.0f, 0.0f); - ImGui::Begin("ResourceTypeSelection", nullptr); + const float splitterWidth = 9.0f; + auto splitterPos = ImGui::GetCursorScreenPos(); + auto splitterHeight = ImGui::GetContentRegionAvail().y; + ImGui::InvisibleButton("Folder splitter", ImVec2(splitterWidth, std::max(splitterHeight, 1.0f))); + if (ImGui::IsItemActive()) + folderPanelWidth = panelWidth + ImGui::GetIO().MouseDelta.x; - // Same height as the toolbar on the right side - ImGui::AlignTextToFramePadding(); - ImGui::TextDisabled("Folders"); + auto splitterHighlighted = ImGui::IsItemActive() || ImGui::IsItemHovered(); + if (splitterHighlighted) + ImGui::SetMouseCursor(ImGuiMouseCursor_ResizeEW); + auto splitterX = splitterPos.x + splitterWidth * 0.5f; + ImGui::GetWindowDrawList()->AddLine(ImVec2(splitterX, splitterPos.y), ImVec2(splitterX, splitterPos.y + splitterHeight), + ImGui::GetColorU32(splitterHighlighted ? ImGuiCol_SeparatorActive : ImGuiCol_Separator), splitterHighlighted ? 2.0f : 1.0f); - ImGui::Separator(); + ImGui::SameLine(0.0f, 0.0f); - RenderDirectoryControl(); + ImGui::BeginChild("ResourceTypeOverview", ImVec2(0.0f, 0.0f), ImGuiChildFlags_None, + ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse); - ImGui::End(); + RenderDirectoryContentControl(); - ImGui::Begin("ResourceTypeOverview", nullptr); + ImGui::Separator(); // Use a child as a dummy to create a drop target, since it doesn't work directly on a window // While Ctrl is held the mouse wheel zooms the icons instead of scrolling ImGui::BeginChild("ResourceTypeDropChild", ImVec2(0.0, 0.0), ImGuiChildFlags_None, ImGui::GetIO().KeyCtrl ? ImGuiWindowFlags_NoScrollWithMouse : ImGuiWindowFlags_None); - RenderDirectoryContentControl(); - - ImGui::Separator(); - RenderDirectoryContent(); ImGui::EndChild(); - if (ImGui::IsDragDropActive() && ImGui::IsWindowHovered()) { + if (ImGui::IsDragDropActive() && ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows)) { ImGui::SetWindowFocus(); } @@ -121,25 +143,27 @@ namespace Atlas::Editor::UI { auto& config = Singletons::config; auto& scenes = config->openedScenes; - // There must be a scene, otherwise we want to get a fatal error + // The same scene, not one with the same name. Prefab windows have scenes of their own which aren't opened auto iter = std::find_if(scenes.begin(), scenes.end(), - [&](const ResourceHandle& item) -> bool { - if (!item.IsLoaded()) - return false; - return item->name == scene->name; - }); - auto sceneHandle = *iter; - - auto nameComponent = entity.TryGetComponent(); - auto entityName = nameComponent ? nameComponent->name : "Entity " + std::to_string(entity); - - auto dataDirectory = Loader::AssetLoader::GetDataDirectory(); - auto assetPath = Common::Path::GetRelative(dataDirectory, currentDirectory) + "/"; - if (assetPath.starts_with('/')) - assetPath.erase(assetPath.begin()); - - auto entityPath = assetPath + entityName + ".aeprefab"; - Serializer::SerializePrefab(sceneHandle.Get(), entity, entityPath); + [&](const ResourceHandle& item) { return item.IsLoaded() && item.Get().get() == scene; }); + if (iter == scenes.end()) { + Notifications::Push({ .message = "Only entities of opened scenes can be saved as prefabs", + .type = NotificationType::Warning }); + } + else { + auto sceneHandle = *iter; + + auto nameComponent = entity.TryGetComponent(); + auto entityName = nameComponent ? nameComponent->name : "Entity " + std::to_string(entity); + + auto dataDirectory = Loader::AssetLoader::GetDataDirectory(); + auto assetPath = Common::Path::GetRelative(dataDirectory, currentDirectory) + "/"; + if (assetPath.starts_with('/')) + assetPath.erase(assetPath.begin()); + + auto entityPath = assetPath + entityName + ".aeprefab"; + Serializer::SerializePrefab(sceneHandle.Get(), entity, entityPath); + } } } @@ -158,7 +182,63 @@ namespace Atlas::Editor::UI { } contentToShowPath.clear(); - ImGui::End(); + ImGui::EndChild(); + + RenderDeleteConfirmation(); + + End(); + + } + + void ContentBrowserWindow::RenderDeleteConfirmation() { + + const char* popupName = "Delete content?"; + if (openDeleteConfirmation) { + ImGui::OpenPopup(popupName); + openDeleteConfirmation = false; + } + + ImGui::SetNextWindowPos(ImGui::GetMainViewport()->GetCenter(), ImGuiCond_Appearing, ImVec2(0.5f, 0.5f)); + if (!ImGui::BeginPopupModal(popupName, nullptr, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings)) + return; + + if (pendingDeletePaths.size() == 1) + ImGui::Text("Delete %s?", std::filesystem::path(pendingDeletePaths.front()).filename().string().c_str()); + else + ImGui::Text("Delete %d items?", int32_t(pendingDeletePaths.size())); + + // A few names, such that a wrong selection is noticed + const size_t shownNames = 6; + if (pendingDeletePaths.size() > 1) { + for (size_t i = 0; i < std::min(shownNames, pendingDeletePaths.size()); i++) + ImGui::TextColored(Theme::TextMuted(), "%s", std::filesystem::path(pendingDeletePaths[i]).filename().string().c_str()); + if (pendingDeletePaths.size() > shownNames) + ImGui::TextColored(Theme::TextMuted(), "and %d more", int32_t(pendingDeletePaths.size() - shownNames)); + } + + ImGui::Spacing(); + ImGui::TextColored(Theme::Warning(), pendingDeleteHasDirectory ? "Folders are deleted with everything in them. This can't be undone" : + "This can't be undone"); + ImGui::Spacing(); + + auto buttonWidth = ImGui::CalcTextSize("Cancel").x * 2.5f; + auto confirm = Widgets::DangerButton("Delete", ImVec2(buttonWidth, 0.0f)); + ImGui::SameLine(); + // Cancel is the safe choice for keyboard navigation + auto cancel = ImGui::Button("Cancel", ImVec2(buttonWidth, 0.0f)); + ImGui::SetItemDefaultFocus(); + cancel |= ImGui::IsKeyPressed(ImGuiKey_Escape, false); + + if (confirm) { + FileSystemHelper::Delete(pendingDeletePaths); + selectionStorage.Clear(); + } + if (confirm || cancel) { + pendingDeletePaths.clear(); + ImGui::CloseCurrentPopup(); + } + + ImGui::EndPopup(); } @@ -178,21 +258,19 @@ namespace Atlas::Editor::UI { auto dataDirectory = Loader::AssetLoader::GetDataDirectory(); auto lineHeight = ImGui::GetTextLineHeight(); - auto set = Singletons::imguiWrapper->GetTextureId(&Singletons::icons->Get(IconType::ArrowLeft)); auto normalizedDataDirectory = Common::Path::Normalize(dataDirectory); bool atRoot = Common::Path::Normalize(currentDirectory) == normalizedDataDirectory; - ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.0f, 0.0f, 0.0f, 0.0f)); - ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 0.0f); - ImGui::BeginDisabled(atRoot); - if (ImGui::ImageButton("Back button", set, ImVec2(lineHeight, lineHeight), ImVec2(0.1f, 0.1f), ImVec2(0.9f, 0.9f))) { + if (Widgets::ToolbarIconButton("Back button", Singletons::icons->Get(IconType::ArrowLeft), "Go to parent folder")) { auto parentPath = std::filesystem::path(currentDirectory).parent_path(); currentDirectory = Common::Path::Normalize(parentPath.string()); } ImGui::EndDisabled(); - ImGui::SetItemTooltip("Go to parent folder"); + + ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.0f, 0.0f, 0.0f, 0.0f)); + ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 0.0f); // Breadcrumbs: every part of the path can be clicked to jump there auto assetPath = Common::Path::GetRelative(dataDirectory, currentDirectory); @@ -249,32 +327,28 @@ namespace Atlas::Editor::UI { auto region = ImGui::GetContentRegionAvail(); auto buttonSize = ImVec2(lineHeight, lineHeight); + // A docked browser also has the button which turns it back into a drawer + auto buttonCount = pinned ? 4.0f : 3.0f; // Wrap input text field into child, such that we can adjust the total size to not overlap anything - ImGui::BeginChild("Search field", ImVec2(std::max(region.x - 2.0f * (buttonSize.x + 2.0f * padding), 100.0f), lineHeight + 2.0f * padding)); + ImGui::BeginChild("Search field", ImVec2(std::max(region.x - buttonCount * (buttonSize.x + 2.0f * padding), 100.0f), lineHeight + 2.0f * padding)); ImGui::SetNextItemWidth(-FLT_MIN); ImGui::InputTextWithHint("##Search", "Search files...", &assetSearch); ImGui::EndChild(); region = ImGui::GetContentRegionAvail(); - auto& filterIcon = Singletons::icons->Get(IconType::Filter); - set = Singletons::imguiWrapper->GetTextureId(&filterIcon); - - auto uvMin = ImVec2(0.1f, 0.1f); - auto uvMax = ImVec2(0.9f, 0.9f); + auto& viewIcon = Singletons::icons->Get(listView ? IconType::ViewGrid : IconType::ViewList); - ImGui::SetCursorPos(ImVec2(region.x - 2.0f * (buttonSize.x + 2.0f * padding), 0.0f)); - ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.0f, 0.0f, 0.0f, 0.0f)); - ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 0.0f); - if (ImGui::ImageButton("Filter button", set, buttonSize, uvMin, uvMax)) { - ImGui::OpenPopup("Content browser filter settings"); - } - ImGui::PopStyleVar(); - ImGui::PopStyleColor(); + ImGui::SetCursorPos(ImVec2(region.x - buttonCount * (buttonSize.x + 2.0f * padding), 0.0f)); + if (Widgets::ToolbarIconButton("View button", viewIcon, listView ? "Show as tiles" : "Show as list")) + listView = !listView; // Mark the button while a filter hides content bool filterActive = (contentFilter & ContentFilterBits::AllBit) != ContentFilterBits::AllBit; - ImGui::SetItemTooltip(filterActive ? "Filter content (active)" : "Filter content"); + ImGui::SetCursorPos(ImVec2(region.x - (buttonCount - 1.0f) * (buttonSize.x + 2.0f * padding), 0.0f)); + if (Widgets::ToolbarIconButton("Filter button", Singletons::icons->Get(IconType::Filter), + filterActive ? "Filter content (active)" : "Filter content")) + ImGui::OpenPopup("Content browser filter settings"); if (filterActive) Widgets::ActiveIndicator(); @@ -296,33 +370,17 @@ namespace Atlas::Editor::UI { contentFilter = isSet ? ContentFilterBits::AllBit : 0; } ImGui::Separator(); - renderSingleBitOption("Audio", ContentFilterBits::AudioBit); - renderSingleBitOption("Mesh", ContentFilterBits::MeshBit); - renderSingleBitOption("Mesh source", ContentFilterBits::MeshSourceBit); - renderSingleBitOption("Material", ContentFilterBits::MaterialBit); - renderSingleBitOption("Terrain", ContentFilterBits::TerrainBit); - renderSingleBitOption("Scene", ContentFilterBits::SceneBit); - renderSingleBitOption("Script", ContentFilterBits::ScriptBit); - renderSingleBitOption("Font", ContentFilterBits::FontBit); - renderSingleBitOption("Prefab", ContentFilterBits::PrefabBit); - renderSingleBitOption("Texture", ContentFilterBits::TextureBit); - renderSingleBitOption("Environment texture", ContentFilterBits::EnvTextureBit); + // The filter bits are in the order of the content types + for (int32_t i = 0; i < static_cast(ContentType::None); i++) + renderSingleBitOption(GetTypeName(static_cast(i)), static_cast(1 << i)); ImGui::EndPopup(); } region = ImGui::GetContentRegionAvail(); - auto& settingsIcon = Singletons::icons->Get(IconType::Settings); - set = Singletons::imguiWrapper->GetTextureId(&settingsIcon); - - ImGui::SetCursorPos(ImVec2(region.x - (buttonSize.x + 2.0f * padding), 0.0f)); - ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.0f, 0.0f, 0.0f, 0.0f)); - ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 0.0f); - if (ImGui::ImageButton("Settings button", set, buttonSize, uvMin, uvMax)) { + ImGui::SetCursorPos(ImVec2(region.x - (buttonCount - 2.0f) * (buttonSize.x + 2.0f * padding), 0.0f)); + if (Widgets::ToolbarIconButton("Settings button", Singletons::icons->Get(IconType::Settings), "Content browser settings")) ImGui::OpenPopup("Content browser settings"); - } - ImGui::PopStyleVar(); - ImGui::PopStyleColor(); if (ImGui::BeginPopup("Content browser settings")) { @@ -332,12 +390,19 @@ namespace Atlas::Editor::UI { ImGui::Checkbox("Filter recursively", &filterRecursively); ImGui::SeparatorText("Display"); + ImGui::Checkbox("Show previews", &showPreviews); + ImGui::SetItemTooltip("Shows textures, meshes, materials, prefabs, fonts and audio instead of the icons of their type"); ImGui::SliderFloat("Icon size", &iconSize, minIconSize, maxIconSize, "%.0f px"); ImGui::TextDisabled("Ctrl + mouse wheel over the content also changes the size"); ImGui::EndPopup(); } + if (pinned) { + ImGui::SetCursorPos(ImVec2(region.x - (buttonSize.x + 2.0f * padding), 0.0f)); + RenderPinButton(); + } + } void ContentBrowserWindow::RenderDirectoryContent() { @@ -349,19 +414,30 @@ namespace Atlas::Editor::UI { iconSize = std::clamp(iconSize + ImGui::GetIO().MouseWheel * 8.0f, minIconSize, maxIconSize); } - auto itemSize = iconSize + 2.0f * padding; - auto columnCount = int32_t(totalWidth / itemSize); - columnCount = columnCount <= 0 ? 1 : columnCount; - - float columnSize = totalWidth / float(columnCount); + auto columnCount = 1; + float columnSize = totalWidth; + gridStart = padding; + + // Tiles fill the width with small gaps, the icon size is their smallest size + if (!listView) { + auto available = totalWidth - 2.0f * tileGap; + columnCount = std::max(1, int32_t((available + tileGap) / (iconSize + tileGap))); + tileSize = std::floor((available - tileGap * float(columnCount - 1)) / float(columnCount)); + columnSize = tileSize + tileGap; + gridStart = tileGap; + } if (!std::filesystem::exists(currentDirectory)) { auto message = "Content directory " + Common::Path::Normalize(currentDirectory) + " has been moved or deleted."; - Notifications::Push({ .message = message, .color = vec3(1.0f, 1.0f, 0.0f) }); + Notifications::Push({ .message = message, .type = NotificationType::Warning }); currentDirectory = Loader::AssetLoader::GetDataDirectory(); } - JobSystem::Wait(searchAndFilterJob); + if (searchAndFilterJob.HasFinished() && hasFoundEntries) { + directories.swap(foundDirectories); + files.swap(foundFiles); + hasFoundEntries = false; + } auto dataDirectory = Loader::AssetLoader::GetDataDirectory(); @@ -372,7 +448,7 @@ namespace Atlas::Editor::UI { ImGuiMultiSelectFlags_ClearOnClickVoid, selectionStorage.Size, entryCount); selectionStorage.ApplyRequests(multiSelectionIO); - ImGui::SetCursorPosX(padding); + ImGui::SetCursorPosX(gridStart); int32_t entryIdx = 0; float columnHeight = 0.0f; @@ -381,12 +457,12 @@ namespace Atlas::Editor::UI { if (directory->assetPath.at(0) == '.') continue; - RenderContentEntry(directory->path, directory->assetPath, ContentType::None, + RenderContentEntry(directory->path, directory->assetPath, ContentType::None, 0, 0, entryIdx++, columnCount, columnSize, columnHeight); } for (const auto& file : files) { - RenderContentEntry(file.path, file.assetPath, file.type, + RenderContentEntry(file.path, file.assetPath, file.type, file.size, file.lastWriteTime, entryIdx++, columnCount, columnSize, columnHeight); } @@ -411,6 +487,14 @@ namespace Atlas::Editor::UI { .type = ContentType::Material, }); } + if (ImGui::MenuItem("Material graph")) { + isEditing = true; + files.push_back(Content{ + .path = path, + .assetPath = path, + .type = ContentType::MaterialGraph, + }); + } if (ImGui::MenuItem("Script")) { isEditing = true; files.push_back(Content{ @@ -456,10 +540,9 @@ namespace Atlas::Editor::UI { if (currentDirectory == directory->path) nodeFlags |= ImGuiTreeNodeFlags_Selected; - // Get button size before removing spacing - float buttonSize = ImGui::GetTextLineHeightWithSpacing(); - - ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(-2.0f, 0.0f)); + auto rowPosY = ImGui::GetCursorPosY(); + auto& style = ImGui::GetStyle(); + auto iconSize = ImGui::GetTextLineHeight(); bool nodeOpen = ImGui::TreeNodeEx(directory->name.c_str(), nodeFlags, ""); @@ -467,18 +550,18 @@ namespace Atlas::Editor::UI { currentDirectory = Common::Path::Normalize(directory->path.string()); } - ImGui::SameLine(); - - auto folderIcon = Singletons::icons->Get(IconType::Folder); + auto folderIcon = Singletons::icons->GetTintable(IconType::Folder); auto set = Singletons::imguiWrapper->GetTextureId(&folderIcon); - ImGui::Image(set, ImVec2(buttonSize, buttonSize), ImVec2(0.1f, 0.1f), ImVec2(0.9f, 0.9f)); + ImGui::SameLine(0.0f, 0.0f); + ImGui::SetCursorPosY(rowPosY + style.FramePadding.y); + ImGui::ImageWithBg(set, ImVec2(iconSize, iconSize), ImVec2(0.1f, 0.1f), ImVec2(0.9f, 0.9f), + ImVec4(0.0f, 0.0f, 0.0f, 0.0f), Theme::ContentIcon(ContentType::None)); - ImGui::PopStyleVar(); - - ImGui::SameLine(); - - ImGui::Text("%s", directory->name.c_str()); + ImGui::SameLine(0.0f, style.ItemInnerSpacing.x); + ImGui::SetCursorPosY(rowPosY); + ImGui::AlignTextToFramePadding(); + ImGui::TextUnformatted(directory->name.c_str()); if (nodeOpen) { for (const auto& childDirectory : directory->directories) @@ -489,14 +572,15 @@ namespace Atlas::Editor::UI { } - void ContentBrowserWindow::RenderContentEntry(const std::filesystem::path& path, const std::string& assetPath, - ContentType contentType, int32_t entryIdx, int32_t columnCount, float columnSize, float& columnHeight) { + void ContentBrowserWindow::RenderContentEntry(const std::filesystem::path& path, const std::string& assetPath, ContentType contentType, + uintmax_t fileSize, int64_t lastWriteTime, int32_t entryIdx, int32_t columnCount, float columnSize, float& columnHeight) { bool isDirectory = contentType == ContentType::None; auto filename = Common::Path::GetFileName(assetPath); - ImVec2 buttonSize = ImVec2(iconSize, iconSize); + auto lineHeight = ImGui::GetTextLineHeight(); + ImVec2 buttonSize = listView ? ImVec2(columnSize - 2.0f * padding, lineHeight + 4.0f) : ImVec2(tileSize, GetTileHeight()); auto cursorPos = ImGui::GetCursorPos(); ImGui::BeginGroup(); @@ -508,9 +592,9 @@ namespace Atlas::Editor::UI { Texture::Texture2D iconTexture; if (isDirectory) - iconTexture = Singletons::icons->Get(IconType::Folder); + iconTexture = Singletons::icons->GetTintable(IconType::Folder); else - iconTexture = GetIcon(contentType); + iconTexture = Singletons::contentPreviews->GetIcon(contentType); auto set = Singletons::imguiWrapper->GetTextureId(&iconTexture); bool highlight = assetPath == hightlightPath; @@ -524,7 +608,27 @@ namespace Atlas::Editor::UI { // Add selectable to allow for multi-select bool selected = selectionStorage.Contains((ImGuiID)entryIdx); ImGui::SetNextItemSelectionUserData(entryIdx); + // Tiles draw their own background, hover and selection, the rectangle of the keyboard focus would be around + // the larger area of the selectable + if (!listView) { + ImGui::PushStyleColor(ImGuiCol_Header, ImVec4(0.0f, 0.0f, 0.0f, 0.0f)); + ImGui::PushStyleColor(ImGuiCol_HeaderHovered, ImVec4(0.0f, 0.0f, 0.0f, 0.0f)); + ImGui::PushStyleColor(ImGuiCol_HeaderActive, ImVec4(0.0f, 0.0f, 0.0f, 0.0f)); + ImGui::PushStyleColor(ImGuiCol_NavCursor, ImVec4(0.0f, 0.0f, 0.0f, 0.0f)); + } ImGui::Selectable("##Selectable", &selected, ImGuiSelectableFlags_None, buttonSize); + if (!listView) + ImGui::PopStyleColor(4); + + auto tileMin = ImGui::GetItemRectMin(); + auto tileHovered = ImGui::IsItemHovered(); + // Only after resting on an entry for a moment, moving over the content doesn't open tooltips + auto showTooltip = ImGui::IsItemHovered(ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayNormal | + ImGuiHoveredFlags_NoSharedDelay) && !ImGui::IsDragDropActive() && !isEditing; + + // Files are dragged right away instead of starting a box selection + if (!isDirectory && ImGui::IsItemClicked()) + ImGui::GetCurrentContext()->BoxSelectState.IsStarting = false; if (ImGui::IsItemHovered()) { if (ImGui::IsMouseDoubleClicked(0)) { @@ -532,6 +636,11 @@ namespace Atlas::Editor::UI { nextDirectory = path.string(); else if (contentType == ContentType::Scene) FileImporter::ImportFile(assetRelativePath); + else if (contentType == ContentType::Mesh || contentType == ContentType::Animation || + contentType == ContentType::Material || contentType == ContentType::Prefab || + contentType == ContentType::MaterialGraph || contentType == ContentType::Script || + contentType == ContentType::Shader) + contentToEditPath = assetRelativePath; } } @@ -554,6 +663,14 @@ namespace Atlas::Editor::UI { PopupPanels::isImportScenePopupVisible = true; } + auto hasAssetEditor = contentType == ContentType::Mesh || contentType == ContentType::Material || + contentType == ContentType::MaterialGraph || contentType == ContentType::Prefab || + contentType == ContentType::Script || contentType == ContentType::Shader; + if (!isDirectory && hasAssetEditor && singleSelect && ImGui::MenuItem("Open")) + contentToEditPath = assetRelativePath; + if (!isDirectory && contentType == ContentType::Scene && singleSelect && ImGui::MenuItem("Open")) + FileImporter::ImportFile(assetRelativePath); + // We shouldn't allow the user to delete the root entity if (singleSelect && ImGui::MenuItem("Open externally")) OpenExternally(std::filesystem::absolute(path).string(), isDirectory); @@ -576,9 +693,12 @@ namespace Atlas::Editor::UI { CopyPasteHelper::Copy(copy); } - if (ImGui::MenuItem("Delete")) { - auto paths = GetSelectedPaths(); - FileSystemHelper::Delete(paths); + // Deleting can't be undone, the window asks before anything is removed + if (ImGui::MenuItem("Delete...")) { + pendingDeletePaths = GetSelectedPaths(); + pendingDeleteHasDirectory = std::any_of(pendingDeletePaths.begin(), pendingDeletePaths.end(), + [](const std::string& path) { return std::filesystem::is_directory(path); }); + openDeleteConfirmation = true; } ImGui::EndPopup(); @@ -587,9 +707,33 @@ namespace Atlas::Editor::UI { // Just draw the icon if it is actually visible bool isVisible = ImGui::IsItemVisible(); if (isVisible) { - ImGui::SameLine(); - ImGui::SetCursorPosX(cursorPos.x); - ImGui::Image(set, buttonSize); + ContentPreviews::Preview preview; + auto hasPreview = !isDirectory && showPreviews && + Singletons::contentPreviews->Get(assetRelativePath, contentType, fileSize, lastWriteTime, preview); + + if (listView) { + ImGui::SameLine(); + ImGui::SetCursorPosX(cursorPos.x); + ImGui::SetCursorPosY(cursorPos.y + 3.0f); + auto imageSize = ImVec2(lineHeight, lineHeight); + if (hasPreview) { + RenderPreview(preview, contentType, imageSize, set); + } + else { + ImGui::ImageWithBg(set, imageSize, ImVec2(0.0f, 0.0f), ImVec2(1.0f, 1.0f), + ImVec4(0.0f, 0.0f, 0.0f, 0.0f), Theme::ContentIcon(contentType)); + } + } + else { + auto editingThis = isEditing && editingPath == path; + auto shortened = RenderTile(tileMin, editingThis ? std::string() : filename, contentType, + selected, tileHovered, set, hasPreview ? &preview : nullptr); + if (isDirectory && shortened && showTooltip) + ImGui::SetTooltip("%s", filename.c_str()); + } + + if (!isDirectory && showTooltip) + RenderContentTooltip(filename, contentType, fileSize, hasPreview ? &preview : nullptr, set); } ImGui::PopStyleVar(); @@ -599,7 +743,12 @@ namespace Atlas::Editor::UI { ImGui::PushStyleColor(ImGuiCol_FrameBg, ImVec4(0.0f, 0.0f, 0.0f, 0.0f)); ImGui::PushStyleColor(ImGuiCol_FrameBgActive, ImVec4(0.0f, 0.0f, 0.0f, 0.0f)); - ImGui::SetNextItemWidth(buttonSize.x); + if (listView) + ImGui::SameLine(); + else + ImGui::SetCursorScreenPos(ImVec2(tileMin.x + tileLabelPadding * 0.5f, + tileMin.y + tileSize)); + ImGui::SetNextItemWidth(listView ? columnSize * 0.5f : buttonSize.x - tileLabelPadding); if (editingChanged) { ImGui::SetKeyboardFocusHere(); } @@ -628,38 +777,25 @@ namespace Atlas::Editor::UI { ImGui::PopStyleColor(); ImGui::PopStyleColor(); - } - else if (isVisible) { - // Single centered line, which is truncated if too long. The full name is shown in the tooltip - auto maxWidth = std::min(columnSize - padding, iconSize + 2.0f * padding); - auto label = filename; - bool truncated = ImGui::CalcTextSize(label.c_str()).x > maxWidth; - if (truncated) { - while (!label.empty() && ImGui::CalcTextSize((label + "...").c_str()).x > maxWidth) - label.pop_back(); - label += "..."; - } - auto textWidth = ImGui::CalcTextSize(label.c_str()).x; - auto cursorX = ImGui::GetCursorPosX(); - ImGui::SetCursorPosX(std::max(0.0f, cursorX + (iconSize - textWidth) * 0.5f)); - ImGui::TextUnformatted(label.c_str()); - if (truncated) - ImGui::SetItemTooltip("%s", filename.c_str()); + // The field is inside the tile, the next row starts below the tile + if (!listView) { + ImGui::SetCursorScreenPos(ImVec2(tileMin.x, tileMin.y + buttonSize.y)); + ImGui::Dummy(ImVec2(0.0f, 0.0f)); + } } - else { - // Keep the layout stable for invisible entries - ImGui::NewLine(); + else if (isVisible && listView) { + RenderListColumns(filename, contentType, fileSize, buttonSize.x); } ImGui::PopID(); ImGui::EndGroup(); - // Advance to next column - columnHeight = std::max(ImGui::GetCursorPosY() - cursorPos.y, columnHeight); + // Advance to next column, rows of tiles have the same gap as the columns + columnHeight = std::max(listView ? ImGui::GetCursorPosY() - cursorPos.y : buttonSize.y + tileGap, columnHeight); - ImGui::SetCursorPosX(((entryIdx + 1) % columnCount) * columnSize + padding); + ImGui::SetCursorPosX(((entryIdx + 1) % columnCount) * columnSize + gridStart); if ((entryIdx + 1) % columnCount == 0) { cursorPos.y = cursorPos.y + columnHeight; ImGui::SetCursorPosY(cursorPos.y); @@ -671,75 +807,252 @@ namespace Atlas::Editor::UI { } - bool ContentBrowserWindow::IsValidFileType(const std::string& filename) { + void ContentBrowserWindow::RenderPreview(const ContentPreviews::Preview& preview, ContentType contentType, ImVec2 size, + ImTextureID iconTexture) { - std::string fileType = Common::Path::GetFileType(filename); - std::transform(fileType.begin(), fileType.end(), fileType.begin(), ::tolower); + auto min = ImGui::GetCursorScreenPos(); + ImGui::Dummy(size); - return Content::contentTypeMapping.contains(fileType); + Singletons::contentPreviews->Draw(ImGui::GetWindowDrawList(), preview, contentType, min, + ImVec2(min.x + size.x, min.y + size.y), iconTexture, true); } - Texture::Texture2D& ContentBrowserWindow::GetIcon(const ContentType contentType) { + float ContentBrowserWindow::GetTileHeight() const { - auto& icons = Singletons::icons; + // Two lines for the name, the color of the type is shown by the line below the thumbnail + return tileSize + 1.5f * tileLabelPadding + 2.0f * ImGui::GetTextLineHeight(); - switch (contentType) { - case ContentType::Audio: return icons->Get(IconType::Audio); - case ContentType::Mesh: return icons->Get(IconType::Mesh); - case ContentType::MeshSource: return icons->Get(IconType::MeshSource); - case ContentType::Material: return icons->Get(IconType::Material); - case ContentType::Scene: return icons->Get(IconType::Scene); - case ContentType::Font: return icons->Get(IconType::Font); - case ContentType::Prefab: return icons->Get(IconType::Prefab); - case ContentType::Texture: return icons->Get(IconType::Image); - case ContentType::EnvironmentTexture: return icons->Get(IconType::EnvironmentImage); - case ContentType::Terrain: return icons->Get(IconType::Terrain); - default: return icons->Get(IconType::Document); + } + + bool ContentBrowserWindow::RenderTile(ImVec2 min, const std::string& filename, ContentType contentType, bool selected, + bool hovered, ImTextureID iconTexture, const ContentPreviews::Preview* preview) { + + auto drawList = ImGui::GetWindowDrawList(); + auto isDirectory = contentType == ContentType::None; + auto lineHeight = ImGui::GetTextLineHeight(); + + auto max = ImVec2(min.x + tileSize, min.y + GetTileHeight()); + auto thumbnailMax = ImVec2(min.x + tileSize, min.y + tileSize); + auto labelWidth = tileSize - 2.0f * tileLabelPadding; + + if (isDirectory) { + // Folders have no card, only a background while they are hovered or selected + if (selected || hovered) + drawList->AddRectFilled(min, max, ImGui::GetColorU32(selected ? Theme::Accent(0.2f) : Theme::AssetCardHovered(0.7f)), + tileRounding); + if (selected) + drawList->AddRect(min, max, ImGui::GetColorU32(Theme::Accent(0.8f)), tileRounding, 0, 1.5f); + + auto inset = 0.1f * tileSize; + drawList->AddImage(iconTexture, ImVec2(min.x + inset, min.y + inset), ImVec2(thumbnailMax.x - inset, thumbnailMax.y - inset), + ImVec2(0.0f, 0.0f), ImVec2(1.0f, 1.0f), ImGui::GetColorU32(Theme::ContentIcon(contentType))); + + return RenderTileName(drawList, filename, ImVec2(min.x + tileLabelPadding, thumbnailMax.y + tileLabelPadding * 0.5f), + labelWidth, true); } + // A soft card which lifts with a shadow when hovered, the thumbnail inside is darker such that previews + // without background stand out + if (hovered && !selected) + drawList->AddRectFilled(ImVec2(min.x, min.y + 3.0f), ImVec2(max.x, max.y + 3.0f), ImGui::GetColorU32(Theme::Shadow(0.8f)), tileRounding); + auto cardColor = selected ? Theme::Accent(0.16f) : (hovered ? Theme::AssetCardHovered() : Theme::AssetCard(0.6f)); + drawList->AddRectFilled(min, max, ImGui::GetColorU32(cardColor), tileRounding); + + auto thumbnailMin = ImVec2(min.x + tileThumbnailInset, min.y + tileThumbnailInset); + thumbnailMax = ImVec2(thumbnailMax.x - tileThumbnailInset, thumbnailMax.y - tileThumbnailInset); + auto thumbnailSize = thumbnailMax.x - thumbnailMin.x; + auto thumbnailRounding = tileRounding - 2.0f; + drawList->AddRectFilled(thumbnailMin, thumbnailMax, ImGui::GetColorU32(Theme::AssetThumbnail()), thumbnailRounding); + + if (preview) { + // Images fill the thumbnail, rendered content and shapes have their own margin + Singletons::contentPreviews->Draw(drawList, *preview, contentType, thumbnailMin, thumbnailMax, iconTexture, false, thumbnailRounding); + } + else { + auto inset = ContentPreviews::iconInset * thumbnailSize; + drawList->AddImage(iconTexture, ImVec2(thumbnailMin.x + inset, thumbnailMin.y + inset), + ImVec2(thumbnailMax.x - inset, thumbnailMax.y - inset), ImVec2(0.0f, 0.0f), ImVec2(1.0f, 1.0f), + ImGui::GetColorU32(Theme::ContentIcon(contentType, ContentPreviews::iconAlpha))); + } + + // A thin line in the color of the type along the bottom of the thumbnail + drawList->AddRectFilled(ImVec2(thumbnailMin.x, thumbnailMax.y - tileTypeLineHeight), thumbnailMax, + ImGui::GetColorU32(Theme::ContentTypeColor(contentType)), thumbnailRounding, ImDrawFlags_RoundCornersBottom); + + if (selected) + drawList->AddRect(min, max, ImGui::GetColorU32(Theme::Accent()), tileRounding, 0, 1.5f); + + // The color says what the file is, the name doesn't need the extension + auto extensionStart = filename.find_last_of('.'); + auto name = extensionStart != std::string::npos && extensionStart > 0 ? filename.substr(0, extensionStart) : filename; + auto labelMin = ImVec2(min.x + tileLabelPadding, thumbnailMax.y + tileThumbnailInset + 0.5f * tileLabelPadding); + auto shortened = RenderTileName(drawList, name, labelMin, labelWidth, false); + + return shortened; + } - void ContentBrowserWindow::UpdateFilteredAndSortedDirEntries() { + bool ContentBrowserWindow::RenderTileName(ImDrawList* drawList, const std::string& name, ImVec2 position, float width, bool centered) { - // Don't want to update anything now - if (isEditing) - return; + if (name.empty()) + return false; - auto contentDirectory = ContentDiscovery::GetDirectory(currentDirectory); - if (!contentDirectory) + auto lineHeight = ImGui::GetTextLineHeight(); + + const char* text = name.c_str(); + const char* textEnd = text + name.size(); + + // As much as fits on the first line, the rest goes to the second one. Lines rather break after a separator + // in the second half of the first line, e.g. M_Decal_ | 01. Names of several parts may break inside a part, + // a single word ends with an ellipsis instead of being torn apart + auto isSeparator = [](char character) { return character == '_' || character == '-' || character == ' ' || character == '.'; }; + + auto firstLineEnd = text; + while (firstLineEnd < textEnd) { + unsigned int character; + auto next = firstLineEnd + ImTextCharFromUtf8(&character, firstLineEnd, textEnd); + if (ImGui::CalcTextSize(text, next).x > width) + break; + firstLineEnd = next; + } + if (firstLineEnd == text && text < textEnd) { + unsigned int character; + firstLineEnd += ImTextCharFromUtf8(&character, text, textEnd); + } + if (firstLineEnd < textEnd) { + auto breakAt = static_cast(nullptr); + for (auto separator = firstLineEnd - 1; separator > text + (firstLineEnd - text) / 2; separator--) { + if (isSeparator(*separator)) { + // A dot starts the second line, the others end the first one + breakAt = *separator == '.' ? separator : separator + 1; + break; + } + } + if (!breakAt) + breakAt = std::any_of(text, textEnd, isSeparator) ? firstLineEnd : textEnd; + firstLineEnd = breakAt; + } + + auto shortened = false; + auto renderLine = [&](const char* lineStart, const char* lineEnd, float y) { + auto textSize = ImGui::CalcTextSize(lineStart, lineEnd); + auto lineWidth = std::min(textSize.x, width); + auto x = centered ? position.x + 0.5f * (width - lineWidth) : position.x; + auto lineMax = ImVec2(x + width, y + lineHeight); + ImGui::RenderTextEllipsis(drawList, ImVec2(x, y), lineMax, std::min(lineMax.x, position.x + width), + position.x + width, lineStart, lineEnd, &textSize); + shortened |= textSize.x > width; + }; + + renderLine(text, firstLineEnd, position.y); + if (firstLineEnd < textEnd) + renderLine(firstLineEnd, textEnd, position.y + lineHeight); + + return shortened; + + } + + void ContentBrowserWindow::RenderContentTooltip(const std::string& filename, ContentType contentType, uintmax_t fileSize, + const ContentPreviews::Preview* preview, ImTextureID iconTexture) { + + if (!ImGui::BeginTooltip()) return; - std::string searchQuery = assetSearch; - if (!searchQuery.empty()) { - std::transform(searchQuery.begin(), searchQuery.end(), searchQuery.begin(), ::tolower); + // A larger preview on the background of the thumbnails + if (preview) { + auto size = float(ContentPreviews::slotSize); + auto min = ImGui::GetCursorScreenPos(); + auto max = ImVec2(min.x + size, min.y + size); + ImGui::Dummy(ImVec2(size, size)); + + auto drawList = ImGui::GetWindowDrawList(); + drawList->AddRectFilled(min, max, ImGui::GetColorU32(Theme::AssetThumbnail()), tileRounding); + auto fullPreview = *preview; + fullPreview.alpha = 1.0f; + Singletons::contentPreviews->Draw(drawList, fullPreview, contentType, min, max, iconTexture, false, tileRounding - 2.0f); } - std::vector discoverdFiles; - bool recursively = searchQuery.empty() ? filterRecursively && contentFilter != ContentFilterBits::AllBit : searchRecursively; - SearchDirectory(contentDirectory, discoverdFiles, searchQuery, recursively); + ImGui::TextUnformatted(filename.c_str()); + ImGui::TextColored(Theme::ContentTypeColor(contentType), "%s", GetTypeName(contentType)); + ImGui::SameLine(); + if (fileSize >= 1024 * 1024) + ImGui::TextDisabled("%.1f MB", float(fileSize) / (1024.0f * 1024.0f)); + else + ImGui::TextDisabled("%.1f KB", float(fileSize) / 1024.0f); - std::sort(discoverdFiles.begin(), discoverdFiles.end(), [](const auto& file0, const auto& file1) { - return file0.name < file1.name; - }); + ImGui::EndTooltip(); + + } - if (assetSearch.empty() && !filterRecursively && contentFilter == ContentFilterBits::AllBit) { - directories = contentDirectory->directories; - files = discoverdFiles; + void ContentBrowserWindow::RenderListColumns(const std::string& filename, ContentType contentType, uintmax_t fileSize, float rowWidth) { + + auto startX = ImGui::GetCursorPosX(); + auto lineHeight = ImGui::GetTextLineHeight(); + + // Everything is on the row of the icon, which already moved the cursor to the next line + auto rowY = ImGui::GetCursorPosY() - lineHeight - ImGui::GetStyle().ItemSpacing.y - 1.0f; + auto nameX = startX + lineHeight + ImGui::GetStyle().ItemInnerSpacing.x; + auto typeX = startX + rowWidth * 0.6f; + auto sizeX = startX + rowWidth * 0.85f; + + ImGui::SetCursorPos(ImVec2(nameX, rowY)); + // Files have a tooltip with their preview and name, shortened folder names get one of their own + auto shortened = Widgets::TextEllipsis(filename.c_str(), filename.c_str() + filename.size(), typeX - nameX - padding); + if (shortened && contentType == ContentType::None && ImGui::IsItemHovered(ImGuiHoveredFlags_Stationary | + ImGuiHoveredFlags_DelayNormal | ImGuiHoveredFlags_NoSharedDelay)) + ImGui::SetTooltip("%s", filename.c_str()); + + ImGui::SetCursorPos(ImVec2(typeX, rowY)); + ImGui::TextDisabled("%s", contentType == ContentType::None ? "Folder" : GetTypeName(contentType)); + + if (contentType != ContentType::None) { + ImGui::SetCursorPos(ImVec2(sizeX, rowY)); + if (fileSize >= 1024 * 1024) + ImGui::TextDisabled("%.1f MB", float(fileSize) / (1024.0f * 1024.0f)); + else + ImGui::TextDisabled("%.1f KB", float(fileSize) / 1024.0f); } - else { - files = discoverdFiles; - directories.clear(); + + } + + const char* ContentBrowserWindow::GetTypeName(ContentType contentType) const { + + switch (contentType) { + case ContentType::Audio: return "Audio"; + case ContentType::Mesh: return "Mesh"; + case ContentType::MeshSource: return "Mesh source"; + case ContentType::Material: return "Material"; + case ContentType::Terrain: return "Terrain"; + case ContentType::Scene: return "Scene"; + case ContentType::Script: return "Script"; + case ContentType::Shader: return "Shader"; + case ContentType::Font: return "Font"; + case ContentType::Prefab: return "Prefab"; + case ContentType::Texture: return "Texture"; + case ContentType::EnvironmentTexture: return "Environment texture"; + case ContentType::Animation: return "Animation"; + case ContentType::MaterialGraph: return "Material graph"; + default: return "File"; } } + bool ContentBrowserWindow::IsValidFileType(const std::string& filename) { + + std::string fileType = Common::Path::GetFileType(filename); + std::transform(fileType.begin(), fileType.end(), fileType.begin(), ::tolower); + + return Content::contentTypeMapping.contains(fileType); + + } + void ContentBrowserWindow::SearchDirectory(const Ref& directory, std::vector& contentFiles, - const std::string& searchQuery, bool recursively) { + const std::string& searchQuery, ContentFilter filter, bool recursively) { for (const auto& file : directory->files) { - // Enum class and ContentFilterBits are in same order, so we can just bitshift the content type - if (!((1 << static_cast(file.type)) & contentFilter)) { + // Enum class and ContentFilterBits are in same order, so we can just bitshift the content type. + if (!((1 << static_cast(file.type)) & filter)) { continue; } @@ -752,7 +1065,7 @@ namespace Atlas::Editor::UI { if (recursively) { for (const auto& childDirectory : directory->directories) { - SearchDirectory(childDirectory, contentFiles, searchQuery, true); + SearchDirectory(childDirectory, contentFiles, searchQuery, filter, true); } } @@ -821,6 +1134,12 @@ namespace Atlas::Editor::UI { return; } + if (type == ContentType::MaterialGraph) { + path.replace_extension("aematgraph"); + Loader::MaterialGraphLoader::SaveGraph(MaterialGraph::Graph::CreateDefault(), path.string()); + return; + } + // All the files with empty contents if (type == ContentType::Script) { path.replace_extension("lua"); @@ -829,7 +1148,7 @@ namespace Atlas::Editor::UI { auto fileStream = Loader::AssetLoader::WriteFile(assetRelative, std::ios::out | std::ios::binary); if (!fileStream.is_open()) { Notifications::Push({"Couldn't write file " + - Loader::AssetLoader::GetRelativePath(assetRelative), vec3(1.0f, 0.0f, 0.0f)}); + Loader::AssetLoader::GetRelativePath(assetRelative), NotificationType::Error}); return; } fileStream.close(); diff --git a/src/editor/ui/windows/ContentBrowserWindow.h b/src/editor/ui/windows/ContentBrowserWindow.h index 1cae8d06a..89db32e2a 100644 --- a/src/editor/ui/windows/ContentBrowserWindow.h +++ b/src/editor/ui/windows/ContentBrowserWindow.h @@ -1,9 +1,10 @@ #pragma once -#include "Window.h" +#include "DrawerWindow.h" #include "Singletons.h" #include "Icons.h" #include "ContentDiscovery.h" +#include "ContentPreviews.h" #include "resource/ResourceManager.h" #include "common/Path.h" #include "ImguiExtension/ImguiWrapper.h" @@ -14,7 +15,7 @@ namespace Atlas::Editor::UI { - class ContentBrowserWindow : public Window { + class ContentBrowserWindow : public DrawerWindow { public: explicit ContentBrowserWindow(bool show); @@ -39,7 +40,10 @@ namespace Atlas::Editor::UI { PrefabBit = (1 << 8), TextureBit = (1 << 9), EnvTextureBit = (1 << 10), - AllBit = (1 << 11) - 1 + AnimationBit = (1 << 11), + MaterialGraphBit = (1 << 12), + ShaderBit = (1 << 13), + AllBit = (1 << static_cast(ContentType::None)) - 1 } ContentFilterBits; std::string currentDirectory = Loader::AssetLoader::GetDataDirectory(); @@ -52,8 +56,15 @@ namespace Atlas::Editor::UI { float iconSize = 64.0f; static constexpr float minIconSize = 32.0f; static constexpr float maxIconSize = 160.0f; + + float folderPanelWidth = 220.0f; + bool listView = false; + // Pictures of textures, meshes, materials etc. instead of the icons of their type + bool showPreviews = true; static inline std::string contentToShowPath = ""; + // Mesh, material, prefab or animation the user wants to open in its editor + static inline std::string contentToEditPath = ""; private: struct ContentCopy { @@ -73,17 +84,33 @@ namespace Atlas::Editor::UI { void RenderDirectoryEntry(const Ref& directory); - void RenderContentEntry(const std::filesystem::path& path, const std::string& assetPath, - ContentType contentType, int32_t entryIdx, int32_t columnCount, float columnSize, float& columnHeight); + void RenderContentEntry(const std::filesystem::path& path, const std::string& assetPath, ContentType contentType, + uintmax_t fileSize, int64_t lastWriteTime, int32_t entryIdx, int32_t columnCount, float columnSize, float& columnHeight); - bool IsValidFileType(const std::string& filename); + // The preview fitted into the area of the icon, the icon fades out while the preview fades in + void RenderPreview(const ContentPreviews::Preview& preview, ContentType contentType, ImVec2 size, ImTextureID iconTexture); + + // Files are cards with their preview, a line in the color of their type and their name. Folders only + // have their icon and name. True if the name was shortened + bool RenderTile(ImVec2 min, const std::string& filename, ContentType contentType, bool selected, bool hovered, + ImTextureID iconTexture, const ContentPreviews::Preview* preview); - Texture::Texture2D& GetIcon(const ContentType contentType); + // Up to two lines, true if the name was shortened + bool RenderTileName(ImDrawList* drawList, const std::string& name, ImVec2 position, float width, bool centered); - void UpdateFilteredAndSortedDirEntries(); + float GetTileHeight() const; - void SearchDirectory(const Ref& directory, std::vector& contentFiles, - const std::string& searchQuery, bool recursively); + void RenderContentTooltip(const std::string& filename, ContentType contentType, uintmax_t fileSize, + const ContentPreviews::Preview* preview, ImTextureID iconTexture); + + void RenderListColumns(const std::string& filename, ContentType contentType, uintmax_t fileSize, float rowWidth); + + bool IsValidFileType(const std::string& filename); + + const char* GetTypeName(ContentType contentType) const; + + void SearchDirectory(const Ref& directory, std::vector& contentFiles, + const std::string& searchQuery, ContentFilter filter, bool recursively); void OpenExternally(const std::string& path, bool isDirectory); @@ -91,6 +118,13 @@ namespace Atlas::Editor::UI { void ApplyEdit(ContentType type); + void RenderDeleteConfirmation(); + + // Files and folders the user chose to delete, removed once confirmed + std::vector pendingDeletePaths; + bool pendingDeleteHasDirectory = false; + bool openDeleteConfirmation = false; + std::string nextDirectory; std::string assetSearch; std::string hightlightPath; @@ -98,6 +132,11 @@ namespace Atlas::Editor::UI { std::vector> directories; std::vector files; + // Results of the search job, the window shows the last ones until the job has finished + std::vector> foundDirectories; + std::vector foundFiles; + bool hasFoundEntries = false; + JobGroup searchAndFilterJob{ "Content search and filter", JobPriority::Medium }; ImGuiSelectionBasicStorage selectionStorage; @@ -109,6 +148,15 @@ namespace Atlas::Editor::UI { std::filesystem::path editingPath; const float padding = 8.0f; + // Size of the tiles in this frame, they fill the width of the window + float tileSize = 64.0f; + float gridStart = 8.0f; + + const float tileGap = 6.0f; + const float tileRounding = 6.0f; + const float tileThumbnailInset = 3.0f; + const float tileTypeLineHeight = 2.0f; + const float tileLabelPadding = 6.0f; }; diff --git a/src/editor/ui/windows/DrawerWindow.cpp b/src/editor/ui/windows/DrawerWindow.cpp new file mode 100644 index 000000000..dd3fb1079 --- /dev/null +++ b/src/editor/ui/windows/DrawerWindow.cpp @@ -0,0 +1,191 @@ +#include "DrawerWindow.h" + +#include "../../Singletons.h" +#include "../../Theme.h" +#include "../../Icons.h" +#include "../Widgets.h" + +#include + +#include + +namespace Atlas::Editor::UI { + + bool DrawerWindow::Begin(ImGuiWindowFlags flags) { + + if (pinToggleRequested) { + SetPinned(!pinned); + pinToggleRequested = false; + } + + if (show && !wasShown) + ImGui::SetNextWindowFocus(); + wasShown = show; + + if (pinned) { + openAmount = show ? 1.0f : 0.0f; + return Window::Begin(flags); + } + + auto step = ImGui::GetIO().DeltaTime / animationTime; + openAmount = std::clamp(openAmount + (show ? step : -step), 0.0f, 1.0f); + if (openAmount <= 0.0f) + return false; + + auto viewport = ImGui::GetMainViewport(); + auto drawerHeight = std::clamp(height, minHeight, std::max(viewport->WorkSize.y - 2.0f * margin, minHeight)); + + // Ease out, the drawer gets slower towards its final height + auto invOpenAmount = 1.0f - openAmount; + auto currentHeight = std::max(drawerHeight * (1.0f - invOpenAmount * invOpenAmount * invOpenAmount), 1.0f); + + ImGui::SetNextWindowPos(ImVec2(viewport->WorkPos.x + margin, + viewport->WorkPos.y + viewport->WorkSize.y - currentHeight - margin)); + ImGui::SetNextWindowSize(ImVec2(viewport->WorkSize.x - 2.0f * margin, currentHeight)); + + flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoMove | + ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoDocking | ImGuiWindowFlags_NoSavedSettings | + ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse; + + ImGui::PushStyleVar(ImGuiStyleVar_WindowMinSize, ImVec2(1.0f, 1.0f)); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(10.0f, 4.0f)); + auto visible = ImGui::Begin(GetNameID(), nullptr, flags); + ImGui::PopStyleVar(2); + + if (!visible) { + ImGui::End(); + return false; + } + + RenderHeader(); + CloseIfLeft(); + + return true; + + } + + void DrawerWindow::SetPinned(bool pinned) { + + this->pinned = pinned; + requestDocking = pinned; + show = pinned || show; + // An unpinned window opens as a drawer, which closes the other drawer + if (!pinned) + openAmount = 0.0f; + + } + + bool DrawerWindow::RenderPinButton() { + + auto& icon = Singletons::icons->Get(pinned ? IconType::PinFilled : IconType::Pin); + auto tooltip = pinned ? "Undock, the window opens as a drawer from the status bar" : + "Dock in layout, the window stays open"; + + if (!Widgets::ToolbarIconButton("Pin button", icon, tooltip)) + return false; + + pinToggleRequested = true; + return true; + + } + + float DrawerWindow::GetPinButtonWidth() const { + + return ImGui::GetTextLineHeight() + 2.0f * ImGui::GetStyle().FramePadding.x; + + } + + void DrawerWindow::TakeOver(DrawerWindow& drawer) { + + openAmount = std::max(openAmount, drawer.openAmount); + drawer.openAmount = 0.0f; + drawer.show = false; + drawer.wasShown = false; + + } + + void DrawerWindow::RenderHeader() { + + auto window = ImGui::GetCurrentWindow(); + auto drawList = ImGui::GetWindowDrawList(); + auto pos = window->Pos; + auto size = window->Size; + + // Soft shadow on the layout below to lift the drawer from it + const float shadowSize = 14.0f; + auto rounding = ImGui::GetStyle().WindowRounding; + auto shadowColor = ImGui::GetColorU32(Theme::Shadow()); + drawList->PushClipRectFullScreen(); + drawList->AddRectFilledMultiColor(ImVec2(pos.x + rounding, pos.y - shadowSize), + ImVec2(pos.x + size.x - rounding, pos.y), 0, 0, shadowColor, shadowColor); + drawList->PopClipRect(); + + // The top edge resizes the drawer + const float handleHeight = 8.0f; + ImGui::SetCursorScreenPos(pos); + ImGui::InvisibleButton("Drawer resize handle", ImVec2(size.x, handleHeight)); + auto handleActive = ImGui::IsItemActive(); + auto handleHovered = ImGui::IsItemHovered(); + if (handleActive) + height = size.y - ImGui::GetIO().MouseDelta.y; + if (handleActive || handleHovered) + ImGui::SetMouseCursor(ImGuiMouseCursor_ResizeNS); + + const float gripWidth = 36.0f; + auto gripColor = handleActive || handleHovered ? Theme::Accent() : Theme::TextMuted(0.5f); + auto gripCenter = pos.x + size.x * 0.5f; + drawList->AddRectFilled(ImVec2(gripCenter - gripWidth * 0.5f, pos.y + 3.0f), + ImVec2(gripCenter + gripWidth * 0.5f, pos.y + 6.0f), ImGui::GetColorU32(gripColor), 2.0f); + + auto startX = ImGui::GetStyle().WindowPadding.x; + ImGui::SetCursorPos(ImVec2(startX, handleHeight)); + ImGui::AlignTextToFramePadding(); + ImGui::TextUnformatted(name.c_str()); + + auto& style = ImGui::GetStyle(); + ImGui::SameLine(ImGui::GetWindowContentRegionMax().x - 2.0f * GetPinButtonWidth() - style.ItemSpacing.x); + RenderPinButton(); + + ImGui::SameLine(); + if (Widgets::ToolbarIconButton("Close drawer", Singletons::icons->Get(IconType::ArrowDown), "Close (Esc)")) + show = false; + + ImGui::Separator(); + + } + + void DrawerWindow::CloseIfLeft() { + + // A drawer which replaced another one is fully open right away, the click that opened it doesn't count + if (!show || openAmount < 1.0f || ImGui::IsWindowAppearing()) + return; + + auto window = ImGui::GetCurrentWindow(); + auto& g = *ImGui::GetCurrentContext(); + auto& io = ImGui::GetIO(); + + // Dragged content gets the layout free as soon as it leaves the drawer, such that it can be dropped there + if (ImGui::IsDragDropActive()) { + auto isSource = g.ActiveIdWindow && g.ActiveIdWindow->RootWindow == window; + if (isSource && !window->Rect().Contains(io.MousePos)) + show = false; + return; + } + + if (ImGui::IsPopupOpen(nullptr, ImGuiPopupFlags_AnyPopupId)) + return; + + auto clicked = ImGui::IsMouseClicked(ImGuiMouseButton_Left) || ImGui::IsMouseClicked(ImGuiMouseButton_Right) || + ImGui::IsMouseClicked(ImGuiMouseButton_Middle); + auto hovered = ImGui::IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows | + ImGuiHoveredFlags_AllowWhenBlockedByActiveItem | ImGuiHoveredFlags_AllowWhenBlockedByPopup); + if (clicked && !hovered) + show = false; + + auto focused = ImGui::IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows); + if (focused && !io.WantTextInput && ImGui::IsKeyPressed(ImGuiKey_Escape, false)) + show = false; + + } + +} diff --git a/src/editor/ui/windows/DrawerWindow.h b/src/editor/ui/windows/DrawerWindow.h new file mode 100644 index 000000000..f3694c9ff --- /dev/null +++ b/src/editor/ui/windows/DrawerWindow.h @@ -0,0 +1,48 @@ +#pragma once + +#include "Window.h" + +namespace Atlas::Editor::UI { + + // Slides up from the status bar and closes when the user continues elsewhere, pinned it stays docked + class DrawerWindow : public Window { + + public: + DrawerWindow(const std::string& name, bool show) : Window(name, show) {} + + bool Begin(ImGuiWindowFlags flags = 0); + + void SetPinned(bool pinned); + + // Toggles between the drawer and the window docked in the layout, a docked window shows it in its toolbar + bool RenderPinButton(); + + float GetPinButtonWidth() const; + + // Replaces an open drawer without playing the animations of both + void TakeOver(DrawerWindow& drawer); + + bool IsVisible() const { return openAmount > 0.0f; } + + bool IsOpening() const { return show && !pinned && openAmount < 1.0f; } + + bool pinned = false; + float height = 420.0f; + + private: + void RenderHeader(); + + void CloseIfLeft(); + + float openAmount = 0.0f; + bool wasShown = false; + // Applied before the window begins, it docks or undocks the window + bool pinToggleRequested = false; + + const float minHeight = 160.0f; + const float margin = 6.0f; + const float animationTime = 0.14f; + + }; + +} diff --git a/src/editor/ui/windows/GeometryBrushWindow.cpp b/src/editor/ui/windows/GeometryBrushWindow.cpp index 586b6f659..947f69e82 100644 --- a/src/editor/ui/windows/GeometryBrushWindow.cpp +++ b/src/editor/ui/windows/GeometryBrushWindow.cpp @@ -42,25 +42,32 @@ namespace Atlas::Editor::UI { void GeometryBrushWindow::RenderBrushSettings(const Ref& activeSceneWindow) { - if (!activeSceneWindow) { + if (!activeSceneWindow) Widgets::Callout("Open a scene to use the geometry brush.", Theme::Warning()); - } - else { - auto scene = activeSceneWindow->scene; - ImGui::TextDisabled("Target scene"); - ImGui::SameLine(); - ImGui::TextUnformatted(scene->name.c_str()); - } - ImGui::Checkbox("Enable", &brushEnabled); + if (Widgets::BeginProperties("Brush")) { + if (activeSceneWindow) { + Widgets::PropertyLabel("Target scene"); + ImGui::AlignTextToFramePadding(); + ImGui::TextUnformatted(SceneWindow::GetSceneLabel(activeSceneWindow->scene).c_str()); + } + + Widgets::PropertyLabel("Enable"); + ImGui::Checkbox("##Enable", &brushEnabled); + + const char* brushTypes[] = { "Create", "Delete" }; + int32_t brushSelection = static_cast(brushType); + Widgets::PropertyLabel("Type"); + Widgets::SegmentedControl("##Type", brushSelection, brushTypes, IM_ARRAYSIZE(brushTypes)); + brushType = static_cast(brushSelection); - const char* brushTypes[] = { "Create", "Delete" }; - int32_t brushSelection = static_cast(brushType); - Widgets::SegmentedControl("Type", brushSelection, brushTypes, IM_ARRAYSIZE(brushTypes)); - brushType = static_cast(brushSelection); + Widgets::PropertyLabel("Radius"); + ImGui::DragFloat("##Brush radius", &brushRadius, 0.5f, 0.5f, 1000.0f); + Widgets::PropertyLabel("Only query terrain"); + ImGui::Checkbox("##Only query terrain", &brushOnlyQueryTerrain); - ImGui::DragFloat("Brush radius", &brushRadius, 0.5f, 0.5f, 1000.0f); - ImGui::Checkbox("Only query terrain", &brushOnlyQueryTerrain); + Widgets::EndProperties(); + } // The delete brush has no further settings if (brushType == BrushType::Create) @@ -113,10 +120,15 @@ namespace Atlas::Editor::UI { ImGui::SeparatorText("Placement"); - ImGui::DragFloat("Brush ray length", &brushRayLength, 0.5f, 0.5f, 1000.0f); - ImGui::DragInt("Brush drop rate (per second)", &brushDropRate, 1.0f, 1, 100000); - - ImGui::Checkbox("Align to surface", &brushAlignToSurface); + if (Widgets::BeginProperties("Placement")) { + Widgets::PropertyLabel("Ray length"); + ImGui::DragFloat("##Brush ray length", &brushRayLength, 0.5f, 0.5f, 1000.0f); + Widgets::PropertyLabel("Drop rate", "Entities placed per second while the brush is held"); + ImGui::DragInt("##Brush drop rate", &brushDropRate, 1.0f, 1, 100000, "%d / s"); + Widgets::PropertyLabel("Align to surface"); + ImGui::Checkbox("##Align to surface", &brushAlignToSurface); + Widgets::EndProperties(); + } } @@ -178,12 +190,12 @@ namespace Atlas::Editor::UI { target.valid = true; } - activeSceneWindow->viewportPanel.primitiveBatchWrapper.RenderLineSphere(hitPosition, - brushRadius, vec3(1.0f), true); + activeSceneWindow->viewportPanel.primitiveBatchWrapper.GetBatch(true)->AddLineSphere(hitPosition, + brushRadius, vec3(1.0f)); } else if (rayCastResult.valid && !rayCastResult.IsNormalValid()) { - activeSceneWindow->viewportPanel.primitiveBatchWrapper.RenderLineSphere(hitPosition, - brushRadius, vec3(1.0f, 0.0f, 0.0f), true); + activeSceneWindow->viewportPanel.primitiveBatchWrapper.GetBatch(true)->AddLineSphere(hitPosition, + brushRadius, vec3(1.0f, 0.0f, 0.0f)); } } @@ -214,9 +226,6 @@ namespace Atlas::Editor::UI { auto scene = brushEntity.GetScene(); - if (!parentEntity.HasComponent()) - parentEntity.AddComponent(); - auto decomposition = brushEntity.GetComponent().Decompose(); Scene::SceneQueryComponents queryComponent = Scene::SceneQueryComponentBits::AllComponentsBit; @@ -243,8 +252,8 @@ namespace Atlas::Editor::UI { if (brushAlignToSurface) { vec3 N = rayCastResult.normal; - glm::vec3 up = glm::vec3(0.0f, 1.0f, 0.0f); - glm::quat rotation = glm::rotation(up, glm::normalize(N)); + vec3 up = vec3(0.0f, 1.0f, 0.0f); + quat rotation = glm::rotation(up, glm::normalize(N)); rot = glm::toMat4(rotation); } @@ -256,15 +265,11 @@ namespace Atlas::Editor::UI { matrix = glm::scale(matrix, decomposition.scale); auto entity = scene->DuplicateEntity(brushEntity); + entity.SetParent(parentEntity); - auto& transformComponent = entity.GetComponent(); - transformComponent.Set(matrix); - - parentEntity.GetComponent().AddChild(entity); - - // Ray cast result is in global space, so need to bring transform to valid local one - transformComponent.globalMatrix = matrix; - transformComponent.ReconstructLocalMatrix(parentEntity); + // Ray cast result is in global space + entity.GetComponent().SetGlobal(matrix, parentEntity); + activeSceneWindow->hasUnsavedChanges = true; } } @@ -292,6 +297,7 @@ namespace Atlas::Editor::UI { continue; scene->DestroyEntity(entity, false); + activeSceneWindow->hasUnsavedChanges = true; } } diff --git a/src/editor/ui/windows/LogWindow.cpp b/src/editor/ui/windows/LogWindow.cpp index 26bd4076c..35b54635c 100644 --- a/src/editor/ui/windows/LogWindow.cpp +++ b/src/editor/ui/windows/LogWindow.cpp @@ -12,6 +12,12 @@ namespace Atlas::Editor::UI { + void LogWindow::Update() { + + UpdateLines(); + + } + void LogWindow::Render() { if (!Begin()) @@ -34,8 +40,9 @@ namespace Atlas::Editor::UI { auto clearWidth = ImGui::CalcTextSize("Clear").x + 2.0f * style.FramePadding.x; auto autoScrollWidth = ImGui::GetFrameHeight() + style.ItemInnerSpacing.x + ImGui::CalcTextSize("Auto-scroll").x; auto selectedWidth = selection.Size > 0 ? ImGui::CalcTextSize("00000 selected").x + style.ItemSpacing.x : 0.0f; + auto pinWidth = pinned ? GetPinButtonWidth() + style.ItemSpacing.x : 0.0f; auto searchWidth = ImGui::GetContentRegionAvail().x - copyWidth - clearWidth - autoScrollWidth - - selectedWidth - 3.0f * style.ItemSpacing.x; + selectedWidth - pinWidth - 3.0f * style.ItemSpacing.x; ImGui::SetNextItemWidth(std::max(searchWidth, 50.0f)); ImGui::InputTextWithHint("##Log search", "Search log...", &logSearch); @@ -57,12 +64,16 @@ namespace Atlas::Editor::UI { ImGui::SameLine(); ImGui::TextDisabled("%d selected", selection.Size); } + + // A docked log can be turned back into a drawer + if (pinned) { + ImGui::SameLine(ImGui::GetWindowContentRegionMax().x - GetPinButtonWidth()); + RenderPinButton(); + } } ImGui::Separator(); - UpdateLines(); - if (copyRequested) CopyLines(selection.Size > 0); @@ -108,6 +119,17 @@ namespace Atlas::Editor::UI { // Full width selectable in the background, the text is drawn on top of it auto rowPos = ImGui::GetCursorPos(); + + // Problems stand out while scrolling through a long log + if (entry.type != Atlas::Log::Type::TYPE_MESSAGE) { + auto rowScreenPos = ImGui::GetCursorScreenPos(); + auto rowEnd = ImVec2(rowScreenPos.x + ImGui::GetContentRegionAvail().x, rowScreenPos.y + lineHeight); + auto isError = entry.type == Atlas::Log::Type::TYPE_ERROR; + auto drawList = ImGui::GetWindowDrawList(); + drawList->AddRectFilled(rowScreenPos, rowEnd, ImGui::GetColorU32(isError ? Theme::Error(0.1f) : Theme::Warning(0.1f))); + drawList->AddRectFilled(rowScreenPos, ImVec2(rowScreenPos.x + 2.0f, rowEnd.y), ImGui::GetColorU32(isError ? errorColor : warningColor)); + } + ImGui::SetNextItemSelectionUserData(i); ImGui::Selectable("##Line", selection.Contains(line.id), ImGuiSelectableFlags_AllowOverlap, ImVec2(0.0f, lineHeight)); @@ -176,12 +198,15 @@ namespace Atlas::Editor::UI { void LogWindow::UpdateLines() { // A different filter shows different lines, so the lines and the selection have to be rebuilt - auto filterState = logSearch + (showMessages ? "1" : "0") + (showWarnings ? "1" : "0") + (showErrors ? "1" : "0"); - if (filterState != lastFilterState) { - lastFilterState = filterState; - lowerSearch = logSearch; - std::transform(lowerSearch.begin(), lowerSearch.end(), lowerSearch.begin(), ::tolower); - linesDirty = true; + if (show) { + auto filterState = logSearch + (showMessages ? "1" : "0") + (showWarnings ? "1" : "0") + (showErrors ? "1" : "0"); + if (filterState != lastFilterState) { + lastFilterState = filterState; + lowerSearch = logSearch; + std::transform(lowerSearch.begin(), lowerSearch.end(), lowerSearch.begin(), ::tolower); + linesDirty = true; + } + unseenWarningCount = unseenErrorCount = 0; } // Cheap check for new entries, only these are copied @@ -199,9 +224,22 @@ namespace Atlas::Editor::UI { } for (size_t i = skip; i < newEntries.size(); i++) { + const auto& entry = newEntries[i]; + if (entry.type != Atlas::Log::Type::TYPE_MESSAGE && !show) { + unseenWarningCount += entry.type == Atlas::Log::Type::TYPE_WARNING ? 1 : 0; + unseenErrorCount += entry.type == Atlas::Log::Type::TYPE_ERROR ? 1 : 0; + } + if (entry.type != Atlas::Log::Type::TYPE_MESSAGE) { + lastProblem = entry.message.substr(0, entry.message.find('\n')); + lastProblemIsError = entry.type == Atlas::Log::Type::TYPE_ERROR; + } + cachedEntries.push_back(std::move(newEntries[i])); - if (!linesDirty) + // The lines of a hidden log are only built once it is shown again + if (!linesDirty && show) AppendLines(firstNewIdx + i); + else + linesDirty = true; } // Trim in batches, every trim needs a rebuild of the lines @@ -213,7 +251,7 @@ namespace Atlas::Editor::UI { } } - if (linesDirty) + if (linesDirty && show) RebuildLines(); } diff --git a/src/editor/ui/windows/LogWindow.h b/src/editor/ui/windows/LogWindow.h index ff6451fbe..54507108f 100644 --- a/src/editor/ui/windows/LogWindow.h +++ b/src/editor/ui/windows/LogWindow.h @@ -1,6 +1,6 @@ #pragma once -#include "Window.h" +#include "DrawerWindow.h" #include "Log.h" #include @@ -8,13 +8,24 @@ namespace Atlas::Editor::UI { - class LogWindow : public Window { + class LogWindow : public DrawerWindow { public: - explicit LogWindow(bool show) : Window("Log", show) {} + explicit LogWindow(bool show) : DrawerWindow("Log", show) { height = 320.0f; } + + // Keeps the entry counts up to date while the drawer is closed + void Update(); void Render(); + // Warnings and errors the user hasn't seen, because the log wasn't open + int32_t GetUnseenWarningCount() const { return unseenWarningCount; } + int32_t GetUnseenErrorCount() const { return unseenErrorCount; } + + // First line of the newest warning or error + const std::string& GetLastProblem() const { return lastProblem; } + bool IsLastProblemError() const { return lastProblemIsError; } + private: // One displayed line. Multi-line messages are split, such that every line has the same height struct Line { @@ -54,6 +65,11 @@ namespace Atlas::Editor::UI { int32_t messageCount = 0; int32_t warningCount = 0; int32_t errorCount = 0; + int32_t unseenWarningCount = 0; + int32_t unseenErrorCount = 0; + + std::string lastProblem; + bool lastProblemIsError = false; std::string logSearch; std::string lowerSearch; diff --git a/src/editor/ui/windows/MaterialEditorWindow.cpp b/src/editor/ui/windows/MaterialEditorWindow.cpp new file mode 100644 index 000000000..316408926 --- /dev/null +++ b/src/editor/ui/windows/MaterialEditorWindow.cpp @@ -0,0 +1,598 @@ +#include "MaterialEditorWindow.h" + +#include "../../DataCreator.h" +#include "../../Notifications.h" +#include "../../Singletons.h" +#include "../../Theme.h" +#include "../Widgets.h" + +#include "loader/AssetLoader.h" +#include "loader/MaterialGraphLoader.h" +#include "materialgraph/Baker.h" +#include "materialgraph/MaterialGraphSerializer.h" +#include "mesh/MeshSerializer.h" +#include "loader/MeshLoader.h" +#include "loader/MaterialLoader.h" + +#include +#include +#include +#include +#include +#include + +namespace Atlas::Editor::UI { + + static const char* previewMeshNames[] = { "Detailed sphere", "Sphere", "Capsule", "Wall" }; + static const char* previewMeshPaths[] = { "", "meshes/chromesphere.aemesh", "meshes/capsule.aemesh", "meshes/metallicwall.aemesh" }; + + MaterialEditorWindow::MaterialEditorWindow(ResourceHandle material, bool show) : + AssetEditorWindow(material.IsValid() ? material.GetResource()->GetFileName() : "No material", show), material(material) { + + Init(); + + } + + MaterialEditorWindow::MaterialEditorWindow(ResourceHandle graph, bool show) : + AssetEditorWindow(graph.IsValid() ? graph.GetResource()->GetFileName() : "No graph", show), + material(ResourceHandle(CreateRef())), editedGraph(graph) { + + material->graph = graph; + Init(); + + } + + MaterialEditorWindow::~MaterialEditorWindow() { + + JobSystem::Wait(graphUsersJob); + + if (material.IsLoaded() && material->HasGraph()) + material->graph->blockingPipelineUsers--; + + } + + void MaterialEditorWindow::Init() { + + LoadPreviewMesh(); + + if (material.IsLoaded() && material->HasGraph()) { + material->graph->blockingPipelineUsers++; + FindOtherUsers(); + } + + if (material.IsLoaded() && !material->graphBake.meshPath.empty()) { + bakeMesh = ResourceManager::GetOrLoadResourceWithLoaderAsync(material->graphBake.meshPath, ResourceOrigin::User, + Loader::MeshLoader::LoadMesh, true); + } + + } + + void MaterialEditorWindow::LoadPreviewMesh() { + + previewMesh = ResourceHandle(previewMeshIdx == 0 ? DataCreator::CreateSphere(material, 128, 192) : + Loader::MeshLoader::LoadMesh(previewMeshPaths[previewMeshIdx], true)); + + previewMesh->data.materials = { material }; + for (auto& subData : previewMesh->data.subData) { + subData.material = material; + subData.materialIdx = 0; + } + + } + + void MaterialEditorWindow::Save() { + + if (!material.IsLoaded()) + return; + + if (material->HasGraph() && !material->graph.IsGenerated()) { + Loader::MaterialGraphLoader::SaveGraph(material->graph.Get(), material->graph.GetResource()->path); + graphPanel.modified = false; + } + + if (material.IsGenerated()) { + Notifications::Push({ .message = "Saved material graph " + editedGraph.GetResource()->GetFileName() }); + return; + } + + Loader::MaterialLoader::SaveMaterial(material.Get(), material.GetResource()->path); + Notifications::Push({ .message = "Saved material " + material.GetResource()->GetFileName() }); + + } + + std::string MaterialEditorWindow::GetAssetPath() const { + + if (editedGraph.IsValid()) + return editedGraph.GetResource()->path; + + return material.IsValid() ? material.GetResource()->path : ""; + + } + + bool MaterialEditorWindow::IsReady() const { + + return material.IsLoaded() && (!editedGraph.IsValid() || editedGraph.IsLoaded()); + + } + + Scene::Entity MaterialEditorWindow::CreatePreviewEntity() { + + return scene->CreatePrefab(previewMesh, false); + + } + + Volume::AABB MaterialEditorWindow::GetBounds() const { + + return previewMesh->data.aabb; + + } + + void MaterialEditorWindow::RenderProperties() { + + RenderHeading("Saves the material and its graph (Ctrl+S)"); + + // Path tracing doesn't run graphs, the preview would only show the values for ray tracing + viewportPanel.allowPathTracing = !material->HasGraph(); + + if (Widgets::SectionHeader("Material graph", ImGuiTreeNodeFlags_DefaultOpen)) + RenderGraphSection(); + + auto compiled = material->HasGraph() ? material->graph->GetCompiled() : nullptr; + auto replacesSurface = compiled && compiled->valid && compiled->hasSurface; + + if (replacesSurface && Widgets::SectionHeader("Bake for ray tracing", ImGuiTreeNodeFlags_DefaultOpen)) + RenderBakeSection(*compiled); + + if (Widgets::SectionHeader(replacesSurface ? "Properties for ray tracing" : "Properties", ImGuiTreeNodeFlags_DefaultOpen)) { + if (replacesSurface) { + Widgets::Callout("The graph describes the surface. Ray traced reflections, global illumination and shadows " + "don't run graphs, they use these values instead.", Theme::Accent()); + } + + materialPanel.Render(Singletons::imguiWrapper, material.Get(), [&](ResourceHandle texture) { + return textureSelectionPanel.Render(texture); + }); + textureSelectionPanel.Reset(); + } + + // Just update the pipelines regardless of any change, as in the mesh component panel + previewMesh->UpdatePipelines(); + + } + + void MaterialEditorWindow::RenderPanels() { + + // Changes from scripts are compiled like the ones of the panel, the history notices them by the state + if (material.IsLoaded() && material->HasGraph() && material->graph->revision != compiledRevision) { + compiledRevision = material->graph->revision; + material->graph->Compile(); + changedOutside = true; + } + + ImGui::Begin(graphPanelWindow.GetNameID()); + + graphPanelWindow.isFocused = ImGui::IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows); + + if (graphPanel.maximized && material->HasGraph()) { + ImGui::TextDisabled("The graph is maximized"); + } + else if (material->HasGraph()) { + RenderGraphCanvas(); + } + else { + ImGui::TextDisabled("This material has no graph, its surface comes from the properties"); + if (!editedGraph.IsValid()) { + ImGui::Spacing(); + Theme::PushPrimaryButton(); + if (ImGui::Button("Create material graph")) + CreateGraph(); + Theme::PopPrimaryButton(); + } + } + + ImGui::End(); + + // Covers the panels of this window only, not the whole editor + if (graphPanel.maximized && material->HasGraph()) { + ImGui::SetNextWindowPos(dockSpacePos); + ImGui::SetNextWindowSize(dockSpaceSize); + ImGui::SetNextWindowViewport(dockSpaceViewport); + + auto name = "Material graph##Maximized" + std::string(graphPanelWindow.GetNameID()); + ImGui::Begin(name.c_str(), nullptr, ImGuiWindowFlags_NoDocking | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoMove | + ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings); + + graphPanelWindow.isFocused = ImGui::IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows); + RenderGraphCanvas(); + + ImGui::End(); + } + + } + + void MaterialEditorWindow::RenderGraphCanvas() { + + RenderSharedGraphWarning(); + + if (graphPanel.Render(material->graph, editedGraph.IsValid() ? nullptr : material.Get().get())) + UpdateMeshesOfGraph(); + + } + + void MaterialEditorWindow::RenderSharedGraphWarning() { + + if (!graphUsers || !graphUsers->finished) + return; + + // The button below replaces graphUsers + auto currentUsers = graphUsers; + + const auto& users = currentUsers->materials; + if (users.empty()) + return; + + std::string names; + const size_t maxNames = 3; + for (size_t i = 0; i < std::min(users.size(), maxNames); i++) + names += (i ? ", " : "") + std::filesystem::path(users[i]).stem().string(); + if (users.size() > maxNames) + names += " and " + std::to_string(users.size() - maxNames) + " more"; + + auto text = (editedGraph.IsValid() ? "Used by " + std::to_string(users.size()) + (users.size() == 1 ? " material: " : " materials: ") : + std::to_string(users.size()) + (users.size() == 1 ? " other material uses" : " other materials use") + " this graph: ") + names + + ". Changing nodes changes all of them. Parameter values belong to each material."; + + Widgets::Callout(text.c_str(), Theme::Warning()); + if (ImGui::IsItemHovered() && users.size() > maxNames) { + ImGui::BeginTooltip(); + for (const auto& user : users) + ImGui::TextUnformatted(user.c_str()); + ImGui::EndTooltip(); + } + + if (!editedGraph.IsValid()) { + if (ImGui::Button("Make a copy for this material")) + MakeGraphUnique(); + ImGui::SetItemTooltip("This material gets its own graph file, the other materials keep the current one"); + } + + } + + void MaterialEditorWindow::FindOtherUsers() { + + JobSystem::Wait(graphUsersJob); + + graphUsers = CreateRef(); + + if (!material.IsLoaded() || !material->graph.IsValid() || material->graph.IsGenerated()) + return; + + auto graphPath = material->graph.GetResource()->path; + auto ownPath = material.IsGenerated() ? std::string() : material.GetResource()->path; + + // Materials which are changed and aren't saved yet only know the current state + std::vector loaded; + for (const auto& loadedMaterial : ResourceManager::GetResources()) { + if (!loadedMaterial.IsLoaded() || loadedMaterial.IsGenerated() || loadedMaterial.GetResource()->path == ownPath) + continue; + if (loadedMaterial->graph.IsValid() && !loadedMaterial->graph.IsGenerated() && loadedMaterial->graph.GetResource()->path == graphPath) + loaded.push_back(loadedMaterial.GetResource()->path); + } + + JobSystem::Execute(graphUsersJob, [users = graphUsers, graphPath, ownPath, loaded = std::move(loaded)](JobData&) { + namespace fs = std::filesystem; + + auto root = fs::path(Loader::AssetLoader::GetAssetDirectory()); + auto fileName = fs::path(graphPath).filename().string(); + auto materials = loaded; + + std::error_code error; + for (auto iter = fs::recursive_directory_iterator(root, fs::directory_options::skip_permission_denied, error); + !error && iter != fs::recursive_directory_iterator(); iter.increment(error)) { + const auto& path = iter->path(); + + if (iter->is_directory(error)) { + auto name = path.filename().string(); + if (!name.empty() && name[0] == '.') + iter.disable_recursion_pending(); + continue; + } + + if (path.extension() != ".aematerial") + continue; + + std::ifstream file(path); + std::stringstream content; + content << file.rdbuf(); + auto text = content.str(); + + // Most materials don't have a graph, parsing them isn't needed + if (text.find(fileName) == std::string::npos) + continue; + + auto relative = fs::relative(path, root, error).generic_string(); + if (relative == ownPath || std::find(materials.begin(), materials.end(), relative) != materials.end()) + continue; + + auto j = json::parse(text, nullptr, false); + if (j.is_discarded() || !j.contains("graphPath")) + continue; + + auto reference = j["graphPath"].get(); + // References inside of packages are relative to the file + auto resolved = reference.starts_with(".") ? fs::path(relative).parent_path() / reference : fs::path(reference); + if (resolved.lexically_normal().generic_string() == graphPath) + materials.push_back(relative); + } + + users->materials = std::move(materials); + users->finished = true; + }); + + } + + void MaterialEditorWindow::MakeGraphUnique() { + + auto directory = std::filesystem::path(material.GetResource()->path).parent_path(); + auto stem = std::filesystem::path(material.GetResource()->path).stem().string(); + + auto path = (directory / (stem + ".aematgraph")).generic_string(); + int32_t counter = 1; + while (std::filesystem::exists(Loader::AssetLoader::GetFullPath(path))) + path = (directory / (stem + "_" + std::to_string(counter++) + ".aematgraph")).generic_string(); + + auto graph = CreateRef(*material->graph.Get()); + graph->name = stem; + graph->Compile(); + Loader::MaterialGraphLoader::SaveGraph(graph, path); + + AttachGraph(ResourceManager::AddResource(path, ResourceOrigin::User, graph)); + + Notifications::Push({ .message = "This material now has its own graph " + std::filesystem::path(path).filename().string() + + ", save the material to keep that" }); + + } + + void MaterialEditorWindow::DockPanels(ImGuiID side, ImGuiID bottom) { + + if (bottom) + ImGui::DockBuilderDockWindow(graphPanelWindow.GetNameID(), bottom); + + } + + bool MaterialEditorWindow::IsPanelFocused() const { + + return graphPanelWindow.isFocused; + + } + + bool MaterialEditorWindow::AllowsViewportShortcuts() const { + + return !graphPanelWindow.isFocused; + + } + + void MaterialEditorWindow::RenderViewportSettings() { + + ImGui::SeparatorText("Preview"); + if (ImGui::Combo("Mesh", &previewMeshIdx, previewMeshNames, IM_ARRAYSIZE(previewMeshNames))) { + LoadPreviewMesh(); + if (scene) { + scene->DestroyEntity(entity); + entity = CreatePreviewEntity(); + FocusAsset(); + } + } + ImGui::SetItemTooltip("Moving vertices need a mesh with enough vertices"); + + } + + void MaterialEditorWindow::CreateGraph() { + + auto directory = std::filesystem::path(material.GetResource()->path).parent_path(); + auto stem = std::filesystem::path(material.GetResource()->path).stem().string(); + + // Graphs can be shared, so an existing one of another material stays untouched + auto path = (directory / (stem + ".aematgraph")).generic_string(); + int32_t counter = 1; + while (std::filesystem::exists(Loader::AssetLoader::GetFullPath(path))) + path = (directory / (stem + "_" + std::to_string(counter++) + ".aematgraph")).generic_string(); + + auto graph = MaterialGraph::Graph::CreateDefault(); + graph->name = stem; + Loader::MaterialGraphLoader::SaveGraph(graph, path); + + AttachGraph(ResourceManager::AddResource(path, ResourceOrigin::User, graph)); + graphPanel.FrameAll(); + + } + + json MaterialEditorWindow::SaveState() const { + + json j; + j["material"] = *material.Get(); + if (material->HasGraph()) + j["graph"] = *material->graph.Get(); + return j; + + } + + void MaterialEditorWindow::RestoreState(const json& j) { + + auto graph = material->graph; + j["material"].get_to(*material.Get()); + + // Graphs without a file aren't part of the material state, the attached one stays + auto restoredGraph = j["material"].contains("graphPath") ? material->graph : + j.contains("graph") ? graph : ResourceHandle(); + material->graph = graph; + if (restoredGraph.GetResource() != graph.GetResource()) + AttachGraph(restoredGraph); + + if (j.contains("graph") && material->HasGraph()) { + j["graph"].get_to(*material->graph.Get()); + graphPanel.OnGraphRestored(*material->graph.Get()); + } + + } + + void MaterialEditorWindow::AttachGraph(const ResourceHandle& graph) { + + if (material->HasGraph()) + material->graph->blockingPipelineUsers--; + + material->graph = graph; + + if (material->HasGraph()) + material->graph->blockingPipelineUsers++; + + graphPanel.Reset(); + + UpdateMeshesOfGraph(); + FindOtherUsers(); + + } + + void MaterialEditorWindow::RenderGraphSection() { + + if (!editedGraph.IsValid()) { + bool changed = false; + auto graph = graphSelectionPanel.Render(material->graph, changed); + graphSelectionPanel.Reset(); + if (changed) { + AttachGraph(graph); + graphPanel.FrameAll(); + } + + if (!material->graph.IsValid()) { + Theme::PushPrimaryButton(); + if (ImGui::Button("Create material graph")) + CreateGraph(); + Theme::PopPrimaryButton(); + } + } + + if (!material->HasGraph()) + return; + + auto compiled = material->graph->GetCompiled(); + if (!compiled) + return; + + for (const auto& error : compiled->errors) + Widgets::Callout(error.message.c_str(), Theme::Error()); + + if (!compiled->parameters.empty()) { + ImGui::SeparatorText("Parameters"); + parametersPanel.RenderParameters(*material.Get(), *compiled); + } + + } + + void MaterialEditorWindow::RenderBakeSection(const MaterialGraph::CompiledGraph& compiled) { + + using namespace MaterialGraph; + + auto& settings = material->graphBake; + + if (material.IsGenerated()) { + ImGui::TextDisabled("Only materials can be baked, this window edits a graph on its own"); + return; + } + + ImGui::PushTextWrapPos(); + ImGui::TextColored(Theme::TextMuted(), "Ray traced reflections, global illumination and shadows don't run graphs. Baking writes the surface " + "of the graph into the properties below, which they use."); + ImGui::PopTextWrapPos(); + + if (Widgets::BeginProperties("Bake settings")) { + const char* modes[] = { "Textures: one moment on one mesh", "Average: one value per property" }; + auto mode = int32_t(settings.mode); + Widgets::PropertyLabel("Mode", "Textures keep the details, but are frozen at one point in time and only fit meshes " + "with the same positions and texture coordinates. Averages lose all details and work for every mesh"); + if (ImGui::Combo("##Mode", &mode, modes, IM_ARRAYSIZE(modes))) + settings.mode = BakeMode(mode); + + if (settings.mode == BakeMode::Textures) { + const int32_t resolutions[] = { 256, 512, 1024, 2048, 4096 }; + Widgets::PropertyLabel("Resolution"); + if (ImGui::BeginCombo("##Resolution", std::to_string(settings.resolution).c_str())) { + for (auto resolution : resolutions) { + if (ImGui::Selectable(std::to_string(resolution).c_str(), resolution == settings.resolution)) + settings.resolution = resolution; + } + ImGui::EndCombo(); + } + } + + Widgets::PropertyLabel("Time", "The moment which gets baked, for graphs which change over time"); + ImGui::DragFloat("##Time", &settings.time, 0.05f, 0.0f, 3600.0f, "%.2f s"); + + Widgets::PropertyLabel("Mesh", "Positions and texture coordinates come from this mesh. Without one the sphere of " + "this window is used"); + bool meshChanged = false; + auto selected = meshSelectionPanel.Render(bakeMesh, meshChanged); + meshSelectionPanel.Reset(); + if (meshChanged) { + bakeMesh = selected; + settings.meshPath = bakeMesh.IsValid() ? bakeMesh.GetResource()->path : ""; + } + + Widgets::EndProperties(); + } + + Theme::PushPrimaryButton(); + auto bake = ImGui::Button("Bake"); + Theme::PopPrimaryButton(); + + ImGui::SameLine(); + ImGui::BeginDisabled(settings.bakedState == 0); + if (Widgets::DangerButton("Remove bake", ImVec2(0.0f, 0.0f))) { + Baker::Clear(*material.Get()); + UpdateMeshesOfGraph(); + previewMesh->UpdatePipelines(); + } + ImGui::EndDisabled(); + ImGui::SetItemTooltip("Brings back the properties from before the first bake. Changes made to them since then are lost"); + + if (bake) { + auto mesh = bakeMesh.IsValid() ? bakeMesh : previewMesh; + auto result = Baker::Bake(material, mesh); + bakeError = result.error; + if (result.success) { + UpdateMeshesOfGraph(); + previewMesh->UpdatePipelines(); + Notifications::Push({ .message = settings.mode == BakeMode::Average ? "Baked the averages of " + material.GetResource()->GetFileName() : + "Baked " + std::to_string(result.maps) + " maps of " + material.GetResource()->GetFileName() + ", save the material to keep them" }); + } + } + + if (!bakeError.empty()) + Widgets::Callout(bakeError.c_str(), Theme::Error()); + + if (settings.bakedState != 0 && settings.bakedState != Baker::GetState(*material.Get())) + Widgets::Callout("The graph, its values or these settings changed since the last bake, ray tracing shows the old state", Theme::Warning()); + else if (settings.bakedState == 0) + ImGui::TextDisabled("Not baked yet, ray tracing uses the properties as they are"); + else + ImGui::TextColored(Theme::Success(), "Baked, ray tracing is up to date"); + + } + + void MaterialEditorWindow::UpdateMeshesOfGraph() { + + for (const auto& mesh : ResourceManager::GetResources()) { + if (!mesh.IsLoaded()) + continue; + + auto usesGraph = false; + for (const auto& meshMaterial : mesh->data.materials) + usesGraph |= meshMaterial.IsLoaded() && meshMaterial->graph == material->graph; + + if (usesGraph) + mesh->UpdatePipelines(); + } + + } + +} diff --git a/src/editor/ui/windows/MaterialEditorWindow.h b/src/editor/ui/windows/MaterialEditorWindow.h new file mode 100644 index 000000000..94fa204c5 --- /dev/null +++ b/src/editor/ui/windows/MaterialEditorWindow.h @@ -0,0 +1,119 @@ +#pragma once + +#include "AssetEditorWindow.h" + +#include "../panels/MaterialGraphPanel.h" +#include "../panels/MaterialGraphParametersPanel.h" +#include "../panels/ResourceSelectionPanel.h" + +#include + +#include +#include +#include + +namespace Atlas::Editor::UI { + + // Edits a material and its graph on a preview mesh + class MaterialEditorWindow : public AssetEditorWindow { + + public: + explicit MaterialEditorWindow(ResourceHandle material, bool show); + + // Edits a graph with a material which only exists for the preview + explicit MaterialEditorWindow(ResourceHandle graph, bool show); + + ~MaterialEditorWindow() override; + + void Save() override; + + std::string GetAssetPath() const override; + + ResourceHandle material; + + MaterialGraphPanel graphPanel; + + protected: + bool IsReady() const override; + + Scene::Entity CreatePreviewEntity() override; + + Volume::AABB GetBounds() const override; + + void RenderProperties() override; + + void RenderPanels() override; + + bool HasBottomPanel() const override { return true; } + + float GetBottomPanelSize() const override { return 0.6f; } + + void DockPanels(ImGuiID side, ImGuiID bottom) override; + + bool IsPanelFocused() const override; + + bool AllowsViewportShortcuts() const override; + + void RenderViewportSettings() override; + + json SaveState() const override; + + void RestoreState(const json& j) override; + + private: + void Init(); + + void LoadPreviewMesh(); + + void CreateGraph(); + + void AttachGraph(const ResourceHandle& graph); + + void RenderGraphSection(); + + void RenderBakeSection(const MaterialGraph::CompiledGraph& compiled); + + void RenderGraphCanvas(); + + void RenderSharedGraphWarning(); + + // Finds the other materials with the graph, also the ones which aren't loaded + void FindOtherUsers(); + + void MakeGraphUnique(); + + struct GraphUsers { + // Only valid when finished + std::vector materials; + std::atomic_bool finished = false; + }; + + // Other meshes with this graph get the new pipelines as well + void UpdateMeshesOfGraph(); + + // Own copy of a mesh, the material replaces the one of the file + ResourceHandle previewMesh; + int32_t previewMeshIdx = 0; + + // Editing a graph without a material of its own, which isn't saved then + ResourceHandle editedGraph; + // Revision of the graph when it was compiled here, scripts count it up + uint32_t compiledRevision = 0; + + Panel graphPanelWindow = Panel("Material graph"); + + Ref graphUsers; + JobGroup graphUsersJob { "Material graph users", JobPriority::Low }; + + ResourceHandle bakeMesh; + ResourceSelectionPanel meshSelectionPanel; + std::string bakeError; + + MaterialGraphParametersPanel parametersPanel; + ImguiExtension::MaterialPanel materialPanel; + ResourceSelectionPanel textureSelectionPanel; + ResourceSelectionPanel graphSelectionPanel; + + }; + +} diff --git a/src/editor/ui/windows/MeshEditorWindow.cpp b/src/editor/ui/windows/MeshEditorWindow.cpp new file mode 100644 index 000000000..bc44b7e95 --- /dev/null +++ b/src/editor/ui/windows/MeshEditorWindow.cpp @@ -0,0 +1,560 @@ +#include "MeshEditorWindow.h" + +#include "../../Notifications.h" +#include "../../Theme.h" +#include "../../tools/ResourcePayloadHelper.h" +#include "../Widgets.h" + +#include "loader/MeshLoader.h" +#include "loader/MaterialLoader.h" +#include "mesh/MeshSerializer.h" +#include "physics/ShapesManager.h" + +#include +#include + +namespace Atlas::Editor::UI { + + MeshEditorWindow::MeshEditorWindow(ResourceHandle mesh, bool show) : + AssetEditorWindow(mesh.IsValid() ? mesh.GetResource()->GetFileName() : "No mesh", show), mesh(mesh) {} + + void MeshEditorWindow::Save() { + + if (!mesh.IsLoaded()) + return; + + Loader::MeshLoader::SaveMesh(mesh.Get(), mesh.GetResource()->path, true); + Notifications::Push({ .message = "Saved mesh " + mesh.GetResource()->GetFileName() }); + + } + + json MeshEditorWindow::SaveState() const { + + if (!mesh.IsLoaded()) + return json(); + + json j = { + {"mobility", int32_t(mesh->mobility)}, + {"invertUVs", mesh->invertUVs}, + {"cullBackFaces", mesh->cullBackFaces}, + {"rayTrace", mesh->rayTrace}, + {"vegetation", mesh->vegetation}, + {"castShadow", mesh->castShadow}, + {"allowedShadowCascades", mesh->allowedShadowCascades}, + {"distanceCulling", mesh->distanceCulling}, + {"shadowDistanceCulling", mesh->shadowDistanceCulling}, + {"rayTraceDistanceCulling", mesh->rayTraceDistanceCulling}, + {"minScreenSize", mesh->minScreenSize}, + {"lodPixelError", mesh->lodPixelError}, + {"animationLodDistance", mesh->animationLodDistance}, + {"animationMaxInterval", mesh->animationMaxInterval}, + {"impostorDistance", mesh->impostorDistance}, + {"impostorShadowDistance", mesh->impostorShadowDistance}, + {"windNoiseTextureLod", mesh->windNoiseTextureLod}, + {"windBendScale", mesh->windBendScale}, + {"windWiggleScale", mesh->windWiggleScale}, + {"softBody", mesh->softBody}, + }; + + auto materials = json::array(); + // Material files have their own history, only embedded materials are edited here + for (const auto& material : mesh->data.materials) { + json materialJson; + if (material.IsValid() && !material.IsGenerated()) + materialJson["path"] = material.GetResource()->path; + else if (material.IsLoaded()) + materialJson["material"] = *material.Get(); + materials.push_back(materialJson); + } + j["materials"] = materials; + + return j; + + } + + void MeshEditorWindow::RestoreState(const json& j) { + + if (!mesh.IsLoaded() || j.is_null()) + return; + + mesh->mobility = Mesh::MeshMobility(j["mobility"].get()); + j.at("invertUVs").get_to(mesh->invertUVs); + j.at("cullBackFaces").get_to(mesh->cullBackFaces); + j.at("rayTrace").get_to(mesh->rayTrace); + j.at("vegetation").get_to(mesh->vegetation); + j.at("castShadow").get_to(mesh->castShadow); + j.at("allowedShadowCascades").get_to(mesh->allowedShadowCascades); + j.at("distanceCulling").get_to(mesh->distanceCulling); + j.at("shadowDistanceCulling").get_to(mesh->shadowDistanceCulling); + j.at("rayTraceDistanceCulling").get_to(mesh->rayTraceDistanceCulling); + j.at("minScreenSize").get_to(mesh->minScreenSize); + j.at("lodPixelError").get_to(mesh->lodPixelError); + j.at("animationLodDistance").get_to(mesh->animationLodDistance); + j.at("animationMaxInterval").get_to(mesh->animationMaxInterval); + j.at("impostorDistance").get_to(mesh->impostorDistance); + j.at("impostorShadowDistance").get_to(mesh->impostorShadowDistance); + j.at("windNoiseTextureLod").get_to(mesh->windNoiseTextureLod); + j.at("windBendScale").get_to(mesh->windBendScale); + j.at("windWiggleScale").get_to(mesh->windWiggleScale); + + j.at("softBody").get_to(mesh->softBody); + mesh->ResetSoftBodySimulationMesh(); + + const auto& materials = j["materials"]; + for (size_t i = 0; i < std::min(materials.size(), mesh->data.materials.size()); i++) { + const auto& materialJson = materials[i]; + auto& material = mesh->data.materials[i]; + + // Another material was selected for the slot. Embedded materials only exist in the mesh, + // a new one gets their values, such that a material file used by the slot isn't overwritten + auto isFileMaterial = materialJson.contains("path"); + auto slotChanged = isFileMaterial ? !material.IsValid() || material.IsGenerated() || + material.GetResource()->path != materialJson["path"].get() : + material.IsValid() && !material.IsGenerated(); + if (slotChanged) { + if (isFileMaterial) + material = ResourceManager::GetOrLoadResourceWithLoader(materialJson["path"], + ResourceOrigin::User, Loader::MaterialLoader::LoadMaterial, false); + else + material = ResourceHandle(CreateRef()); + for (auto& subData : mesh->data.subData) + if (subData.materialIdx == int32_t(i)) + subData.material = material; + } + + if (materialJson.contains("material") && material.IsLoaded()) + materialJson["material"].get_to(*material.Get()); + } + + mesh->UpdatePipelines(); + + } + + std::string MeshEditorWindow::GetAssetPath() const { + + return mesh.IsValid() ? mesh.GetResource()->path : ""; + + } + + bool MeshEditorWindow::Play(const ResourceHandle& animation) { + + if (!scene || !IsSkinned()) + return false; + + auto& animationComponent = entity.HasComponent() ? entity.GetComponent() : + entity.AddComponent(); + animationComponent.Play(animation); + + return true; + + } + + void MeshEditorWindow::StatisticsRow(const char* label, const char* format, ...) { + + ImGui::TableNextRow(); + ImGui::TableNextColumn(); + ImGui::TextColored(Theme::TextMuted(), "%s", label); + ImGui::TableNextColumn(); + + va_list args; + va_start(args, format); + ImGui::TextV(format, args); + va_end(args); + + } + + bool MeshEditorWindow::IsReady() const { + + return mesh.IsLoaded(); + + } + + Scene::Entity MeshEditorWindow::CreatePreviewEntity() { + + // Not static, the mesh can be animated + auto meshEntity = scene->CreatePrefab(mesh, false); + if (IsSkinned()) + meshEntity.AddComponent(); + + return meshEntity; + + } + + Volume::AABB MeshEditorWindow::GetBounds() const { + + return mesh->data.aabb; + + } + + void MeshEditorWindow::RenderProperties() { + + RenderHeading("Saves the mesh and its materials (Ctrl+S)"); + + const auto& data = mesh->data; + if (ImGui::BeginTable("Statistics", 2, ImGuiTableFlags_SizingStretchProp)) { + auto size = data.aabb.max - data.aabb.min; + StatisticsRow("Vertices", "%d", data.GetVertexCount()); + StatisticsRow("Triangles", "%d", data.GetIndexCount() / 3); + StatisticsRow("Sub meshes", "%d", int32_t(data.subData.size())); + StatisticsRow("Materials", "%d", int32_t(data.materials.size())); + StatisticsRow("Size", "%.2f x %.2f x %.2f m", size.x, size.y, size.z); + if (data.IsSkinned()) + StatisticsRow("Joints", "%d", data.skeleton.GetJointCount()); + ImGui::EndTable(); + ImGui::Spacing(); + } + + if (Widgets::SectionHeader("Mesh", ImGuiTreeNodeFlags_DefaultOpen)) { + auto& meshComponent = entity.GetComponent(); + auto wasSkinned = IsSkinned(); + if (meshComponentPanel.Render(scene, entity, meshComponent) && meshComponent.mesh.IsValid()) { + // Another mesh was selected, edit that one instead, the steps of the old one don't apply to it + mesh = meshComponent.mesh; + ResetHistory(); + selectedJoint = -1; + if (IsSkinned() && !entity.HasComponent()) + entity.AddComponent(); + if (IsSkinned() != wasSkinned) + resetDockingLayout = true; + } + } + + if (entity.HasComponent() && Widgets::SectionHeader("Animation", ImGuiTreeNodeFlags_DefaultOpen)) { + auto& animationComponent = entity.GetComponent(); + animationComponentPanel.Render(scene, entity, animationComponent); + } + + // The clips the mesh references, a click plays one + if (!mesh->data.animations.empty() && Widgets::SectionHeader("Animations", ImGuiTreeNodeFlags_DefaultOpen)) { + auto animationComponent = entity.TryGetComponent(); + for (const auto& animation : mesh->data.animations) { + if (!animation.IsLoaded()) + continue; + auto playing = animationComponent && animationComponent->animation == animation; + if (ImGui::Selectable(animation->name.c_str(), playing)) + Play(animation); + } + } + + if (Widgets::SectionHeader("Physics")) + RenderPhysics(); + + if (Widgets::SectionHeader("Soft body")) + RenderSoftBody(); + + } + + void MeshEditorWindow::RenderPanels() { + + if (!IsSkinned()) + return; + + RenderSkeleton(); + + ImGui::Begin(timelinePanelWindow.GetNameID()); + timelinePanelWindow.isFocused = ImGui::IsWindowFocused(ImGuiFocusedFlags_ChildWindows); + if (auto animationComponent = entity.TryGetComponent()) + timelinePanel.Render(*animationComponent, mesh->data.skeleton, selectedJoint); + ImGui::End(); + + } + + bool MeshEditorWindow::HasSidePanel() const { + + return IsSkinned(); + + } + + bool MeshEditorWindow::HasBottomPanel() const { + + return IsSkinned(); + + } + + void MeshEditorWindow::DockPanels(ImGuiID side, ImGuiID bottom) { + + if (side) + ImGui::DockBuilderDockWindow(skeletonPanel.GetNameID(), side); + if (bottom) + ImGui::DockBuilderDockWindow(timelinePanelWindow.GetNameID(), bottom); + + } + + bool MeshEditorWindow::IsPanelFocused() const { + + return skeletonPanel.isFocused || timelinePanelWindow.isFocused; + + } + + void MeshEditorWindow::RenderViewportSettings() { + + ImGui::Checkbox("Show physics", &showPhysics); + ImGui::Checkbox("Show simulation mesh", &softBodyComponentPanel.showSimulationMesh); + ImGui::SetItemTooltip("The mesh soft bodies simulate, with a simulating preview its pinned vertices and pin bounds"); + ImGui::BeginDisabled(!IsSkinned()); + ImGui::Checkbox("Show skeleton", &showSkeleton); + ImGui::EndDisabled(); + + RenderLods(); + + } + + void MeshEditorWindow::AcceptViewportDrop() { + + auto animation = ResourcePayloadHelper::AcceptDropResource(); + if (animation.IsValid() && !Play(animation)) + Notifications::Push({ .message = "The mesh has no skeleton to play the animation on", .type = NotificationType::Error }); + + } + + void MeshEditorWindow::RenderLods() { + + ImGui::SeparatorText("Levels of detail"); + + const auto& data = mesh->data; + auto lodCount = data.GetLodCount(); + auto& forcedLod = scene->forcedMeshLod; + forcedLod = std::min(forcedLod, lodCount - 1); + if (lodCount < 2) { + ImGui::TextColored(Theme::TextMuted(), "None, generated in the mesh settings"); + return; + } + + auto getLabel = [&](int32_t lod) { + if (lod < 0) + return std::string("Automatic"); + size_t indexCount = 0; + for (const auto& subData : data.subData) + indexCount += subData.GetLod(lod).indicesCount; + return "LOD " + std::to_string(lod) + " (" + std::to_string(indexCount / 3) + " triangles)"; + }; + + if (ImGui::BeginCombo("Shown level", getLabel(forcedLod).c_str())) { + for (int32_t lod = -1; lod < lodCount; lod++) { + if (ImGui::Selectable(getLabel(lod).c_str(), lod == forcedLod)) + forcedLod = lod; + } + ImGui::EndCombo(); + } + ImGui::SetItemTooltip("Automatic chooses the level by the distance to the camera"); + ImGui::Checkbox("Color by level", &scene->debugMeshLods); + ImGui::SetItemTooltip("White, green, blue, yellow and red from the full detail on"); + + } + + void MeshEditorWindow::RenderPhysics() { + + if (!entity.HasComponent()) { + ImGui::TextWrapped("Bodies are part of entities. Add one to see how a shape fits the mesh"); + if (ImGui::Button("Add body", ImVec2(-FLT_MIN, 0.0f))) { + auto shape = Physics::ShapesManager::CreateShape(Physics::BoundingBoxShapeSettings { .scale = vec3(1.0f) }); + entity.AddComponent(Physics::BodyCreationSettings { + .objectLayer = Physics::Layers::Movable, .shape = shape }); + showPhysics = true; + } + return; + } + + // Same as in the entity properties, changed settings recreate the body + auto comp = entity.GetComponent(); + rigidBodyComponentPanel.Render(scene, entity, comp); + if (comp.creationSettings) { + entity.RemoveComponent(); + entity.AddComponent(*comp.creationSettings); + } + + if (Widgets::DangerButton("Remove body")) + entity.RemoveComponent(); + + } + + void MeshEditorWindow::RenderSkeleton() { + + ImGui::Begin(skeletonPanel.GetNameID()); + + skeletonPanel.isFocused = ImGui::IsWindowFocused(); + + const auto& joints = mesh->data.skeleton.joints; + const auto& style = ImGui::GetStyle(); + + ImGui::SetNextItemWidth(-FLT_MIN); + ImGui::InputTextWithHint("##Search", "Search joints...", &jointSearch); + + auto toLower = [](std::string text) { + std::transform(text.begin(), text.end(), text.begin(), ::tolower); + return text; + }; + auto search = toLower(jointSearch); + + std::vector> children(joints.size()); + for (int32_t i = 0; i < int32_t(joints.size()); i++) + if (joints[i].parentIdx >= 0) + children[joints[i].parentIdx].push_back(i); + + std::function renderJoint = [&](int32_t jointIdx, int32_t depth) { + auto flags = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick | + ImGuiTreeNodeFlags_SpanAvailWidth | ImGuiTreeNodeFlags_FramePadding; + // While searching the matches are listed flat + bool flat = !search.empty(); + if (children[jointIdx].empty() || flat) + flags |= ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_NoTreePushOnOpen; + if (jointIdx == selectedJoint) + flags |= ImGuiTreeNodeFlags_Selected; + + if (!flat || toLower(joints[jointIdx].name).find(search) != std::string::npos) { + if (!flat && depth < 3) + ImGui::SetNextItemOpen(true, ImGuiCond_Once); + bool open = ImGui::TreeNodeEx(reinterpret_cast(intptr_t(jointIdx)), flags, "%s", joints[jointIdx].name.c_str()); + if (ImGui::IsItemClicked() && !ImGui::IsItemToggledOpen()) + selectedJoint = jointIdx == selectedJoint ? -1 : jointIdx; + + if (!flat && open && !(flags & ImGuiTreeNodeFlags_Leaf)) { + for (auto child : children[jointIdx]) + renderJoint(child, depth + 1); + ImGui::TreePop(); + } + } + + if (flat) + for (auto child : children[jointIdx]) + renderJoint(child, depth + 1); + }; + + auto detailsHeight = selectedJoint >= 0 ? 5.0f * ImGui::GetTextLineHeightWithSpacing() : 0.0f; + ImGui::BeginChild("Joints", ImVec2(0.0f, -detailsHeight)); + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(style.FramePadding.x, 2.0f)); + for (int32_t i = 0; i < int32_t(joints.size()); i++) + if (joints[i].parentIdx < 0) + renderJoint(i, 0); + ImGui::PopStyleVar(); + ImGui::EndChild(); + + if (selectedJoint >= 0 && selectedJoint < int32_t(joints.size())) { + const auto& joint = joints[selectedJoint]; + ImGui::SeparatorText(joint.name.c_str()); + ImGui::TextColored(Theme::TextMuted(), "Parent"); + ImGui::SameLine(); + ImGui::TextUnformatted(joint.parentIdx >= 0 ? joints[joint.parentIdx].name.c_str() : "None"); + if (!joint.hasVertices) + ImGui::TextColored(Theme::TextMuted(), "Doesn't influence any vertices"); + + // Keys of the joint in the current animation + auto animationComponent = entity.TryGetComponent(); + if (animationComponent && animationComponent->animation.IsLoaded()) { + const auto& channels = animationComponent->animation->channels; + auto channel = std::find_if(channels.begin(), channels.end(), + [&](const auto& channel) { return channel.jointName == joint.name; }); + if (channel != channels.end()) + ImGui::Text("%d position, %d rotation, %d scale keys", int32_t(channel->positionTimes.size()), + int32_t(channel->rotationTimes.size()), int32_t(channel->scaleTimes.size())); + else + ImGui::TextColored(Theme::TextMuted(), "Not animated by %s", animationComponent->animation->name.c_str()); + } + } + + ImGui::End(); + + } + + void MeshEditorWindow::RenderOverlays() { + + auto& wrapper = viewportPanel.primitiveBatchWrapper; + + if (showPhysics && scene->physicsWorld) { + physicsDebugDrawSettings.center = cameraEntity.GetComponent().GetLocation(); + scene->physicsWorld->DebugDraw(wrapper.GetBatch(false).get(), physicsDebugDrawSettings); + } + + // Bodies are created again from the new simulation mesh once an edit of its settings is finished + if (pendingSimulationMeshReset && !ImGui::IsAnyItemActive() && !ImGuizmo::IsUsing()) { + mesh->ResetSoftBodySimulationMesh(); + pendingSimulationMeshReset = false; + } + + softBodyComponentPanel.RenderOverlay(scene, entity, wrapper); + viewportPanel.DrawOverlay([this]() { + if (cameraEntity.IsValid()) + softBodyComponentPanel.RenderPinGizmo(scene, entity, viewportPanel.viewport, cameraEntity.GetComponent()); + }); + + if (!showSkeleton || !IsSkinned()) + return; + + // The pose of the component includes its layers, inverse kinematics and joint offsets, before its first + // update the joints are shown in their rest pose + const auto& skeleton = mesh->data.skeleton; + auto animationComponent = entity.TryGetComponent(); + auto animated = animationComponent && !animationComponent->jointMatrices.empty(); + if (!animated) { + skeleton.GetRestPose(restPose); + skeleton.GetGlobalMatrices(restPose, restMatrices); + } + + auto globalMatrix = scene->GetGlobalMatrix(entity); + auto getPosition = [&](int32_t jointIdx) { + auto jointMatrix = animated ? animationComponent->GetJointMatrix(jointIdx) : restMatrices[jointIdx]; + return vec3(globalMatrix * jointMatrix[3]); + }; + + auto extent = glm::length(mesh->data.aabb.max - mesh->data.aabb.min); + for (int32_t i = 0; i < skeleton.GetJointCount(); i++) { + auto position = getPosition(i); + auto selected = i == selectedJoint; + auto color = selected ? vec3(1.0f, 0.6f, 0.1f) : vec3(0.2f, 0.8f, 1.0f); + + auto parentIdx = skeleton.joints[i].parentIdx; + if (parentIdx >= 0) + wrapper.GetBatch(false)->AddLine(getPosition(parentIdx), position, color, color); + if (selected) + wrapper.GetBatch(false)->AddLineSphere(position, 0.02f * extent, color); + } + + } + + void MeshEditorWindow::RenderSoftBody() { + + auto& settings = mesh->softBody; + auto changed = false; + + if (Widgets::BeginProperties("Soft body mesh")) { + Widgets::PropertyLabel("Max simulated vertices", "The simulation mesh is simplified to about this many " + "vertices, zero simulates all vertices of level 0 (welded by position)"); + changed |= ImGui::DragInt("##Max simulated vertices", &settings.maxSimulatedVertices, 1.0f, 0, 1000000); + Widgets::PropertyLabel("Keep borders", "Keeps every vertex on open edges, e.g. the outline of a banner. " + "Otherwise they only slide along the edges"); + changed |= ImGui::Checkbox("##Keep borders", &settings.keepBorders); + Widgets::EndProperties(); + } + + auto simulationMesh = mesh->GetSoftBodySimulationMesh(); + if (ImGui::BeginTable("Soft body statistics", 2, ImGuiTableFlags_SizingStretchProp)) { + StatisticsRow("Simulated vertices", "%d", int32_t(simulationMesh->positions.size())); + StatisticsRow("Simulated triangles", "%d", int32_t(simulationMesh->indices.size() / 3)); + ImGui::EndTable(); + } + ImGui::TextColored(Theme::TextMuted(), "Pins are set per soft body component, the preview can try them"); + + ImGui::SeparatorText("Preview"); + auto simulating = entity.HasComponent(); + if (ImGui::Checkbox("Simulate", &simulating)) { + if (simulating) + entity.AddComponent(); + else + entity.RemoveComponent(); + scene->physicsWorld->pauseSimulation = !simulating; + } + ImGui::SetItemTooltip("The preview gets a soft body, its settings are part of the entity and not saved"); + if (auto softBodyComponent = entity.TryGetComponent()) + softBodyComponentPanel.Render(scene, entity, *softBodyComponent); + + pendingSimulationMeshReset |= changed; + + } + + bool MeshEditorWindow::IsSkinned() const { + + return mesh.IsLoaded() && mesh->data.IsSkinned(); + + } + +} diff --git a/src/editor/ui/windows/MeshEditorWindow.h b/src/editor/ui/windows/MeshEditorWindow.h new file mode 100644 index 000000000..6eaf60976 --- /dev/null +++ b/src/editor/ui/windows/MeshEditorWindow.h @@ -0,0 +1,103 @@ +#pragma once + +#include "AssetEditorWindow.h" + +#include "../panels/AnimationTimelinePanel.h" +#include "../panels/components/MeshComponentPanel.h" +#include "../panels/components/AnimationComponentPanel.h" +#include "../panels/components/RigidBodyComponentPanel.h" +#include "../panels/components/SoftBodyComponentPanel.h" + +#include "resource/Resource.h" + +namespace Atlas::Editor::UI { + + // Edits the settings and materials of a mesh, plays and edits animations on its skeleton + class MeshEditorWindow : public AssetEditorWindow { + + public: + explicit MeshEditorWindow(ResourceHandle mesh, bool show); + + void Save() override; + + std::string GetAssetPath() const override; + + // Plays the animation on the skeleton of the mesh, fails for meshes without one + bool Play(const ResourceHandle& animation); + + ResourceHandle mesh; + + bool showSkeleton = true; + bool showPhysics = true; + + AnimationTimelinePanel timelinePanel; + + protected: + bool IsReady() const override; + + Scene::Entity CreatePreviewEntity() override; + + Volume::AABB GetBounds() const override; + + void RenderProperties() override; + + void RenderPanels() override; + + bool HasSidePanel() const override; + + bool HasBottomPanel() const override; + + void DockPanels(ImGuiID side, ImGuiID bottom) override; + + bool IsPanelFocused() const override; + + void RenderViewportSettings() override; + + void RenderOverlays() override; + + void AcceptViewportDrop() override; + + // The settings and materials of the mesh, the mesh data isn't edited + json SaveState() const override; + + void RestoreState(const json& j) override; + + private: + void RenderSkeleton(); + + // Viewport settings to show a chosen level of detail instead of the one for the camera distance + void RenderLods(); + + // Bodies belong to entities, the preview entity gets one to try shapes for the mesh + void RenderPhysics(); + + // The resolution of the simulation mesh soft bodies of the mesh use, the preview entity can simulate one + void RenderSoftBody(); + + // A row of a table with two columns of muted labels and values + static void StatisticsRow(const char* label, const char* format, ...); + + bool IsSkinned() const; + + Panel skeletonPanel = Panel("Skeleton"); + Panel timelinePanelWindow = Panel("Timeline"); + + MeshComponentPanel meshComponentPanel; + AnimationComponentPanel animationComponentPanel; + RigidBodyComponentPanel rigidBodyComponentPanel; + SoftBodyComponentPanel softBodyComponentPanel; + + // The simulation mesh is created again once an edit of its settings is finished + bool pendingSimulationMeshReset = false; + + Physics::DebugDrawSettings physicsDebugDrawSettings; + + std::vector restPose; + std::vector restMatrices; + + std::string jointSearch; + int32_t selectedJoint = -1; + + }; + +} diff --git a/src/editor/ui/windows/ProfilerWindow.cpp b/src/editor/ui/windows/ProfilerWindow.cpp index b09640435..09078f191 100644 --- a/src/editor/ui/windows/ProfilerWindow.cpp +++ b/src/editor/ui/windows/ProfilerWindow.cpp @@ -1,7 +1,8 @@ #include "ProfilerWindow.h" #include "Clock.h" -#include "graphics/Profiler.h" +#include "profiler/CPUProfiler.h" +#include "profiler/GPUProfiler.h" namespace Atlas::Editor::UI { @@ -13,18 +14,29 @@ namespace Atlas::Editor::UI { auto frameTime = Clock::GetAverage() * 1000.0f; auto fps = frameTime > 0.0f ? 1000.0f / frameTime : 0.0f; - // GPU time is the time of the slowest queue + // CPU time is the time of the main thread, GPU time the time of the slowest queue + profilerPanel.Refresh(); + double cpuTime = 0.0; + for (const auto& threadData : profilerPanel.cpuThreads) { + if (threadData.name != "Main") + continue; + for (const auto& query : threadData.queries) + cpuTime += double(query.elapsedTime); + } + double gpuTime = 0.0; - auto gpuProfilerData = Graphics::Profiler::GetQueriesAverage(32, Graphics::Profiler::OrderBy::MAX_TIME); - for (const auto& threadData : gpuProfilerData) { + for (const auto& threadData : profilerPanel.gpuThreads) { double threadTime = 0.0; for (const auto& query : threadData.queries) - threadTime += double(query.timer.elapsedTime); + threadTime += double(query.elapsedTime); gpuTime = std::max(gpuTime, threadTime); } // Summary tiles: muted label on top, large value below - if (ImGui::BeginTable("Profiler summary", 3, ImGuiTableFlags_SizingStretchSame | ImGuiTableFlags_BordersInnerV)) { + // A drawer has the pin button in its header, the docked window next to the summary + auto pinWidth = pinned ? GetPinButtonWidth() + ImGui::GetStyle().ItemSpacing.x : 0.0f; + if (ImGui::BeginTable("Profiler summary", 4, ImGuiTableFlags_SizingStretchSame | ImGuiTableFlags_BordersInnerV, + ImVec2(-pinWidth, 0.0f))) { auto tile = [](const char* label, const char* format, float value) { ImGui::TableNextColumn(); ImGui::TextDisabled("%s", label); @@ -33,24 +45,33 @@ namespace Atlas::Editor::UI { ImGui::SetWindowFontScale(1.0f); }; - tile("Frame time", "%.2f ms", frameTime); - tile("Frame rate", "%.0f fps", fps); - if (Graphics::Profiler::enable) - tile("GPU time", "%.2f ms", float(gpuTime / 1000000.0)); - else { + auto disabledTile = [](const char* label) { ImGui::TableNextColumn(); - ImGui::TextDisabled("GPU time"); + ImGui::TextDisabled("%s", label); ImGui::SetWindowFontScale(1.6f); ImGui::TextDisabled("-"); ImGui::SetWindowFontScale(1.0f); - } + }; + + tile("Frame time", "%.2f ms", frameTime); + tile("Frame rate", "%.0f fps", fps); + if (CPUProfiler::enable) + tile("CPU main thread", "%.2f ms", float(cpuTime / 1000000.0)); + else + disabledTile("CPU main thread"); + if (GPUProfiler::enable) + tile("GPU time", "%.2f ms", float(gpuTime / 1000000.0)); + else + disabledTile("GPU time"); ImGui::EndTable(); } + if (pinned) { + ImGui::SameLine(ImGui::GetWindowContentRegionMax().x - GetPinButtonWidth()); + RenderPinButton(); + } - ImGui::SeparatorText("GPU timings"); - - gpuProfilerPanel.Render(); + profilerPanel.Render(); End(); diff --git a/src/editor/ui/windows/ProfilerWindow.h b/src/editor/ui/windows/ProfilerWindow.h index 457b20f1a..74f7fb2d2 100644 --- a/src/editor/ui/windows/ProfilerWindow.h +++ b/src/editor/ui/windows/ProfilerWindow.h @@ -1,20 +1,20 @@ #pragma once -#include "Window.h" +#include "DrawerWindow.h" -#include +#include namespace Atlas::Editor::UI { - class ProfilerWindow : public Window { + class ProfilerWindow : public DrawerWindow { public: - explicit ProfilerWindow(bool show) : Window("Profiler", show) {} + explicit ProfilerWindow(bool show) : DrawerWindow("Profiler", show) {} void Render(); private: - ImguiExtension::GPUProfilerPanel gpuProfilerPanel; + ImguiExtension::ProfilerPanel profilerPanel; }; diff --git a/src/editor/ui/windows/ProjectHubWindow.cpp b/src/editor/ui/windows/ProjectHubWindow.cpp new file mode 100644 index 000000000..885e79596 --- /dev/null +++ b/src/editor/ui/windows/ProjectHubWindow.cpp @@ -0,0 +1,390 @@ +#include "ProjectHubWindow.h" +#include "../Widgets.h" +#include "../../Theme.h" + +#include + +#include + +#include +#include +#include +#include +#include + +namespace fs = std::filesystem; + +namespace Atlas::Editor::UI { + + ProjectHubWindow::ProjectHubWindow(const std::string& standardDataDirectory, const std::string& templatesDirectory) + : standardDataDirectory(standardDataDirectory), templatesDirectory(templatesDirectory) { + + for (int32_t i = 0; i < 3; i++) + dialogRequests[i] = { this, DialogType(i) }; + + auto documents = SDL_GetUserFolder(SDL_FOLDER_DOCUMENTS); + newLocation = documents ? fs::path(documents).generic_string() : fs::current_path().generic_string(); + if (newLocation.ends_with('/')) + newLocation.pop_back(); + + LoadEntries(); + LoadTemplates(); + + } + + std::optional ProjectHubWindow::Render(SDL_Window* window) { + + auto openPath = TakeDialogResult(); + + // Laid out like the empty state of the editor: one column in the middle of the window + auto viewport = ImGui::GetMainViewport(); + ImGui::GetBackgroundDrawList(viewport)->AddRectFilled(viewport->Pos, + ImVec2(viewport->Pos.x + viewport->Size.x, viewport->Pos.y + viewport->Size.y), ImGui::GetColorU32(Theme::Base())); + ImGui::SetNextWindowPos(ImVec2(viewport->Pos.x + viewport->Size.x * 0.5f, viewport->Pos.y + viewport->Size.y * 0.5f), + ImGuiCond_Always, ImVec2(0.5f, 0.5f)); + ImGui::Begin("##Projects", nullptr, ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoDocking | + ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoBackground | ImGuiWindowFlags_NoMove | + ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoBringToFrontOnFocus); + + // Heading and buttons are centered over the list + const auto columnWidth = 560.0f; + auto center = [&](float width) { + ImGui::SetCursorPosX(ImGui::GetCursorPosX() + std::max(0.0f, (columnWidth - width) * 0.5f)); + }; + auto buttonWidth = [](const char* label) { + return ImGui::CalcTextSize(label, nullptr, true).x + ImGui::GetStyle().FramePadding.x * 2.0f; + }; + + ImGui::Dummy(ImVec2(columnWidth, 0.0f)); + ImGui::SetWindowFontScale(1.5f); + center(ImGui::CalcTextSize("Atlas Engine").x); + ImGui::TextUnformatted("Atlas Engine"); + ImGui::SetWindowFontScale(1.0f); + const char* subtitle = "Open a project or create a new one"; + center(ImGui::CalcTextSize(subtitle).x); + ImGui::TextDisabled("%s", subtitle); + + ImGui::Dummy(ImVec2(0.0f, 4.0f)); + + center(buttonWidth("New project...") + buttonWidth("Open...") + buttonWidth("Add folder...") + + ImGui::GetStyle().ItemSpacing.x * 2.0f); + Theme::PushPrimaryButton(); + if (ImGui::Button("New project...")) + OpenNewProjectPopup(); + Theme::PopPrimaryButton(); + ImGui::SameLine(); + if (ImGui::Button("Open...")) + ShowDialog(window, DialogType::OpenProject); + ImGui::SetItemTooltip("Opens a .aeproject file"); + ImGui::SameLine(); + if (ImGui::Button("Add folder...")) + ShowDialog(window, DialogType::AddFolder); + ImGui::SetItemTooltip("Adds a folder as a project, a project file is created if it has none"); + + ImGui::Dummy(ImVec2(0.0f, 4.0f)); + ImGui::SetNextItemWidth(columnWidth); + ImGui::InputTextWithHint("##Project search", "Search projects...", &search); + + if (!error.empty()) { + ImGui::Dummy(ImVec2(0.0f, 4.0f)); + Widgets::Callout(error.c_str(), Theme::Error()); + } + + auto matches = [&](const RecentProjects::Entry& entry) { + auto lower = [](std::string text) { + std::transform(text.begin(), text.end(), text.begin(), [](unsigned char c) { return std::tolower(c); }); + return text; + }; + auto query = lower(search); + return query.empty() || lower(entry.name).find(query) != std::string::npos || + lower(entry.path).find(query) != std::string::npos; + }; + + auto formatAge = [](int64_t lastOpened) { + auto now = std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch()).count(); + auto seconds = std::max(now - lastOpened, int64_t(0)); + if (seconds < 60) return std::string("just now"); + if (seconds < 3600) return std::to_string(seconds / 60) + " min ago"; + if (seconds < 86400) return std::to_string(seconds / 3600) + " h ago"; + if (seconds < 2 * 86400) return std::string("yesterday"); + return std::to_string(seconds / 86400) + " days ago"; + }; + + std::string removePath; + if (!entries.empty()) { + ImGui::Dummy(ImVec2(0.0f, 4.0f)); + ImGui::SeparatorText("Recent projects"); + } + + for (size_t i = 0; i < entries.size(); i++) { + const auto& entry = entries[i]; + if (!matches(entry)) + continue; + + ImGui::PushID(entry.path.c_str()); + auto start = ImGui::GetCursorPos(); + auto lineHeight = ImGui::GetTextLineHeightWithSpacing(); + ImGui::BeginDisabled(!entryExists[i]); + if (ImGui::Selectable("##Project", false, ImGuiSelectableFlags_None, ImVec2(columnWidth, lineHeight * 2.0f))) + openPath = entry.path; + ImGui::EndDisabled(); + // Long paths are shortened, the window would otherwise grow wider than the column + auto pathShortened = ImGui::CalcTextSize(entry.path.c_str()).x > columnWidth; + if (!entryExists[i]) + ImGui::SetItemTooltip("The project file doesn't exist anymore"); + else if (pathShortened) + ImGui::SetItemTooltip("%s", entry.path.c_str()); + if (ImGui::BeginPopupContextItem()) { + if (ImGui::MenuItem("Remove from list")) + removePath = entry.path; + ImGui::EndPopup(); + } + auto end = ImGui::GetCursorPos(); + + auto age = formatAge(entry.lastOpened); + auto ageWidth = ImGui::CalcTextSize(age.c_str()).x; + ImGui::SetCursorPos(start); + Widgets::TextEllipsis(entry.name.c_str(), nullptr, columnWidth - ageWidth - ImGui::GetStyle().ItemSpacing.x); + ImGui::SetCursorPos(ImVec2(start.x + columnWidth - ageWidth, start.y)); + ImGui::TextDisabled("%s", age.c_str()); + ImGui::SetCursorPos(ImVec2(start.x, start.y + lineHeight)); + ImGui::PushStyleColor(ImGuiCol_Text, ImGui::GetStyleColorVec4(ImGuiCol_TextDisabled)); + Widgets::TextEllipsis(entry.path.c_str(), nullptr, columnWidth); + ImGui::PopStyleColor(); + ImGui::SetCursorPos(end); + + ImGui::PopID(); + } + + if (!removePath.empty()) { + RecentProjects::Remove(removePath); + LoadEntries(); + } + + if (auto created = RenderNewProjectPopup(window)) + openPath = created; + + ImGui::End(); + + return openPath; + + } + + void ProjectHubWindow::OpenNewProjectPopup() { + + newProjectPopupRequested = true; + error.clear(); + + } + + std::optional ProjectHubWindow::TakeDialogResult() { + + std::scoped_lock lock(dialogMutex); + if (!dialogResult) + return std::nullopt; + + auto [type, path] = *dialogResult; + dialogResult.reset(); + if (type == DialogType::OpenProject) + return path; + if (type == DialogType::AddFolder) { + auto projectPath = AddFolder(path); + return projectPath.empty() ? std::nullopt : std::optional(projectPath); + } + newLocation = path; + return std::nullopt; + + } + + std::optional ProjectHubWindow::RenderNewProjectPopup(SDL_Window* window) { + + // The popup also opens inside a project, without the hub around it + TakeDialogResult(); + + if (newProjectPopupRequested) { + ImGui::OpenPopup("New project"); + newProjectPopupRequested = false; + newName.clear(); + } + + auto viewport = ImGui::GetMainViewport(); + ImGui::SetNextWindowPos(viewport->GetCenter(), ImGuiCond_Appearing, ImVec2(0.5f, 0.5f)); + ImGui::SetNextWindowSize(ImVec2(640.0f, 0.0f), ImGuiCond_Appearing); + + if (!ImGui::BeginPopupModal("New project", nullptr, ImGuiWindowFlags_NoSavedSettings)) + return std::nullopt; + + std::optional created; + + if (Widgets::BeginProperties("New project")) { + Widgets::PropertyLabel("Name"); + if (ImGui::IsWindowAppearing()) + ImGui::SetKeyboardFocusHere(); + ImGui::SetNextItemWidth(-1.0f); + ImGui::InputTextWithHint("##Name", "Name of the project", &newName); + + Widgets::PropertyLabel("Location"); + ImGui::SetNextItemWidth(-ImGui::GetFrameHeight() - ImGui::GetStyle().ItemSpacing.x); + ImGui::InputText("##Location", &newLocation); + ImGui::SameLine(); + if (ImGui::Button("...", ImVec2(ImGui::GetFrameHeight(), 0.0f))) + ShowDialog(window, DialogType::Location); + Widgets::EndProperties(); + } + + ImGui::SeparatorText("Template"); + for (int32_t i = 0; i < int32_t(templates.size()); i++) { + ImGui::PushID(i); + if (ImGui::Selectable(templates[i].name.c_str(), templateIndex == i)) + templateIndex = i; + if (!templates[i].description.empty()) { + ImGui::Indent(); + ImGui::TextColored(Theme::TextMuted(), "%s", templates[i].description.c_str()); + ImGui::Unindent(); + } + ImGui::PopID(); + } + if (templates.empty()) + Widgets::Callout(("No templates found in " + templatesDirectory).c_str(), Theme::Warning()); + + auto target = (fs::path(newLocation) / newName).generic_string(); + std::string validation; + if (newName.empty()) + validation = "The project needs a name"; + else if (newName.find_first_of("<>:\"/\\|?*") != std::string::npos) + validation = "The name can't contain < > : \" / \\ | ? *"; + else if (!fs::is_directory(newLocation)) + validation = "The location doesn't exist"; + else if (fs::exists(target) && !fs::is_empty(target)) + validation = target + " isn't empty"; + else if (templates.empty()) + validation = "There is no template"; + + ImGui::Spacing(); + if (validation.empty()) + ImGui::TextColored(Theme::TextMuted(), "Creates %s/%s.aeproject", target.c_str(), newName.c_str()); + else + ImGui::TextColored(Theme::Warning(), "%s", validation.c_str()); + if (!error.empty()) + Widgets::Callout(error.c_str(), Theme::Error()); + + ImGui::Spacing(); + ImGui::BeginDisabled(!validation.empty()); + if (ImGui::Button("Create") || (validation.empty() && ImGui::IsKeyPressed(ImGuiKey_Enter, false))) { + templateIndex = std::clamp(templateIndex, 0, int32_t(templates.size()) - 1); + auto project = Project::Create(newLocation, newName, templates[templateIndex].directory, standardDataDirectory); + if (project) { + RecentProjects::Add(*project); + LoadEntries(); + created = project->path; + ImGui::CloseCurrentPopup(); + } + else { + error = "The project couldn't be created, the log has the details"; + } + } + ImGui::EndDisabled(); + ImGui::SameLine(); + if (ImGui::Button("Cancel") || ImGui::IsKeyPressed(ImGuiKey_Escape, false)) + ImGui::CloseCurrentPopup(); + + ImGui::EndPopup(); + + return created; + + } + + void ProjectHubWindow::LoadEntries() { + + // Projects might have been moved or deleted, which is checked once instead of every frame + entries = RecentProjects::Load(); + entryExists.clear(); + for (const auto& entry : entries) + entryExists.push_back(fs::exists(entry.path)); + + } + + void ProjectHubWindow::LoadTemplates() { + + std::error_code errorCode; + for (const auto& entry : fs::directory_iterator(templatesDirectory, errorCode)) { + if (!entry.is_directory()) + continue; + + bool hasProject = false; + for (const auto& file : fs::directory_iterator(entry.path(), errorCode)) + hasProject |= file.path().extension() == ".aeproject"; + if (!hasProject) + continue; + + Template projectTemplate = { + .directory = entry.path().generic_string(), + .name = entry.path().filename().string() + }; + + std::ifstream stream(entry.path() / "template.json", std::ios::binary); + if (stream.is_open()) { + auto j = json::parse(stream, nullptr, false); + if (!j.is_discarded()) + try_get_json(j, "description", projectTemplate.description); + } + + templates.push_back(projectTemplate); + } + + // The empty template comes first, it's the one most projects start from + std::stable_sort(templates.begin(), templates.end(), [](const Template& a, const Template& b) { + return a.name == "Empty" && b.name != "Empty"; + }); + + } + + std::string ProjectHubWindow::AddFolder(const std::string& folder) { + + std::error_code errorCode; + for (const auto& entry : fs::directory_iterator(folder, errorCode)) { + if (entry.path().extension() == ".aeproject") + return entry.path().generic_string(); + } + + Project project; + project.name = fs::path(folder).filename().string(); + project.assetDirectory = fs::is_directory(fs::path(folder) / "data") ? "data" : "."; + project.path = (fs::path(folder) / (project.name + ".aeproject")).generic_string(); + if (!project.Save()) { + error = "Couldn't create a project file in " + folder; + return std::string(); + } + + return project.path; + + } + + void ProjectHubWindow::ShowDialog(SDL_Window* window, DialogType type) { + + auto request = &dialogRequests[int32_t(type)]; + if (type == DialogType::OpenProject) { + static const SDL_DialogFileFilter filter = { "Atlas Engine project", "aeproject" }; + SDL_ShowOpenFileDialog(DialogCallback, request, window, &filter, 1, nullptr, false); + } + else { + auto location = type == DialogType::Location && fs::is_directory(newLocation) ? newLocation.c_str() : nullptr; + SDL_ShowOpenFolderDialog(DialogCallback, request, window, location, false); + } + + } + + void ProjectHubWindow::DialogCallback(void* userData, const char* const* files, int32_t filter) { + + // No list on errors, an empty one if the user cancelled + if (!files || !files[0]) + return; + + auto request = static_cast(userData); + std::scoped_lock lock(request->window->dialogMutex); + request->window->dialogResult = std::make_pair(request->type, fs::path(files[0]).generic_string()); + + } + +} diff --git a/src/editor/ui/windows/ProjectHubWindow.h b/src/editor/ui/windows/ProjectHubWindow.h new file mode 100644 index 000000000..517129838 --- /dev/null +++ b/src/editor/ui/windows/ProjectHubWindow.h @@ -0,0 +1,83 @@ +#pragma once + +#include "../../RecentProjects.h" + +#include + +#include +#include +#include +#include + +namespace Atlas::Editor::UI { + + // Shown instead of the editor when it starts without a project: the recent projects, creating a project from a + // template, opening a project file and adding a folder without one as a project + class ProjectHubWindow { + + public: + ProjectHubWindow(const std::string& standardDataDirectory, const std::string& templatesDirectory); + + // Covers the whole window, returns the path of the project file to open + std::optional Render(SDL_Window* window); + + // Asks for the folder and the template of a new project, also while a project is open + void OpenNewProjectPopup(); + + // Returns the project file of the new project once it was created + std::optional RenderNewProjectPopup(SDL_Window* window); + + private: + struct Template { + std::string directory; + std::string name; + std::string description; + }; + + enum class DialogType { + OpenProject = 0, + AddFolder, + Location + }; + + struct DialogRequest { + ProjectHubWindow* window; + DialogType type; + }; + + void LoadEntries(); + + void LoadTemplates(); + + // Uses the project file of the folder or creates one, the assets of folders with a data directory are in there + std::string AddFolder(const std::string& folder); + + void ShowDialog(SDL_Window* window, DialogType type); + + static void DialogCallback(void* userData, const char* const* files, int32_t filter); + + std::string standardDataDirectory; + std::string templatesDirectory; + + std::vector entries; + std::vector entryExists; + std::vector