Compare commits

...
10 Commits
Author SHA1 Message Date
Dynamitos c57ca4efe6 Fixing render layout split 2026-11-21 12:08:35 +01:00
Dynamitos 28a76ed404 Merge pull request 'Basic widgets' (#4) from coding-agent/Seele:main into master
Reviewed-on: Dynamitos/Seele#4
2026-11-10 19:22:54 +01:00
coding-agent 6e1cccdb40 Basic widgets 2026-11-10 18:18:42 +00:00
Dynamitos 949a6738bd Merge pull request 'Application refactor' (#2) from coding-agent/Seele:application-refactor into master
Reviewed-on: Dynamitos/Seele#2
2026-11-09 20:07:56 +01:00
Dynamitos 1f7e7e0541 Engine is up and running 2026-11-09 20:07:40 +01:00
coding-agent 1e34f0e67b refactor: rename WindowManager to Application; move world ownership up
WindowManager.{h,cpp} -> Application.{h,cpp}

The Application class now owns the long-lived world (Scene, SystemGraph,
GameInterface) and is the single setup point. This removes the per-view
duplication where each GameView/PlayView loaded the binary and ran the
simulation independently, which double-simulated with two windows open.

Changes:
- WindowManager -> Application (class, files, includes, CMake)
- Application owns OScene scene_ / OSystemGraph graph_ (OwningPtr)
  and GameInterface* gameInterface (raw, deleted in dtor)
- loadGame(graphics, path, name): single world-setup point
  (dlopen -> setupScene -> append 5 editor systems)
- attachWorld(OScene, OSystemGraph): worldless hosts (benchmark)
  hand ownership in via move
- Frame-loop fix: systemGraph->run() now runs ONCE per frame, before
  the window loop (was per-window -> double-simulated with 2 windows)
- Editor/main.cpp + Benchmark/main.cpp rewired to the new API
- Window.h/.cpp: PWindowManager back-pointer -> PApplication
- 8 include paths updated to Window/Application.h

Compile-verified: Application.cpp, Editor/main.cpp, Benchmark/main.cpp
all pass g++ -std=c++23 -fsyntax-only against the full third-party
include set.
2026-11-09 20:07:40 +01:00
Dynamitos 803531c608 Fix miscellaneus errors 2026-11-09 20:07:40 +01:00
coding-agent c5c66f8cf3 Editor: headless Vulkan graphics + entity/component InspectorView + --headless CLI
Engine (headless construction, no display / no WSI):
- Graphics/Vulkan/Graphics.{h,cpp} + Graphics/Initializer.h: a 'headless' flag
  skips surface/swapchain extension negotiation and the window path so a VkDevice
  can be created with a driver present but no display.
- Scene/Scene.{h,cpp}: null-guards + PScene circular-include decoupling.
- Actor/Entity.{h,cpp}: hasComponent fix (handle-space component query).

Editor:
- Editor/Window/InspectorView.{h,cpp}: Unity-style entity/component inspector on a
  fixed widget pool (no runtime tree mutation) driven by a UIPass in the render
  graph; owns its UI::System via UI::OSystem.
- Editor/ComponentRegistry.{h,cpp}: type-erased component catalog (handle-space only,
  no entt in the editor API) that drives the inspector's component pane.
- Editor/main.cpp: --headless / --dump-entities path (headless device + scene dump,
  no window) and InspectorView wiring with a live PScene on the windowed path.

Compile-verified (-fsyntax-only, -std=c++23) across all touched TUs.
2026-11-09 20:07:40 +01:00
Dynamitos 499407d366 Merge pull request 'docs: add per-subsystem deep-dives + cross-repo orientation (for coding agents)' (#1) from coding-agent/Seele:docs/engine-orientation into master
Reviewed-on: Dynamitos/Seele#1
Reviewed-by: Dynamitos <dynamitos@hey.com>
2026-11-07 23:18:19 +01:00
coding-agent 1324d903cb docs: add per-subsystem deep-dives + cross-repo orientation (for coding agents)
Adds docs/ — a navigation layer on top of AGENTS.md for future coding
agents working on the Seele engine and the MeshShadingDemo harness.

- docs/README.md: index + 30-second orientation + how-to-use workflow.
- docs/cross-repo.md: the engine<->demo contract (2-symbol ABI, the
  ComponentSystem<...> demo pattern with the FlyCamSystem example, the
  CMake in-tree vs install(EXPORT) split, a where-to-look task map).
- docs/subsystems/*.md: 16 per-subsystem deep-dives (scene/ECS, systems,
  game-interface, window, graphics backends, render graph, materials,
  physics, UI, assets, platform, core utils). Each maps public types to
  their defining headers and gives file:line pointers + gotchas.

All cross-links verified resolving. This is documentation only — no source
changes.
2026-11-07 22:08:50 +00:00
86 changed files with 4157 additions and 266 deletions

No files matched your search

+135
View File
@@ -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).
+348
View File
@@ -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.
+70
View File
@@ -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.*
+88
View File
@@ -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.*
+46
View File
@@ -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.*
+87
View File
@@ -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.*
+65
View File
@@ -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.*
+120
View File
@@ -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)" |
+136
View File
@@ -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.*
+54
View File
@@ -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.*
+135
View File
@@ -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) |
+73
View File
@@ -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.*
+94
View File
@@ -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` |
+85 -32
View File
@@ -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})"
@@ -65,8 +87,8 @@ class ListSyntheticProvider:
return True
def Tree_SummaryProvider(valobj, internal_dict):
size = valobj.GetChildMemberWithName('_size').GetValueAsUnsigned(0)
return f"Tree(size={size})"
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):
@@ -87,28 +109,35 @@ class TreeSyntheticProvider:
return None
# Collect all nodes via in-order traversal, then return the one at `index`
nodes = []
self._collect(self.root, nodes)
if self.root and self.root.IsValid():
self._collect(self.root, nodes)
if index >= len(nodes):
return None
return nodes[index].GetChildMemberWithName('data')
data = nodes[index].GetChildMemberWithName('data')
return data if data.IsValid() else None
def _collect(self, node, out):
if not node.IsValid():
return
self._collect(node.GetChildMemberWithName('leftChild'), out)
left = node.GetChildMemberWithName('leftChild')
if left.IsValid():
self._collect(left.Dereference(), out)
out.append(node)
self._collect(node.GetChildMemberWithName('rightChild'), out)
right = node.GetChildMemberWithName('rightChild')
if right.IsValid():
self._collect(right.Dereference(), out)
def update(self):
self.root = self.valobj.GetChildMemberWithName('root')
self.size = self.valobj.GetChildMemberWithName('_size').GetValueAsUnsigned(0)
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 True
return self.size > 0
def Set_SummaryProvider(valobj, internal_dict):
size = valobj.GetChildMemberWithName('_size').GetValueAsUnsigned(0)
return f"Set(size={size})"
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):
@@ -128,28 +157,39 @@ class SetSyntheticProvider:
if index < 0 or index >= self.size:
return None
nodes = []
self._collect(self.root, 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
return nodes[index].GetChildMemberWithName('data')
data = nodes[index].GetChildMemberWithName('data')
return data if data.IsValid() else None
def _collect(self, node, out):
if not node.IsValid():
return
self._collect(node.GetChildMemberWithName('leftChild'), out)
left = node.GetChildMemberWithName('leftChild')
if left.IsValid():
self._collect(left.Dereference(), out)
out.append(node)
self._collect(node.GetChildMemberWithName('rightChild'), out)
right = node.GetChildMemberWithName('rightChild')
if right.IsValid():
self._collect(right.Dereference(), out)
def update(self):
self.root = self.valobj.GetChildMemberWithName('root')
self.size = self.valobj.GetChildMemberWithName('_size').GetValueAsUnsigned(0)
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 True
return self.size > 0
def Map_SummaryProvider(valobj, internal_dict):
size = valobj.GetChildMemberWithName('_size').GetValueAsUnsigned(0)
return f"Map(size={size})"
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):
@@ -169,24 +209,37 @@ class MapSyntheticProvider:
if index < 0 or index >= self.size:
return None
nodes = []
self._collect(self.root, 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
return nodes[index].GetChildMemberWithName('data')
# 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
self._collect(node.GetChildMemberWithName('leftChild'), out)
left = node.GetChildMemberWithName('leftChild')
if left.IsValid():
self._collect(left.Dereference(), out)
out.append(node)
self._collect(node.GetChildMemberWithName('rightChild'), out)
right = node.GetChildMemberWithName('rightChild')
if right.IsValid():
self._collect(right.Dereference(), out)
def update(self):
self.root = self.valobj.GetChildMemberWithName('root')
self.size = self.valobj.GetChildMemberWithName('_size').GetValueAsUnsigned(0)
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 True
return self.size > 0
def Vector_SummaryProvider(valobj, internal_dict):
# Get the template parameters to determine vector length
+3 -1
View File
@@ -359,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;
+1 -1
View File
@@ -68,7 +68,7 @@ struct DrawCallOffsets
};
#ifdef RAY_TRACING
// Shader record buffers are accessed via a different mechanism and don't use descriptor set bindings
layout(set = 15, shaderRecordEXT)
layout(shaderRecordEXT)
#else
layout(push_constant)
#endif
+2 -1
View File
@@ -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;
}
+3 -2
View File
@@ -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([&]() {
+1 -1
View File
@@ -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;
+15 -7
View File
@@ -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();
+1 -1
View File
@@ -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>
+3 -1
View File
@@ -3,4 +3,6 @@ add_subdirectory(Window/)
target_sources(Editor
PRIVATE
main.cpp)
main.cpp
ComponentRegistry.h
ComponentRegistry.cpp)
+208
View File
@@ -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
+83
View File
@@ -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
+233 -21
View File
@@ -1,26 +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, FlexRow, M_4>({},
{
new UI::Text<Font_Arial, Text_8XL>("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();
}
@@ -29,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, KeyModifierFlags) {}
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, KeyModifierFlags) {}
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], "");
}
}
}
+57 -16
View File
@@ -1,37 +1,78 @@
#pragma once
#include "Graphics/RenderPass/RenderGraph.h"
#include "Graphics/RenderPass/UIPass.h"
#include "Window/View.h"
#include "UI/System.h"
#include "UI/Style/Fonts.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, KeyModifierFlags 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, KeyModifierFlags 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 -2
View File
@@ -7,8 +7,8 @@
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() {}
+1 -1
View File
@@ -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;
+1 -1
View File
@@ -50,6 +50,6 @@ void SceneView::mouseButtonCallback(MouseButton button, InputAction action, KeyM
cameraSystem.mouseButtonCallback(button, action);
}
void SceneView::scrollCallback(double, double) {}
void SceneView::scrollCallback(double, double, double, double) {}
void SceneView::fileCallback(int, const char**) {}
+1 -1
View File
@@ -32,7 +32,7 @@ class SceneView : public View {
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, KeyModifierFlags modifier) override;
virtual void scrollCallback(double xOffset, double yOffset) 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)
+121 -17
View File
@@ -10,10 +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;
@@ -21,7 +31,97 @@ 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("/home/dynamitos/{0}Game/", gameName);
std::filesystem::path sourcePath = fmt::format("/home/dynamitos/{0}/", gameName);
@@ -41,7 +141,6 @@ int main() {
StaticMeshVertexData* vd = StaticMeshVertexData::getInstance();
vd->init(graphics);
OWindowManager windowManager = new WindowManager();
AssetRegistry::init(sourcePath / "Assets", graphics);
AssetImporter::init(graphics);
AssetImporter::importFont(FontImportArgs{
@@ -69,6 +168,12 @@ int main() {
});
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,
@@ -76,16 +181,15 @@ int main() {
.title = "SeeleEngine",
.preferredFormat = Gfx::SE_FORMAT_B8G8R8A8_SRGB,
};
auto window = windowManager->addWindow(graphics, mainWindowInfo);
// ViewportCreateInfo sceneViewInfo = {
// .dimensions =
// {
// .size = {1920, 1080},
// .offset = {0, 0},
// },
// };
// OGameView sceneView = new Editor::PlayView(graphics, window, sceneViewInfo, binaryPath);
// sceneView->setFocused();
auto window = application->addWindow(graphics, mainWindowInfo);
ViewportCreateInfo sceneViewInfo = {
.dimensions =
{
.size = {1920, 1080},
.offset = {0, 0},
},
};
OGameView sceneView = new Editor::PlayView(graphics, window, application->scene(), sceneViewInfo);
OInspectorView inspectorView = new Editor::InspectorView(graphics, window,
ViewportCreateInfo{
.dimensions =
@@ -93,12 +197,12 @@ int main() {
.size = {1920, 1080},
.offset = {0, 0},
},
});
},
/* scene = */ application->scene());
inspectorView->setFocused();
window->show();
while (windowManager->isActive() && getGlobals().running) {
windowManager->render();
while (application->isActive() && getGlobals().running) {
application->render();
}
graphics->waitDeviceIdle();
Material::destroy();
+15 -2
View File
@@ -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);
}
+27
View File
@@ -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)...);
}
+1 -1
View File
@@ -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>
+1 -1
View File
@@ -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>
+4
View File
@@ -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;
+5 -1
View File
@@ -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;
+3 -3
View File
@@ -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;
+5 -3
View File
@@ -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); }
+15 -8
View File
@@ -475,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,
});
+7 -11
View File
@@ -8,7 +8,7 @@
using namespace Seele;
UIPass::UIPass(Gfx::PGraphics graphics, UI::PSystem system) : RenderPass(graphics), system(system), passSize(0, 0) {
UIPass::UIPass(Gfx::PGraphics graphics, UI::PSystem system) : RenderPass(graphics), system(system) {
elementBuffer = graphics->createShaderBuffer(ShaderBufferCreateInfo{.name = "RenderStyleElements"});
uiDescriptorLayout = graphics->createDescriptorLayout("pParams");
@@ -119,8 +119,8 @@ void UIPass::publishOutputs() {}
void UIPass::createRenderPass() {
TextureCreateInfo depthBufferInfo = {
.format = Gfx::SE_FORMAT_D32_SFLOAT,
.width = viewport->getWidth(),
.height = viewport->getHeight(),
.width = viewport->getOwner()->getFramebufferWidth(),
.height = viewport->getOwner()->getFramebufferHeight(),
.usage = Gfx::SE_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT,
};
@@ -134,14 +134,10 @@ void UIPass::createRenderPass() {
Gfx::SE_ATTACHMENT_LOAD_OP_CLEAR, Gfx::SE_ATTACHMENT_STORE_OP_STORE);
colorAttachment.clear.color = {{1.0f, 1.0f, 1.0f, 1.0f}};
// the render pass encodes the viewport size, and Vulkan requires a fresh pass object when
// that changes. Re-run createRenderPass() from beginFrame on a viewport resize; the
// pipeline is recreated here from scratch (it embeds renderPass and is size-independent
// otherwise).
if (passSize.x != viewport->getWidth() || passSize.y != viewport->getHeight()) {
passSize = UVector2(viewport->getWidth(), viewport->getHeight());
createRenderPass();
}
Gfx::RenderTargetLayout layout = Gfx::RenderTargetLayout{
.colorAttachments = {colorAttachment},
.depthAttachment = depthAttachment,
};
Array<Gfx::SubPassDependency> dependency = {
{
.srcSubpass = ~0U,
-1
View File
@@ -70,7 +70,6 @@ class UIPass : public RenderPass {
Gfx::PGraphicsPipeline uiPipeline;
UI::PSystem system;
UVector2 passSize; // last viewport size the render pass was created at; recreate on resize
Array<UI::UIRender> renderElements;
Array<RenderElementStyle> elements;
Gfx::OShaderBuffer elementBuffer;
+1 -1
View File
@@ -61,7 +61,7 @@ void Command::beginRenderPass(PRenderPass renderPass, PFramebuffer framebuffer)
.pNext = nullptr,
.renderPass = renderPass->getHandle(),
.framebuffer = framebuffer->getHandle(),
.renderArea = framebuffer->getRenderArea(),
.renderArea = renderPass->getRenderArea(),
.clearValueCount = (uint32)renderPass->getClearValueCount(),
.pClearValues = renderPass->getClearValues(),
};
@@ -68,10 +68,6 @@ Framebuffer::Framebuffer(PGraphics graphics, PRenderPass renderPass, Gfx::Render
.layers = 1,
};
VK_CHECK(vkCreateFramebuffer(graphics->getDevice(), &createInfo, nullptr, &handle));
renderArea = VkRect2D{
.offset = {0, 0},
.extent = {width, height},
};
hash = CRC::Calculate(&description, sizeof(FramebufferDescription), CRC::CRC_32());
}
-2
View File
@@ -22,11 +22,9 @@ class Framebuffer {
virtual ~Framebuffer();
constexpr VkFramebuffer getHandle() const { return handle; }
constexpr uint32 getHash() const { return hash; }
constexpr VkRect2D getRenderArea() const { return renderArea; }
private:
uint32 hash;
VkRect2D renderArea;
PGraphics graphics;
VkFramebuffer handle;
Gfx::RenderTargetLayout layout;
+43 -7
View File
@@ -186,7 +186,7 @@ VkDeviceAddress vkGetAccelerationStructureDeviceAddressKHR(VkDevice device, cons
return getAccelerationStructureDeviceAddress(device, pInfo);
}
Graphics::Graphics() : instance(VK_NULL_HANDLE), handle(VK_NULL_HANDLE), physicalDevice(VK_NULL_HANDLE), callback(VK_NULL_HANDLE) {}
Graphics::Graphics() : instance(VK_NULL_HANDLE), handle(VK_NULL_HANDLE), physicalDevice(VK_NULL_HANDLE), callback(VK_NULL_HANDLE), headless(false) {}
Graphics::~Graphics() {
pipelineCache = nullptr;
@@ -202,6 +202,10 @@ Graphics::~Graphics() {
}
void Graphics::init(GraphicsInitializer initInfo) {
// Capture headless before initInstance so getRequiredExtensions / initInstance /
// createDevice can all branch on it. In headless mode we intentionally skip GLFW
// init, all WSI surface extensions, and the swapchain device extension.
headless = initInfo.headless;
initInstance(initInfo);
setupDebugCallback();
pickPhysicalDevice();
@@ -230,10 +234,9 @@ Gfx::OViewport Graphics::createViewport(Gfx::PWindow owner, const ViewportCreate
return new Viewport(owner, viewportInfo);
}
Gfx::ORenderPass Graphics::createRenderPass(Gfx::RenderTargetLayout layout, Array<Gfx::SubPassDependency> dependencies, URect,
Gfx::ORenderPass Graphics::createRenderPass(Gfx::RenderTargetLayout layout, Array<Gfx::SubPassDependency> dependencies, URect renderArea,
std::string name, Array<uint32> viewMasks, Array<uint32> correlationMasks) {
// todo: re-introduce render area to renderpass
return new RenderPass(this, std::move(layout), std::move(dependencies), name, std::move(viewMasks), std::move(correlationMasks));
return new RenderPass(this, std::move(layout), std::move(dependencies), renderArea, name, std::move(viewMasks), std::move(correlationMasks));
}
void Graphics::beginRenderPass(Gfx::PRenderPass renderPass) {
PRenderPass rp = renderPass.cast<RenderPass>();
@@ -259,6 +262,10 @@ void Graphics::waitDeviceIdle() {
getGraphicsCommands()->refreshCommands();
}
void Graphics::invalidateFramebuffers() {
allocatedFramebuffers.clear();
}
void Graphics::executeCommands(Gfx::ORenderCommand commands) {
Array<Gfx::ORenderCommand> commandArray;
commandArray.add(std::move(commands));
@@ -728,6 +735,25 @@ Array<const char*> Graphics::getRequiredExtensions() {
return hasInstanceExtension(availableExtensions, extensionName);
};
// Headless: no WSI surface support at all. We do not query GLFW (it fails to
// init without a display) and we do not request any surface extension. The
// instance is still valid for descriptor/pipeline layouts, queues, and
// device-local resources — only window/swapchain paths are unavailable.
if (headless) {
#ifdef ENABLE_VALIDATION
extensions.addUnique(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
#endif
Array<const char*> validatedExtensions;
for (uint32 i = 0; i < extensions.size(); ++i) {
if (supportsExtension(extensions[i])) {
validatedExtensions.addUnique(extensions[i]);
} else {
std::cerr << "Warning: Vulkan instance extension not exposed by loader, skipping: " << extensions[i] << std::endl;
}
}
return validatedExtensions;
}
unsigned int glfwExtensionCount = 0;
const char** glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtensionCount);
@@ -830,7 +856,12 @@ Array<const char*> Graphics::getRequiredExtensions() {
}
void Graphics::initInstance(GraphicsInitializer initInfo) {
initializeGlfwForVulkan();
// In headless mode there is no display, so GLFW cannot be initialized. Skip it
// entirely; getRequiredExtensions() already returns a surface-less set in this
// case. Everything else (instance, device, queues) proceeds normally.
if (!headless) {
initializeGlfwForVulkan();
}
VkApplicationInfo appInfo = {
.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO,
.pNext = nullptr,
@@ -981,7 +1012,7 @@ void Graphics::pickPhysicalDevice() {
shaderFloatControls = true;
}
}
rayTracingEnabled = rayTracingPipelineSupport && accelerationStructureSupport && hostOperationsSupport && deviceAddressSupport &&
rayTracingEnabled = false && rayTracingPipelineSupport && accelerationStructureSupport && hostOperationsSupport && deviceAddressSupport &&
descriptorIndexingSupport && spirv14Support && shaderFloatControls;
}
@@ -1056,7 +1087,12 @@ void Graphics::createDevice(GraphicsInitializer initializer) {
*currentPriority++ = 0.0f;
}
}
initializer.deviceExtensions.add(VK_KHR_SWAPCHAIN_EXTENSION_NAME);
// In headless mode there is no swapchain (no window / no surface), so the
// swapchain device extension must not be requested. It is only needed for
// creating swapchain image views, which a headless device never does.
if (!headless) {
initializer.deviceExtensions.add(VK_KHR_SWAPCHAIN_EXTENSION_NAME);
}
if (supportMeshShading()) {
initializer.deviceExtensions.add(VK_EXT_MESH_SHADER_EXTENSION_NAME);
features.get<VkPhysicalDeviceVulkan12Features>().pNext = &meshFeatures.get();
+8
View File
@@ -106,6 +106,7 @@ class Graphics : public Gfx::Graphics {
virtual void beginRenderPass(Gfx::PRenderPass renderPass) override;
virtual void endRenderPass() override;
virtual void waitDeviceIdle() override;
virtual void invalidateFramebuffers() override;
virtual void executeCommands(Gfx::ORenderCommand commands) override;
virtual void executeCommands(Array<Gfx::ORenderCommand> commands) override;
@@ -172,6 +173,13 @@ class Graphics : public Gfx::Graphics {
void pickPhysicalDevice();
void createDevice(GraphicsInitializer initInfo);
// When true, the device is built without any WSI surface support: no GLFW
// init, no VK_KHR_surface / WSI instance extensions, no swapchain device
// extension, and no window. Everything else (instance, queues, descriptor /
// pipeline layouts, device-local resources) is fully functional. This lets the
// engine run on headless machines that have a Vulkan driver but no display.
bool headless;
VkInstance instance;
VkDevice handle;
VkPhysicalDevice physicalDevice;
+5 -1
View File
@@ -9,9 +9,13 @@
using namespace Seele;
using namespace Seele::Vulkan;
RenderPass::RenderPass(PGraphics graphics, Gfx::RenderTargetLayout _layout, Array<Gfx::SubPassDependency> _dependencies, std::string name,
RenderPass::RenderPass(PGraphics graphics, Gfx::RenderTargetLayout _layout, Array<Gfx::SubPassDependency> _dependencies, URect _renderArea, std::string name,
Array<uint32> viewMasks, Array<uint32> correlationMasks)
: Gfx::RenderPass(std::move(_layout), std::move(_dependencies)), graphics(graphics), name(name) {
renderArea = {
.offset = { (int32)_renderArea.offset.x, (int32)_renderArea.offset.y },
.extent = { _renderArea.size.x, _renderArea.size.y },
};
subpassContents = VK_SUBPASS_CONTENTS_SECONDARY_COMMAND_BUFFERS;
Array<VkAttachmentDescription2> attachments;
Array<VkAttachmentReference2> inputRefs;
+3 -1
View File
@@ -2,13 +2,14 @@
#include "Graphics.h"
#include "Resources.h"
#include "Graphics/RenderTarget.h"
#include <vulkan/vulkan_core.h>
namespace Seele {
namespace Vulkan {
class RenderPass : public Gfx::RenderPass {
public:
RenderPass(PGraphics graphics, Gfx::RenderTargetLayout layout, Array<Gfx::SubPassDependency> dependencies, std::string name,
RenderPass(PGraphics graphics, Gfx::RenderTargetLayout layout, Array<Gfx::SubPassDependency> dependencies, URect renderArea, std::string name,
Array<uint32> viewMasks = {}, Array<uint32> correlationMasks = {});
virtual ~RenderPass();
uint32 getFramebufferHash();
@@ -17,6 +18,7 @@ class RenderPass : public Gfx::RenderPass {
constexpr size_t getClearValueCount() const { return clearValues.size(); }
constexpr VkClearValue* getClearValues() const { return clearValues.data(); }
constexpr VkSubpassContents getSubpassContents() const { return subpassContents; }
constexpr VkRect2D getRenderArea() const { return renderArea; }
constexpr const std::string& getName() const { return name; }
constexpr PRenderPassHandle getCommandHandle() const { return renderPass; }
+14 -3
View File
@@ -107,7 +107,12 @@ void glfwMouseButtonCallback(GLFWwindow* handle, int button, int action, int mod
void glfwScrollCallback(GLFWwindow* handle, double xoffset, double yoffset) {
auto* window = static_cast<Seele::Vulkan::Window*>(glfwGetWindowUserPointer(handle));
window->scroll(xoffset, yoffset);
// GLFW's scroll callback does NOT give the cursor position, but per-view routing
// needs it (scroll is spatial, like a mouse move). Query the current cursor pos
// synchronously — it is stable between events and this is the only source we have.
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) {
@@ -257,7 +262,7 @@ void Seele::Vulkan::Window::setMouseMoveCallback(std::function<void(double, doub
void Seele::Vulkan::Window::setMouseButtonCallback(std::function<void(MouseButton, InputAction, KeyModifierFlags)> callback) { mouseButtonCallback = callback; }
void Seele::Vulkan::Window::setScrollCallback(std::function<void(double, double)> callback) { scrollCallback = callback; }
void Seele::Vulkan::Window::setScrollCallback(std::function<void(double x, double y, double xScroll, double yScroll)> callback) { scrollCallback = callback; }
void Seele::Vulkan::Window::setFileCallback(std::function<void(int, const char**)> callback) { fileCallback = callback; }
@@ -271,7 +276,7 @@ void Seele::Vulkan::Window::mouseMove(double x, double y) { mouseMoveCallback(x,
void Seele::Vulkan::Window::mouseButton(MouseButton button, InputAction action, KeyModifierFlags modifier) { mouseButtonCallback(button, action, modifier); }
void Seele::Vulkan::Window::scroll(double x, double y) { scrollCallback(x, y); }
void Seele::Vulkan::Window::scroll(double x, double y, double xScroll, double yScroll) { scrollCallback(x, y, xScroll, yScroll); }
void Seele::Vulkan::Window::fileDrop(int num, const char** files) { fileCallback(num, files); }
@@ -291,6 +296,12 @@ void Seele::Vulkan::Window::resize(int width, int height) {
framebufferWidth = extent.width;
framebufferHeight = extent.height;
createSwapChain();
// The swapchain size changed and the views will be re-laid-out by resizeCallback below,
// which rebuilds each pass's intermediate textures at the new (view) size. Any cached
// framebuffers from the previous size are now stale (their handle-only hash also changed)
// and must be dropped before the next render, or the pass would bind an over-wide
// framebuffer whose renderArea is a sub-slice of it.
graphics->invalidateFramebuffers();
resizeCallback(width, height);
}
+3 -3
View File
@@ -20,7 +20,7 @@ class Window : public Gfx::Window {
virtual void setKeyCallback(std::function<void(KeyCode, InputAction, KeyModifierFlags)> callback) override;
virtual void setMouseMoveCallback(std::function<void(double, double)> callback) override;
virtual void setMouseButtonCallback(std::function<void(MouseButton, InputAction, KeyModifierFlags)> 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;
@@ -28,7 +28,7 @@ class Window : public Gfx::Window {
void keyPress(KeyCode code, InputAction action, KeyModifierFlags modifier);
void mouseMove(double x, double y);
void mouseButton(MouseButton button, InputAction action, KeyModifierFlags 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);
@@ -64,7 +64,7 @@ class Window : public Gfx::Window {
std::function<void(KeyCode, InputAction, KeyModifierFlags)> keyCallback;
std::function<void(double, double)> mouseMoveCallback;
std::function<void(MouseButton, InputAction, KeyModifierFlags)> 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;
+4 -1
View File
@@ -18,7 +18,10 @@ class Window {
virtual void setKeyCallback(std::function<void(KeyCode, InputAction, KeyModifierFlags)> callback) = 0;
virtual void setMouseMoveCallback(std::function<void(double, double)> callback) = 0;
virtual void setMouseButtonCallback(std::function<void(MouseButton, InputAction, KeyModifierFlags)> callback) = 0;
virtual void setScrollCallback(std::function<void(double, double)> callback) = 0;
// The scroll callback carries the cursor POSITION (x, y) in addition to the scroll
// deltas. Position is required for per-view routing (a scroll is a spatial event,
// exactly like a mouse move).
virtual void setScrollCallback(std::function<void(double x, double y, double xScroll, double yScroll)> callback) = 0;
virtual void setFileCallback(std::function<void(int, const char**)> callback) = 0;
virtual void setCloseCallback(std::function<void()> callback) = 0;
virtual void setResizeCallback(std::function<void(uint32, uint32)> callback) = 0;
+1 -1
View File
@@ -4,7 +4,7 @@
#include "Graphics/Shader.h"
#include "MaterialInstance.h"
#include "Serialization/Serialization.h"
#include "Window/WindowManager.h"
#include "Window/Application.h"
#include <fstream>
using namespace Seele;
+7
View File
@@ -13,6 +13,13 @@ struct Rect {
struct URect {
UVector2 size = UVector2(0);
UVector2 offset = UVector2(0);
// Half-open containment test for a window/client-space point (used for per-view input
// hit-testing). Right/bottom edges are exclusive, matching how the column layout in
// Window::onResize tiles the window without seams or double-hits at shared edges.
bool contains(double x, double y) const {
return x >= static_cast<double>(offset.x) && x < static_cast<double>(offset.x + size.x) &&
y >= static_cast<double>(offset.y) && y < static_cast<double>(offset.y + size.y);
}
};
struct Rect3D {
Vector size = Vector(0);
+39 -1
View File
@@ -2,11 +2,21 @@
#include "Graphics/Graphics.h"
#include "LightEnvironment.h"
#include "FluidScene.h"
#include "Actor/Actor.h"
#include "Actor/Entity.h"
using namespace Seele;
// A scene can be built with a null graphics handle (headless / tooling use): in that case
// the GPU-bound sub-systems (light baking, fluid sim) are simply not constructed - they are
// only needed when there is a live device to render/simulate to. The ECS registry and the
// entity roster remain fully functional, which is all a headless inspector or a CLI dump
// needs. This keeps `new Scene(nullptr)` a valid, cheap, side-effect-free construction.
Scene::Scene(Gfx::PGraphics graphics)
: graphics(graphics), lightEnv(new LightEnvironment(graphics)), fluidScene(new FluidScene(graphics)), physics(registry) {}
: graphics(graphics)
, lightEnv(graphics != nullptr ? new LightEnvironment(graphics) : nullptr)
, fluidScene(graphics != nullptr ? new FluidScene(graphics) : nullptr)
, physics(registry) {}
Scene::~Scene() {}
@@ -14,3 +24,31 @@ void Scene::bakeLighting() {}
void Scene::update(float deltaTime) { physics.update(deltaTime); }
// Out-of-line definitions: these need the complete Entity type (getIdentifier()),
// which is only available here (Scene.cpp includes Actor/Entity.h). Scene.h
// forward-declares Entity only, to avoid the circular include.
void Scene::destroyEntity(entt::entity identifier) {
// Unlink from the roster before destroying the record so the roster never points at
// a dead entity. This is the single choke point through which every entity is torn
// down (Entity::~Entity routes here), so the roster stays consistent by construction.
auto& entities = this->entities;
for (size_t i = 0; i < entities.size(); ++i) {
if (entities[i] != nullptr && entities[i]->getIdentifier() == identifier) {
entities.removeAt(i);
break;
}
}
if (registry.valid(identifier)) {
registry.destroy(identifier);
}
}
void Scene::unregisterEntity(entt::entity identifier) {
for (size_t i = 0; i < entities.size(); ++i) {
if (entities[i] != nullptr && entities[i]->getIdentifier() == identifier) {
entities.removeAt(i);
return;
}
}
}
+25 -1
View File
@@ -16,7 +16,22 @@ class Scene {
void bakeLighting();
void update(float deltaTime);
entt::entity createEntity() { return registry.create(); }
void destroyEntity(entt::entity identifier) { registry.destroy(identifier); }
// Out-of-line (Scene.cpp): the bodies need the complete Entity type (they call
// getIdentifier() on roster entries). Scene.h only forward-declares Entity
// (DECLARE_REF) to keep the header light and to avoid a circular include -
// Entity.h includes Scene.h, so Scene.h must not pull Actor/Entity.h back in.
void destroyEntity(entt::entity identifier);
// The scene is the single source of truth for which entities exist. The editor's
// inspector enumerates this roster (non-owning views) to build its entity list - the
// whole point of "the scene owns the entity". Populated as entities are created and
// pruned as they are destroyed; never points at a live handle that outlives its record.
const Array<PEntity>& getEntities() const { return entities; }
// Internal: called by Entity's ctor/dtor to keep the roster in lock-step with the
// registry. Not part of the public "create/destroy" surface (use createEntity /
// destroyEntity for that).
void registerEntity(entt::entity identifier, PEntity self) { entities.add(self); }
// Out-of-line (Scene.cpp): calls getIdentifier() on roster entries -> needs complete Entity.
void unregisterEntity(entt::entity identifier);
template <typename Component, typename... Args> Component& attachComponent(entt::entity entity, Args&&... args) {
return registry.emplace<Component>(entity, std::forward<Args>(args)...);
}
@@ -37,6 +52,15 @@ class Scene {
private:
Gfx::PGraphics graphics;
// The roster: the scene's single source of truth for which entities currently exist.
// Non-owning views (P* = RefPtr, a plain pointer) - the *owning* O* (OwningPtr) held
// by the code that created each actor still owns the C++ object; the roster only tracks
// existence so tooling (the editor's inspector) can enumerate entities in handle space.
// Kept in lock-step by Entity's ctor (registerEntity) and dtor (routed through
// destroyEntity -> unregisterEntity), so it never points at a dead record.
Array<PEntity> entities;
OLightEnvironment lightEnv;
OFluidScene fluidScene;
PhysicsSystem physics;
+2
View File
@@ -7,6 +7,7 @@ target_sources(Engine
FlexLayout.cpp
System.h
System.cpp
Widgets.h
)
target_sources(Engine
@@ -16,6 +17,7 @@ target_sources(Engine
Element.h
FlexLayout.h
System.h
Widgets.h
)
add_subdirectory(Style/)
+90
View File
@@ -0,0 +1,90 @@
#pragma once
#include "UI/Element/Div.h"
#include "UI/Element/Text.h"
#include "UI/Style/Class.h"
namespace Seele {
namespace UI {
// An accordion: a collapsible section with a header that toggles the body.
// HTML analog: <details><summary>
//
// The Accordion is a vertical container with a header (a clickable label)
// and a body (arbitrary children). The body's visibility is toggled by the
// owning view in response to the header's onClick. The Accordion itself does
// not track open/closed state — the view does.
//
// Usage:
// auto* header = new Text<Font_Arial, Text_SM>("Section Title");
// auto* body = new Div<FlexCol>(UI::Attributes{});
// auto* acc = new Accordion<>(UI::Attributes{}, OElement(header), OElement(body));
// // The view owns the "open" state and toggles body's visibility:
// // if (clicked) { bodyVisible = !bodyVisible; acc->setBodyVisible(bodyVisible); }
template<StyleClass... classes>
class Accordion : public Div<classes...> {
public:
using Div<classes...>::attr;
using Div<classes...>::style;
using Div<classes...>::markDirty;
using Div<classes...>::getTheme;
using Div<classes...>::children;
Accordion(Attributes attr, OElement header, OElement body)
: Div<classes...>(std::move(attr), std::initializer_list<OElement>{}) {
_header = PElement(header);
_body = PElement(body);
children.add(std::move(header));
children.add(std::move(body));
if (children.size() >= 2) {
children.back()->setParent(this);
}
style.backgroundColor = Vector(0.10f, 0.10f, 0.12f);
style.gap = 0;
if (_header != nullptr) {
auto* h = _header.getHandle();
if (h != nullptr) {
auto& hs = h->getStyle();
hs.backgroundColor = Vector(0.14f, 0.14f, 0.16f);
hs.paddingLeft = 12;
hs.paddingRight = 12;
hs.paddingTop = 8;
hs.paddingBottom = 8;
}
}
}
virtual ~Accordion() override {}
void setBodyVisible(bool visible) {
if (_body != nullptr) {
auto* b = _body.getHandle();
if (b != nullptr) {
b->getStyle().display = visible ? Display::Flex : Display::Hidden;
b->markDirty();
}
}
}
bool isBodyVisible() const {
if (_body == nullptr) {
return false;
}
auto* b = _body.getHandle();
return b != nullptr && b->getStyle().display == Display::Flex;
}
PElement getHeader() const { return _header; }
PElement getBody() const { return _body; }
void applyStyle(Style parentStyle, const Theme& theme) override {
Div<classes...>::applyStyle(parentStyle, theme);
style.backgroundColor = Vector(0.10f, 0.10f, 0.12f);
style.gap = 0;
}
private:
PElement _header;
PElement _body;
};
} // namespace UI
} // namespace Seele
+22
View File
@@ -4,6 +4,17 @@ target_sources(Engine
Text.h
Button.h
Panel.h
Checkbox.h
ToggleSwitch.h
Radio.h
SelectBox.h
InputField.h
Slider.h
Progressbar.h
TabBar.h
Tooltip.h
Accordion.h
HR.h
)
target_sources(Engine
@@ -13,4 +24,15 @@ target_sources(Engine
Text.h
Button.h
Panel.h
Checkbox.h
ToggleSwitch.h
Radio.h
SelectBox.h
InputField.h
Slider.h
Progressbar.h
TabBar.h
Tooltip.h
Accordion.h
HR.h
)
+68
View File
@@ -0,0 +1,68 @@
#pragma once
#include "UI/Element/Div.h"
#include "UI/Style/Class.h"
namespace Seele {
namespace UI {
// A checkbox: a square indicator + optional label.
// HTML analog: <input type="checkbox">
//
// Usage:
// auto* cb = new Checkbox<>();
// // per-frame: cb->setChecked(viewState.flag)
//
// Pure display widget. The view drives checked state via setChecked().
// The checkbox does NOT handle its own onClick — the view wires the
// toggle logic via attr.onClick on the owning container.
template<StyleClass... classes>
class Checkbox : public Div<classes...> {
public:
using Div<classes...>::attr;
using Div<classes...>::style;
using Div<classes...>::markDirty;
using Div<classes...>::getTheme;
using Div<classes...>::children;
Checkbox(Attributes attr = Attributes{}, std::initializer_list<OElement> children = {})
: Div<classes...>(std::move(attr), children) {
style.height = 20;
style.width = 20;
}
virtual ~Checkbox() override {}
void setChecked(bool checked) {
_checked = checked;
markDirty();
}
bool isChecked() const { return _checked; }
void setHovered(bool hovered) override { _hovered = hovered; }
void setFocused(bool focused) override { _focused = focused; }
bool isFocusable() const override { return attr.focusable; }
void applyStyle(Style parentStyle, const Theme& theme) override {
Div<classes...>::applyStyle(parentStyle, theme);
}
// The System calls applyOverrides() during style() after applyStyle.
// We use it to reflect checked/hover/focus in the background color.
void applyOverrides() override {
const Theme& th = getTheme();
if (_checked) {
style.backgroundColor = th.color(ColorToken::Green);
} else if (_hovered) {
style.backgroundColor = Vector(0.22f, 0.24f, 0.28f);
} else if (_focused) {
style.backgroundColor = Vector(0.20f, 0.22f, 0.26f);
} else {
style.backgroundColor = Vector(0.14f, 0.14f, 0.16f);
}
}
private:
bool _checked = false;
bool _hovered = false;
bool _focused = false;
};
} // namespace UI
} // namespace Seele
+35
View File
@@ -0,0 +1,35 @@
#pragma once
#include "UI/Element/Div.h"
#include "UI/Style/Class.h"
namespace Seele {
namespace UI {
// A horizontal rule: a thin decorative divider line.
// HTML analog: <hr>
//
// A simple 1px tall element with a subtle background color. No interactivity.
template<StyleClass... classes>
class HR : public Div<classes...> {
public:
using Div<classes...>::attr;
using Div<classes...>::style;
HR(Attributes attr = Attributes{}, std::initializer_list<OElement> children = {})
: Div<classes...>(std::move(attr), children) {
style.height = 1;
style.backgroundColor = Vector(0.25f, 0.25f, 0.28f);
style.marginTop = 8;
style.marginBottom = 8;
}
virtual ~HR() override {}
void applyStyle(Style parentStyle, const Theme& theme) override {
Div<classes...>::applyStyle(parentStyle, theme);
style.height = 1;
style.backgroundColor = Vector(0.25f, 0.25f, 0.28f);
style.marginTop = 8;
style.marginBottom = 8;
}
};
} // namespace UI
} // namespace Seele
+98
View File
@@ -0,0 +1,98 @@
#pragma once
#include "UI/Element/Div.h"
#include "UI/Element/Text.h"
#include "UI/Style/Class.h"
namespace Seele {
namespace UI {
// A text input field: a box that displays a placeholder (when empty) or a
// text value (when non-empty). The actual text editing (key handling, cursor,
// IME) is the owning view's responsibility — the view intercepts key events
// and calls setValue() with the updated text.
//
// HTML analog: <input type="text">
//
// Usage:
// auto* field = new InputField<Font_Arial, Text_SM>(UI::Attributes{}, "Enter name...");
// // per-frame: field->setValue(viewState.inputText);
template<StyleClass... classes>
class InputField : public Div<classes...> {
public:
using Div<classes...>::attr;
using Div<classes...>::style;
using Div<classes...>::markDirty;
using Div<classes...>::getTheme;
using Div<classes...>::children;
InputField(Attributes attr, std::string placeholder = "")
: Div<classes...>(std::move(attr), std::initializer_list<OElement>{}) {
attr.focusable = true;
_placeholder = std::move(placeholder);
auto* t = new Text<classes...>(_placeholder);
children.add(OElement(t));
children.back()->setParent(this);
_text = PElement(t);
style.paddingLeft = 12;
style.paddingRight = 12;
style.paddingTop = 8;
style.paddingBottom = 8;
style.backgroundColor = Vector(0.10f, 0.10f, 0.12f);
}
virtual ~InputField() override {}
void setValue(std::string value) {
_value = std::move(value);
markDirty();
}
std::string getValue() const { return _value; }
std::string getPlaceholder() const { return _placeholder; }
void setFocused(bool focused) override {
_focused = focused;
}
void setHovered(bool hovered) override { _hovered = hovered; }
bool isFocusable() const override { return attr.focusable; }
void applyStyle(Style parentStyle, const Theme& theme) override {
Div<classes...>::applyStyle(parentStyle, theme);
}
void applyOverrides() override {
const Theme& th = getTheme();
if (_focused) {
style.backgroundColor = Vector(0.14f, 0.15f, 0.18f);
} else if (_hovered) {
style.backgroundColor = Vector(0.12f, 0.12f, 0.14f);
} else {
style.backgroundColor = Vector(0.10f, 0.10f, 0.12f);
}
// Switch between placeholder (dimmed) and value (full color) display.
if (_text == nullptr) {
return;
}
auto* t = dynamic_cast<Text<classes...>*>(_text.getHandle());
if (t == nullptr) {
return;
}
if (_value.empty()) {
t->setText(_placeholder);
style.textColor = th.color(ColorToken::Gray600);
} else {
t->setText(_value);
style.textColor = th.color(ColorToken::White);
}
markDirty();
}
private:
std::string _placeholder;
std::string _value;
bool _focused = false;
bool _hovered = false;
PElement _text;
};
} // namespace UI
} // namespace Seele
+56
View File
@@ -0,0 +1,56 @@
#pragma once
#include "UI/Element/Div.h"
#include "UI/Style/Class.h"
namespace Seele {
namespace UI {
// A progress bar: a horizontal bar that fills proportionally to a 0.0-1.0 value.
// HTML analog: <progress>
//
// Usage:
// auto* bar = new Progressbar<>();
// // per-frame: bar->setValue(fraction) // 0.0 - 1.0
//
// Pure display widget. The bar's background is a lerp between a dimmed
// "empty" color and an accent "full" color, giving a visual fill effect.
template<StyleClass... classes>
class Progressbar : public Div<classes...> {
public:
using Div<classes...>::attr;
using Div<classes...>::style;
using Div<classes...>::markDirty;
using Div<classes...>::getTheme;
Progressbar(Attributes attr = Attributes{}, std::initializer_list<OElement> children = {})
: Div<classes...>(std::move(attr), children) {
style.height = 8;
}
virtual ~Progressbar() override {}
void setValue(float value) {
_value = value < 0.0f ? 0.0f : (value > 1.0f ? 1.0f : value);
markDirty();
}
float getValue() const { return _value; }
void applyStyle(Style parentStyle, const Theme& theme) override {
Div<classes...>::applyStyle(parentStyle, theme);
}
void applyOverrides() override {
const Theme& th = getTheme();
// Lerp between empty (dimmed) and full (green) based on value.
Vector empty(0.14f, 0.14f, 0.16f);
Vector full = th.color(ColorToken::Green);
float v = _value;
style.backgroundColor = Vector(
empty.x + (full.x - empty.x) * v,
empty.y + (full.y - empty.y) * v,
empty.z + (full.z - empty.z) * v);
}
private:
float _value = 0.0f;
};
} // namespace UI
} // namespace Seele
+66
View File
@@ -0,0 +1,66 @@
#pragma once
#include "UI/Element/Div.h"
#include "UI/Style/Class.h"
namespace Seele {
namespace UI {
// A radio button: a circular indicator + optional label.
// HTML analog: <input type="radio">
//
// Usage:
// auto* r1 = new Radio<>();
// auto* r2 = new Radio<>();
// // per-frame: r1->setSelected(viewState.choice == 0)
// // r2->setSelected(viewState.choice == 1)
//
// Pure display widget. The view owns the selection state and drives
// setSelected() on each radio in the group.
template<StyleClass... classes>
class Radio : public Div<classes...> {
public:
using Div<classes...>::attr;
using Div<classes...>::style;
using Div<classes...>::markDirty;
using Div<classes...>::getTheme;
Radio(Attributes attr = Attributes{}, std::initializer_list<OElement> children = {})
: Div<classes...>(std::move(attr), children) {
style.height = 20;
style.width = 20;
}
virtual ~Radio() override {}
void setSelected(bool selected) {
_selected = selected;
markDirty();
}
bool isSelected() const { return _selected; }
void setHovered(bool hovered) override { _hovered = hovered; }
void setFocused(bool focused) override { _focused = focused; }
bool isFocusable() const override { return attr.focusable; }
void applyStyle(Style parentStyle, const Theme& theme) override {
Div<classes...>::applyStyle(parentStyle, theme);
}
void applyOverrides() override {
const Theme& th = getTheme();
if (_selected) {
style.backgroundColor = th.color(ColorToken::Blue);
} else if (_hovered) {
style.backgroundColor = Vector(0.22f, 0.24f, 0.28f);
} else if (_focused) {
style.backgroundColor = Vector(0.20f, 0.22f, 0.26f);
} else {
style.backgroundColor = Vector(0.14f, 0.14f, 0.16f);
}
}
private:
bool _selected = false;
bool _hovered = false;
bool _focused = false;
};
} // namespace UI
} // namespace Seele
+97
View File
@@ -0,0 +1,97 @@
#pragma once
#include "UI/Element/Div.h"
#include "UI/Element/Text.h"
#include "UI/Style/Class.h"
namespace Seele {
namespace UI {
// A select box (dropdown): a clickable box that displays the current selection.
// HTML analog: <select>
//
// The dropdown list is a SEPARATE element tree managed by the owning view.
// The SelectBox is the trigger: it displays the current selection and an
// arrow indicator. The view toggles the dropdown list's visibility in
// response to onClick and updates the selection when the user picks an item.
//
// Usage (pass the font/size classes via the template pack):
// auto* sel = new SelectBox<Font_Arial, Text_SM>(UI::Attributes{}, "Option A");
// // per-frame: sel->setSelection("Option B"); sel->setOpen(true/false)
template<StyleClass... classes>
class SelectBox : public Div<classes...> {
public:
using Div<classes...>::attr;
using Div<classes...>::style;
using Div<classes...>::markDirty;
using Div<classes...>::getTheme;
using Div<classes...>::children;
SelectBox(Attributes attr, std::string selection = "")
: Div<classes...>(std::move(attr), std::initializer_list<OElement>{}) {
attr.focusable = true;
_selection = std::move(selection);
// Display text: the current selection + a down-arrow indicator.
auto* t = new Text<classes...>(_selection + " ▾");
children.add(OElement(t));
children.back()->setParent(this);
_text = PElement(t);
style.paddingLeft = 12;
style.paddingRight = 12;
style.paddingTop = 8;
style.paddingBottom = 8;
style.backgroundColor = Vector(0.14f, 0.14f, 0.16f);
}
virtual ~SelectBox() override {}
void setSelection(std::string selection) {
_selection = std::move(selection);
if (_text != nullptr) {
if (auto* t = dynamic_cast<Text<classes...>*>(_text.getHandle())) {
t->setText(_selection + " ▾");
}
}
markDirty();
}
std::string getSelection() const { return _selection; }
void setOpen(bool open) {
_open = open;
markDirty();
}
bool isOpen() const { return _open; }
void setHovered(bool hovered) override { _hovered = hovered; }
void setFocused(bool focused) override { _focused = focused; }
bool isFocusable() const override { return attr.focusable; }
void applyStyle(Style parentStyle, const Theme& theme) override {
Div<classes...>::applyStyle(parentStyle, theme);
}
void applyOverrides() override {
const Theme& th = getTheme();
if (_open) {
style.backgroundColor = Vector(0.18f, 0.19f, 0.22f);
style.textColor = th.color(ColorToken::White);
} else if (_hovered) {
style.backgroundColor = Vector(0.18f, 0.19f, 0.22f);
style.textColor = th.color(ColorToken::Gray400);
} else if (_focused) {
style.backgroundColor = Vector(0.16f, 0.17f, 0.20f);
style.textColor = th.color(ColorToken::Gray500);
} else {
style.backgroundColor = Vector(0.14f, 0.14f, 0.16f);
style.textColor = th.color(ColorToken::Gray400);
}
}
private:
std::string _selection;
bool _open = false;
bool _hovered = false;
bool _focused = false;
PElement _text;
};
} // namespace UI
} // namespace Seele
+68
View File
@@ -0,0 +1,68 @@
#pragma once
#include "UI/Element/Div.h"
#include "UI/Style/Class.h"
namespace Seele {
namespace UI {
// A slider: a horizontal track with a fill bar that reflects a 0.0-1.0 value.
// HTML analog: <input type="range">
//
// Usage:
// auto* slider = new Slider<>();
// // per-frame: slider->setValue(viewState.volume) // 0.0 - 1.0
//
// Pure display widget. The slider's background is a lerp between a dimmed
// "track" color and an accent "fill" color based on the value, giving a
// visual fill effect. Mouse drag handling is the owning view's job.
template<StyleClass... classes>
class Slider : public Div<classes...> {
public:
using Div<classes...>::attr;
using Div<classes...>::style;
using Div<classes...>::markDirty;
using Div<classes...>::getTheme;
Slider(Attributes attr = Attributes{}, std::initializer_list<OElement> children = {})
: Div<classes...>(std::move(attr), children) {
attr.focusable = true;
style.height = 8;
}
virtual ~Slider() override {}
void setValue(float value) {
_value = value < 0.0f ? 0.0f : (value > 1.0f ? 1.0f : value);
markDirty();
}
float getValue() const { return _value; }
void setHovered(bool hovered) override { _hovered = hovered; }
void setFocused(bool focused) override { _focused = focused; }
bool isFocusable() const override { return attr.focusable; }
void applyStyle(Style parentStyle, const Theme& theme) override {
Div<classes...>::applyStyle(parentStyle, theme);
}
void applyOverrides() override {
const Theme& th = getTheme();
if (_focused || _hovered) {
style.backgroundColor = th.color(ColorToken::Blue);
} else {
// Lerp between track (dimmed) and accent (blue) for fill effect.
Vector track(0.18f, 0.18f, 0.20f);
Vector accent = th.color(ColorToken::Blue);
float v = _value;
style.backgroundColor = Vector(
track.x + (accent.x - track.x) * v,
track.y + (accent.y - track.y) * v,
track.z + (accent.z - track.z) * v);
}
}
private:
float _value = 0.0f;
bool _hovered = false;
bool _focused = false;
};
} // namespace UI
} // namespace Seele
+72
View File
@@ -0,0 +1,72 @@
#pragma once
#include "UI/Element/Div.h"
#include "UI/Element/Button.h"
#include "UI/Style/Class.h"
namespace Seele {
namespace UI {
// A tab bar: a horizontal row of tab buttons. One tab is highlighted as active.
// HTML analog: <ul role="tablist">
//
// Usage:
// auto* tab1 = new Button<>(UI::Attributes{});
// auto* tab2 = new Button<>(UI::Attributes{});
// auto* tabs = new TabBar<>(UI::Attributes{}, {OElement(tab1), OElement(tab2)});
// // per-frame: tabs->setActiveTab(0)
//
// The tab bar takes a fixed set of Button children at construction (the
// fixed-children constraint). The active tab gets an accent color; the
// others get a dimmed color. The view handles onClick on each button to
// change the active tab.
template<StyleClass... classes>
class TabBar : public Div<classes...> {
public:
using Div<classes...>::attr;
using Div<classes...>::style;
using Div<classes...>::markDirty;
using Div<classes...>::getTheme;
using Div<classes...>::children;
TabBar(Attributes attr, std::initializer_list<OElement> tabs)
: Div<classes...>(std::move(attr), tabs) {
style.direction = FlexDirection::Row;
style.gap = 4;
}
virtual ~TabBar() override {}
void setActiveTab(int index) {
_activeTab = index;
markDirty();
}
int getActiveTab() const { return _activeTab; }
void applyStyle(Style parentStyle, const Theme& theme) override {
Div<classes...>::applyStyle(parentStyle, theme);
style.direction = FlexDirection::Row;
style.gap = 4;
}
void applyOverrides() override {
const Theme& th = getTheme();
int i = 0;
for (auto& child : children) {
if (child == nullptr) {
continue;
}
auto& cs = child->getStyle();
if (i == _activeTab) {
cs.backgroundColor = th.color(ColorToken::Blue);
cs.textColor = th.color(ColorToken::White);
} else {
cs.backgroundColor = Vector(0.14f, 0.14f, 0.16f);
cs.textColor = th.color(ColorToken::Gray500);
}
i++;
}
}
private:
int _activeTab = 0;
};
} // namespace UI
} // namespace Seele
+108
View File
@@ -0,0 +1,108 @@
#pragma once
#include "UI/Element/Div.h"
#include "UI/Element/Text.h"
#include "UI/Style/Class.h"
namespace Seele {
namespace UI {
// A toggle switch: a pill-shaped on/off switch with an optional label.
// HTML analog: <input type="checkbox"> styled as a switch (iOS-style)
//
// Usage:
// auto* toggle = new ToggleSwitch<Font_Arial, Text_SM>(UI::Attributes{}, "Wi-Fi");
// // per-frame: toggle->setOn(viewState.wifi)
//
// The toggle is a Div containing a label Text and an indicator pill.
// The pill's background shifts between off (dimmed) and on (green) based
// on the `on` state. The knob is a child div positioned to the left (off)
// or right (on).
template<StyleClass... classes>
class ToggleSwitch : public Div<classes...> {
public:
using Div<classes...>::attr;
using Div<classes...>::style;
using Div<classes...>::markDirty;
using Div<classes...>::getTheme;
using Div<classes...>::children;
ToggleSwitch(Attributes attr = Attributes{}, std::string label = "")
: Div<classes...>(std::move(attr), std::initializer_list<OElement>{}) {
// Build the label (if any)
if (!label.empty()) {
auto* lbl = new Text<classes...>(label);
children.add(OElement(lbl));
children.back()->setParent(this);
}
// Build the toggle pill: a rounded indicator (60x28)
auto* pill = new Div<>(UI::Attributes{});
{
auto& ps = pill->getStyle();
ps.width = 60;
ps.height = 28;
ps.backgroundColor = Vector(0.20f, 0.20f, 0.22f);
}
_pill = PElement(pill);
children.add(OElement(pill));
children.back()->setParent(this);
// Build the knob: a circle inside the pill (20x20)
auto* knob = new Div<>(UI::Attributes{});
{
auto& ks = knob->getStyle();
ks.width = 20;
ks.height = 20;
ks.backgroundColor = Vector(0.70f, 0.70f, 0.72f);
ks.left = 4;
ks.position = Position::Absolute;
}
_knob = PElement(knob);
children.add(OElement(knob));
children.back()->setParent(this);
style.height = 28;
}
virtual ~ToggleSwitch() override {}
void setOn(bool on) {
_on = on;
markDirty();
}
bool isOn() const { return _on; }
void setHovered(bool hovered) override { _hovered = hovered; }
void applyStyle(Style parentStyle, const Theme& theme) override {
Div<classes...>::applyStyle(parentStyle, theme);
}
void applyOverrides() override {
const Theme& th = getTheme();
if (_pill != nullptr) {
auto* p = _pill.getHandle();
if (p != nullptr) {
if (_on) {
p->getStyle().backgroundColor = th.color(ColorToken::Green);
} else {
p->getStyle().backgroundColor = Vector(0.20f, 0.20f, 0.22f);
}
p->markDirty();
}
}
if (_knob != nullptr) {
auto* k = _knob.getHandle();
if (k != nullptr) {
k->getStyle().left = _on ? 36 : 4;
k->markDirty();
}
}
}
private:
bool _on = false;
bool _hovered = false;
PElement _pill;
PElement _knob;
};
} // namespace UI
} // namespace Seele
+100
View File
@@ -0,0 +1,100 @@
#pragma once
#include "UI/Element/Div.h"
#include "UI/Element/Text.h"
#include "UI/Style/Class.h"
namespace Seele {
namespace UI {
// A tooltip: an element that shows a tooltip bubble when hovered.
// HTML analog: title="..." attribute / CSS :hover tooltip
//
// The Tooltip wraps a child element and, when the child is hovered, shows
// a floating label with the tooltip text. The tooltip is rendered as a
// child element (a Text with a dark background) that is hidden until hover.
//
// Usage:
// auto* target = new Button<>(UI::Attributes{});
// auto* tip = new Tooltip<>(UI::Attributes{}, OElement(target), "Helpful info");
//
// NOTE: the tooltip child is added to the tree at construction. Its position
// is set by the view (absolute positioning) — the Tooltip itself does not
// compute the tooltip's position.
template<StyleClass... classes>
class Tooltip : public Div<classes...> {
public:
using Div<classes...>::attr;
using Div<classes...>::style;
using Div<classes...>::markDirty;
using Div<classes...>::getTheme;
using Div<classes...>::children;
Tooltip(Attributes attr, OElement target, std::string text)
: Div<classes...>(std::move(attr), std::initializer_list<OElement>{}) {
// Wrap the target
children.add(std::move(target));
if (children.size() > 0) {
children.back()->setParent(this);
}
_tipText = std::move(text);
// Build the tooltip bubble: a dark panel with the text
auto* bubble = new Text<classes...>(_tipText);
{
auto& bs = bubble->getStyle();
bs.backgroundColor = Vector(0.05f, 0.05f, 0.06f);
bs.paddingLeft = 8;
bs.paddingRight = 8;
bs.paddingTop = 4;
bs.paddingBottom = 4;
bs.display = Display::Hidden;
}
_bubble = PElement(bubble);
children.add(OElement(bubble));
children.back()->setParent(this);
}
virtual ~Tooltip() override {}
void setText(std::string text) {
_tipText = std::move(text);
if (_bubble != nullptr) {
if (auto* t = dynamic_cast<Text<classes...>*>(_bubble.getHandle())) {
t->setText(_tipText);
}
}
markDirty();
}
void setHovered(bool hovered) override {
_hovered = hovered;
if (_bubble != nullptr) {
if (auto* b = dynamic_cast<Element*>(_bubble.getHandle())) {
if (b != nullptr) {
b->getStyle().display = hovered ? Display::Flex : Display::Hidden;
b->markDirty();
}
}
}
}
void applyStyle(Style parentStyle, const Theme& theme) override {
Div<classes...>::applyStyle(parentStyle, theme);
}
void applyOverrides() override {
const Theme& th = getTheme();
if (_bubble != nullptr) {
if (auto* b = dynamic_cast<Text<classes...>*>(_bubble.getHandle())) {
if (b != nullptr) {
b->getStyle().textColor = th.color(ColorToken::White);
}
}
}
}
private:
std::string _tipText;
PElement _bubble;
bool _hovered = false;
};
} // namespace UI
} // namespace Seele
+33
View File
@@ -0,0 +1,33 @@
#pragma once
// Seele UI: reusable component library.
//
// HTML-analog widgets built on the existing Element/Div/Text/Button base.
// All components are header-only template classes (matching the existing
// Button/Text/Div/Panel pattern). No .cpp files are needed.
//
// Design constraint: "children fixed at construction" — the UI tree's
// structure is immutable at runtime. Dynamic content (dropdown options,
// tab pages, scrollable items) is pre-allocated as a fixed pool at
// construction and driven per-frame by the owning view via setter methods
// (setText, setValue, setChecked, setVisible, etc.).
//
// Interaction model: the only sanctioned input path is Element::attr.onClick
// (delivered by System::processInput on click-release). Components that
// need to react to clicks expose the Button/Div onClick handler; the owning
// view reads state in its per-frame update() and calls the component's
// setters to reflect the new state.
// Form controls
#include "UI/Element/Checkbox.h"
#include "UI/Element/ToggleSwitch.h"
#include "UI/Element/Radio.h"
#include "UI/Element/SelectBox.h"
#include "UI/Element/InputField.h"
#include "UI/Element/Slider.h"
// Display / navigation
#include "UI/Element/Progressbar.h"
#include "UI/Element/TabBar.h"
#include "UI/Element/Tooltip.h"
#include "UI/Element/Accordion.h"
#include "UI/Element/HR.h"
+162
View File
@@ -0,0 +1,162 @@
// Syntax-check TU for the new UI widget components.
// Instantiates each component with template args to force full template
// instantiation, then references key members to ensure they exist.
#include "UI/Widgets.h"
#include "UI/Element/Button.h"
#include "UI/Element/Div.h"
#include "UI/Element/Text.h"
#include "UI/Style/Fonts.h"
using namespace Seele;
using namespace Seele::UI;
// A translation-unit-level function that exercises every new widget type.
// The compiler must fully instantiate each template here.
void widget_smoke_test() {
// --- Checkbox ---
{
auto* cb = new Checkbox<Font_Arial, Text_SM>();
cb->setChecked(true);
(void)cb->isChecked();
cb->setHovered(true);
cb->setFocused(true);
cb->applyOverrides();
(void)cb->style;
(void)cb->attr;
(void)cb->children;
cb->markDirty();
delete cb;
}
// --- ToggleSwitch ---
{
auto* ts = new ToggleSwitch<Font_Arial, Text_SM>(UI::Attributes{}, "Wi-Fi");
ts->setOn(true);
(void)ts->isOn();
ts->setHovered(true);
ts->applyOverrides();
(void)ts->style;
(void)ts->attr;
(void)ts->children;
ts->markDirty();
delete ts;
}
// --- Radio ---
{
auto* r1 = new Radio<Font_Arial, Text_SM>();
r1->setSelected(true);
(void)r1->isSelected();
r1->applyOverrides();
(void)r1->style;
(void)r1->attr;
r1->markDirty();
delete r1;
}
// --- SelectBox ---
{
auto* sel = new SelectBox<Font_Arial, Text_SM>(UI::Attributes{}, "Option A");
sel->setSelection("Option B");
(void)sel->getSelection();
sel->setOpen(true);
(void)sel->isOpen();
sel->applyOverrides();
(void)sel->style;
(void)sel->attr;
(void)sel->children;
sel->markDirty();
delete sel;
}
// --- InputField ---
{
auto* input = new InputField<Font_Arial, Text_SM>(UI::Attributes{}, "Enter name...");
input->setValue("hello");
(void)input->getValue();
(void)input->getPlaceholder();
input->setFocused(true);
input->applyOverrides();
(void)input->style;
(void)input->attr;
(void)input->children;
input->markDirty();
delete input;
}
// --- Slider ---
{
auto* slider = new Slider<Font_Arial, Text_SM>();
slider->setValue(0.75f);
(void)slider->getValue();
slider->applyOverrides();
(void)slider->style;
(void)slider->attr;
slider->markDirty();
delete slider;
}
// --- Progressbar ---
{
auto* bar = new Progressbar<Font_Arial, Text_SM>();
bar->setValue(0.5f);
(void)bar->getValue();
bar->applyOverrides();
(void)bar->style;
(void)bar->attr;
bar->markDirty();
delete bar;
}
// --- TabBar ---
{
auto* tab1 = new Button<Font_Arial, Text_SM>(UI::Attributes{});
auto* tab2 = new Button<Font_Arial, Text_SM>(UI::Attributes{});
auto* tabs = new TabBar<>(UI::Attributes{}, {OElement(tab1), OElement(tab2)});
tabs->setActiveTab(0);
(void)tabs->getActiveTab();
tabs->applyOverrides();
(void)tabs->style;
(void)tabs->attr;
(void)tabs->children;
tabs->markDirty();
delete tabs;
}
// --- Tooltip ---
{
auto* target = new Button<Font_Arial, Text_SM>(UI::Attributes{});
auto* tip = new Tooltip<Font_Arial, Text_SM>(UI::Attributes{}, OElement(target), "Helpful");
tip->setHovered(true);
tip->applyOverrides();
(void)tip->style;
(void)tip->attr;
(void)tip->children;
tip->markDirty();
delete tip;
}
// --- Accordion ---
{
auto* header = new Text<Font_Arial, Text_SM>("Section");
auto* body = new Div<>(UI::Attributes{});
auto* acc = new Accordion<>(UI::Attributes{}, OElement(header), OElement(body));
acc->setBodyVisible(false);
(void)acc->isBodyVisible();
(void)acc->getHeader();
(void)acc->getBody();
(void)acc->style;
(void)acc->attr;
(void)acc->children;
acc->markDirty();
delete acc;
}
// --- HR ---
{
auto* hr = new HR<Font_Arial, Text_SM>();
(void)hr->style;
(void)hr->attr;
delete hr;
}
}
+101
View File
@@ -0,0 +1,101 @@
#include "Application.h"
#include "Graphics/Enums.h"
#include "Graphics/Graphics.h"
#include "System/SystemGraph.h"
#include "Scene/Scene.h"
#include "Game.h"
#include "System/KeyboardInput.h"
#include "System/FluidUpdater.h"
#include "System/LightGather.h"
#include "System/MeshUpdater.h"
#include "System/CameraUpdater.h"
#ifdef WIN32
#include "Platform/Windows/GameInterface.h"
#else
#include "Platform/Linux/GameInterface.h"
#endif
using namespace Seele;
namespace {
// Library extension per platform (mirrors the editor's old binary-path logic).
const char* libraryExtension() {
#ifdef WIN32
return "dll";
#elif __APPLE__
return "dylib";
#else
return "so";
#endif
}
} // namespace
Application::Application() : graphics(nullptr), scene_(nullptr), graph_(nullptr), gameInterface(nullptr) {}
Application::~Application() {
if (gameInterface != nullptr) {
delete gameInterface; // ~GameInterface dlclose()s + destroys the Game instance
gameInterface = nullptr;
}
// `scene_` and `graph_` are OwningPtr: their destructors free the Scene and
// (via the moved-in OSystemBase entries) every System.
}
void Application::loadGame(Gfx::PGraphics graphics, const std::filesystem::path& sourcePath, const std::string& gameName) {
this->graphics = graphics;
// The world is created exactly once, owned by the Application. `loadGame` is
// the single setup point (called once per process) — no null guards needed.
scene_ = OScene(new Scene(graphics));
graph_ = OSystemGraph(new SystemGraph());
// Resolve the game binary and load it (dlopen) once.
std::filesystem::path binaryPath = sourcePath / "bin" / (gameName + "." + libraryExtension());
GameInterface* interface = new GameInterface(binaryPath);
interface->reload();
gameInterface = interface;
// Let the game populate the Scene + SystemGraph we own, then append the
// editor's own systems. This used to live in the editor's main.cpp; it now
// lives here so the world has a single owner and a single setup point.
interface->getGame()->setupScene(scene_, graph_);
// Keep a non-owning handle to the input sink so the focused game view can forward
// keyboard/pointer events into it (which then feed Component::KeyboardInput entities).
// Ownership stays with graph_ (the OSystemBase in its Array owns the real object).
System::OSystemBase sink = new System::KeyboardInput(scene_); // graph_'s Array owns it
keyboardInput_ = PKeyboardInput(static_cast<System::KeyboardInput*>(*sink)); // non-owning: graph_'s Array owns it
graph_->addSystem(std::move(sink));
graph_->addSystem(new System::FluidUpdater(scene_));
graph_->addSystem(new System::LightGather(scene_));
graph_->addSystem(new System::MeshUpdater(scene_));
graph_->addSystem(new System::CameraUpdater(scene_));
}
OWindow Application::addWindow(Gfx::PGraphics graphics, const WindowCreateInfo& createInfo) {
OWindow window = new Window(this, graphics->createWindow(createInfo));
windows.add(window);
return window;
}
void Application::attachWorld(OScene scene, OSystemGraph graph) {
// Worldless hosts (benchmark) build their own world and hand ownership in;
// the Application's owning members take it via move so the frame loop can
// step it and the views can render it.
scene_ = std::move(scene);
graph_ = std::move(graph);
}
void Application::render() {
// Step the world exactly ONCE per frame, independent of how many windows
// are open. The old code re-ran the graph inside the per-window loop, which
// double-simulated with two windows. Views below only render the world.
graph_->run(Gfx::getCurrentFrameDelta());
for (auto& window : windows) {
window->pollInputs();
if (window->isPaused())
continue;
window->render();
}
}
void Application::notifyWindowClosed(PWindow window) { windows.remove(window); }
+69
View File
@@ -0,0 +1,69 @@
#pragma once
#include "Containers/Array.h"
#include "System/SystemGraph.h"
#include "Window.h"
#include <filesystem>
namespace Seele {
DECLARE_NAME_REF(Gfx, Graphics)
DECLARE_REF(Scene)
class Game;
class GameInterface;
namespace System {
class KeyboardInput;
}
typedef ::Seele::RefPtr<Seele::System::KeyboardInput> PKeyboardInput;
// The long-lived top-level application object.
//
// Owns the *world*: the single Scene, the single SystemGraph (the running
// simulation) and the loaded game binary (GameInterface). There is exactly one
// of these per process, and it steps the simulation exactly once per frame --
// regardless of how many windows/views observe the scene. Views hold a
// non-owning PScene and only render; they never own the world.
//
// This is the old "WindowManager", renamed so its true responsibilities
// (windowing + world ownership + the frame loop) are named honestly.
class Application {
public:
Application();
~Application();
// Loads the game binary (dlopen) and lets it populate the Scene +
// SystemGraph it owns, then appends the editor's own systems. Called once,
// by the embedding host (the editor / benchmark main). `graphics` is needed
// to construct the Scene; `sourcePath`/`gameName` resolve the .so.
void loadGame(Gfx::PGraphics graphics, const std::filesystem::path& sourcePath, const std::string& gameName);
// Window management
OWindow addWindow(Gfx::PGraphics graphics, const WindowCreateInfo& createInfo);
void notifyWindowClosed(PWindow window);
bool isActive() const { return getGlobals().running && windows.size(); }
// Per-frame driver: steps the world ONCE, then renders every window.
void render();
// Non-owning handles so views can render the shared world.
PScene scene() const { return scene_; }
PSystemGraph systemGraph() const { return graph_; }
// The world's input sink: the System::KeyboardInput that the focused game
// view forwards keyboard/pointer events into (which then feed Component::
// KeyboardInput entities, e.g. the FlyCam). Null until loadGame() has run.
PKeyboardInput keyboardInput() const { return keyboardInput_; }
// Worldless hosts (e.g. the GPU-timing benchmark, which has no game binary)
// build their own world and hand ownership in; the owning members take it via
// move so the frame loop can step `graph_` and views can render `scene_`.
void attachWorld(OScene scene, OSystemGraph graph);
private:
Array<PWindow> windows;
Gfx::PGraphics graphics;
OScene scene_;
OSystemGraph graph_;
PKeyboardInput keyboardInput_ = nullptr; // non-owning: the OSystemBase in graph_ owns it
GameInterface* gameInterface = nullptr; // owned by Application (dlclose'd in dtor)
};
DEFINE_REF(Application)
} // namespace Seele
+3 -3
View File
@@ -6,8 +6,8 @@ target_sources(Engine
View.cpp
Window.cpp
Window.h
WindowManager.h
WindowManager.cpp)
Application.h
Application.cpp)
target_sources(Engine
PUBLIC FILE_SET HEADERS
@@ -15,4 +15,4 @@ target_sources(Engine
GameView.h
View.h
Window.h
WindowManager.h)
Application.h)
+22 -25
View File
@@ -4,25 +4,21 @@
#include "Graphics/RenderPass/BasePass.h"
#include "Graphics/RenderPass/CachedDepthPass.h"
#include "Graphics/RenderPass/DepthCullingPass.h"
#include "Graphics/RenderPass/FluidRenderPass.h"
#include "Graphics/RenderPass/LightCullingPass.h"
#include "Graphics/RenderPass/RayTracingPass.h"
#include "Graphics/RenderPass/ShadowPass.h"
#include "Graphics/RenderPass/SimulationComputePass.h"
#include "Graphics/RenderPass/SurfaceExtractPass.h"
#include "Graphics/RenderPass/ToneMappingPass.h"
#include "Graphics/RenderPass/VisibilityPass.h"
#include "System/CameraUpdater.h"
#include "System/FluidUpdater.h"
#include "System/LightGather.h"
#include "System/MeshUpdater.h"
#include "Window/Window.h"
#include "Scene/LightEnvironment.h"
using namespace Seele;
GameView::GameView(Gfx::PGraphics graphics, PWindow window, const ViewportCreateInfo& createInfo, std::filesystem::path dllPath)
: View(graphics, window, createInfo, "Game"), graphics(graphics), scene(new Scene(graphics)), gameInterface(dllPath) {
GameView::GameView(Gfx::PGraphics graphics, PWindow window, PScene scene, const ViewportCreateInfo& createInfo)
: View(graphics, window, createInfo, "Game"), graphics(graphics), scene(scene) {
// The Application (which owns the world) is reached via the Window that owns this View.
// The input sink is null until loadGame() runs; the callbacks above null-guard for that.
keyboardSystem = window->app()->keyboardInput();
reloadGame();
renderGraph.addPass(new CachedDepthPass(graphics, scene));
renderGraph.addPass(new DepthCullingPass(graphics, scene));
@@ -56,7 +52,6 @@ void GameView::update() {
for (VertexData* vd : VertexData::getList()) {
vd->resetMeshData();
}
systemGraph->run(updateTime);
scene->update(updateTime);
for (VertexData* vd : VertexData::getList()) {
vd->createDescriptors();
@@ -94,29 +89,31 @@ void GameView::applyArea(URect) {
}
void GameView::reloadGame() {
gameInterface.reload();
systemGraph = new SystemGraph();
gameInterface.getGame()->setupScene(scene, systemGraph);
System::OKeyboardInput keyInput = new System::KeyboardInput(scene);
keyboardSystem = keyInput;
systemGraph->addSystem(std::move(keyInput));
systemGraph->addSystem(new System::FluidUpdater(scene));
systemGraph->addSystem(new System::LightGather(scene));
systemGraph->addSystem(new System::MeshUpdater(scene));
systemGraph->addSystem(new System::CameraUpdater(scene));
}
void GameView::keyCallback(KeyCode code, InputAction action, KeyModifierFlags modifier) {
keyboardSystem->keyCallback(code, action, modifier);
if (keyboardSystem != nullptr) {
keyboardSystem->keyCallback(code, action, modifier);
}
}
void GameView::mouseMoveCallback(double xPos, double yPos) { keyboardSystem->mouseCallback(xPos, yPos); }
void GameView::mouseMoveCallback(double xPos, double yPos) {
if (keyboardSystem != nullptr) {
keyboardSystem->mouseCallback(xPos, yPos);
}
}
void GameView::mouseButtonCallback(MouseButton button, InputAction action, KeyModifierFlags modifier) {
keyboardSystem->mouseButtonCallback(button, action, modifier);
if (keyboardSystem != nullptr) {
keyboardSystem->mouseButtonCallback(button, action, modifier);
}
}
void GameView::scrollCallback(double xScroll, double yScroll) { keyboardSystem->scrollCallback(xScroll, yScroll); }
void GameView::scrollCallback(double xPos, double yPos, double xScroll, double yScroll) {
// The input sink has no cursor-position concept; it only consumes the deltas.
if (keyboardSystem != nullptr) {
keyboardSystem->scrollCallback(xScroll, yScroll);
}
}
void GameView::fileCallback(int, const char**) {}
+4 -5
View File
@@ -2,6 +2,7 @@
#include "Scene/Scene.h"
#include "System/KeyboardInput.h"
#include "Window/View.h"
#include "Window/Application.h"
#ifdef WIN32
#include "Platform/Windows/GameInterface.h" // TODO
@@ -12,7 +13,7 @@
namespace Seele {
class GameView : public View {
public:
GameView(Gfx::PGraphics graphics, PWindow window, const ViewportCreateInfo& createInfo, std::filesystem::path dllPath);
GameView(Gfx::PGraphics graphics, PWindow window, PScene scene, const ViewportCreateInfo& createInfo);
virtual ~GameView();
virtual void beginUpdate() override;
virtual void update() override;
@@ -26,19 +27,17 @@ class GameView : public View {
protected:
virtual void applyArea(URect rect) override;
Gfx::PGraphics graphics;
OScene scene;
GameInterface gameInterface;
PScene scene;
RenderGraph renderGraph;
RenderGraph rayTracingGraph;
OSystemGraph systemGraph;
System::PKeyboardInput keyboardSystem;
float updateTime = 0;
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, KeyModifierFlags modifier) override;
virtual void scrollCallback(double xOffset, double yOffset) override;
virtual void scrollCallback(double xPos, double yPos, double xScroll, double yScroll) override;
virtual void fileCallback(int count, const char** paths) override;
};
DEFINE_REF(GameView)
-3
View File
@@ -8,7 +8,6 @@ View::View(Gfx::PGraphics graphics, PWindow window, const ViewportCreateInfo& vi
: graphics(graphics), createInfo(viewportInfo), owner(window), name(name) {
viewport = graphics->createViewport(owner->getGfxHandle(), viewportInfo);
owner->addView(this);
setFocused();
}
View::~View() {}
@@ -20,6 +19,4 @@ void View::resize(URect area) {
applyArea(area);
}
void View::setFocused() { owner->setFocused(this); }
const std::string& View::getName() { return name; }
+1 -2
View File
@@ -16,7 +16,6 @@ class View {
virtual void prepareRender() = 0;
virtual void render() = 0;
void resize(URect area);
void setFocused();
const std::string& getName();
@@ -31,7 +30,7 @@ class View {
virtual void keyCallback(KeyCode code, InputAction action, uint32_t modifier) = 0;
virtual void mouseMoveCallback(double xPos, double yPos) = 0;
virtual void mouseButtonCallback(MouseButton button, InputAction action, uint32_t modifier) = 0;
virtual void scrollCallback(double xOffset, double yOffset) = 0;
virtual void scrollCallback(double xPos, double yPos, double xScroll, double yScroll) = 0;
virtual void fileCallback(int count, const char** paths) = 0;
friend class Window;
};
+89 -16
View File
@@ -1,11 +1,12 @@
#include "Window.h"
#include "WindowManager.h"
#include "Application.h"
#include <functional>
using namespace Seele;
Window::Window(PWindowManager owner, Gfx::OWindow handle) : owner(owner), gfxHandle(std::move(handle)) {
Window::Window(PApplication owner, Gfx::OWindow handle) : owner(owner), gfxHandle(std::move(handle)) {
gfxHandle->setResizeCallback([this](uint32 w, uint32 h) { onResize(w, h); });
installInputCallbacks();
}
Window::~Window() {}
@@ -28,21 +29,93 @@ void Window::render() {
Gfx::PWindow Window::getGfxHandle() { return gfxHandle; }
void Window::setFocused(PView view) {
auto keyFunction = std::bind(&View::keyCallback, view.getHandle(), std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
auto mouseMoveFunction = std::bind(&View::mouseMoveCallback, view.getHandle(), std::placeholders::_1, std::placeholders::_2);
auto mouseButtonFunction =
std::bind(&View::mouseButtonCallback, view.getHandle(), std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
auto scrollFunction = std::bind(&View::scrollCallback, view.getHandle(), std::placeholders::_1, std::placeholders::_2);
auto fileFunction = std::bind(&View::fileCallback, view.getHandle(), std::placeholders::_1, std::placeholders::_2);
gfxHandle->setKeyCallback(keyFunction);
gfxHandle->setMouseMoveCallback(mouseMoveFunction);
gfxHandle->setMouseButtonCallback(mouseButtonFunction);
gfxHandle->setScrollCallback(scrollFunction);
gfxHandle->setFileCallback(fileFunction);
gfxHandle->setCloseCallback([this]() {
owner->notifyWindowClosed(this);
// The one-shot input dispatchers. Bound ONCE in the ctor (not per focus change), so the
// GLFW layer always talks to a stable `Window::on*` that routes per-event. This is the
// replacement for the old setFocused rebind, which silently made the last-constructed view
// the sole input target.
void Window::installInputCallbacks() {
gfxHandle->setKeyCallback([this](KeyCode code, InputAction action, KeyModifierFlags modifier) { onKeyPress(code, action, modifier); });
gfxHandle->setMouseMoveCallback([this](double x, double y) { onMouseMove(x, y); });
gfxHandle->setMouseButtonCallback([this](MouseButton button, InputAction action, KeyModifierFlags modifier) { onMouseButton(button, action, modifier); });
gfxHandle->setScrollCallback([this](double x, double y, double xScroll, double yScroll) { onScroll(x, y, xScroll, yScroll); });
gfxHandle->setFileCallback([this](int count, const char** paths) {
// File drops have no cursor-position meaning for per-view routing; deliver to the
// keyboard-focus owner (or the first view as a fallback) -- a drop is a user action
// aimed at "the app", not a specific pane.
if (keyboardFocus != nullptr) {
keyboardFocus->fileCallback(count, paths);
} else if (views.size() > 0) {
views[0]->fileCallback(count, paths);
}
});
gfxHandle->setCloseCallback([this]() {
owner->notifyWindowClosed(this);
});
}
// SPATIAL pointer routing. `x`/`y` are window/client coords (GLFW gives these). We hit-test
// every view's on-screen rect and deliver to the view(s) under the cursor, in view-local
// coords (window pos minus the rect origin). The layout is a flat, non-overlapping column
// split (see onResize), so at most ONE view can be under the cursor -- but we loop anyway so
// a future overlapping layout (dockable panes) keeps working without changes here.
//
// Coordinate offset is the crux: GLFW hands us window-absolute coords, but views (the UI
// system, the 3D camera rig) consume VIEW-LOCAL coords. The old code passed raw window
// coords, which only "worked" for the left-anchored (x=0) inspector. The offset below is
// what makes per-view input correct for ANY rect origin.
void Window::onMouseMove(double x, double y) {
lastPointerX = x;
lastPointerY = y;
for (auto& view : views) {
URect rect = view->viewport->getRenderArea();
if (rect.contains(x, y)) {
view->mouseMoveCallback(x - static_cast<double>(rect.offset.x), y - static_cast<double>(rect.offset.y));
}
}
}
void Window::onMouseButton(MouseButton button, InputAction action, KeyModifierFlags modifier) {
// GLFW gives us the button+action but NOT the cursor position, so we hit-test using the
// last known pointer location (kept in sync by onMouseMove). For a column layout the
// pointer is effectively static between a move and the next press, so this is accurate.
lastClickedView = nullptr;
for (auto& view : views) {
URect rect = view->viewport->getRenderArea();
if (rect.contains(lastPointerX, lastPointerY)) {
lastClickedView = view;
view->mouseButtonCallback(button, action, modifier);
}
}
// CLICK-TO-FOCUS: a press (not a hover, not a release) inside a view gives that view
// the keyboard. This is the only sane keyboard-ownership rule -- the keyboard has no
// position, so focus must be an explicit user gesture, never construction order.
if (action == InputAction::PRESS && lastClickedView != nullptr) {
keyboardFocus = lastClickedView;
}
}
void Window::onScroll(double x, double y, double xScroll, double yScroll) {
// The scroll callback now carries the cursor position (x, y) — see the Gfx::Window
// signature. Scroll is a spatial event, so route it exactly like a mouse move.
for (auto& view : views) {
URect rect = view->viewport->getRenderArea();
if (rect.contains(x, y)) {
view->scrollCallback(x - static_cast<double>(rect.offset.x), y - static_cast<double>(rect.offset.y), xScroll, yScroll);
}
}
}
// FOCUS-based keyboard routing: a key event has no position, so it goes to exactly one
// owner (keyboardFocus) -- the view last clicked into. With no focus, the event is dropped
// (better than sending it to an arbitrary view).
void Window::onKeyPress(KeyCode code, InputAction action, KeyModifierFlags modifier) {
if (keyboardFocus != nullptr) {
keyboardFocus->keyCallback(code, action, static_cast<uint32_t>(modifier));
}
}
void Window::setKeyboardFocus(PView view) {
keyboardFocus = view;
}
void Window::onResize(uint32 width, uint32 height) {
+36 -4
View File
@@ -3,24 +3,56 @@
#include "View.h"
namespace Seele {
DECLARE_REF(WindowManager)
DECLARE_REF(Application)
// The logical window, with the graphics proxy
class Window {
public:
Window(PWindowManager owner, Gfx::OWindow handle);
Window(PApplication owner, Gfx::OWindow handle);
~Window();
void show() { gfxHandle->show(); }
void addView(PView view);
void pollInputs();
void render();
Gfx::PWindow getGfxHandle();
void setFocused(PView view);
// The Application that owns this window (non-owning). Views use this to reach
// the world's services (e.g. the input sink) without a global lookup.
PApplication app() const { return owner; }
void setKeyboardFocus(PView view);
void onResize(uint32 width, uint32 height);
constexpr bool isPaused() const { return gfxHandle->isPaused(); }
constexpr bool shouldClose() const { return gfxHandle->shouldClose(); }
protected:
PWindowManager owner;
// Install the one-shot per-event dispatchers. `gfxHandle->pollInput()` fires the
// GLFW callbacks into these; they route each event to the right view(s). Bound ONCE
// here (not per setFocused) so the "last view wins" rebind bug is gone for good.
void installInputCallbacks();
// Pointer (mouse/scroll) routing: SPATIAL. The position is window/client coords; we
// hit-test every view's on-screen rect (already valid via onResize) and deliver to the
// view(s) under the cursor, in VIEW-LOCAL coords (window pos minus the rect origin).
// This is what makes the game viewport and the inspector independently usable.
void onMouseMove(double x, double y);
void onMouseButton(MouseButton button, InputAction action, KeyModifierFlags modifier);
void onScroll(double x, double y, double xScroll, double yScroll);
// Keyboard routing: FOCUS. A key event has no position, so it goes to exactly one
// owner -- keyboardFocus -- which is set by clicking into a view (see onMouseButton).
void onKeyPress(KeyCode code, InputAction action, KeyModifierFlags modifier);
// The window's keyboard focus owner (click-to-focus). Null until the user clicks a
// view; a key event with no focus is dropped.
PView keyboardFocus = nullptr;
// GLFW's mouse-button callback does not carry a cursor position, so pointer hit-testing
// for press/release uses the last known pointer location (kept fresh by onMouseMove).
// For a static column layout the pointer does not move between a move event and the
// following press, so this is accurate in practice.
double lastPointerX = 0.0;
double lastPointerY = 0.0;
PView lastClickedView = nullptr;
PApplication owner;
Array<PView> views;
Gfx::OWindow gfxHandle;
};
-25
View File
@@ -1,25 +0,0 @@
#include "WindowManager.h"
#include "Graphics/Graphics.h"
using namespace Seele;
WindowManager::WindowManager() {}
WindowManager::~WindowManager() {}
OWindow WindowManager::addWindow(Gfx::PGraphics graphics, const WindowCreateInfo& createInfo) {
OWindow window = new Window(this, graphics->createWindow(createInfo));
windows.add(window);
return window;
}
void WindowManager::render() {
for (auto& window : windows) {
window->pollInputs();
if (window->isPaused())
continue;
window->render();
}
}
void WindowManager::notifyWindowClosed(PWindow window) { windows.remove(window); }
-20
View File
@@ -1,20 +0,0 @@
#pragma once
#include "Containers/Array.h"
#include "Window.h"
namespace Seele {
DECLARE_NAME_REF(Gfx, Graphics)
class WindowManager {
public:
WindowManager();
~WindowManager();
OWindow addWindow(Gfx::PGraphics graphics, const WindowCreateInfo& createInfo);
void render();
void notifyWindowClosed(PWindow window);
bool isActive() const { return getGlobals().running && windows.size(); }
private:
Array<PWindow> windows;
};
DEFINE_REF(WindowManager)
} // namespace Seele