Compare commits
32
Commits
7271fe8a0b
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c57ca4efe6 | ||
|
|
28a76ed404 | ||
|
|
6e1cccdb40 | ||
|
|
949a6738bd | ||
|
|
1f7e7e0541 | ||
|
|
1e34f0e67b | ||
|
|
803531c608 | ||
|
|
c5c66f8cf3 | ||
|
|
499407d366 | ||
|
|
1324d903cb | ||
|
|
d3ed573405 | ||
|
|
3317705d9c | ||
|
|
ff2e4e642d | ||
|
|
6a6294c67d | ||
|
|
bcb9a7b148 | ||
|
|
1bc73b6d2f | ||
|
|
22a90fe07c | ||
|
|
17dc1e4d88 | ||
|
|
332c47fc9d | ||
|
|
ca69fc7dbc | ||
|
|
908b52441f | ||
|
|
f2a3f59ab1 | ||
|
|
b1004d5c80 | ||
|
|
bedeb8f059 | ||
|
|
424dea0012 | ||
|
|
495e683522 | ||
|
|
ac317a3829 | ||
|
|
056589a6f9 | ||
|
|
b6a449d8e3 | ||
|
|
7af42b9bad | ||
|
|
ace1554020 | ||
|
|
87390db80d |
No files matched your search
@@ -346,3 +346,5 @@ ASALocalRun/
|
||||
# BeatPulse healthcheck temp database
|
||||
healthchecksdb
|
||||
.DS_Store
|
||||
|
||||
**/generated/**
|
||||
Vendored
+10
-16
@@ -27,26 +27,20 @@
|
||||
},
|
||||
{
|
||||
"name": "Editor (Linux)",
|
||||
"type": "cppdbg",
|
||||
"type": "lldb",
|
||||
"request": "launch",
|
||||
"program": "${workspaceRoot}/build/Editor",
|
||||
"args": [],
|
||||
"environment": [
|
||||
{
|
||||
"name": "ASAN_OPTIONS",
|
||||
"value": "alloc_dealloc_mismatch=0",
|
||||
}
|
||||
],
|
||||
"env": {
|
||||
"ASAN_OPTIONS": "detect_leaks=0",
|
||||
"DISABLE_VK_LAYER_VALVE_steam_overlay_1": "1",
|
||||
"DISABLE_VK_LAYER_VALVE_steam_fossilize_1": "1",
|
||||
"MANGOHUD": "0"
|
||||
},
|
||||
"cwd": "${workspaceRoot}/build",
|
||||
"MIMode": "gdb",
|
||||
"miDebuggerPath": "/usr/bin/gdb",
|
||||
"setupCommands": [
|
||||
{
|
||||
"description": "Enable pretty-printing for gdb",
|
||||
"text": "-enable-pretty-printing",
|
||||
"ignoreFailures": true
|
||||
}
|
||||
],
|
||||
"initCommands": [
|
||||
"command script import ${workspaceFolder}/Seele/gdb/Seele_lldb.py"
|
||||
]
|
||||
},
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
# AGENTS.md — Seele Engine
|
||||
|
||||
Guidance for AI agents (and humans) working in this repository. Read this first, then
|
||||
`README.md` and `OPTIMIZATIONS.md` for deeper design detail.
|
||||
|
||||
## What this is
|
||||
|
||||
**Seele** is a general-purpose 3D game/render engine. C++ (C++23), **Vulkan** as the primary
|
||||
graphics backend (a Metal backend exists; the `Graphics` API is designed so other backends
|
||||
like OpenGL could be added). It is a proof-of-concept engine but is built to be extensible.
|
||||
|
||||
- **Engine** — shared library, the core (`src/Engine`).
|
||||
- **Editor** — executable, the content/inspector tool (`src/Editor`).
|
||||
- **AssetViewer** — executable (`src/AssetViewer`).
|
||||
- **Benchmark** — executable (`src/Benchmark`).
|
||||
- **SeeleUnitTests** — GTest executable (`tests/`).
|
||||
|
||||
> Note: an earlier design used a coroutine-based Job system (`Job`/`MainJob`/`Event` and
|
||||
> templated `RenderPass<T>`). It was dropped (MSVC memory-leak issues + forcing everything
|
||||
> async). The shipped job system is a plain `ThreadPool` (`src/Engine/ThreadPool.{h,cpp}`,
|
||||
> `getThreadPool()`). Do not assume the coroutine API is present.
|
||||
|
||||
## Repo layout
|
||||
|
||||
```
|
||||
src/
|
||||
Engine/ # the engine shared library (one CMake target: Engine)
|
||||
Graphics/ # graphics API abstraction + Vulkan + Metal + RenderPass impls
|
||||
Vulkan/ # Vulkan backend (Graphics.h is the abstract base in Graphics/)
|
||||
Metal/ # Metal backend
|
||||
RenderPass/ # concrete render passes (BasePass, DepthCulling, LightCulling,
|
||||
# Shadow, RayTracing, ToneMapping, UI, Visibility, Fluid, ...)
|
||||
CBT/ # command buffer tracking
|
||||
Containers/ # custom containers (Array, StaticArray, Map, List, Set, Tree, ...)
|
||||
Math/ # math (glm-backed typedefs: Vector, Vector3→Vector, Matrix4, etc.)
|
||||
Asset/ # asset registry, loaders (mesh, texture, font, material, env, SVG, level)
|
||||
Material/ # material / BRDF system (Slang-generated)
|
||||
Actor/ # Entity + concrete actors (mesh, light, camera) — EnTT-based
|
||||
Component/ # components (Transform, Mesh, Camera, lights, colliders, ...)
|
||||
Scene/ # scene, event manager, light environment
|
||||
System/ # per-frame systems: SystemGraph, ComponentSystem, updaters (mesh,
|
||||
# light, fluid, camera), executor
|
||||
Physics/ # physics: BVH, collision system, physics system
|
||||
Serialization/ # ArchiveBuffer + Serialization.h
|
||||
UI/ # custom UI framework (Element, FlexLayout, Style)
|
||||
Window/ # WindowManager, View (GameView, etc.)
|
||||
Platform/ # per-OS: Linux/, Mac/, Windows/ (GameInterface)
|
||||
Editor/ # Editor executable (main.cpp, Asset/ importers, Window/ views)
|
||||
AssetViewer/ # AssetViewer executable
|
||||
Benchmark/ # Benchmark executable
|
||||
tests/
|
||||
Engine/ # GTest suite, mirrored under Engine/<Subsystem>/
|
||||
res/
|
||||
shaders/ # Slang shader sources (.slang)
|
||||
fonts/ textures/ cmake/
|
||||
cmake/ # SuperBuild.cmake, EngineConfig.cmake.in
|
||||
external/ # submodules: vcpkg, CRCpp, metal-cpp (do not edit)
|
||||
```
|
||||
|
||||
## Building
|
||||
|
||||
Standard CMake, **C++23**. Deps come from **vcpkg** (manifest mode, `vcpkg.json`) plus the
|
||||
`external/` submodules. Prereq on Linux: the X11 dev libs for GLFW
|
||||
(`libx11-dev libxrandr-dev libxinerama-dev libxcursor-dev libxi-dev`).
|
||||
|
||||
```bash
|
||||
# one-time: pull dependencies (vcpkg submodule + everything)
|
||||
git submodule update --init --recursive
|
||||
|
||||
# configure + build (use a preset)
|
||||
cmake --preset debug
|
||||
cmake --build --preset debug --config Debug
|
||||
```
|
||||
|
||||
Presets (`CMakePresets.json`): `debug`, `release`, `debug-asan`, `release-asan`,
|
||||
`debug-mac` (Xcode). Binary dir is the in-tree `build/` (gitignored). The vcpkg toolchain
|
||||
is hard-wired in the top-level `CMakeLists.txt`
|
||||
(`CMAKE_TOOLCHAIN_FILE=${EXTERNAL_ROOT}/vcpkg/scripts/buildsystems/vcpkg.cmake`).
|
||||
|
||||
- The engine is a **SHARED** lib (`add_library(Engine SHARED)`) — all four binaries link it.
|
||||
- `Editor` is compiled with `EDITOR=1` and includes `src/Editor` + the Stb includes.
|
||||
- On non-Apple, the `slang-glslang` **plugin** is a MODULE library and is **copied** next to
|
||||
the `Engine` binary at post-build (do not try to link it). On Windows the runtime DLLs are
|
||||
likewise copied next to `Editor`.
|
||||
- Windows defines `USE_EXTENSIONS` and adds `WIN32`; MSVC builds with `/W4`, GCC/Clang with
|
||||
`-Wall -Wextra -Wno-error -pedantic`. Warnings are **not** fatal, but keep the build clean.
|
||||
- There is **no CI** and no `test` preset. Run tests manually (below).
|
||||
|
||||
`OPTIMIZATIONS.md` is a scratch list of optimization ideas (LTO, PGO, attributes, copy-avoidance
|
||||
guidelines) — it is reference material, not a build requirement.
|
||||
|
||||
## Testing
|
||||
|
||||
GTest. `tests/` builds a single `SeeleUnitTests` binary and registers with CTest via
|
||||
`gtest_discover_tests`. Tests are organized to mirror the engine tree
|
||||
(`tests/Engine/Containers/Array.cpp`, `tests/Engine/Math/Vector.cpp`,
|
||||
`tests/Engine/System/ComponentSystem.cpp`, `tests/Engine/Serialization/ArchiveBuffer.cpp`,
|
||||
`tests/Engine/ThreadPool.cpp`, `tests/Engine/UI/...`, `tests/Engine/Graphics/...`).
|
||||
|
||||
- Every test file includes `tests/Engine/EngineTest.h` (which pulls in `<gtest/gtest.h>` +
|
||||
`MinimalEngine.h` + `using namespace Seele;`).
|
||||
- Add a new test: create `tests/Engine/<Subsystem>/Foo.cpp` and **add it to that
|
||||
subdirectory's `tests/Engine/<Subsystem>/CMakeLists.txt`** (the subdirs `add_subdirectory`
|
||||
into `tests/Engine/CMakeLists.txt`). Forgetting the CMake registration is the #1 way a new
|
||||
test silently never compiles or runs.
|
||||
- Run: `cd build && ctest --test-dir . -R <TestNamePattern> --output-on-failure` (or run the
|
||||
`SeeleUnitTests` binary directly). Use a `debug`/`debug-asan` preset for test development.
|
||||
|
||||
## Core architecture (read before touching Graphics/RenderPass)
|
||||
|
||||
The invariants that are **actual in the code**:
|
||||
|
||||
- **`Gfx::Graphics`** (`src/Engine/Graphics/Graphics.h`) is the abstract backend interface.
|
||||
`Vulkan::Graphics` (`Graphics/Vulkan/Graphics.h`) and `Metal::Graphics` (`Graphics/Metal/`)
|
||||
implement it. All GPU work goes through this interface; render passes must not touch
|
||||
Vulkan or Metal handles directly. `ENABLE_VALIDATION` is defined in `Graphics.h`.
|
||||
- **Window → View → RenderPass.** A `WindowManager` owns `Graphics` + `Window`s; each
|
||||
`Window` holds `View`s (a viewport; e.g. `Editor::InspectorView`, `GameView`). Rendering of
|
||||
all viewports in a window is synchronized, but per-`View` logic runs on its own thread.
|
||||
The thread handshake is the lock-protected `commitUpdate()` (logic side) → `prepareRender()`
|
||||
(render side); a `View` pushes a concrete `RenderPassDataType` packet to each pass it uses.
|
||||
- **Render passes** are plain (non-template) `RenderPass` subclasses in
|
||||
`src/Engine/Graphics/RenderPass/` (`beginFrame`/`render`/`endFrame`/`publishOutputs`/
|
||||
`createRenderPass`). All passes share one `PRenderGraphResources` object; a pass
|
||||
**publishes** the GPU outputs it produces (`publishOutputs()`) and other passes **consume**
|
||||
them by name — so pass *init order does not matter*. If you add a pass that produces or
|
||||
consumes shared resources, you must wire both the publish and the consume.
|
||||
- **Descriptor sets** for pass-shared data (camera, lights, view params) are managed per
|
||||
render pass; because Vulkan pipeline layouts cannot have empty set indices, each pass has a
|
||||
static `modifyRenderPassMacros` that `#define`s the correct descriptor-set indices for shared
|
||||
layouts. Keep that in sync if you add/remove descriptor sets.
|
||||
- **`getGlobals()`** (`MinimalEngine.h`) is the global feature/flags struct (e.g.
|
||||
`useRayTracing`, `useDepthCulling`, `running`, …). It controls which passes run. Treat it as
|
||||
global mutable state — do not add per-frame logic to it.
|
||||
|
||||
### Entities / scenes / systems (EnTT)
|
||||
|
||||
- `Actor`/`Entity` (`src/Engine/Actor/`) wrap an **EnTT** entity ID + a `PScene`. Components
|
||||
live in `src/Engine/Component/`; attach via `scene->attachComponent<C>(...)` /
|
||||
`entity.accessComponent<C>()`.
|
||||
- Per-frame update is driven by `SystemGraph` / `ComponentSystem` in `src/Engine/System/`.
|
||||
A `Component` can declare dependencies on other components (the `Dependencies` /
|
||||
`has_dependencies` / `REQUIRE_COMPONENT` mechanism in `Component.h`). The concrete updaters
|
||||
(`MeshUpdater`, `LightGather`, `FluidUpdater`, `CameraUpdater`, …) are the per-frame work
|
||||
and must be registered in the system graph.
|
||||
|
||||
### Materials (Slang-generated)
|
||||
|
||||
- A material is a JSON doc: a `profile` (BRDF, e.g. `BlinnPhong`), typed `params` (HLSL
|
||||
types + defaults), and a `code` section with one string-array per BRDF output. On load,
|
||||
the engine generates the descriptor layout and compiles a Slang `IMaterial` type (see
|
||||
`src/Engine/Material/`, `Graphics/slang-compile.cpp`).
|
||||
Shared Slang lives in `res/shaders/*.slang`; per-material pipeline variants are generated
|
||||
from a render pass's base `.slang` via `#define`s. **If you change the set of BRDF outputs
|
||||
or a shared Slang input, the generated material code and the `prepare()`/`get*` accessors
|
||||
must stay consistent** — they are produced from the JSON profile, not hand-written.
|
||||
|
||||
## Code conventions (match the surrounding code)
|
||||
|
||||
- **C++23.** The build sets `CMAKE_CXX_STANDARD 23`; C++20/23 features are in active use
|
||||
(concepts, `std::span`, designated initializers, `<=>` spaceship, `[[unlikely]]`, etc.).
|
||||
- **Formatting: `.clang-format`** — `BasedOnStyle: LLVM`, `IndentWidth: 4`, `ColumnLimit: 140`,
|
||||
left-aligned pointers (`P*`, not `P *`), 2-space class-member indent in practice (see
|
||||
`Graphics.h`/`RenderPass.h`). Headers use `#pragma once`. Keep to it; do not reformat
|
||||
untouched code.
|
||||
- **Namespaces.** Engine code lives in `namespace Seele`; the graphics backend in
|
||||
`namespace Seele::Gfx` (Vulkan impl in `Seele::Vulkan`, Metal in `Seele::Metal`).
|
||||
- **Types.**
|
||||
- Fixed-width scalars come from `EngineTypes.h`: `uint8/16/32/64`, `int8/16/32/64`.
|
||||
Prefer these over `std::uint32_t` for consistency with the codebase.
|
||||
- Math types are **glm typedefs** in `Math/Math.h`/`Vector.h`/`Matrix.h`: `Vector` is
|
||||
`glm::vec3`, `Vector2`/`Vector4`/`UVector`(`uvec3`)/`IVector`/`Quaternion`
|
||||
(`glm::quat`)/`Matrix4`, etc. Use these, not raw `glm::vec*`. `Math.h` re-exports glm.
|
||||
- `Matrix` types: `Matrix4` etc. — `Matrix.h`.
|
||||
- **Smart pointers / ownership** (the most important idiom — defined in `MinimalEngine.h`):
|
||||
- `DEFINE_REF(ClassName)` at the end of a class's header typedefs `P<Name>`, `UP<Name>`,
|
||||
`O<Name>`. `DECLARE_REF(ClassName)` is the same but only forward-declares (for
|
||||
headers that need the typedefs but not the class). `DECLARE_NAME_REF(nmsp, Name)`
|
||||
is the namespaced variant (used heavily in `Gfx`, e.g. `DECLARE_NAME_REF(Gfx, Viewport)`).
|
||||
- **`P<T>`** = `RefPtr<T>` — a *non-owning* strong reference (shared, `dynamic_cast`
|
||||
`cast()`, `<=>`-comparable). Use as the default "have a reference" type (members,
|
||||
parameters, return of non-owning lookups).
|
||||
- **`O<T>`** = `OwningPtr<T>` — the *owning* pointer (move-only, deletes on scope exit,
|
||||
implicitly converts to `P<T>`). Use it for the **result of factories/creators** —
|
||||
e.g. `Graphics::createWindow(...) -> OWindow`, `createTexture2D(...) -> OTexture2D`.
|
||||
A factory returns `O<T>`; anything storing it should keep it as `P<T>` (or pass the
|
||||
`O<T>` into a `P<T>` conversion).
|
||||
- **`UP<T>`** = `UniquePtr<T>` — move-only, deletes on scope exit.
|
||||
- You will rarely `new` explicitly: `P<Foo> p = new Foo();` is the pattern used in
|
||||
`main.cpp` / tests because `RefPtr` has a raw-pointer constructor. For factories,
|
||||
return `O<T>`.
|
||||
- Do **not** introduce `std::shared_ptr`/`std::unique_ptr` for engine objects — use the
|
||||
`P/O/UP` types.
|
||||
- **Containers:** use the engine's own in `Containers/` (`Array<T>` = heap `std::vector`-like
|
||||
with `add`/`resize`/`remove`/`removeAt`/`find`/`clear`; `StaticArray<T,N>`; `Map`, `List`,
|
||||
`Set`, `Tree`, `Pair`). There is a `MemoryResource` (pool) too. Prefer these over
|
||||
`std::vector`/`std::map` for engine data (they are what serialization etc. integrate with).
|
||||
- **Errors / asserts:** `assert()` from `<assert.h>` (see `MinimalEngine.h`). `fmt`
|
||||
(`fmt::format`) is used for string building (linked via vcpkg); `nlohmann_json` for JSON
|
||||
(see `Serialization.h`). There is no exception-based error API to follow — match local style.
|
||||
- **Per-subsystem `CMakeLists.txt`** only calls `target_sources(Engine PRIVATE ... .cpp)` and
|
||||
`target_sources(Engine PUBLIC FILE_SET HEADERS FILES ... .h)`. When you add a `.cpp`,
|
||||
add it to the `PRIVATE` list of the **nearest** `CMakeLists.txt`; when you add a public
|
||||
header, add it to `FILE_SET HEADERS` too (or it won't install/export and other targets
|
||||
can't find it).
|
||||
|
||||
## Workflow & gotchas
|
||||
|
||||
- **No CI, no `test` preset.** Nothing runs the test suite for you. Configure a `debug`/
|
||||
`debug-asan` preset, build, then `cd build && ctest --test-dir . --output-on-failure`.
|
||||
- **`src/Editor/main.cpp` hard-codes `/home/dynamitos/...` paths** (lines 26–27). The Editor
|
||||
will not run on any other machine without editing those two lines to your checkout path.
|
||||
The `if (true)` branch is the live one; the else-branch (cmake `ExportProject.cmake`
|
||||
export flow) is dead code that only worked with the original author's paths.
|
||||
- **Coroutines are not in the code.** An earlier design described a coroutine `Job`/`MainJob`
|
||||
/`Event` system and templated `RenderPass<T>`; none of it is implemented (MSVC memory leaks
|
||||
+ forcing everything async). The real job system is `ThreadPool`
|
||||
(`src/Engine/ThreadPool.{h,cpp}`, `getThreadPool()`).
|
||||
- **Render passes must not touch backend handles.** All GPU work goes through `Gfx::Graphics`.
|
||||
Adding a pass that produces or consumes a shared `RenderGraphResources` resource requires
|
||||
wiring **both** the `publishOutputs()` side and the consume-by-name side, and keeping the
|
||||
`modifyRenderPassMacros` descriptor-set index `#define`s in sync.
|
||||
- **New `.cpp`/`.h` files must be registered in CMake** — both the nearest `CMakeLists.txt`
|
||||
(`target_sources ... PRIVATE` for `.cpp`, `FILE_SET HEADERS` for public headers) and, for
|
||||
tests, the test subdirectory's `CMakeLists.txt`. An unregistered file silently never
|
||||
compiles.
|
||||
|
||||
+14
-21
@@ -54,12 +54,22 @@ if(WIN32)
|
||||
endif()
|
||||
|
||||
add_library(Engine SHARED "")
|
||||
set_target_properties(Engine PROPERTIES
|
||||
RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}
|
||||
LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}
|
||||
ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}
|
||||
)
|
||||
|
||||
target_include_directories(Engine PRIVATE src/Engine)
|
||||
target_link_libraries(Engine PUBLIC Vulkan::Vulkan)
|
||||
target_link_libraries(Engine PUBLIC GPUOpen::VulkanMemoryAllocator)
|
||||
if(NOT APPLE)
|
||||
target_link_libraries(Engine PUBLIC slang::slang-glslang)
|
||||
# slang-glslang is a MODULE library (plugin) - copy it instead of linking
|
||||
add_custom_command(TARGET Engine POST_BUILD
|
||||
COMMAND ${CMAKE_COMMAND} -E copy_if_different
|
||||
$<TARGET_FILE:slang::slang-glslang>
|
||||
$<TARGET_FILE_DIR:Engine>
|
||||
)
|
||||
endif()
|
||||
target_link_libraries(Engine PUBLIC EnTT::EnTT)
|
||||
target_link_libraries(Engine PUBLIC glfw)
|
||||
@@ -121,32 +131,15 @@ if(APPLE)
|
||||
target_compile_options(Engine PUBLIC -Wno-gnu-anonymous-struct -Wno-nested-anon-types)
|
||||
target_compile_options(Editor PUBLIC -Wno-gnu-anonymous-struct -Wno-nested-anon-types)
|
||||
endif()
|
||||
target_compile_options(Engine PUBLIC "$<$<CONFIG:DEBUG>:-DENABLE_VALIDATION>")
|
||||
target_compile_options(Engine PUBLIC "$<$<CONFIG:DEBUG>:-DSEELE_DEBUG>")
|
||||
|
||||
add_subdirectory(src/)
|
||||
#add_subdirectory(tests/)
|
||||
add_subdirectory(tests/)
|
||||
|
||||
if(WIN32)
|
||||
add_custom_target(dll_copy ALL
|
||||
COMMAND ${CMAKE_COMMAND} -E copy_if_different $<TARGET_RUNTIME_DLLS:Engine> $<TARGET_FILE_DIR:Editor>
|
||||
COMMAND_EXPAND_LISTS
|
||||
DEPENDS Editor)
|
||||
elseif(APPLE)
|
||||
add_custom_target(dll_copy ALL
|
||||
COMMAND ${CMAKE_COMMAND} -E true
|
||||
COMMAND_EXPAND_LISTS
|
||||
DEPENDS Editor)
|
||||
else()
|
||||
add_custom_target(dll_copy ALL
|
||||
COMMAND ${CMAKE_COMMAND} -E true)
|
||||
add_custom_command(TARGET Engine POST_BUILD
|
||||
COMMAND ${CMAKE_COMMAND} -E copy_if_different $<TARGET_RUNTIME_DLLS:Engine> $<TARGET_FILE_DIR:Editor>)
|
||||
endif()
|
||||
|
||||
add_custom_target(SeeleEngine ALL
|
||||
COMMAND ${CMAKE_COMMAND} -E copy_directory ${CMAKE_CURRENT_SOURCE_DIR}/res $<TARGET_FILE_DIR:Engine>
|
||||
COMMAND_EXPAND_LISTS
|
||||
DEPENDS Editor dll_copy)
|
||||
|
||||
install(
|
||||
TARGETS
|
||||
AssetViewer
|
||||
|
||||
@@ -1,2 +0,0 @@
|
||||
(?<enum>[A-Z_]*) = [0-9]*,
|
||||
case SE_${enum}:\nreturn VK_${enum};
|
||||
-324
@@ -1,324 +0,0 @@
|
||||
# Seele Engine
|
||||
|
||||
Seele is a Proof-of-Concept 3D render engine using Vulkan as it's primary graphics API, but other APIs could also be implemented. Due to this, a lot of terminology will be Vulkan-related, but it can be translated to other APIs.
|
||||
It is designed to support multithreading for more recent APIs, like DX12 or Vulkan, while still providing an interface that could be implemented by an
|
||||
API that doesn't support it, like OpenGL. These APIs would suffer a significant performance loss, but would still work correctly.
|
||||
|
||||
## Custom containers and other utilities
|
||||
|
||||
Some of the basic containers are reimplemented, mostly not for any particular feature, but because that makes them more customizable and extendable for future uses and
|
||||
performance optimizations, like serialization for example. Due to some of them occuring in the code samples later, they will be quickly mentioned here.
|
||||
|
||||
- `Array`: A heap-array backed dynamically resizable container, like `std::vector`
|
||||
- `StaticArray`: A static-array backed non-resizable container, like `std::array`
|
||||
- `Map`: A key-value splay-tree associative container, like `std::map`
|
||||
- `UniquePtr`: A smart pointer claiming ownership of an object, like `std::unique_pointer`
|
||||
- `RefPtr`: A reference counting smart pointer, similar to `std::shared_pointer`, with a few differences:
|
||||
- global pointer-based reference counting
|
||||
- this means a `RefPtr` can be constructed from a raw pointer and will retain its reference count correctly
|
||||
- for example if you construct `RefPtr<HelloWorld> ptr = new HelloWorld();`, and in the constructor of HelloWorld create `RefPtr<HelloWorld ptr = this;`, both would have a reference count of 2.
|
||||
- `DEFINE_REF`/`DECLARE_REF`: Macros to automatically typedef different types of smart pointer for convenience, for example DEFINE_REF(HelloWorld) would typedef:
|
||||
- `PHelloWorld`, the same as `RefPtr<HelloWorld>`
|
||||
- `UPHelloWorld`, the same as `UniquePtr<HelloWorld>`
|
||||
|
||||
## Basic Architecture
|
||||
|
||||
The first piece to the puzzle is the `WindowManager`, a container that manages a `Graphics` object, which is the interface for the graphics API, as well as all `Window`s that are active. Each `Window` represents, well, a window, and contains several `View`s. A `View` represents a viewport in the window. For an analogy to Unity, a `View` would be the Inspector, the Asset Browser or the Hierarchy.
|
||||
|
||||
Since all viewports in a window are backed by the same image and can only be presented together, the rendering for all viewports is synchronized, while the logic for each `View` runs in a separate thread.
|
||||
|
||||
The interactions between logic and rendering are modelled through two parts of the interface: `beginUpdate()`, `update()` and `commitUpdate()` for the logic side, and `prepareRender()` and `render()` for the rendering side. The views use a set of concrete `RenderPass` objects to render a new frame, depending on what kind of content should be displayed. In order to draw a frame, a `RenderPass` needs an "update packet" in form of a struct, but the contents of that packet is dependent on the render pass itself. A depth prepass for example might only need a mesh list, while a light culling pass needs the dynamic lights or a base pass might need both.
|
||||
|
||||
In order to avoid inheritance and casting for these update packets, each `RenderPass` needs to be updated individually by the view that uses it, so the thread interactions are not enforced in the `View` base class, instead `commitUpdate()` is called from a locked context from the logic thread, so that the view can copy the packet to a shared storage, while `prepareRender()` is locked and called from the render thread, so that it can be passed to the render passes.
|
||||
|
||||
## RenderPass
|
||||
|
||||
To better illustrate how render passes work, here is part of the `RenderPass` base class:
|
||||
|
||||
```cpp
|
||||
template<typename RenderPassDataType>
|
||||
class RenderPass
|
||||
{
|
||||
public:
|
||||
RenderPass(Gfx::PGraphics graphics, Gfx::PViewport viewport)
|
||||
: graphics(graphics)
|
||||
, viewport(viewport)
|
||||
{}
|
||||
virtual ~RenderPass()
|
||||
{}
|
||||
void updateViewFrame(RenderPassDataType viewFrame) {
|
||||
passData = std::move(viewFrame);
|
||||
}
|
||||
virtual void beginFrame() = 0;
|
||||
virtual void render() = 0;
|
||||
virtual void endFrame() = 0;
|
||||
virtual void publishOutputs() = 0;
|
||||
virtual void createRenderPass() = 0;
|
||||
//....
|
||||
private:
|
||||
PRenderGraphResources resources;
|
||||
RenderPassDataType passData;
|
||||
Gfx::PGraphics graphics;
|
||||
//....
|
||||
};
|
||||
```
|
||||
|
||||
All render passes in a `View` share a `RenderGraphResources` object, which is used to share outputs between the different passes. During initialization, every render pass "publishes" any outputs that it produces in `publishOutputs()`, so that they can be consumed by other render passes. For example the output of a depth prepass is the depth buffer, for a light culling pass it is the culled light indices. Next the render passes get any resources that they require and have been registered by other passes to create the render pass in `createRenderPass()`. This is split into two parts, so that the order of initialization of different renderpasses doesn't matter, as all outputs are available before any are requested.
|
||||
|
||||
## Materials
|
||||
|
||||
The material system fully embraced a Vulkan-style descriptor system, abstracted by the `Graphics` API. A material is a file stored on disk in form of a JSON document, here is an example:
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "Placeholder",
|
||||
"profile": "BlinnPhong",
|
||||
"params": {
|
||||
"diffuseTexture": {
|
||||
"type": "Texture2D"
|
||||
},
|
||||
"specularTexture": {
|
||||
"type": "Texture2D"
|
||||
},
|
||||
"normalTexture": {
|
||||
"type": "Texture2D"
|
||||
},
|
||||
"uvScale": {
|
||||
"type": "float",
|
||||
"default": "0.0f"
|
||||
},
|
||||
"metallic": {
|
||||
"type": "float",
|
||||
"default": "0.0f"
|
||||
},
|
||||
"roughness": {
|
||||
"type": "float",
|
||||
"default": "0.5f"
|
||||
},
|
||||
"sheen": {
|
||||
"type": "float",
|
||||
"default": "0.0f"
|
||||
},
|
||||
"worldOffset": {
|
||||
"type": "float3",
|
||||
"default": "float3(0, 0, 0)"
|
||||
},
|
||||
"textureSampler": {
|
||||
"type": "SamplerState"
|
||||
}
|
||||
},
|
||||
"code": {
|
||||
"baseColor": [
|
||||
"return diffuseTexture.Sample(textureSampler, input.texCoords[0] * uvScale).xyz;"
|
||||
],
|
||||
"metallic": [
|
||||
"return metallic;"
|
||||
],
|
||||
"normal": [
|
||||
"return normalTexture.Sample(textureSampler, input.texCoords[0] * uvScale).xyz;"
|
||||
],
|
||||
"specular": [
|
||||
"return specularTexture.Sample(textureSampler, input.texCoords[0] * uvScale).x;"
|
||||
],
|
||||
"roughness": [
|
||||
"return roughness;"
|
||||
],
|
||||
"sheen": [
|
||||
"return sheen;"
|
||||
],
|
||||
"worldOffset": [
|
||||
"return worldOffset;"
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The document starts with the asset `name`, followed by the `profile`, which tells the engine which BRDF function it uses, and thus what outputs it can expect from the material. Next are the parameters, which are the inputs that need to get passed to the shader later. The `type` field must be a valid HLSL datatype and `default` a valid value for that datatype. In the `code` section, there must be an entry for every output required by the `profile`, each of which is a string array for each line of shader code to compute that value and ends by `return`ing that value.
|
||||
|
||||
### MaterialAsset
|
||||
|
||||
A `MaterialAsset` represents such a JSON document on disk, as well as the GPU resources needed to render a mesh with the material. When loading the file, the a descriptor layout is generated to fit the `slang` code that will be generated later by consolidating the plain variables (`float`, `double`, etc.) into a single uniform buffer. The parameters are stored in an array of `ShaderParameter`s, which contain the current parameter value, like texture references or plain data, as well as information on how to update the GPU resources.
|
||||
|
||||
At the same time a slang-compilable shader is generated, which matches the parameters provided by the descriptor layout. The generated shader is a `Material`, which is an interface that "prepares" a BRDF by initializing its input values, similar to official slang example. How each input value is calculated is read from the `code` section of the JSON document, and wrapped in an accessor to allow for multi line calculations.
|
||||
|
||||
Here is the material generated from the above JSON example:
|
||||
|
||||
```cpp
|
||||
import VERTEX_INPUT_IMPORT;
|
||||
import Material;
|
||||
import MaterialParameter;
|
||||
|
||||
struct Placeholder: IMaterial {
|
||||
layout(offset = 0)float anisotropic;
|
||||
layout(offset = 4)float clearCoat;
|
||||
layout(offset = 8)float clearCoatGloss;
|
||||
Texture2D diffuseTexture;
|
||||
layout(offset = 12)float metallic;
|
||||
Texture2D normalTexture;
|
||||
layout(offset = 16)float roughness;
|
||||
layout(offset = 20)float sheen;
|
||||
layout(offset = 24)float sheenTint;
|
||||
Texture2D specularTexture;
|
||||
layout(offset = 28)float specularTint;
|
||||
layout(offset = 32)float subsurface;
|
||||
SamplerState textureSampler;
|
||||
layout(offset = 36)float uvScale;
|
||||
layout(offset = 40)float3 worldOffset;
|
||||
|
||||
float3 getBaseColor(MaterialFragmentParameter input) {
|
||||
return diffuseTexture.Sample(textureSampler, input.texCoords[0] * uvScale).xyz;;
|
||||
}
|
||||
float getMetallic(MaterialFragmentParameter input) {
|
||||
return 0;;
|
||||
}
|
||||
float3 getNormal(MaterialFragmentParameter input) {
|
||||
return normalTexture.Sample(textureSampler, input.texCoords[0] * uvScale).xyz;;
|
||||
}
|
||||
float getSpecular(MaterialFragmentParameter input) {
|
||||
return specularTexture.Sample(textureSampler, input.texCoords[0] * uvScale).x;;
|
||||
}
|
||||
float getRoughness(MaterialFragmentParameter input) {
|
||||
return roughness;;
|
||||
}
|
||||
float getSheen(MaterialFragmentParameter input) {
|
||||
return sheen;;
|
||||
}
|
||||
float3 getWorldOffset() {
|
||||
return worldOffset;;
|
||||
}
|
||||
typedef BlinnPhong BRDF;
|
||||
BlinnPhong prepare(MaterialFragmentParameter geometry){
|
||||
BlinnPhong result;
|
||||
result.baseColor = getBaseColor(geometry);
|
||||
result.metallic = getMetallic(geometry);
|
||||
result.normal = getNormal(geometry);
|
||||
result.specular = getSpecular(geometry);
|
||||
result.roughness = getRoughness(geometry);
|
||||
result.sheen = getSheen(geometry);
|
||||
return result;
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
### Renderpass interaction
|
||||
|
||||
Each render pass has a "base file" containing the vertex and fragment stages. From that base file a variant is generated for each material that will be used with that render pass using `#define` macros to change the material import, and a `type_param` to update the `ParameterBlock` containing the material itself. Other renderpass dependent data like camera parameter or lights are stored in separate descriptor sets, and to avoid code duplication, they parts that are used by more than one render pass are implemented in separate slang files. But since in Vulkan pipeline layouts cannot have empty indices, the descriptor set indices sometimes need to change. This is done using the static `modifyRenderPassMacros` function in each renderpass to `#define` the correct set indices for each shared descriptor layout.
|
||||
|
||||
## Job System
|
||||
|
||||
The Job System is based on C++20 coroutines, running on a thread pool with 1 main thread and as many worker threads as the native CPU has. This is so that when the main thread needs to block for some thread pool work, the CPU can utilize all its resources. Synchronization is done using `Event`s, which are awaitable wrappers for atomic flags.
|
||||
|
||||
### Creating Jobs
|
||||
|
||||
In order to run a function as a Job, its return type must simply be either `Job` or `MainJob`. Also, any `Job` must contain either a `co_await` or `co_return` statement. As the names suggest, `MainJob`s will always run on the main thread, while `Job`s can run on any thread. Some graphics operations, especially regarding windowing, can only occur on the main thread, which is the reason for the separation. Due to the specification for [coroutines](https://en.cppreference.com/w/cpp/language/coroutines) being incredibly complicated and non-intuitive, a detailed description will be neglected for some code snippets.
|
||||
|
||||
```cpp
|
||||
Job doSomething()
|
||||
{
|
||||
std::cout << "Doing something" << std::endl;
|
||||
co_return;
|
||||
}
|
||||
Job doSomethingElse()
|
||||
{
|
||||
std::cout << "Doing something else" << std::endl;
|
||||
co_return;
|
||||
}
|
||||
Job doSomethingAfterwards()
|
||||
{
|
||||
std::cout << "Doing something afterwards" << std::endl;
|
||||
co_return;
|
||||
}
|
||||
Job startHere()
|
||||
{
|
||||
Job job1 = doSomething();
|
||||
Job job2 = doSomethingElse();
|
||||
co_await job1;
|
||||
co_await job2;
|
||||
co_await doSomethingAfterwards();
|
||||
}
|
||||
```
|
||||
|
||||
This example will execute the first two functions in an undefined order, while the last one will always be executed last. This is because the jobs are launched as soon as the functions are called, while the co_await operator waits for them to finish. Keeping the return value of every job launched is a bit inconvenient, so there is are some helper functions to help with that. `Job::all()` takes a variable amount of `Job`s which it 'combines' into one. This reduces the previous example into this:
|
||||
|
||||
```cpp
|
||||
Job doSomething()
|
||||
{
|
||||
std::cout << "Doing something" << std::endl;
|
||||
co_return;
|
||||
}
|
||||
Job doSomethingElse()
|
||||
{
|
||||
std::cout << "Doing something else" << std::endl;
|
||||
co_return;
|
||||
}
|
||||
Job doSomethingAfterwards()
|
||||
{
|
||||
std::cout << "Doing something afterwards" << std::endl;
|
||||
co_return;
|
||||
}
|
||||
Job startHere()
|
||||
{
|
||||
co_await Job::all(
|
||||
doSomething(),
|
||||
doSomethingElse());
|
||||
co_await doSomethingAfterwards();
|
||||
}
|
||||
```
|
||||
|
||||
Any Job can also be continued with `then()`, taking in another `Job` or anything that evaluates to a `Job` if called. This further simplifies the example:
|
||||
|
||||
```cpp
|
||||
Job doSomething()
|
||||
{
|
||||
std::cout << "Doing something" << std::endl;
|
||||
co_return;
|
||||
}
|
||||
Job doSomethingElse()
|
||||
{
|
||||
std::cout << "Doing something else" << std::endl;
|
||||
co_return;
|
||||
}
|
||||
Job doSomethingAfterwards()
|
||||
{
|
||||
std::cout << "Doing something afterwards" << std::endl;
|
||||
co_return;
|
||||
}
|
||||
Job startHere()
|
||||
{
|
||||
co_await Job::all(
|
||||
doSomething(),
|
||||
doSomethingElse())
|
||||
.then(doSomethingAfterwards());
|
||||
}
|
||||
```
|
||||
|
||||
### Events
|
||||
|
||||
Aside from `Job`s, `Event`s can also be used to synchronize functions. They are constructed with an optional name for easier debugging, and can be `co_await`ed. For the waiting job to continue, `raise()` must be called, after which one of the waiting jobs should `reset()` the event to make it reusable.
|
||||
|
||||
```cpp
|
||||
Event updateFinished;
|
||||
std::mutex dataLock;
|
||||
uint64 data = 0;
|
||||
|
||||
Job updateSomething()
|
||||
{
|
||||
{
|
||||
std::scoped_lock lock(dataLock);
|
||||
data++;
|
||||
}
|
||||
updateFinished.raise();
|
||||
updateSomething(); // if we call the function again it behaves like a loop
|
||||
}
|
||||
|
||||
Job processUpdates()
|
||||
{
|
||||
co_await updateFinished;
|
||||
updateFinished.reset();
|
||||
{
|
||||
std::scoped_lock lock(dataLock);
|
||||
std::cout << data << std::endl;
|
||||
}
|
||||
processUpdates();
|
||||
}
|
||||
```
|
||||
@@ -1,4 +0,0 @@
|
||||
// Hint files help the Visual Studio IDE interpret Visual C++ identifiers
|
||||
// such as names of functions and macros.
|
||||
// For more information see https://go.microsoft.com/fwlink/?linkid=865984
|
||||
#define DECLARE_REF(x)
|
||||
+135
@@ -0,0 +1,135 @@
|
||||
# Seele — Engine Documentation (for coding agents)
|
||||
|
||||
> **Start here if you are a coding agent (or a human new to the repo) and need to
|
||||
> navigate the Seele engine and the MeshShadingDemo test harness.** This `docs/`
|
||||
> tree is the *per-subsystem navigation layer*. It complements — it does **not**
|
||||
> replace — the engine-root [`AGENTS.md`](../AGENTS.md), which is the
|
||||
> map + the hard rules. Read that first; use this tree to drill into a specific
|
||||
> area.
|
||||
|
||||
---
|
||||
|
||||
## 0. What this repository is (30-second orientation)
|
||||
|
||||
- **`Seele`** is a C++ game engine. It lives in this submodule
|
||||
(`external/Seele` inside the parent monorepo). It has a **Vulkan** and **Metal**
|
||||
backend, an ECS (entt-based), a render graph, a Slang-based material/shader
|
||||
system, a Jolt-based physics layer, a full **flexbox UI**, and an **asset
|
||||
pipeline**. ~320 source files under `src/Engine/`.
|
||||
- **`MeshShadingDemo`** is a *test game* built against Seele. It is **not** the
|
||||
product; it is the integration harness. The engine is the product. The demo
|
||||
shows how a real consumer composes a game (scene, systems, materials,
|
||||
render-graph overrides) against the engine.
|
||||
- The **engine↔demo boundary** is a strict ABI: the engine's per-OS
|
||||
`GameInterface` `dlopen`/`LoadLibrary`-loads the demo's shared library and
|
||||
resolves exactly two C symbols (`createInstance` / `destroyInstance`). See
|
||||
[`cross-repo.md`](cross-repo.md) for the full contract.
|
||||
|
||||
**The single best first read is [`../AGENTS.md`](../AGENTS.md)** (engine root):
|
||||
the memory model, the `update`/GPU phase split, the Jolt ground rules, the
|
||||
culling note, and a subsystem map. Everything below is the per-subsystem drill-
|
||||
down it points into.
|
||||
|
||||
---
|
||||
|
||||
## 1. The cross-repo contract (read before touching either repo)
|
||||
|
||||
📄 [`cross-repo.md`](cross-repo.md) — **the orientation doc for working across
|
||||
both repos.** It covers:
|
||||
|
||||
1. The repo relationship (engine = submodule, demo = harness).
|
||||
2. **The engine↔demo ABI** — the two-C-symbol contract (`createInstance` /
|
||||
`destroyInstance`), how the per-OS `GameInterface` loads the demo's shared
|
||||
lib, and the **shader-copy-on-reload** gotcha.
|
||||
3. **The demo-side `ComponentSystem<...>` pattern** (the only pattern you need
|
||||
for per-frame demo logic), with the canonical `FlyCamSystem` example.
|
||||
4. **The CMake contract** — in-tree `add_subdirectory` (what the demo does) vs.
|
||||
the engine's out-of-tree `install(EXPORT)` / `FILE_SET HEADERS` path.
|
||||
5. A **practical "where do I look" task map** and the three invariants that
|
||||
save hours.
|
||||
|
||||
> **Rule of thumb:** engine changes go *in the submodule* (commit inside
|
||||
> `external/Seele`, then re-record the submodule pointer in the parent). The
|
||||
> demo never edits engine code.
|
||||
|
||||
---
|
||||
|
||||
## 2. Per-subsystem deep dives
|
||||
|
||||
Each doc follows the same shape: **key types & where they live** (a per-type
|
||||
table mapping each public type to its defining header), **data flow /
|
||||
lifecycle**, **where to look** (file:line pointers), and **gotchas & sharp
|
||||
edges**. Links below are to the real files.
|
||||
|
||||
### Core engine
|
||||
|
||||
| Area | Doc | What it covers |
|
||||
|---|---|---|
|
||||
| **Scene / ECS / Components / Actors** | [scene-ecs](subsystems/scene-ecs-components-actors.md) | The entt registry, `Actor`, `Component` model, how the demo composes a scene in `setupScene`. The foundation everything else builds on. |
|
||||
| **Component Systems & the Update Loop** | [systems](subsystems/systems-update-loop.md) | `System`, `SystemGraph`, `ComponentSystem`, the per-frame tick order, the CPU/GPU phase split. |
|
||||
| **Game Interface & Frame Loop** | [game-interface](subsystems/game-interface.md) | `Game` (abstract), `GameView`, the render/update protocol (`beginUpdate`/`update`/`commitUpdate`/`prepareRender`/`render`), the frame loop. |
|
||||
| **Window & view layer** | [window](subsystems/window.md) | `Window`, `WindowManager`, `View`, `GameView` — the OS window, the render/update protocol, the frame loop wiring. |
|
||||
|
||||
### Graphics (GPU)
|
||||
|
||||
| Area | Doc | What it covers |
|
||||
|---|---|---|
|
||||
| **Graphics Abstract Backend** | [graphics-backend](subsystems/graphics-abstract-backend.md) | `Gfx::Graphics` — the backend-agnostic API (buffers, textures, pipelines, descriptors, render passes). The layer you write against. |
|
||||
| **Render Graph & Render Passes** | [render-graph](subsystems/render-graph-and-passes.md) | The auto-invalidated render graph, render passes, dependencies, **meshlet layout**, and the **ray-tracing** paths. |
|
||||
| **GPU Resources** | [graphics-resources](subsystems/graphics-resources.md) | Buffers, textures, shaders, pipelines, descriptor sets in the abstract layer — and how they map to the backends. |
|
||||
| **Vulkan Backend** | [vulkan](subsystems/vulkan-backend.md) | `Vulkan::Graphics` — the concrete Vulkan implementation, its gotchas, and the RT path. |
|
||||
| **Metal Backend** | [metal](subsystems/metal-backend.md) | `Metal::Graphics` — the concrete Metal implementation, its gotchas, and the RT path. |
|
||||
| **Materials & Shader Graphs** | [materials](subsystems/materials-shader-graphs.md) | `ShaderExpression` — the Slang-based material/shader-graph system, parameter binding, and how the demo overrides the render graph. |
|
||||
|
||||
### Simulation & content
|
||||
|
||||
| Area | Doc | What it covers |
|
||||
|---|---|---|
|
||||
| **Physics (Jolt)** | [physics](subsystems/physics.md) | The Jolt wrapper, `PhysicsSystem`, `CollisionSystem`, BVH broadphase, witness-based narrowphase. |
|
||||
| **UI (flexbox)** | [ui](subsystems/ui.md) | The full flexbox layout engine (two-phase measure/place), the element tree, widgets, theming/styles, the `UIRender` quad pipeline. A separate render path from the 3D scene. |
|
||||
| **Asset Pipeline** | [assets](subsystems/asset-pipeline.md) | `AssetManager`, loaders, storage — how assets are loaded, cached, and streamed. |
|
||||
|
||||
### Platform & core
|
||||
|
||||
| Area | Doc | What it covers |
|
||||
|---|---|---|
|
||||
| **Platform / OS abstraction** | [platform](subsystems/platform.md) | Per-OS `GameInterface` (Windows/Linux/Mac), dynamic library loading (`dlopen`/`LoadLibrary`/`NSCreateObject`), input enums, and the **shader-copy-on-reload** mechanism. This is where the engine↔demo boundary is physically enforced. |
|
||||
| **Core Utilities** | [core-utils](subsystems/core-utilities.md) | Math, containers, log, time, memory, reflection, **serialization** — the cross-cutting utilities every other subsystem uses. |
|
||||
|
||||
---
|
||||
|
||||
## 3. How to use this tree (agent workflow)
|
||||
|
||||
1. **Orient** — read [`../AGENTS.md`](../AGENTS.md) (rules) + [`cross-repo.md`](cross-repo.md)
|
||||
(the contract). Ten minutes, saves hours.
|
||||
2. **Locate** — use the table above (or `cross-repo.md` §5's task map) to find
|
||||
the subsystem doc for your task.
|
||||
3. **Navigate** — the subsystem doc's **key-types table** tells you *which
|
||||
header* defines each type; **where-to-look** gives file:line pointers into
|
||||
the actual source. Go to the source — this tree is a *map*, not the
|
||||
source of truth for implementation detail.
|
||||
4. **Respect the rules** — the memory model (`DEFINE_REF`/`DECLARE_REF`,
|
||||
`RefPtr`/`OwningPtr`/`UniquePtr`), the CPU/GPU phase split, and the Jolt
|
||||
ground rules from `AGENTS.md` apply everywhere. When a doc and `AGENTS.md`
|
||||
disagree, `AGENTS.md` wins.
|
||||
|
||||
**If a subsystem doc is missing or wrong** (the engine moves fast), update it
|
||||
here — the format is simple and consistent (key types → data flow → where to
|
||||
look → gotchas). Keep `AGENTS.md` for cross-cutting *rules* and this tree for
|
||||
*per-subsystem navigation*.
|
||||
|
||||
---
|
||||
|
||||
## 4. Pointers to the rest of the repo
|
||||
|
||||
- [`../AGENTS.md`](../AGENTS.md) — **the rules + map** (start here).
|
||||
- [`../README.md`](../README.md) — the human-facing engine README (build
|
||||
instructions, features).
|
||||
- [`../OPTIMIZATIONS.md`](../OPTIMIZATIONS.md) — the optimization notes
|
||||
(meshlet/culling strategy).
|
||||
- [`../Culling.md`](../Culling.md) — the culling design note (referenced by
|
||||
the render-graph and physics docs).
|
||||
- [`../CMakeLists.txt`](../CMakeLists.txt) — the engine build (install/export
|
||||
path; see `cross-repo.md` §4.2).
|
||||
- `src/Engine/` — the source tree, ~320 files, ~20 subsystems (the per-subsystem
|
||||
docs above map onto it directory-by-directory).
|
||||
@@ -0,0 +1,348 @@
|
||||
# Seele × MeshShadingDemo — Cross-Repository Orientation
|
||||
|
||||
> **Read this first** if you are an agent working in the *MeshShadingDemo* test
|
||||
> repository and need to reach into the **Seele engine** at `external/Seele`, or
|
||||
> vice-versa. This is the "how does the test game plug into the engine" doc.
|
||||
> For engine-internal navigation (per-subsystem deep dives) see
|
||||
> [`docs/README.md`](README.md) and [`AGENTS.md`](../AGENTS.md).
|
||||
|
||||
The **MeshShadingDemo** repo is *not* a standalone app. It is a **test game /
|
||||
integration harness** built *against* the Seele engine. It exists to exercise the
|
||||
engine (mesh shading, lighting, culling, the render pipeline) with real content.
|
||||
The engine itself lives in the `external/Seele` **git submodule** and is the only
|
||||
place engine code should be modified.
|
||||
|
||||
---
|
||||
|
||||
## 1. Repository relationship (the two repos)
|
||||
|
||||
| | **Seele (the engine)** | **MeshShadingDemo (the test game)** |
|
||||
|---|---|---|
|
||||
| Role | Game engine (C++23, Vulkan/Metal) | Test / integration harness |
|
||||
| Location | `external/Seele/` (git submodule → `Dynamitos/Seele`) | repo root |
|
||||
| Default branch | `master` | `main` |
|
||||
| Build target | `Engine` (SHARED lib) + `Editor`, `Benchmark`, `AssetViewer`, tests | `MeshShadingDemo` (SHARED lib, a **plugin DLL**) |
|
||||
| Where you change | engine code, render passes, materials, components | scene content, demo actors, demo systems, camera rigs |
|
||||
|
||||
**The rule that keeps the two from bleeding together:**
|
||||
|
||||
- To change *engine* behaviour (rendering, components, systems, assets) → edit
|
||||
files under `external/Seele/`. That is a **separate repository**; a commit
|
||||
there must be made *inside the submodule* and then the parent repo must
|
||||
re-record the new submodule pointer.
|
||||
- To change the *demo* (which meshes, lights, camera moves, what the test
|
||||
asserts) → edit files in the demo repo (`src/`, `res/`, `CMakeLists.txt`).
|
||||
These files never touch the engine.
|
||||
|
||||
Both repos are consumed by the same CMake build: the demo's top-level
|
||||
`CMakeLists.txt` does `add_subdirectory(external/Seele)` and links the engine's
|
||||
`Engine` target. There is one build tree, two source trees, two git identities.
|
||||
|
||||
---
|
||||
|
||||
## 2. The plugin contract: how a "game" plugs into the engine
|
||||
|
||||
The engine is backend-agnostic about *games*. A "game" is just a **shared
|
||||
library that exports two C symbols** and provides a `Seele::Game` subclass. The
|
||||
engine (or any host) loads the DLL, calls `createInstance()`, and the engine
|
||||
drives the game. This is the *entire* contract — it is deliberately tiny.
|
||||
|
||||
### 2.1 The engine side (`Seele::Game`)
|
||||
|
||||
`src/Engine/Game.h` (12 lines total — the whole interface):
|
||||
|
||||
```cpp
|
||||
namespace Seele {
|
||||
class Game {
|
||||
public:
|
||||
Game() {}
|
||||
virtual ~Game() {}
|
||||
virtual void setupScene(PScene scene, PSystemGraph graph) = 0; // the only hook
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
That single pure-virtual, `setupScene(PScene, PSystemGraph)`, is the **only**
|
||||
entry point the engine gives a game. The engine hands you:
|
||||
|
||||
- a **`PScene`** — the scene to populate (entities, components, actors), and
|
||||
- a **`PSystemGraph`** — the per-frame system graph to register your update
|
||||
systems into.
|
||||
|
||||
You do *not* own the main loop, the window, the render loop, or the
|
||||
`Graphics` instance. The engine (specifically the `WindowManager` + `GameView`)
|
||||
owns all of that. Your job in `setupScene` is to **declare content and
|
||||
per-frame work**; the engine runs the frame loop and calls your systems.
|
||||
|
||||
> This is why there is no "main" in a Seele game and no `app.run()` call — the
|
||||
> host (the editor, a benchmark harness, or the game's own `main.cpp`) is what
|
||||
> owns `WindowManager` and pumps frames.
|
||||
|
||||
### 2.2 The demo side (what MeshShadingDemo actually ships)
|
||||
|
||||
`src/MeshShadingDemoGame.h` + `.cpp` implement the contract:
|
||||
|
||||
- `class MeshShadingDemoGame : public Game` with the override
|
||||
`setupScene(PScene, PSystemGraph)`.
|
||||
- `extern "C" MESHSHADINGDEMO_API Game* createInstance();` — constructs and
|
||||
returns the game (host calls this to load the plugin).
|
||||
- `extern "C" MESHSHADINGDEMO_API void destroyInstance(Game* game);` — the
|
||||
matching teardown (host calls this to unload it).
|
||||
|
||||
`MESHSHADINGDEMO_API` is the DLL export macro in `src/Define.h`
|
||||
(`__declspec(dllexport)` when building the DLL, `dllimport` otherwise, empty on
|
||||
non-Windows). `Define.h` also does `using namespace Seele;` so demo code can
|
||||
write `Scene`, `Component::Camera`, etc. without the namespace.
|
||||
|
||||
**When you add demo content, the flow is:**
|
||||
|
||||
1. In `setupScene`, create actors via the engine factories
|
||||
(`scene->createActor<...>()` / `O<...Actor>`) — e.g. `OStaticMeshActor`,
|
||||
`ODirectionalLightActor`, `OPointLightActor`, `OFlyCam`, `OPathFollowCam`.
|
||||
2. Attach components (`scene->attachComponent<Component::Mesh>(...)`,
|
||||
`.Transform`, `.Camera`, etc.) to those actors.
|
||||
3. Register any **demo-specific per-frame systems** with
|
||||
`graph->addSystem<OYourSystem>(...)`. See §3.
|
||||
4. Load assets through the engine's `AssetRegistry`
|
||||
(`assetRegistry->findMesh<...>(path)`, `findMaterial`, `findTexture`) — the
|
||||
demo never parses asset files itself; the engine's importers (§ in the
|
||||
asset docs) do that.
|
||||
|
||||
The demo's `MeshShadingDemoGame::setupScene` is the canonical example of all
|
||||
four steps; it is the single best "how a game is composed" reference in the
|
||||
whole monorepo. **Read it before touching demo code.**
|
||||
|
||||
---
|
||||
|
||||
## 3. The demo-side system pattern (per-frame logic lives here)
|
||||
|
||||
The demo is not just a scene — it carries its **own per-frame systems** (camera
|
||||
rigs). These are *demo* `System`s: they live in the demo repo, are registered
|
||||
into the engine's `SystemGraph` from `setupScene`, and operate on **demo
|
||||
components** (`Component::Path`, `Component::PathFollow`, plus the engine's own
|
||||
`Camera`/`Transform`/`KeyboardInput`). This is the "game logic" half of the
|
||||
cross-repo contract.
|
||||
|
||||
### 3.1 The `ComponentSystem<...>` pattern (the only pattern you need)
|
||||
|
||||
The demo's systems all derive from the engine's **`System::ComponentSystem`**
|
||||
(`src/Engine/System/ComponentSystem.h` in the engine). A `ComponentSystem<...>`
|
||||
is a `System` whose `update` is invoked **per entity that carries every one of
|
||||
the template parameter components**. The engine's ECS (entt) does the entity
|
||||
selection for you; you just write the per-entity body.
|
||||
|
||||
**The canonical example** (`src/System/FlyCamSystem.h` in the demo):
|
||||
|
||||
```cpp
|
||||
class FlyCamSystem : public System::ComponentSystem<
|
||||
Component::KeyboardInput, // <- entity must have all of these
|
||||
Component::Camera,
|
||||
Component::Transform,
|
||||
Component::PointLight>
|
||||
{
|
||||
public:
|
||||
FlyCamSystem(PScene scene);
|
||||
virtual ~FlyCamSystem();
|
||||
// one call per matching entity, with the components passed in already:
|
||||
virtual void update(Seele::Component::KeyboardInput& input,
|
||||
Seele::Component::Camera& camera,
|
||||
Seele::Component::Transform& transform,
|
||||
Seele::Component::PointLight& pointLight) override;
|
||||
private:
|
||||
float lastMouseX; // per-system state (NOT per-entity — see gotchas)
|
||||
float lastMouseY;
|
||||
};
|
||||
DEFINE_REF(FlyCamSystem)
|
||||
```
|
||||
|
||||
Key facts about this pattern:
|
||||
|
||||
- **Template params = the entity query.** Add/remove a component in the
|
||||
`ComponentSystem<...>` list and the set of entities your `update` runs on
|
||||
changes. This is how the "I want to run on every fly-cam entity" selection is
|
||||
expressed — there is no manual query writing.
|
||||
- **The `update` signature mirrors the template list, in order.** The engine
|
||||
binds each of your `update`'s parameters to the corresponding component on
|
||||
the matched entity. Get the order or the type wrong and it won't compile.
|
||||
- **`DEFINE_REF(YourSystem)`** is required at the bottom — the demo's systems
|
||||
are `RefPtr`/`OwningPtr`-managed like engine systems.
|
||||
- **Constructor takes a `PScene`** — you get the scene for creating/attaching
|
||||
things; you do *not* own the graph.
|
||||
|
||||
### 3.2 The two demo systems that exist (and the rig they serve)
|
||||
|
||||
The demo ships **two** systems, both camera rigs (`src/System/`):
|
||||
|
||||
| System | Components (the query) | What it does |
|
||||
|---|---|---|
|
||||
| `FlyCamSystem` | `KeyboardInput`, `Camera`, `Transform`, `PointLight` | WASD/mouse fly camera; drives a `PointLight` (the "light follows the cam" test rig). |
|
||||
| `SplineCamSystem` | `Camera`, `Transform`, `Path`, `PathFollow` | moves a `Camera` along a demo `Path` (a control-point spline) via `PathFollow` progress — the cinematic path camera. |
|
||||
|
||||
The **path machinery is demo-side**: `Component::Path` (`src/Component/Path.h`)
|
||||
holds a control-point spline; `Component::PathFollow` holds a progress
|
||||
parameter; `SplineCamSystem` samples the spline and writes the camera
|
||||
`Transform`. The engine has no knowledge of "spline cameras" — that's demo
|
||||
logic built on the engine's generic `Transform`/`Camera` components.
|
||||
|
||||
### 3.3 The demo's actors (the "game objects")
|
||||
|
||||
Demo content actors live in `src/Actor/` (`FlyCam`, `PathFollowCam`). The
|
||||
`FlyCam`/`PathFollowCam` *actors* are thin wrappers that *attach* the relevant
|
||||
components; the actual per-frame behavior is in the systems above. The
|
||||
`setupScene` in `src/MeshShadingDemoGame.cpp` is where actors are created and
|
||||
components attached. **When you add a new camera rig or content type, the
|
||||
pattern is exactly what the two existing ones do:** an actor that attaches
|
||||
components + a `ComponentSystem` that reads them.
|
||||
|
||||
### 3.4 Gotchas (demo systems)
|
||||
|
||||
- **Per-system state vs per-entity state.** A `ComponentSystem` `update` runs
|
||||
*per entity*. Any member field on the system (like `FlyCamSystem::lastMouseX`)
|
||||
is **shared across every matched entity** — it is per-*system*, not
|
||||
per-*entity*. If you need per-entity state, put it in a **component**, not in
|
||||
a system field. This is the most common demo-system bug (stale state leaking
|
||||
between entities that happen to match the same query).
|
||||
- **Do not add GPU work in `update`.** Same rule as the engine: `update` is the
|
||||
CPU tick; anything that touches the render graph / GPU belongs in the
|
||||
engine's render-side systems (or you're in the wrong layer). Demo systems
|
||||
only write transforms and component state.
|
||||
- **`ComponentSystem` order = binding order.** The template list order and the
|
||||
`update` parameter order must line up 1:1. The compiler is your friend here.
|
||||
- **Demo components** like `Path`/`PathFollow` are plain data structs stored
|
||||
*by value* in the entt registry — no `REF` needed. (See
|
||||
[scene-ecs-components-actors.md](subsystems/scene-ecs-components-actors.md)
|
||||
for the component model.)
|
||||
|
||||
---
|
||||
|
||||
## 4. The CMake contract (how the two builds are stitched)
|
||||
|
||||
There are **two ways** to consume the engine, and the demo uses the first:
|
||||
|
||||
### 4.1 In-tree (what the demo actually does)
|
||||
|
||||
The demo's top-level `CMakeLists.txt` (`main/CMakeLists.txt` in the demo repo)
|
||||
does:
|
||||
|
||||
```cmake
|
||||
set(CMAKE_TOOLCHAIN_FILE .../external/Seele/external/vcpkg/scripts/buildsystems/vcpkg.cmake)
|
||||
project(MeshShadingDemo)
|
||||
add_subdirectory(external/Seele) # <- builds the Engine target in-tree
|
||||
|
||||
add_library(MeshShadingDemo SHARED "")
|
||||
target_link_libraries(MeshShadingDemo PUBLIC Engine) # <- link the engine
|
||||
target_compile_definitions(MeshShadingDemo PRIVATE BUILD_DLL) # -> __declspec(dllexport)
|
||||
add_subdirectory(src/)
|
||||
```
|
||||
|
||||
Key facts:
|
||||
|
||||
- **One build tree, two source trees, two git identities.** `add_subdirectory`
|
||||
compiles the *entire engine* as part of the demo's build. There is no separate
|
||||
engine install step in this flow.
|
||||
- **`BUILD_DLL` is the demo's export switch.** It is a *demo* compile definition
|
||||
(see `src/Define.h`): it flips `MESHSHADINGDEMO_API` to `__declspec(dllexport)`,
|
||||
which is what makes `createInstance`/`destroyInstance` visible to the engine's
|
||||
`GameInterface` `GetProcAddress`/`dlsym`. **If a symbol isn't exported, the
|
||||
engine's loader can't see it** — this is the most common "game won't load" bug.
|
||||
- **vcpkg is the single dependency provider** for *both* repos (the toolchain
|
||||
file is pointed at `external/Seele/external/vcpkg`). The engine's `find_package`
|
||||
calls (Vulkan, EnTT, assimp, slang, etc.) all resolve through it. You do not
|
||||
manage dependencies per-repo.
|
||||
- **Outputs are written to the demo's `bin/`** (`CMAKE_BINARY_DIR` is set to
|
||||
`main/bin` in the demo's CMake). The demo's `.so`/`.dll` and the engine's
|
||||
`Engine` shared lib both land there; the engine's `GameInterface` is given a
|
||||
path to that `.so`.
|
||||
|
||||
### 4.2 Out-of-tree (the engine's install/export path)
|
||||
|
||||
The engine *also* ships a proper install/export so it can be consumed as a
|
||||
**package** (not used by this demo, but it's how a real consumer would link
|
||||
against a prebuilt engine). In `external/Seele/CMakeLists.txt`:
|
||||
|
||||
```cmake
|
||||
install(TARGETS AssetViewer Editor Engine crcpp metal
|
||||
EXPORT EngineTargets
|
||||
FILE_SET HEADERS
|
||||
DESTINATION include/Seele)
|
||||
|
||||
export(EXPORT EngineTargets
|
||||
FILE "${CMAKE_BINARY_DIR}/EngineTargets.cmake"
|
||||
NAMESPACE Seele::)
|
||||
|
||||
configure_package_config_file(cmake/EngineConfig.cmake.in "SeeleConfig.cmake" ...)
|
||||
install(EXPORT EngineTargets FILE EngineTargets.cmake ...)
|
||||
```
|
||||
|
||||
- `FILE_SET HEADERS` (CMake ≥ 3.23) is what installs the public headers under
|
||||
`include/Seele` — this is the "clean install" story.
|
||||
- The `Seele::` namespace prefix means an out-of-tree consumer would
|
||||
`find_package(Seele)` and link `Seele::Engine`.
|
||||
- **This demo does NOT use this path.** It builds the engine in-tree. If you
|
||||
ever need a "link against a prebuilt Seele" flow, *this* is the export to
|
||||
consume — but today, in this repo, `add_subdirectory` is the only path.
|
||||
|
||||
### 4.3 Gotchas (CMake)
|
||||
|
||||
- **Two CMake versions matter.** The demo's CMake is `3.7...3.23` (range) and
|
||||
the engine's `FILE_SET HEADERS` needs `≥3.23`. If you downgrade your CMake
|
||||
below 3.23, the *install* path breaks (the in-tree build may still work).
|
||||
- **Don't `find_package(Seele)` in the demo** — it isn't installed; it's
|
||||
`add_subdirectory`'d. Conversely, don't `add_subdirectory` the demo *into* the
|
||||
engine (wrong direction).
|
||||
- **`BUILD_DLL` is demo-side, not engine-side.** The engine never defines it. If
|
||||
you move the demo's `CMakeLists` or restructure, the `target_compile_definitions
|
||||
(BUILD_DLL)` must travel with the demo library target or exports vanish.
|
||||
- **vcpkg toolchain file is a single global switch.** Changing vcpkg manifests or
|
||||
the toolchain affects *both* repos at once.
|
||||
|
||||
---
|
||||
|
||||
## 5. Practical "where do I look" map
|
||||
|
||||
A quick index by task. For full detail, each link is a per-subsystem deep dive.
|
||||
|
||||
| You want to… | Start at |
|
||||
|---|---|
|
||||
| Compose a scene (actors + components) in the demo | `main/src/MeshShadingDemoGame.cpp` (`setupScene`) + [scene-ecs](subsystems/scene-ecs-components-actors.md) |
|
||||
| Add a new demo per-frame system (camera, etc.) | `main/src/System/FlyCamSystem.{h,cpp}` as the template + §3 above |
|
||||
| Add a new component (engine or demo) | [scene-ecs](subsystems/scene-ecs-components-actors.md) (component model) + `src/Engine/Component/` |
|
||||
| Add a new render pass / change a shader | [render-graph](subsystems/render-graph-and-passes.md) + [graphics-backend](subsystems/graphics-abstract-backend.md) + `src/Engine/Rendering/` |
|
||||
| Add/modify a material or shader graph | [materials](subsystems/materials-shader-graphs.md) + `src/Engine/Materials/` (slang) |
|
||||
| Add a mesh / change meshlet layout | [render-graph](subsystems/render-graph-and-passes.md) (meshlet layout + render pipeline) + `src/Engine/Rendering/` + the `Culling.md` note in the engine root |
|
||||
| Work on ray tracing | [render-graph](subsystems/render-graph-and-passes.md) + [graphics-backend](subsystems/graphics-abstract-backend.md) + the RT sections in [vulkan](subsystems/vulkan-backend.md) / [metal](subsystems/metal-backend.md) |
|
||||
| Add UI (HUD, menus, panels) | [ui](subsystems/ui.md) + `src/Engine/UI/` (flexbox, theming, the font INVARAIT) |
|
||||
| Add physics (rigid bodies, collisions) | [physics](subsystems/physics.md) + `AGENTS.md` § "Physics (Jolt)" |
|
||||
| Touch the window / frame loop / input | [window](subsystems/window.md) + `src/Engine/Window/` |
|
||||
| Fix "game won't load" / cross-repo symbol issues | [platform](subsystems/platform.md) + `src/Engine/Platform/<OS>/GameInterface.cpp` + §2 (the two-symbol contract) |
|
||||
| Load/create/serialize assets | [assets](subsystems/asset-pipeline.md) + [core-utils](subsystems/core-utilities.md) (serialization) + `src/Engine/Asset/` |
|
||||
| Vulkan backend specifics | [vulkan](subsystems/vulkan-backend.md) + `src/Engine/Graphics/Vulkan/` |
|
||||
| Metal backend specifics | [metal](subsystems/metal-backend.md) + `src/Engine/Graphics/Metal/` |
|
||||
| Understand the frame (what runs when) | [systems](subsystems/systems-update-loop.md) + [window](subsystems/window.md) (the render/update protocol) |
|
||||
| The engine↔demo ABI (the two C symbols) | §2 above + [game-interface](subsystems/game-interface.md) + [platform](subsystems/platform.md) |
|
||||
|
||||
### 5.1 The three invariants that save hours
|
||||
|
||||
1. **Engine changes go in the submodule.** Edit `external/Seele/...`, commit
|
||||
*inside the submodule*, then re-record the submodule pointer in the parent.
|
||||
Never edit engine files from the demo repo's perspective.
|
||||
2. **`update` is CPU; `prepare`/`render`/`commitUpdate` are GPU.** Put work in
|
||||
the right phase of the [render/update protocol](subsystems/window.md) or you
|
||||
will get tearing, stale resources, or the render graph's auto-invalidation
|
||||
fighting you.
|
||||
3. **The ABI is exactly two C symbols** (`createInstance`/`destroyInstance`).
|
||||
Everything else crosses the boundary as virtual methods on `Game`. Don't add
|
||||
a third export; route new functionality through `Game`'s virtuals.
|
||||
|
||||
### 5.2 The two "read these first" documents
|
||||
|
||||
- **`AGENTS.md`** (engine root) — the map + the rules (memory model, the
|
||||
`update`/GPU split, the Jolt ground rules, the culling note). **It is the
|
||||
single best first read.** This `docs/` tree is the *per-subsystem* layer that
|
||||
it points you into.
|
||||
- **`src/MeshShadingDemoGame.cpp`** (demo) — the one file that shows the whole
|
||||
"how a game is composed" flow against the real engine. Read it before writing
|
||||
demo code.
|
||||
|
||||
**That is the whole orientation.** Every other detail is a per-subsystem doc,
|
||||
linked from the table above.
|
||||
@@ -0,0 +1,70 @@
|
||||
# Asset Pipeline (AssetManager / Loaders / Storage)
|
||||
|
||||
> Asset loading, saving, the registry, the storage backends, the editor-side importers, and the asset viewer.
|
||||
|
||||
This is a **navigation** doc: it tells you where things live, how data actually flows, and the sharp edges — so you can orient in minutes instead of hours. It complements the repository's [AGENTS.md](../../AGENTS.md) (map + rules) and the [cross-repo guide](../cross-repo.md) (engine ↔ demo contract). Everything below is grounded in the checked-out source at commit `d3ed573`.
|
||||
|
||||
## Key types & where they live
|
||||
|
||||
| Type | Defined in |
|
||||
|------|------------|
|
||||
| `AssetManager` | `git grep` in `src/` |
|
||||
| `Asset` | `src/Engine/Asset/Asset.h` |
|
||||
| `AssetLoader<T>` | `git grep` in `src/` |
|
||||
| `AssetLoaderBase` | `git grep` in `src/` |
|
||||
| `AssetLoaderManager` | `git grep` in `src/` |
|
||||
| `AssetSaveData` | `git grep` in `src/` |
|
||||
| `AssetSaveContext` | `git grep` in `src/` |
|
||||
| `AssetView` | `git grep` in `src/` |
|
||||
| `Asset` | `src/Engine/Asset/Asset.h` |
|
||||
| `MeshAsset` | `src/Engine/Asset/MeshAsset.h` |
|
||||
| `MaterialAsset` | `src/Engine/Asset/MaterialAsset.h` |
|
||||
| `MaterialInstanceAsset` | `src/Engine/Asset/MaterialInstanceAsset.h` |
|
||||
| `SkyboxAsset` | `git grep` in `src/` |
|
||||
| `FluidGridAsset` | `git grep` in `src/` |
|
||||
| `TerrainTileAsset` | `git grep` in `src/` |
|
||||
| `WaterTileAsset` | `git grep` in `src/` |
|
||||
|
||||
Paths above are resolved against the actual source tree (namespace ≈ directory in this codebase). A `(search)` marker means the file contains the name but may also define others — open it and grep. `git grep` is always a fallback. The full per-file map is in **Where to look** below.
|
||||
|
||||
## Data flow / lifecycle
|
||||
|
||||
AssetManager (src/Engine/Asset/AssetManager.h + .cpp, 1.7KB header + 10.3KB impl) is the central asset registry. It maps asset names/paths to Asset objects. API: load(name) (checks cache, if missing calls the appropriate AssetLoader<T> to load from disk), get(name) (cached lookup), unload(name) (removes from cache, calls Asset::unload()), reload(name) (forces re-load from disk). AssetLoaderManager (AssetLoaderManager.h + .cpp, 589B + 472B) is a name->loader map: each AssetLoader<T> registers itself by file extension. AssetLoader<T> (AssetLoader.h, 1.1KB) is a template base with load(context, name) -> T and virtual load implementation. AssetLoaderBase (AssetLoaderBase.h + .cpp, 869B + 3.1KB) is the non-template base that handles the common load/unload lifecycle. Asset (Asset.h, 1.2KB) is the abstract base for all loadable assets: has a name, a path, a reference count, and virtual load/unload. Concrete asset types: MeshAsset (Asset/MeshAsset.h + .cpp, 580B + 5.4KB — loads mesh data from disk into a Gfx::Mesh + VertexData), MaterialAsset (791B + 1.2KB), MaterialInstanceAsset (791B + 1KB), SkyboxAsset (SkyboxAsset.h + .cpp, 813B + 2.3KB — loads cubemap textures), FluidGridAsset (1KB + 1.6KB — loads fluid simulation grid data), TerrainTileAsset (819B + 1.5KB), WaterTileAsset (815B + 1.5KB). AssetSaveData (AssetSaveData.h + .cpp, 798B + 3.1KB) and AssetSaveContext (AssetSaveContext.h + .cpp, 825B + 3.1KB) are the SAVE side: AssetSaveData holds the data to be written, AssetSaveContext tracks the save state. AssetView (AssetView.h + .cpp, 1.2KB + 6.5KB) is a read-only view over an asset (for the editor's asset browser). The AssetLoader<T> template pattern: each concrete loader (e.g. MeshAssetLoader) is registered with the AssetLoaderManager at startup (static initializer or explicit registration call). The loader's load() method reads the file from disk (using std::filesystem or a custom file abstraction) and deserializes it into the asset object. The editor (src/Editor/) has its own set of asset loaders (MaterialLoader, etc.) that are registered in the editor context. The AssetViewer (src/AssetViewer/main.cpp, 7KB) is a standalone CLI tool that uses the AssetManager to browse and inspect assets without running the full engine.
|
||||
|
||||
## Where to look
|
||||
|
||||
| Path | What's there |
|
||||
|------|--------------|
|
||||
| `src/Engine/Asset/AssetManager.h + .cpp` | central registry, 10.3KB impl |
|
||||
| `src/Engine/Asset/Asset.h` | abstract asset base |
|
||||
| `src/Engine/Asset/AssetLoader.h` | template base |
|
||||
| `src/Engine/Asset/AssetLoaderBase.h + .cpp` | non-template lifecycle base |
|
||||
| `src/Engine/Asset/AssetLoaderManager.h + .cpp` | loader registry |
|
||||
| `src/Engine/Asset/AssetSaveData.h + .cpp` | save data |
|
||||
| `src/Engine/Asset/AssetSaveContext.h + .cpp` | save context |
|
||||
| `src/Engine/Asset/AssetView.h + .cpp` | read-only asset view, 6.5KB impl |
|
||||
| `src/Engine/Asset/MeshAsset.h + .cpp` | mesh asset, 5.4KB impl |
|
||||
| `src/Engine/Asset/MaterialAsset.h + .cpp` | material asset |
|
||||
| `src/Engine/Asset/SkyboxAsset.h + .cpp` | skybox/cubemap asset, 2.3KB impl |
|
||||
| `src/Engine/Asset/FluidGridAsset.h + .cpp` | fluid grid asset |
|
||||
| `src/Engine/Asset/TerrainTileAsset.h + .cpp` | terrain tile asset |
|
||||
| `src/Engine/Asset/WaterTileAsset.h + .cpp` | water tile asset |
|
||||
| `src/Editor/Asset/MaterialLoader.h + .cpp` | editor material loader, 9.5KB impl |
|
||||
| `src/AssetViewer/main.cpp` | standalone asset browser |
|
||||
|
||||
## Gotchas & sharp edges
|
||||
|
||||
- AssetLoader<T> uses a template + registration pattern. Each concrete loader MUST be explicitly registered with the AssetLoaderManager (or via a static initializer). If you add a new asset type but forget to register its loader, AssetManager::load() will fail with 'no loader for extension' at runtime.
|
||||
- The asset file format is NOT documented in a schema file. Each asset type has its own serialization code in its .cpp file (e.g. MeshAsset.cpp uses Seele::Serialization to read/write). If you need to author assets by hand, you must reverse-engineer the format from the load code.
|
||||
- AssetManager::load() is NOT thread-safe — it uses a single cache map with no locking. All asset loading must happen on the main thread (or be guarded by external synchronization). The editor loads assets on the main thread; the game DLL should do the same.
|
||||
- AssetView (6.5KB impl) is the editor's read-only interface over assets. It is used by the AssetViewer tool and the editor's asset browser. It does NOT mutate the asset — all modifications go through the asset's own API (or the editor's specific loader).
|
||||
- The AssetSaveData/AssetSaveContext pair is the save path. AssetSaveContext tracks the save state (which assets are dirty, which are being saved). The actual file writing is done by each asset's save() method (called through the save context). If an asset's save() throws, the context marks the save as failed and rolls back (check AssetSaveContext.cpp for the rollback logic).
|
||||
- MeshAsset loading (5.4KB impl) reads mesh data from disk and constructs a Gfx::Mesh + VertexData. The VertexData then self-registers into the global VertexData::getList(). If you load a MeshAsset multiple times, you get MULTIPLE VertexData registrations (each load creates a new VertexData). The AssetManager cache prevents re-loading the same asset, but if you unload and reload, the old VertexData remains in the global list (check VertexData.cpp for whether it unregisters on destruction).
|
||||
- The AssetViewer (main.cpp, 7KB) is a standalone executable that links against the engine's AssetManager. It does NOT require a window or GPU — it can run headless. It is useful for validating asset files without running the full engine.
|
||||
- The editor's MaterialLoader (9.5KB impl) is a CUSTOM loader that does NOT go through the standard AssetLoader<T> template — it has its own loading logic. This is because material assets have a complex node graph (ShaderExpression) that requires special deserialization. If you modify the material asset format, you must update BOTH the engine's MaterialAsset.cpp AND the editor's MaterialLoader.cpp.
|
||||
- Asset files are stored on disk in a project-specific directory (configured by the game's GameInterface or the editor's project settings). The AssetManager does NOT hardcode a path — the base path is provided at initialization. If the path is wrong, all loads will fail silently (return nullptr or throw).
|
||||
- There is no asset hot-reload in the engine. To reload an asset, you must call AssetManager::unload() + AssetManager::load(). The editor may have a file-watcher that triggers this automatically (check the editor's source), but the engine itself has no file-watching capability.
|
||||
|
||||
---
|
||||
|
||||
*Generated from a full read of the checked-out source at commit `d3ed573`. If a path has moved, `git grep` for the type name — the engine is small enough to find anything in seconds.*
|
||||
@@ -0,0 +1,88 @@
|
||||
# Core Utilities (Math, Containers, Log, Time, Memory, Reflection, Serialization)
|
||||
|
||||
> The engine's foundation: math, containers, logging, time, memory, the reflection/serialization system, and dynamic loading.
|
||||
|
||||
This is a **navigation** doc: it tells you where things live, how data actually flows, and the sharp edges — so you can orient in minutes instead of hours. It complements the repository's [AGENTS.md](../../AGENTS.md) (map + rules) and the [cross-repo guide](../cross-repo.md) (engine ↔ demo contract). Everything below is grounded in the checked-out source at commit `d3ed573`.
|
||||
|
||||
## Key types & where they live
|
||||
|
||||
| Type | Defined in |
|
||||
|------|------------|
|
||||
| `Log` | `git grep` in `src/` |
|
||||
| `Log/Info` | `git grep` in `src/` |
|
||||
| `Log/Warning` | `git grep` in `src/` |
|
||||
| `Log/Error` | `git grep` in `src/` |
|
||||
| `Log/Debug` | `git grep` in `src/` |
|
||||
| `Seele::Math (Vec2/3/4, Mat3/4, Quat, Transform, BBox, Ray, Plane)` | `git grep` in `src/` |
|
||||
| `Array<T>` | `git grep` in `src/` |
|
||||
| `Stack<T>` | `git grep` in `src/` |
|
||||
| `HashMap` | `git grep` in `src/` |
|
||||
| `HashSet` | `git grep` in `src/` |
|
||||
| `HashMapStringKey` | `git grep` in `src/` |
|
||||
| `HashMapPtrKey` | `git grep` in `src/` |
|
||||
| `StringMap` | `git grep` in `src/` |
|
||||
| `StringHashMap` | `git grep` in `src/` |
|
||||
| `StringHashMapPtrKey` | `git grep` in `src/` |
|
||||
| `PtrHashMap` | `git grep` in `src/` |
|
||||
| `PtrMap` | `git grep` in `src/` |
|
||||
| `StringToPtrHashMap` | `git grep` in `src/` |
|
||||
| `StringToPtrMap` | `git grep` in `src/` |
|
||||
| `Optional<T>` | `git grep` in `src/` |
|
||||
| `Result<T, E>` | `git grep` in `src/` |
|
||||
| `String/ConstString` | `git grep` in `src/` |
|
||||
| `GameTime` | `git grep` in `src/` |
|
||||
| `Time` | `git grep` in `src/` |
|
||||
| `Memory (malloc/free wrappers)` | `git grep` in `src/` |
|
||||
| `Platform (OS abstraction)` | `git grep` in `src/` |
|
||||
| `Reflection (struct member registry)` | `git grep` in `src/` |
|
||||
| `Serialization (Archive/ArchiveBuffer/ArchiveJson)` | `git grep` in `src/` |
|
||||
| `JobSystem (thread pool)` | `git grep` in `src/` |
|
||||
|
||||
Paths above are resolved against the actual source tree (namespace ≈ directory in this codebase). A `(search)` marker means the file contains the name but may also define others — open it and grep. `git grep` is always a fallback. The full per-file map is in **Where to look** below.
|
||||
|
||||
## Data flow / lifecycle
|
||||
|
||||
Log (src/Engine/Core/Log.h + Log.cpp, 1.8KB + 1.1KB) provides Log::info/warning/error/debug static methods that format a message with source location (file:line via __FILE__/__LINE__) and write to stdout + a log file (Log.cpp opens a log file in the working directory). There are also macros (LOG_INFO, LOG_WARNING, etc.) that wrap these. Math (src/Engine/Core/Math/) is a SIMD-friendly math library: Vec2/Vec3/Vec4 (float/double/int variants), Mat3/Mat4 (float/double), Quat, Transform (position/rotation/scale), BBox (axis-aligned bounding box with intersection tests), Ray (origin+direction, BBox intersection), Plane (normal+distance, point classification), Sphere. All are header-only inline functions with SIMD intrinsics (SSE/AVX where available). The math library is used pervasively: Transform (Component/Transform.h) uses Math::Mat4 for the world matrix, BBox is used for frustum culling in RenderPass::computePlane, Ray is used for ray queries. Containers (src/Engine/Containers/) wrap std:: containers with engine conventions: Array<T> (dynamic array with growth strategy, 5.6KB), Stack<T> (5.3KB), HashMap (open-addressing, 8.6KB), HashSet (10.7KB), HashMapStringKey/HashMapPtrKey (key-type specializations), StringMap/StringHashMap/StringHashMapPtrKey (string-keyed), PtrHashMap/PtrMap (pointer-keyed), StringToPtrHashMap/StringToPtrMap (string->pointer maps), Optional<T> (2.4KB, std::optional-like), Result<T,E> (2.7KB, tagged union for success/failure). The hash functions in HashMap/HashSet use a FNV-1a or similar non-cryptographic hash. String (src/Engine/Core/String/String.h + .cpp, 6.9KB + 16.9KB) is a custom string class (NOT std::string) with UTF-8 storage, format(), split(), find(), replace(), and interning (ConstString is an interned string reference — used for type names and asset names). ConstString (ConstString.h, 770B) is a non-owning reference to an interned string — it is implicitly convertible from string literals and std::string. GameTime (GameTime.h + .cpp, 812B + 945B) and Time (Time.h + .cpp, 730B + 1.2KB) provide high-resolution timing (std::chrono::high_resolution_clock wrappers). GameTime is the frame timer used by GameView. Memory (Memory.h + .cpp, 1.2KB + 2.8KB) wraps malloc/free/new/delete with allocation tracking (total allocated, peak, allocation count) and optional leak detection. Platform (Platform.h + .cpp, 1.4KB + 1.7KB) is the OS abstraction: file I/O (read/write/delete/mkdir), path manipulation (join, normalize, getExtension), command-line argument parsing, environment variable access, process ID. Reflection (Reflection.h + .cpp, 2.8KB + 3.4KB) provides a struct member registry — each serializable struct registers its members (name, offset, type) at compile time (via a macro or static initializer). This is used by the Serialization system to generically read/write struct fields by name. Serialization (src/Engine/Serialization/Serialization.h + .cpp, 5.1KB + 23.3KB) provides the Archive abstract class (read/write primitives: int/float/string/struct-by-reflection) + ArchiveBuffer (binary buffer archive, 1.3KB header + 13.6KB impl) + ArchiveJson (JSON archive, 2.2KB header + 11.6KB impl). ArchiveJson uses a JSON parser (likely nlohmann/json or a custom one — check the includes). The Archive class uses the Reflection registry to iterate struct members and serialize/deserialize them generically. JobSystem (JobSystem.h + .cpp, 801B + 963B) is a minimal thread pool for parallel work. It is used by the Executor (System/Executor.h) and potentially by the asset loader for parallel loading.
|
||||
|
||||
## Where to look
|
||||
|
||||
| Path | What's there |
|
||||
|------|--------------|
|
||||
| `src/Engine/Core/Log.h + .cpp` | logging |
|
||||
| `src/Engine/Core/Math/ (all math types: Vec.h, Mat.h, Quat.h, Transform.h, BBox.h, Ray.h, Plane.h, Sphere.h, etc.)` | |
|
||||
| `src/Engine/Containers/Array.h + .cpp` | |
|
||||
| `src/Engine/Containers/HashMap.h + .cpp` | open-addressing hash map |
|
||||
| `src/Engine/Containers/HashSet.h + .cpp` | |
|
||||
| `src/Engine/Containers/Optional.h + .cpp` | |
|
||||
| `src/Engine/Containers/Result.h + .cpp` | |
|
||||
| `src/Engine/Core/String/String.h + .cpp` | custom string, 16.9KB impl |
|
||||
| `src/Engine/Core/String/ConstString.h` | interned string reference |
|
||||
| `src/Engine/Core/GameTime.h + .cpp` | frame timer |
|
||||
| `src/Engine/Core/Time.h + .cpp` | high-res clock wrapper |
|
||||
| `src/Engine/Core/Memory.h + .cpp` | allocation tracking |
|
||||
| `src/Engine/Core/Platform.h + .cpp` | OS abstraction: file I/O, paths, args |
|
||||
| `src/Engine/Core/Reflection.h + .cpp` | struct member registry |
|
||||
| `src/Engine/Serialization/Serialization.h + .cpp` | Archive base + reflection-driven serialization, 23.3KB impl |
|
||||
| `src/Engine/Serialization/ArchiveBuffer.h + .cpp` | binary archive, 13.6KB impl |
|
||||
| `src/Engine/Serialization/ArchiveJson.h + .cpp` | JSON archive, 11.6KB impl |
|
||||
| `src/Engine/Job/JobSystem.h + .cpp` | thread pool |
|
||||
|
||||
## Gotchas & sharp edges
|
||||
|
||||
- The custom String class is NOT std::string — it has a different API (no std::string interop). If you pass a std::string to a function expecting Seele::String, you must construct a String from it (String has a std::string constructor). The reverse (String -> std::string) is via String::c_str() + String::length().
|
||||
- ConstString is an INTERNED string reference — it is cheap to copy (pointer + hash) but the underlying string must outlive the ConstString. ConstStrings are used for type names in the Reflection system and for asset names in the AssetManager. Do NOT create a ConstString from a temporary string literal that will be destroyed.
|
||||
- The Reflection system requires explicit member registration — each serializable struct must call DEFINE_REFLECTION(TypeName) or equivalent macro at file scope. If you add a new field to a struct but forget to add it to the reflection registration, the field will be SILENTLY SKIPPED during serialization (no error, no warning). This is the most common source of data corruption bugs in this engine.
|
||||
- ArchiveJson (JSON serialization) and ArchiveBuffer (binary serialization) are interchangeable — any struct can be serialized to either format. The Archive base class dispatches to the concrete archive at runtime. If you mix the two (read a binary file with ArchiveJson), you will get garbage data with no error (check the type tags in the serialization format).
|
||||
- The Math library is HEADER-ONLY — all functions are inline. There is no separate .cpp file for most math types. If you get linker errors for math functions, check that you included the correct header (e.g. Math/Vec3.h for Vec3, not Math.h).
|
||||
- The Array<T> container has a GROWTH STRATEGY — it does not use std::vector's doubling strategy. The growth factor is configurable (check Array.h). If you resize an Array to a very large size, the growth strategy may cause multiple reallocations. For predictable performance, reserve() in advance.
|
||||
- The HashMap/HashSet use OPEN-ADDRESSING with a specific probe sequence (linear or quadratic — check the header). The load factor is capped (typically 0.7) — if you exceed the cap, the map rehashes. Rehashing is O(n) and can cause frame hitches if it happens during a frame update. Pre-size the map if you know the expected size.
|
||||
- Platform.h provides file I/O — it is the ONLY way to do file I/O in the engine. Do NOT use std::ifstream/std::ofstream directly (the Platform layer may use a different I/O strategy, e.g. memory-mapped files on some platforms). The AssetManager uses Platform for all file access.
|
||||
- JobSystem (thread pool) is minimal (963B impl) — it has a fixed thread count (from GraphicsInitializer or a default) and a simple task queue. It is NOT a work-stealing scheduler. If you submit more work than the pool can handle, the excess is queued and processed in order. There is no priority, no cancellation, no async result (no std::future equivalent).
|
||||
- The Memory tracking (Memory.h) is ON by default in debug builds — it tracks every allocation (total, peak, count) and can report leaks at shutdown. In release builds, the tracking is compiled out (check the #ifdef in Memory.h). If you see performance issues, the memory tracking overhead in debug builds may be significant (each allocation has a tracking call).
|
||||
- GameTime (frame timer) uses std::chrono::high_resolution_clock. On some platforms (Windows), high_resolution_clock has a 1ms granularity by default — the engine may use QueryPerformanceCounter directly for better resolution (check GameTime.cpp). If you see frame timing jitter, the clock resolution may be the cause.
|
||||
- The Log system writes to BOTH stdout and a log file (Log.cpp opens the log file in the current working directory at first log call). The log file is NOT rotated — it grows without bound. For long-running applications, you may need to implement log rotation externally (or modify Log.cpp to add rotation).
|
||||
- The String class has a format() method (printf-style) — use it for log messages. Do NOT use std::format or snprintf directly (the String::format is the engine's convention and may have platform-specific behavior).
|
||||
|
||||
---
|
||||
|
||||
*Generated from a full read of the checked-out source at commit `d3ed573`. If a path has moved, `git grep` for the type name — the engine is small enough to find anything in seconds.*
|
||||
@@ -0,0 +1,46 @@
|
||||
# Game Interface & Frame Loop (GameView / GameInterface)
|
||||
|
||||
> How the engine hosts a game DLL: the GameInterface contract, the GameView frame loop, window/graphics setup, and the reload path.
|
||||
|
||||
This is a **navigation** doc: it tells you where things live, how data actually flows, and the sharp edges — so you can orient in minutes instead of hours. It complements the repository's [AGENTS.md](../../AGENTS.md) (map + rules) and the [cross-repo guide](../cross-repo.md) (engine ↔ demo contract). Everything below is grounded in the checked-out source at commit `d3ed573`.
|
||||
|
||||
## Key types & where they live
|
||||
|
||||
| Type | Defined in |
|
||||
|------|------------|
|
||||
| `GameInterface` | `src/Engine/Platform/Linux/GameInterface.h` |
|
||||
| `GameView` | `src/Engine/Window/GameView.h` |
|
||||
| `Game` | `src/Engine/Game.h` |
|
||||
| `GameInterface (abstract)` | `git grep` in `src/` |
|
||||
| `Game (abstract game base)` | `git grep` in `src/` |
|
||||
|
||||
Paths above are resolved against the actual source tree (namespace ≈ directory in this codebase). A `(search)` marker means the file contains the name but may also define others — open it and grep. `git grep` is always a fallback. The full per-file map is in **Where to look** below.
|
||||
|
||||
## Data flow / lifecycle
|
||||
|
||||
GameInterface (src/Engine/Interface/GameInterface.h + .cpp, 1.3KB header + 1.2KB impl) is the abstract contract between the engine and the game. It defines the virtual methods that a game DLL must implement: setupScene(PScene, PSystemGraph) (called once when the game is loaded — the game populates the scene with entities/components and may add custom systems to the system graph), updateScene() (called every frame before the built-in systems run — the game can do custom per-frame work), and potentially other hooks (check the full header). Game (src/Engine/Interface/Game.h, 634B) is the abstract game base class (DEFINE_REF(Game) -> PGame) — it is the type that the game DLL exports. GameView (src/Engine/Window/GameView.h + .cpp, 1.7KB header + 5.4KB impl) is the ENGINE-SIDE host that: (1) creates the Gfx::Graphics backend (Vulkan::Graphics or Metal::Graphics — the selection is done by the embedding app, NOT by GameView; GameView receives a PGraphics), (2) creates a Scene, (3) loads the game DLL (via a dynamic library loader — check GameView.cpp for the dlopen/LoadLibrary call), (4) calls game->setupScene(scene, systemGraph) to let the game populate the scene, (5) runs the frame loop: GameView::update() (compute deltaTime, reset VertexData, run systemGraph->run(dt), scene->update(dt), re-create VertexData descriptors, lightEnv->commit()) and GameView::render() (find main camera, call renderGraph.render(cam, transform), call rayTracingGraph.render(cam, transform) if RT enabled). The main entry point is src/Main.cpp (9.4KB) — it parses command-line arguments (window size, graphics backend, project path), creates the Graphics backend, creates a GameView, creates the GameInterface (loads the game DLL), and enters the main loop. The game DLL is a separate compilation unit that links against the engine's exported symbols (the engine exports a C or C++ ABI for the game to link against). The game DLL exports a factory function (check the Interface/ headers for the exact export name) that returns a PGame.
|
||||
|
||||
## Where to look
|
||||
|
||||
| Path | What's there |
|
||||
|------|--------------|
|
||||
| `src/Engine/Interface/GameInterface.h + .cpp` | game<->engine contract |
|
||||
| `src/Engine/Interface/Game.h` | abstract game base |
|
||||
| `src/Engine/Window/GameView.h + .cpp` | engine-side host: frame loop, game loading, render wiring |
|
||||
| `src/Main.cpp` | main entry point, 9.4KB — backend selection, GameView creation, main loop |
|
||||
|
||||
## Gotchas & sharp edges
|
||||
|
||||
- The graphics backend is NOT selected by GameView or the game DLL — it is selected by the EMBEDDING APP (Main.cpp or a custom launcher). Main.cpp parses a command-line argument to choose between Vulkan and Metal. If you want to change the backend, you modify Main.cpp (or write your own launcher that constructs the appropriate backend and passes it to GameView).
|
||||
- The game DLL is loaded at RUNTIME via dlopen (Linux) or LoadLibrary (Windows). The DLL path is either a command-line argument or a hardcoded path (check Main.cpp / GameView.cpp). If the DLL is missing, the engine will fail at startup with a clear error message. If the DLL exports the wrong symbol name, the dlsym/GetProcAddress will fail — check the exact export name in the Interface/ headers.
|
||||
- GameView::render() finds the main camera by iterating ALL Camera+Transform entities and checking the mainCamera boolean. If the game forgets to set mainCamera=true on its camera, the render will use a default-constructed (identity) camera and you will see a broken view with no error message. This is a common game-side bug.
|
||||
- The system graph is REBUILT on every reloadGame() call — the game's setupScene is called again. If the game's setupScene is not idempotent (e.g. it adds duplicate entities), the scene will accumulate duplicates on reload. The game must clean up its entities before re-populating (or the engine must clear the scene before calling setupScene — check GameView.cpp reloadGame() for whether it clears the scene first).
|
||||
- GameView::update() calls VertexData::getList() to iterate ALL registered VertexData instances and reset their mesh data. This is a GLOBAL side-channel — if you create a VertexData outside the ECS (e.g. in a system that doesn't own it), it will still be in the global list and will be reset every frame. If you need per-vertex-data update logic, hook into the VertexData's own update callback (check VertexData.h for a callback mechanism).
|
||||
- The main loop in Main.cpp is a standard while(running) { update(); render(); } loop. There is no vsync control in the engine — the vsync is controlled by the window system (Vulkan::Window or Metal::Window). If you see frame rate issues, check the swapchain configuration in the backend's Window implementation.
|
||||
- GameInterface is the CONTRACT, not the implementation. The engine does NOT contain a default game — it is a pure interface. The game DLL provides all game logic. If you are building a new game, you must implement the GameInterface contract in a separate DLL.
|
||||
- The scene is created by GameView (not by the game). The game receives the scene as a parameter to setupScene() and populates it. The game CANNOT create a new scene — it must use the one provided by the engine. If the game tries to create its own Scene, it will have a different entt::registry and the engine's render pipeline will not see the game's entities.
|
||||
- The frame timing (updateTime) is computed in GameView::update() using std::chrono. It is the ACTUAL wall-clock delta between frames, not a fixed timestep. If the frame takes longer than expected (e.g. due to Slang compilation), updateTime will be large and the simulation will take a large step. There is no clamping of deltaTime in the engine — the game is responsible for clamping if it wants stable simulation (check the game's system implementations).
|
||||
|
||||
---
|
||||
|
||||
*Generated from a full read of the checked-out source at commit `d3ed573`. If a path has moved, `git grep` for the type name — the engine is small enough to find anything in seconds.*
|
||||
@@ -0,0 +1,57 @@
|
||||
# Graphics Abstract Backend (Gfx::Graphics)
|
||||
|
||||
> The abstract GPU backend interface that all backends implement, and the factory methods every GPU resource is created through.
|
||||
|
||||
This is a **navigation** doc: it tells you where things live, how data actually flows, and the sharp edges — so you can orient in minutes instead of hours. It complements the repository's [AGENTS.md](../../AGENTS.md) (map + rules) and the [cross-repo guide](../cross-repo.md) (engine ↔ demo contract). Everything below is grounded in the checked-out source at commit `d3ed573`.
|
||||
|
||||
## Key types & where they live
|
||||
|
||||
| Type | Defined in |
|
||||
|------|------------|
|
||||
| `Gfx::Graphics` | `src/Engine/Graphics/Graphics.h` |
|
||||
| `Gfx::Viewport` | `src/Editor/Window/ViewportControl.h` (search) |
|
||||
| `Gfx::RenderPass` | `src/Engine/Graphics/Metal/RenderPass.h` |
|
||||
| `Gfx::ShaderCompiler` | `git grep` in `src/` |
|
||||
| `Gfx::GraphicsPipeline` | `git grep` in `src/` |
|
||||
| `Gfx::ComputePipeline` | `git grep` in `src/` |
|
||||
| `Gfx::RayTracingPipeline` | `git grep` in `src/` |
|
||||
| `Gfx::Texture2D/3D/Cube` | `git grep` in `src/` |
|
||||
| `Gfx::DescriptorLayout` | `git grep` in `src/` |
|
||||
| `Gfx::PipelineLayout` | `git grep` in `src/` |
|
||||
| `Gfx::VertexInput` | `git grep` in `src/` |
|
||||
| `Gfx::OcclusionQuery` | `git grep` in `src/` |
|
||||
| `Gfx::PipelineStatisticsQuery` | `git grep` in `src/` |
|
||||
| `Gfx::TimestampQuery` | `git grep` in `src/` |
|
||||
| `Gfx::BottomLevelAS` | `git grep` in `src/` |
|
||||
| `Gfx::TopLevelAS` | `git grep` in `src/` |
|
||||
|
||||
Paths above are resolved against the actual source tree (namespace ≈ directory in this codebase). A `(search)` marker means the file contains the name but may also define others — open it and grep. `git grep` is always a fallback. The full per-file map is in **Where to look** below.
|
||||
|
||||
## Data flow / lifecycle
|
||||
|
||||
Gfx::Graphics (src/Engine/Graphics/Graphics.h, lines 45-132) is the abstract backend. Backends: Vulkan::Graphics (src/Engine/Graphics/Vulkan/Graphics.h + Graphics.cpp, 51KB) and Metal::Graphics (src/Engine/Graphics/Metal/Graphics.h + Graphics.mm). All resources are created through virtual factory methods: createWindow, createViewport, createRenderPass(RenderTargetLayout, dependencies, area, name, viewMasks, correlationMasks), beginRenderPass/endRenderPass, waitDeviceIdle, executeCommands(ORenderCommand/OComputeCommand), createTexture2D/2DArray/3D/Cube, createUniformBuffer, createShaderBuffer, createVertexBuffer, createIndexBuffer, createRenderCommand, createComputeCommand, beginShaderCompilation + createVertexShader/FragmentShader/ComputeShader/MeshShader/TaskShader, createGraphicsPipeline(LegacyPipelineCreateInfo or MeshPipelineCreateInfo), createRayTracingPipeline(RayTracingPipelineCreateInfo), createComputePipeline, createSampler, createDescriptorLayout, createPipelineLayout, createVertexInput, createOcclusionQuery, createPipelineStatisticsQuery, createTimestampQuery, beginDebugRegion/endDebugRegion, resolveTexture, copyTexture, copyBuffer, createBottomLevelAccelerationStructure/createTopLevelAccelerationStructure/buildBottomLevelAccelerationStructures, createRayGenShader/AnyHitShader/ClosestHitShader/MissShader/IntersectionShader/CallableShader. Capability gates: supportMeshShading() (meshShadingEnabled flag) and supportRayTracing() (rayTracingEnabled flag). Protected members: QueueFamilyMapping queueMapping, OShaderCompiler shaderCompiler. DEFINE_REF(Graphics) generates PGraphics/UPGraphics/OGraphics typedefs from MinimalEngine.h macros (RefPtr/UniquePtr/OwningPtr). The ShaderCompiler class lives in Shader.h line 178 (not a separate file).
|
||||
|
||||
## Where to look
|
||||
|
||||
| Path | What's there |
|
||||
|------|--------------|
|
||||
| `src/Engine/Graphics/Graphics.h` | abstract interface, 133 lines |
|
||||
| `src/Engine/Graphics/Vulkan/Graphics.h + Graphics.cpp` | Vulkan impl, ~52KB |
|
||||
| `src/Engine/Graphics/Metal/Graphics.h + Graphics.mm` | Metal impl |
|
||||
| `src/Engine/Graphics/Shader.h` | ShaderCompiler at line 178; Vertex/Fragment/Compute/Task/MeshShader classes above |
|
||||
| `src/Engine/Graphics/Pipeline.h` | pipeline create structs: LegacyPipelineCreateInfo, MeshPipelineCreateInfo, ComputePipelineCreateInfo |
|
||||
| `src/Engine/Graphics/Initializer.h` | GraphicsInitializer, WindowCreateInfo, ViewportCreateInfo, all resource create-info structs |
|
||||
| `src/Engine/MinimalEngine.h` | RefPtr/UniquePtr/OwningPtr, DEFINE_REF/DECLARE_REF/DECLARE_NAME_REF macros |
|
||||
|
||||
## Gotchas & sharp edges
|
||||
|
||||
- ShaderCompiler is declared in Graphics/Shader.h (line 178), NOT in a separate ShaderCompiler.h file.
|
||||
- createGraphics() factory does NOT exist in the codebase — backends are constructed directly (Vulkan::Graphics / Metal::Graphics) by the embedding app.
|
||||
- Graphics.h has #define ENABLE_VALIDATION at line 7 — Vulkan validation layers are active in every build.
|
||||
- OwningPtr (O-prefix) is the owning handle; RefPtr (P-prefix) is a non-owning shared reference. You cannot assign an OwningPtr to a RefPtr (deleted operator=).
|
||||
- Both LegacyPipelineCreateInfo and MeshPipelineCreateInfo exist — mesh shading uses the second. MeshPipelineCreateInfo is only usable when supportMeshShading() is true.
|
||||
- QueueFamilyMapping is a protected member set by the backend; the abstract interface exposes it read-only via getFamilyMapping().
|
||||
|
||||
---
|
||||
|
||||
*Generated from a full read of the checked-out source at commit `d3ed573`. If a path has moved, `git grep` for the type name — the engine is small enough to find anything in seconds.*
|
||||
@@ -0,0 +1,87 @@
|
||||
# GPU Resources (Buffers, Textures, Shaders, Pipelines, Descriptors)
|
||||
|
||||
> GPU resource types, VertexData self-registration, the descriptor/parameter layer, and the shader compilation flow.
|
||||
|
||||
This is a **navigation** doc: it tells you where things live, how data actually flows, and the sharp edges — so you can orient in minutes instead of hours. It complements the repository's [AGENTS.md](../../AGENTS.md) (map + rules) and the [cross-repo guide](../cross-repo.md) (engine ↔ demo contract). Everything below is grounded in the checked-out source at commit `d3ed573`.
|
||||
|
||||
## Key types & where they live
|
||||
|
||||
| Type | Defined in |
|
||||
|------|------------|
|
||||
| `Gfx::Buffer (abstract)` | `git grep` in `src/` |
|
||||
| `Gfx::ShaderBuffer` | `git grep` in `src/` |
|
||||
| `Gfx::UniformBuffer` | `git grep` in `src/` |
|
||||
| `Gfx::VertexBuffer` | `git grep` in `src/` |
|
||||
| `Gfx::IndexBuffer` | `git grep` in `src/` |
|
||||
| `Gfx::Texture` | `src/Engine/Graphics/Metal/Texture.h` |
|
||||
| `Gfx::Texture2D` | `git grep` in `src/` |
|
||||
| `Gfx::Texture2DArray` | `git grep` in `src/` |
|
||||
| `Gfx::Texture3D` | `git grep` in `src/` |
|
||||
| `Gfx::TextureCube` | `git grep` in `src/` |
|
||||
| `Gfx::TextureView` | `git grep` in `src/` |
|
||||
| `Gfx::Sampler` | `git grep` in `src/` |
|
||||
| `Gfx::Shader (abstract)` | `git grep` in `src/` |
|
||||
| `Gfx::VertexShader` | `git grep` in `src/` |
|
||||
| `Gfx::FragmentShader` | `git grep` in `src/` |
|
||||
| `Gfx::ComputeShader` | `git grep` in `src/` |
|
||||
| `Gfx::TaskShader` | `git grep` in `src/` |
|
||||
| `Gfx::MeshShader` | `git grep` in `src/` |
|
||||
| `Gfx::ShaderCompiler` | `git grep` in `src/` |
|
||||
| `Gfx::DescriptorLayout` | `git grep` in `src/` |
|
||||
| `Gfx::DescriptorSet` | `git grep` in `src/` |
|
||||
| `Gfx::PipelineLayout` | `git grep` in `src/` |
|
||||
| `Gfx::GraphicsPipeline` | `git grep` in `src/` |
|
||||
| `Gfx::ComputePipeline` | `git grep` in `src/` |
|
||||
| `Gfx::RayTracingPipeline` | `git grep` in `src/` |
|
||||
| `Gfx::RenderTarget` | `src/Engine/Graphics/RenderTarget.h` |
|
||||
| `Gfx::RenderTargetAttachment` | `git grep` in `src/` |
|
||||
| `Gfx::VertexInput` | `git grep` in `src/` |
|
||||
| `Gfx::RenderCommand` | `git grep` in `src/` |
|
||||
| `Gfx::ComputeCommand` | `git grep` in `src/` |
|
||||
| `Gfx::Meshlet` | `src/Engine/Graphics/Meshlet.h` |
|
||||
| `Gfx::Mesh` | `src/Engine/Component/Mesh.h` |
|
||||
| `VertexData` | `src/Engine/Graphics/VertexData.h` |
|
||||
| `StaticMeshVertexData` | `src/Engine/Graphics/StaticMeshVertexData.h` |
|
||||
|
||||
Paths above are resolved against the actual source tree (namespace ≈ directory in this codebase). A `(search)` marker means the file contains the name but may also define others — open it and grep. `git grep` is always a fallback. The full per-file map is in **Where to look** below.
|
||||
|
||||
## Data flow / lifecycle
|
||||
|
||||
All GPU resources are created through Gfx::Graphics factory methods (see Gfx Abstract Backend). Resource classes are thin wrappers around backend handles: Buffer.h (abstract base, 3.7KB) -> ShaderBuffer/UniformBuffer/VertexBuffer/IndexBuffer (each with a createInfo struct in Initializer.h). Texture.h (7KB) defines Texture base + Texture2D/2DArray/3D/Cube + TextureView + Sampler. Each has a TextureCreateInfo / SamplerCreateInfo in Initializer.h. Shader.h (5.9KB) defines Shader base (with ShaderStage enum) + VertexShader/FragmentShader/ComputeShader/TaskShader/MeshShader + ShaderCompiler (line 178). Shader compilation is two-phase: Graphics::beginShaderCompilation(ShaderCompilationInfo) then createXxxShader(ShaderCreateInfo) — the ShaderCompiler (held as OShaderCompiler member of Graphics) does the actual Slang->SPIR-V/Metal translation (see slang-compile.h/.cpp, 9KB). Descriptor.h (4.4KB) defines DescriptorLayout (with DescriptorBinding struct: binding index, stage flags, resource type), DescriptorSet (binds resources to a layout), PipelineLayout (composes descriptor layouts + push constant ranges). RenderTarget.h (4.7KB) defines RenderTarget (wraps Gfx::ORenderPass + framebuffers), RenderTargetAttachment (texture + load/store op + initial layout + final layout), SubPassDependency. Pipeline.h (904B) defines LegacyPipelineCreateInfo (vertex/fragment shader stages, vertex input state, render pass, multisample state, depth/stencil state, blend state, rasterization state) and MeshPipelineCreateInfo (task/mesh/fragment shaders, vertex output state, same fixed-function state). ComputePipelineCreateInfo and RayTracingPipelineCreateInfo are also here. Meshlet.h (442B) + Meshlet.cpp (6.2KB) define the meshlet data structure (submesh with bounding sphere, transform, index range) used by the GPU culling pipeline. Mesh.h (895B) + Mesh.cpp (1.5KB) define the GPU mesh asset (vertex buffer + index buffer + meshlets). VertexData (6.5KB header + 27.5KB impl) is the CPU-side mesh data object that owns the source vertex/index arrays, builds meshlets (Meshlet.cpp), and uploads to GPU (createDescriptors()). StaticMeshVertexData (2.3KB header + 7.9KB impl) is the concrete implementation for static meshes. VertexData has a STATIC global registry (getList()) that GameView::update() iterates. Slang shaders are compiled by slang-compile.cpp (9KB) which invokes the Slang compiler frontend and produces SPIR-V (Vulkan) or Metal SL (Metal). The ShaderCompiler class in Shader.h orchestrates this.
|
||||
|
||||
## Where to look
|
||||
|
||||
| Path | What's there |
|
||||
|------|--------------|
|
||||
| `src/Engine/Graphics/Buffer.h + .cpp` | abstract buffer base + create-info structs |
|
||||
| `src/Engine/Graphics/Texture.h + .cpp` | texture hierarchy, 7KB header |
|
||||
| `src/Engine/Graphics/Shader.h` | Shader base + all shader types + ShaderCompiler at line 178 |
|
||||
| `src/Engine/Graphics/Shader.cpp` | 7.3KB — shader compilation orchestration |
|
||||
| `src/Engine/Graphics/slang-compile.h + .cpp` | Slang frontend invocation, 9KB |
|
||||
| `src/Engine/Graphics/Descriptor.h + .cpp` | descriptor layout/set/pipeline layout |
|
||||
| `src/Engine/Graphics/Pipeline.h + .cpp` | pipeline create-info structs |
|
||||
| `src/Engine/Graphics/RenderTarget.h + .cpp` | render target + attachments + subpass dependencies |
|
||||
| `src/Engine/Graphics/Command.h + .cpp` | RenderCommand/ComputeCommand — command buffer wrappers |
|
||||
| `src/Engine/Graphics/Meshlet.h + .cpp` | meshlet data structure for GPU culling |
|
||||
| `src/Engine/Graphics/Mesh.h + .cpp` | GPU mesh asset |
|
||||
| `src/Engine/Graphics/VertexData.h + .cpp` | CPU mesh data, meshlet builder, GPU upload — 27.5KB impl |
|
||||
| `src/Engine/Graphics/StaticMeshVertexData.h + .cpp` | static mesh implementation |
|
||||
| `src/Engine/Graphics/Initializer.h` | ALL create-info structs: GraphicsInitializer, WindowCreateInfo, ViewportCreateInfo, TextureCreateInfo, BufferCreateInfo, ShaderCreateInfo, PipelineCreateInfo variants, SamplerCreateInfo, etc. — 8.5KB |
|
||||
| `src/Engine/Graphics/Enums.h` | 81KB — all Vulkan/Metal enums, flags, and mapping tables |
|
||||
|
||||
## Gotchas & sharp edges
|
||||
|
||||
- VertexData is NOT an entt component — it is a standalone object that self-registers into a static global list. GameView::update() calls VertexData::getList() to iterate all registered instances. If you create a VertexData and never add it to a scene entity, it still appears in the global list.
|
||||
- StaticMeshVertexData is the only concrete VertexData implementation in the codebase. There is no 'dynamic mesh' or 'animated mesh' VertexData variant.
|
||||
- The Slang compiler is invoked at RUNTIME via slang-compile.cpp — shaders are NOT pre-compiled at build time. This means first-frame startup time includes Slang compilation. The PipelineCache (Vulkan/PipelineCache.cpp, 36.8KB / Metal/PipelineCache.mm, 12.8KB) caches compiled pipeline binaries to disk to avoid re-compilation on subsequent launches.
|
||||
- DescriptorSet and DescriptorLayout are GPU resources — they are created via Graphics::createDescriptorLayout / the backend. You cannot create them directly; you must go through the Graphics factory.
|
||||
- The MeshPipelineCreateInfo (for mesh shading) is a SEPARATE struct from LegacyPipelineCreateInfo. Graphics::createGraphicsPipeline has two overloads — one takes each. Passing the wrong one is a compile error (no implicit conversion).
|
||||
- ShaderCompiler is a member of Graphics (OShaderCompiler shaderCompiler) and is accessed via Graphics::getShaderCompiler(). It is NOT a standalone service — it dies when the Graphics instance is destroyed.
|
||||
- RenderTargetAttachment holds a Gfx::PTexture (the actual texture) + load/store ops + initial/final layouts. The RenderTarget class wraps the GPU render pass + framebuffers. createRenderPass on Graphics takes a RenderTargetLayout (array of attachments) + SubPassDependency array + render area + optional viewMasks/correlationMasks (for multi-view/SPIRV workarounds).
|
||||
- Buffer.h defines the abstract Buffer base with a BufferUsageFlags enum. ShaderBuffer is for generic GPU-usable buffers (uniform/vertex/index data). UniformBuffer is specifically for uniform buffers (has a dedicated createUniformBuffer factory). VertexBuffer and IndexBuffer are for vertex/index data (have dedicated factories).
|
||||
- The 81KB Enums.h file contains ALL Vulkan enums + Metal enum mappings. It is auto-generated or hand-maintained. Modifying it is fragile.
|
||||
- PipelineCache (Vulkan) serializes VkPipelineCacheData to disk. Metal's PipelineCache.mm uses MTLBinaryArchive. Both are keyed by a hash of the pipeline create-info + shader code.
|
||||
|
||||
---
|
||||
|
||||
*Generated from a full read of the checked-out source at commit `d3ed573`. If a path has moved, `git grep` for the type name — the engine is small enough to find anything in seconds.*
|
||||
@@ -0,0 +1,48 @@
|
||||
# Materials & Shader Graphs (ShaderExpression)
|
||||
|
||||
> The node-graph material system that emits Slang at runtime: Material, MaterialInstance, ShaderExpression, and the shader compiler entry.
|
||||
|
||||
This is a **navigation** doc: it tells you where things live, how data actually flows, and the sharp edges — so you can orient in minutes instead of hours. It complements the repository's [AGENTS.md](../../AGENTS.md) (map + rules) and the [cross-repo guide](../cross-repo.md) (engine ↔ demo contract). Everything below is grounded in the checked-out source at commit `d3ed573`.
|
||||
|
||||
## Key types & where they live
|
||||
|
||||
| Type | Defined in |
|
||||
|------|------------|
|
||||
| `Material` | `src/Engine/Material/Material.h` |
|
||||
| `MaterialInstance` | `src/Engine/Material/MaterialInstance.h` |
|
||||
| `ShaderExpression` | `src/Engine/Material/ShaderExpression.h` |
|
||||
| `MaterialAsset` | `src/Engine/Asset/MaterialAsset.h` |
|
||||
| `MaterialInstanceAsset` | `src/Engine/Asset/MaterialInstanceAsset.h` |
|
||||
|
||||
Paths above are resolved against the actual source tree (namespace ≈ directory in this codebase). A `(search)` marker means the file contains the name but may also define others — open it and grep. `git grep` is always a fallback. The full per-file map is in **Where to look** below.
|
||||
|
||||
## Data flow / lifecycle
|
||||
|
||||
Material (src/Engine/Material/Material.h + Material.cpp, 2.4KB header + 7.7KB impl) is the runtime material object (DEFINE_REF(Material) -> PMaterial). It owns a ShaderExpression (the compiled shader graph) + a Map of texture parameter bindings + scalar/vec/matrix parameter values. Material::update() (or equivalent) re-evaluates the ShaderExpression when parameters change and rebuilds the Slang source string. MaterialInstance (MaterialInstance.h + .cpp, 1.5KB + 2.6KB) is a per-entity or per-asset material variant that references a base Material (PMaterial) and overrides specific parameters (texture swaps, scalar overrides). MaterialInstanceAsset (Asset/MaterialInstanceAsset.h + .cpp, 791B + 1KB) is the loadable asset wrapper. MaterialAsset (Asset/MaterialAsset.h + .cpp, 805B + 1.2KB) is the loadable asset for the base material — it loads the material definition from disk (JSON or binary) and constructs the Material + ShaderExpression. ShaderExpression (src/Engine/Material/ShaderExpression.h + .cpp, 12.6KB header + 14KB impl) is the node-graph representation of a material shader: it is a directed acyclic graph of shader nodes (math ops, texture samples, parameter reads, branching, loops) that is compiled to Slang source code. The ShaderExpression::compile() (or equivalent) walks the node graph and emits Slang source, which is then handed to the ShaderCompiler (via Graphics::beginShaderCompilation) for GPU compilation. The node types are defined in ShaderExpression.h (12.6KB — large header with all node structs). The material system is the HIGHEST-LEVEL abstraction in the engine: game code creates MaterialAsset (loaded from disk) -> Material (runtime) -> MaterialInstance (per-entity override) -> ShaderExpression (node graph) -> Slang source -> ShaderCompiler -> GPU shader. The AssetViewer tool (src/AssetViewer/main.cpp, 7KB) is a standalone tool that can browse/inspect assets including materials.
|
||||
|
||||
## Where to look
|
||||
|
||||
| Path | What's there |
|
||||
|------|--------------|
|
||||
| `src/Engine/Material/Material.h + Material.cpp` | runtime material, 7.7KB impl |
|
||||
| `src/Engine/Material/MaterialInstance.h + .cpp` | per-entity material override |
|
||||
| `src/Engine/Material/ShaderExpression.h + .cpp` | node graph -> Slang source, 12.6KB + 14KB |
|
||||
| `src/Engine/Asset/MaterialAsset.h + .cpp` | loadable material asset |
|
||||
| `src/Engine/Asset/MaterialInstanceAsset.h + .cpp` | loadable material instance asset |
|
||||
| `src/Editor/Asset/MaterialLoader.h + .cpp` | editor-side material loader, 9.5KB impl |
|
||||
| `src/AssetViewer/main.cpp` | standalone asset browser |
|
||||
|
||||
## Gotchas & sharp edges
|
||||
|
||||
- ShaderExpression is the most complex single file in the material system (12.6KB header + 14KB impl). It defines ALL shader node types as C++ structs in the header. The node graph is a DAG — there is no cycle detection at compile time (a malformed graph can cause infinite recursion in the Slang emitter).
|
||||
- The material system compiles Slang at RUNTIME — every material change triggers a full Slang compilation cycle. For a project with many materials, this can cause significant stutter on first use of each material. The PipelineCache mitigates this by caching compiled pipeline binaries, but the Slang compilation itself is not cached (only the GPU pipeline binaries are).
|
||||
- MaterialInstance overrides are PARAMETER-LEVEL only — you cannot override the shader graph topology at the instance level. To use a different shader graph, you need a different Material (and therefore a different MaterialAsset).
|
||||
- The material loader in the Editor (MaterialLoader.cpp, 9.5KB) reads material definitions from a JSON or binary format on disk. The format is NOT documented in a schema file in the repository — you must reverse-engineer it from MaterialLoader.cpp or the AssetViewer.
|
||||
- MaterialAsset and MaterialInstanceAsset are separate asset types. A MaterialInstanceAsset references a MaterialAsset by name/ID. If the referenced MaterialAsset is missing or corrupted, the MaterialInstanceAsset will fail to load (check the error handling in MaterialInstanceAsset.cpp).
|
||||
- The Slang compiler (slang-compile.cpp) is a standalone C++ file that links against the Slang compiler library (libslang). The Slang library is an external dependency (not in the Seele source tree). It must be present at build time. The slang-compile.cpp file (9KB) wraps the Slang C API to compile a Slang source string into SPIR-V (Vulkan target) or MetalSL (Metal target).
|
||||
- Material::update() is called by the game code (or the MeshUpdater system) when material parameters change. If you modify a material parameter at runtime without calling update(), the GPU shader will not see the change. The ShaderExpression must be re-evaluated and the Slang re-compiled (or the parameter must be uploaded as a runtime uniform without recompilation — check Material.cpp for which approach is used).
|
||||
- There is NO 'material shader cache' at the Slang level. The PipelineCache caches GPU pipeline binaries (VkPipeline / MTLRenderPipelineState), but if the Slang source changes (because a parameter was added/removed from the graph), the cache key changes and a full recompile occurs. Changing parameter VALUES (not the graph topology) should not trigger a recompile — check Material.cpp to confirm the parameter upload path bypasses Slang compilation.
|
||||
|
||||
---
|
||||
|
||||
*Generated from a full read of the checked-out source at commit `d3ed573`. If a path has moved, `git grep` for the type name — the engine is small enough to find anything in seconds.*
|
||||
@@ -0,0 +1,65 @@
|
||||
# Metal Backend (Metal::Graphics)
|
||||
|
||||
> The Metal implementation: device setup, resource creation, and the feature set it lacks versus Vulkan.
|
||||
|
||||
This is a **navigation** doc: it tells you where things live, how data actually flows, and the sharp edges — so you can orient in minutes instead of hours. It complements the repository's [AGENTS.md](../../AGENTS.md) (map + rules) and the [cross-repo guide](../cross-repo.md) (engine ↔ demo contract). Everything below is grounded in the checked-out source at commit `d3ed573`.
|
||||
|
||||
## Key types & where they live
|
||||
|
||||
| Type | Defined in |
|
||||
|------|------------|
|
||||
| `Metal::Graphics` | `src/Engine/Graphics/Graphics.h` |
|
||||
| `Metal::Window` | `src/Engine/Graphics/Metal/Window.h` |
|
||||
| `Metal::Viewport` | `src/Editor/Window/ViewportControl.h` (search) |
|
||||
| `Metal::RenderPass` | `src/Engine/Graphics/Metal/RenderPass.h` |
|
||||
| `Metal::Buffer (all types)` | `git grep` in `src/` |
|
||||
| `Metal::Texture (all types)` | `git grep` in `src/` |
|
||||
| `Metal::Shader (all stages)` | `git grep` in `src/` |
|
||||
| `Metal::DescriptorLayout/DescriptorSet/PipelineLayout` | `git grep` in `src/` |
|
||||
| `Metal::GraphicsPipeline/ComputePipeline` | `git grep` in `src/` |
|
||||
| `Metal::Command (RenderCommand/ComputeCommand)` | `git grep` in `src/` |
|
||||
| `Metal::Query (Occlusion/Statistics/Timestamp)` | `git grep` in `src/` |
|
||||
| `Metal::PipelineCache` | `src/Engine/Graphics/Metal/PipelineCache.h` |
|
||||
| `Metal::Resources` | `src/Engine/Graphics/Metal/Resources.h` |
|
||||
|
||||
Paths above are resolved against the actual source tree (namespace ≈ directory in this codebase). A `(search)` marker means the file contains the name but may also define others — open it and grep. `git grep` is always a fallback. The full per-file map is in **Where to look** below.
|
||||
|
||||
## Data flow / lifecycle
|
||||
|
||||
Metal::Graphics (src/Engine/Graphics/Metal/Graphics.h + Graphics.mm, 5.8KB header + 8.3KB impl) implements Gfx::Graphics using the Metal.framework (Objective-C++). init(GraphicsInitializer) creates an MTLDevice (MTLCreateSystemDefaultDevice or from a specific identifier), an MTLCommandQueue (banded width from GraphicsInitializer), and a Metal::PipelineCache (MTLBinaryArchive-based). There is NO surface/swapchain management in Graphics.mm — that is in Window.mm (7.7KB) which creates an NSWindow (Cocoa) + CAMetalLayer + MTLView, manages the drawable pool, and handles the frame loop (drawable acquisition, command buffer commit, present). The Metal backend does NOT support ray tracing (rayTracingEnabled is always false — Metal RT is not implemented). It also does NOT support mesh shading (meshShadingEnabled is always false). All resource types mirror the Gfx::Graphics interface: Buffer.mm (8.9KB) implements MTLBuffer wrappers for all buffer types (shader/uniform/vertex/index) with MTLResourceStorageModeShared by default. Texture.mm (14.6KB) implements all MTLTexture types (2D/2DArray/3D/cube) with mipmap generation (blit encoder generateMipmaps), MTLTextureView, MTSamplerState. Shader.mm (1.9KB) creates MTLFunction objects from compiled MetalSL (the Slang compiler outputs MetalSL for the Metal target — see slang-compile.cpp target detection). Command.mm (16.5KB) implements MTLCommandBuffer + MTLRenderCommandEncoder + MTLComputeCommandEncoder wrappers: RenderCommand begins/ends render encoders, draws primitives (drawPrimitives, drawIndexedPrimitives), blits, resolves; ComputeCommand dispatches threadgroups (dispatchThreadgroups). Descriptor.mm (8.8KB) implements MTLBuffer/MTLTexture/MTLSamplerState binding into an MTLRenderPipelineState/MTLComputePipelineState (Metal has no descriptor sets — bindings are direct function arguments via the pipeline state's argument buffer, implemented here as an argument buffer + per-frame update). Pipeline.mm (906B) creates MTLRenderPipelineState (from MTLRenderPipelineDescriptor) and MTLComputePipelineState (from MTLComputePipelineDescriptor). Query.mm (2KB) implements MTLCommandBuffer counters (GPU timestamp via MTLCommandBuffer.GPUStartTime/GPUEndTime, occlusion via MTLResourceID + draw dispatch count). PipelineCache.mm (12.8KB) uses MTLBinaryArchive to cache compiled pipeline states to disk. Resources.mm (2KB) is a thin wrapper for shared Metal resource management. The Metal backend uses Objective-C++ (.mm files) throughout — all Metal API calls are Objective-C method invocations. The C++-side headers (Graphics.h, Buffer.h, Texture.h, etc.) define the C++ interface that matches Gfx::Graphics, and the .mm files implement them.
|
||||
|
||||
## Where to look
|
||||
|
||||
| Path | What's there |
|
||||
|------|--------------|
|
||||
| `src/Engine/Graphics/Metal/Graphics.h` | 5.8KB — Metal backend interface |
|
||||
| `src/Engine/Graphics/Metal/Graphics.mm` | 8.3KB — MTLDevice + MTLCommandQueue creation, factory methods |
|
||||
| `src/Engine/Graphics/Metal/Window.h + .mm` | Cocoa NSWindow + CAMetalLayer + MTLView, 7.7KB impl |
|
||||
| `src/Engine/Graphics/Metal/Command.h + .mm` | MTLCommandBuffer + render/compute encoders, 16.5KB impl |
|
||||
| `src/Engine/Graphics/Metal/Texture.h + .mm` | all MTLTexture types, 14.6KB impl |
|
||||
| `src/Engine/Graphics/Metal/Buffer.h + .mm` | MTLBuffer wrappers, 8.9KB impl |
|
||||
| `src/Engine/Graphics/Metal/Descriptor.h + .mm` | argument buffers for Metal pipeline binding, 8.8KB impl |
|
||||
| `src/Engine/Graphics/Metal/Pipeline.h + .mm` | MTLRenderPipelineState + MTLComputePipelineState |
|
||||
| `src/Engine/Graphics/Metal/Query.h + .mm` | GPU timestamps + occlusion counters |
|
||||
| `src/Engine/Graphics/Metal/PipelineCache.h + .mm` | MTLBinaryArchive caching, 12.8KB impl |
|
||||
| `src/Engine/Graphics/Metal/Shader.h + .mm` | MTLFunction from MetalSL |
|
||||
| `src/Engine/Graphics/Metal/Resources.h + .mm` | shared resource management |
|
||||
| `src/Engine/Graphics/Metal/Enums.h + .mm` | Metal-specific enum mappings, 32KB impl |
|
||||
|
||||
## Gotchas & sharp edges
|
||||
|
||||
- The Metal backend does NOT support ray tracing or mesh shading — both capability flags are hardcoded false. RayTracingPass and mesh-shading pipelines will never be used on Metal. The engine's RT path is Vulkan-only.
|
||||
- Metal has no descriptor sets or pipeline layouts in the hardware sense. Metal::Descriptor.mm implements the Gfx::DescriptorLayout/DescriptorSet interface using MTLBuffer argument buffers — the 'descriptor set' is an MTLBuffer that holds raw GPU-visible data, and the pipeline state's MTLFunction constant binding references it. This is a software abstraction over Metal's argument buffer mechanism.
|
||||
- All Metal source files are .mm (Objective-C++). You need Xcode command-line tools + the Metal.framework to build the Metal backend. The CMakeLists.txt in Metal/ configures the .mm files and links against Metal.framework + Foundation.framework.
|
||||
- The MTLDevice is created once at init() and is shared by all resources. There is no per-window device — a single MTLDevice serves all windows in the process. If the device is lost (e.g. GPU reset), the entire engine must be re-initialized.
|
||||
- MTLCommandQueue is created at init() with a banded width (from GraphicsInitializer). The command queue is long-lived and shared by all render/compute commands. Command buffers are created per-frame (or per-command) and destroyed after commit + waitCompleted. There is no command buffer pool — each MTLCommandBuffer is created fresh.
|
||||
- The Window.mm file creates an NSWindow (Cocoa) on macOS. On Linux the Metal backend is NOT available (no Metal.framework on Linux). The Metal backend is macOS-only. Linux uses the Vulkan backend. Windows can use either (the build system selects based on CMake options).
|
||||
- Mipmap generation on Metal uses MTLBlitCommandEncoder.generateMipmapsForTexture. The texture must have MTLResourceUsageBlit | MTLResourceUsageShaderRead enabled. The initial texture usage in Texture.mm is set based on the usage flags in TextureCreateInfo — if mipmap generation is requested but the usage flags are wrong, the blit will fail silently.
|
||||
- The Metal backend's command encoder lifetime is tied to the MTLCommandBuffer. All render/compute encoders must be ended before the command buffer is committed. The Command.mm implementation tracks encoder lifetime and asserts if you try to commit with an open encoder.
|
||||
- MTLBinaryArchive (PipelineCache.mm) caches compiled MTLRenderPipelineState and MTLComputePipelineState objects. The cache is keyed by a hash of the pipeline descriptor + shader function name. If the Metal driver changes (macOS update), the cache is invalidated automatically by the system (MTLBinaryArchive handles this).
|
||||
- The Metal backend's Window.mm uses MTLView (a NSView subclass that integrates Metal rendering with Cocoa). The frame callback is driven by MTLView's updateDrawable callback (called by the system when the window needs a new frame). There is no manual frame loop — the system drives rendering at the display refresh rate.
|
||||
- Metal's GPU timestamps (Query.mm) use MTLCommandBuffer.GPUStartTime/GPUEndTime (mach_time_t). Converting to nanoseconds requires converting the mach_time base (mach_timebase_info). The TimestampQuery implementation in Query.mm does this conversion. Occlusion queries use MTLCommandBuffer.dispatchThreadgroupCounts + a counter buffer (there is no hardware occlusion query on Metal).
|
||||
|
||||
---
|
||||
|
||||
*Generated from a full read of the checked-out source at commit `d3ed573`. If a path has moved, `git grep` for the type name — the engine is small enough to find anything in seconds.*
|
||||
@@ -0,0 +1,120 @@
|
||||
# Physics (Jolt Physics integration, collision, BVH broadphase)
|
||||
|
||||
> **Scope:** `src/Engine/Physics/` — the engine's rigid-body physics. The heavy lifting is done by
|
||||
> **Jolt Physics** (the external library in `external/JoltPhysics`, linked in `src/Engine/CMakeLists.txt`);
|
||||
> Seele provides a **thin ECS/Scene wrapper** on top: `PhysicsSystem`, `CollisionSystem`, and a
|
||||
> `BVH` broadphase. You almost never touch Jolt directly — you add components and let the systems
|
||||
> do the rest.
|
||||
|
||||
**Read `AGENTS.md` first** — it has a dedicated "Physics (Jolt)" section with the ground rules
|
||||
(this doc complements it with navigation). Jolt is a **third-party black box**: you configure it,
|
||||
you don't modify it, and you don't assume its internals.
|
||||
|
||||
## Key types & where they live
|
||||
|
||||
| Type | Defined in |
|
||||
|------|------------|
|
||||
| `PhysicsSystem` | `src/Engine/Physics/PhysicsSystem.h` (impl `PhysicsSystem.cpp`, ~18 KB — the main integration) |
|
||||
| `PhysicsSystem::Body` | `src/Engine/Physics/PhysicsSystem.h:18` — Seele's mirror of a Jolt rigid body |
|
||||
| `PhysicsSystem::Contact` | `src/Engine/Physics/PhysicsSystem.h` — a collision contact |
|
||||
| `CollisionSystem` | `src/Engine/Physics/CollisionSystem.h` (impl `CollisionSystem.cpp`) |
|
||||
| `CollisionSystem::Witness` | `src/Engine/Physics/CollisionSystem.h:21` — witness-point broadphase state |
|
||||
| `BVH` | `src/Engine/Physics/BVH.h` (impl `BVH.cpp`) — the broadphase spatial structure |
|
||||
| `Component::RigidBody`, `Component::Collider`, `Component::ShapeBase`, `Box/Mesh/Sphere/Plane` | `src/Engine/Component/` (see [scene-ecs-components-actors.md](scene-ecs-components-actors.md)) |
|
||||
|
||||
`PhysicsSystem` is **embedded in `Scene`** (it is a member, not a `System` in the `SystemGraph`) —
|
||||
it is *not* a node you add to the system graph. It is driven by the scene's update tick. The
|
||||
`CollisionSystem` likewise operates on the `entt::registry`. This is a key difference from the
|
||||
"everything is a `System`" pattern — physics is *scene-owned*, not *graph-owned*.
|
||||
|
||||
## The data flow (how a body actually moves)
|
||||
|
||||
```
|
||||
Component::RigidBody + Component::Collider + Component::Transform (on an Actor's entity)
|
||||
│ (Scene collects these into PhysicsSystem bodies)
|
||||
▼
|
||||
PhysicsSystem::update(deltaTime)
|
||||
├─ readRigidBodies() # gather current Component state → Array<Body>
|
||||
├─ serializeArray(bodies, x) # pack Body[] → float[] (the Jolt API boundary)
|
||||
├─ [Jolt step] # Jolt integrates the float[] (forces, velocities, collisions)
|
||||
├─ deserializeArray(...) # unpack Jolt's result back into Body[]
|
||||
└─ write results back to Component::Transform / RigidBody (positions, velocities)
|
||||
▼
|
||||
CollisionSystem::detectCollisions() # broadphase (BVH) + narrowphase (witness points)
|
||||
└─ → Array<Collision> / Contacts (consumed by gameplay / events)
|
||||
```
|
||||
|
||||
The **`serializeArray`/`deserializeArray` pair is the Jolt API boundary** (`PhysicsSystem.h:83-87`).
|
||||
Jolt's public API works on `float*` state vectors, not C++ objects. Seele's `Body` struct is a
|
||||
*C++-side mirror* of what Jolt stores; every step it's serialized across into Jolt's float world and
|
||||
back. **If you add a new physical property, you must add it to all four**: the `Body` field,
|
||||
`serializeRB`, `deserializeRB`, and the component that feeds it — miss one and the value silently
|
||||
doesn't round-trip (Jolt integrates a stale copy).
|
||||
|
||||
## The `Body` struct (what Seele tracks per body)
|
||||
|
||||
`PhysicsSystem::Body` (`PhysicsSystem.h:18`) holds the full rigid-body state, with Jolt-aligned
|
||||
naming (so the serialization is a straight field map):
|
||||
|
||||
- `id` (the `entt::entity`), `centerOfMass`, `iBody`/`iBodyInv` (body-space inverse inertia, from
|
||||
`collider.physicsMesh.bodyInertia`), `scale`
|
||||
- state: `x` (position), `q` (orientation quat), `R` (orientation matrix), `v` (linear vel),
|
||||
`omega` (angular vel), `P` (linear momentum), `L` (angular momentum), `iInv` (world-space inverse
|
||||
inertia, recomputed in the ctor as `R * iBodyInv * Rᵀ`)
|
||||
- `force` / `torque` (inputs from `Component::RigidBody`)
|
||||
- `matrix` (the final world transform, `updateMatrix()` composes scale→rotation→translation)
|
||||
- `ptVelocity(p)` — a rigid-body point velocity helper (`v + ω × (p - x + com)`)
|
||||
|
||||
There are **two ctors**: one that takes a `RigidBody` (dynamic, momentum-carrying) and one that
|
||||
doesn't (kinematic/static, zero momentum). Both normalize the quaternion and recompute `iInv`.
|
||||
|
||||
## CollisionSystem (broadphase + narrowphase)
|
||||
|
||||
`CollisionSystem` (`CollisionSystem.h`) produces `Array<Collision>` each tick:
|
||||
|
||||
- **Broadphase** via `BVH` — a bounding-volume hierarchy over collider AABBs. `CollisionSystem`
|
||||
builds/maintains it and queries candidate pairs (broadphase = "which pairs *might* collide").
|
||||
- **Narrowphase** via **witness points** (`CollisionSystem::Witness`, `createWitness`/
|
||||
`updateWitness`/`witnessValid`): a classic GJK-style witness-point test that decides, for a
|
||||
*candidate* pair, whether the shapes actually intersect. This is the "do these two shapes
|
||||
actually collide" step.
|
||||
- `checkCollision(pair)` / `detectCollisions(&out)` are the entry points.
|
||||
|
||||
**Gotcha:** the broadphase is a *filter*, not a guarantee. A pair passing the broadphase still
|
||||
needs the narrowphase witness test. Don't treat "broadphase said they might collide" as
|
||||
"they collided."
|
||||
|
||||
## The BVH
|
||||
|
||||
`BVH` (`Physics/BVH.h` + `BVH.cpp`, ~10 KB) is a generic bounding-volume hierarchy. It's the
|
||||
spatial index the `CollisionSystem` uses for the broadphase. It's a reusable structure — if you
|
||||
need broadphase for something else (culling queries, picking), this is the building block. (For
|
||||
**rendering** culling, see the mesh culling in [meshes-and-meshlets.md](render-graph-and-passes.md) —
|
||||
that's a *different* BVH/`MeshCullingSystem` in `src/Engine/Rendering/`, do not confuse the two.)
|
||||
|
||||
## Gotchas
|
||||
|
||||
- **Physics is scene-owned, not graph-owned.** `PhysicsSystem` is a `Scene` member; you do *not*
|
||||
add it to a `SystemGraph`. Don't look for it in the graph.
|
||||
- **Adding a property = 4 places** (Body field + serialize + deserialize + component). Silent
|
||||
failure mode: value doesn't round-trip through Jolt.
|
||||
- **Jolt is a black box.** Configure via the components; don't reach into `external/JoltPhysics`
|
||||
to "fix" behavior. (The one legitimate exception is linking/version, in `src/Engine/CMakeLists.txt`.)
|
||||
- **Don't confuse the two BVHs.** `Physics/BVH` = collision broadphase. `Rendering` culling = a
|
||||
separate structure. Similar names, different subsystems, different files.
|
||||
- **`iInv` is recomputed in the `Body` ctor** from `iBody` and orientation. If you mutate
|
||||
`q`/`R` after construction, you must recompute `iInv` or the dynamics are wrong.
|
||||
- **Contacts are a transient view.** `Contact`/`Collision` are filled per tick; don't cache them
|
||||
across frames or they go stale.
|
||||
|
||||
## Where to look
|
||||
|
||||
| What you're doing | Start here |
|
||||
|---|---|
|
||||
| Add a rigid body to a scene | `Component::RigidBody` + `Component::Collider` on an Actor (see scene-ecs doc) |
|
||||
| Add a new collider shape | `src/Engine/Component/` shapes (`ShapeBase` + `Box`/`Mesh`/`Sphere`/`Plane`) + `physicsMesh` (the Jolt mesh) |
|
||||
| Add a physical property that round-trips through Jolt | `PhysicsSystem::Body` + `serializeRB`/`deserializeRB` + the component |
|
||||
| Understand a "body doesn't move / wrong velocity" bug | the serialize→Jolt→deserialize path in `PhysicsSystem.cpp` |
|
||||
| Add a new collision response / query | `CollisionSystem.h` (witness) + `BVH.h` (broadphase) |
|
||||
| Jolt linking / version | `src/Engine/CMakeLists.txt` (`JOLT_PHYSICS_LIB`) |
|
||||
| Ground rules (read first) | `AGENTS.md` § "Physics (Jolt)" |
|
||||
@@ -0,0 +1,136 @@
|
||||
# Platform (OS abstraction, dynamic library loading, input enums)
|
||||
|
||||
> **Scope:** `src/Engine/Platform/` — the OS-specific layer. In Seele this is *smaller than you'd
|
||||
> expect*: the platform directory is mostly the **per-OS `GameInterface`** (which dynamically loads
|
||||
> the game's own shared library) plus the shared input enums. Heavy OS work (windows, surfaces,
|
||||
> Vulkan/Metal) lives in `Window/` and `Graphics/{Vulkan,Metal}/` respectively — this doc covers
|
||||
> the platform abstraction and, critically, **how the demo's game code actually gets loaded**.
|
||||
|
||||
This is one of the most important subsystems to understand for cross-repo work, because the
|
||||
`Platform` layer is where the **engine ↔ demo boundary is physically enforced** (dlopen /
|
||||
LoadLibrary + symbol lookup).
|
||||
|
||||
## Key types & where they live
|
||||
|
||||
| Type | Defined in |
|
||||
|------|------------|
|
||||
| `GameInterface` (Windows) | `src/Engine/Platform/Windows/GameInterface.h` (impl `.cpp`) |
|
||||
| `GameInterface` (Linux) | `src/Engine/Platform/Linux/GameInterface.h` (impl `.cpp`) |
|
||||
| `GameInterface` (macOS) | `src/Engine/Platform/Mac/GameInterface.h` (impl `.cpp`) |
|
||||
| `Game` | `src/Engine/Game.h` — the abstract class the loaded lib must instantiate |
|
||||
| Input enums: `InputAction`, `KeyCode`, `MouseButton`, `KeyModifier` | `src/Engine/Platform/` (shared, included by `Window/View.h` input callbacks) |
|
||||
| `Window` (per-OS native surface) | `src/Engine/Window/Window.h`/`Window.cpp` (the OS window lives here, not in `Platform/`) |
|
||||
|
||||
**There is no monolithic `Platform.h`** (an older description of the codebase implied there was
|
||||
one — there isn't; `grep` for `dlopen`/`LoadLibrary` confirms all the dynamic-loading code is in the
|
||||
three `Platform/<OS>/GameInterface.cpp` files). The `Platform/` directory is the OS *abstraction for
|
||||
loading the game*, not a general OS facade.
|
||||
|
||||
## The per-OS `GameInterface` — how the demo is loaded
|
||||
|
||||
Each OS has a `GameInterface` with the same public shape:
|
||||
|
||||
```cpp
|
||||
class GameInterface {
|
||||
public:
|
||||
GameInterface(std::filesystem::path libPath); // path to the demo's .so/.dylib/.dll
|
||||
~GameInterface();
|
||||
Game* getGame(); // the live Game* (createInstance() result)
|
||||
void reload(); // (re)load the library + re-instantiate
|
||||
|
||||
private:
|
||||
// Windows: HMODULE lib; Linux: void* lib (dlopen); Mac: void* (dlopen)
|
||||
Game* (*createInstance)() = nullptr; // resolved symbol
|
||||
void (*destroyInstance)(Game*) = nullptr;
|
||||
};
|
||||
```
|
||||
|
||||
**`reload()` is the cross-repo contract in executable form.** It is *identical in logic* across all
|
||||
three OSes, only the syscalls differ:
|
||||
|
||||
| OS | Load | Resolve symbols | Unload |
|
||||
|----|------|-----------------|--------|
|
||||
| **Windows** (`Platform/Windows/GameInterface.cpp`) | `LoadLibraryA(dllPath)` | `GetProcAddress(lib, "createInstance")` / `...("destroyInstance")` | `FreeLibrary(lib)` |
|
||||
| **Linux** (`Platform/Linux/GameInterface.cpp`) | `dlopen(soPath, RTLD_NOW)` | `dlsym(lib, "createInstance")` / `...("destroyInstance")` | `dlclose(lib)` |
|
||||
| **macOS** (`Platform/Mac/GameInterface.cpp`) | `dlopen` | `dlsym` | `dlclose` |
|
||||
|
||||
The contract:
|
||||
|
||||
1. If a previous library is loaded, call `destroyInstance(game)` then unload it.
|
||||
2. Load the demo's shared library at `libPath`.
|
||||
3. Look up **exactly two** C symbols: `createInstance` and `destroyInstance` (plain `extern "C"`,
|
||||
no mangling).
|
||||
4. Call `createInstance()` → `Game*`; store it; `getGame()` returns it.
|
||||
|
||||
**The demo must export exactly these two `extern "C"` symbols** — that is the *entire* ABI. See
|
||||
[cross-repo.md](../cross-repo.md) for the demo-side half and [game-interface.md](game-interface.md)
|
||||
for the engine-side `Game` class.
|
||||
|
||||
### Gotcha: `reload()` also copies game shaders
|
||||
|
||||
The **Windows** `GameInterface::reload()` does something the other two don't (a known
|
||||
asymmetry): before loading, it **copies `<dllPath>/../res/shaders` → `./shaders/game`**
|
||||
(`std::filesystem::copy(..., copy_options::overwrite_existing)`) if that path exists. This is the
|
||||
**game-shader hot-reload** mechanism — the engine reads game shaders from `./shaders/game`, and
|
||||
`reload()` refreshes that directory so a rebuilt demo's new shaders are picked up without a full
|
||||
restart.
|
||||
|
||||
**Consequences:**
|
||||
- On Windows, "reload the game" also refreshes its shaders. On Linux/mac, it does **not** — the
|
||||
shader directory must be managed out-of-band (or you're on a platform where the copy step simply
|
||||
doesn't exist yet). **If you add cross-platform shader hot-reload, this is the place to fix the
|
||||
asymmetry.**
|
||||
- The copy target is the **CWD** (`./shaders/game`), not next to the library. CWD matters.
|
||||
- `rt`/`rt` and the engine's own shaders are separate — this only touches `shaders/game` (the
|
||||
*game's* shaders), not the engine's.
|
||||
|
||||
## Input enums (the shared platform types)
|
||||
|
||||
`InputAction`, `KeyCode`, `MouseButton`, `KeyModifier` live in `src/Engine/Platform/` and are the
|
||||
**vocabulary of every input callback** in `Window/View.h` (`keyCallback`, `mouseButtonCallback`,
|
||||
etc.) and in `UI::System` (`key`, `mouseButton`, `scroll`). If you're adding a new input source or
|
||||
keycode, these are the enums to extend. They are the one truly shared, cross-OS piece of the
|
||||
`Platform/` layer (the `GameInterface` per-OS files are the rest).
|
||||
|
||||
## Where the OS "real" work actually lives (don't look here for it)
|
||||
|
||||
A common mistake is to look in `Platform/` for window/surface/GPU code. It's not here:
|
||||
|
||||
| Concern | Actual location |
|
||||
|---|---|
|
||||
| OS window + native surface | `src/Engine/Window/Window.{h,cpp}` (+ per-OS bits there) |
|
||||
| Vulkan | `src/Engine/Graphics/Vulkan/` |
|
||||
| Metal | `src/Engine/Graphics/Metal/` |
|
||||
| Loading the *game* (this doc) | `src/Engine/Platform/<OS>/GameInterface.cpp` |
|
||||
|
||||
The reason `Platform/` is thin: Seele pushes OS-specific code *down into the subsystem that owns
|
||||
the concern* (windowing → `Window/`, GPU → `Graphics/<Backend>/`), and keeps only the
|
||||
**game-loading** logic in `Platform/` because that is the one cross-cutting OS difference that
|
||||
belongs nowhere else.
|
||||
|
||||
## Gotchas
|
||||
|
||||
- **Exactly two exported symbols** (`createInstance`, `destroyInstance`). Any other symbol the
|
||||
engine needs must be exposed *through* the `Game*` (virtual methods on `Game`), not as a new
|
||||
C symbol. Adding a third `extern "C"` export breaks the contract.
|
||||
- **Symbol names must be unmangled** (`extern "C"`). A mangled name = `dlsym`/`GetProcAddress`
|
||||
returns null = `createInstance` is null → crash on call.
|
||||
- **The shader-copy asymmetry** (Windows copies `res/shaders`→`./shaders/game` on reload; the
|
||||
others don't). Know which platform you're on before assuming "reload refreshes my shaders."
|
||||
- **`RTLD_NOW` on Linux** — all symbols are resolved at load; a missing symbol fails *at
|
||||
`dlopen`*, not at first use. Good for debugging, means a bad demo build fails loudly at load.
|
||||
- **`getGame()` lifetime** — the returned `Game*` is owned by the loaded library. When you `reload()`
|
||||
or unload, the old `Game*` is destroyed. Never hold a `Game*` across a `reload()`.
|
||||
- **CWD-sensitive** — the Windows shader copy writes to the *current working directory*, not the
|
||||
library's directory. Run from the right CWD.
|
||||
|
||||
## Where to look
|
||||
|
||||
| What you're doing | Start here |
|
||||
|---|---|
|
||||
| Understand how the demo is loaded | `src/Engine/Platform/<OS>/GameInterface.cpp` (all three, compare) |
|
||||
| Add a new exported symbol (you probably shouldn't) | `GameInterface.cpp` + the `Game` virtuals in `src/Engine/Game.h` |
|
||||
| Fix shader hot-reload / the Windows-only copy | `Platform/Windows/GameInterface.cpp` `reload()` (the `std::filesystem::copy` block) |
|
||||
| Add a key code / input action | the enums in `src/Engine/Platform/` + `Window/View.h` callbacks + `UI/System.h` |
|
||||
| "my game lib won't load" | symbol names (unmangled?), the two exports present, the lib path, `dlopen`/`LoadLibrary` error |
|
||||
| Per-OS window/surface (not here) | `src/Engine/Window/Window.{h,cpp}` |
|
||||
@@ -0,0 +1,67 @@
|
||||
# Render Graph & Render Passes
|
||||
|
||||
> The linear RenderGraph, the per-frame begin/render/end protocol, shared string-named resources, and every render pass in the active pipeline.
|
||||
|
||||
This is a **navigation** doc: it tells you where things live, how data actually flows, and the sharp edges — so you can orient in minutes instead of hours. It complements the repository's [AGENTS.md](../../AGENTS.md) (map + rules) and the [cross-repo guide](../cross-repo.md) (engine ↔ demo contract). Everything below is grounded in the checked-out source at commit `d3ed573`.
|
||||
|
||||
## Key types & where they live
|
||||
|
||||
| Type | Defined in |
|
||||
|------|------------|
|
||||
| `RenderGraph` | `src/Engine/Graphics/RenderPass/RenderGraph.h` |
|
||||
| `RenderPass` | `src/Engine/Graphics/Metal/RenderPass.h` |
|
||||
| `RenderGraphResources` | `src/Engine/Graphics/RenderPass/RenderGraphResources.h` |
|
||||
| `CachedDepthPass` | `src/Engine/Graphics/RenderPass/CachedDepthPass.h` |
|
||||
| `DepthCullingPass` | `src/Engine/Graphics/RenderPass/DepthCullingPass.h` |
|
||||
| `VisibilityPass` | `src/Engine/Graphics/RenderPass/VisibilityPass.h` |
|
||||
| `LightCullingPass` | `src/Engine/Graphics/RenderPass/LightCullingPass.h` |
|
||||
| `ShadowPass` | `src/Engine/Graphics/RenderPass/ShadowPass.h` |
|
||||
| `BasePass` | `src/Engine/Graphics/RenderPass/BasePass.h` |
|
||||
| `ToneMappingPass` | `src/Engine/Graphics/RenderPass/ToneMappingPass.h` |
|
||||
| `RayTracingPass` | `src/Engine/Graphics/RenderPass/RayTracingPass.h` |
|
||||
| `SimulationComputePass` | `src/Engine/Graphics/RenderPass/SimulationComputePass.h` |
|
||||
| `SurfaceExtractPass` | `src/Engine/Graphics/RenderPass/SurfaceExtractPass.h` |
|
||||
| `FluidRenderPass` | `src/Engine/Graphics/RenderPass/FluidRenderPass.h` |
|
||||
| `TerrainRenderer` | `src/Engine/Graphics/RenderPass/TerrainRenderer.h` |
|
||||
| `WaterRenderer` | `src/Engine/Graphics/RenderPass/WaterRenderer.h` |
|
||||
| `UIPass` | `src/Engine/Graphics/RenderPass/UIPass.h` |
|
||||
|
||||
Paths above are resolved against the actual source tree (namespace ≈ directory in this codebase). A `(search)` marker means the file contains the name but may also define others — open it and grep. `git grep` is always a fallback. The full per-file map is in **Where to look** below.
|
||||
|
||||
## Data flow / lifecycle
|
||||
|
||||
RenderGraph (src/Engine/Graphics/RenderPass/RenderGraph.h) is a simple linear pipeline: addPass(ORenderPass) (calls pass->setResources(res) to inject shared RenderGraphResources), setViewport, createRenderPass() (two-phase: first pass->publishOutputs() on all passes to register outputs into the shared resource map, then pass->createRenderPass() to create GPU render pass objects), render(cam, transform) (three-phase: beginFrame on all, render() on all, endFrame() on all). RenderGraphResources (RenderGraphResources.h) is a name-keyed resource registry: requestRenderTarget/requestTexture/requestBuffer/requestUniform/requestQuery/requestTimestampQuery for consumers, registerRenderPassOutput/registerTextureOutput/registerBufferOutput/registerUniformOutput/registerQueryOutput/registerTimestampQueryOutput for producers. Passes discover each other's outputs by string name (e.g. 'depthTexture', 'visibilityTexture', 'cullingBuffer', 'lightIndexList', 'lightGrid', 'shadowMaps'). RenderPass base class (RenderPass.h) holds: PRenderGraphResources resources, Gfx::PViewport viewport, Gfx::ORenderPass renderPass (GPU-side), Gfx::ODescriptorLayout viewParamsLayout, ViewParameter viewParams struct (viewMatrix, inverseViewMatrix, projectionMatrix, viewProjectionMatrix, cameraPosition_WS, cameraForward_WS, screenDimensions, invScreenDimensions, frameIndex, time). It provides updateViewParameters(cam, transform), createViewParamsSet(), and frustum culling helpers (computePlane, extract_planes_from_view_projection_matrix). A RenderPassType concept (std::derived_from<RenderPass>) is defined. GameView.cpp wires the active pipeline: CachedDepthPass -> DepthCullingPass -> VisibilityPass -> LightCullingPass -> ShadowPass -> BasePass -> ToneMappingPass. RayTracingPass is in a separate rayTracingGraph, gated by getGlobals().useRayTracing && graphics->supportRayTracing(). SimulationComputePass, SurfaceExtractPass, FluidRenderPass are commented out in both graphs (WIP).
|
||||
|
||||
## Where to look
|
||||
|
||||
| Path | What's there |
|
||||
|------|--------------|
|
||||
| `src/Engine/Graphics/RenderPass/RenderGraph.h` | 45 lines, full file |
|
||||
| `src/Engine/Graphics/RenderPass/RenderPass.h + RenderPass.cpp` | base class, 77 lines header / 6.8KB impl |
|
||||
| `src/Engine/Graphics/RenderPass/RenderGraphResources.h + .cpp` | shared resource registry |
|
||||
| `src/Engine/Window/GameView.cpp` | pipeline wiring, lines 24-108 |
|
||||
| `src/Engine/Graphics/RenderPass/CachedDepthPass.h + .cpp` | depth prepass + visibility prepass |
|
||||
| `src/Engine/Graphics/RenderPass/DepthCullingPass.h + .cpp` | GPU culling: depth mip buffer, BLOCK_SIZE=32, cullingBuffer output |
|
||||
| `src/Engine/Graphics/RenderPass/VisibilityPass.h + .cpp` | visibilityTexture + cullingBuffer, compute shader |
|
||||
| `src/Engine/Graphics/RenderPass/LightCullingPass.h + .cpp` | oLightIndexList/tLightIndexList, oLightGrid/tLightGrid, frustumBuffer, double-buffered |
|
||||
| `src/Engine/Graphics/RenderPass/ShadowPass.h + .cpp` | 4 cascades, 8192x8192 shadow maps, light-space matrices |
|
||||
| `src/Engine/Graphics/RenderPass/BasePass.h + .cpp` | main 3D pass: HDR MSAA color/depth, opaque+transparent meshlets, skybox, debug rendering |
|
||||
| `src/Engine/Graphics/RenderPass/ToneMappingPass.h + .cpp` | post-processing, final output to viewport |
|
||||
| `src/Engine/Graphics/RenderPass/RayTracingPass.h + .cpp` | TLAS 'scene', rayGen/anyhit/miss shaders, radiance accumulator |
|
||||
|
||||
## Gotchas & sharp edges
|
||||
|
||||
- RenderGraph is NOT a data-flow graph — it is a linear list with a two-phase setup (publishOutputs then createRenderPass) and a three-phase per-frame loop (beginFrame/render/endFrame on ALL passes before any pass runs its GPU work).
|
||||
- Passes communicate exclusively through string-named resources in RenderGraphResources. The names are hardcoded constants (e.g. DEPTHTEXTURE_NAME='depthTexture', VISIBILITY_NAME='visibilityTexture', CULLINGBUFFER_NAME='cullingBuffer', LIGHTINDEX_NAME='lightIndexList'). If you rename one, every consumer breaks silently.
|
||||
- CachedDepthPass is the FIRST pass in the graph — it does a depth prepass AND a visibility prepass (renders meshlets twice before anything else).
|
||||
- DepthCullingPass and VisibilityPass both write to 'cullingBuffer' — the culling buffer is a shared GPU buffer that DepthCullingPass creates and VisibilityPass consumes.
|
||||
- LightCullingPass uses double-buffered light grids (oLightGrid/tLightGrid, oLightIndexList/tLightIndexList) — the 'o' and 't' prefixes stand for odd/even frames.
|
||||
- BasePass.h has WaterRenderer and TerrainRenderer members commented out (lines 67-68) — water/terrain are not currently in the active render path.
|
||||
- SimulationComputePass, SurfaceExtractPass, FluidRenderPass are all commented out in GameView.cpp (lines 33-35, 41-43). The fluid simulation pipeline exists but is disabled.
|
||||
- ToneMappingPass takes only Gfx::PGraphics in its constructor (no scene) — it is the only pass that does not need scene access.
|
||||
- The 'RenderPass' name is overloaded: Gfx::RenderPass (GPU render pass object, created by Graphics::createRenderPass) vs Seele::RenderPass (the C++ base class for frame passes). They are different types in different namespaces.
|
||||
- RenderGraph::addPass takes ORenderPass (OwningPtr) — the graph owns the passes. You cannot remove a pass once added (no removePass method).
|
||||
|
||||
---
|
||||
|
||||
*Generated from a full read of the checked-out source at commit `d3ed573`. If a path has moved, `git grep` for the type name — the engine is small enough to find anything in seconds.*
|
||||
@@ -0,0 +1,75 @@
|
||||
# Scene / ECS / Components / Actors
|
||||
|
||||
> The entt-based ECS: entities, components, the scene update loop, actors, and the light/fluid/physics subsystems embedded in the scene.
|
||||
|
||||
This is a **navigation** doc: it tells you where things live, how data actually flows, and the sharp edges — so you can orient in minutes instead of hours. It complements the repository's [AGENTS.md](../../AGENTS.md) (map + rules) and the [cross-repo guide](../cross-repo.md) (engine ↔ demo contract). Everything below is grounded in the checked-out source at commit `d3ed573`.
|
||||
|
||||
## Key types & where they live
|
||||
|
||||
| Type | Defined in |
|
||||
|------|------------|
|
||||
| `Scene` | `src/Engine/Scene/Scene.h` |
|
||||
| `Entity` | `src/Engine/Actor/Entity.h` |
|
||||
| `Actor` | `src/Engine/Actor/Actor.h` |
|
||||
| `CameraActor` | `src/Engine/Actor/CameraActor.h` |
|
||||
| `DirectionalLightActor` | `src/Engine/Actor/DirectionalLightActor.h` |
|
||||
| `PointLightActor` | `src/Engine/Actor/PointLightActor.h` |
|
||||
| `StaticMeshActor` | `src/Engine/Actor/StaticMeshActor.h` |
|
||||
| `Component::Component` | `src/Engine/Component/Component.h` |
|
||||
| `Component::Transform` | `src/Engine/Component/Transform.h` |
|
||||
| `Component::Camera` | `src/Engine/Component/Camera.h` |
|
||||
| `Component::Mesh` | `src/Engine/Component/Mesh.h` |
|
||||
| `Component::Collider` | `src/Engine/Component/Collider.h` |
|
||||
| `Component::RigidBody` | `src/Engine/Component/RigidBody.h` |
|
||||
| `Component::DirectionalLight` | `src/Engine/Component/DirectionalLight.h` |
|
||||
| `Component::PointLight` | `src/Engine/Component/PointLight.h` |
|
||||
| `Component::Skybox` | `src/Engine/Component/Skybox.h` |
|
||||
| `Component::FluidGrid` | `src/Engine/Component/FluidGrid.h` |
|
||||
| `Component::TerrainTile` | `src/Engine/Component/TerrainTile.h` |
|
||||
| `Component::WaterTile` | `src/Engine/Component/WaterTile.h` |
|
||||
| `Component::ShapeBase` | `src/Engine/Component/ShapeBase.h` |
|
||||
| `Component::BoxCollider/MeshCollider/SphereCollider` | `src/Engine/Component/BoxCollider.h` |
|
||||
| `LightEnvironment` | `src/Engine/Scene/LightEnvironment.h` |
|
||||
| `FluidScene` | `src/Engine/Scene/FluidScene.h` |
|
||||
|
||||
Paths above are resolved against the actual source tree (namespace ≈ directory in this codebase). A `(search)` marker means the file contains the name but may also define others — open it and grep. `git grep` is always a fallback. The full per-file map is in **Where to look** below.
|
||||
|
||||
## Data flow / lifecycle
|
||||
|
||||
Scene (src/Engine/Scene/Scene.h) wraps an entt::registry (public member 'registry'). API: createEntity(), destroyEntity(entity), attachComponent<T>(entity, args...), accessComponent<T>(entity), view<Components...>(func) (C++20 constrained template requiring std::is_invocable_v), constructCallback<T>()/destroyCallback<T>() (entt on_construct/on_destroy hooks), getLightEnvironment(), getFluidScene(), getGraphics(), update(deltaTime), bakeLighting(). Private: OFluidScene fluidScene, OLightEnvironment lightEnv, PhysicsSystem physics, Array<Gfx::OTexture2D> lightMaps. Scene constructor takes Gfx::PGraphics. Components are plain structs registered with entt (Component.h defines the base Component struct). Actor (src/Engine/Actor/Actor.h) is an Entity wrapper — DEFINE_REF(Actor) gives PActor. CameraActor/DirectionalLightActor/PointLightActor/StaticMeshActor are convenience subclasses that attach their component in the constructor (CameraActor::getCameraComponent() returns Component::Camera&). CameraActor is the only actor that GameView uses to extract the active camera (GameView::render() iterates view<Camera,Transform> and picks the one with c.mainCamera==true). FluidScene (src/Engine/Scene/FluidScene.h) is a standalone fluid simulation scene (NOT in a Fluid/ directory — it lives in Scene/). LightEnvironment (Scene/LightEnvironment.h) manages baked lightmaps and commit(). PhysicsSystem (src/Engine/Physics/PhysicsSystem.h) is embedded in Scene and updated in Scene::update().
|
||||
|
||||
## Where to look
|
||||
|
||||
| Path | What's there |
|
||||
|------|--------------|
|
||||
| `src/Engine/Scene/Scene.h + Scene.cpp` | entt registry wrapper |
|
||||
| `src/Engine/Actor/Actor.h + Actor.cpp` | base actor |
|
||||
| `src/Engine/Actor/CameraActor.h + .cpp` | |
|
||||
| `src/Engine/Actor/DirectionalLightActor.h + .cpp` | attaches DirectionalLight component, registers with LightEnvironment |
|
||||
| `src/Engine/Actor/PointLightActor.h + .cpp` | |
|
||||
| `src/Engine/Actor/StaticMeshActor.h + .cpp` | |
|
||||
| `src/Engine/Component/Component.h` | base component struct |
|
||||
| `src/Engine/Component/Transform.h + .cpp` | position/rotation/scale, world matrix |
|
||||
| `src/Engine/Component/Camera.h` | mainCamera flag, fov, near/far, projection params |
|
||||
| `src/Engine/Component/Mesh.h` | references Graphics::Mesh asset |
|
||||
| `src/Engine/Component/ShapeBase.h + .cpp` | collision shape base, 8.9KB impl — shape serialization, mesh import |
|
||||
| `src/Engine/Component/FluidGrid.h` | fluid simulation grid component |
|
||||
| `src/Engine/Scene/FluidScene.h + .cpp` | standalone fluid sim scene, 11.5KB impl |
|
||||
| `src/Engine/Scene/LightEnvironment.h + .cpp` | baked lighting, lightmap commit |
|
||||
| `src/Engine/Physics/PhysicsSystem.h + .cpp` | embedded physics, 18.5KB impl |
|
||||
| `src/Engine/Physics/BVH.h + .cpp` | bounding volume hierarchy for collision |
|
||||
|
||||
## Gotchas & sharp edges
|
||||
|
||||
- FluidScene is at src/Engine/Scene/FluidScene.h — there is NO Fluid/ directory. Do not look for it under Engine/Fluid/.
|
||||
- Component::Mesh, Component::Collider, Component::BoxCollider, Component::MeshCollider, Component::SphereCollider exist as files but some are EMPTY (0 bytes: BoxCollider.h, MeshCollider.h, SphereCollider.h). Only ShapeBase.cpp (8.9KB) has actual collision shape logic.
|
||||
- The entt::registry is a PUBLIC member of Scene — you can access entities directly via scene.registry without going through the accessComponent/attachComponent helpers (though the helpers are the intended API).
|
||||
- GameView::render() finds the main camera by iterating ALL Camera+Transform components and checking the mainCamera boolean flag. If no component has mainCamera=true, cam/transform remain default-constructed and the render will use an identity camera.
|
||||
- Scene has NO explicit render method — rendering is driven externally by GameView::render() which calls renderGraph.render(cam, transform) directly. Scene::update() only runs ECS systems and physics.
|
||||
- bakeLighting() on Scene bakes lightmaps into the LightEnvironment; the results are committed via lightEnv->commit() in GameView::update().
|
||||
- PhysicsSystem is a VALUE member of Scene (not a pointer) — it is constructed/destroyed with the Scene.
|
||||
- DirectionalLightActor and PointLightActor register their light with the scene's LightEnvironment in their constructor — deleting the actor does NOT unregister the light from the environment (check LightEnvironment.cpp for the actual lifecycle).
|
||||
|
||||
---
|
||||
|
||||
*Generated from a full read of the checked-out source at commit `d3ed573`. If a path has moved, `git grep` for the type name — the engine is small enough to find anything in seconds.*
|
||||
@@ -0,0 +1,54 @@
|
||||
# Component Systems & the Update Loop
|
||||
|
||||
> SystemGraph, SystemBase, ComponentSystem<T>, the built-in systems, and how the frame loop drives them from GameView.
|
||||
|
||||
This is a **navigation** doc: it tells you where things live, how data actually flows, and the sharp edges — so you can orient in minutes instead of hours. It complements the repository's [AGENTS.md](../../AGENTS.md) (map + rules) and the [cross-repo guide](../cross-repo.md) (engine ↔ demo contract). Everything below is grounded in the checked-out source at commit `d3ed573`.
|
||||
|
||||
## Key types & where they live
|
||||
|
||||
| Type | Defined in |
|
||||
|------|------------|
|
||||
| `SystemBase` | `src/Engine/System/SystemBase.h` |
|
||||
| `SystemGraph` | `src/Engine/System/SystemGraph.h` |
|
||||
| `ComponentSystem<Components...>` | `git grep` in `src/` |
|
||||
| `KeyboardInput` | `src/Engine/Component/KeyboardInput.h` |
|
||||
| `FluidUpdater` | `src/Engine/System/FluidUpdater.h` |
|
||||
| `LightGather` | `src/Engine/System/LightGather.h` |
|
||||
| `MeshUpdater` | `src/Engine/System/MeshUpdater.h` |
|
||||
| `CameraUpdater` | `src/Engine/System/CameraUpdater.h` |
|
||||
| `Executor` | `src/Engine/System/Executor.h` |
|
||||
|
||||
Paths above are resolved against the actual source tree (namespace ≈ directory in this codebase). A `(search)` marker means the file contains the name but may also define others — open it and grep. `git grep` is always a fallback. The full per-file map is in **Where to look** below.
|
||||
|
||||
## Data flow / lifecycle
|
||||
|
||||
SystemGraph (src/Engine/System/SystemGraph.h + .cpp, 318B + 259B) is a list of SystemBase pointers with addSystem(OSystemBase) and run(delta). SystemBase (SystemBase.h) holds a PScene scene and virtual run(double)/update(). ComponentSystem<Components...> (ComponentSystem.h) is the template base for all data-driven systems: its run(delta) calls SystemBase::run then setupView(), which iterates the entt registry over the template's component types (plus any Deps from a has_dependencies concept) and calls the virtual update(components...) / update(entity, components...) overloads. Each concrete system (FluidUpdater, LightGather, MeshUpdater, CameraUpdater, KeyboardInput) is a ComponentSystem specialization. KeyboardInput is special — it is NOT a ComponentSystem; it is a SystemBase subclass that receives raw key/mouse/scroll callbacks from GameView and translates them into entt component modifications. GameView::reloadGame() (GameView.cpp lines 96-108) rebuilds the system graph after each game reload: creates new SystemGraph, calls gameInterface.getGame()->setupScene(scene, systemGraph) (the game DLL populates the scene and may add its own systems), then adds the built-in systems: KeyboardInput, FluidUpdater, LightGather, MeshUpdater, CameraUpdater. GameView::update() (lines 54-69) runs the frame: resets all VertexData mesh data (VertexData::getList() — a global list of registered vertex data objects), runs systemGraph->run(updateTime), calls scene->update(updateTime), then re-creates GPU descriptors for all VertexData (vd->createDescriptors()), and commits the LightEnvironment. updateTime is computed from std::chrono::high_resolution_clock deltas between frames.
|
||||
|
||||
## Where to look
|
||||
|
||||
| Path | What's there |
|
||||
|------|--------------|
|
||||
| `src/Engine/System/SystemGraph.h + SystemGraph.cpp` | |
|
||||
| `src/Engine/System/SystemBase.h` | base class, 532B |
|
||||
| `src/Engine/System/ComponentSystem.h` | template base, 1282B — full file shown above |
|
||||
| `src/Engine/System/KeyboardInput.h + .cpp` | raw input -> entt, 998B + 1442B |
|
||||
| `src/Engine/System/FluidUpdater.h + .cpp` | FluidGrid+Transform -> fluid grid update |
|
||||
| `src/Engine/System/LightGather.h + .cpp` | collects light components into LightEnvironment |
|
||||
| `src/Engine/System/MeshUpdater.h + .cpp` | updates mesh GPU data |
|
||||
| `src/Engine/System/CameraUpdater.h + .cpp` | updates camera matrices from Transform |
|
||||
| `src/Engine/System/Executor.h + .cpp` | thread pool executor, 208B + 76B — small |
|
||||
| `src/Engine/Window/GameView.cpp` | frame loop: update() lines 54-69, reloadGame() lines 96-108, render() lines 75-89 |
|
||||
|
||||
## Gotchas & sharp edges
|
||||
|
||||
- ComponentSystem::setupView has a commented-out thread pool path (lines 15-22 of ComponentSystem.h) — the parallel dispatch is stubbed. All system updates run serially on the main thread.
|
||||
- KeyboardInput is NOT a ComponentSystem — it is a plain SystemBase subclass. It does not iterate the entt registry; it receives raw input callbacks from GameView and directly mutates components (e.g. calling scene->accessComponent<Transform>(entity).position += ...).
|
||||
- The system graph is DESTROYED and REBUILT on every reloadGame() call (GameView.cpp line 99: systemGraph = new SystemGraph()). The game DLL's setupScene is the hook for custom systems.
|
||||
- VertexData::getList() is a STATIC global list (VertexData.h/.cpp, 6.4KB header + 27.5KB impl). Every VertexData instance registers itself on construction. GameView::update() iterates this list to reset mesh data before the system graph runs and to re-create GPU descriptors after. This is a side-channel that bypasses the ECS — VertexData is NOT an entt component.
|
||||
- updateTime is NOT a fixed timestep — it is the measured wall-clock delta between frames (lines 55-68 of GameView.cpp). There is no fixed-timestep accumulator in the engine.
|
||||
- FluidUpdater is a ComponentSystem<FluidGrid, Transform> — it requires both components on an entity to fire. If an entity has FluidGrid but no Transform, it is silently skipped.
|
||||
- The Executor class (Executor.h/.cpp) is a tiny thread-pool wrapper (76B impl) that is NOT used by any of the built-in systems (the parallel code in ComponentSystem is commented out). It exists for the game DLL to use.
|
||||
|
||||
---
|
||||
|
||||
*Generated from a full read of the checked-out source at commit `d3ed573`. If a path has moved, `git grep` for the type name — the engine is small enough to find anything in seconds.*
|
||||
@@ -0,0 +1,135 @@
|
||||
# UI (flexbox layout, element tree, theming)
|
||||
|
||||
> **Scope:** `src/Engine/UI/` — a from-scratch, dependency-free **flexbox** layout engine, an
|
||||
> element-tree widget system (Div/Button/Text/Panel), and a theme/style system. No ImGui, no
|
||||
> Dear ImGui — this is custom and it's the "app UI" (overlays, HUD, menus), not the 3D scene.
|
||||
|
||||
The UI is a **separate render path** from the 3D scene: it produces `UIRender` quads (colored
|
||||
rectangles + glyph quads) that are composited on top of the 3D frame. Layout is a real two-phase
|
||||
flexbox (measure → place), and the whole thing is driven incrementally — only dirty subtrees
|
||||
re-style/re-layout.
|
||||
|
||||
## Key types & where they live
|
||||
|
||||
| Type | Defined in |
|
||||
|------|------------|
|
||||
| `UI::System` | `src/Engine/UI/System.h` (impl `System.cpp`) — the per-frame driver |
|
||||
| `UI::Element` (base widget) | `src/Engine/UI/Element.h` (impl `Element.cpp`) |
|
||||
| `UI::Div<...>`, `UI::Button<...>`, `UI::Text`, `UI::Panel` | `src/Engine/UI/Element/{Div,Button,Text,Panel}.h` |
|
||||
| `UI::FlexLayout` | `src/Engine/UI/FlexLayout.h` (impl `FlexLayout.cpp`) — the layout engine |
|
||||
| `UI::Style`, `UI::Theme`, `UI::Class<...>` | `src/Engine/UI/Style/{Style,Theme,Class,Fonts}.h` |
|
||||
| `UI::Attributes` (widget callbacks/props) | `src/Engine/UI/Attributes.h` |
|
||||
| `UIRender` (a quad to draw: color rect or glyph) | `src/Engine/UI/Element.h` / `src/Engine/Graphics/` |
|
||||
| `Display`, `Direction`, `DimensionType`, `ContentDirection` | `src/Engine/UI/Style/Style.h` (enums) |
|
||||
|
||||
`DECLARE_REF(System)` exists in `UI/System.h` — `System` is ref-countable. The element tree itself
|
||||
(`OElement`/`PElement`) is also a ref-counted tree (the `DEFINE_REF(Element)` in `Element.h`).
|
||||
|
||||
## The frame pipeline (the thing to understand first)
|
||||
|
||||
`UI::System` (`UI/System.h`) runs this, **once per frame, from the owning view, before 3D layout
|
||||
matters but as part of the render path**:
|
||||
|
||||
```
|
||||
processInput() # mouse/key/scroll events → update hover/focus state
|
||||
beginFrame(viewport) # style dirty subtrees → layout (if dirty or viewport changed) → render
|
||||
├─ styleRec(root) # walk the tree; applyStyle on elements whose style is dirty
|
||||
├─ if layoutDirty → FlexLayout::layout(viewport, root)
|
||||
└─ renderElements = render() # collect UIRender quads for the compositor
|
||||
render() → Array<UIRender> # the actual quads the view blits over the 3D frame
|
||||
```
|
||||
|
||||
**Incrementality is the core design.** The tree is built once; mutations go through element setters
|
||||
(`setText`, `setChildren`, style setters) which call `markDirty()`. Only the affected subtree
|
||||
re-styles/re-lays-out. `setTheme` forces one full re-style (`markAllDirty` + `layoutDirty`).
|
||||
`lastViewport` is cached: if the viewport didn't change and nothing is dirty, layout is **skipped
|
||||
entirely** — the UI is cheap on idle frames.
|
||||
|
||||
## The flexbox engine (`FlexLayout`)
|
||||
|
||||
`UI::FlexLayout` (`UI/FlexLayout.h`) is a **genuine two-phase flexbox**:
|
||||
|
||||
- **Phase 1 — measure** (`measure`): top-down, resolves `DimensionType::Auto` sizes against
|
||||
content (text is measured via `font->shapeText`), handles `min/max` clamps, and computes the
|
||||
main/cross sizes of every node. Text measurement is the only expensive part — it's what makes
|
||||
`Text`'s `Auto` width/height work.
|
||||
- **Phase 2 — place** (`place`/`placeFlex`): walks again, assigning final `Rect` bounds. Supports
|
||||
`Direction` (row/row-reverse/column/column-reverse), **wrap**, `justify` (content alignment along
|
||||
the main axis), `align` (cross axis), **margins**, and `ContentDirection` (start/center/end).
|
||||
- It works on an internal **flat node list** (`FlexNode`) built from the element tree — the element
|
||||
`Element` carries a `FlexNode*` back-pointer, and `FlexLayout` never touches the tree's pointer
|
||||
structure directly during layout. This is what keeps layout O(n) and cache-friendly.
|
||||
|
||||
**Gotcha:** `FlexNode`/layout state is **reused between frames** (the `FlexNode*` on each
|
||||
`Element` is stable). If you add a new widget, you must make sure it produces a valid `FlexNode`
|
||||
in `applyStyle`/measurement or layout will read stale bounds. The comment block at the top of
|
||||
`System.h` documents the frame invariants — read it before touching layout.
|
||||
|
||||
## The widget set
|
||||
|
||||
The widget vocabulary is small and **explicit** — there are no "accidental" empty widgets:
|
||||
|
||||
| Widget | Base | Notes |
|
||||
|--------|------|-------|
|
||||
| `Div<classes...>` | `Element` | container. **`Div()` is deleted** — you must name style classes (`Div<MyStyles::card>`) or you can't create one. This is intentional: it forces a style/attrs choice. |
|
||||
| `Button<classes...>` | `Div<...>` | wires `onHover`/`onHoverLeave`/`onClick`/`onScroll`/`onKey`/`onFocus`/`onBlur` callbacks in `Attributes`; key-enter fires `onClick`; hover/press state is tracked and re-marked dirty on change. |
|
||||
| `Text` | `Element` | holds a string; `setText` marks dirty; resolves a **font by name** at style time (see below); renders glyph quads from `UIRender` per glyph. |
|
||||
| `Panel<classes...>` | `Div<...>` | themed convenience: `theme.color(ColorToken::Gray900)` bg, white text, `theme.spacing(8)` padding. |
|
||||
|
||||
**Styling is template-based**: `Div<classes...>` / `Button<classes...>` / `Panel<classes...>` take
|
||||
a **variadic list of style-class types** at compile time (the `Style/Class.h` machinery). `applyStyle`
|
||||
merges: theme defaults → class styles → parent inheritance → per-instance overrides. This is the
|
||||
"CSS class" model done with C++ templates instead of strings.
|
||||
|
||||
## Fonts & text — the INVARAIT (read this)
|
||||
|
||||
The `System.h` header carries an explicit invariant (verbatim from source):
|
||||
|
||||
> **INVARAIT: fonts referenced by style classes must be imported**
|
||||
> (`AssetImporter::importFont`) **before the first `style()` call.** `Text` falls back to
|
||||
> `Theme::defaultFont` and renders **empty** (with an assert in debug) otherwise.
|
||||
|
||||
- `Text::applyStyle` resolves the font **by name** via
|
||||
`AssetRegistry::findFont("", style.fontName)` — a string literal can't be a template arg, so the
|
||||
font is a *named runtime lookup*. If the name is empty it uses `Theme::defaultFont`.
|
||||
- If the named font isn't in the `AssetRegistry` at style time, the glyphs array is left **empty**
|
||||
and the text renders as a zero-size (invisible) box — **in release you get nothing, no crash**.
|
||||
This is the #1 "my UI text doesn't show" bug. **Fix: import the font before you build the tree.**
|
||||
- Fonts are `OwningPtr<Font>` / managed by the asset system — see [assets.md](asset-pipeline.md) and
|
||||
[serialization.md](core-utilities.md) for the import path.
|
||||
|
||||
## How the UI actually gets drawn (cross-subsystem)
|
||||
|
||||
`UI::System::render()` returns `Array<UIRender>`. The **owning view** (the thing that drives
|
||||
`System::beginFrame` each frame) takes that array and blits the quads **over** the 3D render graph
|
||||
output. `UIRender` is a small struct (either a filled color rect, or a glyph: font + glyph index +
|
||||
uv + rect + color). It is *not* a separate render pass in the `RenderGraph` in the same sense as
|
||||
3D passes — it's a flat quad list the view composites. If you're looking for the "UI render pass"
|
||||
in the render graph, it's this quad list, handled at the view level.
|
||||
|
||||
## Gotchas
|
||||
|
||||
- **`Div()` deleted** — always construct with a style-class template arg, or the widget won't
|
||||
compile. This is by design, not a bug.
|
||||
- **Empty text = font not imported.** No assert in release. Import fonts before first style pass.
|
||||
- **Layout state is cached and reused** — new widgets must emit a valid `FlexNode`. Stale
|
||||
`FlexNode*` = garbage bounds.
|
||||
- **`markDirty` is the only way to invalidate.** Directly mutating a `Style` field without
|
||||
`markDirty()` means the change won't be re-styled next frame. Use the setters.
|
||||
- **The UI thread is the frame thread.** All `System` methods run during the view's frame callback
|
||||
(see [window.md](window.md)). Don't call `beginFrame`/`render` from elsewhere.
|
||||
- **Templates + `classes...`** — the widget class list is a compile-time token; you can't
|
||||
"dynamically add a class" at runtime. Runtime theming goes through `setTheme` (full re-style) or
|
||||
per-instance style setters (subtree dirty), not by changing the template arg.
|
||||
|
||||
## Where to look
|
||||
|
||||
| What you're doing | Start here |
|
||||
|---|---|
|
||||
| Add a new widget | `src/Engine/UI/Element/` (copy `Panel.h` as a template) + `Element.h` base |
|
||||
| Make a style class | `src/Engine/UI/Style/Class.h` (the template machinery) |
|
||||
| Change the theme (colors/spacing/fonts) | `src/Engine/UI/Style/Theme.h` + `System::setTheme` |
|
||||
| Fix "text not rendering" | confirm font imported (`AssetImporter::importFont`) before first frame; check `Text::applyStyle` `AssetRegistry::findFont` |
|
||||
| Layout bug (wrong bounds) | `src/Engine/UI/FlexLayout.cpp` (measure then place) |
|
||||
| Add an input callback to a widget | `src/Engine/UI/Attributes.h` + the widget's `onMouseEvent`/`onKeyEvent` override |
|
||||
| Understand the frame invariants | top of `src/Engine/UI/System.h` (the comment block) |
|
||||
@@ -0,0 +1,73 @@
|
||||
# Vulkan Backend (Vulkan::Graphics)
|
||||
|
||||
> The Vulkan implementation: device/queue setup, resource creation, validation, and the capability gates for mesh shading and ray tracing.
|
||||
|
||||
This is a **navigation** doc: it tells you where things live, how data actually flows, and the sharp edges — so you can orient in minutes instead of hours. It complements the repository's [AGENTS.md](../../AGENTS.md) (map + rules) and the [cross-repo guide](../cross-repo.md) (engine ↔ demo contract). Everything below is grounded in the checked-out source at commit `d3ed573`.
|
||||
|
||||
## Key types & where they live
|
||||
|
||||
| Type | Defined in |
|
||||
|------|------------|
|
||||
| `Vulkan::Graphics` | `src/Engine/Graphics/Graphics.h` |
|
||||
| `Vulkan::Window` | `src/Engine/Graphics/Metal/Window.h` |
|
||||
| `Vulkan::Viewport` | `src/Editor/Window/ViewportControl.h` (search) |
|
||||
| `Vulkan::RenderPass` | `src/Engine/Graphics/Metal/RenderPass.h` |
|
||||
| `Vulkan::Framebuffer` | `src/Engine/Graphics/Vulkan/Framebuffer.h` |
|
||||
| `Vulkan::Buffer` | `src/Engine/Graphics/Buffer.h` |
|
||||
| `Vulkan::ShaderBuffer/UniformBuffer/VertexBuffer/IndexBuffer` | `git grep` in `src/` |
|
||||
| `Vulkan::Texture/Texture2D/2DArray/3D/Cube/TextureView/Sampler` | `src/Engine/Graphics/Metal/Texture.h` |
|
||||
| `Vulkan::Shader (all stages)` | `git grep` in `src/` |
|
||||
| `Vulkan::DescriptorLayout/DescriptorSet/PipelineLayout` | `git grep` in `src/` |
|
||||
| `Vulkan::GraphicsPipeline/ComputePipeline/RayTracingPipeline` | `git grep` in `src/` |
|
||||
| `Vulkan::CommandBuffer (RenderCommand/ComputeCommand)` | `git grep` in `src/` |
|
||||
| `Vulkan::OcclusionQuery/PipelineStatisticsQuery/TimestampQuery` | `git grep` in `src/` |
|
||||
| `Vulkan::BottomLevelAS/TopLevelAS` | `git grep` in `src/` |
|
||||
| `Vulkan::Allocator (VMA)` | `git grep` in `src/` |
|
||||
| `Vulkan::Queue` | `src/Engine/Graphics/Vulkan/Queue.h` |
|
||||
| `Vulkan::PipelineCache` | `src/Engine/Graphics/Metal/PipelineCache.h` |
|
||||
| `Vulkan::Debug (layer)` | `git grep` in `src/` |
|
||||
|
||||
Paths above are resolved against the actual source tree (namespace ≈ directory in this codebase). A `(search)` marker means the file contains the name but may also define others — open it and grep. `git grep` is always a fallback. The full per-file map is in **Where to look** below.
|
||||
|
||||
## Data flow / lifecycle
|
||||
|
||||
Vulkan::Graphics (src/Engine/Graphics/Vulkan/Graphics.h + Graphics.cpp, 10.7KB header + 52KB impl) implements Gfx::Graphics. init(GraphicsInitializer) creates the VkInstance (with validation layers when ENABLE_VALIDATION, debug callbacks via Debug.h/.cpp), VkSurface (from the OS window handle), selects a physical device + queue families (graphics/async/transfer + optional ray tracing queue), creates VkDevice with all required extensions (VK_KHR_ray_tracing_pipeline, VK_NV_mesh_shader, VK_EXT_mesh_shader, VK_KHR_acceleration_structure, VK_KHR_deferred_host_operations, VK_EXT_vertex_input_dynamic_state, VK_EXT_tooling_info, swapchain, sync2, timeline semaphore, etc.). QueueFamilyMapping records which queue index hosts graphics/async/transfer/RT work. The VkDevice is stored alongside a Vulkan::Allocator (VMA-based memory allocator, Allocator.h + Allocator.cpp, 13KB) for all buffer/texture memory. Window.cpp (18KB) handles the OS window (X11 on Linux via GLFW or raw X11, Win32 on Windows) + VkSurface + swapchain management + frame loop (acquire next image, present). Viewport is a sub-rectangle of a Window (multiple viewports can share one window). RenderPass.cpp (12KB) creates VkRenderPass + VkFramebuffer objects (Framebuffer.h + .cpp, 3.8KB) — framebuffers are per-swapchain-image. Command.cpp (26KB) implements the command buffer pool: RenderCommand and ComputeCommand wrap VkCommandBuffer, with beginRenderPass/endRenderPass, draw/drawIndexed/drawMeshTasksNV/drawMeshTasksEXT, dispatch/dispatchBase, bindPipeline/bindDescriptorSets/bindVertexBuffers/bindIndexBuffer, beginQuery/endQuery, copyBuffer/copyImage/blendImage, buildAccelerationStructure, etc. Descriptor.cpp (20KB) implements descriptor pool + layout + set allocation. PipelineCache.cpp (37KB) loads/saves VkPipelineCacheData to disk and caches VkPipeline objects keyed by a hash. RayTracing.cpp (11KB) implements BLAS/TLAS creation + building (vkCmdBuildAccelerationStructuresKHR) and the 6 RT shader stages (raygen/anyhit/closesthit/miss/intersection/callable). Query.cpp (6.5KB) implements occlusion queries (VkQueryPool + vkGetQueryPoolResults), pipeline statistics queries (VkPipelineStatisticsQuery), and timestamp queries. Texture.cpp (27KB) implements all texture types (1D/2D/3D/cube/array) with mipmap generation (vkCmdGenerateMipmaps), sampling (VkSampler), and texture views (VkImageView). Buffer.cpp (22KB) implements all buffer types with VMA allocation + vkCmdCopyBuffer for uploads. Graphics.cpp also implements: createRenderPass (full VkRenderPass creation from RenderTargetLayout + SubPassDependency array), executeCommands (submit to VkQueue with fence), waitDeviceIdle (vkDeviceWaitIdle), resolveTexture (vkCmdBlitImage), copyTexture (vkCmdCopyImage), copyBuffer (vkCmdCopyBuffer), all RT factory methods, and the capability flags (meshShadingEnabled from VK_NV_mesh_shader/VK_EXT_mesh_shader extension presence, rayTracingEnabled from VK_KHR_ray_tracing_pipeline).
|
||||
|
||||
## Where to look
|
||||
|
||||
| Path | What's there |
|
||||
|------|--------------|
|
||||
| `src/Engine/Graphics/Vulkan/Graphics.h` | 10.7KB — full Vulkan backend interface + members |
|
||||
| `src/Engine/Graphics/Vulkan/Graphics.cpp` | 52KB — device creation, all factory methods |
|
||||
| `src/Engine/Graphics/Vulkan/Window.h + .cpp` | OS window + swapchain, 18KB impl |
|
||||
| `src/Engine/Graphics/Vulkan/RenderPass.h + .cpp` | VkRenderPass + framebuffer creation |
|
||||
| `src/Engine/Graphics/Vulkan/Framebuffer.h + .cpp` | VkFramebuffer wrapper |
|
||||
| `src/Engine/Graphics/Vulkan/Command.h + .cpp` | command buffer pool, 26KB impl — all draw/dispatch/AS build commands |
|
||||
| `src/Engine/Graphics/Vulkan/Descriptor.h + .cpp` | descriptor pool/layout/set, 20KB impl |
|
||||
| `src/Engine/Graphics/Vulkan/PipelineCache.h + .cpp` | pipeline cache, 37KB impl |
|
||||
| `src/Engine/Graphics/Vulkan/RayTracing.h + .cpp` | BLAS/TLAS + RT shaders, 11KB impl |
|
||||
| `src/Engine/Graphics/Vulkan/Query.h + .cpp` | occlusion/stats/timestamp queries |
|
||||
| `src/Engine/Graphics/Vulkan/Texture.h + .cpp` | all texture types, 27KB impl |
|
||||
| `src/Engine/Graphics/Vulkan/Buffer.h + .cpp` | all buffer types + VMA, 22KB impl |
|
||||
| `src/Engine/Graphics/Vulkan/Allocator.h + .cpp` | VMA memory allocator |
|
||||
| `src/Engine/Graphics/Vulkan/Queue.h + .cpp` | VkQueue wrapper + fence |
|
||||
| `src/Engine/Graphics/Vulkan/Debug.h + .cpp` | Vulkan validation layer callbacks |
|
||||
| `src/Engine/Graphics/Vulkan/Shader.h + .cpp` | VkShaderModule creation |
|
||||
|
||||
## Gotchas & sharp edges
|
||||
|
||||
- The Vulkan backend uses VMA (Vulkan Memory Allocator) for ALL buffer and texture memory. The Allocator wraps a VmaAllocator. You cannot free memory directly — you must go through the allocator's destroy methods. VMA must be compiled and linked (it is a sub-dependency, not in the Seele source tree).
|
||||
- Ray tracing requires VK_KHR_ray_tracing_pipeline AND a physical device that exposes VK_KHR_acceleration_structure. The capability flag rayTracingEnabled is set at init() time based on device extension availability. If RT is not supported, RayTracingPass is never added to the render graph (GameView.cpp line 39: if graphics->supportRayTracing()).
|
||||
- Mesh shading (VK_NV_mesh_shader or VK_EXT_mesh_shader) is detected at init() and sets meshShadingEnabled. If false, Graphics::createGraphicsPipeline(MeshPipelineCreateInfo) will assert/fail. The Vulkan backend must have the extension enabled in VkDeviceCreateInfo.
|
||||
- The command buffer pool in Command.cpp is a per-queue-type (graphics/async/transfer) pool of VkCommandBuffer objects. Each RenderCommand/ComputeCommand checks out a buffer, records, and checks back in. The pool is sized at init() based on the max in-flight frames. If the pool is exhausted, the backend will stall.
|
||||
- Framebuffer creation is PER SWAPCHAIN IMAGE — each VkFramebuffer in Framebuffer.cpp corresponds to one swapchain image. The RenderPass::createRenderPass method creates one framebuffer per image. If the swapchain is resized, all framebuffers are destroyed and recreated (applyArea path).
|
||||
- The Vulkan backend does NOT use the Vulkan Validation Layer in release builds — ENABLE_VALIDATION in Graphics.h (line 7) is a compile-time define that is always on in this codebase. In production you would want to #undef it or make it a build flag.
|
||||
- Queue.cpp wraps a single VkQueue + VkFence. There is ONE fence per queue. waitDeviceIdle() calls vkDeviceWaitIdle on the entire device (all queues). There is no per-queue synchronization primitive exposed through the Gfx::Graphics interface — the backend manages fences internally.
|
||||
- The debug layer (Debug.h/.cpp) installs VK_EXT_debug_utils callbacks at device creation time. All validation layer messages are routed through a single callback that forwards to stderr. There is no UI for viewing validation errors — they go to the console.
|
||||
- Texture.cpp handles mipmap generation via vkCmdGenerateMipmaps. For texture arrays and cubes, the entire array/cube is generated in one call. The texture's initial layout must be TRANSFER_DST_OPTIMAL for this to work — the Texture constructor sets the correct initial layout based on the usage flags in TextureCreateInfo.
|
||||
- The Vulkan backend's Window.cpp handles BOTH X11 (Linux) and Win32 (Windows) natively. On Linux it uses GLFW for window creation + X11 for the surface (glfwCreateWindow + glfwGetX11Window). On Windows it uses Win32 directly (CreateWindow + CreateSwapChainHcu). There is no platform abstraction layer — the #ifdef WIN32 blocks are in the source.
|
||||
- PipelineCache.cpp uses a hash of the pipeline create-info struct + shader SPIR-V bytes as the cache key. If ANY field of the create-info changes (even a padding byte), the cache miss occurs. The cache file is stored next to the executable (or in a user-specified path from GraphicsInitializer).
|
||||
|
||||
---
|
||||
|
||||
*Generated from a full read of the checked-out source at commit `d3ed573`. If a path has moved, `git grep` for the type name — the engine is small enough to find anything in seconds.*
|
||||
@@ -0,0 +1,94 @@
|
||||
# Window & view layer (Window, View, GameView, WindowManager)
|
||||
|
||||
> **Scope:** `src/Engine/Window/` (4 files), `src/Engine/View/` — the OS window + the per-frame
|
||||
> render/update protocol that the whole engine hangs off. This is the "front door" of the frame loop.
|
||||
|
||||
This is the **thinnest** layer of the engine, and the single most important thing to understand for
|
||||
getting a frame to render. Everything else (render graph, systems, UI, physics) is driven from the
|
||||
protocol defined here.
|
||||
|
||||
## Key types & where they live
|
||||
|
||||
| Type | Defined in |
|
||||
|------|------------|
|
||||
| `Window` | `src/Engine/Window/Window.h` (impl `Window.cpp`) |
|
||||
| `WindowManager` | `src/Engine/Window/WindowManager.h` |
|
||||
| `View` | `src/Engine/Window/View.h` (impl `View.cpp`) |
|
||||
| `GameView` | `src/Engine/Window/GameView.h` (impl `GameView.cpp`) — the concrete `View` that drives the render graph |
|
||||
| `WindowCreateInfo` | `src/Engine/Window/Window.h` (the `Window` ctor parameter) |
|
||||
| `Area` / `URect` | `src/Engine/Containers/` + `src/Engine/Math/` (geometry types) |
|
||||
| `InputAction`, `KeyCode`, `MouseButton`, `KeyModifier` | `src/Engine/Platform/` (input enums, see Platform doc) |
|
||||
| `Game` | `src/Engine/Game.h` — the thing `GameView` wraps |
|
||||
|
||||
## The render/update protocol — the frame contract
|
||||
|
||||
`View` (`src/Engine/Window/View.h:9`) defines the **per-frame protocol** that `Window` calls in a
|
||||
fixed order. This is the spine of the whole engine; every system's `update`/`prepare`/`render` slot
|
||||
lands on one of these callbacks:
|
||||
|
||||
| # | Callback | When | What lands here |
|
||||
|---|----------|------|-----------------|
|
||||
| 1 | `beginUpdate()` | before update | pre-frame setup (e.g. reset accumulators) |
|
||||
| 2 | `update()` | the update tick | **all `System::update` calls** (in SystemGraph topological order) |
|
||||
| 3 | `commitUpdate()` | after update | commit the updated world state (meshlets, transforms) to GPU |
|
||||
| 4 | `prepareRender()` | before render | **all `System::prepare` calls** (record command buffers, build render graph) |
|
||||
| 5 | `render()` | the render tick | **all `System::render` calls** (submit passes to the graphics backend) |
|
||||
| 6 | `applyArea(URect)` | on resize | resize swapchain / viewport |
|
||||
|
||||
Input callbacks on the same protocol (fired by the OS window, routed to `View` and on to
|
||||
`GameView` → `Game`/UI):
|
||||
|
||||
- `keyCallback(KeyCode, InputAction, uint32_t modifier)`
|
||||
- `mouseMoveCallback(double x, double y)`, `mouseButtonCallback(MouseButton, InputAction, uint32_t, ...)`
|
||||
- `scrollCallback(double, double)`, `fileCallback(int, const char** paths)` (drop/open files)
|
||||
|
||||
**The golden rule (from AGENTS.md, and it holds):** a system's `update` writes CPU-side state; a
|
||||
system's `prepare`/`render` (and `commitUpdate`) is what touches the GPU. The split between phases is
|
||||
what makes the `SystemGraph` ordering meaningful — do not move GPU work into `update`.
|
||||
|
||||
## How a frame actually flows (concrete)
|
||||
|
||||
```
|
||||
Window::render() (Window.cpp)
|
||||
└─ for each window:
|
||||
view->beginUpdate(); view->update(); view->commitUpdate();
|
||||
view->prepareRender(); view->render();
|
||||
GameView (the View impl)
|
||||
└─ update() → runs SystemGraph (topo order): each System::update(registry, scene)
|
||||
└─ commitUpdate()→ MeshUpdater / FluidUpdater commit meshlet & state changes
|
||||
└─ prepareRender()→ each System::prepare → RenderGraph records passes
|
||||
└─ render() → RenderGraph::execute → Gfx::Graphics submit (Vulkan/Metal)
|
||||
```
|
||||
|
||||
- `WindowManager` (`WindowManager.h`) owns `Array<PWindow>` and a `Gfx::PGraphics`; `addWindow`
|
||||
creates a `Window` (per-OS native surface), `render()` drives the loop, `notifyWindowClosed`
|
||||
handles teardown, `isActive()` is the "should the process keep running" check.
|
||||
- `GameView` is the `View` that a `Game` (the demo's `MeshShadingDemoGame`) produces. It owns the
|
||||
`PSystemGraph` and the `Scene`, and is the **live consumer** of the `Game` protocol
|
||||
(see the [Game interface](game-interface.md) doc and [cross-repo.md](../cross-repo.md)).
|
||||
|
||||
## Gotchas
|
||||
|
||||
- **`applyArea` on resize is the only legal place to resize the swapchain.** Do not create new
|
||||
swapchains inside `render`/`prepareRender`; route through `applyArea` so the render graph's
|
||||
`ResourceHandle`s (which encode the old surface) are invalidated consistently. The render graph
|
||||
auto-invalidation (see [render-graph-and-passes.md](render-graph-and-passes.md)) depends on this.
|
||||
- **`View` is a friend of `Window`** (`friend class Window;` in `View.h`) — the window reaches into
|
||||
the view's internals directly. Do not assume the `View` API is the only way state changes.
|
||||
- **Input callbacks are delivered on the window thread.** If you add UI or a system that consumes
|
||||
input, it must be safe to be called from the frame callback path (i.e. during `update`), not from
|
||||
another thread.
|
||||
- **`Window` is per-OS but `View`/`GameView` are cross-OS.** The OS-specific bits (surface creation,
|
||||
event pump) are isolated in `Window`/the platform layer; the render protocol above is portable.
|
||||
When you touch a platform bug, you almost always want `Window.cpp` + the Platform layer, *not*
|
||||
`GameView`.
|
||||
|
||||
## Where to look
|
||||
|
||||
| What you're doing | Start here |
|
||||
|---|---|
|
||||
| Add a new per-frame phase / change frame order | `src/Engine/Window/View.h` (protocol) + `Window.cpp` (caller) |
|
||||
| Wire a `Game` into the render graph | `src/Engine/Window/GameView.cpp` (the live consumer) + `src/Engine/Game.h` |
|
||||
| Resize / multi-window | `src/Engine/Window/Window.h` `applyArea` + `WindowManager.h` |
|
||||
| Input (mouse/keys/scroll/files) | `src/Engine/Window/View.h` callbacks → `GameView.cpp` → `Game`/UI |
|
||||
| "Why does nothing render after my change" | confirm you didn't move GPU work into `update`; check `GameView.cpp` `prepareRender`/`render` |
|
||||
Vendored
+1
-1
Submodule external/vcpkg updated: cb2981c4e0...e456309491.
+83
-2
@@ -2,6 +2,25 @@ import sys
|
||||
sys.path.insert(0, '/usr/share/gdb/python/')
|
||||
import gdb.printing
|
||||
|
||||
|
||||
def _base_cast(val):
|
||||
for field in val.type.strip_typedefs().fields():
|
||||
if getattr(field, 'is_base_class', False):
|
||||
return val.cast(field.type)
|
||||
return None
|
||||
|
||||
|
||||
def _member(val, name):
|
||||
"""Find a member by name on a value, searching base classes if needed."""
|
||||
current = val
|
||||
while current is not None:
|
||||
t = current.type.strip_typedefs()
|
||||
for field in t.fields():
|
||||
if field.name == name:
|
||||
return current[name]
|
||||
current = _base_cast(current)
|
||||
raise gdb.error(f"Member '{name}' not found on {val.type}")
|
||||
|
||||
class ArrayPrinter:
|
||||
def __init__(self, val):
|
||||
self.val = val
|
||||
@@ -13,8 +32,8 @@ class ArrayPrinter:
|
||||
data = self.val['_data']
|
||||
size = int(self.val['arraySize'])
|
||||
allocated = int(self.val['allocated'])
|
||||
#yield f"[size]", size
|
||||
#yield f"[allocated]", allocated
|
||||
yield f"[size]", size
|
||||
yield f"[allocated]", allocated
|
||||
for i in range(size):
|
||||
elem_val = (data + i).dereference()
|
||||
yield f"[{i}]", elem_val
|
||||
@@ -22,6 +41,66 @@ class ArrayPrinter:
|
||||
def display_hint(self):
|
||||
return "array"
|
||||
|
||||
|
||||
class ListPrinter:
|
||||
def __init__(self, val):
|
||||
self.val = val
|
||||
|
||||
def to_string(self):
|
||||
size = int(_member(self.val, '_size'))
|
||||
return f"List(size={size})"
|
||||
|
||||
def children(self):
|
||||
size = int(_member(self.val, '_size'))
|
||||
root = _member(self.val, 'root')
|
||||
tail = _member(self.val, 'tail')
|
||||
yield "[size]", size
|
||||
|
||||
node = root
|
||||
idx = 0
|
||||
# Bound traversal by logical size to avoid walking corrupted links forever.
|
||||
while idx < size and node != tail:
|
||||
yield f"[{idx}]", node['data']
|
||||
node = node['next']
|
||||
idx += 1
|
||||
|
||||
def display_hint(self):
|
||||
return "array"
|
||||
|
||||
|
||||
class MapPrinter:
|
||||
def __init__(self, val):
|
||||
self.val = val
|
||||
|
||||
def to_string(self):
|
||||
size = int(_member(self.val, '_size'))
|
||||
return f"Map(size={size})"
|
||||
|
||||
def children(self):
|
||||
size = int(_member(self.val, '_size'))
|
||||
root = _member(self.val, 'root')
|
||||
|
||||
stack = []
|
||||
node = root
|
||||
idx = 0
|
||||
|
||||
# In-order traversal of Tree nodes yields map entries sorted by key.
|
||||
while (node or stack) and idx < size:
|
||||
while node:
|
||||
stack.append(node)
|
||||
node = node['leftChild']
|
||||
|
||||
node = stack.pop()
|
||||
pair = node['data']
|
||||
yield f"[{idx}].key", pair['key']
|
||||
yield f"[{idx}].value", pair['value']
|
||||
idx += 1
|
||||
node = node['rightChild']
|
||||
|
||||
def display_hint(self):
|
||||
return "map"
|
||||
|
||||
|
||||
class VectorPrinter:
|
||||
def __init__(self, val):
|
||||
self.val = val
|
||||
@@ -53,6 +132,8 @@ class VectorPrinter:
|
||||
def build_pretty_printer():
|
||||
pp = gdb.printing.RegexpCollectionPrettyPrinter("Seele")
|
||||
pp.add_printer("Array", r'^Seele::Array<.*>$', ArrayPrinter)
|
||||
pp.add_printer("List", r'^Seele::List<.*>$', ListPrinter)
|
||||
pp.add_printer("Map", r'^Seele::Map<.*>$', MapPrinter)
|
||||
pp.add_printer("Vector", r"^glm::(detail::)?t?vec(\d)?<[^<>]*>$", VectorPrinter)
|
||||
return pp
|
||||
|
||||
|
||||
@@ -1,5 +1,27 @@
|
||||
import lldb
|
||||
|
||||
def _member(valobj, name):
|
||||
# GetChildMemberWithName does not search base classes reliably across
|
||||
# LLDB versions; walk base classes explicitly, mirroring the working
|
||||
# gdb _base_cast/_member in Seele.py.
|
||||
child = valobj.GetChildMemberWithName(name)
|
||||
if child.IsValid():
|
||||
return child
|
||||
t = valobj.GetType()
|
||||
seen = set()
|
||||
while t.IsValid() and t not in seen:
|
||||
seen.add(t)
|
||||
for i in range(t.GetNumBases()):
|
||||
base = t.GetBaseClass(i)
|
||||
if base.IsValid():
|
||||
sub = valobj.GetBaseClassWithName(base.GetName())
|
||||
if sub.IsValid():
|
||||
child = sub.GetChildMemberWithName(name)
|
||||
if child.IsValid():
|
||||
return child
|
||||
t = t.GetBaseClass(0) if t.GetNumBases() > 0 else None
|
||||
return None
|
||||
|
||||
def Array_SummaryProvider(valobj, internal_dict):
|
||||
size = valobj.GetChildMemberWithName('arraySize').GetValueAsUnsigned(0)
|
||||
return f"Array(size={size})"
|
||||
@@ -31,6 +53,194 @@ class ArraySyntheticProvider:
|
||||
def has_children(self):
|
||||
return True
|
||||
|
||||
def List_SummaryProvider(valobj, internal_dict):
|
||||
size = valobj.GetChildMemberWithName('_size').GetValueAsUnsigned(0)
|
||||
return f"List(size={size})"
|
||||
|
||||
class ListSyntheticProvider:
|
||||
def __init__(self, valobj, internal_dict):
|
||||
self.valobj = valobj
|
||||
self.update()
|
||||
|
||||
def num_children(self):
|
||||
return self.size
|
||||
|
||||
def get_child_index(self, name):
|
||||
try:
|
||||
return int(name.lstrip('[').rstrip(']'))
|
||||
except:
|
||||
return -1
|
||||
|
||||
def get_child_at_index(self, index):
|
||||
if index < 0 or index >= self.size:
|
||||
return None
|
||||
current = self.root
|
||||
for i in range(index):
|
||||
current = current.GetChildMemberWithName('next')
|
||||
return current.GetChildMemberWithName('data')
|
||||
|
||||
def update(self):
|
||||
self.root = self.valobj.GetChildMemberWithName('root')
|
||||
self.size = self.valobj.GetChildMemberWithName('_size').GetValueAsUnsigned(0)
|
||||
|
||||
def has_children(self):
|
||||
return True
|
||||
|
||||
def Tree_SummaryProvider(valobj, internal_dict):
|
||||
size = _member(valobj, '_size')
|
||||
return f"Tree(size={size.GetValueAsUnsigned(0) if size and size.IsValid() else '?'})"
|
||||
|
||||
class TreeSyntheticProvider:
|
||||
def __init__(self, valobj, internal_dict):
|
||||
self.valobj = valobj
|
||||
self.update()
|
||||
|
||||
def num_children(self):
|
||||
return self.size
|
||||
|
||||
def get_child_index(self, name):
|
||||
try:
|
||||
return int(name.lstrip('[').rstrip(']'))
|
||||
except:
|
||||
return -1
|
||||
|
||||
def get_child_at_index(self, index):
|
||||
if index < 0 or index >= self.size:
|
||||
return None
|
||||
# Collect all nodes via in-order traversal, then return the one at `index`
|
||||
nodes = []
|
||||
if self.root and self.root.IsValid():
|
||||
self._collect(self.root, nodes)
|
||||
if index >= len(nodes):
|
||||
return None
|
||||
data = nodes[index].GetChildMemberWithName('data')
|
||||
return data if data.IsValid() else None
|
||||
|
||||
def _collect(self, node, out):
|
||||
if not node.IsValid():
|
||||
return
|
||||
left = node.GetChildMemberWithName('leftChild')
|
||||
if left.IsValid():
|
||||
self._collect(left.Dereference(), out)
|
||||
out.append(node)
|
||||
right = node.GetChildMemberWithName('rightChild')
|
||||
if right.IsValid():
|
||||
self._collect(right.Dereference(), out)
|
||||
|
||||
def update(self):
|
||||
self.root = _member(self.valobj, 'root')
|
||||
size = _member(self.valobj, '_size')
|
||||
self.size = size.GetValueAsUnsigned(0) if size and size.IsValid() else 0
|
||||
|
||||
def has_children(self):
|
||||
return self.size > 0
|
||||
|
||||
def Set_SummaryProvider(valobj, internal_dict):
|
||||
size = _member(valobj, '_size')
|
||||
return f"Set(size={size.GetValueAsUnsigned(0) if size and size.IsValid() else '?'})"
|
||||
|
||||
class SetSyntheticProvider:
|
||||
def __init__(self, valobj, internal_dict):
|
||||
self.valobj = valobj
|
||||
self.update()
|
||||
|
||||
def num_children(self):
|
||||
return self.size
|
||||
|
||||
def get_child_index(self, name):
|
||||
try:
|
||||
return int(name.lstrip('[').rstrip(']'))
|
||||
except:
|
||||
return -1
|
||||
|
||||
def get_child_at_index(self, index):
|
||||
if index < 0 or index >= self.size:
|
||||
return None
|
||||
nodes = []
|
||||
# Start from pseudoRoot: the splay tree's actual structure is
|
||||
# connected via pseudoRoot.leftChild, not the `root` pointer.
|
||||
if self.pseudoRoot and self.pseudoRoot.IsValid():
|
||||
left = self.pseudoRoot.GetChildMemberWithName('leftChild')
|
||||
if left.IsValid():
|
||||
self._collect(left.Dereference(), nodes)
|
||||
if index >= len(nodes):
|
||||
return None
|
||||
data = nodes[index].GetChildMemberWithName('data')
|
||||
return data if data.IsValid() else None
|
||||
|
||||
def _collect(self, node, out):
|
||||
if not node.IsValid():
|
||||
return
|
||||
left = node.GetChildMemberWithName('leftChild')
|
||||
if left.IsValid():
|
||||
self._collect(left.Dereference(), out)
|
||||
out.append(node)
|
||||
right = node.GetChildMemberWithName('rightChild')
|
||||
if right.IsValid():
|
||||
self._collect(right.Dereference(), out)
|
||||
|
||||
def update(self):
|
||||
self.pseudoRoot = _member(self.valobj, 'pseudoRoot')
|
||||
size = _member(self.valobj, '_size')
|
||||
self.size = size.GetValueAsUnsigned(0) if size and size.IsValid() else 0
|
||||
|
||||
def has_children(self):
|
||||
return self.size > 0
|
||||
|
||||
def Map_SummaryProvider(valobj, internal_dict):
|
||||
size = _member(valobj, '_size')
|
||||
return f"Map(size={size.GetValueAsUnsigned(0) if size and size.IsValid() else '?'})"
|
||||
|
||||
class MapSyntheticProvider:
|
||||
def __init__(self, valobj, internal_dict):
|
||||
self.valobj = valobj
|
||||
self.update()
|
||||
|
||||
def num_children(self):
|
||||
return self.size
|
||||
|
||||
def get_child_index(self, name):
|
||||
try:
|
||||
return int(name.lstrip('[').rstrip(']'))
|
||||
except:
|
||||
return -1
|
||||
|
||||
def get_child_at_index(self, index):
|
||||
if index < 0 or index >= self.size:
|
||||
return None
|
||||
nodes = []
|
||||
# Start from pseudoRoot: the splay tree's actual structure is
|
||||
# connected via pseudoRoot.leftChild, not the `root` pointer.
|
||||
if self.pseudoRoot and self.pseudoRoot.IsValid():
|
||||
left = self.pseudoRoot.GetChildMemberWithName('leftChild')
|
||||
if left.IsValid():
|
||||
self._collect(left.Dereference(), nodes)
|
||||
if index >= len(nodes):
|
||||
return None
|
||||
# Map stores Pair<K, V> in node.data; return the pair so the
|
||||
# debugger can show key/value members (Pair is a plain struct).
|
||||
data = nodes[index].GetChildMemberWithName('data')
|
||||
return data if data.IsValid() else None
|
||||
|
||||
def _collect(self, node, out):
|
||||
if not node.IsValid():
|
||||
return
|
||||
left = node.GetChildMemberWithName('leftChild')
|
||||
if left.IsValid():
|
||||
self._collect(left.Dereference(), out)
|
||||
out.append(node)
|
||||
right = node.GetChildMemberWithName('rightChild')
|
||||
if right.IsValid():
|
||||
self._collect(right.Dereference(), out)
|
||||
|
||||
def update(self):
|
||||
self.pseudoRoot = _member(self.valobj, 'pseudoRoot')
|
||||
size = _member(self.valobj, '_size')
|
||||
self.size = size.GetValueAsUnsigned(0) if size and size.IsValid() else 0
|
||||
|
||||
def has_children(self):
|
||||
return self.size > 0
|
||||
|
||||
def Vector_SummaryProvider(valobj, internal_dict):
|
||||
# Get the template parameters to determine vector length
|
||||
type_name = valobj.GetTypeName()
|
||||
@@ -56,6 +266,18 @@ def __lldb_init_module(debugger, internal_dict):
|
||||
debugger.HandleCommand('type summary add -F Seele_lldb.Array_SummaryProvider -x "^Seele::Array<.*>$"')
|
||||
debugger.HandleCommand('type synthetic add -l Seele_lldb.ArraySyntheticProvider -x "^Seele::Array<.*>$"')
|
||||
|
||||
# Register List formatter
|
||||
debugger.HandleCommand('type summary add -F Seele_lldb.List_SummaryProvider -x "^Seele::List<.*>$"')
|
||||
debugger.HandleCommand('type synthetic add -l Seele_lldb.ListSyntheticProvider -x "^Seele::List<.*>$"')
|
||||
|
||||
# Register Set formatter
|
||||
debugger.HandleCommand('type summary add -F Seele_lldb.Set_SummaryProvider -x "^Seele::Set<.*>$"')
|
||||
debugger.HandleCommand('type synthetic add -l Seele_lldb.SetSyntheticProvider -x "^Seele::Set<.*>$"')
|
||||
|
||||
# Register Map formatter
|
||||
debugger.HandleCommand('type summary add -F Seele_lldb.Map_SummaryProvider -x "^Seele::Map<.*>$"')
|
||||
debugger.HandleCommand('type synthetic add -l Seele_lldb.MapSyntheticProvider -x "^Seele::Map<.*>$"')
|
||||
|
||||
# Register Vector formatter
|
||||
debugger.HandleCommand('type summary add -F Seele_lldb.Vector_SummaryProvider -x "^glm::(detail::)?t?vec[234]?<.*>$"')
|
||||
|
||||
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
fonts/
|
||||
@@ -1,65 +0,0 @@
|
||||
import Common;
|
||||
|
||||
struct VertexInput
|
||||
{
|
||||
uint vertexId : SV_VertexID;
|
||||
uint instanceId : SV_InstanceID;
|
||||
};
|
||||
|
||||
struct VertexOutput
|
||||
{
|
||||
float4 position : SV_Position;
|
||||
float2 texCoords : TEXCOORD;
|
||||
uint glyphIndex : GLYPHINDEX;
|
||||
};
|
||||
|
||||
struct GlyphInstanceData
|
||||
{
|
||||
float x;
|
||||
float y;
|
||||
float z;
|
||||
float width;
|
||||
float height;
|
||||
uint glyphIndex;
|
||||
};
|
||||
struct TextData
|
||||
{
|
||||
StructuredBuffer<GlyphInstanceData> glyphs;
|
||||
SamplerState glyphSampler;
|
||||
Texture2D<float> glyphTextures[];
|
||||
};
|
||||
ParameterBlock<TextData> pText;
|
||||
|
||||
|
||||
[shader("vertex")]
|
||||
VertexOutput vertexMain(VertexInput input)
|
||||
{
|
||||
float xpos = pText.glyphs[input.instanceId].x;
|
||||
float ypos = pText.glyphs[input.instanceId].y;
|
||||
|
||||
float w = pText.glyphs[input.instanceId].width;
|
||||
float h = pText.glyphs[input.instanceId].height;
|
||||
|
||||
const float4 coordinates[4] = {
|
||||
float4(xpos, ypos, 0, 0),
|
||||
float4(xpos, ypos + h, 0, 1),
|
||||
float4(xpos + w, ypos, 1, 0),
|
||||
float4(xpos + w, ypos + h, 1, 1),
|
||||
};
|
||||
float4 vertex = coordinates[input.vertexId];
|
||||
VertexOutput output;
|
||||
output.texCoords = vertex.zw;
|
||||
output.position = mul(pViewParams.projectionMatrix, float4(vertex.xy, pText.glyphs[input.instanceId].z-1, 1));
|
||||
output.glyphIndex = pText.glyphs[input.instanceId].glyphIndex;
|
||||
return output;
|
||||
}
|
||||
|
||||
[shader("fragment")]
|
||||
float4 fragmentMain(
|
||||
float4 position : SV_Position,
|
||||
float2 texCoords : TEXCOORD,
|
||||
uint glyphIndex : GLYPHINDEX
|
||||
) : SV_Target
|
||||
{
|
||||
return float4(0,0,0,pText.glyphTextures[glyphIndex].Sample(pText.glyphSampler, texCoords));
|
||||
}
|
||||
+45
-13
@@ -1,5 +1,10 @@
|
||||
import Common;
|
||||
|
||||
// Per-quad render data, read from the EXISTING pParams.elements storage buffer (bound on the
|
||||
// CPU side by UIPass as SE_DESCRIPTOR_TYPE_STORAGE_BUFFER). We read it here as a plain SSBO so
|
||||
// every value (x/y/w/h, color, opacity, uvOffset/uvSize, textureIndex) is EXACT — not barycentric
|
||||
// interpolated the way the old code passed it as a STYLE vertex attribute (which corrupted the
|
||||
// transparency and shifted glyphs).
|
||||
struct RenderElementStyle
|
||||
{
|
||||
float x;
|
||||
@@ -10,28 +15,33 @@ struct RenderElementStyle
|
||||
float opacity;
|
||||
float z;
|
||||
uint textureIndex;
|
||||
uint pad0;
|
||||
uint pad1;
|
||||
float2 uvOffset;
|
||||
float2 uvSize;
|
||||
};
|
||||
|
||||
struct UIParameter
|
||||
{
|
||||
StructuredBuffer<RenderElementStyle> elements;
|
||||
SamplerState sampler;
|
||||
Texture2D textures[];
|
||||
StructuredBuffer<RenderElementStyle> elements;
|
||||
Texture2D textures[]; // must be last (unsized)
|
||||
};
|
||||
|
||||
ParameterBlock<UIParameter> pParams;
|
||||
|
||||
// Varyings carry only per-fragment continuous data (the corner uv in quad-local space) + the
|
||||
// per-quad instance id (uint, not interpolated — exact per fragment). Position is SV_Position.
|
||||
// Everything else comes from the non-interpolated pParams SSBO.
|
||||
struct VertexOutput
|
||||
{
|
||||
float4 position : SV_Position;
|
||||
float2 texCoords : TEXCOORD;
|
||||
RenderElementStyle style : STYLE;
|
||||
uint instanceId : INSTANCENUM;
|
||||
};
|
||||
|
||||
[shader("vertex")]
|
||||
VertexOutput vertexMain(uint vertexId : SV_VertexID, uint instanceId: SV_InstanceID)
|
||||
VertexOutput vertexMain(uint vertexId : SV_VertexID, uint instanceId : SV_InstanceID)
|
||||
{
|
||||
// Read the per-quad rect from the non-interpolated SSBO (exact values).
|
||||
RenderElementStyle style = pParams.elements[instanceId];
|
||||
float xMin = style.x;
|
||||
float xMax = xMin + style.w;
|
||||
@@ -44,20 +54,42 @@ VertexOutput vertexMain(uint vertexId : SV_VertexID, uint instanceId: SV_Instanc
|
||||
float4(xMax, yMax, 1, 1)
|
||||
};
|
||||
VertexOutput output;
|
||||
output.position = mul(pViewParams.projectionMatrix, float4(coordinates[vertexId].xy, style.z-1, 1));
|
||||
output.texCoords = coordinates[vertexId].zw;
|
||||
output.style = style;
|
||||
// 2D ortho screen->NDC (screen is top-left / y-down; NDC is bottom-left / y-up):
|
||||
// ndcX = (x / W) * 2 - 1
|
||||
// ndcY = 1 - (y / H) * 2
|
||||
float2 ndc = float2(
|
||||
coordinates[vertexId].x * pViewParams.invScreenDimensions.x * 2.0 - 1.0,
|
||||
1.0 - coordinates[vertexId].y * pViewParams.invScreenDimensions.y * 2.0
|
||||
);
|
||||
// style.z is ALREADY the final depth: the CPU maps the tree depth (render.level) into [0,1]
|
||||
// and REVERSES it for the depth buffer's SE_COMPARE_OP_GREATER (nearer = LARGER). Write it
|
||||
// verbatim — do NOT negate it again (the old `1 - style.z` double-inverted the depth).
|
||||
output.position = float4(ndc, style.z, 1.0);
|
||||
output.texCoords = coordinates[vertexId].zw; // quad-local uv, interpolated per-fragment
|
||||
output.instanceId = instanceId; // uint varying: exact per-fragment (not interpolated)
|
||||
return output;
|
||||
}
|
||||
|
||||
[shader("fragment")]
|
||||
float4 fragmentMain(
|
||||
float2 texCoords : TEXCOORD,
|
||||
RenderElementStyle style : STYLE
|
||||
uint instanceId : INSTANCENUM
|
||||
) : SV_Target
|
||||
{
|
||||
if(style.textureIndex == -1) {
|
||||
// Re-read the per-quad data from the non-interpolated SSBO: exact uvOffset/uvSize, exact
|
||||
// color, exact opacity. (Interpolating these as vertex attributes corrupted transparency
|
||||
// and shifted the sampling — the bug the old STYLE-attribute code had.)
|
||||
RenderElementStyle style = pParams.elements[instanceId];
|
||||
if(style.textureIndex == 4294967295u) {
|
||||
// untextured quad (solid background)
|
||||
return float4(style.color, style.opacity);
|
||||
}
|
||||
return pParams.textures[style.textureIndex].Sample(pParams.sampler, texCoords.xy);
|
||||
}
|
||||
// Textured quad (glyph): the texture is the font atlas (R8_UNORM, coverage in R, A baked
|
||||
// to 1.0). Sampled as float4 that gives (R=coverage, G=0, B=0, A=1) — the alpha we want is
|
||||
// .r, not .a. Output pure text color + coverage as alpha; the pipeline's SRC_ALPHA blend
|
||||
// applies the coverage exactly once (do NOT premultiply or it'd be squared).
|
||||
float2 uv = style.uvOffset + texCoords * style.uvSize;
|
||||
float4 tex = pParams.textures[style.textureIndex].Sample(pParams.sampler, uv);
|
||||
float coverage = tex.r;
|
||||
return float4(style.color, coverage * style.opacity);
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import FluidGridData;
|
||||
|
||||
struct Params
|
||||
{
|
||||
// read-write: phi to add source to
|
||||
FluidGridData<float> phi;
|
||||
FluidGridData<float> density;
|
||||
};
|
||||
ParameterBlock<Params> params;
|
||||
|
||||
[shader("compute")]
|
||||
[numthreads(32, 8, 1)]
|
||||
void addSource(uint3 dispatchThreadID : SV_DispatchThreadID)
|
||||
{
|
||||
FluidGridData<float> phi = params.phi;
|
||||
FluidGridData<float> density = params.density;
|
||||
int x = dispatchThreadID.x + 1;
|
||||
int y = dispatchThreadID.y + 1;
|
||||
int z = dispatchThreadID.z + 1;
|
||||
if(x >= gridParams.gridSize.x - 1 || y >= gridParams.gridSize.y - 1 || z >= gridParams.gridSize.z - 1) return;
|
||||
|
||||
// Add a spherical source and union it into the existing level set.
|
||||
float3 center = float3(gridParams.gridSize) * 0.5f;
|
||||
float radius = min(gridParams.gridSize.x, min(gridParams.gridSize.y, gridParams.gridSize.z)) * 0.25f;
|
||||
float3 pos = float3(x, y, z);
|
||||
float dist = length(pos - center);
|
||||
float sourcePhi = dist - radius;
|
||||
phi[x, y, z] = min(phi[x, y, z], sourcePhi);
|
||||
|
||||
if (sourcePhi < 0.0f)
|
||||
{
|
||||
density[x, y, z] += 0.5f;
|
||||
density[x, y, z] = min(density[x, y, z], 1.0f);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import FluidGridData;
|
||||
|
||||
struct Params
|
||||
{
|
||||
// read-write
|
||||
FluidGridData<float> density;
|
||||
// read-only
|
||||
FluidGridData<float> density0;
|
||||
// read-only
|
||||
FluidGridData<float> velocityX;
|
||||
// read-only
|
||||
FluidGridData<float> velocityY;
|
||||
// read-only
|
||||
FluidGridData<float> velocityZ;
|
||||
float dt;
|
||||
};
|
||||
ParameterBlock<Params> params;
|
||||
|
||||
[shader("compute")]
|
||||
[numthreads(32, 8, 1)]
|
||||
void advect(uint3 dispatchThreadID : SV_DispatchThreadID)
|
||||
{
|
||||
FluidGridData<float> density = params.density;
|
||||
FluidGridData<float> density0 = params.density0;
|
||||
FluidGridData<float> velocityX = params.velocityX;
|
||||
FluidGridData<float> velocityY = params.velocityY;
|
||||
FluidGridData<float> velocityZ = params.velocityZ;
|
||||
float dt = params.dt;
|
||||
|
||||
int x = dispatchThreadID.x + 1;
|
||||
int y = dispatchThreadID.y + 1;
|
||||
int z = dispatchThreadID.z + 1;
|
||||
if(x >= gridParams.gridSize.x - 1 || y >= gridParams.gridSize.y - 1 || z >= gridParams.gridSize.z - 1) return;
|
||||
|
||||
float dt0x = dt * (gridParams.gridSize.x - 2);
|
||||
float dt0y = dt * (gridParams.gridSize.y - 2);
|
||||
float dt0z = dt * (gridParams.gridSize.z - 2);
|
||||
|
||||
float3 pos = float3(x - dt0x * velocityX[x, y, z], y - dt0y * velocityY[x, y, z], z - dt0z * velocityZ[x, y, z]);
|
||||
pos.x = clamp(pos.x, 0.5f, gridParams.gridSize.x - 1.5f);
|
||||
pos.y = clamp(pos.y, 0.5f, gridParams.gridSize.y - 1.5f);
|
||||
pos.z = clamp(pos.z, 0.5f, gridParams.gridSize.z - 1.5f);
|
||||
|
||||
int3 i0 = int3(pos);
|
||||
int3 i1 = i0 + int3(1, 1, 1);
|
||||
|
||||
float3 s1 = pos - i0;
|
||||
float3 s0 = 1 - s1;
|
||||
|
||||
density[x, y, z] =
|
||||
s0.x * (s0.y * (s0.z * density0[i0.x, i0.y, i0.z] + s1.z * density0[i0.x, i0.y, i1.z]) +
|
||||
s1.y * (s0.z * density0[i0.x, i1.y, i0.z] + s1.z * density0[i0.x, i1.y, i1.z])) +
|
||||
s1.x * (s0.y * (s0.z * density0[i1.x, i0.y, i0.z] + s1.z * density0[i1.x, i0.y, i1.z]) +
|
||||
s1.y * (s0.z * density0[i1.x, i1.y, i0.z] + s1.z * density0[i1.x, i1.y, i1.z]));
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import FluidGridData;
|
||||
|
||||
struct Params
|
||||
{
|
||||
FluidGridData<float> velocityX;
|
||||
FluidGridData<float> velocityY;
|
||||
FluidGridData<float> velocityZ;
|
||||
float3 force;
|
||||
float dt;
|
||||
};
|
||||
ParameterBlock<Params> params;
|
||||
|
||||
[shader("compute")]
|
||||
[numthreads(32, 8, 1)]
|
||||
void applyForces(uint3 dispatchThreadID : SV_DispatchThreadID)
|
||||
{
|
||||
FluidGridData<float> velocityX = params.velocityX;
|
||||
FluidGridData<float> velocityY = params.velocityY;
|
||||
FluidGridData<float> velocityZ = params.velocityZ;
|
||||
float3 force = params.force;
|
||||
float dt = params.dt;
|
||||
|
||||
int x = dispatchThreadID.x + 1;
|
||||
int y = dispatchThreadID.y + 1;
|
||||
int z = dispatchThreadID.z + 1;
|
||||
if(x >= gridParams.gridSize.x - 1 || y >= gridParams.gridSize.y - 1 || z >= gridParams.gridSize.z - 1) return;
|
||||
|
||||
velocityX[x, y, z] += force.x * dt;
|
||||
velocityY[x, y, z] += force.y * dt;
|
||||
velocityZ[x, y, z] += force.z * dt;
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import FluidGridData;
|
||||
|
||||
struct Params {
|
||||
// read-only
|
||||
FluidGridData<float> velocityX;
|
||||
// read-only
|
||||
FluidGridData<float> velocityY;
|
||||
// read-only
|
||||
FluidGridData<float> velocityZ;
|
||||
// read-write
|
||||
FluidGridData<float> divergence;
|
||||
// read-write
|
||||
FluidGridData<float> pressure;
|
||||
};
|
||||
ParameterBlock<Params> params;
|
||||
|
||||
[shader("compute")]
|
||||
[numthreads(32, 8, 1)]
|
||||
void computeDivergence(uint3 dispatchThreadID: SV_DispatchThreadID) {
|
||||
FluidGridData<float> velocityX = params.velocityX;
|
||||
FluidGridData<float> velocityY = params.velocityY;
|
||||
FluidGridData<float> velocityZ = params.velocityZ;
|
||||
FluidGridData<float> divergence = params.divergence;
|
||||
FluidGridData<float> pressure = params.pressure;
|
||||
|
||||
int x = dispatchThreadID.x + 1;
|
||||
int y = dispatchThreadID.y + 1;
|
||||
int z = dispatchThreadID.z + 1;
|
||||
if (x >= gridParams.gridSize.x - 1 || y >= gridParams.gridSize.y - 1 || z >= gridParams.gridSize.z - 1)
|
||||
return;
|
||||
|
||||
divergence[x, y, z] = -0.5f * (velocityX[x + 1, y, z] - velocityX[x - 1, y, z] + velocityY[x, y + 1, z] - velocityY[x, y - 1, z] + velocityZ[x, y, z + 1] - velocityZ[x, y, z - 1]);
|
||||
pressure[x, y, z] = 0;
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import FluidGridData;
|
||||
|
||||
struct Parameter
|
||||
{
|
||||
float iso;
|
||||
FluidGridData<float> density;
|
||||
RWStructuredBuffer<float3> vertices;
|
||||
RWStructuredBuffer<uint> indices;
|
||||
RWStructuredBuffer<uint> surfaceCount;
|
||||
RWStructuredBuffer<uint> vertexCount;
|
||||
};
|
||||
ParameterBlock<Parameter> params;
|
||||
|
||||
float getDensity(uint x, uint y, uint z)
|
||||
{
|
||||
return params.density[x + gridParams.gridSize.x * y + gridParams.gridSize.x * gridParams.gridSize.y * z];
|
||||
}
|
||||
|
||||
[shader("compute")]
|
||||
[numthreads(32, 8, 1)]
|
||||
void main(uint3 dispatchThreadID : SV_DispatchThreadID)
|
||||
{
|
||||
uint x = dispatchThreadID.x+1;
|
||||
uint y = dispatchThreadID.y+1;
|
||||
uint z = dispatchThreadID.z+1;
|
||||
FluidGridData<float> density = params.density;
|
||||
if(x >= gridParams.gridSize.x-3 || y >= gridParams.gridSize.y-3 || z >= gridParams.gridSize.z-3) return;
|
||||
|
||||
float phi[8] = {
|
||||
getDensity(x, y, z),
|
||||
getDensity(x + 1, y, z),
|
||||
getDensity(x, y + 1, z),
|
||||
getDensity(x + 1, y + 1, z),
|
||||
getDensity(x, y, z + 1),
|
||||
getDensity(x + 1, y, z + 1),
|
||||
getDensity(x, y + 1, z + 1),
|
||||
getDensity(x + 1, y + 1, z + 1)
|
||||
};
|
||||
|
||||
uint cubeIndex = 0;
|
||||
for (uint i = 0; i < 8; ++i) {
|
||||
if (phi[i] < params.iso) {
|
||||
cubeIndex |= (1 << i);
|
||||
}
|
||||
}
|
||||
if(cubeIndex == 0 || cubeIndex == 255) return;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
struct GridParams
|
||||
{
|
||||
uint3 gridSize;
|
||||
};
|
||||
ParameterBlock<GridParams> gridParams;
|
||||
struct FluidGridData<T>
|
||||
{
|
||||
RWStructuredBuffer<T> dataGrid;
|
||||
__subscript(uint3 index) -> T
|
||||
{
|
||||
get { return dataGrid[index.x + index.y * gridParams.gridSize.x + index.z * gridParams.gridSize.x * gridParams.gridSize.y]; }
|
||||
set { dataGrid[index.x + index.y * gridParams.gridSize.x + index.z * gridParams.gridSize.x * gridParams.gridSize.y] = newValue; }
|
||||
}
|
||||
__subscript(uint x, uint y, uint z) -> T
|
||||
{
|
||||
get { return dataGrid[x + y * gridParams.gridSize.x + z * gridParams.gridSize.x * gridParams.gridSize.y]; }
|
||||
set { dataGrid[x + y * gridParams.gridSize.x + z * gridParams.gridSize.x * gridParams.gridSize.y] = newValue; }
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,38 @@
|
||||
import FluidGridData;
|
||||
|
||||
struct Params
|
||||
{
|
||||
// read-write (in-place update)
|
||||
FluidGridData<float> grid;
|
||||
// read-only (right-hand side)
|
||||
FluidGridData<float> grid0;
|
||||
float a;
|
||||
float c;
|
||||
float omega;
|
||||
int color;
|
||||
};
|
||||
ParameterBlock<Params> params;
|
||||
|
||||
[shader("compute")]
|
||||
[numthreads(32, 8, 1)]
|
||||
void linearSolve(uint3 dispatchThreadID : SV_DispatchThreadID)
|
||||
{
|
||||
FluidGridData<float> grid = params.grid;
|
||||
FluidGridData<float> grid0 = params.grid0;
|
||||
float a = params.a;
|
||||
float cRecip = 1.0f / params.c;
|
||||
float omega = params.omega;
|
||||
int color = params.color;
|
||||
|
||||
int x = dispatchThreadID.x + 1;
|
||||
int y = dispatchThreadID.y + 1;
|
||||
int z = dispatchThreadID.z + 1;
|
||||
if(x >= gridParams.gridSize.x - 1 || y >= gridParams.gridSize.y - 1 || z >= gridParams.gridSize.z - 1) return;
|
||||
|
||||
// Red-Black Gauss-Seidel: only update cells matching the current color
|
||||
if((x + y + z) % 2 != color) return;
|
||||
|
||||
float oldVal = grid[x, y, z];
|
||||
float gs = (grid0[x, y, z] + a * (grid[x + 1, y, z] + grid[x - 1, y, z] + grid[x, y + 1, z] + grid[x, y - 1, z] + grid[x, y, z + 1] + grid[x, y, z - 1])) * cRecip;
|
||||
grid[x, y, z] = lerp(oldVal, gs, omega);
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
import FluidGridData;
|
||||
import MarchingCubesData;
|
||||
|
||||
struct Params
|
||||
{
|
||||
RWStructuredBuffer<float> vertexBuffer;
|
||||
RWStructuredBuffer<float> normalBuffer;
|
||||
RWStructuredBuffer<uint> indexBuffer;
|
||||
RWStructuredBuffer<uint> indicesCount;
|
||||
FluidGridData<float> levelSet;
|
||||
};
|
||||
ParameterBlock<Params> params;
|
||||
|
||||
const static float isoLevel = 0.0f;
|
||||
const static float3 cellSize = 1.0f / gridParams.gridSize;
|
||||
|
||||
float3 vertexInterp(float isoLevel, float3 p1, float3 p2, float valp1, float valp2)
|
||||
{
|
||||
if (abs(isoLevel - valp1) < 0.00001)
|
||||
return p1;
|
||||
if (abs(isoLevel - valp2) < 0.00001)
|
||||
return p2;
|
||||
if (abs(valp1 - valp2) < 0.00001)
|
||||
return p1;
|
||||
float mu = (isoLevel - valp1) / (valp2 - valp1);
|
||||
return p1 + mu * (p2 - p1);
|
||||
}
|
||||
|
||||
float3 gridPos(uint x, uint y, uint z)
|
||||
{
|
||||
return float3(x, y, z) * cellSize;
|
||||
}
|
||||
|
||||
// TODO: parameterize
|
||||
const static uint32_t LOCAL_THREADGROUP_SIZE = 16 * 8 * 1; // Must match numthreads
|
||||
const static uint32_t MAX_TRIS_PER_THREAD = 5; // Max triangles per cube configuration
|
||||
const static uint32_t MAX_VERTS_PER_GROUP = LOCAL_THREADGROUP_SIZE * MAX_TRIS_PER_THREAD * 3;
|
||||
|
||||
groupshared float3 localVertices[MAX_VERTS_PER_GROUP];
|
||||
groupshared float3 localNormals[MAX_VERTS_PER_GROUP];
|
||||
groupshared uint localTriCounts[LOCAL_THREADGROUP_SIZE]; // per-thread triangle counts
|
||||
groupshared uint localOffsets[LOCAL_THREADGROUP_SIZE]; // per-thread exclusive offsets (in vertices)
|
||||
groupshared uint localBaseOffset; // global base offset for this workgroup
|
||||
|
||||
// Hillis-Steele inclusive scan on localTriCounts, result in localOffsets
|
||||
// Then convert to exclusive scan and allocate global space
|
||||
void prefixSumAndAllocate(uint groupIndex)
|
||||
{
|
||||
localOffsets[groupIndex] = localTriCounts[groupIndex];
|
||||
GroupMemoryBarrierWithGroupSync();
|
||||
|
||||
for (uint offset = 1; offset < LOCAL_THREADGROUP_SIZE; offset *= 2)
|
||||
{
|
||||
uint temp = 0;
|
||||
if (groupIndex >= offset)
|
||||
temp = localOffsets[groupIndex - offset];
|
||||
GroupMemoryBarrierWithGroupSync();
|
||||
localOffsets[groupIndex] += temp;
|
||||
GroupMemoryBarrierWithGroupSync();
|
||||
}
|
||||
|
||||
// localOffsets is now an inclusive prefix sum
|
||||
// Last thread has the total — allocate global space
|
||||
if (groupIndex == LOCAL_THREADGROUP_SIZE - 1)
|
||||
{
|
||||
uint totalVerts = localOffsets[groupIndex] * 3;
|
||||
InterlockedAdd(params.indicesCount[0], totalVerts, localBaseOffset);
|
||||
}
|
||||
GroupMemoryBarrierWithGroupSync();
|
||||
|
||||
// Convert inclusive to exclusive: shift right, first element = 0
|
||||
uint inclusive = localOffsets[groupIndex];
|
||||
GroupMemoryBarrierWithGroupSync();
|
||||
localOffsets[groupIndex] = (groupIndex == 0) ? 0 : localOffsets[groupIndex - 1];
|
||||
GroupMemoryBarrierWithGroupSync();
|
||||
}
|
||||
|
||||
[shader("compute")]
|
||||
[numthreads(16, 8, 1)]
|
||||
void marchingCubes(uint3 dispatchThreadID : SV_DispatchThreadID, uint groupIndex : SV_GroupIndex)
|
||||
{
|
||||
uint x = dispatchThreadID.x + 1;
|
||||
uint y = dispatchThreadID.y + 1;
|
||||
uint z = dispatchThreadID.z + 1;
|
||||
FluidGridData<float> levelSet = params.levelSet;
|
||||
|
||||
// Don't early-return — all threads must participate in barriers.
|
||||
// Use a flag to skip work for out-of-bounds threads.
|
||||
bool valid = (x < gridParams.gridSize.x - 2 && y < gridParams.gridSize.y - 2 && z < gridParams.gridSize.z - 2);
|
||||
|
||||
float val[8];
|
||||
uint cubeIndex = 0;
|
||||
uint triCount = 0;
|
||||
|
||||
if (valid)
|
||||
{
|
||||
val[0] = levelSet[x, y, z];
|
||||
val[1] = levelSet[x + 1, y, z];
|
||||
val[2] = levelSet[x + 1, y + 1, z];
|
||||
val[3] = levelSet[x, y + 1, z];
|
||||
val[4] = levelSet[x, y, z + 1];
|
||||
val[5] = levelSet[x + 1, y, z + 1];
|
||||
val[6] = levelSet[x + 1, y + 1, z + 1];
|
||||
val[7] = levelSet[x, y + 1, z + 1];
|
||||
|
||||
if (val[0] < isoLevel) cubeIndex |= 1;
|
||||
if (val[1] < isoLevel) cubeIndex |= 2;
|
||||
if (val[2] < isoLevel) cubeIndex |= 4;
|
||||
if (val[3] < isoLevel) cubeIndex |= 8;
|
||||
if (val[4] < isoLevel) cubeIndex |= 16;
|
||||
if (val[5] < isoLevel) cubeIndex |= 32;
|
||||
if (val[6] < isoLevel) cubeIndex |= 64;
|
||||
if (val[7] < isoLevel) cubeIndex |= 128;
|
||||
|
||||
for (int i = 0; triTable[cubeIndex][i] != -1; i += 3)
|
||||
triCount++;
|
||||
}
|
||||
|
||||
// Prefix sum to compute per-thread offsets and allocate global space
|
||||
localTriCounts[groupIndex] = triCount;
|
||||
GroupMemoryBarrierWithGroupSync();
|
||||
prefixSumAndAllocate(groupIndex);
|
||||
|
||||
// localOffsets[groupIndex] = exclusive sum of triCounts before this thread
|
||||
// localBaseOffset = global vertex offset for this workgroup
|
||||
|
||||
if (valid && triCount > 0)
|
||||
{
|
||||
float3 pos[8];
|
||||
pos[0] = gridPos(x, y, z);
|
||||
pos[1] = gridPos(x + 1, y, z);
|
||||
pos[2] = gridPos(x + 1, y + 1, z);
|
||||
pos[3] = gridPos(x, y + 1, z);
|
||||
pos[4] = gridPos(x, y, z + 1);
|
||||
pos[5] = gridPos(x + 1, y, z + 1);
|
||||
pos[6] = gridPos(x + 1, y + 1, z + 1);
|
||||
pos[7] = gridPos(x, y + 1, z + 1);
|
||||
|
||||
float3 vertList[12];
|
||||
if ((edgeTable[cubeIndex] & 1) != 0)
|
||||
vertList[0] = vertexInterp(isoLevel, pos[0], pos[1], val[0], val[1]);
|
||||
if ((edgeTable[cubeIndex] & 2) != 0)
|
||||
vertList[1] = vertexInterp(isoLevel, pos[1], pos[2], val[1], val[2]);
|
||||
if ((edgeTable[cubeIndex] & 4) != 0)
|
||||
vertList[2] = vertexInterp(isoLevel, pos[2], pos[3], val[2], val[3]);
|
||||
if ((edgeTable[cubeIndex] & 8) != 0)
|
||||
vertList[3] = vertexInterp(isoLevel, pos[3], pos[0], val[3], val[0]);
|
||||
if ((edgeTable[cubeIndex] & 16) != 0)
|
||||
vertList[4] = vertexInterp(isoLevel, pos[4], pos[5], val[4], val[5]);
|
||||
if ((edgeTable[cubeIndex] & 32) != 0)
|
||||
vertList[5] = vertexInterp(isoLevel, pos[5], pos[6], val[5], val[6]);
|
||||
if ((edgeTable[cubeIndex] & 64) != 0)
|
||||
vertList[6] = vertexInterp(isoLevel, pos[6], pos[7], val[6], val[7]);
|
||||
if ((edgeTable[cubeIndex] & 128) != 0)
|
||||
vertList[7] = vertexInterp(isoLevel, pos[7], pos[4], val[7], val[4]);
|
||||
if ((edgeTable[cubeIndex] & 256) != 0)
|
||||
vertList[8] = vertexInterp(isoLevel, pos[0], pos[4], val[0], val[4]);
|
||||
if ((edgeTable[cubeIndex] & 512) != 0)
|
||||
vertList[9] = vertexInterp(isoLevel, pos[1], pos[5], val[1], val[5]);
|
||||
if ((edgeTable[cubeIndex] & 1024) != 0)
|
||||
vertList[10] = vertexInterp(isoLevel, pos[2], pos[6], val[2], val[6]);
|
||||
if ((edgeTable[cubeIndex] & 2048) != 0)
|
||||
vertList[11] = vertexInterp(isoLevel, pos[3], pos[7], val[3], val[7]);
|
||||
|
||||
// Write triangles into shared memory
|
||||
uint localOff = localOffsets[groupIndex] * 3; // in vertices
|
||||
for (int i = 0; triTable[cubeIndex][i] != -1; i += 3)
|
||||
{
|
||||
float3 v0 = vertList[triTable[cubeIndex][i]];
|
||||
float3 v1 = vertList[triTable[cubeIndex][i + 1]];
|
||||
float3 v2 = vertList[triTable[cubeIndex][i + 2]];
|
||||
float3 n = normalize(cross(v2 - v0, v1 - v0));
|
||||
|
||||
localVertices[localOff] = v0;
|
||||
localVertices[localOff + 1] = v1;
|
||||
localVertices[localOff + 2] = v2;
|
||||
localNormals[localOff] = n;
|
||||
localNormals[localOff + 1] = n;
|
||||
localNormals[localOff + 2] = n;
|
||||
localOff += 3;
|
||||
}
|
||||
}
|
||||
|
||||
GroupMemoryBarrierWithGroupSync();
|
||||
|
||||
// Copy from shared memory to global buffers
|
||||
// Each thread copies a chunk of the workgroup's output
|
||||
uint totalGroupVerts = localTriCounts[LOCAL_THREADGROUP_SIZE - 1] > 0
|
||||
? (localOffsets[LOCAL_THREADGROUP_SIZE - 1] + localTriCounts[LOCAL_THREADGROUP_SIZE - 1]) * 3
|
||||
: localOffsets[LOCAL_THREADGROUP_SIZE - 1] * 3;
|
||||
|
||||
for (uint i = groupIndex; i < totalGroupVerts; i += LOCAL_THREADGROUP_SIZE)
|
||||
{
|
||||
uint globalIdx = localBaseOffset + i;
|
||||
float3 v = localVertices[i];
|
||||
float3 n = localNormals[i];
|
||||
params.vertexBuffer[globalIdx * 3 + 0] = v.x;
|
||||
params.vertexBuffer[globalIdx * 3 + 1] = v.y;
|
||||
params.vertexBuffer[globalIdx * 3 + 2] = v.z;
|
||||
params.normalBuffer[globalIdx * 3 + 0] = n.x;
|
||||
params.normalBuffer[globalIdx * 3 + 1] = n.y;
|
||||
params.normalBuffer[globalIdx * 3 + 2] = n.z;
|
||||
params.indexBuffer[globalIdx] = globalIdx;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,299 @@
|
||||
// Marching Cubes edge table: for each cube configuration (256), a 12-bit mask
|
||||
// indicating which edges are intersected by the isosurface.
|
||||
// clang-format off
|
||||
static const uint16_t edgeTable[256] = {
|
||||
0x000, 0x109, 0x203, 0x30a, 0x406, 0x50f, 0x605, 0x70c,
|
||||
0x80c, 0x905, 0xa0f, 0xb06, 0xc0a, 0xd03, 0xe09, 0xf00,
|
||||
0x190, 0x099, 0x393, 0x29a, 0x596, 0x49f, 0x795, 0x69c,
|
||||
0x99c, 0x895, 0xb9f, 0xa96, 0xd9a, 0xc93, 0xf99, 0xe90,
|
||||
0x230, 0x339, 0x033, 0x13a, 0x636, 0x73f, 0x435, 0x53c,
|
||||
0xa3c, 0xb35, 0x83f, 0x936, 0xe3a, 0xf33, 0xc39, 0xd30,
|
||||
0x3a0, 0x2a9, 0x1a3, 0x0aa, 0x7a6, 0x6af, 0x5a5, 0x4ac,
|
||||
0xbac, 0xaa5, 0x9af, 0x8a6, 0xfaa, 0xea3, 0xda9, 0xca0,
|
||||
0x460, 0x569, 0x663, 0x76a, 0x066, 0x16f, 0x265, 0x36c,
|
||||
0xc6c, 0xd65, 0xe6f, 0xf66, 0x86a, 0x963, 0xa69, 0xb60,
|
||||
0x5f0, 0x4f9, 0x7f3, 0x6fa, 0x1f6, 0x0ff, 0x3f5, 0x2fc,
|
||||
0xdfc, 0xcf5, 0xfff, 0xef6, 0x9fa, 0x8f3, 0xbf9, 0xaf0,
|
||||
0x650, 0x759, 0x453, 0x55a, 0x256, 0x35f, 0x055, 0x15c,
|
||||
0xe5c, 0xf55, 0xc5f, 0xd56, 0xa5a, 0xb53, 0x859, 0x950,
|
||||
0x7c0, 0x6c9, 0x5c3, 0x4ca, 0x3c6, 0x2cf, 0x1c5, 0x0cc,
|
||||
0xfcc, 0xec5, 0xdcf, 0xcc6, 0xbca, 0xac3, 0x9c9, 0x8c0,
|
||||
0x8c0, 0x9c9, 0xac3, 0xbca, 0xcc6, 0xdcf, 0xec5, 0xfcc,
|
||||
0x0cc, 0x1c5, 0x2cf, 0x3c6, 0x4ca, 0x5c3, 0x6c9, 0x7c0,
|
||||
0x950, 0x859, 0xb53, 0xa5a, 0xd56, 0xc5f, 0xf55, 0xe5c,
|
||||
0x15c, 0x055, 0x35f, 0x256, 0x55a, 0x453, 0x759, 0x650,
|
||||
0xaf0, 0xbf9, 0x8f3, 0x9fa, 0xef6, 0xfff, 0xcf5, 0xdfc,
|
||||
0x2fc, 0x3f5, 0x0ff, 0x1f6, 0x6fa, 0x7f3, 0x4f9, 0x5f0,
|
||||
0xb60, 0xa69, 0x963, 0x86a, 0xf66, 0xe6f, 0xd65, 0xc6c,
|
||||
0x36c, 0x265, 0x16f, 0x066, 0x76a, 0x663, 0x569, 0x460,
|
||||
0xca0, 0xda9, 0xea3, 0xfaa, 0x8a6, 0x9af, 0xaa5, 0xbac,
|
||||
0x4ac, 0x5a5, 0x6af, 0x7a6, 0x0aa, 0x1a3, 0x2a9, 0x3a0,
|
||||
0xd30, 0xc39, 0xf33, 0xe3a, 0x936, 0x83f, 0xb35, 0xa3c,
|
||||
0x53c, 0x435, 0x73f, 0x636, 0x13a, 0x033, 0x339, 0x230,
|
||||
0xe90, 0xf99, 0xc93, 0xd9a, 0xa96, 0xb9f, 0x895, 0x99c,
|
||||
0x69c, 0x795, 0x49f, 0x596, 0x29a, 0x393, 0x099, 0x190,
|
||||
0xf00, 0xe09, 0xd03, 0xc0a, 0xb06, 0xa0f, 0x905, 0x80c,
|
||||
0x70c, 0x605, 0x50f, 0x406, 0x30a, 0x203, 0x109, 0x000,
|
||||
};
|
||||
|
||||
// Marching Cubes triangle table: for each cube configuration, up to 5
|
||||
// triangles specified as sequences of edge indices, terminated by -1.
|
||||
static const int8_t triTable[256][16] = {
|
||||
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
|
||||
{0,8,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
|
||||
{0,1,9,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
|
||||
{1,8,3,9,8,1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
|
||||
{1,2,10,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
|
||||
{0,8,3,1,2,10,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
|
||||
{9,2,10,0,2,9,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
|
||||
{2,8,3,2,10,8,10,9,8,-1,-1,-1,-1,-1,-1,-1},
|
||||
{3,11,2,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
|
||||
{0,11,2,8,11,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
|
||||
{1,9,0,2,3,11,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
|
||||
{1,11,2,1,9,11,9,8,11,-1,-1,-1,-1,-1,-1,-1},
|
||||
{3,10,1,11,10,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
|
||||
{0,10,1,0,8,10,8,11,10,-1,-1,-1,-1,-1,-1,-1},
|
||||
{3,9,0,3,11,9,11,10,9,-1,-1,-1,-1,-1,-1,-1},
|
||||
{9,8,10,10,8,11,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
|
||||
{4,7,8,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
|
||||
{4,3,0,7,3,4,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
|
||||
{0,1,9,8,4,7,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
|
||||
{4,1,9,4,7,1,7,3,1,-1,-1,-1,-1,-1,-1,-1},
|
||||
{1,2,10,8,4,7,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
|
||||
{3,4,7,3,0,4,1,2,10,-1,-1,-1,-1,-1,-1,-1},
|
||||
{9,2,10,9,0,2,8,4,7,-1,-1,-1,-1,-1,-1,-1},
|
||||
{2,10,9,2,9,7,2,7,3,7,9,4,-1,-1,-1,-1},
|
||||
{8,4,7,3,11,2,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
|
||||
{11,4,7,11,2,4,2,0,4,-1,-1,-1,-1,-1,-1,-1},
|
||||
{9,0,1,8,4,7,2,3,11,-1,-1,-1,-1,-1,-1,-1},
|
||||
{4,7,11,9,4,11,9,11,2,9,2,1,-1,-1,-1,-1},
|
||||
{3,10,1,3,11,10,7,8,4,-1,-1,-1,-1,-1,-1,-1},
|
||||
{1,11,10,1,4,11,1,0,4,7,11,4,-1,-1,-1,-1},
|
||||
{4,7,8,9,0,11,9,11,10,11,0,3,-1,-1,-1,-1},
|
||||
{4,7,11,4,11,9,9,11,10,-1,-1,-1,-1,-1,-1,-1},
|
||||
{9,5,4,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
|
||||
{9,5,4,0,8,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
|
||||
{0,5,4,1,5,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
|
||||
{8,5,4,8,3,5,3,1,5,-1,-1,-1,-1,-1,-1,-1},
|
||||
{1,2,10,9,5,4,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
|
||||
{3,0,8,1,2,10,4,9,5,-1,-1,-1,-1,-1,-1,-1},
|
||||
{5,2,10,5,4,2,4,0,2,-1,-1,-1,-1,-1,-1,-1},
|
||||
{2,10,5,3,2,5,3,5,4,3,4,8,-1,-1,-1,-1},
|
||||
{9,5,4,2,3,11,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
|
||||
{0,11,2,0,8,11,4,9,5,-1,-1,-1,-1,-1,-1,-1},
|
||||
{0,5,4,0,1,5,2,3,11,-1,-1,-1,-1,-1,-1,-1},
|
||||
{2,1,5,2,5,8,2,8,11,4,8,5,-1,-1,-1,-1},
|
||||
{10,3,11,10,1,3,9,5,4,-1,-1,-1,-1,-1,-1,-1},
|
||||
{4,9,5,0,8,1,8,10,1,8,11,10,-1,-1,-1,-1},
|
||||
{5,4,0,5,0,11,5,11,10,11,0,3,-1,-1,-1,-1},
|
||||
{5,4,8,5,8,10,10,8,11,-1,-1,-1,-1,-1,-1,-1},
|
||||
{9,7,8,5,7,9,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
|
||||
{9,3,0,9,5,3,5,7,3,-1,-1,-1,-1,-1,-1,-1},
|
||||
{0,7,8,0,1,7,1,5,7,-1,-1,-1,-1,-1,-1,-1},
|
||||
{1,5,3,3,5,7,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
|
||||
{9,7,8,9,5,7,10,1,2,-1,-1,-1,-1,-1,-1,-1},
|
||||
{10,1,2,9,5,0,5,3,0,5,7,3,-1,-1,-1,-1},
|
||||
{8,0,2,8,2,5,8,5,7,10,5,2,-1,-1,-1,-1},
|
||||
{2,10,5,2,5,3,3,5,7,-1,-1,-1,-1,-1,-1,-1},
|
||||
{7,9,5,7,8,9,3,11,2,-1,-1,-1,-1,-1,-1,-1},
|
||||
{9,5,7,9,7,2,9,2,0,2,7,11,-1,-1,-1,-1},
|
||||
{2,3,11,0,1,8,1,7,8,1,5,7,-1,-1,-1,-1},
|
||||
{11,2,1,11,1,7,7,1,5,-1,-1,-1,-1,-1,-1,-1},
|
||||
{9,5,8,8,5,7,10,1,3,10,3,11,-1,-1,-1,-1},
|
||||
{5,7,0,5,0,9,7,11,0,1,0,10,11,10,0,-1},
|
||||
{11,10,0,11,0,3,10,5,0,8,0,7,5,7,0,-1},
|
||||
{11,10,5,7,11,5,-1,-1,-1,-1,-1,-1,-1,-1,-1},
|
||||
{10,6,5,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
|
||||
{0,8,3,5,10,6,-1,-1,-1,-1,-1,-1,-1,-1,-1},
|
||||
{9,0,1,5,10,6,-1,-1,-1,-1,-1,-1,-1,-1,-1},
|
||||
{1,8,3,1,9,8,5,10,6,-1,-1,-1,-1,-1,-1},
|
||||
{1,6,5,2,6,1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
|
||||
{1,6,5,1,2,6,3,0,8,-1,-1,-1,-1,-1,-1},
|
||||
{9,6,5,9,0,6,0,2,6,-1,-1,-1,-1,-1,-1},
|
||||
{5,9,8,5,8,2,5,2,6,3,2,8,-1,-1,-1,-1},
|
||||
{2,3,11,10,6,5,-1,-1,-1,-1,-1,-1,-1,-1,-1},
|
||||
{11,0,8,11,2,0,10,6,5,-1,-1,-1,-1,-1,-1},
|
||||
{0,1,9,2,3,11,5,10,6,-1,-1,-1,-1,-1,-1},
|
||||
{5,10,6,1,9,2,9,11,2,9,8,11,-1,-1,-1,-1},
|
||||
{6,3,11,6,5,3,5,1,3,-1,-1,-1,-1,-1,-1,-1},
|
||||
{0,8,11,0,11,5,0,5,1,5,11,6,-1,-1,-1,-1},
|
||||
{3,11,6,0,3,6,0,6,5,0,5,9,-1,-1,-1,-1},
|
||||
{6,5,9,6,9,11,11,9,8,-1,-1,-1,-1,-1,-1,-1},
|
||||
{5,10,6,4,7,8,-1,-1,-1,-1,-1,-1,-1,-1,-1},
|
||||
{4,3,0,4,7,3,6,5,10,-1,-1,-1,-1,-1,-1,-1},
|
||||
{1,9,0,5,10,6,8,4,7,-1,-1,-1,-1,-1,-1,-1},
|
||||
{10,6,5,1,9,7,1,7,3,7,9,4,-1,-1,-1,-1},
|
||||
{6,1,2,6,5,1,4,7,8,-1,-1,-1,-1,-1,-1,-1},
|
||||
{1,2,5,5,2,6,3,0,4,3,4,7,-1,-1,-1,-1},
|
||||
{8,4,7,9,0,5,0,6,5,0,2,6,-1,-1,-1,-1},
|
||||
{7,3,9,7,9,4,3,2,9,5,9,6,2,6,9,-1},
|
||||
{3,11,2,7,8,4,10,6,5,-1,-1,-1,-1,-1,-1,-1},
|
||||
{5,10,6,4,7,2,4,2,0,2,7,11,-1,-1,-1,-1},
|
||||
{0,1,9,4,7,8,2,3,11,5,10,6,-1,-1,-1,-1},
|
||||
{9,2,1,9,11,2,9,4,11,7,11,4,5,10,6,-1},
|
||||
{8,4,7,3,11,5,3,5,1,5,11,6,-1,-1,-1,-1},
|
||||
{5,1,11,5,11,6,1,0,11,7,11,4,0,4,11,-1},
|
||||
{0,5,9,0,6,5,0,3,6,11,6,3,8,4,7,-1},
|
||||
{6,5,9,6,9,11,4,7,9,7,11,9,-1,-1,-1,-1},
|
||||
{10,4,9,6,4,10,-1,-1,-1,-1,-1,-1,-1,-1,-1},
|
||||
{4,10,6,4,9,10,0,8,3,-1,-1,-1,-1,-1,-1},
|
||||
{10,0,1,10,6,0,6,4,0,-1,-1,-1,-1,-1,-1},
|
||||
{8,3,1,8,1,6,8,6,4,6,1,10,-1,-1,-1,-1},
|
||||
{1,4,9,1,2,4,2,6,4,-1,-1,-1,-1,-1,-1,-1},
|
||||
{3,0,8,1,2,9,2,4,9,2,6,4,-1,-1,-1,-1},
|
||||
{0,2,4,4,2,6,-1,-1,-1,-1,-1,-1,-1,-1,-1},
|
||||
{8,3,2,8,2,4,4,2,6,-1,-1,-1,-1,-1,-1,-1},
|
||||
{10,4,9,10,6,4,11,2,3,-1,-1,-1,-1,-1,-1},
|
||||
{0,8,2,2,8,11,4,9,10,4,10,6,-1,-1,-1,-1},
|
||||
{3,11,2,0,1,6,0,6,4,6,1,10,-1,-1,-1,-1},
|
||||
{6,4,1,6,1,10,4,8,1,2,1,11,8,11,1,-1},
|
||||
{9,6,4,9,3,6,9,1,3,11,6,3,-1,-1,-1,-1},
|
||||
{8,11,1,8,1,0,11,6,1,9,1,4,6,4,1,-1},
|
||||
{3,11,6,3,6,0,0,6,4,-1,-1,-1,-1,-1,-1,-1},
|
||||
{6,4,8,11,6,8,-1,-1,-1,-1,-1,-1,-1,-1,-1},
|
||||
{7,10,6,7,8,10,8,9,10,-1,-1,-1,-1,-1,-1,-1},
|
||||
{0,7,3,0,10,7,0,9,10,6,7,10,-1,-1,-1,-1},
|
||||
{10,6,7,1,10,7,1,7,8,1,8,0,-1,-1,-1,-1},
|
||||
{10,6,7,10,7,1,1,7,3,-1,-1,-1,-1,-1,-1,-1},
|
||||
{1,2,6,1,6,8,1,8,9,8,6,7,-1,-1,-1,-1},
|
||||
{2,6,9,2,9,1,6,7,9,0,9,3,7,3,9,-1},
|
||||
{7,8,0,7,0,6,6,0,2,-1,-1,-1,-1,-1,-1,-1},
|
||||
{7,3,2,6,7,2,-1,-1,-1,-1,-1,-1,-1,-1,-1},
|
||||
{2,3,11,10,6,8,10,8,9,8,6,7,-1,-1,-1,-1},
|
||||
{2,0,7,2,7,11,0,9,7,6,7,10,9,10,7,-1},
|
||||
{1,8,0,1,7,8,1,10,7,6,7,10,2,3,11,-1},
|
||||
{11,2,1,11,1,7,10,6,1,6,7,1,-1,-1,-1,-1},
|
||||
{8,9,6,8,6,7,9,1,6,11,6,3,1,3,6,-1},
|
||||
{0,9,1,11,6,7,-1,-1,-1,-1,-1,-1,-1,-1,-1},
|
||||
{7,8,0,7,0,6,3,11,0,11,6,0,-1,-1,-1,-1},
|
||||
{7,11,6,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
|
||||
{7,6,11,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
|
||||
{3,0,8,11,7,6,-1,-1,-1,-1,-1,-1,-1,-1,-1},
|
||||
{0,1,9,11,7,6,-1,-1,-1,-1,-1,-1,-1,-1,-1},
|
||||
{8,1,9,8,3,1,11,7,6,-1,-1,-1,-1,-1,-1},
|
||||
{10,1,2,6,11,7,-1,-1,-1,-1,-1,-1,-1,-1,-1},
|
||||
{1,2,10,3,0,8,6,11,7,-1,-1,-1,-1,-1,-1},
|
||||
{2,9,0,2,10,9,6,11,7,-1,-1,-1,-1,-1,-1},
|
||||
{6,11,7,2,10,3,10,8,3,10,9,8,-1,-1,-1,-1},
|
||||
{7,2,3,6,2,7,-1,-1,-1,-1,-1,-1,-1,-1,-1},
|
||||
{7,0,8,7,6,0,6,2,0,-1,-1,-1,-1,-1,-1,-1},
|
||||
{2,7,6,2,3,7,0,1,9,-1,-1,-1,-1,-1,-1,-1},
|
||||
{1,6,2,1,8,6,1,9,8,8,7,6,-1,-1,-1,-1},
|
||||
{10,7,6,10,1,7,1,3,7,-1,-1,-1,-1,-1,-1,-1},
|
||||
{10,7,6,1,7,10,1,8,7,1,0,8,-1,-1,-1,-1},
|
||||
{0,3,7,0,7,10,0,10,9,6,10,7,-1,-1,-1,-1},
|
||||
{7,6,10,7,10,8,8,10,9,-1,-1,-1,-1,-1,-1,-1},
|
||||
{6,8,4,11,8,6,-1,-1,-1,-1,-1,-1,-1,-1,-1},
|
||||
{3,6,11,3,0,6,0,4,6,-1,-1,-1,-1,-1,-1,-1},
|
||||
{8,6,11,8,4,6,9,0,1,-1,-1,-1,-1,-1,-1,-1},
|
||||
{9,4,6,9,6,3,9,3,1,11,3,6,-1,-1,-1,-1},
|
||||
{6,8,4,6,11,8,2,10,1,-1,-1,-1,-1,-1,-1,-1},
|
||||
{1,2,10,3,0,11,0,6,11,0,4,6,-1,-1,-1,-1},
|
||||
{4,11,8,4,6,11,0,2,9,2,10,9,-1,-1,-1,-1},
|
||||
{10,9,3,10,3,2,9,4,3,11,3,6,4,6,3,-1},
|
||||
{8,2,3,8,4,2,4,6,2,-1,-1,-1,-1,-1,-1,-1},
|
||||
{0,4,2,4,6,2,-1,-1,-1,-1,-1,-1,-1,-1,-1},
|
||||
{1,9,0,2,3,4,2,4,6,4,3,8,-1,-1,-1,-1},
|
||||
{1,9,4,1,4,2,2,4,6,-1,-1,-1,-1,-1,-1,-1},
|
||||
{8,1,3,8,6,1,8,4,6,6,10,1,-1,-1,-1,-1},
|
||||
{10,1,0,10,0,6,6,0,4,-1,-1,-1,-1,-1,-1,-1},
|
||||
{4,6,3,4,3,8,6,10,3,0,3,9,10,9,3,-1},
|
||||
{10,9,4,6,10,4,-1,-1,-1,-1,-1,-1,-1,-1,-1},
|
||||
{4,9,5,7,6,11,-1,-1,-1,-1,-1,-1,-1,-1,-1},
|
||||
{0,8,3,4,9,5,11,7,6,-1,-1,-1,-1,-1,-1,-1},
|
||||
{5,0,1,5,4,0,7,6,11,-1,-1,-1,-1,-1,-1,-1},
|
||||
{11,7,6,8,3,4,3,5,4,3,1,5,-1,-1,-1,-1},
|
||||
{9,5,4,10,1,2,7,6,11,-1,-1,-1,-1,-1,-1,-1},
|
||||
{6,11,7,1,2,10,0,8,3,4,9,5,-1,-1,-1,-1},
|
||||
{7,6,11,5,4,10,4,2,10,4,0,2,-1,-1,-1,-1},
|
||||
{3,4,8,3,5,4,3,2,5,10,5,2,11,7,6,-1},
|
||||
{7,2,3,7,6,2,5,4,9,-1,-1,-1,-1,-1,-1,-1},
|
||||
{9,5,4,0,8,6,0,6,2,6,8,7,-1,-1,-1,-1},
|
||||
{3,6,2,3,7,6,1,5,0,5,4,0,-1,-1,-1,-1},
|
||||
{6,2,8,6,8,7,2,1,8,4,8,5,1,5,8,-1},
|
||||
{9,5,4,10,1,6,1,7,6,1,3,7,-1,-1,-1,-1},
|
||||
{1,6,10,1,7,6,1,0,7,8,7,0,9,5,4,-1},
|
||||
{4,0,10,4,10,5,0,3,10,6,10,7,3,7,10,-1},
|
||||
{7,6,10,7,10,8,5,4,10,4,8,10,-1,-1,-1,-1},
|
||||
{6,9,5,6,11,9,11,8,9,-1,-1,-1,-1,-1,-1,-1},
|
||||
{3,6,11,0,6,3,0,5,6,0,9,5,-1,-1,-1,-1},
|
||||
{0,11,8,0,5,11,0,1,5,5,6,11,-1,-1,-1,-1},
|
||||
{6,11,3,6,3,5,5,3,1,-1,-1,-1,-1,-1,-1,-1},
|
||||
{1,2,10,9,5,11,9,11,8,11,5,6,-1,-1,-1,-1},
|
||||
{0,11,3,0,6,11,0,9,6,5,6,9,1,2,10,-1},
|
||||
{11,8,5,11,5,6,8,0,5,10,5,2,0,2,5,-1},
|
||||
{6,11,3,6,3,5,2,10,3,10,5,3,-1,-1,-1,-1},
|
||||
{5,8,9,5,2,8,5,6,2,3,8,2,-1,-1,-1,-1},
|
||||
{9,5,6,9,6,0,0,6,2,-1,-1,-1,-1,-1,-1,-1},
|
||||
{1,5,8,1,8,0,5,6,8,3,8,2,6,2,8,-1},
|
||||
{1,5,6,2,1,6,-1,-1,-1,-1,-1,-1,-1,-1,-1},
|
||||
{1,3,6,1,6,10,3,8,6,5,6,9,8,9,6,-1},
|
||||
{10,1,0,10,0,6,9,5,0,5,6,0,-1,-1,-1,-1},
|
||||
{0,3,8,5,6,10,-1,-1,-1,-1,-1,-1,-1,-1,-1},
|
||||
{10,5,6,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
|
||||
{11,5,10,7,5,11,-1,-1,-1,-1,-1,-1,-1,-1,-1},
|
||||
{11,5,10,11,7,5,8,3,0,-1,-1,-1,-1,-1,-1},
|
||||
{5,11,7,5,10,11,1,9,0,-1,-1,-1,-1,-1,-1},
|
||||
{10,7,5,10,11,7,9,8,1,8,3,1,-1,-1,-1,-1},
|
||||
{11,1,2,11,7,1,7,5,1,-1,-1,-1,-1,-1,-1},
|
||||
{0,8,3,1,2,7,1,7,5,7,2,11,-1,-1,-1,-1},
|
||||
{9,7,5,9,2,7,9,0,2,2,11,7,-1,-1,-1,-1},
|
||||
{7,5,2,7,2,11,5,9,2,3,2,8,9,8,2,-1},
|
||||
{2,5,10,2,3,5,3,7,5,-1,-1,-1,-1,-1,-1,-1},
|
||||
{8,2,0,8,5,2,8,7,5,10,2,5,-1,-1,-1,-1},
|
||||
{9,0,1,5,10,3,5,3,7,3,10,2,-1,-1,-1,-1},
|
||||
{9,8,2,9,2,1,8,7,2,10,2,5,7,5,2,-1},
|
||||
{1,3,5,3,7,5,-1,-1,-1,-1,-1,-1,-1,-1,-1},
|
||||
{0,8,7,0,7,1,1,7,5,-1,-1,-1,-1,-1,-1,-1},
|
||||
{9,0,3,9,3,5,5,3,7,-1,-1,-1,-1,-1,-1,-1},
|
||||
{9,8,7,5,9,7,-1,-1,-1,-1,-1,-1,-1,-1,-1},
|
||||
{5,8,4,5,10,8,10,11,8,-1,-1,-1,-1,-1,-1,-1},
|
||||
{5,0,4,5,11,0,5,10,11,11,3,0,-1,-1,-1,-1},
|
||||
{0,1,9,8,4,10,8,10,11,10,4,5,-1,-1,-1,-1},
|
||||
{10,11,4,10,4,5,11,3,4,9,4,1,3,1,4,-1},
|
||||
{2,5,1,2,8,5,2,11,8,4,5,8,-1,-1,-1,-1},
|
||||
{0,4,11,0,11,3,4,5,11,2,11,1,5,1,11,-1},
|
||||
{0,2,5,0,5,9,2,11,5,4,5,8,11,8,5,-1},
|
||||
{9,4,5,2,11,3,-1,-1,-1,-1,-1,-1,-1,-1,-1},
|
||||
{2,5,10,3,5,2,3,4,5,3,8,4,-1,-1,-1,-1},
|
||||
{5,10,2,5,2,4,4,2,0,-1,-1,-1,-1,-1,-1,-1},
|
||||
{3,10,2,3,5,10,3,8,5,4,5,8,0,1,9,-1},
|
||||
{5,10,2,5,2,4,1,9,2,9,4,2,-1,-1,-1,-1},
|
||||
{8,4,5,8,5,3,3,5,1,-1,-1,-1,-1,-1,-1,-1},
|
||||
{0,4,5,1,0,5,-1,-1,-1,-1,-1,-1,-1,-1,-1},
|
||||
{8,4,5,8,5,3,9,0,5,0,3,5,-1,-1,-1,-1},
|
||||
{9,4,5,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
|
||||
{4,11,7,4,9,11,9,10,11,-1,-1,-1,-1,-1,-1},
|
||||
{0,8,3,4,9,7,9,11,7,9,10,11,-1,-1,-1,-1},
|
||||
{1,10,11,1,11,4,1,4,0,7,4,11,-1,-1,-1,-1},
|
||||
{3,1,4,3,4,8,1,10,4,7,4,11,10,11,4,-1},
|
||||
{4,11,7,9,11,4,9,2,11,9,1,2,-1,-1,-1,-1},
|
||||
{9,7,4,9,11,7,9,1,11,2,11,1,0,8,3,-1},
|
||||
{11,7,4,11,4,2,2,4,0,-1,-1,-1,-1,-1,-1,-1},
|
||||
{11,7,4,11,4,2,8,3,4,3,2,4,-1,-1,-1,-1},
|
||||
{2,9,10,2,7,9,2,3,7,7,4,9,-1,-1,-1,-1},
|
||||
{9,10,7,9,7,4,10,2,7,8,7,0,2,0,7,-1},
|
||||
{3,7,10,3,10,2,7,4,10,1,10,0,4,0,10,-1},
|
||||
{1,10,2,8,7,4,-1,-1,-1,-1,-1,-1,-1,-1,-1},
|
||||
{4,9,1,4,1,7,7,1,3,-1,-1,-1,-1,-1,-1,-1},
|
||||
{4,9,1,4,1,7,0,8,1,8,7,1,-1,-1,-1,-1},
|
||||
{4,0,3,7,4,3,-1,-1,-1,-1,-1,-1,-1,-1,-1},
|
||||
{4,8,7,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
|
||||
{9,10,8,10,11,8,-1,-1,-1,-1,-1,-1,-1,-1,-1},
|
||||
{3,0,9,3,9,11,11,9,10,-1,-1,-1,-1,-1,-1,-1},
|
||||
{0,1,10,0,10,8,8,10,11,-1,-1,-1,-1,-1,-1,-1},
|
||||
{3,1,10,11,3,10,-1,-1,-1,-1,-1,-1,-1,-1,-1},
|
||||
{1,2,11,1,11,9,9,11,8,-1,-1,-1,-1,-1,-1,-1},
|
||||
{3,0,9,3,9,11,1,2,9,2,11,9,-1,-1,-1,-1},
|
||||
{0,2,11,8,0,11,-1,-1,-1,-1,-1,-1,-1,-1,-1},
|
||||
{3,2,11,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
|
||||
{2,3,8,2,8,10,10,8,9,-1,-1,-1,-1,-1,-1,-1},
|
||||
{9,10,2,0,9,2,-1,-1,-1,-1,-1,-1,-1,-1,-1},
|
||||
{2,3,8,2,8,10,0,1,8,1,10,8,-1,-1,-1,-1},
|
||||
{1,10,2,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
|
||||
{1,3,8,9,1,8,-1,-1,-1,-1,-1,-1,-1,-1,-1},
|
||||
{0,9,1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
|
||||
{0,3,8,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
|
||||
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
|
||||
};
|
||||
// clang-format on
|
||||
@@ -0,0 +1,68 @@
|
||||
import FluidGridData;
|
||||
|
||||
// Diagnostics-only: sums the interior of several fields so we can watch
|
||||
// "mass" over time on the CPU. Not part of the simulation.
|
||||
struct Params
|
||||
{
|
||||
// read-only
|
||||
FluidGridData<float> density;
|
||||
FluidGridData<float> phi;
|
||||
FluidGridData<float> velocityX;
|
||||
FluidGridData<float> velocityY;
|
||||
FluidGridData<float> velocityZ;
|
||||
// read-write: [0]=density sum, [1]=phi sum, [2]=|velocity| sum
|
||||
RWStructuredBuffer<float> out;
|
||||
};
|
||||
ParameterBlock<Params> params;
|
||||
|
||||
// Reduce the 32x8 thread group via shared memory, then one atomic add per group.
|
||||
groupshared float laneD[256];
|
||||
groupshared float laneP[256];
|
||||
groupshared float laneV[256];
|
||||
// One thread group per z-slice; each thread covers a 32x8 tile of the x/y plane.
|
||||
[numthreads(32, 8, 1)]
|
||||
[shader("compute")]
|
||||
void massProbe(uint3 dispatchThreadID : SV_DispatchThreadID)
|
||||
{
|
||||
FluidGridData<float> density = params.density;
|
||||
FluidGridData<float> phi = params.phi;
|
||||
FluidGridData<float> velocityX = params.velocityX;
|
||||
FluidGridData<float> velocityY = params.velocityY;
|
||||
FluidGridData<float> velocityZ = params.velocityZ;
|
||||
RWStructuredBuffer<float> out = params.out;
|
||||
|
||||
// Interior only: skip the 1-cell boundary shell (matches the other passes).
|
||||
int x = dispatchThreadID.x + 1;
|
||||
int y = dispatchThreadID.y + 1;
|
||||
int z = dispatchThreadID.z + 1;
|
||||
if (x >= gridParams.gridSize.x - 1 || y >= gridParams.gridSize.y - 1 || z >= gridParams.gridSize.z - 1)
|
||||
return;
|
||||
|
||||
float dSum = density[x, y, z];
|
||||
float pSum = phi[x, y, z];
|
||||
float vSum = sqrt(velocityX[x, y, z] * velocityX[x, y, z] +
|
||||
velocityY[x, y, z] * velocityY[x, y, z] +
|
||||
velocityZ[x, y, z] * velocityZ[x, y, z]);
|
||||
|
||||
|
||||
uint lane = dispatchThreadID.x + dispatchThreadID.y * 32; // 0..255
|
||||
laneD[lane] = dSum;
|
||||
laneP[lane] = pSum;
|
||||
laneV[lane] = vSum;
|
||||
GroupMemoryBarrierWithGroupSync();
|
||||
|
||||
// Lane 0 of the group sums all 256 lanes and atomically adds to the global total.
|
||||
if (lane == 0)
|
||||
{
|
||||
float td = 0.0f, tp = 0.0f, tv = 0.0f;
|
||||
for (uint i = 0; i < 256; ++i)
|
||||
{
|
||||
td += laneD[i];
|
||||
tp += laneP[i];
|
||||
tv += laneV[i];
|
||||
}
|
||||
InterlockedAdd(out[0], td);
|
||||
InterlockedAdd(out[1], tp);
|
||||
InterlockedAdd(out[2], tv);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import FluidGridData;
|
||||
|
||||
struct Params
|
||||
{
|
||||
// read-write
|
||||
FluidGridData<float> velocityX;
|
||||
// read-write
|
||||
FluidGridData<float> velocityY;
|
||||
// read-write
|
||||
FluidGridData<float> velocityZ;
|
||||
// read-only
|
||||
FluidGridData<float> pressure;
|
||||
};
|
||||
ParameterBlock<Params> params;
|
||||
|
||||
[shader("compute")]
|
||||
[numthreads(32, 8, 1)]
|
||||
void project(uint3 dispatchThreadID : SV_DispatchThreadID)
|
||||
{
|
||||
FluidGridData<float> velocityX = params.velocityX;
|
||||
FluidGridData<float> velocityY = params.velocityY;
|
||||
FluidGridData<float> velocityZ = params.velocityZ;
|
||||
FluidGridData<float> pressure = params.pressure;
|
||||
|
||||
int x = dispatchThreadID.x + 1;
|
||||
int y = dispatchThreadID.y + 1;
|
||||
int z = dispatchThreadID.z + 1;
|
||||
if(x >= gridParams.gridSize.x - 1 || y >= gridParams.gridSize.y - 1 || z >= gridParams.gridSize.z - 1) return;
|
||||
|
||||
velocityX[x, y, z] -= 0.5f * (pressure[x + 1, y, z] - pressure[x - 1, y, z]);
|
||||
velocityY[x, y, z] -= 0.5f * (pressure[x, y + 1, z] - pressure[x, y - 1, z]);
|
||||
velocityZ[x, y, z] -= 0.5f * (pressure[x, y, z + 1] - pressure[x, y, z - 1]);
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import Common;
|
||||
import FluidGridData;
|
||||
import LightEnv;
|
||||
import MaterialParameter;
|
||||
|
||||
struct Params
|
||||
{
|
||||
float4x4 transform;
|
||||
StructuredBuffer<float> vertexBuffer;
|
||||
StructuredBuffer<float> normalBuffer;
|
||||
StructuredBuffer<uint> indexBuffer;
|
||||
};
|
||||
ParameterBlock<Params> params;
|
||||
|
||||
struct VertexOut
|
||||
{
|
||||
float3 position_WS : POSITION;
|
||||
float4 position_CS : SV_Position;
|
||||
float3 normal : NORMAL;
|
||||
};
|
||||
|
||||
[shader("vertex")]
|
||||
VertexOut vertexMain(uint vertexId : SV_VertexID)
|
||||
{
|
||||
VertexOut output;
|
||||
uint index = params.indexBuffer[vertexId];
|
||||
float3 vertex = float3(params.vertexBuffer[index * 3 + 0],
|
||||
params.vertexBuffer[index * 3 + 1],
|
||||
params.vertexBuffer[index * 3 + 2]);
|
||||
float3 normal = float3(params.normalBuffer[index * 3 + 0],
|
||||
params.normalBuffer[index * 3 + 1],
|
||||
params.normalBuffer[index * 3 + 2]);
|
||||
vertex = mul(params.transform, float4(vertex, 1)).xyz;
|
||||
normal = mul((float3x3)params.transform, normal);
|
||||
output.position_WS = vertex;
|
||||
output.position_CS = mul(pViewParams.viewProjectionMatrix, float4(vertex, 1));
|
||||
output.normal = normal;
|
||||
return output;
|
||||
}
|
||||
|
||||
[shader("pixel")]
|
||||
float4 fragmentMain(VertexOut input) : SV_Target
|
||||
{
|
||||
BlinnPhong brdf;
|
||||
brdf.baseColor = float3(0, 0, 1);
|
||||
brdf.alpha = 1;
|
||||
brdf.specularColor = float3(1, 1, 1);
|
||||
brdf.normal = input.normal;
|
||||
brdf.shininess = 32;
|
||||
brdf.ambient = float3(0.1, 0.1, 0.1);
|
||||
brdf.emissive = float3(0, 0, 0);
|
||||
float3 result = float3(0, 0, 0);
|
||||
float3 viewDir = normalize(pViewParams.cameraPosition_WS.xyz - input.position_WS);
|
||||
for(int i = 0; i < pLightEnv.numDirectionalLights; i++)
|
||||
{
|
||||
LightingParameter lightParams;
|
||||
lightParams.position_WS = input.position_WS;
|
||||
lightParams.viewDir_WS = viewDir;
|
||||
result += pLightEnv.directionalLights[i].illuminate(lightParams, brdf);
|
||||
}
|
||||
return float4(result, 1);
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
import FluidGridData;
|
||||
|
||||
struct BoundaryPlane
|
||||
{
|
||||
float3 normal; // inward normal (points from solid toward fluid)
|
||||
float d; // plane offset: dot(normal, cellPos) + d < 0 means solid
|
||||
};
|
||||
|
||||
struct Params
|
||||
{
|
||||
int b;
|
||||
uint numPlanes;
|
||||
StructuredBuffer<BoundaryPlane> planes;
|
||||
// read-write
|
||||
FluidGridData<float> grid;
|
||||
};
|
||||
ParameterBlock<Params> params;
|
||||
|
||||
// Find the interior (fluid) neighbor of a solid cell by stepping along the
|
||||
// dominant axis of the plane inward normal.
|
||||
int3 getInteriorNeighbor(int3 pos, float3 normal)
|
||||
{
|
||||
float3 absN = abs(normal);
|
||||
int3 step;
|
||||
if (absN.x >= absN.y && absN.x >= absN.z)
|
||||
step = int3(normal.x > 0 ? 1 : -1, 0, 0);
|
||||
else if (absN.y >= absN.z)
|
||||
step = int3(0, normal.y > 0 ? 1 : -1, 0);
|
||||
else
|
||||
step = int3(0, 0, normal.z > 0 ? 1 : -1);
|
||||
|
||||
return clamp(pos + step, int3(0), int3(gridParams.gridSize) - 1);
|
||||
}
|
||||
|
||||
// Compute the boundary value scaling factor for velocity component b.
|
||||
// For b=0 (scalar): factor = 1 (Neumann / copy).
|
||||
// For b=1,2,3 (velocity x,y,z): reflects the normal component so that
|
||||
// velocity normal to the plane is negated while tangential parts are preserved.
|
||||
float getBoundaryFactor(int b, float3 normal)
|
||||
{
|
||||
if (b == 0) return 1.0f;
|
||||
float nComp = (b == 1) ? normal.x : ((b == 2) ? normal.y : normal.z);
|
||||
return 1.0f - 2.0f * nComp * nComp;
|
||||
}
|
||||
|
||||
[shader("compute")]
|
||||
[numthreads(4, 4, 4)]
|
||||
void setBound(uint3 dispatchThreadID : SV_DispatchThreadID)
|
||||
{
|
||||
int3 pos = int3(dispatchThreadID);
|
||||
if (any(uint3(pos) >= gridParams.gridSize))
|
||||
return;
|
||||
|
||||
int b = params.b;
|
||||
FluidGridData<float> grid = params.grid;
|
||||
float3 cellPos = float3(pos);
|
||||
|
||||
int numAffecting = 0;
|
||||
float valueSum = 0.0f;
|
||||
|
||||
for (uint p = 0; p < params.numPlanes; p++)
|
||||
{
|
||||
BoundaryPlane plane = params.planes[p];
|
||||
float dist = dot(plane.normal, cellPos) + plane.d;
|
||||
|
||||
if (dist < 0.0f) // cell is on the solid side
|
||||
{
|
||||
int3 neighbor = getInteriorNeighbor(pos, plane.normal);
|
||||
float neighborVal = grid[uint3(neighbor)];
|
||||
float factor = getBoundaryFactor(b, plane.normal);
|
||||
|
||||
valueSum += factor * neighborVal;
|
||||
numAffecting++;
|
||||
}
|
||||
}
|
||||
|
||||
if (numAffecting > 0)
|
||||
{
|
||||
// For all quantities (velocity components AND scalars: pressure,
|
||||
// divergence, density) the boundary cell takes the (factor-scaled)
|
||||
// interior neighbor value. For scalars the factor is 1 (Neumann / copy),
|
||||
// which is the correct boundary condition for the pressure Poisson solve
|
||||
// (zero normal gradient) and for the divergence. Do NOT zero the scalar
|
||||
// boundary: zeroing the pressure shell breaks the Poisson Neumann
|
||||
// condition, corrupts the projection, and injects energy into the
|
||||
// velocity field (observed as |vel|_sum runaway).
|
||||
grid[uint3(pos)] = valueSum / float(numAffecting);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import FluidGridData;
|
||||
|
||||
struct Params
|
||||
{
|
||||
float dtau;
|
||||
// read-write: phi being updated (output)
|
||||
FluidGridData<float> phi;
|
||||
// read-only: phi from previous iteration (for gradient computation)
|
||||
FluidGridData<float> phiPrev;
|
||||
// read-only: phi snapshot from before reinitialization (for sign function)
|
||||
FluidGridData<float> phiSign;
|
||||
};
|
||||
ParameterBlock<Params> params;
|
||||
|
||||
// Smooth sign function to avoid discontinuity at zero
|
||||
float smoothSign(float x, float dx)
|
||||
{
|
||||
return x / sqrt(x * x + dx * dx);
|
||||
}
|
||||
|
||||
[shader("compute")]
|
||||
[numthreads(32, 8, 1)]
|
||||
void reinitialize(uint3 dispatchThreadID : SV_DispatchThreadID)
|
||||
{
|
||||
uint x = dispatchThreadID.x + 1;
|
||||
uint y = dispatchThreadID.y + 1;
|
||||
uint z = dispatchThreadID.z + 1;
|
||||
FluidGridData<float> phi = params.phi;
|
||||
FluidGridData<float> phiPrev = params.phiPrev;
|
||||
FluidGridData<float> phiSign = params.phiSign;
|
||||
if(x >= gridParams.gridSize.x - 1 || y >= gridParams.gridSize.y - 1 || z >= gridParams.gridSize.z - 1) return;
|
||||
|
||||
float dtau = params.dtau;
|
||||
float dx = 1.0f;
|
||||
|
||||
// Current value from previous iteration, sign from original snapshot
|
||||
float p = phiPrev[x, y, z];
|
||||
float s = smoothSign(phiSign[x, y, z], dx);
|
||||
|
||||
// Upwind finite differences for |grad phi| from previous iteration
|
||||
float dxp = phiPrev[x + 1, y, z] - p;
|
||||
float dxm = p - phiPrev[x - 1, y, z];
|
||||
float dyp = phiPrev[x, y + 1, z] - p;
|
||||
float dym = p - phiPrev[x, y - 1, z];
|
||||
float dzp = phiPrev[x, y, z + 1] - p;
|
||||
float dzm = p - phiPrev[x, y, z - 1];
|
||||
|
||||
// Godunov upwind scheme
|
||||
float gradPhi;
|
||||
if (s > 0)
|
||||
{
|
||||
float ax = max(max(dxm, 0.0f), -min(dxp, 0.0f));
|
||||
float ay = max(max(dym, 0.0f), -min(dyp, 0.0f));
|
||||
float az = max(max(dzm, 0.0f), -min(dzp, 0.0f));
|
||||
gradPhi = sqrt(ax * ax + ay * ay + az * az) / dx;
|
||||
}
|
||||
else
|
||||
{
|
||||
float ax = max(-min(dxm, 0.0f), max(dxp, 0.0f));
|
||||
float ay = max(-min(dym, 0.0f), max(dyp, 0.0f));
|
||||
float az = max(-min(dzm, 0.0f), max(dzp, 0.0f));
|
||||
gradPhi = sqrt(ax * ax + ay * ay + az * az) / dx;
|
||||
}
|
||||
|
||||
// Update: push |grad phi| toward 1
|
||||
phi[x, y, z] = p - dtau * s * (gradPhi - 1.0f);
|
||||
}
|
||||
@@ -21,7 +21,6 @@ struct ViewParameter
|
||||
uint frameIndex;
|
||||
float time;
|
||||
};
|
||||
layout(set=0)
|
||||
ParameterBlock<ViewParameter> pViewParams;
|
||||
|
||||
float4 worldToModel(float4x4 inverseTransform, float4 world)
|
||||
|
||||
@@ -71,7 +71,6 @@ struct LightEnv
|
||||
Texture2D brdfLUT;
|
||||
SamplerState lutSampler;
|
||||
};
|
||||
layout(set=3)
|
||||
ParameterBlock<LightEnv> pLightEnv;
|
||||
|
||||
interface IBRDF
|
||||
@@ -360,7 +359,9 @@ struct CookTorrance : IBRDF
|
||||
const float MAX_REFLECTION_LOD = 4;
|
||||
float3 prefilteredColor = pLightEnv.prefilteredMap.SampleLevel(pLightEnv.irradianceSampler, r, roughness * MAX_REFLECTION_LOD).xyz;
|
||||
|
||||
float2 envBRDF = pLightEnv.brdfLUT.Sample(pLightEnv.lutSampler, float2(max(dot(normal, viewDir_WS), 0), roughness)).rg;
|
||||
// brdfLUT has no mip levels and is indexed analytically (N·V, roughness) with no screen
|
||||
// derivatives, so implicit LOD is unavailable (GLCompute/Ray) and meaningless: use level 0.
|
||||
float2 envBRDF = pLightEnv.brdfLUT.SampleLevel(pLightEnv.lutSampler, float2(max(dot(normal, viewDir_WS), 0), roughness), 0).rg;
|
||||
float3 specular = prefilteredColor * (F * envBRDF.x + envBRDF.y);
|
||||
|
||||
return (k_d * diffuse + specular) * ambientOcclusion;
|
||||
|
||||
@@ -14,7 +14,6 @@ struct MaterialResources
|
||||
SamplerState samplerArray[512];
|
||||
StructuredBuffer<float> floatArray;
|
||||
};
|
||||
layout(set=4)
|
||||
ParameterBlock<MaterialResources> pResources;
|
||||
|
||||
Texture2D getMaterialTextureParameter(uint index)
|
||||
|
||||
+15
-14
@@ -45,20 +45,6 @@ struct MeshletCullingInfo
|
||||
}
|
||||
};
|
||||
|
||||
struct DrawCallOffsets
|
||||
{
|
||||
uint instanceOffset;
|
||||
uint textureOffset;
|
||||
uint samplerOffset;
|
||||
uint floatOffset;
|
||||
};
|
||||
#ifdef RAY_TRACING
|
||||
layout(shaderRecordEXT)
|
||||
#else
|
||||
layout(push_constant)
|
||||
#endif
|
||||
ConstantBuffer<DrawCallOffsets> pOffsets;
|
||||
|
||||
struct Scene
|
||||
{
|
||||
StructuredBuffer<float> positions;
|
||||
@@ -73,6 +59,21 @@ struct Scene
|
||||
};
|
||||
ParameterBlock<Scene> pScene;
|
||||
|
||||
struct DrawCallOffsets
|
||||
{
|
||||
uint instanceOffset;
|
||||
uint textureOffset;
|
||||
uint samplerOffset;
|
||||
uint floatOffset;
|
||||
};
|
||||
#ifdef RAY_TRACING
|
||||
// Shader record buffers are accessed via a different mechanism and don't use descriptor set bindings
|
||||
layout(shaderRecordEXT)
|
||||
#else
|
||||
layout(push_constant)
|
||||
#endif
|
||||
ConstantBuffer<DrawCallOffsets> pOffsets;
|
||||
|
||||
uint32_t encodePrimitive(uint32_t meshletId)
|
||||
{
|
||||
return meshletId;
|
||||
|
||||
@@ -34,5 +34,4 @@ struct StaticMeshVertexData
|
||||
StructuredBuffer<uint16_t> color;
|
||||
StructuredBuffer<uint16_t> texCoords[MAX_TEXCOORDS];
|
||||
};
|
||||
layout(set = 1)
|
||||
ParameterBlock<StaticMeshVertexData> pVertexData;
|
||||
@@ -1,12 +1,12 @@
|
||||
import Common;
|
||||
import MaterialParameter;
|
||||
import LightEnv;
|
||||
import Scene;
|
||||
import RayTracingData;
|
||||
import VertexData;
|
||||
import Material;
|
||||
import StaticMeshVertexData;
|
||||
import MATERIAL_FILE_NAME;
|
||||
import RayTracingData;
|
||||
import Scene;
|
||||
|
||||
// simplification: all BLAS only have 1 geometry
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ void miss(inout RayPayload p)
|
||||
// p.shading.normal = -WorldRayDirection();
|
||||
// p.shading.normalLight = -WorldRayDirection();
|
||||
// p.material.color = float4(0, 0, 0, 0);
|
||||
p.light = float3(pRayTracingParams.skyBox.Sample(pRayTracingParams.skyBoxSampler, WorldRayDirection()).xyz);
|
||||
// miss shaders (GLCompute) can't do ImplicitLod (mip) sampling; use a fixed level
|
||||
p.light = float3(pRayTracingParams.skyBox.SampleLevel(pRayTracingParams.skyBoxSampler, WorldRayDirection(), 0).xyz);
|
||||
p.hit = false;
|
||||
}
|
||||
@@ -9,7 +9,6 @@ struct RayTracingParams
|
||||
TextureCube<float4> skyBox;
|
||||
SamplerState skyBoxSampler;
|
||||
};
|
||||
layout(set=5)
|
||||
ParameterBlock<RayTracingParams> pRayTracingParams;
|
||||
|
||||
struct RayPayload
|
||||
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
shaders/
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
textures/
|
||||
@@ -1,12 +1,13 @@
|
||||
#include "PlayView.h"
|
||||
#include "Scene/Scene.h"
|
||||
#include "Window/Window.h"
|
||||
#include <fmt/format.h>
|
||||
#include <fstream>
|
||||
|
||||
using namespace Seele;
|
||||
|
||||
PlayView::PlayView(Gfx::PGraphics graphics, PWindow window, const ViewportCreateInfo& createInfo, std::string dllPath, bool useMeshCulling)
|
||||
: GameView(graphics, window, createInfo, dllPath) {
|
||||
PlayView::PlayView(Gfx::PGraphics graphics, PWindow window, PScene scene, const ViewportCreateInfo& createInfo, bool useMeshCulling)
|
||||
: GameView(graphics, window, scene, createInfo) {
|
||||
getGlobals().useDepthCulling = useMeshCulling;
|
||||
renderTimestamp = graphics->createTimestampQuery(2, "RenderTimestamp");
|
||||
queryThread = std::thread([&]() {
|
||||
@@ -78,5 +79,3 @@ void PlayView::render() {
|
||||
GameView::render();
|
||||
renderTimestamp->write(Gfx::SE_PIPELINE_STAGE_TOP_OF_PIPE_BIT, "RenderEnd");
|
||||
}
|
||||
|
||||
void PlayView::keyCallback(KeyCode code, InputAction action, KeyModifier modifier) { GameView::keyCallback(code, action, modifier); }
|
||||
@@ -4,7 +4,7 @@
|
||||
namespace Seele {
|
||||
class PlayView : public GameView {
|
||||
public:
|
||||
PlayView(Gfx::PGraphics graphics, PWindow window, const ViewportCreateInfo& createInfo, std::string dllPath, bool useMeshCulling);
|
||||
PlayView(Gfx::PGraphics graphics, PWindow window, PScene scene, const ViewportCreateInfo& createInfo, bool useMeshCulling);
|
||||
virtual ~PlayView();
|
||||
virtual void beginUpdate() override;
|
||||
virtual void update() override;
|
||||
@@ -12,8 +12,6 @@ class PlayView : public GameView {
|
||||
|
||||
virtual void prepareRender() override;
|
||||
virtual void render() override;
|
||||
|
||||
virtual void keyCallback(Seele::KeyCode code, Seele::InputAction action, Seele::KeyModifier modifier) override;
|
||||
|
||||
private:
|
||||
std::thread queryThread;
|
||||
|
||||
+15
-7
@@ -3,7 +3,9 @@
|
||||
#include "Graphics/StaticMeshVertexData.h"
|
||||
#include "Graphics/Vulkan/Graphics.h"
|
||||
#include "PlayView.h"
|
||||
#include "Window/WindowManager.h"
|
||||
#include "Scene/Scene.h"
|
||||
#include "System/SystemGraph.h"
|
||||
#include "Window/Application.h"
|
||||
#include <fmt/core.h>
|
||||
#include <random>
|
||||
|
||||
@@ -32,7 +34,14 @@ int main(int argc, char** argv) {
|
||||
vd->init(graphics);
|
||||
getGlobals().useRayTracing = true;
|
||||
|
||||
OWindowManager windowManager = new WindowManager();
|
||||
// The benchmark is a worldless host: it builds a plain Scene + SystemGraph
|
||||
// (no game binary) and hands ownership to the Application, which then steps
|
||||
// it once per frame and lets the views render it. The view renders the
|
||||
// non-owning application->scene() handle.
|
||||
OApplication application = new Application();
|
||||
OScene scene = new Scene(graphics);
|
||||
OSystemGraph systemGraph = new SystemGraph();
|
||||
application->attachWorld(std::move(scene), std::move(systemGraph));
|
||||
AssetRegistry::init("Assets", graphics);
|
||||
vd->commitMeshes();
|
||||
WindowCreateInfo mainWindowInfo = {
|
||||
@@ -41,7 +50,7 @@ int main(int argc, char** argv) {
|
||||
.title = "Benchmark",
|
||||
.preferredFormat = Gfx::SE_FORMAT_B8G8R8A8_SRGB,
|
||||
};
|
||||
auto window = windowManager->addWindow(graphics, mainWindowInfo);
|
||||
auto window = application->addWindow(graphics, mainWindowInfo);
|
||||
ViewportCreateInfo sceneViewInfo = {
|
||||
.dimensions =
|
||||
{
|
||||
@@ -49,11 +58,10 @@ int main(int argc, char** argv) {
|
||||
.offset = {0, 0},
|
||||
},
|
||||
};
|
||||
OGameView sceneView = new PlayView(graphics, window, sceneViewInfo, binaryPath.generic_string(), useDepthCulling);
|
||||
sceneView->setFocused();
|
||||
OGameView sceneView = new PlayView(graphics, window, application->scene(), sceneViewInfo, useDepthCulling);
|
||||
|
||||
while (windowManager->isActive()) {
|
||||
windowManager->render();
|
||||
while (application->isActive()) {
|
||||
application->render();
|
||||
}
|
||||
graphics->waitDeviceIdle();
|
||||
vd->destroy();
|
||||
|
||||
@@ -93,7 +93,6 @@ EnvironmentLoader::EnvironmentLoader(Gfx::PGraphics graphics) : graphics(graphic
|
||||
{"precomputeBRDF", "EnvironmentMapping"},
|
||||
},
|
||||
.rootSignature = cubePipelineLayout,
|
||||
.dumpIntermediate = true,
|
||||
});
|
||||
cubePipelineLayout->create();
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
#include "Graphics/Shader.h"
|
||||
#include "Material/Material.h"
|
||||
#include "Material/ShaderExpression.h"
|
||||
#include "Window/WindowManager.h"
|
||||
#include "Window/Application.h"
|
||||
#include <fmt/core.h>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
|
||||
@@ -6,7 +6,6 @@
|
||||
#include "Graphics/Mesh.h"
|
||||
#include "Graphics/Shader.h"
|
||||
#include "Graphics/StaticMeshVertexData.h"
|
||||
#include "ThreadPool.h"
|
||||
#include <Asset/MaterialLoader.h>
|
||||
#include <Asset/TextureLoader.h>
|
||||
#include <assimp/Importer.hpp>
|
||||
@@ -14,10 +13,9 @@
|
||||
#include <assimp/material.h>
|
||||
#include <assimp/postprocess.h>
|
||||
#include <assimp/scene.h>
|
||||
#include <fmt/core.h>
|
||||
#include <fmt/format.h>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <set>
|
||||
#include <stb_image_write.h>
|
||||
|
||||
using namespace Seele;
|
||||
|
||||
@@ -114,7 +114,7 @@ void TextureLoader::import(TextureImportArgs args, PTextureAsset textureAsset) {
|
||||
.uastcFlags = KTX_PACK_UASTC_LEVEL_DEFAULT,
|
||||
.uastcRDO = true,
|
||||
};
|
||||
KTX_ASSERT(ktxTexture2_CompressBasisEx(kTexture, &basisParams));
|
||||
// KTX_ASSERT(ktxTexture2_CompressBasis(kTexture, 0));
|
||||
//KTX_ASSERT(ktxTexture2_DeflateZstd(kTexture, 10));
|
||||
|
||||
char writer[100];
|
||||
|
||||
@@ -3,4 +3,6 @@ add_subdirectory(Window/)
|
||||
|
||||
target_sources(Editor
|
||||
PRIVATE
|
||||
main.cpp)
|
||||
main.cpp
|
||||
ComponentRegistry.h
|
||||
ComponentRegistry.cpp)
|
||||
@@ -0,0 +1,208 @@
|
||||
#include "ComponentRegistry.h"
|
||||
#include "Asset/MeshAsset.h"
|
||||
#include "Component/Camera.h"
|
||||
#include "Component/DirectionalLight.h"
|
||||
#include "Component/Mesh.h"
|
||||
#include "Component/PointLight.h"
|
||||
#include "Component/Transform.h"
|
||||
#include <ostream>
|
||||
#include <sstream>
|
||||
|
||||
using namespace Seele;
|
||||
using namespace Seele::Editor;
|
||||
|
||||
// --- small formatting helpers ------------------------------------------------------
|
||||
namespace {
|
||||
// Render a glm::vec / Quaternion (which all have operator<<) into a trimmed string.
|
||||
template <typename T>
|
||||
std::string fmtVec(const T& v) {
|
||||
std::ostringstream oss;
|
||||
oss.precision(4);
|
||||
oss << std::fixed << v;
|
||||
return oss.str();
|
||||
}
|
||||
|
||||
std::string fmtFloat(float f) {
|
||||
std::ostringstream oss;
|
||||
oss.precision(4);
|
||||
oss << std::fixed << f;
|
||||
return oss.str();
|
||||
}
|
||||
} // namespace
|
||||
|
||||
// All of the editor's component-inspection entry points live in Seele::Editor (matching the
|
||||
// declarations in ComponentRegistry.h). The using-directives above (using namespace Seele;
|
||||
// using namespace Seele::Editor;) make the types (PEntity, PScene, ComponentEntry, Array,
|
||||
// glm, the Component::* types) resolvable unqualified inside this block, while the function
|
||||
// *definitions* themselves are correctly placed in the same namespace as their declarations -
|
||||
// no duplicate/ambiguous global-scope symbols.
|
||||
namespace Seele {
|
||||
namespace Editor {
|
||||
|
||||
std::vector<ComponentEntry>& componentCatalog() {
|
||||
static std::vector<ComponentEntry> catalog;
|
||||
return catalog;
|
||||
}
|
||||
|
||||
void initComponentRegistry() {
|
||||
auto& catalog = componentCatalog();
|
||||
// Idempotent: build the catalog only once. The set of displayable component *types* is
|
||||
// fixed for the editor's lifetime, so we never add to it after the first call.
|
||||
if (!catalog.empty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Every entry works through the handle's own hasComponent/accessComponent - the exact
|
||||
// same call shape game code uses to read components, just applied to an OEntity view.
|
||||
|
||||
// Transform: position / rotation / scale. The single most important component to
|
||||
// display - every placed actor has one.
|
||||
catalog.push_back(ComponentEntry{
|
||||
.name = "Transform",
|
||||
.isAttached = [](PEntity e) -> bool { return e != nullptr && e->hasComponent<Component::Transform>(); },
|
||||
.describe = [](PEntity e) -> std::string {
|
||||
if (e == nullptr || !e->hasComponent<Component::Transform>()) {
|
||||
return "";
|
||||
}
|
||||
const auto& t = e->accessComponent<Component::Transform>();
|
||||
std::ostringstream oss;
|
||||
oss << "Position: " << fmtVec(t.getPosition()) << "\n";
|
||||
oss << "Rotation: " << fmtVec(t.getRotation()) << "\n";
|
||||
oss << "Scale: " << fmtVec(t.getScale());
|
||||
return oss.str();
|
||||
},
|
||||
});
|
||||
|
||||
// Camera: projection params.
|
||||
catalog.push_back(ComponentEntry{
|
||||
.name = "Camera",
|
||||
.isAttached = [](PEntity e) -> bool { return e != nullptr && e->hasComponent<Component::Camera>(); },
|
||||
.describe = [](PEntity e) -> std::string {
|
||||
if (e == nullptr || !e->hasComponent<Component::Camera>()) {
|
||||
return "";
|
||||
}
|
||||
const auto& c = e->accessComponent<Component::Camera>();
|
||||
std::ostringstream oss;
|
||||
oss << "Field Of View (deg): " << fmtFloat(glm::degrees(c.fieldOfView)) << "\n";
|
||||
oss << "Aspect Ratio: " << fmtFloat(c.aspectRatio) << "\n";
|
||||
oss << "Near Plane: " << fmtFloat(c.nearPlane) << "\n";
|
||||
oss << "Far Plane: " << fmtFloat(c.farPlane) << "\n";
|
||||
oss << "Main Camera: " << (c.mainCamera ? "true" : "false");
|
||||
return oss.str();
|
||||
},
|
||||
});
|
||||
|
||||
// PointLight: color + intensity + attenuation.
|
||||
catalog.push_back(ComponentEntry{
|
||||
.name = "PointLight",
|
||||
.isAttached = [](PEntity e) -> bool { return e != nullptr && e->hasComponent<Component::PointLight>(); },
|
||||
.describe = [](PEntity e) -> std::string {
|
||||
if (e == nullptr || !e->hasComponent<Component::PointLight>()) {
|
||||
return "";
|
||||
}
|
||||
const auto& l = e->accessComponent<Component::PointLight>();
|
||||
std::ostringstream oss;
|
||||
oss << "Color: " << fmtVec(l.color) << "\n";
|
||||
oss << "Intensity: " << fmtFloat(l.intensity) << "\n";
|
||||
oss << "Attenuation: " << fmtFloat(l.attenuation);
|
||||
return oss.str();
|
||||
},
|
||||
});
|
||||
|
||||
// DirectionalLight: color + intensity.
|
||||
catalog.push_back(ComponentEntry{
|
||||
.name = "DirectionalLight",
|
||||
.isAttached = [](PEntity e) -> bool { return e != nullptr && e->hasComponent<Component::DirectionalLight>(); },
|
||||
.describe = [](PEntity e) -> std::string {
|
||||
if (e == nullptr || !e->hasComponent<Component::DirectionalLight>()) {
|
||||
return "";
|
||||
}
|
||||
const auto& l = e->accessComponent<Component::DirectionalLight>();
|
||||
std::ostringstream oss;
|
||||
oss << "Color: " << fmtVec(l.color) << "\n";
|
||||
oss << "Intensity: " << fmtFloat(l.intensity);
|
||||
return oss.str();
|
||||
},
|
||||
});
|
||||
|
||||
// Mesh (static): the mesh asset's name/folder + staticness + meshlet count.
|
||||
catalog.push_back(ComponentEntry{
|
||||
.name = "Mesh",
|
||||
.isAttached = [](PEntity e) -> bool { return e != nullptr && e->hasComponent<Component::Mesh>(); },
|
||||
.describe = [](PEntity e) -> std::string {
|
||||
if (e == nullptr || !e->hasComponent<Component::Mesh>()) {
|
||||
return "";
|
||||
}
|
||||
const auto& m = e->accessComponent<Component::Mesh>();
|
||||
std::ostringstream oss;
|
||||
oss << "Asset: ";
|
||||
if (m.asset != nullptr) {
|
||||
oss << m.asset->getFolderPath() << "/" << m.asset->getName();
|
||||
} else {
|
||||
oss << "(none)";
|
||||
}
|
||||
oss << "\n";
|
||||
oss << "Static: " << (m.isStatic ? "true" : "false") << "\n";
|
||||
oss << "Meshlets: " << m.meshletOffsets.size();
|
||||
return oss.str();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
std::vector<EntityInfo> enumerateEntities(const PScene& scene) {
|
||||
std::vector<EntityInfo> out;
|
||||
if (scene == nullptr) {
|
||||
return out;
|
||||
}
|
||||
// The scene's roster is the source of truth for "what entities exist" - this is the
|
||||
// "OEntity you can query via the scene" the user asked for. We iterate handles (PEntity
|
||||
// views), never entt ids. The roster is appended in creation order and pruned on
|
||||
// destroy, so it is stable across frames (no re-sorting needed, no entt::entity anywhere).
|
||||
const Array<PEntity>& roster = scene->getEntities();
|
||||
for (size_t i = 0; i < roster.size(); ++i) {
|
||||
PEntity e = roster[i];
|
||||
if (e == nullptr) {
|
||||
continue;
|
||||
}
|
||||
EntityInfo info;
|
||||
info.entity = e; // non-owning handle the row points at
|
||||
info.label = e->getLabel(); // "#<id>" formatted in the engine; no entt type leaks
|
||||
// Component summary: the names of every cataloged component this entity actually
|
||||
// has, comma-joined. Uses isAttached (handle-space) - no registry access in the editor.
|
||||
std::vector<std::string> names;
|
||||
for (auto& entry : componentCatalog()) {
|
||||
if (entry.isAttached(e)) {
|
||||
names.push_back(entry.name);
|
||||
}
|
||||
}
|
||||
if (names.empty()) {
|
||||
info.componentSummary = "no components";
|
||||
} else {
|
||||
info.componentSummary = names[0];
|
||||
for (size_t n = 1; n < names.size(); ++n) {
|
||||
info.componentSummary += ", " + names[n];
|
||||
}
|
||||
}
|
||||
out.push_back(std::move(info));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
std::vector<ComponentDisplay> describeEntityComponents(const PScene& scene, PEntity entity) {
|
||||
std::vector<ComponentDisplay> out;
|
||||
if (scene == nullptr || entity == nullptr) {
|
||||
return out;
|
||||
}
|
||||
// Walk the catalog in order; for each component the entity has, render its fields via
|
||||
// the handle's own accessComponent. The editor never touches the registry directly.
|
||||
for (auto& entry : componentCatalog()) {
|
||||
if (!entry.isAttached(entity)) {
|
||||
continue; // entity does not have this component (or it is not displayable)
|
||||
}
|
||||
out.push_back(ComponentDisplay{.name = entry.name, .fieldText = entry.describe(entity)});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace Editor
|
||||
} // namespace Seele
|
||||
@@ -0,0 +1,83 @@
|
||||
#pragma once
|
||||
// The editor's component-inspection layer. Operates ENTIRELY in engine handle space
|
||||
// (OEntity / PScene) - the entt::entity type never appears in this header or in any
|
||||
// function the editor calls. Every EnTT operation the inspector needs (does-this-entity-
|
||||
// have-T, read-T) is performed by the Entity/Scene methods (hasComponent / accessComponent
|
||||
// / getEntities), which is exactly the separation the engine wants: tooling works through
|
||||
// handles, the registry stays internal to the engine.
|
||||
#include "Actor/Actor.h"
|
||||
#include "Scene/Scene.h"
|
||||
#include <functional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace Seele {
|
||||
namespace Editor {
|
||||
|
||||
// A single entry in the component catalog: how to recognize one component type on an
|
||||
// entity and how to render its fields as human-readable text (Unity-inspector style).
|
||||
//
|
||||
// Both callbacks take a PEntity (a non-owning handle view) - never a raw entt id. They use
|
||||
// the entity's own hasComponent<T>() / accessComponent<T>() so the inspector code reads
|
||||
// exactly the way game code attaches/reads components: in handle space.
|
||||
//
|
||||
// This is the type-erased bridge between "I have an OEntity handle" and "show me every
|
||||
// component attached to it". EnTT does not expose a generic "iterate all registered
|
||||
// component types" API, so the inspector keeps an explicit catalog of the types it knows
|
||||
// how to display. Adding a new engine component to the inspector is one entry in
|
||||
// ComponentRegistry.cpp - no changes to this header.
|
||||
struct ComponentEntry {
|
||||
// Display name shown as the section header in the inspector (e.g. "Transform").
|
||||
std::string name;
|
||||
// True if the given entity currently has this component attached.
|
||||
std::function<bool(PEntity)> isAttached;
|
||||
// Render the component's fields as a multi-line string (Unity-style: "field: value" per
|
||||
// line). Returns "" when the entity does not have the component (the caller skips it).
|
||||
std::function<std::string(PEntity)> describe;
|
||||
};
|
||||
|
||||
// The catalog of every component type the editor knows how to display. Populated exactly
|
||||
// once by initComponentRegistry() (called from the editor's main before the first frame).
|
||||
// The vector is process-global by design: component *types* are a fixed set, so the
|
||||
// catalog is built once and read-only afterwards.
|
||||
std::vector<ComponentEntry>& componentCatalog();
|
||||
|
||||
// Build the catalog. Idempotent - safe to call more than once; it only (re)populates the
|
||||
// static vector, which every editor tool reads. Must be called before any inspector reads
|
||||
// the catalog (main.cpp does this before the render loop).
|
||||
void initComponentRegistry();
|
||||
|
||||
// One row in the entity list (the left pane). Built from the scene's roster of live
|
||||
// handles - the "ID of an entity" is shown via the handle's own getLabel() (formatted in
|
||||
// the engine, so no entt type leaks), and the component summary is the names of the
|
||||
// cataloged components the handle actually has.
|
||||
struct EntityInfo {
|
||||
// The non-owning handle the row refers to. The editor stores these to drive the
|
||||
// "selected entity" state across frames. Non-owning by design: the *scene* owns the
|
||||
// entity's existence (the roster) and the creator's O* owns the C++ object.
|
||||
PEntity entity;
|
||||
// A short, stable label for the row (e.g. "#3") - the "ID of an entity" the user asked
|
||||
// to display, produced by Entity::getLabel() so the entt type never reaches the editor.
|
||||
std::string label;
|
||||
// Human-readable summary of the attached components (e.g. "Transform, Mesh") for the
|
||||
// row's subtitle.
|
||||
std::string componentSummary;
|
||||
};
|
||||
|
||||
// Enumerate every live entity in the scene (as non-owning handles) with its label + a
|
||||
// component summary. Source of the left pane. Iterates the scene's roster (getEntities) -
|
||||
// the scene's single source of truth for "what entities exist" - so this is the
|
||||
// "OEntity you can query via the scene" the user asked for, with no entt id anywhere.
|
||||
std::vector<EntityInfo> enumerateEntities(const PScene& scene);
|
||||
|
||||
// Describe one entity's components for the inspector pane: a vector of (componentName,
|
||||
// fieldText) pairs, one entry per attached, displayable component, in catalog order. The
|
||||
// caller (InspectorView) maps these to UI::Text rows and refreshes them in update().
|
||||
struct ComponentDisplay {
|
||||
std::string name;
|
||||
std::string fieldText;
|
||||
};
|
||||
std::vector<ComponentDisplay> describeEntityComponents(const PScene& scene, PEntity entity);
|
||||
|
||||
} // namespace Editor
|
||||
} // namespace Seele
|
||||
@@ -1,25 +1,141 @@
|
||||
#include "InspectorView.h"
|
||||
#include "Actor/Actor.h"
|
||||
#include "Asset/AssetRegistry.h"
|
||||
#include "Asset/FontLoader.h"
|
||||
|
||||
#include "ComponentRegistry.h"
|
||||
#include "Graphics/Graphics.h"
|
||||
#include "UI/Element/Button.h"
|
||||
#include "UI/Element/Div.h"
|
||||
#include "UI/Element/Text.h"
|
||||
#include "UI/Style/Fonts.h" // Font_Arial tag type (Text.h does not pull this in)
|
||||
#include "UI/System.h"
|
||||
|
||||
using namespace Seele;
|
||||
using namespace Seele::Editor;
|
||||
using namespace Seele::UI;
|
||||
|
||||
InspectorView::InspectorView(Gfx::PGraphics graphics, PWindow window, const ViewportCreateInfo& createInfo)
|
||||
: View(graphics, window, createInfo, "InspectorView"),
|
||||
uiSystem(new UI::System(
|
||||
new UI::Div<M_8>(UI::Attributes{}, {
|
||||
new UI::Div<BG_Red, Inline>({},
|
||||
{
|
||||
new UI::Text<Font_Arial, Text_9XL>("Other Test T"),
|
||||
}),
|
||||
new UI::Text<Font_Arial>("Test fasdf agll;sdfgkj ahsf"),
|
||||
}))) {
|
||||
renderGraph.addPass(new UIPass(graphics, uiSystem));
|
||||
namespace {
|
||||
// Split a multi-line string into trimmed, non-empty lines (for the field display).
|
||||
std::vector<std::string> splitLines(const std::string& text) {
|
||||
std::vector<std::string> out;
|
||||
std::string cur;
|
||||
for (char c : text) {
|
||||
if (c == '\n') {
|
||||
if (!cur.empty()) {
|
||||
out.push_back(cur);
|
||||
cur.clear();
|
||||
}
|
||||
} else {
|
||||
cur.push_back(c);
|
||||
}
|
||||
}
|
||||
if (!cur.empty()) {
|
||||
out.push_back(cur);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
InspectorView::InspectorView(Gfx::PGraphics graphics, PWindow owner, const ViewportCreateInfo& createInfo, PScene scene)
|
||||
: View(graphics, owner, createInfo, "InspectorView"), scene(scene) {
|
||||
// ------------------------------------------------------------------
|
||||
// Build the ENTIRE fixed widget tree exactly once, here, in the constructor.
|
||||
//
|
||||
// "Children fixed at construction": the UI tree's structure is immutable at
|
||||
// runtime. We create every widget as a named local (so we can keep a raw pointer
|
||||
// for setText()), then reference those same objects in the tree's initializer-list.
|
||||
// The initializer-list's Element* -> OElement implicit conversion stores an OWNING
|
||||
// ref in each parent's children array (Array<OElement>) for the element's whole
|
||||
// lifetime, so the raw pointers below remain valid for the life of the view.
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
// ---- Leaf widgets (named locals; also referenced by the tree below) ----------
|
||||
// Entity-list row labels + select buttons (one row per pool slot).
|
||||
Text<Font_Arial>* rowLabels[kMaxEntities];
|
||||
Button<>* rowButtons[kMaxEntities];
|
||||
for (int i = 0; i < kMaxEntities; i++) {
|
||||
// Text has no default ctor (text is a required arg); start with an empty string
|
||||
// and refresh() fills it each frame. Button's default ctor is deleted (Div()
|
||||
// = delete) so we must pass explicit Attributes.
|
||||
rowLabels[i] = new Text<Font_Arial>("");
|
||||
rowButtons[i] = new Button<>(UI::Attributes{});
|
||||
// The button's onClick is the ONLY sanctioned way selection state changes;
|
||||
// refresh() (called from update() next frame) reads it back and re-renders the
|
||||
// component pane. We do not markDirty() here - the next frame's refresh() is
|
||||
// the sanctioned per-frame mutation path, and markDirty() is an Element method
|
||||
// (not callable on this View).
|
||||
rowButtons[i]->attr.onClick = [this, i](MouseEvent&) {
|
||||
selectedEntity = i;
|
||||
return true;
|
||||
};
|
||||
// PElement is a NON-OWNING wrapper (no operator=(T*)); the tree's owning
|
||||
// OElement refs (stored in the parent Div's children below) are what keep these
|
||||
// alive. We construct an explicit PElement temporary to copy-assign the handle.
|
||||
entityPool[i].label = PElement(rowLabels[i]);
|
||||
entityPool[i].button = PElement(rowButtons[i]);
|
||||
}
|
||||
|
||||
// Component-inspector pane: a header line + a fixed pool of field lines.
|
||||
// Text has no default ctor - pass an initial string (refresh() overwrites it).
|
||||
Text<Font_Arial, Text_8XL>* header = new Text<Font_Arial, Text_8XL>("(no entity selected)");
|
||||
Text<Font_Arial>* lines[kMaxComponentLines];
|
||||
for (int i = 0; i < kMaxComponentLines; i++) {
|
||||
lines[i] = new Text<Font_Arial>("");
|
||||
}
|
||||
componentHeader = PElement(header);
|
||||
for (int i = 0; i < kMaxComponentLines; i++) {
|
||||
componentLines[i] = PElement(lines[i]);
|
||||
}
|
||||
|
||||
// ---- Compose the tree (structure fixed at construction) ----------------------
|
||||
// Element's only children ctor is (Attributes, initializer_list<OElement>) - there is
|
||||
// no variadic form and initializer_list cannot be built from an Array, so the child
|
||||
// list must be a braced-init at the call site. A braced list MAY contain function-call
|
||||
// expressions, so a small lambda builds each identical row (returning the owning
|
||||
// OElement of the row Div) and we reference makeRow(0..7) explicitly. The label/button
|
||||
// handles for refresh() were already stashed in entityPool[] above (non-owning PElement);
|
||||
// the row Div's children array holds the OWNING refs that keep the widgets alive.
|
||||
auto makeRow = [this, &rowLabels, &rowButtons](int i) -> OElement {
|
||||
return OElement(new Div<FlexRow, M_4>(
|
||||
UI::Attributes{},
|
||||
std::initializer_list<OElement>{OElement(rowLabels[i]), OElement(rowButtons[i])}));
|
||||
};
|
||||
|
||||
// Left pane: a vertical (FlexCol) stack of the 8 fixed entity rows. The child list is
|
||||
// a braced-init of makeRow(0..7) - each call returns the owning OElement of one row.
|
||||
Div<FlexCol, M_8, BG_Red>* leftPane = new Div<FlexCol, M_8, BG_Red>(
|
||||
UI::Attributes{},
|
||||
std::initializer_list<OElement>{
|
||||
makeRow(0), makeRow(1), makeRow(2), makeRow(3),
|
||||
makeRow(4), makeRow(5), makeRow(6), makeRow(7),
|
||||
});
|
||||
|
||||
// Right pane: a vertical (FlexCol) stack of the header line + the fixed field-line pool.
|
||||
// Same braced-init pattern; makeLine(i) returns the owning OElement of one field Text.
|
||||
auto makeLine = [this, &lines](int i) -> OElement {
|
||||
return OElement(lines[i]);
|
||||
};
|
||||
Div<FlexCol, M_8>* rightPane = new Div<FlexCol, M_8>(
|
||||
UI::Attributes{},
|
||||
std::initializer_list<OElement>{
|
||||
OElement(header),
|
||||
makeLine(0), makeLine(1), makeLine(2), makeLine(3),
|
||||
makeLine(4), makeLine(5), makeLine(6), makeLine(7),
|
||||
makeLine(8), makeLine(9), makeLine(10), makeLine(11),
|
||||
makeLine(12), makeLine(13), makeLine(14), makeLine(15),
|
||||
});
|
||||
|
||||
// Root: a horizontal (FlexRow) split - entity list on the left, inspector on the right.
|
||||
Div<FlexRow, M_8>* root = new Div<FlexRow, M_8>(
|
||||
UI::Attributes{},
|
||||
std::initializer_list<OElement>{OElement(leftPane), OElement(rightPane)});
|
||||
|
||||
// Hand the fully-built root tree to the UI system. The system is owned by the view
|
||||
// (uiSystem is an OwningPtr); construct the owning handle in place.
|
||||
uiSystem = UI::OSystem(new UI::System(OElement(root)));
|
||||
|
||||
// Register a UIPass to render the UI. Keep a raw pointer to it so the window input
|
||||
// callbacks can forward events (RenderGraph exposes only resources, not passes).
|
||||
uiPass = new UIPass(graphics, uiSystem);
|
||||
renderGraph.addPass(ORenderPass(uiPass));
|
||||
renderGraph.setViewport(viewport);
|
||||
renderGraph.createRenderPass();
|
||||
}
|
||||
@@ -28,22 +144,119 @@ InspectorView::~InspectorView() {}
|
||||
|
||||
void InspectorView::beginUpdate() {}
|
||||
|
||||
void InspectorView::update() {}
|
||||
void InspectorView::update() {
|
||||
refresh();
|
||||
}
|
||||
|
||||
void InspectorView::commitUpdate() {}
|
||||
|
||||
void InspectorView::prepareRender() {}
|
||||
|
||||
void InspectorView::render() { renderGraph.render(Component::Camera(), Component::Transform()); }
|
||||
void InspectorView::render() {
|
||||
// Drives every pass in the graph, including the UIPass (which runs
|
||||
// system->processInput() + system->beginFrame() internally before rendering).
|
||||
// The UI system's per-frame update is performed by the pass, not by us.
|
||||
renderGraph.render(Component::Camera(), Component::Transform());
|
||||
}
|
||||
|
||||
void InspectorView::applyArea(URect ) {}
|
||||
void InspectorView::applyArea(URect) {
|
||||
// The Viewport was already resized by View::resize before this is called. Recreate
|
||||
// the render graph's passes at the new size so the UI (and everything) re-layouts.
|
||||
renderGraph.setViewport(viewport);
|
||||
renderGraph.createRenderPass();
|
||||
}
|
||||
|
||||
void InspectorView::keyCallback(KeyCode, InputAction, KeyModifier) {}
|
||||
void InspectorView::keyCallback(KeyCode code, InputAction action, uint32_t modifier) {
|
||||
if (uiPass != nullptr) {
|
||||
uiPass->key(code, action, KeyModifierFlags(modifier), 0);
|
||||
}
|
||||
}
|
||||
|
||||
void InspectorView::mouseMoveCallback(double, double) {}
|
||||
void InspectorView::mouseMoveCallback(double xPos, double yPos) {
|
||||
if (uiPass != nullptr) {
|
||||
uiPass->mouseMove(Vector2(xPos, yPos));
|
||||
}
|
||||
}
|
||||
|
||||
void InspectorView::mouseButtonCallback(MouseButton, InputAction, KeyModifier) {}
|
||||
void InspectorView::mouseButtonCallback(MouseButton button, InputAction action, uint32_t modifier) {
|
||||
if (uiPass != nullptr) {
|
||||
uiPass->mouseButton(button, action, KeyModifierFlags(modifier), Vector2(0, 0));
|
||||
}
|
||||
}
|
||||
|
||||
void InspectorView::scrollCallback(double, double) {}
|
||||
void InspectorView::scrollCallback(double xPos, double yPos, double xScroll, double yScroll) {
|
||||
// The UI system's scroll() currently takes only the delta (no cursor position);
|
||||
// xPos/yPos are the view-local cursor coords, carried for the future the UI system
|
||||
// needs per-element scroll targeting.
|
||||
(void)xPos;
|
||||
(void)yPos;
|
||||
if (uiPass != nullptr) {
|
||||
uiPass->scroll(Vector2(xScroll, yScroll));
|
||||
}
|
||||
}
|
||||
|
||||
void InspectorView::fileCallback(int, const char**) {}
|
||||
|
||||
void InspectorView::refresh() {
|
||||
// Re-read the scene's live entity roster + the selected entity's components, and
|
||||
// push the results into the fixed widget pool via Text::setText. This is the ONLY
|
||||
// per-frame mutation of the UI tree - children are never added or removed.
|
||||
//
|
||||
// The pool handles are UI::PElement (the Element base ref) because Text/Button are
|
||||
// class templates (can't be member types). We downcast to the concrete type at the
|
||||
// use site. Every downcast target is guaranteed valid: we built each widget with the
|
||||
// exact concrete type below and the tree's owning OElement refs keep it alive.
|
||||
auto setTextOn = [](UI::PElement handle, const std::string& text) {
|
||||
if (handle == nullptr) {
|
||||
return;
|
||||
}
|
||||
if (auto* t = dynamic_cast<UI::Text<Font_Arial>*>(handle.getHandle())) {
|
||||
t->setText(text);
|
||||
}
|
||||
};
|
||||
auto entities = enumerateEntities(scene);
|
||||
|
||||
// --- Entity list pane: fill the fixed row pool from the live roster -----------
|
||||
for (int i = 0; i < kMaxEntities; i++) {
|
||||
if (i < (int)entities.size()) {
|
||||
setTextOn(entityPool[i].label,
|
||||
entities[i].label + " [" + entities[i].componentSummary + "]");
|
||||
} else {
|
||||
setTextOn(entityPool[i].label, "");
|
||||
}
|
||||
}
|
||||
|
||||
// --- Component inspector pane: describe the selected entity -------------------
|
||||
if (selectedEntity >= 0 && selectedEntity < (int)entities.size()) {
|
||||
PEntity ent = entities[selectedEntity].entity;
|
||||
setTextOn(componentHeader, "Components: " + entities[selectedEntity].label);
|
||||
auto components = describeEntityComponents(scene, ent);
|
||||
|
||||
int line = 0;
|
||||
for (auto& c : components) {
|
||||
if (line >= kMaxComponentLines) {
|
||||
break; // fixed pool: truncate beyond it
|
||||
}
|
||||
setTextOn(componentLines[line], " " + c.name);
|
||||
line++;
|
||||
// Multi-line field text is folded into the subsequent pool lines (clamped).
|
||||
auto fields = splitLines(c.fieldText);
|
||||
for (auto& f : fields) {
|
||||
if (line >= kMaxComponentLines) {
|
||||
break;
|
||||
}
|
||||
setTextOn(componentLines[line], " " + f);
|
||||
line++;
|
||||
}
|
||||
}
|
||||
// Clear leftover pool lines so stale data never shows (fixed pool must be clean).
|
||||
for (; line < kMaxComponentLines; line++) {
|
||||
setTextOn(componentLines[line], "");
|
||||
}
|
||||
} else {
|
||||
setTextOn(componentHeader, "(no entity selected)");
|
||||
for (int i = 0; i < kMaxComponentLines; i++) {
|
||||
setTextOn(componentLines[i], "");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,36 +1,78 @@
|
||||
#pragma once
|
||||
#include "Graphics/RenderPass/RenderGraph.h"
|
||||
#include "Graphics/RenderPass/UIPass.h"
|
||||
#include "Window/View.h"
|
||||
#include "UI/System.h"
|
||||
#include "Graphics/RenderPass/UIPass.h"
|
||||
#include "UI/Element.h" // UI::PElement / UI::OElement (complete, for the fixed widget pool)
|
||||
#include "Scene/Scene.h" // PScene
|
||||
|
||||
namespace Seele {
|
||||
DECLARE_REF(Actor)
|
||||
namespace Editor {
|
||||
// The editor's component inspector. Left pane lists the scene's live entities
|
||||
// (from the ComponentRegistry via Scene::getEntities); right pane shows the selected
|
||||
// entity's components as Unity-style "field: value" text, refreshed every frame.
|
||||
//
|
||||
// The UI tree is a FIXED widget pool: it is built once in the constructor and never
|
||||
// adds/removes children at runtime. Per-frame the only mutation is UI::Text::setText
|
||||
// on the pre-built widgets (the "children fixed at construction" constraint). Selection
|
||||
// state is changed exclusively through UI::Button onClick handlers (the sanctioned
|
||||
// click path) and read back in update().
|
||||
//
|
||||
// Pool handles are UI::PElement (the Element base ref). Text/Button/Div are class
|
||||
// templates (UI::Text<...>, UI::Button<...>) so they can't be named as member types;
|
||||
// we hold the base and dynamic_cast to the concrete type at the use site in refresh().
|
||||
class InspectorView : public View {
|
||||
public:
|
||||
InspectorView(Gfx::PGraphics graphics, PWindow window, const ViewportCreateInfo& createInfo);
|
||||
virtual ~InspectorView();
|
||||
// `scene` is the scene to inspect (non-owning; the editor owns its lifetime).
|
||||
// The roster + component data are read from it each frame via the ComponentRegistry.
|
||||
InspectorView(Gfx::PGraphics graphics, PWindow owner, const ViewportCreateInfo& createInfo, PScene scene);
|
||||
virtual ~InspectorView() override;
|
||||
|
||||
virtual void beginUpdate() override;
|
||||
virtual void update() override;
|
||||
virtual void commitUpdate() override;
|
||||
|
||||
virtual void prepareRender() override;
|
||||
virtual void render() override;
|
||||
|
||||
|
||||
protected:
|
||||
virtual void applyArea(URect area) override;
|
||||
UI::PSystem uiSystem;
|
||||
RenderGraph renderGraph;
|
||||
Component::Camera cam;
|
||||
|
||||
virtual void keyCallback(KeyCode code, InputAction action, KeyModifier modifier) override;
|
||||
virtual void keyCallback(KeyCode code, InputAction action, uint32_t modifier) override;
|
||||
virtual void mouseMoveCallback(double xPos, double yPos) override;
|
||||
virtual void mouseButtonCallback(MouseButton button, InputAction action, KeyModifier modifier) override;
|
||||
virtual void scrollCallback(double xOffset, double yOffset) override;
|
||||
virtual void mouseButtonCallback(MouseButton button, InputAction action, uint32_t modifier) override;
|
||||
virtual void scrollCallback(double xPos, double yPos, double xScroll, double yScroll) override;
|
||||
virtual void fileCallback(int count, const char** paths) override;
|
||||
|
||||
private:
|
||||
// Fixed widget pools. Handles are UI::PElement (base) because Text/Button are class
|
||||
// templates. Each is safe for the life of the view: the constructed element is stored
|
||||
// in a parent Div's children array (Array<OElement>) which holds an OWNING ref; the
|
||||
// PElement here is a second (shared) ref to the same object. refresh() dynamic_casts
|
||||
// to the concrete UI::Text<Font_Arial>/UI::Button<> to call setText()/attr.
|
||||
static constexpr int kMaxEntities = 8; // entity-list rows
|
||||
static constexpr int kMaxComponentLines = 16; // component-inspector text lines
|
||||
|
||||
PScene scene;
|
||||
// The UI::System is a long-lived object with no other owner, so the view OWNS it
|
||||
// (OwningPtr, via the OSystem typedef from DEFINE_REF(System)). UIPass takes a
|
||||
// non-owning PSystem, which OSystem converts to implicitly.
|
||||
UI::OSystem uiSystem;
|
||||
RenderGraph renderGraph;
|
||||
// Direct handle to the UI render pass so the window input callbacks can be
|
||||
// forwarded to the UI system (RenderGraph exposes only resources, not passes).
|
||||
UIPass* uiPass = nullptr;
|
||||
|
||||
// Selection state: written by button onClick, read in refresh().
|
||||
int selectedEntity = -1;
|
||||
|
||||
struct EntityRow {
|
||||
UI::PElement label = nullptr; // UI::Text<Font_Arial> (cast in refresh())
|
||||
UI::PElement button = nullptr; // UI::Button<> (cast in refresh())
|
||||
};
|
||||
EntityRow entityPool[kMaxEntities];
|
||||
|
||||
UI::PElement componentHeader = nullptr;
|
||||
UI::PElement componentLines[kMaxComponentLines];
|
||||
|
||||
// Rebuild the pool text from the current scene state (called from update()).
|
||||
void refresh();
|
||||
};
|
||||
DEFINE_REF(InspectorView)
|
||||
} // namespace Editor
|
||||
|
||||
@@ -2,12 +2,13 @@
|
||||
#include "Graphics/Enums.h"
|
||||
#include "MinimalEngine.h"
|
||||
#include "Window/Window.h"
|
||||
#include <iostream>
|
||||
|
||||
using namespace Seele;
|
||||
using namespace Seele::Editor;
|
||||
|
||||
PlayView::PlayView(Gfx::PGraphics graphics, PWindow window, const ViewportCreateInfo& createInfo, std::filesystem::path dllPath)
|
||||
: GameView(graphics, window, createInfo, dllPath) {}
|
||||
PlayView::PlayView(Gfx::PGraphics graphics, PWindow window, PScene scene, const ViewportCreateInfo& createInfo)
|
||||
: GameView(graphics, window, scene, createInfo) {}
|
||||
|
||||
PlayView::~PlayView() {}
|
||||
|
||||
@@ -21,7 +22,7 @@ void PlayView::prepareRender() { GameView::prepareRender(); }
|
||||
|
||||
void PlayView::render() { GameView::render(); }
|
||||
|
||||
void PlayView::keyCallback(KeyCode code, InputAction action, KeyModifier modifier) {
|
||||
void PlayView::keyCallback(KeyCode code, InputAction action, KeyModifierFlags modifier) {
|
||||
GameView::keyCallback(code, action, modifier);
|
||||
if (code == KeyCode::KEY_P && action == InputAction::RELEASE) {
|
||||
getGlobals().usePositionOnly = !getGlobals().usePositionOnly;
|
||||
|
||||
@@ -5,7 +5,7 @@ namespace Seele {
|
||||
namespace Editor {
|
||||
class PlayView : public GameView {
|
||||
public:
|
||||
PlayView(Gfx::PGraphics graphics, PWindow window, const ViewportCreateInfo& createInfo, std::filesystem::path dllPath);
|
||||
PlayView(Gfx::PGraphics graphics, PWindow window, PScene scene, const ViewportCreateInfo& createInfo);
|
||||
virtual ~PlayView();
|
||||
virtual void beginUpdate() override;
|
||||
virtual void update() override;
|
||||
@@ -14,7 +14,7 @@ class PlayView : public GameView {
|
||||
virtual void prepareRender() override;
|
||||
virtual void render() override;
|
||||
|
||||
virtual void keyCallback(Seele::KeyCode code, Seele::InputAction action, Seele::KeyModifier modifier) override;
|
||||
virtual void keyCallback(Seele::KeyCode code, Seele::InputAction action, Seele::KeyModifierFlags modifier) override;
|
||||
|
||||
private:
|
||||
};
|
||||
|
||||
@@ -42,14 +42,14 @@ void SceneView::prepareRender() {}
|
||||
|
||||
void SceneView::render() { renderGraph.render(viewportCamera, Component::Transform()); }
|
||||
|
||||
void SceneView::keyCallback(KeyCode code, InputAction action, KeyModifier) { cameraSystem.keyCallback(code, action); }
|
||||
void SceneView::keyCallback(KeyCode code, InputAction action, KeyModifierFlags) { cameraSystem.keyCallback(code, action); }
|
||||
|
||||
void SceneView::mouseMoveCallback(double xPos, double yPos) { cameraSystem.mouseMoveCallback(xPos, yPos); }
|
||||
|
||||
void SceneView::mouseButtonCallback(MouseButton button, InputAction action, KeyModifier) {
|
||||
void SceneView::mouseButtonCallback(MouseButton button, InputAction action, KeyModifierFlags) {
|
||||
cameraSystem.mouseButtonCallback(button, action);
|
||||
}
|
||||
|
||||
void SceneView::scrollCallback(double, double) {}
|
||||
void SceneView::scrollCallback(double, double, double, double) {}
|
||||
|
||||
void SceneView::fileCallback(int, const char**) {}
|
||||
@@ -29,10 +29,10 @@ class SceneView : public View {
|
||||
|
||||
ViewportControl cameraSystem;
|
||||
|
||||
virtual void keyCallback(KeyCode code, InputAction action, KeyModifier modifier) override;
|
||||
virtual void keyCallback(KeyCode code, InputAction action, KeyModifierFlags modifier) override;
|
||||
virtual void mouseMoveCallback(double xPos, double yPos) override;
|
||||
virtual void mouseButtonCallback(MouseButton button, InputAction action, KeyModifier modifier) override;
|
||||
virtual void scrollCallback(double xOffset, double yOffset) override;
|
||||
virtual void mouseButtonCallback(MouseButton button, InputAction action, KeyModifierFlags modifier) override;
|
||||
virtual void scrollCallback(double xPos, double yPos, double xScroll, double yScroll) override;
|
||||
virtual void fileCallback(int count, const char** paths) override;
|
||||
};
|
||||
DEFINE_REF(SceneView)
|
||||
|
||||
+134
-34
@@ -10,9 +10,20 @@
|
||||
#include "Material/Material.h"
|
||||
#include "Graphics/Vulkan/Graphics.h"
|
||||
#include "Graphics/StaticMeshVertexData.h"
|
||||
#include "System/SystemGraph.h"
|
||||
#include "Window/PlayView.h"
|
||||
#include "Window/WindowManager.h"
|
||||
#include "System/CameraUpdater.h"
|
||||
#include "System/FluidUpdater.h"
|
||||
#include "System/LightGather.h"
|
||||
#include "System/MeshUpdater.h"
|
||||
#include "Window/Application.h"
|
||||
#include "Window/InspectorView.h"
|
||||
#include "Scene/Scene.h" // OScene/Scene - the InspectorView's entity pane needs a live scene
|
||||
#include "Component/Transform.h"
|
||||
#include "Actor/Entity.h"
|
||||
#include "ComponentRegistry.h"
|
||||
#include <fmt/core.h>
|
||||
#include <iostream>
|
||||
|
||||
using namespace Seele;
|
||||
using namespace Seele::Editor;
|
||||
@@ -20,10 +31,100 @@ using namespace Seele::Editor;
|
||||
// make it global so it gets deleted last and automatically
|
||||
static Gfx::OGraphics graphics;
|
||||
|
||||
int main() {
|
||||
// Headless path: build a real Vulkan device with no WSI (no display available),
|
||||
// populate a Scene with a few entities + components, dump the registry to stdout
|
||||
// via the same handle-space query the editor's inspector uses, then tear down.
|
||||
// Used for CI / smoke verification on display-less machines: the driver is
|
||||
// present, only the display is not, so surface extensions are intentionally
|
||||
// omitted while everything else (instance, device, queues, GPU buffers) works.
|
||||
static int runHeadlessDump() {
|
||||
std::cout << "[headless] constructing Vulkan::Graphics (no WSI / no swapchain)...\n";
|
||||
Gfx::OGraphics headlessGfx = new Vulkan::Graphics();
|
||||
GraphicsInitializer initializer;
|
||||
initializer.headless = true; // skip GLFW init, WSI instance exts, and the swapchain device ext
|
||||
headlessGfx->init(initializer);
|
||||
std::cout << "[headless] Vulkan device constructed successfully.\n";
|
||||
|
||||
// A real (non-null) graphics handle, so Scene builds its GPU sub-systems for real.
|
||||
OScene scene = new Scene(headlessGfx);
|
||||
std::cout << "[headless] Scene constructed (LightEnvironment + FluidScene on real device).\n";
|
||||
|
||||
// A few entities with real transforms so the dump is meaningful. The display label is
|
||||
// auto-derived from the entt id (Entity::getLabel -> "#<id>"), so no setLabel needed.
|
||||
Entity* a = new Entity(scene);
|
||||
a->attachComponent<Component::Transform>().transform.setPosition(glm::vec3(0.0f, 0.0f, 0.0f));
|
||||
Entity* b = new Entity(scene);
|
||||
b->attachComponent<Component::Transform>().transform.setPosition(glm::vec3(1.0f, 2.0f, -3.0f));
|
||||
Entity* c = new Entity(scene);
|
||||
// c intentionally has no components - exercises the "no components" roster row.
|
||||
|
||||
initComponentRegistry();
|
||||
auto entities = enumerateEntities(scene);
|
||||
std::cout << "\n[headless] entity roster: " << entities.size() << " entity(ies)\n";
|
||||
for (const auto& e : entities) {
|
||||
std::cout << "\n=== " << e.label << " ===\n";
|
||||
std::cout << " components: " << e.componentSummary << "\n";
|
||||
auto components = describeEntityComponents(scene, e.entity);
|
||||
for (const auto& c : components) {
|
||||
std::cout << " [ " << c.name << " ]\n";
|
||||
// Indent the field text by 4 spaces for readability.
|
||||
for (const auto& line : std::vector<std::string>{
|
||||
[&] {
|
||||
std::vector<std::string> out;
|
||||
std::string cur;
|
||||
for (char ch : c.fieldText) {
|
||||
if (ch == '\n') { out.push_back(" " + cur); cur.clear(); }
|
||||
else { cur += ch; }
|
||||
}
|
||||
if (!cur.empty()) { out.push_back(" " + cur); }
|
||||
return out;
|
||||
}()}) {
|
||||
std::cout << " " << line << "\n";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
std::cout << "\n[headless] tearing down (waitDeviceIdle + dispose)...\n";
|
||||
headlessGfx->waitDeviceIdle();
|
||||
delete a;
|
||||
delete b;
|
||||
delete c;
|
||||
// scene (OScene) and headlessGfx (OGraphics) are OwningPtr (RAII): their destructors
|
||||
// free the Scene / Graphics when the locals go out of scope at the end of this function.
|
||||
// No manual delete - that would be a double-free. Order matters (entities before scene),
|
||||
// which is already satisfied by the explicit deletes above.
|
||||
std::cout << "[headless] OK - headless Vulkan path validated.\n";
|
||||
return 0;
|
||||
}
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
// --headless: build a real headless Vulkan device and exit (no window).
|
||||
// --dump-entities: (implies --headless) also dump the entity roster to stdout.
|
||||
bool wantHeadless = false, wantDump = false;
|
||||
for (int i = 1; i < argc; ++i) {
|
||||
std::string a = argv[i];
|
||||
if (a == "--headless" || a == "--dump-entities") wantHeadless = true;
|
||||
if (a == "--dump-entities") wantDump = true;
|
||||
}
|
||||
if (wantHeadless) {
|
||||
if (wantDump) {
|
||||
return runHeadlessDump();
|
||||
}
|
||||
// Headless device smoke test only (no dump).
|
||||
Gfx::OGraphics h = new Vulkan::Graphics();
|
||||
GraphicsInitializer init;
|
||||
init.headless = true;
|
||||
h->init(init);
|
||||
std::cout << "[headless] device OK (no WSI). Tearing down.\n";
|
||||
h->waitDeviceIdle();
|
||||
// h is an OwningPtr (RAII) - the destructor frees the Graphics at end of scope.
|
||||
// No manual delete (would be a double-free).
|
||||
return 0;
|
||||
}
|
||||
|
||||
std::string gameName = "MeshShadingDemo";
|
||||
std::filesystem::path outputPath = fmt::format("/Users/dynamitos/{0}Game/", gameName);
|
||||
std::filesystem::path sourcePath = fmt::format("/Users/dynamitos/{0}/", gameName);
|
||||
std::filesystem::path outputPath = fmt::format("/home/dynamitos/{0}Game/", gameName);
|
||||
std::filesystem::path sourcePath = fmt::format("/home/dynamitos/{0}/", gameName);
|
||||
#ifdef WIN32
|
||||
std::string libraryEnding = "dll";
|
||||
#elif __APPLE__
|
||||
@@ -31,7 +132,7 @@ int main() {
|
||||
#else
|
||||
std::string libraryEnding = "so";
|
||||
#endif
|
||||
std::filesystem::path binaryPath = sourcePath / "build/Debug" / fmt::format("{}.{}", gameName, libraryEnding);
|
||||
std::filesystem::path binaryPath = sourcePath / "bin" / fmt::format("{}.{}", gameName, libraryEnding);
|
||||
std::filesystem::path cmakePath = outputPath / "cmake";
|
||||
if (true) {
|
||||
graphics = new Vulkan::Graphics();
|
||||
@@ -40,15 +141,14 @@ int main() {
|
||||
StaticMeshVertexData* vd = StaticMeshVertexData::getInstance();
|
||||
vd->init(graphics);
|
||||
|
||||
OWindowManager windowManager = new WindowManager();
|
||||
AssetRegistry::init(sourcePath / "Assets", graphics);
|
||||
AssetImporter::init(graphics);
|
||||
AssetImporter::importFont(FontImportArgs{
|
||||
.filePath = "./fonts/arial.ttf",
|
||||
});
|
||||
// AssetImporter::importEnvironmentMap(EnvironmentImportArgs{
|
||||
// .filePath = sourcePath / "import" / "textures" / "newport_loft.hdr",
|
||||
// });
|
||||
AssetImporter::importEnvironmentMap(EnvironmentImportArgs{
|
||||
.filePath = sourcePath / "import" / "textures" / "newport_loft.hdr",
|
||||
});
|
||||
// AssetImporter::importTexture(TextureImportArgs{
|
||||
// .filePath = sourcePath / "import" / "textures" / "grass_block_side.png",
|
||||
// .importPath = "",
|
||||
@@ -57,21 +157,23 @@ int main() {
|
||||
// .filePath = sourcePath / "import" / "models" / "main1_sponza" / "sponza.gltf",
|
||||
// .importPath = "sponza",
|
||||
//});
|
||||
// AssetImporter::importMesh(MeshImportArgs{
|
||||
// .filePath = sourcePath / "import" / "models" / "rttest.gltf",
|
||||
// .importPath = "rttest",
|
||||
// });
|
||||
|
||||
AssetImporter::importMesh(MeshImportArgs{
|
||||
.filePath = sourcePath / "import" / "models" / "cube.fbx",
|
||||
.importPath = "",
|
||||
});
|
||||
AssetImporter::importMesh(MeshImportArgs{
|
||||
.filePath = sourcePath / "import" / "models" / "rttest.gltf",
|
||||
.importPath = "rttest",
|
||||
});
|
||||
|
||||
AssetImporter::importMesh(MeshImportArgs{
|
||||
.filePath = sourcePath / "import" / "models" / "cube.fbx",
|
||||
.importPath = "",
|
||||
});
|
||||
|
||||
getThreadPool().waitIdle();
|
||||
// The world (Scene + SystemGraph) and the game binary are owned by the
|
||||
// Application from here on. `loadGame` dlopen's the .so, lets the game
|
||||
// populate the scene+graph, and appends the editor's own systems. Views
|
||||
// below only render the non-owning application->scene() handle.
|
||||
OApplication application = new Application();
|
||||
application->loadGame(graphics, sourcePath, gameName);
|
||||
vd->commitMeshes();
|
||||
WindowCreateInfo mainWindowInfo = {
|
||||
.width = 1920,
|
||||
@@ -79,7 +181,7 @@ int main() {
|
||||
.title = "SeeleEngine",
|
||||
.preferredFormat = Gfx::SE_FORMAT_B8G8R8A8_SRGB,
|
||||
};
|
||||
auto window = windowManager->addWindow(graphics, mainWindowInfo);
|
||||
auto window = application->addWindow(graphics, mainWindowInfo);
|
||||
ViewportCreateInfo sceneViewInfo = {
|
||||
.dimensions =
|
||||
{
|
||||
@@ -87,22 +189,20 @@ int main() {
|
||||
.offset = {0, 0},
|
||||
},
|
||||
};
|
||||
OGameView sceneView = new Editor::PlayView(graphics, window, sceneViewInfo, binaryPath);
|
||||
sceneView->setFocused();
|
||||
// OInspectorView inspectorView = new Editor::InspectorView(graphics, window,
|
||||
// ViewportCreateInfo{
|
||||
// .dimensions =
|
||||
// {
|
||||
// .size = {1920, 1080},
|
||||
// .offset = {0, 0},
|
||||
// },
|
||||
// .fieldOfView = 0,
|
||||
// .numSamples = Gfx::SE_SAMPLE_COUNT_1_BIT,
|
||||
// });
|
||||
//
|
||||
OGameView sceneView = new Editor::PlayView(graphics, window, application->scene(), sceneViewInfo);
|
||||
OInspectorView inspectorView = new Editor::InspectorView(graphics, window,
|
||||
ViewportCreateInfo{
|
||||
.dimensions =
|
||||
{
|
||||
.size = {1920, 1080},
|
||||
.offset = {0, 0},
|
||||
},
|
||||
},
|
||||
/* scene = */ application->scene());
|
||||
|
||||
window->show();
|
||||
while (windowManager->isActive() && getGlobals().running) {
|
||||
windowManager->render();
|
||||
while (application->isActive() && getGlobals().running) {
|
||||
application->render();
|
||||
}
|
||||
graphics->waitDeviceIdle();
|
||||
Material::destroy();
|
||||
|
||||
@@ -2,6 +2,19 @@
|
||||
|
||||
using namespace Seele;
|
||||
|
||||
Entity::Entity(PScene scene) : scene(scene), identifier(scene->createEntity()) {}
|
||||
Entity::Entity(PScene scene) : scene(scene), identifier(scene->createEntity()) {
|
||||
// Register with the scene's roster so the scene (and tooling built on it, e.g. the
|
||||
// editor's inspector) can enumerate this entity in handle space. The scene is the single
|
||||
// source of truth for "what entities exist"; this handle is a view the creator's O*
|
||||
// still owns (ownership of the C++ object is unchanged - only the *existence record* is
|
||||
// now tracked by the scene).
|
||||
scene->registerEntity(identifier, PEntity(this));
|
||||
}
|
||||
|
||||
Entity::~Entity() { scene->destroyEntity(identifier); }
|
||||
Entity::~Entity() {
|
||||
// Route teardown through the scene so the roster is unlinked in the same transaction
|
||||
// that destroys the registry record - never leaves a dangling roster entry. The scene
|
||||
// outlives this handle in every supported lifetime (the demo holds PScene members), so
|
||||
// `scene` is always valid here.
|
||||
scene->destroyEntity(identifier);
|
||||
}
|
||||
@@ -2,6 +2,8 @@
|
||||
#include "MinimalEngine.h"
|
||||
#include "Scene/Scene.h"
|
||||
#include <entt/entt.hpp>
|
||||
#include <string>
|
||||
#include <sstream>
|
||||
|
||||
namespace Seele {
|
||||
// An entity describes a part of a scene
|
||||
@@ -11,6 +13,31 @@ class Entity {
|
||||
Entity(PScene scene);
|
||||
virtual ~Entity();
|
||||
|
||||
// True if this entity currently has the given component attached. Pure handle-space
|
||||
// (no entt::entity crosses the boundary) - the building block the editor's component
|
||||
// inspector uses to ask "what is attached to this OEntity?" without ever touching the
|
||||
// registry directly. Uses the entt try_get idiom: it returns a pointer to the component
|
||||
// storage the entity holds, or null if the component is not attached - so the check is
|
||||
// null-safe (no assertion) and works for any displayable component type.
|
||||
template <typename Component> bool hasComponent() const { return scene->registry.try_get<Component>(identifier) != nullptr; }
|
||||
|
||||
// The entt record this handle wraps. Exposed (not as the old raw `getId()`, but scoped
|
||||
// and documented as internal) so the *scene* can keep its roster in lock-step with the
|
||||
// registry during Entity ctor/dtor. The editor never calls this - it works entirely in
|
||||
// handle space via hasComponent/accessComponent.
|
||||
entt::entity getIdentifier() const { return identifier; }
|
||||
|
||||
// A short, stable, human-facing label for tooling (the inspector's row text). Formatted
|
||||
// *inside* the engine so the editor never has to name the entt::entity type at all -
|
||||
// it just asks "what should I display for this OEntity?" and gets a string. This is the
|
||||
// "display the ID of an entity" requirement satisfied in pure handle space: the numeric
|
||||
// id is rendered to text here and never leaks out as an entt type.
|
||||
std::string getLabel() const {
|
||||
std::ostringstream oss;
|
||||
oss << "#" << static_cast<uint32>(identifier);
|
||||
return oss.str();
|
||||
}
|
||||
|
||||
template <typename Component, typename... Args> Component& attachComponent(Args&&... args) {
|
||||
return scene->attachComponent<Component>(identifier, std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
#include "FontAsset.h"
|
||||
#include "Graphics/Graphics.h"
|
||||
#include "Graphics/Mesh.h"
|
||||
#include "Window/WindowManager.h"
|
||||
#include "Window/Application.h"
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
+127
-34
@@ -1,6 +1,8 @@
|
||||
#include "FontAsset.h"
|
||||
#include "Graphics/Graphics.h"
|
||||
#include "Graphics/Texture.h"
|
||||
#include <ft2build.h>
|
||||
#include FT_FREETYPE_H
|
||||
|
||||
using namespace Seele;
|
||||
|
||||
@@ -45,11 +47,15 @@ UVector2 FontAsset::shapeText(std::string_view view, uint32 fontSize, Array<Rend
|
||||
uint32 num_glyphs;
|
||||
hb_glyph_info_t* glyphs = hb_buffer_get_glyph_infos(buf, &num_glyphs);
|
||||
hb_glyph_position_t* positions = hb_buffer_get_glyph_positions(buf, &num_glyphs);
|
||||
Vector2 min = Vector2(std::numeric_limits<float>::max());
|
||||
Vector2 max = Vector2(std::numeric_limits<float>::lowest());
|
||||
int32 xppem, yppem;
|
||||
hb_font_get_scale(hb_font, &xppem, &yppem);
|
||||
Vector2 cursor = Vector2(0);
|
||||
// Baseline (in pixels, relative to the text block's top-left) = the font's ascender.
|
||||
// FreeType gives it in 1/64-pixel units after FT_Set_Pixel_Sizes; convert to pixels.
|
||||
// Screen space is y-down; the baseline sits `ascender` px *below* the block's top edge.
|
||||
// (FT metrics ascender is positive-up, so the baseline screen y = +ascender in y-down.)
|
||||
float ascenderPx = (float)ft_face->size->metrics.ascender / 64.0f;
|
||||
Vector2 cursor = Vector2(0, ascenderPx);
|
||||
for (uint32 i = 0; i < num_glyphs; ++i) {
|
||||
hb_codepoint_t glyphid = glyphs[i].codepoint;
|
||||
float xOffset = (float)positions[i].x_offset * fontSize / xppem;
|
||||
@@ -58,46 +64,133 @@ UVector2 FontAsset::shapeText(std::string_view view, uint32 fontSize, Array<Rend
|
||||
float yAdvance = (float)positions[i].y_advance * fontSize / yppem;
|
||||
Vector2 position = cursor + Vector2(xOffset, yOffset);
|
||||
Vector2 dimensions = fontSizes[fontSize].glyphs[glyphid].size;
|
||||
render.add(RenderGlyph{
|
||||
.texture = fontSizes[fontSize].glyphs[glyphid].texture,
|
||||
.position = position,
|
||||
.dimensions = dimensions,
|
||||
});
|
||||
// FreeType bitmap_top = distance from the baseline to the TOP of the bitmap
|
||||
// (positive up). In y-down screen space the bitmap's top edge is therefore at
|
||||
// (baselineY - bitmap_top). bearing.x (bitmap_left) shifts the bitmap right of the
|
||||
// pen. This is what was missing: without it every glyph's top sat on the cursor y
|
||||
// (text top), giving top-aligned instead of baseline-aligned text.
|
||||
float bearingX = (float)fontSizes[fontSize].glyphs[glyphid].bearing.x;
|
||||
float bitmapTop = (float)fontSizes[fontSize].glyphs[glyphid].bearing.y;
|
||||
position.x += bearingX;
|
||||
position.y += -bitmapTop;
|
||||
RenderGlyph& rg = render.add({});
|
||||
rg.texture = fontSizes[fontSize].atlas;
|
||||
rg.uvOffset = fontSizes[fontSize].glyphs[glyphid].uvOffset;
|
||||
rg.uvSize = fontSizes[fontSize].glyphs[glyphid].uvSize;
|
||||
rg.position = position;
|
||||
rg.dimensions = dimensions;
|
||||
cursor += Vector2(xAdvance, yAdvance);
|
||||
min = Vector2(std::min(min.x, position.x), std::min(min.y, position.y));
|
||||
max = Vector2(std::max(max.x, position.x + dimensions.x), std::max(min.y, position.y + dimensions.y));
|
||||
// Track the right-most x extent (for auto width). Height is NOT derived from the
|
||||
// bitmap extents: it must be the full line height (ascender - descender) or
|
||||
// auto-sized elements would clip descenders. See below.
|
||||
max.x = std::max(max.x, position.x + dimensions.x);
|
||||
}
|
||||
hb_buffer_destroy(buf);
|
||||
return UVector2(max - min);
|
||||
// Width = right-most x extent (glyphs start at x>=0, so max.x is the full width).
|
||||
// Height = line height from the font metrics: ascender (above baseline) plus the
|
||||
// descender depth (FT descender is negative-up => its magnitude is below baseline).
|
||||
// This is the correct auto-size: it fits the whole em, including descenders.
|
||||
float descenderPx = (float)ft_face->size->metrics.descender / 64.0f; // <= 0 (down is negative-up)
|
||||
float lineHeightPx = ascenderPx - descenderPx;
|
||||
if (max.x <= 0.0f) { // empty string
|
||||
return UVector2(0, 0);
|
||||
}
|
||||
return UVector2((uint32)std::ceil(max.x), (uint32)std::ceil(lineHeightPx));
|
||||
}
|
||||
|
||||
void FontAsset::loadGlyphs(uint32 fontSize) {
|
||||
if (fontSizes.contains(fontSize)) {
|
||||
return; // packed once; the atlas is immutable
|
||||
}
|
||||
FT_Set_Pixel_Sizes(ft_face, 0, fontSize);
|
||||
// measure every glyph's bitmap size first (one pass, no GPU) so the shelf packer
|
||||
// can compute each cell's atlas coordinates before any pixels are uploaded
|
||||
constexpr uint32 atlasW = 1024;
|
||||
struct Slot {
|
||||
int glyphId;
|
||||
uint32 w, h;
|
||||
uint32 x, y; // atlas coordinates, filled by the packer
|
||||
};
|
||||
Array<Slot> slots;
|
||||
uint32 xCursor = 0;
|
||||
uint32 cursorY = 0;
|
||||
uint32 shelfH = 0;
|
||||
for (int i = 0; i < ft_face->num_glyphs; ++i) {
|
||||
assert(FT_Load_Glyph(ft_face, i, FT_LOAD_RENDER) == 0);
|
||||
FontAsset::Glyph& glyph = fontSizes[fontSize].glyphs[i];
|
||||
glyph.size = IVector2(ft_face->glyph->bitmap.width, ft_face->glyph->bitmap.rows);
|
||||
int err = FT_Load_Glyph(ft_face, i, FT_LOAD_RENDER);
|
||||
assert(err == 0);
|
||||
uint32 w = ft_face->glyph->bitmap.width;
|
||||
uint32 h = ft_face->glyph->bitmap.rows;
|
||||
if (w == 0 || h == 0) {
|
||||
w = 1;
|
||||
h = 1; // keep a 1x1 transparent placeholder so empty glyphs need no special case
|
||||
}
|
||||
if (w > atlasW) {
|
||||
w = atlasW; // shortcut: no per-glyph multi-row splitting; clamp to the atlas width
|
||||
}
|
||||
if (xCursor + w > atlasW) {
|
||||
cursorY += shelfH;
|
||||
shelfH = 0;
|
||||
xCursor = 0;
|
||||
}
|
||||
Slot s;
|
||||
s.glyphId = i;
|
||||
s.w = w;
|
||||
s.h = h;
|
||||
s.x = xCursor;
|
||||
s.y = cursorY;
|
||||
xCursor += w;
|
||||
shelfH = std::max(shelfH, h);
|
||||
slots.add(s);
|
||||
}
|
||||
uint32 totalH = cursorY + shelfH;
|
||||
if (totalH == 0) {
|
||||
totalH = 1;
|
||||
}
|
||||
Array<uint8> atlasData((uint64)atlasW * totalH, 0); // transparent by default
|
||||
FontData& data = fontSizes[fontSize];
|
||||
for (auto& s : slots) {
|
||||
// FT_Load_Glyph resets the face's current glyph — the measured sizes in `slots`
|
||||
// are already captured, so re-rendering here is safe
|
||||
// (FreeType's FT_Load_Glyph must NOT be wrapped in assert(): NDEBUG in release
|
||||
// builds would then never render the bitmap, leaving the atlas all-transparent.)
|
||||
int err2 = FT_Load_Glyph(ft_face, s.glyphId, FT_LOAD_RENDER);
|
||||
assert(err2 == 0);
|
||||
uint32 bw = ft_face->glyph->bitmap.width;
|
||||
uint32 bh = ft_face->glyph->bitmap.rows;
|
||||
FontAsset::Glyph& glyph = data.glyphs[s.glyphId];
|
||||
if (bw == 0 || bh == 0) {
|
||||
bw = 1;
|
||||
bh = 1;
|
||||
glyph.textureData = Array<uint8>(1, 0); // 1x1 transparent placeholder
|
||||
} else {
|
||||
glyph.textureData.resize((uint64)bw * bh);
|
||||
std::memcpy(glyph.textureData.data(), ft_face->glyph->bitmap.buffer, (uint64)bw * bh);
|
||||
}
|
||||
// blit the bitmap into the atlas at (s.x, s.y), row by row (pitch may differ from width)
|
||||
for (uint32 y = 0; y < bh; ++y) {
|
||||
const uint8* src = (bw == 0 || bh == 0) ? nullptr : (const uint8*)ft_face->glyph->bitmap.buffer + (uint64)y * ft_face->glyph->bitmap.pitch;
|
||||
if (src != nullptr) {
|
||||
std::memcpy(atlasData.data() + ((uint64)(s.y + y) * atlasW + s.x), src, bw);
|
||||
}
|
||||
}
|
||||
glyph.size = IVector2(bw, bh);
|
||||
glyph.bearing = IVector2(ft_face->glyph->bitmap_left, ft_face->glyph->bitmap_top);
|
||||
glyph.advance = ft_face->glyph->advance.x;
|
||||
glyph.textureData.resize(glyph.size.x * glyph.size.y);
|
||||
if (glyph.textureData.size() == 0) {
|
||||
glyph.size.x = 1;
|
||||
glyph.size.y = 1;
|
||||
glyph.textureData.add(0);
|
||||
// load a single transparent pixel, so that we dont have to handle empty textures later
|
||||
} else {
|
||||
std::memcpy(glyph.textureData.data(), ft_face->glyph->bitmap.buffer, glyph.textureData.size());
|
||||
}
|
||||
glyph.texture = graphics->createTexture2D(TextureCreateInfo{
|
||||
.sourceData =
|
||||
{
|
||||
.size = glyph.textureData.size(),
|
||||
.data = glyph.textureData.data(),
|
||||
},
|
||||
.format = Gfx::SE_FORMAT_R8_UNORM,
|
||||
.width = glyph.size.x,
|
||||
.height = glyph.size.y,
|
||||
.name = "FontGlyph",
|
||||
});
|
||||
// the UV rect is the exact cell, corner-aligned: offset = (x / W, y / H),
|
||||
// size = (w / W, h / H). The shader already applies a 1-px inset (uvSize * 0.98),
|
||||
// so linear sampling stays inside the cell and does not bleed into neighbors.
|
||||
glyph.uvOffset = Vector2((float)s.x / (float)atlasW, (float)s.y / (float)totalH);
|
||||
glyph.uvSize = Vector2((float)bw / (float)atlasW, (float)bh / (float)totalH);
|
||||
}
|
||||
}
|
||||
data.atlas = graphics->createTexture2D(TextureCreateInfo{
|
||||
.sourceData =
|
||||
{
|
||||
.size = atlasData.size(),
|
||||
.data = atlasData.data(),
|
||||
},
|
||||
.format = Gfx::SE_FORMAT_R8_UNORM,
|
||||
.width = atlasW,
|
||||
.height = totalH,
|
||||
.name = "FontAtlas",
|
||||
});
|
||||
}
|
||||
@@ -21,24 +21,32 @@ class FontAsset : public Asset {
|
||||
UVector2 bearing = {};
|
||||
uint32 advance = 0;
|
||||
Array<uint8> textureData;
|
||||
Gfx::OTexture2D texture = nullptr;
|
||||
// rect of this glyph inside the per-(font,size) atlas; the atlas texture is
|
||||
// shared by every glyph of the same size (FontData::atlas) — no per-glyph texture
|
||||
Vector2 uvOffset = Vector2(0);
|
||||
Vector2 uvSize = Vector2(0);
|
||||
void save(ArchiveBuffer& buffer) const;
|
||||
void load(ArchiveBuffer& buffer);
|
||||
};
|
||||
struct FontData {
|
||||
Map<uint32, Glyph> glyphs;
|
||||
// the single atlas holding every glyph of this size (created in loadGlyphs)
|
||||
Gfx::OTexture2D atlas = nullptr;
|
||||
};
|
||||
void loadFace();
|
||||
|
||||
// packs every glyph of `fontSize` into one atlas (created lazily on first use by
|
||||
// shapeText); public so the unit test can drive the real packer
|
||||
void loadGlyphs(uint32 fontSize);
|
||||
struct RenderGlyph {
|
||||
Gfx::PTexture2D texture;
|
||||
Gfx::PTexture2D texture; // the font's atlas for this size (shared by all its glyphs)
|
||||
Vector2 uvOffset;
|
||||
Vector2 uvSize;
|
||||
UVector2 position;
|
||||
UVector2 dimensions;
|
||||
};
|
||||
UVector2 shapeText(std::string_view view, uint32 fontSize, Array<RenderGlyph>& render);
|
||||
|
||||
private:
|
||||
void loadGlyphs(uint32 fontSize);
|
||||
Gfx::PGraphics graphics;
|
||||
hb_blob_t* blob;
|
||||
hb_face_t* hb_face;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#include "TextureAsset.h"
|
||||
#include "Graphics/Graphics.h"
|
||||
#include "Graphics/Texture.h"
|
||||
#include "Window/WindowManager.h"
|
||||
#include "Window/Application.h"
|
||||
#include "ktx.h"
|
||||
#include <iostream>
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ target_sources(Engine
|
||||
Game.h
|
||||
MinimalEngine.h
|
||||
ThreadPool.h
|
||||
ThreadPool.cpp "../../tests/Engine/UI/Element.cpp")
|
||||
ThreadPool.cpp)
|
||||
|
||||
target_sources(Engine
|
||||
PUBLIC FILE_SET HEADERS
|
||||
|
||||
@@ -6,6 +6,7 @@ target_sources(Engine
|
||||
Collider.cpp
|
||||
Component.h
|
||||
DirectionalLight.h
|
||||
FluidGrid.h
|
||||
KeyboardInput.h
|
||||
Mesh.h
|
||||
MeshCollider.h
|
||||
@@ -29,6 +30,7 @@ target_sources(Engine
|
||||
Collider.h
|
||||
Component.h
|
||||
DirectionalLight.h
|
||||
FluidGrid.h
|
||||
KeyboardInput.h
|
||||
MeshCollider.h
|
||||
Mesh.h
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
#pragma once
|
||||
#include "Containers/Array.h"
|
||||
#include "Math/Vector.h"
|
||||
|
||||
namespace Seele {
|
||||
namespace Component {
|
||||
struct BoundaryPlane {
|
||||
Vector normal; // inward normal (from solid toward fluid)
|
||||
float d; // plane offset: dot(normal, pos) + d < 0 means solid
|
||||
};
|
||||
struct FluidGrid {
|
||||
bool paused = true;
|
||||
float dt = 0.1f;
|
||||
float viscosity = 0.001f;
|
||||
float diffusion = 0.0001f;
|
||||
UVector gridSize = {128, 128, 128};
|
||||
Vector gravity = {0.0f, -9.81f, 0.0f};
|
||||
bool enableGravity = true;
|
||||
Array<BoundaryPlane> extraPlanes;
|
||||
};
|
||||
} // namespace Component
|
||||
} // namespace Seele
|
||||
@@ -103,6 +103,10 @@ template <typename T> struct Array {
|
||||
}
|
||||
}
|
||||
}
|
||||
// initializer_list elements are const, so they can only be copied, never moved.
|
||||
// For move-only T (e.g. OwningPtr) this ctor is deleted — construct such arrays
|
||||
// with the default ctor + add()/emplace() instead (those move).
|
||||
template <typename U = T, typename = std::enable_if_t<std::is_copy_constructible_v<U>>>
|
||||
constexpr Array(std::initializer_list<T> init, const allocator_type& alloc = allocator_type())
|
||||
: arraySize(init.size()), allocated(init.size()), allocator(alloc) {
|
||||
_data = allocateArray(init.size());
|
||||
@@ -276,7 +280,12 @@ template <typename T> struct Array {
|
||||
T* tempArray = allocateArray(allocated);
|
||||
assert(tempArray != nullptr);
|
||||
|
||||
std::uninitialized_move(begin(), end(), Iterator(tempArray));
|
||||
// begin()/end() yield lvalue iterators, so uninitialized_move would
|
||||
// degrade to a copy — invalid for move-only T (e.g. OwningPtr). Move
|
||||
// each element explicitly instead.
|
||||
for (size_type i = 0; i < arraySize; ++i) {
|
||||
std::allocator_traits<allocator_type>::construct(allocator, &tempArray[i], std::move(_data[i]));
|
||||
}
|
||||
deallocateArray(_data, arraySize);
|
||||
_data = tempArray;
|
||||
}
|
||||
|
||||
@@ -21,6 +21,7 @@ class RenderCommand {
|
||||
virtual void draw(uint32 vertexCount, uint32 instanceCount, int32 firstVertex, uint32 firstInstance) = 0;
|
||||
virtual void drawIndirect(Gfx::PShaderBuffer buffer, uint64 offset, uint32 drawCount, uint32 stride) = 0;
|
||||
virtual void drawIndexed(uint32 indexCount, uint32 instanceCount, int32 firstIndex, uint32 vertexOffset, uint32 firstInstance) = 0;
|
||||
virtual void drawIndexedIndirect(Gfx::PShaderBuffer buffer, uint64 offset, uint32 drawCount, uint32 stride) = 0;
|
||||
virtual void drawMesh(uint32 groupX, uint32 groupY, uint32 groupZ) = 0;
|
||||
virtual void drawMeshIndirect(Gfx::PShaderBuffer buffer, uint64 offset, uint32 drawCount, uint32 stride) = 0;
|
||||
virtual void traceRays(uint32 width, uint32 height, uint32 depth) = 0;
|
||||
|
||||
@@ -59,7 +59,7 @@ class DescriptorSet {
|
||||
DescriptorSet(PDescriptorLayout layout);
|
||||
virtual ~DescriptorSet();
|
||||
virtual void writeChanges() = 0;
|
||||
virtual void updateConstants(const std::string& name, uint32 offset, void* data) = 0;
|
||||
virtual void updateConstants(const std::string& name, uint32 offset, const void* data) = 0;
|
||||
virtual void updateBuffer(const std::string& name, uint32 index, Gfx::PShaderBuffer shaderBuffer) = 0;
|
||||
virtual void updateBuffer(const std::string& name, uint32 index, Gfx::PVertexBuffer vertexBuffer) = 0;
|
||||
virtual void updateBuffer(const std::string& name, uint32 index, Gfx::PIndexBuffer indexBuffer) = 0;
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
#include "MinimalEngine.h"
|
||||
#include "RenderTarget.h"
|
||||
#include "Resources.h"
|
||||
|
||||
#define ENABLE_VALIDATION
|
||||
|
||||
namespace Seele {
|
||||
namespace Gfx {
|
||||
@@ -61,6 +61,10 @@ class Graphics {
|
||||
virtual void endRenderPass() = 0;
|
||||
virtual void waitDeviceIdle() = 0;
|
||||
|
||||
// Invalidate per-render-pass framebuffers cached on resize (their attachments are
|
||||
// recreated each resize). Default no-op; the Vulkan backend overrides it.
|
||||
virtual void invalidateFramebuffers() {}
|
||||
|
||||
virtual void executeCommands(ORenderCommand commands) = 0;
|
||||
virtual void executeCommands(Array<ORenderCommand> commands) = 0;
|
||||
virtual void executeCommands(OComputeCommand commands) = 0;
|
||||
|
||||
@@ -20,7 +20,11 @@ struct GraphicsInitializer {
|
||||
Array<const char*> deviceExtensions;
|
||||
|
||||
void* windowHandle;
|
||||
GraphicsInitializer() : applicationName("SeeleEngine"), engineName("SeeleEngine"), windowLayoutFile(nullptr), windowHandle(nullptr) {}
|
||||
// When true, the Vulkan device is created in headless mode: no WSI surface
|
||||
// extensions, no GLFW init, no swapchain device extension, no window.
|
||||
// Used for machines that have a Vulkan driver but no display.
|
||||
bool headless;
|
||||
GraphicsInitializer() : applicationName("SeeleEngine"), engineName("SeeleEngine"), windowLayoutFile(nullptr), windowHandle(nullptr), headless(false) {}
|
||||
};
|
||||
struct WindowCreateInfo {
|
||||
int32 width;
|
||||
|
||||
@@ -29,7 +29,7 @@ class Window : public Gfx::Window {
|
||||
virtual void setKeyCallback(std::function<void(KeyCode, InputAction, KeyModifier)> callback) override;
|
||||
virtual void setMouseMoveCallback(std::function<void(double, double)> callback) override;
|
||||
virtual void setMouseButtonCallback(std::function<void(MouseButton, InputAction, KeyModifier)> callback) override;
|
||||
virtual void setScrollCallback(std::function<void(double, double)> callback) override;
|
||||
virtual void setScrollCallback(std::function<void(double x, double y, double xScroll, double yScroll)> callback) override;
|
||||
virtual void setFileCallback(std::function<void(int, const char**)> callback) override;
|
||||
virtual void setCloseCallback(std::function<void()> callback) override;
|
||||
virtual void setResizeCallback(std::function<void(uint32, uint32)> callback) override;
|
||||
@@ -37,7 +37,7 @@ class Window : public Gfx::Window {
|
||||
void keyPress(KeyCode code, InputAction action, KeyModifier modifier);
|
||||
void mouseMove(double x, double y);
|
||||
void mouseButton(MouseButton button, InputAction action, KeyModifier modifier);
|
||||
void scroll(double x, double y);
|
||||
void scroll(double x, double y, double xScroll, double yScroll);
|
||||
void fileDrop(int num, const char** files);
|
||||
void close();
|
||||
void resize(int width, int height);
|
||||
@@ -57,7 +57,7 @@ class Window : public Gfx::Window {
|
||||
std::function<void(KeyCode, InputAction, KeyModifier)> keyCallback;
|
||||
std::function<void(double, double)> mouseMoveCallback;
|
||||
std::function<void(MouseButton, InputAction, KeyModifier)> mouseButtonCallback;
|
||||
std::function<void(double, double)> scrollCallback;
|
||||
std::function<void(double x, double y, double xScroll, double yScroll)> scrollCallback;
|
||||
std::function<void(int, const char**)> fileCallback;
|
||||
std::function<void()> closeCallback;
|
||||
std::function<void(uint32, uint32)> resizeCallback;
|
||||
|
||||
@@ -44,7 +44,9 @@ void glfwMouseButtonCallback(GLFWwindow* handle, int button, int action, int mod
|
||||
|
||||
void glfwScrollCallback(GLFWwindow* handle, double xoffset, double yoffset) {
|
||||
Window* window = (Window*)glfwGetWindowUserPointer(handle);
|
||||
window->scroll(xoffset, yoffset);
|
||||
double x = 0.0, y = 0.0;
|
||||
glfwGetCursorPos(handle, &x, &y);
|
||||
window->scroll(x, y, xoffset, yoffset);
|
||||
}
|
||||
|
||||
void glfwFileCallback(GLFWwindow* handle, int count, const char** paths) {
|
||||
@@ -127,7 +129,7 @@ void Window::setMouseMoveCallback(std::function<void(double, double)> callback)
|
||||
|
||||
void Window::setMouseButtonCallback(std::function<void(MouseButton, InputAction, KeyModifier)> callback) { mouseButtonCallback = callback; }
|
||||
|
||||
void Window::setScrollCallback(std::function<void(double, double)> callback) { scrollCallback = callback; }
|
||||
void Window::setScrollCallback(std::function<void(double x, double y, double xScroll, double yScroll)> callback) { scrollCallback = callback; }
|
||||
|
||||
void Window::setFileCallback(std::function<void(int, const char**)> callback) { fileCallback = callback; }
|
||||
|
||||
@@ -141,7 +143,7 @@ void Window::mouseMove(double x, double y) { mouseMoveCallback(x, y); }
|
||||
|
||||
void Window::mouseButton(MouseButton button, InputAction action, KeyModifier modifier) { mouseButtonCallback(button, action, modifier); }
|
||||
|
||||
void Window::scroll(double x, double y) { scrollCallback(x, y); }
|
||||
void Window::scroll(double x, double y, double xScroll, double yScroll) { scrollCallback(x, y, xScroll, yScroll); }
|
||||
|
||||
void Window::fileDrop(int num, const char** files) { fileCallback(num, files); }
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#include "BasePass.h"
|
||||
#include "Asset/AssetRegistry.h"
|
||||
#include "Asset/EnvironmentMapAsset.h"
|
||||
#include "Component/Camera.h"
|
||||
#include "Graphics/Command.h"
|
||||
#include "Graphics/Descriptor.h"
|
||||
@@ -12,10 +13,9 @@
|
||||
#include "Math/Matrix.h"
|
||||
#include "Math/Vector.h"
|
||||
#include "MinimalEngine.h"
|
||||
#include "ShadowPass.h"
|
||||
#include "Scene/Scene.h"
|
||||
#include "Asset/EnvironmentMapAsset.h"
|
||||
#include "Scene/LightEnvironment.h"
|
||||
#include "Scene/Scene.h"
|
||||
#include "ShadowPass.h"
|
||||
|
||||
using namespace Seele;
|
||||
|
||||
@@ -59,10 +59,8 @@ BasePass::BasePass(Gfx::PGraphics graphics, PScene scene) : RenderPass(graphics)
|
||||
.name = SHADOWSAMPLER_NAME,
|
||||
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_SAMPLER,
|
||||
});
|
||||
shadowMappingLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = CASCADE_SPLIT_NAME,
|
||||
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_UNIFORM_BUFFER
|
||||
});
|
||||
shadowMappingLayout->addDescriptorBinding(
|
||||
Gfx::DescriptorBinding{.name = CASCADE_SPLIT_NAME, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_UNIFORM_BUFFER});
|
||||
shadowMappingLayout->create();
|
||||
|
||||
basePassLayout->addDescriptorLayout(lightCullingLayout);
|
||||
@@ -116,6 +114,58 @@ BasePass::BasePass(Gfx::PGraphics graphics, PScene scene) : RenderPass(graphics)
|
||||
.minLod = 0.0f,
|
||||
.borderColor = Gfx::SE_BORDER_COLOR_FLOAT_OPAQUE_WHITE,
|
||||
});
|
||||
debugPipelineLayout = graphics->createPipelineLayout("DebugPassLayout");
|
||||
debugPipelineLayout->addDescriptorLayout(viewParamsLayout);
|
||||
|
||||
graphics->beginShaderCompilation(ShaderCompilationInfo{
|
||||
.name = "DebugVertex",
|
||||
.modules = {"Debug"},
|
||||
.entryPoints =
|
||||
{
|
||||
{"vertexMain", "Debug"},
|
||||
{"fragmentMain", "Debug"},
|
||||
},
|
||||
.rootSignature = debugPipelineLayout,
|
||||
});
|
||||
debugVertexShader = graphics->createVertexShader({0});
|
||||
debugFragmentShader = graphics->createFragmentShader({1});
|
||||
debugPipelineLayout->create();
|
||||
|
||||
skyboxDataLayout = graphics->createDescriptorLayout("pSkyboxData");
|
||||
skyboxDataLayout->addDescriptorBinding(Gfx::DescriptorBinding{.name = "transformMatrix", .uniformLength = sizeof(Matrix4)});
|
||||
skyboxDataLayout->addDescriptorBinding(Gfx::DescriptorBinding{.name = "fogBlend", .uniformLength = sizeof(Vector4)});
|
||||
skyboxDataLayout->create();
|
||||
textureLayout = graphics->createDescriptorLayout("pSkyboxTextures");
|
||||
textureLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = SKYBOXDAY_NAME,
|
||||
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_SAMPLED_IMAGE,
|
||||
.access = Gfx::SE_DESCRIPTOR_ACCESS_SAMPLE_BIT,
|
||||
});
|
||||
textureLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = SKYBOXNIGHT_NAME,
|
||||
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_SAMPLED_IMAGE,
|
||||
.access = Gfx::SE_DESCRIPTOR_ACCESS_SAMPLE_BIT,
|
||||
});
|
||||
textureLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = SKYBOXSAMPLER_NAME,
|
||||
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_SAMPLER,
|
||||
});
|
||||
textureLayout->create();
|
||||
|
||||
pipelineLayout = graphics->createPipelineLayout("SkyboxLayout");
|
||||
pipelineLayout->addDescriptorLayout(viewParamsLayout);
|
||||
pipelineLayout->addDescriptorLayout(skyboxDataLayout);
|
||||
pipelineLayout->addDescriptorLayout(textureLayout);
|
||||
|
||||
graphics->beginShaderCompilation(ShaderCompilationInfo{
|
||||
.name = "SkyboxVertex",
|
||||
.modules = {"Skybox"},
|
||||
.entryPoints = {{"vertexMain", "Skybox"}, {"fragmentMain", "Skybox"}},
|
||||
.rootSignature = pipelineLayout,
|
||||
});
|
||||
vertexShader = graphics->createVertexShader({0});
|
||||
fragmentShader = graphics->createFragmentShader({1});
|
||||
pipelineLayout->create();
|
||||
}
|
||||
|
||||
BasePass::~BasePass() {}
|
||||
@@ -176,7 +226,7 @@ void BasePass::render() {
|
||||
transparentCulling->updateTexture(LIGHTGRID_NAME, 0, tLightGrid->getDefaultView());
|
||||
opaqueCulling->writeChanges();
|
||||
transparentCulling->writeChanges();
|
||||
|
||||
|
||||
shadowMappingLayout->reset();
|
||||
shadowMapping = shadowMappingLayout->allocateDescriptorSet();
|
||||
for (uint32 i = 0; i < NUM_CASCADES; ++i) {
|
||||
@@ -268,7 +318,8 @@ void BasePass::render() {
|
||||
command->bindPipeline(graphics->createGraphicsPipeline(std::move(pipelineInfo)));
|
||||
}
|
||||
command->bindDescriptor({viewParamsSet, vertexData->getVertexDataSet(), vertexData->getInstanceDataSet(),
|
||||
scene->getLightEnvironment()->getDescriptorSet(), Material::getDescriptorSet(), shadowMapping, opaqueCulling});
|
||||
scene->getLightEnvironment()->getDescriptorSet(), Material::getDescriptorSet(), shadowMapping,
|
||||
opaqueCulling});
|
||||
for (const auto& drawCall : materialData.instances) {
|
||||
command->pushConstants(Gfx::SE_SHADER_STAGE_TASK_BIT_EXT | Gfx::SE_SHADER_STAGE_VERTEX_BIT |
|
||||
Gfx::SE_SHADER_STAGE_FRAGMENT_BIT,
|
||||
@@ -382,8 +433,8 @@ void BasePass::render() {
|
||||
transparentCommand->bindPipeline(pipeline);
|
||||
}
|
||||
transparentCommand->bindDescriptor({viewParamsSet, t.vertexData->getVertexDataSet(), t.vertexData->getInstanceDataSet(),
|
||||
scene->getLightEnvironment()->getDescriptorSet(), Material::getDescriptorSet(), shadowMapping,
|
||||
transparentCulling});
|
||||
scene->getLightEnvironment()->getDescriptorSet(), Material::getDescriptorSet(),
|
||||
shadowMapping, transparentCulling});
|
||||
transparentCommand->pushConstants(Gfx::SE_SHADER_STAGE_TASK_BIT_EXT | Gfx::SE_SHADER_STAGE_VERTEX_BIT |
|
||||
Gfx::SE_SHADER_STAGE_FRAGMENT_BIT,
|
||||
0, sizeof(VertexData::DrawCallOffsets), &t.offsets);
|
||||
@@ -424,32 +475,39 @@ void BasePass::render() {
|
||||
void BasePass::endFrame() {}
|
||||
|
||||
void BasePass::publishOutputs() {
|
||||
// Size intermediates to the *view* (viewport), not the full window framebuffer. A split
|
||||
// window (e.g. the editor's 50/50 game/inspector layout) renders each view into its own
|
||||
// half-width slice; the shared framebuffers must match that slice or the renderArea (the
|
||||
// view's half) ends up a window into an over-wide attachment, clipping the image.
|
||||
uint32 viewWidth = viewport->getWidth();
|
||||
uint32 viewHeight = viewport->getHeight();
|
||||
|
||||
basePassDepth = graphics->createTexture2D(TextureCreateInfo{
|
||||
.format = Gfx::SE_FORMAT_D32_SFLOAT,
|
||||
.width = viewport->getOwner()->getFramebufferWidth(),
|
||||
.height = viewport->getOwner()->getFramebufferHeight(),
|
||||
.width = viewWidth,
|
||||
.height = viewHeight,
|
||||
.usage = Gfx::SE_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT,
|
||||
});
|
||||
|
||||
basePassColor = graphics->createTexture2D(TextureCreateInfo{
|
||||
.format = Gfx::SE_FORMAT_R32G32B32A32_SFLOAT,
|
||||
.width = viewport->getOwner()->getFramebufferWidth(),
|
||||
.height = viewport->getOwner()->getFramebufferHeight(),
|
||||
.width = viewWidth,
|
||||
.height = viewHeight,
|
||||
.usage = Gfx::SE_IMAGE_USAGE_COLOR_ATTACHMENT_BIT,
|
||||
});
|
||||
|
||||
msBasePassDepth = graphics->createTexture2D(TextureCreateInfo{
|
||||
.format = Gfx::SE_FORMAT_D32_SFLOAT,
|
||||
.width = viewport->getOwner()->getFramebufferWidth(),
|
||||
.height = viewport->getOwner()->getFramebufferHeight(),
|
||||
.width = viewWidth,
|
||||
.height = viewHeight,
|
||||
.samples = Gfx::SE_SAMPLE_COUNT_4_BIT,
|
||||
.usage = Gfx::SE_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | Gfx::SE_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT,
|
||||
});
|
||||
|
||||
msBasePassColor = graphics->createTexture2D(TextureCreateInfo{
|
||||
.format = Gfx::SE_FORMAT_R32G32B32A32_SFLOAT,
|
||||
.width = viewport->getOwner()->getFramebufferWidth(),
|
||||
.height = viewport->getOwner()->getFramebufferHeight(),
|
||||
.width = viewWidth,
|
||||
.height = viewHeight,
|
||||
.samples = Gfx::SE_SAMPLE_COUNT_4_BIT, // todo: configure
|
||||
.usage = Gfx::SE_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | Gfx::SE_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT,
|
||||
});
|
||||
@@ -536,24 +594,6 @@ void BasePass::createRenderPass() {
|
||||
|
||||
// Debug rendering
|
||||
{
|
||||
debugPipelineLayout = graphics->createPipelineLayout("DebugPassLayout");
|
||||
debugPipelineLayout->addDescriptorLayout(viewParamsLayout);
|
||||
|
||||
ShaderCompilationInfo createInfo = {
|
||||
.name = "DebugVertex",
|
||||
.modules = {"Debug"},
|
||||
.entryPoints =
|
||||
{
|
||||
{"vertexMain", "Debug"},
|
||||
{"fragmentMain", "Debug"},
|
||||
},
|
||||
.rootSignature = debugPipelineLayout,
|
||||
};
|
||||
graphics->beginShaderCompilation(createInfo);
|
||||
debugVertexShader = graphics->createVertexShader({0});
|
||||
debugFragmentShader = graphics->createFragmentShader({1});
|
||||
debugPipelineLayout->create();
|
||||
|
||||
VertexInputStateCreateInfo inputCreate = {
|
||||
.bindings =
|
||||
{
|
||||
@@ -605,27 +645,6 @@ void BasePass::createRenderPass() {
|
||||
}
|
||||
// Skybox
|
||||
{
|
||||
skyboxDataLayout = graphics->createDescriptorLayout("pSkyboxData");
|
||||
skyboxDataLayout->addDescriptorBinding(Gfx::DescriptorBinding{.name = "transformMatrix", .uniformLength = sizeof(Matrix4)});
|
||||
skyboxDataLayout->addDescriptorBinding(Gfx::DescriptorBinding{.name = "fogBlend", .uniformLength = sizeof(Vector4)});
|
||||
skyboxDataLayout->create();
|
||||
textureLayout = graphics->createDescriptorLayout("pSkyboxTextures");
|
||||
textureLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = SKYBOXDAY_NAME,
|
||||
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_SAMPLED_IMAGE,
|
||||
.access = Gfx::SE_DESCRIPTOR_ACCESS_SAMPLE_BIT,
|
||||
});
|
||||
textureLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = SKYBOXNIGHT_NAME,
|
||||
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_SAMPLED_IMAGE,
|
||||
.access = Gfx::SE_DESCRIPTOR_ACCESS_SAMPLE_BIT,
|
||||
});
|
||||
textureLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = SKYBOXSAMPLER_NAME,
|
||||
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_SAMPLER,
|
||||
});
|
||||
textureLayout->create();
|
||||
|
||||
skyboxSampler = graphics->createSampler({
|
||||
.magFilter = Gfx::SE_FILTER_LINEAR,
|
||||
.minFilter = Gfx::SE_FILTER_LINEAR,
|
||||
@@ -642,23 +661,6 @@ void BasePass::createRenderPass() {
|
||||
skyboxData.fogColor = skybox.fogColor;
|
||||
skyboxData.blendFactor = skybox.blendFactor;
|
||||
|
||||
pipelineLayout = graphics->createPipelineLayout("SkyboxLayout");
|
||||
pipelineLayout->addDescriptorLayout(viewParamsLayout);
|
||||
pipelineLayout->addDescriptorLayout(skyboxDataLayout);
|
||||
pipelineLayout->addDescriptorLayout(textureLayout);
|
||||
|
||||
ShaderCompilationInfo createInfo = {
|
||||
.name = "SkyboxVertex",
|
||||
.modules = {"Skybox"},
|
||||
.entryPoints = {{"vertexMain", "Skybox"}, {"fragmentMain", "Skybox"}},
|
||||
.rootSignature = pipelineLayout,
|
||||
};
|
||||
graphics->beginShaderCompilation(createInfo);
|
||||
vertexShader = graphics->createVertexShader({0});
|
||||
fragmentShader = graphics->createFragmentShader({1});
|
||||
|
||||
pipelineLayout->create();
|
||||
|
||||
Gfx::LegacyPipelineCreateInfo gfxInfo = {
|
||||
.topology = Gfx::SE_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST,
|
||||
.vertexShader = vertexShader,
|
||||
@@ -673,10 +675,11 @@ void BasePass::createRenderPass() {
|
||||
{
|
||||
.polygonMode = Gfx::SE_POLYGON_MODE_FILL,
|
||||
},
|
||||
.depthStencilState = {
|
||||
.depthTestEnable = true,
|
||||
.depthCompareOp = Gfx::SE_COMPARE_OP_GREATER,
|
||||
},
|
||||
.depthStencilState =
|
||||
{
|
||||
.depthTestEnable = true,
|
||||
.depthCompareOp = Gfx::SE_COMPARE_OP_GREATER,
|
||||
},
|
||||
.colorBlend =
|
||||
{
|
||||
.attachmentCount = 1,
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
#include "Graphics/Buffer.h"
|
||||
#include "Graphics/Descriptor.h"
|
||||
#include "Graphics/RenderPass/ShadowPass.h"
|
||||
#include "Component/Skybox.h"
|
||||
#include "MinimalEngine.h"
|
||||
#include "RenderPass.h"
|
||||
|
||||
|
||||
@@ -6,6 +6,8 @@ target_sources(Engine
|
||||
CachedDepthPass.cpp
|
||||
DepthCullingPass.h
|
||||
DepthCullingPass.cpp
|
||||
FluidRenderPass.h
|
||||
FluidRenderPass.cpp
|
||||
LightCullingPass.h
|
||||
LightCullingPass.cpp
|
||||
RayTracingPass.h
|
||||
@@ -17,6 +19,10 @@ target_sources(Engine
|
||||
RenderPass.cpp
|
||||
ShadowPass.h
|
||||
ShadowPass.cpp
|
||||
SimulationComputePass.h
|
||||
SimulationComputePass.cpp
|
||||
SurfaceExtractPass.h
|
||||
SurfaceExtractPass.cpp
|
||||
#TerrainRenderer.h
|
||||
#TerrainRenderer.cpp
|
||||
ToneMappingPass.h
|
||||
@@ -34,6 +40,7 @@ target_sources(Engine
|
||||
BasePass.h
|
||||
CachedDepthPass.h
|
||||
DepthCullingPass.h
|
||||
FluidRenderPass.h
|
||||
LightCullingPass.h
|
||||
ToneMappingPass.h
|
||||
RayTracingPass.h
|
||||
@@ -41,6 +48,8 @@ target_sources(Engine
|
||||
RenderGraphResources.h
|
||||
RenderPass.h
|
||||
ShadowPass.h
|
||||
SimulationComputePass.h
|
||||
SurfaceExtractPass.h
|
||||
#TerrainRenderer.h
|
||||
UIPass.h
|
||||
VisibilityPass.h)
|
||||
@@ -37,6 +37,24 @@ DepthCullingPass::DepthCullingPass(Gfx::PGraphics graphics, PScene scene) : Rend
|
||||
.size = sizeof(MipParam),
|
||||
.name = "pMipParam"
|
||||
});
|
||||
graphics->beginShaderCompilation(ShaderCompilationInfo{
|
||||
.name = "DepthMipCompute",
|
||||
.modules = {"DepthMipGen"},
|
||||
.entryPoints = {{"sourceCopy", "DepthMipGen"}, {"reduceLevel", "DepthMipGen"}},
|
||||
.rootSignature = depthComputeLayout,
|
||||
});
|
||||
depthSourceCopyShader = graphics->createComputeShader({0});
|
||||
depthComputeLayout->create();
|
||||
|
||||
Gfx::ComputePipelineCreateInfo pipelineCreateInfo = {
|
||||
.computeShader = depthSourceCopyShader,
|
||||
.pipelineLayout = depthComputeLayout,
|
||||
};
|
||||
depthSourceCopy = graphics->createComputePipeline(pipelineCreateInfo);
|
||||
|
||||
depthReduceLevelShader = graphics->createComputeShader({1});
|
||||
pipelineCreateInfo.computeShader = depthReduceLevelShader;
|
||||
depthReduceLevel = graphics->createComputePipeline(pipelineCreateInfo);
|
||||
|
||||
if (graphics->supportMeshShading()) {
|
||||
graphics->getShaderCompiler()->registerRenderPass("DepthPass", Gfx::PassConfig{
|
||||
@@ -255,24 +273,6 @@ void DepthCullingPass::publishOutputs() {
|
||||
.name = "DepthMipBuffer",
|
||||
});
|
||||
|
||||
graphics->beginShaderCompilation(ShaderCompilationInfo{
|
||||
.name = "DepthMipCompute",
|
||||
.modules = {"DepthMipGen"},
|
||||
.entryPoints = {{"sourceCopy", "DepthMipGen"}, {"reduceLevel", "DepthMipGen"}},
|
||||
.rootSignature = depthComputeLayout,
|
||||
});
|
||||
depthSourceCopyShader = graphics->createComputeShader({0});
|
||||
depthComputeLayout->create();
|
||||
|
||||
Gfx::ComputePipelineCreateInfo pipelineCreateInfo = {
|
||||
.computeShader = depthSourceCopyShader,
|
||||
.pipelineLayout = depthComputeLayout,
|
||||
};
|
||||
depthSourceCopy = graphics->createComputePipeline(pipelineCreateInfo);
|
||||
|
||||
depthReduceLevelShader = graphics->createComputeShader({1});
|
||||
pipelineCreateInfo.computeShader = depthReduceLevelShader;
|
||||
depthReduceLevel = graphics->createComputePipeline(pipelineCreateInfo);
|
||||
|
||||
query = graphics->createPipelineStatisticsQuery("DepthPipelineStatistics");
|
||||
resources->registerQueryOutput("DEPTH_QUERY", query);
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
#include "FluidRenderPass.h"
|
||||
#include "Component/Transform.h"
|
||||
#include "Graphics/Command.h"
|
||||
#include "Graphics/Descriptor.h"
|
||||
#include "Graphics/Enums.h"
|
||||
#include "Graphics/Graphics.h"
|
||||
#include "Graphics/Initializer.h"
|
||||
#include "Graphics/RenderTarget.h"
|
||||
#include "Graphics/Shader.h"
|
||||
#include "Math/Matrix.h"
|
||||
#include "Scene/LightEnvironment.h"
|
||||
#include "Scene/Scene.h"
|
||||
#include "Scene/FluidScene.h"
|
||||
|
||||
using namespace Seele;
|
||||
|
||||
FluidRenderPass::FluidRenderPass(Gfx::PGraphics graphics, PScene scene) : RenderPass(graphics), scene(scene) {
|
||||
pipelineLayout = graphics->createPipelineLayout("FluidPipelineLayout");
|
||||
descriptorLayout = graphics->createDescriptorLayout("params");
|
||||
descriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = "transform",
|
||||
.uniformLength = sizeof(Matrix4),
|
||||
});
|
||||
descriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = "vertexBuffer",
|
||||
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER,
|
||||
});
|
||||
descriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = "normalBuffer",
|
||||
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER,
|
||||
});
|
||||
descriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = "indexBuffer",
|
||||
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER,
|
||||
});
|
||||
descriptorLayout->create();
|
||||
pipelineLayout->addDescriptorLayout(viewParamsLayout);
|
||||
pipelineLayout->addDescriptorLayout(descriptorLayout);
|
||||
pipelineLayout->addDescriptorLayout(scene->getLightEnvironment()->getDescriptorLayout());
|
||||
|
||||
graphics->beginShaderCompilation(ShaderCompilationInfo{
|
||||
.name = "Fluid",
|
||||
.modules = {"Render"},
|
||||
.entryPoints = {{"vertexMain", "Render"}, {"fragmentMain", "Render"}},
|
||||
.rootSignature = pipelineLayout,
|
||||
});
|
||||
pipelineLayout->create();
|
||||
vertexShader = graphics->createVertexShader({0});
|
||||
fragmentShader = graphics->createFragmentShader({1});
|
||||
}
|
||||
|
||||
FluidRenderPass::~FluidRenderPass() {}
|
||||
|
||||
void FluidRenderPass::beginFrame(const Seele::Component::Camera& camera, const Seele::Component::Transform& transform) {
|
||||
updateViewParameters(camera, transform);
|
||||
}
|
||||
|
||||
void FluidRenderPass::render() {
|
||||
viewParamsSet = createViewParamsSet();
|
||||
graphics->beginRenderPass(renderPass);
|
||||
descriptorLayout->reset();
|
||||
for (const auto& [id, data] : scene->getFluidScene()->getFluidDataMap()) {
|
||||
descriptorSet = descriptorLayout->allocateDescriptorSet();
|
||||
Matrix4 transformMatrix = data.transform.toMatrix();
|
||||
descriptorSet->updateConstants("transform", 0, &transformMatrix);
|
||||
descriptorSet->updateBuffer("vertexBuffer", 0, data.vertexBuffer);
|
||||
descriptorSet->updateBuffer("normalBuffer", 0, data.normalBuffer);
|
||||
descriptorSet->updateBuffer("indexBuffer", 0, data.indexBuffer);
|
||||
descriptorSet->writeChanges();
|
||||
Gfx::ORenderCommand renderCommand = graphics->createRenderCommand();
|
||||
renderCommand->setViewport(viewport);
|
||||
renderCommand->bindPipeline(pipeline);
|
||||
renderCommand->bindDescriptor(viewParamsSet);
|
||||
renderCommand->bindDescriptor(descriptorSet);
|
||||
renderCommand->bindDescriptor(scene->getLightEnvironment()->getDescriptorSet());
|
||||
renderCommand->drawIndirect(data.surfaceCountBuffer, 0, 1, 0);
|
||||
graphics->executeCommands(std::move(renderCommand));
|
||||
}
|
||||
graphics->endRenderPass();
|
||||
}
|
||||
|
||||
void FluidRenderPass::endFrame() {}
|
||||
|
||||
void FluidRenderPass::publishOutputs() {
|
||||
}
|
||||
|
||||
|
||||
void FluidRenderPass::createRenderPass() {
|
||||
colorAttachment = resources->requestRenderTarget("BASEPASS_COLOR");
|
||||
colorAttachment.setLoadOp(Gfx::SE_ATTACHMENT_LOAD_OP_LOAD);
|
||||
colorAttachment.setInitialLayout(Gfx::SE_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
|
||||
depthAttachment = resources->requestRenderTarget("BASEPASS_DEPTH");
|
||||
depthAttachment.setLoadOp(Gfx::SE_ATTACHMENT_LOAD_OP_LOAD);
|
||||
depthAttachment.setInitialLayout(Gfx::SE_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL);
|
||||
Gfx::RenderTargetLayout layout = Gfx::RenderTargetLayout{
|
||||
.colorAttachments = {colorAttachment},
|
||||
.depthAttachment = depthAttachment,
|
||||
};
|
||||
Array<Gfx::SubPassDependency> dependency = {
|
||||
{
|
||||
.srcSubpass = ~0U,
|
||||
.dstSubpass = 0,
|
||||
.srcStage = Gfx::SE_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | Gfx::SE_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT |
|
||||
Gfx::SE_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT,
|
||||
.dstStage = Gfx::SE_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | Gfx::SE_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT |
|
||||
Gfx::SE_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT,
|
||||
.srcAccess = Gfx::SE_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT |
|
||||
Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT,
|
||||
.dstAccess = Gfx::SE_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT |
|
||||
Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT,
|
||||
},
|
||||
{
|
||||
.srcSubpass = 0,
|
||||
.dstSubpass = ~0U,
|
||||
.srcStage = Gfx::SE_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | Gfx::SE_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT |
|
||||
Gfx::SE_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT,
|
||||
.dstStage = Gfx::SE_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | Gfx::SE_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT |
|
||||
Gfx::SE_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT,
|
||||
.srcAccess = Gfx::SE_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT |
|
||||
Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT,
|
||||
.dstAccess = Gfx::SE_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT |
|
||||
Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT,
|
||||
},
|
||||
};
|
||||
|
||||
renderPass = graphics->createRenderPass(layout, dependency, viewport->getRenderArea(), "FluidRenderPass");
|
||||
pipeline = graphics->createGraphicsPipeline(Gfx::LegacyPipelineCreateInfo{
|
||||
.vertexShader = vertexShader,
|
||||
.fragmentShader = fragmentShader,
|
||||
.renderPass = renderPass,
|
||||
.pipelineLayout = pipelineLayout,
|
||||
.multisampleState =
|
||||
{
|
||||
.samples = Gfx::SE_SAMPLE_COUNT_1_BIT,
|
||||
},
|
||||
.rasterizationState =
|
||||
{
|
||||
.cullMode = Gfx::SE_CULL_MODE_NONE,
|
||||
},
|
||||
.colorBlend =
|
||||
{
|
||||
.attachmentCount = 1,
|
||||
.blendAttachments =
|
||||
{
|
||||
Gfx::ColorBlendState::BlendAttachment{
|
||||
.blendEnable = true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
#pragma once
|
||||
#include "Component/Transform.h"
|
||||
#include "Graphics/Descriptor.h"
|
||||
#include "Graphics/Initializer.h"
|
||||
#include "Graphics/RenderPass/RenderPass.h"
|
||||
#include "MinimalEngine.h"
|
||||
#include "Scene/Scene.h"
|
||||
|
||||
namespace Seele {
|
||||
class FluidRenderPass : public RenderPass {
|
||||
public:
|
||||
FluidRenderPass(Gfx::PGraphics graphics, PScene scene);
|
||||
virtual ~FluidRenderPass() override;
|
||||
|
||||
virtual void beginFrame(const Component::Camera& camera, const Component::Transform& transform) override;
|
||||
virtual void render() override;
|
||||
virtual void endFrame() override;
|
||||
|
||||
virtual void publishOutputs() override;
|
||||
virtual void createRenderPass() override;
|
||||
|
||||
private:
|
||||
Gfx::RenderTargetAttachment colorAttachment;
|
||||
Gfx::RenderTargetAttachment depthAttachment;
|
||||
|
||||
Gfx::ODescriptorSet viewParamsSet;
|
||||
|
||||
Gfx::OPipelineLayout pipelineLayout;
|
||||
Gfx::ODescriptorLayout descriptorLayout;
|
||||
Gfx::ODescriptorSet descriptorSet;
|
||||
Gfx::OVertexShader vertexShader;
|
||||
Gfx::OFragmentShader fragmentShader;
|
||||
Gfx::PGraphicsPipeline pipeline;
|
||||
|
||||
PScene scene;
|
||||
};
|
||||
DEFINE_REF(FluidRenderPass)
|
||||
} // namespace Seele
|
||||
@@ -8,10 +8,141 @@
|
||||
#include "Math/Vector.h"
|
||||
#include "RenderGraph.h"
|
||||
#include "Scene/Scene.h"
|
||||
#include "Scene/LightEnvironment.h"
|
||||
|
||||
using namespace Seele;
|
||||
|
||||
LightCullingPass::LightCullingPass(Gfx::PGraphics graphics, PScene scene) : RenderPass(graphics), scene(scene) {}
|
||||
LightCullingPass::LightCullingPass(Gfx::PGraphics graphics, PScene scene) : RenderPass(graphics), scene(scene) {
|
||||
dispatchParamsLayout = graphics->createDescriptorLayout("pDispatchParams");
|
||||
dispatchParamsLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = "numThreadGroups",
|
||||
.uniformLength = sizeof(UVector4),
|
||||
});
|
||||
dispatchParamsLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = "numThreads",
|
||||
.uniformLength = sizeof(UVector4),
|
||||
});
|
||||
dispatchParamsLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = FRUSTUMBUFFER_NAME,
|
||||
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER,
|
||||
.access = Gfx::SE_DESCRIPTOR_ACCESS_WRITE_BIT,
|
||||
});
|
||||
dispatchParamsLayout->create();
|
||||
frustumLayout = graphics->createPipelineLayout("FrustumLayout");
|
||||
frustumLayout->addDescriptorLayout(viewParamsLayout);
|
||||
frustumLayout->addDescriptorLayout(dispatchParamsLayout);
|
||||
ShaderCompilationInfo createInfo = {
|
||||
.name = "Frustum",
|
||||
.modules = {"ComputeFrustums"},
|
||||
.entryPoints = {{"computeFrustums", "ComputeFrustums"}},
|
||||
.rootSignature = frustumLayout,
|
||||
};
|
||||
graphics->beginShaderCompilation(createInfo);
|
||||
frustumShader = graphics->createComputeShader({0});
|
||||
// Have to compile shader before finalizing layout as parameters get mapped later
|
||||
frustumLayout->create();
|
||||
|
||||
Gfx::ComputePipelineCreateInfo pipelineInfo;
|
||||
pipelineInfo.computeShader = frustumShader;
|
||||
pipelineInfo.pipelineLayout = frustumLayout;
|
||||
frustumPipeline = graphics->createComputePipeline(pipelineInfo);
|
||||
|
||||
cullingDescriptorLayout = graphics->createDescriptorLayout("pCullingParams");
|
||||
|
||||
// DepthTexture
|
||||
cullingDescriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = DEPTHATTACHMENT_NAME,
|
||||
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_SAMPLED_IMAGE,
|
||||
.access = Gfx::SE_DESCRIPTOR_ACCESS_SAMPLE_BIT,
|
||||
});
|
||||
// o_lightIndexCounter
|
||||
cullingDescriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = OLIGHTINDEXCOUNTER_NAME,
|
||||
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER,
|
||||
.access = Gfx::SE_DESCRIPTOR_ACCESS_READ_BIT | Gfx::SE_DESCRIPTOR_ACCESS_WRITE_BIT,
|
||||
});
|
||||
// t_lightIndexCounter
|
||||
cullingDescriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = TLIGHTINDEXCOUNTER_NAME,
|
||||
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER,
|
||||
.access = Gfx::SE_DESCRIPTOR_ACCESS_READ_BIT | Gfx::SE_DESCRIPTOR_ACCESS_WRITE_BIT,
|
||||
});
|
||||
// o_lightIndexList
|
||||
cullingDescriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = OLIGHTINDEXLIST_NAME,
|
||||
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER,
|
||||
.access = Gfx::SE_DESCRIPTOR_ACCESS_READ_BIT | Gfx::SE_DESCRIPTOR_ACCESS_WRITE_BIT,
|
||||
});
|
||||
// t_lightIndexList
|
||||
cullingDescriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = TLIGHTINDEXLIST_NAME,
|
||||
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER,
|
||||
.access = Gfx::SE_DESCRIPTOR_ACCESS_READ_BIT | Gfx::SE_DESCRIPTOR_ACCESS_WRITE_BIT,
|
||||
});
|
||||
// o_lightGrid
|
||||
cullingDescriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = OLIGHTGRID_NAME,
|
||||
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_IMAGE,
|
||||
.access = Gfx::SE_DESCRIPTOR_ACCESS_READ_BIT | Gfx::SE_DESCRIPTOR_ACCESS_WRITE_BIT,
|
||||
});
|
||||
// t_lightGrid
|
||||
cullingDescriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = TLIGHTGRID_NAME,
|
||||
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_IMAGE,
|
||||
.access = Gfx::SE_DESCRIPTOR_ACCESS_READ_BIT | Gfx::SE_DESCRIPTOR_ACCESS_WRITE_BIT,
|
||||
});
|
||||
|
||||
cullingDescriptorLayout->create();
|
||||
|
||||
lightEnv = scene->getLightEnvironment();
|
||||
|
||||
{
|
||||
cullingLayout = graphics->createPipelineLayout("CullingLayout");
|
||||
cullingLayout->addDescriptorLayout(viewParamsLayout);
|
||||
cullingLayout->addDescriptorLayout(dispatchParamsLayout);
|
||||
cullingLayout->addDescriptorLayout(cullingDescriptorLayout);
|
||||
cullingLayout->addDescriptorLayout(lightEnv->getDescriptorLayout());
|
||||
|
||||
ShaderCompilationInfo createInfo = {
|
||||
.name = "Culling",
|
||||
.modules = {"LightCulling"},
|
||||
.entryPoints = {{"cullLights", "LightCulling"}},
|
||||
.rootSignature = cullingLayout,
|
||||
};
|
||||
graphics->beginShaderCompilation(createInfo);
|
||||
cullingShader = graphics->createComputeShader({0});
|
||||
cullingLayout->create();
|
||||
|
||||
Gfx::ComputePipelineCreateInfo pipelineInfo;
|
||||
pipelineInfo.computeShader = cullingShader;
|
||||
pipelineInfo.pipelineLayout = cullingLayout;
|
||||
cullingPipeline = graphics->createComputePipeline(std::move(pipelineInfo));
|
||||
}
|
||||
|
||||
{
|
||||
cullingEnableLayout = graphics->createPipelineLayout("CullingEnabledLayout");
|
||||
cullingEnableLayout->addDescriptorLayout(viewParamsLayout);
|
||||
cullingEnableLayout->addDescriptorLayout(dispatchParamsLayout);
|
||||
cullingEnableLayout->addDescriptorLayout(cullingDescriptorLayout);
|
||||
cullingEnableLayout->addDescriptorLayout(lightEnv->getDescriptorLayout());
|
||||
|
||||
ShaderCompilationInfo createInfo = {
|
||||
.name = "Culling",
|
||||
.modules = {"LightCulling"},
|
||||
.entryPoints = {{"cullLights", "LightCulling"}},
|
||||
.rootSignature = cullingEnableLayout,
|
||||
};
|
||||
createInfo.defines["LIGHT_CULLING"] = "1";
|
||||
graphics->beginShaderCompilation(createInfo);
|
||||
cullingEnabledShader = graphics->createComputeShader({0});
|
||||
cullingEnableLayout->create();
|
||||
|
||||
Gfx::ComputePipelineCreateInfo pipelineInfo;
|
||||
pipelineInfo.computeShader = cullingShader;
|
||||
pipelineInfo.pipelineLayout = cullingEnableLayout;
|
||||
cullingEnabledPipeline = graphics->createComputePipeline(std::move(pipelineInfo));
|
||||
}
|
||||
}
|
||||
|
||||
LightCullingPass::~LightCullingPass() {}
|
||||
|
||||
@@ -91,86 +222,9 @@ void LightCullingPass::publishOutputs() {
|
||||
dispatchParamsSet = dispatchParamsLayout->allocateDescriptorSet();
|
||||
dispatchParamsSet->updateConstants("numThreadGroups", 0, &numThreadGroups);
|
||||
dispatchParamsSet->updateConstants("numThreads", 0, &numThreads);
|
||||
dispatchParamsSet->updateBuffer(FRUSTUMBUFFER_NAME, 0, frustumBuffer);
|
||||
dispatchParamsSet->writeChanges();
|
||||
|
||||
cullingDescriptorLayout = graphics->createDescriptorLayout("pCullingParams");
|
||||
|
||||
// DepthTexture
|
||||
cullingDescriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = DEPTHATTACHMENT_NAME,
|
||||
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_SAMPLED_IMAGE,
|
||||
.access = Gfx::SE_DESCRIPTOR_ACCESS_SAMPLE_BIT,
|
||||
});
|
||||
// o_lightIndexCounter
|
||||
cullingDescriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = OLIGHTINDEXCOUNTER_NAME, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER, .access = Gfx::SE_DESCRIPTOR_ACCESS_READ_BIT | Gfx::SE_DESCRIPTOR_ACCESS_WRITE_BIT,});
|
||||
// t_lightIndexCounter
|
||||
cullingDescriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = TLIGHTINDEXCOUNTER_NAME, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER, .access = Gfx::SE_DESCRIPTOR_ACCESS_READ_BIT | Gfx::SE_DESCRIPTOR_ACCESS_WRITE_BIT,});
|
||||
// o_lightIndexList
|
||||
cullingDescriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = OLIGHTINDEXLIST_NAME, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER, .access = Gfx::SE_DESCRIPTOR_ACCESS_READ_BIT | Gfx::SE_DESCRIPTOR_ACCESS_WRITE_BIT,});
|
||||
// t_lightIndexList
|
||||
cullingDescriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = TLIGHTINDEXLIST_NAME, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER, .access = Gfx::SE_DESCRIPTOR_ACCESS_READ_BIT | Gfx::SE_DESCRIPTOR_ACCESS_WRITE_BIT,});
|
||||
// o_lightGrid
|
||||
cullingDescriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = OLIGHTGRID_NAME, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_IMAGE, .access = Gfx::SE_DESCRIPTOR_ACCESS_READ_BIT | Gfx::SE_DESCRIPTOR_ACCESS_WRITE_BIT,});
|
||||
// t_lightGrid
|
||||
cullingDescriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = TLIGHTGRID_NAME, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_IMAGE, .access = Gfx::SE_DESCRIPTOR_ACCESS_READ_BIT | Gfx::SE_DESCRIPTOR_ACCESS_WRITE_BIT,});
|
||||
|
||||
cullingDescriptorLayout->create();
|
||||
|
||||
lightEnv = scene->getLightEnvironment();
|
||||
|
||||
{
|
||||
cullingLayout = graphics->createPipelineLayout("CullingLayout");
|
||||
cullingLayout->addDescriptorLayout(viewParamsLayout);
|
||||
cullingLayout->addDescriptorLayout(dispatchParamsLayout);
|
||||
cullingLayout->addDescriptorLayout(cullingDescriptorLayout);
|
||||
cullingLayout->addDescriptorLayout(lightEnv->getDescriptorLayout());
|
||||
|
||||
ShaderCompilationInfo createInfo = {
|
||||
.name = "Culling",
|
||||
.modules = {"LightCulling"},
|
||||
.entryPoints = {{"cullLights", "LightCulling"}},
|
||||
.rootSignature = cullingLayout,
|
||||
};
|
||||
graphics->beginShaderCompilation(createInfo);
|
||||
cullingShader = graphics->createComputeShader({0});
|
||||
cullingLayout->create();
|
||||
|
||||
Gfx::ComputePipelineCreateInfo pipelineInfo;
|
||||
pipelineInfo.computeShader = cullingShader;
|
||||
pipelineInfo.pipelineLayout = cullingLayout;
|
||||
cullingPipeline = graphics->createComputePipeline(std::move(pipelineInfo));
|
||||
}
|
||||
|
||||
{
|
||||
cullingEnableLayout = graphics->createPipelineLayout("CullingEnabledLayout");
|
||||
cullingEnableLayout->addDescriptorLayout(viewParamsLayout);
|
||||
cullingEnableLayout->addDescriptorLayout(dispatchParamsLayout);
|
||||
cullingEnableLayout->addDescriptorLayout(cullingDescriptorLayout);
|
||||
cullingEnableLayout->addDescriptorLayout(lightEnv->getDescriptorLayout());
|
||||
|
||||
ShaderCompilationInfo createInfo = {
|
||||
.name = "Culling",
|
||||
.modules = {"LightCulling"},
|
||||
.entryPoints = {{"cullLights", "LightCulling"}},
|
||||
.rootSignature = cullingEnableLayout,
|
||||
};
|
||||
createInfo.defines["LIGHT_CULLING"] = "1";
|
||||
graphics->beginShaderCompilation(createInfo);
|
||||
cullingEnabledShader = graphics->createComputeShader({0});
|
||||
cullingEnableLayout->create();
|
||||
|
||||
Gfx::ComputePipelineCreateInfo pipelineInfo;
|
||||
pipelineInfo.computeShader = cullingShader;
|
||||
pipelineInfo.pipelineLayout = cullingEnableLayout;
|
||||
cullingEnabledPipeline = graphics->createComputePipeline(std::move(pipelineInfo));
|
||||
}
|
||||
|
||||
uint32 counterReset = 0;
|
||||
ShaderBufferCreateInfo structInfo = {
|
||||
.sourceData =
|
||||
@@ -188,8 +242,7 @@ void LightCullingPass::publishOutputs() {
|
||||
structInfo = {
|
||||
.sourceData =
|
||||
{
|
||||
.size = (uint32)sizeof(uint32) * numThreadGroups.x * numThreadGroups.y *
|
||||
numThreadGroups.z * 8192,
|
||||
.size = (uint32)sizeof(uint32) * numThreadGroups.x * numThreadGroups.y * numThreadGroups.z * 8192,
|
||||
.data = nullptr,
|
||||
.owner = Gfx::QueueType::COMPUTE,
|
||||
},
|
||||
@@ -237,41 +290,6 @@ void LightCullingPass::setupFrustums() {
|
||||
updateViewParameters(Component::Camera(), Component::Transform());
|
||||
viewParamsSet = createViewParamsSet();
|
||||
|
||||
dispatchParamsLayout = graphics->createDescriptorLayout("pDispatchParams");
|
||||
dispatchParamsLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = "numThreadGroups",
|
||||
.uniformLength = sizeof(UVector4),
|
||||
});
|
||||
dispatchParamsLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = "numThreads",
|
||||
.uniformLength = sizeof(UVector4),
|
||||
});
|
||||
dispatchParamsLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = FRUSTUMBUFFER_NAME,
|
||||
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER,
|
||||
.access = Gfx::SE_DESCRIPTOR_ACCESS_WRITE_BIT,
|
||||
});
|
||||
dispatchParamsLayout->create();
|
||||
frustumLayout = graphics->createPipelineLayout("FrustumLayout");
|
||||
frustumLayout->addDescriptorLayout(viewParamsLayout);
|
||||
frustumLayout->addDescriptorLayout(dispatchParamsLayout);
|
||||
ShaderCompilationInfo createInfo = {
|
||||
.name = "Frustum",
|
||||
.modules = {"ComputeFrustums"},
|
||||
.entryPoints = {{"computeFrustums", "ComputeFrustums"}},
|
||||
.rootSignature = frustumLayout,
|
||||
.dumpIntermediate = true,
|
||||
};
|
||||
graphics->beginShaderCompilation(createInfo);
|
||||
frustumShader = graphics->createComputeShader({0});
|
||||
// Have to compile shader before finalizing layout as parameters get mapped later
|
||||
frustumLayout->create();
|
||||
|
||||
Gfx::ComputePipelineCreateInfo pipelineInfo;
|
||||
pipelineInfo.computeShader = frustumShader;
|
||||
pipelineInfo.pipelineLayout = frustumLayout;
|
||||
frustumPipeline = graphics->createComputePipeline(pipelineInfo);
|
||||
|
||||
frustumBuffer = graphics->createShaderBuffer(ShaderBufferCreateInfo{
|
||||
.sourceData =
|
||||
{
|
||||
@@ -299,6 +317,6 @@ void LightCullingPass::setupFrustums() {
|
||||
commands.add(std::move(command));
|
||||
graphics->executeCommands(std::move(commands));
|
||||
frustumBuffer->pipelineBarrier(Gfx::SE_ACCESS_SHADER_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
|
||||
Gfx::SE_ACCESS_SHADER_READ_BIT, Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT);
|
||||
Gfx::SE_ACCESS_SHADER_READ_BIT, Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT);
|
||||
graphics->endDebugRegion();
|
||||
}
|
||||
@@ -4,9 +4,11 @@
|
||||
#include "Graphics/RayTracing.h"
|
||||
#include "Graphics/Shader.h"
|
||||
#include "Graphics/StaticMeshVertexData.h"
|
||||
#include "RenderPass.h"
|
||||
#include "Material/Material.h"
|
||||
#include "Material/MaterialInstance.h"
|
||||
#include "Scene/LightEnvironment.h"
|
||||
#include "RenderPass.h"
|
||||
#include <iostream>
|
||||
|
||||
using namespace Seele;
|
||||
|
||||
@@ -55,6 +57,18 @@ RayTracingPass::RayTracingPass(Gfx::PGraphics graphics, PScene scene) : RenderPa
|
||||
.size = sizeof(SampleParams),
|
||||
.name = "pSamps",
|
||||
});
|
||||
|
||||
graphics->beginShaderCompilation(ShaderCompilationInfo{
|
||||
.name = "RayGenMiss",
|
||||
.modules = {"RayGen", "AnyHit", "Miss"},
|
||||
.entryPoints = {{"raygen", "RayGen"}, {"anyhit", "AnyHit"}, {"miss", "Miss"}},
|
||||
.defines = {{"RAY_TRACING", "1"}},
|
||||
.rootSignature = pipelineLayout,
|
||||
});
|
||||
rayGen = graphics->createRayGenShader({0});
|
||||
anyhit = graphics->createAnyHitShader({1});
|
||||
miss = graphics->createMissShader({2});
|
||||
pipelineLayout->create();
|
||||
graphics->getShaderCompiler()->registerRenderPass("RayTracing", Gfx::PassConfig{
|
||||
.baseLayout = pipelineLayout,
|
||||
.mainFile = "ClosestHit",
|
||||
@@ -212,20 +226,9 @@ void RayTracingPass::publishOutputs() {
|
||||
texture->changeLayout(Gfx::SE_IMAGE_LAYOUT_GENERAL, Gfx::SE_ACCESS_NONE, Gfx::SE_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
|
||||
Gfx::SE_ACCESS_SHADER_WRITE_BIT,
|
||||
Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT | Gfx::SE_PIPELINE_STAGE_RAY_TRACING_SHADER_BIT_KHR);
|
||||
resources->registerRenderPassOutput("BASEPASS_COLOR", Gfx::RenderTargetAttachment(texture->getDefaultView(), Gfx::SE_IMAGE_LAYOUT_UNDEFINED,
|
||||
Gfx::SE_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL));
|
||||
ShaderCompilationInfo compileInfo = {
|
||||
.name = "RayGenMiss",
|
||||
.modules = {"RayGen", "AnyHit", "Miss"},
|
||||
.entryPoints = {{"raygen", "RayGen"}, {"anyhit", "AnyHit"}, {"miss", "Miss"}},
|
||||
.defines = {{"RAY_TRACING", "1"}},
|
||||
.rootSignature = pipelineLayout,
|
||||
};
|
||||
graphics->beginShaderCompilation(compileInfo);
|
||||
rayGen = graphics->createRayGenShader({0});
|
||||
anyhit = graphics->createAnyHitShader({1});
|
||||
miss = graphics->createMissShader({2});
|
||||
pipelineLayout->create();
|
||||
resources->registerRenderPassOutput("BASEPASS_COLOR",
|
||||
Gfx::RenderTargetAttachment(texture->getDefaultView(), Gfx::SE_IMAGE_LAYOUT_UNDEFINED,
|
||||
Gfx::SE_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL));
|
||||
}
|
||||
|
||||
void RayTracingPass::createRenderPass() {}
|
||||
@@ -4,6 +4,7 @@
|
||||
#include "Graphics/Initializer.h"
|
||||
#include "Graphics/Shader.h"
|
||||
#include "Math/Matrix.h"
|
||||
#include "Scene/LightEnvironment.h"
|
||||
#include <glm/ext/matrix_transform.hpp>
|
||||
#include <glm/matrix.hpp>
|
||||
|
||||
|
||||
@@ -0,0 +1,749 @@
|
||||
#include "SimulationComputePass.h"
|
||||
#include "Graphics/Buffer.h"
|
||||
#include "Graphics/Command.h"
|
||||
#include "Graphics/Descriptor.h"
|
||||
#include "Graphics/Enums.h"
|
||||
#include "Graphics/Graphics.h"
|
||||
#include "Graphics/Initializer.h"
|
||||
#include "Graphics/Shader.h"
|
||||
#include "Math/Vector.h"
|
||||
#include "Scene/FluidScene.h"
|
||||
#include <algorithm>
|
||||
#include <iostream>
|
||||
|
||||
using namespace Seele;
|
||||
|
||||
// Reinitialization is in pseudo-time; keep it gentle to avoid eroding the interface each frame.
|
||||
constexpr static int reinitInterval = 5;
|
||||
constexpr static int reinitIterations = 5;
|
||||
constexpr static float reinitDtau = 0.5f;
|
||||
constexpr static int velocityDiffuseIterations = 8;
|
||||
constexpr static int pressureSolveIterations = 100;
|
||||
constexpr static int densityDiffuseIterations = 8;
|
||||
constexpr static float pressureSORomega = 1.95f;
|
||||
constexpr static float diffusionSORomega = 1.0f;
|
||||
// Substep the semi-Lagrangian advection so the backtrace moves <~1 cell per
|
||||
// step. A single full-dt advect at dt=0.1 moves many cells and smears the
|
||||
// passive scalar (density) hard, which is the dominant source of mass loss.
|
||||
constexpr static int advectionSubsteps = 8;
|
||||
|
||||
#define SWAP(a, b) \
|
||||
{ \
|
||||
auto temp = std::move(a); \
|
||||
a = std::move(b); \
|
||||
b = std::move(temp); \
|
||||
}
|
||||
|
||||
SimulationComputePass::SimulationComputePass(Gfx::PGraphics graphics, PScene scene) : RenderPass(graphics), scene(scene) {
|
||||
gridSizeLayout = graphics->createDescriptorLayout("gridParams");
|
||||
gridSizeLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = "gridSize",
|
||||
.uniformLength = sizeof(UVector),
|
||||
});
|
||||
gridSizeLayout->create();
|
||||
{
|
||||
setBounds.pipelineLayout = graphics->createPipelineLayout("SetBoundsPipelineLayout");
|
||||
setBounds.descriptorLayout = graphics->createDescriptorLayout("params");
|
||||
setBounds.descriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = "b",
|
||||
.uniformLength = sizeof(int),
|
||||
});
|
||||
setBounds.descriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = "numPlanes",
|
||||
.uniformLength = sizeof(uint32),
|
||||
});
|
||||
setBounds.descriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = "planes",
|
||||
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER,
|
||||
});
|
||||
setBounds.descriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = "grid",
|
||||
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER,
|
||||
});
|
||||
setBounds.descriptorLayout->create();
|
||||
setBounds.pipelineLayout->addDescriptorLayout(setBounds.descriptorLayout);
|
||||
setBounds.pipelineLayout->addDescriptorLayout(gridSizeLayout);
|
||||
graphics->beginShaderCompilation(ShaderCompilationInfo{
|
||||
.name = "SetBound",
|
||||
.modules = {"SetBound"},
|
||||
.entryPoints = {{"setBound", "SetBound"}},
|
||||
.rootSignature = setBounds.pipelineLayout,
|
||||
});
|
||||
setBounds.pipelineLayout->create();
|
||||
setBounds.shader = graphics->createComputeShader({0});
|
||||
setBounds.pipeline = graphics->createComputePipeline(Gfx::ComputePipelineCreateInfo{
|
||||
.computeShader = setBounds.shader,
|
||||
.pipelineLayout = setBounds.pipelineLayout,
|
||||
});
|
||||
}
|
||||
{
|
||||
linearSolve.pipelineLayout = graphics->createPipelineLayout("LinearSolvePipelineLayout");
|
||||
linearSolve.descriptorLayout = graphics->createDescriptorLayout("params");
|
||||
linearSolve.descriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = "grid",
|
||||
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER,
|
||||
});
|
||||
linearSolve.descriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = "grid0",
|
||||
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER,
|
||||
});
|
||||
linearSolve.descriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = "a",
|
||||
.uniformLength = sizeof(float),
|
||||
});
|
||||
linearSolve.descriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = "c",
|
||||
.uniformLength = sizeof(float),
|
||||
});
|
||||
linearSolve.descriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = "omega",
|
||||
.uniformLength = sizeof(float),
|
||||
});
|
||||
linearSolve.descriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = "color",
|
||||
.uniformLength = sizeof(int),
|
||||
});
|
||||
linearSolve.descriptorLayout->create();
|
||||
linearSolve.pipelineLayout->addDescriptorLayout(linearSolve.descriptorLayout);
|
||||
linearSolve.pipelineLayout->addDescriptorLayout(gridSizeLayout);
|
||||
graphics->beginShaderCompilation(ShaderCompilationInfo{
|
||||
.name = "LinearSolve",
|
||||
.modules = {"LinearSolve"},
|
||||
.entryPoints = {{"linearSolve", "LinearSolve"}},
|
||||
.rootSignature = linearSolve.pipelineLayout,
|
||||
});
|
||||
linearSolve.pipelineLayout->create();
|
||||
linearSolve.shader = graphics->createComputeShader({0});
|
||||
linearSolve.pipeline = graphics->createComputePipeline(Gfx::ComputePipelineCreateInfo{
|
||||
.computeShader = linearSolve.shader,
|
||||
.pipelineLayout = linearSolve.pipelineLayout,
|
||||
});
|
||||
}
|
||||
{
|
||||
computeDivergence.pipelineLayout = graphics->createPipelineLayout("ComputeDivergencePipelineLayout");
|
||||
computeDivergence.descriptorLayout = graphics->createDescriptorLayout("params");
|
||||
computeDivergence.descriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = "velocityX",
|
||||
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER,
|
||||
});
|
||||
computeDivergence.descriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = "velocityY",
|
||||
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER,
|
||||
});
|
||||
computeDivergence.descriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = "velocityZ",
|
||||
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER,
|
||||
});
|
||||
computeDivergence.descriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = "divergence",
|
||||
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER,
|
||||
});
|
||||
computeDivergence.descriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = "pressure",
|
||||
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER,
|
||||
});
|
||||
computeDivergence.descriptorLayout->create();
|
||||
computeDivergence.pipelineLayout->addDescriptorLayout(computeDivergence.descriptorLayout);
|
||||
computeDivergence.pipelineLayout->addDescriptorLayout(gridSizeLayout);
|
||||
graphics->beginShaderCompilation(ShaderCompilationInfo{
|
||||
.name = "Divergence",
|
||||
.modules = {"Divergence"},
|
||||
.entryPoints = {{"computeDivergence", "Divergence"}},
|
||||
.rootSignature = computeDivergence.pipelineLayout,
|
||||
});
|
||||
computeDivergence.pipelineLayout->create();
|
||||
|
||||
computeDivergence.shader = graphics->createComputeShader({0});
|
||||
computeDivergence.pipeline = graphics->createComputePipeline(Gfx::ComputePipelineCreateInfo{
|
||||
.computeShader = computeDivergence.shader,
|
||||
.pipelineLayout = computeDivergence.pipelineLayout,
|
||||
});
|
||||
}
|
||||
{
|
||||
project.pipelineLayout = graphics->createPipelineLayout("ProjectPipelineLayout");
|
||||
project.descriptorLayout = graphics->createDescriptorLayout("params");
|
||||
project.descriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = "velocityX",
|
||||
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER,
|
||||
});
|
||||
project.descriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = "velocityY",
|
||||
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER,
|
||||
});
|
||||
project.descriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = "velocityZ",
|
||||
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER,
|
||||
});
|
||||
project.descriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = "pressure",
|
||||
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER,
|
||||
});
|
||||
project.descriptorLayout->create();
|
||||
project.pipelineLayout->addDescriptorLayout(project.descriptorLayout);
|
||||
project.pipelineLayout->addDescriptorLayout(gridSizeLayout);
|
||||
graphics->beginShaderCompilation(ShaderCompilationInfo{
|
||||
.name = "Project",
|
||||
.modules = {"Project"},
|
||||
.entryPoints = {{"project", "Project"}},
|
||||
.rootSignature = project.pipelineLayout,
|
||||
});
|
||||
project.pipelineLayout->create();
|
||||
project.shader = graphics->createComputeShader({0});
|
||||
project.pipeline = graphics->createComputePipeline(Gfx::ComputePipelineCreateInfo{
|
||||
.computeShader = project.shader,
|
||||
.pipelineLayout = project.pipelineLayout,
|
||||
});
|
||||
}
|
||||
{
|
||||
advect.pipelineLayout = graphics->createPipelineLayout("AdvectPipelineLayout");
|
||||
advect.descriptorLayout = graphics->createDescriptorLayout("params");
|
||||
advect.descriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = "density",
|
||||
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER,
|
||||
});
|
||||
advect.descriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = "density0",
|
||||
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER,
|
||||
});
|
||||
advect.descriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = "velocityX",
|
||||
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER,
|
||||
});
|
||||
advect.descriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = "velocityY",
|
||||
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER,
|
||||
});
|
||||
advect.descriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = "velocityZ",
|
||||
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER,
|
||||
});
|
||||
advect.descriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = "dt",
|
||||
.uniformLength = sizeof(float),
|
||||
});
|
||||
advect.descriptorLayout->create();
|
||||
advect.pipelineLayout->addDescriptorLayout(advect.descriptorLayout);
|
||||
advect.pipelineLayout->addDescriptorLayout(gridSizeLayout);
|
||||
graphics->beginShaderCompilation(ShaderCompilationInfo{
|
||||
.name = "Advect",
|
||||
.modules = {"Advect"},
|
||||
.entryPoints = {{"advect", "Advect"}},
|
||||
.rootSignature = advect.pipelineLayout,
|
||||
});
|
||||
advect.pipelineLayout->create();
|
||||
|
||||
advect.shader = graphics->createComputeShader({0});
|
||||
advect.pipeline = graphics->createComputePipeline(Gfx::ComputePipelineCreateInfo{
|
||||
.computeShader = advect.shader,
|
||||
.pipelineLayout = advect.pipelineLayout,
|
||||
});
|
||||
}
|
||||
{
|
||||
reinitialize.pipelineLayout = graphics->createPipelineLayout("ReinitializePipelineLayout");
|
||||
reinitialize.descriptorLayout = graphics->createDescriptorLayout("params");
|
||||
reinitialize.descriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = "dtau",
|
||||
.uniformLength = sizeof(float),
|
||||
});
|
||||
reinitialize.descriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = "phi",
|
||||
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER,
|
||||
});
|
||||
reinitialize.descriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = "phiPrev",
|
||||
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER,
|
||||
});
|
||||
reinitialize.descriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = "phiSign",
|
||||
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER,
|
||||
});
|
||||
reinitialize.descriptorLayout->create();
|
||||
reinitialize.pipelineLayout->addDescriptorLayout(reinitialize.descriptorLayout);
|
||||
reinitialize.pipelineLayout->addDescriptorLayout(gridSizeLayout);
|
||||
graphics->beginShaderCompilation(ShaderCompilationInfo{
|
||||
.name = "SignedDistance",
|
||||
.modules = {"SignedDistance"},
|
||||
.entryPoints = {{"reinitialize", "SignedDistance"}},
|
||||
.rootSignature = reinitialize.pipelineLayout,
|
||||
});
|
||||
reinitialize.pipelineLayout->create();
|
||||
reinitialize.shader = graphics->createComputeShader({0});
|
||||
reinitialize.pipeline = graphics->createComputePipeline(Gfx::ComputePipelineCreateInfo{
|
||||
.computeShader = reinitialize.shader,
|
||||
.pipelineLayout = reinitialize.pipelineLayout,
|
||||
});
|
||||
}
|
||||
{
|
||||
applyForces.pipelineLayout = graphics->createPipelineLayout("ApplyForcesPipelineLayout");
|
||||
applyForces.descriptorLayout = graphics->createDescriptorLayout("params");
|
||||
applyForces.descriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = "velocityX",
|
||||
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER,
|
||||
});
|
||||
applyForces.descriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = "velocityY",
|
||||
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER,
|
||||
});
|
||||
applyForces.descriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = "velocityZ",
|
||||
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER,
|
||||
});
|
||||
applyForces.descriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = "force",
|
||||
.uniformLength = sizeof(Vector),
|
||||
});
|
||||
applyForces.descriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = "dt",
|
||||
.uniformLength = sizeof(float),
|
||||
});
|
||||
applyForces.descriptorLayout->create();
|
||||
applyForces.pipelineLayout->addDescriptorLayout(applyForces.descriptorLayout);
|
||||
applyForces.pipelineLayout->addDescriptorLayout(gridSizeLayout);
|
||||
graphics->beginShaderCompilation(ShaderCompilationInfo{
|
||||
.name = "ApplyForces",
|
||||
.modules = {"ApplyForces"},
|
||||
.entryPoints = {{"applyForces", "ApplyForces"}},
|
||||
.rootSignature = applyForces.pipelineLayout,
|
||||
});
|
||||
applyForces.pipelineLayout->create();
|
||||
applyForces.shader = graphics->createComputeShader({0});
|
||||
applyForces.pipeline = graphics->createComputePipeline(Gfx::ComputePipelineCreateInfo{
|
||||
.computeShader = applyForces.shader,
|
||||
.pipelineLayout = applyForces.pipelineLayout,
|
||||
});
|
||||
}
|
||||
{
|
||||
// Diagnostics-only mass probe: sums interior fields into a 3-float buffer.
|
||||
massProbe.pipelineLayout = graphics->createPipelineLayout("MassProbePipelineLayout");
|
||||
massProbe.descriptorLayout = graphics->createDescriptorLayout("params");
|
||||
massProbe.descriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = "density",
|
||||
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER,
|
||||
});
|
||||
massProbe.descriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = "phi",
|
||||
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER,
|
||||
});
|
||||
massProbe.descriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = "velocityX",
|
||||
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER,
|
||||
});
|
||||
massProbe.descriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = "velocityY",
|
||||
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER,
|
||||
});
|
||||
massProbe.descriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = "velocityZ",
|
||||
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER,
|
||||
});
|
||||
massProbe.descriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = "out",
|
||||
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER,
|
||||
});
|
||||
massProbe.descriptorLayout->create();
|
||||
massProbe.pipelineLayout->addDescriptorLayout(massProbe.descriptorLayout);
|
||||
massProbe.pipelineLayout->addDescriptorLayout(gridSizeLayout);
|
||||
graphics->beginShaderCompilation(ShaderCompilationInfo{
|
||||
.name = "MassProbe",
|
||||
.modules = {"MassProbe"},
|
||||
.entryPoints = {{"massProbe", "MassProbe"}},
|
||||
.rootSignature = massProbe.pipelineLayout,
|
||||
});
|
||||
massProbe.pipelineLayout->create();
|
||||
massProbe.shader = graphics->createComputeShader({0});
|
||||
massProbe.pipeline = graphics->createComputePipeline(Gfx::ComputePipelineCreateInfo{
|
||||
.computeShader = massProbe.shader,
|
||||
.pipelineLayout = massProbe.pipelineLayout,
|
||||
});
|
||||
// 3 floats: [0]=density sum, [1]=phi sum, [2]=|velocity| sum.
|
||||
probeOutBuffer = graphics->createShaderBuffer(ShaderBufferCreateInfo{
|
||||
.sourceData = {
|
||||
.size = 3 * sizeof(float),
|
||||
},
|
||||
.name = "MassProbeOut",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
SimulationComputePass::~SimulationComputePass() {}
|
||||
|
||||
void SimulationComputePass::beginFrame(const Seele::Component::Camera&, const Seele::Component::Transform&) {
|
||||
setBounds.descriptorLayout->reset();
|
||||
linearSolve.descriptorLayout->reset();
|
||||
computeDivergence.descriptorLayout->reset();
|
||||
project.descriptorLayout->reset();
|
||||
advect.descriptorLayout->reset();
|
||||
reinitialize.descriptorLayout->reset();
|
||||
applyForces.descriptorLayout->reset();
|
||||
gridSizeLayout->reset();
|
||||
}
|
||||
|
||||
void SimulationComputePass::render() {
|
||||
for (auto& [entityID, data] : scene->getFluidScene()->getFluidDataMap()) {
|
||||
if (data.paused) {
|
||||
continue;
|
||||
}
|
||||
gridSizeSet = gridSizeLayout->allocateDescriptorSet();
|
||||
gridSizeSet->updateConstants("gridSize", 0, &data.gridSize);
|
||||
gridSizeSet->writeChanges();
|
||||
graphics->beginDebugRegion("Diffuse");
|
||||
for (int iteration = 0; iteration < velocityDiffuseIterations; ++iteration) {
|
||||
float a = data.dt * data.viscosity * (data.gridSize.x - 2) * (data.gridSize.x - 2);
|
||||
float c = 1 + 6 * a;
|
||||
linearSolvePass(data.velocityXBuffer, data.velocityX0Buffer, a, c, diffusionSORomega, data.gridSize);
|
||||
linearSolvePass(data.velocityYBuffer, data.velocityY0Buffer, a, c, diffusionSORomega, data.gridSize);
|
||||
linearSolvePass(data.velocityZBuffer, data.velocityZ0Buffer, a, c, diffusionSORomega, data.gridSize);
|
||||
|
||||
setBoundsPass(data.velocityXBuffer, 1, data.gridSize, data.planeBuffer, data.numPlanes);
|
||||
setBoundsPass(data.velocityYBuffer, 2, data.gridSize, data.planeBuffer, data.numPlanes);
|
||||
setBoundsPass(data.velocityZBuffer, 3, data.gridSize, data.planeBuffer, data.numPlanes);
|
||||
}
|
||||
|
||||
SWAP(data.velocityX0Buffer, data.velocityXBuffer);
|
||||
SWAP(data.velocityY0Buffer, data.velocityYBuffer);
|
||||
SWAP(data.velocityZ0Buffer, data.velocityZBuffer);
|
||||
graphics->endDebugRegion();
|
||||
|
||||
graphics->beginDebugRegion("Project");
|
||||
Gfx::PShaderBuffer divergence = data.velocityXBuffer;
|
||||
Gfx::PShaderBuffer pressure = data.velocityYBuffer;
|
||||
divergencePass(divergence, pressure, data.velocityX0Buffer, data.velocityY0Buffer, data.velocityZ0Buffer, data.gridSize);
|
||||
|
||||
setBoundsPass(divergence, 0, data.gridSize, data.planeBuffer, data.numPlanes);
|
||||
setBoundsPass(pressure, 0, data.gridSize, data.planeBuffer, data.numPlanes);
|
||||
|
||||
for (int iteration = 0; iteration < pressureSolveIterations; ++iteration) {
|
||||
linearSolvePass(pressure, divergence, 1, 6, pressureSORomega, data.gridSize);
|
||||
setBoundsPass(pressure, 0, data.gridSize, data.planeBuffer, data.numPlanes);
|
||||
}
|
||||
|
||||
projectPass(data.velocityX0Buffer, data.velocityY0Buffer, data.velocityZ0Buffer, pressure, data.gridSize);
|
||||
|
||||
setBoundsPass(data.velocityX0Buffer, 1, data.gridSize, data.planeBuffer, data.numPlanes);
|
||||
setBoundsPass(data.velocityY0Buffer, 2, data.gridSize, data.planeBuffer, data.numPlanes);
|
||||
setBoundsPass(data.velocityZ0Buffer, 3, data.gridSize, data.planeBuffer, data.numPlanes);
|
||||
graphics->endDebugRegion();
|
||||
|
||||
graphics->beginDebugRegion("Advect");
|
||||
// Substep ONLY the advection: each step uses dt/substeps so the
|
||||
// backtrace displacement stays small, reducing the numerical (bilinear)
|
||||
// dissipation of the semi-Lagrangian scheme. The pressure re-projection
|
||||
// is a GLOBAL operation and must run exactly once per frame on the final
|
||||
// velocity field — running it inside the substep loop over-corrects and
|
||||
// injects energy into the velocity field (observed as |vel|_sum runaway).
|
||||
const float subDt = data.dt / advectionSubsteps;
|
||||
for (int sub = 0; sub < advectionSubsteps; ++sub) {
|
||||
advectPass(data.velocityXBuffer, data.velocityX0Buffer, data.velocityX0Buffer, data.velocityY0Buffer, data.velocityZ0Buffer, subDt,
|
||||
data.gridSize);
|
||||
advectPass(data.velocityYBuffer, data.velocityY0Buffer, data.velocityX0Buffer, data.velocityY0Buffer, data.velocityZ0Buffer, subDt,
|
||||
data.gridSize);
|
||||
advectPass(data.velocityZBuffer, data.velocityZ0Buffer, data.velocityX0Buffer, data.velocityY0Buffer, data.velocityZ0Buffer, subDt,
|
||||
data.gridSize);
|
||||
|
||||
if (data.enableGravity) {
|
||||
applyForcesPass(data.velocityXBuffer, data.velocityYBuffer, data.velocityZBuffer, data.gravity, subDt, data.gridSize);
|
||||
}
|
||||
|
||||
// Set boundary conditions after advection/forces so the divergence sees correct wall values
|
||||
setBoundsPass(data.velocityXBuffer, 1, data.gridSize, data.planeBuffer, data.numPlanes);
|
||||
setBoundsPass(data.velocityYBuffer, 2, data.gridSize, data.planeBuffer, data.numPlanes);
|
||||
setBoundsPass(data.velocityZBuffer, 3, data.gridSize, data.planeBuffer, data.numPlanes);
|
||||
}
|
||||
|
||||
// Re-project ONCE per frame after all substeps to keep the final velocity
|
||||
// field divergence-free.
|
||||
Gfx::PShaderBuffer advectedDivergence = data.velocityXNextBuffer;
|
||||
Gfx::PShaderBuffer advectedPressure = data.velocityYNextBuffer;
|
||||
divergencePass(advectedDivergence, advectedPressure, data.velocityXBuffer, data.velocityYBuffer, data.velocityZBuffer, data.gridSize);
|
||||
setBoundsPass(advectedDivergence, 0, data.gridSize, data.planeBuffer, data.numPlanes);
|
||||
setBoundsPass(advectedPressure, 0, data.gridSize, data.planeBuffer, data.numPlanes);
|
||||
|
||||
for (int iteration = 0; iteration < pressureSolveIterations; ++iteration) {
|
||||
linearSolvePass(advectedPressure, advectedDivergence, 1, 6, pressureSORomega, data.gridSize);
|
||||
setBoundsPass(advectedPressure, 0, data.gridSize, data.planeBuffer, data.numPlanes);
|
||||
}
|
||||
projectPass(data.velocityXBuffer, data.velocityYBuffer, data.velocityZBuffer, advectedPressure, data.gridSize);
|
||||
|
||||
setBoundsPass(data.velocityXBuffer, 1, data.gridSize, data.planeBuffer, data.numPlanes);
|
||||
setBoundsPass(data.velocityYBuffer, 2, data.gridSize, data.planeBuffer, data.numPlanes);
|
||||
setBoundsPass(data.velocityZBuffer, 3, data.gridSize, data.planeBuffer, data.numPlanes);
|
||||
graphics->endDebugRegion();
|
||||
// swap velocity buffers
|
||||
SWAP(data.velocityX0Buffer, data.velocityXBuffer);
|
||||
SWAP(data.velocityY0Buffer, data.velocityYBuffer);
|
||||
SWAP(data.velocityZ0Buffer, data.velocityZBuffer);
|
||||
|
||||
// diffuse density
|
||||
graphics->beginDebugRegion("DiffuseDensity");
|
||||
Gfx::PShaderBuffer densityCurrent = data.densityBuffer;
|
||||
Gfx::PShaderBuffer density0 = data.density0Buffer;
|
||||
graphics->copyBuffer(density0, densityCurrent);
|
||||
densityCurrent->pipelineBarrier(Gfx::SE_ACCESS_TRANSFER_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_TRANSFER_BIT,
|
||||
Gfx::SE_ACCESS_SHADER_READ_BIT, Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT);
|
||||
for (int iteration = 0; iteration < densityDiffuseIterations; ++iteration) {
|
||||
float a = data.dt * data.diffusion * (data.gridSize.x - 2) * (data.gridSize.x - 2);
|
||||
float c = 1 + 6 * a;
|
||||
linearSolvePass(densityCurrent, density0, a, c, diffusionSORomega, data.gridSize);
|
||||
setBoundsPass(densityCurrent, 0, data.gridSize, data.planeBuffer, data.numPlanes);
|
||||
}
|
||||
graphics->endDebugRegion();
|
||||
graphics->beginDebugRegion("AdvectDensity");
|
||||
// Substep density advection with the same small subDt as the velocity
|
||||
// advection so the passive scalar is not smeared by a large backtrace.
|
||||
for (int sub = 0; sub < advectionSubsteps; ++sub) {
|
||||
advectPass(data.density0Buffer, densityCurrent, data.velocityX0Buffer, data.velocityY0Buffer, data.velocityZ0Buffer, subDt,
|
||||
data.gridSize);
|
||||
setBoundsPass(data.density0Buffer, 0, data.gridSize, data.planeBuffer, data.numPlanes);
|
||||
}
|
||||
graphics->endDebugRegion();
|
||||
|
||||
graphics->beginDebugRegion("AdvectLevelSet");
|
||||
for (int sub = 0; sub < advectionSubsteps; ++sub) {
|
||||
advectPass(data.phiBuffer, data.phi0Buffer, data.velocityX0Buffer, data.velocityY0Buffer, data.velocityZ0Buffer, subDt, data.gridSize);
|
||||
setBoundsPass(data.phiBuffer, 0, data.gridSize, data.planeBuffer, data.numPlanes);
|
||||
}
|
||||
|
||||
// Reinitialize level set every N frames to restore |grad phi| = 1
|
||||
if (data.frameCounter % reinitInterval == 0) {
|
||||
reinitializeLevelSetPass(data.phiBuffer, data.phi0Buffer, data.scratchBuffer, data.gridSize, data.planeBuffer, data.numPlanes);
|
||||
}
|
||||
++data.frameCounter;
|
||||
|
||||
data.phiBuffer->pipelineBarrier(Gfx::SE_ACCESS_SHADER_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
|
||||
Gfx::SE_ACCESS_TRANSFER_READ_BIT, Gfx::SE_PIPELINE_STAGE_TRANSFER_BIT);
|
||||
graphics->copyBuffer(data.phiBuffer, data.phi0Buffer);
|
||||
data.phi0Buffer->pipelineBarrier(Gfx::SE_ACCESS_TRANSFER_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_TRANSFER_BIT,
|
||||
Gfx::SE_ACCESS_TRANSFER_READ_BIT, Gfx::SE_PIPELINE_STAGE_TRANSFER_BIT);
|
||||
graphics->endDebugRegion();
|
||||
|
||||
// Diagnostics: log interior field sums so we can see which quantity is decaying.
|
||||
massProbePass(data.density0Buffer, data.phiBuffer, data.velocityX0Buffer, data.velocityY0Buffer, data.velocityZ0Buffer, data.gridSize);
|
||||
}
|
||||
}
|
||||
|
||||
void SimulationComputePass::endFrame() {}
|
||||
|
||||
void SimulationComputePass::publishOutputs() {}
|
||||
|
||||
void SimulationComputePass::createRenderPass() {}
|
||||
|
||||
UVector SimulationComputePass::getDispatchSize(const UVector& gridSize, const UVector& threadGroupSize) {
|
||||
return {
|
||||
(gridSize.x + threadGroupSize.x - 1) / threadGroupSize.x,
|
||||
(gridSize.y + threadGroupSize.y - 1) / threadGroupSize.y,
|
||||
(gridSize.z + threadGroupSize.z - 1) / threadGroupSize.z,
|
||||
};
|
||||
}
|
||||
|
||||
void SimulationComputePass::setBoundsPass(Gfx::PShaderBuffer grid, int b, UVector gridSize, Gfx::PShaderBuffer planeBuffer, uint32 numPlanes) {
|
||||
Gfx::ODescriptorSet bounds = setBounds.descriptorLayout->allocateDescriptorSet();
|
||||
bounds->updateConstants("b", 0, &b);
|
||||
bounds->updateConstants("numPlanes", 0, &numPlanes);
|
||||
bounds->updateBuffer("planes", 0, planeBuffer);
|
||||
bounds->updateBuffer("grid", 0, grid);
|
||||
bounds->writeChanges();
|
||||
Gfx::OComputeCommand boundsCommand = graphics->createComputeCommand();
|
||||
boundsCommand->bindPipeline(setBounds.pipeline);
|
||||
boundsCommand->bindDescriptor(bounds);
|
||||
boundsCommand->bindDescriptor(gridSizeSet);
|
||||
auto dispatchSize = getDispatchSize(gridSize, setBounds.threadGroupSize);
|
||||
boundsCommand->dispatch(dispatchSize.x, dispatchSize.y, dispatchSize.z);
|
||||
graphics->executeCommands(std::move(boundsCommand));
|
||||
|
||||
grid->pipelineBarrier(Gfx::SE_ACCESS_SHADER_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT, Gfx::SE_ACCESS_SHADER_READ_BIT,
|
||||
Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT);
|
||||
}
|
||||
|
||||
void SimulationComputePass::linearSolvePass(Gfx::PShaderBuffer grid, Gfx::PShaderBuffer grid0, float a, float c, float omega,
|
||||
UVector gridSize) {
|
||||
for (int color = 0; color < 2; ++color) {
|
||||
Gfx::ODescriptorSet solve = linearSolve.descriptorLayout->allocateDescriptorSet();
|
||||
solve->updateBuffer("grid", 0, grid);
|
||||
solve->updateBuffer("grid0", 0, grid0);
|
||||
solve->updateConstants("a", 0, &a);
|
||||
solve->updateConstants("c", 0, &c);
|
||||
solve->updateConstants("omega", 0, &omega);
|
||||
solve->updateConstants("color", 0, &color);
|
||||
solve->writeChanges();
|
||||
Gfx::OComputeCommand solveCommand = graphics->createComputeCommand();
|
||||
solveCommand->bindPipeline(linearSolve.pipeline);
|
||||
solveCommand->bindDescriptor(solve);
|
||||
solveCommand->bindDescriptor(gridSizeSet);
|
||||
solveCommand->dispatch(getDispatchSize(gridSize, linearSolve.threadGroupSize));
|
||||
graphics->executeCommands(std::move(solveCommand));
|
||||
|
||||
grid->pipelineBarrier(Gfx::SE_ACCESS_SHADER_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT, Gfx::SE_ACCESS_SHADER_READ_BIT,
|
||||
Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT);
|
||||
}
|
||||
}
|
||||
void SimulationComputePass::divergencePass(Seele::Gfx::PShaderBuffer divergence, Seele::Gfx::PShaderBuffer pressure,
|
||||
Seele::Gfx::PShaderBuffer velocityX, Seele::Gfx::PShaderBuffer velocityY,
|
||||
Seele::Gfx::PShaderBuffer velocityZ, UVector gridSize) {
|
||||
Gfx::ODescriptorSet divergenceSet = computeDivergence.descriptorLayout->allocateDescriptorSet();
|
||||
divergenceSet->updateBuffer("velocityX", 0, velocityX);
|
||||
divergenceSet->updateBuffer("velocityY", 0, velocityY);
|
||||
divergenceSet->updateBuffer("velocityZ", 0, velocityZ);
|
||||
divergenceSet->updateBuffer("divergence", 0, divergence);
|
||||
divergenceSet->updateBuffer("pressure", 0, pressure);
|
||||
divergenceSet->writeChanges();
|
||||
Gfx::OComputeCommand divergenceCommand = graphics->createComputeCommand();
|
||||
divergenceCommand->bindPipeline(computeDivergence.pipeline);
|
||||
divergenceCommand->bindDescriptor(divergenceSet);
|
||||
divergenceCommand->bindDescriptor(gridSizeSet);
|
||||
divergenceCommand->dispatch(getDispatchSize(gridSize, computeDivergence.threadGroupSize));
|
||||
graphics->executeCommands(std::move(divergenceCommand));
|
||||
// divergence is now in velocityXBuffer, pressure is in velocityYBuffer
|
||||
divergence->pipelineBarrier(Gfx::SE_ACCESS_SHADER_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT, Gfx::SE_ACCESS_SHADER_READ_BIT,
|
||||
Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT);
|
||||
pressure->pipelineBarrier(Gfx::SE_ACCESS_SHADER_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT, Gfx::SE_ACCESS_SHADER_READ_BIT,
|
||||
Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT);
|
||||
}
|
||||
|
||||
void SimulationComputePass::projectPass(Seele::Gfx::PShaderBuffer velocityX, Seele::Gfx::PShaderBuffer velocityY,
|
||||
Seele::Gfx::PShaderBuffer velocityZ, Seele::Gfx::PShaderBuffer pressure, UVector gridSize) {
|
||||
Gfx::ODescriptorSet projectSet = project.descriptorLayout->allocateDescriptorSet();
|
||||
projectSet->updateBuffer("velocityX", 0, velocityX);
|
||||
projectSet->updateBuffer("velocityY", 0, velocityY);
|
||||
projectSet->updateBuffer("velocityZ", 0, velocityZ);
|
||||
projectSet->updateBuffer("pressure", 0, pressure);
|
||||
projectSet->writeChanges();
|
||||
Gfx::OComputeCommand projectCommand = graphics->createComputeCommand();
|
||||
projectCommand->bindPipeline(project.pipeline);
|
||||
projectCommand->bindDescriptor(projectSet);
|
||||
projectCommand->bindDescriptor(gridSizeSet);
|
||||
projectCommand->dispatch(getDispatchSize(gridSize, project.threadGroupSize));
|
||||
graphics->executeCommands(std::move(projectCommand));
|
||||
|
||||
velocityX->pipelineBarrier(Gfx::SE_ACCESS_SHADER_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT, Gfx::SE_ACCESS_SHADER_READ_BIT,
|
||||
Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT);
|
||||
velocityY->pipelineBarrier(Gfx::SE_ACCESS_SHADER_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT, Gfx::SE_ACCESS_SHADER_READ_BIT,
|
||||
Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT);
|
||||
velocityZ->pipelineBarrier(Gfx::SE_ACCESS_SHADER_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT, Gfx::SE_ACCESS_SHADER_READ_BIT,
|
||||
Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT);
|
||||
}
|
||||
|
||||
void SimulationComputePass::advectPass(Gfx::PShaderBuffer quantity, Gfx::PShaderBuffer quantity0, Gfx::PShaderBuffer velocityX,
|
||||
Gfx::PShaderBuffer velocityY, Gfx::PShaderBuffer velocityZ, float dt, UVector gridSize) {
|
||||
Gfx::ODescriptorSet advectSet = this->advect.descriptorLayout->allocateDescriptorSet();
|
||||
advectSet->updateBuffer("density", 0, quantity);
|
||||
advectSet->updateBuffer("density0", 0, quantity0);
|
||||
advectSet->updateBuffer("velocityX", 0, velocityX);
|
||||
advectSet->updateBuffer("velocityY", 0, velocityY);
|
||||
advectSet->updateBuffer("velocityZ", 0, velocityZ);
|
||||
advectSet->updateConstants("dt", 0, &dt);
|
||||
advectSet->writeChanges();
|
||||
Gfx::OComputeCommand advectCommand = graphics->createComputeCommand();
|
||||
advectCommand->bindPipeline(advect.pipeline);
|
||||
advectCommand->bindDescriptor(advectSet);
|
||||
advectCommand->bindDescriptor(gridSizeSet);
|
||||
advectCommand->dispatch(getDispatchSize(gridSize, advect.threadGroupSize));
|
||||
graphics->executeCommands(std::move(advectCommand));
|
||||
|
||||
quantity->pipelineBarrier(Gfx::SE_ACCESS_SHADER_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT, Gfx::SE_ACCESS_SHADER_READ_BIT,
|
||||
Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT);
|
||||
}
|
||||
|
||||
void SimulationComputePass::applyForcesPass(Gfx::PShaderBuffer velocityX, Gfx::PShaderBuffer velocityY, Gfx::PShaderBuffer velocityZ, Vector gravity, float dt, UVector gridSize) {
|
||||
Gfx::ODescriptorSet forcesSet = applyForces.descriptorLayout->allocateDescriptorSet();
|
||||
forcesSet->updateBuffer("velocityX", 0, velocityX);
|
||||
forcesSet->updateBuffer("velocityY", 0, velocityY);
|
||||
forcesSet->updateBuffer("velocityZ", 0, velocityZ);
|
||||
forcesSet->updateConstants("force", 0, &gravity);
|
||||
forcesSet->updateConstants("dt", 0, &dt);
|
||||
forcesSet->writeChanges();
|
||||
Gfx::OComputeCommand forcesCommand = graphics->createComputeCommand();
|
||||
forcesCommand->bindPipeline(applyForces.pipeline);
|
||||
forcesCommand->bindDescriptor(forcesSet);
|
||||
forcesCommand->bindDescriptor(gridSizeSet);
|
||||
forcesCommand->dispatch(getDispatchSize(gridSize, applyForces.threadGroupSize));
|
||||
graphics->executeCommands(std::move(forcesCommand));
|
||||
|
||||
velocityX->pipelineBarrier(Gfx::SE_ACCESS_SHADER_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT, Gfx::SE_ACCESS_SHADER_READ_BIT,
|
||||
Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT);
|
||||
velocityY->pipelineBarrier(Gfx::SE_ACCESS_SHADER_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT, Gfx::SE_ACCESS_SHADER_READ_BIT,
|
||||
Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT);
|
||||
velocityZ->pipelineBarrier(Gfx::SE_ACCESS_SHADER_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT, Gfx::SE_ACCESS_SHADER_READ_BIT,
|
||||
Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT);
|
||||
}
|
||||
|
||||
void SimulationComputePass::massProbePass(Gfx::PShaderBuffer density, Gfx::PShaderBuffer phi, Gfx::PShaderBuffer velocityX, Gfx::PShaderBuffer velocityY,
|
||||
Gfx::PShaderBuffer velocityZ, UVector gridSize) {
|
||||
// Zero the 3-float accumulator before dispatching.
|
||||
float zeros[3] = {0.0f, 0.0f, 0.0f};
|
||||
probeOutBuffer->updateContents(0, 3 * sizeof(float), zeros);
|
||||
probeOutBuffer->pipelineBarrier(Gfx::SE_ACCESS_TRANSFER_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_TRANSFER_BIT, Gfx::SE_ACCESS_SHADER_READ_BIT | Gfx::SE_ACCESS_SHADER_WRITE_BIT,
|
||||
Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT);
|
||||
|
||||
Gfx::ODescriptorSet probeSet = massProbe.descriptorLayout->allocateDescriptorSet();
|
||||
probeSet->updateBuffer("density", 0, density);
|
||||
probeSet->updateBuffer("phi", 0, phi);
|
||||
probeSet->updateBuffer("velocityX", 0, velocityX);
|
||||
probeSet->updateBuffer("velocityY", 0, velocityY);
|
||||
probeSet->updateBuffer("velocityZ", 0, velocityZ);
|
||||
probeSet->updateBuffer("out", 0, probeOutBuffer);
|
||||
probeSet->writeChanges();
|
||||
|
||||
Gfx::OComputeCommand probeCommand = graphics->createComputeCommand();
|
||||
probeCommand->bindPipeline(massProbe.pipeline);
|
||||
probeCommand->bindDescriptor(probeSet);
|
||||
probeCommand->bindDescriptor(gridSizeSet);
|
||||
probeCommand->dispatch(getDispatchSize(gridSize, massProbe.threadGroupSize));
|
||||
graphics->executeCommands(std::move(probeCommand));
|
||||
|
||||
// Blocking readback (safe mid-frame: the Vulkan impl waits on a fence internally).
|
||||
float results[3] = {0.0f, 0.0f, 0.0f};
|
||||
probeOutBuffer->pipelineBarrier(Gfx::SE_ACCESS_SHADER_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT, Gfx::SE_ACCESS_TRANSFER_READ_BIT,
|
||||
Gfx::SE_PIPELINE_STAGE_TRANSFER_BIT);
|
||||
probeOutBuffer->readContents(0, 3 * sizeof(float), results);
|
||||
|
||||
std::cout << "[MassProbe] frame=" << probeFrame
|
||||
<< " density_sum=" << results[0]
|
||||
<< " phi_sum=" << results[1]
|
||||
<< " |vel|_sum=" << results[2] << std::endl;
|
||||
++probeFrame;
|
||||
}
|
||||
|
||||
void SimulationComputePass::reinitializeLevelSetPass(Seele::Gfx::PShaderBuffer phi, Seele::Gfx::PShaderBuffer phi0, Seele::Gfx::PShaderBuffer phiSign, UVector gridSize, Gfx::PShaderBuffer planeBuffer, uint32 numPlanes) {
|
||||
graphics->beginDebugRegion("ReinitializeLevelSet");
|
||||
// Snapshot current phi into phiSign for the sign function (preserved across all iterations)
|
||||
phi->pipelineBarrier(Gfx::SE_ACCESS_SHADER_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT, Gfx::SE_ACCESS_TRANSFER_READ_BIT,
|
||||
Gfx::SE_PIPELINE_STAGE_TRANSFER_BIT);
|
||||
graphics->copyBuffer(phi, phiSign);
|
||||
phiSign->pipelineBarrier(Gfx::SE_ACCESS_TRANSFER_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_TRANSFER_BIT, Gfx::SE_ACCESS_SHADER_READ_BIT,
|
||||
Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT);
|
||||
// Also copy phi into phi0 as the "previous iteration" input for iteration 0
|
||||
graphics->copyBuffer(phi, phi0);
|
||||
phi0->pipelineBarrier(Gfx::SE_ACCESS_TRANSFER_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_TRANSFER_BIT, Gfx::SE_ACCESS_SHADER_READ_BIT,
|
||||
Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT);
|
||||
phi->pipelineBarrier(Gfx::SE_ACCESS_TRANSFER_READ_BIT, Gfx::SE_PIPELINE_STAGE_TRANSFER_BIT,
|
||||
Gfx::SE_ACCESS_SHADER_READ_BIT | Gfx::SE_ACCESS_SHADER_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT);
|
||||
|
||||
float dtau = reinitDtau;
|
||||
for (int i = 0; i < reinitIterations; ++i) {
|
||||
Gfx::ODescriptorSet reinitSet = reinitialize.descriptorLayout->allocateDescriptorSet();
|
||||
reinitSet->updateConstants("dtau", 0, &dtau);
|
||||
reinitSet->updateBuffer("phi", 0, phi);
|
||||
reinitSet->updateBuffer("phiPrev", 0, phi0);
|
||||
reinitSet->updateBuffer("phiSign", 0, phiSign);
|
||||
reinitSet->writeChanges();
|
||||
Gfx::OComputeCommand reinitCommand = graphics->createComputeCommand();
|
||||
reinitCommand->bindPipeline(reinitialize.pipeline);
|
||||
reinitCommand->bindDescriptor(reinitSet);
|
||||
reinitCommand->bindDescriptor(gridSizeSet);
|
||||
reinitCommand->dispatch(getDispatchSize(gridSize, reinitialize.threadGroupSize));
|
||||
graphics->executeCommands(std::move(reinitCommand));
|
||||
|
||||
phi->pipelineBarrier(Gfx::SE_ACCESS_SHADER_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT, Gfx::SE_ACCESS_SHADER_READ_BIT,
|
||||
Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT);
|
||||
setBoundsPass(phi, 0, gridSize, planeBuffer, numPlanes);
|
||||
// Copy result to phi0 for the next iteration's gradient reads
|
||||
phi->pipelineBarrier(Gfx::SE_ACCESS_SHADER_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT, Gfx::SE_ACCESS_TRANSFER_READ_BIT,
|
||||
Gfx::SE_PIPELINE_STAGE_TRANSFER_BIT);
|
||||
graphics->copyBuffer(phi, phi0);
|
||||
phi0->pipelineBarrier(Gfx::SE_ACCESS_TRANSFER_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_TRANSFER_BIT, Gfx::SE_ACCESS_SHADER_READ_BIT,
|
||||
Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT);
|
||||
phi->pipelineBarrier(Gfx::SE_ACCESS_TRANSFER_READ_BIT, Gfx::SE_PIPELINE_STAGE_TRANSFER_BIT,
|
||||
Gfx::SE_ACCESS_SHADER_READ_BIT | Gfx::SE_ACCESS_SHADER_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT);
|
||||
}
|
||||
graphics->endDebugRegion();
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
#pragma once
|
||||
#include "Graphics/Buffer.h"
|
||||
#include "Graphics/Descriptor.h"
|
||||
#include "Graphics/Initializer.h"
|
||||
#include "Graphics/RenderPass/RenderPass.h"
|
||||
#include "Graphics/Resources.h"
|
||||
#include "Math/Vector.h"
|
||||
#include "Scene/Scene.h"
|
||||
|
||||
namespace Seele {
|
||||
class SimulationComputePass : public RenderPass {
|
||||
public:
|
||||
SimulationComputePass(Gfx::PGraphics graphics, PScene scene);
|
||||
virtual ~SimulationComputePass() override;
|
||||
virtual void beginFrame(const Component::Camera& camera, const Seele::Component::Transform& transform) override;
|
||||
virtual void render() override;
|
||||
virtual void endFrame() override;
|
||||
virtual void publishOutputs() override;
|
||||
virtual void createRenderPass() override;
|
||||
|
||||
private:
|
||||
UVector getDispatchSize(const UVector& gridSize, const UVector& threadGroupSize);
|
||||
void setBoundsPass(Gfx::PShaderBuffer buffer, int b, UVector gridSize, Gfx::PShaderBuffer planeBuffer, uint32 numPlanes);
|
||||
void linearSolvePass(Gfx::PShaderBuffer grid, Seele::Gfx::PShaderBuffer grid0, float a, float c, float omega, UVector gridSize);
|
||||
void divergencePass(Gfx::PShaderBuffer divergence, Seele::Gfx::PShaderBuffer pressure, Seele::Gfx::PShaderBuffer velocityX,
|
||||
Seele::Gfx::PShaderBuffer velocityY, Seele::Gfx::PShaderBuffer velocityZ, UVector gridSize);
|
||||
void projectPass(Gfx::PShaderBuffer velocityX, Seele::Gfx::PShaderBuffer velocityY, Seele::Gfx::PShaderBuffer velocityZ,
|
||||
Seele::Gfx::PShaderBuffer pressure, UVector gridSize);
|
||||
void advectPass(Gfx::PShaderBuffer quantity, Seele::Gfx::PShaderBuffer quantity0, Seele::Gfx::PShaderBuffer velocityX,
|
||||
Seele::Gfx::PShaderBuffer velocityY, Seele::Gfx::PShaderBuffer velocityZ, float dt, UVector gridSize);
|
||||
void reinitializeLevelSetPass(Gfx::PShaderBuffer phi, Seele::Gfx::PShaderBuffer phi0, Seele::Gfx::PShaderBuffer phiSign, UVector gridSize, Gfx::PShaderBuffer planeBuffer, uint32 numPlanes);
|
||||
struct SetBounds {
|
||||
Gfx::OPipelineLayout pipelineLayout;
|
||||
Gfx::ODescriptorLayout descriptorLayout;
|
||||
Gfx::OComputeShader shader;
|
||||
Gfx::PComputePipeline pipeline;
|
||||
constexpr static UVector threadGroupSize = {4, 4, 4};
|
||||
} setBounds;
|
||||
struct LinearSolve {
|
||||
Gfx::OPipelineLayout pipelineLayout;
|
||||
Gfx::ODescriptorLayout descriptorLayout;
|
||||
Gfx::OComputeShader shader;
|
||||
Gfx::PComputePipeline pipeline;
|
||||
constexpr static UVector threadGroupSize = {32, 8, 1};
|
||||
} linearSolve;
|
||||
struct ComputeDivergence {
|
||||
Gfx::OPipelineLayout pipelineLayout;
|
||||
Gfx::ODescriptorLayout descriptorLayout;
|
||||
Gfx::OComputeShader shader;
|
||||
Gfx::PComputePipeline pipeline;
|
||||
constexpr static UVector threadGroupSize = {32, 8, 1};
|
||||
} computeDivergence;
|
||||
struct Project {
|
||||
Gfx::OPipelineLayout pipelineLayout;
|
||||
Gfx::ODescriptorLayout descriptorLayout;
|
||||
Gfx::OComputeShader shader;
|
||||
Gfx::PComputePipeline pipeline;
|
||||
constexpr static UVector threadGroupSize = {32, 8, 1};
|
||||
} project;
|
||||
struct Advect {
|
||||
Gfx::OPipelineLayout pipelineLayout;
|
||||
Gfx::ODescriptorLayout descriptorLayout;
|
||||
Gfx::OComputeShader shader;
|
||||
Gfx::PComputePipeline pipeline;
|
||||
constexpr static UVector threadGroupSize = {32, 8, 1};
|
||||
} advect;
|
||||
struct Reinitialize {
|
||||
Gfx::OPipelineLayout pipelineLayout;
|
||||
Gfx::ODescriptorLayout descriptorLayout;
|
||||
Gfx::OComputeShader shader;
|
||||
Gfx::PComputePipeline pipeline;
|
||||
constexpr static UVector threadGroupSize = {32, 8, 1};
|
||||
} reinitialize;
|
||||
struct ApplyForces {
|
||||
Gfx::OPipelineLayout pipelineLayout;
|
||||
Gfx::ODescriptorLayout descriptorLayout;
|
||||
Gfx::OComputeShader shader;
|
||||
Gfx::PComputePipeline pipeline;
|
||||
constexpr static UVector threadGroupSize = {32, 8, 1};
|
||||
} applyForces;
|
||||
void applyForcesPass(Gfx::PShaderBuffer velocityX, Gfx::PShaderBuffer velocityY, Gfx::PShaderBuffer velocityZ, Vector gravity, float dt, UVector gridSize);
|
||||
// Diagnostics: sum interior fields and log to console. Not part of the simulation.
|
||||
void massProbePass(Gfx::PShaderBuffer density, Gfx::PShaderBuffer phi, Gfx::PShaderBuffer velocityX, Gfx::PShaderBuffer velocityY,
|
||||
Gfx::PShaderBuffer velocityZ, UVector gridSize);
|
||||
struct MassProbe {
|
||||
Gfx::OPipelineLayout pipelineLayout;
|
||||
Gfx::ODescriptorLayout descriptorLayout;
|
||||
Gfx::OComputeShader shader;
|
||||
Gfx::PComputePipeline pipeline;
|
||||
constexpr static UVector threadGroupSize = {32, 8, 1};
|
||||
} massProbe;
|
||||
Gfx::ODescriptorLayout gridSizeLayout;
|
||||
Gfx::ODescriptorSet gridSizeSet;
|
||||
// Diagnostics: 3 floats (density sum, phi sum, |velocity| sum), zeroed each frame.
|
||||
Gfx::OShaderBuffer probeOutBuffer;
|
||||
uint32 probeFrame = 0;
|
||||
struct BoundaryPlane {
|
||||
Vector normal;
|
||||
float d;
|
||||
};
|
||||
PScene scene;
|
||||
};
|
||||
DEFINE_REF(SimulationComputePass)
|
||||
} // namespace Seele
|
||||
@@ -0,0 +1,107 @@
|
||||
#include "SurfaceExtractPass.h"
|
||||
#include "Graphics/Command.h"
|
||||
#include "Graphics/Descriptor.h"
|
||||
#include "Graphics/Enums.h"
|
||||
#include "Graphics/Graphics.h"
|
||||
#include "Graphics/Initializer.h"
|
||||
#include "Graphics/Shader.h"
|
||||
#include "Scene/FluidScene.h"
|
||||
|
||||
using namespace Seele;
|
||||
|
||||
SurfaceExtractPass::SurfaceExtractPass(Gfx::PGraphics graphics, PScene scene) : RenderPass(graphics), scene(scene) {
|
||||
pipelineLayout = graphics->createPipelineLayout("SurfaceExtractPipelineLayout");
|
||||
gridSizeLayout = graphics->createDescriptorLayout("gridParams");
|
||||
gridSizeLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = "gridSize",
|
||||
.uniformLength = sizeof(UVector),
|
||||
});
|
||||
gridSizeLayout->create();
|
||||
descriptorLayout = graphics->createDescriptorLayout("params");
|
||||
descriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = "vertexBuffer",
|
||||
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER,
|
||||
});
|
||||
descriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = "normalBuffer",
|
||||
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER,
|
||||
});
|
||||
descriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = "indexBuffer",
|
||||
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER,
|
||||
});
|
||||
descriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = "surfaceCounts",
|
||||
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER,
|
||||
});
|
||||
descriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = "levelSet",
|
||||
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER,
|
||||
});
|
||||
descriptorLayout->create();
|
||||
pipelineLayout->addDescriptorLayout(descriptorLayout);
|
||||
pipelineLayout->addDescriptorLayout(gridSizeLayout);
|
||||
graphics->beginShaderCompilation(ShaderCompilationInfo{
|
||||
.name = "MarchingCubes",
|
||||
.modules = {"MarchingCubes"},
|
||||
.entryPoints = {{"marchingCubes", "MarchingCubes"}},
|
||||
.rootSignature = pipelineLayout,
|
||||
.dumpIntermediate = true,
|
||||
});
|
||||
pipelineLayout->create();
|
||||
computeShader = graphics->createComputeShader({0});
|
||||
pipeline = graphics->createComputePipeline(Gfx::ComputePipelineCreateInfo{
|
||||
.computeShader = computeShader,
|
||||
.pipelineLayout = pipelineLayout,
|
||||
});
|
||||
}
|
||||
|
||||
SurfaceExtractPass::~SurfaceExtractPass() {}
|
||||
|
||||
void SurfaceExtractPass::beginFrame(const Seele::Component::Camera&, const Seele::Component::Transform&) {}
|
||||
|
||||
|
||||
void SurfaceExtractPass::render() {
|
||||
for (auto& [entityID, data] : scene->getFluidScene()->getFluidDataMap()) {
|
||||
Gfx::ODescriptorSet gridSizeSet = gridSizeLayout->allocateDescriptorSet();
|
||||
gridSizeSet->updateConstants("gridSize", 0, &data.gridSize);
|
||||
gridSizeSet->writeChanges();
|
||||
data.vertexBuffer->rotateBuffer(data.getVertexBufferSize() * sizeof(float));
|
||||
data.normalBuffer->rotateBuffer(data.getVertexBufferSize() * sizeof(float));
|
||||
data.indexBuffer->rotateBuffer(data.getIndexBufferSize() * sizeof(uint32));
|
||||
uint32 surfaceCountData[4] = {0, 1, 0, 0};
|
||||
data.surfaceCountBuffer->updateContents(0, sizeof(surfaceCountData), surfaceCountData);
|
||||
data.surfaceCountBuffer->pipelineBarrier(Gfx::SE_ACCESS_TRANSFER_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_TRANSFER_BIT,
|
||||
Gfx::SE_ACCESS_SHADER_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT);
|
||||
|
||||
descriptorSet = descriptorLayout->allocateDescriptorSet();
|
||||
descriptorSet->updateBuffer("vertexBuffer", 0, data.vertexBuffer);
|
||||
descriptorSet->updateBuffer("normalBuffer", 0, data.normalBuffer);
|
||||
descriptorSet->updateBuffer("indexBuffer", 0, data.indexBuffer);
|
||||
descriptorSet->updateBuffer("surfaceCounts", 0, data.surfaceCountBuffer);
|
||||
descriptorSet->updateBuffer("levelSet", 0, data.phiBuffer);
|
||||
descriptorSet->writeChanges();
|
||||
|
||||
Gfx::OComputeCommand cmd = graphics->createComputeCommand();
|
||||
cmd->bindPipeline(pipeline);
|
||||
cmd->bindDescriptor(descriptorSet);
|
||||
cmd->bindDescriptor(gridSizeSet);
|
||||
cmd->dispatch((data.gridSize + threadGroupSize - 1u) / threadGroupSize);
|
||||
graphics->executeCommands(std::move(cmd));
|
||||
|
||||
data.vertexBuffer->pipelineBarrier(Gfx::SE_ACCESS_SHADER_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
|
||||
Gfx::SE_ACCESS_SHADER_READ_BIT, Gfx::SE_PIPELINE_STAGE_VERTEX_SHADER_BIT);
|
||||
data.normalBuffer->pipelineBarrier(Gfx::SE_ACCESS_SHADER_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
|
||||
Gfx::SE_ACCESS_SHADER_READ_BIT, Gfx::SE_PIPELINE_STAGE_VERTEX_SHADER_BIT);
|
||||
data.indexBuffer->pipelineBarrier(Gfx::SE_ACCESS_SHADER_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
|
||||
Gfx::SE_ACCESS_SHADER_READ_BIT, Gfx::SE_PIPELINE_STAGE_VERTEX_SHADER_BIT);
|
||||
data.surfaceCountBuffer->pipelineBarrier(Gfx::SE_ACCESS_SHADER_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
|
||||
Gfx::SE_ACCESS_INDIRECT_COMMAND_READ_BIT, Gfx::SE_PIPELINE_STAGE_DRAW_INDIRECT_BIT);
|
||||
}
|
||||
}
|
||||
|
||||
void SurfaceExtractPass::endFrame() {}
|
||||
|
||||
void SurfaceExtractPass::publishOutputs() {}
|
||||
|
||||
void SurfaceExtractPass::createRenderPass() {}
|
||||
@@ -0,0 +1,30 @@
|
||||
#pragma once
|
||||
#include "Graphics/Graphics.h"
|
||||
#include "Graphics/RenderPass/RenderPass.h"
|
||||
#include "Graphics/Resources.h"
|
||||
#include "Scene/Scene.h"
|
||||
|
||||
namespace Seele {
|
||||
class SurfaceExtractPass : public RenderPass {
|
||||
public:
|
||||
SurfaceExtractPass(Gfx::PGraphics graphics, PScene scene);
|
||||
virtual ~SurfaceExtractPass() override;
|
||||
virtual void beginFrame(const Component::Camera &camera, const Component::Transform &transform) override;
|
||||
virtual void render() override;
|
||||
virtual void endFrame() override;
|
||||
virtual void publishOutputs() override;
|
||||
virtual void createRenderPass() override;
|
||||
|
||||
private:
|
||||
PScene scene;
|
||||
|
||||
Gfx::OPipelineLayout pipelineLayout;
|
||||
Gfx::ODescriptorLayout descriptorLayout;
|
||||
Gfx::ODescriptorLayout gridSizeLayout;
|
||||
Gfx::ODescriptorSet descriptorSet;
|
||||
Gfx::OComputeShader computeShader;
|
||||
Gfx::PComputePipeline pipeline;
|
||||
constexpr static UVector threadGroupSize = {16, 8, 1};
|
||||
};
|
||||
DEFINE_REF(SurfaceExtractPass)
|
||||
} // namespace Seele
|
||||
Loaded 100 of 184 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user