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(render): CompositeBatch draws a model of many parts in a few draws that follow its root, instancing repeated meshes and re-merging only the chunk an edit touches
yhhea972845630f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 94b2f3c95..ff07af1d3 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -14,6 +14,10 @@ published separately; it ships inside the editor.## [Unreleased]+### Added++- **A model of many parts that moves: `CompositeBatch`.** Put it on the root of a ship, a vehicle or a moving platform assembled from many meshes, and while the game runs its parts are drawn in a few draws parented to the root: a mesh repeated four times or more (a deck plank, a rail post) as one instanced set that copies no vertices, every other part merged by draw state into chunks of the root's own space. Moving, turning or scaling the root moves the whole model and merges nothing again. Adding, removing, re-meshing or re-placing a part re-merges only its chunk within half a second (`CompositeBatchingRes.refresh(root)` looks at once), and a part that keeps moving inside the model is let go to draw itself. The root reports what it drew, and so does `get_stats`. On a model of 2,004 parts, the meshes handed to the renderer went from 2,003 to 5 and the CPU frame from 3.3 ms to 1.2–1.4 ms; a model of about a hundred parts costs the same either way. A part under a composite is never also statically batched.+## [0.98.0] - 2026-11-05### Addeddiff --git a/desktop b/desktopindex 23b12eae6..a5a37fd72 160000--- a/desktop+++ b/desktop@@ -1 +1 @@-Subproject commit 23b12eae6b775405bec10c1613d31b881e271b36+Subproject commit a5a37fd7218f75f4d5442a3338c642b63e5102d6diff --git a/docs/astro/src/content/docs/performance/static-batching.mdx b/docs/astro/src/content/docs/performance/static-batching.mdxindex 58f3b1863..0585bf3d0 100644--- a/docs/astro/src/content/docs/performance/static-batching.mdx+++ b/docs/astro/src/content/docs/performance/static-batching.mdx@@ -76,3 +76,53 @@ many different pieces gains more than one made of a few repeated ones.The two frames differ on 1.1% of the pixels, by one level of 255 on 96% of those and at most five, all along geometry edges, fromthe merged vertices being transformed on the CPU in 32-bit floats; run to run the same scene differs on0.003%.++## A model that moves: `CompositeBatch`++A static batch bakes each part where it stands in the world, so a ship, a vehicle or a moving+platform assembled from planks, rails and props cannot use it. Put **`CompositeBatch`** on the+model's **root** instead; the parts need nothing.++```typescript+const ship = world.spawn('Ship');+world.insert(ship, Transform, {});+world.insert(ship, CompositeBatch, {});+// ...planks, posts and props parented under `ship`, each with its own MeshRenderer.+```++While the game runs, the parts are folded in the **root's own space**, and the meshes that draw+them are the root's children:++- Moving, turning or scaling the root moves the whole model. Nothing is merged again.+- A mesh repeated at least **Instance at** times (4 by default), such as a deck plank or a rail+ post, stays one resident mesh. It is drawn as one instanced set, which copies no vertices.+- Every other part is merged, by draw state, into chunks of the root's space. Adding, removing,+ re-meshing or re-placing a part re-merges only the chunk it is in, within half a second. Call+ `app.getResource(CompositeBatchingRes).refresh(root)` to look at once.+- A part that keeps moving inside the model, such as a door or a wheel, is let go after a few+ looks and draws itself, so it never costs a merge a frame.+- The rules a static batch keeps still hold. Skinned, morphing, LOD, billboard and blended parts+ and dynamic bodies draw themselves. A part under a composite is never also statically batched.++The root reports what it drew: **Batched parts**, **Instanced parts**, **Draws** and **Draws+before**, and **Moving parts**.++Measured in the editor's Play on WebGL2, a model of 2,004 parts (1,600 planks, 400 posts and four+props) under one root:++| | Plain | `CompositeBatch` |+|---|---|---|+| Meshes handed to the renderer per frame | 2,003 | 5 |+| Draw calls per frame | 7 | 5 |+| CPU frame cost (three runs of 180 frames) | 3.33–3.35 ms | 1.20–1.36 ms |++Draws barely move, because the renderer already instances a repeated mesh. What the composite+saves is collecting, culling and sorting every part each frame. That saving grows with the part+count: a ship of 108 parts costs about the same either way (0.65–0.67 ms plain, 0.68–0.90 ms+batched). At that size, the pass's own look at its parts, twice a second, is as large as what+it saves.++The `composite-batch` editor check holds the claims on that smaller ship. With mesh shadows off,+its frame matches the plain one within the scene's own frame-to-frame difference, moving the+root re-merges nothing, and an added part re-merges one chunk. With mesh shadows on, shadow edges+land about a pixel apart along roughly 2% of the frame; why is not yet established.diff --git a/docs/astro/src/content/docs/zh-cn/performance/static-batching.mdx b/docs/astro/src/content/docs/zh-cn/performance/static-batching.mdxindex 25fda249f..6fca03d64 100644--- a/docs/astro/src/content/docs/zh-cn/performance/static-batching.mdx+++ b/docs/astro/src/content/docs/zh-cn/performance/static-batching.mdx@@ -71,3 +71,43 @@ world.insert(wall, StaticBatch, {});两帧在 1.1% 的像素上有差别,其中 96% 只差 1 级(共 255 级),最多差 5 级,都在几何边缘,来自合并后的顶点在 CPU 上以 32 位浮点变换;同一场景两次运行之间只差 0.003%。++## 会移动的组合模型:`CompositeBatch`++静态合并把每个部件烘焙在它在世界里的位置,所以由甲板、栏杆和道具拼成的船、车辆或移动平台用不了它。+改为在模型的**根节点**上加 **`CompositeBatch`**,部件本身什么都不用加。++```typescript+const ship = world.spawn('Ship');+world.insert(ship, Transform, {});+world.insert(ship, CompositeBatch, {});+// ……甲板、柱子和道具都挂在 `ship` 下面,各自带 MeshRenderer。+```++游戏运行时,部件按**根节点自己的空间**合并,绘制它们的网格是根节点的子实体:++- 移动、旋转或缩放根节点,整个模型跟着动,不会重新合并任何东西。+- 重复出现至少 **Instance at** 次(默认 4)的网格,比如甲板和栏杆柱,保持为一份常驻网格,+ 作为一个实例化集合绘制,不复制任何顶点。+- 其余部件按绘制状态合并成根节点空间里的若干块。增加、删除、换网格或挪动一个部件,半秒内只重新合并它所在的那一块。+ 要立刻检查,调用 `app.getResource(CompositeBatchingRes).refresh(root)`。+- 在模型内部一直在动的部件(门、轮子)看几次之后会被放开,由它自己绘制,不会每帧都触发一次合并。+- 静态合并的规则仍然适用:蒙皮、变形、LOD、公告板、半透明部件和动态刚体由自己绘制。+ 组合模型下的部件不会再被静态合并。++根节点上会显示合并结果:**Batched parts**、**Instanced parts**、**Draws**、**Draws before** 和 **Moving parts**。++在编辑器 Play、WebGL2 下实测,一个根节点下 2,004 个部件(1,600 块甲板、400 根柱子、4 个道具):++| | 不加 | `CompositeBatch` |+|---|---|---|+| 每帧交给渲染器的网格 | 2,003 | 5 |+| 每帧绘制次数 | 7 | 5 |+| CPU 帧耗时(3 轮,每轮 180 帧) | 3.33–3.35 ms | 1.20–1.36 ms |++绘制次数变化不大,因为渲染器本来就会把重复的网格实例化。组合合并省下的是每帧逐个收集、剔除和排序部件的开销,+部件越多省得越多:108 个部件的小船两种方式差不多(不加 0.65–0.67 ms,加 0.68–0.90 ms),+这个规模下合并过程每秒两次检查部件的开销,和它省下的差不多大。++编辑器检查 `composite-batch` 用这艘小船锁定了这些结论:关掉网格阴影时,合并后的画面与不加时的差别在场景自身逐帧差别之内;+移动根节点不会重新合并;加一个部件只重新合并一块。开着网格阴影时,约 2% 的画面上阴影边缘会差一个像素左右,原因还没有确认。diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.jsonindex 432cf5f21..a35ee7829 100644--- a/docs/astro/src/data/apiStability.generated.json+++ b/docs/astro/src/data/apiStability.generated.json@@ -3,10 +3,10 @@"counts": {"public": 115,"beta": 176,- "experimental": 2821,+ "experimental": 2837,"deprecated": 3},- "total": 3112,+ "total": 3128,"subsystems": [{"id": "mobile-controls",diff --git a/docs/astro/src/data/componentDocs.ts b/docs/astro/src/data/componentDocs.tsindex 5726b4d90..f9c3e521f 100644--- a/docs/astro/src/data/componentDocs.ts+++ b/docs/astro/src/data/componentDocs.ts@@ -101,6 +101,7 @@ export const COMPONENT_DOCS: Record<string, ComponentDoc> = {SpriteMask: { category: 'graphics', summary: "Turns this entity's Sprite into a stencil that cuts the sprites drawn after it — a window, or a hole.", doc: 'graphics/sprites', anchor: 'sprite-masks', 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: '排序组' },GroupOpacity: { category: 'graphics', summary: 'Fades an entity and everything under it; the opacities multiply down the hierarchy into each descendant\'s own alpha.', doc: 'graphics/sprites', anchor: 'fading-a-whole-group', anchorZh: '整组淡出' },+ CompositeBatch: { category: 'graphics', summary: 'Marks the root of a model built from many parts that moves as a whole, so its parts are drawn in a few draws that follow the root: repeated meshes as instanced sets, the rest merged in chunks of the root's space.', doc: 'performance/static-batching', anchor: 'a-model-that-moves-compositebatch', anchorZh: '会移动的组合模型compositebatch' },StaticBatch: { category: 'graphics', summary: 'Marks a mesh that will not move, so the meshes sharing its material are merged into one draw while the game runs; it also records what became of this one.', doc: 'performance/static-batching', anchor: 'what-happens', anchorZh: '会发生什么' },Terrain: { category: 'graphics', summary: 'Ground made from a heightmap or noise, painted by height and slope, and drawn in chunks that coarsen with distance.', doc: 'graphics/terrain', anchor: 'the-component', anchorZh: '组件' },Planet: { category: 'graphics', summary: 'Ground on a sphere, drawn as six quadtrees round the eye from a generator the game registers, finest underfoot and a handful of coarse nodes from space.', doc: 'graphics/terrain', anchor: 'a-planet', anchorZh: '星球' },diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.jsonindex c999eabd6..e4bffd746 100644--- a/docs/astro/src/data/components.generated.json+++ b/docs/astro/src/data/components.generated.json@@ -1104,6 +1104,65 @@}]},+ {+ "name": "CompositeBatch",+ "source": "ts",+ "fields": [+ {+ "key": "instanceMin",+ "type": "number",+ "default": "4",+ "doc": "Parts of one mesh at or past this count are drawn as one instanced set (no copy of their vertices). Fewer are merged.",+ "range": "≥ 2"+ },+ {+ "key": "cellSize",+ "type": "number",+ "default": "0",+ "doc": "Side of a merge chunk in the root's space. Smaller chunks re-merge less on an edit and cull better; 0 chooses from the model's size.",+ "range": "≥ 0"+ },+ {+ "key": "parts",+ "type": "number",+ "default": "0",+ "readonly": true+ },+ {+ "key": "instanced",+ "type": "number",+ "default": "0",+ "readonly": true+ },+ {+ "key": "draws",+ "type": "number",+ "default": "0",+ "readonly": true+ },+ {+ "key": "drawsBefore",+ "type": "number",+ "default": "0",+ "readonly": true+ },+ {+ "key": "moving",+ "type": "number",+ "default": "0",+ "readonly": true+ }+ ],+ "animatable": [+ "instanceMin",+ "cellSize",+ "parts",+ "instanced",+ "draws",+ "drawsBefore",+ "moving"+ ]+ },{"name": "ContentRect","source": "cpp",@@ -8223,7 +8282,8 @@"doc": "None makes this node and its subtree transparent to the pointer — hits pass through to what is behind.","values": ["Auto",- "None"+ "None",+ "Receive"]},{diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex 1266da200..13068e027 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -1,7 +1,7 @@# API surface — esengine/index<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 164 beta · 2032 experimental · 3 deprecated+Symbols: 115 public · 164 beta · 2046 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -2000,6 +2000,11 @@ sprite: number | undefined"hit"```+## COMPOSITE_DEFAULTS — const @experimental+```+CompositeLimits+```+## CacheCleanupPreview — interface @experimental```budgetBytes: number@@ -2841,6 +2846,87 @@ transient: boolean | undefined}```+## CompositeBatch — const @experimental+```+ComponentDef<CompositeBatchData>+```++## CompositeBatchData — interface @experimental+```+cellSize: number+draws: number+drawsBefore: number+instanceMin: number+instanced: number+moving: number+parts: number+```++## CompositeBatchPlugin — class @experimental+```+build: (app: App) => void+cleanup: (app?: App) => void+name: string+static new (): CompositeBatchPlugin+static prototype: CompositeBatchPlugin+```++## CompositeBatching — class @experimental+```+@internal busy_: boolean+@internal composites_: Map<number, CompositeState>+@internal forced_: Set<number>+counts: { scans: number; applies: number; merges: number; placementWrites: number; }+refresh: (root?: Entity) => void+report: (root: Entity) => { sets: number; chunks: number; alone: number; moving: number; refused: number; parts: number; } | null+static new (): CompositeBatching+static prototype: CompositeBatching+```++## CompositeBatchingRes — const @experimental+```+ResourceDef<CompositeBatching>+```++## CompositeChunk — interface @experimental+```+entities: number[]+id: string+key: string+```++## CompositeInstanceSet — interface @experimental+```+entities: number[]+key: string+mesh: number+```++## CompositeLimits — interface @experimental+```+cellSize: number+instanceMin: number+maxVertices: number+```++## CompositePart — interface @experimental+```+center: readonly [number, number, number]+entity: number+key: string+local: Mat4+mesh: number+vertices: number+```++## CompositePlan — interface @experimental+```+alone: number[]+cellSize: number+chunks: CompositeChunk[]+sets: CompositeInstanceSet[]+```+## CompressedTextureFormat — enum @experimental```ASTC_4x4 = "astc-4x4"@@ -4645,6 +4731,7 @@ triangles: numberaudioBytes: number | undefinedaudioStreamedCount: number | undefinedaudioStreamedSavedBytes: number | undefined+compositeBatch: { entity: number; parts: number; instanced: number; draws: number; drawsBefore: number; moving: number; }[] | undefinedcosts: FrameCosts | nullcppCounters: Record<string, number>cppScopes: Record<string, number>@@ -14183,6 +14270,11 @@ MotionDriver<AnimatorBlend2DMotion>(p: { x: number; y: number; z: number; }, q: { x: number; y: number; z: number; w: number; }, s: { x: number; y: number; z: number; }): number[]```+## compositeBatchPlugin — const @experimental+```+Plugin+```+## compressedUploadDecision — function @experimental```(target: CompressedTextureFormat | null, transcoded: boolean): TextureUploadDecision@@ -15958,6 +16050,11 @@ ParticlePlugin(lines: Vec3[][], position: Vec3, rotation: Quat): Vec3[][]```+## planComposite — function @experimental+```+(parts: readonly CompositePart[], limits?: CompositeLimits, cellSize?: number): CompositePlan+```+## planStaticBatches — function @experimental```(candidates: readonly StaticBatchCandidate[], limits?: StaticBatchLimits): StaticBatchPlan@@ -16513,6 +16610,11 @@ PrefabsPlugin(seed: number): () => number```+## rootLocalMatrix — function @experimental+```+(chain: readonly TRS[]): Mat4+```+## rotateVec3ByQuat — function @experimental```(rot: Quat, v: Vec3): Vec3diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex e1a15b9ca..73df06fff 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.native<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 169 beta · 2051 experimental · 3 deprecated+Symbols: 115 public · 169 beta · 2065 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -2000,6 +2000,11 @@ sprite: number | undefined"hit"```+## COMPOSITE_DEFAULTS — const @experimental+```+CompositeLimits+```+## CacheCleanupPreview — interface @experimental```budgetBytes: number@@ -2849,6 +2854,87 @@ transient: boolean | undefined}```+## CompositeBatch — const @experimental+```+ComponentDef<CompositeBatchData>+```++## CompositeBatchData — interface @experimental+```+cellSize: number+draws: number+drawsBefore: number+instanceMin: number+instanced: number+moving: number+parts: number+```++## CompositeBatchPlugin — class @experimental+```+build: (app: App) => void+cleanup: (app?: App) => void+name: string+static new (): CompositeBatchPlugin+static prototype: CompositeBatchPlugin+```++## CompositeBatching — class @experimental+```+@internal busy_: boolean+@internal composites_: Map<number, CompositeState>+@internal forced_: Set<number>+counts: { scans: number; applies: number; merges: number; placementWrites: number; }+refresh: (root?: Entity) => void+report: (root: Entity) => { sets: number; chunks: number; alone: number; moving: number; refused: number; parts: number; } | null+static new (): CompositeBatching+static prototype: CompositeBatching+```++## CompositeBatchingRes — const @experimental+```+ResourceDef<CompositeBatching>+```++## CompositeChunk — interface @experimental+```+entities: number[]+id: string+key: string+```++## CompositeInstanceSet — interface @experimental+```+entities: number[]+key: string+mesh: number+```++## CompositeLimits — interface @experimental+```+cellSize: number+instanceMin: number+maxVertices: number+```++## CompositePart — interface @experimental+```+center: readonly [number, number, number]+entity: number+key: string+local: Mat4+mesh: number+vertices: number+```++## CompositePlan — interface @experimental+```+alone: number[]+cellSize: number+chunks: CompositeChunk[]+sets: CompositeInstanceSet[]+```+## CompressedTextureFormat — enum @experimental```ASTC_4x4 = "astc-4x4"@@ -4653,6 +4739,7 @@ triangles: numberaudioBytes: number | undefinedaudioStreamedCount: number | undefinedaudioStreamedSavedBytes: number | undefined+compositeBatch: { entity: number; parts: number; instanced: number; draws: number; drawsBefore: number; moving: number; }[] | undefinedcosts: FrameCosts | nullcppCounters: Record<string, number>cppScopes: Record<string, number>@@ -14411,6 +14498,11 @@ MotionDriver<AnimatorBlend2DMotion>(p: { x: number; y: number; z: number; }, q: { x: number; y: number; z: number; w: number; }, s: { x: number; y: number; z: number; }): number[]```+## compositeBatchPlugin — const @experimental+```+Plugin+```+## compressedUploadDecision — function @experimental```(target: CompressedTextureFormat | null, transcoded: boolean): TextureUploadDecision@@ -16221,6 +16313,11 @@ ParticlePlugin(lines: Vec3[][], position: Vec3, rotation: Quat): Vec3[][]```+## planComposite — function @experimental+```+(parts: readonly CompositePart[], limits?: CompositeLimits, cellSize?: number): CompositePlan+```+## planStaticBatches — function @experimental```(candidates: readonly StaticBatchCandidate[], limits?: StaticBatchLimits): StaticBatchPlan@@ -16776,6 +16873,11 @@ PrefabsPlugin(seed: number): () => number```+## rootLocalMatrix — function @experimental+```+(chain: readonly TRS[]): Mat4+```+## rotateVec3ByQuat — function @experimental```(rot: Quat, v: Vec3): Vec3diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 6f25d9582..801d7b7d5 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: 115 public · 166 beta · 2031 experimental · 3 deprecated+Symbols: 115 public · 166 beta · 2045 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -1995,6 +1995,11 @@ sprite: number | undefined"hit"```+## COMPOSITE_DEFAULTS — const @experimental+```+CompositeLimits+```+## CacheCleanupPreview — interface @experimental```budgetBytes: number@@ -2836,6 +2841,87 @@ transient: boolean | undefined}```+## CompositeBatch — const @experimental+```+ComponentDef<CompositeBatchData>+```++## CompositeBatchData — interface @experimental+```+cellSize: number+draws: number+drawsBefore: number+instanceMin: number+instanced: number+moving: number+parts: number+```++## CompositeBatchPlugin — class @experimental+```+build: (app: App) => void+cleanup: (app?: App) => void+name: string+static new (): CompositeBatchPlugin+static prototype: CompositeBatchPlugin+```++## CompositeBatching — class @experimental+```+@internal busy_: boolean+@internal composites_: Map<number, CompositeState>+@internal forced_: Set<number>+counts: { scans: number; applies: number; merges: number; placementWrites: number; }+refresh: (root?: Entity) => void+report: (root: Entity) => { sets: number; chunks: number; alone: number; moving: number; refused: number; parts: number; } | null+static new (): CompositeBatching+static prototype: CompositeBatching+```++## CompositeBatchingRes — const @experimental+```+ResourceDef<CompositeBatching>+```++## CompositeChunk — interface @experimental+```+entities: number[]+id: string+key: string+```++## CompositeInstanceSet — interface @experimental+```+entities: number[]+key: string+mesh: number+```++## CompositeLimits — interface @experimental+```+cellSize: number+instanceMin: number+maxVertices: number+```++## CompositePart — interface @experimental+```+center: readonly [number, number, number]+entity: number+key: string+local: Mat4+mesh: number+vertices: number+```++## CompositePlan — interface @experimental+```+alone: number[]+cellSize: number+chunks: CompositeChunk[]+sets: CompositeInstanceSet[]+```+## CompressedTextureFormat — enum @experimental```ASTC_4x4 = "astc-4x4"@@ -4640,6 +4726,7 @@ triangles: numberaudioBytes: number | undefinedaudioStreamedCount: number | undefinedaudioStreamedSavedBytes: number | undefined+compositeBatch: { entity: number; parts: number; instanced: number; draws: number; drawsBefore: number; moving: number; }[] | undefinedcosts: FrameCosts | nullcppCounters: Record<string, number>cppScopes: Record<string, number>@@ -14178,6 +14265,11 @@ MotionDriver<AnimatorBlend2DMotion>(p: { x: number; y: number; z: number; }, q: { x: number; y: number; z: number; w: number; }, s: { x: number; y: number; z: number; }): number[]```+## compositeBatchPlugin — const @experimental+```+Plugin+```+## compressedUploadDecision — function @experimental```(target: CompressedTextureFormat | null, transcoded: boolean): TextureUploadDecision@@ -15963,6 +16055,11 @@ ParticlePlugin(lines: Vec3[][], position: Vec3, rotation: Quat): Vec3[][]```+## planComposite — function @experimental+```+(parts: readonly CompositePart[], limits?: CompositeLimits, cellSize?: number): CompositePlan+```+## planStaticBatches — function @experimental```(candidates: readonly StaticBatchCandidate[], limits?: StaticBatchLimits): StaticBatchPlan@@ -16518,6 +16615,11 @@ PrefabsPlugin(seed: number): () => number```+## rootLocalMatrix — function @experimental+```+(chain: readonly TRS[]): Mat4+```+## rotateVec3ByQuat — function @experimental```(rot: Quat, v: Vec3): Vec3diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 5ad224514..278930160 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: 115 public · 164 beta · 2053 experimental · 3 deprecated+Symbols: 115 public · 164 beta · 2067 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -1995,6 +1995,11 @@ sprite: number | undefined"hit"```+## COMPOSITE_DEFAULTS — const @experimental+```+CompositeLimits+```+## CacheCleanupPreview — interface @experimental```budgetBytes: number@@ -2836,6 +2841,87 @@ transient: boolean | undefined}```+## CompositeBatch — const @experimental+```+ComponentDef<CompositeBatchData>+```++## CompositeBatchData — interface @experimental+```+cellSize: number+draws: number+drawsBefore: number+instanceMin: number+instanced: number+moving: number+parts: number+```++## CompositeBatchPlugin — class @experimental+```+build: (app: App) => void+cleanup: (app?: App) => void+name: string+static new (): CompositeBatchPlugin+static prototype: CompositeBatchPlugin+```++## CompositeBatching — class @experimental+```+@internal busy_: boolean+@internal composites_: Map<number, CompositeState>+@internal forced_: Set<number>+counts: { scans: number; applies: number; merges: number; placementWrites: number; }+refresh: (root?: Entity) => void+report: (root: Entity) => { sets: number; chunks: number; alone: number; moving: number; refused: number; parts: number; } | null+static new (): CompositeBatching+static prototype: CompositeBatching+```++## CompositeBatchingRes — const @experimental+```+ResourceDef<CompositeBatching>+```++## CompositeChunk — interface @experimental+```+entities: number[]+id: string+key: string+```++## CompositeInstanceSet — interface @experimental+```+entities: number[]+key: string+mesh: number+```++## CompositeLimits — interface @experimental+```+cellSize: number+instanceMin: number+maxVertices: number+```++## CompositePart — interface @experimental+```+center: readonly [number, number, number]+entity: number+key: string+local: Mat4+mesh: number+vertices: number+```++## CompositePlan — interface @experimental+```+alone: number[]+cellSize: number+chunks: CompositeChunk[]+sets: CompositeInstanceSet[]+```+## CompressedTextureFormat — enum @experimental```ASTC_4x4 = "astc-4x4"@@ -4640,6 +4726,7 @@ triangles: numberaudioBytes: number | undefinedaudioStreamedCount: number | undefinedaudioStreamedSavedBytes: number | undefined+compositeBatch: { entity: number; parts: number; instanced: number; draws: number; drawsBefore: number; moving: number; }[] | undefinedcosts: FrameCosts | nullcppCounters: Record<string, number>cppScopes: Record<string, number>@@ -14480,6 +14567,11 @@ MotionDriver<AnimatorBlend2DMotion>(p: { x: number; y: number; z: number; }, q: { x: number; y: number; z: number; w: number; }, s: { x: number; y: number; z: number; }): number[]```+## compositeBatchPlugin — const @experimental+```+Plugin+```+## compressedUploadDecision — function @experimental```(target: CompressedTextureFormat | null, transcoded: boolean): TextureUploadDecision@@ -16270,6 +16362,11 @@ ParticlePlugin(lines: Vec3[][], position: Vec3, rotation: Quat): Vec3[][]```+## planComposite — function @experimental+```+(parts: readonly CompositePart[], limits?: CompositeLimits, cellSize?: number): CompositePlan+```+## planStaticBatches — function @experimental```(candidates: readonly StaticBatchCandidate[], limits?: StaticBatchLimits): StaticBatchPlan@@ -16825,6 +16922,11 @@ PrefabsPlugin(seed: number): () => number```+## rootLocalMatrix — function @experimental+```+(chain: readonly TRS[]): Mat4+```+## rotateVec3ByQuat — function @experimental```(rot: Quat, v: Vec3): Vec3diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex b9c12864c..93afba55d 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: 115 public · 164 beta · 2044 experimental · 3 deprecated+Symbols: 115 public · 164 beta · 2058 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -1995,6 +1995,11 @@ sprite: number | undefined"hit"```+## COMPOSITE_DEFAULTS — const @experimental+```+CompositeLimits+```+## CacheCleanupPreview — interface @experimental```budgetBytes: number@@ -2836,6 +2841,87 @@ transient: boolean | undefined}```+## CompositeBatch — const @experimental+```+ComponentDef<CompositeBatchData>+```++## CompositeBatchData — interface @experimental+```+cellSize: number+draws: number+drawsBefore: number+instanceMin: number+instanced: number+moving: number+parts: number+```++## CompositeBatchPlugin — class @experimental+```+build: (app: App) => void+cleanup: (app?: App) => void+name: string+static new (): CompositeBatchPlugin+static prototype: CompositeBatchPlugin+```++## CompositeBatching — class @experimental+```+@internal busy_: boolean+@internal composites_: Map<number, CompositeState>+@internal forced_: Set<number>+counts: { scans: number; applies: number; merges: number; placementWrites: number; }+refresh: (root?: Entity) => void+report: (root: Entity) => { sets: number; chunks: number; alone: number; moving: number; refused: number; parts: number; } | null+static new (): CompositeBatching+static prototype: CompositeBatching+```++## CompositeBatchingRes — const @experimental+```+ResourceDef<CompositeBatching>+```++## CompositeChunk — interface @experimental+```+entities: number[]+id: string+key: string+```++## CompositeInstanceSet — interface @experimental+```+entities: number[]+key: string+mesh: number+```++## CompositeLimits — interface @experimental+```+cellSize: number+instanceMin: number+maxVertices: number+```++## CompositePart — interface @experimental+```+center: readonly [number, number, number]+entity: number+key: string+local: Mat4+mesh: number+vertices: number+```++## CompositePlan — interface @experimental+```+alone: number[]+cellSize: number+chunks: CompositeChunk[]+sets: CompositeInstanceSet[]+```+## CompressedTextureFormat — enum @experimental```ASTC_4x4 = "astc-4x4"@@ -4640,6 +4726,7 @@ triangles: numberaudioBytes: number | undefinedaudioStreamedCount: number | undefinedaudioStreamedSavedBytes: number | undefined+compositeBatch: { entity: number; parts: number; instanced: number; draws: number; drawsBefore: number; moving: number; }[] | undefinedcosts: FrameCosts | nullcppCounters: Record<string, number>cppScopes: Record<string, number>@@ -14211,6 +14298,11 @@ MotionDriver<AnimatorBlend2DMotion>(p: { x: number; y: number; z: number; }, q: { x: number; y: number; z: number; w: number; }, s: { x: number; y: number; z: number; }): number[]```+## compositeBatchPlugin — const @experimental+```+Plugin+```+## compressedUploadDecision — function @experimental```(target: CompressedTextureFormat | null, transcoded: boolean): TextureUploadDecision@@ -15996,6 +16088,11 @@ ParticlePlugin(lines: Vec3[][], position: Vec3, rotation: Quat): Vec3[][]```+## planComposite — function @experimental+```+(parts: readonly CompositePart[], limits?: CompositeLimits, cellSize?: number): CompositePlan+```+## planStaticBatches — function @experimental```(candidates: readonly StaticBatchCandidate[], limits?: StaticBatchLimits): StaticBatchPlan@@ -16551,6 +16648,11 @@ PrefabsPlugin(seed: number): () => number```+## rootLocalMatrix — function @experimental+```+(chain: readonly TRS[]): Mat4+```+## rotateVec3ByQuat — function @experimental```(rot: Quat, v: Vec3): Vec3diff --git a/sdk/src/app/pluginSets.ts b/sdk/src/app/pluginSets.tsindex f7ef5c2b8..e03a8f5b0 100644--- a/sdk/src/app/pluginSets.ts+++ b/sdk/src/app/pluginSets.ts@@ -29,6 +29,7 @@ import { trailPlugin } from '../trail';import { springBonePlugin } from '../springbone';import { meshRendererPlugin } from '../render/meshRenderer';import { staticBatchPlugin } from '../render/staticBatchPlugin';+import { compositeBatchPlugin } from '../render/compositeBatchPlugin';import { impostorPlugin } from '../render/impostor';import { textureStreamingPlugin } from '../render/textureStreaming';import { postProcessPlugin } from '../postprocess';@@ -59,7 +60,7 @@ export const simulationBasePlugins = (): Plugin[] => [/** What exists to be seen. Every entry drives the engine through `engineApi`. */export const presentationBasePlugins = (): Plugin[] => [- animationPlugin, videoPlugin, particlePlugin, trailPlugin, springBonePlugin, meshRendererPlugin, staticBatchPlugin, impostorPlugin, textureStreamingPlugin,+ animationPlugin, videoPlugin, particlePlugin, trailPlugin, springBonePlugin, meshRendererPlugin, staticBatchPlugin, compositeBatchPlugin, impostorPlugin, textureStreamingPlugin,postProcessPlugin,];@@ -70,7 +71,7 @@ export const presentationBasePlugins = (): Plugin[] => [*/export const PLUGIN_BUILD_ORDER: readonly string[] = ['Diagnostics', 'timer', 'velocity', 'lifecycle', 'animation', 'audio', 'video',- 'particle', 'trail', 'springBone', 'meshRenderer', 'staticBatch', 'impostor', 'textureStreaming', 'terrain', 'foliage', 'spline', 'water', 'floating', 'underwater', 'tilemap', 'postProcess', 'timeline',+ 'particle', 'trail', 'springBone', 'meshRenderer', 'staticBatch', 'compositeBatch', 'impostor', 'textureStreaming', 'terrain', 'foliage', 'spline', 'water', 'floating', 'underwater', 'tilemap', 'postProcess', 'timeline','gameplay','perception', 'fsm', 'bt', 'scriptGraph', 'nav', 'eventBinding', 'replication','services',@@ -96,7 +97,7 @@ export function inBuildOrder(plugins: readonly Plugin[]): Plugin[] {export const webBasePlugins = (): Plugin[] => [diagnosticsPlugin,timerPlugin, velocityPlugin, lifecyclePlugin, animationPlugin, audioPlugin, videoPlugin,- particlePlugin, trailPlugin, springBonePlugin, meshRendererPlugin, staticBatchPlugin, impostorPlugin, textureStreamingPlugin, postProcessPlugin,+ particlePlugin, trailPlugin, springBonePlugin, meshRendererPlugin, staticBatchPlugin, compositeBatchPlugin, impostorPlugin, textureStreamingPlugin, postProcessPlugin,eventBindingPlugin,servicesPlugin,];diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.tsindex acaae864d..169ac8ba3 100644--- a/sdk/src/core-content.ts+++ b/sdk/src/core-content.ts@@ -797,6 +797,14 @@ export {StaticBatch, StaticBatching, StaticBatchingRes, StaticBatchPlugin, staticBatchPlugin,StaticBatchState, type StaticBatchData, type StaticBatchSummary,} from './render/staticBatchPlugin';+export {+ CompositeBatch, CompositeBatching, CompositeBatchingRes, CompositeBatchPlugin, compositeBatchPlugin,+ type CompositeBatchData,+} from './render/compositeBatchPlugin';+export {+ planComposite, rootLocalMatrix, COMPOSITE_DEFAULTS,+ type CompositeLimits, type CompositePart, type CompositePlan, type CompositeChunk, type CompositeInstanceSet,+} from './render/compositeBatch';// Terrain and Foliage are optional modules (`esengine/terrain`, `esengine/foliage` install them). Their API stays reachable from// here: a shared chunk is side-effect-free, so what nothing uses is not bundled.export {diff --git a/sdk/src/render/compositeBatch.ts b/sdk/src/render/compositeBatch.tsnew file mode 100644index 000000000..1453bd616--- /dev/null+++ b/sdk/src/render/compositeBatch.ts@@ -0,0 +1,166 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file compositeBatch.ts+ * @brief A model built from many parts, drawn in a few draws, that still moves as a whole.+ *+ * @details A static batch bakes each part's WORLD transform into its vertices, so a merged+ * mesh is nailed to where the parts stood: a ship, a train or a moving platform+ * assembled from planks, rails and props cannot use it. A composite batch bakes+ * each part relative to the composite's ROOT instead, and draws the result from an+ * entity parented to that root. Moving the root moves every draw with no work per+ * part; the parts themselves are never touched again.+ *+ * Two ways to fold a part, chosen per mesh:+ * - a mesh repeated `instanceMin` times or more (deck planks, rail posts) stays one+ * resident mesh and is drawn as the placements of one `MeshInstances` set, which+ * holds a copy of nothing;+ * - every other part is merged, by draw state, into chunks: cells of the root's own+ * space, so adding or removing a part re-merges the one chunk it is in.+ *+ * This module is the arithmetic and the plan; compositeBatchPlugin.ts is the world.+ */+import { planStaticBatches, worldMatrix, type StaticBatchCandidate } from './staticBatch';++/** A 4x4 column-major matrix, as {@link worldMatrix} makes one (doubles, so a deep chain does not drift). */+export type Mat4 = Float64Array;++export interface TRS {+ position: { x: number; y: number; z: number };+ rotation: { x: number; y: number; z: number; w: number };+ scale: { x: number; y: number; z: number };+}++/** `a * b`, column-major. */+export function multiply(a: Mat4, b: Mat4): Mat4 {+ const out = new Float64Array(16);+ for (let c = 0; c < 4; c++) {+ for (let r = 0; r < 4; r++) {+ out[c * 4 + r] = a[r]! * b[c * 4]! + a[4 + r]! * b[c * 4 + 1]! + a[8 + r]! * b[c * 4 + 2]! + a[12 + r]! * b[c * 4 + 3]!;+ }+ }+ return out;+}++/**+ * Where a part stands in its root's space: the product of the LOCAL transforms on the way down+ * from the root to it, root excluded. Read from local transforms rather than from world ones, so+ * the answer does not depend on whether the root has moved this frame and its world matrices+ * have been brought up to date yet.+ */+export function rootLocalMatrix(chain: readonly TRS[]): Mat4 {+ let m = worldMatrix({ x: 0, y: 0, z: 0 }, { x: 0, y: 0, z: 0, w: 1 }, { x: 1, y: 1, z: 1 });+ for (const t of chain) m = multiply(m, worldMatrix(t.position, t.rotation, t.scale));+ return m;+}++/** Whether two placements are the same within a rounding a float transform picks up from a read-back. */+export function sameMatrix(a: Mat4, b: Mat4, eps = 1e-5): boolean {+ for (let i = 0; i < 16; i++) if (Math.abs(a[i]! - b[i]!) > eps * Math.max(1, Math.abs(a[i]!))) return false;+ return true;+}++/** Floats a placement takes in the engine's `MeshInstances`: three rows of the model matrix (translation in .w), then a tint. */+export const COMPOSITE_PLACEMENT_FLOATS = 16;++/** The placements of a `MeshInstances` set, one per matrix, untinted. */+export function placementsOf(matrices: readonly Mat4[]): Float32Array {+ const out = new Float32Array(matrices.length * COMPOSITE_PLACEMENT_FLOATS);+ matrices.forEach((m, n) => {+ const at = n * COMPOSITE_PLACEMENT_FLOATS;+ for (let row = 0; row < 3; row++) {+ out[at + row * 4] = m[row]!;+ out[at + row * 4 + 1] = m[4 + row]!;+ out[at + row * 4 + 2] = m[8 + row]!;+ out[at + row * 4 + 3] = m[12 + row]!;+ }+ out[at + 12] = out[at + 13] = out[at + 14] = out[at + 15] = 1;+ });+ return out;+}++/** One part, as the planner sees it: its draw state, its mesh and where it stands in the root's space. */+export interface CompositePart {+ entity: number;+ /** Draw state plus vertex layout (`staticBatchKey`): parts that may share a draw. */+ key: string;+ /** The mesh handle: parts that may share an instanced set share this AND the key. */+ mesh: number;+ local: Mat4;+ vertices: number;+ /** Centre of its mesh's bounds in the root's space: the cell it is merged in. */+ center: readonly [number, number, number];+}++export interface CompositeLimits {+ /** Parts of one mesh at or past which they are drawn as one instanced set instead of merged. */+ instanceMin: number;+ /** Side of a merge chunk in the root's space; 0 = chosen from the composite's size. */+ cellSize: number;+ /** Vertices a merged chunk may hold before it is split. */+ maxVertices: number;+}++export const COMPOSITE_DEFAULTS: CompositeLimits = { instanceMin: 4, cellSize: 0, maxVertices: 262144 };++/** Parts of one mesh and draw state, drawn as the placements of one set. */+export interface CompositeInstanceSet {+ key: string;+ mesh: number;+ entities: number[];+}++/** Parts merged into one mesh. `id` is stable while the chunk's members are the same, which is what lets an edit re-merge only its chunk. */+export interface CompositeChunk {+ id: string;+ key: string;+ entities: number[];+}++export interface CompositePlan {+ sets: CompositeInstanceSet[];+ chunks: CompositeChunk[];+ /** Parts nothing would draw with: they keep drawing themselves. */+ alone: number[];+ cellSize: number;+}++/**+ * The side of a chunk when the author left it to the planner: a quarter of the composite's+ * longest side, so a ship is a handful of chunks and an edit re-merges a fraction of it.+ */+export function autoCellSize(parts: readonly CompositePart[]): number {+ if (parts.length === 0) return 1;+ const min = [Infinity, Infinity, Infinity], max = [-Infinity, -Infinity, -Infinity];+ for (const p of parts) for (let k = 0; k < 3; k++) { min[k] = Math.min(min[k]!, p.center[k]!); max[k] = Math.max(max[k]!, p.center[k]!); }+ const longest = Math.max(max[0]! - min[0]!, max[1]! - min[1]!, max[2]! - min[2]!);+ return longest > 0 ? longest / 4 : 1;+}++/** Decide which parts are instanced, which are merged and in which chunk, and which draw alone. */+export function planComposite(parts: readonly CompositePart[], limits: CompositeLimits = COMPOSITE_DEFAULTS, cellSize?: number): CompositePlan {+ const byMesh = new Map<string, CompositePart[]>();+ for (const p of parts) {+ const id = `${p.key}|${p.mesh}`;+ const list = byMesh.get(id);+ if (list) list.push(p); else byMesh.set(id, [p]);+ }+ const sets: CompositeInstanceSet[] = [];+ const merge: CompositePart[] = [];+ const instanceMin = Math.max(2, limits.instanceMin);+ for (const list of byMesh.values()) {+ if (list.length >= instanceMin) {+ sets.push({ key: list[0]!.key, mesh: list[0]!.mesh, entities: list.map((p) => p.entity) });+ } else {+ merge.push(...list);+ }+ }+ const size = cellSize ?? (limits.cellSize > 0 ? limits.cellSize : autoCellSize(merge));+ const candidates: StaticBatchCandidate[] = merge.map((p) => ({ entity: p.entity, key: p.key, center: p.center, vertices: p.vertices }));+ const planned = planStaticBatches(candidates, { cellSize: size, maxVertices: limits.maxVertices });+ const chunks = planned.batches.map((b) => {+ const entities = [...b.entities].sort((x, y) => x - y);+ return { id: `${b.key}#${entities.join(',')}`, key: b.key, entities };+ });+ return { sets, chunks, alone: [...planned.alone], cellSize: size };+}diff --git a/sdk/src/render/compositeBatchPlugin.ts b/sdk/src/render/compositeBatchPlugin.tsnew file mode 100644index 000000000..1c8e6ad7f--- /dev/null+++ b/sdk/src/render/compositeBatchPlugin.ts@@ -0,0 +1,524 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file compositeBatchPlugin.ts+ * @brief Draws the parts under a `CompositeBatch` root in a few draws that follow the root wherever it goes.+ *+ * @details The parts stay as authored: scripts find them, colliders collide, the editor picks them; only their+ * MeshRenderer is switched off, and entities parented to the root draw them instead (see compositeBatch.ts+ * for how a part is folded). Because those entities are the root's children, moving, turning or scaling the+ * root moves the whole model at the cost of one transform.+ *+ * The pass looks again twice a second. A part added under the root, removed, switched to another mesh or+ * placed somewhere else in it re-plans the composite, and only the chunks whose members changed are merged+ * again; an instanced set is rewritten, which copies placements, not vertices. A part that keeps moving+ * inside the root (a door, a wheel) is let go after a few looks and draws itself, so it never costs a+ * merge per frame.+ */+import type { App, Plugin } from '../app/app';+import { defineSystem, Schedule } from '../ecs/system';+import { defineResource } from '../ecs/resource';+import {+ Children, defineComponent, getComponent, MeshRenderer, Parent, RuntimeOnly, Transform,+ type AnyComponentDef, type ChildrenData, type ComponentDef, type MeshRendererData, type ParentData, type TransformData,+} from '../ecs/component';+import { BodyType } from '../wasm/wasm.generated';+import { playModeOnly } from '../ecs/env';+import { Assets } from '../asset/AssetPlugin';+import type { MeshData } from '../asset/meshFormat';+import { engineApi } from '../ecs/bridge/engineApi';+import { withScratch } from '../wasm/wasmScratch';+import type { CppRegistry } from '../wasm';+import { log } from '../util/logger';+import type { Entity } from '../types';+import { channelSignature, layoutRefusal, mergeMeshes, staticBatchKey, type StaticBatchRefusal } from './staticBatch';+import {+ COMPOSITE_DEFAULTS, COMPOSITE_PLACEMENT_FLOATS, placementsOf, planComposite, rootLocalMatrix, sameMatrix,+ type CompositeLimits, type CompositePart, type Mat4, type TRS,+} from './compositeBatch';++/** The fields of the `CompositeBatch` component. @experimental */+export interface CompositeBatchData {+ /** Parts of one mesh at or past which they are drawn as one instanced set instead of merged. */+ instanceMin: number;+ /** Side of a merge chunk in the root's own space; 0 lets the pass choose from the model's size. */+ cellSize: number;+ /** Meshes under the root the pass draws (instanced or merged). Written by the pass. */+ parts: number;+ /** Of those, the parts drawn as instanced sets. */+ instanced: number;+ /** Draws the model takes now: sets, merged chunks and the parts that still draw themselves. */+ draws: number;+ /** Draws the same parts took before: one per distinct mesh and draw state. */+ drawsBefore: number;+ /** Parts that kept moving inside the root and were let go to draw themselves. */+ moving: number;+}++/**+ * Marks the root of a model assembled from many parts that moves as a whole (a ship, a vehicle, a moving platform),+ * so its parts may be drawn in a few draws that follow it. Presence is the opt-in; the parts need nothing.+ *+ * @experimental+ */+export const CompositeBatch: ComponentDef<CompositeBatchData> = defineComponent<CompositeBatchData>('CompositeBatch', {+ instanceMin: COMPOSITE_DEFAULTS.instanceMin,+ cellSize: COMPOSITE_DEFAULTS.cellSize,+ parts: 0,+ instanced: 0,+ draws: 0,+ drawsBefore: 0,+ moving: 0,+}, {+ readonlyFields: ['parts', 'instanced', 'draws', 'drawsBefore', 'moving'],+ fields: {+ instanceMin: { min: 2, label: 'Instance at', tooltip: 'Parts of one mesh at or past this count are drawn as one instanced set (no copy of their vertices). Fewer are merged.' },+ cellSize: { min: 0, label: 'Chunk size', tooltip: 'Side of a merge chunk in the root\'s space. Smaller chunks re-merge less on an edit and cull better; 0 chooses from the model\'s size.' },+ parts: { label: 'Batched parts' },+ instanced: { label: 'Instanced parts' },+ draws: { label: 'Draws' },+ drawsBefore: { label: 'Draws before' },+ moving: { label: 'Moving parts' },+ },+});++/** Looks a part may change in a row before it is taken for one that moves inside the model. */+const MOVING_AFTER = 3;+/** Frames between looks at a composite (half a second at 60 fps). A look reads every part through the engine, which is the pass's whole cost on a still model; `refresh(root)` looks at once. */+const SCAN_FRAMES = 30;++interface PartState {+ entity: Entity;+ key: string;+ mesh: number;+ local: Mat4;+ vertices: number;+ center: [number, number, number];+ mr: MeshRendererData;+ /** Looks in a row in which its place in the root changed. */+ changed: number;+}++/** The optional components a refusal looks for, by name: none of them is a subsystem a composite should carry. */+interface RefusalDefs {+ lod?: AnyComponentDef; billboard?: AnyComponentDef; skin?: AnyComponentDef; instances?: AnyComponentDef;+ body?: AnyComponentDef; character?: AnyComponentDef;+}++/** Whether two renderers draw the same way: the state a part's key is made from. */+function sameDrawState(a: MeshRendererData, b: MeshRendererData): boolean {+ return a.material === b.material && a.texture === b.texture && a.normalMap === b.normalMap && a.layer === b.layer+ && a.cullBackfaces === b.cullBackfaces && a.lit === b.lit+ && a.color.r === b.color.r && a.color.g === b.color.g && a.color.b === b.color.b && a.color.a === b.color.a+ && a.parallax.x === b.parallax.x && a.parallax.y === b.parallax.y;+}++interface DrawnChunk { holder: Entity; handle: number; entities: Entity[] }+interface DrawnSet { holder: Entity; entities: Entity[]; placements: Float32Array }++interface CompositeState {+ root: Entity;+ cellSize: number | null;+ parts: Map<Entity, PartState>;+ chunks: Map<string, DrawnChunk>;+ sets: Map<string, DrawnSet>;+ /** Parts whose MeshRenderer this pass switched off, and so must switch back on. */+ owned: Set<Entity>;+ moving: Set<Entity>;+ refused: Map<Entity, StaticBatchRefusal>;+ holders: Set<Entity>;+ nextScan: number;+}++/** Run-time access to the composites: what each one draws, and how to look again now. */+export class CompositeBatching {+ /** @internal */ readonly composites_ = new Map<Entity, CompositeState>();+ /** @internal */ readonly forced_ = new Set<Entity>();+ /** @internal */ busy_ = false;+ /** Work done so far, for a profiler or a check: re-plans, chunk merges, placement writes, scans. */+ readonly counts = { scans: 0, applies: 0, merges: 0, placementWrites: 0 };++ /** Look at `root` (or every composite) on the next frame instead of waiting for the next scheduled look. */+ refresh(root?: Entity): void {+ if (root === undefined) for (const r of this.composites_.keys()) this.forced_.add(r);+ else this.forced_.add(root);+ }++ /** What a composite draws now, or null when it is not one the pass has seen. */+ report(root: Entity): { sets: number; chunks: number; alone: number; moving: number; refused: number; parts: number } | null {+ const c = this.composites_.get(root);+ if (!c) return null;+ const drawn = new Set([...c.chunks.values()].flatMap((x) => x.entities).concat([...c.sets.values()].flatMap((x) => x.entities)));+ return {+ sets: c.sets.size, chunks: c.chunks.size,+ alone: [...c.parts.keys()].filter((e) => !drawn.has(e)).length,+ moving: c.moving.size, refused: c.refused.size, parts: drawn.size,+ };+ }+}++/** The resource the plugin installs. @experimental */+export const CompositeBatchingRes = defineResource<CompositeBatching>(new CompositeBatching(), 'CompositeBatching');++/** Whether `entity` sits under a `CompositeBatch` root (itself excluded): such a part is the composite's, not a static batch's. */+export function underComposite(world: App['world'], entity: Entity): boolean {+ let at = entity;+ for (let depth = 0; depth < 256 && world.has(at, Parent); depth++) {+ at = (world.get(at, Parent) as ParentData).entity;+ if (!world.valid(at)) return false;+ if (world.has(at, CompositeBatch)) return true;+ }+ return false;+}++export class CompositeBatchPlugin implements Plugin {+ name = 'compositeBatch';+ private readonly meshes_ = new Map<number, Promise<MeshData | null>>();++ build(app: App): void {+ const state = new CompositeBatching();+ app.insertResource(CompositeBatchingRes, state);+ let frame = 0;+ app.addSystemToSchedule(Schedule.Update, defineSystem([], () => {+ frame++;+ if (state.busy_ || !app.hasResource(Assets)) return;+ const world = app.world;+ // A root that went away takes its draws with it and gives its parts their own back.+ for (const [root, c] of state.composites_) {+ if (!world.valid(root) || !world.has(root, CompositeBatch)) { this.discard(app, c); state.composites_.delete(root); }+ }+ const due: Entity[] = [];+ for (const root of world.getEntitiesWithComponents([CompositeBatch])) {+ let c = state.composites_.get(root);+ if (!c) {+ c = {+ root, cellSize: null, parts: new Map(), chunks: new Map(), sets: new Map(), owned: new Set(),+ moving: new Set(), refused: new Map(), holders: new Set(), nextScan: frame,+ };+ state.composites_.set(root, c);+ }+ if (state.forced_.has(root) || frame >= c.nextScan) due.push(root);+ }+ if (due.length === 0) return;+ state.busy_ = true;+ void (async () => {+ for (const root of due) {+ const c = state.composites_.get(root);+ if (!c) continue;+ state.forced_.delete(root);+ c.nextScan = frame + SCAN_FRAMES;+ await this.scan(app, c);+ }+ })()+ .catch((e) => log.error('compositeBatch', 'a composite batch pass failed', e))+ .finally(() => { state.busy_ = false; });+ }, { name: 'CompositeBatchSystem' }), { runIf: playModeOnly });+ }++ cleanup(app?: App): void {+ if (!app?.hasResource(CompositeBatchingRes)) return;+ const state = app.getResource(CompositeBatchingRes);+ for (const c of state.composites_.values()) this.discard(app, c);+ state.composites_.clear();+ }++ private meshData(app: App, handle: number): Promise<MeshData | null> {+ let p = this.meshes_.get(handle);+ if (!p) {+ p = app.getResource(Assets).readMeshData(handle).catch(() => null);+ this.meshes_.set(handle, p);+ }+ return p;+ }++ /** The root's subtree (root included), not entering a nested composite or the pass's own draws. */+ private subtree(app: App, c: CompositeState): Entity[] {+ const world = app.world;+ const out: Entity[] = [];+ const stack: Entity[] = [c.root];+ while (stack.length > 0) {+ const e = stack.pop()!;+ if (c.holders.has(e) || !world.valid(e)) continue;+ if (e !== c.root && world.has(e, CompositeBatch)) continue;+ out.push(e);+ if (world.has(e, Children)) for (const child of (world.get(e, Children) as ChildrenData).entities) stack.push(child as Entity);+ }+ return out;+ }++ /** The local transforms from just under the root down to `entity`. */+ private chain(app: App, root: Entity, entity: Entity): TRS[] {+ const world = app.world;+ const out: TRS[] = [];+ let at = entity;+ for (let depth = 0; depth < 256 && at !== root; depth++) {+ const t = world.get(at, Transform) as TransformData;+ out.push({ position: t.position, rotation: t.rotation, scale: t.scale });+ if (!world.has(at, Parent)) break;+ at = (world.get(at, Parent) as ParentData).entity;+ }+ return out.reverse();+ }++ /** Why a part cannot be folded, or null. The same rules a static batch keeps, read the same way. */+ private refusal(app: App, e: Entity, mr: MeshRendererData, defs: RefusalDefs): StaticBatchRefusal | null {+ const world = app.world;+ const has = (def: AnyComponentDef | undefined): boolean => !!def && world.has(e, def);+ if (!mr.opaque) return 'blended';+ if (has(defs.lod)) return 'lod';+ if (has(defs.billboard) && (world.get(e, defs.billboard!) as { enabled: boolean }).enabled) return 'billboard';+ if (has(defs.skin)) return 'skinned';+ if (has(defs.instances)) return 'layout';+ // A body the solver moves goes its own way; a kinematic or static one rides with the root.+ if (has(defs.character) || (has(defs.body) && (world.get(e, defs.body!) as { bodyType: number }).bodyType === BodyType.Dynamic)) return 'moves';+ return null;+ }++ private async scan(app: App, c: CompositeState): Promise<void> {+ const world = app.world;+ const counts = app.getResource(CompositeBatchingRes).counts;+ counts.scans++;+ if (!world.valid(c.root)) return;+ const settings = world.get(c.root, CompositeBatch) as CompositeBatchData;+ const limits: CompositeLimits = { ...COMPOSITE_DEFAULTS, instanceMin: settings.instanceMin, cellSize: settings.cellSize };++ const defs: RefusalDefs = {+ lod: getComponent('LODGroup'), billboard: getComponent('Billboard'), skin: getComponent('MeshSkin'),+ instances: getComponent('MeshInstances'), body: getComponent('RigidBody3D'), character: getComponent('CharacterController3D'),+ };+ const seen = new Set<Entity>();+ const changed = new Set<Entity>();+ let structural = false;+ for (const e of this.subtree(app, c)) {+ if (!world.has(e, MeshRenderer) || !world.has(e, Transform)) continue;+ const mr = world.get(e, MeshRenderer) as MeshRendererData;+ const ours = c.owned.has(e);+ // Switched off by the author (not by this pass) or not loaded yet: nothing to draw.+ if ((!mr.enabled && !ours) || mr.mesh === 0) continue;+ if (c.moving.has(e)) { seen.add(e); continue; }+ const why = this.refusal(app, e, mr, defs);+ if (why) {+ if (!c.refused.has(e)) { c.refused.set(e, why); structural = true; }+ continue;+ }+ c.refused.delete(e);+ // Read once per mesh; every later look takes it from what was read, without a turn of the event loop.+ let mesh = this.resolved_.get(mr.mesh);+ if (mesh === undefined) {+ mesh = await this.meshData(app, mr.mesh);+ this.resolved_.set(mr.mesh, mesh);+ }+ if (!world.valid(e) || !world.valid(c.root)) continue;+ if (!mesh) { c.refused.set(e, 'no-mesh'); continue; }+ const layout = layoutRefusal(mesh);+ if (layout) { c.refused.set(e, layout); continue; }++ const local = rootLocalMatrix(this.chain(app, c.root, e));+ const known = c.parts.get(e);+ const key = known && known.mesh === mr.mesh && sameDrawState(known.mr, mr) ? known.key : staticBatchKey({+ material: mr.material, texture: mr.texture, normalMap: mr.normalMap, color: mr.color, layer: mr.layer,+ cullBackfaces: mr.cullBackfaces, lit: mr.lit, parallax: mr.parallax, group: '',+ }, channelSignature(mesh.channels, mesh.vertexStride));+ const cx = (mesh.aabbMin[0] + mesh.aabbMax[0]) / 2, cy = (mesh.aabbMin[1] + mesh.aabbMax[1]) / 2, cz = (mesh.aabbMin[2] + mesh.aabbMax[2]) / 2;+ const center: [number, number, number] = [+ local[0]! * cx + local[4]! * cy + local[8]! * cz + local[12]!,+ local[1]! * cx + local[5]! * cy + local[9]! * cz + local[13]!,+ local[2]! * cx + local[6]! * cy + local[10]! * cz + local[14]!,+ ];+ seen.add(e);+ const before = known;+ if (!before) {+ c.parts.set(e, { entity: e, key, mesh: mr.mesh, local, vertices: mesh.vertexCount, center, mr: { ...mr, enabled: true }, changed: 0 });+ structural = true;+ continue;+ }+ if (before.key !== key || before.mesh !== mr.mesh) {+ Object.assign(before, { key, mesh: mr.mesh, local, vertices: mesh.vertexCount, center, mr: { ...mr, enabled: true }, changed: 0 });+ changed.add(e);+ continue;+ }+ if (!sameMatrix(before.local, local)) {+ before.changed++;+ before.local = local;+ before.center = center;+ if (before.changed >= MOVING_AFTER) {+ // It moves inside the model: let it draw itself rather than re-merge its chunk every look.+ c.moving.add(e);+ c.parts.delete(e);+ structural = true;+ } else {+ changed.add(e);+ }+ } else {+ before.changed = 0;+ }+ }+ for (const e of [...c.parts.keys()]) if (!seen.has(e)) { c.parts.delete(e); structural = true; }+ for (const e of [...c.moving]) if (!seen.has(e)) c.moving.delete(e);+ for (const e of [...c.refused.keys()]) if (!world.valid(e)) c.refused.delete(e);+ if (!structural && changed.size === 0) return;+ counts.applies++;+ this.apply(app, c, limits, changed);+ }++ /** Re-plan the composite and bring its draws in line, re-merging only the chunks whose members changed. */+ private apply(app: App, c: CompositeState, limits: CompositeLimits, changed: ReadonlySet<Entity>): void {+ const world = app.world;+ const assets = app.getResource(Assets);+ const parts: CompositePart[] = [...c.parts.values()].map((p) => ({+ entity: p.entity, key: p.key, mesh: p.mesh, local: p.local, vertices: p.vertices, center: p.center,+ }));+ if (c.cellSize === null) c.cellSize = limits.cellSize > 0 ? limits.cellSize : null;+ const plan = planComposite(parts, limits, c.cellSize ?? undefined);+ if (c.cellSize === null) c.cellSize = plan.cellSize;++ const drawn = new Set<Entity>();++ // Instanced sets: a placement list, rewritten whenever its members or their places change.+ const liveSets = new Set<string>();+ for (const set of plan.sets) {+ const id = `${set.key}|${set.mesh}`;+ liveSets.add(id);+ const members = set.entities as Entity[];+ for (const e of members) drawn.add(e);+ const placements = placementsOf(members.map((e) => c.parts.get(e)!.local));+ const existing = c.sets.get(id);+ if (existing && sameFloats(existing.placements, placements)) continue;+ const holder = existing?.holder ?? this.holder(app, c, `CompositeBatch set ${c.sets.size + 1}`, { ...c.parts.get(members[0]!)!.mr, mesh: set.mesh });+ if (!existing) {+ const def = getComponent('MeshInstances');+ if (def) world.insert(holder, def, {});+ }+ if (!this.writePlacements(app, holder, placements)) {+ // No placement path on this core: the parts keep drawing themselves.+ for (const e of members) drawn.delete(e);+ if (!existing) { world.despawn(holder); c.holders.delete(holder); }+ liveSets.delete(id);+ continue;+ }+ c.sets.set(id, { holder, entities: members, placements });+ }+ for (const [id, set] of c.sets) {+ if (liveSets.has(id)) continue;+ if (world.valid(set.holder)) world.despawn(set.holder);+ c.holders.delete(set.holder);+ c.sets.delete(id);+ }++ // Merged chunks: kept whole while their members and places are the same, merged again otherwise.+ const liveChunks = new Set<string>();+ for (const chunk of plan.chunks) {+ const members = chunk.entities as Entity[];+ const dirty = members.some((e) => changed.has(e));+ const existing = c.chunks.get(chunk.id);+ if (existing && !dirty) {+ liveChunks.add(chunk.id);+ for (const e of members) drawn.add(e);+ continue;+ }+ app.getResource(CompositeBatchingRes).counts.merges++;+ const merged = mergeMeshes(members.map((e) => ({ mesh: this.cached(c.parts.get(e)!.mesh)!, world: c.parts.get(e)!.local })));+ const handle = assets.createMesh(merged);+ if (handle === 0) {+ log.warn('compositeBatch', `the engine refused a merged chunk of ${members.length} parts (${merged.vertexCount} vertices)`);+ continue;+ }+ if (existing) {+ world.insert(existing.holder, MeshRenderer, { ...(world.get(existing.holder, MeshRenderer) as MeshRendererData), mesh: handle });+ assets.releaseBuiltMesh(existing.handle);+ existing.handle = handle;+ } else {+ const holder = this.holder(app, c, `CompositeBatch chunk ${c.chunks.size + 1}`, { ...c.parts.get(members[0]!)!.mr, mesh: handle });+ c.chunks.set(chunk.id, { holder, handle, entities: members });+ }+ liveChunks.add(chunk.id);+ for (const e of members) drawn.add(e);+ }+ for (const [id, chunk] of c.chunks) {+ if (liveChunks.has(id)) continue;+ if (world.valid(chunk.holder)) world.despawn(chunk.holder);+ assets.releaseBuiltMesh(chunk.handle);+ c.holders.delete(chunk.holder);+ c.chunks.delete(id);+ }++ // Parts drawn by the composite go dark; every other part the pass had switched off draws itself again.+ for (const e of drawn) {+ if (c.owned.has(e) || !world.valid(e)) continue;+ world.insert(e, MeshRenderer, { ...(world.get(e, MeshRenderer) as MeshRendererData), enabled: false });+ c.owned.add(e);+ }+ for (const e of [...c.owned]) {+ if (drawn.has(e)) continue;+ this.restore(app, e);+ c.owned.delete(e);+ }+ this.stamp(app, c, plan.sets.reduce((n, s) => n + s.entities.length, 0), drawn.size);+ }++ /** Mesh data the scan has already read, so a merge never waits. */+ private cached(handle: number): MeshData | null {+ return this.resolved_.get(handle) ?? null;+ }+ private readonly resolved_ = new Map<number, MeshData | null>();++ private holder(app: App, c: CompositeState, name: string, mr: MeshRendererData): Entity {+ const world = app.world;+ const holder = world.spawn(name);+ world.insert(holder, RuntimeOnly);+ world.insert(holder, Transform, {});+ world.insert(holder, MeshRenderer, { ...mr, enabled: true });+ world.setParent(holder, c.root);+ c.holders.add(holder);+ return holder;+ }++ private writePlacements(app: App, holder: Entity, placements: Float32Array): boolean {+ const api = engineApi(app);+ const set = api?.meshInstances_set;+ if (!set || !api._malloc || !api._free || !api.HEAPU8) return false;+ const registry = app.world.getCppRegistry() as CppRegistry;+ app.getResource(CompositeBatchingRes).counts.placementWrites++;+ withScratch({ _malloc: api._malloc, _free: api._free }, (alloc) => {+ const ptr = alloc(Math.max(4, placements.byteLength));+ new Float32Array(api.HEAPU8!.buffer, ptr, placements.length).set(placements);+ set(registry, holder, ptr, placements.length / COMPOSITE_PLACEMENT_FLOATS);+ });+ return true;+ }++ private restore(app: App, e: Entity): void {+ const world = app.world;+ const mr = world.valid(e) ? world.tryGet(e, MeshRenderer) as MeshRendererData | null : null;+ if (mr) world.insert(e, MeshRenderer, { ...mr, enabled: true });+ }++ private stamp(app: App, c: CompositeState, instanced: number, drawnCount: number): void {+ const world = app.world;+ if (!world.valid(c.root) || !world.has(c.root, CompositeBatch)) return;+ const all = [...c.parts.values()];+ const drawsBefore = new Set(all.map((p) => `${p.key}|${p.mesh}`)).size + c.moving.size;+ const draws = c.sets.size + c.chunks.size + (all.length - drawnCount) + c.moving.size;+ world.insert(c.root, CompositeBatch, {+ ...(world.get(c.root, CompositeBatch) as CompositeBatchData),+ parts: drawnCount, instanced, draws, drawsBefore, moving: c.moving.size,+ });+ }++ private discard(app: App, c: CompositeState): void {+ const world = app.world;+ const assets = app.hasResource(Assets) ? app.getResource(Assets) : null;+ for (const set of c.sets.values()) if (world.valid(set.holder)) world.despawn(set.holder);+ for (const chunk of c.chunks.values()) { if (world.valid(chunk.holder)) world.despawn(chunk.holder); assets?.releaseBuiltMesh(chunk.handle); }+ for (const e of c.owned) this.restore(app, e);+ c.sets.clear(); c.chunks.clear(); c.owned.clear(); c.holders.clear(); c.parts.clear();+ }+}++function sameFloats(a: Float32Array, b: Float32Array): boolean {+ if (a.length !== b.length) return false;+ for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;+ return true;+}++export const compositeBatchPlugin: Plugin = new CompositeBatchPlugin();diff --git a/sdk/src/render/staticBatchPlugin.ts b/sdk/src/render/staticBatchPlugin.tsindex 93d7239f4..bea753085 100644--- a/sdk/src/render/staticBatchPlugin.ts+++ b/sdk/src/render/staticBatchPlugin.ts@@ -34,6 +34,7 @@ import {type BatchPart, type StaticBatchCandidate, type StaticBatchGroup, type StaticBatchLimits, type StaticBatchRefusal,type StaticBatchReport,} from './staticBatch';+import { underComposite } from './compositeBatchPlugin';/** Where a marked mesh stands after the last pass: not decided yet, merged, or left out and why. @experimental */export const StaticBatchState = {@@ -241,7 +242,9 @@ export class StaticBatchPlugin implements Plugin {/** Marked entities with a mesh, not yet merged or refused. */private undecided(app: App, state: StaticBatching): Entity[] {const world = app.world;- return world.getEntitiesWithComponents([StaticBatch, MeshRenderer, Transform]).filter((e) => !state.seen_.has(e));+ // A part under a CompositeBatch root moves with that root: baking it where it stands would leave it behind.+ return world.getEntitiesWithComponents([StaticBatch, MeshRenderer, Transform])+ .filter((e) => !state.seen_.has(e) && !underComposite(world, e));}private refuse(app: App, state: StaticBatching, entity: Entity, why: StaticBatchRefusal): void {diff --git a/sdk/src/runtime/frameStats.ts b/sdk/src/runtime/frameStats.tsindex 7d9f1504a..4b3fdb6ce 100644--- a/sdk/src/runtime/frameStats.ts+++ b/sdk/src/runtime/frameStats.ts@@ -11,6 +11,7 @@ import { Quality } from '../render/qualityRuntime';import { Audio } from '../audio/Audio';import { Assets } from '../asset/AssetPlugin';import { StaticBatchingRes, type StaticBatchSummary } from '../render/staticBatchPlugin';+import { CompositeBatch, type CompositeBatchData } from '../render/compositeBatchPlugin';import { TextureStreamingRes } from '../render/textureStreaming';import type { QualityReport } from '../render/quality';@@ -39,6 +40,8 @@ export interface FrameStatsReport {audioStreamedSavedBytes?: number;/** What static batching merged and left out; absent until a mesh has been marked. */staticBatch?: StaticBatchSummary;+ /** Per CompositeBatch root, what it draws now; absent while no root is in the scene. */+ compositeBatch?: { entity: number; parts: number; instanced: number; draws: number; drawsBefore: number; moving: number }[];quality?: QualityReport;/** What texture streaming holds: how many textures, the megabytes they take and would at full size, and how many moves it has made. */textureStreaming?: { enabled: boolean; textures: number; streamedMB: number; fullMB: number; moves: number; failures: number; startedSmall: number };@@ -76,6 +79,19 @@ export function frameStatsReport(app: App): FrameStatsReport {...(app.hasResource(StaticBatchingRes) ? (() => { const s = app.getResource(StaticBatchingRes).summary(); return s ? { staticBatch: s } : {}; })() : {}),quality: app.hasResource(Quality) ? app.getResource(Quality)?.report() : undefined,...textureStreamingStats(app),+ ...compositeBatchStats(app),+ };+}++/** What each CompositeBatch root says it draws, as the pass last wrote it on the root. */+function compositeBatchStats(app: App): Pick<FrameStatsReport, 'compositeBatch'> {+ const roots = app.world.getEntitiesWithComponents([CompositeBatch]);+ if (roots.length === 0) return {};+ return {+ compositeBatch: roots.map((entity) => {+ const c = app.world.get(entity, CompositeBatch) as CompositeBatchData;+ return { entity, parts: c.parts, instanced: c.instanced, draws: c.draws, drawsBefore: c.drawsBefore, moving: c.moving };+ }),};}diff --git a/sdk/tests/composite-batch.test.ts b/sdk/tests/composite-batch.test.tsnew file mode 100644index 000000000..173a576ab--- /dev/null+++ b/sdk/tests/composite-batch.test.ts@@ -0,0 +1,93 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * The composite batch's plan: a part is placed in its ROOT's space (so the draws follow the root),+ * a mesh repeated often enough is one instanced set, the rest are merged in chunks of the root's+ * space, and an edit changes only the chunk it lands in.+ */+import { describe, it, expect } from 'vitest';+import {+ COMPOSITE_DEFAULTS, multiply, placementsOf, planComposite, rootLocalMatrix, sameMatrix, type CompositePart,+} from '../src/render/compositeBatch';+import { worldMatrix } from '../src/render/staticBatch';++const Q0 = { x: 0, y: 0, z: 0, w: 1 };+const ONE = { x: 1, y: 1, z: 1 };+const at = (x: number, y = 0, z = 0) => ({ position: { x, y, z }, rotation: Q0, scale: ONE });+const quarterTurnY = { x: 0, y: Math.SQRT1_2, z: 0, w: Math.SQRT1_2 };++function part(entity: number, key: string, mesh: number, x: number, z = 0): CompositePart {+ const local = rootLocalMatrix([at(x, 0, z)]);+ return { entity, key, mesh, local, vertices: 24, center: [x, 0, z] };+}++describe('rootLocalMatrix', () => {+ it('composes the local transforms from under the root down to the part', () => {+ const m = rootLocalMatrix([{ position: { x: 10, y: 0, z: 0 }, rotation: quarterTurnY, scale: ONE }, at(0, 0, 5)]);+ // Five forward, turned a quarter about Y, lands five along +X from the parent at x = 10.+ expect(m[12]).toBeCloseTo(15);+ expect(m[13]).toBeCloseTo(0);+ expect(m[14]).toBeCloseTo(0);+ });++ it('does not depend on where the root is: the root is not in the chain', () => {+ const local = rootLocalMatrix([at(3, 1, 2)]);+ const rootA = worldMatrix({ x: 0, y: 0, z: 0 }, Q0, ONE);+ const rootB = worldMatrix({ x: 500, y: -20, z: 9 }, quarterTurnY, { x: 2, y: 2, z: 2 });+ // Drawn from an entity parented to the root, the part lands at root * local wherever the root is.+ const a = multiply(rootA, local), b = multiply(rootB, local);+ expect(a[12]).toBeCloseTo(3);+ expect(b[12]).toBeCloseTo(500 + 2 * 2);+ expect(b[14]).toBeCloseTo(9 - 2 * 3);+ expect(sameMatrix(local, rootLocalMatrix([at(3, 1, 2)]))).toBe(true);+ });+});++describe('planComposite', () => {+ const planks = Array.from({ length: 12 }, (_, i) => part(i + 1, 'wood', 7, i));+ const props = [part(100, 'wood', 21, 0.5), part(101, 'wood', 22, 1.5), part(102, 'wood', 23, 2.5)];++ it('draws a repeated mesh as one instanced set, and merges the parts that are each different', () => {+ const plan = planComposite([...planks, ...props], { ...COMPOSITE_DEFAULTS, cellSize: 100 });+ expect(plan.sets).toEqual([{ key: 'wood', mesh: 7, entities: planks.map((p) => p.entity) }]);+ expect(plan.chunks).toHaveLength(1);+ expect(plan.chunks[0]!.entities).toEqual([100, 101, 102]);+ expect(plan.alone).toEqual([]);+ });++ it('leaves a part that nothing shares a draw with to draw itself', () => {+ const plan = planComposite([...props, part(200, 'metal', 30, 1)], { ...COMPOSITE_DEFAULTS, cellSize: 100 });+ expect(plan.alone).toEqual([200]);+ });++ it('merges a mesh that repeats fewer times than instanceMin, and instances it past', () => {+ const three = planks.slice(0, 3);+ expect(planComposite(three, { ...COMPOSITE_DEFAULTS, instanceMin: 4, cellSize: 100 }).sets).toEqual([]);+ expect(planComposite(three, { ...COMPOSITE_DEFAULTS, instanceMin: 3, cellSize: 100 }).sets).toHaveLength(1);+ });++ it('re-merges only the chunk a new part lands in', () => {+ // Two chunks of props, one per cell of side 10 along X.+ const left = [part(300, 'wood', 40, 1), part(301, 'wood', 41, 2)];+ const right = [part(310, 'wood', 42, 21), part(311, 'wood', 43, 22)];+ const before = planComposite([...left, ...right], COMPOSITE_DEFAULTS, 10);+ const after = planComposite([...left, ...right, part(312, 'wood', 44, 23)], COMPOSITE_DEFAULTS, 10);+ const ids = (p: typeof before) => p.chunks.map((c) => c.id);+ const kept = ids(after).filter((id) => ids(before).includes(id));+ expect(kept).toEqual([before.chunks.find((c) => c.entities.includes(300))!.id]);+ expect(after.chunks.find((c) => c.entities.includes(312))!.entities).toEqual([310, 311, 312]);+ });++ it('chooses a chunk size from the model when none is given, and says what it chose', () => {+ const plan = planComposite([part(1, 'k', 1, 0), part(2, 'k', 2, 40)]);+ expect(plan.cellSize).toBeCloseTo(10);+ });+});++describe('placementsOf', () => {+ it('writes the three rows of each matrix with translation last, then an untinted colour', () => {+ const m = rootLocalMatrix([{ position: { x: 4, y: 5, z: 6 }, rotation: Q0, scale: { x: 2, y: 3, z: 1 } }]);+ const out = placementsOf([m]);+ expect(Array.from(out)).toEqual([2, 0, 0, 4, 0, 3, 0, 5, 0, 0, 1, 6, 1, 1, 1, 1]);+ });+});diff --git a/tools/check-corpus-authoring.mjs b/tools/check-corpus-authoring.mjsindex a33773539..0a2e76137 100644--- a/tools/check-corpus-authoring.mjs+++ b/tools/check-corpus-authoring.mjs@@ -157,6 +157,7 @@ const DISPOSITION = {CoverFadeTarget: ['owed', 'the tag that goes with CoverFade, and owed with it'],RainUpright: ['owed', 'no committed example places one yet; it arrives with the top-down rain example RainShelter is owed'],RainShelter: ['owed', 'no committed example places one yet; it arrives with the top-down rain example CoverFade is owed'],+ CompositeBatch: ['owed', 'no corpus scene has a model that moves as a whole yet: its parts are folded while the game runs, which a golden project has no frame to certify — tests/composite-batch.test.ts and the composite-batch editor check (same frame as the plain ship, a moved root re-merges nothing, an added part re-merges one chunk) hold it'],StaticBatch: ['owed', 'no corpus scene marks a mesh yet: a marked mesh is merged while the game runs, which a golden project has no frame to certify — the static-batch-on / static-batch-off render scenes, tests/static-batch.test.ts and the static-batch editor check hold it'],};diff --git a/tools/check-gizmo-coverage.mjs b/tools/check-gizmo-coverage.mjsindex 412c12cb4..c706bdd9e 100644--- a/tools/check-gizmo-coverage.mjs+++ b/tools/check-gizmo-coverage.mjs@@ -122,6 +122,7 @@ const DISPOSITION = {'Planet.cellSize': ['no-place', 'the finest cell of the ground\'s mesh near the eye, not a region of the entity'],'PlacedFoliage.sizeX': ['renders', 'the area the plants are placed over is the outline'],'PlacedFoliage.sizeZ': ['renders', 'the area the plants are placed over is the outline'],+ 'CompositeBatch.cellSize': ['no-place', 'the side of the chunks a model\'s merged parts are cut into in its root\'s space, which decides what an edit re-merges; not a region of the entity'],'PlacedFoliage.cellSize': ['no-place', 'the side of the cells the area is cut into, not a region of the entity'],'Terrain.sizeX': ['renders', 'the ground drawn at it is the outline'],'Terrain.sizeZ': ['renders', 'the ground drawn at it is the outline'],diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex 6c4823363..fec404399 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -3810,4 +3810,8 @@ export const NOTED = {{"note":"The new-project gallery is in Chinese in a Chinese editor."},"fix(sdk): side modules load on a native host with no WebAssembly global, and a video's audio-track probe is not a missing asset":{"internal":"corrects two regressions the v0.98.0 release boot found before any release shipped them"},+ "feat(render): CompositeBatch draws a model of many parts in a few draws that follow its root, instancing repeated meshes and re-merging only the chunk an edit touches":+ {"note":"A model of many parts that moves: `CompositeBatch`."},+ "feat(mcp): get_stats reports what each CompositeBatch root draws, and the composite-batch check holds the batch":+ {"note":"A model of many parts that moves: `CompositeBatch`."},};