Skip to content

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.

feat(render): a subtree can sort as one unit

esenginec809c2c719b7
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index 4cfe7854d..85ea7107d 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -29,7 +29,7 @@ env:
test_registry_ondestroy test_view_api_matrix
test_shader_device test_draw_params test_texture_fb test_buffer_device
test_compressed_format test_batch_builder test_boundary_span test_webgpu_device
- test_clip_depth test_shadow_atlas test_particle_shapes test_lod_selection test_hdr_format
+ test_clip_depth test_sort_key test_shadow_atlas test_particle_shapes test_lod_selection test_hdr_format
test_text_edit test_render_graph test_device_loss test_physics_interpolation
test_bitmap_font test_texture_cache test_mesh_recovery test_aot_host test_aot_conformance
test_frame_lifecycle
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9ea21f89f..1ee45ca77 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -14,6 +14,41 @@ published separately; it ships inside the editor.
## [Unreleased]
+### Added
+
+- **A subtree can sort as one unit.** `sprite.order` is a promise about one sprite
+ against everything else in its layer, and that stops scaling the moment two
+ assembled characters overlap: raising a weapon over the other character raises it
+ over its own body too, and the only way out was globally unique orders across every
+ entity that might ever meet. `SortingGroup` states the layer and order a whole
+ subtree presents outward, and each member's own order becomes its place INSIDE the
+ group — so nothing outside can land between two members, which is the one thing a
+ per-sprite order cannot offer.
+
+ The group takes over everything DERIVED from a layer, not just the key: the camera's
+ culling bit and the layer's ordering rule are asked of the group's layer too.
+ Leaving either on the member y-sorts a group through one sprite and not the next.
+
+ Groups nest, and an inner one does not start a fresh identity — a weapon prefab
+ rigged under an arm would drift out of the character. It becomes one BLOCK in the
+ outer group instead, so it stays whole wherever the arm goes.
+
+ Where the member's order LIVES is the whole design. The group owns the key's top
+ fields, so the member needs the highest field left, and it must be the same field in
+ every packing or two members of one group are incomparable — a group holds an opaque
+ prop under a blended character. [37:30] is the only field directly under stage in all
+ three layouts, and it is stamped there after the fact, which costs nothing outside a
+ group and inside one replaces a projection (depth, shader, world Y) the author's
+ order was overriding anyway.
+
+ Held at three levels, each watched failing first: the bit layout in a new header-only
+ `test_sort_key` harness, the draw path's resolution in `test_batch_builder`, and the
+ editor's picking — which mirrors all of this in `layerOrder.ts`, or a click selects
+ what the person cannot see. Two of the engine cases were TRIVIALLY satisfied when
+ first written (a stated order outranks both depth and world Y, so it cannot be what
+ makes two layer rules disagree) and were rebuilt until sabotage reddened them.
+
+
## [0.63.0] - 2026-09-10
### Added
diff --git a/desktop b/desktop
index 171eda26b..307ebb2ed 160000
--- a/desktop
+++ b/desktop
@@ -1 +1 @@
-Subproject commit 171eda26ba7067d7eba2e95359612dbe7c103954
+Subproject commit 307ebb2ed7fc4f310cd4adb06ea3383ecdb661c3
diff --git a/docs/astro/src/content/docs/graphics/sprites.mdx b/docs/astro/src/content/docs/graphics/sprites.mdx
index 8753b3ff8..19005be8e 100644
--- a/docs/astro/src/content/docs/graphics/sprites.mdx
+++ b/docs/astro/src/content/docs/graphics/sprites.mdx
@@ -118,7 +118,53 @@ sprite.layer = 2; // e.g. "Foreground" — drawn on top
<Aside type="tip">
Sorting layers group things coarsely (background vs gameplay vs UI-in-world). For
- fine ordering *within* a layer, use the entity's `Transform` z position.
+ fine ordering *within* a layer, state `sprite.order` — see below.
+</Aside>
+
+### Order within a layer
+
+`sprite.order` is where a sprite sits **inside** its sorting layer: higher draws on
+top, the range is −128…127, and `0` says nothing at all. It outranks whatever the
+layer would otherwise have inferred — z on a painter layer, world Y on a Y-sorted one:
+
+```typescript
+shadow.order = -1; // under its owner, wherever the owner walks
+weapon.order = 1; // over the hand holding it
+```
+
+On a Y-sorted layer this is the *only* override there is, because z never reaches
+that key at all. Without it, keeping a shadow under its owner meant moving the sprite
+in Y and lying about where it stands.
+
+### Sorting groups
+
+An order is a promise about one sprite against **everything else in the layer**, and
+that stops scaling as soon as two assembled characters overlap: raising a weapon above
+the other character raises it above its own body too.
+
+`SortingGroup` makes an entity and its whole subtree sort as **one unit**. The group
+states the layer and order the assembly presents outward; each member's own
+`sprite.order` becomes its place *inside* the group, and nothing outside the group can
+land between two members.
+
+```typescript
+world.insert(character, SortingGroup, { layer: 2, order: 5 });
+// Inside the character, these are now free to mean only "which part is in front".
+world.update(body, Sprite, (s) => { s.order = 0; });
+world.update(arm, Sprite, (s) => { s.order = 1; });
+```
+
+Two characters are then ordered against each other by their groups alone, and neither
+one's parts can interleave with the other's.
+
+Groups nest. A weapon prefab that carries its own `SortingGroup`, rigged under an
+arm, stays one block wherever the arm goes — the outer group still owns the layer, and
+the block does not come apart around a sibling of the arm.
+
+<Aside type="caution">
+ A group's members and an ungrouped sprite that happens to share the group's layer
+ *and* order interleave in an unspecified way — "nothing lands between the members"
+ is a promise about the group's own place, so give the group a place of its own.
</Aside>
### Scene order breaks the tie
diff --git a/docs/astro/src/content/docs/zh-cn/graphics/sprites.mdx b/docs/astro/src/content/docs/zh-cn/graphics/sprites.mdx
index 17404baa8..1bf06eabe 100644
--- a/docs/astro/src/content/docs/zh-cn/graphics/sprites.mdx
+++ b/docs/astro/src/content/docs/zh-cn/graphics/sprites.mdx
@@ -104,7 +104,46 @@ sprite.layer = 2; // 例如 "Foreground" —— 画在上面
```
<Aside type="tip">
- 排序层做粗粒度分组(背景 vs 玩法 vs 世界内 UI)。层**内**的精细排序,用实体 `Transform` 的 z 位置。
+ 排序层做粗粒度分组(背景 vs 玩法 vs 世界内 UI)。层**内**的精细排序,声明 `sprite.order` —— 见下文。
+</Aside>
+
+### 层内次序
+
+`sprite.order` 是精灵在其排序层**内部**的位置:越大越靠上,范围 −128…127,`0` 表示什么都没说。
+它压过该层本来会推断出的顺序 —— 画家层的 z、Y 排序层的世界 Y:
+
+```typescript
+shadow.order = -1; // 始终在主人脚下,无论主人走到哪
+weapon.order = 1; // 始终在握住它的手上面
+```
+
+在 Y 排序层上这是**唯一**的覆盖手段,因为 z 根本进不了那把键。没有它的时候,想让影子留在
+主人脚下,只能挪动精灵的 Y —— 也就是谎报它站在哪里。
+
+### 排序组
+
+一个 order 是这一个精灵对**整层其他所有东西**的承诺,而两个拼装角色一重叠,这个承诺就不够用了:
+把武器抬到另一个角色之上,也就把它抬到了自己身体之上。
+
+`SortingGroup` 让一个实体连同它的整棵子树**作为一个单元**参与排序。组声明整个装配体对外呈现的
+层与次序;每个成员自己的 `sprite.order` 变成它在**组内**的位置,而组外的任何东西都不可能落到
+两个成员之间。
+
+```typescript
+world.insert(character, SortingGroup, { layer: 2, order: 5 });
+// 在角色内部,这两个数现在只需要表达"哪个部件在前"。
+world.update(body, Sprite, (s) => { s.order = 0; });
+world.update(arm, Sprite, (s) => { s.order = 1; });
+```
+
+于是两个角色之间只由各自的组来排序,谁的部件都不会和对方的交错。
+
+组可以嵌套。一个自带 `SortingGroup` 的武器预制体挂到手臂下面,无论手臂走到哪都保持为一整块 ——
+外层组仍然拥有那个层,而这一块不会被手臂的某个兄弟节点拆开。
+
+<Aside type="caution">
+ 组的成员,和一个恰好与该组**层与次序都相同**的组外精灵,两者之间的交错是未定义的 ——
+ "没有东西落在成员之间"是关于这个组自己那个位置的承诺,所以请给组一个属于它自己的位置。
</Aside>
### 场景顺序决定平局
diff --git a/docs/astro/src/data/componentDocs.ts b/docs/astro/src/data/componentDocs.ts
index cae5deb7a..748554a1d 100644
--- a/docs/astro/src/data/componentDocs.ts
+++ b/docs/astro/src/data/componentDocs.ts
@@ -78,6 +78,7 @@ export const COMPONENT_DOCS: Record<string, ComponentDoc> = {
StreamedWorld: { category: 'world', summary: 'Declares the scene a streamed world and how big the cook cuts its cells.', doc: 'world/streaming', anchor: 'declaring-a-streamed-world', anchorZh: '声明一个流送世界' },
WorldPersistent: { category: 'world', summary: 'Keeps an entity\'s whole subtree out of the partition — it belongs to the persistent world.', doc: 'world/streaming', anchor: 'declaring-a-streamed-world', anchorZh: '声明一个流送世界' },
WorldStreamingSource: { category: 'world', summary: 'Asks for the places near it to exist; several sources are unioned.', doc: 'world/streaming', anchor: 'asking-for-places-streaming-sources', anchorZh: '请求地方存在流送源' },
+ SortingGroup: { category: 'graphics', summary: 'Makes an entity and its whole subtree sort as one unit — the group states the layer and order, members state their place inside it.', doc: 'graphics/sprites', anchor: 'sorting-groups', anchorZh: '排序组' },
LODGroup: { category: 'graphics', summary: 'Cheaper stand-in meshes for a MeshRenderer, chosen by how much of the screen the object covers.', doc: 'performance/level-of-detail', anchor: 'the-lodgroup-component', anchorZh: 'lodgroup-组件' },
Video: { category: 'graphics', summary: 'Plays a video stream onto a surface in the world or the UI.', doc: 'graphics/video', anchor: 'the-video-component', anchorZh: 'video-组件' },
diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.json
index c94df2345..ef4f54926 100644
--- a/docs/astro/src/data/components.generated.json
+++ b/docs/astro/src/data/components.generated.json
@@ -3737,6 +3737,31 @@
"translation"
]
},
+ {
+ "name": "SortingGroup",
+ "source": "cpp",
+ "fields": [
+ {
+ "key": "layer",
+ "type": "enum (sortingLayers)",
+ "default": "0",
+ "doc": "Sorting layer for the entire group — members no longer state their own.",
+ "range": "step 1"
+ },
+ {
+ "key": "order",
+ "type": "number",
+ "default": "0",
+ "doc": "Draw order of the whole group inside its sorting layer — higher draws on top.",
+ "range": "-128–127, step 1"
+ },
+ {
+ "key": "enabled",
+ "type": "boolean",
+ "default": "true"
+ }
+ ]
+ },
{
"name": "SphereCollider3D",
"source": "cpp",
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index fcf00a5d2..0f0dea0a8 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -1,11 +1,11 @@
# API surface — esengine/index
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 113 public · 92 beta · 1676 experimental · 3 deprecated
+Symbols: 113 public · 93 beta · 1677 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
-"ffa08b49cfb9df43"
+"a30e798cbaa98d41"
```
## ANCHOR_AXES — const @experimental
@@ -3008,6 +3008,7 @@ width: number
## DrawRank — interface @experimental
```
+groupInner: number | null | undefined
layer: number
order: LayerOrder
orderInLayer: number
@@ -8010,6 +8011,18 @@ world: World
PlatformSocketReadyState
```
+## SortingGroup — const @experimental
+```
+BuiltinComponentDef<SortingGroupData>
+```
+
+## SortingGroupData — interface @beta
+```
+enabled: boolean
+layer: number
+order: number
+```
+
## SourceDelta — interface @experimental
```
added: readonly AddedEntity[]
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index d1d401bfc..a078aa5ac 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -1,11 +1,11 @@
# API surface — esengine/index.native
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 113 public · 97 beta · 1695 experimental · 3 deprecated
+Symbols: 113 public · 98 beta · 1696 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
-"ffa08b49cfb9df43"
+"a30e798cbaa98d41"
```
## ANCHOR_AXES — const @experimental
@@ -3016,6 +3016,7 @@ width: number
## DrawRank — interface @experimental
```
+groupInner: number | null | undefined
layer: number
order: LayerOrder
orderInLayer: number
@@ -8203,6 +8204,18 @@ world: World
PlatformSocketReadyState
```
+## SortingGroup — const @experimental
+```
+BuiltinComponentDef<SortingGroupData>
+```
+
+## SortingGroupData — interface @beta
+```
+enabled: boolean
+layer: number
+order: number
+```
+
## SourceDelta — interface @experimental
```
added: readonly AddedEntity[]
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index bc736d74d..28c15ade1 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.node
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 113 public · 94 beta · 1675 experimental · 3 deprecated
+Symbols: 113 public · 95 beta · 1676 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -3003,6 +3003,7 @@ width: number
## DrawRank — interface @experimental
```
+groupInner: number | null | undefined
layer: number
order: LayerOrder
orderInLayer: number
@@ -8005,6 +8006,18 @@ world: World
PlatformSocketReadyState
```
+## SortingGroup — const @experimental
+```
+BuiltinComponentDef<SortingGroupData>
+```
+
+## SortingGroupData — interface @beta
+```
+enabled: boolean
+layer: number
+order: number
+```
+
## SourceDelta — interface @experimental
```
added: readonly AddedEntity[]
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index c71f8e296..e4dd24be7 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/minigame
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 113 public · 92 beta · 1697 experimental · 3 deprecated
+Symbols: 113 public · 93 beta · 1698 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -3003,6 +3003,7 @@ width: number
## DrawRank — interface @experimental
```
+groupInner: number | null | undefined
layer: number
order: LayerOrder
orderInLayer: number
@@ -8251,6 +8252,18 @@ world: World
PlatformSocketReadyState
```
+## SortingGroup — const @experimental
+```
+BuiltinComponentDef<SortingGroupData>
+```
+
+## SortingGroupData — interface @beta
+```
+enabled: boolean
+layer: number
+order: number
+```
+
## SourceDelta — interface @experimental
```
added: readonly AddedEntity[]
diff --git a/sdk/etc/wasm.api.md b/sdk/etc/wasm.api.md
index 24b09ba15..e2bea2d8f 100644
--- a/sdk/etc/wasm.api.md
+++ b/sdk/etc/wasm.api.md
@@ -41,6 +41,7 @@ addRigidBody3D: (entity: Entity, component: RigidBody3D) => void
addSegmentCollider2D: (entity: Entity, component: SegmentCollider2D) => void
addShadowCaster2D: (entity: Entity, component: ShadowCaster2D) => void
addShapeRenderer: (entity: Entity, component: ShapeRenderer) => void
+addSortingGroup: (entity: Entity, component: SortingGroup) => void
addSphereCollider3D: (entity: Entity, component: SphereCollider3D) => void
addSpineAnimation: (entity: Entity, component: SpineAnimation) => void
addSprite: (entity: Entity, component: Sprite) => void
@@ -85,6 +86,7 @@ getRigidBody3D: (entity: Entity) => RigidBody3D
getSegmentCollider2D: (entity: Entity) => SegmentCollider2D
getShadowCaster2D: (entity: Entity) => ShadowCaster2D
getShapeRenderer: (entity: Entity) => ShapeRenderer
+getSortingGroup: (entity: Entity) => SortingGroup
getSphereCollider3D: (entity: Entity) => SphereCollider3D
getSpineAnimation: (entity: Entity) => SpineAnimation
getSprite: (entity: Entity) => Sprite
@@ -125,6 +127,7 @@ hasRigidBody3D: (entity: Entity) => boolean
hasSegmentCollider2D: (entity: Entity) => boolean
hasShadowCaster2D: (entity: Entity) => boolean
hasShapeRenderer: (entity: Entity) => boolean
+hasSortingGroup: (entity: Entity) => boolean
hasSphereCollider3D: (entity: Entity) => boolean
hasSpineAnimation: (entity: Entity) => boolean
hasSprite: (entity: Entity) => boolean
@@ -166,6 +169,7 @@ removeRigidBody3D: (entity: Entity) => void
removeSegmentCollider2D: (entity: Entity) => void
removeShadowCaster2D: (entity: Entity) => void
removeShapeRenderer: (entity: Entity) => void
+removeSortingGroup: (entity: Entity) => void
removeSphereCollider3D: (entity: Entity) => void
removeSpineAnimation: (entity: Entity) => void
removeSprite: (entity: Entity) => void
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 88f1b3117..f63ac7dc3 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/wechat
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 113 public · 92 beta · 1687 experimental · 3 deprecated
+Symbols: 113 public · 93 beta · 1688 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -3003,6 +3003,7 @@ width: number
## DrawRank — interface @experimental
```
+groupInner: number | null | undefined
layer: number
order: LayerOrder
orderInLayer: number
@@ -8012,6 +8013,18 @@ world: World
PlatformSocketReadyState
```
+## SortingGroup — const @experimental
+```
+BuiltinComponentDef<SortingGroupData>
+```
+
+## SortingGroupData — interface @beta
+```
+enabled: boolean
+layer: number
+order: number
+```
+
## SourceDelta — interface @experimental
```
added: readonly AddedEntity[]
diff --git a/sdk/src/core-runtime.ts b/sdk/src/core-runtime.ts
index 3c5135d54..30837fb54 100644
--- a/sdk/src/core-runtime.ts
+++ b/sdk/src/core-runtime.ts
@@ -94,6 +94,7 @@ export {
Light,
LightType,
ShadowCaster2D,
+ SortingGroup,
TrailRenderer,
MeshRenderer,
type MeshRendererData,
@@ -121,6 +122,7 @@ export {
type ShapeRendererData,
type LightData,
type ShadowCaster2DData,
+ type SortingGroupData,
type CameraData,
type CanvasData,
type VelocityData,
diff --git a/sdk/src/ecs/bridge/ptrAccessors.generated.ts b/sdk/src/ecs/bridge/ptrAccessors.generated.ts
index 560925efd..fdadcc771 100644
--- a/sdk/src/ecs/bridge/ptrAccessors.generated.ts
+++ b/sdk/src/ecs/bridge/ptrAccessors.generated.ts
@@ -1509,6 +1509,38 @@ export function createShapeRendererData(): ShapeRendererPtrData {
};
}
+export interface SortingGroupPtrData {
+ layer: number;
+ order: number;
+ enabled: boolean;
+}
+
+export function fillSortingGroup(
+ f32: Float32Array, u32: Uint32Array, u8: Uint8Array,
+ ptr: number, out: SortingGroupPtrData,
+): void {
+ out.layer = u32[ptr >> 2] | 0;
+ out.order = u32[(ptr + 4) >> 2] | 0;
+ out.enabled = u8[ptr + 8] !== 0;
+}
+
+export function writeSortingGroup(
+ f32: Float32Array, u32: Uint32Array, u8: Uint8Array,
+ ptr: number, data: SortingGroupPtrData,
+): void {
+ u32[ptr >> 2] = data.layer | 0;
+ u32[(ptr + 4) >> 2] = data.order | 0;
+ u8[ptr + 8] = data.enabled ? 1 : 0;
+}
+
+export function createSortingGroupData(): SortingGroupPtrData {
+ return {
+ layer: 0,
+ order: 0,
+ enabled: false,
+ };
+}
+
export interface SphereCollider3DPtrData {
radius: number;
friction: number;
@@ -2237,6 +2269,7 @@ export const PTR_ACCESSORS: Record<string, PtrAccessor<any>> = {
SegmentCollider2D: { fill: fillSegmentCollider2D, write: writeSegmentCollider2D, create: createSegmentCollider2DData },
ShadowCaster2D: { fill: fillShadowCaster2D, write: writeShadowCaster2D, create: createShadowCaster2DData },
ShapeRenderer: { fill: fillShapeRenderer, write: writeShapeRenderer, create: createShapeRendererData },
+ SortingGroup: { fill: fillSortingGroup, write: writeSortingGroup, create: createSortingGroupData },
SphereCollider3D: { fill: fillSphereCollider3D, write: writeSphereCollider3D, create: createSphereCollider3DData },
SpineAnimation: { fill: fillSpineAnimation, write: writeSpineAnimation, create: createSpineAnimationData },
Sprite: { fill: fillSprite, write: writeSprite, create: createSpriteData },
diff --git a/sdk/src/ecs/component.generated.ts b/sdk/src/ecs/component.generated.ts
index c8cfa3364..5568be438 100644
--- a/sdk/src/ecs/component.generated.ts
+++ b/sdk/src/ecs/component.generated.ts
@@ -15,7 +15,7 @@ import type { AlignContent, AlignItems, AlignSelf, BodyType, CanvasScaleMode, Cl
* getAbiLayoutHash(); BuiltinBridge.connect() compares them and refuses to
* run on mismatch, because mismatched offsets read the wrong heap bytes.
*/
-export const ABI_LAYOUT_HASH = 'ffa08b49cfb9df43';
+export const ABI_LAYOUT_HASH = 'a30e798cbaa98d41';
/**
* One asset-valued field of a component: which field, and what kind of
@@ -793,6 +793,21 @@ export const COMPONENT_META: Record<string, ComponentMetaEntry> = {
parallax: { tooltip: "Parallax scroll factor (1 = with world, <1 = slower, 0 = locked to camera).", advanced: true },
},
},
+ SortingGroup: {
+ defaults: {
+ layer: 0,
+ order: 0,
+ enabled: true,
+ },
+ assetFields: [],
+ entityFields: [],
+ colorFields: [],
+ animatableFields: [],
+ fields: {
+ layer: { step: 1, tooltip: "Sorting layer for the entire group — members no longer state their own.", enumSource: "sortingLayers" },
+ order: { min: -128, max: 127, step: 1, tooltip: "Draw order of the whole group inside its sorting layer — higher draws on top." },
+ },
+ },
SphereCollider3D: {
defaults: {
radius: 0.5,
@@ -1467,6 +1482,18 @@ export interface ShapeRendererData {
enabled: boolean;
}
+/**
+ * The fields of the engine's `SortingGroup` component, generated from
+ * the C++ struct so the two shapes cannot drift.
+ *
+ * @beta
+ */
+export interface SortingGroupData {
+ layer: number;
+ order: number;
+ enabled: boolean;
+}
+
export interface SphereCollider3DData {
radius: number;
friction: number;
diff --git a/sdk/src/ecs/component.ts b/sdk/src/ecs/component.ts
index 31d25a35f..f0dd4d960 100644
--- a/sdk/src/ecs/component.ts
+++ b/sdk/src/ecs/component.ts
@@ -15,6 +15,7 @@ export type { AssetFieldMeta, SkeletalFieldMeta };
// extending the generated base.
import type {
TransformData, SpriteData, ShapeRendererData, LightData, ShadowCaster2DData, DraggableData,
+ SortingGroupData,
CanvasData, VelocityData, ParentData, ChildrenData, SpineAnimationData, DragonBonesAnimationData,
TilemapLayerData, BitmapTextData, TrailRendererData, ParticleForceFieldData,
CameraData as CameraDataCpp, ParticleEmitterData as ParticleEmitterDataCpp,
@@ -797,6 +798,7 @@ export type ScaleMode = (typeof ScaleMode)[keyof typeof ScaleMode];
// automatically; tsc then enforces every consumer matches.
export type {
TransformData, SpriteData, ShapeRendererData, LightData, ShadowCaster2DData, DraggableData,
+ SortingGroupData,
CanvasData, VelocityData, ParentData, ChildrenData, SpineAnimationData, DragonBonesAnimationData,
TilemapLayerData, BitmapTextData, TrailRendererData, ParticleForceFieldData,
};
@@ -912,6 +914,16 @@ export const ShadowCaster2D = defineBuiltin<ShadowCaster2DData>('ShadowCaster2D'
metaDefaults<ShadowCaster2DData>('ShadowCaster2D')
);
+/**
+ * Makes this entity and everything under it sort as ONE unit: the group states the
+ * layer and order the whole subtree presents outward, and each member's own
+ * `Sprite.order` becomes its place INSIDE the group. Nothing outside the group can
+ * land between two of its members, which is what a per-sprite order cannot promise.
+ */
+export const SortingGroup = defineBuiltin<SortingGroupData>('SortingGroup',
+ metaDefaults<SortingGroupData>('SortingGroup')
+);
+
// The authoring defaults that differ from the C++ ctor (an active Orthographic
// at orthoSize 540 vs a Perspective/inactive runtime default) are authored at
// the C++ ES_PROPERTY sites (editor_default=) and merged in by metaDefaults.
diff --git a/sdk/src/ecs/entityPick.ts b/sdk/src/ecs/entityPick.ts
index fc5e34b76..9bcc7f75d 100644
--- a/sdk/src/ecs/entityPick.ts
+++ b/sdk/src/ecs/entityPick.ts
@@ -11,8 +11,10 @@
import type { Entity, Vec3 } from '../types';
import type { World } from './world';
import type { WorldRay } from '../ui/util/math';
-import { Transform, Sprite } from './component';
-import { layerOrderOf, rankPickCandidates, type PickCandidate } from '../render/layerOrder';
+import { Transform, Sprite, SortingGroup, Parent } from './component';
+import {
+ layerOrderOf, rankPickCandidates, sortingIdentity, type PickCandidate,
+} from '../render/layerOrder';
import {
entityWorldBox, meshWorldBox, entityBoxRayHit, type LayoutWorld,
} from './entityBox';
@@ -22,6 +24,28 @@ import {
* sprite it sits on. A realm that draws no gizmos has nothing up there. */
const GIZMO_PICK_LAYER = 1e6;
+/**
+ * The groups enclosing @p entity, OUTERMOST first — what `sortingIdentity` needs.
+ *
+ * Walked per hit rather than resolved once for the world: a pick sees a handful of
+ * candidates, and a table built for all of them would be the renderer's job done a
+ * second time, on a different clock, to answer about the frame that was drawn.
+ */
+function enclosingGroups(world: PickWorld, entity: Entity): { layer: number; order: number }[] {
+ const chain: { layer: number; order: number }[] = [];
+ let current: Entity | undefined = entity;
+ const seen = new Set<Entity>();
+ while (current !== undefined && !seen.has(current)) {
+ seen.add(current);
+ if (world.has(current, SortingGroup)) {
+ const g = world.get(current, SortingGroup);
+ if (g.enabled) chain.push({ layer: g.layer, order: g.order });
+ }
+ current = world.has(current, Parent) ? world.get(current, Parent).entity : undefined;
+ }
+ return chain.reverse();
+}
+
/**
* The reads a pick needs: a box's, plus the World's own list of entities.
*
@@ -71,19 +95,26 @@ export function pickEntitiesByRay(
if (!box || entityBoxRayHit(box, ray.origin, ray.dir) === null) continue;
const sprite = world.has(entity, Sprite) ? world.get(entity, Sprite) : null;
- const layer = sprite ? sprite.layer : unlayered;
+ // A group owns the layer as well as the order, so the layer's RULE is asked of
+ // the group's — the same resolution pushBatchDraw does, for the same reason.
+ const identity = sortingIdentity(
+ enclosingGroups(world, entity),
+ sprite ? sprite.layer : unlayered,
+ sprite?.order ?? 0,
+ );
const t = world.get(entity, Transform);
hits.push({
entity,
index: hits.length,
rank: {
- layer,
- order: layerOrderOf(layer, opts.ySortLayers ?? 0, opts.depthLayers ?? 0),
- orderInLayer: sprite?.order ?? 0,
+ layer: identity.layer,
+ order: layerOrderOf(identity.layer, opts.ySortLayers ?? 0, opts.depthLayers ?? 0),
+ orderInLayer: identity.orderInLayer,
+ groupInner: identity.groupInner,
worldY: t.worldPosition.y,
worldZ: t.worldPosition.z ?? 0,
},
});
}
return rankPickCandidates(hits);
-}
+}
\ No newline at end of file
diff --git a/sdk/src/render/layerOrder.ts b/sdk/src/render/layerOrder.ts
index 6fd258266..ecaf49075 100644
--- a/sdk/src/render/layerOrder.ts
+++ b/sdk/src/render/layerOrder.ts
@@ -60,6 +60,30 @@ export function clampDrawOrder(order: number): number {
return Math.max(-128, Math.min(127, Math.trunc(order) || 0));
}
+/**
+ * The identity a draw presents to the frame once any enclosing `SortingGroup` has had
+ * its say — the JS mirror of `RenderFrame::buildSortingGroups` and `pushBatchDraw`.
+ *
+ * @param groups Enclosing groups, OUTERMOST first, disabled ones already dropped.
+ *
+ * The outermost group owns what the frame sees: nothing outside lands between two
+ * members, which separate by their own order — or the block's, one nesting in.
+ */
+export function sortingIdentity(
+ groups: ReadonlyArray<{ layer: number; order: number }>,
+ ownLayer: number,
+ ownOrder: number,
+): { layer: number; orderInLayer: number; groupInner: number | null } {
+ if (groups.length === 0) {
+ return { layer: ownLayer, orderInLayer: ownOrder, groupInner: null };
+ }
+ return {
+ layer: groups[0].layer,
+ orderInLayer: groups[0].order,
+ groupInner: groups.length > 1 ? groups[1].order : ownOrder,
+ };
+}
+
/** What a draw's place in the frame depends on: its layer, where it sits inside
* that layer, the layer's rule, and the two world coordinates either rule uses. */
export interface DrawRank {
@@ -70,6 +94,10 @@ export interface DrawRank {
/** `Sprite.order`: the author's explicit place within the layer, outranking
* whatever the rule would have inferred. 0 means nothing was stated. */
orderInLayer: number;
+ /** Where this draw sits inside its `SortingGroup`, or null when it is in none.
+ * See {@link sortingIdentity} — with a group, `layer`/`orderInLayer` are the
+ * GROUP's and this is what separates the members. */
+ groupInner?: number | null;
worldY: number;
worldZ: number;
}
@@ -95,6 +123,14 @@ export function compareDrawRank(a: DrawRank, b: DrawRank): number {
const ao = clampDrawOrder(a.orderInLayer);
const bo = clampDrawOrder(b.orderInLayer);
if (ao !== bo) return ao - bo;
+ // Above the rule, where the key spends those bits. Only when BOTH are grouped: a
+ // group colliding with an ungrouped draw on layer AND order interleaves undefined —
+ // that promise is about the group's own place.
+ if (a.groupInner != null && b.groupInner != null) {
+ const ai = clampDrawOrder(a.groupInner);
+ const bi = clampDrawOrder(b.groupInner);
+ if (ai !== bi) return ai - bi;
+ }
return layerFrontness(a.order, a.worldY, a.worldZ) - layerFrontness(b.order, b.worldY, b.worldZ);
}
@@ -116,4 +152,4 @@ export function rankPickCandidates<T>(candidates: ReadonlyArray<PickCandidate<T>
return [...candidates]
.sort((a, b) => compareDrawRank(b.rank, a.rank) || b.index - a.index)
.map((c) => c.entity);
-}
+}
\ No newline at end of file
diff --git a/sdk/src/wasm/ptrLayouts.generated.ts b/sdk/src/wasm/ptrLayouts.generated.ts
index 19ecb1216..4930ae38d 100644
--- a/sdk/src/wasm/ptrLayouts.generated.ts
+++ b/sdk/src/wasm/ptrLayouts.generated.ts
@@ -402,6 +402,14 @@ export const PTR_LAYOUTS: Record<string, PtrLayout> = {
{ name: 'enabled', type: 'bool', offset: 44 },
],
},
+ SortingGroup: {
+ ptrFn: 'getSortingGroupPtr',
+ fields: [
+ { name: 'layer', type: 'i32', offset: 0 },
+ { name: 'order', type: 'i32', offset: 4 },
+ { name: 'enabled', type: 'bool', offset: 8 },
+ ],
+ },
SphereCollider3D: {
ptrFn: 'getSphereCollider3DPtr',
fields: [
diff --git a/sdk/src/wasm/wasm.generated.ts b/sdk/src/wasm/wasm.generated.ts
index 6126642a8..f340cf3e5 100644
--- a/sdk/src/wasm/wasm.generated.ts
+++ b/sdk/src/wasm/wasm.generated.ts
@@ -695,6 +695,12 @@ export interface ShapeRenderer {
enabled: boolean;
}
+export interface SortingGroup {
+ layer: number;
+ order: number;
+ enabled: boolean;
+}
+
export interface SphereCollider3D {
radius: number;
friction: number;
@@ -968,6 +974,10 @@ export interface Registry {
getShapeRenderer(entity: Entity): ShapeRenderer;
addShapeRenderer(entity: Entity, component: ShapeRenderer): void;
removeShapeRenderer(entity: Entity): void;
+ hasSortingGroup(entity: Entity): boolean;
+ getSortingGroup(entity: Entity): SortingGroup;
+ addSortingGroup(entity: Entity, component: SortingGroup): void;
+ removeSortingGroup(entity: Entity): void;
hasSphereCollider3D(entity: Entity): boolean;
getSphereCollider3D(entity: Entity): SphereCollider3D;
addSphereCollider3D(entity: Entity, component: SphereCollider3D): void;
@@ -1058,6 +1068,7 @@ export interface ESEngineModule {
SegmentCollider2D: new () => SegmentCollider2D;
ShadowCaster2D: new () => ShadowCaster2D;
ShapeRenderer: new () => ShapeRenderer;
+ SortingGroup: new () => SortingGroup;
SphereCollider3D: new () => SphereCollider3D;
SpineAnimation: new () => SpineAnimation;
Sprite: new () => Sprite;
diff --git a/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snap b/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snap
index 453220f7c..ab6836412 100644
--- a/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snap
+++ b/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snap
@@ -903,6 +903,19 @@ exports[`builtin FieldMeta (RC9-1 equivalence gate) > matches the golden snapsho
],
},
},
+ "SortingGroup": {
+ "layer": {
+ "enumSource": "sortingLayers",
+ "step": 1,
+ "tooltip": "Sorting layer for the entire group — members no longer state their own.",
+ },
+ "order": {
+ "max": 127,
+ "min": -128,
+ "step": 1,
+ "tooltip": "Draw order of the whole group inside its sorting layer — higher draws on top.",
+ },
+ },
"SpineAnimation": {
"animation": {
"enumSource": "spineAnimations",
diff --git a/sdk/tests/entity-pick.test.ts b/sdk/tests/entity-pick.test.ts
index c94a4dd8b..d7eef6bfc 100644
--- a/sdk/tests/entity-pick.test.ts
+++ b/sdk/tests/entity-pick.test.ts
@@ -9,7 +9,7 @@
*/
import { describe, expect, it } from 'vitest';
import { pickEntitiesByRay } from '../src/ecs/entityPick';
-import { Transform, Sprite, MeshRenderer } from '../src/ecs/component';
+import { Transform, Sprite, MeshRenderer, SortingGroup, Parent } from '../src/ecs/component';
import type { Entity } from '../src/types';
const name = (c: unknown): string => (c as { _name?: string })._name ?? (c as { name: string }).name;
@@ -105,3 +105,44 @@ describe('picking entities by ray', () => {
expect(pickEntitiesByRay(world, down(0, 0))).toHaveLength(2);
});
});
+
+/**
+ * A click has to land on what the person SEES, so the pick resolves groups the way
+ * the renderer does. These pin the two ways that can silently go wrong: reading the
+ * member's layer instead of the group's, and dropping the member order that is the
+ * only thing separating siblings once the group owns the layer.
+ */
+describe('picking inside a sorting group', () => {
+ const g = (layer: number, order: number) => ({ layer, order, enabled: true });
+
+ it('picks the group member stated on top, not the one with the higher own layer', () => {
+ const world = fakeWorld({
+ 1: { Transform: T(0, 0), SortingGroup: g(2, 0) },
+ // Both in the group. The BODY claims a far higher sorting layer of its own,
+ // which the group overrides — while the arm is stated above it inside.
+ 2: { Transform: T(0, 0), Sprite: { ...sprite(30), order: 0 }, Parent: { entity: ent(1) } },
+ 3: { Transform: T(0, 0), Sprite: { ...sprite(0), order: 1 }, Parent: { entity: ent(1) } },
+ });
+ expect(pickEntitiesByRay(world, down(0, 0))[0]).toBe(ent(3));
+ });
+
+ it('puts a whole group above an outsider the members individually sink below', () => {
+ const world = fakeWorld({
+ 1: { Transform: T(0, 0), SortingGroup: g(5, 4) },
+ 2: { Transform: T(0, 0), Sprite: { ...sprite(5), order: -120 }, Parent: { entity: ent(1) } },
+ // Ungrouped, stated above what the member states for itself — and still below
+ // the group the member belongs to.
+ 9: { Transform: T(0, 0), Sprite: { ...sprite(5), order: 3 } },
+ });
+ expect(pickEntitiesByRay(world, down(0, 0))[0]).toBe(ent(2));
+ });
+
+ it('is unaffected by a group that is disabled', () => {
+ const world = fakeWorld({
+ 1: { Transform: T(0, 0), SortingGroup: { layer: 9, order: 9, enabled: false } },
+ 2: { Transform: T(0, 0), Sprite: { ...sprite(1), order: 0 }, Parent: { entity: ent(1) } },
+ 9: { Transform: T(0, 0), Sprite: { ...sprite(2), order: 0 } },
+ });
+ expect(pickEntitiesByRay(world, down(0, 0))[0]).toBe(ent(9));
+ });
+});
diff --git a/sdk/tests/layer-order.test.ts b/sdk/tests/layer-order.test.ts
index 24e9ddd8d..ca45a7b08 100644
--- a/sdk/tests/layer-order.test.ts
+++ b/sdk/tests/layer-order.test.ts
@@ -9,7 +9,9 @@
* individual answer still looks plausible.
*/
import { describe, it, expect } from 'vitest';
-import { LayerOrder, layerOrderOf, layerFrontness, compareDrawRank } from '../src/render/layerOrder';
+import {
+ LayerOrder, layerOrderOf, layerFrontness, compareDrawRank, sortingIdentity,
+} from '../src/render/layerOrder';
describe('layerOrderOf', () => {
it('is painter order when neither mask claims the layer', () => {
@@ -122,3 +124,64 @@ describe('compareDrawRank', () => {
rank(1, LayerOrder.Painter, 0, 0, 300))).toBe(0);
});
});
+
+/**
+ * A group's whole claim is that nothing outside it lands between its members. That is
+ * the property to pin — not "a group sorts" — because every wrong resolution here still
+ * orders the members correctly among themselves and only fails against an outsider.
+ */
+describe('sortingIdentity', () => {
+ const rank = (id: ReturnType<typeof sortingIdentity>, worldZ = 0) => ({
+ layer: id.layer,
+ order: LayerOrder.Painter,
+ orderInLayer: id.orderInLayer,
+ groupInner: id.groupInner,
+ worldY: 0,
+ worldZ,
+ });
+
+ it('leaves an ungrouped draw stating its own layer and order', () => {
+ const id = sortingIdentity([], 3, 7);
+ expect(id).toEqual({ layer: 3, orderInLayer: 7, groupInner: null });
+ });
+
+ it('hands the group the outward identity and the member the inner one', () => {
+ const id = sortingIdentity([{ layer: 5, order: 2 }], 3, 7);
+ expect(id).toEqual({ layer: 5, orderInLayer: 2, groupInner: 7 });
+ });
+
+ it('keeps an outsider from landing between two members', () => {
+ const group = [{ layer: 5, order: 2 }];
+ const low = rank(sortingIdentity(group, 0, -100));
+ const high = rank(sortingIdentity(group, 0, 100));
+ const above = rank(sortingIdentity([], 5, 3));
+ const below = rank(sortingIdentity([], 5, 1));
+ expect(compareDrawRank(low, high)).toBeLessThan(0);
+ expect(compareDrawRank(below, low)).toBeLessThan(0);
+ expect(compareDrawRank(high, above)).toBeLessThan(0);
+ });
+
+ // The engine's nesting rule: the FIRST nesting decides the block and deeper ones
+ // join it, so a sub-assembly cannot be split around a sibling of the block it is in.
+ it('gives a nested group one block order, whatever the member states', () => {
+ const nested = [{ layer: 5, order: 2 }, { layer: 9, order: 4 }];
+ expect(sortingIdentity(nested, 0, 99).groupInner).toBe(4);
+ expect(sortingIdentity(nested, 0, -99).groupInner).toBe(4);
+ });
+
+ it('reads the outermost group for the layer, however deep the nesting', () => {
+ const nested = [{ layer: 5, order: 2 }, { layer: 9, order: 4 }, { layer: 1, order: 6 }];
+ const id = sortingIdentity(nested, 0, 0);
+ expect(id.layer).toBe(5);
+ expect(id.orderInLayer).toBe(2);
+ });
+
+ // Members separate by their stated place BEFORE the layer's rule gets a say —
+ // mirroring the key, where the member field sits directly under stage.
+ it('ranks a member above a nearer sibling it was stated above', () => {
+ const group = [{ layer: 5, order: 0 }];
+ const front = rank(sortingIdentity(group, 0, 0), 1000);
+ const stated = rank(sortingIdentity(group, 0, 1), -1000);
+ expect(compareDrawRank(front, stated)).toBeLessThan(0);
+ });
+});
diff --git a/src/esengine/aot/AotComponents.generated.cpp b/src/esengine/aot/AotComponents.generated.cpp
index effd511db..e4e66d013 100644
--- a/src/esengine/aot/AotComponents.generated.cpp
+++ b/src/esengine/aot/AotComponents.generated.cpp
@@ -27,6 +27,7 @@
#include "esengine/ecs/components/RigidBody2D.hpp"
#include "esengine/ecs/components/ShadowCaster2D.hpp"
#include "esengine/ecs/components/ShapeRenderer.hpp"
+#include "esengine/ecs/components/SortingGroup.hpp"
#include "esengine/ecs/components/SpineAnimation.hpp"
#include "esengine/ecs/components/Sprite.hpp"
#include "esengine/ecs/components/TilemapLayer.hpp"
@@ -200,6 +201,11 @@ ComponentAt engineComponentAt(ecs::Registry& registry, const char* name) {
return registry.tryGet<esengine::ecs::ShapeRenderer>(Entity::fromRaw(raw));
};
}
+ if (std::strcmp(name, "SortingGroup") == 0) {
+ return [&registry](std::uint32_t raw) -> void* {
+ return registry.tryGet<esengine::ecs::SortingGroup>(Entity::fromRaw(raw));
+ };
+ }
if (std::strcmp(name, "SphereCollider3D") == 0) {
return [&registry](std::uint32_t raw) -> void* {
return registry.tryGet<esengine::ecs::SphereCollider3D>(Entity::fromRaw(raw));
@@ -404,6 +410,11 @@ CandidatesOf engineComponentCandidates(ecs::Registry& registry, const char* name
return denseAsIds(registry.entitiesWith<esengine::ecs::ShapeRenderer>());
};
}
+ if (std::strcmp(name, "SortingGroup") == 0) {
+ return [&registry]() -> Candidates {
+ return denseAsIds(registry.entitiesWith<esengine::ecs::SortingGroup>());
+ };
+ }
if (std::strcmp(name, "SphereCollider3D") == 0) {
return [&registry]() -> Candidates {
return denseAsIds(registry.entitiesWith<esengine::ecs::SphereCollider3D>());
@@ -496,6 +507,7 @@ bool isEngineComponent(const char* name) {
if (std::strcmp(name, "SegmentCollider2D") == 0) return true;
if (std::strcmp(name, "ShadowCaster2D") == 0) return true;
if (std::strcmp(name, "ShapeRenderer") == 0) return true;
+ if (std::strcmp(name, "SortingGroup") == 0) return true;
if (std::strcmp(name, "SphereCollider3D") == 0) return true;
if (std::strcmp(name, "SpineAnimation") == 0) return true;
if (std::strcmp(name, "Sprite") == 0) return true;
diff --git a/src/esengine/bindings/EditorAPI.generated.cpp b/src/esengine/bindings/EditorAPI.generated.cpp
index a276e7290..3ebaafb17 100644
--- a/src/esengine/bindings/EditorAPI.generated.cpp
+++ b/src/esengine/bindings/EditorAPI.generated.cpp
@@ -2,10 +2,10 @@
* @file EditorAPI.generated.cpp
* @brief Auto-generated editor API with string-dispatched component access
* @details Generated by EHT - DO NOT EDIT
- * @schema_hash 2847d9de83059b20
+ * @schema_hash 4b73aeac9635cd13
*/
-#define ES_EDITOR_API_SCHEMA_HASH "2847d9de83059b20"
+#define ES_EDITOR_API_SCHEMA_HASH "4b73aeac9635cd13"
#include <emscripten/bind.h>
#include <string>
@@ -31,6 +31,7 @@
#include "../ecs/components/RigidBody3D.hpp"
#include "../ecs/components/ShadowCaster2D.hpp"
#include "../ecs/components/ShapeRenderer.hpp"
+#include "../ecs/components/SortingGroup.hpp"
#include "../ecs/components/SpineAnimation.hpp"
#include "../ecs/components/Sprite.hpp"
#include "../ecs/components/TilemapLayer.hpp"
@@ -90,6 +91,7 @@ std::vector<std::string> editor_getComponentNames() {
"SegmentCollider2D",
"ShadowCaster2D",
"ShapeRenderer",
+ "SortingGroup",
"SphereCollider3D",
"SpineAnimation",
"Sprite",
@@ -509,6 +511,12 @@ std::string editor_getComponentSchema(const std::string& name) {
{"key":"parallax.y","type":"float","group":"ShapeRenderer"},
{"key":"enabled","type":"bool","group":"ShapeRenderer"}
])JSON";
+ } else if (name == "SortingGroup") {
+ return R"JSON([
+ {"key":"layer","type":"int","group":"SortingGroup"},
+ {"key":"order","type":"int","group":"SortingGroup"},
+ {"key":"enabled","type":"bool","group":"SortingGroup"}
+ ])JSON";
} else if (name == "SphereCollider3D") {
return R"JSON([
{"key":"radius","type":"float","group":"SphereCollider3D"},
@@ -810,6 +818,9 @@ bool editor_addComponent(Registry& reg, u32 e, const std::string& name) {
} else if (name == "ShapeRenderer") {
if (!reg.has<esengine::ecs::ShapeRenderer>(entity)) reg.emplace<esengine::ecs::ShapeRenderer>(entity);
return true;
+ } else if (name == "SortingGroup") {
+ if (!reg.has<esengine::ecs::SortingGroup>(entity)) reg.emplace<esengine::ecs::SortingGroup>(entity);
+ return true;
} else if (name == "SphereCollider3D") {
if (!reg.has<esengine::ecs::SphereCollider3D>(entity)) reg.emplace<esengine::ecs::SphereCollider3D>(entity);
return true;
@@ -913,6 +924,8 @@ bool editor_removeComponent(Registry& reg, u32 e, const std::string& name) {
if (reg.has<esengine::ecs::ShadowCaster2D>(entity)) { reg.remove<esengine::ecs::ShadowCaster2D>(entity); return true; }
} else if (name == "ShapeRenderer") {
if (reg.has<esengine::ecs::ShapeRenderer>(entity)) { reg.remove<esengine::ecs::ShapeRenderer>(entity); return true; }
+ } else if (name == "SortingGroup") {
+ if (reg.has<esengine::ecs::SortingGroup>(entity)) { reg.remove<esengine::ecs::SortingGroup>(entity); return true; }
} else if (name == "SphereCollider3D") {
if (reg.has<esengine::ecs::SphereCollider3D>(entity)) { reg.remove<esengine::ecs::SphereCollider3D>(entity); return true; }
} else if (name == "SpineAnimation") {
@@ -972,6 +985,7 @@ bool editor_hasComponent(Registry& reg, u32 e, const std::string& name) {
if (name == "SegmentCollider2D") return reg.has<esengine::ecs::SegmentCollider2D>(entity);
if (name == "ShadowCaster2D") return reg.has<esengine::ecs::ShadowCaster2D>(entity);
if (name == "ShapeRenderer") return reg.has<esengine::ecs::ShapeRenderer>(entity);
+ if (name == "SortingGroup") return reg.has<esengine::ecs::SortingGroup>(entity);
if (name == "SphereCollider3D") return reg.has<esengine::ecs::SphereCollider3D>(entity);
if (name == "SpineAnimation") return reg.has<esengine::ecs::SpineAnimation>(entity);
if (name == "Sprite") return reg.has<esengine::ecs::Sprite>(entity);
@@ -1021,6 +1035,7 @@ std::vector<std::string> editor_getComponents(Registry& reg, u32 e) {
if (reg.has<esengine::ecs::SegmentCollider2D>(entity)) result.push_back("SegmentCollider2D");
if (reg.has<esengine::ecs::ShadowCaster2D>(entity)) result.push_back("ShadowCaster2D");
if (reg.has<esengine::ecs::ShapeRenderer>(entity)) result.push_back("ShapeRenderer");
+ if (reg.has<esengine::ecs::SortingGroup>(entity)) result.push_back("SortingGroup");
if (reg.has<esengine::ecs::SphereCollider3D>(entity)) result.push_back("SphereCollider3D");
if (reg.has<esengine::ecs::SpineAnimation>(entity)) result.push_back("SpineAnimation");
if (reg.has<esengine::ecs::Sprite>(entity)) result.push_back("Sprite");
@@ -2129,6 +2144,13 @@ bool editor_setInt(Registry& reg, u32 e, const std::string& comp, const std::str
else if (field == "layer") { c.layer = static_cast<i32>(value); }
else { return false; }
return true;
+ } else if (comp == "SortingGroup") {
+ if (!reg.has<esengine::ecs::SortingGroup>(entity)) return false;
+ auto& c = reg.get<esengine::ecs::SortingGroup>(entity);
+ if (field == "layer") { c.layer = static_cast<i32>(value); }
+ else if (field == "order") { c.order = static_cast<i32>(value); }
+ else { return false; }
+ return true;
} else if (comp == "SpineAnimation") {
if (!reg.has<esengine::ecs::SpineAnimation>(entity)) return false;
auto& c = reg.get<esengine::ecs::SpineAnimation>(entity);
@@ -2332,6 +2354,11 @@ i32 editor_getInt(Registry& reg, u32 e, const std::string& comp, const std::stri
const auto& c = reg.get<esengine::ecs::ShapeRenderer>(entity);
if (field == "shapeType") { return static_cast<i32>(c.shapeType); }
else if (field == "layer") { return static_cast<i32>(c.layer); }
+ } else if (comp == "SortingGroup") {
+ if (!reg.has<esengine::ecs::SortingGroup>(entity)) return 0;
+ const auto& c = reg.get<esengine::ecs::SortingGroup>(entity);
+ if (field == "layer") { return static_cast<i32>(c.layer); }
+ else if (field == "order") { return static_cast<i32>(c.order); }
} else if (comp == "SpineAnimation") {
if (!reg.has<esengine::ecs::SpineAnimation>(entity)) return 0;
const auto& c = reg.get<esengine::ecs::SpineAnimation>(entity);
@@ -2566,6 +2593,12 @@ bool editor_setBool(Registry& reg, u32 e, const std::string& comp, const std::st
if (field == "enabled") { c.enabled = value; }
else { return false; }
return true;
+ } else if (comp == "SortingGroup") {
+ if (!reg.has<esengine::ecs::SortingGroup>(entity)) return false;
+ auto& c = reg.get<esengine::ecs::SortingGroup>(entity);
+ if (field == "enabled") { c.enabled = value; }
+ else { return false; }
+ return true;
} else if (comp == "SphereCollider3D") {
if (!reg.has<esengine::ecs::SphereCollider3D>(entity)) return false;
auto& c = reg.get<esengine::ecs::SphereCollider3D>(entity);
@@ -2770,6 +2803,10 @@ bool editor_getBool(Registry& reg, u32 e, const std::string& comp, const std::st
if (!reg.has<esengine::ecs::ShapeRenderer>(entity)) return false;
const auto& c = reg.get<esengine::ecs::ShapeRenderer>(entity);
if (field == "enabled") { return c.enabled; }
+ } else if (comp == "SortingGroup") {
+ if (!reg.has<esengine::ecs::SortingGroup>(entity)) return false;
+ const auto& c = reg.get<esengine::ecs::SortingGroup>(entity);
+ if (field == "enabled") { return c.enabled; }
} else if (comp == "SphereCollider3D") {
if (!reg.has<esengine::ecs::SphereCollider3D>(entity)) return false;
const auto& c = reg.get<esengine::ecs::SphereCollider3D>(entity);
diff --git a/src/esengine/bindings/WebBindings.generated.cpp b/src/esengine/bindings/WebBindings.generated.cpp
index b5cca711f..801c6b2f9 100644
--- a/src/esengine/bindings/WebBindings.generated.cpp
+++ b/src/esengine/bindings/WebBindings.generated.cpp
@@ -31,6 +31,7 @@
#include "../ecs/components/RigidBody3D.hpp"
#include "../ecs/components/ShadowCaster2D.hpp"
#include "../ecs/components/ShapeRenderer.hpp"
+#include "../ecs/components/SortingGroup.hpp"
#include "../ecs/components/SpineAnimation.hpp"
#include "../ecs/components/Sprite.hpp"
#include "../ecs/components/TilemapLayer.hpp"
@@ -1711,6 +1712,11 @@ EMSCRIPTEN_BINDINGS(esengine_components) {
.field("parallax", &esengine::ecs::ShapeRenderer::parallax)
.field("enabled", &esengine::ecs::ShapeRenderer::enabled);
+ value_object<esengine::ecs::SortingGroup>("SortingGroup")
+ .field("layer", &esengine::ecs::SortingGroup::layer)
+ .field("order", &esengine::ecs::SortingGroup::order)
+ .field("enabled", &esengine::ecs::SortingGroup::enabled);
+
value_object<esengine::ecs::SphereCollider3D>("SphereCollider3D")
.field("radius", &esengine::ecs::SphereCollider3D::radius)
.field("friction", &esengine::ecs::SphereCollider3D::friction)
@@ -2503,6 +2509,27 @@ EMSCRIPTEN_BINDINGS(esengine_registry) {
r.remove<esengine::ecs::ShapeRenderer>(entity);
}))
+ // SortingGroup
+ .function("hasSortingGroup", optional_override([](Registry& r, u32 e) {
+ return r.has<esengine::ecs::SortingGroup>(static_cast<Entity>(e));
+ }))
+ .function("getSortingGroup", optional_override([](Registry& r, u32 e) -> esengine::ecs::SortingGroup& {
+ auto entity = static_cast<Entity>(e);
+ static esengine::ecs::SortingGroup s_dummy{};
+ if (!r.valid(entity) || !r.has<esengine::ecs::SortingGroup>(entity)) return s_dummy;
+ return r.get<esengine::ecs::SortingGroup>(entity);
+ }), allow_raw_pointers())
+ .function("addSortingGroup", optional_override([](Registry& r, u32 e, const esengine::ecs::SortingGroup& c) {
+ auto entity = static_cast<Entity>(e);
+ if (!r.valid(entity)) return;
+ r.emplaceOrReplace<esengine::ecs::SortingGroup>(entity, c);
+ }))
+ .function("removeSortingGroup", optional_override([](Registry& r, u32 e) {
+ auto entity = static_cast<Entity>(e);
+ if (!r.valid(entity) || !r.has<esengine::ecs::SortingGroup>(entity)) return;
+ r.remove<esengine::ecs::SortingGroup>(entity);
+ }))
+
// SphereCollider3D
.function("hasSphereCollider3D", optional_override([](Registry& r, u32 e) {
return r.has<esengine::ecs::SphereCollider3D>(static_cast<Entity>(e));
@@ -2822,6 +2849,7 @@ emscripten::val esengineGetBuiltinComponentNames() {
arr.set(i++, val(std::string("SegmentCollider2D")));
arr.set(i++, val(std::string("ShadowCaster2D")));
arr.set(i++, val(std::string("ShapeRenderer")));
+ arr.set(i++, val(std::string("SortingGroup")));
arr.set(i++, val(std::string("SphereCollider3D")));
arr.set(i++, val(std::string("SpineAnimation")));
arr.set(i++, val(std::string("Sprite")));
@@ -3098,6 +3126,9 @@ static_assert(offsetof(esengine::ecs::ShapeRenderer, cornerRadius) == 28, "ABI o
static_assert(offsetof(esengine::ecs::ShapeRenderer, layer) == 32, "ABI offset drift: esengine::ecs::ShapeRenderer.layer (EHT expected 32)");
static_assert(offsetof(esengine::ecs::ShapeRenderer, parallax) == 36, "ABI offset drift: esengine::ecs::ShapeRenderer.parallax (EHT expected 36)");
static_assert(offsetof(esengine::ecs::ShapeRenderer, enabled) == 44, "ABI offset drift: esengine::ecs::ShapeRenderer.enabled (EHT expected 44)");
+static_assert(offsetof(esengine::ecs::SortingGroup, layer) == 0, "ABI offset drift: esengine::ecs::SortingGroup.layer (EHT expected 0)");
+static_assert(offsetof(esengine::ecs::SortingGroup, order) == 4, "ABI offset drift: esengine::ecs::SortingGroup.order (EHT expected 4)");
+static_assert(offsetof(esengine::ecs::SortingGroup, enabled) == 8, "ABI offset drift: esengine::ecs::SortingGroup.enabled (EHT expected 8)");
static_assert(offsetof(esengine::ecs::SphereCollider3D, radius) == 0, "ABI offset drift: esengine::ecs::SphereCollider3D.radius (EHT expected 0)");
static_assert(offsetof(esengine::ecs::SphereCollider3D, friction) == 4, "ABI offset drift: esengine::ecs::SphereCollider3D.friction (EHT expected 4)");
static_assert(offsetof(esengine::ecs::SphereCollider3D, restitution) == 8, "ABI offset drift: esengine::ecs::SphereCollider3D.restitution (EHT expected 8)");
@@ -3218,7 +3249,7 @@ static_assert(offsetof(esengine::ecs::Velocity, angular) == 12, "ABI offset drif
// ABI Hash -- runtime handshake against the SDK bundle
// =============================================================================
-static const char* kEsAbiLayoutHash = "ffa08b49cfb9df43";
+static const char* kEsAbiLayoutHash = "a30e798cbaa98d41";
std::string esengineGetAbiLayoutHash() {
return std::string(kEsAbiLayoutHash);
diff --git a/src/esengine/ecs/components/SortingGroup.hpp b/src/esengine/ecs/components/SortingGroup.hpp
new file mode 100644
index 000000000..b48f825d8
--- /dev/null
+++ b/src/esengine/ecs/components/SortingGroup.hpp
@@ -0,0 +1,50 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file SortingGroup.hpp
+ * @brief Makes a subtree sort as ONE unit against the rest of the scene.
+ * @details A character assembled from sprites — body, arm, weapon, cape — has an internal
+ * front-to-back order that must hold, and an external position among everything else.
+ * Without a group those are the same number: raising the weapon above another
+ * character's sprite raises it above its own body too, and the only fix is to hand out
+ * globally-unique orders across every entity that might ever overlap.
+ *
+ * The group states the external promise, so its members no longer have to. Inside it
+ * each member's own `order` means "where in THIS group", and the group's `layer`/`order`
+ * is what the whole subtree presents outward. Nothing outside can land between two
+ * members, which is the property a per-sprite order cannot offer at all.
+ *
+ * Nesting takes the NEAREST enclosing group: an inner group is itself a member of the
+ * outer one, so a weapon's own sub-assembly travels with the arm holding it.
+ *
+ * @copyright Copyright (c) 2026 ESEngine Team
+ * Licensed under the Apache License, Version 2.0.
+ */
+#pragma once
+
+#include "../../core/Types.hpp"
+#include "../../core/Reflection.hpp"
+
+namespace esengine::ecs {
+
+/**
+ * @brief One sorting identity for an entity and everything under it.
+ */
+ES_COMPONENT(stability=beta)
+struct SortingGroup {
+ /** @brief The sorting layer the whole group presents outward. */
+ ES_PROPERTY(step=1, enum_source=sortingLayers,
+ tooltip="Sorting layer for the entire group — members no longer state their own.")
+ i32 layer{0};
+
+ /** @brief Where the group sits inside that layer; higher draws on top. */
+ ES_PROPERTY(step=1, min=-128, max=127,
+ tooltip="Draw order of the whole group inside its sorting layer — higher draws on top.")
+ i32 order{0};
+
+ /** @brief A disabled group is not a group: members sort on their own again. */
+ ES_PROPERTY()
+ bool enabled{true};
+};
+
+} // namespace esengine::ecs
diff --git a/src/esengine/renderer/draw/BatchBuilder.cpp b/src/esengine/renderer/draw/BatchBuilder.cpp
index f26c507b8..3f48b689f 100644
--- a/src/esengine/renderer/draw/BatchBuilder.cpp
+++ b/src/esengine/renderer/draw/BatchBuilder.cpp
@@ -47,12 +47,24 @@ void pushBatchDraw(DrawList& drawList, const ClipState& clips,
u32 vertexByteOffset, u32 vertexCount, u32 indexOffset, u32 indexCount,
const BatchDrawKey& key) {
if (indexCount == 0) return;
+
+ // A group takes over its members' outward identity, so EVERY layer-derived decision
+ // below asks the group's layer: the culling bit, the ordering rule, the key's top field.
+ // Leaving one on the member y-sorts a group through one sprite and not the next.
+ i32 layer = key.layer;
+ i32 order = key.order;
+ const DrawList::GroupIdentity* group = drawList.sortingGroupOf(key.entity.id());
+ if (group) {
+ layer = group->layer;
+ order = group->order;
+ }
+
// The camera's culling mask, applied at the one place draws are produced, so no
// render path can be added that forgets it.
- if (!drawList.layerVisible(key.cullBit ? key.cullBit : DrawList::layerBit(key.layer))) return;
+ if (!drawList.layerVisible(key.cullBit ? key.cullBit : DrawList::layerBit(layer))) return;
DrawCommand cmd{};
- const auto resolve = drawList.layerOrder(key.layer);
+ const auto resolve = drawList.layerOrder(layer);
// A depth layer decides its own stage and depth state; every other layer takes
// what the caller resolved from the material. The rule is the physical one, so
@@ -76,10 +88,17 @@ void pushBatchDraw(DrawList& drawList, const ClipState& clips,
// exists. A stencil write still precedes the draws testing it because UI pre-order
// puts a mask below its descendants in LAYER, the key's top field. Not so on one layer.
cmd.sort_key = resolve == DrawList::LayerOrder::YSort
- ? DrawCommand::buildSortKeyYSorted(stage, key.layer, key.y, key.shaderId,
- key.blend, 0, key.order)
- : DrawCommand::buildSortKey(stage, key.layer, key.shaderId,
- key.blend, 0, key.depth, key.materialId, key.order);
+ ? DrawCommand::buildSortKeyYSorted(stage, layer, key.y, key.shaderId,
+ key.blend, 0, order)
+ : DrawCommand::buildSortKey(stage, layer, key.shaderId,
+ key.blend, 0, key.depth, key.materialId, order);
+ // Inside a group the member's own order is all that separates siblings. Under a NESTED
+ // group it is the inner group's instead — a block does not come apart around another
+ // block's contents.
+ if (group) {
+ cmd.sort_key = DrawCommand::withGroupOrder(
+ cmd.sort_key, group->blockOrder ? group->block : key.order);
+ }
cmd.stage = stage;
cmd.index_offset = indexOffset;
cmd.index_count = indexCount;
@@ -125,7 +144,7 @@ void pushBatchDraw(DrawList& drawList, const ClipState& clips,
}
cmd.entity = key.entity;
cmd.type = key.type;
- cmd.layer = key.layer;
+ cmd.layer = layer;
clips.applyTo(key.entity, cmd);
drawList.push(cmd);
@@ -162,4 +181,4 @@ void appendIndexedBatch(TransientBufferPool& pool, DrawList& drawList, const Cli
appendIndexedDraw(pool, drawList, clips, verts, vertexCount, localIndices, indexCount, key);
}
-} // namespace esengine
+} // namespace esengine
\ No newline at end of file
diff --git a/src/esengine/renderer/draw/DrawCommand.hpp b/src/esengine/renderer/draw/DrawCommand.hpp
index f6d4673a7..14413af4a 100644
--- a/src/esengine/renderer/draw/DrawCommand.hpp
+++ b/src/esengine/renderer/draw/DrawCommand.hpp
@@ -147,6 +147,9 @@ struct DrawCommand {
// opaque [37:30] shader | [29:27] blend | [26:25] flags | [24:14] material | [13:0] depth
// blended [37:18] depth | [17:10] shader | [9:7] blend | [6:5] flags | [4:0] material
+ // A SortingGroup owns [63:40] for its members; [37:30] then carries the member's own
+ // order. See withGroupOrder.
+
// Material pays for the order field, being the only one that can afford it: a
// batching HINT, not identity (canMergeWith compares in full), so a collision costs
// a merge and never a wrong draw.
@@ -205,6 +208,19 @@ struct DrawCommand {
return static_cast<u64>(std::clamp(order + 128, 0, 255)) << 40;
}
+ /**
+ * @brief Re-stamps a member's own order into a key whose top fields a SortingGroup
+ * has taken over.
+ *
+ * @details [37:30] is the only field directly under stage in ALL three packings, and
+ * it must be one field or two members of a group are incomparable. Costs
+ * those bits' projection (depth, shader, worldY) inside a group only.
+ */
+ static u64 withGroupOrder(u64 key, i32 memberOrder) {
+ constexpr u64 field = 0xFFull << 30;
+ return (key & ~field) | (static_cast<u64>(std::clamp(memberOrder + 128, 0, 255)) << 30);
+ }
+
// Order-preserving float → u32: flip the sign bit for positives, all bits for
// negatives, so unsigned compare matches float compare (finite values).
static u32 orderedFloatBits(f32 v) {
@@ -352,4 +368,4 @@ struct DrawCommand {
}
};
-} // namespace esengine
+} // namespace esengine
\ No newline at end of file
diff --git a/src/esengine/renderer/draw/DrawList.hpp b/src/esengine/renderer/draw/DrawList.hpp
index 113d21ecf..692cf8933 100644
--- a/src/esengine/renderer/draw/DrawList.hpp
+++ b/src/esengine/renderer/draw/DrawList.hpp
@@ -9,6 +9,7 @@
#include "../frame/FrameCapture.hpp"
#include "../../math/Math.hpp"
+#include <unordered_map>
#include <vector>
namespace esengine {
@@ -109,6 +110,32 @@ public:
return LayerOrder::Painter;
}
+ /** @brief The sorting identity a SortingGroup imposes on one of its members. */
+ struct GroupIdentity {
+ /// What the whole group presents outward — the key's top two fields.
+ i32 layer = 0;
+ i32 order = 0;
+ /// Set when an INNER group stands between this draw and the outer one: the inner
+ /// group is one block inside the outer, so every draw under it shares the inner
+ /// group's order and stops separating by its own.
+ bool blockOrder = false;
+ i32 block = 0;
+ };
+
+ /** @brief Resolved once per collect, by the one walk that knows the hierarchy —
+ * the draw path only reads it, exactly as it reads ClipState. */
+ void setSortingGroup(u32 entity, const GroupIdentity& identity) {
+ group_identities_[entity] = identity;
+ }
+ void clearSortingGroups() { group_identities_.clear(); }
+
+ /** @brief The group @p entity belongs to, or null when it sorts on its own. */
+ const GroupIdentity* sortingGroupOf(u32 entity) const {
+ if (group_identities_.empty()) return nullptr;
+ auto it = group_identities_.find(entity);
+ return it != group_identities_.end() ? &it->second : nullptr;
+ }
+
private:
struct SortEntry {
u64 key;
@@ -122,6 +149,8 @@ private:
std::vector<DrawCommand> sorted_scratch_; // reused across frames to avoid a
// per-frame heap alloc in finalize()
u32 merged_draw_calls_ = 0;
+ /// Members of a SortingGroup, by entity id — empty in the common frame.
+ std::unordered_map<u32, GroupIdentity> group_identities_;
u32 ysort_mask_ = 0;
u32 depth_mask_ = 0;
/// Any command pushed this collect that tests or writes depth — see needsDepth.
diff --git a/src/esengine/renderer/frame/RenderFrame.cpp b/src/esengine/renderer/frame/RenderFrame.cpp
index 0116ca4df..c85320e19 100644
--- a/src/esengine/renderer/frame/RenderFrame.cpp
+++ b/src/esengine/renderer/frame/RenderFrame.cpp
@@ -9,6 +9,8 @@
#include "../../ecs/components/Transform.hpp"
#include "../../ecs/components/Light.hpp"
#include "../../ecs/components/ShadowCaster2D.hpp"
+#include "../../ecs/components/SortingGroup.hpp"
+#include "../../ecs/components/Hierarchy.hpp"
#include "../../ecs/components/MeshRenderer.hpp"
#include "../../resource/ShaderParser.hpp"
#include "../../core/Log.hpp"
@@ -895,6 +897,68 @@ void RenderFrame::buildClipState() {
}
}
+namespace {
+
+/**
+ * @brief Hands one group's identity to a subtree, stopping the descent at nothing.
+ *
+ * @details An inner group does not start a new identity — a weapon rigged under an arm
+ * would drift out of its character. It becomes a BLOCK in the outer one:
+ * everything below shares the inner group's order.
+ */
+void assignSortingSubtree(ecs::Registry& registry, DrawList& list, Entity entity,
+ DrawList::GroupIdentity identity) {
+ list.setSortingGroup(entity.id(), identity);
+ if (!registry.has<ecs::Children>(entity)) return;
+ for (auto child : registry.get<ecs::Children>(entity).entities) {
+ DrawList::GroupIdentity childIdentity = identity;
+ // The FIRST nesting decides the block; deeper ones join it. A grandchild group
+ // restating it would interleave its contents with a sibling of its own block.
+ if (!childIdentity.blockOrder && registry.has<ecs::SortingGroup>(child)) {
+ const auto& inner = registry.get<ecs::SortingGroup>(child);
+ if (inner.enabled) {
+ childIdentity.blockOrder = true;
+ childIdentity.block = inner.order;
+ }
+ }
+ assignSortingSubtree(registry, list, child, childIdentity);
+ }
+}
+
+/// Whether some ENABLED group already encloses @p entity, making it a member rather
+/// than a root. A disabled group is not a group, so it does not enclose anything.
+bool hasEnclosingGroup(ecs::Registry& registry, Entity entity) {
+ Entity current = entity;
+ while (registry.has<ecs::Parent>(current)) {
+ Entity parent = registry.get<ecs::Parent>(current).entity;
+ if (parent == INVALID_ENTITY) break;
+ if (registry.has<ecs::SortingGroup>(parent) &&
+ registry.get<ecs::SortingGroup>(parent).enabled) {
+ return true;
+ }
+ current = parent;
+ }
+ return false;
+}
+
+} // namespace
+
+void RenderFrame::buildSortingGroups(ecs::Registry& registry) {
+ draw_list_.clearSortingGroups();
+
+ auto groups = registry.view<ecs::SortingGroup>();
+ for (auto entity : groups) {
+ const auto& group = groups.get(entity);
+ if (!group.enabled) continue;
+ // Only the OUTERMOST group seeds an identity; the walk below reaches the inner
+ // ones as blocks. Seeding from an inner group too would overwrite what the outer
+ // one just wrote, and which of the two won would be view iteration order.
+ if (hasEnclosingGroup(registry, entity)) continue;
+ assignSortingSubtree(registry, draw_list_, entity,
+ {group.layer, group.order, false, 0});
+ }
+}
+
RenderFrameContext RenderFrame::makeContext() {
return {
context_,
@@ -1631,6 +1695,7 @@ void RenderFrame::collectAll(ecs::Registry& registry) {
// gathering lights and walking one render type's population are different
// work that a single total cannot be told apart by.
{ ES_PROFILE_SCOPE("render.collect.clip"); buildClipState(); }
+ { ES_PROFILE_SCOPE("render.collect.sorting"); buildSortingGroups(registry); }
{ ES_PROFILE_SCOPE("render.collect.lights"); collectLights(registry); }
// Decided here, drawn by the graph. Nothing in this function may touch the
// device: the frame reaches the host as several calls with its own draws
diff --git a/src/esengine/renderer/frame/RenderFrame.hpp b/src/esengine/renderer/frame/RenderFrame.hpp
index 9aedffce9..245d64c8d 100644
--- a/src/esengine/renderer/frame/RenderFrame.hpp
+++ b/src/esengine/renderer/frame/RenderFrame.hpp
@@ -558,6 +558,8 @@ private:
RenderFrameContext makeContext();
void buildClipState();
+ /// Resolves every SortingGroup into the per-entity identity the draw path reads.
+ void buildSortingGroups(ecs::Registry& registry);
/// Adds a finalized list's cost to this frame's tally (see the definition).
void accumulateStats(const DrawList& list);
/// The overlay pass's body: the projection its geometry was built for, then
diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt
index d89022bec..96502c376 100644
--- a/tests/CMakeLists.txt
+++ b/tests/CMakeLists.txt
@@ -176,6 +176,14 @@ target_include_directories(test_draw_params PRIVATE
)
add_test(NAME test_draw_params COMMAND test_draw_params)
+# The sort key's field layout, asserted on the bits. Header-only, so no engine link.
+add_executable(test_sort_key renderer/test_sort_key.cpp)
+target_include_directories(test_sort_key PRIVATE
+ ${CMAKE_SOURCE_DIR}/src
+ ${CMAKE_SOURCE_DIR}/third_party/glm
+)
+add_test(NAME test_sort_key COMMAND test_sort_key)
+
# Clip-depth convention: the engine builds for [-1,1] and a device keeping [0,1]
# is handed the same projection in its terms. Header-only math, so no engine link.
add_executable(test_clip_depth renderer/test_clip_depth.cpp)
diff --git a/tests/aot/generated/conformance/handshake.h b/tests/aot/generated/conformance/handshake.h
index 3cea771a4..02c02df7b 100644
--- a/tests/aot/generated/conformance/handshake.h
+++ b/tests/aot/generated/conformance/handshake.h
@@ -1,5 +1,5 @@
/* GENERATED by sdk/tests/aot-conformance.test.ts — do not edit. */
/* The contract half of the handshake. The width half is the harness. */
-#define ES_CONF_EXPECTED_CONTRACT_HASH 0x681b5793a937f90bULL
+#define ES_CONF_EXPECTED_CONTRACT_HASH 0xa4154112ef21846cULL
/* And which BUILD the artifact beside this one is. */
#define ES_CONF_EXPECTED_MODULE_CONTRACT 0xc3d0e057d5701a2eULL
diff --git a/tests/aot/generated/conformance/systems_decl.c b/tests/aot/generated/conformance/systems_decl.c
index 92e67c694..de1cf3021 100644
--- a/tests/aot/generated/conformance/systems_decl.c
+++ b/tests/aot/generated/conformance/systems_decl.c
@@ -10,7 +10,7 @@
answer, it is a read of a different field. The address width belongs
to the MACHINE, so it mixes in here rather than in the compiler and a
32-bit artifact cannot load into a 64-bit host. */
-#define ES_ABI_ENGINE_DIGEST 0x681b5793a937f90bULL
+#define ES_ABI_ENGINE_DIGEST 0xa4154112ef21846cULL
ES_EXPORT const uint64_t es_abi_hash =
ES_ABI_ENGINE_DIGEST ^ (0x9e3779b97f4a7c15ULL * (uint64_t)sizeof(es_addr_t));
diff --git a/tests/renderer/test_batch_builder.cpp b/tests/renderer/test_batch_builder.cpp
index 9c6ee7d9c..90a225558 100644
--- a/tests/renderer/test_batch_builder.cpp
+++ b/tests/renderer/test_batch_builder.cpp
@@ -1047,3 +1047,145 @@ TEST_CASE("growth: a steady workload inside capacity never reallocates") {
}
CHECK_EQ(device.resizeBufferCalls, before);
}
+
+// ============================================================================
+// SortingGroup — the resolution pushBatchDraw does, asserted through the frame.
+// The key's own field layout is test_sort_key's; what these hold is that the draw
+// path ASKS the group rather than the member, everywhere a layer is consulted.
+// ============================================================================
+
+// The promise a per-sprite order cannot make. Two members straddle an outsider's
+// order, and the outsider still may not come between them.
+TEST_CASE("group: an outsider cannot be drawn between two members") {
+ Harness h;
+ h.list.setSortingGroup(11, {/*layer=*/3, /*order=*/5, false, 0});
+ h.list.setSortingGroup(12, {/*layer=*/3, /*order=*/5, false, 0});
+ BatchVertex quad[4] = {};
+
+ BatchDrawKey low = quadKey(1, /*layer=*/9); // the member's own layer is ignored
+ low.order = -100;
+ low.entity = Entity(11);
+ BatchDrawKey high = quadKey(3, /*layer=*/9);
+ high.order = 100;
+ high.entity = Entity(12);
+ // Ungrouped, and stated BETWEEN what the two members state for themselves. Sorting
+ // by the member's own order — the pre-group behaviour — puts it in the middle.
+ BatchDrawKey outsider = quadKey(2, /*layer=*/3);
+ outsider.order = 6;
+ outsider.shaderId = 8;
+
+ appendQuad(h.pool, h.list, h.clips, quad, low);
+ appendQuad(h.pool, h.list, h.clips, quad, outsider);
+ appendQuad(h.pool, h.list, h.clips, quad, high);
+ h.list.finalize(h.pool);
+
+ REQUIRE(h.list.mergedDrawCallCount() == 3);
+ // The two members adjacent and in their stated order, the outsider clear of both.
+ CHECK(h.list.command(0).texture_ids[0] == 1);
+ CHECK(h.list.command(1).texture_ids[0] == 3);
+ CHECK(h.list.command(2).texture_ids[0] == 2);
+}
+
+// Everything derived from a layer has to come from the GROUP's layer. A member whose
+// own layer is y-sorted, in a group whose layer is not, must not y-sort.
+TEST_CASE("group: the layer's rule is the group's, not the member's") {
+ Harness h;
+ h.list.setYSortMask(1u << 4);
+ h.list.setSortingGroup(21, {/*layer=*/6, 0, false, 0});
+ h.list.setSortingGroup(22, {/*layer=*/6, 0, false, 0});
+ BatchVertex quad[4] = {};
+
+ // The two rules must DISAGREE or this passes whichever ran. A stated order cannot make
+ // them — it outranks both — so the orders are equal and depth and world Y are set to
+ // opposite conclusions.
+ BatchDrawKey backY = quadKey(1, /*layer=*/4);
+ backY.y = -100.0f; // y-sort: lower Y draws LAST
+ backY.depth = -100.0f; // painter: further draws FIRST
+ backY.entity = Entity(21);
+ BatchDrawKey frontY = quadKey(2, /*layer=*/4);
+ frontY.y = 100.0f;
+ frontY.depth = 100.0f;
+ frontY.shaderId = 8;
+ frontY.entity = Entity(22);
+
+ appendQuad(h.pool, h.list, h.clips, quad, backY);
+ appendQuad(h.pool, h.list, h.clips, quad, frontY);
+ h.list.finalize(h.pool);
+
+ REQUIRE(h.list.mergedDrawCallCount() == 2);
+ // The group's layer is painter-ordered, so depth decides: y-sort would have
+ // reversed exactly this pair.
+ CHECK(h.list.command(0).texture_ids[0] == 1);
+ CHECK(h.list.command(1).texture_ids[0] == 2);
+}
+
+// A group's members answer the camera's culling mask on the group's layer too —
+// otherwise half a character disappears when a camera drops the layer it was rigged in.
+TEST_CASE("group: culling reads the group's layer") {
+ Harness h;
+ h.list.setCullingMask(1u << 6); // the group's layer only
+ h.list.setSortingGroup(31, {/*layer=*/6, 0, false, 0});
+ BatchVertex quad[4] = {};
+
+ BatchDrawKey member = quadKey(1, /*layer=*/4); // a layer this camera does not draw
+ member.entity = Entity(31);
+ BatchDrawKey ungrouped = quadKey(2, /*layer=*/4);
+
+ appendQuad(h.pool, h.list, h.clips, quad, member);
+ appendQuad(h.pool, h.list, h.clips, quad, ungrouped);
+ h.list.finalize(h.pool);
+
+ REQUIRE(h.list.mergedDrawCallCount() == 1);
+ CHECK(h.list.command(0).texture_ids[0] == 1);
+}
+
+// A nested group is one block: its contents share the block's order and do not
+// interleave with a sibling of the block, whatever they state for themselves.
+TEST_CASE("group: a nested group's contents stay one block") {
+ Harness h;
+ h.list.setSortingGroup(41, {/*layer=*/3, 0, /*blockOrder=*/true, /*block=*/0});
+ h.list.setSortingGroup(42, {/*layer=*/3, 0, /*blockOrder=*/true, /*block=*/0});
+ h.list.setSortingGroup(43, {/*layer=*/3, 0, false, 0});
+ BatchVertex quad[4] = {};
+
+ // Two members of the inner block, stated far apart, and a sibling of the block
+ // whose own order sits between those two statements.
+ BatchDrawKey blockLow = quadKey(1, 3);
+ blockLow.order = -50;
+ blockLow.entity = Entity(41);
+ BatchDrawKey sibling = quadKey(2, 3);
+ sibling.order = 1;
+ sibling.shaderId = 8;
+ sibling.entity = Entity(43);
+ BatchDrawKey blockHigh = quadKey(3, 3);
+ blockHigh.order = 50;
+ blockHigh.entity = Entity(42);
+
+ appendQuad(h.pool, h.list, h.clips, quad, blockLow);
+ appendQuad(h.pool, h.list, h.clips, quad, sibling);
+ appendQuad(h.pool, h.list, h.clips, quad, blockHigh);
+ h.list.finalize(h.pool);
+
+ REQUIRE(h.list.mergedDrawCallCount() == 3);
+ CHECK(h.list.command(2).texture_ids[0] == 2); // the sibling is above the whole block
+}
+
+// A group that is not there changes nothing — the field that decides is the table,
+// not the presence of the component elsewhere in the scene.
+TEST_CASE("group: an ungrouped draw is unaffected by another entity's group") {
+ Harness h;
+ h.list.setSortingGroup(51, {/*layer=*/0, /*order=*/100, false, 0});
+ BatchVertex quad[4] = {};
+
+ BatchDrawKey a = quadKey(1, /*layer=*/2);
+ BatchDrawKey b = quadKey(2, /*layer=*/1);
+ b.shaderId = 8;
+
+ appendQuad(h.pool, h.list, h.clips, quad, a);
+ appendQuad(h.pool, h.list, h.clips, quad, b);
+ h.list.finalize(h.pool);
+
+ REQUIRE(h.list.mergedDrawCallCount() == 2);
+ CHECK(h.list.command(0).texture_ids[0] == 2);
+ CHECK(h.list.command(1).texture_ids[0] == 1);
+}
diff --git a/tests/renderer/test_sort_key.cpp b/tests/renderer/test_sort_key.cpp
new file mode 100644
index 000000000..75b7f4d3e
--- /dev/null
+++ b/tests/renderer/test_sort_key.cpp
@@ -0,0 +1,107 @@
+// The sort key's field layout, asserted on the bits rather than through a frame: two
+// draws in the right order prove nothing about WHICH field decided it, and that is what
+// the next change has to keep. Header-only, so no engine link.
+
+#include "esengine/renderer/draw/DrawCommand.hpp"
+
+#include <cstdio>
+
+using namespace esengine;
+
+static int g_failures = 0;
+#define CHECK(cond, msg) \
+ do { \
+ if (!(cond)) { std::printf("FAIL: %s\n", msg); ++g_failures; } \
+ else { std::printf("ok: %s\n", msg); } \
+ } while (0)
+
+/// The key a plain blended sprite gets, with every field the caller can vary.
+static u64 blended(i32 layer, i32 order, f32 depth, u32 shader = 0, u32 material = 0) {
+ return DrawCommand::buildSortKey(RenderStage::Transparent, layer, shader,
+ BlendMode::Normal, 0, depth, material, order);
+}
+
+static u64 opaque(i32 layer, i32 order, f32 depth, u32 shader = 0, u32 material = 0) {
+ return DrawCommand::buildSortKey(RenderStage::Opaque, layer, shader,
+ BlendMode::None, 0, depth, material, order);
+}
+
+static u64 ysorted(i32 layer, i32 order, f32 worldY, u32 shader = 0) {
+ return DrawCommand::buildSortKeyYSorted(RenderStage::Transparent, layer, worldY,
+ shader, BlendMode::Normal, 0, order);
+}
+
+/// The 8 bits a group spends on its members, read back out of a finished key.
+static u64 memberField(u64 key) { return (key >> 30) & 0xFF; }
+
+int main() {
+ // ---- What a group takes over -------------------------------------------------
+ // The promise is that nothing outside lands BETWEEN the members — a claim about the
+ // key's top fields, so it is checked there.
+ {
+ const u64 lowMember = DrawCommand::withGroupOrder(blended(5, 2, 0.0f), -100);
+ const u64 highMember = DrawCommand::withGroupOrder(blended(5, 2, 0.0f), 100);
+ const u64 outsiderAbove = blended(5, 3, 0.0f);
+ const u64 outsiderBelow = blended(5, 1, 0.0f);
+ CHECK(lowMember < highMember, "a member's own order still separates it inside the group");
+ CHECK(outsiderBelow < lowMember && highMember < outsiderAbove,
+ "an outsider cannot land between two members of one group");
+ }
+
+ // The member field must be the SAME field in every packing, or two members of one
+ // group could not be compared at all — the group's own stage is not uniform across
+ // its contents (an opaque prop under a blended character).
+ {
+ const u64 b = DrawCommand::withGroupOrder(blended(5, 0, 1.0f, 0xFF, 0x1F), 7);
+ const u64 o = DrawCommand::withGroupOrder(opaque(5, 0, 1.0f, 0xFF, 0x7FF), 7);
+ const u64 y = DrawCommand::withGroupOrder(ysorted(5, 0, 42.0f, 0xFF), 7);
+ CHECK(memberField(b) == memberField(o) && memberField(o) == memberField(y),
+ "the member field is the same 8 bits in all three packings");
+ CHECK(memberField(b) == 7u + 128u, "a member order is stored biased, like the group's");
+ }
+
+ // Stamping is not appending: it must LAND on those bits whatever they held, or a
+ // deep sprite would out-sort a shallow sibling stated to be above it.
+ {
+ const u64 near = DrawCommand::withGroupOrder(blended(5, 0, 1000.0f), 0);
+ const u64 far = DrawCommand::withGroupOrder(blended(5, 0, -1000.0f), 1);
+ CHECK(near < far, "a stated member order outranks the depth it overwrote");
+ }
+ {
+ const u64 backY = DrawCommand::withGroupOrder(ysorted(5, 0, 500.0f), 1);
+ const u64 frontY = DrawCommand::withGroupOrder(ysorted(5, 0, -500.0f), 0);
+ CHECK(frontY < backY, "a stated member order outranks world Y inside a group");
+ }
+
+ // Negative and out-of-range members, on the same terms as the group's own order:
+ // clamped, never wrapped, because a wrap turns "far on top" into "behind".
+ {
+ const u64 under = DrawCommand::withGroupOrder(blended(5, 0, 0.0f), -1);
+ const u64 unstated = DrawCommand::withGroupOrder(blended(5, 0, 0.0f), 0);
+ const u64 over = DrawCommand::withGroupOrder(blended(5, 0, 0.0f), 5000);
+ const u64 pinned = DrawCommand::withGroupOrder(blended(5, 0, 0.0f), 127);
+ CHECK(under < unstated, "a negative member sinks below an unstated one");
+ CHECK(over == pinned, "a member order past the range pins to the end it ran past");
+ }
+
+ // A group cannot leak: whatever a member states, it stays inside the group's layer.
+ {
+ const u64 loudMember = DrawCommand::withGroupOrder(blended(5, 0, 0.0f), 127);
+ const u64 quietAbove = blended(6, -128, 0.0f);
+ CHECK(loudMember < quietAbove, "the loudest member never escapes its group's layer");
+ }
+
+ // ---- What the stamp leaves alone ---------------------------------------------
+ // Only [37:30] moves. A group that also disturbed the layer, the order or the stage
+ // would reorder the frame in ways nothing here would catch.
+ {
+ const u64 plain = blended(5, 2, 1.0f, 0xFF, 0x1F);
+ const u64 stamped = DrawCommand::withGroupOrder(plain, 3);
+ constexpr u64 memberBits = 0xFFull << 30;
+ CHECK((plain & ~memberBits) == (stamped & ~memberBits),
+ "stamping a member order touches no other field");
+ }
+
+ std::printf(g_failures ? "\n%d check(s) failed\n" : "\nall checks passed\n", g_failures);
+ return g_failures == 0 ? 0 : 1;
+}