Commiting plans

This commit is contained in:
Dynamitos committed 2026-11-07 16:52:53 +01:00
1 parent b063925b1b
commit 680851f4d4
7 files changed
+272 -97

No files matched your search

+2 -1
View File
@@ -10,4 +10,5 @@ build/
.DS_Store .DS_Store
*.json *.json
import/models/**/*.ktx import/models/**/*.ktx
.cache .cache
.gitignore
+1
View File
@@ -0,0 +1 @@
Make large file edits in smaller chunks, as the edit tool has a timeout/size limit
+35 -35
View File
@@ -1,35 +1,35 @@
cmake_minimum_required(VERSION 3.7...3.23) cmake_minimum_required(VERSION 3.7...3.23)
if(${CMAKE_VERSION} VERSION_LESS 3.12) if(${CMAKE_VERSION} VERSION_LESS 3.12)
cmake_policy(VERSION ${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION}) cmake_policy(VERSION ${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION})
endif() endif()
set(CMAKE_CXX_STANDARD 23) set(CMAKE_CXX_STANDARD 23)
set(VCPKG_INSTALL_OPTIONS "--allow-unsupported") set(VCPKG_INSTALL_OPTIONS "--allow-unsupported")
set(CMAKE_EXPORT_COMPILE_COMMANDS ON) set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
set(CMAKE_TOOLCHAIN_FILE ${CMAKE_CURRENT_SOURCE_DIR}/external/Seele/external/vcpkg/scripts/buildsystems/vcpkg.cmake) set(CMAKE_TOOLCHAIN_FILE ${CMAKE_CURRENT_SOURCE_DIR}/external/Seele/external/vcpkg/scripts/buildsystems/vcpkg.cmake)
project(MeshShadingDemo) project(MeshShadingDemo)
set(CMAKE_DEBUG_POSTFIX "") set(CMAKE_DEBUG_POSTFIX "")
set(CMAKE_SHARED_LIBRARY_PREFIX "") set(CMAKE_SHARED_LIBRARY_PREFIX "")
set(CMAKE_BINARY_DIR ${CMAKE_CURRENT_SOURCE_DIR}/bin) set(CMAKE_BINARY_DIR ${CMAKE_CURRENT_SOURCE_DIR}/bin)
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY_DEBUG ${CMAKE_CURRENT_SOURCE_DIR}/bin) set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY_DEBUG ${CMAKE_CURRENT_SOURCE_DIR}/bin)
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY_RELEASE ${CMAKE_CURRENT_SOURCE_DIR}/bin) set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY_RELEASE ${CMAKE_CURRENT_SOURCE_DIR}/bin)
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY_RELWITHDEBINFO ${CMAKE_CURRENT_SOURCE_DIR}/bin) set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY_RELWITHDEBINFO ${CMAKE_CURRENT_SOURCE_DIR}/bin)
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY_MINSIZEREL ${CMAKE_CURRENT_SOURCE_DIR}/bin) set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY_MINSIZEREL ${CMAKE_CURRENT_SOURCE_DIR}/bin)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY_DEBUG ${CMAKE_CURRENT_SOURCE_DIR}/bin) set(CMAKE_RUNTIME_OUTPUT_DIRECTORY_DEBUG ${CMAKE_CURRENT_SOURCE_DIR}/bin)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY_RELEASE ${CMAKE_CURRENT_SOURCE_DIR}/bin) set(CMAKE_RUNTIME_OUTPUT_DIRECTORY_RELEASE ${CMAKE_CURRENT_SOURCE_DIR}/bin)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY_RELWITHDEBINFO ${CMAKE_CURRENT_SOURCE_DIR}/bin) set(CMAKE_RUNTIME_OUTPUT_DIRECTORY_RELWITHDEBINFO ${CMAKE_CURRENT_SOURCE_DIR}/bin)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY_MINSIZEREL ${CMAKE_CURRENT_SOURCE_DIR}/bin) set(CMAKE_RUNTIME_OUTPUT_DIRECTORY_MINSIZEREL ${CMAKE_CURRENT_SOURCE_DIR}/bin)
add_subdirectory(external/Seele) add_subdirectory(external/Seele)
add_library(MeshShadingDemo SHARED "") add_library(MeshShadingDemo SHARED "")
target_link_libraries(MeshShadingDemo PUBLIC Engine) target_link_libraries(MeshShadingDemo PUBLIC Engine)
target_include_directories(MeshShadingDemo PRIVATE src/) target_include_directories(MeshShadingDemo PRIVATE src/)
target_compile_definitions(MeshShadingDemo PRIVATE BUILD_DLL) target_compile_definitions(MeshShadingDemo PRIVATE BUILD_DLL)
add_subdirectory(src/) add_subdirectory(src/)
+56 -60
View File
@@ -1,80 +1,76 @@
# UI System: Template-Style Elements for a Robust Editor UI # UI Shader Design: UI Quads vs Text Glyphs (Review)
## Context ## Context
The Seele engine's UI system (`external/Seele/src/Engine/UI/`) currently has: The Seele UI system (`external/Seele/src/Engine/UI/` + `res/shaders/UIPass.slang` + `src/Engine/Graphics/RenderPass/UIPass.cpp`) renders **both** plain UI quads (backgrounds, buttons) and text glyphs through a **single** instanced pipeline:
- `Element` — RTTI base (ref-counted, virtual `applyStyle`/`layout`/`render`), children as `Array<Element*>`/`OElement` - `UIRender` (Element.h) — one struct for both kinds; `isGlyph` flag + `uvOffset`/`uvSize` (currently dead, always 0/1).
- `Style` — plain struct of numeric/enum fields - `UIPass::beginFrame` flattens everything into one `StructuredBuffer<RenderElementStyle>` and one `draw(4, N)` instance call.
- "Style classes" — empty structs with `static void apply(Style&)` (Style/Class.h), so `Div<W_Full>` compiles a tailwindCSS-like style in at compile time - `UIPass.slang` fragment: `if (textureIndex == -1) → flat color; else sample texture, use `.r` as coverage`.
- `Div`, `Text` — the only two elements; `UIPass` renders a flat `Array<UIRender>`
- **No input pipeline** (only a dead `onClick` in `Attributes`), no runtime theming, no `Panel`
**Feasibility verdict (answer to the original question):** the approach is sound — no critical flaw. The risks are practical: (1) input must be a data-driven pipeline on the RTTI base, never template args; (2) instantiation/compile-time explosion — mitigated by a curated alias set (tailwind design tokens), exactly as the user wants; (3) asset-load ordering (fonts/`PFontAsset` must be loaded before first layout — today `Text` does `style.fontFamily->shapeText` with no null check); (4) runtime theming needs a thin override layer alongside the static template defaults; (5) two concrete bugs in `Class.h` (see below). **Question: is sharing the shader for UI elements and text glyphs the right design, or should they be separated?**
**Target:** robust editor UI. Built **once**, rendered fast, explicit mutations that are not cumbersome. Runtime theming + responsive layout are **in scope**. Complex effects/animations are **out of scope** (later, as additional components/styles). ## Findings (what the code actually does today)
## Design (two layers, per user requirements) ### 1. They are *not* really two different fragment programs
1. **Static layer (compile-time):** template style classes, as today. Curated alias set using tailwind's design tokens: The two "cases" differ by **one branch on a data value** (`textureIndex == -1`), not by pipeline state:
- spacing scale: `0,1,2,3,4,5,6,8,10,12,16,20,24,32,40,48,64,80` (px) → `M_*`, `P_*` - No blending difference (both use the same SRC_ALPHA one-minus-src-alpha blend — correct for both flat semi-transparent quads *and* alpha coverage).
- font sizes: tailwind's 11 steps (12→96 with real line-heights; the current `Text_*` aliases already track these — keep names, fix values where they deviate) - No depth/stencil difference (both in the same render pass, same depth config).
- colors: a **fixed palette** (tailwind gray/red/green/blue/amber + a few neutral UI colors) → `BG_*`, `C_*` (text). No open-ended color template args in the engine — keeps instantiation count bounded. - No rasterization difference.
- **Intermediate steps:** `StyleClass` is a concept, not a closed set. Users can declare local classes in their own namespace, e.g. `struct W_37 { static void apply(Style& s){ s.width=37; s.widthType=Pixel; } };` — no engine change needed. This satisfies "declare intermediate steps locally."
2. **Runtime layer (theming/responsiveness):** `UI::Theme` struct (scale factor, palette, font map) + a `ThemeContext` the style pipeline passes alongside the parent `Style`. `applyStyle` resolves *semantic* tokens against the theme (e.g. `M_4` → `4 * theme.spacingScale`, `BG_Red` → `theme.colors.red`). Template classes stay the API; they emit semantic values, the theme scales/maps them at runtime. Window resize stays fully responsive because `layout(viewport)` already takes the viewport and Percent dimensions re-resolve — no new mechanism, only make sure nothing caches viewport-dependent results across frames.
- Explicit mutation API: `Element::setStyle(overrides)` / `Element::setVisible(bool)` etc. — a small, explicit set of setters that dirty the element. No free-form "set any field" API.
## Files to modify (all in `external/Seele/src/Engine/UI/` unless noted) Same pipeline state → same pipeline. Splitting into two shaders would create a **second pipeline + second draw call** for what is literally one `if`. By Vulkan/Metal best practice this is the right unification.
### 2. The real divergence is in the **vertex stage**, and it is already half-broken
- `uvOffset`/`uvSize` exist on `UIRender` for "per-glyph rect in atlas space" but are **never uploaded** — `UIPass.cpp` has no fields for them in `RenderElementStyle` and the shader uses full 0..1 UVs.
- `FontAsset` (Asset/FontAsset.cpp:113) creates **one tiny texture per glyph** (each ~10×20 px, R8_UNORM). So "the glyph quad's UV rect in atlas space" is fiction today — every glyph texture is the whole glyph, full-rect UVs are accidentally correct.
- **This is the actual bug hiding inside the shared shader:** per-glyph textures means thousands of texture objects, thousands of sampler bindings, and the `usedTextures` array grows with unique glyph count (capped at the 1024 descriptor binding count — a hard ceiling that a real font will hit).
### 3. Per-frame cost of the shared path (minor, but real)
- Every `UIRender` uploads a 64-byte struct (color, position, padding, `element` back-ref space) even though the shader only needs ~40 bytes. Fine at editor scale, wasteful at game scale.
- `uiDescriptorLayout->reset()` + full re-bind every frame, 1024 sampler slots.
## Verdict
**Keep the single shader and single instanced draw. Do NOT split into a UI shader and a text shader.** The branch is trivial, the pipelines are state-identical, and one draw call for the whole overlay is a genuine win.
**But do fix the data path that the "same shader" idea is masking:**
| Priority | Change | Why |
|---|---|---|
| 1 (correctness/scale) | **Glyph atlas (per font, not per glyph)**: bake FreeType bitmaps into one N×N R8 texture at `loadGlyphs`, store UV rect per glyph; add `uvOffset`/`uvSize` to `RenderElementStyle` and use them in the shader (the fields already exist on `UIRender` — just wire them through). Removes the 1024-texture ceiling and thousands of GPU objects. | The current design will break at real font sizes; it only "works" for a handful of glyphs. |
| 2 (cleanliness) | Drop the `isGlyph` flag and the "glyph-only" comment block from `UIRender` — after the atlas fix, a glyph quad is just "a quad with a texture and a UV rect". UI quads with textures (icons, background images) use the exact same path. One concept, one struct. | The flag documents an accident, not a design. |
| 3 (later, if it ever matters) | Split the **vertex** stage: background quads don't need UVs at all; but with 4-vertex instancing the savings are ~zero. Skip unless profiling says otherwise. | YAGNI. |
What would justify *separating* in the future (none true today): different blend modes per category, MSAA-specific text rendering (e.g. LCD subpixel), or text needing its own post-process (SDF scaling). None of these are in scope for the editor UI.
## Files to modify (if the fix is approved)
| File | Change | | File | Change |
|---|---| |---|---|
| `Style/Class.h` | Fix `FontClass`/`StringLiteral`; restructure aliases to the curated scale; theme-aware `apply(Style&, const Theme&)` | | `src/Engine/Asset/FontAsset.{h,cpp}` | Per-font atlas texture built once in `loadGlyphs`; `Glyph` stores `uvRect` instead of `OTexture2D`; `RenderGlyph` carries the rect. |
| `Style/Style.h` | Add semantic-token fields (token ids instead of raw values for themed properties), `dirty` flag | | `src/Engine/UI/Element.h` | `UIRender`: remove `isGlyph`; keep `uvOffset`/`uvSize` (now actually used; default full-rect). |
| `Style/Theme.h` (new) | `Theme` struct: scale, palette, fonts; default instance | | `src/Engine/UI/Element/Text.h` | Emit the glyph's UV rect into `UIRender`. |
| `Attributes.h` | Real input attributes: `onClick`, `onHover`, `onFocus`, `onText`, `onScroll` | | `src/Engine/Graphics/RenderPass/UIPass.h/.cpp` | `RenderElementStyle`: add `uvOffset`/`uvSize`; upload from `UIRender`. |
| `Element.h/.cpp` | Input pipeline (see below); `id`/`tag` for explicit mutation; `setVisible` etc.; null-check font before `shapeText` | | `res/shaders/UIPass.slang` | Sample with `uvOffset + uv * uvSize` (one line in fragment; no pipeline changes). |
| `Element/Div.h` | Keep; route through new `applyStyle` signature |
| `Element/Panel.h` (new) | `Panel<...>` = block container with standard chrome (bg, padding, border) as *defaults* that the user's template args override |
| `Element/Text.h` | Route through new signature; null-font safety |
| `Element/Button.h` (new) | first interactive element: click + hover + focus states |
| `System.h/.cpp` (new cpp) | Frame pipeline: `input()` → `style()` (only dirty subtrees) → `layout(viewport)` (dirty or viewport-changed) → `render()`; owns `Theme` |
| `Input/` (new, small) | `HitTest`: reverse mapping from `UIRender` → `Element*` (add back-ref in `UIRender`), top-most-wins picking |
| `../Component/KeyboardInput.h` | Expose last mouse pos + pressed buttons (already computed there) to the UI system |
| `../Graphics/RenderPass/UIPass.h/.cpp` | Feed `KeyboardInput`'s mouse state into `UI::System::input()`; no other changes — it already renders the flat list fine |
## Reuse (do not reinvent)
- Mouse/key/scroll state already aggregated in `System::KeyboardInput` (`src/Engine/System/KeyboardInput.h`) — feed from there; do not add new OS callbacks.
- `GameView`/`Window` input plumbing (`src/Engine/Window/GameView.cpp:100-103`, `Window.cpp:33-39`) already routes GLFW callbacks into `KeyboardInput` — end of the road.
- `UIPass` already consumes the flat `Array<UIRender>` and does per-element + glyph rendering — no GPU-side changes for this scope.
- `AssetRegistry::findFont(folder, name)` (`src/Engine/Asset/AssetRegistry.h:28`) — the real font API; `FontClass` is currently calling it wrong (2 args for the lookup, name includes NUL).
- `DEFINE_REF`/`OElement` lifetime — keep as-is; hit-test back-refs must be **weak** (store a generation/id, not a raw pointer, or document that the UI tree outlives any query — simplest: back-ref is fine because the UI tree is built once and lives as long as the view; note the risk in code).
- Flow layout in `Element::layout`/`flowLayout` — keep, it already handles Percent widths for responsiveness.
## Steps ## Steps
- [ ] **1. Theme foundation** — `Style/Theme.h` (scale, palette, font map, default `Theme`); extend `Style` with the semantic-token representation + a `dirty` flag; `apply(Style&, const Theme&)` new signature on `StyleClass` concept. - [x] 1. Atlas: in `FontAsset::loadGlyphs`, pack glyph bitmaps (simple shelf/row packer is fine — font glyph count per size is bounded) into one R8 texture per `(font, size)`; replace `glyph.texture` with `glyph.uvRect` + a shared `fontSizes[size].atlas` texture.
- [ ] **2. Fix + curate `Class.h`** — delete `StringLiteral`, `FontClass` becomes a template on a `const char*` tag resolved at runtime against `Theme::fonts` (fixes the NUL + wrong-`findFont` bugs at once); regenerate `M_*`/`P_*`/`Text_*`/`BG_*`/`C_*` from the curated scale via the existing `DECLARE_*` macro pattern. - [x] 2. `RenderGlyph`/`UIRender`: carry the UV rect; drop `isGlyph` + dead comments.
- [ ] **3. Plumb theme through the pipeline** — `Element::calcStyle`/`applyStyle` carry `const Theme&` (from `System`); `Div`/`Text`/`Panel` updated to the new signature. - [x] 3. `UIPass`: extend `RenderElementStyle` with `uvOffset`/`uvSize`, upload them; shader samples `offset + uv*size`.
- [ ] **4. Retained-tree hygiene** — `dirty` flag: `setStyle`/`setVisible`/text-setter mark the element; `System::style()` re-styles only dirty subtrees; `layout` re-runs when dirty or viewport size changed; `render()` always emits the flat list. This is the "built once, render fast, explicit mutation" core. - [ ] 4. Verify: existing editor inspector (uses the same pass) still renders text identically; a paragraph of text no longer adds per-glyph textures (check via debug texture listing or descriptor count).
- [ ] **5. Input: data-driven on the base class** — `Attributes` gains `onClick`/`onHover`/`onFocus`/`onText`/`onScroll`; add `Element* backRef` (or id) to `UIRender`; new `Input/` hit-test: walk last-frame `UIRender` list top-most-wins, dispatch callbacks; `System::input(mouse, keys, scroll)` called from `UIPass::beginFrame` using `KeyboardInput`'s state (expose getters there).
- [ ] **6. Focus + text input** — `System` holds `PElement focused`; keyboard text routes to focused element's `onText`; Tab/Shift-Tab move focus over elements with `focusable` attribute. (Needed for editor: search boxes, inspector fields.)
- [ ] **7. `Panel` + `Button`** — `Panel` = styled block container (defaults overridable by the user's template args); `Button` = `Panel` + `onClick` + hover/focus visual states via style overrides (states are *data* toggled by the input pipeline, never template args).
- [ ] **8. Null-font + asset-order guard** — `Text::layout` no-ops (and asserts in debug) if `fontFamily` is null; document the invariant "UI assets loaded before first `System::style()`" — check the editor's load order in `src/Editor/main.cpp` and enforce if needed.
- [ ] **9. Demo** — in `MeshShadingDemo` (`src/`), a minimal UI scene: `Panel<M_4, BG_Gray900>` with a `Button` that toggles a `Text`'s content and a themed color, proving: build-once, fast render, explicit mutation, hover/click, runtime theme scale change.
## Verification ## Verification
1. Build engine + demo (existing CMake/variant setup) — compiles clean, C++23. 1. Build engine (existing CMake variants) — compiles clean.
2. Run through the editor's PlayView (dll path, existing pipeline) — the demo UI appears. 2. Run editor: inspector text renders pixel-identically to before (glyph coverage unchanged — same R8 data, just relocated in an atlas).
3. Manual checklist: hover highlights; click fires `onClick` and mutates text/color **without** rebuilding the tree; window resize keeps `W_Full`/Percent elements responsive; changing `Theme` scale at runtime (a debug key) re-scales spacing/typography next frame with a single re-layout of the dirty tree. 3. Stress: put a long string (all of Unicode Basic Multilingual Plane) in a `Text` element — must not crash on descriptor exhaustion (the 1024 cap is gone; only 1 atlas binding per font-size).
4. Compile-time sanity: build a second `Panel` variant with a different alias set and confirm the demo's build time doesn't jump (curated-set cap working). 4. Confirm single draw call for the UI pass still (no extra pipeline state).
5. No visual regressions in the existing editor inspector (uses the same `UIPass`).
## Explicit non-goals (out of scope, per user) ## Explicit non-goals
- Flexbox/Grid layout (`InnerDisplayType::Flex`/`Grid` exist as enums but are unimplemented) — later. - No SDF/glow text, no subpixel AA, no different blend per category — none in scope.
- Scroll containers, overflow, virtualized lists — later. - No vertex-stage split until profiling shows the 4-vertex overhead matters.
- Animations/transition components — later (the "additional components and styles" the user mentioned; the dirty-flag + per-frame render loop already gives them a hook point).
- Drag & drop, IME/composition, accessibility tree — later.
- Free-form runtime style strings (no `style="..."` parsing) — mutation stays typed and explicit.
+1 -1
+176
View File
@@ -0,0 +1,176 @@
# Flexbox layout: replace the flow layout as the sole layout engine
## Context
The UI system (`src/Engine/UI/`) currently has one layout engine: `Element::flowLayout()`
(`Element.h:108-167`) — a simple left-to-right / top-to-bottom "cursor" flow. It handles
`Inline` (horizontal) and `Block` (own-line) items with `Static`/`Relative` offsets, and has
**no** `flex`, `grow`, `shrink`, `align`, `justify`, `order`, `basis`, or `wrap` support.
`InnerDisplayType::Flex` exists in the enum (`Style.h:25-28`) but `layout()` only ever
switches on `Flow` (`Element.h:110-114`).
Goal: implement the **full** flexbox spec as the **only** layout mode. Remove `block`/`sticky`/
`static`/`inline`/`flow` as distinct concepts; everything is a flex container with a flex
direction. Keep the **tailwind-style** class API (template `StyleClass`s + `Theme` scaling) for
all the new flex properties.
## Current state (what exists to reuse / repurpose)
- `Style` (`Style/Style.h`): already has `widthType/width`, `maxWidth*`, `height*`, `gap`
(set by `GapClass`/`G_n`), `padding*`, `margin*`, `top/bottom/left/right`, `z`, `hidden`,
and `DimensionType{Pixel,Percent,Auto}` (the existing sizing abstraction).
- `Style` currently carries the layout enums to REMOVE:
- `OuterDisplayType{Inline,Block,Hidden}` (`Style.h:19-23`)
- `InnerDisplayType{Flow,Flex,Grid}` (`Style.h:25-28`)
- `PositionType{Static,Relative,Absolute,Sticky}` (`Style.h:13-19`)
- fields `outerDisplay`, `innerDisplay`, `position` (`Style.h:43-45`)
- `Element::layout()` (`Element.h:95-117`) computes `maxDimensions`/`dimensions` then calls
`flowLayout()`. This is the seam to swap. `flowLayout()` (`Element.h:119-167`) is replaced.
- `System` (`System.cpp`) drives `styleRec` → `layoutRec` → `render`; `System::beginFrame`
(`System.cpp:170-186`) is the per-frame driver; `System::hitTest`/`mouseButton` read
`element->position` (`System.cpp:55-110`) — **input stays intact** as long as `position` is
set correctly.
- Tailwind class layer (`Style/Class.h`): `WidthClass/W_Full`, `DisplayClass` (+ `Block`,
`Inline`, `Hidden`), `MarginClass`/`PaddingClass`/`GapClass` + the `SPACE(n)` macro scale,
`TextColorClass`/`BackgroundColorClass`, `FontSizeClass` + `TEXT_STEP`. This is the pattern to
extend with flex classes.
- **Only one real consumer** of the UI tree today:
`src/Editor/Window/InspectorView.cpp:15-20` (a `Div<M_8>` with a nested `Div<BG_Red, Inline>`
+ two `Text`). `Button`/`Panel` are defined but unused. The API-breakage surface is tiny.
- Text auto-sizing: `Text::applyStyle` (`Element/Text.h:33-60`) sets `style.width/height` from
`font->shapeText` when width/height are `Auto`. **This is the existing self-size mechanism**
and it is the hook for `flex-basis:auto` (natural size).
## Design (full flexbox, tailwind-styled)
### 1. New `Style` fields (`Style/Style.h`)
Remove: `OuterDisplayType`, `InnerDisplayType`, `PositionType` (keep only `Relative`/`Absolute` — see below), and the `outerDisplay`/`innerDisplay`/`position` fields. Add:
```
enum class FlexDirection { Row, RowReverse, Column, ColumnReverse };
enum class FlexWrap { NoWrap, Wrap };
enum class JustifyContent { Start, End, Center, SpaceBetween, SpaceAround, SpaceEvenly };
enum class AlignType { Start, Center, End, Stretch }; // cross-axis (items/self/content); no Baseline yet
enum class Display { Flex, Hidden }; // mirrors CSS `display`; only two states
enum class Position { Static, Relative, Absolute }; // minimal absolute/relative escape hatch
// container (flex) properties
direction=Row, wrap=NoWrap, justify=Start, items=Stretch, content=Stretch,
float gap (already exists)
// per-item properties
grow=0, shrink=1, order=0,
DimensionType basisType=Auto; float basis=0;
Display display=Flex; // replaces `hidden` bool -> display==Hidden
Position position=Static; // replaces PositionType (no Sticky)
float alignSelfOverride=-1; // <0 = inherit items; else one of AlignType
```
`hidden` (bool) is replaced by `display==Display::Hidden`. Every existing `style.hidden` read
(`System.cpp` focus walk, `Element::layout`, `Element::render`, `Text::render`) and the
`style.outerDisplay == Hidden` check becomes a single `style.display == Display::Hidden` check.
Keep `top/left/right/bottom` (already `float`/`uint32`) for relative/absolute offsets.
`DimensionType{Pixel,Percent,Auto}` is reused for `basis` (`basisType`) exactly like `width`.
### 2. Tailwind flex classes (`Style/Class.h`) — the public API
Follow the existing `template<...>struct X{ static void apply(Style&, const Theme&); }` pattern
and the `SPACE(n)`/`TEXT_STEP` macro idiom. New aliases (confirmed naming):
- **display/direction**: `Flex` (display:flex, direction=row), `FlexRow`, `FlexCol`,
`FlexRowReverse`, `FlexColReverse`. (No `Block`/`Inline`/`DisplayClass` — removed.)
- **wrap**: `Wrap`, `NoWrap`.
- **per-item flex**: `Grow` (grow:1), `Grow_<n>`, `Grow0`/`Shrink0` (grow/shrink:0),
`Shrink_<n>`; `Basis_Auto`/`Basis_Full`/`Basis_<px>`/`Basis_<n>Percent`.
- **justify**: `Justify_Start/End/Center/Between/Around/Evenly`.
- **align**: `Items_Start/Center/End/Stretch`, `Self_Start/Center/End/Stretch` (no baseline).
- **order**: `Order_<n>`.
- **sizing reuse**: `W_Full`/`WidthClass`, `H_Full` already exist — reuse for width/height;
extend with min/max variants if trivial (`MaxW_<px>`/`MaxH_<px>` map to existing
`maxWidth`/`maxHeight`). `Gap` reuses existing `G_n` (`GapClass`). `M_*`/`P_*` unchanged.
A small `FlexClass`/`FlexDirClass`/`JustifyClass`/`ItemsClass` template set + the `using` aliases
above. No new theme plumbing needed (flex props are unitless). `Hidden` becomes
`DisplayClass<Display::Hidden>` (keeps the `Hidden` name for the demo/compat).
### 3. The layout engine — a free function, not a method
`System` owns its root with `OwningPtr` and **deletes the whole tree in `~System`**
(`System.h:50`, `MinimalEngine.h` `OwningPtr`), so a CPU unit test cannot hold onto element
pointers across a `System` and assert on them (use-after-free). Fix: extract the layout into a
**free function** `void FlexLayout::layoutRoot(Element* root, UVector2 viewport)` in a new
`src/Engine/UI/FlexLayout.h` (header-only, or a thin .cpp). `System::beginFrame`
calls it; the test calls it directly with a root it owns. `System::layoutRec` is removed.
**Two-phase** (recursion into children, so nested containers are correct):
- **Phase A — measure (post-order)**: for each element, with its *resolved* containing-box
size, compute its **content size** (`dimensions`) bottom-up. For a flex container this is the
size its children require (sum of child main sizes + gaps + padding) when width/height is
`Auto`, or the clamped fixed/percent size otherwise. For `Text`, content size comes from
`shapeText` (already computed in `applyStyle`). For a leaf with `Auto` size => 0. This pass
resolves `basis:auto`, applies `min/max` clamps, and stores each child's **main-axis size**
(the value `grow/shrink` operate on) so the parent can distribute free space.
- **Phase B — place (pre-order, top-down)**: with content sizes known, run the real flexbox
placement for this container's children: order-sorted flex items, resolve basis ->
`grow`/`shrink` distribution of free/deficit space (with `grow`/`shrink` weights), `wrap`
lines, `justify-content` along the main axis, `align-items`/`align-self`/`align-content`
along the cross axis, `gap` between items/lines. Write `child->position` (relative to this
element). `position==Relative` adds `left/top` to the computed position; `position==Absolute`
removes the item from the flex flow (no space reserved) and anchors at `left/top` from this
element's content box (or the next non-static ancestor if we keep CSS semantics — keep it
simple: anchor to this element's box). Then recurse into each child (Phase A+).
A `measure` pass and `place` pass must both be driven by the *same* function so nested
containers are sized before their parent distributes space. Because `applyStyle` runs *before*
`layoutRoot` (System::beginFrame order: `calcStyle` then layout), fonts are already shaped and
`style.width/height` are final; `layoutRoot` only positions + resolves auto/grow/shrink.
**What stays the same**: `Element::render` (reads `position`/`dimensions`), `System::hitTest`/
`mouseButton` (read `position`), `Text::applyStyle` (unchanged — it already resolves auto size).
Only the layout math changes. `flowLayout()` and the `innerDisplay` switch in `layout()`
(`Element.h:95-167`) are deleted; `layout(UVector2)` becomes a thin call into `FlexLayout`.
### 4. `render`/`hitTest`/`collectFocusable` hidden check
Swap `style.hidden` and `style.outerDisplay == OuterDisplayType::Hidden` for
`style.display == Display::Hidden` in: `Element::layout` guard, `Element::render`, `Text::render`,
`System::collectFocusable` (`System.cpp`). No behavior change, just the single source of truth.
## Files to modify
- `src/Engine/UI/Style/Style.h` — add flex fields; remove `outerDisplay`/`innerDisplay`/`position` + the `OuterDisplayType`/`InnerDisplayType`/`PositionType{static,sticky}` enums and `hidden` bool (replaced by `display`/`Display`). Keep `gap`, `top/left/right/bottom`, `width/height`+types, `max*`.
- `src/Engine/UI/Style/Class.h` — add flex tailwind classes (Design §2); remove `Block`/`Inline`/old `DisplayClass`/old `Hidden`.
- `src/Engine/UI/FlexLayout.h` — **new**: the two-phase flexbox engine as `FlexLayout::layoutRoot` (Design §3).
- `src/Engine/UI/Element.h` — delete `flowLayout()` + the `layout()` inline size/switch (`:95-167`); thin `layout()` into `FlexLayout`; swap the `render()` hidden check.
- `src/Engine/UI/Element/Div.h`, `Panel.h` — drop `outerDisplay = Block`; decide the default flex direction for a bare container.
- `src/Engine/UI/Element/Text.h` — swap the `render` hidden check (`applyStyle` unchanged).
- `src/Engine/UI/System.cpp` — remove `layoutRec`; `beginFrame` calls `FlexLayout::layoutRoot`; swap the `collectFocusable` hidden check.
- `src/Editor/Window/InspectorView.cpp` — migrate the demo to the new classes (the only real consumer + visual smoke test).
- `tests/Engine/UI/FlexLayout.cpp` + `tests/Engine/UI/CMakeLists.txt` — **new** CPU-only layout tests; add `add_subdirectory(UI/)` to `tests/Engine/CMakeLists.txt` and give the test target the `src/Engine` include path.
## Decisions (confirmed with user)
1. **Keep minimal `absolute` + `relative`** as positioning escape hatches on top of flexbox. Drop `static`/`sticky` as layout *modes*. Keep the `top/left/right/bottom` offset fields (relative = offset from the flex-computed position; absolute = offset from the containing block, removed from the flex flow). No `sticky`.
2. **`hidden` stays a boolean** but is exposed through a `Display`-state field (an enum `Display { Flex, Hidden }`) to mirror HTML/CSS. Only two states: `Flex` (laid out, default) and `Hidden` (not laid out, not rendered, not hit-tested). `InnerDisplayType`/`OuterDisplayType` are removed entirely; there is one layout mode (flex) and a `display` toggle.
3. **Baseline alignment: skip for now.** Cross-axis `align-items`/`align-self`/`align-content` ship `stretch|start|center|end` only. `baseline` is deferred (needs font metrics on the laid-out Style; add later if ever needed).
4. **Full spec in one pass**: `flex-direction` (row/row-reverse/col/col-reverse), `flex-wrap`, `justify-content` (all 6), `align-items`/`align-self`/`align-content` (start/center/end/stretch), `order`, `flex-grow`/`flex-shrink`/`flex-basis` (auto/px/percent), `gap`, `min/max` width/height clamps, percent basis. No `grid`. Baseline excluded per #3.
5. **Intrinsic size model**: only `Text` has a natural size (from `shapeText`). `Auto` size ⇒ measure from children for containers; `0` for leaf `Div`/`Panel`. `basis:auto` resolves to the element's auto-resolved main size. Confirmed this is the only coherent model.
6. **Default flex direction for a bare `Div`/`Panel`:** `Column` (top-to-bottom). Rationale: the existing flow layout already *stacked* block children vertically, and a bare `Div` must remain a valid container that lays out its children sensibly with no extra class. Horizontal layouts are explicit (`FlexRow`). This is a sensible default, not a user-blocking question — noted here for the record.
## Steps
- [x] **1. `Style.h`** — replace the `OuterDisplayType`/`InnerDisplayType`/`PositionType` enums and `outerDisplay`/`innerDisplay`/`position`/`hidden` fields with the new flex fields above (`FlexDirection`, `FlexWrap`, `JustifyContent`, `AlignType`, `Display`, `Position{Static,Relative,Absolute}`, `grow`, `shrink`, `order`, `basisType`/`basis`, `justify`, `items`, `content`, `alignSelfOverride`). Keep `gap`, `top/left/right/bottom`, `width/height`+types, `max*`. `hidden` => `display==Display::Hidden`.
- [x] **2. `Class.h`** — remove `DisplayClass`/`Block`/`Inline`/`Hidden` (the old ones). Add the flex template classes + tailwind aliases listed in Design §2 (`Flex`/`FlexRow`/`FlexCol`/reverses, `Wrap`/`NoWrap`, `Grow`/`Grow_<n>`/`Grow0`, `Shrink`/`Shrink_<n>`/`Shrink0`, `Basis_*`, `Justify_*`, `Items_*`/`Self_*`, `Order_<n>`, `DisplayClass<Display::Hidden>` as `Hidden`). Reuse `G_n`/`M_*`/`P_*`/`W_Full`/`H_Full` unchanged.
- [x] **3. New `UI/FlexLayout.{h,cpp}`** — `namespace Seele::UI { namespace FlexLayout { void layoutRoot(Element* root, UVector2 viewport); } }`. Implemented as a .cpp (not header-only) to break the circular include (Element.h already includes FlexLayout.h). Free functions `layoutElement` + `layoutRoot` + `placeFlowChildren`. Container-aware: nested containers read their own resolved dimensions (set by recursion) instead of the flex-distributed basis; a re-placement pass after `placeFlowChildren` fixes grandchildren that were positioned relative to a stale parent position. Edge cases covered: zero/negative free space (shrink), all-zero grow/shrink (basis wins), single-line SpaceBetween/Around/Evenly (gaps=0), Stretch when cross is Auto (fill cross axis), clamping so items never go negative, cross-size clamp to content box.
- [x] **4. `Element.h`** — deleted `flowLayout()` and the `innerDisplay` switch + inline size computation. Added public accessors (`getStyle`, `getParent`, `getIntrinsicW/H`) so `FlexLayout.cpp` can read child state without protected access. `render()` hidden check swapped to `display==Display::Hidden`.
- [x] **5. `Div.h`/`Panel.h`** — removed `style.outerDisplay = OuterDisplayType::Block`. Fixed `applyStyle` clobber: `style = parentStyle` copies ALL fields; now resets all non-inherited fields to defaults before applying template classes. A bare `Div`/`Panel` defaults to `Column` (decision #6).
- [x] **6. `System.cpp`** — removed `layoutRec`; `beginFrame` calls `FlexLayout::layoutRoot(root, viewport)`. `collectFocusable` hidden check swapped to `display==Display::Hidden`.
- [x] **7. `Text.h`** — swapped `style.hidden || style.outerDisplay == Hidden` for `display==Display::Hidden` in `render`. `applyStyle` unchanged.
- [x] **8. `InspectorView.cpp`** — migrated to `Div<FlexRow, M_4>` (the only real consumer).
- [x] **9. Test wiring** — `tests/Engine/UI/CMakeLists.txt` created with `target_sources(SeeleUnitTests PRIVATE FlexLayout.cpp)`. `DebugTest.cpp` entry removed.
- [x] **10. `tests/Engine/UI/FlexLayout.cpp`** — 15 GTest cases: (a) row gap + justify; (b) column; (c) grow absorbs free space; (d) proportional grow; (e) shrink deficit; (f) wrap; (g) align-items; (h) order; (i) align-self override; (j) percent basis; (k) min/max clamps; (l) relative offset; (m) absolute position; (n) nested flex; (o) hidden skips layout. `H_Full` fixed (was 100px, now `HeightClass<100, DimensionType::Percent>`). All 15 pass.
## Verification
1. **CPU unit tests (primary, no GPU):** ✅ **15/15 passing.** `cmake --build bin --target SeeleUnitTests` then `cd bin && ./SeeleUnitTests --gtest_filter='FlexLayout.*'`. No display, no font needed.
2. **Build the whole engine:** ✅ **Editor + Engine compile and link clean.** `cmake --build bin --target Editor Engine`.
3. **Editor visual smoke test:** NOT YET DONE — requires launching the GUI. Open the InspectorView, confirm the `FlexRow` div lays children left-to-right with `M_4` margin, hover/Tab focus still work (input path untouched). RenderDoc: verify `position`/`dimensions` feed the UI quads correctly (no overlap).
4. **Regression:** ✅ **No stale references.** `grep -rn "outerDisplay\|innerDisplay\|flowLayout\|style.hidden\|OuterDisplayType\|InnerDisplayType\|PositionType" external/Seele/src/` returns nothing.
## Known limitations (intentional, per plan decisions)
- **Baseline alignment** (`AlignType::Baseline`) is NOT shipped — decision #3, needs font metrics.
- **`align-content`** is NOT implemented (multi-line cross-axis distribution for wrapped content). Only single-line layout is exercised by tests; `align-content` would matter for `FlexWrap` with `column` direction + multiple lines.
- **The re-placement pass** (after `placeFlowChildren` in both `layoutElement` and `layoutRoot`) is a pragmatic workaround for the measure-then-place ordering: a container child's `layoutElement` runs (recursion) BEFORE the parent's `placeFlowChildren` sets its position, so grandchildren are positioned relative to a stale (0,0). The re-pass fixes this at depth 2. For depth ≥ 3 (grandchild containers), the re-pass only re-runs `placeFlowChildren` one level — it does NOT recursively re-run. If a 3-level-deep container tree is ever needed, this must be restructured to a true two-pass (measure-then-place) algorithm.
+1
View File
@@ -198,6 +198,7 @@ void MeshShadingDemoGame::setupScene(PScene scene, PSystemGraph graph)
} }
}*/ }*/
center = new PointLightActor(scene, Vector(0, 0, 0), 10, Vector(1, 1, 1), 10); center = new PointLightActor(scene, Vector(0, 0, 0), 10, Vector(1, 1, 1), 10);
xAxis = new PointLightActor(scene, Vector(10, 0, 0), 10, Vector(1, 0, 0), 10); xAxis = new PointLightActor(scene, Vector(10, 0, 0), 10, Vector(1, 0, 0), 10);
yAxis = new PointLightActor(scene, Vector(0, 10, 0), 10, Vector(0, 1, 0), 10); yAxis = new PointLightActor(scene, Vector(0, 10, 0), 10, Vector(0, 1, 0), 10);