Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
UISystem.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
9
10#include "./UISystem.hpp"
11#include "./UIHitTestSystem.hpp"
12
24
25#include <algorithm>
26#include <cstdint>
27#include <vector>
28
29namespace esengine::ecs {
30
31void UISystem::hitTestUpdate(Registry& registry, const PickRay& ray,
32 const resource::ResourceManager* resources) {
33 hitTestUpdate(registry, ray, ray, resources);
34}
35
36void UISystem::hitTestUpdate(Registry& registry, const PickRay& worldRay, const PickRay& screenRay,
37 const resource::ResourceManager* resources) {
38 hitResult.prev_hit_entity = hitResult.hit_entity;
39 hitResult.hit_entity = INVALID_ENTITY;
40
41 const auto& nodes = tree.nodes_;
42
43 for (i32 i = static_cast<i32>(nodes.size()) - 1; i >= 0; i--) {
44 Entity entity = nodes[i].entity;
45 if (!registry.isEntityActive(entity)) continue;
46
47 auto* interactable = registry.tryGet<Interactable>(entity);
48 if (!interactable || !interactable->enabled || !interactable->raycastTarget) continue;
49 if (!registry.has<Transform>(entity)) continue;
50
51 // Which projection this node was drawn through decides which ray reaches
52 // it. Resolved from the same set the renderer partitions by, so what is
53 // clickable and what is visible cannot come apart.
54 const PickRay& ray = screen_domain_.count(entity.id()) != 0 ? screenRay : worldRay;
55
56 auto& t = registry.get<Transform>(entity);
58
59 // Each node answers on the plane it stands on. Orthographically that is
60 // the same point for every node, so a flat UI picks exactly as before.
61 f32 mouseWorldX = 0.0f, mouseWorldY = 0.0f, hitT = 0.0f;
62 if (!rayHitsPlaneZ(ray, t.worldPosition.z, mouseWorldX, mouseWorldY, hitT)) continue;
63
64 // Hit geometry from the UINode (CSS box, pivot-centered).
65 auto* node = registry.tryGet<UINode>(entity);
66 if (!node || node->hidden_in_tree_) continue;
67 // pointer-events: none on this node or any ancestor — still drawn, but
68 // the pointer passes straight through to whatever is behind it.
69 if (node->pointer_blocked_in_tree_) continue;
70 f32 baseW = node->computed_size_.x;
71 f32 baseH = node->computed_size_.y;
72 f32 pivotX = 0.5f, pivotY = 0.5f;
73
75 registry, entity, t, mouseWorldX, mouseWorldY,
76 baseW, baseH, pivotX, pivotY
77 )) {
78 if (isClippedByMask(registry, entity, mouseWorldX, mouseWorldY)) {
79 continue;
80 }
81 hitResult.hit_entity = entity;
82 return;
83 }
84 }
85
86 // World content is world content: the screen has no sprites or meshes in it.
87 hitWorldContent(registry, worldRay, resources);
88}
89
91 const u32 now = registry.beginChangeRead();
92 const u64 meshes = resources ? resources->meshesRevision() : 0;
93 const u32 since = hit_tick_;
94 bool changed = registry.identity() != hit_registry_ || registry.activityEpoch() != hit_activity_
95 || meshes != hit_meshes_
96 || registry.anyChangedSince<Interactable>(since) || registry.anyChangedSince<UIMask>(since)
97 || registry.anyChangedSince<Canvas>(since) || registry.anyChangedSince<Parent>(since);
98 const bool moved = registry.anyChangedSince<Transform>(since);
99 if (!changed && (moved || registry.anyChangedSince<Sprite>(since)
100 || registry.anyChangedSince<ContentRect>(since) || registry.anyChangedSince<MeshRenderer>(since))) {
101 registry.eachLive<Interactable>([&](Entity e, Interactable&) {
102 if (changed) return;
103 changed = registry.changedSince<Transform>(e, since) || registry.changedSince<Sprite>(e, since)
104 || registry.changedSince<ContentRect>(e, since) || registry.changedSince<MeshRenderer>(e, since);
105 });
106 if (!changed && moved) {
107 registry.eachLive<UIMask>([&](Entity e, UIMask&) {
108 if (!changed) changed = registry.changedSince<Transform>(e, since);
109 });
110 }
111 }
112 hit_registry_ = registry.identity();
113 hit_activity_ = registry.activityEpoch();
114 hit_meshes_ = meshes;
115 hit_tick_ = now;
116 return changed;
117}
118
119namespace {
120
123std::vector<u32> hierarchyPath(Registry& registry, Entity entity) {
124 std::vector<u32> reversed;
125 for (Entity current = entity; ; ) {
126 const auto* parent = registry.tryGet<Parent>(current);
127 if (!parent || parent->entity == INVALID_ENTITY || !registry.valid(parent->entity)) {
128 reversed.push_back(current.id()); // roots are told apart by their number
129 break;
130 }
131 u32 index = 0;
132 if (const auto* children = registry.tryGet<Children>(parent->entity)) {
133 const auto& list = children->entities;
134 index = static_cast<u32>(std::find(list.begin(), list.end(), current) - list.begin());
135 }
136 reversed.push_back(index);
137 current = parent->entity;
138 }
139 return std::vector<u32>(reversed.rbegin(), reversed.rend());
140}
141
143bool drawsBefore(Registry& registry, Entity a, Entity b) {
144 return hierarchyPath(registry, a) < hierarchyPath(registry, b);
145}
146
147} // namespace
148
158void UISystem::hitWorldContent(Registry& registry, const PickRay& ray,
159 const resource::ResourceManager* resources) {
160 Entity best = INVALID_ENTITY;
161 f32 bestT = 0.0f;
162 i32 bestLayer = 0;
163 bool haveBest = false;
164
165 // Nearer wins; at the same distance the higher sorting layer does, and a tie
166 // there goes to the later entity — the order the renderer batches in.
167 const auto consider = [&](Entity entity, f32 t, i32 layer) {
168 if (haveBest) {
169 const bool sameDepth = std::abs(t - bestT) <= 1e-4f;
170 if (!sameDepth && t > bestT) return;
171 if (sameDepth && layer < bestLayer) return;
172 // A full tie goes to the one drawn later, by its place in the hierarchy rather than by where a pool happened to list it or when
173 // it was created: a node taken from a pool and added under a panel is made last and drawn first, and a number cannot tell.
174 if (sameDepth && layer == bestLayer && drawsBefore(registry, entity, best)) return;
175 }
176 haveBest = true;
177 bestT = t;
178 bestLayer = layer;
179 best = entity;
180 };
181
182 registry.eachLive<Sprite, Interactable>(
183 [&](Entity entity, Sprite& sprite, Interactable& interactable) {
184 if (!registry.isEntityActive(entity)) return;
185 if (!interactable.enabled || !interactable.raycastTarget) return;
186 // The layout tree owns anything with a UINode; this pass is for the rest.
187 if (registry.has<UINode>(entity)) return;
188 if (!registry.has<Transform>(entity)) return;
189
190 auto& t = registry.get<Transform>(entity);
191 t.ensureDecomposed();
192
193 f32 px = 0.0f, py = 0.0f, hitT = 0.0f;
194 if (!rayHitsPlaneZ(ray, t.worldPosition.z, px, py, hitT)) return;
195
197 registry, entity, t, px, py, sprite.size.x, sprite.size.y,
198 sprite.pivot.x, sprite.pivot.y
199 )) return;
200
201 consider(entity, hitT, static_cast<i32>(sprite.layer));
202 });
203
204 // An entity that is only a rectangle — a touch area, a scroll viewport — has no sprite to take a box from. A sprite on the same
205 // entity is handled above (it follows the rectangle), so this is for the ones that draw nothing.
206 registry.eachLive<ContentRect, Interactable>(
207 [&](Entity entity, ContentRect& rect, Interactable& interactable) {
208 if (!registry.isEntityActive(entity)) return;
209 if (!interactable.enabled || !interactable.raycastTarget) return;
210 if (registry.has<UINode>(entity) || registry.has<Sprite>(entity)) return;
211 if (!registry.has<Transform>(entity)) return;
212
213 auto& t = registry.get<Transform>(entity);
214 t.ensureDecomposed();
215
216 f32 px = 0.0f, py = 0.0f, hitT = 0.0f;
217 if (!rayHitsPlaneZ(ray, t.worldPosition.z, px, py, hitT)) return;
218
220 registry, entity, t, px, py, rect.size.x, rect.size.y,
221 rect.pivot.x, rect.pivot.y
222 )) return;
223
224 // No sorting layer: it ties with a sprite at the same depth and loses to a higher layer, and the later entity wins a tie.
225 consider(entity, hitT, 0);
226 });
227
228 registry.eachLive<MeshRenderer, Interactable>(
229 [&](Entity entity, MeshRenderer& mesh, Interactable& interactable) {
230 if (!registry.isEntityActive(entity)) return;
231 if (!interactable.enabled || !interactable.raycastTarget) return;
232 if (!mesh.enabled) return;
233 if (registry.has<UINode>(entity)) return;
234 if (!registry.has<Transform>(entity)) return;
235
236 // Bounds come from whichever geometry this is, the same way the cull
237 // reads them: a resident mesh keeps its own and leaves the component's
238 // empty, so reading the component's would test an empty box.
239 const Mesh* resident =
240 (resources && mesh.mesh.isValid()) ? resources->getMesh(mesh.mesh) : nullptr;
241 if (!resident && mesh.indices.empty()) return;
242 const glm::vec3 localMin = resident ? resident->localMin
243 : glm::vec3(mesh.localMin, 0.0f);
244 const glm::vec3 localMax = resident ? resident->localMax
245 : glm::vec3(mesh.localMax, 0.0f);
246
247 auto& t = registry.get<Transform>(entity);
248 t.ensureDecomposed();
249
250 f32 hitT = 0.0f;
251 if (!rayHitsOBB(ray, t.worldPosition, t.worldRotation, t.worldScale,
252 localMin, localMax, hitT)) return;
253
254 consider(entity, hitT, static_cast<i32>(mesh.layer));
255 });
256
257 if (!haveBest) return;
258 hitResult.hit_entity = best;
259}
260
261u32 UISystem::pickAll(Registry& registry, f32 worldX, f32 worldY) {
262 pickResults_.clear();
263 const auto& nodes = tree.nodes_;
264
265 // Depth-first ranking (a label beats its panel), draw order breaking ties.
266 struct Hit {
267 Entity entity;
268 i32 depth;
269 i32 order;
270 };
271 std::vector<Hit> hits;
272
273 for (i32 i = static_cast<i32>(nodes.size()) - 1; i >= 0; i--) {
274 Entity entity = nodes[i].entity;
275 if (!registry.isEntityActive(entity)) continue;
276 if (!registry.has<Transform>(entity)) continue;
277
278 auto* node = registry.tryGet<UINode>(entity);
279 if (!node || node->computed_size_.x <= 0.0f || node->computed_size_.y <= 0.0f) continue;
280
281 auto& t = registry.get<Transform>(entity);
283
285 registry, entity, t, worldX, worldY,
286 node->computed_size_.x, node->computed_size_.y, 0.5f, 0.5f
287 )) continue;
288
289 if (isClippedByMask(registry, entity, worldX, worldY)) continue;
290
291 i32 depth = 0;
292 for (Entity a = entity; registry.has<Parent>(a);) {
293 Entity parent = registry.get<Parent>(a).entity;
294 if (!registry.valid(parent)) break;
295 depth++;
296 a = parent;
297 }
298 auto* vis = registry.tryGet<UIVisual>(entity);
299 hits.push_back({entity, depth, vis ? vis->uiOrder : INT32_MIN});
300 }
301
302 std::sort(hits.begin(), hits.end(), [](const Hit& a, const Hit& b) {
303 if (a.depth != b.depth) return a.depth > b.depth;
304 return a.order > b.order;
305 });
306 pickResults_.reserve(hits.size());
307 for (const Hit& h : hits) pickResults_.push_back(h.entity);
308 return static_cast<u32>(pickResults_.size());
309}
310
311u32 UISystem::pick(Registry& registry, f32 worldX, f32 worldY) {
312 return pickAll(registry, worldX, worldY) > 0 ? pickResults_[0].id() : INVALID_ENTITY.id();
313}
314
315} // namespace esengine::ecs
Canvas component for 2D game resolution management.
The rectangle a piece of world content occupies: a size, and the point of it the entity's transform s...
Hierarchy components for parent-child relationships.
Arbitrary-geometry 2D mesh renderable (deformed sprites, polygons, water surfaces,...
Central resource management system.
2D sprite rendering component
Unified Transform component with local and world-space data.
Pure geometric helpers used by UISystem hit-test.
UI subsystem owning layout tree and hit-test state.
Central container for all entities and components.
Definition Registry.hpp:73
bool isEntityActive(Entity e) const
Definition Registry.hpp:115
bool anyChangedSince(u32 tick) const
Whether any T was written, added or removed after tick: the question a frame that may skip its walk a...
Definition Registry.hpp:220
void eachLive(Func &&func)
each() without the per-call snapshot copy, for read-only passes.
Definition Registry.hpp:890
u32 activityEpoch() const
Definition Registry.hpp:122
T & get(Entity entity)
Gets a component from an entity (must exist).
Definition Registry.hpp:649
bool has(Entity entity) const
Checks if an entity has a specific component.
Definition Registry.hpp:711
u32 beginChangeRead()
For a reader about to look: the tick it is looking at, after which the clock moves on.
Definition Registry.hpp:173
bool changedSince(Entity entity, u32 tick) const
Whether entity's T was written, added or replaced after tick (an answer of beginChangeRead).
Definition Registry.hpp:207
bool valid(Entity entity) const
Checks if an entity is currently valid.
Definition Registry.hpp:518
u64 identity() const
Which registry this is, never shared with another made in this process (a registry assigned over this...
Definition Registry.hpp:166
T * tryGet(Entity entity)
Tries to get a component from an entity.
Definition Registry.hpp:670
bool hitInputsChanged(Registry &registry, const resource::ResourceManager *resources)
Definition UISystem.cpp:90
u32 pick(Registry &registry, f32 worldX, f32 worldY)
Editor pick: the most specific UI entity under the point. Unlike hitTestUpdate it ignores Interactabl...
Definition UISystem.cpp:311
UIHitTestResult hitResult
Definition UISystem.hpp:67
u32 pickAll(Registry &registry, f32 worldX, f32 worldY)
All UI entities under the point, most specific first. Returns the count; read entries via pickResult.
Definition UISystem.cpp:261
void hitTestUpdate(Registry &registry, const PickRay &ray, const resource::ResourceManager *resources=nullptr)
Run ray-vs-content hit-test, updating hitResult. A query: what a press or a hover MEANS is the intera...
Definition UISystem.cpp:31
Central manager for GPU resources.
u64 meshesRevision() const
Changes whenever any mesh is realized (each takes a new Mesh::revision) or released: while it holds,...
bool rayHitsOBB(const PickRay &ray, const glm::vec3 &centre, const glm::quat &rotation, const glm::vec3 &scale, const glm::vec3 &localMin, const glm::vec3 &localMax, f32 &outT)
bool pointInTransformedBox(Registry &registry, Entity entity, Transform &transform, f32 px, f32 py, f32 width, f32 height, f32 pivotX, f32 pivotY)
bool isClippedByMask(Registry &registry, Entity entity, f32 worldMouseX, f32 worldMouseY)
bool rayHitsPlaneZ(const PickRay &ray, f32 planeZ, f32 &outX, f32 &outY, f32 &outT)
std::int32_t i32
Signed 32-bit integer.
Definition Types.hpp:54
std::uint64_t u64
Unsigned 64-bit integer.
Definition Types.hpp:47
constexpr Entity INVALID_ENTITY
Invalid entity sentinel value.
Definition Types.hpp:174
std::uint32_t u32
Unsigned 32-bit integer.
Definition Types.hpp:45
float f32
32-bit floating point
Definition Types.hpp:59
Entity identifier with packed index + generation.
Definition Types.hpp:135
constexpr u32 id() const
Returns the raw packed value for FFI serialization.
Definition Types.hpp:159
Canvas component for 2D game resolution management.
Definition Canvas.hpp:71
The rectangle of this entity's content, in its own units.
Parent reference component.
Definition Hierarchy.hpp:46
Unified transform component.
Definition Transform.hpp:45
UINode — the CSS box-model layout input (the CSS/Flex primary layout model).
Definition UINode.hpp:79
UIVisual — the single UI visual component, merging the former low-level UIRenderer (what the renderer...
Definition UIVisual.hpp:84