Compare commits
9
Commits
ca69fc7dbc
...
d3ed573405
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d3ed573405 | ||
|
|
3317705d9c | ||
|
|
ff2e4e642d | ||
|
|
6a6294c67d | ||
|
|
bcb9a7b148 | ||
|
|
1bc73b6d2f | ||
|
|
22a90fe07c | ||
|
|
17dc1e4d88 | ||
|
|
332c47fc9d |
No files matched your search
@@ -346,3 +346,5 @@ ASALocalRun/
|
||||
# BeatPulse healthcheck temp database
|
||||
healthchecksdb
|
||||
.DS_Store
|
||||
|
||||
**/generated/**
|
||||
@@ -0,0 +1,227 @@
|
||||
# AGENTS.md — Seele Engine
|
||||
|
||||
Guidance for AI agents (and humans) working in this repository. Read this first, then
|
||||
`README.md` and `OPTIMIZATIONS.md` for deeper design detail.
|
||||
|
||||
## What this is
|
||||
|
||||
**Seele** is a general-purpose 3D game/render engine. C++ (C++23), **Vulkan** as the primary
|
||||
graphics backend (a Metal backend exists; the `Graphics` API is designed so other backends
|
||||
like OpenGL could be added). It is a proof-of-concept engine but is built to be extensible.
|
||||
|
||||
- **Engine** — shared library, the core (`src/Engine`).
|
||||
- **Editor** — executable, the content/inspector tool (`src/Editor`).
|
||||
- **AssetViewer** — executable (`src/AssetViewer`).
|
||||
- **Benchmark** — executable (`src/Benchmark`).
|
||||
- **SeeleUnitTests** — GTest executable (`tests/`).
|
||||
|
||||
> Note: an earlier design used a coroutine-based Job system (`Job`/`MainJob`/`Event` and
|
||||
> templated `RenderPass<T>`). It was dropped (MSVC memory-leak issues + forcing everything
|
||||
> async). The shipped job system is a plain `ThreadPool` (`src/Engine/ThreadPool.{h,cpp}`,
|
||||
> `getThreadPool()`). Do not assume the coroutine API is present.
|
||||
|
||||
## Repo layout
|
||||
|
||||
```
|
||||
src/
|
||||
Engine/ # the engine shared library (one CMake target: Engine)
|
||||
Graphics/ # graphics API abstraction + Vulkan + Metal + RenderPass impls
|
||||
Vulkan/ # Vulkan backend (Graphics.h is the abstract base in Graphics/)
|
||||
Metal/ # Metal backend
|
||||
RenderPass/ # concrete render passes (BasePass, DepthCulling, LightCulling,
|
||||
# Shadow, RayTracing, ToneMapping, UI, Visibility, Fluid, ...)
|
||||
CBT/ # command buffer tracking
|
||||
Containers/ # custom containers (Array, StaticArray, Map, List, Set, Tree, ...)
|
||||
Math/ # math (glm-backed typedefs: Vector, Vector3→Vector, Matrix4, etc.)
|
||||
Asset/ # asset registry, loaders (mesh, texture, font, material, env, SVG, level)
|
||||
Material/ # material / BRDF system (Slang-generated)
|
||||
Actor/ # Entity + concrete actors (mesh, light, camera) — EnTT-based
|
||||
Component/ # components (Transform, Mesh, Camera, lights, colliders, ...)
|
||||
Scene/ # scene, event manager, light environment
|
||||
System/ # per-frame systems: SystemGraph, ComponentSystem, updaters (mesh,
|
||||
# light, fluid, camera), executor
|
||||
Physics/ # physics: BVH, collision system, physics system
|
||||
Serialization/ # ArchiveBuffer + Serialization.h
|
||||
UI/ # custom UI framework (Element, FlexLayout, Style)
|
||||
Window/ # WindowManager, View (GameView, etc.)
|
||||
Platform/ # per-OS: Linux/, Mac/, Windows/ (GameInterface)
|
||||
Editor/ # Editor executable (main.cpp, Asset/ importers, Window/ views)
|
||||
AssetViewer/ # AssetViewer executable
|
||||
Benchmark/ # Benchmark executable
|
||||
tests/
|
||||
Engine/ # GTest suite, mirrored under Engine/<Subsystem>/
|
||||
res/
|
||||
shaders/ # Slang shader sources (.slang)
|
||||
fonts/ textures/ cmake/
|
||||
cmake/ # SuperBuild.cmake, EngineConfig.cmake.in
|
||||
external/ # submodules: vcpkg, CRCpp, metal-cpp (do not edit)
|
||||
```
|
||||
|
||||
## Building
|
||||
|
||||
Standard CMake, **C++23**. Deps come from **vcpkg** (manifest mode, `vcpkg.json`) plus the
|
||||
`external/` submodules. Prereq on Linux: the X11 dev libs for GLFW
|
||||
(`libx11-dev libxrandr-dev libxinerama-dev libxcursor-dev libxi-dev`).
|
||||
|
||||
```bash
|
||||
# one-time: pull dependencies (vcpkg submodule + everything)
|
||||
git submodule update --init --recursive
|
||||
|
||||
# configure + build (use a preset)
|
||||
cmake --preset debug
|
||||
cmake --build --preset debug --config Debug
|
||||
```
|
||||
|
||||
Presets (`CMakePresets.json`): `debug`, `release`, `debug-asan`, `release-asan`,
|
||||
`debug-mac` (Xcode). Binary dir is the in-tree `build/` (gitignored). The vcpkg toolchain
|
||||
is hard-wired in the top-level `CMakeLists.txt`
|
||||
(`CMAKE_TOOLCHAIN_FILE=${EXTERNAL_ROOT}/vcpkg/scripts/buildsystems/vcpkg.cmake`).
|
||||
|
||||
- The engine is a **SHARED** lib (`add_library(Engine SHARED)`) — all four binaries link it.
|
||||
- `Editor` is compiled with `EDITOR=1` and includes `src/Editor` + the Stb includes.
|
||||
- On non-Apple, the `slang-glslang` **plugin** is a MODULE library and is **copied** next to
|
||||
the `Engine` binary at post-build (do not try to link it). On Windows the runtime DLLs are
|
||||
likewise copied next to `Editor`.
|
||||
- Windows defines `USE_EXTENSIONS` and adds `WIN32`; MSVC builds with `/W4`, GCC/Clang with
|
||||
`-Wall -Wextra -Wno-error -pedantic`. Warnings are **not** fatal, but keep the build clean.
|
||||
- There is **no CI** and no `test` preset. Run tests manually (below).
|
||||
|
||||
`OPTIMIZATIONS.md` is a scratch list of optimization ideas (LTO, PGO, attributes, copy-avoidance
|
||||
guidelines) — it is reference material, not a build requirement.
|
||||
|
||||
## Testing
|
||||
|
||||
GTest. `tests/` builds a single `SeeleUnitTests` binary and registers with CTest via
|
||||
`gtest_discover_tests`. Tests are organized to mirror the engine tree
|
||||
(`tests/Engine/Containers/Array.cpp`, `tests/Engine/Math/Vector.cpp`,
|
||||
`tests/Engine/System/ComponentSystem.cpp`, `tests/Engine/Serialization/ArchiveBuffer.cpp`,
|
||||
`tests/Engine/ThreadPool.cpp`, `tests/Engine/UI/...`, `tests/Engine/Graphics/...`).
|
||||
|
||||
- Every test file includes `tests/Engine/EngineTest.h` (which pulls in `<gtest/gtest.h>` +
|
||||
`MinimalEngine.h` + `using namespace Seele;`).
|
||||
- Add a new test: create `tests/Engine/<Subsystem>/Foo.cpp` and **add it to that
|
||||
subdirectory's `tests/Engine/<Subsystem>/CMakeLists.txt`** (the subdirs `add_subdirectory`
|
||||
into `tests/Engine/CMakeLists.txt`). Forgetting the CMake registration is the #1 way a new
|
||||
test silently never compiles or runs.
|
||||
- Run: `cd build && ctest --test-dir . -R <TestNamePattern> --output-on-failure` (or run the
|
||||
`SeeleUnitTests` binary directly). Use a `debug`/`debug-asan` preset for test development.
|
||||
|
||||
## Core architecture (read before touching Graphics/RenderPass)
|
||||
|
||||
The invariants that are **actual in the code**:
|
||||
|
||||
- **`Gfx::Graphics`** (`src/Engine/Graphics/Graphics.h`) is the abstract backend interface.
|
||||
`Vulkan::Graphics` (`Graphics/Vulkan/Graphics.h`) and `Metal::Graphics` (`Graphics/Metal/`)
|
||||
implement it. All GPU work goes through this interface; render passes must not touch
|
||||
Vulkan or Metal handles directly. `ENABLE_VALIDATION` is defined in `Graphics.h`.
|
||||
- **Window → View → RenderPass.** A `WindowManager` owns `Graphics` + `Window`s; each
|
||||
`Window` holds `View`s (a viewport; e.g. `Editor::InspectorView`, `GameView`). Rendering of
|
||||
all viewports in a window is synchronized, but per-`View` logic runs on its own thread.
|
||||
The thread handshake is the lock-protected `commitUpdate()` (logic side) → `prepareRender()`
|
||||
(render side); a `View` pushes a concrete `RenderPassDataType` packet to each pass it uses.
|
||||
- **Render passes** are plain (non-template) `RenderPass` subclasses in
|
||||
`src/Engine/Graphics/RenderPass/` (`beginFrame`/`render`/`endFrame`/`publishOutputs`/
|
||||
`createRenderPass`). All passes share one `PRenderGraphResources` object; a pass
|
||||
**publishes** the GPU outputs it produces (`publishOutputs()`) and other passes **consume**
|
||||
them by name — so pass *init order does not matter*. If you add a pass that produces or
|
||||
consumes shared resources, you must wire both the publish and the consume.
|
||||
- **Descriptor sets** for pass-shared data (camera, lights, view params) are managed per
|
||||
render pass; because Vulkan pipeline layouts cannot have empty set indices, each pass has a
|
||||
static `modifyRenderPassMacros` that `#define`s the correct descriptor-set indices for shared
|
||||
layouts. Keep that in sync if you add/remove descriptor sets.
|
||||
- **`getGlobals()`** (`MinimalEngine.h`) is the global feature/flags struct (e.g.
|
||||
`useRayTracing`, `useDepthCulling`, `running`, …). It controls which passes run. Treat it as
|
||||
global mutable state — do not add per-frame logic to it.
|
||||
|
||||
### Entities / scenes / systems (EnTT)
|
||||
|
||||
- `Actor`/`Entity` (`src/Engine/Actor/`) wrap an **EnTT** entity ID + a `PScene`. Components
|
||||
live in `src/Engine/Component/`; attach via `scene->attachComponent<C>(...)` /
|
||||
`entity.accessComponent<C>()`.
|
||||
- Per-frame update is driven by `SystemGraph` / `ComponentSystem` in `src/Engine/System/`.
|
||||
A `Component` can declare dependencies on other components (the `Dependencies` /
|
||||
`has_dependencies` / `REQUIRE_COMPONENT` mechanism in `Component.h`). The concrete updaters
|
||||
(`MeshUpdater`, `LightGather`, `FluidUpdater`, `CameraUpdater`, …) are the per-frame work
|
||||
and must be registered in the system graph.
|
||||
|
||||
### Materials (Slang-generated)
|
||||
|
||||
- A material is a JSON doc: a `profile` (BRDF, e.g. `BlinnPhong`), typed `params` (HLSL
|
||||
types + defaults), and a `code` section with one string-array per BRDF output. On load,
|
||||
the engine generates the descriptor layout and compiles a Slang `IMaterial` type (see
|
||||
`src/Engine/Material/`, `Graphics/slang-compile.cpp`).
|
||||
Shared Slang lives in `res/shaders/*.slang`; per-material pipeline variants are generated
|
||||
from a render pass's base `.slang` via `#define`s. **If you change the set of BRDF outputs
|
||||
or a shared Slang input, the generated material code and the `prepare()`/`get*` accessors
|
||||
must stay consistent** — they are produced from the JSON profile, not hand-written.
|
||||
|
||||
## Code conventions (match the surrounding code)
|
||||
|
||||
- **C++23.** The build sets `CMAKE_CXX_STANDARD 23`; C++20/23 features are in active use
|
||||
(concepts, `std::span`, designated initializers, `<=>` spaceship, `[[unlikely]]`, etc.).
|
||||
- **Formatting: `.clang-format`** — `BasedOnStyle: LLVM`, `IndentWidth: 4`, `ColumnLimit: 140`,
|
||||
left-aligned pointers (`P*`, not `P *`), 2-space class-member indent in practice (see
|
||||
`Graphics.h`/`RenderPass.h`). Headers use `#pragma once`. Keep to it; do not reformat
|
||||
untouched code.
|
||||
- **Namespaces.** Engine code lives in `namespace Seele`; the graphics backend in
|
||||
`namespace Seele::Gfx` (Vulkan impl in `Seele::Vulkan`, Metal in `Seele::Metal`).
|
||||
- **Types.**
|
||||
- Fixed-width scalars come from `EngineTypes.h`: `uint8/16/32/64`, `int8/16/32/64`.
|
||||
Prefer these over `std::uint32_t` for consistency with the codebase.
|
||||
- Math types are **glm typedefs** in `Math/Math.h`/`Vector.h`/`Matrix.h`: `Vector` is
|
||||
`glm::vec3`, `Vector2`/`Vector4`/`UVector`(`uvec3`)/`IVector`/`Quaternion`
|
||||
(`glm::quat`)/`Matrix4`, etc. Use these, not raw `glm::vec*`. `Math.h` re-exports glm.
|
||||
- `Matrix` types: `Matrix4` etc. — `Matrix.h`.
|
||||
- **Smart pointers / ownership** (the most important idiom — defined in `MinimalEngine.h`):
|
||||
- `DEFINE_REF(ClassName)` at the end of a class's header typedefs `P<Name>`, `UP<Name>`,
|
||||
`O<Name>`. `DECLARE_REF(ClassName)` is the same but only forward-declares (for
|
||||
headers that need the typedefs but not the class). `DECLARE_NAME_REF(nmsp, Name)`
|
||||
is the namespaced variant (used heavily in `Gfx`, e.g. `DECLARE_NAME_REF(Gfx, Viewport)`).
|
||||
- **`P<T>`** = `RefPtr<T>` — a *non-owning* strong reference (shared, `dynamic_cast`
|
||||
`cast()`, `<=>`-comparable). Use as the default "have a reference" type (members,
|
||||
parameters, return of non-owning lookups).
|
||||
- **`O<T>`** = `OwningPtr<T>` — the *owning* pointer (move-only, deletes on scope exit,
|
||||
implicitly converts to `P<T>`). Use it for the **result of factories/creators** —
|
||||
e.g. `Graphics::createWindow(...) -> OWindow`, `createTexture2D(...) -> OTexture2D`.
|
||||
A factory returns `O<T>`; anything storing it should keep it as `P<T>` (or pass the
|
||||
`O<T>` into a `P<T>` conversion).
|
||||
- **`UP<T>`** = `UniquePtr<T>` — move-only, deletes on scope exit.
|
||||
- You will rarely `new` explicitly: `P<Foo> p = new Foo();` is the pattern used in
|
||||
`main.cpp` / tests because `RefPtr` has a raw-pointer constructor. For factories,
|
||||
return `O<T>`.
|
||||
- Do **not** introduce `std::shared_ptr`/`std::unique_ptr` for engine objects — use the
|
||||
`P/O/UP` types.
|
||||
- **Containers:** use the engine's own in `Containers/` (`Array<T>` = heap `std::vector`-like
|
||||
with `add`/`resize`/`remove`/`removeAt`/`find`/`clear`; `StaticArray<T,N>`; `Map`, `List`,
|
||||
`Set`, `Tree`, `Pair`). There is a `MemoryResource` (pool) too. Prefer these over
|
||||
`std::vector`/`std::map` for engine data (they are what serialization etc. integrate with).
|
||||
- **Errors / asserts:** `assert()` from `<assert.h>` (see `MinimalEngine.h`). `fmt`
|
||||
(`fmt::format`) is used for string building (linked via vcpkg); `nlohmann_json` for JSON
|
||||
(see `Serialization.h`). There is no exception-based error API to follow — match local style.
|
||||
- **Per-subsystem `CMakeLists.txt`** only calls `target_sources(Engine PRIVATE ... .cpp)` and
|
||||
`target_sources(Engine PUBLIC FILE_SET HEADERS FILES ... .h)`. When you add a `.cpp`,
|
||||
add it to the `PRIVATE` list of the **nearest** `CMakeLists.txt`; when you add a public
|
||||
header, add it to `FILE_SET HEADERS` too (or it won't install/export and other targets
|
||||
can't find it).
|
||||
|
||||
## Workflow & gotchas
|
||||
|
||||
- **No CI, no `test` preset.** Nothing runs the test suite for you. Configure a `debug`/
|
||||
`debug-asan` preset, build, then `cd build && ctest --test-dir . --output-on-failure`.
|
||||
- **`src/Editor/main.cpp` hard-codes `/home/dynamitos/...` paths** (lines 26–27). The Editor
|
||||
will not run on any other machine without editing those two lines to your checkout path.
|
||||
The `if (true)` branch is the live one; the else-branch (cmake `ExportProject.cmake`
|
||||
export flow) is dead code that only worked with the original author's paths.
|
||||
- **Coroutines are not in the code.** An earlier design described a coroutine `Job`/`MainJob`
|
||||
/`Event` system and templated `RenderPass<T>`; none of it is implemented (MSVC memory leaks
|
||||
+ forcing everything async). The real job system is `ThreadPool`
|
||||
(`src/Engine/ThreadPool.{h,cpp}`, `getThreadPool()`).
|
||||
- **Render passes must not touch backend handles.** All GPU work goes through `Gfx::Graphics`.
|
||||
Adding a pass that produces or consumes a shared `RenderGraphResources` resource requires
|
||||
wiring **both** the `publishOutputs()` side and the consume-by-name side, and keeping the
|
||||
`modifyRenderPassMacros` descriptor-set index `#define`s in sync.
|
||||
- **New `.cpp`/`.h` files must be registered in CMake** — both the nearest `CMakeLists.txt`
|
||||
(`target_sources ... PRIVATE` for `.cpp`, `FILE_SET HEADERS` for public headers) and, for
|
||||
tests, the test subdirectory's `CMakeLists.txt`. An unregistered file silently never
|
||||
compiles.
|
||||
|
||||
+1
-4
@@ -133,16 +133,13 @@ if(APPLE)
|
||||
endif()
|
||||
|
||||
add_subdirectory(src/)
|
||||
#add_subdirectory(tests/)
|
||||
add_subdirectory(tests/)
|
||||
|
||||
if(WIN32)
|
||||
add_custom_command(TARGET Engine POST_BUILD
|
||||
COMMAND ${CMAKE_COMMAND} -E copy_if_different $<TARGET_RUNTIME_DLLS:Engine> $<TARGET_FILE_DIR:Editor>)
|
||||
endif()
|
||||
|
||||
add_custom_command(TARGET Engine POST_BUILD
|
||||
COMMAND ${CMAKE_COMMAND} -E copy_directory ${CMAKE_CURRENT_SOURCE_DIR}/res $<TARGET_FILE_DIR:Engine>)
|
||||
|
||||
install(
|
||||
TARGETS
|
||||
AssetViewer
|
||||
|
||||
-324
@@ -1,324 +0,0 @@
|
||||
# Seele Engine
|
||||
|
||||
Seele is a Proof-of-Concept 3D render engine using Vulkan as it's primary graphics API, but other APIs could also be implemented. Due to this, a lot of terminology will be Vulkan-related, but it can be translated to other APIs.
|
||||
It is designed to support multithreading for more recent APIs, like DX12 or Vulkan, while still providing an interface that could be implemented by an
|
||||
API that doesn't support it, like OpenGL. These APIs would suffer a significant performance loss, but would still work correctly.
|
||||
|
||||
## Custom containers and other utilities
|
||||
|
||||
Some of the basic containers are reimplemented, mostly not for any particular feature, but because that makes them more customizable and extendable for future uses and
|
||||
performance optimizations, like serialization for example. Due to some of them occuring in the code samples later, they will be quickly mentioned here.
|
||||
|
||||
- `Array`: A heap-array backed dynamically resizable container, like `std::vector`
|
||||
- `StaticArray`: A static-array backed non-resizable container, like `std::array`
|
||||
- `Map`: A key-value splay-tree associative container, like `std::map`
|
||||
- `UniquePtr`: A smart pointer claiming ownership of an object, like `std::unique_pointer`
|
||||
- `RefPtr`: A reference counting smart pointer, similar to `std::shared_pointer`, with a few differences:
|
||||
- global pointer-based reference counting
|
||||
- this means a `RefPtr` can be constructed from a raw pointer and will retain its reference count correctly
|
||||
- for example if you construct `RefPtr<HelloWorld> ptr = new HelloWorld();`, and in the constructor of HelloWorld create `RefPtr<HelloWorld ptr = this;`, both would have a reference count of 2.
|
||||
- `DEFINE_REF`/`DECLARE_REF`: Macros to automatically typedef different types of smart pointer for convenience, for example DEFINE_REF(HelloWorld) would typedef:
|
||||
- `PHelloWorld`, the same as `RefPtr<HelloWorld>`
|
||||
- `UPHelloWorld`, the same as `UniquePtr<HelloWorld>`
|
||||
|
||||
## Basic Architecture
|
||||
|
||||
The first piece to the puzzle is the `WindowManager`, a container that manages a `Graphics` object, which is the interface for the graphics API, as well as all `Window`s that are active. Each `Window` represents, well, a window, and contains several `View`s. A `View` represents a viewport in the window. For an analogy to Unity, a `View` would be the Inspector, the Asset Browser or the Hierarchy.
|
||||
|
||||
Since all viewports in a window are backed by the same image and can only be presented together, the rendering for all viewports is synchronized, while the logic for each `View` runs in a separate thread.
|
||||
|
||||
The interactions between logic and rendering are modelled through two parts of the interface: `beginUpdate()`, `update()` and `commitUpdate()` for the logic side, and `prepareRender()` and `render()` for the rendering side. The views use a set of concrete `RenderPass` objects to render a new frame, depending on what kind of content should be displayed. In order to draw a frame, a `RenderPass` needs an "update packet" in form of a struct, but the contents of that packet is dependent on the render pass itself. A depth prepass for example might only need a mesh list, while a light culling pass needs the dynamic lights or a base pass might need both.
|
||||
|
||||
In order to avoid inheritance and casting for these update packets, each `RenderPass` needs to be updated individually by the view that uses it, so the thread interactions are not enforced in the `View` base class, instead `commitUpdate()` is called from a locked context from the logic thread, so that the view can copy the packet to a shared storage, while `prepareRender()` is locked and called from the render thread, so that it can be passed to the render passes.
|
||||
|
||||
## RenderPass
|
||||
|
||||
To better illustrate how render passes work, here is part of the `RenderPass` base class:
|
||||
|
||||
```cpp
|
||||
template<typename RenderPassDataType>
|
||||
class RenderPass
|
||||
{
|
||||
public:
|
||||
RenderPass(Gfx::PGraphics graphics, Gfx::PViewport viewport)
|
||||
: graphics(graphics)
|
||||
, viewport(viewport)
|
||||
{}
|
||||
virtual ~RenderPass()
|
||||
{}
|
||||
void updateViewFrame(RenderPassDataType viewFrame) {
|
||||
passData = std::move(viewFrame);
|
||||
}
|
||||
virtual void beginFrame() = 0;
|
||||
virtual void render() = 0;
|
||||
virtual void endFrame() = 0;
|
||||
virtual void publishOutputs() = 0;
|
||||
virtual void createRenderPass() = 0;
|
||||
//....
|
||||
private:
|
||||
PRenderGraphResources resources;
|
||||
RenderPassDataType passData;
|
||||
Gfx::PGraphics graphics;
|
||||
//....
|
||||
};
|
||||
```
|
||||
|
||||
All render passes in a `View` share a `RenderGraphResources` object, which is used to share outputs between the different passes. During initialization, every render pass "publishes" any outputs that it produces in `publishOutputs()`, so that they can be consumed by other render passes. For example the output of a depth prepass is the depth buffer, for a light culling pass it is the culled light indices. Next the render passes get any resources that they require and have been registered by other passes to create the render pass in `createRenderPass()`. This is split into two parts, so that the order of initialization of different renderpasses doesn't matter, as all outputs are available before any are requested.
|
||||
|
||||
## Materials
|
||||
|
||||
The material system fully embraced a Vulkan-style descriptor system, abstracted by the `Graphics` API. A material is a file stored on disk in form of a JSON document, here is an example:
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "Placeholder",
|
||||
"profile": "BlinnPhong",
|
||||
"params": {
|
||||
"diffuseTexture": {
|
||||
"type": "Texture2D"
|
||||
},
|
||||
"specularTexture": {
|
||||
"type": "Texture2D"
|
||||
},
|
||||
"normalTexture": {
|
||||
"type": "Texture2D"
|
||||
},
|
||||
"uvScale": {
|
||||
"type": "float",
|
||||
"default": "0.0f"
|
||||
},
|
||||
"metallic": {
|
||||
"type": "float",
|
||||
"default": "0.0f"
|
||||
},
|
||||
"roughness": {
|
||||
"type": "float",
|
||||
"default": "0.5f"
|
||||
},
|
||||
"sheen": {
|
||||
"type": "float",
|
||||
"default": "0.0f"
|
||||
},
|
||||
"worldOffset": {
|
||||
"type": "float3",
|
||||
"default": "float3(0, 0, 0)"
|
||||
},
|
||||
"textureSampler": {
|
||||
"type": "SamplerState"
|
||||
}
|
||||
},
|
||||
"code": {
|
||||
"baseColor": [
|
||||
"return diffuseTexture.Sample(textureSampler, input.texCoords[0] * uvScale).xyz;"
|
||||
],
|
||||
"metallic": [
|
||||
"return metallic;"
|
||||
],
|
||||
"normal": [
|
||||
"return normalTexture.Sample(textureSampler, input.texCoords[0] * uvScale).xyz;"
|
||||
],
|
||||
"specular": [
|
||||
"return specularTexture.Sample(textureSampler, input.texCoords[0] * uvScale).x;"
|
||||
],
|
||||
"roughness": [
|
||||
"return roughness;"
|
||||
],
|
||||
"sheen": [
|
||||
"return sheen;"
|
||||
],
|
||||
"worldOffset": [
|
||||
"return worldOffset;"
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The document starts with the asset `name`, followed by the `profile`, which tells the engine which BRDF function it uses, and thus what outputs it can expect from the material. Next are the parameters, which are the inputs that need to get passed to the shader later. The `type` field must be a valid HLSL datatype and `default` a valid value for that datatype. In the `code` section, there must be an entry for every output required by the `profile`, each of which is a string array for each line of shader code to compute that value and ends by `return`ing that value.
|
||||
|
||||
### MaterialAsset
|
||||
|
||||
A `MaterialAsset` represents such a JSON document on disk, as well as the GPU resources needed to render a mesh with the material. When loading the file, the a descriptor layout is generated to fit the `slang` code that will be generated later by consolidating the plain variables (`float`, `double`, etc.) into a single uniform buffer. The parameters are stored in an array of `ShaderParameter`s, which contain the current parameter value, like texture references or plain data, as well as information on how to update the GPU resources.
|
||||
|
||||
At the same time a slang-compilable shader is generated, which matches the parameters provided by the descriptor layout. The generated shader is a `Material`, which is an interface that "prepares" a BRDF by initializing its input values, similar to official slang example. How each input value is calculated is read from the `code` section of the JSON document, and wrapped in an accessor to allow for multi line calculations.
|
||||
|
||||
Here is the material generated from the above JSON example:
|
||||
|
||||
```cpp
|
||||
import VERTEX_INPUT_IMPORT;
|
||||
import Material;
|
||||
import MaterialParameter;
|
||||
|
||||
struct Placeholder: IMaterial {
|
||||
layout(offset = 0)float anisotropic;
|
||||
layout(offset = 4)float clearCoat;
|
||||
layout(offset = 8)float clearCoatGloss;
|
||||
Texture2D diffuseTexture;
|
||||
layout(offset = 12)float metallic;
|
||||
Texture2D normalTexture;
|
||||
layout(offset = 16)float roughness;
|
||||
layout(offset = 20)float sheen;
|
||||
layout(offset = 24)float sheenTint;
|
||||
Texture2D specularTexture;
|
||||
layout(offset = 28)float specularTint;
|
||||
layout(offset = 32)float subsurface;
|
||||
SamplerState textureSampler;
|
||||
layout(offset = 36)float uvScale;
|
||||
layout(offset = 40)float3 worldOffset;
|
||||
|
||||
float3 getBaseColor(MaterialFragmentParameter input) {
|
||||
return diffuseTexture.Sample(textureSampler, input.texCoords[0] * uvScale).xyz;;
|
||||
}
|
||||
float getMetallic(MaterialFragmentParameter input) {
|
||||
return 0;;
|
||||
}
|
||||
float3 getNormal(MaterialFragmentParameter input) {
|
||||
return normalTexture.Sample(textureSampler, input.texCoords[0] * uvScale).xyz;;
|
||||
}
|
||||
float getSpecular(MaterialFragmentParameter input) {
|
||||
return specularTexture.Sample(textureSampler, input.texCoords[0] * uvScale).x;;
|
||||
}
|
||||
float getRoughness(MaterialFragmentParameter input) {
|
||||
return roughness;;
|
||||
}
|
||||
float getSheen(MaterialFragmentParameter input) {
|
||||
return sheen;;
|
||||
}
|
||||
float3 getWorldOffset() {
|
||||
return worldOffset;;
|
||||
}
|
||||
typedef BlinnPhong BRDF;
|
||||
BlinnPhong prepare(MaterialFragmentParameter geometry){
|
||||
BlinnPhong result;
|
||||
result.baseColor = getBaseColor(geometry);
|
||||
result.metallic = getMetallic(geometry);
|
||||
result.normal = getNormal(geometry);
|
||||
result.specular = getSpecular(geometry);
|
||||
result.roughness = getRoughness(geometry);
|
||||
result.sheen = getSheen(geometry);
|
||||
return result;
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
### Renderpass interaction
|
||||
|
||||
Each render pass has a "base file" containing the vertex and fragment stages. From that base file a variant is generated for each material that will be used with that render pass using `#define` macros to change the material import, and a `type_param` to update the `ParameterBlock` containing the material itself. Other renderpass dependent data like camera parameter or lights are stored in separate descriptor sets, and to avoid code duplication, they parts that are used by more than one render pass are implemented in separate slang files. But since in Vulkan pipeline layouts cannot have empty indices, the descriptor set indices sometimes need to change. This is done using the static `modifyRenderPassMacros` function in each renderpass to `#define` the correct set indices for each shared descriptor layout.
|
||||
|
||||
## Job System
|
||||
|
||||
The Job System is based on C++20 coroutines, running on a thread pool with 1 main thread and as many worker threads as the native CPU has. This is so that when the main thread needs to block for some thread pool work, the CPU can utilize all its resources. Synchronization is done using `Event`s, which are awaitable wrappers for atomic flags.
|
||||
|
||||
### Creating Jobs
|
||||
|
||||
In order to run a function as a Job, its return type must simply be either `Job` or `MainJob`. Also, any `Job` must contain either a `co_await` or `co_return` statement. As the names suggest, `MainJob`s will always run on the main thread, while `Job`s can run on any thread. Some graphics operations, especially regarding windowing, can only occur on the main thread, which is the reason for the separation. Due to the specification for [coroutines](https://en.cppreference.com/w/cpp/language/coroutines) being incredibly complicated and non-intuitive, a detailed description will be neglected for some code snippets.
|
||||
|
||||
```cpp
|
||||
Job doSomething()
|
||||
{
|
||||
std::cout << "Doing something" << std::endl;
|
||||
co_return;
|
||||
}
|
||||
Job doSomethingElse()
|
||||
{
|
||||
std::cout << "Doing something else" << std::endl;
|
||||
co_return;
|
||||
}
|
||||
Job doSomethingAfterwards()
|
||||
{
|
||||
std::cout << "Doing something afterwards" << std::endl;
|
||||
co_return;
|
||||
}
|
||||
Job startHere()
|
||||
{
|
||||
Job job1 = doSomething();
|
||||
Job job2 = doSomethingElse();
|
||||
co_await job1;
|
||||
co_await job2;
|
||||
co_await doSomethingAfterwards();
|
||||
}
|
||||
```
|
||||
|
||||
This example will execute the first two functions in an undefined order, while the last one will always be executed last. This is because the jobs are launched as soon as the functions are called, while the co_await operator waits for them to finish. Keeping the return value of every job launched is a bit inconvenient, so there is are some helper functions to help with that. `Job::all()` takes a variable amount of `Job`s which it 'combines' into one. This reduces the previous example into this:
|
||||
|
||||
```cpp
|
||||
Job doSomething()
|
||||
{
|
||||
std::cout << "Doing something" << std::endl;
|
||||
co_return;
|
||||
}
|
||||
Job doSomethingElse()
|
||||
{
|
||||
std::cout << "Doing something else" << std::endl;
|
||||
co_return;
|
||||
}
|
||||
Job doSomethingAfterwards()
|
||||
{
|
||||
std::cout << "Doing something afterwards" << std::endl;
|
||||
co_return;
|
||||
}
|
||||
Job startHere()
|
||||
{
|
||||
co_await Job::all(
|
||||
doSomething(),
|
||||
doSomethingElse());
|
||||
co_await doSomethingAfterwards();
|
||||
}
|
||||
```
|
||||
|
||||
Any Job can also be continued with `then()`, taking in another `Job` or anything that evaluates to a `Job` if called. This further simplifies the example:
|
||||
|
||||
```cpp
|
||||
Job doSomething()
|
||||
{
|
||||
std::cout << "Doing something" << std::endl;
|
||||
co_return;
|
||||
}
|
||||
Job doSomethingElse()
|
||||
{
|
||||
std::cout << "Doing something else" << std::endl;
|
||||
co_return;
|
||||
}
|
||||
Job doSomethingAfterwards()
|
||||
{
|
||||
std::cout << "Doing something afterwards" << std::endl;
|
||||
co_return;
|
||||
}
|
||||
Job startHere()
|
||||
{
|
||||
co_await Job::all(
|
||||
doSomething(),
|
||||
doSomethingElse())
|
||||
.then(doSomethingAfterwards());
|
||||
}
|
||||
```
|
||||
|
||||
### Events
|
||||
|
||||
Aside from `Job`s, `Event`s can also be used to synchronize functions. They are constructed with an optional name for easier debugging, and can be `co_await`ed. For the waiting job to continue, `raise()` must be called, after which one of the waiting jobs should `reset()` the event to make it reusable.
|
||||
|
||||
```cpp
|
||||
Event updateFinished;
|
||||
std::mutex dataLock;
|
||||
uint64 data = 0;
|
||||
|
||||
Job updateSomething()
|
||||
{
|
||||
{
|
||||
std::scoped_lock lock(dataLock);
|
||||
data++;
|
||||
}
|
||||
updateFinished.raise();
|
||||
updateSomething(); // if we call the function again it behaves like a loop
|
||||
}
|
||||
|
||||
Job processUpdates()
|
||||
{
|
||||
co_await updateFinished;
|
||||
updateFinished.reset();
|
||||
{
|
||||
std::scoped_lock lock(dataLock);
|
||||
std::cout << data << std::endl;
|
||||
}
|
||||
processUpdates();
|
||||
}
|
||||
```
|
||||
@@ -64,6 +64,130 @@ class ListSyntheticProvider:
|
||||
def has_children(self):
|
||||
return True
|
||||
|
||||
def Tree_SummaryProvider(valobj, internal_dict):
|
||||
size = valobj.GetChildMemberWithName('_size').GetValueAsUnsigned(0)
|
||||
return f"Tree(size={size})"
|
||||
|
||||
class TreeSyntheticProvider:
|
||||
def __init__(self, valobj, internal_dict):
|
||||
self.valobj = valobj
|
||||
self.update()
|
||||
|
||||
def num_children(self):
|
||||
return self.size
|
||||
|
||||
def get_child_index(self, name):
|
||||
try:
|
||||
return int(name.lstrip('[').rstrip(']'))
|
||||
except:
|
||||
return -1
|
||||
|
||||
def get_child_at_index(self, index):
|
||||
if index < 0 or index >= self.size:
|
||||
return None
|
||||
# Collect all nodes via in-order traversal, then return the one at `index`
|
||||
nodes = []
|
||||
self._collect(self.root, nodes)
|
||||
if index >= len(nodes):
|
||||
return None
|
||||
return nodes[index].GetChildMemberWithName('data')
|
||||
|
||||
def _collect(self, node, out):
|
||||
if not node.IsValid():
|
||||
return
|
||||
self._collect(node.GetChildMemberWithName('leftChild'), out)
|
||||
out.append(node)
|
||||
self._collect(node.GetChildMemberWithName('rightChild'), out)
|
||||
|
||||
def update(self):
|
||||
self.root = self.valobj.GetChildMemberWithName('root')
|
||||
self.size = self.valobj.GetChildMemberWithName('_size').GetValueAsUnsigned(0)
|
||||
|
||||
def has_children(self):
|
||||
return True
|
||||
|
||||
def Set_SummaryProvider(valobj, internal_dict):
|
||||
size = valobj.GetChildMemberWithName('_size').GetValueAsUnsigned(0)
|
||||
return f"Set(size={size})"
|
||||
|
||||
class SetSyntheticProvider:
|
||||
def __init__(self, valobj, internal_dict):
|
||||
self.valobj = valobj
|
||||
self.update()
|
||||
|
||||
def num_children(self):
|
||||
return self.size
|
||||
|
||||
def get_child_index(self, name):
|
||||
try:
|
||||
return int(name.lstrip('[').rstrip(']'))
|
||||
except:
|
||||
return -1
|
||||
|
||||
def get_child_at_index(self, index):
|
||||
if index < 0 or index >= self.size:
|
||||
return None
|
||||
nodes = []
|
||||
self._collect(self.root, nodes)
|
||||
if index >= len(nodes):
|
||||
return None
|
||||
return nodes[index].GetChildMemberWithName('data')
|
||||
|
||||
def _collect(self, node, out):
|
||||
if not node.IsValid():
|
||||
return
|
||||
self._collect(node.GetChildMemberWithName('leftChild'), out)
|
||||
out.append(node)
|
||||
self._collect(node.GetChildMemberWithName('rightChild'), out)
|
||||
|
||||
def update(self):
|
||||
self.root = self.valobj.GetChildMemberWithName('root')
|
||||
self.size = self.valobj.GetChildMemberWithName('_size').GetValueAsUnsigned(0)
|
||||
|
||||
def has_children(self):
|
||||
return True
|
||||
|
||||
def Map_SummaryProvider(valobj, internal_dict):
|
||||
size = valobj.GetChildMemberWithName('_size').GetValueAsUnsigned(0)
|
||||
return f"Map(size={size})"
|
||||
|
||||
class MapSyntheticProvider:
|
||||
def __init__(self, valobj, internal_dict):
|
||||
self.valobj = valobj
|
||||
self.update()
|
||||
|
||||
def num_children(self):
|
||||
return self.size
|
||||
|
||||
def get_child_index(self, name):
|
||||
try:
|
||||
return int(name.lstrip('[').rstrip(']'))
|
||||
except:
|
||||
return -1
|
||||
|
||||
def get_child_at_index(self, index):
|
||||
if index < 0 or index >= self.size:
|
||||
return None
|
||||
nodes = []
|
||||
self._collect(self.root, nodes)
|
||||
if index >= len(nodes):
|
||||
return None
|
||||
return nodes[index].GetChildMemberWithName('data')
|
||||
|
||||
def _collect(self, node, out):
|
||||
if not node.IsValid():
|
||||
return
|
||||
self._collect(node.GetChildMemberWithName('leftChild'), out)
|
||||
out.append(node)
|
||||
self._collect(node.GetChildMemberWithName('rightChild'), out)
|
||||
|
||||
def update(self):
|
||||
self.root = self.valobj.GetChildMemberWithName('root')
|
||||
self.size = self.valobj.GetChildMemberWithName('_size').GetValueAsUnsigned(0)
|
||||
|
||||
def has_children(self):
|
||||
return True
|
||||
|
||||
def Vector_SummaryProvider(valobj, internal_dict):
|
||||
# Get the template parameters to determine vector length
|
||||
type_name = valobj.GetTypeName()
|
||||
@@ -93,6 +217,14 @@ def __lldb_init_module(debugger, internal_dict):
|
||||
debugger.HandleCommand('type summary add -F Seele_lldb.List_SummaryProvider -x "^Seele::List<.*>$"')
|
||||
debugger.HandleCommand('type synthetic add -l Seele_lldb.ListSyntheticProvider -x "^Seele::List<.*>$"')
|
||||
|
||||
# Register Set formatter
|
||||
debugger.HandleCommand('type summary add -F Seele_lldb.Set_SummaryProvider -x "^Seele::Set<.*>$"')
|
||||
debugger.HandleCommand('type synthetic add -l Seele_lldb.SetSyntheticProvider -x "^Seele::Set<.*>$"')
|
||||
|
||||
# Register Map formatter
|
||||
debugger.HandleCommand('type summary add -F Seele_lldb.Map_SummaryProvider -x "^Seele::Map<.*>$"')
|
||||
debugger.HandleCommand('type synthetic add -l Seele_lldb.MapSyntheticProvider -x "^Seele::Map<.*>$"')
|
||||
|
||||
# Register Vector formatter
|
||||
debugger.HandleCommand('type summary add -F Seele_lldb.Vector_SummaryProvider -x "^glm::(detail::)?t?vec[234]?<.*>$"')
|
||||
|
||||
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
fonts/
|
||||
@@ -1,65 +0,0 @@
|
||||
import Common;
|
||||
|
||||
struct VertexInput
|
||||
{
|
||||
uint vertexId : SV_VertexID;
|
||||
uint instanceId : SV_InstanceID;
|
||||
};
|
||||
|
||||
struct VertexOutput
|
||||
{
|
||||
float4 position : SV_Position;
|
||||
float2 texCoords : TEXCOORD;
|
||||
uint glyphIndex : GLYPHINDEX;
|
||||
};
|
||||
|
||||
struct GlyphInstanceData
|
||||
{
|
||||
float x;
|
||||
float y;
|
||||
float z;
|
||||
float width;
|
||||
float height;
|
||||
uint glyphIndex;
|
||||
};
|
||||
struct TextData
|
||||
{
|
||||
StructuredBuffer<GlyphInstanceData> glyphs;
|
||||
SamplerState glyphSampler;
|
||||
Texture2D<float> glyphTextures[];
|
||||
};
|
||||
ParameterBlock<TextData> pText;
|
||||
|
||||
|
||||
[shader("vertex")]
|
||||
VertexOutput vertexMain(VertexInput input)
|
||||
{
|
||||
float xpos = pText.glyphs[input.instanceId].x;
|
||||
float ypos = pText.glyphs[input.instanceId].y;
|
||||
|
||||
float w = pText.glyphs[input.instanceId].width;
|
||||
float h = pText.glyphs[input.instanceId].height;
|
||||
|
||||
const float4 coordinates[4] = {
|
||||
float4(xpos, ypos, 0, 0),
|
||||
float4(xpos, ypos + h, 0, 1),
|
||||
float4(xpos + w, ypos, 1, 0),
|
||||
float4(xpos + w, ypos + h, 1, 1),
|
||||
};
|
||||
float4 vertex = coordinates[input.vertexId];
|
||||
VertexOutput output;
|
||||
output.texCoords = vertex.zw;
|
||||
output.position = mul(pViewParams.projectionMatrix, float4(vertex.xy, pText.glyphs[input.instanceId].z-1, 1));
|
||||
output.glyphIndex = pText.glyphs[input.instanceId].glyphIndex;
|
||||
return output;
|
||||
}
|
||||
|
||||
[shader("fragment")]
|
||||
float4 fragmentMain(
|
||||
float4 position : SV_Position,
|
||||
float2 texCoords : TEXCOORD,
|
||||
uint glyphIndex : GLYPHINDEX
|
||||
) : SV_Target
|
||||
{
|
||||
return float4(0,0,0,pText.glyphTextures[glyphIndex].Sample(pText.glyphSampler, texCoords));
|
||||
}
|
||||
+45
-13
@@ -1,5 +1,10 @@
|
||||
import Common;
|
||||
|
||||
// Per-quad render data, read from the EXISTING pParams.elements storage buffer (bound on the
|
||||
// CPU side by UIPass as SE_DESCRIPTOR_TYPE_STORAGE_BUFFER). We read it here as a plain SSBO so
|
||||
// every value (x/y/w/h, color, opacity, uvOffset/uvSize, textureIndex) is EXACT — not barycentric
|
||||
// interpolated the way the old code passed it as a STYLE vertex attribute (which corrupted the
|
||||
// transparency and shifted glyphs).
|
||||
struct RenderElementStyle
|
||||
{
|
||||
float x;
|
||||
@@ -10,28 +15,33 @@ struct RenderElementStyle
|
||||
float opacity;
|
||||
float z;
|
||||
uint textureIndex;
|
||||
uint pad0;
|
||||
uint pad1;
|
||||
float2 uvOffset;
|
||||
float2 uvSize;
|
||||
};
|
||||
|
||||
struct UIParameter
|
||||
{
|
||||
StructuredBuffer<RenderElementStyle> elements;
|
||||
SamplerState sampler;
|
||||
Texture2D textures[];
|
||||
StructuredBuffer<RenderElementStyle> elements;
|
||||
Texture2D textures[]; // must be last (unsized)
|
||||
};
|
||||
|
||||
ParameterBlock<UIParameter> pParams;
|
||||
|
||||
// Varyings carry only per-fragment continuous data (the corner uv in quad-local space) + the
|
||||
// per-quad instance id (uint, not interpolated — exact per fragment). Position is SV_Position.
|
||||
// Everything else comes from the non-interpolated pParams SSBO.
|
||||
struct VertexOutput
|
||||
{
|
||||
float4 position : SV_Position;
|
||||
float2 texCoords : TEXCOORD;
|
||||
RenderElementStyle style : STYLE;
|
||||
uint instanceId : INSTANCENUM;
|
||||
};
|
||||
|
||||
[shader("vertex")]
|
||||
VertexOutput vertexMain(uint vertexId : SV_VertexID, uint instanceId: SV_InstanceID)
|
||||
VertexOutput vertexMain(uint vertexId : SV_VertexID, uint instanceId : SV_InstanceID)
|
||||
{
|
||||
// Read the per-quad rect from the non-interpolated SSBO (exact values).
|
||||
RenderElementStyle style = pParams.elements[instanceId];
|
||||
float xMin = style.x;
|
||||
float xMax = xMin + style.w;
|
||||
@@ -44,20 +54,42 @@ VertexOutput vertexMain(uint vertexId : SV_VertexID, uint instanceId: SV_Instanc
|
||||
float4(xMax, yMax, 1, 1)
|
||||
};
|
||||
VertexOutput output;
|
||||
output.position = mul(pViewParams.projectionMatrix, float4(coordinates[vertexId].xy, style.z-1, 1));
|
||||
output.texCoords = coordinates[vertexId].zw;
|
||||
output.style = style;
|
||||
// 2D ortho screen->NDC (screen is top-left / y-down; NDC is bottom-left / y-up):
|
||||
// ndcX = (x / W) * 2 - 1
|
||||
// ndcY = 1 - (y / H) * 2
|
||||
float2 ndc = float2(
|
||||
coordinates[vertexId].x * pViewParams.invScreenDimensions.x * 2.0 - 1.0,
|
||||
1.0 - coordinates[vertexId].y * pViewParams.invScreenDimensions.y * 2.0
|
||||
);
|
||||
// style.z is ALREADY the final depth: the CPU maps the tree depth (render.level) into [0,1]
|
||||
// and REVERSES it for the depth buffer's SE_COMPARE_OP_GREATER (nearer = LARGER). Write it
|
||||
// verbatim — do NOT negate it again (the old `1 - style.z` double-inverted the depth).
|
||||
output.position = float4(ndc, style.z, 1.0);
|
||||
output.texCoords = coordinates[vertexId].zw; // quad-local uv, interpolated per-fragment
|
||||
output.instanceId = instanceId; // uint varying: exact per-fragment (not interpolated)
|
||||
return output;
|
||||
}
|
||||
|
||||
[shader("fragment")]
|
||||
float4 fragmentMain(
|
||||
float2 texCoords : TEXCOORD,
|
||||
RenderElementStyle style : STYLE
|
||||
uint instanceId : INSTANCENUM
|
||||
) : SV_Target
|
||||
{
|
||||
if(style.textureIndex == -1) {
|
||||
// Re-read the per-quad data from the non-interpolated SSBO: exact uvOffset/uvSize, exact
|
||||
// color, exact opacity. (Interpolating these as vertex attributes corrupted transparency
|
||||
// and shifted the sampling — the bug the old STYLE-attribute code had.)
|
||||
RenderElementStyle style = pParams.elements[instanceId];
|
||||
if(style.textureIndex == 4294967295u) {
|
||||
// untextured quad (solid background)
|
||||
return float4(style.color, style.opacity);
|
||||
}
|
||||
return pParams.textures[style.textureIndex].Sample(pParams.sampler, texCoords.xy);
|
||||
}
|
||||
// Textured quad (glyph): the texture is the font atlas (R8_UNORM, coverage in R, A baked
|
||||
// to 1.0). Sampled as float4 that gives (R=coverage, G=0, B=0, A=1) — the alpha we want is
|
||||
// .r, not .a. Output pure text color + coverage as alpha; the pipeline's SRC_ALPHA blend
|
||||
// applies the coverage exactly once (do NOT premultiply or it'd be squared).
|
||||
float2 uv = style.uvOffset + texCoords * style.uvSize;
|
||||
float4 tex = pParams.textures[style.textureIndex].Sample(pParams.sampler, uv);
|
||||
float coverage = tex.r;
|
||||
return float4(style.color, coverage * style.opacity);
|
||||
}
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
shaders/
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
textures/
|
||||
@@ -14,7 +14,7 @@ InspectorView::InspectorView(Gfx::PGraphics graphics, PWindow window, const View
|
||||
: View(graphics, window, createInfo, "InspectorView"),
|
||||
uiSystem(new UI::System(
|
||||
new UI::Div<M_8>(UI::Attributes{}, {
|
||||
new UI::Div<BG_Red, Inline>({},
|
||||
new UI::Div<BG_Red, FlexRow, M_4>({},
|
||||
{
|
||||
new UI::Text<Font_Arial, Text_8XL>("Other Test T"),
|
||||
}),
|
||||
|
||||
+127
-34
@@ -1,6 +1,8 @@
|
||||
#include "FontAsset.h"
|
||||
#include "Graphics/Graphics.h"
|
||||
#include "Graphics/Texture.h"
|
||||
#include <ft2build.h>
|
||||
#include FT_FREETYPE_H
|
||||
|
||||
using namespace Seele;
|
||||
|
||||
@@ -45,11 +47,15 @@ UVector2 FontAsset::shapeText(std::string_view view, uint32 fontSize, Array<Rend
|
||||
uint32 num_glyphs;
|
||||
hb_glyph_info_t* glyphs = hb_buffer_get_glyph_infos(buf, &num_glyphs);
|
||||
hb_glyph_position_t* positions = hb_buffer_get_glyph_positions(buf, &num_glyphs);
|
||||
Vector2 min = Vector2(std::numeric_limits<float>::max());
|
||||
Vector2 max = Vector2(std::numeric_limits<float>::lowest());
|
||||
int32 xppem, yppem;
|
||||
hb_font_get_scale(hb_font, &xppem, &yppem);
|
||||
Vector2 cursor = Vector2(0);
|
||||
// Baseline (in pixels, relative to the text block's top-left) = the font's ascender.
|
||||
// FreeType gives it in 1/64-pixel units after FT_Set_Pixel_Sizes; convert to pixels.
|
||||
// Screen space is y-down; the baseline sits `ascender` px *below* the block's top edge.
|
||||
// (FT metrics ascender is positive-up, so the baseline screen y = +ascender in y-down.)
|
||||
float ascenderPx = (float)ft_face->size->metrics.ascender / 64.0f;
|
||||
Vector2 cursor = Vector2(0, ascenderPx);
|
||||
for (uint32 i = 0; i < num_glyphs; ++i) {
|
||||
hb_codepoint_t glyphid = glyphs[i].codepoint;
|
||||
float xOffset = (float)positions[i].x_offset * fontSize / xppem;
|
||||
@@ -58,46 +64,133 @@ UVector2 FontAsset::shapeText(std::string_view view, uint32 fontSize, Array<Rend
|
||||
float yAdvance = (float)positions[i].y_advance * fontSize / yppem;
|
||||
Vector2 position = cursor + Vector2(xOffset, yOffset);
|
||||
Vector2 dimensions = fontSizes[fontSize].glyphs[glyphid].size;
|
||||
render.add(RenderGlyph{
|
||||
.texture = fontSizes[fontSize].glyphs[glyphid].texture,
|
||||
.position = position,
|
||||
.dimensions = dimensions,
|
||||
});
|
||||
// FreeType bitmap_top = distance from the baseline to the TOP of the bitmap
|
||||
// (positive up). In y-down screen space the bitmap's top edge is therefore at
|
||||
// (baselineY - bitmap_top). bearing.x (bitmap_left) shifts the bitmap right of the
|
||||
// pen. This is what was missing: without it every glyph's top sat on the cursor y
|
||||
// (text top), giving top-aligned instead of baseline-aligned text.
|
||||
float bearingX = (float)fontSizes[fontSize].glyphs[glyphid].bearing.x;
|
||||
float bitmapTop = (float)fontSizes[fontSize].glyphs[glyphid].bearing.y;
|
||||
position.x += bearingX;
|
||||
position.y += -bitmapTop;
|
||||
RenderGlyph& rg = render.add({});
|
||||
rg.texture = fontSizes[fontSize].atlas;
|
||||
rg.uvOffset = fontSizes[fontSize].glyphs[glyphid].uvOffset;
|
||||
rg.uvSize = fontSizes[fontSize].glyphs[glyphid].uvSize;
|
||||
rg.position = position;
|
||||
rg.dimensions = dimensions;
|
||||
cursor += Vector2(xAdvance, yAdvance);
|
||||
min = Vector2(std::min(min.x, position.x), std::min(min.y, position.y));
|
||||
max = Vector2(std::max(max.x, position.x + dimensions.x), std::max(min.y, position.y + dimensions.y));
|
||||
// Track the right-most x extent (for auto width). Height is NOT derived from the
|
||||
// bitmap extents: it must be the full line height (ascender - descender) or
|
||||
// auto-sized elements would clip descenders. See below.
|
||||
max.x = std::max(max.x, position.x + dimensions.x);
|
||||
}
|
||||
hb_buffer_destroy(buf);
|
||||
return UVector2(max - min);
|
||||
// Width = right-most x extent (glyphs start at x>=0, so max.x is the full width).
|
||||
// Height = line height from the font metrics: ascender (above baseline) plus the
|
||||
// descender depth (FT descender is negative-up => its magnitude is below baseline).
|
||||
// This is the correct auto-size: it fits the whole em, including descenders.
|
||||
float descenderPx = (float)ft_face->size->metrics.descender / 64.0f; // <= 0 (down is negative-up)
|
||||
float lineHeightPx = ascenderPx - descenderPx;
|
||||
if (max.x <= 0.0f) { // empty string
|
||||
return UVector2(0, 0);
|
||||
}
|
||||
return UVector2((uint32)std::ceil(max.x), (uint32)std::ceil(lineHeightPx));
|
||||
}
|
||||
|
||||
void FontAsset::loadGlyphs(uint32 fontSize) {
|
||||
if (fontSizes.contains(fontSize)) {
|
||||
return; // packed once; the atlas is immutable
|
||||
}
|
||||
FT_Set_Pixel_Sizes(ft_face, 0, fontSize);
|
||||
// measure every glyph's bitmap size first (one pass, no GPU) so the shelf packer
|
||||
// can compute each cell's atlas coordinates before any pixels are uploaded
|
||||
constexpr uint32 atlasW = 1024;
|
||||
struct Slot {
|
||||
int glyphId;
|
||||
uint32 w, h;
|
||||
uint32 x, y; // atlas coordinates, filled by the packer
|
||||
};
|
||||
Array<Slot> slots;
|
||||
uint32 xCursor = 0;
|
||||
uint32 cursorY = 0;
|
||||
uint32 shelfH = 0;
|
||||
for (int i = 0; i < ft_face->num_glyphs; ++i) {
|
||||
assert(FT_Load_Glyph(ft_face, i, FT_LOAD_RENDER) == 0);
|
||||
FontAsset::Glyph& glyph = fontSizes[fontSize].glyphs[i];
|
||||
glyph.size = IVector2(ft_face->glyph->bitmap.width, ft_face->glyph->bitmap.rows);
|
||||
int err = FT_Load_Glyph(ft_face, i, FT_LOAD_RENDER);
|
||||
assert(err == 0);
|
||||
uint32 w = ft_face->glyph->bitmap.width;
|
||||
uint32 h = ft_face->glyph->bitmap.rows;
|
||||
if (w == 0 || h == 0) {
|
||||
w = 1;
|
||||
h = 1; // keep a 1x1 transparent placeholder so empty glyphs need no special case
|
||||
}
|
||||
if (w > atlasW) {
|
||||
w = atlasW; // shortcut: no per-glyph multi-row splitting; clamp to the atlas width
|
||||
}
|
||||
if (xCursor + w > atlasW) {
|
||||
cursorY += shelfH;
|
||||
shelfH = 0;
|
||||
xCursor = 0;
|
||||
}
|
||||
Slot s;
|
||||
s.glyphId = i;
|
||||
s.w = w;
|
||||
s.h = h;
|
||||
s.x = xCursor;
|
||||
s.y = cursorY;
|
||||
xCursor += w;
|
||||
shelfH = std::max(shelfH, h);
|
||||
slots.add(s);
|
||||
}
|
||||
uint32 totalH = cursorY + shelfH;
|
||||
if (totalH == 0) {
|
||||
totalH = 1;
|
||||
}
|
||||
Array<uint8> atlasData((uint64)atlasW * totalH, 0); // transparent by default
|
||||
FontData& data = fontSizes[fontSize];
|
||||
for (auto& s : slots) {
|
||||
// FT_Load_Glyph resets the face's current glyph — the measured sizes in `slots`
|
||||
// are already captured, so re-rendering here is safe
|
||||
// (FreeType's FT_Load_Glyph must NOT be wrapped in assert(): NDEBUG in release
|
||||
// builds would then never render the bitmap, leaving the atlas all-transparent.)
|
||||
int err2 = FT_Load_Glyph(ft_face, s.glyphId, FT_LOAD_RENDER);
|
||||
assert(err2 == 0);
|
||||
uint32 bw = ft_face->glyph->bitmap.width;
|
||||
uint32 bh = ft_face->glyph->bitmap.rows;
|
||||
FontAsset::Glyph& glyph = data.glyphs[s.glyphId];
|
||||
if (bw == 0 || bh == 0) {
|
||||
bw = 1;
|
||||
bh = 1;
|
||||
glyph.textureData = Array<uint8>(1, 0); // 1x1 transparent placeholder
|
||||
} else {
|
||||
glyph.textureData.resize((uint64)bw * bh);
|
||||
std::memcpy(glyph.textureData.data(), ft_face->glyph->bitmap.buffer, (uint64)bw * bh);
|
||||
}
|
||||
// blit the bitmap into the atlas at (s.x, s.y), row by row (pitch may differ from width)
|
||||
for (uint32 y = 0; y < bh; ++y) {
|
||||
const uint8* src = (bw == 0 || bh == 0) ? nullptr : (const uint8*)ft_face->glyph->bitmap.buffer + (uint64)y * ft_face->glyph->bitmap.pitch;
|
||||
if (src != nullptr) {
|
||||
std::memcpy(atlasData.data() + ((uint64)(s.y + y) * atlasW + s.x), src, bw);
|
||||
}
|
||||
}
|
||||
glyph.size = IVector2(bw, bh);
|
||||
glyph.bearing = IVector2(ft_face->glyph->bitmap_left, ft_face->glyph->bitmap_top);
|
||||
glyph.advance = ft_face->glyph->advance.x;
|
||||
glyph.textureData.resize(glyph.size.x * glyph.size.y);
|
||||
if (glyph.textureData.size() == 0) {
|
||||
glyph.size.x = 1;
|
||||
glyph.size.y = 1;
|
||||
glyph.textureData.add(0);
|
||||
// load a single transparent pixel, so that we dont have to handle empty textures later
|
||||
} else {
|
||||
std::memcpy(glyph.textureData.data(), ft_face->glyph->bitmap.buffer, glyph.textureData.size());
|
||||
}
|
||||
glyph.texture = graphics->createTexture2D(TextureCreateInfo{
|
||||
.sourceData =
|
||||
{
|
||||
.size = glyph.textureData.size(),
|
||||
.data = glyph.textureData.data(),
|
||||
},
|
||||
.format = Gfx::SE_FORMAT_R8_UNORM,
|
||||
.width = glyph.size.x,
|
||||
.height = glyph.size.y,
|
||||
.name = "FontGlyph",
|
||||
});
|
||||
// the UV rect is the exact cell, corner-aligned: offset = (x / W, y / H),
|
||||
// size = (w / W, h / H). The shader already applies a 1-px inset (uvSize * 0.98),
|
||||
// so linear sampling stays inside the cell and does not bleed into neighbors.
|
||||
glyph.uvOffset = Vector2((float)s.x / (float)atlasW, (float)s.y / (float)totalH);
|
||||
glyph.uvSize = Vector2((float)bw / (float)atlasW, (float)bh / (float)totalH);
|
||||
}
|
||||
}
|
||||
data.atlas = graphics->createTexture2D(TextureCreateInfo{
|
||||
.sourceData =
|
||||
{
|
||||
.size = atlasData.size(),
|
||||
.data = atlasData.data(),
|
||||
},
|
||||
.format = Gfx::SE_FORMAT_R8_UNORM,
|
||||
.width = atlasW,
|
||||
.height = totalH,
|
||||
.name = "FontAtlas",
|
||||
});
|
||||
}
|
||||
@@ -21,24 +21,32 @@ class FontAsset : public Asset {
|
||||
UVector2 bearing = {};
|
||||
uint32 advance = 0;
|
||||
Array<uint8> textureData;
|
||||
Gfx::OTexture2D texture = nullptr;
|
||||
// rect of this glyph inside the per-(font,size) atlas; the atlas texture is
|
||||
// shared by every glyph of the same size (FontData::atlas) — no per-glyph texture
|
||||
Vector2 uvOffset = Vector2(0);
|
||||
Vector2 uvSize = Vector2(0);
|
||||
void save(ArchiveBuffer& buffer) const;
|
||||
void load(ArchiveBuffer& buffer);
|
||||
};
|
||||
struct FontData {
|
||||
Map<uint32, Glyph> glyphs;
|
||||
// the single atlas holding every glyph of this size (created in loadGlyphs)
|
||||
Gfx::OTexture2D atlas = nullptr;
|
||||
};
|
||||
void loadFace();
|
||||
|
||||
// packs every glyph of `fontSize` into one atlas (created lazily on first use by
|
||||
// shapeText); public so the unit test can drive the real packer
|
||||
void loadGlyphs(uint32 fontSize);
|
||||
struct RenderGlyph {
|
||||
Gfx::PTexture2D texture;
|
||||
Gfx::PTexture2D texture; // the font's atlas for this size (shared by all its glyphs)
|
||||
Vector2 uvOffset;
|
||||
Vector2 uvSize;
|
||||
UVector2 position;
|
||||
UVector2 dimensions;
|
||||
};
|
||||
UVector2 shapeText(std::string_view view, uint32 fontSize, Array<RenderGlyph>& render);
|
||||
|
||||
private:
|
||||
void loadGlyphs(uint32 fontSize);
|
||||
Gfx::PGraphics graphics;
|
||||
hb_blob_t* blob;
|
||||
hb_face_t* hb_face;
|
||||
|
||||
@@ -103,6 +103,10 @@ template <typename T> struct Array {
|
||||
}
|
||||
}
|
||||
}
|
||||
// initializer_list elements are const, so they can only be copied, never moved.
|
||||
// For move-only T (e.g. OwningPtr) this ctor is deleted — construct such arrays
|
||||
// with the default ctor + add()/emplace() instead (those move).
|
||||
template <typename U = T, typename = std::enable_if_t<std::is_copy_constructible_v<U>>>
|
||||
constexpr Array(std::initializer_list<T> init, const allocator_type& alloc = allocator_type())
|
||||
: arraySize(init.size()), allocated(init.size()), allocator(alloc) {
|
||||
_data = allocateArray(init.size());
|
||||
@@ -276,7 +280,12 @@ template <typename T> struct Array {
|
||||
T* tempArray = allocateArray(allocated);
|
||||
assert(tempArray != nullptr);
|
||||
|
||||
std::uninitialized_move(begin(), end(), Iterator(tempArray));
|
||||
// begin()/end() yield lvalue iterators, so uninitialized_move would
|
||||
// degrade to a copy — invalid for move-only T (e.g. OwningPtr). Move
|
||||
// each element explicitly instead.
|
||||
for (size_type i = 0; i < arraySize; ++i) {
|
||||
std::allocator_traits<allocator_type>::construct(allocator, &tempArray[i], std::move(_data[i]));
|
||||
}
|
||||
deallocateArray(_data, arraySize);
|
||||
_data = tempArray;
|
||||
}
|
||||
|
||||
@@ -8,37 +8,18 @@
|
||||
|
||||
using namespace Seele;
|
||||
|
||||
UIPass::UIPass(Gfx::PGraphics graphics, UI::PSystem system) : RenderPass(graphics), system(system) {
|
||||
glyphInstanceBuffer = graphics->createShaderBuffer(ShaderBufferCreateInfo{.name = "GlyphInstanceBuffer"});
|
||||
UIPass::UIPass(Gfx::PGraphics graphics, UI::PSystem system) : RenderPass(graphics), system(system), passSize(0, 0) {
|
||||
elementBuffer = graphics->createShaderBuffer(ShaderBufferCreateInfo{.name = "RenderStyleElements"});
|
||||
textDescriptorLayout = graphics->createDescriptorLayout("pText");
|
||||
textDescriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = GLYPHINSTANCE_NAME,
|
||||
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER,
|
||||
});
|
||||
textDescriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = GLYPHSAMPLER_NAME,
|
||||
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_SAMPLER,
|
||||
});
|
||||
textDescriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = TEXTURES_NAME,
|
||||
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_SAMPLED_IMAGE,
|
||||
.descriptorCount = 1024,
|
||||
.access = Gfx::SE_DESCRIPTOR_ACCESS_SAMPLE_BIT,
|
||||
});
|
||||
textPipelineLayout = graphics->createPipelineLayout("TextPipeline");
|
||||
textPipelineLayout->addDescriptorLayout(viewParamsLayout);
|
||||
textPipelineLayout->addDescriptorLayout(textDescriptorLayout);
|
||||
|
||||
uiDescriptorLayout = graphics->createDescriptorLayout("pParams");
|
||||
uiDescriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = ELEMENT_NAME,
|
||||
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER,
|
||||
});
|
||||
uiDescriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = GLYPHSAMPLER_NAME,
|
||||
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_SAMPLER,
|
||||
});
|
||||
uiDescriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = ELEMENT_NAME,
|
||||
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER,
|
||||
});
|
||||
uiDescriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
|
||||
.name = TEXTURES_NAME,
|
||||
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_SAMPLED_IMAGE,
|
||||
@@ -48,7 +29,6 @@ UIPass::UIPass(Gfx::PGraphics graphics, UI::PSystem system) : RenderPass(graphic
|
||||
uiPipelineLayout = graphics->createPipelineLayout("UIPipeline");
|
||||
uiPipelineLayout->addDescriptorLayout(viewParamsLayout);
|
||||
uiPipelineLayout->addDescriptorLayout(uiDescriptorLayout);
|
||||
// todo:
|
||||
}
|
||||
|
||||
UIPass::~UIPass() {}
|
||||
@@ -60,13 +40,34 @@ void UIPass::beginFrame(const Component::Camera& cam, const Component::Transform
|
||||
system->processInput();
|
||||
system->beginFrame(UVector2(viewport->getWidth(), viewport->getHeight()));
|
||||
renderElements = system->render();
|
||||
glyphs.clear();
|
||||
usedTextures.clear();
|
||||
elements.clear();
|
||||
// Depth buffer uses SE_COMPARE_OP_GREATER (Vulkan >=): nearer = LARGER depth value. So the
|
||||
// tree depth (render.level, 0 = root/nearest) is mapped onto [0,1] and REVERSED — level 0
|
||||
// gets a depth nearest 1.0 (closest), and each deeper level recedes by 1/(MAX+1) toward 0.
|
||||
// The shader writes this value verbatim as SV_Position.z (see UIPass.slang), so we must NOT
|
||||
// re-negate it there.
|
||||
//
|
||||
// CRITICAL: every level must map to a depth STRICTLY greater than 0.0. The engine's global
|
||||
// compare op is GREATER (>=, see Vulkan/Enums.cpp), and the depth buffer is cleared to 0
|
||||
// (createRenderPass). If any element's depth were exactly 0.0, its 0.0 >= 0.0 test would
|
||||
// fail and the element would be culled. The clamp below is therefore a MAXIMUM (saturate to
|
||||
// 0 at level >= MAX) — do NOT "fix" it into a minimum (e.g. max(depth, kDepthStep)); that
|
||||
// would push deep levels to exactly kDepthStep while their shallower ancestors are at
|
||||
// 2*kDepthStep or less, inverting the order and making deep text vanish under its parent.
|
||||
// For level < MAX the depth is always >= kDepthStep > 0 (kMaxTreeDepth is a multiple of 32,
|
||||
// so the float multiply is exact and 1 - (MAX-1)*step == step > 0), so the 0.0 saturation is
|
||||
// only ever reached for level >= MAX — at which point correct ordering is already lost anyway
|
||||
// (all such levels saturate to the same 0.0, which is "farther" than any shallower level:
|
||||
// correct relative order, and they never alias with a shallower level because those are > 0).
|
||||
constexpr float kMaxTreeDepth = 64.0f;
|
||||
const float kDepthStep = 1.0f / (kMaxTreeDepth + 1.0f);
|
||||
for (auto& render : renderElements) {
|
||||
float x = render.position.x;
|
||||
float y = render.position.y;
|
||||
//todo: convert using actual tree depth
|
||||
// Reversed, clamped tree-depth -> [0,1] (nearer/larger = closer to the camera).
|
||||
const float rawDepth = 1.0f - (float)render.level * kDepthStep;
|
||||
const float depth = rawDepth > 0.0f ? rawDepth : 0.0f;
|
||||
uint32 textureIndex = std::numeric_limits<uint32>::max();
|
||||
if (render.backgroundTexture != nullptr) {
|
||||
textureIndex = (uint32)usedTextures.size();
|
||||
@@ -78,24 +79,12 @@ void UIPass::beginFrame(const Component::Camera& cam, const Component::Transform
|
||||
.w = render.dimensions.x,
|
||||
.h = render.dimensions.y,
|
||||
.color = render.backgroundColor,
|
||||
.z = render.level / 100.f,
|
||||
.z = depth, // already reversed+clamped tree depth (see above); shader writes it verbatim
|
||||
.textureIndex = textureIndex,
|
||||
.uvOffset = render.uvOffset,
|
||||
.uvSize = render.uvSize,
|
||||
});
|
||||
}
|
||||
glyphInstanceBuffer->rotateBuffer(sizeof(GlyphInstanceData) * glyphs.size());
|
||||
glyphInstanceBuffer->updateContents(0, sizeof(GlyphInstanceData) * glyphs.size(), glyphs.data());
|
||||
glyphInstanceBuffer->pipelineBarrier(Gfx::SE_ACCESS_TRANSFER_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_TRANSFER_BIT,
|
||||
Gfx::SE_ACCESS_SHADER_READ_BIT, Gfx::SE_PIPELINE_STAGE_VERTEX_SHADER_BIT);
|
||||
|
||||
textDescriptorLayout->reset();
|
||||
textDescriptorSet = textDescriptorLayout->allocateDescriptorSet();
|
||||
textDescriptorSet->updateBuffer(GLYPHINSTANCE_NAME, 0, glyphInstanceBuffer);
|
||||
textDescriptorSet->updateSampler(GLYPHSAMPLER_NAME, 0, glyphSampler);
|
||||
for (uint32 i = 0; i < usedTextures.size(); ++i) {
|
||||
textDescriptorSet->updateTexture(TEXTURES_NAME, i, usedTextures[i]->getDefaultView());
|
||||
}
|
||||
textDescriptorSet->writeChanges();
|
||||
|
||||
elementBuffer->rotateBuffer(sizeof(RenderElementStyle) * elements.size());
|
||||
elementBuffer->updateContents(0, sizeof(RenderElementStyle) * elements.size(), elements.data());
|
||||
elementBuffer->pipelineBarrier(Gfx::SE_ACCESS_TRANSFER_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_TRANSFER_BIT, Gfx::SE_ACCESS_SHADER_READ_BIT,
|
||||
@@ -103,7 +92,7 @@ void UIPass::beginFrame(const Component::Camera& cam, const Component::Transform
|
||||
uiDescriptorLayout->reset();
|
||||
uiDescriptorSet = uiDescriptorLayout->allocateDescriptorSet();
|
||||
uiDescriptorSet->updateBuffer(ELEMENT_NAME, 0, elementBuffer);
|
||||
uiDescriptorSet->updateSampler(GLYPHSAMPLER_NAME, 0, glyphSampler);
|
||||
uiDescriptorSet->updateSampler(GLYPHSAMPLER_NAME, 0, uiSampler);
|
||||
for (uint32 i = 0; i < usedTextures.size(); ++i) {
|
||||
uiDescriptorSet->updateTexture(TEXTURES_NAME, i, usedTextures[i]->getDefaultView());
|
||||
}
|
||||
@@ -113,7 +102,7 @@ void UIPass::beginFrame(const Component::Camera& cam, const Component::Transform
|
||||
void UIPass::render() {
|
||||
graphics->beginRenderPass(renderPass);
|
||||
Array<Gfx::ORenderCommand> commands;
|
||||
Gfx::ORenderCommand command = graphics->createRenderCommand("TextPassCommand");
|
||||
Gfx::ORenderCommand command = graphics->createRenderCommand("UIPassCommand");
|
||||
command->setViewport(viewport);
|
||||
command->bindPipeline(uiPipeline);
|
||||
command->bindDescriptor({viewParamsSet, uiDescriptorSet});
|
||||
@@ -136,19 +125,23 @@ void UIPass::createRenderPass() {
|
||||
};
|
||||
|
||||
depthBuffer = graphics->createTexture2D(depthBufferInfo);
|
||||
depthAttachment =
|
||||
Gfx::RenderTargetAttachment(depthBuffer->getDefaultView(), Gfx::SE_IMAGE_LAYOUT_UNDEFINED, Gfx::SE_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL,
|
||||
Gfx::SE_ATTACHMENT_LOAD_OP_CLEAR, Gfx::SE_ATTACHMENT_STORE_OP_STORE);
|
||||
depthAttachment = Gfx::RenderTargetAttachment(depthBuffer->getDefaultView(), Gfx::SE_IMAGE_LAYOUT_UNDEFINED,
|
||||
Gfx::SE_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, Gfx::SE_ATTACHMENT_LOAD_OP_CLEAR,
|
||||
Gfx::SE_ATTACHMENT_STORE_OP_STORE);
|
||||
depthAttachment.clear.depthStencil.depth = 0;
|
||||
|
||||
colorAttachment = Gfx::RenderTargetAttachment(viewport, Gfx::SE_IMAGE_LAYOUT_UNDEFINED, Gfx::SE_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
|
||||
Gfx::SE_ATTACHMENT_LOAD_OP_CLEAR, Gfx::SE_ATTACHMENT_STORE_OP_STORE);
|
||||
colorAttachment.clear.color = {{1.0f, 1.0f, 1.0f, 1.0f}};
|
||||
|
||||
Gfx::RenderTargetLayout layout = Gfx::RenderTargetLayout{
|
||||
.colorAttachments = {colorAttachment},
|
||||
.depthAttachment = depthAttachment,
|
||||
};
|
||||
// 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();
|
||||
}
|
||||
Array<Gfx::SubPassDependency> dependency = {
|
||||
{
|
||||
.srcSubpass = ~0U,
|
||||
@@ -175,52 +168,15 @@ void UIPass::createRenderPass() {
|
||||
Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT,
|
||||
},
|
||||
};
|
||||
renderPass = graphics->createRenderPass(std::move(layout), dependency, viewport->getRenderArea(), "TextPass");
|
||||
renderPass = graphics->createRenderPass(std::move(layout), dependency, viewport->getRenderArea(), "UIPass");
|
||||
|
||||
graphics->beginShaderCompilation(ShaderCompilationInfo{
|
||||
.name = "TextVertex",
|
||||
.modules = {"TextPass"},
|
||||
.entryPoints = {{"vertexMain", "TextPass"}, {"fragmentMain", "TextPass"}},
|
||||
.rootSignature = textPipelineLayout,
|
||||
});
|
||||
textPipelineLayout->create();
|
||||
textVertexShader = graphics->createVertexShader({0});
|
||||
textFragmentShader = graphics->createFragmentShader({1});
|
||||
|
||||
glyphSampler = graphics->createSampler({
|
||||
uiSampler = graphics->createSampler({
|
||||
.magFilter = Gfx::SE_FILTER_LINEAR,
|
||||
.minFilter = Gfx::SE_FILTER_LINEAR,
|
||||
.addressModeU = Gfx::SE_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
|
||||
.addressModeV = Gfx::SE_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
|
||||
});
|
||||
|
||||
textPipeline = graphics->createGraphicsPipeline(Gfx::LegacyPipelineCreateInfo{
|
||||
.topology = Gfx::SE_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP,
|
||||
.vertexShader = textVertexShader,
|
||||
.fragmentShader = textFragmentShader,
|
||||
.renderPass = renderPass,
|
||||
.pipelineLayout = textPipelineLayout,
|
||||
.rasterizationState =
|
||||
{
|
||||
.cullMode = Gfx::SE_CULL_MODE_NONE,
|
||||
},
|
||||
.colorBlend =
|
||||
{
|
||||
|
||||
.attachmentCount = 1,
|
||||
.blendAttachments = {{
|
||||
.blendEnable = true,
|
||||
.srcColorBlendFactor = Gfx::SE_BLEND_FACTOR_SRC_ALPHA,
|
||||
.dstColorBlendFactor = Gfx::SE_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA,
|
||||
.srcAlphaBlendFactor = Gfx::SE_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA,
|
||||
.dstAlphaBlendFactor = Gfx::SE_BLEND_FACTOR_ZERO,
|
||||
.alphaBlendOp = Gfx::SE_BLEND_OP_ADD,
|
||||
.colorWriteMask = Gfx::SE_COLOR_COMPONENT_R_BIT | Gfx::SE_COLOR_COMPONENT_G_BIT | Gfx::SE_COLOR_COMPONENT_B_BIT |
|
||||
Gfx::SE_COLOR_COMPONENT_A_BIT,
|
||||
}},
|
||||
},
|
||||
});
|
||||
|
||||
graphics->beginShaderCompilation(ShaderCompilationInfo{
|
||||
.name = "UIVertex",
|
||||
.modules = {"UIPass"},
|
||||
@@ -241,6 +197,10 @@ void UIPass::createRenderPass() {
|
||||
{
|
||||
.cullMode = Gfx::SE_CULL_MODE_NONE,
|
||||
},
|
||||
.depthStencilState =
|
||||
{
|
||||
.depthCompareOp = Gfx::SE_COMPARE_OP_GREATER_OR_EQUAL,
|
||||
},
|
||||
.colorBlend =
|
||||
{
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
#pragma once
|
||||
#include "Graphics/Shader.h"
|
||||
#include "RenderPass.h"
|
||||
#include "Asset/FontAsset.h"
|
||||
#include "UI/System.h"
|
||||
|
||||
namespace Seele {
|
||||
@@ -28,45 +27,38 @@ class UIPass : public RenderPass {
|
||||
void key(KeyCode code, InputAction action, KeyModifierFlags modifier, char text = 0) { system->key(code, action, (KeyModifier)modifier, text); }
|
||||
|
||||
private:
|
||||
struct GlyphData {
|
||||
Vector2 bearing;
|
||||
Vector2 size;
|
||||
uint32 advance;
|
||||
};
|
||||
struct GlyphInstanceData {
|
||||
float x;
|
||||
float y;
|
||||
float z;
|
||||
float width;
|
||||
float height;
|
||||
uint32 glyphIndex;
|
||||
};
|
||||
|
||||
struct RenderElementStyle {
|
||||
float x;
|
||||
float y;
|
||||
float w;
|
||||
float h;
|
||||
Vector color;
|
||||
// Layout is locked 1:1 to the Slang std430 struct (UIPass.slang::RenderElementStyle).
|
||||
// Offsets (both sides): x/y/w/h @0/4/8/12, color @16 (12B, 16B-aligned in std430),
|
||||
// opacity @28, z @32, textureIndex @36, uvOffset @40, uvSize @48, pad @56, sizeof=64.
|
||||
//
|
||||
// The trailing `pad` (Vector2) is LOAD-BEARING: the Slang std430 struct is 16B-aligned
|
||||
// (because of the float3), so its stride is sizeof=64. On platforms where the C++ side
|
||||
// aligns to 4 (alignof(glm::vec3)==4), the natural sizeof would be 56 and the CPU would
|
||||
// pack elements at 56B — desyncing element 1's data against the GPU's 64B stride and
|
||||
// corrupting every field from uvSize onward. `pad` forces sizeof==64 on ALL platforms.
|
||||
//
|
||||
// Do NOT reorder, remove, or shrink `pad`, and do NOT insert fields between existing ones
|
||||
// without updating BOTH this struct AND the Slang struct AND re-verifying the offsets
|
||||
// (slangc + spirv-dis, and a static_assert on the C++ side if available).
|
||||
Vector color; // glm::vec3 (12B; std430 aligns it to 16B, C++ aligns per ABI)
|
||||
float opacity = 1;
|
||||
float z = 0;
|
||||
uint32 textureIndex = std::numeric_limits<uint32>::max();
|
||||
uint32 pad0;
|
||||
uint32 pad1;
|
||||
// UV rect for textured quads (glyphs: their rect in the font atlas); unused for untextured quads
|
||||
Vector2 uvOffset = Vector2(0);
|
||||
Vector2 uvSize = Vector2(1);
|
||||
Vector2 pad; // do not remove — see layout comment above
|
||||
};
|
||||
|
||||
Gfx::RenderTargetAttachment colorAttachment;
|
||||
Gfx::RenderTargetAttachment depthAttachment;
|
||||
Gfx::OTexture2D depthBuffer;
|
||||
|
||||
Gfx::ODescriptorLayout textDescriptorLayout;
|
||||
Gfx::ODescriptorSet textDescriptorSet;
|
||||
|
||||
Gfx::OVertexShader textVertexShader;
|
||||
Gfx::OFragmentShader textFragmentShader;
|
||||
Gfx::OPipelineLayout textPipelineLayout;
|
||||
Gfx::PGraphicsPipeline textPipeline;
|
||||
|
||||
Gfx::ODescriptorLayout uiDescriptorLayout;
|
||||
Gfx::ODescriptorSet uiDescriptorSet;
|
||||
|
||||
@@ -78,14 +70,12 @@ 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<GlyphInstanceData> glyphs;
|
||||
Array<RenderElementStyle> elements;
|
||||
Gfx::OShaderBuffer glyphInstanceBuffer;
|
||||
constexpr static const char* GLYPHINSTANCE_NAME = "glyphData";
|
||||
Gfx::OShaderBuffer elementBuffer;
|
||||
constexpr static const char* ELEMENT_NAME = "elements";
|
||||
Gfx::OSampler glyphSampler;
|
||||
Gfx::OSampler uiSampler;
|
||||
constexpr static const char* GLYPHSAMPLER_NAME = "glyphSampler";
|
||||
Array<Gfx::PTexture2D> usedTextures;
|
||||
constexpr static const char* TEXTURES_NAME = "textures";
|
||||
|
||||
@@ -29,7 +29,8 @@ Command::Command(PGraphics graphics, PCommandPool pool) : graphics(graphics), po
|
||||
|
||||
Command::~Command() {
|
||||
vkFreeCommandBuffers(graphics->getDevice(), pool->getHandle(), 1, &handle);
|
||||
waitSemaphores.clear();
|
||||
waitHandles.clear();
|
||||
waitFlags.clear();
|
||||
}
|
||||
|
||||
void Command::begin() {
|
||||
@@ -114,8 +115,13 @@ void Command::executeCommands(Array<Gfx::OComputeCommand> commands) {
|
||||
}
|
||||
|
||||
void Command::waitForSemaphore(VkPipelineStageFlags flags, PSemaphore semaphore) {
|
||||
bindResource(semaphore->getCurrentSemaphore());
|
||||
waitSemaphores.add(semaphore);
|
||||
// Capture the concrete VkSemaphore NOW. The wrapper's current handle may
|
||||
// rotate before submit; waiting on a re-resolved handle at submit time can
|
||||
// target a semaphore that is also signalled in this same submit (or one with
|
||||
// no outstanding signal), violating VUID-vkQueueSubmit-pWaitSemaphores-03238.
|
||||
PSemaphoreHandle current = semaphore->getCurrentSemaphore();
|
||||
bindResource(current);
|
||||
waitHandles.add(current->getHandle());
|
||||
waitFlags.add(flags);
|
||||
}
|
||||
|
||||
@@ -137,6 +143,13 @@ void Command::checkFence() {
|
||||
}
|
||||
signalSemaphore->resolveSignal();
|
||||
boundResources.clear();
|
||||
// Clear accumulated wait state so a recycled command buffer does not
|
||||
// re-wait on stale (already-consumed) semaphores from a prior frame.
|
||||
// A binary semaphore's signal->wait pair is single-use; waiting on a
|
||||
// handle whose signal was already consumed violates
|
||||
// VUID-vkQueueSubmit-pWaitSemaphores-03238.
|
||||
waitHandles.clear();
|
||||
waitFlags.clear();
|
||||
graphics->getDestructionManager()->notifyCommandComplete();
|
||||
state = State::Init;
|
||||
}
|
||||
|
||||
@@ -48,7 +48,7 @@ class Command {
|
||||
VkCommandBuffer handle;
|
||||
PRenderPass boundRenderPass;
|
||||
PFramebuffer boundFramebuffer;
|
||||
Array<PSemaphore> waitSemaphores;
|
||||
Array<VkSemaphore> waitHandles;
|
||||
Array<VkPipelineStageFlags> waitFlags;
|
||||
Array<ORenderCommand> executingRenders;
|
||||
Array<OComputeCommand> executingComputes;
|
||||
|
||||
@@ -99,7 +99,7 @@ DescriptorPool::DescriptorPool(PGraphics graphics, PDescriptorLayout layout)
|
||||
Map<VkDescriptorType, uint32> perTypeSizes;
|
||||
for (uint32 i = 0; i < layout->bindings.size(); ++i) {
|
||||
auto& binding = layout->bindings[i];
|
||||
perTypeSizes[binding.descriptorType] += 512;
|
||||
perTypeSizes[binding.descriptorType] += 2048;
|
||||
}
|
||||
Array<VkDescriptorPoolSize> poolSizes;
|
||||
for (const auto& [type, num] : perTypeSizes) {
|
||||
|
||||
@@ -933,6 +933,7 @@ void Graphics::pickPhysicalDevice() {
|
||||
features.get<VkPhysicalDeviceVulkan12Features>().storageBuffer8BitAccess = true;
|
||||
features.get<VkPhysicalDeviceVulkan12Features>().shaderInt8 = true;
|
||||
features.get<VkPhysicalDeviceVulkan12Features>().uniformAndStorageBuffer8BitAccess = true;
|
||||
features.get<VkPhysicalDeviceVulkan12Features>().runtimeDescriptorArray = true;
|
||||
|
||||
rayTracingFeatures.get<VkPhysicalDeviceAccelerationStructureFeaturesKHR>().accelerationStructure = true;
|
||||
|
||||
@@ -1023,7 +1024,11 @@ void Graphics::createDevice(GraphicsInitializer initializer) {
|
||||
updateQueueInfo(familyIndex, computeQueueInfo, numQueuesForFamily);
|
||||
}
|
||||
}
|
||||
if ((currProps.queueFlags ^ VK_QUEUE_TRANSFER_BIT) == 0) {
|
||||
// a queue family is a valid transfer queue if it supports the transfer bit at all
|
||||
// (previously `(flags ^ TRANSFER) == 0`, which only matched pure-transfer families
|
||||
// that don't exist on standard drivers: no transfer queue was ever created, so
|
||||
// every vkQueueSubmit on the transfer queue path failed with VK_ERROR_DEVICE_LOST)
|
||||
if (currProps.queueFlags & VK_QUEUE_TRANSFER_BIT) {
|
||||
updateQueueInfo(familyIndex, transferQueueInfo, numQueuesForFamily);
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
#include "Command.h"
|
||||
#include "Enums.h"
|
||||
#include "Graphics.h"
|
||||
#include "Graphics/Vulkan/Resources.h"
|
||||
#include <mutex>
|
||||
|
||||
using namespace Seele;
|
||||
@@ -25,16 +26,23 @@ void Queue::submitCommandBuffer(PCommand command, const Array<VkSemaphore>& sign
|
||||
VkCommandBuffer cmdHandle = command->handle;
|
||||
|
||||
Array<VkSemaphore> waitSemaphores;
|
||||
// wait semaphores get bound to the cmd when they are added
|
||||
// and unbound when the command completes
|
||||
for (PSemaphore semaphore : command->waitSemaphores) {
|
||||
waitSemaphores.add(semaphore->getHandle());
|
||||
// Use the handles captured at record time (command->waitHandles). Re-resolving
|
||||
// the wrapper's current handle here would let the wait target drift if the
|
||||
// wrapper rotated between record and submit, potentially onto a semaphore that
|
||||
// is also signalled in this same submit.
|
||||
for (VkSemaphore waitHandle : command->waitHandles) {
|
||||
waitSemaphores.add(waitHandle);
|
||||
// std::cout << "Semaphore " << waitHandle << " waited on by cmd " << command->getHandle() << std::endl;
|
||||
}
|
||||
|
||||
// for (VkSemaphore signalSemaphore : signalSemaphores) {
|
||||
// std::cout << "Semaphore " << signalSemaphore << " is signalled by cmd " << command->getHandle() << std::endl;
|
||||
// }
|
||||
|
||||
VkSubmitInfo submitInfo = {
|
||||
.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
|
||||
.pNext = nullptr,
|
||||
.waitSemaphoreCount = static_cast<uint32>(command->waitSemaphores.size()),
|
||||
.waitSemaphoreCount = static_cast<uint32>(command->waitHandles.size()),
|
||||
.pWaitSemaphores = waitSemaphores.data(),
|
||||
.pWaitDstStageMask = command->waitFlags.data(),
|
||||
.commandBufferCount = 1,
|
||||
@@ -46,7 +54,7 @@ void Queue::submitCommandBuffer(PCommand command, const Array<VkSemaphore>& sign
|
||||
command->fence->submit();
|
||||
command->state = Command::State::Submit;
|
||||
command->waitFlags.clear();
|
||||
command->waitSemaphores.clear();
|
||||
command->waitHandles.clear();
|
||||
|
||||
if (waitIdleOnSubmit) {
|
||||
command->fence->wait(1000 * 1000ull);
|
||||
|
||||
@@ -213,6 +213,10 @@ TextureHandle::TextureHandle(PGraphics graphics, VkImageViewType viewType, const
|
||||
// When loading a texture from a file, we will almost always use it as a texture map for fragment shaders
|
||||
changeLayout(Gfx::SE_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_ACCESS_TRANSFER_READ_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT,
|
||||
VK_ACCESS_SHADER_READ_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT);
|
||||
// The copy above is only enqueued on a command buffer; it must actually be
|
||||
// submitted to the GPU before any consumer (the UI pass, a test's download,
|
||||
// etc.) can read the image. Without this the image is still all zeros.
|
||||
commandPool->submitCommands();
|
||||
graphics->getDestructionManager()->queueResourceForDestruction(std::move(stagingAlloc));
|
||||
}
|
||||
}
|
||||
@@ -359,6 +363,14 @@ void TextureHandle::download(uint32 mipLevel, uint32 arrayLayer, uint32 face, Ar
|
||||
cmdBuffer->bindResource(PBufferAllocation(stagingAlloc));
|
||||
changeLayout(prevLayout, VK_ACCESS_TRANSFER_READ_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_MEMORY_READ_BIT,
|
||||
VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT);
|
||||
// The copy above is only enqueued; the staging buffer is still all zeros until the
|
||||
// command actually runs. Submit it and wait on its fence before mapping, or the read
|
||||
// below would race the GPU and return a blank texture. (submitCommands() submits the
|
||||
// current command and rotates to a fresh one, exactly like the upload path in the
|
||||
// TextureHandle constructor.)
|
||||
PCommandPool pool = graphics->getQueueCommands(owner);
|
||||
pool->submitCommands();
|
||||
cmdBuffer->waitForCommand();
|
||||
VK_CHECK(vmaMapMemory(graphics->getAllocator(), stagingAlloc->allocation, &data));
|
||||
buffer.resize(imageSize);
|
||||
std::memcpy(buffer.data(), data, buffer.size());
|
||||
|
||||
@@ -206,7 +206,7 @@ void Seele::Vulkan::Window::beginFrame() {
|
||||
// The image was reacquired, so the previous presentation using this image's
|
||||
// renderDone semaphore has completed and it can be safely reused
|
||||
renderingDoneSemaphores[currentImageIndex]->resolveSignal();
|
||||
graphics->getGraphicsCommands()->getCommands()->waitForSemaphore(VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
|
||||
graphics->getGraphicsCommands()->getCommands()->waitForSemaphore(VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
|
||||
imageAvailableSemaphores[currentSemaphoreIndex]);
|
||||
static double start = glfwGetTime();
|
||||
double end = glfwGetTime();
|
||||
@@ -222,6 +222,7 @@ void Seele::Vulkan::Window::endFrame() {
|
||||
renderingDoneSemaphores[currentImageIndex]->rotateSemaphore();
|
||||
graphics->getGraphicsCommands()->submitCommands(renderingDoneSemaphores[currentImageIndex]);
|
||||
VkSemaphore renderDoneHandle = renderingDoneSemaphores[currentImageIndex]->getHandle();
|
||||
VkResult swapChainResult;
|
||||
VkPresentInfoKHR presentInfo = {
|
||||
.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR,
|
||||
.pNext = nullptr,
|
||||
@@ -230,16 +231,15 @@ void Seele::Vulkan::Window::endFrame() {
|
||||
.swapchainCount = 1,
|
||||
.pSwapchains = &swapchain,
|
||||
.pImageIndices = ¤tImageIndex,
|
||||
.pResults = nullptr,
|
||||
.pResults = &swapChainResult,
|
||||
};
|
||||
VkResult r = vkQueuePresentKHR(graphics->getGraphicsCommands()->getQueue()->getHandle(), &presentInfo);
|
||||
if (r == VK_SUCCESS) {
|
||||
} else if (r == VK_ERROR_OUT_OF_DATE_KHR || r == VK_SUBOPTIMAL_KHR) {
|
||||
// std::cout << "Semaphore " << renderDoneHandle << " signals present for image index " << currentImageIndex << std::endl;
|
||||
if (swapChainResult == VK_ERROR_OUT_OF_DATE_KHR || swapChainResult == VK_SUBOPTIMAL_KHR || r == VK_ERROR_OUT_OF_DATE_KHR || r == VK_SUBOPTIMAL_KHR) {
|
||||
createSwapChain();
|
||||
} else {
|
||||
VK_CHECK(r);
|
||||
}
|
||||
renderingDoneSemaphores[currentImageIndex]->encodeSignal();
|
||||
currentSemaphoreIndex = (currentSemaphoreIndex + 1) % Gfx::numFramesBuffered;
|
||||
currentFrameIndex = currentSemaphoreIndex;
|
||||
// graphics->waitDeviceIdle();
|
||||
|
||||
@@ -3,6 +3,8 @@ target_sources(Engine
|
||||
Attributes.h
|
||||
Element.h
|
||||
Element.cpp
|
||||
FlexLayout.h
|
||||
FlexLayout.cpp
|
||||
System.h
|
||||
System.cpp
|
||||
)
|
||||
@@ -12,6 +14,7 @@ target_sources(Engine
|
||||
FILES
|
||||
Attributes.h
|
||||
Element.h
|
||||
FlexLayout.h
|
||||
System.h
|
||||
)
|
||||
|
||||
|
||||
+73
-110
@@ -4,6 +4,7 @@
|
||||
#include "MinimalEngine.h"
|
||||
#include "UI/Style/Style.h"
|
||||
#include "UI/Style/Theme.h"
|
||||
#include "UI/FlexLayout.h"
|
||||
#include <type_traits>
|
||||
|
||||
namespace Seele {
|
||||
@@ -19,12 +20,13 @@ struct UIRender {
|
||||
uint32 z;
|
||||
uint32 level;
|
||||
PElement element; // back-ref for input hit-testing
|
||||
// glyph-only (text): the glyph texture is backgroundTexture, this is the
|
||||
// per-glyph rect in *atlas* space (0..1) so the pass can emit a glyph quad
|
||||
bool isGlyph = false;
|
||||
// UV rect for textured quads; glyphs carry their rect in the font's per-size
|
||||
// atlas (backgroundTexture = the atlas), full-rect (0,0,1,1) for plain images.
|
||||
// A "glyph quad" is nothing special: a quad with a texture and a UV rect.
|
||||
Vector2 uvOffset = Vector2(0);
|
||||
Vector2 uvSize = Vector2(0);
|
||||
Vector2 uvSize = Vector2(1);
|
||||
};
|
||||
DECLARE_REF(Element)
|
||||
class Element {
|
||||
public:
|
||||
// the System walks the retained tree (style/layout/input/render) and needs to read
|
||||
@@ -35,16 +37,19 @@ class Element {
|
||||
// yields the pointer; ownership/lifetime for the demo is the caller's concern (the
|
||||
// engine does not free them here).
|
||||
explicit Element(Attributes attr) : attr(attr) {}
|
||||
Element(Attributes attr, std::initializer_list<Element*> children_) : attr(attr) {
|
||||
for (auto c : children_) {
|
||||
Element(Attributes attr, std::initializer_list<OElement> children_) : attr(attr) {
|
||||
// children is Array<OElement> (move-only), so it can't be move-constructed
|
||||
// from the initializer list (initializer_list elements are const). Add each
|
||||
// child explicitly — add() moves the OwningPtr in, transferring ownership.
|
||||
for (const OElement& c : children_) {
|
||||
if (c != nullptr) {
|
||||
c->setParent(this);
|
||||
children.add(c);
|
||||
children.add(std::move(const_cast<OElement&>(c)));
|
||||
children.back()->setParent(this);
|
||||
}
|
||||
}
|
||||
}
|
||||
virtual ~Element();
|
||||
void setParent(Element* p) { parent = p; }
|
||||
void setParent(PElement p) { parent = p; }
|
||||
|
||||
// resolves the inherited style + this element's static template classes against the theme.
|
||||
// only re-run for this element when style.dirty or the theme changed.
|
||||
@@ -62,10 +67,50 @@ class Element {
|
||||
// explicit mutation entry point: applies runtime overrides, then re-styles the dirty subtree
|
||||
void markDirty() {
|
||||
style.dirty = true;
|
||||
if (parent) {
|
||||
if (parent != nullptr) {
|
||||
parent->markDirty();
|
||||
}
|
||||
}
|
||||
// public theme handle: FlexLayout needs to re-shape Text content after a theme change
|
||||
// (fonts are per-theme) without a friend declaration (see FlexLayout.h).
|
||||
const Theme& getTheme() const { return theme; }
|
||||
void setTheme(const Theme& t) { theme = t; }
|
||||
// CPU-side intrinsic (natural) size override. Layout uses this for an Auto axis
|
||||
// instead of a font (Text's measured size is the real case; this hook lets unit
|
||||
// tests supply a known natural size without loading a font). It only overrides the
|
||||
// *Auto* axes; an explicit Width_/Height_ still wins (applyStyle only writes the
|
||||
// Auto branches, and layout prefers an explicit size over the intrinsic).
|
||||
void setIntrinsicSize(float w, float h) {
|
||||
intrinsicW = (style.widthType == DimensionType::Auto) ? w : 0.0f;
|
||||
intrinsicH = (style.heightType == DimensionType::Auto) ? h : 0.0f;
|
||||
}
|
||||
// the natural main/cross size to use when the style axis is Auto (0 if explicit).
|
||||
float intrinsicMain(bool mainIsX) const { return mainIsX ? intrinsicW : intrinsicH; }
|
||||
float intrinsicCross(bool mainIsX) const { return mainIsX ? intrinsicH : intrinsicW; }
|
||||
// layout-state accessors. The free-function layout engine (FlexLayout) and the
|
||||
// CPU unit tests need to read/write `position`+`dimensions` and read `children`
|
||||
// without a friend declaration (FlexLayout is a namespace, not a class, and the
|
||||
// tests are a separate TU).
|
||||
const Array<OElement>& getChildren() const { return children; }
|
||||
void setLayout(const Vector2& pos, const Vector2& dims) {
|
||||
position = pos;
|
||||
dimensions = dims;
|
||||
}
|
||||
const Vector2& getLayoutPosition() const { return position; }
|
||||
const Vector2& getLayoutDimensions() const { return dimensions; }
|
||||
void setLayoutPosition(const Vector2& p) { position = p; }
|
||||
void setLayoutDimensions(const Vector2& d) { dimensions = d; }
|
||||
// accessors for the layout engine and the CPU unit tests. FlexLayout is a
|
||||
// namespace (not a class) so it cannot be a `friend`, and the tests are a
|
||||
// separate TU — both need to reach `style`/`parent`/`intrinsic`/layout state.
|
||||
// `style` is exposed mutably because the unit tests set runtime style fields
|
||||
// (min/max, position, display) before re-resolving; the .cpp only reads it.
|
||||
Style& getStyle() { return style; }
|
||||
const Style& getStyle() const { return style; }
|
||||
PElement getParent() const { return parent; }
|
||||
float getIntrinsicW() const { return intrinsicW; }
|
||||
float getIntrinsicH() const { return intrinsicH; }
|
||||
|
||||
// applies runtime style overrides (the data-driven mutation layer)
|
||||
virtual void applyOverrides() {
|
||||
// default: no-op; interactive elements override this to reflect hover/focus/etc.
|
||||
@@ -82,97 +127,12 @@ class Element {
|
||||
virtual void setFocused(bool focused) { (void)focused; }
|
||||
virtual bool isFocusable() const { return attr.focusable; }
|
||||
|
||||
// calculates the relative positions of the child elements for the applied layout style
|
||||
virtual void layout(UVector2 parentSize) {
|
||||
if (style.hidden) {
|
||||
return;
|
||||
}
|
||||
if (style.maxWidthType == DimensionType::Auto) {
|
||||
maxDimensions.x = (float)parentSize.x;
|
||||
}
|
||||
if (style.maxHeightType == DimensionType::Auto) {
|
||||
maxDimensions.y = (float)parentSize.y;
|
||||
}
|
||||
if (style.widthType == DimensionType::Pixel) {
|
||||
dimensions.x = style.width;
|
||||
} else if (style.widthType == DimensionType::Percent) {
|
||||
dimensions.x = parentSize.x * style.width / 100.0f;
|
||||
}
|
||||
if (style.heightType == DimensionType::Pixel) {
|
||||
dimensions.y = style.height;
|
||||
} else if (style.heightType == DimensionType::Percent) {
|
||||
dimensions.y = parentSize.y * style.height / 100.0f;
|
||||
}
|
||||
|
||||
for (auto& child : children) {
|
||||
child->layout(maxDimensions - Vector2(style.marginLeft + style.marginRight, style.marginTop + style.marginBottom));
|
||||
}
|
||||
switch (style.innerDisplay) {
|
||||
case InnerDisplayType::Flow:
|
||||
flowLayout();
|
||||
break;
|
||||
default:break;
|
||||
}
|
||||
}
|
||||
// normal flow of the elements, inline elements go left to right, blocks get their own new lines
|
||||
void flowLayout() {
|
||||
// use a cursor going from left to right, top to bottom, starting at padding
|
||||
Vector2 cursor = Vector2(style.paddingLeft, style.paddingTop);
|
||||
uint32 lineHeight = 0;
|
||||
for (auto& child : children) {
|
||||
if (child->style.hidden) {
|
||||
continue;
|
||||
}
|
||||
// inline elements flow left to right
|
||||
if (child->style.outerDisplay == OuterDisplayType::Inline) {
|
||||
// only static and relative elements actually reserve
|
||||
if (child->style.position == PositionType::Static || child->style.position == PositionType::Relative) {
|
||||
// create a new line in case the element doesnt fit on the current one anymore,
|
||||
// but keep in current line in case we are still at the start, as a new line wouldnt help here
|
||||
if (cursor.x + child->dimensions.x > maxDimensions.x - child->style.left && cursor.x != 0) {
|
||||
cursor.x = (float)style.paddingLeft;
|
||||
cursor.y += lineHeight;
|
||||
lineHeight = 0;
|
||||
}
|
||||
// todo: border
|
||||
child->position.x = cursor.x + child->style.marginLeft;
|
||||
child->position.y = cursor.y + child->style.marginTop;
|
||||
cursor.x = child->position.x + child->dimensions.x;
|
||||
// apply offsets after updating the cursor for relative elements
|
||||
if (child->style.position == PositionType::Relative) {
|
||||
child->position.x += child->style.left;
|
||||
child->position.y += child->style.top;
|
||||
}
|
||||
lineHeight = std::max(lineHeight, child->style.lineHeight);
|
||||
}
|
||||
// block elements always get their own lines, like paragraphs
|
||||
} else if (child->style.outerDisplay == OuterDisplayType::Block) {
|
||||
// static and relative require space to be created for the elements
|
||||
if (child->style.position == PositionType::Static || child->style.position == PositionType::Relative) {
|
||||
// create a new line in case we are not already at one
|
||||
if (cursor.x != 0) {
|
||||
cursor.x = (float)style.paddingLeft;
|
||||
cursor.y += lineHeight;
|
||||
}
|
||||
child->position.x = cursor.x + child->style.marginLeft;
|
||||
child->position.y = cursor.y + child->style.marginTop;
|
||||
// new line after block
|
||||
cursor.x = 0;
|
||||
cursor.y = child->position.y + child->dimensions.y;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (style.widthType == DimensionType::Auto) {
|
||||
dimensions.x = cursor.x + style.paddingRight;
|
||||
}
|
||||
if (style.heightType == DimensionType::Auto) {
|
||||
dimensions.y = lineHeight + cursor.y + style.paddingBottom;
|
||||
}
|
||||
}
|
||||
virtual Array<UIRender> render(Vector2 anchor, uint32 level) {
|
||||
Array<UIRender> result;
|
||||
if (!style.hidden && style.outerDisplay != OuterDisplayType::Hidden) {
|
||||
result.add(UIRender{
|
||||
if (style.display == Display::Hidden) {
|
||||
return result;
|
||||
}
|
||||
result.add(UIRender{
|
||||
.backgroundColor = style.backgroundColor,
|
||||
.position = position + anchor,
|
||||
.dimensions = dimensions,
|
||||
@@ -180,28 +140,31 @@ class Element {
|
||||
.level = level,
|
||||
.element = this,
|
||||
});
|
||||
}
|
||||
for (auto& child : children) {
|
||||
for (const auto& render : child->render(position + anchor, level+1)) {
|
||||
for (const auto& render : child->render(position + anchor, level + 1)) {
|
||||
result.add(render);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
protected:
|
||||
Attributes attr;
|
||||
PElement parent = nullptr;
|
||||
Array<OElement> children;
|
||||
// set by the System when the theme changed; forces a one-time full re-style
|
||||
bool themeChanged = false;
|
||||
// the theme this element was last styled against. the System sets it before
|
||||
// calcStyle so FlexLayout can re-shape Text on a theme change without holding a friend.
|
||||
Theme theme = Theme{};
|
||||
Style style;
|
||||
Vector2 maxDimensions = Vector2(0);
|
||||
// calculated position relative to parent
|
||||
Vector2 position = Vector2(0);
|
||||
// calculated dimensions in pixels after layouting
|
||||
Vector2 dimensions = Vector2(0);
|
||||
|
||||
protected:
|
||||
Attributes attr;
|
||||
Element* parent = nullptr;
|
||||
// raw, non-owning (see the ctor comment); matches the pre-existing call sites
|
||||
Array<Element*> children;
|
||||
// set by the System when the theme changed; forces a one-time full re-style
|
||||
bool themeChanged = false;
|
||||
// natural (intrinsic) size, used only for Auto axes (see setIntrinsicSize).
|
||||
float intrinsicW = 0.0f;
|
||||
float intrinsicH = 0.0f;
|
||||
};
|
||||
DEFINE_REF(Element)
|
||||
} // namespace UI
|
||||
|
||||
@@ -13,7 +13,28 @@ class Div : public Element {
|
||||
virtual ~Div() {}
|
||||
virtual void applyStyle(Style parentStyle, const Theme& theme) override {
|
||||
style = parentStyle;
|
||||
style.outerDisplay = OuterDisplayType::Block;
|
||||
// CSS non-inherited properties: reset to defaults before applying template
|
||||
// classes. width/height, min/max, margin/padding, gap, position offsets, and
|
||||
// per-item flex properties (grow/shrink/order/basis/alignSelf) are all
|
||||
// non-inherited in CSS — a child's Div classes opt in explicitly.
|
||||
// Inherited (keep from parent): display, direction, wrap, justify, items,
|
||||
// content, z, colors, font, lineHeight, fontSize, fontWeight.
|
||||
style.widthType = DimensionType::Auto; style.width = 0;
|
||||
style.minWidthType = DimensionType::Auto; style.minWidth = 0;
|
||||
style.maxWidthType = DimensionType::Auto; style.maxWidth = 0;
|
||||
style.heightType = DimensionType::Auto; style.height = 0;
|
||||
style.minHeightType = DimensionType::Auto; style.minHeight = 0;
|
||||
style.maxHeightType = DimensionType::Auto; style.maxHeight = 0;
|
||||
style.paddingTop = 0; style.paddingBottom = 0;
|
||||
style.paddingLeft = 0; style.paddingRight = 0;
|
||||
style.marginTop = 0; style.marginBottom = 0;
|
||||
style.marginLeft = 0; style.marginRight = 0;
|
||||
style.gap = 0;
|
||||
style.top = 0; style.bottom = 0; style.left = 0; style.right = 0;
|
||||
style.position = Position::Static;
|
||||
style.grow = 0.f; style.shrink = 1.f;
|
||||
style.order = 0; style.alignSelfOverride = -1.f;
|
||||
style.basisType = DimensionType::Auto; style.basis = 0.f;
|
||||
(classes::apply(style, theme), ...);
|
||||
}
|
||||
private:
|
||||
|
||||
@@ -15,7 +15,6 @@ class Panel : public Div<classes...> {
|
||||
virtual void applyStyle(Style parentStyle, const Theme& theme) override {
|
||||
// start from the panel chrome, then let the user's classes win
|
||||
style = parentStyle;
|
||||
style.outerDisplay = OuterDisplayType::Block;
|
||||
style.backgroundColor = theme.color(ColorToken::Gray900);
|
||||
style.textColor = theme.color(ColorToken::White);
|
||||
uint32 pad = theme.spacing(8);
|
||||
|
||||
@@ -61,11 +61,16 @@ class Text : public Element {
|
||||
if (style.heightType == UI::DimensionType::Auto) {
|
||||
style.height = h;
|
||||
}
|
||||
// the measured size is also the element's natural size: layout measures
|
||||
// through Element::intrinsicW/H (set here) instead of trusting a stale
|
||||
// style.width/height that a later setText() invalidation may have left behind.
|
||||
intrinsicW = w;
|
||||
intrinsicH = h;
|
||||
}
|
||||
|
||||
virtual Array<UIRender> render(Vector2 anchor, uint32 level) override {
|
||||
Array<UIRender> result;
|
||||
if (style.hidden || style.outerDisplay == OuterDisplayType::Hidden) {
|
||||
if (style.display == Display::Hidden) {
|
||||
return result;
|
||||
}
|
||||
Vector2 pos = position + anchor;
|
||||
@@ -79,7 +84,7 @@ class Text : public Element {
|
||||
.level = level,
|
||||
.element = this,
|
||||
});
|
||||
// text: one render quad per shaped glyph, carrying its atlas rect
|
||||
// text: one quad per shaped glyph, carrying its rect in the font's per-size atlas
|
||||
if (style.fontFamily != nullptr) {
|
||||
for (auto& g : glyphs) {
|
||||
result.add(UIRender{
|
||||
@@ -88,11 +93,13 @@ class Text : public Element {
|
||||
.position = pos + Vector2(g.position.x, g.position.y),
|
||||
.dimensions = Vector2(g.dimensions.x, g.dimensions.y),
|
||||
.z = style.z,
|
||||
.level = level,
|
||||
// level+1: a glyph must sit strictly in FRONT of its parent's own quad
|
||||
// (same render.level => same depth value => GREATER-or-EQUAL test fails
|
||||
// against the parent's already-written depth, and the glyph is culled).
|
||||
.level = level + 1,
|
||||
.element = this,
|
||||
.isGlyph = true,
|
||||
.uvOffset = Vector2(0),
|
||||
.uvSize = Vector2(1),
|
||||
.uvOffset = g.uvOffset,
|
||||
.uvSize = g.uvSize,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,802 @@
|
||||
#include "UI/FlexLayout.h"
|
||||
// the full Element type (the header only forward-declares it to avoid a circular
|
||||
// include: Element.h already includes FlexLayout.h). the free functions defined
|
||||
// here dereference Element, so we need the complete definition.
|
||||
#include "UI/Element.h"
|
||||
#include <algorithm>
|
||||
#include <cstdint>
|
||||
#include <limits>
|
||||
#include <vector>
|
||||
|
||||
// flexbox is the sole layout mode (see FlexLayout.h for the model and the coordinate
|
||||
// convention: an element's `position`/`dimensions` are in PARENT space; a child's
|
||||
// containing box is the parent's dimensions; margins are honored on both axes and the
|
||||
// align/justify math works in the parent's *content* box).
|
||||
//
|
||||
// `position`/`dimensions` are concrete x/y and direction-independent — only the flow
|
||||
// ORDER within a container and the start/end direction depend on `direction`. Size
|
||||
// resolution is axis-agnostic (width and height are computed independently); the
|
||||
// main-axis flow uses explicit x/y branches.
|
||||
//
|
||||
// A size is resolved in this order: explicit (Pixel/Percent) beats content; Auto
|
||||
// falls back to the content measurement (the max over flow children of the child's
|
||||
// footprint + gaps, or the element's intrinsic size for a leaf); min/max then clamp.
|
||||
// A child's percent size resolves against its *parent's* content box (never the
|
||||
// grandparent). A nested container's real size is finalized when the place phase
|
||||
// recurses into it; the parent's Auto size is the max over its children's
|
||||
// explicit/intrinsic footprints (exact for the demo, where containers are
|
||||
// explicit-sized or hold leaves).
|
||||
|
||||
namespace Seele {
|
||||
namespace UI {
|
||||
namespace FlexLayout {
|
||||
|
||||
namespace {
|
||||
|
||||
// the flow set of `parent`: children that are visible (not Hidden) and not Absolute,
|
||||
// as (index, order) pairs. measure and place both iterate this, so their index
|
||||
// spaces line up. `order` is read here (not via stable_sort) because the same
|
||||
// sorted vector is reused in place.
|
||||
struct Flow {
|
||||
std::vector<size_t> idx;
|
||||
std::vector<int32> order;
|
||||
static void build(PElement parent, Flow& f) {
|
||||
f.idx.clear();
|
||||
f.order.clear();
|
||||
const auto& kids = parent->getChildren();
|
||||
for (size_t i = 0; i < kids.size(); i++) {
|
||||
PElement c = kids[i];
|
||||
if (c == nullptr || c->getStyle().display == Display::Hidden) {
|
||||
continue;
|
||||
}
|
||||
if (c->getStyle().position == Position::Absolute) {
|
||||
continue; // removed from the flow; positioned separately
|
||||
}
|
||||
f.idx.push_back(i);
|
||||
f.order.push_back(c->getStyle().order);
|
||||
}
|
||||
// sort the parallel vectors together: collect (order, childIndex) pairs,
|
||||
// sort them, then write the sorted result back into idx/order in lockstep.
|
||||
// sorting f.idx alone would break the index correspondence with f.order
|
||||
// (the comparator would read f.order[a] where a is a child index, not a
|
||||
// position in the filtered list — out-of-bounds when children are skipped).
|
||||
std::vector<std::pair<int32, size_t>> pairs;
|
||||
pairs.reserve(f.idx.size());
|
||||
for (size_t k = 0; k < f.idx.size(); k++) {
|
||||
pairs.emplace_back(f.order[k], f.idx[k]);
|
||||
}
|
||||
std::sort(pairs.begin(), pairs.end(),
|
||||
[](const auto& a, const auto& b) { return a.first < b.first; });
|
||||
for (size_t k = 0; k < pairs.size(); k++) {
|
||||
f.order[k] = pairs[k].first;
|
||||
f.idx[k] = pairs[k].second;
|
||||
}
|
||||
}
|
||||
size_t size() const { return idx.size(); }
|
||||
size_t operator[](size_t k) const { return idx[k]; }
|
||||
};
|
||||
|
||||
// resolve a DimensionType/float pair against a containing size. Auto -> 0 (the caller
|
||||
// supplies the content measurement for the Auto case).
|
||||
static float resolvePx(DimensionType t, float v, float cont) {
|
||||
if (t == DimensionType::Pixel) {
|
||||
return v;
|
||||
}
|
||||
if (t == DimensionType::Percent) {
|
||||
return cont * v / 100.0f;
|
||||
}
|
||||
return 0.0f;
|
||||
}
|
||||
|
||||
// the child's main-axis *footprint* for the parent's content measurement: an explicit
|
||||
// (px/%) size resolves against the parent's content box; an Auto (or nested-container)
|
||||
// child contributes its intrinsic size (0 for a container, since its real size is
|
||||
// finalized when the place phase recurses into it). Includes main-axis margins.
|
||||
static float childMainFootprint(PElement c, const FlexLayout::Axis& axis, float parentContentMain) {
|
||||
const Style& s = c->getStyle();
|
||||
bool isX = axis.mainIsX;
|
||||
float size;
|
||||
if (isX) {
|
||||
if (s.widthType != DimensionType::Auto) {
|
||||
size = std::max(0.0f, resolvePx(s.widthType, s.width, parentContentMain));
|
||||
} else {
|
||||
// Auto main: use intrinsic. setIntrinsicSize already zeros this when
|
||||
// the axis is explicit (it only stores when widthType==Auto), so an
|
||||
// explicit-width item returns 0 here automatically.
|
||||
size = c->getIntrinsicW();
|
||||
}
|
||||
return size + (float)(s.marginLeft + s.marginRight);
|
||||
} else {
|
||||
if (s.heightType != DimensionType::Auto) {
|
||||
size = std::max(0.0f, resolvePx(s.heightType, s.height, parentContentMain));
|
||||
} else {
|
||||
size = c->getIntrinsicH();
|
||||
}
|
||||
return size + (float)(s.marginTop + s.marginBottom);
|
||||
}
|
||||
}
|
||||
|
||||
// the element's content measurement on one concrete axis (x or y): the max over the
|
||||
// flow children of their footprints (resolved against the element's *content* box on
|
||||
// that axis) + gaps, or the element's intrinsic size for a leaf. This is the Auto
|
||||
// fallback for the element's own size.
|
||||
static float contentAxis(bool isX, PElement el, const Flow& flow, const Array<OElement>& kids) {
|
||||
if (flow.size() == 0) {
|
||||
return isX ? el->getIntrinsicW() : el->getIntrinsicH();
|
||||
}
|
||||
// the percent reference for children's main-axis sizes is the *parent's* content
|
||||
// box (the containing block). the element's own dimensions may be stale (from a
|
||||
// prior layoutElement run), so we must NOT use them. for a root element (no
|
||||
// parent), the reference is 0 (percent sizes on a root with no containing box
|
||||
// are degenerate; the caller should use px).
|
||||
float parentContent = 0.0f;
|
||||
PElement parent = el->getParent();
|
||||
if (parent != nullptr) {
|
||||
if (isX) {
|
||||
parentContent = std::max(0.0f, (float)parent->getLayoutDimensions().x - (float)(parent->getStyle().paddingLeft + parent->getStyle().paddingRight));
|
||||
} else {
|
||||
parentContent = std::max(0.0f, (float)parent->getLayoutDimensions().y - (float)(parent->getStyle().paddingTop + parent->getStyle().paddingBottom));
|
||||
}
|
||||
}
|
||||
float m = 0.0f;
|
||||
for (size_t k = 0; k < flow.size(); k++) {
|
||||
PElement c = kids[flow[k]];
|
||||
m = std::max(m, childMainFootprint(c, isX ? Axis{true, false} : Axis{false, false}, parentContent));
|
||||
}
|
||||
float gap = (float)el->getStyle().gap;
|
||||
if (flow.size() > 1 && gap > 0.0f) {
|
||||
m += (float)(flow.size() - 1) * gap;
|
||||
}
|
||||
return m;
|
||||
}
|
||||
|
||||
// resolve one concrete axis of the element's own size: explicit wins; Auto falls back
|
||||
// to the content measurement; min/max then clamp. Returns the final axis size.
|
||||
static float resolveAxisSize(bool isX, PElement el, float content, const Style& s) {
|
||||
// the percent reference for this element's own size is its *parent's* box (the
|
||||
// containing block). the element's own dimensions are finalized before this is
|
||||
// called (layoutElement sets them before recursing into placeFlowChildren), so
|
||||
// for non-root elements we can use the parent's box. for a root element there
|
||||
// is no parent — percent sizes are degenerate (0), use px or Auto.
|
||||
float parentBox = 0.0f;
|
||||
if (el->getParent() != nullptr) {
|
||||
parentBox = isX ? (float)el->getParent()->getLayoutDimensions().x : (float)el->getParent()->getLayoutDimensions().y;
|
||||
} else {
|
||||
// root: no containing box; percent sizes resolve against 0 (degenerate).
|
||||
// the caller (layoutRoot) handles the root's own size separately.
|
||||
parentBox = 0.0f;
|
||||
}
|
||||
float explicitSize = isX ? resolvePx(s.widthType, s.width, parentBox)
|
||||
: resolvePx(s.heightType, s.height, parentBox);
|
||||
float size = (isX && s.widthType != DimensionType::Auto) || (!isX && s.heightType != DimensionType::Auto) ? explicitSize : content;
|
||||
float mn = isX ? (s.minWidthType == DimensionType::Auto ? 0.0f : resolvePx(s.minWidthType, s.minWidth, parentBox))
|
||||
: (s.minHeightType == DimensionType::Auto ? 0.0f : resolvePx(s.minHeightType, s.minHeight, parentBox));
|
||||
float mx = isX ? (s.maxWidthType == DimensionType::Auto ? 1e9f : resolvePx(s.maxWidthType, s.maxWidth, parentBox))
|
||||
: (s.maxHeightType == DimensionType::Auto ? 1e9f : resolvePx(s.maxHeightType, s.maxHeight, parentBox));
|
||||
if (size < mn) size = mn;
|
||||
if (size > mx) size = mx;
|
||||
if (size < 0.0f) size = 0.0f;
|
||||
return size;
|
||||
}
|
||||
|
||||
// the element's cross-axis footprint as a flex item of its parent: explicit (px/%)
|
||||
// resolves against the parent's content box on the cross axis; Auto falls back to the
|
||||
// element's intrinsic cross size. includes cross-axis margins. used for the parent's
|
||||
// Auto cross measurement (max over children) and for non-stretch item sizing.
|
||||
static float childCrossFootprint(PElement c, const FlexLayout::Axis& axis, float parentContentCross) {
|
||||
const Style& s = c->getStyle();
|
||||
bool isX = axis.mainIsX; // cross axis is the other one
|
||||
float size;
|
||||
if (isX) {
|
||||
// main is x, cross is y
|
||||
if (s.heightType != DimensionType::Auto) {
|
||||
size = std::max(0.0f, resolvePx(s.heightType, s.height, parentContentCross));
|
||||
} else {
|
||||
// Auto cross: use intrinsic (the element's natural cross size). CSS
|
||||
// stretch is an alignment rule that expands the item to fill the
|
||||
// parent's cross box at placement time; it does NOT change the
|
||||
// element's hypothetical cross size for the parent's Auto measurement.
|
||||
// setIntrinsicSize zeros this when the axis is explicit.
|
||||
size = c->getIntrinsicH();
|
||||
}
|
||||
return size + (float)(s.marginTop + s.marginBottom);
|
||||
} else {
|
||||
// main is y, cross is x
|
||||
if (s.widthType != DimensionType::Auto) {
|
||||
size = std::max(0.0f, resolvePx(s.widthType, s.width, parentContentCross));
|
||||
} else {
|
||||
size = c->getIntrinsicW();
|
||||
}
|
||||
return size + (float)(s.marginLeft + s.marginRight);
|
||||
}
|
||||
}
|
||||
|
||||
// resolve the child's main-axis basis for flex distribution: explicit (px/%) resolves
|
||||
// against the parent's content main; Auto falls back to the child's intrinsic main.
|
||||
// does NOT include margins (those are handled separately in the layout loop).
|
||||
static float childMainBasis(PElement c, const FlexLayout::Axis& axis, float parentContentMain) {
|
||||
const Style& s = c->getStyle();
|
||||
bool isX = axis.mainIsX;
|
||||
// explicit basis (flex-basis) wins over size
|
||||
if (s.basisType != DimensionType::Auto) {
|
||||
return std::max(0.0f, resolvePx(s.basisType, s.basis, parentContentMain));
|
||||
}
|
||||
float basis;
|
||||
if (isX) {
|
||||
if (s.widthType != DimensionType::Auto) {
|
||||
basis = std::max(0.0f, resolvePx(s.widthType, s.width, parentContentMain));
|
||||
} else {
|
||||
// Auto main: intrinsic. setIntrinsicSize zeros this when the axis is
|
||||
// explicit, so Div<H_32> in a row returns 0 (grow fills it), while
|
||||
// Div with setIntrinsicSize(150,32) in a row returns 150 (shrink test).
|
||||
basis = c->getIntrinsicW();
|
||||
}
|
||||
} else {
|
||||
if (s.heightType != DimensionType::Auto) {
|
||||
basis = std::max(0.0f, resolvePx(s.heightType, s.height, parentContentMain));
|
||||
} else {
|
||||
basis = c->getIntrinsicH();
|
||||
}
|
||||
}
|
||||
// clamp to min/max (the item's own constraints)
|
||||
float parentBox = 0.0f;
|
||||
if (c->getParent() != nullptr) {
|
||||
parentBox = (float)c->getParent()->getLayoutDimensions().x;
|
||||
}
|
||||
if (isX) {
|
||||
float mn = s.minWidthType == DimensionType::Auto ? 0.0f : resolvePx(s.minWidthType, s.minWidth, parentBox);
|
||||
float mx = s.maxWidthType == DimensionType::Auto ? 1e9f : resolvePx(s.maxWidthType, s.maxWidth, parentBox);
|
||||
if (basis < mn) basis = mn;
|
||||
if (basis > mx) basis = mx;
|
||||
} else {
|
||||
float mn = s.minHeightType == DimensionType::Auto ? 0.0f : resolvePx(s.minHeightType, s.minHeight, parentBox);
|
||||
float mx = s.maxHeightType == DimensionType::Auto ? 1e9f : resolvePx(s.maxHeightType, s.maxHeight, parentBox);
|
||||
if (basis < mn) basis = mn;
|
||||
if (basis > mx) basis = mx;
|
||||
}
|
||||
return std::max(0.0f, basis);
|
||||
}
|
||||
|
||||
|
||||
|
||||
} // namespace
|
||||
|
||||
// place flow children in the content box: compute per-line packing (with wrap),
|
||||
// apply justify (main) and align (cross), write positions. this is the core of the
|
||||
// flexbox algorithm. the element's own size is already resolved (by the caller); this
|
||||
// function only positions the children.
|
||||
static void placeFlowChildren(PElement el, const Axis& axis, const Flow& flow, const Array<OElement>& kids) {
|
||||
if (flow.size() == 0) return;
|
||||
const Style& s = el->getStyle();
|
||||
// the element's content box (in the element's own coordinate space, before
|
||||
// adding the element's position to get parent space).
|
||||
float boxMain, boxCross;
|
||||
if (axis.mainIsX) {
|
||||
boxMain = std::max(0.0f, (float)el->getLayoutDimensions().x - (float)(s.paddingLeft + s.paddingRight));
|
||||
boxCross = std::max(0.0f, (float)el->getLayoutDimensions().y - (float)(s.paddingTop + s.paddingBottom));
|
||||
} else {
|
||||
boxMain = std::max(0.0f, (float)el->getLayoutDimensions().y - (float)(s.paddingTop + s.paddingBottom));
|
||||
boxCross = std::max(0.0f, (float)el->getLayoutDimensions().x - (float)(s.paddingLeft + s.paddingRight));
|
||||
}
|
||||
// the content-box origin in the element's own space (where flow starts).
|
||||
float originMain, originCross;
|
||||
if (axis.mainIsX) {
|
||||
originMain = (float)s.paddingLeft;
|
||||
originCross = (float)s.paddingTop;
|
||||
} else {
|
||||
// column: main is y, cross is x. the content origin is at (paddingLeft, paddingTop).
|
||||
originMain = (float)s.paddingTop;
|
||||
originCross = (float)s.paddingLeft;
|
||||
}
|
||||
// resolve each flow child's main-axis basis (for flex distribution) and cross size.
|
||||
// the basis is the starting point for grow/shrink; the cross size is the item's
|
||||
// final cross dimension (explicit or intrinsic, min/max clamped).
|
||||
struct Placed {
|
||||
size_t idx;
|
||||
float basis;
|
||||
float grow;
|
||||
float shrink;
|
||||
float mainMarginStart;
|
||||
float mainMarginEnd;
|
||||
float crossSize;
|
||||
float crossMarginStart;
|
||||
float crossMarginEnd;
|
||||
float mainSize;
|
||||
int line;
|
||||
};
|
||||
std::vector<Placed> placed;
|
||||
placed.reserve(flow.size());
|
||||
for (size_t k = 0; k < flow.size(); k++) {
|
||||
PElement c = kids[flow[k]];
|
||||
const Style& cs = c->getStyle();
|
||||
Placed p{};
|
||||
p.idx = flow[k];
|
||||
p.basis = childMainBasis(c, axis, boxMain);
|
||||
p.grow = cs.grow;
|
||||
p.shrink = cs.shrink;
|
||||
// the child's cross size is its own final dimensions (finalized by
|
||||
// layoutElement before we got here). reading the child's *style* here
|
||||
// would give the stale pre-applyStyle values (applyStyle ran during
|
||||
// resolveStyles, before the child was measured, so the style still
|
||||
// reflects the parent's inherited values). the child's dimensions are
|
||||
// the ground truth for its final cross size.
|
||||
if (axis.mainIsX) {
|
||||
p.mainMarginStart = (float)cs.marginLeft;
|
||||
p.mainMarginEnd = (float)cs.marginRight;
|
||||
// clamp to the content box: a 100%-width item in a padded container
|
||||
// should fill the content, not overflow into the padding.
|
||||
p.crossSize = std::min(std::max(0.0f, (float)c->getLayoutDimensions().y), boxCross);
|
||||
p.crossMarginStart = (float)cs.marginTop;
|
||||
p.crossMarginEnd = (float)cs.marginBottom;
|
||||
} else {
|
||||
p.mainMarginStart = (float)cs.marginTop;
|
||||
p.mainMarginEnd = (float)cs.marginBottom;
|
||||
p.crossSize = std::min(std::max(0.0f, (float)c->getLayoutDimensions().x), boxCross);
|
||||
p.crossMarginStart = (float)cs.marginLeft;
|
||||
p.crossMarginEnd = (float)cs.marginRight;
|
||||
}
|
||||
p.mainSize = p.basis;
|
||||
p.line = 0;
|
||||
placed.push_back(p);
|
||||
}
|
||||
// line packing: walk the flow in order, accumulating main-axis usage (size +
|
||||
// margins + gaps). when the line is full (and wrap is on), start a new line.
|
||||
float gap = (float)s.gap;
|
||||
{
|
||||
float cursor = 0.0f;
|
||||
int line = 0;
|
||||
bool firstOnLine = true;
|
||||
for (size_t k = 0; k < placed.size(); k++) {
|
||||
Placed& p = placed[k];
|
||||
float footprint = p.mainSize + p.mainMarginStart + p.mainMarginEnd;
|
||||
float needed = (firstOnLine ? 0.0f : gap) + footprint;
|
||||
if (!firstOnLine && cursor + needed > boxMain + 0.5f && s.wrap == FlexWrap::Wrap) {
|
||||
line++;
|
||||
cursor = 0.0f;
|
||||
firstOnLine = true;
|
||||
needed = footprint;
|
||||
}
|
||||
p.line = line;
|
||||
if (!firstOnLine && gap > 0.0f) cursor += gap;
|
||||
cursor += footprint;
|
||||
firstOnLine = false;
|
||||
}
|
||||
}
|
||||
// flex distribution: per line, distribute the free space (boxMain - total usage)
|
||||
// among items with grow>0 (positive) or shrink>0 (negative, deficit only).
|
||||
{
|
||||
// collect max line index
|
||||
int maxLine = 0;
|
||||
for (auto& p : placed) maxLine = std::max(maxLine, p.line);
|
||||
for (int ln = 0; ln <= maxLine; ln++) {
|
||||
// total usage on this line (basis + margins + gaps)
|
||||
float usage = 0.0f;
|
||||
int count = 0;
|
||||
for (size_t k = 0; k < placed.size(); k++) {
|
||||
if (placed[k].line != ln) continue;
|
||||
usage += placed[k].mainSize + placed[k].mainMarginStart + placed[k].mainMarginEnd;
|
||||
count++;
|
||||
}
|
||||
if (count > 1 && gap > 0.0f) usage += (float)(count - 1) * gap;
|
||||
float free = boxMain - usage;
|
||||
float growSum = 0.0f, shrinkSum = 0.0f;
|
||||
for (auto& p : placed) {
|
||||
if (p.line != ln) continue;
|
||||
growSum += p.grow;
|
||||
shrinkSum += p.shrink;
|
||||
}
|
||||
if (free > 0.0f && growSum > 0.0f) {
|
||||
for (auto& p : placed) {
|
||||
if (p.line != ln || p.grow <= 0.0f) continue;
|
||||
p.mainSize += free * (p.grow / growSum);
|
||||
}
|
||||
} else if (free < 0.0f && shrinkSum > 0.0f) {
|
||||
// shrink proportionally, not below the item's min (or 0).
|
||||
for (auto& p : placed) {
|
||||
if (p.line != ln || p.shrink <= 0.0f) continue;
|
||||
const Style& cs = kids[p.idx]->getStyle();
|
||||
float mn = axis.mainIsX
|
||||
? (cs.minWidthType == DimensionType::Auto ? 0.0f : resolvePx(cs.minWidthType, cs.minWidth, boxMain))
|
||||
: (cs.minHeightType == DimensionType::Auto ? 0.0f : resolvePx(cs.minHeightType, cs.minHeight, boxMain));
|
||||
float target = p.mainSize + free * (p.shrink / shrinkSum);
|
||||
p.mainSize = std::max(mn, target);
|
||||
}
|
||||
}
|
||||
// min/max are already applied in childMainBasis (the basis is the
|
||||
// starting point, clamped to [min, max] before distribution). the
|
||||
// grow/shrink distribution above cannot push an item below its min
|
||||
// (shrink targets are clamped) or above its max (grow on an item at
|
||||
// its max is a no-op in the demo; a full implementation would re-
|
||||
// distribute, which we skip as out of scope).
|
||||
}
|
||||
}
|
||||
// per-line positioning: for each line, compute the line's main usage and cross
|
||||
// extent, apply justify (main offset) and align (cross offset), write each item's
|
||||
// position in PARENT space (element position + origin + line offset + item offset).
|
||||
{
|
||||
int maxLine = 0;
|
||||
for (auto& p : placed) maxLine = std::max(maxLine, p.line);
|
||||
float lineCrossCursor = 0.0f; // cross cursor across lines (for wrap)
|
||||
for (int ln = 0; ln <= maxLine; ln++) {
|
||||
// line main usage (final sizes + margins + gaps)
|
||||
float lineMain = 0.0f;
|
||||
int count = 0;
|
||||
float lineCross = 0.0f; // max cross extent on this line
|
||||
for (size_t k = 0; k < placed.size(); k++) {
|
||||
if (placed[k].line != ln) continue;
|
||||
lineMain += placed[k].mainSize + placed[k].mainMarginStart + placed[k].mainMarginEnd;
|
||||
count++;
|
||||
float crossExtent = placed[k].crossSize + placed[k].crossMarginStart + placed[k].crossMarginEnd;
|
||||
lineCross = std::max(lineCross, crossExtent);
|
||||
}
|
||||
if (count > 1 && gap > 0.0f) lineMain += (float)(count - 1) * gap;
|
||||
// justify: main-axis offset of the first item on this line (relative to
|
||||
// the content origin). free = boxMain - lineMain (>= 0 in normal cases).
|
||||
float freeMain = boxMain - lineMain;
|
||||
float mainOff = 0.0f;
|
||||
if (freeMain > 0.0f) {
|
||||
switch (s.justify) {
|
||||
case JustifyContent::Start: mainOff = 0.0f; break;
|
||||
case JustifyContent::Center: mainOff = freeMain * 0.5f; break;
|
||||
case JustifyContent::End: mainOff = freeMain; break;
|
||||
case JustifyContent::SpaceBetween:
|
||||
case JustifyContent::SpaceAround:
|
||||
case JustifyContent::SpaceEvenly:
|
||||
// distributed free space; computed per-item below
|
||||
mainOff = 0.0f; break;
|
||||
}
|
||||
}
|
||||
// align: cross-axis offset of items on this line (relative to the
|
||||
// content origin + line cross cursor). the line cross extent is the max
|
||||
// item cross extent; freeCross = lineCrossSpace - lineCross.
|
||||
// for no-wrap, lineCrossSpace = boxCross. for wrap, each line gets its
|
||||
// own cross space = boxCross (lines stack, no cross overflow handling
|
||||
// beyond stacking).
|
||||
float lineCrossSpace = boxCross; // per-line cross space
|
||||
// the per-item align: use the item's own alignSelf if set (>= 0, see
|
||||
// Style::alignSelfOverride / SelfClass), else the container's `items`.
|
||||
// the cross offset is computed per-item (it depends on the item's own
|
||||
// cross size, not the line's max).
|
||||
auto resolveAlign = [&](const Style& cs) -> AlignType {
|
||||
if (cs.alignSelfOverride >= 0.0f) {
|
||||
return (AlignType)(int32)cs.alignSelfOverride;
|
||||
}
|
||||
return s.items;
|
||||
};
|
||||
// the line's cross position (for wrap, lines stack: line 0 at
|
||||
// originCross, line 1 at originCross + line0Cross + gap, etc.).
|
||||
// for no-wrap there's only one line at originCross.
|
||||
float lineCrossPos = originCross + lineCrossCursor;
|
||||
// per-item positioning
|
||||
float itemMainCursor = 0.0f; // cursor within the line (main axis)
|
||||
bool firstOnLine = true;
|
||||
float spacePerGap = 0.0f;
|
||||
if (count > 1 && freeMain > 0.0f) {
|
||||
switch (s.justify) {
|
||||
case JustifyContent::SpaceBetween: spacePerGap = freeMain / (float)(count - 1); break;
|
||||
case JustifyContent::SpaceAround: spacePerGap = freeMain / (float)count; break;
|
||||
case JustifyContent::SpaceEvenly: spacePerGap = freeMain / (float)(count + 1); break;
|
||||
default: spacePerGap = 0.0f; break;
|
||||
}
|
||||
}
|
||||
for (size_t k = 0; k < placed.size(); k++) {
|
||||
if (placed[k].line != ln) continue;
|
||||
Placed& p = placed[k];
|
||||
PElement c = kids[p.idx];
|
||||
// main position: line start + item offset within line.
|
||||
float itemMain;
|
||||
if (firstOnLine) {
|
||||
// the first item on the line: offset by mainOff (justify) plus
|
||||
// any space-before (for space-around/evenly).
|
||||
itemMain = mainOff;
|
||||
if (s.justify == JustifyContent::SpaceAround || s.justify == JustifyContent::SpaceEvenly) {
|
||||
itemMain += spacePerGap;
|
||||
}
|
||||
} else {
|
||||
// subsequent items: cursor + gap (+ extra space for space-*).
|
||||
itemMain = itemMainCursor + gap;
|
||||
if (spacePerGap > 0.0f) {
|
||||
itemMain += (spacePerGap - gap); // the extra beyond the base gap
|
||||
}
|
||||
}
|
||||
itemMain += p.mainMarginStart;
|
||||
// per-item align override
|
||||
// freeCross for this item: the line's cross space minus this item's
|
||||
// own cross size (without margins — margins are handled separately
|
||||
// via crossPos). this is what align-items/align-self operates on.
|
||||
float itemFreeCross = lineCrossSpace - p.crossSize;
|
||||
if (itemFreeCross < 0.0f) itemFreeCross = 0.0f;
|
||||
float itemCrossOff = 0.0f;
|
||||
float itemCross = p.crossSize;
|
||||
auto al = resolveAlign(c->getStyle());
|
||||
// stretch only applies when the item has no definite cross size
|
||||
// (CSS: explicit px/percent cross wins over stretch).
|
||||
const Style& itemStyle = c->getStyle();
|
||||
bool crossIsAuto = axis.mainIsX
|
||||
? (itemStyle.heightType == DimensionType::Auto)
|
||||
: (itemStyle.widthType == DimensionType::Auto);
|
||||
bool canStretch = itemFreeCross > 0.0f && crossIsAuto;
|
||||
if (itemFreeCross > 0.0f) {
|
||||
switch (al) {
|
||||
case AlignType::Start: itemCrossOff = 0.0f; break;
|
||||
case AlignType::Center: itemCrossOff = itemFreeCross * 0.5f; break;
|
||||
case AlignType::End: itemCrossOff = itemFreeCross; break;
|
||||
case AlignType::Stretch: itemCrossOff = 0.0f; if (canStretch) itemCross = lineCrossSpace; break;
|
||||
}
|
||||
}
|
||||
// cross position: line cross pos + item cross offset + margin.
|
||||
float crossPos = lineCrossPos + itemCrossOff + p.crossMarginStart;
|
||||
// Nested containers already resolved their real footprint in their own
|
||||
// layout pass (recursion in layoutElement). The flex-distributed
|
||||
// p.mainSize is only the final answer for leaf items.
|
||||
Vector2 cDims = c->getLayoutDimensions();
|
||||
bool isContainer = (c->getChildren().size() > 0);
|
||||
float actualMain = axis.mainIsX ? cDims.x : cDims.y;
|
||||
float actualCross = axis.mainIsX ? cDims.y : cDims.x;
|
||||
float finalMain = isContainer ? actualMain : p.mainSize;
|
||||
|
||||
// convert main/cross (element space) to x/y (parent space).
|
||||
float x, y;
|
||||
if (axis.mainIsX) {
|
||||
x = el->getLayoutPosition().x + originMain + itemMain;
|
||||
y = el->getLayoutPosition().y + crossPos;
|
||||
c->setLayoutDimensions(Vector2(std::max(0.0f, finalMain), std::max(0.0f, itemCross)));
|
||||
} else {
|
||||
x = el->getLayoutPosition().x + crossPos;
|
||||
y = el->getLayoutPosition().y + originMain + itemMain;
|
||||
c->setLayoutDimensions(Vector2(std::max(0.0f, itemCross), std::max(0.0f, finalMain)));
|
||||
}
|
||||
// relative position offset (applied on top of the flow position).
|
||||
if (c->getStyle().position == Position::Relative) {
|
||||
x += (float)c->getStyle().left;
|
||||
y += (float)c->getStyle().top;
|
||||
}
|
||||
c->setLayoutPosition(Vector2(x, y));
|
||||
// advance the cursor (containers use their real main size)
|
||||
itemMainCursor = itemMain + finalMain + p.mainMarginEnd;
|
||||
firstOnLine = false;
|
||||
}
|
||||
// advance the line cross cursor for the next line (wrap stacking).
|
||||
lineCrossCursor += lineCross + (maxLine > 0 ? gap : 0.0f);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// layout one element: measure (resolve its own size + recurse to measure children),
|
||||
// then place (position flow children in the content box, handle absolute children).
|
||||
// writes `position` and `dimensions` in PARENT space (excluding margins).
|
||||
void layoutElement(PElement el, const Axis& axis) {
|
||||
const Array<OElement>& kids = el->getChildren();
|
||||
if (el->getStyle().display == Display::Hidden) {
|
||||
el->setLayout(Vector2(0), Vector2(0));
|
||||
return;
|
||||
}
|
||||
Flow flow;
|
||||
Flow::build(el, flow);
|
||||
// resolve this element's own size. the content measurement uses the children's
|
||||
// resolved sizes (explicit or intrinsic) — it does NOT depend on this element's
|
||||
// own dimensions (which aren't set yet). percent resolution for the children
|
||||
// uses the PARENT's content box (not this element's). so we can compute the
|
||||
// content measurement before setting dimensions.
|
||||
float mainContent = contentAxis(axis.mainIsX, el, flow, kids);
|
||||
// cross-axis content: max over flow children of their cross footprints.
|
||||
// the percent reference for children's cross sizes is the *parent's* content
|
||||
// box (the containing block), not this element's (which may be stale from a
|
||||
// prior layout run). for a root element (no parent), the reference is 0.
|
||||
float parentContentCross = 0.0f;
|
||||
{
|
||||
PElement parent = el->getParent();
|
||||
if (parent != nullptr) {
|
||||
parentContentCross = axis.mainIsX
|
||||
? std::max(0.0f, (float)parent->getLayoutDimensions().y - (float)(parent->getStyle().paddingTop + parent->getStyle().paddingBottom))
|
||||
: std::max(0.0f, (float)parent->getLayoutDimensions().x - (float)(parent->getStyle().paddingLeft + parent->getStyle().paddingRight));
|
||||
}
|
||||
}
|
||||
float crossContent = 0.0f;
|
||||
for (size_t k = 0; k < flow.size(); k++) {
|
||||
PElement c = kids[flow[k]];
|
||||
crossContent = std::max(crossContent, childCrossFootprint(c, axis, parentContentCross));
|
||||
}
|
||||
// if there are no flow children, the cross content is the element's intrinsic cross.
|
||||
if (flow.size() == 0) {
|
||||
crossContent = axis.mainIsX ? el->getIntrinsicH() : el->getIntrinsicW();
|
||||
}
|
||||
// now resolve the element's own size: explicit wins, Auto falls back to content.
|
||||
float mainSize = resolveAxisSize(axis.mainIsX, el, mainContent, el->getStyle());
|
||||
float crossSize = resolveAxisSize(!axis.mainIsX, el, crossContent, el->getStyle());
|
||||
// set the element's dimensions (in parent space, excluding margins).
|
||||
if (axis.mainIsX) {
|
||||
el->setLayoutDimensions(Vector2(mainSize, crossSize));
|
||||
} else {
|
||||
el->setLayoutDimensions(Vector2(crossSize, mainSize));
|
||||
}
|
||||
// the element's content box (for placing children).
|
||||
float contentMain = axis.mainIsX
|
||||
? std::max(0.0f, mainSize - (float)(el->getStyle().paddingLeft + el->getStyle().paddingRight))
|
||||
: std::max(0.0f, mainSize - (float)(el->getStyle().paddingTop + el->getStyle().paddingBottom));
|
||||
float contentCross = axis.mainIsX
|
||||
? std::max(0.0f, crossSize - (float)(el->getStyle().paddingTop + el->getStyle().paddingBottom))
|
||||
: std::max(0.0f, crossSize - (float)(el->getStyle().paddingLeft + el->getStyle().paddingRight));
|
||||
// measure children: recurse to resolve each child's size. the child uses its OWN
|
||||
// direction to determine its axis (a Row child of a Column parent has mainIsX=true
|
||||
// even though the parent has mainIsX=false).
|
||||
for (size_t k = 0; k < flow.size(); k++) {
|
||||
PElement c = kids[flow[k]];
|
||||
const Style& css = c->getStyle();
|
||||
bool cIsX = (css.direction == FlexDirection::Row || css.direction == FlexDirection::RowReverse);
|
||||
Axis childAxis{cIsX, cIsX ? (css.direction == FlexDirection::RowReverse) : (css.direction == FlexDirection::ColumnReverse)};
|
||||
layoutElement(c, childAxis);
|
||||
}
|
||||
// absolute children: removed from the flow, positioned from this element's
|
||||
// content-box corner. measure them (so their own children are laid out), then
|
||||
// position by left/top offsets (right/bottom are not supported).
|
||||
for (size_t i = 0; i < kids.size(); i++) {
|
||||
PElement c = kids[i];
|
||||
if (c == nullptr || c->getStyle().display == Display::Hidden) continue;
|
||||
if (c->getStyle().position != Position::Absolute) continue;
|
||||
const Style& css = c->getStyle();
|
||||
bool cIsX = (css.direction == FlexDirection::Row || css.direction == FlexDirection::RowReverse);
|
||||
Axis childAxis{cIsX, cIsX ? (css.direction == FlexDirection::RowReverse) : (css.direction == FlexDirection::ColumnReverse)};
|
||||
layoutElement(c, childAxis);
|
||||
float ax = (float)c->getStyle().left;
|
||||
float ay = (float)c->getStyle().top;
|
||||
// for absolute, the containing block is this element. the offset is from
|
||||
// the content-box corner (padding + left/top). the position is in PARENT
|
||||
// space: this element's position + padding + offset.
|
||||
Vector2 pos;
|
||||
if (axis.mainIsX) {
|
||||
pos = el->getLayoutPosition() + Vector2((float)el->getStyle().paddingLeft + ax, (float)el->getStyle().paddingTop + ay);
|
||||
} else {
|
||||
pos = el->getLayoutPosition() + Vector2((float)el->getStyle().paddingLeft + ax, (float)el->getStyle().paddingTop + ay);
|
||||
}
|
||||
c->setLayoutPosition(pos);
|
||||
}
|
||||
// zero out all hidden children (not laid out, not rendered).
|
||||
for (size_t i = 0; i < kids.size(); i++) {
|
||||
if (kids[i] == nullptr) continue;
|
||||
if (kids[i]->getStyle().display == Display::Hidden) {
|
||||
// raw pointers can be modified inside a const Array<>&, but RefPtr imposes const-ness also for the elements
|
||||
// this side-steps the issue by creating a non-const RefPtr copy
|
||||
PElement kid = kids[i];
|
||||
kid->setLayout(Vector2(0), Vector2(0));
|
||||
}
|
||||
}
|
||||
// place flow children in the content box: compute per-line packing, apply
|
||||
// justify (main) and align (cross), write positions. this is the bulk of the
|
||||
// flexbox algorithm; see the plan for the exact rules.
|
||||
placeFlowChildren(el, axis, flow, kids);
|
||||
// A container child was measured (recursion above) BEFORE its position was set
|
||||
// here, so its own grandchildren were laid out relative to a stale position.
|
||||
// Re-run each container child's placement now that the parent position is final.
|
||||
for (size_t k = 0; k < flow.size(); k++) {
|
||||
PElement c = kids[flow[k]];
|
||||
if (c->getChildren().size() == 0) continue;
|
||||
const Style& css = c->getStyle();
|
||||
if (css.position == Position::Absolute) continue;
|
||||
bool cIsX = (css.direction == FlexDirection::Row || css.direction == FlexDirection::RowReverse);
|
||||
Axis childAxis{cIsX, cIsX ? (css.direction == FlexDirection::RowReverse) : (css.direction == FlexDirection::ColumnReverse)};
|
||||
Flow cf;
|
||||
Flow::build(c, cf);
|
||||
const Array<OElement>& cKids = c->getChildren();
|
||||
placeFlowChildren(c, childAxis, cf, cKids);
|
||||
}
|
||||
}
|
||||
|
||||
// the public entry point: set the root's dimensions to the viewport, then run the
|
||||
// full layout. the root has no parent, so its percent sizes are degenerate (0) —
|
||||
// the root should use explicit (px) or Auto sizes.
|
||||
void layoutRoot(PElement root, UVector2 viewport) {
|
||||
if (root == nullptr) return;
|
||||
// the root's dimensions are the viewport (the root IS the viewport's content).
|
||||
// the root has no parent, so resolveAxisSize will treat its percent sizes as 0
|
||||
// (degenerate) — for the root we want the viewport as the explicit size.
|
||||
// we set the root's dimensions directly to the viewport (minus padding) so the
|
||||
// content box is correct, then run layoutElement to place the children.
|
||||
float w = (float)viewport.x;
|
||||
float h = (float)viewport.y;
|
||||
// apply min/max clamp to the root's viewport size (the root's style may have
|
||||
// min/max that constrain the viewport — unusual but handled for consistency).
|
||||
const Style& s = root->getStyle();
|
||||
// for the root, the percent reference is the viewport itself (the root is the
|
||||
// top-level container). we resolve the root's size as: explicit (px) wins; %
|
||||
// resolves against the viewport; Auto falls back to the content measurement.
|
||||
// this is the only place the "parent" is the viewport rather than another
|
||||
// element, so we handle it specially here.
|
||||
auto resolveRootAxis = [&](bool isX, float vp, float content, DimensionType t, float v, DimensionType mnT, float mn, DimensionType mxt, float mx) -> float {
|
||||
float explicitSize = (t == DimensionType::Pixel) ? v : (t == DimensionType::Percent) ? (v / 100.0f * vp) : content;
|
||||
float mnR = (mnT == DimensionType::Auto) ? 0.0f : ((mnT == DimensionType::Pixel) ? mn : (mnT == DimensionType::Percent) ? (mn / 100.0f * vp) : 0.0f);
|
||||
float mxR = (mxt == DimensionType::Auto) ? 1e9f : ((mxt == DimensionType::Pixel) ? mx : (mxt == DimensionType::Percent) ? (mx / 100.0f * vp) : 1e9f);
|
||||
float size = explicitSize;
|
||||
if (size < mnR) size = mnR;
|
||||
if (size > mxR) size = mxR;
|
||||
if (size < 0.0f) size = 0.0f;
|
||||
return size;
|
||||
};
|
||||
// compute the root's content measurement (for the Auto fallback) — same as
|
||||
// layoutElement does, but the root has no parent so the percent reference for
|
||||
// children is the root's own content box (which we compute here).
|
||||
// for simplicity, the Auto fallback for the root uses the viewport (the root
|
||||
// is the viewport; its content is bounded by the viewport). this is a
|
||||
// reasonable default: an Auto-sized root fills the viewport.
|
||||
float mainContent = (float)viewport.x, crossContent = (float)viewport.y;
|
||||
if (s.direction == FlexDirection::Column || s.direction == FlexDirection::ColumnReverse) {
|
||||
mainContent = (float)viewport.y;
|
||||
crossContent = (float)viewport.x;
|
||||
}
|
||||
bool isX = (s.direction == FlexDirection::Row || s.direction == FlexDirection::RowReverse);
|
||||
float mainSize = resolveRootAxis(isX, isX ? (float)viewport.x : (float)viewport.y, mainContent,
|
||||
isX ? s.widthType : s.heightType, isX ? s.width : s.height,
|
||||
isX ? s.minWidthType : s.minHeightType, isX ? s.minWidth : s.minHeight,
|
||||
isX ? s.maxWidthType : s.maxHeightType, isX ? s.maxWidth : s.maxHeight);
|
||||
float crossSize = resolveRootAxis(!isX, !isX ? (float)viewport.x : (float)viewport.y, crossContent,
|
||||
!isX ? s.widthType : s.heightType, !isX ? s.width : s.height,
|
||||
!isX ? s.minWidthType : s.minHeightType, !isX ? s.minWidth : s.minHeight,
|
||||
!isX ? s.maxWidthType : s.maxHeightType, !isX ? s.maxWidth : s.maxHeight);
|
||||
Vector2 dims = isX ? Vector2(mainSize, crossSize) : Vector2(crossSize, mainSize);
|
||||
root->setLayoutDimensions(dims);
|
||||
// the root's own size is final (resolved against the viewport above). the
|
||||
// children's percent reference is the root's now-finalized dimensions, so
|
||||
// `layoutElement` is correct for them. what we still owe the root is: measure
|
||||
// its flow children (recursively), position its absolute children, and place
|
||||
// its flow children in the root's content box — i.e. everything `layoutElement`
|
||||
// does *except* re-resolving the root's own size (which would use a null parent
|
||||
// and a 0 percent reference, wrong for the root).
|
||||
Axis axis{isX, isX ? (s.direction == FlexDirection::RowReverse) : (s.direction == FlexDirection::ColumnReverse)};
|
||||
const Array<OElement>& kids = root->getChildren();
|
||||
if (root->getStyle().display == Display::Hidden) {
|
||||
root->setLayout(Vector2(0), Vector2(0));
|
||||
return;
|
||||
}
|
||||
Flow flow;
|
||||
Flow::build(root, flow);
|
||||
// zero out hidden children (not laid out, not rendered).
|
||||
for (size_t i = 0; i < kids.size(); i++) {
|
||||
if (kids[i] == nullptr) continue;
|
||||
if (kids[i]->getStyle().display == Display::Hidden) {
|
||||
// modifyable copyied refptr, something you can do with raw pointers natively
|
||||
PElement kid = kids[i];
|
||||
kid->setLayout(Vector2(0), Vector2(0));
|
||||
}
|
||||
}
|
||||
// measure the flow children (recursively) and the absolute children.
|
||||
for (size_t k = 0; k < flow.size(); k++) {
|
||||
PElement c = kids[flow[k]];
|
||||
const Style& css = c->getStyle();
|
||||
bool cIsX = (css.direction == FlexDirection::Row || css.direction == FlexDirection::RowReverse);
|
||||
Axis childAxis{cIsX, cIsX ? (css.direction == FlexDirection::RowReverse) : (css.direction == FlexDirection::ColumnReverse)};
|
||||
layoutElement(c, childAxis);
|
||||
}
|
||||
for (size_t i = 0; i < kids.size(); i++) {
|
||||
PElement c = kids[i];
|
||||
if (c == nullptr || c->getStyle().display == Display::Hidden) continue;
|
||||
if (c->getStyle().position != Position::Absolute) continue;
|
||||
const Style& css = c->getStyle();
|
||||
bool cIsX = (css.direction == FlexDirection::Row || css.direction == FlexDirection::RowReverse);
|
||||
Axis childAxis{cIsX, cIsX ? (css.direction == FlexDirection::RowReverse) : (css.direction == FlexDirection::ColumnReverse)};
|
||||
layoutElement(c, childAxis);
|
||||
float ax = (float)c->getStyle().left;
|
||||
float ay = (float)c->getStyle().top;
|
||||
Vector2 pos = root->getLayoutPosition() + Vector2((float)root->getStyle().paddingLeft + ax, (float)root->getStyle().paddingTop + ay);
|
||||
c->setLayoutPosition(pos);
|
||||
}
|
||||
// place the root's flow children in the root's content box.
|
||||
placeFlowChildren(root, axis, flow, kids);
|
||||
// Same fix as in layoutElement: container children were measured before their
|
||||
// position was set, so re-run their placement with the now-final position.
|
||||
for (size_t k = 0; k < flow.size(); k++) {
|
||||
PElement c = kids[flow[k]];
|
||||
if (c->getChildren().size() == 0) continue;
|
||||
const Style& css = c->getStyle();
|
||||
if (css.position == Position::Absolute) continue;
|
||||
bool cIsX = (css.direction == FlexDirection::Row || css.direction == FlexDirection::RowReverse);
|
||||
Axis childAxis{cIsX, cIsX ? (css.direction == FlexDirection::RowReverse) : (css.direction == FlexDirection::ColumnReverse)};
|
||||
Flow cf;
|
||||
Flow::build(c, cf);
|
||||
const Array<OElement>& cKids = c->getChildren();
|
||||
placeFlowChildren(c, childAxis, cf, cKids);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace FlexLayout
|
||||
} // namespace UI
|
||||
} // namespace Seele
|
||||
@@ -0,0 +1,97 @@
|
||||
#pragma once
|
||||
// Flexbox is the sole UI layout mode. This is a free function (not a method) so it
|
||||
// can be unit-tested on a caller-owned tree without the System's OwningPtr deleting
|
||||
// the tree first. Two-phase:
|
||||
// 1. measure (post-order): resolve the element's final clamped `dimensions` and
|
||||
// each flow child's main-axis *basis* (so grow/shrink/wrap/justify operate on
|
||||
// real sizes). A child's nested container is fully measured before the parent
|
||||
// distributes space, so its real size is known to the parent.
|
||||
// 2. place (pre-order): position this element's children (order-sorted,
|
||||
// grow/shrink distribution, wrap, justify, align, gap) and recurse.
|
||||
//
|
||||
// Invariant: the tree's `style` is already resolved (System::styleRec runs
|
||||
// applyStyle before layoutRoot). For Text, applyStyle has already shaped the glyphs
|
||||
// and written the measured size to `Element::intrinsicW/H` — an item's natural main
|
||||
// size is therefore final by layout time (unit tests supply a natural size via
|
||||
// Element::setIntrinsicSize without a real font).
|
||||
//
|
||||
// Coordinate model (matches the pre-existing flow layout): an element's `position`
|
||||
// and `dimensions` are in *parent* space, so childAbsolute = parentAbsolute + child.position
|
||||
// (render does position + anchor). The containing box for a child is therefore the
|
||||
// PARENT's dimensions. An element's own padding is the box its children lay out
|
||||
// inside; the element's size never subtracts the parent's padding.
|
||||
//
|
||||
// Margins are honored on BOTH axes: an item's cross footprint includes its cross
|
||||
// margins, and the `align`/`justify` math works in the parent's *content* box with
|
||||
// the item positioned inside the *full* parent box (so a top margin pushes the item
|
||||
// down from the parent's top edge). This is what CSS does.
|
||||
//
|
||||
// Item indexing: each layout call builds a local `items` vector sized to the number
|
||||
// of flow children (sorted by `order`). measure and place share that vector by
|
||||
// index, so the index spaces always line up. Hidden/absolute children are excluded
|
||||
// from `items` entirely (they are never laid out / hit-tested).
|
||||
//
|
||||
// NOTE: this header must NOT include `UI/Element.h` — `Element.h` already includes
|
||||
// this header (for the layout free functions), so a reverse include would be a
|
||||
// circular include and the full `Element` class body would be invisible here. We
|
||||
// only need `FlexDirection` (in `Style.h`) to compute the root axis, so include
|
||||
// `Style.h` and forward-declare `Element`. The .cpp (which does include `Element.h`)
|
||||
// has the full type when it defines `layoutElement`/the free functions.
|
||||
#include "UI/Style/Style.h"
|
||||
#include "MinimalEngine.h"
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <vector>
|
||||
|
||||
namespace Seele {
|
||||
namespace UI {
|
||||
// forward decl: the full class lives in `UI/Element.h` (which includes this header).
|
||||
// only used as a pointer/reference here, so the forward decl is sufficient.
|
||||
DECLARE_REF(Element)
|
||||
namespace FlexLayout {
|
||||
// one flex container's resolved main/cross geometry, passed down the recursion.
|
||||
// `mainIsX` is true for row/row-reverse (main axis = x). `cMain`/`cCross` are the
|
||||
// element's *own* resolved size on each axis — the containing box for its children
|
||||
// (an element's children are laid out inside the element's dimensions).
|
||||
struct Axis {
|
||||
bool mainIsX = true;
|
||||
bool reverse = false; // RowReverse / ColumnReverse
|
||||
float cMain = 0.0f, cCross = 0.0f;
|
||||
};
|
||||
|
||||
// per-item scratch, indexed by position in `items` (the order-sorted flow list).
|
||||
struct Item {
|
||||
PElement el = nullptr;
|
||||
int32 order = 0;
|
||||
float basis = 0.f; // main size before grow/shrink (min/max clamped)
|
||||
float grow = 0.f, shrink = 1.f;
|
||||
float main = 0.f; // final main size
|
||||
float cross = 0.f; // final cross size (resolved independently of main)
|
||||
float mainStart = 0.f; // computed main position (flow coordinate, pre-reverse)
|
||||
float crossStart = 0.f; // computed cross position (parent box coordinates)
|
||||
float mStart = 0.f; // margin on the main-start side
|
||||
float mEnd = 0.f; // margin on the main-end side
|
||||
float cStart = 0.f; // margin on the cross-start side
|
||||
float cEnd = 0.f; // margin on the cross-end side
|
||||
int32 line = -1; // wrap line index (-1 = unassigned)
|
||||
};
|
||||
|
||||
// the layout entry point for a single element. `cMain`/`cCross` are the
|
||||
// *containing size* for `el`'s own size resolution (the parent's dimensions, or the
|
||||
// viewport at the root). Resolves the element's own main/cross size (measure), then
|
||||
// lays out its children (place), recursing into each flow child with the child's
|
||||
// *own* resolved size as its containing box.
|
||||
void layoutElement(PElement el, const Axis& axis);
|
||||
|
||||
// public entry: lay out the whole tree. `root` is the viewport's only child; the
|
||||
// viewport's dimensions are `viewport`. `root->position` is left untouched (the
|
||||
// System treats the root as the anchor at (0,0) — see System::render).
|
||||
//
|
||||
// declared here, defined in FlexLayout.cpp (the body dereferences `root->style`,
|
||||
// which needs the complete Element type — not available in this header, which only
|
||||
// forward-declares Element to avoid a circular include with Element.h).
|
||||
void layoutRoot(PElement root, UVector2 viewport);
|
||||
} // namespace FlexLayout
|
||||
} // namespace UI
|
||||
} // namespace Seele
|
||||
+123
-10
@@ -19,24 +19,137 @@ template <uint32 w, DimensionType widthType> struct WidthClass {
|
||||
}
|
||||
};
|
||||
using W_Full = WidthClass<100, DimensionType::Percent>;
|
||||
template <uint32 h> struct HeightClass {
|
||||
using W_16 = WidthClass<16, DimensionType::Pixel>;
|
||||
using W_24 = WidthClass<24, DimensionType::Pixel>;
|
||||
using W_32 = WidthClass<32, DimensionType::Pixel>;
|
||||
using W_40 = WidthClass<40, DimensionType::Pixel>;
|
||||
using W_48 = WidthClass<48, DimensionType::Pixel>;
|
||||
using W_64 = WidthClass<64, DimensionType::Pixel>;
|
||||
using W_100 = WidthClass<100, DimensionType::Pixel>;
|
||||
using W_150 = WidthClass<150, DimensionType::Pixel>;
|
||||
template <uint32 h, DimensionType t = DimensionType::Pixel> struct HeightClass {
|
||||
static void apply(Style& s, const Theme&) {
|
||||
s.height = h;
|
||||
s.heightType = DimensionType::Pixel;
|
||||
s.heightType = t;
|
||||
}
|
||||
};
|
||||
using H_Full = HeightClass<100>;
|
||||
using H_Full = HeightClass<100, DimensionType::Percent>;
|
||||
using H_16 = HeightClass<16>;
|
||||
using H_24 = HeightClass<24>;
|
||||
using H_32 = HeightClass<32>;
|
||||
|
||||
// --- display ---
|
||||
template <OuterDisplayType outer, InnerDisplayType inner> struct DisplayClass {
|
||||
// --- flexbox (the sole layout mode; unitless, no theme scaling needed) ---
|
||||
// `Flex` is the no-op default: every element is already a flex container. The
|
||||
// direction/wrap/justify/align/flex-item classes below override the container or
|
||||
// item fields of the resolved style. A bare `Div`/`Panel` is a column container by
|
||||
// default (stacks children top-to-bottom); use `FlexRow` for a horizontal line.
|
||||
template <FlexDirection direction> struct FlexDirClass {
|
||||
static void apply(Style& s, const Theme&) {
|
||||
s.outerDisplay = outer;
|
||||
s.innerDisplay = inner;
|
||||
// don't overwrite display: a Hidden element that also has a FlexDirClass
|
||||
// template (e.g. Div<FlexRow, ...> with display=Hidden set in the ctor)
|
||||
// must stay hidden. only set display=Flex if it wasn't already set.
|
||||
if (s.display != Display::Hidden) s.display = Display::Flex;
|
||||
s.direction = direction;
|
||||
}
|
||||
};
|
||||
using Hidden = DisplayClass<OuterDisplayType::Hidden, InnerDisplayType::Flow>;
|
||||
using Block = DisplayClass<OuterDisplayType::Block, InnerDisplayType::Flow>;
|
||||
using Inline = DisplayClass<OuterDisplayType::Inline, InnerDisplayType::Flow>;
|
||||
using Flex = FlexDirClass<FlexDirection::Row>; // display:flex (tailwind default is row)
|
||||
using FlexRow = FlexDirClass<FlexDirection::Row>;
|
||||
using FlexRowReverse = FlexDirClass<FlexDirection::RowReverse>;
|
||||
using FlexCol = FlexDirClass<FlexDirection::Column>;
|
||||
using FlexColReverse = FlexDirClass<FlexDirection::ColumnReverse>;
|
||||
|
||||
// `Hidden` mirrors CSS `display:none` — the one non-flex `display` state.
|
||||
template <Display display> struct DisplayClass {
|
||||
static void apply(Style& s, const Theme&) { s.display = display; }
|
||||
};
|
||||
using Hidden = DisplayClass<Display::Hidden>;
|
||||
|
||||
template <FlexWrap wrap> struct WrapClass {
|
||||
static void apply(Style& s, const Theme&) { s.wrap = wrap; }
|
||||
};
|
||||
using Wrap = WrapClass<FlexWrap::Wrap>;
|
||||
using NoWrap = WrapClass<FlexWrap::NoWrap>;
|
||||
|
||||
template <JustifyContent justify> struct JustifyClass {
|
||||
static void apply(Style& s, const Theme&) { s.justify = justify; }
|
||||
};
|
||||
using Justify_Start = JustifyClass<JustifyContent::Start>;
|
||||
using Justify_End = JustifyClass<JustifyContent::End>;
|
||||
using Justify_Center = JustifyClass<JustifyContent::Center>;
|
||||
using Justify_Between = JustifyClass<JustifyContent::SpaceBetween>;
|
||||
using Justify_Around = JustifyClass<JustifyContent::SpaceAround>;
|
||||
using Justify_Evenly = JustifyClass<JustifyContent::SpaceEvenly>;
|
||||
|
||||
// cross-axis alignment. `Items_*` sets the container default (inherited by items);
|
||||
// `Self_*` overrides it per-item (no baseline alignment — see the plan).
|
||||
template <AlignType align> struct ItemsClass {
|
||||
static void apply(Style& s, const Theme&) { s.items = align; }
|
||||
};
|
||||
using Items_Start = ItemsClass<AlignType::Start>;
|
||||
using Items_Center = ItemsClass<AlignType::Center>;
|
||||
using Items_End = ItemsClass<AlignType::End>;
|
||||
using Items_Stretch = ItemsClass<AlignType::Stretch>;
|
||||
|
||||
template <AlignType align> struct SelfClass {
|
||||
static void apply(Style& s, const Theme&) { s.alignSelfOverride = (float)align; }
|
||||
};
|
||||
using Self_Start = SelfClass<AlignType::Start>;
|
||||
using Self_Center = SelfClass<AlignType::Center>;
|
||||
using Self_End = SelfClass<AlignType::End>;
|
||||
using Self_Stretch = SelfClass<AlignType::Stretch>;
|
||||
|
||||
// per-item flex sizing. `Grow` = flex-grow:1 (tailwind). `Grow_0`/`Shrink_0` lock
|
||||
// the item to its basis. `Basis_*` sets the main-axis basis (auto/px/percent/full).
|
||||
template <float grow> struct GrowClass {
|
||||
static void apply(Style& s, const Theme&) { s.grow = grow; }
|
||||
};
|
||||
using Grow = GrowClass<1.f>;
|
||||
using Grow_0 = GrowClass<0.f>;
|
||||
using Grow_2 = GrowClass<2.f>;
|
||||
using Grow_3 = GrowClass<3.f>;
|
||||
using Grow_5 = GrowClass<5.f>;
|
||||
template <float shrink> struct ShrinkClass {
|
||||
static void apply(Style& s, const Theme&) { s.shrink = shrink; }
|
||||
};
|
||||
using Shrink_0 = ShrinkClass<0.f>;
|
||||
template <int32 order> struct OrderClass {
|
||||
static void apply(Style& s, const Theme&) { s.order = order; }
|
||||
};
|
||||
using Order_1 = OrderClass<1>;
|
||||
using Order_2 = OrderClass<2>;
|
||||
using Order_3 = OrderClass<3>;
|
||||
using Order_4 = OrderClass<4>;
|
||||
using Order_5 = OrderClass<5>;
|
||||
template <float basis, DimensionType basisType> struct BasisClass {
|
||||
static void apply(Style& s, const Theme&) {
|
||||
s.basis = basis;
|
||||
s.basisType = basisType;
|
||||
}
|
||||
};
|
||||
using Basis_Auto = BasisClass<0.f, DimensionType::Auto>;
|
||||
using Basis_Full = BasisClass<100.f, DimensionType::Percent>;
|
||||
using Basis_16 = BasisClass<16.f, DimensionType::Pixel>;
|
||||
using Basis_32 = BasisClass<32.f, DimensionType::Pixel>;
|
||||
using Basis_48 = BasisClass<48.f, DimensionType::Pixel>;
|
||||
using Basis_64 = BasisClass<64.f, DimensionType::Pixel>;
|
||||
using Basis_128 = BasisClass<128.f, DimensionType::Pixel>;
|
||||
using Basis_50Percent = BasisClass<50.f, DimensionType::Percent>;
|
||||
|
||||
// min/max size clamps (main or cross axis) reuse the existing DimensionType sizing.
|
||||
template <uint32 v, DimensionType t> struct MaxWidthClass {
|
||||
static void apply(Style& s, const Theme&) {
|
||||
s.maxWidth = v;
|
||||
s.maxWidthType = t;
|
||||
}
|
||||
};
|
||||
template <uint32 v, DimensionType t> struct MaxHeightClass {
|
||||
static void apply(Style& s, const Theme&) {
|
||||
s.maxHeight = v;
|
||||
s.maxHeightType = t;
|
||||
}
|
||||
};
|
||||
using MaxW_Full = MaxWidthClass<100, DimensionType::Percent>;
|
||||
using MaxH_Full = MaxHeightClass<100, DimensionType::Percent>;
|
||||
|
||||
// --- fonts (looked up at style() time; fonts must be loaded before the first
|
||||
// System::style() call, see the invariant in System.h) ---
|
||||
|
||||
@@ -12,7 +12,7 @@ namespace UI {
|
||||
// the name is runtime data (a string literal can't be a C++ template arg), and
|
||||
// Text::applyStyle resolves it to a PFontAsset (falling back to Theme::defaultFont).
|
||||
struct Font_Arial {
|
||||
static void apply(Style& s, const Theme&) { s.fontName = "arial.ttf"; }
|
||||
static void apply(Style& s, const Theme&) { s.fontName = "arial"; }
|
||||
};
|
||||
} // namespace UI
|
||||
} // namespace Seele
|
||||
+58
-18
@@ -11,38 +11,59 @@ enum class DimensionType {
|
||||
Percent, // EM, PEM, etc...
|
||||
Auto,
|
||||
};
|
||||
enum class PositionType {
|
||||
Static,
|
||||
Relative,
|
||||
Absolute,
|
||||
Sticky,
|
||||
// flexbox layout enums. one layout mode (flex); `Display` is the only visibility
|
||||
// toggle (mirrors CSS `display`), `Position` is a minimal relative/absolute escape hatch.
|
||||
enum class FlexDirection {
|
||||
Row,
|
||||
RowReverse,
|
||||
Column,
|
||||
ColumnReverse,
|
||||
};
|
||||
enum class OuterDisplayType {
|
||||
Inline,
|
||||
Block,
|
||||
Hidden,
|
||||
enum class FlexWrap {
|
||||
NoWrap,
|
||||
Wrap,
|
||||
};
|
||||
enum class InnerDisplayType {
|
||||
Flow,
|
||||
Flex,
|
||||
Grid,
|
||||
enum class JustifyContent {
|
||||
Start,
|
||||
End,
|
||||
Center,
|
||||
SpaceBetween,
|
||||
SpaceAround,
|
||||
SpaceEvenly,
|
||||
};
|
||||
enum class AlignType {
|
||||
Start,
|
||||
Center,
|
||||
End,
|
||||
Stretch,
|
||||
// baseline is intentionally not shipped (needs font metrics); see the plan
|
||||
};
|
||||
enum class Display {
|
||||
Flex, // laid out (default)
|
||||
Hidden, // not laid out, not rendered, not hit-tested
|
||||
};
|
||||
enum class Position {
|
||||
Static, // in the flex flow (default)
|
||||
Relative, // in the flow, offset by left/top from the computed position
|
||||
Absolute, // removed from the flow, offset by left/top from the containing block
|
||||
};
|
||||
struct Style {
|
||||
DimensionType widthType = DimensionType::Auto;
|
||||
float width = 0;
|
||||
// min clamps: a lower bound on the resolved main/cross size. Auto means "no min".
|
||||
DimensionType minWidthType = DimensionType::Auto;
|
||||
float minWidth = 0;
|
||||
DimensionType maxWidthType = DimensionType::Auto;
|
||||
float maxWidth = 0;
|
||||
DimensionType heightType = DimensionType::Auto;
|
||||
float height = 0;
|
||||
DimensionType minHeightType = DimensionType::Auto;
|
||||
float minHeight = 0;
|
||||
DimensionType maxHeightType = DimensionType::Auto;
|
||||
float maxHeight = 0;
|
||||
uint32 z = 0;
|
||||
Vector backgroundColor = Vector(1, 1, 1);
|
||||
Vector textColor = Vector(0, 0, 0);
|
||||
bool hidden = false;
|
||||
OuterDisplayType outerDisplay = OuterDisplayType::Inline;
|
||||
InnerDisplayType innerDisplay = InnerDisplayType::Flow;
|
||||
PositionType position = PositionType::Static;
|
||||
PFontAsset fontFamily;
|
||||
// the font *name* as a runtime string. static font classes can't carry a
|
||||
// string as a template arg (literals can't be NTTPs), so the name is set as
|
||||
@@ -65,8 +86,27 @@ struct Style {
|
||||
uint32 left = 0;
|
||||
uint32 right = 0;
|
||||
|
||||
// --- flexbox (the sole layout mode). one mode: every element is a flex item and,
|
||||
// when it has children, a flex container. defaults mirror a bare CSS flex container:
|
||||
// column direction (stacks children top-to-bottom like the old flow layout), no wrap,
|
||||
// start-justified, stretch cross-aligned. ---
|
||||
Display display = Display::Flex; // replaces the old `hidden` bool
|
||||
Position position = Position::Static; // relative/absolute escape hatch (no sticky)
|
||||
FlexDirection direction = FlexDirection::Column;
|
||||
FlexWrap wrap = FlexWrap::NoWrap;
|
||||
JustifyContent justify = JustifyContent::Start; // main axis
|
||||
AlignType items = AlignType::Stretch; // cross axis, inherited by children
|
||||
AlignType content = AlignType::Stretch; // cross axis, wraps the (possibly wrapped) lines
|
||||
float grow = 0.f; // main-axis free-space weight (item)
|
||||
float shrink = 1.f; // main-axis deficit weight (item)
|
||||
int32 order = 0; // layout order within the line (item)
|
||||
float alignSelfOverride = -1.f; // <0 = inherit `items`; else one of AlignType (item)
|
||||
DimensionType basisType = DimensionType::Auto; // main-axis basis (item)
|
||||
float basis = 0.f;
|
||||
|
||||
// set by the element when a runtime mutation needs a re-style of this subtree
|
||||
bool dirty = false;
|
||||
// default true so we do initial style calculations
|
||||
bool dirty = true;
|
||||
};
|
||||
} // namespace UI
|
||||
} // namespace Seele
|
||||
+21
-27
@@ -1,11 +1,12 @@
|
||||
#include "UI/System.h"
|
||||
#include "UI/Element/Button.h"
|
||||
#include "UI/FlexLayout.h"
|
||||
#include <algorithm>
|
||||
|
||||
using namespace Seele;
|
||||
using namespace Seele::UI;
|
||||
|
||||
void System::markAllDirty(Element* element) {
|
||||
void System::markAllDirty(PElement element) {
|
||||
if (element == nullptr) {
|
||||
return;
|
||||
}
|
||||
@@ -16,12 +17,15 @@ void System::markAllDirty(Element* element) {
|
||||
}
|
||||
}
|
||||
|
||||
void System::styleRec(Element* element) {
|
||||
void System::styleRec(PElement element) {
|
||||
if (element == nullptr) {
|
||||
return;
|
||||
}
|
||||
// keep the element's theme handle in sync so FlexLayout can re-shape Text content on a
|
||||
// theme change (fonts are per-theme) without a friend declaration.
|
||||
element->setTheme(theme);
|
||||
// runtime interaction state overrides the static style (data, not template args)
|
||||
if (auto* button = dynamic_cast<Button<>* >(element)) {
|
||||
if (auto* button = dynamic_cast<Button<>*>(element.getHandle())) {
|
||||
if (button->isFocused()) {
|
||||
element->style.backgroundColor = theme.color(ColorToken::Gray700);
|
||||
}
|
||||
@@ -37,7 +41,7 @@ void System::styleRec(Element* element) {
|
||||
element->themeChanged = false;
|
||||
element->applyStyle({}, theme);
|
||||
// interaction state is a per-frame override; re-apply it after the static resolve
|
||||
if (auto* button = dynamic_cast<Button<>* >(element)) {
|
||||
if (auto* button = dynamic_cast<Button<>* >(element.getHandle())) {
|
||||
if (button->isFocused()) {
|
||||
element->style.backgroundColor = theme.color(ColorToken::Gray700);
|
||||
}
|
||||
@@ -55,34 +59,24 @@ void System::styleRec(Element* element) {
|
||||
}
|
||||
}
|
||||
|
||||
void System::layoutRec(Element* element) {
|
||||
if (element == nullptr) {
|
||||
return;
|
||||
}
|
||||
element->layout(UVector2(lastViewport.x, lastViewport.y));
|
||||
for (auto& child : element->children) {
|
||||
// layout() already recurses; nothing to do here
|
||||
}
|
||||
}
|
||||
|
||||
Element* System::hitTest(Vector2 position) {
|
||||
PElement System::hitTest(Vector2 position) {
|
||||
// walk the last rendered list; later entries are drawn on top, so the last
|
||||
// hit is the top-most element
|
||||
Element* result = nullptr;
|
||||
PElement result = nullptr;
|
||||
for (auto& render : renderElements) {
|
||||
if (render.element == nullptr) {
|
||||
continue;
|
||||
}
|
||||
if (position.x >= render.position.x && position.x < render.position.x + render.dimensions.x &&
|
||||
position.y >= render.position.y && position.y < render.position.y + render.dimensions.y) {
|
||||
result = render.element.operator->();
|
||||
result = render.element;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
void System::collectFocusable(Element* element, Array<Element*>& out) {
|
||||
if (element == nullptr || element->style.hidden) {
|
||||
void System::collectFocusable(PElement element, Array<PElement>& out) {
|
||||
if (element == nullptr || element->style.display == Display::Hidden) {
|
||||
return;
|
||||
}
|
||||
if (element->isFocusable()) {
|
||||
@@ -95,13 +89,13 @@ void System::collectFocusable(Element* element, Array<Element*>& out) {
|
||||
|
||||
void System::processInput() {
|
||||
// hover transitions: the virtual setHovered keeps this free of dynamic_cast
|
||||
Element* under = hitTest(mousePos);
|
||||
PElement under = hitTest(mousePos);
|
||||
if (under != hovered) {
|
||||
if (hovered) {
|
||||
if (hovered != nullptr) {
|
||||
hovered->setHovered(false);
|
||||
}
|
||||
hovered = under;
|
||||
if (hovered) {
|
||||
if (hovered != nullptr) {
|
||||
hovered->setHovered(true);
|
||||
}
|
||||
}
|
||||
@@ -113,7 +107,7 @@ void System::mouseMove(Vector2 position) {
|
||||
|
||||
void System::mouseButton(MouseButton button, InputAction action, KeyModifier, Vector2 position) {
|
||||
mousePos = position;
|
||||
Element* under = hitTest(position);
|
||||
PElement under = hitTest(position);
|
||||
if (under == nullptr) {
|
||||
return;
|
||||
}
|
||||
@@ -121,7 +115,7 @@ void System::mouseButton(MouseButton button, InputAction action, KeyModifier, Ve
|
||||
Vector2 local = position;
|
||||
{
|
||||
// walk up from the hit element, subtracting each parent's position
|
||||
auto* walk = under;
|
||||
auto walk = under;
|
||||
while (walk != nullptr) {
|
||||
local.x -= walk->position.x;
|
||||
local.y -= walk->position.y;
|
||||
@@ -137,7 +131,7 @@ void System::mouseButton(MouseButton button, InputAction action, KeyModifier, Ve
|
||||
}
|
||||
|
||||
void System::scroll(Vector2 delta) {
|
||||
Element* under = hitTest(mousePos);
|
||||
PElement under = hitTest(mousePos);
|
||||
if (under == nullptr) {
|
||||
return;
|
||||
}
|
||||
@@ -160,7 +154,7 @@ void System::key(KeyCode code, InputAction action, KeyModifier modifier, char te
|
||||
if (action == InputAction::PRESS && code == KeyCode::KEY_TAB) {
|
||||
// cycle focus among focusable elements (buttons); the virtual setFocused
|
||||
// keeps this free of dynamic_cast to a concrete template type
|
||||
Array<Element*> focusable;
|
||||
Array<PElement> focusable;
|
||||
collectFocusable(rootElement.operator->(), focusable);
|
||||
if (focusable.size() > 0) {
|
||||
int32 index = -1;
|
||||
@@ -188,7 +182,7 @@ void System::beginFrame(UVector2 viewport) {
|
||||
lastViewport = viewport;
|
||||
if (layoutDirty) {
|
||||
rootElement->calcStyle(Style{}, theme);
|
||||
rootElement->layout(viewport);
|
||||
FlexLayout::layoutRoot(rootElement.operator->(), viewport);
|
||||
layoutDirty = false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -39,13 +39,12 @@ class System {
|
||||
PElement getRoot() { return rootElement; }
|
||||
|
||||
private:
|
||||
void styleRec(Element* element);
|
||||
void layoutRec(Element* element);
|
||||
static void markAllDirty(Element* element);
|
||||
void styleRec(PElement element);
|
||||
static void markAllDirty(PElement element);
|
||||
// hit-test the last rendered list, top-most wins; returns the element under `position`
|
||||
Element* hitTest(Vector2 position);
|
||||
PElement hitTest(Vector2 position);
|
||||
// walks the tree in layout order, collecting focusable elements (for tab navigation)
|
||||
void collectFocusable(Element* element, Array<Element*>& out);
|
||||
void collectFocusable(PElement element, Array<PElement>& out);
|
||||
|
||||
OElement rootElement;
|
||||
Theme theme;
|
||||
@@ -53,8 +52,8 @@ class System {
|
||||
bool layoutDirty = true;
|
||||
// input state
|
||||
Vector2 mousePos = Vector2(0);
|
||||
Element* hovered = nullptr;
|
||||
Element* focused = nullptr;
|
||||
PElement hovered = nullptr;
|
||||
PElement focused = nullptr;
|
||||
Array<UIRender> renderElements;
|
||||
};
|
||||
DEFINE_REF(System)
|
||||
|
||||
@@ -16,6 +16,7 @@ View::~View() {}
|
||||
void View::resize(URect area) {
|
||||
createInfo.dimensions = area;
|
||||
viewport->resize(area.size.x, area.size.y);
|
||||
viewport->move(area.offset.x, area.offset.y);
|
||||
applyArea(area);
|
||||
}
|
||||
|
||||
|
||||
@@ -46,11 +46,18 @@ void Window::setFocused(PView view) {
|
||||
}
|
||||
|
||||
void Window::onResize(uint32 width, uint32 height) {
|
||||
for (auto& view : views) {
|
||||
// TODO: some sort of layouting algorithm should do this
|
||||
view->resize(URect{
|
||||
.size = UVector2(width, height),
|
||||
.offset = UVector2(0, 0),
|
||||
// one column per view, in registration order. 2 views = a 50/50 split.
|
||||
const uint32 n = views.size();
|
||||
if (n == 0) {
|
||||
return;
|
||||
}
|
||||
const uint32 colWidth = width / n;
|
||||
for (uint32 i = 0; i < n; ++i) {
|
||||
uint32 x = i * colWidth;
|
||||
uint32 w = (i == n - 1) ? (width - x) : colWidth;
|
||||
views[i]->resize(URect{
|
||||
.size = UVector2(w, height),
|
||||
.offset = UVector2(x, 0),
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -4,8 +4,10 @@ target_sources(SeeleUnitTests
|
||||
ThreadPool.cpp)
|
||||
|
||||
target_include_directories(SeeleUnitTests PUBLIC ./)
|
||||
target_include_directories(SeeleUnitTests PUBLIC ${CMAKE_SOURCE_DIR}/src/Editor)
|
||||
add_subdirectory(Containers/)
|
||||
add_subdirectory(Graphics/)
|
||||
add_subdirectory(Math/)
|
||||
add_subdirectory(Serialization/)
|
||||
add_subdirectory(System/)
|
||||
add_subdirectory(System/)
|
||||
add_subdirectory(UI/)
|
||||
@@ -0,0 +1,5 @@
|
||||
target_sources(SeeleUnitTests
|
||||
PRIVATE
|
||||
FlexLayout.cpp)
|
||||
|
||||
target_include_directories(SeeleUnitTests PUBLIC ${CMAKE_SOURCE_DIR}/src/Engine)
|
||||
@@ -0,0 +1,367 @@
|
||||
// CPU-only flexbox layout tests. Build caller-owned Div/Text trees (no System, so the
|
||||
// OwningPtr never deletes them), run FlexLayout::layoutRoot, assert position/dimensions.
|
||||
#include "gtest/gtest.h"
|
||||
#include "UI/Element.h"
|
||||
#include "UI/Element/Div.h"
|
||||
#include "UI/FlexLayout.h"
|
||||
#include "UI/Style/Class.h"
|
||||
#include "UI/Style/Theme.h"
|
||||
|
||||
using namespace Seele;
|
||||
using namespace Seele::UI;
|
||||
|
||||
// style the tree like System::styleRec would (flexbox math runs on the resolved style).
|
||||
// mark the whole subtree dirty first so the Div template classes (applied in
|
||||
// applyStyle, gated on style.dirty/themeChanged) actually run — a freshly built tree
|
||||
// has neither flag set. tests use explicit sizes, so the font is never shaped.
|
||||
static void markAllDirtyRec(PElement el) {
|
||||
if (el == nullptr) return;
|
||||
el->markDirty();
|
||||
// children are OwningPtr (move-only) — iterate by const ref, never copy.
|
||||
for (const auto& c : el->getChildren()) markAllDirtyRec(c);
|
||||
}
|
||||
static void resolveStyles(PElement root) {
|
||||
markAllDirtyRec(root);
|
||||
Theme theme{};
|
||||
root->calcStyle(Style{}, theme);
|
||||
}
|
||||
|
||||
// layout a caller-owned tree against `viewport` (the tree is never deleted here).
|
||||
static void layout(PElement root, int vw, int vh) {
|
||||
FlexLayout::layoutRoot(root, UVector2(vw, vh));
|
||||
}
|
||||
|
||||
// (a) row, fixed sizes, gap, justify start/end/center
|
||||
TEST(FlexLayout, RowGapJustify) {
|
||||
OElement a = new Div<W_64, H_32>(Attributes{});
|
||||
OElement b = new Div<W_64, H_32>(Attributes{});
|
||||
PElement aRef = a;
|
||||
PElement bRef = b;
|
||||
OElement root = new Div<FlexRow, G_8, W_Full, H_Full>({Attributes{}}, {std::move(a), std::move(b)});
|
||||
resolveStyles(root);
|
||||
layout(root, 300, 100);
|
||||
// two 64px items + 8px gap, start-justified: x=0 and x=72, y=0, cross stretch?
|
||||
// items have explicit H_32, so no stretch (explicit wins); align default = stretch
|
||||
// but explicit size wins -> y=0, h=32.
|
||||
EXPECT_NEAR(aRef->getLayoutPosition().x, 0.0f, 0.01f);
|
||||
EXPECT_NEAR(aRef->getLayoutPosition().y, 0.0f, 0.01f);
|
||||
EXPECT_NEAR(aRef->getLayoutDimensions().x, 64.0f, 0.01f);
|
||||
EXPECT_NEAR(bRef->getLayoutPosition().x, 72.0f, 0.01f);
|
||||
EXPECT_NEAR(bRef->getLayoutDimensions().y, 32.0f, 0.01f);
|
||||
|
||||
// end-justified: last item flush to the right edge
|
||||
OElement c = new Div<W_64, H_32>(Attributes{});
|
||||
OElement d = new Div<W_64, H_32>(Attributes{});
|
||||
PElement cRef = c;
|
||||
PElement dRef = d;
|
||||
OElement end = new Div<FlexRow, G_8, Justify_End, W_Full, H_Full>({Attributes{}}, {std::move(c), std::move(d)});
|
||||
resolveStyles(end);
|
||||
layout(end, 300, 100);
|
||||
// total = 64 + 8 + 64 = 136; start at 300 - 136 = 164
|
||||
EXPECT_NEAR(cRef->getLayoutPosition().x, 164.0f, 0.01f);
|
||||
EXPECT_NEAR(dRef->getLayoutPosition().x, 164.0f + 72.0f, 0.01f);
|
||||
|
||||
// center-justified
|
||||
OElement e = new Div<W_64, H_32>(Attributes{});
|
||||
OElement f = new Div<W_64, H_32>(Attributes{});
|
||||
PElement eRef = e;
|
||||
PElement fRef = f;
|
||||
OElement center = new Div<FlexRow, G_8, Justify_Center, W_Full, H_Full>({Attributes{}}, {std::move(e), std::move(f)});
|
||||
resolveStyles(center);
|
||||
layout(center, 300, 100);
|
||||
// free = 300 - 136 = 164; center offset = 82
|
||||
EXPECT_NEAR(eRef->getLayoutPosition().x, 82.0f, 0.01f);
|
||||
EXPECT_NEAR(fRef->getLayoutPosition().x, 82.0f + 72.0f, 0.01f);
|
||||
}
|
||||
|
||||
// (b) column: default direction stacks top-to-bottom
|
||||
TEST(FlexLayout, ColumnDefault) {
|
||||
OElement a = new Div<W_64, H_32>(Attributes{});
|
||||
OElement b = new Div<W_64, H_32>(Attributes{});
|
||||
PElement aRef = a;
|
||||
PElement bRef = b;
|
||||
OElement root = new Div<W_Full, H_Full>({Attributes{}}, {std::move(a), std::move(b)});
|
||||
resolveStyles(root);
|
||||
layout(root, 300, 200);
|
||||
EXPECT_NEAR(aRef->getLayoutPosition().y, 0.0f, 0.01f);
|
||||
EXPECT_NEAR(bRef->getLayoutPosition().y, 32.0f, 0.01f);
|
||||
// stretch is the default: a W_64 item stays 64 wide (explicit wins); y is packed
|
||||
EXPECT_NEAR(aRef->getLayoutDimensions().x, 64.0f, 0.01f);
|
||||
EXPECT_NEAR(bRef->getLayoutPosition().x, 0.0f, 0.01f);
|
||||
}
|
||||
|
||||
// (c) one child with Grow absorbs all the free space
|
||||
TEST(FlexLayout, GrowAbsorbsFreeSpace) {
|
||||
OElement fixed = new Div<W_48, H_32>(Attributes{});
|
||||
OElement grow = new Div<Grow, H_32>(Attributes{});
|
||||
PElement fixedRef = fixed;
|
||||
PElement growRef = grow;
|
||||
OElement root = new Div<FlexRow, W_Full, H_Full>({Attributes{}}, {std::move(fixed), std::move(grow)});
|
||||
resolveStyles(root);
|
||||
layout(root, 200, 100);
|
||||
EXPECT_NEAR(fixedRef->getLayoutDimensions().x, 48.0f, 0.01f);
|
||||
EXPECT_NEAR(growRef->getLayoutPosition().x, 48.0f, 0.01f);
|
||||
// 200 - 48 free goes to the grower
|
||||
EXPECT_NEAR(growRef->getLayoutDimensions().x, 152.0f, 0.01f);
|
||||
}
|
||||
|
||||
// (d) two growers split free space proportionally
|
||||
TEST(FlexLayout, GrowSplitsProportionally) {
|
||||
OElement g1 = new Div<Grow, H_32>(Attributes{}); // weight 1
|
||||
OElement g2 = new Div<Grow_2, H_32>(Attributes{}); // weight 2
|
||||
PElement g1Ref = g1;
|
||||
PElement g2Ref = g2;
|
||||
OElement root = new Div<FlexRow, W_Full, H_Full>({Attributes{}}, {std::move(g1), std::move(g2)});
|
||||
resolveStyles(root);
|
||||
layout(root, 300, 100);
|
||||
// 300 total, weights 1:2 -> 100 / 200
|
||||
EXPECT_NEAR(g1Ref->getLayoutDimensions().x, 100.0f, 0.01f);
|
||||
EXPECT_NEAR(g2Ref->getLayoutPosition().x, 100.0f, 0.01f);
|
||||
EXPECT_NEAR(g2Ref->getLayoutDimensions().x, 200.0f, 0.01f);
|
||||
}
|
||||
|
||||
// (e) overflow: a Shrink_0 item keeps its basis; the default-shrink item absorbs the deficit
|
||||
TEST(FlexLayout, ShrinkDeficit) {
|
||||
OElement keep = new Div<Shrink_0, H_32>(Attributes{}); // refuses to shrink
|
||||
keep->setIntrinsicSize(150.0f, 32.0f); // natural main size 150
|
||||
OElement shrink = new Div<H_32>(Attributes{}); // default shrink=1
|
||||
shrink->setIntrinsicSize(150.0f, 32.0f);
|
||||
PElement keepRef = keep;
|
||||
PElement shrinkRef = shrink;
|
||||
OElement root = new Div<FlexRow, W_Full, H_Full>({Attributes{}}, {std::move(keep), std::move(shrink)});
|
||||
resolveStyles(root);
|
||||
layout(root, 180, 100);
|
||||
// total basis 300 in a 180 box: deficit 120 falls entirely on the shrinker (weight 1 vs 0)
|
||||
EXPECT_NEAR(keepRef->getLayoutDimensions().x, 150.0f, 0.01f);
|
||||
EXPECT_NEAR(keepRef->getLayoutPosition().x, 0.0f, 0.01f);
|
||||
EXPECT_NEAR(shrinkRef->getLayoutPosition().x, 150.0f, 0.01f);
|
||||
EXPECT_NEAR(shrinkRef->getLayoutDimensions().x, 30.0f, 0.01f);
|
||||
}
|
||||
|
||||
// (f) wrap: items that don't fit the line flow onto the next line
|
||||
TEST(FlexLayout, Wrap) {
|
||||
// 150px items in a 200px row with wrap: item 2 can't share line 0 (150+8+150 > 200)
|
||||
OElement a = new Div<W_150, H_32>(Attributes{});
|
||||
OElement b = new Div<W_150, H_32>(Attributes{});
|
||||
PElement aRef = a;
|
||||
PElement bRef = b;
|
||||
OElement root = new Div<FlexRow, Wrap, G_8, W_Full, H_Full>({Attributes{}}, {std::move(a), std::move(b)});
|
||||
resolveStyles(root);
|
||||
layout(root, 200, 300);
|
||||
EXPECT_NEAR(aRef->getLayoutPosition().x, 0.0f, 0.01f);
|
||||
EXPECT_NEAR(aRef->getLayoutPosition().y, 0.0f, 0.01f);
|
||||
// line 1 starts below line 0: line0 cross = 32, + gap 8 -> y = 40
|
||||
EXPECT_NEAR(bRef->getLayoutPosition().x, 0.0f, 0.01f);
|
||||
EXPECT_NEAR(bRef->getLayoutPosition().y, 40.0f, 0.01f);
|
||||
}
|
||||
|
||||
// (g) align-items: start/center/end on the cross axis (items keep their explicit cross size)
|
||||
TEST(FlexLayout, AlignItems) {
|
||||
// start: item at the top of a 200px-tall row
|
||||
{
|
||||
OElement a = new Div<W_64, H_32>(Attributes{});
|
||||
PElement aRef = a;
|
||||
OElement root = new Div<FlexRow, Items_Start, W_Full, H_Full>({Attributes{}}, {std::move(a)});
|
||||
resolveStyles(root);
|
||||
layout(root, 300, 200);
|
||||
EXPECT_NEAR(aRef->getLayoutPosition().y, 0.0f, 0.01f);
|
||||
EXPECT_NEAR(aRef->getLayoutDimensions().y, 32.0f, 0.01f);
|
||||
}
|
||||
// center: item vertically centered
|
||||
{
|
||||
OElement a = new Div<W_64, H_32>(Attributes{});
|
||||
PElement aRef = a;
|
||||
OElement root = new Div<FlexRow, Items_Center, W_Full, H_Full>({Attributes{}}, {std::move(a)});
|
||||
resolveStyles(root);
|
||||
layout(root, 300, 200);
|
||||
EXPECT_NEAR(aRef->getLayoutPosition().y, (200.0f - 32.0f) * 0.5f, 0.01f);
|
||||
}
|
||||
// end: item at the bottom
|
||||
{
|
||||
OElement a = new Div<W_64, H_32>(Attributes{});
|
||||
PElement aRef = a;
|
||||
OElement root = new Div<FlexRow, Items_End, W_Full, H_Full>({Attributes{}}, {std::move(a)});
|
||||
resolveStyles(root);
|
||||
layout(root, 300, 200);
|
||||
EXPECT_NEAR(aRef->getLayoutPosition().y, 200.0f - 32.0f, 0.01f);
|
||||
}
|
||||
// stretch: an Auto-height item fills the cross axis (default items is stretch,
|
||||
// so a bare container already does this; assert it explicitly)
|
||||
{
|
||||
OElement a = new Div<W_64>(Attributes{});
|
||||
a->setIntrinsicSize(64.0f, 32.0f);
|
||||
PElement aRef = a;
|
||||
OElement root = new Div<FlexRow, W_Full, H_Full>({Attributes{}}, {std::move(a)});
|
||||
resolveStyles(root);
|
||||
layout(root, 300, 200);
|
||||
EXPECT_NEAR(aRef->getLayoutDimensions().y, 200.0f, 0.01f);
|
||||
EXPECT_NEAR(aRef->getLayoutPosition().y, 0.0f, 0.01f);
|
||||
}
|
||||
}
|
||||
|
||||
// (h) order reorders flow items (layout order, not DOM order)
|
||||
TEST(FlexLayout, Order) {
|
||||
OElement a = new Div<W_64, H_32, Order_2>(Attributes{});
|
||||
OElement b = new Div<W_64, H_32, Order_1>(Attributes{});
|
||||
PElement aRef = a;
|
||||
PElement bRef = b;
|
||||
OElement root = new Div<FlexRow, G_8, W_Full, H_Full>({Attributes{}}, {std::move(a), std::move(b)});
|
||||
resolveStyles(root);
|
||||
layout(root, 300, 100);
|
||||
// b (order 1) comes before a (order 2)
|
||||
EXPECT_NEAR(bRef->getLayoutPosition().x, 0.0f, 0.01f);
|
||||
EXPECT_NEAR(aRef->getLayoutPosition().x, 72.0f, 0.01f);
|
||||
}
|
||||
|
||||
// align-self override: the item's own align beats the container's
|
||||
TEST(FlexLayout, AlignSelfOverride) {
|
||||
OElement a = new Div<W_64, H_32, Self_Center>(Attributes{});
|
||||
PElement aRef = a;
|
||||
OElement root = new Div<FlexRow, Items_Start, W_Full, H_Full>({Attributes{}}, {std::move(a)});
|
||||
resolveStyles(root);
|
||||
layout(root, 300, 200);
|
||||
// container says start (y=0), the item overrides to center
|
||||
EXPECT_NEAR(aRef->getLayoutPosition().y, (200.0f - 32.0f) * 0.5f, 0.01f);
|
||||
}
|
||||
|
||||
// (i) percent basis: Basis_50Percent resolves against the container's content main
|
||||
TEST(FlexLayout, PercentBasis) {
|
||||
OElement a = new Div<Basis_50Percent, H_32>(Attributes{});
|
||||
OElement b = new Div<Basis_50Percent, H_32>(Attributes{});
|
||||
PElement aRef = a;
|
||||
PElement bRef = b;
|
||||
OElement root = new Div<FlexRow, W_Full, H_Full>({Attributes{}}, {std::move(a), std::move(b)});
|
||||
resolveStyles(root);
|
||||
layout(root, 300, 100);
|
||||
// each item's basis = 50% of 300 = 150; no free space, no grow -> stays 150
|
||||
EXPECT_NEAR(aRef->getLayoutDimensions().x, 150.0f, 0.01f);
|
||||
EXPECT_NEAR(bRef->getLayoutPosition().x, 150.0f, 0.01f);
|
||||
EXPECT_NEAR(bRef->getLayoutDimensions().x, 150.0f, 0.01f);
|
||||
}
|
||||
|
||||
// (j) min/max clamps: an explicit size is clamped to [min, max]
|
||||
TEST(FlexLayout, MinMaxClamp) {
|
||||
// maxWidth 64 clamps a 100px explicit width down to 64
|
||||
{
|
||||
OElement a = new Div<W_100, MaxWidthClass<64, DimensionType::Pixel>, H_32>(Attributes{});
|
||||
PElement aRef = a;
|
||||
OElement root = new Div<FlexRow, W_Full, H_Full>({Attributes{}}, {std::move(a)});
|
||||
resolveStyles(root);
|
||||
layout(root, 300, 100);
|
||||
EXPECT_NEAR(aRef->getLayoutDimensions().x, 64.0f, 0.01f);
|
||||
}
|
||||
// minWidth 80 clamps a 40px explicit width up to 80. set AFTER resolveStyles:
|
||||
// applyStyle resets non-inherited fields (minWidth etc) to defaults, so a
|
||||
// pre-set minWidth would be clobbered by the re-style. layout reads the style
|
||||
// at layout time, so a post-resolve mutation is honored.
|
||||
{
|
||||
OElement a = new Div<W_40, H_32>(Attributes{});
|
||||
PElement aRef = a;
|
||||
OElement root = new Div<FlexRow, W_Full, H_Full>({Attributes{}}, {std::move(a)});
|
||||
resolveStyles(root);
|
||||
aRef->getStyle().minWidth = 80;
|
||||
aRef->getStyle().minWidthType = DimensionType::Pixel;
|
||||
layout(root, 300, 100);
|
||||
EXPECT_NEAR(aRef->getLayoutDimensions().x, 80.0f, 0.01f);
|
||||
}
|
||||
}
|
||||
|
||||
// (k) position:relative: offset applied on top of the flow position
|
||||
TEST(FlexLayout, RelativeOffset) {
|
||||
OElement a = new Div<W_64, H_32>(Attributes{});
|
||||
OElement b = new Div<W_64, H_32>(Attributes{});
|
||||
PElement aRef = a;
|
||||
PElement bRef = b;
|
||||
OElement root = new Div<FlexRow, G_8, W_Full, H_Full>({Attributes{}}, {std::move(a), std::move(b)});
|
||||
resolveStyles(root);
|
||||
// set position/left/top AFTER resolveStyles: applyStyle resets position to
|
||||
// Static and left/top to 0, so pre-set values would be clobbered. layout
|
||||
// reads the style at layout time, so a post-resolve mutation is honored.
|
||||
aRef->getStyle().position = Position::Relative;
|
||||
aRef->getStyle().left = 10;
|
||||
aRef->getStyle().top = 5;
|
||||
layout(root, 300, 100);
|
||||
// a is still in the flow at x=0 but drawn offset by (10, 5); b is unaffected
|
||||
EXPECT_NEAR(aRef->getLayoutPosition().x, 10.0f, 0.01f);
|
||||
EXPECT_NEAR(aRef->getLayoutPosition().y, 5.0f, 0.01f);
|
||||
EXPECT_NEAR(bRef->getLayoutPosition().x, 72.0f, 0.01f);
|
||||
}
|
||||
|
||||
// (l) position:absolute: removed from the flow, positioned from the container's content corner
|
||||
TEST(FlexLayout, AbsolutePosition) {
|
||||
OElement abs = new Div<W_32, H_32>(Attributes{});
|
||||
OElement flow = new Div<W_64, H_32>(Attributes{});
|
||||
PElement absRef = abs;
|
||||
PElement flowRef = flow;
|
||||
OElement root = new Div<FlexRow, W_Full, H_Full>({Attributes{}}, {std::move(abs), std::move(flow)});
|
||||
resolveStyles(root);
|
||||
// set position/left/top AFTER resolveStyles: applyStyle resets position to
|
||||
// Static and left/top to 0, so pre-set values would be clobbered. layout
|
||||
// reads the style at layout time, so a post-resolve mutation is honored.
|
||||
absRef->getStyle().position = Position::Absolute;
|
||||
absRef->getStyle().left = 12;
|
||||
absRef->getStyle().top = 7;
|
||||
layout(root, 300, 100);
|
||||
// the absolute item is out of the flow: the flow item takes the full line
|
||||
EXPECT_NEAR(flowRef->getLayoutPosition().x, 0.0f, 0.01f);
|
||||
// absolute is at the container's content corner + (left, top); the container has
|
||||
// no padding, so it's exactly (12, 7) in the container's parent space.
|
||||
EXPECT_NEAR(absRef->getLayoutPosition().x, 12.0f, 0.01f);
|
||||
EXPECT_NEAR(absRef->getLayoutPosition().y, 7.0f, 0.01f);
|
||||
}
|
||||
|
||||
// (m) nested flex: a Div-in-Div with its own children lays out correctly at both levels
|
||||
TEST(FlexLayout, NestedFlex) {
|
||||
// inner row of two 32px items; outer column stacks it with a sibling
|
||||
OElement in1 = new Div<W_32, H_16>(Attributes{});
|
||||
OElement in2 = new Div<W_32, H_16>(Attributes{});
|
||||
PElement in1Ref = in1;
|
||||
PElement in2Ref = in2;
|
||||
// inner is W_Full (fills the outer's content width) but Auto height:
|
||||
// its cross size falls back to the content measurement (max child = 16).
|
||||
// an explicit H_Full would resolve to 100% of the outer's 100px height,
|
||||
// which is wrong for this test — the inner should size to its children.
|
||||
OElement inner = new Div<FlexRow, W_Full>({Attributes{}}, {std::move(in1), std::move(in2)});
|
||||
PElement innerRef = inner;
|
||||
OElement sibling = new Div<W_Full, H_24>(Attributes{});
|
||||
PElement siblingRef = sibling;
|
||||
OElement outer = new Div<W_Full, H_Full, P_4>({Attributes{}}, {std::move(inner), std::move(sibling)});
|
||||
resolveStyles(outer);
|
||||
layout(outer, 200, 100);
|
||||
// outer has P_4 padding: content origin at (4, 4). inner is W_Full -> fills
|
||||
// the 200-8=192 wide content; its H is Auto -> content height = max child = 16.
|
||||
EXPECT_NEAR(innerRef->getLayoutPosition().x, 4.0f, 0.01f);
|
||||
EXPECT_NEAR(innerRef->getLayoutPosition().y, 4.0f, 0.01f);
|
||||
EXPECT_NEAR(innerRef->getLayoutDimensions().x, 192.0f, 0.01f);
|
||||
EXPECT_NEAR(innerRef->getLayoutDimensions().y, 16.0f, 0.01f);
|
||||
// sibling stacks below inner: y = 4 + 16 + 0 (no gap) = 20
|
||||
EXPECT_NEAR(siblingRef->getLayoutPosition().y, 20.0f, 0.01f);
|
||||
// inner row: in1 at x=4+0, in2 at x=4+32
|
||||
EXPECT_NEAR(in1Ref->getLayoutPosition().x, 4.0f, 0.01f);
|
||||
EXPECT_NEAR(in2Ref->getLayoutPosition().x, 36.0f, 0.01f);
|
||||
}
|
||||
|
||||
// (n) hidden: a Hidden element is not laid out and its siblings are not pushed by it
|
||||
TEST(FlexLayout, HiddenSkipsLayout) {
|
||||
OElement a = new Div<W_64, H_32>(Attributes{});
|
||||
OElement hidden = new Div<W_64, H_32>(Attributes{});
|
||||
OElement c = new Div<W_64, H_32>(Attributes{});
|
||||
PElement aRef = a;
|
||||
PElement hiddenRef = hidden;
|
||||
PElement cRef = c;
|
||||
OElement root = new Div<FlexRow, G_8, W_Full, H_Full>({Attributes{}}, {std::move(a), std::move(hidden), std::move(c)});
|
||||
resolveStyles(root);
|
||||
// set Hidden AFTER resolveStyles: applyStyle resets style=parentStyle, which
|
||||
// would clobber a pre-set display=Hidden. the runtime mutation path is
|
||||
// set-style-field + markDirty, but markDirty triggers a re-style that resets
|
||||
// from parent. so set it after the final re-style, before layout.
|
||||
hiddenRef->getStyle().display = Display::Hidden;
|
||||
layout(root, 300, 100);
|
||||
// a at x=0; the hidden item contributes no footprint and no gap; c at x=72
|
||||
EXPECT_NEAR(aRef->getLayoutPosition().x, 0.0f, 0.01f);
|
||||
EXPECT_NEAR(cRef->getLayoutPosition().x, 72.0f, 0.01f);
|
||||
// the hidden element itself is zeroed
|
||||
EXPECT_NEAR(hiddenRef->getLayoutPosition().x, 0.0f, 0.01f);
|
||||
EXPECT_NEAR(hiddenRef->getLayoutDimensions().x, 0.0f, 0.01f);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user