A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(input): the pointer is a ray, so a mesh can be clicked at all
esengine672f2e505836
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex 1c2be1d23..e3b1dc9a1 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -12188,7 +12188,7 @@ TrailPlugin## uiHitTestWorld — function @experimental```-(world: PickableWorld, worldX: number, worldY: number): Entity | null+(world: PickableWorld, ray: WorldRay): Entity | null```## uiInteractionPlugin — const @experimentaldiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex 0f0c4422b..297d6706c 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -12431,7 +12431,7 @@ TrailPlugin## uiHitTestWorld — function @experimental```-(world: PickableWorld, worldX: number, worldY: number): Entity | null+(world: PickableWorld, ray: WorldRay): Entity | null```## uiInteractionPlugin — const @experimentaldiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 65630eac8..69573bb49 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -12193,7 +12193,7 @@ TrailPlugin## uiHitTestWorld — function @experimental```-(world: PickableWorld, worldX: number, worldY: number): Entity | null+(world: PickableWorld, ray: WorldRay): Entity | null```## uiInteractionPlugin — const @experimentaldiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 4c09e35b4..612db1be2 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -12449,7 +12449,7 @@ TrailPlugin## uiHitTestWorld — function @experimental```-(world: PickableWorld, worldX: number, worldY: number): Entity | null+(world: PickableWorld, ray: WorldRay): Entity | null```## uiInteractionPlugin — const @experimentaldiff --git a/sdk/etc/wasm.api.md b/sdk/etc/wasm.api.mdindex 97ac62291..44b796334 100644--- a/sdk/etc/wasm.api.md+++ b/sdk/etc/wasm.api.md@@ -415,7 +415,7 @@ uiHitTest_getHitEntity: () => numberuiHitTest_pick: ((registry: CppRegistry, worldX: number, worldY: number) => number) | undefineduiHitTest_pickAll: ((registry: CppRegistry, worldX: number, worldY: number) => number) | undefineduiHitTest_pickResult: ((index: number) => number) | undefined-uiHitTest_update: (registry: CppRegistry, mouseWorldX: number, mouseWorldY: number) => void+uiHitTest_update: (registry: CppRegistry, originX: number, originY: number, originZ: number, dirX: number, dirY: number, dirZ: number) => voiduiLayout_update: (registry: CppRegistry, boxLeft: number, boxBottom: number, boxRight: number, boxTop: number, propertyDirty: boolean) => voiduiNode_computedHeight: (registry: CppRegistry, entity: number) => numberuiNode_computedWidth: (registry: CppRegistry, entity: number) => numberdiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 0ba29ba7d..db77f2fde 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -12215,7 +12215,7 @@ TrailPlugin## uiHitTestWorld — function @experimental```-(world: PickableWorld, worldX: number, worldY: number): Entity | null+(world: PickableWorld, ray: WorldRay): Entity | null```## uiInteractionPlugin — const @experimentaldiff --git a/sdk/src/ecs/bridge/nativeEngineApi.generated.ts b/sdk/src/ecs/bridge/nativeEngineApi.generated.tsindex f4430f74e..2708bf720 100644--- a/sdk/src/ecs/bridge/nativeEngineApi.generated.ts+++ b/sdk/src/ecs/bridge/nativeEngineApi.generated.ts@@ -217,7 +217,7 @@ export interface NativeEngineApi {uiHitTest_pick?(registry: unknown, worldX: number, worldY: number): number;uiHitTest_pickAll?(registry: unknown, worldX: number, worldY: number): number;uiHitTest_pickResult?(index: number): number;- uiHitTest_update?(registry: unknown, mouseWorldX: number, mouseWorldY: number): void;+ uiHitTest_update?(registry: unknown, originX: number, originY: number, originZ: number, dirX: number, dirY: number, dirZ: number): void;uiLayout_update?(registry: unknown, boxLeft: number, boxBottom: number, boxRight: number, boxTop: number, propertyDirty: boolean): void;uiNode_computedHeight?(registry: unknown, entity: number): number;uiNode_computedWidth?(registry: unknown, entity: number): number;diff --git a/sdk/src/ui/input/interaction.ts b/sdk/src/ui/input/interaction.tsindex 5a50a5564..8b7946b19 100644--- a/sdk/src/ui/input/interaction.ts+++ b/sdk/src/ui/input/interaction.ts@@ -17,7 +17,7 @@ import { ensureEntityEvents } from '../../ecs/entityEvents';import { UICameraInfo } from '../core/ui-camera-info';import type { UICameraData } from '../core/ui-camera-info';import type { InteractableData } from './interactable';-import { screenToUiWorld, uiHitTestWorld } from '../util/ui-pick';+import { screenToUiWorld, uiPointerRay, uiHitTestWorld } from '../util/ui-pick';import { platformDevicePixelRatio } from '../../platform';import { ensureComponent, walkParentChain } from '../util/helpers';import type { CppRegistry } from '../../wasm';@@ -106,7 +106,7 @@ export class UIInteractionPlugin implements Plugin {let hitEntity: Entity | null = hoveredEntity;if (needsHitTest) {- hitEntity = uiHitTestWorld(world, worldMouse.x, worldMouse.y);+ hitEntity = uiHitTestWorld(world, uiPointerRay(camera, mouseGLX, mouseGLY));}if (hoveredEntity !== null && !world.valid(hoveredEntity)) {diff --git a/sdk/src/ui/util/ui-pick.ts b/sdk/src/ui/util/ui-pick.tsindex 5d1fe7d78..068abb09d 100644--- a/sdk/src/ui/util/ui-pick.ts+++ b/sdk/src/ui/util/ui-pick.ts@@ -4,7 +4,7 @@ import type { Entity } from '../../types';import type { World } from '../../ecs/world';import type { UICameraData } from '../core/ui-camera-info';import { worldEngineApi } from '../../ecs/bridge/engineApi';-import { screenToWorld, worldToScreen, createInvVPCache } from './math';+import { screenToWorld, worldToScreen, createInvVPCache, screenRay, type WorldRay } from './math';const NO_HIT = 0xffffffff;const vpCache = createInvVPCache();@@ -15,6 +15,18 @@ export function screenToUiWorld(camera: UICameraData, screenGLX: number, screenGreturn screenToWorld(screenGLX, screenGLY, invVP, camera.vpX, camera.vpY, camera.vpW, camera.vpH);}+/**+ * The world ray a screen point names, through the UI camera.+ *+ * @details {@link screenToUiWorld} answers with this ray meeting ONE plane, which+ * picking cannot use: a mesh is a solid and a sprite stands at any depth.+ */+export function uiPointerRay(camera: UICameraData, screenGLX: number, screenGLY: number): WorldRay {+ vpCache.update(camera.viewProjection);+ const invVP = vpCache.getInverse(camera.viewProjection);+ return screenRay(screenGLX, screenGLY, invVP, camera.vpX, camera.vpY, camera.vpW, camera.vpH);+}+export function uiWorldToScreen(camera: UICameraData, worldX: number, worldY: number): { x: number; y: number } {const [x, y] = worldToScreen(worldX, worldY, camera.viewProjection, camera.vpX, camera.vpY, camera.vpW, camera.vpH);return { x, y };@@ -35,14 +47,16 @@ function core(world: PickableWorld) {}/**- * The topmost **interactable** entity at a world point — the same raycast the+ * The topmost **interactable** entity along a pointer ray — the same raycast the* interaction system runs, so a custom cursor agrees with the built-in one.* A query: what a press or a hover MEANS is the interaction system's business.*/-export function uiHitTestWorld(world: PickableWorld, worldX: number, worldY: number): Entity | null {+export function uiHitTestWorld(world: PickableWorld, ray: WorldRay): Entity | null {const c = core(world);if (!c?.engine.uiHitTest_update || !c.engine.uiHitTest_getHitEntity) return null;- c.engine.uiHitTest_update(c.registry, worldX, worldY);+ c.engine.uiHitTest_update(c.registry,+ ray.origin.x, ray.origin.y, ray.origin.z,+ ray.dir.x, ray.dir.y, ray.dir.z);const hit = c.engine.uiHitTest_getHitEntity();return hit === NO_HIT ? null : hit;}diff --git a/sdk/src/wasm.ts b/sdk/src/wasm.tsindex 4871fcabe..d7c94ce2b 100644--- a/sdk/src/wasm.ts+++ b/sdk/src/wasm.ts@@ -530,7 +530,9 @@ export interface ESEngineModule {// UI SystemsuiLayout_update(registry: CppRegistry, boxLeft: number, boxBottom: number, boxRight: number, boxTop: number, propertyDirty: boolean): void;- uiHitTest_update(registry: CppRegistry, mouseWorldX: number, mouseWorldY: number): void;+ uiHitTest_update(registry: CppRegistry,+ originX: number, originY: number, originZ: number,+ dirX: number, dirY: number, dirZ: number): void;uiHitTest_getHitEntity(): number;uiHitTest_pick?(registry: CppRegistry, worldX: number, worldY: number): number;uiHitTest_pickAll?(registry: CppRegistry, worldX: number, worldY: number): number;diff --git a/sdk/tests/ui-pick-world.test.ts b/sdk/tests/ui-pick-world.test.tsindex 81a1df9b0..99a84166a 100644--- a/sdk/tests/ui-pick-world.test.ts+++ b/sdk/tests/ui-pick-world.test.ts@@ -9,9 +9,9 @@*/import { describe, it, expect, beforeAll } from 'vitest';import { World } from '../src/ecs/world';-import { Transform, Sprite } from '../src/ecs/component';+import { Transform, Sprite, MeshRenderer } from '../src/ecs/component';import { Interactable } from '../src/ui/input/interactable';-import type { Entity } from '../src/types';+import type { Entity, Vec3 } from '../src/types';import type { ESEngineModule, CppRegistry } from '../src/wasm';import { loadWasmModule, HAS_WASM } from './helpers/loadWasm';@@ -42,23 +42,63 @@ describe.skipIf(!HAS_WASM)('world-space picking (WASM integration)', () => {/** A plain world-space sprite: no UINode, so the layout tree never sees it. */function sprite(world: World, x: number, y: number,- opts: { size?: number; layer?: number; raycastTarget?: boolean; scale?: number } = {},+ opts: { size?: number; layer?: number; raycastTarget?: boolean; scale?: number;+ z?: number } = {},): Entity {const e = world.spawn();const s = opts.size ?? 100;const k = opts.scale ?? 1;- world.insert(e, Transform, { position: { x, y, z: 0 }, scale: { x: k, y: k, z: 1 } });+ world.insert(e, Transform, { position: { x, y, z: opts.z ?? 0 }, scale: { x: k, y: k, z: 1 } });world.insert(e, Sprite, { size: { x: s, y: s }, layer: opts.layer ?? 0 });world.insert(e, Interactable, { raycastTarget: opts.raycastTarget ?? true });return e;}+ /**+ * A world-space mesh: a quad of inline geometry, which is the only kind a+ * bare registry can hold — a resident .esmesh needs a ResourceManager, and+ * the only difference downstream is where localMin/localMax are read from.+ */+ function mesh(+ world: World, x: number, y: number, z: number,+ opts: { half?: number; layer?: number } = {},+ ): Entity {+ const h = opts.half ?? 50;+ const e = world.spawn();+ world.insert(e, Transform, { position: { x, y, z } });+ world.insert(e, MeshRenderer, { layer: opts.layer ?? 0 });+ world.insert(e, Interactable, { raycastTarget: true });++ const positions = [-h, -h, h, -h, h, h, -h, h];+ const posUv = new Float32Array(positions.length * 2);+ for (let v = 0; v < 4; v++) {+ posUv[v * 4 + 0] = positions[v * 2 + 0];+ posUv[v * 4 + 1] = positions[v * 2 + 1];+ }+ const indices = new Uint32Array([0, 1, 2, 0, 2, 3]);+ const posPtr = module._malloc!(posUv.byteLength);+ const idxPtr = module._malloc!(indices.byteLength);+ module.HEAPF32!.set(posUv, posPtr >> 2);+ module.HEAPU32!.set(indices, idxPtr >> 2);+ module.meshRenderer_setGeometry!(+ world.getCppRegistry() as never, e, posPtr, 4, 0, idxPtr, indices.length);+ module._free!(posPtr);+ module._free!(idxPtr);+ return e;+ }+let frame = 0;+ /** An orthographic pointer: straight down -Z from above everything. */function pickAt(registry: CppRegistry, x: number, y: number): number {+ return pickRay(registry, { x, y, z: 1000 }, { x: 0, y: 0, z: -1 });+ }++ function pickRay(registry: CppRegistry, origin: Vec3, dir: Vec3): number {// transforms_updated is memoised per frame, so each pick needs its own.module.renderer_beginFrame(frame++);module.renderer_updateTransforms(registry as never);- module.uiHitTest_update(registry as never, x, y, false, false, false);+ module.uiHitTest_update(registry as never,+ origin.x, origin.y, origin.z, dir.x, dir.y, dir.z);return module.uiHitTest_getHitEntity();}@@ -129,4 +169,76 @@ describe.skipIf(!HAS_WASM)('world-space picking (WASM integration)', () => {disposeWorld(world, registry);});++ it('hits a MeshRenderer, which no pass reached before', () => {+ const { world, registry } = createWorld();+ const e = mesh(world, 0, 0, 0);++ expect(pickAt(registry, 0, 0)).toBe(e);+ // Outside the quad, so a pass that answers with the only mesh present+ // would pass the line above and fail this one.+ expect(pickAt(registry, 400, 0)).toBe(NO_HIT);++ disposeWorld(world, registry);+ });++ it('takes the NEARER of two meshes stacked in depth', () => {+ const { world, registry } = createWorld();+ const far = mesh(world, 0, 0, -500);+ const near = mesh(world, 0, 0, -100);++ // Both are under the pointer; only depth separates them, and the far one+ // was created first — so an answer that ignored depth would return it.+ expect(pickAt(registry, 0, 0)).toBe(near);+ expect(far).not.toBe(near);++ // Cast the other way and the ranking has to invert.+ expect(pickRay(registry, { x: 0, y: 0, z: -1000 }, { x: 0, y: 0, z: 1 })).toBe(far);++ disposeWorld(world, registry);+ });++ it('follows a perspective ray to where content actually stands', () => {+ const { world, registry } = createWorld();+ // 200 units to the right and 300 back. A pointer from the origin reaches+ // it only if the ray is followed to ITS plane; resolved at z = 0 — which+ // is every answer this pass could give before — it lands at x = 0.+ const e = mesh(world, 200, 0, -300, { half: 40 });++ const len = Math.hypot(200, 0, -300);+ expect(pickRay(registry, { x: 0, y: 0, z: 0 },+ { x: 200 / len, y: 0, z: -300 / len })).toBe(e);+ // Straight down -Z from the origin misses it, so the hit above is the+ // ray's doing and not a box wide enough to catch anything.+ expect(pickAt(registry, 0, 0)).toBe(NO_HIT);++ disposeWorld(world, registry);+ });++ it('meets a sprite on the sprite\'s own plane, not on z = 0', () => {+ const { world, registry } = createWorld();+ // Same geometry as the mesh case, so what differs is only which pass+ // answers: a sprite resolves the ray against a plane, a mesh against a box.+ const e = sprite(world, 200, 0, { size: 80, z: -300 });++ const len = Math.hypot(200, 0, -300);+ expect(pickRay(registry, { x: 0, y: 0, z: 0 },+ { x: 200 / len, y: 0, z: -300 / len })).toBe(e);+ expect(pickAt(registry, 0, 0)).toBe(NO_HIT);++ disposeWorld(world, registry);+ });++ it('lets a sprite in front of a mesh win, by depth alone', () => {+ const { world, registry } = createWorld();+ const behind = mesh(world, 0, 0, -200);+ const front = sprite(world, 0, 0, { size: 100 });++ expect(pickAt(registry, 0, 0)).toBe(front);+ // From behind, the mesh is the near one — so the line above is depth+ // deciding and not sprites simply outranking meshes.+ expect(pickRay(registry, { x: 0, y: 0, z: -1000 }, { x: 0, y: 0, z: 1 })).toBe(behind);++ disposeWorld(world, registry);+ });});diff --git a/sdk/tests/ui-pick.test.ts b/sdk/tests/ui-pick.test.tsindex 4e8525876..6efa8b3af 100644--- a/sdk/tests/ui-pick.test.ts+++ b/sdk/tests/ui-pick.test.ts@@ -12,23 +12,28 @@ const world = (engine: unknown, registry: unknown = REGISTRY) =>const hitTester = (hit: number) =>({ uiHitTest_update: vi.fn(), uiHitTest_getHitEntity: () => hit }) as any;+/** A pointer straight down -Z, which is what an orthographic camera casts. */+const rayAt = (x: number, y: number) =>+ ({ origin: { x, y, z: 1000 }, dir: { x: 0, y: 0, z: -1 } });+describe('uiHitTestWorld', () => {it('returns the hit entity', () => {const engine = hitTester(42);- expect(uiHitTestWorld(world(engine), 10, 20)).toBe(42);- expect(engine.uiHitTest_update).toHaveBeenCalledWith(REGISTRY, 10, 20);+ expect(uiHitTestWorld(world(engine), rayAt(10, 20))).toBe(42);+ // Six floats, not two: the engine is handed the ray, not a plane point.+ expect(engine.uiHitTest_update).toHaveBeenCalledWith(REGISTRY, 10, 20, 1000, 0, 0, -1);});it('maps the no-hit sentinel to null', () => {- expect(uiHitTestWorld(world(hitTester(0xffffffff)), 0, 0)).toBeNull();+ expect(uiHitTestWorld(world(hitTester(0xffffffff)), rayAt(0, 0))).toBeNull();});it('answers null when the world has no engine core behind it', () => {- expect(uiHitTestWorld(world(null), 1, 2)).toBeNull();+ expect(uiHitTestWorld(world(null), rayAt(1, 2))).toBeNull();});it('answers null when the engine is there but no registry is bound', () => {- expect(uiHitTestWorld(world(hitTester(42), null), 1, 2)).toBeNull();+ expect(uiHitTestWorld(world(hitTester(42), null), rayAt(1, 2))).toBeNull();});});diff --git a/src/esengine/bindings/UIBindings.cpp b/src/esengine/bindings/UIBindings.cppindex fdcdbfe7f..65770c7e2 100644--- a/src/esengine/bindings/UIBindings.cpp+++ b/src/esengine/bindings/UIBindings.cpp@@ -16,6 +16,7 @@#include "../core/World.hpp"#include "../ecs/Registry.hpp"#include "../ui/UISystem.hpp"+#include "../resource/ResourceManager.hpp"#include "../ui/UIRenderOrderSystem.hpp"#include "../ecs/TransformSystem.hpp"#include "../ecs/components/Transform.hpp"@@ -32,8 +33,12 @@ void uiLayout_update(ecs::Registry& registry, f32 boxLeft, f32 boxBottom, f32 boctx().require<ecs::UISystem>().layoutUpdate(registry, boxLeft, boxBottom, boxRight, boxTop, propertyDirty);}-void uiHitTest_update(ecs::Registry& registry, f32 mouseWorldX, f32 mouseWorldY) {- ctx().require<ecs::UISystem>().hitTestUpdate(registry, mouseWorldX, mouseWorldY);+void uiHitTest_update(ecs::Registry& registry,+ f32 originX, f32 originY, f32 originZ,+ f32 dirX, f32 dirY, f32 dirZ) {+ const ecs::PickRay ray{{originX, originY, originZ}, {dirX, dirY, dirZ}};+ ctx().require<ecs::UISystem>().hitTestUpdate(registry, ray,+ ctx().tryGet<resource::ResourceManager>());}u32 uiHitTest_getHitEntity() {diff --git a/src/esengine/bindings/UIBindings.hpp b/src/esengine/bindings/UIBindings.hppindex 885b5a7e6..2fe5550ce 100644--- a/src/esengine/bindings/UIBindings.hpp+++ b/src/esengine/bindings/UIBindings.hpp@@ -28,7 +28,13 @@ namespace ecs {void uiLayout_update(ecs::Registry& registry, f32 boxLeft, f32 boxBottom, f32 boxRight, f32 boxTop,bool propertyDirty);-void uiHitTest_update(ecs::Registry& registry, f32 mouseWorldX, f32 mouseWorldY);+/** The runtime raycast. The pointer is a RAY — a screen point names one, and+ * only a chosen plane turns it into a position — so content away from z = 0+ * (a mesh, a sprite on another layer) can be hit at all. `pick`/`pickAll`+ * below stay a point: the editor asks about the flat design surface. */+void uiHitTest_update(ecs::Registry& registry,+ f32 originX, f32 originY, f32 originZ,+ f32 dirX, f32 dirY, f32 dirZ);u32 uiHitTest_getHitEntity();u32 uiHitTest_pick(ecs::Registry& registry, f32 worldX, f32 worldY);u32 uiHitTest_pickAll(ecs::Registry& registry, f32 worldX, f32 worldY);diff --git a/src/esengine/ui/UIHitTestSystem.hpp b/src/esengine/ui/UIHitTestSystem.hppindex d8f1a1837..faa8dcd47 100644--- a/src/esengine/ui/UIHitTestSystem.hpp+++ b/src/esengine/ui/UIHitTestSystem.hpp@@ -14,7 +14,9 @@#include "../ecs/components/UINode.hpp"#include "../ecs/components/UIMask.hpp"+#include <algorithm>#include <cmath>+#include <limits>namespace esengine::ecs {@@ -46,6 +48,74 @@ inline bool pointInOBB(return localX >= left && localX <= right && localY >= bottom && localY <= top;}+/**+ * A pointer, as the ray it is rather than a point on one plane. Orthographically+ * every plane the ray crosses gives the same x/y, so the flat case is this one's+ * degenerate form; under perspective they differ, and a point cannot serve.+ */+struct PickRay {+ glm::vec3 origin{0.0f, 0.0f, 0.0f};+ glm::vec3 dir{0.0f, 0.0f, -1.0f};+};++/**+ * Where @p ray crosses the plane z = @p planeZ, and how far along the ray that+ * is. False when the two are parallel: a plane seen exactly edge-on is a plane+ * the pointer never reaches, and answering with a position would invent one.+ */+inline bool rayHitsPlaneZ(const PickRay& ray, f32 planeZ, f32& outX, f32& outY, f32& outT) {+ if (std::abs(ray.dir.z) <= 1e-9f) return false;+ const f32 t = (planeZ - ray.origin.z) / ray.dir.z;+ if (t < 0.0f) return false; // behind the viewer+ outX = ray.origin.x + ray.dir.x * t;+ outY = ray.origin.y + ray.dir.y * t;+ outT = t;+ return true;+}++/**+ * @p ray against a box in an entity's own frame — a slab test, after folding the+ * entity's rotation and translation out of the ray.+ *+ * @details Scale folds into the BOX, not out of the ray: zero would divide by+ * zero and negative flips rather than shrinks, hence min/max after it.+ */+inline 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) {+ const glm::quat inverse = glm::conjugate(glm::normalize(rotation));+ const glm::vec3 origin = inverse * (ray.origin - centre);+ const glm::vec3 dir = inverse * ray.dir;++ const glm::vec3 a = localMin * scale;+ const glm::vec3 b = localMax * scale;+ const glm::vec3 lo = glm::min(a, b);+ const glm::vec3 hi = glm::max(a, b);++ // Not `near`/`far`: both are macros in the Windows headers the native host+ // pulls in, and a slab test that stops compiling on one platform is worse+ // than two duller names.+ f32 enter = 0.0f;+ f32 exit = std::numeric_limits<f32>::max();+ for (int axis = 0; axis < 3; ++axis) {+ if (std::abs(dir[axis]) <= 1e-9f) {+ // Parallel to this pair of slabs: it can only ever be inside them.+ if (origin[axis] < lo[axis] || origin[axis] > hi[axis]) return false;+ continue;+ }+ f32 t0 = (lo[axis] - origin[axis]) / dir[axis];+ f32 t1 = (hi[axis] - origin[axis]) / dir[axis];+ if (t0 > t1) std::swap(t0, t1);+ enter = std::max(enter, t0);+ exit = std::min(exit, t1);+ if (enter > exit) return false;+ }+ outT = enter;+ return true;+}+inline bool isClippedByMask(Registry& registry,Entity entity,diff --git a/src/esengine/ui/UISystem.cpp b/src/esengine/ui/UISystem.cppindex 5b43af99d..a8d6d6c8e 100644--- a/src/esengine/ui/UISystem.cpp+++ b/src/esengine/ui/UISystem.cpp@@ -16,13 +16,16 @@#include "../ecs/components/UINode.hpp"#include "../ecs/components/UIVisual.hpp"#include "../ecs/components/Sprite.hpp"+#include "../ecs/components/MeshRenderer.hpp"+#include "../resource/ResourceManager.hpp"#include <algorithm>#include <cstdint>namespace esengine::ecs {-void UISystem::hitTestUpdate(Registry& registry, f32 mouseWorldX, f32 mouseWorldY) {+void UISystem::hitTestUpdate(Registry& registry, const PickRay& ray,+ const resource::ResourceManager* resources) {hitResult.prev_hit_entity = hitResult.hit_entity;hitResult.hit_entity = INVALID_ENTITY;@@ -40,6 +43,11 @@ void UISystem::hitTestUpdate(Registry& registry, f32 mouseWorldX, f32 mouseWorldauto& t = registry.get<Transform>(entity);t.ensureDecomposed();+ // Each node answers on the plane it stands on. Orthographically that is+ // the same point for every node, so a flat UI picks exactly as before.+ f32 mouseWorldX = 0.0f, mouseWorldY = 0.0f, hitT = 0.0f;+ if (!rayHitsPlaneZ(ray, t.worldPosition.z, mouseWorldX, mouseWorldY, hitT)) continue;+// Hit geometry from the UINode (CSS box, pivot-centered).auto* node = registry.tryGet<UINode>(entity);if (!node || node->hidden_in_tree_) continue;@@ -68,21 +76,39 @@ void UISystem::hitTestUpdate(Registry& registry, f32 mouseWorldX, f32 mouseWorld}}- hitWorldSprites(registry, mouseWorldX, mouseWorldY);+ hitWorldContent(registry, ray, resources);}/**- * World-space pick, for entities the layout tree does not contain.+ * World-space pick, for entities the layout tree does not contain — it takes its+ * geometry from UINode, leaving a bare Sprite and every MeshRenderer unreachable.+ * UI wins any overlap, hence running only after a miss.*- * The loop above takes its geometry from UINode, so a Sprite without one can- * never be hit there. Its size and pivot are its visible extent, so that is the- * box; UI wins any overlap, hence running only after a miss.+ * Sprites answer on their own plane, meshes against their oriented bounds, both+ * ranked by distance along the ray. A flat scene puts every sprite at the same+ * distance, so there the sorting layer decides alone.*/-void UISystem::hitWorldSprites(Registry& registry, f32 mouseWorldX, f32 mouseWorldY) {+void UISystem::hitWorldContent(Registry& registry, const PickRay& ray,+ const resource::ResourceManager* resources) {Entity best = INVALID_ENTITY;+ f32 bestT = 0.0f;i32 bestLayer = 0;bool haveBest = false;+ // Nearer wins; at the same distance the higher sorting layer does, and a tie+ // there goes to the later entity — the order the renderer batches in.+ const auto consider = [&](Entity entity, f32 t, i32 layer) {+ if (haveBest) {+ const bool sameDepth = std::abs(t - bestT) <= 1e-4f;+ if (!sameDepth && t > bestT) return;+ if (sameDepth && layer < bestLayer) return;+ }+ haveBest = true;+ bestT = t;+ bestLayer = layer;+ best = entity;+ };+registry.eachLive<Sprite, Interactable>([&](Entity entity, Sprite& sprite, Interactable& interactable) {if (!interactable.enabled || !interactable.raycastTarget) return;@@ -93,22 +119,46 @@ void UISystem::hitWorldSprites(Registry& registry, f32 mouseWorldX, f32 mouseWorauto& t = registry.get<Transform>(entity);t.ensureDecomposed();+ f32 px = 0.0f, py = 0.0f, hitT = 0.0f;+ if (!rayHitsPlaneZ(ray, t.worldPosition.z, px, py, hitT)) return;+if (!pointInOBB(- mouseWorldX, mouseWorldY,+ px, py,t.worldPosition.x, t.worldPosition.y,sprite.size.x * t.worldScale.x, sprite.size.y * t.worldScale.y,sprite.pivot.x, sprite.pivot.y,t.worldRotation.z, t.worldRotation.w)) return;- // Draw order decides who is on top, and layer is what carries it. A tie- // goes to the later entity, which is the order the renderer batches in.- const i32 layer = static_cast<i32>(sprite.layer);- if (!haveBest || layer >= bestLayer) {- haveBest = true;- bestLayer = layer;- best = entity;- }+ consider(entity, hitT, static_cast<i32>(sprite.layer));+ });++ registry.eachLive<MeshRenderer, Interactable>(+ [&](Entity entity, MeshRenderer& mesh, Interactable& interactable) {+ if (!interactable.enabled || !interactable.raycastTarget) return;+ if (!mesh.enabled) return;+ if (registry.has<UINode>(entity)) return;+ if (!registry.has<Transform>(entity)) return;++ // Bounds come from whichever geometry this is, the same way the cull+ // reads them: a resident mesh keeps its own and leaves the component's+ // empty, so reading the component's would test an empty box.+ const Mesh* resident =+ (resources && mesh.mesh.isValid()) ? resources->getMesh(mesh.mesh) : nullptr;+ if (!resident && mesh.indices.empty()) return;+ const glm::vec3 localMin = resident ? resident->localMin+ : glm::vec3(mesh.localMin, 0.0f);+ const glm::vec3 localMax = resident ? resident->localMax+ : glm::vec3(mesh.localMax, 0.0f);++ auto& t = registry.get<Transform>(entity);+ t.ensureDecomposed();++ f32 hitT = 0.0f;+ if (!rayHitsOBB(ray, t.worldPosition, t.worldRotation, t.worldScale,+ localMin, localMax, hitT)) return;++ consider(entity, hitT, static_cast<i32>(mesh.layer));});if (!haveBest) return;diff --git a/src/esengine/ui/UISystem.hpp b/src/esengine/ui/UISystem.hppindex c11f5d4cd..380fee783 100644--- a/src/esengine/ui/UISystem.hpp+++ b/src/esengine/ui/UISystem.hpp@@ -16,10 +16,13 @@#include "../ecs/Entity.hpp"#include "../ecs/Registry.hpp"#include "./UITree.hpp"+#include "./UIHitTestSystem.hpp"#include <memory>#include <vector>+namespace esengine::resource { class ResourceManager; }+namespace esengine::ecs {// Retained Yoga node cache — persists YGNodes across frames so a stable UI tree@@ -44,7 +47,7 @@ struct UIHitTestResult {* @code* auto& ui = ctx.require<ecs::UISystem>();* ui.layoutUpdate(registry, -960, -540, 960, 540);- * ui.hitTestUpdate(registry, mouseX, mouseY);+ * ui.hitTestUpdate(registry, PickRay{cameraPos, pointerDir}, &resources);* auto hitEntity = ui.getHitEntity();* @endcode*/@@ -77,9 +80,15 @@ public:// ---- Hit test pass (defined in UISystem.cpp) ----- /** @brief Run point-vs-UI hit-test, updating hitResult. A query: what a- * press or a hover MEANS is the interaction system's, and it is in TS. */- void hitTestUpdate(Registry& registry, f32 mouseWorldX, f32 mouseWorldY);+ /**+ * @brief Run ray-vs-content hit-test, updating hitResult. A query: what a+ * press or a hover MEANS is the interaction system's, and it is in TS.+ * @details UI wins any overlap, topmost first; below it world content ranks+ * by distance along the ray, sorting layer breaking a flat scene's+ * tie. Without @p resources only inline mesh geometry can be hit.+ */+ void hitTestUpdate(Registry& registry, const PickRay& ray,+ const resource::ResourceManager* resources = nullptr);/** @brief Editor pick: the most specific UI entity under the point. Unlike* hitTestUpdate it ignores Interactable and mutates no state. */@@ -102,7 +111,8 @@ public:private:/** @brief World-space pick for entities outside the layout tree (see .cpp) */- void hitWorldSprites(Registry& registry, f32 mouseWorldX, f32 mouseWorldY);+ void hitWorldContent(Registry& registry, const PickRay& ray,+ const resource::ResourceManager* resources);std::vector<Entity> pickResults_;